oxe-cc 1.16.0 → 1.21.1

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 (284) hide show
  1. package/.github/copilot-instructions.md +177 -177
  2. package/.github/dependabot.yml +31 -31
  3. package/.github/workflows/ci.yml +159 -138
  4. package/.github/workflows/release.yml +107 -106
  5. package/AGENTS.md +97 -97
  6. package/CHANGELOG.md +1032 -856
  7. package/README.md +673 -600
  8. package/assets/readme-banner.svg +19 -19
  9. package/bin/banner.txt +13 -13
  10. package/bin/lib/oxe-agent-install.cjs +650 -650
  11. package/bin/lib/oxe-artifact-catalog.cjs +376 -376
  12. package/bin/lib/oxe-azure.cjs +1445 -1445
  13. package/bin/lib/oxe-budget.cjs +117 -0
  14. package/bin/lib/oxe-change.cjs +230 -0
  15. package/bin/lib/oxe-command-registry.cjs +31 -31
  16. package/bin/lib/oxe-commit-convention.cjs +85 -0
  17. package/bin/lib/oxe-context-engine.cjs +874 -874
  18. package/bin/lib/oxe-core-command-handlers.cjs +82 -82
  19. package/bin/lib/oxe-criterion-coverage.cjs +58 -0
  20. package/bin/lib/oxe-dashboard.cjs +737 -737
  21. package/bin/lib/oxe-dossier.cjs +281 -0
  22. package/bin/lib/oxe-install-resolve.cjs +134 -106
  23. package/bin/lib/oxe-manifest.cjs +124 -124
  24. package/bin/lib/oxe-npm-version.cjs +66 -66
  25. package/bin/lib/oxe-operational.cjs +4484 -2676
  26. package/bin/lib/oxe-phase-gates.cjs +280 -0
  27. package/bin/lib/oxe-plan-json.cjs +433 -0
  28. package/bin/lib/oxe-plugin-cli.cjs +95 -95
  29. package/bin/lib/oxe-plugins.cjs +432 -432
  30. package/bin/lib/oxe-process.cjs +56 -56
  31. package/bin/lib/oxe-program.cjs +205 -0
  32. package/bin/lib/oxe-project-env.cjs +178 -0
  33. package/bin/lib/oxe-project-health.cjs +2962 -2846
  34. package/bin/lib/oxe-rationality.cjs +73 -49
  35. package/bin/lib/oxe-release.cjs +42 -0
  36. package/bin/lib/oxe-repo-rules.cjs +108 -0
  37. package/bin/lib/oxe-runtime-semantics.cjs +514 -514
  38. package/bin/lib/oxe-scorecard.cjs +164 -0
  39. package/bin/lib/oxe-security.cjs +289 -289
  40. package/bin/lib/oxe-spike.cjs +98 -0
  41. package/bin/lib/oxe-verify-dryrun.cjs +152 -0
  42. package/bin/lib/oxe-workflows.cjs +145 -145
  43. package/bin/oxe-cc.js +6281 -5829
  44. package/docs/INTEGRATION.md +182 -182
  45. package/docs/QUALITY-GATES.md +46 -46
  46. package/docs/RELEASE-READINESS.md +87 -86
  47. package/docs/RUNTIME-SMOKE-MATRIX.md +137 -137
  48. package/docs/oxespace-1.5/BACKLOG.md +273 -0
  49. package/docs/oxevoice/BACKLOG.md +244 -0
  50. package/lib/runtime/compiler/graph-compiler.d.ts +13 -0
  51. package/lib/runtime/compiler/graph-compiler.js +40 -3
  52. package/lib/runtime/delivery/promotion-pipeline.js +6 -2
  53. package/lib/runtime/events/catalog.d.ts +1 -1
  54. package/lib/runtime/events/catalog.js +11 -0
  55. package/lib/runtime/executor/adapters/claude-cli.d.ts +63 -0
  56. package/lib/runtime/executor/adapters/claude-cli.js +250 -0
  57. package/lib/runtime/executor/adapters/http-openai.d.ts +9 -0
  58. package/lib/runtime/executor/adapters/http-openai.js +18 -0
  59. package/lib/runtime/executor/adapters/registry.d.ts +13 -0
  60. package/lib/runtime/executor/adapters/registry.js +29 -0
  61. package/lib/runtime/executor/adapters/types.d.ts +21 -0
  62. package/lib/runtime/executor/adapters/types.js +2 -0
  63. package/lib/runtime/executor/built-in-tools.d.ts +8 -0
  64. package/lib/runtime/executor/built-in-tools.js +40 -9
  65. package/lib/runtime/executor/index.d.ts +12 -2
  66. package/lib/runtime/executor/index.js +28 -1
  67. package/lib/runtime/executor/llm-task-executor.d.ts +35 -2
  68. package/lib/runtime/executor/llm-task-executor.js +97 -21
  69. package/lib/runtime/executor/node-context.d.ts +83 -0
  70. package/lib/runtime/executor/node-context.js +116 -0
  71. package/lib/runtime/executor/node-prompt-builder.d.ts +2 -0
  72. package/lib/runtime/executor/node-prompt-builder.js +2 -0
  73. package/lib/runtime/executor/shell-argv.d.ts +30 -0
  74. package/lib/runtime/executor/shell-argv.js +57 -0
  75. package/lib/runtime/executor/stream-completion.d.ts +11 -0
  76. package/lib/runtime/executor/stream-completion.js +10 -1
  77. package/lib/runtime/index.d.ts +5 -2
  78. package/lib/runtime/index.js +8 -1
  79. package/lib/runtime/program/index.d.ts +1 -0
  80. package/lib/runtime/program/index.js +17 -0
  81. package/lib/runtime/program/program-model.d.ts +74 -0
  82. package/lib/runtime/program/program-model.js +195 -0
  83. package/lib/runtime/projection/projection-engine.d.ts +10 -1
  84. package/lib/runtime/projection/projection-engine.js +25 -1
  85. package/lib/runtime/reducers/run-state-reducer.js +5 -0
  86. package/lib/runtime/scheduler/run-journal.d.ts +19 -1
  87. package/lib/runtime/scheduler/run-journal.js +40 -1
  88. package/lib/runtime/scheduler/scheduler.d.ts +30 -0
  89. package/lib/runtime/scheduler/scheduler.js +195 -19
  90. package/lib/runtime/verification/contract-exports.d.ts +24 -0
  91. package/lib/runtime/verification/contract-exports.js +201 -0
  92. package/lib/runtime/verification/index.d.ts +1 -0
  93. package/lib/runtime/verification/index.js +1 -0
  94. package/lib/runtime/verification/test-report-parsers.d.ts +37 -0
  95. package/lib/runtime/verification/test-report-parsers.js +180 -0
  96. package/lib/runtime/verification/verification-compiler.d.ts +67 -1
  97. package/lib/runtime/verification/verification-compiler.js +302 -25
  98. package/lib/runtime/verification/verification-manifest.d.ts +10 -0
  99. package/lib/runtime/verification/verification-manifest.js +18 -3
  100. package/lib/runtime/workspace/strategies/git-worktree.d.ts +9 -0
  101. package/lib/runtime/workspace/strategies/git-worktree.js +81 -0
  102. package/lib/sdk/README.md +61 -61
  103. package/lib/sdk/index.cjs +815 -810
  104. package/lib/sdk/index.d.ts +982 -982
  105. package/lib/sdk/index.types.ts +933 -933
  106. package/oxe/schemas/plan-agents.schema.json +122 -122
  107. package/oxe/schemas/plan.schema.json +85 -0
  108. package/oxe/templates/ACTIVE-RUN.template.json +32 -32
  109. package/oxe/templates/CAPABILITIES.template.md +7 -7
  110. package/oxe/templates/CAPABILITY.template.md +45 -45
  111. package/oxe/templates/CHECKPOINT.template.md +37 -37
  112. package/oxe/templates/CHECKPOINTS.template.md +7 -7
  113. package/oxe/templates/CODEBASE-DELTA.template.md +33 -33
  114. package/oxe/templates/CONFIG.md +105 -105
  115. package/oxe/templates/DISCUSS.template.md +44 -44
  116. package/oxe/templates/DOCS_BROWNFIELD_LAYOUT.md +55 -55
  117. package/oxe/templates/EXECUTION-RUNTIME.template.md +68 -68
  118. package/oxe/templates/FIXTURE-PACK.template.json +23 -23
  119. package/oxe/templates/FIXTURE-PACK.template.md +11 -11
  120. package/oxe/templates/GIT_HOOKS_OXE.md +52 -52
  121. package/oxe/templates/HYPOTHESES.template.md +33 -33
  122. package/oxe/templates/IMPLEMENTATION-PACK.template.json +42 -42
  123. package/oxe/templates/IMPLEMENTATION-PACK.template.md +16 -16
  124. package/oxe/templates/INVESTIGATION.template.md +38 -38
  125. package/oxe/templates/LESSONS-METRICS.template.json +13 -13
  126. package/oxe/templates/LESSONS.template.md +43 -43
  127. package/oxe/templates/MEMORY.template.md +49 -49
  128. package/oxe/templates/MILESTONES.template.md +17 -17
  129. package/oxe/templates/NOTES.template.md +16 -16
  130. package/oxe/templates/OBSERVATIONS.template.md +18 -18
  131. package/oxe/templates/PLAN-REVIEW.template.md +31 -31
  132. package/oxe/templates/PLAN.template.md +66 -66
  133. package/oxe/templates/PLUGINS.md +108 -108
  134. package/oxe/templates/REFERENCE-ANCHORS.template.md +9 -9
  135. package/oxe/templates/RESEARCH.template.md +57 -57
  136. package/oxe/templates/RESUME.template.md +49 -49
  137. package/oxe/templates/ROADMAP.template.md +44 -44
  138. package/oxe/templates/SECURITY.template.md +72 -72
  139. package/oxe/templates/SESSION.template.md +34 -34
  140. package/oxe/templates/SKILL.template.md +26 -26
  141. package/oxe/templates/SPEC.template.md +54 -54
  142. package/oxe/templates/STATE-REFERENCE.md +125 -125
  143. package/oxe/templates/STATE.md +30 -30
  144. package/oxe/templates/WORKFLOW_AUTHORING.md +93 -93
  145. package/oxe/templates/config.template.json +38 -38
  146. package/oxe/templates/plan-agent-messages-README.template.md +9 -9
  147. package/oxe/templates/plan-agents.template.json +30 -30
  148. package/oxe/templates/quick-agents.template.json +24 -24
  149. package/oxe/workflows/ask.md +96 -96
  150. package/oxe/workflows/capabilities.md +25 -25
  151. package/oxe/workflows/checkpoint.md +37 -37
  152. package/oxe/workflows/compact.md +44 -44
  153. package/oxe/workflows/dashboard.md +33 -33
  154. package/oxe/workflows/debug.md +34 -34
  155. package/oxe/workflows/discuss.md +86 -86
  156. package/oxe/workflows/execute.md +255 -255
  157. package/oxe/workflows/forensics.md +48 -48
  158. package/oxe/workflows/help.md +355 -355
  159. package/oxe/workflows/loop.md +67 -67
  160. package/oxe/workflows/milestone.md +95 -95
  161. package/oxe/workflows/next.md +45 -45
  162. package/oxe/workflows/obs.md +167 -167
  163. package/oxe/workflows/oxe.md +150 -149
  164. package/oxe/workflows/plan-agent.md +143 -143
  165. package/oxe/workflows/plan.md +525 -523
  166. package/oxe/workflows/project.md +55 -55
  167. package/oxe/workflows/quick.md +185 -185
  168. package/oxe/workflows/references/adaptive-discovery.md +27 -27
  169. package/oxe/workflows/references/flow-robustness-contract.md +80 -80
  170. package/oxe/workflows/references/legacy-brownfield.md +136 -136
  171. package/oxe/workflows/references/plan-agent-chat-protocol.md +99 -99
  172. package/oxe/workflows/references/plan-json-acceptance-program.md +143 -0
  173. package/oxe/workflows/references/reasoning-discovery.md +28 -28
  174. package/oxe/workflows/references/reasoning-execution.md +29 -29
  175. package/oxe/workflows/references/reasoning-planning.md +32 -32
  176. package/oxe/workflows/references/reasoning-review.md +29 -29
  177. package/oxe/workflows/references/reasoning-status.md +24 -24
  178. package/oxe/workflows/references/robustness-elevation.md +295 -295
  179. package/oxe/workflows/references/session-path-resolution.md +71 -71
  180. package/oxe/workflows/research.md +66 -66
  181. package/oxe/workflows/retro.md +117 -117
  182. package/oxe/workflows/review-pr.md +53 -53
  183. package/oxe/workflows/route.md +32 -32
  184. package/oxe/workflows/security.md +67 -67
  185. package/oxe/workflows/session.md +213 -213
  186. package/oxe/workflows/ship.md +142 -142
  187. package/oxe/workflows/skill.md +44 -44
  188. package/oxe/workflows/spec.md +569 -566
  189. package/oxe/workflows/ui-review.md +32 -32
  190. package/oxe/workflows/ui-spec.md +25 -25
  191. package/oxe/workflows/update.md +35 -35
  192. package/oxe/workflows/validate-gaps.md +45 -45
  193. package/oxe/workflows/verify-audit.md +73 -73
  194. package/oxe/workflows/verify.md +247 -244
  195. package/oxe/workflows/workflow-authoring.md +34 -34
  196. package/oxe/workflows/workstream.md +97 -97
  197. package/package.json +132 -129
  198. package/packages/runtime/package.json +18 -18
  199. package/packages/runtime/src/audit/audit-trail.ts +243 -243
  200. package/packages/runtime/src/audit/index.ts +2 -2
  201. package/packages/runtime/src/audit/policy-pack.ts +62 -62
  202. package/packages/runtime/src/compiler/graph-compiler.ts +336 -285
  203. package/packages/runtime/src/compiler/index.ts +1 -1
  204. package/packages/runtime/src/context/context-pack-builder.ts +339 -339
  205. package/packages/runtime/src/context/context-pack-store.ts +197 -197
  206. package/packages/runtime/src/context/context-profiles.ts +60 -60
  207. package/packages/runtime/src/context/index.ts +3 -3
  208. package/packages/runtime/src/decision/decision-engine.ts +174 -174
  209. package/packages/runtime/src/decision/decision-memo.ts +211 -211
  210. package/packages/runtime/src/decision/index.ts +2 -2
  211. package/packages/runtime/src/delivery/branch-manager.ts +91 -91
  212. package/packages/runtime/src/delivery/ci-checks.ts +285 -285
  213. package/packages/runtime/src/delivery/delivery-records.ts +75 -75
  214. package/packages/runtime/src/delivery/index.ts +5 -5
  215. package/packages/runtime/src/delivery/pr-manager.ts +112 -112
  216. package/packages/runtime/src/delivery/promotion-pipeline.ts +342 -334
  217. package/packages/runtime/src/events/bus.ts +92 -92
  218. package/packages/runtime/src/events/catalog.ts +45 -34
  219. package/packages/runtime/src/events/envelope.ts +14 -14
  220. package/packages/runtime/src/events/index.ts +3 -3
  221. package/packages/runtime/src/evidence/evidence-store.ts +130 -130
  222. package/packages/runtime/src/evidence/index.ts +1 -1
  223. package/packages/runtime/src/executor/adapters/claude-cli.ts +285 -0
  224. package/packages/runtime/src/executor/adapters/http-openai.ts +16 -0
  225. package/packages/runtime/src/executor/adapters/registry.ts +33 -0
  226. package/packages/runtime/src/executor/adapters/types.ts +24 -0
  227. package/packages/runtime/src/executor/built-in-tools.ts +36 -8
  228. package/packages/runtime/src/executor/index.ts +12 -2
  229. package/packages/runtime/src/executor/llm-task-executor.ts +125 -25
  230. package/packages/runtime/src/executor/node-context.ts +210 -0
  231. package/packages/runtime/src/executor/node-prompt-builder.ts +5 -0
  232. package/packages/runtime/src/executor/shell-argv.ts +66 -0
  233. package/packages/runtime/src/executor/stream-completion.ts +16 -1
  234. package/packages/runtime/src/gate/gate-manager.ts +289 -289
  235. package/packages/runtime/src/gate/index.ts +1 -1
  236. package/packages/runtime/src/index.ts +54 -44
  237. package/packages/runtime/src/models/attempt.ts +19 -19
  238. package/packages/runtime/src/models/evidence.ts +21 -21
  239. package/packages/runtime/src/models/gate-decision.ts +25 -25
  240. package/packages/runtime/src/models/index.ts +8 -8
  241. package/packages/runtime/src/models/run.ts +24 -24
  242. package/packages/runtime/src/models/session.ts +11 -11
  243. package/packages/runtime/src/models/verification-result.ts +10 -10
  244. package/packages/runtime/src/models/work-item.ts +25 -25
  245. package/packages/runtime/src/models/workspace.ts +31 -31
  246. package/packages/runtime/src/plugins/capability-adapter.ts +313 -313
  247. package/packages/runtime/src/plugins/capability-matrix.ts +126 -126
  248. package/packages/runtime/src/plugins/index.ts +5 -5
  249. package/packages/runtime/src/plugins/plugin-abi.ts +106 -106
  250. package/packages/runtime/src/plugins/plugin-manifest.ts +118 -118
  251. package/packages/runtime/src/plugins/plugin-registry.ts +241 -241
  252. package/packages/runtime/src/policy/index.ts +1 -1
  253. package/packages/runtime/src/policy/policy-engine.ts +330 -330
  254. package/packages/runtime/src/program/index.ts +1 -0
  255. package/packages/runtime/src/program/program-model.ts +233 -0
  256. package/packages/runtime/src/projection/index.ts +1 -1
  257. package/packages/runtime/src/projection/projection-engine.ts +361 -328
  258. package/packages/runtime/src/reducers/debug-reducer.ts +36 -36
  259. package/packages/runtime/src/reducers/index.ts +2 -2
  260. package/packages/runtime/src/reducers/run-state-reducer.ts +329 -326
  261. package/packages/runtime/src/scheduler/agent-registry.ts +132 -132
  262. package/packages/runtime/src/scheduler/agent-roles.ts +109 -109
  263. package/packages/runtime/src/scheduler/index.ts +4 -4
  264. package/packages/runtime/src/scheduler/multi-agent-coordinator.ts +1017 -1017
  265. package/packages/runtime/src/scheduler/run-journal.ts +105 -62
  266. package/packages/runtime/src/scheduler/scheduler.ts +1144 -938
  267. package/packages/runtime/src/verification/contract-exports.ts +203 -0
  268. package/packages/runtime/src/verification/index.ts +3 -2
  269. package/packages/runtime/src/verification/test-report-parsers.ts +198 -0
  270. package/packages/runtime/src/verification/verification-compiler.ts +766 -438
  271. package/packages/runtime/src/verification/verification-manifest.ts +281 -256
  272. package/packages/runtime/src/workspace/index.ts +5 -5
  273. package/packages/runtime/src/workspace/strategies/ephemeral-container.ts +126 -126
  274. package/packages/runtime/src/workspace/strategies/git-worktree.ts +150 -87
  275. package/packages/runtime/src/workspace/strategies/inplace.ts +38 -38
  276. package/packages/runtime/src/workspace/workspace-manager.ts +16 -16
  277. package/packages/runtime/tsconfig.json +23 -23
  278. package/vscode-extension/.vscodeignore +9 -9
  279. package/vscode-extension/package.json +193 -193
  280. package/vscode-extension/src/extension.js +320 -320
  281. package/vscode-extension/src/shared/contextLoader.js +137 -137
  282. package/vscode-extension/src/shared/contractBuilder.js +159 -159
  283. package/vscode-extension/src/shared/stateReader.js +101 -101
  284. package/docs/oxe-artifact-map.html +0 -1172
