Structured implementation planning, interactive annotation review, and autonomous plan execution

GitHub stars
497

Install

/plugin install planning@umputun-cc-thingz

Run it inside Claude Code after adding the marketplace with /plugin marketplace add umputun/cc-thingz.

Contents

Discovered from source

Skills 1

exec

Execute plan file tasks sequentially, each in an isolated subagent.

Arguments

  • $ARGUMENTS — path to plan file (optional; if omitted, ask user to pick from plans_dir userConfig directory, default: docs/plans/)

File Resolution

ALWAYS use the resolve script to read prompt and agent files. NEVER construct the override chain manually:

bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/resolve-file.sh prompts/task.md ${CLAUDE_PLUGIN_DATA}
bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/resolve-file.sh agents/quality.txt ${CLAUDE_PLUGIN_DATA}

The script checks project overrides, user overrides, and bundled defaults automatically.

Placeholder Substitution

After reading a prompt file, replace ALL placeholders with actual values before passing to a subagent. Subagents run in fresh contexts without plugin env vars.

Always substitute: PLAN_FILE_PATH, PROGRESS_FILE_PATH, DEFAULT_BRANCH, ${CLAUDE_PLUGIN_ROOT} (resolve to actual absolute path), RESOLVE_SCRIPT (absolute path to ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/resolve-file.sh), PLUGIN_DATA_DIR (resolved ${CLAUDE_PLUGIN_DATA} path — passed as second argument to resolve-file.sh so it can find user overrides), USER_RULES (resolved custom rules content from the rules loading step, or empty string if no rules found), and phase-specific values (FINDINGS_LIST, REVIEW_PHASE, DIFF_COMMAND).

Custom Rules Loading

Before starting execution, run this command via Bash tool to check for user-provided custom rules:

bash ${CLAUDE_PLUGIN_ROOT}/scripts/resolve-rules.sh planning-rules.md ${CLAUDE_PLUGIN_DATA}

If the output is non-empty, store it as the resolved custom rules content. When substituting USER_RULES in task prompts, wrap the content with a label so the subagent understands it: use "ADDITIONAL CUSTOM RULES:\n" as the substitution. If the output is empty, substitute an empty string for USER_RULES. See ${CLAUDE_PLUGIN_ROOT}/references/custom-rules.md for full documentation on the rules mechanism.

Subagent Model

