pi-plans 0.8.0 → 0.8.2

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
@@ -137,7 +137,7 @@ Planning artifacts live under `./.git/pi-plans/plans/YYYY-MM-DD-<topic>/` by def
137
137
  | Visible Refiner overlay | Delegated reviewer subagents surface as a named public overlay in the TUI — one `Reviewer` panel with per-lane tool progress, full streaming transcript with follow-bottom scroll, Tab-pane focus, retention until the user presses `Esc` after completion, and clean cancelled/timed-out vs completed states. `reviewers: 3` renders three equal-height panes inside the same overlay |
138
138
  | Tracked execution | The current wave and remaining tasks are injected each turn; task progress is reported exclusively through the `plans_update_task` tool (status + evidence / skipReason, audit-only rollback); the task dashboard shows the tree live (compact aboveEditor widget, Ctrl+Shift+T expanded view with ✓/▸/~/· markers, width-adaptive); a stall watchdog pauses after three settled rounds without task-state change; the status bar shows lifecycle, `x/y` task progress, elapsed time, and token usage in real time |
139
139
  | Multi-run workdirs (0.6.0) | Several pi sessions can plan concurrently in one workdir: the run registry derives from `runs/` (no shared pointer to race), each session binds to its run, and same-topic runs get suffixed artifact dirs. `/plans-abandon`, `/plans-execute`, and `/resume-plans` are binding-first and open a descriptive run-picker form when more than one candidate exists; `/plans` lists all runs (newest first, bound run marked) |
