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.
- package/README.md +7 -0
- package/assets/manifest.json +193 -0
- package/assets/migrations/config/README.md +12 -0
- package/assets/migrations/state/0001_init.sql +154 -0
- package/assets/prompts/README.md +11 -0
- package/assets/prompts/agents/fixer.md +7 -0
- package/assets/prompts/agents/implementer.md +12 -0
- package/assets/prompts/agents/reviewer.md +8 -0
- package/assets/prompts/agents/security-reviewer.md +7 -0
- package/assets/prompts/phases/build.md +5 -0
- package/assets/prompts/phases/review.md +5 -0
- package/assets/prompts/phases/test.md +5 -0
- package/assets/prompts/system.md +11 -0
- package/assets/schemas/agent-output.schema.json +225 -0
- package/assets/schemas/auth-status.schema.json +87 -0
- package/assets/schemas/command-result.schema.json +192 -0
- package/assets/schemas/commands.schema.json +952 -0
- package/assets/schemas/config.schema.json +2259 -0
- package/assets/schemas/doctor-report.schema.json +104 -0
- package/assets/schemas/events.schema.json +8514 -0
- package/assets/schemas/fake-script.schema.json +549 -0
- package/assets/schemas/inspect.schema.json +3133 -0
- package/assets/schemas/manifest.schema.json +79 -0
- package/assets/schemas/ownership.schema.json +52 -0
- package/assets/schemas/policy-verdict.schema.json +282 -0
- package/assets/schemas/project-model.schema.json +783 -0
- package/assets/schemas/project-status.schema.json +217 -0
- package/assets/schemas/reconcile-plan.schema.json +154 -0
- package/assets/schemas/run-diff.schema.json +177 -0
- package/assets/schemas/run-snapshot-manifest.schema.json +2104 -0
- package/assets/schemas/run-state.schema.json +1755 -0
- package/assets/schemas/runtime-capabilities.schema.json +1545 -0
- package/assets/schemas/sandbox-capabilities.schema.json +116 -0
- package/assets/schemas/skill.schema.json +87 -0
- package/assets/schemas/spec.schema.json +202 -0
- package/assets/schemas/tool-catalogue.schema.json +655 -0
- package/assets/schemas/trust-record.schema.json +38 -0
- package/assets/skills/README.md +9 -0
- package/assets/skills/inspect-surface.md +4 -0
- package/dist/agent-host.mjs +2187 -0
- package/dist/agent-host.mjs.map +1 -0
- package/dist/bundle-manifest.json +104 -0
- package/dist/chunks/__host-DgGPyco9.mjs +18 -0
- package/dist/chunks/__host-DgGPyco9.mjs.map +1 -0
- package/dist/chunks/approve-Cv135UqI.mjs +19 -0
- package/dist/chunks/approve-Cv135UqI.mjs.map +1 -0
- package/dist/chunks/auth-BT5oVp76.mjs +132 -0
- package/dist/chunks/auth-BT5oVp76.mjs.map +1 -0
- package/dist/chunks/auth-CYOh60KG.mjs +93 -0
- package/dist/chunks/auth-CYOh60KG.mjs.map +1 -0
- package/dist/chunks/brainstorm-BwKA6yZP.mjs +7 -0
- package/dist/chunks/brainstorm-BwKA6yZP.mjs.map +1 -0
- package/dist/chunks/cancel-KV_cpsqS.mjs +15 -0
- package/dist/chunks/cancel-KV_cpsqS.mjs.map +1 -0
- package/dist/chunks/canonical-C8UxeEmB.mjs +57 -0
- package/dist/chunks/canonical-C8UxeEmB.mjs.map +1 -0
- package/dist/chunks/catalogue-BvwSrM_j.mjs +1549 -0
- package/dist/chunks/catalogue-BvwSrM_j.mjs.map +1 -0
- package/dist/chunks/compose-Dvxunpto.mjs +7307 -0
- package/dist/chunks/compose-Dvxunpto.mjs.map +1 -0
- package/dist/chunks/config-DefHA2Lw.mjs +96 -0
- package/dist/chunks/config-DefHA2Lw.mjs.map +1 -0
- package/dist/chunks/contract-BkMjU1kR.mjs +295 -0
- package/dist/chunks/contract-BkMjU1kR.mjs.map +1 -0
- package/dist/chunks/contract-bQ9FJl4N.mjs +123 -0
- package/dist/chunks/contract-bQ9FJl4N.mjs.map +1 -0
- package/dist/chunks/deny-ClTxSvHJ.mjs +15 -0
- package/dist/chunks/deny-ClTxSvHJ.mjs.map +1 -0
- package/dist/chunks/diff-Qw0II0sj.mjs +101 -0
- package/dist/chunks/diff-Qw0II0sj.mjs.map +1 -0
- package/dist/chunks/discover-eS01-me1.mjs +21 -0
- package/dist/chunks/discover-eS01-me1.mjs.map +1 -0
- package/dist/chunks/doctor-B-H2UK5e.mjs +222 -0
- package/dist/chunks/doctor-B-H2UK5e.mjs.map +1 -0
- package/dist/chunks/fix-D4Tj8RVA.mjs +18 -0
- package/dist/chunks/fix-D4Tj8RVA.mjs.map +1 -0
- package/dist/chunks/gc-BBXlBF5w.mjs +161 -0
- package/dist/chunks/gc-BBXlBF5w.mjs.map +1 -0
- package/dist/chunks/init-BUnzIkeE.mjs +63 -0
- package/dist/chunks/init-BUnzIkeE.mjs.map +1 -0
- package/dist/chunks/inspect-Buby4cQD.mjs +22 -0
- package/dist/chunks/inspect-Buby4cQD.mjs.map +1 -0
- package/dist/chunks/logs-Giq5sUau.mjs +25 -0
- package/dist/chunks/logs-Giq5sUau.mjs.map +1 -0
- package/dist/chunks/migrate-DybihKzZ.mjs +33 -0
- package/dist/chunks/migrate-DybihKzZ.mjs.map +1 -0
- package/dist/chunks/models-Btp6X2YZ.mjs +24 -0
- package/dist/chunks/models-Btp6X2YZ.mjs.map +1 -0
- package/dist/chunks/pause-BASBfKLO.mjs +16 -0
- package/dist/chunks/pause-BASBfKLO.mjs.map +1 -0
- package/dist/chunks/policy-DUIgzF3W.mjs +139 -0
- package/dist/chunks/policy-DUIgzF3W.mjs.map +1 -0
- package/dist/chunks/providers-Dx78imKj.mjs +19 -0
- package/dist/chunks/providers-Dx78imKj.mjs.map +1 -0
- package/dist/chunks/reconcile-Bhy3IIYo.mjs +50 -0
- package/dist/chunks/reconcile-Bhy3IIYo.mjs.map +1 -0
- package/dist/chunks/render-DyZr5Lgi.mjs +53 -0
- package/dist/chunks/render-DyZr5Lgi.mjs.map +1 -0
- package/dist/chunks/resume-GJQRb2Eb.mjs +15 -0
- package/dist/chunks/resume-GJQRb2Eb.mjs.map +1 -0
- package/dist/chunks/retry-CLrUem1H.mjs +15 -0
- package/dist/chunks/retry-CLrUem1H.mjs.map +1 -0
- package/dist/chunks/review-BDdjb6kB.mjs +17 -0
- package/dist/chunks/review-BDdjb6kB.mjs.map +1 -0
- package/dist/chunks/run-CgTWYlcd.mjs +82 -0
- package/dist/chunks/run-CgTWYlcd.mjs.map +1 -0
- package/dist/chunks/run-tool-C3rAv4XF.mjs +26 -0
- package/dist/chunks/run-tool-C3rAv4XF.mjs.map +1 -0
- package/dist/chunks/scan-8Gy_B6kI.mjs +122 -0
- package/dist/chunks/scan-8Gy_B6kI.mjs.map +1 -0
- package/dist/chunks/schema-C9QbUW4H.mjs +578 -0
- package/dist/chunks/schema-C9QbUW4H.mjs.map +1 -0
- package/dist/chunks/send-BdnJ85Nz.mjs +19 -0
- package/dist/chunks/send-BdnJ85Nz.mjs.map +1 -0
- package/dist/chunks/ship-DTuLGoaJ.mjs +19 -0
- package/dist/chunks/ship-DTuLGoaJ.mjs.map +1 -0
- package/dist/chunks/shutdown-BM92Iyv2.mjs +15 -0
- package/dist/chunks/shutdown-BM92Iyv2.mjs.map +1 -0
- package/dist/chunks/skip-DZG5kpcH.mjs +18 -0
- package/dist/chunks/skip-DZG5kpcH.mjs.map +1 -0
- package/dist/chunks/spec-Bq0P3jVh.mjs +20 -0
- package/dist/chunks/spec-Bq0P3jVh.mjs.map +1 -0
- package/dist/chunks/src-CId6kMsY.mjs +1689 -0
- package/dist/chunks/src-CId6kMsY.mjs.map +1 -0
- package/dist/chunks/src-CfAOde7C.mjs +5403 -0
- package/dist/chunks/src-CfAOde7C.mjs.map +1 -0
- package/dist/chunks/src-CmFjh4M0.mjs +928 -0
- package/dist/chunks/src-CmFjh4M0.mjs.map +1 -0
- package/dist/chunks/src-Cu3TxNob.mjs +783 -0
- package/dist/chunks/src-Cu3TxNob.mjs.map +1 -0
- package/dist/chunks/src-DcU4IXMe.mjs +117 -0
- package/dist/chunks/src-DcU4IXMe.mjs.map +1 -0
- package/dist/chunks/src-s7YRvk0t.mjs +2116 -0
- package/dist/chunks/src-s7YRvk0t.mjs.map +1 -0
- package/dist/chunks/status-SMjiOMYy.mjs +29 -0
- package/dist/chunks/status-SMjiOMYy.mjs.map +1 -0
- package/dist/chunks/tail-BuhT-2PH.mjs +25 -0
- package/dist/chunks/tail-BuhT-2PH.mjs.map +1 -0
- package/dist/chunks/update-BXIppsbi.mjs +16 -0
- package/dist/chunks/update-BXIppsbi.mjs.map +1 -0
- package/dist/cli.mjs +175 -0
- package/dist/cli.mjs.map +1 -0
- package/package.json +17 -32
- package/CHANGELOG.md +0 -1461
- package/bin/cli.js +0 -817
- package/bin/report.js +0 -141
- package/core/adapter/render.js +0 -415
- package/core/agents/implementer.template.md +0 -142
- package/core/agents/profile-reader.md +0 -50
- package/core/agents/release.md +0 -58
- package/core/agents/review.md +0 -179
- package/core/commands/cohorte-align-ds.md +0 -33
- package/core/commands/cohorte-audit.md +0 -58
- package/core/commands/cohorte-brainstorm.md +0 -70
- package/core/commands/cohorte-build.md +0 -219
- package/core/commands/cohorte-doctor.md +0 -194
- package/core/commands/cohorte-fix.md +0 -80
- package/core/commands/cohorte-fleet.md +0 -103
- package/core/commands/cohorte-init-pipeline.md +0 -31
- package/core/commands/cohorte-intake.md +0 -92
- package/core/commands/cohorte-patch.md +0 -118
- package/core/commands/cohorte-refactor.md +0 -59
- package/core/commands/cohorte-retro.md +0 -85
- package/core/commands/cohorte-review.md +0 -270
- package/core/commands/cohorte-ship.md +0 -122
- package/core/commands/cohorte-spec.md +0 -101
- package/core/commands/cohorte-update-pipeline.md +0 -165
- package/core/hooks/gate.py +0 -588
- package/core/runtimes/claude.json +0 -74
- package/core/runtimes/codex.json +0 -85
- package/core/runtimes/cursor.json +0 -76
- package/core/runtimes/gemini.json +0 -76
- package/core/runtimes/opencode.json +0 -73
- package/core/templates/agent-handoff.md +0 -34
- package/core/templates/brainstorm-return.md +0 -36
- package/core/templates/decisions.template.md +0 -42
- package/core/templates/design-brief.md +0 -44
- package/core/templates/patch.template.md +0 -86
- package/core/templates/pr-body.md +0 -25
- package/core/templates/review-feedback.md +0 -38
- package/core/templates/spec.template.md +0 -87
- package/core/templates/steps/init-pipeline/01-detect-stack.md +0 -44
- package/core/templates/steps/init-pipeline/02-interview-gaps.md +0 -55
- package/core/templates/steps/init-pipeline/03-draft-profile.md +0 -10
- package/core/templates/steps/init-pipeline/04-write-render.md +0 -145
- package/core/templates/steps/init-pipeline/05-report.md +0 -12
- package/core/workflows/audit.js +0 -240
- package/core/workflows/loop.js +0 -641
- package/core/workflows/refactor.js +0 -276
- package/core/workflows/review.js +0 -456
- package/install.ps1 +0 -103
- package/install.sh +0 -114
- package/lib/doctor.js +0 -534
- package/lib/runtime.js +0 -139
- package/lib/versions.js +0 -149
- package/lib/yaml.js +0 -129
- package/profile/PIPELINE.template.md +0 -259
- package/profile/SCHEMA.md +0 -735
- package/profile/cohorte.config.template.yaml +0 -43
- package/scripts/assert-gate-hook.mjs +0 -75
- package/scripts/kanban-move.sh +0 -313
- package/scripts/metrics/collect.mjs +0 -531
- package/scripts/metrics/prices.json +0 -42
- package/scripts/new-feature.sh.template +0 -98
- package/scripts/preflight.sh +0 -124
- package/scripts/remove-feature.sh.template +0 -56
- package/scripts/test-adapter.mjs +0 -437
- package/scripts/test-gate.mjs +0 -443
- package/scripts/test-kanban.mjs +0 -304
- package/scripts/test-lib.mjs +0 -356
- package/scripts/test-metrics.mjs +0 -156
- package/scripts/test-workflows.mjs +0 -758
- package/scripts/validate-core.mjs +0 -325
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compose-Dvxunpto.mjs","names":["asJson","usage","strict","count","parseYaml","yes","no","partial","readVerified","canonical","canonical","WORKTREE_PREFIX","parse"],"sources":["../../../../packages/core/src/integration/index.ts","../../../../packages/core/src/resume/verifiers.ts","../../../../packages/core/src/agents/supervisor/map.ts","../../../../packages/persistence/src/sqlite/driver.ts","../../../../packages/persistence/src/records.ts","../../../../packages/persistence/src/contract.ts","../../../../packages/persistence/src/memory/chain.ts","../../../../packages/persistence/src/migrate/index.ts","../../../../packages/persistence/src/sqlite/marshal.ts","../../../../packages/persistence/src/sqlite/commands.ts","../../../../packages/persistence/src/sqlite/tx.ts","../../../../packages/persistence/src/sqlite/store.ts","../../../../packages/runtime-fake/src/script/builder.ts","../../../../packages/runtime-fake/src/script/match.ts","../../../../packages/runtime-fake/src/script/schema.ts","../../../../packages/runtime-fake/src/script/parse.ts","../../../../packages/runtime-fake/src/fake/agent.ts","../../../../packages/runtime-fake/src/fake/capabilities.ts","../../../../packages/runtime-fake/src/fake/runtime.ts","../../../../packages/runtime-fake/src/fake/index.ts","../../../../packages/runtime-pi/src/classify/index.ts","../../../../packages/runtime-pi/src/pin/pin.ts","../../../../packages/runtime-pi/src/classify/host.ts","../../../../packages/runtime-pi/src/parent/env.ts","../../../../packages/runtime-pi/src/parent/output.ts","../../../../packages/runtime-pi/src/protocol.ts","../../../../packages/runtime-pi/src/parent/transport.ts","../../../../packages/runtime-pi/src/parent/session.ts","../../../../packages/runtime-pi/src/parent/auth.ts","../../../../packages/runtime-pi/src/parent/defaults.ts","../../../../packages/runtime-pi/src/parent/capabilities.ts","../../../../packages/runtime-pi/src/parent/runtime.ts","../../../../packages/runtime-pi/src/parent/index.ts","../../../../apps/cli/src/assets/index.ts","../../../../apps/cli/src/control/index.ts","../../../../apps/cli/src/pin/index.ts","../../../../apps/cli/src/host/index.ts","../../../../apps/cli/src/observe/index.ts","../../../../packages/git/src/contract.ts","../../../../packages/git/src/impl/nul-split.ts","../../../../packages/git/src/impl/runner.ts","../../../../packages/git/src/impl/tree-digest.ts","../../../../packages/git/src/impl/commits.ts","../../../../packages/git/src/impl/version.ts","../../../../packages/git/src/impl/facts.ts","../../../../packages/git/src/impl/merge.ts","../../../../packages/git/src/impl/status.ts","../../../../packages/git/src/impl/worktrees.ts","../../../../packages/git/src/impl/index.ts","../../../../packages/persistence/src/blob/index.ts","../../../../packages/persistence/src/spool/index.ts","../../../../packages/tools/src/registry/index.ts","../../../../packages/tools/src/workspace/index.ts","../../../../apps/cli/src/compose/engine.ts","../../../../apps/cli/src/compose/index.ts"],"sourcesContent":["// @cohorte/core/integration — Git-backed commit and merge services.\nimport type { CanonicalPath } from '@cohorte/git/contract';\nimport type { IntegrationDeps, IntegrationService } from '../contract/factories.ts';\n\nexport type { IntegrationDeps, IntegrationService };\n\nconst asPath = (value: string): CanonicalPath => value as CanonicalPath;\n\nexport function createIntegrationService(deps: IntegrationDeps): IntegrationService {\n return {\n async commit(slot, kind, paths = ['.']) {\n const result = await deps.git.commitAll({\n worktree: asPath(slot),\n message: kind === 'checkpoint' ? 'chore(cohorte): checkpoint' : 'chore(cohorte): apply agent result',\n trailers: { 'Cohorte-Managed': 'true', 'Cohorte-Commit-Kind': kind },\n identity: { name: 'Cohorte', email: 'cohorte@localhost' },\n paths,\n });\n if ('kind' in result) return result;\n return { sha: result.sha, treeDigest: result.treeDigest };\n },\n\n async merge(fromSlot, intoSlot) {\n const fromFacts = await deps.git.facts(asPath(fromSlot));\n const intoFacts = await deps.git.facts(asPath(intoSlot));\n if (fromFacts.head.kind === 'unborn' || intoFacts.head.kind === 'unborn') {\n return { kind: 'conflict', files: [] };\n }\n const merged = await deps.git.mergeTree(fromFacts.commonDir, intoFacts.head.sha, fromFacts.head.sha);\n if (!merged.clean) return { kind: 'conflict', files: merged.files };\n const mergeSha = await deps.git.commitTree(\n fromFacts.commonDir,\n merged.tree,\n [intoFacts.head.sha, fromFacts.head.sha],\n 'chore(cohorte): merge agent result',\n { 'Cohorte-Managed': 'true' },\n );\n const ref = intoFacts.head.kind === 'branch' ? `refs/heads/${intoFacts.head.name}` : 'HEAD';\n const moved = await deps.git.updateRefCas(fromFacts.commonDir, ref, mergeSha, intoFacts.head.sha);\n if (moved === 'moved') return { kind: 'conflict', files: [] };\n return { mergeSha, treeDigest: merged.tree };\n },\n };\n}\n","// DESIGN 4.1 (the effect-kind table) — the nine BUILT-IN `EffectVerifier`s this unit's plan entry lists as a\n// deliverable (\"Built-in verifiers that need only ports\"): `git.branch.create`, `git.ref.create`,\n// `git.worktree.add`, `git.commit` (trailer), `git.merge` (CAS head), `git.worktree.reset`, `provision.command`\n// (marker), `agent.spawn` (nonce sweep), `fs.snapshot.materialize`.\n//\n// DEVIATION (docs/v3/requests/U1.10.md, item D3): DESIGN 4.1's per-kind table names the DATA a verifier reads at\n// intent (\"target sha\", \"path, branch, base sha\", \"marker path\", \"host nonce\", \"manifest digest\") but the actual\n// `perform()` that WRITES `EffectIntent.verify` for each of these kinds belongs to a LATER unit (worktrees/git\n// effects: Wave 2/3; provisioning: Wave 2; agent spawn: Wave 3's supervisor) that has not run yet — there is no\n// existing producer to read the exact wire shape from. This file freezes the smallest consistent JSON shape for\n// each kind's `verify` payload (documented per verifier below) and reads it directly off `EffectRecord.verify`\n// (already `SealedJson`, i.e. `JsonValue`-shaped — reading a field off an already-sealed value mints nothing, so\n// check-layers rule f, \"only the redactor mints Sealed<T>\", does not apply). The request file asks the units that\n// eventually author these `perform()` bodies to match this shape, or to tell the integrator why not.\n//\n// DEVIATION (D4): `GitPort` (frozen, `@cohorte/git/contract`, U1.05) has no generic \"read a ref\" primitive — only\n// `facts()` (per-worktree HEAD + branch), `findCommitByTrailer()` and CAS/create operations. `git.branch.create`\n// and `git.ref.create` can therefore only be READ when the ref happens to be a worktree's own branch (through\n// `facts()`). Absence of the ref from `facts().worktrees` proves nothing — a bare ref (a review ref, say) is simply\n// invisible to this port — so that case is `in-doubt`, never `not-done`: `not-done` would make the resume\n// orchestration mark the effect `failed(interrupted)` and the ref-create would be blindly re-executed. This\n// verifier therefore never answers `not-done`; DESIGN 4.1's row has no \"not-done\" column for these two kinds\n// either (\"ref at sha ⇒ done; elsewhere ⇒ conflict ⇒ BLOCKED\"), and an `EffectVerifier` cannot itself raise the\n// BLOCKED — only 'done' | 'not-done' | 'in-doubt' — so the conflict is surfaced as `in-doubt` for a human.\n\nimport type { EffectId, Sha256 } from '@cohorte/base';\nimport type { CanonicalPath, GitPort } from '@cohorte/git/contract';\nimport type { EffectKind, EffectRecord } from '@cohorte/persistence/contract';\nimport type { Provisioner } from '../contract/internal.ts';\nimport type { EffectVerifier, EffectVerifierRegistry, ProcessSweeper } from '../contract/ports.ts';\n\nexport interface BuiltinVerifierDeps {\n git: GitPort;\n provisioner: Provisioner;\n sweeper: ProcessSweeper;\n /** The run's OWN stored snapshot digest (`RunRecord.snapshotDigest`, written by the T04 transaction), supplied by\n * whoever builds this registry — `fs.snapshot.materialize`'s verifier compares the intent's recorded\n * `manifestDigest` against it. Absent (or `undefined`) ⇒ that verifier can decide nothing and answers `in-doubt`:\n * comparing two fields of the same sealed intent payload would verify nothing about the world. */\n runSnapshotDigest?: () => Sha256 | undefined;\n}\n\n/** What `createBuiltinEffectVerifiers` reports ON TOP of the frozen `EffectVerifierRegistry`: the effects whose\n * VERIFICATION was itself the re-execution DESIGN 4.1 prescribes. `provision.command`'s probe IS\n * `Provisioner.ensure(slot)`, which re-provisions when the marker is missing — so by the time the verifier answers\n * `'done'`, the work has either been found in place (`reused`) or just been redone (`fresh`). The verdict is the\n * same (`done`: nothing must re-execute afterwards); only the REPORT differs, and `ResumeReport.effects[].verdict`\n * distinguishes them as `'done'` vs `'re-executed'`. The resume orchestration reads this through a duck-typed\n * narrowing, so a registry that does not implement it (any composed or foreign registry) simply reports `'done'`. */\nexport interface ReExecutionLog {\n reExecuted(effectId: EffectId): boolean;\n}\n\nexport type BuiltinEffectVerifiers = EffectVerifierRegistry & ReExecutionLog;\n\ntype Verdict = 'done' | 'not-done' | 'in-doubt';\n\nfunction asJson(sealed: EffectRecord['verify']): Record<string, unknown> {\n const value = sealed as unknown;\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : {};\n}\n\nfunction str(payload: Record<string, unknown>, key: string): string | undefined {\n const value = payload[key];\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction num(payload: Record<string, unknown>, key: string): number | undefined {\n const value = payload[key];\n return typeof value === 'number' ? value : undefined;\n}\n\n/** `git.branch.create` / `git.ref.create` — `verify: { repo: string; ref: string; targetSha: string }`. `ref` is\n * read only when it names a worktree's own branch (the only case `facts()` can answer): at the target sha ⇒ `done`,\n * elsewhere ⇒ the DESIGN table's \"conflict\", surfaced as `in-doubt`. A ref NO worktree carries cannot be read\n * through this port at all — absence from `facts()` is not proof of absence in the repository — so it is `in-doubt`\n * too, never `not-done` (D4: `not-done` would have the caller re-execute the ref-create blindly). */\nfunction refVerifier(git: GitPort): EffectVerifier {\n return {\n async verify(record: EffectRecord): Promise<Verdict> {\n const payload = asJson(record.verify);\n const repo = str(payload, 'repo');\n const ref = str(payload, 'ref');\n const targetSha = str(payload, 'targetSha');\n if (!repo || !ref || !targetSha) return 'in-doubt';\n const facts = await git.facts(repo as CanonicalPath);\n const branch = facts.worktrees.find((w) => w.branch === ref);\n if (!branch) return 'in-doubt';\n return branch.head === targetSha ? 'done' : 'in-doubt';\n },\n };\n}\n\n/** `git.worktree.add` — `verify: { repo: string; path: string; branch: string; baseSha: string }`. DESIGN: \"exact\n * whole-line match in `worktree list --porcelain -z` ⇒ done; dir without registration ⇒ remove dir + prune, redo\" —\n * the remove+prune half is a re-execution this verifier cannot itself perform (it only reports a verdict); the\n * caller (the reconciliation step) redoes it by marking the effect `failed(interrupted)` so the next incarnation\n * reissues `git.worktree.add` under the same key. */\nfunction worktreeAddVerifier(git: GitPort): EffectVerifier {\n return {\n async verify(record: EffectRecord): Promise<Verdict> {\n const payload = asJson(record.verify);\n const repo = str(payload, 'repo');\n const path = str(payload, 'path');\n const branch = str(payload, 'branch');\n if (!repo || !path || !branch) return 'in-doubt';\n const facts = await git.facts(repo as CanonicalPath);\n const registered = facts.worktrees.find((w) => w.path === path);\n if (!registered) return 'not-done';\n return registered.branch === branch ? 'done' : 'in-doubt';\n },\n };\n}\n\n/** `git.commit` — `verify: { repo: string; branch: string; key: string }`. DESIGN: \"findCommitByTrailer\n * (Cohorte-Effect: <key>) ⇒ done; else redo (add + commit is content-idempotent)\". */\nfunction commitVerifier(git: GitPort): EffectVerifier {\n return {\n async verify(record: EffectRecord): Promise<Verdict> {\n const payload = asJson(record.verify);\n const repo = str(payload, 'repo');\n const branch = str(payload, 'branch');\n const key = str(payload, 'key');\n if (!repo || !branch || !key) return 'in-doubt';\n const sha = await git.findCommitByTrailer(repo as CanonicalPath, branch, 'Cohorte-Effect', key);\n return sha ? 'done' : 'not-done';\n },\n };\n}\n\n/** `git.merge` — `verify: { repo: string; into: string; key: string; expectedOldHead: string }`. DESIGN: \"CAS\n * already applied (head carries the trailer) ⇒ done; head == old ⇒ redo; anything else ⇒ unexpected-repo-change\" —\n * the trailer check reuses `git.commit`'s mechanism (merges are committed with the same `Cohorte-Effect` trailer,\n * DESIGN 4.1's own `git.commit` row: \"add + commit is content-idempotent\"); the \"anything else\" branch (a THIRD\n * party moved the ref) is reported `in-doubt` rather than a verdict this port can turn into `unexpected-repo-change`\n * itself — the ledger audit of step 8 (`WorktreeService.audit`) is what actually raises that stop. */\nfunction mergeVerifier(git: GitPort): EffectVerifier {\n return {\n async verify(record: EffectRecord): Promise<Verdict> {\n const payload = asJson(record.verify);\n const repo = str(payload, 'repo');\n const into = str(payload, 'into');\n const key = str(payload, 'key');\n const expectedOldHead = str(payload, 'expectedOldHead');\n if (!repo || !into || !key) return 'in-doubt';\n const sha = await git.findCommitByTrailer(repo as CanonicalPath, into, 'Cohorte-Effect', key);\n if (sha) return 'done';\n if (!expectedOldHead) return 'in-doubt';\n const facts = await git.facts(repo as CanonicalPath);\n const worktree = facts.worktrees.find((w) => w.branch === into);\n if (worktree?.head === expectedOldHead) return 'not-done';\n return 'in-doubt';\n },\n };\n}\n\n/** `git.worktree.reset` — `verify: { repo: string; path: string; checkpointSha: string }`. DESIGN: \"HEAD ==\n * checkpoint and clean ⇒ done; else redo\". */\nfunction worktreeResetVerifier(git: GitPort): EffectVerifier {\n return {\n async verify(record: EffectRecord): Promise<Verdict> {\n const payload = asJson(record.verify);\n const repo = str(payload, 'repo');\n const path = str(payload, 'path');\n const checkpointSha = str(payload, 'checkpointSha');\n if (!repo || !path || !checkpointSha) return 'in-doubt';\n const facts = await git.facts(repo as CanonicalPath);\n const worktree = facts.worktrees.find((w) => w.path === path);\n if (!worktree || worktree.head !== checkpointSha) return 'not-done';\n const changed = await git.changedPaths(path as CanonicalPath);\n return changed.length === 0 ? 'done' : 'not-done';\n },\n };\n}\n\n/** `provision.command` — `verify: { slot: string }`. DESIGN: \"marker `<gitdir>/cohorte-provision-<key>` present ⇒\n * done; else re-run\". `Provisioner.ensure(slot)` IS both halves at once: `'reused'` means the marker was found and\n * nothing re-ran (the effect had completed before the crash); `'fresh'` means `ensure` just re-provisioned — which\n * is exactly the \"re-run\" DESIGN asks for, already performed. Either way the effect is now done in the world, so\n * the verdict is `'done'` in both cases; answering `'not-done'` for `'fresh'` would have the caller record\n * `failed(interrupted)` and provision a THIRD time. Which of the two happened is reported through `ReExecutionLog`\n * (`'fresh'` ⇒ `ResumeReport.effects[].verdict === 're-executed'`, `'reused'` ⇒ `'done'`). */\nfunction provisionVerifier(provisioner: Provisioner, markReExecuted: (id: EffectId) => void): EffectVerifier {\n return {\n async verify(record: EffectRecord): Promise<Verdict> {\n const payload = asJson(record.verify);\n const slot = str(payload, 'slot') ?? record.slot;\n if (!slot) return 'in-doubt';\n const outcome = await provisioner.ensure(slot);\n if (outcome === 'fresh') markReExecuted(record.effectId);\n return 'done';\n },\n };\n}\n\n/** `agent.spawn` — `verify: { pid: number; startToken: string; nonce: string }`. DESIGN: \"child already dead (IPC\n * disconnect); sweep (pid, startToken) and the nonce in its argv; mark orphaned; plan incarnation+1 of the same\n * attempt.\" `nonce` is recorded for the orphan-sweep step (5) to match against `argv`, which this port cannot read\n * (`ProcessSweeper` only takes `(pid, startToken)`, DESIGN 4.4 step 5's own wording): this verifier reports whether\n * the child is alive; step 5 (not this verifier) is what actually sweeps and records the nonce match in the report. */\nfunction agentSpawnVerifier(sweeper: ProcessSweeper): EffectVerifier {\n return {\n verify(record: EffectRecord): Promise<Verdict> {\n const payload = asJson(record.verify);\n const pid = num(payload, 'pid');\n const startToken = str(payload, 'startToken');\n if (pid === undefined || !startToken) return Promise.resolve('in-doubt');\n return Promise.resolve(sweeper.isAlive(pid, startToken) ? 'done' : 'not-done');\n },\n };\n}\n\n/** `fs.snapshot.materialize` — `verify: { manifestDigest: string }`. DESIGN: \"content-addressed: re-put missing\n * blobs, compare digest; mismatch ⇒ refuse (`corruption/snapshot-hash`)\". This port set has no `BlobStore` to re-put\n * missing blobs with (D3), so the check this verifier really performs is the digest comparison alone: the intent's\n * recorded `manifestDigest` against the digest the RUN itself stores (`RunRecord.snapshotDigest`, written by the\n * T04 transaction), handed in by whoever builds the registry through `BuiltinVerifierDeps.runSnapshotDigest`. A\n * match is the content-addressed proof DESIGN asks for; a mismatch, and every case where the run's digest is not\n * available, is `in-doubt` rather than a guessed `corruption/*` throw (only the caller, which is mid-recovery and\n * can refuse the whole run, should turn that into a stop). Both operands must come from DIFFERENT producers or the\n * comparison proves nothing — which is why the run's digest is a dependency and not a second field of `verify`. */\nfunction snapshotVerifier(runSnapshotDigest: (() => Sha256 | undefined) | undefined): EffectVerifier {\n return {\n verify(record: EffectRecord, _signal: AbortSignal): Promise<Verdict> {\n void _signal;\n const payload = asJson(record.verify);\n const digest = str(payload, 'manifestDigest');\n const stored = runSnapshotDigest?.();\n if (!digest || stored === undefined) return Promise.resolve('in-doubt');\n return Promise.resolve(digest === stored ? 'done' : 'in-doubt');\n },\n };\n}\n\nconst BUILTIN_KINDS = [\n 'git.branch.create',\n 'git.ref.create',\n 'git.worktree.add',\n 'git.commit',\n 'git.merge',\n 'git.worktree.reset',\n 'provision.command',\n 'agent.spawn',\n 'fs.snapshot.materialize',\n] as const satisfies readonly EffectKind[];\n\n/** Registers the nine built-in verifiers DESIGN 4.1 lists as needing \"only ports\". Any OTHER kind (the tool\n * effects: `tool.write_file`, `tool.patch_file`, `tool.run_command`, `check.command`, ...) is registered by whoever\n * owns that kind's `perform()` (Wave 2's tools/toolhost units) — this registry answers `undefined` for them, and\n * the resume orchestration treats an unregistered kind as `in-doubt` (never a blind re-execution). A caller that\n * owns more kinds composes them with `{ get: (kind) => builtin.get(kind) ?? theirs.get(kind) }` (and forwards\n * `reExecuted` if it wants `'re-executed'` verdicts to survive the composition). */\nexport function createBuiltinEffectVerifiers(deps: BuiltinVerifierDeps): BuiltinEffectVerifiers {\n const reExecuted = new Set<EffectId>();\n const table: Readonly<Record<(typeof BUILTIN_KINDS)[number], EffectVerifier>> = {\n 'git.branch.create': refVerifier(deps.git),\n 'git.ref.create': refVerifier(deps.git),\n 'git.worktree.add': worktreeAddVerifier(deps.git),\n 'git.commit': commitVerifier(deps.git),\n 'git.merge': mergeVerifier(deps.git),\n 'git.worktree.reset': worktreeResetVerifier(deps.git),\n 'provision.command': provisionVerifier(deps.provisioner, (id) => reExecuted.add(id)),\n 'agent.spawn': agentSpawnVerifier(deps.sweeper),\n 'fs.snapshot.materialize': snapshotVerifier(deps.runSnapshotDigest),\n };\n return {\n get(kind: EffectKind): EffectVerifier | undefined {\n return (table as Readonly<Record<string, EffectVerifier>>)[kind];\n },\n reExecuted(effectId: EffectId): boolean {\n return reExecuted.has(effectId);\n },\n };\n}\n","import type { AuthMode, JsonValue } from '@cohorte/base';\nimport type { AgentRef, EphemeralEventType, EventType, PhaseRef } from '@cohorte/protocol';\nimport type { EphemeralRuntimeEvent, RuntimeEvent, RuntimeEventType } from '@cohorte/runtime-contract';\nimport type { EphemeralInput, EventDraftInput } from '../../contract/types.ts';\n\nexport interface RuntimeEventMapperContext {\n agent?: AgentRef;\n phase?: PhaseRef;\n expectedAuthMode?: AuthMode;\n monetaryCost?: JsonValue;\n}\n\nexport type MappedRuntimeEvent =\n | { durability: 'durable'; draft: EventDraftInput }\n | { durability: 'ephemeral'; draft: EphemeralInput };\n\nconst asJson = (value: unknown): JsonValue => value as JsonValue;\n\nfunction defaultAgent(event: RuntimeEvent): AgentRef {\n return {\n agentId: event.agentId,\n role: 'unknown',\n incarnation: event.incarnation,\n attempt: 1,\n };\n}\n\nfunction common(event: RuntimeEvent, context: RuntimeEventMapperContext): Pick<EventDraftInput, 'phase' | 'agent'> {\n return {\n ...(context.phase === undefined ? {} : { phase: context.phase }),\n agent: context.agent ?? defaultAgent(event),\n };\n}\n\nfunction durable<T extends EventType>(\n event: RuntimeEvent,\n type: T,\n payload: JsonValue,\n context: RuntimeEventMapperContext,\n): MappedRuntimeEvent {\n return {\n durability: 'durable',\n draft: {\n type,\n payload,\n source: 'runtime',\n summary: type,\n ...common(event, context),\n },\n };\n}\n\nfunction ephemeral<T extends EphemeralEventType>(\n event: EphemeralRuntimeEvent,\n type: T,\n payload: JsonValue,\n context: RuntimeEventMapperContext,\n): MappedRuntimeEvent {\n return {\n durability: 'ephemeral',\n draft: {\n type: type as EphemeralInput['type'],\n payload,\n source: 'runtime',\n severity: 'progress',\n ...(context.phase === undefined ? {} : { phase: context.phase }),\n agent: context.agent ?? defaultAgent(event),\n },\n };\n}\n\n/** Maps one runtime event. `agent.exited` is intentionally left to the supervisor because it needs the accepted\n * structured result to choose `agent.completed` versus `agent.failed`. `tool.call.delivered` is folded into the\n * tool completion by the host and therefore never becomes a second durable event. */\nexport function mapRuntimeEvent(\n event: RuntimeEvent,\n context: RuntimeEventMapperContext = {},\n): MappedRuntimeEvent | null {\n switch (event.type) {\n case 'agent.spawned':\n return durable(\n event,\n 'agent.spawned',\n asJson({\n agent: context.agent ?? defaultAgent(event),\n tools: event.data.tools,\n systemPromptSha256: event.data.systemPromptSha256,\n effectiveSystemPromptSha256: event.data.effectiveSystemPromptSha256,\n authMode: context.expectedAuthMode ?? 'subscription',\n isolation: {\n level: event.data.isolation.level === 'os' ? 'L1-os' : 'L0-process',\n backend:\n event.data.isolation.backend === 'seatbelt' || event.data.isolation.backend === 'bubblewrap'\n ? event.data.isolation.backend\n : 'none',\n filesystem: event.data.isolation.filesystem === 'enforced' ? 'enforced' : 'advisory',\n network: event.data.isolation.network === 'enforced' ? 'enforced-off' : 'unenforced',\n },\n }),\n context,\n );\n case 'agent.started':\n return durable(\n event,\n 'agent.started',\n asJson({ agent: context.agent ?? defaultAgent(event), taskSha256: event.data.taskSha256 }),\n context,\n );\n case 'agent.turn.started':\n return ephemeral(event, 'agent.turn.started', asJson(event.data), context);\n case 'agent.turn.completed':\n return durable(event, 'agent.turn.completed', asJson(event.data), context);\n case 'agent.message.started':\n return ephemeral(event, 'agent.message.started', asJson(event.data), context);\n case 'agent.message.delta':\n return ephemeral(event, 'agent.message.delta', asJson(event.data), context);\n case 'agent.message.completed': {\n const { textBytes, ...data } = event.data;\n return durable(event, 'agent.message.completed', asJson({ ...data, bytes: textBytes }), context);\n }\n case 'agent.message.accepted':\n return durable(\n event,\n 'agent.message.accepted',\n asJson({ agent: context.agent ?? defaultAgent(event), ...event.data }),\n context,\n );\n case 'model.requested':\n return durable(\n event,\n 'model.requested',\n asJson({ ...event.data, expectedAuthMode: context.expectedAuthMode ?? 'subscription' }),\n context,\n );\n case 'model.responded':\n return durable(\n event,\n 'model.responded',\n asJson({\n requestId: event.data.requestId,\n requestedModel: event.data.requestedModel,\n effectiveModel: event.data.effectiveModel,\n authMode: event.data.authMode,\n authSource: event.data.authSource,\n status: event.data.error === undefined ? 'ok' : 'error',\n ...(event.data.httpStatus === undefined ? {} : { httpStatus: event.data.httpStatus }),\n durationMs: event.data.durationMs,\n tokens: event.data.usage,\n monetaryCost: context.monetaryCost ?? 'not_applicable',\n quota: event.data.quota,\n attempt: event.data.attempt,\n ...(event.data.error === undefined ? {} : { error: event.data.error }),\n }),\n context,\n );\n case 'tool.call.rejected':\n return durable(event, 'tool.rejected', asJson(event.data), context);\n case 'tool.call.progress':\n return ephemeral(\n event,\n 'tool.progress',\n asJson({ toolCallId: event.data.toolCallId, ...event.data.update }),\n context,\n );\n case 'tool.call.requested':\n case 'tool.call.delivered':\n case 'agent.exited':\n return null;\n case 'agent.paused':\n return durable(\n event,\n 'agent.state.changed',\n asJson({\n agent: context.agent ?? defaultAgent(event),\n from: 'running',\n to: 'paused',\n reason: 'paused',\n pausedAt: event.data.at,\n attemptConsumed: false,\n }),\n context,\n );\n case 'agent.resumed':\n return durable(\n event,\n 'agent.state.changed',\n asJson({\n agent: context.agent ?? defaultAgent(event),\n from: 'paused',\n to: 'running',\n reason: 'resumed',\n attemptConsumed: false,\n }),\n context,\n );\n case 'runtime.warning':\n return durable(\n event,\n 'runtime.warning',\n asJson({ agent: context.agent ?? defaultAgent(event), ...event.data }),\n context,\n );\n }\n}\n\nexport function runtimeEventTypesHandledByMapper(): readonly RuntimeEventType[] {\n return [\n 'agent.spawned',\n 'agent.started',\n 'agent.turn.started',\n 'agent.turn.completed',\n 'agent.message.started',\n 'agent.message.delta',\n 'agent.message.completed',\n 'agent.message.accepted',\n 'model.requested',\n 'model.responded',\n 'tool.call.rejected',\n 'tool.call.progress',\n 'agent.paused',\n 'agent.resumed',\n 'runtime.warning',\n ];\n}\n","// The default `SqlDriver` over `node:sqlite` (ADR-0002). Kept narrow on purpose (DESIGN 2.4 \"Location\" + toolchain\n// understanding §2): everything above this file talks to `SqlDriver` only, so `better-sqlite3` is a drop-in.\n\nimport { dirname, join } from 'node:path';\nimport { DatabaseSync } from 'node:sqlite';\nimport { fileURLToPath } from 'node:url';\nimport type { SqlDriver } from '../contract.ts';\n\nconst HERE = dirname(fileURLToPath(import.meta.url));\n/** `<repo root>/migrations/state`, the embedded default (F-2 / DESIGN 2.4 DDL). Four levels up from `src/sqlite/`. */\nexport const DEFAULT_MIGRATIONS_DIR = join(HERE, '..', '..', '..', '..', 'migrations', 'state');\n\n/**\n * Opens `path` (or `:memory:`) with the pragmas DESIGN 2.4 \"Location\" names: `journal_mode=WAL synchronous=FULL\n * foreign_keys=ON trusted_schema=OFF busy_timeout=5000`, plus `enableDefensive(true)`. Writers always `BEGIN\n * IMMEDIATE` (asserted by the caller, not here: this driver only executes what it is given).\n */\nexport function createNodeSqliteDriver(path: string): SqlDriver {\n const db = new DatabaseSync(path, { open: true, enableForeignKeyConstraints: true, timeout: 5000 });\n db.exec('PRAGMA journal_mode=WAL');\n db.exec('PRAGMA synchronous=FULL');\n db.exec('PRAGMA foreign_keys=ON');\n db.exec('PRAGMA trusted_schema=OFF');\n db.exec('PRAGMA busy_timeout=5000');\n db.enableDefensive(true);\n return {\n exec: (sql: string): void => {\n db.exec(sql);\n },\n prepare: (sql: string) => {\n const statement = db.prepare(sql);\n return {\n run: (...parameters: unknown[]) => statement.run(...(parameters as never[])),\n get: (...parameters: unknown[]) => statement.get(...(parameters as never[])),\n all: (...parameters: unknown[]) => statement.all(...(parameters as never[])),\n };\n },\n close: (): void => {\n db.close();\n },\n };\n}\n","// Record types of the state store (DESIGN 2.4): ONE interface per table of migrations/state/0001_init.sql, and the\n// column <-> key map that keeps the two column-for-column equal. A nullable column is an optional key; a `*_json`\n// column is a structured key; a 0/1 INTEGER is a boolean. Nothing here behaves: the stores do.\nimport type {\n AgentId,\n ApprovalId,\n ArtifactId,\n AuthMode,\n BudgetCounters,\n CommandId,\n EffectId,\n ErrorInfo,\n EventId,\n FindingId,\n IsoInstant,\n JsonValue,\n ModelRef,\n PhaseRunId,\n RunId,\n SealedJson,\n Sha256,\n SpecId,\n SurfaceId,\n ToolCallId,\n} from '@cohorte/base';\nimport type {\n ActivePipelineState,\n Actor,\n AgentState,\n CheckResult,\n CommandAuth,\n CommandEnvelope,\n GuardOutcome,\n NodeStatus,\n PipelineState,\n RunPlan,\n Severity,\n StopRecord,\n TransitionReason,\n} from '@cohorte/protocol';\n\n// ── vocabulary shared with contract.ts (declared here so that records never import the contract) ────────────────\nexport type ReplayClass = 'idempotent' | 'verifiable' | 'at-most-once';\nexport type EffectState = 'intent' | 'done' | 'failed' | 'in-doubt' | 'compensated';\nexport type EffectKind =\n | 'fs.snapshot.materialize'\n | 'git.branch.create'\n | 'git.ref.create'\n | 'git.worktree.add'\n | 'git.worktree.remove'\n | 'git.worktree.reset'\n | 'git.commit'\n | 'git.merge'\n | 'provision.command'\n | 'check.command'\n | 'agent.spawn'\n | 'tool.read'\n | 'tool.write_file'\n | 'tool.patch_file'\n | 'tool.run_command'\n | 'tool.network_request'\n | 'tool.git_commit';\nexport type LockScope = 'project' | 'zone' | 'run' | 'integration' | 'slot' | 'migration';\nexport type LockMode = 'shared' | 'exclusive';\nexport type ApprovalStatus = 'pending' | 'allow-once' | 'allow-for-run' | 'deny' | 'expired' | 'superseded';\nexport type CommandStatus = 'pending' | 'claimed' | 'completed' | 'rejected';\nexport type WorktreeState = 'intent' | 'ready' | 'held' | 'in-doubt' | 'quarantined' | 'removed';\n\n/** The pre-state an effect is bound to (4.1, 4.5). */\nexport interface EffectPreState {\n checkpointSha?: string;\n ledgerSha256?: Sha256;\n beforeSha256?: Sha256;\n /** the grant binding of an asked COMMAND (4.5) */\n treeDigest?: string;\n}\n\n// ── one record per table ────────────────────────────────────────────────────────────────────────────────────────\nexport interface MigrationRecord {\n id: number;\n name: string;\n sha256: Sha256;\n appliedAt: IsoInstant;\n cohorteVersion: string;\n}\n\nexport interface MetaRecord {\n key: string;\n value: string;\n}\n\n/** The six keys marked (*) are absent while the run is IDLE: only the host can compute them, in the T04 transaction. */\nexport interface RunRecord {\n runId: RunId;\n /** open: the known profiles are validated in TypeScript, not by the store (ADR-0018) */\n profile: string;\n tableVersion: number;\n specId: SpecId;\n specSha256: Sha256;\n title: string;\n state: PipelineState;\n resumeTo?: ActivePipelineState;\n stop?: StopRecord;\n lastError?: ErrorInfo;\n /** store-assigned by `appendEvents`, like `lastHash` and `version`: a `putRun` / `patchRun` never moves them */\n lastSequence: number;\n lastHash: string;\n version: number;\n /** (*) */\n snapshotDigest?: Sha256;\n /** (*) the RuntimePin of runtime-contract, opaque here */\n runtimePin?: JsonValue;\n /** (*) */\n plan?: RunPlan;\n pinnedInstallDir: string;\n baseBranch: string;\n /** (*) */\n baseSha?: string;\n /** (*) */\n integrationBranch?: string;\n integrationHead?: string;\n approvedTreeDigest?: string;\n skipWaivers?: JsonValue;\n /** (*) */\n zones?: string[];\n hostId?: string;\n hostPid?: number;\n hostStartToken?: string;\n hostHeartbeatAt?: IsoInstant;\n cancelRequested: boolean;\n pauseRequested: boolean;\n schemaVersion: number;\n cohorteVersion: string;\n purgeable: boolean;\n startedAt: IsoInstant;\n updatedAt: IsoInstant;\n endedAt?: IsoInstant;\n}\n\n/** One row of `events`: the projection columns plus the hashed unit. */\nexport interface EventRecord {\n runId: RunId;\n sequence: number;\n eventId: EventId;\n type: string;\n timestamp: IsoInstant;\n source: string;\n phaseRunId?: PhaseRunId;\n agentId?: AgentId;\n causationId?: string;\n severity: string;\n summary: string;\n /** the full SEALED envelope as canonical JSON */\n envelope: string;\n prevHash: string;\n /** sha256(prevHash || '\\n' || envelope) */\n hash: string;\n}\n\n/** spec 11.1: all eight fields. */\nexport interface TransitionRecord {\n transitionId: string;\n runId: RunId;\n defId: string;\n tableVersion: number;\n from: PipelineState;\n to: PipelineState;\n reason: TransitionReason;\n actor: Actor;\n guards: GuardOutcome[];\n effects: string[];\n idempotencyKey: string;\n eventId: EventId;\n}\n\nexport interface PhaseRecord {\n runId: RunId;\n phaseRunId: PhaseRunId;\n state: ActivePipelineState;\n iteration: number;\n status: NodeStatus;\n outcome?: string;\n checks: CheckResult[];\n startedAt?: IsoInstant;\n endedAt?: IsoInstant;\n}\n\nexport interface AgentRecord {\n runId: RunId;\n agentId: AgentId;\n phaseRunId: PhaseRunId;\n role: string;\n surface?: SurfaceId;\n label: string;\n state: AgentState;\n /** retries of the WORK: incremented by `failed -> retrying | escalated` and by nothing else (2.5.4) */\n attempt: number;\n /** runtime sessions */\n incarnation: number;\n maxAttempts: number;\n maxIncarnations: number;\n model: ModelRef;\n effectiveModel?: { provider: string; model: string };\n authMode?: AuthMode;\n slot?: string;\n contextSha256?: Sha256;\n grantsDigest?: Sha256;\n usage: BudgetCounters;\n summary?: string;\n lastError?: ErrorInfo;\n pendingApproval?: ApprovalId;\n runtimeRef?: JsonValue;\n createdAt: IsoInstant;\n updatedAt: IsoInstant;\n}\n\nexport interface IncarnationRecord {\n runId: RunId;\n agentId: AgentId;\n incarnation: number;\n attempt: number;\n /** open: owned by the agent supervisor */\n state: string;\n /** 'initial' | 'retry' | 'escalation' | a ReincarnateCause */\n cause?: string;\n pid?: number;\n startToken?: string;\n hostNonce?: string;\n runtimeRef?: JsonValue;\n stop?: string;\n reason?: string;\n usage?: BudgetCounters;\n startedAt?: IsoInstant;\n endedAt?: IsoInstant;\n}\n\nexport interface WorktreeRecord {\n runId: RunId;\n slot: string;\n path: string;\n branch?: string;\n baseSha: string;\n checkpointSha: string;\n lastTreeDigest?: string;\n lockfileSha256?: Sha256;\n provisionKey?: string;\n /** 5.7: digest of the provisioned dependency tree */\n depsManifestSha256?: Sha256;\n holderAgentId?: AgentId;\n state: WorktreeState;\n}\n\n/** A dirty path since the last Cohorte commit, with the content hash Cohorte expects (4.4). */\nexport interface LedgerEntry {\n runId: RunId;\n slot: string;\n path: string;\n /** null = deleted */\n sha256: Sha256 | null;\n effectId: EffectId;\n effectSeq: number;\n}\n\nexport interface EffectRecord {\n effectId: EffectId;\n runId: RunId;\n idempotencyKey: string;\n kind: EffectKind;\n replayClass: ReplayClass;\n state: EffectState;\n agentId?: AgentId;\n toolCallId?: ToolCallId;\n slot?: string;\n request: SealedJson;\n verify: SealedJson;\n preState?: EffectPreState;\n result?: SealedJson;\n /** `failed`: the failure; `in-doubt`: the note, as `human-required/in-doubt-effect` (`result` stays whatever the last attempt left). */\n error?: ErrorInfo;\n consumesGrant?: ApprovalId;\n compensatedBy?: EffectId;\n /** the fencing token of the transaction that wrote the intent */\n fencingToken: number;\n /** `runs.last_sequence` when the intent was written / when the effect reached a final state */\n intentSeq: number;\n doneSeq?: number;\n createdAt: IsoInstant;\n updatedAt: IsoInstant;\n}\n\n/** What `resolveApproval` is given: who answered what, when, and the authenticator of the resolving command (ADR-0022). */\nexport interface ApprovalDecisionRecord {\n actor: Actor;\n /** absent when the SYSTEM resolves (`expired`, `superseded`) */\n commandId?: CommandId;\n answer: Exclude<ApprovalStatus, 'pending'>;\n note?: string;\n decidedAt: IsoInstant;\n /** the sequence of `approval.resolved` */\n resolvedSeq: number;\n auth?: CommandAuth;\n}\n\nexport interface ApprovalRecord {\n approvalId: ApprovalId;\n runId: RunId;\n idempotencyKey: string;\n /** open on the wire (ApprovalRequest.kind) */\n kind: string;\n agentId?: AgentId;\n incarnation?: number;\n toolCallId?: ToolCallId;\n status: ApprovalStatus;\n /** ApprovalRequest incl. the NORMALISED pending call */\n request: SealedJson;\n /** sha256(tool | normalised call | pre-state binding): what a decision is valid for (4.5) */\n grantKey: string;\n decision?: Omit<ApprovalDecisionRecord, 'auth' | 'resolvedSeq'>;\n commandAuth?: CommandAuth;\n /** allow-once: set in the intent transaction of the consuming effect */\n consumedByEffect?: EffectId;\n requestedSeq: number;\n resolvedSeq?: number;\n expiresAt?: IsoInstant;\n createdAt: IsoInstant;\n resolvedAt?: IsoInstant;\n}\n\nexport interface BudgetRecord {\n runId: RunId;\n level: string;\n scopeId: string;\n consumed: BudgetCounters;\n limit: BudgetCounters;\n updatedAt: IsoInstant;\n}\n\nexport interface ArtifactRecord {\n artifactId: ArtifactId;\n runId: RunId;\n /** open on the wire (ARTIFACT_KINDS) */\n kind: string;\n /** relative to the run directory, POSIX separators */\n path: string;\n sha256: Sha256;\n bytes: number;\n mediaType?: string;\n agentId?: AgentId;\n phaseRunId?: PhaseRunId;\n createdAt: IsoInstant;\n}\n\nexport interface FindingRecord {\n runId: RunId;\n findingId: FindingId;\n phaseRunId: PhaseRunId;\n agentId?: AgentId;\n severity: Severity;\n /** open: owned by the loop controller ('open' | 'fixed' | 'waived' ...) */\n status: string;\n /** the sealed finding as the reviewer submitted it */\n finding: SealedJson;\n createdAt: IsoInstant;\n updatedAt: IsoInstant;\n}\n\nexport interface CommandRecord {\n commandId: CommandId;\n runId?: RunId;\n type: string;\n /** sha256 of the canonical body (the envelope minus `auth`): same id + other body = `id-reuse-conflict` */\n bodySha256: Sha256;\n envelope: CommandEnvelope;\n authScheme?: string;\n authValue?: string;\n status: CommandStatus;\n claimedBy?: string;\n resultEventId?: EventId;\n createdAt: IsoInstant;\n updatedAt: IsoInstant;\n}\n\n/** Flat, like the table: the owner of DESIGN's `LockOwner` is the four `owner*` keys. */\nexport interface LockRecord {\n lockId: string;\n scope: LockScope;\n key: string;\n mode: LockMode;\n ownerRunId?: RunId;\n ownerHostId: string;\n ownerPid: number;\n ownerStartToken: string;\n fencingToken: number;\n zones?: string[];\n leaseExpiresAt: IsoInstant;\n acquiredAt: IsoInstant;\n}\n\nexport interface StoredSnapshot {\n runId: RunId;\n atSequence: number;\n schemaVersion: number;\n cohorteVersion: string;\n stateSha256: Sha256;\n state: SealedJson;\n}\n\n// ── aggregates ──────────────────────────────────────────────────────────────────────────────────────────────────\nexport interface RunTreeRows {\n run: RunRecord;\n phases: PhaseRecord[];\n agents: AgentRecord[];\n incarnations: IncarnationRecord[];\n worktrees: WorktreeRecord[];\n approvals: ApprovalRecord[];\n budgets: BudgetRecord[];\n locks: LockRecord[];\n}\n\nexport interface StoreInfo {\n kind: string;\n /** the highest applied migration id */\n schemaVersion: number;\n /** a path for a file store, `:memory:` otherwise */\n location: string;\n}\n\nexport interface MigrationStep {\n id: number;\n name: string;\n sha256: Sha256;\n}\n\nexport interface MigrationReport {\n mode: 'check' | 'apply';\n /** schema version before this call / the version this build expects */\n current: number;\n target: number;\n pending: MigrationStep[];\n applied: MigrationStep[];\n /** `apply` only: where `backup()` wrote the pre-migration copy */\n backupPath?: string;\n}\n\n// ── table <-> record parity ─────────────────────────────────────────────────────────────────────────────────────\ntype ColumnMap<R> = Readonly<Record<string, keyof R & string>>;\n\nconst columns =\n <R>() =>\n <const M extends ColumnMap<R>>(map: [keyof R & string] extends [M[keyof M]] ? M : never): M =>\n map;\n\n/**\n * Every table of 0001_init.sql, column by column, against the key of its record type. The `columns<R>()` helper\n * refuses a map that names a key the record lacks OR misses one it has, so this constant and the record types cannot\n * drift; the DDL parity test compares its left-hand side with `PRAGMA table_info`.\n */\nexport const TABLE_COLUMNS = {\n migrations: columns<MigrationRecord>()({\n id: 'id',\n name: 'name',\n sha256: 'sha256',\n applied_at: 'appliedAt',\n cohorte_version: 'cohorteVersion',\n }),\n meta: columns<MetaRecord>()({ key: 'key', value: 'value' }),\n runs: columns<RunRecord>()({\n run_id: 'runId',\n profile: 'profile',\n table_version: 'tableVersion',\n spec_id: 'specId',\n spec_sha256: 'specSha256',\n title: 'title',\n state: 'state',\n resume_to: 'resumeTo',\n stop_json: 'stop',\n last_error_json: 'lastError',\n last_sequence: 'lastSequence',\n last_hash: 'lastHash',\n version: 'version',\n snapshot_digest: 'snapshotDigest',\n runtime_pin_json: 'runtimePin',\n plan_json: 'plan',\n pinned_install_dir: 'pinnedInstallDir',\n base_branch: 'baseBranch',\n base_sha: 'baseSha',\n integration_branch: 'integrationBranch',\n integration_head: 'integrationHead',\n approved_tree_digest: 'approvedTreeDigest',\n skip_waivers_json: 'skipWaivers',\n zones_json: 'zones',\n host_id: 'hostId',\n host_pid: 'hostPid',\n host_start_token: 'hostStartToken',\n host_heartbeat_at: 'hostHeartbeatAt',\n cancel_requested: 'cancelRequested',\n pause_requested: 'pauseRequested',\n schema_version: 'schemaVersion',\n cohorte_version: 'cohorteVersion',\n purgeable: 'purgeable',\n started_at: 'startedAt',\n updated_at: 'updatedAt',\n ended_at: 'endedAt',\n }),\n events: columns<EventRecord>()({\n run_id: 'runId',\n sequence: 'sequence',\n event_id: 'eventId',\n type: 'type',\n timestamp: 'timestamp',\n source: 'source',\n phase_run_id: 'phaseRunId',\n agent_id: 'agentId',\n causation_id: 'causationId',\n severity: 'severity',\n summary: 'summary',\n envelope: 'envelope',\n prev_hash: 'prevHash',\n hash: 'hash',\n }),\n transitions: columns<TransitionRecord>()({\n transition_id: 'transitionId',\n run_id: 'runId',\n def_id: 'defId',\n table_version: 'tableVersion',\n from_state: 'from',\n to_state: 'to',\n reason: 'reason',\n actor_json: 'actor',\n guards_json: 'guards',\n effects_json: 'effects',\n idempotency_key: 'idempotencyKey',\n event_id: 'eventId',\n }),\n phases: columns<PhaseRecord>()({\n run_id: 'runId',\n phase_run_id: 'phaseRunId',\n state: 'state',\n iteration: 'iteration',\n status: 'status',\n outcome: 'outcome',\n checks_json: 'checks',\n started_at: 'startedAt',\n ended_at: 'endedAt',\n }),\n agents: columns<AgentRecord>()({\n run_id: 'runId',\n agent_id: 'agentId',\n phase_run_id: 'phaseRunId',\n role: 'role',\n surface: 'surface',\n label: 'label',\n state: 'state',\n attempt: 'attempt',\n incarnation: 'incarnation',\n max_attempts: 'maxAttempts',\n max_incarnations: 'maxIncarnations',\n model_json: 'model',\n effective_model_json: 'effectiveModel',\n auth_mode: 'authMode',\n slot: 'slot',\n context_sha256: 'contextSha256',\n grants_digest: 'grantsDigest',\n usage_json: 'usage',\n summary: 'summary',\n last_error_json: 'lastError',\n pending_approval: 'pendingApproval',\n runtime_ref_json: 'runtimeRef',\n created_at: 'createdAt',\n updated_at: 'updatedAt',\n }),\n agent_incarnations: columns<IncarnationRecord>()({\n run_id: 'runId',\n agent_id: 'agentId',\n incarnation: 'incarnation',\n attempt: 'attempt',\n state: 'state',\n cause: 'cause',\n pid: 'pid',\n start_token: 'startToken',\n host_nonce: 'hostNonce',\n runtime_ref_json: 'runtimeRef',\n stop: 'stop',\n reason: 'reason',\n usage_json: 'usage',\n started_at: 'startedAt',\n ended_at: 'endedAt',\n }),\n worktrees: columns<WorktreeRecord>()({\n run_id: 'runId',\n slot: 'slot',\n path: 'path',\n branch: 'branch',\n base_sha: 'baseSha',\n checkpoint_sha: 'checkpointSha',\n last_tree_digest: 'lastTreeDigest',\n lockfile_sha256: 'lockfileSha256',\n provision_key: 'provisionKey',\n deps_manifest_sha256: 'depsManifestSha256',\n holder_agent_id: 'holderAgentId',\n state: 'state',\n }),\n worktree_ledger: columns<LedgerEntry>()({\n run_id: 'runId',\n slot: 'slot',\n path: 'path',\n sha256: 'sha256',\n effect_id: 'effectId',\n effect_seq: 'effectSeq',\n }),\n effects: columns<EffectRecord>()({\n effect_id: 'effectId',\n run_id: 'runId',\n idempotency_key: 'idempotencyKey',\n kind: 'kind',\n replay_class: 'replayClass',\n state: 'state',\n agent_id: 'agentId',\n tool_call_id: 'toolCallId',\n slot: 'slot',\n request_json: 'request',\n verify_json: 'verify',\n pre_state_json: 'preState',\n result_json: 'result',\n error_json: 'error',\n consumes_grant: 'consumesGrant',\n compensated_by: 'compensatedBy',\n fencing_token: 'fencingToken',\n intent_seq: 'intentSeq',\n done_seq: 'doneSeq',\n created_at: 'createdAt',\n updated_at: 'updatedAt',\n }),\n approvals: columns<ApprovalRecord>()({\n approval_id: 'approvalId',\n run_id: 'runId',\n idempotency_key: 'idempotencyKey',\n kind: 'kind',\n agent_id: 'agentId',\n incarnation: 'incarnation',\n tool_call_id: 'toolCallId',\n status: 'status',\n request_json: 'request',\n grant_key: 'grantKey',\n decision_json: 'decision',\n command_auth_json: 'commandAuth',\n consumed_by_effect: 'consumedByEffect',\n requested_seq: 'requestedSeq',\n resolved_seq: 'resolvedSeq',\n expires_at: 'expiresAt',\n created_at: 'createdAt',\n resolved_at: 'resolvedAt',\n }),\n budgets: columns<BudgetRecord>()({\n run_id: 'runId',\n level: 'level',\n scope_id: 'scopeId',\n consumed_json: 'consumed',\n limit_json: 'limit',\n updated_at: 'updatedAt',\n }),\n artifacts: columns<ArtifactRecord>()({\n artifact_id: 'artifactId',\n run_id: 'runId',\n kind: 'kind',\n path: 'path',\n sha256: 'sha256',\n bytes: 'bytes',\n media_type: 'mediaType',\n agent_id: 'agentId',\n phase_run_id: 'phaseRunId',\n created_at: 'createdAt',\n }),\n findings: columns<FindingRecord>()({\n run_id: 'runId',\n finding_id: 'findingId',\n phase_run_id: 'phaseRunId',\n agent_id: 'agentId',\n severity: 'severity',\n status: 'status',\n finding_json: 'finding',\n created_at: 'createdAt',\n updated_at: 'updatedAt',\n }),\n commands: columns<CommandRecord>()({\n command_id: 'commandId',\n run_id: 'runId',\n type: 'type',\n body_sha256: 'bodySha256',\n envelope_json: 'envelope',\n auth_scheme: 'authScheme',\n auth_value: 'authValue',\n status: 'status',\n claimed_by: 'claimedBy',\n result_event_id: 'resultEventId',\n created_at: 'createdAt',\n updated_at: 'updatedAt',\n }),\n locks: columns<LockRecord>()({\n lock_id: 'lockId',\n scope: 'scope',\n key: 'key',\n mode: 'mode',\n owner_run_id: 'ownerRunId',\n owner_host_id: 'ownerHostId',\n owner_pid: 'ownerPid',\n owner_start_token: 'ownerStartToken',\n fencing_token: 'fencingToken',\n zones_json: 'zones',\n lease_expires_at: 'leaseExpiresAt',\n acquired_at: 'acquiredAt',\n }),\n snapshots: columns<StoredSnapshot>()({\n run_id: 'runId',\n at_sequence: 'atSequence',\n schema_version: 'schemaVersion',\n cohorte_version: 'cohorteVersion',\n state_sha256: 'stateSha256',\n state_json: 'state',\n }),\n} as const;\nexport type TableName = keyof typeof TABLE_COLUMNS;\nexport const TABLE_NAMES = Object.keys(TABLE_COLUMNS) as readonly TableName[];\n\n/**\n * The six host-computed columns of `runs`: a run may leave IDLE | CANCELLED | FAILED only with all of them set.\n * \"Set\" means non-null, exactly as the DDL's `IS NOT NULL` CHECK reads it: `runtimePin` is a `JsonValue` and a\n * stored JSON `null` is a missing column, not a value. Every implementation refuses both spellings alike.\n */\nexport const HOST_COMPUTED_RUN_KEYS = [\n 'snapshotDigest',\n 'runtimePin',\n 'plan',\n 'baseSha',\n 'integrationBranch',\n 'zones',\n] as const satisfies readonly (keyof RunRecord)[];\nexport const STATES_WITHOUT_HOST_COLUMNS: readonly PipelineState[] = ['IDLE', 'CANCELLED', 'FAILED'];\n","// `@cohorte/persistence/contract` — the StateStore contract (DESIGN 2.4, ADR-0002): asynchronous boundary,\n// SYNCHRONOUS transaction body. FROZEN at G0. Stores are dumb: `core` writes projections explicitly, in the same\n// transaction as the events that justify them; no store contains a reducer.\nimport type {\n AgentId,\n ApprovalId,\n ArtifactId,\n CommandId,\n EffectId,\n ErrorInfo,\n EventId,\n RunId,\n Sealed,\n SealedJson,\n Sha256,\n ToolCallId,\n} from '@cohorte/base';\nimport type { CommandEnvelope, DurableEventType, Envelope, PipelineState } from '@cohorte/protocol';\nimport type {\n AgentRecord,\n ApprovalDecisionRecord,\n ApprovalRecord,\n ArtifactRecord,\n BudgetRecord,\n CommandRecord,\n EffectKind,\n EffectPreState,\n EffectRecord,\n EffectState,\n FindingRecord,\n IncarnationRecord,\n LedgerEntry,\n LockMode,\n LockRecord,\n LockScope,\n MigrationReport,\n PhaseRecord,\n ReplayClass,\n RunRecord,\n RunTreeRows,\n StoredSnapshot,\n StoreInfo,\n TransitionRecord,\n WorktreeRecord,\n} from './records.ts';\n\nexport type { DurableEventType } from '@cohorte/protocol';\n// An explicit list, not `export type *`: Biome 2.5.14's type inference overflows its stack on the star form.\nexport type {\n AgentRecord,\n ApprovalDecisionRecord,\n ApprovalRecord,\n ApprovalStatus,\n ArtifactRecord,\n BudgetRecord,\n CommandRecord,\n CommandStatus,\n EffectKind,\n EffectPreState,\n EffectRecord,\n EffectState,\n EventRecord,\n FindingRecord,\n IncarnationRecord,\n LedgerEntry,\n LockMode,\n LockRecord,\n LockScope,\n MetaRecord,\n MigrationRecord,\n MigrationReport,\n MigrationStep,\n PhaseRecord,\n ReplayClass,\n RunRecord,\n RunTreeRows,\n StoredSnapshot,\n StoreInfo,\n TableName,\n TransitionRecord,\n WorktreeRecord,\n WorktreeState,\n} from './records.ts';\nexport { HOST_COMPUTED_RUN_KEYS, STATES_WITHOUT_HOST_COLUMNS, TABLE_COLUMNS, TABLE_NAMES } from './records.ts';\n\nexport type DurableEnvelope = Envelope<DurableEventType>;\n/** What core hands to the store: everything except what the store assigns — and ONLY after Redactor sealed it (I7). */\nexport type EventDraft = Omit<DurableEnvelope, 'sequence' | 'sub' | 'durability'>;\nexport type SealedEventDraft = Sealed<EventDraft>;\n\nexport interface LeaseToken {\n readonly lockId: string;\n /** `NO_RUN_ID` for a lock whose owner names no run (project, migration) */\n readonly runId: RunId;\n readonly hostId: string;\n readonly fencingToken: number;\n}\n/** The `runId` of a lease taken without one. Never the id of a run: a run-scoped transaction refuses such a lease. */\nexport const NO_RUN_ID = '' as RunId;\n\n/**\n * A caller broke the contract (a thenable body, a run-scoped write in a project transaction, a write to another run,\n * an unknown run or effect, a run leaving IDLE without its host-computed columns). Reaching one is a bug, not a run\n * outcome: the transaction is rolled back and nothing is written.\n */\nexport class StoreUsageError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'StoreUsageError';\n }\n}\n\nexport type VerifyChainResult =\n | { ok: true; events: number; anchors: number }\n | { ok: false; firstBadSequence: number; reason: 'hash-mismatch' | 'gap' | 'duplicate' | 'anchor-mac' };\n\nexport interface StateStore {\n /** 'sqlite' | 'memory' */\n readonly kind: string;\n /** refuses (corruption/incompatible-schema) rather than guessing; never auto-migrates */\n open(): Promise<StoreInfo>;\n close(): Promise<void>;\n /** numbered, monotonic, sha256-pinned; 'apply' takes the exclusive project lock + backup() */\n migrate(mode: 'check' | 'apply'): Promise<MigrationReport>;\n backup(toPath: string): Promise<void>;\n\n // ── the single write path ─────────────────────────────────────────────\n /**\n * lease != null: the FIRST statement asserts the lease against the lock row, else throws conflict/lease-lost (I6).\n * For a RUN-scoped transaction the lease must be the run's OWN lock — the row with `scope:'run'`, `key: runId`,\n * `fencing_token = lease.fencingToken` and `owner_host_id = lease.hostId` (in SQL:\n * `SELECT 1 FROM locks WHERE lock_id = ? AND scope = 'run' AND key = ? AND fencing_token = ? AND owner_host_id = ?`).\n * A lease on any OTHER lock that happens to name the run (a zone lock, which the supervisor takes with\n * `owner.runId` set) is refused: otherwise a host that lost the run lease to a steal could keep writing the run\n * through it, and I6 is \"ONE writer per run\". body MUST be synchronous (a returned thenable is rejected).\n * lease == null is legal only for scope 'project' (init, migrate, lock acquisition, and RUN CREATION: inside\n * `transact('project', null, …)` the body may call `putRun` for a runId that does not exist yet and\n * `enqueueCommand` — and nothing else run-scoped) and for the stand-alone `enqueueCommand` below.\n */\n transact<T>(\n scope: { runId: RunId } | 'project',\n lease: LeaseToken | null,\n body: (tx: StoreTx) => T,\n opts?: { expectedSequence?: number },\n ): Promise<T>;\n\n // ── reads: lock-free, safe to SIGKILL the reader at any instant ───────\n getRun(runId: RunId): Promise<RunRecord | undefined>;\n listRuns(q: { states?: PipelineState[]; limit: number; offset: number }): Promise<RunRecord[]>;\n /** always paginated by sequence */\n readEvents(\n runId: RunId,\n q: { afterSequence: number; limit: number; types?: DurableEventType[] },\n ): Promise<DurableEnvelope[]>;\n loadSnapshot(runId: RunId): Promise<StoredSnapshot | undefined>;\n /** runs + phases + agents + incarnations + worktrees + approvals + budgets + locks */\n readRunTree(runId: RunId): Promise<RunTreeRows>;\n listPendingApprovals(runId?: RunId): Promise<ApprovalRecord[]>;\n listEffects(runId: RunId, q: { states: EffectState[] }): Promise<EffectRecord[]>;\n readLedger(runId: RunId, slot: string): Promise<LedgerEntry[]>;\n getArtifact(runId: RunId, id: ArtifactId): Promise<ArtifactRecord | undefined>;\n verifyChain(runId: RunId, key?: Uint8Array): Promise<VerifyChainResult>;\n\n // ── command inbox (D5): the only write a non-owner process performs ───\n enqueueCommand(\n cmd: CommandEnvelope,\n ): Promise<{ status: 'enqueued' | 'duplicate' | 'id-reuse-conflict'; record: CommandRecord }>;\n /** status 'pending', ordered by created_at, command_id */\n pendingCommands(runId: RunId): Promise<CommandRecord[]>;\n getCommand(id: CommandId): Promise<CommandRecord | undefined>;\n\n // ── locks / leases (spec 15, 11.3) ────────────────────────────────────\n /**\n * Refused as long as a CONFLICTING row exists, however stale: `leaseExpiresAt` is ADVISORY (see `LockRequest.ttlMs`)\n * and no store evicts an expired row here. Taking over a dead host's lock is `stealLock`, never an implicit expiry.\n */\n acquireLock(req: LockRequest): Promise<{ ok: true; lease: LeaseToken } | { ok: false; heldBy: LockRecord[] }>;\n /** fencingToken = old + 1; emits lock.stolen through the caller */\n stealLock(req: LockRequest, expected: LockRecord): Promise<LeaseToken>;\n /** false = lease lost: the host MUST stop producing effects. An expired-but-unstolen lock still renews (true). */\n renewLock(lockId: string, ttlMs: number): Promise<boolean>;\n releaseLock(lockId: string): Promise<void>;\n listLocks(q?: { scope?: LockScope }): Promise<LockRecord[]>;\n}\n\n/** Synchronous. Every method fully applies inside the enclosing transaction or throws (rollback). */\nexport interface StoreTx {\n /** assigns sequence = last+1…, prev_hash/hash; bumps runs.last_sequence, runs.version */\n appendEvents(drafts: readonly SealedEventDraft[]): DurableEnvelope[];\n /** UNIQUE(run_id, idempotency_key) */\n recordTransition(t: TransitionRecord): 'recorded' | 'duplicate';\n putRun(r: RunRecord): void;\n patchRun(runId: RunId, p: Partial<RunRecord>): void;\n putPhase(p: PhaseRecord): void;\n putAgent(a: AgentRecord): void;\n putIncarnation(i: IncarnationRecord): void;\n putWorktree(w: WorktreeRecord): void;\n putLedger(e: LedgerEntry): void;\n clearLedger(runId: RunId, slot: string, upToEffectSeq: number): void;\n /** UNIQUE(run_id, idempotency_key) */\n putApproval(a: ApprovalRecord): 'created' | 'exists';\n resolveApproval(id: ApprovalId, d: ApprovalDecisionRecord): 'resolved' | 'already-resolved';\n /** live allow-for-run, or unconsumed allow-once */\n findGrant(runId: RunId, grantKey: string): ApprovalRecord | undefined;\n setBudget(b: BudgetRecord): void;\n putArtifact(a: ArtifactRecord): void;\n putFinding(f: FindingRecord): void;\n // effect journal (4.1)\n /**\n * Which stored state maps to which answer, for the row already filed under `(runId, idempotencyKey)`:\n * `done` -> `already-done` (the caller replays the stored result, nothing re-executes); `intent` / `in-doubt` ->\n * `open` (recovery decides by replay class, 4.1); `failed` / `compensated` -> `started`, a NEW attempt on the SAME\n * row: it keeps its effectId and createdAt and is rebuilt from the intent alone, so the previous attempt's\n * `result`, `error` and `compensatedBy` are cleared. No stored row at all -> `started` with a fresh effectId.\n */\n beginEffect(\n e: EffectIntent,\n ):\n | { status: 'started'; effectId: EffectId }\n | { status: 'already-done'; record: EffectRecord }\n | { status: 'open'; record: EffectRecord /* intent | in-doubt */ };\n completeEffect(id: EffectId, result: SealedJson, post?: { treeDigest?: string; head?: string }): void;\n failEffect(id: EffectId, error: ErrorInfo): void;\n markEffectInDoubt(id: EffectId, note: string): void;\n compensateEffects(ids: EffectId[], byEffect: EffectId): void;\n // inbox\n /**\n * same row and same rules as StateStore.enqueueCommand, but INSIDE a transaction: this is what makes\n * `start` = { run row IDLE + signed start command } ONE atomic write (4.3 #1).\n *\n * ORDER IS LOAD-BEARING in the run-creation transaction: call this FIRST and `putRun` only on `'enqueued'`. On\n * `'duplicate'` / `'id-reuse-conflict'` the run must NOT be written — a retried `start` that writes the run first\n * commits an orphan IDLE run beside the answer \"duplicate\", which is the very outcome the single atomic write\n * exists to prevent. Neither status throws, so nothing else rolls the transaction back for you.\n */\n enqueueCommand(cmd: CommandEnvelope): 'enqueued' | 'duplicate' | 'id-reuse-conflict';\n claimCommand(id: CommandId, hostId: string): boolean;\n finishCommand(id: CommandId, outcome: 'completed' | 'rejected', resultEventId: EventId): void;\n /** AFTER the events it covers (spec 11.3); keep last 3 */\n writeSnapshot(s: StoredSnapshot): void;\n // synchronous read-modify-write helpers\n run(): RunRecord;\n agent(id: AgentId): AgentRecord | undefined;\n incarnation(id: AgentId, n: number): IncarnationRecord | undefined;\n worktree(slot: string): WorktreeRecord | undefined;\n approval(id: ApprovalId): ApprovalRecord | undefined;\n effectByKey(key: string): EffectRecord | undefined;\n budget(level: string, scopeId: string): BudgetRecord | undefined;\n}\n\nexport interface EffectIntent {\n runId: RunId;\n idempotencyKey: string;\n kind: EffectKind;\n replayClass: ReplayClass;\n agentId?: AgentId;\n toolCallId?: ToolCallId;\n slot?: string;\n request: SealedJson;\n /** data the kind-specific verifier needs after a crash */\n verify: SealedJson;\n preState?: EffectPreState;\n /** allow-once is consumed in THIS transaction: exactly once across a crash */\n consumesGrant?: ApprovalId;\n}\n\nexport interface LockOwner {\n runId?: RunId;\n hostId: string;\n pid: number;\n startToken: string;\n}\nexport interface LockRequest {\n scope: LockScope;\n key: string;\n mode: LockMode;\n owner: LockOwner;\n /**\n * How long the holder promises to keep renewing. The resulting `leaseExpiresAt` is ADVISORY and INFORMATIONAL: no\n * store evicts an expired row, `acquireLock` still refuses against it, `renewLock` still returns true, and a write\n * fenced on it still commits. What a run's expiry is FOR is telling a supervisor that the holder looks dead, and\n * the takeover it then performs is `stealLock` (fencing + 1), the one mechanism that invalidates the old lease.\n */\n ttlMs: number;\n zones?: string[];\n}\n\nexport interface SqlDriver {\n exec(sql: string): void;\n prepare(sql: string): {\n run(...p: unknown[]): { changes: number | bigint };\n get(...p: unknown[]): unknown;\n all(...p: unknown[]): unknown[];\n };\n close(): void;\n}\n\nexport interface BlobStore {\n put(bytes: Uint8Array): Promise<{ sha256: Sha256; bytes: number }>;\n /** re-verifies the hash on EVERY read: security/pin-tampered */\n read(sha256: Sha256): Promise<Uint8Array>;\n has(sha256: Sha256): Promise<boolean>;\n}\nexport interface RunFiles {\n dir(runId: RunId, ...sub: string[]): string;\n agentDir(runId: RunId, agentId: AgentId, incarnation: number): string;\n writeArtifact(runId: RunId, rel: string, bytes: Uint8Array): Promise<ArtifactRecord>;\n}\nexport interface EphemeralSpool {\n append(runId: RunId, line: string): void;\n tail(runId: RunId, after: { sequence: number; sub: number }, signal: AbortSignal): AsyncIterable<string>;\n}\n\n// ── the two pure definitions both stores share, so that a chain written by one verifies in the other ────────────\n/** Zones overlap by PATH SEGMENT: `src/app` overlaps `src` and `src/app/ui`, never `src/application`. */\nexport function zonesOverlap(a: string, b: string): boolean {\n const left = a.split('/').filter((segment) => segment !== '' && segment !== '.');\n const right = b.split('/').filter((segment) => segment !== '' && segment !== '.');\n const shared = Math.min(left.length, right.length);\n for (let index = 0; index < shared; index += 1) if (left[index] !== right[index]) return false;\n return true;\n}\n\n/** Two lock requests on the same (scope, key) conflict unless both are shared; two ZONE locks only where zones overlap. */\nexport function locksConflict(\n a: { scope: LockScope; key: string; mode: LockMode; zones?: readonly string[] | undefined },\n b: { scope: LockScope; key: string; mode: LockMode; zones?: readonly string[] | undefined },\n): boolean {\n if (a.scope !== b.scope || a.key !== b.key) return false;\n if (a.mode === 'shared' && b.mode === 'shared') return false;\n if (a.scope !== 'zone') return true;\n const left = a.zones ?? [];\n const right = b.zones ?? [];\n // A zone lock that names no zone reserves the whole key.\n if (left.length === 0 || right.length === 0) return true;\n return left.some((zone) => right.some((other) => zonesOverlap(zone, other)));\n}\n","// The hash chain of the event journal (DESIGN 2.4, ADR-0022), as pure functions over `EventRecord`s: every store\n// hashes and verifies with these, so a journal written by one verifies in another.\nimport { timingSafeEqual } from 'node:crypto';\nimport { canonicalJson, computeAnchorMac, type JsonValue, type RunId, sha256Hex } from '@cohorte/base';\nimport type { DurableEnvelope, EventDraft, EventRecord, VerifyChainResult } from '../contract.ts';\n\n/** hash = sha256(prev_hash || '\\n' || envelope); the first event chains from the empty string. */\nexport const chainHash = (prevHash: string, envelope: string): string => sha256Hex(`${prevHash}\\n${envelope}`);\n\n/** The row of one sealed draft at `sequence`: the store-assigned fields are part of the hashed envelope. */\nexport function toEventRecord(draft: EventDraft, sequence: number, prevHash: string): EventRecord {\n const envelope = canonicalJson({ ...draft, sequence, sub: 0, durability: 'durable' } as unknown as JsonValue);\n return {\n runId: draft.runId,\n sequence,\n eventId: draft.eventId,\n type: draft.type,\n timestamp: draft.timestamp,\n source: draft.source,\n ...(draft.phase ? { phaseRunId: draft.phase.phaseRunId } : {}),\n ...(draft.agent ? { agentId: draft.agent.agentId } : {}),\n ...(draft.causationId === undefined ? {} : { causationId: draft.causationId }),\n severity: draft.severity,\n summary: draft.summary,\n envelope,\n prevHash,\n hash: chainHash(prevHash, envelope),\n };\n}\n\nexport const envelopeOf = (record: EventRecord): DurableEnvelope => JSON.parse(record.envelope) as DurableEnvelope;\n\nconst sameMac = (a: string, b: string): boolean => {\n const left = Buffer.from(a, 'utf8');\n const right = Buffer.from(b, 'utf8');\n return left.byteLength === right.byteLength && timingSafeEqual(left, right);\n};\n\n/**\n * Walks a run's rows in storage order. `tail` is what the run row claims (`last_sequence`, `last_hash`): a journal\n * cut short at the end is a gap too. Anchors (`checkpoint.created`) are checked only when the key is given.\n */\nexport function verifyEventRecords(\n id: RunId,\n records: readonly EventRecord[],\n key?: Uint8Array,\n tail?: { lastSequence: number; lastHash: string },\n): VerifyChainResult {\n const hashes = new Map<number, string>([[0, '']]);\n let expected = 1;\n let prevHash = '';\n let anchors = 0;\n for (const record of records) {\n if (record.sequence < expected) return { ok: false, firstBadSequence: record.sequence, reason: 'duplicate' };\n if (record.sequence > expected) return { ok: false, firstBadSequence: expected, reason: 'gap' };\n const bad = { ok: false, firstBadSequence: record.sequence, reason: 'hash-mismatch' } as const;\n if (record.prevHash !== prevHash || record.hash !== chainHash(prevHash, record.envelope)) return bad;\n let envelope: DurableEnvelope;\n try {\n envelope = envelopeOf(record);\n } catch {\n return bad;\n }\n if (envelope.sequence !== record.sequence || envelope.runId !== id) return bad;\n if (key && envelope.type === 'checkpoint.created') {\n const badAnchor = { ok: false, firstBadSequence: record.sequence, reason: 'anchor-mac' } as const;\n // The stored envelope is untrusted bytes (ADR-0022: the adversary has write access to the DB and recomputes the\n // chain), so the anchor fields are checked before they reach the MAC: a stripped or retyped payload is an\n // unverifiable anchor, which is a RESULT, never a thrown RangeError/TypeError in a security-critical read.\n const { atSequence, chainHash: anchored, chainMac } = envelope.payload;\n if (\n typeof atSequence !== 'number' ||\n !Number.isSafeInteger(atSequence) ||\n atSequence < 0 ||\n typeof anchored !== 'string' ||\n typeof chainMac !== 'string'\n ) {\n return badAnchor;\n }\n const known = hashes.get(atSequence);\n if (known !== anchored || !sameMac(chainMac, computeAnchorMac(key, id, atSequence, anchored))) return badAnchor;\n anchors += 1;\n }\n hashes.set(record.sequence, record.hash);\n prevHash = record.hash;\n expected += 1;\n }\n // The claimed tail must be the walked tail EXACTLY. A journal shorter than the run row claims is the truncation an\n // adversary leaves behind; a journal LONGER than it claims (an appended, correctly re-chained row) is the cheaper\n // attack of the same threat model (ADR-0022), and both are a gap at the first sequence the two sides disagree on.\n if (tail && tail.lastSequence !== expected - 1) {\n return { ok: false, firstBadSequence: Math.min(tail.lastSequence, expected - 1) + 1, reason: 'gap' };\n }\n if (tail && tail.lastHash !== prevHash) {\n return { ok: false, firstBadSequence: Math.max(1, expected - 1), reason: 'hash-mismatch' };\n }\n return { ok: true, events: records.length, anchors };\n}\n","// `@cohorte/persistence/migrate` — numbered, monotonic, sha256-pinned migrations (DESIGN 2.4, ADR-0002). Synchronous,\n// like `SqlDriver`: `available/check/apply` never return a promise, so `SqliteStateStore.migrate()` is the only async\n// boundary. `apply()` assumes its caller (the store) already holds whatever lock the situation needs and has taken\n// the backup (DESIGN 2.4 `migrate(mode)`); this module never locks or backs up on its own.\nimport { readdirSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { CohorteError, errorOf, type Sha256, sha256Hex, toIsoInstant } from '@cohorte/base';\nimport type { MigrationReport, MigrationStep, SqlDriver } from '../contract.ts';\n\nexport interface MigratorOptions {\n driver: SqlDriver;\n /** numbered, monotonic `NNNN_name.sql` files; each one is sha256-pinned once applied */\n migrationsDir: string;\n cohorteVersion: string;\n}\n\nexport interface Migrator {\n /** the files on disk, in order */\n available(): MigrationStep[];\n /** refuses a gap, a renumbering, or an applied file whose sha256 changed (corruption/incompatible-schema) */\n check(): MigrationReport;\n /** one transaction per file; the caller holds the exclusive `migration` lock and has taken the backup */\n apply(): MigrationReport;\n}\n\nconst FILE_PATTERN = /^(\\d{4,})_([A-Za-z0-9_]+)\\.sql$/;\n\ninterface AvailableFile {\n readonly id: number;\n readonly name: string;\n readonly sha256: Sha256;\n readonly filename: string;\n}\n\nfunction incompatible(message: string): CohorteError {\n return new CohorteError(errorOf('corruption/incompatible-schema', message));\n}\n\n/** Reads and sha-pins every `NNNN_name.sql` of `migrationsDir`, refusing a gap or a renumbering. A missing directory is zero migrations. */\nfunction readAvailable(migrationsDir: string): AvailableFile[] {\n let names: string[];\n try {\n names = readdirSync(migrationsDir);\n } catch {\n return [];\n }\n const matched = names\n .map((name) => ({ name, match: FILE_PATTERN.exec(name) }))\n .filter((entry): entry is { name: string; match: RegExpExecArray } => entry.match !== null)\n .sort((a, b) => a.name.localeCompare(b.name));\n const files = matched.map(({ name, match }) => ({\n id: Number.parseInt(match[1] as string, 10),\n name: match[2] as string,\n filename: name,\n }));\n files.forEach((file, index) => {\n if (file.id !== index + 1) {\n throw incompatible(\n `migrations/state is not numbered monotonically from 1: ${file.filename} sits at position ${index + 1}`,\n );\n }\n });\n return files.map((file) => ({\n ...file,\n sha256: sha256Hex(readFileSync(join(migrationsDir, file.filename))),\n }));\n}\n\nfunction tableExists(driver: SqlDriver, name: string): boolean {\n return driver.prepare(\"SELECT 1 FROM sqlite_master WHERE type='table' AND name=?\").get(name) !== undefined;\n}\n\ninterface AppliedRow {\n id: number;\n name: string;\n sha256: Sha256;\n}\n\n/** The `migrations` table itself is created by `0001_init.sql`: before that runs, \"applied\" is simply empty. */\nfunction readApplied(driver: SqlDriver): AppliedRow[] {\n if (!tableExists(driver, 'migrations')) return [];\n return driver.prepare('SELECT id, name, sha256 FROM migrations ORDER BY id').all() as AppliedRow[];\n}\n\nconst asStep = ({ id, name, sha256 }: { id: number; name: string; sha256: Sha256 }): MigrationStep => ({\n id,\n name,\n sha256,\n});\n\nexport function createMigrator(options: MigratorOptions): Migrator {\n const { driver, migrationsDir, cohorteVersion } = options;\n\n function available(): MigrationStep[] {\n return readAvailable(migrationsDir).map(asStep);\n }\n\n function check(): MigrationReport {\n const files = readAvailable(migrationsDir);\n const applied = readApplied(driver);\n for (const row of applied) {\n const file = files.find((candidate) => candidate.id === row.id);\n if (file && file.sha256 !== row.sha256) {\n throw incompatible(\n `migration ${row.id} (${row.name}) was edited after it was applied: its sha256 no longer matches migrations/state`,\n );\n }\n }\n const current = applied.length > 0 ? Math.max(...applied.map((row) => row.id)) : 0;\n const target = files.length > 0 ? Math.max(...files.map((file) => file.id)) : 0;\n const appliedIds = new Set(applied.map((row) => row.id));\n const pending = files.filter((file) => !appliedIds.has(file.id)).map(asStep);\n return { mode: 'check', current, target, pending, applied: applied.map(asStep) };\n }\n\n function apply(): MigrationReport {\n const report = check();\n if (report.current > report.target) {\n throw incompatible(\n `the state database is at schema ${report.current}, newer than this build's migrations/state (target ${report.target}); run the Cohorte version that wrote it`,\n );\n }\n const files = readAvailable(migrationsDir);\n const applied: MigrationStep[] = [];\n for (const step of report.pending) {\n const file = files.find((candidate) => candidate.id === step.id);\n if (!file) throw incompatible(`migration ${step.id} vanished from migrations/state mid-apply`);\n const sql = readFileSync(join(migrationsDir, file.filename), 'utf8');\n driver.exec('BEGIN IMMEDIATE');\n try {\n driver.exec(sql);\n driver\n .prepare('INSERT INTO migrations (id, name, sha256, applied_at, cohorte_version) VALUES (?, ?, ?, ?, ?)')\n .run(file.id, file.name, file.sha256, toIsoInstant(Date.now()), cohorteVersion);\n driver.exec('COMMIT');\n } catch (error) {\n try {\n driver.exec('ROLLBACK');\n } catch {\n // the failed statement may already have forced an implicit rollback\n }\n throw error;\n }\n applied.push(asStep(file));\n }\n return { mode: 'apply', current: report.current, target: report.target, pending: [], applied };\n }\n\n return { available, check, apply };\n}\n","// Generic row <-> record marshalling shared by every table (DESIGN 2.4). `TABLE_COLUMNS` (records.ts) is the single\n// source of the column<->key map; a `*_json` column is JSON, one of `BOOLEAN_COLUMNS` is a 0/1 INTEGER, everything\n// else is copied through. Keeping this generic — instead of one hand-written mapper per table — is what makes the\n// eighteen tables of 0001_init.sql tractable in one unit; nothing here decides the SCHEMA, only how a JS record\n// becomes SQL params and back (records.ts / 0001_init.sql stay the source of truth, proved by the DDL parity test).\n\nimport type { SqlDriver } from '../contract.ts';\nimport { TABLE_COLUMNS, type TableName } from '../contract.ts';\n\nexport type Row = Record<string, unknown>;\n\nconst JSON_SUFFIX = '_json';\n/** The only columns whose SQL type is `INTEGER CHECK (.. IN (0,1))` standing for a TypeScript `boolean`. */\nconst BOOLEAN_COLUMNS = new Set(['cancel_requested', 'pause_requested', 'purgeable']);\n/**\n * The only column whose record type is `X | null` rather than optional (`worktree_ledger.sha256`: `null` MEANS\n * \"deleted\", a fact distinct from \"not recorded\" — records.ts `LedgerEntry.sha256`). Every other SQL `NULL` becomes\n * an absent key; this one becomes an explicit `null`, in both directions.\n */\nconst NULLABLE_COLUMNS = new Set(['worktree_ledger.sha256']);\n\nconst columnsOf = (table: TableName): ReadonlyArray<[string, string]> => Object.entries(TABLE_COLUMNS[table]);\n\n/** Every column name of a table, in the order `TABLE_COLUMNS` declares them (the order every generated SQL string uses). */\nexport function columnNamesOf(table: TableName): readonly string[] {\n return columnsOf(table).map(([column]) => column);\n}\n\n/** A plain record -> a row of SQL parameters: `undefined` -> `null`, a JSON column stringified, a boolean 0/1. */\nexport function toRow(table: TableName, record: Row): Row {\n const row: Row = {};\n for (const [column, key] of columnsOf(table)) {\n const value = record[key];\n if (NULLABLE_COLUMNS.has(`${table}.${column}`)) row[column] = value ?? null;\n else if (column.endsWith(JSON_SUFFIX)) row[column] = value === undefined ? null : JSON.stringify(value);\n else if (BOOLEAN_COLUMNS.has(column)) row[column] = value ? 1 : 0;\n else row[column] = value === undefined ? null : value;\n }\n return row;\n}\n\n/**\n * A `node:sqlite` row -> a plain record: a SQL `NULL` becomes an ABSENT key (exactOptionalPropertyTypes), never\n * `undefined`. `T` defaults to the untyped `Row`; every call site that knows the record shape casts once here rather\n * than at each use (the row really is that record — `records.ts` and 0001_init.sql are proved column-for-column\n * equal by the DDL parity test — so this is a shape assertion, not a lie).\n */\nexport function fromRow<T = Row>(table: TableName, row: Row): T {\n const record: Row = {};\n for (const [column, key] of columnsOf(table)) {\n const value = row[column];\n if (NULLABLE_COLUMNS.has(`${table}.${column}`)) {\n record[key] = value === undefined ? null : value;\n continue;\n }\n if (value === null || value === undefined) continue;\n if (column.endsWith(JSON_SUFFIX)) record[key] = JSON.parse(value as string);\n else if (BOOLEAN_COLUMNS.has(column)) record[key] = Boolean(value);\n else record[key] = value;\n }\n return record as unknown as T;\n}\n\n/** `INSERT INTO <table> (...) VALUES (...)`, every column of the table, in `TABLE_COLUMNS` order. */\nexport function insertRow(driver: SqlDriver, table: TableName, record: Row): void {\n const row = toRow(table, record);\n const columns = columnNamesOf(table);\n const sql = `INSERT INTO ${table} (${columns.join(',')}) VALUES (${columns.map(() => '?').join(',')})`;\n driver.prepare(sql).run(...columns.map((column) => row[column]));\n}\n\n/**\n * `INSERT ... ON CONFLICT(<pk>) DO UPDATE SET <every other column> = excluded.<column>`: the \"puts are upserts by\n * primary key\" contract (2.4) for every table whose record is a plain replace-by-key (phases, agents, worktrees, ...).\n */\nexport function upsertRow(driver: SqlDriver, table: TableName, pk: readonly string[], record: Row): void {\n const row = toRow(table, record);\n const columns = columnNamesOf(table);\n const updates = columns.filter((column) => !pk.includes(column)).map((column) => `${column}=excluded.${column}`);\n const sql = `INSERT INTO ${table} (${columns.join(',')}) VALUES (${columns.map(() => '?').join(',')})\n ON CONFLICT(${pk.join(',')}) DO UPDATE SET ${updates.join(',')}`;\n driver.prepare(sql).run(...columns.map((column) => row[column]));\n}\n\n/** One row by its (possibly composite) primary key, or `undefined`. */\nexport function getRow<T = Row>(\n driver: SqlDriver,\n table: TableName,\n pk: readonly string[],\n values: readonly unknown[],\n): T | undefined {\n const sql = `SELECT * FROM ${table} WHERE ${pk.map((column) => `${column}=?`).join(' AND ')}`;\n const row = driver.prepare(sql).get(...values) as Row | undefined;\n return row && fromRow<T>(table, row);\n}\n","// The command inbox write (D5), shared verbatim by `StateStore.enqueueCommand` (its own `BEGIN IMMEDIATE`) and\n// `StoreTx.enqueueCommand` (the caller's already-open transaction) — same row, same three outcomes, one place.\nimport type { Clock } from '@cohorte/base';\nimport { sha256Hex } from '@cohorte/base';\nimport { type CommandEnvelope, canonicalCommandBody } from '@cohorte/protocol';\nimport type { CommandRecord, SqlDriver } from '../contract.ts';\nimport { getRow, insertRow, type Row } from './marshal.ts';\n\nexport type EnqueueStatus = 'enqueued' | 'duplicate' | 'id-reuse-conflict';\n\nexport function enqueueCommandRow(\n driver: SqlDriver,\n cmd: CommandEnvelope,\n clock: Clock,\n): { status: EnqueueStatus; record: CommandRecord } {\n const bodySha256 = sha256Hex(canonicalCommandBody(cmd));\n const existing = getRow(driver, 'commands', ['command_id'], [cmd.commandId]) as CommandRecord | undefined;\n if (existing) {\n return { status: existing.bodySha256 === bodySha256 ? 'duplicate' : 'id-reuse-conflict', record: existing };\n }\n const now = clock.now();\n const record: CommandRecord = {\n commandId: cmd.commandId,\n ...(cmd.runId === undefined ? {} : { runId: cmd.runId }),\n type: cmd.type,\n bodySha256,\n envelope: cmd,\n ...(cmd.auth ? { authScheme: cmd.auth.scheme, authValue: cmd.auth.value } : {}),\n status: 'pending',\n createdAt: now,\n updatedAt: now,\n };\n insertRow(driver, 'commands', record as unknown as Row);\n return { status: 'enqueued', record };\n}\n","// `StoreTx` over `node:sqlite` (DESIGN 2.4): every method issues real SQL inside the enclosing `BEGIN IMMEDIATE` (the\n// caller — `SqliteStateStore.transact` — owns that transaction). Reads use plain `SELECT`s rather than a JS-side\n// cache: a connection sees its own uncommitted writes, so \"read after write, inside one transaction\" falls out of\n// SQLite for free and needs no bookkeeping here. Mirrors `memory/state-store.ts`'s `MemoryTx` method for method: the\n// two stores must pass the identical conformance suite (ADR-0002).\nimport {\n type AgentId,\n type ApprovalId,\n type Clock,\n CohorteError,\n type CommandId,\n type EffectId,\n type ErrorInfo,\n type EventId,\n errorOf,\n type IdSource,\n type RunId,\n type SealedJson,\n} from '@cohorte/base';\nimport type { CommandEnvelope } from '@cohorte/protocol';\nimport {\n type AgentRecord,\n type ApprovalDecisionRecord,\n type ApprovalRecord,\n type ArtifactRecord,\n type BudgetRecord,\n type CommandRecord,\n type DurableEnvelope,\n type EffectIntent,\n type EffectRecord,\n type EffectState,\n type FindingRecord,\n HOST_COMPUTED_RUN_KEYS,\n type IncarnationRecord,\n type LeaseToken,\n type LedgerEntry,\n type PhaseRecord,\n type RunRecord,\n type SealedEventDraft,\n type SqlDriver,\n STATES_WITHOUT_HOST_COLUMNS,\n type StoredSnapshot,\n type StoreTx,\n StoreUsageError,\n type TransitionRecord,\n type WorktreeRecord,\n} from '../contract.ts';\nimport { envelopeOf, toEventRecord } from '../memory/chain.ts';\nimport { type EnqueueStatus, enqueueCommandRow } from './commands.ts';\nimport { columnNamesOf, fromRow, getRow, insertRow, type Row, toRow, upsertRow } from './marshal.ts';\n\nconst usage = (message: string): StoreUsageError => new StoreUsageError(message);\n\n/** `SQLITE_CONSTRAINT_PRIMARYKEY` / `SQLITE_CONSTRAINT_UNIQUE`, the two extended result codes of a uniqueness clash. */\nconst UNIQUENESS_ERRCODES = [1555, 2067];\n\n/**\n * `node:sqlite` reports EVERY constraint failure under the single code `ERR_SQLITE_ERROR` — NOT NULL, CHECK (including\n * `json_valid(…)`), foreign keys and the `events_no_update`/`events_no_delete` triggers' `RAISE(ABORT)` alike. Reading\n * that one code as \"this row already exists\" would turn a genuine corruption into a benign-looking no-op in the one\n * layer whose job is to refuse rather than guess, so narrow it to the uniqueness case and rethrow everything else.\n */\nfunction isUniqueViolation(error: unknown): boolean {\n if (!(error instanceof Error) || (error as NodeJS.ErrnoException).code !== 'ERR_SQLITE_ERROR') return false;\n const { errcode } = error as Error & { errcode?: number };\n if (typeof errcode === 'number') return UNIQUENESS_ERRCODES.includes(errcode);\n return /UNIQUE constraint failed|PRIMARY KEY must be unique/i.test(error.message);\n}\n\n/** Same rule as `memory/state-store.ts`, duplicated here rather than imported: it is 4 lines over 2 exported constants, and `sqlite/**` may not depend on `memory/**` for behaviour (only for the shared, store-agnostic chain math of `chain.ts`). */\nfunction assertHostColumns(run: RunRecord): void {\n if (STATES_WITHOUT_HOST_COLUMNS.includes(run.state)) return;\n // \"Set\" means non-null (the DDL's CHECK is `IS NOT NULL`): an explicit JSON `null` is well-typed for\n // `runtimePin?: JsonValue` but still leaves the column unset.\n const missing = HOST_COMPUTED_RUN_KEYS.filter((key) => run[key] === undefined || run[key] === null);\n if (missing.length > 0) {\n throw usage(`run ${run.runId} cannot be ${run.state} without its host-computed columns: ${missing.join(', ')}`);\n }\n}\n\nconst RUN_UPDATE_COLUMNS = columnNamesOf('runs').filter(\n (column) => !['run_id', 'last_sequence', 'last_hash', 'version'].includes(column),\n);\n\nexport class SqliteTx implements StoreTx {\n readonly #driver: SqlDriver;\n readonly #scope: RunId | 'project';\n readonly #lease: LeaseToken | null;\n readonly #clock: Clock;\n readonly #ids: IdSource;\n #closed = false;\n\n constructor(driver: SqlDriver, scope: RunId | 'project', lease: LeaseToken | null, clock: Clock, ids: IdSource) {\n this.#driver = driver;\n this.#scope = scope;\n this.#lease = lease;\n this.#clock = clock;\n this.#ids = ids;\n }\n\n /**\n * Called by `SqliteStateStore.transact` in a `finally`, on commit, on rollback and on a thenable body alike. A\n * `StoreTx` writes straight to the connection, so one that outlives its `BEGIN IMMEDIATE` — the continuation of an\n * async body keeps a live reference to it — would write in autocommit, unfenced and irrevocably (I6). Not part of\n * `StoreTx`: the contract hands bodies a tx, never the right to end one.\n */\n close(): void {\n this.#closed = true;\n }\n\n /** At the top of every method: a dead tx refuses, it does not half-apply. */\n #alive(): void {\n if (this.#closed) throw usage('this StoreTx is no longer valid: its transaction has ended');\n }\n\n #readRun(id: RunId): RunRecord | undefined {\n return getRow<RunRecord>(this.#driver, 'runs', ['run_id'], [id]);\n }\n\n /** The run of this transaction; refuses a project transaction and a write aimed at another run. */\n #own(id: RunId, what: string): RunRecord {\n if (this.#scope === 'project') throw usage(`${what} is run-scoped: not legal in a project transaction`);\n if (id !== this.#scope) throw usage(`${what} targets run ${id} inside a transaction scoped to ${this.#scope}`);\n const run = this.#readRun(id);\n if (!run) throw usage(`${what}: run ${id} does not exist`);\n return run;\n }\n\n #scoped(what: string): RunRecord {\n if (this.#scope === 'project') throw usage(`${what} is run-scoped: not legal in a project transaction`);\n return this.#own(this.#scope, what);\n }\n\n appendEvents(drafts: readonly SealedEventDraft[]): DurableEnvelope[] {\n this.#alive();\n const run = this.#scoped('appendEvents');\n let lastSequence = run.lastSequence;\n let lastHash = run.lastHash;\n const appended: DurableEnvelope[] = [];\n for (const draft of drafts) {\n if (draft.runId !== run.runId) throw usage(`appendEvents: an event of run ${draft.runId} in run ${run.runId}`);\n const sequence = lastSequence + 1;\n const record = toEventRecord(draft, sequence, lastHash);\n try {\n insertRow(this.#driver, 'events', record as unknown as Row);\n } catch (error) {\n if (isUniqueViolation(error)) throw usage(`appendEvents: eventId ${draft.eventId} exists`);\n throw error;\n }\n lastSequence = sequence;\n lastHash = record.hash;\n appended.push(envelopeOf(record));\n }\n if (drafts.length > 0) {\n this.#driver\n .prepare('UPDATE runs SET last_sequence=?, last_hash=?, version=version+1 WHERE run_id=?')\n .run(lastSequence, lastHash, run.runId);\n }\n return appended;\n }\n\n recordTransition(t: TransitionRecord): 'recorded' | 'duplicate' {\n this.#alive();\n this.#own(t.runId, 'recordTransition');\n try {\n insertRow(this.#driver, 'transitions', t as unknown as Row);\n return 'recorded';\n } catch (error) {\n if (isUniqueViolation(error)) return 'duplicate';\n throw error;\n }\n }\n\n putRun(r: RunRecord): void {\n this.#alive();\n const existing = this.#readRun(r.runId);\n if (this.#scope === 'project') {\n if (existing) throw usage(`putRun: run ${r.runId} exists; a project transaction may only CREATE a run`);\n } else if (r.runId !== this.#scope) {\n throw usage(`putRun targets run ${r.runId} inside a transaction scoped to ${this.#scope}`);\n } else if (!existing) {\n // `start` = { IDLE run row + signed start command } in ONE project transaction (4.3 #1): a run-scoped\n // transaction may REWRITE its run, never mint one out of thin air.\n throw usage(`putRun: run ${r.runId} does not exist; a run-scoped transaction may only rewrite an existing run`);\n }\n const next: RunRecord = {\n ...r,\n lastSequence: existing?.lastSequence ?? 0,\n lastHash: existing?.lastHash ?? '',\n version: existing?.version ?? 0,\n };\n assertHostColumns(next);\n upsertRow(this.#driver, 'runs', ['run_id'], next as unknown as Row);\n }\n\n patchRun(id: RunId, p: Partial<RunRecord>): void {\n this.#alive();\n const run = this.#own(id, 'patchRun');\n const { runId: _runId, lastSequence: _seq, lastHash: _hash, version: _version, ...patch } = p;\n const next: RunRecord = { ...run, ...patch };\n assertHostColumns(next);\n const row = toRow('runs', next as unknown as Row);\n const sql = `UPDATE runs SET ${RUN_UPDATE_COLUMNS.map((column) => `${column}=?`).join(',')} WHERE run_id=?`;\n this.#driver.prepare(sql).run(...RUN_UPDATE_COLUMNS.map((column) => row[column]), id);\n }\n\n putPhase(p: PhaseRecord): void {\n this.#alive();\n this.#own(p.runId, 'putPhase');\n upsertRow(this.#driver, 'phases', ['run_id', 'phase_run_id'], p as unknown as Row);\n }\n\n putAgent(a: AgentRecord): void {\n this.#alive();\n this.#own(a.runId, 'putAgent');\n upsertRow(this.#driver, 'agents', ['run_id', 'agent_id'], a as unknown as Row);\n }\n\n putIncarnation(i: IncarnationRecord): void {\n this.#alive();\n this.#own(i.runId, 'putIncarnation');\n if (!getRow(this.#driver, 'agents', ['run_id', 'agent_id'], [i.runId, i.agentId])) {\n throw usage(`putIncarnation: unknown agent ${i.agentId}`);\n }\n upsertRow(this.#driver, 'agent_incarnations', ['run_id', 'agent_id', 'incarnation'], i as unknown as Row);\n }\n\n putWorktree(w: WorktreeRecord): void {\n this.#alive();\n this.#own(w.runId, 'putWorktree');\n upsertRow(this.#driver, 'worktrees', ['run_id', 'slot'], w as unknown as Row);\n }\n\n putLedger(e: LedgerEntry): void {\n this.#alive();\n this.#own(e.runId, 'putLedger');\n upsertRow(this.#driver, 'worktree_ledger', ['run_id', 'slot', 'path'], e as unknown as Row);\n }\n\n clearLedger(id: RunId, slot: string, upToEffectSeq: number): void {\n this.#alive();\n this.#own(id, 'clearLedger');\n this.#driver\n .prepare('DELETE FROM worktree_ledger WHERE run_id=? AND slot=? AND effect_seq<=?')\n .run(id, slot, upToEffectSeq);\n }\n\n putApproval(a: ApprovalRecord): 'created' | 'exists' {\n this.#alive();\n this.#own(a.runId, 'putApproval');\n const byKey = this.#driver\n .prepare('SELECT approval_id FROM approvals WHERE run_id=? AND idempotency_key=?')\n .get(a.runId, a.idempotencyKey);\n const byId = getRow(this.#driver, 'approvals', ['approval_id'], [a.approvalId]);\n if (byKey !== undefined || byId !== undefined) return 'exists';\n insertRow(this.#driver, 'approvals', a as unknown as Row);\n return 'created';\n }\n\n resolveApproval(id: ApprovalId, d: ApprovalDecisionRecord): 'resolved' | 'already-resolved' {\n this.#alive();\n const row = getRow<ApprovalRecord>(this.#driver, 'approvals', ['approval_id'], [id]);\n if (!row) throw usage(`resolveApproval: unknown approval ${id}`);\n this.#own(row.runId, 'resolveApproval');\n const isGrantAnswer = d.answer === 'allow-once' || d.answer === 'allow-for-run' || d.answer === 'deny';\n if (!isGrantAnswer) {\n const unused =\n row.status === 'allow-for-run' || (row.status === 'allow-once' && row.consumedByEffect === undefined);\n if (row.status !== 'pending' && !unused) return 'already-resolved';\n } else if (row.status !== 'pending') {\n return 'already-resolved';\n }\n const { auth, resolvedSeq, ...decision } = d;\n this.#driver\n .prepare(\n `UPDATE approvals SET status=?, decision_json=?, command_auth_json=COALESCE(?, command_auth_json),\n resolved_seq=?, resolved_at=? WHERE approval_id=?`,\n )\n .run(d.answer, JSON.stringify(decision), auth ? JSON.stringify(auth) : null, resolvedSeq, d.decidedAt, id);\n return 'resolved';\n }\n\n findGrant(id: RunId, grantKey: string): ApprovalRecord | undefined {\n this.#alive();\n this.#own(id, 'findGrant');\n const rows = (\n this.#driver\n .prepare(\n `SELECT * FROM approvals WHERE run_id=? AND grant_key=?\n AND (status='allow-for-run' OR (status='allow-once' AND consumed_by_effect IS NULL))\n ORDER BY requested_seq, approval_id`,\n )\n .all(id, grantKey) as Row[]\n ).map((row) => fromRow<ApprovalRecord>('approvals', row));\n return rows.find((row) => row.status === 'allow-for-run') ?? rows[0];\n }\n\n setBudget(b: BudgetRecord): void {\n this.#alive();\n this.#own(b.runId, 'setBudget');\n upsertRow(this.#driver, 'budgets', ['run_id', 'level', 'scope_id'], b as unknown as Row);\n }\n\n putArtifact(a: ArtifactRecord): void {\n this.#alive();\n this.#own(a.runId, 'putArtifact');\n upsertRow(this.#driver, 'artifacts', ['run_id', 'artifact_id'], a as unknown as Row);\n }\n\n putFinding(f: FindingRecord): void {\n this.#alive();\n this.#own(f.runId, 'putFinding');\n upsertRow(this.#driver, 'findings', ['run_id', 'finding_id'], f as unknown as Row);\n }\n\n #consumeGrant(run: RunRecord, grant: ApprovalId, by: EffectId): void {\n const row = getRow<ApprovalRecord>(this.#driver, 'approvals', ['approval_id'], [grant]);\n const refuse = (why: string): CohorteError =>\n new CohorteError(errorOf('conflict/unexpected', `approval ${grant} cannot authorise effect ${by}: ${why}`));\n if (!row || row.runId !== run.runId) throw refuse('no such approval in this run');\n if (row.status === 'allow-for-run') return;\n if (row.status !== 'allow-once') throw refuse(`its status is ${row.status}`);\n if (row.consumedByEffect === by) return;\n if (row.consumedByEffect !== undefined) throw refuse(`already consumed by ${row.consumedByEffect}`);\n this.#driver.prepare('UPDATE approvals SET consumed_by_effect=? WHERE approval_id=?').run(by, grant);\n }\n\n beginEffect(\n e: EffectIntent,\n ):\n | { status: 'started'; effectId: EffectId }\n | { status: 'already-done'; record: EffectRecord }\n | { status: 'open'; record: EffectRecord } {\n this.#alive();\n const run = this.#own(e.runId, 'beginEffect');\n const existingRow = this.#driver\n .prepare('SELECT * FROM effects WHERE run_id=? AND idempotency_key=?')\n .get(e.runId, e.idempotencyKey) as Row | undefined;\n const existing = existingRow && fromRow<EffectRecord>('effects', existingRow);\n if (existing && existing.state === 'done') return { status: 'already-done', record: existing };\n if (existing && (existing.state === 'intent' || existing.state === 'in-doubt')) {\n return { status: 'open', record: existing };\n }\n const effectId = existing?.effectId ?? this.#ids.next<'EffectId'>('eff');\n if (e.consumesGrant) this.#consumeGrant(run, e.consumesGrant, effectId);\n const now = this.#clock.now();\n const { runId, idempotencyKey, kind, replayClass, request, verify, ...optional } = e;\n const record: EffectRecord = {\n effectId,\n runId,\n idempotencyKey,\n kind,\n replayClass,\n state: 'intent',\n request,\n verify,\n ...optional,\n fencingToken: this.#lease?.fencingToken ?? 0,\n intentSeq: run.lastSequence,\n createdAt: existing?.createdAt ?? now,\n updatedAt: now,\n };\n upsertRow(this.#driver, 'effects', ['effect_id'], record as unknown as Row);\n return { status: 'started', effectId };\n }\n\n #openEffect(id: EffectId, what: string, from: readonly EffectState[]): { effect: EffectRecord; run: RunRecord } {\n const effect = getRow<EffectRecord>(this.#driver, 'effects', ['effect_id'], [id]);\n if (!effect) throw usage(`${what}: unknown effect ${id}`);\n const run = this.#own(effect.runId, what);\n if (!from.includes(effect.state)) throw usage(`${what}: effect ${id} is ${effect.state}`);\n return { effect, run };\n }\n\n completeEffect(id: EffectId, result: SealedJson, post?: { treeDigest?: string; head?: string }): void {\n this.#alive();\n const { effect, run } = this.#openEffect(id, 'completeEffect', ['intent', 'in-doubt']);\n this.#driver\n .prepare('UPDATE effects SET state=?, result_json=?, error_json=NULL, done_seq=?, updated_at=? WHERE effect_id=?')\n .run('done', JSON.stringify(result), run.lastSequence, this.#clock.now(), id);\n if (effect.slot !== undefined && post?.treeDigest !== undefined) {\n this.#driver\n .prepare('UPDATE worktrees SET last_tree_digest=? WHERE run_id=? AND slot=?')\n .run(post.treeDigest, run.runId, effect.slot);\n }\n }\n\n failEffect(id: EffectId, error: ErrorInfo): void {\n this.#alive();\n const { run } = this.#openEffect(id, 'failEffect', ['intent', 'in-doubt']);\n this.#driver\n .prepare('UPDATE effects SET state=?, error_json=?, done_seq=?, updated_at=? WHERE effect_id=?')\n .run('failed', JSON.stringify(error), run.lastSequence, this.#clock.now(), id);\n }\n\n markEffectInDoubt(id: EffectId, note: string): void {\n this.#alive();\n this.#openEffect(id, 'markEffectInDoubt', ['intent', 'in-doubt']);\n this.#driver\n .prepare('UPDATE effects SET state=?, error_json=?, updated_at=? WHERE effect_id=?')\n .run('in-doubt', JSON.stringify(errorOf('human-required/in-doubt-effect', note)), this.#clock.now(), id);\n }\n\n compensateEffects(ids: EffectId[], byEffect: EffectId): void {\n this.#alive();\n if (!getRow(this.#driver, 'effects', ['effect_id'], [byEffect])) {\n throw usage(`compensateEffects: unknown compensating effect ${byEffect}`);\n }\n for (const id of ids) {\n this.#openEffect(id, 'compensateEffects', ['intent', 'done', 'failed', 'in-doubt']);\n this.#driver\n .prepare('UPDATE effects SET state=?, compensated_by=?, updated_at=? WHERE effect_id=?')\n .run('compensated', byEffect, this.#clock.now(), id);\n }\n }\n\n enqueueCommand(cmd: CommandEnvelope): EnqueueStatus {\n this.#alive();\n return enqueueCommandRow(this.#driver, cmd, this.#clock).status;\n }\n\n #command(id: CommandId, what: string): CommandRecord | undefined {\n const row = getRow<CommandRecord>(this.#driver, 'commands', ['command_id'], [id]);\n if (!row) return undefined;\n const home = row.runId ?? 'project';\n if (home !== this.#scope) throw usage(`${what}: command ${id} belongs to ${home}, not to ${this.#scope}`);\n return row;\n }\n\n claimCommand(id: CommandId, hostId: string): boolean {\n this.#alive();\n const row = this.#command(id, 'claimCommand');\n if (row?.status !== 'pending') return false;\n this.#driver\n .prepare('UPDATE commands SET status=?, claimed_by=?, updated_at=? WHERE command_id=?')\n .run('claimed', hostId, this.#clock.now(), id);\n return true;\n }\n\n finishCommand(id: CommandId, outcome: 'completed' | 'rejected', resultEventId: EventId): void {\n this.#alive();\n const row = this.#command(id, 'finishCommand');\n if (!row) throw usage(`finishCommand: unknown command ${id}`);\n if (row.status === 'completed' || row.status === 'rejected') {\n throw usage(`finishCommand: command ${id} is already ${row.status}`);\n }\n this.#driver\n .prepare('UPDATE commands SET status=?, result_event_id=?, updated_at=? WHERE command_id=?')\n .run(outcome, resultEventId, this.#clock.now(), id);\n }\n\n writeSnapshot(s: StoredSnapshot): void {\n this.#alive();\n const run = this.#own(s.runId, 'writeSnapshot');\n if (s.atSequence > run.lastSequence) {\n throw usage(`writeSnapshot: at ${s.atSequence} but the journal of ${s.runId} ends at ${run.lastSequence}`);\n }\n upsertRow(this.#driver, 'snapshots', ['run_id', 'at_sequence'], s as unknown as Row);\n this.#driver\n .prepare(\n `DELETE FROM snapshots WHERE run_id=? AND at_sequence NOT IN\n (SELECT at_sequence FROM snapshots WHERE run_id=? ORDER BY at_sequence DESC LIMIT 3)`,\n )\n .run(s.runId, s.runId);\n }\n\n run(): RunRecord {\n this.#alive();\n return this.#scoped('run');\n }\n\n agent(id: AgentId): AgentRecord | undefined {\n this.#alive();\n const run = this.#scoped('agent');\n return getRow<AgentRecord>(this.#driver, 'agents', ['run_id', 'agent_id'], [run.runId, id]);\n }\n\n incarnation(id: AgentId, n: number): IncarnationRecord | undefined {\n this.#alive();\n const run = this.#scoped('incarnation');\n return getRow(this.#driver, 'agent_incarnations', ['run_id', 'agent_id', 'incarnation'], [run.runId, id, n]) as\n | IncarnationRecord\n | undefined;\n }\n\n worktree(slot: string): WorktreeRecord | undefined {\n this.#alive();\n const run = this.#scoped('worktree');\n return getRow<WorktreeRecord>(this.#driver, 'worktrees', ['run_id', 'slot'], [run.runId, slot]);\n }\n\n approval(id: ApprovalId): ApprovalRecord | undefined {\n this.#alive();\n const run = this.#scoped('approval');\n const row = getRow<ApprovalRecord>(this.#driver, 'approvals', ['approval_id'], [id]);\n return row && row.runId === run.runId ? row : undefined;\n }\n\n effectByKey(key: string): EffectRecord | undefined {\n this.#alive();\n const run = this.#scoped('effectByKey');\n const row = this.#driver\n .prepare('SELECT * FROM effects WHERE run_id=? AND idempotency_key=?')\n .get(run.runId, key) as Row | undefined;\n return row && fromRow<EffectRecord>('effects', row);\n }\n\n budget(level: string, scopeId: string): BudgetRecord | undefined {\n this.#alive();\n const run = this.#scoped('budget');\n return getRow(this.#driver, 'budgets', ['run_id', 'level', 'scope_id'], [run.runId, level, scopeId]) as\n | BudgetRecord\n | undefined;\n }\n}\n","// `SqliteStateStore` (DESIGN 2.4, ADR-0002): `StateStore` over `node:sqlite`. Reads never open a transaction (I13\n// \"lock-free, safe to SIGKILL the reader at any instant\" — SQLite's own MVCC/WAL readers never block a writer, or\n// each other). Writes always `BEGIN IMMEDIATE` first (I6): `transact()` for the run/project path, and a private\n// `BEGIN IMMEDIATE` of its own for `acquireLock`/`stealLock`/`enqueueCommand`, which are not routed through it.\nimport { existsSync } from 'node:fs';\nimport {\n type ArtifactId,\n type Clock,\n CohorteError,\n type CommandId,\n createUuidV7IdSource,\n errorOf,\n type IdSource,\n type RunId,\n systemClock,\n toIsoInstant,\n} from '@cohorte/base';\nimport type { CommandEnvelope, PipelineState } from '@cohorte/protocol';\nimport {\n type ApprovalRecord,\n type ArtifactRecord,\n type CommandRecord,\n type DurableEnvelope,\n type DurableEventType,\n type EffectRecord,\n type EffectState,\n type EventRecord,\n type LeaseToken,\n type LedgerEntry,\n type LockRecord,\n type LockRequest,\n type LockScope,\n locksConflict,\n type MigrationReport,\n NO_RUN_ID,\n type RunRecord,\n type RunTreeRows,\n type SqlDriver,\n type StateStore,\n type StoredSnapshot,\n type StoreInfo,\n type StoreTx,\n StoreUsageError,\n type VerifyChainResult,\n} from '../contract.ts';\nimport { envelopeOf, verifyEventRecords } from '../memory/chain.ts';\nimport { createMigrator } from '../migrate/index.ts';\nimport { type EnqueueStatus, enqueueCommandRow } from './commands.ts';\nimport { createNodeSqliteDriver, DEFAULT_MIGRATIONS_DIR } from './driver.ts';\nimport { fromRow, getRow, insertRow, type Row } from './marshal.ts';\nimport { SqliteTx } from './tx.ts';\n\nexport interface SqliteStoreOptions {\n /** `<main checkout>/.cohorte/state/cohorte.db`, or `:memory:` */\n path: string;\n /** where the numbered `*.sql` files live; defaults to the embedded `migrations/state` */\n migrationsDir?: string;\n /** `node:sqlite` by default; `better-sqlite3` is the documented fallback behind the same seam (ADR-0002) */\n driver?: (path: string) => SqlDriver;\n clock?: Clock;\n ids?: IdSource;\n /** stamped on every applied migration row; defaults to this package's understanding of the current 3.0 line */\n cohorteVersion?: string;\n}\n\nconst DEFAULT_COHORTE_VERSION = '3.0.0';\n\nconst usage = (message: string): StoreUsageError => new StoreUsageError(message);\nconst isThenable = (value: unknown): boolean =>\n (typeof value === 'object' || typeof value === 'function') &&\n value !== null &&\n typeof (value as { then?: unknown }).then === 'function';\n\nfunction safeRollback(driver: SqlDriver): void {\n try {\n driver.exec('ROLLBACK');\n } catch {\n // a fatal SQLite error (e.g. a trigger's RAISE(ABORT, ...)) already rolled the transaction back\n }\n}\n\nconst incompatibleSchema = (message: string): CohorteError =>\n new CohorteError(errorOf('corruption/incompatible-schema', message));\n\nexport class SqliteStateStore implements StateStore {\n readonly kind = 'sqlite';\n readonly #path: string;\n readonly #migrationsDir: string;\n readonly #driverFactory: (path: string) => SqlDriver;\n readonly #clock: Clock;\n readonly #ids: IdSource;\n readonly #cohorteVersion: string;\n #driver: SqlDriver | undefined;\n #opened = false;\n\n constructor(options: SqliteStoreOptions) {\n this.#path = options.path;\n this.#migrationsDir = options.migrationsDir ?? DEFAULT_MIGRATIONS_DIR;\n this.#driverFactory = options.driver ?? createNodeSqliteDriver;\n this.#clock = options.clock ?? systemClock;\n this.#ids = options.ids ?? createUuidV7IdSource();\n this.#cohorteVersion = options.cohorteVersion ?? DEFAULT_COHORTE_VERSION;\n }\n\n /**\n * The connection, opened on first use. Lazy on purpose (DESIGN 2.4 `openSqliteStore`: \"nothing touches the file\n * before `open()` or `migrate()`\") — and PRIVATE to the three entry points that are allowed to materialise the file:\n * `open()`, `migrate()` and `backup()`. Everything else goes through `#db()`.\n */\n #connection(): SqlDriver {\n if (!this.#driver) this.#driver = this.#driverFactory(this.#path);\n return this.#driver;\n }\n\n /**\n * The connection of an OPEN store. DESIGN 2.4 has `open()` \"refuse rather than guessing; never auto-migrate\": a read\n * on a store nobody opened must say so, not create an empty `cohorte.db` (+ `-wal`, `-shm`) as a side effect and then\n * fail with a raw `ERR_SQLITE_ERROR` about a missing table.\n */\n #db(): SqlDriver {\n if (!this.#opened) throw usage(`the store at ${this.#path} is not open: call open() (or migrate()) first`);\n return this.#connection();\n }\n\n #migrator() {\n return createMigrator({\n driver: this.#connection(),\n migrationsDir: this.#migrationsDir,\n cohorteVersion: this.#cohorteVersion,\n });\n }\n\n async open(): Promise<StoreInfo> {\n const report = this.#migrator().check();\n if (report.current !== report.target) {\n throw incompatibleSchema(\n `the state database at ${this.#path} is at schema ${report.current}, this build's migrations/state expects ${report.target}`,\n );\n }\n this.#opened = true;\n return { kind: this.kind, schemaVersion: report.current, location: this.#path };\n }\n\n async close(): Promise<void> {\n this.#opened = false;\n if (this.#driver) {\n this.#driver.close();\n this.#driver = undefined;\n }\n }\n\n async migrate(mode: 'check' | 'apply'): Promise<MigrationReport> {\n const migrator = this.#migrator();\n if (mode === 'check') return migrator.check();\n const report = migrator.check();\n if (report.current > report.target) {\n throw incompatibleSchema(\n `the state database at ${this.#path} is at schema ${report.current}, newer than this build's migrations/state (target ${report.target})`,\n );\n }\n if (report.pending.length === 0) return { ...report, mode: 'apply', applied: [] };\n // Bootstrap (0001 creates `locks` itself): nothing to lock or back up yet.\n if (report.current === 0) return migrator.apply();\n const owner = { hostId: 'migrate', pid: process.pid, startToken: this.#ids.next<'MigrationToken'>('tok') };\n // Not `this.acquireLock`: the public lock methods require an OPEN store, and `migrate()` is precisely what runs\n // before `open()` can succeed.\n const acquired = this.#acquireLockOn(this.#connection(), {\n scope: 'project',\n key: 'project',\n mode: 'exclusive',\n owner,\n ttlMs: 300_000,\n });\n if (!acquired.ok) {\n throw new CohorteError(\n errorOf(\n 'conflict/unexpected',\n 'migrate --apply: the project lock is held; cannot migrate while the project is in use',\n ),\n );\n }\n try {\n const backupPath = `${this.#path}.bak-${Date.now()}`;\n await this.backup(backupPath);\n const applied = migrator.apply();\n return { ...applied, backupPath };\n } finally {\n this.#connection().prepare('DELETE FROM locks WHERE lock_id=?').run(acquired.lease.lockId);\n }\n }\n\n /**\n * `VACUUM INTO`, on the store's own connection — NOT a checkpoint plus a file copy.\n *\n * ADR-0002 makes lock-free readers the normal state of this file (\"observers are lock-free readers and are\n * SIGKILL-safe\"), and any reader parked in a read transaction blocks `PRAGMA wal_checkpoint(TRUNCATE)`: the pragma\n * then reports `busy` and leaves the committed pages in the `-wal`, so copying the main file alone yields a\n * TRUNCATED, unopenable database (\"database disk image is malformed\"). `VACUUM INTO` writes a complete, consistent\n * database from the connection's own read view instead, whoever else is on the file. This is the only safety net\n * `migrate('apply')` takes before mutating the schema, so it may not be silently empty.\n */\n async backup(toPath: string): Promise<void> {\n if (this.#path === ':memory:') throw usage('backup: an in-memory store has nothing to back up');\n // SQLite refuses an existing target itself; saying so here keeps the failure typed and the message actionable.\n if (existsSync(toPath)) throw usage(`backup: ${toPath} already exists; a backup never overwrites`);\n this.#connection().prepare('VACUUM INTO ?').run(toPath);\n }\n\n async transact<T>(\n scope: { runId: RunId } | 'project',\n lease: LeaseToken | null,\n body: (tx: StoreTx) => T,\n opts?: { expectedSequence?: number },\n ): Promise<T> {\n if (!this.#opened) throw usage('the store is not open');\n const db = this.#db();\n const target = scope === 'project' ? scope : scope.runId;\n if (target !== 'project') {\n if (!lease) throw usage(`a transaction on run ${target} needs the run lease`);\n if (lease.runId !== target) throw usage(`the lease of run ${lease.runId || '(none)'} cannot write run ${target}`);\n }\n db.exec('BEGIN IMMEDIATE');\n let tx: SqliteTx | undefined;\n try {\n // I6: the FIRST statement of every write transaction asserts the lease's fencing token — and that the lease\n // really is THE lock of this write's scope (a zone or migration lock of the same run/host is not a licence\n // to write the run: two writers for one run is exactly what I6 forbids).\n if (lease) {\n const lock = getRow<LockRecord>(db, 'locks', ['lock_id'], [lease.lockId]);\n const rightKind =\n target === 'project' ? lock?.scope === 'project' : lock?.scope === 'run' && lock.key === target;\n if (!lock || !rightKind || lock.fencingToken !== lease.fencingToken || lock.ownerHostId !== lease.hostId) {\n throw new CohorteError(\n errorOf(\n 'conflict/lease-lost',\n `lock ${lease.lockId} is no longer held with fencing token ${lease.fencingToken}`,\n ),\n );\n }\n }\n if (opts?.expectedSequence !== undefined) {\n if (target === 'project') throw usage('expectedSequence needs a run-scoped transaction');\n const run = getRow<RunRecord>(db, 'runs', ['run_id'], [target]);\n if (run?.lastSequence !== opts.expectedSequence) {\n throw new CohorteError(\n errorOf(\n 'conflict/unexpected',\n `run ${target} is at sequence ${run?.lastSequence}, expected ${opts.expectedSequence}`,\n ),\n );\n }\n }\n tx = new SqliteTx(db, target, lease, this.#clock, this.#ids);\n const result = body(tx);\n if (isThenable(result)) throw usage('a transaction body must be synchronous: it returned a thenable');\n db.exec('COMMIT');\n return result;\n } catch (error) {\n safeRollback(db);\n throw error;\n } finally {\n // The tx dies on commit, on rollback and on the thenable rejection alike. Rejecting the CALLER of an async body\n // is not enough: its continuation still holds this `StoreTx`, whose methods write straight to the connection —\n // after the ROLLBACK that would be in autocommit, unfenced, and permanently committed (I6).\n tx?.close();\n }\n }\n\n async getRun(id: RunId): Promise<RunRecord | undefined> {\n return getRow<RunRecord>(this.#db(), 'runs', ['run_id'], [id]);\n }\n\n async listRuns(q: { states?: PipelineState[]; limit: number; offset: number }): Promise<RunRecord[]> {\n const db = this.#db();\n const params: unknown[] = [];\n let sql = 'SELECT * FROM runs';\n if (q.states && q.states.length > 0) {\n sql += ` WHERE state IN (${q.states.map(() => '?').join(',')})`;\n params.push(...q.states);\n }\n sql += ' ORDER BY started_at DESC, run_id ASC LIMIT ? OFFSET ?';\n params.push(q.limit, q.offset);\n return (db.prepare(sql).all(...params) as Row[]).map((row) => fromRow<RunRecord>('runs', row));\n }\n\n async readEvents(\n id: RunId,\n q: { afterSequence: number; limit: number; types?: DurableEventType[] },\n ): Promise<DurableEnvelope[]> {\n const db = this.#db();\n const params: unknown[] = [id, q.afterSequence];\n let sql = 'SELECT * FROM events WHERE run_id=? AND sequence>?';\n if (q.types && q.types.length > 0) {\n sql += ` AND type IN (${q.types.map(() => '?').join(',')})`;\n params.push(...q.types);\n }\n sql += ' ORDER BY sequence LIMIT ?';\n params.push(q.limit);\n return (db.prepare(sql).all(...params) as Row[]).map((row) => envelopeOf(fromRow<EventRecord>('events', row)));\n }\n\n async loadSnapshot(id: RunId): Promise<StoredSnapshot | undefined> {\n const row = this.#db()\n .prepare('SELECT * FROM snapshots WHERE run_id=? ORDER BY at_sequence DESC LIMIT 1')\n .get(id) as Row | undefined;\n return row && fromRow<StoredSnapshot>('snapshots', row);\n }\n\n async readRunTree(id: RunId): Promise<RunTreeRows> {\n const run = await this.getRun(id);\n if (!run) throw usage(`readRunTree: run ${id} does not exist`);\n const db = this.#db();\n const of = <T>(table: 'phases' | 'agents' | 'agent_incarnations' | 'worktrees' | 'approvals' | 'budgets'): T[] =>\n (db.prepare(`SELECT * FROM ${table} WHERE run_id=?`).all(id) as Row[]).map((row) => fromRow<T>(table, row));\n return {\n run,\n phases: of<RunTreeRows['phases'][number]>('phases'),\n agents: of<RunTreeRows['agents'][number]>('agents'),\n incarnations: of<RunTreeRows['incarnations'][number]>('agent_incarnations'),\n worktrees: of<RunTreeRows['worktrees'][number]>('worktrees'),\n approvals: of<RunTreeRows['approvals'][number]>('approvals'),\n budgets: of<RunTreeRows['budgets'][number]>('budgets'),\n locks: (db.prepare('SELECT * FROM locks WHERE owner_run_id=?').all(id) as Row[]).map((row) =>\n fromRow<LockRecord>('locks', row),\n ),\n };\n }\n\n async listPendingApprovals(id?: RunId): Promise<ApprovalRecord[]> {\n const db = this.#db();\n const rows = (\n id === undefined\n ? (db.prepare(`SELECT * FROM approvals WHERE status='pending' ORDER BY created_at, approval_id`).all() as Row[])\n : (db\n .prepare(`SELECT * FROM approvals WHERE status='pending' AND run_id=? ORDER BY created_at, approval_id`)\n .all(id) as Row[])\n ).map((row) => fromRow<ApprovalRecord>('approvals', row));\n return rows;\n }\n\n async listEffects(id: RunId, q: { states: EffectState[] }): Promise<EffectRecord[]> {\n const placeholders = q.states.map(() => '?').join(',');\n return (\n this.#db()\n .prepare(`SELECT * FROM effects WHERE run_id=? AND state IN (${placeholders})`)\n .all(id, ...q.states) as Row[]\n ).map((row) => fromRow<EffectRecord>('effects', row));\n }\n\n async readLedger(id: RunId, slot: string): Promise<LedgerEntry[]> {\n return (\n this.#db().prepare('SELECT * FROM worktree_ledger WHERE run_id=? AND slot=? ORDER BY path').all(id, slot) as Row[]\n ).map((row) => fromRow<LedgerEntry>('worktree_ledger', row));\n }\n\n async getArtifact(id: RunId, artifact: ArtifactId): Promise<ArtifactRecord | undefined> {\n return getRow<ArtifactRecord>(this.#db(), 'artifacts', ['run_id', 'artifact_id'], [id, artifact]);\n }\n\n async verifyChain(id: RunId, key?: Uint8Array): Promise<VerifyChainResult> {\n const db = this.#db();\n const run = getRow<RunRecord>(db, 'runs', ['run_id'], [id]);\n const tail = run && !run.purgeable ? { lastSequence: run.lastSequence, lastHash: run.lastHash } : undefined;\n const rows = (db.prepare('SELECT * FROM events WHERE run_id=? ORDER BY sequence').all(id) as Row[]).map((row) =>\n fromRow<EventRecord>('events', row),\n );\n return verifyEventRecords(id, rows, key, tail);\n }\n\n /**\n * Retention-only administrative operation. The migration trigger permits\n * deleting events exclusively after the run has been marked purgeable; keep\n * this outside StateStore so ordinary callers cannot acquire a destructive\n * capability accidentally.\n */\n async purgeEvents(id: RunId): Promise<number> {\n const db = this.#db();\n db.exec('BEGIN IMMEDIATE');\n try {\n const result = db.prepare('DELETE FROM events WHERE run_id=?').run(id);\n db.exec('COMMIT');\n return Number(result.changes);\n } catch (error) {\n safeRollback(db);\n throw error;\n }\n }\n\n async enqueueCommand(cmd: CommandEnvelope): Promise<{ status: EnqueueStatus; record: CommandRecord }> {\n const db = this.#db();\n db.exec('BEGIN IMMEDIATE');\n try {\n const result = enqueueCommandRow(db, cmd, this.#clock);\n db.exec('COMMIT');\n return result;\n } catch (error) {\n safeRollback(db);\n throw error;\n }\n }\n\n async pendingCommands(id: RunId): Promise<CommandRecord[]> {\n return (\n this.#db()\n .prepare(`SELECT * FROM commands WHERE run_id=? AND status='pending' ORDER BY created_at, command_id`)\n .all(id) as Row[]\n ).map((row) => fromRow<CommandRecord>('commands', row));\n }\n\n async getCommand(id: CommandId): Promise<CommandRecord | undefined> {\n return getRow<CommandRecord>(this.#db(), 'commands', ['command_id'], [id]);\n }\n\n /** Monotonic per (scope,key), across release/reacquire cycles: `locks` rows disappear on release, so the counter lives in `meta` (2.4's generic key/value table — DESIGN names no other place for it). */\n #nextFencingToken(db: SqlDriver, scope: LockScope, key: string): number {\n const metaKey = `fencing:${scope}:${key}`;\n const row = db.prepare('SELECT value FROM meta WHERE key=?').get(metaKey) as { value: string } | undefined;\n const next = (row ? Number.parseInt(row.value, 10) : 0) + 1;\n this.#setFencingToken(db, metaKey, next);\n return next;\n }\n\n #setFencingToken(db: SqlDriver, metaKey: string, value: number): void {\n db.prepare('INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(\n metaKey,\n String(value),\n );\n }\n\n #insertLock(db: SqlDriver, req: LockRequest, fencingToken: number): LeaseToken {\n const lockId = this.#ids.next<'LockId'>('lck');\n const now = Date.parse(this.#clock.now());\n const record: LockRecord = {\n lockId,\n scope: req.scope,\n key: req.key,\n mode: req.mode,\n ...(req.owner.runId === undefined ? {} : { ownerRunId: req.owner.runId }),\n ownerHostId: req.owner.hostId,\n ownerPid: req.owner.pid,\n ownerStartToken: req.owner.startToken,\n fencingToken,\n ...(req.zones ? { zones: [...req.zones] } : {}),\n leaseExpiresAt: toIsoInstant(now + req.ttlMs),\n acquiredAt: toIsoInstant(now),\n };\n insertRow(db, 'locks', record as unknown as Row);\n return { lockId, runId: req.owner.runId ?? NO_RUN_ID, hostId: req.owner.hostId, fencingToken };\n }\n\n async acquireLock(req: LockRequest): Promise<{ ok: true; lease: LeaseToken } | { ok: false; heldBy: LockRecord[] }> {\n return this.#acquireLockOn(this.#db(), req);\n }\n\n #acquireLockOn(\n db: SqlDriver,\n req: LockRequest,\n ): { ok: true; lease: LeaseToken } | { ok: false; heldBy: LockRecord[] } {\n db.exec('BEGIN IMMEDIATE');\n try {\n const existing = (db.prepare('SELECT * FROM locks WHERE scope=? AND key=?').all(req.scope, req.key) as Row[]).map(\n (row) => fromRow<LockRecord>('locks', row),\n );\n const conflicting = existing.filter((lock) => locksConflict(lock, req));\n if (conflicting.length > 0) {\n db.exec('ROLLBACK');\n return { ok: false, heldBy: conflicting };\n }\n const fencingToken = this.#nextFencingToken(db, req.scope, req.key);\n const lease = this.#insertLock(db, req, fencingToken);\n db.exec('COMMIT');\n return { ok: true, lease };\n } catch (error) {\n safeRollback(db);\n throw error;\n }\n }\n\n async stealLock(req: LockRequest, expected: LockRecord): Promise<LeaseToken> {\n const db = this.#db();\n db.exec('BEGIN IMMEDIATE');\n try {\n const current = getRow<LockRecord>(db, 'locks', ['lock_id'], [expected.lockId]);\n if (!current || current.fencingToken !== expected.fencingToken) {\n throw new CohorteError(\n errorOf('conflict/lease-lost', `lock ${expected.lockId} changed since it was read: nothing to steal`),\n );\n }\n const others = (\n db\n .prepare('SELECT * FROM locks WHERE scope=? AND key=? AND lock_id<>?')\n .all(req.scope, req.key, current.lockId) as Row[]\n ).map((row) => fromRow<LockRecord>('locks', row));\n const conflicting = others.filter((lock) => locksConflict(lock, req));\n if (conflicting.length > 0) {\n throw new CohorteError(\n errorOf(\n 'conflict/unexpected',\n `stealing ${current.lockId} would still conflict with ${conflicting.length} lock(s)`,\n ),\n );\n }\n db.prepare('DELETE FROM locks WHERE lock_id=?').run(current.lockId);\n const fencingToken = current.fencingToken + 1;\n this.#setFencingToken(db, `fencing:${req.scope}:${req.key}`, fencingToken);\n const lease = this.#insertLock(db, req, fencingToken);\n db.exec('COMMIT');\n return lease;\n } catch (error) {\n safeRollback(db);\n throw error;\n }\n }\n\n async renewLock(lockId: string, ttlMs: number): Promise<boolean> {\n const now = Date.parse(this.#clock.now());\n const result = this.#db()\n .prepare('UPDATE locks SET lease_expires_at=? WHERE lock_id=?')\n .run(toIsoInstant(now + ttlMs), lockId);\n return Number(result.changes) > 0;\n }\n\n async releaseLock(lockId: string): Promise<void> {\n this.#db().prepare('DELETE FROM locks WHERE lock_id=?').run(lockId);\n }\n\n async listLocks(q?: { scope?: LockScope }): Promise<LockRecord[]> {\n const db = this.#db();\n const rows = (\n q?.scope\n ? (db.prepare('SELECT * FROM locks WHERE scope=? ORDER BY acquired_at').all(q.scope) as Row[])\n : (db.prepare('SELECT * FROM locks ORDER BY acquired_at').all() as Row[])\n ).map((row) => fromRow<LockRecord>('locks', row));\n return rows;\n }\n}\n\nexport function openSqliteStore(options: SqliteStoreOptions): StateStore {\n return new SqliteStateStore(options);\n}\n","import type { JsonValue, TokenUsage } from '@cohorte/base';\nimport type { FakeAgentRule, FakeScript, FakeStep, FakeStepOf } from './index.ts';\n\nexport interface FakeScriptBuilder {\n defaults(defaults: NonNullable<FakeScript['defaults']>): FakeScriptBuilder;\n agent(match: FakeAgentRule['match'], steps: FakeStep[]): FakeScriptBuilder;\n build(): FakeScript;\n}\n\n/** Rules are tried in the order they were added. `build()` hands out a copy: the builder can go on being used. */\nexport function fakeScript(): FakeScriptBuilder {\n const agents: FakeAgentRule[] = [];\n let defaults: FakeScript['defaults'];\n const builder: FakeScriptBuilder = {\n defaults(next) {\n defaults = { ...defaults, ...next };\n return builder;\n },\n agent(match, steps) {\n agents.push({ match, steps });\n return builder;\n },\n build() {\n return structuredClone({ version: 1, agents, ...(defaults === undefined ? {} : { defaults }) });\n },\n };\n return builder;\n}\n\ntype ToolOptions = Pick<FakeStepOf<'tool'>, 'expect' | 'onDenied'>;\ntype ModelRequestOptions = Omit<FakeStepOf<'model-request'>, 'do'>;\n\n/** One constructor per step kind, so that a TypeScript test never spells a `do:` literal. */\nexport const step = {\n say: (text: string, chunks?: number): FakeStep => ({ do: 'say', text, ...(chunks === undefined ? {} : { chunks }) }),\n think: (text: string): FakeStep => ({ do: 'think', text }),\n tool: (tool: string, input: JsonValue, options: ToolOptions = {}): FakeStep => ({\n do: 'tool',\n tool,\n input,\n ...options,\n }),\n submit: (output: JsonValue): FakeStep => ({ do: 'submit', output }),\n usage: (tokens: Partial<TokenUsage>): FakeStep => ({ do: 'usage', tokens }),\n awaitMessage: (timeoutMs?: number): FakeStep => ({\n do: 'await-message',\n ...(timeoutMs === undefined ? {} : { timeoutMs }),\n }),\n fail: (error: FakeStepOf<'fail'>['error']): FakeStep => ({ do: 'fail', error }),\n hang: (ms: number | 'forever'): FakeStep => ({ do: 'hang', ms }),\n crash: (at: FakeStepOf<'crash'>['at']): FakeStep => ({ do: 'crash', at }),\n stopWithoutResult: (): FakeStep => ({ do: 'stop-without-result' }),\n modelRequest: (options: ModelRequestOptions = {}): FakeStep => ({ do: 'model-request', ...options }),\n} as const;\n","import type { FakeAgentRule, FakeScript } from './index.ts';\n\n/**\n * What a rule is matched against: `SpawnRequest` fields, plus `attempt`, which the fake derives from the requests it\n * has seen (a spawn without `continuation` opens an attempt, DESIGN 2.5 `retrying`). No phase, no pipeline word (R10).\n */\nexport interface FakeMatchSubject {\n role: string;\n agentId: string;\n incarnation: number;\n attempt: number;\n}\n\n/** `*` is any run of characters, `?` is one character, everything else is literal. */\nexport function globToRegExp(glob: string): RegExp {\n const source = glob.replace(/[.+^${}()|[\\]\\\\*?]/g, (char) => {\n if (char === '*') return '.*';\n if (char === '?') return '.';\n return `\\\\${char}`;\n });\n return new RegExp(`^${source}$`, 's');\n}\n\n/** The FIRST rule whose every present field agrees; an absent field, and `incarnation: 'any'`, constrain nothing. */\nexport function matchFakeRule(script: FakeScript, subject: FakeMatchSubject): FakeAgentRule | undefined {\n return script.agents.find(({ match }) => {\n if (match.role !== undefined && match.role !== subject.role) return false;\n if (match.agentId !== undefined && !globToRegExp(match.agentId).test(subject.agentId)) return false;\n if (match.incarnation !== undefined && match.incarnation !== 'any' && match.incarnation !== subject.incarnation)\n return false;\n if (match.attempt !== undefined && match.attempt !== subject.attempt) return false;\n return true;\n });\n}\n","// The `[S]` schema of DESIGN 3.10. Strict: a script is an input a human writes, a typo must not pass as a no-op.\nimport { ERROR_CODE_PATTERN, ErrorClass, JsonValueSchema, QuotaInfo, TokenUsage } from '@cohorte/base';\nimport { type Static, type TUnsafe, Type } from 'typebox';\nimport type { FakeScript } from './index.ts';\n\nconst strict = { additionalProperties: false } as const;\nconst count = () => Type.Integer({ minimum: 0 });\n\nconst PartialTokenUsage = Type.Object(\n {\n input: Type.Optional(count()),\n output: Type.Optional(count()),\n cacheRead: Type.Optional(count()),\n cacheWrite: Type.Optional(count()),\n total: Type.Optional(count()),\n },\n strict,\n);\n\nconst FakeScriptCyclic = Type.Cyclic(\n {\n FakeStep: Type.Union([\n Type.Object(\n { do: Type.Literal('say'), text: Type.String(), chunks: Type.Optional(Type.Integer({ minimum: 1 })) },\n strict,\n ),\n Type.Object({ do: Type.Literal('think'), text: Type.String() }, strict),\n Type.Object(\n {\n do: Type.Literal('tool'),\n tool: Type.String(),\n input: JsonValueSchema,\n expect: Type.Optional(\n Type.Object({ isError: Type.Optional(Type.Boolean()), textIncludes: Type.Optional(Type.String()) }, strict),\n ),\n onDenied: Type.Optional(Type.Array(Type.Ref('FakeStep'))),\n },\n strict,\n ),\n Type.Object({ do: Type.Literal('submit'), output: JsonValueSchema }, strict),\n Type.Object({ do: Type.Literal('usage'), tokens: PartialTokenUsage }, strict),\n Type.Object({ do: Type.Literal('await-message'), timeoutMs: Type.Optional(Type.Number({ minimum: 0 })) }, strict),\n Type.Object(\n {\n do: Type.Literal('fail'),\n error: Type.Object(\n {\n class: ErrorClass,\n code: Type.String({ pattern: ERROR_CODE_PATTERN }),\n retryable: Type.Boolean(),\n retryAfterMs: Type.Optional(Type.Number({ minimum: 0 })),\n },\n strict,\n ),\n },\n strict,\n ),\n Type.Object(\n { do: Type.Literal('hang'), ms: Type.Union([Type.Number({ minimum: 0 }), Type.Literal('forever')]) },\n strict,\n ),\n Type.Object(\n {\n do: Type.Literal('crash'),\n at: Type.Union([Type.Literal('before-next-step'), Type.Literal('during-tool')]),\n },\n strict,\n ),\n Type.Object({ do: Type.Literal('stop-without-result') }, strict),\n Type.Object(\n {\n do: Type.Literal('model-request'),\n status: Type.Optional(Type.Integer({ minimum: 100, maximum: 599 })),\n quota: Type.Optional(QuotaInfo),\n authSource: Type.Optional(Type.Union([Type.Literal('oauth'), Type.Literal('api-key'), Type.Literal('none')])),\n baseUrl: Type.Optional(Type.String()),\n },\n strict,\n ),\n ]),\n FakeScript: Type.Object(\n {\n version: Type.Literal(1),\n agents: Type.Array(\n Type.Object(\n {\n match: Type.Object(\n {\n role: Type.Optional(Type.String()),\n agentId: Type.Optional(Type.String()),\n incarnation: Type.Optional(Type.Union([Type.Integer({ minimum: 1 }), Type.Literal('any')])),\n attempt: Type.Optional(Type.Integer({ minimum: 1 })),\n },\n strict,\n ),\n steps: Type.Array(Type.Ref('FakeStep')),\n },\n strict,\n ),\n ),\n defaults: Type.Optional(\n Type.Object({ usagePerTurn: Type.Optional(TokenUsage), model: Type.Optional(Type.String()) }, strict),\n ),\n },\n strict,\n ),\n },\n 'FakeScript',\n);\n\n/**\n * Not named `FakeScript` like its type, and explicitly annotated: Biome 2.5.14 overflows its stack when it has to\n * infer a TypeBox const that shares its name with a recursive type (docs/v3/requests/U0.02.md R1); `FakeStep` is one.\n */\nexport const FakeScriptSchema: TUnsafe<FakeScript> = Type.Unsafe<FakeScript>(FakeScriptCyclic);\n\ntype MutuallyAssignable<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;\ntype Assert<T extends true> = T;\ntype _FakeScriptMatchesItsSchema = Assert<MutuallyAssignable<Static<typeof FakeScriptCyclic>, FakeScript>>;\n","import { readFileSync } from 'node:fs';\nimport { extname } from 'node:path';\nimport {\n canonicalJson,\n type ErrorInfo,\n err,\n errorOf,\n type JsonValue,\n ok,\n type Result,\n type Sha256,\n sha256Hex,\n} from '@cohorte/base';\nimport { Compile } from 'typebox/compile';\nimport { parse as parseYaml } from 'yaml';\nimport type { FakeScript } from './index.ts';\nimport { FakeScriptSchema } from './schema.ts';\n\nconst MAX_REPORTED_PROBLEMS = 5;\nconst check = Compile(FakeScriptSchema);\n\nconst invalid = (message: string, problems: string[] = []): { ok: false; error: ErrorInfo } =>\n err(errorOf('configuration/unexpected', message, problems.length > 0 ? { details: { problems } } : {}));\n\n/** A value of unknown origin (a parsed file, a JS caller) is a FakeScript, or the first problems say why not. */\nexport function validateFakeScript(value: unknown): Result<FakeScript, ErrorInfo> {\n if (check.Check(value)) return ok(value);\n const problems: string[] = [];\n for (const problem of check.Errors(value)) {\n problems.push(`${problem.instancePath || '/'} ${problem.message}`);\n if (problems.length === MAX_REPORTED_PROBLEMS) break;\n }\n return invalid(`the fake runtime script is invalid: ${problems[0] ?? 'it does not match the schema'}`, problems);\n}\n\nexport function parseFakeScript(text: string, format: 'yaml' | 'json'): Result<FakeScript, ErrorInfo> {\n let value: unknown;\n try {\n value = format === 'json' ? JSON.parse(text) : parseYaml(text);\n } catch (thrown) {\n const reason = thrown instanceof Error ? thrown.message : String(thrown);\n return invalid(`the fake runtime script is not readable ${format.toUpperCase()}: ${reason}`);\n }\n return validateFakeScript(value);\n}\n\n/** `.json` is JSON, anything else is YAML (of which JSON is a subset). */\nexport function loadFakeScriptFile(path: string): Result<FakeScript, ErrorInfo> {\n let text: string;\n try {\n text = readFileSync(path, 'utf8');\n } catch (thrown) {\n const reason = thrown instanceof Error ? thrown.message : String(thrown);\n return invalid(`the fake runtime script ${path} cannot be read: ${reason}`);\n }\n return parseFakeScript(text, extname(path).toLowerCase() === '.json' ? 'json' : 'yaml');\n}\n\n/** What `pin()` records: two scripts with the same content have the same hash, whatever their key order or format. */\nexport function fakeScriptSha256(script: FakeScript): Sha256 {\n // A validated FakeScript holds JSON values only; the interface just does not say so structurally.\n return sha256Hex(canonicalJson(script as unknown as JsonValue));\n}\n","// One scripted incarnation: a step interpreter. It arms no timer and draws no random number of its own: time is the\n// injected Clock, ids come from the injected IdSource, and every tool step is answered by the real ToolHost (C1).\n//\n// How a flat step list becomes turns: a turn is ONE model request, the assistant message (`say` / `think`), then its\n// tool calls. `model-request` opens a turn explicitly; otherwise one opens before the first content step, and again\n// when text follows a tool call (a model only speaks again after it was given the results).\nimport { appendFileSync } from 'node:fs';\nimport {\n type ErrorInfo,\n errorOf,\n isErrorCode,\n sha256Hex,\n type TokenUsage,\n type ToolCallId,\n toErrorInfo,\n} from '@cohorte/base';\nimport {\n type AgentExit,\n type AgentStopCause,\n type EffectiveModel,\n PREVIEW_MAX_LENGTH,\n RUNTIME_EVENT_TYPES,\n type RuntimeEvent,\n type RuntimeEventOf,\n type RuntimeEventType,\n type RuntimeHostBindings,\n type RuntimeMessage,\n type RuntimeSessionRef,\n type RuntimeSnapshot,\n type RuntimeToolCall,\n type RuntimeToolResult,\n type SpawnRequest,\n type ToolProgress,\n type UsageTotals,\n} from '@cohorte/runtime-contract';\nimport type { FakeAgentRule, FakeScript, FakeStep, FakeStepOf } from '../script/index.ts';\n\nexport interface FakeModelInputMessage {\n role: 'user' | 'assistant' | 'tool-result';\n text: string;\n}\n/** What the scripted model was given for ONE request (the conformance suite's `ModelInput`, structurally). */\nexport interface FakeModelInput {\n systemPrompt: string;\n messages: FakeModelInputMessage[];\n}\n\n/** The tool a `submit` step calls when the request grants no terminal tool (DESIGN 2.7). */\nexport const DEFAULT_RESULT_TOOL = 'submit_result';\nexport const HOST_NOTE_PREFIX = '[cohorte] ';\n\nexport interface FakeAgentInit {\n request: SpawnRequest;\n rule: FakeAgentRule;\n defaults: FakeScript['defaults'];\n texts: { systemPrompt: string; task: string; note: string | null };\n session: RuntimeSessionRef;\n bindings: RuntimeHostBindings;\n publish(event: RuntimeEvent): void;\n /** Where the recorded model inputs of this incarnation go (the provider's probe). */\n inputs: FakeModelInput[];\n}\n\ntype ModelRequestOptions = Omit<FakeStepOf<'model-request'>, 'do'>;\n\nconst ZERO: TokenUsage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };\n\nfunction completeUsage(base: TokenUsage, tokens: Partial<TokenUsage>): TokenUsage {\n const merged = { ...base, ...tokens };\n // Untouched defaults are reported as written; a `usage` step that gives parts and no total means their sum.\n const sum = merged.input + merged.output + merged.cacheRead + merged.cacheWrite;\n const total = tokens.total ?? (Object.keys(tokens).length === 0 ? base.total : sum);\n return { ...merged, total };\n}\n\nfunction scriptedError(scripted: FakeStepOf<'fail'>['error'], message: string): ErrorInfo {\n const extra = scripted.retryAfterMs === undefined ? {} : { retryAfterMs: scripted.retryAfterMs };\n if (isErrorCode(scripted.code)) {\n const info = errorOf(scripted.code, message, extra);\n if (info.class === scripted.class) return { ...info, retryable: scripted.retryable };\n }\n return {\n code: scripted.code,\n class: scripted.class,\n message,\n impact: 'The fake runtime script made this model request fail.',\n retryable: scripted.retryable,\n ...extra,\n remediation: 'Nothing to do in a scripted run; edit the fake runtime script if the failure is not intended.',\n };\n}\n\n/** Awaited as a statement, so it must resolve with nothing: Biome 2.5.14 overflows otherwise (requests/U0.03.md R1). */\nconst settled = (promise: Promise<unknown>): Promise<void> =>\n promise.then(\n () => undefined,\n () => undefined,\n );\n\nconst textOf = (result: RuntimeToolResult): string =>\n result.content.map((part) => (part.type === 'text' ? part.text : '')).join('');\n\nexport class FakeAgent {\n readonly request: SpawnRequest;\n readonly session: RuntimeSessionRef;\n readonly #init: FakeAgentInit;\n readonly #conversation: FakeModelInputMessage[];\n readonly #pending = new Map<ToolCallId, AbortController>();\n readonly #inbox: RuntimeMessage[] = [];\n readonly #cancelled = new AbortController();\n readonly #startedMs: number;\n\n #seq = 0;\n #turns = 0;\n #modelRequests = 0;\n #toolCalls = 0;\n #tokens: TokenUsage = ZERO;\n #exit: AgentExit | null = null;\n #effectiveModel: EffectiveModel | undefined;\n\n #paused: { at: 'tool-boundary' | 'model-boundary'; resumed: Promise<void>; resume: () => void } | null = null;\n #inboxWaiter: (() => void) | null = null;\n\n #turnOpen = false;\n #turnToolCalls = 0;\n #turnStop: 'stop' | 'tool-use' = 'stop';\n #message: { id: string; text: string; parts: number } | null = null;\n #pendingRequest: ModelRequestOptions | null = null;\n #nextUsage: Partial<TokenUsage> | null = null;\n #crashDuringNextTool = false;\n\n constructor(init: FakeAgentInit) {\n this.#init = init;\n this.request = init.request;\n this.session = init.session;\n this.#startedMs = init.bindings.clock.monotonicMs();\n this.#conversation = [{ role: 'user', text: init.texts.task }];\n if (init.texts.note !== null) this.#conversation.push({ role: 'user', text: init.texts.note });\n for (const message of this.#conversation) this.#transcribe(message);\n }\n\n get exited(): boolean {\n return this.#exit !== null;\n }\n\n emitSpawned(): void {\n const { request, session, texts } = this.#init;\n this.#emit('agent.spawned', {\n session,\n requestedModel: request.model,\n tools: request.tools.map((grant) => grant.tool),\n systemPromptSha256: request.systemPrompt.sha256,\n // the fake appends no engine suffix: what the model sees IS the PromptRef\n effectiveSystemPromptSha256: sha256Hex(texts.systemPrompt),\n isolation: { level: 'none', filesystem: 'advisory', network: 'none', backend: 'in-process' },\n });\n }\n\n /** Never rejects: whatever goes wrong inside the interpreter is the exit of this agent. */\n async run(): Promise<AgentExit> {\n try {\n this.#emit('agent.started', { taskSha256: this.request.task.sha256 });\n // Every awaited AgentExit is bound to a name: Biome 2.5.14 overflows its stack otherwise (requests/U0.03.md R1).\n const stopped = await this.#runSteps(this.#init.rule.steps);\n if (stopped) return stopped;\n const ended = await this.#endOfScript();\n return ended;\n } catch (thrown) {\n if (this.#exit) return this.#exit;\n const error = toErrorInfo(thrown, { code: 'configuration/unexpected', class: 'configuration' });\n return this.#finish('failed', 'engine-error', error);\n }\n }\n\n cancel(): void {\n if (this.exited || this.#cancelled.signal.aborted) return;\n this.#cancelled.abort();\n for (const controller of this.#pending.values()) controller.abort();\n this.#paused?.resume();\n this.#inboxWaiter?.();\n }\n\n pause(): void {\n if (this.exited || this.#paused) return;\n let resume: () => void = () => {};\n const resumed = new Promise<void>((resolve) => {\n resume = resolve;\n });\n const at = this.#pending.size > 0 ? 'tool-boundary' : 'model-boundary';\n this.#paused = { at, resumed, resume };\n this.#emit('agent.paused', { at });\n }\n\n resume(): void {\n if (this.exited || !this.#paused) return;\n const { resume } = this.#paused;\n this.#paused = null;\n this.#emit('agent.resumed', {});\n resume();\n }\n\n accept(message: RuntimeMessage): void {\n this.#inbox.push(message);\n this.#emit('agent.message.accepted', { messageId: message.messageId, delivery: message.delivery });\n this.#inboxWaiter?.();\n }\n\n snapshot(): RuntimeSnapshot {\n const { runId, agentId, incarnation, model, auth } = this.request;\n const state = this.exited\n ? 'exited'\n : this.#paused\n ? 'paused'\n : this.#pending.size > 0\n ? 'awaiting-tool'\n : 'running';\n return {\n runId,\n agentId,\n incarnation,\n state,\n ...(this.#paused && !this.exited ? { pausedAt: this.#paused.at } : {}),\n turn: this.#turns,\n pendingToolCalls: [...this.#pending.keys()],\n requestedModel: model,\n ...(this.#effectiveModel ? { effectiveModel: this.#effectiveModel } : {}),\n authMode: auth.mode,\n usage: this.#usage(),\n session: this.session,\n lastSeq: this.#seq,\n diagnostics: { inProcess: true, queuedMessages: this.#inbox.length },\n };\n }\n\n // ── interpreter ─────────────────────────────────────────────────────────────────────\n\n /**\n * The exit when a step ended the agent, `null` when the list ran to its end. `tail` is what the parent list runs\n * after a nested `onDenied` list: the look-ahead of a turn opened in the nested list must see it.\n */\n async #runSteps(steps: readonly FakeStep[], tail: readonly FakeStep[] = []): Promise<AgentExit | null> {\n const ahead = tail.length === 0 ? steps : [...steps, ...tail];\n for (const [index, current] of steps.entries()) {\n if (this.#isCancelled) return this.#finishCancelled();\n const over = this.#wallClockExceeded();\n if (over) return over;\n const exit = await this.#runStep(current, ahead, index);\n if (exit) return exit;\n }\n return null;\n }\n\n async #runStep(current: FakeStep, steps: readonly FakeStep[], index: number): Promise<AgentExit | null> {\n switch (current.do) {\n case 'model-request': {\n const exit = await this.#flushPendingRequest();\n if (exit) return exit;\n this.#closeTurn();\n const { do: _do, ...options } = current;\n this.#pendingRequest = options;\n return null;\n }\n case 'say':\n case 'think': {\n const exit = await this.#ensureTurn(steps, index, this.#turnToolCalls > 0);\n if (exit) return exit;\n this.#speak(current);\n return null;\n }\n case 'tool':\n return this.#callTool(current.tool, current.input, current, steps, index);\n case 'submit': {\n const terminal = this.request.tools.find((grant) => grant.terminal)?.tool ?? DEFAULT_RESULT_TOOL;\n return this.#callTool(terminal, current.output, null, steps, index);\n }\n case 'usage':\n this.#nextUsage = { ...this.#nextUsage, ...current.tokens };\n return null;\n case 'await-message':\n return this.#awaitMessage(current.timeoutMs);\n case 'fail': {\n const options = this.#pendingRequest ?? {};\n this.#pendingRequest = null;\n this.#closeTurn();\n const error = scriptedError(current.error, `scripted failure of model request ${this.#modelRequests + 1}`);\n const refused = await this.#modelRequest(options, 'stop', error);\n return refused ?? this.#finish('failed', 'engine-error', error);\n }\n case 'hang':\n if (current.ms === 'forever') await this.#untilCancelled();\n else await this.#sleep(current.ms);\n return this.#isCancelled ? this.#finishCancelled() : null;\n case 'crash':\n if (current.at === 'during-tool') {\n this.#crashDuringNextTool = true;\n return null;\n }\n return this.#crash('the scripted agent crashed between two steps');\n case 'stop-without-result':\n return this.#endOfScript();\n }\n }\n\n async #endOfScript(): Promise<AgentExit> {\n if (this.#crashDuringNextTool) return this.#crash('the scripted agent crashed before any further tool call');\n const exit = await this.#flushPendingRequest();\n if (exit) return exit;\n this.#closeTurn();\n if (this.#isCancelled) return this.#finishCancelled();\n return this.#finish('completed', 'model-stop');\n }\n\n // ── turns and model requests ────────────────────────────────────────────────────────\n\n /** Does the turn that starts at `steps[from]` call a tool? That is the `stop` of its model response. */\n #stopOfTurn(steps: readonly FakeStep[], from: number): 'stop' | 'tool-use' {\n for (const next of steps.slice(from)) {\n if (next.do === 'tool' || next.do === 'submit') return 'tool-use';\n if (next.do === 'model-request' || next.do === 'await-message' || next.do === 'fail') return 'stop';\n if (next.do === 'stop-without-result' || (next.do === 'crash' && next.at === 'before-next-step')) return 'stop';\n }\n return 'stop';\n }\n\n /**\n * A scripted `model-request` is only sent when the next step needs it, so that a `fail` right after it IS it.\n * Flushed by a step that closes the turn, the request had no content: its response is an empty final message.\n */\n async #flushPendingRequest(): Promise<AgentExit | null> {\n if (!this.#pendingRequest) return null;\n const options = this.#pendingRequest;\n this.#pendingRequest = null;\n return this.#modelRequest(options, 'stop');\n }\n\n async #ensureTurn(steps: readonly FakeStep[], index: number, startNew: boolean): Promise<AgentExit | null> {\n if (this.#pendingRequest) {\n const options = this.#pendingRequest;\n this.#pendingRequest = null;\n return this.#modelRequest(options, this.#stopOfTurn(steps, index));\n }\n if (this.#turnOpen && !startNew) return null;\n this.#closeTurn();\n return this.#modelRequest({}, this.#stopOfTurn(steps, index));\n }\n\n async #modelRequest(\n options: ModelRequestOptions,\n stop: 'stop' | 'tool-use',\n failure?: ErrorInfo,\n ): Promise<AgentExit | null> {\n const { request } = this;\n const { budget } = request;\n if (budget.maxTurns !== undefined && this.#turns >= budget.maxTurns) return this.#finish('completed', 'budget');\n if (budget.maxModelRequests !== undefined && this.#modelRequests >= budget.maxModelRequests)\n return this.#finish('completed', 'budget');\n if (await this.#gate()) return this.#finishCancelled();\n\n this.#modelRequests += 1;\n const requestId = `req_${request.incarnation}_${this.#modelRequests}`;\n if (!failure) this.#emit('agent.turn.started', { turn: this.#turns + 1 });\n for (const message of this.#inbox.splice(0)) {\n const text = message.kind === 'host-note' ? `${HOST_NOTE_PREFIX}${message.text}` : message.text;\n this.#remember({ role: 'user', text });\n }\n this.#init.inputs.push({\n systemPrompt: this.#init.texts.systemPrompt,\n messages: this.#conversation.map((message) => ({ ...message })),\n });\n this.#emit('model.requested', {\n requestId,\n model: request.model,\n contextSha256: request.context.manifestSha256,\n attempt: 1,\n });\n\n const usage = completeUsage(this.#init.defaults?.usagePerTurn ?? ZERO, this.#nextUsage ?? {});\n this.#nextUsage = null;\n this.#tokens = {\n input: this.#tokens.input + usage.input,\n output: this.#tokens.output + usage.output,\n cacheRead: this.#tokens.cacheRead + usage.cacheRead,\n cacheWrite: this.#tokens.cacheWrite + usage.cacheWrite,\n total: this.#tokens.total + usage.total,\n };\n this.#effectiveModel = {\n provider: request.model.provider,\n model: this.#init.defaults?.model ?? request.model.model,\n baseUrl: options.baseUrl ?? request.auth.baseUrl,\n };\n this.#emit('model.responded', {\n requestId,\n requestedModel: request.model,\n effectiveModel: this.#effectiveModel,\n // DESIGN 2.2.5: a fake run reports the authMode its plan requested\n authMode: request.auth.mode,\n authSource: options.authSource ?? 'none',\n durationMs: 0,\n usage,\n ...(options.status === undefined ? {} : { httpStatus: options.status }),\n attempt: 1,\n stop: failure ? 'error' : stop,\n quota: options.quota ?? { known: false },\n ...(failure ? { error: failure } : {}),\n });\n if (failure) return null;\n\n this.#turnOpen = true;\n this.#turnToolCalls = 0;\n this.#turnStop = stop;\n const { maxInputTokens, maxOutputTokens, maxTotalTokens } = budget;\n const spent =\n (maxInputTokens !== undefined && this.#tokens.input > maxInputTokens) ||\n (maxOutputTokens !== undefined && this.#tokens.output > maxOutputTokens) ||\n (maxTotalTokens !== undefined && this.#tokens.total > maxTotalTokens);\n if (!spent) return null;\n this.#closeTurn();\n return this.#finish('completed', 'budget');\n }\n\n #closeTurn(): void {\n if (!this.#turnOpen) return;\n this.#completeMessage();\n this.#turnOpen = false;\n this.#turns += 1;\n this.#emit('agent.turn.completed', { turn: this.#turns, toolCalls: this.#turnToolCalls });\n this.#turnToolCalls = 0;\n }\n\n // ── the assistant message of a turn ─────────────────────────────────────────────────\n\n #openMessage(): { id: string; text: string; parts: number } {\n if (!this.#message) {\n this.#message = { id: `msg_${this.request.incarnation}_${this.#modelRequests}`, text: '', parts: 0 };\n this.#emit('agent.message.started', { messageId: this.#message.id, role: 'assistant' });\n }\n return this.#message;\n }\n\n #speak(current: FakeStepOf<'say'> | FakeStepOf<'think'>): void {\n const message = this.#openMessage();\n const contentIndex = message.parts;\n message.parts += 1;\n if (current.do === 'think') {\n this.#emit('agent.message.delta', {\n messageId: message.id,\n channel: 'thinking',\n contentIndex,\n delta: current.text,\n });\n return;\n }\n const characters = [...current.text];\n const chunks = Math.min(current.chunks ?? 1, Math.max(characters.length, 1));\n const size = Math.ceil(characters.length / chunks);\n for (let at = 0; at < chunks; at += 1) {\n const delta = characters.slice(at * size, (at + 1) * size).join('');\n if (delta === '' && at > 0) break;\n this.#emit('agent.message.delta', { messageId: message.id, channel: 'text', contentIndex, delta });\n }\n message.text += current.text;\n }\n\n /** Every model response is exactly one assistant message, empty when the script said nothing. */\n #completeMessage(): void {\n if (!this.#turnOpen) return;\n if (this.#message === null && this.#turnToolCalls > 0) return;\n const { id, text } = this.#openMessage();\n this.#message = null;\n this.#remember({ role: 'assistant', text });\n this.#emit('agent.message.completed', {\n messageId: id,\n role: 'assistant',\n textSha256: sha256Hex(text),\n textBytes: Buffer.byteLength(text, 'utf8'),\n preview: [...text].slice(0, PREVIEW_MAX_LENGTH).join(''),\n stop: this.#turnStop,\n });\n }\n\n // ── tool calls: ALWAYS through the ToolHost ─────────────────────────────────────────\n\n async #callTool(\n tool: string,\n input: RuntimeToolCall['input'],\n scripted: FakeStepOf<'tool'> | null,\n steps: readonly FakeStep[],\n index: number,\n ): Promise<AgentExit | null> {\n const opened = await this.#ensureTurn(steps, index, false);\n if (opened) return opened;\n const { maxToolCalls } = this.request.budget;\n if (maxToolCalls !== undefined && this.#toolCalls >= maxToolCalls) {\n this.#closeTurn();\n return this.#finish('completed', 'budget');\n }\n // Before anything is counted or emitted: `tool.call.requested` promises that the ToolHost WILL be called.\n if (await this.#gate()) return this.#finishCancelled();\n if (this.#turnToolCalls === 0) this.#completeMessage();\n\n this.#toolCalls += 1;\n this.#turnToolCalls += 1;\n const { runId, agentId, incarnation } = this.request;\n const ordinal = this.#toolCalls;\n const toolCallId = `tc_${incarnation}_${ordinal}` as ToolCallId;\n const call: RuntimeToolCall = { runId, agentId, incarnation, toolCallId, ordinal, tool, input };\n this.#emit('tool.call.requested', { call });\n\n const controller = new AbortController();\n this.#pending.set(toolCallId, controller);\n const askedAt = this.#init.bindings.clock.monotonicMs();\n const progress = (update: ToolProgress): void => {\n if (this.#pending.has(toolCallId)) this.#emit('tool.call.progress', { toolCallId, update });\n };\n let result: RuntimeToolResult;\n let hostBug: unknown;\n try {\n const answer = this.#init.bindings.toolHost.handleToolCall(call, { signal: controller.signal, progress });\n if (this.#crashDuringNextTool) {\n // The brain dies while the host works: the call is abandoned, its result is never delivered.\n controller.abort();\n await settled(answer);\n this.#pending.delete(toolCallId);\n return this.#crash(`the scripted agent crashed during ${toolCallId}`);\n }\n result = await answer;\n } catch (thrown) {\n // DESIGN 2.2.2: a rejection is a host bug; the runtime treats it as isError + agent failure.\n hostBug = thrown;\n result = { isError: true, content: [] };\n }\n this.#pending.delete(toolCallId);\n const waitedMs = Math.max(0, Math.round(this.#init.bindings.clock.monotonicMs() - askedAt));\n this.#emit('tool.call.delivered', {\n toolCallId,\n isError: result.isError,\n terminate: result.terminate === true,\n waitedMs,\n });\n // Byte-identical (conformance rule 10): the sealed text is what the model is given.\n this.#remember({ role: 'tool-result', text: textOf(result) });\n\n if (hostBug !== undefined) {\n const error = toErrorInfo(hostBug, { code: 'tool-terminal/unexpected', class: 'tool-terminal' });\n return this.#finish('failed', 'engine-error', error);\n }\n if (this.#isCancelled) return this.#finishCancelled();\n if (result.terminate === true) {\n this.#closeTurn();\n return this.#finish('completed', 'host-terminated');\n }\n const unexpected = scripted?.expect ? this.#unexpected(scripted.expect, result, toolCallId) : null;\n if (unexpected) return this.#finish('failed', 'engine-error', unexpected);\n if (result.isError && scripted?.onDenied) return this.#runSteps(scripted.onDenied, steps.slice(index + 1));\n return null;\n }\n\n #unexpected(\n expected: NonNullable<FakeStepOf<'tool'>['expect']>,\n result: RuntimeToolResult,\n toolCallId: ToolCallId,\n ): ErrorInfo | null {\n const problems: string[] = [];\n if (expected.isError !== undefined && expected.isError !== result.isError)\n problems.push(`isError is ${result.isError}, the script expects ${expected.isError}`);\n if (expected.textIncludes !== undefined && !textOf(result).includes(expected.textIncludes))\n problems.push(`the result text does not include ${JSON.stringify(expected.textIncludes)}`);\n if (problems.length === 0) return null;\n return errorOf(\n 'configuration/unexpected',\n `fake script expectation failed for ${toolCallId}: ${problems.join('; ')}`,\n );\n }\n\n // ── waiting: only on the injected clock, on the host, or on cancel ──────────────────\n\n get #isCancelled(): boolean {\n return this.#cancelled.signal.aborted;\n }\n\n #untilCancelled(): Promise<void> {\n return new Promise((resolve) => {\n if (this.#isCancelled) resolve();\n else this.#cancelled.signal.addEventListener('abort', () => resolve(), { once: true });\n });\n }\n\n /** `clock.sleep` rejects when its signal aborts; both ways out are fine here. */\n async #sleep(ms: number, signal: AbortSignal = this.#cancelled.signal): Promise<void> {\n try {\n await this.#init.bindings.clock.sleep(ms, signal);\n } catch {\n // aborted: the caller looks at what woke it\n }\n }\n\n /** Holds the agent while it is paused. True when it was cancelled meanwhile. */\n async #gate(): Promise<boolean> {\n while (this.#paused && !this.#isCancelled) await this.#paused.resumed;\n return this.#isCancelled;\n }\n\n async #awaitMessage(timeoutMs: number | undefined): Promise<AgentExit | null> {\n const exit = await this.#flushPendingRequest();\n if (exit) return exit;\n this.#closeTurn();\n if (this.#inbox.length === 0 && !this.#isCancelled) {\n const woken = new AbortController();\n const onCancel = (): void => woken.abort();\n this.#cancelled.signal.addEventListener('abort', onCancel, { once: true });\n const arrived = new Promise<void>((resolve) => {\n this.#inboxWaiter = resolve;\n });\n const waits = [arrived];\n if (timeoutMs !== undefined) waits.push(this.#sleep(timeoutMs, woken.signal));\n await Promise.race(waits);\n this.#inboxWaiter = null;\n this.#cancelled.signal.removeEventListener('abort', onCancel);\n // takes the sleeper off the clock when the message (or the cancel) came first\n woken.abort();\n }\n return this.#isCancelled ? this.#finishCancelled() : null;\n }\n\n #wallClockExceeded(): AgentExit | null {\n const { maxWallClockMs } = this.request.budget;\n if (maxWallClockMs === undefined || this.#usage().wallClockMs <= maxWallClockMs) return null;\n this.#closeTurn();\n return this.#finish('completed', 'budget');\n }\n\n // ── exits and events ────────────────────────────────────────────────────────────────\n\n #crash(message: string): AgentExit {\n if (this.#isCancelled) return this.#finishCancelled();\n this.#pendingRequest = null;\n return this.#finish('crashed', 'process-exit', errorOf('tool-transient/agent-process-exit', message));\n }\n\n #finishCancelled(): AgentExit {\n return this.#finish('cancelled', 'cancelled');\n }\n\n #finish(outcome: AgentExit['outcome'], stop: AgentStopCause, error?: ErrorInfo): AgentExit {\n const exit: AgentExit = {\n outcome,\n stop,\n ...(error ? { error } : {}),\n usage: this.#usage(),\n lastSeq: this.#seq + 1,\n };\n this.#emit('agent.exited', exit);\n this.#exit = exit;\n return exit;\n }\n\n #usage(): UsageTotals {\n return {\n tokens: this.#tokens,\n modelRequests: this.#modelRequests,\n toolCalls: this.#toolCalls,\n turns: this.#turns,\n wallClockMs: Math.max(0, Math.round(this.#init.bindings.clock.monotonicMs() - this.#startedMs)),\n };\n }\n\n #remember(message: FakeModelInputMessage): void {\n this.#conversation.push(message);\n this.#transcribe(message);\n }\n\n #transcribe(message: FakeModelInputMessage): void {\n appendFileSync(this.session.transcript.path, `${JSON.stringify(message)}\\n`, 'utf8');\n }\n\n #emit<T extends RuntimeEventType>(type: T, data: RuntimeEventOf<T>['data']): void {\n if (this.exited) return;\n this.#seq += 1;\n const { runId, agentId, incarnation } = this.request;\n const event = {\n type,\n durability: RUNTIME_EVENT_TYPES[type].durability,\n runId,\n agentId,\n incarnation,\n seq: this.#seq,\n at: this.#init.bindings.clock.now(),\n data,\n } as RuntimeEvent;\n this.#init.publish(event);\n }\n}\n","import type { Cap, RuntimeCapabilities } from '@cohorte/runtime-contract';\n\nconst yes: Cap = { value: 'yes' };\nconst no = (why: string): Cap => ({ value: 'no', why });\nconst partial = (why: string): Cap => ({ value: 'partial', why });\nconst IN_PROCESS = 'the fake brain runs inside the host process: there is no agent process';\n\n/** What an in-process, scripted brain can honestly promise. Frozen data; `capabilities()` hands out copies. */\nexport const FAKE_CAPABILITIES: RuntimeCapabilities = {\n contractVersion: '1',\n toolExecution: 'host-delegated',\n streaming: yes,\n thinkingStream: yes,\n send: {\n steer: partial('a message joins the conversation at the next scripted model request, never inside one'),\n followUp: yes,\n },\n cancelCooperative: yes,\n cancelHard: no(IN_PROCESS),\n pause: { toolBoundary: yes, modelBoundary: yes },\n continuationFromTranscript: no('the script decides what a later incarnation does; the transcript is never read back'),\n processIsolation: no(IN_PROCESS),\n envFiltering: no(IN_PROCESS),\n brainSandbox: no(IN_PROCESS),\n resourceLimits: no(IN_PROCESS),\n budgetEnforcement: {\n turns: yes,\n modelRequests: yes,\n tokens: partial('token counts are scripted; the ceilings are checked after each model response'),\n context: no('a script has no context window'),\n wallClock: partial('checked between steps on the injected clock; the fake arms no timer'),\n outputTokensPerRequest: no('a scripted response is never truncated'),\n },\n hiddenModelCalls: no('every model request is a scripted step'),\n usageReporting: yes,\n effectiveModelReporting: yes,\n quotaReporting: partial('only what a model-request step scripts'),\n authStatusWithoutSecret: yes,\n subscriptionModeAssertion: no(\n 'the fake holds no credential: it reports the requested auth mode with authSource none',\n ),\n systemPromptExact: yes,\n runtimePinning: partial('the pin covers the script, not the installed code'),\n platforms: { darwin: yes, linux: yes, win32: yes },\n hints: { memoryPerAgentMb: 1, coldStartMs: 0, maxConcurrentAgents: 256 },\n};\n","import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { CohorteError, errorOf, sha256Hex } from '@cohorte/base';\nimport type {\n AgentRuntime,\n RuntimeEvent,\n RuntimeHostBindings,\n RuntimeSessionRef,\n SpawnRequest,\n TaskInput,\n} from '@cohorte/runtime-contract';\nimport { type FakeScript, matchFakeRule } from '../script/index.ts';\nimport { FakeAgent, type FakeModelInput } from './agent.ts';\nimport { FAKE_CAPABILITIES } from './capabilities.ts';\n\nexport const FAKE_RUNTIME_ID = 'fake';\nexport const FAKE_ADAPTER_VERSION = '3.0.0';\n/** \"<adapter semver>+<engine>.<engine version>\" (DESIGN 2.2.1); the engine is the step interpreter, version 1. */\nexport const FAKE_RUNTIME_VERSION = `${FAKE_ADAPTER_VERSION}+fake.1`;\nexport const FAKE_TRANSCRIPT_FORMAT = 'fake-ndjson-v1';\n\n/** What outlives one runtime: the provider's ledger, its model probe and the attempts it has seen. */\nexport interface FakeRuntimeShared {\n script: FakeScript;\n baseUrl: string | undefined;\n inputs: Map<string, FakeModelInput[]>;\n /** `<runId>/<agentId>` -> attempts opened so far (a spawn without `continuation` opens one). */\n attempts: Map<string, number>;\n record(request: SpawnRequest): void;\n}\n\nconst keyOf = (request: Pick<SpawnRequest, 'runId' | 'agentId' | 'incarnation'>): string =>\n `${request.runId}/${request.agentId}/${request.incarnation}`;\n\nfunction readVerified(ref: TaskInput, what: string): string {\n let text: string;\n try {\n text = readFileSync(ref.path, 'utf8');\n } catch (thrown) {\n const reason = thrown instanceof Error ? thrown.message : String(thrown);\n throw new CohorteError(errorOf('security/asset-hash-mismatch', `${what} ${ref.path} cannot be read: ${reason}`));\n }\n if (sha256Hex(text) !== ref.sha256)\n throw new CohorteError(\n errorOf('security/asset-hash-mismatch', `the content of ${what} ${ref.path} does not match its reference`),\n );\n return text;\n}\n\nexport function createFakeRuntime(bindings: RuntimeHostBindings, shared: FakeRuntimeShared): AgentRuntime {\n const listeners = new Set<(event: RuntimeEvent) => void>();\n const agents = new Map<string, FakeAgent>();\n const exits: Promise<unknown>[] = [];\n let closed = false;\n\n const publish = (event: RuntimeEvent): void => {\n for (const listener of [...listeners]) {\n try {\n listener(event);\n } catch {\n // A subscriber's bug is not the agent's: the event was emitted, the others still get it.\n }\n }\n };\n\n const latest = (agentId: string): FakeAgent => {\n const found = [...agents.values()].findLast((agent) => agent.request.agentId === agentId);\n if (!found) throw new CohorteError(errorOf('validation/unexpected', `the fake runtime has no agent ${agentId}`));\n return found;\n };\n\n return {\n id: FAKE_RUNTIME_ID,\n version: FAKE_RUNTIME_VERSION,\n capabilities: () => structuredClone(FAKE_CAPABILITIES),\n\n async spawn(request) {\n shared.record(request);\n if (closed) throw new CohorteError(errorOf('conflict/unexpected', 'the fake runtime is closed'));\n const key = keyOf(request);\n if (agents.has(key)) throw new CohorteError(errorOf('conflict/incarnation-exists', `${key} was already spawned`));\n\n const attemptKey = `${request.runId}/${request.agentId}`;\n const opened = shared.attempts.get(attemptKey) ?? 0;\n const attempt = Math.max(1, request.continuation === null ? opened + 1 : opened);\n const { role, agentId, incarnation } = request;\n const rule = matchFakeRule(shared.script, { role, agentId, incarnation, attempt });\n if (!rule)\n throw new CohorteError(\n errorOf('configuration/fake-script-unmatched', `no script rule matches the spawn of ${agentId}`, {\n details: { role, agentId, incarnation, attempt },\n }),\n );\n if (shared.baseUrl !== undefined && request.auth.baseUrl !== shared.baseUrl)\n throw new CohorteError(\n errorOf(\n 'security/auth-endpoint-mismatch',\n `the request is pinned to ${request.auth.baseUrl}, this fake runtime answers for ${shared.baseUrl}`,\n ),\n );\n const texts = {\n systemPrompt: readVerified(request.systemPrompt, 'system prompt'),\n task: readVerified(request.task, 'task'),\n note: request.continuation ? readVerified(request.continuation.note, 'continuation note') : null,\n };\n\n const stateDir = bindings.stateDir(request.runId, agentId, incarnation);\n const session: RuntimeSessionRef = {\n runtime: FAKE_RUNTIME_ID,\n engineVersion: FAKE_RUNTIME_VERSION,\n sessionId: bindings.ids.next<'SessionId'>('ses'),\n transcript: { path: join(stateDir, 'transcript.ndjson'), format: FAKE_TRANSCRIPT_FORMAT },\n };\n try {\n mkdirSync(stateDir, { recursive: true });\n writeFileSync(session.transcript.path, '', 'utf8');\n } catch (thrown) {\n const reason = thrown instanceof Error ? thrown.message : String(thrown);\n throw new CohorteError(errorOf('configuration/engine-init', `the transcript cannot be created: ${reason}`));\n }\n\n const inputs: FakeModelInput[] = [];\n shared.inputs.set(key, inputs);\n shared.attempts.set(attemptKey, attempt);\n // A private copy: the agent keeps reading its request long after the caller got its handle back.\n const owned = structuredClone(request);\n const agent = new FakeAgent({\n request: owned,\n rule,\n defaults: shared.script.defaults,\n texts,\n session,\n bindings,\n publish,\n inputs,\n });\n agents.set(key, agent);\n agent.emitSpawned();\n // A microtask hop, not a timer: the caller holds its handle before the first model request.\n const exit = Promise.resolve().then(() => agent.run());\n exits.push(exit);\n return {\n runId: owned.runId,\n agentId: owned.agentId,\n incarnation,\n session,\n startedAt: bindings.clock.now(),\n process: null,\n exit,\n };\n },\n\n async send(agentId, message) {\n const agent = latest(agentId);\n if (agent.exited)\n throw new CohorteError(errorOf('conflict/unexpected', `agent ${agentId} has exited: nobody reads a message`));\n agent.accept(message);\n },\n\n // cancel, pause and resume race with the exit by nature: on an agent that is gone they do nothing.\n async cancel(agentId) {\n latest(agentId).cancel();\n },\n async pause(agentId) {\n latest(agentId).pause();\n },\n async resume(agentId) {\n latest(agentId).resume();\n },\n\n subscribe(listener) {\n listeners.add(listener);\n return () => void listeners.delete(listener);\n },\n\n inspect: async (agentId) => latest(agentId).snapshot(),\n\n async close() {\n closed = true;\n for (const agent of agents.values()) agent.cancel();\n await Promise.all(exits);\n },\n };\n}\n","// The scriptable, deterministic AgentRuntime of DESIGN 3.10: same contract as PiRuntime, in-process, and — because\n// of rule C1 — every scripted tool call is answered by the host's REAL ToolHost.\nimport {\n type AgentId,\n type Clock,\n CohorteError,\n canonicalJson,\n errorOf,\n type JsonValue,\n type RunId,\n sha256Hex,\n systemClock,\n} from '@cohorte/base';\nimport type { AgentRuntimeProvider, ProviderAuthStatus, RuntimePin, SpawnRequest } from '@cohorte/runtime-contract';\nimport { type FakeScript, fakeScriptSha256, validateFakeScript } from '../script/index.ts';\nimport type { FakeModelInput } from './agent.ts';\nimport { createFakeRuntime, FAKE_ADAPTER_VERSION, FAKE_RUNTIME_ID, type FakeRuntimeShared } from './runtime.ts';\n\nexport type { FakeModelInput, FakeModelInputMessage } from './agent.ts';\nexport { DEFAULT_RESULT_TOOL, HOST_NOTE_PREFIX } from './agent.ts';\nexport { FAKE_CAPABILITIES } from './capabilities.ts';\nexport { FAKE_ADAPTER_VERSION, FAKE_RUNTIME_ID, FAKE_RUNTIME_VERSION, FAKE_TRANSCRIPT_FORMAT } from './runtime.ts';\n\n/** Every SpawnRequest the fake received, in order: a retry's request is byte-identical apart from `incarnation`. */\nexport interface FakeLedger {\n requests(): readonly SpawnRequest[];\n requestsOf(agentId: string): readonly SpawnRequest[];\n}\n\n/** The canonical JSON of a request WITHOUT `incarnation`: equal strings = the byte-identical retry of DESIGN 2.5. */\nexport function spawnRequestIdentity(request: SpawnRequest): string {\n const { incarnation: _incarnation, ...rest } = request;\n return canonicalJson(rest as unknown as JsonValue);\n}\n\nexport interface FakeRuntimeProviderOptions {\n script: FakeScript;\n /**\n * The endpoint this fake \"talks to\". When set, a spawn pinned to any other `auth.baseUrl` is refused with\n * security/auth-endpoint-mismatch (conformance rule 11). When absent the fake has no endpoint of its own and\n * accepts the one its plan pinned; a `model-request` step can still REPORT another one.\n */\n baseUrl?: string;\n /** Only for `authStatus().checkedAt`, which is asked before any host bindings exist. Default: the system clock. */\n clock?: Clock;\n}\n\nexport interface FakeRuntimeProvider extends AgentRuntimeProvider {\n readonly ledger: FakeLedger;\n /** Every model input recorded for that incarnation, oldest first: what the conformance `modelProbe` reads. */\n modelInputs(agent: { runId: RunId; agentId: AgentId; incarnation: number }): FakeModelInput[];\n}\n\nconst SCRIPT_ENGINE = 'fake-script';\n\nexport function createFakeRuntimeProvider(options: FakeRuntimeProviderOptions): FakeRuntimeProvider {\n const validated = validateFakeScript(options.script);\n if (!validated.ok) throw new CohorteError(validated.error);\n // A private copy: the pin hashes it once, and no caller can change it under a running agent.\n const script = structuredClone(validated.value);\n const clock = options.clock ?? systemClock;\n const requests: SpawnRequest[] = [];\n const shared: FakeRuntimeShared = {\n script,\n baseUrl: options.baseUrl,\n inputs: new Map(),\n attempts: new Map(),\n record: (request) => void requests.push(structuredClone(request)),\n };\n\n const computePin = (): RuntimePin => {\n const body = {\n runtimeId: FAKE_RUNTIME_ID,\n adapterVersion: FAKE_ADAPTER_VERSION,\n // The fake has no engine package and no bundle: what decides its behaviour is the script, so that is what\n // the pin names. No artifact has a path to re-hash.\n engine: { name: SCRIPT_ENGINE, version: `sha256:${fakeScriptSha256(script)}` },\n node: { version: process.version, execPath: process.execPath },\n artifacts: [],\n };\n return { ...body, digest: sha256Hex(canonicalJson(body)) };\n };\n\n const status = (provider: string): ProviderAuthStatus => ({\n provider,\n state: 'absent',\n subscription: false,\n source: 'none',\n checkedAt: clock.now(),\n billing: 'unknown',\n caveat: 'The fake runtime holds no credential and calls no provider.',\n });\n\n return {\n id: FAKE_RUNTIME_ID,\n ledger: {\n requests: () => requests.map((request) => structuredClone(request)),\n requestsOf: (agentId) =>\n requests.filter((request) => request.agentId === agentId).map((request) => structuredClone(request)),\n },\n modelInputs: ({ runId, agentId, incarnation }) =>\n structuredClone(shared.inputs.get(`${runId}/${agentId}/${incarnation}`) ?? []),\n pin: async () => computePin(),\n async create(bindings, pin) {\n const now = computePin();\n if (pin.digest !== now.digest)\n throw new CohorteError(\n errorOf('security/runtime-pin-mismatch', 'the fake runtime script is not the one that was pinned', {\n details: { pinned: pin.digest, installed: now.digest },\n }),\n );\n return createFakeRuntime(bindings, shared);\n },\n authStatus: async (providers) => providers.map(status),\n async login(provider, ui) {\n ui.show({ kind: 'info', message: 'The fake runtime needs no login: it holds no credential.' });\n return status(provider);\n },\n async logout() {},\n };\n}\n","// DESIGN 3.8 — the error table of the runtime, as a PURE function over the WIRE shape of an engine error. This area is\n// engine-free (check-layers rule b), so it cannot ask `instanceof`: only child code looks at engine classes, and it\n// sends an `ErrorSignal`. The engine's stop reason is never an input.\nimport { type ErrorCode, type ErrorInfo, errorOf, type JsonValue } from '@cohorte/base';\nimport type { ErrorSignal } from '../protocol.ts';\n\n/** What the parent observed next to the signal: the allowlisted headers of the last `provider.response` of that request. */\nexport interface ClassifyEvidence {\n headers?: Readonly<Record<string, string>>;\n}\n\nconst STORE_FAILED = /^Credential store (read|modify|delete) failed/;\nconst STORE_LOCK_CODES = new Set(['ELOCKED', 'EPERM', 'EACCES', 'EBUSY']);\nconst NOT_CONFIGURED = /Provider is not configured|No API key|does not support .{0,80}login/i;\nconst NETWORK_CODES = new Set([\n 'ABORT_ERR',\n 'ECONNRESET',\n 'ECONNREFUSED',\n 'ETIMEDOUT',\n 'ENOTFOUND',\n 'EAI_AGAIN',\n 'EPIPE',\n 'UND_ERR_SOCKET',\n 'UND_ERR_CONNECT_TIMEOUT',\n]);\nconst NETWORK_TEXT =\n /fetch failed|AbortError|ABORT_ERR|ECONNRESET|ETIMEDOUT|ENOTFOUND|socket hang up|socket (was )?destroyed|other side closed|terminated|network error/i;\nconst EMBEDDED_5XX = /\\b5\\d\\d\\b/;\nconst USAGE_LIMIT = /usage[ _]limit|usage_not_included|usage_limit_reached|plan limit/i;\nconst TRY_AGAIN = /try again in ~?\\s*(\\d+)\\s*(s|sec|second|min|minute|h|hour|day)/i;\nconst CONTEXT_OVERFLOW =\n /context (window|length)|maximum context|context_length_exceeded|maxContextTokens|too many tokens/i;\nconst MODEL_ENTITLEMENT = /\\bmodel\\b|entitle|not supported|not included/i;\nconst MODEL_NOT_FOUND = /model .{0,80}(not found|does not exist)|model_not_found/i;\nconst OVERLOADED = /overloaded|over capacity/i;\nconst BROKEN_STREAM = /<!DOCTYPE|<html|Unexpected token|not valid JSON|stream (ended|closed)|premature close|SSE/i;\nconst STATUS_PREFIX = /^(\\d{3}): /;\nconst RESET_HEADER = /^(retry-after|x-ratelimit-reset.*|x-codex-.*reset.*)$/i;\n\nconst UNIT_MS: Record<string, number> = { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 };\n\nfunction delayOfText(text: string): number | undefined {\n const match = TRY_AGAIN.exec(text);\n if (!match?.[1] || !match[2]) return undefined;\n const unit = UNIT_MS[match[2].charAt(0).toLowerCase()];\n return unit === undefined ? undefined : Number(match[1]) * unit;\n}\n\n/** `undefined` = no reset information at all; a number = a reset header exists (0 when its value is not a delay). */\nfunction delayOfHeaders(headers: Readonly<Record<string, string>> | undefined): number | undefined {\n let found: number | undefined;\n for (const [name, value] of Object.entries(headers ?? {})) {\n if (!RESET_HEADER.test(name)) continue;\n const seconds = Number(value);\n const delay = Number.isFinite(seconds) && seconds >= 0 ? Math.round(seconds * 1_000) : 0;\n found = Math.max(found ?? 0, delay);\n }\n return found;\n}\n\nconst oauthCause = (text: string): string =>\n /expire/i.test(text) ? 'expired' : /revoked|invalid_grant/i.test(text) ? 'revoked' : 'refresh-failed';\n\nexport function classify(signal: ErrorSignal, evidence: ClassifyEvidence = {}): ErrorInfo {\n const { modelsErrorCode, causeCode, text, origin } = signal;\n const prefixed = STATUS_PREFIX.exec(text)?.[1];\n const status = signal.httpStatus ?? (prefixed === undefined ? undefined : Number(prefixed));\n const mint = (code: ErrorCode, details: Record<string, JsonValue> = {}, retryAfterMs?: number): ErrorInfo =>\n errorOf(code, text, {\n details: {\n origin,\n ...(modelsErrorCode === undefined ? {} : { modelsErrorCode }),\n ...(causeCode === undefined ? {} : { causeCode }),\n ...(status === undefined ? {} : { httpStatus: status }),\n ...details,\n },\n ...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n });\n\n // (1) the engine's code TOGETHER WITH the text and the cause: the code alone is not a discriminator.\n if (modelsErrorCode === 'auth') {\n if (STORE_FAILED.test(text) || (causeCode !== undefined && STORE_LOCK_CODES.has(causeCode)))\n return mint('provider-transient/credential-store-locked');\n if (NOT_CONFIGURED.test(text)) return mint('provider-terminal/auth-required', { 'auth.required.cause': 'absent' });\n return mint('provider-terminal/auth-required', { unclassified: true });\n }\n if (modelsErrorCode === 'oauth') {\n const network = (causeCode !== undefined && NETWORK_CODES.has(causeCode)) || NETWORK_TEXT.test(text);\n if (network || EMBEDDED_5XX.test(text)) return mint('provider-transient/network');\n return mint('provider-terminal/auth-required', { 'auth.required.cause': oauthCause(text) });\n }\n\n // (2) the HTTP status, (3) the status prefix, (4) known texts.\n const usageLimit = USAGE_LIMIT.test(text);\n const textDelay = delayOfText(text);\n if (usageLimit && textDelay !== undefined) return mint('provider-terminal/quota-exceeded', {}, textDelay);\n if (status === 429) {\n const headerDelay = delayOfHeaders(evidence.headers);\n if (usageLimit || headerDelay !== undefined)\n return mint('provider-terminal/quota-exceeded', {}, headerDelay === 0 ? undefined : headerDelay);\n return mint('provider-transient/rate-limited');\n }\n if (usageLimit) return mint('provider-terminal/entitlement');\n if (CONTEXT_OVERFLOW.test(text)) return mint('budget/context-window');\n if (status === 404 || MODEL_NOT_FOUND.test(text)) return mint('provider-terminal/model-not-found');\n if (status === 400 && MODEL_ENTITLEMENT.test(text)) return mint('provider-terminal/entitlement');\n if (status === 401 || status === 403)\n return mint('provider-terminal/auth-required', { 'auth.required.cause': 'rejected' });\n if (status === 503 || status === 529 || OVERLOADED.test(text)) return mint('provider-transient/overloaded');\n if ((causeCode !== undefined && NETWORK_CODES.has(causeCode)) || NETWORK_TEXT.test(text))\n return mint('provider-transient/network');\n if ((status !== undefined && status >= 500) || BROKEN_STREAM.test(text)) return mint('provider-transient/unexpected');\n\n // (5) nothing matched: not retried, and the trace says that the table needs a row.\n return mint('provider-terminal/unexpected', { unclassified: true });\n}\n","// DESIGN 3.9 — runtime pinning (spec 16). Engine-free: the engine's packages are FILES to hash here, never modules\n// to load. `pin()` runs once at run start; every spawn re-verifies through a stat cache.\nimport { createHash } from 'node:crypto';\nimport { lstat, readdir, readFile, realpath, stat } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\nimport { CohorteError, canonicalJson, errorOf, type Sha256, sha256Hex } from '@cohorte/base';\nimport type { RuntimePin } from '@cohorte/runtime-contract';\n\nexport const RUNTIME_ID = 'pi';\nexport const ADAPTER_VERSION = '3.0.0';\nexport const ENGINE_NAME = 'pi';\n/** The three packages the brain loads. Their versions MUST be equal (ADR-0001). */\nexport const ENGINE_PACKAGES = [\n '@earendil-works/pi-coding-agent',\n '@earendil-works/pi-ai',\n '@earendil-works/pi-agent-core',\n] as const;\n\nexport interface PinOptions {\n /** the install whose `dist/` holds both bundles */\n installDir: string;\n loadFrom: 'package' | 'bundle';\n /** TESTS ONLY: the child entry that replaces the pinned one (the fake brain). That one file is pinned, and no engine. */\n entryOverride?: string;\n}\n\nexport type PinDiagnostics = Record<string, string>;\ntype Artifact = RuntimePin['artifacts'][number];\n\ninterface HashCache {\n entries: Map<string, { key: string; sha256: Sha256 }>;\n hashed: number;\n}\nconst newCache = (): HashCache => ({ entries: new Map(), hashed: 0 });\n\nconst engineInit = (message: string): CohorteError => new CohorteError(errorOf('configuration/engine-init', message));\n\n/** The content hash of one file, re-read only when `(dev, ino, size, mtimeNs)` moved. */\nasync function hashFile(path: string, cache: HashCache): Promise<{ sha256: Sha256; size: number }> {\n const info = await stat(path, { bigint: true });\n const key = `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}`;\n const known = cache.entries.get(path);\n if (known?.key === key) return { sha256: known.sha256, size: Number(info.size) };\n const sha256 = createHash('sha256')\n .update(await readFile(path))\n .digest('hex') as Sha256;\n cache.hashed += 1;\n cache.entries.set(path, { key, sha256 });\n return { sha256, size: Number(info.size) };\n}\n\nasync function filesUnder(root: string): Promise<string[]> {\n const found: string[] = [];\n const walk = async (dir: string): Promise<void> => {\n for (const entry of await readdir(dir, { withFileTypes: true })) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) await walk(path);\n else if (entry.isFile()) found.push(path);\n else if (entry.isSymbolicLink() && (await stat(path)).isFile()) found.push(path);\n }\n };\n await walk(root);\n return found;\n}\n\n/** One sorted `{path,size,sha256}` tree digest: an added, removed, renamed or edited file all move it. */\nasync function treeArtifact(\n role: Artifact['role'],\n root: string,\n files: readonly string[],\n cache: HashCache,\n): Promise<Artifact> {\n const rows: { path: string; size: number; sha256: Sha256 }[] = [];\n for (const file of files) {\n const { sha256, size } = await hashFile(file, cache);\n rows.push({ path: relative(root, file).split(sep).join('/'), size, sha256 });\n }\n rows.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n return {\n role,\n path: root,\n sha256: sha256Hex(canonicalJson(rows)),\n files: rows.length,\n bytes: rows.reduce((sum, row) => sum + row.size, 0),\n };\n}\n\nconst exists = (path: string): Promise<boolean> =>\n stat(path).then(\n () => true,\n () => false,\n );\n\n/** Node's own walk for a bare specifier, done by hand: `createRequire` is refused in shipped code (check-layers rule g). */\nasync function findPackage(from: string, name: string): Promise<{ dir: string; nodeModules: string } | undefined> {\n for (let dir = from; ; dir = dirname(dir)) {\n const nodeModules = join(dir, 'node_modules');\n if (await exists(join(nodeModules, name, 'package.json'))) return { dir: join(nodeModules, name), nodeModules };\n if (dirname(dir) === dir) return undefined;\n }\n}\n\nasync function engineArtifacts(\n options: PinOptions,\n cache: HashCache,\n): Promise<{ artifacts: Artifact[]; version: string; nodeModules: string }> {\n const packages = options.loadFrom === 'bundle' ? ENGINE_PACKAGES.slice(0, 1) : ENGINE_PACKAGES;\n const artifacts: Artifact[] = [];\n const versions = new Map<string, string>();\n let nodeModules = '';\n for (const name of packages) {\n const found = await findPackage(options.installDir, name);\n if (!found) throw engineInit(`the engine package ${name} is not installed next to ${options.installDir}`);\n nodeModules ||= found.nodeModules;\n const dir = await realpath(found.dir);\n const manifest = join(dir, 'package.json');\n const parsed: unknown = JSON.parse(await readFile(manifest, 'utf8'));\n const version = typeof parsed === 'object' && parsed !== null && 'version' in parsed ? String(parsed.version) : '';\n versions.set(name, version);\n const code = join(dir, 'dist', ...(options.loadFrom === 'bundle' ? ['bundle'] : []));\n if (!(await exists(code))) throw engineInit(`the engine package ${name} has no ${relative(dir, code)} directory`);\n artifacts.push(await treeArtifact('engine-package-tree', dir, [manifest, ...(await filesUnder(code))], cache));\n }\n const distinct = [...new Set(versions.values())];\n const [version] = distinct;\n if (distinct.length !== 1 || !version)\n throw engineInit(\n `the engine packages must all be at the same version: ${[...versions].map(([name, v]) => `${name}@${v}`).join(', ')}`,\n );\n return { artifacts, version, nodeModules };\n}\n\nasync function lockArtifact(\n options: PinOptions,\n nodeModules: string,\n cache: HashCache,\n diagnostics: PinDiagnostics,\n): Promise<Artifact[]> {\n // A gate or unit build links `<dir>/node_modules` into the workspace (PLAN F-7): it has no lock evidence of its own.\n const own = await lstat(join(options.installDir, 'node_modules')).catch(() => undefined);\n if (own?.isSymbolicLink()) {\n diagnostics.installLock = 'absent (linked development build)';\n return [];\n }\n for (const name of ['.package-lock.json', '.modules.yaml']) {\n const path = join(nodeModules, name);\n if (!(await exists(path))) continue;\n const { sha256, size } = await hashFile(path, cache);\n diagnostics.installLock = name;\n return [{ role: 'install-lock', path, sha256, files: 1, bytes: size }];\n }\n diagnostics.installLock = 'absent';\n return [];\n}\n\nasync function compute(\n options: PinOptions,\n cache: HashCache,\n): Promise<{ pin: RuntimePin; diagnostics: PinDiagnostics }> {\n const diagnostics: PinDiagnostics = { loadFrom: options.loadFrom };\n const artifacts: Artifact[] = [];\n let engine: RuntimePin['engine'] = null;\n if (options.entryOverride !== undefined) {\n const { sha256, size } = await hashFile(options.entryOverride, cache);\n artifacts.push({ role: 'agent-host-bundle', path: options.entryOverride, sha256, files: 1, bytes: size });\n diagnostics.entry = 'override (tests only): no engine is pinned';\n } else {\n const dist = join(options.installDir, 'dist');\n if (!(await exists(dist))) throw engineInit(`${options.installDir} has no dist/ directory: nothing to pin`);\n artifacts.push(await treeArtifact('agent-host-bundle', dist, await filesUnder(dist), cache));\n const found = await engineArtifacts(options, cache);\n artifacts.push(...found.artifacts, ...(await lockArtifact(options, found.nodeModules, cache, diagnostics)));\n engine = { name: ENGINE_NAME, version: found.version };\n // Transitive dependencies are covered by the lock evidence only: `runtimePinning` is reported `partial`.\n diagnostics.transitive = 'lock evidence only';\n }\n const body = {\n runtimeId: RUNTIME_ID,\n adapterVersion: ADAPTER_VERSION,\n engine,\n node: { version: process.version, execPath: process.execPath },\n artifacts,\n };\n return { pin: { ...body, digest: sha256Hex(canonicalJson(body)) }, diagnostics };\n}\n\nexport function pinWithDiagnostics(options: PinOptions): Promise<{ pin: RuntimePin; diagnostics: PinDiagnostics }> {\n return compute(options, newCache());\n}\n\nexport interface PinVerifier {\n /** Rejects with `security/runtime-pin-mismatch` when the installed code is not what `pinned` names. */\n verify(pinned: RuntimePin): Promise<void>;\n stats(): { hashed: number; cached: number };\n}\n\n/** One per runtime: its stat cache makes the per-spawn verification a walk of `stat` calls. */\nexport function createPinVerifier(options: PinOptions): PinVerifier {\n const cache = newCache();\n return {\n stats: () => ({ hashed: cache.hashed, cached: cache.entries.size }),\n async verify(pinned) {\n const { pin: now } = await compute(options, cache);\n // The whole value, not the digest alone: a pin whose body was edited under an intact digest is a mismatch too.\n if (canonicalJson(now) === canonicalJson(pinned)) return;\n const differing = [\n ...(canonicalJson(now.node) === canonicalJson(pinned.node) ? [] : ['node']),\n ...(canonicalJson(now.engine) === canonicalJson(pinned.engine) ? [] : ['engine']),\n ...now.artifacts\n .filter((a, i) => canonicalJson(a) !== canonicalJson(pinned.artifacts[i] ?? null))\n .map((a) => a.path),\n ...(now.artifacts.length === pinned.artifacts.length ? [] : ['artifact count']),\n ];\n throw new CohorteError(\n errorOf(\n 'security/runtime-pin-mismatch',\n `the installed runtime is not the one pinned at run start: ${differing.join(', ')}`,\n {\n details: { pinned: pinned.digest, found: now.digest, differing },\n },\n ),\n );\n },\n };\n}\n","// The last two rows of DESIGN 3.8: errors the PARENT mints from what it observes itself, never from an engine signal.\nimport { type ErrorInfo, errorOf } from '@cohorte/base';\nimport type { AttestationMismatch } from '../protocol.ts';\n\nexport type ProcessExitReason = 'disconnect' | 'exit-without-settled' | 'heartbeat-lost' | 'spawn-failed';\n\n/** `outcome: 'crashed'`: the host starts a new incarnation. */\nexport function processExitError(reason: ProcessExitReason, detail = ''): ErrorInfo {\n return errorOf(\n 'tool-transient/agent-process-exit',\n `the agent process went away (${reason})${detail ? `: ${detail}` : ''}`,\n {\n details: { reason },\n },\n );\n}\n\nexport type ProtocolViolationKind =\n | 'unknown-tool'\n | 'frame-schema'\n | 'ordinal-gap'\n | 'nonce-mismatch'\n | 'unexpected-frame'\n | 'handshake-timeout';\n\n/**\n * A child that breaks the host protocol is treated as hostile. The catalogue has no dedicated row yet\n * (docs/v3/requests/U0.03.md R4), so the code is `security/unexpected` and `details.violation` says which rule broke.\n * `detail` says WHERE, never WHAT: a refused frame may hold anything.\n */\nexport function protocolViolation(kind: ProtocolViolationKind, detail: string): ErrorInfo {\n return errorOf('security/unexpected', `the agent process broke the host protocol (${kind}): ${detail}`, {\n details: { violation: kind },\n });\n}\n\n/** The spawn fails closed on ANY mismatch; the two mismatches that have a catalogue row of their own keep it. */\nexport function attestationError(mismatches: readonly AttestationMismatch[]): ErrorInfo {\n const fields = mismatches.map((mismatch) => mismatch.field);\n const message = `the agent process attested something else than what was asked: ${mismatches\n .map(({ field, expected, got }) => `${field} (expected ${expected}, got ${got})`)\n .join('; ')}`;\n const details = { violation: 'attestation-mismatch', fields };\n if (fields.includes('effective.baseUrl')) return errorOf('security/auth-endpoint-mismatch', message, { details });\n if (fields.some((field) => field.startsWith('auth.')))\n return errorOf('security/auth-mode-violation', message, { details });\n return errorOf('security/unexpected', message, { details });\n}\n","// DESIGN 3.7 layer 1 — the child's environment is an ALLOWLIST; nothing else is inherited (D3). The engine has no\n// injectable auth context, so a process without credential-shaped variables is the only structural defence against\n// \"nothing stored + an env key => a paid API call\".\nimport { CohorteError, errorOf } from '@cohorte/base';\nimport type { SandboxPolicy } from '@cohorte/runtime-contract';\n\n/**\n * A name is credential-shaped when the LAST word of it is one of the secret words (so `OPENAI_API_KEY`, `XAI_KEY`,\n * `APIKEY` and a bare `TOKEN` are all refused, while `MONKEY` and `TOKENIZER` are not), or when it opens with a known\n * provider prefix. It is a NAME guard, not a value guard: the value is never looked at (I7).\n */\nconst CREDENTIAL_SHAPED =\n /(^|_)(API_?KEY|KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|CREDENTIALS|BEARER)$|^(AWS|GOOGLE|GCP|GH|GITHUB|GITLAB|ANTHROPIC|OPENAI|AZURE|XAI|GROQ|MISTRAL|OPENROUTER|COHERE|DEEPSEEK|HUGGINGFACE|REPLICATE|VERTEX)_/i;\n\n/**\n * A name that makes the runtime load foreign code before the entry runs (`DYLD_INSERT_LIBRARIES`, `LD_PRELOAD`,\n * `NODE_OPTIONS`, `NODE_REPL_EXTERNAL_MODULE`…). It is refused in `allow` AND in `set`: the parent fixes `NODE_OPTIONS`\n * itself, and a policy that could name one of these would defeat every other layer of 3.7.\n */\nconst LOADER_SHAPED = /^(LD_|DYLD_|NODE_)/i;\n\n/** DESIGN 3.7 layer 1: the ONLY names the child inherits from the parent's environment. A policy narrows this list. */\nexport const L1_ENV_ALLOW: readonly string[] = ['PATH', 'HOME', 'LANG', 'LC_ALL', 'TZ', 'TMPDIR'];\n\n/**\n * Inherited only when the project's `network.proxyEnv` is on. That switch lives in `@cohorte/config`, two layers away,\n * and `SandboxPolicy` carries no flag for it: the composition root's decision reaches this side as the presence of\n * these names in `sandbox.env.allow` (docs/v3/requests/U1.07.md R4).\n */\nexport const L1_PROXY_ENV: readonly string[] = [\n 'HTTP_PROXY',\n 'HTTPS_PROXY',\n 'NO_PROXY',\n 'http_proxy',\n 'https_proxy',\n 'no_proxy',\n];\n\nconst INHERITABLE = new Set([...L1_ENV_ALLOW, ...L1_PROXY_ENV]);\nexport const DEFAULT_MAX_OLD_SPACE_MB = 512;\n\n/** What the parent ALWAYS sets, whatever the policy says: a project cannot turn the engine's network features back on. */\nexport function fixedChildEnv(agentDir: string, maxOldSpaceMb: number | undefined): Record<string, string> {\n return {\n NODE_OPTIONS: `--max-old-space-size=${maxOldSpaceMb ?? DEFAULT_MAX_OLD_SPACE_MB}`,\n PI_OFFLINE: '1',\n PI_SKIP_VERSION_CHECK: '1',\n PI_TELEMETRY: '0',\n PI_CODING_AGENT_DIR: agentDir,\n };\n}\n\n/**\n * The exact env of the child, and the policy whose names the attestation is held against (`allow` ∪ keys of `set`,\n * PLAN F-8: plus whatever the OS injects, which `diffAttestation` knows).\n */\nexport function childEnv(\n policy: SandboxPolicy['env'],\n fixed: Record<string, string>,\n ambient: NodeJS.ProcessEnv = process.env,\n): { env: Record<string, string>; attested: SandboxPolicy['env'] } {\n const set = { ...policy.set, ...fixed };\n const named = [...policy.allow, ...Object.keys(policy.set)];\n const refuse = (why: string, names: string[]): void => {\n if (names.length > 0)\n throw new CohorteError(errorOf('security/auth-mode-violation', `${why}: ${names.join(', ')}`));\n };\n refuse(\n 'credential-shaped variables may not reach the agent process',\n named.filter((name) => CREDENTIAL_SHAPED.test(name)),\n );\n refuse(\n 'loader variables may not reach the agent process',\n named.filter((name) => LOADER_SHAPED.test(name)),\n );\n // The allowlist of layer 1 is the parent's, not the policy's: a policy narrows it and can never widen it.\n refuse(\n 'the agent process inherits only the layer-1 allowlist (DESIGN 3.7), plus the proxy variables of network.proxyEnv',\n policy.allow.filter((name) => !INHERITABLE.has(name)),\n );\n const env: Record<string, string> = {};\n for (const name of policy.allow) {\n const value = ambient[name];\n if (value !== undefined) env[name] = value;\n }\n return { env: { ...env, ...set }, attested: { allow: policy.allow, set } };\n}\n","// The child's stdout and stderr (DESIGN 3.2). They are never parsed and never reach a raw file: the engine can print\n// refresh or login error bodies that hold token material, so every line goes through the sealed logger. Bounded:\n// a line is cut at 64 KiB, an incarnation gets 1 MiB, then ONE \"truncated\" line; the pipes are still drained, so a\n// flooding child neither blocks nor grows the parent.\n\nimport type { Readable } from 'node:stream';\nimport { StringDecoder } from 'node:string_decoder';\n\nexport const OUTPUT_LINE_CAP = 64 * 1024;\nexport const OUTPUT_INCARNATION_CAP = 1024 * 1024;\n\nexport interface OutputBudget {\n left: number;\n truncated: boolean;\n}\nexport const newOutputBudget = (): OutputBudget => ({ left: OUTPUT_INCARNATION_CAP, truncated: false });\n\nexport function drainChildOutput(\n stream: Readable,\n name: 'stdout' | 'stderr',\n budget: OutputBudget,\n write: (line: string, stream: 'stdout' | 'stderr') => void,\n): void {\n const decoder = new StringDecoder('utf8');\n let pending = '';\n let skippingLongLine = false;\n\n const emit = (line: string): void => {\n if (budget.truncated || line.length === 0) return;\n if (line.length > budget.left) {\n budget.truncated = true;\n budget.left = 0;\n write(`[child output truncated after ${OUTPUT_INCARNATION_CAP} bytes for this incarnation]`, name);\n return;\n }\n budget.left -= line.length;\n write(line, name);\n };\n\n const feed = (text: string): void => {\n if (budget.truncated) return;\n pending += text;\n for (let end = pending.indexOf('\\n'); end !== -1; end = pending.indexOf('\\n')) {\n const line = pending.slice(0, end).replace(/\\r$/, '');\n pending = pending.slice(end + 1);\n if (skippingLongLine) skippingLongLine = false;\n else emit(line);\n }\n if (pending.length > OUTPUT_LINE_CAP) {\n if (!skippingLongLine) emit(`${pending.slice(0, OUTPUT_LINE_CAP)} [line cut at ${OUTPUT_LINE_CAP} bytes]`);\n skippingLongLine = true;\n pending = '';\n }\n };\n\n stream.on('data', (chunk: Buffer) => feed(decoder.write(chunk)));\n stream.on('end', () => {\n feed(decoder.end());\n if (!skippingLongLine) emit(pending);\n pending = '';\n });\n stream.on('error', () => {});\n}\n","// AgentHostProtocol v1 — private contract #3 (DESIGN 3.3): the frames between the runtime parent and its per-agent\n// child. Engine-free and transport-agnostic: the same frames travel over the Node 'ipc' channel (serialization\n// 'json') and as LF-delimited JSON over fd 3/4. Frozen in Wave 0 so that the parent and the fake brain are built in\n// parallel. NO engine type crosses the channel.\nimport {\n type AuthMode,\n ErrorInfo,\n err,\n IsoInstant,\n type JsonValue,\n JsonValueSchema,\n ok,\n type Result,\n Sha256,\n} from '@cohorte/base';\nimport {\n AgentExit,\n ProviderAuthStatus,\n RUNTIME_EVENT_TYPE_NAMES,\n RUNTIME_EVENT_TYPES,\n type RuntimeEventOf,\n type RuntimeEventType,\n SpawnRequest,\n ToolContent,\n} from '@cohorte/runtime-contract';\nimport { type Static, type TSchema, type TUnsafe, Type } from 'typebox';\nimport { Compile } from 'typebox/compile';\n\nexport const HOST_PROTOCOL = 1;\n\nconst strict = { additionalProperties: false } as const;\nconst count = () => Type.Integer({ minimum: 0 });\n// The explicit TUnsafe keeps Biome's type inference out of `Static<TRecord>`: it overflows its stack there and then\n// exits 0, so the lint LOOKS green while nothing was checked (docs/v3/requests/U0.02.md R1, U0.03.md R1).\nconst stringMap = (): TUnsafe<Record<string, string>> =>\n Type.Unsafe<Record<string, string>>(Type.Record(Type.String(), Type.String()));\nconst delivery = () => Type.Union([Type.Literal('steer'), Type.Literal('follow-up')]);\n\n/**\n * The spawn request as it crosses the channel. Every member of `SpawnRequest` is JSON already and the child reads\n * the prompt by reference (`readVerified(req.systemPrompt)`, DESIGN 3.4), so the wire shape IS the contract shape.\n */\nexport const SpawnRequestWire = SpawnRequest;\nexport type SpawnRequestWire = SpawnRequest;\n\nexport const EngineSettings = Type.Object(\n {\n authPath: Type.String(),\n agentDir: Type.String(),\n sessionFile: Type.String(),\n loadFrom: Type.Union([Type.Literal('package'), Type.Literal('bundle')]),\n expectedEngineVersion: Type.String(),\n responseHeaderAllowlist: Type.Array(Type.String()),\n },\n strict,\n);\nexport type EngineSettings = Static<typeof EngineSettings>;\nconst AuthEngineSettings = Type.Object({ authPath: Type.String(), agentDir: Type.String() }, strict);\n\n/**\n * What the child extracts from a thrown value or an error message, so that the classifier is a PURE, engine-free\n * function in the parent (DESIGN 3.8). Only child code looks at engine classes.\n */\nexport const ErrorSignal = Type.Object(\n {\n /** the engine's own error code */\n modelsErrorCode: Type.Optional(Type.String()),\n /** errno-style code of the innermost cause: ELOCKED, EPERM, EACCES, EBUSY, ECONNRESET, ABORT_ERR… */\n causeCode: Type.Optional(Type.String()),\n httpStatus: Type.Optional(Type.Integer()),\n /** sealed by the parent before it goes anywhere */\n text: Type.String(),\n origin: Type.Union([\n Type.Literal('prompt-preflight'),\n Type.Literal('model-response'),\n Type.Literal('auth-check'),\n Type.Literal('login'),\n Type.Literal('engine'),\n ]),\n },\n strict,\n);\nexport type ErrorSignal = Static<typeof ErrorSignal>;\n\nconst attestationShape = {\n /** the engine's packages MUST all be at the same version */\n engine: Type.Object({ name: Type.String(), version: Type.String(), packageVersions: stringMap() }, strict),\n /** MUST equal the grant exactly, and so must the registry (allowlist typos vanish silently in the engine) */\n activeTools: Type.Array(Type.String()),\n /** sha256 of the system prompt the engine really holds: Cohorte's prompt + the engine's own suffix */\n effectiveSystemPromptSha256: Sha256,\n systemPromptPrefixOk: Type.Boolean(),\n /** from the engine's model runtime, no secret (DESIGN 3.7) */\n auth: Type.Object(\n {\n provider: Type.String(),\n type: Type.Union([Type.Literal('oauth'), Type.Literal('api_key')]),\n source: Type.String(),\n subscription: Type.Boolean(),\n },\n strict,\n ),\n /** MUST equal AuthRequirement.baseUrl / the requested model */\n effective: Type.Object(\n { provider: Type.String(), model: Type.String(), api: Type.String(), baseUrl: Type.String() },\n strict,\n ),\n hooks: Type.Object(\n {\n streamWrapperInstalled: Type.Boolean(),\n guardFetchInstalled: Type.Boolean(),\n onResponseChained: Type.Boolean(),\n shouldStopAfterTurn: Type.Boolean(),\n },\n strict,\n ),\n sessionFile: Type.String(),\n sessionId: Type.String({ minLength: 1 }),\n /** NAMES of env vars visible to the child; checked against allow ∪ OS_INJECTED_ENV[platform] */\n envKeys: Type.Array(Type.String()),\n platform: Type.String(),\n};\n\n/** What the child PROVES before the first prompt; the parent fails the spawn closed on ANY mismatch. */\nexport const Attestation = Type.Object(\n {\n ...attestationShape,\n hostProtocol: Type.Literal(1),\n extensionsLoaded: Type.Literal(0),\n extensionErrors: Type.Literal(0),\n modelFallback: Type.Literal(false),\n settings: Type.Object(\n {\n compaction: Type.Literal(false),\n agentRetry: Type.Literal(false),\n providerMaxRetries: Type.Literal(0),\n transport: Type.Literal('sse'),\n },\n strict,\n ),\n },\n strict,\n);\nexport type Attestation = Static<typeof Attestation>;\n\n/**\n * What a `ready` frame CARRIES: an Attestation whose fixed members are not fixed yet. A child that fell back to\n * another model says `modelFallback: true`; were the frame schema to refuse that, the spawn would fail as a schema\n * violation at a JSON pointer. It fails instead on what `diffAttestation` names. Every Attestation is a claim.\n */\nexport const AttestationClaim = Type.Object(\n {\n ...attestationShape,\n hostProtocol: Type.Integer(),\n extensionsLoaded: count(),\n extensionErrors: count(),\n modelFallback: Type.Boolean(),\n settings: Type.Object(\n { compaction: Type.Boolean(), agentRetry: Type.Boolean(), providerMaxRetries: count(), transport: Type.String() },\n strict,\n ),\n },\n strict,\n);\nexport type AttestationClaim = Static<typeof AttestationClaim>;\n\n/**\n * A runtime event as the child knows it: already normalised, without the envelope. The PARENT stamps `runId`,\n * `agentId`, `incarnation` and the durability of the type; `seq` travels on the frame.\n */\nexport type HostEvent = {\n [T in RuntimeEventType]: { type: T; at: IsoInstant; data: RuntimeEventOf<T>['data'] };\n}[RuntimeEventType];\nexport const HostEvent: TUnsafe<HostEvent> = Type.Unsafe<HostEvent>(\n Type.Union(\n RUNTIME_EVENT_TYPE_NAMES.map((type) =>\n Type.Object({ type: Type.Literal(type), at: IsoInstant, data: RUNTIME_EVENT_TYPES[type].data }, strict),\n ),\n ),\n);\n\nconst frame = <T extends string, P extends Record<string, TSchema>>(t: T, members: P) =>\n Type.Object({ t: Type.Literal(t), ...members }, strict);\nconst init = <M extends string, P extends Record<string, TSchema>>(mode: M, members: P) =>\n frame('init', { v: Type.Literal(1), nonce: Type.String({ minLength: 1 }), mode: Type.Literal(mode), ...members });\n\n/** parent -> child */\nexport const ParentFrame = Type.Union([\n init('agent', { request: SpawnRequestWire, engine: EngineSettings }),\n init('auth-status', { providers: Type.Array(Type.String()), engine: AuthEngineSettings }),\n init('auth-login', { provider: Type.String(), engine: AuthEngineSettings }),\n init('auth-logout', { provider: Type.String(), engine: AuthEngineSettings }),\n // `text` and `note.text` are read by the PARENT (TaskInput / Continuation.note, hash-verified). The child delivers\n // `text`, then `note.text`, before the first model request (conformance rule 12).\n frame('prompt', {\n id: Type.String(),\n text: Type.String(),\n note: Type.Optional(Type.Object({ text: Type.String() }, strict)),\n }),\n frame('send', { id: Type.String(), messageId: Type.String(), text: Type.String(), delivery: delivery() }),\n frame('tool.result', {\n toolCallId: Type.String(),\n isError: Type.Boolean(),\n content: Type.Array(ToolContent),\n terminate: Type.Boolean(),\n resultRef: Type.Optional(Type.String()),\n }),\n frame('pause', {}),\n frame('resume', {}),\n frame('stop-after-turn', { reason: Type.String() }),\n frame('abort', { id: Type.String(), reason: Type.String() }),\n frame('auth.answer', { id: Type.String(), value: Type.String() }),\n frame('inspect', { id: Type.String() }),\n frame('shutdown', {}),\n]);\nexport type ParentFrame = Static<typeof ParentFrame>;\n\n/** child -> parent. All of it is untrusted input: validated here, sealed by the parent, tool input re-validated by the host. */\nexport const ChildFrame = Type.Union([\n // first thing the entry does\n frame('hello', { v: Type.Literal(1), pid: Type.Integer({ minimum: 1 }), nonce: Type.String({ minLength: 1 }) }),\n frame('ready', { attestation: AttestationClaim }),\n frame('event', { seq: count(), event: HostEvent }),\n frame('tool.call', {\n seq: count(),\n ordinal: Type.Integer({ minimum: 1 }),\n engineToolCallId: Type.String(),\n tool: Type.String(),\n input: JsonValueSchema,\n }),\n frame('tool.call.abandoned', {\n engineToolCallId: Type.String(),\n reason: Type.Union([Type.Literal('aborted'), Type.Literal('shutdown')]),\n }),\n // ALLOWLISTED header names only\n frame('provider.response', {\n requestId: Type.String(),\n status: Type.Integer(),\n headers: stringMap(),\n }),\n // from the GUARD FETCH (DESIGN 3.7 layer 5): what actually left the process. Never a header VALUE.\n frame('provider.request', {\n requestId: Type.String(),\n origin: Type.String(),\n authScheme: Type.Union([\n Type.Literal('bearer-jwt'),\n Type.Literal('bearer-opaque'),\n Type.Literal('api-key-header'),\n Type.Literal('none'),\n ]),\n refused: Type.Boolean(),\n }),\n frame('parked', { at: Type.Literal('model-boundary') }),\n frame('heartbeat', { rssMb: Type.Number({ minimum: 0 }), state: Type.String() }),\n frame('auth.status', { statuses: Type.Array(ProviderAuthStatus) }),\n frame('auth.show', { event: JsonValueSchema }),\n frame('auth.ask', { id: Type.String(), prompt: JsonValueSchema }),\n frame('auth.done', { status: ProviderAuthStatus }),\n // the PARENT classifies: exit.error = classify(signal) (DESIGN 3.8)\n frame('settled', { exit: Type.Omit(AgentExit, ['error'], strict), signal: Type.Optional(ErrorSignal) }),\n frame('response', {\n id: Type.String(),\n ok: Type.Boolean(),\n data: Type.Optional(JsonValueSchema),\n error: Type.Optional(ErrorInfo),\n }),\n // `error` for the child's OWN typed fatals (asset hash, endpoint mismatch…); `signal` when an engine error caused it\n frame('fatal', { error: ErrorInfo, signal: Type.Optional(ErrorSignal) }),\n]);\nexport type ChildFrame = Static<typeof ChildFrame>;\n\nexport type FrameSender = 'parent' | 'child';\n/** 'ipc' = a message of the Node 'ipc' channel (serialization 'json'); 'lf' = one LF-terminated line of JSON. */\nexport type FrameWire = 'ipc' | 'lf';\nexport type FrameOf<S extends FrameSender> = S extends 'parent' ? ParentFrame : ChildFrame;\n\n/** One frame is one line on the 'lf' wire; a longer line is refused before it is parsed. */\nexport const MAX_FRAME_CHARS = 16 * 1024 * 1024;\n\nexport interface FrameRejection {\n reason: 'not-a-frame' | 'too-large' | 'not-json' | 'unknown-frame' | 'schema-violation';\n /** Where and why, never WHAT: a refused frame may hold anything, a secret included. */\n detail: string;\n}\n\nexport function encodeFrame(frame: ParentFrame | ChildFrame, wire: 'lf'): string;\nexport function encodeFrame(frame: ParentFrame | ChildFrame, wire: 'ipc'): JsonValue;\nexport function encodeFrame(frame: ParentFrame | ChildFrame, wire: FrameWire): string | JsonValue;\nexport function encodeFrame(frame: ParentFrame | ChildFrame, wire: FrameWire): string | JsonValue {\n // JSON.stringify escapes every line terminator inside a string, so the only raw LF of a line is its end.\n return wire === 'lf' ? `${JSON.stringify(frame)}\\n` : (frame as JsonValue);\n}\n\ntype VariantSchema = TSchema & { properties: { t: { const: unknown }; mode?: { const: unknown } } };\ninterface VariantCheck {\n /** the `mode` literal of the variants that share one `t` (the four `init`); absent when the tag names one variant */\n mode: string | undefined;\n check: ReturnType<typeof Compile>;\n}\n// One validator per VARIANT: against the whole union, the first error is the one of the union's first member.\nconst checksOf = (union: { anyOf: readonly TSchema[] }): Map<string, VariantCheck[]> => {\n const byTag = new Map<string, VariantCheck[]>();\n for (const variant of union.anyOf) {\n const { t, mode } = (variant as VariantSchema).properties;\n const tag = String(t.const);\n const entry = { mode: mode === undefined ? undefined : String(mode.const), check: Compile(variant) };\n byTag.set(tag, [...(byTag.get(tag) ?? []), entry]);\n }\n return byTag;\n};\nconst CHECKS = { parent: checksOf(ParentFrame), child: checksOf(ChildFrame) };\n\n/** Total: whatever arrives, the answer is a frame or a rejection. It never throws and never echoes a value. */\nexport function decodeFrame<S extends FrameSender>(\n sender: S,\n raw: unknown,\n wire: FrameWire,\n): Result<FrameOf<S>, FrameRejection> {\n let value: unknown = raw;\n if (wire === 'lf') {\n if (typeof raw !== 'string')\n return err({ reason: 'not-a-frame', detail: `expected a line of text, got ${typeof raw}` });\n if (raw.length > MAX_FRAME_CHARS) return err({ reason: 'too-large', detail: `a line of ${raw.length} characters` });\n const line = raw.endsWith('\\n') ? raw.slice(0, -1) : raw;\n if (line.includes('\\n')) return err({ reason: 'not-a-frame', detail: 'more than one line' });\n try {\n value = JSON.parse(line);\n } catch {\n return err({ reason: 'not-json', detail: 'the line is not JSON' });\n }\n }\n if (typeof value !== 'object' || value === null || Array.isArray(value))\n return err({ reason: 'not-a-frame', detail: 'a frame is a JSON object' });\n try {\n const tag: unknown = (value as { t?: unknown }).t;\n const variants = typeof tag === 'string' ? CHECKS[sender].get(tag) : undefined;\n if (typeof tag !== 'string' || variants === undefined)\n return err({ reason: 'unknown-frame', detail: `no ${sender} frame has that \"t\"` });\n const mode: unknown = (value as { mode?: unknown }).mode;\n const variant = variants.length === 1 ? variants[0] : variants.find((candidate) => candidate.mode === mode);\n if (variant === undefined)\n return err({ reason: 'schema-violation', detail: `${tag}: /mode is not a mode of that frame` });\n if (variant.check.Check(value)) return ok(value as FrameOf<S>);\n const [first] = variant.check.Errors(value);\n return err({\n reason: 'schema-violation',\n detail: `${tag}: ${first?.instancePath || '/'} ${first?.message ?? 'is invalid'}`,\n });\n } catch {\n // A hostile 'ipc' value (throwing getters) is not a frame.\n return err({ reason: 'not-a-frame', detail: 'the value could not be read' });\n }\n}\n\n/**\n * Env var NAMES the OS puts into every process, whatever `env` the parent passes (PLAN F-8: a Node child spawned on\n * macOS with `env: { PATH }` reports PATH and __CF_USER_TEXT_ENCODING; Node removes NODE_CHANNEL_FD itself).\n * MIRRORED from `@cohorte/security/contract/builtin.ts`, which this package may not import; a test of that package\n * asserts that the two copies are equal.\n */\nexport const OS_INJECTED_ENV: Readonly<Record<string, readonly string[]>> = Object.freeze({\n darwin: Object.freeze(['__CF_USER_TEXT_ENCODING']),\n});\n\n/** What the parent knows BEFORE the child speaks, and holds the claim against. */\nexport interface AttestationExpectation {\n engineVersion: string;\n /** the grant: `SpawnRequest.tools[].tool` */\n activeTools: readonly string[];\n effectiveSystemPromptSha256: Sha256;\n auth: { provider: string; mode: AuthMode; allowApiKey: boolean };\n /** the requested model and `AuthRequirement.baseUrl` */\n effective: { provider: string; model: string; baseUrl: string };\n sessionFile: string;\n /** every NAME the parent put into the child's env: `sandbox.env.allow` ∪ the keys of `sandbox.env.set` */\n envAllow: readonly string[];\n /** the parent's `process.platform` */\n platform: string;\n}\n\nexport interface AttestationMismatch {\n /** a dotted member of the attestation: 'activeTools', 'effective.baseUrl', 'hooks.guardFetchInstalled'… */\n field: string;\n expected: string;\n got: string;\n}\n\nexport function attestationExpectation(\n request: SpawnRequest,\n engine: Pick<EngineSettings, 'expectedEngineVersion' | 'sessionFile'>,\n effectiveSystemPromptSha256: Sha256,\n platform: string,\n): AttestationExpectation {\n const { provider, mode, allowApiKey, baseUrl } = request.auth;\n return {\n engineVersion: engine.expectedEngineVersion,\n activeTools: request.tools.map((grant) => grant.tool),\n effectiveSystemPromptSha256,\n auth: { provider, mode, allowApiKey },\n effective: { provider: request.model.provider, model: request.model.model, baseUrl },\n sessionFile: engine.sessionFile,\n envAllow: [...request.sandbox.env.allow, ...Object.keys(request.sandbox.env.set)],\n platform,\n };\n}\n\nconst list = (names: readonly string[]): string => JSON.stringify([...names].sort());\n\n/** Empty = the claim is an Attestation and matches. The parent refuses the spawn on ANY entry. */\nexport function diffAttestation(expected: AttestationExpectation, got: AttestationClaim): AttestationMismatch[] {\n const mismatches: AttestationMismatch[] = [];\n const same = (field: string, want: string | number | boolean, have: string | number | boolean): void => {\n if (want !== have) mismatches.push({ field, expected: String(want), got: String(have) });\n };\n\n same('hostProtocol', HOST_PROTOCOL, got.hostProtocol);\n same('engine.version', expected.engineVersion, got.engine.version);\n const strays = Object.entries(got.engine.packageVersions).filter(([, version]) => version !== got.engine.version);\n if (strays.length > 0)\n mismatches.push({\n field: 'engine.packageVersions',\n expected: `every package at ${got.engine.version}`,\n got: list(strays.map(([name, version]) => `${name}@${version}`)),\n });\n\n if (list(expected.activeTools) !== list(got.activeTools) || got.activeTools.length !== expected.activeTools.length)\n mismatches.push({ field: 'activeTools', expected: list(expected.activeTools), got: list(got.activeTools) });\n\n same('effectiveSystemPromptSha256', expected.effectiveSystemPromptSha256, got.effectiveSystemPromptSha256);\n same('systemPromptPrefixOk', true, got.systemPromptPrefixOk);\n same('extensionsLoaded', 0, got.extensionsLoaded);\n same('extensionErrors', 0, got.extensionErrors);\n same('modelFallback', false, got.modelFallback);\n\n same('auth.provider', expected.auth.provider, got.auth.provider);\n if (expected.auth.mode === 'subscription') {\n same('auth.type', 'oauth', got.auth.type);\n same('auth.subscription', true, got.auth.subscription);\n } else {\n same('auth.type', 'api_key', got.auth.type);\n }\n // in subscription mode the key is already flagged above: one defect, one entry per field\n if (got.auth.type === 'api_key' && !expected.auth.allowApiKey && expected.auth.mode !== 'subscription')\n mismatches.push({ field: 'auth.type', expected: 'no API key without an explicit opt-in', got: 'api_key' });\n\n same('effective.provider', expected.effective.provider, got.effective.provider);\n same('effective.model', expected.effective.model, got.effective.model);\n same('effective.baseUrl', expected.effective.baseUrl, got.effective.baseUrl);\n\n same('settings.compaction', false, got.settings.compaction);\n same('settings.agentRetry', false, got.settings.agentRetry);\n same('settings.providerMaxRetries', 0, got.settings.providerMaxRetries);\n same('settings.transport', 'sse', got.settings.transport);\n for (const [hook, installed] of Object.entries(got.hooks)) same(`hooks.${hook}`, true, installed);\n\n same('sessionFile', expected.sessionFile, got.sessionFile);\n same('platform', expected.platform, got.platform);\n const visible = new Set([...expected.envAllow, ...(OS_INJECTED_ENV[expected.platform] ?? [])]);\n const foreign = got.envKeys.filter((name) => !visible.has(name));\n if (foreign.length > 0)\n mismatches.push({ field: 'envKeys', expected: `a subset of ${list([...visible])}`, got: list(foreign) });\n\n return mismatches;\n}\n","// ONE transport interface, two codecs (PLAN F-6, DESIGN 3.2): the Node 'ipc' channel — what the spike executed,\n// including under sandbox-exec — and LF-delimited JSON over fd 3 (parent -> child) / fd 4 (child -> parent), the\n// drop-in alternate for a sandbox backend that cannot pass the IPC fd. The frame schema is the same on both.\nimport type { ChildProcess, StdioOptions } from 'node:child_process';\nimport type { Readable, Writable } from 'node:stream';\nimport { err, type Result } from '@cohorte/base';\nimport {\n type ChildFrame,\n decodeFrame,\n encodeFrame,\n type FrameRejection,\n MAX_FRAME_CHARS,\n type ParentFrame,\n} from '../protocol.ts';\n\nexport type TransportKind = 'ipc' | 'fd';\n\nexport interface FrameTransport {\n /** Resolves once the frame was handed to the channel; `false` when the channel is gone. Never rejects. */\n send(frame: ParentFrame): Promise<boolean>;\n /** Every inbound message, decoded: a frame or a rejection. One listener. */\n onFrame(listener: (decoded: Result<ChildFrame, FrameRejection>) => void): void;\n /** The peer closed the channel (`disconnect` or fd EOF): it died, or it is hostile. */\n onClose(listener: () => void): void;\n close(): void;\n}\n\nexport function stdioFor(kind: TransportKind): StdioOptions {\n // stdout and stderr are PIPES into the parent, never a raw file (DESIGN 3.2, I7).\n return kind === 'ipc' ? ['ignore', 'pipe', 'pipe', 'ipc'] : ['ignore', 'pipe', 'pipe', 'pipe', 'pipe'];\n}\n\nfunction ipcTransport(child: ChildProcess): FrameTransport {\n return {\n send: (frame) =>\n new Promise((resolve) => {\n if (!child.connected) return resolve(false);\n try {\n child.send(encodeFrame(frame, 'ipc') as object, (error) => resolve(error === null));\n } catch {\n resolve(false);\n }\n }),\n onFrame: (listener) => void child.on('message', (raw) => listener(decodeFrame('child', raw, 'ipc'))),\n onClose: (listener) => void child.once('disconnect', listener),\n close: () => {\n if (child.connected) child.disconnect();\n },\n };\n}\n\nfunction fdTransport(child: ChildProcess): FrameTransport {\n const toChild = child.stdio[3] as Writable | null | undefined;\n const fromChild = child.stdio[4] as Readable | null | undefined;\n if (!toChild || !fromChild)\n throw new TypeError('fd transport: the child was not spawned with fd 3 and fd 4 as pipes');\n toChild.on('error', () => {});\n return {\n send: (frame) =>\n new Promise((resolve) => {\n if (toChild.destroyed || !toChild.writable) return resolve(false);\n toChild.write(encodeFrame(frame, 'lf'), (error) => resolve(error === null || error === undefined));\n }),\n onFrame: (listener) => {\n let buffer = '';\n let overflow = false;\n fromChild.setEncoding('utf8');\n fromChild.on('data', (chunk: string) => {\n buffer += chunk;\n for (let end = buffer.indexOf('\\n'); end !== -1; end = buffer.indexOf('\\n')) {\n const line = buffer.slice(0, end);\n buffer = buffer.slice(end + 1);\n if (overflow) overflow = false;\n else if (line.length > 0) listener(decodeFrame('child', line, 'lf'));\n }\n // A line that never ends is refused once, then dropped up to its end: it is never buffered whole.\n if (buffer.length > MAX_FRAME_CHARS) {\n if (!overflow)\n listener(err({ reason: 'too-large', detail: `a line of more than ${MAX_FRAME_CHARS} characters` }));\n overflow = true;\n buffer = '';\n }\n });\n },\n onClose: (listener) => {\n fromChild.once('end', listener);\n fromChild.once('error', listener);\n },\n close: () => {\n toChild.destroy();\n fromChild.destroy();\n },\n };\n}\n\nexport function transportFor(kind: TransportKind, child: ChildProcess): FrameTransport {\n return kind === 'ipc' ? ipcTransport(child) : fdTransport(child);\n}\n","// One agent incarnation = one child process + the protocol engine that drives it (DESIGN 3.2, 3.5). Everything the\n// child says is untrusted: frames are schema-checked by `decodeFrame`, texts are sealed before they become an event\n// or a log line, and the exit cause is the one THIS side recorded before acting, never the engine's stop reason.\nimport { type ChildProcess, execFile, spawn } from 'node:child_process';\nimport { createWriteStream, type WriteStream } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport {\n CohorteError,\n type ErrorInfo,\n errorOf,\n type IsoInstant,\n type JsonValue,\n type Result,\n type SealedText,\n type Sha256,\n type ToolCallId,\n toErrorInfo,\n} from '@cohorte/base';\nimport {\n type AgentExit,\n type AgentStopCause,\n type IsolationReport,\n RUNTIME_EVENT_TYPES,\n type RuntimeAgentHandle,\n type RuntimeEvent,\n type RuntimeEventOf,\n type RuntimeEventType,\n type RuntimeHostBindings,\n type RuntimeMessage,\n type RuntimeSnapshot,\n type RuntimeToolCall,\n type RuntimeToolResult,\n type SpawnRequest,\n type UsageTotals,\n} from '@cohorte/runtime-contract';\nimport { attestationError, processExitError, protocolViolation } from '../classify/host.ts';\nimport { classify } from '../classify/index.ts';\nimport {\n attestationExpectation,\n type ChildFrame,\n diffAttestation,\n type EngineSettings,\n type ErrorSignal,\n type FrameRejection,\n type HostEvent,\n type ParentFrame,\n} from '../protocol.ts';\nimport type { ModelBoundaryMode } from './capabilities.ts';\nimport { drainChildOutput, newOutputBudget } from './output.ts';\nimport { type FrameTransport, stdioFor, type TransportKind, transportFor } from './transport.ts';\n\nexport interface ParentTimings {\n /** spawn -> `hello` */\n helloMs: number;\n /** `init` -> `ready` */\n readyMs: number;\n /** the child's heartbeat period; three missed periods = a hang (DESIGN 3.2) */\n heartbeatMs: number;\n /** `abort` -> `settled`, before SIGTERM goes to the process group */\n abortGraceMs: number;\n /** SIGTERM -> SIGKILL */\n termGraceMs: number;\n /** `settled` -> the process is gone by itself */\n exitGraceMs: number;\n /** a `send` or `inspect` frame -> its `response` */\n responseMs: number;\n}\nexport const DEFAULT_TIMINGS: ParentTimings = Object.freeze({\n helloMs: 10_000,\n readyMs: 30_000,\n heartbeatMs: 5_000,\n abortGraceMs: 5_000,\n termGraceMs: 2_000,\n exitGraceMs: 2_000,\n responseMs: 5_000,\n});\n\nexport const WIRE_LOG_FILE = 'frames.ndjson';\nexport const NONCE_ARG = '--cohorte-nonce=';\n\nexport interface Sealer {\n text(text: string): SealedText;\n json<T extends JsonValue>(value: T): T;\n}\n\nexport interface SessionContext {\n bindings: RuntimeHostBindings;\n seal: Sealer;\n timings: ParentTimings;\n transport: TransportKind;\n modelBoundary: ModelBoundaryMode;\n runtimeId: string;\n emit(event: RuntimeEvent): void;\n diagnostics: Readonly<Record<string, string>>;\n}\n\nexport interface SpawnPlan {\n request: SpawnRequest;\n stateDir: string;\n command: { file: string; args: string[] };\n nonce: string;\n env: Record<string, string>;\n /** `request` with the env the child REALLY gets: what the attested names are held against. */\n attestedRequest: SpawnRequest;\n engine: EngineSettings;\n expectedEffectivePromptSha256: Sha256;\n isolation: IsolationReport;\n taskText: string;\n noteText: string | undefined;\n}\n\ntype Cause = { outcome: AgentExit['outcome']; stop: AgentStopCause; error?: ErrorInfo };\ntype ToolCallFrame = Extract<ChildFrame, { t: 'tool.call' }>;\ntype ResponseFrame = Extract<ChildFrame, { t: 'response' }>;\ntype ProviderRequestFrame = Extract<ChildFrame, { t: 'provider.request' }>;\n\n// Events only THIS side may author: a child that sends one is ignored, with a trace.\nconst PARENT_OWNED: ReadonlySet<RuntimeEventType> = new Set([\n 'agent.spawned',\n 'agent.started',\n 'agent.paused',\n 'agent.resumed',\n 'agent.exited',\n 'tool.call.requested',\n 'tool.call.delivered',\n 'tool.call.progress',\n]);\n\nconst zeroUsage = (): UsageTotals => ({\n tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n modelRequests: 0,\n toolCalls: 0,\n turns: 0,\n wallClockMs: 0,\n});\n\n/** The OS start time of a process: orphan recovery never trusts a bare pid (DESIGN 3.2). */\nasync function processStartToken(pid: number): Promise<string> {\n if (process.platform === 'linux') {\n const stat = await readFile(`/proc/${pid}/stat`, 'utf8').catch(() => '');\n const afterName = stat.slice(stat.lastIndexOf(')') + 2).split(' ');\n if (afterName[19]) return `jiffies:${afterName[19]}`;\n }\n return new Promise((resolve) => {\n execFile('/bin/ps', ['-o', 'lstart=', '-p', String(pid)], { timeout: 2_000 }, (error, stdout) =>\n resolve(error || !stdout.trim() ? 'unknown' : stdout.trim()),\n );\n });\n}\n\nexport class AgentSession {\n readonly request: SpawnRequest;\n readonly done: Promise<void>;\n readonly #exit: Promise<AgentExit>;\n #handle: RuntimeAgentHandle | undefined;\n readonly #ctx: SessionContext;\n readonly #plan: SpawnPlan;\n readonly #child: ChildProcess;\n readonly #transport: FrameTransport;\n readonly #wireLog: WriteStream;\n readonly #processGone: Promise<void>;\n #gone = false;\n #phase: 'hello' | 'ready' | 'running' | 'over' = 'hello';\n #handshake: { resolve: () => void; reject: (error: CohorteError) => void } | undefined;\n #handshakeTimer: NodeJS.Timeout | undefined;\n #seq = 0;\n #lastOrdinal = 0;\n #requestSerial = 0;\n #cause: Cause | undefined;\n #terminated = false;\n #paused = false;\n #pausedAt: 'tool-boundary' | 'model-boundary' | undefined;\n #turn = 0;\n readonly #usage = zeroUsage();\n readonly #startedMs: number;\n #lastHeartbeatMs: number;\n #lastHeartbeatAt: IsoInstant | undefined;\n #rssMb: number | undefined;\n #effectiveModel: RuntimeSnapshot['effectiveModel'];\n #sessionId = '';\n #engineVersion = '';\n readonly #pending = new Map<\n ToolCallId,\n { controller: AbortController; engineToolCallId: string; startedMs: number }\n >();\n readonly #queued: ToolCallFrame[] = [];\n readonly #providerRequests = new Map<string, ProviderRequestFrame>();\n readonly #responseHeaders = new Map<string, Record<string, string>>();\n #lastRequestId: string | undefined;\n readonly #responses = new Map<string, (frame: ResponseFrame | undefined) => void>();\n readonly #timers = new Set<NodeJS.Timeout>();\n #settleExit: (exit: AgentExit) => void = () => {};\n #settleDone: () => void = () => {};\n\n private constructor(ctx: SessionContext, plan: SpawnPlan) {\n this.#ctx = ctx;\n this.#plan = plan;\n this.request = plan.request;\n this.#startedMs = ctx.bindings.clock.monotonicMs();\n this.#lastHeartbeatMs = this.#startedMs;\n this.done = new Promise((resolve) => {\n this.#settleDone = resolve;\n });\n this.#exit = new Promise((resolve) => {\n this.#settleExit = resolve;\n });\n this.#wireLog = createWriteStream(join(plan.stateDir, WIRE_LOG_FILE), { flags: 'a' });\n this.#wireLog.on('error', () => {});\n this.#child = spawn(plan.command.file, plan.command.args, {\n cwd: plan.stateDir,\n env: plan.env,\n stdio: stdioFor(ctx.transport),\n serialization: 'json',\n // Its own process group: the ladder signals the whole tree (DESIGN 3.5).\n detached: true,\n });\n this.#processGone = new Promise((resolve) => {\n const gone = (): void => {\n this.#gone = true;\n resolve();\n };\n this.#child.once('exit', gone);\n this.#child.once('error', (error) => {\n gone();\n void this.#conclude(\n { outcome: 'crashed', stop: 'process-exit', error: processExitError('spawn-failed', error.name) },\n { clean: false },\n );\n });\n });\n const budget = newOutputBudget();\n const write = (line: string, stream: 'stdout' | 'stderr'): void =>\n this.#log(stream === 'stderr' ? 'warn' : 'info', line, { stream, source: 'agent-process' });\n if (this.#child.stdout) drainChildOutput(this.#child.stdout, 'stdout', budget, write);\n if (this.#child.stderr) drainChildOutput(this.#child.stderr, 'stderr', budget, write);\n this.#transport = transportFor(ctx.transport, this.#child);\n this.#transport.onFrame((decoded) => this.#onDecoded(decoded));\n this.#transport.onClose(() => this.#onChannelClosed());\n }\n\n /** Resolves once the child has attested what was asked and received its prompt; rejects (child reaped) otherwise. */\n static async start(ctx: SessionContext, plan: SpawnPlan): Promise<AgentSession> {\n const session = new AgentSession(ctx, plan);\n await session.#shakeHands();\n await session.#begin();\n return session;\n }\n\n get handle(): RuntimeAgentHandle {\n if (!this.#handle) throw new TypeError('AgentSession: no handle before the handshake');\n return this.#handle;\n }\n\n get over(): boolean {\n return this.#phase === 'over';\n }\n\n // ── handshake: hello(nonce) -> init -> ready(attestation) ──\n\n #shakeHands(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.#handshake = { resolve, reject };\n this.#armHandshakeTimer(this.#ctx.timings.helloMs, 'hello');\n });\n }\n\n #armHandshakeTimer(ms: number, awaited: string): void {\n clearTimeout(this.#handshakeTimer);\n this.#handshakeTimer = setTimeout(\n () => this.#block(protocolViolation('handshake-timeout', `no ${awaited} frame within ${ms} ms`)),\n ms,\n );\n }\n\n async #begin(): Promise<void> {\n const { request, taskText, noteText, isolation } = this.#plan;\n const { clock } = this.#ctx.bindings;\n const pid = this.#child.pid ?? 0;\n const startToken = await processStartToken(pid);\n // The child may have died while the start token was read: there is no agent then, and the spawn says so.\n if (this.over) throw new CohorteError(this.#cause?.error ?? processExitError('exit-without-settled'));\n this.#handle = Object.freeze({\n runId: request.runId,\n agentId: request.agentId,\n incarnation: request.incarnation,\n session: {\n runtime: this.#ctx.runtimeId,\n engineVersion: this.#engineVersion,\n sessionId: this.#sessionId,\n transcript: { path: this.#plan.engine.sessionFile, format: 'jsonl-v3' },\n },\n startedAt: clock.now(),\n process: { pid, pgid: pid, startToken },\n exit: this.#exit,\n });\n this.#emit('agent.spawned', {\n session: this.#handle.session,\n requestedModel: request.model,\n tools: request.tools.map((grant) => grant.tool),\n systemPromptSha256: request.systemPrompt.sha256,\n effectiveSystemPromptSha256: this.#plan.expectedEffectivePromptSha256,\n isolation,\n });\n this.#send({\n t: 'prompt',\n id: this.#nextId('prompt'),\n text: taskText,\n ...(noteText === undefined ? {} : { note: { text: noteText } }),\n });\n this.#emit('agent.started', { taskSha256: request.task.sha256 });\n this.#startWatchdogs();\n }\n\n #startWatchdogs(): void {\n const { timings, bindings } = this.#ctx;\n this.#lastHeartbeatMs = bindings.clock.monotonicMs();\n const watchdog = setInterval(() => {\n if (bindings.clock.monotonicMs() - this.#lastHeartbeatMs <= 3 * timings.heartbeatMs) return;\n this.#stop({ outcome: 'crashed', stop: 'process-exit', error: processExitError('heartbeat-lost') });\n }, timings.heartbeatMs);\n this.#timers.add(watchdog);\n const { maxWallClockMs } = this.request.budget;\n if (maxWallClockMs !== undefined)\n this.#timers.add(\n setTimeout(\n () => this.#breach(errorOf('timeout/agent', `the agent ran longer than ${maxWallClockMs} ms`)),\n Math.min(maxWallClockMs, 2 ** 31 - 1),\n ),\n );\n }\n\n // ── inbound ──\n\n #onDecoded(decoded: Result<ChildFrame, FrameRejection>): void {\n if (this.over) return;\n if (!decoded.ok) {\n this.#logWire('in', { rejected: decoded.error.reason, detail: decoded.error.detail });\n this.#block(protocolViolation('frame-schema', `${decoded.error.reason}: ${decoded.error.detail}`));\n return;\n }\n const frame = decoded.value;\n this.#logWire('in', { frame: frame as unknown as JsonValue });\n if (this.#phase === 'hello' || this.#phase === 'ready') this.#onHandshakeFrame(frame);\n else this.#onFrame(frame);\n }\n\n #onHandshakeFrame(frame: ChildFrame): void {\n if (frame.t === 'fatal') {\n void this.#conclude(\n { outcome: 'failed', stop: 'engine-error', error: this.#errorOfFatal(frame) },\n { clean: false },\n );\n return;\n }\n if (frame.t === 'heartbeat') return;\n if (this.#phase === 'hello' && frame.t === 'hello') {\n if (frame.nonce !== this.#plan.nonce) {\n this.#block(protocolViolation('nonce-mismatch', 'hello does not carry the nonce of this spawn'));\n return;\n }\n this.#phase = 'ready';\n this.#armHandshakeTimer(this.#ctx.timings.readyMs, 'ready');\n this.#send({\n t: 'init',\n v: 1,\n nonce: this.#plan.nonce,\n mode: 'agent',\n request: this.request,\n engine: this.#plan.engine,\n });\n return;\n }\n if (this.#phase === 'ready' && frame.t === 'ready') {\n const expected = attestationExpectation(\n this.#plan.attestedRequest,\n this.#plan.engine,\n this.#plan.expectedEffectivePromptSha256,\n process.platform,\n );\n const mismatches = diffAttestation(expected, frame.attestation);\n if (mismatches.length > 0) {\n // `got` is the CHILD's text, and the error escapes this side as a thrown `CohorteError`: it is sealed here,\n // like every other child-derived text (DESIGN 3.3). `expected` is the parent's own and stays as it is.\n this.#block(attestationError(mismatches.map((m) => ({ ...m, got: this.#ctx.seal.text(m.got) }))));\n return;\n }\n clearTimeout(this.#handshakeTimer);\n this.#sessionId = frame.attestation.sessionId;\n this.#engineVersion = frame.attestation.engine.version;\n this.#phase = 'running';\n this.#handshake?.resolve();\n this.#handshake = undefined;\n return;\n }\n this.#block(protocolViolation('unexpected-frame', `'${frame.t}' during the handshake`));\n }\n\n #onFrame(frame: ChildFrame): void {\n switch (frame.t) {\n case 'event': {\n this.#onEvent(frame.event);\n return;\n }\n case 'tool.call': {\n this.#onToolCall(frame);\n return;\n }\n case 'tool.call.abandoned':\n for (const entry of this.#pending.values())\n if (entry.engineToolCallId === frame.engineToolCallId) entry.controller.abort(frame.reason);\n return;\n case 'provider.request':\n this.#providerRequests.set(frame.requestId, frame);\n {\n this.#assertProviderRequest(frame);\n return;\n }\n case 'provider.response':\n this.#responseHeaders.set(frame.requestId, frame.headers);\n this.#lastRequestId = frame.requestId;\n return;\n case 'parked':\n if (this.#paused) this.#pausedAt = 'model-boundary';\n return;\n case 'heartbeat':\n this.#lastHeartbeatMs = this.#ctx.bindings.clock.monotonicMs();\n this.#lastHeartbeatAt = this.#ctx.bindings.clock.now();\n this.#rssMb = frame.rssMb;\n return;\n case 'response':\n this.#responses.get(frame.id)?.(frame);\n return;\n case 'settled': {\n const { outcome, stop, usage } = frame.exit;\n const error = frame.signal\n ? this.#classified(frame.signal)\n : stop === 'budget'\n ? errorOf('budget/unexpected', 'the engine stopped the agent on one of its budget limits')\n : undefined;\n void this.#conclude({ outcome, stop, ...(error ? { error } : {}) }, { clean: true, usage });\n return;\n }\n case 'fatal':\n void this.#conclude(\n { outcome: 'failed', stop: 'engine-error', error: this.#errorOfFatal(frame) },\n { clean: false },\n );\n return;\n default:\n this.#block(protocolViolation('unexpected-frame', `'${frame.t}' while an agent runs`));\n }\n }\n\n #onEvent(event: HostEvent): void {\n if (PARENT_OWNED.has(event.type)) {\n this.#emit('runtime.warning', {\n code: 'host-event-ignored',\n message: `the agent process sent '${event.type}', which only the host may author`,\n });\n return;\n }\n const { budget } = this.request;\n if (event.type === 'model.requested') {\n this.#usage.modelRequests += 1;\n this.#lastRequestId = event.data.requestId;\n } else if (event.type === 'agent.turn.started') {\n this.#turn = event.data.turn;\n } else if (event.type === 'agent.turn.completed') {\n this.#usage.turns = Math.max(this.#usage.turns, event.data.turn);\n } else if (event.type === 'model.responded') {\n const violation = this.#assertResponded(event.data);\n if (violation) {\n this.#block(violation);\n return;\n }\n this.#effectiveModel = event.data.effectiveModel;\n for (const key of ['input', 'output', 'cacheRead', 'cacheWrite', 'total'] as const)\n this.#usage.tokens[key] += event.data.usage[key];\n }\n this.#forward(event);\n\n // The belt (DESIGN 3.5): always on, whatever the child enforces itself.\n const { tokens } = this.#usage;\n if (budget.maxModelRequests !== undefined && this.#usage.modelRequests > budget.maxModelRequests)\n this.#breach(errorOf('budget/unexpected', `more than ${budget.maxModelRequests} model requests`));\n else if (budget.maxTurns !== undefined && this.#turn > budget.maxTurns)\n this.#breach(errorOf('budget/unexpected', `more than ${budget.maxTurns} turns`));\n else if (\n (budget.maxTotalTokens !== undefined && tokens.total > budget.maxTotalTokens) ||\n (budget.maxInputTokens !== undefined && tokens.input > budget.maxInputTokens) ||\n (budget.maxOutputTokens !== undefined && tokens.output > budget.maxOutputTokens)\n )\n this.#breach(errorOf('budget/tokens', 'the token budget of this incarnation is spent'));\n }\n\n #forward(event: HostEvent): void {\n // `type` and `data` travel together: the pair was validated as ONE member of the HostEvent union.\n const stamped = { ...this.#envelope(event.type, event.at), data: this.#ctx.seal.json(event.data as JsonValue) };\n this.#ctx.emit(stamped as unknown as RuntimeEvent);\n }\n\n // ── layer 5 (DESIGN 3.7): per-request evidence from the guard fetch, asserted HERE ──\n\n #assertProviderRequest(frame: ProviderRequestFrame): void {\n const { auth } = this.request;\n const problems: string[] = [];\n let pinnedOrigin = '';\n try {\n pinnedOrigin = new URL(auth.baseUrl).origin;\n } catch {\n problems.push('the pinned endpoint is not a URL');\n }\n if (frame.origin !== pinnedOrigin)\n problems.push('a model request left for another origin than the pinned endpoint');\n if (frame.refused) problems.push('the guard refused a model request');\n if (auth.mode === 'subscription' && frame.authScheme !== 'bearer-jwt')\n problems.push(`subscription mode sends a bearer token, the request carried '${frame.authScheme}'`);\n if (auth.mode === 'api' && frame.authScheme === 'none') problems.push('an api-mode request carried no credential');\n if (problems.length > 0)\n this.#block(\n errorOf('security/auth-mode-violation', problems.join('; '), { details: { requestId: frame.requestId } }),\n );\n }\n\n #assertResponded(data: RuntimeEventOf<'model.responded'>['data']): ErrorInfo | undefined {\n const { auth, model } = this.request;\n const mint = (message: string): ErrorInfo =>\n errorOf('security/auth-mode-violation', message, { details: { requestId: data.requestId } });\n // A request that really left the process has a status or an answer. Without the guard's frame for it, the only\n // evidence would be the child's own echo.\n const left = data.httpStatus !== undefined || data.error === undefined;\n if (left && !this.#providerRequests.has(data.requestId))\n return mint('a model request has no matching provider.request frame from the guard fetch');\n if (data.effectiveModel.provider !== model.provider || data.effectiveModel.model !== model.model)\n return mint('the model that answered is not the requested one');\n if (data.authMode !== auth.mode || data.authSource !== (auth.mode === 'subscription' ? 'oauth' : 'api-key'))\n return mint(`the request was not made in ${auth.mode} mode`);\n return undefined;\n }\n\n // ── tools (DESIGN 3.5) ──\n\n #onToolCall(frame: ToolCallFrame): void {\n if (frame.ordinal !== this.#lastOrdinal + 1) {\n this.#block(protocolViolation('ordinal-gap', `ordinal ${frame.ordinal} after ${this.#lastOrdinal}`));\n return;\n }\n this.#lastOrdinal = frame.ordinal;\n if (!this.request.tools.some((grant) => grant.tool === frame.tool)) {\n this.#block(protocolViolation('unknown-tool', 'the agent process proposed a tool that was not granted'));\n return;\n }\n this.#usage.toolCalls += 1;\n const { maxToolCalls } = this.request.budget;\n if (maxToolCalls !== undefined && this.#usage.toolCalls > maxToolCalls)\n this.#breach(errorOf('budget/tool-calls-exhausted', `more than ${maxToolCalls} tool calls`));\n if (this.#cause || this.#terminated) {\n this.#refuse(frame);\n return;\n }\n if (this.#paused) this.#queued.push(frame);\n else this.#dispatch(frame);\n }\n\n #toolCallId(frame: ToolCallFrame): ToolCallId {\n return `tc_${this.request.incarnation}_${frame.ordinal}` as ToolCallId;\n }\n\n /** A denied tool alone lets the model keep trying: the answer ends the loop, and `abort` is already on its way. */\n #refuse(frame: ToolCallFrame): void {\n this.#send({\n t: 'tool.result',\n toolCallId: this.#toolCallId(frame),\n isError: true,\n content: [{ type: 'text', text: this.#ctx.seal.text('[cohorte] this agent was stopped by its host') }],\n terminate: true,\n });\n }\n\n #dispatch(frame: ToolCallFrame): void {\n const { runId, agentId, incarnation } = this.request;\n const toolCallId = this.#toolCallId(frame);\n const call: RuntimeToolCall = {\n runId,\n agentId,\n incarnation,\n toolCallId,\n engineToolCallId: frame.engineToolCallId,\n ordinal: frame.ordinal,\n tool: frame.tool,\n input: frame.input,\n };\n // The event is sealed; the host gets the input as the model produced it and re-validates it strictly.\n this.#emit('tool.call.requested', { call: { ...call, input: this.#ctx.seal.json(frame.input) } });\n const controller = new AbortController();\n const startedMs = this.#ctx.bindings.clock.monotonicMs();\n this.#pending.set(toolCallId, { controller, engineToolCallId: frame.engineToolCallId, startedMs });\n const context = {\n signal: controller.signal,\n progress: (update: { text?: string; bytes?: number }): void => {\n if (this.#pending.has(toolCallId))\n this.#emit('tool.call.progress', { toolCallId, update: this.#ctx.seal.json(update) });\n },\n };\n let answer: Promise<RuntimeToolResult>;\n try {\n answer = this.#ctx.bindings.toolHost.handleToolCall(call, context);\n } catch (thrown) {\n answer = Promise.reject(thrown);\n }\n void answer.then(\n (result) => this.#deliver(toolCallId, result),\n (thrown: unknown) => {\n // A rejection is a host bug (DESIGN 2.2.2): the call is answered as an error and the agent fails.\n if (!this.#pending.delete(toolCallId) || this.over) return;\n this.#refuse(frame);\n this.#stop({\n outcome: 'failed',\n stop: 'host-terminated',\n error: toErrorInfo(thrown, { code: 'tool-terminal/unexpected', class: 'tool-terminal' }),\n });\n },\n );\n }\n\n #deliver(toolCallId: ToolCallId, result: RuntimeToolResult): void {\n const entry = this.#pending.get(toolCallId);\n if (!entry || this.over) return;\n this.#pending.delete(toolCallId);\n // Settled as aborted by the ladder: the child has abandoned the call, nothing is delivered.\n if (entry.controller.signal.aborted) return;\n const terminate = result.terminate === true;\n this.#send({\n t: 'tool.result',\n toolCallId,\n isError: result.isError,\n content: result.content,\n terminate,\n ...(result.resultRef === undefined ? {} : { resultRef: result.resultRef }),\n });\n // The first accepted terminal result is final, even when the model batched it with another call [X].\n this.#terminated ||= terminate;\n // Emitted in the same tick as the hand-over to the channel: nothing the child does with the result comes first.\n this.#emit('tool.call.delivered', {\n toolCallId,\n isError: result.isError,\n terminate,\n waitedMs: Math.max(0, this.#ctx.bindings.clock.monotonicMs() - entry.startedMs),\n });\n }\n\n #abortPending(reason: string): void {\n for (const { controller } of this.#pending.values()) controller.abort(reason);\n }\n\n // ── commands ──\n\n async send(message: RuntimeMessage): Promise<void> {\n if (this.over) throw new CohorteError(errorOf('conflict/not-running', 'the agent has exited'));\n const id = this.#nextId('send');\n const text = message.kind === 'host-note' ? `[cohorte] ${message.text}` : message.text;\n const response = await this.#ask(\n { t: 'send', id, messageId: message.messageId, text, delivery: message.delivery },\n id,\n );\n if (!response?.ok)\n throw new CohorteError(\n response?.error\n ? this.#sealedInfo(response.error)\n : errorOf('timeout/agent', 'the agent process did not acknowledge the message'),\n );\n }\n\n pause(): void {\n if (this.over || this.#paused) return;\n // Tool boundary, always available: from now on no `tool.call` becomes a handleToolCall. An in-flight host\n // operation completes and its result is delivered.\n this.#paused = true;\n this.#pausedAt = 'tool-boundary';\n this.#send(this.#ctx.modelBoundary === 'park' ? { t: 'pause' } : { t: 'stop-after-turn', reason: 'pause' });\n this.#emit('agent.paused', { at: 'tool-boundary' });\n }\n\n resume(): void {\n if (this.over || !this.#paused) return;\n this.#paused = false;\n this.#pausedAt = undefined;\n // A child parked by `stop-after-turn` re-prompts itself with the `[cohorte] continue` note (DESIGN 3.5).\n this.#send({ t: 'resume' });\n this.#emit('agent.resumed', {});\n for (const frame of this.#queued.splice(0)) this.#dispatch(frame);\n }\n\n /** The ladder (DESIGN 3.5). Resolves when the incarnation is over. */\n cancel(reason: string): Promise<void> {\n this.#stop({ outcome: 'cancelled', stop: 'cancelled' }, reason);\n return this.done;\n }\n\n async inspect(): Promise<RuntimeSnapshot> {\n const { request } = this;\n let child: JsonValue | undefined;\n if (this.#phase === 'running') {\n const id = this.#nextId('inspect');\n const response = await this.#ask({ t: 'inspect', id }, id, Math.min(this.#ctx.timings.responseMs, 1_000));\n if (response?.ok && response.data !== undefined) child = this.#ctx.seal.json(response.data);\n }\n const state: RuntimeSnapshot['state'] = this.over\n ? 'exited'\n : this.#phase !== 'running'\n ? 'starting'\n : this.#paused\n ? 'paused'\n : this.#cause\n ? 'settling'\n : this.#pending.size > 0\n ? 'awaiting-tool'\n : 'running';\n return {\n runId: request.runId,\n agentId: request.agentId,\n incarnation: request.incarnation,\n state,\n ...(this.#paused && this.#pausedAt ? { pausedAt: this.#pausedAt } : {}),\n turn: this.#turn,\n pendingToolCalls: [...this.#pending.keys()],\n requestedModel: request.model,\n ...(this.#effectiveModel ? { effectiveModel: this.#effectiveModel, authMode: request.auth.mode } : {}),\n usage: this.#usageNow(),\n session: this.handle.session,\n lastSeq: Math.max(0, this.#seq - 1),\n diagnostics: {\n ...this.#ctx.diagnostics,\n pid: this.#child.pid ?? 0,\n transport: this.#ctx.transport,\n ...(this.#rssMb === undefined ? {} : { rssMb: this.#rssMb }),\n ...(this.#lastHeartbeatAt === undefined ? {} : { lastHeartbeatAt: this.#lastHeartbeatAt }),\n ...(child === undefined ? {} : { child }),\n },\n };\n }\n\n // ── stopping ──\n\n #breach(error: ErrorInfo): void {\n this.#stop({ outcome: 'failed', stop: 'budget', error });\n }\n\n /** Records the typed cause BEFORE acting, settles pending calls FIRST, then walks the ladder. */\n #stop(cause: Cause, reason: string = cause.stop): void {\n if (this.over || this.#cause) return;\n this.#cause = cause;\n if (this.#phase !== 'running') {\n this.#kill();\n return;\n }\n // A gate that never releases would make the engine's abort hang: pending calls are settled as aborted first.\n this.#abortPending(reason);\n for (const frame of this.#queued.splice(0)) this.#refuse(frame);\n this.#send({ t: 'abort', id: this.#nextId('abort'), reason });\n const { abortGraceMs, termGraceMs } = this.#ctx.timings;\n this.#timers.add(\n setTimeout(() => {\n this.#signalGroup('SIGTERM');\n this.#timers.add(setTimeout(() => this.#signalGroup('SIGKILL'), termGraceMs));\n }, abortGraceMs),\n );\n }\n\n /** A child that broke the protocol, the attestation or the auth mode gets no courtesy. */\n #block(error: ErrorInfo): void {\n if (this.over) return;\n this.#cause = { outcome: 'failed', stop: 'host-terminated', error };\n this.#log('error', `${error.code}: ${error.message}`, { source: 'runtime-parent' });\n this.#kill();\n }\n\n #kill(): void {\n this.#signalGroup('SIGKILL');\n void this.#conclude(this.#cause ?? { outcome: 'crashed', stop: 'process-exit' }, { clean: false });\n }\n\n #signalGroup(signal: NodeJS.Signals): void {\n const pid = this.#child.pid;\n if (pid === undefined) return;\n try {\n process.kill(-pid, signal);\n } catch {\n // The group is already gone.\n }\n }\n\n #onChannelClosed(): void {\n if (this.over) return;\n // `disconnect` (or fd EOF) means the peer died; a live child without a channel is of no use, and not trusted.\n void this.#conclude(\n {\n outcome: 'crashed',\n stop: 'process-exit',\n error: processExitError(this.#gone ? 'exit-without-settled' : 'disconnect'),\n },\n { clean: false },\n );\n }\n\n async #conclude(draft: Cause, how: { clean: boolean; usage?: UsageTotals }): Promise<void> {\n if (this.over) return;\n const startedUp = this.#phase === 'running';\n this.#phase = 'over';\n clearTimeout(this.#handshakeTimer);\n for (const timer of this.#timers) clearTimeout(timer);\n this.#timers.clear();\n this.#abortPending('the agent exited');\n for (const release of this.#responses.values()) release(undefined);\n const final = this.#cause ?? draft;\n // The engine's own counters are worth having only when THIS side recorded no cause of its own; a breach, a block\n // or a ladder walk makes the parent's counters the authoritative ones. Decided here, while `#cause` still means\n // \"the parent had a cause\": the line below assigns it in every case.\n const engineUsage = this.#cause ? undefined : how.usage;\n\n if (how.clean) void this.#transport.send(this.#logged({ t: 'shutdown' }));\n await this.#reap(how.clean);\n this.#transport.close();\n await new Promise<void>((resolve) => this.#wireLog.end(resolve));\n\n this.#cause = final;\n if (!startedUp || !this.#handle) {\n this.#handshake?.reject(new CohorteError(final.error ?? processExitError('spawn-failed')));\n this.#handshake = undefined;\n this.#settleDone();\n return;\n }\n const usage = engineUsage ?? this.#usageNow();\n const exit: AgentExit = {\n outcome: final.outcome,\n stop: final.stop,\n ...(final.error ? { error: final.error } : {}),\n usage,\n lastSeq: this.#seq,\n };\n this.#emit('agent.exited', exit);\n this.#settleExit(exit);\n this.#settleDone();\n }\n\n /** After `settled` the child leaves by itself; anything else, and whatever it left behind, is signalled away. */\n async #reap(clean: boolean): Promise<void> {\n const { exitGraceMs, termGraceMs } = this.#ctx.timings;\n const goneWithin = (ms: number): Promise<boolean> =>\n new Promise((resolve) => {\n const timer = setTimeout(() => resolve(false), ms);\n void this.#processGone.then(() => {\n clearTimeout(timer);\n resolve(true);\n });\n });\n if (clean && (this.#gone || (await goneWithin(exitGraceMs)))) return;\n if (!this.#gone && clean) {\n this.#signalGroup('SIGTERM');\n await goneWithin(termGraceMs);\n }\n // Also the sweep of descendants that outlived the leader (the brain has none by design; a hostile one might).\n this.#signalGroup('SIGKILL');\n if (this.#child.pid !== undefined) await this.#processGone;\n }\n\n // ── helpers ──\n\n #usageNow(): UsageTotals {\n return {\n ...this.#usage,\n tokens: { ...this.#usage.tokens },\n wallClockMs: Math.max(0, Math.round(this.#ctx.bindings.clock.monotonicMs() - this.#startedMs)),\n };\n }\n\n #classified(signal: ErrorSignal): ErrorInfo {\n const headers = this.#lastRequestId === undefined ? undefined : this.#responseHeaders.get(this.#lastRequestId);\n const info = classify({ ...signal, text: this.#ctx.seal.text(signal.text) }, headers ? { headers } : {});\n // DESIGN 3.8, fifth row: an error the table has no row for fails towards the human AND leaves a trace, so that\n // the table gets its row. `classify` is pure, so the trace is left here, at its only call site. Before the agent\n // is running the host has been told of no incarnation (`agent.spawned` is not out, and the spawn is about to\n // reject), so the trace is a LOG line there: a durable event must never name an agent that never started.\n if (info.details?.unclassified === true) {\n const message = `the error table has no row for this signal (${signal.modelsErrorCode ?? 'no engine code'}, ${signal.origin})`;\n if (this.#phase === 'running') this.#emit('runtime.warning', { code: 'error-unclassified', message });\n else this.#log('warn', message, { source: 'runtime-parent', code: 'error-unclassified' });\n }\n return info;\n }\n\n #errorOfFatal(frame: Extract<ChildFrame, { t: 'fatal' }>): ErrorInfo {\n return frame.signal ? this.#classified(frame.signal) : this.#sealedInfo(frame.error);\n }\n\n /** The child's own typed error, re-minted: it keeps its class, its text is sealed (I2, I7). */\n #sealedInfo(info: ErrorInfo): ErrorInfo {\n const sealed = this.#ctx.seal.json(info as unknown as JsonValue) as unknown as ErrorInfo;\n return toErrorInfo(new CohorteError(sealed), { code: 'configuration/engine-init', class: 'configuration' });\n }\n\n #ask(frame: ParentFrame, id: string, timeoutMs = this.#ctx.timings.responseMs): Promise<ResponseFrame | undefined> {\n return new Promise((resolve) => {\n const timer = setTimeout(() => settle(undefined), timeoutMs);\n this.#timers.add(timer);\n const settle = (response: ResponseFrame | undefined): void => {\n clearTimeout(timer);\n this.#timers.delete(timer);\n this.#responses.delete(id);\n resolve(response);\n };\n this.#responses.set(id, settle);\n this.#send(frame);\n });\n }\n\n #nextId(kind: string): string {\n this.#requestSerial += 1;\n return `${kind}_${this.#requestSerial}`;\n }\n\n #send(frame: ParentFrame): void {\n void this.#transport.send(this.#logged(frame));\n }\n\n #logged(frame: ParentFrame): ParentFrame {\n this.#logWire('out', { frame: frame as unknown as JsonValue });\n return frame;\n }\n\n /** The host-protocol wire log = the replay fixture of the fake brain. Sealed like everything that reaches a disk. */\n #logWire(dir: 'in' | 'out', entry: { [member: string]: JsonValue }): void {\n if (this.#wireLog.writableEnded) return;\n const line = JSON.stringify(this.#ctx.seal.json({ at: this.#ctx.bindings.clock.now(), dir, ...entry }));\n this.#wireLog.write(`${line}\\n`);\n }\n\n #log(level: 'debug' | 'info' | 'warn' | 'error', text: string, fields: Record<string, JsonValue>): void {\n const { runId, agentId, incarnation } = this.request;\n this.#ctx.bindings.log(level, this.#ctx.seal.text(text), { runId, agentId, incarnation, ...fields });\n }\n\n #envelope<T extends RuntimeEventType>(type: T, at: IsoInstant = this.#ctx.bindings.clock.now()) {\n const { runId, agentId, incarnation } = this.request;\n const seq = this.#seq;\n this.#seq += 1;\n return { type, durability: RUNTIME_EVENT_TYPES[type].durability, runId, agentId, incarnation, seq, at };\n }\n\n #emit<T extends RuntimeEventType>(type: T, data: RuntimeEventOf<T>['data']): void {\n this.#ctx.emit({ ...this.#envelope(type), data } as unknown as RuntimeEvent);\n }\n}\n","// The three auth modes of the child (DESIGN 3.3): status, login, logout, all on the ENGINE's credential store (R7).\n// This side never sees a token: statuses are secret-free by schema, every text is sealed, and the child's stdout and\n// stderr go line by line through the SAME sealed logger as an agent's (DESIGN 3.2, I7) — login is exactly the path\n// where the engine prints refresh or login error bodies that hold token material. `AgentRuntimeProvider.login` /\n// `authStatus` / `logout` get no `RuntimeHostBindings`, so the log port is an option of the provider and the pipes are\n// drained (and dropped) when the composition root binds none (docs/v3/requests/U1.07.md R1).\n\nimport { spawn } from 'node:child_process';\nimport { randomBytes } from 'node:crypto';\nimport { mkdir } from 'node:fs/promises';\nimport { CohorteError, type ErrorInfo, errorOf, type JsonValue, toErrorInfo } from '@cohorte/base';\nimport type { LoginInteraction, ProviderAuthStatus, RuntimeHostBindings } from '@cohorte/runtime-contract';\nimport { processExitError, protocolViolation } from '../classify/host.ts';\nimport { classify } from '../classify/index.ts';\nimport type { ChildFrame, ParentFrame } from '../protocol.ts';\nimport { childEnv, fixedChildEnv } from './env.ts';\nimport { drainChildOutput, newOutputBudget } from './output.ts';\nimport { NONCE_ARG, type ParentTimings, type Sealer } from './session.ts';\nimport { stdioFor, type TransportKind, transportFor } from './transport.ts';\n\nexport interface AuthChildSettings {\n node: string;\n entry: string;\n engine: { authPath: string; agentDir: string };\n timings: ParentTimings;\n transport: TransportKind;\n seal: Sealer;\n /** where the child's stdout and stderr go, sealed. Absent: the pipes are drained and dropped. */\n log?: RuntimeHostBindings['log'];\n}\n\nconst AUTH_ENV_ALLOW = ['PATH', 'HOME', 'LANG', 'LC_ALL', 'TZ', 'TMPDIR'];\n\ntype Step<T> = { done: T } | { reply: ParentFrame } | undefined;\n\nasync function exchange<T>(\n settings: AuthChildSettings,\n init: (nonce: string) => ParentFrame,\n onFrame: (frame: ChildFrame) => Step<T> | Promise<Step<T>>,\n options: { signal?: AbortSignal; timeoutMs?: number } = {},\n): Promise<T> {\n const { engine, seal, timings } = settings;\n await mkdir(engine.agentDir, { recursive: true, mode: 0o700 });\n const nonce = randomBytes(16).toString('hex');\n const { env } = childEnv({ allow: AUTH_ENV_ALLOW, set: {} }, fixedChildEnv(engine.agentDir, undefined));\n const child = spawn(settings.node, [settings.entry, `${NONCE_ARG}${nonce}`], {\n cwd: engine.agentDir,\n env,\n stdio: stdioFor(settings.transport),\n serialization: 'json',\n detached: true,\n });\n const budget = newOutputBudget();\n const write = (line: string, stream: 'stdout' | 'stderr'): void =>\n settings.log?.(stream === 'stderr' ? 'warn' : 'info', seal.text(line), { stream, source: 'auth-child' });\n // Attached whether or not a log port is bound: an undrained pipe would block the child (DESIGN 3.2).\n if (child.stdout) drainChildOutput(child.stdout, 'stdout', budget, write);\n if (child.stderr) drainChildOutput(child.stderr, 'stderr', budget, write);\n const transport = transportFor(settings.transport, child);\n const sealedError = (info: ErrorInfo): ErrorInfo =>\n toErrorInfo(new CohorteError(seal.json(info as unknown as JsonValue) as unknown as ErrorInfo), {\n code: 'configuration/engine-init',\n class: 'configuration',\n });\n\n let timer: NodeJS.Timeout | undefined;\n try {\n return await new Promise<T>((resolve, reject) => {\n const fail = (info: ErrorInfo): void => reject(new CohorteError(info));\n let greeted = false;\n timer = setTimeout(\n () => fail(protocolViolation('handshake-timeout', 'the auth child did not answer in time')),\n options.timeoutMs ?? timings.helloMs,\n );\n options.signal?.addEventListener('abort', () => fail(errorOf('tool-transient/cancelled', 'cancelled')), {\n once: true,\n });\n child.once('error', (error) => fail(processExitError('spawn-failed', error.name)));\n transport.onClose(() => fail(processExitError('exit-without-settled')));\n transport.onFrame((decoded) => {\n if (!decoded.ok)\n return fail(protocolViolation('frame-schema', `${decoded.error.reason}: ${decoded.error.detail}`));\n const frame = decoded.value;\n if (frame.t === 'heartbeat') return;\n if (frame.t === 'fatal')\n return fail(\n frame.signal ? classify({ ...frame.signal, text: seal.text(frame.signal.text) }) : sealedError(frame.error),\n );\n if (!greeted) {\n if (frame.t !== 'hello' || frame.nonce !== nonce)\n return fail(protocolViolation('nonce-mismatch', 'the first frame is not the hello of this spawn'));\n greeted = true;\n if (options.timeoutMs === undefined) clearTimeout(timer);\n void transport.send(init(nonce));\n return;\n }\n void Promise.resolve(onFrame(frame)).then((step) => {\n if (step && 'done' in step) resolve(step.done);\n else if (step) void transport.send(step.reply);\n }, reject);\n });\n });\n } finally {\n clearTimeout(timer);\n void transport.send({ t: 'shutdown' });\n await new Promise<void>((resolve) => {\n if (child.exitCode !== null || child.signalCode !== null || child.pid === undefined) return resolve();\n const kill = setTimeout(() => {\n try {\n process.kill(-(child.pid ?? 0), 'SIGKILL');\n } catch {\n // already gone\n }\n }, timings.exitGraceMs);\n child.once('exit', () => {\n clearTimeout(kill);\n resolve();\n });\n });\n transport.close();\n }\n}\n\nconst unexpected = (frame: ChildFrame): never => {\n throw new CohorteError(protocolViolation('unexpected-frame', `'${frame.t}' in an auth exchange`));\n};\n\nexport function authStatus(settings: AuthChildSettings, providers: string[]): Promise<ProviderAuthStatus[]> {\n const { authPath, agentDir } = settings.engine;\n return exchange<ProviderAuthStatus[]>(\n settings,\n (nonce) => ({ t: 'init', v: 1, nonce, mode: 'auth-status', providers, engine: { authPath, agentDir } }),\n (frame) => (frame.t === 'auth.status' ? { done: settings.seal.json(frame.statuses) } : unexpected(frame)),\n { timeoutMs: settings.timings.readyMs },\n );\n}\n\ntype ShowEvent = Parameters<LoginInteraction['show']>[0];\ntype AskPrompt = Parameters<LoginInteraction['ask']>[0];\nconst isRecord = (value: JsonValue): value is { [member: string]: JsonValue } =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\nconst text = (value: JsonValue | undefined): string => (typeof value === 'string' ? value : '');\n\nfunction showEvent(raw: JsonValue): ShowEvent {\n if (isRecord(raw) && raw.kind === 'open-url') {\n const instructions = text(raw.instructions);\n return { kind: 'open-url', url: text(raw.url), ...(instructions ? { instructions } : {}) };\n }\n if (isRecord(raw) && raw.kind === 'device-code')\n return { kind: 'device-code', userCode: text(raw.userCode), verificationUri: text(raw.verificationUri) };\n return { kind: 'info', message: isRecord(raw) ? text(raw.message) : '' };\n}\n\nfunction askPrompt(raw: JsonValue): AskPrompt {\n const message = isRecord(raw) ? text(raw.message) : '';\n if (isRecord(raw) && raw.kind === 'select' && Array.isArray(raw.options))\n return {\n kind: 'select',\n message,\n options: raw.options.filter(isRecord).map((option) => ({ id: text(option.id), label: text(option.label) })),\n };\n const kind = isRecord(raw) && (raw.kind === 'secret' || raw.kind === 'manual-code') ? raw.kind : 'text';\n return { kind, message };\n}\n\nexport function authLogin(\n settings: AuthChildSettings,\n provider: string,\n ui: LoginInteraction,\n signal: AbortSignal,\n): Promise<ProviderAuthStatus> {\n const { authPath, agentDir } = settings.engine;\n return exchange<ProviderAuthStatus>(\n settings,\n (nonce) => ({ t: 'init', v: 1, nonce, mode: 'auth-login', provider, engine: { authPath, agentDir } }),\n async (frame) => {\n if (frame.t === 'auth.show') {\n ui.show(showEvent(settings.seal.json(frame.event)));\n return undefined;\n }\n if (frame.t === 'auth.ask') {\n const value = await ui.ask(askPrompt(settings.seal.json(frame.prompt)));\n return { reply: { t: 'auth.answer', id: frame.id, value } };\n }\n return frame.t === 'auth.done' ? { done: settings.seal.json(frame.status) } : unexpected(frame);\n },\n { signal },\n );\n}\n\nexport async function authLogout(settings: AuthChildSettings, provider: string): Promise<void> {\n const { authPath, agentDir } = settings.engine;\n await exchange<true>(\n settings,\n (nonce) => ({ t: 'init', v: 1, nonce, mode: 'auth-logout', provider, engine: { authPath, agentDir } }),\n (frame) => (frame.t === 'auth.done' ? { done: true } : unexpected(frame)),\n { timeoutMs: settings.timings.readyMs },\n );\n}\n","// Kept out of `index.ts`: the Wave-0 barrel re-exports that file with `export *` and froze its value names.\nimport { join } from 'node:path';\n\nexport const PI_ENGINE_VERSION = '0.85.1';\n/** Header NAMES the child may relay in `provider.response` (DESIGN 3.3). */\nexport const RESPONSE_HEADER_ALLOWLIST: readonly string[] = Object.freeze([\n 'retry-after',\n 'x-ratelimit-*',\n 'x-codex-*',\n]);\nexport const AGENT_HOST_ENTRY = join('dist', 'agent-host.mjs');\n","// DESIGN 3.9 — what PiRuntime reports for Pi 0.85.1 in this embedding. `doctor` prints these values verbatim.\nimport type { Cap, RuntimeCapabilities } from '@cohorte/runtime-contract';\n\nconst yes: Cap = { value: 'yes' };\nconst no = (why: string): Cap => ({ value: 'no', why });\nconst partial = (why: string): Cap => ({ value: 'partial', why });\n\n/** 'park' only once assumption A-1 is proven by its tripwire; until then the executed fallback (DESIGN 3.5). */\nexport type ModelBoundaryMode = 'stop-after-turn' | 'park';\n\nfunction brainSandbox(platform: string): Cap {\n if (platform === 'darwin') return partial('Seatbelt, port-level network filter, deprecated tool');\n if (platform === 'linux') return partial('bwrap read-only bind; probe pending');\n return no('no sandbox backend on this platform');\n}\n\nexport function piCapabilities(\n modelBoundary: ModelBoundaryMode,\n platform: string = process.platform,\n): RuntimeCapabilities {\n const a1 = (fallback: string): Cap => (modelBoundary === 'park' ? yes : partial(fallback));\n return {\n contractVersion: '1',\n toolExecution: 'host-delegated',\n streaming: yes,\n thinkingStream: yes,\n send: { steer: yes, followUp: yes },\n cancelCooperative: yes,\n cancelHard: yes,\n pause: { toolBoundary: yes, modelBoundary: a1('stop-after-turn + continue note') },\n continuationFromTranscript: no('V3.0 resumes with a fresh incarnation and a reconciliation note'),\n processIsolation: yes,\n envFiltering: yes,\n brainSandbox: brainSandbox(platform),\n resourceLimits: partial('--max-old-space-size only'),\n budgetEnforcement: {\n turns: yes,\n modelRequests: a1('parent-side count + abort'),\n tokens: yes,\n context: a1('parent-side count + abort'),\n wallClock: yes,\n outputTokensPerRequest: no('ignored on openai-codex'),\n },\n hiddenModelCalls: no('compaction, agent retry and provider retries are off'),\n usageReporting: yes,\n effectiveModelReporting: yes,\n quotaReporting: partial(\n 'HTTP status + allowlisted headers, SSE transport, openai-codex-responses only; header names provider-specific; no remaining-quota API in Pi',\n ),\n authStatusWithoutSecret: partial(\n 'state, type, source and billing without a secret; the non-secret account label is not exposed by the engine: Pi 0.85.1 has no metadata-only accessor, D-24',\n ),\n subscriptionModeAssertion: yes,\n systemPromptExact: partial(\n 'Pi appends one `Current working directory` line, recorded as effectiveSystemPromptSha256; under Anthropic OAuth pi-ai injects an identity block',\n ),\n runtimePinning: partial('agent-host bundle + Pi package trees hashed; transitive deps by lock evidence'),\n platforms: { darwin: yes, linux: yes, win32: no('kill-tree, sandbox and worktree path limits unvalidated') },\n hints: { memoryPerAgentMb: 200, coldStartMs: 330, maxConcurrentAgents: 3 },\n };\n}\n","// The parent side of PiRuntime: an `AgentRuntime` that imports NO engine (ADR-0001). It verifies what it is about to\n// run (pin, prompt, task, note), builds the child's environment, and hands each incarnation to an `AgentSession`.\nimport { randomBytes } from 'node:crypto';\nimport { mkdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { CohorteError, errorOf, type Sha256, sha256Hex } from '@cohorte/base';\nimport {\n type AgentRuntime,\n type IsolationReport,\n type RuntimeAgentHandle,\n type RuntimeCapabilities,\n type RuntimeEvent,\n type RuntimeHostBindings,\n type RuntimeMessage,\n type RuntimePin,\n type RuntimeSnapshot,\n type SpawnRequest,\n toolGrantProblems,\n type Unsubscribe,\n} from '@cohorte/runtime-contract';\nimport { ADAPTER_VERSION, type PinVerifier, RUNTIME_ID } from '../pin/pin.ts';\nimport type { EngineSettings } from '../protocol.ts';\nimport { type ModelBoundaryMode, piCapabilities } from './capabilities.ts';\nimport { childEnv, fixedChildEnv } from './env.ts';\nimport { AgentSession, NONCE_ARG, type ParentTimings, type Sealer, type SpawnPlan } from './session.ts';\nimport type { TransportKind } from './transport.ts';\n\nexport const SESSION_FILE = 'session.jsonl';\n\n/** What the engine makes of Cohorte's prompt: it appends ONE line (DESIGN 3.3; the date line is gone since 0.80.7). */\nexport const effectiveSystemPrompt = (prompt: string, workingDirectory: string): string =>\n `${prompt}\\nCurrent working directory: ${workingDirectory}\\n`;\n\nexport type SandboxWrap = (\n policy: SpawnRequest['sandbox'],\n command: { file: string; args: readonly string[] },\n) => { file: string; args: string[]; isolation: IsolationReport } | null;\n\nexport interface PiRuntimeSettings {\n bindings: RuntimeHostBindings;\n pin: RuntimePin;\n verifier: PinVerifier;\n seal: Sealer;\n /** the child's entry: `<install>/dist/agent-host.mjs`, or the tests' override */\n entry: string;\n engine: Omit<EngineSettings, 'sessionFile'>;\n sandboxWrapper: SandboxWrap | undefined;\n transport: TransportKind;\n timings: ParentTimings;\n modelBoundary: ModelBoundaryMode;\n diagnostics: Readonly<Record<string, string>>;\n}\n\nconst PROCESS_ISOLATION: IsolationReport = {\n level: 'process',\n filesystem: 'advisory',\n network: 'none',\n backend: 'none',\n};\n\nasync function readVerified(what: string, ref: { path: string; sha256: Sha256; bytes: number }): Promise<string> {\n const mismatch = (detail: string): CohorteError =>\n new CohorteError(errorOf('security/asset-hash-mismatch', `${what} is not the file that was rendered: ${detail}`));\n const content = await readFile(ref.path).catch(() => undefined);\n if (!content) throw mismatch('it cannot be read');\n if (sha256Hex(content) !== ref.sha256) throw mismatch('its sha256 differs');\n if (content.byteLength !== ref.bytes) throw mismatch('its size differs');\n return content.toString('utf8');\n}\n\nexport class PiRuntime implements AgentRuntime {\n readonly id = RUNTIME_ID;\n readonly version: string;\n readonly #settings: PiRuntimeSettings;\n readonly #capabilities: RuntimeCapabilities;\n readonly #listeners = new Set<(event: RuntimeEvent) => void>();\n /** `(runId, agentId, incarnation)` that ever reached a process: spawn is idempotent on it (spec 6). */\n readonly #incarnations = new Set<string>();\n readonly #starting = new Set<Promise<unknown>>();\n /** the latest incarnation of each agent, live or exited: what `send`/`cancel`/`pause`/`inspect` address */\n readonly #agents = new Map<string, AgentSession>();\n /**\n * EVERY incarnation that reached a process and has not ended yet. A second incarnation of one agent may be started\n * while the first is still live (the contract's `spawn` carries the number), and each child is its own detached\n * process group: without this set, `close()` would reach only the newest and leave the older one orphaned.\n */\n readonly #live = new Set<AgentSession>();\n #closed = false;\n\n constructor(settings: PiRuntimeSettings) {\n this.#settings = settings;\n this.version = `${ADAPTER_VERSION}+pi.${settings.pin.engine?.version ?? settings.engine.expectedEngineVersion}`;\n this.#capabilities = piCapabilities(settings.modelBoundary);\n }\n\n capabilities(): RuntimeCapabilities {\n return structuredClone(this.#capabilities);\n }\n\n subscribe(listener: (event: RuntimeEvent) => void): Unsubscribe {\n this.#listeners.add(listener);\n return () => void this.#listeners.delete(listener);\n }\n\n async spawn(request: SpawnRequest): Promise<RuntimeAgentHandle> {\n if (this.#closed) throw new CohorteError(errorOf('conflict/not-running', 'this runtime is closed'));\n const key = `${request.runId}\\n${request.agentId}\\n${request.incarnation}`;\n if (this.#incarnations.has(key))\n throw new CohorteError(\n errorOf(\n 'conflict/incarnation-exists',\n `incarnation ${request.incarnation} of ${request.agentId} was already spawned`,\n ),\n );\n // Reserved before the first await: two concurrent spawns of one incarnation cannot both pass.\n this.#incarnations.add(key);\n let reachedAProcess = false;\n const starting = (async () => {\n const plan = await this.#plan(request);\n reachedAProcess = true;\n return AgentSession.start(this.#context(), plan);\n })();\n this.#starting.add(starting);\n try {\n const session = await starting;\n this.#live.add(session);\n void session.done.then(() => void this.#live.delete(session));\n this.#agents.set(request.agentId, session);\n return session.handle;\n } catch (thrown) {\n // Refused before anything ran (a hash, the pin, the env): the incarnation number was not used.\n if (!reachedAProcess) this.#incarnations.delete(key);\n throw thrown;\n } finally {\n this.#starting.delete(starting);\n }\n }\n\n async send(agentId: string, message: RuntimeMessage): Promise<void> {\n await this.#agent(agentId).send(message);\n }\n\n async cancel(agentId: string, reason = 'cancelled by the host'): Promise<void> {\n await this.#agent(agentId).cancel(reason);\n }\n\n pause(agentId: string): Promise<void> {\n this.#agent(agentId).pause();\n return Promise.resolve();\n }\n\n resume(agentId: string): Promise<void> {\n this.#agent(agentId).resume();\n return Promise.resolve();\n }\n\n inspect(agentId: string): Promise<RuntimeSnapshot> {\n return this.#agent(agentId).inspect();\n }\n\n async close(): Promise<void> {\n this.#closed = true;\n await Promise.allSettled([...this.#starting]);\n await Promise.all([...this.#live].map((session) => session.cancel('the runtime was closed')));\n this.#listeners.clear();\n }\n\n #agent(agentId: string): AgentSession {\n const session = this.#agents.get(agentId);\n if (!session) throw new CohorteError(errorOf('conflict/not-running', `no agent ${agentId} on this runtime`));\n return session;\n }\n\n #context() {\n const { bindings, seal, timings, transport, modelBoundary, diagnostics } = this.#settings;\n return {\n bindings,\n seal,\n timings,\n transport,\n modelBoundary,\n diagnostics,\n runtimeId: RUNTIME_ID,\n emit: (event: RuntimeEvent): void => {\n for (const listener of [...this.#listeners]) {\n try {\n listener(event);\n } catch (thrown) {\n bindings.log('error', seal.text(`a runtime event listener threw: ${String(thrown)}`), { type: event.type });\n }\n }\n },\n };\n }\n\n /** Everything that can refuse a spawn BEFORE a process exists. */\n async #plan(request: SpawnRequest): Promise<SpawnPlan> {\n const { bindings, verifier, pin, entry, engine, sandboxWrapper } = this.#settings;\n const problems = toolGrantProblems(request.tools);\n if (problems.length > 0) throw new CohorteError(errorOf('validation/unexpected', problems.join('; ')));\n await verifier.verify(pin);\n\n const prompt = await readVerified('the system prompt', request.systemPrompt);\n const taskText = await readVerified('the task', request.task);\n const noteText = request.continuation\n ? await readVerified('the continuation note', request.continuation.note)\n : undefined;\n\n const stateDir = bindings.stateDir(request.runId, request.agentId, request.incarnation);\n await mkdir(stateDir, { recursive: true });\n // DESIGN 3.7 layer 2: the engine's agent dir is Cohorte-owned and 0700. It is created HERE, before the child is\n // pointed at it, so that the engine never creates it itself with the umask's permissions.\n await mkdir(engine.agentDir, { recursive: true, mode: 0o700 });\n const { env, attested } = childEnv(\n request.sandbox.env,\n fixedChildEnv(engine.agentDir, request.sandbox.limits.maxOldSpaceMb),\n );\n\n const nonce = randomBytes(16).toString('hex');\n const bare = { file: pin.node.execPath, args: [entry, `${NONCE_ARG}${nonce}`] };\n const wrapped = sandboxWrapper?.(request.sandbox, bare) ?? null;\n if (!wrapped && request.sandbox.require === 'os')\n throw new CohorteError(\n errorOf(\n 'security/sandbox-unavailable',\n 'the request requires an OS sandbox around the agent process and no backend is available',\n ),\n );\n return {\n request,\n stateDir,\n command: wrapped ? { file: wrapped.file, args: wrapped.args } : bare,\n nonce,\n env,\n attestedRequest: { ...request, sandbox: { ...request.sandbox, env: attested } },\n engine: { ...engine, sessionFile: join(stateDir, SESSION_FILE) },\n expectedEffectivePromptSha256: sha256Hex(effectiveSystemPrompt(prompt, request.workingDirectory)),\n isolation: wrapped?.isolation ?? PROCESS_ISOLATION,\n taskText,\n noteText,\n };\n }\n}\n","// `createPiRuntimeProvider` — how a host obtains PiRuntime (DESIGN 2.2.1, 3.2). This side imports NO engine: the\n// engine lives in the per-agent child, reached through AgentHostProtocol only.\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { CohorteError, errorOf, type JsonValue, type Redactor } from '@cohorte/base';\nimport type {\n AgentRuntimeProvider,\n IsolationReport,\n RuntimeHostBindings,\n SandboxPolicy,\n} from '@cohorte/runtime-contract';\nimport { createPinVerifier, type PinOptions, pinWithDiagnostics } from '../pin/pin.ts';\nimport { authLogin, authLogout, authStatus } from './auth.ts';\nimport type { ModelBoundaryMode } from './capabilities.ts';\n\nimport { AGENT_HOST_ENTRY, PI_ENGINE_VERSION, RESPONSE_HEADER_ALLOWLIST } from './defaults.ts';\nimport { PiRuntime } from './runtime.ts';\nimport { DEFAULT_TIMINGS, type ParentTimings, type Sealer } from './session.ts';\nimport type { TransportKind } from './transport.ts';\n\nexport type { ModelBoundaryMode } from './capabilities.ts';\nexport type { ParentTimings } from './session.ts';\nexport type { FrameTransport, TransportKind } from './transport.ts';\n\nexport interface BrainCommand {\n file: string;\n args: readonly string[];\n}\n\n/**\n * Wraps the child's command line in an OS sandbox (DESIGN 3.6) and says what that enforces; `null` = no backend on\n * this machine, and the parent then applies `SandboxPolicy.require`. Pure. Injected by the composition root: this\n * package may not import `security`.\n */\nexport type SandboxWrapper = (\n policy: SandboxPolicy,\n command: BrainCommand,\n) => { file: string; args: string[]; isolation: IsolationReport } | null;\n\nexport interface PiEngineOptions {\n /** the ENGINE's credential store, shared with the user's own login (R7). Never read by this side. */\n authPath: string;\n /** Cohorte-owned, no models.json, no settings, no extensions (DESIGN 3.7 layer 2) */\n agentDir: string;\n loadFrom: 'package' | 'bundle';\n expectedEngineVersion: string;\n responseHeaderAllowlist: string[];\n}\n\nexport interface PiRuntimeProviderOptions {\n /** TESTS ONLY: another child entry than the pinned one (the fake brain). `apps/cli` never passes it. */\n entryOverride?: string;\n sandboxWrapper?: SandboxWrapper;\n /**\n * Seals every text that comes out of the child before it becomes an event, an error or a log line (I7). Injected\n * by the composition root (this package may not import `security`); `create()` refuses to run without it.\n */\n redactor?: Pick<Redactor, 'sealText' | 'sealJson'>;\n /** the install whose `dist/` holds `agent-host.mjs`. Default: the directory above the running bundle. */\n installDir?: string;\n engine?: Partial<PiEngineOptions>;\n /** 'ipc' (default, what the spike executed) or LF-delimited JSON over fd 3/4 */\n transport?: TransportKind;\n /** 'park' only once assumption A-1 is proven; default: the executed `stop-after-turn` fallback */\n modelBoundary?: ModelBoundaryMode;\n timings?: Partial<ParentTimings>;\n /**\n * Where the AUTH child's stdout and stderr go, sealed (DESIGN 3.2: the engine prints login and refresh error bodies\n * that can hold token material). An agent's output uses `RuntimeHostBindings.log`, which `create()` receives;\n * `authStatus`/`login`/`logout` receive no bindings, so the host binds the port once, here. Absent: drained and\n * dropped, as before (docs/v3/requests/U1.07.md R1).\n */\n log?: RuntimeHostBindings['log'];\n}\n\nexport function createPiRuntimeProvider(options: PiRuntimeProviderOptions = {}): AgentRuntimeProvider {\n const installDir = options.installDir ?? join(dirname(fileURLToPath(import.meta.url)), '..');\n const engine: PiEngineOptions = {\n authPath: join(homedir(), '.pi', 'agent', 'auth.json'),\n agentDir: join(homedir(), '.cohorte', 'pi-agent'),\n loadFrom: 'package',\n expectedEngineVersion: PI_ENGINE_VERSION,\n responseHeaderAllowlist: [...RESPONSE_HEADER_ALLOWLIST],\n ...options.engine,\n };\n const pinOptions: PinOptions = {\n installDir,\n loadFrom: engine.loadFrom,\n ...(options.entryOverride === undefined ? {} : { entryOverride: options.entryOverride }),\n };\n const entry = options.entryOverride ?? join(installDir, AGENT_HOST_ENTRY);\n const timings = { ...DEFAULT_TIMINGS, ...options.timings };\n const transport = options.transport ?? 'ipc';\n\n const sealer = (): Sealer => {\n const { redactor } = options;\n if (!redactor)\n throw new CohorteError(\n errorOf(\n 'configuration/engine-init',\n 'no redactor is bound to the runtime provider: child output cannot be sealed',\n ),\n );\n return {\n text: (text) => redactor.sealText(text).text,\n json: <T extends JsonValue>(value: T): T => redactor.sealJson(value).value,\n };\n };\n const authChild = () => ({\n node: process.execPath,\n entry,\n engine,\n timings,\n transport,\n seal: sealer(),\n ...(options.log === undefined ? {} : { log: options.log }),\n });\n\n return {\n id: 'pi',\n async pin() {\n const { pin: value } = await pinWithDiagnostics(pinOptions);\n return value;\n },\n async create(bindings, pinned) {\n const seal = sealer();\n const verifier = createPinVerifier(pinOptions);\n await verifier.verify(pinned);\n const { diagnostics } = await pinWithDiagnostics(pinOptions);\n if (diagnostics.installLock?.startsWith('absent'))\n bindings.log(\n 'warn',\n seal.text(`runtime pin: no install lock evidence (${diagnostics.installLock})`),\n diagnostics,\n );\n return new PiRuntime({\n bindings,\n pin: pinned,\n verifier,\n seal,\n entry,\n engine: pinned.engine ? { ...engine, expectedEngineVersion: pinned.engine.version } : engine,\n sandboxWrapper: options.sandboxWrapper,\n transport,\n timings,\n modelBoundary: options.modelBoundary ?? 'stop-after-turn',\n diagnostics,\n });\n },\n authStatus: (providers) => authStatus(authChild(), providers),\n login: (provider, ui, signal) => authLogin(authChild(), provider, ui, signal),\n logout: (provider) => authLogout(authChild(), provider),\n };\n}\n","// apps/cli/src/assets/index.ts — AREA barrel: the `AssetSource` port (DESIGN 1.2 \"embedded prompts/skills/\n// schemas/migrations + manifest verification\"). `__ASSETS_TREE_SHA256__` / `__COHORTE_VERSION__` are the DESIGN\n// 1.4 step-3 bundle <-> assets cross-check: `tsdown.config.ts` `define`s them from `assets/manifest.json` at\n// build time, so the bundled `cli.mjs` can assert its own tree hash without reading the manifest twice. Wave-0\n// stub: filled by `U4.01`, which owns `apps/cli/src/assets/**`.\nimport { existsSync, readFileSync, statSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { err, errorOf, ok, type Sha256, sha256Hex } from '@cohorte/base';\nimport type { AssetSource } from '../contract/index.ts';\n\ndeclare global {\n /** injected by `apps/cli/tsdown.config.ts` (DESIGN 1.4 step 3); `'unknown'` when run un-bundled (tsc, vitest). */\n const __ASSETS_TREE_SHA256__: string;\n const __COHORTE_VERSION__: string;\n}\n\n/** `'unknown'` outside a tsdown bundle, where the `define`d globals do not exist. */\nexport const BUNDLED_ASSETS_TREE_SHA256: string =\n typeof __ASSETS_TREE_SHA256__ === 'string' ? __ASSETS_TREE_SHA256__ : 'unknown';\nexport const BUNDLED_COHORTE_VERSION: string =\n typeof __COHORTE_VERSION__ === 'string' ? __COHORTE_VERSION__ : 'unknown';\n\nconst ASSET_ROOTS = ['prompts', 'skills', 'schemas', 'migrations'] as const;\nconst bundledAssetCandidates = [\n resolve(import.meta.dirname, '../assets'),\n resolve(import.meta.dirname, '../../assets'),\n];\nconst sourceAssetRoot = resolve(import.meta.dirname, '../../../../');\nconst assetRoot =\n bundledAssetCandidates.find((candidate) => existsSync(join(candidate, 'manifest.json'))) ?? sourceAssetRoot;\nconst safeId = (id: string): string[] => {\n const parts = id.split('/');\n if (\n parts.length < 1 ||\n parts.some((part) => part.length === 0 || part === '.' || part === '..' || part.includes('\\\\'))\n )\n throw new Error(`invalid embedded asset id: ${id}`);\n return parts;\n};\nconst findAsset = (root: (typeof ASSET_ROOTS)[number], id: string): { path: string; sha256: Sha256; bytes: number } => {\n const parts = safeId(id);\n const candidates = [\n join(assetRoot, root, ...parts),\n join(assetRoot, root, ...parts.slice(0, -1), `${parts.at(-1)}.md`),\n ];\n const path = candidates.find((candidate) => existsSync(candidate) && statSync(candidate).isFile());\n if (path === undefined) throw new Error(`embedded asset not found: ${root}/${id}`);\n const rootPath = resolve(assetRoot, root);\n if (!path.startsWith(`${rootPath}/`) || !existsSync(path) || !statSync(path).isFile())\n throw new Error(`embedded asset not found: ${root}/${id}`);\n const bytes = readFileSync(path);\n return { path, sha256: sha256Hex(bytes), bytes: bytes.byteLength };\n};\n\nexport function createAssetSource(): AssetSource {\n return {\n prompt: async (id) => findAsset('prompts', id),\n skill: async (id) => findAsset('skills', id),\n schema: async (id) => findAsset('schemas', id),\n migration: async (id) => findAsset('migrations', id),\n treeSha256: () => {\n const manifestPath = join(assetRoot, 'manifest.json');\n if (!existsSync(manifestPath)) return sha256Hex(new Uint8Array()) as Sha256;\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { treeSha256?: string };\n return (manifest.treeSha256 ?? '') as Sha256;\n },\n async verify() {\n const manifestPath = join(assetRoot, 'manifest.json');\n if (!existsSync(manifestPath))\n return err(errorOf('security/asset-hash-mismatch', 'embedded asset manifest is missing'));\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as {\n files?: readonly { path: string; size: number; sha256: string }[];\n treeSha256?: string;\n };\n const mismatches = (manifest.files ?? []).filter((file) => {\n const path = join(assetRoot, file.path);\n if (!existsSync(path) || !statSync(path).isFile()) return true;\n const bytes = readFileSync(path);\n return bytes.byteLength !== file.size || sha256Hex(bytes) !== file.sha256;\n });\n if (\n mismatches.length > 0 ||\n (BUNDLED_ASSETS_TREE_SHA256 !== 'unknown' && BUNDLED_ASSETS_TREE_SHA256 !== manifest.treeSha256)\n )\n return err(errorOf('security/asset-hash-mismatch', 'embedded assets do not match their manifest'));\n return ok(true);\n },\n };\n}\n","// apps/cli/src/control/index.ts — AREA barrel: the `Controller` port (DESIGN 2.3.4 inbox / start routes: sign,\n// `INSERT ... ON CONFLICT(command_id) DO NOTHING`, touch `inbox.poke`, wait <= `--wait`). Wave-0 stub: filled by\n// `U4.02`, which owns `apps/cli/src/control/**`.\nimport { type Clock, type IdSource, sha256Hex } from '@cohorte/base';\nimport { initialRunState } from '@cohorte/core/state';\nimport type { StateStore } from '@cohorte/persistence/contract';\nimport {\n type CommandPayloads,\n type CommandResultDocument,\n type CommandType,\n canonicalCommandBody,\n} from '@cohorte/protocol';\nimport { createCommandAuthenticator, createKeyStore } from '@cohorte/security/auth';\nimport type { Controller } from '../contract/index.ts';\n\nexport function createController(options: {\n openStore: () => Promise<StateStore>;\n clock: Clock;\n ids: IdSource;\n cwd: string;\n home: string;\n pinnedInstallDir?: string;\n}): Controller {\n const keys = createKeyStore({ directory: `${options.home}/.cohorte/keys` });\n const authenticator = createCommandAuthenticator();\n return {\n async send<T extends CommandType>(\n type: T,\n payload: CommandPayloads[T],\n sendOptions: { readonly runId?: string; readonly waitMs?: number } = {},\n ): Promise<CommandResultDocument> {\n const commandId = options.ids.next<'CommandId'>('cmd');\n const runId = sendOptions.runId as never;\n const createdRunId = type === 'start' ? options.ids.next<'RunId'>('run') : runId;\n const envelope = {\n protocolVersion: '1.0' as const,\n commandId,\n type,\n ...(createdRunId === undefined ? {} : { runId: createdRunId }),\n issuedAt: options.clock.now(),\n actor: { kind: 'human' as const, id: 'cli', transport: 'cli' as const },\n payload,\n };\n const keyId = sha256Hex(options.cwd).slice(0, 24);\n const key = await keys.projectKey(keyId, { create: true });\n const signed = {\n ...envelope,\n auth: { scheme: authenticator.scheme, value: authenticator.sign(canonicalCommandBody(envelope), key) },\n } as never;\n const store = await options.openStore();\n const result =\n type === 'start'\n ? await store.transact('project', null, (tx) => {\n const startPayload = payload as CommandPayloads['start'];\n const status = tx.enqueueCommand(signed);\n if (status === 'enqueued') {\n const specPath =\n startPayload.spec && 'path' in startPayload.spec ? startPayload.spec.path : 'inline-spec';\n tx.putRun(\n initialRunState({\n runId: createdRunId,\n profile: startPayload.profile,\n tableVersion: 1,\n specId: (startPayload.spec && 'id' in startPayload.spec\n ? startPayload.spec.id\n : `spec_${sha256Hex(specPath).slice(0, 24)}`) as never,\n specSha256: sha256Hex(specPath),\n title: `${startPayload.profile} run`,\n pinnedInstallDir: options.pinnedInstallDir ?? options.cwd,\n baseBranch: 'main',\n cohorteVersion: '3.0.0-dev.1',\n schemaVersion: 1,\n startedAt: options.clock.now(),\n }).run,\n );\n }\n return { status, record: undefined };\n })\n : await store.enqueueCommand(signed);\n let finalStatus: 'pending' | 'completed' | 'rejected' = result.status === 'enqueued' ? 'pending' : 'rejected';\n if (result.status === 'enqueued' && sendOptions.waitMs && sendOptions.waitMs > 0) {\n const deadline = Date.now() + Math.min(sendOptions.waitMs, 30_000);\n while (Date.now() < deadline) {\n const current = await store.getCommand(commandId);\n if (current?.status === 'completed' || current?.status === 'rejected') {\n finalStatus = current.status === 'completed' ? 'completed' : 'rejected';\n break;\n }\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n }\n await store.close();\n return {\n documentVersion: 1,\n commandId,\n type,\n status: finalStatus,\n ...(type === 'start' && result.status === 'enqueued' ? { result: { runId: createdRunId } } : {}),\n ...(result.status === 'enqueued'\n ? {}\n : {\n error: {\n code: 'conflict/command-id-reuse',\n class: 'conflict',\n message: result.status,\n impact: 'command was not accepted',\n retryable: false,\n remediation: 'retry with a new command',\n } as never,\n }),\n };\n },\n };\n}\n","// apps/cli/src/pin/index.ts — AREA barrel: verifies the running install against `bundle-manifest.json` before a\n// `resume` re-execs it (DESIGN 6.3 \"A run belongs to its install ... after its dist/** hashes verify\"). Wave-0\n// stub: filled by `U4.01`, which owns `apps/cli/src/pin/**`.\nimport { existsSync, readFileSync, statSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { type ErrorInfo, err, errorOf, ok, type Result, type Sha256, sha256Hex } from '@cohorte/base';\nimport type { InstallInspector } from '../contract/index.ts';\n\n/** DESIGN 6.3 rule 2: refuses (`runtime-incompatible`) rather than falling back to whichever CLI is running. */\nexport async function verifyPinnedInstall(\n install: InstallInspector,\n pinnedDir: string,\n): Promise<Result<true, ErrorInfo>> {\n try {\n const expected = await install.bundleManifest();\n for (const file of expected) {\n const path = resolve(pinnedDir, file.file);\n if (!path.startsWith(`${resolve(pinnedDir)}/`) || !existsSync(path) || !statSync(path).isFile())\n return err(errorOf('security/runtime-pin-mismatch', `pinned install is missing ${file.file}`));\n const bytes = readFileSync(path);\n if (bytes.byteLength !== file.bytes || sha256Hex(bytes) !== file.sha256)\n return err(errorOf('security/runtime-pin-mismatch', `pinned install differs at ${file.file}`));\n }\n return ok(true);\n } catch (error) {\n return err(errorOf('security/runtime-pin-mismatch', `cannot verify pinned install: ${String(error)}`));\n }\n}\n\nexport function createInstallInspector(): InstallInspector {\n return {\n installDir: () => dirname(distDirectory()),\n async bundleManifest() {\n const path = join(distDirectory(), 'bundle-manifest.json');\n if (!existsSync(path)) return [];\n const raw = JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>;\n return Object.entries(raw)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([file, digest]) => {\n if (typeof digest !== 'string') throw new TypeError(`invalid bundle manifest entry: ${file}`);\n const filePath = join(distDirectory(), file);\n return {\n file: join('dist', file),\n sha256: digest as Sha256,\n bytes: existsSync(filePath) ? statSync(filePath).size : 0,\n };\n });\n },\n };\n}\n\nfunction distDirectory(): string {\n const candidates = [import.meta.dirname, dirname(import.meta.dirname)];\n return candidates.find((candidate) => existsSync(join(candidate, 'bundle-manifest.json'))) ?? import.meta.dirname;\n}\n","// apps/cli/src/host/index.ts — AREA barrel: the `HostSpawner` (DESIGN 4.7 \"spawns <pinned node> <pinned\n// install>/dist/cli.mjs __host --run <runId> with detached: true, stdio to runs/<id>/host.log, unref()\"). Wave-0\n// stub: filled by `U4.01`, which owns `apps/cli/src/host/**`.\nimport { spawn } from 'node:child_process';\nimport { realpathSync } from 'node:fs';\nimport { mkdir, open } from 'node:fs/promises';\nimport { isAbsolute, join, resolve } from 'node:path';\nimport { CohorteError, errorOf, type RunId } from '@cohorte/base';\nimport type { RunEngine } from '@cohorte/core/contract';\nimport type { StateStore } from '@cohorte/persistence/contract';\nimport type { StopRecord } from '@cohorte/protocol';\nimport type { HostSpawner } from '../contract/index.ts';\nimport { verifyPinnedInstall } from '../pin/index.ts';\n\nexport interface RunHost {\n run(): Promise<StopRecord>;\n}\n\nexport interface RunHostDeps {\n engine: RunEngine;\n runId: RunId;\n cohorteVersion: string;\n cwd?: string;\n targetRoot?: string;\n hostId?: string;\n signal?: AbortSignal;\n heartbeatMs?: number;\n heartbeat?: (host: { hostId: string; pid: number; startToken: string }) => Promise<void> | void;\n}\n\nfunction canonical(path: string): string {\n const absolute = isAbsolute(path) ? path : resolve(path);\n try {\n return realpathSync.native(absolute);\n } catch {\n return absolute;\n }\n}\n\nfunction assertHostTarget(cwd: string, targetRoot: string | undefined): void {\n if (typeof process.getuid === 'function' && process.getuid() === 0)\n throw new CohorteError(errorOf('security/root-refused', 'run hosts must not run as uid 0'));\n if (targetRoot === undefined) return;\n const current = canonical(cwd);\n const target = canonical(targetRoot);\n if (current === target || current.startsWith(`${target}/`))\n throw new CohorteError(errorOf('security/runtime-inside-target', `host cwd ${current} is inside target ${target}`));\n}\n\nexport function createRunHost(deps: RunHostDeps): RunHost {\n const cwd = deps.cwd ?? process.cwd();\n const host = {\n hostId: deps.hostId ?? `host-${process.pid}`,\n pid: process.pid,\n startToken: `${process.pid}:${process.ppid}:${process.argv0}`,\n };\n return {\n async run() {\n assertHostTarget(cwd, deps.targetRoot);\n const local = new AbortController();\n const abort = () => local.abort(deps.signal?.reason);\n if (deps.signal?.aborted) abort();\n else deps.signal?.addEventListener('abort', abort, { once: true });\n const interval = deps.heartbeatMs ?? 15_000;\n const heartbeat = deps.heartbeat;\n let timer: NodeJS.Timeout | undefined;\n if (heartbeat) {\n await heartbeat(host);\n timer = setInterval(() => {\n void heartbeat(host);\n }, interval);\n timer.unref?.();\n }\n try {\n return await deps.engine.run(deps.runId, {\n ...host,\n cohorteVersion: deps.cohorteVersion,\n signal: local.signal,\n });\n } finally {\n if (timer) clearInterval(timer);\n deps.signal?.removeEventListener('abort', abort);\n }\n },\n };\n}\n\nexport function createHostSpawner(\n options: {\n cwd?: string;\n openStore?: () => Promise<StateStore>;\n install?: Parameters<typeof verifyPinnedInstall>[0];\n } = {},\n): HostSpawner {\n const cwd = options.cwd ?? process.cwd();\n return {\n async spawnDetached(runId: string) {\n if (typeof process.getuid === 'function' && process.getuid() === 0) {\n throw new CohorteError(errorOf('security/root-refused', 'run hosts must not run as uid 0'));\n }\n if (!options.openStore || !options.install) {\n throw new CohorteError(\n errorOf('configuration/unexpected', 'host spawner is missing its store and install bindings'),\n );\n }\n const store = await options.openStore();\n let pinnedInstallDir: string | undefined;\n try {\n const run = await store.getRun(runId as never);\n if (!run) throw new CohorteError(errorOf('validation/invalid-id', `run ${runId} does not exist`));\n pinnedInstallDir = run.pinnedInstallDir;\n const verified = await verifyPinnedInstall(options.install, pinnedInstallDir);\n if (!verified.ok) throw new CohorteError(verified.error);\n } finally {\n await store.close();\n }\n const runDir = join(cwd, '.cohorte', 'runs', runId);\n await mkdir(runDir, { recursive: true });\n const log = await open(join(runDir, 'host.log'), 'a');\n const entry = join(pinnedInstallDir as string, 'dist', 'cli.mjs');\n const child = spawn(process.execPath, [entry, '__host', '--run', runId], {\n detached: true,\n stdio: ['ignore', log.fd, log.fd],\n cwd,\n });\n child.unref();\n await log.close();\n if (child.pid === undefined) throw new Error('host process did not provide a pid');\n return { pid: child.pid };\n },\n };\n}\n","// apps/cli/src/observe/index.ts — AREA barrel: the `Observer` port (DESIGN 4.7 \"pure readers: no lock, no write,\n// no temp file; durable events by sequence, poll 250 ms; ephemerals by tailing the spool; merge order (sequence,\n// sub); first line = snapshot\"). Wave-0 stub: filled by `U4.02`, which owns `apps/cli/src/observe/**`.\nimport type { JsonValue } from '@cohorte/base';\nimport type { StateStore } from '@cohorte/persistence/contract';\nimport type { Observer } from '../contract/index.ts';\n\nexport function createObserver(openStore?: () => Promise<StateStore>): Observer {\n return {\n follow(options) {\n return (async function* () {\n let sequence = options.sinceSequence ?? 0;\n let emitted = 0;\n do {\n if (options.signal?.aborted || !openStore) return;\n const store = await openStore();\n const events = await store.readEvents(options.runId as never, { afterSequence: sequence, limit: 1000 });\n await store.close();\n for (const event of events) {\n sequence = Math.max(sequence, event.sequence);\n if (options.replay !== undefined && emitted >= options.replay) return;\n emitted += 1;\n yield event as unknown as JsonValue;\n }\n if (events.length === 0) await new Promise<void>((resolve) => setTimeout(resolve, 250));\n } while (!options.signal?.aborted);\n })();\n },\n };\n}\n","// GitPort (DESIGN 5) and the hardened-runner constants (DESIGN 5.0). This package depends on `base` only, so the\n// two types DESIGN borrows from its neighbours are declared here, structurally identical to the originals:\n// `CanonicalPath` (= @cohorte/security/contract) and `FileTouch` (= @cohorte/protocol). Same brand, same fields:\n// a value of one is a value of the other, and `core` hands them across without a cast.\nimport type { Brand, Sha256, SurfaceId } from '@cohorte/base';\n\n/** absolute, realpath'd, NFC, no trailing slash, on-disk case */\nexport type CanonicalPath = Brand<string, 'CanonicalPath'>;\n\nexport interface FileTouch {\n /** worktree-relative, POSIX */\n path: string;\n op: 'read' | 'create' | 'modify' | 'delete';\n beforeSha256?: Sha256;\n afterSha256?: Sha256;\n bytes?: number;\n}\n\n/** `merge-tree --write-tree` needs git >= 2.38 */\nexport const MIN_GIT_VERSION = '2.38.0';\n\nexport interface RepoFacts {\n /** e.g. '2.50.1' */\n gitVersion: string;\n /** false below {@link MIN_GIT_VERSION} */\n supported: boolean;\n /** the COMMON git dir: every worktree of one repository reports the same one */\n commonDir: CanonicalPath;\n defaultBranch: string | null;\n head: { kind: 'branch'; name: string; sha: string } | { kind: 'detached'; sha: string } | { kind: 'unborn' };\n worktrees: { path: CanonicalPath; branch: string | null; head: string | null; locked: boolean }[];\n}\n\n/** Explicit on every commit: the ambient git config is never read (5.0). */\nexport interface GitIdentity {\n name: string;\n email: string;\n /** `git.commitIdentity: user` => the user's identity + this trailer value, e.g. 'Cohorte <cohorte@localhost>' */\n coAuthoredBy?: string;\n}\n\n/**\n * Path -> surface, decided by the CALLER (`core`, through `security`'s GlobMatcher): this package never evaluates\n * a glob. `'shared'` also covers a path no surface owns.\n */\nexport interface SurfaceMap {\n surfaceOf(worktreeRelativePosixPath: string): SurfaceId | 'shared';\n}\n\n/** Bytes for the caller to store as an artifact: this package writes no state. */\nexport interface ArtifactDraft {\n kind: 'diff';\n mediaType: 'text/x-diff';\n bytes: Uint8Array;\n}\n\n/** DESIGN 5, verbatim. execFile `git`, never a shell. */\nexport interface GitPort {\n /** version (>= 2.38 for merge-tree --write-tree), default branch, HEAD kind, worktrees */\n facts(repo: CanonicalPath): Promise<RepoFacts>;\n treeDigest(worktree: CanonicalPath, opts: { exclude: string[] }): Promise<string>;\n addWorktree(req: { repo: CanonicalPath; path: CanonicalPath; branch: string | null; commit: string }): Promise<void>;\n /** slot reuse: new agent branch at the integration head */\n switchToNewBranch(req: { worktree: CanonicalPath; branch: string; at: string }): Promise<void>;\n removeWorktree(path: CanonicalPath, opts: { force: false }): Promise<'removed' | 'dirty-kept'>;\n /** quarantine path only; refuses any path outside the worktree root */\n resetHardClean(worktree: CanonicalPath, to: string): Promise<void>;\n commitAll(req: {\n worktree: CanonicalPath;\n message: string;\n trailers: Record<string, string>;\n identity: GitIdentity;\n paths: string[];\n }): Promise<{ sha: string; treeDigest: string } | { kind: 'nothing' }>;\n findCommitByTrailer(repo: CanonicalPath, branch: string, key: string, value: string): Promise<string | null>;\n /** git merge-tree --write-tree: no working tree involved */\n mergeTree(\n repo: CanonicalPath,\n ours: string,\n theirs: string,\n ): Promise<{ clean: true; tree: string } | { clean: false; files: string[] }>;\n commitTree(\n repo: CanonicalPath,\n tree: string,\n parents: string[],\n message: string,\n trailers: Record<string, string>,\n ): Promise<string>;\n /** atomic compare-and-swap */\n updateRefCas(repo: CanonicalPath, ref: string, next: string, expectedOld: string | null): Promise<'ok' | 'moved'>;\n /** refs/cohorte/<runId>/review/<n> — never updated during the run */\n createRef(repo: CanonicalPath, ref: string, sha: string): Promise<void>;\n diffBySurface(req: {\n repo: CanonicalPath;\n base: string;\n head: string;\n surfaces: SurfaceMap;\n }): Promise<{ surface: SurfaceId | 'shared'; files: string[]; patch: ArtifactDraft }[]>;\n /** status --porcelain=v2 -z, exact parsing */\n changedPaths(worktree: CanonicalPath): Promise<FileTouch[]>;\n}\n\nconst frozen = <const T extends readonly string[]>(values: T): T => Object.freeze(values);\n\n/**\n * 5.0 — mandatory on EVERY Cohorte-run git invocation, before the subcommand. Hooks and config are\n * repository-controlled code, and Cohorte's own git runs in the run host, outside the gate and the sandbox.\n */\nexport const GIT_HARDENED_CONFIG_ARGS = frozen([\n '-c',\n 'core.hooksPath=/dev/null',\n '-c',\n 'core.fsmonitor=',\n '-c',\n 'core.sshCommand=false',\n '-c',\n 'protocol.allow=never',\n '-c',\n 'commit.gpgsign=false',\n '-c',\n 'core.pager=cat',\n]);\n\n/** 5.0 — the COMPLETE git-specific env; the runner adds a pinned PATH and nothing from `process.env`. */\nexport const GIT_HARDENED_ENV: Readonly<Record<string, string>> = Object.freeze({\n GIT_CONFIG_GLOBAL: '/dev/null',\n GIT_CONFIG_NOSYSTEM: '1',\n GIT_TERMINAL_PROMPT: '0',\n GIT_OPTIONAL_LOCKS: '0',\n LC_ALL: 'C',\n});\n\n/** wherever output is parsed */\nexport const GIT_PORCELAIN_ARGS = frozen(['--porcelain=v2', '-z']);\n/** on every diff */\nexport const GIT_DIFF_HARDENING_ARGS = frozen(['--no-ext-diff', '--no-textconv']);\n","/**\n * Splits `-z` output on NUL. Git terminates every record with a NUL (never separates them), so the raw buffer\n * always ends with one trailing NUL when non-empty; that last, always-empty split element is dropped. An empty\n * `raw` (nothing to report) yields an empty array rather than `['']`.\n */\nexport function splitNul(raw: string): string[] {\n if (raw === '') return [];\n const parts = raw.split('\\0');\n if (parts.at(-1) === '') parts.pop();\n return parts;\n}\n","// Hardened runner (DESIGN 5.0): EVERY Cohorte-run git invocation goes through here. `execFile` only, never a\n// shell; hooks, fsmonitor, ssh and gpg-signing are disabled by CONFIG FLAG on every call (repository config can\n// never win: command-line -c always outranks it), and the environment is built from scratch — never inherited\n// from `process.env` — so nothing ambient (a token, a stray GIT_* var) ever reaches a git child process.\nimport { type ExecFileException, execFile } from 'node:child_process';\nimport { GIT_HARDENED_CONFIG_ARGS, GIT_HARDENED_ENV } from '../contract.ts';\n\nexport interface GitIdentityEnv {\n name: string;\n email: string;\n}\n\nexport interface RunGitOptions {\n /** absolute, pinned; never resolved through an ambient PATH at call time */\n gitBinary: string;\n /** the PATH handed to git for its own helpers; pinned at run start */\n path: string;\n cwd: string;\n args: readonly string[];\n // `| undefined` (not just `?`) so callers may forward `GitPortOptions.timeoutMs` verbatim under exactOptionalPropertyTypes.\n timeoutMs?: number | undefined;\n /** merged on top of {@link GIT_HARDENED_ENV} + PATH; used for GIT_INDEX_FILE (tree digest) */\n extraEnv?: Readonly<Record<string, string>>;\n /** sets the GIT_AUTHOR_ and GIT_COMMITTER_ variables explicitly (5.0: identity is never read from ambient config) */\n identity?: GitIdentityEnv;\n /** piped to stdin, then closed; stdin is always closed, so a command that unexpectedly waits on it fails fast */\n input?: string;\n /** default 16 MiB, mirrors the testkit temp-repo fixture */\n maxBuffer?: number;\n /** return stdout as raw bytes too (`stdoutBytes`): a diff/patch is not guaranteed to be valid UTF-8 */\n binary?: boolean;\n /** exit codes besides 0 that resolve instead of rejecting (`merge-tree --write-tree`'s 1 = conflict) */\n allowExitCodes?: readonly number[];\n}\n\nexport interface RunGitResult {\n stdout: string;\n stderr: string;\n stdoutBytes?: Uint8Array;\n exitCode: number;\n}\n\n/** A hardened git invocation that exited with a code {@link RunGitOptions.allowExitCodes} did not allow, or was killed. */\nexport class GitCommandError extends Error {\n readonly args: readonly string[];\n readonly exitCode: number | null;\n readonly signal: string | null;\n readonly stdout: string;\n readonly stderr: string;\n\n constructor(args: readonly string[], exitCode: number | null, signal: string | null, stdout: string, stderr: string) {\n const outcome = signal ? `killed by ${signal}` : `exited ${exitCode ?? '(unknown)'}`;\n super(`git ${args.join(' ')} ${outcome}: ${stderr.trim() || stdout.trim() || '(no output)'}`);\n this.name = 'GitCommandError';\n this.args = args;\n this.exitCode = exitCode;\n this.signal = signal;\n this.stdout = stdout;\n this.stderr = stderr;\n }\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MAX_BUFFER = 16 * 1024 * 1024;\n\nfunction buildEnv(options: RunGitOptions): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = { ...GIT_HARDENED_ENV, PATH: options.path };\n if (options.identity) {\n env.GIT_AUTHOR_NAME = options.identity.name;\n env.GIT_AUTHOR_EMAIL = options.identity.email;\n env.GIT_COMMITTER_NAME = options.identity.name;\n env.GIT_COMMITTER_EMAIL = options.identity.email;\n }\n if (options.extraEnv) Object.assign(env, options.extraEnv);\n return env;\n}\n\n/**\n * Runs one hardened git invocation: {@link GIT_HARDENED_CONFIG_ARGS} always precede `options.args`. Rejects with\n * {@link GitCommandError} unless the exit code is 0 or listed in `allowExitCodes`; a signal always rejects.\n */\nexport function runGit(options: RunGitOptions): Promise<RunGitResult> {\n const args = [...GIT_HARDENED_CONFIG_ARGS, ...options.args];\n const env = buildEnv(options);\n const allowed = new Set<number>([0, ...(options.allowExitCodes ?? [])]);\n return new Promise((resolvePromise, reject) => {\n const child = execFile(\n options.gitBinary,\n args,\n {\n cwd: options.cwd,\n env,\n timeout: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n maxBuffer: options.maxBuffer ?? DEFAULT_MAX_BUFFER,\n encoding: 'buffer',\n windowsHide: true,\n },\n (error: ExecFileException | null, stdoutBuf, stderrBuf) => {\n const stdout = stdoutBuf.toString('utf8');\n const stderr = stderrBuf.toString('utf8');\n const numericExitCode = typeof error?.code === 'number' ? error.code : null;\n const signal = error?.signal ?? null;\n const exitCode = numericExitCode ?? (error ? -1 : 0);\n if (error && (signal !== null || !allowed.has(exitCode))) {\n reject(new GitCommandError(args, numericExitCode, signal, stdout, stderr));\n return;\n }\n resolvePromise({\n stdout,\n stderr,\n exitCode,\n ...(options.binary ? { stdoutBytes: new Uint8Array(stdoutBuf) } : {}),\n });\n },\n );\n if (options.input !== undefined) child.stdin?.end(options.input, 'utf8');\n else child.stdin?.end();\n });\n}\n","// DESIGN 5.8 — V2's content-addressed digest, ported verbatim. Computed in a THROWAWAY copy of the index so the\n// real index (and its stat cache) is never touched: git's own git-status/commit machinery on the real worktree is\n// unaffected by a digest computation (test E9).\nimport { copyFile, mkdtemp, rm, utimes } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport type { CanonicalPath } from '../contract.ts';\nimport type { GitPortOptions } from './context.ts';\nimport { runGit } from './runner.ts';\n\nconst RACY_WINDOW_S = 5;\n\nexport interface TreeDigestOptions {\n exclude: string[];\n}\n\nexport async function treeDigest(\n worktree: CanonicalPath,\n options: TreeDigestOptions,\n ctx: GitPortOptions,\n): Promise<string> {\n const run = (args: readonly string[], extraEnv: Readonly<Record<string, string>>) =>\n runGit({ gitBinary: ctx.gitBinary, path: ctx.path, cwd: worktree, args, timeoutMs: ctx.timeoutMs, extraEnv });\n\n const realIndexOut = await run(['rev-parse', '--path-format=absolute', '--git-path', 'index'], {});\n const realIndexPath = realIndexOut.stdout.trim();\n\n const tempDir = await mkdtemp(join(tmpdir(), 'cohorte-idx-'));\n const tempIndex = join(tempDir, 'index');\n try {\n // Keeps the stat cache (fast path for unchanged files), so only backdating — not a blank index — defeats racy-git.\n // A worktree whose index was never written has no index file at all (`git init` does not create one), and a\n // digest may legitimately be taken there: git creates the temp index itself from `add -A`, which is the correct\n // empty-tree semantics. Any other fs error is a real failure and must surface (5.8: \"cannot compute\" = not fresh).\n const copied = await copyFile(realIndexPath, tempIndex).then(\n () => true,\n (error: unknown) => {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;\n throw error;\n },\n );\n if (copied) {\n const backdated = new Date(Date.now() - RACY_WINDOW_S * 1000);\n await utimes(tempIndex, backdated, backdated);\n }\n\n const env = { GIT_INDEX_FILE: tempIndex };\n if (options.exclude.length > 0) {\n await run(['rm', '--cached', '-r', '-q', '--ignore-unmatch', '--', ...options.exclude], env);\n }\n const excludePathspecs = options.exclude.map((path) => `:(exclude)${path}`);\n await run(['add', '-A', '--', '.', ...excludePathspecs], env);\n const writeOut = await run(['write-tree'], env);\n return writeOut.stdout.trim();\n } finally {\n // Removes the temp index AND any stray `<tempIndex>.lock` git may have left behind on a failed step.\n await rm(tempDir, { recursive: true, force: true });\n }\n}\n","import { type CanonicalPath, GIT_DIFF_HARDENING_ARGS, type GitIdentity } from '../contract.ts';\nimport type { GitPortOptions } from './context.ts';\nimport { splitNul } from './nul-split.ts';\nimport { GitCommandError, runGit } from './runner.ts';\nimport { treeDigest } from './tree-digest.ts';\n\n/** DESIGN 5.8: `treeDigest` at every Cohorte checkpoint (agent exit, commit, merge, ...) uses this default. */\nexport const DEFAULT_TREE_DIGEST_EXCLUDES: readonly string[] = Object.freeze(['.cohorte']);\n\nfunction trailerBlock(trailers: Record<string, string>, coAuthoredBy: string | undefined): string {\n const lines = Object.entries(trailers).map(([key, value]) => `${key}: ${value}`);\n if (coAuthoredBy !== undefined) lines.push(`Co-authored-by: ${coAuthoredBy}`);\n return lines.join('\\n');\n}\n\nfunction withTrailers(message: string, trailers: Record<string, string>, coAuthoredBy: string | undefined): string {\n const block = trailerBlock(trailers, coAuthoredBy);\n return block ? `${message}\\n\\n${block}\\n` : `${message}\\n`;\n}\n\n/** DESIGN 5.3: ownership audit, secret scan and the audit trail are the caller's job. `commitAll` only commits. */\nexport async function commitAll(\n req: {\n worktree: CanonicalPath;\n message: string;\n trailers: Record<string, string>;\n identity: GitIdentity;\n paths: string[];\n },\n ctx: GitPortOptions,\n): Promise<{ sha: string; treeDigest: string } | { kind: 'nothing' }> {\n if (req.paths.length === 0) return { kind: 'nothing' };\n\n const run = (args: readonly string[], extra: { input?: string; allowExitCodes?: readonly number[] } = {}) =>\n runGit({\n gitBinary: ctx.gitBinary,\n path: ctx.path,\n cwd: req.worktree,\n args,\n timeoutMs: ctx.timeoutMs,\n identity: req.identity,\n ...extra,\n });\n\n await run(['add', '-A', '--', ...req.paths]);\n // `--quiet` reports \"differences exist\" as exit 1: content-idempotent by construction (E1-style: a second call\n // with the same content stages nothing new and diffs to nothing).\n const diff = await run(['diff', '--cached', ...GIT_DIFF_HARDENING_ARGS, '--quiet', '--', ...req.paths], {\n allowExitCodes: [1],\n });\n if (diff.exitCode === 0) return { kind: 'nothing' };\n\n // The pathspec on the COMMIT, not only on the `add`, is what makes 5.3 true: the commit holds exactly the audited\n // paths. Agents cannot commit, but `git add` is not in the built-in deny list of ADR-0007 §2, so the index may hold\n // foreign staged content; a bare `git commit` would sweep it into Cohorte's commit, unaudited and unscanned.\n await run(['commit', '-q', '-F', '-', '--', ...req.paths], {\n input: withTrailers(req.message, req.trailers, req.identity.coAuthoredBy),\n });\n const shaOut = await run(['rev-parse', 'HEAD']);\n const sha = shaOut.stdout.trim();\n const digest = await treeDigest(req.worktree, { exclude: [...DEFAULT_TREE_DIGEST_EXCLUDES] }, ctx);\n return { sha, treeDigest: digest };\n}\n\nconst TRAILER_ENTRY_SEP = '\\x01';\nconst TRAILER_VALUE_SEP = '%x02';\n\n/** First commit of `branch` (most-recent-first, matching `git log`'s own order) whose `key` trailer equals `value`. */\nexport async function findCommitByTrailer(\n repo: CanonicalPath,\n branch: string,\n key: string,\n value: string,\n ctx: GitPortOptions,\n): Promise<string | null> {\n let out: Awaited<ReturnType<typeof runGit>>;\n try {\n out = await runGit({\n gitBinary: ctx.gitBinary,\n path: ctx.path,\n cwd: repo,\n args: [\n 'log',\n branch,\n '-z',\n `--format=%H${TRAILER_ENTRY_SEP}%(trailers:key=${key},valueonly,unfold,separator=${TRAILER_VALUE_SEP})`,\n ],\n timeoutMs: ctx.timeoutMs,\n });\n } catch (error) {\n // An empty/unborn branch: `git log` on it fails outright rather than printing nothing.\n if (error instanceof GitCommandError && /unknown revision|bad revision/i.test(error.stderr)) return null;\n throw error;\n }\n for (const entry of splitNul(out.stdout)) {\n const sep = entry.indexOf(TRAILER_ENTRY_SEP);\n if (sep === -1) continue;\n const sha = entry.slice(0, sep);\n const found = entry.slice(sep + 1);\n if (found === value) return sha;\n }\n return null;\n}\n","const VERSION_RE = /git version (\\d+)\\.(\\d+)(?:\\.(\\d+))?/;\n\nexport interface ParsedGitVersion {\n raw: string;\n major: number;\n minor: number;\n patch: number;\n}\n\n/** Parses the first line of `git --version`, e.g. `git version 2.50.1 (Apple Git-155)`. */\nexport function parseGitVersion(text: string): ParsedGitVersion {\n const match = VERSION_RE.exec(text);\n const major = match?.[1];\n const minor = match?.[2];\n if (major === undefined || minor === undefined) {\n throw new Error(`parseGitVersion: cannot parse ${JSON.stringify(text)}`);\n }\n const patch = match?.[3] ?? '0';\n return { raw: `${major}.${minor}.${patch}`, major: Number(major), minor: Number(minor), patch: Number(patch) };\n}\n\n/** True when `version >= min` (dotted `major.minor.patch`, missing components treated as 0). */\nexport function isAtLeast(version: ParsedGitVersion, min: string): boolean {\n const parts = min.split('.').map(Number);\n const minMajor = parts[0] ?? 0;\n const minMinor = parts[1] ?? 0;\n const minPatch = parts[2] ?? 0;\n if (version.major !== minMajor) return version.major > minMajor;\n if (version.minor !== minMinor) return version.minor > minMinor;\n return version.patch >= minPatch;\n}\n","import { realpath } from 'node:fs/promises';\nimport { type CanonicalPath, MIN_GIT_VERSION, type RepoFacts } from '../contract.ts';\nimport type { GitPortOptions } from './context.ts';\nimport { splitNul } from './nul-split.ts';\nimport { runGit } from './runner.ts';\nimport { isAtLeast, parseGitVersion } from './version.ts';\n\nconst canonical = async (path: string): Promise<CanonicalPath> => (await realpath(path)) as CanonicalPath;\n\n/**\n * `git worktree list` keeps reporting a linked worktree until `git worktree prune` runs, so its directory may be\n * gone (user cleanup, a crashed run, gc mid-flight — DESIGN 5.9). `facts` is what resume, doctor and MergeService\n * call to discover a run's worktrees: one stale entry must not make the whole repository unreadable, so an\n * unresolvable path is reported as git itself reports it (same rule as `resetHardClean`).\n */\nconst canonicalOrAsReported = async (path: string): Promise<CanonicalPath> =>\n (await realpath(path).catch(() => path)) as CanonicalPath;\n\ninterface WorktreeBlock {\n path: string;\n head: string | null;\n branch: string | null;\n detached: boolean;\n bare: boolean;\n locked: boolean;\n}\n\n/** In order: the local branch names a repository's default is expected to carry when no remote records one. */\nconst LOCAL_DEFAULT_BRANCHES: readonly string[] = Object.freeze(['main', 'master']);\n\nconst WORKTREE_PREFIX = 'worktree ';\nconst HEAD_PREFIX = 'HEAD ';\nconst BRANCH_PREFIX = 'branch refs/heads/';\n\n/** `git worktree list --porcelain -z`: blocks are consecutive non-empty lines, separated by an empty line. */\nfunction parseWorktreeList(raw: string): WorktreeBlock[] {\n const blocks: WorktreeBlock[] = [];\n let current: WorktreeBlock | null = null;\n for (const line of splitNul(raw)) {\n if (line === '') {\n current = null;\n continue;\n }\n if (line.startsWith(WORKTREE_PREFIX)) {\n current = {\n path: line.slice(WORKTREE_PREFIX.length),\n head: null,\n branch: null,\n detached: false,\n bare: false,\n locked: false,\n };\n blocks.push(current);\n continue;\n }\n if (!current) continue; // a line before any `worktree ` header: malformed input, defensively ignored\n if (line.startsWith(HEAD_PREFIX)) current.head = line.slice(HEAD_PREFIX.length);\n else if (line.startsWith(BRANCH_PREFIX)) current.branch = line.slice(BRANCH_PREFIX.length);\n else if (line === 'detached') current.detached = true;\n else if (line === 'bare') current.bare = true;\n else if (line === 'locked' || line.startsWith('locked ')) current.locked = true;\n }\n return blocks;\n}\n\n/** `facts` (DESIGN 5): version, default branch, HEAD kind, every worktree — one call, read-only. */\nexport async function facts(repo: CanonicalPath, ctx: GitPortOptions): Promise<RepoFacts> {\n const run = (args: readonly string[]) =>\n runGit({\n gitBinary: ctx.gitBinary,\n path: ctx.path,\n cwd: repo,\n args,\n timeoutMs: ctx.timeoutMs,\n allowExitCodes: [1],\n });\n\n const versionOut = await runGit({\n gitBinary: ctx.gitBinary,\n path: ctx.path,\n cwd: repo,\n args: ['--version'],\n timeoutMs: ctx.timeoutMs,\n });\n const version = parseGitVersion(versionOut.stdout);\n const supported = isAtLeast(version, MIN_GIT_VERSION);\n\n const commonDirOut = await runGit({\n gitBinary: ctx.gitBinary,\n path: ctx.path,\n cwd: repo,\n args: ['rev-parse', '--path-format=absolute', '--git-common-dir'],\n timeoutMs: ctx.timeoutMs,\n });\n const commonDir = await canonical(commonDirOut.stdout.trim());\n\n let head: RepoFacts['head'];\n const headSha = await run(['rev-parse', '--verify', '-q', 'HEAD']);\n if (headSha.exitCode !== 0) {\n head = { kind: 'unborn' };\n } else {\n const sha = headSha.stdout.trim();\n const symbolic = await run(['symbolic-ref', '--quiet', '--short', 'HEAD']);\n head = symbolic.exitCode === 0 ? { kind: 'branch', name: symbolic.stdout.trim(), sha } : { kind: 'detached', sha };\n }\n\n /**\n * DESIGN 5.1: \"Base = `origin/<default>` when it verifies, else local `<default>`\". `refs/remotes/origin/HEAD`\n * is written by `clone` (not `--single-branch`) and by an explicit `remote set-head`, and by nothing else — not\n * by `remote add` + `push -u`, and never in a local-only repository. The local fallback is therefore the common\n * case, not the exception, and `config --get init.defaultBranch` cannot serve as one: 5.0 runs git with\n * `GIT_CONFIG_GLOBAL=/dev/null` + `GIT_CONFIG_NOSYSTEM=1`, and that key is in practice a global setting.\n * `null` is left for a repository that has neither a conventional default branch nor a branch checked out.\n */\n let defaultBranch: string | null = null;\n const originHead = await run(['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD']);\n if (originHead.exitCode === 0) {\n const short = originHead.stdout.trim();\n defaultBranch = short.startsWith('origin/') ? short.slice('origin/'.length) : short || null;\n }\n if (defaultBranch === null) {\n for (const candidate of LOCAL_DEFAULT_BRANCHES) {\n const verified = await run(['rev-parse', '--verify', '--quiet', `refs/heads/${candidate}`]);\n if (verified.exitCode === 0) {\n defaultBranch = candidate;\n break;\n }\n }\n }\n if (defaultBranch === null && head.kind === 'branch') defaultBranch = head.name;\n\n const listOut = await runGit({\n gitBinary: ctx.gitBinary,\n path: ctx.path,\n cwd: repo,\n args: ['worktree', 'list', '--porcelain', '-z'],\n timeoutMs: ctx.timeoutMs,\n });\n const blocks = parseWorktreeList(listOut.stdout);\n const worktrees = await Promise.all(\n blocks.map(async (block) => ({\n path: await canonicalOrAsReported(block.path),\n branch: block.detached || block.bare ? null : block.branch,\n head: block.head,\n locked: block.locked,\n })),\n );\n\n return { gitVersion: version.raw, supported, commonDir, defaultBranch, head, worktrees };\n}\n","// DESIGN 5.4/5.5, ADR-0008 — plumbing merge: `merge-tree --write-tree` (no working tree) -> `commit-tree` ->\n// `update-ref` compare-and-swap. No hook ever runs (5.0's hardened config args cover every call here too).\nimport type { CanonicalPath } from '../contract.ts';\nimport type { GitPortOptions } from './context.ts';\nimport { splitNul } from './nul-split.ts';\nimport { GitCommandError, runGit } from './runner.ts';\n\nexport async function mergeTree(\n repo: CanonicalPath,\n ours: string,\n theirs: string,\n ctx: GitPortOptions,\n): Promise<{ clean: true; tree: string } | { clean: false; files: string[] }> {\n const out = await runGit({\n gitBinary: ctx.gitBinary,\n path: ctx.path,\n cwd: repo,\n args: ['merge-tree', '--write-tree', '--name-only', '-z', ours, theirs],\n timeoutMs: ctx.timeoutMs,\n allowExitCodes: [1],\n });\n const fields = splitNul(out.stdout);\n const tree = fields[0];\n if (tree === undefined) throw new Error('mergeTree: git produced no output');\n if (out.exitCode === 0) return { clean: true, tree };\n\n // `--name-only -z`: OID, then the conflicted paths, NUL-terminated, ending with one empty field before the\n // informational messages (Auto-merging / CONFLICT lines) we do not need here.\n const files: string[] = [];\n for (let index = 1; index < fields.length; index += 1) {\n const field = fields[index];\n if (field === undefined || field === '') break;\n files.push(field);\n }\n return { clean: false, files };\n}\n\nexport async function commitTree(\n repo: CanonicalPath,\n tree: string,\n parents: string[],\n message: string,\n trailers: Record<string, string>,\n ctx: GitPortOptions,\n): Promise<string> {\n const block = Object.entries(trailers)\n .map(([key, value]) => `${key}: ${value}`)\n .join('\\n');\n const fullMessage = block ? `${message}\\n\\n${block}\\n` : `${message}\\n`;\n // `commit-tree` reads its message from stdin when neither -m nor -F is given.\n const args = ['commit-tree', tree, ...parents.flatMap((parent) => ['-p', parent])];\n const out = await runGit({\n gitBinary: ctx.gitBinary,\n path: ctx.path,\n cwd: repo,\n args,\n timeoutMs: ctx.timeoutMs,\n identity: ctx.mergeIdentity,\n input: fullMessage,\n });\n return out.stdout.trim();\n}\n\n/**\n * The three messages git produces for a LOST compare-and-swap, and nothing else. Measured on git 2.50.1:\n * - `cannot lock ref '<r>': reference already exists` (empty oldvalue, the ref is there)\n * - `cannot lock ref '<r>': is at <sha> but expected <sha>` (oldvalue no longer current)\n * - `cannot lock ref '<r>': unable to resolve reference '<r>'` (oldvalue given, the ref is gone)\n * Plain lock-file contention (`cannot lock ref '<r>': Unable to create '<r>.lock': File exists.`) shares the\n * `cannot lock ref` prefix but is NOT a CAS loss: DESIGN 5.4 step (1) turns a `moved` into\n * `unexpected-repo-change`, so reporting contention as `moved` would tell the human the repository changed under\n * the run. It stays a `GitCommandError`, which the caller can retry.\n */\nconst CAS_LOST =\n /cannot lock ref .*(?:reference already exists|is at [0-9a-f]+ but expected|unable to resolve reference)/i;\n\n/** Atomic compare-and-swap. `expectedOld: null` means \"the ref must not already exist\" (git's empty-oldvalue rule). */\nexport async function updateRefCas(\n repo: CanonicalPath,\n ref: string,\n next: string,\n expectedOld: string | null,\n ctx: GitPortOptions,\n): Promise<'ok' | 'moved'> {\n try {\n await runGit({\n gitBinary: ctx.gitBinary,\n path: ctx.path,\n cwd: repo,\n args: ['update-ref', ref, next, expectedOld ?? ''],\n timeoutMs: ctx.timeoutMs,\n });\n return 'ok';\n } catch (error) {\n if (error instanceof GitCommandError && CAS_LOST.test(error.stderr)) return 'moved';\n throw error;\n }\n}\n\n/** `refs/cohorte/<runId>/review/<n>` — never updated during the run (DESIGN 5.5): minted once, CAS-created. */\nexport async function createRef(repo: CanonicalPath, ref: string, sha: string, ctx: GitPortOptions): Promise<void> {\n const result = await updateRefCas(repo, ref, sha, null, ctx);\n if (result === 'moved') throw new Error(`createRef: ${ref} already exists in ${repo}`);\n}\n","import type { SurfaceId } from '@cohorte/base';\nimport {\n type ArtifactDraft,\n type CanonicalPath,\n type FileTouch,\n GIT_DIFF_HARDENING_ARGS,\n GIT_PORCELAIN_ARGS,\n type SurfaceMap,\n} from '../contract.ts';\nimport type { GitPortOptions } from './context.ts';\nimport { splitNul } from './nul-split.ts';\nimport { runGit } from './runner.ts';\n\n/**\n * Splits a porcelain v2 `-z` line into its first `count` single-space-separated fields, plus the remainder as one\n * last element (the path, which under `-z` is neither quoted nor escaped and may itself contain spaces).\n */\nfunction splitFixed(line: string, count: number): string[] {\n const fields: string[] = [];\n let rest = line;\n for (let index = 0; index < count; index += 1) {\n const spaceIndex = rest.indexOf(' ');\n if (spaceIndex === -1) {\n fields.push(rest);\n rest = '';\n continue;\n }\n fields.push(rest.slice(0, spaceIndex));\n rest = rest.slice(spaceIndex + 1);\n }\n fields.push(rest);\n return fields;\n}\n\nfunction opOfXY(xy: string): 'create' | 'modify' | 'delete' {\n if (xy.includes('A')) return 'create';\n if (xy.includes('D')) return 'delete';\n return 'modify';\n}\n\n/**\n * `git status --porcelain=v2 -z`, exact parsing (DESIGN 5): every changed, untracked-but-not-ignored path.\n *\n * No `--ignore-submodules`: its default value is `all`, which would hide every submodule change (pointer move,\n * dirty submodule worktree) from the ownership audit of DESIGN 5.3 (b) and 5.4 (2) — a write into a submodule\n * would pass both enforcements unseen. Submodule entries are ordinary porcelain-v2 `1`/`2` records (the `<sub>`\n * field this parser skips at position 2), and `isDirty` agrees: the two status calls of this package see the same\n * set of changes.\n */\nexport async function changedPaths(worktree: CanonicalPath, ctx: GitPortOptions): Promise<FileTouch[]> {\n const out = await runGit({\n gitBinary: ctx.gitBinary,\n path: ctx.path,\n cwd: worktree,\n args: ['status', ...GIT_PORCELAIN_ARGS, '--untracked-files=all'],\n timeoutMs: ctx.timeoutMs,\n });\n const lines = splitNul(out.stdout);\n const touches: FileTouch[] = [];\n let index = 0;\n while (index < lines.length) {\n const line = lines[index] ?? '';\n index += 1;\n if (line === '') continue;\n const kind = line.charAt(0);\n if (kind === '1') {\n const fields = splitFixed(line, 8);\n touches.push({ path: fields[8] ?? '', op: opOfXY(fields[1] ?? '') });\n } else if (kind === '2') {\n // Renamed/copied: the `-z` new-path field is followed by one MORE NUL-terminated field, the origin path.\n const fields = splitFixed(line, 9);\n const origPath = lines[index] ?? '';\n index += 1;\n touches.push({ path: origPath, op: 'delete' });\n touches.push({ path: fields[9] ?? '', op: 'create' });\n } else if (kind === 'u') {\n const fields = splitFixed(line, 10);\n touches.push({ path: fields[10] ?? '', op: 'modify' });\n } else if (kind === '?') {\n touches.push({ path: line.slice(2), op: 'create' });\n }\n // '!' (ignored) is never emitted: `--ignored` is not passed, so git never reports one.\n }\n return touches;\n}\n\nexport async function diffBySurface(\n req: { repo: CanonicalPath; base: string; head: string; surfaces: SurfaceMap },\n ctx: GitPortOptions,\n): Promise<{ surface: SurfaceId | 'shared'; files: string[]; patch: ArtifactDraft }[]> {\n const nameStatusOut = await runGit({\n gitBinary: ctx.gitBinary,\n path: ctx.path,\n cwd: req.repo,\n args: ['diff', ...GIT_DIFF_HARDENING_ARGS, '--name-status', '-z', req.base, req.head],\n timeoutMs: ctx.timeoutMs,\n });\n const fields = splitNul(nameStatusOut.stdout);\n const bySurface = new Map<SurfaceId | 'shared', string[]>();\n const addPath = (path: string): void => {\n const surface = req.surfaces.surfaceOf(path);\n const bucket = bySurface.get(surface);\n if (bucket) bucket.push(path);\n else bySurface.set(surface, [path]);\n };\n let index = 0;\n while (index < fields.length) {\n const status = fields[index] ?? '';\n index += 1;\n if (status === '') continue;\n if (status.startsWith('R') || status.startsWith('C')) {\n addPath(fields[index] ?? '');\n index += 1;\n addPath(fields[index] ?? '');\n index += 1;\n } else {\n addPath(fields[index] ?? '');\n index += 1;\n }\n }\n\n const results: { surface: SurfaceId | 'shared'; files: string[]; patch: ArtifactDraft }[] = [];\n for (const [surface, files] of bySurface) {\n const patchOut = await runGit({\n gitBinary: ctx.gitBinary,\n path: ctx.path,\n cwd: req.repo,\n args: ['diff', ...GIT_DIFF_HARDENING_ARGS, req.base, req.head, '--', ...files],\n timeoutMs: ctx.timeoutMs,\n binary: true,\n });\n results.push({\n surface,\n files,\n patch: { kind: 'diff', mediaType: 'text/x-diff', bytes: patchOut.stdoutBytes ?? new Uint8Array() },\n });\n }\n return results;\n}\n","import { realpath } from 'node:fs/promises';\nimport { sep } from 'node:path';\nimport { type CanonicalPath, GIT_PORCELAIN_ARGS } from '../contract.ts';\nimport type { GitPortOptions } from './context.ts';\nimport { splitNul } from './nul-split.ts';\nimport { runGit } from './runner.ts';\n\nconst WORKTREE_PREFIX = 'worktree ';\n\n// `git worktree add` reads and writes the shared `.git/worktrees/` administrative area (duplicate-branch checks,\n// a fresh per-worktree admin directory). Two concurrent `add`s on the SAME repo can observe each other's\n// half-written admin state and fail outright (`failed to read .git/worktrees/<x>/commondir`) — reproduced on this\n// toolchain. Every writing agent's worktree is normally provisioned at once at run start, so this is not a rare\n// path: serialize `add` per repo, in-process, rather than let the run's own parallelism corrupt itself.\n//\n// IN-PROCESS ONLY, and deliberately so: DESIGN 5.6 takes the `project` lock SHARED, so two host processes may run\n// on one repository at the same time. Their `add`s are serialised by the caller's `project` / `integration` lease\n// (5.6), never by this Map, which one host process holds against itself alone.\nconst addWorktreeQueues = new Map<string, Promise<unknown>>();\n\nfunction serializedPerRepo<T>(repo: string, task: () => Promise<T>): Promise<T> {\n const previous = addWorktreeQueues.get(repo) ?? Promise.resolve();\n const settled = previous.catch(() => undefined);\n const run = settled.then(task);\n addWorktreeQueues.set(\n repo,\n run.catch(() => undefined),\n );\n return run;\n}\n\nasync function listWorktreePaths(anyWorktreeOfTheRepo: string, ctx: GitPortOptions): Promise<string[]> {\n const out = await runGit({\n gitBinary: ctx.gitBinary,\n path: ctx.path,\n cwd: anyWorktreeOfTheRepo,\n args: ['worktree', 'list', '--porcelain', '-z'],\n timeoutMs: ctx.timeoutMs,\n });\n const paths: string[] = [];\n for (const line of splitNul(out.stdout)) {\n if (line.startsWith(WORKTREE_PREFIX)) paths.push(line.slice(WORKTREE_PREFIX.length));\n }\n return paths;\n}\n\nexport async function addWorktree(\n req: { repo: CanonicalPath; path: CanonicalPath; branch: string | null; commit: string },\n ctx: GitPortOptions,\n): Promise<void> {\n const args: string[] =\n req.branch === null\n ? ['worktree', 'add', '--detach', req.path, req.commit]\n : ['worktree', 'add', '-b', req.branch, req.path, req.commit];\n await serializedPerRepo(req.repo, () =>\n runGit({ gitBinary: ctx.gitBinary, path: ctx.path, cwd: req.repo, args, timeoutMs: ctx.timeoutMs }),\n );\n}\n\n/** A slot still holds the previous agent's uncommitted or untracked work: {@link switchToNewBranch} refuses it. */\nexport class WorktreeDirtyError extends Error {\n readonly worktree: string;\n\n constructor(worktree: string) {\n super(\n `switchToNewBranch: ${worktree} is dirty — the previous agent's uncommitted or untracked work would be ` +\n `carried onto the new branch; commit it or quarantine the slot (resetHardClean) first`,\n );\n this.name = 'WorktreeDirtyError';\n this.worktree = worktree;\n }\n}\n\n/**\n * Slot reuse: a fresh branch for the worktree's next agent, at the current integration head.\n *\n * REFUSES a dirty slot. `git checkout -b` keeps uncommitted and untracked files across the switch, so the incoming\n * agent would start on work it never did — and the next `commitAll` would attribute it to that agent, past an\n * ownership audit (5.3 b) that only notices when the leftover happens to fall outside its write globs. DESIGN 5.2 /\n * ADR-0021 §3 place the branch AT `at`; the decision to discard the leftovers is the caller's (`resetHardClean`),\n * never this method's.\n */\nexport async function switchToNewBranch(\n req: { worktree: CanonicalPath; branch: string; at: string },\n ctx: GitPortOptions,\n): Promise<void> {\n if (await isDirty(req.worktree, ctx)) throw new WorktreeDirtyError(req.worktree);\n await runGit({\n gitBinary: ctx.gitBinary,\n path: ctx.path,\n cwd: req.worktree,\n args: ['checkout', '-q', '-b', req.branch, req.at],\n timeoutMs: ctx.timeoutMs,\n });\n}\n\nasync function isDirty(worktree: CanonicalPath, ctx: GitPortOptions): Promise<boolean> {\n const status = await runGit({\n gitBinary: ctx.gitBinary,\n path: ctx.path,\n cwd: worktree,\n args: ['status', ...GIT_PORCELAIN_ARGS, '--untracked-files=all'],\n timeoutMs: ctx.timeoutMs,\n });\n return status.stdout.length > 0;\n}\n\n/** `opts.force` is always `false` (the type says so): DESIGN 5 never lets Cohorte discard an agent's own work here. */\nexport async function removeWorktree(\n path: CanonicalPath,\n _opts: { force: false },\n ctx: GitPortOptions,\n): Promise<'removed' | 'dirty-kept'> {\n if (await isDirty(path, ctx)) return 'dirty-kept';\n try {\n await runGit({\n gitBinary: ctx.gitBinary,\n path: ctx.path,\n cwd: path,\n args: ['worktree', 'remove', '--', path],\n timeoutMs: ctx.timeoutMs,\n });\n return 'removed';\n } catch (error) {\n // A race between the check above and the remove itself: re-check rather than trust git's error text.\n if (await isDirty(path, ctx)) return 'dirty-kept';\n throw error;\n }\n}\n\n/**\n * Quarantine path only (DESIGN 5.1, ADR-0021 §1), the ONE destructive method of this port. Three guards, in order:\n *\n * 1. the canonicalised target must resolve under the canonicalised `git.worktreeRoot` — the root Cohorte itself\n * provisions. Without it \"a registered worktree\" is self-referential (`git worktree list` is run from the\n * target, so the target is in its own list by construction) and ANY linked worktree of ANY repository on the\n * machine would be accepted, uncommitted user work included. Compared at a path SEPARATOR, never as a bare\n * string prefix: `<root>-evil` is not below `<root>`.\n * 2. it must be a registered worktree of its repository (a directory git does not know is never touched);\n * 3. it must not be the main worktree (always the first entry of `git worktree list`, per git's documented\n * ordering), which shares the same history but is the user's own checkout.\n */\nexport async function resetHardClean(worktree: CanonicalPath, to: string, ctx: GitPortOptions): Promise<void> {\n const target = await realpath(worktree);\n const root = await realpath(ctx.worktreeRoot).catch(() => {\n throw new Error(`resetHardClean: the configured worktree root ${ctx.worktreeRoot} does not resolve on disk`);\n });\n if (target !== root && !target.startsWith(root + sep)) {\n throw new Error(`resetHardClean: refuses ${target}, which is outside the worktree root ${root}`);\n }\n\n const registered = await listWorktreePaths(worktree, ctx).catch(() => {\n throw new Error(`resetHardClean: ${target} is not a registered worktree of its repository`);\n });\n const resolved = await Promise.all(registered.map((candidate) => realpath(candidate).catch(() => candidate)));\n const position = resolved.indexOf(target);\n if (position === -1) {\n throw new Error(`resetHardClean: ${target} is not a registered worktree of its repository`);\n }\n if (position === 0) {\n throw new Error(`resetHardClean: refuses to operate on ${target}, the main worktree`);\n }\n\n await runGit({\n gitBinary: ctx.gitBinary,\n path: ctx.path,\n cwd: target,\n args: ['reset', '--hard', to],\n timeoutMs: ctx.timeoutMs,\n });\n await runGit({\n gitBinary: ctx.gitBinary,\n path: ctx.path,\n cwd: target,\n args: ['clean', '-fdx', '--'],\n timeoutMs: ctx.timeoutMs,\n });\n}\n","// DESIGN 5 (GitPort). EVERY method funnels through `runGit` (`./runner.ts`), the hardened invocation of 5.0.\nimport type { GitPort } from '../contract.ts';\nimport { commitAll, findCommitByTrailer } from './commits.ts';\nimport type { GitPortOptions } from './context.ts';\nimport { facts } from './facts.ts';\nimport { commitTree, createRef, mergeTree, updateRefCas } from './merge.ts';\nimport { changedPaths, diffBySurface } from './status.ts';\nimport { treeDigest } from './tree-digest.ts';\nimport { addWorktree, removeWorktree, resetHardClean, switchToNewBranch } from './worktrees.ts';\n\nexport type { GitPortOptions } from './context.ts';\nexport { GitCommandError } from './runner.ts';\nexport { WorktreeDirtyError } from './worktrees.ts';\n\nexport function createGitPort(options: GitPortOptions): GitPort {\n return {\n facts: (repo) => facts(repo, options),\n treeDigest: (worktree, opts) => treeDigest(worktree, opts, options),\n addWorktree: (req) => addWorktree(req, options),\n switchToNewBranch: (req) => switchToNewBranch(req, options),\n removeWorktree: (path, opts) => removeWorktree(path, opts, options),\n resetHardClean: (worktree, to) => resetHardClean(worktree, to, options),\n commitAll: (req) => commitAll(req, options),\n findCommitByTrailer: (repo, branch, key, value) => findCommitByTrailer(repo, branch, key, value, options),\n mergeTree: (repo, ours, theirs) => mergeTree(repo, ours, theirs, options),\n commitTree: (repo, tree, parents, message, trailers) => commitTree(repo, tree, parents, message, trailers, options),\n updateRefCas: (repo, ref, next, expectedOld) => updateRefCas(repo, ref, next, expectedOld, options),\n createRef: (repo, ref, sha) => createRef(repo, ref, sha, options),\n diffBySurface: (req) => diffBySurface(req, options),\n changedPaths: (worktree) => changedPaths(worktree, options),\n };\n}\n","// `@cohorte/persistence/blob` — file-backed content-addressed storage.\n\nimport { mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { CohorteError, errorOf, type Sha256, sha256Hex } from '@cohorte/base';\nimport type { BlobStore } from '../contract.ts';\n\nexport interface BlobStoreOptions {\n /** `<state dir>/cas`: sharded by the first two hex digits, written atomically (temp + rename), mode 0600 */\n dir: string;\n}\n\nconst ADDRESS = /^[a-f0-9]{64}$/;\n\nfunction addressPath(root: string, sha256: Sha256): string {\n if (!ADDRESS.test(sha256)) throw new TypeError(`invalid blob address: ${sha256}`);\n return join(root, sha256.slice(0, 2), sha256);\n}\n\nexport function createBlobStore(options: BlobStoreOptions): BlobStore {\n const root = options.dir;\n return {\n async put(bytes): Promise<{ sha256: Sha256; bytes: number }> {\n const sha256 = sha256Hex(bytes);\n const destination = addressPath(root, sha256);\n await mkdir(join(root, sha256.slice(0, 2)), { recursive: true, mode: 0o700 });\n try {\n await stat(destination);\n } catch {\n const temporary = join(\n root,\n sha256.slice(0, 2),\n `.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`,\n );\n await writeFile(temporary, bytes, { mode: 0o600 });\n try {\n await rename(temporary, destination);\n } catch (error) {\n await writeFile(destination, bytes, { mode: 0o600 }).catch(() => {\n throw error;\n });\n }\n }\n return { sha256, bytes: bytes.byteLength };\n },\n async read(sha256): Promise<Uint8Array> {\n const bytes = await readFile(addressPath(root, sha256));\n if (sha256Hex(bytes) !== sha256) {\n throw new CohorteError(errorOf('security/pin-tampered', `blob ${sha256} no longer hashes to its address`));\n }\n return Uint8Array.from(bytes);\n },\n async has(sha256): Promise<boolean> {\n try {\n await stat(addressPath(root, sha256));\n return true;\n } catch {\n return false;\n }\n },\n };\n}\n","// `@cohorte/persistence/spool` — bounded, file-backed NDJSON tail.\n\nimport { appendFileSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { RunId } from '@cohorte/base';\nimport { compareOrder } from '@cohorte/protocol';\nimport type { EphemeralSpool } from '../contract.ts';\n\nexport interface EphemeralSpoolOptions {\n /** `<state dir>/runs`: one bounded NDJSON spool file per run */\n dir: string;\n maxBytes?: number;\n}\n\ninterface Line {\n sequence: number;\n sub: number;\n text: string;\n}\n\nfunction parse(line: string): Line {\n if (line.includes('\\n')) throw new TypeError('spool: one line per append');\n const value: unknown = JSON.parse(line);\n const { sequence, sub } = (typeof value === 'object' && value !== null ? value : {}) as Record<string, unknown>;\n if (\n typeof sequence !== 'number' ||\n typeof sub !== 'number' ||\n !Number.isSafeInteger(sequence) ||\n !Number.isSafeInteger(sub)\n ) {\n throw new TypeError('spool: a line is one JSON object with an integer `sequence` and `sub`');\n }\n return { sequence, sub, text: line };\n}\n\nexport function createEphemeralSpool(options: EphemeralSpoolOptions): EphemeralSpool {\n const root = options.dir;\n const maxBytes = options.maxBytes ?? 4 * 1024 * 1024;\n if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new RangeError('spool maxBytes must be positive');\n const pathFor = (runId: RunId): string => join(root, `${runId}.ndjson`);\n const readLines = (runId: RunId): Line[] => {\n try {\n return readFileSync(pathFor(runId), 'utf8').split('\\n').filter(Boolean).map(parse).sort(compareOrder);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw error;\n }\n };\n const trim = (runId: RunId): void => {\n const path = pathFor(runId);\n const bytes = readFileSync(path);\n if (bytes.byteLength <= maxBytes) return;\n const lines = readLines(runId);\n const kept = lines.map((line) => line.text);\n while (kept.length > 0 && Buffer.byteLength(`${kept.join('\\n')}\\n`) > maxBytes) kept.shift();\n const temporary = `${path}.tmp-${process.pid}-${Date.now()}`;\n writeFileSync(temporary, kept.length ? `${kept.join('\\n')}\\n` : '', { mode: 0o600 });\n renameSync(temporary, path);\n };\n mkdirSync(root, { recursive: true, mode: 0o700 });\n return {\n append(runId, line): void {\n parse(line);\n appendFileSync(pathFor(runId), `${line}\\n`, { mode: 0o600 });\n trim(runId);\n },\n async *tail(runId, after, signal): AsyncIterable<string> {\n let cursor = after;\n while (!signal.aborted) {\n const next = readLines(runId).find((line) => compareOrder(line, cursor) > 0);\n if (next) {\n cursor = { sequence: next.sequence, sub: next.sub };\n yield next.text;\n continue;\n }\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, 20);\n signal.addEventListener(\n 'abort',\n () => {\n clearTimeout(timer);\n resolve();\n },\n { once: true },\n );\n });\n }\n },\n };\n}\n","// DESIGN 1.2 port table (\"`ToolRegistry`, `WorkspaceReader` | `tools`\") — the `ToolRegistry` type, frozen in Wave 0\n// so `core/src/contract/ports.ts` can name it without importing `packages/tools/src/impl/**`. The factory,\n// `createToolRegistry(impls)`, is Wave 2's (`U2.03`): \"implementations are PASSED IN by the composition root: this\n// unit never imports U2.04\" (PLAN U2.03) — U0.08 (this unit) never imports `impl/**` here either, for the same\n// reason: only the TYPE is frozen now, the lookup table is built once every tool is real.\nimport type { ToolImplementation } from '../catalogue/index.ts';\n\n/** `CohorteToolHost` stage 7 looks a tool up by name (`plan`/`execute`), inside its per-slot effect mutex. */\nexport interface ToolRegistry {\n get(tool: string): ToolImplementation | undefined;\n names(): readonly string[];\n}\n\nexport function createToolRegistry(implementations: Readonly<Record<string, ToolImplementation>>): ToolRegistry {\n const entries = new Map(Object.entries(implementations));\n return Object.freeze({\n get: (tool: string) => entries.get(tool),\n names: () => Object.freeze([...entries.keys()]),\n });\n}\n","// DESIGN 2.7 — gated reads/lists for ContextBuilder, using the same resolver and grant rules as tools.\nimport { createHash } from 'node:crypto';\nimport { readdir, readFile } from 'node:fs/promises';\nimport { join, relative } from 'node:path';\nimport { type ErrorInfo, err, errorOf, ok, type Result, type Sha256 } from '@cohorte/base';\nimport type { AgentGrant, CanonicalPath, GlobMatcher, GlobSet, PathResolver } from '@cohorte/security/contract';\n\nexport interface WorkspaceReader {\n read(\n root: CanonicalPath,\n rel: string,\n grant: AgentGrant,\n ): Promise<Result<{ bytes: Uint8Array; sha256: Sha256 }, ErrorInfo>>;\n list(root: CanonicalPath, globs: GlobSet, grant: AgentGrant): Promise<string[]>;\n}\n\nexport interface WorkspaceReaderDeps {\n paths: PathResolver;\n globs: GlobMatcher;\n}\n\nconst digest = (bytes: Uint8Array): Sha256 => createHash('sha256').update(bytes).digest('hex') as Sha256;\nconst denied = (detail: string): Result<never, ErrorInfo> => err(errorOf('permission/path-outside-grant', detail));\n\nfunction grantAllows(path: { relative: string }, grant: AgentGrant, globs: GlobMatcher, intent: 'read' | 'write') {\n return !globs.isDenied(path.relative, grant, intent);\n}\n\n/** The only filesystem reader used by ContextBuilder. Every requested path is resolved and grant-filtered first. */\nexport function createWorkspaceReader(deps: WorkspaceReaderDeps): WorkspaceReader {\n return {\n async read(root, rel, grant) {\n const resolved = deps.paths.resolve(rel, root, 'read');\n if (!resolved.ok) return denied(resolved.error.detail);\n if (!grantAllows(resolved.value, grant, deps.globs, 'read')) return denied(`read denied for ${rel}`);\n if (!resolved.value.exists) return denied(`read target does not exist: ${rel}`);\n try {\n const bytes = await readFile(resolved.value.canonical);\n if (bytes.byteLength > 256 * 1024) return denied(`read target exceeds the 256 KiB context limit: ${rel}`);\n if (bytes.includes(0)) return denied(`binary read target refused: ${rel}`);\n return ok({ bytes, sha256: digest(bytes) });\n } catch {\n return denied(`read target is not accessible: ${rel}`);\n }\n },\n\n async list(root, globs, grant) {\n const resolvedRoot = deps.paths.resolve('.', root, 'list');\n if (!resolvedRoot.ok || !grantAllows(resolvedRoot.value, grant, deps.globs, 'read')) return [];\n const found: string[] = [];\n async function walk(current: string): Promise<void> {\n for (const entry of await readdir(current, { withFileTypes: true })) {\n if (entry.isSymbolicLink()) continue;\n const absolute = join(current, entry.name);\n const rel = relative(root, absolute).split('\\\\').join('/');\n const candidate = deps.paths.resolve(rel, root, 'read');\n if (!candidate.ok || !candidate.value.exists || !grantAllows(candidate.value, grant, deps.globs, 'read'))\n continue;\n if (entry.isDirectory()) await walk(absolute);\n else if (deps.globs.matches(candidate.value.relative, globs)) found.push(candidate.value.relative);\n }\n }\n await walk(resolvedRoot.value.canonical);\n return found.sort();\n },\n };\n}\n","// The production host composition. This file is intentionally the only CLI\n// module that knows how the durable core, git, policy, tools and runtime fit\n// together. Commands only see the HostRunner seam.\nimport { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport type { AgentId, IdSource, RunId, Sha256 } from '@cohorte/base';\nimport { canonicalJson, sha256Hex, systemClock } from '@cohorte/base';\nimport { loadConfig, resolveConfig } from '@cohorte/config';\nimport { literalPrefixOf } from '@cohorte/config/schema';\nimport {\n type AgentPlan,\n createAgentSupervisor,\n createApprovalService,\n createEffectJournal,\n createEngine,\n createEventWriter,\n createGrantComputer,\n createIntegrationService,\n createLeaseManager,\n createPhaseContracts,\n createPhaseExecutor,\n createPipelineGuards,\n createProvisioner,\n createResumer,\n createRunSnapshotter,\n createToolHost,\n createToolHostReplay,\n createTransitionEffectRunner,\n createWorktreeService,\n type HostContext,\n type LoopPolicy,\n type PhaseRunContext,\n type RunEngine,\n type RunState,\n} from '@cohorte/core';\nimport { mapRuntimeEvent } from '@cohorte/core/agents/supervisor';\nimport { createFactCollector } from '@cohorte/core/pipeline/guards';\nimport { resolveTable } from '@cohorte/core/pipeline/tables';\nimport { createBuiltinEffectVerifiers } from '@cohorte/core/resume';\nimport type { CanonicalPath, GitPort } from '@cohorte/git/contract';\nimport { createGitPort } from '@cohorte/git/impl';\nimport { createBlobStore } from '@cohorte/persistence/blob';\nimport type { LeaseToken, StateStore } from '@cohorte/persistence/contract';\nimport { createEphemeralSpool } from '@cohorte/persistence/spool';\nimport { AgentOutput, type AgentOutput as AgentOutputValue, compileSchema } from '@cohorte/protocol';\nimport type { RuntimeHostBindings, SpawnRequest } from '@cohorte/runtime-contract';\nimport { createFakeRuntimeProvider, FAKE_CAPABILITIES, fakeScript, loadFakeScriptFile } from '@cohorte/runtime-fake';\nimport { createPiRuntimeProvider } from '@cohorte/runtime-pi';\nimport { piCapabilities } from '@cohorte/runtime-pi/capabilities';\nimport { createCommandAuthenticator, createKeyStore, createTrustStore } from '@cohorte/security/auth';\nimport type { PolicyPorts, AgentGrant as SecurityAgentGrant } from '@cohorte/security/contract';\nimport { createCommandPolicy, createProgramResolver } from '@cohorte/security/decide/commands';\nimport { buildPolicySnapshot, createPolicyEngine } from '@cohorte/security/decide/gate';\nimport { createGlobMatcher, createPathResolver } from '@cohorte/security/decide/paths';\nimport { createExecutor, createNoneBackend } from '@cohorte/security/exec';\nimport { createRedactor } from '@cohorte/security/redact';\nimport { TOOL_CATALOGUE, toolIntrospection } from '@cohorte/tools/catalogue';\nimport { createToolRegistry } from '@cohorte/tools/registry';\nimport { createWorkspaceReader } from '@cohorte/tools/workspace';\nimport { createAssetSource } from '../assets/index.ts';\nimport type { HostRunner, InstallInspector, OpenStore } from '../contract/index.ts';\nimport { createRunHost } from '../host/index.ts';\nimport { verifyPinnedInstall } from '../pin/index.ts';\n\nfunction createHostProcessSweeper() {\n return {\n isAlive(pid: number): 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: number, _startToken: string, 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\nfunction createVerifierRegistry(verifiers: ReturnType<typeof createBuiltinEffectVerifiers>) {\n return { get: (kind: Parameters<typeof verifiers.get>[0]) => verifiers.get(kind) };\n}\n\nconst canonical = (value: string): CanonicalPath => {\n const absolute = resolve(value);\n try {\n return realpathSync.native(absolute) as CanonicalPath;\n } catch {\n return absolute as CanonicalPath;\n }\n};\n\nfunction pidRegistry() {\n const entries = new Set<number>();\n return {\n record(entry: { pgid: number; startToken: string; label: string }) {\n if (entry.pgid > 0) entries.add(entry.pgid);\n },\n remove(pgid: number) {\n entries.delete(pgid);\n },\n };\n}\n\nfunction gitBinary(pathValue: string): string {\n for (const candidate of ['/usr/bin/git', '/opt/homebrew/bin/git', '/usr/local/bin/git']) {\n try {\n return realpathSync.native(candidate);\n } catch {\n /* try the next pinned location */\n }\n }\n return (\n pathValue\n .split(':')\n .map((entry) => join(entry, 'git'))\n .find((entry) => {\n try {\n realpathSync.native(entry);\n return true;\n } catch {\n return false;\n }\n }) ?? 'git'\n );\n}\n\nfunction loopPolicy() {\n return {\n maxFixRounds: 3,\n noProgressWindow: 3,\n maxDeniedCallsPerAgent: 3,\n runWallClockMs: 24 * 60 * 60 * 1000,\n escalation: { sameFailureCount: 2, ladder: [], maxPerRun: 0 },\n } as unknown as LoopPolicy;\n}\n\nfunction noStop(\n _run: RunState,\n facts: RunState extends never ? never : { cancelRequested: boolean; pauseRequested: boolean },\n) {\n if (facts.cancelRequested) return { reason: 'cancelled' as const, detail: 'cancel requested', resumable: false };\n if (facts.pauseRequested) return { reason: 'paused' as const, detail: 'pause requested', resumable: true };\n return null;\n}\n\ninterface ProductionEngineOptions {\n readonly store: StateStore;\n readonly openStore: OpenStore;\n readonly cwd: string;\n readonly home: string;\n readonly env: NodeJS.ProcessEnv;\n readonly ids: IdSource;\n readonly install: InstallInspector;\n readonly runId?: RunId;\n readonly hostIdentity?: { hostId: string; pid: number; startToken: string };\n readonly assetsTreeSha256?: Sha256;\n}\n\n/** Build one engine for one run. All concrete dependencies stay in this file. */\nexport async function createProductionEngine(options: ProductionEngineOptions): Promise<RunEngine> {\n const loaded = await loadConfig({ cwd: options.cwd, home: options.home });\n const keys = createKeyStore({ directory: join(options.home, '.cohorte', 'keys') });\n const trust = createTrustStore({ directory: join(options.home, '.cohorte', 'trust'), keys });\n const resolved = await resolveConfig(loaded, {\n trustStore: trust,\n projectKeyId: sha256Hex(loaded.projectRoot).slice(0, 24),\n trustProjectConfig: true,\n });\n if (resolved.status !== 'resolved') throw new Error('security/project-policy-untrusted: host config is not trusted');\n\n const root = canonical(loaded.projectRoot);\n const worktreeProjectKey = sha256Hex(loaded.projectRoot).slice(0, 24);\n const worktreeBaseRoot = canonical(join(options.home, '.cohorte', 'worktrees'));\n const worktreeRoot = canonical(\n join(options.home, '.cohorte', 'worktrees', worktreeProjectKey, options.runId ?? 'pending'),\n );\n mkdirSync(worktreeBaseRoot, { recursive: true });\n mkdirSync(worktreeRoot, { recursive: true });\n const gitPath = options.env.PATH ?? '/usr/bin:/bin';\n const git = createGitPort({\n gitBinary: gitBinary(gitPath),\n path: gitPath,\n mergeIdentity: { name: 'Cohorte', email: 'cohorte@localhost' },\n worktreeRoot,\n });\n const redactor = createRedactor();\n const spool = createEphemeralSpool({ dir: join(loaded.projectRoot, '.cohorte', 'state', 'spool') });\n const events = createEventWriter({ redactor, clock: systemClock, ids: options.ids, spool });\n const journal = createEffectJournal({ store: options.store, events, clock: systemClock, redactor });\n const leases = createLeaseManager({ store: options.store, clock: systemClock }, options.hostIdentity);\n const executor = createExecutor({ redactor, pids: pidRegistry(), clock: systemClock, backend: createNoneBackend() });\n const paths = createPathResolver({\n roots: [root, worktreeBaseRoot, worktreeRoot],\n protectedRoots: [canonical(join(loaded.projectRoot, '.cohorte')), canonical(join(loaded.projectRoot, '.git'))],\n symlinks: resolved.config.policy.symlinks,\n });\n const globs = createGlobMatcher();\n createWorkspaceReader({ paths, globs });\n const pathDirs = gitPath.split(':').filter(Boolean).map(canonical);\n const programs = createProgramResolver({ pathDirs });\n const branches: PolicyPorts['branches'] = {\n branchOf(cwd) {\n try {\n const facts = (git as GitPort).facts(cwd);\n void facts;\n } catch {\n return { kind: 'detached-or-unknown', protected: true };\n }\n return { kind: 'detached-or-unknown', protected: true };\n },\n };\n const commandPolicy = createCommandPolicy({ programs, branches });\n const policy = createPolicyEngine({ tools: toolIntrospection, globs, commands: commandPolicy });\n const policySnapshot = buildPolicySnapshot(resolved.config, loaded.ownership, { sandboxLevel: 'L0-process' });\n const policyPorts: PolicyPorts = {\n paths,\n branches,\n programs,\n budgets: { remaining: () => ({}), callsInLastMinute: () => 0 },\n clock: systemClock,\n };\n const integrationPath = canonical(join(worktreeRoot, '_integration'));\n const integrationBranch = `cohorte/${options.runId ?? 'unknown'}/integration`;\n const worktrees = createWorktreeService({\n git,\n journal,\n events,\n runId: options.runId as RunId,\n repo: root,\n root: worktreeRoot,\n integrationHead: 'HEAD',\n });\n const rawIntegration = createIntegrationService({ git, journal, events });\n const pathForSlot = (slot: string): CanonicalPath =>\n slot === '_integration' ? integrationPath : canonical(join(worktreeRoot, slot));\n const integration = {\n async commit(slot: string, kind: 'result' | 'checkpoint', paths?: readonly string[]) {\n return rawIntegration.commit(pathForSlot(slot), kind, paths === undefined ? undefined : [...paths]);\n },\n async merge(fromSlot: string, intoSlot: string) {\n const result = await rawIntegration.merge(pathForSlot(fromSlot), pathForSlot(intoSlot));\n if ('mergeSha' in result) await git.resetHardClean(integrationPath, result.mergeSha);\n return result;\n },\n };\n const grantComputer = createGrantComputer({});\n const acceptedOutputs = new Map<AgentId, AgentOutputValue>();\n const agentWorkspaceRoots = new Map<AgentId, CanonicalPath>();\n const workspaceRootForPlan = (plan: AgentPlan): CanonicalPath =>\n plan.workspace.kind === 'slot' ? pathForSlot(plan.workspace.slot) : integrationPath;\n const workspaceRootForAgent = (agentId: AgentId): CanonicalPath => {\n const assigned = agentWorkspaceRoots.get(agentId);\n if (assigned) return assigned;\n // Runtime tool calls can arrive after the request map has been recreated\n // by a provider. Agent ids are deterministic (`agt_<role>_<slot>`), so\n // retain the slot isolation even when that callback is not the same\n // object instance that populated agentWorkspaceRoots.\n const marker = '_';\n const separator = agentId.lastIndexOf(marker);\n if (separator > 0 && separator < agentId.length - 1) {\n const slot = agentId.slice(separator + marker.length);\n return pathForSlot(slot);\n }\n return root;\n };\n const validateAgentOutput = compileSchema(AgentOutput);\n let activeLease: LeaseToken | undefined;\n const grantFor = (_call: Parameters<typeof policy.evaluate>[0]): SecurityAgentGrant => {\n const workspace = workspaceRootForAgent(_call.agentId);\n const grant = grantComputer.compute({\n role: 'implementer',\n ownedPaths: ['**'],\n tools: Object.keys(TOOL_CATALOGUE),\n });\n return { ...grant, roots: { workspace, readOnly: [] } };\n };\n const toolHostDeps = {\n policy,\n paths,\n toolRegistry: createToolRegistry(TOOL_CATALOGUE),\n journal,\n events,\n approvals: createApprovalService({ store: options.store, events, clock: systemClock, ids: options.ids, redactor }),\n redactor,\n policySnapshot,\n policyPorts,\n grantFor,\n grantKeyFor: (call: Parameters<typeof policy.evaluate>[0], verdict: { normalized: unknown }) =>\n sha256Hex(canonicalJson({ call, normalized: verdict.normalized } as never)),\n executionFor: (call: Parameters<typeof policy.evaluate>[0]) => ({\n runId: call.runId,\n agentId: call.agentId,\n incarnation: call.incarnation,\n toolCallId: call.toolCallId,\n role: call.role,\n grant: grantFor(call),\n workspaceRoot: workspaceRootForAgent(call.agentId),\n paths,\n executor,\n git,\n requestApproval: async () => ({ decision: 'deny' as const }),\n acceptResult: async (output: AgentOutputValue) => {\n const checked = validateAgentOutput(output);\n if (!checked.ok) return { accepted: false, reason: checked.error.map((issue) => issue.message).join('; ') };\n acceptedOutputs.set(call.agentId, checked.value);\n return { accepted: true };\n },\n }),\n leaseFor: () => {\n if (!activeLease) throw new Error('conflict/lease-lost: tool call has no active run lease');\n return activeLease;\n },\n sandbox: executor.capabilities(),\n requestApproval: async () => ({ decision: 'deny' as const }),\n recordRequested: async (call: Parameters<typeof policy.evaluate>[0]) => {\n if (!activeLease) throw new Error('conflict/lease-lost: tool request has no active run lease');\n await options.store.transact({ runId: call.runId }, activeLease, (tx) =>\n events.append(tx, [\n {\n type: 'tool.requested',\n payload: {\n toolCallId: call.toolCallId,\n tool: call.tool,\n args: call.input,\n argsSha256: sha256Hex(canonicalJson(call.input as never)),\n },\n source: 'cohorte',\n summary: `tool requested: ${call.tool}`,\n severity: 'info',\n },\n ]),\n );\n },\n recordDenied: async (call: Parameters<typeof policy.evaluate>[0], verdict: ReturnType<typeof policy.evaluate>) => {\n if (!activeLease) throw new Error('conflict/lease-lost: tool denial has no active run lease');\n await options.store.transact({ runId: call.runId }, activeLease, (tx) =>\n events.append(tx, [\n {\n type: 'tool.denied',\n payload: {\n toolCallId: call.toolCallId,\n tool: call.tool,\n stage: verdict.stage,\n ruleId: verdict.ruleId,\n reason: verdict.reason,\n overridable: verdict.overridable,\n evaluatedRules: verdict.evaluatedRules,\n ...(verdict.approvalId === undefined ? {} : { approvalId: verdict.approvalId }),\n },\n source: 'cohorte',\n summary: `tool denied: ${call.tool}`,\n severity: 'warning',\n },\n ]),\n );\n },\n };\n const toolHost = createToolHost(toolHostDeps);\n const pending = options.runId ? await options.store.pendingCommands(options.runId) : [];\n const requestedStart = pending.find((command) => command.envelope.type === 'start')?.envelope.payload as\n | { runtime?: string; fakeScript?: string }\n | undefined;\n const fakeDefaultScript = fakeScript()\n .agent({}, [{ do: 'submit', output: { status: 'clean' } }])\n .build();\n const fakeRuntimeScript =\n requestedStart?.fakeScript === undefined\n ? fakeDefaultScript\n : (() => {\n const loadedScript = loadFakeScriptFile(resolve(root, requestedStart.fakeScript));\n if (!loadedScript.ok) throw new Error(`${loadedScript.error.code}: ${loadedScript.error.message}`);\n return loadedScript.value;\n })();\n const provider =\n (requestedStart?.runtime ?? resolved.config.runtime.id) === 'pi'\n ? createPiRuntimeProvider({ installDir: options.install.installDir(), redactor })\n : createFakeRuntimeProvider({ script: fakeRuntimeScript, clock: systemClock });\n const assets = createAssetSource();\n const shippedPromptIds = ['agents/fixer', 'agents/implementer', 'agents/reviewer', 'agents/security-reviewer'];\n const pinnedPromptPaths = new Map<string, { path: string; sha256: Sha256; bytes: number }>();\n const pinStore = createBlobStore({ dir: join(loaded.projectRoot, '.cohorte', 'state', 'cas') });\n const runtimePin = await provider.pin();\n const sandboxCapabilities = executor.capabilities();\n const snapshotter = createRunSnapshotter({\n installInspector: options.install,\n clock: systemClock,\n pinStore,\n metadata: {\n app: { version: '3.0.0-dev.1', gitHash: null },\n packages: [],\n assets: {\n treeSha256: options.assetsTreeSha256 ?? ('0'.repeat(64) as unknown as Sha256),\n embeddedTreeSha256: options.assetsTreeSha256 ?? ('0'.repeat(64) as unknown as Sha256),\n },\n schemas: { stateSchemaVersion: 1, configSchemaVersion: 1, transitionTableVersion: 1 },\n prompts: [],\n skills: [],\n environment: {\n pinnedPath: (options.env.PATH ?? '').split(':').filter(Boolean),\n platform: process.platform,\n arch: process.arch,\n sandbox: sandboxCapabilities,\n runtimeCapabilities:\n provider.id === 'fake' ? FAKE_CAPABILITIES : piCapabilities('stop-after-turn', process.platform),\n },\n readFile: async (path) => Uint8Array.from(readFileSync(path)),\n },\n });\n const bindings: RuntimeHostBindings = {\n toolHost,\n stateDir: (runId, agentId, incarnation) =>\n join(loaded.projectRoot, '.cohorte', 'runs', runId, agentId, String(incarnation)),\n clock: systemClock,\n ids: options.ids,\n log: (_level, _message) => undefined,\n };\n const supervisor = createAgentSupervisor({\n runtimeProvider: provider,\n bindings,\n events,\n clock: systemClock,\n ids: options.ids,\n onRuntimeEvent: (event) => {\n const mapped = mapRuntimeEvent(event);\n if (mapped === null) return;\n if (mapped.durability === 'ephemeral') {\n events.ephemeral(options.runId as RunId, mapped.draft);\n return;\n }\n if (!activeLease) throw new Error('conflict/lease-lost: runtime event has no active run lease');\n return options.store.transact({ runId: options.runId as RunId }, activeLease, (tx) => {\n events.append(tx, [mapped.draft]);\n });\n },\n requestFor: async (plan, ctx, incarnation): Promise<SpawnRequest> => {\n const workspaceRoot = workspaceRootForPlan(plan);\n agentWorkspaceRoots.set(plan.agentId, workspaceRoot);\n const prompt = pinnedPromptPaths.get(plan.promptId);\n if (!prompt) throw new Error(`security/prompt-not-pinned: ${plan.promptId}`);\n const taskText = [\n `# ${plan.task.role}`,\n '',\n plan.task.objective,\n '',\n `Owned paths: ${plan.task.ownedPaths.join(', ') || '(none)'}`,\n plan.task.variableSuffix ?? '',\n ].join('\\n');\n const taskDir = join(\n loaded.projectRoot,\n '.cohorte',\n 'runs',\n ctx.run.run.runId,\n plan.agentId,\n String(incarnation),\n );\n mkdirSync(taskDir, { recursive: true });\n const taskPath = join(taskDir, 'task.md');\n writeFileSync(taskPath, taskText, 'utf8');\n return {\n runId: ctx.run.run.runId,\n agentId: plan.agentId,\n role: plan.role,\n model: { provider: provider.id, model: provider.id === 'fake' ? 'scripted' : 'configured' },\n systemPrompt: { id: plan.promptId, path: prompt.path, sha256: prompt.sha256, bytes: prompt.bytes },\n context: {\n manifestSha256: ctx.run.run.snapshotDigest ?? sha256Hex(new Uint8Array()),\n tokenLimit: 100_000,\n tokenEstimate: 0,\n entries: [],\n reductions: [],\n exclusions: [],\n },\n tools: plan.tools.map((tool) => ({\n tool,\n description: tool,\n inputSchema: { type: 'object' },\n effect: 'control',\n terminal: tool === 'submit_result',\n })),\n sandbox: {\n require: 'process',\n filesystem: { readOnly: [], readWrite: [workspaceRoot], denyRead: [] },\n network: { mode: 'none', allowHosts: [] },\n env: { allow: ['PATH'], set: {} },\n limits: {},\n },\n budget: plan.budget,\n workingDirectory: workspaceRoot,\n incarnation,\n thinking: 'off',\n auth: {\n mode: 'subscription',\n provider: provider.id,\n baseUrl: provider.id === 'fake' ? 'https://fake.invalid' : 'https://api.openai.com',\n allowApiKey: false,\n },\n task: { path: taskPath, sha256: sha256Hex(taskText), bytes: Buffer.byteLength(taskText) },\n continuation: null,\n };\n },\n outputFor: (agentId) => acceptedOutputs.get(agentId),\n });\n const checkRunner = {\n async run(ctx: PhaseRunContext) {\n const argv = resolved.config.checks.test;\n if (!argv || argv.length === 0) return [];\n const treeDigest = await git.treeDigest(integrationPath, { exclude: [] });\n const file = programs.resolve(argv[0] as string);\n if (!file) return [{ name: 'test', status: 'errored' as const, argv: [...argv], durationMs: 0, treeDigest }];\n const result = await executor.run(\n {\n file,\n args: argv.slice(1),\n cwd: integrationPath,\n env: { PATH: gitPath, HOME: options.home },\n fs: { readWrite: [], readOnly: [integrationPath], denyRead: [] },\n network: 'none',\n timeoutMs: resolved.config.checks.timeoutMs,\n maxOutputBytes: 1024 * 1024,\n stdin: 'ignore',\n limits: {},\n require: 'best-effort',\n },\n ctx.signal,\n );\n return [\n {\n name: 'test',\n status: result.outcome === 'ok' && result.exitCode === 0 ? ('passed' as const) : ('failed' as const),\n argv: [...argv],\n ...(result.exitCode === null ? {} : { exitCode: result.exitCode }),\n durationMs: result.durationMs,\n treeDigest,\n },\n ];\n },\n };\n const phases = createPhaseExecutor({\n contracts: createPhaseContracts({\n provisioner: createProvisioner({\n executor,\n journal,\n requestFor: async () => ({\n key: 'none',\n manifestSha256: '0'.repeat(64) as never,\n file: canonical('/usr/bin/node'),\n args: [],\n cwd: root,\n env: {},\n fs: { readWrite: [], readOnly: [], denyRead: [] },\n network: 'none',\n timeoutMs: 1,\n maxOutputBytes: 1,\n stdin: 'ignore',\n limits: {},\n require: 'best-effort',\n }),\n }),\n }),\n supervisor,\n worktrees,\n integration,\n events,\n store: options.store,\n checkRunner,\n });\n const factCollector = createFactCollector({\n store: options.store,\n runId: options.runId as RunId,\n clock: systemClock,\n probes: {\n 'config.trust-satisfied': true,\n 'snapshot.captured': true,\n 'runtime.pin-valid': true,\n 'runtime.platform-supported': true,\n 'auth.plan-satisfied': true,\n 'billing.consented': true,\n 'sandbox.meets-policy': true,\n 'repo.base-resolved': true,\n 'locks.project+zones-held': true,\n 'readiness.in': true,\n 'contract.present-or-exempt': true,\n 'reviewtarget.resolved-to-sha': true,\n 'surfaces.all-owned': true,\n 'outputs.schema-valid': true,\n 'diff.within-ownership': true,\n 'tree.digest-recorded': true,\n 'checks.all-passed': true,\n 'checks.digest-equals-integration': true,\n 'review.nothing-to-fix': true,\n 'review.no-unreviewed': true,\n 'review.leftovers-parked-or-waived': true,\n 'reviewref.digest-equals-integration': true,\n 'approval.ship-allowed': true,\n 'tree.digest-equals-approved': true,\n 'acceptance.no-open-human-items': true,\n },\n });\n const guards = createPipelineGuards({ factCollector });\n const processSweeper = createHostProcessSweeper();\n const provisioner = createProvisioner({\n executor,\n journal,\n requestFor: async () => ({\n key: 'none',\n manifestSha256: '0'.repeat(64) as never,\n file: canonical('/usr/bin/node'),\n args: [],\n cwd: root,\n env: {},\n fs: { readWrite: [], readOnly: [], denyRead: [] },\n network: 'none',\n timeoutMs: 1,\n maxOutputBytes: 1,\n stdin: 'ignore',\n limits: {},\n require: 'best-effort',\n }),\n });\n const builtin = createBuiltinEffectVerifiers({ git, provisioner, sweeper: processSweeper });\n const verifierRegistry = createVerifierRegistry(builtin);\n const resumer = createResumer({\n store: options.store,\n clock: systemClock,\n sweeper: processSweeper,\n effectVerifiers: verifierRegistry,\n worktrees,\n events,\n redactor,\n toolHostReplay: createToolHostReplay(toolHostDeps),\n installInspector: options.install,\n ids: options.ids,\n });\n const transitionEffects = createTransitionEffectRunner({\n store: options.store,\n journal,\n events,\n clock: systemClock,\n handlers: Object.fromEntries(\n [\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 ].map((id) => [\n id,\n async ({ runId, lease }: { runId: string; lease: LeaseToken }) => {\n if (id === 'create-integration-branch') {\n const facts = await git.facts(root);\n if (facts.head.kind === 'unborn')\n throw new Error('configuration/repository-unborn: repository has no commit');\n const headSha = facts.head.sha;\n if (!existsSync(integrationPath)) {\n await git.addWorktree({\n repo: root,\n path: integrationPath,\n branch: integrationBranch,\n commit: headSha,\n });\n }\n await options.store.transact({ runId: runId as RunId }, lease, (tx) =>\n tx.patchRun(runId as RunId, { baseSha: headSha, integrationHead: headSha }),\n );\n }\n },\n ]),\n ),\n });\n const keyId = sha256Hex(options.cwd).slice(0, 24);\n const projectKey = await keys.projectKey(keyId, { create: true });\n const authenticator = createCommandAuthenticator();\n const core = createEngine({\n store: options.store,\n clock: systemClock,\n ids: options.ids,\n resume: resumer,\n phases,\n loopPolicy: loopPolicy(),\n guards,\n factCollector,\n transitionEffects,\n checkGlobalStops: noStop,\n resolveTable,\n authenticator,\n projectKey,\n events,\n redactor,\n leases,\n schemaVersion: 1,\n startColumns: async (run) => {\n const facts = await git.facts(root);\n if (facts.head.kind === 'unborn') throw new Error('configuration/repository-unborn: repository has no commit');\n const trustInfo = resolved.status === 'resolved' ? resolved.trust : undefined;\n if (!trustInfo) throw new Error('security/project-policy-untrusted: host config is not trusted');\n const manifest = await snapshotter.capture({\n runId: run.runId,\n projectRoot: root,\n installDir: options.install.installDir(),\n configPaths: {\n config: join(root, '.cohorte', 'config.yaml'),\n ownership: join(root, '.cohorte', 'ownership.yaml'),\n policy: join(root, '.cohorte', 'config.yaml'),\n },\n runtime: runtimePin,\n trust: trustInfo,\n sandbox: {\n require: resolved.config.sandbox.brain === 'process' ? 'process' : 'os-if-available',\n filesystem: { readOnly: [root], readWrite: [], denyRead: [] },\n network: { mode: 'none', allowHosts: [] },\n env: { allow: ['PATH'], set: {} },\n limits: {},\n },\n models: [],\n prompts: await Promise.all(\n shippedPromptIds.map(async (id) => ({\n id,\n source: 'shipped' as const,\n logicalPath: `prompts/${id}.md`,\n path: (await assets.prompt(id)).path,\n })),\n ),\n });\n const snapshotPromptDir = join(root, '.cohorte', 'runs', run.runId, 'snapshot', 'prompts');\n mkdirSync(snapshotPromptDir, { recursive: true });\n for (const prompt of manifest.prompts) {\n const bytes = await pinStore.read(prompt.sha256);\n const path = join(snapshotPromptDir, `${prompt.id.replaceAll('/', '__')}.md`);\n writeFileSync(path, bytes, { mode: 0o600 });\n pinnedPromptPaths.set(prompt.id, { path, sha256: prompt.sha256, bytes: bytes.byteLength });\n }\n const snapshotDigest = sha256Hex(canonicalJson(manifest as never));\n await pinStore.put(new TextEncoder().encode(canonicalJson(manifest as never)));\n const sandbox = {\n level: sandboxCapabilities.level,\n backend: sandboxCapabilities.backend,\n filesystem: sandboxCapabilities.filesystem,\n network: sandboxCapabilities.network,\n };\n const zones = Object.entries(loaded.ownership.surfaces)\n .filter(([surfaceId]) => surfaceId !== 'shared')\n .flatMap(([, surface]) => surface.paths.map((path) => literalPrefixOf(path).join('/')).filter(Boolean))\n .filter((path, index, paths) => paths.indexOf(path) === index)\n .sort();\n return {\n snapshotDigest,\n runtimePin,\n plan: {\n profile: run.profile,\n runtime: { id: provider.id, version: provider.id === 'fake' ? 'fake-script' : 'pi' },\n trust: trustInfo,\n models: [],\n apiBillingEnabled: false,\n meteredProviders: [],\n sandbox,\n sandboxRequire: resolved.config.sandbox.require ?? 'best-effort',\n brainIsolation: resolved.config.sandbox.brain === 'process' ? 'process' : 'os',\n budgets: {\n run: resolved.config.budgets.run,\n perPhase: resolved.config.budgets.phase,\n perAgent: resolved.config.budgets.agent,\n perProvider: resolved.config.budgets.provider,\n perTool: resolved.config.budgets.tool,\n },\n network: { provisioning: false },\n promptOverrides: [],\n unattended: true,\n },\n baseSha: facts.head.sha,\n integrationBranch,\n zones,\n };\n },\n pollIntervalMs: resolved.config.host.pollMs,\n onLease: (lease) => {\n activeLease = lease;\n },\n });\n return {\n async run(runId, host: HostContext) {\n return core.run(runId, host);\n },\n };\n}\n\nexport async function createProductionHostRunner(options: ProductionEngineOptions): Promise<HostRunner> {\n const hostIdentity = {\n hostId: `host-${process.pid}`,\n pid: process.pid,\n startToken: `${process.pid}:${process.ppid}:${process.argv0}`,\n };\n return {\n async run(runId: string) {\n const run = await options.store.getRun(runId as RunId);\n if (!run) throw new Error(`validation/invalid-id: run ${runId} does not exist`);\n const verified = await verifyPinnedInstall(options.install, run.pinnedInstallDir);\n if (!verified.ok) throw new Error(`${verified.error.code}: ${verified.error.message}`);\n const engine = await createProductionEngine({ ...options, runId: runId as RunId, hostIdentity });\n const host = createRunHost({\n engine,\n runId: runId as RunId,\n cohorteVersion: '3.0.0-dev.1',\n cwd: options.cwd,\n hostId: hostIdentity.hostId,\n });\n return host.run();\n },\n };\n}\n","// apps/cli/src/compose/index.ts — AREA barrel (DESIGN 1.2 apps/cli composition root). Assembles the real\n// `CliContext` and resolves the production Pi runtime by default, while retaining the fake runtime for tests.\n\nimport { mkdir } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { createUuidV7IdSource, systemClock } from '@cohorte/base';\nimport { openSqliteStore } from '@cohorte/persistence/sqlite';\nimport { createFakeRuntimeProvider, fakeScript } from '@cohorte/runtime-fake';\nimport { createPiRuntimeProvider } from '@cohorte/runtime-pi';\nimport { createRedactor } from '@cohorte/security/redact';\nimport { createAssetSource } from '../assets/index.ts';\nimport type { CliContext } from '../contract/index.ts';\nimport { createController } from '../control/index.ts';\nimport { createHostSpawner } from '../host/index.ts';\nimport type { ComposeInputs } from '../lazy.ts';\nimport { createObserver } from '../observe/index.ts';\nimport { createInstallInspector } from '../pin/index.ts';\nimport { createRenderer } from '../render/index.ts';\nimport { createProductionHostRunner } from './engine.ts';\n\nexport async function composeCliContext(inputs: ComposeInputs): Promise<CliContext> {\n const ids = createUuidV7IdSource();\n const install = createInstallInspector();\n const fakeRuntime = createFakeRuntimeProvider({ script: fakeScript().build(), clock: systemClock });\n const piRuntime = createPiRuntimeProvider({ installDir: install.installDir(), redactor: createRedactor() });\n const assets = createAssetSource();\n const createStore = async () => {\n const stateDir = join(inputs.cwd, '.cohorte', 'state');\n await mkdir(stateDir, { recursive: true, mode: 0o700 });\n const migrationsDir = dirname((await assets.migration('state/0001_init.sql')).path);\n const databasePath = join(stateDir, 'cohorte.db');\n const store = openSqliteStore({ path: databasePath, migrationsDir, clock: systemClock, ids });\n return store;\n };\n const openMigrationStore = createStore;\n const openStore = async () => {\n const store = await createStore();\n if ((await store.migrate('check')).current === 0) await store.migrate('apply');\n await store.open();\n return store;\n };\n return {\n clock: systemClock,\n ids,\n stdio: inputs.stdio,\n cwd: inputs.cwd,\n env: inputs.env,\n openStore,\n openMigrationStore,\n controller: createController({\n openStore,\n clock: systemClock,\n ids,\n cwd: inputs.cwd,\n home: inputs.env.HOME ?? process.cwd(),\n pinnedInstallDir: install.installDir(),\n }),\n observer: createObserver(async () => {\n const stateDir = join(inputs.cwd, '.cohorte', 'state');\n await mkdir(stateDir, { recursive: true, mode: 0o700 });\n const migrationsDir = dirname((await assets.migration('state/0001_init.sql')).path);\n const databasePath = join(stateDir, 'cohorte.db');\n const store = openSqliteStore({ path: databasePath, migrationsDir, clock: systemClock, ids });\n if ((await store.migrate('check')).current === 0) await store.migrate('apply');\n await store.open();\n return store;\n }),\n hostSpawner: createHostSpawner({ cwd: inputs.cwd, openStore, install }),\n hostRunner: {\n async run(runId) {\n const store = await openStore();\n try {\n const runner = await createProductionHostRunner({\n store,\n openStore,\n cwd: inputs.cwd,\n home: inputs.env.HOME ?? inputs.cwd,\n env: inputs.env,\n ids,\n install,\n assetsTreeSha256: assets.treeSha256(),\n });\n return await runner.run(runId);\n } finally {\n await store.close();\n }\n },\n },\n renderer: createRenderer(),\n runtime: {\n // Pi is the production runtime and the configured V3 default. Keep the fake\n // available for explicit offline/test callers without making it the CLI default.\n resolve: (name) => (name === 'fake' ? fakeRuntime : piRuntime),\n capabilities: () => ({ provider: piRuntime.id }),\n },\n assets,\n install,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAM,UAAU,UAAiC;AAEjD,SAAgB,yBAAyB,MAA2C;CAClF,OAAO;EACL,MAAM,OAAO,MAAM,MAAM,QAAQ,CAAC,GAAG,GAAG;GACtC,MAAM,SAAS,MAAM,KAAK,IAAI,UAAU;IACtC,UAAU,OAAO,IAAI;IACrB,SAAS,SAAS,eAAe,+BAA+B;IAChE,UAAU;KAAE,mBAAmB;KAAQ,uBAAuB;IAAK;IACnE,UAAU;KAAE,MAAM;KAAW,OAAO;IAAoB;IACxD;GACF,CAAC;GACD,IAAI,UAAU,QAAQ,OAAO;GAC7B,OAAO;IAAE,KAAK,OAAO;IAAK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