---
name: senai-plan
description: Pi Senai Plan stage — research, interview, plan, review
---

# Plan Stage

Turn the mission into an approved implementation plan at `<plan>`.

## Mission type awareness

The mission type comes from the brainstorm (state.json `missionType` / the
brief's `## Mission type` section). It decides what the plan targets:

- **feature / bugfix / upgrade** — normal plan: source files + tests +
  verification steps.
- **docs** — documentation-only: the plan's `## Files` lists `.md` files
  only (README, CHANGELOG, docs/). No source-code changes; the Document
  stage is skipped for this type (docs ARE the implementation).
- **test** — test-only: the plan's `## Files` lists test files only
  (unit / integration / e2e). The plan's `## Verification` MUST end with
  the suite run (e.g. `npm test` all green) — that run is the deliverable.
- **explore** — has NO plan stage. `/senai-plan` refuses to adopt an
  explore brainstorm; if you see an explore decision document, tell the
  user to start a new brainstorm seeded with it instead.

## Sequence

```
scout-1, scout-2, scout-3, scout-4 (parallel) → discussion → AskUserQuestion → planner → plan-overview → reviewer-correctness, reviewer-security, reviewer-tests, reviewer-architecture (parallel) → approval gate
```

**Critical rules:**
- Spawn fresh scouts every run. Do NOT reuse or read scout reports from any previous run folder.
- **Brainstorm handoff** — When the state or stage prompt references a discussion document (`discussionDocPath`), read it BEFORE spawning scouts. It holds the user's decisions: `## Agreed` (follow these), `## Not wanted` (never propose these again — reasons included), `## Open` (resolve these at the AskUserQuestion step). The file is the truth, not chat memory. This works from a fresh session: the path comes from state.json / the compaction summary.
- Do not edit source files in this stage.
- Do not wait for user input except at the AskUserQuestion step and the final approval gate.
- The extension requires valid `.pi/senai/agents.json`, `.pi/senai/files.json`, and `.pi/senai/agents_files.json` before this command runs; if any are missing, tell the user to run the matching `/senai-configure-*` command.

## Subagent conventions

Use the `subagent` tool (provided by `pi-interactive-subagents`) with pi.dev best practices:

- **Context mode** — Use `session-mode: standalone` or `lineage-only` for ALL plan-stage agents (scouts, discussion, planner, plan-overview, reviewers). Never use `fork`: it copies the parent's full conversation into the child and wastes tokens. Give each agent the artifact paths it needs in its task (scout reports, discussion notes, plan file) — the agent reads those files itself.
- **Agent parameter** — Every `subagent()` call MUST include `agent:` with the mapped agent name from the Agent Registry block in your stage prompt — NOT the placeholder built-in names (`scout`, `planner`) used in the examples below. The spawn guard hard-blocks placeholder names when roles are remapped, and a spawn without `agent:` runs as a default agent without the role's mandate and tools.
- **Autonomous completion** — Registry agents generated by pi-senai carry `auto-exit: true`, so the pane closes automatically and the main session receives a completion notification. If you spawn a custom agent without it, explicitly tell the agent to finish and exit after writing its output.
- **Turn / runaway guard** — If your subagent extension supports `max_turns`, set a hard cap:
  - **Scouts:** `15`
  - **Discussion agent:** `15`
  - **Planner:** `25`
  - **Plan-overview writer:** `15`
  - **Reviewers:** `15` each
  With `pi-interactive-subagents`, rely on `auto-exit: true` and `subagent_interrupt` for runaway or stalled agents instead.
- **Explicit output** — Every writer subagent must be told exactly which artifact path to write (`<scoutAngle1>`, `<plan>`, `<reviewCorrectness>`, etc.).
- **Review loops** — If a reviewer reports a blocking issue, do not restart the whole Plan stage. Instead:
  1. **Plan-level issue** (unclear task, missing step, wrong approach) → respawn the **planner** with the reviewer feedback.
  2. **Context issue** (wrong assumption, missing dependency, stale code info) → respawn the relevant **scout** first, then the **planner**.
  3. Re-run only the affected reviewers after the fix.
  4. Go back to `AskUserQuestion` only if the issue reveals a requirement only the user can answer.
- **No isolation parameter** — The subagent tool has no `isolation`/`worktree` parameter; never pass one. Plan-stage agents are read-only on source and each writes only its own artifact file, so parallel writes never collide.
- **Only real tools** — Call only tools that exist in your toolset. For content search use the available search tool, or run `grep` through the shell tool — NEVER invent a tool name (a hallucinated `grep` tool call wasted a turn in a real run).
- **The pane's "N denied" counter is NOT missing tools** — it counts the spawning tools (`subagent`, `subagent_resume`, `subagent_interrupt`, `subagents_list`), which generated agents never get by design (`spawning: false`). It does not mean `write` or `bash` is missing. A genuinely blocked tool returns its reason in the tool result — read that, not the counter.

## Synchronization and checkpoint rules

`pi-interactive-subagents` runs each subagent asynchronously in its own multiplexer pane. The `subagent()` call returns immediately and the agent works in the background; a completion notification is steered back to the main session when the agent finishes. To avoid duplicate spawns and premature approval gates:

1. **Use unique names for every parallel subagent** so you can identify each one in the live subagent widget.
2. **Wait for all completion notifications before proceeding.** After launching parallel agents, do not continue until each one has reported back. Do not assume an agent failed just because its output file is not yet present. Do not create polling tasks or repeated TaskUpdate/status checks while waiting — notifications wake you automatically.
3. **If an expected file is missing, check the live widget first.**
   - If the agent is still shown as `starting`/`active`/`waiting`, wait.
   - If the agent is `stalled`, or you received a failure / `caller_ping`, interrupt it with `subagent_interrupt({ name: "<name>" })` and wait once.
   - `subagent_interrupt` is soft (turn-level) — if the agent stays alive after the interrupt, tell the user to close its pane manually, then respawn with a unique name (e.g. `-retry` suffix). Never leave two agents of the same role running at once.
   - Only respawn after confirming the original run is no longer healthy.
4. **Verify every artifact — a "completed" notice is NOT proof.** Process exit does not mean the artifact was written. On EVERY completion notification, immediately run `test -s <artifactPath>` (bash) for the artifact that subagent was assigned:
   - File exists and is non-empty → proceed to the next step.
   - File missing or empty → do NOT respawn cold. Call `subagent_resume` with the session path from the result message and instruct the agent to write the file. Cold-respawn only if resume fails.
   - Never wait after a completed notification — act on it in the same turn.
   - NEVER ask the user to say "its completed" or to confirm a subagent finished; you own this check.
5. **Never write a subagent's artifact yourself.** If it cannot finish, fix the spawn (agent, tools, task) and relaunch.
6. **Strict checkpoints:**
   - Do not start the discussion agent until **all four** `scout-angle_*.md` files exist.
   - Do not start the planner until `<discussionNotes>` includes the user’s answers and all four scout files exist.
   - **Bugfix missions:** do not start the planner until the deep scout dig (see section 5) is written to the run's scout notes.
   - Do not start the reviewers until `<plan>` and `<planOverview>` exist.
   - Do not present the approval gate until `reviewCorrectness`, `reviewSecurity`, `reviewTests`, and `reviewArchitecture` all exist and the live subagent widget shows no Plan-stage reviewers are still running.

## 1. Parallel scouts

Read the **Spawn Cadence** block in your stage prompt — it tells you the current tier (A = parallel burst, B = staggered, C = batch-2, D = fully serial) and the exact dispatch rule for this run. The block is generated from `.IDE_Plans/pi-senai/spawn-cadence.json` and demotes automatically on rate-limit errors. Each scout must write its own report.

**429 playbook:** if a result says `Sub-agent "X" failed ... 429` (rate limit / provider overload):
1. Wait about 60 seconds (e.g. `sleep 60` via bash) before retrying.
2. Resume the session with `subagent_resume` using the session path from the result — do NOT cold-respawn; a fresh spawn restarts the whole agent and wastes tokens.
3. Only cold-respawn (with a unique `-retry` name) if resume also fails.

- **scout-1** (agent: mapped name for role `scout-1` from the Agent Registry block): Architecture / big-picture reconnaissance for mission `"<mission>"`. Write to `<scoutAngle1>`.
- **scout-2** (agent: mapped name for role `scout-2`): Code Search. Write to `<scoutAngle2>`.
- **scout-3** (agent: mapped name for role `scout-3`): Code Risk / dependency audit. Write to `<scoutAngle3>`.
- **scout-4** (agent: mapped name for role `scout-4`): PRD / documentation audit. Read customer documents such as PRD, RTM, development order, and atomic-function specs. Summarize requirements, acceptance criteria, constraints, and open questions. Write to `<scoutAngle4>`.

Wait for all four to finish, then read the reports. If a report is missing, check the live subagent widget first; only respawn if the agent is stalled or has failed.

## 2. Discussion agent

Spawn one discussion agent (agent: mapped name for role `discussion` from the Agent Registry block) that reads the four scout reports and drafts 2-5 clarifying questions for the user about `"<mission>"`. Write questions and a brief analysis to `<discussionNotes>`.

## 3. AskUserQuestion

Read `<discussionNotes>` and ask the drafted questions using the **AskUserQuestion** tool. Wait for the answers. Do not proceed until the user answers.

**AskUserQuestion format rules (the tool rejects violations):**
- Every question MUST end with `?`.
- The `header` field MUST be at most 12 characters — one short word or acronym (e.g. `Dedup`, `TC-L6`, `Scope`). A real run had calls rejected twice for headers like `isSameDay_ dedup` and `TC-L6 windows`; put the detail in the question text, not the header.
- Keep question text short; long background belongs in `<discussionNotes>`, not the dialog.

## 4. Update discussion notes

Append the user's answers to `<discussionNotes>`.

## 5. Planner

**Checkpoint:** Confirm all four scout reports and `<discussionNotes>` (including user answers) exist before spawning the planner.

**Bugfix deep scout dig (bugfix missions only):** before the planner runs, dispatch ONE deeper scout pass (agent: mapped name for role `scout-2` from the Agent Registry block) seeded with the finalized `mission-brief.md` — its `## Reproduction steps`, `## Expected vs actual`, and `## Root cause` hypothesis sections. The scout verifies the hypothesis against the real code and names the exact files/functions. It writes the dig to `scout-bugfix-dig.md` inside the Plan scouts directory (path in the stage prompt header). Do not start the planner until this dig exists — the planner reads it alongside the four scout reports.

Spawn the planner (agent: mapped name for role `planner` from the Agent Registry block) with the mission, the four scout reports, and `<discussionNotes>`. Write the implementation plan to `<plan>`. The plan must contain concrete, executable tasks.

**Size cap:** keep `<plan>` focused — at most ~15KB. The plan is injected into every later stage prompt, so bloat costs tokens on every turn. Move long detail (full file listings, exhaustive code snippets, long rationales) into referenced files under the plan directory (e.g. `plan/notes-<topic>.md`) and link them from the plan.

**Verification section (required):** `<plan>` MUST end with a `## Verification` section listing the exact commands or steps that prove the mission succeeded (e.g. `npm test`, a named test case, a manual check with expected output). The Deliver stage runs this section as the final gate. A plan without it is incomplete — if a reviewer or you find it missing, send the plan back to the planner.

**Files manifest (required):** `<plan>` MUST carry a `## Files` section with a markdown table listing every file the plan touches — one row per file: `| path | layer | action | reason |` where `path` is project-relative (never absolute, never `..`), `layer` names the architecture layer, and `action` is exactly `create`, `edit`, or `delete`. No duplicate paths. The approve gate parses this table deterministically and hard-blocks plans without a valid manifest — if a reviewer or you find it missing or malformed, send the plan back to the planner.

**Framework field (required):** `<plan>` MUST record the chosen framework in a `## Framework` section — a single framework id from the chirpi framework-library (e.g. `nextjs`, `express`, `django`), or `none` when the project has no framework. When the profiler detected a framework from dependencies or the plan's tech stack names one, the entry must match it exactly; the approve gate hard-blocks missing or contradicting entries.

## 6. Plan overview writer

Spawn the plan-overview writer (agent: mapped name for role `plan-overview` from the Agent Registry block) to read `<plan>` and `<discussionNotes>` and write a user-friendly summary to `<planOverview>`.

## 7. Parallel reviewers

Spawn four reviewers, using the dispatch rule from the **Spawn Cadence** block (same cadence as the scouts — the cadence applies to every parallel subagent burst in this stage). Each writes to its assigned path. On a rate-limit failure (429 / 5xx / stopReason:error), apply the 429 playbook from section 1 (wait ~60s, then `subagent_resume`). Wait for all four to finish and confirm their files exist (non-empty) before the approval gate.

- **reviewer-correctness** → `<reviewCorrectness>`: Is the plan technically correct and complete?
- **reviewer-security** → `<reviewSecurity>`: Security and privacy concerns?
- **reviewer-architecture** → `<reviewArchitecture>`: Does the plan's file and folder layout (the `## Files` manifest paths and layers) match the architecture's layer map and forbidden patterns? Write a blocking issue to `<reviewArchitecture>` for every misplaced file or layer violation.
- **reviewer-tests** → `<reviewTests>`: Validate the plan's test strategy against this checklist. Write a blocking issue to `<reviewTests>` if any item is missing:
  1. `<plan>` ends with a `## Verification` section listing specific commands or named test cases (not "tests pass").
  2. High-risk areas (auth, money, data loss, concurrency) name explicit test cases.
  3. Input validation tests are listed (empty, null, max-length, invalid encoding).
  4. Boundary and edge cases are listed for every numeric / length / range contract.
  5. The test framework name and test path are named (so the implementer does not have to guess).
  6. No public contract is left untested.
  7. Property-based tests are mentioned for pure functions.
  8. Coverage floor (default 80%) and security-critical paths are named.

## 8. Approval gate

**Checkpoint:** Confirm `reviewCorrectness`, `reviewSecurity`, `reviewTests`, and `reviewArchitecture` exist and that no reviewer subagent is still running before presenting the approval gate.

Present the plan, overview, and reviews to the user:

> Plan: `<plan>`. Overview: `<planOverview>`. Reviews: correctness `<reviewCorrectness>`, security `<reviewSecurity>`, tests `<reviewTests>`, architecture `<reviewArchitecture>`. Approve to move to Implement?

Do NOT start Implement until the user approves. Once approved, tell the user to run `/senai-approve`, which will mark the plan approved and automatically start the Implement stage.