140
- | Execution reviewer | When every task reaches a terminal state, the run status moves to `verifying` and an independent read-only reviewer verifies each `VC-###` check in a detached, overlay-visible round (Esc closes; Ctrl+Shift+R reopens the in-flight round); failed checks roll their covered tasks (children cascade, skipped reopen) back to pending and inject the review report; five committed rounds bound the loop — exhaustion pauses in every mode, and only an explicit `/plans-execute` confirmation grants a fresh budget (ordinary input and restores never refill). Checks with all-skipped coverage pass; checks covering no task never audit |
140
+ | Execution reviewer | When every task reaches a terminal state, the run status moves to `verifying` and an independent read-only reviewer verifies each `VC-###` check AND reports severity-graded `F-###` findings over the whole implemented change in a detached, overlay-visible round (Esc closes; Ctrl+Shift+R reopens the in-flight round). Finding ids are stable across rounds (absence from the newest report = resolved). A failed check or a high-severity finding opens one union fix round: mapped tasks roll back to pending (children cascade, skipped reopen; an unmapped high gets a plan task appended mechanically from the reviewer's proposed title), and the executor is woken exactly once with a findings summary plus the round-report path. The run completes when every check is affirmatively `pass` and no high finding remains; residual medium/low findings are summarized at completion, and an exhausted budget completes with any unresolved high findings disclosed by id. The review budget is a per-run choice (1/2/3/5/unlimited, default 3) asked exactly once — when every task is terminal, right before round 1 — and stored in the checkpoint: a numeric budget bounds committed rounds, while `unlimited` runs until no high finding remains behind a no-progress valve (three consecutive identical outcomes) and a run-cumulative hard cap of 50 committed rounds. Exhaustion pauses in every mode, and only an explicit `/plans-execute` confirmation re-opens the budget picker and grants a fresh budget (unresolved findings survive the renewal; ordinary input and restores never refill). Checks with all-skipped coverage pass; checks covering no task never audit |
141
141
  | Execution handoff | The accepted plan executes in the current session after explicit approval (never auto-completed); legacy `I-###` plans parse through the compatibility mapping with an upgrade notice; 0.6.0 in-flight runs resume compatibly (delegated-executor orphans re-approve, paused executions rebuild from the task tree) |
142
142
  | Execution-phase compaction | Pi core owns scheduling; pi-plans maps the active plan path, current task, task ids, and remaining `VC-###` checks into the VCC sections. Proactive triggers and model-generated summary paths are removed. |
143
143
  | Planning-phase compaction | During `run.status=planning` with no active execution, pi-plans maps active run, artifact directory, latest plan path from session entries, and observed current-I markers into the VCC sections. Without an active planning run, compaction returns to Pi core. Additionally, creating a new run (`plans start-run`) proactively requests one pre-plan VCC compaction and resumes planning with a hidden message (default on; `prePlanCompact:false` disables). |
@@ -310,7 +310,7 @@ The plan is the contract. Refinement converges on scope while nothing is writabl
310
310
 
311
311
  **What can Auto-complete decide on my behalf?**
312
312
 
313
- Planning and refinement choices only (the recommended option). Choosing Auto-complete enables the recommended answer for later eligible planning questions in the current run and the extension continues the planning turn when the model stops early. Use `/plans-autocomplete-stop` to take back control. It is never offered for execution approval, installs, publishing, deployment, merge, push, or credentials — those questions stop and wait for you. After execution completes, the independent execution reviewer verifies every check; the five-round budget pauses the run for review in every mode when exhausted, and only an explicit `/plans-execute` confirmation grants a fresh budget.
313
+ Planning and refinement choices only (the recommended option). Choosing Auto-complete enables the recommended answer for later eligible planning questions in the current run and the extension continues the planning turn when the model stops early. Use `/plans-autocomplete-stop` to take back control. It is never offered for execution approval, installs, publishing, deployment, merge, push, or credentials — those questions stop and wait for you. After execution completes, the independent execution reviewer verifies every check; the per-run review budget (1/2/3/5/unlimited, default 3, chosen when the task tree first goes terminal) pauses the run for review in every mode when exhausted, and only an explicit `/plans-execute` confirmation re-opens the budget picker and grants a fresh budget.
314
314
 
315
315
  **Where does all the state live?**
316
316
 
@@ -1,32 +1,41 @@
1
1
  ---
2
2
  name: pi-plans-execution-reviewer
3
- description: Read-only execution reviewer for pi-plans; verifies an implemented worktree against the plan's verification checks and returns a tri-state verdict per check.
3
+ description: Read-only execution reviewer for pi-plans; verifies an implemented worktree against the plan's verification checks and reports severity-graded implementation findings that drive the fix loop.
4
4
  tools: read, grep, find, ls
5
5
  ---
6
6
 
7
- You are the execution reviewer in the pi-plans workflow. Your job is to decide
8
- whether an already-implemented worktree satisfies the verification checks of an
9
- accepted plan.
7
+ You are the execution reviewer in the pi-plans workflow. Each review round has
8
+ two jobs: decide whether an already-implemented worktree satisfies the
9
+ verification checks of an accepted plan, and report implementation findings —
10
+ defects you can point at in the repository — that the executor will fix before
11
+ the next round. A round is useful only when both outputs are present.
10
12
 
11
13
  Rules:
12
14
 
13
15
  - Perform read-only analysis. Never edit, write, or delete any file, never commit, never push, never spawn subagents.
14
16
  - Verify against the actual repository using your read tools before judging. A check passes only on evidence you actually inspected.
15
17
  - You are auditing a worktree that is already written. "The file is missing" is a finding to report, not a reason to stay silent.
16
- - You do not fix anything and you do not propose follow-up work. Your only output is a verdict per check.
18
+ - You do not fix anything. You report verdicts and findings; the fix loop acts on them.
17
19
 
18
20
  ## Output contract
19
21
 
20
- Output Markdown with exactly one section per check, in the order given by the
21
- brief:
22
+ Output exactly two sections, in this order.
23
+
24
+ ### 1. Verification verdicts
25
+
26
+ One section per check, in the order given by the brief. The preferred shape
27
+ puts the id and the verdict on one line (the runner reads this form first):
22
28
 
23
29
  - `VC-###` — verdict: pass | fail | undeterminable; evidence: <repo path/command or recorded output proving it>; note: <one line>.
24
30
 
31
+ A heading-style section is also read: start it with the id (`### VC-###` or a
32
+ bullet that names the check) and keep that check's `verdict:` line inside the
33
+ section. Whichever form you choose, use ONE form for the whole report and
34
+ never let one check's verdict drift into another's section.
35
+
25
36
  Emit **every** check the brief lists, in the brief's order. Never omit a check,
26
37
  never merge two checks into one section, never invent a check that is not listed.
27
38
 
28
- ## Choosing the verdict
29
-
30
39
  - `pass` — you inspected the evidence and it establishes the check's condition.
31
40
  - `fail` — you inspected the evidence and the check's condition is **demonstrably** not met. Use this only when you can point at the specific thing that breaks the condition.
32
41
  - `undeterminable` — you could **not** reach a conclusion. Use this whenever the evidence is missing, unreadable, ambiguous, or beyond what your read-only tools can reach.
@@ -37,4 +46,47 @@ yours, and reporting it honestly is strictly better than guessing.
37
46
  **Never report `fail` for want of evidence.** "I could not find it" is
38
47
  `undeterminable`, not `fail`. Collapsing the two turns a tooling gap into an
39
48
  accusation of incorrect work, and the runner acts on that accusation — it rolls
40
- the covered tasks back and reopens work that may be perfectly fine.
49
+ the covered tasks back and reopens work that may be perfectly fine.
50
+
51
+ ### 2. Implementation findings
52
+
53
+ Report defects anywhere in the implemented work — not only what the checks
54
+ cover. Scope is the whole change the plan drove, judged against the plan's
55
+ intent. If you find nothing worth reporting, emit exactly `- none.` under the
56
+ heading and stop.
57
+
58
+ One bullet per finding, exact line grammar (field order is fixed; fields are
59
+ separated by `; `):
60
+
61
+ - `F-###` — severity: high | medium | low; tasks: Task-N, Task-M | none; proposed-task: <imperative one-line title>; note: <one line>; evidence: <repo path or command output proving it>
62
+
63
+ Rules for the fields:
64
+
65
+ - `F-###` — a stable id. The brief lists the previous round's unresolved
66
+ findings: when a listed problem is still present, **reuse its id verbatim**
67
+ and do not renumber. A problem is resolved only by no longer reporting it.
68
+ Brand-new problems take the next unused number after the highest id you have
69
+ seen (in the brief or in this report).
70
+ - `severity` — `high` blocks completion and wakes the executor for a fix
71
+ round; `medium` and `low` are recorded and summarized at completion. Grade
72
+ by consequence: `high` = correctness, data loss, security, broken promised
73
+ behavior, or a verification check that is demonstrably unmet. `medium` =
74
+ should be fixed, but the plan's promised behavior still holds without it.
75
+ `low` = polish, naming, comments, minor drift. Do not inflate; do not
76
+ downgrade a real `high` to avoid waking the executor.
77
+ - `tasks` — the task id(s) whose work is defective, comma-separated, or
78
+ `none` when no existing task owns the defect. Only use ids from the brief's
79
+ task list. A `high` finding with `tasks: none` must carry a
80
+ `proposed-task:` field (below); the runner appends that task to the plan
81
+ mechanically, so write it as a self-contained imperative title (e.g.
82
+ `cap retry backoff at 60s in src/client.ts`). Omit `proposed-task:` for
83
+ mapped findings and for `medium`/`low`.
84
+ - `note` — one line: what is wrong and what breaks.
85
+ - `evidence` — a repository path (with line anchor when useful) or a short
86
+ quoted excerpt that an executor with read tools can re-inspect. A source
87
+ path plus a defect argument is sufficient; you have no execution tools, so
88
+ never fabricate command output.
89
+
90
+ Every reported defect must have a bullet. Never fold two defects into one
91
+ bullet; never mention a defect in prose without a bullet — findings outside
92
+ the grammar are invisible to the runner.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-plans",
3
- "version": "0.8.0",
3
+ "version": "0.8.2",
4
4
  "description": "Human-in-the-loop planning extension for the Pi coding agent: researched, refined Markdown plans before any code changes.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -41,7 +41,7 @@
41
41
  "README.md",
42
42
  "LICENSE",
43
43
  "CONTRIBUTING.md",
44
- "AGENTS.md",
44
+ "AGENTS.md",
45
45
  "index.ts",
46
46
  "agents/",
47
47
  "docs/assets",
@@ -131,15 +131,20 @@ When the user picks `✓ Accept PLAN_vN and execute it now` in the merged questi
131
131
 
132
132
  - every agent turn is injected with the current wave's open tasks, the remaining task list, verification-check summary, and execution rules (wave order, `plans_update_task` reporting with status + evidence / skipReason, subprocess polling backoff 5s -> 10s -> 20s -> 40s -> 80s then keep polling at 80s, no stopgaps, dependency and library discipline, minimum tests);
133
133
  - task progress flows exclusively through the `plans_update_task` tool: one call per task closing it as `complete` (with evidence) or `skipped` (with skipReason); closed statuses are immutable outside the audit-authorized rollback channel; subtasks close before their parent;
134
- - the task dashboard tracks the whole tree live: a compact aboveEditor widget (current task ▸, progress bar, ✓/· counts, VC pass count, wave indicator, pause state, audit-outcome line) and the Ctrl+Shift+T expanded tree view (✓/▸/~/·/↺ markers, current-task anchor, VC list with audit state, width-adaptive layout). `↺` marks a task that was completed and then rolled back by a failed audit: it is open again but still shows the evidence from its previous attempt;
135
- - a stall watchdog pauses execution after three consecutive settled rounds without any task-status change (genuine user input or `/plans-execute` resumes without losing progress). A round in which the agent ran successful tool calls counts as progress even with no status change, so investigating the codebase is never mistaken for a dead agent;
134
+ - the task dashboard tracks the whole tree live: a compact aboveEditor widget (current task ▸, progress bar, ✓/· counts, VC pass count, wave indicator, pause state, audit-outcome line, unresolved-findings line visible in both the repairing and verifying phases, and a `⊘ blocked` row naming the open rolled-back tasks while the review is blocked) and the Ctrl+Shift+T expanded tree view (✓/▸/~/·/↺ markers, current-task anchor, VC list with audit state, width-adaptive layout). `↺` marks a task that was completed and then rolled back by a failed audit: it is open again but still shows the evidence from its previous attempt;
135
+ - while a failed round's reopened tasks are still open, the wake message states explicitly that NO review round is running (the tree is not terminal, so the review cannot start) and carries a `BLOCKED` block naming every open rolled-back task, its provenance (`reopened by round N`), and the required `plans_update_task` action — closing a task's children does not close the task itself. The blocker is persisted in the checkpoint (`execution.blocked`), so the pause reason, the dashboard row, and the `/resume-plans` brief can name it after a restart;
136
+ - a stall watchdog pauses execution after three consecutive settled rounds without any task-status change (genuine user input or `/plans-execute` resumes without losing progress). A round in which the agent ran successful tool calls counts as progress even with no status change, so investigating the codebase is never mistaken for a dead agent. Blocked raises escalate on their OWN ladder (`execution.blocked.escalatedRounds`, which tool activity does not reset but which DOES reset to zero whenever the blocker set shrinks — closing one reopened task per settled round is progress, never a reason to harden or pause): the wake wording hardens on each consecutive no-progress blocked wake, ONE visible `pi-plans-exec-blocked` system line is emitted per escalation level, and the third consecutive no-progress blocked wake pauses the run with the blocker as the reason (`blocked: review round N cannot start — …`) instead of the watchdog's own metric. A resume (ordinary input or `/plans-execute`) grants a fresh blocked ladder without refilling the review budget;
136
137
  - when every task reaches a terminal state, the run status moves to `verifying` and an independent read-only execution reviewer (`agents/execution-reviewer.md`) verifies each check against the worktree in a detached round whose progress renders in a dedicated overlay (Esc closes it; Ctrl+Shift+R reopens the in-flight round). Each check gets one of three verdicts:
137
138
  - `pass` — the evidence establishes the check's condition;
138
139
  - `fail` — the condition is demonstrably not met; the covered tasks roll back to pending (children cascade, skipped tasks reopen, the `evidence` of the previous attempt is retained while `skipReason` is cleared) and the audit report is injected;
139
- - `undeterminable` — the reviewer could not reach a conclusion. This is never a failure and never a completion: nothing rolls back, the loop self-schedules the retry (no agent wake), and each retry counts toward the five-round budget.
140
-
141
- The run completes only when every pending check is affirmatively `pass`. A partial round credits the checks that passed and leaves the rest for the next round. Checks whose covered tasks are all skipped pass as skipped-pass; checks covering no task never enter the audit; checks already satisfied in an earlier round are neither re-briefed nor re-judged;
142
- - the round budget is five COMMITTED rounds (pass, fail, or undeterminable; discarded fingerprint-mismatch attempts and cancellations burn nothing; two consecutive discards commit as one undeterminable round). Exhaustion pauses the run in EVERY mode — interactive and auto-approve/headless alike — with an in-band `pi-plans-review-paused` message; ordinary user input and session restores never lift the pause or refill the budget. The only fresh-budget surface is `/plans-execute`, whose explicit confirmation grants five more rounds. The watchdog counter is rebased by real tool activity;
140
+ - `undeterminable` — the reviewer could not reach a conclusion. This is never a failure and never a completion: nothing rolls back, the loop self-schedules the retry (no agent wake), and each retry counts as a committed round against the run's review budget. An all-undeterminable round that also reports a high-severity finding still wakes the executor — a finding is actionable independent of verdict evidence;
141
+ - `F-###` findings — every round also reports severity-graded implementation findings (`high | medium | low`) over the whole implemented change, not just what the checks cover. Ids are stable: the brief lists the previous round's unresolved findings and the reviewer reuses their ids verbatim while the problem persists; absence from the newest round's report is the resolution signal. A `high` finding (or a `fail` verdict) opens ONE union fix round: mapped tasks roll back to pending exactly like a failed check's coverage (children cascade, evidence retained), and a `high` whose `tasks: none` names no owner gets a plan task appended mechanically from the reviewer's `proposed-task` title — the reviewer itself stays read-only. The executor is woken exactly once with a findings summary plus the round-report path. A pure finding-driven rollback deliberately keeps earlier VC passes (the findings channel re-examines the repaired work next round); only a `fail`-driven rollback invalidates the checks covering the reopened tasks. Unresolved findings persist across checkpoint restores, session restores, and fresh budget grants.
142
+
143
+ The run completes only when every pending check is affirmatively `pass` AND the newest round reports no high-severity finding; residual `medium`/`low` findings are summarized in the completion message and stay recorded in the round reports. A partial round credits the checks that passed and leaves the rest for the next round. Checks whose covered tasks are all skipped pass as skipped-pass; checks covering no task never enter the audit; checks already satisfied in an earlier round are neither re-briefed nor re-judged;
144
+ - the round budget is a PER-RUN choice, resolved exactly once — right before round 1, when every task is terminal and the review is genuinely owed. An interactive session shows the budget panel (1 / 2 / 3 / 5 / unlimited, preselected on a re-pick); every other case (no UI, headless/print/json, auto-approve, RPC without menus) applies the default 3 with one visible note, and the checkpoint records `reviewBudgetDefaulted` so the dashboard and the resume brief mark it `(default)`. The value lives in the run checkpoint (`execution.reviewBudget`), never in the plan file, and picking is never a per-round question;
145
+ - a numeric budget counts COMMITTED rounds (pass, fail, or undeterminable; discarded fingerprint-mismatch attempts and cancellations burn nothing; two consecutive discards commit as one undeterminable round) and resets per grant;
146
+ - `unlimited` runs until no high finding remains, guarded by two valves: the no-progress valve pauses after three consecutive committed rounds with an identical outcome signature (sorted failed checks + undeterminable checks + high-finding ids, so a round that never produces a report — spawn failure or discard synthesis — still counts), and a run-cumulative hard cap of 50 committed rounds (`execution.reviewRoundsTotal`, never reset) pauses the run. An explicit `/plans-execute` grant that lands on `unlimited` lifts the hard cap by another 50 rounds (`execution.reviewCapExtension`);
147
+ - exhaustion pauses the run in EVERY mode — interactive and auto-approve/headless alike — with an in-band `pi-plans-review-paused` message naming the real budget, EXCEPT when every verification check is already satisfied: then the run completes even with unresolved high findings, which the completion message discloses by id (the findings stay in the round reports and the checkpoint). Ordinary user input and session restores never lift a pause or refill the budget. The only fresh-budget surface is `/plans-execute`: its confirmation re-opens the budget panel with the current value preselected and resets the per-grant round counter, the no-progress valve, and (only for an `unlimited` pick) extends the hard cap; Esc keeps the run paused. A pre-feature checkpoint that already spent rounds keeps its legacy bound of five committed rounds instead of being cut to the new default mid-flight. The watchdog counter is rebased by real tool activity;
143
148
  - execution-phase compaction is handled only when Pi core emits manual `/compact`, threshold, or overflow events; summaries are deterministic VCC-style summaries, include session-derived plan/current-task/checklist context, use smart tail keep and `keep:N`, and never call a model;
144
149
  - the read-only guard lifts: full write access returns;
145
150
  - the run status moves to `executing`, then `verifying` while the review loop owns the run, then `done` when every check passes (a failed round rolls its tasks back and returns the run to `executing` for repair);
@@ -156,8 +161,11 @@ session is idle, and neither pending input nor compaction owns continuation.
156
161
  Each eligible settled cycle can send at most one hidden custom message with
157
162
  the current execution rules. Tool `turn_end` events only update usage; they
158
163
  never prequeue continuation reminders. The stall watchdog counts settled
159
- cycles without task-state change (threshold 3) and pauses instead of waking;
160
- user interruption and final model errors pause too. Genuine interactive/RPC
164
+ cycles without task-state change (threshold 3); while a rolled-back blocker
165
+ keeps the review from starting, the blocked ladder escalates the wake first
166
+ (naming the open tasks and stating that no review round is running) and only
167
+ its third consecutive raise pauses — a blocked pause names the blocker rather
168
+ than the watchdog metric. User interruption and final model errors pause too. Genuine interactive/RPC
161
169
  user input or `/plans-execute` resumes a paused active execution without
162
170
  losing task progress; extension input cannot unpause it. New-plan handoffs
163
171
  and the `execute_plan` tool still require explicit approval. Print/JSON
@@ -203,11 +203,11 @@ One run directory per planning request: `<git-common-dir>/pi-plans/runs/<YYYYMMD
203
203
 
204
204
  ## Workflow Checkpoints (`/resume-plans`)
205
205
 
206
- Each run may carry a `checkpoint.json` — the durable, cross-session workflow state that `/resume-plans` restores in the current session. It records: logical `phase` (`planning | reviewing | executing | completed`; the legacy 0.6.0 `implementation-review` phase is read-tolerated and maps to done), `nextAction`, the exact plan identity (path + version + SHA-256), pending/answered questions (stable `questionId`), review rounds with per-lane status and result-file references, execution approval evidence (plan digest, worktree, `git revparse HEAD` at approval, task progress map, audit rounds with the failed and undeterminable check sets, the watchdog budget counter, verified VC set, usage), and ownership metadata. Full review outputs live in separate `reviews/` files; the checkpoint keeps only validated references.
206
+ Each run may carry a `checkpoint.json` — the durable, cross-session workflow state that `/resume-plans` restores in the current session. It records: logical `phase` (`planning | reviewing | executing | completed`; the legacy 0.6.0 `implementation-review` phase is read-tolerated and maps to done), `nextAction`, the exact plan identity (path + version + SHA-256), pending/answered questions (stable `questionId`), review rounds with per-lane status and result-file references, execution approval evidence (plan digest, worktree, `git revparse HEAD` at approval, task progress map, audit rounds with the failed and undeterminable check sets plus the unresolved findings of the newest committed round, the watchdog budget counter, verified VC set, usage), and ownership metadata. Full review outputs live in separate `reviews/` files; the checkpoint keeps only validated references.
207
207
 
208
208
  Rules:
209
209
 
210
- - Validation is explicit: unknown schema versions, malformed shapes, and unexpected keys are rejected; missing and corrupt checkpoints are distinct, and corrupt files are never silently overwritten. Keys added by a later version (`execution.stallRounds`, `execution.audit.undeterminable`) are optional on read, so checkpoints written before them keep loading.
210
+ - Validation is explicit: unknown schema versions, malformed shapes, and unexpected keys are rejected; missing and corrupt checkpoints are distinct, and corrupt files are never silently overwritten. Keys added by a later version (`execution.stallRounds`, `execution.blocked`, `execution.reviewBudget`, `execution.reviewBudgetDefaulted`, `execution.reviewRoundsTotal`, `execution.reviewCapExtension`, `execution.reviewNoProgress`, `execution.audit.undeterminable`, `execution.audit.findings`, `execution.planAmended`) are optional on read, so checkpoints written before them keep loading. `execution.planAmended` is set when the review loop mechanically appended finding tasks to the approved plan; the checkpoint's plan identity was re-stamped to the amended digest at that moment while the approval record keeps the original. `execution.blocked` (`{ rolledBack, tasks, round, escalatedRounds, since }`) records the newest failed round's rollback set — captured when the round commits, because the reopen helpers mutate the task tree and report only flipped nodes — plus the still-open tasks among it; it drives the `BLOCKED` wake block, the blocked escalation ladder, the pause reason, the dashboard row, and the resume brief. It is deleted (not left stale) when the last blocker closes, when the run stops, and when the audit passes. `execution.reviewBudget` is the per-run execution-review budget: a positive integer round count or the literal `"unlimited"` (absent = not chosen yet, or written by a pre-0.9.3 build — a checkpoint that already spent rounds resolves to the legacy bound of five). `execution.reviewBudgetDefaulted` marks a budget that came from the no-UI fallback rather than a user pick (the dashboard and resume brief annotate it `(default)`). `execution.reviewRoundsTotal` counts committed review rounds across the whole run and never resets; together with `execution.reviewCapExtension` (lifted by 50 rounds on every explicit `/plans-execute` grant that lands on `unlimited`) it bounds the `unlimited` budget with a run-cumulative hard cap. `execution.reviewNoProgress` (`{ key, streak }`) is the unlimited budget's no-progress valve state: the signature of the newest committed round's outcome (sorted failed checks + undeterminable checks + high-finding ids) plus its consecutive-run count. All five keys are dropped by a stop and by completion (a migration carries them, since they describe the user's choice and the run's spend, not the invalidated code state).
211
211
  - Writes are atomic with monotonic revisions; writers may require ownership (token + generation) or an expected revision.
212
212
  - Model-driven boundaries (plan written, review consolidated, termination condition recorded, implementation round finished, completed) go through the whitelisted `plans record-checkpoint` action, which enforces state-machine preconditions — it cannot set execution approval, mark VCs passed, or forge terminal states.
213
213
  - `ask_choice` accepts `questionId`/`purpose`; a pending question is durable before the panel opens and the answer before it returns. When a crash leaves a question both answered (ledger) and pending (checkpoint), the answered entry wins.
package/src/auditor.ts CHANGED
@@ -3,20 +3,27 @@
3
3
  * reaches a terminal state, an independent read-only subagent verifies the
4
4
  * plan's verification checks against the worktree. Failed checks roll their
5
5
  * covered tasks back to pending (exclusively inside the review flow). The
6
- * loop is bounded at REVIEW_MAX_ROUNDS committed rounds; exhaustion pauses
7
- * the run for the user in every mode (fail-closed, never a hang and never a
8
- * silent stop) — only an explicit /plans-execute confirmation grants a fresh
9
- * budget.
6
+ * loop is bounded by the per-run review budget (v0.9.3: `ReviewBudget` in
7
+ * ./review-budget.ts, chosen right before round 1 and stored in the run
8
+ * checkpoint); exhaustion pauses the run for the user in every mode
9
+ * (fail-closed, never a hang and never a silent stop) — only an explicit
10
+ * /plans-execute confirmation grants a fresh budget.
10
11
  */
11
12
 
12
13
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
13
14
  import * as fs from "node:fs";
14
15
  import * as path from "node:path";
15
- import { auditableChecks, skippedPassCheckIds, type TaskView } from "./tasks.ts";
16
- import type { CheckItem } from "./plan.ts";
16
+ import { auditableChecks, flattenTaskViews, skippedPassCheckIds, type TaskView } from "./tasks.ts";
17
+ import { normalizeTaskId, type CheckItem } from "./plan.ts";
17
18
  import { messaging } from "./messaging.ts";
18
19
 
19
- /** Budget cap: committed rounds per user-granted budget. Discarded (fingerprint-changed) attempts do not count. */
20
+ /** Legacy fixed cap (v0.8–v0.9.2): the review-round budget is now a per-run
21
+ * choice (`ReviewBudget` in ./review-budget.ts, default 3, pickable 1/2/3/5/
22
+ * unlimited). This constant survives ONLY for checkpoints and tests written
23
+ * against the old fixed budget — a pre-feature checkpoint that already spent
24
+ * rounds keeps the 5-round bound (`LEGACY_REVIEW_MAX_ROUNDS`). It no longer
25
+ * gates any round.
26
+ * @deprecated use `resolveStoredBudget` / `budgetExhausted` from ./review-budget.ts */
20
27
  export const REVIEW_MAX_ROUNDS = 5;
21
28
 
22
29
  /** Legacy alias for one release: checkpoints and old builds still know this name. */
@@ -29,9 +36,36 @@ export interface AuditOutcome {
29
36
  /** Checks whose report carried no readable verdict, or whose evidence was
30
37
  * inconclusive. Never treated as `failed`: see src/exec.ts. */
31
38
  undeterminable: string[];
39
+ /** Severity-graded implementation findings from this round (v0.9). Absent
40
+ * on legacy shapes means "no findings reported"; the parse boundary always
41
+ * sets a concrete array so hand-written construction sites cannot silently
42
+ * drop them. */
43
+ findings?: ReviewFinding[];
32
44
  report: string;
33
45
  }
34
46
 
47
+ /** Severity vocabulary for implementation findings; mirrors the plan
48
+ * priority words. `malformed` marks a bullet the grammar parser could not
49
+ * read — it is recorded and displayed but never drives a rollback. */
50
+ export type FindingSeverity = "high" | "medium" | "low" | "malformed";
51
+
52
+ export interface ReviewFinding {
53
+ /** Stable id, normalized uppercase (`F-001`). Reused verbatim across
54
+ * rounds while the problem persists; absence from the newest round's
55
+ * report is the resolution signal. */
56
+ id: string;
57
+ severity: FindingSeverity;
58
+ /** Task ids owning the defect (normalized), `[]` when unmapped. */
59
+ taskIds: string[];
60
+ /** Required for unmapped high findings: the runner appends this as a new
61
+ * plan task mechanically, so it must be a self-contained imperative title. */
62
+ proposedTask?: string;
63
+ note: string;
64
+ evidence: string;
65
+ /** Original bullet, for degraded records and round reports. */
66
+ raw: string;
67
+ }
68
+
35
69
  /** Parse the verdict lines of an audit report against the checks that are
36
70
  * still pending. A pending check with no readable verdict is
37
71
  * `undeterminable`, never `failed` — the caller must be able to tell "the
@@ -40,6 +74,58 @@ export interface ParsedAudit {
40
74
  passed: string[];
41
75
  failed: string[];
42
76
  undeterminable: string[];
77
+ findings: ReviewFinding[];
78
+ }
79
+
80
+ /** One finding bullet's field-capture helper: lazily up to the next
81
+ * `; <known-field>:` boundary or the end of the line, so free text in one
82
+ * field cannot swallow the next. */
83
+ function captureField(line: string, field: string): string | undefined {
84
+ const m = line.match(new RegExp(`${field}:\\s*(.*?)(?=;\\s*(?:severity|tasks|proposed-task|note|evidence):|$)`, "i"));
85
+ return m ? m[1].trim().replace(/^[*_`~]+|[*_`~]+$/g, "") : undefined;
86
+ }
87
+
88
+ /** Parse the findings bullets of a review report. Degrade, never crash, never
89
+ * roll back: a bullet with an F-### id but unreadable fields is recorded with
90
+ * severity "malformed" (visible, non-blocking), exactly like the verdict
91
+ * parser's emphasis tolerance — a strict grammar once silently discarded
92
+ * verdicts and fail-closed rolled correct work back. */
93
+ export function parseFindings(report: string, knownTaskIds?: Set<string>): ReviewFinding[] {
94
+ const findings: ReviewFinding[] = [];
95
+ const seen = new Set<string>();
96
+ for (const match of report.matchAll(/^\s*[-*]\s+`?(F-\d+)`?\b/gim)) {
97
+ const id = match[1].toUpperCase();
98
+ if (seen.has(id)) continue; // conflicting duplicates resolve to the first
99
+ seen.add(id);
100
+ // The bullet regex's leading \s* may swallow the preceding newline, so
101
+ // slice(index) can start mid-whitespace; strip it before taking the line.
102
+ const line = match.input!.slice(match.index!).replace(/^[\s]+/, "").split(/\n/)[0];
103
+ const severityRaw = captureField(line, "severity")?.toLowerCase();
104
+ const tasksRaw = captureField(line, "tasks");
105
+ const taskIds = (tasksRaw ?? "")
106
+ .split(/[,,,、]/)
107
+ .map((token) => normalizeTaskId(token.trim()))
108
+ .filter((t): t is string => t !== null)
109
+ .filter((t) => !knownTaskIds || knownTaskIds.has(t));
110
+ const severity: FindingSeverity =
111
+ severityRaw === "high" || severityRaw === "medium" || severityRaw === "low" ? severityRaw : "malformed";
112
+ if (severity === "malformed" || !tasksRaw) {
113
+ // Unreadable severity, or the grammar's mandatory tasks field missing:
114
+ // degrade to a recorded non-blocking entry.
115
+ findings.push({ id, severity: "malformed", taskIds: [], note: captureField(line, "note") ?? line.trim(), evidence: captureField(line, "evidence") ?? "", raw: line.trim() });
116
+ continue;
117
+ }
118
+ findings.push({
119
+ id,
120
+ severity,
121
+ taskIds,
122
+ proposedTask: captureField(line, "proposed-task") || undefined,
123
+ note: captureField(line, "note") ?? "",
124
+ evidence: captureField(line, "evidence") ?? "",
125
+ raw: line.trim(),
126
+ });
127
+ }
128
+ return findings;
43
129
  }
44
130
 
45
131
  /** Checks this round must judge: auditable (covering at least one task) and
@@ -51,13 +137,27 @@ export function auditablePendingChecks(checklist: CheckItem[], tasks: TaskView[]
51
137
  }
52
138
 
53
139
  /** Build the audit brief for the read-only subagent. Exported for tests. */
54
- export function buildAuditTask(planPath: string, checklist: CheckItem[], tasks: TaskView[], round: number): string {
140
+ export function buildAuditTask(
141
+ planPath: string,
142
+ checklist: CheckItem[],
143
+ tasks: TaskView[],
144
+ round: number,
145
+ priorFindings: ReviewFinding[] = [],
146
+ ): string {
55
147
  const checks = auditablePendingChecks(checklist, tasks)
56
148
  .map((check) => `- \`${check.id}\`: ${check.text}`)
