pi-plans 0.1.2 → 0.3.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 (76) hide show
  1. package/README.md +98 -19
  2. package/index.ts +147 -66
  3. package/package.json +7 -1
  4. package/references/pi-planning-workflow.md +21 -3
  5. package/references/state-and-config.md +35 -3
  6. package/scripts/validate.ts +4 -0
  7. package/src/autocomplete.ts +163 -0
  8. package/src/code-graph/commands.ts +437 -0
  9. package/src/code-graph/discovery.ts +118 -0
  10. package/src/code-graph/git.ts +108 -0
  11. package/src/code-graph/identity.ts +59 -0
  12. package/src/code-graph/indexer.ts +281 -0
  13. package/src/code-graph/materialize.ts +166 -0
  14. package/src/code-graph/mode.ts +28 -0
  15. package/src/code-graph/mutations.ts +160 -0
  16. package/src/code-graph/parser.ts +51 -0
  17. package/src/code-graph/parsers/javascript.ts +35 -0
  18. package/src/code-graph/parsers/python.ts +160 -0
  19. package/src/code-graph/parsers/tree-sitter.ts +316 -0
  20. package/src/code-graph/paths.ts +85 -0
  21. package/src/code-graph/prompts.ts +18 -0
  22. package/src/code-graph/resolver.ts +69 -0
  23. package/src/code-graph/runtime.ts +158 -0
  24. package/src/code-graph/schema.ts +135 -0
  25. package/src/code-graph/screening.ts +82 -0
  26. package/src/code-graph/store.ts +278 -0
  27. package/src/code-graph/summary.ts +435 -0
  28. package/src/code-graph/types.ts +163 -0
  29. package/src/compaction.ts +1256 -0
  30. package/src/config-command.ts +326 -0
  31. package/src/exec.ts +519 -625
  32. package/src/plan.ts +37 -0
  33. package/src/query-hook.ts +82 -0
  34. package/src/refine-prompts.ts +50 -0
  35. package/src/refine-ui-helpers.ts +142 -0
  36. package/src/refine-ui-state.ts +144 -0
  37. package/src/refine-ui.ts +430 -0
  38. package/src/state.ts +24 -29
  39. package/src/subagent.ts +299 -70
  40. package/tests/ask-choice.test.ts +263 -0
  41. package/tests/autocomplete.test.ts +147 -0
  42. package/tests/code-graph-apply.test.ts +185 -0
  43. package/tests/code-graph-commands.test.ts +211 -0
  44. package/tests/code-graph-db.test.ts +166 -0
  45. package/tests/code-graph-discovery.test.ts +38 -0
  46. package/tests/code-graph-git.test.ts +94 -0
  47. package/tests/code-graph-index.test.ts +175 -0
  48. package/tests/code-graph-loop.e2e.test.ts +159 -0
  49. package/tests/code-graph-mutations.test.ts +117 -0
  50. package/tests/code-graph-parser.test.ts +85 -0
  51. package/tests/code-graph-rollback.test.ts +100 -0
  52. package/tests/code-graph-summary-batching.test.ts +518 -0
  53. package/tests/code-graph-summary.test.ts +148 -0
  54. package/tests/compaction.test.ts +388 -0
  55. package/tests/config-command.test.ts +255 -0
  56. package/tests/exec.test.ts +751 -422
  57. package/tests/execute-plan.test.ts +65 -0
  58. package/tests/fixtures/code-graph/sample.js +36 -0
  59. package/tests/fixtures/code-graph/sample.py +20 -0
  60. package/tests/fixtures/code-graph/sample.ts +15 -0
  61. package/tests/graph-aware-file-tools.test.ts +411 -0
  62. package/tests/plan.test.ts +11 -1
  63. package/tests/plans.test.ts +6 -5
  64. package/tests/query-hook.test.ts +82 -0
  65. package/tests/refine-prompts.test.ts +67 -2
  66. package/tests/refine-ui.test.ts +392 -0
  67. package/tests/state.test.ts +12 -15
  68. package/tests/subagent.test.ts +120 -0
  69. package/tools/ask-choice.ts +180 -11
  70. package/tools/code-graph.ts +254 -0
  71. package/tools/execute-plan.ts +7 -39
  72. package/tools/graph-aware-file-tools.ts +392 -0
  73. package/tools/plans.ts +84 -18
  74. package/tools/refine.ts +180 -80
  75. package/src/execution-panel.ts +0 -633
  76. package/tests/execution-panel.test.ts +0 -234
