pi-plans 0.2.0 → 0.3.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.
Files changed (75) hide show
  1. package/README.md +90 -26
  2. package/agents/ref-analyst.md +18 -0
  3. package/index.ts +121 -9
  4. package/package.json +16 -1
  5. package/references/pi-planning-workflow.md +21 -6
  6. package/references/state-and-config.md +52 -5
  7. package/scripts/validate.ts +5 -0
  8. package/skills/plan-with-refs/SKILL.md +3 -3
  9. package/src/code-graph/commands.ts +483 -0
  10. package/src/code-graph/discovery.ts +118 -0
  11. package/src/code-graph/git.ts +108 -0
  12. package/src/code-graph/identity.ts +59 -0
  13. package/src/code-graph/indexer.ts +281 -0
  14. package/src/code-graph/materialize.ts +166 -0
  15. package/src/code-graph/mode.ts +28 -0
  16. package/src/code-graph/mutations.ts +160 -0
  17. package/src/code-graph/parser.ts +51 -0
  18. package/src/code-graph/parsers/javascript.ts +35 -0
  19. package/src/code-graph/parsers/python.ts +160 -0
  20. package/src/code-graph/parsers/tree-sitter.ts +316 -0
  21. package/src/code-graph/paths.ts +85 -0
  22. package/src/code-graph/prompts.ts +18 -0
  23. package/src/code-graph/resolver.ts +69 -0
  24. package/src/code-graph/runtime.ts +158 -0
  25. package/src/code-graph/schema.ts +135 -0
  26. package/src/code-graph/screening.ts +82 -0
  27. package/src/code-graph/store.ts +278 -0
  28. package/src/code-graph/summary.ts +435 -0
  29. package/src/code-graph/types.ts +163 -0
  30. package/src/compaction.ts +1125 -371
  31. package/src/config-command.ts +361 -0
  32. package/src/exec.ts +508 -693
  33. package/src/guard.ts +14 -1
  34. package/src/refine-prompts.ts +109 -0
  35. package/src/refine-ui-helpers.ts +71 -18
  36. package/src/refine-ui-state.ts +88 -22
  37. package/src/refine-ui.ts +210 -102
  38. package/src/state.ts +36 -7
  39. package/src/subagent.ts +164 -61
  40. package/src/termination-prompt.ts +22 -0
  41. package/tests/analyze-refs.test.ts +265 -0
  42. package/tests/ask-choice.test.ts +264 -0
  43. package/tests/autocomplete.test.ts +6 -1
  44. package/tests/code-graph-apply-action.test.ts +173 -0
  45. package/tests/code-graph-apply.test.ts +185 -0
  46. package/tests/code-graph-commands.test.ts +211 -0
  47. package/tests/code-graph-db.test.ts +166 -0
  48. package/tests/code-graph-discovery.test.ts +38 -0
  49. package/tests/code-graph-git.test.ts +94 -0
  50. package/tests/code-graph-index.test.ts +175 -0
  51. package/tests/code-graph-loop.e2e.test.ts +159 -0
  52. package/tests/code-graph-mutations.test.ts +117 -0
  53. package/tests/code-graph-parser.test.ts +85 -0
  54. package/tests/code-graph-rollback.test.ts +100 -0
  55. package/tests/code-graph-summary-batching.test.ts +518 -0
  56. package/tests/code-graph-summary.test.ts +148 -0
  57. package/tests/compaction.test.ts +371 -57
  58. package/tests/config-command.test.ts +263 -0
  59. package/tests/exec.test.ts +808 -241
  60. package/tests/fixtures/code-graph/sample.js +36 -0
  61. package/tests/fixtures/code-graph/sample.py +20 -0
  62. package/tests/fixtures/code-graph/sample.ts +15 -0
  63. package/tests/graph-aware-file-tools.test.ts +411 -0
  64. package/tests/guard.test.ts +27 -1
  65. package/tests/plans.test.ts +10 -0
  66. package/tests/refine-prompts.test.ts +101 -2
  67. package/tests/refine-ui.test.ts +371 -72
  68. package/tests/state.test.ts +32 -0
  69. package/tests/subagent.test.ts +48 -20
  70. package/tools/analyze-refs.ts +263 -0
  71. package/tools/ask-choice.ts +159 -11
  72. package/tools/code-graph.ts +277 -0
  73. package/tools/graph-aware-file-tools.ts +392 -0
  74. package/tools/plans.ts +97 -2
  75. package/tools/refine.ts +61 -15
