oxe-cc 1.0.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (322) hide show
  1. package/.cursor/commands/oxe-ask.md +3 -3
  2. package/.cursor/commands/oxe-capabilities.md +3 -3
  3. package/.cursor/commands/oxe-checkpoint.md +3 -3
  4. package/.cursor/commands/oxe-compact.md +3 -3
  5. package/.cursor/commands/oxe-dashboard.md +3 -3
  6. package/.cursor/commands/oxe-debug.md +3 -3
  7. package/.cursor/commands/oxe-discuss.md +3 -3
  8. package/.cursor/commands/oxe-execute.md +7 -4
  9. package/.cursor/commands/oxe-forensics.md +3 -3
  10. package/.cursor/commands/oxe-help.md +3 -3
  11. package/.cursor/commands/oxe-loop.md +3 -3
  12. package/.cursor/commands/oxe-milestone.md +3 -3
  13. package/.cursor/commands/oxe-next.md +3 -3
  14. package/.cursor/commands/oxe-obs.md +3 -3
  15. package/.cursor/commands/oxe-plan-agent.md +3 -3
  16. package/.cursor/commands/oxe-plan.md +3 -3
  17. package/.cursor/commands/oxe-project.md +3 -3
  18. package/.cursor/commands/oxe-quick.md +3 -3
  19. package/.cursor/commands/oxe-research.md +3 -3
  20. package/.cursor/commands/oxe-retro.md +3 -3
  21. package/.cursor/commands/oxe-review-pr.md +3 -3
  22. package/.cursor/commands/oxe-route.md +3 -3
  23. package/.cursor/commands/oxe-scan.md +3 -3
  24. package/.cursor/commands/oxe-security.md +3 -3
  25. package/.cursor/commands/oxe-session.md +4 -4
  26. package/.cursor/commands/oxe-ship.md +45 -0
  27. package/.cursor/commands/oxe-skill.md +3 -3
  28. package/.cursor/commands/oxe-spec.md +3 -3
  29. package/.cursor/commands/oxe-ui-review.md +3 -3
  30. package/.cursor/commands/oxe-ui-spec.md +3 -3
  31. package/.cursor/commands/oxe-update.md +3 -3
  32. package/.cursor/commands/oxe-validate-gaps.md +3 -3
  33. package/.cursor/commands/oxe-verify.md +6 -3
  34. package/.cursor/commands/oxe-workstream.md +3 -3
  35. package/.cursor/commands/oxe.md +6 -6
  36. package/.github/copilot-instructions.md +94 -4
  37. package/.github/prompts/oxe-ask.prompt.md +3 -3
  38. package/.github/prompts/oxe-capabilities.prompt.md +3 -3
  39. package/.github/prompts/oxe-checkpoint.prompt.md +3 -3
  40. package/.github/prompts/oxe-compact.prompt.md +3 -3
  41. package/.github/prompts/oxe-dashboard.prompt.md +3 -3
  42. package/.github/prompts/oxe-debug.prompt.md +3 -3
  43. package/.github/prompts/oxe-discuss.prompt.md +3 -3
  44. package/.github/prompts/oxe-execute.prompt.md +7 -4
  45. package/.github/prompts/oxe-forensics.prompt.md +3 -3
  46. package/.github/prompts/oxe-help.prompt.md +3 -3
  47. package/.github/prompts/oxe-loop.prompt.md +3 -3
  48. package/.github/prompts/oxe-milestone.prompt.md +3 -3
  49. package/.github/prompts/oxe-next.prompt.md +3 -3
  50. package/.github/prompts/oxe-obs.prompt.md +3 -3
  51. package/.github/prompts/oxe-plan-agent.prompt.md +3 -3
  52. package/.github/prompts/oxe-plan.prompt.md +3 -3
  53. package/.github/prompts/oxe-project.prompt.md +3 -3
  54. package/.github/prompts/oxe-quick.prompt.md +3 -3
  55. package/.github/prompts/oxe-research.prompt.md +3 -3
  56. package/.github/prompts/oxe-retro.prompt.md +3 -3
  57. package/.github/prompts/oxe-review-pr.prompt.md +3 -3
  58. package/.github/prompts/oxe-route.prompt.md +3 -3
  59. package/.github/prompts/oxe-scan.prompt.md +3 -3
  60. package/.github/prompts/oxe-security.prompt.md +3 -3
  61. package/.github/prompts/oxe-session.prompt.md +4 -4
  62. package/.github/prompts/oxe-ship.prompt.md +45 -0
  63. package/.github/prompts/oxe-skill.prompt.md +3 -3
  64. package/.github/prompts/oxe-spec.prompt.md +3 -3
  65. package/.github/prompts/oxe-ui-review.prompt.md +3 -3
  66. package/.github/prompts/oxe-ui-spec.prompt.md +3 -3
  67. package/.github/prompts/oxe-update.prompt.md +3 -3
  68. package/.github/prompts/oxe-validate-gaps.prompt.md +3 -3
  69. package/.github/prompts/oxe-verify.prompt.md +6 -3
  70. package/.github/prompts/oxe-workstream.prompt.md +3 -3
  71. package/.github/prompts/oxe.prompt.md +5 -5
  72. package/AGENTS.md +43 -28
  73. package/CHANGELOG.md +193 -0
  74. package/README.md +610 -529
  75. package/bin/banner.txt +1 -1
  76. package/bin/lib/oxe-agent-install.cjs +69 -69
  77. package/bin/lib/oxe-azure.cjs +1445 -1445
  78. package/bin/lib/oxe-context-engine.cjs +867 -867
  79. package/bin/lib/oxe-dashboard.cjs +76 -28
  80. package/bin/lib/oxe-operational.cjs +2144 -1340
  81. package/bin/lib/oxe-project-health.cjs +483 -1
  82. package/bin/lib/oxe-runtime-semantics.cjs +12 -0
  83. package/bin/oxe-cc.js +554 -152
  84. package/commands/oxe/ask.md +7 -3
  85. package/commands/oxe/capabilities.md +2 -2
  86. package/commands/oxe/checkpoint.md +3 -3
  87. package/commands/oxe/compact.md +3 -3
  88. package/commands/oxe/dashboard.md +2 -2
  89. package/commands/oxe/debug.md +3 -3
  90. package/commands/oxe/discuss.md +2 -2
  91. package/commands/oxe/execute.md +7 -4
  92. package/commands/oxe/forensics.md +3 -3
  93. package/commands/oxe/help.md +2 -2
  94. package/commands/oxe/loop.md +3 -3
  95. package/commands/oxe/milestone.md +3 -3
  96. package/commands/oxe/next.md +3 -3
  97. package/commands/oxe/obs.md +3 -3
  98. package/commands/oxe/oxe.md +5 -5
  99. package/commands/oxe/plan-agent.md +2 -2
  100. package/commands/oxe/plan.md +2 -2
  101. package/commands/oxe/project.md +3 -3
  102. package/commands/oxe/quick.md +2 -2
  103. package/commands/oxe/research.md +3 -3
  104. package/commands/oxe/retro.md +3 -3
  105. package/commands/oxe/review-pr.md +3 -3
  106. package/commands/oxe/route.md +3 -3
  107. package/commands/oxe/scan.md +3 -3
  108. package/commands/oxe/security.md +3 -3
  109. package/commands/oxe/session.md +4 -4
  110. package/commands/oxe/ship.md +49 -0
  111. package/commands/oxe/skill.md +2 -2
  112. package/commands/oxe/spec.md +4 -4
  113. package/commands/oxe/ui-review.md +3 -3
  114. package/commands/oxe/ui-spec.md +3 -3
  115. package/commands/oxe/update.md +2 -2
  116. package/commands/oxe/validate-gaps.md +3 -3
  117. package/commands/oxe/verify.md +7 -4
  118. package/commands/oxe/workstream.md +3 -3
  119. package/lib/runtime/audit/audit-trail.d.ts +71 -0
  120. package/lib/runtime/audit/audit-trail.js +154 -0
  121. package/lib/runtime/audit/index.d.ts +2 -0
  122. package/lib/runtime/audit/index.js +18 -0
  123. package/lib/runtime/audit/policy-pack.d.ts +15 -0
  124. package/lib/runtime/audit/policy-pack.js +57 -0
  125. package/lib/runtime/context/context-pack-builder.d.ts +15 -0
  126. package/lib/runtime/context/context-pack-builder.js +42 -0
  127. package/lib/runtime/context/context-pack-store.d.ts +38 -0
  128. package/lib/runtime/context/context-pack-store.js +142 -0
  129. package/lib/runtime/context/context-profiles.d.ts +11 -0
  130. package/lib/runtime/context/context-profiles.js +51 -0
  131. package/lib/runtime/context/index.d.ts +2 -0
  132. package/lib/runtime/context/index.js +2 -0
  133. package/lib/runtime/decision/decision-engine.d.ts +43 -0
  134. package/lib/runtime/decision/decision-engine.js +127 -0
  135. package/lib/runtime/decision/decision-memo.d.ts +53 -0
  136. package/lib/runtime/decision/decision-memo.js +173 -0
  137. package/lib/runtime/decision/index.d.ts +2 -0
  138. package/lib/runtime/decision/index.js +18 -0
  139. package/lib/runtime/delivery/branch-manager.d.ts +1 -0
  140. package/lib/runtime/delivery/branch-manager.js +7 -0
  141. package/lib/runtime/delivery/ci-checks.js +34 -1
  142. package/lib/runtime/delivery/delivery-records.d.ts +34 -0
  143. package/lib/runtime/delivery/delivery-records.js +48 -0
  144. package/lib/runtime/delivery/index.d.ts +2 -0
  145. package/lib/runtime/delivery/index.js +2 -0
  146. package/lib/runtime/delivery/promotion-pipeline.d.ts +63 -0
  147. package/lib/runtime/delivery/promotion-pipeline.js +224 -0
  148. package/lib/runtime/gate/gate-manager.d.ts +41 -0
  149. package/lib/runtime/gate/gate-manager.js +108 -1
  150. package/lib/runtime/index.d.ts +5 -2
  151. package/lib/runtime/index.js +7 -1
  152. package/lib/runtime/models/gate-decision.d.ts +4 -1
  153. package/lib/runtime/models/workspace.d.ts +3 -0
  154. package/lib/runtime/plugins/capability-adapter.d.ts +12 -0
  155. package/lib/runtime/plugins/capability-adapter.js +204 -0
  156. package/lib/runtime/plugins/capability-matrix.d.ts +25 -0
  157. package/lib/runtime/plugins/capability-matrix.js +90 -0
  158. package/lib/runtime/plugins/index.d.ts +3 -0
  159. package/lib/runtime/plugins/index.js +3 -0
  160. package/lib/runtime/plugins/plugin-abi.d.ts +2 -0
  161. package/lib/runtime/plugins/plugin-manifest.d.ts +22 -0
  162. package/lib/runtime/plugins/plugin-manifest.js +95 -0
  163. package/lib/runtime/plugins/plugin-registry.d.ts +46 -0
  164. package/lib/runtime/plugins/plugin-registry.js +84 -2
  165. package/lib/runtime/policy/policy-engine.d.ts +47 -1
  166. package/lib/runtime/policy/policy-engine.js +172 -9
  167. package/lib/runtime/projection/projection-engine.d.ts +9 -1
  168. package/lib/runtime/projection/projection-engine.js +73 -3
  169. package/lib/runtime/reducers/run-state-reducer.d.ts +26 -0
  170. package/lib/runtime/reducers/run-state-reducer.js +117 -1
  171. package/lib/runtime/scheduler/agent-registry.d.ts +44 -0
  172. package/lib/runtime/scheduler/agent-registry.js +96 -0
  173. package/lib/runtime/scheduler/agent-roles.d.ts +54 -0
  174. package/lib/runtime/scheduler/agent-roles.js +62 -0
  175. package/lib/runtime/scheduler/index.d.ts +3 -0
  176. package/lib/runtime/scheduler/index.js +3 -0
  177. package/lib/runtime/scheduler/multi-agent-coordinator.d.ts +45 -1
  178. package/lib/runtime/scheduler/multi-agent-coordinator.js +234 -35
  179. package/lib/runtime/scheduler/run-journal.d.ts +18 -0
  180. package/lib/runtime/scheduler/run-journal.js +54 -0
  181. package/lib/runtime/scheduler/scheduler.d.ts +29 -1
  182. package/lib/runtime/scheduler/scheduler.js +387 -14
  183. package/lib/runtime/verification/index.d.ts +1 -0
  184. package/lib/runtime/verification/index.js +1 -0
  185. package/lib/runtime/verification/verification-compiler.d.ts +43 -0
  186. package/lib/runtime/verification/verification-compiler.js +137 -0
  187. package/lib/runtime/verification/verification-manifest.d.ts +67 -0
  188. package/lib/runtime/verification/verification-manifest.js +179 -0
  189. package/lib/runtime/workspace/strategies/ephemeral-container.d.ts +1 -0
  190. package/lib/runtime/workspace/strategies/ephemeral-container.js +4 -0
  191. package/lib/runtime/workspace/strategies/git-worktree.d.ts +1 -0
  192. package/lib/runtime/workspace/strategies/git-worktree.js +2 -0
  193. package/lib/runtime/workspace/strategies/inplace.d.ts +1 -0
  194. package/lib/runtime/workspace/strategies/inplace.js +2 -0
  195. package/lib/runtime/workspace/workspace-manager.d.ts +2 -1
  196. package/lib/sdk/README.md +9 -9
  197. package/lib/sdk/index.cjs +33 -24
  198. package/lib/sdk/index.d.ts +149 -14
  199. package/oxe/templates/ACTIVE-RUN.template.json +32 -32
  200. package/oxe/templates/CAPABILITIES.template.md +7 -7
  201. package/oxe/templates/CAPABILITY.template.md +45 -45
  202. package/oxe/templates/CHECKPOINTS.template.md +7 -7
  203. package/oxe/templates/EXECUTION-RUNTIME.template.md +68 -68
  204. package/oxe/templates/HYPOTHESES.template.md +33 -33
  205. package/oxe/templates/LESSONS-METRICS.template.json +13 -13
  206. package/oxe/templates/NOTES.template.md +16 -16
  207. package/oxe/templates/PLAN-REVIEW.template.md +31 -31
  208. package/oxe/templates/SESSION.template.md +34 -34
  209. package/oxe/templates/SKILL.template.md +26 -26
  210. package/oxe/templates/STATE.md +55 -55
  211. package/oxe/templates/WORKFLOW_AUTHORING.md +18 -18
  212. package/oxe/workflows/ask.md +96 -92
  213. package/oxe/workflows/capabilities.md +25 -25
  214. package/oxe/workflows/checkpoint.md +14 -10
  215. package/oxe/workflows/dashboard.md +33 -33
  216. package/oxe/workflows/debug.md +19 -15
  217. package/oxe/workflows/discuss.md +12 -12
  218. package/oxe/workflows/execute.md +44 -2
  219. package/oxe/workflows/forensics.md +13 -9
  220. package/oxe/workflows/help.md +352 -304
  221. package/oxe/workflows/loop.md +17 -13
  222. package/oxe/workflows/next.md +22 -22
  223. package/oxe/workflows/obs.md +4 -0
  224. package/oxe/workflows/oxe.md +64 -31
  225. package/oxe/workflows/plan-agent.md +9 -9
  226. package/oxe/workflows/project.md +6 -1
  227. package/oxe/workflows/quick.md +10 -10
  228. package/oxe/workflows/references/reasoning-discovery.md +28 -28
  229. package/oxe/workflows/references/reasoning-execution.md +29 -29
  230. package/oxe/workflows/references/reasoning-planning.md +32 -32
  231. package/oxe/workflows/references/reasoning-review.md +29 -29
  232. package/oxe/workflows/references/reasoning-status.md +24 -24
  233. package/oxe/workflows/references/robustness-elevation.md +295 -295
  234. package/oxe/workflows/references/workflow-runtime-contracts.json +952 -907
  235. package/oxe/workflows/research.md +32 -28
  236. package/oxe/workflows/retro.md +4 -0
  237. package/oxe/workflows/review-pr.md +15 -11
  238. package/oxe/workflows/route.md +16 -16
  239. package/oxe/workflows/scan.md +4 -0
  240. package/oxe/workflows/security.md +14 -10
  241. package/oxe/workflows/session.md +213 -197
  242. package/oxe/workflows/ship.md +142 -0
  243. package/oxe/workflows/skill.md +44 -44
  244. package/oxe/workflows/spec.md +15 -0
  245. package/oxe/workflows/ui-review.md +20 -16
  246. package/oxe/workflows/ui-spec.md +7 -3
  247. package/oxe/workflows/validate-gaps.md +13 -9
  248. package/oxe/workflows/verify-audit.md +73 -73
  249. package/oxe/workflows/verify.md +52 -3
  250. package/package.json +92 -92
  251. package/packages/runtime/package.json +17 -17
  252. package/packages/runtime/src/audit/audit-trail.ts +243 -0
  253. package/packages/runtime/src/audit/index.ts +2 -0
  254. package/packages/runtime/src/audit/policy-pack.ts +62 -0
  255. package/packages/runtime/src/compiler/graph-compiler.ts +245 -245
  256. package/packages/runtime/src/compiler/index.ts +1 -1
  257. package/packages/runtime/src/context/context-pack-builder.ts +259 -193
  258. package/packages/runtime/src/context/context-pack-store.ts +197 -0
  259. package/packages/runtime/src/context/context-profiles.ts +60 -0
  260. package/packages/runtime/src/context/index.ts +3 -1
  261. package/packages/runtime/src/decision/decision-engine.ts +174 -0
  262. package/packages/runtime/src/decision/decision-memo.ts +211 -0
  263. package/packages/runtime/src/decision/index.ts +2 -0
  264. package/packages/runtime/src/delivery/branch-manager.ts +91 -84
  265. package/packages/runtime/src/delivery/ci-checks.ts +285 -252
  266. package/packages/runtime/src/delivery/delivery-records.ts +75 -0
  267. package/packages/runtime/src/delivery/index.ts +5 -3
  268. package/packages/runtime/src/delivery/pr-manager.ts +112 -112
  269. package/packages/runtime/src/delivery/promotion-pipeline.ts +334 -0
  270. package/packages/runtime/src/events/bus.ts +92 -92
  271. package/packages/runtime/src/events/catalog.ts +29 -29
  272. package/packages/runtime/src/events/envelope.ts +14 -14
  273. package/packages/runtime/src/events/index.ts +3 -3
  274. package/packages/runtime/src/evidence/evidence-store.ts +130 -130
  275. package/packages/runtime/src/evidence/index.ts +1 -1
  276. package/packages/runtime/src/gate/gate-manager.ts +289 -137
  277. package/packages/runtime/src/gate/index.ts +1 -1
  278. package/packages/runtime/src/index.ts +41 -32
  279. package/packages/runtime/src/models/attempt.ts +19 -19
  280. package/packages/runtime/src/models/evidence.ts +21 -21
  281. package/packages/runtime/src/models/gate-decision.ts +25 -21
  282. package/packages/runtime/src/models/index.ts +8 -8
  283. package/packages/runtime/src/models/run.ts +24 -24
  284. package/packages/runtime/src/models/session.ts +11 -11
  285. package/packages/runtime/src/models/verification-result.ts +10 -10
  286. package/packages/runtime/src/models/work-item.ts +25 -25
  287. package/packages/runtime/src/models/workspace.ts +31 -28
  288. package/packages/runtime/src/plugins/capability-adapter.ts +206 -0
  289. package/packages/runtime/src/plugins/capability-matrix.ts +126 -0
  290. package/packages/runtime/src/plugins/index.ts +5 -2
  291. package/packages/runtime/src/plugins/plugin-abi.ts +97 -95
  292. package/packages/runtime/src/plugins/plugin-manifest.ts +118 -0
  293. package/packages/runtime/src/plugins/plugin-registry.ts +232 -119
  294. package/packages/runtime/src/policy/index.ts +1 -1
  295. package/packages/runtime/src/policy/policy-engine.ts +330 -113
  296. package/packages/runtime/src/projection/index.ts +1 -1
  297. package/packages/runtime/src/projection/projection-engine.ts +328 -249
  298. package/packages/runtime/src/reducers/debug-reducer.ts +36 -36
  299. package/packages/runtime/src/reducers/index.ts +2 -2
  300. package/packages/runtime/src/reducers/run-state-reducer.ts +269 -127
  301. package/packages/runtime/src/scheduler/agent-registry.ts +132 -0
  302. package/packages/runtime/src/scheduler/agent-roles.ts +109 -0
  303. package/packages/runtime/src/scheduler/index.ts +4 -1
  304. package/packages/runtime/src/scheduler/multi-agent-coordinator.ts +521 -231
  305. package/packages/runtime/src/scheduler/run-journal.ts +62 -0
  306. package/packages/runtime/src/scheduler/scheduler.ts +722 -281
  307. package/packages/runtime/src/verification/index.ts +2 -1
  308. package/packages/runtime/src/verification/verification-compiler.ts +436 -225
  309. package/packages/runtime/src/verification/verification-manifest.ts +252 -0
  310. package/packages/runtime/src/workspace/index.ts +5 -5
  311. package/packages/runtime/src/workspace/strategies/ephemeral-container.ts +126 -121
  312. package/packages/runtime/src/workspace/strategies/git-worktree.ts +79 -77
  313. package/packages/runtime/src/workspace/strategies/inplace.ts +38 -35
  314. package/packages/runtime/src/workspace/workspace-manager.ts +16 -15
  315. package/packages/runtime/tsconfig.json +17 -17
  316. package/vscode-extension/.vscodeignore +7 -7
  317. package/vscode-extension/oxe-agents-1.0.0.vsix +0 -0
  318. package/vscode-extension/package.json +185 -185
  319. package/vscode-extension/src/extension.js +310 -310
  320. package/vscode-extension/src/shared/contextLoader.js +137 -137
  321. package/vscode-extension/src/shared/contractBuilder.js +159 -159
  322. package/vscode-extension/src/shared/stateReader.js +101 -101
