@chroxy/server 0.10.0 → 0.11.10

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 (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -0,0 +1,1342 @@
1
+ /**
2
+ * OrchestrationManager (engine, epic #6691, steps E-2 + E-3) — the committee
3
+ * engine. Owns run lifecycle: an architect session plans the epic, worker
4
+ * sessions execute subtasks, the architect reviews each plan-of-attack and
5
+ * result, and a synthesis turn produces the report.
6
+ *
7
+ * Two worker kinds:
8
+ * - audit (read-only): read/search the repo, report findings. sdk/byok/codex.
9
+ * - implement (write-capable, E-3): edit files in an ISOLATED worktree, then
10
+ * the orchestrator commits + merges the branch into a run-owned integration
11
+ * worktree. codex-ONLY in v1 (codexSandbox:'workspace-write' is the only
12
+ * verified path jail; sdk/byok write pending #6735). The engine NEVER touches
13
+ * the user's branch/working tree and NEVER pushes — output is branches.
14
+ *
15
+ * The wire projection is E-4; restart-reconcile / orphan-sweep / gate-timeouts /
16
+ * pause-resume + the automated conflict-fixup worker are E-3 part 3.
17
+ *
18
+ * Wires the merged foundations: RunLedger (M-2) for durable state + usage,
19
+ * run-budget (M-3) for soft caps, TurnDriver (E-1) to drive sessions,
20
+ * decision-contract (E-1) for the structured committee decisions, run-model
21
+ * (E-1) for the gate registry, role-prompts (this step), and the permission
22
+ * gate. Sessions are real SessionManager sessions (one model per session).
23
+ *
24
+ * The manager is event-driven and async; each subtask advances through the
25
+ * committee loop as its turns resolve. All external collaborators are injected,
26
+ * so the whole loop is testable against a scripted fake provider.
27
+ */
28
+
29
+ import { EventEmitter } from 'node:events'
30
+ import { randomBytes } from 'node:crypto'
31
+ import { extractDecision, DecisionParseError, buildRepairPrompt } from './decision-contract.js'
32
+ import { makeGate, resolveGate as resolveGateModel, nextGateId, assertRunTransition, assertNodeTransition } from './run-model.js'
33
+ import {
34
+ architectPreamble, auditWorkerPreamble, implementWorkerPreamble, presetFor,
35
+ buildPlanPrompt, buildPoaPrompt, buildPoaReviewPrompt,
36
+ buildExecutePrompt, buildResultReviewPrompt, buildSynthesisPrompt,
37
+ } from './role-prompts.js'
38
+ import { createGitOps } from './git-ops.js'
39
+ import { TurnError } from './turn-driver.js'
40
+ import { recordToRunSummary, recordToRunDetail, gateToWire } from './to-wire.js'
41
+ import { buildRunReport, renderReportMarkdown } from './run-report.js'
42
+
43
+ const DEFAULTS = {
44
+ maxParallelWorkers: 2,
45
+ reserveSessions: 1,
46
+ maxCommitteeIterations: 4,
47
+ maxParseRetries: 2,
48
+ turnTimeoutMs: 30 * 60 * 1000,
49
+ diff: { maxBytes: 65536, maxFileBytes: 8192 },
50
+ bash: { implementAllowlist: [] },
51
+ }
52
+
53
+ // Providers whose sessions can be metered AND permission-gated read-only (S-2
54
+ // design matrix). audit workers must be one of these.
55
+ const AUDIT_ELIGIBLE_PROVIDERS = new Set(['claude-sdk', 'claude-byok', 'codex'])
56
+
57
+ // #7036: providers vetted for the ARCHITECT role. The members coincide with
58
+ // AUDIT_ELIGIBLE_PROVIDERS today but the REASON is different, so this is named
59
+ // separately rather than aliased — the two can diverge without one silently
60
+ // re-opening the other's hole.
61
+ //
62
+ // The architect drives TurnDriver, which treats any `result` as turn-terminal.
63
+ // `claude-cli` emits a SYNTHETIC result on an intentional stop
64
+ // (`cli-session._emitInterruptedTurnResult`, fired BEFORE `stopped`), and
65
+ // TurnDriver cannot distinguish it from a real one. Two consequences: an
66
+ // interrupted architect turn resolves as COMPLETED, so the decision parser reads
67
+ // a truncated plan/review as authoritative; and since #7033 the trailing
68
+ // `stopped` lands on the NEXT queued turn and rejects it TURN_STOPPED — and
69
+ // committee reviews serialise on the architect session, so a queued turn there
70
+ // is the normal case, not an edge case.
71
+ //
72
+ // PRECISELY what this closes, and what it does NOT:
73
+ //
74
+ // CLOSED — the queued-turn kill. Only claude-cli emits `result` THEN `stopped`
75
+ // for one interrupt, so only claude-cli can settle turn 1 and have the trailing
76
+ // `stopped` land on turn 2. None of the three below emit `stopped` after a
77
+ // `result`, so excluding claude-cli removes this failure by construction.
78
+ //
79
+ // CLOSED (#7072) — false success on an interrupted turn, for claude-sdk and
80
+ // claude-byok. A `result` payload carries `interrupted: true` when the turn
81
+ // ended by abort/interrupt/stall rather than completion, and TurnDriver rejects
82
+ // it (TURN_STOPPED, or TURN_ERROR for a stall) instead of resolving it:
83
+ // * claude-byok: an interrupt landing in the TOOL phase (not mid-stream) ends
84
+ // the loop at the `signal.aborted` check and emits its `result` marked
85
+ // stopped + interrupted.
86
+ // * claude-sdk: the stream-STALL synthetic `result` is marked interrupted and
87
+ // names the failure; a Stop the SDK answers with an `aborted_*` result is
88
+ // marked by BaseSession.emit for every result whose turnOutcome is `stopped`.
89
+ //
90
+ // NOT CLOSED — codex app-server. It ends an interrupted turn with
91
+ // `turn/completed`, which `_finishTurn` reports as a normal result without
92
+ // reading `turn.status` (the protocol's TurnStatus has an `interrupted` value).
93
+ // Whether the real binary answers `turn/interrupt` that way is unverified
94
+ // against a live process (#7072 follow-up), so an operator Stop on a codex
95
+ // architect session may still settle as a completed turn.
96
+ //
97
+ // So this set means "vetted to not kill the NEXT turn", and — for claude-sdk and
98
+ // claude-byok — "cannot report an interrupted turn as complete". Anything outside
99
+ // it is unvetted for either.
100
+ const ARCHITECT_ELIGIBLE_PROVIDERS = new Set(['claude-sdk', 'claude-byok', 'codex'])
101
+
102
+ // v1: write/implement workers are codex-ONLY. codexSandbox:'workspace-write' is a
103
+ // verified OS jail confining edits to the worktree; acceptEdits/allow rules are
104
+ // path-AGNOSTIC and do NOT confine paths, so sdk/byok can't be safely write-
105
+ // capable until their sandbox is verified (tracked in #6735). A run whose worker
106
+ // provider isn't implement-eligible has its implement subtasks coerced to audit.
107
+ const IMPLEMENT_ELIGIBLE_PROVIDERS = new Set(['codex'])
108
+
109
+ // Engine-side subtask states that end scheduling. 'escalated' is deliberately
110
+ // excluded — it awaits a user gate, so it must block synthesis.
111
+ //
112
+ // 'interrupted' (#7038) IS included: nothing will re-drive a stopped subtask on
113
+ // its own, so leaving it out would park the run forever waiting on a node that
114
+ // can no longer move — a hang, not a status bug. It stays resumable in the
115
+ // transition table (`interrupted -> briefing`, run-model.js); an explicit resume
116
+ // re-enters the loop, which is what makes it different from 'failed'.
117
+ const TERMINAL_SUBTASK_STATES = new Set(['done', 'failed', 'skipped', 'interrupted'])
118
+ function isTerminalSubtaskState(state) { return TERMINAL_SUBTASK_STATES.has(state) }
119
+
120
+ export class OrchestrationManager extends EventEmitter {
121
+ /**
122
+ * @param {{
123
+ * sessionManager: any, ledger: any, turnDriver: any, permissionGateFactory?: Function,
124
+ * config?: object, roles?: object, validateCwd?: (cwd: string) => (string|null),
125
+ * now?: () => number, log?: object,
126
+ * }} opts
127
+ */
128
+ constructor({ sessionManager, ledger, turnDriver, gitOps = null, permissionGateFactory = null, config = {}, roles = null, validateCwd = null, now = () => Date.now(), log = null }) {
129
+ super()
130
+ if (!sessionManager) throw new Error('OrchestrationManager requires a sessionManager')
131
+ if (!ledger) throw new Error('OrchestrationManager requires a ledger')
132
+ if (!turnDriver) throw new Error('OrchestrationManager requires a turnDriver')
133
+ this._sm = sessionManager
134
+ this._ledger = ledger
135
+ this._driver = turnDriver
136
+ const cfg = config.orchestration || config || {}
137
+ this._cfg = {
138
+ ...DEFAULTS,
139
+ ...cfg,
140
+ diff: { ...DEFAULTS.diff, ...(cfg.diff || {}) },
141
+ bash: { ...DEFAULTS.bash, ...(cfg.bash || {}) },
142
+ }
143
+ this._gitOps = gitOps || createGitOps()
144
+ this._roles = roles || cfg.roles || null
145
+ this._validateCwd = validateCwd
146
+ this._now = now
147
+ this._log = log
148
+ this._runs = new Map() // runId -> engine state
149
+ // #7142: the backgrounded `startRun` promises `createAndStartRun` launches.
150
+ // A start is a multi-minute architect turn that nothing awaits, so without a
151
+ // handle `dispose()` could neither wait for it nor tell it the manager is
152
+ // gone. Each entry removes itself when it settles (it never rejects).
153
+ this._starts = new Set()
154
+ this._reports = new Map() // runId -> the architect's synthesis narrative markdown
155
+ this._reportDocs = new Map() // runId -> { json, markdown } — the persisted M-4 report artifacts
156
+ this._maxReports = 32
157
+ // Final wire-projected snapshots for terminal runs (their engine state is
158
+ // deleted from _runs, so gates/timeline would otherwise be gone). Bounded.
159
+ this._completedSnapshots = new Map() // runId -> { seq, run: RunDetail }
160
+ this._maxCompletedSnapshots = 32
161
+ this._maxSessions = Number.isFinite(config.maxSessions) ? config.maxSessions : 5
162
+
163
+ // #6733: a run stalled on session capacity has NOTHING in flight, so no
164
+ // internal event will ever re-drive its scheduler. Subscribe unconditionally
165
+ // (rather than arming on the first stall and disarming on recovery) — the
166
+ // handler is a no-op walk of `_runs` when nothing is stalled, and arm/disarm
167
+ // bookkeeping is exactly how a stall state latches. Removed in dispose().
168
+ this._disposed = false
169
+ this._onSessionFreed = () => this._onSessionCapacityFreed()
170
+ if (typeof sessionManager.on === 'function') sessionManager.on('session_destroyed', this._onSessionFreed)
171
+
172
+ // Owned-session registry drives the permission gate (answers ONLY our sessions).
173
+ if (permissionGateFactory) {
174
+ this._gate = permissionGateFactory({
175
+ sessionManager,
176
+ isOwnedSession: (sid) => this._isOwnedSession(sid),
177
+ policyForSession: (sid) => this._roleClassForSession(sid),
178
+ emitEscalation: (info) => this._onPermissionEscalation(info),
179
+ bashAllowlist: this._cfg.bash.implementAllowlist || [],
180
+ log,
181
+ })
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Tear the engine down. Everything that stops the manager from touching its
187
+ * collaborators happens SYNCHRONOUSLY, before this returns: `_disposed` is set
188
+ * first, and `_failRun`, the background-start handlers and `startRun`'s
189
+ * post-plan continuation all check it (#7142). So a start still in flight
190
+ * when the manager goes away can no longer journal onto — or log through — a
191
+ * torn-down ledger/log, whether or not the caller waits.
192
+ *
193
+ * The returned promise resolves once every backgrounded start has settled.
194
+ * An in-flight start only settles when its architect turn does, and the turn
195
+ * is the TurnDriver's to abort, not this class's — the driver is injected and
196
+ * its owner disposes it (`dispose()` rejects in-flight turns SESSION_GONE).
197
+ * Dispose the driver BEFORE awaiting this, and before disposing the ledger the
198
+ * start would otherwise journal to.
199
+ *
200
+ * @returns {Promise<void>}
201
+ */
202
+ dispose() {
203
+ this._disposed = true
204
+ if (this._onSessionFreed && typeof this._sm.off === 'function') this._sm.off('session_destroyed', this._onSessionFreed)
205
+ this._onSessionFreed = null
206
+ this._gate?.dispose?.()
207
+ return Promise.allSettled([...this._starts]).then(() => undefined)
208
+ }
209
+
210
+ // --- status writes: the FSM choke point (#6732) --------------------------
211
+ //
212
+ // EVERY run/subtask status the engine journals goes through one of these two
213
+ // methods, and nothing else in this file may call `this._ledger.setStatus` /
214
+ // `this._ledger.updateSubtask` directly. run-model's transition tables are the
215
+ // contract; before #6732 they were exported but never invoked, so an engine
216
+ // bug that produced e.g. `planning -> synthesizing` or `pending -> done` was
217
+ // journaled silently. A guard wired into only SOME write paths is worse than
218
+ // none — it advertises coverage it does not have — hence the single choke
219
+ // point (asserted by orchestration-transition-guards.test.js, which fails if a
220
+ // second raw call site appears).
221
+ //
222
+ // Posture is FAIL-CLOSED: an illegal transition throws TransitionError
223
+ // (code ILLEGAL_TRANSITION) and nothing is written. The transition tables
224
+ // enumerate FORWARD PROGRESS only; the error terminals (`failed`, `cancelled`,
225
+ // `cancelling`, `interrupted`, `suspended`) are legal from any non-terminal
226
+ // state, so a teardown path can never be wedged by the guard it just tripped.
227
+
228
+ /** Journal a run status change, asserting the transition first. Also advances
229
+ * the engine's `run.phase` mirror so the two can't drift. */
230
+ _setRunStatus(run, next, reason = null) {
231
+ const record = this._ledger.getRun(run.runId)
232
+ // No record (evicted/never created) → the ledger write is a no-op, so there
233
+ // is no transition to validate and nothing to journal.
234
+ if (record) assertRunTransition(record.status, next)
235
+ run.phase = next
236
+ return this._ledger.setStatus(run.runId, next, reason)
237
+ }
238
+
239
+ /** Journal a subtask status change, asserting the transition first. */
240
+ _setSubtaskStatus(run, subtaskId, next) {
241
+ const st = this._ledger.getRun(run.runId)?.subtasks?.find((s) => s.subtaskId === subtaskId)
242
+ if (st) assertNodeTransition(st.status, next)
243
+ return this._ledger.updateSubtask(run.runId, subtaskId, { status: next })
244
+ }
245
+
246
+ // --- run creation --------------------------------------------------------
247
+
248
+ createRun({ title = '', goal = null, cwd, preset = null, budgetUsd = null, autoApprovePlan = false, roleOverrides = null } = {}) {
249
+ if (!cwd || typeof cwd !== 'string') throw new Error('createRun requires a cwd')
250
+ if (this._validateCwd) {
251
+ const cwdError = this._validateCwd(cwd)
252
+ if (cwdError) throw new Error(`invalid cwd: ${cwdError}`)
253
+ }
254
+ if (this._runs.size > 0) throw new Error('a run is already active (one run at a time in v1)')
255
+
256
+ const presetDef = preset ? presetFor(preset) : null
257
+ const effectiveGoal = goal || presetDef?.goalTemplate || null
258
+ if (!effectiveGoal) throw new Error('createRun requires a goal or a preset that provides one')
259
+
260
+ const roleModels = this._resolveRoles(roleOverrides)
261
+ const implementEligible = IMPLEMENT_ELIGIBLE_PROVIDERS.has(roleModels.worker.provider)
262
+ const configSnapshot = {
263
+ cwd,
264
+ roleModels,
265
+ budget: { maxUsd: Number.isFinite(budgetUsd) ? budgetUsd : null, warnPercent: 80 },
266
+ }
267
+ const record = this._ledger.createRun({ title: title || (presetDef?.name ?? 'orchestration run'), preset, configSnapshot })
268
+ const runId = record.runId
269
+
270
+ this._runs.set(runId, {
271
+ runId,
272
+ cwd,
273
+ goal: effectiveGoal,
274
+ preset: presetDef,
275
+ autoApprovePlan: autoApprovePlan === true,
276
+ roleModels,
277
+ implementEligible, // codex-only in v1 (#6735) — else implement subtasks coerce to audit
278
+ architectSessionId: null,
279
+ ownedSessions: new Map(), // sessionId -> { role: 'architect'|'audit'|'implement'|'fixup', subtaskId }
280
+ gates: new Map(), // gateId -> gate
281
+ subtasks: new Map(), // subtaskId -> { iterations, poa, result, state, role, branch, baseSha, worktreePath }
282
+ results: [], // accepted { title, summary }
283
+ integration: null, // { worktreePath, branch, merged: [] } — lazily created on first accepted implement subtask
284
+ mergeChain: Promise.resolve(), // per-run mutex serializing integration-worktree ops (create/merge/abort)
285
+ timeline: [], // [RunTimelineEntry] activity feed (gate opens/resolves + committee reviews)
286
+ timelineSeq: 0, // monotonic per-run seq for timeline entries
287
+ wireSeq: 0, // per-run wire delta seq (bumped on successful broadcast in E-4 part 3)
288
+ phase: 'created',
289
+ cancelled: false,
290
+ })
291
+ return record
292
+ }
293
+
294
+ _resolveRoles(overrides) {
295
+ const base = this._roles || {}
296
+ const merged = { ...base, ...(overrides || {}) }
297
+ const architect = merged.architect
298
+ const worker = merged.auditWorker || merged.worker
299
+ if (!architect?.provider || !architect?.model) throw new Error('orchestration roles.architect must set { provider, model }')
300
+ if (!worker?.provider || !worker?.model) throw new Error('orchestration roles.worker/auditWorker must set { provider, model }')
301
+ // NOTE: this runs at createRun only. A future resume path (#6743) will carry
302
+ // `configSnapshot.roleModels` persisted BEFORE this gate existed, so a
303
+ // pre-#7036 record could reintroduce a claude-cli architect — re-validate
304
+ // there too rather than trusting the snapshot.
305
+ if (!ARCHITECT_ELIGIBLE_PROVIDERS.has(architect.provider)) {
306
+ throw new Error(`architect provider '${architect.provider}' is not vetted for turn-terminal semantics (use ${[...ARCHITECT_ELIGIBLE_PROVIDERS].join('/')})`)
307
+ }
308
+ if (!AUDIT_ELIGIBLE_PROVIDERS.has(worker.provider)) {
309
+ throw new Error(`audit worker provider '${worker.provider}' cannot be permission-gated read-only (use ${[...AUDIT_ELIGIBLE_PROVIDERS].join('/')})`)
310
+ }
311
+ return { architect, worker }
312
+ }
313
+
314
+ // --- lifecycle -----------------------------------------------------------
315
+
316
+ async startRun(runId) {
317
+ const run = this._get(runId)
318
+ if (run.phase !== 'created') throw new Error(`run ${runId} already started (phase ${run.phase})`)
319
+ this._setRunStatus(run, 'planning')
320
+ // Announce the run the moment it starts planning. Before #7138 the first
321
+ // delta a new run ever produced was the epic_plan gate below — the far side
322
+ // of a multi-minute architect turn — which was invisible while nothing could
323
+ // start a run at all. Now that starts work, that gap is what the operator
324
+ // sees: the dashboard closes its new-run modal on the ack and waits for the
325
+ // list delta to bring the run in, so without this the runs list stays empty
326
+ // for minutes after a successful start.
327
+ this._emitRunDelta(run)
328
+ let plan
329
+ try {
330
+ plan = await this._plan(run)
331
+ } catch (err) {
332
+ // The owner disposed the manager (and so its TurnDriver) mid-plan: the
333
+ // turn rejecting SESSION_GONE is the teardown, not a plan failure, and
334
+ // there is no ledger left to journal it to (#7142).
335
+ if (this._disposed) return { runId, phase: run.phase }
336
+ return this._failRun(run, `PLAN_${err instanceof DecisionParseError ? 'PARSE' : 'FAILED'}`, err)
337
+ }
338
+ // A cancel that landed while this turn was in flight wins. Destroying a
339
+ // session normally rejects its turn (SESSION_GONE), but a plan that resolves
340
+ // in the window between `run.cancelled = true` and the destroy lands here
341
+ // instead — and journals subtasks onto a run the ledger has already recorded
342
+ // as cancelled. (`_setRunStatus` below would then trip the FSM guard, so the
343
+ // record ends up with phantom subtasks AND a rejected startRun.) `_runSubtask`
344
+ // makes the same re-check after its awaits.
345
+ if (run.cancelled) return { runId, phase: run.phase }
346
+ // Same for a dispose (#7142): the plan resolved after the manager went away,
347
+ // and everything below journals to a ledger its owner is about to (or has
348
+ // already) disposed.
349
+ if (this._disposed) return { runId, phase: run.phase }
350
+ // Materialize subtasks. A subtask runs 'implement' (write-capable) ONLY when
351
+ // the architect asked for it AND the run's worker provider is
352
+ // implement-eligible (codex, #6735) AND no preset forces audit. Otherwise it
353
+ // is coerced to read-only 'audit' — labeling it worker.implement while it
354
+ // actually runs read-only would make the run record lie.
355
+ for (const spec of plan.subtasks) {
356
+ const subtaskId = `st_${randomBytes(4).toString('hex')}`
357
+ const wantsImplement = spec.role === 'implement'
358
+ const role = run.preset?.forceRole ?? (wantsImplement && run.implementEligible ? 'implement' : 'audit')
359
+ if (wantsImplement && role !== 'implement') {
360
+ this._log?.warn?.(`orchestration: subtask "${spec.title}" requested implement; coerced to audit (${run.preset?.forceRole ? 'preset forces audit' : 'worker provider not implement-eligible'})`)
361
+ }
362
+ this._ledger.createSubtask(runId, { subtaskId, role: `worker.${role}`, title: spec.title })
363
+ run.subtasks.set(subtaskId, { iterations: 0, spec: { ...spec, role }, state: 'pending', poa: null, result: null, branch: null, baseSha: null, worktreePath: null })
364
+ }
365
+
366
+ if (run.autoApprovePlan) {
367
+ return this._beginExecuting(run)
368
+ }
369
+ // open the epic_plan user gate — the spend gate
370
+ const gate = this._openGate(run, { kind: 'epic_plan', summary: `Approve the ${run.subtasks.size}-subtask audit plan`, detail: plan.summary ?? null })
371
+ this._setRunStatus(run, 'plan_review')
372
+ this.emit('gate_opened', { runId, gate })
373
+ this._emitRunDelta(run, { gate })
374
+ return { runId, phase: 'plan_review', gateId: gate.gateId }
375
+ }
376
+
377
+ /**
378
+ * The WS surface's entry point (#7138): mint the run, then drive it — returning
379
+ * as soon as the run EXISTS, not when planning finishes.
380
+ *
381
+ * `startRun` awaits the architect's planning turn, which is a real model call
382
+ * measured in minutes. The surface cannot await that: the ack is documented as
383
+ * carrying "the newly-minted runId" (surface.md, ServerOrchestrationActionAckSchema)
384
+ * and the dashboard holds its pending-action spinner until the ack arrives with
385
+ * no timeout of its own. Everything after the mint reaches clients through the
386
+ * run_delta broadcasts instead.
387
+ *
388
+ * Validation therefore splits by WHEN it can be known: `createRun`'s rejections
389
+ * (bad cwd, no goal, a run already active) are synchronous, so the caller can
390
+ * report them and nothing is created. A failure once the run exists is journaled
391
+ * onto the run — the same path any in-flight failure takes — so a client holding
392
+ * the runId learns of it from the run's own status rather than from a reply it
393
+ * has already received.
394
+ */
395
+ createAndStartRun(opts = {}) {
396
+ const record = this.createRun(opts)
397
+ const start = this.startRun(record.runId)
398
+ .catch((err) => {
399
+ // The run may already be gone (cancelled, or _failRun ran inside startRun).
400
+ const run = this._runs.get(record.runId)
401
+ if (!run || this._disposed) return null
402
+ return this._failRun(run, 'START_FAILED', err)
403
+ })
404
+ .catch((err) => {
405
+ // A disposed manager's log/ledger belong to someone else now (#7142).
406
+ if (this._disposed) return
407
+ this._log?.warn?.(`orchestration: run ${record.runId} failed to start and could not be journaled: ${err?.message || String(err)}`)
408
+ })
409
+ // Track it so `dispose()` can wait for it (#7142). `start` should never reject, but if
410
+ // the final handler itself throws, removal still runs and no derived promise
411
+ // is left rejecting unhandled.
412
+ this._starts.add(start)
413
+ const forget = () => { this._starts.delete(start) }
414
+ start.then(forget, forget)
415
+ return record
416
+ }
417
+
418
+ /**
419
+ * Wire-level run control (`orchestration_run_action`). `cancel` is the only
420
+ * action this engine implements, and the only one the wire schema carries
421
+ * (#7140). `pause`/`resume` have no user-driven implementation —
422
+ * `_pauseForBudget`/`_pauseForResources` are internal stalls the scheduler
423
+ * clears itself, not a pause a client can hold — so the schema no longer
424
+ * admits them. This refusal stays as the engine's own backstop for a caller
425
+ * that reaches it without the wire validator: fail loudly rather than ack a
426
+ * no-op.
427
+ */
428
+ async runAction(runId, action) {
429
+ if (action === 'cancel') {
430
+ const result = await this.cancelRun(runId, { reason: 'user' })
431
+ // cancelRun answers null for an unknown run; acking that would report a
432
+ // cancel that never happened.
433
+ if (!result) throw new Error(`run ${runId} not found`)
434
+ return result
435
+ }
436
+ const err = new Error(`run action '${action}' is not supported by this engine`)
437
+ err.code = 'ACTION_UNSUPPORTED'
438
+ throw err
439
+ }
440
+
441
+ async _plan(run) {
442
+ const sessionId = this._spawnSession(run, { role: 'architect' })
443
+ run.architectSessionId = sessionId
444
+ run.ownedSessions.set(sessionId, { role: 'architect', subtaskId: null })
445
+ // The architect reads/greps the repo to plan and review; it never edits.
446
+ // Give it the same read-only rules as workers so its Read/Glob/Grep are
447
+ // settled without prompting (else — with no rules and the gate deliberately
448
+ // deny-only for it — a read request would wedge until the turn watchdog
449
+ // fires and fails the run). Anything else it emits (Bash) hits the gate.
450
+ this._applyReadOnlyRules(sessionId)
451
+ const repoMap = ''
452
+ const prompt = buildPlanPrompt({ goal: run.goal, repoMap, maxSubtasks: 8 })
453
+ const { decision } = await this._driveDecision(run, sessionId, prompt, 'epic_plan', 'plan', null)
454
+ return decision
455
+ }
456
+
457
+ async resolveGate(runId, gateId, { decision, note = null, budgetUsd = null } = {}) {
458
+ const run = this._get(runId)
459
+ const gate = run.gates.get(gateId)
460
+ if (!gate) {
461
+ const err = new Error(`gate ${gateId} not found`)
462
+ err.code = 'GATE_NOT_FOUND'
463
+ throw err
464
+ }
465
+ const resolved = resolveGateModel(gate, { decision, note, budgetUsd, resolvedAt: this._now() })
466
+ run.gates.set(gateId, resolved)
467
+ this._appendTimeline(run, { kind: 'gate_resolved', gateId, nodeId: gate.nodeId ?? null, summary: `${gate.kind} gate ${decision}`, detail: note })
468
+ this.emit('gate_resolved', { runId, gate: resolved })
469
+ this._emitRunDelta(run, { gate: resolved })
470
+
471
+ if (gate.kind === 'epic_plan') {
472
+ if (decision === 'approve') return this._beginExecuting(run)
473
+ // Any non-approve decision on the plan (reject, revise, skip) declines it,
474
+ // and a declined plan is a cancellation, not a failure (design §3.2:
475
+ // plan_review --reject--> cancelled; #7131). The reason code tells it apart
476
+ // from a manual cancel ('user'); the reviewer's note is already journaled on
477
+ // the gate_resolved timeline entry.
478
+ return this.cancelRun(run.runId, { reason: 'plan_rejected' })
479
+ }
480
+ if (gate.kind === 'escalation') {
481
+ return this._resolveEscalation(run, gate, decision, note)
482
+ }
483
+ return { runId, gateId, decision }
484
+ }
485
+
486
+ _beginExecuting(run) {
487
+ this._setRunStatus(run, 'executing')
488
+ this._schedule(run)
489
+ return { runId: run.runId, phase: 'executing' }
490
+ }
491
+
492
+ // --- scheduler -----------------------------------------------------------
493
+
494
+ _schedule(run) {
495
+ if (run.cancelled) return
496
+ // `resource_paused` (#6733) is a STALL, not a stop — the scheduler MUST be
497
+ // able to re-enter it, both when a freed session slot re-arms it and when a
498
+ // gate resolution retires the last pending subtask while it is stalled.
499
+ // Early-returning on it instead would latch the pause: with zero workers in
500
+ // flight there is no other event that ever re-drives this run.
501
+ if (run.phase !== 'executing' && run.phase !== 'resource_paused') return
502
+ const all = [...run.subtasks.values()]
503
+ // Ready to synthesize only when EVERY subtask is terminal. 'escalated' is
504
+ // NOT terminal — it blocks synthesis until the user resolves its gate, so a
505
+ // sibling escalation can't let the run synthesize with a hole in it.
506
+ if (all.every((s) => isTerminalSubtaskState(s.state))) {
507
+ this._synthesize(run).catch((err) => this._failRun(run, 'SYNTHESIS_FAILED', err))
508
+ return
509
+ }
510
+ const pending = [...run.subtasks.entries()].filter(([, s]) => s.state === 'pending')
511
+ for (const [subtaskId] of pending) {
512
+ if (this._activeWorkerCount(run) >= this._cfg.maxParallelWorkers) break
513
+ if (!this._sessionHeadroom()) {
514
+ // #6733 — a stall needs ALL THREE: pending work (we are inside the
515
+ // pending loop, and this subtask is still `pending`), ZERO workers in
516
+ // flight, and no headroom. With a worker still running this is ordinary
517
+ // saturation — its completion re-enters _schedule — and pausing there
518
+ // would fire on most runs and train the operator to ignore the state.
519
+ if (this._activeWorkerCount(run) === 0) this._pauseForResources(run)
520
+ break
521
+ }
522
+ // Headroom is back, so the stall condition no longer holds. Clear it
523
+ // BEFORE any other pause/spawn decision so the state never lies and the
524
+ // next status write (a budget pause, say) starts from `executing`.
525
+ this._clearResourcePause(run)
526
+ const budget = this._ledger.evaluateBudget(run.runId, { role: 'worker.audit' })
527
+ if (budget && budget.ok === false) { this._pauseForBudget(run); break }
528
+ const st = run.subtasks.get(subtaskId)
529
+ st.state = 'active'
530
+ this._runSubtask(run, subtaskId).catch((err) => {
531
+ // #7038 — a DELIBERATE stop is not a crash. TurnDriver already gives an
532
+ // interrupt its own code (TURN_STOPPED, #7009) and run-model already
533
+ // declares an `interrupted` node state; this arm mapped every thrown
534
+ // turn to `failed`, so nothing ever wrote it and an operator Stop was
535
+ // recorded exactly like a worker that blew up. `interrupted` is also the
536
+ // resumable one (`interrupted -> briefing`), so the mislabel discarded
537
+ // the only thing that distinguishes the two.
538
+ const interrupted = err instanceof TurnError && err.code === 'TURN_STOPPED'
539
+ if (interrupted) this._log?.info?.(`subtask ${subtaskId} interrupted: ${err?.message || err}`)
540
+ else this._log?.warn?.(`subtask ${subtaskId} crashed: ${err?.message || err}`)
541
+ this._finishSubtask(run, subtaskId, interrupted ? 'interrupted' : 'failed').catch(() => {})
542
+ })
543
+ }
544
+ }
545
+
546
+ async _runSubtask(run, subtaskId) {
547
+ const st = run.subtasks.get(subtaskId)
548
+ let sessionId = await this._spawnWorker(run, subtaskId)
549
+
550
+ let feedback = null
551
+ // committee loop for this subtask
552
+ while (true) {
553
+ // Bail if the run was cancelled/torn down while an await was in flight —
554
+ // don't drive more turns or write status on a dead run.
555
+ if (run.cancelled || !this._runs.has(run.runId)) return null
556
+ // `iterations` counts committee round-trips already spent; at the cap we
557
+ // stop and escalate rather than looping forever on a stubborn subtask.
558
+ if (st.iterations >= this._cfg.maxCommitteeIterations) {
559
+ return this._escalateSubtask(run, subtaskId, 'committee iteration cap exceeded')
560
+ }
561
+ // 1) plan-of-attack. This is also the loop's re-entry point after a revise
562
+ // or a redelegate, so it owns the `briefing` write for every path.
563
+ this._setSubtaskStatus(run, subtaskId, 'briefing')
564
+ const poa = await this._driveDecision(run, sessionId, buildPoaPrompt({ subtask: st.spec }), 'plan_of_attack', 'poa', subtaskId).then((r) => r.decision)
565
+ st.poa = poa
566
+ // 2) architect reviews the PoA (usage attributed to architect.review, NOT
567
+ // the subtask cell — see _architectReview)
568
+ this._setSubtaskStatus(run, subtaskId, 'poa_review')
569
+ const poaReview = await this._architectReview(run, buildPoaReviewPrompt({ subtask: st.spec, poa }), 'poa_review')
570
+ this._ledger.recordCommitteeReview(run.runId, subtaskId, { phase: 'plan', verdict: poaReview.verdict, reviewerSessionId: run.architectSessionId, notes: poaReview.feedback ?? '' })
571
+ this._appendTimeline(run, { kind: 'committee_review', nodeId: subtaskId, verdict: poaReview.verdict, summary: `plan-of-attack ${poaReview.verdict}`, detail: poaReview.feedback ?? null })
572
+ if (poaReview.verdict === 'escalate') return this._escalateSubtask(run, subtaskId, poaReview.feedback || 'architect escalated the plan')
573
+ if (poaReview.verdict === 'revise' || poaReview.verdict === 'redelegate') {
574
+ st.iterations += 1
575
+ feedback = poaReview.feedback ?? null
576
+ if (poaReview.verdict === 'redelegate') sessionId = await this._respawnWorker(run, subtaskId, sessionId)
577
+ continue
578
+ }
579
+ // 3) execute
580
+ this._setSubtaskStatus(run, subtaskId, 'executing')
581
+ const result = await this._driveDecision(run, sessionId, buildExecutePrompt({ subtask: st.spec, feedback }), 'work_result', 'execute', subtaskId).then((r) => r.decision)
582
+ st.result = result
583
+ // 3b) implement subtasks: commit the worktree and compute a review diff so
584
+ // the architect reviews the ACTUAL change, not just the worker's summary.
585
+ const diff = st.spec.role === 'implement' ? await this._commitAndDiff(run, subtaskId, sessionId) : null
586
+ // 4) architect reviews the result (+ diff for implement)
587
+ this._setSubtaskStatus(run, subtaskId, 'result_review')
588
+ const resultReview = await this._architectReview(run, buildResultReviewPrompt({ subtask: st.spec, result, diff }), 'result_review')
589
+ this._ledger.recordCommitteeReview(run.runId, subtaskId, { phase: 'result', verdict: resultReview.verdict, reviewerSessionId: run.architectSessionId, notes: resultReview.feedback ?? '' })
590
+ this._appendTimeline(run, { kind: 'committee_review', nodeId: subtaskId, verdict: resultReview.verdict, summary: `result ${resultReview.verdict}`, detail: resultReview.feedback ?? null })
591
+ if (resultReview.verdict === 'approve') {
592
+ if (st.spec.role === 'implement') return await this._acceptImplement(run, subtaskId, sessionId, result)
593
+ run.results.push({ title: st.spec.title, summary: result.summary })
594
+ await this._destroySession(run, sessionId)
595
+ return this._finishSubtask(run, subtaskId, 'done')
596
+ }
597
+ if (resultReview.verdict === 'escalate') return this._escalateSubtask(run, subtaskId, resultReview.feedback || 'architect escalated the result')
598
+ // revise / redelegate → loop with feedback (redelegate gets a fresh worker)
599
+ st.iterations += 1
600
+ feedback = resultReview.feedback ?? null
601
+ if (resultReview.verdict === 'redelegate') sessionId = await this._respawnWorker(run, subtaskId, sessionId)
602
+ }
603
+ }
604
+
605
+ // Spawn + register + rule-gate + attach a worker session for a subtask.
606
+ async _spawnWorker(run, subtaskId) {
607
+ const st = run.subtasks.get(subtaskId)
608
+ const role = st.spec.role === 'implement' ? 'implement' : 'audit'
609
+ // `spawning` (design §3.3: pending -> spawning -> briefing) — the worker
610
+ // session does not exist yet, so this state, not `briefing`, is what the
611
+ // subtask is actually in while createSession + worktree setup run (and it is
612
+ // what a SessionLimitError throw leaves behind). `briefing` is written by
613
+ // the committee loop's first step, immediately after this returns.
614
+ this._setSubtaskStatus(run, subtaskId, 'spawning')
615
+ const sessionId = this._spawnSession(run, { role, subtaskId })
616
+ run.ownedSessions.set(sessionId, { role, subtaskId })
617
+ if (role === 'implement') {
618
+ // The write worker got an isolated worktree (worktree:true) — put it on a
619
+ // named branch and record the branch-point so the review diff + merge are
620
+ // reproducible. Its writes are confined by the OS sandbox (codex
621
+ // workspace-write), NOT by permission rules, so we do NOT apply read-only
622
+ // rules (they would deny the edits acceptEdits is meant to allow).
623
+ const worktreePath = this._workerWorktreePath(sessionId)
624
+ st.worktreePath = worktreePath
625
+ if (worktreePath) {
626
+ const branchName = `chroxy/orch/${run.runId}/${subtaskId}`
627
+ try {
628
+ const branchExists = await this._gitOps.branchExists(worktreePath, branchName)
629
+ if (branchExists.exists) await this._gitOps.deleteBranch(worktreePath, branchName)
630
+ const { branch, baseSha } = await this._gitOps.createBranch(worktreePath, branchName)
631
+ st.branch = branch
632
+ st.baseSha = baseSha
633
+ } catch (err) {
634
+ this._log?.warn?.(`orchestration: createBranch failed for ${subtaskId}: ${err?.message || err}`)
635
+ }
636
+ }
637
+ } else {
638
+ this._applyReadOnlyRules(sessionId)
639
+ }
640
+ this._ledger.attachSession(run.runId, subtaskId, { sessionId, provider: run.roleModels.worker.provider, model: run.roleModels.worker.model, meterable: true })
641
+ return sessionId
642
+ }
643
+
644
+ // redelegate: tear down the current worker and hand the subtask to a fresh one.
645
+ async _respawnWorker(run, subtaskId, oldSessionId) {
646
+ await this._destroySession(run, oldSessionId)
647
+ this._setSubtaskStatus(run, subtaskId, 'respawning')
648
+ return this._spawnWorker(run, subtaskId)
649
+ }
650
+
651
+ // Release every session a subtask still owns (worker + any fixup). Awaits the
652
+ // auto-commit-before-destroy of an implement worktree so no work is lost.
653
+ async _releaseSubtaskSessions(run, subtaskId) {
654
+ for (const [sid, meta] of [...run.ownedSessions]) {
655
+ if (meta.subtaskId === subtaskId && meta.role !== 'architect') await this._destroySession(run, sid)
656
+ }
657
+ }
658
+
659
+ async _finishSubtask(run, subtaskId, status) {
660
+ if (run.cancelled || !this._runs.has(run.runId)) return
661
+ const st = run.subtasks.get(subtaskId)
662
+ if (st) st.state = status
663
+ this._setSubtaskStatus(run, subtaskId, status)
664
+ await this._releaseSubtaskSessions(run, subtaskId)
665
+ this._schedule(run)
666
+ }
667
+
668
+ async _escalateSubtask(run, subtaskId, reason) {
669
+ const st = run.subtasks.get(subtaskId)
670
+ if (st) st.state = 'escalated'
671
+ this._setSubtaskStatus(run, subtaskId, 'escalated')
672
+ // Free this subtask's worker so a pending sibling can take the slot while
673
+ // the user resolves the escalation gate (auto-commits implement work first).
674
+ await this._releaseSubtaskSessions(run, subtaskId)
675
+ const gate = this._openGate(run, { kind: 'escalation', nodeId: subtaskId, summary: `Subtask "${st?.spec?.title ?? subtaskId}" escalated`, detail: reason })
676
+ this.emit('gate_opened', { runId: run.runId, gate })
677
+ this._emitRunDelta(run, { gate })
678
+ this._schedule(run)
679
+ return { runId: run.runId, subtaskId, escalated: true, gateId: gate.gateId }
680
+ }
681
+
682
+ async _resolveEscalation(run, gate, decision, note) {
683
+ const subtaskId = gate.nodeId
684
+ const st = subtaskId ? run.subtasks.get(subtaskId) : null
685
+ if (!st) return { runId: run.runId, resolved: true }
686
+ if (decision === 'skip') { await this._finishSubtask(run, subtaskId, 'skipped'); return { runId: run.runId, subtaskId, skipped: true } }
687
+ // The escalation verb is `fail-run` (engine.md §3.3): the user is deliberately
688
+ // failing the run, unlike a rejected plan, which cancels it (#7131).
689
+ if (decision === 'reject') return this._failRun(run, 'ESCALATION_REJECTED', new Error(note || 'user failed the run'))
690
+ // approve / revise → re-drive the subtask (iteration reset via a fresh worker)
691
+ st.state = 'pending'
692
+ st.iterations = 0
693
+ this._schedule(run)
694
+ return { runId: run.runId, subtaskId, retrying: true }
695
+ }
696
+
697
+ async _synthesize(run) {
698
+ this._setRunStatus(run, 'synthesizing')
699
+ const { decision } = await this._driveDecision(run, run.architectSessionId, buildSynthesisPrompt({ goal: run.goal, results: run.results }), 'synthesis', 'synthesis', null)
700
+ // Keep the architect's narrative in memory (it feeds the persisted report).
701
+ this._rememberReport(run.runId, decision.reportMarkdown)
702
+ await this._destroySession(run, run.architectSessionId)
703
+ // Remove the integration worktree; its branch (the run's output) is kept.
704
+ const integrationBranch = run.integration?.branch ?? null
705
+ await this._cleanupIntegration(run)
706
+ this._setRunStatus(run, 'completed')
707
+ // M-4: derive + persist report.{json,md} (metrics report with the synthesis
708
+ // narrative prepended) so the artifact survives restarts.
709
+ this._buildAndPersistReport(run.runId)
710
+ this.emit('run_completed', { runId: run.runId, reportMarkdown: decision.reportMarkdown, integrationBranch })
711
+ this._emitRunDelta(run)
712
+ this._cacheCompletedSnapshot(run)
713
+ this._runs.delete(run.runId)
714
+ return { runId: run.runId, phase: 'completed', reportMarkdown: decision.reportMarkdown, integrationBranch }
715
+ }
716
+
717
+ // --- turn driving + decisions -------------------------------------------
718
+
719
+ async _architectReview(run, prompt, kind) {
720
+ // subtaskId is intentionally null: the review turn's tokens belong to the
721
+ // architect.review role, NOT the subtask's own usage cell (which tracks the
722
+ // worker's cost). Folding it in would price the architect's turn with the
723
+ // worker's provider and spuriously flip the subtask's modelDrift flag. The
724
+ // review's LINK to the subtask is recorded separately via recordCommitteeReview.
725
+ const { decision } = await this._driveDecision(run, run.architectSessionId, prompt, kind, kind, null)
726
+ return decision
727
+ }
728
+
729
+ // --- implement (write) path ---------------------------------------------
730
+
731
+ // Auto-commit an implement worker's worktree and compute a capped review diff
732
+ // so the architect reviews the actual change.
733
+ async _commitAndDiff(run, subtaskId, sessionId) {
734
+ const st = run.subtasks.get(subtaskId)
735
+ const worktreePath = st.worktreePath || this._workerWorktreePath(sessionId)
736
+ if (!worktreePath || !st.baseSha) return null
737
+ try {
738
+ await this._gitOps.autoCommit({ worktreePath, subtaskId })
739
+ return await this._gitOps.computeCappedDiff({
740
+ repoDir: worktreePath, baseSha: st.baseSha, headRef: 'HEAD',
741
+ maxBytes: this._cfg.diff.maxBytes, maxFileBytes: this._cfg.diff.maxFileBytes,
742
+ })
743
+ } catch (err) {
744
+ this._log?.warn?.(`orchestration: commit/diff failed for ${subtaskId}: ${err?.message || err}`)
745
+ return null
746
+ }
747
+ }
748
+
749
+ // Accept an approved implement subtask: destroy the worker (auto-commits its
750
+ // OWN worktree — safe to run concurrently), then merge its branch into the
751
+ // run's integration worktree UNDER A PER-RUN LOCK so parallel accepts never
752
+ // overlap (create/merge/abort share one integration checkout — concurrent git
753
+ // merges would collide on index.lock and spuriously "fail"). Clean → done;
754
+ // conflict → abort + escalate (the automated fixup worker is E-3 part 3).
755
+ async _acceptImplement(run, subtaskId, sessionId, result) {
756
+ const st = run.subtasks.get(subtaskId)
757
+ this._setSubtaskStatus(run, subtaskId, 'merging')
758
+ await this._destroySession(run, sessionId)
759
+ if (!st.branch || !st.baseSha) return this._escalateSubtask(run, subtaskId, 'no branch/worktree to merge')
760
+ return this._withMergeLock(run, () => this._mergeAccepted(run, subtaskId, result))
761
+ }
762
+
763
+ // Serialize the integration-worktree critical section per run: chain each
764
+ // caller behind the previous one so at most one create/merge/abort runs at a
765
+ // time. This is what makes "sequential merge" real.
766
+ async _withMergeLock(run, fn) {
767
+ const prev = run.mergeChain
768
+ let release
769
+ run.mergeChain = new Promise((r) => { release = r })
770
+ await prev.catch(() => {})
771
+ try { return await fn() } finally { release() }
772
+ }
773
+
774
+ async _mergeAccepted(run, subtaskId, result) {
775
+ if (run.cancelled || !this._runs.has(run.runId)) return null
776
+ const st = run.subtasks.get(subtaskId)
777
+ const integration = await this._ensureIntegration(run, st.baseSha)
778
+ if (!integration) return this._escalateSubtask(run, subtaskId, 'could not create the integration worktree')
779
+ let merge
780
+ try {
781
+ merge = await this._gitOps.mergeNoFf({ integrationWorktree: integration.worktreePath, branch: st.branch, subtaskId })
782
+ } catch (err) {
783
+ return this._escalateSubtask(run, subtaskId, `merge failed: ${err?.message || err}`)
784
+ }
785
+ if (merge.ok) {
786
+ integration.merged.push(subtaskId)
787
+ run.results.push({ title: st.spec.title, summary: result.summary, branch: st.branch })
788
+ return this._finishSubtask(run, subtaskId, 'done')
789
+ }
790
+ try { await this._gitOps.abortMerge(integration.worktreePath) } catch { /* best-effort */ }
791
+ return this._escalateSubtask(run, subtaskId, `merge conflict in: ${(merge.conflictFiles || []).join(', ') || '(see git status)'}`)
792
+ }
793
+
794
+ // Lazily create the run's integration worktree on the first accepted implement
795
+ // subtask (audit-only / repo-audit runs never create one). Only ever called
796
+ // from within _withMergeLock, so the check-then-act is not a TOCTOU race.
797
+ async _ensureIntegration(run, baseSha) {
798
+ if (run.integration) return run.integration
799
+ const branchName = `chroxy/orch/${run.runId}/integration`
800
+ try {
801
+ const { worktreePath, branch } = await this._gitOps.createIntegrationWorktree({ repoDir: run.cwd, runId: run.runId, branchName, baseSha })
802
+ run.integration = { worktreePath, branch, merged: [] }
803
+ return run.integration
804
+ } catch (err) {
805
+ this._log?.warn?.(`orchestration: createIntegrationWorktree failed: ${err?.message || err}`)
806
+ return null
807
+ }
808
+ }
809
+
810
+ // Drive one turn and extract its decision, with a repair-reprompt ladder.
811
+ async _driveDecision(run, sessionId, prompt, kind, turnLabel, subtaskId) {
812
+ let attempt = 0
813
+ let currentPrompt = prompt
814
+ let lastError = null
815
+ while (attempt <= this._cfg.maxParseRetries) {
816
+ const { text, result } = await this._driver.driveTurn(sessionId, currentPrompt, { label: turnLabel, timeoutMs: this._cfg.turnTimeoutMs })
817
+ const roleClass = run.ownedSessions.get(sessionId)?.role ?? null
818
+ // dotted ledger role: architect plan/synthesis vs architect.review, worker.audit
819
+ const ledgerRole = roleClass === 'architect'
820
+ ? (turnLabel === 'poa_review' || turnLabel === 'result_review' ? 'architect.review' : 'architect')
821
+ : `worker.${roleClass}`
822
+ this._ledger.recordTurnUsage(run.runId, {
823
+ subtaskId, sessionId, role: ledgerRole, turnLabel, terminalEvent: 'result', data: result,
824
+ })
825
+ try {
826
+ return { decision: extractDecision(text, kind).decision }
827
+ } catch (err) {
828
+ lastError = err
829
+ attempt += 1
830
+ if (attempt > this._cfg.maxParseRetries) break
831
+ currentPrompt = buildRepairPrompt(kind, err) // cheap: context is cached
832
+ }
833
+ }
834
+ throw lastError || new DecisionParseError('no_block', 'exhausted parse retries')
835
+ }
836
+
837
+ // --- session spawn/teardown ---------------------------------------------
838
+
839
+ _spawnSession(run, { role, subtaskId = null }) {
840
+ const spec = role === 'architect' ? run.roleModels.architect : run.roleModels.worker
841
+ const preamble = role === 'architect' ? architectPreamble()
842
+ : role === 'implement' ? implementWorkerPreamble()
843
+ : auditWorkerPreamble()
844
+ const opts = {
845
+ name: `orch:${run.runId}:${role}${subtaskId ? `:${subtaskId}` : ''}`,
846
+ cwd: run.cwd,
847
+ provider: spec.provider,
848
+ model: spec.model,
849
+ // implement workers accept their own edits (path confinement comes from the
850
+ // OS sandbox, NOT permission rules); everyone else prompts (gate answers).
851
+ permissionMode: role === 'implement' ? 'acceptEdits' : 'approve',
852
+ sessionPreamble: preamble,
853
+ metadata: { orchestrationRunId: run.runId, orchestrationRole: role === 'architect' ? 'architect' : `worker.${role}` },
854
+ }
855
+ if (role === 'implement') {
856
+ // Fail-closed: the write jail is codex-only in v1 (#6735). createRun already
857
+ // gates this, but hard-assert at the spawn choke point so any future path
858
+ // that produced a non-codex implement role aborts loudly rather than
859
+ // spawning an UNSANDBOXED write worker (acceptEdits does not confine paths).
860
+ if (spec.provider !== 'codex') throw new Error(`implement worker requires a codex provider (write jail is codex-only in v1); got '${spec.provider}'`)
861
+ // Isolated write worktree + the OS write jail.
862
+ opts.worktree = true
863
+ opts.codexSandbox = 'workspace-write'
864
+ } else if (spec.provider === 'codex') {
865
+ opts.codexSandbox = 'read-only' // architect + audit are read-only (#6690)
866
+ }
867
+ const sessionId = this._sm.createSession(opts)
868
+ return sessionId
869
+ }
870
+
871
+ // The isolated worktree dir SessionManager created for a worktree:true session.
872
+ _workerWorktreePath(sessionId) {
873
+ const entry = this._sm.getSession?.(sessionId)
874
+ return entry?.worktreePath || entry?.session?.worktreePath || null
875
+ }
876
+
877
+ _applyReadOnlyRules(sessionId) {
878
+ const session = this._sm.getSession?.(sessionId)?.session
879
+ if (session && typeof session.setPermissionRules === 'function') {
880
+ session.setPermissionRules([
881
+ { tool: 'Read', decision: 'allow' }, { tool: 'Glob', decision: 'allow' }, { tool: 'Grep', decision: 'allow' },
882
+ { tool: 'Write', decision: 'deny' }, { tool: 'Edit', decision: 'deny' }, { tool: 'NotebookEdit', decision: 'deny' }, { tool: 'apply_patch', decision: 'deny' },
883
+ ])
884
+ }
885
+ }
886
+
887
+ // The single teardown choke point. For an implement worker, auto-commit its
888
+ // worktree FIRST — destroySession removes the worktree, which would delete
889
+ // uncommitted work. This covers every release path (accept, finish, escalate,
890
+ // redelegate, fail, cancel) at one site.
891
+ async _destroySession(run, sessionId) {
892
+ if (!sessionId) return
893
+ const meta = run.ownedSessions.get(sessionId)
894
+ if (meta?.role === 'implement' && meta.subtaskId) {
895
+ const st = run.subtasks.get(meta.subtaskId)
896
+ const worktreePath = st?.worktreePath || this._workerWorktreePath(sessionId)
897
+ if (worktreePath) {
898
+ try { await this._gitOps.autoCommit({ worktreePath, subtaskId: meta.subtaskId }) }
899
+ catch (err) { this._log?.warn?.(`orchestration: auto-commit before destroy failed for ${sessionId}: ${err?.message || err}`) }
900
+ }
901
+ }
902
+ run.ownedSessions.delete(sessionId)
903
+ try { this._sm.destroySession?.(sessionId) } catch { /* best-effort */ }
904
+ }
905
+
906
+ // --- helpers -------------------------------------------------------------
907
+
908
+ _openGate(run, { kind, nodeId = null, summary, detail = null, budgetUsd = null }) {
909
+ const gate = makeGate({ gateId: nextGateId(run.runId), runId: run.runId, kind, nodeId, summary, detail, budgetUsd, openedAt: this._now() })
910
+ run.gates.set(gate.gateId, gate)
911
+ this._appendTimeline(run, { kind: 'gate_opened', gateId: gate.gateId, nodeId, summary })
912
+ return gate
913
+ }
914
+
915
+ // Append a bounded activity-feed entry (projected to RunTimelineEntry by to-wire).
916
+ _appendTimeline(run, { kind, summary, nodeId = null, gateId = null, verdict = null, detail = null }) {
917
+ run.timelineSeq += 1
918
+ run.timeline.push({ seq: run.timelineSeq, at: this._now(), kind, summary, nodeId, gateId, verdict, detail })
919
+ if (run.timeline.length > 500) run.timeline.splice(0, run.timeline.length - 500)
920
+ }
921
+
922
+ // Build + emit a wire `orchestration_run_delta` for host-level clients (the
923
+ // daemon forwards it to WsServer._broadcastOrchestrationDelta). Carries the
924
+ // updated run header (RunSummary) + the changed gate. `wireSeq` is bumped per
925
+ // emit; a gap self-heals via the client re-requesting the full snapshot (the
926
+ // reducer applies a delta only when seq === held + 1). No-op for a gone run.
927
+ _emitRunDelta(run, { gate = null } = {}) {
928
+ const record = this._ledger.getRun(run.runId)
929
+ if (!record) return
930
+ run.wireSeq += 1
931
+ const delta = {
932
+ type: 'orchestration_run_delta',
933
+ runId: run.runId,
934
+ seq: run.wireSeq,
935
+ generatedAt: new Date(this._now()).toISOString(),
936
+ run: recordToRunSummary(record, this._snapshotExtras(run)),
937
+ }
938
+ if (gate) delta.gate = gateToWire(gate)
939
+ this.emit('run_delta', delta)
940
+ }
941
+
942
+ _pauseForBudget(run) {
943
+ this._setRunStatus(run, 'budget_paused')
944
+ this.emit('run_budget_paused', { runId: run.runId })
945
+ this._emitRunDelta(run)
946
+ }
947
+
948
+ // --- #6733: session-pool starvation --------------------------------------
949
+ //
950
+ // `_sessionHeadroom()` counts the daemon's TOTAL live sessions, not this run's
951
+ // own, so unrelated interactive sessions can leave a run unable to spawn ANY
952
+ // worker. Before this, `_schedule` just `break`ed: the run stayed in
953
+ // `executing` with pending subtasks, zero workers, and no gate — healthy-
954
+ // looking and permanently stuck. It now reports the stall, and — because
955
+ // nothing internal will ever re-drive a run with no work in flight — it
956
+ // re-checks on the only signal that capacity came back: a session going away.
957
+
958
+ /** Enter the stall. Callers must have established all three conditions. */
959
+ _pauseForResources(run) {
960
+ // No self-loop: a second pause while already stalled is not a state change
961
+ // (and `resource_paused -> resource_paused` is illegal by design).
962
+ if (run.phase === 'resource_paused') return
963
+ const live = this._liveSessionCount()
964
+ const detail = `${live}/${this._maxSessions} daemon sessions live (${this._cfg.reserveSessions} reserved) — no slot for the next worker`
965
+ this._setRunStatus(run, 'resource_paused', 'SESSION_POOL_EXHAUSTED')
966
+ this._appendTimeline(run, { kind: 'resource_paused', summary: 'waiting for session capacity', detail })
967
+ this.emit('run_resource_paused', {
968
+ runId: run.runId,
969
+ liveSessions: live,
970
+ maxSessions: this._maxSessions,
971
+ reserveSessions: this._cfg.reserveSessions,
972
+ })
973
+ this._emitRunDelta(run)
974
+ }
975
+
976
+ /** Leave the stall. No-op unless the run is actually stalled. */
977
+ _clearResourcePause(run) {
978
+ if (run.phase !== 'resource_paused') return
979
+ this._setRunStatus(run, 'executing')
980
+ this._appendTimeline(run, { kind: 'resource_resumed', summary: 'session capacity available — resuming' })
981
+ this.emit('run_resource_resumed', { runId: run.runId, liveSessions: this._liveSessionCount() })
982
+ this._emitRunDelta(run)
983
+ }
984
+
985
+ // A session — anyone's — went away, so the pool may have room again. Re-drive
986
+ // every stalled run's scheduler; `_schedule` re-checks headroom itself and
987
+ // clears the pause only if it can actually spawn.
988
+ //
989
+ // Deferred to a microtask because `session_destroyed` is emitted from INSIDE
990
+ // SessionManager.destroySession: scheduling synchronously would call
991
+ // createSession from within a teardown that has not finished its own
992
+ // bookkeeping. The defer also means the headroom read sees the completed
993
+ // destroy, never a half-torn-down pool.
994
+ _onSessionCapacityFreed() {
995
+ queueMicrotask(() => {
996
+ if (this._disposed) return
997
+ for (const run of [...this._runs.values()]) {
998
+ if (run.cancelled || run.phase !== 'resource_paused') continue
999
+ this._schedule(run)
1000
+ }
1001
+ })
1002
+ }
1003
+
1004
+ _onPermissionEscalation(info) {
1005
+ const run = this._runForSession(info.sessionId)
1006
+ if (!run) return
1007
+ this.emit('permission_escalation', { runId: run.runId, ...info })
1008
+ }
1009
+
1010
+ async _failRun(run, code, err) {
1011
+ // A manager that has been disposed owns nothing any more: its ledger may be
1012
+ // flushed and closed, its log gone. A start that was in flight at dispose
1013
+ // time is rejected by the TurnDriver teardown and lands here a tick later;
1014
+ // journaling `failed` then would write to a disposed ledger (#7142).
1015
+ if (this._disposed) return { runId: run.runId, phase: run.phase }
1016
+ // A cancel that already tore the run down wins: don't overwrite the
1017
+ // terminal 'cancelled' status with 'failed' (or double-emit lifecycle
1018
+ // events) when an in-flight turn rejects SESSION_GONE on the next tick.
1019
+ if (run.cancelled || !this._runs.has(run.runId)) return { runId: run.runId, phase: run.phase }
1020
+ this._setRunStatus(run, 'failed', code)
1021
+ // tear down any owned sessions (auto-commits implement worktrees first)
1022
+ for (const sid of [...run.ownedSessions.keys()]) await this._destroySession(run, sid)
1023
+ await this._cleanupIntegration(run)
1024
+ this.emit('run_failed', { runId: run.runId, code, message: err?.message || String(err) })
1025
+ this._emitRunDelta(run)
1026
+ this._cacheCompletedSnapshot(run)
1027
+ this._runs.delete(run.runId)
1028
+ return { runId: run.runId, phase: 'failed', code }
1029
+ }
1030
+
1031
+ async cancelRun(runId, { reason = 'user' } = {}) {
1032
+ const run = this._runs.get(runId)
1033
+ if (!run) return null
1034
+ // #7132 — a cancel already in flight OWNS the teardown; a second one is a
1035
+ // no-op ack, not a second teardown. Nothing downstream stops it otherwise:
1036
+ // `cancelling -> cancelling` is a LEGAL transition (the run-model treats the
1037
+ // cancel/suspend/fail terminals as reachable from any non-terminal state), so
1038
+ // a concurrent cancel re-runs the whole body — auto-committing every
1039
+ // implement worktree twice and `git worktree remove`-ing the integration
1040
+ // worktree twice, both racing on the same paths. Worse, the loser then
1041
+ // reaches the `cancelled` write below with the ledger already `cancelled` —
1042
+ // a TERMINAL source, so the guard throws ILLEGAL_TRANSITION and the WS
1043
+ // surface reports ORCHESTRATION_ACTION_FAILED for a cancel that succeeded.
1044
+ // Now that `cancel` is reachable over the wire (#7138) a double-click does
1045
+ // exactly this, so the guard lands with the surface that exposes it.
1046
+ //
1047
+ // `phase` is the engine's own mirror, written synchronously by
1048
+ // `_setRunStatus` before this method's first `await` — so a re-entrant call
1049
+ // always observes it, without depending on the ledger having flushed.
1050
+ if (run.phase === 'cancelling' || run.phase === 'cancelled') return { runId, phase: run.phase }
1051
+ run.cancelled = true
1052
+ // `cancelling` is the teardown-in-progress state (design §3.2:
1053
+ // "any state --cancelRun--> cancelling --> cancelled"). Journaling it BEFORE
1054
+ // the awaits — rather than jumping straight to `cancelled` — is what makes
1055
+ // the FSM's intermediate state real: an observer polling during a slow
1056
+ // teardown (interrupt + auto-commit of every implement worktree) sees
1057
+ // `cancelling`, and a teardown that throws leaves a truthful non-terminal
1058
+ // status instead of a `cancelled` run that was never torn down.
1059
+ this._setRunStatus(run, 'cancelling', reason)
1060
+ // ...and BROADCAST it. Journaling alone makes the intermediate state visible
1061
+ // only to a poller; every other status write in this class emits a delta
1062
+ // immediately after, and this one was the exception. Without it the teardown
1063
+ // below — interrupt + auto-commit of every implement worktree, then the
1064
+ // integration cleanup — is silent on the wire, so the dashboard sits on the
1065
+ // pre-cancel status and keeps offering the Cancel button (RunControls hides
1066
+ // itself on `cancelling`) for the whole duration. Emitting BEFORE the awaits
1067
+ // is the point: the delta has to lead the teardown, not trail it.
1068
+ this._emitRunDelta(run)
1069
+ // interrupt every in-flight owned session, then release (auto-commit → destroy)
1070
+ // so no implement worker's uncommitted work is lost.
1071
+ for (const sid of [...run.ownedSessions.keys()]) {
1072
+ try { this._sm.getSession?.(sid)?.session?.interrupt?.() } catch { /* ignore */ }
1073
+ }
1074
+ for (const sid of [...run.ownedSessions.keys()]) await this._destroySession(run, sid)
1075
+ await this._cleanupIntegration(run)
1076
+ this._setRunStatus(run, 'cancelled', reason)
1077
+ this.emit('run_cancelled', { runId, reason })
1078
+ this._emitRunDelta(run)
1079
+ this._cacheCompletedSnapshot(run)
1080
+ this._runs.delete(runId)
1081
+ return { runId, phase: 'cancelled' }
1082
+ }
1083
+
1084
+ // Remove the run's integration WORKTREE (orchestrator-owned, under the
1085
+ // worktrees root). The integration BRANCH is KEPT — it is the run's output.
1086
+ async _cleanupIntegration(run) {
1087
+ if (!run.integration?.worktreePath) return
1088
+ try {
1089
+ await this._gitOps.removeWorktree({ repoDir: run.cwd, worktreePath: run.integration.worktreePath })
1090
+ await this._gitOps.pruneWorktrees(run.cwd)
1091
+ } catch (err) { this._log?.warn?.(`orchestration: integration cleanup failed: ${err?.message || err}`) }
1092
+ run.integration = null
1093
+ }
1094
+
1095
+ _get(runId) {
1096
+ const run = this._runs.get(runId)
1097
+ if (!run) throw new Error(`run ${runId} not found`)
1098
+ return run
1099
+ }
1100
+ _isOwnedSession(sessionId) {
1101
+ for (const run of this._runs.values()) if (run.ownedSessions.has(sessionId)) return true
1102
+ return false
1103
+ }
1104
+ _roleClassForSession(sessionId) {
1105
+ // The gate policy per owned session:
1106
+ // - implement/fixup → 'implement' (Bash matched against the allowlist; else escalate)
1107
+ // - architect/audit → 'audit' (read-only; reads are rule-allowed and never
1108
+ // reach the gate, anything else is denied). The architect maps to 'audit'
1109
+ // rather than null so the gate answers (denies) it instead of IGNORING it
1110
+ // and wedging a stray tool until the turn watchdog fires.
1111
+ for (const run of this._runs.values()) {
1112
+ const meta = run.ownedSessions.get(sessionId)
1113
+ if (meta) return (meta.role === 'implement' || meta.role === 'fixup') ? 'implement' : 'audit'
1114
+ }
1115
+ return null
1116
+ }
1117
+ _runForSession(sessionId) {
1118
+ for (const run of this._runs.values()) if (run.ownedSessions.has(sessionId)) return run
1119
+ return null
1120
+ }
1121
+ _activeWorkerCount(run) {
1122
+ let n = 0
1123
+ for (const s of run.subtasks.values()) if (s.state === 'active') n += 1
1124
+ return n
1125
+ }
1126
+ _liveSessionCount() {
1127
+ return typeof this._sm.listSessions === 'function' ? this._sm.listSessions().length : this._sm._sessions?.size ?? 0
1128
+ }
1129
+ _sessionHeadroom() {
1130
+ // NOTE: this is the daemon's TOTAL live session count, not the run's own —
1131
+ // unrelated sessions can starve a run, which is why #6733 exists. Reserving
1132
+ // orchestration capacity up front (counting only owned sessions) is the other
1133
+ // half of that issue and is deliberately not done here.
1134
+ const size = this._liveSessionCount()
1135
+ // Room to spawn ONE more session while still leaving reserveSessions slots
1136
+ // free — strict, so the reserve is preserved AFTER the new session exists.
1137
+ return size + 1 <= this._maxSessions - this._cfg.reserveSessions
1138
+ }
1139
+
1140
+ // --- read API (consumed by the S-2 handlers) — wire-projected via to-wire ---
1141
+
1142
+ // RunSummary[] for the runs list. Active runs use their live engine extras (so
1143
+ // pendingUserGates is accurate); a terminal run whose engine state is gone
1144
+ // uses its cached final snapshot, else projects from the record alone.
1145
+ listRuns() {
1146
+ // The ledger index gives ordering (newest first) + the run ids; project each
1147
+ // from its full record so the summary is complete.
1148
+ return this._ledger.listRuns().map((row) => {
1149
+ const record = this._ledger.getRun(row.runId)
1150
+ if (!record) return null
1151
+ const run = this._runs.get(row.runId)
1152
+ if (run) return recordToRunSummary(record, this._snapshotExtras(run))
1153
+ const cached = this._completedSnapshots.get(row.runId)
1154
+ // cached.summary (a lean RunSummary) — NOT cached.run (a fat RunDetail):
1155
+ // the runs list must stay lightweight (RunSummarySchema is .passthrough(),
1156
+ // so a RunDetail would silently balloon every terminal row with its
1157
+ // nodes/timeline/rollup).
1158
+ return cached ? cached.summary : recordToRunSummary(record, { report: this._reportExtra(row.runId) })
1159
+ }).filter(Boolean)
1160
+ }
1161
+
1162
+ // { seq, run: RunDetail } for one run.
1163
+ getRunSnapshot(runId) {
1164
+ const run = this._runs.get(runId)
1165
+ if (run) {
1166
+ const record = this._ledger.getRun(runId)
1167
+ if (!record) return null
1168
+ return { seq: run.wireSeq, run: recordToRunDetail(record, this._snapshotExtras(run)) }
1169
+ }
1170
+ const cached = this._completedSnapshots.get(runId)
1171
+ if (cached) return cached
1172
+ const record = this._ledger.getRun(runId)
1173
+ if (!record) return null
1174
+ return { seq: 0, run: recordToRunDetail(record, { report: this._reportExtra(runId) }) }
1175
+ }
1176
+
1177
+ // Assemble the projection `extras` bag from a run's live engine state.
1178
+ _snapshotExtras(run) {
1179
+ const nodeExtras = {}
1180
+ for (const [subtaskId, st] of run.subtasks) {
1181
+ nodeExtras[subtaskId] = {
1182
+ branch: st.branch ?? null,
1183
+ worktreePath: st.worktreePath ?? null,
1184
+ planSummary: st.poa?.plan ?? null,
1185
+ resultSummary: st.result?.summary ?? null,
1186
+ attempt: st.iterations ?? 0,
1187
+ committeeIterations: st.iterations ?? 0,
1188
+ }
1189
+ }
1190
+ return {
1191
+ epicPrompt: run.goal ?? '',
1192
+ gates: [...run.gates.values()],
1193
+ timeline: run.timeline,
1194
+ nodeExtras,
1195
+ report: this._reportExtra(run.runId),
1196
+ }
1197
+ }
1198
+
1199
+ // The report artifacts for a run, in preference order: the in-memory docs
1200
+ // (built at completion / re-annotation), then the persisted report.{json,md}
1201
+ // (a restarted daemon), then the bare synthesis narrative (legacy fallback).
1202
+ // The disk read is SKIPPED for live runs: a report only exists at terminal
1203
+ // state, and _snapshotExtras runs on hot paths (every delta emit, listRuns) —
1204
+ // probing the filesystem per delta for a file that can't exist yet would be
1205
+ // pure waste.
1206
+ _reportExtra(runId) {
1207
+ const docs = this._reportDocs.get(runId)
1208
+ if (docs) return docs
1209
+ if (!this._runs.has(runId)) {
1210
+ const persisted = this._ledger.readReport?.(runId)
1211
+ if (persisted) return persisted
1212
+ }
1213
+ const md = this._reports.get(runId)
1214
+ return md ? { json: '', markdown: md } : null
1215
+ }
1216
+
1217
+ // M-4: derive the metrics report from the ledger record, prepend the
1218
+ // architect's synthesis narrative, persist report.{json,md}, and keep the
1219
+ // docs in memory for snapshots. Never throws (derived state; the journal is
1220
+ // ground truth and the report can be regenerated).
1221
+ _buildAndPersistReport(runId) {
1222
+ try {
1223
+ const record = this._ledger.getRun(runId)
1224
+ if (!record) return null
1225
+ // The synthesis narrative's only durable copy is the persisted report's
1226
+ // `synthesis` field — after a restart (or _reports LRU eviction) the
1227
+ // in-memory copy is gone, and overwriting report.{json,md} without this
1228
+ // fallback would DESTROY the narrative (a re-annotated old run would lose
1229
+ // its audit findings forever).
1230
+ const narrative = this._reports.get(runId) ?? this._persistedNarrative(runId)
1231
+ const report = buildRunReport(record)
1232
+ report.synthesis = narrative
1233
+ const markdown = (narrative ? `${narrative}\n\n---\n\n` : '') + renderReportMarkdown(report)
1234
+ const json = JSON.stringify(report, null, 2)
1235
+ this._ledger.writeReport(runId, { json, markdown })
1236
+ this._reportDocs.set(runId, { json, markdown })
1237
+ while (this._reportDocs.size > this._maxReports) {
1238
+ this._reportDocs.delete(this._reportDocs.keys().next().value)
1239
+ }
1240
+ return { json, markdown }
1241
+ } catch (err) {
1242
+ this._log?.warn?.(`orchestration: report generation failed for ${runId}: ${err?.message || err}`)
1243
+ return null
1244
+ }
1245
+ }
1246
+
1247
+ // Recover the synthesis narrative from the persisted report.json (a restarted
1248
+ // daemon / evicted in-memory copy). Null when absent or unparseable.
1249
+ _persistedNarrative(runId) {
1250
+ try {
1251
+ const persisted = this._ledger.readReport?.(runId)
1252
+ if (!persisted?.json) return null
1253
+ const parsed = JSON.parse(persisted.json)
1254
+ return typeof parsed?.synthesis === 'string' ? parsed.synthesis : null
1255
+ } catch {
1256
+ return null
1257
+ }
1258
+ }
1259
+
1260
+ // M-4 (#6701): annotate a run for the dogfood measurement — attach the
1261
+ // monolithic-baseline session's usage and/or a verdict-quality note. Works on
1262
+ // live AND terminal runs (operates via the ledger, not engine state); on a
1263
+ // terminal run the persisted report + frozen snapshot are refreshed.
1264
+ async annotate(runId, { baselineSessionId = null, verdictQuality = undefined } = {}) {
1265
+ const record = this._ledger.getRun(runId)
1266
+ if (!record) {
1267
+ const err = new Error(`run ${runId} not found`)
1268
+ err.code = 'RUN_NOT_FOUND'
1269
+ throw err
1270
+ }
1271
+ if (verdictQuality !== undefined) this._ledger.note(runId, { verdictQuality })
1272
+ if (baselineSessionId) {
1273
+ const entry = this._sm.getSession?.(baselineSessionId)
1274
+ if (!entry) {
1275
+ const err = new Error(`baseline session ${baselineSessionId} not found`)
1276
+ err.code = 'BASELINE_SESSION_NOT_FOUND'
1277
+ throw err
1278
+ }
1279
+ const u = entry.cumulativeUsage || null
1280
+ const costUsd = Number.isFinite(u?.costUsd) ? u.costUsd : 0
1281
+ // A subscription-billed baseline (claude-tui, the default provider) keeps
1282
+ // costUsd at 0 forever while doing real work — recording it as a $0
1283
+ // baseline would render "delegation cost MORE than the monolithic run",
1284
+ // the exact inversion the honesty rules exist to prevent. Same for a
1285
+ // session with NO usage accumulator at all: no signal ≠ $0. Flag both
1286
+ // unmetered so the report suppresses the money delta and surfaces the gap.
1287
+ const hadActivity = (u?.turnsBilled ?? 0) > 0 || (u?.inputTokens ?? 0) > 0 || (u?.outputTokens ?? 0) > 0
1288
+ this._ledger.setBaseline(runId, {
1289
+ sessionId: baselineSessionId,
1290
+ // a plain session's spend signal is its provider-reported cumulative cost
1291
+ effectiveUsd: costUsd,
1292
+ unmetered: !u || (costUsd === 0 && hadActivity),
1293
+ inputTokens: u?.inputTokens, outputTokens: u?.outputTokens,
1294
+ cacheReadTokens: u?.cacheReadTokens, cacheCreationTokens: u?.cacheCreationTokens,
1295
+ })
1296
+ }
1297
+ // refresh derived artifacts for a terminal run (a live run rebuilds at completion)
1298
+ if (!this._runs.has(runId)) {
1299
+ const docs = this._buildAndPersistReport(runId)
1300
+ const cached = this._completedSnapshots.get(runId)
1301
+ if (cached) {
1302
+ const fresh = this._ledger.getRun(runId)
1303
+ // suppress the money figure for an unmetered baseline (matches the report)
1304
+ if (Number.isFinite(fresh?.baseline?.effectiveUsd) && fresh?.baseline?.unmetered !== true) cached.run.baselineEffectiveUsd = fresh.baseline.effectiveUsd
1305
+ if (fresh?.notes?.verdictQuality != null) cached.run.verdictQuality = String(fresh.notes.verdictQuality)
1306
+ if (docs) cached.run.report = docs
1307
+ }
1308
+ }
1309
+ return { runId, annotated: true }
1310
+ }
1311
+
1312
+ // On terminal, freeze BOTH the detail (for getRunSnapshot) and the summary
1313
+ // (for the lightweight runs list) so the snapshot survives the run's engine
1314
+ // state being deleted from _runs. Never throws: a projection failure must not
1315
+ // skip the caller's _runs.delete (a leaked run wedges createRun's one-run-at-
1316
+ // a-time guard for the process lifetime).
1317
+ _cacheCompletedSnapshot(run) {
1318
+ try {
1319
+ const record = this._ledger.getRun(run.runId)
1320
+ if (!record) return
1321
+ const extras = this._snapshotExtras(run)
1322
+ this._completedSnapshots.set(run.runId, {
1323
+ seq: run.wireSeq,
1324
+ run: recordToRunDetail(record, extras),
1325
+ summary: recordToRunSummary(record, extras),
1326
+ })
1327
+ while (this._completedSnapshots.size > this._maxCompletedSnapshots) {
1328
+ this._completedSnapshots.delete(this._completedSnapshots.keys().next().value)
1329
+ }
1330
+ } catch (err) {
1331
+ this._log?.warn?.(`orchestration: caching terminal snapshot failed for ${run.runId}: ${err?.message || err}`)
1332
+ }
1333
+ }
1334
+
1335
+ _rememberReport(runId, markdown) {
1336
+ this._reports.set(runId, markdown)
1337
+ while (this._reports.size > this._maxReports) {
1338
+ const oldest = this._reports.keys().next().value
1339
+ this._reports.delete(oldest)
1340
+ }
1341
+ }
1342
+ }