@tangle-network/agent-runtime 7.0.0 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/README.md +0 -3
  3. package/dist/{activation-Ba9IAgQ3.js → activation-Ce4zUcu8.js} +4 -4
  4. package/dist/{activation-Ba9IAgQ3.js.map → activation-Ce4zUcu8.js.map} +1 -1
  5. package/dist/{activation-DIkTEBWF.d.ts → activation-xxvLF1-1.d.ts} +2 -2
  6. package/dist/agent.d.ts +1 -1
  7. package/dist/agent.js +3 -3
  8. package/dist/{bundle-Cy5igJdv.js → bundle-CcpL2lfr.js} +2 -2
  9. package/dist/{bundle-Cy5igJdv.js.map → bundle-CcpL2lfr.js.map} +1 -1
  10. package/dist/candidate-execution/index.js +4 -4
  11. package/dist/continuation-CIyKnS1Q.js +451 -0
  12. package/dist/continuation-CIyKnS1Q.js.map +1 -0
  13. package/dist/{coordination-manager-DQZ2u6L-.js → coordination-manager-sa_PkISw.js} +194 -148
  14. package/dist/coordination-manager-sa_PkISw.js.map +1 -0
  15. package/dist/{coordination-map-routing-CKRNZSaV.js → coordination-map-routing-XZXTlCmn.js} +2 -4
  16. package/dist/coordination-map-routing-XZXTlCmn.js.map +1 -0
  17. package/dist/{delegate-DFLSVjFG.js → delegate-DhTkJIta.js} +3 -3
  18. package/dist/{delegate-DFLSVjFG.js.map → delegate-DhTkJIta.js.map} +1 -1
  19. package/dist/durable.d.ts +1 -1
  20. package/dist/durable.js +13 -12
  21. package/dist/durable.js.map +1 -1
  22. package/dist/{errors-AzSuGI23.js → errors-DG8yufqX.js} +8 -1
  23. package/dist/errors-DG8yufqX.js.map +1 -0
  24. package/dist/{failure-cause-rJTm_Tx8.js → failure-cause-CVB-YE88.js} +12 -8
  25. package/dist/{failure-cause-rJTm_Tx8.js.map → failure-cause-CVB-YE88.js.map} +1 -1
  26. package/dist/{graph-registry-7X2nrreR.js → graph-registry-czAwYwNj.js} +133 -9
  27. package/dist/graph-registry-czAwYwNj.js.map +1 -0
  28. package/dist/{graph-registry-gYbq4L5Z.js → graph-registry-uTIyyy7A.js} +1 -1
  29. package/dist/graph-tSIT_eWK.js +1793 -0
  30. package/dist/graph-tSIT_eWK.js.map +1 -0
  31. package/dist/{improve-BolbYegO.js → improve-H08hiIw9.js} +19 -48
  32. package/dist/improve-H08hiIw9.js.map +1 -0
  33. package/dist/index.d.ts +3 -3
  34. package/dist/index.js +16 -16
  35. package/dist/intelligence.d.ts +2 -2
  36. package/dist/intelligence.js +8 -8
  37. package/dist/intelligence.js.map +1 -1
  38. package/dist/kernel.d.ts +2 -2
  39. package/dist/kernel.js +16 -15
  40. package/dist/{loop-runner-Cs9IJ6Nk.d.ts → loop-runner-BGwhcn1p.d.ts} +2 -2
  41. package/dist/{loop-runner-C9W3T_3T.js → loop-runner-ChqK8kSz.js} +3 -3
  42. package/dist/{loop-runner-C9W3T_3T.js.map → loop-runner-ChqK8kSz.js.map} +1 -1
  43. package/dist/loop-runner-bin.d.ts +1 -1
  44. package/dist/loop-runner-bin.js +1 -1
  45. package/dist/mcp/bin.js +7 -5
  46. package/dist/mcp/bin.js.map +1 -1
  47. package/dist/mcp/index.d.ts +1 -1
  48. package/dist/mcp/index.js +9 -9
  49. package/dist/mcp/memory-bin.js +2 -2
  50. package/dist/{model-policy-JOcg3NRs.js → model-policy-yxOrDTTj.js} +9 -9
  51. package/dist/model-policy-yxOrDTTj.js.map +1 -0
  52. package/dist/{prepare-Dtfk_Wi_.js → prepare-BnF8nGIg.js} +4 -4
  53. package/dist/{prepare-Dtfk_Wi_.js.map → prepare-BnF8nGIg.js.map} +1 -1
  54. package/dist/{profile-CNSQjOes.js → profile-CD25rTJF.js} +4 -4
  55. package/dist/{profile-CNSQjOes.js.map → profile-CD25rTJF.js.map} +1 -1
  56. package/dist/profiles.d.ts +1 -1
  57. package/dist/profiles.js +2 -2
  58. package/dist/{provision-supervisor-BQFHjCtN.js → provision-supervisor-Dx4TXTMM.js} +8 -8
  59. package/dist/{provision-supervisor-BQFHjCtN.js.map → provision-supervisor-Dx4TXTMM.js.map} +1 -1
  60. package/dist/{run-cancellation-B84X8ZAP.js → run-cancellation-DYszFJtQ.js} +4 -4
  61. package/dist/{run-cancellation-B84X8ZAP.js.map → run-cancellation-DYszFJtQ.js.map} +1 -1
  62. package/dist/{run-state-Dh1bGERI.js → run-state-DHBoJjaF.js} +5 -5
  63. package/dist/{run-state-Dh1bGERI.js.map → run-state-DHBoJjaF.js.map} +1 -1
  64. package/dist/{runtime-C9F1PG2A.js → runtime-CaM5Gbbv.js} +76 -987
  65. package/dist/runtime-CaM5Gbbv.js.map +1 -0
  66. package/dist/{sandbox-profile-compat-oFGWESLn.js → sandbox-profile-compat-l-SLQnGb.js} +2 -2
  67. package/dist/{sandbox-profile-compat-oFGWESLn.js.map → sandbox-profile-compat-l-SLQnGb.js.map} +1 -1
  68. package/dist/{search-executor-CKR9_6NR.js → search-executor-B9L8W_1O.js} +17 -46
  69. package/dist/search-executor-B9L8W_1O.js.map +1 -0
  70. package/dist/{server-Dh3SQGQT.js → server-BlDV8sj_.js} +32 -8
  71. package/dist/{server-Dh3SQGQT.js.map → server-BlDV8sj_.js.map} +1 -1
  72. package/dist/{settle-record-C6LdVvok.js → settle-record-WWQasnDq.js} +2 -2
  73. package/dist/{settle-record-C6LdVvok.js.map → settle-record-WWQasnDq.js.map} +1 -1
  74. package/dist/{snapshot-Cgj2Wzi6.js → snapshot-BKI_w3JD.js} +19 -5
  75. package/dist/snapshot-BKI_w3JD.js.map +1 -0
  76. package/dist/{structural-rollout-Dapf2aZY.js → structural-rollout-C1xxoWcN.js} +18 -54
  77. package/dist/structural-rollout-C1xxoWcN.js.map +1 -0
  78. package/dist/{supervise-xwl2D6q3.js → supervise-DWiSgPLB.js} +101 -111
  79. package/dist/supervise-DWiSgPLB.js.map +1 -0
  80. package/dist/{supervision-discovery-B47U8TH5.js → supervision-discovery-C9kfBLKy.js} +4 -4
  81. package/dist/{supervision-discovery-B47U8TH5.js.map → supervision-discovery-C9kfBLKy.js.map} +1 -1
  82. package/dist/{supervisor-gC-u_PRk.js → supervisor-Dpeu7rnZ.js} +206 -693
  83. package/dist/supervisor-Dpeu7rnZ.js.map +1 -0
  84. package/dist/{supervisor-accounting-DxLQ_TQe.js → supervisor-accounting-Bw4MJk-b.js} +434 -423
  85. package/dist/supervisor-accounting-Bw4MJk-b.js.map +1 -0
  86. package/dist/testing.d.ts +1 -1
  87. package/dist/testing.js +13 -13
  88. package/dist/{tool-server-Dg350Bgz.js → tool-server-DYwRbi0I.js} +3 -3
  89. package/dist/{tool-server-Dg350Bgz.js.map → tool-server-DYwRbi0I.js.map} +1 -1
  90. package/dist/{top-web-BJLnFQdr.js → top-web-B3HOAtrZ.js} +9 -7
  91. package/dist/{top-web-BJLnFQdr.js.map → top-web-B3HOAtrZ.js.map} +1 -1
  92. package/dist/tui/bin.js +3 -3
  93. package/dist/tui/index.d.ts +1 -1
  94. package/dist/tui/index.js +2 -2
  95. package/dist/{types-Jg274chm.d.ts → types-C_qbnw9N.d.ts} +1335 -1413
  96. package/dist/{util-C_cdPNC4.js → util-fcckrkKp.js} +39 -113
  97. package/dist/util-fcckrkKp.js.map +1 -0
  98. package/dist/{workspace-streams-B7yNMahl.js → workspace-streams-DA9R3j-p.js} +2 -2
  99. package/dist/{workspace-streams-B7yNMahl.js.map → workspace-streams-DA9R3j-p.js.map} +1 -1
  100. package/package.json +1 -1
  101. package/dist/coordination-manager-DQZ2u6L-.js.map +0 -1
  102. package/dist/coordination-map-routing-CKRNZSaV.js.map +0 -1
  103. package/dist/errors-AzSuGI23.js.map +0 -1
  104. package/dist/graph-BjQF2syl.js +0 -579
  105. package/dist/graph-BjQF2syl.js.map +0 -1
  106. package/dist/graph-registry-7X2nrreR.js.map +0 -1
  107. package/dist/improve-BolbYegO.js.map +0 -1
  108. package/dist/model-policy-JOcg3NRs.js.map +0 -1
  109. package/dist/runtime-C9F1PG2A.js.map +0 -1
  110. package/dist/search-executor-CKR9_6NR.js.map +0 -1
  111. package/dist/snapshot-Cgj2Wzi6.js.map +0 -1
  112. package/dist/structural-rollout-Dapf2aZY.js.map +0 -1
  113. package/dist/supervise-xwl2D6q3.js.map +0 -1
  114. package/dist/supervisor-accounting-DxLQ_TQe.js.map +0 -1
  115. package/dist/supervisor-gC-u_PRk.js.map +0 -1
  116. package/dist/util-C_cdPNC4.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph-tSIT_eWK.js","names":["sha256Bytes","fsConstants"],"sources":["../src/runtime/isolated-checker-outputs.ts","../src/runtime/isolated-checker.ts","../src/runtime/supervise/graph-backend.ts","../src/runtime/supervise/stored-graph-check.ts","../src/runtime/supervise/graph.ts"],"sourcesContent":["import { type BigIntStats, constants } from 'node:fs'\nimport { lstat, open } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { AgentCandidateArtifactRef, Sha256Digest } from '@tangle-network/agent-interface'\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport { sha256Bytes } from '../candidate-execution/digest'\nimport { persistCandidateOutputArtifact } from '../candidate-execution/output-artifacts'\nimport type { AgentCandidateOutputArtifactPort } from '../candidate-execution/types'\nimport { ValidationError } from '../errors'\nimport { runAbortable } from './supervise/abortable'\nimport { armDeadlineTimer } from './supervise/deadline'\n\nconst MAX_FILES = 16\nconst MAX_BYTES = 64 * 1024 * 1024\nconst MAX_TIMEOUT_MS = 120_000\n\n/** Explicit files the caller approves for retention. Never include secrets or hidden judge inputs. */\nexport interface IsolatedCheckOutputDeclaration {\n /** Exact, portable, tree-relative regular files; no directories, globs, or links. At most 16. */\n readonly paths: readonly string[]\n readonly maxFileBytes: number\n /** Maximum captured file bytes across the declaration, at most 64 MiB. */\n readonly maxTotalBytes: number\n /** Capture and verified persistence deadline, independent of command cancellation. Default 30 s; at most 120 s. */\n readonly timeoutMs?: number\n}\n\n/** Evidence uses the caller's existing artifact store; Runtime does not choose its durability policy. */\nexport interface IsolatedCheckOutputOptions extends IsolatedCheckOutputDeclaration {\n readonly executionId: string\n readonly artifacts: AgentCandidateOutputArtifactPort\n}\n\n/** Bounded codes, never exception text, command output, or secret-bearing provider diagnostics. */\nexport type IsolatedCheckOutputFailure =\n | 'missing'\n | 'unsafe-path'\n | 'size-limit'\n | 'capture-failed'\n | 'store-failed'\n | 'timeout'\n\nexport interface IsolatedCheckOutputEvidence {\n readonly executionId: string\n /** Digest of the exact input copy before the command starts, using the workspace-manifest format. */\n readonly inputDigest: Sha256Digest\n readonly status: 'retained' | 'incomplete'\n readonly files: ReadonlyArray<{\n readonly path: string\n readonly artifact: AgentCandidateArtifactRef\n }>\n readonly missing: ReadonlyArray<{\n readonly path: string\n readonly reason: IsolatedCheckOutputFailure\n }>\n /** Private recovery custody, only on incomplete retention. Do not publish filesystem coordinates. */\n readonly source?:\n | { readonly kind: 'local'; readonly path: string }\n | { readonly kind: 'sandbox'; readonly sandboxId: string; readonly state: 'stopped' }\n}\n\n/** Validate authored declarations before starting a check. The returned paths are detached and frozen. */\nexport function validateIsolatedCheckOutputs(value: unknown): IsolatedCheckOutputDeclaration {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new ValidationError('check outputs must be a declaration object')\n const item = value as Record<string, unknown>\n if (\n Object.keys(item).some(\n (key) => !['paths', 'maxFileBytes', 'maxTotalBytes', 'timeoutMs'].includes(key),\n )\n )\n throw new ValidationError('check outputs has an unknown field')\n if (!Array.isArray(item.paths) || item.paths.length < 1 || item.paths.length > MAX_FILES)\n throw new ValidationError('check outputs must name between 1 and 16 files')\n const paths: string[] = []\n for (const path of item.paths) {\n if (\n typeof path !== 'string' ||\n path.length > 512 ||\n !/^[A-Za-z0-9._-]+(?:\\/[A-Za-z0-9._-]+)*$/u.test(path) ||\n path\n .split('/')\n .some((part) => part === '.' || part === '..' || part === '.git' || part === '.sidecar') ||\n paths.some(\n (prior) => prior === path || prior.startsWith(`${path}/`) || path.startsWith(`${prior}/`),\n )\n )\n throw new ValidationError('check outputs paths must be distinct portable relative files')\n paths.push(path)\n }\n for (const key of ['maxFileBytes', 'maxTotalBytes'] as const) {\n if (\n typeof item[key] !== 'number' ||\n !Number.isSafeInteger(item[key]) ||\n item[key] < 1 ||\n item[key] > MAX_BYTES\n )\n throw new ValidationError('check output byte limits must be positive integers at most 64 MiB')\n }\n const maxFileBytes = item.maxFileBytes as number\n const maxTotalBytes = item.maxTotalBytes as number\n if (maxFileBytes > maxTotalBytes)\n throw new ValidationError('check outputs maxFileBytes must not exceed maxTotalBytes')\n if (\n item.timeoutMs !== undefined &&\n (typeof item.timeoutMs !== 'number' ||\n !Number.isSafeInteger(item.timeoutMs) ||\n item.timeoutMs < 1 ||\n item.timeoutMs > MAX_TIMEOUT_MS)\n )\n throw new ValidationError('check outputs timeoutMs must be a positive integer at most 120000')\n return Object.freeze({\n paths: Object.freeze(paths),\n maxFileBytes,\n maxTotalBytes,\n ...(item.timeoutMs === undefined ? {} : { timeoutMs: item.timeoutMs as number }),\n })\n}\n\n/** Resolve and validate trusted ports before any isolated work starts. */\nexport function prepareIsolatedCheckOutputs(\n options: IsolatedCheckOutputOptions | undefined,\n): IsolatedCheckOutputOptions | undefined {\n if (options === undefined) return undefined\n const { executionId, artifacts, ...declaration } = options\n const validated = validateIsolatedCheckOutputs(declaration)\n if (\n typeof executionId !== 'string' ||\n executionId.trim() === '' ||\n executionId.length > 200 ||\n /\\p{Cc}/u.test(executionId)\n )\n throw new ValidationError('check outputs executionId must be a nonempty bounded identifier')\n if (typeof artifacts?.put !== 'function' || typeof artifacts?.read !== 'function')\n throw new ValidationError('check outputs requires a readable output artifact port')\n return Object.freeze({ ...validated, executionId, artifacts })\n}\n\nclass OutputCaptureError extends Error {\n constructor(readonly reason: IsolatedCheckOutputFailure) {\n super(reason)\n }\n}\n\ntype ReadOutput = (path: string, maxBytes: number, signal: AbortSignal) => Promise<Uint8Array>\n\n/** Capture runs after command settlement, even on command failure or cancellation. There are no retries. */\nexport async function retainIsolatedCheckOutputs(\n options: IsolatedCheckOutputOptions,\n inputDigest: Sha256Digest,\n read: ReadOutput,\n): Promise<IsolatedCheckOutputEvidence> {\n const controller = new AbortController()\n const clearTimer = armDeadlineTimer(options.timeoutMs ?? 30_000, () => controller.abort(), true)\n const files: Array<{ path: string; artifact: AgentCandidateArtifactRef }> = []\n const missing: Array<{ path: string; reason: IsolatedCheckOutputFailure }> = []\n let totalBytes = 0\n try {\n for (const path of options.paths) {\n let phase: 'capture-failed' | 'store-failed' = 'capture-failed'\n try {\n const bytes = await runAbortable(\n () =>\n read(\n path,\n Math.min(options.maxFileBytes, options.maxTotalBytes - totalBytes),\n controller.signal,\n ),\n controller.signal,\n 'output capture deadline exceeded',\n )\n totalBytes += bytes.byteLength\n phase = 'store-failed'\n const artifact = await runAbortable(\n () =>\n persistCandidateOutputArtifact(options.artifacts, {\n executionId: options.executionId,\n purpose: 'grader-evidence',\n bytes,\n signal: controller.signal,\n }),\n controller.signal,\n 'output persistence deadline exceeded',\n )\n files.push({ path, artifact })\n } catch (error) {\n missing.push({\n path,\n reason: controller.signal.aborted\n ? 'timeout'\n : error instanceof OutputCaptureError\n ? error.reason\n : phase,\n })\n }\n }\n } finally {\n clearTimer()\n }\n return Object.freeze({\n executionId: options.executionId,\n inputDigest,\n status: missing.length === 0 ? 'retained' : 'incomplete',\n files: Object.freeze(files.map((file) => Object.freeze(file))),\n missing: Object.freeze(missing.map((file) => Object.freeze(file))),\n })\n}\n\n/** The local namespace has exited; the trusted host must keep its private copy stable. */\nexport function localCheckOutputReader(root: string): ReadOutput {\n return async (path, maxBytes, signal) => {\n try {\n const rootInfo = await lstat(root)\n if (!rootInfo.isDirectory() || rootInfo.isSymbolicLink())\n throw new OutputCaptureError('unsafe-path')\n let current = root\n const parts = path.split('/')\n let expected: BigIntStats | undefined\n for (let index = 0; index < parts.length; index++) {\n current = join(current, parts[index]!)\n const info = await lstat(current, { bigint: true })\n if (\n info.isSymbolicLink() ||\n (index < parts.length - 1 ? !info.isDirectory() : !info.isFile() || info.nlink !== 1n)\n )\n throw new OutputCaptureError('unsafe-path')\n expected = info\n }\n signal.throwIfAborted()\n const file = await open(\n current,\n constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,\n )\n try {\n const before = await file.stat({ bigint: true })\n if (\n !before.isFile() ||\n before.nlink !== 1n ||\n before.dev !== expected?.dev ||\n before.ino !== expected?.ino\n )\n throw new OutputCaptureError('unsafe-path')\n if (before.size > BigInt(maxBytes)) throw new OutputCaptureError('size-limit')\n const chunks: Buffer[] = []\n let total = 0\n const buffer = Buffer.allocUnsafe(Math.min(65_536, maxBytes + 1))\n while (true) {\n signal.throwIfAborted()\n const { bytesRead } = await file.read(\n buffer,\n 0,\n Math.min(buffer.length, maxBytes - total + 1),\n null,\n )\n if (bytesRead === 0) break\n total += bytesRead\n if (total > maxBytes) throw new OutputCaptureError('size-limit')\n chunks.push(Buffer.from(buffer.subarray(0, bytesRead)))\n }\n const after = await file.stat({ bigint: true })\n if (\n before.size !== BigInt(total) ||\n before.size !== after.size ||\n before.mtimeNs !== after.mtimeNs ||\n before.ctimeNs !== after.ctimeNs ||\n after.nlink !== 1n\n )\n throw new OutputCaptureError('capture-failed')\n return Buffer.concat(chunks, total)\n } finally {\n await file.close()\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException)?.code === 'ENOENT')\n throw new OutputCaptureError('missing')\n if (['ELOOP', 'ENOTDIR'].includes((error as NodeJS.ErrnoException)?.code ?? ''))\n throw new OutputCaptureError('unsafe-path')\n throw error\n }\n }\n}\n\n/** Preserve a whole box only after its native lifecycle owner confirms stopped state. */\nexport async function stopCheckBoxForRecovery(box: SandboxInstance): Promise<boolean> {\n const controller = new AbortController()\n const clearTimer = armDeadlineTimer(30_000, () => controller.abort(), true)\n try {\n await runAbortable(\n () => box.stop({ wait: true, signal: controller.signal }),\n controller.signal,\n 'check recovery stop deadline exceeded',\n )\n return true\n } catch {\n return false\n } finally {\n clearTimer()\n }\n}\n\n/** Whether kill and process exit were confirmed; recovery custody still needs a whole-box stop. */\nexport async function stopCheckProcess(\n child: Awaited<ReturnType<SandboxInstance['process']['spawnExact']>>,\n): Promise<boolean> {\n const controller = new AbortController()\n const clearTimer = armDeadlineTimer(5_000, () => controller.abort(), true)\n try {\n await runAbortable(\n async () => {\n await child.kill('SIGKILL', { tree: true })\n await child.wait()\n },\n controller.signal,\n 'check process stop deadline exceeded',\n )\n return true\n } catch {\n // The caller stops or deletes the entire box before releasing its custody.\n return false\n } finally {\n clearTimer()\n }\n}\n\n// Fixed code, argv-only inputs, no shell. Directory descriptors prevent a swapped ancestor symlink\n// from redirecting a read. The regular file descriptor is bounded and checked again after reading.\nexport const isolatedCheckOutputCaptureProgram = `import base64, errno, hashlib, json, os, stat, sys\nfds=[]\ndef fail(reason):\n print(json.dumps({'error':reason})); sys.exit(0)\ntry:\n root,path,limit=sys.argv[1],sys.argv[2],int(sys.argv[3])\n directory=os.open(root,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW); fds.append(directory)\n parts=path.split('/')\n for part in parts[:-1]:\n directory=os.open(part,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=directory); fds.append(directory)\n before=os.stat(parts[-1],dir_fd=directory,follow_symlinks=False)\n if not stat.S_ISREG(before.st_mode) or before.st_nlink!=1: fail('unsafe-path')\n fd=os.open(parts[-1],os.O_RDONLY|os.O_NOFOLLOW|os.O_NONBLOCK,dir_fd=directory); fds.append(fd)\n opened=os.fstat(fd)\n if not stat.S_ISREG(opened.st_mode) or opened.st_nlink!=1 or (before.st_dev,before.st_ino)!=(opened.st_dev,opened.st_ino): fail('unsafe-path')\n if opened.st_size>limit: fail('size-limit')\n chunks=[]; total=0\n while True:\n chunk=os.read(fd,min(1048576,limit-total+1))\n if not chunk: break\n total+=len(chunk)\n if total>limit: fail('size-limit')\n chunks.append(chunk)\n after=os.fstat(fd)\n if (opened.st_size,opened.st_mtime_ns,opened.st_ctime_ns,opened.st_nlink)!=(after.st_size,after.st_mtime_ns,after.st_ctime_ns,after.st_nlink) or total!=opened.st_size: fail('capture-failed')\n data=b''.join(chunks)\n print(json.dumps({'content':base64.b64encode(data).decode('ascii'),'sha256':'sha256:'+hashlib.sha256(data).hexdigest()}))\nexcept OSError as error:\n fail('missing' if error.errno==errno.ENOENT else 'unsafe-path' if error.errno in (errno.ELOOP,errno.ENOTDIR) else 'capture-failed')\nfinally:\n for fd in reversed(fds): os.close(fd)\n`\n\n/** A box with declared outputs needs python3; missing capture tooling fails closed and keeps custody. */\nexport function boxCheckOutputReader(\n box: SandboxInstance,\n root: string,\n timeoutMs: number,\n): ReadOutput {\n return async (path, maxBytes, signal) => {\n const child = await box.process.spawnExact(\n '/usr/bin/python3',\n ['-I', '-S', '-c', isolatedCheckOutputCaptureProgram, root, path, String(maxBytes)],\n {\n env: { PATH: '/usr/bin:/bin', LANG: 'C' },\n inheritEnv: false,\n timeoutMs,\n },\n )\n let stopping: Promise<boolean> | undefined\n const stop = () => {\n stopping ??= stopCheckProcess(child)\n }\n signal.addEventListener('abort', stop, { once: true })\n if (signal.aborted) stop()\n const chunks: string[] = []\n const limit = Math.ceil(maxBytes / 3) * 4 + 2_048\n let length = 0\n let overflow = false\n const collect = async (stream: AsyncIterable<string>, keep: boolean) => {\n for await (const text of stream) {\n length += Buffer.byteLength(text)\n if (length > limit) {\n overflow = true\n stop()\n } else if (keep) chunks.push(text)\n }\n }\n try {\n await Promise.all([collect(child.stdout(), true), collect(child.stderr(), false)])\n if (overflow || (await child.wait()) !== 0) throw new OutputCaptureError('capture-failed')\n signal.throwIfAborted()\n const value = JSON.parse(chunks.join('')) as Record<string, unknown>\n if (\n value.error === 'missing' ||\n value.error === 'unsafe-path' ||\n value.error === 'size-limit' ||\n value.error === 'capture-failed'\n )\n throw new OutputCaptureError(value.error)\n if (typeof value.content !== 'string' || typeof value.sha256 !== 'string')\n throw new OutputCaptureError('capture-failed')\n const bytes = Buffer.from(value.content, 'base64')\n if (bytes.byteLength > maxBytes) throw new OutputCaptureError('size-limit')\n if (sha256Bytes(bytes) !== value.sha256) throw new OutputCaptureError('capture-failed')\n return bytes\n } catch (error) {\n stop()\n throw error\n } finally {\n signal.removeEventListener('abort', stop)\n await stopping\n }\n }\n}\n","import { execFile, spawn } 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 boxCheckOutputReader,\n type IsolatedCheckOutputEvidence,\n type IsolatedCheckOutputOptions,\n localCheckOutputReader,\n prepareIsolatedCheckOutputs,\n retainIsolatedCheckOutputs,\n stopCheckBoxForRecovery,\n stopCheckProcess,\n} from './isolated-checker-outputs'\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}\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 /** 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\nexport type IsolatedCheckResult =\n | {\n succeeded: true\n value: { stdout: string; stderr: string }\n box?: IsolatedCheckBoxEvidence\n outputs?: IsolatedCheckOutputEvidence\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 }\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.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 ? 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 execute(args, timeoutMs, maxOutputBytes, options.signal)\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 }\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 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/** The box's process supervisor prefixes this to stderr when it cannot start the executable. */\nconst BOX_EXEC_FAILURE = 'process-supervisor: exec failed'\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.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 }\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 = ['.', '-type', 'f', '-exec', 'sha256sum', '{}', '+']\n const child = await box.process.spawnExact('find', hash, {\n cwd: BOX_TREE,\n env: { PATH: '/usr/bin:/bin', LANG: 'C' },\n inheritEnv: false,\n timeoutMs: BOX_SETUP_SECONDS * 1_000,\n })\n let listing = ''\n for await (const text of child.stdout()) listing += text\n if ((await child.wait()) !== 0) throw new Error('Check box could not hash the tree it received')\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' | 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 const capture = async (stream: AsyncIterable<string>, target: Buffer[]) => {\n for await (const text of stream) {\n if (deadline.signal.aborted) break\n const chunk = Buffer.from(text)\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 }\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 Promise.all([capture(running.stdout(), stdout), capture(running.stderr(), stderr)])\n const exitCode = await running.wait()\n const exitSignal = (await running.status()).exitSignal\n return { exitCode, exitSignal }\n },\n deadline.signal,\n 'Check interrupted',\n )\n } catch (error) {\n if (child) stopping ??= stopCheckProcess(child)\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,\n })\n if (failure)\n return finish({ succeeded: false, reason: failure, diagnostic: err || failure, ...evidence })\n if (exitCode === 127 && err.startsWith(BOX_EXEC_FAILURE))\n return finish({ succeeded: false, reason: 'refused', diagnostic: err, ...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\nfunction execute(\n args: string[],\n timeoutMs: number,\n limit: number,\n signal?: AbortSignal,\n): Promise<IsolatedCheckResult> {\n return new Promise((done) => {\n const child = spawn('/usr/bin/bwrap', ['--json-status-fd', '3', ...args], {\n env: {},\n stdio: ['ignore', 'pipe', 'pipe', 'pipe'],\n detached: true,\n })\n const stdout: Buffer[] = []\n const stderr: Buffer[] = []\n let bytes = 0\n let status = ''\n let failure: 'timeout' | 'cancelled' | 'output-limit' | undefined\n const stop = (reason: typeof failure) => {\n failure ??= reason\n if (child.pid) {\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 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 })\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', (code) => {\n clearTimer()\n signal?.removeEventListener('abort', cancel)\n const out = Buffer.concat(stdout).toString()\n const err = Buffer.concat(stderr).toString()\n const evidence = { stdout: out, stderr: err, exitCode: code }\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({ succeeded: false, reason: failure, diagnostic: err || failure, ...evidence })\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 } })\n })\n })\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 { mkdirSync, realpathSync } from 'node:fs'\nimport { cp, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { isAbsolute, join, relative } from 'node:path'\nimport type { SandboxResources } from '@tangle-network/sandbox'\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 { runIsolatedCheck } from '../isolated-checker'\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 /** 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}\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}\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}\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 const receipt = value as CommandCheckReceipt\n return (\n receipt.key === receiptKey(receipt) &&\n receipt.valid === (receipt.exitCode === 0 && receipt.nativeValid)\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(directory: string, task: unknown): 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}\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): Promise<{ exitCode: number | null; stdout: string; output: string }> {\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: { ...secrets, GRAPH_EVIDENCE: evidence },\n })\n const timedOut = result.timedOut ? `\\n[check timed out after ${timeoutMs} ms]` : ''\n return {\n exitCode: result.timedOut ? null : result.exitCode,\n stdout: result.stdout,\n output: result.stdout + result.stderr + timedOut,\n }\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): Promise<{ exitCode: number | null; stdout: string; output: string }> {\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\"; export GRAPH_EVIDENCE; ${check.command}`,\n ],\n timeoutMs: check.timeoutMs ?? CHECK_TIMEOUT_MS,\n maxOutputBytes: 16 * CHECK_OUTPUT_LIMIT,\n env: secrets,\n signal,\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.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 }\n const stdout = result.stdout ?? ''\n const output = stdout + (result.stderr ?? '')\n if (result.reason === 'failed' && typeof result.exitCode === 'number')\n return { exitCode: result.exitCode, stdout, output }\n if (result.reason === 'timeout')\n return { exitCode: null, stdout, output: `${output}\\n[check timed out]` }\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 Object.entries(secrets)\n .sort(([, a], [, b]) => b.length - a.length)\n .reduce((out, [name, value]) => out.replaceAll(value, `[redacted:${name}]`), text)\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 }\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 }\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({ runId, node: id, checkDigest, at: spawn?.assignmentId })\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 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 let ran: Awaited<ReturnType<typeof runLocalCheck>>\n try {\n await writeEvidence(evidence, task)\n ran = local\n ? await runLocalCheck(check, local.cwd, evidence, signal, secrets)\n : await runBoxCheck(\n check,\n id,\n placement as GraphCheckPlacement,\n evidence,\n signal,\n secrets,\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: true,\n valid: ran.exitCode === 0,\n ...(json === undefined ? {} : { json }),\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 { 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 {\n bindGraphCheckNodes,\n bindGraphCommand,\n type GraphCheckNode,\n type GraphCheckPlacement,\n type GraphCommandCheck,\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 '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] 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}\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 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 })\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 task =\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\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, 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C,CAAC,SAAS,IAClD,EAAE,qBAAqB,QAAQ,oBAAoB,IACnD,CAAC;GAEL,GAAI,SAAS,KAAA,IACT,CAAC,IACD;IACE,WAAW,YAAY,SAAS;IAChC,GAAI,cAAc,EAAE,WAAW;IAC/B,GAAI,KAAK,cAAc,EACrB,YAAY,qBAAqB,KAAK,YAAY,SAAS,KAAK,EAClE;IACA,WAAW,KAAK;IAChB,MAAM;KAAE,YAAY;KAAG,GAAG,KAAK;IAAK;GACtC;GACJ;EACF;EAEA,MAAM,aACJ,cAAc,KAAA,IACV,MAAM,UAAU,aAAa,MAAM,gBAAgB,IACnD,MAAM,uBAAuB,aAAa,MAAM;GAAE,GAAG;GAAkB,OAAO;EAAU,CAAC;EAE/F,MAAM,EAAE,QAAQ,gBAAgB,uBAAuB,MAAM,QAAQ,OAAO;EAC5E,MAAM,YAAY,MAAM,SAAS,UAAU;EAC3C,IAAI,WAAW,SAAS,YACtB,MAAM,IAAI,gBAAgB,UAAU,UAAU,QAAQ,UAAU;EAElE,MAAM,SAAS,WAAW,UAAU;EACpC,MAAM,UAAU,WAAW;EAK3B,MAAM,iBACJ,OAAO,SAAS,gBACf,OAAO,WAAW,aACjB,OAAO,WAAW,eAClB,OAAO,WAAW,sBAClB,OAAO,WAAW;EACtB,IAAI,OAAO,SAAS,YAAY,CAAC,kBAAkB,mBAAmB,SAAS,GAG7E,MAAM,IAAI,kBAAkB,oBAAoB,QAAQ,MAAM;EAEhE,OAAO;GAAE;GAAQ;GAAQ;GAAgB;GAAO,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;EAAG;CAClF;CAEA,OAAO,MAAM;AACf"}
@@ -1,15 +1,15 @@
1
- import { $r as linkAbort, ei as runAbortable } from "./supervisor-accounting-DxLQ_TQe.js";
2
- import { i as ConfigError } from "./errors-AzSuGI23.js";
3
- import { F as collectAgentTurn, I as streamAgentTurn } from "./structural-rollout-Dapf2aZY.js";
4
- import { I as armDeadlineTimer } from "./util-C_cdPNC4.js";
5
- import { n as detachedSnapshot } from "./snapshot-Cgj2Wzi6.js";
6
- import { Bt as runSettledCommand, C as createExecutor, Wt as terminateProcessTreeAndConfirm } from "./supervisor-gC-u_PRk.js";
7
- import { a as concreteProfileModel, t as assertExecutableAgentProfile } from "./model-policy-JOcg3NRs.js";
1
+ import { oi as linkAbort, si as runAbortable } from "./supervisor-accounting-Bw4MJk-b.js";
2
+ import { i as ConfigError } from "./errors-DG8yufqX.js";
3
+ import { F as collectAgentTurn, I as streamAgentTurn } from "./structural-rollout-C1xxoWcN.js";
4
+ import { I as armDeadlineTimer } from "./util-fcckrkKp.js";
5
+ import { n as detachedSnapshot } from "./snapshot-BKI_w3JD.js";
6
+ import { C as createExecutor, Lt as terminateProcessTreeAndConfirm, Nt as runSettledCommand } from "./supervisor-Dpeu7rnZ.js";
7
+ import { a as concreteProfileModel, t as assertExecutableAgentProfile } from "./model-policy-yxOrDTTj.js";
8
8
  import { l as sha256 } from "./jsonl-file-DsxVI0E_.js";
9
- import { L as immutableCandidateValue, N as canonicalCandidateDigest$1, z as sha256Bytes$1 } from "./workspace-streams-B7yNMahl.js";
9
+ import { L as immutableCandidateValue, N as canonicalCandidateDigest$1, z as sha256Bytes$1 } from "./workspace-streams-DA9R3j-p.js";
10
10
  import { i as syncDurableDirectory, r as publishExclusiveDurableFile } from "./durable-file-DstVeHcj.js";
11
- import { C as serializeRolloutPolicy, S as normalizeRolloutPolicy, w as structuralRolloutPolicyFromProfile, x as applyRolloutPolicyToProfile } from "./activation-Ba9IAgQ3.js";
12
- import { a as reconcileInterruptedSearchCalls, b as improveSearchCost, c as searchExecutor, d as taggedLedger, i as isSearchEnvironmentFault, n as assertSearchLanes, s as searchCallTags, v as decideClosedSearch } from "./search-executor-CKR9_6NR.js";
11
+ import { C as serializeRolloutPolicy, S as normalizeRolloutPolicy, w as structuralRolloutPolicyFromProfile, x as applyRolloutPolicyToProfile } from "./activation-Ce4zUcu8.js";
12
+ import { a as reconcileInterruptedSearchCalls, b as improveSearchCost, c as searchExecutor, d as taggedLedger, i as isSearchEnvironmentFault, n as assertSearchLanes, s as searchCallTags, v as decideClosedSearch } from "./search-executor-B9L8W_1O.js";
13
13
  import { agentProfileEnvironmentSchema, agentProfileSchema, agentProfileTrainingSchema, agentTrainingDatasetIdentitySchema, agentTrainingParametersSchema, agentTrainingReceiptSchema, agentTrainingTaskKey, agentTrainingTaskSchema, applyAgentProfileDiff, canonicalAgentProfileDigest, canonicalCandidateBytes, diffAgentProfiles, sha256DigestSchema, snapshotAgentProfile, trainedModelIdForArtifact } from "@tangle-network/agent-interface";
14
14
  import { canonicalJson, makeProposalFinding } from "@tangle-network/agent-eval";
15
15
  import { redact } from "@tangle-network/agent-eval/traces";
@@ -246,43 +246,14 @@ function worktreeChangedPaths(worktreePath) {
246
246
  }
247
247
  // src/improvement/agentic-generator.ts
248
248
  /**
249
- *
250
- * `agenticGenerator` — the full-agentic `CandidateGenerator`. It runs a real
251
- * authored profile inside the candidate worktree the driver already created,
252
- * letting the agent read the codebase + the research proposal findings and
253
- * make the change in place. The driver then commits the worktree into a
254
- * `CodeSurface`.
255
- *
256
- * Every paid shot enters Runtime through `createExecutor` + `streamAgentTurn`.
257
- * The caller supplies the exact `AgentProfile` and a worktree-aware executor
258
- * placement; Runtime validates and records the profile that actually ran. Two
259
- * built-in placements edit the supplied worktree itself: `{ backend:'cli-in-place',
260
- * workspacePath: worktreePath }` runs a local coding CLI (claude-code / codex /
261
- * opencode / pi) in that directory, and `{ backend:'bridge', cwd: worktreePath }`
262
- * runs a cli-bridge session there. `cli-worktree` is NOT one of them — it cuts a
263
- * worktree of its own, so every shot would read as an empty tree.
264
- *
265
- * `maxShots` is the DEPTH dial — a multi-shot verify-in-session loop, NOT the
266
- * kernel `runAgentRounds`. Each shot runs one full harness session in the (persistent)
267
- * worktree; between shots the loop refines based on what the last shot produced:
268
- * - empty tree → "you changed nothing, make the edits" → retry
269
- * - dirty + `verify` fails → feed the verifier's failure into the next shot
270
- * (the worktree persists, so the harness RESUMES atop its own failing
271
- * edits with the error in hand — no session-specific retry path needed)
272
- * - dirty + `verify` ok (or no verifier configured) → return the candidate
273
- * - dirty + `verify` ok + `keepGoing` → bank the tree and spend the next shot
274
- * A candidate that never verifies within `maxShots` is discarded (`applied:
275
- * false`), never shipped — if you configured a verifier, a non-passing tree is
276
- * not a candidate. With no verifier, the first dirty shot is the candidate.
277
- *
278
- * BEST-OF-N is the `keepGoing` path, and the loop owns it end to end. A
279
- * verifier that passes a tree and asks for another shot has its tree
280
- * snapshotted as a Git tree object; when the budget ends, the highest-`score`
281
- * tree is RESTORED into the worktree and returned as the candidate. So the
282
- * caller ranks and the loop moves the bytes — a caller never has to write a
283
- * passing tree back itself. The budget ends on the last shot, or earlier on a
284
- * `keepGoing`-less pass, and a last shot that broke or reverted the change does
285
- * not cost the candidate the verified tree an earlier shot produced.
249
+ * `agenticGenerator` runs an authored profile in the driver's candidate worktree, then the driver
250
+ * commits that tree to a `CodeSurface`. Shots enter through `createExecutor` and `streamAgentTurn`.
251
+ * Placements that edit this worktree are `cli-in-place` (`workspacePath`) and `bridge` (`cwd`).
252
+ * `cli-worktree` cuts another worktree and every shot looks empty. `maxShots` is a verify loop, not
253
+ * `runAgentRounds`: an empty tree is retried, a failed `verify` is fed into the next shot on the
254
+ * same tree, a pass returns, and `keepGoing` snapshots the Git tree and restores the highest score
255
+ * when the budget ends. A verifier that never passes discards the candidate. With no verifier, the
256
+ * first dirty shot is the candidate.
286
257
  *
287
258
  * @stable
288
259
  */
@@ -3036,4 +3007,4 @@ async function improve(profileOrCode, opts) {
3036
3007
  }
3037
3008
  export { assertProfileTrainingIsHeldOut as a, withMethodRuntimeControls as c, commandVerifier as d, addRuntimeUsage as f, assertCandidateValidator as i, rethrowAfterCleanup as l, isUsageAmount as m, createCommandProfileTrainer as n, parseExecutionRef as o, createRuntimeUsageTotals as p, searchMethod as r, privateValuePaths as s, improve as t, agenticGenerator as u };
3038
3009
 
3039
- //# sourceMappingURL=improve-BolbYegO.js.map
3010
+ //# sourceMappingURL=improve-H08hiIw9.js.map