@tangle-network/agent-runtime 9.0.16 → 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/dist/{activation-y6NAn3sW.d.ts → activation-CDlOqX5a.d.ts} +7 -8
  3. package/dist/{activation-DgT20fzX.js → activation-CEGkyzEG.js} +2 -2
  4. package/dist/{activation-DgT20fzX.js.map → activation-CEGkyzEG.js.map} +1 -1
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +3 -3
  7. package/dist/candidate-execution/index.d.ts +3 -0
  8. package/dist/candidate-execution/index.js +10 -3
  9. package/dist/candidate-execution/index.js.map +1 -1
  10. package/dist/{delegate-Cmu5OF3M.js → delegate-V2Nz8GgO.js} +2 -2
  11. package/dist/{delegate-Cmu5OF3M.js.map → delegate-V2Nz8GgO.js.map} +1 -1
  12. package/dist/{coordination-manager-CFtnSLPw.js → driver-control-acknowledgers-CJDYLJmW.js} +1042 -1042
  13. package/dist/driver-control-acknowledgers-CJDYLJmW.js.map +1 -0
  14. package/dist/durable.d.ts +5 -5
  15. package/dist/durable.js +13 -13
  16. package/dist/durable.js.map +1 -1
  17. package/dist/{failure-cause-WifbY42M.js → failure-cause-BI7cfDWx.js} +14 -2
  18. package/dist/failure-cause-BI7cfDWx.js.map +1 -0
  19. package/dist/{graph-registry-B_1C7qye.js → graph-registry-DxhlgHdA.js} +1 -1
  20. package/dist/{graph-registry-BbZN5deo.js → graph-registry-j9t9J0KT.js} +11 -12
  21. package/dist/{graph-registry-BbZN5deo.js.map → graph-registry-j9t9J0KT.js.map} +1 -1
  22. package/dist/{graph-DqtIiS94.js → graph-wJOMQ1kC.js} +8 -8
  23. package/dist/{graph-DqtIiS94.js.map → graph-wJOMQ1kC.js.map} +1 -1
  24. package/dist/{improve-B0vNv6e7.js → improve-DOjywiPq.js} +42 -26
  25. package/dist/{improve-B0vNv6e7.js.map → improve-DOjywiPq.js.map} +1 -1
  26. package/dist/index.d.ts +38 -6
  27. package/dist/index.js +59 -20
  28. package/dist/index.js.map +1 -1
  29. package/dist/intelligence.d.ts +93 -63
  30. package/dist/intelligence.js +166 -73
  31. package/dist/intelligence.js.map +1 -1
  32. package/dist/kernel.d.ts +3 -3
  33. package/dist/kernel.js +16 -15
  34. package/dist/{loop-runner-BvVdDdZC.js → loop-runner-CPTOzSol.js} +2 -2
  35. package/dist/{loop-runner-BvVdDdZC.js.map → loop-runner-CPTOzSol.js.map} +1 -1
  36. package/dist/{loop-runner-CfMOsISJ.d.ts → loop-runner-DwxZbYW5.d.ts} +2 -2
  37. package/dist/loop-runner-bin.d.ts +1 -1
  38. package/dist/loop-runner-bin.js +1 -1
  39. package/dist/mcp/bin.js +3 -3
  40. package/dist/mcp/index.d.ts +1 -1
  41. package/dist/mcp/index.js +7 -7
  42. package/dist/mcp/memory-bin.js +1 -1
  43. package/dist/{model-policy-CZwhXp8O.js → model-policy-CqDuBTq-.js} +12 -2
  44. package/dist/model-policy-CqDuBTq-.js.map +1 -0
  45. package/dist/{prepare-Cw4ZaN01.js → prepare-DT-ibRsm.js} +2 -2
  46. package/dist/{prepare-Cw4ZaN01.js.map → prepare-DT-ibRsm.js.map} +1 -1
  47. package/dist/profiles.d.ts +1 -1
  48. package/dist/profiles.js +1 -1
  49. package/dist/{provision-supervisor-BjKluSKl.js → provision-supervisor-B1_Kow9m.js} +6 -6
  50. package/dist/{provision-supervisor-BjKluSKl.js.map → provision-supervisor-B1_Kow9m.js.map} +1 -1
  51. package/dist/{run-cancellation-BvGEEwRG.js → run-cancellation-D5m6JHPH.js} +2 -2
  52. package/dist/{run-cancellation-BvGEEwRG.js.map → run-cancellation-D5m6JHPH.js.map} +1 -1
  53. package/dist/{run-state-Dd_AjWd6.js → run-state-DKOXe08H.js} +5 -5
  54. package/dist/{run-state-Dd_AjWd6.js.map → run-state-DKOXe08H.js.map} +1 -1
  55. package/dist/{runtime-7VEM9muH.js → runtime-C5cWSMqU.js} +191 -24
  56. package/dist/runtime-C5cWSMqU.js.map +1 -0
  57. package/dist/{search-executor-Dqtm1fOC.js → search-executor-CA6fTYWz.js} +5 -5
  58. package/dist/{search-executor-Dqtm1fOC.js.map → search-executor-CA6fTYWz.js.map} +1 -1
  59. package/dist/{server-B8Kmit_v.js → server-C8Z3vYdI.js} +4 -4
  60. package/dist/{server-B8Kmit_v.js.map → server-C8Z3vYdI.js.map} +1 -1
  61. package/dist/{settle-record-BvH2-Ao5.js → settle-record-BDxPAO4m.js} +2 -2
  62. package/dist/{settle-record-BvH2-Ao5.js.map → settle-record-BDxPAO4m.js.map} +1 -1
  63. package/dist/{structural-rollout-CYc8PE2N.js → structural-rollout-B0HPcP9G.js} +5 -5
  64. package/dist/{structural-rollout-CYc8PE2N.js.map → structural-rollout-B0HPcP9G.js.map} +1 -1
  65. package/dist/{supervise-BayNu7qZ.js → supervise-Dvj-8S6D.js} +2341 -2283
  66. package/dist/supervise-Dvj-8S6D.js.map +1 -0
  67. package/dist/{supervision-discovery-Ca4QO4rG.js → supervision-discovery-CbrwcgJy.js} +3 -3
  68. package/dist/{supervision-discovery-Ca4QO4rG.js.map → supervision-discovery-CbrwcgJy.js.map} +1 -1
  69. package/dist/{supervisor-Bx21Hy27.js → supervisor-DwdeUC2l.js} +218 -47
  70. package/dist/supervisor-DwdeUC2l.js.map +1 -0
  71. package/dist/{supervisor-accounting-StDNW1YT.js → supervisor-accounting-C48Yo9QC.js} +507 -341
  72. package/dist/supervisor-accounting-C48Yo9QC.js.map +1 -0
  73. package/dist/testing.d.ts +1 -1
  74. package/dist/testing.js +11 -11
  75. package/dist/{tool-server-CirrqFlr.js → tool-server-DsCeBr-C.js} +2 -2
  76. package/dist/{tool-server-CirrqFlr.js.map → tool-server-DsCeBr-C.js.map} +1 -1
  77. package/dist/{top-web-Cg7ywIkF.js → top-web-CTOq4psb.js} +6 -6
  78. package/dist/{top-web-Cg7ywIkF.js.map → top-web-CTOq4psb.js.map} +1 -1
  79. package/dist/tui/bin.js +3 -3
  80. package/dist/tui/index.d.ts +1 -1
  81. package/dist/tui/index.js +2 -2
  82. package/dist/{types-_j53efrk.d.ts → types-lnF0wIJW.d.ts} +8245 -8153
  83. package/dist/{workspace-streams-BakRr-Pl.js → workspace-streams-C7PGLAUd.js} +3 -3
  84. package/dist/workspace-streams-C7PGLAUd.js.map +1 -0
  85. package/package.json +5 -4
  86. package/dist/coordination-manager-CFtnSLPw.js.map +0 -1
  87. package/dist/failure-cause-WifbY42M.js.map +0 -1
  88. package/dist/model-policy-CZwhXp8O.js.map +0 -1
  89. package/dist/runtime-7VEM9muH.js.map +0 -1
  90. package/dist/supervise-BayNu7qZ.js.map +0 -1
  91. package/dist/supervisor-Bx21Hy27.js.map +0 -1
  92. package/dist/supervisor-accounting-StDNW1YT.js.map +0 -1
  93. package/dist/workspace-streams-BakRr-Pl.js.map +0 -1
