opencode-swarm-plugin 0.26.1 → 0.27.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 (77) hide show
  1. package/.turbo/turbo-build.log +4 -4
  2. package/CHANGELOG.md +23 -0
  3. package/README.md +43 -46
  4. package/bin/swarm.ts +8 -8
  5. package/dist/compaction-hook.d.ts +57 -0
  6. package/dist/compaction-hook.d.ts.map +1 -0
  7. package/dist/hive.d.ts +741 -0
  8. package/dist/hive.d.ts.map +1 -0
  9. package/dist/index.d.ts +139 -23
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +1353 -350
  12. package/dist/learning.d.ts +9 -9
  13. package/dist/plugin.js +1176 -350
  14. package/dist/schemas/cell-events.d.ts +1352 -0
  15. package/dist/schemas/{bead-events.d.ts.map → cell-events.d.ts.map} +1 -1
  16. package/dist/schemas/{bead.d.ts → cell.d.ts} +173 -29
  17. package/dist/schemas/cell.d.ts.map +1 -0
  18. package/dist/schemas/index.d.ts +11 -7
  19. package/dist/schemas/index.d.ts.map +1 -1
  20. package/dist/structured.d.ts +17 -7
  21. package/dist/structured.d.ts.map +1 -1
  22. package/dist/swarm-decompose.d.ts +5 -5
  23. package/dist/swarm-orchestrate.d.ts +16 -2
  24. package/dist/swarm-orchestrate.d.ts.map +1 -1
  25. package/dist/swarm-prompts.d.ts +9 -9
  26. package/dist/swarm-prompts.d.ts.map +1 -1
  27. package/dist/swarm-review.d.ts +210 -0
  28. package/dist/swarm-review.d.ts.map +1 -0
  29. package/dist/swarm-worktree.d.ts +185 -0
  30. package/dist/swarm-worktree.d.ts.map +1 -0
  31. package/dist/swarm.d.ts +7 -0
  32. package/dist/swarm.d.ts.map +1 -1
  33. package/dist/tool-availability.d.ts +3 -2
  34. package/dist/tool-availability.d.ts.map +1 -1
  35. package/docs/analysis-socratic-planner-pattern.md +1 -1
  36. package/docs/planning/ADR-007-swarm-enhancements-worktree-review.md +168 -0
  37. package/docs/testing/context-recovery-test.md +2 -2
  38. package/evals/README.md +2 -2
  39. package/evals/scorers/index.ts +7 -7
  40. package/examples/commands/swarm.md +21 -23
  41. package/examples/plugin-wrapper-template.ts +310 -44
  42. package/examples/skills/{beads-workflow → hive-workflow}/SKILL.md +40 -40
  43. package/examples/skills/swarm-coordination/SKILL.md +1 -1
  44. package/global-skills/swarm-coordination/SKILL.md +14 -14
  45. package/global-skills/swarm-coordination/references/coordinator-patterns.md +3 -3
  46. package/package.json +2 -2
  47. package/src/compaction-hook.ts +161 -0
  48. package/src/{beads.integration.test.ts → hive.integration.test.ts} +92 -80
  49. package/src/{beads.ts → hive.ts} +378 -219
  50. package/src/index.ts +57 -20
  51. package/src/learning.ts +9 -9
  52. package/src/output-guardrails.test.ts +4 -4
  53. package/src/output-guardrails.ts +9 -9
  54. package/src/planning-guardrails.test.ts +1 -1
  55. package/src/planning-guardrails.ts +1 -1
  56. package/src/schemas/{bead-events.test.ts → cell-events.test.ts} +83 -77
  57. package/src/schemas/cell-events.ts +807 -0
  58. package/src/schemas/{bead.ts → cell.ts} +95 -41
  59. package/src/schemas/evaluation.ts +1 -1
  60. package/src/schemas/index.ts +90 -18
  61. package/src/schemas/swarm-context.ts +2 -2
  62. package/src/structured.test.ts +15 -15
  63. package/src/structured.ts +18 -11
  64. package/src/swarm-decompose.ts +23 -23
  65. package/src/swarm-orchestrate.ts +135 -21
  66. package/src/swarm-prompts.ts +43 -43
  67. package/src/swarm-review.test.ts +702 -0
  68. package/src/swarm-review.ts +696 -0
  69. package/src/swarm-worktree.test.ts +501 -0
  70. package/src/swarm-worktree.ts +575 -0
  71. package/src/swarm.integration.test.ts +12 -12
  72. package/src/tool-availability.ts +36 -3
  73. package/dist/beads.d.ts +0 -386
  74. package/dist/beads.d.ts.map +0 -1
  75. package/dist/schemas/bead-events.d.ts +0 -698
  76. package/dist/schemas/bead.d.ts.map +0 -1
  77. package/src/schemas/bead-events.ts +0 -583