package/tools/refine.ts CHANGED
@@ -15,12 +15,21 @@ import { Type } from "typebox";
15
15
  import * as fs from "node:fs";
16
16
  import * as path from "node:path";
17
17
  import { loadConfig, normalizeWorkdir, readActive, recordSubagent, resolveStateRootOrNull, StateError, type RoleConfig } from "../src/state.ts";
18
- import { buildCriticizerTask, buildReviewerTask, reviewerLanes } from "../src/refine-prompts.ts";
18
+ import { buildCriticizerTask, buildImplementationCriticizerTask, buildImplementationReviewerTask, buildReviewerTask, reviewerLanes } from "../src/refine-prompts.ts";
19
+ import { graphBlockForRefiner } from "../src/code-graph/prompts.ts";
19
20
  import { runPiSubagent, stripFrontmatter } from "../src/subagent.ts";
21
+ import { RefineOverlayController, refineOverlayContext } from "../src/refine-ui.ts";
22
+
20
23
 
21
24
  const RefineParams = Type.Object({
22
25
  role: StringEnum(["reviewer", "criticizer"] as const, { description: "Refinement role to run" }),
23
26
  planPath: Type.String({ description: "Path to the PLAN_vN.md to review (absolute or relative to workdir)" }),
27
+ target: Type.Optional(
28
+ StringEnum(["plan", "implementation"] as const, {
29
+ description:
30
+ 'Review target: "plan" (default) reviews the plan text; "implementation" reviews the implemented worktree against the plan\'s goals and acceptance criteria (post-execution amelioration).',
31
+ }),
32
+ ),
24
33
  focus: Type.Optional(Type.String({ description: "Specific concerns to direct the pass at" })),
25
34
  reviewers: Type.Optional(
26
35
  Type.Integer({
@@ -46,7 +55,30 @@ function roleGateError(role: string, roleConfig: RoleConfig | undefined, problem
46
55
  );
47
56
  }
48
57
 
58
+ function setupRefinementExecution(
59
+ ctx: ExtensionContext,
60
+ parentSignal: AbortSignal | undefined,
61
+ role: "reviewer" | "criticizer",
62
+ lanes: Array<{ id: string; label?: string }>,
63
+ modelLabel?: string,
64
+ ) {
65
+ const controller = new AbortController();
66
+ const relayAbort = () => controller.abort();
67
+ if (parentSignal?.aborted) controller.abort();
68
+ else parentSignal?.addEventListener("abort", relayAbort, { once: true });
49
69
 
70
+ const overlay = ctx.mode === "tui" ? new RefineOverlayController(role, lanes, relayAbort) : undefined;
71
+ overlay?.open(refineOverlayContext(ctx), modelLabel);
72
+
73
+ return {
74
+ signal: controller.signal,
75
+ overlay,
76
+ async close() {
77
+ await overlay?.close();
78
+ parentSignal?.removeEventListener("abort", relayAbort);
79
+ },
80
+ };
81
+ }
50
82
 
51
83
  export function registerRefineTool(pi: ExtensionAPI, baseDir: string): void {
52
84
  const agentsDir = path.join(baseDir, "agents");
@@ -60,7 +92,7 @@ export function registerRefineTool(pi: ExtensionAPI, baseDir: string): void {
60
92
  name: "refine",
61
93
  label: "Refine",
62
94
  description:
63
- "Run a reviewer or criticizer refinement round on a PLAN_vN.md via read-only Pi subagents. Reviewer: findings with IDs, severity, evidence, impact, fix, disposition. Criticizer: up to five adaptive questions. Use reviewers: 3 for the big-plan concurrent reviewer round. Refuses to spawn until the role's mode and model are confirmed in .git/pi_plans/config.json (ask via ask_choice, persist via the plans tool).",
95
+ "Run a reviewer or criticizer refinement round on a PLAN_vN.md (target=\"plan\", default) or on the implemented worktree (target=\"implementation\", post-execution amelioration) via read-only Pi subagents. Reviewer: findings with IDs, severity, evidence, impact, fix, disposition. Criticizer: up to five adaptive questions. Use reviewers: 3 for the big-plan concurrent reviewer round. Refuses to spawn until the role's mode and model are confirmed in .git/pi_plans/config.json (ask via ask_choice, persist via the plans tool).",
64
96
  promptSnippet: "Run reviewer/criticizer plan-refinement rounds",
65
97
  parameters: RefineParams,
66
98
 
@@ -97,15 +129,28 @@ export function registerRefineTool(pi: ExtensionAPI, baseDir: string): void {
97
129
  }
98
130
  };
99
131
 
132
+ const target = params.target ?? "plan";
133
+ const pickTask = (role: "reviewer" | "criticizer", lens: string | null): string => {
134
+ if (role === "reviewer") {
135
+ return target === "implementation"
136
+ ? buildImplementationReviewerTask({ planText, planPath, lens, focus: params.focus, context: params.context })
137
+ : buildReviewerTask({ planText, planPath, lens, focus: params.focus, context: params.context });
138
+ }
139
+ return target === "implementation"
140
+ ? buildImplementationCriticizerTask({ planText, planPath, focus: params.focus, context: params.context })
141
+ : buildCriticizerTask({ planText, planPath, focus: params.focus, context: params.context });
142
+ };
143
+
100
144
  const systemPrompt = loadAgentPrompt(params.role);
145
+ const graphEnabled = config.graph_enabled === true;
146
+ const subagentTools = graphEnabled ? ["read", "grep", "find", "ls", "code_graph"] : undefined;
147
+ const graphPrompt = graphBlockForRefiner(graphEnabled);
101
148
  const inheritModel = ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined;
102
149
  const model = roleConfig.model_selector ?? inheritModel;
150
+ const modelLabel = model ?? "inherit";
103
151
 
104
152
  if (roleConfig.mode === "current-session") {
105
- const task =
106
- params.role === "reviewer"
107
- ? buildReviewerTask({ planText, planPath, lens: null, focus: params.focus, context: params.context })
108
- : buildCriticizerTask({ planText, planPath, focus: params.focus, context: params.context });
153
+ const task = pickTask(params.role, null);
109
154
  return {
110
155
  content: [
111
156
  {
@@ -113,101 +158,155 @@ export function registerRefineTool(pi: ExtensionAPI, baseDir: string): void {
113
158
  text: `Role mode is current-session: perform the read-only ${params.role} pass yourself, in this session, following this brief. Do not spawn anything.\n\n${task}`,
114
159
  },
115
160
  ],
116
- details: { mode: "current-session", role: params.role, planPath },
161
+ details: { mode: "current-session", role: params.role, planPath, target },
117
162
  };
118
163
  }
119
164
 
120
165
  if (params.role === "criticizer") {
121
166
  const name = `${roleConfig.name_prefix}-criticizer-${Date.now().toString(36)}`;
122
- const result = await runPiSubagent({
123
- systemPrompt,
124
- task: buildCriticizerTask({ planText, planPath, focus: params.focus, context: params.context }),
125
- cwd: workdir,
126
- model,
127
- signal,
128
- });
129
- record(name, result.ok ? result.model ?? model : null);
130
- if (!result.ok) {
131
- throw new Error(
132
- `criticizer subagent failed: ${result.errorMessage ?? "unknown error"}${result.stderr ? `\nstderr: ${result.stderr.slice(0, 2000)}` : ""}`,
133
- );
167
+ const execution = setupRefinementExecution(ctx, signal, "criticizer", [{ id: name, label: "criticizer" }], modelLabel);
168
+ try {
169
+ const result = await runPiSubagent({
170
+ systemPrompt: `${systemPrompt}\n\n${graphPrompt}`,
171
+ task: pickTask("criticizer", null),
172
+ cwd: workdir,
173
+ model,
174
+ tools: subagentTools,
175
+ signal: execution.signal,
176
+ onProgress: (event) => execution.overlay?.update(name, event),
177
+ });
178
+ execution.overlay?.complete(name, result);
179
+ record(name, result.ok ? result.model ?? model : null);
180
+ if (!result.ok) {
181
+ throw new Error(
182
+ `criticizer subagent failed: ${result.errorMessage ?? "unknown error"}${result.stderr ? `\nstderr: ${result.stderr.slice(0, 2000)}` : ""}`,
183
+ );
184
+ }
185
+ return {
186
+ content: [
187
+ {
188
+ type: "text",
189
+ text: `${result.output}\n\n---\nAsk each criticizer question with ask_choice (one call per question, in the configured language), record every answer, then revise the plan only after every question has an answer.`,
190
+ },
191
+ ],
192
+ details: { mode: "delegated-subagent", role: params.role, planPath, target, model: result.model ?? model },
193
+ };
194
+ } finally {
195
+ await execution.close();
134
196
  }
135
- return {
136
- content: [
137
- {
138
- type: "text",
139
- text: `${result.output}\n\n---\nAsk each criticizer question with ask_choice (one call per question, in the configured language), record every answer, then revise the plan only after every question has an answer.`,
140
- },
141
- ],
142
- details: { mode: "delegated-subagent", role: params.role, planPath, model: result.model ?? model },
143
- };
144
197
  }
145
198
 
146
- // Reviewer round: 1 by default, 3 for the big-plan concurrent round.
147
199
  const count = Math.min(3, Math.max(1, params.reviewers ?? 1));
148
200
  const lanes = reviewerLanes(count);
149
201
  const jobs = lanes.map((lane) => {
150
202
  const name = `${roleConfig.name_prefix}-${active?.run_id ?? "adhoc"}-${lane.id}`;
151
- const task = buildReviewerTask({ planText, planPath, lens: lane.lens, focus: params.focus, context: params.context });
203
+ const task = pickTask("reviewer", lane.lens);
152
204
  return { lane, name, task };
153
205
  });
154
206
 
155
- const results = await Promise.all(
156
- jobs.map(async (job) => {
157
- try {
158
- const result = await runPiSubagent({ systemPrompt, task: job.task, cwd: workdir, model, signal });
159
- record(job.name, result.ok ? result.model ?? model : null);
160
- return { job, result };
161
- } catch (error) {
162
- record(job.name, null);
163
- const message = error instanceof Error ? error.message : String(error);
164
- return {
165
- job,
166
- result: { ok: false, output: "", model: model ?? undefined, errorMessage: message, stderr: "", turns: 0 },
167
- };
168
- }
169
- }),
207
+ // Per-plan amelioration round counter (post-execution loop auditability).
208
+ const roundsSlot = ctx.sessionManager as unknown as { __ameliorateRounds?: Map<string, number> };
209
+ const nextRound = (planPath: string): number => {
210
+ roundsSlot.__ameliorateRounds ??= new Map();
211
+ const round = (roundsSlot.__ameliorateRounds.get(planPath) ?? 0) + 1;
212
+ roundsSlot.__ameliorateRounds.set(planPath, round);
213
+ return round;
214
+ };
215
+
216
+ const execution = setupRefinementExecution(
217
+ ctx,
218
+ signal,
219
+ "reviewer",
220
+ jobs.map((job) => ({ id: job.lane.id, label: job.lane.id })),
221
+ modelLabel,
170
222
  );
223
+ try {
224
+ const results = await Promise.all(
225
+ jobs.map(async (job) => {
226
+ try {
227
+ const result = await runPiSubagent({
228
+ systemPrompt: `${systemPrompt}\n\n${graphPrompt}`,
229
+ task: job.task,
230
+ cwd: workdir,
231
+ model,
232
+ tools: subagentTools,
233
+ signal: execution.signal,
234
+ onProgress: (event) => execution.overlay?.update(job.lane.id, event),
235
+ });
236
+ execution.overlay?.complete(job.lane.id, result);
237
+ record(job.name, result.ok ? result.model ?? model : null);
238
+ if (target === "implementation" && result.ok) {
239
+ try {
240
+ pi.appendEntry("pi-plans-ameliorate", {
241
+ planPath,
242
+ phase: "round",
243
+ currentRound: nextRound(planPath),
244
+ lane: job.lane.id,
245
+ });
246
+ } catch {
247
+ /* appendEntry is best-effort; audit trail survives in subagents.jsonl */
248
+ }
249
+ }
250
+ return { job, result };
251
+ } catch (error) {
252
+ record(job.name, null);
253
+ const message = error instanceof Error ? error.message : String(error);
254
+ const result = {
255
+ ok: false,
256
+ output: "",
257
+ model: model ?? undefined,
258
+ errorMessage: message,
259
+ stderr: "",
260
+ turns: 0,
261
+ };
262
+ execution.overlay?.complete(job.lane.id, result);
263
+ return { job, result };
264
+ }
265
+ }),
266
+ );
171
267
 
172
- const sections: string[] = [];
173
- let failures = 0;
174
- for (const { job, result } of results) {
175
- const title = job.lane.lens ? `${job.name} — ${job.lane.lens}` : job.name;
176
- if (!result.ok) {
177
- failures += 1;
178
- sections.push(`### ${title} — FAILED\n${result.errorMessage ?? "unknown error"}`);
179
- continue;
268
+ const sections: string[] = [];
269
+ let failures = 0;
270
+ for (const { job, result } of results) {
271
+ const title = job.lane.lens ? `${job.name} — ${job.lane.lens}` : job.name;
272
+ if (!result.ok) {
273
+ failures += 1;
274
+ sections.push(`### ${title} — FAILED\n${result.errorMessage ?? "unknown error"}`);
275
+ continue;
276
+ }
277
+ sections.push(`### ${title}\n${result.output}`);
278
+ }
279
+ if (failures === results.length) {
280
+ const first = results[0];
281
+ throw new Error(
282
+ `all reviewer subagents failed: ${first?.result.errorMessage ?? "unknown error"}${first?.result.stderr ? `\nstderr: ${first.result.stderr.slice(0, 2000)}` : ""}${model ? `\nIf the model selector "${model}" is unavailable, reset the confirmation (plans set-role --reset-confirmation) and re-ask the model-confirmation question.` : ""}`,
283
+ );
180
284
  }
181
- sections.push(`### ${title}\n${result.output}`);
182
- }
183
- if (failures === results.length) {
184
- const first = results[0];
185
- throw new Error(
186
- `all reviewer subagents failed: ${first?.result.errorMessage ?? "unknown error"}${first?.result.stderr ? `\nstderr: ${first.result.stderr.slice(0, 2000)}` : ""}${model ? `\nIf the model selector "${model}" is unavailable, reset the confirmation (plans set-role --reset-confirmation) and re-ask the model-confirmation question.` : ""}`,
187
- );
188
- }
189
285
 
190
- const combined = sections.join("\n\n---\n\n");
191
- const truncation = truncateHead(combined, { maxLines: 2000, maxBytes: 50 * 1024 });
192
- let text = truncation.content;
193
- if (truncation.truncated) text += `\n\n[Output truncated; full outputs remain in this tool result's details.]`;
286
+ const combined = sections.join("\n\n---\n\n");
287
+ const truncation = truncateHead(combined, { maxLines: 2000, maxBytes: 50 * 1024 });
288
+ let text = truncation.content;
289
+ if (truncation.truncated) text += `\n\n[Output truncated; full outputs remain in this tool result's details.]`;
194
290
 
195
- return {
196
- content: [
197
- {
198
- type: "text",
199
- text: `${text}\n\n---\nConsolidate: merge and dedupe findings into PLAN_vN_reviewer_comments.md${count === 3 ? " (one consolidated file; keep each finding's source reviewer, severity, evidence, and disposition)" : ""}, accept or reject each finding on repo/reference evidence, surface at most five high-priority findings to the user, then immediately ask the next refinement-mode question with ask_choice.`,
291
+ return {
292
+ content: [
293
+ {
294
+ type: "text",
295
+ text: `${text}\n\n---\nConsolidate: merge and dedupe findings into PLAN_vN_reviewer_comments.md${count === 3 ? " (one consolidated file; keep each finding's source reviewer, severity, evidence, and disposition)" : ""}, accept or reject each finding on repo/reference evidence, surface at most five high-priority findings to the user, then immediately ask the next refinement-mode question with ask_choice.`,
296
+ },
297
+ ],
298
+ details: {
299
+ mode: "delegated-subagent",
300
+ role: "reviewer",
301
+ planPath,
302
+ reviewers: count,
303
+ model,
304
+ outputs: results.map(({ job, result }) => ({ name: job.name, lane: job.lane.id, lens: job.lane.lens, ok: result.ok, output: result.output, stderr: result.stderr, turns: result.turns })),
200
305
  },
201
- ],
202
- details: {
203
- mode: "delegated-subagent",
204
- role: "reviewer",
205
- planPath,
206
- reviewers: count,
207
- model,
208
- outputs: results.map(({ job, result }) => ({ name: job.name, lane: job.lane.id, lens: job.lane.lens, ok: result.ok, output: result.output, stderr: result.stderr, turns: result.turns })),
209
- },
210
- };
306
+ };
307
+ } finally {
308
+ await execution.close();
309
+ }
211
310
  },
212
311
 
213
312
  renderCall(args, theme) {
@@ -218,6 +317,7 @@ export function registerRefineTool(pi: ExtensionAPI, baseDir: string): void {
218
317
  theme.fg("muted", count > 1 ? ` ×${count}` : "");
219
318
  const short = args.planPath ? args.planPath.split("/").pop() : "";
220
319
  if (short) text += theme.fg("dim", ` ${short}`);
320
+ if (args.target === "implementation") text += theme.fg("dim", " (implementation)");
221
321
  if (args.focus) text += `\n${theme.fg("dim", ` focus: ${args.focus.slice(0, 80)}`)}`;
222
322
  return new Text(text, 0, 0);
223
323
  },