# Pi Planning Workflow

This reference is shared by the `pi-plans` skills. It is a planning workflow only. Implementation after acceptance runs in the extension-managed execution loop.

## Required Pi Context

This skill set is written for the Pi coding agent's documented behavior:

- the five skills are contributed by the pi-plans extension and loaded as Pi skills (also invokable as `/skill:<name>`);
- skill references and helper sources are resolved relative to the directory containing `SKILL.md`;
- Planning and reference analysis run with the extension tools `plans`, `ask_choice`, `refine`, `analyze_refs`, and `execute_plan`;
- `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`;
- 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;
- 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;
- 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; in addition, creating a new planning run (`plans start-run`) proactively requests one pre-plan VCC compaction before the first planning question and resumes the planning turn with a hidden message (default on, `prePlanCompact` in `pi-vcc-config.json`);

## Planning Boundary

- Treat the user's request as a planning target, not as write authorization.
- 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).
- The normal pre-handoff writes are `.git/pi_plans/` state plus planning artifacts under the configured artifact root (default `./docs/pi-plans/...`).
- 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`.
- After the user explicitly approves the execution handoff, leave this planning workflow and execute in the extension-managed loop (see Execution Handoff).

## State And Settings

Before the first planning question, read `references/state-and-config.md` and initialize the target workspace state with the `plans` tool:

```json
{ "action": "init", "workdir": "<target-workdir>" }
```

State lives under the workspace's resolved git common dir as `.git/pi_plans/` (auto-ignored, no `.gitignore` entries; the tool auto-runs `git init` when the workdir safely has no repository). The target workspace is the current working directory unless the user explicitly names another repository.

If `language.tag` is missing from `.git/pi_plans/config.json`, ask the language setting question (via `ask_choice`) before any product question. Persist it with `plans` (`set-language`); this question does not count against the planning-question limit.

If `artifact_root_source` is missing from `.git/pi_plans/config.json` or is `unset`, ask the planning docs location question (via `ask_choice`) before any product question. Persist it with `plans` (`set-artifact-root`); this question does not count against the planning-question limit.

Reviewer and criticizer settings also live in `config.json`. If a role's mode is missing/invalid or its `confirmed_at` is `null` when the role is about to run, ask the matching role-setting or model-confirmation question (via `ask_choice`), persist with `plans` (`set-role`), and then run the `refine` tool. The `refine` tool refuses to spawn until the gates pass.

## First-Turn Contract

1. Inspect the target Git repository read-only before asking product questions. Prefer `rg`/`grep` when available, then focused file reads, `git status`, `git log`, existing tests, and user-provided logs.
2. If a question can be answered from the repo, answer it from evidence instead of asking the user.
3. After required language and planning-docs-location setup, the first user-facing planning response must be one `ask_choice` question, not a completed plan or implementation.
4. Ask one question per message. Do not batch multiple decisions into one prompt.

## Evidence Ladder

Resolve unknowns in this order:

1. Codebase evidence.
2. Cited web or reference evidence.
3. User choice.

When the recommended option depends on a web-verifiable claim, search first (websearch skill when installed; otherwise `curl`, `gh`, or other bash tools already available) and cite the source in the eventual plan. Do not present a recommendation backed only by an unchecked assumption.

## Choice Prompt Format

Every user-facing planning or refinement question goes through the `ask_choice` tool:

- `options`: ordered options, recommended option first with `recommended: true` (exactly one), each with the tradeoff that matters in `description`;
- do not add `Other` or `Auto-complete` yourself — the tool appends `Other…` second-last and `Auto-complete` last;
- pass `autoComplete: false` for the merged accept/execute question — it contains the execution approval, so Auto-complete never appears there — and for any install waiver, publishing, deployment, merge, push, credential, or external-state question. Auto-complete may choose the recommended planning or refinement option only.
- When the user selects Auto-complete, it remains active for the current planning run: later eligible questions use their recommended options automatically, and the extension queues one deduplicated follow-up if the model stops after an auto-completed answer. `/plans-autocomplete-stop` disables it; session restore may reactivate it only for the same active run while its status is `planning`.

Answers are recorded automatically in the active run's `decisions.jsonl`. You must still maintain `DECISIONS.md` in the artifact directory (summary table of questions, options, answers, answer sources, open assumptions).

## Required Artifact Directory

Create a run only after initial read-only inspection makes the topic clear:

```json
{ "action": "start-run", "workdir": "<target-workdir>", "topic": "<short topic>", "skill": "<skill-name>", "requestText": "<original request>" }
```

The tool creates the configured artifact directory root (default `./docs/pi-plans/YYYY-MM-DD-<topic>/`) and the private run state `.git/pi_plans/runs/<run-id>/`, and stores the active run pointer. Use a short lowercase slug for the topic. Keep paths stable once written.

`DECISIONS.md` records: original request; repository evidence inspected; each question, options, selected answer, and whether it came from the user or Auto-complete; assumptions still open; external sources consulted; language, reviewer, and criticizer settings used.

## Final Scope Confirmation

Before writing `PLAN_v1.md`, ask the mandatory final scope confirmation via `ask_choice` (it does not count against the skill's planning-question limit):

1. `No more requirements` — the scope is ready for `PLAN_v1.md` (recommended).
2. `Add more requirements` — capture additional constraints before drafting.
3. `Other`.
4. `Auto-complete`.

If the user adds requirements, resolve only the necessary follow-up questions, then repeat the final scope confirmation.

## Plan Artifact Requirements

Every `PLAN_vN.md` must include stable IDs that are never recycled across revisions: goals and non-goals; requirements and constraints; implementation items; affected paths; dependencies and sequencing; risks and mitigations; acceptance criteria; verification steps; repo and external evidence; resolved decisions; revision ledger.

Every plan version must include a dedicated `## Verifier Checklist` section. Each item is a Markdown checkbox of the exact shape:

