@mrclrchtr/supi-review 2.8.0 → 3.0.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 (44) hide show
  1. package/README.md +71 -180
  2. package/node_modules/@mrclrchtr/supi-core/package.json +2 -1
  3. package/node_modules/@mrclrchtr/supi-core/src/api.ts +2 -0
  4. package/node_modules/@mrclrchtr/supi-core/src/evidence-badge.ts +40 -0
  5. package/package.json +3 -3
  6. package/src/config.ts +30 -21
  7. package/src/git-command.ts +78 -0
  8. package/src/git.ts +306 -505
  9. package/src/history/collect.ts +43 -120
  10. package/src/model.ts +3 -1
  11. package/src/review-path.ts +85 -0
  12. package/src/review-result.ts +43 -92
  13. package/src/review.ts +154 -290
  14. package/src/session/review-plan-store.ts +20 -51
  15. package/src/target/packet.ts +46 -369
  16. package/src/tool/agent-review-schemas.ts +101 -104
  17. package/src/tool/agent-review-tools.ts +268 -309
  18. package/src/tool/child-failure-diagnostics.ts +1 -1
  19. package/src/tool/child-resource-loader.ts +37 -0
  20. package/src/tool/child-session-runner.ts +83 -0
  21. package/src/tool/output-page.ts +47 -0
  22. package/src/tool/planner-runner.ts +69 -0
  23. package/src/tool/review-runner.ts +42 -257
  24. package/src/tool/review-system-prompt.ts +12 -110
  25. package/src/tool/review-tools.ts +119 -0
  26. package/src/tool/review-workflow.ts +309 -0
  27. package/src/tool/runner-helpers.ts +3 -8
  28. package/src/tool/schemas.ts +75 -62
  29. package/src/tui/common.ts +175 -0
  30. package/src/tui/prepare.ts +132 -0
  31. package/src/tui/run.ts +160 -0
  32. package/src/types.ts +153 -275
  33. package/src/history/synthesize.ts +0 -121
  34. package/src/tool/agent-review-workflow.ts +0 -398
  35. package/src/tool/brief-runner.ts +0 -180
  36. package/src/tool/guidance.ts +0 -21
  37. package/src/tool/review-handlers.ts +0 -314
  38. package/src/tool/snapshot-tools.ts +0 -117
  39. package/src/ui/flow.ts +0 -189
  40. package/src/ui/format-content.ts +0 -143
  41. package/src/ui/renderer.ts +0 -274
  42. package/src/ui/review-plan-inspector.ts +0 -391
  43. package/src/ui/review-tool-format.ts +0 -138
  44. package/src/ui/review-tool-renderer.ts +0 -234
