@tangle-network/agent-runtime 10.0.19 → 10.0.20

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 (93) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/{activation-DLnZJab0.js → activation-5TrUzeFd.js} +2 -2
  3. package/dist/{activation-DLnZJab0.js.map → activation-5TrUzeFd.js.map} +1 -1
  4. package/dist/{activation-BudDVuT6.d.ts → activation-B0arteLE.d.ts} +2 -2
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +4 -4
  7. package/dist/{delegate-9b8qGlXp.js → delegate-DnW85VY0.js} +2 -2
  8. package/dist/{delegate-9b8qGlXp.js.map → delegate-DnW85VY0.js.map} +1 -1
  9. package/dist/{driver-control-acknowledgers-b5MsXxR5.js → driver-control-acknowledgers-vgmZqgZ-.js} +8 -8
  10. package/dist/{driver-control-acknowledgers-b5MsXxR5.js.map → driver-control-acknowledgers-vgmZqgZ-.js.map} +1 -1
  11. package/dist/durable-writer-thread.js +4 -4
  12. package/dist/durable.d.ts +1 -1
  13. package/dist/durable.js +13 -14
  14. package/dist/durable.js.map +1 -1
  15. package/dist/{graph--n31XKWJ.js → graph-DHNPE7kw.js} +8 -8
  16. package/dist/{graph--n31XKWJ.js.map → graph-DHNPE7kw.js.map} +1 -1
  17. package/dist/{graph-registry-aMRd94PD.js → graph-registry-DI8o9iCB.js} +1 -1
  18. package/dist/{graph-registry-SgsCxCTZ.js → graph-registry-qyaNDATw.js} +2 -3
  19. package/dist/{graph-registry-SgsCxCTZ.js.map → graph-registry-qyaNDATw.js.map} +1 -1
  20. package/dist/{improve-sIZhpXqE.js → improve-BLFqeD3X.js} +6 -6
  21. package/dist/{improve-sIZhpXqE.js.map → improve-BLFqeD3X.js.map} +1 -1
  22. package/dist/index.d.ts +3 -3
  23. package/dist/index.js +10 -10
  24. package/dist/intelligence.d.ts +2 -2
  25. package/dist/intelligence.js +4 -4
  26. package/dist/{continuation-CDdjAkpk.js → jsonl-file-B2ESMrTh.js} +396 -4
  27. package/dist/jsonl-file-B2ESMrTh.js.map +1 -0
  28. package/dist/kernel.d.ts +1 -1
  29. package/dist/kernel.js +17 -18
  30. package/dist/{loop-runner-Bn7lFuQZ.d.ts → loop-runner-BFC781pC.d.ts} +2 -2
  31. package/dist/{loop-runner-Dt7I2oMa.js → loop-runner-CITvo-q1.js} +2 -2
  32. package/dist/{loop-runner-Dt7I2oMa.js.map → loop-runner-CITvo-q1.js.map} +1 -1
  33. package/dist/loop-runner-bin.d.ts +1 -1
  34. package/dist/loop-runner-bin.js +1 -1
  35. package/dist/mcp/bin.js +3 -3
  36. package/dist/mcp/index.d.ts +1 -1
  37. package/dist/mcp/index.js +6 -6
  38. package/dist/mcp/memory-bin.js +1 -1
  39. package/dist/profiles.d.ts +1 -1
  40. package/dist/{provision-supervisor-DfDAdtqb.js → provision-supervisor-CyUbiMz8.js} +6 -6
  41. package/dist/{provision-supervisor-DfDAdtqb.js.map → provision-supervisor-CyUbiMz8.js.map} +1 -1
  42. package/dist/{result-blob-store-Dke805sV.js → result-blob-store-CJjp44Mz.js} +3 -3
  43. package/dist/{result-blob-store-Dke805sV.js.map → result-blob-store-CJjp44Mz.js.map} +1 -1
  44. package/dist/{run-cancellation-B0SgcidY.js → run-cancellation-BNBmsY3a.js} +2 -2
  45. package/dist/{run-cancellation-B0SgcidY.js.map → run-cancellation-BNBmsY3a.js.map} +1 -1
  46. package/dist/{run-lock-BOg7BaXF.js → run-lock-Dcr79Wql.js} +2 -2
  47. package/dist/{run-lock-BOg7BaXF.js.map → run-lock-Dcr79Wql.js.map} +1 -1
  48. package/dist/{run-reopen-B7TN2aQQ.js → run-reopen-Cr2SHmYa.js} +6 -6
  49. package/dist/{run-reopen-B7TN2aQQ.js.map → run-reopen-Cr2SHmYa.js.map} +1 -1
  50. package/dist/{run-state-BNBUy2uK.js → run-state-AYXAe_lX.js} +7 -7
  51. package/dist/{run-state-BNBUy2uK.js.map → run-state-AYXAe_lX.js.map} +1 -1
  52. package/dist/{runtime-DXeWY00j.js → runtime-D-FpUoQg.js} +19 -20
  53. package/dist/{runtime-DXeWY00j.js.map → runtime-D-FpUoQg.js.map} +1 -1
  54. package/dist/{search-executor-BoQHI2Tz.js → search-executor-BHfb4p6C.js} +4 -4
  55. package/dist/{search-executor-BoQHI2Tz.js.map → search-executor-BHfb4p6C.js.map} +1 -1
  56. package/dist/{server-Xkgobp5y.js → server-CAXzZHVz.js} +4 -4
  57. package/dist/{server-Xkgobp5y.js.map → server-CAXzZHVz.js.map} +1 -1
  58. package/dist/{settle-record-B5OpVDnC.js → settle-record-BlIw2MU1.js} +3 -3
  59. package/dist/{settle-record-B5OpVDnC.js.map → settle-record-BlIw2MU1.js.map} +1 -1
  60. package/dist/{structural-rollout-BSF5tzUm.js → structural-rollout-BVuf5hFl.js} +4 -4
  61. package/dist/{structural-rollout-BSF5tzUm.js.map → structural-rollout-BVuf5hFl.js.map} +1 -1
  62. package/dist/{supervise-Drc1Pj1d.js → supervise-Ci8wiyla.js} +13 -13
  63. package/dist/supervise-Ci8wiyla.js.map +1 -0
  64. package/dist/{supervise-identity-Cz-Hzg9s.js → supervise-identity-CtxWEk1I.js} +3 -3
  65. package/dist/{supervise-identity-Cz-Hzg9s.js.map → supervise-identity-CtxWEk1I.js.map} +1 -1
  66. package/dist/{supervision-discovery-DdRd1lsz.js → supervision-discovery-DKxqbnHf.js} +4 -4
  67. package/dist/{supervision-discovery-DdRd1lsz.js.map → supervision-discovery-DKxqbnHf.js.map} +1 -1
  68. package/dist/{supervisor-CwUD7dsm.js → supervisor-KcnH2hC4.js} +10 -592
  69. package/dist/supervisor-KcnH2hC4.js.map +1 -0
  70. package/dist/{supervisor-accounting-CPDPG8mH.js → supervisor-accounting-DlDUl58C.js} +600 -8
  71. package/dist/supervisor-accounting-DlDUl58C.js.map +1 -0
  72. package/dist/{supervisor-root-contract-Uw2q3nvG.js → supervisor-root-contract-BCbu1A4n.js} +3 -3
  73. package/dist/{supervisor-root-contract-Uw2q3nvG.js.map → supervisor-root-contract-BCbu1A4n.js.map} +1 -1
  74. package/dist/testing.d.ts +1 -1
  75. package/dist/testing.js +11 -11
  76. package/dist/{failure-cause-C96rzF-d.js → tool-server-n4XYpCok.js} +181 -2
  77. package/dist/tool-server-n4XYpCok.js.map +1 -0
  78. package/dist/{top-web-5ThvdyD0.js → top-web-B-sHmI3g.js} +8 -8
  79. package/dist/{top-web-5ThvdyD0.js.map → top-web-B-sHmI3g.js.map} +1 -1
  80. package/dist/tui/bin.js +3 -3
  81. package/dist/tui/index.d.ts +1 -1
  82. package/dist/tui/index.js +2 -2
  83. package/dist/{types-BLhsL4qy.d.ts → types-YXZL7Wxi.d.ts} +5 -3
  84. package/package.json +1 -1
  85. package/dist/continuation-CDdjAkpk.js.map +0 -1
  86. package/dist/failure-cause-C96rzF-d.js.map +0 -1
  87. package/dist/jsonl-file-B8xfYz9M.js +0 -397
  88. package/dist/jsonl-file-B8xfYz9M.js.map +0 -1
  89. package/dist/supervise-Drc1Pj1d.js.map +0 -1
  90. package/dist/supervisor-CwUD7dsm.js.map +0 -1
  91. package/dist/supervisor-accounting-CPDPG8mH.js.map +0 -1
  92. package/dist/tool-server-BhsyVDj2.js +0 -174
  93. package/dist/tool-server-BhsyVDj2.js.map +0 -1
@@ -1 +1 @@
1
- export { s as listGraphRuns, c as loadGraph } from "./graph-registry-SgsCxCTZ.js";
1
+ export { s as listGraphRuns, c as loadGraph } from "./graph-registry-qyaNDATw.js";
@@ -1,6 +1,5 @@
1
- import { _ as runAbortable, a as readCommittedJsonFile, c as withJsonlFileLock, f as sha256, s as upsertCommittedJsonLine, t as isNoEntError } from "./jsonl-file-B8xfYz9M.js";
1
+ import { a as readCommittedJsonFile, c as withJsonlFileLock, p as admitContinuationPolicy, s as upsertCommittedJsonLine, t as isNoEntError, w as runAbortable, y as sha256 } from "./jsonl-file-B2ESMrTh.js";
2
2
  import { m as ValidationError } from "./errors-DG8yufqX.js";
3
- import { n as admitContinuationPolicy } from "./continuation-CDdjAkpk.js";
4
3
  import { t as detachedFrozen } from "./snapshot-BKLziJ5K.js";
5
4
  import { u as writeAtomicDurableFile } from "./durable-file-pao7FijS.js";
6
5
  import { n as resolveJsonPointer } from "./coordination-map-routing-DovTCk1Y.js";
@@ -985,4 +984,4 @@ async function storedGraphDigests(reg) {
985
984
  }
986
985
  export { portableContinuationPolicySchema as A, boxCheckOutputReader as C, stopCheckBoxForRecovery as D, retainIsolatedCheckOutputs as E, stopCheckProcess as O, graphRouteWhenSchema as S, prepareIsolatedCheckOutputs as T, compileGraphParameters as _, graphRegistry as a, graphFileNeedSchema as b, loadGraph as c, recordGraphRun as d, recordStoredGraphRun as f, bindGraphParameters as g, assertGraphTriggerBindings as h, graphFromStored as i, assertJsonData as j, validateIsolatedCheckOutputs as k, lookupGraph as l, taskShapeDigest as m, graphCorpusSummary as n, graphRunsFor as o, storedGraphDigests as p, graphDigest as r, listGraphRuns as s, digestOfGraph as t, pickBestGraph as u, graphTriggerBindingsSchema as v, localCheckOutputReader as w, graphFileSchema as x, graphCheckNodeSchema as y };
987
986
 
