5-phase-workflow 3.1.2 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,7 +33,7 @@ This adds the foifi rules to `AGENTS.md` as one marked block, links your existin
33
33
 
34
34
  1. **Plan** — use Claude Code's plan mode (shift+tab). Plans include a mermaid diagram where it helps.
35
35
  2. **Approve** — Claude runs `/5:implement` on its own: small plans directly, larger ones with parallel agents. It checks that the build and tests pass.
36
- 3. **Review** — runs automatically after the implementation: correctness, security, and your standards. Claude fixes the clear findings itself and asks you only about real decisions, one question at a time.
36
+ 3. **Review** — runs automatically after the implementation: correctness, security, your standards, and — for install, update, and ordering changes — the flows across files. Claude fixes every clear finding itself and asks you only about real decisions, one question at a time.
37
37
 
38
38
  On Codex, start with `$5-plan`; the rest is the same.
39
39
 
@@ -55,10 +55,10 @@ A compact plan (1-2 files, no migration, security/auth, or public API change) is
55
55
 
56
56
  A full plan goes through four steps:
57
57
 
58
- 1. `step-orchestrator-agent` derives the execution graph — steps, execution mode, dependency edges, model choice, targeted pattern references, and verify commands.
59
- 2. Executor agents implement the components using an inline executor contract, independent ones in parallel. Each follows the repository standards and style skills that apply to its target. Mechanical work runs on `haiku`, ordinary logic on `sonnet`, complex work and every retry on `opus` at medium effort.
58
+ 1. `step-orchestrator-agent` derives the execution graph — steps, execution mode, dependency edges, model choice, targeted pattern references, and verify commands. A component that needs a file another component creates goes into a later step.
59
+ 2. Executor agents implement the components using an inline executor contract, independent ones in parallel. Each follows the repository standards and style skills that apply to its target. Mechanical work runs on `haiku`, ordinary logic on `sonnet`, complex work and every retry on `opus` at medium effort. With `advisor: true` in `.5/config.json` (opt-in, Claude Code only, off by default), executors consult Claude Code's advisor tool at hard decisions and the first retry stays on the planned model (at least `sonnet`); turn the advisor on with `/advisor opus`. When the session has no advisor tool, `/5:implement` says so and runs without it. A component that finds a needed project file missing reports `blocked` instead of failing; it reruns after the next step, not as a retry.
60
60
  3. When every component was mechanical and passed, build and tests run once plus the scope check. Otherwise `verification-agent` checks completeness, build/tests, the plan's acceptance criteria when it states any, and scope.
61
- 4. `/5:review` runs once on the files the run changed — `code-review`, `security-review` for security-sensitive files, and `review-style` — and `/5:address-review-findings` then fixes the clear findings on its own and asks you only about real decisions, one question at a time. Auto-commit comes after, so approved fixes land in the same commit.
61
+ 4. The run's files are reviewed and the findings fixed — `code-review`, `review-style`, `security-review` for security-sensitive plans, and a flow review that traces fresh installs, interrupted updates, missing directories, and ordering across files when the plan touches those paths. On Claude Code this happens inside the workflow: one fixer per file applies every clear finding, including a clearly better way a reviewer points out, and build, tests, e2e, and lint run again with up to two repair attempts. You are asked only about findings that need a product, API, data, or security decision, one at a time, after the workflow. On Codex and for compact plans, `/5:review` and `/5:address-review-findings` do the same. Auto-commit comes after, so the fixes land in the same commit.
62
62
 
63
63
  Nothing is persisted. If a run fails or is interrupted, fix the cause and rerun `/5:implement`; executors see work already in the files.
64
64
 
@@ -76,7 +76,7 @@ On Claude Code, review delegates to the built-in `code-review` skill. Effort def
76
76
  .5/features/{feature-name}/review-findings-{timestamp}.md
77
77
  ```
78
78
 
79
- When findings exist after `/5:implement`, `/5:review` hands them straight to `/5:address-review-findings`. When you start `/5:review` yourself — possibly on someone else's branch — it asks once before fixing anything and running build and tests. It fixes clear findings on its own — confirmed bugs, security issues, breaches of a repository standard, and style findings with a clear local fix — skips obsolete or out-of-scope ones, and asks you only about real decisions, one question at a time. Then it runs build, tests, and lint, and reports what it fixed, what it skipped, and what you decided. To go through saved findings again, or to decide on every finding yourself:
79
+ When findings exist, `/5:review` hands them straight to `/5:address-review-findings`, also when you started the review yourself. It fixes clear findings on its own — confirmed bugs, security issues, breaches of a repository standard, style findings, and clearly better ways to do the same thing — checks uncertain findings against the code before it would ask, skips obsolete or out-of-scope ones, and asks you only about real decisions, one question at a time. Then it runs build, tests, and lint, and reports what it fixed, what it skipped, and what you decided. To go through saved findings again, or to decide on every finding yourself:
80
80
 
81
81
  ```text
82
82
  /5:address-review-findings {feature-name} [--interactive]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "5-phase-workflow",
3
- "version": "3.1.2",
3
+ "version": "3.2.1",
4
4
  "description": "A dev-workflow for Claude Code and Codex",
