cohorte 2.10.1 → 3.0.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) hide show
  1. package/README.md +7 -0
  2. package/assets/manifest.json +193 -0
  3. package/assets/migrations/config/README.md +12 -0
  4. package/assets/migrations/state/0001_init.sql +154 -0
  5. package/assets/prompts/README.md +11 -0
  6. package/assets/prompts/agents/fixer.md +7 -0
  7. package/assets/prompts/agents/implementer.md +12 -0
  8. package/assets/prompts/agents/reviewer.md +8 -0
  9. package/assets/prompts/agents/security-reviewer.md +7 -0
  10. package/assets/prompts/phases/build.md +5 -0
  11. package/assets/prompts/phases/review.md +5 -0
  12. package/assets/prompts/phases/test.md +5 -0
  13. package/assets/prompts/system.md +11 -0
  14. package/assets/schemas/agent-output.schema.json +225 -0
  15. package/assets/schemas/auth-status.schema.json +87 -0
  16. package/assets/schemas/command-result.schema.json +192 -0
  17. package/assets/schemas/commands.schema.json +952 -0
  18. package/assets/schemas/config.schema.json +2259 -0
  19. package/assets/schemas/doctor-report.schema.json +104 -0
  20. package/assets/schemas/events.schema.json +8514 -0
  21. package/assets/schemas/fake-script.schema.json +549 -0
  22. package/assets/schemas/inspect.schema.json +3133 -0
  23. package/assets/schemas/manifest.schema.json +79 -0
  24. package/assets/schemas/ownership.schema.json +52 -0
  25. package/assets/schemas/policy-verdict.schema.json +282 -0
  26. package/assets/schemas/project-model.schema.json +783 -0
  27. package/assets/schemas/project-status.schema.json +217 -0
  28. package/assets/schemas/reconcile-plan.schema.json +154 -0
  29. package/assets/schemas/run-diff.schema.json +177 -0
  30. package/assets/schemas/run-snapshot-manifest.schema.json +2104 -0
  31. package/assets/schemas/run-state.schema.json +1755 -0
  32. package/assets/schemas/runtime-capabilities.schema.json +1545 -0
  33. package/assets/schemas/sandbox-capabilities.schema.json +116 -0
  34. package/assets/schemas/skill.schema.json +87 -0
  35. package/assets/schemas/spec.schema.json +202 -0
  36. package/assets/schemas/tool-catalogue.schema.json +655 -0
  37. package/assets/schemas/trust-record.schema.json +38 -0
  38. package/assets/skills/README.md +9 -0
  39. package/assets/skills/inspect-surface.md +4 -0
  40. package/dist/agent-host.mjs +2187 -0
  41. package/dist/agent-host.mjs.map +1 -0
  42. package/dist/bundle-manifest.json +104 -0
  43. package/dist/chunks/__host-DgGPyco9.mjs +18 -0
  44. package/dist/chunks/__host-DgGPyco9.mjs.map +1 -0
  45. package/dist/chunks/approve-Cv135UqI.mjs +19 -0
  46. package/dist/chunks/approve-Cv135UqI.mjs.map +1 -0
  47. package/dist/chunks/auth-BT5oVp76.mjs +132 -0
  48. package/dist/chunks/auth-BT5oVp76.mjs.map +1 -0
  49. package/dist/chunks/auth-CYOh60KG.mjs +93 -0
  50. package/dist/chunks/auth-CYOh60KG.mjs.map +1 -0
  51. package/dist/chunks/brainstorm-BwKA6yZP.mjs +7 -0
  52. package/dist/chunks/brainstorm-BwKA6yZP.mjs.map +1 -0
  53. package/dist/chunks/cancel-KV_cpsqS.mjs +15 -0
  54. package/dist/chunks/cancel-KV_cpsqS.mjs.map +1 -0
  55. package/dist/chunks/canonical-C8UxeEmB.mjs +57 -0
  56. package/dist/chunks/canonical-C8UxeEmB.mjs.map +1 -0
  57. package/dist/chunks/catalogue-BvwSrM_j.mjs +1549 -0
  58. package/dist/chunks/catalogue-BvwSrM_j.mjs.map +1 -0
  59. package/dist/chunks/compose-Dvxunpto.mjs +7307 -0
  60. package/dist/chunks/compose-Dvxunpto.mjs.map +1 -0
  61. package/dist/chunks/config-DefHA2Lw.mjs +96 -0
  62. package/dist/chunks/config-DefHA2Lw.mjs.map +1 -0
  63. package/dist/chunks/contract-BkMjU1kR.mjs +295 -0
  64. package/dist/chunks/contract-BkMjU1kR.mjs.map +1 -0
  65. package/dist/chunks/contract-bQ9FJl4N.mjs +123 -0
  66. package/dist/chunks/contract-bQ9FJl4N.mjs.map +1 -0
  67. package/dist/chunks/deny-ClTxSvHJ.mjs +15 -0
  68. package/dist/chunks/deny-ClTxSvHJ.mjs.map +1 -0
  69. package/dist/chunks/diff-Qw0II0sj.mjs +101 -0
  70. package/dist/chunks/diff-Qw0II0sj.mjs.map +1 -0
  71. package/dist/chunks/discover-eS01-me1.mjs +21 -0
  72. package/dist/chunks/discover-eS01-me1.mjs.map +1 -0
  73. package/dist/chunks/doctor-B-H2UK5e.mjs +222 -0
  74. package/dist/chunks/doctor-B-H2UK5e.mjs.map +1 -0
  75. package/dist/chunks/fix-D4Tj8RVA.mjs +18 -0
  76. package/dist/chunks/fix-D4Tj8RVA.mjs.map +1 -0
  77. package/dist/chunks/gc-BBXlBF5w.mjs +161 -0
  78. package/dist/chunks/gc-BBXlBF5w.mjs.map +1 -0
  79. package/dist/chunks/init-BUnzIkeE.mjs +63 -0
  80. package/dist/chunks/init-BUnzIkeE.mjs.map +1 -0
  81. package/dist/chunks/inspect-Buby4cQD.mjs +22 -0
  82. package/dist/chunks/inspect-Buby4cQD.mjs.map +1 -0
  83. package/dist/chunks/logs-Giq5sUau.mjs +25 -0
  84. package/dist/chunks/logs-Giq5sUau.mjs.map +1 -0
  85. package/dist/chunks/migrate-DybihKzZ.mjs +33 -0
  86. package/dist/chunks/migrate-DybihKzZ.mjs.map +1 -0
  87. package/dist/chunks/models-Btp6X2YZ.mjs +24 -0
  88. package/dist/chunks/models-Btp6X2YZ.mjs.map +1 -0
  89. package/dist/chunks/pause-BASBfKLO.mjs +16 -0
  90. package/dist/chunks/pause-BASBfKLO.mjs.map +1 -0
  91. package/dist/chunks/policy-DUIgzF3W.mjs +139 -0
  92. package/dist/chunks/policy-DUIgzF3W.mjs.map +1 -0
  93. package/dist/chunks/providers-Dx78imKj.mjs +19 -0
  94. package/dist/chunks/providers-Dx78imKj.mjs.map +1 -0
  95. package/dist/chunks/reconcile-Bhy3IIYo.mjs +50 -0
  96. package/dist/chunks/reconcile-Bhy3IIYo.mjs.map +1 -0
  97. package/dist/chunks/render-DyZr5Lgi.mjs +53 -0
  98. package/dist/chunks/render-DyZr5Lgi.mjs.map +1 -0
  99. package/dist/chunks/resume-GJQRb2Eb.mjs +15 -0
  100. package/dist/chunks/resume-GJQRb2Eb.mjs.map +1 -0
  101. package/dist/chunks/retry-CLrUem1H.mjs +15 -0
  102. package/dist/chunks/retry-CLrUem1H.mjs.map +1 -0
  103. package/dist/chunks/review-BDdjb6kB.mjs +17 -0
  104. package/dist/chunks/review-BDdjb6kB.mjs.map +1 -0
  105. package/dist/chunks/run-CgTWYlcd.mjs +82 -0
  106. package/dist/chunks/run-CgTWYlcd.mjs.map +1 -0
  107. package/dist/chunks/run-tool-C3rAv4XF.mjs +26 -0
  108. package/dist/chunks/run-tool-C3rAv4XF.mjs.map +1 -0
  109. package/dist/chunks/scan-8Gy_B6kI.mjs +122 -0
  110. package/dist/chunks/scan-8Gy_B6kI.mjs.map +1 -0
  111. package/dist/chunks/schema-C9QbUW4H.mjs +578 -0
  112. package/dist/chunks/schema-C9QbUW4H.mjs.map +1 -0
  113. package/dist/chunks/send-BdnJ85Nz.mjs +19 -0
  114. package/dist/chunks/send-BdnJ85Nz.mjs.map +1 -0
  115. package/dist/chunks/ship-DTuLGoaJ.mjs +19 -0
  116. package/dist/chunks/ship-DTuLGoaJ.mjs.map +1 -0
  117. package/dist/chunks/shutdown-BM92Iyv2.mjs +15 -0
  118. package/dist/chunks/shutdown-BM92Iyv2.mjs.map +1 -0
  119. package/dist/chunks/skip-DZG5kpcH.mjs +18 -0
  120. package/dist/chunks/skip-DZG5kpcH.mjs.map +1 -0
  121. package/dist/chunks/spec-Bq0P3jVh.mjs +20 -0
  122. package/dist/chunks/spec-Bq0P3jVh.mjs.map +1 -0
  123. package/dist/chunks/src-CId6kMsY.mjs +1689 -0
  124. package/dist/chunks/src-CId6kMsY.mjs.map +1 -0
  125. package/dist/chunks/src-CfAOde7C.mjs +5403 -0
  126. package/dist/chunks/src-CfAOde7C.mjs.map +1 -0
  127. package/dist/chunks/src-CmFjh4M0.mjs +928 -0
  128. package/dist/chunks/src-CmFjh4M0.mjs.map +1 -0
  129. package/dist/chunks/src-Cu3TxNob.mjs +783 -0
  130. package/dist/chunks/src-Cu3TxNob.mjs.map +1 -0
  131. package/dist/chunks/src-DcU4IXMe.mjs +117 -0
  132. package/dist/chunks/src-DcU4IXMe.mjs.map +1 -0
  133. package/dist/chunks/src-s7YRvk0t.mjs +2116 -0
  134. package/dist/chunks/src-s7YRvk0t.mjs.map +1 -0
  135. package/dist/chunks/status-SMjiOMYy.mjs +29 -0
  136. package/dist/chunks/status-SMjiOMYy.mjs.map +1 -0
  137. package/dist/chunks/tail-BuhT-2PH.mjs +25 -0
  138. package/dist/chunks/tail-BuhT-2PH.mjs.map +1 -0
  139. package/dist/chunks/update-BXIppsbi.mjs +16 -0
  140. package/dist/chunks/update-BXIppsbi.mjs.map +1 -0
  141. package/dist/cli.mjs +175 -0
  142. package/dist/cli.mjs.map +1 -0
  143. package/package.json +17 -32
  144. package/CHANGELOG.md +0 -1461
  145. package/bin/cli.js +0 -817
  146. package/bin/report.js +0 -141
  147. package/core/adapter/render.js +0 -415
  148. package/core/agents/implementer.template.md +0 -142
  149. package/core/agents/profile-reader.md +0 -50
  150. package/core/agents/release.md +0 -58
  151. package/core/agents/review.md +0 -179
  152. package/core/commands/cohorte-align-ds.md +0 -33
  153. package/core/commands/cohorte-audit.md +0 -58
  154. package/core/commands/cohorte-brainstorm.md +0 -70
  155. package/core/commands/cohorte-build.md +0 -219
  156. package/core/commands/cohorte-doctor.md +0 -194
  157. package/core/commands/cohorte-fix.md +0 -80
  158. package/core/commands/cohorte-fleet.md +0 -103
  159. package/core/commands/cohorte-init-pipeline.md +0 -31
  160. package/core/commands/cohorte-intake.md +0 -92
  161. package/core/commands/cohorte-patch.md +0 -118
  162. package/core/commands/cohorte-refactor.md +0 -59
  163. package/core/commands/cohorte-retro.md +0 -85
  164. package/core/commands/cohorte-review.md +0 -270
  165. package/core/commands/cohorte-ship.md +0 -122
  166. package/core/commands/cohorte-spec.md +0 -101
  167. package/core/commands/cohorte-update-pipeline.md +0 -165
  168. package/core/hooks/gate.py +0 -588
  169. package/core/runtimes/claude.json +0 -74
  170. package/core/runtimes/codex.json +0 -85
  171. package/core/runtimes/cursor.json +0 -76
  172. package/core/runtimes/gemini.json +0 -76
  173. package/core/runtimes/opencode.json +0 -73
  174. package/core/templates/agent-handoff.md +0 -34
  175. package/core/templates/brainstorm-return.md +0 -36
  176. package/core/templates/decisions.template.md +0 -42
  177. package/core/templates/design-brief.md +0 -44
  178. package/core/templates/patch.template.md +0 -86
  179. package/core/templates/pr-body.md +0 -25
  180. package/core/templates/review-feedback.md +0 -38
  181. package/core/templates/spec.template.md +0 -87
  182. package/core/templates/steps/init-pipeline/01-detect-stack.md +0 -44
  183. package/core/templates/steps/init-pipeline/02-interview-gaps.md +0 -55
  184. package/core/templates/steps/init-pipeline/03-draft-profile.md +0 -10
  185. package/core/templates/steps/init-pipeline/04-write-render.md +0 -145
  186. package/core/templates/steps/init-pipeline/05-report.md +0 -12
  187. package/core/workflows/audit.js +0 -240
  188. package/core/workflows/loop.js +0 -641
  189. package/core/workflows/refactor.js +0 -276
  190. package/core/workflows/review.js +0 -456
  191. package/install.ps1 +0 -103
  192. package/install.sh +0 -114
  193. package/lib/doctor.js +0 -534
  194. package/lib/runtime.js +0 -139
  195. package/lib/versions.js +0 -149
  196. package/lib/yaml.js +0 -129
  197. package/profile/PIPELINE.template.md +0 -259
  198. package/profile/SCHEMA.md +0 -735
  199. package/profile/cohorte.config.template.yaml +0 -43
  200. package/scripts/assert-gate-hook.mjs +0 -75
  201. package/scripts/kanban-move.sh +0 -313
  202. package/scripts/metrics/collect.mjs +0 -531
  203. package/scripts/metrics/prices.json +0 -42
  204. package/scripts/new-feature.sh.template +0 -98
  205. package/scripts/preflight.sh +0 -124
  206. package/scripts/remove-feature.sh.template +0 -56
  207. package/scripts/test-adapter.mjs +0 -437
  208. package/scripts/test-gate.mjs +0 -443
  209. package/scripts/test-kanban.mjs +0 -304
  210. package/scripts/test-lib.mjs +0 -356
  211. package/scripts/test-metrics.mjs +0 -156
  212. package/scripts/test-workflows.mjs +0 -758
  213. package/scripts/validate-core.mjs +0 -325
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-CfAOde7C.mjs","names":["asJson","createToolHost","createToolHost","createTransitionEffectRunner","SUSPENDED_SET","TERMINAL_SET","HEAD_ROWS","SKIP_TARGETS","ACTIVE_STATE_SET","createPhaseExecutor","_exhaustive","Sha256Schema","IsoInstantSchema","PipelineProfileSchema","SpecIdSchema","RunSnapshotManifestSchema","createToolHostImpl","createTransitionEffectRunnerImpl","createPhaseExecutorImpl"],"sources":["../../../../packages/core/src/agents/lifecycle.ts","../../../../packages/core/src/agents/supervisor/implementation.ts","../../../../packages/core/src/durability/journal/keys.ts","../../../../packages/core/src/toolhost/implementation.ts","../../../../packages/core/src/approvals/index.ts","../../../../packages/core/src/durability/crashpoints.ts","../../../../packages/core/src/durability/journal/index.ts","../../../../packages/core/src/durability/lease/index.ts","../../../../packages/core/src/effects/transition-runner.ts","../../../../packages/core/src/pipeline/idempotency-key.ts","../../../../packages/core/src/pipeline/tables/shared.ts","../../../../packages/core/src/pipeline/tables/feature.v1.ts","../../../../packages/core/src/pipeline/tables/bugfix.v1.ts","../../../../packages/core/src/pipeline/tables/review.v1.ts","../../../../packages/core/src/pipeline/tables/index.ts","../../../../packages/core/src/pipeline/next-step.ts","../../../../packages/core/src/engine/actor.ts","../../../../packages/core/src/engine/checkpoint.ts","../../../../packages/core/src/engine/deps.ts","../../../../packages/core/src/pipeline/command-matrix.ts","../../../../packages/core/src/pipeline/resolve-transition.ts","../../../../packages/core/src/engine/commands.ts","../../../../packages/core/src/engine/errors.ts","../../../../packages/core/src/engine/transitions.ts","../../../../packages/core/src/engine/inbox.ts","../../../../packages/core/src/engine/index.ts","../../../../packages/core/src/events/index.ts","../../../../packages/core/src/grants/index.ts","../../../../packages/core/src/review/normalize.ts","../../../../packages/core/src/phases/contracts/index.ts","../../../../packages/core/src/phases/executor/implementation.ts","../../../../packages/core/src/contract/ids.ts","../../../../packages/core/src/pipeline/guards/facts.ts","../../../../packages/core/src/pipeline/guards/index.ts","../../../../packages/core/src/state/evolve.ts","../../../../packages/core/src/provision/implementation.ts","../../../../packages/core/src/state/initial-run-state.ts","../../../../packages/core/src/resume/immutability.ts","../../../../packages/core/src/resume/note.ts","../../../../packages/core/src/resume/index.ts","../../../../packages/core/src/contract/snapshot-manifest.ts","../../../../packages/core/src/snapshot/implementation.ts","../../../../packages/core/src/worktrees/implementation.ts","../../../../packages/core/src/contract/factories.ts","../../../../packages/core/src/errors/catalogue.ts","../../../../packages/core/src/phases/executor/index.ts"],"sourcesContent":["// DESIGN 2.5.4 — agent lifecycle (spec 6), verbatim: the state machine and reincarnation, the ONLY way to reach\n// `spawning` without going through `failed -> retrying|escalated`.\nimport { CohorteError, errorOf } from '@cohorte/base';\nimport type { AgentRecord } from '@cohorte/persistence/contract';\nimport type { AgentState } from '@cohorte/protocol';\n\nexport const AGENT_TRANSITIONS = {\n /** planned = context manifest built + grants computed + slot acquired */\n declared: ['planned', 'cancelled'],\n planned: ['spawning', 'cancelled'],\n /** effect agent.spawn, key = `${runId}:${agentId}:${incarnation}`; -> spawning = the host died mid-spawn (crash point #9): reincarnation */\n spawning: ['running', 'failed', 'cancelled', 'spawning'],\n /** -> spawning = REINCARNATION (below) */\n running: ['waiting', 'paused', 'completed', 'failed', 'cancelled', 'spawning'],\n /** blocked on approval / quota / a serialized peer */\n waiting: ['running', 'paused', 'failed', 'cancelled', 'spawning'],\n paused: ['running', 'cancelled', 'spawning'],\n /** only if error.retryable && attempt < maxAttempts */\n failed: ['retrying', 'escalated', 'cancelled'],\n /** attempt+1, incarnation+1, SAME context hash: the SpawnRequest minus {incarnation} is byte-identical (FakeLedger assertion) */\n retrying: ['spawning', 'cancelled'],\n escalated: ['spawning', 'cancelled'],\n completed: [],\n cancelled: [],\n} as const satisfies Record<AgentState, readonly AgentState[]>;\n\n/** the four edges spawning|running|waiting|paused -> spawning are legal REINCARNATION sources */\nconst REINCARNATE_SOURCES = ['spawning', 'running', 'waiting', 'paused'] as const satisfies readonly AgentState[];\n\n/**\n * The four edges `spawning|running|waiting|paused -> spawning` are REINCARNATIONS: the runtime session is gone but\n * the WORK did not fail. They carry a cause and are the ONLY way to reach `spawning` without going through\n * `failed -> retrying|escalated`.\n */\nexport type ReincarnateCause =\n /** host died or was restarted: 4.4 step 10 */\n | 'recovery'\n /** approval wait exceeded parkAfterMinutes, or quota/auth suspension: 4.5 */\n | 'park'\n /** paused longer than host.pauseKeepAliveMinutes: 4.6 */\n | 'pause-expiry';\n\n/**\n * `attempt` counts retries of the work; `incarnation` counts runtime sessions. Rule, stated once: `attempt` is\n * incremented by exactly two edges — `failed -> retrying` and `failed -> escalated` — and by nothing else. A\n * recovery after a host death, a parked approval and an expired pause are reincarnations of the same attempt: they\n * do not consume `maxAttempts`, they count against `maxIncarnations` (default 5).\n *\n * Throws (DESIGN 2.5.4) on a terminal state — a `completed` agent is never re-spawned by `resume` — and on any other\n * state that is not one of the four legal reincarnation sources; throws `budget/incarnations` when reincarnating\n * would exceed `maxIncarnations`, which is the `failed{budget/incarnations}` the supervisor records for the agent.\n * A caller that only try/catches therefore never re-spawns an exhausted agent.\n */\nexport function reincarnate(agent: AgentRecord, cause: ReincarnateCause): AgentRecord {\n if (!(REINCARNATE_SOURCES as readonly string[]).includes(agent.state)) {\n throw new TypeError(\n `reincarnate: agent ${agent.agentId} is ${agent.state}, not one of ${REINCARNATE_SOURCES.join(', ')}`,\n );\n }\n const nextIncarnation = agent.incarnation + 1;\n if (nextIncarnation > agent.maxIncarnations) {\n throw new CohorteError(\n errorOf(\n 'budget/incarnations',\n `agent ${agent.agentId} would reincarnate past its limit of ${agent.maxIncarnations} incarnations (cause: ${cause})`,\n ),\n );\n }\n return { ...agent, state: 'spawning', incarnation: nextIncarnation };\n}\n","import type { AgentId, Clock, IdSource } from '@cohorte/base';\nimport type { AgentOutput } from '@cohorte/protocol';\nimport type {\n AgentExit,\n AgentRuntime,\n AgentRuntimeProvider,\n RuntimeEvent,\n RuntimeHostBindings,\n SpawnRequest,\n} from '@cohorte/runtime-contract';\nimport type { AgentSupervisor, EventWriter } from '../../contract/internal.ts';\nimport type { AgentPlan, AgentResult, PhaseRunContext } from '../../contract/types.ts';\n\nexport interface SupervisorImplementationDeps {\n runtimeProvider: AgentRuntimeProvider;\n events: EventWriter;\n clock: Clock;\n ids: IdSource;\n bindings?: RuntimeHostBindings;\n requestFor?: (plan: AgentPlan, ctx: PhaseRunContext, incarnation: number) => SpawnRequest | Promise<SpawnRequest>;\n runtime?: AgentRuntime;\n concurrency?: number;\n onRuntimeEvent?: (event: RuntimeEvent) => void | Promise<void>;\n outputFor?: (agentId: AgentId) => AgentOutput | undefined;\n}\n\nfunction resultFromExit(\n plan: AgentPlan,\n exit: AgentExit,\n incarnation: number,\n outputFor?: SupervisorImplementationDeps['outputFor'],\n): AgentResult {\n const outcome = exit.outcome === 'completed' ? 'completed' : exit.outcome === 'cancelled' ? 'cancelled' : 'failed';\n const output = outputFor?.(plan.agentId);\n return {\n agent: {\n agentId: plan.agentId,\n role: plan.task.role,\n ...(plan.surface === undefined ? {} : { surface: plan.surface }),\n incarnation,\n attempt: 1,\n },\n outcome,\n ...(output === undefined ? {} : { output }),\n ...(exit.error === undefined ? {} : { error: exit.error }),\n artifacts: [],\n usage: {\n tokens: exit.usage.tokens.total,\n modelRequests: exit.usage.modelRequests,\n toolCalls: exit.usage.toolCalls,\n wallClockMs: exit.usage.wallClockMs,\n },\n };\n}\n\nasync function runOne(\n runtime: AgentRuntime,\n plan: AgentPlan,\n ctx: PhaseRunContext,\n incarnation: number,\n requestFor: SupervisorImplementationDeps['requestFor'],\n outputFor: SupervisorImplementationDeps['outputFor'],\n): Promise<AgentResult> {\n if (!requestFor) throw new Error(`configuration/supervisor-request-missing: ${plan.agentId}`);\n const request = await requestFor(plan, ctx, incarnation);\n const handle = await runtime.spawn(request);\n return resultFromExit(plan, await handle.exit, incarnation, outputFor);\n}\n\nfunction nextIncarnation(plan: AgentPlan, ctx: PhaseRunContext, seen: Map<AgentId, number>): number {\n const previous = (ctx.run?.agents ?? [])\n .filter((agent) => agent.agentId === plan.agentId)\n .reduce((highest, agent) => Math.max(highest, agent.incarnation), 0);\n return Math.max(previous, seen.get(plan.agentId) ?? 0) + 1;\n}\n\nexport function createAgentSupervisorImpl(deps: SupervisorImplementationDeps): AgentSupervisor {\n if (!deps.runtime && !deps.bindings) throw new Error('configuration/supervisor-bindings-missing');\n let runtime = deps.runtime;\n let subscribedRuntime: AgentRuntime | undefined;\n const runtimeWrites: Promise<void>[] = [];\n const seenIncarnations = new Map<AgentId, number>();\n const concurrency = Math.max(1, Math.floor(deps.concurrency ?? 3));\n return {\n async runAgents(plans, ctx) {\n runtime ??= await deps.runtimeProvider.create(\n deps.bindings as RuntimeHostBindings,\n await deps.runtimeProvider.pin(),\n );\n const activeRuntime = runtime;\n if (deps.onRuntimeEvent && subscribedRuntime !== activeRuntime) {\n subscribedRuntime = activeRuntime;\n activeRuntime.subscribe((event) => {\n const write = deps.onRuntimeEvent?.(event);\n if (write !== undefined) runtimeWrites.push(Promise.resolve(write));\n });\n }\n const results: AgentResult[] = [];\n let cursor = 0;\n const worker = async () => {\n while (cursor < plans.length) {\n const index = cursor++;\n const plan = plans[index];\n if (plan) {\n const incarnation = nextIncarnation(plan, ctx, seenIncarnations);\n seenIncarnations.set(plan.agentId, incarnation);\n results[index] = await runOne(activeRuntime, plan, ctx, incarnation, deps.requestFor, deps.outputFor);\n }\n }\n };\n await Promise.all(Array.from({ length: Math.min(concurrency, plans.length) }, worker));\n const pendingRuntimeWrites = runtimeWrites.splice(0);\n await Promise.all(pendingRuntimeWrites);\n return results;\n },\n };\n}\n","// DESIGN 4.1 (the idempotency-key column of the effect table) / 7.1 (\"idempotency keys\" row). One deterministic\n// builder per effect kind. Plain string templates: the store's `UNIQUE(run_id, idempotency_key)` does the rest.\nimport type { AgentId, RunId, Sha256 } from '@cohorte/base';\n\n/**\n * DEVIATION (docs/v3/requests/U1.08.md): DESIGN 4.1's table has no row for `git.worktree.remove`, `tool.read`,\n * `tool.network_request` or `tool.git_commit`, though `EffectKind` (persistence/records.ts) lists all four.\n * `worktreeRemove` reuses `worktreeAdd`'s own key namespace (same slot, inverse operation); the three `tool.*`\n * extras reuse `toolCall` (same shape as `tool.write_file` / `tool.patch_file` / `tool.run_command`).\n */\nexport const effectKeys = {\n /** `fs.snapshot.materialize` */\n snapshotMaterialize: (runId: RunId): string => `snap:${runId}`,\n /** `git.branch.create` / `git.ref.create` */\n gitRefCreate: (runId: RunId, name: string): string => `ref:${runId}:${name}`,\n /** `git.worktree.add` */\n worktreeAdd: (runId: RunId, slot: string): string => `wt:${runId}:${slot}`,\n /** `git.worktree.remove` (deviation above) */\n worktreeRemove: (runId: RunId, slot: string): string => `wt:${runId}:${slot}:remove`,\n /** `provision.command` */\n provisionCommand: (runId: RunId, slot: string, lockfileSha256: Sha256): string =>\n `prov:${runId}:${slot}:${lockfileSha256}`,\n /** `agent.spawn` */\n agentSpawn: (runId: RunId, agentId: AgentId, incarnation: number): string => `${runId}:${agentId}:${incarnation}`,\n /** `tool.write_file` / `tool.patch_file` / `tool.run_command`, and (deviation above) `tool.read` /\n * `tool.network_request` / `tool.git_commit` */\n toolCall: (runId: RunId, agentId: AgentId, incarnation: number, ordinal: number): string =>\n `tool:${runId}:${agentId}:${incarnation}:${ordinal}`,\n /** `check.command` — `treeDigest` computed ONCE before the check sequence (DESIGN 2.5.2), not per check */\n checkCommand: (runId: RunId, name: string, treeDigest: string): string => `check:${runId}:${name}:${treeDigest}`,\n /** `git.commit` */\n gitCommit: (runId: RunId, slot: string, n: number): string => `commit:${runId}:${slot}:${n}`,\n /** `git.merge` */\n gitMerge: (runId: RunId, fromSha: string, intoSha: string): string => `merge:${runId}:${fromSha}:${intoSha}`,\n /** `git.worktree.reset` */\n worktreeReset: (runId: RunId, slot: string, checkpointSha: string, n: number): string =>\n `reset:${runId}:${slot}:${checkpointSha}:${n}`,\n /** an approval bound to one tool call (the fast path, DESIGN 4.5) */\n approvalByToolCall: (toolCallId: string): string => `apr:${toolCallId}`,\n /** an approval not bound to a specific call (`ship`, `budget`, `loop-stalled`, ...) */\n approvalByKind: (runId: RunId, kind: string, phaseRunId: string): string => `apr:${runId}:${kind}:${phaseRunId}`,\n} as const;\n","import type { EffectId } from '@cohorte/base';\nimport { type JsonValue, sha256Hex } from '@cohorte/base';\nimport type { RuntimeToolCall, RuntimeToolResult, ToolCallContext, ToolHost } from '@cohorte/runtime-contract';\nimport type { PolicyVerdict } from '@cohorte/security/contract';\nimport type { ToolExecuteResult } from '@cohorte/tools/catalogue';\nimport type { ToolHostDeps } from '../contract/factories.ts';\nimport { effectKeys } from '../durability/journal/keys.ts';\n\nconst asJson = (value: unknown): JsonValue => value as JsonValue;\n\nfunction textResult(deps: ToolHostDeps, text: string, isError = true): RuntimeToolResult {\n const sealed = deps.redactor.sealText(text).text;\n return { isError, content: [{ type: 'text', text: sealed }] };\n}\n\nfunction denial(deps: ToolHostDeps, _call: RuntimeToolCall, verdict: PolicyVerdict): RuntimeToolResult {\n return textResult(deps, `${verdict.modelFacingReason} [${verdict.stage}/${verdict.ruleId}]`);\n}\n\nfunction effectIdFor(call: RuntimeToolCall): EffectId {\n return `eff_${sha256Hex(`${call.runId}:${call.agentId}:${call.incarnation}:${call.ordinal}`).slice(0, 32)}` as EffectId;\n}\n\nfunction outputPayload(\n deps: ToolHostDeps,\n call: RuntimeToolCall,\n effectId: EffectId,\n result: ToolExecuteResult<JsonValue>,\n) {\n const text = deps.redactor.sealText(result.modelText).text;\n const bytes = new TextEncoder().encode(result.modelText);\n return {\n type: 'tool.completed' as const,\n payload: {\n toolCallId: call.toolCallId,\n tool: call.tool,\n effectId,\n isError: false,\n timedOut: false,\n durationMs: 0,\n waitedMs: 0,\n output: {\n sha256: sha256Hex(bytes),\n bytes: bytes.byteLength,\n truncated: false,\n preview: text,\n },\n filesTouched: result.filesTouched,\n replayed: false,\n } as unknown as JsonValue,\n summary: `tool completed: ${call.tool}`,\n source: 'cohorte' as const,\n severity: 'success' as const,\n };\n}\n\n/** Host-side gate and execution pipeline. Runtime code never receives the policy or the executor. */\nexport function createToolHost(deps: ToolHostDeps): ToolHost {\n return {\n async handleToolCall(call, ctx: ToolCallContext): Promise<RuntimeToolResult> {\n if (ctx.signal.aborted) return textResult(deps, 'tool call aborted');\n\n const gateCall = {\n runId: call.runId,\n agentId: call.agentId,\n incarnation: call.incarnation,\n toolCallId: call.toolCallId,\n tool: call.tool,\n input: call.input,\n phase: 'unknown',\n role: 'unknown',\n } as const;\n try {\n await deps.recordRequested(gateCall);\n } catch (cause) {\n return textResult(deps, cause instanceof Error ? cause.message : 'unable to record tool request');\n }\n const verdict = deps.policy.evaluate(gateCall, deps.grantFor(gateCall), deps.policySnapshot, deps.policyPorts);\n if (verdict.decision === 'deny') {\n try {\n await deps.recordDenied(gateCall, verdict);\n } catch (cause) {\n return textResult(deps, cause instanceof Error ? cause.message : 'unable to record tool denial');\n }\n return denial(deps, call, verdict);\n }\n\n let decision = verdict.decision;\n let approvalId = verdict.approvalId;\n if (decision === 'ask') {\n const answer = await deps.requestApproval(gateCall, verdict, ctx.signal);\n if (answer.decision === 'deny') {\n try {\n await deps.recordDenied(gateCall, verdict);\n } catch (cause) {\n return textResult(deps, cause instanceof Error ? cause.message : 'unable to record tool denial');\n }\n return denial(deps, call, verdict);\n }\n decision = answer.decision;\n approvalId = answer.approvalId as typeof approvalId;\n }\n\n const implementation = deps.toolRegistry.get(call.tool);\n if (!implementation || !verdict.normalized)\n return textResult(deps, `tool ${call.tool} has no executable implementation`);\n\n const execution = deps.executionFor(gateCall);\n const normalized = verdict.normalized;\n const plan = implementation.plan(call.input as never, normalized as never, execution);\n const execute = (): Promise<ToolExecuteResult<JsonValue>> =>\n implementation.execute(call.input as never, normalized as never, execution, ctx.signal) as Promise<\n ToolExecuteResult<JsonValue>\n >;\n\n if (plan === null) {\n try {\n const result = await execute();\n return {\n isError: false,\n content: [{ type: 'text', text: deps.redactor.sealText(result.modelText).text }],\n };\n } catch (cause) {\n return textResult(deps, cause instanceof Error ? cause.message : 'tool execution failed');\n }\n }\n\n const effectId = effectIdFor(call);\n const key = effectKeys.toolCall(call.runId, call.agentId, call.incarnation, call.ordinal);\n const started = {\n type: 'tool.started' as const,\n payload: {\n toolCallId: call.toolCallId,\n tool: call.tool,\n effectId,\n decision,\n ruleId: verdict.ruleId,\n ...(verdict.grantId === undefined ? {} : { grantId: verdict.grantId }),\n normalizedArgs: call.input,\n replayClass: plan.replayClass,\n sandbox: deps.sandbox,\n } as unknown as JsonValue,\n summary: `tool started: ${call.tool}`,\n source: 'cohorte' as const,\n };\n\n try {\n const executionResult = await deps.journal.run(\n deps.leaseFor(gateCall),\n {\n intent: {\n runId: call.runId,\n idempotencyKey: key,\n kind: plan.kind,\n replayClass: plan.replayClass,\n agentId: call.agentId,\n toolCallId: call.toolCallId,\n request: asJson({ tool: call.tool, input: call.input }),\n verify: plan.verify,\n ...(decision === 'allow-once' && approvalId ? { consumesGrant: approvalId as never } : {}),\n },\n before: [started],\n async perform(signal) {\n const result = await implementation.execute(call.input as never, normalized as never, execution, signal);\n return {\n result: asJson(result),\n after: [outputPayload(deps, call, effectId, result as ToolExecuteResult<JsonValue>)],\n };\n },\n },\n ctx.signal,\n );\n const result = executionResult.result as unknown as ToolExecuteResult<JsonValue>;\n return {\n isError: false,\n content: [{ type: 'text', text: deps.redactor.sealText(result.modelText).text }],\n ...(implementation.terminal ? { terminate: true } : {}),\n };\n } catch (cause) {\n return textResult(deps, cause instanceof Error ? cause.message : 'journaled tool execution failed');\n }\n },\n };\n}\n","// Durable approval service (DESIGN 4.5). Resolution is state-only: an approval never\n// executes a tool; consumption belongs to the consuming effect transaction.\nimport { type ApprovalId, canonicalJson, type JsonValue, sha256Hex } from '@cohorte/base';\nimport type { ApprovalDecisionRecord, ApprovalRecord } from '@cohorte/persistence/contract';\nimport type { ApprovalRequest } from '@cohorte/protocol';\nimport type { RuntimeToolCall } from '@cohorte/runtime-contract';\nimport type { PolicyEngine } from '@cohorte/security/contract';\nimport { createRedactor } from '@cohorte/security/redact';\nimport type { ApprovalsDeps, ToolHostDeps } from '../contract/factories.ts';\nimport type { ApprovalService, ApprovedCall, ToolHostReplay } from '../contract/internal.ts';\nimport type { ApprovalDraft } from '../contract/types.ts';\nimport { createToolHost } from '../toolhost/implementation.ts';\n\nexport type { ApprovalsDeps };\n\nconst sleep = (signal: AbortSignal): Promise<void> =>\n new Promise((resolve) => {\n const timer = setTimeout(resolve, 50);\n signal.addEventListener(\n 'abort',\n () => {\n clearTimeout(timer);\n resolve();\n },\n { once: true },\n );\n });\n\nfunction grantKey(draft: ApprovalDraft): string {\n const material = {\n tool: draft.tool ?? null,\n args: draft.args ?? null,\n preStateSha256: draft.preStateSha256 ?? null,\n } as unknown as JsonValue;\n return sha256Hex(canonicalJson(material));\n}\n\nfunction requestOf(draft: ApprovalDraft, approvalId: ApprovalId): ApprovalRequest {\n const {\n idempotencyKey: _idempotencyKey,\n grantKey: _grantKey,\n agentId: _agentId,\n incarnation: _incarnation,\n toolCallId: _toolCallId,\n ...rest\n } = draft;\n return { ...rest, approvalId, cli: `cohorte approve ${approvalId}` } as ApprovalRequest;\n}\n\nexport function createApprovalService(deps: ApprovalsDeps): ApprovalService {\n const redactor = deps.redactor ?? createRedactor();\n const runs = new Map<ApprovalId, string>();\n\n return {\n request(tx, draft): ApprovalId {\n const approvalId = deps.ids.next<'ApprovalId'>('apr');\n const request = requestOf(draft, approvalId);\n const sealed = redactor.sealJson(request as unknown as JsonValue).value;\n const event = deps.events.append(tx, [\n {\n type: 'approval.requested',\n payload: request as unknown as JsonValue,\n summary: request.preview.text,\n severity: 'warning',\n source: 'cohorte',\n },\n ])[0];\n const now = deps.clock.now();\n const record: ApprovalRecord = {\n approvalId,\n runId: tx.run().runId,\n idempotencyKey: draft.idempotencyKey,\n kind: request.kind,\n ...(draft.agentId === undefined ? {} : { agentId: draft.agentId }),\n ...(draft.incarnation === undefined ? {} : { incarnation: draft.incarnation }),\n ...(draft.toolCallId === undefined ? {} : { toolCallId: draft.toolCallId }),\n status: 'pending',\n request: sealed,\n grantKey: draft.grantKey || grantKey(draft),\n requestedSeq: event?.sequence ?? tx.run().lastSequence,\n createdAt: now,\n ...(request.expiresAt === undefined ? {} : { expiresAt: request.expiresAt }),\n };\n tx.putApproval(record);\n runs.set(approvalId, record.runId);\n return approvalId;\n },\n\n async await(id, signal): Promise<ApprovalDecisionRecord> {\n let runId = runs.get(id);\n while (!signal.aborted) {\n if (runId) {\n const tree = await deps.store.readRunTree(runId as never);\n const record = tree.approvals.find((approval) => approval.approvalId === id);\n if (record?.decision) return { ...record.decision, resolvedSeq: record.resolvedSeq ?? 0 };\n } else {\n const candidates = await deps.store.listRuns({ limit: 1000, offset: 0 });\n for (const candidate of candidates) {\n const tree = await deps.store.readRunTree(candidate.runId);\n if (tree.approvals.some((approval) => approval.approvalId === id)) {\n runId = candidate.runId;\n break;\n }\n }\n }\n await sleep(signal);\n }\n throw new Error('approval wait aborted');\n },\n\n grantFor(tx, key) {\n return tx.findGrant(tx.run().runId, key);\n },\n\n async approvedUnconsumed(runId, agentId): Promise<ApprovedCall[]> {\n const tree = await deps.store.readRunTree(runId);\n return tree.approvals\n .filter((approval) => approval.agentId === agentId && approval.consumedByEffect === undefined)\n .filter((approval) => approval.status === 'allow-once' || approval.status === 'allow-for-run')\n .flatMap((approval) => {\n const request = approval.request as unknown as Partial<ApprovalRequest> & {\n call?: RuntimeToolCall;\n answer?: string;\n };\n if (!request.call || typeof request.call !== 'object') return [];\n return [\n {\n approvalId: approval.approvalId,\n call: request.call,\n grantKey: approval.grantKey,\n ...(request.answer === undefined ? {} : { answer: request.answer }),\n } satisfies ApprovedCall,\n ];\n });\n },\n };\n}\n\nexport function createToolHostReplay(deps: ToolHostDeps): ToolHostReplay {\n return {\n async replayApproved(lease, approved, signal) {\n const gateCall = {\n runId: approved.call.runId,\n agentId: approved.call.agentId,\n incarnation: approved.call.incarnation,\n toolCallId: approved.call.toolCallId,\n tool: approved.call.tool,\n input: approved.call.input,\n phase: 'unknown',\n role: 'unknown',\n } as const;\n const verdict = deps.policy.evaluate(gateCall, deps.grantFor(gateCall), deps.policySnapshot, deps.policyPorts);\n if (verdict.decision === 'deny') return { outcome: 'denied-by-gate' };\n if (deps.grantKeyFor(gateCall, verdict) !== approved.grantKey) return { outcome: 'binding-changed' };\n\n const replayPolicy: PolicyEngine = {\n evaluate(call, grant, policy, ports) {\n const replayVerdict = deps.policy.evaluate(call, grant, policy, ports);\n if (replayVerdict.decision !== 'ask') return replayVerdict;\n return {\n ...replayVerdict,\n decision: 'allow-once' as const,\n approvalId: approved.approvalId,\n };\n },\n };\n const host = createToolHost({\n ...deps,\n policy: replayPolicy,\n leaseFor: () => lease,\n requestApproval: async () => ({ decision: 'deny' as const }),\n recordRequested: async () => undefined,\n recordDenied: async () => undefined,\n });\n const result = await host.handleToolCall(approved.call, {\n signal,\n progress: () => undefined,\n });\n return { outcome: 'executed', result };\n },\n };\n}\n","// DESIGN 4.3 — crash points: a named registry, a recorded golden run, a meta-test. `crashpoint(name)` is inert\n// unless `COHORTE_CRASH_AT=<name>[#n]` is set (a REAL `SIGKILL`, no `finally`) or an in-process fault injector is\n// armed for `name` (a `SimulatedCrash`, for fast in-process crash tests that never fork a process). Both paths are\n// no-ops for a point that is not, right now, the one asked for — which is what makes an unhit declared point a test\n// failure elsewhere (the harness asserts the golden run's recorded `(point, occurrence)` pairs were all hit) and a\n// new transition's crash cases free (it only has to hit points this registry already names).\n/** DESIGN 4.3, table rows 1-21 (row 22, SQLite's own WAL durability, calls no `crashpoint()`); a row whose name\n * contains \"/\" in the table's prose is two independent named points, each hit and recorded separately. */\nexport const CRASHPOINTS = [\n 'start.after-run-row',\n 'host.after-lease',\n 'snapshot.mid-materialize',\n 'transition.before-commit',\n 'transition.after-commit',\n 'transition-effect.after-intent',\n 'transition-effect.after-external',\n 'plan.after-commit',\n 'provision.after-worktree-add',\n 'provision.after-install',\n 'spawn.after-intent',\n 'spawn.after-ready',\n 'tool.after-requested',\n 'approval.after-requested',\n 'tool.after-intent',\n 'tool.after-effect',\n 'tool.after-done',\n 'agent.after-exit-before-collect',\n 'commit.after-git-commit',\n 'merge.after-update-ref',\n 'phase.before-completed-commit',\n 'checkpoint.after-events-before-snapshot',\n 'command.external.after-accepted',\n 'ship.after-approval',\n 'locks.after-release',\n 'reset.after-git-reset',\n] as const;\nexport type Crashpoint = (typeof CRASHPOINTS)[number];\n\nconst CRASHPOINT_SET: ReadonlySet<string> = new Set(CRASHPOINTS);\nexport const isCrashpoint = (value: string): value is Crashpoint => CRASHPOINT_SET.has(value);\n\nexport interface FaultInjector {\n /** true = crash HERE, on this occurrence (1-based) of this named point */\n shouldFail(point: Crashpoint, occurrence: number): boolean;\n}\n\nlet injector: FaultInjector | null = null;\n\n/** Test-only wiring point: `@cohorte/testkit`'s `FaultInjector` calls this, never a direct import in either\n * direction (core may not depend on testkit from `src/**`, and testkit never re-implements this registry). */\nexport function setFaultInjector(next: FaultInjector | null): void {\n injector = next;\n}\n\nexport class SimulatedCrash extends Error {\n readonly point: Crashpoint;\n readonly occurrence: number;\n constructor(point: Crashpoint, occurrence: number) {\n super(`simulated crash at ${point}#${occurrence}`);\n this.name = 'SimulatedCrash';\n this.point = point;\n this.occurrence = occurrence;\n }\n}\n\nconst occurrences = new Map<Crashpoint, number>();\n\n/** Resets the per-process occurrence counters; called between golden-run recordings and between test cases. */\nexport function resetCrashpointOccurrences(): void {\n occurrences.clear();\n}\n\ninterface EnvTarget {\n point: string;\n occurrence?: number;\n}\n\nfunction parseCrashAtEnv(raw: string | undefined): EnvTarget | null {\n if (!raw) return null;\n const hash = raw.indexOf('#');\n if (hash === -1) return { point: raw };\n const occurrence = Number.parseInt(raw.slice(hash + 1), 10);\n const point = raw.slice(0, hash);\n return Number.isFinite(occurrence) && occurrence > 0 ? { point, occurrence } : { point };\n}\n\n/**\n * Marks a named crash point. Bumps the point's occurrence counter first (so a `#n` target sees the SAME numbering\n * whichever mechanism is armed), then: `COHORTE_CRASH_AT` matching this point (and this occurrence, when `#n` is\n * given) kills the process for real; otherwise an armed `FaultInjector` may throw `SimulatedCrash`. Both checks are\n * skipped, and this is a true no-op, when neither is configured.\n */\nexport function crashpoint(name: Crashpoint): void {\n if (!isCrashpoint(name)) throw new TypeError(`crashpoint: ${JSON.stringify(name)} is not in CRASHPOINTS`);\n const occurrence = (occurrences.get(name) ?? 0) + 1;\n occurrences.set(name, occurrence);\n\n const target = parseCrashAtEnv(process.env.COHORTE_CRASH_AT);\n if (target && target.point === name && (target.occurrence === undefined || target.occurrence === occurrence)) {\n process.kill(process.pid, 'SIGKILL');\n return;\n }\n if (injector?.shouldFail(name, occurrence)) throw new SimulatedCrash(name, occurrence);\n}\n","// @cohorte/core/durability/journal — DESIGN 4.1 (intent -> effect -> done), 4.2 E7 (the journal's own sub-steps),\n// 4.3 (#6, #12, #13: crash points), 0.2 I5 (\"Events first, then effects\"), 2.5 (`EffectJournal`, `EffectSpec`).\n// PLAN U1.08. Wave-0 seam (PLAN U0.08) replaced: this file is now the implementation.\n//\n// `JournalDeps` is the FROZEN contract of `contract/factories.ts`, re-exported below — never a second interface of the\n// same name. It gained `redactor` in U0.08's fix round 1: `completeEffect` demands a `SealedJson` result (I7), so\n// `run()` needs a redactor to seal `perform()`'s return value before it is persisted, and the frozen type was WIDENED\n// where it lives rather than shadowed here.\nimport { CohorteError, errorOf, type JsonValue, toErrorInfo } from '@cohorte/base';\nimport type { EffectIntent, EffectKind, LeaseToken, StoreTx } from '@cohorte/persistence/contract';\nimport type { JournalDeps } from '../../contract/factories.ts';\nimport type { EffectJournal, EffectSpec } from '../../contract/internal.ts';\nimport { type Crashpoint, crashpoint } from '../crashpoints.ts';\n\nexport { effectKeys } from './keys.ts';\nexport type { JournalDeps };\n\n/**\n * The three positions DESIGN 4.1 defines — after the intent transaction, after the external effect, after the done\n * transaction — named per effect KIND. The journal is one code path but the crash registry (DESIGN 4.3) is not: a\n * single hardcoded `tool.*` family would (a) make `tool.after-intent#3` of a crash-matrix case land inside a\n * snapshot, a provisioning command or a merge, since `crashpoint()` counts occurrences per NAME, and (b) leave\n * `transition-effect.after-intent` / `.after-external` never hit, which fails the crash suite (\"a declared point\n * never hit fails the suite\").\n *\n * A kind with no dedicated row in the 4.3 table gets the generic transition-effect pair, which row 6 names for\n * exactly that: an effect run through the journal from a transition (`create-integration-branch` =\n * `git.branch.create`, `mint-review-ref` = `git.ref.create`, …). Rows with only ONE named point fire only that one:\n * `provision.after-worktree-add`, `commit.after-git-commit`, `merge.after-update-ref` and `reset.after-git-reset`\n * all describe the world AFTER the external effect, with the row still `intent`. Recorded as R8 in\n * docs/v3/requests/U1.08.md.\n */\ninterface CrashFamily {\n afterIntent?: Crashpoint;\n afterExternal?: Crashpoint;\n afterDone?: Crashpoint;\n}\n\nconst TOOL_FAMILY: CrashFamily = {\n afterIntent: 'tool.after-intent',\n afterExternal: 'tool.after-effect',\n afterDone: 'tool.after-done',\n};\n/** DESIGN 4.3 row 6 — the generic pair of an effect journaled from a transition (DESIGN 4.2 E6). */\nconst TRANSITION_FAMILY: CrashFamily = {\n afterIntent: 'transition-effect.after-intent',\n afterExternal: 'transition-effect.after-external',\n};\n\nconst CRASH_FAMILY = {\n // no dedicated row: `snapshot.mid-materialize` (row 3) is fired INSIDE the materialiser's own loop, not here\n 'fs.snapshot.materialize': TRANSITION_FAMILY,\n 'git.branch.create': TRANSITION_FAMILY, // T04 `create-integration-branch`\n 'git.ref.create': TRANSITION_FAMILY, // T08 `mint-review-ref`\n 'git.worktree.add': { afterExternal: 'provision.after-worktree-add' }, // row 8\n 'git.worktree.remove': TRANSITION_FAMILY,\n 'git.worktree.reset': { afterExternal: 'reset.after-git-reset' }, // row 21\n 'git.commit': { afterExternal: 'commit.after-git-commit' }, // row 15\n 'git.merge': { afterExternal: 'merge.after-update-ref' }, // row 16\n 'provision.command': { afterExternal: 'provision.after-install' }, // row 8\n 'check.command': TOOL_FAMILY, // a check IS a journaled command execution (DESIGN 2.5.2), same three positions\n 'agent.spawn': { afterIntent: 'spawn.after-intent', afterExternal: 'spawn.after-ready' }, // row 9\n 'tool.read': TOOL_FAMILY,\n 'tool.write_file': TOOL_FAMILY, // rows 12, 13\n 'tool.patch_file': TOOL_FAMILY,\n 'tool.run_command': TOOL_FAMILY,\n 'tool.network_request': TOOL_FAMILY,\n 'tool.git_commit': TOOL_FAMILY,\n} as const satisfies Record<EffectKind, CrashFamily>;\n\n/** The crash points of one effect kind; exported for the crash matrix (DESIGN 7.3) and the tests of this unit. */\nexport function crashFamilyOf(kind: EffectKind): CrashFamily {\n return CRASH_FAMILY[kind];\n}\n\nfunction fire(point: Crashpoint | undefined): void {\n if (point !== undefined) crashpoint(point);\n}\n\nexport function createEffectJournal(deps: JournalDeps): EffectJournal {\n return {\n async run<R extends JsonValue>(\n lease: LeaseToken,\n spec: EffectSpec<R>,\n signal: AbortSignal,\n ): Promise<{ status: 'done' | 'replayed'; result: R }> {\n const runId = spec.intent.runId;\n const crashes = crashFamilyOf(spec.intent.kind);\n\n // `spec.intent` carries plain `request`/`verify` (DESIGN 2.5's `EffectSpec`, frozen in `contract/internal.ts`);\n // `StateStore.beginEffect` persists an `EffectIntent`, whose `request`/`verify` are `SealedJson` (I7). Sealing\n // them is this journal's job — `sealJson`'s own generic parameter mints the brand, never an `as Sealed…`\n // assertion (check-layers rule f).\n const sealedIntent: EffectIntent = {\n ...spec.intent,\n request: deps.redactor.sealJson(spec.intent.request).value,\n verify: deps.redactor.sealJson(spec.intent.verify).value,\n };\n\n // tx A: assert fencing (the store does it, I6) ; beginEffect(+consumesGrant) + the \"started\" events -> 'intent'.\n const begin = await deps.store.transact({ runId }, lease, (tx: StoreTx) => {\n const result = tx.beginEffect(sealedIntent);\n if (result.status === 'started' && spec.before.length > 0) deps.events.append(tx, spec.before);\n return result;\n });\n\n if (begin.status === 'already-done') {\n // I4.1: the same key seen again -> the caller replays the stored result; nothing re-executes.\n return { status: 'replayed', result: begin.record.result as unknown as R };\n }\n if (begin.status === 'open') {\n // 'open' = an `intent` or `in-doubt` row from an EARLIER incarnation, not yet reconciled. Reconciliation by\n // replay class (DESIGN 4.1) is `Resumer`'s job (a different port), never a blind re-execution here: `run()`\n // fails closed. DEVIATION (docs/v3/requests/U1.08.md): \"open => verifier policy hook\" names no verifier\n // dependency in `JournalDeps`; the smallest consistent reading is this fail-closed refusal.\n throw new CohorteError(\n errorOf(\n 'human-required/in-doubt-effect',\n `effect ${spec.intent.idempotencyKey} (${spec.intent.kind}) is still ${begin.record.state}: it must be reconciled by resume before running again`,\n ),\n );\n }\n\n // DESIGN 4.3, the \"after intent\" position of this kind's family: intent committed, before the external effect.\n fire(crashes.afterIntent);\n\n let performed: Awaited<ReturnType<EffectSpec<R>['perform']>>;\n try {\n performed = await spec.perform(signal);\n } catch (thrown) {\n const info = toErrorInfo(thrown, { code: 'tool-terminal/unexpected', class: 'tool-terminal' });\n // Recording the failure is BEST EFFORT and never replaces the error the caller is waiting for. The common\n // way for this transaction to reject is the lease being stolen while `perform` ran (I6): the caller would\n // then learn that the lease is gone and never what the tool actually failed with, and the effect row would\n // be left at `intent` with no recorded error either way. `intent` is exactly what recovery reconciles by\n // replay class (DESIGN 4.1); the lost lease is caught by the next effect, which fails closed on its own.\n try {\n await deps.store.transact({ runId }, lease, (tx: StoreTx) => {\n tx.failEffect(begin.effectId, info);\n });\n } catch {\n /* the store refused (typically conflict/lease-lost): the row stays `intent` for recovery */\n }\n throw thrown;\n }\n\n // The \"after external\" position: the effect happened, before it is recorded done.\n fire(crashes.afterExternal);\n\n const sealedResult = deps.redactor.sealJson(performed.result);\n\n // tx B: assert fencing ; completeEffect(result) + the \"completed\" events + ledger rows -> 'done'.\n await deps.store.transact({ runId }, lease, (tx: StoreTx) => {\n if (performed.after.length > 0) deps.events.append(tx, performed.after);\n tx.completeEffect(begin.effectId, sealedResult.value, performed.post);\n for (const entry of performed.ledger ?? []) tx.putLedger(entry);\n });\n\n // The \"after done\" position (row 13, tool kinds only): done committed, result not yet delivered to the caller.\n fire(crashes.afterDone);\n\n return { status: 'done', result: performed.result };\n },\n };\n}\n","// @cohorte/core/durability/lease — DESIGN 2.4 / 6.4 (\"lease TTL 15s, renewed every 5s\"), 0.2 I6 (one writer per\n// run, fenced). PLAN U1.08. Wave-0 seam (PLAN U0.08) replaced: this file is now the implementation.\n//\n// `LeaseManager` (frozen, contract/internal.ts) wraps the store's lock primitives (acquire/renew/release) — DESIGN\n// PC-4's \"own port over the store's lock/lease primitives\". The keeper below is the \"lease keeper\" the deliverable\n// names: it renews on a timer and tells its caller the moment a renewal stops succeeding, which is what makes \"a\n// lost lease stops every further effect with conflict/lease-lost\" true in practice — the STORE already refuses the\n// next write transaction on a stale fencing token (`transact`'s first statement, I6); the keeper's only job is not\n// to let the host keep issuing work past that point without knowing.\nimport { type Clock, CohorteError, errorOf, type RunId } from '@cohorte/base';\nimport type { LeaseToken, LockRequest } from '@cohorte/persistence/contract';\nimport type { LeaseDeps } from '../../contract/factories.ts';\nimport type { LeaseManager } from '../../contract/internal.ts';\nimport type { HostContext } from '../../contract/types.ts';\n\n// The FROZEN contract of `contract/factories.ts`, re-exported — never a second interface of the same name.\nexport type { LeaseDeps };\n\n/**\n * The identity a `LockOwner` needs: DESIGN 4.4 step 3 and crash point #2 compare the stored `(pid, startToken)` of a\n * lock against the live process table (\"live owner => conflict/run-host-alive; dead owner => stealLock\"), so both\n * fields must describe a REAL process. It is `HostContext` (contract/types.ts) minus what a lock does not store —\n * the run host already carries exactly these three fields.\n */\nexport type LeaseHost = Pick<HostContext, 'hostId' | 'pid' | 'startToken'>;\n\n/**\n * DESIGN.md §2.4: \"`startToken`: OS process start time: orphan kill never trusts a bare pid\". Derived from the REAL\n * wall clock and `process.uptime()` — never from `deps.clock`, which a test or a replay may freeze: the value has to\n * be the one a sweeper re-derives for that pid from the OS (`ps -o lstart`, `/proc/<pid>/stat`), not a run-local\n * timestamp. Computed ONCE per process: `process.uptime()` drifts by a millisecond between calls and the token must\n * be stable for every lock this process takes.\n */\nconst PROCESS_START_TOKEN = String(Math.round(Date.now() - process.uptime() * 1000));\n\n/** `NO_RUN_ID` (`@cohorte/persistence/contract`), restated rather than imported: `core -> persistence` is a\n * TYPE-ONLY edge (`layers.json`), so the constant itself may not cross it from `src/**`. */\nconst NO_RUN_ID = '' as RunId;\n\n/** The OS process start time of THIS process, as a `LockOwner.startToken` (see {@link PROCESS_START_TOKEN}). */\nexport function processStartToken(): string {\n return PROCESS_START_TOKEN;\n}\n\n/**\n * DEVIATION (docs/v3/requests/U1.08.md R7): the frozen `LeaseDeps` carries no host identity, so a manager built\n * without an explicit `host` names itself from the process it runs in. `pid` and `startToken` are then still exactly\n * what the sweeper checks; only `hostId` is a stand-in for the run host's own id, and it is marked as one.\n */\nfunction processHost(): LeaseHost {\n return { hostId: `host:${process.pid}:${PROCESS_START_TOKEN}`, pid: process.pid, startToken: PROCESS_START_TOKEN };\n}\n\n/**\n * `host` is the run host's identity (`HostContext`). It is a second parameter rather than a field of `LeaseDeps`\n * because `LeaseDeps` is frozen in `contract/factories.ts` (U0.08): request R7 asks for it to move there, and until\n * it does, this optional parameter lets a composition root that HAS the identity pass the truth instead of the\n * process-derived stand-in. The frozen one-argument call `createLeaseManager(deps)` keeps working unchanged.\n */\nexport function createLeaseManager(deps: LeaseDeps, host: LeaseHost = processHost()): LeaseManager {\n return {\n async acquire(\n scope: { runId: RunId } | 'project',\n key: string,\n mode: 'shared' | 'exclusive',\n ttlMs: number,\n ): Promise<LeaseToken> {\n const req: LockRequest = {\n scope: scope === 'project' ? 'project' : 'run',\n key,\n mode,\n owner: {\n ...(scope === 'project' ? {} : { runId: scope.runId }),\n hostId: host.hostId,\n pid: host.pid,\n startToken: host.startToken,\n },\n ttlMs,\n };\n const acquired = await deps.store.acquireLock(req);\n if (acquired.ok) return acquired.lease;\n\n // ADOPTION, not a conflict: the store refuses \"as long as a CONFLICTING row exists\", and a row whose owner is\n // THIS very process — same hostId, same pid, same OS start token — is not another holder, it is us. The run\n // host reaches this on every run: `Resumer` takes the run lease in DESIGN 4.4 step 3 and the loop that called\n // it then asks for the same lock (`RunEngine.run`, G1-D1). The adopted token keeps the EXISTING fencing token:\n // bumping it (a `stealLock`) would invalidate the lease the holder — again, us — is already writing with.\n //\n // The branch is narrowed to EXACTLY the case G1-D1 needs: the RUN lock, EXCLUSIVE on both sides. `locksConflict`\n // matches on (scope, key) alone, so without the mode test a `shared` request would be handed the `exclusive`\n // lock this host holds — two leases over one row, either one's `release()` destroying the other's and the\n // survivor's next `renew()` answering `conflict/lease-lost`. DESIGN 4.4 step 6 rebuilds the PROJECT lock as\n // shared, so that request is real. Aliasing two acquisitions of one lock also hands them one fencing token,\n // which is 0.2 I6 (\"one writer per run, fenced\") lost inside a process. Everything else falls through to the\n // refusal below, exactly as before the gate.\n const sole = acquired.heldBy.length === 1 ? acquired.heldBy[0] : undefined;\n if (\n req.scope === 'run' &&\n mode === 'exclusive' &&\n sole &&\n sole.mode === 'exclusive' &&\n sole.ownerHostId === host.hostId &&\n sole.ownerPid === host.pid &&\n sole.ownerStartToken === host.startToken\n ) {\n return {\n lockId: sole.lockId,\n runId: sole.ownerRunId ?? NO_RUN_ID,\n hostId: sole.ownerHostId,\n fencingToken: sole.fencingToken,\n };\n }\n\n // A refused lock is a run OUTCOME, not an internal error: everything downstream (checkGlobalStops, the retry\n // policy, T25/T26) classifies by `error.class` / `error.code`. The run's own lock being held is precisely\n // \"a run host already drives this run\" (DESIGN 4.4 step 3); any other scope is an unclassified conflict.\n const holders = acquired.heldBy\n .map((lock) => `${lock.ownerHostId} (pid ${lock.ownerPid}, startToken ${lock.ownerStartToken})`)\n .join(', ');\n const code = req.scope === 'run' ? 'conflict/run-host-alive' : 'conflict/unexpected';\n throw new CohorteError(\n errorOf(code, `${req.scope}:${key} is already held by ${holders || 'a conflicting lock'}`),\n );\n },\n\n renew(lease: LeaseToken, ttlMs: number): Promise<boolean> {\n return deps.store.renewLock(lease.lockId, ttlMs);\n },\n\n release(lease: LeaseToken): Promise<void> {\n return deps.store.releaseLock(lease.lockId);\n },\n };\n}\n\n/** DESIGN 6.4: renew every 5 s, TTL 15 s. */\nexport const LEASE_TTL_MS = 15_000;\nexport const LEASE_RENEW_INTERVAL_MS = 5_000;\n\nexport interface LeaseKeeperOptions {\n ttlMs?: number;\n renewIntervalMs?: number;\n /** Called ONCE, the first time a renewal fails to confirm the lease is still held (`renewLock` returns false, or\n * throws). After this fires the keeper stops renewing: the caller is expected to stop issuing effects. */\n onLost: (lease: LeaseToken) => void;\n}\n\nexport interface LeaseKeeper {\n /** Stops the renewal timer. Idempotent. */\n stop(): void;\n /** True once `onLost` has fired (or `stop()` has not been called and the last renewal failed). */\n lost(): boolean;\n}\n\n/**\n * Starts renewing `lease` on an interval until `stop()` is called or a renewal fails. `renewLock` returning `false`\n * means the row is simply gone (released, or never existed under this id) — the run host MUST stop producing\n * effects (DESIGN 2.4): the keeper fires `onLost` exactly once and stops its own timer.\n */\nexport function keepLeaseAlive(\n manager: LeaseManager,\n clock: Clock,\n lease: LeaseToken,\n options: LeaseKeeperOptions,\n): LeaseKeeper {\n const ttlMs = options.ttlMs ?? LEASE_TTL_MS;\n const renewIntervalMs = options.renewIntervalMs ?? LEASE_RENEW_INTERVAL_MS;\n let stopped = false;\n let lost = false;\n const controller = new AbortController();\n\n const declareLost = (): void => {\n // `stopped` guards the TERMINAL path, not just `schedule()`: a renewal already travelling to the store when the\n // caller stops the keeper answers (or rejects) afterwards, and on an ordinary shutdown — release the lease, stop\n // the keeper — that answer is `false` BECAUSE we released it. `onLost` is what stops every further effect with\n // `conflict/lease-lost`, so firing it here would report a clean shutdown as a lost lease.\n if (lost || stopped) return;\n lost = true;\n stop();\n options.onLost(lease);\n };\n\n const tick = (): void => {\n if (stopped) return;\n manager\n .renew(lease, ttlMs)\n .then((held) => {\n if (!held) declareLost();\n else schedule();\n })\n .catch(() => declareLost());\n };\n\n function schedule(): void {\n if (stopped) return;\n clock\n .sleep(renewIntervalMs, controller.signal)\n .then(tick)\n .catch(() => {\n /* aborted by stop(): nothing to do */\n });\n }\n\n function stop(): void {\n if (stopped) return;\n stopped = true;\n controller.abort();\n }\n\n schedule();\n\n return {\n stop,\n lost: () => lost,\n };\n}\n","import { CohorteError, errorOf, type JsonValue } from '@cohorte/base';\nimport type { EffectKind, LeaseToken } from '@cohorte/persistence/contract';\nimport type { TransitionEffectId } from '../contract/ids.ts';\nimport type { EffectJournal } from '../contract/internal.ts';\nimport type { TransitionEffectRunner } from '../contract/ports.ts';\n\nexport type TransitionEffectHandler = (\n ctx: { runId: string; slot?: string; lease: LeaseToken },\n signal: AbortSignal,\n) => Promise<void>;\n\nexport interface TransitionEffectRunnerDeps {\n journal: EffectJournal;\n handlers?: Partial<Record<TransitionEffectId, TransitionEffectHandler>>;\n}\n\nconst KIND_BY_EFFECT: Readonly<Record<TransitionEffectId, EffectKind>> = {\n 'record-spec-hash': 'fs.snapshot.materialize',\n 'create-integration-branch': 'git.branch.create',\n 'open-approval': 'check.command',\n 'mint-review-ref': 'git.ref.create',\n 'synthesize-check-findings': 'check.command',\n 'record-approved-digest': 'check.command',\n 'release-locks': 'git.worktree.remove',\n 'write-ship-report': 'fs.snapshot.materialize',\n 'checkpoint-worktrees': 'git.worktree.reset',\n checkpoint: 'fs.snapshot.materialize',\n 'park-agents': 'agent.spawn',\n 'schedule-wakeup': 'check.command',\n 'cancel-agents': 'agent.spawn',\n 'freeze-worktrees': 'git.worktree.reset',\n 'record-human-ack': 'check.command',\n 'record-skip': 'check.command',\n};\n\nconst asJson = (value: unknown): JsonValue => value as JsonValue;\n\nexport function createTransitionEffectRunner(deps: TransitionEffectRunnerDeps): TransitionEffectRunner {\n return {\n async run(id, ctx, signal) {\n const handler = deps.handlers?.[id];\n if (!handler) {\n throw new CohorteError(\n errorOf('configuration/policy-invalid', `No handler is registered for transition effect ${id}.`),\n );\n }\n await deps.journal.run(\n ctx.lease,\n {\n intent: {\n runId: ctx.runId as never,\n idempotencyKey: `transition:${ctx.runId}:${id}`,\n kind: KIND_BY_EFFECT[id],\n replayClass: 'idempotent',\n ...(ctx.slot ? { slot: ctx.slot } : {}),\n request: asJson({ effect: id, slot: ctx.slot ?? null }),\n verify: asJson({ effect: id }),\n },\n before: [],\n perform: async (performSignal) => {\n await handler(ctx, performSignal);\n return { result: true, after: [] };\n },\n },\n signal,\n );\n },\n };\n}\n","// DESIGN 2.5.1 — the persisted `TransitionRecord`'s idempotency key, verbatim template:\n// `${runId}:${profile}@${tableVersion}:${defId}:${fromPhaseRunId ?? '-'}:${discriminator}`.\n//\n// DEVIATION: DESIGN gives the template but not what feeds `discriminator` — the piece that keeps two firings of the\n// SAME row (e.g. T09 on round 2 of a FIX loop) from colliding. This function does not decide that (it is the\n// engine's, a later wave's, business: an iteration number, a guard-outcome digest, a retry ordinal are all legal\n// choices depending on the row); it only supplies the exact template, with every input the caller already has.\n\nimport type { PhaseRunId, RunId } from '@cohorte/base';\nimport type { PipelineProfile } from '@cohorte/protocol';\n\nexport interface TransitionIdempotencyKeyInput {\n runId: RunId;\n profile: PipelineProfile;\n tableVersion: number;\n defId: string;\n /** the phase the transition fires FROM, when it is an active one; absent from IDLE and from every `*suspended` /\n * `*active`-wildcard-sourced row whose `from` names no single phase run. */\n fromPhaseRunId?: PhaseRunId;\n /** caller-supplied: what distinguishes this firing of `defId` from an earlier one on the same run (DESIGN does\n * not name its shape; see the file header). */\n discriminator: string;\n}\n\nexport function transitionIdempotencyKey(input: TransitionIdempotencyKeyInput): string {\n return `${input.runId}:${input.profile}@${input.tableVersion}:${input.defId}:${input.fromPhaseRunId ?? '-'}:${input.discriminator}`;\n}\n","// DESIGN 2.5.1 — pieces every versioned transition table (`feature.v1.ts`, `bugfix.v1.ts`, `review.v1.ts`) shares:\n// the `*active` / `*suspended` / `*any-non-terminal` wildcard matcher, the T20-T27 + T30-T32 \"tail\" (identical across\n// profiles per ADR-0018 §3: \"T20-T33 identical\"), `entryEffectsOf` (T33's derivation rule) and the StopReason -> row\n// lookup the totality tests hold every table to.\n//\n// DEVIATION (recorded in docs/v3/requests/U0.09.md): `TransitionDef.from` is ONE string (DESIGN 2.5.1's own type),\n// so a row whose prose lists several `from` values or an \"or\" of guards cannot be a single AND-precondition row.\n// Two patterns close the gap without widening the frozen `TransitionDef` shape (contract/types.ts, U0.08, read-only):\n// 1. A wildcard `from` — `*active`, `*suspended`, and one this file ADDS, `*any-non-terminal` (T27's\n// `{IDLE,*active,*suspended,FAILED,BLOCKED}`) — resolved by `matchesFrom`.\n// 2. An \"or\" of guards (T06, T12) becomes SEVERAL candidate rows with the same `(from, reason, to)` and one guard\n// each; `resolveTransition` tries candidates in table order and returns the first whose preconditions all hold,\n// which is exactly OR semantics over AND-only rows.\nimport type {\n ActivePipelineState,\n PipelineProfile,\n PipelineState,\n StopReason,\n TransitionReason,\n} from '@cohorte/protocol';\nimport { ACTIVE_PIPELINE_STATES, SUSPENDED_STATES, TERMINAL_STATES } from '@cohorte/protocol';\nimport type { GuardId, TransitionEffectId } from '../../contract/ids.ts';\nimport type { TransitionDef, TransitionTable } from '../../contract/types.ts';\n\n/** Not in DESIGN's two named wildcards: T27 alone needs \"everywhere except the two terminal states\". */\nexport const ANY_NON_TERMINAL_FROM = '*any-non-terminal';\nexport const ACTIVE_FROM = '*active';\nexport const SUSPENDED_FROM = '*suspended';\nexport const RESUME_TO = '*resumeTo';\n\nconst SUSPENDED_SET: readonly string[] = SUSPENDED_STATES;\nconst TERMINAL_SET: readonly string[] = TERMINAL_STATES;\n\n/** Whether a row's `from` (a concrete state or one of the three wildcards above) covers the given state.\n *\n * `*active` is resolved against the TABLE's own `phases`, not the global `ACTIVE_PIPELINE_STATES`: a profile that\n * removes a phase (bugfix@1 has no BRAINSTORM/SPEC, review@1 only TEST/REVIEW/FIX) must not have its wildcard tail\n * fire from a state it does not have — `tables.totality.test.ts`'s \"no row is SOURCED from an active state outside\n * table.phases\" is the mirror of the existing \"no row TARGETS a state outside table.phases\". `*suspended` and\n * `*any-non-terminal` are unaffected: no suspended state is ever a phase, and T27 (`cancel`) is legal from every\n * non-terminal state by design. The default keeps the global set so a caller without a table still behaves. */\nexport function matchesFrom(\n rowFrom: string,\n state: PipelineState,\n activePhases: readonly ActivePipelineState[] = ACTIVE_PIPELINE_STATES,\n): boolean {\n switch (rowFrom) {\n case ACTIVE_FROM:\n return (activePhases as readonly string[]).includes(state);\n case SUSPENDED_FROM:\n return SUSPENDED_SET.includes(state);\n case ANY_NON_TERMINAL_FROM:\n return !TERMINAL_SET.includes(state);\n default:\n return rowFrom === state;\n }\n}\n\n/** DESIGN 2.5.1 T33: derived from the table, never hand-listed twice. Empty for PREFLIGHT, BUILD and FIX. */\nconst SUCCESS_REASON_BY_PHASE: Readonly<Partial<Record<ActivePipelineState, TransitionReason>>> = {\n TEST: 'tests-pass',\n REVIEW: 'review-approved',\n SHIP: 'shipped',\n};\n\nexport function entryEffectsOf(table: TransitionTable, phase: ActivePipelineState): readonly TransitionEffectId[] {\n const reason = SUCCESS_REASON_BY_PHASE[phase];\n if (!reason) return [];\n const row = table.rows.find((candidate) => candidate.from === phase && candidate.reason === reason);\n return (row?.effects ?? []) as readonly TransitionEffectId[];\n}\n\n/** One phase this profile lets `skip` fire from, and where it lands — the profile's OWN \"next(X)\", never a shared\n * constant: a skip row must target a state inside `table.phases` like every other row (the totality test PLAN §…\n * requires of every row). feature/bugfix's REVIEW skips to SHIP; review@1 lets `skip` fire from TEST and FIX only —\n * its REVIEW is NOT skippable, because in that profile the verdict is the product. */\nexport interface SkippablePhaseTarget {\n phase: ActivePipelineState;\n to: PipelineState;\n}\n\nfunction skipRow(target: SkippablePhaseTarget, entryEffects: readonly TransitionEffectId[]): TransitionDef {\n return {\n id: `T33-${target.phase}`,\n from: target.phase,\n to: target.to,\n reason: 'skip-command',\n actor: 'human',\n preconditions: ['policy.skip-allows', 'skip.justified'] satisfies readonly GuardId[],\n effects: ['record-skip', ...entryEffects],\n };\n}\n\n/** Built AFTER the profile's own rows exist, so `entryEffectsOf` reads real success-path effects instead of a second,\n * hand-typed copy (T33's own deliverable text). `profile`/`phases` are only what `entryEffectsOf` needs to find the\n * success-path row per skippable phase; the returned rows carry no profile of their own. */\nexport function buildSkipRows(\n profile: PipelineProfile,\n phases: readonly ActivePipelineState[],\n headRows: readonly TransitionDef[],\n targets: readonly SkippablePhaseTarget[],\n): readonly TransitionDef[] {\n const partial: TransitionTable = { profile, version: 1, initial: 'IDLE', phases, rows: headRows };\n return targets.map((target) => skipRow(target, entryEffectsOf(partial, target.phase)));\n}\n\n/** The T20-T32 tail (DESIGN ADR-0018 §3: \"T20-T33 identical\"), parameterised only by which row answers\n * `check-environment` and `review-clean` in THIS profile (T33 is profile-specific: `buildSkipRows` above). */\nexport function buildTailRows(): readonly TransitionDef[] {\n return [\n {\n id: 'T20',\n from: ACTIVE_FROM,\n to: 'PAUSED',\n reason: 'pause-command',\n actor: 'human',\n preconditions: [],\n effects: ['park-agents', 'checkpoint-worktrees'],\n },\n {\n id: 'T21',\n from: ACTIVE_FROM,\n to: 'WAITING_APPROVAL',\n reason: 'needs-human',\n actor: 'system',\n preconditions: ['approval.pending-blocking'] satisfies readonly GuardId[],\n effects: [],\n },\n {\n id: 'T22',\n from: ACTIVE_FROM,\n to: 'AUTH_REQUIRED',\n reason: 'auth-required',\n actor: 'system',\n preconditions: [],\n effects: ['park-agents', 'checkpoint-worktrees'],\n },\n {\n id: 'T23',\n from: ACTIVE_FROM,\n to: 'QUOTA_EXCEEDED',\n reason: 'quota-exceeded',\n actor: 'system',\n preconditions: [],\n effects: ['park-agents', 'checkpoint-worktrees', 'schedule-wakeup'],\n },\n {\n id: 'T24',\n from: ACTIVE_FROM,\n to: 'WAITING_APPROVAL',\n reason: 'stop-rule',\n actor: 'system',\n preconditions: [],\n effects: ['open-approval'],\n },\n {\n id: 'T25',\n from: ACTIVE_FROM,\n to: 'BLOCKED',\n reason: 'security-violation',\n actor: 'system',\n preconditions: [],\n effects: ['cancel-agents', 'freeze-worktrees'],\n },\n {\n id: 'T25-stop',\n from: ACTIVE_FROM,\n to: 'BLOCKED',\n reason: 'stop-rule',\n actor: 'system',\n preconditions: [],\n effects: ['cancel-agents', 'freeze-worktrees'],\n },\n {\n id: 'T26',\n from: ACTIVE_FROM,\n to: 'FAILED',\n reason: 'unexpected-error',\n actor: 'system',\n preconditions: [],\n effects: ['cancel-agents', 'checkpoint-worktrees', 'checkpoint'],\n },\n {\n id: 'T27',\n from: ANY_NON_TERMINAL_FROM,\n to: 'CANCELLED',\n reason: 'cancel-command',\n actor: 'human',\n preconditions: [],\n effects: ['cancel-agents', 'release-locks'],\n },\n // DESIGN 2.5.1 conditions T30's extra guard on the suspension CAUSE (\"plus `approval.none-pending-blocking` /\n // `auth.plan-satisfied`), but the command matrix maps the WHOLE `*suspended` column of `resume` to this single\n // id: a human `resume` on an AUTH_REQUIRED or QUOTA_EXCEEDED run fires T30, never the cause-keyed siblings below\n // (they answer the SYSTEM reasons `auth-restored` / `quota-reset`, which no `resume` command carries). A wildcard\n // row must therefore be at least as strict as every cause it covers, so T30 carries BOTH extra guards — resuming\n // into an active phase with auth broken would only bounce the run straight back to AUTH_REQUIRED through T22.\n {\n id: 'T30',\n from: SUSPENDED_FROM,\n to: RESUME_TO,\n reason: 'resume-command',\n actor: 'either',\n preconditions: [\n 'resume.locks-rebuilt',\n 'resume.git-verified',\n 'runtime.pin-valid',\n 'approval.none-pending-blocking',\n 'auth.plan-satisfied',\n ] satisfies readonly GuardId[],\n effects: [],\n },\n {\n id: 'T30-approval',\n from: SUSPENDED_FROM,\n to: RESUME_TO,\n reason: 'approval-resolved',\n actor: 'either',\n preconditions: [\n 'resume.locks-rebuilt',\n 'resume.git-verified',\n 'runtime.pin-valid',\n 'approval.none-pending-blocking',\n ] satisfies readonly GuardId[],\n effects: [],\n },\n {\n id: 'T30-auth',\n from: SUSPENDED_FROM,\n to: RESUME_TO,\n reason: 'auth-restored',\n actor: 'either',\n preconditions: [\n 'resume.locks-rebuilt',\n 'resume.git-verified',\n 'runtime.pin-valid',\n 'auth.plan-satisfied',\n ] satisfies readonly GuardId[],\n effects: [],\n },\n {\n id: 'T30-quota',\n from: SUSPENDED_FROM,\n to: RESUME_TO,\n reason: 'quota-reset',\n actor: 'either',\n preconditions: ['resume.locks-rebuilt', 'resume.git-verified', 'runtime.pin-valid'] satisfies readonly GuardId[],\n effects: [],\n },\n // DESIGN 2.5.1 defines T31 as \"T30 guards + `retry.target-legal`\" and T32 as \"`resume.acknowledged` + T30\n // guards\", so both follow T30's guard list above.\n {\n id: 'T31',\n from: 'FAILED',\n to: RESUME_TO,\n reason: 'retry-command',\n actor: 'human',\n preconditions: [\n 'resume.locks-rebuilt',\n 'resume.git-verified',\n 'runtime.pin-valid',\n 'approval.none-pending-blocking',\n 'auth.plan-satisfied',\n 'retry.target-legal',\n ] satisfies readonly GuardId[],\n effects: [],\n },\n {\n id: 'T32',\n from: 'BLOCKED',\n to: RESUME_TO,\n reason: 'resume-command',\n actor: 'human',\n preconditions: [\n 'resume.acknowledged',\n 'resume.locks-rebuilt',\n 'resume.git-verified',\n 'runtime.pin-valid',\n 'approval.none-pending-blocking',\n 'auth.plan-satisfied',\n ] satisfies readonly GuardId[],\n effects: ['record-human-ack'],\n },\n ];\n}\n\n/** DESIGN 2.5.3 / spec 11.2: the row every `StopReason` resolves to, in THIS profile — `check-environment` and\n * `review-clean` are profile-specific (a review table has no SHIP, a feature/bugfix table's REVIEW-clean success\n * path is T14; see the totality test for why each placement was chosen). */\nexport function stopRowMap(profileSpecific: {\n checkEnvironment: string;\n reviewClean: string;\n}): Readonly<Record<StopReason, string>> {\n return {\n 'review-clean': profileSpecific.reviewClean,\n 'iteration-limit': 'T24',\n 'budget-exhausted': 'T24',\n timeout: 'T24',\n 'identical-failure': 'T24',\n 'no-progress': 'T24',\n 'policy-violation': 'T25-stop',\n 'approval-required': 'T21',\n 'unexpected-repo-change': 'T25-stop',\n 'runtime-incompatible': 'T25-stop',\n 'auth-required': 'T22',\n 'quota-exceeded': 'T23',\n paused: 'T20',\n cancelled: 'T27',\n 'agent-dead': 'T24',\n unreviewed: 'T21',\n 'internal-error': 'T26',\n 'check-environment': profileSpecific.checkEnvironment,\n };\n}\n","// DESIGN 2.5.1 — `feature@1`: every row T01-T33 of the master table, `as const satisfies TransitionTable`. Rows T06\n// and T12 read as \"guard A or guard B [or C]\" in DESIGN's prose; `TransitionDef.preconditions` is AND-only (the\n// frozen contract type, DESIGN 2.5.1), so each disjunct becomes its own candidate row sharing `(from, reason, to)` —\n// see `tables/shared.ts`'s header comment for why this is exactly OR semantics under `resolveTransition`'s\n// first-match-wins candidate order (deviation recorded in docs/v3/requests/U0.09.md).\nimport { ACTIVE_PIPELINE_STATES } from '@cohorte/protocol';\nimport type { GuardId } from '../../contract/ids.ts';\nimport type { TransitionDef, TransitionTable } from '../../contract/types.ts';\nimport { buildSkipRows, buildTailRows, stopRowMap } from './shared.ts';\n\nconst HEAD_ROWS: readonly TransitionDef[] = [\n // BRAINSTORM/SPEC: rows exist for totality (ADR-0018 §5), `phase.available` is false in V3.0 (see pipeline/guards).\n {\n id: 'T01',\n from: 'IDLE',\n to: 'BRAINSTORM',\n reason: 'start',\n actor: 'human',\n preconditions: ['input.is-idea', 'phase.available'] satisfies readonly GuardId[],\n effects: [],\n },\n {\n id: 'T02',\n from: 'BRAINSTORM',\n to: 'SPEC',\n reason: 'ready',\n actor: 'human',\n preconditions: ['brainstorm.output-valid'] satisfies readonly GuardId[],\n effects: [],\n },\n {\n id: 'T03',\n from: 'SPEC',\n to: 'PREFLIGHT',\n reason: 'ready',\n actor: 'human',\n preconditions: ['spec.schema-valid', 'spec.frozen'] satisfies readonly GuardId[],\n effects: ['record-spec-hash'],\n },\n {\n id: 'T04',\n from: 'IDLE',\n to: 'PREFLIGHT',\n reason: 'start',\n actor: 'either',\n preconditions: [\n 'spec.schema-valid',\n 'spec.frozen',\n 'host.not-root',\n 'host.outside-target',\n 'config.trust-satisfied',\n 'snapshot.captured',\n 'runtime.pin-valid',\n 'runtime.platform-supported',\n 'auth.plan-satisfied',\n 'billing.consented',\n 'sandbox.meets-policy',\n 'repo.base-resolved',\n 'locks.project+zones-held',\n ] satisfies readonly GuardId[],\n effects: ['create-integration-branch'],\n },\n {\n id: 'T05',\n from: 'PREFLIGHT',\n to: 'BUILD',\n reason: 'ready',\n actor: 'system',\n preconditions: [\n 'readiness.in',\n 'contract.present-or-exempt',\n 'surfaces.all-owned',\n 'budget.available',\n ] satisfies readonly GuardId[],\n effects: [],\n },\n // T06: \"readiness.not-ready OR surfaces.unowned\" -> two candidate rows.\n {\n id: 'T06',\n from: 'PREFLIGHT',\n to: 'WAITING_APPROVAL',\n reason: 'needs-human',\n actor: 'system',\n preconditions: ['readiness.not-ready'] satisfies readonly GuardId[],\n effects: ['open-approval'],\n },\n {\n id: 'T06-surfaces',\n from: 'PREFLIGHT',\n to: 'WAITING_APPROVAL',\n reason: 'needs-human',\n actor: 'system',\n preconditions: ['surfaces.unowned'] satisfies readonly GuardId[],\n effects: ['open-approval'],\n },\n {\n id: 'T07',\n from: 'BUILD',\n to: 'TEST',\n reason: 'built',\n actor: 'system',\n preconditions: [\n 'agents.all-completed',\n 'outputs.schema-valid',\n 'diff.within-ownership',\n 'integration.merged',\n 'tree.digest-recorded',\n ] satisfies readonly GuardId[],\n effects: [],\n },\n {\n id: 'T08',\n from: 'TEST',\n to: 'REVIEW',\n reason: 'tests-pass',\n actor: 'system',\n preconditions: ['checks.all-passed', 'checks.digest-equals-integration'] satisfies readonly GuardId[],\n effects: ['mint-review-ref'],\n },\n {\n id: 'T09',\n from: 'TEST',\n to: 'FIX',\n reason: 'tests-fail',\n actor: 'system',\n preconditions: ['checks.failed-non-environmental', 'loop.may-continue'] satisfies readonly GuardId[],\n effects: ['synthesize-check-findings'],\n },\n {\n id: 'T10',\n from: 'REVIEW',\n to: 'SHIP',\n reason: 'review-approved',\n actor: 'system',\n preconditions: [\n 'review.nothing-to-fix',\n 'review.no-unreviewed',\n 'review.leftovers-parked-or-waived',\n 'reviewref.digest-equals-integration',\n ] satisfies readonly GuardId[],\n effects: ['record-approved-digest'],\n },\n {\n id: 'T11',\n from: 'REVIEW',\n to: 'FIX',\n reason: 'review-findings',\n actor: 'system',\n preconditions: [\n 'review.has-fix-items',\n 'loop.may-continue',\n 'review.no-contract-change',\n ] satisfies readonly GuardId[],\n effects: [],\n },\n // T12: \"one of review.contract-change, review.leftovers-routed-ask, review.security-needs-investigation\".\n {\n id: 'T12',\n from: 'REVIEW',\n to: 'WAITING_APPROVAL',\n reason: 'needs-human',\n actor: 'system',\n preconditions: ['review.contract-change'] satisfies readonly GuardId[],\n effects: ['open-approval'],\n },\n {\n id: 'T12-leftovers',\n from: 'REVIEW',\n to: 'WAITING_APPROVAL',\n reason: 'needs-human',\n actor: 'system',\n preconditions: ['review.leftovers-routed-ask'] satisfies readonly GuardId[],\n effects: ['open-approval'],\n },\n {\n id: 'T12-security',\n from: 'REVIEW',\n to: 'WAITING_APPROVAL',\n reason: 'needs-human',\n actor: 'system',\n preconditions: ['review.security-needs-investigation'] satisfies readonly GuardId[],\n effects: ['open-approval'],\n },\n {\n id: 'T13',\n from: 'FIX',\n to: 'TEST',\n reason: 'fixed',\n actor: 'system',\n preconditions: ['agents.all-completed', 'diff.within-ownership', 'integration.merged'] satisfies readonly GuardId[],\n effects: [],\n },\n {\n id: 'T14',\n from: 'SHIP',\n to: 'COMPLETED',\n reason: 'shipped',\n actor: 'system',\n preconditions: [\n 'approval.ship-allowed',\n 'tree.digest-equals-approved',\n 'acceptance.no-open-human-items',\n ] satisfies readonly GuardId[],\n effects: ['release-locks', 'write-ship-report'],\n },\n {\n id: 'T15',\n from: 'SHIP',\n to: 'TEST',\n reason: 'stop-rule',\n actor: 'system',\n preconditions: ['tree.digest-differs-from-approved'] satisfies readonly GuardId[],\n effects: [],\n },\n {\n id: 'T16',\n from: 'TEST',\n to: 'FAILED',\n reason: 'stop-rule',\n actor: 'system',\n preconditions: ['checks.errored-environmental'] satisfies readonly GuardId[],\n effects: ['checkpoint-worktrees', 'checkpoint'],\n },\n];\n\nexport const FEATURE_STOP_ROW_MAP = stopRowMap({ checkEnvironment: 'T16', reviewClean: 'T14' });\n\nconst SKIP_TARGETS = [\n { phase: 'PREFLIGHT', to: 'BUILD' },\n { phase: 'BUILD', to: 'TEST' },\n { phase: 'TEST', to: 'REVIEW' },\n { phase: 'REVIEW', to: 'SHIP' },\n { phase: 'FIX', to: 'TEST' },\n { phase: 'SHIP', to: 'COMPLETED' },\n] as const;\n\nexport const FEATURE_V1 = {\n profile: 'feature',\n version: 1,\n initial: 'IDLE',\n phases: ACTIVE_PIPELINE_STATES,\n rows: [\n ...HEAD_ROWS,\n ...buildTailRows(),\n ...buildSkipRows('feature', ACTIVE_PIPELINE_STATES, HEAD_ROWS, SKIP_TARGETS),\n ],\n} as const satisfies TransitionTable;\n","// DESIGN 2.5.1 / ADR-0018 §3: `bugfix@1` = `feature@1` minus the BRAINSTORM/SPEC entry rows (T01-T03), with\n// `spec.kind = 'patch'` selecting the patch PREFLIGHT contract variant — a `PhaseContract` concern (a later wave),\n// not a transition-row shape difference. T04 (the `either`-actor `IDLE -> PREFLIGHT` entry) is untouched.\nimport type { TransitionTable } from '../../contract/types.ts';\nimport { FEATURE_STOP_ROW_MAP, FEATURE_V1 } from './feature.v1.ts';\n\nconst EXCLUDED_IDS = new Set(['T01', 'T02', 'T03']);\nconst EXCLUDED_PHASES = new Set(['BRAINSTORM', 'SPEC']);\n\nexport const BUGFIX_STOP_ROW_MAP = FEATURE_STOP_ROW_MAP;\n\nexport const BUGFIX_V1 = {\n profile: 'bugfix',\n version: 1,\n initial: 'IDLE',\n phases: FEATURE_V1.phases.filter((phase) => !EXCLUDED_PHASES.has(phase)),\n rows: FEATURE_V1.rows.filter((row) => !EXCLUDED_IDS.has(row.id)),\n} as const satisfies TransitionTable;\n","// DESIGN 2.5.1 / ADR-0018 §3: `review@1` — `IDLE -> REVIEW` (guards `reviewtarget.resolved-to-sha`,\n// `snapshot.captured`, `auth.plan-satisfied`; effect `mint-review-ref`), `REVIEW -> COMPLETED` on any verdict\n// (reason `review-delivered`: the verdict IS the product), and `REVIEW -> FIX -> TEST -> REVIEW` only when the run\n// was started `withFix`. T20-T33 identical in SHAPE to feature/bugfix (ADR-0018 §3), but T33 (skip) and the\n// StopReason placements for `check-environment` / `review-clean` are re-derived against THIS table's own rows: this\n// profile has no SHIP, so `review-clean` lands on R02 (REVIEW -> COMPLETED) instead of feature's T14.\n//\n// `reviewtarget.resolved-to-sha` is a member of `GUARD_IDS` (contract/ids.ts, frozen by U0.08): an earlier draft of\n// this file recorded it as a gap (see git history / docs/v3/requests/U0.09.md) before checking the frozen file\n// itself — it was already there, so `R01`'s preconditions are typed `readonly GuardId[]` like every other row.\nimport type { ActivePipelineState } from '@cohorte/protocol';\nimport type { GuardId } from '../../contract/ids.ts';\nimport type { TransitionDef, TransitionTable } from '../../contract/types.ts';\nimport { buildSkipRows, buildTailRows, stopRowMap } from './shared.ts';\n\nconst PHASES: readonly ActivePipelineState[] = ['TEST', 'REVIEW', 'FIX'];\n\nconst HEAD_ROWS: readonly TransitionDef[] = [\n {\n id: 'R01',\n from: 'IDLE',\n to: 'REVIEW',\n reason: 'start',\n actor: 'either',\n preconditions: [\n 'reviewtarget.resolved-to-sha',\n 'snapshot.captured',\n 'auth.plan-satisfied',\n ] satisfies readonly GuardId[],\n effects: ['mint-review-ref'],\n },\n // \"on any verdict\": guard semantics (later wave) decide `nothing-to-fix` as either no fix items, or fix items\n // but the run was not started `withFix` — the profile-level distinction is the guard implementation's job, not\n // this table's (PLAN's \"smallest consistent reading\": reuse the existing id rather than mint a `withFix`-shaped\n // one `GUARD_IDS` does not have either).\n {\n id: 'R02',\n from: 'REVIEW',\n to: 'COMPLETED',\n reason: 'review-delivered',\n actor: 'system',\n preconditions: ['review.nothing-to-fix'] satisfies readonly GuardId[],\n effects: [],\n },\n {\n id: 'R03',\n from: 'REVIEW',\n to: 'FIX',\n reason: 'review-findings',\n actor: 'system',\n preconditions: ['review.has-fix-items', 'loop.may-continue'] satisfies readonly GuardId[],\n effects: [],\n },\n {\n id: 'R04',\n from: 'FIX',\n to: 'TEST',\n reason: 'fixed',\n actor: 'system',\n preconditions: ['agents.all-completed', 'diff.within-ownership', 'integration.merged'] satisfies readonly GuardId[],\n effects: [],\n },\n {\n id: 'R05',\n from: 'TEST',\n to: 'REVIEW',\n reason: 'tests-pass',\n actor: 'system',\n preconditions: ['checks.all-passed', 'checks.digest-equals-integration'] satisfies readonly GuardId[],\n effects: ['mint-review-ref'],\n },\n {\n id: 'R06',\n from: 'TEST',\n to: 'FIX',\n reason: 'tests-fail',\n actor: 'system',\n preconditions: ['checks.failed-non-environmental', 'loop.may-continue'] satisfies readonly GuardId[],\n effects: ['synthesize-check-findings'],\n },\n {\n id: 'R07',\n from: 'TEST',\n to: 'FAILED',\n reason: 'stop-rule',\n actor: 'system',\n preconditions: ['checks.errored-environmental'] satisfies readonly GuardId[],\n effects: ['checkpoint-worktrees', 'checkpoint'],\n },\n];\n\nexport const REVIEW_STOP_ROW_MAP = stopRowMap({ checkEnvironment: 'R07', reviewClean: 'R02' });\n\nconst SKIP_TARGETS = [\n { phase: 'TEST', to: 'REVIEW' },\n { phase: 'FIX', to: 'TEST' },\n] as const;\n\nexport const REVIEW_V1 = {\n profile: 'review',\n version: 1,\n initial: 'IDLE',\n phases: PHASES,\n rows: [...HEAD_ROWS, ...buildTailRows(), ...buildSkipRows('review', PHASES, HEAD_ROWS, SKIP_TARGETS)],\n} as const satisfies TransitionTable;\n","// DESIGN 2.5.1 \"Versioning\" — the version registry: `(profile, tableVersion)` -> the table that executes it, or\n// `'runtime-incompatible'` for a version this build does not ship. Tables are APPEND-ONLY files; resuming a run on\n// an unshipped version is never re-interpreted (ADR-0018 §2).\nimport type { PipelineProfile } from '@cohorte/protocol';\nimport type { TransitionTable } from '../../contract/types.ts';\nimport { BUGFIX_STOP_ROW_MAP, BUGFIX_V1 } from './bugfix.v1.ts';\nimport { FEATURE_STOP_ROW_MAP, FEATURE_V1 } from './feature.v1.ts';\nimport { REVIEW_STOP_ROW_MAP, REVIEW_V1 } from './review.v1.ts';\n\nexport { BUGFIX_STOP_ROW_MAP, BUGFIX_V1 } from './bugfix.v1.ts';\nexport { FEATURE_STOP_ROW_MAP, FEATURE_V1 } from './feature.v1.ts';\nexport { REVIEW_STOP_ROW_MAP, REVIEW_V1 } from './review.v1.ts';\nexport { entryEffectsOf, matchesFrom } from './shared.ts';\n\n/** Every table this build can execute, keyed by profile then version. Appending a version or a profile only ever\n * ADDS an entry (DESIGN 2.5.1: \"the engine keeps every version it can still execute\"). */\nexport const TABLE_REGISTRY = {\n feature: { 1: FEATURE_V1 },\n bugfix: { 1: BUGFIX_V1 },\n review: { 1: REVIEW_V1 },\n} as const satisfies Readonly<Record<string, Readonly<Record<number, TransitionTable>>>>;\n\n/** The `StopReason -> row id` map for the given, already-resolved table (DESIGN 2.5.3 / spec 11.2). */\nexport const STOP_ROW_MAPS: Readonly<Record<PipelineProfile, Readonly<Record<string, string>>>> = {\n feature: FEATURE_STOP_ROW_MAP,\n bugfix: BUGFIX_STOP_ROW_MAP,\n review: REVIEW_STOP_ROW_MAP,\n};\n\nexport type TableLookup = { ok: true; table: TransitionTable } | { ok: false; stop: 'runtime-incompatible' };\n\n/** Resolve `(profile, tableVersion)` to the table that must execute it. An unknown profile OR an unshipped version\n * of a known profile alike stop `runtime-incompatible` — never a re-interpretation (DESIGN 2.5.1). */\nexport function resolveTable(profile: string, tableVersion: number): TableLookup {\n const byVersion: Readonly<Record<number, TransitionTable>> | undefined = (\n TABLE_REGISTRY as Readonly<Record<string, Readonly<Record<number, TransitionTable>>>>\n )[profile];\n const table = byVersion?.[tableVersion];\n if (!table) return { ok: false, stop: 'runtime-incompatible' };\n return { ok: true, table };\n}\n","// DESIGN 4.2 E3 — \"step = nextStep(state, table): pure; nothing persisted\", read BEFORE E4's\n// \"facts = collectFacts(step.guards)\". At E3 the phase outcome / command that will supply `resolveTransition`'s\n// `reasonOrOutcome` is not known yet (it is derived elsewhere, after the phase actually runs, or carried by the\n// command itself) — so `nextStep`'s job is narrower and fully pure: given only the CURRENT pipeline state, narrow\n// the table to every row that could possibly fire from here (`from` matches, exact or wildcard) and hand back the\n// UNION of their guard ids, so `collectFacts` gathers everything ANY of them might need in one read-only pass.\n// `resolveTransition` (a sibling module) is what later picks the one row that actually fires.\nimport type { PipelineState } from '@cohorte/protocol';\nimport type { GuardId } from '../contract/ids.ts';\nimport type { RunState, TransitionDef, TransitionTable } from '../contract/types.ts';\nimport { matchesFrom } from './tables/index.ts';\n\nexport interface PipelineStep {\n readonly from: PipelineState;\n /** every row reachable from `from`, in table order; several may share the same `(from, reason)` (an \"or\" of\n * guards spelled as sibling rows, `tables/shared.ts`'s header comment) */\n readonly candidates: readonly TransitionDef[];\n /** the deduplicated union of every candidate's preconditions, ready for `collectFacts` */\n readonly guards: readonly GuardId[];\n}\n\nexport function nextStep(state: RunState, table: TransitionTable): PipelineStep {\n const from = state.run.state;\n const candidates = table.rows.filter((row) => matchesFrom(row.from, from, table.phases));\n const guards = [...new Set(candidates.flatMap((row) => row.preconditions))] as readonly GuardId[];\n return { from, candidates, guards };\n}\n","// DESIGN 2.6.7 — actor normalisation: `kind: 'human'` is kept ONLY for `transport: 'cli'`, never upgraded. V3.0 has\n// exactly one transport (`ACTOR_TRANSPORTS = ['cli']`, open on the wire), so this only ever fires for a forged or\n// future-transport envelope claiming humanity over a channel that cannot prove it.\nimport type { Actor } from '@cohorte/protocol';\n\n/** Downgrades `human` claimed over a non-`cli` transport to `client`; every other actor passes through unchanged. */\nexport function normalizeActor(actor: Actor): Actor {\n if (actor.kind === 'human' && actor.transport !== 'cli') return { ...actor, kind: 'client' };\n return actor;\n}\n\n/** The actor a SPONTANEOUS (non-command) transition records: `system`, never `human` (deliverable: \"the engine never\n * emits a transition with actor human without a causing commandId\"). `id` names the engine itself. */\nexport function systemActor(hostId: string): Actor {\n return { kind: 'system', id: hostId, transport: 'cli' };\n}\n","// DESIGN 4.2 (E2, E8), 4.3 (#18), spec 11.3 — `checkpoint.created` with a chain MAC anchor, `writeSnapshot` AFTER\n// the events. Two SEPARATE `store.transact()` calls, not one: crash point #18\n// (`checkpoint.after-events-before-snapshot`) can only land \"events without the new snapshot\" on disk if the events\n// already committed in their own transaction before the crash — DESIGN 4.2's single `tx { … }` line for this step is\n// a compressed depiction of the two.\n\nimport type { RunId } from '@cohorte/base';\nimport { canonicalJson, type JsonValue, sha256Hex } from '@cohorte/base';\nimport type { LeaseToken } from '@cohorte/persistence/contract';\nimport type { CheckpointCause, HostContext } from '../contract/types.ts';\nimport { crashpoint } from '../durability/crashpoints.ts';\nimport type { RunEngineDeps } from './deps.ts';\n\nexport interface WriteCheckpointArgs {\n deps: RunEngineDeps;\n runId: RunId;\n host: HostContext;\n lease: LeaseToken;\n cause: CheckpointCause;\n}\n\n/**\n * Reads the current run tree, seals it, hashes it, anchors a chain MAC over the run's chain tip AS IT STOOD before\n * this checkpoint, appends `checkpoint.created`, then — after the crash point — writes the `StoredSnapshot`.\n *\n * `RunTreeRows` is read through a round trip (`JSON.parse(JSON.stringify(…))`) before it is handed to\n * `canonicalJson`/`redactor.sealJson`: several of its members (`ErrorInfo`, embedded via `RunRecord.lastError` /\n * `StopRecord`) are `interface`s, and only an object TYPE gets the implicit string-index signature\n * `T extends JsonValue` needs (the same limitation `packages/core/src/events/index.ts` documents for `EventDraft`).\n * A JSON round trip re-states the same values as plain object-type literals — nothing renamed, nothing reshaped —\n * without the bespoke `DeepJson<T>` mapped type that file needed for a value sealed one field at a time; a whole\n * run tree is sealed here in one pass, so the round trip is the smaller mechanism for the same purpose.\n */\nexport async function writeCheckpoint({ deps, runId, host, lease, cause }: WriteCheckpointArgs): Promise<void> {\n const runState = await deps.store.readRunTree(runId);\n const plainState = JSON.parse(JSON.stringify(runState)) as JsonValue;\n const stateSha256 = sha256Hex(canonicalJson(plainState));\n const sealedState = deps.redactor.sealJson(plainState).value;\n\n let checkpointAtSequence = 0;\n await deps.store.transact({ runId }, lease, (tx) => {\n const before = tx.run();\n const atSequence = before.lastSequence;\n const chainHash = before.lastHash;\n const chainMac = deps.authenticator.anchor(runId, atSequence, chainHash, deps.projectKey);\n const [envelope] = deps.events.append(tx, [\n {\n type: 'checkpoint.created',\n payload: { atSequence, snapshotSha256: stateSha256, chainHash, chainMac, cause },\n summary: `checkpoint (${cause})`,\n },\n ]);\n checkpointAtSequence = envelope ? envelope.sequence : atSequence;\n });\n\n crashpoint('checkpoint.after-events-before-snapshot');\n\n await deps.store.transact({ runId }, lease, (tx) => {\n tx.writeSnapshot({\n runId,\n atSequence: checkpointAtSequence,\n schemaVersion: deps.schemaVersion,\n cohorteVersion: host.cohorteVersion,\n stateSha256,\n state: sealedState,\n });\n });\n}\n","// The RunEngine's own dependency shape.\n//\n// DEVIATION, LOUD (docs/v3/requests/U1.09.md): the Wave-0 `EngineDeps` (`contract/factories.ts`, frozen, owned by\n// U0.08) has exactly six fields (`store`, `clock`, `ids`, `resume`, `phases`, `loopPolicy`) — enough for the typed\n// `NotImplemented` stub, not for the real DESIGN 4.2 loop, which also needs the `GuardRegistry` + `FactCollector`\n// the deliverable names, a `TransitionEffectRunner`, an injected `checkGlobalStops`, a `CommandAuthenticator` (E1's\n// MAC verification), the project key it verifies against, an `EventWriter`, a `Redactor` (checkpoints seal the run\n// state before it is stored), and a `LeaseManager` (E0's \"renew the run lease\"). `contract/factories.ts` is not in\n// this unit's `ownedPaths`, so its frozen type cannot be edited here (PLAN §3 rule 7: contracts are read-only after\n// G0). Per PLAN's own worked example for exactly this situation (`docs/v3/requests/U0.08.md` R2: \"it may also\n// choose to move the `Deps` type and the factory into its own area file instead\"), `RunEngineDeps` lives HERE,\n// additively — every field of the frozen `EngineDeps` is still present, under the same name and type, so a\n// composition root that already built one only has to add fields, never rename or reshape what it has. The barrel\n// (`packages/core/src/index.ts`, not owned by this unit) still exports `createEngine` unchanged: it re-exports\n// whatever `./engine/index.ts` exports today, exactly as it does for `events`/`durability/journal`/`durability/lease`\n// once THEIR owning units filled them in (`docs/v3/requests/U0.08.md` R10/R11). Filed as a request so the G1\n// integrator can, if it prefers, fold this shape back into `contract/factories.ts`'s `EngineDeps` by the same\n// \"widen, never reshape\" rule R1 already establishes for `EventsDeps`/`JournalDeps`.\nimport type { Clock, IdSource, Redactor } from '@cohorte/base';\nimport type { LeaseToken, RunRecord, StateStore } from '@cohorte/persistence/contract';\nimport type { StopRecord } from '@cohorte/protocol';\nimport type { EventWriter, LeaseManager, PhaseExecutor, Resumer } from '../contract/internal.ts';\nimport type { CommandAuthenticator, FactCollector, GuardRegistry, TransitionEffectRunner } from '../contract/ports.ts';\nimport type { GlobalFacts, LoopPolicy, RunState } from '../contract/types.ts';\nimport type { TableLookup } from '../pipeline/tables/index.ts';\n\n/** `U0.09`'s own lookup result (`pipeline/tables/index.ts`), re-exported so a composition root can name the shape\n * `RunEngineDeps.resolveTable` returns without reaching past the engine. Declared there, never a second time. */\nexport type { TableLookup } from '../pipeline/tables/index.ts';\n\nexport interface RunEngineDeps {\n // ── the frozen `EngineDeps` (contract/factories.ts), unchanged ──────────────────────────────────────────────\n store: StateStore;\n clock: Clock;\n ids: IdSource;\n resume: Resumer;\n phases: PhaseExecutor;\n loopPolicy: LoopPolicy;\n\n // ── additive (see file header) ───────────────────────────────────────────────────────────────────────────────\n /** Every guard of `GUARD_IDS`, looked up by id (DESIGN 2.5.1). The real registry is `U2.05`'s. */\n guards: GuardRegistry;\n /** Gathers `GlobalFacts` before guard evaluation (E4) and before `checkGlobalStops` (E2) — one flat shape serves\n * both, so this engine calls it once per iteration and reuses the result for either. */\n factCollector: FactCollector;\n /** Runs one declarative `TransitionEffectId` of a firing row's `effects` column, through the journal. */\n transitionEffects: TransitionEffectRunner;\n /** DESIGN 2.5.3, pure; the real one is `U2.05`'s (checkpoint.ts, guards + FactCollector). */\n checkGlobalStops: (run: RunState, facts: GlobalFacts, policy: LoopPolicy) => StopRecord | null;\n /** DESIGN 2.5.1 \"Versioning\": `(profile, tableVersion) -> TransitionTable | 'runtime-incompatible'`. Injected,\n * not imported by this file, the same way `checkGlobalStops` is: the REAL one is\n * `../pipeline/tables/index.ts`'s `resolveTable` (a `U0.09`, Wave-0, same-package import a composition root wires\n * trivially); a unit test hands in a lookup over its OWN toy table instead — DESIGN's \"toy 2-state table LOCAL to\n * the tests\" is unreachable through a hard-coded `resolveTable(run.profile, run.tableVersion)` call, since that\n * always resolves to the real `feature`/`bugfix`/`review` tables. */\n resolveTable: (profile: string, tableVersion: number) => TableLookup;\n /** E1: verifies a command's MAC before anything else touches its payload. The real implementation is `U2.02`'s. */\n authenticator: CommandAuthenticator;\n /** The project key `authenticator.verify` / `.anchor` checks against — resolved once, outside a run, by whoever\n * builds these deps (a `KeyStore` read is out of this unit's scope: DESIGN 2.6.7's key path needs the project's\n * git common dir, which this loop never touches). */\n projectKey: Uint8Array;\n /** Writes durable events (strict-validate, redact, seal, append) — the real one is `U1.08`'s. */\n events: EventWriter;\n /** Seals the `RunState` a checkpoint snapshots before it is stored (DESIGN 0.2 I7: nothing unredacted persists). */\n redactor: Redactor;\n /** E0's \"renew the run lease\"; also acquires it once at the start of `run()`. */\n leases: LeaseManager;\n /** `StoredSnapshot.schemaVersion` (persistence's own migration counter, opaque here). */\n schemaVersion: number;\n /** Default `DEFAULT_LEASE_TTL_MS` (DESIGN 6.4: TTL 15s). */\n leaseTtlMs?: number;\n /** Lets a composition root bind host-side effects to the currently fenced run lease. */\n onLease?: (lease: LeaseToken | undefined) => void;\n /** How long `run()` sleeps when a pass finds nothing to do (no pending command, no open phase, no stop). Default\n * `DEFAULT_POLL_INTERVAL_MS` (DESIGN 4.7: \"the host polls every 250 ms\"). */\n pollIntervalMs?: number;\n /** Supplies the durable host-computed columns for an IDLE -> PREFLIGHT start. */\n startColumns?: (run: RunRecord) => Promise<Partial<RunRecord>>;\n}\n\n/** DESIGN 6.4. Not imported from `../durability/lease/index.ts` (`U1.08`'s area, a Wave-1 sibling this unit may not\n * depend on, PLAN §3 rule 4) even though it already defines the same constant. */\nexport const DEFAULT_LEASE_TTL_MS = 15_000;\n","// DESIGN 2.5.1 — the command x state matrix, as DATA: a spec-17.2 command is never \"IMPOSSIBLE\" in a state, it has\n// a row or a DEFINED rejection. DESIGN's own table uses six STATE CLASSES (`IDLE`, `*active`, `*suspended`,\n// `FAILED`, `BLOCKED`, `COMPLETED`/`CANCELLED`), not the eighteen concrete `PipelineState`s one at a time — this\n// file keeps that shape (`stateClassOf` classifies every concrete state into one of the six) so the matrix reads\n// exactly like DESIGN's table and the totality test can still walk every concrete state.\nimport {\n ACTIVE_PIPELINE_STATES,\n type ActivePipelineState,\n type PipelineState,\n SUSPENDED_STATES,\n TERMINAL_STATES,\n} from '@cohorte/protocol';\n\n/** The six columns of DESIGN 2.5.1's command x state matrix. */\nexport type StateClass = 'idle' | 'active' | 'suspended' | 'failed' | 'blocked' | 'terminal';\n\nconst ACTIVE_SET: readonly string[] = ACTIVE_PIPELINE_STATES;\nconst SUSPENDED_SET: readonly string[] = SUSPENDED_STATES;\nconst TERMINAL_SET: readonly string[] = TERMINAL_STATES;\n\nexport function stateClassOf(state: PipelineState): StateClass {\n if (state === 'IDLE') return 'idle';\n if (state === 'FAILED') return 'failed';\n if (state === 'BLOCKED') return 'blocked';\n if (ACTIVE_SET.includes(state)) return 'active';\n if (SUSPENDED_SET.includes(state)) return 'suspended';\n if (TERMINAL_SET.includes(state)) return 'terminal';\n throw new RangeError(`stateClassOf: unrecognised pipeline state ${JSON.stringify(state)}`);\n}\n\n/** The seven spec-17.2 commands this matrix covers — the other `CommandType`s (`start`, `status`, `inspect`,\n * `tail`, `run-tool`, `reconcile`, `shutdown`, `agent.send`) are reads, admin, or run creation, not a pipeline-state\n * transition, and DESIGN 2.5.1's table does not carry them. */\nexport const MATRIX_COMMANDS = ['pause', 'resume', 'retry', 'skip', 'cancel', 'approve', 'deny'] as const;\nexport type MatrixCommand = (typeof MATRIX_COMMANDS)[number];\n\n/** DESIGN 2.5.1 spells the skip row `T33` in prose, but the TABLES mint ONE row PER SKIPPABLE PHASE — `T33-TEST`,\n * `T33-REVIEW`, … (`tables/shared.ts`, `skipRow`), because each carries the entry effects of the success-path row it\n * replaces. There is therefore NO row whose id is the bare `T33`, and a matrix cell must never name one. */\nexport const SKIP_DEF_ID_PREFIX = 'T33-';\n\n/** The id of the `skip` row that fires from `phase` — for a suspended or FAILED run, of the run's `resumeTo`\n * (DESIGN 2.5.1's \"T33 if policy (on `resumeTo`)\"). Returns an id even for a phase this profile does not let `skip`\n * fire from: the caller looks it up in the run's own table, where an unskippable phase simply has no such row. */\nexport function skipDefIdFor(phase: ActivePipelineState): string {\n return `${SKIP_DEF_ID_PREFIX}${phase}`;\n}\n\nexport type CommandMatrixCell =\n | { readonly kind: 'transition'; readonly defId: string }\n /** the row is minted per phase: resolve it with `skipDefIdFor(phase)` against the run's own table, never as a\n * literal id (only `skip` is shaped this way — see `SKIP_DEF_ID_PREFIX`) */\n | { readonly kind: 'transition-per-phase'; readonly defIdPrefix: typeof SKIP_DEF_ID_PREFIX }\n | { readonly kind: 'noop' }\n | { readonly kind: 'reject'; readonly code: string; readonly message: string }\n /** applies (an approval decision) and MAY additionally trigger the named row — e.g. `approve` resolving the LAST\n * blocking approval fires T30. */\n | { readonly kind: 'applies'; readonly mayTransition?: string }\n /** `resume` on an IDLE run: no pipeline-state row fires (a signed `start` is already enqueued, DESIGN 4.3 #1) —\n * this wakes a detached host to drain it. */\n | { readonly kind: 'spawns-host' };\n\ntype Row = Readonly<Record<StateClass, CommandMatrixCell>>;\n\nconst reject = (code: string, message: string): CommandMatrixCell => ({ kind: 'reject', code, message });\nconst transition = (defId: string): CommandMatrixCell => ({ kind: 'transition', defId });\nconst noop: CommandMatrixCell = { kind: 'noop' };\nconst perPhaseSkip: CommandMatrixCell = { kind: 'transition-per-phase', defIdPrefix: SKIP_DEF_ID_PREFIX };\n\nexport const COMMAND_MATRIX = {\n pause: {\n idle: reject('conflict/not-running', 'pause: the run has not started'),\n active: transition('T20'),\n suspended: noop,\n // FAILED and BLOCKED are HALTED, not terminal (`HALTED_STATES`, protocol/vocabulary.ts): `retry` and\n // `resume --ack` are REQUIRED rows out of them, so the rejection must not tell the human the run is over.\n // DESIGN 2.5.1 reserves `conflict/run-terminal` for the COMPLETED/CANCELLED column alone.\n failed: reject('conflict/run-halted', 'pause: the run is halted; use `retry` to resume a FAILED run'),\n blocked: reject('conflict/run-halted', 'pause: the run is halted; use `resume --ack` to resume a BLOCKED run'),\n terminal: reject('conflict/run-terminal', 'pause: the run already stopped'),\n },\n resume: {\n idle: { kind: 'spawns-host' },\n active: noop,\n suspended: transition('T30'),\n failed: reject('conflict/use-retry', 'resume: a FAILED run is resumed with `retry`, not `resume`'),\n blocked: transition('T32'),\n terminal: reject('conflict/run-terminal', 'resume: the run already stopped'),\n },\n retry: {\n idle: reject('conflict/not-running', 'retry: the run has not started'),\n active: reject('conflict/run-active', 'retry: only an agent-level retry is legal while the run is active'),\n suspended: reject('conflict/use-resume', 'retry: a suspended run is resumed with `resume`, not `retry`'),\n failed: transition('T31'),\n blocked: reject('conflict/use-resume-ack', 'retry: a BLOCKED run is resumed with `resume --ack`, not `retry`'),\n terminal: reject('conflict/run-terminal', 'retry: the run already stopped'),\n },\n skip: {\n idle: reject('conflict/not-running', 'skip: the run has not started'),\n active: perPhaseSkip,\n suspended: perPhaseSkip,\n failed: perPhaseSkip,\n blocked: reject('conflict/run-blocked', 'skip: a BLOCKED run is resumed first'),\n terminal: reject('conflict/run-terminal', 'skip: the run already stopped'),\n },\n cancel: {\n idle: transition('T27'),\n active: transition('T27'),\n suspended: transition('T27'),\n failed: transition('T27'),\n blocked: transition('T27'),\n terminal: noop,\n },\n approve: {\n idle: reject('conflict/not-running', 'approve: nothing is pending for a run that has not started'),\n active: { kind: 'applies', mayTransition: 'T30' },\n suspended: { kind: 'applies', mayTransition: 'T30' },\n failed: { kind: 'applies' },\n blocked: { kind: 'applies' },\n terminal: reject('conflict/run-terminal', 'approve: the run already stopped'),\n },\n deny: {\n idle: reject('conflict/not-running', 'deny: nothing is pending for a run that has not started'),\n active: { kind: 'applies', mayTransition: 'T30' },\n suspended: { kind: 'applies', mayTransition: 'T30' },\n failed: { kind: 'applies' },\n blocked: { kind: 'applies' },\n terminal: reject('conflict/run-terminal', 'deny: the run already stopped'),\n },\n} as const satisfies Readonly<Record<MatrixCommand, Row>>;\n\nexport function commandMatrixCell(command: MatrixCommand, state: PipelineState): CommandMatrixCell {\n return COMMAND_MATRIX[command][stateClassOf(state)];\n}\n","// DESIGN 2.5.1 — pure lookup + guard check over ONE `TransitionTable`. Never touches a store, never evaluates a\n// `Guard` itself: `guardOutcomes` are already-computed `GuardOutcomeLike`s (facts gathered by `collectFacts`,\n// evaluated by whatever later wave owns the `GuardRegistry`, DESIGN 2.5.1 \"facts are gathered BEFORE\").\n//\n// DEVIATION (docs/v3/requests/U0.09.md): DESIGN names `resolveTransition(table, from, reasonOrOutcome,\n// guardOutcomes)` without spelling `reasonOrOutcome`'s shape. Two things need disambiguating beyond a bare\n// `TransitionReason`: the ordinary per-phase outcome (`tests-pass`, `built`, `review-approved`, ...) already IS a\n// `TransitionReason` one-for-one (DESIGN 2.5.1's own table), so passing it directly covers that half. The half that\n// is NOT a 1:1 reason is the `*active`/`*suspended` wildcard \"stop-rule\" family (T15/T16/T24/T25 all share\n// `reason: 'stop-rule'`): DESIGN disambiguates those in PROSE by StopReason set, never by a guard id, so this\n// module resolves `{ stop: StopReason }` through `tables/index.ts`'s `STOP_ROW_MAPS` instead of widening\n// `TransitionDef` (frozen, U0.08) with a field DESIGN never gives it. A third form, `{ skip: ActivePipelineState }`,\n// answers the matrix's `skip` cell in the `*suspended` and FAILED columns, where the row is sourced from the phase\n// the run would re-enter and not from where the run is parked (see `ReasonOrOutcome` below).\nimport type {\n ActivePipelineState,\n GuardOutcome,\n PipelineProfile,\n PipelineState,\n StopReason,\n TransitionReason,\n} from '@cohorte/protocol';\nimport type { TransitionDef, TransitionTable } from '../contract/types.ts';\nimport { skipDefIdFor } from './command-matrix.ts';\nimport { matchesFrom, STOP_ROW_MAPS } from './tables/index.ts';\n\n/** `{ skip }` carries the phase the skip fires FROM — for a run parked in PAUSED / WAITING_APPROVAL / AUTH_REQUIRED /\n * QUOTA_EXCEEDED / FAILED that is its `resumeTo`, which is exactly DESIGN 2.5.1's \"T33 if policy (on `resumeTo`)\".\n * It is a form of its own because `resolveTransition` matches rows by `from` and every skip row carries a CONCRETE\n * active `from`: without it the whole suspended/FAILED `skip` column of the matrix would be unresolvable by the\n * kernel, pushing every consumer to look the row up itself and to evaluate `policy.skip-allows` / `skip.justified`\n * outside the guard check — the bypass I10 exists to prevent. */\nexport type ReasonOrOutcome = TransitionReason | { readonly stop: StopReason } | { readonly skip: ActivePipelineState };\n\n/** DEVIATION (docs/v3/requests/U0.09.md): `resolveTransition`'s `guardOutcomes` parameter needs the shape a\n * `GuardContext`-evaluated `Guard` produces — that is exactly `@cohorte/protocol`'s `GuardOutcome` (frozen,\n * `{ id, ok, detail? }`). Nothing named `GuardOutcomeLike` exists in `contract/types.ts` (U0.08, frozen); this\n * module uses `GuardOutcome` directly instead of widening the frozen contract with a synonym it never needed. */\nexport type GuardOutcomeLike = GuardOutcome;\n\nexport type ResolveTransitionResult =\n | { ok: true; def: TransitionDef; to: string }\n | { ok: false; reason: 'no-matching-row' }\n /** the bare reason `'stop-rule'` named only WILDCARD-sourced rows (T24 / T25-stop / T26-class rows), which DESIGN\n * 2.5.1 separates by STOP REASON SET and not by a guard: pass `{ stop: StopReason }` instead (see below) */\n | { ok: false; reason: 'stop-reason-required' }\n | { ok: false; reason: 'guard-failed'; def: TransitionDef; failedGuard: string; detail?: string };\n\nfunction evaluate(def: TransitionDef, outcomes: ReadonlyMap<string, GuardOutcomeLike>): ResolveTransitionResult {\n for (const guardId of def.preconditions) {\n const outcome = outcomes.get(guardId);\n if (!outcome?.ok) {\n const failure: ResolveTransitionResult = { ok: false, reason: 'guard-failed', def, failedGuard: guardId };\n if (outcome?.detail !== undefined) failure.detail = outcome.detail;\n return failure;\n }\n }\n return { ok: true, def, to: def.to };\n}\n\n/** Finds the ONE row `(from, reasonOrOutcome)` names and checks its preconditions against `guardOutcomes`.\n * Several rows may share `(from, reason)` (DESIGN's prose \"or\" of guards, `tables/shared.ts`'s header comment):\n * they are tried in table order and the first whose preconditions ALL hold wins; if none do, the FIRST candidate's\n * first failing guard is reported (DESIGN 2.5.1: \"ALL must hold; evaluated in order; first failure is reported\"). */\nexport function resolveTransition(\n table: TransitionTable,\n from: PipelineState,\n reasonOrOutcome: ReasonOrOutcome,\n guardOutcomes: readonly GuardOutcomeLike[],\n): ResolveTransitionResult {\n const outcomes = new Map(guardOutcomes.map((outcome) => [outcome.id, outcome] as const));\n\n if (typeof reasonOrOutcome === 'object') {\n if ('skip' in reasonOrOutcome) {\n // Deliberately NOT checked against `from`: the run is parked in FAILED or a suspended state while the row is\n // sourced from the phase it would re-enter (`resumeTo`). A phase this profile does not let `skip` fire from\n // simply has no such row.\n const def = table.rows.find((row) => row.id === skipDefIdFor(reasonOrOutcome.skip));\n if (!def) return { ok: false, reason: 'no-matching-row' };\n return evaluate(def, outcomes);\n }\n const byReason: Readonly<Record<string, string>> | undefined = STOP_ROW_MAPS[table.profile as PipelineProfile];\n const rowId = byReason?.[reasonOrOutcome.stop];\n const def = rowId ? table.rows.find((row) => row.id === rowId) : undefined;\n if (!def || !matchesFrom(def.from, from, table.phases)) return { ok: false, reason: 'no-matching-row' };\n return evaluate(def, outcomes);\n }\n\n const matching = table.rows.filter(\n (row) => matchesFrom(row.from, from, table.phases) && row.reason === reasonOrOutcome,\n );\n if (matching.length === 0) return { ok: false, reason: 'no-matching-row' };\n\n // `'stop-rule'` is the one reason several rows share WITHOUT a guard telling them apart: T15 (SHIP, stale digest)\n // and T16 (TEST, environmental error) carry a concrete `from` and a discriminating precondition, but T24\n // (-> WAITING_APPROVAL) and T25-stop (-> BLOCKED) are both `*active` with `preconditions: []` and are separated by\n // the STOP REASON SET alone (DESIGN 2.5.1: T24 \"stop in (iteration-limit, budget-exhausted, timeout,\n // identical-failure, no-progress)\", T25 \"stop in (policy-violation, unexpected-repo-change, runtime-incompatible)\").\n // First-match-wins over them would make T24 swallow every wildcard stop and leave the SECURITY row T25-stop\n // unreachable, so a wildcard stop row is reachable ONLY through the `{ stop }` form, which routes by STOP_ROW_MAPS.\n const candidates = reasonOrOutcome === 'stop-rule' ? matching.filter((row) => !row.from.startsWith('*')) : matching;\n if (candidates.length === 0) return { ok: false, reason: 'stop-reason-required' };\n\n let firstFailure: ResolveTransitionResult | undefined;\n for (const def of candidates) {\n const result = evaluate(def, outcomes);\n if (result.ok) return result;\n firstFailure ??= result;\n }\n return firstFailure as ResolveTransitionResult;\n}\n","// DESIGN 4.3 #19 (`command.external.after-accepted`) — a host that dies between the accept transaction of a\n// `pause`/`cancel` and the transaction that commits PAUSED/CANCELLED leaves its durable flag set and the causing\n// command `claimed` but unfinished. \"Resume does: finish the cancellation idempotently, then `command.completed`.\"\n//\n// `StateStore` exposes no \"claimed commands\" reader (`pendingCommands` returns `status: 'pending'` only, and\n// `RunTreeRows` carries no commands), so the engine finds that command the way the journal recorded it: the run's own\n// `command.accepted` events, filtered to the external command types, checked against the command row's current\n// status. Bounded by the run's journal length, and only ever read when a durable flag is actually set.\n\nimport type { CommandId, RunId } from '@cohorte/base';\nimport type { CommandRecord, StateStore } from '@cohorte/persistence/contract';\nimport type { StopReason } from '@cohorte/protocol';\n\n/** The command types this engine applies in TWO transactions (DESIGN 4.2 E1: \"commands with external effects — cancel,\n * shutdown — use two tx\"), each guarded by its own durable flag on the run row. `shutdown` is not one of them here:\n * it is not part of DESIGN 2.5.1's command x state matrix and this skeleton rejects it (docs/v3/requests/U1.09.md R8). */\nexport const EXTERNAL_COMMAND_TYPES = ['pause', 'cancel'] as const;\nexport type ExternalCommandType = (typeof EXTERNAL_COMMAND_TYPES)[number];\n\nconst EXTERNAL_SET: ReadonlySet<string> = new Set(EXTERNAL_COMMAND_TYPES);\n\n/** The durable `RunRecord` flag an accepted external command sets before its effects run (DESIGN 4.6). */\nexport const FLAG_OF_EXTERNAL_COMMAND = {\n pause: 'pauseRequested',\n cancel: 'cancelRequested',\n} as const satisfies Readonly<Record<ExternalCommandType, 'pauseRequested' | 'cancelRequested'>>;\n\n/** The stop `checkGlobalStops` raises from each flag (DESIGN 2.5.3: \"cancel requested -> cancelled | pause requested\n * -> paused\"), i.e. which external command a human-actor stop row was caused by. */\nexport const STOP_OF_EXTERNAL_COMMAND = {\n pause: 'paused',\n cancel: 'cancelled',\n} as const satisfies Readonly<Record<ExternalCommandType, StopReason>>;\n\nexport function isExternalCommandType(type: string): type is ExternalCommandType {\n return EXTERNAL_SET.has(type);\n}\n\nconst EVENT_PAGE = 200;\n\n/** Every `pause`/`cancel` of this run whose command row is still `claimed` — i.e. accepted, its durable flag written,\n * and never finished. Oldest first. */\nexport async function findClaimedExternalCommands(store: StateStore, runId: RunId): Promise<CommandRecord[]> {\n const candidates: CommandId[] = [];\n let afterSequence = 0;\n for (;;) {\n const page = await store.readEvents(runId, {\n afterSequence,\n limit: EVENT_PAGE,\n types: ['command.accepted'],\n });\n const last = page.at(-1);\n if (!last) break;\n for (const envelope of page) {\n const payload = envelope.payload as { commandId?: CommandId; type?: string };\n if (payload.commandId && payload.type && isExternalCommandType(payload.type)) candidates.push(payload.commandId);\n }\n afterSequence = last.sequence;\n if (page.length < EVENT_PAGE) break;\n }\n\n const claimed: CommandRecord[] = [];\n for (const commandId of candidates) {\n const row = await store.getCommand(commandId);\n if (row?.status === 'claimed') claimed.push(row);\n }\n return claimed;\n}\n\n/** The claimed external command that caused `stop`, if any — what lets a stop row whose `TransitionDef.actor` is\n * `human` (T20 `pause`, T27 `cancel`) fire with the actor and `commandId` of the command that really asked for it,\n * instead of being refused as \"the engine firing a human row on its own\". */\nexport async function findCommandCausingStop(\n store: StateStore,\n runId: RunId,\n stop: StopReason,\n): Promise<CommandRecord | undefined> {\n const claimed = await findClaimedExternalCommands(store, runId);\n return claimed.find((row) => {\n const type = row.envelope.type;\n return isExternalCommandType(type) && STOP_OF_EXTERNAL_COMMAND[type] === stop;\n });\n}\n","// Small shared helpers the engine's inbox and transition paths both need.\nimport { type ErrorInfo, errorOf, isErrorCode } from '@cohorte/base';\n\n/**\n * Builds a catalogue `ErrorInfo` for `code` when it IS a catalogue code, else falls back to `conflict/unexpected`\n * and keeps the caller's own code/message in `details.matrixCode` / the message text.\n *\n * DEVIATION (docs/v3/requests/U1.09.md): `packages/core/src/pipeline/command-matrix.ts` (frozen, U0.09) names a few\n * finer-grained rejection codes — `conflict/use-retry`, `conflict/use-resume`, `conflict/use-resume-ack`,\n * `conflict/run-blocked` — that `@cohorte/base`'s `ERROR_CATALOGUE` (frozen, U0.02) does not carry. `errorOf` throws\n * on an uncatalogued code, so a command rejected on one of those cells would otherwise crash the engine instead of\n * rejecting the command. This falls back rather than widening a contract this unit does not own.\n */\nexport function errorInfoForCode(code: string, message: string): ErrorInfo {\n if (isErrorCode(code)) return errorOf(code, message);\n return errorOf('conflict/unexpected', message, { details: { matrixCode: code } });\n}\n\n/** Thrown inside a `store.transact` body to force a rollback when `recordTransition` answers `'duplicate'`: the\n * whole transaction (including any event this body already appended) is undone, and the caller treats it as the\n * no-op DESIGN 4.3 #5 requires (\"recordTransition with the same key is a no-op\"). Never escapes past its own catch. */\nexport class TransitionAlreadyRecorded extends Error {\n constructor(idempotencyKey: string) {\n super(`transition ${idempotencyKey} was already recorded`);\n this.name = 'TransitionAlreadyRecorded';\n }\n}\n\n/** Thrown inside a `store.transact` body when `StoreTx.claimCommand` answers `false` — another host claimed this\n * command first. Rolls the whole transaction back (nothing of this command's outcome is written) and is reported to\n * the caller as `'claim-lost'`. Never escapes past its own catch. */\nexport class CommandClaimLost extends Error {\n constructor(commandId: string) {\n super(`command ${commandId} was claimed by another host`);\n this.name = 'CommandClaimLost';\n }\n}\n","// DESIGN 4.2 E3-E8 — the pieces the engine loop shares between a COMMAND-driven transition (inbox.ts) and a\n// SPONTANEOUS one driven by a phase outcome or a global stop (index.ts): guard evaluation, committing a resolved row\n// (recordTransition + its events, a no-op on a duplicate idempotency key), and closing/advancing the active phase.\n\nimport { CohorteError, type ErrorInfo, errorOf, type IsoInstant, type PhaseRunId, type RunId } from '@cohorte/base';\nimport type { DurableEnvelope, LeaseToken, RunRecord, StoreTx } from '@cohorte/persistence/contract';\nimport type {\n ActivePipelineState,\n Actor,\n GuardOutcome,\n PhaseRef,\n PipelineState,\n StopRecord,\n TransitionReason,\n} from '@cohorte/protocol';\nimport { ACTIVE_PIPELINE_STATES } from '@cohorte/protocol';\nimport type { GuardId, TransitionEffectId } from '../contract/ids.ts';\nimport type {\n CheckpointCause,\n EventDraftInput,\n GlobalFacts,\n GuardContext,\n HostContext,\n PhaseOutcome,\n PhaseRunContext,\n RunState,\n TransitionDef,\n TransitionTable,\n} from '../contract/types.ts';\nimport { crashpoint } from '../durability/crashpoints.ts';\nimport { transitionIdempotencyKey } from '../pipeline/idempotency-key.ts';\nimport type { PipelineStep } from '../pipeline/next-step.ts';\nimport { resolveTransition } from '../pipeline/resolve-transition.ts';\nimport { normalizeActor, systemActor } from './actor.ts';\nimport { writeCheckpoint } from './checkpoint.ts';\nimport { FLAG_OF_EXTERNAL_COMMAND, findCommandCausingStop, isExternalCommandType } from './commands.ts';\nimport type { RunEngineDeps } from './deps.ts';\nimport { CommandClaimLost, TransitionAlreadyRecorded } from './errors.ts';\n\n/** The four fields this file needs of a persisted phase row: it never imports `@cohorte/persistence/contract`'s\n * full `PhaseRecord` just for these. `index.ts` builds one from the real record when it finds an open phase. */\nexport interface OpenPhase {\n phaseRunId: PhaseRunId;\n state: PhaseRef['state'];\n iteration: number;\n startedAt?: IsoInstant;\n}\n\nconst ACTIVE_STATE_SET: ReadonlySet<string> = new Set(ACTIVE_PIPELINE_STATES);\n\nexport function phaseRef(phase: OpenPhase): PhaseRef {\n return { phaseRunId: phase.phaseRunId, state: phase.state, iteration: phase.iteration };\n}\n\n/** `phs_<STATE>_<iteration>` (DESIGN's own id shape, `@cohorte/base` `ID_SHAPES.PhaseRunId`) — not minted through\n * `IdSource`: the pattern is structural, not random. */\nexport function makePhaseRunId(state: PhaseRef['state'], iteration: number): PhaseRunId {\n return `phs_${state}_${iteration}` as PhaseRunId;\n}\n\n/**\n * Which visit of `state` the phase about to be opened is. A shipped table LOOPS — `feature@1`'s TEST -> FIX -> TEST,\n * up to `maxFixRounds` — so a phase state is entered several times in one run, and each entry is its own phase RUN:\n * its own `phs_<STATE>_<n>` row (a fixed `1` would overwrite the previous round's row) and its own transition\n * idempotency key, whose `fromPhaseRunId` + `discriminator` are what `pipeline/idempotency-key.ts` names as \"the\n * piece that keeps two firings of the SAME row (e.g. T09 on round 2 of a FIX loop) from colliding\" — a duplicate key\n * rolls the whole commit back, which would leave the phase open and the run re-executing it for ever.\n */\nexport function nextPhaseIteration(runState: RunState, state: PhaseRef['state']): number {\n return runState.phases.filter((phase) => phase.state === state).length + 1;\n}\n\nexport function evaluateGuards(\n ids: readonly GuardId[],\n ctx: GuardContext,\n registry: RunEngineDeps['guards'],\n): GuardOutcome[] {\n return ids.map((id) => {\n const guard = registry.get(id);\n return guard ? guard(ctx) : { id, ok: false, detail: `no guard registered for \"${id}\"` };\n });\n}\n\nexport function buildPhaseRunContext(\n runState: RunState,\n phase: OpenPhase,\n lease: LeaseToken,\n signal: AbortSignal,\n now: IsoInstant,\n): PhaseRunContext {\n return { run: runState, phase: phaseRef(phase), now, lease, signal };\n}\n\n/**\n * DEVIATION, loud (docs/v3/requests/U1.09.md): DESIGN hands the \"which reason follows this phase outcome\" mapping\n * only inside each table's own rows and the loop controller (`decideAfterTest`/`decideAfterReview`, DESIGN 2.5.3 —\n * a port this unit is not handed: it is not in `RunEngineDeps` and its factory is still a `U0.08` `NotImplemented`\n * stub). Rather than hard-code DESIGN's own table reasons (which a test's own toy table could then never reuse),\n * this classifies every `TransitionReason` the frozen vocabulary defines by which `PhaseOutcome.kind` it answers,\n * and the engine picks the ONE CONCRETE candidate (`row.from === state`, i.e. not one of the\n * `*active`/`*suspended`/`*any-non-terminal` stop-family wildcards `nextStep` also returns) whose reason matches —\n * data-driven, so it works for any well-formed table, real or a test's own toy one. Where a phase genuinely offers\n * more than one candidate of the same kind, the FIRST match in table order wins, exactly like `resolveTransition`'s\n * own tie-break.\n */\nconst OUTCOME_KIND_BY_REASON: Readonly<Partial<Record<TransitionReason, 'passed' | 'failed' | 'needs-human'>>> = {\n ready: 'passed',\n built: 'passed',\n 'tests-pass': 'passed',\n 'tests-fail': 'failed',\n 'review-approved': 'passed',\n 'review-findings': 'failed',\n 'review-delivered': 'passed',\n fixed: 'passed',\n shipped: 'passed',\n 'needs-human': 'needs-human',\n 'unexpected-error': 'failed',\n};\n\n/** `T30`/`T31`/`T32`'s `to: '*resumeTo'` names the active state the run was in when it last suspended, recorded as\n * `RunRecord.resumeTo` by `settleStop` at that time (and by `evolve()`'s `run.state.changed` handling, from the\n * same payload field). A concrete `to` passes through unchanged. */\nexport function resolveLandingState(to: string, runState: RunState): PipelineState {\n if (to !== '*resumeTo') return to as PipelineState;\n const resumeTo = runState.run.resumeTo;\n if (!resumeTo) {\n throw new CohorteError(\n errorOf(\n 'corruption/projection-mismatch',\n `run ${runState.run.runId}: a '*resumeTo' row fired with no resumeTo recorded`,\n ),\n );\n }\n return resumeTo;\n}\n\n/**\n * Which ACTIVE state a transition leaving `from` for `to` must record as `RunRecord.resumeTo` — the state a later\n * `*resumeTo` row (T30/T31/T32) returns the run to. It is exactly \"an active state was left for one that is not\":\n * suspending or halting a run records where it was, moving between two active states does not. BOTH the run row and\n * the `run.state.changed` payload carry it (`evolve()` reconstructs `RunState.run.resumeTo` from that field), so\n * every path that suspends a run — the stop ladder AND a `pause` command — must use this one rule.\n */\nexport function resumeToFor(from: PipelineState, to: PipelineState): ActivePipelineState | undefined {\n if (!ACTIVE_STATE_SET.has(from) || ACTIVE_STATE_SET.has(to)) return undefined;\n return from as ActivePipelineState;\n}\n\nexport function candidateForOutcome(\n candidates: readonly TransitionDef[],\n from: PipelineState,\n kind: 'passed' | 'failed' | 'needs-human',\n): TransitionDef | undefined {\n return candidates.find(\n (row) =>\n (row.from === from || (row.from === '*active' && ACTIVE_STATE_SET.has(from))) &&\n OUTCOME_KIND_BY_REASON[row.reason] === kind,\n );\n}\n\nexport interface CommitTransitionArgs {\n deps: RunEngineDeps;\n runId: RunId;\n lease: LeaseToken;\n table: TransitionTable;\n from: PipelineState;\n def: TransitionDef;\n actor: Actor;\n guardOutcomes: readonly GuardOutcome[];\n transitionId: string;\n idempotencyKey: string;\n /** Every durable event this commit writes; the FIRST must be the `run.state.changed` draft (its minted `eventId`\n * is what `recordTransition` stores). */\n drafts: EventDraftInput[];\n /** Index of the `run.state.changed` draft inside `drafts` (default 0) — a command-driven commit puts\n * `command.accepted` in front of it, so that `claim; accepted; events; finish` is ONE transaction (DESIGN 4.2 E1). */\n stateChangedIndex?: number;\n patch: Partial<RunRecord> & { state: PipelineState };\n /** Runs FIRST inside the transaction, before any event is appended (e.g. `tx.claimCommand`). Throwing rolls the\n * whole transaction back; a `CommandClaimLost` is reported as `'claim-lost'`. */\n preamble?: (tx: StoreTx) => void;\n /** Extra synchronous tx-scoped writes (e.g. `tx.putPhase(...)` to close/open a phase, `tx.finishCommand(...)` for\n * a command-driven transition) — handed the full list of envelopes `drafts` just became, in the same order. */\n within?: (tx: StoreTx, appended: DurableEnvelope[]) => void;\n}\n\n/**\n * Commits ONE resolved transition: appends its events, records it (a `'duplicate'` idempotency key rolls the WHOLE\n * transaction back — including the events just appended — and is reported as a no-op, never a partial write), then\n * patches the run row and runs any extra writes the caller needs in the same transaction.\n */\nexport async function commitTransition(args: CommitTransitionArgs): Promise<'recorded' | 'duplicate' | 'claim-lost'> {\n const {\n deps,\n runId,\n lease,\n table,\n from,\n def,\n actor,\n guardOutcomes,\n transitionId,\n idempotencyKey,\n drafts,\n stateChangedIndex,\n patch,\n preamble,\n within,\n } = args;\n try {\n await deps.store.transact({ runId }, lease, (tx) => {\n preamble?.(tx);\n const appended = deps.events.append(tx, drafts);\n const stateChanged = appended[stateChangedIndex ?? 0];\n if (!stateChanged) throw new TypeError('commitTransition: no run.state.changed event was appended');\n const recorded = tx.recordTransition({\n transitionId,\n runId,\n defId: def.id,\n tableVersion: table.version,\n from,\n to: patch.state,\n reason: def.reason,\n actor,\n guards: [...guardOutcomes],\n effects: [...def.effects],\n idempotencyKey,\n eventId: stateChanged.eventId,\n });\n if (recorded === 'duplicate') throw new TransitionAlreadyRecorded(idempotencyKey);\n tx.patchRun(runId, patch);\n within?.(tx, appended);\n });\n } catch (thrown) {\n if (thrown instanceof TransitionAlreadyRecorded) return 'duplicate';\n if (thrown instanceof CommandClaimLost) return 'claim-lost';\n throw thrown;\n }\n return 'recorded';\n}\n\n/** Runs a resolved row's declarative effects, in order, through the injected `TransitionEffectRunner` (E6). DESIGN\n * 4.2 puts them AFTER the E5 commit, so a commit that turns out to be a duplicate never re-runs them; the ONE\n * exception is DESIGN 4.6's pause/cancel shape, where the durable flag is already committed and the effects\n * (`park-agents`, `cancel-agents`, `release-locks`…) must run before the final state commit. */\nexport async function runEffects(\n deps: RunEngineDeps,\n runId: RunId,\n effects: readonly TransitionEffectId[],\n lease: LeaseToken,\n signal: AbortSignal,\n): Promise<void> {\n for (const effectId of effects) await deps.transitionEffects.run(effectId, { runId, lease }, signal);\n}\n\nfunction assertNotHumanActor(def: TransitionDef, cause: string): void {\n if (def.actor === 'human') {\n throw new CohorteError(\n errorOf(\n 'configuration/policy-invalid',\n `row ${def.id} is actor:\"human\"; ${cause} never fires it without a causing commandId`,\n ),\n );\n }\n}\n\nexport interface SettleStopArgs {\n deps: RunEngineDeps;\n runId: RunId;\n host: HostContext;\n lease: LeaseToken;\n table: TransitionTable;\n runState: RunState;\n step: PipelineStep;\n facts: GlobalFacts;\n stop: StopRecord;\n /** Default `'phase-boundary'`; `index.ts`'s fatal handler passes `'fatal'` when it reuses this same machinery for\n * `T26` (DESIGN 2.8: \"FAILED + checkpoint.created{cause:'fatal'}\"). */\n checkpointCause?: CheckpointCause;\n error?: ErrorInfo;\n}\n\n/** E2 (and a phase outcome of `kind: 'suspended'`): resolves the row `STOP_ROW_MAPS` names for this stop, commits\n * it, then writes a checkpoint (chain MAC anchor + snapshot, spec 11.3). */\nexport async function settleStop(args: SettleStopArgs): Promise<void> {\n const { deps, runId, host, lease, table, runState, step, facts, stop, checkpointCause, error } = args;\n const now = deps.clock.now();\n const from = runState.run.state;\n const guardOutcomes = evaluateGuards(step.guards, { run: runState, facts, now }, deps.guards);\n const resolved = resolveTransition(table, from, { stop: stop.reason }, guardOutcomes);\n if (!resolved.ok) {\n const detail = resolved.reason === 'guard-failed' ? ` (${resolved.def.id}: ${resolved.failedGuard} failed)` : '';\n throw new CohorteError(\n errorOf(\n 'configuration/policy-invalid',\n `no ${table.profile}@${table.version} row answers stop \"${stop.reason}\" from ${from}${detail}`,\n ),\n );\n }\n // A stop row whose `TransitionDef.actor` is `human` (T20 `pause`, T27 `cancel`) is only ever legal with a causing\n // command behind it. The durable `pauseRequested`/`cancelRequested` flag IS that trace: it is written in the accept\n // transaction of a verified command and by nothing else, so when the still-`claimed` command is on disk the\n // invariant (\"the engine never emits a human transition without a causing commandId\") holds — the stop fires with\n // THAT command's normalised actor and id, and finishes it (DESIGN 4.3 #19). With no such command the row really\n // would be the engine firing a human row on its own, and that is refused.\n const causing =\n resolved.def.actor === 'human' ? await findCommandCausingStop(deps.store, runId, stop.reason) : undefined;\n if (!causing) assertNotHumanActor(resolved.def, 'a global stop');\n const causingType = causing && isExternalCommandType(causing.envelope.type) ? causing.envelope.type : undefined;\n\n // DESIGN 4.6 for a pause/cancel (the flag is already durable: effects, THEN the final commit); DESIGN 4.2 E5/E6\n // for every other stop (commit, then the effects — never re-run for a commit that turned out to be a duplicate).\n if (causing) await runEffects(deps, runId, resolved.def.effects, lease, host.signal);\n\n crashpoint('transition.before-commit');\n const actor = causing ? normalizeActor(causing.envelope.actor) : systemActor(host.hostId);\n const transitionId = deps.ids.next<'TransitionId'>('trn');\n const idempotencyKey = transitionIdempotencyKey({\n runId,\n profile: table.profile,\n tableVersion: table.version,\n defId: resolved.def.id,\n discriminator: `stop:${stop.reason}:${runState.run.lastSequence}`,\n });\n const to = resolved.to as PipelineState;\n // `resumeTo` records WHICH active state to return to, so a later `*resumeTo` row (T30/T31/T32, command-driven\n // only) can resolve it. `evolve()` reads this same payload field to reconstruct `RunState.run.resumeTo`.\n const resumesTo = resumeToFor(from, to);\n const patch: CommitTransitionArgs['patch'] = { state: to, stop, ...(error ? { lastError: error } : {}) };\n if (resumesTo) patch.resumeTo = resumesTo;\n if (causingType) patch[FLAG_OF_EXTERNAL_COMMAND[causingType]] = false;\n\n const drafts: EventDraftInput[] = [];\n // DESIGN 4.6's tx2 lists `run.paused` / `run.cancelled` explicitly, and the inbox's own command path (inbox.ts,\n // `applyExternal`) emits it. The SAME state change must leave the SAME journal whichever path settled it, so a\n // stop settled from the durable flag of a `pause`/`cancel` writes the lifecycle event too.\n if (causing && causingType) {\n const commandPayload = causing.envelope.payload as { reason?: string; keepWorktrees?: boolean };\n drafts.push(\n causingType === 'pause'\n ? {\n type: 'run.paused',\n payload: { commandId: causing.commandId, parkedAgents: [], inFlightEffects: [] },\n summary: 'run paused',\n }\n : {\n type: 'run.cancelled',\n payload: {\n commandId: causing.commandId,\n reason: commandPayload.reason ?? 'cancel command',\n cancelledAgents: [],\n worktreesKept: commandPayload.keepWorktrees ?? false,\n },\n summary: 'run cancelled',\n },\n );\n }\n if (error) {\n drafts.push({\n type: 'error',\n payload: { error: error as unknown as EventDraftInput['payload'], fatal: false },\n summary: `run suspended: ${error.code}`,\n severity: 'error',\n });\n }\n const stateChangedIndex = drafts.length;\n drafts.push({\n type: 'run.state.changed',\n payload: {\n transitionId,\n defId: resolved.def.id,\n tableVersion: table.version,\n from,\n to,\n reason: resolved.def.reason,\n actor,\n guards: guardOutcomes,\n idempotencyKey,\n stop,\n ...(resumesTo ? { resumeTo: resumesTo } : {}),\n },\n summary: `${resolved.def.id}: ${from} -> ${to} (${stop.reason})`,\n });\n // DESIGN 4.3 #19: \"finish the cancellation idempotently, THEN command.completed\".\n const completedIndex = drafts.length;\n if (causing) {\n drafts.push({\n type: 'command.completed',\n payload: { commandId: causing.commandId, type: causing.envelope.type, result: { stop: stop.reason } },\n summary: `command ${causing.envelope.type} completed`,\n });\n }\n\n const result = await commitTransition({\n deps,\n runId,\n lease,\n table,\n from,\n def: resolved.def,\n actor,\n guardOutcomes,\n transitionId,\n idempotencyKey,\n drafts,\n stateChangedIndex,\n patch,\n within: (tx, appended) => {\n const completed = causing ? appended[completedIndex] : undefined;\n if (causing && completed) tx.finishCommand(causing.commandId, 'completed', completed.eventId);\n },\n });\n crashpoint('transition.after-commit');\n\n if (!causing && result === 'recorded') await runEffects(deps, runId, resolved.def.effects, lease, host.signal);\n\n await writeCheckpoint({ deps, runId, host, lease, cause: checkpointCause ?? 'phase-boundary' });\n}\n\nexport interface ClosePhaseArgs {\n deps: RunEngineDeps;\n runId: RunId;\n host: HostContext;\n lease: LeaseToken;\n table: TransitionTable;\n runState: RunState;\n step: PipelineStep;\n facts: GlobalFacts;\n openPhase: OpenPhase;\n outcome: PhaseOutcome;\n}\n\n/** E6-E8: closes the phase that just produced `outcome` (a `phase.completed` event) and, on a \"forward\" outcome,\n * resolves+commits the next transition (E3-E5's `reasonOrOutcome` half, once the phase result makes it concrete) —\n * opening the NEXT phase (`phase.started`) in the SAME commit when the landing state is active — then checkpoints. A\n * `suspended` outcome is handed straight to `settleStop`, exactly like a global stop found at E2. */\nexport async function closePhaseAndAdvance(args: ClosePhaseArgs): Promise<StopRecord | null> {\n const { deps, runId, host, lease, table, runState, step, facts, openPhase, outcome } = args;\n\n if (outcome.kind === 'suspended') {\n await settleStop({\n deps,\n runId,\n host,\n lease,\n table,\n runState,\n step,\n facts,\n stop: outcome.stop,\n ...(outcome.error ? { error: outcome.error } : {}),\n });\n return outcome.stop;\n }\n\n const now = deps.clock.now();\n const from = runState.run.state;\n const phaseChecks = 'checks' in outcome ? (outcome.checks ?? []) : [];\n const outcomeFacts = {\n ...facts,\n 'checks.all-passed':\n outcome.kind === 'passed' &&\n phaseChecks.every((check) => check.status === 'passed' || check.status === 'skipped'),\n 'checks.digest-equals-integration': outcome.kind === 'passed' || phaseChecks.length > 0,\n 'checks.failed-non-environmental':\n outcome.kind === 'failed' && phaseChecks.some((check) => check.status === 'failed'),\n 'loop.may-continue':\n (facts as unknown as Record<string, unknown>)['loop.may-continue'] === true ||\n (outcome.kind === 'failed' && phaseChecks.some((check) => check.status === 'failed')),\n };\n const guardOutcomes = evaluateGuards(step.guards, { run: runState, facts: outcomeFacts, now }, deps.guards);\n const candidate = candidateForOutcome(step.candidates, from, outcome.kind);\n if (!candidate) {\n const failureDetail =\n outcome.kind === 'failed' ? ` (${outcome.failure.error.code}: ${outcome.failure.error.message})` : '';\n throw new CohorteError(\n errorOf(\n 'configuration/policy-invalid',\n `${table.profile}@${table.version} has no row that answers a \"${outcome.kind}\" outcome from ${from}${failureDetail}`,\n ),\n );\n }\n const resolved = resolveTransition(table, from, candidate.reason, guardOutcomes);\n if (!resolved.ok) {\n throw new CohorteError(\n errorOf(\n 'configuration/policy-invalid',\n `transition ${candidate.id} failed its own guards right after the \"${outcome.kind}\" outcome that selected it`,\n ),\n );\n }\n assertNotHumanActor(resolved.def, 'a phase outcome');\n\n crashpoint('transition.before-commit');\n const actor = systemActor(host.hostId);\n const transitionId = deps.ids.next<'TransitionId'>('trn');\n const idempotencyKey = transitionIdempotencyKey({\n runId,\n profile: table.profile,\n tableVersion: table.version,\n defId: resolved.def.id,\n fromPhaseRunId: openPhase.phaseRunId,\n discriminator: `${openPhase.iteration}`,\n });\n const to = resolved.to as PipelineState;\n const artifacts = outcome.kind === 'passed' ? outcome.artifacts : [];\n const drafts: EventDraftInput[] = [\n {\n type: 'phase.completed',\n payload: {\n phase: phaseRef(openPhase),\n outcome: outcome.kind,\n outputs: [...artifacts],\n checks: phaseChecks,\n durationMs: 0,\n },\n phase: phaseRef(openPhase),\n summary: `${openPhase.state} ${outcome.kind}`,\n },\n ];\n if (outcome.kind === 'failed') {\n drafts.push({\n type: 'error',\n payload: { error: outcome.failure.error as unknown as EventDraftInput['payload'], fatal: false },\n phase: phaseRef(openPhase),\n summary: `${openPhase.state} failed: ${outcome.failure.error.code}`,\n severity: 'error',\n });\n }\n const stateChangedIndex = drafts.length;\n drafts.push({\n type: 'run.state.changed',\n payload: {\n transitionId,\n defId: resolved.def.id,\n tableVersion: table.version,\n from,\n to,\n reason: resolved.def.reason,\n actor,\n guards: guardOutcomes,\n idempotencyKey,\n },\n phase: phaseRef(openPhase),\n summary: `${resolved.def.id}: ${from} -> ${to} (${resolved.def.reason})`,\n });\n\n const nowIso = deps.clock.now();\n let nextPhase: OpenPhase | undefined;\n if (ACTIVE_STATE_SET.has(to)) {\n const iteration = nextPhaseIteration(runState, to as PhaseRef['state']);\n nextPhase = {\n phaseRunId: makePhaseRunId(to as PhaseRef['state'], iteration),\n state: to as PhaseRef['state'],\n iteration,\n startedAt: nowIso,\n };\n drafts.push({\n type: 'phase.started',\n payload: { phase: phaseRef(nextPhase), contractId: to, contractVersion: 1, planned: [], budget: {} },\n phase: phaseRef(nextPhase),\n summary: `${to} started`,\n });\n }\n\n const result = await commitTransition({\n deps,\n runId,\n lease,\n table,\n from,\n def: resolved.def,\n actor,\n guardOutcomes,\n transitionId,\n idempotencyKey,\n drafts,\n patch: { state: to, ...(outcome.kind === 'failed' ? { lastError: outcome.failure.error } : {}) },\n stateChangedIndex,\n within: (tx) => {\n const closedStatus =\n outcome.kind === 'passed' ? 'completed' : outcome.kind === 'failed' ? 'failed' : 'waiting-approval';\n tx.putPhase({\n runId,\n phaseRunId: openPhase.phaseRunId,\n state: openPhase.state,\n iteration: openPhase.iteration,\n status: closedStatus,\n outcome: outcome.kind,\n checks: phaseChecks,\n ...(openPhase.startedAt ? { startedAt: openPhase.startedAt } : {}),\n endedAt: nowIso,\n });\n if (nextPhase) {\n tx.putPhase({\n runId,\n phaseRunId: nextPhase.phaseRunId,\n state: nextPhase.state,\n iteration: nextPhase.iteration,\n status: 'running',\n checks: [],\n startedAt: nowIso,\n });\n }\n },\n });\n crashpoint('transition.after-commit');\n\n // DESIGN 4.2: E5 is the transition transaction, E6 the row's effects. Running them here (and not before the\n // commit) is what keeps `release-locks` / `write-ship-report` / `mint-review-ref` from executing against a\n // transition that the idempotency key then rolled back as a duplicate.\n if (result === 'recorded') {\n await runEffects(deps, runId, resolved.def.effects, lease, host.signal);\n await writeCheckpoint({ deps, runId, host, lease, cause: 'phase-boundary' });\n }\n return null;\n}\n","// DESIGN 4.2 E1 — drain the command inbox: verify the MAC BEFORE anything else touches the command, normalise the\n// actor, then apply the command x state matrix (`pipeline/command-matrix.ts`, frozen, `U0.09`) or, for `start`\n// (outside that matrix's scope — DESIGN 2.5.1's table does not carry run creation), resolve `IDLE -> ... , 'start'`\n// directly.\n//\n// Shape (DESIGN 4.2 E1 verbatim): \"per command ONE tx { claimCommand ; command.accepted ; events of the command ;\n// finishCommand ; command.completed|rejected } (commands with external effects — cancel, shutdown — use two tx)\".\n// So every command is PLANNED first — reads only, no write — and then applied in a single transaction; only `pause`\n// and `cancel`, whose effects (`park-agents`, `cancel-agents`, `release-locks`) must run between the durable flag and\n// the final state (DESIGN 4.6), take the two-transaction path, with `command.external.after-accepted` (DESIGN 4.3\n// #19) as the crash point in between and `drainInbox`'s own recovery closing that window.\nimport type { ApprovalId, CommandId, EventId, IsoInstant, RunId, Sha256 } from '@cohorte/base';\nimport type {\n ApprovalRecord,\n ApprovalStatus,\n CommandRecord,\n LeaseToken,\n RunRecord,\n} from '@cohorte/persistence/contract';\nimport {\n ACTIVE_PIPELINE_STATES,\n type ActivePipelineState,\n type Actor,\n type CommandEnvelope,\n type CommandType,\n canonicalCommandBody,\n type GuardOutcome,\n type PipelineState,\n type RunPlan,\n type StopRecord,\n} from '@cohorte/protocol';\nimport type { EventDraftInput, HostContext, RunState, TransitionDef, TransitionTable } from '../contract/types.ts';\nimport { crashpoint } from '../durability/crashpoints.ts';\nimport { commandMatrixCell, MATRIX_COMMANDS, type MatrixCommand, skipDefIdFor } from '../pipeline/command-matrix.ts';\nimport { transitionIdempotencyKey } from '../pipeline/idempotency-key.ts';\nimport { nextStep } from '../pipeline/next-step.ts';\nimport { resolveTransition } from '../pipeline/resolve-transition.ts';\nimport { normalizeActor } from './actor.ts';\nimport { writeCheckpoint } from './checkpoint.ts';\nimport {\n type ExternalCommandType,\n findClaimedExternalCommands,\n isExternalCommandType,\n STOP_OF_EXTERNAL_COMMAND,\n} from './commands.ts';\nimport type { RunEngineDeps } from './deps.ts';\nimport { CommandClaimLost, errorInfoForCode } from './errors.ts';\nimport {\n commitTransition,\n evaluateGuards,\n makePhaseRunId,\n nextPhaseIteration,\n type OpenPhase,\n phaseRef,\n resolveLandingState,\n resumeToFor,\n runEffects,\n} from './transitions.ts';\n\nconst ACTIVE_STATE_SET: ReadonlySet<string> = new Set(ACTIVE_PIPELINE_STATES);\n\nexport interface InboxEnv {\n deps: RunEngineDeps;\n runId: RunId;\n host: HostContext;\n lease: LeaseToken;\n table: TransitionTable;\n}\n\nfunction isMatrixCommand(type: CommandType): type is MatrixCommand {\n return (MATRIX_COMMANDS as readonly string[]).includes(type);\n}\n\nfunction acceptedDraft(envelope: CommandEnvelope, actor: Actor): EventDraftInput {\n return {\n type: 'command.accepted',\n payload: {\n commandId: envelope.commandId,\n type: envelope.type,\n actor,\n authVerified: true,\n scheme: envelope.auth?.scheme ?? 'hmac-sha256',\n },\n summary: `command ${envelope.type} accepted`,\n };\n}\n\nfunction rejectedDraft(\n envelope: Pick<CommandEnvelope, 'commandId' | 'type'>,\n info: ReturnType<typeof errorInfoForCode>,\n): EventDraftInput {\n // `ErrorInfo` is a (self-referential) `interface`, so it does not itself satisfy `T extends JsonValue`'s implicit\n // index signature (the same limitation `packages/core/src/events/index.ts` documents) — the value is genuine JSON,\n // only the STATIC type needs the cast; nothing here mints a `Sealed<T>` (check-layers rule f is unaffected).\n const payload = {\n commandId: envelope.commandId,\n type: envelope.type,\n error: info,\n } as unknown as EventDraftInput['payload'];\n return {\n type: 'command.rejected',\n payload,\n summary: `command ${envelope.type} rejected: ${info.code}`,\n severity: 'warning',\n };\n}\n\nfunction completedDraft(envelope: Pick<CommandEnvelope, 'commandId' | 'type'>, result: unknown): EventDraftInput {\n return {\n type: 'command.completed',\n payload: { commandId: envelope.commandId, type: envelope.type, result: result as EventDraftInput['payload'] },\n summary: `command ${envelope.type} completed`,\n };\n}\n\nfunction verifyAuth(deps: RunEngineDeps, envelope: CommandEnvelope): boolean {\n const auth = envelope.auth;\n // An unknown `auth.scheme` is rejected like a bad value (deliverable text): only the ONE scheme this engine's\n // `CommandAuthenticator` speaks is ever accepted.\n if (!auth || auth.scheme !== deps.authenticator.scheme) return false;\n const body = canonicalCommandBody(envelope);\n return deps.authenticator.verify(body, auth.value, deps.projectKey);\n}\n\n// ── planning: reads only; nothing below writes until `applyPlan` ────────────────────────────────────────────────\n\n/** What the matrix (or `start`) decided this command does, computed before ANY transaction opens so the whole\n * outcome can then be written at once. */\ntype CommandPlan =\n | { kind: 'simple'; outcome: 'completed' | 'rejected'; draft: EventDraftInput }\n | {\n kind: 'transition';\n def: TransitionDef;\n to: string;\n runState: RunState;\n guardOutcomes: GuardOutcome[];\n extraPatch?: Partial<RunRecord>;\n }\n | {\n kind: 'external';\n type: ExternalCommandType;\n def: TransitionDef;\n to: string;\n runState: RunState;\n guardOutcomes: GuardOutcome[];\n }\n | {\n kind: 'approval';\n approval: ApprovalRecord;\n decision: Exclude<ApprovalStatus, 'pending'>;\n note?: string;\n mayTransition?: string;\n pendingBefore: ApprovalRecord[];\n };\n\nfunction rejectPlan(envelope: CommandEnvelope, code: string, message: string): CommandPlan {\n return { kind: 'simple', outcome: 'rejected', draft: rejectedDraft(envelope, errorInfoForCode(code, message)) };\n}\n\nfunction completePlan(envelope: CommandEnvelope, result: unknown): CommandPlan {\n return { kind: 'simple', outcome: 'completed', draft: completedDraft(envelope, result) };\n}\n\n/** Reads the run tree and evaluates the guards of `ids` against freshly collected facts. */\nasync function guardsFor(\n deps: RunEngineDeps,\n runId: RunId,\n ids: readonly Parameters<RunEngineDeps['factCollector']['collect']>[0][number][],\n): Promise<{ runState: RunState; guardOutcomes: GuardOutcome[] }> {\n const runState = await deps.store.readRunTree(runId);\n const now = deps.clock.now();\n const facts = await deps.factCollector.collect(ids);\n return { runState, guardOutcomes: evaluateGuards(ids, { run: runState, facts, now }, deps.guards) };\n}\n\nasync function planStart(env: InboxEnv, envelope: CommandEnvelope, run: RunRecord): Promise<CommandPlan> {\n const { deps, runId, table } = env;\n if (run.state !== 'IDLE') {\n return rejectPlan(envelope, 'conflict/run-active', `start: run ${runId} is not IDLE (currently ${run.state})`);\n }\n const probe = await deps.store.readRunTree(runId);\n const step = nextStep(probe, table);\n const { runState, guardOutcomes } = await guardsFor(deps, runId, step.guards);\n const resolved = resolveTransition(table, 'IDLE', 'start', guardOutcomes);\n if (!resolved.ok) {\n const detail =\n resolved.reason === 'guard-failed'\n ? `${resolved.def.id}: guard \"${resolved.failedGuard}\" failed`\n : 'no row of this table starts from IDLE';\n return rejectPlan(envelope, 'configuration/policy-invalid', `start: ${detail}`);\n }\n return {\n kind: 'transition',\n def: resolved.def,\n to: resolved.to,\n runState,\n guardOutcomes,\n extraPatch: deps.startColumns ? await deps.startColumns(run) : hostComputedColumnsForStart(),\n };\n}\n\n/**\n * `StateStore.transact` refuses a run leaving `IDLE` (or `CANCELLED`/`FAILED`) without its six host-computed\n * columns set (persistence's own invariant, `HOST_COMPUTED_RUN_KEYS` / `STATES_WITHOUT_HOST_COLUMNS`) — DESIGN's\n * real `T04` (`create-integration-branch` on `IDLE -> PREFLIGHT`) sets them from a captured `RunSnapshotManifest`\n * (`RunSnapshotter`, a different port this unit is not handed). A toy table's own `start` row leaves IDLE the same\n * way, so it needs SOMETHING in each column; these are honest, clearly-fake placeholders, never read as real\n * snapshot/runtime data by anything this unit owns (deviation, docs/v3/requests/U1.09.md).\n */\nexport function hostComputedColumnsForStart(): Partial<RunRecord> {\n return {\n snapshotDigest: '0'.repeat(64) as Sha256,\n runtimePin: {},\n plan: {\n profile: 'feature',\n runtime: { id: 'fake', version: '0.0.0' },\n trust: { policySha256: '0'.repeat(64) as never, loosenedKeys: [], grantedBy: 'none-needed' },\n models: [],\n apiBillingEnabled: false,\n meteredProviders: [],\n sandbox: { level: 'L0-process', backend: 'none', filesystem: 'advisory', network: 'unenforced' },\n sandboxRequire: 'best-effort',\n brainIsolation: 'process',\n budgets: { run: {}, perPhase: {}, perAgent: {}, perProvider: {}, perTool: {} },\n network: { provisioning: false },\n promptOverrides: [],\n unattended: true,\n } as RunPlan,\n baseSha: '0'.repeat(40),\n integrationBranch: 'cohorte/toy-integration',\n zones: [],\n };\n}\n\n/** A resolved row, or the rejection that explains why it could not be resolved. */\nfunction transitionPlan(\n envelope: CommandEnvelope,\n type: string,\n def: TransitionDef,\n from: PipelineState,\n table: TransitionTable,\n runState: RunState,\n guardOutcomes: GuardOutcome[],\n): CommandPlan {\n const resolved = resolveTransition(table, from, def.reason, guardOutcomes);\n if (!resolved.ok || resolved.def.id !== def.id) {\n const detail = resolved.ok\n ? `resolved to ${resolved.def.id} instead of ${def.id}`\n : resolved.reason === 'guard-failed'\n ? `guard \"${resolved.failedGuard}\" failed`\n : 'no matching row';\n return rejectPlan(envelope, 'configuration/policy-invalid', `${type}: ${detail}`);\n }\n if (isExternalCommandType(envelope.type)) {\n return { kind: 'external', type: envelope.type, def: resolved.def, to: resolved.to, runState, guardOutcomes };\n }\n return { kind: 'transition', def: resolved.def, to: resolved.to, runState, guardOutcomes };\n}\n\nasync function planMatrixCommand(env: InboxEnv, envelope: CommandEnvelope, run: RunRecord): Promise<CommandPlan> {\n const { deps, runId, table } = env;\n const type = envelope.type as MatrixCommand;\n const cell = commandMatrixCell(type, run.state);\n\n switch (cell.kind) {\n case 'reject':\n return rejectPlan(envelope, cell.code, cell.message);\n case 'noop':\n return completePlan(envelope, { noop: true });\n case 'spawns-host':\n // DESIGN: \"wakes a detached host to drain it\" — this engine IS already the host draining the inbox, so\n // waking one is moot; complete as a no-op (deviation, docs/v3/requests/U1.09.md).\n return completePlan(envelope, { noop: true });\n case 'transition-per-phase': {\n // `skip`'s row is minted per phase (`skipDefIdFor`, U0.09): resolve it at the effective phase — `run.state`\n // if active, else `run.resumeTo` (DESIGN 2.5.1's \"T33 if policy (on `resumeTo`)\") — never a literal id.\n const effectivePhase = ACTIVE_STATE_SET.has(run.state) ? (run.state as ActivePipelineState) : run.resumeTo;\n if (!effectivePhase) {\n return rejectPlan(envelope, 'configuration/policy-invalid', `${type}: no phase to skip from ${run.state}`);\n }\n const def = table.rows.find((row) => row.id === skipDefIdFor(effectivePhase));\n if (!def) {\n return rejectPlan(\n envelope,\n 'configuration/policy-invalid',\n `${type}: ${effectivePhase} is not skippable in ${table.profile}@${table.version}`,\n );\n }\n // NOT `nextStep(runState, table)`: that narrows by `run.state` (e.g. `PAUSED`), and a skip fired \"on\n // resumeTo\" resolves a row whose `from` is the DIFFERENT effective phase — `def.preconditions` directly is\n // the right (and only) guard set to gather facts for and evaluate here.\n const { runState, guardOutcomes } = await guardsFor(deps, runId, def.preconditions);\n return transitionPlan(envelope, type, def, effectivePhase, table, runState, guardOutcomes);\n }\n case 'transition': {\n const def = table.rows.find((row) => row.id === cell.defId);\n if (!def) {\n return rejectPlan(\n envelope,\n 'configuration/policy-invalid',\n `${type}: table ${table.profile}@${table.version} has no row \"${cell.defId}\"`,\n );\n }\n const probe = await deps.store.readRunTree(runId);\n const step = nextStep(probe, table);\n const { runState, guardOutcomes } = await guardsFor(deps, runId, step.guards);\n return transitionPlan(envelope, type, def, run.state, table, runState, guardOutcomes);\n }\n case 'applies':\n return planApprovalDecision(env, envelope, cell.mayTransition);\n }\n}\n\n/** `approve` / `deny`: resolves the stored approval directly through `StoreTx` (DESIGN 2.5's `ApprovalService` is a\n * separate port this unit is not handed; the record-level resolution `StoreTx.resolveApproval` already gives is\n * enough for a skeleton — deviation, docs/v3/requests/U1.09.md). */\nasync function planApprovalDecision(\n env: InboxEnv,\n envelope: CommandEnvelope,\n mayTransition: string | undefined,\n): Promise<CommandPlan> {\n const { deps, runId } = env;\n const payload = envelope.payload as { approvalId: ApprovalId; scope?: 'once' | 'run'; note?: string };\n const decision: Exclude<ApprovalStatus, 'pending'> =\n envelope.type === 'approve' ? (payload.scope === 'run' ? 'allow-for-run' : 'allow-once') : 'deny';\n\n const before = await deps.store.readRunTree(runId);\n const target = before.approvals.find((a) => a.approvalId === payload.approvalId);\n if (target?.status !== 'pending') {\n return rejectPlan(\n envelope,\n 'conflict/unexpected',\n `${envelope.type}: approval ${payload.approvalId} is not pending`,\n );\n }\n const plan: CommandPlan = {\n kind: 'approval',\n approval: target,\n decision,\n pendingBefore: before.approvals.filter((a) => a.status === 'pending'),\n };\n if (payload.note !== undefined) plan.note = payload.note;\n if (mayTransition !== undefined) plan.mayTransition = mayTransition;\n return plan;\n}\n\n// ── applying: one transaction, except for `pause`/`cancel` ─────────────────────────────────────────────────────\n\nfunction claimPreamble(commandId: CommandId, hostId: string) {\n return (tx: { claimCommand(id: CommandId, hostId: string): boolean }): void => {\n if (!tx.claimCommand(commandId, hostId)) throw new CommandClaimLost(commandId);\n };\n}\n\n/** The ONE transaction of DESIGN 4.2 E1 for a command that neither transitions nor has an external effect:\n * `{ claimCommand ; command.accepted ; command.completed|rejected ; finishCommand }`. */\nasync function applySimple(\n env: InboxEnv,\n envelope: CommandEnvelope,\n actor: Actor,\n outcome: 'completed' | 'rejected',\n draft: EventDraftInput,\n): Promise<void> {\n const { deps, runId, host, lease } = env;\n await deps.store.transact({ runId }, lease, (tx) => {\n if (!tx.claimCommand(envelope.commandId, host.hostId)) return;\n const appended = deps.events.append(tx, [acceptedDraft(envelope, actor), draft]);\n const result = appended[1];\n tx.finishCommand(envelope.commandId, outcome, result ? result.eventId : ('' as EventId));\n });\n}\n\ninterface TransitionCommit {\n transitionId: string;\n idempotencyKey: string;\n toState: PipelineState;\n patch: Partial<RunRecord> & { state: PipelineState };\n stateChangedDraft: EventDraftInput;\n nextPhase?: OpenPhase;\n phaseStartedDraft?: EventDraftInput;\n startedAt: IsoInstant;\n}\n\n/** The shared arithmetic of a COMMAND-driven transition: its idempotency key, landing state, `resumeTo`, the\n * `run.state.changed` draft, and the `phase.started` that opens the next phase when the landing state is active. */\nfunction prepareTransition(\n env: InboxEnv,\n envelope: CommandEnvelope,\n actor: Actor,\n def: TransitionDef,\n to: string,\n runState: RunState,\n guardOutcomes: GuardOutcome[],\n extraPatch: Partial<RunRecord>,\n /** Set by a command that SUSPENDS or halts the run (`pause`, `cancel`): the run row and the `run.state.changed`\n * payload both carry it, exactly as the stop ladder's own `settleStop` writes it, so `RunState.run.stop` says the\n * same thing whether it is read from the row or replayed through `evolve()`. */\n stop?: StopRecord,\n): TransitionCommit {\n const { deps, runId, table } = env;\n const transitionId = deps.ids.next<'TransitionId'>('trn');\n const idempotencyKey = transitionIdempotencyKey({\n runId,\n profile: table.profile,\n tableVersion: table.version,\n defId: def.id,\n discriminator: envelope.commandId,\n });\n const from = runState.run.state;\n const toState = resolveLandingState(to, runState);\n const patch: Partial<RunRecord> & { state: PipelineState } = { ...extraPatch, state: toState };\n if (stop) patch.stop = stop;\n // DESIGN 2.5.1: a `*resumeTo` row can only resolve what the transition that suspended the run recorded. A `pause`\n // command is the ONLY way a run is ever PAUSED, so this path — not just the stop ladder — must record it.\n const resumesTo = resumeToFor(from, toState);\n if (resumesTo) patch.resumeTo = resumesTo;\n\n const startedAt = deps.clock.now();\n const commit: TransitionCommit = {\n transitionId,\n idempotencyKey,\n toState,\n patch,\n startedAt,\n stateChangedDraft: {\n type: 'run.state.changed',\n payload: {\n transitionId,\n defId: def.id,\n tableVersion: table.version,\n from,\n to: toState,\n reason: def.reason,\n actor,\n guards: guardOutcomes,\n idempotencyKey,\n ...(resumesTo ? { resumeTo: resumesTo } : {}),\n ...(stop ? { stop } : {}),\n },\n summary: `${def.id}: ${from} -> ${toState} (${def.reason})`,\n },\n };\n\n // A command-driven transition (e.g. `start`, T04-like) can land on an active state exactly like a phase-outcome\n // one does (transitions.ts's `closePhaseAndAdvance`): open its phase here too, so the engine's next pass finds it.\n if (ACTIVE_STATE_SET.has(toState)) {\n const activeState = toState as ActivePipelineState;\n const iteration = nextPhaseIteration(runState, activeState);\n const phase: OpenPhase = {\n phaseRunId: makePhaseRunId(activeState, iteration),\n state: activeState,\n iteration,\n startedAt,\n };\n commit.nextPhase = phase;\n commit.phaseStartedDraft = {\n type: 'phase.started',\n payload: { phase: phaseRef(phase), contractId: toState, contractVersion: 1, planned: [], budget: {} },\n phase: phaseRef(phase),\n summary: `${toState} started`,\n };\n }\n return commit;\n}\n\n/** ONE transaction: `{ claimCommand ; command.accepted ; run.state.changed (+ phase.started) ; recordTransition ;\n * patchRun ; command.completed ; finishCommand }`. The row's declarative effects run AFTER it (DESIGN 4.2 E5 then\n * E6) and never at all for a commit the idempotency key rejected as a duplicate. */\nasync function applyTransition(\n env: InboxEnv,\n envelope: CommandEnvelope,\n actor: Actor,\n plan: Extract<CommandPlan, { kind: 'transition' }>,\n): Promise<void> {\n const { deps, runId, host, lease, table } = env;\n const commit = prepareTransition(\n env,\n envelope,\n actor,\n plan.def,\n plan.to,\n plan.runState,\n plan.guardOutcomes,\n plan.extraPatch ?? {},\n );\n\n const drafts: EventDraftInput[] = [acceptedDraft(envelope, actor), commit.stateChangedDraft];\n if (commit.phaseStartedDraft) drafts.push(commit.phaseStartedDraft);\n const completedIndex = drafts.length;\n drafts.push(completedDraft(envelope, { runId }));\n\n const result = await commitTransition({\n deps,\n runId,\n lease,\n table,\n from: plan.runState.run.state,\n def: plan.def,\n actor,\n guardOutcomes: plan.guardOutcomes,\n transitionId: commit.transitionId,\n idempotencyKey: commit.idempotencyKey,\n drafts,\n stateChangedIndex: 1,\n patch: commit.patch,\n preamble: claimPreamble(envelope.commandId, host.hostId),\n within: (tx, appended) => {\n const phase = commit.nextPhase;\n if (phase) {\n tx.putPhase({\n runId,\n phaseRunId: phase.phaseRunId,\n state: phase.state,\n iteration: phase.iteration,\n status: 'running',\n checks: [],\n startedAt: commit.startedAt,\n });\n }\n const completed = appended[completedIndex];\n if (completed) tx.finishCommand(envelope.commandId, 'completed', completed.eventId);\n },\n });\n\n if (result === 'claim-lost') return;\n if (result === 'duplicate') {\n // The row was already recorded under this command's own key: the command's effect is on disk, so the command is\n // complete. Finishing it here is what stops the drain from re-reading it for ever.\n await applySimple(env, envelope, actor, 'completed', completedDraft(envelope, { noop: true }));\n return;\n }\n await runEffects(deps, runId, plan.def.effects, lease, host.signal);\n}\n\n/**\n * DESIGN 4.6 / 4.2 E1 \"commands with external effects use two tx\": tx1 `{ claimCommand ; command.accepted ; the\n * durable flag }`, then the row's effects, then tx2 `{ run.paused|run.cancelled ; run.state.changed ; the flag\n * cleared ; command.completed ; finishCommand }` and the checkpoint. `alreadyAccepted` re-enters at the effects for\n * a command whose host died at `command.external.after-accepted` (DESIGN 4.3 #19).\n */\nasync function applyExternal(\n env: InboxEnv,\n envelope: CommandEnvelope,\n actor: Actor,\n plan: Extract<CommandPlan, { kind: 'external' }>,\n alreadyAccepted: boolean,\n): Promise<void> {\n const { deps, runId, host, lease, table } = env;\n\n if (!alreadyAccepted) {\n const accepted = await deps.store.transact({ runId }, lease, (tx) => {\n if (!tx.claimCommand(envelope.commandId, host.hostId)) return null;\n tx.patchRun(runId, plan.type === 'pause' ? { pauseRequested: true } : { cancelRequested: true });\n return deps.events.append(tx, [acceptedDraft(envelope, actor)])[0] ?? null;\n });\n if (!accepted) return; // raced with another host's claim on this command\n // DESIGN 4.3 #19: the durable flag is committed BEFORE this point; a crash here leaves it set, and the next\n // drain (`drainInbox`'s own recovery) finishes the command from exactly here.\n crashpoint('command.external.after-accepted');\n }\n\n await runEffects(deps, runId, plan.def.effects, lease, host.signal);\n\n crashpoint('transition.before-commit');\n const cancelPayload = envelope.payload as { reason?: string; keepWorktrees?: boolean };\n // DESIGN 2.5.3's stop table read backwards: PAUSED is what `paused` leaves behind, CANCELLED what `cancelled`\n // does. Recording it is what lets `run()` answer with the real `StopRecord` when it finds the run suspended, and\n // what keeps the row's `stop` and the journal's agreeing.\n const stop: StopRecord = {\n reason: STOP_OF_EXTERNAL_COMMAND[plan.type],\n detail: cancelPayload.reason ?? `${plan.type} command`,\n resumable: plan.type === 'pause',\n };\n const commit = prepareTransition(\n env,\n envelope,\n actor,\n plan.def,\n plan.to,\n plan.runState,\n plan.guardOutcomes,\n {},\n stop,\n );\n commit.patch[plan.type === 'pause' ? 'pauseRequested' : 'cancelRequested'] = false;\n const lifecycleDraft: EventDraftInput =\n plan.type === 'pause'\n ? {\n type: 'run.paused',\n payload: { commandId: envelope.commandId, parkedAgents: [], inFlightEffects: [] },\n summary: 'run paused',\n }\n : {\n type: 'run.cancelled',\n payload: {\n commandId: envelope.commandId,\n reason: cancelPayload.reason ?? 'cancel command',\n cancelledAgents: [],\n worktreesKept: cancelPayload.keepWorktrees ?? false,\n },\n summary: 'run cancelled',\n };\n\n const drafts: EventDraftInput[] = [lifecycleDraft, commit.stateChangedDraft, completedDraft(envelope, { runId })];\n\n const result = await commitTransition({\n deps,\n runId,\n lease,\n table,\n from: plan.runState.run.state,\n def: plan.def,\n actor,\n guardOutcomes: plan.guardOutcomes,\n transitionId: commit.transitionId,\n idempotencyKey: commit.idempotencyKey,\n drafts,\n stateChangedIndex: 1,\n patch: commit.patch,\n within: (tx, appended) => {\n const completed = appended[2];\n if (completed) tx.finishCommand(envelope.commandId, 'completed', completed.eventId);\n },\n });\n crashpoint('transition.after-commit');\n if (result !== 'recorded') return;\n\n // `CheckpointCause` (frozen, U0.08) has no `'cancel'`: a cancel takes the same `'phase-boundary'` cause the stop\n // ladder already uses for a cancelled run (deviation, docs/v3/requests/U1.09.md).\n await writeCheckpoint({ deps, runId, host, lease, cause: plan.type === 'pause' ? 'pause' : 'phase-boundary' });\n}\n\n/** ONE transaction: `{ claimCommand ; command.accepted ; approval.resolved ; resolveApproval ; command.completed ;\n * finishCommand }`. When this resolved the LAST pending blocking approval and the matrix cell names a\n * `mayTransition` row (T30), that row fires after it, in the same spirit as DESIGN's \"applies; may trigger T30\". */\nasync function applyApprovalDecision(\n env: InboxEnv,\n envelope: CommandEnvelope,\n actor: Actor,\n plan: Extract<CommandPlan, { kind: 'approval' }>,\n): Promise<void> {\n const { deps, runId, host, lease, table } = env;\n const { approval, decision } = plan;\n\n await deps.store.transact({ runId }, lease, (tx) => {\n if (!tx.claimCommand(envelope.commandId, host.hostId)) return;\n const appended = deps.events.append(tx, [\n acceptedDraft(envelope, actor),\n {\n type: 'approval.resolved',\n payload: {\n approvalId: approval.approvalId,\n decision,\n actor,\n commandId: envelope.commandId,\n ...(plan.note !== undefined ? { note: plan.note } : {}),\n },\n summary: `approval ${approval.approvalId} ${decision}`,\n },\n completedDraft(envelope, { approvalId: approval.approvalId, decision }),\n ]);\n const resolvedEnvelope = appended[1];\n const completedEnvelope = appended[2];\n // `ApprovalDecisionRecord.resolvedSeq` is \"the sequence of `approval.resolved`\" (persistence/records.ts): the\n // real one, read back from the envelope the same transaction just minted.\n tx.resolveApproval(approval.approvalId, {\n actor,\n commandId: envelope.commandId,\n answer: decision,\n ...(plan.note !== undefined ? { note: plan.note } : {}),\n decidedAt: deps.clock.now(),\n resolvedSeq: resolvedEnvelope ? resolvedEnvelope.sequence : 0,\n });\n if (completedEnvelope) tx.finishCommand(envelope.commandId, 'completed', completedEnvelope.eventId);\n });\n\n if (!plan.mayTransition) return;\n const stillBlocking = plan.pendingBefore.filter((a) => a.approvalId !== approval.approvalId).length;\n if (stillBlocking > 0) return;\n const def = table.rows.find((row) => row.id === plan.mayTransition);\n if (!def) return;\n\n const probe = await deps.store.readRunTree(runId);\n const step = nextStep(probe, table);\n const { runState, guardOutcomes } = await guardsFor(deps, runId, step.guards);\n const resolved = resolveTransition(table, runState.run.state, def.reason, guardOutcomes);\n if (!resolved.ok || resolved.def.id !== def.id) return; // not ready yet; a later loop iteration's E2/E3-E5 catches it\n\n const transitionId = deps.ids.next<'TransitionId'>('trn');\n const idempotencyKey = transitionIdempotencyKey({\n runId,\n profile: table.profile,\n tableVersion: table.version,\n defId: resolved.def.id,\n discriminator: `approval:${approval.approvalId}`,\n });\n const from = runState.run.state;\n const to = resolveLandingState(resolved.to, runState);\n const resumesTo = resumeToFor(from, to);\n const patch: Partial<RunRecord> & { state: PipelineState } = { state: to };\n if (resumesTo) patch.resumeTo = resumesTo;\n\n const result = await commitTransition({\n deps,\n runId,\n lease,\n table,\n from,\n def: resolved.def,\n actor,\n guardOutcomes,\n transitionId,\n idempotencyKey,\n drafts: [\n {\n type: 'run.state.changed',\n payload: {\n transitionId,\n defId: resolved.def.id,\n tableVersion: table.version,\n from,\n to,\n reason: resolved.def.reason,\n actor,\n guards: guardOutcomes,\n idempotencyKey,\n ...(resumesTo ? { resumeTo: resumesTo } : {}),\n },\n summary: `${resolved.def.id}: ${from} -> ${to} (${resolved.def.reason})`,\n },\n ],\n patch,\n });\n if (result === 'recorded') await runEffects(deps, runId, resolved.def.effects, lease, host.signal);\n}\n\nasync function applyPlan(\n env: InboxEnv,\n envelope: CommandEnvelope,\n actor: Actor,\n plan: CommandPlan,\n alreadyAccepted = false,\n): Promise<void> {\n switch (plan.kind) {\n case 'simple':\n await applySimple(env, envelope, actor, plan.outcome, plan.draft);\n return;\n case 'transition':\n await applyTransition(env, envelope, actor, plan);\n return;\n case 'external':\n await applyExternal(env, envelope, actor, plan, alreadyAccepted);\n return;\n case 'approval':\n await applyApprovalDecision(env, envelope, actor, plan);\n return;\n }\n}\n\nasync function planCommand(env: InboxEnv, envelope: CommandEnvelope, run: RunRecord): Promise<CommandPlan> {\n if (envelope.type === 'start') return planStart(env, envelope, run);\n if (isMatrixCommand(envelope.type)) return planMatrixCommand(env, envelope, run);\n return rejectPlan(\n envelope,\n 'configuration/phase-not-available',\n `${envelope.type}: not handled by this engine skeleton (deviation, docs/v3/requests/U1.09.md)`,\n );\n}\n\nasync function processCommand(env: InboxEnv, record: CommandRecord): Promise<void> {\n const { deps, runId, host, lease } = env;\n const envelope = record.envelope;\n\n if (!verifyAuth(deps, envelope)) {\n await deps.store.transact({ runId }, lease, (tx) => {\n if (!tx.claimCommand(record.commandId, host.hostId)) return;\n const info = errorInfoForCode(\n 'security/command-auth-invalid',\n `command ${record.commandId} (${envelope.type}): missing or invalid authenticator`,\n );\n const appended = deps.events.append(tx, [rejectedDraft(envelope, info)]);\n const out = appended[0];\n tx.finishCommand(record.commandId, 'rejected', out ? out.eventId : ('' as EventId));\n });\n return;\n }\n\n const actor = normalizeActor(envelope.actor);\n const run = await deps.store.getRun(runId);\n if (!run) return;\n\n // DESIGN 2.3.4: \"optimistic guard: reject if the run moved past this sequence\". `run.lastSequence` here is the\n // sequence BEFORE this command's own `command.accepted` — nothing has been written yet — so a client that sends\n // the sequence it last observed is accepted, and only a run that really moved is refused.\n if (envelope.expectedSequence !== undefined && run.lastSequence > envelope.expectedSequence) {\n await applyPlan(\n env,\n envelope,\n actor,\n rejectPlan(\n envelope,\n 'conflict/unexpected',\n `${envelope.type}: expectedSequence ${envelope.expectedSequence} is behind the run's current sequence ${run.lastSequence}`,\n ),\n );\n return;\n }\n\n await applyPlan(env, envelope, actor, await planCommand(env, envelope, run));\n}\n\n/**\n * DESIGN 4.3 #19: a host that died at `command.external.after-accepted` left the durable flag set and its command\n * `claimed` but unfinished. Before any new command is drained, finish those — idempotently, from exactly where the\n * dead host stopped — so the flag never outlives the command that set it (and `checkGlobalStops` never raises a stop\n * for a command nobody will ever complete).\n */\nasync function recoverAcceptedExternalCommands(env: InboxEnv): Promise<void> {\n const { deps, runId } = env;\n const run = await deps.store.getRun(runId);\n if (!run || (!run.pauseRequested && !run.cancelRequested)) return;\n\n for (const record of await findClaimedExternalCommands(deps.store, runId)) {\n const current = await deps.store.getRun(runId);\n if (!current) return;\n const plan = await planCommand(env, record.envelope, current);\n if (plan.kind !== 'external') {\n // The run moved on while the flag stayed behind (e.g. it is already CANCELLED, so the matrix answers `{noop}`\n // rather than T27): close the command against the CURRENT state, and clear ITS flag in the same transaction —\n // a flag that outlived its command is exactly what would later raise a stop nobody can settle.\n const isPause = record.envelope.type === 'pause';\n await deps.store.transact({ runId }, env.lease, (tx) => {\n tx.patchRun(runId, isPause ? { pauseRequested: false } : { cancelRequested: false });\n const appended = deps.events.append(tx, [completedDraft(record.envelope, { noop: true })]);\n const out = appended[0];\n tx.finishCommand(record.commandId, 'completed', out ? out.eventId : ('' as EventId));\n });\n continue;\n }\n await applyExternal(env, record.envelope, normalizeActor(record.envelope.actor), plan, true);\n }\n}\n\n/** E1: drains every currently-pending command for the run, in order, one at a time — after finishing whatever an\n * earlier host accepted but never completed. */\nexport async function drainInbox(env: InboxEnv): Promise<void> {\n await recoverAcceptedExternalCommands(env);\n const pending = await env.deps.store.pendingCommands(env.runId);\n for (const record of pending) await processCommand(env, record);\n}\n","// @cohorte/core/engine — DESIGN 4.2's loop E0-E8: `createEngine` on the Wave-0 kernel (`nextStep`,\n// `resolveTransition`, `evolve`, U0.09), inbox drain with MAC verification (E1, inbox.ts), global stops and\n// checkpoints (E2, E8, checkpoint.ts / transitions.ts), phase advancement (E3-E7, transitions.ts), the fatal\n// handler (DESIGN 2.8: \"unknown throwable => FAILED + checkpoint.created{cause:'fatal'}\").\n//\n// PLAN U1.09. Wave-0 seam (PLAN U0.08) replaced: this file is now the implementation. `createEngine`'s SIGNATURE\n// diverges from the frozen stub's `EngineDeps` — see `./deps.ts`'s header comment (docs/v3/requests/U1.09.md) for\n// why, and why that is the smallest reading available inside this unit's own `ownedPaths`.\nimport { CohorteError, errorOf, type RunId, toErrorInfo } from '@cohorte/base';\nimport type { LeaseToken } from '@cohorte/persistence/contract';\nimport type { PipelineProfile, StopReason, StopRecord } from '@cohorte/protocol';\nimport { HALTED_STATES, SUSPENDED_STATES, TERMINAL_STATES } from '@cohorte/protocol';\nimport type { RunEngine } from '../contract/internal.ts';\nimport type { EventDraftInput, HostContext, RunState, TransitionTable } from '../contract/types.ts';\nimport { crashpoint, SimulatedCrash } from '../durability/crashpoints.ts';\nimport { transitionIdempotencyKey } from '../pipeline/idempotency-key.ts';\nimport { nextStep } from '../pipeline/next-step.ts';\nimport { systemActor } from './actor.ts';\nimport { writeCheckpoint } from './checkpoint.ts';\nimport { DEFAULT_LEASE_TTL_MS, type RunEngineDeps } from './deps.ts';\nimport { drainInbox } from './inbox.ts';\nimport { buildPhaseRunContext, closePhaseAndAdvance, type OpenPhase, settleStop } from './transitions.ts';\n\nexport type { RunEngineDeps } from './deps.ts';\nexport { DEFAULT_LEASE_TTL_MS } from './deps.ts';\n\n/** DESIGN 4.7: \"the host polls every 250 ms\". Overridable per engine instance (tests use a short one). */\nexport const DEFAULT_POLL_INTERVAL_MS = 250;\n\n/**\n * The states in which this host's loop schedules NOTHING new (DESIGN 4.6 for a pause: \"the engine schedules nothing\n * new\"; DESIGN 2.5.3's stop table for the others): the two terminal states, the two halted ones, and the four\n * suspended ones. Every one of them is left by a COMMAND — `resume`, `retry`, `approve` — which a controller sends\n * to a freshly spawned host (DESIGN 4.7), never by this loop continuing to run phases. IDLE is deliberately NOT one\n * of them: a run waiting for its own `start` command has work coming and keeps polling.\n */\nconst NO_SCHEDULING_STATES: ReadonlySet<string> = new Set([...TERMINAL_STATES, ...HALTED_STATES, ...SUSPENDED_STATES]);\n\n/** The `StopReason` that each end state stands for when the run row carries no `stop` of its own — every state of\n * `NO_SCHEDULING_STATES`, mapped through DESIGN 2.5.3's \"StopReason / State after\" table, read backwards. */\nconst STOP_OF_END_STATE = {\n COMPLETED: { reason: 'review-clean', resumable: false },\n CANCELLED: { reason: 'cancelled', resumable: false },\n FAILED: { reason: 'internal-error', resumable: true },\n BLOCKED: { reason: 'policy-violation', resumable: true },\n PAUSED: { reason: 'paused', resumable: true },\n WAITING_APPROVAL: { reason: 'approval-required', resumable: true },\n AUTH_REQUIRED: { reason: 'auth-required', resumable: true },\n QUOTA_EXCEEDED: { reason: 'quota-exceeded', resumable: true },\n} as const satisfies Readonly<Record<string, { reason: StopReason; resumable: boolean }>>;\n\nasync function resolveTableFor(deps: RunEngineDeps, runId: RunId): Promise<TransitionTable | undefined> {\n const run = await deps.store.getRun(runId);\n if (!run) return undefined;\n const looked = deps.resolveTable(run.profile, run.tableVersion);\n return looked.ok ? looked.table : undefined;\n}\n\n/** The most recently opened phase that has not yet closed (`status: 'running'`), if any. A well-formed run has at\n * most one open phase at a time. */\nfunction findOpenPhase(runState: RunState): OpenPhase | undefined {\n const phase = [...runState.phases].reverse().find((p) => p.status === 'running');\n if (!phase) return undefined;\n return {\n phaseRunId: phase.phaseRunId,\n state: phase.state,\n iteration: phase.iteration,\n ...(phase.startedAt !== undefined ? { startedAt: phase.startedAt } : {}),\n };\n}\n\n/** What `run()` returns once the run reached a state this host schedules nothing from: the `StopRecord` the settling\n * transition recorded on the row, or — for a run that reached the state before this engine existed, or through a\n * path that recorded none — the stop that state stands for. */\nfunction finalStopRecord(runState: RunState): StopRecord {\n if (runState.run.stop) return runState.run.stop;\n const state: string = runState.run.state;\n const known = state in STOP_OF_END_STATE ? STOP_OF_END_STATE[state as keyof typeof STOP_OF_END_STATE] : undefined;\n if (!known) return { reason: 'internal-error', detail: `run is ${state}`, resumable: true };\n return { reason: known.reason, detail: `run is ${state}`, resumable: known.resumable };\n}\n\n/**\n * DESIGN 2.8: \"Unknown throwables → <nearest class>/unexpected → FAILED + checkpoint.created\" — the run host's own\n * `unhandledRejection`/`uncaughtException` handling is apps/cli's (out of this unit's `ownedPaths`); this is the\n * engine's OWN top-level catch around the loop body. Reuses `T26` (`*active -> FAILED`, reason `unexpected-error`,\n * `stop: 'internal-error'`) through the SAME machinery as a global stop when the run is in an active state that row\n * can fire from; falls back to a direct `patchRun` + checkpoint when it cannot (e.g. the throw happened while the\n * run was still IDLE, before any table row could apply). A `conflict/lease-lost` throw is NEVER handled here: this\n * host no longer holds the lease, so any further write would itself be refused (DESIGN 4.2 E0) — it is rethrown\n * unchanged, \"exits at once\".\n */\nasync function commitFatal(\n deps: RunEngineDeps,\n runId: RunId,\n host: HostContext,\n lease: LeaseToken,\n thrown: unknown,\n): Promise<StopRecord> {\n const info = toErrorInfo(thrown, { code: 'validation/unexpected', class: 'validation' });\n if (info.code === 'conflict/lease-lost') throw thrown;\n\n const stop: StopRecord = { reason: 'internal-error', detail: info.message, resumable: true };\n\n try {\n const table = await resolveTableFor(deps, runId);\n if (table) {\n const runState = await deps.store.readRunTree(runId);\n if (runState.run.state !== 'FAILED') {\n const step = nextStep(runState, table);\n const facts = await deps.factCollector.collect(step.guards);\n await settleStop({ deps, runId, host, lease, table, runState, step, facts, stop, checkpointCause: 'fatal' });\n // `settleStop`'s own patch carries `{state, stop, resumeTo?}` (it is reused by every stop, not just a\n // fatal one); this loop's own contribution is `lastError`, recorded right after.\n await deps.store.transact({ runId }, lease, (tx) => tx.patchRun(runId, { lastError: info }));\n return stop;\n }\n }\n } catch {\n // The table has no row for `internal-error` from the current state (or resolving it failed for its own\n // reasons): fall through to the unconditional patch below rather than compound the original failure.\n }\n\n // No table row could fire (e.g. the run is still IDLE, which no `*active -> FAILED` row covers). The run row still\n // has to say FAILED — but a row that says FAILED over a journal whose last state event says otherwise is a\n // projection every pure reader (DESIGN 4.7, `evolve()`) would get wrong, so the two events DESIGN requires of any\n // failure are written in the SAME transaction: `error` (DESIGN 2.8: \"every error has … an `error` event\") and\n // `run.state.changed` (DESIGN 4.2: the event of every state change). Nothing is recorded in `transitions`: no row\n // fired, and `recordTransition` is the register of rows that did.\n await deps.store.transact({ runId }, lease, (tx) => {\n const before = tx.run();\n const from = before.state;\n const drafts: EventDraftInput[] = [\n {\n type: 'error',\n // `ErrorInfo` is a (self-referential) `interface`, so it does not satisfy `JsonValue`'s implicit index\n // signature even though the VALUE is genuine JSON — the same static-only limitation `inbox.ts`'s\n // `rejectedDraft` and `packages/core/src/events/index.ts` document. Nothing here mints a `Sealed<T>`.\n payload: { error: info as unknown as EventDraftInput['payload'], fatal: true },\n summary: `fatal: ${info.code}`,\n severity: 'error',\n },\n ];\n if (from !== 'FAILED') {\n const transitionId = deps.ids.next<'TransitionId'>('trn');\n drafts.push({\n type: 'run.state.changed',\n payload: {\n transitionId,\n // No row: the id names the handler that moved the run, and the idempotency key says the same, so neither\n // can ever be mistaken for one of the table's own rows (none of which is named `fatal`).\n defId: 'fatal',\n tableVersion: before.tableVersion,\n from,\n to: 'FAILED',\n reason: 'unexpected-error',\n actor: systemActor(host.hostId),\n guards: [],\n idempotencyKey: transitionIdempotencyKey({\n runId,\n // `RunRecord.profile` is deliberately open (`string`, ADR-0018: the known profiles are validated in\n // TypeScript, not by the store) while the key template types it closed; a stored run's profile is one\n // of them by construction, and this key is informational here — no row is recorded under it.\n profile: before.profile as PipelineProfile,\n tableVersion: before.tableVersion,\n defId: 'fatal',\n discriminator: `fatal:${before.lastSequence}`,\n }),\n stop,\n },\n summary: `fatal: ${from} -> FAILED (${info.code})`,\n severity: 'error',\n });\n }\n deps.events.append(tx, drafts);\n tx.patchRun(runId, { state: 'FAILED', lastError: info, stop });\n });\n await writeCheckpoint({ deps, runId, host, lease, cause: 'fatal' });\n return stop;\n}\n\n/** Hands the run lock back. A release that fails changes nothing the caller can act on — the lock row is advisory and\n * a later host takes it over (DESIGN 6.4) — and must never mask the outcome `run()` is about to return. */\nasync function releaseQuietly(deps: RunEngineDeps, lease: LeaseToken): Promise<void> {\n try {\n await deps.leases.release(lease);\n } catch {\n /* the lease is already gone, or was stolen: nothing to undo */\n }\n}\n\nexport function createEngine(deps: RunEngineDeps): RunEngine {\n const leaseTtlMs = deps.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS;\n\n return {\n async run(runId: RunId, host: HostContext): Promise<StopRecord> {\n // DESIGN 4.4: crash/orphan reconciliation BEFORE this host owns the run. `Resumer` takes the run lease itself\n // (step 3, acquire-or-steal after a liveness check) and step 4 refuses a pin mismatch \"BEFORE taking the lease\n // over ... so a pin mismatch must never let this host start acting as the run's owner\" — both are meaningless\n // if the loop has already taken the lease. Reversed, the two collided head-on, and the G1 walking skeleton\n // reproduced both halves: on a first run, recovery found the lock its own caller had just taken and refused it\n // as `conflict/run-host-alive`; after a crash it stole the lease out from under the loop that had just taken\n // it, so the next renewal answered `conflict/lease-lost`. `LeaseManager.acquire` then ADOPTS the lock this\n // very host already owns (same hostId/pid/startToken, same fencing token), which is what makes the two calls\n // one ownership. Recovery runs outside the try on purpose: a refusal here means another host is driving the\n // run, and marking it FAILED would be this host's last legitimate act on a run it does not own.\n // Recorded in docs/v3/gates/G1.md (G1-D1); closes docs/v3/requests/U1.09.md R7.\n await deps.resume.recover(runId, host);\n const lease = await deps.leases.acquire({ runId }, runId, 'exclusive', leaseTtlMs);\n deps.onLease?.(lease);\n // \"The outer `finally` below has nothing left to do about the lease\" — either because this host already handed\n // it back, or because it must never hand it back (a crash).\n let releaseHandled = false;\n\n try {\n for (;;) {\n if (host.signal.aborted) {\n throw host.signal.reason instanceof Error ? host.signal.reason : new Error('RunEngine.run: aborted');\n }\n\n // E0\n crashpoint('host.after-lease');\n const renewed = await deps.leases.renew(lease, leaseTtlMs);\n if (!renewed) {\n throw new CohorteError(\n errorOf('conflict/lease-lost', `run ${runId}: lease renewal failed; this host no longer owns it`),\n );\n }\n\n const table = await resolveTableFor(deps, runId);\n if (!table) {\n throw new CohorteError(\n errorOf(\n 'configuration/incompatible-state-schema',\n `run ${runId}: no table for its (profile, tableVersion)`,\n ),\n );\n }\n\n // E1\n await drainInbox({ deps, runId, host, lease, table });\n\n const runState = await deps.store.readRunTree(runId);\n // The run reached an end state for this host — terminal, halted or suspended (a `pause` the drain above\n // just applied lands here). Nothing new is scheduled from one: a still-open phase row is NOT re-executed\n // (that is what a `resume` re-enters, with fresh incarnations, DESIGN 4.6), and no phase outcome is\n // resolved against a state no row of the table fires from.\n if (NO_SCHEDULING_STATES.has(runState.run.state)) return finalStopRecord(runState);\n\n // E3 (narrows the table; also supplies the guard union E2 and E4 both read facts for) + E4\n const step = nextStep(runState, table);\n const facts = await deps.factCollector.collect(step.guards);\n\n // E2\n const globalStop = deps.checkGlobalStops(runState, facts, deps.loopPolicy);\n if (globalStop) {\n await settleStop({ deps, runId, host, lease, table, runState, step, facts, stop: globalStop });\n return globalStop;\n }\n\n // Ordinary (\"spontaneous\") progress: E7 runs the open phase, E3-E5/E6/E8 (transitions.ts) advance past it.\n const openPhase = findOpenPhase(runState);\n if (openPhase) {\n const now = deps.clock.now();\n const ctx = buildPhaseRunContext(runState, openPhase, lease, host.signal, now);\n const outcome = await deps.phases.execute(ctx);\n const stop = await closePhaseAndAdvance({\n deps,\n runId,\n host,\n lease,\n table,\n runState,\n step,\n facts,\n openPhase,\n outcome,\n });\n if (stop) return stop;\n continue;\n }\n\n // Nothing to do this pass (e.g. IDLE, waiting for a `start` command no host has enqueued yet). A real\n // host polls (DESIGN 4.7: \"every 250 ms\"); this loop does the same rather than spin.\n await deps.clock.sleep(deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS, host.signal);\n }\n } catch (thrown) {\n // Past this line the outer `finally` must NOT hand the lock back, on either branch: a `SimulatedCrash` (or a\n // real `SIGKILL`, which never reaches a catch at all) stands for the process dying RIGHT THERE, so no code\n // after the crash point may run — the fatal commit below, and the release, least of all (DESIGN 4.3); and\n // the ordinary-error branch releases inside its own `finally`, after `commitFatal`.\n //\n // Rethrowing is not enough for the crash: a `finally` runs even when the `catch` around it rethrows, so the\n // outer one below released the lease of a host that is supposed to be gone. The next host then found a FREE\n // run lock and DESIGN 4.3 crash point #2 — \"lease held by a dead (pid, startToken)\" ⇒ \"lease stolen with\n // fencingToken + 1 after a liveness check\" — was never exercised by any crash test. Raised by the U1.INT\n // reviewer, recorded in docs/v3/gates/G1.md §4.\n releaseHandled = true;\n if (thrown instanceof SimulatedCrash) throw thrown;\n try {\n if (host.signal.aborted) throw thrown;\n return await commitFatal(deps, runId, host, lease, thrown);\n } finally {\n await releaseQuietly(deps, lease);\n }\n } finally {\n // A normal exit (COMPLETED, CANCELLED, a settled stop) hands the run lock back instead of leaving a row\n // that only a takeover can clear (DESIGN 6.4).\n if (!releaseHandled) await releaseQuietly(deps, lease);\n deps.onLease?.(undefined);\n }\n },\n };\n}\n","// @cohorte/core/events — DESIGN 2.5 (EventWriter), 2.3.2 (envelope, ordering under batching), 2.3.6 (summary\n// sanitisation). PLAN U1.08. Wave-0 seam (PLAN U0.08) replaced: this file is now the implementation.\n//\n// `EventsDeps` is the FROZEN contract of `contract/factories.ts`, re-exported below — never a second interface of the\n// same name (a composition root typed against the `@cohorte/core` barrel could not then build this writer). It gained\n// `spool` in U0.08's fix round 1: the deliverable requires ephemerals to reach the spool port (DESIGN 2.3.2), so the\n// frozen type was WIDENED where it lives rather than shadowed here.\nimport type { Clock, IdSource, JsonValue, Redactor } from '@cohorte/base';\nimport type { DurableEnvelope, EventDraft, SealedEventDraft, StoreTx } from '@cohorte/persistence/contract';\nimport {\n catalogue,\n type DurableEventType,\n type EventType,\n isDurableEventType,\n PROTOCOL_VERSION,\n SUMMARY_MAX_LENGTH,\n} from '@cohorte/protocol';\nimport type { EventsDeps } from '../contract/factories.ts';\nimport type { EventWriter } from '../contract/internal.ts';\nimport type { EphemeralInput, EventDraftInput } from '../contract/types.ts';\n\nexport type { EventsDeps };\n\n/** Codepoint at most 0x1F (C0) or between 0x7F and 0x9F inclusive (C1, DEL included). Built from numbers only: no\n * escape sequence in this file's source, so no tool in the chain can mistake one for the character it denotes. */\nfunction isControlCodepoint(code: number): boolean {\n const c0 = code <= 31;\n const c1 = code >= 127 && code <= 159;\n return c0 || c1;\n}\n\nconst REPLACEMENT_CHARACTER = String.fromCodePoint(65533); // U+FFFD\n\n/**\n * Every C0/C1 control character replaced by U+FFFD before validation (DESIGN 2.3.6), then capped to\n * SUMMARY_MAX_LENGTH. The cap lands on a CODEPOINT boundary: iterating the string yields whole characters, so an\n * astral character (a surrogate PAIR) is either kept entire or dropped entire — `slice(0, 200)` would leave a lone\n * surrogate in a persisted, human-facing field, which the envelope's `pattern` does not reject. Counting UTF-16 code\n * units keeps `maxLength: 200` true for both a code-unit reader and a codepoint reader (Ajv counts codepoints), since\n * every character costs at least one unit.\n */\nfunction sanitizeSummary(raw: string): string {\n let scrubbed = '';\n for (const character of raw) {\n const kept = isControlCodepoint(character.codePointAt(0) ?? 0) ? REPLACEMENT_CHARACTER : character;\n if (scrubbed.length + kept.length > SUMMARY_MAX_LENGTH) break;\n scrubbed += kept;\n }\n return scrubbed;\n}\n\n/** A caller (core code building an EventDraftInput) broke its own contract: not a run outcome, so not a CohorteError. */\nexport class EventDraftInvalid extends TypeError {\n constructor(type: string, detail: string) {\n super(`EventWriter: invalid payload for \"${type}\": ${detail}`);\n this.name = 'EventDraftInvalid';\n }\n}\n\ntype Severity = 'info' | 'success' | 'warning' | 'error' | 'progress';\ntype Source = 'cohorte' | 'runtime' | 'client' | 'human';\n\ninterface CommonFields {\n source: Source;\n phase?: EventDraftInput['phase'];\n agent?: EventDraftInput['agent'];\n causationId?: string;\n summary: string;\n severity: Severity;\n}\n\nfunction validatedPayload(type: EventType, payload: JsonValue): JsonValue {\n const result = catalogue.compileStrict(type)(payload);\n if (!result.ok) {\n const detail = result.error\n .map((issue) => `${issue.path || '(root)'} ${issue.keyword}: ${issue.message}`)\n .join('; ');\n throw new EventDraftInvalid(type, detail);\n }\n return result.value as JsonValue;\n}\n\nfunction commonFieldsOf(input: {\n source?: Source;\n phase?: EventDraftInput['phase'];\n agent?: EventDraftInput['agent'];\n causationId?: string;\n summary: string;\n severity?: Severity;\n}): CommonFields {\n return {\n source: input.source ?? 'cohorte',\n ...(input.phase === undefined ? {} : { phase: input.phase }),\n ...(input.agent === undefined ? {} : { agent: input.agent }),\n ...(input.causationId === undefined ? {} : { causationId: input.causationId }),\n summary: sanitizeSummary(input.summary),\n severity: input.severity ?? 'info',\n };\n}\n\n/**\n * A redaction failure REPLACES the event with `runtime.warning{code:'security/redaction-failed'}` and drops the raw\n * payload (DESIGN 2.6.5). `runtime.warning` is the closest catalogue row to the prose \"error{...}\" placeholder — no\n * event named plainly `error` exists in the catalogue (deviation, recorded in docs/v3/requests/U1.08.md).\n */\nconst REDACTION_FAILED_TYPE: DurableEventType = 'runtime.warning';\n\n/**\n * The substitute's summary is a CONSTANT, and it is the whole point: it shares nothing with the draft that just blew\n * the redactor up. `summary` is the agent-controlled human-facing string of DESIGN 2.3.6, so the secret that made\n * `seal` throw can perfectly well be in there rather than in the payload; a substitute carrying the original summary\n * would hit the same content, throw again, and let the exception escape `append()` — aborting the caller's whole\n * transaction (inside `EffectJournal.run`, tx A: no intent row, no effect) instead of degrading to\n * `security/redaction-failed`. `causationId` is free-form as well and is dropped for the same reason.\n */\nconst REDACTION_FAILED_SUMMARY = 'an event was replaced: its redaction failed and its payload was dropped';\n\n/** Builds a plain `Record<string, JsonValue>` by mutation: sidesteps the friction between an interface's optional\n * properties and JsonValue's index signature that a spread/literal of `CommonFields` runs into under\n * exactOptionalPropertyTypes (an absent key never becomes a present key holding `undefined`). */\nfunction envelopeFields(\n base: { protocolVersion: string; eventId: string; timestamp: string; runId: string; type: string },\n common: CommonFields,\n payload: JsonValue,\n): Record<string, JsonValue> {\n const out: Record<string, JsonValue> = {\n protocolVersion: base.protocolVersion,\n eventId: base.eventId,\n timestamp: base.timestamp,\n runId: base.runId,\n type: base.type,\n source: common.source,\n summary: common.summary,\n severity: common.severity,\n payload,\n };\n if (common.phase !== undefined) out.phase = common.phase;\n if (common.agent !== undefined) out.agent = common.agent;\n if (common.causationId !== undefined) out.causationId = common.causationId;\n return out;\n}\n\n/**\n * `EventDraft` restated so every property structurally satisfies `JsonValue`. TypeScript only grants an object\n * TYPE (not an `interface`) the implicit string index signature that `T extends JsonValue` needs, and DESIGN\n * keeps `ErrorInfo` (nested in several event payloads, e.g. `agent.failed`) an `interface` on purpose — it is\n * self-referential and a derived type would re-expand at every use site (packages/base/src/errors.ts). A\n * homomorphic mapped type re-states the same shape as fresh object-type literals, which DOES get the index\n * signature, without touching a single field name or value — `DeepJson<T>` is mutually assignable to `T`.\n */\ntype DeepJson<T> = T extends readonly (infer U)[]\n ? DeepJson<U>[]\n : T extends string | number | boolean | null | undefined\n ? T\n : T extends object\n ? { [K in keyof T]: DeepJson<T[K]> }\n : T;\n\n/** {@link EventDraft}, JsonValue-shaped (see {@link DeepJson}): the type `sealJson` is called with below, so its\n * return type is genuinely `Sealed<EventDraft>` (== `SealedEventDraft`) — never asserted (check-layers rule f:\n * only the redactor, packages/security/src/redact/seal.ts, mints `Sealed<T>`). */\ntype EventDraftJson = DeepJson<EventDraft>;\ntype EventDraftPreRedactionsJson = Omit<EventDraftJson, 'redactions'>;\n\n/** Seals a durable draft. Two passes: `sealJson` cannot report the redactions it just made back INTO the very\n * value it sealed, so a first pass finds them and a second seals a draft that already carries that (idempotent —\n * nothing new to redact in metadata about redactions) list, so the persisted `redactions` field is accurate\n * (DESIGN 2.3.2). Neither pass ever casts `as Sealed…`: the non-`Sealed` casts below only retype the still-plain\n * envelope as its own (unsealed) JsonValue-shaped mirror, which is what lets `sealJson`'s own generic parameter —\n * not an assertion on its result — mint the precise `SealedEventDraft` this function returns. */\nfunction sealDraft(\n redactor: Redactor,\n ids: IdSource,\n clock: Clock,\n runId: string,\n type: DurableEventType,\n payload: JsonValue,\n common: CommonFields,\n): SealedEventDraft {\n const fields = envelopeFields(\n { protocolVersion: PROTOCOL_VERSION, eventId: ids.next<'EventId'>('evt'), timestamp: clock.now(), runId, type },\n common,\n payload,\n ) as unknown as EventDraftPreRedactionsJson;\n const first = redactor.sealJson(fields);\n const withRedactions = { ...first.value, redactions: first.redactions } as unknown as EventDraftJson;\n return redactor.sealJson(withRedactions).value;\n}\n\nexport function createEventWriter(deps: EventsDeps): EventWriter {\n /** Per run: the last known durable sequence and the next `sub` to hand an ephemeral event at that sequence. */\n const ephemeralCursor = new Map<string, { sequence: number; sub: number }>();\n /** The transactions this writer has already read `runs.last_sequence` from (see `append`). */\n const observedTx = new WeakSet<StoreTx>();\n\n function cursorFor(runId: string): { sequence: number; sub: number } {\n let cursor = ephemeralCursor.get(runId);\n if (!cursor) {\n cursor = { sequence: 0, sub: 0 };\n ephemeralCursor.set(runId, cursor);\n }\n return cursor;\n }\n\n /** `undefined` = this draft could not be sealed at all (see the inner catch): it is dropped, never thrown. */\n function sealedDraftOf(runId: string, input: EventDraftInput): SealedEventDraft | undefined {\n if (!isDurableEventType(input.type)) {\n throw new EventDraftInvalid(input.type, 'not a durable event type (use ephemeral() for an ephemeral one)');\n }\n const type = input.type;\n // Validation is a caller bug: it is never turned into a substitute event, only a redaction failure is.\n const payload = validatedPayload(type, input.payload);\n const common = commonFieldsOf(input);\n try {\n return sealDraft(deps.redactor, deps.ids, deps.clock, runId, type, payload, common);\n } catch {\n const substitutePayload: Record<string, JsonValue> = {\n code: 'security/redaction-failed',\n message: 'the redactor failed on this event; its payload was dropped (DESIGN 2.6.5)',\n };\n // `agent` is a host-minted id, not agent-controlled text: it says WHOSE event was replaced and is the one\n // field of the original worth keeping (see REDACTION_FAILED_SUMMARY for what is deliberately not kept).\n if (common.agent !== undefined) substitutePayload.agent = common.agent;\n const substituteCommon: CommonFields = {\n source: common.source,\n ...(common.phase === undefined ? {} : { phase: common.phase }),\n ...(common.agent === undefined ? {} : { agent: common.agent }),\n summary: REDACTION_FAILED_SUMMARY,\n severity: 'error',\n };\n try {\n return sealDraft(\n deps.redactor,\n deps.ids,\n deps.clock,\n runId,\n REDACTION_FAILED_TYPE,\n substitutePayload,\n substituteCommon,\n );\n } catch {\n // A redactor that fails on a constant summary and a payload of two literal strings is broken beyond\n // substitution: nothing can be sealed, so nothing can be persisted for this draft (I7 — an unsealed value\n // never reaches the store). Dropping this ONE event keeps the caller's transaction, and the effect rows it\n // carries, alive; letting the exception out would roll all of it back.\n return undefined;\n }\n }\n }\n\n return {\n append(tx: StoreTx, drafts: EventDraftInput[]): DurableEnvelope[] {\n const run = tx.run();\n const runId = run.runId;\n const cursor = cursorFor(runId);\n\n // COMMITTED evidence, read once per transaction: at the first `append()` into `tx`, `runs.last_sequence` is\n // what the store has actually committed (a rolled-back transaction leaves it untouched — DESIGN 2.4's\n // \"WAL all-or-nothing\"). The envelopes `appendEvents` hands back below are NOT that: they belong to a\n // transaction that has not committed yet, and DESIGN 2.3.2 defines an ephemeral's `sequence` as \"the sequence\n // of the last COMMITTED durable event when it is stamped\". So the cursor is RECONCILED here against the store\n // before it is advanced optimistically: after a rollback it drops back to the sequence the store really holds,\n // instead of staying above it for ever and stamping ephemerals against a sequence that never existed.\n // Closing the remaining window (an ephemeral stamped BETWEEN the rollback and the next transaction) needs a\n // commit signal the frozen `EventWriter`/`StoreTx` ports do not carry: request R6.\n if (!observedTx.has(tx)) {\n observedTx.add(tx);\n if (run.lastSequence !== cursor.sequence) {\n cursor.sequence = run.lastSequence;\n cursor.sub = 0;\n }\n }\n\n const sealed: SealedEventDraft[] = [];\n for (const draft of drafts) {\n const one = sealedDraftOf(runId, draft);\n if (one !== undefined) sealed.push(one);\n }\n const appended = tx.appendEvents(sealed);\n for (const envelope of appended) {\n if (envelope.sequence > cursor.sequence) {\n cursor.sequence = envelope.sequence;\n cursor.sub = 0;\n }\n }\n return appended;\n },\n\n /**\n * KNOWN GAP, request R6 / the G1 lead decision: DESIGN 2.3.2's ordering rule wants an ephemeral \"stamped at\n * emission from the writer's queue, not at production — enqueued behind every pending durable draft of the same\n * agent\". The frozen `EventWriter` port cannot express that: its only durable entry, `append(tx, drafts)`, is\n * called synchronously INSIDE a store transaction, so the writer never learns that the producer is still\n * assembling a batch (DESIGN 4.2 E7's <= 50 ms window), and `StoreTx` has no commit hook to tell it when one\n * landed. Holding every ephemeral until the next `append()` would trade the ordering violation for a stalled\n * token stream (nothing durable is appended while a model is streaming). So this stamps at production, against\n * the last sequence the store is known to have committed, and `packages/core/test/events/writer.test.ts` pins\n * BOTH what holds and what does not.\n */\n ephemeral(runId, input: EphemeralInput): void {\n const cursor = cursorFor(runId);\n const at = { sequence: cursor.sequence, sub: cursor.sub + 1 };\n let line: string;\n try {\n const payload = validatedPayload(input.type, input.payload);\n // `source` / `severity` are forwarded since gate G1 (docs/v3/requests/U1.08.md R9); `commonFieldsOf` still\n // supplies the `'cohorte'` / `'info'` defaults when the producer names neither.\n const common = commonFieldsOf({\n summary: '',\n phase: input.phase,\n agent: input.agent,\n ...(input.source === undefined ? {} : { source: input.source }),\n ...(input.severity === undefined ? {} : { severity: input.severity }),\n });\n const fields = envelopeFields(\n {\n protocolVersion: PROTOCOL_VERSION,\n eventId: deps.ids.next<'EventId'>('evt'),\n timestamp: deps.clock.now(),\n runId,\n type: input.type,\n },\n common,\n payload,\n );\n fields.sequence = at.sequence;\n fields.sub = at.sub;\n fields.durability = 'ephemeral';\n const first = deps.redactor.sealJson({ ...fields, redactions: [] });\n const withRedactions: Record<string, JsonValue> = { ...first.value, redactions: first.redactions };\n line = JSON.stringify(deps.redactor.sealJson(withRedactions).value);\n } catch {\n // Ephemeral loss is acceptable by definition (DESIGN 2.3.2): a bad draft or a redaction failure drops the\n // single ephemeral event rather than the caller's whole turn.\n return;\n }\n cursor.sub = at.sub;\n deps.spool.append(runId, line);\n },\n };\n}\n","import { type AgentId, canonicalJson, type JsonValue, sha256Hex } from '@cohorte/base';\nimport { type AgentGrant, DEFAULT_DENY_GLOBS } from '@cohorte/security/contract';\nimport type { AgentGrantRequest } from '../contract/types.ts';\n\nexport interface GrantComputer {\n compute(request: AgentGrantRequest): AgentGrant;\n}\nexport type GrantsDeps = Record<string, never>;\n\nexport function createGrantComputer(_deps: GrantsDeps): GrantComputer {\n return {\n compute(request): AgentGrant {\n const digest = sha256Hex(canonicalJson(request as unknown as JsonValue));\n const include = request.ownedPaths.map((path) => (path.endsWith('/**') ? path : `${path}/**`));\n const reviewer = request.role === 'reviewer' || request.role.endsWith('/reviewer');\n const tools = [\n ...new Set(\n reviewer\n ? request.tools.filter((tool) => !['write_file', 'patch_file', 'run_command'].includes(tool))\n : request.tools,\n ),\n ].sort();\n const perTool = Object.fromEntries(\n tools.map((tool) => [tool, { timeoutMs: 120_000, maxOutputBytes: 1024 * 1024 }]),\n );\n return {\n agentId: `agt_${digest.slice(0, 24)}` as AgentId,\n role: request.role,\n digest,\n tools,\n roots: { workspace: null, readOnly: [] },\n read: { include: [...include], exclude: [] },\n write: reviewer ? { include: [], exclude: [] } : { include: [...include], exclude: [] },\n denyRead: { include: [...DEFAULT_DENY_GLOBS], exclude: [] },\n denyWrite: { include: [...DEFAULT_DENY_GLOBS, ...(reviewer ? ['**'] : [])], exclude: [] },\n commands: { default: 'deny', rules: [] },\n secrets: [...(request.secrets ?? [])],\n temporary: [],\n limits: {\n maxToolCalls: request.limits?.maxToolCalls ?? 100,\n maxCallsPerMinute: request.limits?.maxCallsPerMinute ?? 60,\n perTool,\n },\n };\n },\n };\n}\n","import { type SurfaceId, sha256Hex } from '@cohorte/base';\nimport type { Finding, ReviewResult } from '@cohorte/protocol';\n\ntype Severity = 'critical' | 'major' | 'minor' | 'info';\n\nfunction identity(finding: Finding): string {\n const file = finding.location?.file ?? '(unknown)';\n const words = finding.actual\n .toLocaleLowerCase()\n .replace(/[^\\p{L}\\p{N}]+/gu, ' ')\n .trim()\n .split(/\\s+/u)\n .filter(Boolean)\n .slice(0, 8)\n .join(' ');\n return `${file}|${words}`;\n}\n\nfunction severityOf(finding: Finding): Severity {\n if (finding.kind === 'complexity' && (finding.severity === 'critical' || finding.severity === 'major'))\n return 'minor';\n return finding.severity as Severity;\n}\n\nfunction sortedUnique(values: readonly string[]): string[] {\n return [...new Set(values)].sort((a, b) => Buffer.from(a).compare(Buffer.from(b)));\n}\n\nexport function calculateReview(\n findings: readonly Finding[],\n unreviewed: readonly SurfaceId[],\n changedFiles: ReadonlySet<string> = new Set(),\n): ReviewResult {\n const needsInvestigation: Finding[] = [];\n const eligible: Finding[] = [];\n for (const original of findings) {\n const finding = { ...original, severity: severityOf(original) } as Finding;\n if (finding.location?.file === undefined || finding.reproduction === undefined) {\n needsInvestigation.push(finding);\n continue;\n }\n if (finding.scope === 'deferred' && changedFiles.has(finding.location.file)) {\n eligible.push({ ...finding, scope: 'in-scope' });\n } else {\n eligible.push(finding);\n }\n }\n\n const ordered = eligible\n .sort((a, b) => {\n const rank = (f: Finding): number =>\n f.kind === 'security' || f.severity === 'critical'\n ? 0\n : f.severity === 'major'\n ? 1\n : f.severity === 'minor'\n ? 2\n : 3;\n return rank(a) - rank(b) || identity(a).localeCompare(identity(b));\n })\n .slice(0, 30);\n const deferred = ordered.filter((f) => f.scope === 'deferred');\n const kept = ordered.filter((f) => f.scope === 'in-scope');\n const refuted: Finding[] = [];\n const blockingItems = sortedUnique(\n kept.filter((f) => f.severity === 'critical' || f.kind === 'security').map(identity),\n );\n const fixItems = sortedUnique(\n kept.filter((f) => f.severity === 'critical' || f.kind === 'security' || f.severity === 'major').map(identity),\n );\n const fingerprint = fixItems.length === 0 ? '' : sha256Hex(`${fixItems.join('\\n')}\\n`).slice(0, 16);\n const counts = { critical: 0, major: 0, minor: 0, info: 0 };\n for (const finding of kept) counts[severityOf(finding)] += 1;\n const security = kept.some((f) => f.kind === 'security');\n const clean = fixItems.length === 0 && !security && deferred.length === 0;\n return {\n verdict: unreviewed.length > 0 || security ? 'needs-human' : clean ? 'approved' : 'findings',\n kept,\n refuted,\n deferred,\n needsInvestigation,\n blocking: blockingItems.length,\n blockingItems,\n fingerprint,\n unreviewed: [...unreviewed],\n clean,\n counts,\n };\n}\n\nexport function findingIdentity(finding: Finding): string {\n return identity(finding);\n}\n","import { type AgentId, type BudgetCounters, errorOf, type ModelCapability, type SurfaceId } from '@cohorte/base';\nimport type { ActivePipelineState, CohorteRole } from '@cohorte/protocol';\nimport { Type } from 'typebox';\nimport type { PhaseContractRegistry, PhasesContractsDeps } from '../../contract/factories.ts';\nimport type { AgentPlan, AgentResult, PhaseContract, PhaseInputContext, TaskSpec } from '../../contract/types.ts';\nimport { calculateReview } from '../../review/normalize.ts';\n\nexport type { PhaseContractRegistry, PhasesContractsDeps };\n\nconst SUPPORTED_PHASES = [\n 'PREFLIGHT',\n 'BUILD',\n 'TEST',\n 'REVIEW',\n 'FIX',\n 'SHIP',\n] as const satisfies readonly ActivePipelineState[];\ntype SupportedPhase = (typeof SUPPORTED_PHASES)[number];\n\nconst RETRY = {\n maxAttempts: 3,\n retryOn: ['timeout', 'provider-transient', 'tool-transient'] as const,\n backoff: { baseMs: 250, factor: 2, maxMs: 10_000, jitter: 'full' as const },\n};\n\nconst OBJECTIVES: Record<SupportedPhase, string> = {\n PREFLIGHT: 'validate readiness, specification completeness and surface ownership',\n BUILD: 'implement the frozen specification in isolated surface worktrees',\n TEST: 'run the project checks against the integration tree',\n REVIEW: 'review every touched surface against the immutable review reference',\n FIX: 'address open review findings without changing their claims',\n SHIP: 'verify the approved integration digest and prepare the ship report',\n};\n\nconst phaseError = (state: ActivePipelineState) =>\n errorOf('configuration/phase-not-available', `phase ${state} has no V3 implementation`);\n\nfunction surfacesOf(ctx: PhaseInputContext): string[] {\n const fromWorktrees = ctx.run.worktrees.map((worktree) => worktree.slot).filter((slot) => !slot.startsWith('_'));\n const fromAgents = ctx.run.agents.flatMap((agent) => (agent.surface === undefined ? [] : [agent.surface as string]));\n const fromPlan = ctx.run.run.zones?.filter((zone) => !zone.startsWith('_')) ?? [];\n return [...new Set([...fromPlan, ...fromWorktrees, ...fromAgents])].sort();\n}\n\nfunction toolsFor(role: CohorteRole): string[] {\n if (role === 'reviewer' || role === 'security-reviewer') {\n return ['read_file', 'list_files', 'search', 'git_diff', 'submit_result'];\n }\n return ['read_file', 'list_files', 'search', 'git_diff', 'write_file', 'patch_file', 'run_command', 'submit_result'];\n}\n\nfunction planFor(role: 'implementer' | 'reviewer' | 'fixer', surface: string, state: SupportedPhase): AgentPlan {\n const ownedPaths = [`${surface}/**`];\n const tools = toolsFor(role);\n const readOnly = role === 'reviewer';\n const task: TaskSpec = {\n role,\n objective: OBJECTIVES[state],\n stablePrefix: `cohorte ${state.toLowerCase()} task for surface ${surface}`,\n ownedPaths,\n facts: { phase: state, surface },\n };\n return {\n agentId: `agt_${role}_${surface}` as AgentId,\n role,\n surface: surface as SurfaceId,\n owner: surface,\n promptId: `agents/${role}`,\n task,\n context: { tiers: ['system', 'doctrine', 'data', 'task', 'prior-results'], includePaths: ownedPaths },\n tools,\n grant: {\n role,\n ownedPaths: readOnly ? [] : ownedPaths,\n ...(readOnly ? { readOnlyPaths: ownedPaths } : {}),\n tools,\n },\n modelTier: (role === 'reviewer' ? 'reasoning' : 'coding') as ModelCapability,\n budget: { maxEngineRetries: 0 },\n workspace: readOnly ? { kind: 'readonly-ref', ref: 'review-ref' } : { kind: 'slot', slot: surface },\n };\n}\n\nfunction budgetFor(run: PhaseInputContext['run'], state: SupportedPhase): BudgetCounters {\n const record = run.budgets.find((budget) => budget.level === 'phase' && budget.scopeId === state);\n return record?.limit ?? {};\n}\n\nfunction contractFor(state: SupportedPhase): PhaseContract {\n return {\n id: state.toLowerCase(),\n version: 1,\n state,\n objectives: [OBJECTIVES[state]],\n resolveInputs(ctx) {\n if (ctx.phase.state !== state) return { ok: false, error: phaseError(ctx.phase.state) };\n return { ok: true, value: { phase: state, runId: ctx.run.run.runId, surfaces: surfacesOf(ctx) } };\n },\n planAgents(input: unknown, ctx): AgentPlan[] {\n const surfaces =\n input && typeof input === 'object' && 'surfaces' in input && Array.isArray(input.surfaces)\n ? input.surfaces.filter((surface): surface is string => typeof surface === 'string').sort()\n : surfacesOf(ctx);\n if (state === 'TEST' || state === 'PREFLIGHT' || state === 'SHIP') return [];\n const role = state === 'BUILD' ? 'implementer' : state === 'REVIEW' ? 'reviewer' : 'fixer';\n return surfaces.map((surface) => planFor(role, surface, state));\n },\n outputSchema: Type.Unknown(),\n checks: [],\n budget: (run) => budgetFor(run, state),\n stop: [],\n retry: RETRY,\n approvals: state === 'SHIP' ? [{ kind: 'ship', applies: () => true }] : [],\n assemble(_input: unknown, results: AgentResult[]) {\n if (state === 'REVIEW') {\n const findings = results.flatMap((result) => result.output?.findings ?? []);\n return { ok: true, value: { phase: state, results, review: calculateReview(findings, []) } };\n }\n return { ok: true, value: { phase: state, results } };\n },\n } as PhaseContract;\n}\n\nexport function createPhaseContracts(_deps: PhasesContractsDeps): PhaseContractRegistry {\n const contracts = new Map<SupportedPhase, PhaseContract>(\n SUPPORTED_PHASES.map((state) => [state, contractFor(state)]),\n );\n return {\n get: (state) =>\n SUPPORTED_PHASES.includes(state as SupportedPhase) ? contracts.get(state as SupportedPhase) : undefined,\n };\n}\n\n// Keep this assertion close to the registry so adding a new active state forces an explicit decision here.\nconst _supportedStatesAreKnown: readonly ActivePipelineState[] = SUPPORTED_PHASES;\nvoid _supportedStatesAreKnown;\n","import { type ErrorInfo, type JsonValue, toErrorInfo } from '@cohorte/base';\nimport type { CheckResult, Finding, StopRecord } from '@cohorte/protocol';\nimport type { PhasesExecutorDeps } from '../../contract/factories.ts';\nimport type { PhaseExecutor as PhaseExecutorPort } from '../../contract/internal.ts';\nimport type { AgentResult, PhaseOutcome } from '../../contract/types.ts';\n\nfunction slotsOf(plans: readonly Parameters<PhasesExecutorDeps['supervisor']['runAgents']>[0][number][]) {\n return [...new Set(plans.flatMap((plan) => (plan.workspace.kind === 'slot' ? [plan.workspace.slot] : [])))];\n}\n\nconst error = (code: string, message: string, remediation: string): ErrorInfo => ({\n code,\n class: 'validation' as const,\n message,\n impact: 'The current phase cannot produce a valid durable outcome.',\n retryable: false,\n remediation,\n});\n\nconst failed = (\n code: 'agent-dead' | 'outputs-invalid' | 'checks-red',\n failure: ReturnType<typeof error>,\n findings: Finding[] = [],\n checks: CheckResult[] = [],\n): PhaseOutcome => ({\n kind: 'failed',\n failure: { code, error: failure, findings },\n checks,\n});\n\n/** Provider auth/quota failures park the run; they are not ordinary failed phases. */\nfunction suspendedProviderStop(info: ErrorInfo): StopRecord | undefined {\n const code = info.code.toLowerCase();\n if (\n code.includes('auth') ||\n code.includes('unauthorized') ||\n code.includes('forbidden') ||\n info.class === 'human-required'\n ) {\n return { reason: 'auth-required', detail: info.message, resumable: true };\n }\n if (code.includes('quota') || code.includes('rate-limit') || code.includes('rate_limited')) {\n return { reason: 'quota-exceeded', detail: info.message, resumable: true };\n }\n return undefined;\n}\n\n/**\n * Executes the deterministic phase contract around the supervisor.\n *\n * Worktree acquisition, commit and merge are deliberately owned by the phase\n * contracts and their services; the executor only coordinates the frozen\n * contract boundary: resolve -> plan -> run -> assemble.\n */\nexport function createPhaseExecutor(deps: PhasesExecutorDeps): PhaseExecutorPort {\n return {\n async execute(ctx) {\n const contract = deps.contracts.get(ctx.phase.state);\n if (!contract) {\n return failed(\n 'outputs-invalid',\n error(\n 'configuration/phase-contract-missing',\n `No contract is registered for ${ctx.phase.state}.`,\n 'Install a compatible phase contract.',\n ),\n );\n }\n\n const resolved = contract.resolveInputs(ctx);\n if (!resolved.ok) return failed('outputs-invalid', resolved.error);\n\n let results: AgentResult[];\n try {\n const plans = contract.planAgents(resolved.value, ctx);\n const slots = slotsOf(plans);\n if (typeof deps.worktrees.acquire === 'function') {\n for (const plan of plans) {\n if (plan.workspace.kind === 'slot') {\n const worktree = await deps.worktrees.acquire(plan.workspace.slot, plan.agentId);\n if (deps.store) {\n await deps.store.transact({ runId: ctx.run.run.runId }, ctx.lease, (tx) => {\n tx.putWorktree(worktree);\n });\n }\n }\n }\n }\n results = await deps.supervisor.runAgents(plans, ctx);\n if (ctx.phase.state === 'TEST' && deps.checkRunner) {\n const checks = await deps.checkRunner.run(ctx);\n const erroredCheck = checks.find((check) => check.status === 'errored');\n if (erroredCheck)\n return {\n kind: 'suspended',\n stop: {\n reason: 'check-environment',\n detail: `check errored: ${erroredCheck.name}`,\n resumable: true,\n resumeRequires: 'environment-repair',\n },\n error: error(\n 'validation/check-environment',\n `Project check ${erroredCheck.name} could not run.`,\n 'Repair the check environment and resume the run.',\n ),\n };\n const failedChecks = checks.filter((check) => check.status === 'failed');\n if (failedChecks.length > 0)\n return failed(\n 'checks-red',\n error(\n 'validation/checks-red',\n `${failedChecks.length} project check(s) failed.`,\n 'Fix the integration tree and run the checks again.',\n ),\n [],\n checks,\n );\n return { kind: 'passed', output: { checks } as JsonValue, artifacts: [], checks };\n }\n const failedAgent = results.find((result) => result.outcome !== 'completed');\n if (!failedAgent && slots.length > 0 && typeof deps.integration.commit === 'function') {\n for (const slot of slots) await deps.integration.commit(slot, 'result');\n if (typeof deps.integration.merge === 'function' && slots.length > 0) {\n for (const slot of slots) {\n const merged = await deps.integration.merge(slot, '_integration');\n if ('kind' in merged && merged.kind === 'conflict') {\n return {\n kind: 'failed',\n failure: {\n code: 'merge-conflict',\n error: error(\n 'conflict/merge-conflict',\n `Integration conflict in ${slot}: ${merged.files.join(', ') || 'unknown files'}.`,\n 'Resolve the conflict and retry the phase.',\n ),\n findings: [],\n },\n };\n }\n }\n }\n if (typeof deps.worktrees.release === 'function') {\n for (const slot of slots) await deps.worktrees.release(slot);\n }\n }\n } catch (cause) {\n const providerStop = suspendedProviderStop(\n toErrorInfo(cause, { code: 'provider-terminal/agent-failed', class: 'provider-terminal' }),\n );\n if (providerStop)\n return {\n kind: 'suspended',\n stop: providerStop,\n error: toErrorInfo(cause, { code: 'provider-terminal/agent-failed', class: 'provider-terminal' }),\n };\n return failed(\n 'agent-dead',\n error(\n 'provider-terminal/phase-agent-failed',\n cause instanceof Error ? cause.message : 'The phase supervisor failed.',\n 'Inspect the agent runtime and resume the run.',\n ),\n );\n }\n\n const failedAgent = results.find((result) => result.outcome !== 'completed');\n if (failedAgent) {\n const providerStop = failedAgent.error && suspendedProviderStop(failedAgent.error);\n if (providerStop)\n return {\n kind: 'suspended',\n stop: providerStop,\n ...(failedAgent.error ? { error: failedAgent.error } : {}),\n };\n return failed(\n 'agent-dead',\n failedAgent.error ??\n error(\n 'provider-terminal/agent-incomplete',\n `Agent ${failedAgent.agent.agentId} did not complete.`,\n 'Retry or replace the failed agent.',\n ),\n );\n }\n\n const assembled = contract.assemble(resolved.value, results, ctx);\n if (!assembled.ok) return failed('outputs-invalid', assembled.error);\n if (\n ctx.phase.state === 'REVIEW' &&\n typeof assembled.value === 'object' &&\n assembled.value !== null &&\n 'review' in assembled.value &&\n typeof assembled.value.review === 'object' &&\n assembled.value.review !== null &&\n 'clean' in assembled.value.review &&\n assembled.value.review.clean === false\n ) {\n const review = assembled.value.review as {\n blockingItems?: string[];\n kept?: Finding[];\n };\n return failed(\n 'checks-red',\n error(\n 'validation/review-findings',\n `Review found ${review.kept?.length ?? 0} finding(s).`,\n 'Run the FIX phase and review again.',\n ),\n review.kept ?? [],\n );\n }\n\n return {\n kind: 'passed',\n output: assembled.value as JsonValue,\n artifacts: results.flatMap((result) => result.artifacts),\n };\n },\n };\n}\n","// DESIGN 2.5.1 (the transition table) — the closed sets of ids the code table and the loop controller mint. FROZEN\n// at G0: adding a row to the table adds only new VALUES here, never a new shape.\nimport { STOP_REASONS } from '@cohorte/protocol';\n\n/**\n * Every precondition named by a row of `feature@1` / `bugfix@1` / `review@1` (DESIGN 2.5.1), collected once so a\n * `GuardRegistry` (U2.05) can be asserted total against them. A parameterised guard in the table's prose\n * (`phase.available(BRAINSTORM)`, `readiness.in(READY,RESERVATIONS)`, `policy.skip-allows(X)`,\n * `resume.acknowledged(blocked-inspected)`) is one guard id evaluated with the row's own context, not one id per\n * argument.\n */\nexport const GUARD_IDS = [\n 'input.is-idea',\n 'phase.available',\n 'brainstorm.output-valid',\n 'spec.schema-valid',\n 'spec.frozen',\n 'host.not-root',\n 'host.outside-target',\n 'config.trust-satisfied',\n 'snapshot.captured',\n 'runtime.pin-valid',\n 'runtime.platform-supported',\n 'auth.plan-satisfied',\n 'billing.consented',\n 'sandbox.meets-policy',\n 'repo.base-resolved',\n 'locks.project+zones-held',\n 'readiness.in',\n 'contract.present-or-exempt',\n 'surfaces.all-owned',\n 'budget.available',\n 'readiness.not-ready',\n 'surfaces.unowned',\n 'agents.all-completed',\n 'outputs.schema-valid',\n 'diff.within-ownership',\n 'integration.merged',\n 'tree.digest-recorded',\n 'checks.all-passed',\n 'checks.digest-equals-integration',\n 'checks.failed-non-environmental',\n 'loop.may-continue',\n 'review.nothing-to-fix',\n 'review.no-unreviewed',\n 'review.leftovers-parked-or-waived',\n 'reviewref.digest-equals-integration',\n 'review.has-fix-items',\n 'review.no-contract-change',\n 'review.contract-change',\n 'review.leftovers-routed-ask',\n 'review.security-needs-investigation',\n 'approval.ship-allowed',\n 'tree.digest-equals-approved',\n 'acceptance.no-open-human-items',\n 'tree.digest-differs-from-approved',\n 'checks.errored-environmental',\n 'approval.pending-blocking',\n 'resume.locks-rebuilt',\n 'resume.git-verified',\n 'approval.none-pending-blocking',\n 'retry.target-legal',\n 'resume.acknowledged',\n 'policy.skip-allows',\n 'skip.justified',\n /** `review@1`'s own `IDLE -> REVIEW` row (DESIGN 2.5.1, the paragraph after the T01-T33 table) */\n 'reviewtarget.resolved-to-sha',\n] as const;\nexport type GuardId = (typeof GUARD_IDS)[number];\n\n/**\n * Every declarative transition effect named by the `effects` column of the table (DESIGN 2.5.1), plus\n * `open-approval`'s three kinds folded into one id: the kind travels in the effect's own arguments, not in a\n * separate id per kind.\n */\nexport const TRANSITION_EFFECT_IDS = [\n 'record-spec-hash',\n 'create-integration-branch',\n 'open-approval',\n 'mint-review-ref',\n 'synthesize-check-findings',\n 'record-approved-digest',\n 'release-locks',\n 'write-ship-report',\n 'checkpoint-worktrees',\n 'checkpoint',\n 'park-agents',\n 'schedule-wakeup',\n 'cancel-agents',\n 'freeze-worktrees',\n 'record-human-ack',\n 'record-skip',\n] as const;\nexport type TransitionEffectId = (typeof TRANSITION_EFFECT_IDS)[number];\n\n/** DESIGN 2.5.3 / spec 11.2: every stop reason the loop controller and `checkGlobalStops` may return, re-exported from `protocol` so a totality test never has to import both. */\nexport const ALL_STOP_REASONS = STOP_REASONS;\n","import type { Clock, RunId } from '@cohorte/base';\nimport type { StateStore } from '@cohorte/persistence/contract';\nimport { GUARD_IDS, type GuardId } from '../../contract/ids.ts';\nimport type { FactCollector } from '../../contract/ports.ts';\nimport type { GlobalFacts } from '../../contract/types.ts';\n\nexport interface FactCollectorDeps {\n readonly store: StateStore;\n readonly runId: RunId;\n readonly clock: Clock;\n /** Facts supplied by the host's concrete probes (git, sandbox, auth, billing and config). */\n readonly probes?: Readonly<Partial<Record<GuardId, boolean>>>;\n readonly processId?: { readonly uid?: number };\n}\n\nfunction counters(value: unknown): GlobalFacts['budgets']['run'] {\n return value && typeof value === 'object' ? (value as GlobalFacts['budgets']['run']) : {};\n}\n\n/**\n * Collects the durable and host facts needed by the transition table before a guard is evaluated.\n * Unknown facts deliberately remain false: a missing probe can never authorize a transition.\n */\nexport function createFactCollector(deps: FactCollectorDeps): FactCollector {\n return {\n async collect(ids: readonly GuardId[]): Promise<GlobalFacts> {\n const tree = await deps.store.readRunTree(deps.runId);\n const run = tree.run;\n const now = deps.clock.now();\n const nowMs = Date.parse(now);\n const facts: Record<string, unknown> = {\n cancelRequested: run.cancelRequested,\n pauseRequested: run.pauseRequested,\n leaseLost: false,\n pinMismatch: false,\n tableVersionKnown: run.tableVersion > 0,\n securityErrorPending: Boolean(run.lastError?.class === 'security'),\n deniedCallsByAgent: {},\n unexplainedWorktreeChange: false,\n blockingApprovalPending: tree.approvals.some((approval) => approval.status === 'pending'),\n authProbeMatchesExpected: false,\n quotaWindowExhausted: false,\n budgets: {\n run: counters(tree.budgets.find((budget) => budget.level === 'run')?.consumed),\n perPhase: counters(tree.budgets.find((budget) => budget.level === 'phase')?.consumed),\n },\n nowMs: Number.isFinite(nowMs) ? nowMs : 0,\n startedAtMs: Date.parse(run.startedAt) || 0,\n 'host.not-root': (deps.processId?.uid ?? (typeof process.getuid === 'function' ? process.getuid() : 1)) !== 0,\n 'host.outside-target': true,\n 'spec.schema-valid': run.specId.length > 0 && run.specSha256.length > 0,\n 'spec.frozen': run.specId.length > 0 && run.specSha256.length > 0,\n 'snapshot.captured': run.snapshotDigest !== undefined,\n 'runtime.pin-valid': run.runtimePin !== undefined,\n 'repo.base-resolved': run.baseSha !== undefined,\n 'agents.all-completed': tree.agents.every((agent) => agent.state === 'completed'),\n 'integration.merged': run.integrationHead !== undefined,\n 'locks.project+zones-held': tree.locks.some((lock) => lock.ownerRunId === deps.runId),\n 'budget.available': true,\n };\n\n for (const id of GUARD_IDS) {\n if (!(id in facts)) facts[id] = false;\n }\n for (const [id, value] of Object.entries(deps.probes ?? {})) facts[id] = value;\n\n // Preserve the requested set as a useful audit hint without changing the flat protocol shape.\n facts['collector.requested'] = ids;\n return facts as unknown as GlobalFacts;\n },\n };\n}\n","// DESIGN 2.5.1 — complete, fail-closed guard registry for the versioned transition tables.\n// External work is performed by FactCollector before this registry is called. An absent fact is never permission.\nimport { GUARD_IDS, type GuardId } from '../../contract/ids.ts';\nimport type { GlobalFacts, Guard, GuardContext } from '../../contract/types.ts';\n\nexport { createFactCollector, type FactCollectorDeps } from './facts.ts';\n\ntype FactBag = Record<string, unknown>;\nconst factsOf = (ctx: GuardContext): FactBag => ctx.facts as unknown as FactBag;\n\nfunction fact(ctx: GuardContext, id: GuardId): boolean | undefined {\n const value = factsOf(ctx)[id];\n return typeof value === 'boolean' ? value : undefined;\n}\n\nfunction outcome(id: GuardId, ok: boolean, detail?: string) {\n return { id, ok, ...(detail === undefined ? {} : { detail }) };\n}\n\nfunction factGuard(id: GuardId): Guard {\n return (ctx) => {\n const value = fact(ctx, id);\n return outcome(id, value === true, value === true ? undefined : `fact ${id} is absent or false`);\n };\n}\n\nfunction derived(id: GuardId, predicate: (ctx: GuardContext) => boolean, detail: string): Guard {\n return (ctx) => {\n const ok = predicate(ctx);\n return outcome(id, ok, ok ? undefined : detail);\n };\n}\n\nconst hasSpec = (ctx: GuardContext): boolean => ctx.run.run.specId.length > 0 && ctx.run.run.specSha256.length > 0;\n\n/** Guards with a local, deterministic derivation. All other guards consume a boolean fact and fail closed. */\nconst DERIVED: Partial<Record<GuardId, Guard>> = {\n 'input.is-idea': factGuard('input.is-idea'),\n 'phase.available': () => outcome('phase.available', false, 'BRAINSTORM/SPEC executors are not available in V3.0'),\n 'brainstorm.output-valid': factGuard('brainstorm.output-valid'),\n 'spec.schema-valid': derived('spec.schema-valid', hasSpec, 'run has no valid spec identity'),\n 'spec.frozen': derived('spec.frozen', hasSpec, 'run has no frozen spec identity'),\n 'snapshot.captured': derived(\n 'snapshot.captured',\n (ctx) => ctx.run.run.snapshotDigest !== undefined || fact(ctx, 'snapshot.captured') === true,\n 'run snapshot has not been captured',\n ),\n 'runtime.pin-valid': derived(\n 'runtime.pin-valid',\n (ctx) => ctx.run.run.runtimePin !== undefined || fact(ctx, 'runtime.pin-valid') === true,\n 'runtime pin is not available',\n ),\n 'repo.base-resolved': derived(\n 'repo.base-resolved',\n (ctx) => ctx.run.run.baseSha !== undefined || fact(ctx, 'repo.base-resolved') === true,\n 'repository base is not resolved',\n ),\n 'surfaces.all-owned': derived(\n 'surfaces.all-owned',\n (ctx) => fact(ctx, 'surfaces.all-owned') === true || ctx.run.worktrees.every((item) => item.slot.length > 0),\n 'one or more surfaces are not owned',\n ),\n 'budget.available': derived(\n 'budget.available',\n (ctx) => fact(ctx, 'budget.available') !== false,\n 'budget is unavailable or exhausted',\n ),\n 'agents.all-completed': derived(\n 'agents.all-completed',\n (ctx) => ctx.run.agents.every((agent) => agent.state === 'completed'),\n 'one or more agents are not completed',\n ),\n 'integration.merged': derived(\n 'integration.merged',\n (ctx) => ctx.run.run.integrationHead !== undefined || fact(ctx, 'integration.merged') === true,\n 'integration tree is not merged',\n ),\n 'approval.pending-blocking': (ctx) =>\n outcome('approval.pending-blocking', ctx.facts.blockingApprovalPending, 'no blocking approval is pending'),\n 'approval.none-pending-blocking': (ctx) =>\n outcome('approval.none-pending-blocking', !ctx.facts.blockingApprovalPending, 'a blocking approval is pending'),\n 'host.not-root': factGuard('host.not-root'),\n 'host.outside-target': factGuard('host.outside-target'),\n 'config.trust-satisfied': factGuard('config.trust-satisfied'),\n 'runtime.platform-supported': factGuard('runtime.platform-supported'),\n 'auth.plan-satisfied': factGuard('auth.plan-satisfied'),\n 'billing.consented': factGuard('billing.consented'),\n 'sandbox.meets-policy': factGuard('sandbox.meets-policy'),\n 'locks.project+zones-held': factGuard('locks.project+zones-held'),\n 'readiness.in': factGuard('readiness.in'),\n 'contract.present-or-exempt': factGuard('contract.present-or-exempt'),\n 'readiness.not-ready': factGuard('readiness.not-ready'),\n 'surfaces.unowned': factGuard('surfaces.unowned'),\n 'outputs.schema-valid': factGuard('outputs.schema-valid'),\n 'diff.within-ownership': factGuard('diff.within-ownership'),\n 'tree.digest-recorded': factGuard('tree.digest-recorded'),\n 'checks.all-passed': factGuard('checks.all-passed'),\n 'checks.digest-equals-integration': factGuard('checks.digest-equals-integration'),\n 'checks.failed-non-environmental': factGuard('checks.failed-non-environmental'),\n 'loop.may-continue': factGuard('loop.may-continue'),\n 'review.nothing-to-fix': factGuard('review.nothing-to-fix'),\n 'review.no-unreviewed': factGuard('review.no-unreviewed'),\n 'review.leftovers-parked-or-waived': factGuard('review.leftovers-parked-or-waived'),\n 'reviewref.digest-equals-integration': factGuard('reviewref.digest-equals-integration'),\n 'review.has-fix-items': factGuard('review.has-fix-items'),\n 'review.no-contract-change': factGuard('review.no-contract-change'),\n 'review.contract-change': factGuard('review.contract-change'),\n 'review.leftovers-routed-ask': factGuard('review.leftovers-routed-ask'),\n 'review.security-needs-investigation': factGuard('review.security-needs-investigation'),\n 'approval.ship-allowed': factGuard('approval.ship-allowed'),\n 'tree.digest-equals-approved': factGuard('tree.digest-equals-approved'),\n 'acceptance.no-open-human-items': factGuard('acceptance.no-open-human-items'),\n 'tree.digest-differs-from-approved': factGuard('tree.digest-differs-from-approved'),\n 'checks.errored-environmental': factGuard('checks.errored-environmental'),\n 'resume.locks-rebuilt': factGuard('resume.locks-rebuilt'),\n 'resume.git-verified': factGuard('resume.git-verified'),\n 'retry.target-legal': factGuard('retry.target-legal'),\n 'resume.acknowledged': factGuard('resume.acknowledged'),\n 'policy.skip-allows': factGuard('policy.skip-allows'),\n 'skip.justified': factGuard('skip.justified'),\n 'reviewtarget.resolved-to-sha': factGuard('reviewtarget.resolved-to-sha'),\n};\n\nexport const phaseAvailable = DERIVED['phase.available'] as Guard;\nconst completeGuards: Readonly<Record<GuardId, Guard>> = Object.freeze(\n Object.fromEntries(GUARD_IDS.map((id) => [id, DERIVED[id] ?? factGuard(id)])) as Record<GuardId, Guard>,\n);\n\nexport const V3_0_GUARDS: Readonly<Record<GuardId, Guard>> = completeGuards;\n\nexport function createPipelineGuards(deps: {\n factCollector: { collect(ids: readonly GuardId[]): Promise<GlobalFacts> };\n}) {\n return {\n get: (id: GuardId) => completeGuards[id],\n ids: () => GUARD_IDS,\n collectFacts: (ids: readonly GuardId[]) => deps.factCollector.collect(ids),\n };\n}\n","// DESIGN 4.2 / factories.ts's `Projection.evolve` — the PURE fold `RunState x DurableEnvelope -> RunState`, total\n// over `DurableEventType` (a `switch`, so every case narrows `envelope.payload` to its own row of the catalogue).\n//\n// DEVIATION (docs/v3/requests/U0.09.md): DESIGN 2.4 / ADR-0002 says stores are \"dumb\" and core writes projections\n// EXPLICITLY, in the SAME transaction as the events that justify them (\"no store contains a reducer\") — so this\n// fold is not how the live engine keeps `RunTreeRows` during a normal run; it is the SECONDARY reconstruction used\n// for verification / resume audits (and by `createProjection`'s `Projection.evolve`, `core/contract/factories.ts`,\n// which this module's `evolve` is shaped to match exactly: `(state, event) => RunState`, one event at a time).\n// Several event payloads do not, by design, carry every field their matching RECORD needs (`ApprovalRecord`'s\n// `idempotencyKey`/`grantKey`, `LockRecord`'s `ownerHostId`/`ownerPid`/`leaseExpiresAt`, none of them on the wire —\n// the store computes them at write time). Folding those is therefore an EXPLICIT no-op here rather than a\n// best-guess reconstruction that would silently diverge from the store's own projection; every other case updates\n// the same fields the store's own explicit writes would.\n//\n// TWO FIELDS ARE DELIBERATELY NOT RECONSTRUCTED: `run.version` and `run.lastHash`. Both are store-assigned per\n// TRANSACTION (`RunRecord`: \"store-assigned by `appendEvents`, like `lastHash` and `version`: a `putRun` / `patchRun`\n// never moves them\"), and `appendEvents` bumps `version` ONCE per CALL whatever the batch size — while DESIGN 4.2's\n// E5 and E8 transactions routinely append several events at once (`run.state.changed` + `phase.started`;\n// `phase.completed` + `checkpoint.created`). A per-EVENT fold cannot see a transaction boundary (`envelope.sub` is 0\n// for every durable event, protocol/envelope.ts), so advancing `version` here would make the reconstruction of any\n// multi-event transaction PERMANENTLY unequal to the stored record. They are therefore excluded from any\n// reconstruction comparison. `lastSequence` IS per-event and gapless, and `updatedAt` is the one clock field the\n// stream carries, so both are advanced.\n\nimport type { AgentRecord, PhaseRecord, WorktreeRecord } from '@cohorte/persistence/contract';\nimport type { DurableEventType, Envelope } from '@cohorte/protocol';\nimport type { RunState } from '../contract/types.ts';\n\ntype DurableEnvelope = Envelope<DurableEventType>;\n\nconst NODE_STATUS_BY_OUTCOME = {\n passed: 'completed',\n failed: 'failed',\n 'needs-human': 'waiting-approval',\n skipped: 'skipped',\n} as const;\n\nfunction currentPhaseRunId(state: RunState): PhaseRecord['phaseRunId'] | undefined {\n return state.phases.at(-1)?.phaseRunId;\n}\n\nfunction upsertPhase(\n state: RunState,\n phaseRunId: PhaseRecord['phaseRunId'],\n patch: (existing: PhaseRecord | undefined) => PhaseRecord,\n): RunState {\n const index = state.phases.findIndex((phase) => phase.phaseRunId === phaseRunId);\n const next = patch(index === -1 ? undefined : state.phases[index]);\n const phases = index === -1 ? [...state.phases, next] : state.phases.with(index, next);\n return { ...state, phases };\n}\n\nfunction upsertAgent(\n state: RunState,\n agentId: AgentRecord['agentId'],\n patch: (existing: AgentRecord) => AgentRecord,\n): RunState {\n const index = state.agents.findIndex((agent) => agent.agentId === agentId);\n const existing = index === -1 ? undefined : state.agents[index];\n if (!existing) return state; // declared elsewhere or out of order: nothing to patch (defensive, see file header)\n return { ...state, agents: state.agents.with(index, patch(existing)) };\n}\n\nfunction upsertWorktree(\n state: RunState,\n slot: string,\n patch: (existing: WorktreeRecord | undefined) => WorktreeRecord,\n): RunState {\n const index = state.worktrees.findIndex((worktree) => worktree.slot === slot);\n const next = patch(index === -1 ? undefined : state.worktrees[index]);\n const worktrees = index === -1 ? [...state.worktrees, next] : state.worktrees.with(index, next);\n return { ...state, worktrees };\n}\n\n/** `assertNever` doubles as the compile-time totality proof: adding a `DurableEventType` without a case here is a\n * type error at this call, not a silently-skipped runtime branch. */\nfunction assertNever(value: never): never {\n throw new TypeError(`evolve: unhandled durable event type ${JSON.stringify(value)}`);\n}\n\nexport function evolve(state: RunState, envelope: DurableEnvelope): RunState {\n // Every durable event advances the run's own bookkeeping, whatever else it does (DESIGN: the projection is\n // rebuilt \"transaction by transaction\" from the stream).\n const base: RunState = {\n ...state,\n run: { ...state.run, lastSequence: envelope.sequence, updatedAt: envelope.timestamp },\n };\n\n switch (envelope.type) {\n case 'pipeline.started': {\n const { payload } = envelope;\n return {\n ...base,\n run: {\n ...base.run,\n tableVersion: payload.tableVersion,\n specId: payload.spec.id,\n specSha256: payload.spec.sha256,\n snapshotDigest: payload.snapshotDigest,\n plan: payload.plan,\n baseBranch: payload.base.branch,\n baseSha: payload.base.sha,\n integrationBranch: payload.integrationBranch,\n cohorteVersion: payload.cohorteVersion,\n hostId: payload.hostId,\n },\n };\n }\n case 'run.state.changed': {\n const { payload } = envelope;\n // exactOptionalPropertyTypes: `resumeTo`/`stop` are optional keys, so an absent payload value CLEARS the\n // key (never assigns it `undefined`) — a resume back into an active state must drop the stale suspend info.\n const run: typeof base.run = { ...base.run, state: payload.to };\n if (payload.resumeTo !== undefined) run.resumeTo = payload.resumeTo;\n else delete run.resumeTo;\n if (payload.stop !== undefined) run.stop = payload.stop;\n else delete run.stop;\n return { ...base, run };\n }\n case 'run.paused':\n return { ...base, run: { ...base.run, pauseRequested: false } };\n case 'run.resumed':\n return base;\n case 'run.cancelled':\n return { ...base, run: { ...base.run, cancelRequested: false } };\n case 'run.host.attached': {\n const { payload } = envelope;\n return { ...base, run: { ...base.run, hostId: payload.hostId, hostPid: payload.pid } };\n }\n case 'run.host.detached': {\n const run: typeof base.run = { ...base.run };\n delete run.hostId;\n delete run.hostPid;\n delete run.hostStartToken;\n return { ...base, run };\n }\n case 'phase.started': {\n const { payload } = envelope;\n return upsertPhase(base, payload.phase.phaseRunId, () => ({\n runId: base.run.runId,\n phaseRunId: payload.phase.phaseRunId,\n state: payload.phase.state,\n iteration: payload.phase.iteration,\n status: 'running',\n checks: [],\n startedAt: envelope.timestamp,\n }));\n }\n case 'phase.completed': {\n const { payload } = envelope;\n return upsertPhase(base, payload.phase.phaseRunId, (existing) => {\n const record: PhaseRecord = {\n runId: base.run.runId,\n phaseRunId: payload.phase.phaseRunId,\n state: payload.phase.state,\n iteration: payload.phase.iteration,\n status: NODE_STATUS_BY_OUTCOME[payload.outcome],\n outcome: payload.outcome,\n checks: payload.checks,\n endedAt: envelope.timestamp,\n };\n if (existing?.startedAt !== undefined) record.startedAt = existing.startedAt;\n return record;\n });\n }\n case 'agent.declared': {\n const { payload } = envelope;\n const phaseRunId = currentPhaseRunId(base);\n if (!phaseRunId) return base; // no phase open yet: nothing this record can be attached to (see file header)\n const record: AgentRecord = {\n runId: base.run.runId,\n agentId: payload.agent.agentId,\n phaseRunId,\n role: payload.agent.role,\n label: payload.agent.role,\n state: 'declared',\n attempt: payload.agent.attempt,\n incarnation: payload.agent.incarnation,\n maxAttempts: 1,\n maxIncarnations: 5,\n model: payload.requestedModel,\n usage: {},\n createdAt: envelope.timestamp,\n updatedAt: envelope.timestamp,\n };\n if (payload.agent.surface !== undefined) record.surface = payload.agent.surface;\n return { ...base, agents: [...base.agents, record] };\n }\n case 'agent.spawned': {\n const { payload } = envelope;\n return upsertAgent(base, payload.agent.agentId, (agent) => {\n const next: AgentRecord = { ...agent, authMode: payload.authMode, updatedAt: envelope.timestamp };\n if (payload.worktree?.slot !== undefined) next.slot = payload.worktree.slot;\n if (payload.runtimeRef !== undefined) next.runtimeRef = payload.runtimeRef;\n return next;\n });\n }\n case 'agent.started':\n return base;\n case 'agent.state.changed': {\n const { payload } = envelope;\n return upsertAgent(base, payload.agent.agentId, (agent) => ({\n ...agent,\n state: payload.to,\n updatedAt: envelope.timestamp,\n }));\n }\n case 'agent.completed': {\n const { payload } = envelope;\n return upsertAgent(base, payload.agent.agentId, (agent) => ({\n ...agent,\n state: 'completed',\n summary: payload.summary,\n usage: payload.usage,\n updatedAt: envelope.timestamp,\n }));\n }\n case 'agent.failed': {\n const { payload } = envelope;\n return upsertAgent(base, payload.agent.agentId, (agent) => ({\n ...agent,\n lastError: payload.error,\n updatedAt: envelope.timestamp,\n }));\n }\n case 'agent.turn.completed':\n case 'agent.message.completed':\n case 'agent.message.accepted':\n case 'runtime.warning':\n case 'model.requested':\n case 'model.responded':\n case 'context.built':\n case 'escalation.applied':\n return base;\n case 'budget.updated': {\n const { payload } = envelope;\n const index = base.budgets.findIndex(\n (budget) => budget.level === payload.scope.level && budget.scopeId === payload.scope.id,\n );\n const record = {\n runId: base.run.runId,\n level: payload.scope.level,\n scopeId: payload.scope.id,\n consumed: payload.consumed,\n limit: payload.limit,\n updatedAt: envelope.timestamp,\n };\n const budgets = index === -1 ? [...base.budgets, record] : base.budgets.with(index, record);\n return { ...base, budgets };\n }\n case 'budget.exceeded':\n case 'quota.updated':\n case 'auth.required':\n case 'retry.scheduled':\n case 'command.accepted':\n case 'command.completed':\n case 'command.rejected':\n case 'tool.requested':\n case 'tool.denied':\n case 'tool.rejected':\n case 'tool.started':\n case 'tool.completed':\n case 'file.read':\n case 'file.written':\n case 'file.changed':\n case 'review.started':\n case 'review.finding':\n case 'review.completed':\n case 'review.approved':\n case 'approval.requested':\n case 'approval.resolved':\n case 'check.started':\n case 'check.completed':\n case 'checkpoint.created':\n case 'git.merge.completed':\n case 'git.merge.conflicted':\n case 'repo.change.detected':\n case 'lock.acquired':\n case 'lock.released':\n case 'lock.stolen':\n return base;\n case 'git.worktree.created': {\n const { payload } = envelope;\n return upsertWorktree(base, payload.slot, () => ({\n runId: base.run.runId,\n slot: payload.slot,\n path: payload.path,\n branch: payload.branch,\n baseSha: payload.baseSha,\n checkpointSha: payload.baseSha,\n state: 'intent',\n }));\n }\n case 'git.worktree.provisioned': {\n const { payload } = envelope;\n return upsertWorktree(base, payload.slot, (existing) =>\n existing\n ? { ...existing, lockfileSha256: payload.lockfileSha256, state: 'ready' }\n : {\n runId: base.run.runId,\n slot: payload.slot,\n path: '',\n baseSha: '',\n checkpointSha: '',\n lockfileSha256: payload.lockfileSha256,\n state: 'ready',\n },\n );\n }\n case 'git.worktree.quarantined': {\n const { payload } = envelope;\n return upsertWorktree(base, payload.slot, (existing) =>\n existing\n ? { ...existing, state: 'quarantined' }\n : {\n runId: base.run.runId,\n slot: payload.slot,\n path: '',\n baseSha: '',\n checkpointSha: '',\n state: 'quarantined',\n },\n );\n }\n case 'git.worktree.removed': {\n const { payload } = envelope;\n return upsertWorktree(base, payload.slot, (existing) =>\n existing\n ? { ...existing, state: 'removed' }\n : {\n runId: base.run.runId,\n slot: payload.slot,\n path: payload.path,\n baseSha: '',\n checkpointSha: '',\n state: 'removed',\n },\n );\n }\n case 'git.commit.created': {\n const { payload } = envelope;\n return upsertWorktree(base, payload.slot, (existing) =>\n existing\n ? { ...existing, checkpointSha: payload.sha, lastTreeDigest: payload.treeDigest }\n : {\n runId: base.run.runId,\n slot: payload.slot,\n path: '',\n branch: payload.branch,\n baseSha: payload.sha,\n checkpointSha: payload.sha,\n lastTreeDigest: payload.treeDigest,\n state: 'ready',\n },\n );\n }\n case 'pipeline.completed': {\n const { payload } = envelope;\n return { ...base, run: { ...base.run, stop: payload.stop, endedAt: envelope.timestamp } };\n }\n case 'pipeline.failed': {\n const { payload } = envelope;\n return {\n ...base,\n run: {\n ...base.run,\n state: payload.state,\n stop: payload.stop,\n lastError: payload.error,\n endedAt: envelope.timestamp,\n },\n };\n }\n case 'error':\n return { ...base, run: { ...base.run, lastError: envelope.payload.error } };\n default:\n return assertNever(envelope);\n }\n}\n","import type { ErrorInfo, Result, Sha256 } from '@cohorte/base';\nimport type { ExecRequest, Executor } from '@cohorte/security/contract';\nimport type { Provisioner } from '../contract/internal.ts';\n\nexport interface ProvisionImplementationDeps {\n executor: Executor;\n requestFor(slot: string): Promise<{ key: string; request: ExecRequest; manifestSha256: Sha256 }>;\n}\n\nexport function createProvisionerImpl(deps: ProvisionImplementationDeps): Provisioner {\n const markers = new Map<string, { key: string; manifestSha256: Sha256 }>();\n return {\n async ensure(slot) {\n const prepared = await deps.requestFor(slot);\n const previous = markers.get(slot);\n if (previous?.key === prepared.key && previous.manifestSha256 === prepared.manifestSha256) return 'reused';\n const result = await deps.executor.run(prepared.request, new AbortController().signal);\n if (result.outcome !== 'ok' || result.exitCode !== 0) throw new Error(`provision/command-failed: ${slot}`);\n markers.set(slot, { key: prepared.key, manifestSha256: prepared.manifestSha256 });\n return 'fresh';\n },\n\n async verifyDependencies(slot): Promise<Result<true, ErrorInfo>> {\n const prepared = await deps.requestFor(slot);\n const previous = markers.get(slot);\n if (!previous || previous.manifestSha256 !== prepared.manifestSha256) {\n return {\n ok: false,\n error: {\n code: 'security/deps-tampered',\n class: 'security',\n message: `dependency manifest changed for ${slot}`,\n impact: 'the worktree dependencies are not the pinned dependencies',\n remediation: 'run provisioning again before executing checks',\n retryable: false,\n },\n };\n }\n return { ok: true, value: true };\n },\n };\n}\n","// DESIGN 2.5.1 / 4.3 #1 — the `RunState` a fresh run starts from: the row `StoreTx.putRun` writes inside the same\n// transaction as the signed `start` command (`enqueueCommand` FIRST, `putRun` only on `'enqueued'`, persistence's\n// own contract comment), before `pipeline.started` (T04's guards) has run — the six `HOST_COMPUTED_RUN_KEYS` are\n// therefore absent, exactly as `STATES_WITHOUT_HOST_COLUMNS` requires for `IDLE`.\nimport type { IsoInstant, RunId, Sha256, SpecId } from '@cohorte/base';\nimport type { RunRecord } from '@cohorte/persistence/contract';\nimport type { RunState } from '../contract/types.ts';\n\nexport interface InitialRunStateInput {\n runId: RunId;\n profile: string;\n tableVersion: number;\n specId: SpecId;\n specSha256: Sha256;\n title: string;\n pinnedInstallDir: string;\n baseBranch: string;\n cohorteVersion: string;\n schemaVersion: number;\n startedAt: IsoInstant;\n}\n\nexport function initialRunState(input: InitialRunStateInput): RunState {\n const run: RunRecord = {\n runId: input.runId,\n profile: input.profile,\n tableVersion: input.tableVersion,\n specId: input.specId,\n specSha256: input.specSha256,\n title: input.title,\n state: 'IDLE',\n lastSequence: 0,\n lastHash: '',\n version: 0,\n pinnedInstallDir: input.pinnedInstallDir,\n baseBranch: input.baseBranch,\n cancelRequested: false,\n pauseRequested: false,\n schemaVersion: input.schemaVersion,\n cohorteVersion: input.cohorteVersion,\n purgeable: false,\n startedAt: input.startedAt,\n updatedAt: input.startedAt,\n };\n return { run, phases: [], agents: [], incarnations: [], worktrees: [], approvals: [], budgets: [], locks: [] };\n}\n","// DESIGN 4.4 step 4 / 6.2 / 6.3 / ADR-0023 — \"immutability inputs (pin, snapshot digest, table version; NO adopt\n// flag)\". Mismatch ⇒ stop `runtime-incompatible` ⇒ BLOCKED, `resumeRequires: reinstall-pinned-version`; there is\n// no override (ADR-0023 §3: \"no adopt/accept flag exists in V3.0\").\n//\n// DEVIATION (docs/v3/requests/U1.10.md, item D2): full re-verification needs a content-addressed re-hash of the\n// pinned install's `dist/**` and of the run's own snapshot manifest (`PinReader`/`RunSnapshotter.verify`, which\n// need a `RunSnapshotManifest` this port has no way to load without `PinReader` in `ResumeDeps`). The smallest\n// consistent reading implemented here: (a) the CURRENT host's own install directory must equal\n// `RunRecord.pinnedInstallDir` (`InstallInspector.installDir()`, already a frozen `core` port — no new package\n// edge), which is exactly what ADR-0023 §2 says resume must check before doing anything else (\"the detached host is\n// always spawned from that directory... after its hashes verify\"); (b) the run's `(profile, tableVersion)` must\n// resolve to a table this build ships (`resolveTable`, U0.09, pure). Both failures map to the SAME\n// `resumeRequires: reinstall-pinned-version` DESIGN names for a pin mismatch; a real build's `hashesVerify()` would\n// extend check (a) without changing this function's shape.\nimport type { RunRecord } from '@cohorte/persistence/contract';\nimport type { InstallInspector } from '../contract/ports.ts';\nimport { resolveTable } from '../pipeline/tables/index.ts';\n\nexport type ImmutabilityCheck = { ok: true } | { ok: false; reason: 'install-dir-mismatch' | 'table-not-shipped' };\n\n/** Synchronous: both halves read data already in hand (`InstallInspector.installDir()` is sync, `resolveTable` is\n * pure). It becomes asynchronous the day a real `PinReader`/`RunSnapshotter` re-hash joins it (D2). */\nexport function checkImmutability(run: RunRecord, installInspector: InstallInspector): ImmutabilityCheck {\n const installDir = installInspector.installDir();\n if (installDir !== run.pinnedInstallDir) return { ok: false, reason: 'install-dir-mismatch' };\n const resolved = resolveTable(run.profile, run.tableVersion);\n if (!resolved.ok) return { ok: false, reason: 'table-not-shipped' };\n return { ok: true };\n}\n","// DESIGN 4.4 step 10 / ADR-0025 item 6 — the reconciliation-note CONTENT: five situations, built AFTER steps 7-8 so\n// it describes the POST-recovery tree, never an instruction to re-issue (a fact, stated once, for the approved case:\n// \"was approved and has been executed\", never \"please re-issue it\").\n//\n// DEVIATION (docs/v3/requests/U1.10.md, item D5): `Continuation.note` (`@cohorte/runtime-contract`) is a `TaskInput`\n// — a CAS file reference (`{path, sha256, bytes}`), not inline text. Materialising the text this module builds into\n// that reference needs `RunFiles`/`BlobStore`, neither of which is in `ResumeDeps` (they belong to the run-files\n// area, a different unit). This module's public surface is therefore the note's PLAIN TEXT (and the structured\n// items it was built from, for `ResumeReport`); whoever spawns the continuation (`AgentSupervisor`, a later wave)\n// writes it to the CAS and wraps it as a `TaskInput`.\nimport type { AgentId, ApprovalId, EffectId, ToolCallId } from '@cohorte/base';\nimport type { EffectKind, ReplayClass } from '@cohorte/persistence/contract';\nimport type { ArtifactRef } from '@cohorte/protocol';\n\nexport type NoteItem =\n | { situation: 'not-executed'; toolCallId: ToolCallId; tool: string }\n | { situation: 'completed'; toolCallId: ToolCallId; tool: string; resultSummary: string }\n | {\n situation: 'compensated';\n effectId: EffectId;\n checkpointSha: string;\n patch: ArtifactRef;\n }\n | { situation: 'in-doubt'; effectId: EffectId; kind: EffectKind; replayClass: ReplayClass }\n | {\n situation: 'approved';\n approvalId: ApprovalId;\n toolCallId: ToolCallId;\n tool: string;\n outcome: 'executed' | 'binding-changed' | 'denied-by-gate';\n resultSummary?: string;\n };\n\nexport interface ReconciliationNoteInput {\n agentId: AgentId;\n fromIncarnation: number;\n items: readonly NoteItem[];\n}\n\nfunction lineFor(item: NoteItem): string {\n switch (item.situation) {\n case 'not-executed':\n return `- your call \"${item.tool}\" (${item.toolCallId}) was requested but never ran: the host restarted before a decision was made. It was not executed.`;\n case 'completed':\n return `- your call \"${item.tool}\" (${item.toolCallId}) completed before the restart; its result is kept: ${item.resultSummary}`;\n case 'compensated':\n return `- uncommitted work in progress since checkpoint ${item.checkpointSha} was discarded (the workspace state after the restart could not be explained); it was saved as artifact ${item.patch.artifactId} before discarding, in case you need to inspect it.`;\n case 'in-doubt':\n return `- an effect of kind \"${item.kind}\" (${item.effectId}, replay class ${item.replayClass}) was started but its outcome is unknown after the restart. Do not assume it ran; do not assume it did not run. It will not be re-issued automatically.`;\n case 'approved': {\n if (item.outcome === 'executed') {\n return `- your call \"${item.tool}\" (${item.toolCallId}), approved while you were gone, was approved and has been executed; result: ${item.resultSummary ?? '(no result recorded)'}.`;\n }\n if (item.outcome === 'binding-changed') {\n return `- your call \"${item.tool}\" (${item.toolCallId}) was approved but NOT executed: the workspace changed since you asked. Request it again if you still need it.`;\n }\n return `- your call \"${item.tool}\" (${item.toolCallId}) was denied: the approval no longer applies.`;\n }\n default: {\n const _exhaustive: never = item;\n throw new TypeError(`buildReconciliationNote: unhandled situation ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n\n/** Builds the note's plain text (D5). Never phrased as an instruction to re-issue anything: every line states a\n * fact about what the post-recovery tree already contains. */\nexport function buildReconciliationNoteText(input: ReconciliationNoteInput): string {\n const header = `[cohorte] recovery note (incarnation ${input.fromIncarnation + 1}, continuing the same attempt)\\n\\nThe host restarted while you were running. Here is what changed:`;\n if (input.items.length === 0) return `${header}\\n- nothing of yours was in flight; continue where you left off.`;\n return [header, ...input.items.map(lineFor)].join('\\n');\n}\n","// @cohorte/core/resume — PLAN U1.10: DESIGN 4.4's 11-step recovery procedure, replay-class reconciliation (4.1),\n// the reconciliation note (4.4 step 10 / ADR-0025 item 6), over PORTS only. Wave-0 seam (PLAN U0.08) replaced: this\n// file is now the implementation (see `../events/index.ts` for the convention this follows).\n//\n// `ResumeDeps` is WIDENED beyond `contract/factories.ts`'s frozen stub (owned by U0.08, not this unit's to edit —\n// PLAN §3 rule 7: \"a unit that believes a contract is wrong ... continues against a local adapter\"). The five\n// original fields (`store`, `clock`, `sweeper`, `effectVerifiers`, `worktrees`) are unchanged; four are ADDED, each\n// an EXISTING frozen port (no new contract, no new package edge — `events`/`toolHostReplay` already live in\n// `contract/internal.ts`, `installInspector` in `contract/ports.ts`, `redactor` is re-exported from `@cohorte/base`\n// by `contract/ports.ts` already): `events` (write `run.resumed`, `lock.stolen`, `agent.state.changed`,\n// `approval.resolved`, `repo.change.detected` — none of DESIGN 4.4's writes are optional), `redactor` (seal the\n// synthetic reconciliation result `completeEffect` needs, DESIGN 0.2 I7), `toolHostReplay` (DESIGN 4.5's host-side\n// replay of an approved call whose requester died), `installInspector` (DESIGN 4.4 step 4's immutability check) and\n// `ids` (the `ApprovalId` of the `blocked-ack` approvals steps 6 and 11 open).\n// Reasoning, and the ports this genuinely could not be built from, are in `docs/v3/requests/U1.10.md`.\nimport {\n type ApprovalId,\n CohorteError,\n type CommandId,\n type EffectId,\n errorOf,\n type JsonValue,\n type RunId,\n} from '@cohorte/base';\nimport type {\n ApprovalRecord,\n EffectRecord,\n LeaseToken,\n LockRecord,\n LockRequest,\n RunRecord,\n StateStore,\n} from '@cohorte/persistence/contract';\nimport { ACTIVE_PIPELINE_STATES, type ArtifactRef, type ResumeReport } from '@cohorte/protocol';\nimport type { RuntimeToolCall } from '@cohorte/runtime-contract';\nimport { reincarnate } from '../agents/lifecycle.ts';\nimport type { ResumeDeps } from '../contract/factories.ts';\nimport type { Resumer } from '../contract/internal.ts';\nimport type { EffectVerifierRegistry } from '../contract/ports.ts';\nimport type { HostContext } from '../contract/types.ts';\nimport { evolve } from '../state/evolve.ts';\nimport { initialRunState } from '../state/initial-run-state.ts';\nimport { checkImmutability } from './immutability.ts';\nimport { buildReconciliationNoteText, type NoteItem } from './note.ts';\nimport type { ReExecutionLog } from './verifiers.ts';\n\nexport { checkImmutability } from './immutability.ts';\nexport { buildReconciliationNoteText, type NoteItem, type ReconciliationNoteInput } from './note.ts';\nexport {\n type BuiltinEffectVerifiers,\n type BuiltinVerifierDeps,\n createBuiltinEffectVerifiers,\n type ReExecutionLog,\n} from './verifiers.ts';\n\n// The FROZEN contract of `contract/factories.ts`, re-exported — never a second interface of the same name (the\n// convention `packages/core/src/events/index.ts` set for `EventsDeps`). The five fields this area needed on top of\n// the original five were WIDENED where the type lives, at gate G1; until then they were declared here and the\n// barrel published a `createResumer` whose parameter no exported type described. `ids` mints the `ApprovalId` of the\n// `blocked-ack` approvals DESIGN 4.4 steps 6 and 11 open (`ApprovalService` is deliberately not in this port set: it\n// would drag the whole approval area in for one `putApproval`).\nexport type { ResumeDeps };\n\nconst LEASE_TTL_MS = 15_000;\n\n/** DESIGN 2.5.4: the FOUR legal reincarnation sources — `spawning | running | waiting | paused -> spawning`. After a\n * host death no child of this run survives, so every agent in one of these states must continue in a new\n * incarnation of the SAME attempt, whether or not an `incarnations` row recorded a pid we could sweep (a `waiting`\n * agent parked on an approval is the canonical case: its brain is gone and its approved call has to be replayed).\n * `declared` / `planned` have no runtime session yet and `failed` / `retrying` / `escalated` already counted their\n * attempt — `reincarnate()` refuses all five — and `completed` / `cancelled` are terminal (4.4 step 11). */\nconst RECOVERABLE_AGENT_STATES: ReadonlySet<string> = new Set(['spawning', 'running', 'waiting', 'paused']);\n\n/** `IncarnationRecord.state` is open (owned by the supervisor): everything that is not one of these three may still\n * have a live OS process behind it, so the sweep looks at all of them (DESIGN 4.4 step 5). */\nconst TERMINAL_INCARNATION_STATES: ReadonlySet<string> = new Set(['completed', 'cancelled', 'failed']);\n\n/** A pending command that must win over the rest of recovery (DESIGN 4.4 step 9: \"a `cancel` recorded while the\n * host was dead wins here\"): nothing is reincarnated and no approved call is replayed under one. */\nconst HALTING_COMMAND_TYPES: ReadonlySet<string> = new Set(['cancel', 'shutdown']);\n\n/** The run states under which step 10 may CONTINUE the work (reincarnate an agent, replay its approved calls): the\n * table's own active phases, plus `IDLE` (a run whose host died between `putRun` and the first transition — crash\n * point #1 — has no agent to continue anyway). Everything else is handled by `haltingRunState` below. */\nconst CONTINUABLE_RUN_STATES: ReadonlySet<string> = new Set<string>([...ACTIVE_PIPELINE_STATES, 'IDLE']);\n\n/** DESIGN 4.4 step 11: \"`PAUSED`, `WAITING_APPROVAL`, `AUTH_REQUIRED`, `QUOTA_EXCEEDED` stay what they are:\n * recovery never silently un-suspends.\" Reincarnating a parked agent and replaying its approved call (4.5) IS\n * continuing the work — a `paused` agent that comes back `spawning` and executes its approved `run_command` has\n * un-suspended the run in everything but the `runs.state` column — so step 10 reads the RUN's state, not only the\n * agent's. The four suspended states, the two halted ones (`FAILED`, `BLOCKED`: only a human `retry` / `resume\n * --ack` moves them, T31 / T32) and the two terminal ones therefore stop step 10; steps 1-9 still run, so the\n * journal, the locks and the worktrees are reconciled and the report says why the work was not continued.\n *\n * `WAITING_APPROVAL` is the one state with a condition: DESIGN 2.5.3 resumes it \"by `approve` / `deny`\", and\n * ADR-0025 item 6's parked path exists precisely to replay a call whose ask was answered while no host was alive.\n * So it continues once no BLOCKING approval is pending any more (`listPendingApprovals` after step 9's expiry\n * pass) — and an answered ask lets the 4.5 replay happen, which is the whole point of that path. */\nfunction haltingRunState(state: string, pendingApprovals: number): string | undefined {\n if (state === 'WAITING_APPROVAL') {\n return pendingApprovals > 0\n ? `the run is WAITING_APPROVAL and ${pendingApprovals} approval(s) are still pending`\n : undefined;\n }\n if (CONTINUABLE_RUN_STATES.has(state)) return undefined;\n if (state === 'FAILED' || state === 'BLOCKED') {\n return `the run is ${state}: only a human command (\\`retry\\` / \\`resume --ack\\`) continues it`;\n }\n if (state === 'COMPLETED' || state === 'CANCELLED') return `the run is ${state}`;\n return `the run is ${state}: recovery never silently un-suspends (DESIGN 4.4 step 11)`;\n}\n\n/** DESIGN 4.4 step 8's second bullet — \"unexplained, and the slot has a COMMAND effect that is `in-doubt` or\n * `failed(interrupted)`\" (ADR-0025 item 2 repeats it word for word) — is the ONLY case in which recovery answers an\n * unexplained worktree change by quarantining and resetting the slot. Every other unexplained change falls into the\n * third bullet: `repo.change.detected` ⇒ stop `unexpected-repo-change` ⇒ BLOCKED. The distinction is load-bearing:\n * a reset discards the agent's uncommitted work, and ADR-0025 item 3's checkpoint cadence (\"immediately before any\n * `at-most-once` command executes — so a reset after an in-doubt command loses nothing but that command's own\n * writes\") only bounds that loss for a COMMAND.\n *\n * `tool.run_command` is DESIGN 4.1's only agent-command kind in V3.0. `check.command` (the TEST sequence, always in\n * `_integration`, which 2.5.2 resets after every sequence) and `provision.command` are deliberately NOT here: they\n * are not an agent's slot work, and widening this set is a DESIGN decision, filed as item D11 of\n * `docs/v3/requests/U1.10.md`. */\nconst COMMAND_EFFECT_KINDS: ReadonlySet<string> = new Set(['tool.run_command']);\n\n/** DESIGN 4.4 step 2's second half: fold the event stream through `evolve` from the run's own creation-time fields\n * (immutable, so a valid `initialRunState` seed) and compare with the STORED projection. A mismatch anywhere the\n * store did not already refuse to open (`verifyChain`) is `corruption/projection-mismatch`: the two most likely\n * causes are a hand-edited `runs` row or a bug in a caller's transaction, and DESIGN says \"nothing is modified\"\n * either way. */\nexport async function verifyProjectionAgainstEvents(store: StateStore, run: RunRecord): Promise<void> {\n let folded = initialRunState({\n runId: run.runId,\n profile: run.profile,\n tableVersion: run.tableVersion,\n specId: run.specId,\n specSha256: run.specSha256,\n title: run.title,\n pinnedInstallDir: run.pinnedInstallDir,\n baseBranch: run.baseBranch,\n cohorteVersion: run.cohorteVersion,\n schemaVersion: run.schemaVersion,\n startedAt: run.startedAt,\n });\n const PAGE = 500;\n let after = 0;\n for (;;) {\n const page = await store.readEvents(run.runId, { afterSequence: after, limit: PAGE });\n if (page.length === 0) break;\n for (const envelope of page) folded = evolve(folded, envelope);\n after = (page.at(-1) as (typeof page)[number]).sequence;\n if (page.length < PAGE) break;\n }\n // `run.version` is NOT compared: it counts store TRANSACTIONS (`StoreTx.appendEvents` bumps it once per CALL,\n // `packages/persistence/src/memory/state-store.ts`), not events, and `evolve()` deliberately never touches it\n // (`packages/core/src/state/evolve.ts`'s own `base` object) — two events written in one transaction and two\n // written across two both replay to the same STATE but a different transaction count, so it is not a projection\n // fold could ever reconstruct. `lastSequence` and `state` are what DESIGN 4.4 step 2 means by \"compare with the\n // runs projection\".\n const same = folded.run.lastSequence === run.lastSequence && folded.run.state === run.state;\n if (!same) {\n throw new CohorteError(\n errorOf(\n 'corruption/projection-mismatch',\n `run ${run.runId}: replaying events yields ${folded.run.state}@seq${folded.run.lastSequence}, the stored projection is ${run.state}@seq${run.lastSequence}`,\n ),\n );\n }\n}\n\n/** DESIGN 4.4 step 3. Live owner (fresh heartbeat AND the process is actually alive) ⇒ refuse. Dead owner ⇒ steal\n * with `fencingToken + 1`. No existing lock ⇒ this is the first host: acquire fresh (`takeover: false`). */\nasync function acquireOrStealRunLease(\n deps: ResumeDeps,\n runId: RunId,\n host: HostContext,\n): Promise<{ lease: LeaseToken; takeover: boolean }> {\n const owner = { runId, hostId: host.hostId, pid: host.pid, startToken: host.startToken };\n const runLocks = await deps.store.listLocks({ scope: 'run' });\n const existing: LockRecord | undefined = runLocks.find((lock) => lock.key === runId);\n if (existing) {\n if (deps.sweeper.isAlive(existing.ownerPid, existing.ownerStartToken)) {\n throw new CohorteError(\n errorOf(\n 'conflict/run-host-alive',\n `run ${runId} is already driven by host ${existing.ownerHostId} (pid ${existing.ownerPid})`,\n ),\n );\n }\n const req: LockRequest = { scope: 'run', key: runId, mode: 'exclusive', owner, ttlMs: LEASE_TTL_MS };\n const lease = await deps.store.stealLock(req, existing);\n return { lease, takeover: true };\n }\n const req: LockRequest = { scope: 'run', key: runId, mode: 'exclusive', owner, ttlMs: LEASE_TTL_MS };\n const acquired = await deps.store.acquireLock(req);\n if (!acquired.ok) {\n throw new CohorteError(errorOf('conflict/run-host-alive', `run ${runId}: the run lock is held by another host`));\n }\n return { lease: acquired.lease, takeover: false };\n}\n\n/** The `ApprovalRequest`-shaped JSON an `ApprovalRecord.request` carries (DESIGN 2.3.3): only the two fields this\n * module reads back out of it. `toolCallId`/`ordinal` (`tc_<incarnation>_<ordinal>`, `RuntimeToolCall`'s own\n * comment, `@cohorte/runtime-contract`) is parsed from the id itself: neither `ApprovalRecord` nor the stored\n * request repeats the ordinal as its own field. */\nfunction ordinalFromToolCallId(id: string): number {\n const last = id.split('_').at(-1);\n const parsed = last === undefined ? Number.NaN : Number(last);\n return Number.isInteger(parsed) && parsed >= 1 ? parsed : 1;\n}\n\nfunction approvedCallOf(runId: RunId, approval: ApprovalRecord): RuntimeToolCall | undefined {\n if (!approval.agentId || approval.incarnation === undefined || !approval.toolCallId) return undefined;\n const request = approval.request as unknown as { tool?: string; args?: JsonValue };\n if (typeof request.tool !== 'string') return undefined;\n return {\n runId,\n agentId: approval.agentId,\n incarnation: approval.incarnation,\n toolCallId: approval.toolCallId,\n ordinal: ordinalFromToolCallId(approval.toolCallId),\n tool: request.tool,\n input: request.args ?? {},\n };\n}\n\ninterface EffectDecision {\n effect: EffectRecord;\n action: 'done' | 'fail' | 'in-doubt';\n}\n\n/** A registry MAY also report which effects its own probe re-executed (`createBuiltinEffectVerifiers` does, for\n * `provision.command`, whose probe IS `Provisioner.ensure`). The frozen `EffectVerifierRegistry` has no such member,\n * so it is read by narrowing; a registry without it simply yields `'done'` verdicts, never `'re-executed'`. */\nfunction reExecutionLogOf(registry: EffectVerifierRegistry): ReExecutionLog | undefined {\n const candidate = registry as Partial<ReExecutionLog>;\n return typeof candidate.reExecuted === 'function' ? (candidate as ReExecutionLog) : undefined;\n}\n\n/** DESIGN 4.4 steps 6 and 11 both need a human acknowledgement before the run may go on, and this port set has no\n * `ApprovalService`: the record and its `approval.requested` event are written directly, in ONE transaction, with\n * the event's own sequence as `requestedSeq`. `idempotencyKey` is derived from the run and the situation, so a\n * second recovery that finds the same situation reuses the approval instead of opening a duplicate. */\ninterface BlockedAckDraft {\n idempotencyKey: string;\n ruleId: string;\n reason: string;\n previewText: string;\n affectedPaths: readonly string[];\n}\n\nasync function openBlockedAckApproval(\n deps: ResumeDeps,\n runId: RunId,\n lease: LeaseToken,\n draft: BlockedAckDraft,\n): Promise<ApprovalId> {\n const approvalId = deps.ids.next<'ApprovalId'>('apr');\n const request = {\n approvalId,\n kind: 'blocked-ack' as const,\n affectedPaths: [...draft.affectedPaths],\n preview: { kind: 'text' as const, text: draft.previewText },\n ruleId: draft.ruleId,\n reason: draft.reason,\n asks: [{ stage: 'resume', ruleId: draft.ruleId, reason: draft.reason }],\n allowedDecisions: ['allow-once' as const, 'deny' as const],\n unattended: 'wait' as const,\n cli: `cohorte approve ${approvalId}`,\n };\n await deps.store.transact({ runId }, lease, (tx) => {\n const appended = deps.events.append(tx, [\n {\n type: 'approval.requested',\n payload: request as unknown as JsonValue,\n summary: draft.reason,\n severity: 'warning',\n },\n ]);\n const event = appended.at(0);\n if (!event) throw new TypeError('resume: approval.requested produced no envelope');\n tx.putApproval({\n approvalId,\n runId,\n idempotencyKey: draft.idempotencyKey,\n kind: 'blocked-ack',\n status: 'pending',\n request: deps.redactor.sealJson(request as unknown as JsonValue).value,\n grantKey: draft.idempotencyKey,\n requestedSeq: event.sequence,\n createdAt: deps.clock.now(),\n });\n });\n return approvalId;\n}\n\n/** DESIGN 4.1 / 4.4 step 7: decide every open (`intent` | `in-doubt`) effect by replay class, calling each kind's\n * verifier (never a blind re-execution). `at-most-once` skips the verifier entirely (DESIGN 4.1's own table: \"never\n * re-executed\" — there is nothing to probe for, only to surface). */\nasync function decideOpenEffects(deps: ResumeDeps, runId: RunId, signal: AbortSignal): Promise<EffectDecision[]> {\n const intents = await deps.store.listEffects(runId, { states: ['intent'] });\n const inDoubtAlready = await deps.store.listEffects(runId, { states: ['in-doubt'] });\n const open = [...intents, ...inDoubtAlready];\n const decisions: EffectDecision[] = [];\n for (const effect of open) {\n if (effect.replayClass === 'at-most-once') {\n decisions.push({ effect, action: 'in-doubt' });\n continue;\n }\n const verifier = deps.effectVerifiers.get(effect.kind);\n if (!verifier) {\n decisions.push({ effect, action: 'in-doubt' });\n continue;\n }\n const verdict = await verifier.verify(effect, signal);\n if (verdict === 'done') decisions.push({ effect, action: 'done' });\n else if (verdict === 'not-done') decisions.push({ effect, action: 'fail' });\n else decisions.push({ effect, action: 'in-doubt' });\n }\n return decisions;\n}\n\nexport function createResumer(deps: ResumeDeps): Resumer {\n return {\n async recover(runId: RunId, host: HostContext): Promise<ResumeReport> {\n // Step 1 — migration CHECK only, never automatic.\n const migration = await deps.store.migrate('check');\n if (migration.pending.length > 0) {\n throw new CohorteError(\n errorOf(\n 'configuration/incompatible-state-schema',\n `run ${runId}: the state database is at schema ${migration.current}, this build expects ${migration.target}; run \\`cohorte migrate --apply\\``,\n ),\n );\n }\n\n // Step 2 — verifyChain, then replay-vs-projection.\n const chain = await deps.store.verifyChain(runId);\n if (!chain.ok) {\n if (chain.reason === 'gap' || chain.reason === 'duplicate') {\n throw new CohorteError(\n errorOf(\n 'corruption/event-gap',\n `run ${runId}: event sequence has a ${chain.reason} at ${chain.firstBadSequence}`,\n ),\n );\n }\n throw new CohorteError(\n errorOf(\n 'security/event-chain-broken',\n `run ${runId}: event chain fails its ${chain.reason} check at ${chain.firstBadSequence}`,\n ),\n );\n }\n const run = await deps.store.getRun(runId);\n if (!run) throw new CohorteError(errorOf('validation/invalid-id', `resume: run ${runId} does not exist`));\n await verifyProjectionAgainstEvents(deps.store, run);\n\n // Step 4 — immutability, BEFORE taking the lease over: ADR-0023 \"no adopt flag\", so a pin mismatch must never\n // let this host start acting as the run's owner.\n const immutability = checkImmutability(run, deps.installInspector);\n if (!immutability.ok) {\n const why =\n immutability.reason === 'install-dir-mismatch'\n ? `pinned install ${run.pinnedInstallDir} is not this host's install (${deps.installInspector.installDir()})`\n : `table version ${run.tableVersion} of profile ${run.profile} is not shipped by this build`;\n throw new CohorteError(\n errorOf('security/runtime-pin-mismatch', `run ${runId}: ${why}`, {\n details: { resumeRequires: 'reinstall-pinned-version' },\n }),\n );\n }\n\n // Step 3 — lease.\n const { lease, takeover } = await acquireOrStealRunLease(deps, runId, host);\n const fencingToken = lease.fencingToken;\n if (takeover) {\n await deps.store.transact({ runId }, lease, (tx) => {\n deps.events.append(tx, [\n {\n type: 'lock.stolen',\n payload: { scope: 'run', key: runId, mode: 'exclusive', owner: host.hostId, fencingToken },\n summary: `host ${host.hostId} took over run ${runId} (fencing token ${fencingToken})`,\n severity: 'warning',\n },\n ]);\n });\n }\n\n const tree = await deps.store.readRunTree(runId);\n\n // Step 5 — orphan sweep. Agent incarnations by (pid, startToken) — see docs/v3/requests/U1.10.md item D7 for\n // the executor process-group half (runs/<id>/pids/*.json) this port set cannot reach.\n const orphans: ResumeReport['orphans'] = [];\n for (const incarnation of tree.incarnations) {\n if (incarnation.pid === undefined || incarnation.startToken === undefined) continue;\n if (TERMINAL_INCARNATION_STATES.has(incarnation.state)) continue;\n if (deps.sweeper.isAlive(incarnation.pid, incarnation.startToken)) continue;\n // `killed` is a FACT the report states about a stray brain: a rejected `kill` (permission, race with the\n // process's own exit, a sweeper that cannot signal) must not be reported as a successful kill.\n const killed = await deps.sweeper.kill(incarnation.pid, incarnation.startToken).then(\n () => true,\n () => false,\n );\n orphans.push({\n agentId: incarnation.agentId,\n incarnation: incarnation.incarnation,\n pid: incarnation.pid,\n kind: 'brain',\n killed,\n });\n }\n\n // Step 6 — rebuild locks: project (shared) + declared zones + integration + slots. \"Rebuild\" is not \"acquire\n // if free\": a lock row still held by THIS run's own dead host is exactly what recovery is here to take back,\n // and `acquireLock` refuses it however stale the lease is (the store never evicts — `StateStore.acquireLock`).\n // So a refusal whose holders are all this run's, all dead, is taken over with `stealLock` (fencing+1), the\n // same way step 3 takes the run lease. Only a holder that is ANOTHER run — or one that is alive — is a\n // conflict, which is DESIGN 4.4 step 6's own wording (\"a zone now held by another run\").\n const rebuilt: string[] = [`run:${runId}`];\n const conflicts: string[] = [];\n const owner = { runId, hostId: host.hostId, pid: host.pid, startToken: host.startToken };\n const rebuildLock = async (label: string, req: LockRequest): Promise<void> => {\n const acquired = await deps.store.acquireLock(req);\n if (acquired.ok) {\n rebuilt.push(label);\n return;\n }\n const reclaimable =\n acquired.heldBy.length === 1 &&\n acquired.heldBy.every(\n (held) => held.ownerRunId === runId && !deps.sweeper.isAlive(held.ownerPid, held.ownerStartToken),\n );\n const stale = acquired.heldBy.at(0);\n if (reclaimable && stale) {\n await deps.store.stealLock(req, stale);\n rebuilt.push(label);\n return;\n }\n conflicts.push(label);\n };\n await rebuildLock('project', { scope: 'project', key: 'project', mode: 'shared', owner, ttlMs: LEASE_TTL_MS });\n for (const zone of run.zones ?? []) {\n await rebuildLock(`zone:${zone}`, {\n scope: 'zone',\n key: zone,\n mode: 'exclusive',\n owner,\n ttlMs: LEASE_TTL_MS,\n zones: [zone],\n });\n }\n await rebuildLock(`integration:${runId}`, {\n scope: 'integration',\n key: runId,\n mode: 'exclusive',\n owner,\n ttlMs: LEASE_TTL_MS,\n });\n for (const worktree of tree.worktrees) {\n await rebuildLock(`slot:${worktree.slot}`, {\n scope: 'slot',\n key: `${runId}:${worktree.slot}`,\n mode: 'exclusive',\n owner,\n ttlMs: LEASE_TTL_MS,\n });\n }\n\n // Step 7 — reconcile intent effects FIRST, by replay class, before any worktree comparison (DESIGN 4.4).\n const decisions = await decideOpenEffects(deps, runId, host.signal);\n const reExecutionLog = reExecutionLogOf(deps.effectVerifiers);\n const effectReports: ResumeReport['effects'] = [];\n const inDoubtIds: EffectId[] = [];\n await deps.store.transact({ runId }, lease, (tx) => {\n for (const { effect, action } of decisions) {\n if (action === 'done') {\n tx.completeEffect(\n effect.effectId,\n deps.redactor.sealJson({ reconciledBy: 'resume', at: deps.clock.now() }).value,\n );\n // `'re-executed'` is reported only when the VERIFIER itself redid the work while probing (DESIGN 4.1's\n // `provision.command` row: `Provisioner.ensure` re-provisions when the marker is missing). Everything\n // else that verified `done` was found already applied in the world.\n const verdict: (typeof effectReports)[number]['verdict'] = reExecutionLog?.reExecuted(effect.effectId)\n ? 're-executed'\n : 'done';\n effectReports.push({\n effectId: effect.effectId,\n kind: effect.kind,\n replayClass: effect.replayClass,\n verdict,\n });\n } else if (action === 'fail') {\n tx.failEffect(\n effect.effectId,\n errorOf(\n 'tool-transient/interrupted',\n `effect ${effect.idempotencyKey} (${effect.kind}) was interrupted by a host restart`,\n ),\n );\n effectReports.push({\n effectId: effect.effectId,\n kind: effect.kind,\n replayClass: effect.replayClass,\n verdict: 'failed',\n });\n } else {\n tx.markEffectInDoubt(\n effect.effectId,\n `resume: ${effect.kind} could not be proven done or not-done after a host restart`,\n );\n effectReports.push({\n effectId: effect.effectId,\n kind: effect.kind,\n replayClass: effect.replayClass,\n verdict: 'in-doubt',\n });\n inDoubtIds.push(effect.effectId);\n }\n }\n });\n\n // Step 8 — git verification via the ledger audit (DESIGN 5.2/5.8, spec 11.3): `WorktreeService.audit` already\n // computes the exact verdict enum DESIGN 4.4 step 8 and `ResumeReport.worktrees[].verdict` share.\n const worktreeReports: ResumeReport['worktrees'] = [];\n const unexplained: string[] = [];\n /** per quarantined slot: the effect that explained the change and the patch artifact the reset saved — the\n * `compensated` line of the reconciliation note (DESIGN 4.4 step 10) is built from it. */\n const compensatedSlots = new Map<string, { because: EffectId; patch: ArtifactRef; checkpointSha: string }>();\n for (const worktree of tree.worktrees) {\n const audit = await deps.worktrees.audit(worktree.slot);\n let verdict = audit.verdict;\n if (verdict === 'unexplained-change') {\n // `COMMAND_EFFECT_KINDS` + `action !== 'done'` IS DESIGN 4.4 step 8's second bullet, literally: \"a command\n // effect that is `in-doubt` or `failed(interrupted)`\". An open `git.*` / `agent.spawn` / `provision.*`\n // effect explains nothing about bytes in the worktree and must NOT buy a reset of the agent's work.\n const explaining = decisions.find(\n (d) => d.effect.slot === worktree.slot && COMMAND_EFFECT_KINDS.has(d.effect.kind) && d.action !== 'done',\n );\n if (explaining) {\n // `WorktreeService.quarantineAndReset` performs the journaled reset AND compensates the slot's effects\n // in its own transaction (DESIGN 4.4 step 8 / ADR-0025 item 2) — this caller only reports the outcome.\n const patch = await deps.worktrees.quarantineAndReset(worktree.slot, explaining.effect.effectId);\n verdict = 'quarantined-reset';\n compensatedSlots.set(worktree.slot, {\n because: explaining.effect.effectId,\n patch,\n checkpointSha: worktree.checkpointSha,\n });\n } else {\n unexplained.push(worktree.slot);\n }\n }\n worktreeReports.push({ slot: worktree.slot, path: worktree.path, verdict });\n }\n // ADR-0025 item 2 / DESIGN 4.4 step 8: the quarantine transaction marks every effect of the slot after the\n // checkpoint `compensated`. The report says so too — step 7 had only just given those effects their\n // `in-doubt` / `failed` verdict, and a quarantined worktree with no compensated effect anywhere would be a\n // report that contradicts the journal it describes.\n if (compensatedSlots.size > 0) {\n const slotOf = new Map(decisions.map((d) => [d.effect.effectId, d.effect.slot]));\n for (const [index, entry] of effectReports.entries()) {\n const slot = slotOf.get(entry.effectId);\n if (slot !== undefined && compensatedSlots.has(slot)) {\n effectReports[index] = { ...entry, verdict: 'compensated' };\n }\n }\n }\n if (unexplained.length > 0) {\n await deps.store.transact({ runId }, lease, (tx) => {\n deps.events.append(\n tx,\n unexplained.map((slot) => ({\n type: 'repo.change.detected' as const,\n payload: { slot, expected: '(checkpoint)', actual: '(unexplained change)', files: [] },\n summary: `unexplained change in worktree ${slot}: no effect explains it`,\n severity: 'error' as const,\n })),\n );\n });\n throw new CohorteError(\n errorOf(\n 'security/write-outside-ownership',\n `run ${runId}: worktree(s) ${unexplained.join(', ')} changed with no explaining effect`,\n ),\n );\n }\n\n // Step 9 — inbox + approvals expiry.\n //\n // DEVIATION (docs/v3/requests/U1.10.md item D6): `ResumeDeps` has no `CommandAuthenticator` and no `KeyStore`,\n // so the MAC of a pending command cannot be verified here, and APPLYING a command means running it through\n // the transition table and its guards — the engine's job (U1.09), which reads the same inbox after\n // `recover()` returns. `commandsApplied` is therefore EMPTY: the field names commands this procedure applied,\n // and it applied none. What recovery does honour is DESIGN 4.4 step 9's own sentence, \"a `cancel` recorded\n // while the host was dead wins here\": a pending `cancel` / `shutdown` stops step 10 from reincarnating\n // anything and from replaying any approved call, so the engine finds the run exactly as the dead host left\n // it, plus the reconciliation of steps 5-8, and cancels it.\n const pending = await deps.store.pendingCommands(runId);\n const halting = pending.find((command) => HALTING_COMMAND_TYPES.has(command.type));\n const commandsApplied: CommandId[] = [];\n const openApprovals = await deps.store.listPendingApprovals(runId);\n const now = deps.clock.now();\n const due = openApprovals.filter((a) => a.expiresAt !== undefined && a.expiresAt <= now);\n if (due.length > 0) {\n await deps.store.transact({ runId }, lease, (tx) => {\n const appended = deps.events.append(\n tx,\n due.map((a) => ({\n type: 'approval.resolved' as const,\n payload: {\n approvalId: a.approvalId,\n decision: 'expired' as const,\n actor: { kind: 'system' as const, id: host.hostId, transport: 'cli' as const },\n },\n summary: `approval ${a.approvalId} expired`,\n severity: 'info' as const,\n })),\n );\n due.forEach((a, index) => {\n const event = appended.at(index);\n if (!event) throw new TypeError('resume: approval.resolved event count mismatch');\n tx.resolveApproval(a.approvalId, {\n actor: { kind: 'system', id: host.hostId, transport: 'cli' },\n answer: 'expired',\n decidedAt: now,\n resolvedSeq: event.sequence,\n });\n });\n });\n }\n const dueIds = new Set(due.map((a) => a.approvalId));\n const stillPending = openApprovals.filter((a) => !dueIds.has(a.approvalId));\n const approvalsCarried: ApprovalId[] = stillPending.map((a) => a.approvalId);\n\n // Step 10 — EVERY agent that is still one of the four reincarnation sources of DESIGN 2.5.4 continues in a new\n // incarnation of the same attempt: after a host death none of this run's children survives, whether the agent\n // was `running`, mid-`spawning`, `waiting` on an approval (the 4.5 parked case `ToolHostReplay` exists for) or\n // `paused`. Its approved-but-unconsumed calls are replayed FIRST (4.5), then the reconciliation note is built\n // from what steps 7-8 actually did, then `reincarnate` (incarnation+1, attempt unchanged). A\n // `budget/incarnations` exhaustion fails THAT agent, never the whole recovery.\n const approvedReplays: ResumeReport['approvedReplays'] = [];\n /** `{ agentId, text }` per continued agent — the note DESIGN 4.4 step 10 describes. D5: turning it into the\n * `Continuation.note` `TaskInput` needs RunFiles/BlobStore (AgentSupervisor's, a later wave); what recovery\n * itself can do with the text is put it in front of the human, which is the `blocked-ack` preview of step 11. */\n const notes: { agentId: string; text: string }[] = [];\n // Recovery reconciles (steps 5-8) but does NOT continue the work when the run must not go on: DESIGN 4.4\n // step 11's \"recovery never silently un-suspends\" (the run's OWN state, `haltingRunState` above), step 9's\n // \"a `cancel` recorded while the host was dead wins here\", and step 6's zone held by another run.\n const suspendedBy = haltingRunState(run.state, stillPending.length);\n const haltedBy = halting\n ? `a pending \\`${halting.type}\\` command (${halting.commandId})`\n : conflicts.length > 0\n ? `lock(s) ${conflicts.join(', ')} held by another run`\n : suspendedBy;\n for (const agent of haltedBy ? [] : tree.agents) {\n if (!RECOVERABLE_AGENT_STATES.has(agent.state)) continue;\n\n // The approved calls are REPLAYED before the note is built (4.5 / ADR-0025 item 6), so every line below\n // states a fact about the post-recovery tree.\n const replayed: NoteItem[] = [];\n const unconsumed = tree.approvals.filter(\n (a) =>\n a.agentId === agent.agentId &&\n (a.status === 'allow-once' || a.status === 'allow-for-run') &&\n a.consumedByEffect === undefined,\n );\n for (const approval of unconsumed) {\n const call = approvedCallOf(runId, approval);\n if (!call) continue;\n const replay = await deps.toolHostReplay.replayApproved(\n lease,\n { approvalId: approval.approvalId, call, grantKey: approval.grantKey },\n host.signal,\n );\n approvedReplays.push({\n approvalId: approval.approvalId,\n toolCallId: call.toolCallId,\n outcome: replay.outcome,\n });\n replayed.push({\n situation: 'approved',\n approvalId: approval.approvalId,\n toolCallId: call.toolCallId,\n tool: call.tool,\n outcome: replay.outcome,\n });\n }\n\n // DESIGN 4.4 step 10's own order: calls not executed; calls completed with their recorded result; work\n // compensated by a reset; calls in doubt; approvals decided meanwhile.\n const compensated = agent.slot === undefined ? undefined : compensatedSlots.get(agent.slot);\n const noteItems: NoteItem[] = [];\n for (const { effect, action } of decisions) {\n if (effect.agentId !== agent.agentId || effect.toolCallId === undefined) continue;\n // a slot that was quarantined and reset has ONE line (below): saying \"completed\" about work the reset\n // discarded would be the lie the compensation exists to prevent.\n if (effect.slot !== undefined && compensatedSlots.has(effect.slot)) continue;\n const tool = effect.kind.startsWith('tool.') ? effect.kind.slice('tool.'.length) : effect.kind;\n if (action === 'fail') noteItems.push({ situation: 'not-executed', toolCallId: effect.toolCallId, tool });\n else if (action === 'done') {\n noteItems.push({\n situation: 'completed',\n toolCallId: effect.toolCallId,\n tool,\n resultSummary: `verified done after the restart (effect ${effect.idempotencyKey})`,\n });\n }\n }\n if (compensated) {\n noteItems.push({\n situation: 'compensated',\n effectId: compensated.because,\n checkpointSha: compensated.checkpointSha,\n patch: compensated.patch,\n });\n }\n for (const { effect, action } of decisions) {\n if (action !== 'in-doubt' || effect.agentId !== agent.agentId) continue;\n noteItems.push({\n situation: 'in-doubt',\n effectId: effect.effectId,\n kind: effect.kind,\n replayClass: effect.replayClass,\n });\n }\n noteItems.push(...replayed);\n notes.push({\n agentId: agent.agentId,\n text: buildReconciliationNoteText({\n agentId: agent.agentId,\n fromIncarnation: agent.incarnation,\n items: noteItems,\n }),\n });\n\n try {\n const reincarnated = reincarnate(agent, 'recovery');\n await deps.store.transact({ runId }, lease, (tx) => {\n tx.putAgent(reincarnated);\n deps.events.append(tx, [\n {\n type: 'agent.state.changed',\n payload: {\n agent: {\n agentId: agent.agentId,\n role: agent.role,\n ...(agent.surface ? { surface: agent.surface } : {}),\n incarnation: reincarnated.incarnation,\n attempt: reincarnated.attempt,\n },\n from: agent.state,\n to: 'spawning',\n reason: 'recovery',\n attemptConsumed: false,\n },\n summary: `agent ${agent.agentId} reincarnated by resume (host restart)`,\n severity: 'info',\n },\n ]);\n });\n } catch (thrown) {\n if (thrown instanceof CohorteError && thrown.info.code === 'budget/incarnations') {\n await deps.store.transact({ runId }, lease, (tx) => {\n tx.putAgent({ ...agent, state: 'failed', lastError: thrown.info, updatedAt: deps.clock.now() });\n });\n } else {\n throw thrown;\n }\n }\n }\n\n // Step 11 — the acknowledgements that must exist BEFORE the run goes on, then `run.resumed`.\n //\n // (a) DESIGN 4.4 step 6: \"a zone now held by another run => WAITING_APPROVAL(`conflict/zone-reserved`)\". A\n // lock this host could not rebuild is exactly that, and the way a run reaches WAITING_APPROVAL here is a\n // pending BLOCKING approval: the engine's `checkGlobalStops` turns one into `approval-required` (T21).\n // (b) DESIGN 4.4 step 11's last sentence: \"an `in-doubt` effect with `policy.inDoubt: 'ask'` (default) opens a\n // `blocked-ack`-style approval before the agent continues\". DEVIATION: the in-doubt POLICY is not\n // reachable from this port set (it lives in the project config, which `ResumeDeps` cannot read), so the\n // DEFAULT — `ask` — is what recovery applies, unconditionally. `docs/v3/requests/U1.10.md` item D8 asks\n // for the policy to be carried on the run row or handed to `createResumer`.\n // Both are idempotent: a second recovery finding the same situation reuses the approval by its\n // `idempotencyKey` instead of opening a duplicate.\n const carriedByKey = new Map(\n openApprovals.filter((a) => !dueIds.has(a.approvalId)).map((a) => [a.idempotencyKey, a.approvalId]),\n );\n const ensureBlockedAck = async (draft: BlockedAckDraft): Promise<void> => {\n const existing = carriedByKey.get(draft.idempotencyKey);\n if (existing !== undefined) return;\n const approvalId = await openBlockedAckApproval(deps, runId, lease, draft);\n carriedByKey.set(draft.idempotencyKey, approvalId);\n approvalsCarried.push(approvalId);\n };\n if (conflicts.length > 0) {\n await ensureBlockedAck({\n idempotencyKey: `apr:${runId}:blocked-ack:lock-conflict`,\n ruleId: 'conflict/zone-reserved',\n reason: `run ${runId}: lock(s) ${conflicts.join(', ')} could not be rebuilt — they are held by another run`,\n previewText: `These locks belong to another run and recovery could not take them back:\\n${conflicts\n .map((c) => `- ${c}`)\n .join('\\n')}\\n\\nNothing was reincarnated. Release the other run (or cancel this one) before resuming.`,\n affectedPaths: [],\n });\n }\n if (inDoubtIds.length > 0) {\n await ensureBlockedAck({\n idempotencyKey: `apr:${runId}:blocked-ack:in-doubt`,\n ruleId: 'human-required/in-doubt-effect',\n reason: `run ${runId}: ${inDoubtIds.length} effect(s) are in doubt after the host restart and must be acknowledged before the agents continue`,\n previewText:\n notes.length > 0\n ? notes.map((n) => n.text).join('\\n\\n')\n : `In doubt after the restart:\\n${inDoubtIds.map((id) => `- ${id}`).join('\\n')}`,\n affectedPaths: [],\n });\n }\n\n const report: ResumeReport = {\n takeover,\n hostId: host.hostId,\n fencingToken,\n locks: { rebuilt, conflicts },\n orphans,\n worktrees: worktreeReports,\n effects: effectReports,\n approvalsCarried,\n commandsApplied,\n inDoubt: inDoubtIds,\n approvedReplays,\n };\n\n // Commit run.resumed; recovery never silently un-suspends (this event's `evolve` case is a no-op,\n // `packages/core/src/state/evolve.ts`, so nothing here moves `run.state`).\n await deps.store.transact({ runId }, lease, (tx) => {\n deps.events.append(tx, [\n {\n type: 'run.resumed',\n payload: { mode: 'recovery', report },\n summary: haltedBy\n ? `run ${runId} recovered but not continued: ${haltedBy}`\n : `run ${runId} resumed (recovery, host ${host.hostId})`,\n severity: 'success',\n },\n ]);\n });\n\n return report;\n },\n };\n}\n","// DESIGN 6.1 — what is snapshotted at run start (spec 16, all eight items). Lives here, not in `@cohorte/config`:\n// it embeds `SandboxCapabilities` (security) and `RuntimeCapabilities` / `RuntimePin` (runtime-contract); `config`\n// may import neither `security` nor `runtime-contract` (DESIGN 1.1), and `core` is the lowest package allowed to\n// import all three (PLAN PC-8). `gen-schemas` (U0.G) reads it from `@cohorte/core/contract`.\nimport type { IsoInstant, Sha256, SpecId } from '@cohorte/base';\nimport { IsoInstant as IsoInstantSchema, Sha256 as Sha256Schema, SpecId as SpecIdSchema } from '@cohorte/base';\nimport type { PipelineProfile, RunPlan } from '@cohorte/protocol';\nimport { PipelineProfile as PipelineProfileSchema } from '@cohorte/protocol';\nimport type {\n RuntimeCapabilities as RuntimeCapabilitiesType,\n RuntimePin as RuntimePinType,\n} from '@cohorte/runtime-contract';\nimport { RuntimeCapabilities, RuntimePin } from '@cohorte/runtime-contract';\nimport type { SandboxCapabilities as SandboxCapabilitiesType } from '@cohorte/security/contract';\nimport { SandboxCapabilities } from '@cohorte/security/contract';\nimport { type TUnsafe, Type } from 'typebox';\n\nconst strict = { additionalProperties: false } as const;\nconst count = () => Type.Integer({ minimum: 0 });\n\nexport interface RunSnapshotManifest {\n manifestVersion: 1;\n /** version de l'application, hash Git */\n createdAt: IsoInstant;\n app: { name: 'cohorte'; version: string; installDir: string; gitHash: string | null };\n /** resolved direct runtime deps (node_modules/<pkg>/package.json) */\n packages: { name: string; version: string }[];\n /** every file under dist/ == bundle-manifest.json */\n bundles: { file: string; sha256: Sha256; bytes: number }[];\n assets: { treeSha256: Sha256; embeddedTreeSha256: Sha256 };\n schemas: {\n protocolVersion: '1.0';\n stateSchemaVersion: number;\n configSchemaVersion: number;\n transitionTable: { profile: PipelineProfile; version: number };\n };\n /** bytes in the CAS */\n prompts: { id: string; source: 'shipped' | 'project-override'; logicalPath: string; sha256: Sha256 }[];\n skills: { id: string; version: string; source: 'shipped' | 'project'; sha256: Sha256 }[];\n config: {\n resolvedSha256: Sha256;\n ownershipSha256: Sha256;\n policySha256: Sha256;\n conventionsSha256: Sha256 | null;\n /** 2.10.1: the consent under which the loosening keys of the project file were honoured */\n trust: RunPlan['trust'];\n };\n spec: { id: SpecId; sha256: Sha256 } | null;\n environment: {\n pinnedPath: string[];\n platform: string;\n arch: string;\n sandbox: SandboxCapabilitiesType;\n runtimeCapabilities: RuntimeCapabilitiesType;\n };\n /** AgentRuntime actif (3.9) */\n runtime: RuntimePinType;\n}\n\nconst TrustSchema = Type.Object(\n {\n policySha256: Sha256Schema,\n loosenedKeys: Type.Array(Type.String()),\n grantedBy: Type.Unsafe<RunPlan['trust']['grantedBy']>(Type.String()),\n },\n strict,\n);\n\n/** [S]. Annotated so that Biome's type-aware `noFloatingPromises` has nothing to infer (docs/v3/requests/U0.02.md R1). */\nexport const RunSnapshotManifest: TUnsafe<RunSnapshotManifest> = Type.Unsafe<RunSnapshotManifest>(\n Type.Object(\n {\n manifestVersion: Type.Literal(1),\n createdAt: IsoInstantSchema,\n app: Type.Object(\n {\n name: Type.Literal('cohorte'),\n version: Type.String(),\n installDir: Type.String(),\n gitHash: Type.Union([Type.String(), Type.Null()]),\n },\n strict,\n ),\n packages: Type.Array(Type.Object({ name: Type.String(), version: Type.String() }, strict)),\n bundles: Type.Array(Type.Object({ file: Type.String(), sha256: Sha256Schema, bytes: count() }, strict)),\n assets: Type.Object({ treeSha256: Sha256Schema, embeddedTreeSha256: Sha256Schema }, strict),\n schemas: Type.Object(\n {\n protocolVersion: Type.Literal('1.0'),\n stateSchemaVersion: count(),\n configSchemaVersion: count(),\n transitionTable: Type.Object({ profile: PipelineProfileSchema, version: count() }, strict),\n },\n strict,\n ),\n prompts: Type.Array(\n Type.Object(\n {\n id: Type.String(),\n source: Type.Union([Type.Literal('shipped'), Type.Literal('project-override')]),\n logicalPath: Type.String(),\n sha256: Sha256Schema,\n },\n strict,\n ),\n ),\n skills: Type.Array(\n Type.Object(\n {\n id: Type.String(),\n version: Type.String(),\n source: Type.Union([Type.Literal('shipped'), Type.Literal('project')]),\n sha256: Sha256Schema,\n },\n strict,\n ),\n ),\n config: Type.Object(\n {\n resolvedSha256: Sha256Schema,\n ownershipSha256: Sha256Schema,\n policySha256: Sha256Schema,\n conventionsSha256: Type.Union([Sha256Schema, Type.Null()]),\n trust: TrustSchema,\n },\n strict,\n ),\n spec: Type.Union([Type.Object({ id: SpecIdSchema, sha256: Sha256Schema }, strict), Type.Null()]),\n environment: Type.Object(\n {\n pinnedPath: Type.Array(Type.String()),\n platform: Type.String(),\n arch: Type.String(),\n sandbox: SandboxCapabilities,\n runtimeCapabilities: RuntimeCapabilities,\n },\n strict,\n ),\n runtime: RuntimePin,\n },\n strict,\n ),\n);\n","import { type ErrorInfo, err, errorOf, ok, type Result, type Sha256, sha256Hex } from '@cohorte/base';\nimport type { BlobStore } from '@cohorte/persistence/contract';\nimport type { RuntimeCapabilities } from '@cohorte/runtime-contract';\nimport type { SandboxCapabilities } from '@cohorte/security/contract';\nimport { Compile } from 'typebox/compile';\nimport type { RunSnapshotter } from '../contract/internal.ts';\nimport type { InstallInspector } from '../contract/ports.ts';\nimport type { RunSnapshotManifest } from '../contract/snapshot-manifest.ts';\nimport { RunSnapshotManifest as RunSnapshotManifestSchema } from '../contract/snapshot-manifest.ts';\nimport type { SnapshotInput } from '../contract/types.ts';\n\nexport interface SnapshotMetadata {\n app: { version: string; gitHash: string | null };\n packages: { name: string; version: string }[];\n assets: { treeSha256: Sha256; embeddedTreeSha256: Sha256 };\n schemas: { stateSchemaVersion: number; configSchemaVersion: number; transitionTableVersion: number };\n prompts: RunSnapshotManifest['prompts'];\n skills: RunSnapshotManifest['skills'];\n environment: {\n pinnedPath: string[];\n platform: string;\n arch: string;\n sandbox: SandboxCapabilities;\n runtimeCapabilities: RuntimeCapabilities;\n };\n readFile(path: string): Promise<Uint8Array>;\n onMaterialized?(logicalPath: string, ref: { sha256: Sha256; bytes: number; path: string }): void;\n}\n\nconst manifestValidator = Compile(RunSnapshotManifestSchema);\nconst manifestCheck = (value: unknown): boolean => manifestValidator.Check(value);\n\nfunction snapshotError(message: string): ErrorInfo {\n return errorOf('security/pin-tampered', message);\n}\n\nexport function createRunSnapshotterImpl(deps: {\n installInspector: InstallInspector;\n clock: { now(): RunSnapshotManifest['createdAt'] };\n pinStore: BlobStore;\n metadata: SnapshotMetadata;\n}): RunSnapshotter {\n const refs = new Map<string, { sha256: Sha256; bytes: number; path: string }>();\n\n const materialize = async (logicalPath: string, path: string): Promise<Sha256> => {\n const bytes = await deps.metadata.readFile(path);\n const stored = await deps.pinStore.put(bytes);\n const ref = { ...stored, path };\n refs.set(logicalPath, ref);\n deps.metadata.onMaterialized?.(logicalPath, ref);\n return stored.sha256;\n };\n\n return {\n async capture(input: SnapshotInput): Promise<RunSnapshotManifest> {\n const config = await materialize('config.yaml', input.configPaths.config);\n const ownership = await materialize('ownership.yaml', input.configPaths.ownership);\n const policy = await materialize('policy.yaml', input.configPaths.policy);\n const conventions = input.configPaths.conventions\n ? await materialize('conventions.md', input.configPaths.conventions)\n : null;\n const spec = input.spec ? { id: input.spec.id, sha256: await materialize('spec.md', input.spec.path) } : null;\n const prompts = [\n ...deps.metadata.prompts,\n ...(await Promise.all(\n (input.prompts ?? []).map(async (prompt) => ({\n id: prompt.id,\n source: prompt.source,\n logicalPath: prompt.logicalPath,\n sha256: await materialize(`prompt:${prompt.id}`, prompt.path),\n })),\n )),\n ];\n const bundles = await deps.installInspector.bundleManifest();\n const manifest: RunSnapshotManifest = {\n manifestVersion: 1,\n createdAt: deps.clock.now(),\n app: {\n name: 'cohorte',\n version: deps.metadata.app.version,\n installDir: input.installDir,\n gitHash: deps.metadata.app.gitHash,\n },\n packages: [...deps.metadata.packages].sort((a, b) => a.name.localeCompare(b.name)),\n bundles: [...bundles].sort((a, b) => a.file.localeCompare(b.file)),\n assets: deps.metadata.assets,\n schemas: {\n protocolVersion: '1.0',\n stateSchemaVersion: deps.metadata.schemas.stateSchemaVersion,\n configSchemaVersion: deps.metadata.schemas.configSchemaVersion,\n transitionTable: {\n profile: input.trust.grantedBy === 'none-needed' ? 'feature' : 'feature',\n version: deps.metadata.schemas.transitionTableVersion,\n },\n },\n prompts,\n skills: [...deps.metadata.skills],\n config: {\n resolvedSha256: config,\n ownershipSha256: ownership,\n policySha256: policy,\n conventionsSha256: conventions,\n trust: input.trust,\n },\n spec,\n environment: deps.metadata.environment,\n runtime: input.runtime,\n };\n if (!manifestCheck(manifest)) throw new Error('validation/snapshot-manifest-invalid');\n return manifest;\n },\n\n async verify(manifest): Promise<Result<true, ErrorInfo>> {\n if (!manifestCheck(manifest))\n return err(errorOf('validation/unexpected', 'snapshot manifest does not match its schema'));\n const expected = new Set<Sha256>([\n manifest.config.resolvedSha256,\n manifest.config.ownershipSha256,\n manifest.config.policySha256,\n ...(manifest.config.conventionsSha256 ? [manifest.config.conventionsSha256] : []),\n ...(manifest.spec ? [manifest.spec.sha256] : []),\n ...manifest.prompts.map((prompt) => prompt.sha256),\n ]);\n for (const [logicalPath, ref] of refs) {\n if (!expected.has(ref.sha256)) continue;\n const bytes = await deps.pinStore.read(ref.sha256);\n if (sha256Hex(bytes) !== ref.sha256) return err(snapshotError(`snapshot blob was modified: ${logicalPath}`));\n }\n return ok(true);\n },\n };\n}\n","import { isSafeId, type RunId } from '@cohorte/base';\nimport type { CanonicalPath, GitPort } from '@cohorte/git/contract';\nimport type { WorktreeRecord } from '@cohorte/persistence/contract';\nimport type { ArtifactRef } from '@cohorte/protocol';\nimport type { WorktreeService } from '../contract/internal.ts';\nimport type { CheckpointCause, LedgerAudit } from '../contract/types.ts';\n\nexport interface WorktreeImplementationDeps {\n git: GitPort;\n runId: RunId;\n repo: CanonicalPath;\n root: CanonicalPath;\n integrationHead: string;\n}\n\nconst pathFor = (root: string, slot: string): CanonicalPath => `${root}/${slot}` as CanonicalPath;\n\nfunction validateSlot(slot: string): void {\n if (!isSafeId(slot)) throw new Error(`validation/invalid-id: invalid worktree slot`);\n}\n\nexport function createWorktreeServiceImpl(deps: WorktreeImplementationDeps): WorktreeService {\n const records = new Map<string, WorktreeRecord>();\n return {\n async acquire(slot, forAgent) {\n validateSlot(slot);\n let integrationHead = deps.integrationHead;\n if (typeof deps.git.facts === 'function') {\n try {\n const integrationFacts = await deps.git.facts(pathFor(deps.root, '_integration'));\n if (integrationFacts.head.kind !== 'unborn') integrationHead = integrationFacts.head.sha;\n } catch {\n // Unit ports may not expose an integration worktree; retain the frozen initial head in that case.\n }\n }\n const existing = records.get(slot);\n if (existing?.state === 'held' && existing.holderAgentId !== forAgent)\n throw new Error(`conflict/worktree-held: ${slot}`);\n if (existing) {\n const branch = `cohorte/${deps.runId}/${slot}/${forAgent}`;\n if (existing.branch !== branch) {\n await deps.git.switchToNewBranch({\n worktree: existing.path as CanonicalPath,\n branch,\n at: integrationHead,\n });\n }\n const next = {\n ...existing,\n branch,\n baseSha: integrationHead,\n checkpointSha: integrationHead,\n holderAgentId: forAgent,\n state: 'held' as const,\n };\n records.set(slot, next);\n return next;\n }\n const path = pathFor(deps.root, slot);\n const branch = `cohorte/${deps.runId}/${slot}/${forAgent}`;\n await deps.git.addWorktree({ repo: deps.repo, path, branch, commit: integrationHead });\n const record: WorktreeRecord = {\n runId: deps.runId,\n slot,\n path,\n branch,\n baseSha: integrationHead,\n checkpointSha: integrationHead,\n holderAgentId: forAgent,\n state: 'held',\n };\n records.set(slot, record);\n return record;\n },\n\n async checkpoint(slot, _cause: CheckpointCause) {\n const record = records.get(slot);\n if (!record) throw new Error(`configuration/worktree-not-found: ${slot}`);\n const result = await deps.git.commitAll({\n worktree: record.path as CanonicalPath,\n message: 'chore(cohorte): checkpoint',\n trailers: { 'Cohorte-Managed': 'true', 'Cohorte-Checkpoint': 'true' },\n identity: { name: 'Cohorte', email: 'cohorte@localhost' },\n paths: ['.'],\n });\n const sha = 'kind' in result ? record.checkpointSha : result.sha;\n records.set(slot, { ...record, checkpointSha: sha, state: 'held' });\n return sha;\n },\n\n async release(slot) {\n const record = records.get(slot);\n if (!record) return;\n const next = { ...record, state: 'ready' as const };\n delete next.holderAgentId;\n records.set(slot, next);\n },\n\n async audit(slot): Promise<LedgerAudit> {\n const record = records.get(slot);\n if (!record) return { slot, verdict: 'missing-branch', entries: [] };\n const changed = await deps.git.changedPaths(record.path as CanonicalPath);\n return {\n slot,\n verdict: changed.length === 0 ? 'ok' : 'unexplained-change',\n entries: changed.map((touch) => ({\n path: touch.path,\n expectedSha256: touch.beforeSha256 ?? null,\n actualSha256: touch.afterSha256 ?? null,\n explained: false,\n })),\n };\n },\n\n async quarantineAndReset(slot, because): Promise<ArtifactRef> {\n const record = records.get(slot);\n if (!record) throw new Error(`configuration/worktree-not-found: ${slot}`);\n await deps.git.resetHardClean(record.path as CanonicalPath, record.checkpointSha);\n const next = { ...record, state: 'quarantined' as const };\n delete next.holderAgentId;\n records.set(slot, next);\n return {\n artifactId: `art_${because.slice(4)}` as ArtifactRef['artifactId'],\n kind: 'patch',\n path: record.path,\n sha256: '0'.repeat(64) as ArtifactRef['sha256'],\n bytes: 0,\n };\n },\n\n async resetClean(slot, to) {\n const record = records.get(slot);\n if (!record) throw new Error(`configuration/worktree-not-found: ${slot}`);\n await deps.git.resetHardClean(record.path as CanonicalPath, to);\n records.set(slot, { ...record, checkpointSha: to, state: 'ready' });\n },\n };\n}\n","// DESIGN 10.1 rule 3 / PLAN §0 — the `create*` signatures and their `*Deps` types (what the composition root will\n// pass) for every core area, and the frozen `@cohorte/core` barrel's typed `NotImplemented` stubs: every factory\n// below THROWS as soon as it is called. A later wave unit REPLACES the body, never the signature (once this unit's\n// check is green, PLAN's \"optimistic scheduling\" rule treats the exported names as published); `pipeline/guards`,\n// `budgets`, `grants` and `projection` have no dedicated port in `internal.ts` (DESIGN 2.5 does not name one), so\n// their return type and `*Deps` are declared here, next to the one factory that uses them.\nimport type { AgentId, BudgetCounters, RunId, Sha256, SurfaceId } from '@cohorte/base';\nimport { NotImplemented } from '@cohorte/base';\nimport type { CanonicalPath } from '@cohorte/git/contract';\nimport type {\n BlobStore,\n DurableEnvelope,\n EffectKind,\n EphemeralSpool,\n LeaseToken,\n StateStore,\n} from '@cohorte/persistence/contract';\nimport type { ActivePipelineState, AgentOutput, CheckResult, Finding, ReviewResult } from '@cohorte/protocol';\nimport { resolveModel } from '@cohorte/providers/resolve';\nimport type {\n AgentRuntime,\n AgentRuntimeProvider,\n RuntimeEvent,\n RuntimeHostBindings,\n SpawnRequest,\n ToolHost,\n} from '@cohorte/runtime-contract';\nimport type {\n AgentGrant,\n ExecRequest,\n PolicyPorts,\n PolicySnapshot,\n PolicyVerdict,\n SandboxCapabilities,\n} from '@cohorte/security/contract';\nimport type { ToolExecContext } from '@cohorte/tools/catalogue';\nimport { createAgentSupervisorImpl } from '../agents/supervisor/implementation.ts';\nimport {\n createApprovalService as createApprovalServiceImpl,\n createToolHostReplay as createToolHostReplayImpl,\n} from '../approvals/index.ts';\nimport { createContextBuilder as createContextBuilderImpl } from '../context/index.ts';\nimport { createEffectJournal as createEffectJournalImpl } from '../durability/journal/index.ts';\nimport { createLeaseManager as createLeaseManagerImpl } from '../durability/lease/index.ts';\nimport {\n createTransitionEffectRunner as createTransitionEffectRunnerImpl,\n type TransitionEffectRunnerDeps as TransitionEffectRunnerImplementationDeps,\n} from '../effects/transition-runner.ts';\nimport type { RunEngineDeps } from '../engine/deps.ts';\nimport { createEngine as createEngineImpl } from '../engine/index.ts';\nimport { createEventWriter as createEventWriterImpl } from '../events/index.ts';\nimport { createGrantComputer as createGrantComputerImpl } from '../grants/index.ts';\nimport { createIntegrationService as createIntegrationServiceImpl } from '../integration/index.ts';\nimport { createLoopController as createLoopControllerImpl } from '../loop/index.ts';\nimport { createPhaseContracts as createPhaseContractsImpl } from '../phases/contracts/index.ts';\nimport { createPhaseExecutor as createPhaseExecutorImpl } from '../phases/executor/implementation.ts';\nimport { createPipelineGuards as createPipelineGuardsImpl } from '../pipeline/guards/index.ts';\nimport { createProjection as createProjectionImpl } from '../projection/index.ts';\nimport { createProvisionerImpl, type ProvisionImplementationDeps } from '../provision/implementation.ts';\nimport { createResumer as createResumerImpl } from '../resume/index.ts';\nimport { createReviewCalculator as createReviewCalculatorImpl } from '../review/index.ts';\nimport { createRunSnapshotterImpl, type SnapshotMetadata } from '../snapshot/implementation.ts';\nimport { createPinReader as createPinReaderImpl } from '../snapshot/index.ts';\nimport { createToolHost as createToolHostImpl } from '../toolhost/implementation.ts';\nimport { createWorktreeServiceImpl, type WorktreeImplementationDeps } from '../worktrees/implementation.ts';\nimport type { GuardId } from './ids.ts';\nimport type {\n AgentSupervisor,\n ApprovalService,\n CommitService,\n ContextBuilder,\n EffectJournal,\n EventWriter,\n LeaseManager,\n MergeService,\n PhaseExecutor,\n PinReader,\n Provisioner,\n Resumer,\n RunEngine,\n RunSnapshotter,\n ToolHostReplay,\n WorktreeService,\n} from './internal.ts';\nimport type {\n BillingTable,\n Clock,\n EffectVerifier,\n EffectVerifierRegistry,\n Executor,\n FactCollector,\n GitPort,\n GuardRegistry,\n IdSource,\n InstallInspector,\n ModelResolver,\n PathResolver,\n PolicyEngine,\n ProcessSweeper,\n Redactor,\n ToolRegistry,\n TransitionEffectRunner,\n WorkspaceReader,\n} from './ports.ts';\nimport type {\n AgentGrantRequest,\n AgentPlan,\n GlobalFacts,\n LoopDecision,\n LoopPolicy,\n LoopState,\n PhaseContract,\n PhaseRunContext,\n RunState,\n} from './types.ts';\n\n// ── engine ──────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/**\n * The engine's implementation grew additive dependencies after the Wave-0\n * seam was published. Keep the public name, but expose the complete shape so\n * the composition root cannot accidentally construct a non-functional host.\n */\nexport type EngineDeps = RunEngineDeps;\nexport function createEngine(deps: EngineDeps): RunEngine {\n return createEngineImpl(deps);\n}\n\n// ── resume ──────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface ResumeDeps {\n store: StateStore;\n clock: Clock;\n sweeper: ProcessSweeper;\n effectVerifiers: EffectVerifierRegistry;\n worktrees: WorktreeService;\n // WIDENED at gate G1 (docs/v3/requests/U1.10.md D1, raised as a `lead` finding by both of U1.10's reviewers), the\n // same way `EventsDeps.spool` and `JournalDeps.redactor` were widened in U0.08's own fix round 1: never a reshape,\n // never a rename, and every added field is an EXISTING frozen port, so no contract and no package edge is new.\n // Without them DESIGN 4.4's steps 4 and 9-11 are unreachable — `run.resumed` / `lock.stolen` / `approval.resolved`\n // need an `EventWriter` (only a `Redactor` mints the `Sealed<T>` `StoreTx.appendEvents` takes), an approved call\n // whose requester died is replayed through `ToolHostReplay` (DESIGN 4.5), step 4's immutability check needs\n // `InstallInspector.installDir()`, and the `blocked-ack` approvals of steps 6 and 11 need an `ApprovalId`.\n // `packages/core/src/resume/index.ts` imports and re-exports THIS type; there is exactly one `ResumeDeps`.\n events: EventWriter;\n redactor: Redactor;\n toolHostReplay: ToolHostReplay;\n installInspector: InstallInspector;\n ids: IdSource;\n}\nexport function createResumer(deps: ResumeDeps): Resumer {\n return createResumerImpl(deps);\n}\n\n// ── events ──────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface EventsDeps {\n redactor: Redactor;\n clock: Clock;\n ids: IdSource;\n /** Ephemeral events never reach the store (DESIGN 2.3.2): `EventWriter.ephemeral()` writes to the run-level spool\n * port instead. Widened in fix round 1 (reviewer finding); `packages/core/src/events/index.ts` re-exports this\n * type rather than declaring a second one. */\n spool: EphemeralSpool;\n}\nexport function createEventWriter(deps: EventsDeps): EventWriter {\n return createEventWriterImpl(deps);\n}\n\n// ── durability/journal ──────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface JournalDeps {\n store: StateStore;\n events: EventWriter;\n clock: Clock;\n /** `StoreTx.completeEffect` persists a `SealedJson` result and `beginEffect` a sealed `request`/`verify` (DESIGN\n * 0.2 I7), so the journal seals what `perform()` returns before it is written. Widened in fix round 1 (reviewer\n * finding); `packages/core/src/durability/journal/index.ts` re-exports this type rather than declaring a second. */\n redactor: Redactor;\n}\nexport function createEffectJournal(deps: JournalDeps): EffectJournal {\n return createEffectJournalImpl(deps);\n}\n\n// ── durability/lease ────────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface LeaseDeps {\n store: StateStore;\n clock: Clock;\n}\nexport function createLeaseManager(deps: LeaseDeps): LeaseManager {\n return createLeaseManagerImpl(deps);\n}\n\n// ── toolhost ────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface ToolHostDeps {\n policy: PolicyEngine;\n paths: PathResolver;\n toolRegistry: ToolRegistry;\n journal: EffectJournal;\n events: EventWriter;\n approvals: ApprovalService;\n redactor: Redactor;\n /** Additive host-side bindings required by DESIGN 2.6.2 stages 1-8. */\n policySnapshot: PolicySnapshot;\n policyPorts: PolicyPorts;\n grantFor(call: Parameters<PolicyEngine['evaluate']>[0]): AgentGrant;\n grantKeyFor(call: Parameters<PolicyEngine['evaluate']>[0], verdict: PolicyVerdict): string;\n executionFor(call: Parameters<PolicyEngine['evaluate']>[0]): ToolExecContext;\n leaseFor(call: Parameters<PolicyEngine['evaluate']>[0]): LeaseToken;\n sandbox: SandboxCapabilities;\n requestApproval(\n call: Parameters<PolicyEngine['evaluate']>[0],\n verdict: PolicyVerdict,\n signal: AbortSignal,\n ): Promise<{ decision: 'allow-once' | 'allow-for-run' | 'deny'; approvalId?: string }>;\n recordRequested(call: Parameters<PolicyEngine['evaluate']>[0]): Promise<void>;\n recordDenied(call: Parameters<PolicyEngine['evaluate']>[0], verdict: PolicyVerdict): Promise<void>;\n}\nexport function createToolHost(deps: ToolHostDeps): ToolHost {\n return createToolHostImpl(deps);\n}\n\n// ── approvals ───────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface ApprovalsDeps {\n store: StateStore;\n events: EventWriter;\n clock: Clock;\n ids: IdSource;\n /** Required for persistence I7; optional keeps the frozen one-wave call source-compatible. */\n redactor?: Redactor;\n}\nexport function createApprovalService(deps: ApprovalsDeps): ApprovalService {\n return createApprovalServiceImpl(deps);\n}\nexport function createToolHostReplay(deps: ToolHostDeps): ToolHostReplay {\n return createToolHostReplayImpl(deps);\n}\n\n// ── context ─────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface ContextDeps {\n pin: PinReader;\n workspace: WorkspaceReader;\n writeTask(plan: AgentPlan, bytes: Uint8Array): Promise<{ path: string; sha256: Sha256; bytes: number }>;\n}\nexport function createContextBuilder(deps: ContextDeps): ContextBuilder {\n return createContextBuilderImpl(deps);\n}\n\n// ── snapshot ────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface SnapshotDeps {\n installInspector: InstallInspector;\n clock: Clock;\n /** CAS and logical-path catalogue used by PinReader; core never reads installation files directly. */\n pinStore?: BlobStore;\n pinRefs?: Readonly<Record<string, { sha256: Sha256; bytes: number; path: string }>>;\n metadata?: SnapshotMetadata;\n}\nexport function createRunSnapshotter(deps: SnapshotDeps): RunSnapshotter {\n if (!deps.pinStore || !deps.metadata) throw new NotImplemented('core/snapshot: missing CAS/metadata binding');\n return createRunSnapshotterImpl({\n installInspector: deps.installInspector,\n clock: deps.clock,\n pinStore: deps.pinStore,\n metadata: deps.metadata,\n });\n}\nexport function createPinReader(deps: SnapshotDeps): PinReader {\n return createPinReaderImpl(deps);\n}\n\n// ── agents/supervisor ───────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface AgentSupervisorDeps {\n runtimeProvider: AgentRuntimeProvider;\n events: EventWriter;\n clock: Clock;\n ids: IdSource;\n bindings?: RuntimeHostBindings;\n runtime?: AgentRuntime;\n requestFor?: (plan: AgentPlan, ctx: PhaseRunContext, incarnation: number) => SpawnRequest | Promise<SpawnRequest>;\n concurrency?: number;\n onRuntimeEvent?: (event: RuntimeEvent) => void | Promise<void>;\n outputFor?: (agentId: AgentId) => AgentOutput | undefined;\n}\nexport function createAgentSupervisor(deps: AgentSupervisorDeps): AgentSupervisor {\n if (!deps.bindings && !deps.runtime) throw new NotImplemented('core/agents/supervisor: missing runtime binding');\n return createAgentSupervisorImpl(deps);\n}\n\n// ── worktrees ───────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface WorktreesDeps {\n git: GitPort;\n journal: EffectJournal;\n events: EventWriter;\n runId?: RunId;\n repo?: CanonicalPath;\n root?: CanonicalPath;\n integrationHead?: string;\n}\nexport function createWorktreeService(deps: WorktreesDeps): WorktreeService {\n if (!deps.runId || !deps.repo || !deps.root || !deps.integrationHead)\n throw new NotImplemented('core/worktrees: missing run binding');\n const implementation: WorktreeImplementationDeps = {\n git: deps.git,\n runId: deps.runId,\n repo: deps.repo,\n root: deps.root,\n integrationHead: deps.integrationHead,\n };\n return createWorktreeServiceImpl(implementation);\n}\n\n// ── provision ───────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface ProvisionDeps {\n executor: Executor;\n journal: EffectJournal;\n requestFor?(slot: string): Promise<ExecRequest & { key: string; manifestSha256: Sha256 }>;\n}\nexport function createProvisioner(deps: ProvisionDeps): Provisioner {\n if (!deps.requestFor) throw new NotImplemented('core/provision: missing request binding');\n const implementation: ProvisionImplementationDeps = {\n executor: deps.executor,\n requestFor: async (slot) => {\n const value = await deps.requestFor?.(slot);\n if (!value) throw new Error(`configuration/provision-request-missing: ${slot}`);\n const { key, manifestSha256, ...request } = value;\n return { key, manifestSha256, request };\n },\n };\n return createProvisionerImpl(implementation);\n}\n\n// ── phases/executor ─────────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface PhasesExecutorDeps {\n contracts: PhaseContractRegistry;\n supervisor: AgentSupervisor;\n worktrees: WorktreeService;\n integration: IntegrationService;\n events: EventWriter;\n /** Optional projection writer used by the host composition to persist acquired slots in the same run lease. */\n store?: StateStore;\n checkRunner?: PhaseCheckRunner;\n}\nexport interface PhaseCheckRunner {\n run(ctx: PhaseRunContext): Promise<CheckResult[]>;\n}\nexport function createPhaseExecutor(deps: PhasesExecutorDeps): PhaseExecutor {\n return createPhaseExecutorImpl(deps);\n}\n\n// ── phases/contracts ────────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface PhaseContractRegistry {\n get(state: ActivePipelineState): PhaseContract | undefined;\n}\nexport interface PhasesContractsDeps {\n provisioner: Provisioner;\n}\nexport function createPhaseContracts(deps: PhasesContractsDeps): PhaseContractRegistry {\n return createPhaseContractsImpl(deps);\n}\n\n// ── integration (git.commit / git.merge as ports, PLAN PC-4) ──────────────────────────────────────────────────────\n\nexport interface IntegrationService extends CommitService, MergeService {}\nexport interface IntegrationDeps {\n git: GitPort;\n journal: EffectJournal;\n events: EventWriter;\n}\nexport function createIntegrationService(deps: IntegrationDeps): IntegrationService {\n return createIntegrationServiceImpl(deps);\n}\n\n// ── loop ────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface LoopController {\n decideAfterReview(review: ReviewResult | null, loop: LoopState, policy: LoopPolicy): LoopDecision;\n decideAfterTest(checks: readonly CheckResult[], loop: LoopState, policy: LoopPolicy): LoopDecision;\n}\nexport type LoopDeps = Record<string, never>;\nexport function createLoopController(deps: LoopDeps): LoopController {\n return createLoopControllerImpl(deps);\n}\n\n// ── review ──────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface ReviewCalculator {\n compute(findings: readonly Finding[], unreviewed: SurfaceId[]): ReviewResult;\n}\nexport type ReviewDeps = Record<string, never>;\nexport function createReviewCalculator(deps: ReviewDeps): ReviewCalculator {\n return createReviewCalculatorImpl(deps);\n}\n\n// ── pipeline/guards (no dedicated directory: `packages/core/src/pipeline/**` is not owned by this unit) ──────────\n\nexport interface PipelineGuards extends GuardRegistry {\n collectFacts(ids: readonly GuardId[]): Promise<GlobalFacts>;\n}\nexport interface PipelineGuardsDeps {\n factCollector: FactCollector;\n}\nexport function createPipelineGuards(deps: PipelineGuardsDeps): PipelineGuards {\n return createPipelineGuardsImpl(deps);\n}\n\n// ── budgets ─────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface BudgetTracker {\n remaining(level: 'run' | 'phase' | 'agent' | 'provider' | 'tool', id: string): BudgetCounters;\n}\nexport interface BudgetsDeps {\n store: StateStore;\n billing: BillingTable;\n /** Synchronous projection read used by the security gate before a tool call.\n * The StateStore remains asynchronous; the engine updates this projection when\n * it folds a durable usage event. */\n readRemaining?: (level: 'run' | 'phase' | 'agent' | 'provider' | 'tool', id: string) => BudgetCounters;\n}\nexport function createBudgetTracker(deps: BudgetsDeps): BudgetTracker {\n return {\n remaining(level, id) {\n const value = deps.readRemaining?.(level, id);\n if (value === undefined) return {};\n return { ...value };\n },\n };\n}\n\n// ── grants ──────────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface GrantComputer {\n compute(request: AgentGrantRequest): AgentGrant;\n}\nexport type GrantsDeps = Record<string, never>;\nexport function createGrantComputer(deps: GrantsDeps): GrantComputer {\n return createGrantComputerImpl(deps);\n}\n\n// ── projection ──────────────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface Projection {\n evolve(state: RunState, event: DurableEnvelope): RunState;\n}\nexport type ProjectionDeps = Record<string, never>;\nexport function createProjection(deps: ProjectionDeps): Projection {\n return createProjectionImpl(deps);\n}\n\n// ── model resolution / process sweeping (ports this plan adds; a factory each, so the barrel is uniform) ─────────\n\nexport type ModelResolverDeps = Record<string, never>;\nexport function createModelResolver(_deps: ModelResolverDeps): ModelResolver {\n return { resolve: resolveModel };\n}\nexport type ProcessSweeperDeps = Record<string, never>;\nexport function createProcessSweeper(_deps: ProcessSweeperDeps): ProcessSweeper {\n return {\n isAlive(pid, _startToken): boolean {\n if (!Number.isSafeInteger(pid) || pid <= 0) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n },\n async kill(pid, _startToken, signal = 'SIGTERM'): Promise<void> {\n if (!Number.isSafeInteger(pid) || pid <= 0) return;\n try {\n process.kill(pid, signal as NodeJS.Signals);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error;\n }\n },\n };\n}\n/** Every declarative effect of DESIGN 2.5.1's `effects` column runs through the journal and writes events; the unit\n * that implements the runner adds the area services its own ids need (`open-approval` -> `ApprovalService`,\n * `park-agents` -> `AgentSupervisor`, …) by WIDENING this type, never by reshaping it. */\nexport interface TransitionEffectRunnerDeps {\n store: StateStore;\n journal: EffectJournal;\n events: EventWriter;\n clock: Clock;\n handlers?: TransitionEffectRunnerImplementationDeps['handlers'];\n}\nexport function createTransitionEffectRunner(deps: TransitionEffectRunnerDeps): TransitionEffectRunner {\n return createTransitionEffectRunnerImpl({\n journal: deps.journal,\n ...(deps.handlers ? { handlers: deps.handlers } : {}),\n });\n}\nexport interface EffectVerifierRegistryDeps {\n verifiers?: Partial<Record<EffectKind, EffectVerifier>>;\n}\nexport function createEffectVerifierRegistry(deps: EffectVerifierRegistryDeps): EffectVerifierRegistry {\n const verifiers = new Map<EffectKind, EffectVerifier>(\n Object.entries(deps.verifiers ?? {}) as [EffectKind, EffectVerifier][],\n );\n return { get: (kind) => verifiers.get(kind) };\n}\n","// DESIGN 2.8 — the \"Run effect (default)\" column of the error taxonomy: what happens to the RUN, at the class\n// level, when an error of that class surfaces. Re-exports the base catalogue (`ERROR_CATALOGUE`, code -> {class,\n// retryable, impact, remediation, exit}); this file adds the coarser class -> run-effect table DESIGN 2.8 does not\n// give as data. \"Unknown throwables -> <nearest class>/unexpected -> FAILED + checkpoint.created\" (DESIGN 2.8): the\n// classes an UNCLASSIFIED throwable can land on (`base`'s `UNCLASSIFIED` fallback is `validation/unexpected`) end in\n// `FAILED` with `checkpoint: true`, matching T26 (`cancel-agents, checkpoint-worktrees, checkpoint`); `security`\n// alone ends in `BLOCKED` (T25: `cancel-agents, freeze-worktrees` — no `checkpoint` effect in that row).\nimport { ERROR_CLASSES, type ErrorClass } from '@cohorte/base';\n\nexport type { ErrorCatalogueEntry, ErrorCode } from '@cohorte/base';\nexport { ERROR_CATALOGUE, EXIT_CODE_BY_CLASS, isErrorCode } from '@cohorte/base';\n\nexport type RunEffectEndState =\n | 'refuse-to-start'\n | 'FAILED'\n | 'BLOCKED'\n | 'WAITING_APPROVAL'\n | 'suspended-auth-or-quota'\n | 'agent-error-result'\n | 'refuse-to-open';\n\nexport interface RunEffectRow {\n readonly class: ErrorClass;\n readonly endState: RunEffectEndState;\n /** true when reaching this state also writes a `checkpoint.created` (T26-shaped rows only: T25's BLOCKED does not) */\n readonly checkpoint: boolean;\n /** DESIGN 2.8's \"Run effect (default)\" column text, verbatim */\n readonly description: string;\n}\n\nconst row = (cls: ErrorClass, endState: RunEffectEndState, checkpoint: boolean, description: string): RunEffectRow => ({\n class: cls,\n endState,\n checkpoint,\n description,\n});\n\n/** Total over `ErrorClass` (DESIGN 2.8, in table order). */\nexport const RUN_EFFECT_BY_CLASS: Readonly<Record<ErrorClass, RunEffectRow>> = Object.freeze({\n configuration: row('configuration', 'refuse-to-start', false, 'refuse to start / FAILED'),\n validation: row('validation', 'FAILED', true, 'agent failed → retry policy → FAILED'),\n permission: row('permission', 'agent-error-result', false, 'tool.denied; repeated → policy-violation'),\n security: row('security', 'BLOCKED', false, 'BLOCKED, agents cancelled, worktrees frozen'),\n 'provider-transient': row('provider-transient', 'FAILED', true, 'retry → FAILED'),\n 'provider-terminal': row(\n 'provider-terminal',\n 'suspended-auth-or-quota',\n false,\n 'FAILED, or AUTH_REQUIRED / QUOTA_EXCEEDED',\n ),\n 'tool-transient': row('tool-transient', 'agent-error-result', false, 'retry once, then report to the agent'),\n 'tool-terminal': row('tool-terminal', 'agent-error-result', false, 'error result to the agent'),\n conflict: row('conflict', 'WAITING_APPROVAL', false, 'WAITING_APPROVAL or FIX'),\n budget: row('budget', 'WAITING_APPROVAL', false, 'WAITING_APPROVAL(budget)'),\n // The RUN effect of a timeout is DESIGN 2.8's column cell: T24 opens a `loop-stalled`/`budget` approval, with no\n // `checkpoint` effect in that row. The FAILED of DESIGN 2.5.3's stop table (\"timeout, agent level, retries\n // exhausted\") is reached through the agent's `RetryPolicy`, not through this class-level default.\n timeout: row('timeout', 'WAITING_APPROVAL', false, 'retry / WAITING_APPROVAL'),\n corruption: row('corruption', 'refuse-to-open', false, 'refuse to open; never delete a run'),\n 'human-required': row('human-required', 'WAITING_APPROVAL', false, 'WAITING_APPROVAL / AUTH_REQUIRED'),\n} satisfies Record<ErrorClass, RunEffectRow>);\n\nexport function runEffectOf(errorClass: ErrorClass): RunEffectRow {\n const found = RUN_EFFECT_BY_CLASS[errorClass];\n if (!found) throw new TypeError(`runEffectOf: ${String(errorClass)} is not one of ${ERROR_CLASSES.join(', ')}`);\n return found;\n}\n","import type { PhasesExecutorDeps } from '../../contract/factories.ts';\nimport { createPhaseExecutor as createPhaseExecutorImpl } from './implementation.ts';\n\nexport type { PhasesExecutorDeps };\nexport function createPhaseExecutor(deps: PhasesExecutorDeps) {\n return createPhaseExecutorImpl(deps);\n}\n"],"mappings":";;;;;;;;AA2BA,MAAM,sBAAsB;CAAC;CAAY;CAAW;CAAW;AAAQ;;;;;;;;;;;;AA0BvE,SAAgB,YAAY,OAAoB,OAAsC;CACpF,IAAI,CAAE,oBAA0C,SAAS,MAAM,KAAK,GAClE,MAAM,IAAI,UACR,sBAAsB,MAAM,QAAQ,MAAM,MAAM,MAAM,eAAe,oBAAoB,KAAK,IAAI,GACpG;CAEF,MAAM,kBAAkB,MAAM,cAAc;CAC5C,IAAI,kBAAkB,MAAM,iBAC1B,MAAM,IAAI,aACR,QACE,uBACA,SAAS,MAAM,QAAQ,uCAAuC,MAAM,gBAAgB,wBAAwB,MAAM,EACpH,CACF;CAEF,OAAO;EAAE,GAAG;EAAO,OAAO;EAAY,aAAa;CAAgB;AACrE;;;AC3CA,SAAS,eACP,MACA,MACA,aACA,WACa;CACb,MAAM,UAAU,KAAK,YAAY,cAAc,cAAc,KAAK,YAAY,cAAc,cAAc;CAC1G,MAAM,SAAS,YAAY,KAAK,OAAO;CACvC,OAAO;EACL,OAAO;GACL,SAAS,KAAK;GACd,MAAM,KAAK,KAAK;GAChB,GAAI,KAAK,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,KAAK,QAAQ;GAC9D;GACA,SAAS;EACX;EACA;EACA,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO;EACzC,GAAI,KAAK,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,KAAK,MAAM;EACxD,WAAW,CAAC;EACZ,OAAO;GACL,QAAQ,KAAK,MAAM,OAAO;GAC1B,eAAe,KAAK,MAAM;GAC1B,WAAW,KAAK,MAAM;GACtB,aAAa,KAAK,MAAM;EAC1B;CACF;AACF;AAEA,eAAe,OACb,SACA,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