@@ -1,342 +1,301 @@
1
- import { mkdtempSync, writeFileSync } from "node:fs";
2
- import { tmpdir } from "node:os";
3
- import { join } from "node:path";
4
- import {
5
- buildSessionContext,
6
- DEFAULT_MAX_BYTES,
7
- DEFAULT_MAX_LINES,
8
- type ExtensionAPI,
9
- formatSize,
10
- truncateHead,
11
- } from "@earendil-works/pi-coding-agent";
12
- import { recordDebugEvent } from "@mrclrchtr/supi-core/debug";
1
+ import { buildSessionContext, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { StatusSpinner } from "@mrclrchtr/supi-core/status-spinner";
13
3
  import { loadReviewConfig } from "../config.ts";
14
- import { isCommitObjectId, summarizeReviewSnapshot } from "../git.ts";
15
- import { serializeSessionContext } from "../history/collect.ts";
16
- import { CURRENT_SESSION_REVIEW_MODEL, resolveAgentReviewModel } from "../model.ts";
17
- import { ReviewPlanStore } from "../session/review-plan-store.ts";
18
- import type {
19
- BriefEvaluation,
20
- PreparedAgentReviewDetails,
21
- ReviewProgress,
22
- ReviewTargetSpec,
23
- } from "../types.ts";
24
- import { formatBriefSynthesisFailureCopy } from "../ui/format-content.ts";
25
- import { formatAgentReviewBatch, formatPreparedAgentReview } from "../ui/review-tool-format.ts";
26
- import {
27
- type AgentReviewProgressDetails,
28
- renderPrepareReviewCall,
29
- renderPrepareReviewResult,
30
- renderRunReviewCall,
31
- renderRunReviewResult,
32
- } from "../ui/review-tool-renderer.ts";
4
+ import { summarizeReviewSnapshot } from "../git.ts";
5
+ import { collectPlannerContext } from "../history/collect.ts";
6
+ import { resolveAgentReviewModel } from "../model.ts";
7
+ import type { ReviewPlanStore } from "../session/review-plan-store.ts";
8
+ import { renderPrepareCall, renderPrepareResult } from "../tui/prepare.ts";
9
+ import { renderRunCall, renderRunResult } from "../tui/run.ts";
10
+ import type { ReviewBatchDetails, ReviewTargetSpec, ReviewTaskResult } from "../types.ts";
33
11
  import {
34
- type PrepareAgentReviewInput,
35
- prepareAgentReviewSchema,
36
- type RunAgentReviewInput,
37
- runAgentReviewSchema,
12
+ type PrepareReviewToolInput,
13
+ parsePrepareReviewToolInput,
14
+ parseRunReviewToolInput,
15
+ prepareReviewSchema,
16
+ runReviewSchema,
38
17
  } from "./agent-review-schemas.ts";
39
- import { prepareAgentReviewPlan, runAgentReviewBatch } from "./agent-review-workflow.ts";
40
- import { formatChildLifecycleTrace } from "./child-lifecycle-trace.ts";
41
- import {
42
- PREPARE_REVIEW_TOOL_NAME,
43
- prepareReviewPromptGuidelines,
44
- prepareReviewPromptSnippet,
45
- prepareReviewToolDescription,
46
- RUN_REVIEW_TOOL_NAME,
47
- runReviewToolDescription,
48
- } from "./guidance.ts";
49
-
50
- const TOOL_OUTPUT_CONTRACT =
51
- " Output is truncated at 2,000 lines or 50KB; full Markdown is saved to a temporary file when truncated.";
52
-
53
- /** Register the two-stage agent-driven Session-Aware Review tools. */
54
- export function registerAgentReviewTools(
55
- pi: ExtensionAPI,
56
- planStore = new ReviewPlanStore(),
57
- ): void {
58
- pi.registerTool({
59
- name: PREPARE_REVIEW_TOOL_NAME,
60
- label: "Prepare Review",
61
- description: prepareReviewToolDescription + TOOL_OUTPUT_CONTRACT,
62
- promptSnippet: prepareReviewPromptSnippet,
63
- promptGuidelines: prepareReviewPromptGuidelines,
64
- parameters: prepareAgentReviewSchema,
65
- // biome-ignore lint/complexity/useMaxParams: pi ToolDefinition.execute signature
66
- async execute(_toolCallId, params, signal, onUpdate, ctx) {
67
- const input = params as PrepareAgentReviewInput;
68
- const configuredModelId = loadReviewConfig(ctx.cwd).agentModel;
69
- const model = resolveAgentReviewModel(ctx, configuredModelId);
70
- if (!model) {
71
- if (configuredModelId === CURRENT_SESSION_REVIEW_MODEL) {
72
- throw new Error("No current session model is available for review preparation.");
73
- }
74
- throw new Error(
75
- `Configured agent review model "${configuredModelId}" is not available in Pi's scoped model set. Choose another model in /supi-settings.`,
76
- );
77
- }
78
-
79
- const target = parseTarget(input);
80
- const sessionContext = buildSessionContext(
81
- ctx.sessionManager.getEntries(),
82
- ctx.sessionManager.getLeafId(),
83
- );
84
- const serializedContext = serializeSessionContext(sessionContext.messages);
85
- const note = input.note?.trim() || undefined;
18
+ import { pageText } from "./output-page.ts";
19
+ import { prepareReview, runReview } from "./review-workflow.ts";
86
20
 
87
- pi.events.emit("supi:working:start", { source: "supi-review" });
88
- try {
89
- const outcome = await prepareAgentReviewPlan({
90
- cwd: ctx.cwd,
91
- target,
92
- note,
93
- serializedContext,
94
- model,
95
- signal,
96
- planStore,
97
- onProgress: (progress) => {
98
- onUpdate?.({
99
- content: [{ type: "text", text: "Synthesizing review brief…" }],
100
- details: prepareProgressDetails(progress),
101
- });
102
- },
103
- });
104
- if (outcome.kind !== "prepared") {
105
- throw new Error(formatPreparationFailure(outcome));
106
- }
107
-
108
- const details: PreparedAgentReviewDetails = {
109
- kind: "review-prepared",
110
- planId: outcome.plan.id,
111
- briefPromptVersion: outcome.plan.briefPromptVersion,
112
- generatedBrief: outcome.plan.generatedBrief,
113
- snapshot: summarizeReviewSnapshot(outcome.plan.snapshot),
114
- snapshotFingerprint: outcome.plan.snapshotFingerprint,
115
- modelId: outcome.plan.model.canonicalId,
116
- };
117
- activateRunTool(pi);
118
- return toolResult(formatPreparedAgentReview(details), details, PREPARE_REVIEW_TOOL_NAME);
119
- } finally {
120
- pi.events.emit("supi:working:end", { source: "supi-review" });
121
- }
122
- },
123
- renderCall(args, theme) {
124
- return renderPrepareReviewCall(args, theme);
125
- },
126
- renderResult(result, { expanded }, theme) {
127
- return renderPrepareReviewResult(result, expanded, theme);
128
- },
129
- });
130
-
131
- pi.registerTool({
132
- name: RUN_REVIEW_TOOL_NAME,
133
- label: "Run Review",
134
- description: runReviewToolDescription + TOOL_OUTPUT_CONTRACT,
135
- parameters: runAgentReviewSchema,
136
- // biome-ignore lint/complexity/useMaxParams: pi ToolDefinition.execute signature
137
- async execute(_toolCallId, params, signal, onUpdate, ctx) {
138
- const input = params as RunAgentReviewInput;
139
- const progress = createBatchProgress(input.reviewers.map((reviewer) => reviewer.id.trim()));
140
-
141
- pi.events.emit("supi:working:start", { source: "supi-review" });
142
- try {
143
- const outcome = await runAgentReviewBatch({
144
- cwd: ctx.cwd,
145
- planId: input.planId,
146
- critique: input.critique,
147
- revisedBrief: input.revisedBrief,
148
- reviewers: input.reviewers,
149
- signal,
150
- planStore,
151
- onBriefEvaluation: (evaluation) => {
152
- recordBriefCritique(ctx.cwd, evaluation, input.reviewers.length);
153
- },
154
- onReviewerProgress: (reviewerId, reviewerProgress) => {
155
- progress.reviewers[reviewerId] = reviewerProgress;
156
- onUpdate?.({
157
- content: [
158
- {
159
- type: "text",
160
- text: `Running reviewers… ${progress.completed}/${progress.total} completed`,
161
- },
162
- ],
163
- details: batchProgressDetails(progress),
164
- });
165
- },
166
- onReviewerDone: (reviewerId) => {
167
- progress.completed++;
168
- progress.reviewers[reviewerId] = {
169
- ...(progress.reviewers[reviewerId] ?? { turns: 0, toolUses: 0 }),
170
- currentFocus: undefined,
171
- };
172
- onUpdate?.({
173
- content: [
174
- {
175
- type: "text",
176
- text: `Running reviewers… ${progress.completed}/${progress.total} completed`,
177
- },
178
- ],
179
- details: batchProgressDetails(progress),
180
- });
181
- },
182
- });
183
- if (outcome.kind !== "completed") throw new Error(outcome.reason);
184
-
185
- return toolResult(
186
- formatAgentReviewBatch(outcome.details),
187
- outcome.details,
188
- RUN_REVIEW_TOOL_NAME,
189
- );
190
- } finally {
191
- pi.events.emit("supi:working:end", { source: "supi-review" });
192
- }
193
- },
194
- renderCall(args, theme, context) {
195
- return renderRunReviewCall(args, context.expanded, theme);
196
- },
197
- renderResult(result, { expanded }, theme) {
198
- return renderRunReviewResult(result, expanded, theme);
199
- },
200
- });
201
-
202
- pi.on("session_start", () => {
203
- planStore.clear();
204
- deactivateRunTool(pi);
205
- });
206
- pi.on("session_shutdown", () => {
207
- planStore.clear();
208
- });
21
+ function target(input: PrepareReviewToolInput["target"]): ReviewTargetSpec {
22
+ return (input ?? { kind: "working-tree" }) as ReviewTargetSpec;
209
23
  }
210
24
 
211
- function parseTarget(input: PrepareAgentReviewInput): ReviewTargetSpec {
212
- const target = input.target;
213
- if (!target) return { kind: "working-tree" };
214
- if (target.kind === "working-tree") {
215
- if (target.base || target.sha) {
216
- throw new Error('target.base and target.sha must be omitted for "working-tree".');
25
+ function formatPrepared(plan: {
26
+ id: string;
27
+ snapshot: { title: string; changedFiles: string[] };
28
+ plannerDraft?: { sharedContext?: string; tasks: Array<{ id: string; instructions: string }> };
29
+ }): string {
30
+ const lines = [
31
+ "# Review Plan Prepared",
32
+ "",
33
+ `Plan ID: ${plan.id}`,
34
+ `Target: ${plan.snapshot.title}`,
35
+ `Files changed: ${plan.snapshot.changedFiles.length}`,
36
+ ];
37
+ if (plan.plannerDraft) {
38
+ lines.push("", "## Planner Draft");
39
+ if (plan.plannerDraft.sharedContext) lines.push("", plan.plannerDraft.sharedContext);
40
+ for (const task of plan.plannerDraft.tasks) {
41
+ lines.push("", `### ${task.id}`, task.instructions);
217
42
  }
218
- return { kind: "working-tree" };
43
+ lines.push("", "Call supi_review_run with an explicit accept-draft or use-review decision.");
44
+ } else {
45
+ lines.push("", "Call supi_review_run with a use-review decision containing one to four tasks.");
219
46
  }
220
- if (target.kind === "branch") {
221
- if (target.sha) throw new Error('target.sha must be omitted when target.kind is "branch".');
222
- const base = target.base?.trim();
223
- if (!base) throw new Error('target.base is required when target.kind is "branch".');
224
- if (base.startsWith("-")) {
225
- throw new Error("target.base must name a local branch, not a Git option.");
226
- }
227
- return { kind: "branch", base };
47
+ return lines.join("\n");
48
+ }
49
+
50
+ function formatTaskResult(result: ReviewTaskResult): string[] {
51
+ const lines = [
52
+ "",
53
+ `## ${result.taskId}`,
54
+ `Model: ${result.modelId}`,
55
+ `Packet SHA-256: ${result.packetHash}`,
56
+ ];
57
+ if (result.status === "failed") return [...lines, `Status: failed (${result.failureCode})`];
58
+ if (result.status === "canceled") return [...lines, "Status: canceled"];
59
+ if (result.status === "timeout") {
60
+ return [...lines, `Status: timeout (${result.timeoutMs} ms)`];
228
61
  }
229
- if (target.base) throw new Error('target.base must be omitted when target.kind is "commit".');
230
- const sha = target.sha?.trim();
231
- if (!sha) throw new Error('target.sha is required when target.kind is "commit".');
232
- if (!isCommitObjectId(sha)) {
233
- throw new Error("target.sha must be a hexadecimal commit object id (7–64 characters).");
62
+ lines.push(`Verdict: ${result.verdict.toUpperCase()}`, "", result.summary);
63
+ for (const finding of result.findings) {
64
+ lines.push(
65
+ "",
66
+ `- ${finding.title} [${finding.blocksAcceptance ? "blocking" : "non-blocking"}; impact ${finding.impact}; effort ${finding.effort}; confidence ${finding.confidence}]`,
67
+ ...(finding.location
68
+ ? [
69
+ ` Location: ${finding.location.path}:${finding.location.startLine}-${finding.location.endLine}`,
70
+ ]
71
+ : []),
72
+ ` ${finding.description}`,
73
+ );
234
74
  }
235
- return { kind: "commit", sha };
75
+ return lines;
236
76
  }
237
77
 
238
- function formatPreparationFailure(
239
- outcome: Exclude<Awaited<ReturnType<typeof prepareAgentReviewPlan>>, { kind: "prepared" }>,
240
- ): string {
241
- if (outcome.kind === "no-snapshot") return outcome.reason;
242
-
243
- const { result } = outcome;
244
- const trace = result.diagnostics?.lifecycleTrace;
245
- return trace
246
- ? `${formatBriefSynthesisFailureCopy(result)}\n\n${formatChildLifecycleTrace(trace)}`
247
- : formatBriefSynthesisFailureCopy(result);
78
+ export function formatReviewBatch(details: ReviewBatchDetails): string {
79
+ const lines = [
80
+ "# Review Complete",
81
+ "",
82
+ `Mode: ${details.mode}`,
83
+ `Provenance: ${details.provenance}`,
84
+ `Target: ${details.snapshot.title}`,
85
+ ];
86
+ if (details.planning) {
87
+ lines.push(
88
+ `Planner: ${details.planning.modelId} (protocol ${details.planning.promptVersion})`,
89
+ `Planner decision: ${details.planning.decision}`,
90
+ );
91
+ }
92
+ for (const result of details.results) lines.push(...formatTaskResult(result));
93
+ return lines.join("\n");
248
94
  }
249
95
 
250
- function activateRunTool(pi: ExtensionAPI): void {
251
- const active = pi.getActiveTools();
252
- if (active.includes(RUN_REVIEW_TOOL_NAME)) return;
253
- pi.setActiveTools([...active, RUN_REVIEW_TOOL_NAME]);
96
+ function resolveModels(ctx: Parameters<Parameters<ExtensionAPI["registerTool"]>[0]["execute"]>[4]) {
97
+ const config = loadReviewConfig(ctx.cwd);
98
+ const reviewer = resolveAgentReviewModel(ctx, config.agentModel);
99
+ const planner = resolveAgentReviewModel(ctx, config.plannerModel);
100
+ if (!reviewer)
101
+ throw new Error(`Configured reviewer model "${config.agentModel}" is unavailable.`);
102
+ return { reviewer, planner, config };
254
103
  }
255
104
 
256
- function deactivateRunTool(pi: ExtensionAPI): void {
257
- const active = pi.getActiveTools();
258
- if (!active.includes(RUN_REVIEW_TOOL_NAME)) return;
259
- pi.setActiveTools(active.filter((name) => name !== RUN_REVIEW_TOOL_NAME));
260
- }
105
+ /**
106
+ * Wraps onUpdate to also update a StatusSpinner with progress counts.
107
+ * Returns the adapted callback that both updates the spinner and calls onUpdate.
108
+ */
109
+ function wireSpinnerToProgress(
110
+ // biome-ignore lint/suspicious/noExplicitAny: tool execute ctx type is narrower than ExtensionContext
111
+ ctx: any,
112
+ // biome-ignore lint/suspicious/noExplicitAny: onUpdate callback type varies per tool
113
+ onUpdate: any,
114
+ startMessage = "Reviewing…",
115
+ ): {
116
+ statusSpinner: StatusSpinner;
117
+ wrappedUpdate: (result: {
118
+ content: Array<{ type: "text"; text: string }>;
119
+ details: Record<string, unknown>;
120
+ }) => void;
121
+ } {
122
+ const statusSpinner = new StatusSpinner(ctx, "supi-review");
123
+ statusSpinner.start(startMessage);
261
124
 
262
- function prepareProgressDetails(progress: ReviewProgress): AgentReviewProgressDetails {
263
- return {
264
- kind: "review-progress",
265
- phase: "prepare",
266
- completed: 0,
267
- total: 1,
268
- reviewers: { synthesis: progress },
125
+ let completedCount = 0;
126
+ let totalCount = 0;
127
+ const wrappedUpdate = (result: {
128
+ content: Array<{ type: "text"; text: string }>;
129
+ details: Record<string, unknown>;
130
+ }) => {
131
+ const details = result.details as { completedCount?: number; totalCount?: number };
132
+ completedCount = details.completedCount ?? completedCount;
133
+ totalCount = details.totalCount ?? totalCount;
134
+ const label =
135
+ totalCount > 0
136
+ ? `Reviewing… (${completedCount} of ${totalCount} tasks complete)`
137
+ : "Reviewing…";
138
+ statusSpinner.update(label);
139
+ onUpdate?.(result);
269
140
  };
141
+ return { statusSpinner, wrappedUpdate };
270
142
  }
271
143
 
272
- interface BatchProgressState {
273
- completed: number;
274
- total: number;
275
- reviewers: Record<string, ReviewProgress>;
144
+ /** Compute the initial task count for the progress indicator. */
145
+ function initialTaskCount(
146
+ input: ReturnType<typeof parseRunReviewToolInput>,
147
+ planStore: ReviewPlanStore,
148
+ ): number {
149
+ if (input.mode === "direct") return input.review?.tasks?.length ?? 1;
150
+ if (input.decision?.kind === "use-review") return input.decision.review?.tasks?.length ?? 0;
151
+ if (input.decision?.kind === "accept-draft") {
152
+ return planStore.peek(input.planId)?.plannerDraft?.tasks.length ?? 0;
153
+ }
154
+ return 0;
276
155
  }
277
156
 
278
- function createBatchProgress(reviewerIds: string[]): BatchProgressState {
279
- return {
280
- completed: 0,
281
- total: reviewerIds.length,
282
- reviewers: Object.fromEntries(
283
- reviewerIds.map((id) => [id, { turns: 0, toolUses: 0 } satisfies ReviewProgress]),
284
- ),
157
+ /** Factory for the supi_review_run execute function with animated status-bar spinner. */
158
+ function makeRunReviewExecute(
159
+ planStore: ReviewPlanStore,
160
+ ): NonNullable<Parameters<ExtensionAPI["registerTool"]>[0]["execute"]> {
161
+ // biome-ignore lint/complexity/useMaxParams: Pi ToolDefinition execute signature
162
+ return async (_id, params, signal, onUpdate, ctx) => {
163
+ const input = parseRunReviewToolInput(params);
164
+
165
+ const { statusSpinner, wrappedUpdate } = wireSpinnerToProgress(ctx, onUpdate);
166
+
167
+ const taskCount = initialTaskCount(input, planStore);
168
+ wrappedUpdate({
169
+ content: [{ type: "text", text: "Starting review…" }],
170
+ details: taskCount > 0 ? { completedCount: 0, totalCount: taskCount } : {},
171
+ });
172
+
173
+ try {
174
+ const outcome =
175
+ input.mode === "direct"
176
+ ? await runReview({
177
+ mode: "direct",
178
+ cwd: ctx.cwd,
179
+ target: input.target,
180
+ review: input.review,
181
+ reviewerModel: resolveModels(ctx).reviewer,
182
+ signal,
183
+ onUpdate: wrappedUpdate,
184
+ })
185
+ : await runReview({
186
+ mode: "prepared",
187
+ cwd: ctx.cwd,
188
+ planId: input.planId,
189
+ decision: input.decision,
190
+ planStore,
191
+ signal,
192
+ onUpdate: wrappedUpdate,
193
+ });
194
+ if (outcome.kind !== "completed") throw new Error(outcome.reason);
195
+ return {
196
+ content: [{ type: "text", text: pageText(formatReviewBatch(outcome.details)).text }],
197
+ details: outcome.details,
198
+ };
199
+ } finally {
200
+ statusSpinner.stop();
201
+ }
285
202
  };
286
203
  }
287
204
 
288
- function batchProgressDetails(progress: BatchProgressState): AgentReviewProgressDetails {
289
- return {
290
- kind: "review-progress",
291
- phase: "review",
292
- completed: progress.completed,
293
- total: progress.total,
294
- reviewers: { ...progress.reviewers },
295
- };
205
+ /** Throw an actionable error from a non-prepared outcome. */
206
+ function throwPrepareFailure(
207
+ outcome: { kind: string; reason?: string } & Record<string, unknown>,
208
+ ): never {
209
+ if (outcome.kind === "no-target")
210
+ throw new Error(outcome.reason ?? "No reviewable changes found.");
211
+ const result = outcome.result as { kind: string; failureCode?: string; timeoutMs?: number };
212
+ const diagnostic =
213
+ result.kind === "failed"
214
+ ? result.failureCode
215
+ : result.kind === "timeout"
216
+ ? `timeout (${result.timeoutMs} ms)`
217
+ : result.kind;
218
+ throw new Error(`Planner failed: ${diagnostic}`);
296
219
  }
297
220
 
298
- function recordBriefCritique(
299
- cwd: string,
300
- evaluation: BriefEvaluation,
301
- reviewerCount: number,
302
- ): void {
303
- recordDebugEvent({
304
- source: "supi-review",
305
- level: "info",
306
- category: "brief-critique",
307
- message: `Main agent submitted a brief critique with verdict ${evaluation.critique.verdict}`,
308
- cwd,
309
- data: {
310
- planId: evaluation.planId,
311
- briefPromptVersion: evaluation.briefPromptVersion,
312
- verdict: evaluation.critique.verdict,
313
- findingCount: evaluation.critique.findings.length,
314
- reviewerCount,
315
- modelId: evaluation.synthesizerModelId,
316
- snapshotFingerprint: evaluation.snapshotFingerprint,
221
+ /** Register optional preparation and universal direct/prepared execution tools. */
222
+ export function registerAgentReviewTools(pi: ExtensionAPI, planStore: ReviewPlanStore): void {
223
+ pi.registerTool({
224
+ name: "supi_review_prepare",
225
+ label: "Prepare Review",
226
+ description: "Create a one-shot Review Plan, optionally with a lightweight Planner Draft.",
227
+ promptSnippet: "Prepare an optional one-shot code review plan",
228
+ promptGuidelines: [
229
+ "Use supi_review_prepare only when a caller wants to inspect or request a Planner Draft before execution.",
230
+ "Use supi_review_run in direct mode when the current skill or agent already knows the review tasks.",
231
+ ],
232
+ parameters: prepareReviewSchema,
233
+ renderCall: renderPrepareCall,
234
+ renderResult: renderPrepareResult,
235
+ // biome-ignore lint/complexity/useMaxParams: Pi ToolDefinition execute signature
236
+ async execute(_id, params, signal, onUpdate, ctx) {
237
+ const input = parsePrepareReviewToolInput(params);
238
+ const models = resolveModels(ctx);
239
+ if ((input.planning ?? "none") === "suggest" && !models.planner) {
240
+ throw new Error(`Configured Planner model "${models.config.plannerModel}" is unavailable.`);
241
+ }
242
+
243
+ const { statusSpinner, wrappedUpdate } = wireSpinnerToProgress(
244
+ ctx,
245
+ onUpdate,
246
+ "Preparing review…",
247
+ );
248
+
249
+ try {
250
+ const session = buildSessionContext(
251
+ ctx.sessionManager.getEntries(),
252
+ ctx.sessionManager.getLeafId(),
253
+ );
254
+ const outcome = await prepareReview({
255
+ cwd: ctx.cwd,
256
+ target: target(input.target),
257
+ planning: input.planning ?? "none",
258
+ plannerContext: collectPlannerContext(session.messages),
259
+ reviewerModel: models.reviewer,
260
+ plannerModel: models.planner,
261
+ planStore,
262
+ signal,
263
+ onUpdate: wrappedUpdate,
264
+ });
265
+ if (outcome.kind !== "prepared") throwPrepareFailure(outcome);
266
+ return {
267
+ content: [{ type: "text", text: pageText(formatPrepared(outcome.plan)).text }],
268
+ details: {
269
+ kind: "review-prepared",
270
+ planId: outcome.plan.id,
271
+ snapshot: summarizeReviewSnapshot(outcome.plan.snapshot),
272
+ reviewerModelId: outcome.plan.reviewerModel.canonicalId,
273
+ plannerDraft: outcome.plan.plannerDraft,
274
+ plannerModelId: outcome.plan.plannerModelId,
275
+ plannerPromptVersion: outcome.plan.plannerPromptVersion,
276
+ },
277
+ };
278
+ } finally {
279
+ statusSpinner.stop();
280
+ }
317
281
  },
318
- rawData: evaluation,
319
282
  });
320
- }
321
283
 
322
- function toolResult<TDetails>(content: string, details: TDetails, toolName: string) {
323
- const truncation = truncateHead(content, {
324
- maxLines: DEFAULT_MAX_LINES,
325
- maxBytes: DEFAULT_MAX_BYTES,
284
+ pi.registerTool({
285
+ name: "supi_review_run",
286
+ label: "Run Review",
287
+ description: "Run one to four caller-defined review tasks directly or from a prepared plan.",
288
+ promptSnippet: "Run independent read-only code review tasks",
289
+ promptGuidelines: [
290
+ "Use supi_review_run directly when a skill or the main agent already has complete review task instructions.",
291
+ "Repository stability from invocation through completion is a caller precondition for supi_review_run.",
292
+ ],
293
+ parameters: runReviewSchema,
294
+ renderCall: renderRunCall,
295
+ renderResult: renderRunResult,
296
+ execute: makeRunReviewExecute(planStore),
326
297
  });
327
- if (!truncation.truncated) {
328
- return { content: [{ type: "text" as const, text: truncation.content }], details };
329
- }
330
298
 
331
- const dir = mkdtempSync(join(tmpdir(), "supi-review-"));
332
- const file = join(dir, `${toolName}.md`);
333
- writeFileSync(file, content, { encoding: "utf-8", mode: 0o600 });
334
- const note =
335
- `\n\n[Output truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines ` +
336
- `(${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)}). ` +
337
- `Full output saved to: ${file}]`;
338
- return {
339
- content: [{ type: "text" as const, text: truncation.content + note }],
340
- details,
341
- };
299
+ pi.on("session_start", () => planStore.clear());
300
+ pi.on("session_shutdown", () => planStore.clear());
342
301
  }
@@ -65,7 +65,7 @@ export function createEarlyCancellationDiagnostics(): ChildFailureDiagnostics {
65
65
 
66
66
  /** Generate static parent-facing copy for a host-owned child failure code. */
67
67
  export function formatChildFailureCopy(stage: ChildStage, code: ChildFailureCode): string {
68
- const label = stage === "brief-synthesis" ? "Brief synthesis" : "Reviewer";
68
+ const label = stage === "planner" ? "Planner" : "Reviewer";
69
69
  switch (code) {
70
70
  case "session-creation-failed":
71
71
  return `${label} session could not be created.`;
@@ -0,0 +1,37 @@
1
+ import { DefaultResourceLoader, SettingsManager } from "@earendil-works/pi-coding-agent";
2
+
3
+ /** Loader and settings manager preconfigured for an isolated child session. */
4
+ export interface IsolatedChildResources {
5
+ loader: DefaultResourceLoader;
6
+ settingsManager: SettingsManager;
7
+ }
8
+
9
+ /**
10
+ * Build child-session resources with no ambient settings or discovered prompt
11
+ * content. Compaction and retries stay disabled so provider limits apply to the
12
+ * original packet directly.
13
+ */
14
+ export function createIsolatedChildResources(
15
+ cwd: string,
16
+ protocolPrompt: string,
17
+ agentDir = process.env.PI_CODING_AGENT_DIR || "",
18
+ ): IsolatedChildResources {
19
+ const settingsManager = SettingsManager.inMemory({
20
+ compaction: { enabled: false },
21
+ retry: { enabled: false },
22
+ });
23
+ const loader = new DefaultResourceLoader({
24
+ cwd,
25
+ agentDir,
26
+ settingsManager,
27
+ noExtensions: true,
28
+ noSkills: true,
29
+ noPromptTemplates: true,
30
+ noThemes: true,
31
+ noContextFiles: true,
32
+ appendSystemPrompt: [protocolPrompt],
33
+ systemPromptOverride: () => undefined,
34
+ appendSystemPromptOverride: () => [protocolPrompt],
35
+ });
36
+ return { loader, settingsManager };
37
+ }