5
5
  "bin": {
6
6
  "foifi": "bin/install.js"
@@ -18,6 +18,11 @@ You follow the plan, your component, and existing codebase patterns. You do not
18
18
  5. Follow the standards `/5:implement` assigns: read the parts of the repository standards and style skills that apply to your target. Repository standards win over the style skills. If the target area has a local skill or rule, follow it too.
19
19
  6. Run every verify command assigned to your component. If none is assigned, verify touched files exist and run the narrowest relevant test/build command you can infer.
20
20
  7. Fix local mechanical issues you caused. Stop for architectural changes, auth gates, missing external services, or unclear product decisions.
21
+ 8. When a project file or symbol your component needs does not exist yet, do not create it: stop with `STATUS: blocked` and name it under `BLOCKED_BY`. `/5:implement` reruns you after the next step instead of retrying.
22
+
23
+ ## Advisor (opt-in)
24
+
25
+ Only when `/5:implement` says the advisor is enabled (`.5/config.json` `advisor: true`, and the session has the advisor tool): consult it before committing to an approach when the intent is ambiguous or crosses modules, and when the same verify failure returns after a fix. Do not consult it for mechanical edits or to confirm work that already passes. On a retry, consult it before your first edit.
21
26
 
22
27
  ## Simplicity
23
28
 
@@ -27,7 +32,8 @@ End with exactly:
27
32
 
28
33
  ```text
29
34
  ---RESULT---
30
- STATUS: success | failed
35
+ STATUS: success | failed | blocked
36
+ BLOCKED_BY: none | {the missing project file or symbol}
31
37
  FILES_CREATED: [comma-separated paths]
32
38
  FILES_MODIFIED: [comma-separated paths]
33
39
  VERIFY: passed | failed | skipped
@@ -43,7 +49,9 @@ Keep the result block concise. Do not include command logs, diffs, or long expla
43
49
 
44
50
  **Fix and note** in deviations: imports, type mismatches, or lint you caused; a nearby existing convention that contradicts the plan (follow the convention).
45
51
 
46
- **Stop and report** as failed: a required dependency/package is absent; a database/schema/auth/API contract change not in the plan.
52
+ **Stop and report** as failed: a required package is absent; a database/schema/auth/API contract change not in the plan.
53
+
54
+ **Stop and report** as blocked: a project file or symbol the component needs has not been created yet.
47
55
 
48
56
  **Report the exact evidence, but do not mark the component failed**, when verify fails only from pre-existing unrelated issues (your change is complete and correct; record the failure as a deviation so verification can treat it as pre-existing).
49
57
 
@@ -17,6 +17,7 @@ Turn the plan into execution state that `/5:implement` can run without rethinkin
17
17
  - Name each component in short kebab-case.
18
18
  - Group independent components into the same step with `mode: "parallel"`.
19
19
  - Use `mode: "sequential"` when components touch the same file, one imports another, or an explicit dependency exists.
20
+ - For each component, list the project files and symbols it includes, requires, imports, calls, or tests. When another component creates one of them, add it to `dependsOn` and put it in an earlier step — never the same parallel step or a later one.
20
21
  - Prefer fewer steps when dependencies allow.
21
22
  - Tests normally run after the components they validate.
22
23
  - Choose `model: "haiku"` for mechanical work: localized UI changes, tests, docs, config edits, and simple single-file changes.
@@ -25,6 +26,7 @@ Turn the plan into execution state that `/5:implement` can run without rethinkin
25
26
  - Pick `patternRefs` from patterns the plan names, or from nearby existing files found with Glob/Grep. Prefer one primary reference; use a second only when it adds a distinct convention. Include line ranges or symbols when known so executors avoid reading whole files.
26
27
  - Pick `verifyCommands` from `.5/config.json`, the plan, package scripts, and target-specific checks. Prefer narrow checks first, then project-level build/test.
27
28
  - Preserve user decisions exactly. Exclude work the plan defers or rules out.
29
+ - Set `securitySensitive` when the plan touches auth, authorization, user input handling, secrets, cryptography, or SQL/shell/path construction, and `lifecycleSensitive` when it touches install, update, migration, deploy, or bootstrap paths, or the order in which files are written, uploaded, or loaded. They decide which reviewers run after the implementation.
28
30
 
29
31
  ## Output
30
32
 
@@ -32,6 +34,8 @@ Return this shape:
32
34
 
33
35
  ```json
34
36
  {
37
+ "securitySensitive": false,
38
+ "lifecycleSensitive": false,
35
39
  "steps": [
36
40
  {
37
41
  "number": 1,
@@ -71,7 +75,7 @@ Return this shape:
71
75
  Before returning:
72
76
 
73
77
  - Every piece of planned work is represented once unless the plan defers it.
74
- - Every non-first-step dependency refers to an existing component name.
78
+ - Every non-first-step dependency refers to an existing component name in an earlier step.
75
79
  - Every component has 1-2 high-signal `patternRefs`, or a note explaining why no pattern exists.
76
80
  - Every component has at least one verify command or a note explaining why verification is manual.
77
81
  - Rename components must set `sourceFile` to the original path and `file` to the destination path.
@@ -19,7 +19,7 @@ You are a Review Fix Coordinator. You fix what is clear, ask the user only what
19
19
  ## Options
20
20
 
21
21
  - `--interactive` — ask about every finding, one at a time, instead of deciding the clear ones yourself.
22
- - `dirty: {paths}` — files that held the user's own uncommitted work before the run (`/5:implement` passes this). A finding in one of them may sit in that earlier work, so it is always **ask**, never fixed on your own.
22
+ - `dirty: {paths}` — files that held the user's own uncommitted work before the run (`/5:implement` passes this). A finding in one of them may sit in that earlier work, so it is never fixed on your own and never asked about: record it as `wait` with the reason "pre-run dirty file" and list it in the report.
23
23
 
24
24
  ## Process
25
25
 
@@ -31,9 +31,10 @@ You are a Review Fix Coordinator. You fix what is clear, ask the user only what
31
31
  - Find the latest `.5/features/{feature}/review-findings-*.md`. If missing, tell the user to run `/5:review` and stop.
32
32
  - Parse each finding into compact records with `id`, `file`, `line`, `category`, `severity`, `description`, `suggestedFix`, and `originalReviewerMessage`.
33
33
  - Sort each finding into one group:
34
- - **fix** — a confirmed bug, security issue, breach of a repository standard, or style finding with a clear, local fix that changes no behavior beyond the finding.
35
- - **wont_fix** — obsolete, a duplicate, outside the feature scope, or based on an incorrect premise.
36
- - **ask** — uncertain (`Question` category), spanning several files, or needing a design, product, or API decision; also any fix whose suggested change you cannot apply with confidence.
34
+ - **fix** — a confirmed bug, security issue, breach of a repository standard, style finding, or a clearly better way to do the same thing (simpler, reuses existing code, more robust), with a concrete fix. Spanning several files is no reason to ask.
35
+ - **wont_fix** — obsolete, a duplicate, outside the feature scope, based on an incorrect premise, or a marginal gain.
36
+ - **ask** — only when the right fix depends on a product, API, data, or security trade-off the plan does not settle, or would contradict the plan. Before asking about a `Question` finding or a fix you are unsure of, read the code: confirmed → **fix**, refuted → **wont_fix**. Ask only what is still open after that.
37
+ - The user wants to be involved as little as possible. When in doubt between **fix** and **ask**, and the fix is reversible and inside the reviewed files, choose **fix**.
37
38
  - Record `fix` and `wont_fix` yourself, each with a one-line reason.
38
39
  - For each **ask** finding, ask the user — **one finding per question, one question at a time**. Show `Decision {current}/{total}`, file and line, a concise description, the suggested fix, and your recommendation. Options: `fix`, `wont_fix`, `wait`, or textual instructions. Treat textual instructions as `fix` with `customInstructions` unless the text clearly says to defer or reject the finding.
39
40
  - With `--interactive`, ask about every finding this way instead.
@@ -137,6 +137,12 @@ If "Cancel": Exit immediately with message "Configuration unchanged."
137
137
  1. "No (recommended)" → `git.autoCommit: false`
138
138
  2. "Yes - commit after each implementation step" → `git.autoCommit: true`
139
139
 
140
+ **2f2. Advisor during implementation (Claude Code only — skip on Codex and set `advisor: false`):**
141
+ - "Let `/5:implement` executors consult Claude Code's advisor tool at hard decisions, and retry a failed component once on its planned model before escalating to opus? Needs the advisor turned on in Claude Code (`/advisor opus`); it is experimental and Anthropic-API only. Without the tool in the session, `/5:implement` warns and runs without it."
142
+ - Options:
143
+ 1. "No (recommended)" → `advisor: false`
144
+ 2. "Yes" → `advisor: true`
145
+
140
146
  **2g. Commit message pattern:**
141
147
 
142
148
  When the repository already documents a commit convention (step 1e or 1e2), that convention wins and AGENTS.md links it. Skip the question, and derive the closest pattern from the convention with the `{ticket-id}` and `{short-description}` placeholders — for example `feat({ticket-id}): {short-description}` for Conventional Commits — and store it as `git.commitMessage.pattern`, so auto-commits follow the convention too. Otherwise ask:
@@ -189,7 +195,7 @@ Using the values gathered from Steps 1 and 2, write `.5/config.json` directly.
189
195
  mkdir -p .5
190
196
  ```
191
197
 
192
- **Schema:** Read `.claude/references/configure-tables.md` section "Config Schema" for the full JSON structure. Fill all values from user responses (including `rules.generate` from step 2j2). Write with pretty-printed JSON. Read back to verify correctness.
198
+ **Schema:** Read `.claude/references/configure-tables.md` section "Config Schema" for the full JSON structure. Fill all values from user responses (including `advisor` from step 2f2 and `rules.generate` from step 2j2). Write with pretty-printed JSON. Read back to verify correctness.
193
199
 
194
200
  **Update `.5/version.json` with configure timestamp:**
195
201
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: 5:implement
3
- description: Executes a plan from .5/planning/. Compact plans are implemented inline in this session; full plans run through the Workflow tool when available (parallel waves, schema-validated agents), otherwise an equivalent prose loop. Codex always uses the prose loop. Verifies that the plan was built and works, then runs /5:review.
3
+ description: Executes a plan from .5/planning/. Compact plans are implemented inline in this session; full plans run through the Workflow tool when available (parallel waves, schema-validated agents), otherwise an equivalent prose loop. Codex always uses the prose loop. Verifies that the plan was built and works, then reviews the run's files and fixes the clear findings — inside the workflow on Claude Code, via /5:review otherwise.
4
4
  allowed-tools: Agent, Read, Write, Edit, Glob, Grep, Bash, Workflow, Skill, AskUserQuestion
5
5
  user-invocable: true
6
6
  argument-hint: [feature-name-or-plan-path]
@@ -23,7 +23,7 @@ Find the plan:
23
23
 
24
24
  Plans have no fixed shape. The feature name is the plan's `feature` frontmatter field when it has one, otherwise the file name without `.md`.
25
25
 
26
- Read the plan and `.5/config.json` if it exists. Nothing is persisted between runs; a rerun starts over, and executors see work that is already done in the files.
26
+ Read the plan and `.5/config.json` if it exists. The advisor is **enabled** for this run only when `.5/config.json` has `advisor: true`, the runtime is Claude Code, and this session actually has an advisor tool — subagents inherit it from here. When the setting is on but the tool is missing, tell the user once — "Advisor is on in `.5/config.json`, but no advisor tool is available in this session (`/advisor opus`, Anthropic API only); running without it." — and run with the advisor disabled. Codex has no advisor tool and ignores the setting. Nothing is persisted between runs; a rerun starts over, and executors see work that is already done in the files.
27
27
 
28
28
  A plan is **compact** when it changes 1-2 files with no data migration, no security/auth change, and no public API change. Every other plan is **full**.
29
29
 
@@ -38,6 +38,8 @@ Record `git rev-parse HEAD` as this run's **fixed point** for the review in Step
38
38
 
39
39
  Run build/test commands from `.5/config.json`. Skip commands set to `none`. Keep the results in context for this run — they are what lets verification tell pre-existing failures apart from new ones. If baseline fails, warn and continue.
40
40
 
41
+ When a command cannot run at all — a tool or dependency is not installed, or a download fails because the network is blocked — say so right away: "Build/test cannot run here ({reason}); this run is verified only by reading the code." Carry the same line into the report, so the user knows CI is the first real check.
42
+
41
43
  ## Step 3: Run
42
44
 
43
45
  ### Compact plan: implement inline
@@ -59,15 +61,22 @@ It moves orchestration into deterministic JS, fires parallel components concurre
59
61
  "feature": "{feature-name}",
60
62
  "paths": {"plan": "{plan-path}", "config": ".5/config.json"},
61
63
  "standards": {"repo": ["CONTRIBUTING.md"], "styles": ["/abs/path/.claude/skills/fowler-code-smells/SKILL.md"]},
62
- "baseline": [{"command": "...", "status": "passed|failed|skipped", "summary": "one line"}]
64
+ "baseline": [{"command": "...", "status": "passed|failed|skipped", "summary": "one line"}],
65
+ "advisor": false,
66
+ "fixedPoint": "{fixed-point}",
67
+ "dirty": ["{pre-run dirty file}"]
63
68
  }
64
69
  ```
65
70
 
66
71
  - `standards` holds the repository standards and style skill paths from Step 1. Executors follow them while writing code.
67
72
  - `baseline` is the array from Step 2 (or `[]`); the workflow's verifier treats those failures as pre-existing and reuses passing results instead of rerunning them.
73
+ - `advisor` is `true` only when the advisor is enabled (Step 1). It adds the advisor rule to the executors and keeps their first retry on the planned model, at least `sonnet`.
74
+ - `fixedPoint` and `dirty` are the fixed point and the pre-run dirty files from Step 2. The workflow reviews only the run's files since the fixed point and never edits a dirty file.
68
75
  - The workflow reads the config **file** at `paths.config` itself; do not pass build/test/commit settings inline.
69
76
 
70
- 2. If the returned `verification.inline` is `true` (every component was mechanical and passed, so no verification agent ran), run the **fast-path check** (3c) and take its result as the verification.
77
+ The workflow also reviews and fixes: after verification it runs the correctness and standards reviewers — plus security and flow reviewers when the plan touches security or install/update/ordering paths — fixes every clear finding with one fixer per file, and reruns build, test, e2e, and lint with up to two repair attempts. It skips review and fix when verification failed.
78
+
79
+ 2. If the returned `verification.inline` is `true` (every component was mechanical and passed, so no verification agent ran), run steps 2-4 of the **fast-path check** (3c) — the scope part. Build and test already ran in `review.checks`; take their result as the verification.
71
80
  3. Continue with Step 4.
72
81
 
73
82
  ### Full plan, without the `Workflow` tool (prose loop)
@@ -86,14 +95,15 @@ For each step:
86
95
  2. Spawn executors with the component's model. Run `opus` at `effort: "medium"`.
87
96
  - **Parallel step: emit all of the step's executor Agent calls in a single message so they run concurrently.**
88
97
  - Sequential step (same-file or dependency): one executor at a time.
89
- - Give each executor only its component block, required `patternRefs`, verify commands, the standards from Step 1, and the inline contract below — do not make it read `step-executor-agent.md`.
98
+ - Give each executor only its component block, required `patternRefs`, verify commands, the standards from Step 1, and the inline contract below — do not make it read `step-executor-agent.md`. When the advisor is enabled, append the advisor line after the contract.
90
99
 
91
100
  ```text
92
- Implement exactly the assigned component. Read only listed patternRefs ranges/symbols and the target file. Nothing is persisted between runs, so your work may already be done: for `create`, read the target first when it exists — if it already fulfils the intent, report success with no change; otherwise complete it, never overwrite it blindly. Read the parts of the repository standards and style skills that apply to your target and follow them; repository standards win over the styles. Make the smallest coherent change — reuse existing codebase code first, then stdlib, native platform features, and installed dependencies; touch only the target file and what it strictly needs (its test, an import site) — run assigned verify commands, and stop (STATUS: failed) for missing dependencies, unplanned auth/schema/API changes, or unclear product decisions. If verify fails only from pre-existing unrelated issues, report it under DEVIATIONS with the exact evidence and keep STATUS: success — your change is complete. Do not make more than three attempts on the same failing issue.
101
+ Implement exactly the assigned component. Read only listed patternRefs ranges/symbols and the target file. Nothing is persisted between runs, so your work may already be done: for `create`, read the target first when it exists — if it already fulfils the intent, report success with no change; otherwise complete it, never overwrite it blindly. Read the parts of the repository standards and style skills that apply to your target and follow them; repository standards win over the styles. Make the smallest coherent change — reuse existing codebase code first, then stdlib, native platform features, and installed dependencies; touch only the target file and what it strictly needs (its test, an import site) — run assigned verify commands. When a project file or symbol your component needs does not exist yet, do not create it: stop with STATUS: blocked and name it under BLOCKED_BY. Stop (STATUS: failed) for a missing package, unplanned auth/schema/API changes, or unclear product decisions. If verify fails only from pre-existing unrelated issues, report it under DEVIATIONS with the exact evidence and keep STATUS: success — your change is complete. Do not make more than three attempts on the same failing issue.
93
102
 
94
103
  End with:
95
104
  ---RESULT---
96
- STATUS: success | failed
105
+ STATUS: success | failed | blocked
106
+ BLOCKED_BY: none | {the missing project file or symbol}
97
107
  FILES_CREATED: [comma-separated paths]
98
108
  FILES_MODIFIED: [comma-separated paths]
99
109
  VERIFY: passed | failed | skipped
@@ -103,9 +113,17 @@ ERROR: none | {error description}
103
113
  ---END---
104
114
  ```
105
115
 
116
+ Advisor line (only when the advisor is enabled):
117
+
118
+ ```text
119
+ Advisor: if an advisor tool is available, consult it before committing to an approach when the intent is ambiguous or crosses modules, and when the same verify failure returns after a fix. Do not consult it for mechanical edits or to confirm work that already passes.
120
+ ```
121
+
106
122
  3. Parse only the `---RESULT---` block from each executor. Trust the executor's report — do not re-read files you did not change to confirm them.
107
123
 
108
- Retry failed components up to twice on `opus` at `effort: "medium"`. Never fix code in the orchestrator context.
124
+ Retry a failed component up to twice, right after it fails (in a sequential step, before the next component starts), on `opus` at `effort: "medium"`. When the advisor is enabled, the first retry stays on the component's planned model — at least `sonnet` — and asks the executor to consult the advisor before its first edit; only the second escalates to `opus`.
125
+
126
+ `STATUS: blocked` is no retry reason: the component needs a project file or symbol another component has not created yet, and no model can fix that. Rerun it on its planned model once the next step has finished; if it is still blocked, rerun it once more after the last step. Still blocked after that counts as failed. Give every retry the previous attempt's `STATUS`, `VERIFY`, `ERROR`, and `DEVIATIONS` (or that it returned no result). A `STATUS: success` with `VERIFY: failed` is no retry reason: it can come from pre-existing failures, which verification separates using the baseline. Never fix code in the orchestrator context.
109
127
 
110
128
  #### 3c. Verify
111
129
 
@@ -134,11 +152,21 @@ Set `SCOPE: passed | drift`. Drift never changes the verification status; it onl
134
152
 
135
153
  ## Step 4: Review
136
154
 
137
- Run `/5:review since {fixed-point} files: {run-files} feature: {feature-name} dirty: {dirty-files}` with the fixed point and the pre-run dirty files from Step 2 (`dirty: none` when there are none). `{run-files}` lists the files this run created, modified, or deleted, so changes the user already had stay out of the review. `/5:review` runs every quality check exactly once — the built-in `code-review`, `security-review` for security-sensitive files, and `review-style` against the repository standards and the style skills — saves the findings, fixes the clear ones on its own, and asks the user only about real decisions, one at a time. Run it on every path, and before the auto-commit, so approved fixes land in the same commit.
155
+ Review and fix the run's files before the auto-commit, so fixes land in the same commit. The user should be involved as little as possible: every clear finding — including a clearly better way the review points out — is fixed without asking.
156
+
157
+ **After the Workflow route:** the workflow already reviewed and fixed. If `review` is `null`, verification failed and there is nothing to review yet. Otherwise:
158
+
159
+ 1. Write `.5/features/{feature-name}/review-findings-{YYYYMMDD-HHmmss}.md` from `review.findings` using `.claude/templates/workflow/REVIEW-FINDINGS.md`: `action: fix` → **Category:** `Fixable`, `decide` → `Question`, `report` and `skip` → `Manual` with their `reason`; `severity`, `file`, `line`, `description`, and `fix` map to their fields, and the reviewer name goes into **Original Reviewer Message:**.
160
+ 2. Findings with `action: decide` are the only ones you ask about — one finding per question, one question at a time, in the format of `/5:address-review-findings` step 2. Apply the chosen fixes and run its post-fix verification (steps 3-4). Also retry each `fix` finding with `status: failed` once yourself; one that still fails goes into the report, not to the user.
161
+ 3. Write `.5/features/{feature-name}/review-decisions-{YYYYMMDD-HHmmss}.json` in the format of `/5:address-review-findings`: the workflow's fixes as `decidedBy: claude`, the answers as `decidedBy: user`.
162
+
163
+ The code is **green** when `review.checks` is `null` or `passed` and the post-fix verification of step 2, if any ran, passed.
164
+
165
+ **Every other route** (compact plan, prose loop, Codex): Run `/5:review since {fixed-point} files: {run-files} feature: {feature-name} dirty: {dirty-files}` with the fixed point and the pre-run dirty files from Step 2 (`dirty: none` when there are none). `{run-files}` lists the files this run created, modified, or deleted, so changes the user already had stay out of the review. `/5:review` runs every quality check exactly once — the built-in `code-review`, `security-review` for security-sensitive files, the flow review for install/update/ordering paths, and `review-style` against the repository standards and the style skills — saves the findings, and hands them to `/5:address-review-findings`, which fixes the clear ones on its own and asks the user only about real decisions. The code is green when no review fix was applied or it reported `Review findings addressed: yes`.
138
166
 
139
167
  ## Step 5: Auto-commit
140
168
 
141
- If `.5/config.json` `git.autoCommit` is `true`, verification passed, and Step 4 left the code green — no review fix was applied, or `/5:address-review-findings` reported `Review findings addressed: yes` — commit, including the review fixes from Step 4 for those files, once per step for a full plan, once for a compact plan:
169
+ If `.5/config.json` `git.autoCommit` is `true`, verification passed, and Step 4 left the code green — commit, including the review fixes from Step 4 for those files, once per step for a full plan, once for a compact plan:
142
170
 
143
171
  1. Stage only files that step owns: each component's `file` for create/modify/delete, both `sourceFile` and `file` for rename, plus the executors' reported `FILES_CREATED`/`FILES_MODIFIED`. For a compact plan, stage the files you changed. Do not stage unrelated changes. **Never stage a pre-run dirty file** (Step 2), on any plan: it holds the user's own unfinished work. Leave it uncommitted and list it in the report.
144
172
  2. Build the message from `git.commitMessage.pattern`, replacing `{ticket-id}` with the ticket the plan or the branch name gives (or empty) and `{short-description}` with `step {number}: {step-name}` (compact plan: a short summary of the change); trim redundant whitespace/punctuation when the ticket is empty.
@@ -150,7 +178,9 @@ When a review fix left build, tests, e2e, or lint failing, do not commit; report
150
178
 
151
179
  Report: completed/failed component counts, verification status, auto-commit count and any failures, and any failed commands, missing tests, or unmet acceptance criteria. When verification failed, tell the user to fix the reported issues and rerun `/5:implement {feature-name}`. Also list, one line each:
152
180
 
153
- - **Review:** the findings count from `/5:review` and how many were fixed.
181
+ - **Review:** the findings count, how many were fixed without asking, how many you asked about, and every failed fix.
182
+ - **Blocked:** components that stayed blocked, with what they were waiting for — a sign the plan's step order is wrong.
183
+ - **Not verified locally:** the line from Step 2, when build/test could not run here.
154
184
  - **Scope:** drift findings from verification, plus files an executor touched outside its planned target (the workflow returns these as `extraFiles`). Suggest `/5:lean-check {feature-name}` when there are any.
155
185
  - **Skipped:** every non-`none` `SKIPPED` entry from the executors, so deliberate omissions stay visible.
156
186
  - **Not committed:** pre-run dirty files the run changed — they also hold the user's earlier work, so the user commits them.
@@ -48,6 +48,19 @@ Skill(skill: "security-review")
48
48
 
49
49
  Use the vulnerabilities it reports. Skip it for diffs that touch none of these areas.
50
50
 
51
+ **Flow review** — a diff reviewer reads file by file and misses failures that only show across files and states. When the diff touches install, update, migration, deploy, or bootstrap paths, the order in which files are written, uploaded, or loaded, or is security-sensitive, spawn one agent on `opus` at `effort: "medium"`:
52
+
53
+ ```text
54
+ Trace behavior ACROSS the changed files and the states they run in. Read the entry points, then follow each flow end to end:
55
+ - a fresh install with no earlier state: missing directories, files, config, or database rows;
56
+ - an upgrade from the previous version, and an update that stops halfway;
57
+ - the order of operations across files: what is written, uploaded, loaded, or required first, and what breaks when that order changes or one step fails;
58
+ - output, headers, or side effects that happen before guards, error handling, or error suppression are in place;
59
+ - files and helpers the change relies on but does not check, and tests that assert the old order or state.
60
+ Report only failures you can describe as a concrete sequence of states. Do not edit files.
61
+ Output the same blocks as the fallback path below.
62
+ ```
63
+
51
64
  **Standards review** — then invoke `review-style` in report-only mode. It checks the same changes against the repository's own standards and the style skills it lists, and repository standards win:
52
65
 
53
66
  ```text
@@ -92,7 +105,7 @@ When the findings come from the `code-review` skill, map its reported fields ont
92
105
  | Reported finding | Template field |
93
106
  |---|---|
94
107
  | `verdict: CONFIRMED` with a localized, single-file fix | **Category:** `Fixable` |
95
- | `verdict: PLAUSIBLE` | **Category:** `Question` |
108
+ | `verdict: PLAUSIBLE` | read the code and confirm or refute it yourself: confirmed → as `CONFIRMED`, refuted → leave it out, still open → **Category:** `Question` |
96
109
  | `verdict: CONFIRMED` but spanning files or needing a design decision | **Category:** `Manual` |
97
110
  | `category: correctness` | **Severity:** `error` (`warning` when `PLAUSIBLE`) |
98
111
  | `category: simplification` / `efficiency` / `test-coverage` | **Severity:** `suggestion` |
@@ -103,7 +116,9 @@ When the findings come from the `code-review` skill, map its reported fields ont
103
116
 
104
117
  Findings from `security-review` map to **Category:** `Fixable` when the fix is local, otherwise `Manual`, always with **Severity:** `error`; its explanation of the exploit goes into **Original Reviewer Message:**.
105
118
 
106
- Findings from the fallback path map directly: Fixable Issues, Questions, and Manual Review become their matching categories.
119
+ Findings from the fallback path and the flow review map directly: Fixable Issues, Questions, and Manual Review become their matching categories.
120
+
121
+ Use `Question` sparingly: only for a finding whose fix depends on a decision the user must make. A clearly better way to do the same thing is `Fixable`, not a question.
107
122
 
108
123
  Findings from `review-style` map like this. Leave out its Suppressed findings; a repository standard overrides them.
109
124
 
@@ -134,7 +149,4 @@ Findings saved at `.5/features/{feature-name}/review-findings-{timestamp}.md`
134
149
 
135
150
  If there are no findings, stop here.
136
151
 
137
- Otherwise hand off to `/5:address-review-findings {feature-name}`. It fixes the clear findings on its own, asks the user one question at a time only about real decisions, and then runs build, test, and lint.
138
-
139
- - **Called by `/5:implement`** (the `since … files:` scope): run `/5:address-review-findings {feature-name} dirty: {dirty-paths}` right away. The user approved the plan, and these are the run's own files — except the dirty ones, which also hold the user's earlier work.
140
- - **Started on its own:** the reviewed code may come from someone else's branch, and the fixes are followed by the project's build and test commands. Ask once: "Fix the clear findings on my own and then run build, test, and lint?" On yes, run it. On no, stop and tell the user they can run `/5:address-review-findings {feature-name}` (or `--interactive`) later.
152
+ Otherwise run `/5:address-review-findings {feature-name}` right away — with `dirty: {dirty-paths}` when `/5:implement` called this review. It fixes the clear findings on its own, asks the user one question at a time only about real decisions, and then runs build, test, and lint. Do not ask before handing off: the user asked for the review, and the findings exist to be fixed. A user who wants to decide every finding runs `/5:address-review-findings {feature-name} --interactive`.
@@ -66,6 +66,7 @@ Check files in this order (first match wins):
66
66
  "available": false
67
67
  }
68
68
  },
69
+ "advisor": false,
69
70
  "git": {
70
71
  "autoCommit": false,
71
72
  "commitMessage": {
@@ -1,11 +1,13 @@
1
1
  export const meta = {
2
2
  name: '5-implement',
3
- description: 'Execute a full plan: derive steps, run executors in parallel waves, verify. Claude Code only; Codex uses the prose loop.',
3
+ description: 'Execute a full plan: derive steps, run executors in parallel waves, verify, review, fix the findings. Claude Code only; Codex uses the prose loop.',
4
4
  whenToUse: 'Invoked by the /5:implement command for full plans when the Workflow tool is available. Compact plans never reach it; the command implements them inline.',
5
5
  phases: [
6
6
  { title: 'Orchestrate', detail: 'one orchestrator agent derives steps + components' },
7
- { title: 'Execute', detail: 'one executor agent per component; parallel components fire together per step' },
8
- { title: 'Verify', detail: 'inline when all passed + mechanical, else one verification agent' }
7
+ { title: 'Execute', detail: 'one executor agent per component; parallel components fire together per step; blocked components rerun after the next step' },
8
+ { title: 'Verify', detail: 'inline when all passed + mechanical, else one verification agent' },
9
+ { title: 'Review', detail: 'correctness, standards, and — when the plan calls for them — security and flow reviewers in parallel' },
10
+ { title: 'Fix', detail: 'one fixer per file for every clear finding, then build/test/lint with one repair round' }
9
11
  ]
10
12
  }
11
13
 
@@ -14,12 +16,19 @@ export const meta = {
14
16
  // inline, schema-validated form of src/agents/*-agent.md. Those .md files remain
15
17
  // the canonical human-readable contract; keep these prompts in sync with them.
16
18
  //
19
+ // The reviewer prompts are the schema-validated form of src/commands/5/review.md,
20
+ // the fixer prompt and the triage rules that of address-review-findings.md.
21
+ //
17
22
  // This script has NO filesystem access. It orchestrates agents and RETURNS the
18
- // final result. The /5:implement command runs the fast-path build/test check and
19
- // auto-commit after this returns. Nothing is persisted: a rerun starts over.
23
+ // final result. The /5:implement command writes the findings file, asks the user
24
+ // about the few findings that need a decision, runs the scope check, and
25
+ // auto-commits after this returns. Nothing is persisted: a rerun starts over.
20
26
  //
21
27
  // Models: haiku for mechanical work, sonnet for ordinary logic, opus at effort
22
- // medium for complex work and for every retry.
28
+ // medium for complex work and for every retry. With args.advisor (opt-in, from
29
+ // .5/config.json; the command sets it only when the advisor tool is available)
30
+ // executors consult Claude Code's advisor tool at decision points and the first
31
+ // retry stays on the planned model, at least sonnet.
23
32
  // ─────────────────────────────────────────────────────────────────────────────
24
33
 
25
34
  const RESULT_SCHEMA = {
@@ -27,7 +36,8 @@ const RESULT_SCHEMA = {
27
36
  additionalProperties: false,
28
37
  required: ['status', 'verify', 'skipped'],
29
38
  properties: {
30
- status: { enum: ['success', 'failed'] },
39
+ status: { enum: ['success', 'failed', 'blocked'] },
40
+ blockedBy: { type: 'string', description: 'when blocked: the project file or symbol that does not exist yet' },
31
41
  filesCreated: { type: 'array', items: { type: 'string' } },
32
42
  filesModified: { type: 'array', items: { type: 'string' } },
33
43
  verify: { enum: ['passed', 'failed', 'skipped'] },
@@ -37,6 +47,77 @@ const RESULT_SCHEMA = {
37
47
  }
38
48
  }
39
49
 
50
+ const FINDINGS_SCHEMA = {
51
+ type: 'object',
52
+ additionalProperties: false,
53
+ required: ['findings'],
54
+ properties: {
55
+ findings: {
56
+ type: 'array',
57
+ items: {
58
+ type: 'object',
59
+ additionalProperties: false,
60
+ required: ['file', 'description', 'action'],
61
+ properties: {
62
+ file: { type: 'string' },
63
+ line: { type: 'integer' },
64
+ severity: { enum: ['error', 'warning', 'suggestion'] },
65
+ description: { type: 'string' },
66
+ fix: { type: 'string', description: 'the concrete change to make' },
67
+ action: { enum: ['fix', 'decide', 'skip'] },
68
+ reason: { type: 'string', description: 'one line: why skip, or which decision the user must make' }
69
+ }
70
+ }
71
+ }
72
+ }
73
+ }
74
+
75
+ const FIX_SCHEMA = {
76
+ type: 'object',
77
+ additionalProperties: false,
78
+ required: ['items'],
79
+ properties: {
80
+ items: {
81
+ type: 'array',
82
+ items: {
83
+ type: 'object',
84
+ additionalProperties: false,
85
+ required: ['id', 'status'],
86
+ properties: {
87
+ id: { type: 'string' },
88
+ status: { enum: ['applied', 'rejected', 'failed'] },
89
+ note: { type: 'string', description: 'one line: what changed, or why rejected/failed' }
90
+ }
91
+ }
92
+ },
93
+ filesModified: { type: 'array', items: { type: 'string' } }
94
+ }
95
+ }
96
+
97
+ const CHECKS_SCHEMA = {
98
+ type: 'object',
99
+ additionalProperties: false,
100
+ required: ['status', 'commands'],
101
+ properties: {
102
+ status: { enum: ['passed', 'failed'] },
103
+ commands: {
104
+ type: 'array',
105
+ items: {
106
+ type: 'object',
107
+ additionalProperties: false,
108
+ required: ['command', 'status'],
109
+ properties: {
110
+ category: { enum: ['build', 'test', 'e2e', 'lint'] },
111
+ command: { type: 'string' },
112
+ status: { enum: ['passed', 'failed', 'skipped', 'pre-existing'] },
113
+ summary: { type: 'string' }
114
+ }
115
+ }
116
+ },
117
+ filesModified: { type: 'array', items: { type: 'string' } }
118
+ }
119
+ }
120
+
40
121
  const VERIFICATION_SCHEMA = {
41
122
  type: 'object',
42
123
  additionalProperties: false,
@@ -69,6 +150,8 @@ const STATE_SCHEMA = {
69
150
  additionalProperties: false,
70
151
  required: ['steps', 'pendingComponents'],
71
152
  properties: {
153
+ securitySensitive: { type: 'boolean', description: 'the change touches auth, authorization, user input, secrets, crypto, or SQL/shell/path construction' },
154
+ lifecycleSensitive: { type: 'boolean', description: 'the change touches install, update, migration, deploy, or bootstrap paths, or ordering across files' },
72
155
  steps: {
73
156
  type: 'array',
74
157
  items: {
@@ -137,8 +220,20 @@ The plan has no fixed shape. Derive the components from whatever it describes: o
137
220
  - 1-2 high-signal patternRefs per component with line ranges or symbols so executors avoid whole-file reads. Take them from the plan where it names patterns, else find them with Glob/Grep.
138
221
  - verifyCommands: narrowest relevant check first, then project build/test.
139
222
  - Exclude work the plan defers or rules out. Represent every other component once. dependsOn must reference existing component names.
223
+ - Dependencies: for each component, list the project files and symbols it includes, requires, imports, calls, or tests. When another component creates one of them, add that component to dependsOn and put it in an EARLIER step — never the same parallel step or a later one.
224
+ - securitySensitive: true when the plan touches auth, authorization, user input handling, secrets, cryptography, or SQL/shell/path construction. lifecycleSensitive: true when it touches install, update, migration, deploy, or bootstrap paths, or the order in which files are written, uploaded, or loaded.
225
+
226
+ Return an object matching the schema (securitySensitive, lifecycleSensitive, steps[] and pendingComponents[]).`
227
+ }
228
+
229
+ const ADVISOR_RULE = 'Advisor: if an advisor tool is available, consult it before committing to an approach when the intent is ambiguous or crosses modules, and when the same verify failure returns after a fix. Do not consult it for mechanical edits or to confirm work that already passes.'
140
230
 
141
- Return an object matching the schema (steps[] and pendingComponents[]).`
231
+ function retryContext(previous, a) {
232
+ const failure = previous
233
+ ? `status ${previous.status}, verify ${previous.verify}, error: ${previous.error || 'none'}, deviations: ${previous.deviations || 'none'}`
234
+ : 'the agent crashed without returning a result'
235
+ const advisor = a.advisor ? ' Consult the advisor, if available, before your first edit.' : ''
236
+ return `This is a RETRY of a failed attempt (${failure}). Read the target as the previous attempt left it, find the root cause, and correct it.${advisor}`
142
237
  }
143
238
 
144
239
  function executorPrompt(c, a, opts) {
@@ -147,9 +242,8 @@ function executorPrompt(c, a, opts) {
147
242
  const standards = a.standards || {}
148
243
  const repoStandards = (standards.repo || []).map(f => ` - ${f}`).join('\n') || ' - none found'
149
244
  const styles = (standards.styles || []).map(f => ` - ${f}`).join('\n') || ' - none found'
150
- const retry = opts && opts.retry
151
- ? '\nThis is a RETRY of a failed attempt — read the error context carefully and correct the root cause.'
152
- : ''
245
+ const retry = opts && opts.retry ? `\n${retryContext(opts.result, a)}` : ''
246
+ const advisor = a.advisor ? `\n\n${ADVISOR_RULE}` : ''
153
247
  return `You are a Step Executor. Implement EXACTLY this component and nothing more.${retry}
154
248
 
155
249
  Component: ${c.name}
@@ -166,16 +260,16 @@ ${repoStandards}
166
260
  Style skills:
167
261
  ${styles}
168
262
 
169
- Rules: Nothing is persisted between runs, so your work may already be done: for \`create\`, read the target first when it exists — if it already fulfils the intent, report success with no change; otherwise complete it, never overwrite it blindly. Smallest coherent change; reuse what already exists in this codebase before writing new code, then prefer stdlib, native platform features, and installed dependencies; touch only the target file and what it strictly needs (its test, an import site); mirror existing naming/exports/layout/tests; follow any local skill or rule; add no new dependency; no abstraction or error handling beyond what the intent requires. Fix mechanical issues you cause (imports, types, lint). STOP and report failed for missing dependencies, unplanned auth/schema/API/contract changes, or unclear product decisions. If verify fails only from pre-existing unrelated issues, report that as a deviation with the exact evidence — do not mark the component failed. Do not make more than three attempts on the same failing issue.
263
+ Rules: Nothing is persisted between runs, so your work may already be done: for \`create\`, read the target first when it exists — if it already fulfils the intent, report success with no change; otherwise complete it, never overwrite it blindly. Smallest coherent change; reuse what already exists in this codebase before writing new code, then prefer stdlib, native platform features, and installed dependencies; touch only the target file and what it strictly needs (its test, an import site); mirror existing naming/exports/layout/tests; follow any local skill or rule; add no new dependency; no abstraction or error handling beyond what the intent requires. Fix mechanical issues you cause (imports, types, lint). When a project file or symbol your component needs does not exist yet, do not create it: STOP and report status blocked with blockedBy — /5:implement reruns you after the next step. STOP and report failed for a missing package, unplanned auth/schema/API/contract changes, or unclear product decisions. If verify fails only from pre-existing unrelated issues, report that as a deviation with the exact evidence — do not mark the component failed. Do not make more than three attempts on the same failing issue.${advisor}
170
264
 
171
265
  Then run: ${verify}
172
266
 
173
- Return structured output: status, filesCreated, filesModified, verify, deviations (none or brief), skipped (none, or what you deliberately did not build — add when ...), error (none or description). Keep it concise — no logs or diffs unless failed.`
267
+ Return structured output: status, blockedBy (only when blocked), filesCreated, filesModified, verify, deviations (none or brief), skipped (none, or what you deliberately did not build — add when ...), error (none or description). Keep it concise — no logs or diffs unless failed.`
174
268
  }
175
269
 
176
270
  function verifyPrompt(a, results) {
177
271
  const ran = results.flatMap(s => s.items.map(i =>
178
- ` step ${s.step} ${i.component.name}: ${i.result ? i.result.status : 'no result'} (verify ${i.result ? i.result.verify : '?'})${i.escalated ? ' [escalated to opus]' : ''}`))
272
+ ` step ${s.step} ${i.component.name}: ${i.result ? i.result.status : 'no result'}${i.result && i.result.blockedBy ? ` by ${i.result.blockedBy}` : ''} (verify ${i.result ? i.result.verify : '?'})${i.escalated ? ' [escalated to opus]' : i.retried ? ' [retried]' : ''}`))
179
273
  const summary = ran.join('\n') || ' (no components ran)'
180
274
  const repoStandards = ((a.standards && a.standards.repo) || []).join(', ') || 'none found'
181
275
  const baseline = (a.baseline && a.baseline.length)
@@ -199,6 +293,80 @@ Checks — only whether the plan was built and works; code quality and correctne
199
293
  Return structured output: status, completeness, infrastructure, acceptanceCriteria ("satisfied/total"), scope, commands[], failures[] (one "drift: {path} — {why}" entry per drift finding).`
200
294
  }
201
295
 
296
+ // The user should be asked as little as possible: "decide" is the exception, "fix" the default.
297
+ const TRIAGE_RULE = `Set an action on every finding:
298
+ - fix: you are confident it is real and the fix is concrete — a bug, a security issue, a breach of a repository standard, a style finding, or a clearly better way to do the same thing (simpler, reuses existing code, more robust). This is the default.
299
+ - decide: ONLY when the right fix depends on a product, API, data, or security trade-off the plan does not settle, or the fix would contradict the plan. Say in reason which decision the user must make.
300
+ - skip: you could not confirm it by reading the code, it is outside these files, or the gain is marginal. Say why in reason.
301
+ Check uncertain findings against the code yourself before choosing; never pass uncertainty on as decide. Give line, severity (error for bugs and security, warning for likely problems, suggestion for improvements), description, and the concrete fix. Do not edit any file.`
302
+
303
+ function reviewScope(a, files) {
304
+ return `Review the changes since commit ${a.fixedPoint || 'HEAD'} in exactly these files — they are uncommitted in the working tree; read untracked ones whole, since git diff omits them:
305
+ ${files.map(f => ` - ${f}`).join('\n')}
306
+ Ignore every other change in the working tree.`
307
+ }
308
+
309
+ function correctnessPrompt(a, files) {
310
+ return `You are a Code Reviewer. ${reviewScope(a, files)}
311
+
312
+ If the built-in code-review skill is available, invoke Skill(skill: "code-review", args: "high") — never with --fix or --comment — and keep only its findings in these files. Otherwise review the diff blind, on its merits: triage files by risk; read full files only for high-risk changes, public API boundaries, security/auth, and data migrations. Report bugs, security, performance, code quality, API design, missing tests, and over-engineering (unnecessary abstractions, single-use indirection, speculative generality, reinventing stdlib or existing dependencies).
313
+
314
+ ${TRIAGE_RULE}`
315
+ }
316
+
317
+ function securityPrompt(a, files) {
318
+ return `You are a Security Reviewer. ${reviewScope(a, files)}
319
+
320
+ If the built-in security-review skill is available, invoke Skill(skill: "security-review") and keep only its findings in these files. Otherwise review them for authentication and authorization gaps, unvalidated input, leaked secrets, weak cryptography, and SQL/shell/path injection. Every security finding has severity error.
321
+
322
+ ${TRIAGE_RULE}`
323
+ }
324
+
325
+ function standardsPrompt(a, files) {
326
+ return `You are a Standards Reviewer. Invoke Skill(skill: "review-style", args: "${a.fixedPoint || 'HEAD'} files: ${files.join(', ')} report only"); if it cannot be invoked, read .claude/skills/review-style/SKILL.md and follow it with the same arguments. Leave out its Suppressed findings. ⛔️ hard breaches of a repository standard are severity error, ⚠️ judgement calls severity suggestion; a judgement call whose fix is clearly better is fix, otherwise skip.
327
+
328
+ ${TRIAGE_RULE}`
329
+ }
330
+
331
+ function flowPrompt(a, files) {
332
+ return `You are a Flow Reviewer. ${reviewScope(a, files)}
333
+
334
+ A diff reviewer reads file by file; you trace behavior ACROSS these files and the states they run in. Read the entry points, then follow each flow end to end:
335
+ - a fresh install with no earlier state: missing directories, files, config, or database rows;
336
+ - an upgrade from the previous version, and an update that stops halfway;
337
+ - the order of operations across files: what is written, uploaded, loaded, or required first, and what breaks when that order changes or one step fails;
338
+ - output, headers, or side effects that happen before guards, error handling, or error suppression are in place;
339
+ - files and helpers the change relies on but does not check, and tests that assert the old order or state.
340
+ Report only failures you can describe as a concrete sequence of states.
341
+
342
+ ${TRIAGE_RULE}`
343
+ }
344
+
345
+ function fixerPrompt(a, file, findings) {
346
+ const list = findings.map(f => ` - ${f.id}${f.line ? ` (line ${f.line})` : ''}: ${f.description} → ${f.fix || 'fix as described'}`).join('\n')
347
+ const dirty = (a.dirty || []).join(', ') || 'none'
348
+ return `You are a Review Fixer. Apply these review findings in ${file}:
349
+ ${list}
350
+
351
+ Read the file first, then apply the fixes from the highest line to the lowest. Touch another file only when a fix strictly needs it (its test, a caller), and never one of these, which hold the user's own uncommitted work: ${dirty}. Make no unrelated change. When reading the code shows a finding's premise is wrong, mark it rejected with the reason — do not ask. Follow the repository standards first, then the style skills. Run the narrowest relevant test or build for the file.
352
+
353
+ Return structured output: one item per finding id (applied, rejected, or failed, with a one-line note) and filesModified.`
354
+ }
355
+
356
+ function checksPrompt(a, files) {
357
+ const baseline = (a.baseline && a.baseline.length)
358
+ ? a.baseline.map(b => ` ${b.command || '?'}: ${b.status}`).join('\n')
359
+ : ' (none recorded)'
360
+ return `You are the final Checks agent. Identify the commands from ${a.paths.config} and, only as needed, the project manifests (package.json, Makefile, pyproject.toml, Cargo.toml, Gradle files). Run every available command in the categories build, test, e2e, and lint; skip a category only when no command exists or it is configured as none.
361
+
362
+ Baseline (pre-change) results — a failure listed here is pre-existing; report it as pre-existing:
363
+ ${baseline}
364
+
365
+ When a command fails because of this run's changes, fix the cause with the smallest change in these files only — ${files.join(', ')} — and rerun it. At most two repair attempts per command. Do not touch any other file.
366
+
367
+ Return structured output: status (passed when every command passed, was skipped, or failed only pre-existing), commands[] with category, command, status, and a one-line summary, and filesModified (repairs only).`
368
+ }
369
+
202
370
  // ── Helpers ──────────────────────────────────────────────────────────────────
203
371
 
204
372
  // Model options per tier. Opus runs at medium effort: deep enough for complex work, cheaper than high.
@@ -206,42 +374,137 @@ function modelOpts(model) {
206
374
  return model === 'opus' ? { model: 'opus', effort: 'medium' } : { model: model || 'haiku' }
207
375
  }
208
376
 
377
+ // A crashed agent (null result) counts as failed: an infra error should not be treated more
378
+ // harshly than a clean structured failure. verify "failed" alone is no retry reason: it can come
379
+ // from pre-existing issues, which the verifier separates using the baseline. "blocked" is no retry
380
+ // reason either: no model can build on a file that does not exist yet, so it waits for the next step.
381
+ function needsRetry(result) {
382
+ return result == null || result.status === 'failed'
383
+ }
384
+
385
+ function isBlocked(item) {
386
+ return !!item.result && item.result.status === 'blocked'
387
+ }
388
+
389
+ // Retries escalate to opus. With the advisor available, the first retry stays on the planned model
390
+ // (at least sonnet) and consults the advisor instead; only the second escalates.
391
+ function retryModel(c, attempt, a) {
392
+ if (!(a.advisor && attempt === 1)) return 'opus'
393
+ return c.model === 'haiku' || !c.model ? 'sonnet' : c.model
394
+ }
395
+
396
+ // Runs one component and retries it up to twice, handing each retry the previous failure.
397
+ async function runComponent(c, a) {
398
+ const run = (model, label, previous) => agent(executorPrompt(c, a, previous),
399
+ { label, phase: 'Execute', ...modelOpts(model), schema: RESULT_SCHEMA }).catch(() => null)
400
+
401
+ // `last` is the latest attempt, null when it crashed; `item.result` keeps the latest structured result.
402
+ let last = await run(c.model, `exec:${c.name}`)
403
+ const item = { component: c, result: last, retried: false, escalated: false }
404
+ for (let attempt = 1; attempt <= 2 && needsRetry(item.result); attempt++) {
405
+ const model = retryModel(c, attempt, a)
406
+ log(`retry ${c.name} (attempt ${attempt + 1}) on ${model || 'haiku'}`)
407
+ item.retried = true
408
+ item.escalated = item.escalated || model === 'opus'
409
+ last = await run(model, `retry:${c.name}`, { retry: true, result: last })
410
+ if (last) item.result = last
411
+ }
412
+ return item
413
+ }
414
+
209
415
  async function runStep(step, components, a) {
210
416
  const stepComps = components.filter(c => step.components.includes(c.name))
211
- if (!stepComps.length) return { step: step.number, name: step.name, mode: step.mode, items: [] }
212
-
213
- let waveResults
214
- if (step.mode === 'parallel' && stepComps.length > 1) {
215
- // Fire every parallel component together — true concurrency, one wave.
216
- waveResults = await parallel(stepComps.map(c => () =>
217
- agent(executorPrompt(c, a), { label: `exec:${c.name}`, phase: 'Execute', ...modelOpts(c.model), schema: RESULT_SCHEMA })
218
- .then(result => ({ component: c, result }))
219
- .catch(() => ({ component: c, result: null }))))
417
+ let items
418
+ if (step.mode === 'parallel') {
419
+ // Fire every parallel component together, retries included — true concurrency, one wave.
420
+ items = await parallel(stepComps.map(c => () => runComponent(c, a)))
220
421
  } else {
221
- waveResults = []
222
- for (const c of stepComps) {
223
- const result = await agent(executorPrompt(c, a), { label: `exec:${c.name}`, phase: 'Execute', ...modelOpts(c.model), schema: RESULT_SCHEMA })
224
- .catch(() => null)
225
- waveResults.push({ component: c, result })
226
- }
422
+ // Sequential components depend on each other, so each one is retried before the next starts.
423
+ items = []
424
+ for (const c of stepComps) items.push(await runComponent(c, a))
227
425
  }
426
+ return { step: step.number, name: step.name, mode: step.mode, items }
427
+ }
428
+
429
+ // Reruns blocked components in place, once the step that should create what they need has run.
430
+ async function rerunBlocked(items, a, afterStep) {
431
+ log(`rerun ${items.length} blocked component(s): ${items.map(i => `${i.component.name} (${i.result.blockedBy || '?'})`).join(', ')}`)
432
+ await parallel(items.map(item => async () => {
433
+ const again = await runComponent(item.component, a)
434
+ if (again.result) item.result = again.result
435
+ item.retried = item.retried || again.retried
436
+ item.escalated = item.escalated || again.escalated
437
+ item.lastTry = afterStep
438
+ }))
439
+ }
440
+
441
+ const stripDot = f => f.replace(/^\.\//, '')
228
442
 
229
- // Retry failed OR crashed (null) components up to twice, escalating to opus.
230
- // A crashed agent (null result) is retried too — an infra error should not be
231
- // treated more harshly than a clean structured failure.
232
- for (const wr of waveResults) {
233
- let attempt = 1
234
- while ((wr.result == null || wr.result.status === 'failed') && attempt <= 2) {
235
- log(`retry ${wr.component.name} (attempt ${attempt + 1}) on opus`)
236
- wr.escalated = true
237
- const retried = await agent(executorPrompt(wr.component, a, { retry: true }),
238
- { label: `retry:${wr.component.name}`, phase: 'Execute', ...modelOpts('opus'), schema: RESULT_SCHEMA }).catch(() => null)
239
- if (retried) wr.result = retried
240
- attempt++
443
+ // Review the run's files, triage the findings, fix every clear one, then rerun build/test/lint.
444
+ async function reviewAndFix(a, plan, allItems, verification, usedOpus) {
445
+ const runFiles = [...new Set(allItems.flatMap(i => [
446
+ i.component.file, i.component.sourceFile,
447
+ ...(i.result ? [...(i.result.filesCreated || []), ...(i.result.filesModified || [])] : [])
448
+ ]).filter(Boolean).map(stripDot))]
449
+ const dirty = new Set((a.dirty || []).map(stripDot))
450
+
451
+ phase('Review')
452
+ const reviewers = [
453
+ { key: 'correctness', prompt: correctnessPrompt, model: 'sonnet' },
454
+ { key: 'standards', prompt: standardsPrompt, model: 'sonnet' }
455
+ ]
456
+ if (plan.securitySensitive) reviewers.push({ key: 'security', prompt: securityPrompt, model: 'sonnet' })
457
+ if (plan.lifecycleSensitive || plan.securitySensitive) reviewers.push({ key: 'flow', prompt: flowPrompt, model: 'opus' })
458
+ const reports = await parallel(reviewers.map(r => () =>
459
+ agent(r.prompt(a, runFiles), { label: `review:${r.key}`, phase: 'Review', ...modelOpts(r.model), schema: FINDINGS_SCHEMA })
460
+ .then(out => out && out.findings.map(f => ({ ...f, reviewer: r.key })))))
461
+ const missing = reviewers.filter((r, n) => !reports[n]).map(r => r.key)
462
+ if (missing.length) log(`reviewer(s) returned nothing: ${missing.join(', ')}`)
463
+
464
+ // Dedup by file and line, keep only the run's files; findings in pre-run dirty files are reported, never fixed.
465
+ const findings = []
466
+ const seen = new Set()
467
+ let outside = 0
468
+ for (const f of reports.filter(Boolean).flat()) {
469
+ const file = stripDot(f.file)
470
+ if (!runFiles.includes(file)) { outside++; continue }
471
+ const key = `${file}:${f.line || 0}`
472
+ if (f.line && seen.has(key)) continue
473
+ seen.add(key)
474
+ const finding = { ...f, file, id: `R${findings.length + 1}` }
475
+ if (dirty.has(file) && finding.action !== 'skip') {
476
+ finding.action = 'report'
477
+ finding.reason = 'pre-run dirty file: may sit in your own earlier work, left untouched'
241
478
  }
479
+ findings.push(finding)
242
480
  }
481
+ if (outside) log(`review: dropped ${outside} finding(s) outside the run's files`)
243
482
 
244
- return { step: step.number, name: step.name, mode: step.mode, items: waveResults }
483
+ phase('Fix')
484
+ const byFile = new Map()
485
+ for (const f of findings.filter(f => f.action === 'fix')) {
486
+ if (!byFile.has(f.file)) byFile.set(f.file, [])
487
+ byFile.get(f.file).push(f)
488
+ }
489
+ const fixModel = plan.securitySensitive ? 'opus' : 'sonnet'
490
+ await parallel([...byFile].map(([file, list]) => async () => {
491
+ const out = await agent(fixerPrompt(a, file, list), { label: `fix:${file}`, phase: 'Fix', ...modelOpts(list.some(f => f.reviewer === 'flow') ? 'opus' : fixModel), schema: FIX_SCHEMA })
492
+ .catch(() => null)
493
+ for (const f of list) {
494
+ const item = out && out.items.find(i => i.id === f.id)
495
+ f.status = item ? item.status : 'failed'
496
+ if (item && item.note) f.note = item.note
497
+ }
498
+ }))
499
+ const applied = findings.filter(f => f.status === 'applied').length
500
+ log(`review: ${findings.length} finding(s), ${applied} fixed, ${findings.filter(f => f.action === 'decide').length} need a decision`)
501
+
502
+ // The inline fast path ran no build/test yet, and applied fixes change what the verifier saw.
503
+ let checks = null
504
+ if (applied || verification.inline) {
505
+ checks = await agent(checksPrompt(a, runFiles), { label: 'checks', phase: 'Fix', ...modelOpts(usedOpus ? 'opus' : 'sonnet'), schema: CHECKS_SCHEMA })
506
+ }
507
+ return { reviewers: reviewers.map(r => r.key), missing, runFiles, findings, checks }
245
508
  }
246
509
 
247
510
  // ── Main ─────────────────────────────────────────────────────────────────────
@@ -254,10 +517,22 @@ const steps = plan.steps
254
517
  const components = plan.pendingComponents
255
518
 
256
519
  phase('Execute')
520
+ // A blocked component waits for the next step, then — if still blocked — for the end of the run.
257
521
  const results = []
258
- for (const step of steps) {
259
- results.push(await runStep(step, components, a))
522
+ let waiting = []
523
+ const late = []
524
+ for (let n = 0; n < steps.length; n++) {
525
+ const r = await runStep(steps[n], components, a)
526
+ results.push(r)
527
+ if (waiting.length) {
528
+ await rerunBlocked(waiting, a, n)
529
+ late.push(...waiting.filter(isBlocked))
530
+ }
531
+ waiting = r.items.filter(isBlocked)
532
+ waiting.forEach(i => { i.lastTry = n })
260
533
  }
534
+ const finalRerun = [...late.filter(i => i.lastTry < steps.length - 1), ...waiting]
535
+ if (finalRerun.length) await rerunBlocked(finalRerun, a, steps.length)
261
536
 
262
537
  phase('Verify')
263
538
  const allItems = results.flatMap(s => s.items)
@@ -265,11 +540,10 @@ const allPassed = allItems.length > 0 && allItems.every(i => i.result && i.resul
265
540
  // Mechanical when every component was planned as haiku and none needed a retry; anything
266
541
  // else signals reasoning-level work that warrants the full verification agent.
267
542
  const usedOpus = components.some(c => c.model === 'opus') || allItems.some(i => i.escalated)
268
- const mechanical = !usedOpus && components.every(c => (c.model || 'haiku') === 'haiku')
543
+ const mechanical = !usedOpus && !allItems.some(i => i.retried) && components.every(c => (c.model || 'haiku') === 'haiku')
269
544
  // Deterministic scope signal: files an executor touched beyond its planned target(s).
270
545
  // Tests and import sites are legitimate, so this is reported for the user, never a failure.
271
546
  const extraFiles = allItems.flatMap(i => {
272
- const stripDot = f => f.replace(/^\.\//, '')
273
547
  const planned = new Set([i.component.file, i.component.sourceFile].filter(Boolean).map(stripDot))
274
548
  const touched = i.result ? [...(i.result.filesCreated || []), ...(i.result.filesModified || [])].map(stripDot) : []
275
549
  return touched.filter(f => !planned.has(f)).map(f => ({ component: i.component.name, file: f }))
@@ -277,8 +551,8 @@ const extraFiles = allItems.flatMap(i => {
277
551
  if (extraFiles.length) log(`scope: ${extraFiles.length} file(s) touched outside planned targets`)
278
552
  let verification
279
553
  if (allPassed && mechanical) {
280
- log('all components passed + mechanical — no verification agent; /5:implement runs build/test and the scope check')
281
- // No shell access here: /5:implement runs build/test and the scope check itself when it sees inline: true.
554
+ log('all components passed + mechanical — no verification agent; the Checks agent runs build/test, /5:implement the scope check')
555
+ // No shell access here: the Checks agent in reviewAndFix runs build/test, /5:implement the scope check, when it sees inline: true.
282
556
  verification = { status: 'passed', completeness: 'passed', infrastructure: 'passed', acceptanceCriteria: 'n/a', commands: [], failures: [], inline: true }
283
557
  } else {
284
558
  verification = await agent(verifyPrompt(a, results), {
@@ -286,7 +560,16 @@ if (allPassed && mechanical) {
286
560
  })
287
561
  }
288
562
 
289
- // Returned to the /5:implement command for the fast-path check, per-step staging, and the report.
563
+ // Reviewing a run that did not build wastes the review: the rerun after the fix reviews again.
564
+ let review = null
565
+ if (verification.status === 'failed') {
566
+ log('verification failed — review and fix skipped')
567
+ } else {
568
+ review = await reviewAndFix(a, plan, allItems, verification, usedOpus)
569
+ }
570
+ const checksPassed = !review || !review.checks || review.checks.status === 'passed'
571
+
572
+ // Returned to the /5:implement command for the findings file, the decisions, the scope check, per-step staging, and the report.
290
573
  return {
291
574
  feature: a.feature,
292
575
  steps,
@@ -295,9 +578,10 @@ return {
295
578
  step: s.step,
296
579
  name: s.name,
297
580
  mode: s.mode,
298
- items: s.items.map(i => ({ component: i.component.name, file: i.component.file, sourceFile: i.component.sourceFile, escalated: !!i.escalated, result: i.result }))
581
+ items: s.items.map(i => ({ component: i.component.name, file: i.component.file, sourceFile: i.component.sourceFile, retried: i.retried, escalated: i.escalated, result: i.result }))
299
582
  })),
300
583
  verification,
301
584
  extraFiles,
302
- status: verification.status === 'passed' ? 'completed' : 'failed'
585
+ review,
586
+ status: verification.status === 'passed' && checksPassed ? 'completed' : 'failed'
303
587
  }