pi-plans 0.5.7 → 0.7.0

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 (112) hide show
  1. package/CONTRIBUTING.md +126 -0
  2. package/README.md +49 -39
  3. package/agents/ref-analyst.md +7 -4
  4. package/agents/reviewer.md +12 -3
  5. package/index.ts +74 -40
  6. package/package.json +2 -1
  7. package/references/pi-planning-workflow.md +45 -58
  8. package/references/plan-artifact-template.md +71 -60
  9. package/references/state-and-config.md +63 -47
  10. package/scripts/bench/pi-adapter/pi_plans_bench.py +33 -22
  11. package/scripts/bench/pi-adapter/rpc_driver.mjs +4 -4
  12. package/scripts/run-tests.ts +12 -1
  13. package/scripts/validate.ts +22 -10
  14. package/skills/debug-and-plan/SKILL.md +4 -4
  15. package/skills/plan-big/SKILL.md +5 -5
  16. package/skills/plan-normal/SKILL.md +5 -5
  17. package/skills/plan-small/SKILL.md +5 -5
  18. package/skills/plan-with-refs/SKILL.md +8 -8
  19. package/skills/planning/SKILL.md +1 -1
  20. package/src/ask-form.ts +4 -4
  21. package/src/auditor.ts +126 -0
  22. package/src/auto-approve.ts +1 -1
  23. package/src/autocomplete.ts +19 -17
  24. package/src/code-graph/commands.ts +2 -2
  25. package/src/code-graph/community.ts +1 -1
  26. package/src/code-graph/paths.ts +1 -1
  27. package/src/code-graph/watch.ts +2 -2
  28. package/src/compaction.ts +3 -3
  29. package/src/config-command.ts +154 -76
  30. package/src/dashboard.ts +257 -0
  31. package/src/exec.ts +709 -705
  32. package/src/global-state.ts +304 -0
  33. package/src/guard.ts +16 -3
  34. package/src/messaging.ts +44 -0
  35. package/src/plan.ts +421 -112
  36. package/src/query-hook.ts +4 -4
  37. package/src/refine-prompts.ts +14 -72
  38. package/src/refine-ui-helpers.ts +24 -5
  39. package/src/refine-ui-state.ts +1 -1
  40. package/src/refine-ui.ts +1 -1
  41. package/src/resume-command.ts +40 -130
  42. package/src/resume.ts +15 -17
  43. package/src/role-panels.ts +542 -0
  44. package/src/run-context.ts +5 -4
  45. package/src/run-picker.ts +98 -0
  46. package/src/state.ts +380 -77
  47. package/src/subagent.ts +32 -1
  48. package/src/task-tool.ts +100 -0
  49. package/src/tasks.ts +189 -0
  50. package/src/thinking-levels.ts +67 -0
  51. package/src/ui-language.ts +3 -54
  52. package/src/workflow-state.ts +78 -57
  53. package/tests/analyze-refs.test.ts +35 -18
  54. package/tests/ask-choice-pros-cons.test.ts +147 -0
  55. package/tests/ask-choice-schema.test.ts +0 -12
  56. package/tests/ask-choice.test.ts +2 -49
  57. package/tests/ask-form-tool.test.ts +4 -5
  58. package/tests/ask-form.test.ts +2 -2
  59. package/tests/auditor.test.ts +111 -0
  60. package/tests/auto-approve.test.ts +7 -10
  61. package/tests/autocomplete.test.ts +8 -11
  62. package/tests/code-graph-apply-action.test.ts +2 -2
  63. package/tests/code-graph-commands.test.ts +2 -2
  64. package/tests/code-graph-index.test.ts +2 -2
  65. package/tests/code-graph-loop.e2e.test.ts +1 -1
  66. package/tests/code-graph-mutations.test.ts +1 -1
  67. package/tests/code-graph-rollback.test.ts +1 -1
  68. package/tests/code-graph-v05.test.ts +2 -2
  69. package/tests/compaction.test.ts +1 -1
  70. package/tests/config-command.test.ts +103 -100
  71. package/tests/dashboard.test.ts +268 -0
  72. package/tests/exec-lifecycle.test.ts +181 -115
  73. package/tests/exec-panel-lifecycle.test.ts +106 -251
  74. package/tests/exec.test.ts +617 -1706
  75. package/tests/execute-plan.test.ts +44 -19
  76. package/tests/extension-load.test.ts +48 -0
  77. package/tests/global-state.test.ts +371 -0
  78. package/tests/graph-aware-file-tools.test.ts +5 -5
  79. package/tests/guard.test.ts +1 -1
  80. package/tests/multi-run.test.ts +184 -0
  81. package/tests/plan.test.ts +139 -62
  82. package/tests/plans.test.ts +7 -79
  83. package/tests/refine-prompts.test.ts +20 -71
  84. package/tests/refine-resume.test.ts +27 -22
  85. package/tests/refine-ui.test.ts +6 -15
  86. package/tests/resume-lifecycle.test.ts +37 -22
  87. package/tests/resume.test.ts +43 -88
  88. package/tests/role-panels.test.ts +391 -0
  89. package/tests/run-context.test.ts +1 -1
  90. package/tests/run-ownership.test.ts +1 -1
  91. package/tests/stale-ctx.test.ts +218 -0
  92. package/tests/state.test.ts +151 -32
  93. package/tests/subagent-thinking.test.ts +65 -0
  94. package/tests/subagent-usage.test.ts +1 -1
  95. package/tests/task-tool.test.ts +61 -0
  96. package/tests/thinking-levels.test.ts +77 -0
  97. package/tests/ui-language.test.ts +2 -17
  98. package/tests/workflow-state.test.ts +17 -99
  99. package/tools/analyze-refs.ts +67 -32
  100. package/tools/ask-choice.ts +19 -49
  101. package/tools/code-graph.ts +2 -2
  102. package/tools/execute-plan.ts +63 -33
  103. package/tools/graph-aware-file-tools.ts +6 -4
  104. package/tools/plans.ts +40 -66
  105. package/tools/refine.ts +101 -164
  106. package/agents/criticizer.md +0 -18
  107. package/scripts/bench/pi-adapter/__pycache__/pi_plans_bench.cpython-312.pyc +0 -0
  108. package/src/panel.ts +0 -473
  109. package/src/termination-prompt.ts +0 -73
  110. package/tests/goal-wait.test.ts +0 -269
  111. package/tests/panel-i-zero.test.ts +0 -420
  112. package/tests/panel.test.ts +0 -355
@@ -17,7 +17,7 @@ const EXPECTED_SKILLS = new Set([
17
17
  "debug-and-plan",
18
18
  ]);
19
19
  const REQUIRED_REFERENCES = ["pi-planning-workflow.md", "plan-artifact-template.md", "state-and-config.md"];
