opencode-swarm-plugin 0.29.0 → 0.30.2

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 (42) hide show
  1. package/.turbo/turbo-build.log +4 -4
  2. package/CHANGELOG.md +94 -0
  3. package/README.md +3 -6
  4. package/bin/swarm.test.ts +163 -0
  5. package/bin/swarm.ts +304 -72
  6. package/dist/hive.d.ts.map +1 -1
  7. package/dist/index.d.ts +94 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +18825 -3469
  10. package/dist/memory-tools.d.ts +209 -0
  11. package/dist/memory-tools.d.ts.map +1 -0
  12. package/dist/memory.d.ts +124 -0
  13. package/dist/memory.d.ts.map +1 -0
  14. package/dist/plugin.js +18775 -3430
  15. package/dist/schemas/index.d.ts +7 -0
  16. package/dist/schemas/index.d.ts.map +1 -1
  17. package/dist/schemas/worker-handoff.d.ts +78 -0
  18. package/dist/schemas/worker-handoff.d.ts.map +1 -0
  19. package/dist/swarm-orchestrate.d.ts +50 -0
  20. package/dist/swarm-orchestrate.d.ts.map +1 -1
  21. package/dist/swarm-prompts.d.ts +1 -1
  22. package/dist/swarm-prompts.d.ts.map +1 -1
  23. package/dist/swarm-review.d.ts +4 -0
  24. package/dist/swarm-review.d.ts.map +1 -1
  25. package/docs/planning/ADR-008-worker-handoff-protocol.md +293 -0
  26. package/examples/plugin-wrapper-template.ts +157 -28
  27. package/package.json +3 -1
  28. package/src/hive.integration.test.ts +114 -0
  29. package/src/hive.ts +33 -22
  30. package/src/index.ts +41 -8
  31. package/src/memory-tools.test.ts +111 -0
  32. package/src/memory-tools.ts +273 -0
  33. package/src/memory.integration.test.ts +266 -0
  34. package/src/memory.test.ts +334 -0
  35. package/src/memory.ts +441 -0
  36. package/src/schemas/index.ts +18 -0
  37. package/src/schemas/worker-handoff.test.ts +271 -0
  38. package/src/schemas/worker-handoff.ts +131 -0
  39. package/src/swarm-orchestrate.ts +262 -24
  40. package/src/swarm-prompts.ts +48 -5
  41. package/src/swarm-review.ts +7 -0
  42. package/src/swarm.integration.test.ts +386 -9
@@ -26,6 +26,12 @@
26
26
  * - `AgentProgressSchema` - Individual agent status
27
27
  * - `SpawnedAgentSchema` - Spawned agent metadata
28
28
  *
29
+ * ## Worker Handoff Schemas (Swarm Contracts)
30
+ * - `WorkerHandoffSchema` - Complete structured handoff contract
31
+ * - `WorkerHandoffContractSchema` - Task contract (files, criteria)
32
+ * - `WorkerHandoffContextSchema` - Narrative context (epic summary, role)
33
+ * - `WorkerHandoffEscalationSchema` - Escalation protocols
34
+ *
29
35
  * @module schemas
30
36
  */
31
37
  export { CellStatusSchema, CellTypeSchema, CellDependencySchema, CellSchema, CellCreateArgsSchema, CellUpdateArgsSchema, CellCloseArgsSchema, CellQueryArgsSchema, SubtaskSpecSchema, CellTreeSchema, EpicCreateArgsSchema, EpicCreateResultSchema, type CellStatus, type CellType, type CellDependency, type Cell, type CellCreateArgs, type CellUpdateArgs, type CellCloseArgs, type CellQueryArgs, type SubtaskSpec, type CellTree, type EpicCreateArgs, type EpicCreateResult, } from "./cell";