package/README.md CHANGED
@@ -113,15 +113,16 @@ Planning artifacts live under `./docs/pi-plans/YYYY-MM-DD-<topic>/` by default (
113
113
  | Capability | In short |
114
114
  |---|---|
115
115
  | Planning router + five specialist skills | Start with `/skill:planning` to route to the narrowest matching specialist (`plan-small` → `plan-big`, `debug-and-plan`, `plan-with-refs`) |
116
- | Choice prompts | `ask_choice`: recommended option first, answers auto-recorded per run; choosing Auto-complete enables recommendation-only answers for later eligible questions in the current planning run, with `/plans-autocomplete-stop` available to take back control |
117
- | Refinement rounds | Read-only reviewer/criticizer Pi subagents consolidate findings into the next plan version; delegated runs have standalone `Reviewer`/`Criticizer` progress overlays that close before the tool result returns |
116
+ | Choice prompts | `ask_choice`: recommended option first, answers auto-recorded per run; choosing Auto-complete enables recommendation-only answers for later eligible questions in the current planning run, with `/plans-autocomplete-stop` available to take back control. After execution completes, the continuation prompt enters goal-running mode by default: it asks only for the implementation-review loop's termination condition and then keeps refining until the loop ends or the cap is reached. |
117
+ | Refinement rounds | Read-only reviewer/criticizer Pi subagents consolidate findings into the next plan version; delegated runs have standalone `Reviewer`/`Criticizer` progress overlays that close before the tool result returns; `analyze_refs` shows the same kind of overlay titled `Refs` while per-reference analysis subagents run |
118
118
  | Workspace state | Config, runs, decisions, refs, and subagent ledgers in `.git/pi_plans/` (git common dir) |
119
- | Smart compact (I-aware) | History is sliced by `I-###` instead of VC. The current-I slice above 20% of the model window triggers a bounded summary with paired `Read:` records, retains a legal recent suffix, targets <10% post-context, and records a hard-floor reason when unreachable. Planning phase falls back to the latest plan/Q&A focus when no current marker exists; cooldown + resume guard prevent ping-pong; one hidden continuation is queued when Pi reports `willRetry: false` |
120
- | Visible Refiner overlay | Delegated reviewer/criticizer subagents surface as a named public overlay in the TUI — one `Reviewer`/`Criticizer` panel with per-lane tool progress, bounded output preview, and clean cancelled/timed-out vs completed states. The overlay opens when the round starts and closes before the tool result returns to the main session |
119
+ | VCC compact | Active planning/execution compaction uses deterministic, no-LLM VCC-style summaries when Pi core emits manual `/compact`, threshold, or overflow events. Summaries use five bracket sections plus a brief transcript, keep a smart recent tail, support `keep:N`, and write VCC details/stats without adding `/pi-vcc` commands. |
120
+ | Visible Refiner overlay | Delegated reviewer/criticizer subagents surface as a named public overlay in the TUI — one `Reviewer`/`Criticizer` 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 |
121
121
  | Tracked execution | Checklist injected each turn; `[DONE:VC-xxx]` markers drive completion; implementation items report progress with `[I-xxx:implemented]` / `[I-xxx:validating]` markers; the bottom status bar shows lifecycle, `x/y` progress, elapsed time, and input/output token usage in real time |
122
+ | Goal-wait continuation | While execution is active, a turn that ends with unpassed VCs gets an automatic light follow-up (`🔁 goal-wait` in the status bar) — the worker keeps going, and rounds blocked on an external event poll via the taught `waiting for` backoff instead of stopping. Guard rails: 3 consecutive no-progress rounds, or 6 waiting rounds, pause the continuation (`⏸ goal-wait paused (reason)` in the status bar); any new input or `/plans-execute` re-kicks it, and `/plans-stop` always terminates |
122
123
  | Execution handoff | The accepted plan resumes in the current session model; no separate model selection is performed. |
123
- | Execution-phase compaction | Pi core owns threshold, overflow, and manual scheduling; pi-plans adds a current-I proactive check once the current-I slice exceeds 20% of the model window, summarizes I-level history and bounded `Read:` records, retains a legal recent suffix, targets under 10% when possible, and records hard-floor reasons when not; one hidden continuation is queued when Pi reports `willRetry: false` |
124
- | Planning-phase auto compaction | In active planning runs (run.status=planning, no execution), the current-I check uses the same 20%/10% best-effort policy when a marker exists; without a marker it protects the latest plan/Q&A focus, while Pi threshold, overflow, and manual compaction remain supported; cooldown + resume guard prevent ping-pong and hidden resume messages stay out of model context |
124
+ | Execution-phase compaction | Pi core owns scheduling; pi-plans maps the active plan path, current `I-###`, implementation IDs, and remaining `VC-###` checklist into the VCC sections. The old current-I proactive trigger and model-generated summary path are removed. |
125
+ | 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. |
125
126
  | Efficient executor prompt | Each turn, the executor is steered by a fused rule set — Marcos Hernanz's AGENTS.md principles × Ponytail minimalism: layered growth, simplest implementation, long-term architecture (no stopgaps), library discipline — so plans finish in fewer tokens and fewer detours |
126
127
  | Write guard | `edit`/`write` blocked outside planning artifacts while a run is active |
127
128
 
@@ -129,11 +130,13 @@ Planning artifacts live under `./docs/pi-plans/YYYY-MM-DD-<topic>/` by default (
129
130
 
130
131
  | Tool / Command | Purpose |
131
132
  |---|---|
132
- | `plans` | State CLI: `init`, `show`, `set-language`, `set-artifact-root`, `set-role`, `start-run`, `set-status`, `record-decision`, `record-ref`, `record-subagent` |
133
+ | `plans` | State CLI: `init`, `show`, `set-language`, `set-artifact-root`, `set-refs-root`, `set-role`, `start-run`, `set-status`, `record-decision`, `record-ref`, `record-subagent` |
133
134
  | `ask_choice` | Numbered choice prompt; `autoComplete: false` for the merged accept/execute question and external-state questions |
134
- | `refine` | Reviewer/criticizer round via standalone read-only subagents (`--mode json -p --no-session --tools read,grep,find,ls`); delegated TUI runs show one `Reviewer`/`Criticizer` overlay and close it before returning; `reviewers: 3` for big plans; enforces role/model confirmation gates |
135
+ | `refine` | Reviewer/criticizer round via standalone read-only subagents (`--mode json -p --no-session --tools read,grep,find,ls`, plus `code_graph` for both roles when the workspace has the code graph enabled); `target: "plan"` (default) reviews the plan, `target: "implementation"` reviews the implemented worktree against the plan; delegated TUI runs show one `Reviewer`/`Criticizer` overlay (78% width × 78% height, top-center, ≥72 cols) with per-lane transcript, follow-bottom scroll, Tab focus, and retention until `Esc`; `reviewers: 3` renders three equal-height panes; enforces role/model confirmation gates |
136
+ | `analyze_refs` | plan-with-refs reference analysis: one independent read-only subagent per downloaded reference (cwd = the ref directory), reusing the reviewer role gates and the concurrent overlay (titled `Refs`); batches of at most 3 lanes run sequentially; returns structured per-reference sections for `REF_ANALYSIS.md` |
135
137
  | `execute_plan` | Execution handoff: re-confirms with the user and enters extension-managed execution mode |
136
138
  | `/plans` | Show config, active run, and execution progress |
139
+ | `/config-pi-plans` | Re-ask workspace defaults for language, artifact root, refs root, code graph, reviewer mode/model, and criticizer mode/model |
137
140
  | `/plans-execute [plan.md]` | Manual execution handoff (defaults to highest `PLAN_vN.md`) |
138
141
  | `/update-plan [plan.md] [reason…]` | Interrupt-and-refine: stops execution (if any), returns the run to planning, and directs the agent to revise the plan into `PLAN_vN+1.md` while preserving verified work |
139
142
  | `/plans-autocomplete-stop` | Stop the current run's Auto-complete mode and return later planning questions to normal interaction |
@@ -141,24 +144,26 @@ Planning artifacts live under `./docs/pi-plans/YYYY-MM-DD-<topic>/` by default (
141
144
  | `/plans-abandon` | Abandon the active run (lifts the write guard; artifacts stay) |
142
145
  | Status bar (lifecycle) | 💬 Q&A → 📝 draft written (planning sub-phases) → ⌛ executing `x/y · spent · in/out-toks` in the bottom status bar → ⛔ stopped / 🎯 done / 🚫 abandoned |
143
146
 
144
- ## Smart compact (I-aware)
147
+ ## VCC compact
145
148
 
146
- Default `compaction` is Pi-core-owned: threshold, overflow, and manual `/compact` always run as designed. On top of that, pi-plans layers an **I-aware policy** so long, tool-heavy sessions survive the same run instead of running out of context:
149
+ Pi core remains the owner of compaction scheduling: manual `/compact`, threshold, and overflow events are emitted by Pi as usual. During an active pi-plans planning or execution run, pi-plans handles `session_before_compact` with a deterministic VCC-style compiler instead of calling a model for a summary.
147
150
 
148
- - **Slice by implementation item.** History is grouped by `[I-###:current]` markers instead of `[DONE:VC-xxx]`. The current I's prefix can be summarized, the current I's recent suffix stays raw, and finished `I-###` items become independent sections.
149
- - **Bounded read history.** Every paired `read` call/result is reduced to `Read: <path> line <X-Y> Extracted information summary: ...` (line range is `unknown` when no offset/limit is given). Records deduplicate by path/range across compactions and never embed full raw tool output.
150
- - **20%/10% best-effort budget.** When the current-I slice exceeds 20% of `ctx.getContextUsage().contextWindow`, a compact is requested on the next settled turn. The summary's `details` record `contextWindow`, `tokensBefore`, `currentITokens`, `summaryTokens`, `keptSuffixTokens`, `estimatedAfterTokens`, `targetRatio`, `currentI`, `firstKeptEntryId`, `targetMet`, and a `hardFloorReason` when the 10% target cannot be reached (system prompt, tool definitions, single oversized tool result). Hard floors stop the loop; they do not silently fall through.
151
- - **Pi-owned scheduling preserved.** Threshold, overflow, and manual triggers still come from Pi core. pi-plans only customizes the summary and re-arms once usage falls below the low watermark. The hidden `Continue execution.` resume message is queued on non-retry compactions and never enters model context.
152
- - **Bounded model call.** Custom summaries reuse the current Pi model via `ctx.modelRegistry.complete(model, context, options)` with `event.signal`, `cacheRetention: "none"`, a fresh `sessionId`, and bounded `maxTokens`. Empty, length-stopped, error, or tool-call responses fall back to Pi's default compaction no half-checkpoint is ever written.
153
- - **Phase isolation.** Planning and execution keep independent compaction state (`pi-plans-plan-resume` vs `pi-plans-exec-resume`); planning without a current marker protects the latest plan/Q&A focus rather than leaking execution state.
151
+ - **Summary shape.** The summary contains exactly five bracket sections: `[Session Goal]`, `[Files And Changes]`, `[Commits]`, `[Outstanding Context]`, and `[User Preferences]`, followed by `---` and a ranked brief transcript. Execution contributes plan path, current `I-###`, implementation IDs, and remaining verifier IDs; planning contributes run ID, artifact directory, latest plan path from session entries, and any observed current-I marker.
152
+ - **Session-only input.** Compact summaries are built from the event's branch entries, previous summary, file ops, pi-plans custom session entries, and live phase state. The compiler does not read plan files, git history, or the worktree to invent context.
153
+ - **Tail policy.** The default keep is one recent user turn; smart keep may retain more turns when the tail is still small. Explicit `keep:N` is honored, while no-anchor and oversized-tail cases use a deterministic token-budget cut that avoids starting retained context with an orphan tool result.
154
+ - **Manual matrix.** Plain `/compact` and `/compact keep:N` compact and show stats without continuing. `/compact <text>` and `/compact keep:N <text>` compact, then send the text once as the follow-up prompt. Internal pi-plans compaction markers are never reused as user follow-up prompts.
155
+ - **Fallbacks and stats.** Unsafe manual/threshold cuts cancel with a warning; overflow or retrying unsafe cuts return control to Pi core. Successful VCC compactions notify with kept-tail and summarized-message stats. Threshold/overflow compactions may queue one hidden continuation only when the running Pi version still needs it and `continueAfterThresholdCompact` is enabled.
156
+ - **Repo-private config.** Defaults are scaffolded in `.git/pi_plans/pi-vcc-config.json` under the resolved git common dir: `overrideDefaultCompaction:true`, `smartKeepTail:true`, `continueAfterThresholdCompact:true`, `debug:false`. Global pi-vcc config and `PI_VCC_CONFIG_PATH` are intentionally ignored.
154
157
 
155
158
  ## Visible Refiner overlay
156
159
 
157
- Delegated `refine` rounds (reviewer or criticizer) show their progress directly inside the Pi TUI instead of disappearing into the child process's terminal. The overlay is a public, named panel so users always know who is doing what:
160
+ Delegated `refine` rounds (reviewer or criticizer) and `analyze_refs` rounds (titled `Refs`) show their progress directly inside the Pi TUI instead of disappearing into the child process's terminal. The overlay is a public, named panel so users always know who is doing what:
158
161
 
159
- - **Named public overlays.** Each round uses the literal overlay name `Reviewer` or `Criticizer` (no dependency on `pi-btw`; the renderer is built on Pi's public `pi-tui` primitives). The big-plan concurrent reviewer round renders one reviewer lane per subagent under the same `Reviewer` overlay.
160
- - **Bounded live detail.** The overlay tracks lane state (`pending running completed | cancelled | timed-out`) and the most recent tool call plus a clipped argument preview. Raw tool output is never surfaced, so progress stays legible even when subagents read large files.
161
- - **Clean lifecycle edges.** The overlay opens at round start, advances via the JSONL progress feed emitted by `pi --mode json`, and is `close()`d before the round's conclusion returns as a tool result to the main session. Cancelled and timed-out children render as terminal states with the original error message — never as silent drops.
162
+ - **Pi-btw-aligned geometry.** Each round uses `width: "78%"`, `minWidth: 72`, `maxHeight: "78%"`, `anchor: "top-center"`, and `{ top: 1, left: 2, right: 2 }` margins (no dependency on `pi-btw`; the renderer is built on Pi's public `pi-tui` primitives).
163
+ - **Complete streaming transcript.** Assistant text, thinking blocks, tool calls, tool results, and stderr are merged per turn/content block into lane entries without overlay-facing truncation; only the viewport slices them. Final `message_end` / `tool_execution_end` overwrite the live snapshot with the authoritative content.
164
+ - **No input row.** The overlay has no composer, no submit path, and no printable input forwarding. Only `Esc`, `Tab`/`Shift+Tab`, `↑/↓`, `PgUp/PgDn`, and SGR mouse wheel are consumed; everything else is ignored by design.
165
+ - **Equal-height panes for `reviewers: 3`.** Concurrent reviewer rounds render one reviewer lane per subagent as three independent equal-height panes inside the same top-center overlay; each pane keeps its own scroll offset and `follow-bottom` state. `Tab`/`Shift+Tab` switches the focused pane and scroll keys only affect it.
166
+ - **Lifecycle.** The overlay opens at round start, advances via the JSONL progress feed emitted by `pi --mode json`, and is dismissed by `Esc`. `Esc` is close-only — it never aborts the refiner child; the child keeps running to natural completion and its result still flows back through the tool result path. A new refinement round replaces any retained finished overlay to avoid overlay stacking. Cancelled and timed-out children render as terminal states with the original error message — never as silent drops.
162
167
  - **Tool-only progress.** The overlay only consumes tool and message lifecycle events from the child; unrelated `pi` events are ignored, so a noisy upstream release does not desync the panel.
163
168
 
164
169
  ## The execution rules
@@ -214,23 +219,79 @@ or register the absolute path in `~/.pi/agent/settings.json`:
214
219
  { "extensions": ["/absolute/path/to/pi-plans"] }
215
220
  ```
216
221
 
222
+ ## Code graph (v0.3+)
223
+
224
+ `/init-graph` walks the worktree, parses JavaScript/TypeScript and Python
225
+ files with Tree-sitter, and stores a normalized function graph in
226
+ `.git/pi_plans/code_graph.db`. The DB is the canonical source for downstream
227
+ agents: function rows expose a low-token `description`/`inputs`/`outputs`
228
+ JSON view, call edges are normalized with `in_links`/`out_links` derived on
229
+ read, and each function retains its full UTF-8 source.
230
+
231
+ - `/init-graph [--reindex] [--no-summary] [--no-commit]` — scan the worktree and write the graph; if `code_graph.db` already exists, it first asks whether to rebuild or sync changed paths via `/update-graph` (non-interactive runs and `--reindex` stay on the rebuild path). With `--reindex` it keeps the existing full-worktree reindex semantics on the rebuild path. Dirty trees get a `chore(code-graph): pre-init snapshot` commit first (`--no-commit` skips). After indexing it records a `code_graph_snapshot` (HEAD + uncommitted paths) that `/graph-drift` compares against. The parser dependencies are installed via npm (`tree-sitter`, grammars).
232
+ - `/graph-status` — print function/file/edge counts.
233
+ - `/update-graph [--dry-run] [--base <commit>]` — incrementally reindex only the paths `git status --porcelain` reports (including untracked and rename targets); deleted files' DB rows are purged, never resurrected. `/init-graph` uses this path when you choose the sync-changes branch.
234
+ - `/graph-drift [--json] [--commit-aware]` — direction-aware convergence check:
235
+ (a) per-file hash match or a pending apply marker, (b) every uncommitted
236
+ indexable path is indexed, (c) snapshot vs current HEAD (informational).
237
+ - `/apply-graph [--force]` — materialize DB edits back to source. Files with
238
+ `pending_kind='update'` are written (created when missing on disk);
239
+ `pending_kind='delete'` files are removed from disk and the DB; pending-null
240
+ missing files are skipped, never resurrected. Refuses when the active
241
+ planning run is `planning`/`accepted`.
242
+ - `/enable-graph` / `/disable-graph` — toggle the `graph_enabled` config
243
+ flag (disable refuses while drift is dirty). When enabled, planner/refiner/
244
+ executor prompts hard-require function-level reads for indexed code, and the
245
+ built-in `read`/`write`/`edit` tools become graph-aware overrides for
246
+ indexed source files: `read` returns a capped function digest (≤50 lines,
247
+ synthetic anonymous entries folded) with `full: true` as the only whole-file
248
+ exit (small/zero-function files return full text); `write`/`edit` stage
249
+ DB-first mutations; unexpected fallbacks (not indexed / runtime unavailable /
250
+ config unreadable) are marked in the result; refiner and criticizer
251
+ subagents get the `code_graph` tool in their allowlist (verified in headless
252
+ no-session children); the executor loop
253
+ becomes DB-first: `code_graph` mutations → `code_graph apply` (agent-side
254
+ materialization; its result carries counts and the post-apply drift
255
+ summary) → `plans final-commit` → `/init-graph`.
256
+ - The `code_graph` tool provides read-only screening (`status`, `screening`,
257
+ `get-function`, `manifest`), DB-first mutations (`update-function`,
258
+ `update-file`, `delete-file` — all mark files `pending_materialization`
259
+ and append to `change_log`), `list-pending`, and the agent-invokable
260
+ `apply` action (same planning/accepted gate as `/apply-graph`; also
261
+ refused for read-only refiner subagents via the `PI_PLANS_REFINER` env
262
+ marker; returns per-file counts plus a post-apply drift summary without
263
+ changing run status) so agents can navigate, stage, materialize, and
264
+ edit the graph without pulling `full_code`.
265
+
266
+ Runtime requirements: the base extension still requires Node ≥ 22.6; the
267
+ graph feature additionally requires Node ≥ 22.13 (or `--experimental-sqlite`)
268
+ so that `node:sqlite` is available without flag. Pi's host currently ships
269
+ Node ≥ 22.19, so a fresh install works out of the box. The code graph also
270
+ needs the optional `tree-sitter` parser packages, which are **not** installed
271
+ automatically — add them to the workspace (or global tree) where pi runs:
272
+ `npm i tree-sitter tree-sitter-javascript tree-sitter-typescript tree-sitter-python`. Without them, planning and execution work normally and graph
273
+ tools report which package is missing. On unsupported
274
+ runtimes (Bun, missing parsers) graph commands fail locally without
275
+ affecting the planning workflow.
276
+
217
277
  ## Layout
218
278
 
219
279
  ```
220
280
  pi-plans/
221
281
  ├── index.ts # Extension entry: tools, commands, guard, execution loop
222
- ├── tools/ # plans, ask-choice, refine, execute-plan
282
+ ├── tools/ # plans, ask-choice, refine, execute-plan, code-graph
223
283
  ├── src/ # state, guard, plan parsing, subagent runner, refine overlay, exec loop
284
+ │ └── code-graph/ # SQLite schema/store, parsers, indexer, summary, materialize
224
285
  ├── skills/ # The planning router plus five specialist planning skills
225
286
  ├── references/ # Shared workflow, state/config, plan template (normative)
226
287
  ├── agents/ # reviewer.md / criticizer.md subagent prompts
227
288
  ├── scripts/validate.ts # Structure validator
228
- └── tests/ # node:test suite (state, guard, plan parsing, execution, refine progress)
289
+ └── tests/ # node:test suite (state, guard, plan parsing, execution, refine progress, code-graph)
229
290
  ```
230
291
 
231
292
  ## Safety model
232
293
 
233
- Before the approved handoff the workflow writes only `.git/pi_plans/` state, the run's artifact directory, and `~/.cache/pi-plans/` — the extension blocks `edit`/`write` elsewhere while a run is `planning`/`accepted` (bash stays discipline-bound: inspection, `git init`, downloads into the cache). Reviewer/criticizer subagents run with read-only tools. `Auto-complete` may answer planning and refinement questions only; it is never offered for execution, installs, publishing, deployment, merge, push, or credential use, and non-interactive sessions stop instead of auto-approving those.
294
+ Before the approved handoff the workflow writes only `.git/pi_plans/` state, the run's artifact directory, `~/.cache/pi-plans/`, and the configured refs root (set via `plans set-refs-root` or `/config-pi-plans`; the recommended `.git/pi-plans/refs/` lives inside the git dir and needs no extra guard) — the extension blocks `edit`/`write` elsewhere while a run is `planning`/`accepted` (bash stays discipline-bound: inspection, `git init`, downloads into the cache). Reviewer/criticizer/ref-analyst subagents run with read-only tools. `Auto-complete` may answer planning and refinement questions only; it is never offered for execution, installs, publishing, deployment, merge, push, or credential use, and non-interactive sessions stop instead of auto-approving those.
234
295
 
235
296
  ## Verification
236
297
 
@@ -239,7 +300,10 @@ npm run validate # structure validator
239
300
  npm test # node:test suite (stdlib only, no deps)
240
301
  ```
241
302
 
242
- Both run on Node ≥ 22.6 via `--experimental-strip-types`; no npm dependencies.
303
+ Both run on Node ≥ 22.6 via `--experimental-strip-types`. The graph
304
+ extension additionally requires `node:sqlite` (Node ≥ 22.13 unflagged, or
305
+ any Node ≥ 22.6 with `--experimental-sqlite`) and the four parser
306
+ dependencies listed in `dependencies`.
243
307
 
244
308
  ## FAQ
245
309
 
@@ -249,11 +313,11 @@ The plan is the contract. Refinement converges on scope while nothing is writabl
249
313
 
250
314
  **What can Auto-complete decide on my behalf?**
251
315
 
252
- 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.
316
+ 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, interactive sessions enter goal-running review mode automatically and ask only for the implementation-review loop's termination condition; the loop then continues until that condition or the 5-round cap. Headless sessions stay silent.
253
317
 
254
318
  **Where does all the state live?**
255
319
 
256
- Preferences and run ledgers in `.git/pi_plans/` inside your workspace's git directory (never tracked, never published); plan artifacts under the configured artifact root (default `./docs/pi-plans/`); large downloaded references outside the repo under `~/.cache/pi-plans/`.
320
+ Preferences and run ledgers in `.git/pi_plans/` inside your workspace's git directory (never tracked, never published); plan artifacts under the configured artifact root (default `./docs/pi-plans/`); reference downloads under the configured refs root — asked once per workspace (recommended `.git/pi-plans/refs/`), changeable via `plans set-refs-root` or `/config-pi-plans`.
257
321
 
258
322
  **How is this different from just prompting an AI to make changes?**
259
323
 
@@ -0,0 +1,18 @@
1
+ ---
2
+ name: pi-plans-ref-analyst
3
+ description: Read-only reference analyst for pi-plans plan-with-refs runs; deep-reads one downloaded reference and extracts adoptable ideas for the target repository.
4
+ tools: read, grep, find, ls
5
+ ---
6
+
7
+ You are a read-only reference analyst in the pi-plans plan-with-refs workflow.
8
+
9
+ Rules:
10
+
11
+ - Perform read-only analysis. Never edit, write, or delete any file.
12
+ - Your working directory is the local copy of ONE downloaded reference. Deep-read it: entry points, README/docs, core modules, tests, and configuration.
13
+ - Judge the reference through the lens of the target repository described in your task: what is worth borrowing, what is not, and why.
14
+ - Every claim needs evidence: a file path inside the reference (with line numbers when quoting). No evidence, no claim.
15
+ - You are evidence, not authority: state what you verified, not what you assume.
16
+ - Stay inside the reference directory; do not wander the filesystem.
17
+
18
+ Output structured Markdown in exactly the seven sections your task specifies, in that order, with no extra top-level sections.
package/index.ts CHANGED
@@ -32,11 +32,15 @@ import {
32
32
  handlePlanningBeforeCompact,
33
33
  handlePlanningCompact,
34
34
  handlePlanningCompactFailed,
35
+ noteCompactionEnded,
36
+ noteCompactionStarted,
35
37
  PLANNING_PLAN_WRITTEN_CUSTOM_TYPE,
36
38
  registerExecutionTurnHandlers,
37
39
  refreshPlanningCompactionCooldown,
38
40
  requestPlanningCompaction,
39
41
  restoreFromSession,
42
+ resetGoalWaitTurnFlags,
43
+ resumeGoalWaitIfPaused,
40
44
  stopExecution,
41
45
  updateStatusWidget,
42
46
  shouldTriggerPlanningCompaction,
@@ -50,12 +54,25 @@ import {
50
54
  } from "./src/autocomplete.ts";
51
55
  import { planningWriteBlockReason } from "./src/guard.ts";
52
56
  import { registerQueryInterviewHooks } from "./src/query-hook.ts";
57
+ import { registerCodeGraphTool } from "./tools/code-graph.ts";
58
+ import { registerGraphAwareFileTools } from "./tools/graph-aware-file-tools.ts";
59
+ import {
60
+ initGraphCommand,
61
+ applyGraphCommand,
62
+ graphStatusCommand,
63
+ updateGraphCommand,
64
+ graphDriftCommand,
65
+ enableGraphCommand,
66
+ disableGraphCommand,
67
+ } from "./src/code-graph/commands.ts";
53
68
  import { latestPlanVersion, nextPlanVersionPath } from "./src/plan.ts";
54
- import { getRun, readActive, recordDecision, resolveStateRootOrNull, setRunStatus } from "./src/state.ts";
69
+ import { configPiPlansCommand } from "./src/config-command.ts";
70
+ import { getRun, loadConfig, readActive, recordDecision, resolveStateRootOrNull, setRunStatus } from "./src/state.ts";
55
71
  import { registerAskChoiceTool } from "./tools/ask-choice.ts";
56
72
  import { executeHandoff, registerExecutePlanTool } from "./tools/execute-plan.ts";
57
73
  import { registerPlansTool } from "./tools/plans.ts";
58
74
  import { registerRefineTool } from "./tools/refine.ts";
75
+ import { registerAnalyzeRefsTool } from "./tools/analyze-refs.ts";
59
76
 
60
77
  const baseDir = dirname(fileURLToPath(import.meta.url));
61
78
 
@@ -67,12 +84,17 @@ const extensionLoadedAt = new Date();
67
84
  function extensionStalenessLine(): string {
68
85
  try {
69
86
  const dirs = [baseDir, path.join(baseDir, "src"), path.join(baseDir, "tools")];
87
+ const stack: string[] = [...dirs];
70
88
  let newest = 0;
71
- for (const dir of dirs) {
72
- for (const name of fs.readdirSync(dir)) {
73
- if (!name.endsWith(".ts")) continue;
74
- const mtime = fs.statSync(path.join(dir, name)).mtimeMs;
75
- if (mtime > newest) newest = mtime;
89
+ while (stack.length) {
90
+ const dir = stack.pop()!;
91
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
92
+ const full = path.join(dir, entry.name);
93
+ if (entry.isDirectory()) stack.push(full);
94
+ else if (entry.isFile() && entry.name.endsWith(".ts")) {
95
+ const mtime = fs.statSync(full).mtimeMs;
96
+ if (mtime > newest) newest = mtime;
97
+ }
76
98
  }
77
99
  }
78
100
  if (newest > extensionLoadedAt.getTime() + 2000) {
@@ -96,8 +118,11 @@ export default function piPlansExtension(pi: ExtensionAPI): void {
96
118
  registerPlansTool(pi);
97
119
  registerAskChoiceTool(pi);
98
120
  registerRefineTool(pi, baseDir);
121
+ registerAnalyzeRefsTool(pi, baseDir);
99
122
  registerExecutePlanTool(pi);
100
123
  registerQueryInterviewHooks(pi, hasActivePlanningWorkflow);
124
+ registerCodeGraphTool(pi);
125
+ registerGraphAwareFileTools(pi);
101
126
 
102
127
  // Contribute the router skill plus the five specialist planning skills.
103
128
  pi.on("resources_discover", () => ({
@@ -162,6 +187,32 @@ export default function piPlansExtension(pi: ExtensionAPI): void {
162
187
  return;
163
188
  });
164
189
 
190
+ // Bidirectional code-graph reminder hook: separate from the planning guard
191
+ // above (which early-returns during execution). Fires only when the graph
192
+ // is enabled and an execution is active. Reminders are best-effort notifies.
193
+ pi.on("tool_call", async (event, ctx) => {
194
+ if (!getExecution()) return;
195
+ const stateRoot = resolveStateRootOrNull(ctx.cwd);
196
+ if (!stateRoot) return;
197
+ let graphEnabled = false;
198
+ try {
199
+ graphEnabled = loadConfig(stateRoot).graph_enabled === true;
200
+ } catch {
201
+ return;
202
+ }
203
+ if (!graphEnabled) return;
204
+ if (event.toolName === "edit" || event.toolName === "write") {
205
+ ctx.ui?.notify?.("code-graph: source edited directly — run /update-graph to sync the graph, or use code_graph mutations + code_graph apply for DB-first edits", "info");
206
+ return;
207
+ }
208
+ if (event.toolName === "code_graph") {
209
+ const action = String((event.input as { action?: string }).action ?? "");
210
+ if (action === "update-function" || action === "update-file" || action === "delete-file") {
211
+ ctx.ui?.notify?.("code-graph: mutation staged — run code_graph apply to materialize (its result includes the post-apply drift summary)", "info");
212
+ }
213
+ }
214
+ });
215
+
165
216
  pi.on("context", (event) => {
166
217
  const filteredExecution = filterExecutionResumeMessages(event.messages as Array<{ customType?: string }>);
167
218
  const messages = filterPlanningResumeMessages(filteredExecution);
@@ -171,17 +222,20 @@ export default function piPlansExtension(pi: ExtensionAPI): void {
171
222
  });
172
223
 
173
224
  pi.on("session_before_compact", async (event, ctx) => {
225
+ noteCompactionStarted(ctx, event.customInstructions);
174
226
  const executionResult = await handleExecutionBeforeCompact(pi, ctx, event);
175
227
  if (executionResult) return executionResult;
176
228
  return handlePlanningBeforeCompact(pi, ctx, event);
177
229
  });
178
230
  pi.on("session_compact", async (event, ctx) => {
179
- handleExecutionCompact(pi, ctx, event);
180
- handlePlanningCompact(pi, ctx, event);
231
+ await handleExecutionCompact(pi, ctx, event);
232
+ await handlePlanningCompact(pi, ctx, event);
233
+ noteCompactionEnded(ctx, event.customInstructions);
181
234
  });
182
235
  pi.on("session_compact_failed", async (event, ctx) => {
183
236
  handleExecutionCompactFailed(pi, ctx, event);
184
237
  handlePlanningCompactFailed(pi, ctx, event);
238
+ noteCompactionEnded(ctx, event.customInstructions);
185
239
  });
186
240
 
187
241
  // Flush points for deferred execution-loop writes: primary drain when the
@@ -197,7 +251,9 @@ export default function piPlansExtension(pi: ExtensionAPI): void {
197
251
  // -----------------------------------------------------------------------
198
252
  pi.on("before_agent_start", async (_event, ctx) => {
199
253
  drainExecutionFlush(pi, ctx);
200
- const content = executionContextMessage();
254
+ resetGoalWaitTurnFlags();
255
+ resumeGoalWaitIfPaused(pi, ctx);
256
+ const content = executionContextMessage(ctx);
201
257
  if (!content) {
202
258
  if (!getExecution() && shouldTriggerPlanningCompaction(ctx)) {
203
259
  requestPlanningCompaction(ctx);
@@ -235,6 +291,55 @@ export default function piPlansExtension(pi: ExtensionAPI): void {
235
291
  // Commands
236
292
  // -----------------------------------------------------------------------
237
293
 
294
+ pi.registerCommand("init-graph", {
295
+ description: "Index the worktree into .git/pi_plans/code_graph.db. If a graph DB already exists, prompt to rebuild or sync changed paths via /update-graph; `--reindex` and non-interactive runs stay on the rebuild path.",
296
+ handler: async (args, ctx) => {
297
+ await initGraphCommand(args, ctx);
298
+ },
299
+ });
300
+
301
+ pi.registerCommand("apply-graph", {
302
+ description: "Apply code_graph.db changes back to source. Refuses during active planning/accepted run.",
303
+ handler: async (args, ctx) => {
304
+ await applyGraphCommand(args, ctx);
305
+ },
306
+ });
307
+
308
+ pi.registerCommand("graph-status", {
309
+ description: "Show code graph counts (functions, files, edges).",
310
+ handler: async (args, ctx) => {
311
+ await graphStatusCommand(args, ctx);
312
+ },
313
+ });
314
+
315
+ pi.registerCommand("update-graph", {
316
+ description: "Incrementally reindex working-tree changes (git status porcelain, incl. untracked/renames) into code_graph.db. Also used by /init-graph when you choose the sync-changes branch. Flags: --dry-run, --base <commit>.",
317
+ handler: async (args, ctx) => {
318
+ await updateGraphCommand(args, ctx);
319
+ },
320
+ });
321
+
322
+ pi.registerCommand("graph-drift", {
323
+ description: "Check DB↔source convergence (hash/pending, uncommitted coverage, snapshot). Flags: --json, --commit-aware.",
324
+ handler: async (args, ctx) => {
325
+ await graphDriftCommand(args, ctx);
326
+ },
327
+ });
328
+
329
+ pi.registerCommand("enable-graph", {
330
+ description: "Enable the code graph: agents prefer graph reads and DB-first edits.",
331
+ handler: async (_args, ctx) => {
332
+ await enableGraphCommand(_args, ctx);
333
+ },
334
+ });
335
+
336
+ pi.registerCommand("disable-graph", {
337
+ description: "Disable the code graph (refuses while DB/source drift is dirty).",
338
+ handler: async (_args, ctx) => {
339
+ await disableGraphCommand(_args, ctx);
340
+ },
341
+ });
342
+
238
343
  pi.registerCommand("plans", {
239
344
  description: "Show pi-plans state: config, active run, and execution progress",
240
345
  handler: async (_args, ctx) => {
@@ -264,6 +369,13 @@ export default function piPlansExtension(pi: ExtensionAPI): void {
264
369
  },
265
370
  });
266
371
 
372
+ pi.registerCommand("config-pi-plans", {
373
+ description: "Re-ask and update pi-plans workspace config: language, artifact root, graph, reviewer, and criticizer defaults",
374
+ handler: async (args, ctx) => {
375
+ await configPiPlansCommand(args, ctx);
376
+ },
377
+ });
378
+
267
379
  pi.registerCommand("plans-autocomplete-stop", {
268
380
  description: "Stop Auto-complete for the active planning run",
269
381
  handler: async (_args, ctx) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-plans",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
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",
@@ -54,5 +54,20 @@
54
54
  "validate": "node --experimental-strip-types scripts/validate.ts",
55
55
  "test": "node --experimental-strip-types scripts/run-tests.ts",
56
56
  "prepack": "npm run validate && npm test"
57
+ },
58
+ "dependencies": {},
59
+ "devDependencies": {
60
+ "@earendil-works/pi-ai": "0.84.4",
61
+ "@earendil-works/pi-coding-agent": "0.84.4",
62
+ "@earendil-works/pi-server": "0.84.4",
63
+ "@earendil-works/pi-tui": "0.84.4",
64
+ "typebox": "1.3.7",
65
+ "tree-sitter": "^0.25.1",
66
+ "tree-sitter-javascript": "^0.25.0",
67
+ "tree-sitter-python": "^0.25.0",
68
+ "tree-sitter-typescript": "^0.23.2"
69
+ },
70
+ "overrides": {
71
+ "tree-sitter": "^0.25.1"
57
72
  }
58
73
  }
@@ -8,17 +8,18 @@ This skill set is written for the Pi coding agent's documented behavior:
8
8
 
9
9
  - the five skills are contributed by the pi-plans extension and loaded as Pi skills (also invokable as `/skill:<name>`);
10
10
  - skill references and helper sources are resolved relative to the directory containing `SKILL.md`;
11
- - the extension provides these tools: `plans` (workspace state), `ask_choice` (choice prompts), `refine` (reviewer/criticizer subagents), and `execute_plan` (execution handoff);
12
- - `refine` spawns read-only Pi subagents (`pi --mode json -p --no-session --tools read,grep,find,ls`) with isolated context; delegated Reviewer/Criticizer runs show a standalone aggregate overlay titled `Reviewer` or `Criticizer`, close the overlay before returning, and return conclusions to the main session as tool output;
11
+ - Planning and reference analysis run with the extension tools `plans`, `ask_choice`, `refine`, `analyze_refs`, and `execute_plan`;
12
+ - `refine` spawns read-only Pi subagents (`pi --mode json -p --no-session --tools read,grep,find,ls`, plus `code_graph` for both roles when workspace `graph_enabled` is true) with isolated context; delegated Reviewer/Criticizer runs show a standalone aggregate overlay titled `Reviewer` or `Criticizer` (78% × 78% top-center, ≥72 cols, no input row), stream assistant/thinking/tool events into per-lane transcripts with follow-bottom scroll, dismiss on `Esc` (close-only the refiner child keeps running and its result still flows back as tool output), replace any retained finished overlay when a new round begins, and return conclusions to the main session as tool output; `analyze_refs` spawns one read-only subagent per downloaded reference (cwd = that ref's directory) reusing the reviewer role gates, shows the same overlay titled `Refs` in batches of at most 3 lanes, and returns structured per-reference sections for `REF_ANALYSIS.md`;
13
+ - when graph mode is enabled, graph-aware `read`/`edit` overrides are active for indexed source files: `read` returns a capped function digest (≤50 lines, synthetic anonymous entries folded) by default — drill in via `offset/limit` or `code_graph get-function`, and `full: true` is the only whole-file exit (small/zero-function files return full text; safety truncation matches native read); `write`/`edit` stage DB-first mutations until materialized via the `code_graph` tool's `apply` action (same planning/accepted gate as /apply-graph; refused for read-only refiner subagents via the PI_PLANS_REFINER marker; returns a per-file report with counts and a post-apply drift summary, and never changes run status); unexpected fallbacks (`not indexed` / `runtime unavailable` / `config read failed`) are marked at the top of the result while flag-off fallbacks stay unmarked;
13
14
  - the execution loop is extension-managed: remaining verifier items are injected each turn, implementation items emit `[I-###:current]`/`[I-###:implemented|validating]`, and `[DONE:VC-xxx]` markers are tracked with a bottom status bar;
14
- - execution and planning compaction keep Pi's SessionManager as the history owner, group compacted history by implementation item, retain a legal current-I suffix, summarize paired reads as bounded `Read: <path> line <X-Y> Extracted information summary: ...` records, and target `<10%` of the model window after a current-I slice exceeds `20%`; hard-floor cases are recorded instead of looping;
15
+ - execution and planning compaction keep Pi's SessionManager as the history owner; during active pi-plans runs, `session_before_compact` uses a deterministic no-LLM VCC-style summary with `[Session Goal]`, `[Files And Changes]`, `[Commits]`, `[Outstanding Context]`, `[User Preferences]`, and a ranked brief transcript; Pi core owns manual `/compact`, threshold, and overflow scheduling, while pi-plans handles smart tail keep, `keep:N`, stats, and phase-specific run/plan/current-I/checklist context;
15
16
 
16
17
  ## Planning Boundary
17
18
 
18
19
  - Treat the user's request as a planning target, not as write authorization.
19
- - Before the execution handoff, do not edit target source files, docs, configs, package metadata, generated assets, or tests outside the planning artifact directory and the pi-plans state under `.git/pi_plans/`. The extension enforces this for `edit` and `write` while a run is active: only `.git/pi_plans/`, the run's artifact directory, and `~/.cache/pi-plans/` are writable. Bash is not machine-guarded — keep it read-only by discipline (inspection, `git init`, downloads into the cache).
20
+ - Before the execution handoff, do not edit target source files, docs, configs, package metadata, generated assets, or tests outside the planning artifact directory and the pi-plans state under `.git/pi_plans/`. The extension enforces this for `edit` and `write` while a run is active: only `.git/pi_plans/`, the run's artifact directory, `~/.cache/pi-plans/`, and the configured refs root are writable. Bash is not machine-guarded — keep it read-only by discipline (inspection, `git init`, downloads into the cache).
20
21
  - The normal pre-handoff writes are `.git/pi_plans/` state plus planning artifacts under the configured artifact root (default `./docs/pi-plans/...`).
21
- - Large downloaded references belong outside the target repo by default, under `~/.cache/pi-plans/refs/<repo-slug>/<topic>/`; record their paths and evidence in `REF_ANALYSIS.md`.
22
+ - Downloaded references go to the workspace's configured refs root (`refs_root` in `.git/pi_plans/config.json`; unset → ask once via `ask_choice`, recommended `.git/pi-plans/refs/`, second `./refs/`, third `~/.cache/pi-plans/refs/`; persist with the `plans` tool, `set-refs-root`) and their paths and evidence are recorded in `REF_ANALYSIS.md`.
22
23
  - After the user explicitly approves the execution handoff, leave this planning workflow and execute in the extension-managed loop (see Execution Handoff).
23
24
 
24
25
  ## State And Settings
@@ -129,13 +130,27 @@ A refinement round is complete when all reviewer outputs have returned or all cr
129
130
  When the user picks `✓ Accept PLAN_vN and execute it now` in the merged question, mark the plan accepted and call the `execute_plan` tool (or the user runs `/plans-execute`). It re-confirms with the user, then the extension enters execution mode:
130
131
 
131
132
  - every agent turn is injected with the remaining verifier checklist and execution rules (layered simplest implementation, waiting for subprocess-backed verification with backoff 5s -> 10s -> 20s -> 40s -> 80s, then keep polling at 80s and restart at 5s for each new subprocess, no stopgaps, dependency and library discipline, minimum tests);
132
- - execution-phase compaction may proactively compact the current-I slice above 20% of the model window, summarizes the oldest eligible prefix and bounded Read records, preserves a legal recent suffix, and records whether the <10% target was met; Pi still owns threshold, overflow, and manual scheduling;
133
+ - 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-I/checklist context, use smart tail keep and `keep:N`, and never call a model or request proactive current-I compaction;
133
134
  - the read-only guard lifts: full write access returns;
134
135
  - the run status moves to `executing`, then `done` when the last `[DONE:VC-xxx]` marker lands;
135
136
  - `/plans-stop` stops execution; `/plans` shows progress.
136
137
 
137
138
  If the user declines, stay in planning (or stop, per their choice). Never start implementation without the approved handoff.
138
139
 
140
+ ### Post-Execution Continuation
141
+
142
+ When execution completes in an interactive session, the completion message attaches a goal-running continuation block and triggers a new agent turn so the model can enter the implementation-review loop immediately. The interactive-only trigger keeps headless sessions silent (no unconsented subagent cost). The same behavior applies on both completion call sites (the normal `turn_end` completion and the `restoreFromSession` recovery path).
143
+
144
+ The agent then asks one `ask_choice` question for the termination condition of the implementation-review loop:
145
+
146
+ - `autoComplete: false` — suppresses the run-scoped Auto-complete mode for this question.
147
+ - Options (recommended first): 1. until no high-severity finding (hard cap 5 rounds) 2. 1 round 3. 2 rounds 4. 3 rounds.
148
+ - Each refinement round calls `refine` with `role: "reviewer", target: "implementation"`, accepts findings on evidence, applies fixes, re-runs relevant tests, and records progress. The hard cap is 5 rounds regardless of the chosen termination condition.
149
+ - Round audit trail: `decisions.jsonl`, `subagents.jsonl`, and `pi-plans-ameliorate` entries (one at goal start, then one per round) carry `currentRound` for post-hoc verification.
150
+ - Headless sessions skip the prompt entirely; no `pi-plans-ameliorate` entry is appended.
151
+
152
+ `refine` accepts a `target` parameter (`"plan"` default, `"implementation"` for the post-execution loop). The implementation brief anchors findings to the plan's goals and acceptance criteria, explicitly assesses delivery maturity (MVP-only vs. long-term refinement: stopgaps, missing tests, technical debt, production readiness), and tags out-of-scope improvements as low severity.
153
+
139
154
  ## Red Flags
140
155
 
141
156
  Stop and return to the workflow if any of these happen: