@linxiraos/pi-messenger 1.1.0 → 1.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 (66) hide show
  1. package/CHANGELOG.md +741 -676
  2. package/LICENSE +45 -0
  3. package/README.md +424 -424
  4. package/THIRD-PARTY-NOTICES.txt +22951 -0
  5. package/config-overlay.ts +175 -171
  6. package/config.ts +221 -209
  7. package/crew/agents/crew-plan-sync.md +66 -64
  8. package/crew/agents/crew-planner.md +173 -172
  9. package/crew/agents/crew-reviewer.md +58 -58
  10. package/crew/agents/crew-worker.md +130 -129
  11. package/crew/agents.ts +507 -434
  12. package/crew/handlers/coordination.ts +350 -332
  13. package/crew/handlers/plan.ts +988 -906
  14. package/crew/handlers/review.ts +354 -333
  15. package/crew/handlers/revise.ts +400 -376
  16. package/crew/handlers/status.ts +303 -295
  17. package/crew/handlers/sync.ts +237 -233
  18. package/crew/handlers/task.ts +820 -792
  19. package/crew/handlers/team.ts +294 -235
  20. package/crew/handlers/work.ts +467 -425
  21. package/crew/id-allocator.ts +30 -30
  22. package/crew/index.ts +297 -257
  23. package/crew/live-progress.ts +58 -58
  24. package/crew/lobby.ts +504 -473
  25. package/crew/prompt.ts +262 -252
  26. package/crew/registry.ts +114 -114
  27. package/crew/spawn.ts +135 -111
  28. package/crew/state-autonomous.ts +163 -164
  29. package/crew/state-planning.ts +264 -263
  30. package/crew/state.ts +20 -20
  31. package/crew/store.ts +646 -642
  32. package/crew/task-actions.ts +162 -131
  33. package/crew/team/store.ts +572 -479
  34. package/crew/team/subagent-roles.ts +105 -87
  35. package/crew/team/types.ts +50 -50
  36. package/crew/types.ts +194 -194
  37. package/crew/utils/artifacts.ts +57 -62
  38. package/crew/utils/config.ts +158 -156
  39. package/crew/utils/discover.ts +221 -219
  40. package/crew/utils/install.ts +94 -85
  41. package/crew/utils/migrations.ts +126 -0
  42. package/crew/utils/progress.ts +191 -187
  43. package/crew/utils/result.ts +16 -16
  44. package/crew/utils/risk-labels.ts +5 -7
  45. package/crew/utils/task-format.ts +14 -14
  46. package/crew/utils/team-roles.ts +44 -28
  47. package/crew/utils/truncate.ts +76 -79
  48. package/crew/utils/verdict.ts +55 -55
  49. package/editor-binary.ts +150 -0
  50. package/editor-command.ts +107 -0
  51. package/editor-target.ts +40 -0
  52. package/feed.ts +321 -268
  53. package/handlers.ts +1041 -1107
  54. package/index.ts +1314 -1206
  55. package/install.mjs +187 -189
  56. package/lib.ts +587 -467
  57. package/overlay-actions.ts +519 -511
  58. package/overlay-coordinator.ts +150 -150
  59. package/overlay-render.ts +770 -676
  60. package/overlay.ts +872 -830
  61. package/package.json +64 -60
  62. package/paths.ts +60 -0
  63. package/skills/pi-messenger-crew/SKILL.md +375 -347
  64. package/store.ts +1147 -1139
  65. package/teamagent-command.ts +321 -0
  66. package/vitest.config.ts +10 -10