20
- const REQUIRED_AGENTS = ["reviewer.md", "criticizer.md"];
20
+ const REQUIRED_AGENTS = ["reviewer.md"];
21
21
  const REQUIRED_TOOL_FILES = [
22
22
  "tools/plans.ts",
23
23
  "tools/ask-choice.ts",
@@ -26,6 +26,7 @@ const REQUIRED_TOOL_FILES = [
26
26
  "tools/execute-plan.ts",
27
27
  "tools/code-graph.ts",
28
28
  "src/state.ts",
29
+ "src/global-state.ts",
29
30
  "src/guard.ts",
30
31
  "src/plan.ts",
31
32
  "src/subagent.ts",
@@ -69,7 +70,7 @@ function validateSkill(dir: string): void {
69
70
  if (!description || description.length > 1024) fail(`${file}: invalid description length`);
70
71
  if (!/Use|MUST USE/.test(description)) fail(`${file}: description should include routing language`);
71
72
 
72
- const requiredPhrases = ["Auto-complete", "ask_choice", "refine", "language", "reviewer", "criticizer", ".git/pi_plans"];
73
+ const requiredPhrases = ["Auto-complete", "ask_choice", "refine", "language", "reviewer", ".git/pi-plans", "drawback"];
73
74
  for (const phrase of requiredPhrases) {
74
75
  if (!text.includes(phrase)) fail(`${file}: missing required phrase ${phrase!}`);
75
76
  }
@@ -77,14 +78,24 @@ function validateSkill(dir: string): void {
77
78
 
78
79
  function validateDefaultConfig(): void {
79
80
  const source = fs.readFileSync(path.join(ROOT, "src", "state.ts"), "utf8");
80
- if (!source.includes('"pi-plans-reviewer"') || !source.includes('"pi-plans-criticizer"')) {
81
- fail("src/state.ts: name_prefix defaults missing");
82
- }
83
- if (source.includes("effort")) fail("src/state.ts: per-role effort must not exist");
84
- if (!source.includes('"delegated-subagent"')) fail("src/state.ts: delegated-subagent default missing");
85
81
  if (!source.includes('artifact_root: DEFAULT_ARTIFACT_ROOT')) fail("src/state.ts: artifact_root default missing");
86
82
  if (!source.includes('artifact_root_source: "unset"')) fail("src/state.ts: artifact_root_source default missing");
87
83
  if (!source.includes('artifact_root_updated_at: null')) fail("src/state.ts: artifact_root_updated_at default missing");
84
+ // The reviewer role defaults live in the GLOBAL config module (v0.7.0):
85
+ // one reviewer, one file, shared across workspaces.
86
+ const globalSource = fs.readFileSync(path.join(ROOT, "src", "global-state.ts"), "utf8");
87
+ if (!globalSource.includes('"pi-plans-reviewer"')) {
88
+ fail("src/global-state.ts: reviewer name_prefix default missing");
89
+ }
90
+ if (!globalSource.includes('"delegated-subagent"')) {
91
+ fail("src/global-state.ts: delegated-subagent default missing");
92
+ }
93
+ if (!globalSource.includes('thinking_level')) {
94
+ fail("src/global-state.ts: reviewer thinking_level field missing");
95
+ }
96
+ if (!globalSource.includes("PI_PLANS_GLOBAL_DIR")) {
97
+ fail("src/global-state.ts: PI_PLANS_GLOBAL_DIR override missing");
98
+ }
88
99
  }
89
100
 
90
101
  interface PackageJson {
@@ -131,7 +142,7 @@ function validatePackageMetadata(): void {
131
142
  if (!skills.has("./skills")) fail("package.json: pi.skills must include ./skills");
132
143
 
133
144
  const files = new Set((pkg.files ?? []).map(normalizePackageEntry));
134
- for (const required of ["README.md", "LICENSE", "index.ts", "agents", "references", "scripts", "skills", "src", "tests", "tools"]) {
145
+ for (const required of ["README.md", "LICENSE", "CONTRIBUTING.md", "index.ts", "agents", "references", "scripts", "skills", "src", "tests", "tools"]) {
135
146
  if (!files.has(required)) fail(`package.json: files must include ${required}`);
136
147
  }
137
148
  for (const excluded of ["!scripts/bench/vendor", "!scripts/bench/results"]) {
@@ -153,6 +164,7 @@ const PACK_BLACKLIST_PREFIXES = ["scripts/bench/vendor/", "scripts/bench/results
153
164
  const REQUIRED_PACK_ENTRIES = [
154
165
  "README.md",
155
166
  "LICENSE",
167
+ "CONTRIBUTING.md",
156
168
  "index.ts",
157
169
  "package.json",
158
170
  "agents/reviewer.md",
@@ -234,8 +246,8 @@ function main(): void {
234
246
  for (const ref of REQUIRED_REFERENCES) {
235
247
  const file = path.join(ROOT, "references", ref);
236
248
  if (!fs.existsSync(file)) fail(`missing reference ${ref}`);
237
- if (!fs.readFileSync(file, "utf8").includes(".git/pi_plans")) {
238
- fail(`${ref}: missing .git/pi_plans state location`);
249
+ if (!fs.readFileSync(file, "utf8").includes(".git/pi-plans")) {
250
+ fail(`${ref}: missing .git/pi-plans state location`);
239
251
  }
240
252
  }
241
253
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: debug-and-plan
3
- description: Diagnose failures before creating a Pi plan. MUST USE for bugs, CI failures, test failures, regressions, incidents, broken behavior, root cause, RCA, or debug-why requests before deciding whether to plan; preserve language, reviewer, and criticizer settings in `.git/pi_plans/config.json`; exclude ordinary feature planning, direct implementation-only, factual/explanation, trivial command-only, or explicit no-plan requests.
3
+ description: Diagnose failures before creating a Pi plan. MUST USE for bugs, CI failures, test failures, regressions, incidents, broken behavior, root cause, RCA, or debug-why requests before deciding whether to plan; preserve the workspace language settings in `.git/pi-plans/config.json` and the reviewer role in the global config (`~/.pi/pi-plans/config.json`); exclude ordinary feature planning, direct implementation-only, factual/explanation, trivial command-only, or explicit no-plan requests.
4
4
  ---
5
5
 
6
6
  # Debug And Plan
@@ -9,13 +9,13 @@ Use this skill for problem or failure inputs that need diagnosis before planning
9
9
 
10
10
  ## Pi Setup
11
11
 
12
- Read `../../references/pi-planning-workflow.md` and `../../references/state-and-config.md` — both normative — and follow their setup, state, `language`, and reviewer/criticizer rules. Initialize workspace state with the `plans` tool (`action: "init"`); state lives in `.git/pi_plans/`. Ask every question with the `ask_choice` tool (batch related questions into one `questions: [...]` form call, 2-8 items; scope/handoff stays single-question with `autoComplete: false`); run refinement rounds with the `refine` tool.
12
+ Read `../../references/pi-planning-workflow.md` and `../../references/state-and-config.md` — both normative — and follow their setup, state, `language`, and reviewer rules. Initialize workspace state with the `plans` tool (`action: "init"`); state lives in `.git/pi-plans/`. Ask every question with the `ask_choice` tool (batch related questions into one `questions: [...]` form call, 2-8 items; scope/handoff stays single-question with `autoComplete: false`); run refinement rounds with the `refine` tool.
13
13
 
14
14
  ## Diagnostic Workflow
15
15
 
16
16
  1. Inspect available evidence first: repository files, logs, tests, command output, stack traces, recent diffs, CI output, environment details, and user-provided symptoms.
17
17
  2. Produce an in-message RCA summary before asking whether to plan. Use at most 5 Whys. Stop with `unknown` when evidence is insufficient; do not invent a cause.
18
- 3. Ask one `ask_choice` question in the configured language whose preamble includes the RCA summary, with these options:
18
+ 3. Ask one `ask_choice` question in the configured language whose preamble includes the RCA summary, with these options. Every option you write carries a `description` of `✓ <advantage> / ✗ <drawback>` in the configured language, kept terse:
19
19
  1. `Create the scoped fix plan` — recommended when evidence supports a planning path.
20
20
  2. `Stop after RCA` — keep the diagnosis only.
21
21
  3. `Other` / 4. `Auto-complete` are added by the tool.
@@ -32,4 +32,4 @@ Do not ask the user to choose the level unless the evidence supports two materia
32
32
 
33
33
  ## PROBLEM_ANALYSIS.md
34
34
 
35
- After opt-in, create the selected planning run's `.git/pi_plans` state and public artifact directory (`plans` action `start-run`), then write `PROBLEM_ANALYSIS.md` before `PLAN_v1.md`. Include: original problem; symptoms and reproduction status; evidence inspected; RCA summary and 5 Whys (ending early with `unknown` when evidence stops); suspected root cause and confidence; planning skill selected and why; language, reviewer, and criticizer settings used; open diagnostic gaps the plan must address. Pass the original problem, RCA summary, evidence, and `PROBLEM_ANALYSIS.md` path into the selected planning skill.
35
+ After opt-in, create the selected planning run's `.git/pi-plans` state and public artifact directory (`plans` action `start-run`), then write `PROBLEM_ANALYSIS.md` before `PLAN_v1.md`. Include: original problem; symptoms and reproduction status; evidence inspected; RCA summary and 5 Whys (ending early with `unknown` when evidence stops); suspected root cause and confidence; planning skill selected and why; language, reviewer, and reviewer settings used; open diagnostic gaps the plan must address. Pass the original problem, RCA summary, evidence, and `PROBLEM_ANALYSIS.md` path into the selected planning skill.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: plan-big
3
- description: Create a large Pi plan before implementation. Use for open-ended or high-risk repo efforts needing 10 or more planning questions, web research, concurrent reviewer or criticizer refinement, and refinement until convergence; exclude direct implementation-only, factual/explanation, trivial command-only, or explicit no-plan requests.
3
+ description: Create a large Pi plan before implementation. Use for open-ended or high-risk repo efforts needing 10 or more planning questions, web research, concurrent reviewer refinement (findings plus questions), and refinement until convergence; exclude direct implementation-only, factual/explanation, trivial command-only, or explicit no-plan requests.
4
4
  ---
5
5
 
6
6
  # Plan Big
@@ -9,16 +9,16 @@ Use this skill when the user wants a large, high-risk, or open-ended plan before
9
9
 
10
10
  ## Pi Setup
11
11
 
12
- Read `../../references/pi-planning-workflow.md` and `../../references/state-and-config.md` — both normative — and follow their setup, state, `language`, and reviewer/criticizer rules. Initialize workspace state with the `plans` tool (`action: "init"`); state lives in `.git/pi_plans/`. Ask every question with the `ask_choice` tool; run refinement rounds with the `refine` tool.
12
+ Read `../../references/pi-planning-workflow.md` and `../../references/state-and-config.md` — both normative — and follow their setup, state, `language`, and reviewer rules. Initialize workspace state with the `plans` tool (`action: "init"`); state lives in `.git/pi-plans/`. Ask every question with the `ask_choice` tool; run refinement rounds with the `refine` tool.
13
13
 
14
14
  ## Depth Contract
15
15
 
16
16
  - Inspect the target Git repo read-only before the first product question.
17
- - Ask at least 10 planning questions; no maximum — stop only when the decision tree is genuinely resolved. Each via `ask_choice` (recommended option first; the tool adds `Other` second-last and `Auto-complete` last). Phase them in batches of up to 8: submit ONE `questions: [...]` form call per phase, think about the answers, then continue with the next batch or follow-ups.
17
+ - Ask at least 10 planning questions; no maximum — stop only when the decision tree is genuinely resolved. Each via `ask_choice` (recommended option first; the tool adds `Other` second-last and `Auto-complete` last). Every option you write carries a `description` of `✓ <advantage> / ✗ <drawback>` in the configured language, kept terse — the user chooses by weighing what each option gains against what it costs. Phase them in batches of up to 8: submit ONE `questions: [...]` form call per phase, think about the answers, then continue with the next batch or follow-ups.
18
18
  - Batch protocol (0.4.0): when a round has several questions, submit them together as one `ask_choice` call with `questions: [...]` (2-8 items, recommended option first per question) — the tool opens one tabbed multiple-choice form with a submit page instead of asking one at a time. After the batch returns, think about the answers, then follow up in later calls (batch again for 2+ related follow-ups; single `question` for one). `Esc` on the form returns the answered subset as partial answers — continue with what you got and re-ask only what matters. The final scope confirmation and the execution handoff are ALWAYS single-question calls with `autoComplete: false`; batches reject those questions.
19
- - Use web research during both brainstorming and refinement when outside facts, patterns, or ecosystem constraints matter, and cite sources in the plan.
19
+ - Use web research during both brainstorming and refinement when outside facts, patterns, or ecosystem constraints matter, and cite sources in the plan. Optionally (never required) you may also search 1–2 named references — a paper (e.g. arXiv), an engineering blog post, or another repository — whose technique or measurements strengthen the plan's reasoning; cite their URLs in the plan's Evidence section. This optional reference search does not count against the planning-question limit and never requires downloading or analyzing material (that is plan-with-refs' job).
20
20
  - Ask the final scope confirmation, then write `PLAN_v1.md` per `../../references/plan-artifact-template.md`.
21
- - After each plan version, ask the merged accept/execute question via `ask_choice` with `autoComplete: false` — never run `refine` unless the user picked another round at that question. Default sequence: one `Reviewer` round as three concurrent independent reviewers (`refine` with `reviewers: 3`, consolidated by the main agent per the shared workflow), then one `Criticizer` round; afterwards the recommended option is `✓ Accept & execute now` in the merged accept/execute question. Beyond the default sequence, refine until convergence on high-priority findings, unresolved questions, or evidence gaps; surface at most five per round. Then the merged accept/execute question (ask_choice with `autoComplete: false`: ✓ Accept & execute now / Accept, don't execute yet / another round) and the `execute_plan` tool.
21
+ - After each plan version, ask the merged accept/execute question via `ask_choice` with `autoComplete: false` — never run `refine` unless the user picked another round at that question. Default sequence: one reviewer round as three concurrent independent reviewers (`refine` with `reviewers: 3`), each returning findings (`F-###`) and up to five questions (`Q-1..Q-5`); consolidate per the shared workflow, ask every question with `ask_choice`, record the answers, then revise. Afterwards the recommended option is `✓ Accept & execute now` in the merged accept/execute question. Beyond the default sequence, refine until convergence on high-priority findings, unresolved questions, or evidence gaps; surface at most five per round. Then the merged accept/execute question (ask_choice with `autoComplete: false`: ✓ Accept & execute now / Accept, don't execute yet / another round) and the `execute_plan` tool.
22
22
 
23
23
  ## Fit
24
24
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: plan-normal
3
- description: Create a researched Pi plan before implementation. Use for broad or risky repo changes needing 5 to 10 planning questions, web research, reviewer or criticizer refinement, and bounded refinement; exclude direct implementation-only, factual/explanation, trivial command-only, or explicit no-plan requests.
3
+ description: Create a researched Pi plan before implementation. Use for broad or risky repo changes needing 5 to 10 planning questions, web research, reviewer refinement (findings plus questions), and bounded refinement; exclude direct implementation-only, factual/explanation, trivial command-only, or explicit no-plan requests.
4
4
  ---
5
5
 
6
6
  # Plan Normal
@@ -9,16 +9,16 @@ Use this skill when the user wants a substantive plan before a repository change
9
9
 
10
10
  ## Pi Setup
11
11
 
12
- Read `../../references/pi-planning-workflow.md` and `../../references/state-and-config.md` — both normative — and follow their setup, state, `language`, and reviewer/criticizer rules. Initialize workspace state with the `plans` tool (`action: "init"`); state lives in `.git/pi_plans/`. Ask every question with the `ask_choice` tool; run refinement rounds with the `refine` tool.
12
+ Read `../../references/pi-planning-workflow.md` and `../../references/state-and-config.md` — both normative — and follow their setup, state, `language`, and reviewer rules. Initialize workspace state with the `plans` tool (`action: "init"`); state lives in `.git/pi-plans/`. Ask every question with the `ask_choice` tool; run refinement rounds with the `refine` tool.
13
13
 
14
14
  ## Depth Contract
15
15
 
16
16
  - Inspect the target Git repo read-only before the first product question.
17
- - Ask 5 to 10 planning questions via `ask_choice` (recommended option first; the tool adds `Other` second-last and `Auto-complete` last). Submit the first batch of up to 8 as ONE `questions: [...]` form call, think about the answers, then follow up in later batches (2+ related questions) or single-question calls.
17
+ - Ask 5 to 10 planning questions via `ask_choice` (recommended option first; the tool adds `Other` second-last and `Auto-complete` last). Every option you write carries a `description` of `✓ <advantage> / ✗ <drawback>` in the configured language, kept terse — the user chooses by weighing what each option gains against what it costs. Submit the first batch of up to 8 as ONE `questions: [...]` form call, think about the answers, then follow up in later batches (2+ related questions) or single-question calls.
18
18
  - Batch protocol (0.4.0): when a round has several questions, submit them together as one `ask_choice` call with `questions: [...]` (2-8 items, recommended option first per question) — the tool opens one tabbed multiple-choice form with a submit page instead of asking one at a time. After the batch returns, think about the answers, then follow up in later calls (batch again for 2+ related follow-ups; single `question` for one). `Esc` on the form returns the answered subset as partial answers — continue with what you got and re-ask only what matters. The final scope confirmation and the execution handoff are ALWAYS single-question calls with `autoComplete: false`; batches reject those questions.
19
- - Use web research whenever outside library behavior, ecosystem precedent, UX convention, protocol semantics, or compatibility affects the recommendation (websearch skill when installed; otherwise `curl`/`gh` via bash), and cite sources in the plan.
19
+ - Use web research whenever outside library behavior, ecosystem precedent, UX convention, protocol semantics, or compatibility affects the recommendation (websearch skill when installed; otherwise `curl`/`gh` via bash), and cite sources in the plan. Optionally (never required) you may also search 1–2 named references — a paper (e.g. arXiv), an engineering blog post, or another repository — whose technique or measurements strengthen the plan's reasoning; cite their URLs in the plan's Evidence section. This optional reference search does not count against the planning-question limit and never requires downloading or analyzing material (that is plan-with-refs' job).
20
20
  - Ask the final scope confirmation, then write `PLAN_v1.md` per `../../references/plan-artifact-template.md`.
21
- - After each plan version, ask the merged accept/execute question via `ask_choice` with `autoComplete: false` — never run `refine` unless the user picked another round at that question. Default sequence: one `Reviewer` round, then one `Criticizer` round; afterwards the recommended option is `✓ Accept & execute now` in the merged accept/execute question. Up to five rounds total, continuing only for high-priority findings or unresolved criticizer questions; surface at most five per round. Then the merged accept/execute question (ask_choice with `autoComplete: false`: ✓ Accept & execute now / Accept, don't execute yet / another round) and the `execute_plan` tool.
21
+ - After each plan version, ask the merged accept/execute question via `ask_choice` with `autoComplete: false` — never run `refine` unless the user picked another round at that question. Default sequence: one reviewer round (findings `F-###` plus up to five questions `Q-1..Q-5` in the same output); ask every question with `ask_choice`, record the answers, then revise. Afterwards the recommended option is `✓ Accept & execute now` in the merged accept/execute question. Up to five rounds total, continuing only for high-priority findings or unresolved reviewer questions; surface at most five per round. Then the merged accept/execute question (ask_choice with `autoComplete: false`: ✓ Accept & execute now / Accept, don't execute yet / another round) and the `execute_plan` tool.
22
22
 
23
23
  ## Fit
24
24
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: plan-small
3
- description: Create a small Pi plan before implementation. Use for small scoped repo changes needing 1 to 3 planning questions and one criticizer refinement pass; exclude direct implementation-only, factual/explanation, trivial command-only, or explicit no-plan requests.
3
+ description: Create a small Pi plan before implementation. Use for small scoped repo changes needing 1 to 3 planning questions and one reviewer refinement pass; exclude direct implementation-only, factual/explanation, trivial command-only, or explicit no-plan requests.
4
4
  ---
5
5
 
6
6
  # Plan Small
@@ -9,15 +9,15 @@ Use this skill when the user wants a compact plan before a repository change.
9
9
 
10
10
  ## Pi Setup
11
11
 
12
- Read `../../references/pi-planning-workflow.md` and `../../references/state-and-config.md` — both normative — and follow their setup, state, `language`, and reviewer/criticizer rules. Initialize workspace state with the `plans` tool (`action: "init"`); state lives in `.git/pi_plans/`. Ask every question with the `ask_choice` tool; run the refinement round with the `refine` tool.
12
+ Read `../../references/pi-planning-workflow.md` and `../../references/state-and-config.md` — both normative — and follow their setup, state, `language`, and reviewer rules. Initialize workspace state with the `plans` tool (`action: "init"`); state lives in `.git/pi-plans/`. Ask every question with the `ask_choice` tool; run the refinement round with the `refine` tool.
13
13
 
14
14
  ## Depth Contract
15
15
 
16
16
  - Inspect the target Git repo read-only before the first product question.
17
- - Ask 1 to 3 planning questions via `ask_choice` (recommended option first; the tool adds `Other` second-last and `Auto-complete` last). With 2-3 ready questions, batch them into ONE `questions: [...]` form call; a single question uses the classic `question` form.
17
+ - Ask 1 to 3 planning questions via `ask_choice` (recommended option first; the tool adds `Other` second-last and `Auto-complete` last). Every option you write carries a `description` of `✓ <advantage> / ✗ <drawback>` in the configured language, kept terse — the user chooses by weighing what each option gains against what it costs. With 2-3 ready questions, batch them into ONE `questions: [...]` form call; a single question uses the classic `question` form.
18
18
  - Batch protocol (0.4.0): when a round has several questions, submit them together as one `ask_choice` call with `questions: [...]` (2-8 items, recommended option first per question) — the tool opens one tabbed multiple-choice form with a submit page instead of asking one at a time. After the batch returns, think about the answers, then follow up in later calls (batch again for 2+ related follow-ups; single `question` for one). `Esc` on the form returns the answered subset as partial answers — continue with what you got and re-ask only what matters. The final scope confirmation and the execution handoff are ALWAYS single-question calls with `autoComplete: false`; batches reject those questions.
19
- - Ask the final scope confirmation, then write `PLAN_v1.md` under the artifact root (normally the configured workspace root, default `./docs/pi-plans/YYYY-MM-DD-topic/`) per `../../references/plan-artifact-template.md`.
20
- - After each plan version, ask the merged accept/execute question via `ask_choice` with `autoComplete: false` — never run `refine` unless the user picked another round at that question. Default: exactly one round, recommended mode `Criticizer`; afterwards the recommended option is `✓ Accept & execute now` in the merged accept/execute question (ask_choice with `autoComplete: false`: ✓ Accept & execute now / Accept, don't execute yet / another round), then the `execute_plan` tool.
19
+ - Ask the final scope confirmation, then write `PLAN_v1.md` under the artifact root (normally the configured workspace root, default `./.git/pi-plans/plans/YYYY-MM-DD-topic/`) per `../../references/plan-artifact-template.md`.
20
+ - After each plan version, ask the merged accept/execute question via `ask_choice` with `autoComplete: false` — never run `refine` unless the user picked another round at that question. Default: exactly one reviewer round (findings plus up to five questions); afterwards the recommended option is `✓ Accept & execute now` in the merged accept/execute question (ask_choice with `autoComplete: false`: ✓ Accept & execute now / Accept, don't execute yet / another round), then the `execute_plan` tool.
21
21
 
22
22
  ## Fit
23
23
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: plan-with-refs
3
- description: Research references before creating a Pi plan. Use when repo-change planning needs downloaded projects, articles, papers, docs, per-reference analysis, adoption questions, language settings, and reviewer or criticizer refinement; exclude direct implementation-only, factual/explanation, trivial command-only, or explicit no-plan requests.
3
+ description: Research references before creating a Pi plan. Use when repo-change planning needs downloaded projects, articles, papers, docs, per-reference analysis, adoption questions, language settings, and reviewer refinement (findings plus questions); exclude direct implementation-only, factual/explanation, trivial command-only, or explicit no-plan requests.
4
4
  ---
5
5
 
6
6
  # Plan With Refs
@@ -9,22 +9,22 @@ Use this skill when external references must shape the plan before implementatio
9
9
 
10
10
  ## Pi Setup
11
11
 
12
- Read `../../references/pi-planning-workflow.md` and `../../references/state-and-config.md` — both normative — and follow their setup, state, `language`, and reviewer/criticizer rules. Initialize workspace state with the `plans` tool (`action: "init"`); state lives in `.git/pi_plans/`. Ask every question with the `ask_choice` tool (batch related questions and adoption questions into one `questions: [...]` form call, 2-8 items; scope/handoff stays single-question with `autoComplete: false`); run refinement rounds with the `refine` tool.
12
+ Read `../../references/pi-planning-workflow.md` and `../../references/state-and-config.md` — both normative — and follow their setup, state, `language`, and reviewer rules. Initialize workspace state with the `plans` tool (`action: "init"`); state lives in `.git/pi-plans/`. Ask every question with the `ask_choice` tool (batch related questions and adoption questions into one `questions: [...]` form call, 2-8 items; scope/handoff stays single-question with `autoComplete: false`); run refinement rounds with the `refine` tool.
13
13
 
14
14
  ## Required Reference Flow
15
15
 
16
16
  1. Inspect the target Git repo read-only before external research so search terms match the actual codebase and constraints.
17
- 2. Create the `.git/pi_plans` run state and planning artifact directory once the topic is clear (`plans` action `start-run`).
17
+ 2. Create the `.git/pi-plans` run state and planning artifact directory once the topic is clear (`plans` action `start-run`).
18
18
  3. Search proactively for related projects, articles, papers, docs, and prior art. Prefer a websearch skill when installed; otherwise use bash tools such as `curl` or `gh` when already available.
19
- 4. Before the first download, check `refs_root` in `.git/pi_plans/config.json` (`plans` action `show`). If it is unset, ask exactly one `ask_choice` question — recommended `.git/pi-plans/refs/` (inside the git dir, never tracked), second `./refs/`, third `~/.cache/pi-plans/refs/` — and persist with `plans` (`set-refs-root`); this question does not count against the planning-question limit. Then download or clone at least 3 credible references before writing `PLAN_v1.md`, under the configured refs root (create per-ref subdirectories). Landing pages, README-only snapshots, abstracts, package metadata, or curl-only fragments do not count when deeper source material is available.
20
- 5. For every reference, record source metadata and local path in `REF_ANALYSIS.md` and in the run's `refs.jsonl` (via `plans` action `record-ref`): title, URL, kind, retrieval method, date accessed, local path, coverage, and evidence gaps.
19
+ 4. Before the first download, check `refs_root` in `.git/pi-plans/config.json` (`plans` action `show`). If it is unset, ask exactly one `ask_choice` question — recommended `.git/pi-plans/refs/` (inside the git dir, never tracked), second `./refs/`, third `~/.cache/pi-plans/refs/` — with each option's `description` set to `✓ <advantage> / ✗ <drawback>` in the configured language, kept terse, and persist with `plans` (`set-refs-root`); this question does not count against the planning-question limit. Then download at least 3 credible references across at least 2 distinct origins before writing `PLAN_v1.md`, under the configured refs root (one subdirectory per reference — `analyze_refs` requires directories). References are NOT limited to GitHub repositories: papers (e.g. arXiv), engineering blog posts, and documentation sites are first-class, and theoretical references count exactly as much as implementation references. A download is qualified per medium: repo = clone (full working tree); paper = the full text (arXiv HTML preferred, else the PDF with extracted text into `paper.txt`/`paper.md`; an abstract alone never qualifies); blog/docs site = the full-article readable markdown saved locally (single-page posts are fine — they ARE the source; only fragments or teasers fail). Landing pages, README-only snapshots, abstracts, package metadata, or curl-only fragments do not count when deeper source material is available.
20
+ 5. For every reference, record source metadata and local path in `REF_ANALYSIS.md` and in the run's `refs.jsonl` (via `plans` action `record-ref`): title, URL, kind (`project` for repos, `paper` for papers, `article` for blog posts, `docs` for documentation sites), retrieval method, date accessed, local path, coverage, and evidence gaps.
21
21
  6. For every reference, run the `analyze_refs` tool (required path — it replaces manual structured reads): one independent read-only subagent per reference deep-reads it and returns structured sections (Overview / Key Mechanisms And Design Tradeoffs / Adoptable Ideas For The Target Repo / Pitfalls And Anti-Patterns / Evidence Citations / Coverage / Evidence Gaps). Paste each analysis into `REF_ANALYSIS.md` and fill `coverage` and `gaps` in `refs.jsonl` via `plans` (`record-ref`) before asking adoption questions.
22
- 7. For every reference after analysis, ask at least 3 ref-specific adoption questions via `ask_choice` before using its ideas in `PLAN_v1.md`; each based on downloaded content, recommended option first, `Other` second-last, `Auto-complete` last (the tool appends both). Batch one reference's adoption questions into a single `questions: [...]` form call.
22
+ 7. For every reference after analysis, ask at least 3 ref-specific adoption questions via `ask_choice` before using its ideas in `PLAN_v1.md`; each based on downloaded content, recommended option first, `Other` second-last, `Auto-complete` last (the tool appends both). Every option you write carries a `description` of `✓ <advantage> / ✗ <drawback>` in the configured language, kept terse — adoption choices trade a real gain against a real cost, so state both. Batch one reference's adoption questions into a single `questions: [...]` form call.
23
23
  8. Block rather than pad if fewer than 3 credible references exist, unless the user explicitly narrows the topic or waives the minimum. `Auto-complete` cannot grant this waiver.
24
- 9. Continue with big-plan depth: at least 10 planning questions, required web research during brainstorming and refinement (`refine` `reviewers: 3` reviewer round, then a criticizer round), no refinement limit, at most five high-priority comments or questions per refinement round. Then the merged accept/execute question (ask_choice with `autoComplete: false`: ✓ Accept & execute now / Accept, don't execute yet / another round) and the `execute_plan` tool.
24
+ 9. Continue with big-plan depth: at least 10 planning questions, required web research during brainstorming and refinement (`refine` `reviewers: 3` reviewer round carrying findings and questions), no refinement limit, at most five high-priority comments or questions per refinement round. Then the merged accept/execute question (ask_choice with `autoComplete: false`: ✓ Accept & execute now / Accept, don't execute yet / another round) and the `execute_plan` tool.
25
25
 
26
26
  ## REF_ANALYSIS.md
27
27
 
28
- Include: original request and repo evidence that shaped the search; attempted queries and selection criteria; references selected and rejected; configured refs root and local download paths; the per-reference `analyze_refs` structured analyses (pasted verbatim, one section per reference); adoption questions and recorded answers; accepted ideas, rejected ideas, and reasons; evidence gaps and user-granted waivers; language, reviewer, and criticizer settings used.
28
+ Include: original request and repo evidence that shaped the search; attempted queries and selection criteria; references selected and rejected; configured refs root and local download paths; the per-reference `analyze_refs` structured analyses (pasted verbatim, one section per reference); adoption questions and recorded answers; accepted ideas, rejected ideas, and reasons; evidence gaps and user-granted waivers; language, reviewer, and reviewer settings used.
29
29
 
30
30
  Reference ideas are not eligible for `PLAN_v1.md` until their adoption question answers are recorded.
@@ -19,4 +19,4 @@ Use this skill when a task is planning-related but the right specialist is not o
19
19
 
20
20
  ## Pi Setup
21
21
 
22
- Use the same language, `ask_choice`, `refine`, reviewer, criticizer, Auto-complete, and `.git/pi_plans` rules as the selected specialist skill and the shared workflow. Questions prefer the 0.4.0 batch form: one `ask_choice` call with `questions: [...]` (2-8) opens a tabbed multiple-choice form; scope confirmation and execution handoff stay single-question with `autoComplete: false`.
22
+ Use the same language, `ask_choice`, `refine`, reviewer, Auto-complete, and `.git/pi-plans` rules as the selected specialist skill and the shared workflow — including the per-option `✓ <advantage> / ✗ <drawback>` descriptions, which every option you write carries in the configured language, kept terse. Questions prefer the 0.4.0 batch form: one `ask_choice` call with `questions: [...]` (2-8) opens a tabbed multiple-choice form; scope confirmation and execution handoff stay single-question with `autoComplete: false`.
package/src/ask-form.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * The form is a tabbed dialog opened via ctx.ui.custom: one tab per question
5
5
  * (options always visible in the first frame — options-first fit contract from
6
- * pi-goal-x's questionnaire) plus a final submit page listing every Q/A, and a
6
+ * a guided multi-question questionnaire) plus a final submit page listing every Q/A, and a
7
7
  * custom-answer row per tab that switches into a Focusable single-line input
8
8
  * (CURSOR_MARKER + hardware cursor so zh-Hans IME composition works).
9
9
  *
@@ -69,7 +69,7 @@ export interface FormState {
69
69
  custom: (string | null)[];
70
70
  /** Whether the user explicitly confirmed an answer on tab i (Enter on an
71
71
  * option row or a committed custom answer). The cursor `selection` alone
72
- * never flips this — goal-x aligned ■/□ chips read this field. */
72
+ * never flips this — the ■/□ chips read this field. */
73
73
  confirmed: boolean[];
74
74
  /** Current tab: 0..N-1 = question tabs, N = submit page. */
75
75
  tab: number;
@@ -86,7 +86,7 @@ export function createFormState(questions: FormQuestion[], lang: UiLanguage = "e
86
86
  // Cursor position per tab: pre-positioned on the recommended option
87
87
  // where present. This is ONLY the highlight — an answer counts only
88
88
  // after the user confirms it (Enter/custom submit), tracked in
89
- // `confirmed` (pi-goal-x semantics: chips show □ until answered).
89
+ // `confirmed` semantics: chips show □ until answered.
90
90
  selection: questions.map((q) => q.options.findIndex((o) => o.recommended === true)),
91
91
  confirmed: questions.map(() => false),
92
92
  custom: questions.map(() => null),
@@ -286,7 +286,7 @@ export const FORM_ROWS_RESERVE = 4;
286
286
  export const FORM_FALLBACK_ROWS = 30;
287
287
 
288
288
  /**
289
- * pi-goal-x aligned question-tab frame: accent borders, tab chips with a
289
+ * themed question-tab frame: accent borders, tab chips with a
290
290
  * selectedBg background on the active chip (■ answered / □ pending), colored
291
291
  * question line, dim key hints. Under a `rows` budget it degrades richest
292
292
  * first — descriptions, then blank separators, then the borders (the chips
package/src/auditor.ts ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Completion auditor (v0.6.1): when every task reaches a terminal state, an
3
+ * independent read-only subagent verifies the plan's verification checks
4
+ * against the worktree. Failed checks roll their covered tasks back to
5
+ * pending (exclusively inside the audit flow); three failed rounds pause the
6
+ * run for the user — or terminate it as stopped under auto-approve/headless
7
+ * so pipelines never hang.
8
+ */
9
+
10
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
11
+ import * as fs from "node:fs";
12
+ import { auditRollbackSet, auditableChecks, skippedPassCheckIds, type TaskView } from "./tasks.ts";
13
+ import type { CheckItem } from "./plan.ts";
14
+ import { messaging } from "./messaging.ts";
15
+
16
+ export const AUDIT_MAX_ROUNDS = 3;
17
+
18
+ export interface AuditOutcome {
19
+ round: number;
20
+ passed: string[];
21
+ failed: string[];
22
+ /** Rolled-back task ids (empty when the audit passed). */
23
+ rolledBack: string[];
24
+ report: string;
25
+ }
26
+
27
+ /** Build the audit brief for the read-only subagent. Exported for tests. */
28
+ export function buildAuditTask(planPath: string, checklist: CheckItem[], tasks: TaskView[], round: number): string {
29
+ const checks = auditableChecks(checklist, tasks)
30
+ .map((check) => `- \`${check.id}\`: ${check.text}`)
31
+ .join("\n");
32
+ return `Goal: verify that the implemented worktree satisfies the accepted plan's verification checks.
33
+
34
+ Target plan: ${planPath} (audit round ${round})
35
+
36
+ Authority boundary: read-only analysis only. Do not edit, write, delete, commit, push, or spawn subagents.
37
+
38
+ Evidence: inspect the repository with read, grep, find, ls, and targeted commands (bash is not granted — rely on the read tools) before judging each check. Tests may be referenced from their recorded evidence; do not re-run them.
39
+
40
+ Checks to verify (only these; checks covering no task are excluded):
41
+
42
+ ${checks}
43
+
44
+ Output: Markdown with exactly one section per check, in checklist order:
45
+
46
+ - \`VC-###\` — verdict: pass | fail; evidence: <repo path/command proving it>; note: <one line>.
47
+
48
+ Every check needs a verdict backed by evidence you actually inspected. If the evidence is inconclusive, verdict is fail with what is missing.`;
49
+ }
50
+
51
+ /** Parse the audit subagent's verdict lines. Exported for tests. */
52
+ export function parseAuditReport(report: string, checklist: CheckItem[]): { passed: string[]; failed: string[] } {
53
+ const passed: string[] = [];
54
+ const failed: string[] = [];
55
+ const known = new Set(checklist.map((item) => item.id));
56
+ for (const match of report.matchAll(/`?(VC-\d+)`?[^\n]*?verdict:\s*(pass|fail)/gi)) {
57
+ const id = match[1].toUpperCase();
58
+ if (!known.has(id)) continue;
59
+ (match[2].toLowerCase() === "pass" ? passed : failed).push(id);
60
+ }
61
+ // Dedupe, keep first occurrence order; a check with conflicting verdicts fails.
62
+ for (const id of [...passed]) if (failed.includes(id)) passed.splice(passed.indexOf(id), 1);
63
+ return { passed: [...new Set(passed)], failed: [...new Set(failed)] };
64
+ }
65
+
66
+ /** Pure decision core: given a parsed report, mutate the task tree with the
67
+ * rollback set. Returns the outcome (rolled-back ids). Exported for tests. */
68
+ export function applyAuditOutcome(
69
+ checklist: CheckItem[],
70
+ tasks: TaskView[],
71
+ round: number,
72
+ passed: string[],
73
+ failed: string[],
74
+ report: string,
75
+ ): AuditOutcome {
76
+ for (const id of passed) {
77
+ const item = checklist.find((candidate) => candidate.id === id);
78
+ if (item) item.done = true;
79
+ }
80
+ const rolledBack: string[] = [];
81
+ for (const id of failed) {
82
+ rolledBack.push(...auditRollbackSet(tasks, checklist, id));
83
+ }
84
+ return { round, passed, failed, rolledBack, report };
85
+ }
86
+
87
+ /** Skipped-pass checks (all covered tasks skipped) pass without audit. */
88
+ export function presolvedCheckIds(checklist: CheckItem[], tasks: TaskView[]): string[] {
89
+ return skippedPassCheckIds(checklist, tasks);
90
+ }
91
+
92
+ /** Spawn the audit subagent and apply its outcome. Returns null when the
93
+ * audit subagent itself failed to run (treated as a failed round with an
94
+ * empty rollback; the caller counts it against the round cap). */
95
+ export async function runCompletionAudit(
96
+ ctx: ExtensionContext,
97
+ opts: {
98
+ planPath: string;
99
+ checklist: CheckItem[];
100
+ tasks: TaskView[];
101
+ round: number;
102
+ model?: string;
103
+ signal?: AbortSignal;
104
+ },
105
+ ): Promise<AuditOutcome | null> {
106
+ const { runPiSubagent } = await import("./subagent.ts");
107
+ const task = buildAuditTask(opts.planPath, opts.checklist, opts.tasks, opts.round);
108
+ let agentPrompt = "You are a read-only completion auditor for pi-plans.";
109
+ try {
110
+ agentPrompt = fs.readFileSync(new URL("../agents/reviewer.md", import.meta.url), "utf8");
111
+ } catch {
112
+ /* fall back to the inline prompt */
113
+ }
114
+ const result = await runPiSubagent({
115
+ systemPrompt: `${agentPrompt}\n\nYou are acting as the completion auditor; the task brief below defines the output contract.`,
116
+ task,
117
+ cwd: ctx.cwd,
118
+ model: opts.model,
119
+ tools: ["read", "grep", "find", "ls"],
120
+ signal: opts.signal,
121
+ });
122
+ if (!result.ok) return null;
123
+ const { passed, failed } = parseAuditReport(result.output, opts.checklist);
124
+ messaging().appendEntry("pi-plans-audit", { planPath: opts.planPath, round: opts.round, passed, failed });
125
+ return applyAuditOutcome(opts.checklist, opts.tasks, opts.round, passed, failed, result.output);
126
+ }
@@ -28,7 +28,7 @@ export function isAutoApproveEnabled(): boolean {
28
28
  * must answer interactively) while a false negative would silently bypass a
29
29
  * safety gate. Word-boundary anchored where short words could over-match.
30
30
  * NOTE: package *installation inside a disposable benchmark container* is
31
- * plan-lifecycle (the criticizer legitimately asks about installing deps);
31
+ * plan-lifecycle (the reviewer legitimately asks about installing deps);
32
32
  * only externally-visible state (publish/deploy/merge/push/credentials/...)
33
33
  * is hard-rejected. Install-permission waivers are still caught via
34
34
  * "waiver". */
@@ -3,6 +3,7 @@
3
3
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
4
  import { getRun, readActive } from "./state.ts";
5
5
  import { resolveActiveRun } from "./run-context.ts";
6
+ import { messaging, tryMessaging } from "./messaging.ts";
6
7
 
7
8
  export const AUTOCOMPLETE_ENTRY = "pi-plans-autocomplete";
8
9
  const AUTOCOMPLETE_CONTINUE = "Continue the current planning workflow. Raise the next relevant question with ask_choice; do not stop after an auto-completed answer.";
@@ -22,12 +23,6 @@ type SessionWithAutoComplete = ExtensionContext["sessionManager"] & {
22
23
  __piPlansAutoComplete?: AutoCompleteState;
23
24
  };
24
25
 
25
- let api: ExtensionAPI | null = null;
26
-
27
- export function setAutoCompleteApi(next: ExtensionAPI | null): void {
28
- api = next;
29
- }
30
-
31
26
  function sessionState(ctx: ExtensionContext): AutoCompleteState | undefined {
32
27
  return (ctx.sessionManager as SessionWithAutoComplete).__piPlansAutoComplete;
33
28
  }
@@ -39,9 +34,17 @@ function activePlanningRun(ctx: ExtensionContext): { runId: string } | null {
39
34
  return run?.status === "planning" ? { runId: run.run_id } : null;
40
35
  }
41
36
 
42
- function appendState(runId: string, enabled: boolean, reason?: string): void {
43
- if (!api) return;
44
- api.appendEntry(AUTOCOMPLETE_ENTRY, { runId, enabled, ...(reason ? { reason } : {}) });
37
+ function appendState(ctx: ExtensionContext, runId: string, enabled: boolean, reason?: string): void {
38
+ // Best-effort persistence: the in-memory session state is authoritative for
39
+ // the live turn; never let an unwired (tests) or stale (session swap) messaging
40
+ // surface break the ask_choice / handoff flows that call this.
41
+ const m = tryMessaging();
42
+ if (!m) return;
43
+ try {
44
+ m.appendEntry(AUTOCOMPLETE_ENTRY, { runId, enabled, ...(reason ? { reason } : {}) });
45
+ } catch {
46
+ /* session swap in flight; the entry is optional */
47
+ }
45
48
  }
46
49
 
47
50
  export function enableAutoComplete(ctx: ExtensionContext): boolean {
@@ -57,7 +60,7 @@ export function enableAutoComplete(ctx: ExtensionContext): boolean {
57
60
  autoChoiceCount: 0,
58
61
  planWritten: false,
59
62
  };
60
- appendState(run.runId, true);
63
+ appendState(ctx, run.runId, true);
61
64
  return true;
62
65
  }
63
66
 
@@ -67,7 +70,7 @@ export function disableAutoComplete(ctx: ExtensionContext, reason = "disabled"):
67
70
  const runId = state?.runId ?? run?.runId;
68
71
  if (!runId && !state?.enabled) return false;
69
72
  if (state) state.enabled = false;
70
- if (runId) appendState(runId, false, reason);
73
+ if (runId) appendState(ctx, runId, false, reason);
71
74
  return true;
72
75
  }
73
76
 
@@ -110,12 +113,12 @@ export function shouldContinueAutoComplete(ctx: ExtensionContext): boolean {
110
113
  }
111
114
 
112
115
  export async function continueAutoComplete(ctx: ExtensionContext): Promise<boolean> {
113
- if (!api || !shouldContinueAutoComplete(ctx)) return false;
116
+ if (!shouldContinueAutoComplete(ctx)) return false;
114
117
  const state = sessionState(ctx);
115
118
  if (!state) return false;
116
119
  state.pendingFollowUp = true;
117
120
  try {
118
- await api.sendUserMessage(AUTOCOMPLETE_CONTINUE, { deliverAs: "followUp" });
121
+ await messaging().sendUserMessage(AUTOCOMPLETE_CONTINUE, { deliverAs: "followUp" });
119
122
  return true;
120
123
  } catch {
121
124
  state.pendingFollowUp = false;
@@ -123,12 +126,11 @@ export async function continueAutoComplete(ctx: ExtensionContext): Promise<boole
123
126
  }
124
127
  }
125
128
 
126
- export function registerAutoCompleteTurnHandlers(pi: ExtensionAPI): void {
127
- setAutoCompleteApi(pi);
128
- pi.on("turn_start", async (_event, ctx) => {
129
+ export function registerAutoCompleteTurnHandlers(ext: ExtensionAPI): void {
130
+ ext.on("turn_start", async (_event, ctx) => {
129
131
  resetAutoCompleteTurn(ctx);
130
132
  });
131
- pi.on("turn_end", async (event, ctx) => {
133
+ ext.on("turn_end", async (event, ctx) => {
132
134
  const message = event.message as { role?: string } | undefined;
133
135
  if (message?.role === "assistant") await continueAutoComplete(ctx);
134
136
  });
@@ -153,7 +153,7 @@ export async function initGraphCommand(args: string, ctx: CommandContext): Promi
153
153
  "info",
154
154
  );
155
155
  try {
156
- const reportPath = generateGraphReport(store, `${paths.gitCommonDir}/pi_plans/graph`, {
156
+ const reportPath = generateGraphReport(store, `${paths.gitCommonDir}/pi-plans/graph`, {
157
157
  files: report.filesScanned,
158
158
  functions: report.functionsIndexed,
159
159
  ms: report.durationMs,
@@ -441,7 +441,7 @@ async function runChangedPathSync(
441
441
  "info",
442
442
  );
443
443
  try {
444
- generateGraphReport(store, `${paths.gitCommonDir}/pi_plans/graph`, {
444
+ generateGraphReport(store, `${paths.gitCommonDir}/pi-plans/graph`, {
445
445
  files: report.filesScanned,
446
446
  functions: report.functionsIndexed,
447
447
  ms: report.durationMs,
@@ -164,7 +164,7 @@ export function computeCommunities(store: Store): {
164
164
  return { communities: sortedGroups.length, nodes: order.length, godNodes };
165
165
  }
166
166
 
167
- /** Render GRAPH_REPORT.md (plan R-005) under `<gitCommonDir>/pi_plans/graph/`. */
167
+ /** Render GRAPH_REPORT.md (plan R-005) under `<gitCommonDir>/pi-plans/graph/`. */
168
168
  export function generateGraphReport(store: Store, graphDir: string, baseline?: { files: number; functions: number; ms: number }): string {
169
169
  const stats = computeCommunities(store);
170
170
  const edgeStats = store.read(() =>
@@ -34,7 +34,7 @@ export function resolveCanonicalWorktree(workdir: string): WorktreePaths {
34
34
  }
35
35
  const worktreeRoot = path.resolve(toplevel.stdout.trim());
36
36
  const gitCommonDir = path.resolve(workdir, common.stdout.trim());
37
- const stateRoot = path.join(gitCommonDir, "pi_plans");
37
+ const stateRoot = path.join(gitCommonDir, "pi-plans");
38
38
  if (!resolveStateRootOrNull(workdir)) {
39
39
  throw new PathError(`pi-plans state missing; run a planning init first`);
40
40
  }
@@ -4,7 +4,7 @@
4
4
  * pinned to the pi extension hooks — started by /watch-graph (or session_start
5
5
  * when the enabled marker is set), stopped by /unwatch-graph, disable-graph,
6
6
  * and an idempotent session_shutdown handler. A PID+heartbeat lock under
7
- * .git/pi_plans/graph/watch keeps a single writer per worktree across pi
7
+ * .git/pi-plans/graph/watch keeps a single writer per worktree across pi
8
8
  * sessions; per-file single-flight dedupes apply-trigger vs watch events.
9
9
  */
10
10
 
@@ -32,7 +32,7 @@ interface ActiveWatcher {
32
32
  const activeWatchers = new Map<string, ActiveWatcher>();
33
33
 
34
34
  function graphDir(paths: WorktreePaths): string {
35
- return path.join(paths.gitCommonDir, "pi_plans", "graph");
35
+ return path.join(paths.gitCommonDir, "pi-plans", "graph");
36
36
  }
37
37
 
38
38
  function lockPath(paths: WorktreePaths): string {
package/src/compaction.ts CHANGED
@@ -994,9 +994,9 @@ function phaseContextLines(context?: PiPlansVccPhaseContext): Partial<Record<typ
994
994
  const outstandingContext: string[] = [];
995
995
  if (context.phase === "execution") {
996
996
  sessionGoal.push(context.planPath ? `Execute accepted plan ${context.planPath}` : "Execute the accepted pi-plans plan");
997
- if (context.currentI) outstandingContext.push(`Current implementation item: ${context.currentI}`);
998
- if (context.remainingVerifierIds?.length) outstandingContext.push(`Remaining verifier items: ${context.remainingVerifierIds.slice(0, 12).join(", ")}`);
999
- if (context.implementationIds?.length) outstandingContext.push(`Implementation items: ${context.implementationIds.slice(0, 16).join(", ")}`);
997
+ if (context.currentI) outstandingContext.push(`Current task: ${context.currentI}`);
998
+ if (context.remainingVerifierIds?.length) outstandingContext.push(`Remaining verification checks: ${context.remainingVerifierIds.slice(0, 12).join(", ")}`);
999
+ if (context.implementationIds?.length) outstandingContext.push(`Plan tasks: ${context.implementationIds.slice(0, 24).join(", ")}`);
1000
1000
  } else {
1001
1001
  sessionGoal.push(context.runId ? `Continue active planning run ${context.runId}` : "Continue active pi-plans planning");
1002
1002
  if (context.planPath) outstandingContext.push(`Latest plan path from session: ${context.planPath}`);