988
- //# sourceMappingURL=graph-registry-SgsCxCTZ.js.map
987
+ //# sourceMappingURL=graph-registry-qyaNDATw.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"graph-registry-SgsCxCTZ.js","names":[],"sources":["../src/json-data.ts","../src/runtime/supervise/continuation-data.ts","../src/runtime/isolated-checker-outputs.ts","../src/runtime/supervise/graph-file-schema.ts","../src/runtime/supervise/graph-parameters.ts","../src/runtime/supervise/graph-registry.ts"],"sourcesContent":["import { ValidationError } from './errors'\n\n/** Inspect descriptors instead of invoking accessors; JSON has no getters, symbols, prototypes,\n * sparse arrays, undefined, closures or cycles. Repeated non-cyclic references remain JSON data. */\nexport function assertJsonData(\n value: unknown,\n context: string,\n visiting = new Set<object>(),\n): void {\n function fail(message: string): never {\n throw new ValidationError(`${context}: ${message}`)\n }\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return\n if (typeof value === 'number' && Number.isFinite(value)) return\n if (!value || typeof value !== 'object' || visiting.has(value))\n fail('expected finite, acyclic JSON data without executable values')\n const array = Array.isArray(value)\n const prototype = Object.getPrototypeOf(value)\n if (array ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null)\n fail('expected plain JSON objects and arrays')\n visiting.add(value)\n const descriptors = Object.getOwnPropertyDescriptors(value)\n const keys = Reflect.ownKeys(descriptors)\n if (array && keys.length !== value.length + 1) fail('sparse arrays are not canonical JSON')\n for (const key of keys) {\n if (array && key === 'length') continue\n const property = typeof key === 'string' ? descriptors[key] : undefined\n if (!property || !property.enumerable || !('value' in property))\n fail('JSON data cannot contain symbols, hidden properties or accessors')\n if (array && (!/^(0|[1-9]\\d*)$/.test(key as string) || Number(key) >= value.length))\n fail('arrays may contain only indexed JSON values')\n assertJsonData(property.value, context, visiting)\n }\n visiting.delete(value)\n}\n","import { z } from 'zod'\nimport { ValidationError } from '../../errors'\nimport { assertJsonData } from '../../json-data'\nimport { admitContinuationPolicy, type ContinuationPolicy } from './continuation'\nimport { detachedFrozen } from './snapshot'\n\n/** Record-owned policy data; callbacks, panel execution and a host-computed best stay outside. */\nexport type PortableContinuationPolicy = Omit<\n ContinuationPolicy,\n 'append' | 'runPanel' | 'panel' | 'panelUsd' | 'best'\n> & { readonly panel: 'off' }\n\n/** The canonical policy admission, restricted to portable JSON rather than host callbacks. */\nexport const portableContinuationPolicySchema = z\n .unknown()\n .transform<PortableContinuationPolicy>((value, context) => {\n try {\n assertJsonData(value, 'graph continuation')\n const policy = value as unknown as PortableContinuationPolicy\n admitContinuationPolicy(policy, 'graph continuation')\n if (\n policy.panel !== 'off' ||\n 'append' in policy ||\n 'runPanel' in policy ||\n 'panelUsd' in policy\n )\n throw new ValidationError(\n 'graph continuation: portable policies cannot carry host callbacks or panel execution',\n )\n for (const [record, keys, name] of [\n [\n policy,\n ['deadline', 'maxBarren', 'profile', 'failures', 'panel', 'bar', 'reference', 'session'],\n 'policy',\n ],\n [\n policy.profile,\n [\n 'id',\n 'opening',\n 'plan',\n 'rules',\n 'headings',\n 'barRule',\n 'questions',\n 'panelModel',\n 'review',\n ],\n 'profile',\n ],\n [\n policy.profile.headings,\n ['failures', 'protected', 'changed', 'findings', 'bar', 'plan', 'rules'],\n 'headings',\n ],\n ] as const) {\n const allowed = new Set<string>(keys)\n for (const key of Object.keys(record))\n if (!allowed.has(key))\n throw new ValidationError(`graph continuation: unknown ${name} field '${key}'`)\n }\n return detachedFrozen(policy)\n } catch (error) {\n context.addIssue({\n code: 'custom',\n message: error instanceof Error ? error.message : String(error),\n })\n return z.NEVER\n }\n })\n","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 /** Trusted host redaction, applied before hashing or persistence; never authored by the check. */\n readonly redact?: (bytes: Uint8Array) => Uint8Array\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, redact, ...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 if (redact !== undefined && typeof redact !== 'function')\n throw new ValidationError('check outputs redact must be a function')\n return Object.freeze({ ...validated, executionId, artifacts, ...(redact && { redact }) })\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 captured = 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 const bytes = options.redact ? options.redact(captured) : captured\n if (\n !(bytes instanceof Uint8Array) ||\n bytes.byteLength > options.maxFileBytes ||\n Math.max(captured.byteLength, bytes.byteLength) > options.maxTotalBytes - totalBytes\n )\n throw new OutputCaptureError('size-limit')\n totalBytes += Math.max(captured.byteLength, 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 { z } from 'zod'\nimport { resolveJsonPointer } from '../../mcp/tools/coordination-map-routing'\nimport type { RouteWhen } from '../../mcp/tools/coordination-route-contracts'\nimport { validateIsolatedCheckOutputs } from '../isolated-checker-outputs'\nimport { portableContinuationPolicySchema } from './continuation-data'\n\nconst scalar = z.union([z.string(), z.number().finite(), z.boolean(), z.null()])\nconst pointer = z.string().regex(/^(?:\\/(?:[^~]|~[01])*)*$/)\nconst matchBase = { node: z.string().min(1).optional(), pointer }\nconst equals = z.strictObject({ ...matchBase, equals: scalar })\nconst oneOf = z.strictObject({ ...matchBase, in: z.array(scalar) })\nconst exists = z.strictObject({ ...matchBase, exists: z.boolean() })\nconst match = z.union([equals, oneOf, exists])\n\n/** The same data grammar as routes; no executable expressions or additional operators. */\nexport const graphRouteWhenSchema = z.union([match, z.strictObject({ all: z.array(match).min(1) })])\n\nconst parameter = z.strictObject({\n default: z.unknown().optional(),\n type: z.enum(['string', 'number', 'integer', 'boolean', 'object', 'array', 'null']).optional(),\n})\nconst command = z.strictObject({\n command: z.string().min(1),\n timeoutMs: z.number().int().positive().optional(),\n})\nconst nonnegativeInteger = z.number().int().nonnegative()\n\n/** Portable provider selection; credentials and concrete connection IDs belong to the host. */\nexport const graphFileNeedSchema = z.union([\n z.string().trim().min(1),\n z.strictObject({\n provider: z.string().trim().min(1),\n account: z.string().trim().min(1).optional(),\n capabilities: z.array(z.string().trim().min(1)).min(1),\n alias: z.string().trim().min(1).optional(),\n }),\n])\n\n/** A check node's command: no model, no seat. Params substitute as elsewhere. */\nexport const graphCheckNodeSchema = z.strictObject({\n command: z.string().min(1),\n timeoutMs: z.number().int().positive().optional(),\n environment: z.string().min(1).optional(),\n egress: z.array(z.string().min(1)).optional(),\n runtime: z.enum(['docker', 'firecracker']).optional(),\n secrets: z.array(z.string().regex(/^[A-Z_][A-Z0-9_]*$/)).optional(),\n outputs: z.unknown().transform(validateIsolatedCheckOutputs).optional(),\n resources: z\n .strictObject({\n cpuCores: z.number().positive().optional(),\n memoryMB: z.number().int().positive().optional(),\n diskGB: z.number().positive().optional(),\n })\n .optional(),\n})\n\n/** Authoring envelope. Canonical profiles and topology are validated by their existing owners. */\nexport const graphFileSchema = z.strictObject({\n digest: z.string().min(1).optional(),\n graph: z.string().min(1).optional(),\n describe: z.string().optional(),\n params: z.record(z.string().min(1), parameter).optional(),\n nodes: z\n .array(\n z.strictObject({\n id: z.string().min(1),\n profile: z.record(z.string(), z.unknown()).optional(),\n seat: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]).optional(),\n needs: z.array(graphFileNeedSchema).optional(),\n check: graphCheckNodeSchema.optional(),\n }),\n )\n .min(1),\n workspace: z.enum(['cwd', 'fresh']).optional(),\n continuation: portableContinuationPolicySchema.optional(),\n entry: z\n .array(\n z.union([z.string().min(1), z.strictObject({ node: z.string().min(1), task: z.unknown() })]),\n )\n .min(1)\n .optional(),\n edges: z.array(z.record(z.string(), z.unknown())),\n gates: z.array(z.unknown()).optional(),\n budget: z.strictObject({\n maxIterations: nonnegativeInteger.optional(),\n maxTokens: nonnegativeInteger.optional(),\n maxUsd: z.number().finite().nonnegative().optional(),\n deadlineMs: nonnegativeInteger.optional(),\n resources: z\n .record(z.string(), z.strictObject({ unit: z.string().min(1), limit: nonnegativeInteger }))\n .optional(),\n }),\n check: z\n .union([\n equals.extend({ describe: z.string().optional() }),\n oneOf.extend({ describe: z.string().optional() }),\n exists.extend({ describe: z.string().optional() }),\n z.strictObject({ describe: z.string().optional(), all: z.array(match).min(1) }),\n z.strictObject({ describe: z.string().optional(), command }),\n ])\n .optional(),\n deliverable: z\n .strictObject({\n describe: z.string().optional(),\n checkRef: z.string().min(1),\n requireSubmission: z.boolean().optional(),\n command: command.optional(),\n when: graphRouteWhenSchema.optional(),\n })\n .optional(),\n on: z.unknown().optional(),\n})\n\n/** Judge the flow's terminal-output map with RouteWhen's own JSON-pointer semantics. */\nexport function checkGraphRoute(when: RouteWhen, output: unknown): boolean {\n return ('all' in when ? when.all : [when]).every((condition) => {\n let document = output\n if (condition.node !== undefined) {\n if (!output || typeof output !== 'object' || !Object.hasOwn(output, condition.node))\n return false\n document = (output as Record<string, unknown>)[condition.node]\n }\n const selected = resolveJsonPointer(document, condition.pointer)\n if ('exists' in condition) return selected.found === condition.exists\n if (!selected.found) return false\n return 'equals' in condition\n ? selected.value === condition.equals\n : condition.in.some((value) => value === selected.value)\n })\n}\n","import { z } from 'zod'\nimport { ValidationError } from '../../errors'\n\nexport interface GraphParameterBindings {\n readonly params?: Readonly<Record<string, unknown>>\n readonly trigger?: Readonly<Record<string, unknown>>\n}\n\nconst triggerPart = z.strictObject({ trigger: z.array(z.string()).min(1) })\nconst literalPart = z.strictObject({ literal: z.string() })\n/** Explicit authored trigger slots in compiled graph data. An empty list marks fully bound data. */\nexport const graphTriggerBindingsSchema = z.array(\n z\n .strictObject({\n path: z.array(z.union([z.string(), z.number().int().nonnegative()])).min(1),\n mode: z.enum(['value', 'text']),\n parts: z.array(z.union([literalPart, triggerPart])).min(1),\n })\n .superRefine((slot, context) => {\n if (\n !slot.parts.some((part) => 'trigger' in part) ||\n (slot.mode === 'value' && (slot.parts.length !== 1 || !('trigger' in slot.parts[0]!)))\n )\n context.addIssue({\n code: 'custom',\n message: 'binding requires authored trigger parts; value slots require one trigger',\n })\n }),\n)\n/** @useDeclaredType */\nexport type GraphTriggerBinding = z.infer<typeof graphTriggerBindingsSchema>[number]\n\ntype Part = GraphTriggerBinding['parts'][number]\n\nfunction readBinding(\n namespace: keyof GraphParameterBindings,\n keys: readonly string[],\n bindings: GraphParameterBindings,\n): unknown {\n let found: unknown = bindings[namespace]\n for (const key of keys) {\n if (!found || typeof found !== 'object' || !Object.hasOwn(found, key))\n throw new ValidationError(`graph parameters: missing ${[namespace, ...keys].join('.')}`)\n found = (found as Record<string, unknown>)[key]\n }\n if (found === undefined)\n throw new ValidationError(`graph parameters: missing ${[namespace, ...keys].join('.')}`)\n return structuredClone(found)\n}\n\nfunction textValue(value: unknown, expression: string): string {\n if (value !== null && typeof value === 'object')\n throw new ValidationError(`graph parameters: ${expression} needs a whole JSON slot`)\n return String(value)\n}\n\nfunction pendingText(parts: readonly Part[]): string {\n return parts\n .map((part) => ('literal' in part ? part.literal : `\\${trigger.${part.trigger.join('.')}}`))\n .join('')\n}\n\n/** Compile authored slots once. Inserted values are data, never recursively parsed templates. */\nexport function compileGraphParameters(\n value: unknown,\n bindings: GraphParameterBindings,\n options: { readonly defer?: readonly (keyof GraphParameterBindings)[] } = {},\n): { value: unknown; triggerBindings: GraphTriggerBinding[] } {\n const visiting = new Set<object>()\n const triggerBindings: GraphTriggerBinding[] = []\n const bind = (item: unknown, path: Array<string | number>): unknown => {\n if (typeof item === 'string') {\n if (item.replace(/\\$\\{[^{}]+\\}/g, '').includes('${'))\n throw new ValidationError('graph parameters: malformed reference')\n const whole = /^\\$\\{([^{}]+)\\}$/.exec(item)\n const parts: Part[] = []\n let cursor = 0\n let wholeValue: unknown\n let boundWhole = false\n for (const match of item.matchAll(/\\$\\{([^{}]+)\\}/g)) {\n if (match.index > cursor) parts.push({ literal: item.slice(cursor, match.index) })\n const [namespace, ...keys] = match[1]!.split('.')\n if ((namespace !== 'params' && namespace !== 'trigger') || keys.length === 0)\n throw new ValidationError(`graph parameters: unsupported reference \\${${match[1]}}`)\n if (options.defer?.includes(namespace)) {\n if (namespace === 'trigger') parts.push({ trigger: keys })\n else parts.push({ literal: match[0] })\n } else {\n const found = readBinding(namespace, keys, bindings)\n if (whole) {\n wholeValue = found\n boundWhole = true\n } else parts.push({ literal: textValue(found, match[1]!) })\n }\n cursor = match.index + match[0].length\n }\n if (boundWhole) return wholeValue\n if (cursor === 0) return item\n if (cursor < item.length) parts.push({ literal: item.slice(cursor) })\n if (parts.some((part) => 'trigger' in part))\n triggerBindings.push({ path, mode: whole ? 'value' : 'text', parts })\n return pendingText(parts)\n }\n if (!item || typeof item !== 'object') return item\n if (visiting.has(item)) throw new ValidationError('graph parameters: cyclic data is not JSON')\n visiting.add(item)\n const bound = Array.isArray(item)\n ? item.map((child, index) => bind(child, [...path, index]))\n : Object.fromEntries(\n Object.entries(item).map(([key, child]) => [key, bind(child, [...path, key])]),\n )\n visiting.delete(item)\n return bound\n }\n return { value: bind(value, []), triggerBindings }\n}\n\n/** Legacy authored-data binding. Compiled graphs use bindCompiledGraphTriggers instead. */\nexport function bindGraphParameters(\n value: unknown,\n bindings: GraphParameterBindings,\n options: { readonly defer?: readonly (keyof GraphParameterBindings)[] } = {},\n): unknown {\n return compileGraphParameters(value, bindings, options).value\n}\n\n/** Check provenance against the exact provisional values without reading trigger data. */\nexport function assertGraphTriggerBindings(\n value: unknown,\n slots: readonly GraphTriggerBinding[],\n): void {\n const seen = new Set<string>()\n for (const slot of graphTriggerBindingsSchema.parse(slots)) {\n const key = JSON.stringify(slot.path.map(String))\n if (seen.has(key)) throw new ValidationError('graph parameters: duplicate trigger binding path')\n seen.add(key)\n let found: unknown = value\n for (const key of slot.path) {\n if (!found || typeof found !== 'object' || !Object.hasOwn(found, key))\n throw new ValidationError('graph parameters: trigger binding path does not exist')\n found = (found as Record<string | number, unknown>)[key]\n }\n if (found !== pendingText(slot.parts))\n throw new ValidationError(\n 'graph parameters: trigger binding does not match its provisional value',\n )\n }\n}\n\n/** Only explicitly recorded authored slots bind. Literal parameter/trigger values are untouched. */\nexport function bindCompiledGraphTriggers<T>(\n value: T,\n slots: readonly GraphTriggerBinding[],\n trigger: GraphParameterBindings['trigger'],\n): T {\n assertGraphTriggerBindings(value, slots)\n const bound = structuredClone(value)\n for (const slot of slots) {\n let parent = bound as Record<string | number, unknown>\n for (const key of slot.path.slice(0, -1)) parent = parent[key] as typeof parent\n parent[slot.path.at(-1)!] =\n slot.mode === 'value'\n ? readBinding('trigger', (slot.parts[0]! as { trigger: string[] }).trigger, { trigger })\n : slot.parts\n .map((part) =>\n 'literal' in part\n ? part.literal\n : textValue(\n readBinding('trigger', part.trigger, { trigger }),\n `trigger.${part.trigger.join('.')}`,\n ),\n )\n .join('')\n }\n return bound\n}\n","/**\n * `graph-registry` — the designer's memory: graphs and their outcomes as files.\n *\n * The AgentGraph algebra makes a graph PLAIN DATA (nodes with pinned profiles,\n * edges with registry-versioned directives, a budget, a deliverable\n * description), which is the property that lets a graph be stored, replayed\n * byte-identical, and mutated like code. This module is the thin durable layer\n * on top: one JSONL record per run, the exact graph content-addressed beside\n * it. The natural home is a SANDBOX WORKSPACE — the platform's snapshot story\n * (Firecracker restore, warm leases, `continuity: 'resume'`) then makes the\n * registry the agent's compounding execution memory across runs: a rerun over\n * the same sandbox finds every graph the designer ever ran, what each cost,\n * and whether it delivered.\n *\n * ORACLES STAY ENVIRONMENT-OWNED. `DeliverableSpec.check` is a function and is\n * deliberately NOT stored: a stored graph keeps the deliverable's `describe`\n * and an optional `checkRef`, and replay re-binds the check from the caller's\n * environment. This is the graph contract's own doctrine — graders are\n * environment, never workers — applied to persistence.\n *\n * Scoring is a documented heuristic, not a learned model: delivered beats\n * failed, then cheaper (tokens, then iterations), then most recent. A designer\n * that needs better selection replaces `pickBest`, not the records.\n */\n\nimport { mkdir, readdir, readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { sha256 } from '../../content-digest'\nimport {\n isNoEntError,\n readCommittedJsonFile,\n upsertCommittedJsonLine,\n withJsonlFileLock,\n} from '../../durable/jsonl-file'\nimport { ValidationError } from '../../errors'\nimport { portableContinuationPolicySchema } from './continuation-data'\nimport { writeAtomicDurableFile } from './durable-file'\nimport type { AgentGraph, GraphEdge } from './graph'\nimport { checkGraphRoute } from './graph-file-schema'\nimport {\n bindCompiledGraphTriggers,\n bindGraphParameters,\n type GraphTriggerBinding,\n} from './graph-parameters'\n\nexport type { GraphTriggerBinding } from './graph-parameters'\n\nimport type { GraphCheckNode, GraphFromStoredOptions } from './stored-graph-check'\n\nexport type {\n GraphCheckNode,\n GraphCheckNodes,\n GraphCheckOutput,\n GraphCheckPlacement,\n GraphCommandCheck,\n GraphFromStoredOptions,\n} from './stored-graph-check'\n\n/** @inline */\ninterface StoredGraphContent {\n readonly digest: string\n /** Authored trigger-slot provenance; present (even empty) on compiled loader output. */\n readonly triggerBindings?: readonly GraphTriggerBinding[]\n readonly nodes: ReadonlyArray<{\n readonly id: string\n readonly profile: AgentProfile\n /** A check node; its profile is `{ name: id }`. */\n readonly check?: GraphCheckNode\n }>\n readonly deliverable: Pick<\n AgentGraph['deliverable'],\n 'describe' | 'checkRef' | 'command' | 'when'\n > & {\n readonly requireSubmission?: AgentGraph['deliverable']['requireSubmission']\n }\n /** A flow graph's entry and gates; absent for any other graph. */\n readonly entry?: AgentGraph['entry']\n readonly gates?: AgentGraph['gates']\n readonly workspace?: AgentGraph['workspace']\n readonly continuation?: AgentGraph['continuation']\n}\n\n/** A graph as stored. Observed imports retain unknown directives and budgets;\n * they describe what happened and cannot be replayed as executable graphs. */\nexport type StoredGraph = StoredGraphContent &\n (\n | {\n readonly observed?: false\n readonly edges: ReadonlyArray<GraphEdge>\n readonly budget: AgentGraph['budget']\n }\n | {\n readonly observed: true\n readonly edges: ReadonlyArray<\n | GraphEdge\n | {\n readonly from: string\n readonly to: string\n }\n >\n readonly budget?: AgentGraph['budget']\n }\n )\n\n/** Editable graph data; registration computes its digest when it is omitted. */\nexport type StoredGraphInput = Omit<\n Extract<StoredGraph, { readonly observed?: false }>,\n 'digest'\n> & {\n readonly digest?: string\n}\n\n/** One run or an explicitly incomplete observation of a graph, for one task shape. */\nexport interface GraphRunRecord {\n /** Content-address of the exact graph that ran. */\n readonly graphDigest: string\n /** Digest of the normalized task shape the designer computed for lookup. */\n readonly taskDigest: string\n readonly startedAt: string\n /** Absent while running or when completion was not established. */\n readonly finishedAt?: string\n readonly outcome:\n | { readonly kind: 'delivered'; readonly summary?: string }\n | { readonly kind: 'no-winner'; readonly reason?: string }\n | { readonly kind: 'unknown' | 'running'; readonly reason: string }\n /** Measured accounting; running observations are to date. Unknown channels omitted. */\n readonly cost: {\n readonly iterations?: number\n readonly tokens?: number\n readonly usd?: number\n readonly ms?: number\n readonly inputTokens?: number\n readonly outputTokens?: number\n readonly humanMessages?: number\n readonly leadMessages?: number\n /** Elapsed wall time from the task start to an independently verified merge. */\n readonly mergeMs?: number\n }\n /** Metered ledger size, absent when a source exposes relationships without traversals. */\n readonly traversals?: number\n readonly exhaustedEdges?: ReadonlyArray<string>\n /** Explicit source metadata, never classified from transcript or PR prose. */\n readonly taskType?: 'feature' | 'bugfix' | 'consolidation' | 'investigation' | 'ops'\n /** Stable run identity; re-ingesting this source replaces its observation. */\n readonly source?: { readonly kind: string; readonly id: string; readonly url?: string }\n readonly observedAt?: string\n /** Link to the canonical trace run; execution trees remain trace-owned. */\n readonly traceRunId?: string\n /** Canonical ordered adjacency. This is not a graph-isomorphism claim. */\n readonly topologyDigest?: string\n readonly evidence?: ReadonlyArray<{\n readonly kind: string\n readonly url: string\n readonly at?: string\n }>\n readonly nodeUsage?: ReadonlyArray<{\n readonly nodeId: string\n readonly sourceId?: string\n readonly startedAt?: string\n /** Latest recorded activity, not a claim that the node finished. */\n readonly lastRecordAt?: string\n readonly finishedAt?: string\n readonly inputTokens?: number\n readonly outputTokens?: number\n readonly humanMessages?: number\n readonly leadMessages?: number\n }>\n /** Missing or partial evidence, including incomplete accounting channels. */\n readonly unknowns?: ReadonlyArray<string>\n}\n\nexport interface GraphRegistryDir {\n readonly root: string\n}\n\nconst RECORDS_FILE = 'records.jsonl'\nconst GRAPHS_DIR = 'graphs'\n\n/** Canonical serialization for content-addressing: stable key order, sorted. */\nfunction canonicalJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`\n if (value && typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`\n }\n return JSON.stringify(value)\n}\n\n/** Digest of the exact graph (nodes + edges + budget + deliverable describe, and a flow graph's\n * entry and gates). An absent key is not serialized, so a graph without `entry` keeps the digest\n * it had before flow graphs were stored. */\nexport function graphDigest(graph: Omit<StoredGraph, 'digest'>): string {\n const { continuation, ...content } = graph\n if (content.entry !== undefined && content.deliverable.requireSubmission)\n throw new ValidationError('a graph with an entry has no manager to submit its result')\n const policy =\n continuation === undefined ? undefined : portableContinuationPolicySchema.parse(continuation)\n if (policy !== undefined && content.entry !== undefined)\n throw new ValidationError('graph continuation with entry has no root manager')\n return sha256(\n canonicalJson({ ...content, ...(policy === undefined ? {} : { continuation: policy }) }),\n )\n}\n\n/** Digest of the normalized task shape a designer looks records up by. */\nexport function taskShapeDigest(taskShape: Record<string, unknown>): string {\n return sha256(canonicalJson(taskShape))\n}\n\n/** Digest of a runnable graph exactly as the registry stores it — the value\n * `recordGraphRun` demands. Callers recording real runs hash through this,\n * never hand-rolled, so a record always matches its graph. */\nexport function digestOfGraph(graph: AgentGraph): string {\n return storeGraph(graph).digest\n}\n\nfunction storeGraph(graph: AgentGraph): StoredGraph {\n const { describe, requireSubmission, checkRef, command, when } = graph.deliverable\n const continuation = graph.continuation\n const content = {\n nodes: graph.nodes,\n edges: graph.edges,\n budget: graph.budget,\n ...(graph.triggerBindings === undefined ? {} : { triggerBindings: graph.triggerBindings }),\n deliverable: {\n ...(describe ? { describe } : {}),\n ...(requireSubmission === undefined ? {} : { requireSubmission }),\n ...(checkRef ? { checkRef } : {}),\n ...(command ? { command } : {}),\n ...(when ? { when } : {}),\n },\n ...(graph.entry === undefined ? {} : { entry: graph.entry }),\n ...(graph.gates === undefined ? {} : { gates: graph.gates }),\n ...(graph.workspace === undefined ? {} : { workspace: graph.workspace }),\n ...(continuation === undefined\n ? {}\n : { continuation: portableContinuationPolicySchema.parse(continuation) }),\n }\n return { digest: graphDigest(content), ...content }\n}\n\nfunction assertRecord(record: GraphRunRecord): void {\n if (typeof record.graphDigest !== 'string' || record.graphDigest.length === 0)\n throw new ValidationError('graph-registry: record.graphDigest is required')\n if (typeof record.taskDigest !== 'string' || record.taskDigest.length === 0)\n throw new ValidationError('graph-registry: record.taskDigest is required')\n if (!Number.isFinite(Date.parse(record.startedAt)))\n throw new ValidationError('graph-registry: record.startedAt must be a timestamp')\n if (!['delivered', 'no-winner', 'unknown', 'running'].includes(record.outcome.kind))\n throw new ValidationError('graph-registry: invalid record.outcome.kind')\n if (\n (record.outcome.kind === 'delivered' || record.outcome.kind === 'no-winner') &&\n (!record.finishedAt || !Number.isFinite(Date.parse(record.finishedAt)))\n )\n throw new ValidationError('graph-registry: terminal outcomes require record.finishedAt')\n if (\n (record.outcome.kind === 'unknown' || record.outcome.kind === 'running') &&\n !record.outcome.reason\n )\n throw new ValidationError('graph-registry: incomplete outcomes require a reason')\n if (record.source && (!record.source.kind || !record.source.id))\n throw new ValidationError('graph-registry: source.kind and source.id are required')\n if (\n record.finishedAt &&\n (!Number.isFinite(Date.parse(record.finishedAt)) ||\n Date.parse(record.finishedAt) < Date.parse(record.startedAt))\n )\n throw new ValidationError('graph-registry: finishedAt precedes startedAt or is invalid')\n for (const [channel, value] of Object.entries(record.cost)) {\n if (value !== undefined && (typeof value !== 'number' || !Number.isFinite(value) || value < 0))\n throw new ValidationError(`graph-registry: invalid cost.${channel}`)\n }\n}\n\nfunction recordKey(record: GraphRunRecord): string {\n assertRecord(record)\n if (record.source) return JSON.stringify(['source', record.source.kind, record.source.id])\n return JSON.stringify([record.taskDigest, record.graphDigest, record.startedAt])\n}\n\n/** Open (or lazily create) a registry rooted at a workspace directory. The\n * directory is the sandbox workspace; snapshots carry it across runs. */\nexport function graphRegistry(root: string): GraphRegistryDir {\n if (!root || root.trim().length === 0)\n throw new ValidationError('graphRegistry: root directory is required')\n return { root }\n}\n\n/** Append one run record; the exact graph is content-addressed beside it.\n * Idempotent per (taskDigest, graphDigest, startedAt): a replayed append with\n * the same key replaces the prior row rather than duplicating it. */\nexport async function recordGraphRun(\n reg: GraphRegistryDir,\n graph: AgentGraph,\n record: GraphRunRecord,\n): Promise<StoredGraph> {\n const stored = storeGraph(graph)\n return recordStoredGraphRun(reg, stored, record)\n}\n\n/** Store an executable graph or an observed external topology in the same registry.\n * Imported observations retain their source identity and never authorize replay.\n * A reader refreshing facts can preserve independently joined labels; an explicit\n * correction leaves preserveLabels unset and replaces the record. */\nexport async function recordStoredGraphRun(\n reg: GraphRegistryDir,\n definition: StoredGraph | StoredGraphInput,\n record?: GraphRunRecord,\n options: { readonly preserveLabels?: boolean } = {},\n): Promise<StoredGraph> {\n const { digest, continuation, ...topology } = definition\n const content = {\n ...topology,\n ...(continuation === undefined\n ? {}\n : { continuation: portableContinuationPolicySchema.parse(continuation) }),\n }\n const stored = { ...content, digest: digest ?? graphDigest(content) } as StoredGraph\n if (stored.observed && !record)\n throw new ValidationError('graph-registry: observed graphs require a source run identity')\n if (record) {\n assertRecord(record)\n if (stored.observed && !record.source)\n throw new ValidationError('graph-registry: observed graphs require a source run identity')\n if (!stored.observed && !record.finishedAt)\n throw new ValidationError('graph-registry: native graph runs require a completion timestamp')\n if (\n (!stored.observed || record.traversals !== undefined) &&\n (!Number.isSafeInteger(record.traversals) || record.traversals! < 0)\n )\n throw new ValidationError(\n 'graph-registry: native graphs require metered traversals; observed counts must be non-negative integers',\n )\n if (stored.digest !== record.graphDigest) {\n throw new ValidationError(\n `graph-registry: record.graphDigest ${record.graphDigest} does not match the supplied graph (${stored.digest}) — record the graph that actually ran`,\n )\n }\n }\n if (graphDigest(content) !== stored.digest)\n throw new ValidationError('graph-registry: stored graph content does not match its digest')\n await mkdir(join(reg.root, GRAPHS_DIR), { recursive: true })\n const file = join(reg.root, RECORDS_FILE)\n return withJsonlFileLock(file, async (canonicalPath) => {\n if (!record) {\n await persistGraph(reg, stored)\n return stored\n }\n let persisted = record\n if (options.preserveLabels && record.source) {\n const prior = (await readCommittedJsonFile<GraphRunRecord>(canonicalPath)).find(\n (row) => row.source?.kind === record.source!.kind && row.source.id === record.source!.id,\n )\n if (prior) {\n const taskType = record.taskType ?? prior.taskType\n const priorTerminal =\n prior.outcome.kind === 'delivered' || prior.outcome.kind === 'no-winner'\n const incomingUnassessed =\n record.outcome.kind === 'unknown' || record.outcome.kind === 'running'\n if (priorTerminal && incomingUnassessed && prior.startedAt !== record.startedAt)\n throw new ValidationError(\n 'graph-registry: preserving labels requires the same task start and source identity',\n )\n const evidence = [...(prior.evidence ?? []), ...(record.evidence ?? [])]\n persisted = {\n ...record,\n ...(taskType ? { taskType } : {}),\n ...(record.unknowns\n ? {\n unknowns: record.unknowns.filter(\n (reason) => !(taskType && reason === 'task type not explicitly labeled'),\n ),\n }\n : {}),\n ...(evidence.length\n ? {\n evidence: [\n ...new Map(evidence.map((entry) => [canonicalJson(entry), entry])).values(),\n ],\n }\n : {}),\n ...(priorTerminal && incomingUnassessed\n ? {\n outcome: prior.outcome,\n finishedAt: prior.finishedAt,\n cost: {\n ...record.cost,\n ...(prior.cost.ms === undefined ? {} : { ms: prior.cost.ms }),\n ...(prior.cost.mergeMs === undefined ? {} : { mergeMs: prior.cost.mergeMs }),\n },\n }\n : {}),\n }\n }\n }\n assertRecord(persisted)\n await persistGraph(reg, stored)\n await upsertCommittedJsonLine(canonicalPath, persisted, recordKey)\n return stored\n })\n}\n\nasync function persistGraph(reg: GraphRegistryDir, stored: StoredGraph): Promise<void> {\n if (await loadGraph(reg, stored.digest)) return\n // Content-addressed revisions are immutable; the same reader verifies existing bytes.\n const revisionPath = join(reg.root, GRAPHS_DIR, `${stored.digest}.json`)\n writeAtomicDurableFile(revisionPath, JSON.stringify(stored), { preserveMode: true })\n}\n\n/** All records, newest last. */\nexport async function listGraphRuns(reg: GraphRegistryDir): Promise<GraphRunRecord[]> {\n return readCommittedJsonFile<GraphRunRecord>(join(reg.root, RECORDS_FILE))\n}\n\n/** Filters over the existing graph run records. Missing source kind is native. */\nexport interface GraphRunQuery {\n readonly taskDigest?: string\n readonly taskType?: GraphRunRecord['taskType'] | 'unknown'\n readonly topologyDigest?: string\n readonly sourceKind?: string\n}\n\nfunction observedTopology(record: GraphRunRecord): string {\n return record.topologyDigest ?? (record.source ? 'unknown' : record.graphDigest)\n}\n\n/** Records for one task shape or deterministic label query, newest last. */\nexport async function graphRunsFor(\n reg: GraphRegistryDir,\n query: string | GraphRunQuery = {},\n): Promise<GraphRunRecord[]> {\n const filters = typeof query === 'string' ? { taskDigest: query } : query\n return (await listGraphRuns(reg)).filter(\n (row) =>\n (filters.taskDigest === undefined || row.taskDigest === filters.taskDigest) &&\n (filters.taskType === undefined || (row.taskType ?? 'unknown') === filters.taskType) &&\n (filters.topologyDigest === undefined || observedTopology(row) === filters.topologyDigest) &&\n (filters.sourceKind === undefined || (row.source?.kind ?? 'native') === filters.sourceKind),\n )\n}\n\n/** Descriptive task-type/topology measurements, with every population explicit.\n * Unknown and running runs never enter the assessed denominator or medians. */\nexport interface GraphCorpusGroup {\n readonly taskType: NonNullable<GraphRunRecord['taskType']> | 'unknown'\n readonly topologyDigest: string\n readonly delivered: number\n readonly assessed: number\n readonly unknown: number\n readonly deliveredRate: number | null\n readonly medianWallMs: number | null\n readonly wallMsCount: number\n readonly medianMergeMs: number | null\n readonly mergeMsCount: number\n readonly medianTokens: number | null\n readonly tokenCount: number\n readonly medianHumanMessages: number | null\n readonly humanMessageCount: number\n readonly runs: readonly GraphRunRecord[]\n}\n\n/** The registry's observational view. It neither authorizes replay nor proves a causal win. */\nexport interface GraphCorpusSummary {\n readonly recordCount: number\n readonly groups: readonly GraphCorpusGroup[]\n}\n\nfunction medianKnown(values: readonly (number | undefined)[]): {\n median: number | null\n count: number\n} {\n const known = values\n .filter((value): value is number => value !== undefined && Number.isFinite(value) && value >= 0)\n .sort((a, b) => a - b)\n const middle = Math.floor(known.length / 2)\n return {\n count: known.length,\n median:\n known.length === 0\n ? null\n : known.length % 2\n ? known[middle]!\n : (known[middle - 1]! + known[middle]!) / 2,\n }\n}\n\n// The single observational policy used by both query and pickBestGraph. Native\n// selection below remains unchanged; this policy is an explicit descriptive opt-in.\nfunction observedGraphSummary(records: readonly GraphRunRecord[]): GraphCorpusSummary {\n const groups = new Map<string, GraphRunRecord[]>()\n for (const record of records) {\n const key = JSON.stringify([record.taskType ?? 'unknown', observedTopology(record)])\n const rows = groups.get(key)\n if (rows) rows.push(record)\n else groups.set(key, [record])\n }\n const summaries: GraphCorpusGroup[] = [...groups.values()].map((runs) => {\n const assessed = runs.filter(\n (run) => run.outcome.kind === 'delivered' || run.outcome.kind === 'no-winner',\n )\n const delivered = assessed.filter((run) => run.outcome.kind === 'delivered')\n const wall = medianKnown(assessed.map((run) => run.cost.ms))\n const merge = medianKnown(\n delivered\n .filter((run) => run.evidence?.some((entry) => entry.kind === 'pr-merged'))\n .map((run) => run.cost.mergeMs),\n )\n const tokens = medianKnown(assessed.map((run) => run.cost.tokens))\n const human = medianKnown(assessed.map((run) => run.cost.humanMessages))\n return {\n taskType: runs[0]!.taskType ?? 'unknown',\n topologyDigest: observedTopology(runs[0]!),\n delivered: delivered.length,\n assessed: assessed.length,\n unknown: runs.length - assessed.length,\n deliveredRate: assessed.length ? delivered.length / assessed.length : null,\n medianWallMs: wall.median,\n wallMsCount: wall.count,\n medianMergeMs: merge.median,\n mergeMsCount: merge.count,\n medianTokens: tokens.median,\n tokenCount: tokens.count,\n medianHumanMessages: human.median,\n humanMessageCount: human.count,\n runs,\n }\n })\n summaries.sort((a, b) => {\n const delivered = (b.deliveredRate ?? -1) - (a.deliveredRate ?? -1)\n if (delivered) return delivered\n for (const key of ['medianWallMs', 'medianTokens', 'medianHumanMessages'] as const) {\n if (a[key] === b[key]) continue\n if (a[key] === null) return 1\n if (b[key] === null) return -1\n return a[key]! - b[key]!\n }\n return a.taskType.localeCompare(b.taskType) || a.topologyDigest.localeCompare(b.topologyDigest)\n })\n return { recordCount: records.length, groups: summaries }\n}\n\n/** Query and rank the same registry records using the opt-in observational\n * policy: delivery rate, wall time, tokens, then human messages; unknowns last. */\nexport async function graphCorpusSummary(\n reg: GraphRegistryDir,\n query: GraphRunQuery = {},\n): Promise<GraphCorpusSummary> {\n return observedGraphSummary(await graphRunsFor(reg, query))\n}\n\nexport type GraphSelection =\n | { readonly kind: 'replay'; readonly graph: StoredGraph; readonly record: GraphRunRecord }\n | { readonly kind: 'author'; readonly reason: string }\n\n/** The documented heuristic: delivered beats failed; among delivered, cheaper\n * (tokens, then iterations) wins; ties go to the most recent. */\nexport function pickBestGraph(\n records: ReadonlyArray<GraphRunRecord>,\n options: { readonly policy?: 'native' | 'observed' } = {},\n): GraphRunRecord | undefined {\n if (options.policy === 'observed') {\n const group = observedGraphSummary(records).groups[0]\n return group && pickBestGraph(group.runs)\n }\n const delivered = records.filter((row) => row.outcome.kind === 'delivered')\n if (delivered.length === 0) return undefined\n const better = (a: GraphRunRecord, b: GraphRunRecord): GraphRunRecord => {\n const aTokens = a.cost.tokens ?? Number.POSITIVE_INFINITY\n const bTokens = b.cost.tokens ?? Number.POSITIVE_INFINITY\n if (aTokens !== bTokens) return aTokens < bTokens ? a : b\n const aIter = a.cost.iterations ?? Number.POSITIVE_INFINITY\n const bIter = b.cost.iterations ?? Number.POSITIVE_INFINITY\n if (aIter !== bIter) return aIter < bIter ? a : b\n return a.finishedAt! >= b.finishedAt! ? a : b\n }\n return delivered.reduce((best, row) => (better(best, row) === best ? best : row))\n}\n\n/** Read the exact content-addressed graph, including non-executable observations. */\nexport async function loadGraph(\n reg: GraphRegistryDir,\n digest: string,\n): Promise<StoredGraph | undefined> {\n try {\n const stored = JSON.parse(\n await readFile(join(reg.root, GRAPHS_DIR, `${digest}.json`), 'utf8'),\n ) as StoredGraph\n const { digest: actual, ...content } = stored\n if (actual !== digest || graphDigest(content) !== digest)\n throw new ValidationError(\n 'graph-registry: stored graph revision is immutable but its content differs',\n )\n return stored\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\n }\n}\n\n/** The designer's lookup: replay the known-good graph for this task shape, or\n * author a new one — with the reason stated either way (the decision is data). */\nexport async function lookupGraph(\n reg: GraphRegistryDir,\n taskDigest: string,\n): Promise<GraphSelection> {\n const records = await graphRunsFor(reg, taskDigest)\n const candidates: GraphRunRecord[] = []\n const loaded = new Map<string, StoredGraph | undefined>()\n for (const record of records) {\n if (!loaded.has(record.graphDigest))\n loaded.set(record.graphDigest, await loadGraph(reg, record.graphDigest))\n const graph = loaded.get(record.graphDigest)\n if (!graph?.observed) candidates.push(record)\n }\n if (records.length && !candidates.length)\n return {\n kind: 'author',\n reason: 'only observed topologies are available; author an executable graph',\n }\n const best = pickBestGraph(candidates)\n if (best) {\n const graph = await loadGraph(reg, best.graphDigest)\n if (graph) return { kind: 'replay', graph, record: best }\n return {\n kind: 'author',\n reason: `best record's graph ${best.graphDigest.slice(0, 12)} is missing from the registry`,\n }\n }\n return {\n kind: 'author',\n reason:\n records.length === 0\n ? 'first run for this task shape'\n : 'no graph delivered for this task shape yet',\n }\n}\n\n/** Rehydrate a stored graph, binding trigger data and an environment-owned named check. */\nexport function graphFromStored(\n stored: StoredGraph | StoredGraphInput,\n environment: AgentGraph['deliverable']['check'] | GraphFromStoredOptions = {},\n): AgentGraph {\n if (stored.observed)\n throw new ValidationError('graphFromStored: observed topology cannot be replayed')\n const {\n digest: _digest,\n observed: _observed,\n triggerBindings: _triggerBindings,\n deliverable,\n ...topology\n } = (\n stored.triggerBindings !== undefined\n ? bindCompiledGraphTriggers(\n stored,\n stored.triggerBindings,\n typeof environment === 'function' ? undefined : (environment.trigger ?? {}),\n )\n : typeof environment === 'function'\n ? stored\n : bindGraphParameters(stored, { trigger: environment.trigger ?? {} })\n ) as typeof stored\n const selected =\n typeof environment === 'function'\n ? environment\n : environment.checks && Object.hasOwn(environment.checks, deliverable.checkRef ?? '')\n ? environment.checks[deliverable.checkRef!]\n : deliverable.checkRef === 'command'\n ? deliverable.command\n : deliverable.checkRef === 'route' && deliverable.when\n ? (((out, context) =>\n context\n ? context.originalVerdict?.valid !== false\n : checkGraphRoute(\n deliverable.when!,\n out,\n )) satisfies AgentGraph['deliverable']['check'])\n : undefined\n if (!selected)\n throw new ValidationError(\n `graphFromStored: unknown checkRef ${deliverable.checkRef ?? '(missing)'}`,\n )\n const materialized = {\n ...(stored.triggerBindings === undefined ? {} : { triggerBindings: [] as const }),\n ...(topology.continuation === undefined\n ? {}\n : { continuation: portableContinuationPolicySchema.parse(topology.continuation) }),\n }\n if (typeof selected === 'function') {\n const { command: _command, ...description } = deliverable\n return { ...topology, ...materialized, deliverable: { ...description, check: selected } }\n }\n const command =\n selected === deliverable.command\n ? selected\n : (bindGraphParameters(selected, {\n trigger: (environment as GraphFromStoredOptions).trigger ?? {},\n }) as typeof selected)\n return {\n ...topology,\n ...materialized,\n deliverable: {\n ...deliverable,\n command,\n check: () => false, // runGraph binds the independent command authority before execution.\n },\n }\n}\n\n/** Digests present on disk (integrity probe for tests and audits). */\nexport async function storedGraphDigests(reg: GraphRegistryDir): Promise<string[]> {\n try {\n return (await readdir(join(reg.root, GRAPHS_DIR)))\n .filter((name) => name.endsWith('.json'))\n .map((name) => name.slice(0, -'.json'.length))\n .sort()\n } catch {\n return []\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAIA,SAAgB,eACd,OACA,SACA,2BAAW,IAAI,IAAY,GACrB;CACN,SAAS,KAAK,SAAwB;EACpC,MAAM,IAAI,gBAAgB,GAAG,QAAQ,IAAI,SAAS;CACpD;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GAAG,gBAAgB;EAC9C,OAAO;GAAE,GAAG;GAAU,GAAG;GAAc,aAAa;IAAE,GAAG;IAAa,OAAO;GAAS;EAAE;CAC1F;CACA,MAAM,UACJ,aAAa,YAAY,UACrB,WACC,oBAAoB,UAAU,EAC7B,SAAU,YAAuC,WAAW,CAAC,EAC/D,CAAC;CACP,OAAO;EACL,GAAG;EACH,GAAG;EACH,aAAa;GACX,GAAG;GACH;GACA,aAAa;EACf;CACF;AACF;;AAGA,eAAsB,mBAAmB,KAA0C;CACjF,IAAI;EACF,QAAQ,MAAM,QAAQ,KAAK,IAAI,MAAM,UAAU,CAAC,EAAA,CAC7C,QAAQ,SAAS,KAAK,SAAS,OAAO,CAAC,CAAC,CACxC,KAAK,SAAS,KAAK,MAAM,GAAG,EAAe,CAAC,CAAC,CAC7C,KAAK;CACV,QAAQ;EACN,OAAO,CAAC;CACV;AACF"}
1
+ {"version":3,"file":"graph-registry-qyaNDATw.js","names":[],"sources":["../src/json-data.ts","../src/runtime/supervise/continuation-data.ts","../src/runtime/isolated-checker-outputs.ts","../src/runtime/supervise/graph-file-schema.ts","../src/runtime/supervise/graph-parameters.ts","../src/runtime/supervise/graph-registry.ts"],"sourcesContent":["import { ValidationError } from './errors'\n\n/** Inspect descriptors instead of invoking accessors; JSON has no getters, symbols, prototypes,\n * sparse arrays, undefined, closures or cycles. Repeated non-cyclic references remain JSON data. */\nexport function assertJsonData(\n value: unknown,\n context: string,\n visiting = new Set<object>(),\n): void {\n function fail(message: string): never {\n throw new ValidationError(`${context}: ${message}`)\n }\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return\n if (typeof value === 'number' && Number.isFinite(value)) return\n if (!value || typeof value !== 'object' || visiting.has(value))\n fail('expected finite, acyclic JSON data without executable values')\n const array = Array.isArray(value)\n const prototype = Object.getPrototypeOf(value)\n if (array ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null)\n fail('expected plain JSON objects and arrays')\n visiting.add(value)\n const descriptors = Object.getOwnPropertyDescriptors(value)\n const keys = Reflect.ownKeys(descriptors)\n if (array && keys.length !== value.length + 1) fail('sparse arrays are not canonical JSON')\n for (const key of keys) {\n if (array && key === 'length') continue\n const property = typeof key === 'string' ? descriptors[key] : undefined\n if (!property || !property.enumerable || !('value' in property))\n fail('JSON data cannot contain symbols, hidden properties or accessors')\n if (array && (!/^(0|[1-9]\\d*)$/.test(key as string) || Number(key) >= value.length))\n fail('arrays may contain only indexed JSON values')\n assertJsonData(property.value, context, visiting)\n }\n visiting.delete(value)\n}\n","import { z } from 'zod'\nimport { ValidationError } from '../../errors'\nimport { assertJsonData } from '../../json-data'\nimport { admitContinuationPolicy, type ContinuationPolicy } from './continuation'\nimport { detachedFrozen } from './snapshot'\n\n/** Record-owned policy data; callbacks, panel execution and a host-computed best stay outside. */\nexport type PortableContinuationPolicy = Omit<\n ContinuationPolicy,\n 'append' | 'runPanel' | 'panel' | 'panelUsd' | 'best'\n> & { readonly panel: 'off' }\n\n/** The canonical policy admission, restricted to portable JSON rather than host callbacks. */\nexport const portableContinuationPolicySchema = z\n .unknown()\n .transform<PortableContinuationPolicy>((value, context) => {\n try {\n assertJsonData(value, 'graph continuation')\n const policy = value as unknown as PortableContinuationPolicy\n admitContinuationPolicy(policy, 'graph continuation')\n if (\n policy.panel !== 'off' ||\n 'append' in policy ||\n 'runPanel' in policy ||\n 'panelUsd' in policy\n )\n throw new ValidationError(\n 'graph continuation: portable policies cannot carry host callbacks or panel execution',\n )\n for (const [record, keys, name] of [\n [\n policy,\n ['deadline', 'maxBarren', 'profile', 'failures', 'panel', 'bar', 'reference', 'session'],\n 'policy',\n ],\n [\n policy.profile,\n [\n 'id',\n 'opening',\n 'plan',\n 'rules',\n 'headings',\n 'barRule',\n 'questions',\n 'panelModel',\n 'review',\n ],\n 'profile',\n ],\n [\n policy.profile.headings,\n ['failures', 'protected', 'changed', 'findings', 'bar', 'plan', 'rules'],\n 'headings',\n ],\n ] as const) {\n const allowed = new Set<string>(keys)\n for (const key of Object.keys(record))\n if (!allowed.has(key))\n throw new ValidationError(`graph continuation: unknown ${name} field '${key}'`)\n }\n return detachedFrozen(policy)\n } catch (error) {\n context.addIssue({\n code: 'custom',\n message: error instanceof Error ? error.message : String(error),\n })\n return z.NEVER\n }\n })\n","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 /** Trusted host redaction, applied before hashing or persistence; never authored by the check. */\n readonly redact?: (bytes: Uint8Array) => Uint8Array\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, redact, ...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 if (redact !== undefined && typeof redact !== 'function')\n throw new ValidationError('check outputs redact must be a function')\n return Object.freeze({ ...validated, executionId, artifacts, ...(redact && { redact }) })\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 captured = 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 const bytes = options.redact ? options.redact(captured) : captured\n if (\n !(bytes instanceof Uint8Array) ||\n bytes.byteLength > options.maxFileBytes ||\n Math.max(captured.byteLength, bytes.byteLength) > options.maxTotalBytes - totalBytes\n )\n throw new OutputCaptureError('size-limit')\n totalBytes += Math.max(captured.byteLength, 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 { z } from 'zod'\nimport { resolveJsonPointer } from '../../mcp/tools/coordination-map-routing'\nimport type { RouteWhen } from '../../mcp/tools/coordination-route-contracts'\nimport { validateIsolatedCheckOutputs } from '../isolated-checker-outputs'\nimport { portableContinuationPolicySchema } from './continuation-data'\n\nconst scalar = z.union([z.string(), z.number().finite(), z.boolean(), z.null()])\nconst pointer = z.string().regex(/^(?:\\/(?:[^~]|~[01])*)*$/)\nconst matchBase = { node: z.string().min(1).optional(), pointer }\nconst equals = z.strictObject({ ...matchBase, equals: scalar })\nconst oneOf = z.strictObject({ ...matchBase, in: z.array(scalar) })\nconst exists = z.strictObject({ ...matchBase, exists: z.boolean() })\nconst match = z.union([equals, oneOf, exists])\n\n/** The same data grammar as routes; no executable expressions or additional operators. */\nexport const graphRouteWhenSchema = z.union([match, z.strictObject({ all: z.array(match).min(1) })])\n\nconst parameter = z.strictObject({\n default: z.unknown().optional(),\n type: z.enum(['string', 'number', 'integer', 'boolean', 'object', 'array', 'null']).optional(),\n})\nconst command = z.strictObject({\n command: z.string().min(1),\n timeoutMs: z.number().int().positive().optional(),\n})\nconst nonnegativeInteger = z.number().int().nonnegative()\n\n/** Portable provider selection; credentials and concrete connection IDs belong to the host. */\nexport const graphFileNeedSchema = z.union([\n z.string().trim().min(1),\n z.strictObject({\n provider: z.string().trim().min(1),\n account: z.string().trim().min(1).optional(),\n capabilities: z.array(z.string().trim().min(1)).min(1),\n alias: z.string().trim().min(1).optional(),\n }),\n])\n\n/** A check node's command: no model, no seat. Params substitute as elsewhere. */\nexport const graphCheckNodeSchema = z.strictObject({\n command: z.string().min(1),\n timeoutMs: z.number().int().positive().optional(),\n environment: z.string().min(1).optional(),\n egress: z.array(z.string().min(1)).optional(),\n runtime: z.enum(['docker', 'firecracker']).optional(),\n secrets: z.array(z.string().regex(/^[A-Z_][A-Z0-9_]*$/)).optional(),\n outputs: z.unknown().transform(validateIsolatedCheckOutputs).optional(),\n resources: z\n .strictObject({\n cpuCores: z.number().positive().optional(),\n memoryMB: z.number().int().positive().optional(),\n diskGB: z.number().positive().optional(),\n })\n .optional(),\n})\n\n/** Authoring envelope. Canonical profiles and topology are validated by their existing owners. */\nexport const graphFileSchema = z.strictObject({\n digest: z.string().min(1).optional(),\n graph: z.string().min(1).optional(),\n describe: z.string().optional(),\n params: z.record(z.string().min(1), parameter).optional(),\n nodes: z\n .array(\n z.strictObject({\n id: z.string().min(1),\n profile: z.record(z.string(), z.unknown()).optional(),\n seat: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]).optional(),\n needs: z.array(graphFileNeedSchema).optional(),\n check: graphCheckNodeSchema.optional(),\n }),\n )\n .min(1),\n workspace: z.enum(['cwd', 'fresh']).optional(),\n continuation: portableContinuationPolicySchema.optional(),\n entry: z\n .array(\n z.union([z.string().min(1), z.strictObject({ node: z.string().min(1), task: z.unknown() })]),\n )\n .min(1)\n .optional(),\n edges: z.array(z.record(z.string(), z.unknown())),\n gates: z.array(z.unknown()).optional(),\n budget: z.strictObject({\n maxIterations: nonnegativeInteger.optional(),\n maxTokens: nonnegativeInteger.optional(),\n maxUsd: z.number().finite().nonnegative().optional(),\n deadlineMs: nonnegativeInteger.optional(),\n resources: z\n .record(z.string(), z.strictObject({ unit: z.string().min(1), limit: nonnegativeInteger }))\n .optional(),\n }),\n check: z\n .union([\n equals.extend({ describe: z.string().optional() }),\n oneOf.extend({ describe: z.string().optional() }),\n exists.extend({ describe: z.string().optional() }),\n z.strictObject({ describe: z.string().optional(), all: z.array(match).min(1) }),\n z.strictObject({ describe: z.string().optional(), command }),\n ])\n .optional(),\n deliverable: z\n .strictObject({\n describe: z.string().optional(),\n checkRef: z.string().min(1),\n requireSubmission: z.boolean().optional(),\n command: command.optional(),\n when: graphRouteWhenSchema.optional(),\n })\n .optional(),\n on: z.unknown().optional(),\n})\n\n/** Judge the flow's terminal-output map with RouteWhen's own JSON-pointer semantics. */\nexport function checkGraphRoute(when: RouteWhen, output: unknown): boolean {\n return ('all' in when ? when.all : [when]).every((condition) => {\n let document = output\n if (condition.node !== undefined) {\n if (!output || typeof output !== 'object' || !Object.hasOwn(output, condition.node))\n return false\n document = (output as Record<string, unknown>)[condition.node]\n }\n const selected = resolveJsonPointer(document, condition.pointer)\n if ('exists' in condition) return selected.found === condition.exists\n if (!selected.found) return false\n return 'equals' in condition\n ? selected.value === condition.equals\n : condition.in.some((value) => value === selected.value)\n })\n}\n","import { z } from 'zod'\nimport { ValidationError } from '../../errors'\n\nexport interface GraphParameterBindings {\n readonly params?: Readonly<Record<string, unknown>>\n readonly trigger?: Readonly<Record<string, unknown>>\n}\n\nconst triggerPart = z.strictObject({ trigger: z.array(z.string()).min(1) })\nconst literalPart = z.strictObject({ literal: z.string() })\n/** Explicit authored trigger slots in compiled graph data. An empty list marks fully bound data. */\nexport const graphTriggerBindingsSchema = z.array(\n z\n .strictObject({\n path: z.array(z.union([z.string(), z.number().int().nonnegative()])).min(1),\n mode: z.enum(['value', 'text']),\n parts: z.array(z.union([literalPart, triggerPart])).min(1),\n })\n .superRefine((slot, context) => {\n if (\n !slot.parts.some((part) => 'trigger' in part) ||\n (slot.mode === 'value' && (slot.parts.length !== 1 || !('trigger' in slot.parts[0]!)))\n )\n context.addIssue({\n code: 'custom',\n message: 'binding requires authored trigger parts; value slots require one trigger',\n })\n }),\n)\n/** @useDeclaredType */\nexport type GraphTriggerBinding = z.infer<typeof graphTriggerBindingsSchema>[number]\n\ntype Part = GraphTriggerBinding['parts'][number]\n\nfunction readBinding(\n namespace: keyof GraphParameterBindings,\n keys: readonly string[],\n bindings: GraphParameterBindings,\n): unknown {\n let found: unknown = bindings[namespace]\n for (const key of keys) {\n if (!found || typeof found !== 'object' || !Object.hasOwn(found, key))\n throw new ValidationError(`graph parameters: missing ${[namespace, ...keys].join('.')}`)\n found = (found as Record<string, unknown>)[key]\n }\n if (found === undefined)\n throw new ValidationError(`graph parameters: missing ${[namespace, ...keys].join('.')}`)\n return structuredClone(found)\n}\n\nfunction textValue(value: unknown, expression: string): string {\n if (value !== null && typeof value === 'object')\n throw new ValidationError(`graph parameters: ${expression} needs a whole JSON slot`)\n return String(value)\n}\n\nfunction pendingText(parts: readonly Part[]): string {\n return parts\n .map((part) => ('literal' in part ? part.literal : `\\${trigger.${part.trigger.join('.')}}`))\n .join('')\n}\n\n/** Compile authored slots once. Inserted values are data, never recursively parsed templates. */\nexport function compileGraphParameters(\n value: unknown,\n bindings: GraphParameterBindings,\n options: { readonly defer?: readonly (keyof GraphParameterBindings)[] } = {},\n): { value: unknown; triggerBindings: GraphTriggerBinding[] } {\n const visiting = new Set<object>()\n const triggerBindings: GraphTriggerBinding[] = []\n const bind = (item: unknown, path: Array<string | number>): unknown => {\n if (typeof item === 'string') {\n if (item.replace(/\\$\\{[^{}]+\\}/g, '').includes('${'))\n throw new ValidationError('graph parameters: malformed reference')\n const whole = /^\\$\\{([^{}]+)\\}$/.exec(item)\n const parts: Part[] = []\n let cursor = 0\n let wholeValue: unknown\n let boundWhole = false\n for (const match of item.matchAll(/\\$\\{([^{}]+)\\}/g)) {\n if (match.index > cursor) parts.push({ literal: item.slice(cursor, match.index) })\n const [namespace, ...keys] = match[1]!.split('.')\n if ((namespace !== 'params' && namespace !== 'trigger') || keys.length === 0)\n throw new ValidationError(`graph parameters: unsupported reference \\${${match[1]}}`)\n if (options.defer?.includes(namespace)) {\n if (namespace === 'trigger') parts.push({ trigger: keys })\n else parts.push({ literal: match[0] })\n } else {\n const found = readBinding(namespace, keys, bindings)\n if (whole) {\n wholeValue = found\n boundWhole = true\n } else parts.push({ literal: textValue(found, match[1]!) })\n }\n cursor = match.index + match[0].length\n }\n if (boundWhole) return wholeValue\n if (cursor === 0) return item\n if (cursor < item.length) parts.push({ literal: item.slice(cursor) })\n if (parts.some((part) => 'trigger' in part))\n triggerBindings.push({ path, mode: whole ? 'value' : 'text', parts })\n return pendingText(parts)\n }\n if (!item || typeof item !== 'object') return item\n if (visiting.has(item)) throw new ValidationError('graph parameters: cyclic data is not JSON')\n visiting.add(item)\n const bound = Array.isArray(item)\n ? item.map((child, index) => bind(child, [...path, index]))\n : Object.fromEntries(\n Object.entries(item).map(([key, child]) => [key, bind(child, [...path, key])]),\n )\n visiting.delete(item)\n return bound\n }\n return { value: bind(value, []), triggerBindings }\n}\n\n/** Legacy authored-data binding. Compiled graphs use bindCompiledGraphTriggers instead. */\nexport function bindGraphParameters(\n value: unknown,\n bindings: GraphParameterBindings,\n options: { readonly defer?: readonly (keyof GraphParameterBindings)[] } = {},\n): unknown {\n return compileGraphParameters(value, bindings, options).value\n}\n\n/** Check provenance against the exact provisional values without reading trigger data. */\nexport function assertGraphTriggerBindings(\n value: unknown,\n slots: readonly GraphTriggerBinding[],\n): void {\n const seen = new Set<string>()\n for (const slot of graphTriggerBindingsSchema.parse(slots)) {\n const key = JSON.stringify(slot.path.map(String))\n if (seen.has(key)) throw new ValidationError('graph parameters: duplicate trigger binding path')\n seen.add(key)\n let found: unknown = value\n for (const key of slot.path) {\n if (!found || typeof found !== 'object' || !Object.hasOwn(found, key))\n throw new ValidationError('graph parameters: trigger binding path does not exist')\n found = (found as Record<string | number, unknown>)[key]\n }\n if (found !== pendingText(slot.parts))\n throw new ValidationError(\n 'graph parameters: trigger binding does not match its provisional value',\n )\n }\n}\n\n/** Only explicitly recorded authored slots bind. Literal parameter/trigger values are untouched. */\nexport function bindCompiledGraphTriggers<T>(\n value: T,\n slots: readonly GraphTriggerBinding[],\n trigger: GraphParameterBindings['trigger'],\n): T {\n assertGraphTriggerBindings(value, slots)\n const bound = structuredClone(value)\n for (const slot of slots) {\n let parent = bound as Record<string | number, unknown>\n for (const key of slot.path.slice(0, -1)) parent = parent[key] as typeof parent\n parent[slot.path.at(-1)!] =\n slot.mode === 'value'\n ? readBinding('trigger', (slot.parts[0]! as { trigger: string[] }).trigger, { trigger })\n : slot.parts\n .map((part) =>\n 'literal' in part\n ? part.literal\n : textValue(\n readBinding('trigger', part.trigger, { trigger }),\n `trigger.${part.trigger.join('.')}`,\n ),\n )\n .join('')\n }\n return bound\n}\n","/**\n * `graph-registry` — the designer's memory: graphs and their outcomes as files.\n *\n * The AgentGraph algebra makes a graph PLAIN DATA (nodes with pinned profiles,\n * edges with registry-versioned directives, a budget, a deliverable\n * description), which is the property that lets a graph be stored, replayed\n * byte-identical, and mutated like code. This module is the thin durable layer\n * on top: one JSONL record per run, the exact graph content-addressed beside\n * it. The natural home is a SANDBOX WORKSPACE — the platform's snapshot story\n * (Firecracker restore, warm leases, `continuity: 'resume'`) then makes the\n * registry the agent's compounding execution memory across runs: a rerun over\n * the same sandbox finds every graph the designer ever ran, what each cost,\n * and whether it delivered.\n *\n * ORACLES STAY ENVIRONMENT-OWNED. `DeliverableSpec.check` is a function and is\n * deliberately NOT stored: a stored graph keeps the deliverable's `describe`\n * and an optional `checkRef`, and replay re-binds the check from the caller's\n * environment. This is the graph contract's own doctrine — graders are\n * environment, never workers — applied to persistence.\n *\n * Scoring is a documented heuristic, not a learned model: delivered beats\n * failed, then cheaper (tokens, then iterations), then most recent. A designer\n * that needs better selection replaces `pickBest`, not the records.\n */\n\nimport { mkdir, readdir, readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { sha256 } from '../../content-digest'\nimport {\n isNoEntError,\n readCommittedJsonFile,\n upsertCommittedJsonLine,\n withJsonlFileLock,\n} from '../../durable/jsonl-file'\nimport { ValidationError } from '../../errors'\nimport { portableContinuationPolicySchema } from './continuation-data'\nimport { writeAtomicDurableFile } from './durable-file'\nimport type { AgentGraph, GraphEdge } from './graph'\nimport { checkGraphRoute } from './graph-file-schema'\nimport {\n bindCompiledGraphTriggers,\n bindGraphParameters,\n type GraphTriggerBinding,\n} from './graph-parameters'\n\nexport type { GraphTriggerBinding } from './graph-parameters'\n\nimport type { GraphCheckNode, GraphFromStoredOptions } from './stored-graph-check'\n\nexport type {\n GraphCheckNode,\n GraphCheckNodes,\n GraphCheckOutput,\n GraphCheckPlacement,\n GraphCommandCheck,\n GraphFromStoredOptions,\n} from './stored-graph-check'\n\n/** @inline */\ninterface StoredGraphContent {\n readonly digest: string\n /** Authored trigger-slot provenance; present (even empty) on compiled loader output. */\n readonly triggerBindings?: readonly GraphTriggerBinding[]\n readonly nodes: ReadonlyArray<{\n readonly id: string\n readonly profile: AgentProfile\n /** A check node; its profile is `{ name: id }`. */\n readonly check?: GraphCheckNode\n }>\n readonly deliverable: Pick<\n AgentGraph['deliverable'],\n 'describe' | 'checkRef' | 'command' | 'when'\n > & {\n readonly requireSubmission?: AgentGraph['deliverable']['requireSubmission']\n }\n /** A flow graph's entry and gates; absent for any other graph. */\n readonly entry?: AgentGraph['entry']\n readonly gates?: AgentGraph['gates']\n readonly workspace?: AgentGraph['workspace']\n readonly continuation?: AgentGraph['continuation']\n}\n\n/** A graph as stored. Observed imports retain unknown directives and budgets;\n * they describe what happened and cannot be replayed as executable graphs. */\nexport type StoredGraph = StoredGraphContent &\n (\n | {\n readonly observed?: false\n readonly edges: ReadonlyArray<GraphEdge>\n readonly budget: AgentGraph['budget']\n }\n | {\n readonly observed: true\n readonly edges: ReadonlyArray<\n | GraphEdge\n | {\n readonly from: string\n readonly to: string\n }\n >\n readonly budget?: AgentGraph['budget']\n }\n )\n\n/** Editable graph data; registration computes its digest when it is omitted. */\nexport type StoredGraphInput = Omit<\n Extract<StoredGraph, { readonly observed?: false }>,\n 'digest'\n> & {\n readonly digest?: string\n}\n\n/** One run or an explicitly incomplete observation of a graph, for one task shape. */\nexport interface GraphRunRecord {\n /** Content-address of the exact graph that ran. */\n readonly graphDigest: string\n /** Digest of the normalized task shape the designer computed for lookup. */\n readonly taskDigest: string\n readonly startedAt: string\n /** Absent while running or when completion was not established. */\n readonly finishedAt?: string\n readonly outcome:\n | { readonly kind: 'delivered'; readonly summary?: string }\n | { readonly kind: 'no-winner'; readonly reason?: string }\n | { readonly kind: 'unknown' | 'running'; readonly reason: string }\n /** Measured accounting; running observations are to date. Unknown channels omitted. */\n readonly cost: {\n readonly iterations?: number\n readonly tokens?: number\n readonly usd?: number\n readonly ms?: number\n readonly inputTokens?: number\n readonly outputTokens?: number\n readonly humanMessages?: number\n readonly leadMessages?: number\n /** Elapsed wall time from the task start to an independently verified merge. */\n readonly mergeMs?: number\n }\n /** Metered ledger size, absent when a source exposes relationships without traversals. */\n readonly traversals?: number\n readonly exhaustedEdges?: ReadonlyArray<string>\n /** Explicit source metadata, never classified from transcript or PR prose. */\n readonly taskType?: 'feature' | 'bugfix' | 'consolidation' | 'investigation' | 'ops'\n /** Stable run identity; re-ingesting this source replaces its observation. */\n readonly source?: { readonly kind: string; readonly id: string; readonly url?: string }\n readonly observedAt?: string\n /** Link to the canonical trace run; execution trees remain trace-owned. */\n readonly traceRunId?: string\n /** Canonical ordered adjacency. This is not a graph-isomorphism claim. */\n readonly topologyDigest?: string\n readonly evidence?: ReadonlyArray<{\n readonly kind: string\n readonly url: string\n readonly at?: string\n }>\n readonly nodeUsage?: ReadonlyArray<{\n readonly nodeId: string\n readonly sourceId?: string\n readonly startedAt?: string\n /** Latest recorded activity, not a claim that the node finished. */\n readonly lastRecordAt?: string\n readonly finishedAt?: string\n readonly inputTokens?: number\n readonly outputTokens?: number\n readonly humanMessages?: number\n readonly leadMessages?: number\n }>\n /** Missing or partial evidence, including incomplete accounting channels. */\n readonly unknowns?: ReadonlyArray<string>\n}\n\nexport interface GraphRegistryDir {\n readonly root: string\n}\n\nconst RECORDS_FILE = 'records.jsonl'\nconst GRAPHS_DIR = 'graphs'\n\n/** Canonical serialization for content-addressing: stable key order, sorted. */\nfunction canonicalJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`\n if (value && typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`\n }\n return JSON.stringify(value)\n}\n\n/** Digest of the exact graph (nodes + edges + budget + deliverable describe, and a flow graph's\n * entry and gates). An absent key is not serialized, so a graph without `entry` keeps the digest\n * it had before flow graphs were stored. */\nexport function graphDigest(graph: Omit<StoredGraph, 'digest'>): string {\n const { continuation, ...content } = graph\n if (content.entry !== undefined && content.deliverable.requireSubmission)\n throw new ValidationError('a graph with an entry has no manager to submit its result')\n const policy =\n continuation === undefined ? undefined : portableContinuationPolicySchema.parse(continuation)\n if (policy !== undefined && content.entry !== undefined)\n throw new ValidationError('graph continuation with entry has no root manager')\n return sha256(\n canonicalJson({ ...content, ...(policy === undefined ? {} : { continuation: policy }) }),\n )\n}\n\n/** Digest of the normalized task shape a designer looks records up by. */\nexport function taskShapeDigest(taskShape: Record<string, unknown>): string {\n return sha256(canonicalJson(taskShape))\n}\n\n/** Digest of a runnable graph exactly as the registry stores it — the value\n * `recordGraphRun` demands. Callers recording real runs hash through this,\n * never hand-rolled, so a record always matches its graph. */\nexport function digestOfGraph(graph: AgentGraph): string {\n return storeGraph(graph).digest\n}\n\nfunction storeGraph(graph: AgentGraph): StoredGraph {\n const { describe, requireSubmission, checkRef, command, when } = graph.deliverable\n const continuation = graph.continuation\n const content = {\n nodes: graph.nodes,\n edges: graph.edges,\n budget: graph.budget,\n ...(graph.triggerBindings === undefined ? {} : { triggerBindings: graph.triggerBindings }),\n deliverable: {\n ...(describe ? { describe } : {}),\n ...(requireSubmission === undefined ? {} : { requireSubmission }),\n ...(checkRef ? { checkRef } : {}),\n ...(command ? { command } : {}),\n ...(when ? { when } : {}),\n },\n ...(graph.entry === undefined ? {} : { entry: graph.entry }),\n ...(graph.gates === undefined ? {} : { gates: graph.gates }),\n ...(graph.workspace === undefined ? {} : { workspace: graph.workspace }),\n ...(continuation === undefined\n ? {}\n : { continuation: portableContinuationPolicySchema.parse(continuation) }),\n }\n return { digest: graphDigest(content), ...content }\n}\n\nfunction assertRecord(record: GraphRunRecord): void {\n if (typeof record.graphDigest !== 'string' || record.graphDigest.length === 0)\n throw new ValidationError('graph-registry: record.graphDigest is required')\n if (typeof record.taskDigest !== 'string' || record.taskDigest.length === 0)\n throw new ValidationError('graph-registry: record.taskDigest is required')\n if (!Number.isFinite(Date.parse(record.startedAt)))\n throw new ValidationError('graph-registry: record.startedAt must be a timestamp')\n if (!['delivered', 'no-winner', 'unknown', 'running'].includes(record.outcome.kind))\n throw new ValidationError('graph-registry: invalid record.outcome.kind')\n if (\n (record.outcome.kind === 'delivered' || record.outcome.kind === 'no-winner') &&\n (!record.finishedAt || !Number.isFinite(Date.parse(record.finishedAt)))\n )\n throw new ValidationError('graph-registry: terminal outcomes require record.finishedAt')\n if (\n (record.outcome.kind === 'unknown' || record.outcome.kind === 'running') &&\n !record.outcome.reason\n )\n throw new ValidationError('graph-registry: incomplete outcomes require a reason')\n if (record.source && (!record.source.kind || !record.source.id))\n throw new ValidationError('graph-registry: source.kind and source.id are required')\n if (\n record.finishedAt &&\n (!Number.isFinite(Date.parse(record.finishedAt)) ||\n Date.parse(record.finishedAt) < Date.parse(record.startedAt))\n )\n throw new ValidationError('graph-registry: finishedAt precedes startedAt or is invalid')\n for (const [channel, value] of Object.entries(record.cost)) {\n if (value !== undefined && (typeof value !== 'number' || !Number.isFinite(value) || value < 0))\n throw new ValidationError(`graph-registry: invalid cost.${channel}`)\n }\n}\n\nfunction recordKey(record: GraphRunRecord): string {\n assertRecord(record)\n if (record.source) return JSON.stringify(['source', record.source.kind, record.source.id])\n return JSON.stringify([record.taskDigest, record.graphDigest, record.startedAt])\n}\n\n/** Open (or lazily create) a registry rooted at a workspace directory. The\n * directory is the sandbox workspace; snapshots carry it across runs. */\nexport function graphRegistry(root: string): GraphRegistryDir {\n if (!root || root.trim().length === 0)\n throw new ValidationError('graphRegistry: root directory is required')\n return { root }\n}\n\n/** Append one run record; the exact graph is content-addressed beside it.\n * Idempotent per (taskDigest, graphDigest, startedAt): a replayed append with\n * the same key replaces the prior row rather than duplicating it. */\nexport async function recordGraphRun(\n reg: GraphRegistryDir,\n graph: AgentGraph,\n record: GraphRunRecord,\n): Promise<StoredGraph> {\n const stored = storeGraph(graph)\n return recordStoredGraphRun(reg, stored, record)\n}\n\n/** Store an executable graph or an observed external topology in the same registry.\n * Imported observations retain their source identity and never authorize replay.\n * A reader refreshing facts can preserve independently joined labels; an explicit\n * correction leaves preserveLabels unset and replaces the record. */\nexport async function recordStoredGraphRun(\n reg: GraphRegistryDir,\n definition: StoredGraph | StoredGraphInput,\n record?: GraphRunRecord,\n options: { readonly preserveLabels?: boolean } = {},\n): Promise<StoredGraph> {\n const { digest, continuation, ...topology } = definition\n const content = {\n ...topology,\n ...(continuation === undefined\n ? {}\n : { continuation: portableContinuationPolicySchema.parse(continuation) }),\n }\n const stored = { ...content, digest: digest ?? graphDigest(content) } as StoredGraph\n if (stored.observed && !record)\n throw new ValidationError('graph-registry: observed graphs require a source run identity')\n if (record) {\n assertRecord(record)\n if (stored.observed && !record.source)\n throw new ValidationError('graph-registry: observed graphs require a source run identity')\n if (!stored.observed && !record.finishedAt)\n throw new ValidationError('graph-registry: native graph runs require a completion timestamp')\n if (\n (!stored.observed || record.traversals !== undefined) &&\n (!Number.isSafeInteger(record.traversals) || record.traversals! < 0)\n )\n throw new ValidationError(\n 'graph-registry: native graphs require metered traversals; observed counts must be non-negative integers',\n )\n if (stored.digest !== record.graphDigest) {\n throw new ValidationError(\n `graph-registry: record.graphDigest ${record.graphDigest} does not match the supplied graph (${stored.digest}) — record the graph that actually ran`,\n )\n }\n }\n if (graphDigest(content) !== stored.digest)\n throw new ValidationError('graph-registry: stored graph content does not match its digest')\n await mkdir(join(reg.root, GRAPHS_DIR), { recursive: true })\n const file = join(reg.root, RECORDS_FILE)\n return withJsonlFileLock(file, async (canonicalPath) => {\n if (!record) {\n await persistGraph(reg, stored)\n return stored\n }\n let persisted = record\n if (options.preserveLabels && record.source) {\n const prior = (await readCommittedJsonFile<GraphRunRecord>(canonicalPath)).find(\n (row) => row.source?.kind === record.source!.kind && row.source.id === record.source!.id,\n )\n if (prior) {\n const taskType = record.taskType ?? prior.taskType\n const priorTerminal =\n prior.outcome.kind === 'delivered' || prior.outcome.kind === 'no-winner'\n const incomingUnassessed =\n record.outcome.kind === 'unknown' || record.outcome.kind === 'running'\n if (priorTerminal && incomingUnassessed && prior.startedAt !== record.startedAt)\n throw new ValidationError(\n 'graph-registry: preserving labels requires the same task start and source identity',\n )\n const evidence = [...(prior.evidence ?? []), ...(record.evidence ?? [])]\n persisted = {\n ...record,\n ...(taskType ? { taskType } : {}),\n ...(record.unknowns\n ? {\n unknowns: record.unknowns.filter(\n (reason) => !(taskType && reason === 'task type not explicitly labeled'),\n ),\n }\n : {}),\n ...(evidence.length\n ? {\n evidence: [\n ...new Map(evidence.map((entry) => [canonicalJson(entry), entry])).values(),\n ],\n }\n : {}),\n ...(priorTerminal && incomingUnassessed\n ? {\n outcome: prior.outcome,\n finishedAt: prior.finishedAt,\n cost: {\n ...record.cost,\n ...(prior.cost.ms === undefined ? {} : { ms: prior.cost.ms }),\n ...(prior.cost.mergeMs === undefined ? {} : { mergeMs: prior.cost.mergeMs }),\n },\n }\n : {}),\n }\n }\n }\n assertRecord(persisted)\n await persistGraph(reg, stored)\n await upsertCommittedJsonLine(canonicalPath, persisted, recordKey)\n return stored\n })\n}\n\nasync function persistGraph(reg: GraphRegistryDir, stored: StoredGraph): Promise<void> {\n if (await loadGraph(reg, stored.digest)) return\n // Content-addressed revisions are immutable; the same reader verifies existing bytes.\n const revisionPath = join(reg.root, GRAPHS_DIR, `${stored.digest}.json`)\n writeAtomicDurableFile(revisionPath, JSON.stringify(stored), { preserveMode: true })\n}\n\n/** All records, newest last. */\nexport async function listGraphRuns(reg: GraphRegistryDir): Promise<GraphRunRecord[]> {\n return readCommittedJsonFile<GraphRunRecord>(join(reg.root, RECORDS_FILE))\n}\n\n/** Filters over the existing graph run records. Missing source kind is native. */\nexport interface GraphRunQuery {\n readonly taskDigest?: string\n readonly taskType?: GraphRunRecord['taskType'] | 'unknown'\n readonly topologyDigest?: string\n readonly sourceKind?: string\n}\n\nfunction observedTopology(record: GraphRunRecord): string {\n return record.topologyDigest ?? (record.source ? 'unknown' : record.graphDigest)\n}\n\n/** Records for one task shape or deterministic label query, newest last. */\nexport async function graphRunsFor(\n reg: GraphRegistryDir,\n query: string | GraphRunQuery = {},\n): Promise<GraphRunRecord[]> {\n const filters = typeof query === 'string' ? { taskDigest: query } : query\n return (await listGraphRuns(reg)).filter(\n (row) =>\n (filters.taskDigest === undefined || row.taskDigest === filters.taskDigest) &&\n (filters.taskType === undefined || (row.taskType ?? 'unknown') === filters.taskType) &&\n (filters.topologyDigest === undefined || observedTopology(row) === filters.topologyDigest) &&\n (filters.sourceKind === undefined || (row.source?.kind ?? 'native') === filters.sourceKind),\n )\n}\n\n/** Descriptive task-type/topology measurements, with every population explicit.\n * Unknown and running runs never enter the assessed denominator or medians. */\nexport interface GraphCorpusGroup {\n readonly taskType: NonNullable<GraphRunRecord['taskType']> | 'unknown'\n readonly topologyDigest: string\n readonly delivered: number\n readonly assessed: number\n readonly unknown: number\n readonly deliveredRate: number | null\n readonly medianWallMs: number | null\n readonly wallMsCount: number\n readonly medianMergeMs: number | null\n readonly mergeMsCount: number\n readonly medianTokens: number | null\n readonly tokenCount: number\n readonly medianHumanMessages: number | null\n readonly humanMessageCount: number\n readonly runs: readonly GraphRunRecord[]\n}\n\n/** The registry's observational view. It neither authorizes replay nor proves a causal win. */\nexport interface GraphCorpusSummary {\n readonly recordCount: number\n readonly groups: readonly GraphCorpusGroup[]\n}\n\nfunction medianKnown(values: readonly (number | undefined)[]): {\n median: number | null\n count: number\n} {\n const known = values\n .filter((value): value is number => value !== undefined && Number.isFinite(value) && value >= 0)\n .sort((a, b) => a - b)\n const middle = Math.floor(known.length / 2)\n return {\n count: known.length,\n median:\n known.length === 0\n ? null\n : known.length % 2\n ? known[middle]!\n : (known[middle - 1]! + known[middle]!) / 2,\n }\n}\n\n// The single observational policy used by both query and pickBestGraph. Native\n// selection below remains unchanged; this policy is an explicit descriptive opt-in.\nfunction observedGraphSummary(records: readonly GraphRunRecord[]): GraphCorpusSummary {\n const groups = new Map<string, GraphRunRecord[]>()\n for (const record of records) {\n const key = JSON.stringify([record.taskType ?? 'unknown', observedTopology(record)])\n const rows = groups.get(key)\n if (rows) rows.push(record)\n else groups.set(key, [record])\n }\n const summaries: GraphCorpusGroup[] = [...groups.values()].map((runs) => {\n const assessed = runs.filter(\n (run) => run.outcome.kind === 'delivered' || run.outcome.kind === 'no-winner',\n )\n const delivered = assessed.filter((run) => run.outcome.kind === 'delivered')\n const wall = medianKnown(assessed.map((run) => run.cost.ms))\n const merge = medianKnown(\n delivered\n .filter((run) => run.evidence?.some((entry) => entry.kind === 'pr-merged'))\n .map((run) => run.cost.mergeMs),\n )\n const tokens = medianKnown(assessed.map((run) => run.cost.tokens))\n const human = medianKnown(assessed.map((run) => run.cost.humanMessages))\n return {\n taskType: runs[0]!.taskType ?? 'unknown',\n topologyDigest: observedTopology(runs[0]!),\n delivered: delivered.length,\n assessed: assessed.length,\n unknown: runs.length - assessed.length,\n deliveredRate: assessed.length ? delivered.length / assessed.length : null,\n medianWallMs: wall.median,\n wallMsCount: wall.count,\n medianMergeMs: merge.median,\n mergeMsCount: merge.count,\n medianTokens: tokens.median,\n tokenCount: tokens.count,\n medianHumanMessages: human.median,\n humanMessageCount: human.count,\n runs,\n }\n })\n summaries.sort((a, b) => {\n const delivered = (b.deliveredRate ?? -1) - (a.deliveredRate ?? -1)\n if (delivered) return delivered\n for (const key of ['medianWallMs', 'medianTokens', 'medianHumanMessages'] as const) {\n if (a[key] === b[key]) continue\n if (a[key] === null) return 1\n if (b[key] === null) return -1\n return a[key]! - b[key]!\n }\n return a.taskType.localeCompare(b.taskType) || a.topologyDigest.localeCompare(b.topologyDigest)\n })\n return { recordCount: records.length, groups: summaries }\n}\n\n/** Query and rank the same registry records using the opt-in observational\n * policy: delivery rate, wall time, tokens, then human messages; unknowns last. */\nexport async function graphCorpusSummary(\n reg: GraphRegistryDir,\n query: GraphRunQuery = {},\n): Promise<GraphCorpusSummary> {\n return observedGraphSummary(await graphRunsFor(reg, query))\n}\n\nexport type GraphSelection =\n | { readonly kind: 'replay'; readonly graph: StoredGraph; readonly record: GraphRunRecord }\n | { readonly kind: 'author'; readonly reason: string }\n\n/** The documented heuristic: delivered beats failed; among delivered, cheaper\n * (tokens, then iterations) wins; ties go to the most recent. */\nexport function pickBestGraph(\n records: ReadonlyArray<GraphRunRecord>,\n options: { readonly policy?: 'native' | 'observed' } = {},\n): GraphRunRecord | undefined {\n if (options.policy === 'observed') {\n const group = observedGraphSummary(records).groups[0]\n return group && pickBestGraph(group.runs)\n }\n const delivered = records.filter((row) => row.outcome.kind === 'delivered')\n if (delivered.length === 0) return undefined\n const better = (a: GraphRunRecord, b: GraphRunRecord): GraphRunRecord => {\n const aTokens = a.cost.tokens ?? Number.POSITIVE_INFINITY\n const bTokens = b.cost.tokens ?? Number.POSITIVE_INFINITY\n if (aTokens !== bTokens) return aTokens < bTokens ? a : b\n const aIter = a.cost.iterations ?? Number.POSITIVE_INFINITY\n const bIter = b.cost.iterations ?? Number.POSITIVE_INFINITY\n if (aIter !== bIter) return aIter < bIter ? a : b\n return a.finishedAt! >= b.finishedAt! ? a : b\n }\n return delivered.reduce((best, row) => (better(best, row) === best ? best : row))\n}\n\n/** Read the exact content-addressed graph, including non-executable observations. */\nexport async function loadGraph(\n reg: GraphRegistryDir,\n digest: string,\n): Promise<StoredGraph | undefined> {\n try {\n const stored = JSON.parse(\n await readFile(join(reg.root, GRAPHS_DIR, `${digest}.json`), 'utf8'),\n ) as StoredGraph\n const { digest: actual, ...content } = stored\n if (actual !== digest || graphDigest(content) !== digest)\n throw new ValidationError(\n 'graph-registry: stored graph revision is immutable but its content differs',\n )\n return stored\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\n }\n}\n\n/** The designer's lookup: replay the known-good graph for this task shape, or\n * author a new one — with the reason stated either way (the decision is data). */\nexport async function lookupGraph(\n reg: GraphRegistryDir,\n taskDigest: string,\n): Promise<GraphSelection> {\n const records = await graphRunsFor(reg, taskDigest)\n const candidates: GraphRunRecord[] = []\n const loaded = new Map<string, StoredGraph | undefined>()\n for (const record of records) {\n if (!loaded.has(record.graphDigest))\n loaded.set(record.graphDigest, await loadGraph(reg, record.graphDigest))\n const graph = loaded.get(record.graphDigest)\n if (!graph?.observed) candidates.push(record)\n }\n if (records.length && !candidates.length)\n return {\n kind: 'author',\n reason: 'only observed topologies are available; author an executable graph',\n }\n const best = pickBestGraph(candidates)\n if (best) {\n const graph = await loadGraph(reg, best.graphDigest)\n if (graph) return { kind: 'replay', graph, record: best }\n return {\n kind: 'author',\n reason: `best record's graph ${best.graphDigest.slice(0, 12)} is missing from the registry`,\n }\n }\n return {\n kind: 'author',\n reason:\n records.length === 0\n ? 'first run for this task shape'\n : 'no graph delivered for this task shape yet',\n }\n}\n\n/** Rehydrate a stored graph, binding trigger data and an environment-owned named check. */\nexport function graphFromStored(\n stored: StoredGraph | StoredGraphInput,\n environment: AgentGraph['deliverable']['check'] | GraphFromStoredOptions = {},\n): AgentGraph {\n if (stored.observed)\n throw new ValidationError('graphFromStored: observed topology cannot be replayed')\n const {\n digest: _digest,\n observed: _observed,\n triggerBindings: _triggerBindings,\n deliverable,\n ...topology\n } = (\n stored.triggerBindings !== undefined\n ? bindCompiledGraphTriggers(\n stored,\n stored.triggerBindings,\n typeof environment === 'function' ? undefined : (environment.trigger ?? {}),\n )\n : typeof environment === 'function'\n ? stored\n : bindGraphParameters(stored, { trigger: environment.trigger ?? {} })\n ) as typeof stored\n const selected =\n typeof environment === 'function'\n ? environment\n : environment.checks && Object.hasOwn(environment.checks, deliverable.checkRef ?? '')\n ? environment.checks[deliverable.checkRef!]\n : deliverable.checkRef === 'command'\n ? deliverable.command\n : deliverable.checkRef === 'route' && deliverable.when\n ? (((out, context) =>\n context\n ? context.originalVerdict?.valid !== false\n : checkGraphRoute(\n deliverable.when!,\n out,\n )) satisfies AgentGraph['deliverable']['check'])\n : undefined\n if (!selected)\n throw new ValidationError(\n `graphFromStored: unknown checkRef ${deliverable.checkRef ?? '(missing)'}`,\n )\n const materialized = {\n ...(stored.triggerBindings === undefined ? {} : { triggerBindings: [] as const }),\n ...(topology.continuation === undefined\n ? {}\n : { continuation: portableContinuationPolicySchema.parse(topology.continuation) }),\n }\n if (typeof selected === 'function') {\n const { command: _command, ...description } = deliverable\n return { ...topology, ...materialized, deliverable: { ...description, check: selected } }\n }\n const command =\n selected === deliverable.command\n ? selected\n : (bindGraphParameters(selected, {\n trigger: (environment as GraphFromStoredOptions).trigger ?? {},\n }) as typeof selected)\n return {\n ...topology,\n ...materialized,\n deliverable: {\n ...deliverable,\n command,\n check: () => false, // runGraph binds the independent command authority before execution.\n },\n }\n}\n\n/** Digests present on disk (integrity probe for tests and audits). */\nexport async function storedGraphDigests(reg: GraphRegistryDir): Promise<string[]> {\n try {\n return (await readdir(join(reg.root, GRAPHS_DIR)))\n .filter((name) => name.endsWith('.json'))\n .map((name) => name.slice(0, -'.json'.length))\n .sort()\n } catch {\n return []\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAIA,SAAgB,eACd,OACA,SACA,2BAAW,IAAI,IAAY,GACrB;CACN,SAAS,KAAK,SAAwB;EACpC,MAAM,IAAI,gBAAgB,GAAG,QAAQ,IAAI,SAAS;CACpD;CACA,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,OAAO,UAAU,WAAW;CAC/E,IAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,GAAG;CACzD,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,SAAS,IAAI,KAAK,GAC3D,KAAK,8DAA8D;CACrE,MAAM,QAAQ,MAAM,QAAQ,KAAK;CACjC,M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,aAAa;GACX,GAAG;GACH;GACA,aAAa;EACf;CACF;AACF;;AAGA,eAAsB,mBAAmB,KAA0C;CACjF,IAAI;EACF,QAAQ,MAAM,QAAQ,KAAK,IAAI,MAAM,UAAU,CAAC,EAAA,CAC7C,QAAQ,SAAS,KAAK,SAAS,OAAO,CAAC,CAAC,CACxC,KAAK,SAAS,KAAK,MAAM,GAAG,EAAe,CAAC,CAAC,CAC7C,KAAK;CACV,QAAQ;EACN,OAAO,CAAC;CACV;AACF"}
@@ -1,14 +1,14 @@
1
1
  import { i as ConfigError } from "./errors-DG8yufqX.js";
2
- import { F as collectAgentTurn, I as streamAgentTurn } from "./structural-rollout-BSF5tzUm.js";
3
- import { _ as runAbortable, f as sha256, g as linkAbort } from "./jsonl-file-B8xfYz9M.js";
2
+ import { F as collectAgentTurn, I as streamAgentTurn } from "./structural-rollout-BVuf5hFl.js";
3
+ import { C as linkAbort, w as runAbortable, y as sha256 } from "./jsonl-file-B2ESMrTh.js";
4
4
  import { o as armDeadlineTimer } from "./deadline-CySmJ_0S.js";
5
5
  import { n as detachedSnapshot } from "./snapshot-BKLziJ5K.js";
6
- import { Bt as terminateProcessTreeAndConfirm, It as runSettledCommand, w as createExecutor } from "./supervisor-CwUD7dsm.js";
6
+ import { Et as terminateProcessTreeAndConfirm, St as runSettledCommand, w as createExecutor } from "./supervisor-KcnH2hC4.js";
7
7
  import { a as concreteProfileModel, t as assertExecutableAgentProfile } from "./model-policy-DFuhCC0-.js";
8
8
  import { l as syncDurableDirectory, o as publishExclusiveDurableFile } from "./durable-file-pao7FijS.js";
9
9
  import { b as sha256Bytes$1, m as canonicalCandidateDigest$1, v as immutableCandidateValue } from "./output-artifacts-AqkZ8lO2.js";
10
- import { C as serializeRolloutPolicy, S as normalizeRolloutPolicy, w as structuralRolloutPolicyFromProfile, x as applyRolloutPolicyToProfile } from "./activation-DLnZJab0.js";
11
- 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-BoQHI2Tz.js";
10
+ import { C as serializeRolloutPolicy, S as normalizeRolloutPolicy, w as structuralRolloutPolicyFromProfile, x as applyRolloutPolicyToProfile } from "./activation-5TrUzeFd.js";
11
+ 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-BHfb4p6C.js";
12
12
  import { agentProfileEnvironmentSchema, agentProfileSchema, agentProfileTrainingSchema, agentTrainingDatasetIdentitySchema, agentTrainingParametersSchema, agentTrainingReceiptSchema, agentTrainingTaskKey, agentTrainingTaskSchema, applyAgentProfileDiff, canonicalAgentProfileDigest, canonicalCandidateBytes, diffAgentProfiles, sha256DigestSchema, snapshotAgentProfile, trainedModelIdForArtifact } from "@tangle-network/agent-interface";
13
13
  import { canonicalJson, makeProposalFinding } from "@tangle-network/agent-eval";
14
14
  import { redact } from "@tangle-network/agent-eval/traces";
@@ -3062,4 +3062,4 @@ async function improve(profileOrCode, opts) {
3062
3062
  }
3063
3063
  export { assertProfileTrainingIsHeldOut as a, assertNoCallerArtifactDescriptor as c, agenticGenerator as d, commandVerifier as f, isUsageAmount as h, assertCandidateValidator as i, withMethodRuntimeControls as l, createRuntimeUsageTotals as m, createCommandProfileTrainer as n, parseExecutionRef as o, addRuntimeUsage as p, searchMethod as r, privateValuePaths as s, improve as t, rethrowAfterCleanup as u };
3064
3064
 
3065
- //# sourceMappingURL=improve-sIZhpXqE.js.map
3065
+ //# sourceMappingURL=improve-BLFqeD3X.js.map