@@ -0,0 +1,696 @@
1
+ /**
2
+ * Swarm Structured Review Module
3
+ *
4
+ * Provides coordinator-driven review of worker output before completion.
5
+ * The review is epic-aware - it checks if work serves the overall goal
6
+ * and enables downstream tasks.
7
+ *
8
+ * Key features:
9
+ * - Generate review prompts with full epic context
10
+ * - Track review attempts (max 3 before task fails)
11
+ * - Send structured feedback to workers
12
+ * - Gate completion on review approval
13
+ *
14
+ * Credit: Review patterns inspired by https://github.com/nexxeln/opencode-config
15
+ */
16
+
17
+ import { tool } from "@opencode-ai/plugin";
18
+ import { z } from "zod";
19
+ import { sendSwarmMessage, type HiveAdapter } from "swarm-mail";
20
+ import { getHiveAdapter } from "./hive";
21
+
22
+ // ============================================================================
23
+ // Types & Schemas
24
+ // ============================================================================
25
+
26
+ /**
27
+ * Review issue - a specific problem found during review
28
+ */
29
+ export interface ReviewIssue {
30
+ file: string;
31
+ line?: number;
32
+ issue: string;
33
+ suggestion?: string;
34
+ }
35
+
36
+ export const ReviewIssueSchema = z.object({
37
+ file: z.string(),
38
+ line: z.number().optional(),
39
+ issue: z.string(),
40
+ suggestion: z.string().optional(),
41
+ });
42
+
43
+ /**
44
+ * Review result - the outcome of a review
45
+ */
46
+ export interface ReviewResult {
47
+ status: "approved" | "needs_changes";
48
+ summary?: string;
49
+ issues?: ReviewIssue[];
50
+ remaining_attempts?: number;
51
+ }
52
+
53
+ export const ReviewResultSchema = z
54
+ .object({
55
+ status: z.enum(["approved", "needs_changes"]),
56
+ summary: z.string().optional(),
57
+ issues: z.array(ReviewIssueSchema).optional(),
58
+ remaining_attempts: z.number().optional(),
59
+ })
60
+ .refine(
61
+ (data) => {
62
+ // If status is needs_changes, issues must be provided
63
+ if (data.status === "needs_changes") {
64
+ return data.issues && data.issues.length > 0;
65
+ }
66
+ return true;
67
+ },
68
+ {
69
+ message: "issues array is required when status is 'needs_changes'",
70
+ }
71
+ );
72
+
73
+ /**
74
+ * Dependency info for review context
75
+ */
76
+ export interface DependencyInfo {
77
+ id: string;
78
+ title: string;
79
+ summary?: string;
80
+ }
81
+
82
+ /**
83
+ * Downstream task info
84
+ */
85
+ export interface DownstreamTask {
86
+ id: string;
87
+ title: string;
88
+ }
89
+
90
+ /**
91
+ * Review prompt context
92
+ */
93
+ export interface ReviewPromptContext {
94
+ epic_id: string;
95
+ epic_title: string;
96
+ epic_description?: string;
97
+ task_id: string;
98
+ task_title: string;
99
+ task_description?: string;
100
+ files_touched: string[];
101
+ diff: string;
102
+ completed_dependencies?: DependencyInfo[];
103
+ downstream_tasks?: DownstreamTask[];
104
+ }
105
+
106
+ // ============================================================================
107
+ // Review Attempt Tracking
108
+ // ============================================================================
109
+
110
+ /**
111
+ * In-memory tracking of review attempts per task
112
+ * Key: task_id, Value: attempt count
113
+ */
114
+ const reviewAttempts = new Map<string, number>();
115
+
116
+ const MAX_REVIEW_ATTEMPTS = 3;
117
+
118
+ /**
119
+ * Get current attempt count for a task
120
+ */
121
+ function getAttemptCount(taskId: string): number {
122
+ return reviewAttempts.get(taskId) || 0;
123
+ }
124
+
125
+ /**
126
+ * Increment attempt count for a task
127
+ * @returns New attempt count
128
+ */
129
+ function incrementAttempt(taskId: string): number {
130
+ const current = getAttemptCount(taskId);
131
+ const newCount = current + 1;
132
+ reviewAttempts.set(taskId, newCount);
133
+ return newCount;
134
+ }
135
+
136
+ /**
137
+ * Clear attempt count (on success or task reset)
138
+ */
139
+ function clearAttempts(taskId: string): void {
140
+ reviewAttempts.delete(taskId);
141
+ }
142
+
143
+ /**
144
+ * Get remaining attempts
145
+ */
146
+ function getRemainingAttempts(taskId: string): number {
147
+ return MAX_REVIEW_ATTEMPTS - getAttemptCount(taskId);
148
+ }
149
+
150
+ // ============================================================================
151
+ // Review Prompt Generation
152
+ // ============================================================================
153
+
154
+ /**
155
+ * Generate a review prompt with full epic context
156
+ *
157
+ * The prompt includes:
158
+ * - Epic goal (big picture)
159
+ * - Task requirements
160
+ * - Dependency context (what this builds on)
161
+ * - Downstream context (what depends on this)
162
+ * - The actual code diff
163
+ * - Review criteria checklist
164
+ */
165
+ export function generateReviewPrompt(context: ReviewPromptContext): string {
166
+ const sections: string[] = [];
167
+
168
+ // Header
169
+ sections.push(`# Code Review: ${context.task_title}`);
170
+ sections.push("");
171
+
172
+ // Epic context (big picture)
173
+ sections.push("## Epic Goal");
174
+ sections.push(`**${context.epic_title}**`);
175
+ if (context.epic_description) {
176
+ sections.push(context.epic_description);
177
+ }
178
+ sections.push("");
179
+
180
+ // Task requirements
181
+ sections.push("## Task Requirements");
182
+ sections.push(`**${context.task_title}**`);
183
+ if (context.task_description) {
184
+ sections.push(context.task_description);
185
+ }
186
+ sections.push("");
187
+
188
+ // Dependency context
189
+ if (
190
+ context.completed_dependencies &&
191
+ context.completed_dependencies.length > 0
192
+ ) {
193
+ sections.push("## This Task Builds On");
194
+ for (const dep of context.completed_dependencies) {
195
+ sections.push(`- **${dep.title}** (${dep.id})`);
196
+ if (dep.summary) {
197
+ sections.push(` ${dep.summary}`);
198
+ }
199
+ }
200
+ sections.push("");
201
+ }
202
+
203
+ // Downstream context
204
+ if (context.downstream_tasks && context.downstream_tasks.length > 0) {
205
+ sections.push("## Downstream Tasks (depend on this)");
206
+ for (const task of context.downstream_tasks) {
207
+ sections.push(`- **${task.title}** (${task.id})`);
208
+ }
209
+ sections.push("");
210
+ }
211
+
212
+ // Files touched
213
+ sections.push("## Files Modified");
214
+ for (const file of context.files_touched) {
215
+ sections.push(`- \`${file}\``);
216
+ }
217
+ sections.push("");
218
+
219
+ // Code diff
220
+ sections.push("## Code Changes");
221
+ sections.push("```diff");
222
+ sections.push(context.diff);
223
+ sections.push("```");
224
+ sections.push("");
225
+
226
+ // Review criteria
227
+ sections.push("## Review Criteria");
228
+ sections.push("");
229
+ sections.push("Please evaluate the changes against these criteria:");
230
+ sections.push("");
231
+ sections.push(
232
+ "1. **Fulfills Requirements**: Does the code implement what the task requires?"
233
+ );
234
+ sections.push(
235
+ "2. **Serves Epic Goal**: Does this work contribute to the overall epic objective?"
236
+ );
237
+ sections.push(
238
+ "3. **Enables Downstream**: Can downstream tasks use this work as expected?"
239
+ );
240
+ sections.push("4. **Type Safety**: Are types correct and complete?");
241
+ sections.push("5. **No Critical Bugs**: Are there any obvious bugs or issues?");
242
+ sections.push(
243
+ "6. **Test Coverage**: Are there tests for the new code? (warning only)"
244
+ );
245
+ sections.push("");
246
+
247
+ // Response format
248
+ sections.push("## Response Format");
249
+ sections.push("");
250
+ sections.push("Respond with a JSON object:");
251
+ sections.push("```json");
252
+ sections.push(`{
253
+ "status": "approved" | "needs_changes",
254
+ "summary": "Brief summary of your review",
255
+ "issues": [
256
+ {
257
+ "file": "path/to/file.ts",
258
+ "line": 42,
259
+ "issue": "Description of the problem",
260
+ "suggestion": "How to fix it"
261
+ }
262
+ ]
263
+ }`);
264
+ sections.push("```");
265
+
266
+ return sections.join("\n");
267
+ }
268
+
269
+ // ============================================================================
270
+ // HiveAdapter Helper
271
+ // ============================================================================
272
+
273
+ /**
274
+ * Get or create a HiveAdapter for a project (safe wrapper)
275
+ */
276
+ async function getHiveAdapterSafe(projectPath: string): Promise<HiveAdapter | null> {
277
+ try {
278
+ return getHiveAdapter(projectPath);
279
+ } catch {
280
+ return null;
281
+ }
282
+ }
283
+
284
+ /**
285
+ * Get dependencies for a cell by querying all cells and checking their parent_id
286
+ * Note: This is a simplified approach - a full implementation would use the dependency graph
287
+ */
288
+ async function getCellDependencies(
289
+ adapter: HiveAdapter,
290
+ projectKey: string,
291
+ _cellId: string,
292
+ epicId: string
293
+ ): Promise<{ completed: DependencyInfo[]; downstream: DownstreamTask[] }> {
294
+ const completedDependencies: DependencyInfo[] = [];
295
+ const downstreamTasks: DownstreamTask[] = [];
296
+
297
+ try {
298
+ // Get all subtasks of the epic
299
+ const subtasks = await adapter.queryCells(projectKey, { parent_id: epicId });
300
+
301
+ for (const subtask of subtasks) {
302
+ // Skip the current task
303
+ if (subtask.id === _cellId) continue;
304
+
305
+ // Completed tasks are potential dependencies
306
+ if (subtask.status === "closed") {
307
+ completedDependencies.push({
308
+ id: subtask.id,
309
+ title: subtask.title,
310
+ summary: subtask.closed_reason ?? undefined,
311
+ });
312
+ }
313
+
314
+ // For downstream, we'd need to check the dependency graph
315
+ // For now, we include all non-closed tasks as potential downstream
316
+ if (subtask.status !== "closed") {
317
+ downstreamTasks.push({
318
+ id: subtask.id,
319
+ title: subtask.title,
320
+ });
321
+ }
322
+ }
323
+ } catch {
324
+ // Continue without dependency info
325
+ }
326
+
327
+ return { completed: completedDependencies, downstream: downstreamTasks };
328
+ }
329
+
330
+ // ============================================================================
331
+ // Tool Definitions
332
+ // ============================================================================
333
+
334
+ /**
335
+ * Generate a review prompt for a completed subtask
336
+ *
337
+ * Fetches epic and task details, gets the git diff, and generates
338
+ * a comprehensive review prompt.
339
+ */
340
+ export const swarm_review = tool({
341
+ description:
342
+ "Generate a review prompt for a completed subtask. Includes epic context, dependencies, and diff.",
343
+ args: {
344
+ project_key: z.string().describe("Project path"),
345
+ epic_id: z.string().describe("Epic cell ID"),
346
+ task_id: z.string().describe("Subtask cell ID to review"),
347
+ files_touched: z
348
+ .array(z.string())
349
+ .optional()
350
+ .describe("Files modified (will get diff for these)"),
351
+ },
352
+ async execute(args): Promise<string> {
353
+ let epicTitle = args.epic_id;
354
+ let epicDescription: string | undefined;
355
+ let taskTitle = args.task_id;
356
+ let taskDescription: string | undefined;
357
+ let completedDependencies: DependencyInfo[] = [];
358
+ let downstreamTasks: DownstreamTask[] = [];
359
+
360
+ // Try to get cell details from HiveAdapter
361
+ const adapter = await getHiveAdapterSafe(args.project_key);
362
+ if (adapter) {
363
+ try {
364
+ // Get epic details
365
+ const epic = await adapter.getCell(args.project_key, args.epic_id);
366
+ if (epic) {
367
+ epicTitle = epic.title || epicTitle;
368
+ epicDescription = epic.description ?? undefined;
369
+ }
370
+
371
+ // Get task details
372
+ const task = await adapter.getCell(args.project_key, args.task_id);
373
+ if (task) {
374
+ taskTitle = task.title || taskTitle;
375
+ taskDescription = task.description ?? undefined;
376
+ }
377
+
378
+ // Get dependencies
379
+ const deps = await getCellDependencies(
380
+ adapter,
381
+ args.project_key,
382
+ args.task_id,
383
+ args.epic_id
384
+ );
385
+ completedDependencies = deps.completed;
386
+ downstreamTasks = deps.downstream;
387
+ } catch {
388
+ // Continue with defaults if adapter fails
389
+ }
390
+ }
391
+
392
+ // Get git diff for files
393
+ let diff = "";
394
+ if (args.files_touched && args.files_touched.length > 0) {
395
+ try {
396
+ const diffResult = await Bun.$`git diff HEAD~1 -- ${args.files_touched}`
397
+ .cwd(args.project_key)
398
+ .quiet()
399
+ .nothrow();
400
+
401
+ if (diffResult.exitCode === 0) {
402
+ diff = diffResult.stdout.toString();
403
+ } else {
404
+ // Try staged diff
405
+ const stagedResult =
406
+ await Bun.$`git diff --cached -- ${args.files_touched}`
407
+ .cwd(args.project_key)
408
+ .quiet()
409
+ .nothrow();
410
+ diff = stagedResult.stdout.toString();
411
+ }
412
+ } catch {
413
+ // Git diff failed, continue without it
414
+ }
415
+ }
416
+
417
+ // Generate the review prompt
418
+ const reviewPrompt = generateReviewPrompt({
419
+ epic_id: args.epic_id,
420
+ epic_title: epicTitle,
421
+ epic_description: epicDescription,
422
+ task_id: args.task_id,
423
+ task_title: taskTitle,
424
+ task_description: taskDescription,
425
+ files_touched: args.files_touched || [],
426
+ diff: diff || "(no diff available)",
427
+ completed_dependencies:
428
+ completedDependencies.length > 0 ? completedDependencies : undefined,
429
+ downstream_tasks:
430
+ downstreamTasks.length > 0 ? downstreamTasks : undefined,
431
+ });
432
+
433
+ return JSON.stringify(
434
+ {
435
+ review_prompt: reviewPrompt,
436
+ context: {
437
+ epic_id: args.epic_id,
438
+ epic_title: epicTitle,
439
+ task_id: args.task_id,
440
+ task_title: taskTitle,
441
+ files_touched: args.files_touched || [],
442
+ completed_dependencies: completedDependencies.length,
443
+ downstream_tasks: downstreamTasks.length,
444
+ remaining_attempts: getRemainingAttempts(args.task_id),
445
+ },
446
+ },
447
+ null,
448
+ 2
449
+ );
450
+ },
451
+ });
452
+
453
+ /**
454
+ * Send review feedback to a worker
455
+ *
456
+ * Tracks review attempts and fails the task after 3 rejections.
457
+ */
458
+ export const swarm_review_feedback = tool({
459
+ description:
460
+ "Send review feedback to a worker. Tracks attempts (max 3). Fails task after 3 rejections.",
461
+ args: {
462
+ project_key: z.string().describe("Project path"),
463
+ task_id: z.string().describe("Subtask cell ID"),
464
+ worker_id: z.string().describe("Worker agent name"),
465
+ status: z.enum(["approved", "needs_changes"]).describe("Review status"),
466
+ summary: z.string().optional().describe("Review summary"),
467
+ issues: z
468
+ .string()
469
+ .optional()
470
+ .describe("JSON array of ReviewIssue objects (for needs_changes)"),
471
+ },
472
+ async execute(args): Promise<string> {
473
+ // Parse issues if provided
474
+ let parsedIssues: ReviewIssue[] = [];
475
+ if (args.issues) {
476
+ try {
477
+ parsedIssues = JSON.parse(args.issues);
478
+ } catch {
479
+ return JSON.stringify(
480
+ {
481
+ success: false,
482
+ error: "Failed to parse issues JSON",
483
+ },
484
+ null,
485
+ 2
486
+ );
487
+ }
488
+ }
489
+
490
+ // Validate: needs_changes requires issues
491
+ if (args.status === "needs_changes" && parsedIssues.length === 0) {
492
+ return JSON.stringify(
493
+ {
494
+ success: false,
495
+ error: "needs_changes status requires at least one issue",
496
+ },
497
+ null,
498
+ 2
499
+ );
500
+ }
501
+
502
+ // Extract epic ID for thread
503
+ const epicId = args.task_id.includes(".")
504
+ ? args.task_id.split(".")[0]
505
+ : args.task_id;
506
+
507
+ if (args.status === "approved") {
508
+ // Mark as approved and clear attempts
509
+ markReviewApproved(args.task_id);
510
+
511
+ // Send approval message
512
+ await sendSwarmMessage({
513
+ projectPath: args.project_key,
514
+ fromAgent: "coordinator",
515
+ toAgents: [args.worker_id],
516
+ subject: `APPROVED: ${args.task_id}`,
517
+ body: `## Review Approved ✓
518
+
519
+ ${args.summary || "Your work has been approved."}
520
+
521
+ You may now complete the task with \`swarm_complete\`.`,
522
+ threadId: epicId,
523
+ importance: "normal",
524
+ });
525
+
526
+ return JSON.stringify(
527
+ {
528
+ success: true,
529
+ status: "approved",
530
+ task_id: args.task_id,
531
+ message: "Review approved. Worker can now complete the task.",
532
+ },
533
+ null,
534
+ 2
535
+ );
536
+ }
537
+
538
+ // Handle needs_changes
539
+ const attemptNumber = incrementAttempt(args.task_id);
540
+ const remaining = MAX_REVIEW_ATTEMPTS - attemptNumber;
541
+
542
+ // Check if task should fail
543
+ if (remaining <= 0) {
544
+ // Mark task as blocked using HiveAdapter
545
+ const adapter = await getHiveAdapterSafe(args.project_key);
546
+ if (adapter) {
547
+ try {
548
+ await adapter.changeCellStatus(args.project_key, args.task_id, "blocked");
549
+ } catch {
550
+ // Continue even if status update fails
551
+ }
552
+ }
553
+
554
+ // Send failure message
555
+ await sendSwarmMessage({
556
+ projectPath: args.project_key,
557
+ fromAgent: "coordinator",
558
+ toAgents: [args.worker_id],
559
+ subject: `FAILED: ${args.task_id} - max review attempts reached`,
560
+ body: `## Task Failed ✗
561
+
562
+ Maximum review attempts (${MAX_REVIEW_ATTEMPTS}) reached.
563
+
564
+ **Last Issues:**
565
+ ${parsedIssues.map((i: ReviewIssue) => `- ${i.file}${i.line ? `:${i.line}` : ""}: ${i.issue}`).join("\n")}
566
+
567
+ The task has been marked as blocked. A human or different approach is needed.`,
568
+ threadId: epicId,
569
+ importance: "urgent",
570
+ });
571
+
572
+ return JSON.stringify(
573
+ {
574
+ success: true,
575
+ status: "needs_changes",
576
+ task_failed: true,
577
+ task_id: args.task_id,
578
+ attempt: attemptNumber,
579
+ remaining_attempts: 0,
580
+ message: `Task failed after ${MAX_REVIEW_ATTEMPTS} review attempts`,
581
+ },
582
+ null,
583
+ 2
584
+ );
585
+ }
586
+
587
+ // Send feedback message
588
+ const issuesList = parsedIssues
589
+ .map((i: ReviewIssue) => {
590
+ let line = `- **${i.file}**`;
591
+ if (i.line) line += `:${i.line}`;
592
+ line += `: ${i.issue}`;
593
+ if (i.suggestion) line += `\n → ${i.suggestion}`;
594
+ return line;
595
+ })
596
+ .join("\n");
597
+
598
+ await sendSwarmMessage({
599
+ projectPath: args.project_key,
600
+ fromAgent: "coordinator",
601
+ toAgents: [args.worker_id],
602
+ subject: `NEEDS CHANGES: ${args.task_id} (attempt ${attemptNumber}/${MAX_REVIEW_ATTEMPTS})`,
603
+ body: `## Review: Changes Needed
604
+
605
+ ${args.summary || "Please address the following issues:"}
606
+
607
+ **Issues:**
608
+ ${issuesList}
609
+
610
+ **Remaining attempts:** ${remaining}
611
+
612
+ Please fix these issues and request another review.`,
613
+ threadId: epicId,
614
+ importance: "high",
615
+ });
616
+
617
+ return JSON.stringify(
618
+ {
619
+ success: true,
620
+ status: "needs_changes",
621
+ task_id: args.task_id,
622
+ attempt: attemptNumber,
623
+ remaining_attempts: remaining,
624
+ issues: parsedIssues,
625
+ message: `Feedback sent. ${remaining} attempt(s) remaining.`,
626
+ },
627
+ null,
628
+ 2
629
+ );
630
+ },
631
+ });
632
+
633
+ // ============================================================================
634
+ // Review Gate for swarm_complete
635
+ // ============================================================================
636
+
637
+ /**
638
+ * Review status for a task
639
+ */
640
+ interface TaskReviewStatus {
641
+ reviewed: boolean;
642
+ approved: boolean;
643
+ attempt_count: number;
644
+ remaining_attempts: number;
645
+ }
646
+
647
+ /**
648
+ * In-memory tracking of review status per task
649
+ */
650
+ const reviewStatus = new Map<string, { approved: boolean; timestamp: number }>();
651
+
652
+ /**
653
+ * Mark a task as reviewed and approved
654
+ */
655
+ export function markReviewApproved(taskId: string): void {
656
+ reviewStatus.set(taskId, { approved: true, timestamp: Date.now() });
657
+ clearAttempts(taskId);
658
+ }
659
+
660
+ /**
661
+ * Check if a task has been approved
662
+ */
663
+ export function isReviewApproved(taskId: string): boolean {
664
+ const status = reviewStatus.get(taskId);
665
+ return status?.approved ?? false;
666
+ }
667
+
668
+ /**
669
+ * Get review status for a task
670
+ */
671
+ export function getReviewStatus(taskId: string): TaskReviewStatus {
672
+ const status = reviewStatus.get(taskId);
673
+ return {
674
+ reviewed: status !== undefined,
675
+ approved: status?.approved ?? false,
676
+ attempt_count: getAttemptCount(taskId),
677
+ remaining_attempts: getRemainingAttempts(taskId),
678
+ };
679
+ }
680
+
681
+ /**
682
+ * Clear review status (for testing or reset)
683
+ */
684
+ export function clearReviewStatus(taskId: string): void {
685
+ reviewStatus.delete(taskId);
686
+ clearAttempts(taskId);
687
+ }
688
+
689
+ // ============================================================================
690
+ // Exports
691
+ // ============================================================================
692
+
693
+ export const reviewTools = {
694
+ swarm_review,
695
+ swarm_review_feedback,
696
+ };