57
149
  .join("\n");
58
- return `Goal: verify that the implemented worktree satisfies the accepted plan's verification checks.
150
+ const taskList = flattenTaskViews(tasks)
151
+ .map((t) => `- \`${t.id}\`: ${t.title} (${t.status})`)
152
+ .join("\n");
153
+ const prior = priorFindings.length
154
+ ? `Unresolved findings from earlier rounds (reuse these exact ids while the problem persists; a problem is resolved only by no longer reporting it):
59
155
 
60
- Target plan: ${planPath} (audit round ${round})
156
+ ${priorFindings.map((f) => `- \`${f.id}\` — severity: ${f.severity}; tasks: ${f.taskIds.join(", ") || "none"}; note: ${f.note}`).join("\n")}`
157
+ : "(none — this is the first round with findings in scope)";
158
+ return `Goal: verify that the implemented worktree satisfies the accepted plan's verification checks, and report implementation findings that drive the fix loop.
159
+
160
+ Target plan: ${planPath} (review round ${round})
61
161
 
62
162
  Authority boundary: read-only analysis only. Do not edit, write, delete, commit, push, or spawn subagents.
63
163
 
@@ -67,36 +167,75 @@ Checks to verify (only these; checks covering no task and checks already satisfi
67
167
 
68
168
  ${checks}
69
169
 
70
- Output: Markdown with exactly one section per check, in the order above:
170
+ Plan tasks (the only ids valid in a finding's tasks field):
171
+
172
+ ${taskList}
173
+
174
+ ${prior}
175
+
176
+ Output: exactly two sections, in this order.
177
+
178
+ 1. Verification verdicts — one section per check, in the order above:
71
179
 
72
180
  - \`VC-###\` — verdict: pass | fail | undeterminable; evidence: <repo path/command proving it>; note: <one line>.
73
181
 
74
- Emit every listed check exactly once. \`undeterminable\` is a legitimate answer: use it whenever the evidence is missing, unreadable, ambiguous, or beyond your read-only reach. Report \`fail\` only when you can point at the specific thing that breaks the condition — never report \`fail\` for want of evidence.`;
182
+ Emit every listed check exactly once. \`undeterminable\` is a legitimate answer: use it whenever the evidence is missing, unreadable, ambiguous, or beyond your read-only reach. Report \`fail\` only when you can point at the specific thing that breaks the condition — never report \`fail\` for want of evidence.
183
+
184
+ 2. Implementation findings — one bullet per defect anywhere in the implemented change (not only what the checks cover), exact line grammar:
185
+
186
+ - \`F-###\` — severity: high | medium | low; tasks: Task-N, Task-M | none; proposed-task: <imperative one-line title>; note: <one line>; evidence: <repo path or quoted excerpt>
187
+
188
+ \`high\` wakes the executor for a fix round; \`medium\`/\`low\` are recorded. When no existing task owns the defect use \`tasks: none\` and (required for high) a self-contained \`proposed-task:\` title. If nothing is worth reporting, emit exactly \`- none.\` under the findings heading.`;
75
189
  }
76
190
 
77
191
  /** Parse the audit subagent's verdict lines. Exported for tests. */
78
- export function parseAuditReport(report: string, pendingVcIds: string[]): ParsedAudit {
192
+ export function parseAuditReport(report: string, pendingVcIds: string[], knownTaskIds?: Set<string>): ParsedAudit {
79
193
  const passed: string[] = [];
80
194
  const failed: string[] = [];
81
195
  const known = new Set(pendingVcIds.map((id) => id.toUpperCase()));
82
- // The auditor writes Markdown, so a verdict may carry emphasis
196
+ // The reviewer writes Markdown, so a verdict may carry emphasis
83
197
  // (`**pass**`, `*pass*`, `_pass_`, `` `pass` ``). Requiring a bare token
84
198
  // silently discarded such verdicts, and the caller's fail-closed rule then
85
199
  // marked every check failed and rolled the whole run back -- reporting
86
200
  // correct work as failure. Tolerate the markers; \b keeps `passed` and
87
201
  // `passing` from matching.
88
- for (const match of report.matchAll(/`?(VC-\d+)`?[^\n]*?verdict:\s*[*_`~]*\s*(pass|fail|undeterminable)\b/gi)) {
89
- const id = match[1].toUpperCase();
90
- if (!known.has(id)) continue;
91
- const verdict = match[2].toLowerCase();
202
+ // v0.9: finding bullets (F-###) are excluded from verdict scanning — a
203
+ // finding's note may cite a VC id, and that must never register a verdict.
204
+ // v0.9.1 (F-011): the contract promises "one section per check" and an
205
+ // equally literal reading puts the id in a `### VC-###` heading with the
206
+ // verdict on a line of its own below it. The old same-line-only scan
207
+ // parsed such reports to ZERO verdicts and burned whole budgets as
208
+ // undeterminable. The scan is now section-aware: a line that NAMES a
209
+ // known check at a heading/bullet start opens that check's section, and a
210
+ // bare `verdict:` token attributes to the nearest open section; an
211
+ // id-and-verdict pair on one line stays direct.
212
+ const record = (id: string, verdict: string): void => {
92
213
  if (verdict === "pass") passed.push(id);
93
214
  else if (verdict === "fail") failed.push(id);
215
+ };
216
+ const verdictToken = /verdict:\s*[*_`~]*\s*(pass|fail|undeterminable)\b/i;
217
+ let current: string | null = null;
218
+ for (const line of report.split(/\n/)) {
219
+ if (/^\s*[-*]\s+`?F-\d+`?\b/i.test(line)) continue; // finding bullet
220
+ const sectionId = line.match(/^\s*(?:#{1,6}\s+|[-*]\s+)?`?(VC-\d+)`?\b/i);
221
+ if (sectionId) {
222
+ const id = sectionId[1].toUpperCase();
223
+ if (known.has(id)) current = id;
224
+ }
225
+ const direct = line.match(/`?(VC-\d+)`?[^\n]*?verdict:\s*[*_`~]*\s*(pass|fail|undeterminable)\b/i);
226
+ if (direct) {
227
+ const id = direct[1].toUpperCase();
228
+ if (known.has(id)) record(id, direct[2].toLowerCase());
229
+ continue;
230
+ }
231
+ const bare = line.match(verdictToken);
232
+ if (bare && current) record(current, bare[1].toLowerCase());
94
233
  }
95
234
  // A check with conflicting verdicts resolves to fail: the reader saw both.
96
235
  for (const id of [...new Set(passed)]) if (failed.includes(id)) passed.splice(passed.indexOf(id), 1);
97
236
  const undecided = new Set(known);
98
237
  for (const id of [...passed, ...failed]) undecided.delete(id);
99
- return { passed: [...new Set(passed)], failed: [...new Set(failed)], undeterminable: [...undecided] };
238
+ return { passed: [...new Set(passed)], failed: [...new Set(failed)], undeterminable: [...undecided], findings: parseFindings(report, knownTaskIds) };
100
239
  }
101
240
 
102
241
  /** Pure decision core: classify a parsed report into the audit outcome. It
@@ -109,6 +248,7 @@ export function applyAuditOutcome(round: number, parsed: ParsedAudit, report: st
109
248
  passed: parsed.passed,
110
249
  failed: parsed.failed,
111
250
  undeterminable: parsed.undeterminable,
251
+ findings: parsed.findings,
112
252
  report,
113
253
  };
114
254
  }
@@ -132,6 +272,9 @@ export async function runCompletionAudit(
132
272
  checklist: CheckItem[];
133
273
  tasks: TaskView[];
134
274
  round: number;
275
+ /** Unresolved findings from earlier committed rounds, injected into
276
+ * the brief so the reviewer reuses stable ids (v0.9). */
277
+ priorFindings?: ReviewFinding[];
135
278
  model?: string;
136
279
  thinkingLevel?: string;
137
280
  timeoutMs?: number;
@@ -141,7 +284,7 @@ export async function runCompletionAudit(
141
284
  ): Promise<AuditRoundResult> {
142
285
  const { runPiSubagent } = await import("./subagent.ts");
143
286
  const pending = auditablePendingChecks(opts.checklist, opts.tasks);
144
- const task = buildAuditTask(opts.planPath, opts.checklist, opts.tasks, opts.round);
287
+ const task = buildAuditTask(opts.planPath, opts.checklist, opts.tasks, opts.round, opts.priorFindings ?? []);
145
288
  // agents/auditor.md, not agents/reviewer.md: the reviewer prompt mandates a
146
289
  // plan-review shape (`## Findings` / `## Questions`, F-###) and never says
147
290
  // "verdict", so auditing under it produced reports this parser could not
@@ -165,13 +308,14 @@ export async function runCompletionAudit(
165
308
  if (result.cancelled === true) return { cancelled: true };
166
309
  return null;
167
310
  }
168
- const parsed = parseAuditReport(result.output, pending.map((item) => item.id));
311
+ const parsed = parseAuditReport(result.output, pending.map((item) => item.id), new Set(flattenTaskViews(opts.tasks).map((t) => t.id)));
169
312
  messaging().appendEntry("pi-plans-audit", {
170
313
  planPath: opts.planPath,
171
314
  round: opts.round,
172
315
  passed: parsed.passed,
173
316
  failed: parsed.failed,
174
317
  undeterminable: parsed.undeterminable,
318
+ highFindings: parsed.findings.filter((f) => f.severity === "high").map((f) => f.id),
175
319
  });
176
320
  return applyAuditOutcome(opts.round, parsed, result.output);
177
321
  }
@@ -191,6 +335,9 @@ export function writeReviewRoundReport(
191
335
  passed: string[];
192
336
  failed: string[];
193
337
  undeterminable: string[];
338
+ /** v0.9 findings from this round; recorded in the round report so the
339
+ * file stays the full evidence record. */
340
+ findings?: ReviewFinding[];
194
341
  discardedReason?: string;
195
342
  fingerprintCaptured?: string;
196
343
  fingerprintFound?: string;
@@ -209,6 +356,8 @@ export function writeReviewRoundReport(
209
356
  `- passed: ${entry.passed.join(", ") || "(none)"}`,
210
357
  `- failed: ${entry.failed.join(", ") || "(none)"}`,
211
358
  `- undeterminable: ${entry.undeterminable.join(", ") || "(none)"}`,
359
+ `- high findings: ${entry.findings?.filter((f) => f.severity === "high").map((f) => f.id).join(", ") || "(none)"}`,
360
+ ...(entry.findings?.length ? [`- findings: ${entry.findings.map((f) => `${f.id} (${f.severity}${f.proposedTask ? "; proposed: " + f.proposedTask : ""})`).join(" | ")}`] : []),
212
361
  ...(entry.discardedReason ? [`- discarded: ${entry.discardedReason}`] : []),
213
362
  `- fingerprint (captured): ${entry.fingerprintCaptured ?? "(n/a)"}`,
214
363
  `- fingerprint (at resolve): ${entry.fingerprintFound ?? "(n/a)"}`,