@@ -1,1017 +1,1017 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import { appendEvent } from '../events/bus';
4
- import type { ExecutionGraph, GraphNode } from '../compiler/graph-compiler';
5
- import type { WorkspaceManager, WorkspaceRequest } from '../workspace/workspace-manager';
6
- import type { WorkspaceLease, SnapshotRef } from '../models/workspace';
7
- import type { TaskExecutor, TaskResult, SchedulerContext, RunResult } from './scheduler';
8
- import { Scheduler } from './scheduler';
9
- import { buildHandoff } from './agent-roles';
10
- import type { CooperativeHandoff } from './agent-roles';
11
- import { AgentRegistry } from './agent-registry';
12
-
13
- export type CoordinationMode = 'parallel' | 'competitive' | 'cooperative';
14
-
15
- export interface AgentSpec {
16
- id: string;
17
- executor: TaskExecutor;
18
- workspaceManager: WorkspaceManager;
19
- /** Task IDs this agent is responsible for (used in parallel mode) */
20
- assignedTaskIds?: string[];
21
- }
22
-
23
- export interface CoordinationOptions {
24
- mode: CoordinationMode;
25
- agents: AgentSpec[];
26
- projectRoot: string;
27
- sessionId: string | null;
28
- runId: string;
29
- onEvent?: SchedulerContext['onEvent'];
30
- heartbeatTimeoutMs?: number;
31
- applyWorkspaceMerges?: boolean;
32
- }
33
-
34
- export interface ArbitrationRecord {
35
- work_item_id: string;
36
- mode: CoordinationMode;
37
- winner_agent_id: string | null;
38
- participant_agent_ids: string[];
39
- success: boolean;
40
- failure_class: TaskResult['failure_class'];
41
- evidence_count: number;
42
- recorded_at: string;
43
- }
44
-
45
- export interface MultiAgentOwnership {
46
- work_item_id: string;
47
- owner_agent_id: string;
48
- }
49
-
50
- export interface WorkspaceMergeRecord {
51
- work_item_id: string;
52
- agent_id: string;
53
- workspace_id: string;
54
- strategy: string;
55
- isolation_level: 'shared' | 'isolated';
56
- branch: string | null;
57
- base_commit: string | null;
58
- root_path: string | null;
59
- mutation_scope: string[];
60
- diff_paths: string[];
61
- evidence_refs: string[];
62
- evidence_count: number;
63
- verify_status: 'pass' | 'fail' | 'partial';
64
- status: 'ready' | 'merged' | 'blocked' | 'skipped';
65
- blocker: string | null;
66
- applied_paths: string[];
67
- diff_summary: {
68
- added: number;
69
- modified: number;
70
- missing: number;
71
- paths: string[];
72
- };
73
- next_action: string | null;
74
- recorded_at: string;
75
- }
76
-
77
- export interface WorkspaceMergeReport {
78
- schema_version: 1;
79
- run_id: string;
80
- generated_at: string;
81
- workspace_isolation: 'git_worktree';
82
- merge_readiness: 'ready' | 'blocked' | 'partial';
83
- arbitration_required: boolean;
84
- blockers: string[];
85
- records: WorkspaceMergeRecord[];
86
- }
87
-
88
- export interface MultiAgentStatusSnapshot {
89
- run_id: string;
90
- mode: CoordinationMode;
91
- workspace_isolation_required: 'isolated';
92
- workspace_isolation_enforced: boolean;
93
- agent_count: number;
94
- ownership: MultiAgentOwnership[];
95
- completed: string[];
96
- failed: string[];
97
- blocked: string[];
98
- agent_results: Array<{
99
- agent_id: string;
100
- isolation_level: 'shared' | 'isolated';
101
- assigned_task_ids: string[];
102
- completed: string[];
103
- failed: string[];
104
- timed_out: boolean;
105
- reassigned_task_ids: string[];
106
- }>;
107
- worktrees: WorkspaceMergeRecord[];
108
- workspace_merge: WorkspaceMergeReport;
109
- merge_blockers: string[];
110
- arbitration_required: boolean;
111
- orphan_reassignments: Array<{ from_agent_id: string; to_agent_id: string; work_item_ids: string[] }>;
112
- timed_out_agents: Array<{ agent_id: string; work_item_ids: string[]; detected_at: string }>;
113
- updated_at: string;
114
- }
115
-
116
- export interface MultiAgentOperationalSummary {
117
- run_id: string;
118
- mode: CoordinationMode;
119
- workspace_isolation_enforced: boolean;
120
- agent_count: number;
121
- completed_count: number;
122
- failed_count: number;
123
- blocked_count: number;
124
- ownership_count: number;
125
- handoff_count: number;
126
- arbitration_count: number;
127
- orphan_reassignment_count: number;
128
- timeout_count: number;
129
- participating_agents: string[];
130
- workspace_isolation: 'git_worktree';
131
- merge_readiness: WorkspaceMergeReport['merge_readiness'];
132
- arbitration_required: boolean;
133
- merge_blocker_count: number;
134
- health: 'healthy' | 'degraded';
135
- updated_at: string;
136
- }
137
-
138
- export interface CoordinationResult {
139
- mode: CoordinationMode;
140
- run_id: string;
141
- completed: string[];
142
- failed: string[];
143
- blocked: string[];
144
- agent_results: Array<{ agent_id: string; completed: string[]; failed: string[] }>;
145
- handoffs?: CooperativeHandoff[];
146
- arbitration_results?: ArbitrationRecord[];
147
- workspace_merge_report?: WorkspaceMergeReport;
148
- state?: MultiAgentStatusSnapshot;
149
- summary?: MultiAgentOperationalSummary;
150
- }
151
-
152
- function ensureRunDir(projectRoot: string, runId: string): string {
153
- const dir = path.join(projectRoot, '.oxe', 'runs', runId);
154
- fs.mkdirSync(dir, { recursive: true });
155
- return dir;
156
- }
157
-
158
- function persistMultiAgentArtifacts(
159
- projectRoot: string,
160
- runId: string,
161
- state: MultiAgentStatusSnapshot,
162
- handoffs: CooperativeHandoff[] = [],
163
- arbitrationResults: ArbitrationRecord[] = [],
164
- workspaceMergeReport: WorkspaceMergeReport = emptyWorkspaceMergeReport(runId)
165
- ): void {
166
- const runDir = ensureRunDir(projectRoot, runId);
167
- fs.writeFileSync(path.join(runDir, 'multi-agent-state.json'), JSON.stringify(state, null, 2), 'utf8');
168
- fs.writeFileSync(path.join(runDir, 'handoffs.json'), JSON.stringify(handoffs, null, 2), 'utf8');
169
- fs.writeFileSync(path.join(runDir, 'arbitration-results.json'), JSON.stringify(arbitrationResults, null, 2), 'utf8');
170
- fs.writeFileSync(path.join(runDir, 'workspace-merge-report.json'), JSON.stringify(workspaceMergeReport, null, 2), 'utf8');
171
- const summary: MultiAgentOperationalSummary = {
172
- run_id: state.run_id,
173
- mode: state.mode,
174
- workspace_isolation_enforced: state.workspace_isolation_enforced,
175
- agent_count: state.agent_count,
176
- completed_count: state.completed.length,
177
- failed_count: state.failed.length,
178
- blocked_count: state.blocked.length,
179
- ownership_count: state.ownership.length,
180
- handoff_count: handoffs.length,
181
- arbitration_count: arbitrationResults.length,
182
- orphan_reassignment_count: state.orphan_reassignments.length,
183
- timeout_count: state.timed_out_agents.length,
184
- participating_agents: state.agent_results.map((entry) => entry.agent_id),
185
- workspace_isolation: 'git_worktree',
186
- merge_readiness: workspaceMergeReport.merge_readiness,
187
- arbitration_required: workspaceMergeReport.arbitration_required,
188
- merge_blocker_count: workspaceMergeReport.blockers.length,
189
- health: state.timed_out_agents.length > 0 || state.failed.length > 0 ? 'degraded' : 'healthy',
190
- updated_at: state.updated_at,
191
- };
192
- fs.writeFileSync(path.join(runDir, 'multi-agent-summary.json'), JSON.stringify(summary, null, 2), 'utf8');
193
- }
194
-
195
- function ensureIsolatedAgents(agents: AgentSpec[]): void {
196
- const shared = agents.filter((agent) => agent.workspaceManager.isolation_level !== 'isolated');
197
- if (shared.length === 0) return;
198
- const ids = shared.map((agent) => `${agent.id}:${agent.workspaceManager.isolation_level}`).join(', ');
199
- throw new Error(`Multi-agent requires isolated workspaces. Invalid agents: ${ids}`);
200
- }
201
-
202
- function buildOwnership(agents: AgentSpec[], partitions: string[][]): MultiAgentOwnership[] {
203
- const ownership: MultiAgentOwnership[] = [];
204
- for (let idx = 0; idx < agents.length; idx += 1) {
205
- for (const workItemId of partitions[idx] ?? []) {
206
- ownership.push({
207
- work_item_id: workItemId,
208
- owner_agent_id: agents[idx].id,
209
- });
210
- }
211
- }
212
- return ownership;
213
- }
214
-
215
- function makeState(
216
- mode: CoordinationMode,
217
- runId: string,
218
- agents: AgentSpec[],
219
- partitions: string[][],
220
- agentResults: Array<{ agent_id: string; completed: string[]; failed: string[]; timed_out: boolean; reassigned_task_ids: string[] }>,
221
- completed: string[],
222
- failed: string[],
223
- blocked: string[],
224
- orphanReassignments: Array<{ from_agent_id: string; to_agent_id: string; work_item_ids: string[] }>,
225
- timedOutAgents: Array<{ agent_id: string; work_item_ids: string[]; detected_at: string }>,
226
- workspaceMergeReport: WorkspaceMergeReport = emptyWorkspaceMergeReport(runId)
227
- ): MultiAgentStatusSnapshot {
228
- return {
229
- run_id: runId,
230
- mode,
231
- workspace_isolation_required: 'isolated',
232
- workspace_isolation_enforced: true,
233
- agent_count: agents.length,
234
- ownership: buildOwnership(agents, partitions),
235
- completed,
236
- failed,
237
- blocked,
238
- agent_results: agents.map((agent, idx) => {
239
- const result = agentResults.find((entry) => entry.agent_id === agent.id);
240
- return {
241
- agent_id: agent.id,
242
- isolation_level: agent.workspaceManager.isolation_level,
243
- assigned_task_ids: partitions[idx] ?? agent.assignedTaskIds ?? [],
244
- completed: result?.completed ?? [],
245
- failed: result?.failed ?? [],
246
- timed_out: Boolean(result?.timed_out),
247
- reassigned_task_ids: result?.reassigned_task_ids ?? [],
248
- };
249
- }),
250
- worktrees: workspaceMergeReport.records,
251
- workspace_merge: workspaceMergeReport,
252
- merge_blockers: workspaceMergeReport.blockers,
253
- arbitration_required: workspaceMergeReport.arbitration_required,
254
- orphan_reassignments: orphanReassignments,
255
- timed_out_agents: timedOutAgents,
256
- updated_at: new Date().toISOString(),
257
- };
258
- }
259
-
260
- function emptyWorkspaceMergeReport(runId: string): WorkspaceMergeReport {
261
- return {
262
- schema_version: 1,
263
- run_id: runId,
264
- generated_at: new Date().toISOString(),
265
- workspace_isolation: 'git_worktree',
266
- merge_readiness: 'ready',
267
- arbitration_required: false,
268
- blockers: [],
269
- records: [],
270
- };
271
- }
272
-
273
- function ensureGitWorktreeLease(agent: AgentSpec, lease: WorkspaceLease): void {
274
- if (lease.isolation_level !== 'isolated' || lease.strategy !== 'git_worktree') {
275
- throw new Error(`Multi-agent real requires git_worktree isolated workspace. Agent ${agent.id} received ${lease.strategy}/${lease.isolation_level}.`);
276
- }
277
- }
278
-
279
- function mutationScopeOf(node?: GraphNode): string[] {
280
- return Array.isArray(node?.mutation_scope) ? node!.mutation_scope.map(String).filter(Boolean) : [];
281
- }
282
-
283
- function createMergeRecord(
284
- agent: AgentSpec,
285
- node: GraphNode,
286
- lease: WorkspaceLease,
287
- result?: TaskResult
288
- ): WorkspaceMergeRecord {
289
- const evidenceRefs = Array.isArray(result?.evidence) ? result!.evidence.map(String).filter(Boolean) : [];
290
- const scope = mutationScopeOf(node);
291
- return {
292
- work_item_id: node.id,
293
- agent_id: agent.id,
294
- workspace_id: lease.workspace_id,
295
- strategy: lease.strategy,
296
- isolation_level: lease.isolation_level,
297
- branch: lease.branch ?? null,
298
- base_commit: lease.base_commit ?? null,
299
- root_path: lease.root_path ?? null,
300
- mutation_scope: scope,
301
- diff_paths: scope,
302
- evidence_refs: evidenceRefs,
303
- evidence_count: evidenceRefs.length,
304
- verify_status: result ? (result.success ? 'pass' : 'fail') : 'partial',
305
- status: result ? (result.success ? 'ready' : 'blocked') : 'ready',
306
- blocker: result && !result.success ? `verify_failed:${result.failure_class}` : null,
307
- applied_paths: [],
308
- diff_summary: { added: 0, modified: 0, missing: 0, paths: scope },
309
- next_action: result && !result.success ? 'Corrija a falha de verify/evidence antes de aplicar merge do workspace.' : null,
310
- recorded_at: new Date().toISOString(),
311
- };
312
- }
313
-
314
- function enrichMergeRecordWithResult(record: WorkspaceMergeRecord, result?: TaskResult): WorkspaceMergeRecord {
315
- if (!result) return record;
316
- const evidenceRefs = Array.isArray(result.evidence) ? result.evidence.map(String).filter(Boolean) : [];
317
- return {
318
- ...record,
319
- evidence_refs: evidenceRefs,
320
- evidence_count: evidenceRefs.length,
321
- verify_status: result.success ? 'pass' : 'fail',
322
- status: result.success ? 'ready' : 'blocked',
323
- blocker: result.success ? null : `verify_failed:${result.failure_class}`,
324
- next_action: result.success ? null : 'Corrija a falha de verify/evidence antes de aplicar merge do workspace.',
325
- recorded_at: new Date().toISOString(),
326
- };
327
- }
328
-
329
- function buildWorkspaceMergeReport(
330
- runId: string,
331
- records: WorkspaceMergeRecord[],
332
- extraBlockers: string[] = [],
333
- arbitrationRequired = false
334
- ): WorkspaceMergeReport {
335
- const blockers = [
336
- ...extraBlockers,
337
- ...records.filter((record) => record.status === 'blocked' && record.blocker).map((record) => `${record.work_item_id}:${record.blocker}`),
338
- ];
339
- return {
340
- schema_version: 1,
341
- run_id: runId,
342
- generated_at: new Date().toISOString(),
343
- workspace_isolation: 'git_worktree',
344
- merge_readiness: blockers.length > 0 ? 'blocked' : records.some((record) => record.status === 'ready') ? 'partial' : 'ready',
345
- arbitration_required: arbitrationRequired,
346
- blockers,
347
- records,
348
- };
349
- }
350
-
351
- function detectMutationConflicts(graph: ExecutionGraph, agents: AgentSpec[], partitions: string[][]): string[] {
352
- const owners = new Map<string, string>();
353
- const conflicts: string[] = [];
354
- for (let idx = 0; idx < agents.length; idx += 1) {
355
- for (const nodeId of partitions[idx] ?? []) {
356
- const node = graph.nodes.get(nodeId);
357
- for (const scope of mutationScopeOf(node)) {
358
- const previous = owners.get(scope);
359
- if (previous && previous !== agents[idx].id) {
360
- conflicts.push(`mutation_scope_overlap:${scope}:${previous}:${agents[idx].id}`);
361
- } else {
362
- owners.set(scope, agents[idx].id);
363
- }
364
- }
365
- }
366
- }
367
- return conflicts;
368
- }
369
-
370
- function applyWorkspaceRecord(projectRoot: string, record: WorkspaceMergeRecord): WorkspaceMergeRecord {
371
- if (!record.root_path || record.status !== 'ready') return record;
372
- const appliedPaths: string[] = [];
373
- const summary = { added: 0, modified: 0, missing: 0, paths: [...record.mutation_scope] };
374
- for (const relativePath of record.mutation_scope) {
375
- const source = path.join(record.root_path, relativePath);
376
- const target = path.join(projectRoot, relativePath);
377
- if (!fs.existsSync(source) || fs.statSync(source).isDirectory()) {
378
- summary.missing += 1;
379
- return {
380
- ...record,
381
- status: 'blocked',
382
- blocker: `missing_output:${relativePath}`,
383
- diff_summary: summary,
384
- next_action: `Materialize o arquivo esperado ${relativePath} no worktree do agente antes do merge.`,
385
- };
386
- }
387
- if (fs.existsSync(target)) summary.modified += 1;
388
- else summary.added += 1;
389
- fs.mkdirSync(path.dirname(target), { recursive: true });
390
- fs.copyFileSync(source, target);
391
- appliedPaths.push(relativePath);
392
- }
393
- return {
394
- ...record,
395
- status: 'merged',
396
- blocker: null,
397
- applied_paths: appliedPaths,
398
- diff_summary: summary,
399
- next_action: null,
400
- };
401
- }
402
-
403
- function createTrackingWorkspaceManager(
404
- base: WorkspaceManager,
405
- agent: AgentSpec,
406
- graph: ExecutionGraph,
407
- records: WorkspaceMergeRecord[]
408
- ): WorkspaceManager & { disposeDeferred(): Promise<void> } {
409
- const leases = new Map<string, WorkspaceLease>();
410
- return {
411
- isolation_level: base.isolation_level,
412
- allocate: async (req: WorkspaceRequest) => {
413
- const lease = await base.allocate(req);
414
- ensureGitWorktreeLease(agent, lease);
415
- leases.set(lease.workspace_id, lease);
416
- const node = graph.nodes.get(req.work_item_id);
417
- if (node) records.push(createMergeRecord(agent, node, lease));
418
- return lease;
419
- },
420
- snapshot: (id: string): Promise<SnapshotRef> => base.snapshot(id),
421
- reset: (id: string, snapRef: SnapshotRef): Promise<void> => base.reset(id, snapRef),
422
- dispose: async () => {
423
- // Scheduler calls dispose before the coordinator can reconcile diffs.
424
- // Defer real cleanup until the merge report has been produced.
425
- },
426
- disposeDeferred: async () => {
427
- await Promise.all([...leases.keys()].map((id) => base.dispose(id).catch(() => {})));
428
- leases.clear();
429
- },
430
- };
431
- }
432
-
433
- async function runGraphForAgent(
434
- graph: ExecutionGraph,
435
- nodeIds: string[],
436
- agent: AgentSpec,
437
- idx: number,
438
- opts: CoordinationOptions,
439
- heartbeatTimeoutMs: number | null
440
- ): Promise<{
441
- agent_id: string;
442
- completed: string[];
443
- failed: string[];
444
- timed_out: boolean;
445
- assigned_task_ids: string[];
446
- reassigned_task_ids: string[];
447
- workspace_records: WorkspaceMergeRecord[];
448
- cleanup: () => Promise<void>;
449
- }> {
450
- const subGraph = subGraphFor(graph, nodeIds);
451
- const workspaceRecords: WorkspaceMergeRecord[] = [];
452
- if (subGraph.nodes.size === 0) {
453
- return {
454
- agent_id: agent.id,
455
- completed: [],
456
- failed: [],
457
- timed_out: false,
458
- assigned_task_ids: nodeIds,
459
- reassigned_task_ids: [],
460
- workspace_records: workspaceRecords,
461
- cleanup: async () => {},
462
- };
463
- }
464
- const trackingWorkspaceManager = createTrackingWorkspaceManager(agent.workspaceManager, agent, graph, workspaceRecords);
465
- const taskResults = new Map<string, TaskResult>();
466
- const trackingExecutor: TaskExecutor = {
467
- execute: async (node, lease, runId, attemptNumber) => {
468
- const result = await agent.executor.execute(node, lease, runId, attemptNumber);
469
- taskResults.set(node.id, result);
470
- return result;
471
- },
472
- };
473
- const ctx: SchedulerContext = {
474
- projectRoot: opts.projectRoot,
475
- sessionId: opts.sessionId,
476
- runId: `${opts.runId}-agent${idx}`,
477
- executor: trackingExecutor,
478
- workspaceManager: trackingWorkspaceManager,
479
- onEvent: opts.onEvent,
480
- };
481
- const scheduler = new Scheduler();
482
- const work = scheduler.run(subGraph, ctx);
483
- if (!heartbeatTimeoutMs || heartbeatTimeoutMs <= 0) {
484
- const result = await work;
485
- const reconciledRecords = workspaceRecords.map((record) => enrichMergeRecordWithResult(record, taskResults.get(record.work_item_id)));
486
- return {
487
- agent_id: agent.id,
488
- completed: result.completed,
489
- failed: result.failed,
490
- timed_out: false,
491
- assigned_task_ids: nodeIds,
492
- reassigned_task_ids: [],
493
- workspace_records: reconciledRecords,
494
- cleanup: () => trackingWorkspaceManager.disposeDeferred(),
495
- };
496
- }
497
- let timer: NodeJS.Timeout | null = null;
498
- const raced: { type: 'result'; result: RunResult } | { type: 'timeout' } = await Promise.race([
499
- work.then((result) => ({ type: 'result' as const, result })),
500
- new Promise<{ type: 'timeout' }>((resolve) => {
501
- timer = setTimeout(() => resolve({ type: 'timeout' }), heartbeatTimeoutMs);
502
- }),
503
- ]);
504
- if (timer) clearTimeout(timer);
505
- if (raced && raced.type === 'timeout') {
506
- return {
507
- agent_id: agent.id,
508
- completed: [],
509
- failed: [],
510
- timed_out: true,
511
- assigned_task_ids: nodeIds,
512
- reassigned_task_ids: [],
513
- workspace_records: workspaceRecords,
514
- cleanup: () => trackingWorkspaceManager.disposeDeferred(),
515
- };
516
- }
517
- const result = raced.result;
518
- const reconciledRecords = workspaceRecords.map((record) => enrichMergeRecordWithResult(record, taskResults.get(record.work_item_id)));
519
- return {
520
- agent_id: agent.id,
521
- completed: result.completed,
522
- failed: result.failed,
523
- timed_out: false,
524
- assigned_task_ids: nodeIds,
525
- reassigned_task_ids: [],
526
- workspace_records: reconciledRecords,
527
- cleanup: () => trackingWorkspaceManager.disposeDeferred(),
528
- };
529
- }
530
-
531
- // ─── Parallel mode ───────────────────────────────────────────────────────────
532
-
533
- async function runParallel(
534
- graph: ExecutionGraph,
535
- opts: CoordinationOptions
536
- ): Promise<CoordinationResult> {
537
- const { agents, projectRoot, sessionId, runId } = opts;
538
- ensureIsolatedAgents(agents);
539
- const heartbeatTimeoutMs = opts.heartbeatTimeoutMs ?? null;
540
-
541
- const partitions = agents.map((agent) => [...(agent.assignedTaskIds ?? [])]);
542
- if (partitions.every((partition) => partition.length === 0)) {
543
- const allIds = [...graph.nodes.keys()];
544
- allIds.forEach((id, index) => {
545
- partitions[index % agents.length].push(id);
546
- });
547
- }
548
- const mutationConflicts = detectMutationConflicts(graph, agents, partitions);
549
- if (mutationConflicts.length > 0) {
550
- const blocked = mutationConflicts;
551
- const workspaceMergeReport = buildWorkspaceMergeReport(runId, [], blocked);
552
- const state = makeState('parallel', runId, agents, partitions, [], [], [], blocked, [], [], workspaceMergeReport);
553
- persistMultiAgentArtifacts(projectRoot, runId, state, [], [], workspaceMergeReport);
554
- appendEvent(projectRoot, sessionId, {
555
- type: 'WorkItemBlocked',
556
- run_id: runId,
557
- payload: { mode: 'parallel', blockers: blocked },
558
- });
559
- return {
560
- mode: 'parallel',
561
- run_id: runId,
562
- completed: [],
563
- failed: [],
564
- blocked,
565
- agent_results: [],
566
- arbitration_results: [],
567
- workspace_merge_report: workspaceMergeReport,
568
- state,
569
- summary: loadMultiAgentSummary(projectRoot, runId) || undefined,
570
- };
571
- }
572
- const registry = new AgentRegistry(heartbeatTimeoutMs == null ? 30_000 : heartbeatTimeoutMs);
573
- agents.forEach((agent, idx) => {
574
- registry.register(agent.id, agent.executor, agent.workspaceManager, partitions[idx] ?? []);
575
- });
576
-
577
- appendEvent(projectRoot, sessionId, {
578
- type: 'RunStarted',
579
- run_id: runId,
580
- payload: { mode: 'parallel', agent_count: agents.length, isolation_level: 'isolated' },
581
- });
582
-
583
- const initialResults = await Promise.all(
584
- agents.map(async (agent, idx) => {
585
- registry.beat(agent.id, partitions[idx][0] || null);
586
- const result = await runGraphForAgent(graph, partitions[idx], agent, idx, opts, heartbeatTimeoutMs);
587
- registry.setStatus(agent.id, result.timed_out ? 'timeout' : 'idle');
588
- return result;
589
- })
590
- );
591
-
592
- const timedOutAgents = [];
593
- const blocked: string[] = [];
594
- const orphanReassignments: Array<{ from_agent_id: string; to_agent_id: string; work_item_ids: string[] }> = [];
595
- const agentResults = initialResults.map((entry) => ({
596
- ...entry,
597
- reassigned_task_ids: entry.reassigned_task_ids || [],
598
- }));
599
- const liveAgents = agentResults.filter((entry) => !entry.timed_out);
600
- for (const timedOut of agentResults.filter((entry) => entry.timed_out)) {
601
- timedOutAgents.push({
602
- agent_id: timedOut.agent_id,
603
- work_item_ids: timedOut.assigned_task_ids,
604
- detected_at: new Date().toISOString(),
605
- });
606
- const fallback = liveAgents.find((entry) => entry.agent_id !== timedOut.agent_id);
607
- if (!fallback || timedOut.assigned_task_ids.length === 0) continue;
608
- const fallbackIdx = agents.findIndex((agent) => agent.id === fallback.agent_id);
609
- const timeoutIdx = agents.findIndex((agent) => agent.id === timedOut.agent_id);
610
- const rerun = await runGraphForAgent(graph, timedOut.assigned_task_ids, agents[fallbackIdx], fallbackIdx, opts, null);
611
- fallback.completed.push(...rerun.completed);
612
- fallback.failed.push(...rerun.failed);
613
- fallback.workspace_records.push(...rerun.workspace_records);
614
- fallback.reassigned_task_ids.push(...timedOut.assigned_task_ids);
615
- const previousCleanup = fallback.cleanup;
616
- fallback.cleanup = async () => {
617
- await previousCleanup?.();
618
- await rerun.cleanup?.();
619
- };
620
- partitions[fallbackIdx] = [...partitions[fallbackIdx], ...timedOut.assigned_task_ids];
621
- partitions[timeoutIdx] = [];
622
- orphanReassignments.push({
623
- from_agent_id: timedOut.agent_id,
624
- to_agent_id: fallback.agent_id,
625
- work_item_ids: timedOut.assigned_task_ids,
626
- });
627
- }
628
-
629
- const completed = Array.from(new Set(agentResults.flatMap((result) => result.completed)));
630
- const failed = Array.from(new Set(agentResults.flatMap((result) => result.failed)));
631
- const rawRecords = agentResults.flatMap((result) => result.workspace_records || []);
632
- const mergedRecords = opts.applyWorkspaceMerges
633
- ? rawRecords.map((record) => applyWorkspaceRecord(projectRoot, record))
634
- : rawRecords;
635
- await Promise.all(agentResults.map((result) => result.cleanup?.().catch(() => {})));
636
- const workspaceMergeReport = buildWorkspaceMergeReport(runId, mergedRecords, blocked);
637
- const state = makeState('parallel', runId, agents, partitions, agentResults, completed, failed, blocked, orphanReassignments, timedOutAgents, workspaceMergeReport);
638
- persistMultiAgentArtifacts(projectRoot, runId, state, [], [], workspaceMergeReport);
639
-
640
- appendEvent(projectRoot, sessionId, {
641
- type: 'RunCompleted',
642
- run_id: runId,
643
- payload: { mode: 'parallel', completed: completed.length, failed: failed.length },
644
- });
645
-
646
- return {
647
- mode: 'parallel',
648
- run_id: runId,
649
- completed,
650
- failed,
651
- blocked,
652
- agent_results: agentResults,
653
- arbitration_results: [],
654
- workspace_merge_report: workspaceMergeReport,
655
- state,
656
- summary: loadMultiAgentSummary(projectRoot, runId) || undefined,
657
- };
658
- }
659
-
660
- // ─── Competitive mode ────────────────────────────────────────────────────────
661
-
662
- async function runCompetitive(
663
- graph: ExecutionGraph,
664
- opts: CoordinationOptions
665
- ): Promise<CoordinationResult> {
666
- if (opts.agents.length < 2) {
667
- throw new Error('Competitive mode requires at least 2 agents');
668
- }
669
- ensureIsolatedAgents(opts.agents);
670
- const [agentA, agentB] = opts.agents;
671
- const { projectRoot, sessionId, runId } = opts;
672
-
673
- appendEvent(projectRoot, sessionId, {
674
- type: 'RunStarted',
675
- run_id: runId,
676
- payload: { mode: 'competitive', isolation_level: 'isolated' },
677
- });
678
-
679
- const completed: string[] = [];
680
- const failed: string[] = [];
681
- const blocked: string[] = [];
682
- const arbitrationResults: ArbitrationRecord[] = [];
683
- const workspaceRecords: WorkspaceMergeRecord[] = [];
684
-
685
- for (const wave of graph.waves) {
686
- for (const nodeId of wave.node_ids) {
687
- const node = graph.nodes.get(nodeId)!;
688
- const result = await competeTwoAgents(nodeId, node, agentA, agentB, opts, arbitrationResults, workspaceRecords);
689
- if (result.success) completed.push(nodeId);
690
- else failed.push(nodeId);
691
- if (failed.length > 0) break;
692
- }
693
- if (failed.length > 0) break;
694
- }
695
-
696
- const partitions = [Array.from(graph.nodes.keys()), Array.from(graph.nodes.keys())];
697
- const workspaceMergeReport = buildWorkspaceMergeReport(runId, workspaceRecords, blocked, true);
698
- const state = makeState(
699
- 'competitive',
700
- runId,
701
- opts.agents,
702
- partitions,
703
- [
704
- { agent_id: agentA.id, completed, failed, timed_out: false, reassigned_task_ids: [] },
705
- { agent_id: agentB.id, completed: [], failed: [], timed_out: false, reassigned_task_ids: [] },
706
- ],
707
- completed,
708
- failed,
709
- blocked,
710
- [],
711
- [],
712
- workspaceMergeReport
713
- );
714
- persistMultiAgentArtifacts(projectRoot, runId, state, [], arbitrationResults, workspaceMergeReport);
715
-
716
- appendEvent(projectRoot, sessionId, {
717
- type: 'RunCompleted',
718
- run_id: runId,
719
- payload: { mode: 'competitive', completed: completed.length },
720
- });
721
-
722
- return {
723
- mode: 'competitive',
724
- run_id: runId,
725
- completed,
726
- failed,
727
- blocked,
728
- agent_results: [
729
- { agent_id: agentA.id, completed, failed },
730
- { agent_id: agentB.id, completed: [], failed: [] },
731
- ],
732
- arbitration_results: arbitrationResults,
733
- workspace_merge_report: workspaceMergeReport,
734
- state,
735
- summary: loadMultiAgentSummary(projectRoot, runId) || undefined,
736
- };
737
- }
738
-
739
- async function competeTwoAgents(
740
- nodeId: string,
741
- node: GraphNode,
742
- agentA: AgentSpec,
743
- agentB: AgentSpec,
744
- opts: CoordinationOptions,
745
- arbitrationResults: ArbitrationRecord[],
746
- workspaceRecords: WorkspaceMergeRecord[]
747
- ): Promise<TaskResult> {
748
- const { projectRoot, sessionId, runId } = opts;
749
-
750
- const allocA = await agentA.workspaceManager.allocate({
751
- work_item_id: nodeId, attempt_number: 1, strategy: node.workspace_strategy, mutation_scope: node.mutation_scope,
752
- });
753
- ensureGitWorktreeLease(agentA, allocA);
754
- const allocB = await agentB.workspaceManager.allocate({
755
- work_item_id: nodeId, attempt_number: 1, strategy: node.workspace_strategy, mutation_scope: node.mutation_scope,
756
- });
757
- ensureGitWorktreeLease(agentB, allocB);
758
-
759
- appendEvent(projectRoot, sessionId, {
760
- type: 'AttemptStarted',
761
- run_id: runId,
762
- work_item_id: nodeId,
763
- payload: { mode: 'competitive', agents: [agentA.id, agentB.id] },
764
- });
765
-
766
- const [resultA, resultB] = await Promise.all([
767
- agentA.executor.execute(node, allocA, runId, 1).catch((error) => ({
768
- success: false, failure_class: 'env' as const, evidence: [], output: String(error),
769
- })),
770
- agentB.executor.execute(node, allocB, runId, 1).catch((error) => ({
771
- success: false, failure_class: 'env' as const, evidence: [], output: String(error),
772
- })),
773
- ]);
774
-
775
- const candidates = [
776
- { agent: agentA, alloc: allocA, result: resultA },
777
- { agent: agentB, alloc: allocB, result: resultB },
778
- ].sort((left, right) => {
779
- const leftScore = (left.result.success ? 10_000 : 0) + left.result.evidence.length * 100 - String(left.result.output || '').length;
780
- const rightScore = (right.result.success ? 10_000 : 0) + right.result.evidence.length * 100 - String(right.result.output || '').length;
781
- return rightScore - leftScore;
782
- });
783
- const winnerCandidate = candidates[0];
784
- const winner = winnerCandidate.result;
785
- const winnerAgentId = winnerCandidate.agent.id;
786
- const winnerRecord = createMergeRecord(winnerCandidate.agent, node, winnerCandidate.alloc, winner);
787
- workspaceRecords.push(opts.applyWorkspaceMerges ? applyWorkspaceRecord(projectRoot, winnerRecord) : winnerRecord);
788
-
789
- await Promise.all([
790
- agentA.workspaceManager.dispose(allocA.workspace_id).catch(() => {}),
791
- agentB.workspaceManager.dispose(allocB.workspace_id).catch(() => {}),
792
- ]);
793
- arbitrationResults.push({
794
- work_item_id: nodeId,
795
- mode: 'competitive',
796
- winner_agent_id: winnerAgentId,
797
- participant_agent_ids: [agentA.id, agentB.id],
798
- success: winner.success,
799
- failure_class: winner.failure_class,
800
- evidence_count: winner.evidence.length,
801
- recorded_at: new Date().toISOString(),
802
- });
803
-
804
- if (winner.success) {
805
- appendEvent(projectRoot, sessionId, { type: 'WorkItemCompleted', run_id: runId, work_item_id: nodeId, payload: { mode: 'competitive', winner_agent_id: winnerAgentId } });
806
- } else {
807
- appendEvent(projectRoot, sessionId, { type: 'WorkItemBlocked', run_id: runId, work_item_id: nodeId, payload: { mode: 'competitive', failure_class: winner.failure_class, winner_agent_id: winnerAgentId } });
808
- }
809
-
810
- return winner;
811
- }
812
-
813
- // ─── Cooperative mode ────────────────────────────────────────────────────────
814
-
815
- async function runCooperative(
816
- graph: ExecutionGraph,
817
- opts: CoordinationOptions
818
- ): Promise<CoordinationResult> {
819
- if (opts.agents.length < 2) {
820
- throw new Error('Cooperative mode requires at least 2 agents');
821
- }
822
- ensureIsolatedAgents(opts.agents);
823
- const [planner, executor] = opts.agents;
824
- const { projectRoot, sessionId, runId } = opts;
825
- const handoffs: CooperativeHandoff[] = [];
826
- const workspaceRecords: WorkspaceMergeRecord[] = [];
827
-
828
- appendEvent(projectRoot, sessionId, {
829
- type: 'RunStarted',
830
- run_id: runId,
831
- payload: { mode: 'cooperative', planner: planner.id, executor: executor.id, isolation_level: 'isolated' },
832
- });
833
-
834
- const completed: string[] = [];
835
- const failed: string[] = [];
836
- const blocked: string[] = [];
837
-
838
- for (const wave of graph.waves) {
839
- for (const nodeId of wave.node_ids) {
840
- const node = graph.nodes.get(nodeId)!;
841
-
842
- const planAlloc = await planner.workspaceManager.allocate({
843
- work_item_id: nodeId,
844
- attempt_number: 1,
845
- strategy: node.workspace_strategy,
846
- mutation_scope: node.mutation_scope,
847
- });
848
- ensureGitWorktreeLease(planner, planAlloc);
849
- await planner.workspaceManager.dispose(planAlloc.workspace_id).catch(() => {});
850
-
851
- const handoff = buildHandoff({
852
- from_agent_id: planner.id,
853
- to_agent_id: executor.id,
854
- from_role: 'planner',
855
- to_role: 'executor',
856
- work_item_id: nodeId,
857
- context_pack_ref: null,
858
- });
859
- handoffs.push(handoff);
860
-
861
- appendEvent(projectRoot, sessionId, {
862
- type: 'AttemptStarted',
863
- run_id: runId,
864
- work_item_id: nodeId,
865
- payload: { mode: 'cooperative', handoff_id: handoff.handoff_id },
866
- });
867
-
868
- const execAlloc = await executor.workspaceManager.allocate({
869
- work_item_id: nodeId,
870
- attempt_number: 1,
871
- strategy: node.workspace_strategy,
872
- mutation_scope: node.mutation_scope,
873
- });
874
- ensureGitWorktreeLease(executor, execAlloc);
875
-
876
- let result: TaskResult;
877
- try {
878
- result = await executor.executor.execute(node, execAlloc, runId, 1);
879
- } catch (error) {
880
- result = { success: false, failure_class: 'env', evidence: [], output: String(error) };
881
- }
882
- const mergeRecord = createMergeRecord(executor, node, execAlloc, result);
883
- workspaceRecords.push(opts.applyWorkspaceMerges ? applyWorkspaceRecord(projectRoot, mergeRecord) : mergeRecord);
884
- await executor.workspaceManager.dispose(execAlloc.workspace_id).catch(() => {});
885
-
886
- if (result.success) {
887
- completed.push(nodeId);
888
- appendEvent(projectRoot, sessionId, { type: 'WorkItemCompleted', run_id: runId, work_item_id: nodeId, payload: { mode: 'cooperative' } });
889
- } else {
890
- failed.push(nodeId);
891
- appendEvent(projectRoot, sessionId, { type: 'WorkItemBlocked', run_id: runId, work_item_id: nodeId, payload: { mode: 'cooperative', failure_class: result.failure_class } });
892
- break;
893
- }
894
- }
895
- if (failed.length > 0) break;
896
- }
897
-
898
- const partitions = [Array.from(graph.nodes.keys()), Array.from(graph.nodes.keys())];
899
- const workspaceMergeReport = buildWorkspaceMergeReport(runId, workspaceRecords, blocked);
900
- const state = makeState(
901
- 'cooperative',
902
- runId,
903
- opts.agents,
904
- partitions,
905
- [
906
- { agent_id: planner.id, completed: [], failed: [], timed_out: false, reassigned_task_ids: [] },
907
- { agent_id: executor.id, completed, failed, timed_out: false, reassigned_task_ids: [] },
908
- ],
909
- completed,
910
- failed,
911
- blocked,
912
- [],
913
- [],
914
- workspaceMergeReport
915
- );
916
- persistMultiAgentArtifacts(projectRoot, runId, state, handoffs, [], workspaceMergeReport);
917
-
918
- appendEvent(projectRoot, sessionId, {
919
- type: 'RunCompleted',
920
- run_id: runId,
921
- payload: { mode: 'cooperative', completed: completed.length, failed: failed.length },
922
- });
923
-
924
- return {
925
- mode: 'cooperative',
926
- run_id: runId,
927
- completed,
928
- failed,
929
- blocked,
930
- agent_results: [
931
- { agent_id: planner.id, completed: [], failed: [] },
932
- { agent_id: executor.id, completed, failed },
933
- ],
934
- handoffs,
935
- arbitration_results: [],
936
- workspace_merge_report: workspaceMergeReport,
937
- state,
938
- summary: loadMultiAgentSummary(projectRoot, runId) || undefined,
939
- };
940
- }
941
-
942
- // ─── Public API ──────────────────────────────────────────────────────────────
943
-
944
- export class MultiAgentCoordinator {
945
- async run(graph: ExecutionGraph, opts: CoordinationOptions): Promise<CoordinationResult> {
946
- switch (opts.mode) {
947
- case 'parallel': return runParallel(graph, opts);
948
- case 'competitive': return runCompetitive(graph, opts);
949
- case 'cooperative': return runCooperative(graph, opts);
950
- default:
951
- throw new Error(`Unknown coordination mode: ${opts.mode}`);
952
- }
953
- }
954
- }
955
-
956
- export function multiAgentStatePath(projectRoot: string, runId: string): string {
957
- return path.join(projectRoot, '.oxe', 'runs', runId, 'multi-agent-state.json');
958
- }
959
-
960
- export function multiAgentSummaryPath(projectRoot: string, runId: string): string {
961
- return path.join(projectRoot, '.oxe', 'runs', runId, 'multi-agent-summary.json');
962
- }
963
-
964
- export function workspaceMergeReportPath(projectRoot: string, runId: string): string {
965
- return path.join(projectRoot, '.oxe', 'runs', runId, 'workspace-merge-report.json');
966
- }
967
-
968
- export function loadMultiAgentState(projectRoot: string, runId: string): MultiAgentStatusSnapshot | null {
969
- const statePath = multiAgentStatePath(projectRoot, runId);
970
- if (!fs.existsSync(statePath)) return null;
971
- try {
972
- return JSON.parse(fs.readFileSync(statePath, 'utf8')) as MultiAgentStatusSnapshot;
973
- } catch {
974
- return null;
975
- }
976
- }
977
-
978
- export function loadMultiAgentSummary(projectRoot: string, runId: string): MultiAgentOperationalSummary | null {
979
- const summaryPath = multiAgentSummaryPath(projectRoot, runId);
980
- if (!fs.existsSync(summaryPath)) return null;
981
- try {
982
- return JSON.parse(fs.readFileSync(summaryPath, 'utf8')) as MultiAgentOperationalSummary;
983
- } catch {
984
- return null;
985
- }
986
- }
987
-
988
- export function loadWorkspaceMergeReport(projectRoot: string, runId: string): WorkspaceMergeReport | null {
989
- const reportPath = workspaceMergeReportPath(projectRoot, runId);
990
- if (!fs.existsSync(reportPath)) return null;
991
- try {
992
- return JSON.parse(fs.readFileSync(reportPath, 'utf8')) as WorkspaceMergeReport;
993
- } catch {
994
- return null;
995
- }
996
- }
997
-
998
- // ─── Helpers ─────────────────────────────────────────────────────────────────
999
-
1000
- function subGraphFor(graph: ExecutionGraph, nodeIds: string[]): ExecutionGraph {
1001
- const ids = new Set(nodeIds);
1002
- const nodes = new Map([...graph.nodes].filter(([id]) => ids.has(id)));
1003
- const edges = graph.edges.filter((edge) => ids.has(edge.from) && ids.has(edge.to));
1004
- const waves = graph.waves
1005
- .map((wave) => ({
1006
- wave_number: wave.wave_number,
1007
- node_ids: wave.node_ids.filter((id) => ids.has(id)),
1008
- }))
1009
- .filter((wave) => wave.node_ids.length > 0);
1010
-
1011
- return {
1012
- nodes,
1013
- edges,
1014
- waves,
1015
- metadata: { ...graph.metadata, node_count: nodes.size, wave_count: waves.length },
1016
- };
1017
- }
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { appendEvent } from '../events/bus';
4
+ import type { ExecutionGraph, GraphNode } from '../compiler/graph-compiler';
5
+ import type { WorkspaceManager, WorkspaceRequest } from '../workspace/workspace-manager';
6
+ import type { WorkspaceLease, SnapshotRef } from '../models/workspace';
7
+ import type { TaskExecutor, TaskResult, SchedulerContext, RunResult } from './scheduler';
8
+ import { Scheduler } from './scheduler';
9
+ import { buildHandoff } from './agent-roles';
10
+ import type { CooperativeHandoff } from './agent-roles';
11
+ import { AgentRegistry } from './agent-registry';
12
+
13
+ export type CoordinationMode = 'parallel' | 'competitive' | 'cooperative';
14
+
15
+ export interface AgentSpec {
16
+ id: string;
17
+ executor: TaskExecutor;
18
+ workspaceManager: WorkspaceManager;
19
+ /** Task IDs this agent is responsible for (used in parallel mode) */
20
+ assignedTaskIds?: string[];
21
+ }
22
+
23
+ export interface CoordinationOptions {
24
+ mode: CoordinationMode;
25
+ agents: AgentSpec[];
26
+ projectRoot: string;
27
+ sessionId: string | null;
28
+ runId: string;
29
+ onEvent?: SchedulerContext['onEvent'];
30
+ heartbeatTimeoutMs?: number;
31
+ applyWorkspaceMerges?: boolean;
32
+ }
33
+
34
+ export interface ArbitrationRecord {
35
+ work_item_id: string;
36
+ mode: CoordinationMode;
37
+ winner_agent_id: string | null;
38
+ participant_agent_ids: string[];
39
+ success: boolean;
40
+ failure_class: TaskResult['failure_class'];
41
+ evidence_count: number;
42
+ recorded_at: string;
43
+ }
44
+
45
+ export interface MultiAgentOwnership {
46
+ work_item_id: string;
47
+ owner_agent_id: string;
48
+ }
49
+
50
+ export interface WorkspaceMergeRecord {
51
+ work_item_id: string;
52
+ agent_id: string;
53
+ workspace_id: string;
54
+ strategy: string;
55
+ isolation_level: 'shared' | 'isolated';
56
+ branch: string | null;
57
+ base_commit: string | null;
58
+ root_path: string | null;
59
+ mutation_scope: string[];
60
+ diff_paths: string[];
61
+ evidence_refs: string[];
62
+ evidence_count: number;
63
+ verify_status: 'pass' | 'fail' | 'partial';
64
+ status: 'ready' | 'merged' | 'blocked' | 'skipped';
65
+ blocker: string | null;
66
+ applied_paths: string[];
67
+ diff_summary: {
68
+ added: number;
69
+ modified: number;
70
+ missing: number;
71
+ paths: string[];
72
+ };
73
+ next_action: string | null;
74
+ recorded_at: string;
75
+ }
76
+
77
+ export interface WorkspaceMergeReport {
78
+ schema_version: 1;
79
+ run_id: string;
80
+ generated_at: string;
81
+ workspace_isolation: 'git_worktree';
82
+ merge_readiness: 'ready' | 'blocked' | 'partial';
83
+ arbitration_required: boolean;
84
+ blockers: string[];
85
+ records: WorkspaceMergeRecord[];
86
+ }
87
+
88
+ export interface MultiAgentStatusSnapshot {
89
+ run_id: string;
90
+ mode: CoordinationMode;
91
+ workspace_isolation_required: 'isolated';
92
+ workspace_isolation_enforced: boolean;
93
+ agent_count: number;
94
+ ownership: MultiAgentOwnership[];
95
+ completed: string[];
96
+ failed: string[];
97
+ blocked: string[];
98
+ agent_results: Array<{
99
+ agent_id: string;
100
+ isolation_level: 'shared' | 'isolated';
101
+ assigned_task_ids: string[];
102
+ completed: string[];
103
+ failed: string[];
104
+ timed_out: boolean;
105
+ reassigned_task_ids: string[];
106
+ }>;
107
+ worktrees: WorkspaceMergeRecord[];
108
+ workspace_merge: WorkspaceMergeReport;
109
+ merge_blockers: string[];
110
+ arbitration_required: boolean;
111
+ orphan_reassignments: Array<{ from_agent_id: string; to_agent_id: string; work_item_ids: string[] }>;
112
+ timed_out_agents: Array<{ agent_id: string; work_item_ids: string[]; detected_at: string }>;
113
+ updated_at: string;
114
+ }
115
+
116
+ export interface MultiAgentOperationalSummary {
117
+ run_id: string;
118
+ mode: CoordinationMode;
119
+ workspace_isolation_enforced: boolean;
120
+ agent_count: number;
121
+ completed_count: number;
122
+ failed_count: number;
123
+ blocked_count: number;
124
+ ownership_count: number;
125
+ handoff_count: number;
126
+ arbitration_count: number;
127
+ orphan_reassignment_count: number;
128
+ timeout_count: number;
129
+ participating_agents: string[];
130
+ workspace_isolation: 'git_worktree';
131
+ merge_readiness: WorkspaceMergeReport['merge_readiness'];
132
+ arbitration_required: boolean;
133
+ merge_blocker_count: number;
134
+ health: 'healthy' | 'degraded';
135
+ updated_at: string;
136
+ }
137
+
138
+ export interface CoordinationResult {
139
+ mode: CoordinationMode;
140
+ run_id: string;
141
+ completed: string[];
142
+ failed: string[];
143
+ blocked: string[];
144
+ agent_results: Array<{ agent_id: string; completed: string[]; failed: string[] }>;
145
+ handoffs?: CooperativeHandoff[];
146
+ arbitration_results?: ArbitrationRecord[];
147
+ workspace_merge_report?: WorkspaceMergeReport;
148
+ state?: MultiAgentStatusSnapshot;
149
+ summary?: MultiAgentOperationalSummary;
150
+ }
151
+
152
+ function ensureRunDir(projectRoot: string, runId: string): string {
153
+ const dir = path.join(projectRoot, '.oxe', 'runs', runId);
154
+ fs.mkdirSync(dir, { recursive: true });
155
+ return dir;
156
+ }
157
+
158
+ function persistMultiAgentArtifacts(
159
+ projectRoot: string,
160
+ runId: string,
161
+ state: MultiAgentStatusSnapshot,
162
+ handoffs: CooperativeHandoff[] = [],
163
+ arbitrationResults: ArbitrationRecord[] = [],
164
+ workspaceMergeReport: WorkspaceMergeReport = emptyWorkspaceMergeReport(runId)
165
+ ): void {
166
+ const runDir = ensureRunDir(projectRoot, runId);
167
+ fs.writeFileSync(path.join(runDir, 'multi-agent-state.json'), JSON.stringify(state, null, 2), 'utf8');
168
+ fs.writeFileSync(path.join(runDir, 'handoffs.json'), JSON.stringify(handoffs, null, 2), 'utf8');
169
+ fs.writeFileSync(path.join(runDir, 'arbitration-results.json'), JSON.stringify(arbitrationResults, null, 2), 'utf8');
170
+ fs.writeFileSync(path.join(runDir, 'workspace-merge-report.json'), JSON.stringify(workspaceMergeReport, null, 2), 'utf8');
171
+ const summary: MultiAgentOperationalSummary = {
172
+ run_id: state.run_id,
173
+ mode: state.mode,
174
+ workspace_isolation_enforced: state.workspace_isolation_enforced,
175
+ agent_count: state.agent_count,
176
+ completed_count: state.completed.length,
177
+ failed_count: state.failed.length,
178
+ blocked_count: state.blocked.length,
179
+ ownership_count: state.ownership.length,
180
+ handoff_count: handoffs.length,
181
+ arbitration_count: arbitrationResults.length,
182
+ orphan_reassignment_count: state.orphan_reassignments.length,
183
+ timeout_count: state.timed_out_agents.length,
184
+ participating_agents: state.agent_results.map((entry) => entry.agent_id),
185
+ workspace_isolation: 'git_worktree',
186
+ merge_readiness: workspaceMergeReport.merge_readiness,
187
+ arbitration_required: workspaceMergeReport.arbitration_required,
188
+ merge_blocker_count: workspaceMergeReport.blockers.length,
189
+ health: state.timed_out_agents.length > 0 || state.failed.length > 0 ? 'degraded' : 'healthy',
190
+ updated_at: state.updated_at,
191
+ };
192
+ fs.writeFileSync(path.join(runDir, 'multi-agent-summary.json'), JSON.stringify(summary, null, 2), 'utf8');
193
+ }
194
+
195
+ function ensureIsolatedAgents(agents: AgentSpec[]): void {
196
+ const shared = agents.filter((agent) => agent.workspaceManager.isolation_level !== 'isolated');
197
+ if (shared.length === 0) return;
198
+ const ids = shared.map((agent) => `${agent.id}:${agent.workspaceManager.isolation_level}`).join(', ');
199
+ throw new Error(`Multi-agent requires isolated workspaces. Invalid agents: ${ids}`);
200
+ }
201
+
202
+ function buildOwnership(agents: AgentSpec[], partitions: string[][]): MultiAgentOwnership[] {
203
+ const ownership: MultiAgentOwnership[] = [];
204
+ for (let idx = 0; idx < agents.length; idx += 1) {
205
+ for (const workItemId of partitions[idx] ?? []) {
206
+ ownership.push({
207
+ work_item_id: workItemId,
208
+ owner_agent_id: agents[idx].id,
209
+ });
210
+ }
211
+ }
212
+ return ownership;
213
+ }
214
+
215
+ function makeState(
216
+ mode: CoordinationMode,
217
+ runId: string,
218
+ agents: AgentSpec[],
219
+ partitions: string[][],
220
+ agentResults: Array<{ agent_id: string; completed: string[]; failed: string[]; timed_out: boolean; reassigned_task_ids: string[] }>,
221
+ completed: string[],
222
+ failed: string[],
223
+ blocked: string[],
224
+ orphanReassignments: Array<{ from_agent_id: string; to_agent_id: string; work_item_ids: string[] }>,
225
+ timedOutAgents: Array<{ agent_id: string; work_item_ids: string[]; detected_at: string }>,
226
+ workspaceMergeReport: WorkspaceMergeReport = emptyWorkspaceMergeReport(runId)
227
+ ): MultiAgentStatusSnapshot {
228
+ return {
229
+ run_id: runId,
230
+ mode,
231
+ workspace_isolation_required: 'isolated',
232
+ workspace_isolation_enforced: true,
233
+ agent_count: agents.length,
234
+ ownership: buildOwnership(agents, partitions),
235
+ completed,
236
+ failed,
237
+ blocked,
238
+ agent_results: agents.map((agent, idx) => {
239
+ const result = agentResults.find((entry) => entry.agent_id === agent.id);
240
+ return {
241
+ agent_id: agent.id,
242
+ isolation_level: agent.workspaceManager.isolation_level,
243
+ assigned_task_ids: partitions[idx] ?? agent.assignedTaskIds ?? [],
244
+ completed: result?.completed ?? [],
245
+ failed: result?.failed ?? [],
246
+ timed_out: Boolean(result?.timed_out),
247
+ reassigned_task_ids: result?.reassigned_task_ids ?? [],
248
+ };
249
+ }),
250
+ worktrees: workspaceMergeReport.records,
251
+ workspace_merge: workspaceMergeReport,
252
+ merge_blockers: workspaceMergeReport.blockers,
253
+ arbitration_required: workspaceMergeReport.arbitration_required,
254
+ orphan_reassignments: orphanReassignments,
255
+ timed_out_agents: timedOutAgents,
256
+ updated_at: new Date().toISOString(),
257
+ };
258
+ }
259
+
260
+ function emptyWorkspaceMergeReport(runId: string): WorkspaceMergeReport {
261
+ return {
262
+ schema_version: 1,
263
+ run_id: runId,
264
+ generated_at: new Date().toISOString(),
265
+ workspace_isolation: 'git_worktree',
266
+ merge_readiness: 'ready',
267
+ arbitration_required: false,
268
+ blockers: [],
269
+ records: [],
270
+ };
271
+ }
272
+
273
+ function ensureGitWorktreeLease(agent: AgentSpec, lease: WorkspaceLease): void {
274
+ if (lease.isolation_level !== 'isolated' || lease.strategy !== 'git_worktree') {
275
+ throw new Error(`Multi-agent real requires git_worktree isolated workspace. Agent ${agent.id} received ${lease.strategy}/${lease.isolation_level}.`);
276
+ }
277
+ }
278
+
279
+ function mutationScopeOf(node?: GraphNode): string[] {
280
+ return Array.isArray(node?.mutation_scope) ? node!.mutation_scope.map(String).filter(Boolean) : [];
281
+ }
282
+
283
+ function createMergeRecord(
284
+ agent: AgentSpec,
285
+ node: GraphNode,
286
+ lease: WorkspaceLease,
287
+ result?: TaskResult
288
+ ): WorkspaceMergeRecord {
289
+ const evidenceRefs = Array.isArray(result?.evidence) ? result!.evidence.map(String).filter(Boolean) : [];
290
+ const scope = mutationScopeOf(node);
291
+ return {
292
+ work_item_id: node.id,
293
+ agent_id: agent.id,
294
+ workspace_id: lease.workspace_id,
295
+ strategy: lease.strategy,
296
+ isolation_level: lease.isolation_level,
297
+ branch: lease.branch ?? null,
298
+ base_commit: lease.base_commit ?? null,
299
+ root_path: lease.root_path ?? null,
300
+ mutation_scope: scope,
301
+ diff_paths: scope,
302
+ evidence_refs: evidenceRefs,
303
+ evidence_count: evidenceRefs.length,
304
+ verify_status: result ? (result.success ? 'pass' : 'fail') : 'partial',
305
+ status: result ? (result.success ? 'ready' : 'blocked') : 'ready',
306
+ blocker: result && !result.success ? `verify_failed:${result.failure_class}` : null,
307
+ applied_paths: [],
308
+ diff_summary: { added: 0, modified: 0, missing: 0, paths: scope },
309
+ next_action: result && !result.success ? 'Corrija a falha de verify/evidence antes de aplicar merge do workspace.' : null,
310
+ recorded_at: new Date().toISOString(),
311
+ };
312
+ }
313
+
314
+ function enrichMergeRecordWithResult(record: WorkspaceMergeRecord, result?: TaskResult): WorkspaceMergeRecord {
315
+ if (!result) return record;
316
+ const evidenceRefs = Array.isArray(result.evidence) ? result.evidence.map(String).filter(Boolean) : [];
317
+ return {
318
+ ...record,
319
+ evidence_refs: evidenceRefs,
320
+ evidence_count: evidenceRefs.length,
321
+ verify_status: result.success ? 'pass' : 'fail',
322
+ status: result.success ? 'ready' : 'blocked',
323
+ blocker: result.success ? null : `verify_failed:${result.failure_class}`,
324
+ next_action: result.success ? null : 'Corrija a falha de verify/evidence antes de aplicar merge do workspace.',
325
+ recorded_at: new Date().toISOString(),
326
+ };
327
+ }
328
+
329
+ function buildWorkspaceMergeReport(
330
+ runId: string,
331
+ records: WorkspaceMergeRecord[],
332
+ extraBlockers: string[] = [],
333
+ arbitrationRequired = false
334
+ ): WorkspaceMergeReport {
335
+ const blockers = [
336
+ ...extraBlockers,
337
+ ...records.filter((record) => record.status === 'blocked' && record.blocker).map((record) => `${record.work_item_id}:${record.blocker}`),
338
+ ];
339
+ return {
340
+ schema_version: 1,
341
+ run_id: runId,
342
+ generated_at: new Date().toISOString(),
343
+ workspace_isolation: 'git_worktree',
344
+ merge_readiness: blockers.length > 0 ? 'blocked' : records.some((record) => record.status === 'ready') ? 'partial' : 'ready',
345
+ arbitration_required: arbitrationRequired,
346
+ blockers,
347
+ records,
348
+ };
349
+ }
350
+
351
+ function detectMutationConflicts(graph: ExecutionGraph, agents: AgentSpec[], partitions: string[][]): string[] {
352
+ const owners = new Map<string, string>();
353
+ const conflicts: string[] = [];
354
+ for (let idx = 0; idx < agents.length; idx += 1) {
355
+ for (const nodeId of partitions[idx] ?? []) {
356
+ const node = graph.nodes.get(nodeId);
357
+ for (const scope of mutationScopeOf(node)) {
358
+ const previous = owners.get(scope);
359
+ if (previous && previous !== agents[idx].id) {
360
+ conflicts.push(`mutation_scope_overlap:${scope}:${previous}:${agents[idx].id}`);
361
+ } else {
362
+ owners.set(scope, agents[idx].id);
363
+ }
364
+ }
365
+ }
366
+ }
367
+ return conflicts;
368
+ }
369
+
370
+ function applyWorkspaceRecord(projectRoot: string, record: WorkspaceMergeRecord): WorkspaceMergeRecord {
371
+ if (!record.root_path || record.status !== 'ready') return record;
372
+ const appliedPaths: string[] = [];
373
+ const summary = { added: 0, modified: 0, missing: 0, paths: [...record.mutation_scope] };
374
+ for (const relativePath of record.mutation_scope) {
375
+ const source = path.join(record.root_path, relativePath);
376
+ const target = path.join(projectRoot, relativePath);
377
+ if (!fs.existsSync(source) || fs.statSync(source).isDirectory()) {
378
+ summary.missing += 1;
379
+ return {
380
+ ...record,
381
+ status: 'blocked',
382
+ blocker: `missing_output:${relativePath}`,
383
+ diff_summary: summary,
384
+ next_action: `Materialize o arquivo esperado ${relativePath} no worktree do agente antes do merge.`,
385
+ };
386
+ }
387
+ if (fs.existsSync(target)) summary.modified += 1;
388
+ else summary.added += 1;
389
+ fs.mkdirSync(path.dirname(target), { recursive: true });
390
+ fs.copyFileSync(source, target);
391
+ appliedPaths.push(relativePath);
392
+ }
393
+ return {
394
+ ...record,
395
+ status: 'merged',
396
+ blocker: null,
397
+ applied_paths: appliedPaths,
398
+ diff_summary: summary,
399
+ next_action: null,
400
+ };
401
+ }
402
+
403
+ function createTrackingWorkspaceManager(
404
+ base: WorkspaceManager,
405
+ agent: AgentSpec,
406
+ graph: ExecutionGraph,
407
+ records: WorkspaceMergeRecord[]
408
+ ): WorkspaceManager & { disposeDeferred(): Promise<void> } {
409
+ const leases = new Map<string, WorkspaceLease>();
410
+ return {
411
+ isolation_level: base.isolation_level,
412
+ allocate: async (req: WorkspaceRequest) => {
413
+ const lease = await base.allocate(req);
414
+ ensureGitWorktreeLease(agent, lease);
415
+ leases.set(lease.workspace_id, lease);
416
+ const node = graph.nodes.get(req.work_item_id);
417
+ if (node) records.push(createMergeRecord(agent, node, lease));
418
+ return lease;
419
+ },
420
+ snapshot: (id: string): Promise<SnapshotRef> => base.snapshot(id),
421
+ reset: (id: string, snapRef: SnapshotRef): Promise<void> => base.reset(id, snapRef),
422
+ dispose: async () => {
423
+ // Scheduler calls dispose before the coordinator can reconcile diffs.
424
+ // Defer real cleanup until the merge report has been produced.
425
+ },
426
+ disposeDeferred: async () => {
427
+ await Promise.all([...leases.keys()].map((id) => base.dispose(id).catch(() => {})));
428
+ leases.clear();
429
+ },
430
+ };
431
+ }
432
+
433
+ async function runGraphForAgent(
434
+ graph: ExecutionGraph,
435
+ nodeIds: string[],
436
+ agent: AgentSpec,
437
+ idx: number,
438
+ opts: CoordinationOptions,
439
+ heartbeatTimeoutMs: number | null
440
+ ): Promise<{
441
+ agent_id: string;
442
+ completed: string[];
443
+ failed: string[];
444
+ timed_out: boolean;
445
+ assigned_task_ids: string[];
446
+ reassigned_task_ids: string[];
447
+ workspace_records: WorkspaceMergeRecord[];
448
+ cleanup: () => Promise<void>;
449
+ }> {
450
+ const subGraph = subGraphFor(graph, nodeIds);
451
+ const workspaceRecords: WorkspaceMergeRecord[] = [];
452
+ if (subGraph.nodes.size === 0) {
453
+ return {
454
+ agent_id: agent.id,
455
+ completed: [],
456
+ failed: [],
457
+ timed_out: false,
458
+ assigned_task_ids: nodeIds,
459
+ reassigned_task_ids: [],
460
+ workspace_records: workspaceRecords,
461
+ cleanup: async () => {},
462
+ };
463
+ }
464
+ const trackingWorkspaceManager = createTrackingWorkspaceManager(agent.workspaceManager, agent, graph, workspaceRecords);
465
+ const taskResults = new Map<string, TaskResult>();
466
+ const trackingExecutor: TaskExecutor = {
467
+ execute: async (node, lease, runId, attemptNumber) => {
468
+ const result = await agent.executor.execute(node, lease, runId, attemptNumber);
469
+ taskResults.set(node.id, result);
470
+ return result;
471
+ },
472
+ };
473
+ const ctx: SchedulerContext = {
474
+ projectRoot: opts.projectRoot,
475
+ sessionId: opts.sessionId,
476
+ runId: `${opts.runId}-agent${idx}`,
477
+ executor: trackingExecutor,
478
+ workspaceManager: trackingWorkspaceManager,
479
+ onEvent: opts.onEvent,
480
+ };
481
+ const scheduler = new Scheduler();
482
+ const work = scheduler.run(subGraph, ctx);
483
+ if (!heartbeatTimeoutMs || heartbeatTimeoutMs <= 0) {
484
+ const result = await work;
485
+ const reconciledRecords = workspaceRecords.map((record) => enrichMergeRecordWithResult(record, taskResults.get(record.work_item_id)));
486
+ return {
487
+ agent_id: agent.id,
488
+ completed: result.completed,
489
+ failed: result.failed,
490
+ timed_out: false,
491
+ assigned_task_ids: nodeIds,
492
+ reassigned_task_ids: [],
493
+ workspace_records: reconciledRecords,
494
+ cleanup: () => trackingWorkspaceManager.disposeDeferred(),
495
+ };
496
+ }
497
+ let timer: NodeJS.Timeout | null = null;
498
+ const raced: { type: 'result'; result: RunResult } | { type: 'timeout' } = await Promise.race([
499
+ work.then((result) => ({ type: 'result' as const, result })),
500
+ new Promise<{ type: 'timeout' }>((resolve) => {
501
+ timer = setTimeout(() => resolve({ type: 'timeout' }), heartbeatTimeoutMs);
502
+ }),
503
+ ]);
504
+ if (timer) clearTimeout(timer);
505
+ if (raced && raced.type === 'timeout') {
506
+ return {
507
+ agent_id: agent.id,
508
+ completed: [],
509
+ failed: [],
510
+ timed_out: true,
511
+ assigned_task_ids: nodeIds,
512
+ reassigned_task_ids: [],
513
+ workspace_records: workspaceRecords,
514
+ cleanup: () => trackingWorkspaceManager.disposeDeferred(),
515
+ };
516
+ }
517
+ const result = raced.result;
518
+ const reconciledRecords = workspaceRecords.map((record) => enrichMergeRecordWithResult(record, taskResults.get(record.work_item_id)));
519
+ return {
520
+ agent_id: agent.id,
521
+ completed: result.completed,
522
+ failed: result.failed,
523
+ timed_out: false,
524
+ assigned_task_ids: nodeIds,
525
+ reassigned_task_ids: [],
526
+ workspace_records: reconciledRecords,
527
+ cleanup: () => trackingWorkspaceManager.disposeDeferred(),
528
+ };
529
+ }
530
+
531
+ // ─── Parallel mode ───────────────────────────────────────────────────────────
532
+
533
+ async function runParallel(
534
+ graph: ExecutionGraph,
535
+ opts: CoordinationOptions
536
+ ): Promise<CoordinationResult> {
537
+ const { agents, projectRoot, sessionId, runId } = opts;
538
+ ensureIsolatedAgents(agents);
539
+ const heartbeatTimeoutMs = opts.heartbeatTimeoutMs ?? null;
540
+
541
+ const partitions = agents.map((agent) => [...(agent.assignedTaskIds ?? [])]);
542
+ if (partitions.every((partition) => partition.length === 0)) {
543
+ const allIds = [...graph.nodes.keys()];
544
+ allIds.forEach((id, index) => {
545
+ partitions[index % agents.length].push(id);
546
+ });
547
+ }
548
+ const mutationConflicts = detectMutationConflicts(graph, agents, partitions);
549
+ if (mutationConflicts.length > 0) {
550
+ const blocked = mutationConflicts;
551
+ const workspaceMergeReport = buildWorkspaceMergeReport(runId, [], blocked);
552
+ const state = makeState('parallel', runId, agents, partitions, [], [], [], blocked, [], [], workspaceMergeReport);
553
+ persistMultiAgentArtifacts(projectRoot, runId, state, [], [], workspaceMergeReport);
554
+ appendEvent(projectRoot, sessionId, {
555
+ type: 'WorkItemBlocked',
556
+ run_id: runId,
557
+ payload: { mode: 'parallel', blockers: blocked },
558
+ });
559
+ return {
560
+ mode: 'parallel',
561
+ run_id: runId,
562
+ completed: [],
563
+ failed: [],
564
+ blocked,
565
+ agent_results: [],
566
+ arbitration_results: [],
567
+ workspace_merge_report: workspaceMergeReport,
568
+ state,
569
+ summary: loadMultiAgentSummary(projectRoot, runId) || undefined,
570
+ };
571
+ }
572
+ const registry = new AgentRegistry(heartbeatTimeoutMs == null ? 30_000 : heartbeatTimeoutMs);
573
+ agents.forEach((agent, idx) => {
574
+ registry.register(agent.id, agent.executor, agent.workspaceManager, partitions[idx] ?? []);
575
+ });
576
+
577
+ appendEvent(projectRoot, sessionId, {
578
+ type: 'RunStarted',
579
+ run_id: runId,
580
+ payload: { mode: 'parallel', agent_count: agents.length, isolation_level: 'isolated' },
581
+ });
582
+
583
+ const initialResults = await Promise.all(
584
+ agents.map(async (agent, idx) => {
585
+ registry.beat(agent.id, partitions[idx][0] || null);
586
+ const result = await runGraphForAgent(graph, partitions[idx], agent, idx, opts, heartbeatTimeoutMs);
587
+ registry.setStatus(agent.id, result.timed_out ? 'timeout' : 'idle');
588
+ return result;
589
+ })
590
+ );
591
+
592
+ const timedOutAgents = [];
593
+ const blocked: string[] = [];
594
+ const orphanReassignments: Array<{ from_agent_id: string; to_agent_id: string; work_item_ids: string[] }> = [];
595
+ const agentResults = initialResults.map((entry) => ({
596
+ ...entry,
597
+ reassigned_task_ids: entry.reassigned_task_ids || [],
598
+ }));
599
+ const liveAgents = agentResults.filter((entry) => !entry.timed_out);
600
+ for (const timedOut of agentResults.filter((entry) => entry.timed_out)) {
601
+ timedOutAgents.push({
602
+ agent_id: timedOut.agent_id,
603
+ work_item_ids: timedOut.assigned_task_ids,
604
+ detected_at: new Date().toISOString(),
605
+ });
606
+ const fallback = liveAgents.find((entry) => entry.agent_id !== timedOut.agent_id);
607
+ if (!fallback || timedOut.assigned_task_ids.length === 0) continue;
608
+ const fallbackIdx = agents.findIndex((agent) => agent.id === fallback.agent_id);
609
+ const timeoutIdx = agents.findIndex((agent) => agent.id === timedOut.agent_id);
610
+ const rerun = await runGraphForAgent(graph, timedOut.assigned_task_ids, agents[fallbackIdx], fallbackIdx, opts, null);
611
+ fallback.completed.push(...rerun.completed);
612
+ fallback.failed.push(...rerun.failed);
613
+ fallback.workspace_records.push(...rerun.workspace_records);
614
+ fallback.reassigned_task_ids.push(...timedOut.assigned_task_ids);
615
+ const previousCleanup = fallback.cleanup;
616
+ fallback.cleanup = async () => {
617
+ await previousCleanup?.();
618
+ await rerun.cleanup?.();
619
+ };
620
+ partitions[fallbackIdx] = [...partitions[fallbackIdx], ...timedOut.assigned_task_ids];
621
+ partitions[timeoutIdx] = [];
622
+ orphanReassignments.push({
623
+ from_agent_id: timedOut.agent_id,
624
+ to_agent_id: fallback.agent_id,
625
+ work_item_ids: timedOut.assigned_task_ids,
626
+ });
627
+ }
628
+
629
+ const completed = Array.from(new Set(agentResults.flatMap((result) => result.completed)));
630
+ const failed = Array.from(new Set(agentResults.flatMap((result) => result.failed)));
631
+ const rawRecords = agentResults.flatMap((result) => result.workspace_records || []);
632
+ const mergedRecords = opts.applyWorkspaceMerges
633
+ ? rawRecords.map((record) => applyWorkspaceRecord(projectRoot, record))
634
+ : rawRecords;
635
+ await Promise.all(agentResults.map((result) => result.cleanup?.().catch(() => {})));
636
+ const workspaceMergeReport = buildWorkspaceMergeReport(runId, mergedRecords, blocked);
637
+ const state = makeState('parallel', runId, agents, partitions, agentResults, completed, failed, blocked, orphanReassignments, timedOutAgents, workspaceMergeReport);
638
+ persistMultiAgentArtifacts(projectRoot, runId, state, [], [], workspaceMergeReport);
639
+
640
+ appendEvent(projectRoot, sessionId, {
641
+ type: 'RunCompleted',
642
+ run_id: runId,
643
+ payload: { mode: 'parallel', completed: completed.length, failed: failed.length },
644
+ });
645
+
646
+ return {
647
+ mode: 'parallel',
648
+ run_id: runId,
649
+ completed,
650
+ failed,
651
+ blocked,
652
+ agent_results: agentResults,
653
+ arbitration_results: [],
654
+ workspace_merge_report: workspaceMergeReport,
655
+ state,
656
+ summary: loadMultiAgentSummary(projectRoot, runId) || undefined,
657
+ };
658
+ }
659
+
660
+ // ─── Competitive mode ────────────────────────────────────────────────────────
661
+
662
+ async function runCompetitive(
663
+ graph: ExecutionGraph,
664
+ opts: CoordinationOptions
665
+ ): Promise<CoordinationResult> {
666
+ if (opts.agents.length < 2) {
667
+ throw new Error('Competitive mode requires at least 2 agents');
668
+ }
669
+ ensureIsolatedAgents(opts.agents);
670
+ const [agentA, agentB] = opts.agents;
671
+ const { projectRoot, sessionId, runId } = opts;
672
+
673
+ appendEvent(projectRoot, sessionId, {
674
+ type: 'RunStarted',
675
+ run_id: runId,
676
+ payload: { mode: 'competitive', isolation_level: 'isolated' },
677
+ });
678
+
679
+ const completed: string[] = [];
680
+ const failed: string[] = [];
681
+ const blocked: string[] = [];
682
+ const arbitrationResults: ArbitrationRecord[] = [];
683
+ const workspaceRecords: WorkspaceMergeRecord[] = [];
684
+
685
+ for (const wave of graph.waves) {
686
+ for (const nodeId of wave.node_ids) {
687
+ const node = graph.nodes.get(nodeId)!;
688
+ const result = await competeTwoAgents(nodeId, node, agentA, agentB, opts, arbitrationResults, workspaceRecords);
689
+ if (result.success) completed.push(nodeId);
690
+ else failed.push(nodeId);
691
+ if (failed.length > 0) break;
692
+ }
693
+ if (failed.length > 0) break;
694
+ }
695
+
696
+ const partitions = [Array.from(graph.nodes.keys()), Array.from(graph.nodes.keys())];
697
+ const workspaceMergeReport = buildWorkspaceMergeReport(runId, workspaceRecords, blocked, true);
698
+ const state = makeState(
699
+ 'competitive',
700
+ runId,
701
+ opts.agents,
702
+ partitions,
703
+ [
704
+ { agent_id: agentA.id, completed, failed, timed_out: false, reassigned_task_ids: [] },
705
+ { agent_id: agentB.id, completed: [], failed: [], timed_out: false, reassigned_task_ids: [] },
706
+ ],
707
+ completed,
708
+ failed,
709
+ blocked,
710
+ [],
711
+ [],
712
+ workspaceMergeReport
713
+ );
714
+ persistMultiAgentArtifacts(projectRoot, runId, state, [], arbitrationResults, workspaceMergeReport);
715
+
716
+ appendEvent(projectRoot, sessionId, {
717
+ type: 'RunCompleted',
718
+ run_id: runId,
719
+ payload: { mode: 'competitive', completed: completed.length },
720
+ });
721
+
722
+ return {
723
+ mode: 'competitive',
724
+ run_id: runId,
725
+ completed,
726
+ failed,
727
+ blocked,
728
+ agent_results: [
729
+ { agent_id: agentA.id, completed, failed },
730
+ { agent_id: agentB.id, completed: [], failed: [] },
731
+ ],
732
+ arbitration_results: arbitrationResults,
733
+ workspace_merge_report: workspaceMergeReport,
734
+ state,
735
+ summary: loadMultiAgentSummary(projectRoot, runId) || undefined,
736
+ };
737
+ }
738
+
739
+ async function competeTwoAgents(
740
+ nodeId: string,
741
+ node: GraphNode,
742
+ agentA: AgentSpec,
743
+ agentB: AgentSpec,
744
+ opts: CoordinationOptions,
745
+ arbitrationResults: ArbitrationRecord[],
746
+ workspaceRecords: WorkspaceMergeRecord[]
747
+ ): Promise<TaskResult> {
748
+ const { projectRoot, sessionId, runId } = opts;
749
+
750
+ const allocA = await agentA.workspaceManager.allocate({
751
+ work_item_id: nodeId, attempt_number: 1, strategy: node.workspace_strategy, mutation_scope: node.mutation_scope,
752
+ });
753
+ ensureGitWorktreeLease(agentA, allocA);
754
+ const allocB = await agentB.workspaceManager.allocate({
755
+ work_item_id: nodeId, attempt_number: 1, strategy: node.workspace_strategy, mutation_scope: node.mutation_scope,
756
+ });
757
+ ensureGitWorktreeLease(agentB, allocB);
758
+
759
+ appendEvent(projectRoot, sessionId, {
760
+ type: 'AttemptStarted',
761
+ run_id: runId,
762
+ work_item_id: nodeId,
763
+ payload: { mode: 'competitive', agents: [agentA.id, agentB.id] },
764
+ });
765
+
766
+ const [resultA, resultB] = await Promise.all([
767
+ agentA.executor.execute(node, allocA, runId, 1).catch((error) => ({
768
+ success: false, failure_class: 'env' as const, evidence: [], output: String(error),
769
+ })),
770
+ agentB.executor.execute(node, allocB, runId, 1).catch((error) => ({
771
+ success: false, failure_class: 'env' as const, evidence: [], output: String(error),
772
+ })),
773
+ ]);
774
+
775
+ const candidates = [
776
+ { agent: agentA, alloc: allocA, result: resultA },
777
+ { agent: agentB, alloc: allocB, result: resultB },
778
+ ].sort((left, right) => {
779
+ const leftScore = (left.result.success ? 10_000 : 0) + left.result.evidence.length * 100 - String(left.result.output || '').length;
780
+ const rightScore = (right.result.success ? 10_000 : 0) + right.result.evidence.length * 100 - String(right.result.output || '').length;
781
+ return rightScore - leftScore;
782
+ });
783
+ const winnerCandidate = candidates[0];
784
+ const winner = winnerCandidate.result;
785
+ const winnerAgentId = winnerCandidate.agent.id;
786
+ const winnerRecord = createMergeRecord(winnerCandidate.agent, node, winnerCandidate.alloc, winner);
787
+ workspaceRecords.push(opts.applyWorkspaceMerges ? applyWorkspaceRecord(projectRoot, winnerRecord) : winnerRecord);
788
+
789
+ await Promise.all([
790
+ agentA.workspaceManager.dispose(allocA.workspace_id).catch(() => {}),
791
+ agentB.workspaceManager.dispose(allocB.workspace_id).catch(() => {}),
792
+ ]);
793
+ arbitrationResults.push({
794
+ work_item_id: nodeId,
795
+ mode: 'competitive',
796
+ winner_agent_id: winnerAgentId,
797
+ participant_agent_ids: [agentA.id, agentB.id],
798
+ success: winner.success,
799
+ failure_class: winner.failure_class,
800
+ evidence_count: winner.evidence.length,
801
+ recorded_at: new Date().toISOString(),
802
+ });
803
+
804
+ if (winner.success) {
805
+ appendEvent(projectRoot, sessionId, { type: 'WorkItemCompleted', run_id: runId, work_item_id: nodeId, payload: { mode: 'competitive', winner_agent_id: winnerAgentId } });
806
+ } else {
807
+ appendEvent(projectRoot, sessionId, { type: 'WorkItemBlocked', run_id: runId, work_item_id: nodeId, payload: { mode: 'competitive', failure_class: winner.failure_class, winner_agent_id: winnerAgentId } });
808
+ }
809
+
810
+ return winner;
811
+ }
812
+
813
+ // ─── Cooperative mode ────────────────────────────────────────────────────────
814
+
815
+ async function runCooperative(
816
+ graph: ExecutionGraph,
817
+ opts: CoordinationOptions
818
+ ): Promise<CoordinationResult> {
819
+ if (opts.agents.length < 2) {
820
+ throw new Error('Cooperative mode requires at least 2 agents');
821
+ }
822
+ ensureIsolatedAgents(opts.agents);
823
+ const [planner, executor] = opts.agents;
824
+ const { projectRoot, sessionId, runId } = opts;
825
+ const handoffs: CooperativeHandoff[] = [];
826
+ const workspaceRecords: WorkspaceMergeRecord[] = [];
827
+
828
+ appendEvent(projectRoot, sessionId, {
829
+ type: 'RunStarted',
830
+ run_id: runId,
831
+ payload: { mode: 'cooperative', planner: planner.id, executor: executor.id, isolation_level: 'isolated' },
832
+ });
833
+
834
+ const completed: string[] = [];
835
+ const failed: string[] = [];
836
+ const blocked: string[] = [];
837
+
838
+ for (const wave of graph.waves) {
839
+ for (const nodeId of wave.node_ids) {
840
+ const node = graph.nodes.get(nodeId)!;
841
+
842
+ const planAlloc = await planner.workspaceManager.allocate({
843
+ work_item_id: nodeId,
844
+ attempt_number: 1,
845
+ strategy: node.workspace_strategy,
846
+ mutation_scope: node.mutation_scope,
847
+ });
848
+ ensureGitWorktreeLease(planner, planAlloc);
849
+ await planner.workspaceManager.dispose(planAlloc.workspace_id).catch(() => {});
850
+
851
+ const handoff = buildHandoff({
852
+ from_agent_id: planner.id,
853
+ to_agent_id: executor.id,
854
+ from_role: 'planner',
855
+ to_role: 'executor',
856
+ work_item_id: nodeId,
857
+ context_pack_ref: null,
858
+ });
859
+ handoffs.push(handoff);
860
+
861
+ appendEvent(projectRoot, sessionId, {
862
+ type: 'AttemptStarted',
863
+ run_id: runId,
864
+ work_item_id: nodeId,
865
+ payload: { mode: 'cooperative', handoff_id: handoff.handoff_id },
866
+ });
867
+
868
+ const execAlloc = await executor.workspaceManager.allocate({
869
+ work_item_id: nodeId,
870
+ attempt_number: 1,
871
+ strategy: node.workspace_strategy,
872
+ mutation_scope: node.mutation_scope,
873
+ });
874
+ ensureGitWorktreeLease(executor, execAlloc);
875
+
876
+ let result: TaskResult;
877
+ try {
878
+ result = await executor.executor.execute(node, execAlloc, runId, 1);
879
+ } catch (error) {
880
+ result = { success: false, failure_class: 'env', evidence: [], output: String(error) };
881
+ }
882
+ const mergeRecord = createMergeRecord(executor, node, execAlloc, result);
883
+ workspaceRecords.push(opts.applyWorkspaceMerges ? applyWorkspaceRecord(projectRoot, mergeRecord) : mergeRecord);
884
+ await executor.workspaceManager.dispose(execAlloc.workspace_id).catch(() => {});
885
+
886
+ if (result.success) {
887
+ completed.push(nodeId);
888
+ appendEvent(projectRoot, sessionId, { type: 'WorkItemCompleted', run_id: runId, work_item_id: nodeId, payload: { mode: 'cooperative' } });
889
+ } else {
890
+ failed.push(nodeId);
891
+ appendEvent(projectRoot, sessionId, { type: 'WorkItemBlocked', run_id: runId, work_item_id: nodeId, payload: { mode: 'cooperative', failure_class: result.failure_class } });
892
+ break;
893
+ }
894
+ }
895
+ if (failed.length > 0) break;
896
+ }
897
+
898
+ const partitions = [Array.from(graph.nodes.keys()), Array.from(graph.nodes.keys())];
899
+ const workspaceMergeReport = buildWorkspaceMergeReport(runId, workspaceRecords, blocked);
900
+ const state = makeState(
901
+ 'cooperative',
902
+ runId,
903
+ opts.agents,
904
+ partitions,
905
+ [
906
+ { agent_id: planner.id, completed: [], failed: [], timed_out: false, reassigned_task_ids: [] },
907
+ { agent_id: executor.id, completed, failed, timed_out: false, reassigned_task_ids: [] },
908
+ ],
909
+ completed,
910
+ failed,
911
+ blocked,
912
+ [],
913
+ [],
914
+ workspaceMergeReport
915
+ );
916
+ persistMultiAgentArtifacts(projectRoot, runId, state, handoffs, [], workspaceMergeReport);
917
+
918
+ appendEvent(projectRoot, sessionId, {
919
+ type: 'RunCompleted',
920
+ run_id: runId,
921
+ payload: { mode: 'cooperative', completed: completed.length, failed: failed.length },
922
+ });
923
+
924
+ return {
925
+ mode: 'cooperative',
926
+ run_id: runId,
927
+ completed,
928
+ failed,
929
+ blocked,
930
+ agent_results: [
931
+ { agent_id: planner.id, completed: [], failed: [] },
932
+ { agent_id: executor.id, completed, failed },
933
+ ],
934
+ handoffs,
935
+ arbitration_results: [],
936
+ workspace_merge_report: workspaceMergeReport,
937
+ state,
938
+ summary: loadMultiAgentSummary(projectRoot, runId) || undefined,
939
+ };
940
+ }
941
+
942
+ // ─── Public API ──────────────────────────────────────────────────────────────
943
+
944
+ export class MultiAgentCoordinator {
945
+ async run(graph: ExecutionGraph, opts: CoordinationOptions): Promise<CoordinationResult> {
946
+ switch (opts.mode) {
947
+ case 'parallel': return runParallel(graph, opts);
948
+ case 'competitive': return runCompetitive(graph, opts);
949
+ case 'cooperative': return runCooperative(graph, opts);
950
+ default:
951
+ throw new Error(`Unknown coordination mode: ${opts.mode}`);
952
+ }
953
+ }
954
+ }
955
+
956
+ export function multiAgentStatePath(projectRoot: string, runId: string): string {
957
+ return path.join(projectRoot, '.oxe', 'runs', runId, 'multi-agent-state.json');
958
+ }
959
+
960
+ export function multiAgentSummaryPath(projectRoot: string, runId: string): string {
961
+ return path.join(projectRoot, '.oxe', 'runs', runId, 'multi-agent-summary.json');
962
+ }
963
+
964
+ export function workspaceMergeReportPath(projectRoot: string, runId: string): string {
965
+ return path.join(projectRoot, '.oxe', 'runs', runId, 'workspace-merge-report.json');
966
+ }
967
+
968
+ export function loadMultiAgentState(projectRoot: string, runId: string): MultiAgentStatusSnapshot | null {
969
+ const statePath = multiAgentStatePath(projectRoot, runId);
970
+ if (!fs.existsSync(statePath)) return null;
971
+ try {
972
+ return JSON.parse(fs.readFileSync(statePath, 'utf8')) as MultiAgentStatusSnapshot;
973
+ } catch {
974
+ return null;
975
+ }
976
+ }
977
+
978
+ export function loadMultiAgentSummary(projectRoot: string, runId: string): MultiAgentOperationalSummary | null {
979
+ const summaryPath = multiAgentSummaryPath(projectRoot, runId);
980
+ if (!fs.existsSync(summaryPath)) return null;
981
+ try {
982
+ return JSON.parse(fs.readFileSync(summaryPath, 'utf8')) as MultiAgentOperationalSummary;
983
+ } catch {
984
+ return null;
985
+ }
986
+ }
987
+
988
+ export function loadWorkspaceMergeReport(projectRoot: string, runId: string): WorkspaceMergeReport | null {
989
+ const reportPath = workspaceMergeReportPath(projectRoot, runId);
990
+ if (!fs.existsSync(reportPath)) return null;
991
+ try {
992
+ return JSON.parse(fs.readFileSync(reportPath, 'utf8')) as WorkspaceMergeReport;
993
+ } catch {
994
+ return null;
995
+ }
996
+ }
997
+
998
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
999
+
1000
+ function subGraphFor(graph: ExecutionGraph, nodeIds: string[]): ExecutionGraph {
1001
+ const ids = new Set(nodeIds);
1002
+ const nodes = new Map([...graph.nodes].filter(([id]) => ids.has(id)));
1003
+ const edges = graph.edges.filter((edge) => ids.has(edge.from) && ids.has(edge.to));
1004
+ const waves = graph.waves
1005
+ .map((wave) => ({
1006
+ wave_number: wave.wave_number,
1007
+ node_ids: wave.node_ids.filter((id) => ids.has(id)),
1008
+ }))
1009
+ .filter((wave) => wave.node_ids.length > 0);
1010
+
1011
+ return {
1012
+ nodes,
1013
+ edges,
1014
+ waves,
1015
+ metadata: { ...graph.metadata, node_count: nodes.size, wave_count: waves.length },
1016
+ };
1017
+ }