@@ -34,6 +40,7 @@ export { CriterionEvaluationSchema, WeightedCriterionEvaluationSchema, Evaluatio
34
40
  export { EffortLevelSchema, DependencyTypeSchema, DecomposedSubtaskSchema, SubtaskDependencySchema, TaskDecompositionSchema, DecomposeArgsSchema, SpawnedAgentSchema, SwarmSpawnResultSchema, AgentProgressSchema, SwarmStatusSchema, type EffortLevel, type DependencyType, type DecomposedSubtask, type SubtaskDependency, type TaskDecomposition, type DecomposeArgs, type SpawnedAgent, type SwarmSpawnResult, type AgentProgress, type SwarmStatus, } from "./task";
35
41
  export { MandateContentTypeSchema, MandateStatusSchema, VoteTypeSchema, MandateEntrySchema, VoteSchema, MandateScoreSchema, CreateMandateArgsSchema, CastVoteArgsSchema, QueryMandatesArgsSchema, ScoreCalculationResultSchema, DEFAULT_MANDATE_DECAY_CONFIG, mandateSchemas, type MandateContentType, type MandateStatus, type VoteType, type MandateEntry, type Vote, type MandateScore, type MandateDecayConfig, type CreateMandateArgs, type CastVoteArgs, type QueryMandatesArgs, type ScoreCalculationResult, } from "./mandate";
36
42
  export { SwarmStrategySchema, SwarmDirectivesSchema, SwarmRecoverySchema, SwarmBeadContextSchema, CreateSwarmContextArgsSchema, UpdateSwarmContextArgsSchema, QuerySwarmContextsArgsSchema, type SwarmStrategy, type SwarmDirectives, type SwarmRecovery, type SwarmBeadContext, type CreateSwarmContextArgs, type UpdateSwarmContextArgs, type QuerySwarmContextsArgs, } from "./swarm-context";
43
+ export { WorkerHandoffContractSchema, WorkerHandoffContextSchema, WorkerHandoffEscalationSchema, WorkerHandoffSchema, type WorkerHandoff, type WorkerHandoffContract, type WorkerHandoffContext, type WorkerHandoffEscalation, } from "./worker-handoff";
37
44
  export { BaseCellEventSchema, CellCreatedEventSchema, CellUpdatedEventSchema, CellStatusChangedEventSchema, CellClosedEventSchema, CellReopenedEventSchema, CellDeletedEventSchema, CellDependencyAddedEventSchema, CellDependencyRemovedEventSchema, CellLabelAddedEventSchema, CellLabelRemovedEventSchema, CellCommentAddedEventSchema, CellCommentUpdatedEventSchema, CellCommentDeletedEventSchema, CellEpicChildAddedEventSchema, CellEpicChildRemovedEventSchema, CellEpicClosureEligibleEventSchema, CellAssignedEventSchema, CellWorkStartedEventSchema, CellCompactedEventSchema, CellEventSchema, createCellEvent, isCellEventType, getCellIdFromEvent, isStateTransitionEvent, isEpicEvent, isAgentEvent, type CellEvent, type CellCreatedEvent, type CellUpdatedEvent, type CellStatusChangedEvent, type CellClosedEvent, type CellReopenedEvent, type CellDeletedEvent, type CellDependencyAddedEvent, type CellDependencyRemovedEvent, type CellLabelAddedEvent, type CellLabelRemovedEvent, type CellCommentAddedEvent, type CellCommentUpdatedEvent, type CellCommentDeletedEvent, type CellEpicChildAddedEvent, type CellEpicChildRemovedEvent, type CellEpicClosureEligibleEvent, type CellAssignedEvent, type CellWorkStartedEvent, type CellCompactedEvent, } from "./cell-events";
38
45
  export { BaseBeadEventSchema, BeadCreatedEventSchema, BeadUpdatedEventSchema, BeadStatusChangedEventSchema, BeadClosedEventSchema, BeadReopenedEventSchema, BeadDeletedEventSchema, BeadDependencyAddedEventSchema, BeadDependencyRemovedEventSchema, BeadLabelAddedEventSchema, BeadLabelRemovedEventSchema, BeadCommentAddedEventSchema, BeadCommentUpdatedEventSchema, BeadCommentDeletedEventSchema, BeadEpicChildAddedEventSchema, BeadEpicChildRemovedEventSchema, BeadEpicClosureEligibleEventSchema, BeadAssignedEventSchema, BeadWorkStartedEventSchema, BeadCompactedEventSchema, BeadEventSchema, createBeadEvent, isBeadEventType, getBeadIdFromEvent, type BeadEvent, type BeadCreatedEvent, type BeadUpdatedEvent, type BeadStatusChangedEvent, type BeadClosedEvent, type BeadReopenedEvent, type BeadDeletedEvent, type BeadDependencyAddedEvent, type BeadDependencyRemovedEvent, type BeadLabelAddedEvent, type BeadLabelRemovedEvent, type BeadCommentAddedEvent, type BeadCommentUpdatedEvent, type BeadCommentDeletedEvent, type BeadEpicChildAddedEvent, type BeadEpicChildRemovedEvent, type BeadEpicClosureEligibleEvent, type BeadAssignedEvent, type BeadWorkStartedEvent, type BeadCompactedEvent, } from "./cell-events";
39
46
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/schemas/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAGH,OAAO,EACL,gBAAgB,EAChB,cAAc,EACd,oBAAoB,EACpB,UAAU,EACV,oBAAoB,EACpB,oBAAoB,EACpB,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EACjB,cAAc,EACd,oBAAoB,EACpB,sBAAsB,EACtB,KAAK,UAAU,EACf,KAAK,QAAQ,EACb,KAAK,cAAc,EACnB,KAAK,IAAI,EACT,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,KAAK,aAAa,EAClB,KAAK,aAAa,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EACjC,KAAK,iBAAiB,EACtB,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,GACxB,MAAM,eAAe,CAAC"}
@@ -0,0 +1,78 @@
1
+ /**
2
+ * WorkerHandoff schemas - structured contracts replacing prose instructions
3
+ *
4
+ * Replaces the 400-line SUBTASK_PROMPT_V2 with machine-readable contracts.
5
+ * Workers receive typed handoffs with explicit files, criteria, and escalation paths.
6
+ */
7
+ import { z } from "zod";
8
+ /**
9
+ * Contract section - the binding agreement between coordinator and worker
10
+ *
11
+ * Defines:
12
+ * - What task to complete (task_id)
13
+ * - What files to modify (files_owned) vs read (files_readonly)
14
+ * - What's already done (dependencies_completed)
15
+ * - How to know you're done (success_criteria)
16
+ */
17
+ export declare const WorkerHandoffContractSchema: z.ZodObject<{
18
+ task_id: z.ZodString;
19
+ files_owned: z.ZodDefault<z.ZodArray<z.ZodString>>;
20
+ files_readonly: z.ZodDefault<z.ZodArray<z.ZodString>>;
21
+ dependencies_completed: z.ZodDefault<z.ZodArray<z.ZodString>>;
22
+ success_criteria: z.ZodArray<z.ZodString>;
23
+ }, z.core.$strip>;
24
+ export type WorkerHandoffContract = z.infer<typeof WorkerHandoffContractSchema>;
25
+ /**
26
+ * Context section - the narrative explaining the "why"
27
+ *
28
+ * Provides:
29
+ * - Big picture (epic_summary)
30
+ * - This worker's specific role
31
+ * - What's already been done
32
+ * - What comes after
33
+ */
34
+ export declare const WorkerHandoffContextSchema: z.ZodObject<{
35
+ epic_summary: z.ZodString;
36
+ your_role: z.ZodString;
37
+ what_others_did: z.ZodString;
38
+ what_comes_next: z.ZodString;
39
+ }, z.core.$strip>;
40
+ export type WorkerHandoffContext = z.infer<typeof WorkerHandoffContextSchema>;
41
+ /**
42
+ * Escalation section - what to do when things go wrong
43
+ *
44
+ * Defines:
45
+ * - How to report blockers
46
+ * - Protocol for scope changes
47
+ */
48
+ export declare const WorkerHandoffEscalationSchema: z.ZodObject<{
49
+ blocked_contact: z.ZodString;
50
+ scope_change_protocol: z.ZodString;
51
+ }, z.core.$strip>;
52
+ export type WorkerHandoffEscalation = z.infer<typeof WorkerHandoffEscalationSchema>;
53
+ /**
54
+ * Complete WorkerHandoff - combines all three sections
55
+ *
56
+ * This is the full structured contract that replaces prose instructions.
57
+ */
58
+ export declare const WorkerHandoffSchema: z.ZodObject<{
59
+ contract: z.ZodObject<{
60
+ task_id: z.ZodString;
61
+ files_owned: z.ZodDefault<z.ZodArray<z.ZodString>>;
62
+ files_readonly: z.ZodDefault<z.ZodArray<z.ZodString>>;
63
+ dependencies_completed: z.ZodDefault<z.ZodArray<z.ZodString>>;
64
+ success_criteria: z.ZodArray<z.ZodString>;
65
+ }, z.core.$strip>;
66
+ context: z.ZodObject<{
67
+ epic_summary: z.ZodString;
68
+ your_role: z.ZodString;
69
+ what_others_did: z.ZodString;
70
+ what_comes_next: z.ZodString;
71
+ }, z.core.$strip>;
72
+ escalation: z.ZodObject<{
73
+ blocked_contact: z.ZodString;
74
+ scope_change_protocol: z.ZodString;
75
+ }, z.core.$strip>;
76
+ }, z.core.$strip>;
77
+ export type WorkerHandoff = z.infer<typeof WorkerHandoffSchema>;
78
+ //# sourceMappingURL=worker-handoff.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-handoff.d.ts","sourceRoot":"","sources":["../../src/schemas/worker-handoff.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;;;;GAQG;AACH,eAAO,MAAM,2BAA2B;;;;;;iBAwCtC,CAAC;AACH,MAAM,MAAM,qBAAqB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,2BAA2B,CAAC,CAAC;AAEhF;;;;;;;;GAQG;AACH,eAAO,MAAM,0BAA0B;;;;;iBAwBrC,CAAC;AACH,MAAM,MAAM,oBAAoB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,0BAA0B,CAAC,CAAC;AAE9E;;;;;;GAMG;AACH,eAAO,MAAM,6BAA6B;;;iBAYxC,CAAC;AACH,MAAM,MAAM,uBAAuB,GAAG,CAAC,CAAC,KAAK,CAC3C,OAAO,6BAA6B,CACrC,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;iBAI9B,CAAC;AACH,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC"}
@@ -19,6 +19,56 @@
19
19
  * - 3-strike detection for architectural problems
20
20
  */
21
21
  import { z } from "zod";
22
+ import { type WorkerHandoff } from "./schemas/worker-handoff";
23
+ /**
24
+ * Generate a WorkerHandoff object from subtask parameters
25
+ *
26
+ * Creates a machine-readable contract that replaces prose instructions in SUBTASK_PROMPT_V2.
27
+ * Workers receive typed handoffs with explicit files, criteria, and escalation paths.
28
+ *
29
+ * @param params - Subtask parameters
30
+ * @returns WorkerHandoff object validated against schema
31
+ */
32
+ export declare function generateWorkerHandoff(params: {
33
+ task_id: string;
34
+ files_owned: string[];
35
+ files_readonly?: string[];
36
+ dependencies_completed?: string[];
37
+ success_criteria?: string[];
38
+ epic_summary: string;
39
+ your_role: string;
40
+ what_others_did?: string;
41
+ what_comes_next?: string;
42
+ }): WorkerHandoff;
43
+ /**
44
+ * Validate that files_touched is a subset of files_owned (supports globs)
45
+ *
46
+ * Checks contract compliance - workers should only modify files they own.
47
+ * Glob patterns in files_owned are matched against files_touched paths.
48
+ *
49
+ * @param files_touched - Actual files modified by the worker
50
+ * @param files_owned - Files the worker is allowed to modify (may include globs)
51
+ * @returns Validation result with violations list
52
+ *
53
+ * @example
54
+ * ```typescript
55
+ * // Exact match - passes
56
+ * validateContract(["src/a.ts"], ["src/a.ts", "src/b.ts"])
57
+ * // => { valid: true, violations: [] }
58
+ *
59
+ * // Glob match - passes
60
+ * validateContract(["src/auth/service.ts"], ["src/auth/**"])
61
+ * // => { valid: true, violations: [] }
62
+ *
63
+ * // Violation - fails
64
+ * validateContract(["src/other.ts"], ["src/auth/**"])
65
+ * // => { valid: false, violations: ["src/other.ts"] }
66
+ * ```
67
+ */
68
+ export declare function validateContract(files_touched: string[], files_owned: string[]): {
69
+ valid: boolean;
70
+ violations: string[];
71
+ };
22
72
  /**
23
73
  * Initialize swarm and check tool availability
24
74
  *
@@ -1 +1 @@
1
- {"version":3,"file":"swarm-orchestrate.d.ts","sourceRoot":"","sources":["../src/swarm-orchestrate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAGH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AA8hBxB;;;;;;;;;;GAUG;AACH,eAAO,MAAM,UAAU;;;;;;;;;;;;;CA8JrB,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,YAAY;;;;;;;;;;CAoFvB,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;CAkHzB,CAAC;AAEH;;;;;;;;GAQG;AACH,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;CA6E1B,CAAC;AAEH;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqnBzB,CAAC;AAEH;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkJ/B,CAAC;AAEH;;;;;;;;GAQG;AACH,eAAO,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;CA6CjC,CAAC;AAEH;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB;;;;;;;;;;CAmClC,CAAC;AAEH;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB;;;;;;;;CAmB9B,CAAC;AAEH;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;CAoJ9B,CAAC;AA4BH;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM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AC;AAEH;;;;;;;;GAQG;AACH,eAAO,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgMtB,CAAC;AAMH,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAc5B,CAAC"}
@@ -37,7 +37,7 @@ export declare const SUBTASK_PROMPT = "You are a swarm agent working on a subtas
37
37
  *
38
38
  * Supports {error_context} placeholder for retry prompts.
39
39
  */
40
- export declare const SUBTASK_PROMPT_V2 = "You are a swarm agent working on: **{subtask_title}**\n\n## [IDENTITY]\nAgent: (assigned at spawn)\nCell: {bead_id}\nEpic: {epic_id}\n\n## [TASK]\n{subtask_description}\n\n## [FILES]\nReserved (exclusive):\n{file_list}\n\nOnly modify these files. Need others? Message the coordinator.\n\n## [CONTEXT]\n{shared_context}\n\n{compressed_context}\n\n{error_context}\n\n## [MANDATORY SURVIVAL CHECKLIST]\n\n**CRITICAL: Follow this checklist IN ORDER. Each step builds on the previous.**\n\n### Step 1: Initialize Coordination (REQUIRED - DO THIS FIRST)\n```\nswarmmail_init(project_path=\"{project_path}\", task_description=\"{bead_id}: {subtask_title}\")\n```\n\n**This registers you with the coordination system and enables:**\n- File reservation tracking\n- Inter-agent communication\n- Progress monitoring\n- Conflict detection\n\n**If you skip this step, your work will not be tracked and swarm_complete will fail.**\n\n### Step 2: Query Past Learnings (BEFORE starting work)\n```\nsemantic-memory_find(query=\"<keywords from your task>\", limit=5)\n```\n\n**Check if past agents solved similar problems.** Search for:\n- Error messages if debugging\n- Domain concepts (e.g., \"authentication\", \"caching\")\n- Technology stack (e.g., \"Next.js\", \"React\")\n- Patterns (e.g., \"event sourcing\", \"validation\")\n\n**Past learnings save time and prevent repeating mistakes.**\n\n### Step 3: Load Relevant Skills (if available)\n```\nskills_list() # See what skills exist\nskills_use(name=\"<relevant-skill>\", context=\"<your task>\") # Load skill\n```\n\n**Common skill triggers:**\n- Writing tests? \u2192 `skills_use(name=\"testing-patterns\")`\n- Breaking dependencies? \u2192 `skills_use(name=\"testing-patterns\")`\n- Multi-agent coordination? \u2192 `skills_use(name=\"swarm-coordination\")`\n- Building a CLI? \u2192 `skills_use(name=\"cli-builder\")`\n\n### Step 4: Reserve Your Files (YOU reserve, not coordinator)\n```\nswarmmail_reserve(\n paths=[{file_list}],\n reason=\"{bead_id}: {subtask_title}\",\n exclusive=true\n)\n```\n\n**Workers reserve their own files.** This prevents edit conflicts with other agents.\n\n### Step 5: Do the Work\n- Read your assigned files\n- Implement changes\n- Verify (typecheck if applicable)\n\n### Step 6: Report Progress at Milestones\n```\nswarm_progress(\n project_key=\"{project_path}\",\n agent_name=\"<your-agent-name>\",\n bead_id=\"{bead_id}\",\n status=\"in_progress\",\n progress_percent=25, # or 50, 75\n message=\"<what you just completed>\"\n)\n```\n\n**Report at 25%, 50%, 75% completion.** This:\n- Triggers auto-checkpoint (saves context)\n- Keeps coordinator informed\n- Prevents silent failures\n\n### Step 7: Manual Checkpoint BEFORE Risky Operations\n```\nswarm_checkpoint(\n project_key=\"{project_path}\",\n agent_name=\"<your-agent-name>\",\n bead_id=\"{bead_id}\"\n)\n```\n\n**Call BEFORE:**\n- Large refactors\n- File deletions\n- Breaking API changes\n- Anything that might fail catastrophically\n\n**Checkpoints preserve context so you can recover if things go wrong.**\n\n### Step 8: Store Learnings (if you discovered something)\n```\nsemantic-memory_store(\n information=\"<what you learned, WHY it matters, how to apply it>\",\n metadata=\"<tags: domain, tech-stack, pattern-type>\"\n)\n```\n\n**Store:**\n- Tricky bugs you solved (root cause + solution)\n- Project-specific patterns or domain rules\n- Tool/library gotchas and workarounds\n- Failed approaches (anti-patterns to avoid)\n\n**Don't store generic knowledge.** Store the WHY, not just the WHAT.\n\n### Step 9: Complete (REQUIRED - releases reservations)\n```\nswarm_complete(\n project_key=\"{project_path}\",\n agent_name=\"<your-agent-name>\",\n bead_id=\"{bead_id}\",\n summary=\"<what you accomplished>\",\n files_touched=[\"list\", \"of\", \"files\"]\n)\n```\n\n**This automatically:**\n- Runs UBS bug scan\n- Releases file reservations\n- Records learning signals\n- Notifies coordinator\n\n**DO NOT manually close the cell with hive_close.** Use swarm_complete.\n\n## [SWARM MAIL COMMUNICATION]\n\n### Check Inbox Regularly\n```\nswarmmail_inbox() # Check for coordinator messages\nswarmmail_read_message(message_id=N) # Read specific message\n```\n\n### When Blocked\n```\nswarmmail_send(\n to=[\"coordinator\"],\n subject=\"BLOCKED: {bead_id}\",\n body=\"<blocker description, what you need>\",\n importance=\"high\",\n thread_id=\"{epic_id}\"\n)\nhive_update(id=\"{bead_id}\", status=\"blocked\")\n```\n\n### Report Issues to Other Agents\n```\nswarmmail_send(\n to=[\"OtherAgent\", \"coordinator\"],\n subject=\"Issue in {bead_id}\",\n body=\"<describe problem, don't fix their code>\",\n thread_id=\"{epic_id}\"\n)\n```\n\n### Manual Release (if needed)\n```\nswarmmail_release() # Manually release reservations\n```\n\n**Note:** `swarm_complete` automatically releases reservations. Only use manual release if aborting work.\n\n## [OTHER TOOLS]\n### Hive - You Have Autonomy to File Issues\nYou can create new cells against this epic when you discover:\n- **Bugs**: Found a bug while working? File it.\n- **Tech debt**: Spotted something that needs cleanup? File it.\n- **Follow-up work**: Task needs more work than scoped? File a follow-up.\n- **Dependencies**: Need something from another agent? File and link it.\n\n```\nhive_create(\n title=\"<descriptive title>\",\n type=\"bug\", # or \"task\", \"chore\"\n priority=2,\n parent_id=\"{epic_id}\", # Links to this epic\n description=\"Found while working on {bead_id}: <details>\"\n)\n```\n\n**Don't silently ignore issues.** File them so they get tracked and addressed.\n\nOther cell operations:\n- hive_update(id, status) - Mark blocked if stuck\n- hive_query(status=\"open\") - See what else needs work\n\n### Skills\n- skills_list() - Discover available skills\n- skills_use(name) - Activate skill for specialized guidance\n- skills_create(name) - Create new skill (if you found a reusable pattern)\n\n## [CRITICAL REQUIREMENTS]\n\n**NON-NEGOTIABLE:**\n1. Step 1 (swarmmail_init) MUST be first - do it before anything else\n2. Step 2 (semantic-memory_find) MUST happen before starting work\n3. Step 4 (swarmmail_reserve) - YOU reserve files, not coordinator\n4. Step 6 (swarm_progress) - Report at milestones, don't work silently\n5. Step 9 (swarm_complete) - Use this to close, NOT hive_close\n\n**If you skip these steps:**\n- Your work won't be tracked (swarm_complete will fail)\n- You'll waste time repeating solved problems (no semantic memory query)\n- Edit conflicts with other agents (no file reservation)\n- Lost work if you crash (no checkpoints)\n- Future agents repeat your mistakes (no learnings stored)\n\nBegin now.";
40
+ export declare const SUBTASK_PROMPT_V2 = "You are a swarm agent working on: **{subtask_title}**\n\n## [IDENTITY]\nAgent: (assigned at spawn)\nCell: {bead_id}\nEpic: {epic_id}\n\n## [TASK]\n{subtask_description}\n\n## [FILES]\nReserved (exclusive):\n{file_list}\n\nOnly modify these files. Need others? Message the coordinator.\n\n## [CONTEXT]\n{shared_context}\n\n{compressed_context}\n\n{error_context}\n\n## [MANDATORY SURVIVAL CHECKLIST]\n\n**CRITICAL: Follow this checklist IN ORDER. Each step builds on the previous.**\n\n### Step 1: Initialize Coordination (REQUIRED - DO THIS FIRST)\n```\nswarmmail_init(project_path=\"{project_path}\", task_description=\"{bead_id}: {subtask_title}\")\n```\n\n**This registers you with the coordination system and enables:**\n- File reservation tracking\n- Inter-agent communication\n- Progress monitoring\n- Conflict detection\n\n**If you skip this step, your work will not be tracked and swarm_complete will fail.**\n\n### Step 2: Query Past Learnings (BEFORE starting work)\n```\nsemantic-memory_find(query=\"<keywords from your task>\", limit=5)\n```\n\n**Check if past agents solved similar problems.** Search for:\n- Error messages if debugging\n- Domain concepts (e.g., \"authentication\", \"caching\")\n- Technology stack (e.g., \"Next.js\", \"React\")\n- Patterns (e.g., \"event sourcing\", \"validation\")\n\n**Past learnings save time and prevent repeating mistakes.**\n\n### Step 3: Load Relevant Skills (if available)\n```\nskills_list() # See what skills exist\nskills_use(name=\"<relevant-skill>\", context=\"<your task>\") # Load skill\n```\n\n**Common skill triggers:**\n- Writing tests? \u2192 `skills_use(name=\"testing-patterns\")`\n- Breaking dependencies? \u2192 `skills_use(name=\"testing-patterns\")`\n- Multi-agent coordination? \u2192 `skills_use(name=\"swarm-coordination\")`\n- Building a CLI? \u2192 `skills_use(name=\"cli-builder\")`\n\n### Step 4: Reserve Your Files (YOU reserve, not coordinator)\n```\nswarmmail_reserve(\n paths=[{file_list}],\n reason=\"{bead_id}: {subtask_title}\",\n exclusive=true\n)\n```\n\n**Workers reserve their own files.** This prevents edit conflicts with other agents.\n\n### Step 5: Do the Work (TDD MANDATORY)\n\n**Follow RED \u2192 GREEN \u2192 REFACTOR. No exceptions.**\n\n1. **RED**: Write a failing test that describes the expected behavior\n - Test MUST fail before you write implementation\n - If test passes immediately, your test is wrong\n \n2. **GREEN**: Write minimal code to make the test pass\n - Don't over-engineer - just make it green\n - Hardcode if needed, refactor later\n \n3. **REFACTOR**: Clean up while tests stay green\n - Run tests after every change\n - If tests break, undo and try again\n\n```bash\n# Run tests continuously\nbun test <your-test-file> --watch\n```\n\n**Why TDD?**\n- Catches bugs before they exist\n- Documents expected behavior\n- Enables fearless refactoring\n- Proves your code works\n\n### Step 6: Report Progress at Milestones\n```\nswarm_progress(\n project_key=\"{project_path}\",\n agent_name=\"<your-agent-name>\",\n bead_id=\"{bead_id}\",\n status=\"in_progress\",\n progress_percent=25, # or 50, 75\n message=\"<what you just completed>\"\n)\n```\n\n**Report at 25%, 50%, 75% completion.** This:\n- Triggers auto-checkpoint (saves context)\n- Keeps coordinator informed\n- Prevents silent failures\n\n### Step 7: Manual Checkpoint BEFORE Risky Operations\n```\nswarm_checkpoint(\n project_key=\"{project_path}\",\n agent_name=\"<your-agent-name>\",\n bead_id=\"{bead_id}\"\n)\n```\n\n**Call BEFORE:**\n- Large refactors\n- File deletions\n- Breaking API changes\n- Anything that might fail catastrophically\n\n**Checkpoints preserve context so you can recover if things go wrong.**\n\n### Step 8: Store Learnings (if you discovered something)\n```\nsemantic-memory_store(\n information=\"<what you learned, WHY it matters, how to apply it>\",\n metadata=\"<tags: domain, tech-stack, pattern-type>\"\n)\n```\n\n**Store:**\n- Tricky bugs you solved (root cause + solution)\n- Project-specific patterns or domain rules\n- Tool/library gotchas and workarounds\n- Failed approaches (anti-patterns to avoid)\n\n**Don't store generic knowledge.** Store the WHY, not just the WHAT.\n\n### Step 9: Complete (REQUIRED - releases reservations)\n```\nswarm_complete(\n project_key=\"{project_path}\",\n agent_name=\"<your-agent-name>\",\n bead_id=\"{bead_id}\",\n summary=\"<what you accomplished>\",\n files_touched=[\"list\", \"of\", \"files\"]\n)\n```\n\n**This automatically:**\n- Runs UBS bug scan\n- Releases file reservations\n- Records learning signals\n- Notifies coordinator\n\n**DO NOT manually close the cell with hive_close.** Use swarm_complete.\n\n## [SWARM MAIL COMMUNICATION]\n\n### Check Inbox Regularly\n```\nswarmmail_inbox() # Check for coordinator messages\nswarmmail_read_message(message_id=N) # Read specific message\n```\n\n### When Blocked\n```\nswarmmail_send(\n to=[\"coordinator\"],\n subject=\"BLOCKED: {bead_id}\",\n body=\"<blocker description, what you need>\",\n importance=\"high\",\n thread_id=\"{epic_id}\"\n)\nhive_update(id=\"{bead_id}\", status=\"blocked\")\n```\n\n### Report Issues to Other Agents\n```\nswarmmail_send(\n to=[\"OtherAgent\", \"coordinator\"],\n subject=\"Issue in {bead_id}\",\n body=\"<describe problem, don't fix their code>\",\n thread_id=\"{epic_id}\"\n)\n```\n\n### Manual Release (if needed)\n```\nswarmmail_release() # Manually release reservations\n```\n\n**Note:** `swarm_complete` automatically releases reservations. Only use manual release if aborting work.\n\n## [OTHER TOOLS]\n### Hive - You Have Autonomy to File Issues\nYou can create new cells against this epic when you discover:\n- **Bugs**: Found a bug while working? File it.\n- **Tech debt**: Spotted something that needs cleanup? File it.\n- **Follow-up work**: Task needs more work than scoped? File a follow-up.\n- **Dependencies**: Need something from another agent? File and link it.\n\n```\nhive_create(\n title=\"<descriptive title>\",\n type=\"bug\", # or \"task\", \"chore\"\n priority=2,\n parent_id=\"{epic_id}\", # Links to this epic\n description=\"Found while working on {bead_id}: <details>\"\n)\n```\n\n**Don't silently ignore issues.** File them so they get tracked and addressed.\n\nOther cell operations:\n- hive_update(id, status) - Mark blocked if stuck\n- hive_query(status=\"open\") - See what else needs work\n\n### Skills\n- skills_list() - Discover available skills\n- skills_use(name) - Activate skill for specialized guidance\n- skills_create(name) - Create new skill (if you found a reusable pattern)\n\n## [CRITICAL REQUIREMENTS]\n\n**NON-NEGOTIABLE:**\n1. Step 1 (swarmmail_init) MUST be first - do it before anything else\n2. Step 2 (semantic-memory_find) MUST happen before starting work\n3. Step 4 (swarmmail_reserve) - YOU reserve files, not coordinator\n4. Step 6 (swarm_progress) - Report at milestones, don't work silently\n5. Step 9 (swarm_complete) - Use this to close, NOT hive_close\n\n**If you skip these steps:**\n- Your work won't be tracked (swarm_complete will fail)\n- You'll waste time repeating solved problems (no semantic memory query)\n- Edit conflicts with other agents (no file reservation)\n- Lost work if you crash (no checkpoints)\n- Future agents repeat your mistakes (no learnings stored)\n\nBegin now.";
41
41
  /**
42
42
  * Prompt for self-evaluation before completing a subtask.
43
43
  *
@@ -1 +1 @@
1
- {"version":3,"file":"swarm-prompts.d.ts","sourceRoot":"","sources":["../src/swarm-prompts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAQH;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB,m6EAkET,CAAC;AAEzB;;GAEG;AACH,eAAO,MAAM,6BAA6B,gxDAyDlB,CAAC;AAEzB;;;;;GAKG;AACH,eAAO,MAAM,cAAc,mk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EAAE,MAAM,EAAE,CAAC;QAC1B,iBAAiB,CAAC,EAAE,MAAM,CAAC;KAC5B,CAAC;CACH,GAAG,MAAM,CA2ET;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE;IAC1C,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,aAAa,EAAE,MAAM,CAAC;IACtB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,GAAG,MAAM,CAUT;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE;IAC7C,OAAO,EAAE,MAAM,CAAC;IAChB,aAAa,EAAE,MAAM,CAAC;IACtB,aAAa,EAAE,MAAM,EAAE,CAAC;CACzB,GAAG,MAAM,CAMT;AAMD;;GAEG;AACH,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;CAoC/B,CAAC;AAEH;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0D9B,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,uBAAuB;;;;;;;;;;;;CAoClC,CAAC;AAEH;;;;;GAKG;AACH,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;CA0I5B,CAAC;AAEH,eAAO,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAKvB,CAAC"}
@@ -167,6 +167,10 @@ export declare function getReviewStatus(taskId: string): TaskReviewStatus;
167
167
  * Clear review status (for testing or reset)
168
168
  */
169
169
  export declare function clearReviewStatus(taskId: string): void;
170
+ /**
171
+ * Mark a task as reviewed but not approved (for testing)
172
+ */
173
+ export declare function markReviewRejected(taskId: string): void;
170
174
  export declare const reviewTools: {
171
175
  swarm_review: {
172
176
  description: string;
@@ -1 +1 @@
1
- {"version":3,"file":"swarm-review.d.ts","sourceRoot":"","sources":["../src/swarm-review.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAQxB;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,eAAO,MAAM,iBAAiB;;;;;iBAK5B,CAAC;AAEH;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,UAAU,GAAG,eAAe,CAAC;IACrC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,WAAW,EAAE,CAAC;IACvB,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;iBAkB5B,CAAC;AAEJ;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,aAAa,EAAE,MAAM,EAAE,CAAC;IACxB,IAAI,EAAE,MA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AO,CAAC;IAClB,QAAQ,EAAE,OAAO,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,kBAAkB,EAAE,MAAM,CAAC;CAC5B;AAOD;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAGvD;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAGxD;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,gBAAgB,CAQhE;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAGtD;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAEvD;AAMD,eAAO,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAGvB,CAAC"}
@@ -0,0 +1,293 @@
1
+ # ADR-008: Worker Handoff Protocol - Structured Contracts Over Prose
2
+
3
+ ## Status
4
+
5
+ Proposed
6
+
7
+ ## Context
8
+
9
+ The current `SUBTASK_PROMPT_V2` is a **280-line prose instruction manual** that gets injected into every swarm worker's context. This approach has fundamental problems:
10
+
11
+ ### Current Problems
12
+
13
+ 1. **Workers ignore prose** - Long text instructions get skimmed or missed entirely
14
+ 2. **No validation** - Can't programmatically verify workers followed protocol
15
+ 3. **Context bloat** - 280 lines * N workers burns tokens fast
16
+ 4. **Drift and violations** - Workers modify files outside their scope, no automatic detection
17
+ 5. **Manual error recovery** - Coordinator can't auto-detect contract violations
18
+
19
+ **Concrete example of failure:**
20
+ ```
21
+ Worker assigned: ["src/auth/service.ts"]
22
+ Worker actually touched: ["src/auth/service.ts", "src/lib/jwt.ts", "src/types/user.ts"]
23
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
24
+ Scope creep undetected until swarm_complete
25
+ ```
26
+
27
+ Current `swarm_complete` validates `files_touched ⊆ files_owned`, but the **contract** was never machine-readable to begin with.
28
+
29
+ ### Research & Inspirations
30
+
31
+ From "Patterns for Building AI Agents" and production event-driven systems:
32
+
33
+ **mdflow adapter pattern:**
34
+ - Convention-based behavior inference
35
+ - Template variables define expectations
36
+ - Minimal configuration, maximum clarity
37
+
38
+ **Bellemare's event-driven orchestration:**
39
+ - Explicit contracts between services
40
+ - Commands vs Events distinction
41
+ - Contract violations fail fast with clear errors
42
+
43
+ **Key insight:** Agents need **two channels**:
44
+ 1. **Contract** (machine-readable, validated) - WHAT to do, WHERE to do it
45
+ 2. **Context** (human-readable, advisory) - WHY it matters, HOW it fits together
46
+
47
+ ## Decision
48
+
49
+ Replace 280-line prose with **WorkerHandoff envelope** that separates contract from context.
50
+
51
+ ### WorkerHandoff Structure
52
+
53
+ ```typescript
54
+ interface WorkerHandoff {
55
+ // Machine-readable - enforced by tools
56
+ contract: {
57
+ task_id: string; // Cell ID for tracking
58
+ files_owned: string[]; // Exclusive write access (validated)
59
+ files_readonly: string[]; // Can read, MUST NOT modify (validated)
60
+ dependencies_completed: string[]; // Tasks that finished before this
61
+ success_criteria: string[]; // Exit conditions (checkable)
62
+ };
63
+
64
+ // Human-readable - advisory context
65
+ context: {
66
+ epic_summary: string; // Big picture goal
67
+ your_role: string; // What this subtask accomplishes
68
+ what_others_did: string; // Dependency outputs
69
+ what_comes_next: string; // Downstream task expectations
70
+ };
71
+
72
+ // Escalation paths - when things go wrong
73
+ escalation: {
74
+ blocked_contact: string; // "coordinator" or agent name
75
+ scope_change_protocol: string; // "swarmmail_send + await approval"
76
+ };
77
+ }
78
+ ```
79
+
80
+ ### Example Handoff
81
+
82
+ ```json
83
+ {
84
+ "contract": {
85
+ "task_id": "bd-123.2",
86
+ "files_owned": ["src/auth/service.ts", "src/auth/service.test.ts"],
87
+ "files_readonly": ["src/types/user.ts", "src/lib/jwt.ts"],
88
+ "dependencies_completed": ["bd-123.1"],
89
+ "success_criteria": [
90
+ "AuthService.login() returns JWT token",
91
+ "Tests pass: bun test src/auth/service.test.ts",
92
+ "Type check passes: tsc --noEmit"
93
+ ]
94
+ },
95
+ "context": {
96
+ "epic_summary": "Add OAuth authentication to user service",
97
+ "your_role": "Implement AuthService with JWT token generation",
98
+ "what_others_did": "bd-123.1 created User schema with email/password fields",
99
+ "what_comes_next": "bd-123.3 will integrate this service into API routes"
100
+ },
101
+ "escalation": {
102
+ "blocked_contact": "coordinator",
103
+ "scope_change_protocol": "swarmmail_send(subject='Scope Change', ack_required=true)"
104
+ }
105
+ }
106
+ ```
107
+
108
+ ### Validation in swarm_complete
109
+
110
+ ```typescript
111
+ // swarm_complete now validates against contract
112
+ function validateCompletion(handoff: WorkerHandoff, result: CompletionReport) {
113
+ const violations: string[] = [];
114
+
115
+ // 1. File scope violations
116
+ const unauthorized = result.files_touched.filter(
117
+ f => !handoff.contract.files_owned.includes(f)
118
+ );
119
+ if (unauthorized.length > 0) {
120
+ violations.push(`Touched unauthorized files: ${unauthorized.join(", ")}`);
121
+ }
122
+
123
+ // 2. Success criteria (checkable ones)
124
+ for (const criterion of handoff.contract.success_criteria) {
125
+ if (criterion.startsWith("Tests pass:")) {
126
+ // Run the test command, validate exit 0
127
+ }
128
+ if (criterion.startsWith("Type check passes:")) {
129
+ // Run tsc --noEmit, validate exit 0
130
+ }
131
+ }
132
+
133
+ // 3. Learning signals from violations
134
+ if (violations.length > 0) {
135
+ recordLearningSignal({
136
+ task_id: handoff.contract.task_id,
137
+ violation_type: "scope_creep",
138
+ details: violations,
139
+ impact: "negative" // Penalize decomposition strategy
140
+ });
141
+ }
142
+
143
+ return { valid: violations.length === 0, violations };
144
+ }
145
+ ```
146
+
147
+ ### Integration with Existing Tools
148
+
149
+ **swarm_spawn_subtask generates handoffs:**
150
+
151
+ ```typescript
152
+ export const swarm_spawn_subtask = tool(/* ... */)
153
+ .handler(async ({ input, context }) => {
154
+ const handoff: WorkerHandoff = {
155
+ contract: {
156
+ task_id: input.bead_id,
157
+ files_owned: input.files,
158
+ files_readonly: inferReadonlyFiles(input.files, epicContext),
159
+ dependencies_completed: input.dependencies_completed || [],
160
+ success_criteria: generateSuccessCriteria(input.subtask_description)
161
+ },
162
+ context: {
163
+ epic_summary: epicContext.summary,
164
+ your_role: input.subtask_title,
165
+ what_others_did: summarizeDependencies(input.dependencies_completed),
166
+ what_comes_next: summarizeDownstream(input.bead_id)
167
+ },
168
+ escalation: {
169
+ blocked_contact: "coordinator",
170
+ scope_change_protocol: "swarmmail_send(subject='Scope Change', ack_required=true)"
171
+ }
172
+ };
173
+
174
+ return formatHandoff(handoff); // Compact JSON + minimal prose wrapper
175
+ });
176
+ ```
177
+
178
+ **swarm_complete validates contract:**
179
+
180
+ ```typescript
181
+ export const swarm_complete = tool(/* ... */)
182
+ .handler(async ({ input, context }) => {
183
+ const handoff = getStoredHandoff(input.bead_id);
184
+ const validation = validateCompletion(handoff, {
185
+ files_touched: input.files_touched,
186
+ summary: input.summary
187
+ });
188
+
189
+ if (!validation.valid) {
190
+ throw new Error(
191
+ `Contract violations detected:\n${validation.violations.join("\n")}`
192
+ );
193
+ }
194
+
195
+ // Proceed with UBS scan, reservation release, etc.
196
+ });
197
+ ```
198
+
199
+ ## Consequences
200
+
201
+ ### Positive
202
+
203
+ - **Validation enforced** - Can't complete with contract violations
204
+ - **Clear boundaries** - Workers know exactly what's in/out of scope
205
+ - **Better learning** - Scope creep violations feed back into strategy selection
206
+ - **Context efficiency** - Contract is ~30 lines JSON vs 280 lines prose
207
+ - **Fail fast** - Violations detected immediately, not during merge
208
+ - **Programmatic recovery** - Coordinator can auto-detect and reassign work
209
+
210
+ ### Negative
211
+
212
+ - **Requires storage** - Handoffs must persist (already have event store)
213
+ - **Success criteria limited** - Can't validate all criteria automatically
214
+ - **Migration cost** - Existing `SUBTASK_PROMPT_V2` users need update
215
+ - **More upfront work** - Coordinator must generate better contracts
216
+
217
+ ### Neutral
218
+
219
+ - **Prose still exists** - `context` field provides human explanation, just smaller
220
+ - **Not eliminating checklist** - 9-step survival checklist stays, but moves to tool enforcement
221
+
222
+ ## Implementation Notes
223
+
224
+ ### Phase 1: Storage & Schema
225
+
226
+ 1. Add `WorkerHandoff` schema to swarm-mail event types
227
+ 2. Store handoffs in event log when spawning subtasks
228
+ 3. Retrieve handoffs in `swarm_complete` for validation
229
+
230
+ ### Phase 2: Generation Logic
231
+
232
+ 1. Implement `inferReadonlyFiles()` - analyze imports/dependencies
233
+ 2. Implement `generateSuccessCriteria()` - parse task description for checkable conditions
234
+ 3. Implement `summarizeDependencies()` and `summarizeDownstream()` - build context from epic graph
235
+
236
+ ### Phase 3: Validation
237
+
238
+ 1. Add contract validation to `swarm_complete`
239
+ 2. Implement checkable criteria runners (test commands, type checks)
240
+ 3. Record learning signals for violations
241
+
242
+ ### Phase 4: Migration
243
+
244
+ 1. Update `formatSubtaskPromptV2` to generate handoff JSON
245
+ 2. Deprecate 280-line prose template
246
+ 3. Update tests for new handoff format
247
+
248
+ ### Phase 5: Enhanced Features (Future)
249
+
250
+ 1. **Readonly enforcement** - Detect modifications to `files_readonly` via git diff
251
+ 2. **Dependency validation** - Verify `dependencies_completed` actually ran first
252
+ 3. **Auto-generated success criteria** - Parse test files, infer criteria from code
253
+
254
+ ## Alternatives Considered
255
+
256
+ ### Keep Prose, Add Validation
257
+
258
+ Keep `SUBTASK_PROMPT_V2` but add validation after-the-fact. **Rejected** because:
259
+ - Still burns 280 lines of context per worker
260
+ - Workers still ignore prose
261
+ - Validation happens too late (after work done)
262
+
263
+ ### Minimal Contract Only
264
+
265
+ Remove context entirely, pure machine contract. **Rejected** because:
266
+ - Workers need WHY to make good judgment calls
267
+ - Context helps with edge cases not in contract
268
+ - Loss of human readability hurts debugging
269
+
270
+ ### Command Pattern (Bellemare Style)
271
+
272
+ Full event-sourcing with Command objects. **Rejected** because:
273
+ - Over-engineered for current needs
274
+ - Already have event store for coordination
275
+ - Contract + context is simpler and sufficient
276
+
277
+ ## References
278
+
279
+ - **"Patterns for Building AI Agents"** - Subagent context sharing patterns
280
+ - **mdflow** - Convention-based adapter design, template variable contracts
281
+ - **Bellemare's "Building Event-Driven Microservices"** - Explicit contracts, fail-fast validation
282
+ - **Current implementation:** `src/swarm-prompts.ts` (SUBTASK_PROMPT_V2, lines 253-530)
283
+ - **Related:** ADR-007 (Structured Review), ADR-002 (Package Extraction)
284
+
285
+ ## Success Criteria
286
+
287
+ - [ ] `WorkerHandoff` schema defined and validated with Zod
288
+ - [ ] `swarm_spawn_subtask` generates handoffs instead of raw prose
289
+ - [ ] `swarm_complete` validates contract before accepting completion
290
+ - [ ] Scope violations trigger learning signals (negative feedback)
291
+ - [ ] Workers receive handoff as JSON + compact context wrapper (<50 lines)
292
+ - [ ] Test suite validates contract enforcement catches violations
293
+ - [ ] Migration path documented for existing swarm users