@@ -1,333 +1,354 @@
1
- /**
2
- * Crew - Review Handler
3
- *
4
- * Spawns reviewer with git diff context for task or plan review.
5
- * Simplified: works with current plan
6
- */
7
-
8
- import { execSync } from "node:child_process";
9
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
10
- import type { CrewParams } from "../types.ts";
11
- import { result } from "../utils/result.ts";
12
- import { spawnAgents } from "../agents.ts";
13
- import { discoverCrewAgents } from "../utils/discover.ts";
14
- import { loadCrewConfig } from "../utils/config.ts";
15
- import { parseVerdict, type ParsedReview } from "../utils/verdict.ts";
16
- import * as store from "../store.ts";
17
-
18
- export async function execute(
19
- params: CrewParams,
20
- ctx: ExtensionContext,
21
- sessionModel?: string,
22
- ) {
23
- const cwd = ctx.cwd;
24
- const { target, type } = params;
25
- const config = loadCrewConfig(store.getCrewDir(cwd));
26
- const reviewerModel = config.models?.reviewer ?? sessionModel;
27
-
28
- if (!target) {
29
- return result("Error: target (task ID) required for review action.\n\nUsage: pi_messenger({ action: \"review\", target: \"task-1\" })", {
30
- mode: "review",
31
- error: "missing_target"
32
- });
33
- }
34
-
35
- // Check for reviewer agent
36
- const availableAgents = discoverCrewAgents(cwd);
37
- const hasReviewer = availableAgents.some(a => a.name === "crew-reviewer");
38
- if (!hasReviewer) {
39
- return result("Error: crew-reviewer agent not found. Required for code review.", {
40
- mode: "review",
41
- error: "no_reviewer"
42
- });
43
- }
44
-
45
- if (type && type !== "impl" && type !== "plan") {
46
- return result("Error: review type must be 'impl' or 'plan'.", {
47
- mode: "review",
48
- error: "invalid_type",
49
- type,
50
- });
51
- }
52
-
53
- // Determine review type: "impl" for task, "plan" for plan review
54
- const reviewType = type ?? (target.startsWith("task-") ? "impl" : "plan");
55
-
56
- if (reviewType === "impl") {
57
- return reviewImplementation(cwd, target, reviewerModel);
58
- } else {
59
- return reviewPlan(cwd, reviewerModel);
60
- }
61
- }
62
-
63
- // =============================================================================
64
- // Implementation Review
65
- // =============================================================================
66
-
67
- export async function reviewImplementation(cwd: string, taskId: string, modelOverride?: string) {
68
- const task = store.getTask(cwd, taskId);
69
- if (!task) {
70
- return result(`Error: Task ${taskId} not found.`, {
71
- mode: "review",
72
- error: "task_not_found",
73
- target: taskId
74
- });
75
- }
76
-
77
- if (task.status !== "done" && task.status !== "in_progress") {
78
- return result(`Error: Task ${taskId} is ${task.status}. Can only review in_progress or done tasks.`, {
79
- mode: "review",
80
- error: "invalid_status",
81
- status: task.status
82
- });
83
- }
84
-
85
- // Get git diff
86
- const baseCommit = task.base_commit;
87
- if (!baseCommit) {
88
- return result(`Error: Task ${taskId} has no base_commit. Cannot generate diff.`, {
89
- mode: "review",
90
- error: "no_base_commit"
91
- });
92
- }
93
-
94
- const taskBranch = getTaskBranch(taskId, cwd);
95
- const diffResult = getGitDiff(baseCommit, cwd, taskBranch ?? undefined);
96
- const diff = diffResult.text;
97
- const commitLog = getCommitLog(baseCommit, cwd, taskBranch ?? undefined);
98
- const diffError = taskBranch && diffResult.status === "empty"
99
- ? `**ERROR:** Task branch \`${taskBranch}\` exists but has no changes relative to base ${baseCommit.slice(0, 12)}. The implementation appears to be missing from the branch.`
100
- : null;
101
-
102
- // Get task spec for context
103
- const taskSpec = store.getTaskSpec(cwd, taskId) ?? "";
104
- const plan = store.getPlan(cwd);
105
-
106
- // Build review prompt
107
- const prompt = `# Code Review Request
108
-
109
- ## Task Information
110
-
111
- **Task ID:** ${taskId}
112
- **Task Title:** ${task.title}
113
- **PRD:** ${plan?.prd ?? "Unknown"}
114
-
115
- ## Task Specification
116
-
117
- ${taskSpec || "*No spec available*"}
118
-
119
- ## Changes
120
- ### Commits
121
- ${commitLog || "*No commits*"}
122
-
123
- ### Diff
124
- ${diffError ?? `\`\`\`diff
125
- ${diff}
126
- \`\`\``}
127
-
128
- ## Your Review
129
-
130
- Review this implementation following the crew-reviewer protocol.
131
- Output your verdict as SHIP, NEEDS_WORK, or MAJOR_RETHINK with detailed feedback.`;
132
-
133
- // Spawn reviewer
134
- const [reviewResult] = await spawnAgents([{
135
- agent: "crew-reviewer",
136
- task: prompt,
137
- modelOverride,
138
- }], cwd);
139
-
140
- if (reviewResult.exitCode !== 0) {
141
- return result(`Error: Reviewer failed: ${reviewResult.error ?? "Unknown error"}`, {
142
- mode: "review",
143
- error: "reviewer_failed"
144
- });
145
- }
146
-
147
- // Parse verdict from output
148
- const verdict: ParsedReview = parseVerdict(reviewResult.output);
149
-
150
- // Store review feedback in task for retry context
151
- store.updateTask(cwd, taskId, {
152
- last_review: {
153
- verdict: verdict.verdict,
154
- summary: verdict.summary,
155
- issues: verdict.issues,
156
- suggestions: verdict.suggestions,
157
- reviewed_at: new Date().toISOString()
158
- }
159
- });
160
- const shortSummary = verdict.summary.split("\n")[0].slice(0, 120);
161
- const progressMsg = `Review: ${verdict.verdict} — ${shortSummary}`;
162
- store.appendTaskProgress(cwd, taskId, "system", progressMsg);
163
-
164
- const text = `# Review: ${taskId}
165
-
166
- **Verdict:** ${verdict.verdict}
167
-
168
- ${verdict.summary}
169
-
170
- ${verdict.issues.length > 0 ? `## Issues\n${verdict.issues.map(i => `- ${i}`).join("\n")}` : ""}
171
-
172
- ${verdict.suggestions.length > 0 ? `## Suggestions\n${verdict.suggestions.map(s => `- ${s}`).join("\n")}` : ""}
173
-
174
- ${verdict.verdict === "SHIP" ? "✅ Ready to merge!" : verdict.verdict === "NEEDS_WORK" ? "⚠️ Address issues and re-review." : "🔄 Consider re-planning this task."}`;
175
-
176
- return result(text, {
177
- mode: "review",
178
- type: "impl",
179
- taskId,
180
- verdict: verdict.verdict,
181
- issueCount: verdict.issues.length,
182
- suggestionCount: verdict.suggestions.length
183
- });
184
- }
185
-
186
- // =============================================================================
187
- // Plan Review
188
- // =============================================================================
189
-
190
- async function reviewPlan(cwd: string, modelOverride?: string) {
191
- const plan = store.getPlan(cwd);
192
- if (!plan) {
193
- return result("Error: No plan found.", {
194
- mode: "review",
195
- error: "no_plan"
196
- });
197
- }
198
-
199
- const planSpec = store.getPlanSpec(cwd);
200
- const tasks = store.getTasks(cwd);
201
-
202
- // Build task overview
203
- const taskOverview = tasks.map(t => {
204
- const spec = store.getTaskSpec(cwd, t.id);
205
- const deps = t.depends_on.length > 0 ? ` (deps: ${t.depends_on.join(", ")})` : "";
206
- const specPreview = spec && !spec.includes("*Spec pending*")
207
- ? `\n ${spec.slice(0, 200)}${spec.length > 200 ? "..." : ""}`
208
- : "";
209
- return `- ${t.id}: ${t.title}${deps}${specPreview}`;
210
- }).join("\n");
211
-
212
- // Build review prompt
213
- const prompt = `# Plan Review Request
214
-
215
- ## Plan Information
216
-
217
- **PRD:** ${store.getPlanLabel(plan)}
218
- **Tasks:** ${tasks.length}
219
- **Progress:** ${plan.completed_count}/${plan.task_count}
220
-
221
- ## Plan Specification
222
-
223
- ${planSpec || "*No spec available*"}
224
-
225
- ## Task Breakdown
226
-
227
- ${taskOverview || "*No tasks*"}
228
-
229
- ## Your Review
230
-
231
- Review this plan for:
232
- 1. Completeness - Are all requirements covered?
233
- 2. Task granularity - Are tasks appropriately sized?
234
- 3. Dependencies - Are dependencies correct and complete?
235
- 4. Gaps - Are there missing tasks or edge cases?
236
- 5. Parallelism - Are there unnecessary sequential dependencies? Tasks that don't share files or types should be independent.
237
- 6. Critical path - What's the longest dependency chain? Could it be shortened?
238
-
239
- Output your verdict as SHIP (plan is solid), NEEDS_WORK (minor adjustments), or MAJOR_RETHINK (fundamental issues).`;
240
-
241
- // Spawn reviewer
242
- const [reviewResult] = await spawnAgents([{
243
- agent: "crew-reviewer",
244
- task: prompt,
245
- modelOverride,
246
- }], cwd);
247
-
248
- if (reviewResult.exitCode !== 0) {
249
- return result(`Error: Reviewer failed: ${reviewResult.error ?? "Unknown error"}`, {
250
- mode: "review",
251
- error: "reviewer_failed"
252
- });
253
- }
254
-
255
- // Parse verdict
256
- const verdict: ParsedReview = parseVerdict(reviewResult.output);
257
-
258
- const text = `# Plan Review
259
-
260
- **PRD:** ${store.getPlanLabel(plan)}
261
- **Verdict:** ${verdict.verdict}
262
-
263
- ${verdict.summary}
264
-
265
- ${verdict.issues.length > 0 ? `## Issues\n${verdict.issues.map(i => `- ${i}`).join("\n")}` : ""}
266
-
267
- ${verdict.suggestions.length > 0 ? `## Suggestions\n${verdict.suggestions.map(s => `- ${s}`).join("\n")}` : ""}
268
-
269
- ${verdict.verdict === "SHIP" ? "✅ Plan is ready for execution!" : verdict.verdict === "NEEDS_WORK" ? "⚠️ Adjust plan before starting work." : "🔄 Consider re-planning with more context."}`;
270
-
271
- return result(text, {
272
- mode: "review",
273
- type: "plan",
274
- prd: plan.prd,
275
- verdict: verdict.verdict,
276
- issueCount: verdict.issues.length,
277
- suggestionCount: verdict.suggestions.length
278
- });
279
- }
280
-
281
- // =============================================================================
282
- // Helpers
283
- // =============================================================================
284
-
285
- // Resolve the task's branch (task/<id>), if it exists. Branches are shared
286
- // refs, so this covers branches checked out in linked worktrees as well.
287
- function getTaskBranch(taskId: string, cwd: string): string | null {
288
- try {
289
- execSync(`git rev-parse --verify refs/heads/task/${taskId}`, {
290
- cwd,
291
- encoding: "utf-8",
292
- stdio: ["pipe", "pipe", "pipe"],
293
- timeout: 2000,
294
- });
295
- return `task/${taskId}`;
296
- } catch {
297
- return null;
298
- }
299
- }
300
-
301
- type GitDiffResult =
302
- | { status: "content"; text: string }
303
- | { status: "empty"; text: "*No changes*" }
304
- | { status: "error"; text: string };
305
-
306
- function getGitDiff(baseCommit: string, cwd: string, ref?: string): GitDiffResult {
307
- const range = ref ? `${baseCommit}...${ref}` : `${baseCommit}..HEAD`;
308
- try {
309
- const diff = execSync(
310
- `git diff ${range}`,
311
- { cwd, encoding: "utf-8", maxBuffer: 5 * 1024 * 1024, stdio: ["pipe", "pipe", "pipe"] }
312
- );
313
- if (diff.length > 50000) {
314
- return { status: "content", text: diff.slice(0, 50000) + "\n\n[Diff truncated - too large]" };
315
- }
316
- return diff ? { status: "content", text: diff } : { status: "empty", text: "*No changes*" };
317
- } catch (err) {
318
- const message = err instanceof Error ? err.message : "Unknown error";
319
- return { status: "error", text: `*Failed to get diff: ${message}*` };
320
- }
321
- }
322
-
323
- function getCommitLog(baseCommit: string, cwd: string, ref?: string): string {
324
- const range = ref ? `${baseCommit}..${ref}` : `${baseCommit}..HEAD`;
325
- try {
326
- return execSync(
327
- `git log ${range} --oneline --no-decorate`,
328
- { cwd, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }
329
- ).trim() || "*No commits*";
330
- } catch {
331
- return "*No commits*";
332
- }
333
- }
1
+ /**
2
+ * Crew - Review Handler
3
+ *
4
+ * Spawns reviewer with git diff context for task or plan review.
5
+ * Simplified: works with current plan
6
+ */
7
+
8
+ import { execSync } from "node:child_process";
9
+ import type { ExtensionContext } from "@linxiraos/zeta";
10
+ import type { CrewParams } from "../types.ts";
11
+ import { result } from "../utils/result.ts";
12
+ import { spawnAgents } from "../agents.ts";
13
+ import { discoverCrewAgents } from "../utils/discover.ts";
14
+ import { loadCrewConfig } from "../utils/config.ts";
15
+ import { parseVerdict, type ParsedReview } from "../utils/verdict.ts";
16
+ import * as store from "../store.ts";
17
+
18
+ export async function execute(params: CrewParams, ctx: ExtensionContext, sessionModel?: string) {
19
+ const cwd = ctx.cwd;
20
+ const { target, type } = params;
21
+ const config = loadCrewConfig(store.getCrewDir(cwd));
22
+ const reviewerModel = config.models?.reviewer ?? sessionModel;
23
+
24
+ if (!target) {
25
+ return result(
26
+ 'Error: target (task ID) required for review action.\n\nUsage: pi_messenger({ action: "review", target: "task-1" })',
27
+ {
28
+ mode: "review",
29
+ error: "missing_target",
30
+ },
31
+ );
32
+ }
33
+
34
+ // Check for reviewer agent
35
+ const availableAgents = discoverCrewAgents(cwd);
36
+ const hasReviewer = availableAgents.some(a => a.name === "crew-reviewer");
37
+ if (!hasReviewer) {
38
+ return result("Error: crew-reviewer agent not found. Required for code review.", {
39
+ mode: "review",
40
+ error: "no_reviewer",
41
+ });
42
+ }
43
+
44
+ if (type && type !== "impl" && type !== "plan") {
45
+ return result("Error: review type must be 'impl' or 'plan'.", {
46
+ mode: "review",
47
+ error: "invalid_type",
48
+ type,
49
+ });
50
+ }
51
+
52
+ // Determine review type: "impl" for task, "plan" for plan review
53
+ const reviewType = type ?? (target.startsWith("task-") ? "impl" : "plan");
54
+
55
+ if (reviewType === "impl") {
56
+ return reviewImplementation(cwd, target, reviewerModel);
57
+ } else {
58
+ return reviewPlan(cwd, reviewerModel);
59
+ }
60
+ }
61
+
62
+ // =============================================================================
63
+ // Implementation Review
64
+ // =============================================================================
65
+
66
+ export async function reviewImplementation(cwd: string, taskId: string, modelOverride?: string) {
67
+ const task = store.getTask(cwd, taskId);
68
+ if (!task) {
69
+ return result(`Error: Task ${taskId} not found.`, {
70
+ mode: "review",
71
+ error: "task_not_found",
72
+ target: taskId,
73
+ });
74
+ }
75
+
76
+ if (task.status !== "done" && task.status !== "in_progress") {
77
+ return result(`Error: Task ${taskId} is ${task.status}. Can only review in_progress or done tasks.`, {
78
+ mode: "review",
79
+ error: "invalid_status",
80
+ status: task.status,
81
+ });
82
+ }
83
+
84
+ // Get git diff
85
+ const baseCommit = task.base_commit;
86
+ if (!baseCommit) {
87
+ return result(`Error: Task ${taskId} has no base_commit. Cannot generate diff.`, {
88
+ mode: "review",
89
+ error: "no_base_commit",
90
+ });
91
+ }
92
+
93
+ const taskBranch = getTaskBranch(taskId, cwd);
94
+ const diffResult = getGitDiff(baseCommit, cwd, taskBranch ?? undefined);
95
+ const diff = diffResult.text;
96
+ const commitLog = getCommitLog(baseCommit, cwd, taskBranch ?? undefined);
97
+ const diffError =
98
+ taskBranch && diffResult.status === "empty"
99
+ ? `**ERROR:** Task branch \`${taskBranch}\` exists but has no changes relative to base ${baseCommit.slice(0, 12)}. The implementation appears to be missing from the branch.`
100
+ : null;
101
+
102
+ // Get task spec for context
103
+ const taskSpec = store.getTaskSpec(cwd, taskId) ?? "";
104
+ const plan = store.getPlan(cwd);
105
+
106
+ // Build review prompt
107
+ const prompt = `# Code Review Request
108
+
109
+ ## Task Information
110
+
111
+ **Task ID:** ${taskId}
112
+ **Task Title:** ${task.title}
113
+ **PRD:** ${plan?.prd ?? "Unknown"}
114
+
115
+ ## Task Specification
116
+
117
+ ${taskSpec || "*No spec available*"}
118
+
119
+ ## Changes
120
+ ### Commits
121
+ ${commitLog || "*No commits*"}
122
+
123
+ ### Diff
124
+ ${
125
+ diffError ??
126
+ `\`\`\`diff
127
+ ${diff}
128
+ \`\`\``
129
+ }
130
+
131
+ ## Your Review
132
+
133
+ Review this implementation following the crew-reviewer protocol.
134
+ Output your verdict as SHIP, NEEDS_WORK, or MAJOR_RETHINK with detailed feedback.`;
135
+
136
+ // Spawn reviewer
137
+ const [reviewResult] = await spawnAgents(
138
+ [
139
+ {
140
+ agent: "crew-reviewer",
141
+ task: prompt,
142
+ modelOverride,
143
+ },
144
+ ],
145
+ cwd,
146
+ );
147
+
148
+ if (reviewResult.exitCode !== 0) {
149
+ return result(`Error: Reviewer failed: ${reviewResult.error ?? "Unknown error"}`, {
150
+ mode: "review",
151
+ error: "reviewer_failed",
152
+ });
153
+ }
154
+
155
+ // Parse verdict from output
156
+ const verdict: ParsedReview = parseVerdict(reviewResult.output);
157
+
158
+ // Store review feedback in task for retry context
159
+ store.updateTask(cwd, taskId, {
160
+ last_review: {
161
+ verdict: verdict.verdict,
162
+ summary: verdict.summary,
163
+ issues: verdict.issues,
164
+ suggestions: verdict.suggestions,
165
+ reviewed_at: new Date().toISOString(),
166
+ },
167
+ });
168
+ const shortSummary = verdict.summary.split("\n")[0].slice(0, 120);
169
+ const progressMsg = `Review: ${verdict.verdict} — ${shortSummary}`;
170
+ store.appendTaskProgress(cwd, taskId, "system", progressMsg);
171
+
172
+ const text = `# Review: ${taskId}
173
+
174
+ **Verdict:** ${verdict.verdict}
175
+
176
+ ${verdict.summary}
177
+
178
+ ${verdict.issues.length > 0 ? `## Issues\n${verdict.issues.map(i => `- ${i}`).join("\n")}` : ""}
179
+
180
+ ${verdict.suggestions.length > 0 ? `## Suggestions\n${verdict.suggestions.map(s => `- ${s}`).join("\n")}` : ""}
181
+
182
+ ${verdict.verdict === "SHIP" ? "✅ Ready to merge!" : verdict.verdict === "NEEDS_WORK" ? "⚠️ Address issues and re-review." : "🔄 Consider re-planning this task."}`;
183
+
184
+ return result(text, {
185
+ mode: "review",
186
+ type: "impl",
187
+ taskId,
188
+ verdict: verdict.verdict,
189
+ issueCount: verdict.issues.length,
190
+ suggestionCount: verdict.suggestions.length,
191
+ });
192
+ }
193
+
194
+ // =============================================================================
195
+ // Plan Review
196
+ // =============================================================================
197
+
198
+ async function reviewPlan(cwd: string, modelOverride?: string) {
199
+ const plan = store.getPlan(cwd);
200
+ if (!plan) {
201
+ return result("Error: No plan found.", {
202
+ mode: "review",
203
+ error: "no_plan",
204
+ });
205
+ }
206
+
207
+ const planSpec = store.getPlanSpec(cwd);
208
+ const tasks = store.getTasks(cwd);
209
+
210
+ // Build task overview
211
+ const taskOverview = tasks
212
+ .map(t => {
213
+ const spec = store.getTaskSpec(cwd, t.id);
214
+ const deps = t.depends_on.length > 0 ? ` (deps: ${t.depends_on.join(", ")})` : "";
215
+ const specPreview =
216
+ spec && !spec.includes("*Spec pending*")
217
+ ? `\n ${spec.slice(0, 200)}${spec.length > 200 ? "..." : ""}`
218
+ : "";
219
+ return `- ${t.id}: ${t.title}${deps}${specPreview}`;
220
+ })
221
+ .join("\n");
222
+
223
+ // Build review prompt
224
+ const prompt = `# Plan Review Request
225
+
226
+ ## Plan Information
227
+
228
+ **PRD:** ${store.getPlanLabel(plan)}
229
+ **Tasks:** ${tasks.length}
230
+ **Progress:** ${plan.completed_count}/${plan.task_count}
231
+
232
+ ## Plan Specification
233
+
234
+ ${planSpec || "*No spec available*"}
235
+
236
+ ## Task Breakdown
237
+
238
+ ${taskOverview || "*No tasks*"}
239
+
240
+ ## Your Review
241
+
242
+ Review this plan for:
243
+ 1. Completeness - Are all requirements covered?
244
+ 2. Task granularity - Are tasks appropriately sized?
245
+ 3. Dependencies - Are dependencies correct and complete?
246
+ 4. Gaps - Are there missing tasks or edge cases?
247
+ 5. Parallelism - Are there unnecessary sequential dependencies? Tasks that don't share files or types should be independent.
248
+ 6. Critical path - What's the longest dependency chain? Could it be shortened?
249
+
250
+ Output your verdict as SHIP (plan is solid), NEEDS_WORK (minor adjustments), or MAJOR_RETHINK (fundamental issues).`;
251
+
252
+ // Spawn reviewer
253
+ const [reviewResult] = await spawnAgents(
254
+ [
255
+ {
256
+ agent: "crew-reviewer",
257
+ task: prompt,
258
+ modelOverride,
259
+ },
260
+ ],
261
+ cwd,
262
+ );
263
+
264
+ if (reviewResult.exitCode !== 0) {
265
+ return result(`Error: Reviewer failed: ${reviewResult.error ?? "Unknown error"}`, {
266
+ mode: "review",
267
+ error: "reviewer_failed",
268
+ });
269
+ }
270
+
271
+ // Parse verdict
272
+ const verdict: ParsedReview = parseVerdict(reviewResult.output);
273
+
274
+ const text = `# Plan Review
275
+
276
+ **PRD:** ${store.getPlanLabel(plan)}
277
+ **Verdict:** ${verdict.verdict}
278
+
279
+ ${verdict.summary}
280
+
281
+ ${verdict.issues.length > 0 ? `## Issues\n${verdict.issues.map(i => `- ${i}`).join("\n")}` : ""}
282
+
283
+ ${verdict.suggestions.length > 0 ? `## Suggestions\n${verdict.suggestions.map(s => `- ${s}`).join("\n")}` : ""}
284
+
285
+ ${verdict.verdict === "SHIP" ? "✅ Plan is ready for execution!" : verdict.verdict === "NEEDS_WORK" ? "⚠️ Adjust plan before starting work." : "🔄 Consider re-planning with more context."}`;
286
+
287
+ return result(text, {
288
+ mode: "review",
289
+ type: "plan",
290
+ prd: plan.prd,
291
+ verdict: verdict.verdict,
292
+ issueCount: verdict.issues.length,
293
+ suggestionCount: verdict.suggestions.length,
294
+ });
295
+ }
296
+
297
+ // =============================================================================
298
+ // Helpers
299
+ // =============================================================================
300
+
301
+ // Resolve the task's branch (task/<id>), if it exists. Branches are shared
302
+ // refs, so this covers branches checked out in linked worktrees as well.
303
+ function getTaskBranch(taskId: string, cwd: string): string | null {
304
+ try {
305
+ execSync(`git rev-parse --verify refs/heads/task/${taskId}`, {
306
+ cwd,
307
+ encoding: "utf-8",
308
+ stdio: ["pipe", "pipe", "pipe"],
309
+ timeout: 2000,
310
+ });
311
+ return `task/${taskId}`;
312
+ } catch {
313
+ return null;
314
+ }
315
+ }
316
+
317
+ type GitDiffResult =
318
+ | { status: "content"; text: string }
319
+ | { status: "empty"; text: "*No changes*" }
320
+ | { status: "error"; text: string };
321
+
322
+ function getGitDiff(baseCommit: string, cwd: string, ref?: string): GitDiffResult {
323
+ const range = ref ? `${baseCommit}...${ref}` : `${baseCommit}..HEAD`;
324
+ try {
325
+ const diff = execSync(`git diff ${range}`, {
326
+ cwd,
327
+ encoding: "utf-8",
328
+ maxBuffer: 5 * 1024 * 1024,
329
+ stdio: ["pipe", "pipe", "pipe"],
330
+ });
331
+ if (diff.length > 50000) {
332
+ return { status: "content", text: diff.slice(0, 50000) + "\n\n[Diff truncated - too large]" };
333
+ }
334
+ return diff ? { status: "content", text: diff } : { status: "empty", text: "*No changes*" };
335
+ } catch (err) {
336
+ const message = err instanceof Error ? err.message : "Unknown error";
337
+ return { status: "error", text: `*Failed to get diff: ${message}*` };
338
+ }
339
+ }
340
+
341
+ function getCommitLog(baseCommit: string, cwd: string, ref?: string): string {
342
+ const range = ref ? `${baseCommit}..${ref}` : `${baseCommit}..HEAD`;
343
+ try {
344
+ return (
345
+ execSync(`git log ${range} --oneline --no-decorate`, {
346
+ cwd,
347
+ encoding: "utf-8",
348
+ stdio: ["pipe", "pipe", "pipe"],
349
+ }).trim() || "*No commits*"
350
+ );
351
+ } catch {
352
+ return "*No commits*";
353
+ }
354
+ }