@@ -467,7 +467,7 @@ function workspaceLimits(overrides) {
467
467
  return Object.freeze(limits);
468
468
  }
469
469
  function safeArchivePath(value, maxPathBytes) {
470
- if (typeof value !== "string" || !value || !isWellFormedUnicode(value) || Buffer.byteLength(value, "utf8") > maxPathBytes || isAbsolute(value) || win32.isAbsolute(value) || value.includes("\\") || value.includes("\0") || hasControlCharacter(value) || value.split("/").some((part) => !part || part === "." || part === "..") || [".git", ".sidecar"].includes(value.split("/")[0]?.toLowerCase() ?? "")) throw new Error(`candidate workspace archive contains an unsafe path: ${String(value)}`);
470
+ if (typeof value !== "string" || !isWellFormedUnicode(value) || Buffer.byteLength(value, "utf8") > maxPathBytes || isAbsolute(value) || win32.isAbsolute(value) || value.includes("\\") || value.includes("\0") || hasControlCharacter(value) || value.split("/").some((part) => !part || part === "." || part === "..") || [".git", ".sidecar"].includes(value.split("/")[0]?.toLowerCase() ?? "") || value.split("/").some((part) => part.toLowerCase() === ".agent-home")) throw new Error(`candidate workspace archive contains an unsafe path: ${String(value)}`);
471
471
  return value;
472
472
  }
