@tangle-network/agent-runtime 10.0.4 → 10.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/{activation-38MolXIP.js → activation-B3qLMoog.js} +2 -2
  3. package/dist/{activation-38MolXIP.js.map → activation-B3qLMoog.js.map} +1 -1
  4. package/dist/{activation-Ckx0yHjT.d.ts → activation-CT-rr2-5.d.ts} +2 -2
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +4 -4
  7. package/dist/{continuation-CL4B1Y4M.js → continuation-Bccak14N.js} +3 -3
  8. package/dist/{continuation-CL4B1Y4M.js.map → continuation-Bccak14N.js.map} +1 -1
  9. package/dist/{delegate-dhNeiaH_.js → delegate-BFP1uCNY.js} +2 -2
  10. package/dist/{delegate-dhNeiaH_.js.map → delegate-BFP1uCNY.js.map} +1 -1
  11. package/dist/{driver-control-acknowledgers-C6GaGBf_.js → driver-control-acknowledgers-jdlf49OQ.js} +13 -11
  12. package/dist/driver-control-acknowledgers-jdlf49OQ.js.map +1 -0
  13. package/dist/durable-file-iPCEs_-s.js +1 -0
  14. package/dist/{durable-file-lXnojyij.js → durable-file-pao7FijS.js} +7 -11
  15. package/dist/durable-file-pao7FijS.js.map +1 -0
  16. package/dist/durable-writer-thread.js +5 -5
  17. package/dist/durable.d.ts +4 -1
  18. package/dist/durable.js +22 -16
  19. package/dist/durable.js.map +1 -1
  20. package/dist/{failure-cause-DoCCGLDH.js → failure-cause-DvYGlOEV.js} +13 -5
  21. package/dist/{failure-cause-DoCCGLDH.js.map → failure-cause-DvYGlOEV.js.map} +1 -1
  22. package/dist/{graph-CwLg3LGC.js → graph-CiApRth2.js} +10 -14
  23. package/dist/graph-CiApRth2.js.map +1 -0
  24. package/dist/{graph-registry-Bs6mGKou.js → graph-registry-CGKyYabE.js} +1 -1
  25. package/dist/{graph-registry-DtGd03zk.js → graph-registry-CRskE_Yp.js} +4 -4
  26. package/dist/{graph-registry-DtGd03zk.js.map → graph-registry-CRskE_Yp.js.map} +1 -1
  27. package/dist/{improve-C_LKfgH9.js → improve-LJaiGxdI.js} +8 -8
  28. package/dist/{improve-C_LKfgH9.js.map → improve-LJaiGxdI.js.map} +1 -1
  29. package/dist/index.d.ts +3 -3
  30. package/dist/index.js +11 -11
  31. package/dist/intelligence.d.ts +2 -2
  32. package/dist/intelligence.js +4 -4
  33. package/dist/{jsonl-file-DyzefaZ6.js → jsonl-file-vE9H9UXa.js} +3 -3
  34. package/dist/{jsonl-file-DyzefaZ6.js.map → jsonl-file-vE9H9UXa.js.map} +1 -1
  35. package/dist/kernel.d.ts +2 -2
  36. package/dist/kernel.js +20 -20
  37. package/dist/{loop-runner-LWqWf8FD.d.ts → loop-runner-D6egvap-.d.ts} +2 -2
  38. package/dist/{loop-runner-BS3ru-yj.js → loop-runner-Dgow637w.js} +2 -2
  39. package/dist/{loop-runner-BS3ru-yj.js.map → loop-runner-Dgow637w.js.map} +1 -1
  40. package/dist/loop-runner-bin.d.ts +1 -1
  41. package/dist/loop-runner-bin.js +1 -1
  42. package/dist/mcp/bin.js +3 -3
  43. package/dist/mcp/index.d.ts +1 -1
  44. package/dist/mcp/index.js +7 -7
  45. package/dist/mcp/memory-bin.js +1 -1
  46. package/dist/{model-policy-DZnL8Yj9.js → model-policy-DTbTFyOG.js} +12 -6
  47. package/dist/model-policy-DTbTFyOG.js.map +1 -0
  48. package/dist/profiles.d.ts +1 -1
  49. package/dist/profiles.js +1 -1
  50. package/dist/{provision-supervisor-D8N0l2DM.js → provision-supervisor-DLOeyFHV.js} +8 -8
  51. package/dist/{provision-supervisor-D8N0l2DM.js.map → provision-supervisor-DLOeyFHV.js.map} +1 -1
  52. package/dist/{result-blob-store-DfTcyQ05.js → result-blob-store-BMMzqpHa.js} +4 -4
  53. package/dist/{result-blob-store-DfTcyQ05.js.map → result-blob-store-BMMzqpHa.js.map} +1 -1
  54. package/dist/{run-cancellation-D3qc9wAD.js → run-cancellation-Bv7ooTJa.js} +129 -54
  55. package/dist/run-cancellation-Bv7ooTJa.js.map +1 -0
  56. package/dist/{run-lock-D1xnb9ve.js → run-lock-Ckakh1Uq.js} +3 -3
  57. package/dist/{run-lock-D1xnb9ve.js.map → run-lock-Ckakh1Uq.js.map} +1 -1
  58. package/dist/{run-reopen-DVM5AEKV.js → run-reopen-KAnkEJV4.js} +7 -7
  59. package/dist/{run-reopen-DVM5AEKV.js.map → run-reopen-KAnkEJV4.js.map} +1 -1
  60. package/dist/{run-state-tgQ-S9Ln.js → run-state-Bcci4zIN.js} +7 -7
  61. package/dist/{run-state-tgQ-S9Ln.js.map → run-state-Bcci4zIN.js.map} +1 -1
  62. package/dist/{runtime-BTECV05R.js → runtime-DCo0OP4n.js} +46 -55
  63. package/dist/runtime-DCo0OP4n.js.map +1 -0
  64. package/dist/{search-executor-Uco2_KTB.js → search-executor-Dn5YmHsg.js} +5 -5
  65. package/dist/{search-executor-Uco2_KTB.js.map → search-executor-Dn5YmHsg.js.map} +1 -1
  66. package/dist/{server-BMp24-xn.js → server-DxpG9y6W.js} +4 -4
  67. package/dist/{server-BMp24-xn.js.map → server-DxpG9y6W.js.map} +1 -1
  68. package/dist/{settle-record-au3w7bQG.js → settle-record-DMdeNy8A.js} +4 -4
  69. package/dist/{settle-record-au3w7bQG.js.map → settle-record-DMdeNy8A.js.map} +1 -1
  70. package/dist/{structural-rollout-D8wufVJI.js → structural-rollout-DOmjcEMD.js} +5 -5
  71. package/dist/{structural-rollout-D8wufVJI.js.map → structural-rollout-DOmjcEMD.js.map} +1 -1
  72. package/dist/{supervise-DtVdvZpr.js → supervise-D7jtypE-.js} +34 -29
  73. package/dist/supervise-D7jtypE-.js.map +1 -0
  74. package/dist/{supervise-identity-S5XwgaF3.js → supervise-identity-QavM_M4r.js} +4 -4
  75. package/dist/{supervise-identity-S5XwgaF3.js.map → supervise-identity-QavM_M4r.js.map} +1 -1
  76. package/dist/{supervision-discovery-Cqu4NxPV.js → supervision-discovery-CFZnbNTB.js} +6 -9
  77. package/dist/supervision-discovery-CFZnbNTB.js.map +1 -0
  78. package/dist/{supervisor-CHgCAMjm.js → supervisor-BFs4u2Vo.js} +147 -73
  79. package/dist/supervisor-BFs4u2Vo.js.map +1 -0
  80. package/dist/{supervisor-accounting-CZ7i4cd5.js → supervisor-accounting-CgipDzYg.js} +59 -20
  81. package/dist/supervisor-accounting-CgipDzYg.js.map +1 -0
  82. package/dist/{supervisor-root-contract-D70KTGXF.js → supervisor-root-contract-Ca5xp0Vg.js} +3 -3
  83. package/dist/{supervisor-root-contract-D70KTGXF.js.map → supervisor-root-contract-Ca5xp0Vg.js.map} +1 -1
  84. package/dist/testing.d.ts +1 -1
  85. package/dist/testing.js +11 -11
  86. package/dist/{tool-server-DQCdu3am.js → tool-server-Cb7LBW4e.js} +2 -2
  87. package/dist/{tool-server-DQCdu3am.js.map → tool-server-Cb7LBW4e.js.map} +1 -1
  88. package/dist/{top-web-COrMqTRC.js → top-web-oDO4xhNE.js} +8 -8
  89. package/dist/{top-web-COrMqTRC.js.map → top-web-oDO4xhNE.js.map} +1 -1
  90. package/dist/tui/bin.js +3 -3
  91. package/dist/tui/index.d.ts +1 -1
  92. package/dist/tui/index.js +2 -2
  93. package/dist/{types-9xsn2GGY.d.ts → types-CKsn_wgO.d.ts} +26 -4
  94. package/package.json +1 -1
  95. package/dist/driver-control-acknowledgers-C6GaGBf_.js.map +0 -1
  96. package/dist/durable-file-DJ3JsA4B.js +0 -1
  97. package/dist/durable-file-lXnojyij.js.map +0 -1
  98. package/dist/graph-CwLg3LGC.js.map +0 -1
  99. package/dist/model-policy-DZnL8Yj9.js.map +0 -1
  100. package/dist/run-cancellation-D3qc9wAD.js.map +0 -1
  101. package/dist/runtime-BTECV05R.js.map +0 -1
  102. package/dist/supervise-DtVdvZpr.js.map +0 -1
  103. package/dist/supervision-discovery-Cqu4NxPV.js.map +0 -1
  104. package/dist/supervisor-CHgCAMjm.js.map +0 -1
  105. package/dist/supervisor-accounting-CZ7i4cd5.js.map +0 -1