```markdown
- [ ] `VC-001` covers `I-001`; pass condition: ...; evidence: ...; metric: <threshold or reason not quantified>.
```

The execution loop parses `- [ ] \`VC-###\`` items and tracks `[DONE:VC-###]` markers, so keep IDs on the checkbox line. Use `references/plan-artifact-template.md` when drafting.

## Refinement

After each plan version, ask one merged accept/execute question via `ask_choice` with `autoComplete: false` — it contains the execution approval, so Auto-complete never appears. Options:

1. `✓ Accept PLAN_vN and execute it now` — mark the plan accepted (`plans set-status accepted`), then call the `execute_plan` tool.
2. `Accept PLAN_vN, don't execute yet` — mark accepted; resume later via `/plans-execute`.
3. `Run another round: <the level's default next refine mode>` — only while the level's default sequence is unfinished.

The recommended option follows the skill level's default sequence: while the default rounds are unfinished it is option 3's default next mode (`plan-small`: `Criticizer`; `plan-normal`: `Reviewer` then `Criticizer`; `plan-big`: three concurrent reviewers (`refine` with `reviewers: 3`) then `Criticizer`); once the default sequence is complete it is option 1.

If the user selects `Reviewer` or `Criticizer`, run the `refine` tool with the plan path and any focus. Reviewer output consolidates into `PLAN_vN_reviewer_comments.md` with findings IDs, severity, affected plan IDs, evidence, impact, recommended fix, and disposition. Revise the next plan only for findings accepted on evidence.

### Concurrent Reviewers (big plans)

A big-plan reviewer round runs three independent reviewer subagents (`reviewers: 3`); each gets its own emphasis lens but forms its own priorities. After they return, merge and dedupe their findings into one consolidated `PLAN_vN_reviewer_comments.md`, keeping each finding's source reviewer, severity, evidence, and disposition, and surface at most five high-priority comments to the user. Treat agreement between independent reviewers as stronger evidence, not as authority; every accepted finding still needs repo or reference evidence.

### Criticizer Rounds

Present each criticizer question with `ask_choice` (one call per question, in the configured language). Before each question, summarize the original criticism in at most three sentences and highlight the most important point. Do not revise the plan until every criticizer question has a recorded answer.

### Round Lifecycle

A refinement round is complete when all reviewer outputs have returned or all criticizer questions have answers. In the same turn: consolidate, accept or reject each finding on evidence (the user may override any disposition), revise to `PLAN_v(N+1).md` when accepted items require it (copy, edit only the new version, update the revision ledger and verifier checklist), then immediately ask the next merged accept/execute question. Never end a turn merely because a round completed.

## Execution Handoff

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:

- 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);
- 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;
- the read-only guard lifts: full write access returns;
- the run status moves to `executing`, then `done` when the last `[DONE:VC-xxx]` marker lands;
- `/plans-stop` stops execution; `/plans` shows progress.

If the user declines, stay in planning (or stop, per their choice). Never start implementation without the approved handoff.

### Execution Goal-Wait

In TUI/RPC, automatic goal-wait is evaluated only at `agent_settled`, after
Pi has finished natural tool continuation, retries, and compaction. The
extension rechecks that the same execution is active and incomplete, the
session is idle, and neither pending input nor compaction owns continuation.
Each eligible settled cycle can send at most one hidden custom message with
the current execution rules and remaining VC checklist. Tool `turn_end`
events only update progress; they never prequeue goal-wait reminders.