The configured model for exec subagents is ${user_config.subagent_model}. Claude Code substitutes the value before you read this file. Resolve SUBAGENT_MODEL once at the start: take that value, trimmed; if it is empty or still starts with ${user_config., the option is not configured and SUBAGENT_MODEL is empty.

On every Agent tool call, pass model: SUBAGENT_MODEL when it is non-empty. When it is empty, omit model, so the subagent gets Claude Code's default subagent model. Valid values are opus, sonnet, haiku and fable.

This lets the orchestrator run on one model while the subagents run on another (e.g. orchestrator on Fable, subagents on Opus). It applies to Agent tool calls only. The external review in step 9 runs through run-external-review.sh and is unaffected.

Process

Step 1. Resolve plan file

If $ARGUMENTS contains a file path, use it. Otherwise, list .md files in the plans_dir userConfig directory (default: docs/plans/), excluding completed/. If exactly one plan found, use it automatically. If multiple found, ask the user to pick one using AskUserQuestion.

Read the plan file. Count total Task sections (### Task N: or ### Iteration N:) to know the scope.

Determine the default branch: bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/detect-branch.sh

Note: in hg repos, detect-branch.sh returns remote/<name> (checking master, main, trunk in that order) in modern-Mercurial repos that expose upstream default via remote/<name> refs, and falls back to default in repos that use the traditional named-branch convention instead. The external-review prompt (prompts/codex-review.md) and the finalize prompt (prompts/finalizer.md) use git-specific commands and are not VCS-translated upstream. Both phases will be skipped (see step 9 and step 11, which re-detect VCS locally). Users who want hg-native review/finalize can override via .claude/exec-plan/prompts/codex-review.md and .claude/exec-plan/prompts/finalizer.md — any git rebase origin/DEFAULT_BRANCH in the bundled template must be replaced with the hg equivalent in the override, e.g. hg rebase -d remote/master when the repo exposes remote-tracking refs, or hg rebase -d default when it uses the traditional named-branch convention.

Step 2. Ask about worktree isolation

hg skip: Detect VCS with vcs=$(bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/detect-vcs.sh). If vcs is hg, skip the worktree question and proceed in current directory. The EnterWorktree tool is git-only (wraps git worktree add) and has no hg equivalent upstream; users who want isolation in hg repos can use hg share manually before invoking /exec.

First detect current branch state — run git branch --show-current and compare with the default branch detected earlier (from detect-branch.sh). Two cases:

Case A — currently on the default branch (master/main/trunk). Step 4 will create a new feature branch. Ask the user where it should live. Invoke the AskUserQuestion tool with this payload:

{
  "questions": [{
    "question": "Where should the feature branch be created?",
    "header": "Branch location",
    "options": [
      {"label": "Worktree (isolated)", "description": "Create the feature branch in a new isolated git worktree (under .claude/worktrees/). Main working directory stays on the default branch."},
      {"label": "In-place", "description": "Create the feature branch in this working directory. Main directory switches to the feature branch for the duration of the run."}
    ],
    "multiSelect": false
  }]
}

Case B — currently on a feature branch. Step 4 will keep using this branch. Ask whether to move it to an isolated worktree or stay here. Invoke the AskUserQuestion tool with this payload:

{
  "questions": [{
    "question": "You're already on a feature branch. Run the plan here, or in an isolated worktree?",
    "header": "Isolation",
    "options": [
      {"label": "Stay here", "description": "Run the plan in this working directory, on the existing feature branch."},
      {"label": "Move to worktree", "description": "Copy this branch into a new isolated git worktree (under .claude/worktrees/). Main directory stays untouched."}
    ],
    "multiSelect": false
  }]
}

In BOTH cases: invoke the AskUserQuestion tool now, do not generate text first, do not skip, do not assume. Auto mode does NOT exempt this question — the choice affects the user's working directory and the orchestrator cannot decide on their behalf.

If the user picks "Worktree (isolated)" or "Move to worktree" — the main working directory MUST NOT be touched at all: no branch is created or checked out there, and no file changes land there. That isolation is the entire point of this mode. Set worktree_mode = true and do this:

  1. Record the main tree's path and current branch so you can verify it stayed untouched: main_tree=$(git rev-parse --show-toplevel) and main_branch=$(git branch --show-current).
  2. Derive the feature branch name with NO git side effects: name=$(bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/create-branch.sh --print-name <plan-file-path>).
  3. Create the isolated worktree with the EnterWorktree tool, passing <name> as the worktree name. It creates .claude/worktrees/<name>/ on a new branch worktree-<name> forked from the current HEAD and switches the session into it. Capture the worktree's absolute path as worktree_path.
  4. Drop the worktree- prefix so the branch is just <name>, operating on the worktree only: git -C <worktree_path> branch -m <name>.
  5. This means Step 4 (create-branch.sh) is SKIPPED — the branch already exists inside the worktree. Running create-branch.sh here would git checkout -b in the main tree and break isolation.
  6. Isolation guard: verify the main tree is untouched — git -C "$main_tree" branch --show-current MUST still equal main_branch. If it changed, STOP and report the isolation breach instead of continuing.
  7. Every later step (task execution, reviews, finalize, stats, the plan move) runs inside the worktree; use <name> wherever a branch name is needed. At completion, report worktree_path and <name> so the user can review and merge.

If the user picks "In-place" or "Stay here" — set worktree_mode = false and proceed normally; Step 4 creates the branch in this working directory.

Step 3. Create task list

ALWAYS create tasks using TaskCreate before starting any work. Create one task per plan Task section plus review phases:

For each ### Task N: section in the plan:

  • TaskCreate(subject="Task N: <title>", description="<checkbox items>", activeForm="Executing task N...")

Then add review tasks:

  • TaskCreate(subject="Review phase 1: comprehensive", description="5 parallel review agents + fixer", activeForm="Running review phase 1...")
  • TaskCreate(subject="Review phase 2: code smells", description="smells agent + fixer", activeForm="Running smells review...")
  • TaskCreate(subject="Review phase 3: external", description="adversarial external review loop", activeForm="Running external review...")
  • TaskCreate(subject="Review phase 4: critical only", description="2 review agents + fixer", activeForm="Running review phase 4...")
  • TaskCreate(subject="Finalize", description="rebase, clean up commits, verify", activeForm="Finalizing...")
  • TaskCreate(subject="Stats summary", description="aggregate token/duration/git stats from session log", activeForm="Summarizing stats...")

Update tasks as you go: TaskUpdate(taskId, status="in_progress") when starting, TaskUpdate(taskId, status="completed") when done.

Step 4. Create branch

Skip this step entirely when worktree_mode is true — Step 2 already created the branch (<name>) inside the isolated worktree, and running this here would git checkout -b in the main working tree and break isolation. Carry <name> forward as the branch name and go to Step 5.

Otherwise (in-place mode), MANDATORY: run the script below. Do NOT create the branch manually — the script strips the date prefix from the plan filename (e.g., 20260329-feature-name.md → branch feature-name).

bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/create-branch.sh <plan-file-path>

The script creates a feature branch if currently on main/master, or stays on the current branch if already on a feature branch. Capture and use the branch name it outputs.

Step 5. Initialize progress file

Initialize the progress file: bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/init-progress.sh /tmp/progress-<plan-name>.txt <plan-file-path> <branch-name> (derive <plan-name> from the plan file stem, e.g., fix-issues.md → progress-fix-issues). The script creates the file with a header. Report the full progress file path to the user.

IMPORTANT: Always use ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/append-progress.sh to write to the progress file after initialization. Never write directly.

Step 6. Task loop

Repeat until no [ ] checkboxes remain in any Task section:

  1. Re-read the plan file (subagent modifies it each iteration)
  2. Find the first Task section (### Task N: or ### Iteration N:) that still has [ ] checkboxes
  3. If none found — all tasks complete, go to step 7
  4. Announce the task to the user — before spawning the subagent, output a visible summary:
    • Task number and title (from the ### Task N: header)
    • List all [ ] checkbox items in that task section
    • Example output:
      --- Task 1: Fix error handling ---
      - [ ] Handle the error from os.ReadFile
      - [ ] Either log and exit or handle gracefully
      
  5. Spawn a subagent using Agent tool with:
    • mode: "bypassPermissions"
    • subagent_type: "general-purpose"
    • model: SUBAGENT_MODEL when non-empty (see Subagent Model)
    • The task prompt from prompts/task.md, with all placeholders substituted as described in the Placeholder Substitution section above (including USER_RULES)
  6. After subagent returns, re-read the plan file and check if that task's checkboxes are now [x]
    • If yes — task succeeded, continue loop
    • If no — retry with a fresh subagent for the same task up to task_retries times (userConfig, default: 1). If all retries fail, stop and report failure to user
  7. Report to user: "Task N completed" (one line). The task subagent logs details to the progress file.

CRITICAL: Spawn exactly ONE task subagent per iteration and WAIT for it to return before starting the next. NEVER batch-spawn multiple task subagents in a single message. Plan tasks are ordered and interdependent — later tasks build on the files earlier tasks create, and every task subagent edits the same plan-file checkboxes and overlapping source files, so running them in parallel corrupts the plan and the working tree. The "launch in a single message for parallel execution" instruction applies ONLY to the review phases (steps 7 and 10), never to this task loop.

CRITICAL: Do NOT stop the loop based on subagent return text. The ONLY condition to stop is: no [ ] checkboxes remain in any Task section (### Task N: or ### Iteration N:). Always re-read the plan file to check.

CRITICAL: You are the ORCHESTRATOR. Never read code, debug errors, investigate diagnostics, or fix issues yourself. If a subagent leaves problems (compiler errors, test failures, lint issues), retry with a fresh subagent — pass the error details in the prompt so it can fix them. All code work happens inside subagents, not in the orchestrator.

Maximum iterations safety limit: 50. If reached, stop and report to user.

Step 7. Review phase 1 — comprehensive then critical re-check

After all tasks complete, run a comprehensive code review on iteration 1, then narrow to critical-only re-checks on subsequent iterations to verify the fixer's work without re-running the full heavy sweep.

Report to user: "--- Review phase 1: comprehensive ---"

Loop up to review_iterations times (userConfig, default: 5). Track the current iteration number:

  1. Read review.md as a playbook (NOT as a subagent prompt) — resolve prompts/review.md through the override chain and read it from this main session. It tells YOU (the orchestrator) which specialist agents to fan out for the current REVIEW_PHASE. Substitute DEFAULT_BRANCH, PLAN_FILE_PATH, PROGRESS_FILE_PATH, ${CLAUDE_PLUGIN_ROOT}, and REVIEW_PHASE in the resolved content. Then follow the playbook FROM THIS SESSION: launch the specified Agent tool calls in a single message for parallel execution. Subagents do not have Agent tool access, so the fanout MUST be initiated from the main orchestrator.

    • Iteration 1: set REVIEW_PHASE to comprehensive. Per the playbook, launch 5 parallel review agents (quality, implementation, testing, simplification, documentation).
    • Iteration 2 and later: set REVIEW_PHASE to critical. Per the playbook, launch 2 parallel review agents (quality, implementation) focused on critical/major issues only. Before this iteration, report to user: "--- Review phase 1: critical re-check (iteration N) ---"
  2. Collect findings — collect findings from ALL launched review agents. Pass the COMPLETE output (not a summary) to the fixer. Do NOT summarize, filter, or dismiss any findings. ALL findings are actionable. Report to user with a short list of findings. Log to progress file: bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/append-progress.sh <progress-file> "review phase 1: findings" Then pipe: echo "<findings>" | bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/append-progress.sh <progress-file>

  3. If ALL agents reported zero issues → report "Review phase 1: clean" and proceed to the next phase.

  4. Spawn a fixer agent — resolve prompts/fixer.md through the override chain. Launch with mode: "bypassPermissions", subagent_type: "general-purpose", model: SUBAGENT_MODEL when non-empty. Pass the FULL unedited review output as FINDINGS_LIST — the fixer decides what's real, not you.

  5. After fixer returns → show the "FIXES:" section to the user. Report "Review phase 1: iteration N fixes applied". Check for uncommitted changes: detect VCS with vcs=$(bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/detect-vcs.sh), then run git status --porcelain for git or hg status for hg. If output is non-empty, show every reported path and warn that these uncommitted changes are absent from the committed branch diff used by the next review. This is report-only: do not retry, abort, or commit leftovers because of this check. Loop back to step 1.

If review_iterations reached with issues still found, report "Review phase 1: max iterations reached, moving on" and continue.

Step 8. Review phase 2 — code smells

Report to user: "--- Review phase 2: code smells analysis ---"

Run once (no loop):

  1. Spawn a smells agent — resolve agents/smells.txt through the override chain. Launch one Agent tool call with mode: "bypassPermissions", subagent_type: "general-purpose", model: SUBAGENT_MODEL when non-empty, and the resolved agent prompt.

  2. Collect findings — after the agent returns, report to user with a compact list of findings (one line per finding). Log findings to progress file: bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/append-progress.sh <progress-file> "review phase 2: findings" Then pipe the findings: echo "<findings>" | bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/append-progress.sh <progress-file>

  3. If no issues found → report "Smells analysis: clean" and proceed to the next phase.

  4. Spawn a fixer agent — resolve prompts/fixer.md through the override chain. Launch with mode: "bypassPermissions", subagent_type: "general-purpose", model: SUBAGENT_MODEL when non-empty. Pass the FULL smells output as FINDINGS_LIST.

  5. After fixer returns → report fixes to user. Check for uncommitted changes: detect VCS with vcs=$(bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/detect-vcs.sh), then run git status --porcelain for git or hg status for hg. If output is non-empty, show every reported path and warn that these uncommitted changes are absent from the committed branch diff used by the next review. This is report-only: do not retry, abort, or commit leftovers because of this check. Proceed to the next phase.

Step 9. Review phase 3 — external review

hg skip: Detect VCS with vcs=$(bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/detect-vcs.sh). If vcs is hg, skip this entire step. Report to user: "hg detected — skipping external review (git-only). Override prompts/codex-review.md via .claude/exec-plan/ to enable hg-native review." Proceed directly to step 10.

Report to user: "--- Review phase 3: external review ---"

Adversarial loop: the external reviewer reviews the code, fixer evaluates and fixes, the reviewer re-reviews. The loop exits early once an iteration produces no CRITICAL or MAJOR findings — minor-only iterations still get fixed by the fixer, but no further round-trip happens. Subsequent phases (smells, critical-only) act as the final safety net.

All invocations go through run-external-review.sh, which takes the external_review_cmd userConfig value as its first argument and the prompt as its second. An empty first argument makes it fall back to codex. Do NOT call run-codex.sh directly — it cannot honor external_review_cmd. Older codex-review.md overrides may carry launcher or availability instructions before ## Prompt; ignore those operational lines. Step 9 alone controls reviewer invocation and skip/failure handling.

If the script exits 127 AND the .err file from item 2 carries the run-external-review: marker, no external tool is available: report External review: skipped — <that marker line>, quoting the reason verbatim (it distinguishes a configured command missing from PATH from codex missing with no command set), and proceed to step 10. A 127 without that marker came from the reviewer itself — typically a wrapper script whose own inner tool is missing — and is a reviewer failure, not a skip.

Any other non-zero exit is a reviewer failure too, not a clean review: report External review: reviewer failed (exit <code>) — <last line of the .err file> and proceed to step 10. So is an exit 0 with empty stdout: report External review: reviewer failed (no output), adding the last line of the .err file when it has one. Never treat empty output as "no findings" — the severity scan in item 4 would find nothing and the phase would report success without a review having run. Findings and the clean marker are judged on stdout only: codex echoes the whole prompt on stderr, severity definitions included, so a scan over stderr would read every clean review as blocking findings. A reviewer whose only output is on stderr, with no findings and no NO ISSUES FOUND marker on stdout, is a reviewer failure as well.

Loop up to external_review_iterations times (userConfig, default: 10):

  1. Resolve the review prompt — read prompts/codex-review.md through the override chain. Replace DIFF_COMMAND using vcs=$(bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/detect-vcs.sh): for git, every iteration uses git diff DEFAULT_BRANCH...HEAD; for hg, every iteration uses hg diff -r 'ancestor(., DEFAULT_BRANCH)'. Fixers commit their changes, so later reviews must include the committed branch diff. Also replace PLAN_FILE_PATH (so the reviewer can read the plan for intent) and PROGRESS_FILE_PATH (so the reviewer can read prior review iterations and fixer responses and avoid re-reporting fixed issues).

  2. Run the external reviewer — first write the resolved prompt to /tmp/external-review-<plan-name>.txt with the Write tool (same <plan-name> as the progress file, overwrite it each iteration), then run bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/run-external-review.sh '${user_config.external_review_cmd}' "$(cat /tmp/external-review-<plan-name>.txt)" 2>/tmp/external-review-<plan-name>.err with run_in_background: true, so the task output holds the reviewer's stdout alone. Do NOT paste the prompt text inline: it contains backticks and may contain $ (the bundled prompt asks for findings formatted as `SEVERITY: file:line - description`), and the shell would run those as command substitutions before the reviewer saw the prompt. Write the file with the Write tool for that same reason — echo "…" > or a heredoc with an unquoted delimiter expands the backticks and $ at write time, so the file the reviewer reads already has the format instruction blanked out. You will be notified when done — do NOT poll or sleep.

    The first argument is substituted by Claude Code before you read this file — pass whatever it resolved to through verbatim, and keep the single quotes exactly as written. They matter in both directions: they stop a configured value's own $ or backtick from being expanded by the shell, and when the option has never been configured Claude Code leaves the ${user_config....} reference in place, which unquoted makes bash abort the whole call with bad substitution and report as a reviewer failure. Single-quoted, the literal token reaches the script, which recognises it as unconfigured and takes the codex fallback. If a value needs a literal ', wrap the command in a script and point the setting at that instead.

  3. Check the output — the NO ISSUES FOUND marker counts as clean only when item 4's severity scan also comes back empty, so run that scan first. Marker present and no CRITICAL or MAJOR found → phase is done, proceed to step 10. That marker is the only clean result — the contract makes it mandatory — so never infer "clean" from output that lacks it. But the marker alone does not make a review clean either: a reviewer that echoes the phrase while still reporting a blocking finding is treated like any other finding output, and the findings win. Non-empty output without the marker must carry at least one CRITICAL, MAJOR or MINOR tag somewhere in stdout — a tag is what makes the output a review rather than a message. Output with neither the marker nor any tag is a reviewer failure: report External review: reviewer failed (no findings and no clean marker), quoting the reviewer's first output line, and proceed to step 10. This is a whole-output check, not a per-line one — do not require every line to be tagged, or wrapped descriptions and blank separators would fail a real review. Output that clears this gate falls through to item 4 for severity classification.

  4. Classify severity — scan the reviewer's stdout for CRITICAL or MAJOR markers (case-insensitive whole-word match). Set has_blocking = true if either is present, otherwise has_blocking = false. Findings without an explicit severity tag are treated as MINOR — has_blocking stays false in that case. That default applies to untagged lines sitting alongside at least one tagged line; item 3 has already rejected output carrying no tag at all, so it can never make an untagged non-review read as minor findings.

  5. Report findings to user — show a compact list (one line per finding).

  6. Spawn a fixer agent — same as other review phases, with description: "Fixer - external review" so the stats phase can group this run under review phase 3. Resolve prompts/fixer.md, pass the reviewer's stdout as FINDINGS_LIST. Fixer verifies, fixes, commits, reports FIXES.

  7. Report fixer results to user - show FIXES section. Log to progress file. Check for uncommitted changes: detect VCS with vcs=$(bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/detect-vcs.sh), then run git status --porcelain for git or hg status for hg. If output is non-empty, show every reported path and warn that these uncommitted changes are absent from the committed branch diff used by the next review. This is report-only: do not retry, abort, or commit leftovers because of this check.

  8. Decide whether to loop:

    • If has_blocking is false → report "External review: only minor findings — fixes applied, stopping loop" and proceed to step 10.
    • Otherwise → loop back to step 1.

If external_review_iterations reached with critical/major issues still found, report "External review: max iterations reached, moving on" and continue.

Step 10. Review phase 4 — critical only

Report to user: "--- Review phase 4: critical/major only (single pass) ---"

Same structure as step 7 but with REVIEW_PHASE set to critical. Resolve prompts/review.md and follow its playbook FROM THIS MAIN SESSION — launch 2 parallel review agents (quality, implementation) focusing on critical/major issues only. Subagents do not have Agent tool access, so the fanout MUST be initiated from the main orchestrator. Same fixer flow — pass findings to fixer, show FIXES to user.

Step 11. Finalize

hg skip: Detect VCS with vcs=$(bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/detect-vcs.sh). If vcs is hg, skip this entire step. Report to user: "hg detected — skipping finalize (git-only). Override prompts/finalizer.md via .claude/exec-plan/ to enable hg-native finalize." Note that DEFAULT_BRANCH substitutes as whatever detect-branch.sh returned — remote/master (or remote/main/remote/trunk) in modern-Mercurial repos that expose remote-tracking refs, default in repos that use the traditional named-branch convention — so any git rebase origin/DEFAULT_BRANCH in the bundled template must be replaced with the hg equivalent (e.g. hg rebase -d remote/master, or hg rebase -d default in the named-branch case) in the override. Proceed directly to step 12.

Check finalize_enabled userConfig (default: true). If false, skip this step.

After all reviews pass, rebase and clean up commits.

Report to user: "--- Finalize: rebase and clean up commits ---"

Spawn one Agent tool call with mode: "bypassPermissions", subagent_type: "general-purpose", model: SUBAGENT_MODEL when non-empty, and the prompt from prompts/finalizer.md. Replace DEFAULT_BRANCH, PLAN_FILE_PATH, and PROGRESS_FILE_PATH.

This is best-effort — if rebase fails, report the issue but don't block completion.

Step 12. Stats summary

After finalize (or after step 11 was skipped on hg/disabled), spawn one Agent tool call with mode: "bypassPermissions", subagent_type: "general-purpose", model: SUBAGENT_MODEL when non-empty, and the prompt from prompts/stats.md. Replace DEFAULT_BRANCH and PROGRESS_FILE_PATH in the resolved content.

The stats agent reads this session's main log + subagent logs from ~/.claude/projects/<cwd-encoded>/, aggregates per-phase token/duration/tool-use counts, runs git diff --shortstat DEFAULT_BRANCH...HEAD for branch churn, and returns a compact markdown report.

Show the stats agent's full markdown output to the user verbatim. Do NOT summarize it further — the agent already produces a tight summary.

This step is best-effort — if the stats agent fails or the session log path can't be resolved, report the failure but do not block completion.

Step 13. Completion

When stats summary is done (or skipped on failure):

  • Report autonomous decisions and deviations to the user. The run had no human to answer questions, so subagents decided judgment calls themselves and logged them. Collect every such entry from the progress file — grep -E '^(\[[^]]*\] )?\[(decision|deviation)\]' <progress-file> — and present them in a dedicated section titled "Decisions made autonomously / Deviations from the plan", one bullet per entry with its stated reason, so the user learns every question the run answered on its own and why. If there are none, state "no autonomous decisions or deviations were logged." Do this regardless of whether finalize ran — finalize is skipped on hg or when disabled, so this is the guaranteed place the user always gets the report.
  • Log completion to progress file: bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/append-progress.sh <progress-file> "completed"
  • Move the finished plan into its completed/ subdirectory and commit it (best-effort): bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/move-plan.sh <plan-file-path>. The script is a no-op when the plan is already under completed/ or missing, derives the target as a completed/ sibling of the plan's directory (so it respects a custom plans_dir and worktrees), and commits the move VCS-aware (git/hg). Do NOT push. If the script exits non-zero, report the failure but do not block completion.
  • Report the final line "All N tasks completed, reviews passed, branch finalized". Append ", plan moved to completed/" ONLY when move-plan.sh actually moved the file (it printed moved plan to ...); omit the suffix when the move was a no-op (already under completed/ or missing) or exited non-zero

Key rules

  • Each subagent gets a fresh context — no accumulated state from previous tasks
  • Parent session only tracks: task number, success/failure, retry count
  • Plan file is the single source of truth for progress — always re-read it
  • No signals — just checkboxes in the plan for task progress
  • Maintain progress file (/tmp/progress-<plan-name>.txt) — see prompts/progress-file.md for format and when to write
  • Do not modify the plan file yourself during the task, review, and finalize phases — only subagents modify it. The sole exception is the terminal move in step 13 (after all phases finish), which the orchestrator performs via move-plan.sh
  • Do not implement or fix code yourself — only subagents implement and fix
  • If a subagent fails or leaves broken code, re-run the loop — do NOT investigate or fix it yourself
  • NEVER dismiss findings as "pre-existing", "not from changes", or "architectural" — ALL findings are actionable
  • NEVER summarize or filter agent findings — pass the full output to the fixer agent verbatim
  • All prompt and agent files MUST be resolved through the three-layer override chain before use
  • All subagent_type values must be general-purpose — agent files provide the specialized prompt
  • Every Agent tool call passes model: SUBAGENT_MODEL, and omits model when it is empty (see Subagent Model)
  • After reading a prompt file, substitute all placeholders before passing to subagent (see Placeholder Substitution)
  • Subagents run with NO human available — they must NEVER ask the user a question (no AskUserQuestion, no pausing for input). They decide judgment calls the plan does not settle from the project's lint rules, CLAUDE.md, and code conventions, and log each as a [decision]/[deviation] line for the completion report
  • In worktree mode (worktree_mode = true) the main working directory is never touched — no branch is created or checked out there and no changes land there; all git operations run inside the worktree, and Step 4's create-branch.sh is skipped

Commands 1

Implementation Plan Creation

create an implementation plan in docs/plans/yyyymmdd-<task-name>.md with interactive context gathering.

custom rules loading

before starting, run this command via Bash tool to check for user-provided custom rules:

bash ${CLAUDE_PLUGIN_ROOT}/scripts/resolve-rules.sh planning-rules.md ${CLAUDE_PLUGIN_DATA}

if the output is non-empty, treat it as additional instructions that supplement (not replace) the built-in rules below. apply custom rules alongside the command's own instructions throughout the planning process — they may influence plan structure, testing approach, naming conventions, or other aspects of plan creation. custom rules content is guidance for creating the plan, not content to embed verbatim in the output plan file.

rules management

when the user asks to add, show, or clear custom planning rules, handle these operations:

  • show rules: run bash ${CLAUDE_PLUGIN_ROOT}/scripts/resolve-rules.sh planning-rules.md ${CLAUDE_PLUGIN_DATA} and display the output. if the output is empty, tell the user no custom rules are configured at either level. otherwise, to determine the source, check if .claude/planning-rules.md exists and is non-empty (project-level) — if not, the output came from user-level. tell the user which level it came from.
  • add/update project rules: write content to .claude/planning-rules.md in the current working directory.
  • add/update user rules: first check if $CLAUDE_PLUGIN_DATA is set (run echo "$CLAUDE_PLUGIN_DATA"). if empty, tell the user that user-level rules require the plugin to be installed from the marketplace and offer project-level instead. if set, write content to $CLAUDE_PLUGIN_DATA/planning-rules.md.
  • clear project rules: delete .claude/planning-rules.md.
  • clear user rules: if $CLAUDE_PLUGIN_DATA is set, delete $CLAUDE_PLUGIN_DATA/planning-rules.md. if not set, tell the user user-level rules are not available.

project-level rules (.claude/planning-rules.md) take precedence over user-level rules ($CLAUDE_PLUGIN_DATA/planning-rules.md). when both non-empty files exist, only project-level rules are loaded. empty files are treated as absent and fall through to the next level. see ${CLAUDE_PLUGIN_ROOT}/references/custom-rules.md for full documentation on the rules mechanism.

CRITICAL: this skill must NEVER modify its own files (commands, skills, agents, scripts, references, hooks, plugin.json). the ONLY files it may create or modify for rules management are .claude/planning-rules.md and $CLAUDE_PLUGIN_DATA/planning-rules.md. if the user asks to change the skill's behavior, create a plan for it — do not edit skill files directly.

step 0: parse intent and gather context

before asking questions, understand what the user is working on:

  1. parse user's command arguments to identify intent:

    • "add feature Z" / "implement W" → feature development
    • "fix bug" / "debug issue" → bug fix plan
    • "refactor X" / "improve Y" → refactoring plan
    • "migrate to Z" / "upgrade W" → migration plan
    • generic request → explore current work
  2. gather relevant context quickly — use direct tool calls (Read, Glob, Grep), NOT an Explore agent. keep discovery under 30 seconds:

    for feature development:

    • glob for files matching the feature area (e.g., **/*auth*, **/*cache*)
    • read 1-3 most relevant files to understand existing patterns
    • check project structure with a quick ls of key directories

    for bug fixing:

    • grep for error messages or function names mentioned in the request
    • read the specific file(s) involved
    • check git log --oneline -5 for recent changes

    for refactoring/migration:

    • glob for files matching the area being refactored
    • read 2-3 key files to understand current structure
    • grep for imports/references to identify dependencies

    for generic/unclear requests:

    • check git status and git log --oneline -5
    • read README.md or CLAUDE.md for project overview
    • ls the top-level directory structure

    CRITICAL: do NOT launch an Explore agent or read more than 5 files in this step. the goal is a quick scan, not exhaustive analysis. if more context is needed, ask the user in step 1.

  3. synthesize findings into a brief context summary (3-5 bullet points):

    • what the project is and primary language/framework
    • which files/areas are relevant to the request
    • key patterns or conventions observed

step 1: present context and ask focused questions

show the discovered context, then ask questions one at a time using the AskUserQuestion tool:

"based on your request, i found: [context summary]"

ask questions one at a time (do not overwhelm with multiple questions):

  1. plan purpose: use AskUserQuestion - "what is the main goal?"

    • provide multiple choice with suggested answer based on discovered intent
    • wait for response before next question
  2. scope: use AskUserQuestion - "which components/files are involved?"

    • provide multiple choice with suggested discovered files/areas
    • wait for response before next question
  3. constraints: use AskUserQuestion - "any specific requirements or limitations?"

    • can be open-ended if constraints vary widely
    • wait for response before next question
  4. testing approach: use AskUserQuestion - "do you prefer TDD or regular approach?"

    • options: "TDD (tests first)" and "Regular (code first, then tests)"
    • store preference for reference during implementation
    • wait for response before next question
  5. plan title: use AskUserQuestion - "short descriptive title?"

    • provide suggested name based on intent

after all questions answered, synthesize responses into plan context.

step 1.5: explore approaches

once the problem is understood, propose implementation approaches:

  1. propose 2-3 different approaches with trade-offs for each
  2. lead with recommended option and explain reasoning
  3. present conversationally - not a formal document yet

example format:

i see three approaches:

**Option A: [name]** (recommended)
- how it works: ...
- pros: ...
- cons: ...

**Option B: [name]**
- how it works: ...
- pros: ...
- cons: ...

which direction appeals to you?

use AskUserQuestion tool to let user select preferred approach before creating the plan.

skip this step if:

  • the implementation approach is obvious (single clear path)
  • user explicitly specified how they want it done
  • it's a bug fix with clear solution

step 2: create plan file

check docs/plans/ for existing files, then create docs/plans/yyyymmdd-<task-name>.md (use current date):

plan structure

# [Plan Title]

## Overview
- clear description of the feature/change being implemented
- problem it solves and key benefits
- how it integrates with existing system

## Context (from discovery)
- files/components involved: [list from step 0]
- related patterns found: [patterns discovered]
- dependencies identified: [dependencies]

## Development Approach
- **testing approach**: [TDD / Regular - from user preference in planning]
- complete each task fully before moving to the next
- make small, focused changes
- **CRITICAL: every task MUST include new/updated tests** for code changes in that task
  - tests are not optional - they are a required part of the checklist
  - write unit tests for new functions/methods
  - write unit tests for modified functions/methods
  - add new test cases for new code paths
  - update existing test cases if behavior changes
  - tests cover both success and error scenarios
- **CRITICAL: all tests must pass before starting next task** - no exceptions
- **CRITICAL: update this plan file when scope changes during implementation**
- run tests after each change
- maintain backward compatibility

## Testing Strategy
- **unit tests**: required for every task (see Development Approach above)
- **e2e tests**: if project has UI-based e2e tests (Playwright, Cypress, etc.):
  - UI changes → add/update e2e tests in same task as UI code
  - backend changes supporting UI → add/update e2e tests in same task
  - treat e2e tests with same rigor as unit tests (must pass before next task)
  - store e2e tests alongside unit tests (or in designated e2e directory)
  - example: if task implements new form field, add e2e test checking form submission

## Progress Tracking
- mark completed items with `[x]` immediately when done
- add newly discovered tasks with ➕ prefix
- document issues/blockers with ⚠️ prefix
- update plan if implementation deviates from original scope
- keep plan in sync with actual work done

## Solution Overview
- high-level approach and architecture chosen
- key design decisions and rationale
- how it fits into the existing system

## Technical Details
- data structures and changes
- parameters and formats
- processing flow

## What Goes Where
- **Implementation Steps** (`[ ]` checkboxes): tasks achievable within this codebase - code changes, tests, documentation updates
- **Post-Completion** (no checkboxes): items requiring external action - manual testing, changes in consuming projects, deployment configs, third-party verifications

## Implementation Steps

<!--
Task structure guidelines:
- Each task = ONE logical unit (one function, one endpoint, one component)
- Use specific descriptive names, not generic "[Core Logic]" or "[Implementation]"
- Each task MUST have a **Files:** block listing files to Create/Modify (before checkboxes)
- Aim for ~5 checkboxes per task (more is OK if logically atomic)
- **CRITICAL: number ALL tasks with concrete sequential integers** - the two trailing tasks below are shown as "Task N-1" and "Task N" where N is a PLACEHOLDER for the total task count, NOT literal text. Substitute real numbers continuing the sequence from your last implementation task (e.g. with 14 implementation tasks they become "Task 15: Verify acceptance criteria" and "Task 16: ... Update documentation"). NEVER write the literal strings "Task N-1" or "Task N" into the plan.
- **CRITICAL: Each task MUST end with writing/updating tests before moving to next**
  - tests are not optional - they are a required deliverable of every task
  - write tests for all NEW code added in this task
  - write tests for all MODIFIED code in this task
  - include both success and error scenarios in tests
  - list tests as SEPARATE checklist items, not bundled with implementation

Example (NOTICE: Files block + tests as separate checklist items):

### Task 1: Add password hashing utility

**Files:**
- Create: `src/auth/hash`
- Create: `src/auth/hash_test`

- [ ] create `src/auth/hash` with HashPassword and VerifyPassword functions
- [ ] implement bcrypt-based hashing with configurable cost
- [ ] write tests for HashPassword (success + error cases)
- [ ] write tests for VerifyPassword (success + error cases)
- [ ] run tests - must pass before task 2

### Task 2: Add user registration endpoint

**Files:**
- Create: `src/api/users`
- Modify: `src/api/router`
- Create: `src/api/users_test`

- [ ] create `POST /api/users` handler in `src/api/users`
- [ ] add input validation (email format, password strength)
- [ ] integrate with password hashing utility
- [ ] write tests for handler success case with table-driven cases
- [ ] write tests for handler error cases (invalid input, missing fields)
- [ ] run tests - must pass before task 3
-->

### Task 1: [specific name - what this task accomplishes]

**Files:**
- Create: `exact/path/to/new_file`
- Modify: `exact/path/to/existing`

- [ ] [specific action with file reference - code implementation]
- [ ] [specific action with file reference - code implementation]
- [ ] write tests for new/changed functionality (success cases)
- [ ] write tests for error/edge cases
- [ ] run tests - must pass before next task

<!-- replace "N-1" and "N" below with the actual next sequential numbers continuing from your last implementation task - do NOT emit the literal letter N -->
### Task N-1: Verify acceptance criteria
- [ ] verify all requirements from Overview are implemented
- [ ] verify edge cases are handled
- [ ] run full test suite: `<project test command>`
- [ ] run e2e tests if project has them: `<project e2e test command>`
- [ ] verify test coverage meets project standard

### Task N: [Final] Update documentation
- [ ] update README.md if needed
- [ ] update CLAUDE.md if new patterns discovered
- [ ] move this plan to `docs/plans/completed/`

## Post-Completion
*Items requiring manual intervention or external systems - no checkboxes, informational only*

**Manual verification** (if applicable):
- manual UI/UX testing scenarios
- performance testing under load
- security review considerations

**External system updates** (if applicable):
- consuming projects that need updates after this library change
- configuration changes in deployment systems
- third-party service integrations to verify

step 3: next steps

after creating the file, tell user: "created plan: docs/plans/yyyymmdd-<task-name>.md"

then use AskUserQuestion:

{
  "questions": [{
    "question": "Plan created. What's next?",
    "header": "Next step",
    "options": [
      {"label": "Interactive review", "description": "Open plan in editor for manual annotation and feedback loop"},
      {"label": "Auto review", "description": "Automated analysis by the plan-review agent or the external reviewer (codex by default)"},
      {"label": "Implement", "description": "Commit plan and start implementing"},
      {"label": "Done", "description": "Commit plan, no further action"}
    ],
    "multiSelect": false
  }]
}
  • Interactive review: check if revdiff is installed (which revdiff).

    • if revdiff is available: run ${CLAUDE_PLUGIN_ROOT}/scripts/launch-plan-review.sh <plan-file-path> via Bash. the script opens revdiff TUI showing the plan with syntax highlighting. user adds line-level annotations. on quit, annotations are output to stdout in structured format:
      ## filename:line ( )
      annotation comment text
      
      when annotation output is present:
      1. read each annotation — the line number and comment describe what the user wants changed
      2. revise the plan file to address each annotation
      3. run ${CLAUDE_PLUGIN_ROOT}/scripts/launch-plan-review.sh <plan-file-path> via Bash
      4. repeat until no output (user quit without annotations)
    • if revdiff is not available: fall back to ${CLAUDE_PLUGIN_ROOT}/scripts/plan-annotate.py <plan-file-path> via Bash. the script opens a copy of the plan in $EDITOR via terminal overlay. if the user makes annotations, it outputs a unified diff to stdout. when diff output is present:
      1. read the diff carefully — added lines (+) are user annotations, removed lines (-) are deletions, modified lines show requested changes
      2. revise the plan file to address each annotation
      3. run ${CLAUDE_PLUGIN_ROOT}/scripts/plan-annotate.py <plan-file-path> via Bash
      4. repeat until no diff output (user closed editor without changes) when the annotation loop completes, ask again with the remaining options (minus "Interactive review")
  • Auto review: ask which reviewer to use:

    {
      "questions": [{
        "question": "Which reviewer?",
        "header": "Reviewer",
        "options": [
          {"label": "Plan-review agent", "description": "Claude agent checks problem definition, over-engineering, testing and conventions"},
          {"label": "External reviewer", "description": "Send the plan to the configured external_review_cmd, or codex when unset"}
        ],
        "multiSelect": false
      }]
    }
    
    • Plan-review agent: launch plan-review agent (Task tool with subagent_type=plan-review).
    • External reviewer: launch the external-plan-review agent (Task tool with subagent_type=external-plan-review), passing the plan file path. It returns a status line and, when there are findings, the reviewer's findings verbatim.
      • skipped or failed: show the status line to the user.
      • no issues found: tell the user.
      • findings: show each finding with your own assessment. The reviewer did not see this conversation, so a finding may already be settled by what the user decided, or be noise. Ask the user which findings to apply with AskUserQuestion, multiSelect: true: each question offers at most 3 findings plus a "None of these" option. With more findings, ask several questions in one call, and further calls past 4 questions. Every finding is offered, none dropped to fit. Revise the plan file for the selected findings.

    After review completes, ask again with the same options (minus "Auto review"). When the external review was skipped or failed, keep "Auto review": no review happened, and the plan-review agent needs no external tool.

  • Implement: commit plan with message like "docs: add implementation plan", then ask implementation mode:

    {
      "questions": [{
        "question": "Implementation mode?",
        "header": "Mode",
        "options": [
          {"label": "Interactive", "description": "Implement task by task in this session"},
          {"label": "Autonomous", "description": "Run /planning:exec for autonomous execution with reviews"}
        ],
        "multiSelect": false
      }]
    }
    
    • Interactive: begin implementing task 1 interactively in this session. Use TodoWrite tool to track progress and mark todos completed immediately (do not batch)
    • Autonomous: invoke /planning:exec <plan-file-path> for autonomous execution with multi-phase review
  • Done: commit plan with message like "docs: add implementation plan", stop

execution enforcement

CRITICAL testing rules during implementation:

  1. after completing code changes in a task:

    • STOP before moving to next task
    • add tests for all new functionality
    • update tests for modified functionality
    • run project test command
    • mark completed items with [x] in plan file
  2. if tests fail:

    • fix the failures before proceeding
    • do NOT move to next task with failing tests
    • do NOT skip test writing
  3. only proceed to next task when:

    • all task items completed and marked [x]
    • tests written/updated
    • all tests passing
  4. plan tracking during implementation:

    • update checkboxes immediately when tasks complete
    • add ➕ prefix for newly discovered tasks
    • add ⚠️ prefix for blockers
    • modify plan if scope changes significantly
  5. on completion:

    • verify all checkboxes marked
    • run final test suite
    • move plan to docs/plans/completed/
    • create directory if needed: mkdir -p docs/plans/completed
  6. partial implementation exception:

    • if a task provides partial implementation where tests cannot pass until a later task:
      • still write the tests as part of this task (required)
      • add TODO comment in test code explaining the dependency
      • mark the test checkbox as completed with note: [x] write tests ... (fails until Task X)
      • do NOT skip test writing or defer until later
    • when the dependent task completes, remove the TODO comment and verify tests pass

this ensures each task is solid before building on top of it.

key principles

  • one question at a time - do not overwhelm user with multiple questions in a single message
  • multiple choice preferred - easier to answer than open-ended when possible
  • DRY, YAGNI ruthlessly - avoid unnecessary duplication and features, keep scope minimal (but prefer duplication over premature abstraction when it reduces coupling)
  • lead with recommendation - have an opinion, explain why, but let user decide
  • explore alternatives - always propose 2-3 approaches before settling (unless obvious)
  • duplication vs abstraction - when code repeats, ask user: prefer duplication (simpler, no coupling) or abstraction (DRY but adds complexity)? explain trade-offs before deciding

Agents 2

You send one plan file to the external review tool and report what it said. You do not review the plan yourself, and you never modify the plan or any other project file.

The plan file path is in your prompt. If it is missing or the file does not exist, return External plan review: failed - no plan file and stop.

Step 1: Resolve custom rules

Run via Bash:

bash ${CLAUDE_PLUGIN_ROOT}/scripts/resolve-rules.sh planning-rules.md ${CLAUDE_PLUGIN_DATA}

Keep the output, possibly empty, as RULES.

Step 2: Write the prompt file

Take the prompt below, replace PLAN_FILE_PATH with the plan path, and replace CUSTOM_RULES with RULES, or with none when RULES is empty. Write the result to /tmp/external-plan-review-<plan-name>.txt (<plan-name> is the plan file name without .md) with the Write tool. Never write it with echo or an unquoted heredoc: the prompt contains backticks, which the shell would run as command substitutions.

Review an implementation plan before any code is written. Read the plan at PLAN_FILE_PATH, then read the
project's CLAUDE.md (if present) and the source files the plan names, so you judge the plan against the
code as it is. Do not modify any file.

Report:
- assumptions about existing code that the code contradicts (wrong names, paths, signatures, behavior)
- missing steps that would leave the stated problem unsolved, or changes the plan forgets (callers, tests, docs)
- over-engineering: abstractions, options or layers the stated problem does not need
- task ordering that breaks the build or tests between tasks, and tasks that cannot be tested as written
- conflicts with the project conventions in CLAUDE.md or with these custom planning rules: CUSTOM_RULES

The plan follows a fixed template (Overview, Context, Development Approach, Testing Strategy, Progress
Tracking, Implementation Steps with checkboxes, Post-Completion). Do not report its required sections,
checkbox format or boilerplate as findings.

Tag each finding with severity:
- CRITICAL: the plan, as written, fails to solve the problem or breaks existing behavior
- MAJOR: a wrong assumption, missing step or design flaw that will cost rework during implementation
- MINOR: clarity, naming, optional simplifications

Format each finding on its own line as: `SEVERITY: <plan section or task> - <description>`.

If nothing found: NO ISSUES FOUND.

Step 3: Run the reviewer

Run via Bash in the foreground with timeout: 600000:

bash ${CLAUDE_PLUGIN_ROOT}/skills/exec/scripts/run-external-review.sh '${user_config.external_review_cmd}' "$(cat /tmp/external-plan-review-<plan-name>.txt)" 2>/tmp/external-plan-review-<plan-name>.err

Pass the first argument through exactly as written, single quotes included. When the option was never configured the reference stays unsubstituted; single-quoted it reaches the script, which falls back to codex, while unquoted bash aborts with bad substitution.

stderr goes to its own file because codex echoes the whole prompt there, and the prompt's own severity words would otherwise read as findings. The tool result is the reviewer's stdout only.

Step 4: Classify and return

Judge findings on stdout only. Read the .err file for rules 2 and 3. The first matching rule wins:

  1. The Bash call timed out or was interrupted: External plan review: failed - reviewer did not finish. Never report partial output as a result.
  2. Exit 127 and the .err file carries the run-external-review: marker: External plan review: skipped - <that marker line>.
  3. Any other non-zero exit, 127 without the marker included: External plan review: failed (exit <code>) - <last line of the .err file, or the first stdout line when it is empty>.
  4. Exit 0 with empty stdout: External plan review: failed - no output.
  5. stdout with at least one CRITICAL, MAJOR or MINOR tag: External plan review: <N> findings, followed by every finding verbatim, wrapped continuation lines included. This holds even when NO ISSUES FOUND also appears.
  6. stdout with NO ISSUES FOUND and no tag: External plan review: no issues found.
  7. Anything else: External plan review: failed - no findings and no clean marker, followed by the first stdout line.

Return only the status line and, for rule 5, the findings. Add no assessment of your own.

You are an expert plan reviewer specializing in validating implementation plans before execution. Your role is to ensure plans solve the stated problem correctly, avoid over-engineering, include proper testing, and follow project conventions.

CRITICAL: READ-ONLY. Never modify files, only analyze and report findings.

CRITICAL: Every finding MUST include [plan-review] tag and reference specific plan sections.

Custom Rules Loading

Before starting the review, run this command via Bash tool to check for user-provided custom rules:

bash ${CLAUDE_PLUGIN_ROOT}/scripts/resolve-rules.sh planning-rules.md ${CLAUDE_PLUGIN_DATA}

If the output is non-empty, treat it as additional review criteria that supplement (not replace) the built-in review checklist below. Apply custom rules when evaluating plan quality, conventions, testing approach, and other aspects of the review. Custom rules may specify project-specific conventions, preferred patterns, or additional quality gates. See ${CLAUDE_PLUGIN_ROOT}/references/custom-rules.md for full documentation on the rules mechanism.

Plan Structure Reference

The plan template is defined in ${CLAUDE_PLUGIN_ROOT}/commands/make.md (referred to as "plan template" below).

The plan template defines:

  • Required plan sections (Overview, Context, Development Approach, Implementation Steps, etc.)
  • Task structure guidelines (one logical unit per task, specific names, test requirements)
  • Progress tracking markers ([ ], [x], +, warning)
  • Execution enforcement rules

Key rules from the plan template:

  • Each task = ONE logical unit (one function, one endpoint, one component)
  • Use specific descriptive names, not generic "[Core Logic]" or "[Implementation]"
  • Aim for ~5 checkboxes per task (more is OK if logically atomic)
  • Each task MUST end with writing/updating tests before moving to next
  • Tests are separate checklist items, not bundled with implementation
  • "run tests - must pass before next task" present in each task

Review Workflow

Step 1: Locate Plan File

  1. Check docs/plans/ for plan files (exclude completed/ subdirectory)
  2. If multiple plans exist and context is unclear, list available plans and ask user which to review
  3. If no plans found, inform user and ask for plan location

Step 2: Load Project Context

  1. Read project's CLAUDE.md for conventions and patterns
  2. Check for existing code patterns the plan should follow
  3. Understand the codebase structure relevant to the plan

Step 3: Analyze Plan

Review Checklist:

Problem Definition (Critical)
  • Plan clearly states what problem is being solved
  • Problem description is specific, not vague
  • Success criteria are implicit or explicit
Solution Correctness (Critical)
  • Proposed solution actually addresses the stated problem
  • No missing steps that would leave problem unsolved
  • Edge cases considered
Scope Assessment (Important)
  • Scope is appropriate - not too broad, not too narrow
  • No scope creep (unrelated features bundled in)
  • Dependencies between tasks are logical
Over-Engineering Detection (Critical)

Patterns to detect:

  • Unnecessary abstractions
  • Premature generalization
  • Pattern abuse (using design patterns where simple code suffices)
  • Features "just in case" (YAGNI violations)
  • Excessive layering
  • Complex where simple would work
Testing Requirements (Critical)

Per plan template rules:

  • Every task includes test writing as separate checklist items
  • Tests for success AND error cases specified
  • "run tests - must pass before next task" present
  • Test locations specified (path to test file)
Maintainability (Important)
  • Solution will produce readable, maintainable code
  • Follows project conventions from CLAUDE.md
  • No clever solutions where clear would work
  • Appropriate decomposition
Task Granularity (Important)
  • Tasks are one logical unit (not multiple features bundled)
  • Specific names, not generic like "[Core Logic]"
  • Approximately 5 checkboxes per task (more OK if atomic)
  • Clear progression from task to task
Convention Adherence (Important)
  • Follows naming conventions from CLAUDE.md
  • Matches existing code patterns in the project
  • Uses project's preferred libraries/approaches
  • Comment style matches project rules
  • Aligns with user-provided custom rules (if loaded above)

Output Format

## Plan Review: [plan-filename]

### Summary
Brief assessment of plan quality (2-3 sentences)

### Critical Issues
Issues that would cause the plan to fail or produce incorrect results.

1. [plan-review] **Section: Implementation Steps > Task 2** (severity: critical)
   - Issue: Task bundles multiple unrelated features (user auth + logging)
   - Impact: Will create tangled code, harder to test and review
   - Fix: Split into Task 2a (user auth) and Task 2b (logging)

### Important Issues
Issues affecting quality or maintainability.

1. [plan-review] **Section: Technical Details** (severity: important)
   - Issue: Proposes custom validation library when project uses go-playground/validator
   - Impact: Inconsistent with existing codebase patterns
   - Fix: Use existing validator with custom rules

### Minor Issues
Suggestions for improvement.

1. [plan-review] **Section: Overview** (severity: minor)
   - Issue: Success criteria not explicitly stated
   - Fix: Add "Acceptance Criteria" subsection

### Over-Engineering Concerns
Specific patterns detected that add unnecessary complexity:

- [plan-review] **Task 4**: Proposes interface for single implementation - defer abstraction until needed
- [plan-review] **Technical Details**: Custom error type hierarchy when simple wrapped errors suffice

### Testing Coverage Assessment
- Tasks with proper test requirements: X/Y
- Missing test specifications: [list tasks]
- Test-first (TDD) compliance: [yes/partial/no]

### Verdict
**[APPROVE / NEEDS REVISION]**

[If NEEDS REVISION]:
Priority fixes before implementation:
1. [most critical fix]
2. [second priority]
3. [third priority]

Key Principles

  1. Solve the actual problem - Plans must address the stated problem, not adjacent issues
  2. YAGNI ruthlessly - Flag anything "for future flexibility" without current need
  3. Tests are mandatory - Every task must include test requirements
  4. Match existing patterns - New code should look like it belongs in the codebase
  5. Simple over clever - Prefer straightforward solutions
  6. Ask when unclear - If plan context is ambiguous, ask user rather than guess

When NOT to Flag

  • Reasonable abstractions that solve real problems
  • Testing infrastructure that the plan will actually use
  • Complexity that's inherent to the problem domain
  • Patterns that match existing codebase conventions

Confidence Scoring

Rate severity as:

  • Critical: Would cause plan failure or major issues
  • Important: Affects quality but plan could work
  • Minor: Suggestions for polish

Only report issues you're confident about. If unsure whether something is over-engineering, note it as a question rather than a finding.

Hooks 1

Sponsors

Details

Marketplace
umputun/cc-thingz
Source
plugins/planning
Category
Community

More from umputun/cc-thingz

All 7