473
473
  function assertWorkspacePathOrder(path, previousPath, observedPaths, errorMessage) {
@@ -1536,6 +1536,6 @@ async function* oneChunk(bytes) {
1536
1536
  function asError(error) {
1537
1537
  return error instanceof Error ? error : new Error(String(error));
1538
1538
  }
1539
- export { isWellFormedUnicode as _, verifyAgentCandidateWorkspaceArtifacts as a, hasControlCharacter as b, createAgentCandidateWorkspacePort as c, verifyTaskCheckout as d, verifyTaskOutcomePatch as f, assertExactObjectKeys as g, workspaceLimits as h, readAgentCandidateWorkspaceArtifactFiles as i, readCandidateGitHubResource as l, safeArchivePath as m, captureAgentCandidateWorkspaceTreeToArtifacts as n, verifyAgentCandidateWorkspaceTree as o, captureAgentCandidateWorkspaceFiles as p, materializeAgentCandidateWorkspaceFromArtifacts as r, captureAgentCandidateWorkspace as s, captureAgentCandidateWorkspaceToArtifacts as t, verifyCandidateCode as u, markPutStreamVerified as v, verifiedArtifactChunks as y };
1539
+ export { assertExactObjectKeys as _, verifyAgentCandidateWorkspaceArtifacts as a, verifiedArtifactChunks as b, createAgentCandidateWorkspacePort as c, verifyCandidateCode as d, verifyTaskCheckout as f, workspaceLimits as g, safeArchivePath as h, readAgentCandidateWorkspaceArtifactFiles as i, readCandidateGitHubResource as l, captureAgentCandidateWorkspaceFiles as m, captureAgentCandidateWorkspaceTreeToArtifacts as n, verifyAgentCandidateWorkspaceTree as o, verifyTaskOutcomePatch as p, materializeAgentCandidateWorkspaceFromArtifacts as r, captureAgentCandidateWorkspace as s, captureAgentCandidateWorkspaceToArtifacts as t, readCandidateGitTreeFiles as u, isWellFormedUnicode as v, hasControlCharacter as x, markPutStreamVerified as y };
1540
1540
 
1541
- //# sourceMappingURL=workspace-streams-BakRr-Pl.js.map
1541
+ //# sourceMappingURL=workspace-streams-C7PGLAUd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workspace-streams-C7PGLAUd.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 !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 value.split('/').some((part) => part.toLowerCase() === '.agent-home')\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}\nfunction asError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error))\n}\n"],"mappings":";;;;;;;;;;;;;;;;AACA,SAAgB,oBAAoB,OAAwB;CAC1D,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS;EACjD,MAAM,OAAO,MAAM,WAAW,KAAK;EACnC,IAAI,OAAO,MAAQ,SAAS,KAAM,OAAO;CAC3C;CACA,OAAO;AACT;;;ACOA,gBAAuB,uBACrB,UACA,MACA,QAC4B;CAC5B,QAAQ,eAAe;CACvB,IAAI,EAAE,aAAa,aAAa,CAAC,KAAK,YACpC,MAAM,IAAI,MAAM,kDAAkD;CAEpE,MAAM,SACJ,aAAa,WACT,CAAC,OAAO,KAAK,SAAS,SAAS,QAAQ,CAAC,IACxC,KAAK,WAAY,UAAU,EAAE,OAAO,CAAC;CAC3C,MAAM,OAAO,WAAW,QAAQ;CAChC,IAAI,aAAa;CACjB,WAAW,MAAM,SAAS,QAAQ;EAChC,QAAQ,eAAe;EACvB,IAAI,EAAE,iBAAiB,aACrB,MAAM,IAAI,MAAM,6CAA6C;EAC/D,cAAc,MAAM;EACpB,IAAI,aAAa,SAAS,YACxB,MAAM,IAAI,MAAM,gDAAgD;EAClE,KAAK,OAAO,KAAK;EACjB,MAAM;CACR;CACA,QAAQ,eAAe;CACvB,IAAI,eAAe,SAAS,cAAc,UAAU,KAAK,OAAO,KAAK,QAAQ,SAAS,QACpF,MAAM,IAAI,MAAM,yDAAyD;AAE7E;AAEA,MAAM,oCAAoB,IAAI,QAAwB;;;;;;AAOtD,SAAgB,sBAAsB,WAAmB,YAA0B;CACjF,kBAAkB,IAAI,WAAW,UAAU;AAC7C;;AAGA,SAAgB,oBAAoB,MAAiD;CACnF,OACE,KAAK,cAAc,KAAA,KACnB,KAAK,eAAe,K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AAK,CAAC;AACjE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-runtime",
3
- "version": "9.0.16",
3
+ "version": "10.0.0",
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": {
@@ -119,7 +119,7 @@
119
119
  "@arethetypeswrong/cli": "0.18.5",
120
120
  "@biomejs/biome": "^2.6.4",
121
121
  "@modelcontextprotocol/sdk": "1.32.2",
122
- "@tangle-network/agent-eval": "1.0.25",
122
+ "@tangle-network/agent-eval": "1.0.32",
123
123
  "@tangle-network/agent-interface": "5.10.24",
124
124
  "@tangle-network/agent-provider-cli-bridge": "2.0.10",
125
125
  "@tangle-network/agent-provider-daytona": "0.8.0",
@@ -146,8 +146,8 @@
146
146
  },
147
147
  "license": "MIT",
148
148
  "peerDependencies": {
149
- "@tangle-network/agent-eval": "^1.0.1",
150
- "@tangle-network/agent-interface": "^5.10.19",
149
+ "@tangle-network/agent-eval": "^1.0.32",
150
+ "@tangle-network/agent-interface": "^5.10.24",
151
151
  "@tangle-network/sandbox": "^1.0.265"
152
152
  },
153
153
  "dependencies": {
@@ -156,6 +156,7 @@
156
156
  "@tangle-network/agent-knowledge": "^23.0.0",
157
157
  "@tangle-network/agent-profile-materialize": "^1.1.64",
158
158
  "@tangle-network/agent-trace-contract": "^2.2.2",
159
+ "@tangle-network/harness-sessions": "^1.0.13",
159
160
  "tar-stream": "3.2.2",
160
161
  "yaml": "2.9.1",
161
162
  "zod": "^4.6.6"