@tangle-network/agent-runtime 9.0.7 → 9.0.10

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 (99) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/{activation-BA4WLqwN.js → activation-BuKAzxZB.js} +4 -4
  3. package/dist/{activation-BA4WLqwN.js.map → activation-BuKAzxZB.js.map} +1 -1
  4. package/dist/{activation-OSYxeVWi.d.ts → activation-CVVpVGyG.d.ts} +2 -2
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +4 -4
  7. package/dist/{bundle-CcpL2lfr.js → bundle-9NLb1WO3.js} +2 -2
  8. package/dist/{bundle-CcpL2lfr.js.map → bundle-9NLb1WO3.js.map} +1 -1
  9. package/dist/candidate-execution/index.js +5 -4
  10. package/dist/candidate-execution/index.js.map +1 -1
  11. package/dist/{continuation-DDPfLw2w.js → continuation-CZaeHEzQ.js} +2 -2
  12. package/dist/{continuation-DDPfLw2w.js.map → continuation-CZaeHEzQ.js.map} +1 -1
  13. package/dist/{coordination-manager-CawAzVwE.js → coordination-manager-B-Ugh18D.js} +6 -6
  14. package/dist/{coordination-manager-CawAzVwE.js.map → coordination-manager-B-Ugh18D.js.map} +1 -1
  15. package/dist/deadline-CySmJ_0S.js +134 -0
  16. package/dist/deadline-CySmJ_0S.js.map +1 -0
  17. package/dist/{delegate-CXtDKuZm.js → delegate-Dizy-1ZC.js} +2 -2
  18. package/dist/{delegate-CXtDKuZm.js.map → delegate-Dizy-1ZC.js.map} +1 -1
  19. package/dist/durable.d.ts +1 -1
  20. package/dist/durable.js +13 -13
  21. package/dist/{failure-cause-W0o778qO.js → failure-cause-WifbY42M.js} +2 -2
  22. package/dist/{failure-cause-W0o778qO.js.map → failure-cause-WifbY42M.js.map} +1 -1
  23. package/dist/{graph-wQhBJwV_.js → graph-Bf3axJxp.js} +210 -300
  24. package/dist/graph-Bf3axJxp.js.map +1 -0
  25. package/dist/{graph-registry-Dbm8QhbA.js → graph-registry-B_1C7qye.js} +1 -1
  26. package/dist/{graph-registry-D0FE9VpR.js → graph-registry-BbZN5deo.js} +282 -6
  27. package/dist/graph-registry-BbZN5deo.js.map +1 -0
  28. package/dist/{improve-CKQwcCz1.js → improve-JThdxpGB.js} +8 -9
  29. package/dist/{improve-CKQwcCz1.js.map → improve-JThdxpGB.js.map} +1 -1
  30. package/dist/index.d.ts +3 -3
  31. package/dist/index.js +15 -102
  32. package/dist/index.js.map +1 -1
  33. package/dist/intelligence.d.ts +2 -2
  34. package/dist/intelligence.js +7 -7
  35. package/dist/{jsonl-file-DsxVI0E_.js → jsonl-file-BhuxeejY.js} +114 -2
  36. package/dist/jsonl-file-BhuxeejY.js.map +1 -0
  37. package/dist/kernel.d.ts +2 -2
  38. package/dist/kernel.js +17 -16
  39. package/dist/{loop-runner-CCdQ1pmE.d.ts → loop-runner-40_tD2d4.d.ts} +2 -2
  40. package/dist/{loop-runner-3Acu4nGM.js → loop-runner-D8FP4oEN.js} +2 -2
  41. package/dist/{loop-runner-3Acu4nGM.js.map → loop-runner-D8FP4oEN.js.map} +1 -1
  42. package/dist/loop-runner-bin.d.ts +1 -1
  43. package/dist/loop-runner-bin.js +1 -1
  44. package/dist/mcp/bin.js +3 -3
  45. package/dist/mcp/index.d.ts +1 -1
  46. package/dist/mcp/index.js +7 -7
  47. package/dist/mcp/memory-bin.js +1 -1
  48. package/dist/output-artifacts-AqkZ8lO2.js +331 -0
  49. package/dist/output-artifacts-AqkZ8lO2.js.map +1 -0
  50. package/dist/{prepare-D7WwIddG.js → prepare-Cw4ZaN01.js} +5 -4
  51. package/dist/{prepare-D7WwIddG.js.map → prepare-Cw4ZaN01.js.map} +1 -1
  52. package/dist/{profile-BT0X-dm5.js → profile-Cxl_Ajl2.js} +2 -2
  53. package/dist/{profile-BT0X-dm5.js.map → profile-Cxl_Ajl2.js.map} +1 -1
  54. package/dist/profiles.d.ts +1 -1
  55. package/dist/{provision-supervisor-Cm6RLHuw.js → provision-supervisor-BDAXc65B.js} +8 -6
  56. package/dist/{provision-supervisor-Cm6RLHuw.js.map → provision-supervisor-BDAXc65B.js.map} +1 -1
  57. package/dist/{run-cancellation-B4-1Rt4u.js → run-cancellation-Cy9ie5cQ.js} +3 -3
  58. package/dist/{run-cancellation-B4-1Rt4u.js.map → run-cancellation-Cy9ie5cQ.js.map} +1 -1
  59. package/dist/{run-state-D1LkVTBQ.js → run-state-9FP-wBWK.js} +6 -6
  60. package/dist/{run-state-D1LkVTBQ.js.map → run-state-9FP-wBWK.js.map} +1 -1
  61. package/dist/{runtime-Bpad93aK.js → runtime-Czu2SSMy.js} +50 -25
  62. package/dist/{runtime-Bpad93aK.js.map → runtime-Czu2SSMy.js.map} +1 -1
  63. package/dist/{search-executor-D8TxXXSY.js → search-executor-Dl_WUQeH.js} +6 -6
  64. package/dist/{search-executor-D8TxXXSY.js.map → search-executor-Dl_WUQeH.js.map} +1 -1
  65. package/dist/{server-ctFbmRE5.js → server-Dbge7VDj.js} +5 -5
  66. package/dist/{server-ctFbmRE5.js.map → server-Dbge7VDj.js.map} +1 -1
  67. package/dist/{settle-record-BmXd-_3O.js → settle-record-tgpwk6QF.js} +3 -3
  68. package/dist/{settle-record-BmXd-_3O.js.map → settle-record-tgpwk6QF.js.map} +1 -1
  69. package/dist/{structural-rollout-DXymZ3go.js → structural-rollout-DUMYWwZ3.js} +7 -6
  70. package/dist/{structural-rollout-DXymZ3go.js.map → structural-rollout-DUMYWwZ3.js.map} +1 -1
  71. package/dist/{supervise-BTjv6h7v.js → supervise-BpcWjDMr.js} +12 -10
  72. package/dist/{supervise-BTjv6h7v.js.map → supervise-BpcWjDMr.js.map} +1 -1
  73. package/dist/{supervision-discovery-DzYBmrJC.js → supervision-discovery-Hekh50FG.js} +5 -5
  74. package/dist/{supervision-discovery-DzYBmrJC.js.map → supervision-discovery-Hekh50FG.js.map} +1 -1
  75. package/dist/{supervisor-Cnn37lon.js → supervisor-CdrDXnOJ.js} +9 -8
  76. package/dist/{supervisor-Cnn37lon.js.map → supervisor-CdrDXnOJ.js.map} +1 -1
  77. package/dist/{supervisor-accounting-BMrdsYxz.js → supervisor-accounting-us4w7tG6.js} +65 -154
  78. package/dist/supervisor-accounting-us4w7tG6.js.map +1 -0
  79. package/dist/testing.d.ts +1 -1
  80. package/dist/testing.js +13 -13
  81. package/dist/{tool-server-Df-Uy99W.js → tool-server-CirrqFlr.js} +2 -2
  82. package/dist/{tool-server-Df-Uy99W.js.map → tool-server-CirrqFlr.js.map} +1 -1
  83. package/dist/{top-web-Qk6x-A9O.js → top-web-xSGEh02D.js} +7 -7
  84. package/dist/{top-web-Qk6x-A9O.js.map → top-web-xSGEh02D.js.map} +1 -1
  85. package/dist/tui/bin.js +3 -3
  86. package/dist/tui/index.d.ts +1 -1
  87. package/dist/tui/index.js +2 -2
  88. package/dist/{types-KQkbyDmn.d.ts → types-DRijOelA.d.ts} +189 -164
  89. package/dist/{util-fcckrkKp.js → util-qsH5cC9S.js} +3 -132
  90. package/dist/util-qsH5cC9S.js.map +1 -0
  91. package/dist/{workspace-streams-DA9R3j-p.js → workspace-streams-BakRr-Pl.js} +9 -330
  92. package/dist/workspace-streams-BakRr-Pl.js.map +1 -0
  93. package/package.json +1 -1
  94. package/dist/graph-registry-D0FE9VpR.js.map +0 -1
  95. package/dist/graph-wQhBJwV_.js.map +0 -1
  96. package/dist/jsonl-file-DsxVI0E_.js.map +0 -1
  97. package/dist/supervisor-accounting-BMrdsYxz.js.map +0 -1
  98. package/dist/util-fcckrkKp.js.map +0 -1
  99. package/dist/workspace-streams-DA9R3j-p.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workspace-streams-BakRr-Pl.js","names":["canonicalCandidateBytes","canonicalCandidateDigest","sha256Bytes","canonicalCandidateBytes","sha256Bytes","fsConstants","canonicalCandidateBytes","canonicalCandidateBytes","canonicalCandidateDigest"],"sources":["../src/path-control-characters.ts","../src/candidate-execution/artifact-streams.ts","../src/candidate-execution/exact-object.ts","../src/candidate-execution/workspace-archive.ts","../src/candidate-execution/git-materialize.ts","../src/candidate-execution/workspace-archive-local.ts","../src/candidate-execution/workspace-streams.ts"],"sourcesContent":["/** Whether a serialized field contains an ASCII control or delete character. */\nexport function hasControlCharacter(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index)\n if (code < 0x20 || code === 0x7f) return true\n }\n return false\n}\n","import { createHash } from 'node:crypto'\nimport {\n type AgentCandidateArtifactRef,\n type AgentCandidateCapturedArtifact,\n agentCandidateArtifactRefSchema,\n} from '@tangle-network/agent-interface'\nimport { immutableCandidateValue } from './digest'\nimport type {\n AgentCandidateArtifactPort,\n AgentCandidateOutputArtifactPort,\n AgentCandidateOutputPurpose,\n} from './types'\n\n/** Verify the complete stream, including its final digest, before accepting its consumer's result. */\nexport async function* verifiedArtifactChunks(\n artifact: AgentCandidateCapturedArtifact,\n port: AgentCandidateArtifactPort,\n signal?: AbortSignal,\n): AsyncGenerator<Uint8Array> {\n signal?.throwIfAborted()\n if (!('content' in artifact) && !port.readStream) {\n throw new Error('streaming workspace artifacts require readStream')\n }\n const chunks =\n 'content' in artifact\n ? [Buffer.from(artifact.content, 'base64')]\n : port.readStream!(artifact, { signal })\n const hash = createHash('sha256')\n let byteLength = 0\n for await (const chunk of chunks) {\n signal?.throwIfAborted()\n if (!(chunk instanceof Uint8Array))\n throw new Error('candidate artifact emitted a non-byte chunk')\n byteLength += chunk.byteLength\n if (byteLength > artifact.byteLength)\n throw new Error('candidate artifact exceeds its declared length')\n hash.update(chunk)\n yield chunk\n }\n signal?.throwIfAborted()\n if (byteLength !== artifact.byteLength || `sha256:${hash.digest('hex')}` !== artifact.sha256) {\n throw new Error('candidate artifact failed digest or length verification')\n }\n}\n\nconst selfVerifyingPuts = new WeakMap<object, object>()\n\n/**\n * Declare that this exact putStream resolves only after reading its stored object back from where\n * this exact readStream reads it, and matching its digest and length. The claim belongs to the\n * pair, so a wrapper that replaces either function never inherits it.\n */\nexport function markPutStreamVerified(putStream: object, readStream: object): void {\n selfVerifyingPuts.set(putStream, readStream)\n}\n\n/** Whether a port's putStream already read back what its readStream will return. */\nexport function putStreamVerifiedBy(port: AgentCandidateOutputArtifactPort): boolean {\n return (\n port.putStream !== undefined &&\n port.readStream !== undefined &&\n selfVerifyingPuts.get(port.putStream) === port.readStream\n )\n}\n\n/** Stream evaluator evidence into its existing store and verify durable readback before returning. */\nexport async function persistCandidateOutputArtifactStream(\n port: AgentCandidateOutputArtifactPort,\n input: {\n executionId: string\n purpose: AgentCandidateOutputPurpose\n chunks: AsyncIterable<Uint8Array>\n maxBytes: number\n signal?: AbortSignal\n },\n): Promise<AgentCandidateArtifactRef> {\n if (!port.putStream || !port.readStream) {\n throw new Error('streaming workspace persistence requires putStream and readStream')\n }\n input.signal?.throwIfAborted()\n const hash = createHash('sha256')\n let byteLength = 0\n let consumed = false\n async function* checked(): AsyncGenerator<Uint8Array> {\n for await (const chunk of input.chunks) {\n input.signal?.throwIfAborted()\n if (!(chunk instanceof Uint8Array))\n throw new Error('candidate artifact emitted a non-byte chunk')\n byteLength += chunk.byteLength\n if (byteLength > input.maxBytes)\n throw new Error('candidate workspace archive exceeds maxArchiveBytes')\n hash.update(chunk)\n yield chunk\n }\n consumed = true\n input.signal?.throwIfAborted()\n }\n const chunks = checked()\n try {\n const ref = agentCandidateArtifactRefSchema.parse(\n await port.putStream({\n executionId: input.executionId,\n purpose: input.purpose,\n chunks,\n ...(input.signal ? { signal: input.signal } : {}),\n }),\n )\n input.signal?.throwIfAborted()\n if (\n !consumed ||\n ref.sha256 !== `sha256:${hash.digest('hex')}` ||\n ref.byteLength !== byteLength\n ) {\n throw new Error('candidate output locator does not identify the submitted bytes')\n }\n // A port that already read its stored object back is not read a third time. Measured\n // 2026-10-11: a critics tribunal on /mnt/traces re-read 1.1 GB/min of just-written workspace\n // archives, each one written once and read back twice.\n if (!putStreamVerifiedBy(port)) {\n for await (const _chunk of verifiedArtifactChunks(ref, port, input.signal)) {\n // Verification consumes the durable object without retaining it.\n }\n }\n return immutableCandidateValue(ref)\n } finally {\n await chunks.return(undefined)\n }\n}\n","/** Reject unknown fields while requiring every declared non-optional field. */\nexport function assertExactObjectKeys(\n value: unknown,\n required: readonly string[],\n label: string,\n optional: readonly string[] = [],\n): void {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`)\n }\n const allowed = new Set([...required, ...optional])\n if (allowed.size !== required.length + optional.length) {\n throw new Error(`${label} exact-key contract contains duplicate fields`)\n }\n for (const key of Object.keys(value)) {\n if (!allowed.has(key)) throw new Error(`${label} contains unknown field ${key}`)\n }\n for (const key of required) {\n if (!(key in value)) throw new Error(`${label} is missing field ${key}`)\n }\n}\n\n/**\n * Reject a string carrying a lone surrogate. A well-formed UTF-16 string round-trips through UTF-8\n * unchanged; a lone surrogate does not, so a value that passes here is safe to persist and re-read\n * as the same bytes.\n */\nexport function isWellFormedUnicode(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index)\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(index + 1)\n if (!(next >= 0xdc00 && next <= 0xdfff)) return false\n index++\n } else if (code >= 0xdc00 && code <= 0xdfff) {\n return false\n }\n }\n return true\n}\n","import { isAbsolute, win32 } from 'node:path'\nimport { isAnyArrayBuffer, isSharedArrayBuffer } from 'node:util/types'\nimport { isRecord } from '@tangle-network/agent-core'\nimport type {\n AgentCandidateCapturedArtifact,\n AgentCandidateWorkspaceSnapshotEvidence,\n} from '@tangle-network/agent-interface'\nimport { extract, type Pack, pack, type Extract as TarExtract } from 'tar-stream'\nimport { hasControlCharacter } from '../path-control-characters'\nimport { candidateWorkspaceManifest, verifyBytes } from './artifacts'\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDigest,\n deepFreezeCandidate,\n embeddedCandidateArtifact,\n sha256Bytes,\n} from './digest'\nimport { isWellFormedUnicode } from './exact-object'\nimport { persistCandidateOutputArtifact } from './output-artifacts'\nimport type { AgentCandidateExecutorWorkspaceFile } from './types'\nimport type { CaptureAgentCandidateWorkspaceOptions } from './workspace-archive-local'\n\nconst archiveKind = 'agent-candidate-workspace-archive' as const\nconst workspaceEntryPrefix = 'workspace/'\nconst repositoryMetadataEntry = 'metadata/repository.json'\nconst repositoryBundleEntry = 'metadata/repository.bundle'\nconst repositoryIndexEntry = 'metadata/repository.index.json'\nconst repositoryIndexPrefix = 'index/'\nconst fixedTarTime = new Date(0)\n\nexport interface AgentCandidateWorkspaceArchiveLimits {\n maxArchiveBytes: number\n maxEmbeddedArtifactBytes: number\n maxFiles: number\n maxFileBytes: number\n maxTotalFileBytes: number\n maxPathBytes: number\n maxRepositoryBundleBytes: number\n}\n\nconst defaultLimits: AgentCandidateWorkspaceArchiveLimits = Object.freeze({\n maxArchiveBytes: 512 * 1024 * 1024,\n maxEmbeddedArtifactBytes: 1024 * 1024,\n maxFiles: 50_000,\n maxFileBytes: 128 * 1024 * 1024,\n maxTotalFileBytes: 256 * 1024 * 1024,\n maxPathBytes: 4_096,\n maxRepositoryBundleBytes: 128 * 1024 * 1024,\n})\n\nexport interface WorkspaceArchiveRepository {\n headCommit: string\n headTree: string\n bundle: {\n sha256: `sha256:${string}`\n byteLength: number\n bytes: Uint8Array\n }\n workingTree?: { files: Array<{ path: string; mode: number; bytes: Uint8Array }> }\n}\n\ninterface WorkspaceArchiveRepositoryMetadata {\n kind: typeof archiveKind\n headCommit: string\n headTree: string\n bundle: {\n sha256: `sha256:${string}`\n byteLength: number\n }\n workingTree?: { indexManifest: { sha256: `sha256:${string}`; byteLength: number } }\n}\n\ninterface DecodedWorkspaceArchive {\n files: Array<{ path: string; mode: number; bytes: Uint8Array }>\n repository?: WorkspaceArchiveRepository\n}\n\nexport interface CapturedAgentCandidateWorkspace {\n readonly snapshot: AgentCandidateWorkspaceSnapshotEvidence\n /** Caller-owned bytes accepted by createAgentCandidateWorkspacePort. */\n readonly archive: Uint8Array\n}\n\n/** Capture detached files returned by a remote executor into the standard archive. */\nexport async function captureAgentCandidateWorkspaceFiles(\n input: readonly AgentCandidateExecutorWorkspaceFile[],\n options: Omit<\n CaptureAgentCandidateWorkspaceOptions,\n 'includeRepository' | 'repositoryContents'\n > = {},\n): Promise<CapturedAgentCandidateWorkspace> {\n const limits = workspaceLimits(options.limits)\n return captureWorkspaceFiles(\n normalizeWorkspaceFiles(input, limits),\n undefined,\n limits,\n options.artifactPersistence,\n )\n}\n\nexport async function captureWorkspaceFiles(\n files: readonly AgentCandidateExecutorWorkspaceFile[],\n repository: WorkspaceArchiveRepository | undefined,\n limits: AgentCandidateWorkspaceArchiveLimits,\n artifactPersistence: CaptureAgentCandidateWorkspaceOptions['artifactPersistence'],\n): Promise<CapturedAgentCandidateWorkspace> {\n const material = candidateWorkspaceManifest(files)\n const manifest = canonicalCandidateBytes(material)\n const archive = await encodeWorkspaceArchive(files, repository, limits.maxArchiveBytes)\n if (\n !artifactPersistence &&\n (manifest.byteLength > limits.maxEmbeddedArtifactBytes ||\n archive.byteLength > limits.maxEmbeddedArtifactBytes)\n ) {\n throw new Error(\n 'candidate workspace artifacts exceed maxEmbeddedArtifactBytes; artifactPersistence is required',\n )\n }\n const manifestArtifact = await captureWorkspaceArtifact('manifest', manifest, artifactPersistence)\n const archiveArtifact = await captureWorkspaceArtifact('archive', archive, artifactPersistence)\n const snapshot = deepFreezeCandidate({\n kind: 'agent-candidate-workspace-snapshot',\n digest: canonicalCandidateDigest(material),\n material,\n manifest: manifestArtifact,\n archive: archiveArtifact,\n } satisfies AgentCandidateWorkspaceSnapshotEvidence)\n return Object.freeze({ snapshot, archive })\n}\n\nasync function captureWorkspaceArtifact(\n kind: 'manifest' | 'archive',\n bytes: Uint8Array,\n persistence: CaptureAgentCandidateWorkspaceOptions['artifactPersistence'],\n): Promise<AgentCandidateCapturedArtifact> {\n if (!persistence) return embeddedCandidateArtifact(bytes)\n if (!persistence.executionId.trim()) {\n throw new Error('candidate workspace artifact persistence requires an executionId')\n }\n return persistCandidateOutputArtifact(persistence.outputArtifacts, {\n executionId: persistence.executionId,\n purpose: kind === 'manifest' ? 'candidate-workspace-manifest' : 'candidate-workspace-archive',\n bytes,\n ...(persistence.signal ? { signal: persistence.signal } : {}),\n })\n}\n\n/** Verify a portable archive before its source environment may be discarded. */\nexport async function verifyAgentCandidateWorkspaceArchive(input: {\n role: 'task' | 'candidate' | 'knowledge' | 'memory'\n snapshot: AgentCandidateWorkspaceSnapshotEvidence\n archive: Uint8Array\n limits?: Partial<AgentCandidateWorkspaceArchiveLimits>\n}): Promise<void> {\n await decodeVerifiedWorkspaceArchive({ ...input, limits: workspaceLimits(input.limits) })\n}\n\nexport async function decodeVerifiedWorkspaceArchive(input: {\n role: 'task' | 'candidate' | 'knowledge' | 'memory'\n snapshot: AgentCandidateWorkspaceSnapshotEvidence\n archive: Uint8Array\n limits: AgentCandidateWorkspaceArchiveLimits\n}): Promise<DecodedWorkspaceArchive> {\n verifyBytes(\n input.archive,\n input.snapshot.archive.sha256,\n input.snapshot.archive.byteLength,\n 'candidate workspace archive',\n )\n const decoded = await parseWorkspaceArchive(input.archive, input.limits)\n if (decoded.repository && input.role !== 'task') {\n throw new Error('only task workspaces may carry a Git repository')\n }\n assertArchiveMatchesSnapshot(decoded.files, input.snapshot)\n return decoded\n}\n\nasync function encodeWorkspaceArchive(\n files: ReadonlyArray<{ path: string; mode: number; bytes: Uint8Array }>,\n repository: WorkspaceArchiveRepository | undefined,\n maxArchiveBytes: number,\n): Promise<Uint8Array> {\n const archive = pack()\n const output = collectStream(archive, maxArchiveBytes, 'candidate workspace archive')\n try {\n await writeWorkspaceArchiveEntries(archive, files, repository)\n archive.finalize()\n return await output\n } catch (error) {\n archive.destroy(error instanceof Error ? error : new Error(String(error)))\n await output.catch(() => undefined)\n throw error\n }\n}\n\nasync function verifyCanonicalWorkspaceArchive(\n files: ReadonlyArray<{ path: string; mode: number; bytes: Uint8Array }>,\n repository: WorkspaceArchiveRepository | undefined,\n expected: Uint8Array,\n maxArchiveBytes: number,\n): Promise<void> {\n const archive = pack()\n const comparison = streamEqualsBytes(\n archive,\n expected,\n maxArchiveBytes,\n 'candidate workspace archive',\n )\n try {\n await writeWorkspaceArchiveEntries(archive, files, repository)\n archive.finalize()\n if (!(await comparison)) throw new Error('candidate workspace tar is not canonical')\n } catch (error) {\n archive.destroy(error instanceof Error ? error : new Error(String(error)))\n await comparison.catch(() => undefined)\n throw error\n }\n}\n\nasync function writeWorkspaceArchiveEntries(\n archive: Pack,\n files: ReadonlyArray<{ path: string; mode: number; bytes: Uint8Array }>,\n repository: WorkspaceArchiveRepository | undefined,\n): Promise<void> {\n for (const file of files) {\n await writeTarEntry(archive, `${workspaceEntryPrefix}${file.path}`, file.mode, file.bytes)\n }\n if (!repository) return\n const indexManifest = repository.workingTree\n ? canonicalCandidateBytes(candidateWorkspaceManifest(repository.workingTree.files))\n : undefined\n const metadata = canonicalCandidateBytes({\n kind: archiveKind,\n headCommit: repository.headCommit,\n headTree: repository.headTree,\n bundle: {\n sha256: repository.bundle.sha256,\n byteLength: repository.bundle.byteLength,\n },\n ...(indexManifest\n ? {\n workingTree: {\n indexManifest: {\n sha256: sha256Bytes(indexManifest),\n byteLength: indexManifest.byteLength,\n },\n },\n }\n : {}),\n } satisfies WorkspaceArchiveRepositoryMetadata)\n await writeTarEntry(archive, repositoryMetadataEntry, 0o600, metadata)\n await writeTarEntry(archive, repositoryBundleEntry, 0o600, repository.bundle.bytes)\n if (repository.workingTree && indexManifest) {\n await writeTarEntry(archive, repositoryIndexEntry, 0o600, indexManifest)\n for (const file of repository.workingTree.files) {\n await writeTarEntry(archive, `${repositoryIndexPrefix}${file.path}`, file.mode, file.bytes)\n }\n }\n}\n\nasync function parseWorkspaceArchive(\n bytes: Uint8Array,\n limits: AgentCandidateWorkspaceArchiveLimits,\n): Promise<DecodedWorkspaceArchive> {\n if (bytes.byteLength > limits.maxArchiveBytes) {\n throw new Error('candidate workspace archive exceeds maxArchiveBytes')\n }\n const parser = extract()\n const files: DecodedWorkspaceArchive['files'] = []\n const observedEntryNames = new Set<string>()\n const observedPaths = new Set<string>()\n let totalBytes = 0\n let retainedEntryBytes = 0\n let previousPath: string | undefined\n let repositoryMetadata: WorkspaceArchiveRepositoryMetadata | undefined\n let repositoryBundle: Uint8Array | undefined\n let repositoryIndex: Uint8Array | undefined\n const indexFiles: DecodedWorkspaceArchive['files'] = []\n const indexPaths = new Set<string>()\n let previousIndexPath: string | undefined\n let indexBytes = 0\n const decoded = (async () => {\n for await (const entry of parser) {\n const name = entry.header.name\n if (\n entry.header.type !== 'file' ||\n typeof name !== 'string' ||\n observedEntryNames.has(name)\n ) {\n throw new Error('candidate workspace tar contains an invalid entry')\n }\n observedEntryNames.add(name)\n if (name.startsWith(workspaceEntryPrefix)) {\n if (files.length >= limits.maxFiles) {\n throw new Error('candidate workspace archive has an invalid file count')\n }\n const path = safeArchivePath(name.slice(workspaceEntryPrefix.length), limits.maxPathBytes)\n if (!isWorkspaceFileMode(entry.header.mode)) {\n throw new Error(`candidate workspace archive has an unsupported mode: ${path}`)\n }\n assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits)\n const fileBytes = await readTarEntry(entry, limits.maxFileBytes, `workspace file ${path}`)\n retainedEntryBytes += fileBytes.byteLength\n assertWorkspacePathOrder(\n path,\n previousPath,\n observedPaths,\n 'candidate workspace archive paths must be unique and sorted',\n )\n previousPath = path\n if (fileBytes.byteLength > limits.maxTotalFileBytes - totalBytes) {\n throw new Error('candidate workspace archive exceeds maxTotalFileBytes')\n }\n totalBytes += fileBytes.byteLength\n files.push({ path, mode: entry.header.mode, bytes: fileBytes })\n } else if (name === repositoryMetadataEntry) {\n if (entry.header.mode !== 0o600 || repositoryMetadata) {\n throw new Error('candidate workspace archive repository metadata is invalid')\n }\n assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits)\n const metadataBytes = await readTarEntry(\n entry,\n limits.maxPathBytes,\n 'candidate repository metadata',\n )\n retainedEntryBytes += metadataBytes.byteLength\n repositoryMetadata = parseRepositoryMetadata(metadataBytes, limits)\n } else if (name === repositoryBundleEntry) {\n if (entry.header.mode !== 0o600 || repositoryBundle) {\n throw new Error('candidate workspace archive repository bundle is invalid')\n }\n assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits)\n repositoryBundle = await readTarEntry(\n entry,\n limits.maxRepositoryBundleBytes,\n 'candidate Git bundle',\n )\n retainedEntryBytes += repositoryBundle.byteLength\n } else if (name === repositoryIndexEntry) {\n if (entry.header.mode !== 0o600 || repositoryIndex) {\n throw new Error('candidate workspace archive repository index is invalid')\n }\n assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits)\n repositoryIndex = await readTarEntry(\n entry,\n limits.maxArchiveBytes,\n 'candidate Git index manifest',\n )\n retainedEntryBytes += repositoryIndex.byteLength\n } else if (name.startsWith(repositoryIndexPrefix)) {\n if (\n !repositoryMetadata?.workingTree ||\n !repositoryIndex ||\n indexFiles.length >= limits.maxFiles\n ) {\n throw new Error('candidate Git index evidence is incomplete or exceeds maxFiles')\n }\n const path = safeArchivePath(name.slice(repositoryIndexPrefix.length), limits.maxPathBytes)\n if (entry.header.mode !== 0o644 && entry.header.mode !== 0o755) {\n throw new Error('candidate Git index contains an unsupported mode')\n }\n assertWorkspacePathOrder(\n path,\n previousIndexPath,\n indexPaths,\n 'candidate Git index paths must be unique and sorted',\n )\n previousIndexPath = path\n assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits)\n if (\n entry.header.size === undefined ||\n entry.header.size > limits.maxTotalFileBytes - indexBytes\n ) {\n throw new Error('candidate Git index exceeds maxTotalFileBytes')\n }\n if (entry.header.size > limits.maxFileBytes)\n throw new Error('candidate Git index exceeds maxFileBytes')\n const fileBytes = await readTarEntry(entry, limits.maxFileBytes, `Git index file ${path}`)\n retainedEntryBytes += fileBytes.byteLength\n indexBytes += fileBytes.byteLength\n indexFiles.push({ path, mode: entry.header.mode, bytes: fileBytes })\n } else {\n throw new Error(`candidate workspace tar contains an unsupported entry: ${name}`)\n }\n }\n if (Boolean(repositoryMetadata) !== Boolean(repositoryBundle)) {\n throw new Error('candidate workspace archive repository evidence is incomplete')\n }\n if (Boolean(repositoryMetadata?.workingTree) !== Boolean(repositoryIndex)) {\n throw new Error('candidate workspace archive repository index evidence is incomplete')\n }\n const repository =\n repositoryMetadata && repositoryBundle\n ? repositoryFromTar(repositoryMetadata, repositoryBundle, repositoryIndex, indexFiles)\n : undefined\n return { files, ...(repository ? { repository } : {}) }\n })()\n parser.end(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength))\n const result = await decoded\n await verifyCanonicalWorkspaceArchive(\n result.files,\n result.repository,\n bytes,\n limits.maxArchiveBytes,\n )\n return result\n}\n\nfunction assertRetainedArchiveSize(\n archiveBytes: number,\n retainedEntryBytes: number,\n entryBytes: number | undefined,\n limits: AgentCandidateWorkspaceArchiveLimits,\n): void {\n if (\n !Number.isSafeInteger(entryBytes) ||\n entryBytes === undefined ||\n entryBytes < 0 ||\n entryBytes > limits.maxArchiveBytes - archiveBytes - retainedEntryBytes\n ) {\n throw new Error('candidate workspace archive exceeds maxArchiveBytes while decoding')\n }\n}\n\nfunction parseRepositoryMetadata(\n bytes: Uint8Array,\n limits: AgentCandidateWorkspaceArchiveLimits,\n): WorkspaceArchiveRepositoryMetadata {\n let value: unknown\n try {\n value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes))\n } catch (error) {\n throw new Error('candidate workspace archive repository metadata is invalid', { cause: error })\n }\n if (\n !isRecord(value) ||\n !['bundle,headCommit,headTree,kind', 'bundle,headCommit,headTree,kind,workingTree'].includes(\n Object.keys(value).sort().join(','),\n ) ||\n value.kind !== archiveKind ||\n typeof value.headCommit !== 'string' ||\n typeof value.headTree !== 'string' ||\n !isRecord(value.bundle) ||\n Object.keys(value.bundle).sort().join(',') !== 'byteLength,sha256' ||\n typeof value.bundle.sha256 !== 'string' ||\n !/^sha256:[a-f0-9]{64}$/.test(value.bundle.sha256) ||\n !Number.isSafeInteger(value.bundle.byteLength) ||\n (value.bundle.byteLength as number) <= 0 ||\n (value.bundle.byteLength as number) > limits.maxRepositoryBundleBytes\n ) {\n throw new Error('candidate workspace archive repository is invalid')\n }\n if (!Buffer.from(canonicalCandidateBytes(value)).equals(Buffer.from(bytes))) {\n throw new Error('candidate workspace archive repository metadata is not canonical')\n }\n assertGitObjectId(value.headCommit, 'repository HEAD')\n assertGitObjectId(value.headTree, 'repository HEAD tree')\n if (value.headCommit.length !== value.headTree.length) {\n throw new Error('candidate repository HEAD and tree use different object formats')\n }\n let workingTree: WorkspaceArchiveRepositoryMetadata['workingTree']\n if ('workingTree' in value) {\n const working = value.workingTree\n if (\n !isRecord(working) ||\n Object.keys(working).join(',') !== 'indexManifest' ||\n !isRecord(working.indexManifest) ||\n Object.keys(working.indexManifest).sort().join(',') !== 'byteLength,sha256' ||\n typeof working.indexManifest.sha256 !== 'string' ||\n !/^sha256:[a-f0-9]{64}$/.test(working.indexManifest.sha256) ||\n !Number.isSafeInteger(working.indexManifest.byteLength) ||\n (working.indexManifest.byteLength as number) < 0 ||\n (working.indexManifest.byteLength as number) > limits.maxArchiveBytes\n ) {\n throw new Error('candidate workspace archive repository index is invalid')\n }\n workingTree = {\n indexManifest: {\n sha256: working.indexManifest.sha256 as `sha256:${string}`,\n byteLength: working.indexManifest.byteLength as number,\n },\n }\n }\n return {\n kind: archiveKind,\n headCommit: value.headCommit,\n headTree: value.headTree,\n bundle: {\n sha256: value.bundle.sha256 as `sha256:${string}`,\n byteLength: value.bundle.byteLength as number,\n },\n ...(workingTree ? { workingTree } : {}),\n }\n}\n\nfunction repositoryFromTar(\n metadata: WorkspaceArchiveRepositoryMetadata,\n bundle: Uint8Array,\n indexManifest: Uint8Array | undefined,\n indexFiles: DecodedWorkspaceArchive['files'],\n): WorkspaceArchiveRepository {\n verifyBytes(bundle, metadata.bundle.sha256, metadata.bundle.byteLength, 'candidate Git bundle')\n if (metadata.workingTree && indexManifest) {\n verifyBytes(\n indexManifest,\n metadata.workingTree.indexManifest.sha256,\n metadata.workingTree.indexManifest.byteLength,\n 'candidate Git index manifest',\n )\n if (\n !Buffer.from(indexManifest).equals(\n Buffer.from(canonicalCandidateBytes(candidateWorkspaceManifest(indexFiles))),\n )\n ) {\n throw new Error('candidate Git index files do not match the captured manifest')\n }\n }\n return {\n headCommit: metadata.headCommit,\n headTree: metadata.headTree,\n bundle: { ...metadata.bundle, bytes: bundle },\n ...(metadata.workingTree && indexManifest ? { workingTree: { files: indexFiles } } : {}),\n }\n}\n\nasync function writeTarEntry(\n archive: Pack,\n name: string,\n mode: number,\n bytes: Uint8Array,\n): Promise<void> {\n await new Promise<void>((resolveEntry, rejectEntry) => {\n archive.entry(\n workspaceTarHeader(name, mode, bytes.byteLength),\n Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength),\n (error) => (error ? rejectEntry(error) : resolveEntry()),\n )\n })\n}\n\ntype TarEntry = TarExtract extends AsyncIterable<infer Entry> ? Entry : never\n\nasync function readTarEntry(entry: TarEntry, maxBytes: number, label: string): Promise<Uint8Array> {\n const size = entry.header.size\n if (!Number.isSafeInteger(size) || size === undefined || size < 0 || size > maxBytes) {\n throw new Error(`${label} has an invalid tar size`)\n }\n const bytes = await collectStream(entry, maxBytes, label)\n if (bytes.byteLength !== size) throw new Error(`${label} differs from its tar size`)\n return bytes\n}\n\nasync function collectStream(\n stream: AsyncIterable<unknown>,\n maxBytes: number,\n label: string,\n): Promise<Uint8Array> {\n const chunks: Buffer[] = []\n let totalBytes = 0\n for await (const chunk of stream) {\n if (!(chunk instanceof Uint8Array)) {\n throw new Error(`${label} emitted a non-byte chunk`)\n }\n if (chunk.byteLength > maxBytes - totalBytes) {\n const error = new Error(`${label} exceeds its size limit`)\n if ('destroy' in stream && typeof stream.destroy === 'function') stream.destroy(error)\n throw error\n }\n const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n chunks.push(bytes)\n totalBytes += bytes.byteLength\n }\n return Buffer.concat(chunks, totalBytes)\n}\n\nasync function streamEqualsBytes(\n stream: AsyncIterable<unknown>,\n expected: Uint8Array,\n maxBytes: number,\n label: string,\n): Promise<boolean> {\n const expectedBuffer = Buffer.from(expected.buffer, expected.byteOffset, expected.byteLength)\n let equal = true\n let offset = 0\n for await (const chunk of stream) {\n if (!(chunk instanceof Uint8Array)) {\n throw new Error(`${label} emitted a non-byte chunk`)\n }\n if (chunk.byteLength > maxBytes - offset) {\n const error = new Error(`${label} exceeds its size limit`)\n if ('destroy' in stream && typeof stream.destroy === 'function') stream.destroy(error)\n throw error\n }\n const observed = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)\n if (\n offset + observed.byteLength > expectedBuffer.byteLength ||\n !observed.equals(expectedBuffer.subarray(offset, offset + observed.byteLength))\n ) {\n equal = false\n }\n offset += observed.byteLength\n }\n return equal && offset === expectedBuffer.byteLength\n}\n\nfunction assertArchiveMatchesSnapshot(\n files: ReadonlyArray<{ path: string; mode: number; bytes: Uint8Array }>,\n snapshot: AgentCandidateWorkspaceSnapshotEvidence,\n): void {\n const material = candidateWorkspaceManifest(files)\n const materialBytes = canonicalCandidateBytes(material)\n verifyBytes(\n materialBytes,\n snapshot.manifest.sha256,\n snapshot.manifest.byteLength,\n 'candidate workspace manifest',\n )\n if (\n canonicalCandidateDigest(material) !== snapshot.digest ||\n !Buffer.from(materialBytes).equals(Buffer.from(canonicalCandidateBytes(snapshot.material)))\n ) {\n throw new Error('candidate workspace archive does not match its snapshot manifest')\n }\n}\n\nexport function assertWorkspaceFilesWithinLimits(\n files: ReadonlyArray<\n { path: string; mode: number } & ({ bytes: Uint8Array } | { byteLength: number })\n >,\n limits: AgentCandidateWorkspaceArchiveLimits,\n): void {\n if (files.length > limits.maxFiles) {\n throw new Error('candidate workspace exceeds maxFiles')\n }\n let totalBytes = 0\n let previousPath: string | undefined\n const observedPaths = new Set<string>()\n for (const file of files) {\n const path = safeArchivePath(file.path, limits.maxPathBytes)\n assertWorkspacePathOrder(\n path,\n previousPath,\n observedPaths,\n 'candidate workspace paths must be unique and sorted',\n )\n previousPath = path\n if (!isWorkspaceFileMode(file.mode)) {\n throw new Error(`candidate workspace file has unsupported mode: ${path}`)\n }\n if ('bytes' in file && 'byteLength' in file)\n throw new Error(`candidate workspace file has ambiguous length: ${path}`)\n const byteLength = 'bytes' in file ? file.bytes.byteLength : file.byteLength\n if (!Number.isSafeInteger(byteLength) || byteLength < 0 || byteLength > limits.maxFileBytes) {\n throw new Error(`candidate workspace file exceeds maxFileBytes: ${path}`)\n }\n totalBytes += byteLength\n if (totalBytes > limits.maxTotalFileBytes) {\n throw new Error('candidate workspace exceeds maxTotalFileBytes')\n }\n }\n}\n\nfunction normalizeWorkspaceFiles(\n input: readonly AgentCandidateExecutorWorkspaceFile[],\n limits: AgentCandidateWorkspaceArchiveLimits,\n): AgentCandidateExecutorWorkspaceFile[] {\n if (!Array.isArray(input)) {\n throw new Error('candidate workspace files must be an array')\n }\n const fileCount = input.length\n if (fileCount > limits.maxFiles) {\n throw new Error('candidate workspace exceeds maxFiles')\n }\n let totalBytes = 0\n const files: AgentCandidateExecutorWorkspaceFile[] = []\n for (let index = 0; index < fileCount; index++) {\n const inputFile = input[index]\n if (!isRecord(inputFile) || Object.keys(inputFile).sort().join(',') !== 'bytes,mode,path') {\n throw new Error(`candidate workspace file ${index} is invalid`)\n }\n const descriptors = Object.getOwnPropertyDescriptors(inputFile)\n if (\n !('value' in (descriptors.path ?? {})) ||\n !('value' in (descriptors.mode ?? {})) ||\n !('value' in (descriptors.bytes ?? {}))\n ) {\n throw new Error(`candidate workspace file ${index} must use fixed values`)\n }\n const path = safeArchivePath(descriptors.path?.value, limits.maxPathBytes)\n const mode = descriptors.mode?.value\n const inputBytes = descriptors.bytes?.value\n if (!isWorkspaceFileMode(mode)) {\n throw new Error(`candidate workspace file has unsupported mode: ${path}`)\n }\n const view = inspectWorkspaceBytes(inputBytes, path)\n if (view.byteLength > limits.maxFileBytes) {\n throw new Error(`candidate workspace file exceeds maxFileBytes: ${path}`)\n }\n if (view.byteLength > limits.maxTotalFileBytes - totalBytes) {\n throw new Error('candidate workspace exceeds maxTotalFileBytes')\n }\n if (view.byteLength > Math.max(0, limits.maxArchiveBytes - 1024)) {\n throw new Error('candidate workspace archive exceeds maxArchiveBytes')\n }\n totalBytes += view.byteLength\n files.push({ path, mode, bytes: detachWorkspaceBytes(view) })\n }\n files.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0))\n assertWorkspaceFilesWithinLimits(files, limits)\n return files\n}\n\nfunction isWorkspaceFileMode(value: unknown): value is number {\n return Number.isSafeInteger(value) && (value as number) >= 0 && (value as number) <= 0o777\n}\n\nexport function workspaceLimits(\n overrides: Partial<AgentCandidateWorkspaceArchiveLimits> | undefined,\n): AgentCandidateWorkspaceArchiveLimits {\n const limits = { ...defaultLimits, ...overrides }\n for (const [name, value] of Object.entries(limits)) {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new Error(`candidate workspace ${name} must be a positive safe integer`)\n }\n }\n return Object.freeze(limits)\n}\n\nexport function safeArchivePath(value: unknown, maxPathBytes: number): string {\n if (\n typeof value !== 'string' ||\n !value ||\n !isWellFormedUnicode(value) ||\n Buffer.byteLength(value, 'utf8') > maxPathBytes ||\n isAbsolute(value) ||\n win32.isAbsolute(value) ||\n value.includes('\\\\') ||\n value.includes('\\0') ||\n hasControlCharacter(value) ||\n value.split('/').some((part) => !part || part === '.' || part === '..') ||\n ['.git', '.sidecar'].includes(value.split('/')[0]?.toLowerCase() ?? '')\n ) {\n throw new Error(`candidate workspace archive contains an unsafe path: ${String(value)}`)\n }\n return value\n}\n\nexport function assertWorkspacePathOrder(\n path: string,\n previousPath: string | undefined,\n observedPaths: Set<string>,\n errorMessage: string,\n): void {\n if (previousPath !== undefined && previousPath >= path) throw new Error(errorMessage)\n for (let slash = path.indexOf('/'); slash !== -1; slash = path.indexOf('/', slash + 1)) {\n if (observedPaths.has(path.slice(0, slash))) throw new Error(errorMessage)\n }\n observedPaths.add(path)\n}\n\nfunction inspectWorkspaceBytes(\n input: unknown,\n path: string,\n): { buffer: ArrayBuffer; byteOffset: number; byteLength: number } {\n let buffer: ArrayBufferLike\n let byteOffset: number\n let byteLength: number\n try {\n buffer = typedArrayBufferGetter.call(input as Uint8Array) as ArrayBufferLike\n byteOffset = typedArrayByteOffsetGetter.call(input as Uint8Array) as number\n byteLength = typedArrayByteLengthGetter.call(input as Uint8Array) as number\n } catch {\n throw new Error(`candidate workspace file bytes are invalid: ${path}`)\n }\n if (isSharedArrayBuffer(buffer)) {\n throw new Error(`candidate workspace file uses shared bytes: ${path}`)\n }\n if (!isAnyArrayBuffer(buffer)) {\n throw new Error(`candidate workspace file bytes are invalid: ${path}`)\n }\n return { buffer, byteOffset, byteLength }\n}\n\nfunction detachWorkspaceBytes(input: {\n buffer: ArrayBuffer\n byteOffset: number\n byteLength: number\n}): Uint8Array {\n const { buffer, byteOffset, byteLength } = input\n const copy = new Uint8Array(byteLength)\n Uint8Array.prototype.set.call(copy, new Uint8Array(buffer, byteOffset, byteLength))\n return copy\n}\n\nexport function assertGitObjectId(value: string, label: string): void {\n if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value)) {\n throw new Error(`candidate repository ${label} is not a Git object id`)\n }\n}\n\ntype TypedArrayGetter = (this: Uint8Array) => unknown\n\nfunction requireTypedArrayGetter(name: 'buffer' | 'byteOffset' | 'byteLength'): TypedArrayGetter {\n const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype) as object\n const getter = Object.getOwnPropertyDescriptor(typedArrayPrototype, name)?.get\n if (!getter) throw new Error(`typed array intrinsic ${name} accessor is unavailable`)\n return getter\n}\n\nconst typedArrayBufferGetter = requireTypedArrayGetter('buffer')\nconst typedArrayByteOffsetGetter = requireTypedArrayGetter('byteOffset')\nconst typedArrayByteLengthGetter = requireTypedArrayGetter('byteLength')\n\n/** Shared canonical header for both archive encoders. */\nexport function workspaceTarHeader(name: string, mode: number, size: number) {\n return {\n name,\n mode,\n uid: 0,\n gid: 0,\n size,\n mtime: fixedTarTime,\n type: 'file' as const,\n uname: '',\n gname: '',\n }\n}\n","import { spawn } from 'node:child_process'\nimport { mkdir, mkdtemp, readFile, realpath, rm, stat } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join, resolve } from 'node:path'\nimport type {\n AgentCandidateCode,\n AgentCandidateGitHubRepository,\n AgentCandidateGitHubResource,\n AgentCandidateWorkspaceManifestMaterial,\n} from '@tangle-network/agent-interface'\nimport { hasControlCharacter } from '../path-control-characters'\n\nimport { candidateWorkspaceManifest, verifyBytes } from './artifacts'\nimport { canonicalCandidateBytes } from './digest'\nimport type { AgentCandidateRepositoryPort } from './types'\n\ninterface GitResult {\n stdout: Buffer\n stderr: Buffer\n}\n\nexport async function verifyCandidateCode(\n code: AgentCandidateCode,\n repositories: AgentCandidateRepositoryPort,\n patchBytes?: Uint8Array,\n): Promise<string | undefined> {\n if (code.kind === 'disabled') return undefined\n const repositoryRoot = await verifiedRepositoryRoot(code.repository, repositories)\n await assertCommitAndBaseTree(repositoryRoot, code.baseCommit, code.baseTree)\n\n if (code.kind === 'no-op') {\n await assertSafeTree(repositoryRoot, code.baseTree)\n return code.baseTree\n }\n if (!patchBytes) throw new Error('git-patch candidate is missing verified patch bytes')\n\n const temporary = await mkdtemp(join(tmpdir(), 'agent-candidate-git-'))\n try {\n const indexFile = join(temporary, 'index')\n await runCandidateGit(repositoryRoot, ['read-tree', code.baseTree], undefined, {\n GIT_INDEX_FILE: indexFile,\n })\n await runCandidateGit(\n repositoryRoot,\n ['apply', '--cached', '--binary', '--whitespace=nowarn', '-'],\n patchBytes,\n { GIT_INDEX_FILE: indexFile },\n )\n const candidateTree = (\n await runCandidateGit(repositoryRoot, ['write-tree'], undefined, {\n GIT_INDEX_FILE: indexFile,\n })\n ).stdout\n .toString('utf8')\n .trim()\n if (candidateTree !== code.candidateTree) {\n throw new Error(\n `git patch materialized tree ${candidateTree} does not match ${code.candidateTree}`,\n )\n }\n await assertSafeTree(repositoryRoot, candidateTree)\n return candidateTree\n } finally {\n await rm(temporary, { recursive: true, force: true })\n }\n}\n\nexport async function readCandidateGitHubResource(\n resource: AgentCandidateGitHubResource,\n repositories: AgentCandidateRepositoryPort,\n): Promise<Uint8Array> {\n const repositoryRoot = await verifiedRepositoryRoot(resource.repository, repositories)\n const commitType = (\n await runCandidateGit(repositoryRoot, ['cat-file', '-t', resource.commit])\n ).stdout\n .toString('utf8')\n .trim()\n if (commitType !== 'commit') {\n throw new Error(`GitHub resource commit is not a commit object: ${resource.commit}`)\n }\n const listing = (\n await runCandidateGit(repositoryRoot, ['ls-tree', '-z', resource.commit, '--', resource.path])\n ).stdout\n const entries = parseTreeEntries(listing)\n if (entries.length !== 1 || entries[0]?.path !== resource.path) {\n throw new Error(`GitHub resource path is not one exact file: ${resource.path}`)\n }\n const entry = entries[0]\n if (entry?.type !== 'blob' || (entry.mode !== '100644' && entry.mode !== '100755')) {\n throw new Error(`GitHub resource path is not a regular Git blob: ${resource.path}`)\n }\n const bytes = (await runCandidateGit(repositoryRoot, ['cat-file', 'blob', entry.object])).stdout\n verifyBytes(bytes, resource.sha256, resource.byteLength, `GitHub resource ${resource.path}`)\n return Uint8Array.from(bytes)\n}\n\nexport async function verifyTaskCheckout(\n taskRoot: string,\n expected: { baseCommit: string; baseTree: string },\n): Promise<void> {\n const root = resolve(taskRoot)\n const head = (await runCandidateGit(root, ['rev-parse', 'HEAD'])).stdout.toString('utf8').trim()\n if (head !== expected.baseCommit) {\n throw new Error(`task checkout HEAD ${head} does not match ${expected.baseCommit}`)\n }\n const tree = (await runCandidateGit(root, ['rev-parse', 'HEAD^{tree}'])).stdout\n .toString('utf8')\n .trim()\n if (tree !== expected.baseTree) {\n throw new Error(`task checkout base tree ${tree} does not match ${expected.baseTree}`)\n }\n}\n\n/**\n * Apply an evaluator-captured binary diff in a detached object database and\n * prove its result tree exactly matches the captured after-state manifest.\n */\nexport async function verifyTaskOutcomePatch(input: {\n repositoryRoot: string\n baseCommit: string\n baseTree: string\n resultTree: string\n patch: Uint8Array\n afterState: AgentCandidateWorkspaceManifestMaterial\n}): Promise<{ resultTree: string; resultCommit: string }> {\n const repositoryRoot = resolve(input.repositoryRoot)\n await verifyTaskCheckout(repositoryRoot, input)\n const gitDir = resolve(\n (await runCandidateGit(repositoryRoot, ['rev-parse', '--absolute-git-dir'])).stdout\n .toString('utf8')\n .trim(),\n )\n if ((await realpath(gitDir)) !== gitDir || gitDir.includes(':')) {\n throw new Error('task Git object store has an unsupported path')\n }\n await assertNoGitIndirection(repositoryRoot, gitDir, 'task repository')\n\n const temporary = await mkdtemp(join(tmpdir(), 'agent-candidate-task-outcome-'))\n try {\n const objectDirectory = join(temporary, 'objects')\n const indexFile = join(temporary, 'index')\n await mkdir(objectDirectory)\n const gitEnvironment = {\n GIT_INDEX_FILE: indexFile,\n GIT_OBJECT_DIRECTORY: objectDirectory,\n GIT_ALTERNATE_OBJECT_DIRECTORIES: join(gitDir, 'objects'),\n }\n await runCandidateGit(repositoryRoot, ['read-tree', input.baseTree], undefined, gitEnvironment)\n if (input.patch.byteLength > 0) {\n await runCandidateGit(\n repositoryRoot,\n ['apply', '--cached', '--binary', '--whitespace=nowarn', '-'],\n input.patch,\n gitEnvironment,\n )\n }\n const resultTree = (\n await runCandidateGit(repositoryRoot, ['write-tree'], undefined, gitEnvironment)\n ).stdout\n .toString('utf8')\n .trim()\n if (resultTree !== input.resultTree) {\n throw new Error(\n `task outcome patch materialized tree ${resultTree} does not match ${input.resultTree}`,\n )\n }\n await assertSafeTree(repositoryRoot, resultTree, gitEnvironment)\n const observed = await workspaceManifestFromGitTree(repositoryRoot, resultTree, gitEnvironment)\n if (\n !Buffer.from(canonicalCandidateBytes(observed)).equals(\n Buffer.from(canonicalCandidateBytes(input.afterState)),\n )\n ) {\n throw new Error('task outcome after-state does not match the materialized result tree')\n }\n const resultCommit = (\n await runCandidateGit(\n repositoryRoot,\n ['commit-tree', resultTree, '-p', input.baseCommit],\n Buffer.from('candidate task outcome\\n', 'utf8'),\n {\n ...gitEnvironment,\n GIT_AUTHOR_NAME: 'Tangle Evaluator',\n GIT_AUTHOR_EMAIL: 'evaluator@tangle.tools',\n GIT_AUTHOR_DATE: '2000-01-01T00:00:00Z',\n GIT_COMMITTER_NAME: 'Tangle Evaluator',\n GIT_COMMITTER_EMAIL: 'evaluator@tangle.tools',\n GIT_COMMITTER_DATE: '2000-01-01T00:00:00Z',\n },\n )\n ).stdout\n .toString('utf8')\n .trim()\n const committedTree = (\n await runCandidateGit(\n repositoryRoot,\n ['rev-parse', `${resultCommit}^{tree}`],\n undefined,\n gitEnvironment,\n )\n ).stdout\n .toString('utf8')\n .trim()\n if (committedTree !== resultTree) {\n throw new Error('task outcome evaluator commit does not bind the verified result tree')\n }\n return { resultTree, resultCommit }\n } finally {\n await rm(temporary, { recursive: true, force: true })\n }\n}\n\nasync function verifiedRepositoryRoot(\n repository: AgentCandidateGitHubRepository,\n repositories: AgentCandidateRepositoryPort,\n): Promise<string> {\n const repositoryRoot = resolve(await repositories.resolve(repository))\n const rootStats = await stat(repositoryRoot)\n if (!rootStats.isDirectory()) throw new Error('candidate repository path is not a directory')\n\n const origin = (await runCandidateGit(repositoryRoot, ['remote', 'get-url', 'origin'])).stdout\n .toString('utf8')\n .trim()\n const actual = parseGitHubRemote(origin)\n if (!actual || actual.owner !== repository.owner || actual.repo !== repository.repo) {\n throw new Error(\n `local repository origin ${origin || '<missing>'} does not match github.com/${repository.owner}/${repository.repo}`,\n )\n }\n\n const gitDirText = (\n await runCandidateGit(repositoryRoot, ['rev-parse', '--absolute-git-dir'])\n ).stdout\n .toString('utf8')\n .trim()\n const gitDir = resolve(gitDirText)\n await assertNoGitIndirection(repositoryRoot, gitDir, 'candidate repository')\n return repositoryRoot\n}\n\nexport async function assertNoGitIndirection(\n repositoryRoot: string,\n gitDir: string,\n label: string,\n): Promise<void> {\n const replacements = (\n await runCandidateGit(repositoryRoot, ['for-each-ref', '--format=%(refname)', 'refs/replace'])\n ).stdout\n .toString('utf8')\n .trim()\n if (replacements) throw new Error(`${label} contains Git replace refs`)\n // `--git-common-dir` answers relative to the worktree for an ordinary repository, so the\n // path is resolved against a root the caller supplied and carries whatever symlinks that\n // root carries. Read the object store through its RESOLVED path: the alternates below must\n // be read at the real location, and a symlinked prefix is the OS's own doing on macOS,\n // where a temp root lives under /var, a symlink to /private/var.\n const commonDir = await realpath(\n resolve(\n repositoryRoot,\n (await runCandidateGit(repositoryRoot, ['rev-parse', '--git-common-dir'])).stdout\n .toString('utf8')\n .trim(),\n ),\n )\n if (commonDir.includes(':')) {\n throw new Error(`${label} Git common directory has an unsupported path`)\n }\n for (const objectRoot of new Set([gitDir, commonDir])) {\n for (const name of ['alternates', 'http-alternates']) {\n const path = join(objectRoot, 'objects', 'info', name)\n try {\n const contents = await readFile(path, 'utf8')\n if (contents.trim()) throw new Error(`${label} uses forbidden Git ${name}`)\n } catch (error) {\n if (!isNoEntry(error)) throw error\n }\n }\n }\n}\n\nasync function assertCommitAndBaseTree(\n repositoryRoot: string,\n commit: string,\n expectedTree: string,\n): Promise<void> {\n const type = (await runCandidateGit(repositoryRoot, ['cat-file', '-t', commit])).stdout\n .toString('utf8')\n .trim()\n if (type !== 'commit') throw new Error(`candidate base object is not a commit: ${commit}`)\n const actualTree = (\n await runCandidateGit(repositoryRoot, ['rev-parse', `${commit}^{tree}`])\n ).stdout\n .toString('utf8')\n .trim()\n if (actualTree !== expectedTree) {\n throw new Error(`candidate base commit tree ${actualTree} does not match ${expectedTree}`)\n }\n}\n\nasync function assertSafeTree(\n repositoryRoot: string,\n tree: string,\n environment: Record<string, string> = {},\n): Promise<void> {\n const listing = (\n await runCandidateGit(\n repositoryRoot,\n ['ls-tree', '-rz', '--full-tree', tree],\n undefined,\n environment,\n )\n ).stdout\n const entries = parseTreeEntries(listing)\n if (entries.length === 0) throw new Error('candidate Git tree cannot be empty')\n for (const entry of entries) {\n if (entry.type !== 'blob' || (entry.mode !== '100644' && entry.mode !== '100755')) {\n throw new Error(\n `candidate Git tree contains a symlink, submodule, or non-blob: ${entry.path}`,\n )\n }\n assertSafeGitPath(entry.path)\n }\n}\n\nasync function workspaceManifestFromGitTree(\n repositoryRoot: string,\n tree: string,\n environment: Record<string, string>,\n): Promise<AgentCandidateWorkspaceManifestMaterial> {\n return candidateWorkspaceManifest(\n await readCandidateGitTreeFiles(repositoryRoot, tree, environment),\n )\n}\n\nexport async function readCandidateGitTreeFiles(\n repositoryRoot: string,\n tree: string,\n environment: Record<string, string> = {},\n limits?: { maxFiles: number; maxFileBytes: number; maxTotalFileBytes: number },\n): Promise<Array<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }>> {\n const listing = (\n await runCandidateGit(\n repositoryRoot,\n ['ls-tree', '-rzl', '--full-tree', tree],\n undefined,\n environment,\n )\n ).stdout\n const files: Array<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }> = []\n const entries = parseTreeEntries(listing)\n if (limits && entries.length > limits.maxFiles) {\n throw new Error('candidate Git tree exceeds maxFiles')\n }\n let totalBytes = 0\n for (const entry of entries) {\n if (entry.type !== 'blob' || (entry.mode !== '100644' && entry.mode !== '100755')) {\n throw new Error(`candidate Git tree contains a non-regular file: ${entry.path}`)\n }\n assertSafeGitPath(entry.path)\n if (entry.size === undefined) {\n throw new Error(`candidate Git tree is missing blob size: ${entry.path}`)\n }\n if (limits && entry.size > limits.maxFileBytes) {\n throw new Error(`candidate Git tree file exceeds maxFileBytes: ${entry.path}`)\n }\n totalBytes += entry.size\n if (limits && totalBytes > limits.maxTotalFileBytes) {\n throw new Error('candidate Git tree exceeds maxTotalFileBytes')\n }\n const bytes = (\n await runCandidateGit(\n repositoryRoot,\n ['cat-file', 'blob', entry.object],\n undefined,\n environment,\n )\n ).stdout\n if (bytes.byteLength !== entry.size) {\n throw new Error(`candidate Git blob size changed: ${entry.path}`)\n }\n files.push({\n path: entry.path,\n mode: entry.mode === '100755' ? 0o755 : 0o644,\n bytes: Uint8Array.from(bytes),\n })\n }\n return files.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0))\n}\n\nfunction parseTreeEntries(bytes: Uint8Array): Array<{\n mode: string\n type: string\n object: string\n size?: number\n path: string\n}> {\n const raw = Buffer.from(bytes)\n const decoded = raw.toString('utf8')\n if (!Buffer.from(decoded, 'utf8').equals(raw)) {\n throw new Error('candidate Git tree contains a non-UTF-8 path')\n }\n const rows = decoded.split('\\0').filter(Boolean)\n return rows.map((row) => {\n const tab = row.indexOf('\\t')\n const header = row.slice(0, tab).split(' ').filter(Boolean)\n const path = row.slice(tab + 1)\n const [mode, type, object, sizeText] = header\n if (tab < 1 || !mode || !type || !object || !path) {\n throw new Error('malformed Git tree entry')\n }\n const size = sizeText && /^\\d+$/.test(sizeText) ? Number(sizeText) : undefined\n if (size !== undefined && !Number.isSafeInteger(size)) {\n throw new Error('candidate Git tree entry size exceeds the safe integer range')\n }\n return { mode, type, object, ...(size === undefined ? {} : { size }), path }\n })\n}\n\nfunction assertSafeGitPath(path: string): void {\n if (\n !path ||\n path.startsWith('/') ||\n path.includes('\\\\') ||\n path.includes('\\0') ||\n hasControlCharacter(path) ||\n path.split('/').some((part) => !part || part === '.' || part === '..') ||\n path.split('/')[0]?.toLowerCase() === '.git'\n ) {\n throw new Error(`candidate Git tree contains an unsafe path: ${path}`)\n }\n}\n\nfunction parseGitHubRemote(value: string): { owner: string; repo: string } | undefined {\n const match = value.match(\n /^(?:https?:\\/\\/github\\.com\\/|ssh:\\/\\/git@github\\.com\\/|git@github\\.com:)([^/]+)\\/([^/]+?)(?:\\.git)?$/,\n )\n if (!match?.[1] || !match[2]) return undefined\n return { owner: match[1], repo: match[2] }\n}\n\nexport async function runCandidateGit(\n repositoryRoot: string,\n args: string[],\n input?: Uint8Array,\n extraEnv: Record<string, string> = {},\n options: { maxOutputBytes?: number; readUserExclusions?: boolean } = {},\n): Promise<GitResult> {\n if (\n options.readUserExclusions &&\n (args.length !== 7 ||\n args.slice(0, 4).join(',') !== 'config,--includes,--path,--default' ||\n args.slice(5).join(',') !== '--get,core.excludesFile')\n ) {\n throw new Error('user Git configuration may only supply the effective exclusion path')\n }\n if (\n options.maxOutputBytes !== undefined &&\n (!Number.isSafeInteger(options.maxOutputBytes) || options.maxOutputBytes < 0)\n ) {\n throw new Error('candidate Git maxOutputBytes must be a nonnegative safe integer')\n }\n const env = Object.fromEntries(\n Object.entries(process.env).filter(([name]) => !name.startsWith('GIT_')),\n ) as Record<string, string>\n Object.assign(env, {\n GIT_CONFIG_NOSYSTEM: '1',\n GIT_CONFIG_GLOBAL: '/dev/null',\n GIT_CONFIG_SYSTEM: '/dev/null',\n GIT_TERMINAL_PROMPT: '0',\n GIT_NO_REPLACE_OBJECTS: '1',\n LC_ALL: 'C',\n ...extraEnv,\n })\n // Only this read-only config query can consult user configuration. Commands which read blobs,\n // bundle, or restore a repository retain isolation from credentials and executable settings.\n if (options.readUserExclusions) {\n for (const name of ['GIT_CONFIG_GLOBAL', 'GIT_CONFIG_SYSTEM', 'GIT_CONFIG_NOSYSTEM']) {\n delete env[name]\n if (process.env[name] !== undefined) env[name] = process.env[name]\n }\n }\n const fullArgs = [\n '-c',\n 'core.hooksPath=/dev/null',\n '-c',\n 'core.fsmonitor=false',\n '-c',\n 'core.untrackedCache=false',\n '-c',\n 'protocol.file.allow=never',\n '-C',\n repositoryRoot,\n ...args,\n ]\n return await new Promise((resolveResult, reject) => {\n const child = spawn('git', fullArgs, { env, stdio: ['pipe', 'pipe', 'pipe'] })\n const stdout: Buffer[] = []\n const stderr: Buffer[] = []\n let outputBytes = 0\n let exceeded = false\n function retain(chunks: Buffer[], chunk: Buffer): void {\n if (exceeded) return\n outputBytes += chunk.byteLength\n if (options.maxOutputBytes !== undefined && outputBytes > options.maxOutputBytes) {\n exceeded = true\n child.kill('SIGKILL')\n return\n }\n chunks.push(chunk)\n }\n child.stdout.on('data', (chunk: Buffer) => retain(stdout, chunk))\n child.stderr.on('data', (chunk: Buffer) => retain(stderr, chunk))\n child.on('error', reject)\n child.stdin.on('error', reject)\n child.on('close', (code, signal) => {\n if (exceeded) {\n reject(new Error('candidate Git command exceeds maxOutputBytes'))\n return\n }\n const out = Buffer.concat(stdout)\n const err = Buffer.concat(stderr)\n if (code !== 0) {\n reject(\n new Error(\n `git ${args[0] ?? '<command>'} failed (${signal ?? code}): ${err.toString('utf8').trim()}`,\n ),\n )\n return\n }\n resolveResult({ stdout: out, stderr: err })\n })\n if (input) child.stdin.end(input)\n else child.stdin.end()\n })\n}\n\nfunction isNoEntry(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: string }).code === 'ENOENT'\n )\n}\n","import { randomUUID } from 'node:crypto'\nimport { constants as fsConstants } from 'node:fs'\nimport {\n lstat,\n mkdir,\n mkdtemp,\n open,\n readdir,\n readFile,\n realpath,\n rename,\n rm,\n writeFile,\n} from 'node:fs/promises'\nimport { homedir, tmpdir } from 'node:os'\nimport { dirname, join, resolve, sep } from 'node:path'\nimport type { AgentCandidateWorkspaceSnapshotEvidence } from '@tangle-network/agent-interface'\nimport {\n candidateWorkspaceManifest,\n captureMaterializedWorkspace,\n verifyMaterializedWorkspace,\n} from './artifacts'\nimport { canonicalCandidateBytes, sha256Bytes } from './digest'\nimport {\n assertNoGitIndirection,\n readCandidateGitTreeFiles,\n runCandidateGit,\n} from './git-materialize'\nimport type { AgentCandidateOutputArtifactPort, AgentCandidateWorkspacePort } from './types'\nimport {\n type AgentCandidateWorkspaceArchiveLimits,\n assertGitObjectId,\n assertWorkspaceFilesWithinLimits,\n type CapturedAgentCandidateWorkspace,\n captureWorkspaceFiles,\n decodeVerifiedWorkspaceArchive,\n safeArchivePath,\n type WorkspaceArchiveRepository,\n workspaceLimits,\n} from './workspace-archive'\n\nexport interface CaptureAgentCandidateWorkspaceOptions {\n /** Include Git HEAD so task preparation can prove its exact commit and tree. */\n includeRepository?: boolean\n /**\n * `working-tree` preserves tracked and unignored untracked regular files, deletions, exact modes,\n * and the complete bounded Git index. Git-ignored files stay excluded. Requires includeRepository.\n * The caller must hold the workspace lease against writers; observed drift fails capture.\n * The manifest digest covers files, while the archive digest also binds HEAD and the index.\n */\n repositoryContents?: 'head' | 'working-tree'\n limits?: Partial<AgentCandidateWorkspaceArchiveLimits>\n /** Use the evaluator-owned artifact store when manifest or archive bytes should not be embedded. */\n artifactPersistence?: {\n executionId: string\n outputArtifacts: AgentCandidateOutputArtifactPort\n signal?: AbortSignal\n }\n}\n\nexport interface CreateAgentCandidateWorkspacePortOptions {\n limits?: Partial<AgentCandidateWorkspaceArchiveLimits>\n}\n\n/** Capture one exact regular-file workspace for immutable candidate execution. */\nexport async function captureAgentCandidateWorkspace(\n rootInput: string,\n options: CaptureAgentCandidateWorkspaceOptions = {},\n): Promise<CapturedAgentCandidateWorkspace> {\n const root = resolve(rootInput)\n const limits = workspaceLimits(options.limits)\n if (\n options.repositoryContents !== undefined &&\n options.repositoryContents !== 'head' &&\n options.repositoryContents !== 'working-tree'\n ) {\n throw new Error('candidate repositoryContents is invalid')\n }\n if (options.repositoryContents !== undefined && !options.includeRepository) {\n throw new Error('candidate repositoryContents requires includeRepository')\n }\n const captured = options.includeRepository\n ? await captureRepository(root, limits, options.repositoryContents === 'working-tree')\n : await captureMaterializedWorkspace(root, {\n limits: {\n maxFiles: limits.maxFiles,\n maxFileBytes: limits.maxFileBytes,\n maxTotalFileBytes: limits.maxTotalFileBytes,\n },\n })\n assertWorkspaceFilesWithinLimits(captured.files, limits)\n const repository = 'repository' in captured ? captured.repository : undefined\n return captureWorkspaceFiles(captured.files, repository, limits, options.artifactPersistence)\n}\n\n/** Create the standard bounded materializer for candidate execution ports. */\nexport function createAgentCandidateWorkspacePort(\n options: CreateAgentCandidateWorkspacePortOptions = {},\n): AgentCandidateWorkspacePort {\n const limits = workspaceLimits(options.limits)\n const port: AgentCandidateWorkspacePort = {\n materialize: async ({ role, snapshot, archive, destination, signal }) => {\n await materializeAgentCandidateWorkspace({\n role,\n snapshot,\n archive,\n destination,\n limits,\n signal,\n })\n },\n }\n return Object.freeze(port)\n}\n\nasync function materializeAgentCandidateWorkspace(input: {\n role: 'task' | 'candidate' | 'knowledge' | 'memory'\n snapshot: AgentCandidateWorkspaceSnapshotEvidence\n archive: Uint8Array\n destination: string\n limits: AgentCandidateWorkspaceArchiveLimits\n signal?: AbortSignal\n}): Promise<void> {\n input.signal?.throwIfAborted()\n const decoded = await decodeVerifiedWorkspaceArchive(input)\n input.signal?.throwIfAborted()\n const destination = resolve(input.destination)\n await prepareEmptyDestination(destination, { createDestination: false })\n input.signal?.throwIfAborted()\n const staging = await mkdtemp(`${destination}.materializing-`)\n try {\n input.signal?.throwIfAborted()\n await writeWorkspaceFiles(staging, decoded.files, input.signal)\n if (decoded.repository) {\n await materializeRepository(decoded.repository, staging, input.limits, input.signal)\n }\n input.signal?.throwIfAborted()\n await verifyMaterializedWorkspace(staging, input.snapshot.material, {\n ignoredProtectedRootEntries: decoded.repository ? ['.git'] : [],\n })\n input.signal?.throwIfAborted()\n await rename(staging, destination)\n } catch (error) {\n await rm(staging, { recursive: true, force: true })\n throw error\n }\n}\n\nasync function captureRepository(\n requestedRoot: string,\n limits: AgentCandidateWorkspaceArchiveLimits,\n workingTree: boolean,\n): Promise<{\n files: Array<{ path: string; mode: number; bytes: Uint8Array }>\n repository: WorkspaceArchiveRepository\n}> {\n const requestedStats = await lstat(requestedRoot)\n if (!requestedStats.isDirectory() || requestedStats.isSymbolicLink()) {\n throw new Error('candidate repository root must be a real directory')\n }\n // Capture the RESOLVED root. The property this guards is that capture starts at one real\n // worktree root with no aliasing, which resolving satisfies directly — rejecting a symlinked\n // prefix outright does not, and makes capture impossible on macOS, where the OS itself hands\n // out temp paths under /var, a symlink to /private/var. Git reports a resolved path, so the\n // worktree-root comparison below needs the resolved form on both sides.\n const root = await realpath(requestedRoot)\n const resolvedStats = await lstat(root)\n if (!resolvedStats.isDirectory() || resolvedStats.isSymbolicLink()) {\n throw new Error('candidate repository root must resolve to a real directory')\n }\n const topLevel = (await runCandidateGit(root, ['rev-parse', '--show-toplevel'])).stdout\n .toString('utf8')\n .trim()\n if ((await realpath(resolve(topLevel))) !== root) {\n throw new Error('candidate repository capture must start at the Git worktree root')\n }\n const gitDir = resolve(\n (await runCandidateGit(root, ['rev-parse', '--absolute-git-dir'])).stdout\n .toString('utf8')\n .trim(),\n )\n if ((await realpath(gitDir)) !== gitDir || gitDir.includes(':')) {\n throw new Error('candidate repository Git object store has an unsupported path')\n }\n await assertNoGitIndirection(root, gitDir, 'candidate repository')\n const headCommit = (await runCandidateGit(root, ['rev-parse', 'HEAD'])).stdout\n .toString('utf8')\n .trim()\n const headTree = (await runCandidateGit(root, ['rev-parse', 'HEAD^{tree}'])).stdout\n .toString('utf8')\n .trim()\n assertGitObjectId(headCommit, 'HEAD')\n assertGitObjectId(headTree, 'HEAD tree')\n if (headCommit.length !== headTree.length) {\n throw new Error('candidate repository HEAD and tree use different object formats')\n }\n const working = workingTree ? await captureRepositoryWorkingTree(root, limits) : undefined\n const files = working?.files ?? (await readCandidateGitTreeFiles(root, headTree, {}, limits))\n assertWorkspaceFilesWithinLimits(files, limits)\n const reachableBytesText = (\n await runCandidateGit(root, ['rev-list', '--disk-usage', '--objects', 'HEAD'])\n ).stdout\n .toString('utf8')\n .trim()\n const reachableBytes = Number(reachableBytesText)\n if (!Number.isSafeInteger(reachableBytes) || reachableBytes < 0) {\n throw new Error('candidate repository reachable size is invalid')\n }\n if (reachableBytes > limits.maxRepositoryBundleBytes) {\n throw new Error('candidate repository exceeds maxRepositoryBundleBytes')\n }\n const temporary = await mkdtemp(join(tmpdir(), 'agent-candidate-workspace-bundle-'))\n const bundlePath = join(temporary, `${randomUUID()}.bundle`)\n try {\n await runCandidateGit(root, ['bundle', 'create', bundlePath, 'HEAD'])\n const bundle = Uint8Array.from(await readFile(bundlePath))\n if (bundle.byteLength > limits.maxRepositoryBundleBytes) {\n throw new Error('candidate repository bundle exceeds maxRepositoryBundleBytes')\n }\n if (working) {\n const after = await readRepositoryWorkingState(root, limits)\n if (\n after.paths !== working.state.paths ||\n after.index !== working.state.index ||\n (await runCandidateGit(root, ['rev-parse', 'HEAD'])).stdout.toString('utf8').trim() !==\n headCommit\n ) {\n throw new Error('candidate repository changed during working-tree capture')\n }\n const presentPaths = await existingRepositoryPaths(root, after.paths, limits)\n if (presentPaths.join('\\0') !== files.map((file) => file.path).join('\\0')) {\n throw new Error('candidate repository files changed during working-tree capture')\n }\n await verifyMaterializedWorkspace(root, candidateWorkspaceManifest(files), {\n ignoredProtectedRootEntries: ['.git'],\n selectedPaths: files.map((file) => file.path),\n })\n }\n return {\n files,\n repository: {\n headCommit,\n headTree,\n bundle: {\n sha256: sha256Bytes(bundle),\n byteLength: bundle.byteLength,\n bytes: bundle,\n },\n ...(working\n ? {\n workingTree: { files: working.state.files },\n }\n : {}),\n },\n }\n } finally {\n await rm(temporary, { recursive: true, force: true })\n }\n}\n\nasync function readRepositoryWorkingState(\n root: string,\n limits: AgentCandidateWorkspaceArchiveLimits,\n): Promise<{\n paths: string\n index: string\n files: Array<{ path: string; mode: number; bytes: Uint8Array }>\n}> {\n const env = { GIT_OPTIONAL_LOCKS: '0' }\n const listingLimit = Math.min(\n limits.maxArchiveBytes,\n limits.maxFiles * (limits.maxPathBytes + 256),\n )\n const index = new TextDecoder('utf-8', { fatal: true }).decode(\n (\n await runCandidateGit(root, ['ls-files', '--stage', '-z'], undefined, env, {\n maxOutputBytes: listingLimit,\n })\n ).stdout,\n )\n const entries = index\n .split('\\0')\n .filter(Boolean)\n .map((entry) => {\n const match = /^(100644|100755) ([a-f0-9]{40}|[a-f0-9]{64}) 0\\t(.+)$/u.exec(entry)\n if (!match)\n throw new Error('candidate working-tree capture requires a resolved regular-file Git index')\n const [, mode, object, path] = match\n if (!object || !path) throw new Error('candidate Git index is invalid')\n return {\n path: safeArchivePath(path, limits.maxPathBytes),\n mode: mode === '100755' ? 0o755 : 0o644,\n object,\n }\n })\n if (entries.length > limits.maxFiles) throw new Error('candidate Git index exceeds maxFiles')\n const debugIndex = (\n await runCandidateGit(root, ['ls-files', '--debug', '-z'], undefined, env, {\n maxOutputBytes: listingLimit,\n })\n ).stdout.toString('utf8')\n if ([...debugIndex.matchAll(/\\tflags: ([a-f0-9]+)\\n/gu)].some((match) => match[1] !== '0')) {\n throw new Error('candidate working-tree capture does not support special Git index flags')\n }\n // Inspect every staged blob's size before reading any blob. A deleted or shortened working file\n // must not conceal an oversized staged version, including highly compressible binary content.\n const sizes = entries.length\n ? (\n await runCandidateGit(\n root,\n ['cat-file', '--batch-check'],\n Buffer.from(entries.map((entry) => entry.object).join('\\n') + '\\n'),\n env,\n { maxOutputBytes: listingLimit },\n )\n ).stdout\n .toString('utf8')\n .trimEnd()\n .split('\\n')\n : []\n if (sizes.length !== entries.length)\n throw new Error('candidate Git index blob metadata is incomplete')\n let totalBytes = 0\n const byteLengths = entries.map((entry, index) => {\n const match = /^([a-f0-9]{40}|[a-f0-9]{64}) blob (\\d+)$/u.exec(sizes[index] ?? '')\n const size = Number(match?.[2])\n if (!match || match[1] !== entry.object || !Number.isSafeInteger(size) || size < 0) {\n throw new Error('candidate Git index blob metadata is invalid')\n }\n if (size > limits.maxFileBytes)\n throw new Error(`candidate Git index file exceeds maxFileBytes: ${entry.path}`)\n if (size > limits.maxTotalFileBytes - totalBytes)\n throw new Error('candidate Git index exceeds maxTotalFileBytes')\n totalBytes += size\n return size\n })\n const files: Array<{ path: string; mode: number; bytes: Uint8Array }> = []\n for (const [index, entry] of entries.entries()) {\n const bytes = (\n await runCandidateGit(root, ['cat-file', 'blob', entry.object], undefined, env, {\n maxOutputBytes: limits.maxFileBytes,\n })\n ).stdout\n if (bytes.byteLength !== byteLengths[index])\n throw new Error('candidate Git index blob size changed')\n files.push({ path: entry.path, mode: entry.mode, bytes: Uint8Array.from(bytes) })\n }\n files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))\n assertWorkspaceFilesWithinLimits(files, limits)\n const defaultExcludes = join(\n process.env.XDG_CONFIG_HOME || join(homedir(), '.config'),\n 'git',\n 'ignore',\n )\n const excludes = new TextDecoder('utf-8', { fatal: true })\n .decode(\n (\n await runCandidateGit(\n root,\n [\n 'config',\n '--includes',\n '--path',\n '--default',\n defaultExcludes,\n '--get',\n 'core.excludesFile',\n ],\n undefined,\n {},\n { maxOutputBytes: limits.maxPathBytes, readUserExclusions: true },\n )\n ).stdout,\n )\n .replace(/\\n$/u, '')\n const paths = new TextDecoder('utf-8', { fatal: true }).decode(\n (\n await runCandidateGit(\n root,\n [\n '-c',\n `core.excludesFile=${excludes}`,\n 'ls-files',\n '--cached',\n '--others',\n '--exclude-standard',\n '-z',\n ],\n undefined,\n env,\n { maxOutputBytes: listingLimit },\n )\n ).stdout,\n )\n for (const path of paths.split('\\0').filter(Boolean)) safeArchivePath(path, limits.maxPathBytes)\n return { paths, index, files }\n}\n\nasync function captureRepositoryWorkingTree(\n root: string,\n limits: AgentCandidateWorkspaceArchiveLimits,\n) {\n const state = await readRepositoryWorkingState(root, limits)\n const selectedPaths = await existingRepositoryPaths(root, state.paths, limits)\n const captured = await captureMaterializedWorkspace(root, {\n ignoredProtectedRootEntries: ['.git'],\n selectedPaths,\n limits,\n })\n const files = [...captured.files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))\n return { state, files }\n}\n\nasync function existingRepositoryPaths(\n root: string,\n listing: string,\n limits: AgentCandidateWorkspaceArchiveLimits,\n): Promise<string[]> {\n const paths = [...new Set(listing.split('\\0').filter(Boolean))].sort()\n if (paths.length > limits.maxFiles) throw new Error('candidate workspace exceeds maxFiles')\n const selectedPaths: string[] = []\n for (const path of paths) {\n const safe = safeArchivePath(path, limits.maxPathBytes)\n try {\n await lstat(workspacePath(root, safe))\n selectedPaths.push(safe)\n } catch (error) {\n if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) throw error\n }\n }\n return selectedPaths\n}\n\nexport async function prepareEmptyDestination(\n destination: string,\n options: { createDestination?: boolean } = {},\n): Promise<void> {\n await mkdir(options.createDestination === false ? dirname(destination) : destination, {\n recursive: true,\n mode: 0o700,\n })\n let stats\n try {\n stats = await lstat(destination)\n } catch (error) {\n if (options.createDestination === false && (error as NodeJS.ErrnoException).code === 'ENOENT')\n return\n throw error\n }\n if (!stats.isDirectory() || stats.isSymbolicLink()) {\n throw new Error('candidate workspace destination must be a real directory')\n }\n // A symlinked PREFIX is the OS's own doing on macOS, where temp paths live under /var, a\n // symlink to /private/var. What must hold is that the destination itself is a real\n // directory, which both this check and the lstat above require.\n const resolvedDestination = await realpath(destination)\n const resolvedStats = await lstat(resolvedDestination)\n if (!resolvedStats.isDirectory() || resolvedStats.isSymbolicLink()) {\n throw new Error('candidate workspace destination must resolve to a real directory')\n }\n if ((await readdir(destination)).length > 0) {\n throw new Error('candidate workspace destination must be empty')\n }\n}\n\nasync function writeWorkspaceFiles(\n destination: string,\n files: ReadonlyArray<{ path: string; mode: number; bytes: Uint8Array }>,\n signal?: AbortSignal,\n): Promise<void> {\n for (const file of files) {\n signal?.throwIfAborted()\n const path = workspacePath(destination, file.path)\n await mkdir(dirname(path), { recursive: true, mode: 0o700 })\n const descriptor = await open(\n path,\n fsConstants.O_WRONLY |\n fsConstants.O_CREAT |\n fsConstants.O_EXCL |\n (typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0),\n 0o600,\n )\n try {\n signal?.throwIfAborted()\n await descriptor.writeFile(file.bytes, { signal })\n const stats = await descriptor.stat()\n if (!stats.isFile() || stats.nlink !== 1) {\n throw new Error(`candidate workspace file identity changed while writing: ${file.path}`)\n }\n await descriptor.chmod(file.mode)\n signal?.throwIfAborted()\n } finally {\n await descriptor.close()\n }\n }\n}\n\nasync function materializeRepository(\n repository: WorkspaceArchiveRepository,\n destination: string,\n limits: AgentCandidateWorkspaceArchiveLimits,\n signal?: AbortSignal,\n): Promise<void> {\n signal?.throwIfAborted()\n const git = async (\n args: string[],\n bytes?: Uint8Array,\n options: { maxOutputBytes?: number } = {},\n ) => {\n signal?.throwIfAborted()\n const result = await runCandidateGit(destination, args, bytes, {}, options)\n signal?.throwIfAborted()\n return result\n }\n const temporary = await mkdtemp(join(tmpdir(), 'agent-candidate-workspace-bundle-'))\n const bundlePath = join(temporary, `${randomUUID()}.bundle`)\n try {\n signal?.throwIfAborted()\n await writeFile(bundlePath, repository.bundle.bytes, { flag: 'wx', mode: 0o600, signal })\n await git([\n 'init',\n '--quiet',\n '--initial-branch=candidate',\n `--object-format=${repository.headCommit.length === 64 ? 'sha256' : 'sha1'}`,\n ])\n await git(['bundle', 'verify', bundlePath])\n await git(['bundle', 'unbundle', bundlePath])\n const objectType = (await git(['cat-file', '-t', repository.headCommit])).stdout\n .toString('utf8')\n .trim()\n if (objectType !== 'commit') throw new Error('candidate repository HEAD is not a commit')\n const observedTree = (await git(['rev-parse', `${repository.headCommit}^{tree}`])).stdout\n .toString('utf8')\n .trim()\n if (observedTree !== repository.headTree) {\n throw new Error('candidate repository bundle HEAD tree changed')\n }\n await git(['update-ref', '--no-deref', 'HEAD', repository.headCommit])\n await git(['read-tree', repository.headTree])\n if (repository.workingTree) {\n // All staged content has passed archive limits and manifest verification before Git sees it.\n // Rebuilding an index from explicit blobs avoids binary-patch expansion and diff configuration.\n await git(['read-tree', '--empty'])\n const entries: string[] = []\n for (const file of repository.workingTree.files) {\n const object = (\n await git(['hash-object', '-w', '--stdin'], file.bytes, { maxOutputBytes: 256 })\n ).stdout\n .toString('utf8')\n .trim()\n assertGitObjectId(object, 'staged blob')\n entries.push(`${file.mode === 0o755 ? '100755' : '100644'} ${object}\\t${file.path}\\0`)\n }\n if (entries.length)\n await git(['update-index', '-z', '--index-info'], Buffer.from(entries.join('')))\n const indexTree = (await git(['write-tree'])).stdout.toString('utf8').trim()\n const observed = await readCandidateGitTreeFiles(destination, indexTree, {}, limits)\n signal?.throwIfAborted()\n if (\n !Buffer.from(canonicalCandidateBytes(candidateWorkspaceManifest(observed))).equals(\n Buffer.from(\n canonicalCandidateBytes(candidateWorkspaceManifest(repository.workingTree.files)),\n ),\n )\n )\n throw new Error('candidate repository staged files do not match the captured index')\n return\n }\n\n const status = (await git(['status', '--porcelain=v1', '--untracked-files=all'])).stdout\n .toString('utf8')\n .trim()\n if (status) throw new Error('candidate repository files do not exactly match HEAD')\n } finally {\n await rm(temporary, { recursive: true, force: true })\n }\n}\n\nexport function workspacePath(root: string, relativePath: string): string {\n const path = resolve(root, relativePath)\n if (!path.startsWith(`${root}${sep}`)) {\n throw new Error(`candidate workspace archive path escapes its destination: ${relativePath}`)\n }\n return path\n}\n","import { createHash } from 'node:crypto'\nimport { constants } from 'node:fs'\nimport { mkdir, mkdtemp, open, realpath, rename, rm } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\nimport type {\n AgentCandidateArtifactRef,\n AgentCandidateWorkspaceManifestMaterial,\n AgentCandidateWorkspaceSnapshotEvidence,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { extract, type Pack, pack } from 'tar-stream'\nimport { mapWithConcurrency } from '../runtime/util'\nimport { persistCandidateOutputArtifactStream, verifiedArtifactChunks } from './artifact-streams'\nimport { scanMaterializedWorkspaceManifest, verifyBytes } from './artifacts'\nimport { canonicalCandidateBytes, canonicalCandidateDigest, deepFreezeCandidate } from './digest'\nimport type { AgentCandidateArtifactPort } from './types'\nimport {\n type AgentCandidateWorkspaceArchiveLimits,\n assertWorkspaceFilesWithinLimits,\n workspaceLimits,\n workspaceTarHeader,\n} from './workspace-archive'\nimport {\n type CaptureAgentCandidateWorkspaceOptions,\n prepareEmptyDestination,\n workspacePath,\n} from './workspace-archive-local'\n\ntype WorkspaceFile = AgentCandidateWorkspaceManifestMaterial['files'][number]\n\n/**\n * Files a tree capture stores at once; each waits on a durable-store round trip of its own and on\n * four fsyncs. On drew-gtr-pro, with three 180 ms store requests per file, 64 at once\n * stored a 473-file workspace in 83 s and 110 s against 128 s and 139 s for 16 at once, in\n * alternating runs, holding the same 16 sync threads.\n */\nconst CAPTURE_FILES_AT_ONCE = 64\n\nexport interface CaptureAgentCandidateWorkspaceToArtifactsOptions {\n limits?: Partial<AgentCandidateWorkspaceArchiveLimits>\n /**\n * Root-relative files or directories to leave out of the capture, each by its exact path. A\n * caller whose root holds data another capture already keeps, such as a provider's retained\n * native session trees, or an environment it can rebuild, such as a virtualenv, names them here\n * instead of storing them on every capture. The manifest then describes only what was kept.\n */\n excludedPaths?: readonly string[]\n artifactPersistence: NonNullable<CaptureAgentCandidateWorkspaceOptions['artifactPersistence']>\n}\n\n/** Capture regular files to durable artifacts with memory bounded by the manifest and stream buffers. */\nexport async function captureAgentCandidateWorkspaceToArtifacts(\n rootInput: string,\n options: CaptureAgentCandidateWorkspaceToArtifactsOptions,\n): Promise<{ readonly snapshot: AgentCandidateWorkspaceSnapshotEvidence }> {\n const { outputArtifacts, executionId, signal } = options.artifactPersistence\n if (!outputArtifacts.putStream || !outputArtifacts.readStream) {\n throw new Error('streaming workspace persistence requires putStream and readStream')\n }\n if (!executionId.trim())\n throw new Error('candidate workspace artifact persistence requires an executionId')\n signal?.throwIfAborted()\n const limits = workspaceLimits(options.limits)\n const material = await scanMaterializedWorkspaceManifest(rootInput, {\n limits,\n signal,\n excludedPaths: options.excludedPaths,\n })\n validateManifest(material, limits)\n const root = await realpath(resolve(rootInput))\n const manifest = canonicalCandidateBytes(material)\n const manifestArtifact = await persistCandidateOutputArtifactStream(outputArtifacts, {\n executionId,\n purpose: 'candidate-workspace-manifest',\n chunks: oneChunk(manifest),\n maxBytes: manifest.byteLength,\n signal,\n })\n const archiveArtifact = await persistCandidateOutputArtifactStream(outputArtifacts, {\n executionId,\n purpose: 'candidate-workspace-archive',\n chunks: workspaceArchiveChunks(root, material, signal),\n maxBytes: limits.maxArchiveBytes,\n signal,\n })\n return Object.freeze({\n snapshot: deepFreezeCandidate({\n kind: 'agent-candidate-workspace-snapshot' as const,\n digest: canonicalCandidateDigest(material),\n material,\n manifest: manifestArtifact,\n archive: archiveArtifact,\n }),\n })\n}\n\n/**\n * A workspace stored as one content-addressed object per file plus the manifest that names them.\n *\n * Its digest is the manifest's, the same identity an archived capture of the same files has. Two\n * trees share every file they have in common, so storing one costs only the files no earlier\n * capture in the store holds: on Discovery Lab run terraform-dc-tokens-20261006d, the files a\n * director changed between two captures one to two minutes apart were 5.5 to 8.2 MB of a\n * 60 to 70 MB workspace.\n */\nexport interface AgentCandidateWorkspaceTree {\n readonly kind: 'agent-candidate-workspace-tree'\n /** The manifest's digest; the manifest is the object of this digest. */\n readonly digest: Sha256Digest\n readonly manifest: AgentCandidateArtifactRef\n readonly files: number\n /** The bytes of every file in the workspace. */\n readonly bytes: number\n /** The bytes this capture added to the store; every other file was already there. */\n readonly storedBytes: number\n}\n\n/**\n * Store a workspace as a tree: each regular file the store does not already hold, then the\n * manifest. The store must find objects by content (`locate`) and stream them.\n */\nexport async function captureAgentCandidateWorkspaceTreeToArtifacts(\n rootInput: string,\n options: CaptureAgentCandidateWorkspaceToArtifactsOptions,\n): Promise<AgentCandidateWorkspaceTree> {\n const { outputArtifacts, executionId, signal } = options.artifactPersistence\n if (!outputArtifacts.putStream || !outputArtifacts.readStream || !outputArtifacts.locate) {\n throw new Error('workspace tree persistence requires putStream, readStream and locate')\n }\n if (!executionId.trim())\n throw new Error('candidate workspace artifact persistence requires an executionId')\n signal?.throwIfAborted()\n const limits = workspaceLimits(options.limits)\n const material = await scanMaterializedWorkspaceManifest(rootInput, {\n limits,\n signal,\n excludedPaths: options.excludedPaths,\n })\n validateManifest(material, limits)\n const root = await realpath(resolve(rootInput))\n const bytes = material.files.reduce((sum, file) => sum + file.byteLength, 0)\n let storedBytes = 0\n // Each file's put waits for its durable copy, so one file at a time costs a store round trip\n // and its fsyncs per file: drew-gtr-pro's retire stored one 2 KB file per 1.8 s.\n // Files with the same content are one object, stored once.\n const distinct = [...new Map(material.files.map((file) => [file.sha256, file])).values()]\n const locate = outputArtifacts.locate.bind(outputArtifacts)\n await mapWithConcurrency(distinct, CAPTURE_FILES_AT_ONCE, async (file) => {\n signal?.throwIfAborted()\n const held = await locate(\n { sha256: file.sha256, byteLength: file.byteLength },\n signal === undefined ? undefined : { signal },\n )\n if (held !== undefined) return\n const stored = await persistCandidateOutputArtifactStream(outputArtifacts, {\n executionId,\n purpose: 'candidate-workspace-file',\n chunks: workspaceFileChunks(root, file, signal),\n maxBytes: file.byteLength,\n signal,\n })\n if (stored.sha256 !== file.sha256 || stored.byteLength !== file.byteLength)\n throw new Error(`workspace file changed during capture: ${file.path}`)\n storedBytes += file.byteLength\n })\n const manifestBytes = canonicalCandidateBytes(material)\n const manifest = await persistCandidateOutputArtifactStream(outputArtifacts, {\n executionId,\n purpose: 'candidate-workspace-manifest',\n chunks: oneChunk(manifestBytes),\n maxBytes: manifestBytes.byteLength,\n signal,\n })\n const digest = canonicalCandidateDigest(material)\n if (manifest.sha256 !== digest)\n throw new Error('candidate workspace manifest digest does not name its stored bytes')\n return deepFreezeCandidate({\n kind: 'agent-candidate-workspace-tree' as const,\n digest,\n manifest,\n files: material.files.length,\n bytes,\n storedBytes,\n })\n}\n\n/**\n * Read a tree back by its digest and confirm the store holds every file it names. Returns the\n * manifest; reading a file is `artifacts.read` of what `locate` returns for its digest.\n */\nexport async function verifyAgentCandidateWorkspaceTree(\n tree: Pick<AgentCandidateWorkspaceTree, 'digest' | 'manifest'>,\n artifacts: AgentCandidateArtifactPort,\n options: { limits?: Partial<AgentCandidateWorkspaceArchiveLimits>; signal?: AbortSignal } = {},\n): Promise<AgentCandidateWorkspaceManifestMaterial> {\n const { signal } = options\n if (!artifacts.locate) throw new Error('workspace tree verification requires locate')\n if (tree.manifest.sha256 !== tree.digest)\n throw new Error('workspace tree digest does not name its manifest')\n signal?.throwIfAborted()\n // A durable store that holds evicted objects serves them as streams; its buffered read may refuse.\n let bytes: Uint8Array\n if (artifacts.readStream) {\n const chunks: Uint8Array[] = []\n for await (const chunk of verifiedArtifactChunks(tree.manifest, artifacts, signal))\n chunks.push(chunk)\n bytes = Buffer.concat(chunks)\n } else bytes = await artifacts.read(tree.manifest)\n verifyBytes(bytes, tree.manifest.sha256, tree.manifest.byteLength, 'workspace tree manifest')\n const material = JSON.parse(\n Buffer.from(bytes).toString('utf8'),\n ) as AgentCandidateWorkspaceManifestMaterial\n validateManifest(material, workspaceLimits(options.limits))\n if (canonicalCandidateDigest(material) !== tree.digest)\n throw new Error('workspace tree manifest is not canonical')\n for (const file of material.files) {\n signal?.throwIfAborted()\n const held = await artifacts.locate(\n { sha256: file.sha256, byteLength: file.byteLength },\n signal === undefined ? undefined : { signal },\n )\n if (held === undefined) throw new Error(`workspace tree file is not in the store: ${file.path}`)\n }\n return material\n}\n\nexport interface AgentCandidateWorkspaceArtifactsOptions {\n role: 'task' | 'candidate' | 'knowledge' | 'memory'\n snapshot: AgentCandidateWorkspaceSnapshotEvidence\n artifacts: AgentCandidateArtifactPort\n limits?: Partial<AgentCandidateWorkspaceArchiveLimits>\n signal?: AbortSignal\n}\n\n/** Verify durable regular-file workspace evidence without retaining archive or file contents. */\nexport async function verifyAgentCandidateWorkspaceArtifacts(\n input: AgentCandidateWorkspaceArtifactsOptions,\n): Promise<void> {\n await consumeWorkspaceArtifacts(input)\n}\n\n/** Read selected files only after the existing verifier has accepted the entire archive. */\nexport async function readAgentCandidateWorkspaceArtifactFiles(\n input: AgentCandidateWorkspaceArtifactsOptions & {\n readonly paths: readonly string[]\n readonly maxReadBytes: number\n },\n): Promise<ReadonlyMap<string, Uint8Array>> {\n if (!Number.isSafeInteger(input.maxReadBytes) || input.maxReadBytes < 0)\n throw new Error('workspace selective read requires a non-negative safe maxReadBytes')\n const selected = new Map<string, Uint8Array[]>()\n const files = new Map(input.snapshot.material.files.map((file) => [file.path, file]))\n let bytes = 0\n for (const path of input.paths) {\n if (selected.has(path)) throw new Error('workspace selective read repeats a path')\n const file = files.get(path)\n if (!file) throw new Error(`workspace selective read names a missing file: ${path}`)\n bytes += file.byteLength\n if (!Number.isSafeInteger(bytes) || bytes > input.maxReadBytes)\n throw new Error('workspace selective read exceeds maxReadBytes')\n selected.set(path, [])\n }\n await consumeWorkspaceArtifacts(input, undefined, selected)\n return new Map([...selected].map(([path, chunks]) => [path, Buffer.concat(chunks)]))\n}\n\n/** Restore regular files into an empty destination after complete verification; paths selects a subset. */\nexport async function materializeAgentCandidateWorkspaceFromArtifacts(\n input: AgentCandidateWorkspaceArtifactsOptions & {\n destination: string\n paths?: readonly string[]\n },\n): Promise<void> {\n input.signal?.throwIfAborted()\n if (!input.artifacts.readStream)\n throw new Error('streaming workspace artifacts require readStream')\n const paths = input.paths === undefined ? undefined : new Set(input.paths)\n if (paths && paths.size !== input.paths?.length)\n throw new Error('workspace selection must name unique manifest files')\n const destination = resolve(input.destination)\n await prepareEmptyDestination(destination)\n const staging = await mkdtemp(`${destination}.materializing-`)\n try {\n await consumeWorkspaceArtifacts(input, staging, undefined, paths)\n input.signal?.throwIfAborted()\n await rename(staging, destination)\n } catch (error) {\n await rm(staging, { recursive: true, force: true })\n throw error\n }\n}\n\nasync function consumeWorkspaceArtifacts(\n input: AgentCandidateWorkspaceArtifactsOptions,\n destination?: string,\n selected?: Map<string, Uint8Array[]>,\n paths?: ReadonlySet<string>,\n): Promise<void> {\n const { artifacts, signal } = input\n const snapshot = deepFreezeCandidate(structuredClone(input.snapshot))\n signal?.throwIfAborted()\n if (!artifacts.readStream) throw new Error('streaming workspace artifacts require readStream')\n const limits = workspaceLimits(input.limits)\n validateManifest(snapshot.material, limits)\n if (paths) {\n const files = new Set(snapshot.material.files.map((file) => file.path))\n if ([...paths].some((path) => !files.has(path)))\n throw new Error('workspace selection must name unique manifest files')\n }\n if (snapshot.archive.byteLength > limits.maxArchiveBytes)\n throw new Error('candidate workspace archive exceeds maxArchiveBytes')\n const manifest = canonicalCandidateBytes(snapshot.material)\n verifyBytes(\n manifest,\n snapshot.manifest.sha256,\n snapshot.manifest.byteLength,\n 'candidate workspace manifest',\n )\n if (canonicalCandidateDigest(snapshot.material) !== snapshot.digest)\n throw new Error('workspace snapshot digest does not match its canonical manifest material')\n let offset = 0\n for await (const chunk of verifiedArtifactChunks(snapshot.manifest, artifacts, signal)) {\n if (\n !Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength).equals(\n manifest.subarray(offset, offset + chunk.byteLength),\n )\n ) {\n throw new Error('workspace manifest artifact is not the exact canonical manifest material')\n }\n offset += chunk.byteLength\n }\n\n const parser = extract()\n const canonical = pack()\n const canonicalResult = digestChunks(canonical, limits.maxArchiveBytes, signal)\n // Both drains start before writing, so tar-stream's backpressure bounds every queue.\n const reading = pipeline(\n Readable.from(verifiedArtifactChunks(snapshot.archive, artifacts, signal)),\n parser as unknown as NodeJS.WritableStream,\n { signal },\n )\n reading.catch(() => undefined)\n canonicalResult.catch(() => undefined)\n try {\n let index = 0\n for await (const entry of parser) {\n signal?.throwIfAborted()\n const expected = snapshot.material.files[index++]\n if (\n !expected ||\n entry.header.type !== 'file' ||\n entry.header.name !== `workspace/${expected.path}` ||\n entry.header.mode !== expected.mode ||\n entry.header.size !== expected.byteLength\n ) {\n throw new Error('candidate workspace archive does not match its snapshot manifest')\n }\n const file =\n destination && (!paths || paths.has(expected.path))\n ? await openDestination(destination, expected.path)\n : undefined\n try {\n async function* checked(): AsyncGenerator<Uint8Array> {\n const hash = createHash('sha256')\n let byteLength = 0\n for await (const chunk of entry) {\n if (!(chunk instanceof Uint8Array))\n throw new Error('workspace entry emitted a non-byte chunk')\n signal?.throwIfAborted()\n byteLength += chunk.byteLength\n if (byteLength > expected!.byteLength)\n throw new Error('workspace entry exceeds its manifest length')\n hash.update(chunk)\n if (file) await file.writeFile(chunk)\n selected?.get(expected!.path)?.push(Uint8Array.from(chunk))\n yield chunk\n }\n if (\n byteLength !== expected!.byteLength ||\n `sha256:${hash.digest('hex')}` !== expected!.sha256\n ) {\n throw new Error('candidate workspace archive does not match its snapshot manifest')\n }\n }\n await appendTarFile(canonical, expected, checked(), signal)\n if (file) await file.chmod(expected.mode)\n } finally {\n await file?.close()\n }\n }\n if (index !== snapshot.material.files.length)\n throw new Error('candidate workspace archive does not match its snapshot manifest')\n await reading\n canonical.finalize()\n const observed = await canonicalResult\n if (\n observed.byteLength !== snapshot.archive.byteLength ||\n observed.sha256 !== snapshot.archive.sha256\n ) {\n throw new Error('candidate workspace tar is not canonical')\n }\n } catch (error) {\n parser.destroy(asError(error))\n canonical.destroy(asError(error))\n await Promise.allSettled([reading, canonicalResult])\n throw error\n }\n}\n\nasync function openDestination(destination: string, relativePath: string) {\n const path = workspacePath(destination, relativePath)\n await mkdir(dirname(path), { recursive: true, mode: 0o700 })\n return open(\n path,\n constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,\n 0o600,\n )\n}\n\nasync function* workspaceArchiveChunks(\n root: string,\n material: AgentCandidateWorkspaceManifestMaterial,\n signal?: AbortSignal,\n): AsyncGenerator<Uint8Array> {\n const archive = pack()\n const writing = (async () => {\n try {\n for (const file of material.files) {\n signal?.throwIfAborted()\n await appendTarFile(archive, file, workspaceFileChunks(root, file, signal), signal)\n }\n archive.finalize()\n } catch (error) {\n archive.destroy(asError(error))\n throw error\n }\n })()\n writing.catch(() => undefined)\n try {\n for await (const chunk of archive) {\n if (!(chunk instanceof Uint8Array))\n throw new Error('workspace archive emitted a non-byte chunk')\n signal?.throwIfAborted()\n yield chunk\n }\n await writing\n } finally {\n archive.destroy()\n await writing.catch(() => undefined)\n }\n}\n\nasync function* workspaceFileChunks(\n root: string,\n expected: WorkspaceFile,\n signal?: AbortSignal,\n): AsyncGenerator<Uint8Array> {\n const path = workspacePath(root, expected.path)\n if ((await realpath(path)) !== path)\n throw new Error(`workspace file path changed during capture: ${expected.path}`)\n const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)\n try {\n const stats = await file.stat()\n if (\n !stats.isFile() ||\n stats.nlink !== 1 ||\n stats.size !== expected.byteLength ||\n (stats.mode & 0o777) !== expected.mode\n ) {\n throw new Error(`workspace file changed during capture: ${expected.path}`)\n }\n const hash = createHash('sha256')\n let byteLength = 0\n for await (const chunk of file.createReadStream({\n autoClose: false,\n highWaterMark: 64 * 1024,\n })) {\n signal?.throwIfAborted()\n byteLength += chunk.byteLength\n if (byteLength > expected.byteLength)\n throw new Error(`workspace file changed during capture: ${expected.path}`)\n hash.update(chunk)\n yield chunk\n }\n if (byteLength !== expected.byteLength || `sha256:${hash.digest('hex')}` !== expected.sha256) {\n throw new Error(`workspace file changed during capture: ${expected.path}`)\n }\n } finally {\n await file.close()\n }\n}\n\nasync function appendTarFile(\n archive: Pack,\n file: WorkspaceFile,\n chunks: AsyncIterable<Uint8Array>,\n signal?: AbortSignal,\n): Promise<void> {\n const entry = archive.entry(\n workspaceTarHeader(`workspace/${file.path}`, file.mode, file.byteLength),\n )\n await pipeline(Readable.from(chunks), entry as unknown as NodeJS.WritableStream, { signal })\n}\n\nasync function digestChunks(\n chunks: AsyncIterable<unknown>,\n maxBytes: number,\n signal?: AbortSignal,\n) {\n const hash = createHash('sha256')\n let byteLength = 0\n for await (const chunk of chunks) {\n if (!(chunk instanceof Uint8Array))\n throw new Error('workspace archive emitted a non-byte chunk')\n signal?.throwIfAborted()\n byteLength += chunk.byteLength\n if (byteLength > maxBytes)\n throw new Error('candidate workspace archive exceeds maxArchiveBytes')\n hash.update(chunk)\n }\n return { sha256: `sha256:${hash.digest('hex')}`, byteLength }\n}\n\nfunction validateManifest(\n material: AgentCandidateWorkspaceManifestMaterial,\n limits: AgentCandidateWorkspaceArchiveLimits,\n): void {\n if (material.kind !== 'agent-candidate-workspace-manifest')\n throw new Error('candidate workspace has an invalid manifest kind')\n assertWorkspaceFilesWithinLimits(material.files, limits)\n}\n\nasync function* oneChunk(bytes: Uint8Array): AsyncGenerator<Uint8Array> {\n yield bytes\n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,aAAa,SAAS,YACxB,MAAM,IAAI,MAAM,0CAA0C,SAAS,MAAM;GAC3E,KAAK,OAAO,KAAK;GACjB,MAAM;EACR;EACA,IAAI,eAAe,SAAS,cAAc,UAAU,KAAK,OAAO,KAAK,QAAQ,SAAS,QACpF,MAAM,IAAI,MAAM,0CAA0C,SAAS,MAAM;CAE7E,UAAU;EACR,MAAM,KAAK,MAAM;CACnB;AACF;AAEA,eAAe,cACb,SACA,MACA,QACA,QACe;CACf,MAAM,QAAQ,QAAQ,MACpB,mBAAmB,aAAa,KAAK,QAAQ,KAAK,MAAM,KAAK,UAAU,CACzE;CACA,MAAM,SAAS,SAAS,KAAK,MAAM,GAAG,OAA2C,EAAE,OAAO,CAAC;AAC7F;AAEA,eAAe,aACb,QACA,UACA,QACA;CACA,MAAM,OAAO,WAAW,QAAQ;CAChC,IAAI,aAAa;CACjB,WAAW,MAAM,SAAS,QAAQ;EAChC,IAAI,EAAE,iBAAiB,aACrB,MAAM,IAAI,MAAM,4CAA4C;EAC9D,QAAQ,eAAe;EACvB,cAAc,MAAM;EACpB,IAAI,aAAa,UACf,MAAM,IAAI,MAAM,qDAAqD;EACvE,KAAK,OAAO,KAAK;CACnB;CACA,OAAO;EAAE,QAAQ,UAAU,KAAK,OAAO,KAAK;EAAK;CAAW;AAC9D;AAEA,SAAS,iBACP,UACA,QACM;CACN,IAAI,SAAS,SAAS,sCACpB,MAAM,IAAI,MAAM,kDAAkD;CACpE,iCAAiC,SAAS,OAAO,MAAM;AACzD;AAEA,gBAAgB,SAAS,OAA+C;CACtE,MAAM;AACR;AACA,SAAS,QAAQ,OAAuB;CACtC,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AACjE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-runtime",
3
- "version": "9.0.7",
3
+ "version": "9.0.10",
4
4
  "description": "Shared task-lifecycle skeleton for agents: a recursive loop kernel for chat turns, one-shot tasks, and multi-attempt loops, with trace capture and eval-gated self-improvement. Domain behavior lives in adapters; scoring and ship-gates in @tangle-network/agent-eval.",
5
5
  "homepage": "https://github.com/tangle-network/agent-runtime#readme",
6
6
  "repository": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"graph-registry-D0FE9VpR.js","names":[],"sources":["../src/json-data.ts","../src/runtime/supervise/continuation-data.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 { z } from 'zod'\nimport { resolveJsonPointer } from '../../mcp/tools/coordination-map-routing'\nimport type { RouteWhen } from '../../mcp/tools/coordination-route-contracts'\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/** 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 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(z.string().min(1)).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 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 /** 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 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, 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 ...(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 const revisionPath = join(reg.root, GRAPHS_DIR, `${stored.digest}.json`)\n try {\n const { digest: existingDigest, ...existing } = JSON.parse(\n await readFile(revisionPath, 'utf8'),\n ) as StoredGraph\n if (existingDigest !== stored.digest || graphDigest(existing) !== stored.digest)\n throw new ValidationError(\n 'graph-registry: stored graph revision is immutable but its content differs',\n )\n } catch (error) {\n if (!isNoEntError(error)) throw error\n // Content-addressed revisions are immutable. Rewriting one on every run adds\n // an unnecessary durable publication to the record lock's critical section.\n writeAtomicDurableFile(revisionPath, JSON.stringify(stored), { preserveMode: true })\n }\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/** Load a stored graph by digest. */\nexport async function loadGraph(\n reg: GraphRegistryDir,\n digest: string,\n): Promise<StoredGraph | undefined> {\n try {\n return JSON.parse(\n await readFile(join(reg.root, GRAPHS_DIR, `${digest}.json`), 'utf8'),\n ) as StoredGraph\n } catch {\n return undefined\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}\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