No-progress and literal `waiting for` counters advance only on eligible
settled cycles. Real marker progress resets both; thresholds remain 3 and 6.
User interruption and final model errors also pause continuation. Genuine
interactive/RPC user input or `/plans-execute` can resume a paused active
execution without losing verified VCs; extension input cannot unpause it.
New-plan handoffs and the `execute_plan` tool still require explicit approval.
Completion, stop, and session replacement invalidate the extension's wake
identity without clearing user or other-extension queues. Print/JSON
single-shot sessions keep VC tracking and completion but never auto-wake;
use RPC for persistent headless execution.

### Post-Execution Continuation

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).

The agent then asks two `ask_choice` questions (each single-question, `autoComplete: false`) to configure the implementation-review loop:

1. **Termination condition** (questionId `termination-condition`, recommended first: goal wait) — options: 1. goal wait: continue until no unpassed VCs remain (auto-continue each round) 2. until no high-severity finding (hard cap 5 rounds) 3. 1 round 4. 2 rounds 5. 3 rounds.
2. **Reviewer count** (questionId `impl-review-reviewer-count`, `allowOther: false`, pure digit labels `1`/`2`/`3`, recommended first): "How many concurrent reviewers should each implementation-review round use?" The recommended default follows the run's skill: `plan-big` / `plan-with-refs` → 3, others → 1.

Both answers persist TOGETHER in one `plans record-checkpoint` (`transition: "implementation-review-configured"`, `terminationCondition` + `reviewerCount`). Each refinement round calls `refine` with `role: "reviewer", target: "implementation", reviewers: <configured reviewerCount>`; an omitted `reviewers` falls back to the run's configured `reviewerCount` from the checkpoint, so restarts and worktree migrations never silently revert 2/3 to 1. Each round 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. Multi-reviewer rounds (2 or 3) consolidate like big-plan rounds: merge and dedupe findings into one `PLAN_vN_reviewer_comments.md`, keep each finding's source reviewer, severity, evidence, and disposition, and surface at most five high-priority findings. Crash recovery: if the process dies after one or both answers were recorded in `decisions.jsonl` but before the combined write, `/resume-plans` rebuilds the answered configuration from the ledger, asks only the missing question(s), and then performs the single combined write (the re-ask guard rejects duplicate configuration writes while the fields are already set).
- 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.
- Headless sessions skip the prompt entirely; no `pi-plans-ameliorate` entry is appended.

`refine` records each round and lane outcome durably (successful outputs are persisted to run-state files before the tool result returns) and accepts `resumeRoundId` to resume an interrupted round lane-by-lane: completed lanes are reused from their persisted outputs and never re-run; a round id is never reused across plan versions.

## Resuming (`/resume-plans`)

After a restart or in a fresh session, `/resume-plans` (interactive only) restores the repository's working plan in the current session: the unfinished active run wins; otherwise a unique candidate resumes directly and multiple candidates get a chooser. It resumes unfinished planning (re-asks the pending question with the same `questionId`, never re-asks answered decisions), reviewing (resumes interrupted rounds via `refine resumeRoundId`, consolidates completed ones), execution (durable approval: unchanged plan digest keeps the authorization — a changed HEAD re-verifies old VCs first; legacy runs without checkpoints must re-approve), and the implementation-review loop (asks the termination condition and reviewer count only when they were never chosen — answered decisions are rebuilt from the ledger, never re-asked). While the loop is live, the pi-plans panel stays alive as a compact impl-review box (round count, reviewer count or "config pending", termination condition) and the status line mirrors it; once the checkpoint phase flips to `completed` the panel unregisters and the status line shows `(done)`. Linked worktrees share candidates; cross-worktree resumes confirm, copy artifacts without overwriting, reset approval and VC validity, and restart round counts. Record semantic boundaries with `plans record-checkpoint` (`plan-written`, `review-consolidated`, `implementation-review-configured`, `implementation-round-finished`, `completed` with evidence).

`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.

## Red Flags

Stop and return to the workflow if any of these happen:

- implementing before the approved execution handoff;
- running `refine` without first asking the merged accept/execute question, or before the role gates pass;
- ending a turn after a completed refinement round without asking the next merged accept/execute question;
- storing planning settings outside the target workspace's `.git/pi_plans/` state directory;
- asking multiple planning questions in one message, or asking them outside `ask_choice`;
- writing `PLAN_v1.md` before final scope confirmation;
- accepting vague answers that contradict repo or reference evidence;
- treating a reviewer or criticizer as authority instead of evidence;
- offering Auto-complete for execution, install, deploy, merge, push, or destructive cleanup approval.