@@ -1,231 +1,521 @@
1
- import { appendEvent } from '../events/bus';
2
- import type { ExecutionGraph, GraphNode } from '../compiler/graph-compiler';
3
- import type { WorkspaceManager } from '../workspace/workspace-manager';
4
- import type { TaskExecutor, TaskResult, SchedulerContext } from './scheduler';
5
- import { Scheduler } from './scheduler';
6
- import type { WorkspaceLease } from '../models/workspace';
7
-
8
- export type CoordinationMode = 'parallel' | 'competitive' | 'cooperative';
9
-
10
- export interface AgentSpec {
11
- id: string;
12
- executor: TaskExecutor;
13
- workspaceManager: WorkspaceManager;
14
- /** Task IDs this agent is responsible for (used in parallel mode) */
15
- assignedTaskIds?: string[];
16
- }
17
-
18
- export interface CoordinationOptions {
19
- mode: CoordinationMode;
20
- agents: AgentSpec[];
21
- projectRoot: string;
22
- sessionId: string | null;
23
- runId: string;
24
- onEvent?: SchedulerContext['onEvent'];
25
- }
26
-
27
- export interface CoordinationResult {
28
- mode: CoordinationMode;
29
- run_id: string;
30
- completed: string[];
31
- failed: string[];
32
- blocked: string[];
33
- agent_results: Array<{ agent_id: string; completed: string[]; failed: string[] }>;
34
- }
35
-
36
- // ─── Parallel mode ───────────────────────────────────────────────────────────
37
- // Tasks are partitioned across agents. Each agent runs its own Scheduler
38
- // on a sub-graph. Results are merged.
39
-
40
- async function runParallel(
41
- graph: ExecutionGraph,
42
- opts: CoordinationOptions
43
- ): Promise<CoordinationResult> {
44
- const { agents, projectRoot, sessionId, runId } = opts;
45
-
46
- // Partition tasks across agents (round-robin if assignedTaskIds not set)
47
- const partitions = agents.map((a) => a.assignedTaskIds ?? []);
48
- if (partitions.every((p) => p.length === 0)) {
49
- const allIds = [...graph.nodes.keys()];
50
- allIds.forEach((id, i) => {
51
- partitions[i % agents.length].push(id);
52
- });
53
- }
54
-
55
- appendEvent(projectRoot, sessionId, {
56
- type: 'RunStarted',
57
- run_id: runId,
58
- payload: { mode: 'parallel', agent_count: agents.length },
59
- });
60
-
61
- const agentResults = await Promise.all(
62
- agents.map(async (agent, idx) => {
63
- const subGraph = subGraphFor(graph, partitions[idx]);
64
- if (subGraph.nodes.size === 0) {
65
- return { agent_id: agent.id, completed: [], failed: [] };
66
- }
67
- const ctx: SchedulerContext = {
68
- projectRoot,
69
- sessionId,
70
- runId: `${runId}-agent${idx}`,
71
- executor: agent.executor,
72
- workspaceManager: agent.workspaceManager,
73
- onEvent: opts.onEvent,
74
- };
75
- const scheduler = new Scheduler();
76
- const result = await scheduler.run(subGraph, ctx);
77
- return { agent_id: agent.id, completed: result.completed, failed: result.failed };
78
- })
79
- );
80
-
81
- const completed = agentResults.flatMap((r) => r.completed);
82
- const failed = agentResults.flatMap((r) => r.failed);
83
-
84
- appendEvent(projectRoot, sessionId, {
85
- type: 'RunCompleted',
86
- run_id: runId,
87
- payload: { mode: 'parallel', completed: completed.length, failed: failed.length },
88
- });
89
-
90
- return { mode: 'parallel', run_id: runId, completed, failed, blocked: [], agent_results: agentResults };
91
- }
92
-
93
- // ─── Competitive mode ────────────────────────────────────────────────────────
94
- // Two agents attempt the same task. First success wins; the loser's workspace
95
- // is disposed. Requires exactly 2 agents.
96
-
97
- async function runCompetitive(
98
- graph: ExecutionGraph,
99
- opts: CoordinationOptions
100
- ): Promise<CoordinationResult> {
101
- if (opts.agents.length < 2) {
102
- throw new Error('Competitive mode requires at least 2 agents');
103
- }
104
- const [agentA, agentB] = opts.agents;
105
- const { projectRoot, sessionId, runId } = opts;
106
-
107
- appendEvent(projectRoot, sessionId, {
108
- type: 'RunStarted',
109
- run_id: runId,
110
- payload: { mode: 'competitive' },
111
- });
112
-
113
- const completed: string[] = [];
114
- const failed: string[] = [];
115
-
116
- for (const wave of graph.waves) {
117
- for (const nodeId of wave.node_ids) {
118
- const node = graph.nodes.get(nodeId)!;
119
- const result = await competeTwoAgents(nodeId, node, agentA, agentB, opts);
120
- if (result.success) completed.push(nodeId);
121
- else failed.push(nodeId);
122
- if (failed.length > 0) break;
123
- }
124
- if (failed.length > 0) break;
125
- }
126
-
127
- appendEvent(projectRoot, sessionId, {
128
- type: 'RunCompleted',
129
- run_id: runId,
130
- payload: { mode: 'competitive', completed: completed.length },
131
- });
132
-
133
- return {
134
- mode: 'competitive',
135
- run_id: runId,
136
- completed,
137
- failed,
138
- blocked: [],
139
- agent_results: [
140
- { agent_id: agentA.id, completed, failed },
141
- { agent_id: agentB.id, completed: [], failed: [] },
142
- ],
143
- };
144
- }
145
-
146
- async function competeTwoAgents(
147
- nodeId: string,
148
- node: GraphNode,
149
- agentA: AgentSpec,
150
- agentB: AgentSpec,
151
- opts: CoordinationOptions
152
- ): Promise<TaskResult> {
153
- const { projectRoot, sessionId, runId } = opts;
154
-
155
- const allocA = await agentA.workspaceManager.allocate({
156
- work_item_id: nodeId, attempt_number: 1, strategy: node.workspace_strategy, mutation_scope: node.mutation_scope,
157
- });
158
- const allocB = await agentB.workspaceManager.allocate({
159
- work_item_id: nodeId, attempt_number: 1, strategy: node.workspace_strategy, mutation_scope: node.mutation_scope,
160
- });
161
-
162
- appendEvent(projectRoot, sessionId, {
163
- type: 'AttemptStarted',
164
- run_id: runId,
165
- work_item_id: nodeId,
166
- payload: { mode: 'competitive', agents: [agentA.id, agentB.id] },
167
- });
168
-
169
- // Race both agents — first success wins
170
- const [resultA, resultB] = await Promise.all([
171
- agentA.executor.execute(node, allocA, runId, 1).catch((e) => ({
172
- success: false, failure_class: 'env' as const, evidence: [], output: String(e),
173
- })),
174
- agentB.executor.execute(node, allocB, runId, 1).catch((e) => ({
175
- success: false, failure_class: 'env' as const, evidence: [], output: String(e),
176
- })),
177
- ]);
178
-
179
- // Clean up both workspaces
180
- await Promise.all([
181
- agentA.workspaceManager.dispose(allocA.workspace_id).catch(() => {}),
182
- agentB.workspaceManager.dispose(allocB.workspace_id).catch(() => {}),
183
- ]);
184
-
185
- // Pick winner: prefer success; if both succeed, prefer A (primary agent)
186
- const winner = resultA.success ? resultA : resultB.success ? resultB : resultA;
187
-
188
- if (winner.success) {
189
- appendEvent(projectRoot, sessionId, { type: 'WorkItemCompleted', run_id: runId, work_item_id: nodeId, payload: { mode: 'competitive' } });
190
- } else {
191
- appendEvent(projectRoot, sessionId, { type: 'WorkItemBlocked', run_id: runId, work_item_id: nodeId, payload: { mode: 'competitive', failure_class: winner.failure_class } });
192
- }
193
-
194
- return winner;
195
- }
196
-
197
- // ─── Public API ──────────────────────────────────────────────────────────────
198
-
199
- export class MultiAgentCoordinator {
200
- async run(graph: ExecutionGraph, opts: CoordinationOptions): Promise<CoordinationResult> {
201
- switch (opts.mode) {
202
- case 'parallel': return runParallel(graph, opts);
203
- case 'competitive': return runCompetitive(graph, opts);
204
- case 'cooperative':
205
- // Cooperative mode: planner (agent[0]) prepares context,
206
- // executor (agent[1]) implements. For R3, delegate to sequential parallel.
207
- return runParallel(graph, { ...opts, mode: 'parallel' });
208
- default:
209
- throw new Error(`Unknown coordination mode: ${opts.mode}`);
210
- }
211
- }
212
- }
213
-
214
- // ─── Helpers ─────────────────────────────────────────────────────────────────
215
-
216
- function subGraphFor(graph: ExecutionGraph, nodeIds: string[]): ExecutionGraph {
217
- const ids = new Set(nodeIds);
218
- const nodes = new Map([...graph.nodes].filter(([id]) => ids.has(id)));
219
- const edges = graph.edges.filter((e) => ids.has(e.from) && ids.has(e.to));
220
- const waves = graph.waves.map((w) => ({
221
- wave_number: w.wave_number,
222
- node_ids: w.node_ids.filter((id) => ids.has(id)),
223
- })).filter((w) => w.node_ids.length > 0);
224
-
225
- return {
226
- nodes,
227
- edges,
228
- waves,
229
- metadata: { ...graph.metadata, node_count: nodes.size, wave_count: waves.length },
230
- };
231
- }
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 } from '../workspace/workspace-manager';
6
+ import type { TaskExecutor, TaskResult, SchedulerContext } from './scheduler';
7
+ import { Scheduler } from './scheduler';
8
+ import { buildHandoff } from './agent-roles';
9
+ import type { CooperativeHandoff } from './agent-roles';
10
+
11
+ export type CoordinationMode = 'parallel' | 'competitive' | 'cooperative';
12
+
13
+ export interface AgentSpec {
14
+ id: string;
15
+ executor: TaskExecutor;
16
+ workspaceManager: WorkspaceManager;
17
+ /** Task IDs this agent is responsible for (used in parallel mode) */
18
+ assignedTaskIds?: string[];
19
+ }
20
+
21
+ export interface CoordinationOptions {
22
+ mode: CoordinationMode;
23
+ agents: AgentSpec[];
24
+ projectRoot: string;
25
+ sessionId: string | null;
26
+ runId: string;
27
+ onEvent?: SchedulerContext['onEvent'];
28
+ }
29
+
30
+ export interface ArbitrationRecord {
31
+ work_item_id: string;
32
+ mode: CoordinationMode;
33
+ winner_agent_id: string | null;
34
+ participant_agent_ids: string[];
35
+ success: boolean;
36
+ failure_class: TaskResult['failure_class'];
37
+ evidence_count: number;
38
+ recorded_at: string;
39
+ }
40
+
41
+ export interface MultiAgentOwnership {
42
+ work_item_id: string;
43
+ owner_agent_id: string;
44
+ }
45
+
46
+ export interface MultiAgentStatusSnapshot {
47
+ run_id: string;
48
+ mode: CoordinationMode;
49
+ workspace_isolation_required: 'isolated';
50
+ workspace_isolation_enforced: boolean;
51
+ agent_count: number;
52
+ ownership: MultiAgentOwnership[];
53
+ completed: string[];
54
+ failed: string[];
55
+ blocked: string[];
56
+ agent_results: Array<{
57
+ agent_id: string;
58
+ isolation_level: 'shared' | 'isolated';
59
+ assigned_task_ids: string[];
60
+ completed: string[];
61
+ failed: string[];
62
+ }>;
63
+ orphan_reassignments: Array<{ from_agent_id: string; to_agent_id: string; work_item_ids: string[] }>;
64
+ updated_at: string;
65
+ }
66
+
67
+ export interface CoordinationResult {
68
+ mode: CoordinationMode;
69
+ run_id: string;
70
+ completed: string[];
71
+ failed: string[];
72
+ blocked: string[];
73
+ agent_results: Array<{ agent_id: string; completed: string[]; failed: string[] }>;
74
+ handoffs?: CooperativeHandoff[];
75
+ arbitration_results?: ArbitrationRecord[];
76
+ state?: MultiAgentStatusSnapshot;
77
+ }
78
+
79
+ function ensureRunDir(projectRoot: string, runId: string): string {
80
+ const dir = path.join(projectRoot, '.oxe', 'runs', runId);
81
+ fs.mkdirSync(dir, { recursive: true });
82
+ return dir;
83
+ }
84
+
85
+ function persistMultiAgentArtifacts(
86
+ projectRoot: string,
87
+ runId: string,
88
+ state: MultiAgentStatusSnapshot,
89
+ handoffs: CooperativeHandoff[] = [],
90
+ arbitrationResults: ArbitrationRecord[] = []
91
+ ): void {
92
+ const runDir = ensureRunDir(projectRoot, runId);
93
+ fs.writeFileSync(path.join(runDir, 'multi-agent-state.json'), JSON.stringify(state, null, 2), 'utf8');
94
+ fs.writeFileSync(path.join(runDir, 'handoffs.json'), JSON.stringify(handoffs, null, 2), 'utf8');
95
+ fs.writeFileSync(path.join(runDir, 'arbitration-results.json'), JSON.stringify(arbitrationResults, null, 2), 'utf8');
96
+ }
97
+
98
+ function ensureIsolatedAgents(agents: AgentSpec[]): void {
99
+ const shared = agents.filter((agent) => agent.workspaceManager.isolation_level !== 'isolated');
100
+ if (shared.length === 0) return;
101
+ const ids = shared.map((agent) => `${agent.id}:${agent.workspaceManager.isolation_level}`).join(', ');
102
+ throw new Error(`Multi-agent requires isolated workspaces. Invalid agents: ${ids}`);
103
+ }
104
+
105
+ function buildOwnership(agents: AgentSpec[], partitions: string[][]): MultiAgentOwnership[] {
106
+ const ownership: MultiAgentOwnership[] = [];
107
+ for (let idx = 0; idx < agents.length; idx += 1) {
108
+ for (const workItemId of partitions[idx] ?? []) {
109
+ ownership.push({
110
+ work_item_id: workItemId,
111
+ owner_agent_id: agents[idx].id,
112
+ });
113
+ }
114
+ }
115
+ return ownership;
116
+ }
117
+
118
+ function makeState(
119
+ mode: CoordinationMode,
120
+ runId: string,
121
+ agents: AgentSpec[],
122
+ partitions: string[][],
123
+ agentResults: Array<{ agent_id: string; completed: string[]; failed: string[] }>,
124
+ completed: string[],
125
+ failed: string[],
126
+ blocked: string[],
127
+ orphanReassignments: Array<{ from_agent_id: string; to_agent_id: string; work_item_ids: string[] }>
128
+ ): MultiAgentStatusSnapshot {
129
+ return {
130
+ run_id: runId,
131
+ mode,
132
+ workspace_isolation_required: 'isolated',
133
+ workspace_isolation_enforced: true,
134
+ agent_count: agents.length,
135
+ ownership: buildOwnership(agents, partitions),
136
+ completed,
137
+ failed,
138
+ blocked,
139
+ agent_results: agents.map((agent, idx) => {
140
+ const result = agentResults.find((entry) => entry.agent_id === agent.id);
141
+ return {
142
+ agent_id: agent.id,
143
+ isolation_level: agent.workspaceManager.isolation_level,
144
+ assigned_task_ids: partitions[idx] ?? agent.assignedTaskIds ?? [],
145
+ completed: result?.completed ?? [],
146
+ failed: result?.failed ?? [],
147
+ };
148
+ }),
149
+ orphan_reassignments: orphanReassignments,
150
+ updated_at: new Date().toISOString(),
151
+ };
152
+ }
153
+
154
+ // ─── Parallel mode ───────────────────────────────────────────────────────────
155
+
156
+ async function runParallel(
157
+ graph: ExecutionGraph,
158
+ opts: CoordinationOptions
159
+ ): Promise<CoordinationResult> {
160
+ const { agents, projectRoot, sessionId, runId } = opts;
161
+ ensureIsolatedAgents(agents);
162
+
163
+ const partitions = agents.map((agent) => [...(agent.assignedTaskIds ?? [])]);
164
+ if (partitions.every((partition) => partition.length === 0)) {
165
+ const allIds = [...graph.nodes.keys()];
166
+ allIds.forEach((id, index) => {
167
+ partitions[index % agents.length].push(id);
168
+ });
169
+ }
170
+
171
+ appendEvent(projectRoot, sessionId, {
172
+ type: 'RunStarted',
173
+ run_id: runId,
174
+ payload: { mode: 'parallel', agent_count: agents.length, isolation_level: 'isolated' },
175
+ });
176
+
177
+ const agentResults = await Promise.all(
178
+ agents.map(async (agent, idx) => {
179
+ const subGraph = subGraphFor(graph, partitions[idx]);
180
+ if (subGraph.nodes.size === 0) {
181
+ return { agent_id: agent.id, completed: [], failed: [] };
182
+ }
183
+ const ctx: SchedulerContext = {
184
+ projectRoot,
185
+ sessionId,
186
+ runId: `${runId}-agent${idx}`,
187
+ executor: agent.executor,
188
+ workspaceManager: agent.workspaceManager,
189
+ onEvent: opts.onEvent,
190
+ };
191
+ const scheduler = new Scheduler();
192
+ const result = await scheduler.run(subGraph, ctx);
193
+ return { agent_id: agent.id, completed: result.completed, failed: result.failed };
194
+ })
195
+ );
196
+
197
+ const completed = agentResults.flatMap((result) => result.completed);
198
+ const failed = agentResults.flatMap((result) => result.failed);
199
+ const blocked: string[] = [];
200
+ const orphanReassignments: Array<{ from_agent_id: string; to_agent_id: string; work_item_ids: string[] }> = [];
201
+ const state = makeState('parallel', runId, agents, partitions, agentResults, completed, failed, blocked, orphanReassignments);
202
+ persistMultiAgentArtifacts(projectRoot, runId, state);
203
+
204
+ appendEvent(projectRoot, sessionId, {
205
+ type: 'RunCompleted',
206
+ run_id: runId,
207
+ payload: { mode: 'parallel', completed: completed.length, failed: failed.length },
208
+ });
209
+
210
+ return {
211
+ mode: 'parallel',
212
+ run_id: runId,
213
+ completed,
214
+ failed,
215
+ blocked,
216
+ agent_results: agentResults,
217
+ arbitration_results: [],
218
+ state,
219
+ };
220
+ }
221
+
222
+ // ─── Competitive mode ────────────────────────────────────────────────────────
223
+
224
+ async function runCompetitive(
225
+ graph: ExecutionGraph,
226
+ opts: CoordinationOptions
227
+ ): Promise<CoordinationResult> {
228
+ if (opts.agents.length < 2) {
229
+ throw new Error('Competitive mode requires at least 2 agents');
230
+ }
231
+ ensureIsolatedAgents(opts.agents);
232
+ const [agentA, agentB] = opts.agents;
233
+ const { projectRoot, sessionId, runId } = opts;
234
+
235
+ appendEvent(projectRoot, sessionId, {
236
+ type: 'RunStarted',
237
+ run_id: runId,
238
+ payload: { mode: 'competitive', isolation_level: 'isolated' },
239
+ });
240
+
241
+ const completed: string[] = [];
242
+ const failed: string[] = [];
243
+ const blocked: string[] = [];
244
+ const arbitrationResults: ArbitrationRecord[] = [];
245
+
246
+ for (const wave of graph.waves) {
247
+ for (const nodeId of wave.node_ids) {
248
+ const node = graph.nodes.get(nodeId)!;
249
+ const result = await competeTwoAgents(nodeId, node, agentA, agentB, opts, arbitrationResults);
250
+ if (result.success) completed.push(nodeId);
251
+ else failed.push(nodeId);
252
+ if (failed.length > 0) break;
253
+ }
254
+ if (failed.length > 0) break;
255
+ }
256
+
257
+ const partitions = [Array.from(graph.nodes.keys()), Array.from(graph.nodes.keys())];
258
+ const state = makeState(
259
+ 'competitive',
260
+ runId,
261
+ opts.agents,
262
+ partitions,
263
+ [
264
+ { agent_id: agentA.id, completed, failed },
265
+ { agent_id: agentB.id, completed: [], failed: [] },
266
+ ],
267
+ completed,
268
+ failed,
269
+ blocked,
270
+ []
271
+ );
272
+ persistMultiAgentArtifacts(projectRoot, runId, state, [], arbitrationResults);
273
+
274
+ appendEvent(projectRoot, sessionId, {
275
+ type: 'RunCompleted',
276
+ run_id: runId,
277
+ payload: { mode: 'competitive', completed: completed.length },
278
+ });
279
+
280
+ return {
281
+ mode: 'competitive',
282
+ run_id: runId,
283
+ completed,
284
+ failed,
285
+ blocked,
286
+ agent_results: [
287
+ { agent_id: agentA.id, completed, failed },
288
+ { agent_id: agentB.id, completed: [], failed: [] },
289
+ ],
290
+ arbitration_results: arbitrationResults,
291
+ state,
292
+ };
293
+ }
294
+
295
+ async function competeTwoAgents(
296
+ nodeId: string,
297
+ node: GraphNode,
298
+ agentA: AgentSpec,
299
+ agentB: AgentSpec,
300
+ opts: CoordinationOptions,
301
+ arbitrationResults: ArbitrationRecord[]
302
+ ): Promise<TaskResult> {
303
+ const { projectRoot, sessionId, runId } = opts;
304
+
305
+ const allocA = await agentA.workspaceManager.allocate({
306
+ work_item_id: nodeId, attempt_number: 1, strategy: node.workspace_strategy, mutation_scope: node.mutation_scope,
307
+ });
308
+ const allocB = await agentB.workspaceManager.allocate({
309
+ work_item_id: nodeId, attempt_number: 1, strategy: node.workspace_strategy, mutation_scope: node.mutation_scope,
310
+ });
311
+
312
+ appendEvent(projectRoot, sessionId, {
313
+ type: 'AttemptStarted',
314
+ run_id: runId,
315
+ work_item_id: nodeId,
316
+ payload: { mode: 'competitive', agents: [agentA.id, agentB.id] },
317
+ });
318
+
319
+ const [resultA, resultB] = await Promise.all([
320
+ agentA.executor.execute(node, allocA, runId, 1).catch((error) => ({
321
+ success: false, failure_class: 'env' as const, evidence: [], output: String(error),
322
+ })),
323
+ agentB.executor.execute(node, allocB, runId, 1).catch((error) => ({
324
+ success: false, failure_class: 'env' as const, evidence: [], output: String(error),
325
+ })),
326
+ ]);
327
+
328
+ await Promise.all([
329
+ agentA.workspaceManager.dispose(allocA.workspace_id).catch(() => {}),
330
+ agentB.workspaceManager.dispose(allocB.workspace_id).catch(() => {}),
331
+ ]);
332
+
333
+ const winner = resultA.success ? resultA : resultB.success ? resultB : resultA;
334
+ const winnerAgentId = resultA.success ? agentA.id : resultB.success ? agentB.id : agentA.id;
335
+ arbitrationResults.push({
336
+ work_item_id: nodeId,
337
+ mode: 'competitive',
338
+ winner_agent_id: winnerAgentId,
339
+ participant_agent_ids: [agentA.id, agentB.id],
340
+ success: winner.success,
341
+ failure_class: winner.failure_class,
342
+ evidence_count: winner.evidence.length,
343
+ recorded_at: new Date().toISOString(),
344
+ });
345
+
346
+ if (winner.success) {
347
+ appendEvent(projectRoot, sessionId, { type: 'WorkItemCompleted', run_id: runId, work_item_id: nodeId, payload: { mode: 'competitive', winner_agent_id: winnerAgentId } });
348
+ } else {
349
+ appendEvent(projectRoot, sessionId, { type: 'WorkItemBlocked', run_id: runId, work_item_id: nodeId, payload: { mode: 'competitive', failure_class: winner.failure_class, winner_agent_id: winnerAgentId } });
350
+ }
351
+
352
+ return winner;
353
+ }
354
+
355
+ // ─── Cooperative mode ────────────────────────────────────────────────────────
356
+
357
+ async function runCooperative(
358
+ graph: ExecutionGraph,
359
+ opts: CoordinationOptions
360
+ ): Promise<CoordinationResult> {
361
+ if (opts.agents.length < 2) {
362
+ throw new Error('Cooperative mode requires at least 2 agents');
363
+ }
364
+ ensureIsolatedAgents(opts.agents);
365
+ const [planner, executor] = opts.agents;
366
+ const { projectRoot, sessionId, runId } = opts;
367
+ const handoffs: CooperativeHandoff[] = [];
368
+
369
+ appendEvent(projectRoot, sessionId, {
370
+ type: 'RunStarted',
371
+ run_id: runId,
372
+ payload: { mode: 'cooperative', planner: planner.id, executor: executor.id, isolation_level: 'isolated' },
373
+ });
374
+
375
+ const completed: string[] = [];
376
+ const failed: string[] = [];
377
+ const blocked: string[] = [];
378
+
379
+ for (const wave of graph.waves) {
380
+ for (const nodeId of wave.node_ids) {
381
+ const node = graph.nodes.get(nodeId)!;
382
+
383
+ const planAlloc = await planner.workspaceManager.allocate({
384
+ work_item_id: nodeId,
385
+ attempt_number: 1,
386
+ strategy: node.workspace_strategy,
387
+ mutation_scope: node.mutation_scope,
388
+ });
389
+ await planner.workspaceManager.dispose(planAlloc.workspace_id).catch(() => {});
390
+
391
+ const handoff = buildHandoff({
392
+ from_agent_id: planner.id,
393
+ to_agent_id: executor.id,
394
+ from_role: 'planner',
395
+ to_role: 'executor',
396
+ work_item_id: nodeId,
397
+ context_pack_ref: null,
398
+ });
399
+ handoffs.push(handoff);
400
+
401
+ appendEvent(projectRoot, sessionId, {
402
+ type: 'AttemptStarted',
403
+ run_id: runId,
404
+ work_item_id: nodeId,
405
+ payload: { mode: 'cooperative', handoff_id: handoff.handoff_id },
406
+ });
407
+
408
+ const execAlloc = await executor.workspaceManager.allocate({
409
+ work_item_id: nodeId,
410
+ attempt_number: 1,
411
+ strategy: node.workspace_strategy,
412
+ mutation_scope: node.mutation_scope,
413
+ });
414
+
415
+ let result: TaskResult;
416
+ try {
417
+ result = await executor.executor.execute(node, execAlloc, runId, 1);
418
+ } catch (error) {
419
+ result = { success: false, failure_class: 'env', evidence: [], output: String(error) };
420
+ }
421
+ await executor.workspaceManager.dispose(execAlloc.workspace_id).catch(() => {});
422
+
423
+ if (result.success) {
424
+ completed.push(nodeId);
425
+ appendEvent(projectRoot, sessionId, { type: 'WorkItemCompleted', run_id: runId, work_item_id: nodeId, payload: { mode: 'cooperative' } });
426
+ } else {
427
+ failed.push(nodeId);
428
+ appendEvent(projectRoot, sessionId, { type: 'WorkItemBlocked', run_id: runId, work_item_id: nodeId, payload: { mode: 'cooperative', failure_class: result.failure_class } });
429
+ break;
430
+ }
431
+ }
432
+ if (failed.length > 0) break;
433
+ }
434
+
435
+ const partitions = [Array.from(graph.nodes.keys()), Array.from(graph.nodes.keys())];
436
+ const state = makeState(
437
+ 'cooperative',
438
+ runId,
439
+ opts.agents,
440
+ partitions,
441
+ [
442
+ { agent_id: planner.id, completed: [], failed: [] },
443
+ { agent_id: executor.id, completed, failed },
444
+ ],
445
+ completed,
446
+ failed,
447
+ blocked,
448
+ []
449
+ );
450
+ persistMultiAgentArtifacts(projectRoot, runId, state, handoffs, []);
451
+
452
+ appendEvent(projectRoot, sessionId, {
453
+ type: 'RunCompleted',
454
+ run_id: runId,
455
+ payload: { mode: 'cooperative', completed: completed.length, failed: failed.length },
456
+ });
457
+
458
+ return {
459
+ mode: 'cooperative',
460
+ run_id: runId,
461
+ completed,
462
+ failed,
463
+ blocked,
464
+ agent_results: [
465
+ { agent_id: planner.id, completed: [], failed: [] },
466
+ { agent_id: executor.id, completed, failed },
467
+ ],
468
+ handoffs,
469
+ arbitration_results: [],
470
+ state,
471
+ };
472
+ }
473
+
474
+ // ─── Public API ──────────────────────────────────────────────────────────────
475
+
476
+ export class MultiAgentCoordinator {
477
+ async run(graph: ExecutionGraph, opts: CoordinationOptions): Promise<CoordinationResult> {
478
+ switch (opts.mode) {
479
+ case 'parallel': return runParallel(graph, opts);
480
+ case 'competitive': return runCompetitive(graph, opts);
481
+ case 'cooperative': return runCooperative(graph, opts);
482
+ default:
483
+ throw new Error(`Unknown coordination mode: ${opts.mode}`);
484
+ }
485
+ }
486
+ }
487
+
488
+ export function multiAgentStatePath(projectRoot: string, runId: string): string {
489
+ return path.join(projectRoot, '.oxe', 'runs', runId, 'multi-agent-state.json');
490
+ }
491
+
492
+ export function loadMultiAgentState(projectRoot: string, runId: string): MultiAgentStatusSnapshot | null {
493
+ const statePath = multiAgentStatePath(projectRoot, runId);
494
+ if (!fs.existsSync(statePath)) return null;
495
+ try {
496
+ return JSON.parse(fs.readFileSync(statePath, 'utf8')) as MultiAgentStatusSnapshot;
497
+ } catch {
498
+ return null;
499
+ }
500
+ }
501
+
502
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
503
+
504
+ function subGraphFor(graph: ExecutionGraph, nodeIds: string[]): ExecutionGraph {
505
+ const ids = new Set(nodeIds);
506
+ const nodes = new Map([...graph.nodes].filter(([id]) => ids.has(id)));
507
+ const edges = graph.edges.filter((edge) => ids.has(edge.from) && ids.has(edge.to));
508
+ const waves = graph.waves
509
+ .map((wave) => ({
510
+ wave_number: wave.wave_number,
511
+ node_ids: wave.node_ids.filter((id) => ids.has(id)),
512
+ }))
513
+ .filter((wave) => wave.node_ids.length > 0);
514
+
515
+ return {
516
+ nodes,
517
+ edges,
518
+ waves,
519
+ metadata: { ...graph.metadata, node_count: nodes.size, wave_count: waves.length },
520
+ };
521
+ }