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