@@ -1 +0,0 @@
1
- export { d as writeAtomicDurableFile } from "./durable-file-lXnojyij.js";
@@ -1 +0,0 @@
1
- {"version":3,"file":"durable-file-lXnojyij.js","names":["fsConstants"],"sources":["../src/durable/run-fence.ts","../src/durable/durable-writer.ts","../src/runtime/supervise/durable-file.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\nimport { closeSync, existsSync, fstatSync, openSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { isMainThread } from 'node:worker_threads'\nimport { tryAcquireAtomicFileLock } from '@tangle-network/agent-eval/ledger-core'\nimport type { LockIdentity } from '@tangle-network/agent-eval/lock-holder'\n\n/** The immutable claim carried by every write in one directory execution. @internal */\nexport interface RunWriteClaim {\n readonly path: string\n readonly generation: number\n readonly lock: LockIdentity\n}\n\nconst claims = new AsyncLocalStorage<RunWriteClaim | undefined>()\nconst publications = new AsyncLocalStorage<{ readonly claim: RunWriteClaim; active: boolean }>()\n\n// Set on the durable writer thread (durable-writer-thread.ts): the one thread that runs claimed writes.\nlet writerThread = false\n\n/** Mark this thread as the process's durable writer. @internal */\nexport function markDurableWriterThread(): void {\n writerThread = true\n}\n\n/** True on the durable writer thread. @internal */\nexport function onDurableWriterThread(): boolean {\n return writerThread\n}\n\n/** The claim the current asynchronous context carries, if any. @internal */\nexport function currentRunWriteClaim(): RunWriteClaim | undefined {\n return claims.getStore()\n}\n\n/** Bind asynchronous work, including callbacks, to the generation that admitted it. @internal */\nexport function runWithWriteClaim<T>(claim: RunWriteClaim, operation: () => T): T {\n return claims.run(claim, operation)\n}\n\n/** Capture a store's acquisition once, even when later called from an unrelated emitter. @internal */\nexport function captureRunWriteContext(): <T>(operation: () => T) => T {\n let claim = claims.getStore()\n return <T>(operation: () => T): T => {\n claim ??= claims.getStore()\n return claims.run(claim, operation)\n }\n}\n\n/** Serialize claim changes and file mutations under the same cross-process guard. @internal */\nexport function mutateRunClaim<T>(path: string, operation: () => T): T {\n // Old writers use an unowned directory guard. Never race one or guess that it is stale.\n const legacyGuard = `${path}.guard`\n if (existsSync(legacyGuard)) {\n throw new Error(\n `supervisePursuit: cannot mutate ${path}; inspect ${legacyGuard} and remove it only after confirming no lock mutation is active`,\n )\n }\n const deadline = performance.now() + 5_000\n const sleeper = new Int32Array(new SharedArrayBuffer(4))\n for (;;) {\n const acquisition = tryAcquireAtomicFileLock({ lockPath: `${path}.mutation` })\n if (acquisition.acquired) {\n try {\n return operation()\n } finally {\n acquisition.lock.release()\n }\n }\n if (performance.now() >= deadline) throw new Error(`run directory mutation is held: ${path}`)\n Atomics.wait(sleeper, 0, 0, 10)\n }\n}\n\n/**\n * Fence an actual file mutation, not an earlier advisory check. No await occurs between the\n * ownership check and publication, and acquire/release use this same guard. Unclaimed standalone\n * stores retain their existing single-writer contract; pursuit-owned work always carries a claim.\n * @internal\n */\nexport function fenceRunWrite<T>(operation: () => T): T {\n const claim = claims.getStore()\n if (claim === undefined) return operation()\n // A claimed write on the main thread would hold the run's mutation lock against the durable\n // writer and block the event loop on the disk: it must be sent through `runFenced`.\n if (isMainThread && !writerThread) {\n throw new Error('a claimed run write reached the main thread; send it through runFenced')\n }\n const publication = publications.getStore()\n if (\n publication?.active &&\n publication.claim.path === claim.path &&\n publication.claim.generation === claim.generation\n )\n return operation()\n return mutateRunClaim(claim.path, () => {\n let holder: Partial<RunWriteClaim> | undefined\n try {\n const fd = openSync(claim.path, 'r')\n try {\n const stat = fstatSync(fd, { bigint: true })\n if (\n stat.dev.toString() !== claim.lock.dev ||\n stat.ino.toString() !== claim.lock.ino ||\n stat.birthtimeNs.toString() !== claim.lock.birthtimeNs\n ) {\n throw new Error('run lock inode changed')\n }\n holder = JSON.parse(readFileSync(fd, 'utf8')) as Partial<RunWriteClaim>\n } finally {\n closeSync(fd)\n }\n } catch (cause) {\n throw new Error(`run directory generation ${claim.generation} lost its claim`, { cause })\n }\n if (\n holder?.generation !== claim.generation ||\n holder.lock?.dev !== claim.lock.dev ||\n holder.lock?.ino !== claim.lock.ino ||\n holder.lock?.birthtimeNs !== claim.lock.birthtimeNs\n ) {\n throw new Error(`run directory generation ${claim.generation} lost its claim`)\n }\n // Nested synchronous primitives share the guard. A callback queued here keeps its claim,\n // but cannot inherit a live guard after this publication has returned.\n const publication = { claim, active: true }\n try {\n return publications.run(publication, operation)\n } finally {\n publication.active = false\n }\n })\n}\n\n/** Persistent generation counter survives a clean release of supervise.lock. @internal */\nexport function runGenerationPath(runDir: string): string {\n return resolve(runDir, 'supervise.generation')\n}\n","/**\n * The durable writer: one thread per process that performs every claimed run-directory write.\n *\n * A fenced write is synchronous by contract (lock, claim check, mutation and fsync with no await\n * between them), and on a saturated disk its open, link and fsync calls wait on the filesystem\n * journal: a coordinator whose event loop ran them was measured blocked 20 to 70 s at a time.\n * Here the same synchronous code runs on its own thread. Only that thread takes a run directory's\n * mutation lock in this process, so a caller never spins on a lock this process holds.\n *\n * - `durableCall` blocks the calling thread until the writer answers, exactly as the inline write\n * did, for callers whose contract is synchronous.\n * - `durableCallAsync` resolves with the writer's answer and leaves the event loop free.\n * - On the writer thread both run the operation inline, so a fenced helper may call another.\n * - Operations run in the order they were sent, sync and async alike.\n * - A call the writer does not answer within `DURABLE_WRITER_DEADLINE_MS` fails, and the writer\n * keeps running. A writer that errors or exits fails every waiting and later call and is never\n * replaced. Nothing falls back to writing on the calling thread.\n *\n * @internal\n */\n\nimport { existsSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { fileURLToPath } from 'node:url'\nimport { isMainThread, MessageChannel, receiveMessageOnPort, Worker } from 'node:worker_threads'\nimport {\n currentRunWriteClaim,\n markDurableWriterThread,\n onDurableWriterThread,\n type RunWriteClaim,\n} from './run-fence'\n\n/** Longer than the worst fsync measured on a saturated disk (70 s), so only a dead writer trips it. */\nexport const DURABLE_WRITER_DEADLINE_MS = 180_000\n\n/** A named operation and its JSON arguments; names resolve in `durable-writer-thread.ts`. */\nexport interface DurableOperation {\n readonly name: string\n readonly args: readonly unknown[]\n}\n\ninterface Request extends DurableOperation {\n readonly id: number\n readonly claim: RunWriteClaim | undefined\n readonly sync: boolean\n}\n\ntype Reply =\n | { readonly id: number; readonly ok: true; readonly value: unknown }\n | {\n readonly id: number\n readonly ok: false\n readonly error: {\n message: string\n name?: string\n code?: string\n stack?: string\n fields?: Record<string, unknown>\n }\n }\n\nlet runInline: ((operation: DurableOperation) => unknown) | undefined\n\n/** Called by the writer thread's entry: operations sent from this thread now run inline. */\nexport function becomeDurableWriter(inline: (operation: DurableOperation) => unknown): void {\n markDurableWriterThread()\n runInline = inline\n}\n\n/**\n * Whether a write goes to the writer: a claimed write made by the main thread, or with `always`,\n * any write the main thread makes (run-directory acquisition and release take the same lock before\n * a claim exists). Unclaimed writes keep their caller-owned single-writer contract and run inline,\n * and other worker threads never start a second writer that would contend for the same lock.\n */\nexport function routesToDurableWriter(always = false): boolean {\n return (\n !onDurableWriterThread() && isMainThread && (always || currentRunWriteClaim() !== undefined)\n )\n}\n\n/**\n * Run the fenced operation `fn(...args)`: inline when the write is not routed, otherwise on the\n * writer under the caller's claim, blocking this thread until it answers. `fn` takes its own fence\n * (`fenceRunWrite` or `mutateRunClaim`) and is registered under `name` in durable-writer-thread.ts;\n * arguments and the result cross the thread as structured clones.\n */\nexport function runFenced<A extends unknown[], T>(\n name: string,\n fn: (...args: A) => T,\n ...args: A\n): T {\n return routesToDurableWriter() ? durableCall<T>({ name, args }) : fn(...args)\n}\n\n/** `runFenced` without blocking: the event loop stays free while the writer works. */\nexport function runFencedAsync<A extends unknown[], T>(\n name: string,\n fn: (...args: A) => T,\n ...args: A\n): Promise<T> {\n if (routesToDurableWriter()) return durableCallAsync<T>({ name, args })\n try {\n return Promise.resolve(fn(...args))\n } catch (error) {\n return Promise.reject(error)\n }\n}\n\n/** `runFencedAsync` for run-directory acquisition and release, routed from the main thread even\n * before a claim exists, since they take the same mutation lock the writer holds. */\nexport function runFencedAlways<A extends unknown[], T>(\n name: string,\n fn: (...args: A) => T,\n ...args: A\n): Promise<T> {\n if (routesToDurableWriter(true)) return durableCallAsync<T>({ name, args })\n try {\n return Promise.resolve(fn(...args))\n } catch (error) {\n return Promise.reject(error)\n }\n}\n\ninterface Writer {\n readonly worker: Worker\n readonly syncReplies: MessageChannel\n readonly signal: Int32Array\n readonly pending: Map<\n number,\n { resolve: (value: unknown) => void; reject: (error: Error) => void; timer: NodeJS.Timeout }\n >\n}\n\nlet writer: Writer | undefined\n// Set when the writer errors or exits. It is never replaced: it may have died inside a fence\n// holding the run's mutation lock under this live pid, and a new writer could only spin on that\n// lock. Every later routed write fails at once with this cause.\nlet writerDeath: Error | undefined\nlet nextId = 0\n\n// Errors an operation throws are rebuilt on the caller's thread as their own class, with their\n// own fields, so `instanceof` and fields such as a lock holder survive the thread boundary.\nconst errorClasses = new Map<string, { prototype: Error }>()\n\n/** Rebuild errors named `name` thrown on the writer as instances of `errorClass`. @internal */\nexport function registerDurableErrorClass(name: string, errorClass: { prototype: Error }): void {\n errorClasses.set(name, errorClass)\n}\n\n/**\n * The writer's entry beside this module: TypeScript in a source checkout, JavaScript in a built\n * package. A tool that bundles Runtime again must emit `src/durable/durable-writer-thread.ts` as\n * `durable-writer-thread.js` (or `.mjs`) beside the bundle; without it, writes fail with this cause.\n */\nfunction threadUrl(): URL {\n const here = import.meta.url\n if (here.endsWith('.ts')) return new URL('./durable-writer-thread.ts', here)\n for (const name of ['./durable-writer-thread.js', './durable-writer-thread.mjs']) {\n const candidate = new URL(name, here)\n if (existsSync(candidate)) return candidate\n }\n throw new Error(\n `durable writer entry durable-writer-thread.js is not beside ${fileURLToPath(here)}; a bundle of Runtime must emit it there`,\n )\n}\n\nfunction start(): Writer {\n const url = threadUrl()\n // Source checkouts (tests) load the TypeScript entry through tsx; a built package ships JavaScript.\n // Only what the entry needs: some of the parent's flags (--expose-gc) are refused in a worker.\n const execArgv = url.pathname.endsWith('.ts')\n ? ['--import', createRequire(import.meta.url).resolve('tsx')]\n : []\n const syncReplies = new MessageChannel()\n const signal = new Int32Array(new SharedArrayBuffer(4))\n const worker = new Worker(fileURLToPath(url), {\n execArgv,\n workerData: { syncReplies: syncReplies.port2, signal },\n transferList: [syncReplies.port2],\n })\n worker.unref()\n const state: Writer = { worker, syncReplies, signal, pending: new Map() }\n const die = (error: Error) => {\n writerDeath ??= error\n for (const waiting of state.pending.values()) {\n clearTimeout(waiting.timer)\n waiting.reject(writerDeath)\n }\n state.pending.clear()\n }\n worker.on('message', (reply: Reply) => {\n const waiting = state.pending.get(reply.id)\n // A reply whose caller already gave up at its deadline has nobody to answer.\n if (!waiting) return\n state.pending.delete(reply.id)\n clearTimeout(waiting.timer)\n if (state.pending.size === 0) worker.unref()\n if (reply.ok) waiting.resolve(reply.value)\n else waiting.reject(revive(reply.error))\n })\n worker.on('error', (error: Error) =>\n die(new Error(`durable writer failed: ${error.message}`, { cause: error })),\n )\n worker.on('exit', (code) => die(new Error(`durable writer exited with code ${code}`)))\n return state\n}\n\nfunction current(): Writer {\n if (writerDeath !== undefined) throw writerDeath\n writer ??= start()\n return writer\n}\n\nfunction revive(error: Extract<Reply, { ok: false }>['error']): Error {\n const errorClass = error.name === undefined ? undefined : errorClasses.get(error.name)\n const revived: Error = errorClass ? Object.create(errorClass.prototype) : new Error(error.message)\n return Object.assign(revived, error.fields ?? {}, {\n message: error.message,\n name: error.name ?? 'Error',\n ...(error.code === undefined ? {} : { code: error.code }),\n ...(error.stack === undefined ? {} : { stack: error.stack }),\n })\n}\n\nfunction overdue(operation: DurableOperation): Error {\n // The writer keeps running: stopping it inside a fence would leave the run's mutation lock held.\n return new Error(\n `durable writer did not answer ${operation.name} within ${DURABLE_WRITER_DEADLINE_MS} ms; the writer is still running`,\n )\n}\n\nfunction request(operation: DurableOperation, sync: boolean): Request {\n return {\n id: ++nextId,\n name: operation.name,\n args: operation.args,\n claim: currentRunWriteClaim(),\n sync,\n }\n}\n\n/** Perform `operation` on the writer and wait for it, blocking this thread as the inline write did. */\nexport function durableCall<T>(operation: DurableOperation): T {\n if (onDurableWriterThread()) return runInline!(operation) as T\n const state = current()\n const sent = request(operation, true)\n const deadline = performance.now() + DURABLE_WRITER_DEADLINE_MS\n Atomics.store(state.signal, 0, 0)\n state.worker.postMessage(sent)\n // The writer's exit and error events need this loop, which waits here; the deadline catches a\n // writer killed without a reply (out of memory, native abort) and a backlog that never drains.\n for (;;) {\n for (\n let received = receiveMessageOnPort(state.syncReplies.port1);\n received;\n received = receiveMessageOnPort(state.syncReplies.port1)\n ) {\n const reply = received.message as Reply\n // An older id is the late answer to a call that already failed at its deadline.\n if (reply.id !== sent.id) continue\n if (!reply.ok) throw revive(reply.error)\n return reply.value as T\n }\n const remaining = deadline - performance.now()\n if (remaining <= 0) throw overdue(operation)\n Atomics.wait(state.signal, 0, 0, remaining)\n Atomics.store(state.signal, 0, 0)\n }\n}\n\n/** Perform `operation` on the writer without blocking this thread. */\nexport function durableCallAsync<T>(operation: DurableOperation): Promise<T> {\n if (onDurableWriterThread()) {\n try {\n return Promise.resolve(runInline!(operation) as T)\n } catch (error) {\n return Promise.reject(error)\n }\n }\n let state: Writer\n try {\n state = current()\n } catch (error) {\n return Promise.reject(error)\n }\n const sent = request(operation, false)\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n state.pending.delete(sent.id)\n if (state.pending.size === 0) state.worker.unref()\n reject(overdue(operation))\n }, DURABLE_WRITER_DEADLINE_MS)\n timer.unref()\n state.pending.set(sent.id, { resolve: resolve as (value: unknown) => void, reject, timer })\n state.worker.ref()\n state.worker.postMessage(sent)\n })\n}\n\nexport type { Reply as DurableWriterReply, Request as DurableWriterRequest }\n","/**\n * Small filesystem durability primitives for Runtime-owned state.\n *\n * Callers must validate their path and parent directory before invoking these functions.\n * The exclusive writer protects a no-clobber publication race; the atomic writer replaces one\n * state file after its temporary contents reach stable storage.\n *\n * @internal\n */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n appendFileSync,\n type BigIntStats,\n closeSync,\n existsSync,\n fchmodSync,\n constants as fsConstants,\n fstatSync,\n fsyncSync,\n linkSync,\n lstatSync,\n mkdirSync,\n openSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n writeSync,\n} from 'node:fs'\nimport { dirname, join, relative, resolve } from 'node:path'\nimport { runFenced, runFencedAlways } from '../../durable/durable-writer'\nimport { fenceRunWrite } from '../../durable/run-fence'\n\ninterface DurableFileOptions {\n readonly mode?: number\n}\n\n/**\n * File content, or content computed from the new file's own stat when it must name the file's\n * inode (a lock record that later proves it was written for this very file).\n */\ntype DurableFileContent = string | ((file: BigIntStats) => string)\n\n/**\n * Publish a new file without replacing a concurrent winner. The published entry is a hard link\n * of the temporary file, so a content function sees the published file's inode.\n */\nexport function publishExclusiveDurableFile(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions = {},\n): boolean {\n // Content computed from the new file's own stat cannot cross a thread; its one caller, run-lock\n // acquisition, already runs on the durable writer.\n return typeof content === 'string'\n ? runFenced('publishExclusiveDurableFile', publishExclusiveFenced, filePath, content, options)\n : publishExclusiveFenced(filePath, content, options)\n}\n\n/**\n * `publishExclusiveDurableFile` without blocking the calling thread on the disk: from the main\n * thread the write runs on the durable writer whether or not a run claim is held.\n */\nexport function publishExclusiveDurableFileAsync(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): Promise<boolean> {\n return runFencedAlways(\n 'publishExclusiveDurableFile',\n publishExclusiveFenced,\n filePath,\n content,\n options,\n )\n}\n\n/** The fenced exclusive publication the durable writer runs. @internal */\nexport function publishExclusiveFenced(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions = {},\n): boolean {\n return fenceRunWrite(() => publishExclusiveDurableFileUnchecked(filePath, content, options))\n}\n\nfunction publishExclusiveDurableFileUnchecked(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions = {},\n): boolean {\n const temporaryPath = `${filePath}.${randomUUID()}.tmp`\n let operationFailed = false\n let operationError: unknown\n let published = false\n try {\n writeExclusiveDurableFile(temporaryPath, content, options)\n try {\n linkSync(temporaryPath, filePath)\n syncDurableDirectory(dirname(filePath))\n published = true\n } catch (error) {\n if (!isAlreadyExistsError(error)) throw error\n }\n } catch (error) {\n operationFailed = true\n operationError = error\n }\n let cleanupError: unknown\n try {\n unlinkSync(temporaryPath)\n } catch (error) {\n if (!isNoEntryError(error)) cleanupError = error\n }\n if (operationFailed) throw operationError\n if (cleanupError !== undefined) throw cleanupError\n return published\n}\n\n/** Fsync a directory after publishing a durable file entry. */\nexport function syncDurableDirectory(directoryPath: string): void {\n const fd = openSync(directoryPath, 'r')\n try {\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n\n/** Fsync one durable file after its contents reach stable storage. */\nfunction syncDurableFile(filePath: string, exactMode?: number): void {\n const fd = openSync(filePath, 'r')\n try {\n if (exactMode !== undefined && process.platform !== 'win32') fchmodSync(fd, exactMode)\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n\n/**\n * Append whole lines to a run file under the fence, creating `directory` first when given. Each\n * line is one O_APPEND write (well under PIPE_BUF), so concurrent writers never interleave; there\n * is no fsync, as for the observability logs that use it.\n */\nexport function appendRunLines(\n filePath: string,\n lines: readonly string[],\n options: { readonly directory?: string; readonly mode?: number } = {},\n): void {\n runFenced('appendRunLines', appendRunLinesFenced, filePath, lines, options)\n}\n\n/** `appendRunLines` without blocking the calling thread on the disk, claimed or not. */\nexport function appendRunLinesAsync(\n filePath: string,\n lines: readonly string[],\n options: { readonly directory?: string; readonly mode?: number } = {},\n): Promise<void> {\n return runFencedAlways('appendRunLines', appendRunLinesFenced, filePath, lines, options)\n}\n\n/** The fenced line append the durable writer runs. @internal */\nexport function appendRunLinesFenced(\n filePath: string,\n lines: readonly string[],\n options: { readonly directory?: string; readonly mode?: number } = {},\n): void {\n fenceRunWrite(() => {\n if (options.directory !== undefined) mkdirSync(options.directory, { recursive: true })\n const fd = openSync(filePath, 'a', options.mode ?? 0o666)\n try {\n for (const line of lines) appendFileSync(fd, line)\n } finally {\n closeSync(fd)\n }\n })\n}\n\n/** Append one record with O_APPEND, then fsync the file and containing directory. */\nexport function appendDurableFile(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): void {\n runFenced('appendDurableFile', appendDurableFenced, filePath, content, options)\n}\n\n/** The fenced durable append the durable writer runs. @internal */\nexport function appendDurableFenced(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): void {\n fenceRunWrite(() => appendDurableFileUnchecked(filePath, content, options))\n}\n\nfunction appendDurableFileUnchecked(\n filePath: string,\n content: string,\n options: DurableFileOptions = {},\n): void {\n const flags =\n fsConstants.O_APPEND |\n fsConstants.O_CREAT |\n fsConstants.O_WRONLY |\n (typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0)\n const fd = openSync(filePath, flags, options.mode ?? 0o600)\n try {\n if (process.platform !== 'win32') fchmodSync(fd, options.mode ?? 0o600)\n const expectedBytes = Buffer.byteLength(content, 'utf8')\n const writtenBytes = writeSync(fd, content, undefined, 'utf8')\n if (writtenBytes !== expectedBytes) {\n throw new Error(\n `durable append wrote ${writtenBytes} of ${expectedBytes} bytes to '${filePath}'`,\n )\n }\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n syncDurableDirectory(dirname(filePath))\n}\n\n/** Reject a path that escapes its run directory or traverses a symbolic link. */\nexport function assertNoSymlinkDescendant(root: string, target: string, label = 'path'): void {\n const base = resolve(root)\n const exact = resolve(target)\n const rel = relative(base, exact)\n if (rel === '..' || rel.startsWith(`..${process.platform === 'win32' ? '\\\\' : '/'}`)) {\n throw new Error(`${label} path escapes its run directory`)\n }\n if (existsSync(base) && lstatSync(base).isSymbolicLink()) {\n throw new Error(`${label} path contains a symbolic link: ${base}`)\n }\n let current = base\n for (const part of rel.split(/[\\\\/]/u).filter(Boolean)) {\n current = join(current, part)\n if (!existsSync(current)) continue\n if (lstatSync(current).isSymbolicLink()) {\n throw new Error(`${label} path contains a symbolic link: ${current}`)\n }\n }\n}\n\n/** Write, fsync, atomically replace, and fsync one Runtime-owned state file.\n * preserveMode retains ordinary access permissions despite the current umask; a new\n * file keeps normal creation semantics. Callers still own path validation and write exclusion. */\nexport function writeAtomicDurableFile(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions & { readonly preserveMode?: boolean } = {},\n): void {\n if (typeof content === 'string')\n runFenced('writeAtomicDurableFile', writeAtomicFenced, filePath, content, options)\n else writeAtomicFenced(filePath, content, options)\n}\n\n/** `writeAtomicDurableFile` without blocking the calling thread on the disk, claimed or not. */\nexport function writeAtomicDurableFileAsync(\n filePath: string,\n content: string,\n options: DurableFileOptions & { readonly preserveMode?: boolean } = {},\n): Promise<void> {\n return runFencedAlways('writeAtomicDurableFile', writeAtomicFenced, filePath, content, options)\n}\n\n/** The fenced atomic replacement the durable writer runs. @internal */\nexport function writeAtomicFenced(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions & { readonly preserveMode?: boolean } = {},\n): void {\n fenceRunWrite(() => writeAtomicDurableFileUnchecked(filePath, content, options))\n}\n\nfunction writeAtomicDurableFileUnchecked(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions & { readonly preserveMode?: boolean } = {},\n): void {\n const temporaryPath = `${filePath}.${randomUUID()}.tmp`\n let operationFailed = false\n let operationError: unknown\n try {\n let mode = options.mode\n let exactMode = false\n if (options.preserveMode) {\n try {\n mode = statSync(filePath).mode & 0o777\n exactMode = true\n } catch (error) {\n if (!isNoEntryError(error)) throw error\n }\n }\n writeExclusiveDurableFile(temporaryPath, content, { mode }, exactMode)\n renameSync(temporaryPath, filePath)\n syncDurableDirectory(dirname(filePath))\n } catch (error) {\n operationFailed = true\n operationError = error\n }\n let cleanupError: unknown\n try {\n unlinkSync(temporaryPath)\n } catch (error) {\n if (!isNoEntryError(error)) cleanupError = error\n // A successful rename removes the temporary directory entry.\n }\n if (operationFailed) throw operationError\n if (cleanupError !== undefined) throw cleanupError\n}\n\nfunction writeExclusiveDurableFile(\n filePath: string,\n content: DurableFileContent,\n options: DurableFileOptions,\n exactMode = false,\n): void {\n const fd = openSync(filePath, 'wx', options.mode ?? 0o666)\n try {\n const text = typeof content === 'string' ? content : content(fstatSync(fd, { bigint: true }))\n writeFileSync(fd, text, 'utf8')\n } finally {\n closeSync(fd)\n }\n syncDurableFile(filePath, exactMode ? options.mode : undefined)\n}\n\nfunction isAlreadyExistsError(error: unknown): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'EEXIST'\n )\n}\n\nfunction isNoEntryError(error: unknown): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ENOENT'\n )\n}\n"],"mappings":";;;;;;;;;AAcA,MAAM,SAAS,IAAI,kBAA6C;AAChE,MAAM,eAAe,IAAI,kBAAsE;AAG/F,IAAI,eAAe;;AAGnB,SAAgB,0BAAgC;CAC9C,eAAe;AACjB;;AAGA,SAAgB,wBAAiC;CAC/C,OAAO;AACT;;AAGA,SAAgB,uBAAkD;CAChE,OAAO,OAAO,SAAS;AACzB;;AAGA,SAAgB,kBAAqB,OAAsB,WAAuB;CAChF,OAAO,OAAO,IAAI,OAAO,SAAS;AACpC;;AAGA,SAAgB,yBAAuD;CACrE,IAAI,QAAQ,OAAO,SAAS;CAC5B,QAAW,cAA0B;EACnC,UAAU,OAAO,SAAS;EAC1B,OAAO,OAAO,IAAI,OAAO,SAAS;CACpC;AACF;;AAGA,SAAgB,eAAkB,MAAc,WAAuB;CAErE,MAAM,cAAc,GAAG,KAAK;CAC5B,IAAI,WAAW,WAAW,GACxB,MAAM,IAAI,MACR,mCAAmC,KAAK,YAAY,YAAY,gEAClE;CAEF,MAAM,WAAW,YAAY,IAAI,IAAI;CACrC,MAAM,UAAU,IAAI,WAAW,IAAI,kBAAkB,CAAC,CAAC;CACvD,SAAS;EACP,MAAM,cAAc,yBAAyB,EAAE,UAAU,GAAG,KAAK,W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,cACV,IAAI;GACF,OAAO,SAAS,QAAQ,CAAC,CAAC,OAAO;GACjC,YAAY;EACd,SAAS,OAAO;GACd,IAAI,CAAC,eAAe,KAAK,GAAG,MAAM;EACpC;EAEF,0BAA0B,eAAe,SAAS,EAAE,KAAK,GAAG,SAAS;EACrE,WAAW,eAAe,QAAQ;EAClC,qBAAqB,QAAQ,QAAQ,CAAC;CACxC,SAAS,OAAO;EACd,kBAAkB;EAClB,iBAAiB;CACnB;CACA,IAAI;CACJ,IAAI;EACF,WAAW,aAAa;CAC1B,SAAS,OAAO;EACd,IAAI,CAAC,eAAe,KAAK,GAAG,eAAe;CAE7C;CACA,IAAI,iBAAiB,MAAM;CAC3B,IAAI,iBAAiB,KAAA,GAAW,MAAM;AACxC;AAEA,SAAS,0BACP,UACA,SACA,SACA,YAAY,OACN;CACN,MAAM,KAAK,SAAS,UAAU,MAAM,QAAQ,QAAQ,GAAK;CACzD,IAAI;EACF,MAAM,OAAO,OAAO,YAAY,WAAW,UAAU,QAAQ,UAAU,IAAI,EAAE,QAAQ,KAAK,CAAC,CAAC;EAC5F,cAAc,IAAI,MAAM,MAAM;CAChC,UAAU;EACR,UAAU,EAAE;CACd;CACA,gBAAgB,UAAU,YAAY,QAAQ,OAAO,KAAA,CAAS;AAChE;AAEA,SAAS,qBAAqB,OAAyB;CACrD,OACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS;AAE3C;AAEA,SAAS,eAAe,OAAyB;CAC/C,OACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS;AAE3C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"graph-CwLg3LGC.js","names":["delay","fsConstants","canonicalCandidateBytes"],"sources":["../src/runtime/isolated-check-cpu.ts","../src/runtime/isolated-checker-process.ts","../src/runtime/isolated-checker.ts","../src/runtime/supervise/graph-backend.ts","../src/runtime/isolated-check-result.ts","../src/runtime/supervise/stored-graph-check.ts","../src/runtime/supervise/graph.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { mkdir, readFile, rmdir, stat, writeFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport { setTimeout as delay } from 'node:timers/promises'\n\nexport interface IsolatedCheckCpuCounters {\n usageUsec: number\n userUsec: number\n systemUsec: number\n /** Ancillary kernel observations; null fields are unavailable, never zero. */\n resources?: IsolatedCheckCpuResources\n}\n\nexport interface IsolatedCheckCpuResources {\n /** Cgroup PSI some.total: time with at least one runnable task waiting, not summed task wait. */\n runnableWaitSomeUsec: number | null\n ancestorsComplete: boolean\n ancestors: {\n cgroupPath: string\n inode: number | null\n cpuMax: string | null\n throttledUsec: number | null\n }[]\n}\n\nconst cgroupRoot = '/sys/fs/cgroup'\nexport const isolatedCheckCpuAncestorLimit = 32\n\nasync function optionalFile(path: string): Promise<string | null> {\n try {\n return await readFile(path, 'utf8')\n } catch {\n return null\n }\n}\n\nfunction optionalCounter(match: RegExpExecArray | null): number | null {\n const value = match ? Number(match[1]) : NaN\n return Number.isSafeInteger(value) && value >= 0 ? value : null\n}\n\nasync function resources(path: string): Promise<IsolatedCheckCpuResources> {\n const pressure = await optionalFile(join(path, 'cpu.pressure'))\n const ancestors: IsolatedCheckCpuResources['ancestors'] = []\n let current = dirname(path)\n let complete = false\n for (let depth = 0; depth < isolatedCheckCpuAncestorLimit; depth++) {\n const [identity, quota, text] = await Promise.all([\n stat(current).catch(() => null),\n optionalFile(join(current, 'cpu.max')),\n optionalFile(join(current, 'cpu.stat')),\n ])\n ancestors.push({\n cgroupPath: current,\n inode: identity?.ino ?? null,\n cpuMax: quota && /^(max|[0-9]+) [1-9][0-9]*$/.test(quota.trim()) ? quota.trim() : null,\n throttledUsec: optionalCounter(/^throttled_usec ([0-9]+)$/m.exec(text ?? '')),\n })\n if (current === cgroupRoot) {\n complete = true\n break\n }\n current = dirname(current)\n if (!current.startsWith(`${cgroupRoot}/`) && current !== cgroupRoot) break\n }\n return {\n runnableWaitSomeUsec: optionalCounter(/^some [^\\n]*total=([0-9]+)\\s*$/m.exec(pressure ?? '')),\n ancestors,\n ancestorsComplete: complete,\n }\n}\n\nexport interface IsolatedCheckCpuIdentity {\n source: 'cgroup-v2'\n boundary: 'after-membership-through-tree-exit'\n sessionId: string\n cgroupPath: string\n inode: number\n}\n\n/** Only the blocked workload tree enters this cgroup; the caller stays outside it. */\nexport type IsolatedCheckCpuEvidence = IsolatedCheckCpuIdentity &\n (\n | { available: true; before: IsolatedCheckCpuCounters; after: IsolatedCheckCpuCounters }\n | { available: false; diagnostic: string }\n )\n\n/** Reusable sequential CPU accounting inside an already delegated Linux cgroup.\n * Opening does not change limits or delegation. close refuses an occupied or active group.\n */\nexport interface IsolatedCheckCpuSession {\n readonly id: string\n readonly cgroupPath: string\n close(): Promise<void>\n}\n\nexport type IsolatedCheckCpuSessionResult =\n | { succeeded: true; value: IsolatedCheckCpuSession }\n | { succeeded: false; reason: 'unavailable'; diagnostic: string; recoveryCgroupPath?: string }\n\ninterface CpuState {\n identity: IsolatedCheckCpuIdentity\n busy: boolean\n closed: boolean\n closing?: Promise<void>\n}\nconst sessions = new WeakMap<IsolatedCheckCpuSession, CpuState>()\n\nasync function counters(path: string): Promise<IsolatedCheckCpuCounters> {\n const text = await readFile(join(path, 'cpu.stat'), 'utf8')\n const counter = (key: string) => {\n const match = new RegExp(`^${key} ([0-9]+)$`, 'm').exec(text)\n const value = match ? Number(match[1]) : NaN\n if (!Number.isSafeInteger(value) || value < 0) throw new Error(`Invalid CPU counter ${key}`)\n return value\n }\n return {\n usageUsec: counter('usage_usec'),\n userUsec: counter('user_usec'),\n systemUsec: counter('system_usec'),\n resources: await resources(path),\n }\n}\n\nasync function emptyGroup(state: CpuState): Promise<void> {\n const path = state.identity.cgroupPath\n if ((await stat(path)).ino !== state.identity.inode)\n throw new Error('CPU cgroup identity changed')\n if (!/^populated 0$/m.test(await readFile(join(path, 'cgroup.events'), 'utf8')))\n throw new Error('CPU cgroup still contains processes')\n}\n\n/** Requires delegation from the execution placement; never creates a host-wide scope or fallback. */\nexport async function createIsolatedCheckCpuSession(): Promise<IsolatedCheckCpuSessionResult> {\n let path: string | undefined\n let identity: IsolatedCheckCpuIdentity | undefined\n try {\n if (process.platform !== 'linux')\n throw new Error('CPU accounting requires delegated Linux cgroup v2')\n const own = /^0::(\\/[^\\n]*)$/m.exec(await readFile('/proc/self/cgroup', 'utf8'))?.[1]\n if (!own || own.split('/').includes('..'))\n throw new Error('Current cgroup v2 identity unavailable')\n const id = randomUUID()\n const target = join(cgroupRoot, own.slice(1), `runtime-check-${id}`)\n await mkdir(target)\n path = target\n identity = {\n source: 'cgroup-v2',\n boundary: 'after-membership-through-tree-exit',\n sessionId: id,\n cgroupPath: path,\n inode: (await stat(path)).ino,\n }\n await counters(path)\n await writeFile(join(path, 'cgroup.kill'), '1')\n const state: CpuState = { identity, busy: false, closed: false }\n const session: IsolatedCheckCpuSession = Object.freeze({\n id,\n cgroupPath: path,\n async close() {\n if (state.closed) return\n if (state.busy) throw new Error('CPU session has an active check')\n return (state.closing ??= (async () => {\n try {\n await emptyGroup(state)\n await rmdir(target)\n state.closed = true\n } finally {\n state.closing = undefined\n }\n })())\n },\n })\n sessions.set(session, state)\n return { succeeded: true, value: session }\n } catch (error) {\n let recoveryCgroupPath = path\n if (path && identity) {\n try {\n if ((await stat(path)).ino === identity.inode) {\n await rmdir(path)\n recoveryCgroupPath = undefined\n }\n } catch {\n /* Keep the exact owned recovery identity when removal cannot be confirmed. */\n }\n }\n return {\n succeeded: false,\n reason: 'unavailable',\n diagnostic: String(error),\n ...(recoveryCgroupPath ? { recoveryCgroupPath } : {}),\n }\n }\n}\n\n/** Package-internal lease: the caller cannot manufacture a resource identity. */\nexport async function acquireIsolatedCheckCpu(session: IsolatedCheckCpuSession) {\n const state = sessions.get(session)\n if (!state || state.closed || state.closing || state.busy)\n throw new Error('CPU session is unavailable or busy')\n state.busy = true\n let before: IsolatedCheckCpuCounters | undefined\n try {\n await emptyGroup(state)\n } catch (error) {\n state.busy = false\n throw error\n }\n return {\n async start(pids: readonly number[]) {\n if (before) throw new Error('CPU workload already started')\n if ((await stat(state.identity.cgroupPath)).ino !== state.identity.inode)\n throw new Error('CPU cgroup identity changed')\n for (const pid of new Set(pids)) {\n if (!Number.isSafeInteger(pid) || pid < 1)\n throw new Error('Invalid protected process identity')\n await writeFile(join(state.identity.cgroupPath, 'cgroup.procs'), String(pid))\n }\n before = await counters(state.identity.cgroupPath)\n },\n async kill() {\n if ((await stat(state.identity.cgroupPath)).ino !== state.identity.inode)\n throw new Error('CPU cgroup identity changed')\n await writeFile(join(state.identity.cgroupPath, 'cgroup.kill'), '1')\n },\n async finish(remainingMs: number): Promise<IsolatedCheckCpuEvidence> {\n try {\n if (!before) throw new Error('Workload was not released under CPU accounting')\n const deadline = performance.now() + Math.max(0, remainingMs)\n while (true) {\n if ((await stat(state.identity.cgroupPath)).ino !== state.identity.inode)\n throw new Error('CPU cgroup identity changed')\n if (\n /^populated 0$/m.test(\n await readFile(join(state.identity.cgroupPath, 'cgroup.events'), 'utf8'),\n )\n )\n break\n if (performance.now() >= deadline)\n throw new Error('CPU cgroup still contains processes at the check deadline')\n await delay(Math.min(10, Math.max(1, deadline - performance.now())))\n }\n const after = await counters(state.identity.cgroupPath)\n if (\n (['usageUsec', 'userUsec', 'systemUsec'] as const).some(\n (key) => after[key] < before![key],\n )\n )\n throw new Error('CPU counters moved backwards')\n return { ...state.identity, available: true, before, after }\n } catch (error) {\n return { ...state.identity, available: false, diagnostic: String(error) }\n }\n },\n release() {\n state.busy = false\n },\n }\n}\n","import { spawn } from 'node:child_process'\nimport type { Writable } from 'node:stream'\nimport type { acquireIsolatedCheckCpu } from './isolated-check-cpu'\nimport type { IsolatedCheckResult } from './isolated-checker'\nimport { armDeadlineTimer } from './supervise/deadline'\n\nexport function executeIsolatedCheckProcess(\n args: string[],\n timeoutMs: number,\n limit: number,\n signal?: AbortSignal,\n cpu?: Awaited<ReturnType<typeof acquireIsolatedCheckCpu>>,\n): Promise<IsolatedCheckResult> {\n return new Promise((done) => {\n const began = performance.now()\n // No exec or fork precedes the explicit permit; EOF aborts this trusted launcher.\n // Descendants, including Bubblewrap's namespaces, are born in the owned cgroup.\n const gatedExec =\n 'import os,sys; os.write(3,b\"R\\\\n\"); permit=os.read(4,1); os.close(4); (os.execve(sys.argv[1],sys.argv[1:],{}) if permit==b\"1\" else os._exit(125))'\n const argv = [\n '/usr/bin/bwrap',\n '--json-status-fd',\n '3',\n ...(cpu ? ['--unshare-user', '--disable-userns'] : []),\n ...args,\n ]\n const child = spawn(\n cpu ? '/usr/bin/python3' : argv[0]!,\n cpu ? ['-I', '-c', gatedExec, ...argv] : argv.slice(1),\n {\n env: {},\n stdio: cpu\n ? ['ignore', 'pipe', 'pipe', 'pipe', 'pipe']\n : ['ignore', 'pipe', 'pipe', 'pipe'],\n detached: true,\n },\n )\n const stdout: Buffer[] = []\n const stderr: Buffer[] = []\n let bytes = 0\n let status = ''\n let failure: 'timeout' | 'cancelled' | 'output-limit' | 'refused' | undefined\n let cpuError: string | undefined\n let cpuStarting: Promise<void> | undefined\n let cpuStopping: Promise<void> | undefined\n const release = cpu ? (child.stdio[4] as Writable) : undefined\n const killProcessGroup = () => {\n if (child.pid && child.exitCode === null && child.signalCode === null) {\n try {\n process.kill(-child.pid, 'SIGKILL')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ESRCH') child.kill('SIGKILL')\n }\n }\n }\n const stop = (reason: typeof failure) => {\n failure ??= reason\n if (!cpu) return killProcessGroup()\n // Do not reap/reuse the blocked launcher's PID during its membership write.\n cpuStopping ??= (async () => {\n await cpuStarting\n try {\n await cpu.kill()\n } catch (error) {\n cpuError ??= String(error)\n } finally {\n killProcessGroup()\n }\n })()\n }\n const clearTimer = armDeadlineTimer(timeoutMs, () => stop('timeout'), true)\n const cancel = () => stop('cancelled')\n signal?.addEventListener('abort', cancel, { once: true })\n if (signal?.aborted) cancel()\n const capture = (target: Buffer[]) => (chunk: Buffer) => {\n const remaining = Math.max(0, limit - bytes)\n bytes += chunk.length\n if (remaining) target.push(chunk.subarray(0, remaining))\n if (bytes > limit) stop('output-limit')\n }\n child.stdio[3]?.on('data', (chunk: Buffer) => {\n if (status.length + chunk.length > 16_384) {\n stop('output-limit')\n return\n }\n status += chunk.toString()\n if (cpu && !cpuStarting && !failure && child.pid && status.startsWith('R\\n')) {\n cpuStarting = (async () => {\n try {\n await cpu.start([child.pid!])\n if (!failure && child.exitCode === null && child.signalCode === null) release?.end('1')\n } catch (error) {\n cpuError = String(error)\n stop('refused')\n }\n })()\n }\n })\n release?.on('error', (error) => {\n cpuError = String(error)\n stop('refused')\n })\n // EOF aborts before exec; cancellation kills the owned cgroup after membership.\n child.once('exit', () => release?.destroy())\n child.stdout!.on('data', capture(stdout))\n child.stderr!.on('data', capture(stderr))\n let spawnError: Error | undefined\n child.on('error', (error) => {\n spawnError = error\n })\n child.on('close', async (code) => {\n const cpuCommandWallMs = cpu ? performance.now() - began : undefined\n await cpuStarting\n await cpuStopping\n const cpuEvidence = await cpu?.finish(timeoutMs - (performance.now() - began))\n clearTimer()\n signal?.removeEventListener('abort', cancel)\n const outBytes = Buffer.concat(stdout)\n const errBytes = Buffer.concat(stderr)\n const out = outBytes.toString()\n const err = errBytes.toString()\n const command = {\n wallMs: cpuCommandWallMs ?? performance.now() - began,\n stdoutBase64: outBytes.toString('base64'),\n stderrBase64: errBytes.toString('base64'),\n outputComplete: bytes <= limit,\n ...(cpuEvidence ? { cpu: cpuEvidence } : {}),\n }\n const evidence = { stdout: out, stderr: err, exitCode: code, command }\n // Only Bubblewrap writes this private pipe; command stderr cannot forge setup status.\n const executed = status.split('\\n').some((line) => {\n try {\n const record: unknown = JSON.parse(line)\n return (\n record !== null &&\n typeof record === 'object' &&\n 'exit-code' in record &&\n typeof record['exit-code'] === 'number' &&\n record['exit-code'] === code\n )\n } catch {\n return false\n }\n })\n if (failure)\n done({\n succeeded: false,\n reason: failure,\n diagnostic: cpuError || err || failure,\n ...evidence,\n })\n else if (spawnError)\n done({ succeeded: false, reason: 'refused', diagnostic: String(spawnError), ...evidence })\n else if (!executed)\n done({\n succeeded: false,\n reason: 'refused',\n diagnostic: err || 'Bubblewrap did not confirm command execution',\n ...evidence,\n })\n else if (code !== 0)\n done({\n succeeded: false,\n reason: 'failed',\n diagnostic: err || out || `Check exited ${code}`,\n ...evidence,\n })\n else done({ succeeded: true, value: { stdout: out, stderr: err }, command })\n })\n })\n}\n","import { execFile } from 'node:child_process'\nimport { randomUUID } from 'node:crypto'\nimport { constants as fsConstants } from 'node:fs'\nimport {\n chmod,\n lstat,\n mkdir,\n mkdtemp,\n open,\n opendir,\n readlink,\n realpath,\n rm,\n stat,\n symlink,\n writeFile,\n} from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { dirname, join, relative, sep } from 'node:path'\nimport { promisify } from 'node:util'\nimport {\n type AgentCandidateWorkspaceManifestMaterial,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport type {\n CreateSandboxOptions,\n SandboxInstance,\n SandboxResources,\n} from '@tangle-network/sandbox'\nimport {\n captureMaterializedWorkspace,\n scanMaterializedWorkspaceManifest,\n WorkspaceScanLimitError,\n} from '../candidate-execution/artifacts'\nimport {\n acquireIsolatedCheckCpu,\n type IsolatedCheckCpuEvidence,\n type IsolatedCheckCpuSession,\n} from './isolated-check-cpu'\nimport {\n boxCheckOutputReader,\n type IsolatedCheckOutputEvidence,\n type IsolatedCheckOutputOptions,\n localCheckOutputReader,\n prepareIsolatedCheckOutputs,\n retainIsolatedCheckOutputs,\n stopCheckBoxForRecovery,\n stopCheckProcess,\n} from './isolated-checker-outputs'\nimport { executeIsolatedCheckProcess } from './isolated-checker-process'\nimport { runAbortable } from './supervise/abortable'\nimport { armDeadlineTimer } from './supervise/deadline'\n\nexport {\n type IsolatedCheckOutputDeclaration,\n type IsolatedCheckOutputEvidence,\n type IsolatedCheckOutputFailure,\n type IsolatedCheckOutputOptions,\n validateIsolatedCheckOutputs,\n} from './isolated-checker-outputs'\n\nexport interface IsolatedCheckOptions {\n /** Trusted workspace boundary containing the untrusted tree. */\n workspaceRoot: string\n tree: string\n /** Executable and arguments, without host shell interpretation. */\n command: readonly [string, ...string[]]\n timeoutMs?: number\n maxOutputBytes?: number\n /** Maximum regular-file bytes copied or captured from the input tree when set. */\n maxInputBytes?: number\n /** Maximum entries in the input tree when set. */\n maxInputEntries?: number\n signal?: AbortSignal\n /** Run the check in its own Sandbox box instead of Linux Bubblewrap on this host. */\n box?: IsolatedCheckBox\n /** Environment the command receives beside PATH, HOME and LANG: a declared check's named\n * secrets and its own settings. Nothing else of this process's environment reaches it. */\n env?: Readonly<Record<string, string>>\n /** Retain explicitly approved output files, on command success or failure, before cleanup. */\n outputs?: IsolatedCheckOutputOptions\n /** Sequential local workload-tree CPU accounting; requires a delegated session. */\n cpuSession?: IsolatedCheckCpuSession\n}\n\n/**\n * A fresh Sandbox box for one check, owned by an account the judged run holds no key to.\n *\n * Any key of a Sandbox account can read, write, and execute in every box of that account.\n * A check box on the run's own account is therefore reachable by the run it judges.\n * The check refuses before it creates a box when its account is one of `builderAccounts`.\n */\nexport interface IsolatedCheckBox {\n /**\n * Client authenticated with the check's own key: a `Sandbox` from SDK 0.46 or later.\n * Written as its two methods because the Runtime peer range admits SDKs without `createIsolated`.\n */\n client: {\n getIdentity(): Promise<{ customerId: string }>\n createIsolated(\n options: Omit<CreateSandboxOptions, 'ownerContext'>,\n requestOptions?: { signal?: AbortSignal },\n ): Promise<SandboxInstance>\n }\n /** `customerId` from `Sandbox.getIdentity()` for every Sandbox key the judged run holds. */\n builderAccounts: readonly [string, ...string[]]\n /** The check is the run's own step in its owner's account (a graph check node), not a judge:\n * `builderAccounts` is not consulted, and the box keeps a durable home. */\n ownerStep?: true\n /** Sandbox environment or image that holds the check's toolchain. */\n environment: string\n /** Set `memoryMB` to require the API to report a finite granted limit before upload. */\n resources?: SandboxResources\n /** Sandbox's `runtime` create field, sent by SDK 1.0.265 and later. Absent: its default. */\n runtime?: 'docker' | 'firecracker'\n /** Domains the check may reach, such as a knowledge store or a git host. Empty or absent: the\n * box's egress is blocked. Otherwise strict: these domains only, with no implicit list. */\n egress?: readonly string[]\n /**\n * The check runs containers. Sandbox starts a box's rootless container daemon only with its\n * managed agent runtime, so this box is created with `agent: true`; it still receives no owner\n * secret, which its create receipt must confirm. It is not `ephemeral`, so its home is a disk\n * sized by `resources.diskGB` instead of a small in-memory home that image layers overflow.\n */\n containers?: boolean\n}\n\n/** The box a check ran in and the exact bytes it received. */\nexport interface IsolatedCheckBoxEvidence {\n sandboxId: string\n /** `customerId` of the check's key. */\n account: string\n /** API-reported granted memory limit in MiB, when explicitly requested. */\n memoryMB?: number\n /** Every file the box received; each sha256 is also the digest the box computed on receipt. */\n input: AgentCandidateWorkspaceManifestMaterial\n /** Canonical digest of `input`. */\n inputDigest: Sha256Digest\n}\n\n/** Local protected-command launch through closed pipes, excluding input staging and cleanup.\n * Capture contains exact bounded bytes; outputComplete is false when the capture limit omitted bytes.\n * A refused launch can carry diagnostics without proving command execution. Box backends leave this absent.\n */\nexport interface IsolatedCheckCommandEvidence {\n wallMs: number\n /** Canonical manifest digest of the copied input, provided for local CPU checks. */\n inputDigest?: Sha256Digest\n stdoutBase64: string\n stderrBase64: string\n outputComplete: boolean\n cpu?: IsolatedCheckCpuEvidence\n}\n\nexport type IsolatedCheckResult =\n | {\n succeeded: true\n value: { stdout: string; stderr: string }\n box?: IsolatedCheckBoxEvidence\n outputs?: IsolatedCheckOutputEvidence\n command?: IsolatedCheckCommandEvidence\n }\n | {\n succeeded: false\n reason:\n | 'refused'\n | 'failed'\n | 'timeout'\n | 'cancelled'\n | 'output-limit'\n | 'input-limit'\n | 'cleanup-failed'\n diagnostic: string\n /** Bounded command evidence, when a process was launched. */\n stdout?: string\n stderr?: string\n exitCode?: number | null\n /** Cleanup failures never replace the primary command failure. */\n cleanupDiagnostic?: string\n /** Present once a check box received its complete input. */\n box?: IsolatedCheckBoxEvidence\n outputs?: IsolatedCheckOutputEvidence\n command?: IsolatedCheckCommandEvidence\n }\n\nconst toolchains = ['/usr', '/bin', '/lib', '/lib64']\nconst contains = (parent: string, child: string) => {\n const path = relative(parent, child)\n return path === '' || (path !== '..' && !path.startsWith(`..${sep}`) && !path.startsWith(sep))\n}\n\n/**\n * Run an untrusted check in Linux Bubblewrap, or in its own Sandbox box when `box` is set.\n * Never falls back to host execution.\n *\n * Bubblewrap requires /usr/bin/bwrap and permission to create Linux namespaces.\n * Only trusted system toolchains, private proc/dev/tmp, and the writable copy are mounted.\n * The canonical input path remains the working directory. Requested output files are retained\n * before cleanup; otherwise copy writes are discarded.\n * Time and output are bounded; input copy bytes and entries are bounded when requested.\n * The command's memory and generated files require a resource-limited placement.\n * Callers must keep the input and trusted toolchains stable while preparing the check.\n *\n * A box check creates one fresh box with no owner secrets and blocked egress (or strict egress to\n * the placement's named domains), delivers the tree's regular files verified by sha256, runs the\n * command there with only the environment `env` names, and deletes the box after successful\n * requested retention. Incomplete retention returns private recovery custody only after the\n * native owner confirms the box stopped. Box file capture requires /usr/bin/python3. Local recovery scratch is the\n * caller's responsibility; the resource-limited placement requirement still applies.\n */\nexport async function runIsolatedCheck(\n options: IsolatedCheckOptions,\n): Promise<IsolatedCheckResult> {\n if (!options.cpuSession) return runProtectedCheck(options)\n if (options.box)\n return {\n succeeded: false,\n reason: 'refused',\n diagnostic: 'CPU sessions require local delegated execution',\n }\n let cpu: Awaited<ReturnType<typeof acquireIsolatedCheckCpu>> | undefined\n try {\n cpu = await acquireIsolatedCheckCpu(options.cpuSession)\n return await runProtectedCheck(options, cpu)\n } catch (error) {\n return { succeeded: false, reason: 'refused', diagnostic: String(error) }\n } finally {\n cpu?.release()\n }\n}\n\nasync function runProtectedCheck(\n options: IsolatedCheckOptions,\n cpu?: Awaited<ReturnType<typeof acquireIsolatedCheckCpu>>,\n): Promise<IsolatedCheckResult> {\n if (options.box) return runInBox(options, options.box)\n let scratch: string | undefined\n let outputs: IsolatedCheckOutputEvidence | undefined\n let result: IsolatedCheckResult\n try {\n const retention = prepareIsolatedCheckOutputs(options.outputs)\n if (process.platform !== 'linux') throw new Error('Linux Bubblewrap namespaces are required')\n const { timeoutMs, maxOutputBytes, maxInputBytes, maxInputEntries } = checkLimits(options)\n if (options.signal?.aborted)\n return { succeeded: false, reason: 'cancelled', diagnostic: 'Check cancelled' }\n const { workspace, tree } = await protectedTree(options)\n const binds: string[] = []\n for (const path of toolchains) {\n let actual: string\n try {\n actual = await realpath(path)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue\n throw error\n }\n for (const mount of [path, actual]) {\n if (\n contains(mount, workspace) ||\n contains(workspace, mount) ||\n contains(mount, tree) ||\n contains(tree, mount)\n ) {\n throw new Error(`Toolchain overlaps protected workspace: ${path}`)\n }\n }\n binds.push('--ro-bind', actual, path)\n }\n // Fixed mount destinations must not cover or be covered by the evidence tree.\n if (['/proc', '/dev'].some((path) => contains(path, tree) || contains(tree, path))) {\n throw new Error('Tree overlaps a reserved namespace mount')\n }\n scratch = await mkdtemp(join(tmpdir(), 'runtime-check-'))\n if (contains(tree, scratch)) throw new Error('Temporary storage must be outside the input tree')\n const copy = join(scratch, 'tree')\n await copyBoundedTree(tree, copy, maxInputBytes, maxInputEntries)\n const input = retention || cpu ? await scanMaterializedWorkspaceManifest(copy) : undefined\n if (retention && input) assertOutputPathsUnoccupied(retention.paths, input)\n const args = [\n '--unshare-all',\n '--die-with-parent',\n '--new-session',\n '--cap-drop',\n 'ALL',\n '--clearenv',\n '--setenv',\n 'PATH',\n '/usr/bin:/bin',\n '--setenv',\n 'HOME',\n '/tmp',\n '--setenv',\n 'LANG',\n 'C',\n ...Object.entries(options.env ?? {}).flatMap(([name, value]) => ['--setenv', name, value]),\n ...binds,\n '--proc',\n '/proc',\n '--dev',\n '/dev',\n '--tmpfs',\n '/tmp',\n '--bind',\n copy,\n tree,\n '--chdir',\n tree,\n '--',\n ...options.command,\n ]\n result = await executeIsolatedCheckProcess(args, timeoutMs, maxOutputBytes, options.signal, cpu)\n if (cpu && input && result.command) result.command.inputDigest = canonicalCandidateDigest(input)\n if (retention && input && (result.succeeded || result.reason !== 'refused')) {\n outputs = await retainIsolatedCheckOutputs(\n retention,\n canonicalCandidateDigest(input),\n localCheckOutputReader(copy),\n )\n if (outputs.status === 'incomplete')\n outputs = { ...outputs, source: { kind: 'local', path: scratch } }\n result = withRetainedOutputs(result, outputs)\n }\n } catch (error) {\n result = {\n succeeded: false,\n reason: error instanceof InputLimitError ? 'input-limit' : 'refused',\n diagnostic: String(error),\n }\n }\n if (scratch && outputs?.status !== 'incomplete') {\n try {\n await removeScratch(scratch)\n } catch (error) {\n const cleanupDiagnostic = String(error)\n result = result.succeeded\n ? {\n succeeded: false,\n reason: 'cleanup-failed',\n diagnostic: cleanupDiagnostic,\n stdout: result.value.stdout,\n stderr: result.value.stderr,\n exitCode: 0,\n ...(result.command ? { command: result.command } : {}),\n }\n : { ...result, cleanupDiagnostic }\n }\n }\n return outputs ? { ...result, outputs } : result\n}\n\n/** A preexisting input file must never masquerade as newly produced evaluator evidence. */\nfunction assertOutputPathsUnoccupied(\n paths: readonly string[],\n input: AgentCandidateWorkspaceManifestMaterial,\n): void {\n for (const path of paths)\n if (\n input.files.some(\n (file) =>\n file.path === path ||\n file.path.startsWith(`${path}/`) ||\n path.startsWith(`${file.path}/`),\n )\n )\n throw new Error('Declared check output path overlaps an input file')\n}\n\nfunction withRetainedOutputs(\n result: IsolatedCheckResult,\n outputs: IsolatedCheckOutputEvidence,\n): IsolatedCheckResult {\n if (!result.succeeded || outputs.status === 'retained') return { ...result, outputs }\n return {\n succeeded: false,\n reason: 'failed',\n diagnostic: 'Check outputs were not completely retained',\n stdout: result.value.stdout,\n stderr: result.value.stderr,\n exitCode: 0,\n ...(result.command ? { command: result.command } : {}),\n outputs,\n }\n}\n\nfunction checkLimits(options: IsolatedCheckOptions): {\n timeoutMs: number\n maxOutputBytes: number\n maxInputBytes?: number\n maxInputEntries?: number\n} {\n const timeoutMs = options.timeoutMs ?? 30_000\n const maxOutputBytes = options.maxOutputBytes ?? 1_048_576\n const maxInputBytes = options.maxInputBytes\n const maxInputEntries = options.maxInputEntries\n if (\n !Number.isSafeInteger(timeoutMs) ||\n timeoutMs < 1 ||\n timeoutMs > 2_147_483_647 ||\n !Number.isSafeInteger(maxOutputBytes) ||\n maxOutputBytes < 1 ||\n (maxInputBytes !== undefined && (!Number.isSafeInteger(maxInputBytes) || maxInputBytes < 1)) ||\n (maxInputEntries !== undefined &&\n (!Number.isSafeInteger(maxInputEntries) || maxInputEntries < 1))\n )\n throw new Error('Invalid execution limits')\n if (!options.command.length || !options.command[0]) throw new Error('A command is required')\n return { timeoutMs, maxOutputBytes, maxInputBytes, maxInputEntries }\n}\n\nclass InputLimitError extends Error {}\n\n/** Copy in bounded chunks, preserving symlink text without reading its target. */\nasync function copyBoundedTree(\n source: string,\n destination: string,\n maxBytes: number | undefined,\n maxEntries: number | undefined,\n): Promise<void> {\n let bytes = 0\n let entries = 0\n const buffer = Buffer.allocUnsafe(1024 * 1024)\n const visit = async (from: string, to: string, isRoot = false): Promise<void> => {\n if (!isRoot && ++entries > (maxEntries ?? Number.MAX_SAFE_INTEGER))\n throw new InputLimitError('Input tree exceeds maxInputEntries')\n const info = await lstat(from)\n if (info.isSymbolicLink()) {\n await symlink(await readlink(from), to)\n } else if (info.isDirectory()) {\n await mkdir(to, { mode: 0o700 })\n for await (const entry of await opendir(from))\n await visit(join(from, entry.name), join(to, entry.name))\n await chmod(to, info.mode & 0o777)\n } else if (info.isFile()) {\n if (maxBytes !== undefined && info.size > maxBytes - bytes)\n throw new InputLimitError('Input tree exceeds maxInputBytes')\n const input = await open(from, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW)\n try {\n const output = await open(to, 'wx', info.mode & 0o777)\n try {\n while (true) {\n const { bytesRead } = await input.read(\n buffer,\n 0,\n maxBytes === undefined\n ? buffer.length\n : Math.min(buffer.length, maxBytes - bytes + 1),\n null,\n )\n if (bytesRead === 0) break\n bytes += bytesRead\n if (maxBytes !== undefined && bytes > maxBytes)\n throw new InputLimitError('Input tree exceeds maxInputBytes')\n let written = 0\n while (written < bytesRead) {\n const result = await output.write(buffer, written, bytesRead - written)\n if (result.bytesWritten === 0) throw new Error('Input copy made no write progress')\n written += result.bytesWritten\n }\n }\n } finally {\n await output.close()\n }\n await chmod(to, info.mode & 0o777)\n } finally {\n await input.close()\n }\n } else {\n throw new Error(`Input tree contains an unsupported entry: ${from}`)\n }\n }\n await visit(source, destination, true)\n}\n\nasync function checkInputEntries(root: string, maxEntries: number): Promise<void> {\n let count = 0\n const visit = async (path: string, isRoot = false): Promise<void> => {\n if (!isRoot && ++count > maxEntries)\n throw new InputLimitError('Input tree exceeds maxInputEntries')\n if (!(await lstat(path)).isDirectory()) return\n for await (const entry of await opendir(path)) await visit(join(path, entry.name))\n }\n await visit(root, true)\n}\n\nasync function protectedTree(\n options: IsolatedCheckOptions,\n): Promise<{ workspace: string; tree: string }> {\n const workspace = await realpath(options.workspaceRoot)\n const tree = await realpath(options.tree)\n if (!contains(workspace, tree) || !(await stat(tree)).isDirectory())\n throw new Error('Tree must be a directory inside the workspace')\n return { workspace, tree }\n}\n\n/** Box-workspace-relative directory that receives the tree and is the command's cwd. */\nconst BOX_TREE = 'tree'\n/** Setup headroom in the requested native lifetime policy; this is not a deletion guarantee. */\nconst BOX_SETUP_SECONDS = 900\n/** The box's own process timeout is a backstop behind this module's deadline. */\nconst BOX_PROCESS_BACKSTOP_MS = 30_000\n\nasync function runInBox(\n options: IsolatedCheckOptions,\n placement: IsolatedCheckBox,\n): Promise<IsolatedCheckResult> {\n let box: SandboxInstance | undefined\n let evidence: IsolatedCheckBoxEvidence | undefined\n let outputs: IsolatedCheckOutputEvidence | undefined\n let retention: IsolatedCheckOutputOptions | undefined\n let maxLifetimeSeconds: number | undefined\n let commandAttempted = false\n let commandSettled = false\n let result: IsolatedCheckResult\n try {\n retention = prepareIsolatedCheckOutputs(options.outputs)\n const { timeoutMs, maxOutputBytes, maxInputBytes, maxInputEntries } = checkLimits(options)\n maxLifetimeSeconds = Math.ceil(timeoutMs / 1_000) + BOX_SETUP_SECONDS\n if (options.signal?.aborted)\n return { succeeded: false, reason: 'cancelled', diagnostic: 'Check cancelled' }\n const { tree } = await protectedTree(options)\n if (maxInputEntries !== undefined) await checkInputEntries(tree, maxInputEntries)\n // Read each file once: the digest recorded is the digest of the bytes sent.\n const captured = await captureMaterializedWorkspace(tree, {\n limits: {\n maxFiles: maxInputEntries ?? Number.MAX_SAFE_INTEGER,\n maxFileBytes: maxInputBytes ?? Number.MAX_SAFE_INTEGER,\n maxTotalFileBytes: maxInputBytes ?? Number.MAX_SAFE_INTEGER,\n },\n })\n if (retention) assertOutputPathsUnoccupied(retention.paths, captured.manifest)\n const judge = placement.ownerStep !== true\n if (\n judge &&\n (placement.builderAccounts.length === 0 || placement.builderAccounts.some((id) => !id))\n )\n throw new Error('builderAccounts must name the account of every key the judged run holds')\n const memoryMB = placement.resources?.memoryMB\n if (\n memoryMB !== undefined &&\n (!Number.isSafeInteger(memoryMB) ||\n memoryMB < 1 ||\n placement.resources?.advisory === true ||\n placement.resources?.advisoryFields?.includes('memoryMB'))\n )\n throw new Error('Check box requires an explicit finite resources.memoryMB limit')\n const account = (await placement.client.getIdentity()).customerId\n if (!account) throw new Error('Sandbox returned no account for the check key')\n if (judge && placement.builderAccounts.includes(account))\n throw new Error(\n `Check account ${account} is an account the judged run holds a key to, so the run can reach the check box`,\n )\n options.signal?.throwIfAborted()\n box = await placement.client.createIsolated(\n {\n environment: placement.environment,\n agent: placement.containers === true,\n bare: false,\n ephemeral: placement.containers !== true && judge,\n egressPolicy: egressFor(placement),\n ...(placement.runtime ? { runtime: placement.runtime } : {}),\n ...(placement.resources ? { resources: placement.resources } : {}),\n maxLifetimeSeconds,\n // A new identity per call: a replayed create could return a box another caller used.\n idempotencyKey: `agent-runtime-check-${randomUUID()}`,\n },\n options.signal ? { signal: options.signal } : undefined,\n )\n const receipt = box.createReceipt()\n if (\n receipt?.outcome !== 'created' ||\n receipt.ownerContext !== 'isolated' ||\n !Array.isArray(receipt.injectedSecrets) ||\n receipt.injectedSecrets.length !== 0\n )\n throw new Error('Sandbox did not confirm a fresh box with no owner secrets')\n const grantedMemoryMB = box.resources?.memoryMB\n if (\n memoryMB !== undefined &&\n (typeof grantedMemoryMB !== 'number' ||\n !Number.isSafeInteger(grantedMemoryMB) ||\n grantedMemoryMB < 1 ||\n grantedMemoryMB > memoryMB)\n )\n throw new Error('Sandbox did not confirm the requested finite memory cgroup limit')\n const egress = (await box.egress.get()).policy\n const wanted = egressFor(placement)\n if (\n egress.mode !== wanted.mode ||\n (wanted.mode === 'strict' &&\n (egress.includeImplicitDomains === true ||\n [...(egress.allowDomains ?? [])].sort().join(',') !==\n [...(wanted.allowDomains ?? [])].sort().join(',')))\n )\n throw new Error(\n `Check box egress is ${egress.mode} ${JSON.stringify(egress.allowDomains ?? [])}, not ${wanted.mode} ${JSON.stringify(wanted.allowDomains ?? [])}`,\n )\n // One archive, not a request per file: a box's sidecar admits a few hundred file requests a\n // minute. It is staged from the captured bytes, so the box receives what the manifest names.\n const staging = await mkdtemp(join(tmpdir(), 'runtime-check-box-'))\n try {\n for (const file of captured.files) {\n const path = join(staging, file.path)\n await mkdir(dirname(path), { recursive: true })\n await writeFile(path, file.bytes, { mode: file.mode })\n }\n options.signal?.throwIfAborted()\n await box.fs.uploadDir(staging, BOX_TREE)\n } finally {\n await rm(staging, { recursive: true, force: true })\n }\n await verifyBoxTree(box, captured.manifest.files)\n evidence = {\n sandboxId: box.id,\n account,\n ...(memoryMB === undefined ? {} : { memoryMB: grantedMemoryMB }),\n input: captured.manifest,\n inputDigest: canonicalCandidateDigest(captured.manifest),\n }\n commandAttempted = true\n const execution = await executeInBox(\n box,\n options.command,\n timeoutMs,\n maxOutputBytes,\n options.env ?? {},\n options.signal,\n )\n result = execution.result\n commandSettled = execution.commandSettled\n } catch (error) {\n result = {\n succeeded: false,\n reason: options.signal?.aborted\n ? 'cancelled'\n : error instanceof InputLimitError || error instanceof WorkspaceScanLimitError\n ? 'input-limit'\n : 'refused',\n diagnostic: String(error),\n }\n }\n // A transport failure leaves command state unknown. Preserve that box only after its native\n // lifecycle owner confirms a whole-box stop; never keep live or unconfirmed recovery custody.\n if (\n box &&\n evidence &&\n retention &&\n maxLifetimeSeconds !== undefined &&\n commandAttempted &&\n (!commandSettled || result.succeeded || result.reason !== 'refused')\n ) {\n outputs = commandSettled\n ? await retainIsolatedCheckOutputs(\n retention,\n evidence.inputDigest,\n boxCheckOutputReader(box, BOX_TREE, retention.timeoutMs ?? 30_000),\n )\n : {\n executionId: retention.executionId,\n inputDigest: evidence.inputDigest,\n status: 'incomplete',\n files: [],\n missing: retention.paths.map((path) => ({ path, reason: 'capture-failed' as const })),\n }\n result = withRetainedOutputs(result, outputs)\n if (outputs.status === 'incomplete') {\n if (await stopCheckBoxForRecovery(box))\n outputs = {\n ...outputs,\n source: { kind: 'sandbox', sandboxId: box.id, state: 'stopped' },\n }\n else if (!result.succeeded)\n result = {\n ...result,\n cleanupDiagnostic: 'Recovery source stop was not confirmed; box deletion was requested',\n }\n }\n }\n if (box && outputs?.source?.kind !== 'sandbox') {\n try {\n await box.delete()\n } catch (error) {\n const cleanupDiagnostic = `Check box ${box.id} was not deleted: ${String(error)}`\n result = result.succeeded\n ? {\n succeeded: false,\n reason: 'cleanup-failed',\n diagnostic: cleanupDiagnostic,\n stdout: result.value.stdout,\n stderr: result.value.stderr,\n exitCode: 0,\n ...(result.command ? { command: result.command } : {}),\n }\n : {\n ...result,\n cleanupDiagnostic: [result.cleanupDiagnostic, cleanupDiagnostic]\n .filter(Boolean)\n .join('; '),\n }\n }\n }\n return { ...result, ...(evidence ? { box: evidence } : {}), ...(outputs ? { outputs } : {}) }\n}\n\n/** Refuse unless the box reads each file with its manifest digest. `find` names the files: a box\n * process takes 256 arguments at most. A name holding a newline or backslash, which coreutils\n * escapes, does not compare. */\nasync function verifyBoxTree(\n box: SandboxInstance,\n files: readonly { path: string; sha256: string }[],\n) {\n const hash = ['find', '.', '-type', 'f', '-exec', 'sha256sum', '{}', '+'] as const\n const { result } = await executeInBox(box, hash, BOX_SETUP_SECONDS * 1_000, Infinity, {})\n if (!result.succeeded) throw new Error(`Check box could not hash its tree: ${result.diagnostic}`)\n const listing = result.value.stdout\n // Each line is `<hex> ./<path>`.\n const read = new Set(\n listing.split('\\n').map((line) => `sha256:${line.slice(0, 64)} ${line.slice(68)}`),\n )\n for (const file of files)\n if (!read.has(`${file.sha256} ${file.path}`))\n throw new Error(`Check box received different bytes for ${file.path}`)\n}\n\n/** Blocked unless the placement names domains; then strict, with no implicit domain list. */\nfunction egressFor(placement: IsolatedCheckBox): {\n mode: 'blocked' | 'strict'\n allowDomains?: string[]\n includeImplicitDomains?: false\n} {\n const domains = [...new Set(placement.egress ?? [])].filter((domain) => domain.trim() !== '')\n return domains.length === 0\n ? { mode: 'blocked' }\n : { mode: 'strict', allowDomains: domains, includeImplicitDomains: false }\n}\n\nasync function executeInBox(\n box: SandboxInstance,\n command: readonly [string, ...string[]],\n timeoutMs: number,\n limit: number,\n env: Readonly<Record<string, string>>,\n signal?: AbortSignal,\n): Promise<{ result: IsolatedCheckResult; commandSettled: boolean }> {\n const [executable, ...args] = command\n let child: Awaited<ReturnType<SandboxInstance['process']['spawnExact']>> | undefined\n const deadline = new AbortController()\n const stdout: Buffer[] = []\n const stderr: Buffer[] = []\n let bytes = 0\n let failure: 'timeout' | 'cancelled' | 'output-limit' | 'refused' | undefined\n let stopping: Promise<boolean> | undefined\n let stopped = false\n const stop = (reason: typeof failure) => {\n failure ??= reason\n deadline.abort()\n if (child) stopping ??= stopCheckProcess(child)\n }\n const clearTimer = armDeadlineTimer(timeoutMs, () => stop('timeout'), true)\n const cancel = () => stop('cancelled')\n signal?.addEventListener('abort', cancel, { once: true })\n if (signal?.aborted) cancel()\n // The box retains the output; a log stream that ends before its exit event is read again whole.\n const capture = async (running: NonNullable<typeof child>) => {\n while (!deadline.signal.aborted)\n try {\n stdout.length = stderr.length = bytes = 0\n for await (const { type, data } of running.logs()) {\n if (deadline.signal.aborted) return\n const chunk = Buffer.from(data)\n if (bytes < limit)\n (type === 'stdout' ? stdout : stderr).push(chunk.subarray(0, limit - bytes))\n bytes += chunk.length\n if (bytes > limit) stop('output-limit')\n }\n return\n } catch (error) {\n if (!String(error).includes('stream ended before its exit event')) throw error\n }\n }\n let completion: { exitCode: number; exitSignal?: string } | undefined\n try {\n child = await runAbortable(\n () => {\n const launching = box.process.spawnExact(executable, args, {\n cwd: BOX_TREE,\n env: { PATH: '/usr/bin:/bin', HOME: '/tmp', LANG: 'C', ...env },\n inheritEnv: false,\n timeoutMs: timeoutMs + BOX_PROCESS_BACKSTOP_MS,\n })\n // A late response must not leave a newly observed process running after the caller stopped.\n void launching.then(\n (late) => {\n if (deadline.signal.aborted) void stopCheckProcess(late)\n },\n () => undefined,\n )\n return launching\n },\n deadline.signal,\n 'Check interrupted',\n )\n const running = child\n completion = await runAbortable(\n async () => {\n await capture(running)\n return { exitCode: await running.wait(), exitSignal: (await running.status()).exitSignal }\n },\n deadline.signal,\n 'Check interrupted',\n )\n } catch (error) {\n if (child) stopping ??= stopCheckProcess(child)\n else if (!failure && (error as Error)?.message?.startsWith('Command setup failed')) {\n failure = 'refused'\n stderr.push(Buffer.from((error as Error).message))\n }\n if (!failure) throw error\n } finally {\n clearTimer()\n signal?.removeEventListener('abort', cancel)\n stopped = (await stopping) === true\n }\n const out = Buffer.concat(stdout).toString()\n const err = Buffer.concat(stderr).toString()\n const exitCode = completion?.exitCode ?? null\n const exitSignal = completion?.exitSignal\n const evidence = { stdout: out, stderr: err, exitCode: exitSignal ? null : exitCode }\n const finish = (result: IsolatedCheckResult) => ({\n result,\n commandSettled: completion !== undefined || stopped || failure === 'refused',\n })\n if (failure)\n return finish({ succeeded: false, reason: failure, diagnostic: err || failure, ...evidence })\n if (exitSignal)\n return finish({\n succeeded: false,\n reason: 'failed',\n diagnostic: err || `Check killed by ${exitSignal}`,\n ...evidence,\n })\n if (exitCode !== 0)\n return finish({\n succeeded: false,\n reason: 'failed',\n diagnostic: err || out || `Check exited ${exitCode}`,\n ...evidence,\n })\n return finish({ succeeded: true, value: { stdout: out, stderr: err } })\n}\n\nconst executeFile = promisify(execFile)\n\n/** GNU tools traverse relative to open directories, including trees deeper than PATH_MAX.\n * Recursive chmod ignores encountered symlinks; rm never follows their targets. */\nasync function removeScratch(path: string): Promise<void> {\n const options = { env: {}, timeout: 10_000, maxBuffer: 16_384 }\n let permissionError: unknown\n try {\n await executeFile(\n '/bin/chmod',\n ['--recursive', '--preserve-root', 'u+rwX', '--', path],\n options,\n )\n } catch (error) {\n permissionError = error\n }\n try {\n await executeFile(\n '/bin/rm',\n ['--recursive', '--force', '--one-file-system', '--', path],\n options,\n )\n } catch (error) {\n throw new Error(\n [permissionError, error]\n .filter((value) => value !== undefined)\n .map(String)\n .join('; '),\n )\n }\n}\n","import { ValidationError } from '../../errors'\nimport type { RunGraphOptions } from './graph'\n\n/** Graph nodes expose JSON outputs through Runtime's resumable execution transports. */\nexport function graphExecutionOptions(options: RunGraphOptions): RunGraphOptions {\n if (options.makeLeafAgent) return options\n const backend = options.backend\n if (backend)\n return backend.backend === 'bridge' || backend.backend === 'provider'\n ? { ...options, backend: { ...backend, outputFormat: 'json' } }\n : options\n const bridgeUrl = process.env.CLI_BRIDGE_URL\n const bridgeBearer = process.env.BRIDGE_BEARER ?? process.env.CLI_BRIDGE_BEARER\n if (!bridgeUrl || !bridgeBearer)\n throw new ValidationError(\n 'runGraph: start CLI Bridge and supply backend: { backend: \"bridge\", bridgeUrl, bridgeBearer, cwd }, or configure CLI_BRIDGE_URL and BRIDGE_BEARER',\n )\n return {\n ...options,\n backend: {\n backend: 'bridge',\n bridgeUrl,\n bridgeBearer,\n cwd: process.cwd(),\n outputFormat: 'json',\n },\n }\n}\n","import {\n agentCandidateArtifactRefSchema,\n agentCandidateWorkspaceManifestMaterialSchema,\n canonicalCandidateDigest,\n sha256DigestSchema,\n} from '@tangle-network/agent-interface'\nimport { type ZodType, z } from 'zod'\nimport { isolatedCheckCpuAncestorLimit } from './isolated-check-cpu'\nimport type { IsolatedCheckBoxEvidence, IsolatedCheckResult } from './isolated-checker'\nimport {\n type IsolatedCheckOutputEvidence,\n validateIsolatedCheckOutputs,\n} from './isolated-checker-outputs'\n\nexport const isolatedCheckOutputEvidenceSchema: ZodType<IsolatedCheckOutputEvidence> = z\n .object({\n executionId: z\n .string()\n .max(200)\n .refine((value) => value.trim() !== '' && !/\\p{Cc}/u.test(value)),\n inputDigest: sha256DigestSchema,\n status: z.enum(['retained', 'incomplete']),\n files: z\n .array(z.object({ path: z.string(), artifact: agentCandidateArtifactRefSchema }).strict())\n .max(16),\n missing: z\n .array(\n z\n .object({\n path: z.string(),\n reason: z.enum([\n 'missing',\n 'unsafe-path',\n 'size-limit',\n 'capture-failed',\n 'store-failed',\n 'timeout',\n ]),\n })\n .strict(),\n )\n .max(16),\n source: z\n .discriminatedUnion('kind', [\n z.object({ kind: z.literal('local'), path: z.string().min(1) }).strict(),\n z\n .object({\n kind: z.literal('sandbox'),\n sandboxId: z.string().min(1),\n state: z.literal('stopped'),\n })\n .strict(),\n ])\n .optional(),\n })\n .strict()\n .superRefine((value, context) => {\n try {\n validateIsolatedCheckOutputs({\n paths: [...value.files, ...value.missing].map((file) => file.path),\n maxFileBytes: 64 * 1024 * 1024,\n maxTotalBytes: 64 * 1024 * 1024,\n })\n } catch {\n context.addIssue({ code: 'custom', message: 'Check output evidence has invalid paths' })\n }\n if (\n (value.status === 'retained') !== (value.missing.length === 0) ||\n (value.status === 'retained' && value.source !== undefined) ||\n value.files.reduce((bytes, file) => bytes + file.artifact.byteLength, 0) > 64 * 1024 * 1024\n )\n context.addIssue({ code: 'custom', message: 'Check output evidence is inconsistent' })\n })\n\n/** Decode the existing execution contract without widening or reinterpreting its evidence. */\nexport const isolatedCheckBoxEvidenceSchema: ZodType<IsolatedCheckBoxEvidence> = z\n .object({\n sandboxId: z.string().min(1),\n account: z.string().min(1),\n memoryMB: z.number().finite().positive().optional(),\n input: agentCandidateWorkspaceManifestMaterialSchema,\n inputDigest: sha256DigestSchema,\n })\n .strict()\n .superRefine((value, context) => {\n if (canonicalCandidateDigest(value.input) !== value.inputDigest)\n context.addIssue({\n code: 'custom',\n message: 'Check input digest does not match its manifest',\n })\n })\n\nconst cpuCounterSchema = z\n .object({\n usageUsec: z.number().int().nonnegative(),\n userUsec: z.number().int().nonnegative(),\n systemUsec: z.number().int().nonnegative(),\n resources: z\n .object({\n runnableWaitSomeUsec: z.number().int().nonnegative().nullable(),\n ancestorsComplete: z.boolean(),\n ancestors: z\n .array(\n z\n .object({\n cgroupPath: z.string().min(1),\n inode: z.number().int().positive().nullable(),\n cpuMax: z.string().nullable(),\n throttledUsec: z.number().int().nonnegative().nullable(),\n })\n .strict(),\n )\n .max(isolatedCheckCpuAncestorLimit),\n })\n .strict()\n .optional(),\n })\n .strict()\nconst cpuIdentityShape = {\n source: z.literal('cgroup-v2'),\n boundary: z.literal('after-membership-through-tree-exit'),\n sessionId: z.string().uuid(),\n cgroupPath: z.string().min(1),\n inode: z.number().int().positive(),\n}\n\nconst isolatedCheckCommandEvidenceSchema = z\n .object({\n wallMs: z.number().finite().nonnegative(),\n inputDigest: sha256DigestSchema.optional(),\n stdoutBase64: z.base64(),\n stderrBase64: z.base64(),\n outputComplete: z.boolean(),\n cpu: z\n .discriminatedUnion('available', [\n z\n .object({\n ...cpuIdentityShape,\n available: z.literal(true),\n before: cpuCounterSchema,\n after: cpuCounterSchema,\n })\n .strict(),\n z\n .object({ ...cpuIdentityShape, available: z.literal(false), diagnostic: z.string() })\n .strict(),\n ])\n .optional(),\n })\n .strict()\n\n/** Execution evidence, not a verdict about task correctness or permission to execute again. */\nexport const isolatedCheckResultSchema: ZodType<IsolatedCheckResult> = z.discriminatedUnion(\n 'succeeded',\n [\n z\n .object({\n succeeded: z.literal(true),\n value: z.object({ stdout: z.string(), stderr: z.string() }).strict(),\n box: isolatedCheckBoxEvidenceSchema.optional(),\n outputs: isolatedCheckOutputEvidenceSchema.optional(),\n command: isolatedCheckCommandEvidenceSchema.optional(),\n })\n .strict(),\n z\n .object({\n succeeded: z.literal(false),\n reason: z.enum([\n 'refused',\n 'failed',\n 'timeout',\n 'cancelled',\n 'output-limit',\n 'input-limit',\n 'cleanup-failed',\n ]),\n diagnostic: z.string(),\n stdout: z.string().optional(),\n stderr: z.string().optional(),\n exitCode: z.number().int().nullable().optional(),\n cleanupDiagnostic: z.string().optional(),\n box: isolatedCheckBoxEvidenceSchema.optional(),\n outputs: isolatedCheckOutputEvidenceSchema.optional(),\n command: isolatedCheckCommandEvidenceSchema.optional(),\n })\n .strict(),\n ],\n)\n","import { mkdirSync, realpathSync } from 'node:fs'\nimport { cp, lstat, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { isAbsolute, join, relative } from 'node:path'\nimport { canonicalCandidateDigest } from '@tangle-network/agent-interface'\nimport type { SandboxResources } from '@tangle-network/sandbox'\nimport { scanMaterializedWorkspaceManifest } from '../../candidate-execution/artifacts'\nimport { canonicalCandidateBytes } from '../../candidate-execution/digest'\nimport { contentAddress } from '../../durable/content-address'\nimport {\n appendCommittedJsonLine,\n readCommittedJsonLines,\n withJsonlFileLock,\n} from '../../durable/jsonl-file'\nimport { ValidationError } from '../../errors'\nimport type { MakeWorkerAgent } from '../../mcp/tools/coordination-contracts'\nimport { defaultRunCommand, runSettledCommand } from '../../mcp/worktree-harness'\nimport type { DeclaredCheckPlacement } from '../declared-check'\nimport { isolatedCheckOutputEvidenceSchema } from '../isolated-check-result'\nimport { type IsolatedCheckBox, runIsolatedCheck } from '../isolated-checker'\nimport {\n type IsolatedCheckOutputDeclaration,\n type IsolatedCheckOutputEvidence,\n type IsolatedCheckOutputOptions,\n localCheckOutputReader,\n prepareIsolatedCheckOutputs,\n retainIsolatedCheckOutputs,\n} from '../isolated-checker-outputs'\nimport type { CompletionCheckContext } from './completion-gate'\nimport { runtimeCheckFactory } from './flow-brain'\nimport type { AgentGraph, RunGraphOptions } from './graph'\nimport { retainedExecutorContext } from './retained-executor'\nimport type { Agent, AgentSpec, ExecutorFactory, ExecutorResult } from './types'\n\n/** An environment-owned check command, run outside the agent's conversation. */\nexport interface GraphCommandCheck {\n readonly command: string\n readonly timeoutMs?: number\n}\n\n/** A graph node that runs a command instead of an agent: no model, no seat. Locally it runs in the\n * run's working directory; with `RunGraphOptions.checkPlacement` it runs in a fresh Sandbox box\n * built from `environment`, through the box runner a declared check uses. */\nexport interface GraphCheckNode {\n readonly command: string\n /** Default 15 minutes. */\n readonly timeoutMs?: number\n /** The box image under `checkPlacement`; required there, unused locally. */\n readonly environment?: string\n /** Domains a box may reach. Absent or empty: egress is blocked. Unused locally. */\n readonly egress?: readonly string[]\n /** The box's Sandbox runtime under `checkPlacement`. Absent: the Sandbox default. */\n readonly runtime?: IsolatedCheckBox['runtime']\n /** Environment variable names the command needs; a missing one fails the node. In a box they\n * resolve only from the placement's `env`, the run owner's secrets. */\n readonly secrets?: readonly string[]\n /** The box's size under `checkPlacement`. */\n readonly resources?: SandboxResources\n /** Explicit tree-relative files to retain before cleanup, on success or failure. */\n readonly outputs?: IsolatedCheckOutputDeclaration\n}\n\n/** Where check nodes run in boxes: the run owner's own account. A check node is a step of the\n * graph, not a judge, so `builderAccounts` is optional and never refuses the owner's account. */\nexport interface GraphCheckPlacement\n extends Omit<DeclaredCheckPlacement, 'builderAccounts' | 'env'> {\n readonly builderAccounts?: DeclaredCheckPlacement['builderAccounts']\n /** The owner's secrets, or a resolver called before each box run so short-lived tokens stay\n * fresh. Absent: no secrets. */\n readonly env?:\n | Readonly<Record<string, string | undefined>>\n | ((request: {\n readonly node: string\n readonly secrets: readonly string[]\n readonly signal: AbortSignal\n }) => Promise<Readonly<Record<string, string | undefined>>>)\n}\n\n/** A check node's settled output. `json` is the last stdout line when it parses as an object. */\nexport interface GraphCheckOutput {\n readonly pass: boolean\n readonly exitCode: number | null\n /** The last 64 KiB of stdout followed by stderr. */\n readonly output: string\n readonly json?: Record<string, unknown>\n /** Verified artifact references; private recovery coordinates never reach downstream nodes. */\n readonly outputs?: Omit<IsolatedCheckOutputEvidence, 'source'>\n}\n\nexport interface GraphFromStoredOptions {\n readonly trigger?: Readonly<Record<string, unknown>>\n readonly checks?: Readonly<Record<string, AgentGraph['deliverable']['check'] | GraphCommandCheck>>\n}\n\ninterface CommandCheckReceipt {\n readonly version: 1\n readonly key: string\n readonly binding: string\n readonly checkDigest: string\n readonly nodeName: string\n readonly nodeId: string\n readonly attemptId: string\n readonly outputDigest: string\n readonly exitCode: number | null\n readonly output: string\n readonly outputTruncated: boolean\n readonly nativeValid: boolean\n readonly valid: boolean\n /** Check nodes only: the parsed last stdout line. */\n readonly json?: Record<string, unknown>\n readonly outputs?: IsolatedCheckOutputEvidence\n}\n\n/** Driver-owned journal identity. Worker output never supplies any part of this authority. */\nfunction receiptKey(receipt: Omit<CommandCheckReceipt, 'key'>): string {\n return contentAddress({\n binding: receipt.binding,\n checkDigest: receipt.checkDigest,\n nodeName: receipt.nodeName,\n nodeId: receipt.nodeId,\n attemptId: receipt.attemptId,\n outputDigest: receipt.outputDigest,\n })\n}\n\nfunction isReceipt(value: unknown): value is CommandCheckReceipt {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false\n const row = value as Record<string, unknown>\n if (\n row.version !== 1 ||\n ![\n 'key',\n 'binding',\n 'checkDigest',\n 'nodeName',\n 'nodeId',\n 'attemptId',\n 'outputDigest',\n 'output',\n ].every((key) => typeof row[key] === 'string') ||\n !row.nodeName ||\n !row.nodeId ||\n !row.attemptId ||\n !(row.exitCode === null || Number.isSafeInteger(row.exitCode)) ||\n typeof row.outputTruncated !== 'boolean' ||\n typeof row.nativeValid !== 'boolean' ||\n typeof row.valid !== 'boolean'\n )\n return false\n if (\n row.outputs !== undefined &&\n !isolatedCheckOutputEvidenceSchema.safeParse(row.outputs).success\n )\n return false\n const receipt = value as CommandCheckReceipt\n return (\n receipt.key === receiptKey(receipt) &&\n receipt.valid ===\n (receipt.exitCode === 0 && receipt.nativeValid && receipt.outputs?.status !== 'incomplete')\n )\n}\n\nasync function appendReceipt(\n file: string,\n workspace: string | undefined,\n receipt: Omit<CommandCheckReceipt, 'key'>,\n): Promise<void> {\n await withJsonlFileLock(file, async (canonicalPath) => {\n if (workspace !== undefined && within(workspace, canonicalPath))\n throw new ValidationError(\n 'runGraph: command receipt journal resolves inside worker workspace',\n )\n await appendCommittedJsonLine(canonicalPath, { ...receipt, key: receiptKey(receipt) })\n })\n}\n\nfunction within(directory: string, path: string): boolean {\n const offset = relative(directory, path)\n return offset === '' || (!isAbsolute(offset) && offset !== '..' && !offset.startsWith('../'))\n}\n\n/** The run's working directory (a loopback Bridge cwd or local CLI workspace) and its driver-owned\n * run directory, which must lie outside it. */\nfunction localCheckDirectories(options: RunGraphOptions): { cwd: string; runDir: string } {\n const cwd = backendWorkspace(options)\n if (!cwd)\n throw new ValidationError(\n 'runGraph: command checks require a loopback Bridge or local CLI workspace; provider node binding is unsupported',\n )\n return { cwd, runDir: driverRunDir(options, cwd) }\n}\n\nfunction backendWorkspace(options: RunGraphOptions): string | undefined {\n const backend = options.backend\n if (!backend) return undefined\n const workspace =\n backend.backend === 'bridge'\n ? backend.cwd\n : backend.backend === 'cli-in-place'\n ? backend.workspacePath\n : undefined\n return !workspace ||\n (backend.backend === 'bridge' &&\n !['localhost', '127.0.0.1', '[::1]'].includes(new URL(backend.bridgeUrl).hostname))\n ? undefined\n : realpathSync(workspace)\n}\n\nfunction driverRunDir(options: RunGraphOptions, workspace: string | undefined): string {\n if (!options.runDir)\n throw new ValidationError(\n 'runGraph: command checks require a driver-owned runDir outside the workspace',\n )\n mkdirSync(options.runDir, { recursive: true })\n const runDir = realpathSync(options.runDir)\n if (workspace !== undefined && within(workspace, runDir))\n throw new ValidationError('runGraph: command check runDir must be outside the worker workspace')\n return runDir\n}\n\n/** Lower a named check onto the local workspace, with evidence in the driver's durable state.\n * The run directory has the same trust boundary as RunContext journals: keep it outside the\n * worker workspace and do not mount it into the worker. A remote Bridge cannot run a host check.\n * Provider validators are refused because their context does not identify the admitted node.\n */\nexport function bindGraphCommand(\n graph: AgentGraph,\n options: RunGraphOptions,\n): { graph: AgentGraph; options: RunGraphOptions } {\n const { command: definition, ...deliverable } = graph.deliverable\n if (!definition) return { graph, options }\n const { command, timeoutMs = 60_000 } = definition\n if (!command.trim() || !Number.isSafeInteger(timeoutMs) || timeoutMs <= 0)\n throw new ValidationError(\n 'graphFromStored: command check needs a command and positive timeoutMs',\n )\n if (options.makeLeafAgent || graph.nodes.some((node) => node.check))\n throw new ValidationError('runGraph: command checks need a backend and no check nodes')\n const { cwd, runDir } = localCheckDirectories(options)\n const file = join(runDir, 'command-checks.jsonl')\n const checkDigest = contentAddress({ command, timeoutMs, cwd })\n const binding = contentAddress({\n graph: { ...graph, deliverable: { ...deliverable, check: undefined } },\n runId: options.runId ?? options.runContext?.runId,\n checkDigest,\n })\n const nodeNames = new Set(graph.nodes.map((node) => node.id))\n\n // The map is supplied by Runtime's flow finalizer. It contains terminal graph node IDs and\n // outputs, never receipt metadata. Every match must come from this run's driver journal.\n const checkFinal = async (out: unknown): Promise<boolean> => {\n if (!out || typeof out !== 'object' || Array.isArray(out)) return false\n const entries = Object.entries(out)\n if (entries.length === 0 || entries.some(([name]) => !nodeNames.has(name))) return false\n return withJsonlFileLock(file, async (canonicalPath) => {\n if (within(cwd, canonicalPath)) return false\n const latest = new Map<string, CommandCheckReceipt>()\n for await (const raw of readCommittedJsonLines<unknown>(canonicalPath, {\n allowMissing: true,\n })) {\n if (!isReceipt(raw)) return false\n if (raw.binding !== binding || raw.checkDigest !== checkDigest) continue\n latest.set(contentAddress([raw.nodeName, raw.outputDigest]), raw)\n }\n return entries.every(\n ([name, output]) =>\n latest.get(contentAddress([name, contentAddress(output)]))?.valid === true,\n )\n })\n }\n\n const checkLeaf = async (out: unknown, context: CompletionCheckContext): Promise<boolean> => {\n const node = context.node\n const nodeName = context.profile.name\n if (!node || !node.nodeId || !node.attemptId || !nodeName || !nodeNames.has(nodeName))\n return false\n // Always execute for a fresh leaf. A prior success, even for identical output, never skips\n // this check. gateFactoryOnDeliverable deduplicates only one invocation's exact artifact.\n const outputDigest = contentAddress(out)\n let result: { exitCode: number | null; output: string }\n try {\n result = await defaultRunCommand({ command, cwd, timeoutMs, signal: context.signal })\n } catch (error) {\n // An unavailable check invalidates an earlier identical output too; it cannot inherit\n // a prior success just because the current command did not reach a normal exit.\n result = { exitCode: null, output: error instanceof Error ? error.message : String(error) }\n }\n const bytes = Buffer.from(result.output)\n const limit = 64 * 1024\n const receipt: Omit<CommandCheckReceipt, 'key'> = {\n version: 1,\n binding,\n checkDigest,\n nodeName,\n nodeId: node.nodeId,\n attemptId: node.attemptId,\n outputDigest,\n exitCode: result.exitCode,\n output: bytes.subarray(0, limit).toString('utf8'),\n outputTruncated: bytes.length > limit,\n nativeValid: context.originalVerdict?.valid !== false,\n valid: result.exitCode === 0 && context.originalVerdict?.valid !== false,\n }\n await appendReceipt(file, cwd, receipt)\n return receipt.valid\n }\n return {\n graph: {\n ...graph,\n deliverable: {\n ...deliverable,\n check: (out, context) =>\n context === undefined ? checkFinal(out) : checkLeaf(out, context),\n },\n },\n options,\n }\n}\n\n/** The leaves of a flow's check nodes, for `supervise()`'s leaf path. */\nexport interface GraphCheckNodes {\n readonly names: ReadonlyArray<string>\n readonly leaf: MakeWorkerAgent\n}\n\nconst CHECK_OUTPUT_LIMIT = 64 * 1024\nconst CHECK_TIMEOUT_MS = 15 * 60_000\nconst safeNodeFile = /^(?!\\.\\.?$)[A-Za-z0-9._-]+$/\n\nfunction tail(text: string): { output: string; truncated: boolean } {\n const bytes = Buffer.from(text)\n return bytes.length <= CHECK_OUTPUT_LIMIT\n ? { output: text, truncated: false }\n : {\n output: bytes.subarray(bytes.length - CHECK_OUTPUT_LIMIT).toString('utf8'),\n truncated: true,\n }\n}\n\nfunction lastJsonObject(stdout: string): Record<string, unknown> | undefined {\n const line = stdout.trimEnd().split('\\n').at(-1)?.trim()\n if (!line?.startsWith('{')) return undefined\n try {\n const value: unknown = JSON.parse(line)\n return value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n } catch {\n return undefined\n }\n}\n\n/** Each settled result a routes spawn carries: its source and its evidence, by node id. */\nfunction evidenceOf(task: unknown): Array<[string, unknown]> {\n if (!task || typeof task !== 'object') return []\n const { from, evidence } = task as { from?: unknown; evidence?: unknown }\n const entries = new Map<string, unknown>()\n if (from && typeof from === 'object' && 'node' in from && 'result' in from)\n entries.set(String((from as { node: unknown }).node), (from as { result: unknown }).result)\n if (evidence && typeof evidence === 'object' && !Array.isArray(evidence))\n for (const [id, result] of Object.entries(evidence)) entries.set(id, result)\n return [...entries]\n}\n\nasync function writeEvidence(\n directory: string,\n task: unknown,\n trigger: RunGraphOptions['trigger'],\n): Promise<void> {\n await mkdir(directory, { recursive: true })\n for (const [id, result] of evidenceOf(task)) {\n if (!safeNodeFile.test(id)) throw new ValidationError(`runGraph: evidence node id ${id}`)\n await writeFile(join(directory, `${id}.json`), `${JSON.stringify(result)}\\n`)\n }\n await mkdir(join(directory, '_input'), { recursive: true })\n await writeFile(\n join(directory, '_input', 'task.json'),\n canonicalCandidateBytes({\n task,\n ...(trigger === undefined ? {} : { trigger }),\n }),\n )\n}\n\nasync function readSecrets(\n names: readonly string[] | undefined,\n environment: Readonly<Record<string, string | undefined>>,\n node: string,\n): Promise<Record<string, string>> {\n const secrets: Record<string, string> = {}\n for (const name of names ?? []) {\n const value = environment[name]\n if (!value) throw new ValidationError(`runGraph: check node ${node} needs secret ${name}`)\n secrets[name] = value\n }\n return secrets\n}\n\n/** Run one check node's command locally, in the run's working directory. */\nasync function runLocalCheck(\n check: GraphCheckNode,\n cwd: string,\n evidence: string,\n signal: AbortSignal,\n secrets: Record<string, string>,\n retention?: IsolatedCheckOutputOptions,\n): Promise<CheckExecution> {\n const prior = new Map(\n await Promise.all(\n (retention?.paths ?? []).map(\n async (path) =>\n [\n path,\n await lstat(join(cwd, path), { bigint: true }).catch((error: NodeJS.ErrnoException) => {\n if (error.code !== 'ENOENT') throw error\n return undefined\n }),\n ] as const,\n ),\n ),\n )\n const inputDigest = retention\n ? canonicalCandidateDigest(await scanMaterializedWorkspaceManifest(evidence))\n : undefined\n const timeoutMs = check.timeoutMs ?? CHECK_TIMEOUT_MS\n const result = await runSettledCommand({\n command: '/bin/sh',\n args: ['-c', check.command],\n cwd,\n timeoutMs,\n signal,\n env: {\n ...secrets,\n GRAPH_EVIDENCE: evidence,\n GRAPH_INPUT: join(evidence, '_input', 'task.json'),\n },\n })\n const timedOut = result.timedOut ? `\\n[check timed out after ${timeoutMs} ms]` : ''\n const readOutput = localCheckOutputReader(cwd)\n const captured = retention\n ? await retainIsolatedCheckOutputs(retention, inputDigest!, async (path, maxBytes, signal) => {\n const before = prior.get(path)\n if (before) {\n const after = await lstat(join(cwd, path), { bigint: true })\n if (\n (['dev', 'ino', 'size', 'mtimeNs', 'ctimeNs'] as const).every(\n (key) => before[key] === after[key],\n )\n )\n throw new Error('Declared local check output was not changed by this command')\n }\n return readOutput(path, maxBytes, signal)\n })\n : undefined\n const outputs =\n captured?.status === 'incomplete'\n ? { ...captured, source: { kind: 'local' as const, path: cwd } }\n : captured\n return {\n exitCode: result.timedOut ? null : result.exitCode,\n stdout: result.stdout,\n output: result.stdout + result.stderr + timedOut,\n ...(outputs && { outputs }),\n }\n}\n\ninterface CheckExecution {\n exitCode: number | null\n stdout: string\n output: string\n nativeValid?: boolean\n outputs?: IsolatedCheckOutputEvidence\n}\n\n/** Run one check node's command in a fresh box on the check account, as a declared check does. */\nasync function runBoxCheck(\n check: GraphCheckNode,\n node: string,\n placement: GraphCheckPlacement,\n evidence: string,\n signal: AbortSignal,\n secrets: Record<string, string>,\n outputs?: IsolatedCheckOutputOptions,\n): Promise<CheckExecution> {\n const workspaceRoot = await mkdtemp(join(evidence, '..', 'box-'))\n try {\n const tree = join(workspaceRoot, 'tree')\n await mkdir(tree)\n await cp(evidence, join(tree, '_evidence'), { recursive: true })\n const result = await runIsolatedCheck({\n workspaceRoot,\n tree,\n command: [\n '/bin/sh',\n '-c',\n `GRAPH_EVIDENCE=\"$PWD/_evidence\"; GRAPH_INPUT=\"$GRAPH_EVIDENCE/_input/task.json\"; export GRAPH_EVIDENCE GRAPH_INPUT; ${check.command}`,\n ],\n timeoutMs: check.timeoutMs ?? CHECK_TIMEOUT_MS,\n maxOutputBytes: 16 * CHECK_OUTPUT_LIMIT,\n env: secrets,\n signal,\n ...(outputs && { outputs }),\n box: {\n client: placement.client,\n // Not consulted for an owner step; carried only because judges require it.\n builderAccounts: placement.builderAccounts ?? ['run-owner'],\n ownerStep: true,\n environment: check.environment as string,\n ...(check.egress === undefined ? {} : { egress: check.egress }),\n ...(check.runtime === undefined ? {} : { runtime: check.runtime }),\n ...(check.resources === undefined ? {} : { resources: check.resources }),\n },\n })\n if (result.succeeded)\n return {\n exitCode: 0,\n stdout: result.value.stdout,\n output: result.value.stdout + result.value.stderr,\n ...(result.outputs && { outputs: result.outputs }),\n }\n const stdout = result.stdout ?? ''\n const output = stdout + (result.stderr ?? '')\n if (result.outputs || result.reason === 'failed' || result.reason === 'timeout')\n return {\n exitCode: result.exitCode ?? null,\n stdout,\n output: `${output}\\n[check ${result.reason}: ${result.diagnostic}]`,\n nativeValid: result.reason === 'failed' || result.reason === 'timeout',\n ...(result.outputs && { outputs: result.outputs }),\n }\n throw new Error(\n redact(`runGraph: check node ${node} box ${result.reason}: ${result.diagnostic}`, secrets),\n )\n } finally {\n await rm(workspaceRoot, { recursive: true, force: true })\n }\n}\n\n/** Every resolved secret value becomes `[redacted:NAME]` before output leaves the check. */\nfunction redact(text: string, secrets: Record<string, string>): string {\n return redactBytes(Buffer.from(text), secrets).toString('utf8')\n}\n\nfunction redactBytes(\n bytes: Uint8Array,\n secrets: Record<string, string>,\n maxBytes = Number.MAX_SAFE_INTEGER,\n): Buffer {\n let out = Buffer.from(bytes)\n for (const [name, value] of Object.entries(secrets).sort(([, a], [, b]) => b.length - a.length)) {\n const needle = Buffer.from(value)\n const replacement = Buffer.from(`[redacted:${name}]`)\n let length = out.length\n for (let at = out.indexOf(needle); at !== -1; at = out.indexOf(needle, at + needle.length)) {\n length += replacement.length - needle.length\n if (length > maxBytes) throw new Error('Redacted check output exceeds its byte limit')\n }\n if (length === out.length && !out.includes(needle)) continue\n const redacted = Buffer.allocUnsafe(length)\n let start = 0\n let offset = 0\n for (let at = out.indexOf(needle); at !== -1; at = out.indexOf(needle, start)) {\n offset += out.copy(redacted, offset, start, at)\n offset += replacement.copy(redacted, offset)\n start = at + needle.length\n }\n out.copy(redacted, offset, start)\n out = redacted\n }\n return out\n}\n\nfunction checkOutput(receipt: Omit<CommandCheckReceipt, 'key'>): GraphCheckOutput {\n return {\n pass: receipt.valid,\n exitCode: receipt.exitCode,\n output: receipt.output,\n ...(receipt.json === undefined ? {} : { json: receipt.json }),\n ...(receipt.outputs === undefined\n ? {}\n : { outputs: (({ source: _source, ...outputs }) => outputs)(receipt.outputs) }),\n }\n}\n\n/** The receipt a run context's journal holds for this binding, as executor evidence. */\nasync function replayContextReceipt(\n context: NonNullable<RunGraphOptions['runContext']>,\n runId: string,\n binding: string,\n checkDigest: string,\n): Promise<GraphCheckOutput | undefined> {\n for (const event of (await context.journal.loadTree(runId)) ?? []) {\n if (event.kind !== 'execution-evidence') continue\n const row = ((await context.blobs.get(event.outRef)) as { graphCheckReceipt?: unknown })\n ?.graphCheckReceipt\n if (isReceipt(row) && row.binding === binding && row.checkDigest === checkDigest)\n return checkOutput(row)\n }\n return undefined\n}\n\n/** A node attempt's journaled settle, so a resumed run never runs a settled command again. */\nasync function replayCheckReceipt(\n file: string,\n binding: string,\n checkDigest: string,\n): Promise<GraphCheckOutput | undefined> {\n return withJsonlFileLock(file, async (canonicalPath) => {\n for await (const row of readCommittedJsonLines<unknown>(canonicalPath, {\n allowMissing: true,\n })) {\n if (isReceipt(row) && row.binding === binding && row.checkDigest === checkDigest)\n return checkOutput(row)\n }\n return undefined\n })\n}\n\n/**\n * Bind a flow graph's check nodes. Each spawn of a check node runs its command once and settles\n * `{ pass, exitCode, output, json }` as a usable result, so routes branch on `/pass`. The receipt\n * rides the run's `command-checks.jsonl` beside the command deliverable's, and a node attempt that\n * already holds a receipt replays it instead of running the command again.\n */\nexport function bindGraphCheckNodes(\n graph: AgentGraph,\n options: RunGraphOptions,\n): GraphCheckNodes | undefined {\n const checks = new Map(\n graph.nodes.flatMap((node) => (node.check === undefined ? [] : [[node.id, node.check]])),\n )\n if (checks.size === 0) return undefined\n if (graph.entry === undefined)\n throw new ValidationError('runGraph: check nodes run only in a flow graph (one with entry)')\n for (const node of graph.nodes)\n if (!safeNodeFile.test(node.id))\n throw new ValidationError(\n `runGraph: node id ${JSON.stringify(node.id)} cannot name an evidence file; use letters, digits, '.', '_' and '-'`,\n )\n for (const edge of graph.edges)\n if (edge.kind === 'maps' && [edge.to, edge.join].some((id) => id && checks.has(id)))\n throw new ValidationError('runGraph: a check node runs from entry or routes, not a maps edge')\n const placement = options.checkPlacement\n for (const [id, check] of checks) {\n const timeoutMs = check.timeoutMs ?? CHECK_TIMEOUT_MS\n if (!check.command.trim() || !Number.isSafeInteger(timeoutMs) || timeoutMs <= 0)\n throw new ValidationError(`runGraph: check node ${id} needs a command and positive timeoutMs`)\n if (placement && !check.environment?.trim())\n throw new ValidationError(`runGraph: check node ${id} needs environment for box placement`)\n if (check.outputs !== undefined) {\n if (!options.checkArtifacts)\n throw new ValidationError(`runGraph: check node ${id} outputs require checkArtifacts`)\n prepareIsolatedCheckOutputs({\n ...check.outputs,\n executionId: 'graph-check-preflight',\n artifacts: options.checkArtifacts,\n })\n }\n }\n const local = placement === undefined ? localCheckDirectories(options) : undefined\n const workspace = local?.cwd ?? backendWorkspace(options)\n // A box placement with a run context and no runDir (a hosted SQL run) keeps its receipts in\n // that context's journal, so whichever worker resumes the run replays them.\n const context = local || options.runDir ? undefined : options.runContext\n const runDir = context ? undefined : (local?.runDir ?? driverRunDir(options, workspace))\n const file = runDir === undefined ? undefined : join(runDir, 'command-checks.jsonl')\n const runId = options.runId ?? options.runContext?.runId\n const leaf: MakeWorkerAgent = (profile, spawn) => {\n const id = profile.name as string\n const check = checks.get(id)\n if (check === undefined) throw new ValidationError(`runGraph: ${id} is not a check node`)\n const checkDigest = contentAddress({\n ...check,\n timeoutMs: check.timeoutMs ?? CHECK_TIMEOUT_MS,\n at: local?.cwd ?? 'box',\n })\n // The spawn's assignment is stable across a resume, so a settled traversal replays its receipt.\n const binding = contentAddress({\n runId,\n node: id,\n checkDigest,\n at: spawn?.assignmentId,\n ...(options.trigger === undefined ? {} : { trigger: options.trigger }),\n })\n const executorFactory: ExecutorFactory<unknown> = (_spec, context_) => {\n let artifact: ExecutorResult<unknown> | undefined\n const settle = (out: GraphCheckOutput, ms: number): ExecutorResult<unknown> => {\n artifact = {\n out,\n outRef: contentAddress(out),\n verdict: { valid: true, score: out.pass ? 1 : 0 },\n spent: {\n iterations: 1,\n tokens: { input: 0, output: 0 },\n tokensKnown: true,\n usd: 0,\n usdKnown: true,\n ms,\n },\n }\n return artifact\n }\n const execute = async (task: unknown, signal: AbortSignal) => {\n const node = context_.node\n if (!node?.nodeId || !node.attemptId || !spawn)\n throw new ValidationError(`runGraph: check node ${id} ran outside a supervised node`)\n const attempt = { binding, checkDigest, nodeId: node.nodeId, attemptId: node.attemptId }\n const prior = file\n ? await replayCheckReceipt(file, binding, checkDigest)\n : await replayContextReceipt(context!, runId!, binding, checkDigest)\n if (prior) return settle(prior, 0)\n const started = Date.now()\n const staged = runDir ? undefined : await mkdtemp(join(tmpdir(), 'graph-check-'))\n const evidence = join(\n runDir ?? (staged as string),\n 'graph-evidence',\n contentAddress(attempt).slice('sha256:'.length, 'sha256:'.length + 24),\n )\n const box = placement as GraphCheckPlacement\n const secrets = await readSecrets(\n local ? check.secrets?.filter((name) => process.env[name]) : check.secrets,\n local\n ? process.env\n : typeof box.env === 'function'\n ? await box.env({ node: id, secrets: check.secrets ?? [], signal })\n : (box.env ?? {}),\n id,\n )\n const retention = check.outputs && {\n ...check.outputs,\n executionId: binding,\n artifacts: options.checkArtifacts!,\n redact: (bytes: Uint8Array) => redactBytes(bytes, secrets, check.outputs!.maxFileBytes),\n }\n let ran: Awaited<ReturnType<typeof runLocalCheck>>\n try {\n await writeEvidence(evidence, task, options.trigger)\n ran = local\n ? await runLocalCheck(check, local.cwd, evidence, signal, secrets, retention)\n : await runBoxCheck(\n check,\n id,\n placement as GraphCheckPlacement,\n evidence,\n signal,\n secrets,\n retention,\n )\n } finally {\n if (staged) await rm(staged, { recursive: true, force: true })\n }\n const { output, truncated } = tail(redact(ran.output, secrets))\n const json = lastJsonObject(redact(ran.stdout, secrets))\n const receipt: Omit<CommandCheckReceipt, 'key'> = {\n version: 1,\n ...attempt,\n nodeName: id,\n outputDigest: contentAddress(task),\n exitCode: ran.exitCode,\n output,\n outputTruncated: truncated,\n nativeValid: ran.nativeValid !== false,\n valid:\n ran.exitCode === 0 && ran.nativeValid !== false && ran.outputs?.status !== 'incomplete',\n ...(json === undefined ? {} : { json }),\n ...(ran.outputs === undefined ? {} : { outputs: ran.outputs }),\n }\n // Without an evidence channel the settle itself is still journaled and replayed.\n if (file) await appendReceipt(file, workspace, receipt)\n else\n await retainedExecutorContext(context_)?.onEvidence?.({\n graphCheckReceipt: { ...receipt, key: receiptKey(receipt) },\n })\n return settle(checkOutput(receipt), Date.now() - started)\n }\n return {\n runtime: 'graph-check',\n execute,\n // A recovered check replays its receipt, or runs the idempotent command again.\n recover: execute,\n async teardown() {\n return { destroyed: true }\n },\n resultArtifact() {\n if (!artifact) throw new ValidationError(`runGraph: check node ${id} has not settled`)\n return artifact\n },\n }\n }\n const spec: AgentSpec = {\n profile,\n harness: null,\n executorFactory: runtimeCheckFactory(executorFactory),\n }\n return { name: id, act: async () => '', executorSpec: spec } as Agent<unknown, unknown> & {\n executorSpec: AgentSpec\n }\n }\n return { names: [...checks.keys()], leaf }\n}\n","/**\n * `runGraph` interprets a topology on `supervise()`. Nodes are canonical `AgentProfile`s, edges\n * carry versioned {@link PromptHandle} directives, and `deliverable` and one conserved `budget`\n * are mandatory. It does not schedule: `runAgentRounds` is not the substrate. A spawn's\n * `profile.name` is the node id, so a driver cannot add capabilities the node did not define.\n * Every delegates, analyzes, maps, or routes hop is an edge-ledger row (`delivered`, `stripped`,\n * `empty`, `unpropagated`, `failed`) on the result and in the journal. Edge text lives in the\n * prompt registry. A delegates edge at its traversal cap refuses. `continuity: 'resume'`\n * re-attaches to the node's latest settled session; ledger hops say `fresh`, `resume`, or `steer`.\n * A `maps` edge spawns one authorized item per selected array element and then the join, on the\n * same pool, with no model turn. With `entry` set, Runtime owns the root and fires `routes` on\n * settle (`graph-flow.ts`). An `analyzes` edge names a registry lens or a graph node, never a\n * delegates target, and an id in both places is refused.\n *\n * @experimental\n */\n\nimport { resolve } from 'node:path'\nimport { type AgentProfile, canonicalCandidateDigest } from '@tangle-network/agent-interface'\nimport type { AgentCandidateOutputArtifactPort } from '../../candidate-execution/types'\nimport { ConfigError, ValidationError } from '../../errors'\nimport type { AnalystRegistry } from '../../mcp/tools/coordination-analysts'\nimport type { MakeWorkerAgent } from '../../mcp/tools/coordination-contracts'\nimport type { MapItemFailurePolicy } from '../../mcp/tools/coordination-map-contracts'\nimport type { ContinuityMode } from '../../mcp/tools/coordination-messages'\nimport type {\n GateDecision,\n GateDecisionRecord,\n GateRequest,\n RouteGate,\n RouteWhen,\n} from '../../mcp/tools/coordination-route-contracts'\nimport { composeRuntimeHooks, type RuntimeHooks } from '../../runtime-hooks'\nimport { harnessRunsAgent } from '../harness-role'\nimport type { ToolLoopChat } from '../tool-loop'\nimport type { DeliverableSpec } from './completion-gate'\nimport {\n type PortableContinuationPolicy,\n portableContinuationPolicySchema,\n} from './continuation-data'\nimport { runtimeFlowBrain } from './flow-brain'\nimport { graphExecutionOptions } from './graph-backend'\nimport {\n createFlowRun,\n flowRootProfile,\n GraphRouteError,\n journaledGateDecider,\n routeFlowOf,\n validateFlowGraph,\n} from './graph-flow'\nimport { createGraphOverlay } from './graph-overlay'\nimport {\n graphRootProfile,\n type RootValidatedGraph,\n type ValidatedGraph,\n validateGraphTopology,\n} from './graph-topology'\nimport { kernelPromptRegistry, type PromptHandle, type PromptRegistry } from './prompt-registry'\nimport { createFileRunContext, createInMemoryRunContext, withRunContext } from './run-context'\nimport { detachedSnapshot } from './snapshot'\nimport {\n bindGraphCheckNodes,\n bindGraphCommand,\n type GraphCheckNode,\n type GraphCheckPlacement,\n type GraphCommandCheck,\n type GraphFromStoredOptions,\n} from './stored-graph-check'\nimport {\n profileGuidanceComposer,\n type SuperviseOptions,\n supervise,\n superviseWithTestBrain,\n} from './supervise'\nimport type { Budget, NodeId, ResultBlobStore, SpawnJournal, SupervisedResult } from './types'\n\nexport type { MapItemFailurePolicy } from '../../mcp/tools/coordination-map-contracts'\nexport type {\n GateDecision,\n GateRequest,\n JsonScalar,\n RouteGate as GraphGate,\n RouteMatch,\n RouteWhen,\n} from '../../mcp/tools/coordination-route-contracts'\nexport { GraphRouteError } from './graph-flow'\nexport { defaultEdgeTraversalCap } from './graph-topology'\n\n// ── The algebra ────────────────────────────────────────────────────────────────\n\n/** A graph node: an id and a canonical `AgentProfile`. The profile is the ONLY way a node is\n * described — its `prompt.systemPrompt` is the standing role (the 0.117 canonical resolution;\n * never a legacy top-level-only reduction), its tools/mcp/resources are its capabilities. */\nexport interface GraphNode {\n readonly id: NodeId\n readonly profile: AgentProfile\n /** A check node: Runtime runs this command instead of an agent (flow graphs only). Its profile is\n * `{ name: id }`; `graphFromStored` writes both. */\n readonly check?: GraphCheckNode\n}\n\nexport type GraphEdge =\n /** Work flows down. The delegation directive is DATA → versionable, sweepable, optimizable.\n * Each spawn of `to` by `from` — and each mid-run steer from `from` to a live `to` worker —\n * is one traversal. */\n | {\n readonly kind: 'delegates'\n readonly from: NodeId\n readonly to: NodeId\n readonly directive: PromptHandle\n /** Cyclic-graph backstop: traversals beyond this REFUSE (fail loud). Default\n * {@link defaultEdgeTraversalCap}. */\n readonly maxTraversals?: number\n /** Default continuity for this edge's SPAWN traversals. `'resume'` makes every spawn after\n * the node's first re-attach to its most recent SETTLED worker: a NEW live worker whose\n * spawn context carries `resume: { ofWorker, sequence }` for the executor seam, spending\n * from the same conserved pool — the node's first spawn is effectively `'fresh'`, and a\n * spawn while a prior worker is still live refuses loudly (steer is the live channel).\n * The driver's per-call `spawn_worker` `continuity` argument overrides either way. Omit =\n * `'fresh'` (today's behavior, byte-identical). Caps count resumes exactly like fresh\n * spawns. */\n readonly continuity?: ContinuityMode\n }\n /** Findings flow anywhere: an analyst over N nodes' settled traces, delivered to ONE node.\n * With a LENS analyst the directive wraps the findings for the recipient; with a NODE analyst\n * the directive is the analyst agent's task and the findings are its settle output. */\n | {\n readonly kind: 'analyzes'\n /** The analyst REFERENCE, in one of two forms: a lens id resolved against\n * `RunGraphOptions.analysts` (environment), or the id of a graph NODE with no delegates\n * edge pointing at it — then each matching settle spawns that node's pinned profile as a\n * tool-equipped analyst WORKER (same spawn machinery, conserved budget, trace join) whose\n * task is this edge's directive plus the settled worker's trace evidence and whose settle\n * output is the findings. An id that is both a node and a registry lens is refused. */\n readonly analyst: string\n readonly over: ReadonlyArray<NodeId>\n readonly to: NodeId\n readonly directive: PromptHandle\n /** Observability cap: traversals beyond this are LEDGERED as exhausted (`unpropagated`).\n * Only delegates caps refuse traversal — they are what close the spawn cycle. */\n readonly maxTraversals?: number\n }\n /**\n * Fan-out over a list that exists only at run time, then one join. When `from` settles `done`,\n * the array at `pointer` in its result is expanded: each element becomes the TASK of one item\n * run, at most `concurrency` at a time, and once every item settled the `join` node runs with\n * `{ map, source, items, results: [{ index, item, result }], failures: [{ index, item, outcome,\n * reason }] }`, results in item order. The runtime spawns the items and the join (`from`'s\n * driver spends no turn on them) through the same authorized spawn path a delegates spawn\n * takes: each item reserves its budget from the one conserved pool and is pinned to the edge's\n * profile, so an item's content can never choose what runs.\n *\n * An item is either the node `to` (its pinned profile plus this edge's directive) or the nested\n * `graph`, started per item exactly as `run_graph` starts a graph. Refusals are loud and\n * ledgered, and the driver is woken with them: a pointer that does not resolve to an array, more\n * elements than `maxItems`, or a `concurrency` the run's worker-slot bound can never honor.\n * `concurrency` otherwise THROTTLES (items wait for a free place); it never refuses an item.\n *\n * An edge rather than a node-level spec, because every kernel invariant a map must keep already\n * attaches to edge traversal: pinning admits only the edge's item and join nodes (the spawn\n * context carries a runtime-authored `map` marker), each item is admitted like a spawn and\n * reserves from the conserved pool, each item settles under its own deliverable check, and each\n * expansion, item and join is a ledger row with its journal twin. Topology stays static; only the\n * traversal count is dynamic, so validation and the one-node-one-profile rule are unchanged.\n */\n | {\n readonly kind: 'maps'\n /** The source node: a delegates target, or the join of another maps edge. Each of its `done`\n * settles expands the map once. */\n readonly from: NodeId\n /** RFC 6901 JSON pointer into `from`'s settled result (`''` is the whole result). */\n readonly pointer: string\n /** The item node, run once per element with the element as its task. Exactly one of `to`\n * and `graph`. Reachable only through this edge: never a delegates target. */\n readonly to?: NodeId\n /** A graph run per element as one subtask, through the `run_graph` path. */\n readonly graph?: GraphTopology\n /** Receives the ordered results once every item settled. Reachable only through this edge. */\n readonly join: NodeId\n /** The item directive, appended to the item node's instructions per traversal. */\n readonly directive: PromptHandle\n /** Lists longer than this are refused before any item runs. */\n readonly maxItems: number\n /** How many items run at once. */\n readonly concurrency: number\n readonly onItemFailure: MapItemFailurePolicy\n /** Each item's budget, merged over the per-worker default as `spawn_worker`'s `budget` is. */\n readonly itemBudget?: Partial<Budget>\n }\n /**\n * A route in a flow graph (one with `entry`): Runtime traverses it when `from` settles, so no\n * root decides the order, the branch, the repair loop or the stop. On each usable settle of\n * `from` its outgoing routes edges are tried in declaration order and the first whose `when`\n * holds fires; an edge without `when` is the default branch and comes last. A node target is\n * spawned with `{ from: { node, result }, evidence: { [id]: latest usable result } }` (a join's\n * target with `{ from: { nodes }, evidence }`, see below) and the directive appended to its pinned instructions; `{ stop }` ends the run with no winner and\n * `GraphResult.stopped`; `{ finish }` makes this settle part of the run's output.\n *\n * A fork lists two or more nodes in `to`: one traversal spawns each of them at once, each under\n * its own key `route:<edge id>#<traversal>:<node>`. A join lists two or more nodes in `from`: it\n * fires once every member has settled usably since it last fired, and the target's task is\n * `{ from: { nodes: <members in declared order> }, evidence }` with each member's latest result\n * in `evidence`, so it does not depend on which member settled last and a resumed run derives the\n * same task. A routes edge that spawns a node with a settled worker in this flow (a back edge)\n * names that node's latest settled worker as the spawn's `successorOf`. A join carries no `when`, and it is the only routes edge\n * leaving each of its members. A route into a node that still has a running worker throws\n * {@link GraphRouteError} with reason `target-live`: converging branches use a join.\n */\n | {\n readonly kind: 'routes'\n readonly from: NodeId | ReadonlyArray<NodeId>\n readonly to:\n | NodeId\n | ReadonlyArray<NodeId>\n | { readonly stop: string }\n | { readonly finish: string }\n readonly directive: PromptHandle\n /** Absent on the default edge and on every join. A match reads `from` unless it names a node\n * in `evidence`. */\n readonly when?: RouteWhen\n /** Nodes whose latest usable result rides the target's task. */\n readonly evidence?: ReadonlyArray<NodeId>\n /** Traversals beyond this are skipped (ledgered `unpropagated`) and matching continues with\n * the next edge. Default {@link defaultEdgeTraversalCap}. Every routes cycle, each subcycle\n * included, must cross an edge that sets it. */\n readonly maxTraversals?: number\n /** `'resume'` re-attaches each spawn of the target to its latest settled session. Omit =\n * `'fresh'`. */\n readonly continuity?: ContinuityMode\n }\n\n/** A topology without the run's own budget and deliverable: the form a `maps` edge runs per item,\n * as `run_graph` runs it. With `entry` it is a flow graph. Inside a maps item, the item value is\n * the task of every entry whose task is the placeholder `{ item: true }`; a down settle inside the item ends\n * that item only, and the maps edge's `onItemFailure` decides the join. */\nexport interface GraphTopology {\n readonly nodes: ReadonlyArray<GraphNode>\n readonly edges: ReadonlyArray<GraphEdge>\n readonly entry?: AgentGraph['entry']\n /** Refused here: a maps item's graph and a `run_graph` subtask have no `decideGate`. */\n readonly gates?: AgentGraph['gates']\n}\n\nexport interface AgentGraph {\n /** Preserve fully bound literal data when serializing a hydrated graph. */\n readonly triggerBindings?: readonly []\n readonly nodes: ReadonlyArray<GraphNode>\n readonly edges: ReadonlyArray<GraphEdge>\n /** Termination is mandatory, not optional: the independent completion oracle. */\n readonly deliverable: DeliverableSpec<unknown> & {\n readonly checkRef?: string\n readonly command?: GraphCommandCheck\n readonly when?: RouteWhen\n }\n /** One conserved pool across the whole graph — cycles without conservation never terminate. */\n readonly budget: Budget\n /** Setting it makes this a FLOW graph: Runtime spawns every entry at once, each with its task,\n * and traverses `routes` edges itself. No node is a root and no caller brain runs; the run's\n * output is `{ [node]: latest usable result }` over its terminal nodes and `finish` sources,\n * judged by `deliverable`. A stored route check (`checkRef: 'route'`) may also name a\n * non-terminal node: its condition reads that node's latest delivered output, while the output\n * stays terminal-only. */\n readonly entry?: ReadonlyArray<{ readonly node: NodeId; readonly task: unknown }>\n /** Flow-graph vertices that are not agents: a routes edge into one awaits\n * `RunGraphOptions.decideGate`, and one edge per choice leaves it, matching\n * `{ pointer: '/choice', equals: <choice> }`. A `finish` leaving a gate outputs\n * `{ [gate]: { choice, by } }`. */\n readonly gates?: ReadonlyArray<RouteGate>\n /** Where nodes run: `cwd` (default) is the run's working directory; `fresh` is a new empty\n * directory the run owns, which the host creates and passes as that working directory\n * (`graphWorkspace`). */\n readonly workspace?: 'cwd' | 'fresh'\n /** The authored root's continuation; a flow has no root manager. */\n readonly continuation?: PortableContinuationPolicy\n}\n\n// ── The edge ledger ────────────────────────────────────────────────────────────\n\n/** `failed` is a maps item or join that ran and settled without a usable result (down, or\n * rejected by its deliverable check); a traversal that never reached a worker is `unpropagated`. */\nexport type EdgeDeliveryOutcome = 'delivered' | 'stripped' | 'empty' | 'unpropagated' | 'failed'\n\n/** How one ledgered hop CONTINUED: a spawn traversal stamps its effective spawn mode\n * (`'fresh'` | `'resume'`), and every mid-run delivery into an already-live recipient — a\n * driver steer leg and every analyzes delivery (routed steer or driver-destined finding) —\n * stamps `'steer'`. Zero ambiguity: every row carries exactly one of the three. */\nexport type TraversalContinuity = ContinuityMode | 'steer'\n\n/** One recorded edge traversal — the in-memory row; the journal twin is the `edge` SpawnEvent. */\nexport interface EdgeTraversal {\n /** Stable edge id: `delegates:<from>-><to>`, `analyzes:<analyst>:<over…>-><to>`,\n * `maps:<from>-><to | graph>-><join>`, `routes:<from>#<ordinal>-><to | stop:<reason> |\n * finish:<reason>>`, or `routes:entry-><node>` for an entry. */\n readonly edge: string\n readonly kind: 'delegates' | 'analyzes' | 'maps' | 'routes'\n readonly from: string\n readonly to: string\n /** The resolved directive reference (`<surface>/v<n>`). */\n readonly directive: string\n /** 1-based per-edge ordinal. */\n readonly traversal: number\n readonly outcome: EdgeDeliveryOutcome\n /** How this hop continued — see {@link TraversalContinuity}. */\n readonly continuity: TraversalContinuity\n /** Bytes of directive + payload that actually crossed the edge. */\n readonly bytes: number\n readonly reason?: string\n /** The concrete worker node id, once known. A maps expansion names the source worker. */\n readonly workerId?: string\n /** Present on maps rows: the expansion of the source's list, one item by its index, or the\n * join. */\n readonly map?: { readonly phase: 'expand' | 'item' | 'join'; readonly index?: number }\n /** Present on a gate's decision row (`gate:<id>`, `traversal` = visit): who decided, and what. */\n readonly gate?: GateDecisionRecord\n}\n\n/** A delegates edge exhausted its traversal cap and the run produced no winner: the cap, not the\n * task, ended it. Carries the full evidence so failing loud loses nothing. */\nexport class GraphEdgeCapError extends Error {\n readonly exhaustedEdges: ReadonlyArray<string>\n readonly ledger: ReadonlyArray<EdgeTraversal>\n readonly result: SupervisedResult<unknown>\n constructor(\n exhaustedEdges: ReadonlyArray<string>,\n ledger: ReadonlyArray<EdgeTraversal>,\n result: SupervisedResult<unknown>,\n ) {\n super(\n `runGraph: edge traversal cap exhausted on ${exhaustedEdges.join(', ')} and the run ` +\n 'delivered no winner — the cap (the cyclic-graph backstop), not the task, ended this run. ' +\n 'Raise maxTraversals on the edge or fix the cycle; the full edge ledger and the ' +\n 'supervised result ride on this error.',\n )\n this.name = 'GraphEdgeCapError'\n this.exhaustedEdges = exhaustedEdges\n this.ledger = ledger\n this.result = result\n }\n}\n\n// ── Options / result ───────────────────────────────────────────────────────────\n\n/**\n * Every `SuperviseOptions` key, partitioned by what `runGraph` does with it.\n *\n * `runGraph` starts one `supervise()` run, so every option that run honors is a graph option too\n * unless the graph itself owns the value. This used to be an opt-in list written by hand, and the\n * hand lost: 25 of 49 keys never reached `supervise()` from a graph, including `childSettleGraceMs`\n * (a root-driver failure tore down children that had ALREADY computed the deliverable) and\n * `driverRetry` (agent-runtime#963). Each absence was discovered by losing a run.\n *\n * The four lists below must cover `keyof SuperviseOptions` exactly. `everySuperviseOptionIsClassified`\n * below fails to COMPILE, naming the offender, when a key belongs to none of them — so the next\n * option added to `supervise()` cannot go missing here silently. It has to be classified, and\n * classifying it as forwarded is one word.\n */\n\n/** The graph derives these from the `AgentGraph` itself; a caller value would be overwritten. */\nconst GRAPH_OWNED_SUPERVISE_OPTIONS = [\n 'rootDriverFromBackend',\n 'resolveSpawnProfile',\n 'budget',\n 'deliverable',\n 'makeWorkerAgent',\n 'onCoordinationEvent',\n 'analyzeOnSettle',\n 'mapOnSettle',\n // A flow graph's entries and routes edges; its runtime-owned root runs them.\n 'routeFlow',\n // A flow graph's check nodes, bound from `checkPlacement` or the run's working directory.\n 'checkNodes',\n 'continuityByProfile',\n // A graph pins every node and its delegation edges; a node never gains spawn rights it lacks.\n 'inheritSpawnRights',\n // The graph's own directive `registry`, which its maps items and `run_graph` subtasks resolve against.\n 'promptRegistry',\n] as const\n\n/** Caller-facing on `RunGraphOptions`, but the graph wraps or defaults the value before it goes in:\n * `hooks` composes with the graph's own spawn-binding hook, `authorizeMessage` is wrapped so a\n * narrowed instruction ledgers `stripped`, `authorizeSpawn` runs AFTER the graph has pinned the\n * node (so a product sees the canonical profile, never the driver's stub), `makeLeafAgent` is the\n * caller's leaf override slotted under the graph's pinning, `analysts` rides only with analyze\n * routes, and `journal`/`blobs`/`runId` get graph defaults. */\nconst GRAPH_TRANSFORMED_SUPERVISE_OPTIONS = [\n 'hooks',\n 'authorizeMessage',\n 'authorizeSpawn',\n 'makeLeafAgent',\n 'analysts',\n 'journal',\n 'blobs',\n 'runId',\n // Replays a journaled decision before asking the caller.\n 'decideGate',\n] as const\n\n/** Not reachable from a graph, with the reason. `registry` is a NAME COLLISION, not a policy:\n * `RunGraphOptions.registry` is the directive `PromptRegistry` and `SuperviseOptions.registry` is\n * the `SuperviseRegistry` name→value table. Two different types under one name; the graph's wins.\n * Giving the supervise one a graph channel means renaming a public option, so it is recorded here\n * rather than silently dropped. */\nconst GRAPH_REFUSED_SUPERVISE_OPTIONS = ['registry'] as const\n\n/**\n * Forwarded to the root `supervise()` VERBATIM. Everything not owned, transformed, or refused\n * above belongs here — the default is \"a graph honors it\", not \"someone remembered to add it\".\n */\nconst GRAPH_FORWARDED_SUPERVISE_OPTIONS = [\n 'parking',\n 'backend',\n // Forwarded: composes guidance into the root and into profiles a manager authors. The graph also\n // composes each PINNED node profile, because pinning replaces the composed `{ name }` stub.\n 'profileGuidance',\n // Forwarded, not graph-owned: a graph pins WHICH nodes run, never who answers a question one of\n // them raises. Without it a graph run's `ask_parent` would always report `no-parent` even when\n // the caller wired an inbox.\n 'escalateQuestion',\n 'rootHandle',\n 'signal',\n 'execution',\n 'resolveDeliverable',\n 'coordination',\n 'peerMail',\n 'peerAudit',\n 'traceTools',\n 'driverBackend',\n 'profileSecurity',\n 'authorizeSpawn',\n 'router',\n 'driveHarness',\n 'selectSeat',\n 'driverRetry',\n 'onDriverAttempt',\n 'continuation',\n 'childSettleGraceMs',\n 'teardownConfirmMs',\n 'retainedAtSettlement',\n 'resolveDriveHarness',\n 'driveHarnessMaterialization',\n 'resolveSupervisorTools',\n 'servesToolNames',\n 'extraTools',\n 'executeExtraTool',\n 'recoverExecutor',\n 'perWorker',\n 'reservationPolicy',\n 'deadlineCheckIn',\n 'budgetStopHoldMs',\n 'workerSlots',\n 'watchWorkers',\n 'stallAfterMs',\n 'wake',\n 'runDir',\n 'resume',\n 'segment',\n 'runContext',\n 'steerDir',\n 'stopRule',\n 'onProgressStop',\n 'maxDepth',\n 'maxTurns',\n 'compaction',\n 'now',\n 'allowedModels',\n 'finalizer',\n 'otel',\n // Forwarded: the registry a manager's `run_graph` resolves stored graphs against. A node of this\n // graph cannot start another graph (pinning refuses it), so it matters to no node here.\n 'graphRegistry',\n] as const\n\ntype ClassifiedSuperviseOption =\n | (typeof GRAPH_OWNED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_TRANSFORMED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_REFUSED_SUPERVISE_OPTIONS)[number]\n | (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]\n\n/**\n * Every key `RunGraphOptions` accepts, as data: the forwarded and transformed `SuperviseOptions`\n * keys, the name-colliding `registry`, and the graph's own `brain`. `GRAPH_OWNED_SUPERVISE_OPTIONS`\n * is deliberately absent — a caller value for one of those is overwritten by the graph, so it is\n * refused by name rather than discarded.\n *\n * The assignment below fails to COMPILE, naming the key, when `RunGraphOptions` declares something\n * this list does not carry.\n */\nconst runGraphOptionKeys = [\n ...GRAPH_FORWARDED_SUPERVISE_OPTIONS,\n ...GRAPH_TRANSFORMED_SUPERVISE_OPTIONS,\n ...GRAPH_REFUSED_SUPERVISE_OPTIONS,\n 'brain',\n 'checkPlacement',\n 'checkArtifacts',\n 'trigger',\n] as const\n\ntype UnlistedRunGraphOption = Exclude<keyof RunGraphOptions, (typeof runGraphOptionKeys)[number]>\nconst everyRunGraphOptionIsListed: UnlistedRunGraphOption extends never\n ? true\n : UnlistedRunGraphOption = true\nvoid everyRunGraphOptionIsListed\n\nconst runGraphOptionKeySet: ReadonlySet<string> = new Set<string>(runGraphOptionKeys)\nconst graphOwnedOptionKeySet: ReadonlySet<string> = new Set<string>(GRAPH_OWNED_SUPERVISE_OPTIONS)\n\n/**\n * Refuse an option key the graph would not read, naming it and saying which kind it is.\n *\n * A graph-owned key is the sharper case: it type-checks against a widened `SuperviseOptions`\n * value, the graph derives its own value and overwrites the caller's, the run succeeds, and the\n * capability the caller asked for is not there. The rename of the leaf seam from `makeWorkerAgent`\n * to `makeLeafAgent` is the shape of the failure — the old name stayed a valid `SuperviseOptions`\n * key AND a graph-owned one, so a caller that kept passing it got a run with no leaf override and\n * no complaint.\n */\nfunction assertRunGraphOptionKeys(opts: RunGraphOptions): void {\n const graphOwned: string[] = []\n const unknown: string[] = []\n for (const key of Object.keys(opts)) {\n if (runGraphOptionKeySet.has(key)) continue\n if (graphOwnedOptionKeySet.has(key)) graphOwned.push(key)\n else unknown.push(key)\n }\n if (graphOwned.length > 0) {\n throw new ConfigError(\n `runGraph: ${graphOwned.sort().join(', ')} — the graph derives this from the AgentGraph ` +\n 'itself, so a caller value is overwritten and the capability it asks for would silently ' +\n 'be absent',\n )\n }\n if (unknown.length > 0) {\n throw new ConfigError(\n `runGraph: unknown option ${unknown.sort().join(', ')} — no reader consults that name, so ` +\n 'the value would be discarded and the capability it asks for would silently be absent',\n )\n }\n}\n\n/** A `SuperviseOptions` key in none of the four lists makes this assignment fail, and the compiler\n * error names the key. Classify it — `GRAPH_FORWARDED_SUPERVISE_OPTIONS` is usually the answer. */\ntype UnclassifiedSuperviseOption = Exclude<keyof SuperviseOptions, ClassifiedSuperviseOption>\nconst everySuperviseOptionIsClassified: UnclassifiedSuperviseOption extends never\n ? true\n : UnclassifiedSuperviseOption = true\nvoid everySuperviseOptionIsClassified\n\n/** `backend` and `driverBackend` keep graph-specific documentation below.\n *\n * Do not inherit and redeclare them through an indexed access type.\n * TypeScript 7 correctly treats `SuperviseOptions['backend']` as including `undefined`, which makes\n * that redeclaration wider than the exact optional property inherited from `SuperviseOptions`.\n */\ntype GraphInheritedSuperviseOption = Exclude<\n (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number],\n 'backend' | 'driverBackend'\n>\n\n/** Copy every forwarded option the caller actually set. Absent stays absent: `supervise()` and the\n * graph must not disagree about what \"unset\" means. */\nfunction forwardedSuperviseOptions(\n opts: RunGraphOptions,\n): Pick<SuperviseOptions, (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]> {\n const forwarded: Record<string, unknown> = {}\n for (const key of GRAPH_FORWARDED_SUPERVISE_OPTIONS) {\n const value = (opts as Record<string, unknown>)[key]\n if (value !== undefined) forwarded[key] = value\n }\n return forwarded as Pick<SuperviseOptions, (typeof GRAPH_FORWARDED_SUPERVISE_OPTIONS)[number]>\n}\n\n/**\n * Options for one `runGraph` run.\n *\n * Extends every forwarded `SuperviseOptions` key, so a graph honors what a `supervise()` run\n * honors WITHOUT anyone restating it here. Only the graph-specific members and the ones whose\n * graph semantics differ are declared below; everything else inherits its type AND its\n * documentation from `SuperviseOptions`, which is the one owner of both.\n */\nexport interface RunGraphOptions extends Pick<SuperviseOptions, GraphInheritedSuperviseOption> {\n /** WHERE worker nodes run — the executor backend. Provide this OR `makeLeafAgent`. Forwarded to\n * `supervise()`, which derives every authorized leaf from it. A node that declares\n * `agent_runtime_coordination_spawn_worker` becomes a nested supervisor instead, whose own\n * leaves are derived the same way. */\n readonly backend?: Exclude<SuperviseOptions['backend'], undefined>\n /** WHERE the ROOT node's harness brain runs — forwarded to `supervise()` verbatim (see\n * `SuperviseOptions.driverBackend`). Needed when the root node's profile declares an external\n * harness (`codex`, `claude-code`, `opencode`): that root is driven by the harness, not by the\n * router brain, and automatic execution supports a local `bridge`. Unlike `supervise()`, this\n * does NOT default to `backend`: a graph's `backend` places WORKER nodes, so the root driver\n * is selected only by this field. Omit = no harness driver, which is correct for a root whose\n * `profile.harness` is omitted or `cli-base` (that root runs on the router brain). */\n readonly driverBackend?: Exclude<SuperviseOptions['driverBackend'], undefined>\n /** Leaf-execution override (offline tests / advanced). `runGraph` still owns node pinning,\n * directive delivery, and the edge ledger AROUND this seam — only the leaf `act` is yours.\n * Slots INSIDE the kernel's authorized path (`SuperviseOptions.makeLeafAgent`), so a node that\n * declares the spawn tool still becomes a nested supervisor even under an offline leaf. */\n readonly makeLeafAgent?: MakeWorkerAgent\n /** The ROOT driver's inference seam — a caller-owned `ToolLoopChat` that makes every root\n * model call. Use it when the root's decisions must be caller-owned orchestration (a\n * deterministic conversation driver, a persona loop with its own LLM calls) rather than a\n * router-derived model call. The graph machinery around the seam is unchanged: node pinning,\n * directive delivery, the edge ledger, and the journal twin all run the same shipped path,\n * and the root profile keeps prompt control (`prompt-control-execution` materialization —\n * `systemPrompt`/`instructions` still apply). What moves to the caller with the brain:\n * model selection and provider-identity validation (`expectedModel` cannot be enforced on a\n * call the runtime did not place) and per-turn usage reporting (a brain that reports no\n * usage meters nothing into the pool). Omit = the router brain derived from the root\n * profile — the unchanged default. Mutually exclusive with `driverBackend`, and refused\n * when the root profile declares an external harness (that root is driven BY the harness). */\n readonly brain?: ToolLoopChat\n /** Caller-side runtime hooks (telemetry, policy, product extensions). Composed AFTER the\n * graph's own spawn-binding hook on the SAME event stream — the graph never swallows the\n * seam supervise() exposes. */\n readonly hooks?: RuntimeHooks\n /** The analyst lens registry `analyzes` edges resolve against. ENVIRONMENT — needed only for\n * lens analysts; an analyzes edge naming a graph NODE as its analyst needs no registry. */\n readonly analysts?: AnalystRegistry\n /** Answers a flow gate while the process holds the run; the wait counts against its deadline.\n * ENVIRONMENT, like `analysts`; required when the graph declares gates. */\n readonly decideGate?: (request: GateRequest) => Promise<GateDecision>\n /** Directive registry. Default: the seeded kernel registry (`kernelPromptRegistry()`).\n *\n * NOT `SuperviseOptions.registry`, which is the `SuperviseRegistry` name→value table for\n * code-valued options. The two share a name and nothing else, and this one wins here — see\n * `GRAPH_REFUSED_SUPERVISE_OPTIONS`. */\n readonly registry?: PromptRegistry\n /** The run journal the edge ledger and every spawn/settle ride. Default: in-memory. */\n readonly journal?: SpawnJournal\n readonly blobs?: ResultBlobStore\n readonly runId?: string\n /** Product authority over every steer/answer instruction (the filter seam). `runGraph` observes\n * what it CHANGES: a narrowed instruction ledgers its steer traversal as `stripped`. */\n readonly authorizeMessage?: SuperviseOptions['authorizeMessage']\n /** Where check nodes run: a fresh Sandbox box per check, created by `client` on the check account,\n * from each node's `environment`. Absent = locally, in the run's working directory (a loopback\n * Bridge `cwd` or a `cli-in-place` workspace). */\n readonly checkPlacement?: GraphCheckPlacement\n /** Trusted readable artifact store for declared check outputs, retained before box cleanup. */\n readonly checkArtifacts?: AgentCandidateOutputArtifactPort\n /** Structured event data for GRAPH_INPUT; bound to the run's task identity, never a shell slot. */\n readonly trigger?: GraphFromStoredOptions['trigger']\n}\n\nexport interface GraphResult<Out = unknown> {\n readonly result: SupervisedResult<Out>\n /** Every edge traversal, in occurrence order — the observable-edge contract. */\n readonly ledger: ReadonlyArray<EdgeTraversal>\n /** Edge ids whose traversal cap was hit — analyzes exhaustion included (observable here, never\n * a refusal). A DELEGATES cap paired with a `no-winner` result THROWS\n * ({@link GraphEdgeCapError}) instead of returning: only delegates caps refuse spawns, so only\n * they can have ended the run. A LIFECYCLE no-winner (`aborted` / `budget-exhausted`) returns\n * normally even with an exhausted delegates cap — the abort or the pool, not the cap, ended\n * that run, and the exhaustion stays observable here. */\n readonly exhaustedEdges: ReadonlyArray<string>\n readonly runId: string\n /** Why a flow graph ended early: a `stop` edge fired (`edge` names it), or a flow node settled\n * down (no `edge`; `reason` is `down: <worker reason>`) or, where a route was needed, without a\n * usable result (no `edge`; `reason` is `unusable: <why>`). Live flow workers are aborted. */\n readonly stopped?: {\n readonly code?: string\n readonly edge?: string\n readonly at: NodeId\n readonly workerId: string\n readonly reason: string\n }\n}\n\n/** `RunGraphOptions` with the brain REQUIRED — the shape the `/testing` entry's\n * `runGraphWithTestBrain` keeps accepting now that `brain` is a production option. */\nexport interface RunGraphTestOptions extends RunGraphOptions {\n readonly brain: ToolLoopChat\n}\n\n// ── Validation ─────────────────────────────────────────────────────────────────\n\n/** Validate the graph and resolve every directive BEFORE any compute is spent — an invalid\n * topology or an unknown directive is a configuration fault, never a mid-run surprise. */\nfunction validateGraph(\n graph: AgentGraph,\n registry: PromptRegistry,\n analysts: AnalystRegistry | undefined,\n): ValidatedGraph {\n if (graph.entry === undefined) {\n if (!Array.isArray(graph.nodes) || graph.nodes.length === 0) {\n throw new ValidationError('runGraph: graph.nodes must be a non-empty array')\n }\n if (!Array.isArray(graph.edges) || graph.edges.length === 0) {\n throw new ValidationError('runGraph: graph.edges must be a non-empty array')\n }\n }\n if (typeof graph.deliverable?.check !== 'function') {\n throw new ValidationError('runGraph: graph.deliverable is mandatory (termination oracle)')\n }\n if (typeof graph.budget !== 'object' || graph.budget === null) {\n throw new ValidationError('runGraph: graph.budget is mandatory (the conserved pool)')\n }\n if (graph.entry !== undefined) return validateFlowGraph(graph, registry, analysts)\n if (graph.gates !== undefined)\n throw new ValidationError('runGraph: graph.gates needs graph.entry')\n return validateGraphTopology(graph.nodes, graph.edges, registry, analysts)\n}\n\n// ── The runner ─────────────────────────────────────────────────────────────────\n\n/**\n * Execute an {@link AgentGraph}. A flow graph (`entry` set) runs from its entries and routes edges\n * under a runtime-owned root that places no model call. Otherwise the root node becomes the\n * supervisor (`supervise()` — the execution core), each worker node is spawnable BY NODE ID\n * (`spawn_worker` with `profile: { name: '<node id>' }`; the node's canonical profile is pinned by\n * the graph), each\n * delegates directive is appended to the worker profile's `prompt.instructions` per traversal,\n * and each analyzes edge becomes an analyst-on-settle route with a real DESTINATION. Every\n * traversal is ledgered and journaled.\n */\nexport function runGraph(graph: AgentGraph, opts: RunGraphOptions): Promise<GraphResult> {\n const { brain, ...runtimeOptions } = graphExecutionOptions(opts)\n return superviseAgentGraph(graph, runtimeOptions, brain)\n}\n\n/** Alias for graph tests written before `RunGraphOptions.brain` was production. The production\n * entry accepts the same shape; this wrapper only keeps the `/testing` import path working. */\nexport function runGraphWithTestBrain(\n graph: AgentGraph,\n opts: RunGraphTestOptions,\n): Promise<GraphResult> {\n const { brain, ...runtimeOptions } = opts\n return superviseAgentGraph(graph, runtimeOptions, brain)\n}\n\n/**\n * The graph supervise run, as its own entry: the engine's `run-graph` preset node executes exactly\n * this, so the preset and `runGraph` are the same code path by construction (agent-runtime#982).\n */\n/**\n * Every refusal a graph earns before any compute, in one place: the authoring contract. `runGraph`\n * calls it FIRST so a malformed graph throws synchronously, exactly as it did before the engine\n * preset (agent-runtime#982) moved execution behind a promise.\n */\nexport function assertRunGraphAuthoring(\n graph: AgentGraph,\n opts: RunGraphOptions,\n brain?: ToolLoopChat,\n): ReturnType<typeof validateGraph> {\n assertRunGraphOptionKeys(opts)\n if (graph.continuation !== undefined) {\n portableContinuationPolicySchema.parse(graph.continuation)\n if (opts.continuation !== undefined)\n throw new ValidationError(\n 'runGraph: graph.continuation and opts.continuation have two policy owners',\n )\n if (graph.entry !== undefined)\n throw new ValidationError('runGraph: graph.continuation with graph.entry has no root manager')\n }\n const registry = opts.registry ?? kernelPromptRegistry()\n const validated = validateGraph(graph, registry, opts.analysts)\n const requireLeaves = (): void => {\n if (!opts.backend && !opts.makeLeafAgent) {\n throw new ValidationError(\n 'runGraph: provide opts.backend (where nodes run) or opts.makeLeafAgent',\n )\n }\n }\n if (validated.flow !== undefined) {\n // A flow's root is Runtime's own: nothing a caller sets for a root manager has a reader.\n const rootOptions = [\n ...(brain ? ['brain'] : []),\n ...(['driverBackend', 'finalizer', 'maxTurns', 'compaction'] as const).filter(\n (key) => opts[key] !== undefined,\n ),\n ]\n if (rootOptions.length > 0) {\n throw new ValidationError(\n `runGraph: ${rootOptions.join(', ')} with graph.entry — a flow graph has no root ` +\n 'manager: Runtime spawns its entries and traverses its routes edges, and the graph ' +\n \"owns the run's output\",\n )\n }\n if ((graph.gates?.length ?? 0) > 0 && opts.decideGate === undefined) {\n throw new ValidationError('runGraph: graph.gates needs opts.decideGate to answer them')\n }\n requireLeaves()\n return validated\n }\n const { root } = validated as RootValidatedGraph\n if (graph.continuation !== undefined && !harnessRunsAgent(root.profile.harness))\n throw new ValidationError('runGraph: graph.continuation requires an external-harness root')\n // A caller brain and a harness driver are two answers to WHO makes the root's calls: refuse the\n // contradiction before any compute, and refuse a harness-driven root outright — the harness IS\n // that root's brain, so a supplied one would be silently ignored downstream.\n if (brain && opts.driverBackend) {\n throw new ValidationError(\n 'runGraph: brain and driverBackend are mutually exclusive — a caller brain makes the root model calls, a driverBackend places a harness that makes its own',\n )\n }\n if (brain && harnessRunsAgent(root.profile.harness)) {\n throw new ValidationError(\n `runGraph: root node '${root.id}' declares harness '${root.profile.harness}', so the harness drives it — a caller brain applies only to a router-brained root (profile.harness omitted or 'cli-base')`,\n )\n }\n requireLeaves()\n return validated\n}\n\nexport function superviseAgentGraph(\n graph: AgentGraph,\n opts: RunGraphOptions,\n brain?: ToolLoopChat,\n): Promise<GraphResult> {\n const { continuation, ...topology } = graph\n graph = {\n ...topology,\n ...(continuation === undefined\n ? {}\n : { continuation: portableContinuationPolicySchema.parse(continuation) }),\n }\n if (graph.deliverable.command !== undefined) {\n const bound = bindGraphCommand(graph, opts)\n return superviseAgentGraph(bound.graph, bound.options, brain)\n }\n const registry = opts.registry ?? kernelPromptRegistry()\n if (opts.runContext?.acquire !== undefined) {\n return withRunContext(opts.runContext, opts.signal, (runContext, signal) =>\n superviseAgentGraph(\n graph,\n {\n ...opts,\n runContext,\n ...(signal === undefined ? {} : { signal }),\n },\n brain,\n ),\n )\n }\n const validated = assertRunGraphAuthoring(graph, opts, brain)\n const trigger =\n opts.trigger === undefined ? undefined : detachedSnapshot(opts.trigger, 'runGraph trigger')\n const context =\n opts.runContext ??\n (opts.runDir === undefined\n ? createInMemoryRunContext()\n : createFileRunContext(resolve(opts.runDir)))\n const journal = opts.journal ?? context.journal\n const blobs = opts.blobs ?? context.blobs\n const runId =\n opts.runId ??\n opts.runContext?.runId ??\n `graph-${canonicalCandidateDigest(graph.nodes.map((n) => n.id)).slice('sha256:'.length, 'sha256:'.length + 12)}`\n const now = opts.now ?? Date.now\n const checkNodes = bindGraphCheckNodes(graph, { ...opts, runId, trigger })\n\n // The graph layer: node pinning, analyst routes, continuity defaults and the edge ledger. A\n // `run_graph` subtask builds the same overlay around its nested manager.\n // `profileGuidance` composes the profile a manager authors, but a graph then swaps that\n // `{ name }` stub for the pinned node profile. Compose the pinned profile too, so every node\n // that runs carries its harness and model guidance. Composition is idempotent.\n const guidance = profileGuidanceComposer(opts.profileGuidance)\n const overlay = createGraphOverlay(validated, {\n registry,\n journal,\n runId,\n now,\n ...(guidance ? { guidance } : {}),\n ...(opts.authorizeSpawn ? { authorizeSpawn: opts.authorizeSpawn } : {}),\n })\n // A flow graph: Runtime schedules its nodes, and its root manager is Runtime's own.\n const flow = validated.flow === undefined ? undefined : createFlowRun(overlay.nodeOfWorker)\n // Always present: the kernel refuses steer/answer whenever spawn authorization is on (the\n // graph's pinning IS spawn authorization), so a graph with no caller filter passes instructions\n // through unchanged rather than losing its steer channel. Only a caller filter can strip.\n const callerAuthorizeMessage = opts.authorizeMessage\n const authorizeMessage = overlay.observeMessages<\n Parameters<NonNullable<SuperviseOptions['authorizeMessage']>>[0]\n >((input) =>\n callerAuthorizeMessage ? callerAuthorizeMessage(input) : { instruction: input.instruction },\n )\n\n // ── Spawn-hook: bind ledger rows to concrete worker ids, then journal them ──\n const graphHooks: RuntimeHooks = {\n onEvent: (event) => {\n if (event.target !== 'agent.spawn' || event.phase !== 'after') return\n const payload = event.payload as { childId?: unknown; assignmentId?: unknown } | undefined\n if (typeof payload?.childId !== 'string' || typeof payload.assignmentId !== 'string') return\n return overlay.bindSpawn(event.parentId, payload.assignmentId, payload.childId)\n },\n }\n const hooks = composeRuntimeHooks(graphHooks, opts.hooks)\n const rootProfile =\n flow === undefined\n ? graphRootProfile(validated as RootValidatedGraph, registry)\n : flowRootProfile\n const rootBrain = flow === undefined ? brain : runtimeFlowBrain()\n const description =\n flow === undefined\n ? (graph.deliverable.describe ??\n `Deliver the graph's deliverable by driving your worker nodes (root: '${(validated as RootValidatedGraph).root.id}').`)\n : (graph.deliverable.describe ?? 'Runtime runs this flow graph from its entries.')\n const task = trigger === undefined ? description : { task: description, trigger }\n\n // Every configuration fault above throws SYNCHRONOUSLY (matching `supervise()`'s own\n // contract); only the run itself is asynchronous.\n const start = async (): Promise<GraphResult> => {\n const superviseOptions = {\n // The backend also drives seat-bearing flow nodes, which use the managed driver lifecycle.\n // A flow's root keeps Runtime's deterministic brain; deriving its child driver adds no root\n // inference. Rooted graphs keep driverBackend explicit rather than inheriting backend.\n ...forwardedSuperviseOptions(opts),\n rootDriverFromBackend: flow !== undefined,\n // Graph-owned values come after the spread: the graph, not the caller, decides these.\n budget: graph.budget,\n ...(graph.continuation === undefined ? {} : { continuation: graph.continuation }),\n deliverable: flow?.routeCheck(graph.deliverable) ?? graph.deliverable,\n authorizeSpawn: overlay.authorizeSpawn,\n resolveSpawnProfile: overlay.resolveSpawnProfile,\n inheritSpawnRights: false,\n promptRegistry: registry,\n ...(opts.makeLeafAgent ? { makeLeafAgent: opts.makeLeafAgent } : {}),\n journal,\n blobs,\n runId,\n hooks,\n onCoordinationEvent: async (\n context: { readonly depth: number },\n _eventId: unknown,\n record: { readonly event: Parameters<typeof overlay.onCoordinationEvent>[0] },\n ) => {\n // A route event belongs to the flow of the manager that published it: a flow inside a\n // maps item or a run_graph subtask ledgers and concludes its own.\n if (record.event.type === 'route' && context.depth !== 0) return\n overlay.onCoordinationEvent(record.event)\n flow?.observe(record.event)\n },\n // Lens routes resolve against the registry; agent routes carry their own analyst profile,\n // so a graph whose only analysts are nodes needs no registry at all.\n ...(overlay.routes.length > 0\n ? {\n analyzeOnSettle: overlay.routes,\n ...(opts.analysts ? { analysts: opts.analysts } : {}),\n }\n : {}),\n ...(overlay.maps.length > 0 ? { mapOnSettle: overlay.maps } : {}),\n ...(Object.keys(overlay.continuityByProfile).length > 0\n ? { continuityByProfile: overlay.continuityByProfile }\n : {}),\n // A flow root's wake batches nothing for a decision, so it ends its turn on the first event.\n ...(flow === undefined\n ? {}\n : {\n routeFlow: routeFlowOf(validated),\n ...(checkNodes && { checkNodes }),\n ...(opts.decideGate && {\n decideGate: journaledGateDecider(opts.decideGate, journal, runId),\n }),\n finalizer: flow.finalizer,\n wake: { debounceMs: 0, ...opts.wake },\n }),\n authorizeMessage,\n } satisfies SuperviseOptions\n // The flow root reaches supervise through the same brain seam a caller brain takes.\n const supervised =\n rootBrain === undefined\n ? await supervise(rootProfile, task, superviseOptions)\n : await superviseWithTestBrain(rootProfile, task, { ...superviseOptions, brain: rootBrain })\n\n const { ledger, exhaustedEdges, exhaustedDelegates } = await overlay.settle()\n const concluded = flow?.conclude(supervised)\n if (concluded?.kind === 'unrouted') {\n throw new GraphRouteError(concluded.unrouted, ledger, supervised)\n }\n const result = concluded?.result ?? supervised\n const stopped = concluded?.stopped\n // A LIFECYCLE ending (caller abort, exhausted budget, deadline) is its own complete explanation: the\n // cap did not end that run even when it was exhausted along the way, and blaming it would\n // misattribute the ending (and turn a caller-initiated abort into a throw). The exhaustion\n // stays observable in `exhaustedEdges` either way.\n const lifecycleEnded =\n result.kind === 'no-winner' &&\n (result.reason === 'aborted' ||\n result.reason === 'cancelled' ||\n result.reason === 'budget-exhausted' ||\n result.reason === 'deadline')\n if (result.kind !== 'winner' && !lifecycleEnded && exhaustedDelegates.length > 0) {\n // Fail LOUD: the backstop, not the task, ended this run. The evidence rides on the error.\n // Only DELEGATES caps refuse spawns, so only they can be the cause named here.\n throw new GraphEdgeCapError(exhaustedDelegates, ledger, result)\n }\n return { result, ledger, exhaustedEdges, runId, ...(stopped ? { stopped } : {}) }\n }\n\n return start()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAM,aAAa;AAGnB,eAAe,aAAa,MAAsC;CAChE,IAAI;EACF,OAAO,MAAM,SAAS,MAAM,MAAM;CACpC,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,gBAAgB,OAA8C;CACrE,M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