@tangle-network/agent-runtime 0.301.0 → 0.306.1
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.
- package/dist/{activation-V6aaOlZV.js → activation-C5wesfzd.js} +3 -3
- package/dist/{activation-V6aaOlZV.js.map → activation-C5wesfzd.js.map} +1 -1
- package/dist/{activation-CRgEJutr.d.ts → activation-wZ-8vOjV.d.ts} +88 -13
- package/dist/agent.d.ts +2 -2
- package/dist/agent.js +2 -2
- package/dist/{bundle-C9v5TH_H.js → bundle-C8EO05u3.js} +2 -2
- package/dist/{bundle-C9v5TH_H.js.map → bundle-C8EO05u3.js.map} +1 -1
- package/dist/candidate-execution/index.d.ts +3 -26
- package/dist/candidate-execution/index.js +6 -6
- package/dist/{coordination-driver-vNrdQBSH.js → coordination-driver-yj9HPXef.js} +9 -16
- package/dist/coordination-driver-yj9HPXef.js.map +1 -0
- package/dist/{delegate-B-jFJcbW.js → delegate-KtrL9HWq.js} +2 -2
- package/dist/{delegate-B-jFJcbW.js.map → delegate-KtrL9HWq.js.map} +1 -1
- package/dist/durable.d.ts +3 -15
- package/dist/durable.js +158 -124
- package/dist/durable.js.map +1 -1
- package/dist/{graph-Dwv_hQB_.js → graph-DcdyHbgf.js} +4 -5
- package/dist/graph-DcdyHbgf.js.map +1 -0
- package/dist/{improvement-cycle-Cf37Kexd.js → improvement-cycle-DsN-TVXR.js} +1129 -10
- package/dist/improvement-cycle-DsN-TVXR.js.map +1 -0
- package/dist/{index-CxBVmgqL.d.ts → index-DflDZq_I.d.ts} +50 -688
- package/dist/index.d.ts +378 -12
- package/dist/index.js +223 -320
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +5 -5
- package/dist/intelligence.js +7 -8
- package/dist/intelligence.js.map +1 -1
- package/dist/kernel.d.ts +4 -4
- package/dist/kernel.js +9 -9
- package/dist/{loop-runner-bin-DiTNiJNs.d.ts → loop-runner-bin-DZfRUVWy.d.ts} +3 -3
- package/dist/{loop-runner-bin-C8MI8N1A.js → loop-runner-bin-rVrSX5l1.js} +3 -3
- package/dist/{loop-runner-bin-C8MI8N1A.js.map → loop-runner-bin-rVrSX5l1.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +6 -35
- package/dist/mcp/index.js +311 -364
- package/dist/mcp/index.js.map +1 -1
- package/dist/model-policy-DydyWTQg.js.map +1 -1
- package/dist/{openai-tools-BeogJ6V8.d.ts → openai-tools-YO30D2s3.d.ts} +2 -2
- package/dist/{prepare-CGVNMb1o.js → prepare--nWcazPr.js} +7 -13
- package/dist/prepare--nWcazPr.js.map +1 -0
- package/dist/{profile-BetOB4_Q.js → profile-h04LDjV6.js} +2 -2
- package/dist/{profile-BetOB4_Q.js.map → profile-h04LDjV6.js.map} +1 -1
- package/dist/profiles.d.ts +2 -94
- package/dist/profiles.js +2 -451
- package/dist/profiles.js.map +1 -1
- package/dist/{protected-model-port-CAa0t1MT.d.ts → protected-model-port-C9QtEf3y.d.ts} +2 -2
- package/dist/{protected-model-port-CuVHkhti.js → protected-model-port-wwalbyXM.js} +4 -4
- package/dist/{protected-model-port-CuVHkhti.js.map → protected-model-port-wwalbyXM.js.map} +1 -1
- package/dist/{provision-supervisor-CS0fBIhp.js → provision-supervisor-WxFEFQeJ.js} +4 -3
- package/dist/{provision-supervisor-CS0fBIhp.js.map → provision-supervisor-WxFEFQeJ.js.map} +1 -1
- package/dist/{runtime-6VPSJVeg.js → runtime-B9eBIyws.js} +67 -469
- package/dist/runtime-B9eBIyws.js.map +1 -0
- package/dist/{search-method-wTTS7mGG.js → search-executor-2tWr38Qw.js} +239 -1132
- package/dist/search-executor-2tWr38Qw.js.map +1 -0
- package/dist/{server-BfHD5iLD.js → server-CpKcrOPj.js} +5 -12
- package/dist/server-CpKcrOPj.js.map +1 -0
- package/dist/{stream-agent-turn-B1ipFtOc.d.ts → stream-agent-turn-B1giFgOg.d.ts} +2 -2
- package/dist/{substrate-DKBMd0Dl.d.ts → substrate-L_sC7jCD.d.ts} +2 -2
- package/dist/{supervise-BJrEC2Mh.js → supervise-DllOHM4M.js} +14 -24
- package/dist/supervise-DllOHM4M.js.map +1 -0
- package/dist/{supervisor-DA_nvF-h.js → supervisor-gCfG6K1-.js} +488 -1407
- package/dist/supervisor-gCfG6K1-.js.map +1 -0
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +14 -14
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +1 -1
- package/dist/{types-jD9mNnJM.d.ts → types-DeuEkBhI.d.ts} +114 -258
- package/dist/{workspace-archive-pz8YJ1fr.d.ts → workspace-streams-CpSmt3zx.d.ts} +67 -3
- package/dist/{workspace-streams-D5gHJdTb.js → workspace-streams-ILw0eWZ0.js} +694 -2
- package/dist/workspace-streams-ILw0eWZ0.js.map +1 -0
- package/package.json +8 -8
- package/skills/generate-eval/SKILL.md +1 -1
- package/skills/profile-authoring/SKILL.md +2 -2
- package/dist/coordination-driver-vNrdQBSH.js.map +0 -1
- package/dist/graph-Dwv_hQB_.js.map +0 -1
- package/dist/improvement-cycle-Cf37Kexd.js.map +0 -1
- package/dist/prepare-CGVNMb1o.js.map +0 -1
- package/dist/runtime-6VPSJVeg.js.map +0 -1
- package/dist/search-method-wTTS7mGG.js.map +0 -1
- package/dist/server-BfHD5iLD.js.map +0 -1
- package/dist/supervise-BJrEC2Mh.js.map +0 -1
- package/dist/supervisor-DA_nvF-h.js.map +0 -1
- package/dist/workspace-streams-D5gHJdTb.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"prepare-CGVNMb1o.js","names":["SHA256_PATTERN","canonicalCandidateDigest","requireString","requireNumber","requireObject","assertExecutionId","assertSha256Digest","assertCount","canonicalCandidateDigest","canonicalCandidateDigest","canonicalCandidateBytes","modelLimits","sha256Bytes","canonicalCandidateDigest","canonicalCandidateBytes","sha256Bytes","sha256Bytes","canonicalCandidateDigest","canonicalCandidateBytes","canonicalCandidateBytes","sha256Bytes","errorMessage","canonicalCandidateBytes","canonicalCandidateDigest","canonicalCandidateBytes","canonicalCandidateBytes","canonicalCandidateDigest","sha256Bytes","resolveHostPath"],"sources":["../src/candidate-execution/claim-file-formats.ts","../src/candidate-execution/claim-terminal.ts","../src/candidate-execution/cleanup.ts","../src/candidate-execution/claim.ts","../src/candidate-execution/execution-window.ts","../src/candidate-execution/execution-roots.ts","../src/candidate-execution/types.ts","../src/candidate-execution/prepared-state.ts","../src/candidate-execution/claim-plan.ts","../src/candidate-execution/executor-capture.ts","../src/candidate-execution/model-settlement.ts","../src/candidate-execution/finalize.ts","../src/candidate-execution/benchmark-grader.ts","../src/candidate-execution/executor-capture-evidence.ts","../src/candidate-execution/outcome-evidence.ts","../src/candidate-execution/protected-trace-store.ts","../src/candidate-execution/execute.ts","../src/candidate-execution/verify.ts","../src/candidate-execution/knowledge.ts","../src/candidate-execution/prepare.ts"],"sourcesContent":["import {\n type AgentCandidateArtifactRef,\n agentCandidateArtifactRefSchema,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport type { AgentCandidateExecutionClaim, AgentCandidateExecutionTerminalRecord } from './claim'\nimport { immutableCandidateValue } from './digest'\nimport { assertExactObjectKeys } from './exact-object'\n\nexport interface AgentCandidatePreparationEvidence {\n readonly executionPlan: AgentCandidateArtifactRef\n readonly materializationReceipt: AgentCandidateArtifactRef\n}\n\nexport function sealCandidatePreparationEvidence(\n value: unknown,\n executionPlanDigest: Sha256Digest,\n): AgentCandidatePreparationEvidence {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('candidate execution preparation evidence must be an object')\n }\n const record = value as Record<string, unknown>\n assertExactObjectKeys(\n record,\n ['executionPlan', 'materializationReceipt'],\n 'candidate execution preparation evidence',\n )\n const executionPlan = immutableCandidateValue(\n agentCandidateArtifactRefSchema.parse(record.executionPlan),\n )\n const materializationReceipt = immutableCandidateValue(\n agentCandidateArtifactRefSchema.parse(record.materializationReceipt),\n )\n if (executionPlan.sha256 !== executionPlanDigest) {\n throw new Error('candidate execution plan artifact digest does not match its claim')\n }\n return Object.freeze({ executionPlan, materializationReceipt })\n}\n\nexport interface PersistedAgentCandidateExecutionClaim extends AgentCandidateExecutionClaim {\n phase: 'claimed'\n leaseDigest: Sha256Digest\n}\n\nexport interface PersistedAgentCandidateExecutionPending {\n kind: 'candidate-execution-pending-terminal'\n terminal: AgentCandidateExecutionTerminalRecord\n}\n\nexport interface PersistedAgentCandidateExecutionPhase {\n kind: 'candidate-execution-phase'\n executionId: string\n attempt: number\n executionPlanDigest: Sha256Digest\n phase: 'candidate-may-run'\n}\n\nexport interface PersistedAgentCandidateExecutionTerminal {\n terminal: AgentCandidateExecutionTerminalRecord\n}\n","import type {\n AgentCandidateArtifactRef,\n AgentCandidateFixedSpend,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { agentCandidateArtifactRefSchema } from '@tangle-network/agent-interface'\n\nimport type {\n AgentCandidateExecutionClaim,\n AgentCandidateExecutionFailureClass,\n AgentCandidateExecutionFinishResult,\n AgentCandidateExecutionPhase,\n AgentCandidateExecutionRecoveryEvidence,\n AgentCandidateExecutionStageResult,\n AgentCandidateExecutionTerminalRecord,\n AgentCandidateExecutionTerminalResult,\n} from './claim'\nimport { sealCandidatePreparationEvidence } from './claim-file-formats'\nimport { canonicalCandidateDigest, immutableCandidateValue } from './digest'\nimport { assertExactObjectKeys as assertExactKeys } from './exact-object'\n\nconst SHA256_PATTERN = /^sha256:[a-f0-9]{64}$/\n\nexport function terminalRecord(\n claim: AgentCandidateExecutionClaim,\n result: AgentCandidateExecutionTerminalResult,\n): AgentCandidateExecutionTerminalRecord {\n const terminal = sealTerminalResult(result)\n const value = {\n executionId: claim.executionId,\n attempt: claim.attempt,\n bundleDigest: claim.bundleDigest,\n executionPlanDigest: claim.executionPlanDigest,\n preparationEvidence: claim.preparationEvidence,\n ...terminal,\n }\n return immutableCandidateValue({\n ...value,\n terminalDigest: canonicalCandidateDigest(value),\n }) as AgentCandidateExecutionTerminalRecord\n}\n\nexport function recoveredTerminalRecord(\n claim: AgentCandidateExecutionClaim,\n phase: AgentCandidateExecutionPhase,\n evidence: AgentCandidateExecutionRecoveryEvidence,\n): AgentCandidateExecutionTerminalRecord {\n const recovered = sealRecoveryEvidence(evidence, claim)\n return terminalRecord(claim, {\n status: 'failed',\n failureClass:\n recovered.failureClass === 'pre-model-infrastructure' && phase !== 'claimed'\n ? 'unknown'\n : recovered.failureClass,\n usage: recovered.usage,\n modelSettlement: recovered.modelSettlement,\n ...(recovered.failureEvidence ? { failureEvidence: recovered.failureEvidence } : {}),\n })\n}\n\nexport function assertTerminalAllowedInPhase(\n phase: AgentCandidateExecutionPhase,\n terminal: AgentCandidateExecutionTerminalRecord,\n): void {\n if (\n phase === 'candidate-may-run' &&\n terminal.status === 'failed' &&\n terminal.failureClass === 'pre-model-infrastructure'\n ) {\n throw new Error('candidate execution crossed candidate-may-run before pre-model failure')\n }\n if (\n phase === 'claimed' &&\n (terminal.status === 'succeeded' ||\n (terminal.status === 'failed' &&\n (terminal.failureClass === 'execution' ||\n terminal.failureClass === 'post-model-infrastructure')))\n ) {\n throw new Error('candidate execution terminal requires candidate-may-run phase')\n }\n}\n\nexport function rejectedFinish(\n existing: AgentCandidateExecutionTerminalRecord,\n requestedTerminalDigest: Sha256Digest,\n): AgentCandidateExecutionFinishResult {\n return Object.freeze({\n finished: false,\n terminal: existing,\n exactReplay: existing.terminalDigest === requestedTerminalDigest,\n })\n}\n\nexport function rejectedStage(\n existing: AgentCandidateExecutionTerminalRecord,\n requested: AgentCandidateExecutionTerminalRecord,\n): AgentCandidateExecutionStageResult {\n return Object.freeze({\n staged: false,\n terminal: existing,\n exactReplay: existing.terminalDigest === requested.terminalDigest,\n })\n}\n\nexport function requireStagedTerminal(\n staged: AgentCandidateExecutionTerminalRecord | undefined,\n terminalDigest: Sha256Digest,\n): AgentCandidateExecutionTerminalRecord {\n if (!staged) throw new Error('candidate execution terminal has not been staged')\n if (staged.terminalDigest !== terminalDigest) {\n throw new Error('candidate execution terminal digest does not match staged outbox')\n }\n return staged\n}\n\nexport function sealTerminalDigest(value: Sha256Digest): Sha256Digest {\n assertSha256Digest(value, 'terminalDigest')\n return value\n}\n\nexport function assertRecoveryMatchesStaged(\n staged: AgentCandidateExecutionTerminalRecord,\n recovered: AgentCandidateExecutionTerminalRecord,\n): void {\n if (\n canonicalCandidateDigest(staged.usage) !== canonicalCandidateDigest(recovered.usage) ||\n canonicalCandidateDigest(staged.modelSettlement) !==\n canonicalCandidateDigest(recovered.modelSettlement)\n ) {\n throw new Error('candidate execution recovery evidence does not match staged model evidence')\n }\n}\n\nexport function sealTerminalRecordValue(\n value: Record<string, unknown>,\n label: string,\n): AgentCandidateExecutionTerminalRecord {\n const status = requireTerminalStatus(value.status, label)\n assertExactKeys(\n value,\n status === 'succeeded'\n ? [\n 'executionId',\n 'attempt',\n 'bundleDigest',\n 'executionPlanDigest',\n 'preparationEvidence',\n 'terminalDigest',\n 'status',\n 'usage',\n 'modelSettlement',\n 'taskOutcome',\n 'benchmarkResult',\n 'runReceipt',\n ]\n : [\n 'executionId',\n 'attempt',\n 'bundleDigest',\n 'executionPlanDigest',\n 'preparationEvidence',\n 'terminalDigest',\n 'status',\n 'failureClass',\n 'usage',\n 'modelSettlement',\n ...(value.failureEvidence ? ['failureEvidence'] : []),\n ],\n label,\n )\n const executionPlanDigest = requireString(\n value.executionPlanDigest,\n label,\n 'executionPlanDigest',\n ) as Sha256Digest\n const identity = {\n executionId: requireString(value.executionId, label, 'executionId'),\n attempt: requireNumber(value.attempt, label, 'attempt'),\n bundleDigest: requireString(value.bundleDigest, label, 'bundleDigest') as Sha256Digest,\n executionPlanDigest,\n preparationEvidence: sealCandidatePreparationEvidence(\n value.preparationEvidence,\n executionPlanDigest,\n ),\n }\n assertExecutionId(identity.executionId)\n if (!Number.isSafeInteger(identity.attempt) || identity.attempt < 1) {\n throw new Error(`${label} has invalid attempt`)\n }\n assertSha256Digest(identity.bundleDigest, 'bundleDigest')\n assertSha256Digest(identity.executionPlanDigest, 'executionPlanDigest')\n if (identity.preparationEvidence.executionPlan.sha256 !== identity.executionPlanDigest) {\n throw new Error(`${label} execution plan artifact does not match executionPlanDigest`)\n }\n const result = sealTerminalResult(\n status === 'succeeded'\n ? {\n status,\n usage: requireObject(value.usage, label, 'usage') as unknown as AgentCandidateFixedSpend,\n modelSettlement: requireArtifactRef(value.modelSettlement, label, 'modelSettlement'),\n taskOutcome: requireArtifactRef(value.taskOutcome, label, 'taskOutcome'),\n benchmarkResult: requireArtifactRef(value.benchmarkResult, label, 'benchmarkResult'),\n runReceipt: requireArtifactRef(value.runReceipt, label, 'runReceipt'),\n }\n : {\n status,\n failureClass: requireFailureClass(value.failureClass, label),\n usage: requireObject(value.usage, label, 'usage') as unknown as AgentCandidateFixedSpend,\n modelSettlement: requireArtifactRef(value.modelSettlement, label, 'modelSettlement'),\n ...(value.failureEvidence\n ? {\n failureEvidence: requireArtifactRef(\n value.failureEvidence,\n label,\n 'failureEvidence',\n ),\n }\n : {}),\n },\n )\n const material = { ...identity, ...result }\n const terminalDigest = requireString(\n value.terminalDigest,\n label,\n 'terminalDigest',\n ) as Sha256Digest\n assertSha256Digest(terminalDigest, 'terminalDigest')\n if (terminalDigest !== canonicalCandidateDigest(material)) {\n throw new Error(`${label} has invalid terminalDigest`)\n }\n return immutableCandidateValue({\n ...material,\n terminalDigest,\n }) as AgentCandidateExecutionTerminalRecord\n}\n\nexport function assertTerminalMatchesClaim(\n terminal: AgentCandidateExecutionTerminalRecord,\n claim: AgentCandidateExecutionClaim,\n path: string,\n): void {\n if (\n terminal.executionId !== claim.executionId ||\n terminal.attempt !== claim.attempt ||\n terminal.bundleDigest !== claim.bundleDigest ||\n terminal.executionPlanDigest !== claim.executionPlanDigest ||\n canonicalCandidateDigest(terminal.preparationEvidence) !==\n canonicalCandidateDigest(claim.preparationEvidence)\n ) {\n throw new Error(`candidate execution terminal record at ${path} does not match its claim`)\n }\n}\n\nexport function assertTerminalMatchesStaged(\n terminal: AgentCandidateExecutionTerminalRecord,\n staged: AgentCandidateExecutionTerminalRecord,\n path: string,\n): void {\n if (\n terminal.terminalDigest !== staged.terminalDigest ||\n canonicalCandidateDigest(terminal) !== canonicalCandidateDigest(staged)\n ) {\n throw new Error(`candidate execution terminal record at ${path} differs from staged outbox`)\n }\n}\n\nfunction sealRecoveryEvidence(\n evidence: AgentCandidateExecutionRecoveryEvidence,\n claim: AgentCandidateExecutionClaim,\n): AgentCandidateExecutionRecoveryEvidence {\n assertExactKeys(\n evidence,\n [\n 'failureClass',\n 'usage',\n 'modelSettlement',\n 'process',\n 'model',\n ...(evidence.failureEvidence ? ['failureEvidence'] : []),\n ...(evidence.memory ? ['memory'] : []),\n ],\n 'candidate execution recovery evidence',\n )\n assertFailureClass(evidence.failureClass)\n const usage = sealUsage(evidence.usage)\n if (evidence.failureClass === 'pre-model-infrastructure' && usage.modelCalls !== 0) {\n throw new Error('pre-model infrastructure failure cannot contain model calls')\n }\n const modelSettlement = sealArtifactRef(evidence.modelSettlement, 'modelSettlement')\n const failureEvidence = evidence.failureEvidence\n ? sealArtifactRef(evidence.failureEvidence, 'failureEvidence')\n : undefined\n assertExactKeys(\n evidence.process,\n ['stopped', 'executionPlanDigest'],\n 'candidate execution process closure evidence',\n )\n if (\n evidence.process.stopped !== true ||\n evidence.process.executionPlanDigest !== claim.executionPlanDigest\n ) {\n throw new Error('candidate execution recovery does not prove the claimed process stopped')\n }\n assertExactKeys(\n evidence.model,\n ['closed', 'preparationId', 'grantDigest'],\n 'candidate execution model closure evidence',\n )\n if (\n evidence.model.closed !== true ||\n evidence.model.preparationId !== claim.cleanup.preparationId ||\n evidence.model.grantDigest !== claim.cleanup.modelGrantDigest\n ) {\n throw new Error('candidate execution recovery does not prove the claimed model grant closed')\n }\n if (claim.cleanup.memory) {\n if (!evidence.memory) {\n throw new Error('candidate execution recovery is missing memory closure evidence')\n }\n assertExactKeys(\n evidence.memory,\n ['closed', 'preparationId', 'accessDigest', 'effectiveNamespace'],\n 'candidate execution memory closure evidence',\n )\n if (\n evidence.memory.closed !== true ||\n evidence.memory.preparationId !== claim.cleanup.preparationId ||\n evidence.memory.accessDigest !== claim.cleanup.memory.accessDigest ||\n evidence.memory.effectiveNamespace !== claim.cleanup.memory.effectiveNamespace\n ) {\n throw new Error(\n 'candidate execution recovery does not prove the claimed memory access closed',\n )\n }\n } else if (evidence.memory !== undefined) {\n throw new Error('candidate execution recovery has unexpected memory closure evidence')\n }\n return Object.freeze({\n failureClass: evidence.failureClass,\n usage,\n modelSettlement,\n ...(failureEvidence ? { failureEvidence } : {}),\n process: Object.freeze({ ...evidence.process }),\n model: Object.freeze({ ...evidence.model }),\n ...(evidence.memory ? { memory: Object.freeze({ ...evidence.memory }) } : {}),\n })\n}\n\nfunction sealTerminalResult(\n result: AgentCandidateExecutionTerminalResult,\n): AgentCandidateExecutionTerminalResult {\n if (result.status !== 'succeeded' && result.status !== 'failed') {\n throw new Error('candidate execution terminal status is invalid')\n }\n assertExactKeys(\n result,\n result.status === 'succeeded'\n ? ['status', 'usage', 'modelSettlement', 'taskOutcome', 'benchmarkResult', 'runReceipt']\n : [\n 'status',\n 'failureClass',\n 'usage',\n 'modelSettlement',\n ...(result.failureEvidence ? ['failureEvidence'] : []),\n ],\n 'candidate execution terminal result',\n )\n const usage = sealUsage(result.usage)\n const modelSettlement = sealArtifactRef(result.modelSettlement, 'modelSettlement')\n if (result.status === 'succeeded') {\n return Object.freeze({\n status: 'succeeded',\n usage,\n modelSettlement,\n taskOutcome: sealArtifactRef(result.taskOutcome, 'taskOutcome'),\n benchmarkResult: sealArtifactRef(result.benchmarkResult, 'benchmarkResult'),\n runReceipt: sealArtifactRef(result.runReceipt, 'runReceipt'),\n })\n }\n assertFailureClass(result.failureClass)\n if (result.failureClass === 'pre-model-infrastructure' && usage.modelCalls !== 0) {\n throw new Error('pre-model infrastructure failure cannot contain model calls')\n }\n return Object.freeze({\n status: 'failed',\n failureClass: result.failureClass,\n usage,\n modelSettlement,\n ...(result.failureEvidence\n ? { failureEvidence: sealArtifactRef(result.failureEvidence, 'failureEvidence') }\n : {}),\n })\n}\n\nfunction sealUsage(usage: AgentCandidateFixedSpend): AgentCandidateFixedSpend {\n assertExactKeys(\n usage,\n [\n 'costUsdNanos',\n 'inputTokens',\n 'outputTokens',\n 'cachedInputTokens',\n 'reasoningTokens',\n 'modelCalls',\n 'costProvenance',\n ],\n 'candidate execution terminal usage',\n )\n for (const field of [\n 'costUsdNanos',\n 'inputTokens',\n 'outputTokens',\n 'cachedInputTokens',\n 'reasoningTokens',\n 'modelCalls',\n ] as const) {\n assertCount(usage[field], `terminal usage ${field}`)\n }\n if (usage.costProvenance !== 'observed' && usage.costProvenance !== 'estimated') {\n throw new Error('terminal usage costProvenance must be observed or estimated')\n }\n return Object.freeze({\n costUsdNanos: usage.costUsdNanos,\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n reasoningTokens: usage.reasoningTokens,\n modelCalls: usage.modelCalls,\n costProvenance: usage.costProvenance,\n })\n}\n\nfunction sealArtifactRef(ref: AgentCandidateArtifactRef, label: string): AgentCandidateArtifactRef {\n const parsed = agentCandidateArtifactRefSchema.parse(ref)\n if (!Number.isSafeInteger(parsed.byteLength)) {\n throw new Error(`candidate execution terminal ${label} byteLength exceeds safe integer range`)\n }\n return immutableCandidateValue(parsed)\n}\n\nfunction requireArtifactRef(\n value: unknown,\n path: string,\n field: string,\n): AgentCandidateArtifactRef {\n return requireObject(value, path, field) as unknown as AgentCandidateArtifactRef\n}\n\nfunction requireString(value: unknown, path: string, field: string): string {\n if (typeof value !== 'string') {\n throw new Error(`candidate execution record at ${path} has invalid ${field}`)\n }\n return value\n}\n\nfunction requireNumber(value: unknown, path: string, field: string): number {\n if (typeof value !== 'number') {\n throw new Error(`candidate execution record at ${path} has invalid ${field}`)\n }\n return value\n}\n\nfunction requireObject(value: unknown, path: string, field: string): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`candidate execution record at ${path} has invalid ${field}`)\n }\n return value as Record<string, unknown>\n}\n\nfunction requireTerminalStatus(\n value: unknown,\n path: string,\n): AgentCandidateExecutionTerminalResult['status'] {\n if (value !== 'succeeded' && value !== 'failed') {\n throw new Error(`candidate execution terminal record at ${path} has invalid status`)\n }\n return value\n}\n\nfunction requireFailureClass(value: unknown, path: string): AgentCandidateExecutionFailureClass {\n try {\n assertFailureClass(value)\n return value\n } catch (error) {\n throw new Error(`candidate execution terminal record at ${path} has invalid failureClass`, {\n cause: error,\n })\n }\n}\n\nfunction assertFailureClass(value: unknown): asserts value is AgentCandidateExecutionFailureClass {\n if (\n value !== 'pre-model-infrastructure' &&\n value !== 'execution' &&\n value !== 'post-model-infrastructure' &&\n value !== 'unknown'\n ) {\n throw new Error('candidate execution failureClass is invalid')\n }\n}\n\nfunction assertExecutionId(value: unknown): asserts value is string {\n if (typeof value !== 'string' || !/^[A-Za-z0-9._:-]{1,200}$/.test(value)) {\n throw new Error('candidate execution claim executionId is invalid')\n }\n}\n\nfunction assertSha256Digest(value: string, field: string): void {\n if (!SHA256_PATTERN.test(value)) {\n throw new Error(`candidate execution claim ${field} must be a lowercase sha256 digest`)\n }\n}\n\nfunction assertCount(value: unknown, label: string): asserts value is number {\n if (!Number.isSafeInteger(value) || (value as number) < 0) {\n throw new Error(`candidate execution ${label} must be a non-negative safe integer`)\n }\n}\n","export const DEFAULT_CANDIDATE_CLEANUP_TIMEOUT_MS = 30_000\n/** Largest delay Node schedules without clamping to one millisecond. */\nexport const MAX_CANDIDATE_TIMER_INTERVAL_MS = 2_147_483_647\n\nexport function candidateCleanupTimeout(timeoutMs: number | undefined): number {\n const effective = timeoutMs ?? DEFAULT_CANDIDATE_CLEANUP_TIMEOUT_MS\n if (\n !Number.isSafeInteger(effective) ||\n effective <= 0 ||\n effective > MAX_CANDIDATE_TIMER_INTERVAL_MS\n ) {\n throw new Error('candidate cleanup timeout is outside the supported timer range')\n }\n return effective\n}\n\nexport function candidateCleanupDeadline(timeoutMs: number | undefined): number {\n return Date.now() + candidateCleanupTimeout(timeoutMs)\n}\n\n/** Freeze a separate result-construction budget; defaults to the task wall limit. */\nexport function candidateResultTimeout(\n timeoutMs: number | undefined,\n taskTimeoutMs: number,\n): number {\n const effective = timeoutMs ?? taskTimeoutMs\n if (\n !Number.isSafeInteger(effective) ||\n effective <= 0 ||\n effective > MAX_CANDIDATE_TIMER_INTERVAL_MS\n ) {\n throw new Error('candidate result timeout is outside the supported timer range')\n }\n return effective\n}\n\n/** Bound an evaluator cleanup call and cancel the underlying port at expiry. */\nexport async function withinCandidateCleanupDeadline<T>(\n operation: (signal: AbortSignal) => Promise<T>,\n deadlineAtMs: number,\n label: string,\n): Promise<T> {\n return withinCandidateDeadline(operation, deadlineAtMs, new CandidateCleanupTimeoutError(label))\n}\n\n/**\n * Bound cancellable scoring/result work. Every side-effecting port called by\n * `operation` must honor the supplied signal before durable publication.\n */\nexport async function withinCandidateResultDeadline<T>(\n operation: (signal: AbortSignal) => Promise<T>,\n deadlineAtMs: number,\n label: string,\n): Promise<T> {\n return withinCandidateDeadline(operation, deadlineAtMs, new CandidateResultTimeoutError(label))\n}\n\nasync function withinCandidateDeadline<T>(\n operation: (signal: AbortSignal) => Promise<T>,\n deadlineAtMs: number,\n timeoutError: Error,\n): Promise<T> {\n const remainingMs = deadlineAtMs - Date.now()\n if (remainingMs <= 0) throw timeoutError\n\n const controller = new AbortController()\n const pending = Promise.resolve().then(() => operation(controller.signal))\n void pending.catch(() => undefined)\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n const result = await Promise.race([\n pending,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n controller.abort(timeoutError)\n reject(timeoutError)\n }, remainingMs)\n }),\n ])\n // Exact-boundary completion is ambiguous under event-loop delay.\n if (Date.now() >= deadlineAtMs) {\n controller.abort(timeoutError)\n throw timeoutError\n }\n return result\n } finally {\n if (timer) clearTimeout(timer)\n }\n}\n\nexport class CandidateCleanupTimeoutError extends Error {\n constructor(label: string) {\n super(`${label} did not complete before the evaluator cleanup deadline`)\n this.name = 'CandidateCleanupTimeoutError'\n }\n}\n\nexport class CandidateResultTimeoutError extends Error {\n constructor(label: string) {\n super(`${label} did not complete before the evaluator result deadline`)\n this.name = 'CandidateResultTimeoutError'\n }\n}\n","/** Durable one-shot lifecycle for candidate execution attempts. */\n\nimport { createHash, randomBytes, timingSafeEqual } from 'node:crypto'\nimport { readFile } from 'node:fs/promises'\nimport {\n type AgentCandidateArtifactRef,\n type AgentCandidateAttemptPolicy,\n type AgentCandidateFixedSpend,\n type AgentCandidateResolvedModel,\n agentCandidateResolvedModelSchema,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n type AgentCandidatePreparationEvidence,\n type PersistedAgentCandidateExecutionClaim,\n type PersistedAgentCandidateExecutionPending,\n type PersistedAgentCandidateExecutionPhase,\n type PersistedAgentCandidateExecutionTerminal,\n sealCandidatePreparationEvidence,\n} from './claim-file-formats'\nimport {\n assertRecoveryMatchesStaged,\n assertTerminalAllowedInPhase,\n assertTerminalMatchesClaim,\n recoveredTerminalRecord,\n rejectedFinish,\n rejectedStage,\n requireStagedTerminal,\n sealTerminalDigest,\n sealTerminalRecordValue,\n terminalRecord,\n} from './claim-terminal'\nimport { candidateCleanupTimeout, candidateResultTimeout } from './cleanup'\nimport { canonicalCandidateDigest, immutableCandidateValue } from './digest'\nimport { assertExactObjectKeys as assertExactKeys } from './exact-object'\n\n/** Non-secret identities a trusted recovery worker needs to close an abandoned attempt. */\nexport interface AgentCandidateExecutionCleanupHandles {\n readonly preparationId: string\n readonly modelGrantDigest: Sha256Digest\n readonly resolvedModel: AgentCandidateResolvedModel\n readonly traceRunId: string\n readonly cleanupTimeoutMs: number\n readonly memory?: {\n readonly accessDigest: Sha256Digest\n readonly effectiveNamespace: string\n }\n}\n\n/** Immutable signed identity stored for one execution attempt. */\nexport interface AgentCandidateExecutionClaim {\n readonly executionId: string\n readonly attempt: number\n readonly maxAttempts: number\n readonly retryPolicy: AgentCandidateAttemptPolicy['retryPolicy']\n readonly bundleDigest: Sha256Digest\n readonly executionPlanDigest: Sha256Digest\n /** Durable canonical bytes needed to reconstruct the signed preparation. */\n readonly preparationEvidence: AgentCandidatePreparationEvidence\n /** Frozen plan identity with only attempt number and per-attempt grant identity normalized. */\n readonly retryLineageDigest: Sha256Digest\n /** The winning lease stops authorizing a new terminal write at this instant. */\n readonly leaseExpiresAtMs: number\n /** Frozen budget for task verification, executable grading, and receipt construction. */\n readonly resultTimeoutMs: number\n /** Non-secret handles retained so an expired attempt can be closed and reconciled. */\n readonly cleanup: AgentCandidateExecutionCleanupHandles\n}\n\n/** Secret capability required to finish the acquired attempt. */\nexport interface AgentCandidateExecutionLease {\n readonly executionId: string\n readonly attempt: number\n readonly token: string\n readonly expiresAtMs: number\n}\n\n/** Only the first class is retryable, and only when the closed model ledger has zero calls. */\nexport type AgentCandidateExecutionFailureClass =\n | 'pre-model-infrastructure'\n | 'execution'\n | 'post-model-infrastructure'\n | 'unknown'\n\n/** Evaluator-owned terminal facts staged durably before the terminal CAS. */\nexport type AgentCandidateExecutionTerminalResult =\n | {\n readonly status: 'succeeded'\n readonly usage: AgentCandidateFixedSpend\n readonly modelSettlement: AgentCandidateArtifactRef\n readonly taskOutcome: AgentCandidateArtifactRef\n readonly benchmarkResult: AgentCandidateArtifactRef\n readonly runReceipt: AgentCandidateArtifactRef\n }\n | {\n readonly status: 'failed'\n readonly failureClass: AgentCandidateExecutionFailureClass\n readonly usage: AgentCandidateFixedSpend\n readonly modelSettlement: AgentCandidateArtifactRef\n readonly failureEvidence?: AgentCandidateArtifactRef\n }\n\n/** Durable terminal record for one acquired execution attempt. */\nexport type AgentCandidateExecutionTerminalRecord = AgentCandidateExecutionTerminalResult & {\n readonly executionId: string\n readonly attempt: number\n readonly bundleDigest: Sha256Digest\n readonly executionPlanDigest: Sha256Digest\n readonly preparationEvidence: AgentCandidateExecutionClaim['preparationEvidence']\n /** RFC 8785 SHA-256 of this record with `terminalDigest` omitted. */\n readonly terminalDigest: Sha256Digest\n}\n\n/** Monotonic durable phase: the second value means candidate code could have started. */\nexport type AgentCandidateExecutionPhase = 'claimed' | 'candidate-may-run'\n\n/** Trusted, independently observed closure facts for one expired winning lease. */\nexport interface AgentCandidateExecutionRecoveryEvidence {\n readonly failureClass: AgentCandidateExecutionFailureClass\n readonly usage: AgentCandidateFixedSpend\n readonly modelSettlement: AgentCandidateArtifactRef\n readonly failureEvidence?: AgentCandidateArtifactRef\n readonly process: {\n readonly stopped: true\n readonly executionPlanDigest: Sha256Digest\n }\n readonly model: {\n readonly closed: true\n readonly preparationId: string\n readonly grantDigest: Sha256Digest\n }\n readonly memory?: {\n readonly closed: true\n readonly preparationId: string\n readonly accessDigest: Sha256Digest\n readonly effectiveNamespace: string\n }\n}\n\nexport interface AgentCandidateExecutionAttemptRef {\n readonly executionId: string\n readonly attempt: number\n}\n\n/** Persisted state available to a fresh trusted recovery worker after a crash. */\nexport interface AgentCandidateExecutionAttemptRecord {\n readonly claim: AgentCandidateExecutionClaim\n readonly phase: AgentCandidateExecutionPhase\n /** Durable outbox content written before the terminal compare-and-set. */\n readonly staged?: AgentCandidateExecutionTerminalRecord\n readonly terminal?: AgentCandidateExecutionTerminalRecord\n}\n\n/** Result of atomically claiming one execution attempt. */\nexport type AgentCandidateExecutionClaimResult =\n | {\n readonly acquired: true\n readonly claim: AgentCandidateExecutionClaim\n readonly lease: AgentCandidateExecutionLease\n }\n | {\n readonly acquired: false\n readonly reason: 'already-claimed'\n /** The durable winner already occupying this execution-attempt slot. */\n readonly claim: AgentCandidateExecutionClaim\n /** True only when every signed claim field matches the durable winner. */\n readonly exactReplay: boolean\n }\n | {\n readonly acquired: false\n readonly reason: 'retry-not-eligible'\n readonly claim: AgentCandidateExecutionClaim\n readonly detail: AgentCandidateRetryRejection\n }\n\n/** Result of atomically recording an attempt's terminal facts. */\nexport type AgentCandidateExecutionFinishResult =\n | {\n readonly finished: true\n readonly terminal: AgentCandidateExecutionTerminalRecord\n }\n | {\n readonly finished: false\n readonly terminal: AgentCandidateExecutionTerminalRecord\n /** True when a repeated finish supplied the same terminal digest. */\n readonly exactReplay: boolean\n }\n\n/** Result of durably staging the one immutable terminal outbox entry. */\nexport type AgentCandidateExecutionStageResult =\n | {\n readonly staged: true\n readonly terminal: AgentCandidateExecutionTerminalRecord\n }\n | {\n readonly staged: false\n readonly terminal: AgentCandidateExecutionTerminalRecord\n readonly exactReplay: boolean\n }\n\n/** Result of crossing the irreversible candidate-may-run boundary. */\nexport type AgentCandidateExecutionPhaseResult =\n | { readonly marked: true; readonly phase: 'candidate-may-run' }\n | { readonly marked: false; readonly phase: 'candidate-may-run' }\n\nexport type AgentCandidateRetryRejection =\n | 'prior-attempt-missing'\n | 'prior-attempt-running'\n | 'prior-attempt-succeeded'\n | 'prior-attempt-spent-model-calls'\n | 'prior-attempt-not-pre-model-infrastructure'\n | 'retry-lineage-mismatch'\n\n/**\n * Atomic one-shot store for candidate execution attempts.\n *\n * Implementations must linearize both methods across every process sharing the\n * store. Terminal publication is deliberately two-step: `stageTerminal`\n * fsyncs the complete immutable outbox record, then `finish` publishes exactly\n * those staged bytes by digest. A crash between the two leaves recoverable\n * evidence rather than an ambiguous completed run.\n */\nexport interface AgentCandidateExecutionClaimStore {\n tryClaim(claim: AgentCandidateExecutionClaim): Promise<AgentCandidateExecutionClaimResult>\n getAttempt(\n attempt: AgentCandidateExecutionAttemptRef,\n ): Promise<AgentCandidateExecutionAttemptRecord | undefined>\n /** Persist the point after which candidate code may have run. */\n markCandidateMayRun(\n lease: AgentCandidateExecutionLease,\n ): Promise<AgentCandidateExecutionPhaseResult>\n /** Fsync the complete terminal record into the durable outbox. */\n stageTerminal(\n lease: AgentCandidateExecutionLease,\n result: AgentCandidateExecutionTerminalResult,\n ): Promise<AgentCandidateExecutionStageResult>\n /** Publish exactly the staged terminal identified by `terminalDigest`. */\n finish(\n lease: AgentCandidateExecutionLease,\n terminalDigest: Sha256Digest,\n ): Promise<AgentCandidateExecutionFinishResult>\n /**\n * Write a failed terminal only after the lease expired and a trusted worker\n * independently proved process death plus model and memory closure.\n */\n recoverExpired(\n attempt: AgentCandidateExecutionAttemptRef,\n evidence: AgentCandidateExecutionRecoveryEvidence,\n ): Promise<AgentCandidateExecutionFinishResult>\n}\n\ninterface StoredClaim {\n claim: AgentCandidateExecutionClaim\n leaseDigest: Sha256Digest\n phase: AgentCandidateExecutionPhase\n staged?: AgentCandidateExecutionTerminalRecord\n terminal?: AgentCandidateExecutionTerminalRecord\n}\n\nfunction attemptRecord(\n claim: AgentCandidateExecutionClaim,\n phase: AgentCandidateExecutionPhase,\n staged?: AgentCandidateExecutionTerminalRecord,\n terminal?: AgentCandidateExecutionTerminalRecord,\n): AgentCandidateExecutionAttemptRecord {\n return Object.freeze({\n claim,\n phase,\n ...(staged ? { staged } : {}),\n ...(terminal ? { terminal } : {}),\n })\n}\n\nexport interface InMemoryAgentCandidateExecutionClaimStoreOptions {\n /** Testable evaluator clock; defaults to `Date.now`. */\n now?: () => number\n}\n\n/** Single-process lifecycle implementation. */\nexport class InMemoryAgentCandidateExecutionClaimStore\n implements AgentCandidateExecutionClaimStore\n{\n private readonly claims = new Map<string, StoredClaim>()\n private readonly now: () => number\n\n constructor(options: InMemoryAgentCandidateExecutionClaimStoreOptions = {}) {\n this.now = options.now ?? Date.now\n }\n\n async tryClaim(\n requested: AgentCandidateExecutionClaim,\n ): Promise<AgentCandidateExecutionClaimResult> {\n const claim = sealClaim(requested)\n const slot = claimSlot(claim)\n const existing = this.claims.get(slot)\n if (existing) return rejectedExistingClaim(existing.claim, claim)\n assertUnexpiredLease(claim.leaseExpiresAtMs, this.now())\n\n const retryRejection = retryRejectionFromMemory(this.claims, claim)\n if (retryRejection) return rejectedRetry(claim, retryRejection)\n\n const lease = newLease(claim)\n // No await may occur between the read and write: this is the linearization\n // point for every caller sharing this store instance.\n this.claims.set(slot, {\n claim,\n leaseDigest: leaseDigest(lease),\n phase: 'claimed',\n })\n return Object.freeze({ acquired: true, claim, lease })\n }\n\n async getAttempt(\n requestedAttempt: AgentCandidateExecutionAttemptRef,\n ): Promise<AgentCandidateExecutionAttemptRecord | undefined> {\n const attempt = sealAttemptRef(requestedAttempt)\n const stored = this.claims.get(claimSlot(attempt))\n return stored\n ? attemptRecord(stored.claim, stored.phase, stored.staged, stored.terminal)\n : undefined\n }\n\n async markCandidateMayRun(\n requestedLease: AgentCandidateExecutionLease,\n ): Promise<AgentCandidateExecutionPhaseResult> {\n const lease = sealLease(requestedLease)\n const stored = this.requireClaim(lease)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n if (stored.phase === 'candidate-may-run') {\n return Object.freeze({ marked: false, phase: 'candidate-may-run' })\n }\n if (stored.staged || stored.terminal) {\n throw new Error('candidate execution terminal was staged before candidate-may-run phase')\n }\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n stored.phase = 'candidate-may-run'\n return Object.freeze({ marked: true, phase: 'candidate-may-run' })\n }\n\n async stageTerminal(\n requestedLease: AgentCandidateExecutionLease,\n result: AgentCandidateExecutionTerminalResult,\n ): Promise<AgentCandidateExecutionStageResult> {\n const lease = sealLease(requestedLease)\n const stored = this.requireClaim(lease)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const terminal = terminalRecord(stored.claim, result)\n if (stored.staged) return rejectedStage(stored.staged, terminal)\n assertTerminalAllowedInPhase(stored.phase, terminal)\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n stored.staged = terminal\n return Object.freeze({ staged: true, terminal })\n }\n\n async finish(\n requestedLease: AgentCandidateExecutionLease,\n requestedTerminalDigest: Sha256Digest,\n ): Promise<AgentCandidateExecutionFinishResult> {\n const lease = sealLease(requestedLease)\n const terminalDigest = sealTerminalDigest(requestedTerminalDigest)\n const stored = this.requireClaim(lease)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const staged = requireStagedTerminal(stored.staged, terminalDigest)\n if (stored.terminal) return rejectedFinish(stored.terminal, terminalDigest)\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n\n // The terminal assignment is the in-memory finish linearization point and\n // publishes the exact immutable object already present in the outbox.\n stored.terminal = staged\n return Object.freeze({ finished: true, terminal: staged })\n }\n\n async recoverExpired(\n requestedAttempt: AgentCandidateExecutionAttemptRef,\n evidence: AgentCandidateExecutionRecoveryEvidence,\n ): Promise<AgentCandidateExecutionFinishResult> {\n const attempt = sealAttemptRef(requestedAttempt)\n const stored = this.requireClaim(attempt, 'candidate execution recovery')\n const recovered = recoveredTerminalRecord(stored.claim, stored.phase, evidence)\n if (stored.staged) assertRecoveryMatchesStaged(stored.staged, recovered)\n const requestedDigest = stored.staged?.terminalDigest ?? recovered.terminalDigest\n if (stored.terminal) return rejectedFinish(stored.terminal, requestedDigest)\n assertExpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const terminal = stored.staged ?? recovered\n assertRecoveryMatchesStaged(terminal, recovered)\n stored.staged ??= terminal\n stored.terminal = terminal\n return Object.freeze({ finished: true, terminal })\n }\n\n private requireClaim(\n attempt: Pick<AgentCandidateExecutionLease, 'executionId' | 'attempt'>,\n operation = 'candidate execution lease',\n ): StoredClaim {\n const stored = this.claims.get(claimSlot(attempt))\n if (!stored) throw new Error(`${operation} does not name an acquired attempt`)\n return stored\n }\n}\n\nconst SHA256_PATTERN = /^sha256:[a-f0-9]{64}$/\nconst LEASE_TOKEN_PATTERN = /^candidate-execution-lease\\.[A-Za-z0-9_-]{43}$/\nconst PREPARATION_ID_PATTERN = /^candidate-preparation\\.[A-Za-z0-9_-]{43}$/\n\nfunction sealClaim(claim: AgentCandidateExecutionClaim): AgentCandidateExecutionClaim {\n assertExactKeys(\n claim,\n [\n 'executionId',\n 'attempt',\n 'maxAttempts',\n 'retryPolicy',\n 'bundleDigest',\n 'executionPlanDigest',\n 'preparationEvidence',\n 'retryLineageDigest',\n 'leaseExpiresAtMs',\n 'resultTimeoutMs',\n 'cleanup',\n ],\n 'candidate execution claim',\n )\n assertExecutionId(claim.executionId)\n if (!Number.isSafeInteger(claim.attempt) || claim.attempt < 1) {\n throw new Error('candidate execution claim attempt must be a positive safe integer')\n }\n if (!Number.isSafeInteger(claim.maxAttempts) || claim.maxAttempts < 1) {\n throw new Error('candidate execution claim maxAttempts must be a positive safe integer')\n }\n if (claim.attempt > claim.maxAttempts) {\n throw new Error('candidate execution claim attempt exceeds maxAttempts')\n }\n if (!['none', 'pre-model-infrastructure-only'].includes(claim.retryPolicy)) {\n throw new Error('candidate execution claim retryPolicy is invalid')\n }\n if (claim.retryPolicy === 'none' && claim.maxAttempts !== 1) {\n throw new Error('candidate execution claim retryPolicy none requires maxAttempts 1')\n }\n assertSha256Digest(claim.bundleDigest, 'bundleDigest')\n assertSha256Digest(claim.executionPlanDigest, 'executionPlanDigest')\n const preparationEvidence = sealCandidatePreparationEvidence(\n claim.preparationEvidence,\n claim.executionPlanDigest,\n )\n assertSha256Digest(claim.retryLineageDigest, 'retryLineageDigest')\n assertPositiveTimestamp(claim.leaseExpiresAtMs, 'leaseExpiresAtMs')\n candidateResultTimeout(claim.resultTimeoutMs, claim.resultTimeoutMs)\n const cleanup = sealCleanupHandles(claim.cleanup)\n return Object.freeze({\n executionId: claim.executionId,\n attempt: claim.attempt,\n maxAttempts: claim.maxAttempts,\n retryPolicy: claim.retryPolicy,\n bundleDigest: claim.bundleDigest,\n executionPlanDigest: claim.executionPlanDigest,\n preparationEvidence,\n retryLineageDigest: claim.retryLineageDigest,\n leaseExpiresAtMs: claim.leaseExpiresAtMs,\n resultTimeoutMs: claim.resultTimeoutMs,\n cleanup,\n })\n}\n\nfunction sealCleanupHandles(\n cleanup: AgentCandidateExecutionCleanupHandles,\n): AgentCandidateExecutionCleanupHandles {\n assertExactKeys(\n cleanup,\n cleanup.memory\n ? [\n 'preparationId',\n 'modelGrantDigest',\n 'resolvedModel',\n 'traceRunId',\n 'cleanupTimeoutMs',\n 'memory',\n ]\n : ['preparationId', 'modelGrantDigest', 'resolvedModel', 'traceRunId', 'cleanupTimeoutMs'],\n 'candidate execution cleanup handles',\n )\n if (!PREPARATION_ID_PATTERN.test(cleanup.preparationId)) {\n throw new Error('candidate execution cleanup preparationId is invalid')\n }\n assertSha256Digest(cleanup.modelGrantDigest, 'cleanup modelGrantDigest')\n const resolvedModel = immutableCandidateValue(\n agentCandidateResolvedModelSchema.parse(cleanup.resolvedModel),\n )\n assertBoundedIdentifier(cleanup.traceRunId, 'cleanup traceRunId', 512)\n const cleanupTimeoutMs = candidateCleanupTimeout(cleanup.cleanupTimeoutMs)\n const memory = cleanup.memory ? sealMemoryCleanupHandle(cleanup.memory) : undefined\n return Object.freeze({\n preparationId: cleanup.preparationId,\n modelGrantDigest: cleanup.modelGrantDigest,\n resolvedModel,\n traceRunId: cleanup.traceRunId,\n cleanupTimeoutMs,\n ...(memory ? { memory } : {}),\n })\n}\n\nfunction sealMemoryCleanupHandle(\n memory: NonNullable<AgentCandidateExecutionCleanupHandles['memory']>,\n): NonNullable<AgentCandidateExecutionCleanupHandles['memory']> {\n assertExactKeys(\n memory,\n ['accessDigest', 'effectiveNamespace'],\n 'candidate execution memory cleanup handle',\n )\n assertSha256Digest(memory.accessDigest, 'memory accessDigest')\n assertBoundedIdentifier(memory.effectiveNamespace, 'memory effectiveNamespace', 1_024)\n return Object.freeze({\n accessDigest: memory.accessDigest,\n effectiveNamespace: memory.effectiveNamespace,\n })\n}\n\nfunction sealAttemptRef(\n attempt: AgentCandidateExecutionAttemptRef,\n): AgentCandidateExecutionAttemptRef {\n assertExactKeys(attempt, ['executionId', 'attempt'], 'candidate execution attempt reference')\n assertExecutionId(attempt.executionId)\n if (!Number.isSafeInteger(attempt.attempt) || attempt.attempt < 1) {\n throw new Error('candidate execution attempt reference must have a positive safe attempt')\n }\n return Object.freeze({ executionId: attempt.executionId, attempt: attempt.attempt })\n}\n\nfunction sealLease(lease: AgentCandidateExecutionLease): AgentCandidateExecutionLease {\n assertExactKeys(\n lease,\n ['executionId', 'attempt', 'token', 'expiresAtMs'],\n 'candidate execution lease',\n )\n if (lease.executionId.length === 0 || !Number.isSafeInteger(lease.attempt) || lease.attempt < 1) {\n throw new Error('candidate execution lease identity is invalid')\n }\n if (!LEASE_TOKEN_PATTERN.test(lease.token)) {\n throw new Error('candidate execution lease token is invalid')\n }\n assertPositiveTimestamp(lease.expiresAtMs, 'lease expiresAtMs')\n return Object.freeze({\n executionId: lease.executionId,\n attempt: lease.attempt,\n token: lease.token,\n expiresAtMs: lease.expiresAtMs,\n })\n}\n\nfunction newLease(claim: AgentCandidateExecutionClaim): AgentCandidateExecutionLease {\n return Object.freeze({\n executionId: claim.executionId,\n attempt: claim.attempt,\n token: `candidate-execution-lease.${randomBytes(32).toString('base64url')}`,\n expiresAtMs: claim.leaseExpiresAtMs,\n })\n}\n\nfunction leaseDigest(lease: AgentCandidateExecutionLease): Sha256Digest {\n return sha256(lease.token)\n}\n\nfunction assertLease(\n expectedDigest: Sha256Digest,\n expectedExpiresAtMs: number,\n lease: AgentCandidateExecutionLease,\n): void {\n const expected = Buffer.from(expectedDigest)\n const actual = Buffer.from(leaseDigest(lease))\n if (\n expected.length !== actual.length ||\n !timingSafeEqual(expected, actual) ||\n lease.expiresAtMs !== expectedExpiresAtMs\n ) {\n throw new Error('candidate execution lease is invalid')\n }\n}\n\nfunction claimSlot(claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>): string {\n return createHash('sha256')\n .update(JSON.stringify([claim.executionId, claim.attempt]), 'utf8')\n .digest('hex')\n}\n\nfunction retryRejectionFromMemory(\n claims: ReadonlyMap<string, StoredClaim>,\n claim: AgentCandidateExecutionClaim,\n): AgentCandidateRetryRejection | undefined {\n if (claim.attempt === 1) return undefined\n const prior = claims.get(\n claimSlot({ executionId: claim.executionId, attempt: claim.attempt - 1 }),\n )\n return retryRejection(claim, prior)\n}\n\nfunction retryRejection(\n claim: AgentCandidateExecutionClaim,\n prior:\n | {\n claim: AgentCandidateExecutionClaim\n terminal?: AgentCandidateExecutionTerminalRecord\n }\n | undefined,\n): AgentCandidateRetryRejection | undefined {\n if (!prior) return 'prior-attempt-missing'\n if (\n claim.retryPolicy !== 'pre-model-infrastructure-only' ||\n prior.claim.retryPolicy !== claim.retryPolicy ||\n prior.claim.maxAttempts !== claim.maxAttempts ||\n prior.claim.bundleDigest !== claim.bundleDigest ||\n prior.claim.retryLineageDigest !== claim.retryLineageDigest\n ) {\n return 'retry-lineage-mismatch'\n }\n if (!prior.terminal) return 'prior-attempt-running'\n if (prior.terminal.status === 'succeeded') return 'prior-attempt-succeeded'\n if (prior.terminal.usage.modelCalls !== 0) return 'prior-attempt-spent-model-calls'\n if (prior.terminal.failureClass !== 'pre-model-infrastructure') {\n return 'prior-attempt-not-pre-model-infrastructure'\n }\n return undefined\n}\n\nfunction rejectedExistingClaim(\n existing: AgentCandidateExecutionClaim,\n requested: AgentCandidateExecutionClaim,\n): AgentCandidateExecutionClaimResult {\n return Object.freeze({\n acquired: false,\n reason: 'already-claimed',\n claim: existing,\n exactReplay: canonicalCandidateDigest(existing) === canonicalCandidateDigest(requested),\n })\n}\n\nfunction rejectedRetry(\n claim: AgentCandidateExecutionClaim,\n detail: AgentCandidateRetryRejection,\n): AgentCandidateExecutionClaimResult {\n return Object.freeze({ acquired: false, reason: 'retry-not-eligible', claim, detail })\n}\n\nasync function readClaim(path: string): Promise<StoredClaim> {\n const parsed = await readJsonObject(path, 'claim')\n const record = parsed as Partial<PersistedAgentCandidateExecutionClaim>\n assertExactKeys(\n parsed,\n [\n 'executionId',\n 'attempt',\n 'maxAttempts',\n 'retryPolicy',\n 'bundleDigest',\n 'executionPlanDigest',\n 'preparationEvidence',\n 'retryLineageDigest',\n 'leaseExpiresAtMs',\n 'resultTimeoutMs',\n 'cleanup',\n 'phase',\n 'leaseDigest',\n ],\n `candidate execution claim at ${path}`,\n )\n const claim = sealClaim({\n executionId: requireString(record.executionId, path, 'executionId'),\n attempt: requireNumber(record.attempt, path, 'attempt'),\n maxAttempts: requireNumber(record.maxAttempts, path, 'maxAttempts'),\n retryPolicy: requireRetryPolicy(record.retryPolicy, path),\n bundleDigest: requireString(record.bundleDigest, path, 'bundleDigest') as Sha256Digest,\n executionPlanDigest: requireString(\n record.executionPlanDigest,\n path,\n 'executionPlanDigest',\n ) as Sha256Digest,\n preparationEvidence: requireObject(\n record.preparationEvidence,\n path,\n 'preparationEvidence',\n ) as unknown as AgentCandidateExecutionClaim['preparationEvidence'],\n retryLineageDigest: requireString(\n record.retryLineageDigest,\n path,\n 'retryLineageDigest',\n ) as Sha256Digest,\n leaseExpiresAtMs: requireNumber(record.leaseExpiresAtMs, path, 'leaseExpiresAtMs'),\n resultTimeoutMs: requireNumber(record.resultTimeoutMs, path, 'resultTimeoutMs'),\n cleanup: requireObject(\n record.cleanup,\n path,\n 'cleanup',\n ) as unknown as AgentCandidateExecutionCleanupHandles,\n })\n const persistedLeaseDigest = requireString(\n record.leaseDigest,\n path,\n 'leaseDigest',\n ) as Sha256Digest\n assertSha256Digest(persistedLeaseDigest, 'leaseDigest')\n if (record.phase !== 'claimed') {\n throw new Error(`candidate execution claim at ${path} has invalid initial phase`)\n }\n return { claim, leaseDigest: persistedLeaseDigest, phase: 'claimed' }\n}\n\nasync function readClaimIfPresent(path: string): Promise<StoredClaim | undefined> {\n try {\n return await readClaim(path)\n } catch (error) {\n if (isMissingError(error)) return undefined\n throw error\n }\n}\n\nasync function readTerminal(path: string): Promise<AgentCandidateExecutionTerminalRecord> {\n const parsed = await readJsonObject(path, 'terminal record')\n const record = parsed as Partial<PersistedAgentCandidateExecutionTerminal>\n assertExactKeys(parsed, ['terminal'], `candidate execution terminal record at ${path}`)\n return sealTerminalRecordValue(\n requireObject(record.terminal, path, 'terminal'),\n `candidate execution terminal record at ${path}`,\n )\n}\n\nasync function readTerminalIfPresent(\n path: string,\n): Promise<AgentCandidateExecutionTerminalRecord | undefined> {\n try {\n return await readTerminal(path)\n } catch (error) {\n if (isMissingError(error)) return undefined\n throw error\n }\n}\n\ntype ReadCandidateExecutionTransition =\n | { kind: 'phase' }\n | { kind: 'pending'; terminal: AgentCandidateExecutionTerminalRecord }\n\nasync function readTransitionIfPresent(\n path: string,\n claim: AgentCandidateExecutionClaim,\n): Promise<ReadCandidateExecutionTransition | undefined> {\n let parsed: Record<string, unknown>\n try {\n parsed = await readJsonObject(path, 'transition record')\n } catch (error) {\n if (isMissingError(error)) return undefined\n throw error\n }\n if (parsed.kind === 'candidate-execution-phase') {\n const record = parsed as unknown as PersistedAgentCandidateExecutionPhase\n assertExactKeys(\n parsed,\n ['kind', 'executionId', 'attempt', 'executionPlanDigest', 'phase'],\n `candidate execution phase record at ${path}`,\n )\n if (\n record.executionId !== claim.executionId ||\n record.attempt !== claim.attempt ||\n record.executionPlanDigest !== claim.executionPlanDigest ||\n record.phase !== 'candidate-may-run'\n ) {\n throw new Error(`candidate execution phase record at ${path} does not match its claim`)\n }\n return { kind: 'phase' }\n }\n if (parsed.kind === 'candidate-execution-pending-terminal') {\n const record = parsed as unknown as PersistedAgentCandidateExecutionPending\n assertExactKeys(parsed, ['kind', 'terminal'], `candidate execution pending record at ${path}`)\n const terminal = sealTerminalRecordValue(\n requireObject(record.terminal, path, 'terminal'),\n `candidate execution pending record at ${path}`,\n )\n assertTerminalMatchesClaim(terminal, claim, path)\n return { kind: 'pending', terminal }\n }\n throw new Error(`candidate execution transition record at ${path} has invalid kind`)\n}\n\nasync function readJsonObject(path: string, kind: string): Promise<Record<string, unknown>> {\n let parsed: unknown\n try {\n parsed = JSON.parse(await readFile(path, 'utf8'))\n } catch (error) {\n if (isMissingError(error)) throw error\n throw new Error(`candidate execution ${kind} at ${path} is unreadable`, { cause: error })\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`candidate execution ${kind} at ${path} is not an object`)\n }\n return parsed as Record<string, unknown>\n}\n\nfunction assertSameSlot(\n existing: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n requested: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n path: string,\n): void {\n if (existing.executionId !== requested.executionId || existing.attempt !== requested.attempt) {\n throw new Error(`candidate execution record at ${path} does not match its claim slot`)\n }\n}\n\nfunction assertSha256Digest(value: string, field: string): void {\n if (!SHA256_PATTERN.test(value)) {\n throw new Error(`candidate execution claim ${field} must be a lowercase sha256 digest`)\n }\n}\n\nfunction requireString(value: unknown, path: string, field: string): string {\n if (typeof value !== 'string') {\n throw new Error(`candidate execution record at ${path} has invalid ${field}`)\n }\n return value\n}\n\nfunction requireNumber(value: unknown, path: string, field: string): number {\n if (typeof value !== 'number') {\n throw new Error(`candidate execution record at ${path} has invalid ${field}`)\n }\n return value\n}\n\nfunction requireObject(value: unknown, path: string, field: string): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`candidate execution record at ${path} has invalid ${field}`)\n }\n return value as Record<string, unknown>\n}\n\nfunction requireRetryPolicy(\n value: unknown,\n path: string,\n): AgentCandidateAttemptPolicy['retryPolicy'] {\n if (value !== 'none' && value !== 'pre-model-infrastructure-only') {\n throw new Error(`candidate execution record at ${path} has invalid retryPolicy`)\n }\n return value\n}\n\nfunction assertExecutionId(value: unknown): asserts value is string {\n if (typeof value !== 'string' || !/^[A-Za-z0-9._:-]{1,200}$/.test(value)) {\n throw new Error('candidate execution claim executionId is invalid')\n }\n}\n\nfunction assertBoundedIdentifier(\n value: unknown,\n label: string,\n maxLength: number,\n): asserts value is string {\n if (\n typeof value !== 'string' ||\n value.length === 0 ||\n value.length > maxLength ||\n hasControlCharacter(value)\n ) {\n throw new Error(`candidate execution ${label} is invalid`)\n }\n}\n\nfunction 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\nfunction assertPositiveTimestamp(value: unknown, label: string): asserts value is number {\n if (!Number.isSafeInteger(value) || (value as number) <= 0) {\n throw new Error(`candidate execution ${label} must be a positive safe timestamp`)\n }\n}\n\nfunction assertClock(value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error('candidate execution claim-store clock returned an invalid timestamp')\n }\n}\n\nfunction assertUnexpiredLease(expiresAtMs: number, nowMs: number): void {\n assertClock(nowMs)\n if (nowMs >= expiresAtMs) throw new Error('candidate execution lease has expired')\n}\n\nfunction assertExpiredLease(expiresAtMs: number, nowMs: number): void {\n assertClock(nowMs)\n if (nowMs < expiresAtMs) throw new Error('candidate execution lease has not expired')\n}\n\nfunction sha256(value: string): Sha256Digest {\n return `sha256:${createHash('sha256').update(value, 'utf8').digest('hex')}`\n}\n\nfunction isMissingError(error: unknown): boolean {\n return isNodeError(error, 'ENOENT')\n}\n\nfunction isNodeError(error: unknown, code: string): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === code\n )\n}\n\nexport const candidateClaimFileInternals = Object.freeze({\n assertExpiredLease,\n assertLease,\n assertSameSlot,\n assertUnexpiredLease,\n attemptRecord,\n claimSlot,\n leaseDigest,\n newLease,\n readClaim,\n readClaimIfPresent,\n readTerminal,\n readTerminalIfPresent,\n readTransitionIfPresent,\n rejectedExistingClaim,\n rejectedRetry,\n retryRejection,\n sealAttemptRef,\n sealClaim,\n sealLease,\n})\n\nexport { candidateExecutionClaim } from './claim-plan'\n","import { MAX_CANDIDATE_TIMER_INTERVAL_MS } from './cleanup'\n\nexport const CANDIDATE_TERMINAL_PERSISTENCE_MARGIN_MS = 10_000\nconst CANDIDATE_POST_RUN_CLEANUP_PHASES = 4\n\n/** Process stop, access closure, model evidence, and task/result evidence. */\nexport function candidatePostRunWindowMs(\n cleanupTimeoutMs: number,\n resultTimeoutMs: number,\n): number {\n const windowMs =\n cleanupTimeoutMs * CANDIDATE_POST_RUN_CLEANUP_PHASES +\n resultTimeoutMs +\n CANDIDATE_TERMINAL_PERSISTENCE_MARGIN_MS\n if (!Number.isSafeInteger(windowMs) || windowMs > MAX_CANDIDATE_TIMER_INTERVAL_MS) {\n throw new Error('candidate post-run window exceeds the supported timer range')\n }\n return windowMs\n}\n\n/** Maximum owner lifetime from claim through process stop, access closure, and terminal write. */\nexport function candidateExecutionOwnerWindowMs(\n timeoutMs: number,\n cleanupTimeoutMs: number,\n resultTimeoutMs: number,\n): number {\n const windowMs = timeoutMs + candidatePostRunWindowMs(cleanupTimeoutMs, resultTimeoutMs)\n if (!Number.isSafeInteger(windowMs) || windowMs > MAX_CANDIDATE_TIMER_INTERVAL_MS) {\n throw new Error('candidate execution and cleanup window exceeds the supported timer range')\n }\n return windowMs\n}\n\n/** Time reserved after scoring for failure evidence plus terminal publication. */\nexport function candidateTerminalWindowMs(cleanupTimeoutMs: number): number {\n const windowMs = cleanupTimeoutMs + CANDIDATE_TERMINAL_PERSISTENCE_MARGIN_MS\n if (!Number.isSafeInteger(windowMs) || windowMs > MAX_CANDIDATE_TIMER_INTERVAL_MS) {\n throw new Error('candidate terminal window exceeds the supported timer range')\n }\n return windowMs\n}\n","import { posix } from 'node:path'\n\n/** Absolute container roots owned by one isolated candidate execution. */\nexport interface AgentCandidateExecutionRoots {\n readonly taskRoot: string\n readonly candidateRoot?: string\n /** Private runtime HOME used for agent-scoped profile files, when needed. */\n readonly profileRoot?: string\n}\n\n/** Validate the canonical identity and isolation boundary for execution roots. */\nexport function assertAgentCandidateExecutionRoots(roots: AgentCandidateExecutionRoots): void {\n const entries = [\n ['task', roots.taskRoot],\n ['candidate', roots.candidateRoot],\n ['profile', roots.profileRoot],\n ] as const\n for (const [name, root] of entries) {\n if (root === undefined) continue\n if (!posix.isAbsolute(root) || posix.normalize(root) !== root) {\n throw new Error(`execution ${name} root must be a canonical absolute path`)\n }\n }\n for (let left = 0; left < entries.length; left++) {\n const entry = entries[left]\n if (!entry) continue\n const [leftName, leftRoot] = entry\n if (leftRoot === undefined) continue\n for (let right = left + 1; right < entries.length; right++) {\n const rightEntry = entries[right]\n if (!rightEntry) continue\n const [rightName, rightRoot] = rightEntry\n if (rightRoot !== undefined && executionPathsOverlap(leftRoot, rightRoot)) {\n throw new Error(\n `execution ${leftName} and ${rightName} roots must be distinct and non-overlapping`,\n )\n }\n }\n }\n}\n\nexport function executionPathsOverlap(left: string, right: string): boolean {\n const a = posix.normalize(left)\n const b = posix.normalize(right)\n return (\n a === b || b.startsWith(a === '/' ? '/' : `${a}/`) || a.startsWith(b === '/' ? '/' : `${b}/`)\n )\n}\n","import type { BenchmarkEvaluation, TraceStore } from '@tangle-network/agent-eval'\nimport type {\n AgentCandidateArtifactRef,\n AgentCandidateAttemptPolicy,\n AgentCandidateBenchmarkSuite,\n AgentCandidateBenchmarkTask,\n AgentCandidateBundle,\n AgentCandidateCapturedArtifact,\n AgentCandidateContainer,\n AgentCandidateEffectiveMemory,\n AgentCandidateExecutionLimits,\n AgentCandidateExecutionPlanEvidence,\n AgentCandidateFixedSpend,\n AgentCandidateGitHubRepository,\n AgentCandidateInstructionDelivery,\n AgentCandidateKnowledgeRef,\n AgentCandidateKnowledgeStateScope,\n AgentCandidateMaterializationReceipt,\n AgentCandidateMemoryReceipt,\n AgentCandidateModelAccessNetwork,\n AgentCandidateModelSettlementCall,\n AgentCandidateOciPlatform,\n AgentCandidateProfileActivation,\n AgentCandidateProfilePlanEvidence,\n AgentCandidateResolvedModel,\n AgentCandidateRunCell,\n AgentCandidateRunReceipt,\n AgentCandidateTaskOutcomeEvidence,\n AgentCandidateTaskOutcomeMaterial,\n AgentCandidateTaskOutputSpec,\n AgentCandidateTermination,\n AgentCandidateWorkspaceManifestMaterial,\n AgentCandidateWorkspaceSnapshotEvidence,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport type { AgentCandidateExecutionRoots } from './execution-roots'\n\nexport const verifiedCandidateBrand: unique symbol = Symbol('verifiedAgentCandidate')\nexport const preparedCandidateBrand: unique symbol = Symbol('preparedAgentCandidate')\nexport const verifiedTaskOutcomeBrand: unique symbol = Symbol('verifiedTaskOutcome')\n\n/** Reads one content-addressed object from the closed S3/IPFS locator set. */\nexport interface AgentCandidateArtifactPort {\n read(ref: AgentCandidateArtifactRef): Promise<Uint8Array>\n /** Stream an artifact without materializing its complete contents. */\n readStream?(\n ref: AgentCandidateArtifactRef,\n options?: { signal?: AbortSignal },\n ): AsyncIterable<Uint8Array>\n}\n\nexport type AgentCandidateOutputPurpose =\n | 'execution-plan'\n | 'materialization-receipt'\n | 'candidate-workspace-manifest'\n | 'candidate-workspace-archive'\n | 'task-manifest'\n | 'task-archive'\n | 'task-patch'\n | 'task-output'\n | 'task-outcome'\n | 'memory-after-manifest'\n | 'memory-after-archive'\n | 'grader-evidence'\n | 'benchmark-result'\n | 'model-settlement'\n | 'trace'\n | 'executor-native-evidence'\n | 'executor-capture'\n | 'run-receipt'\n | 'knowledge-retrieval-config'\n | 'knowledge-evaluation'\n | 'failure-evidence'\n\n/** Durable content-addressed evidence store controlled only by the evaluator. */\nexport interface AgentCandidateOutputArtifactPort extends AgentCandidateArtifactPort {\n /** Consume all chunks before publishing; preserve put's identity and cancellation guarantees. */\n putStream?(input: {\n executionId: string\n purpose: AgentCandidateOutputPurpose\n chunks: AsyncIterable<Uint8Array>\n signal?: AbortSignal\n }): Promise<AgentCandidateArtifactRef>\n\n /** Must be idempotent for identical bytes and return only a durable S3/IPFS locator. */\n put(input: {\n executionId: string\n purpose: AgentCandidateOutputPurpose\n bytes: Uint8Array\n /** Abort must prevent durable publication when it happens before resolution. */\n signal?: AbortSignal\n }): Promise<AgentCandidateArtifactRef>\n}\n\n/** Resolves a declared GitHub repository to an already-present local Git object store. */\nexport interface AgentCandidateRepositoryPort {\n resolve(repository: AgentCandidateGitHubRepository): Promise<string>\n}\n\nexport interface AgentCandidateVerificationPorts {\n artifacts: AgentCandidateArtifactPort\n repositories: AgentCandidateRepositoryPort\n}\n\n/**\n * Materializes an already-verified workspace archive.\n *\n * The runtime independently scans every resulting byte, mode, and path against\n * the signed manifest after this returns. Implementations may therefore unpack\n * any archive encoding, or no-op when the exact workspace is already present.\n */\nexport interface AgentCandidateWorkspacePort {\n materialize(input: {\n role: 'task' | 'candidate' | 'knowledge' | 'memory'\n snapshot: AgentCandidateWorkspaceSnapshotEvidence\n archive: Uint8Array\n destination: string\n }): Promise<void>\n}\n\nexport interface ResolvedAgentCandidateContainer {\n source: 'pinned-container' | 'evaluator-task-container'\n image: string\n indexDigest: Sha256Digest\n manifestDigest: Sha256Digest\n platform: AgentCandidateOciPlatform\n}\n\nexport interface AgentCandidateContainerPort {\n resolve(input: {\n candidate: AgentCandidateContainer | undefined\n evaluatorTaskContainer: ResolvedAgentCandidateContainer | undefined\n }): Promise<ResolvedAgentCandidateContainer>\n}\n\nexport interface AgentCandidateModelPort {\n resolve(input: {\n requested: string\n harness: AgentCandidateBundle['execution']['harness']\n reasoningEffort: NonNullable<AgentCandidateBundle['profile']['model']>['reasoningEffort']\n }): Promise<AgentCandidateResolvedModel>\n /**\n * Reserve a stable access identity without creating a live credential.\n * The reservation is scoped to `preparationId` and must automatically expire\n * at `expiresAtMs`, even if this call returns ambiguously to the runtime.\n */\n reserveGrant(input: {\n executionId: string\n preparationId: string\n expiresAtMs: number\n attempt: AgentCandidateAttemptPolicy\n bundleDigest: Sha256Digest\n resolved: AgentCandidateResolvedModel\n limits: AgentCandidateModelLimits\n }): Promise<AgentCandidateProtectedModelReservation>\n /** Create the live scoped credential only after the execution attempt is durably claimed. */\n activateGrant(input: {\n executionId: string\n preparationId: string\n grantDigest: Sha256Digest\n resolved: AgentCandidateResolvedModel\n deadlineAtMs: number\n }): Promise<AgentCandidateProtectedModelActivation>\n /**\n * Atomically revoke the grant, drain in-flight calls, and return its immutable final ledger.\n * This operation must be idempotent for the exact preparation and must also\n * settle a reservation that was never activated. It must never affect a\n * different preparation, even when both reservations report the same digest.\n */\n settleGrant(input: {\n executionId: string\n preparationId: string\n grantDigest: Sha256Digest\n resolved: AgentCandidateResolvedModel\n reason: 'completed' | 'failed' | 'timeout' | 'replayed' | 'preparation-failed' | 'abandoned'\n }): Promise<AgentCandidateProtectedModelSettlement>\n}\n\n/** Limits mechanically enforced by the evaluator-owned model gateway. */\nexport type AgentCandidateModelLimits = Pick<\n AgentCandidateExecutionLimits,\n 'maxModelCalls' | 'maxInputTokens' | 'maxOutputTokens' | 'maxCostUsd'\n> & {\n /** Optional caller-declared cap across input and output tokens. */\n maxTotalTokens?: number\n}\n\nexport interface AgentCandidateProtectedModelReservation {\n preparationId: string\n digest: Sha256Digest\n /** Evaluator service must expire and revoke this reservation at this epoch millisecond. */\n expiresAtMs: number\n /** The gateway must stop calls before any declared model limit is exceeded. */\n enforcedLimits: AgentCandidateModelLimits\n /** Exact public endpoint exception; every other candidate destination stays blocked. */\n network: AgentCandidateModelAccessNetwork\n}\n\nexport interface AgentCandidateProtectedModelActivation {\n /** Injected only into the trusted executor after all pre-launch checks pass. */\n env: Readonly<Record<string, string>>\n}\n\nexport interface AgentCandidateProtectedModelSettlement {\n preparationId: string\n grantDigest: Sha256Digest\n closed: true\n /** Router's terminal integrity result. False must never become a receipt. */\n usageWithinLimits: boolean\n calls: readonly AgentCandidateProtectedModelSettlementCall[]\n}\n\n/** Protected-port wire call with the gateway's counted input total preserved. */\nexport type AgentCandidateProtectedModelSettlementCall = AgentCandidateModelSettlementCall & {\n accountedInputTokens: number\n}\n\nexport interface AgentCandidateMemoryResetResult {\n preparationId: string\n accessDigest: Sha256Digest\n expiresAtMs: number\n evidence: AgentCandidateCapturedArtifact\n emptyStateDigest: Sha256Digest\n beforeState: AgentCandidateWorkspaceSnapshotEvidence\n}\n\nexport interface AgentCandidateMemoryPort {\n /**\n * Reset and reserve exact task memory without returning live access.\n * The service must scope the reservation to `preparationId`, automatically\n * revoke it at `expiresAtMs`, and never reuse it for another preparation.\n */\n reset(input: {\n executionId: string\n preparationId: string\n expiresAtMs: number\n effectiveNamespace: string\n seed?: Uint8Array\n seedDigest?: Sha256Digest\n }): Promise<AgentCandidateMemoryResetResult>\n /**\n * Create live scoped access only after the execution attempt is durably claimed.\n * Activation must match the exact preparation/access pair and may not extend expiry.\n */\n activate(input: {\n executionId: string\n preparationId: string\n accessDigest: Sha256Digest\n effectiveNamespace: string\n deadlineAtMs: number\n }): Promise<{ env: Readonly<Record<string, string>> }>\n /**\n * Revoke evaluator-owned access after process death or a failed preparation.\n * Must be idempotent and concurrency-safe for the exact preparation/access\n * pair and must never close a different preparation.\n */\n close(input: {\n executionId: string\n preparationId: string\n accessDigest: Sha256Digest\n effectiveNamespace: string\n reason: 'completed' | 'failed' | 'timeout' | 'replayed' | 'preparation-failed' | 'abandoned'\n }): Promise<{ closed: true }>\n}\n\nexport interface AgentCandidateExecutionPorts extends AgentCandidateVerificationPorts {\n workspaces: AgentCandidateWorkspacePort\n containers: AgentCandidateContainerPort\n models: AgentCandidateModelPort\n memory: AgentCandidateMemoryPort\n}\n\n/** Runtime placement for one exact cell from a signed candidate experiment. */\nexport interface AgentCandidateTaskExecution {\n executionId: string\n runCell: AgentCandidateRunCell\n benchmarkSuite: AgentCandidateBenchmarkSuite\n task: AgentCandidateBenchmarkTask\n /** Absolute paths inside the evaluator-owned execution environment. */\n executionRoots: AgentCandidateExecutionRoots\n /** Host-side staging roots. These are verified but never signed as container paths. */\n stagingRoots: {\n taskRoot: string\n candidateRoot?: string\n profileRoot: string\n }\n}\n\nexport interface VerifiedAgentCandidate {\n readonly bundle: AgentCandidateBundle\n readonly materializedTree?: string\n readonly [verifiedCandidateBrand]: true\n}\n\nexport interface CanonicalCandidateDocument<T> {\n readonly value: T\n /** Canonical UTF-8 bytes of `value` with its top-level digest omitted. */\n readonly bytes: Uint8Array\n readonly digest: Sha256Digest\n}\n\nexport interface PreparedAgentCandidateLaunch {\n executable: string\n /** Complete fixed argv, including profile materializer flags but excluding task delivery. */\n args: readonly string[]\n env: Readonly<Record<string, string>>\n /** Informational subset already present at the tail of `args`; executors must not append twice. */\n flags: readonly string[]\n cwd: string\n}\n\nexport interface PreparedAgentCandidateInstruction {\n bytes: Uint8Array\n delivery: AgentCandidateInstructionDelivery\n}\n\n/** Exact file-backed knowledge admitted by the candidate bundle. */\nexport interface PreparedAgentCandidateKnowledge {\n readonly candidate: AgentCandidateKnowledgeRef\n readonly stateScope?: Readonly<AgentCandidateKnowledgeStateScope>\n readonly snapshot: AgentCandidateWorkspaceSnapshotEvidence\n readonly files: readonly AgentCandidateExecutorWorkspaceFile[]\n readonly retrievalConfig?: Uint8Array\n}\n\nexport interface PreparedAgentCandidateTrace {\n runId: string\n tags: Readonly<Record<string, string>>\n env: Readonly<Record<string, string>>\n}\n\nexport interface PreparedAgentCandidateExecution {\n readonly bundle: AgentCandidateBundle\n readonly benchmark: {\n readonly suite: AgentCandidateBenchmarkSuite\n readonly task: AgentCandidateBenchmarkTask\n }\n readonly executionId: string\n readonly roots: {\n execution: AgentCandidateExecutionRoots\n staging: {\n taskRoot: string\n candidateRoot?: string\n profileRoot: string\n }\n }\n readonly profilePlan: {\n value: AgentCandidateProfilePlanEvidence\n bytes: Uint8Array\n written: readonly string[]\n }\n readonly profileActivation: AgentCandidateProfileActivation\n readonly executionPlan: {\n value: AgentCandidateExecutionPlanEvidence\n bytes: Uint8Array\n }\n readonly materializationReceipt: CanonicalCandidateDocument<AgentCandidateMaterializationReceipt>\n readonly launch: PreparedAgentCandidateLaunch\n readonly instruction: PreparedAgentCandidateInstruction\n readonly resolvedModel: AgentCandidateResolvedModel\n readonly knowledge?: PreparedAgentCandidateKnowledge\n readonly trace: PreparedAgentCandidateTrace\n readonly memory: AgentCandidateEffectiveMemory\n readonly [preparedCandidateBrand]: true\n}\n\nexport type { AgentCandidateBenchmarkGraderIdentity } from '@tangle-network/agent-interface'\n\nexport interface AgentCandidateProtectedRunCapture {\n executionId: string\n termination: AgentCandidateTermination\n}\n\n/** Raw evaluator capture made only after the candidate process is dead. */\nexport type AgentCandidateExecutorTaskOutcomeCapture =\n | {\n readonly kind: 'workspace'\n /** Claimed final tree. The runtime recomputes it independently from `gitDiff`. */\n readonly resultTree: string\n /** Complete evaluator-captured workspace description after candidate execution. */\n readonly afterState: AgentCandidateWorkspaceManifestMaterial\n /** Reproducible workspace archive corresponding to `afterState`. */\n readonly archive: Uint8Array\n /** Exact binary patch from the signed task base to `afterState`. */\n readonly gitDiff: Uint8Array\n }\n | {\n readonly kind: 'output'\n /** Exact evaluator-captured final output bytes. */\n readonly bytes: Uint8Array\n }\n\n/** Raw isolated-memory capture made only after access has been revoked. */\nexport interface AgentCandidateExecutorMemoryCapture {\n readonly afterState: AgentCandidateWorkspaceManifestMaterial\n readonly archive: Uint8Array\n}\n\n/** Replayable evaluator result captured only after process death and trace drain. */\nexport interface AgentCandidateExecutorFinalCapture {\n readonly taskOutcome?: AgentCandidateExecutorTaskOutcomeCapture\n /** Required only when the prepared candidate uses isolated task memory. */\n readonly memoryAfter?: AgentCandidateExecutorMemoryCapture\n /** Executor-native bytes preserved when a fresh worker cannot reconstruct a verified outcome. */\n readonly evidence?: Uint8Array\n}\n\n/** Immutable evaluator evidence retained with a verified candidate task outcome. */\nexport type PersistedTaskOutcomeEvidence<\n Kind extends AgentCandidateTaskOutcomeMaterial['outcome']['kind'],\n> = Omit<AgentCandidateTaskOutcomeEvidence, 'material'> & {\n readonly artifact: AgentCandidateArtifactRef\n readonly material: Omit<AgentCandidateTaskOutcomeMaterial, 'outcome'> & {\n readonly outcome: Extract<AgentCandidateTaskOutcomeMaterial['outcome'], { kind: Kind }>\n }\n}\n\n/** Branded task outcome that has survived independent evaluator verification. */\nexport type VerifiedAgentCandidateTaskOutcome =\n | {\n readonly kind: 'workspace'\n readonly evidence: PersistedTaskOutcomeEvidence<'workspace'>\n readonly patch: Uint8Array\n readonly [verifiedTaskOutcomeBrand]: true\n }\n | {\n readonly kind: 'output'\n readonly evidence: PersistedTaskOutcomeEvidence<'output'>\n readonly spec: AgentCandidateTaskOutputSpec\n readonly bytes: Uint8Array\n readonly [verifiedTaskOutcomeBrand]: true\n }\n\n/**\n * Evaluator-owned executable grader, pinned by immutable implementation bytes.\n *\n * `run` is an isolation boundary, not an arbitrary scoring callback. The\n * implementation admitted to that boundary is supplied by the runtime after\n * artifact verification. Implementations must derive every returned binding\n * digest from the bytes and task outcome they actually admitted, rather than\n * copying an expected digest from ambient configuration.\n */\nexport interface AgentCandidateBenchmarkGraderPort {\n readonly name: string\n readonly version: string\n readonly artifact: AgentCandidateArtifactRef\n run(input: {\n readonly executionId: string\n readonly termination: AgentCandidateTermination\n readonly outcome: VerifiedAgentCandidateTaskOutcome\n /** Exact verified artifact bytes. Each read returns a detached copy. */\n readonly implementation: {\n readonly byteLength: number\n readonly bytes: Uint8Array\n }\n /** Frozen result deadline; runners must stop work and side effects when aborted. */\n readonly signal: AbortSignal\n }): Promise<{\n readonly evaluation: BenchmarkEvaluation\n /** Raw grader output needed to audit or reproduce the normalized result. */\n readonly evidence: Uint8Array\n /** Runtime-checked binding between admitted code, task input, and raw output. */\n readonly binding: {\n /** Digest computed from the implementation bytes admitted to execution. */\n readonly implementationDigest: Sha256Digest\n /** Digest of the exact runtime-verified task outcome graded by this run. */\n readonly taskOutcomeDigest: Sha256Digest\n /** Digest computed from `evidence` before it leaves the execution boundary. */\n readonly outputDigest: Sha256Digest\n }\n }>\n}\n\n/** One detached request passed to the trusted environment-specific executor. */\nexport interface AgentCandidateExecutorRequest {\n readonly executionId: string\n readonly benchmark: PreparedAgentCandidateExecution['benchmark']\n /** Immutable bytes from which the executor creates fresh isolated workspaces. */\n readonly inputs: {\n readonly task: AgentCandidateExecutorWorkspaceInput\n readonly candidate?: AgentCandidateExecutorWorkspaceInput\n readonly profile: {\n readonly files: readonly AgentCandidateExecutorProfileFile[]\n }\n }\n readonly roots: PreparedAgentCandidateExecution['roots']['execution']\n readonly profilePlan: PreparedAgentCandidateExecution['profilePlan']\n readonly profileActivation: AgentCandidateProfileActivation\n readonly executionPlan: PreparedAgentCandidateExecution['executionPlan']\n readonly materializationReceipt: CanonicalCandidateDocument<AgentCandidateMaterializationReceipt>\n readonly launch: PreparedAgentCandidateLaunch\n readonly instruction: PreparedAgentCandidateInstruction\n readonly resolvedModel: AgentCandidateResolvedModel\n /** Mechanically enforced by the runtime plus executor process-death acknowledgement. */\n readonly hardLimits: Pick<AgentCandidateExecutionLimits, 'timeoutMs'>\n /** Validity bound checked against protected traces; generic black-box executors cannot preempt it. */\n readonly observedLimits: Pick<AgentCandidateExecutionLimits, 'maxSteps'>\n readonly knowledge?: PreparedAgentCandidateKnowledge\n readonly trace: PreparedAgentCandidateTrace\n readonly memory: AgentCandidateEffectiveMemory\n}\n\n/**\n * Executes one prepared request inside an evaluator-owned isolation boundary.\n *\n * `request.launch.env` is the complete allowlisted environment, including\n * protected model, memory, and trace bindings. Implementations must not merge\n * ambient host variables into it. The returned capture deliberately contains\n * no candidate-authored usage or score fields.\n */\nexport interface AgentCandidateExecutorPort {\n execute(\n request: AgentCandidateExecutorRequest,\n context: {\n traceStore: TraceStore\n /** Aborted by the runtime at the exact frozen wall-time deadline. */\n signal: AbortSignal\n /** Absolute epoch-millisecond deadline owned by the runtime. */\n deadlineAtMs: number\n },\n ): Promise<AgentCandidateProtectedRunCapture>\n /** Kill the exact process/container and drain trace writes. Must be idempotent. */\n stop(\n request: AgentCandidateExecutorStopRequest,\n context: {\n traceStore: TraceStore\n reason: 'completed' | 'failed' | 'timeout'\n /** Aborted at the frozen execution deadline or evaluator cleanup deadline. */\n signal: AbortSignal\n /** Absolute execution deadline; a later stop acknowledgement cannot produce success. */\n deadlineAtMs: number\n },\n ): Promise<{ readonly stopped: true }>\n /** Capture immutable final evidence after stop. Must be replayable by a fresh worker. */\n capture(\n request: AgentCandidateExecutorStopRequest,\n context: {\n traceStore: TraceStore\n /** Aborted at the frozen execution deadline or evaluator cleanup deadline. */\n signal: AbortSignal\n },\n ): Promise<AgentCandidateExecutorFinalCapture>\n /** Remove evaluator-owned execution resources after final capture. Must be idempotent. */\n dispose?(\n request: AgentCandidateExecutorStopRequest,\n context: {\n signal: AbortSignal\n },\n ): Promise<{ readonly disposed: true }>\n}\n\n/** Opaque process identity used for termination without re-exposing launch credentials. */\nexport interface AgentCandidateExecutorStopRequest {\n readonly executionId: string\n readonly executionPlanDigest: Sha256Digest\n}\n\nexport interface AgentCandidateExecutorWorkspaceInput {\n readonly snapshot: AgentCandidateWorkspaceSnapshotEvidence\n readonly files: readonly AgentCandidateExecutorWorkspaceFile[]\n}\n\nexport interface AgentCandidateExecutorWorkspaceFile {\n readonly path: string\n readonly mode: number\n readonly bytes: Uint8Array\n}\n\n/** One exact profile file supplied to an evaluator-owned executor. */\nexport interface AgentCandidateExecutorProfileFile {\n readonly path: string\n readonly mode: number\n /** Omit for a workspace-root file; agent-root files use the private Pi directory. */\n readonly root?: 'agent'\n readonly bytes: Uint8Array\n}\n\nexport type AgentCandidateRunFinalization =\n | {\n succeeded: true\n receipt: CanonicalCandidateDocument<AgentCandidateRunReceipt>\n artifacts: {\n executorCapture: AgentCandidateArtifactRef\n modelSettlement: AgentCandidateArtifactRef\n taskOutcome: AgentCandidateArtifactRef\n benchmarkResult: AgentCandidateArtifactRef\n runReceipt: AgentCandidateArtifactRef\n }\n }\n | {\n succeeded: false\n reason: string\n partial: {\n executionId: string\n bundleDigest: Sha256Digest\n executionPlanDigest: Sha256Digest\n materializationReceiptDigest: Sha256Digest\n termination?: AgentCandidateTermination\n }\n /** Independent evaluator-gateway usage, even when execution or trace capture failed. */\n usage: AgentCandidateFixedSpend | null\n }\n\n/** Protected trace tags that bind a run to one prepared candidate execution. */\nexport const CANDIDATE_TRACE_TAGS = {\n executionId: 'tangle.candidate.execution_id',\n bundleDigest: 'tangle.candidate.bundle_digest',\n executionPlanDigest: 'tangle.candidate.execution_plan_digest',\n materializationReceiptDigest: 'tangle.candidate.materialization_receipt_digest',\n} as const\n\n/** Environment keys used to propagate immutable candidate trace identity. */\nexport const CANDIDATE_TRACE_ENV = {\n executionId: 'TANGLE_CANDIDATE_EXECUTION_ID',\n bundleDigest: 'TANGLE_CANDIDATE_BUNDLE_DIGEST',\n executionPlanDigest: 'TANGLE_CANDIDATE_EXECUTION_PLAN_DIGEST',\n materializationReceiptDigest: 'TANGLE_CANDIDATE_MATERIALIZATION_RECEIPT_DIGEST',\n traceRunId: 'TANGLE_TRACE_RUN_ID',\n} as const\n\nexport type PreparedMemoryReceipt = AgentCandidateMemoryReceipt\n","import {\n type AgentCandidateBenchmarkSuite,\n type AgentCandidateBenchmarkTask,\n type AgentCandidateWorkspaceManifestMaterial,\n agentCandidateBenchmarkSuiteSchema,\n agentCandidateBenchmarkTaskSchema,\n agentCandidateExecutionPlanEvidenceSchema,\n agentCandidateMaterializationReceiptSchema,\n agentCandidateProfilePlanEvidenceSchema,\n} from '@tangle-network/agent-interface'\n\nimport { verifyMaterializedProfileWorkspace, verifyMaterializedWorkspace } from './artifacts'\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n immutableCandidateValue,\n omitTopLevelDigest,\n sha256Bytes,\n} from './digest'\nimport { assertAgentCandidateExecutionRoots } from './execution-roots'\nimport { verifyTaskCheckout } from './git-materialize'\nimport { parseAgentCandidateProfileActivation } from './profile'\nimport type {\n AgentCandidateExecutionPorts,\n AgentCandidateExecutorRequest,\n AgentCandidateExecutorWorkspaceFile,\n AgentCandidateProtectedModelActivation,\n AgentCandidateProtectedModelReservation,\n PreparedAgentCandidateExecution,\n} from './types'\nimport { CANDIDATE_TRACE_ENV, CANDIDATE_TRACE_TAGS, preparedCandidateBrand } from './types'\n\nexport interface PreparedCandidateState {\n ports: AgentCandidateExecutionPorts\n bundle: PreparedAgentCandidateExecution['bundle']\n benchmarkSuite: AgentCandidateBenchmarkSuite\n benchmarkTask: AgentCandidateBenchmarkTask\n executionId: string\n roots: PreparedAgentCandidateExecution['roots']\n profilePlan: PreparedAgentCandidateExecution['profilePlan']\n profileActivation: PreparedAgentCandidateExecution['profileActivation']\n executionPlan: PreparedAgentCandidateExecution['executionPlan']\n materializationReceipt: PreparedAgentCandidateExecution['materializationReceipt']\n launch: PreparedAgentCandidateExecution['launch']\n instruction: PreparedAgentCandidateExecution['instruction']\n resolvedModel: PreparedAgentCandidateExecution['resolvedModel']\n preparationId: string\n reservationExpiresAtMs: number\n cleanupTimeoutMs: number\n resultTimeoutMs: number\n modelReservation: AgentCandidateProtectedModelReservation\n executorInputs: {\n taskFiles: ReadonlyArray<{\n path: string\n mode: number\n bytes: Uint8Array\n }>\n candidateFiles?: ReadonlyArray<{\n path: string\n mode: number\n bytes: Uint8Array\n }>\n profileFiles: ReadonlyArray<{\n path: string\n mode: number\n root?: 'agent'\n bytes: Uint8Array\n }>\n }\n memoryReservation?: {\n preparationId: string\n accessDigest: `sha256:${string}`\n expiresAtMs: number\n effectiveNamespace: string\n }\n knowledge?: PreparedAgentCandidateExecution['knowledge']\n trace: PreparedAgentCandidateExecution['trace']\n memory: PreparedAgentCandidateExecution['memory']\n}\n\nconst stateByExecution = new WeakMap<PreparedAgentCandidateExecution, PreparedCandidateState>()\nconst lifecycleByExecution = new WeakMap<\n PreparedAgentCandidateExecution,\n {\n status:\n | 'prepared'\n | 'claiming'\n | 'claimed'\n | 'running'\n | 'settling'\n | 'disposing'\n | 'succeeded'\n | 'failed'\n | 'disposal-failed'\n | 'cleanup-failed'\n | 'disposed'\n }\n>()\n\nexport function createPreparedCandidateExecution(\n input: PreparedCandidateState,\n): PreparedAgentCandidateExecution {\n const state = detachPreparedCandidateState(input)\n assertPrivateCandidateIntegrity(state)\n const prepared = Object.freeze({\n bundle: state.bundle,\n benchmark: Object.freeze({ suite: state.benchmarkSuite, task: state.benchmarkTask }),\n executionId: state.executionId,\n roots: state.roots,\n profilePlan: evidenceView(state.profilePlan),\n profileActivation: state.profileActivation,\n executionPlan: evidenceView(state.executionPlan),\n materializationReceipt: state.materializationReceipt,\n launch: state.launch,\n instruction: bytesView(state.instruction, 'bytes'),\n resolvedModel: state.resolvedModel,\n ...(state.knowledge ? { knowledge: knowledgeView(state.knowledge) } : {}),\n trace: state.trace,\n memory: state.memory,\n [preparedCandidateBrand]: true as const,\n })\n stateByExecution.set(prepared, state)\n lifecycleByExecution.set(prepared, { status: 'prepared' })\n return prepared\n}\n\nexport function getPreparedCandidateState(\n prepared: PreparedAgentCandidateExecution,\n): PreparedCandidateState {\n const state = stateByExecution.get(prepared)\n if (!state || prepared[preparedCandidateBrand] !== true) {\n throw new Error('execution must come from prepareAgentCandidateExecution')\n }\n return state\n}\n\n/** Revalidates the exact private bytes immediately before execution or finalization. */\nexport function assertPreparedCandidateIntegrity(\n prepared: PreparedAgentCandidateExecution,\n): PreparedCandidateState {\n const state = getPreparedCandidateState(prepared)\n assertPrivateCandidateIntegrity(state)\n return state\n}\n\n/** Atomically reserves this in-memory prepared value before the first await. */\nexport function beginPreparedCandidateClaim(\n prepared: PreparedAgentCandidateExecution,\n): PreparedCandidateState {\n const state = assertPreparedCandidateIntegrity(prepared)\n transitionLifecycle(prepared, ['prepared'], 'claiming')\n return state\n}\n\n/** Claim an unexecuted preparation for explicit resource disposal. */\nexport function beginPreparedCandidateDisposal(\n prepared: PreparedAgentCandidateExecution,\n): PreparedCandidateState {\n const state = assertPreparedCandidateIntegrity(prepared)\n transitionLifecycle(prepared, ['prepared', 'disposal-failed', 'cleanup-failed'], 'disposing')\n return state\n}\n\nexport function markPreparedCandidateClaimed(prepared: PreparedAgentCandidateExecution): void {\n transitionLifecycle(prepared, ['claiming'], 'claimed')\n}\n\n/** Reveal protected values only after the durable claim and workspace checks succeed. */\nexport function beginPreparedCandidateRun(\n prepared: PreparedAgentCandidateExecution,\n modelAccess: AgentCandidateProtectedModelActivation,\n memoryAccess?: { env: Readonly<Record<string, string>> },\n): { state: PreparedCandidateState; request: AgentCandidateExecutorRequest } {\n const state = assertPreparedCandidateIntegrity(prepared)\n assertProtectedEnvironment(state, modelAccess.env, memoryAccess?.env)\n transitionLifecycle(prepared, ['claimed'], 'running')\n const completeEnvironment = immutableCandidateValue({\n ...state.launch.env,\n ...modelAccess.env,\n ...(memoryAccess?.env ?? {}),\n ...state.trace.env,\n })\n const material = state.executionPlan.value.material\n const request = Object.freeze({\n executionId: state.executionId,\n benchmark: preparedBenchmark(state),\n inputs: Object.freeze({\n task: workspaceInputView(state.benchmarkTask.workspace, state.executorInputs.taskFiles),\n ...(material.candidateWorkspace && state.executorInputs.candidateFiles\n ? {\n candidate: workspaceInputView(\n material.candidateWorkspace,\n state.executorInputs.candidateFiles,\n ),\n }\n : {}),\n profile: Object.freeze({\n files: Object.freeze(\n state.executorInputs.profileFiles.map((file) => profileFileView(file)),\n ),\n }),\n }),\n roots: state.roots.execution,\n profilePlan: evidenceView(state.profilePlan),\n profileActivation: state.profileActivation,\n executionPlan: evidenceView(state.executionPlan),\n materializationReceipt: state.materializationReceipt,\n launch: immutableCandidateValue({ ...state.launch, env: completeEnvironment }),\n instruction: bytesView(state.instruction, 'bytes'),\n resolvedModel: state.resolvedModel,\n hardLimits: Object.freeze({ timeoutMs: state.executionPlan.value.material.limits.timeoutMs }),\n observedLimits: Object.freeze({ maxSteps: state.executionPlan.value.material.limits.maxSteps }),\n ...(state.knowledge ? { knowledge: knowledgeView(state.knowledge) } : {}),\n trace: state.trace,\n memory: state.memory,\n })\n return { state, request }\n}\n\nfunction preparedBenchmark(\n state: PreparedCandidateState,\n): PreparedAgentCandidateExecution['benchmark'] {\n return Object.freeze({ suite: state.benchmarkSuite, task: state.benchmarkTask })\n}\n\nexport function consumePreparedCandidateExecution(\n prepared: PreparedAgentCandidateExecution,\n outcome: 'succeeded' | 'failed' | 'disposed' | 'disposal-failed' | 'cleanup-failed',\n): void {\n transitionLifecycle(\n prepared,\n outcome === 'disposed' || outcome === 'disposal-failed' ? ['disposing'] : ['settling'],\n outcome,\n )\n}\n\nexport function beginPreparedCandidateSettlement(prepared: PreparedAgentCandidateExecution): void {\n transitionLifecycle(prepared, ['claiming', 'claimed', 'running'], 'settling')\n}\n\n/** Rechecks every mutable staging byte immediately before handing control to an executor. */\nexport async function assertPreparedCandidateWorkspaces(\n state: PreparedCandidateState,\n): Promise<void> {\n const plan = state.executionPlan.value.material\n await verifyMaterializedWorkspace(\n state.roots.staging.taskRoot,\n state.benchmarkTask.workspace.material,\n {\n ignoredProtectedRootEntries: ['.git', '.sidecar'],\n },\n )\n if (state.benchmarkTask.repository) {\n await verifyTaskCheckout(state.roots.staging.taskRoot, state.benchmarkTask.repository)\n }\n await verifyMaterializedProfileWorkspace(\n state.roots.staging.profileRoot,\n state.profilePlan.value.material,\n )\n if (plan.candidateWorkspace) {\n const candidateRoot = state.roots.staging.candidateRoot\n if (!candidateRoot) throw new Error('prepared candidate staging root is missing')\n await verifyMaterializedWorkspace(candidateRoot, plan.candidateWorkspace.material)\n } else if (state.roots.staging.candidateRoot !== undefined) {\n throw new Error('disabled candidate unexpectedly has a staging root')\n }\n}\n\nfunction detachPreparedCandidateState(input: PreparedCandidateState): PreparedCandidateState {\n const benchmarkSuite = immutableCandidateValue(\n agentCandidateBenchmarkSuiteSchema.parse(input.benchmarkSuite),\n )\n const benchmarkTask = immutableCandidateValue(\n agentCandidateBenchmarkTaskSchema.parse(input.benchmarkTask),\n )\n const profilePlan = immutableCandidateValue(\n agentCandidateProfilePlanEvidenceSchema.parse(input.profilePlan.value),\n )\n const profileActivation = parseAgentCandidateProfileActivation(\n input.profileActivation,\n profilePlan.digest,\n )\n const executionPlan = immutableCandidateValue(\n agentCandidateExecutionPlanEvidenceSchema.parse(input.executionPlan.value),\n )\n const receiptValue = immutableCandidateValue(\n agentCandidateMaterializationReceiptSchema.parse(input.materializationReceipt.value),\n )\n const materializationReceipt = canonicalCandidateDocument(\n omitTopLevelDigest(receiptValue),\n ) as PreparedAgentCandidateExecution['materializationReceipt']\n if (materializationReceipt.digest !== input.materializationReceipt.digest) {\n throw new Error('materialization receipt digest changed while sealing prepared execution')\n }\n return Object.freeze({\n ports: input.ports,\n bundle: input.bundle,\n benchmarkSuite,\n benchmarkTask,\n executionId: input.executionId,\n roots: immutableCandidateValue(input.roots),\n profilePlan: Object.freeze({\n value: profilePlan,\n bytes: Uint8Array.from(input.profilePlan.bytes),\n written: Object.freeze([...input.profilePlan.written]),\n }),\n profileActivation,\n executionPlan: Object.freeze({\n value: executionPlan,\n bytes: Uint8Array.from(input.executionPlan.bytes),\n }),\n materializationReceipt,\n launch: immutableCandidateValue(input.launch),\n instruction: Object.freeze({\n bytes: Uint8Array.from(input.instruction.bytes),\n delivery: immutableCandidateValue(input.instruction.delivery),\n }),\n resolvedModel: immutableCandidateValue(input.resolvedModel),\n preparationId: input.preparationId,\n reservationExpiresAtMs: input.reservationExpiresAtMs,\n cleanupTimeoutMs: input.cleanupTimeoutMs,\n resultTimeoutMs: input.resultTimeoutMs,\n modelReservation: immutableCandidateValue(input.modelReservation),\n executorInputs: Object.freeze({\n taskFiles: immutableExecutorFiles(input.executorInputs.taskFiles),\n ...(input.executorInputs.candidateFiles\n ? { candidateFiles: immutableExecutorFiles(input.executorInputs.candidateFiles) }\n : {}),\n profileFiles: immutableExecutorFiles(input.executorInputs.profileFiles),\n }),\n ...(input.memoryReservation\n ? { memoryReservation: immutableCandidateValue(input.memoryReservation) }\n : {}),\n ...(input.knowledge\n ? {\n knowledge: Object.freeze({\n candidate: immutableCandidateValue(input.knowledge.candidate),\n ...(input.knowledge.stateScope\n ? { stateScope: immutableCandidateValue(input.knowledge.stateScope) }\n : {}),\n snapshot: immutableCandidateValue(input.knowledge.snapshot),\n files: immutableExecutorFiles(input.knowledge.files),\n ...(input.knowledge.retrievalConfig\n ? { retrievalConfig: Uint8Array.from(input.knowledge.retrievalConfig) }\n : {}),\n }),\n }\n : {}),\n trace: immutableCandidateValue(input.trace),\n memory: immutableCandidateValue(input.memory),\n })\n}\n\nfunction assertPrivateCandidateIntegrity(state: PreparedCandidateState): void {\n assertAgentCandidateExecutionRoots(state.roots.execution)\n const bundleMaterial = omitTopLevelDigest(state.bundle)\n if (canonicalCandidateDigest(bundleMaterial) !== state.bundle.digest) {\n throw new Error('prepared candidate bundle no longer matches its digest')\n }\n assertPlanEvidence(state.profilePlan.value, state.profilePlan.bytes, 'profile plan')\n parseAgentCandidateProfileActivation(state.profileActivation, state.profilePlan.value.digest)\n assertPlanEvidence(state.executionPlan.value, state.executionPlan.bytes, 'execution plan')\n agentCandidateExecutionPlanEvidenceSchema.parse(state.executionPlan.value)\n\n const receipt = agentCandidateMaterializationReceiptSchema.parse(\n state.materializationReceipt.value,\n )\n const receiptBytes = canonicalCandidateBytes(omitTopLevelDigest(receipt))\n if (\n canonicalCandidateDigest(omitTopLevelDigest(receipt)) !== state.materializationReceipt.digest ||\n !Buffer.from(receiptBytes).equals(Buffer.from(state.materializationReceipt.bytes))\n ) {\n throw new Error('prepared materialization receipt no longer matches its canonical bytes')\n }\n\n assertSignedBenchmarkInput(state)\n const instruction = Buffer.from(state.benchmarkTask.instruction, 'utf8')\n if (\n !Buffer.from(state.instruction.bytes).equals(instruction) ||\n JSON.stringify(state.instruction.delivery) !==\n JSON.stringify(state.executionPlan.value.material.instructionDelivery)\n ) {\n throw new Error('prepared instruction no longer matches the signed execution plan')\n }\n if (\n !/^candidate-preparation\\.[A-Za-z0-9_-]{43}$/.test(state.preparationId) ||\n !Number.isSafeInteger(state.reservationExpiresAtMs) ||\n state.reservationExpiresAtMs <= 0 ||\n !Number.isSafeInteger(state.cleanupTimeoutMs) ||\n state.cleanupTimeoutMs <= 0 ||\n !Number.isSafeInteger(state.resultTimeoutMs) ||\n state.resultTimeoutMs <= 0 ||\n JSON.stringify(state.resolvedModel) !==\n JSON.stringify(state.executionPlan.value.material.model.resolved) ||\n state.modelReservation.digest !== state.executionPlan.value.material.model.access.grantDigest ||\n state.modelReservation.preparationId !== state.preparationId ||\n state.modelReservation.expiresAtMs !== state.reservationExpiresAtMs ||\n canonicalCandidateDigest(state.modelReservation.network) !==\n canonicalCandidateDigest(state.executionPlan.value.material.model.access.network) ||\n canonicalCandidateDigest(state.modelReservation.enforcedLimits) !==\n canonicalCandidateDigest(modelLimits(state.executionPlan.value.material.limits))\n ) {\n throw new Error('prepared model access no longer matches the signed execution plan')\n }\n assertExecutorInputs(state)\n assertPreparedKnowledge(state)\n if (\n (state.memory.mode === 'isolated' && !state.memoryReservation) ||\n (state.memory.mode === 'disabled' && state.memoryReservation)\n ) {\n throw new Error('prepared memory reservation does not match the signed execution plan')\n }\n if (\n state.memory.mode === 'isolated' &&\n state.memoryReservation &&\n (state.memoryReservation.preparationId !== state.preparationId ||\n state.memoryReservation.expiresAtMs !== state.reservationExpiresAtMs ||\n state.memoryReservation.effectiveNamespace !== state.memory.effectiveNamespace)\n ) {\n throw new Error('prepared memory reservation identity no longer matches the execution')\n }\n if (JSON.stringify(state.memory) !== JSON.stringify(state.executionPlan.value.material.memory)) {\n throw new Error('prepared memory no longer matches the signed execution plan')\n }\n\n const expectedTags = {\n [CANDIDATE_TRACE_TAGS.executionId]: state.executionId,\n [CANDIDATE_TRACE_TAGS.bundleDigest]: state.bundle.digest,\n [CANDIDATE_TRACE_TAGS.executionPlanDigest]: state.executionPlan.value.digest,\n [CANDIDATE_TRACE_TAGS.materializationReceiptDigest]: state.materializationReceipt.digest,\n }\n const expectedTraceEnvironment = {\n [CANDIDATE_TRACE_ENV.executionId]: state.executionId,\n [CANDIDATE_TRACE_ENV.bundleDigest]: state.bundle.digest,\n [CANDIDATE_TRACE_ENV.executionPlanDigest]: state.executionPlan.value.digest,\n [CANDIDATE_TRACE_ENV.materializationReceiptDigest]: state.materializationReceipt.digest,\n [CANDIDATE_TRACE_ENV.traceRunId]: state.trace.runId,\n }\n if (\n !state.trace.runId.startsWith(\n `${state.executionId}:attempt-${state.executionPlan.value.material.runCell.attempt}:`,\n ) ||\n canonicalCandidateDigest(state.trace.tags) !== canonicalCandidateDigest(expectedTags) ||\n canonicalCandidateDigest(state.trace.env) !== canonicalCandidateDigest(expectedTraceEnvironment)\n ) {\n throw new Error('prepared trace identity no longer matches the signed execution')\n }\n}\n\nfunction assertPlanEvidence(\n evidence:\n | PreparedAgentCandidateExecution['profilePlan']['value']\n | PreparedAgentCandidateExecution['executionPlan']['value'],\n bytes: Uint8Array,\n label: string,\n): void {\n const expected = canonicalCandidateBytes(evidence.material)\n if (\n sha256Bytes(expected) !== evidence.digest ||\n !Buffer.from(expected).equals(Buffer.from(bytes)) ||\n evidence.artifact.sha256 !== evidence.digest ||\n evidence.artifact.byteLength !== bytes.byteLength ||\n !('content' in evidence.artifact) ||\n !Buffer.from(evidence.artifact.content, 'base64').equals(Buffer.from(bytes))\n ) {\n throw new Error(`prepared ${label} no longer matches its canonical bytes`)\n }\n}\n\nfunction evidenceView<T extends { value: unknown; bytes: Uint8Array }>(evidence: T): T {\n const bytes = Uint8Array.from(evidence.bytes)\n return Object.freeze({\n ...evidence,\n get bytes(): Uint8Array {\n return Uint8Array.from(bytes)\n },\n })\n}\n\nfunction bytesView<T extends { bytes: Uint8Array }>(value: T, key: 'bytes'): T {\n const bytes = Uint8Array.from(value.bytes)\n return Object.freeze({\n ...value,\n get [key](): Uint8Array {\n return Uint8Array.from(bytes)\n },\n })\n}\n\nfunction knowledgeView(\n knowledge: NonNullable<PreparedAgentCandidateExecution['knowledge']>,\n): NonNullable<PreparedAgentCandidateExecution['knowledge']> {\n const retrievalConfig = knowledge.retrievalConfig\n ? Uint8Array.from(knowledge.retrievalConfig)\n : undefined\n return Object.freeze({\n candidate: knowledge.candidate,\n ...(knowledge.stateScope ? { stateScope: immutableCandidateValue(knowledge.stateScope) } : {}),\n snapshot: knowledge.snapshot,\n files: Object.freeze(knowledge.files.map((file) => profileFileView(file))),\n ...(retrievalConfig\n ? {\n get retrievalConfig(): Uint8Array {\n return Uint8Array.from(retrievalConfig)\n },\n }\n : {}),\n })\n}\nfunction workspaceInputView(\n snapshot: AgentCandidateExecutorRequest['inputs']['task']['snapshot'],\n sourceFiles: PreparedCandidateState['executorInputs']['taskFiles'],\n): AgentCandidateExecutorRequest['inputs']['task'] {\n return Object.freeze({\n snapshot,\n files: Object.freeze(sourceFiles.map((file) => executorFileView(file))),\n })\n}\n\nfunction profileFileView(source: {\n path: string\n mode: number\n root?: 'agent'\n bytes: Uint8Array\n}): AgentCandidateExecutorRequest['inputs']['profile']['files'][number] {\n const bytes = Uint8Array.from(source.bytes)\n return Object.freeze({\n path: source.path,\n mode: source.mode,\n ...(source.root === 'agent' ? { root: 'agent' as const } : {}),\n get bytes(): Uint8Array {\n return Uint8Array.from(bytes)\n },\n })\n}\n\nfunction executorFileView(\n source: PreparedCandidateState['executorInputs']['taskFiles'][number],\n): AgentCandidateExecutorWorkspaceFile {\n const bytes = Uint8Array.from(source.bytes)\n return Object.freeze({\n path: source.path,\n mode: source.mode,\n get bytes(): Uint8Array {\n return Uint8Array.from(bytes)\n },\n })\n}\n\nfunction assertExecutorInputs(state: PreparedCandidateState): void {\n const material = state.executionPlan.value.material\n assertWorkspaceExecutorFiles(\n state.executorInputs.taskFiles,\n state.benchmarkTask.workspace.material,\n )\n if (material.candidateWorkspace) {\n if (!state.executorInputs.candidateFiles) {\n throw new Error('prepared candidate executor files are missing')\n }\n assertWorkspaceExecutorFiles(\n state.executorInputs.candidateFiles,\n material.candidateWorkspace.material,\n )\n } else if (state.executorInputs.candidateFiles) {\n throw new Error('disabled candidate has executor files')\n }\n\n const expectedFiles = state.profilePlan.value.material.files\n if (state.executorInputs.profileFiles.length !== expectedFiles.length) {\n throw new Error('prepared profile executor files do not match the signed profile plan')\n }\n for (let index = 0; index < expectedFiles.length; index++) {\n const expected = expectedFiles[index]\n const actual = state.executorInputs.profileFiles[index]\n if (\n !expected ||\n !actual ||\n actual.path !== expected.relPath ||\n (actual.root ?? 'workspace') !== (expected.root ?? 'workspace') ||\n actual.mode !== expected.mode ||\n sha256Bytes(actual.bytes) !== expected.contentSha256\n ) {\n throw new Error('prepared profile executor files do not match the signed profile plan')\n }\n }\n}\n\nfunction assertPreparedKnowledge(state: PreparedCandidateState): void {\n const expected = state.bundle.knowledge\n const actual = state.knowledge\n if (!expected || !actual) {\n if (expected || actual)\n throw new Error('prepared knowledge does not match the candidate bundle')\n return\n }\n if (\n canonicalCandidateDigest(actual.candidate) !== canonicalCandidateDigest(expected.candidate) ||\n canonicalCandidateDigest(actual.stateScope ?? null) !==\n canonicalCandidateDigest(expected.stateScope ?? null) ||\n canonicalCandidateDigest(actual.snapshot) !== canonicalCandidateDigest(expected.snapshot) ||\n state.executionPlan.value.material.knowledgeManifestDigest !== expected.snapshot.digest\n ) {\n throw new Error('prepared knowledge identity does not match the candidate bundle')\n }\n assertWorkspaceExecutorFiles(actual.files, expected.snapshot.material)\n if (!expected.retrievalConfig || !actual.retrievalConfig) {\n if (expected.retrievalConfig || actual.retrievalConfig) {\n throw new Error('prepared knowledge retrieval config does not match the candidate bundle')\n }\n return\n }\n if (\n actual.retrievalConfig.byteLength !== expected.retrievalConfig.byteLength ||\n sha256Bytes(actual.retrievalConfig) !== expected.retrievalConfig.sha256\n ) {\n throw new Error('prepared knowledge retrieval config does not match the candidate bundle')\n }\n}\n\nfunction assertWorkspaceExecutorFiles(\n actualFiles: PreparedCandidateState['executorInputs']['taskFiles'],\n expected: AgentCandidateWorkspaceManifestMaterial,\n): void {\n if (actualFiles.length !== expected.files.length) {\n throw new Error('prepared workspace executor files do not match the signed manifest')\n }\n for (let index = 0; index < expected.files.length; index++) {\n const actual = actualFiles[index]\n const planned = expected.files[index]\n if (\n !actual ||\n !planned ||\n actual.path !== planned.path ||\n actual.mode !== planned.mode ||\n actual.bytes.byteLength !== planned.byteLength ||\n sha256Bytes(actual.bytes) !== planned.sha256\n ) {\n throw new Error('prepared workspace executor files do not match the signed manifest')\n }\n }\n}\n\nfunction assertSignedBenchmarkInput(state: PreparedCandidateState): void {\n const plan = state.executionPlan.value.material\n const cell = plan.runCell\n const suite = state.benchmarkSuite\n const task = state.benchmarkTask\n const receipt = state.materializationReceipt.value\n const cellIndex = cell.taskIndex * suite.reps + cell.repetition\n if (\n canonicalCandidateDigest(omitTopLevelDigest(suite)) !== suite.digest ||\n canonicalCandidateDigest(omitTopLevelDigest(task)) !== task.digest ||\n canonicalCandidateDigest(omitTopLevelDigest(cell)) !== cell.digest ||\n cell.bundleDigest !== state.bundle.digest ||\n cell.suiteDigest !== suite.digest ||\n cell.taskDigest !== task.digest ||\n suite.taskDigests[cell.taskIndex] !== task.digest ||\n suite.seeds[cellIndex] !== cell.seed ||\n cell.repetition >= suite.reps ||\n cell.attempt < 1 ||\n cell.attempt > task.attempt.maxAttempts\n ) {\n throw new Error('prepared candidate no longer matches its signed experiment cell')\n }\n const suiteBytes = canonicalCandidateBytes(omitTopLevelDigest(suite))\n const taskBytes = canonicalCandidateBytes(omitTopLevelDigest(task))\n if (\n receipt.benchmark.suite.digest !== suite.digest ||\n receipt.benchmark.suite.material.sha256 !== sha256Bytes(suiteBytes) ||\n receipt.benchmark.suite.material.byteLength !== suiteBytes.byteLength ||\n receipt.benchmark.task.digest !== task.digest ||\n receipt.benchmark.task.material.sha256 !== sha256Bytes(taskBytes) ||\n receipt.benchmark.task.material.byteLength !== taskBytes.byteLength\n ) {\n throw new Error('materialization receipt no longer matches its signed benchmark input')\n }\n}\n\nfunction immutableExecutorFiles<\n T extends { path: string; mode: number; root?: 'agent'; bytes: Uint8Array },\n>(files: ReadonlyArray<T>): ReadonlyArray<T> {\n return Object.freeze(\n files.map((file) => Object.freeze({ ...file, bytes: Uint8Array.from(file.bytes) }) as T),\n )\n}\n\nfunction modelLimits(\n limits: PreparedAgentCandidateExecution['executionPlan']['value']['material']['limits'],\n): AgentCandidateProtectedModelReservation['enforcedLimits'] {\n return {\n maxModelCalls: limits.maxModelCalls,\n maxInputTokens: limits.maxInputTokens,\n maxOutputTokens: limits.maxOutputTokens,\n maxCostUsd: limits.maxCostUsd,\n }\n}\n\nfunction transitionLifecycle(\n prepared: PreparedAgentCandidateExecution,\n expected: ReadonlyArray<\n | 'prepared'\n | 'claiming'\n | 'claimed'\n | 'running'\n | 'settling'\n | 'disposing'\n | 'succeeded'\n | 'failed'\n | 'disposal-failed'\n | 'cleanup-failed'\n | 'disposed'\n >,\n next:\n | 'claiming'\n | 'claimed'\n | 'running'\n | 'settling'\n | 'disposing'\n | 'succeeded'\n | 'failed'\n | 'disposal-failed'\n | 'cleanup-failed'\n | 'disposed',\n): void {\n const lifecycle = lifecycleByExecution.get(prepared)\n if (!lifecycle || !expected.includes(lifecycle.status)) {\n throw new Error(`prepared candidate execution is already ${lifecycle?.status ?? 'unknown'}`)\n }\n lifecycle.status = next\n}\n\nfunction assertProtectedEnvironment(\n state: PreparedCandidateState,\n modelEnvironment: Readonly<Record<string, string>>,\n memoryEnvironment: Readonly<Record<string, string>> | undefined,\n): void {\n const seen = new Set([...Object.keys(state.launch.env), ...Object.keys(state.trace.env)])\n for (const [name, value] of [\n ...Object.entries(modelEnvironment),\n ...Object.entries(memoryEnvironment ?? {}),\n ]) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || typeof value !== 'string' || value.length < 8) {\n throw new Error('protected model activation contains an invalid environment binding')\n }\n if (seen.has(name)) {\n throw new Error(`protected model activation collides with environment binding ${name}`)\n }\n seen.add(name)\n }\n}\n","import type { AgentCandidateArtifactRef, Sha256Digest } from '@tangle-network/agent-interface'\n\nimport { type AgentCandidateExecutionClaim, candidateClaimFileInternals } from './claim'\nimport { canonicalCandidateDigest } from './digest'\nimport { candidateExecutionOwnerWindowMs } from './execution-window'\nimport { assertPreparedCandidateIntegrity } from './prepared-state'\nimport type { PreparedAgentCandidateExecution } from './types'\n\n/** Extract the complete durable claim from a prepared execution. */\nexport function candidateExecutionClaim(\n prepared: PreparedAgentCandidateExecution,\n preparationEvidence: {\n executionPlan: AgentCandidateArtifactRef\n materializationReceipt: AgentCandidateArtifactRef\n },\n): AgentCandidateExecutionClaim {\n const state = assertPreparedCandidateIntegrity(prepared)\n const material = prepared.executionPlan.value.material\n const attempt = {\n number: material.runCell.attempt,\n maxAttempts: state.benchmarkTask.attempt.maxAttempts,\n retryPolicy: state.benchmarkTask.attempt.retryPolicy,\n } as const\n const nowMs = Date.now()\n if (!Number.isSafeInteger(nowMs) || nowMs < 0) {\n throw new Error('candidate execution claim-store clock returned an invalid timestamp')\n }\n const leaseExpiresAtMs =\n nowMs +\n candidateExecutionOwnerWindowMs(\n material.limits.timeoutMs,\n state.cleanupTimeoutMs,\n state.resultTimeoutMs,\n )\n if (!Number.isSafeInteger(leaseExpiresAtMs) || leaseExpiresAtMs <= 0) {\n throw new Error('candidate execution leaseExpiresAtMs must be a positive safe timestamp')\n }\n if (leaseExpiresAtMs > state.reservationExpiresAtMs) {\n throw new Error(\n 'candidate preparation expires before its full execution and cleanup owner window',\n )\n }\n if (\n preparationEvidence.executionPlan.sha256 !== prepared.executionPlan.value.digest ||\n preparationEvidence.executionPlan.byteLength !== state.executionPlan.bytes.byteLength\n ) {\n throw new Error('persisted execution plan does not match its canonical preparation bytes')\n }\n if (\n preparationEvidence.materializationReceipt.sha256 !== state.materializationReceipt.digest ||\n preparationEvidence.materializationReceipt.byteLength !==\n state.materializationReceipt.bytes.byteLength\n ) {\n throw new Error(\n 'persisted materialization receipt does not match its canonical preparation bytes',\n )\n }\n return candidateClaimFileInternals.sealClaim({\n executionId: prepared.executionId,\n attempt: attempt.number,\n maxAttempts: attempt.maxAttempts,\n retryPolicy: attempt.retryPolicy,\n bundleDigest: prepared.bundle.digest,\n executionPlanDigest: prepared.executionPlan.value.digest,\n preparationEvidence,\n retryLineageDigest: retryLineageDigest(prepared, state.resultTimeoutMs),\n leaseExpiresAtMs,\n resultTimeoutMs: state.resultTimeoutMs,\n cleanup: {\n preparationId: state.preparationId,\n modelGrantDigest: state.modelReservation.digest,\n resolvedModel: state.resolvedModel,\n traceRunId: state.trace.runId,\n cleanupTimeoutMs: state.cleanupTimeoutMs,\n ...(state.memoryReservation\n ? {\n memory: {\n accessDigest: state.memoryReservation.accessDigest,\n effectiveNamespace: state.memoryReservation.effectiveNamespace,\n },\n }\n : {}),\n },\n })\n}\n\nfunction retryLineageDigest(\n prepared: PreparedAgentCandidateExecution,\n resultTimeoutMs: number,\n): Sha256Digest {\n const material = prepared.executionPlan.value.material\n return canonicalCandidateDigest({\n resultTimeoutMs,\n executionPlan: {\n ...material,\n runCell: {\n ...material.runCell,\n attempt: 0,\n digest: `sha256:${'0'.repeat(64)}`,\n },\n model: {\n ...material.model,\n access: {\n ...material.model.access,\n grantDigest: `sha256:${'0'.repeat(64)}`,\n },\n },\n memory:\n material.memory.mode === 'disabled'\n ? material.memory\n : {\n mode: 'isolated',\n scope: 'task',\n effectiveNamespace: 'candidate/retry-lineage-normalized',\n reset: {\n kind: 'fresh',\n emptyStateDigest: material.memory.reset.emptyStateDigest,\n },\n beforeState: {\n digest: material.memory.beforeState.digest,\n material: material.memory.beforeState.material,\n manifest: {\n sha256: material.memory.beforeState.manifest.sha256,\n byteLength: material.memory.beforeState.manifest.byteLength,\n },\n archive: {\n sha256: material.memory.beforeState.archive.sha256,\n byteLength: material.memory.beforeState.archive.byteLength,\n },\n },\n ...(material.memory.seedDigest ? { seedDigest: material.memory.seedDigest } : {}),\n },\n },\n })\n}\n","import {\n type AgentCandidateTaskOutcomeSpec,\n agentCandidateTerminationSchema,\n agentCandidateWorkspaceManifestMaterialSchema,\n} from '@tangle-network/agent-interface'\nimport { assertExactObjectKeys as assertExactKeys } from './exact-object'\nimport type { AgentCandidateExecutorFinalCapture, AgentCandidateProtectedRunCapture } from './types'\n\nconst sealedFinalCaptureBrand: unique symbol = Symbol('sealedAgentCandidateExecutorFinalCapture')\n\nexport type SealedAgentCandidateExecutorFinalCapture = AgentCandidateExecutorFinalCapture & {\n readonly [sealedFinalCaptureBrand]: true\n}\n\n/** Validate and detach the only candidate-authored fields accepted from execution. */\nexport function sealAgentCandidateProtectedRunCapture(\n value: unknown,\n): AgentCandidateProtectedRunCapture {\n const capture = requireRecord(value, 'candidate execution capture')\n assertExactKeys(capture, ['executionId', 'termination'], 'candidate execution capture')\n if (typeof capture.executionId !== 'string' || capture.executionId.length === 0) {\n throw new Error('candidate execution capture has an invalid executionId')\n }\n return Object.freeze({\n executionId: capture.executionId,\n termination: Object.freeze(agentCandidateTerminationSchema.parse(capture.termination)),\n })\n}\n\n/** Validate, detach, and freeze evaluator-owned evidence captured after process death. */\nexport function sealAgentCandidateExecutorFinalCapture(\n value: unknown,\n expectedOutcome: AgentCandidateTaskOutcomeSpec,\n): SealedAgentCandidateExecutorFinalCapture {\n const capture = requireRecord(value, 'candidate final capture')\n assertExactKeys(capture, [], 'candidate final capture', [\n 'taskOutcome',\n 'memoryAfter',\n 'evidence',\n ])\n\n const taskOutcome = capture.taskOutcome\n ? sealTaskOutcomeCapture(capture.taskOutcome, expectedOutcome)\n : undefined\n const memoryAfter = capture.memoryAfter ? sealMemoryCapture(capture.memoryAfter) : undefined\n if (capture.evidence !== undefined && !(capture.evidence instanceof Uint8Array)) {\n throw new Error('candidate executor evidence must be a byte array')\n }\n const evidence = capture.evidence ? Uint8Array.from(capture.evidence) : undefined\n return Object.freeze({\n ...(taskOutcome ? { taskOutcome } : {}),\n ...(memoryAfter ? { memoryAfter: Object.freeze(memoryAfter) } : {}),\n ...(evidence ? { evidence } : {}),\n [sealedFinalCaptureBrand]: true as const,\n })\n}\n\n/** Prove exact process death before any final evidence capture. */\nexport function sealAgentCandidateExecutorStopAcknowledgement(value: unknown): void {\n const capture = requireRecord(value, 'candidate stop acknowledgement')\n assertExactKeys(capture, ['stopped'], 'candidate stop acknowledgement')\n if (capture.stopped !== true) {\n throw new Error('candidate stop acknowledgement does not prove process death')\n }\n}\n\nfunction sealMemoryCapture(\n value: unknown,\n): NonNullable<AgentCandidateExecutorFinalCapture['memoryAfter']> {\n const capture = requireRecord(value, 'candidate memory capture')\n assertExactKeys(capture, ['afterState', 'archive'], 'candidate memory capture')\n if (!(capture.archive instanceof Uint8Array)) {\n throw new Error('candidate memory capture archive must be a byte array')\n }\n return Object.freeze({\n afterState: Object.freeze(\n agentCandidateWorkspaceManifestMaterialSchema.parse(capture.afterState),\n ),\n archive: Uint8Array.from(capture.archive),\n })\n}\n\nfunction sealTaskOutcomeCapture(\n value: unknown,\n expected: AgentCandidateTaskOutcomeSpec,\n): NonNullable<AgentCandidateExecutorFinalCapture['taskOutcome']> {\n const capture = requireRecord(value, 'candidate task capture')\n if (capture.kind === 'output') {\n assertExactKeys(capture, ['kind', 'bytes'], 'candidate task output capture')\n if (expected.kind !== 'output') {\n throw new Error('candidate task output capture does not match the signed outcome kind')\n }\n if (!(capture.bytes instanceof Uint8Array)) {\n throw new Error('candidate task output capture must contain a byte array')\n }\n if (capture.bytes.byteLength > expected.maxBytes) {\n throw new Error(`candidate task output exceeds the frozen ${expected.maxBytes}-byte maximum`)\n }\n return Object.freeze({ kind: 'output', bytes: Uint8Array.from(capture.bytes) })\n }\n assertExactKeys(\n capture,\n ['kind', 'resultTree', 'afterState', 'archive', 'gitDiff'],\n 'candidate task capture',\n )\n if (capture.kind !== 'workspace') {\n throw new Error('candidate task capture has an invalid outcome kind')\n }\n if (expected.kind !== 'workspace') {\n throw new Error('candidate workspace capture does not match the signed outcome kind')\n }\n if (\n typeof capture.resultTree !== 'string' ||\n !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(capture.resultTree)\n ) {\n throw new Error('candidate task capture resultTree is not a Git object id')\n }\n if (!(capture.archive instanceof Uint8Array) || !(capture.gitDiff instanceof Uint8Array)) {\n throw new Error('candidate task capture archive and gitDiff must be byte arrays')\n }\n const afterState = agentCandidateWorkspaceManifestMaterialSchema.parse(capture.afterState)\n return Object.freeze({\n kind: 'workspace',\n resultTree: capture.resultTree,\n afterState: Object.freeze(afterState),\n archive: Uint8Array.from(capture.archive),\n gitDiff: Uint8Array.from(capture.gitDiff),\n })\n}\n\nfunction requireRecord(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`)\n }\n return value as Record<string, unknown>\n}\n","import { isLlmSpan, type LlmSpan, type TraceStore } from '@tangle-network/agent-eval'\nimport type {\n AgentCandidateFixedSpend,\n AgentCandidateModelSettlementCall,\n} from '@tangle-network/agent-interface'\nimport { assertExactObjectKeys } from './exact-object'\nimport type { AgentCandidateProtectedModelSettlement } from './types'\n\nconst USD_NANOS = 1_000_000_000\n\nexport interface SealedAgentCandidateModelSettlement {\n readonly value: AgentCandidateProtectedModelSettlement\n /** `inputTokens` is the gateway's accounted input total. */\n readonly usage: AgentCandidateFixedSpend\n}\n\n/** Validate and detach the evaluator gateway's terminal, revoked call ledger. */\nexport function sealAgentCandidateModelSettlement(\n settlement: AgentCandidateProtectedModelSettlement,\n expected: { preparationId: string; grantDigest: string; model: string },\n): SealedAgentCandidateModelSettlement {\n assertExactObjectKeys(\n settlement,\n ['preparationId', 'grantDigest', 'closed', 'usageWithinLimits', 'calls'],\n 'model settlement',\n )\n if (settlement.closed !== true) throw new Error('protected model grant is not closed')\n if (settlement.usageWithinLimits !== true) {\n throw new Error('protected model settlement reports usage outside frozen limits')\n }\n if (settlement.grantDigest !== expected.grantDigest) {\n throw new Error('protected model settlement grant digest does not match the reservation')\n }\n if (settlement.preparationId !== expected.preparationId) {\n throw new Error('protected model settlement preparation does not match the reservation')\n }\n if (!Array.isArray(settlement.calls)) {\n throw new Error('protected model settlement calls must be an array')\n }\n\n const callIds = new Set<string>()\n const spanIds = new Set<string>()\n let accountedInputTokens = 0\n let outputTokens = 0\n let cachedInputTokens = 0\n let reasoningTokens = 0\n let costUsdNanos = 0\n let costProvenance: AgentCandidateFixedSpend['costProvenance'] = 'observed'\n const calls = settlement.calls.map((source, index) => {\n assertExactObjectKeys(\n source,\n [\n 'callId',\n 'generationId',\n 'traceSpanId',\n 'status',\n 'model',\n 'startedAtMs',\n 'endedAtMs',\n 'inputTokens',\n 'accountedInputTokens',\n 'outputTokens',\n 'cachedInputTokens',\n 'reasoningTokens',\n 'costUsdNanos',\n 'costProvenance',\n ],\n `model settlement call ${index}`,\n )\n assertIdentifier(source.callId, `model settlement call ${index} callId`)\n assertIdentifier(source.generationId, `model settlement call ${index} generationId`)\n assertIdentifier(source.traceSpanId, `model settlement call ${index} traceSpanId`)\n if (source.traceSpanId !== source.generationId) {\n throw new Error(`model settlement call ${index} traceSpanId is not its router generationId`)\n }\n if (source.status !== 'succeeded' && source.status !== 'failed') {\n throw new Error(`model settlement call ${index} has an invalid status`)\n }\n if (callIds.has(source.callId))\n throw new Error('protected model settlement has duplicate call ids')\n if (spanIds.has(source.traceSpanId)) {\n throw new Error('protected model settlement has duplicate trace span ids')\n }\n callIds.add(source.callId)\n spanIds.add(source.traceSpanId)\n if (source.model !== expected.model) {\n throw new Error(`protected model settlement call ${index} has an unexpected model`)\n }\n assertTimestamp(source.startedAtMs, `model settlement call ${index} startedAtMs`)\n assertTimestamp(source.endedAtMs, `model settlement call ${index} endedAtMs`)\n if (source.endedAtMs < source.startedAtMs) {\n throw new Error(`model settlement call ${index} ended before it started`)\n }\n assertCount(source.inputTokens, `model settlement call ${index} inputTokens`)\n assertCount(source.accountedInputTokens, `model settlement call ${index} accountedInputTokens`)\n if (source.accountedInputTokens < source.inputTokens) {\n throw new Error(\n `model settlement call ${index} accountedInputTokens cannot be less than inputTokens`,\n )\n }\n assertCount(source.outputTokens, `model settlement call ${index} outputTokens`)\n assertCount(source.cachedInputTokens, `model settlement call ${index} cachedInputTokens`)\n cachedInputTokens = safeAdd(\n cachedInputTokens,\n source.cachedInputTokens,\n 'cached input token total',\n )\n assertCount(source.reasoningTokens, `model settlement call ${index} reasoningTokens`)\n reasoningTokens = safeAdd(reasoningTokens, source.reasoningTokens, 'reasoning token total')\n assertCount(source.costUsdNanos, `model settlement call ${index} costUsdNanos`)\n if (source.costProvenance !== 'observed' && source.costProvenance !== 'estimated') {\n throw new Error(`model settlement call ${index} has an invalid cost provenance`)\n }\n if (source.costProvenance === 'estimated') costProvenance = 'estimated'\n accountedInputTokens = safeAdd(\n accountedInputTokens,\n source.accountedInputTokens,\n 'accounted input token total',\n )\n outputTokens = safeAdd(outputTokens, source.outputTokens, 'output token total')\n costUsdNanos = safeAdd(costUsdNanos, source.costUsdNanos, 'cost total')\n return Object.freeze({ ...source })\n })\n\n const usage = Object.freeze({\n costUsdNanos,\n inputTokens: accountedInputTokens,\n outputTokens,\n cachedInputTokens,\n reasoningTokens,\n modelCalls: calls.length,\n costProvenance,\n })\n return Object.freeze({\n value: Object.freeze({\n preparationId: settlement.preparationId,\n grantDigest: settlement.grantDigest,\n closed: true as const,\n usageWithinLimits: true as const,\n calls: Object.freeze(calls),\n }),\n usage,\n })\n}\n\n/**\n * Append the only accepted LLM spans from the router's closed ledger.\n * Candidate and executor code may write tool/process spans, but never model usage.\n */\nexport async function appendAuthoritativeModelSettlementSpans(\n traceStore: TraceStore,\n runId: string,\n settlement: SealedAgentCandidateModelSettlement,\n): Promise<void> {\n const run = await traceStore.getRun(runId)\n if (!run) throw new Error(`protected trace run is missing before model settlement: ${runId}`)\n if (run.status === 'running' || run.endedAt === undefined) {\n throw new Error('protected trace run must be terminal before model spans are appended')\n }\n const existing = await traceStore.spans({ runId })\n if (existing.some(isLlmSpan)) {\n throw new Error(\n 'protected trace contains a model span not authored from the closed router ledger',\n )\n }\n const occupiedIds = new Set(existing.map((span) => span.spanId))\n for (const call of settlement.value.calls) {\n if (occupiedIds.has(call.traceSpanId)) {\n throw new Error(\n `protected trace span identity collides with router generation ${call.generationId}`,\n )\n }\n await traceStore.appendSpan({\n runId,\n spanId: call.traceSpanId,\n kind: 'llm',\n name: 'protected model call',\n model: call.model,\n messages: [],\n startedAt: call.startedAtMs,\n endedAt: call.endedAtMs,\n status: call.status === 'succeeded' ? 'ok' : 'error',\n inputTokens: call.inputTokens,\n outputTokens: call.outputTokens,\n cachedTokens: call.cachedInputTokens,\n reasoningTokens: call.reasoningTokens,\n costUsd: call.costUsdNanos / USD_NANOS,\n attributes: {\n 'tangle.protected_model.source': 'router-settlement',\n 'tangle.router.call_id': call.callId,\n 'tangle.router.generation_id': call.generationId,\n },\n })\n }\n}\n\n/** Match every protected trace span one-for-one against gateway call evidence. */\nexport function assertTraceMatchesModelSettlement(\n spans: readonly LlmSpan[],\n settlement: SealedAgentCandidateModelSettlement,\n): void {\n if (spans.length !== settlement.value.calls.length) {\n throw new Error(\n `protected trace model calls ${spans.length} do not match model ledger ${settlement.value.calls.length}`,\n )\n }\n const byId = new Map(spans.map((span) => [span.spanId, span]))\n if (byId.size !== spans.length) throw new Error('protected trace has duplicate model span ids')\n for (const call of settlement.value.calls) {\n const span = byId.get(call.traceSpanId)\n if (!span) {\n throw new Error(`protected trace is missing model ledger span ${call.traceSpanId}`)\n }\n assertTraceCall(span, call)\n }\n}\n\nexport function usdToNanos(value: number, label: string): number {\n if (!Number.isFinite(value) || value < 0) throw new Error(`${label} must be nonnegative`)\n const nanos = Math.round(value * USD_NANOS)\n if (!Number.isSafeInteger(nanos)) throw new Error(`${label} exceeds fixed-point range`)\n return nanos\n}\n\nfunction assertTraceCall(span: LlmSpan, call: AgentCandidateModelSettlementCall): void {\n if (span.model !== call.model) {\n throw new Error(`protected trace span ${span.spanId} model does not match model ledger`)\n }\n if (\n span.startedAt !== call.startedAtMs ||\n span.endedAt !== call.endedAtMs ||\n span.status !== (call.status === 'succeeded' ? 'ok' : 'error')\n ) {\n throw new Error(\n `protected trace span ${span.spanId} timing or status does not match model ledger`,\n )\n }\n if (\n span.attributes?.['tangle.protected_model.source'] !== 'router-settlement' ||\n span.attributes?.['tangle.router.call_id'] !== call.callId ||\n span.attributes?.['tangle.router.generation_id'] !== call.generationId\n ) {\n throw new Error(`protected trace span ${span.spanId} lacks router settlement provenance`)\n }\n for (const [name, traced, settled] of [\n ['inputTokens', span.inputTokens, call.inputTokens],\n ['outputTokens', span.outputTokens, call.outputTokens],\n ['cachedInputTokens', span.cachedTokens ?? 0, call.cachedInputTokens],\n ['reasoningTokens', span.reasoningTokens ?? 0, call.reasoningTokens],\n ] as const) {\n if (traced === undefined || traced !== settled) {\n throw new Error(\n `protected trace span ${span.spanId} ${name} ${traced} does not match model ledger ${settled}`,\n )\n }\n }\n if (span.costUsd === undefined) {\n throw new Error(`protected trace span ${span.spanId} is missing costUsd`)\n }\n const tracedCost = usdToNanos(span.costUsd, `protected trace span ${span.spanId} costUsd`)\n if (tracedCost !== call.costUsdNanos) {\n throw new Error(\n `protected trace span ${span.spanId} costUsdNanos ${tracedCost} does not match model ledger ${call.costUsdNanos}`,\n )\n }\n}\n\nfunction assertIdentifier(value: unknown, label: string): asserts value is string {\n if (typeof value !== 'string' || value.length === 0 || value.length > 256) {\n throw new Error(`${label} must be a non-empty bounded string`)\n }\n}\n\nfunction assertCount(value: unknown, label: string): asserts value is number {\n if (!Number.isSafeInteger(value) || (value as number) < 0) {\n throw new Error(`${label} must be a nonnegative safe integer`)\n }\n}\n\nfunction assertTimestamp(value: unknown, label: string): asserts value is number {\n if (!Number.isSafeInteger(value) || (value as number) <= 0) {\n throw new Error(`${label} must be a positive safe integer`)\n }\n}\n\nfunction safeAdd(left: number, right: number, label: string): number {\n const total = left + right\n if (!Number.isSafeInteger(total)) throw new Error(`${label} exceeds safe integer range`)\n return total\n}\n","import type { Span, TraceStore } from '@tangle-network/agent-eval'\nimport { isLlmSpan, REDACTION_VERSION } from '@tangle-network/agent-eval'\nimport type {\n AgentCandidateBenchmarkResultEvidence,\n AgentCandidateFixedSpend,\n AgentCandidateMemoryReceipt,\n AgentCandidateModelSettlementEvidence,\n AgentCandidateRunReceipt,\n AgentCandidateTermination,\n} from '@tangle-network/agent-interface'\nimport {\n agentCandidateRunReceiptSchema,\n agentCandidateWorkspaceSnapshotEvidenceSchema,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateBytes, canonicalCandidateDocument, sha256Bytes } from './digest'\nimport type { SealedAgentCandidateExecutorFinalCapture } from './executor-capture'\nimport type { PersistedAgentCandidateExecutorCapture } from './executor-capture-evidence'\nimport {\n assertTraceMatchesModelSettlement,\n type SealedAgentCandidateModelSettlement,\n usdToNanos,\n} from './model-settlement'\nimport { persistCandidateOutputArtifact } from './output-artifacts'\nimport type { PreparedCandidateState } from './prepared-state'\nimport {\n assertNoProtectedBytes,\n type ProtectedRedactionReport,\n type ProtectedTraceIdentity,\n redactProtectedReason,\n redactProtectedValue,\n} from './protected-redaction'\nimport {\n type AgentCandidateOutputArtifactPort,\n type AgentCandidateProtectedRunCapture,\n type AgentCandidateRunFinalization,\n CANDIDATE_TRACE_TAGS,\n type VerifiedAgentCandidateTaskOutcome,\n} from './types'\n\ninterface CandidateFinalizationEvidence {\n finalCapture: SealedAgentCandidateExecutorFinalCapture\n persistedCapture: PersistedAgentCandidateExecutorCapture\n modelSettlement: AgentCandidateModelSettlementEvidence & {\n artifact: import('@tangle-network/agent-interface').AgentCandidateArtifactRef\n }\n taskOutcome: VerifiedAgentCandidateTaskOutcome\n benchmarkResult: AgentCandidateBenchmarkResultEvidence & {\n artifact: import('@tangle-network/agent-interface').AgentCandidateArtifactRef\n }\n outputArtifacts: AgentCandidateOutputArtifactPort\n}\n\n/** Builds a candidate run receipt exclusively from protected trace and memory evidence. */\nexport async function finalizeAgentCandidateRun(\n state: PreparedCandidateState,\n capture: AgentCandidateProtectedRunCapture,\n traceStore: TraceStore,\n traceIdentity: ProtectedTraceIdentity,\n settlement: SealedAgentCandidateModelSettlement,\n evidence: CandidateFinalizationEvidence,\n protectedValues: readonly string[],\n writeRedactionReport?: ProtectedRedactionReport,\n signal?: AbortSignal,\n): Promise<AgentCandidateRunFinalization> {\n let termination: AgentCandidateTermination | undefined\n try {\n signal?.throwIfAborted()\n if (capture.executionId !== state.executionId) {\n throw new Error('protected capture execution id does not match the prepared execution')\n }\n termination = capture.termination\n if (\n termination.kind === 'timeout' &&\n termination.timeoutMs !== state.executionPlan.value.material.limits.timeoutMs\n ) {\n throw new Error('timeout termination does not match the frozen execution limit')\n }\n\n const run = await traceStore.getRun(traceIdentity.runId)\n if (!run) throw new Error(`protected trace run is missing: ${traceIdentity.runId}`)\n if (run.status === 'running' || run.endedAt === undefined) {\n throw new Error('protected trace run is not terminal')\n }\n assertTraceBindings(run.tags, traceIdentity.tags)\n\n const [spans, events, budget, artifacts] = await Promise.all([\n traceStore.spans({ runId: run.runId }),\n traceStore.events({ runId: run.runId }),\n traceStore.budget(run.runId),\n traceStore.artifacts(run.runId),\n ])\n const orderedSpans = [...spans].sort(\n (a, b) => a.startedAt - b.startedAt || compareStrings(a.spanId, b.spanId),\n )\n const orderedEvents = [...events].sort(\n (a, b) => a.timestamp - b.timestamp || compareStrings(a.eventId, b.eventId),\n )\n const orderedBudget = [...budget].sort(\n (a, b) => a.timestamp - b.timestamp || compareStrings(a.dimension, b.dimension),\n )\n const orderedArtifacts = [...artifacts].sort((a, b) =>\n compareStrings(a.artifactId, b.artifactId),\n )\n\n const modelSpans = orderedSpans.filter(isLlmSpan)\n assertTraceMatchesModelSettlement(modelSpans, settlement)\n const steps = enforceLimits(state, run.startedAt, run.endedAt, orderedSpans, settlement)\n const memory = await memoryReceipt(\n state,\n evidence.finalCapture,\n evidence.persistedCapture.memoryAfter,\n signal,\n )\n const redacted = redactProtectedValue(\n {\n run: { ...run, redactionVersion: REDACTION_VERSION },\n spans: orderedSpans,\n events: orderedEvents,\n budget: orderedBudget,\n artifacts: orderedArtifacts,\n },\n protectedValues,\n )\n const combinedByRule = { ...(writeRedactionReport?.byRule ?? {}) }\n for (const [rule, count] of Object.entries(redacted.report.byRule)) {\n combinedByRule[rule] = (combinedByRule[rule] ?? 0) + count\n }\n const traceMaterial = {\n ...(redacted.value as Record<string, unknown>),\n evaluatorLimits: { resultTimeoutMs: state.resultTimeoutMs },\n redaction: {\n version: REDACTION_VERSION,\n redactionCount:\n (writeRedactionReport?.redactionCount ?? 0) + redacted.report.redactionCount,\n byRule: combinedByRule,\n },\n }\n const traceBytes = canonicalCandidateBytes(traceMaterial)\n assertNoProtectedBytes(traceBytes, protectedValues)\n const traceArtifact = await persistCandidateOutputArtifact(evidence.outputArtifacts, {\n executionId: state.executionId,\n purpose: 'trace',\n bytes: traceBytes,\n signal,\n })\n const trace = {\n artifact: traceArtifact,\n eventCount:\n 1 +\n orderedSpans.length +\n orderedEvents.length +\n orderedBudget.length +\n orderedArtifacts.length,\n modelCallCount: modelSpans.length,\n }\n const document = canonicalCandidateDocument<AgentCandidateRunReceipt>({\n kind: 'agent-candidate-run',\n digestAlgorithm: 'rfc8785-sha256',\n bundleDigest: state.bundle.digest,\n runCellDigest: state.executionPlan.value.material.runCell.digest,\n materializationReceiptDigest: state.materializationReceipt.digest,\n executionPlanDigest: state.executionPlan.value.digest,\n timing: {\n startedAtMs: run.startedAt,\n endedAtMs: run.endedAt,\n durationMs: run.endedAt - run.startedAt,\n },\n steps,\n memory,\n trace,\n termination,\n executorCapture: evidence.persistedCapture.evidence,\n modelSettlement: evidence.modelSettlement,\n taskOutcome: evidence.taskOutcome.evidence,\n benchmarkResult: evidence.benchmarkResult,\n })\n agentCandidateRunReceiptSchema.parse(document.value)\n const runReceipt = await persistCandidateOutputArtifact(evidence.outputArtifacts, {\n executionId: state.executionId,\n purpose: 'run-receipt',\n bytes: document.bytes,\n signal,\n })\n return {\n succeeded: true,\n receipt: document,\n artifacts: {\n modelSettlement: evidence.modelSettlement.artifact,\n executorCapture: evidence.persistedCapture.evidence,\n taskOutcome: evidence.taskOutcome.evidence.artifact,\n benchmarkResult: evidence.benchmarkResult.artifact,\n runReceipt,\n },\n }\n } catch (error) {\n return {\n ...failedAgentCandidateRun(\n state,\n redactProtectedReason(\n error instanceof Error ? error.message : String(error),\n protectedValues,\n ),\n termination,\n settlement.usage,\n ),\n }\n }\n}\n\nfunction assertTraceBindings(\n tags: Record<string, string> | undefined,\n expected: Readonly<Record<string, string>>,\n): void {\n for (const name of Object.values(CANDIDATE_TRACE_TAGS)) {\n if (tags?.[name] !== expected[name]) {\n throw new Error(`protected trace is not bound to prepared execution tag ${name}`)\n }\n }\n}\n\nfunction enforceLimits(\n state: PreparedCandidateState,\n startedAt: number,\n endedAt: number,\n spans: Span[],\n settlement: SealedAgentCandidateModelSettlement,\n): number {\n const limits = state.executionPlan.value.material.limits\n const usage = settlement.usage\n // The runtime-owned Date.now deadline decides when the process must stop.\n // This separately rejects a receipt whose evaluator-owned trace claims a\n // longer run; neither clock can make an over-limit execution admissible.\n const wallMs = endedAt - startedAt\n if (!Number.isFinite(wallMs) || wallMs < 0 || wallMs > limits.timeoutMs) {\n throw new Error(`protected trace wall time ${wallMs} exceeds ${limits.timeoutMs}`)\n }\n const steps = spans.filter((span) => span.kind === 'tool').length\n const checks: Array<[number, number, string]> = [\n [steps, limits.maxSteps, 'tool steps'],\n [usage.modelCalls, limits.maxModelCalls, 'model calls'],\n [usage.inputTokens, limits.maxInputTokens, 'input tokens'],\n [usage.outputTokens, limits.maxOutputTokens, 'output tokens'],\n ]\n for (const [actual, limit, label] of checks) {\n if (actual > limit) throw new Error(`protected ${label} ${actual} exceeds ${limit}`)\n }\n if (usage.costUsdNanos > usdToNanos(limits.maxCostUsd, 'frozen maxCostUsd')) {\n throw new Error(\n `protected cost USD ${usage.costUsdNanos / 1_000_000_000} exceeds ${limits.maxCostUsd}`,\n )\n }\n return steps\n}\n\nasync function memoryReceipt(\n state: PreparedCandidateState,\n capture: SealedAgentCandidateExecutorFinalCapture,\n persisted: PersistedAgentCandidateExecutorCapture['memoryAfter'],\n signal?: AbortSignal,\n): Promise<AgentCandidateMemoryReceipt> {\n signal?.throwIfAborted()\n if (state.memory.mode === 'disabled') {\n if (capture.memoryAfter !== undefined || persisted !== undefined) {\n throw new Error('disabled memory cannot return an after-state')\n }\n return { mode: 'disabled' }\n }\n if (!capture.memoryAfter) throw new Error('isolated memory is missing its protected after-state')\n if (!persisted) throw new Error('isolated memory is missing persisted capture evidence')\n const afterState = capture.memoryAfter.afterState\n const manifestBytes = canonicalCandidateBytes(afterState)\n const snapshot = agentCandidateWorkspaceSnapshotEvidenceSchema.parse({\n kind: 'agent-candidate-workspace-snapshot',\n digest: sha256Bytes(manifestBytes),\n material: afterState,\n manifest: persisted.manifest,\n archive: persisted.archive,\n })\n return {\n mode: 'isolated',\n scope: 'task',\n effectiveNamespace: state.memory.effectiveNamespace,\n resetEvidenceDigest: state.memory.reset.evidence.sha256,\n beforeStateDigest: state.memory.beforeState.digest,\n afterState: snapshot,\n }\n}\n\nexport function failedAgentCandidateRun(\n state: PreparedCandidateState,\n reason: string,\n termination?: AgentCandidateTermination,\n usage: AgentCandidateFixedSpend | null = null,\n): AgentCandidateRunFinalization & { succeeded: false } {\n return {\n succeeded: false,\n reason,\n partial: {\n executionId: state.executionId,\n bundleDigest: state.bundle.digest,\n executionPlanDigest: state.executionPlan.value.digest,\n materializationReceiptDigest: state.materializationReceipt.digest,\n ...(termination ? { termination } : {}),\n },\n usage,\n }\n}\n\nfunction compareStrings(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0\n}\n","import type { BenchmarkEvaluation } from '@tangle-network/agent-eval'\nimport type {\n AgentCandidateBenchmarkGraderIdentity,\n AgentCandidateFixedSpend,\n AgentCandidateTermination,\n} from '@tangle-network/agent-interface'\n\nimport { readVerifiedArtifact } from './artifacts'\nimport { canonicalCandidateDigest, immutableCandidateValue, sha256Bytes } from './digest'\nimport type {\n AgentCandidateBenchmarkGraderPort,\n AgentCandidateOutputArtifactPort,\n VerifiedAgentCandidateTaskOutcome,\n} from './types'\n\nexport interface BoundAgentCandidateBenchmarkRun {\n readonly grader: AgentCandidateBenchmarkGraderIdentity\n readonly grading: {\n readonly usage: AgentCandidateFixedSpend\n readonly timing: {\n readonly startedAtMs: number\n readonly endedAtMs: number\n readonly durationMs: number\n }\n }\n readonly evaluation: BenchmarkEvaluation\n readonly evidence: Uint8Array\n}\n\n/**\n * Admit verified grader bytes to the evaluator runner and reject any result\n * that is not bound to those bytes, the exact task outcome, and its raw output.\n */\nexport async function runBoundCandidateBenchmarkGrader(input: {\n executionId: string\n termination: AgentCandidateTermination\n outcome: VerifiedAgentCandidateTaskOutcome\n expectedGrader: AgentCandidateBenchmarkGraderIdentity\n grader: AgentCandidateBenchmarkGraderPort\n artifacts: AgentCandidateOutputArtifactPort\n signal?: AbortSignal\n}): Promise<BoundAgentCandidateBenchmarkRun> {\n input.signal?.throwIfAborted()\n const descriptor = snapshotGraderDescriptor(input.grader, input.expectedGrader)\n const implementationBytes = await readVerifiedArtifact(descriptor.artifact, input.artifacts)\n if (implementationBytes.byteLength === 0) {\n throw new Error('candidate benchmark grader implementation cannot be empty')\n }\n const expectedImplementationDigest = sha256Bytes(implementationBytes)\n const termination = immutableCandidateValue(input.termination)\n const run = input.grader.run\n const startedAtMs = Date.now()\n const result = await run(\n Object.freeze({\n executionId: input.executionId,\n termination,\n outcome: input.outcome,\n implementation: detachedImplementation(implementationBytes),\n signal: input.signal ?? new AbortController().signal,\n }),\n )\n const endedAtMs = Math.max(startedAtMs, Date.now())\n input.signal?.throwIfAborted()\n assertExactRunnerResult(result)\n\n const evidence = Uint8Array.from(result.evidence)\n const outputDigest = sha256Bytes(evidence)\n if (result.binding.implementationDigest !== expectedImplementationDigest) {\n throw new Error(\n 'candidate benchmark grader executed implementation digest does not match its verified artifact',\n )\n }\n if (result.binding.taskOutcomeDigest !== input.outcome.evidence.digest) {\n throw new Error(\n 'candidate benchmark grader task outcome digest does not match verified outcome',\n )\n }\n if (result.binding.outputDigest !== outputDigest) {\n throw new Error('candidate benchmark grader raw output digest does not match returned evidence')\n }\n\n return Object.freeze({\n grader: descriptor,\n grading: immutableCandidateValue({\n usage: emptyFixedSpend(),\n timing: {\n startedAtMs,\n endedAtMs,\n durationMs: endedAtMs - startedAtMs,\n },\n }),\n evaluation: result.evaluation,\n evidence,\n })\n}\n\nfunction snapshotGraderDescriptor(\n grader: AgentCandidateBenchmarkGraderPort,\n expected: AgentCandidateBenchmarkGraderIdentity,\n): BoundAgentCandidateBenchmarkRun['grader'] {\n if (!grader.name || !grader.version) {\n throw new Error('candidate benchmark grader name and version must be non-empty')\n }\n const actual = {\n name: grader.name,\n version: grader.version,\n format: 'tangle-grader' as const,\n artifact: grader.artifact,\n }\n if (canonicalCandidateDigest(actual) !== canonicalCandidateDigest(expected)) {\n throw new Error('candidate benchmark grader does not match the signed task grader')\n }\n return immutableCandidateValue(expected)\n}\n\nfunction emptyFixedSpend(): AgentCandidateFixedSpend {\n return {\n inputTokens: 0,\n outputTokens: 0,\n cachedInputTokens: 0,\n reasoningTokens: 0,\n modelCalls: 0,\n costUsdNanos: 0,\n costProvenance: 'observed',\n }\n}\n\nfunction detachedImplementation(bytes: Uint8Array): {\n readonly byteLength: number\n readonly bytes: Uint8Array\n} {\n const stored = Uint8Array.from(bytes)\n return Object.freeze({\n byteLength: stored.byteLength,\n get bytes(): Uint8Array {\n return Uint8Array.from(stored)\n },\n })\n}\n\nfunction assertExactRunnerResult(\n value: unknown,\n): asserts value is Awaited<ReturnType<AgentCandidateBenchmarkGraderPort['run']>> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('candidate benchmark grader result must be an object')\n }\n const result = value as Record<string, unknown>\n const keys = Object.keys(result).sort()\n if (\n keys.length !== 3 ||\n keys[0] !== 'binding' ||\n keys[1] !== 'evaluation' ||\n keys[2] !== 'evidence'\n ) {\n throw new Error('candidate benchmark grader returned unknown or missing fields')\n }\n if (!(result.evidence instanceof Uint8Array)) {\n throw new Error('candidate benchmark grader evidence must be bytes')\n }\n if (\n result.binding === null ||\n typeof result.binding !== 'object' ||\n Array.isArray(result.binding)\n ) {\n throw new Error('candidate benchmark grader binding must be an object')\n }\n const bindingKeys = Object.keys(result.binding).sort()\n if (\n bindingKeys.length !== 3 ||\n bindingKeys[0] !== 'implementationDigest' ||\n bindingKeys[1] !== 'outputDigest' ||\n bindingKeys[2] !== 'taskOutcomeDigest'\n ) {\n throw new Error('candidate benchmark grader binding returned unknown or missing fields')\n }\n}\n","import type {\n AgentCandidateArtifactRef,\n AgentCandidateTaskOutcomeSpec,\n AgentCandidateTaskOutputSpec,\n AgentCandidateWorkspaceManifestMaterial,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateBytes } from './digest'\nimport type { SealedAgentCandidateExecutorFinalCapture } from './executor-capture'\nimport { persistCandidateOutputArtifact } from './output-artifacts'\nimport type { AgentCandidateOutputArtifactPort } from './types'\n\nexport type PersistedAgentCandidateTaskCapture =\n | {\n readonly kind: 'workspace'\n readonly resultTree: string\n readonly afterState: AgentCandidateWorkspaceManifestMaterial\n readonly manifest: AgentCandidateArtifactRef\n readonly archive: AgentCandidateArtifactRef\n readonly gitDiff: AgentCandidateArtifactRef\n }\n | {\n readonly kind: 'output'\n readonly spec: AgentCandidateTaskOutputSpec\n readonly artifact: AgentCandidateArtifactRef\n }\n\nexport interface PersistedAgentCandidateExecutorCapture {\n readonly evidence: AgentCandidateArtifactRef\n readonly taskOutcome?: PersistedAgentCandidateTaskCapture\n readonly memoryAfter?: {\n readonly afterState: AgentCandidateWorkspaceManifestMaterial\n readonly manifest: AgentCandidateArtifactRef\n readonly archive: AgentCandidateArtifactRef\n }\n}\n\n/** Persist structurally valid post-stop bytes without claiming they passed outcome verification. */\nexport async function persistAgentCandidateExecutorCapture(\n identity: { executionId: string; executionPlanDigest: Sha256Digest },\n expected: AgentCandidateTaskOutcomeSpec,\n capture: SealedAgentCandidateExecutorFinalCapture,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n signal?: AbortSignal,\n): Promise<PersistedAgentCandidateExecutorCapture> {\n const executorEvidence = capture.evidence\n ? await persistCandidateOutputArtifact(outputArtifacts, {\n executionId: identity.executionId,\n purpose: 'executor-native-evidence',\n bytes: capture.evidence,\n signal,\n })\n : undefined\n const taskOutcome = capture.taskOutcome\n ? await persistTaskCapture(\n identity.executionId,\n expected,\n capture.taskOutcome,\n outputArtifacts,\n signal,\n )\n : undefined\n const memoryAfter = capture.memoryAfter\n ? await persistWorkspaceCapture(\n identity.executionId,\n 'memory-after-manifest',\n 'memory-after-archive',\n capture.memoryAfter.afterState,\n capture.memoryAfter.archive,\n outputArtifacts,\n signal,\n )\n : undefined\n const bytes = canonicalCandidateBytes({\n kind: 'agent-candidate-executor-capture',\n executionPlanDigest: identity.executionPlanDigest,\n ...(executorEvidence ? { executorEvidence } : {}),\n ...(taskOutcome ? { taskOutcome } : {}),\n ...(memoryAfter ? { memoryAfter } : {}),\n })\n const evidence = await persistCandidateOutputArtifact(outputArtifacts, {\n executionId: identity.executionId,\n purpose: 'executor-capture',\n bytes,\n signal,\n })\n return Object.freeze({\n evidence,\n ...(taskOutcome ? { taskOutcome: Object.freeze(taskOutcome) } : {}),\n ...(memoryAfter ? { memoryAfter: Object.freeze(memoryAfter) } : {}),\n })\n}\n\nasync function persistTaskCapture(\n executionId: string,\n expected: AgentCandidateTaskOutcomeSpec,\n capture: NonNullable<SealedAgentCandidateExecutorFinalCapture['taskOutcome']>,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n signal?: AbortSignal,\n): Promise<PersistedAgentCandidateTaskCapture> {\n if (capture.kind === 'output') {\n if (expected.kind !== 'output')\n throw new Error('captured output does not match the signed task')\n const artifact = await persistCandidateOutputArtifact(outputArtifacts, {\n executionId,\n purpose: 'task-output',\n bytes: capture.bytes,\n signal,\n })\n return {\n kind: 'output',\n spec: { mediaType: expected.mediaType, maxBytes: expected.maxBytes },\n artifact,\n }\n }\n if (expected.kind !== 'workspace') {\n throw new Error('captured workspace does not match the signed task')\n }\n const workspace = await persistWorkspaceCapture(\n executionId,\n 'task-manifest',\n 'task-archive',\n capture.afterState,\n capture.archive,\n outputArtifacts,\n signal,\n )\n const gitDiff = await persistCandidateOutputArtifact(outputArtifacts, {\n executionId,\n purpose: 'task-patch',\n bytes: capture.gitDiff,\n signal,\n })\n return { kind: 'workspace', resultTree: capture.resultTree, ...workspace, gitDiff }\n}\n\nasync function persistWorkspaceCapture(\n executionId: string,\n manifestPurpose: 'task-manifest' | 'memory-after-manifest',\n archivePurpose: 'task-archive' | 'memory-after-archive',\n afterState: AgentCandidateWorkspaceManifestMaterial,\n archiveBytes: Uint8Array,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n signal?: AbortSignal,\n): Promise<{\n afterState: AgentCandidateWorkspaceManifestMaterial\n manifest: AgentCandidateArtifactRef\n archive: AgentCandidateArtifactRef\n}> {\n const manifestBytes = canonicalCandidateBytes(afterState)\n const [manifest, archive] = await Promise.all([\n persistCandidateOutputArtifact(outputArtifacts, {\n executionId,\n purpose: manifestPurpose,\n bytes: manifestBytes,\n signal,\n }),\n persistCandidateOutputArtifact(outputArtifacts, {\n executionId,\n purpose: archivePurpose,\n bytes: archiveBytes,\n signal,\n }),\n ])\n return { afterState, manifest, archive }\n}\n","import { mkdtemp, rm } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\n\nimport type { BenchmarkEvaluation } from '@tangle-network/agent-eval'\nimport {\n type AgentCandidateArtifactRef,\n type AgentCandidateBenchmarkResultEvidence,\n type AgentCandidateModelSettlementEvidence,\n type AgentCandidateResolvedModel,\n type AgentCandidateTaskOutcomeEvidence,\n type AgentCandidateTaskOutcomeMaterial,\n type AgentCandidateTaskOutcomeSpec,\n type AgentCandidateTaskOutputSpec,\n type AgentCandidateTaskRepository,\n type AgentCandidateTermination,\n type AgentCandidateWorkspaceSnapshotEvidence,\n agentCandidateBenchmarkResultEvidenceSchema,\n agentCandidateModelSettlementEvidenceSchema,\n agentCandidateTaskOutcomeEvidenceSchema,\n agentCandidateWorkspaceSnapshotEvidenceSchema,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport { readMaterializedWorkspaceFiles } from './artifacts'\nimport { runBoundCandidateBenchmarkGrader } from './benchmark-grader'\nimport {\n canonicalCandidateBytes,\n embeddedCandidateArtifact,\n immutableCandidateValue,\n sha256Bytes,\n} from './digest'\nimport type { SealedAgentCandidateExecutorFinalCapture } from './executor-capture'\nimport {\n type PersistedAgentCandidateExecutorCapture,\n type PersistedAgentCandidateTaskCapture,\n persistAgentCandidateExecutorCapture,\n} from './executor-capture-evidence'\nimport { verifyTaskOutcomePatch } from './git-materialize'\nimport type { SealedAgentCandidateModelSettlement } from './model-settlement'\nimport { persistCandidateOutputArtifact } from './output-artifacts'\nimport type { PreparedCandidateState } from './prepared-state'\nimport { assertNoProtectedBytes } from './protected-redaction'\nimport type {\n AgentCandidateBenchmarkGraderPort,\n AgentCandidateExecutorTaskOutcomeCapture,\n AgentCandidateOutputArtifactPort,\n VerifiedAgentCandidateTaskOutcome,\n} from './types'\nimport { verifiedTaskOutcomeBrand } from './types'\n\nexport type PersistedAgentCandidateModelSettlement = AgentCandidateModelSettlementEvidence & {\n artifact: AgentCandidateArtifactRef\n}\n\nexport type PersistedAgentCandidateBenchmarkResult = AgentCandidateBenchmarkResultEvidence & {\n artifact: AgentCandidateArtifactRef\n}\n\n/** Persist the closed evaluator model ledger as canonical receipt evidence. */\nexport async function persistCandidateModelSettlement(\n state: PreparedCandidateState,\n settlement: SealedAgentCandidateModelSettlement,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n): Promise<PersistedAgentCandidateModelSettlement> {\n return await persistCandidateModelSettlementEvidence(\n {\n executionId: state.executionId,\n executionPlanDigest: state.executionPlan.value.digest,\n resolvedModel: state.resolvedModel,\n },\n settlement,\n outputArtifacts,\n )\n}\n\n/** Persist a closed model ledger when only durable recovery identity remains. */\nexport async function persistCandidateModelSettlementEvidence(\n identity: {\n executionId: string\n executionPlanDigest: Sha256Digest\n resolvedModel: AgentCandidateResolvedModel\n },\n settlement: SealedAgentCandidateModelSettlement,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n): Promise<PersistedAgentCandidateModelSettlement> {\n const material = {\n kind: 'agent-candidate-model-settlement-material' as const,\n executionPlanDigest: identity.executionPlanDigest,\n preparationId: settlement.value.preparationId,\n grantDigest: settlement.value.grantDigest,\n closed: true as const,\n usageWithinLimits: settlement.value.usageWithinLimits,\n resolved: identity.resolvedModel,\n calls: settlement.value.calls.map((call) => ({\n callId: call.callId,\n generationId: call.generationId,\n traceSpanId: call.traceSpanId,\n status: call.status,\n model: call.model,\n startedAtMs: call.startedAtMs,\n endedAtMs: call.endedAtMs,\n inputTokens: call.inputTokens,\n accountedInputTokens: call.accountedInputTokens,\n outputTokens: call.outputTokens,\n cachedInputTokens: call.cachedInputTokens ?? 0,\n reasoningTokens: call.reasoningTokens ?? 0,\n costUsdNanos: call.costUsdNanos,\n costProvenance: call.costProvenance,\n })),\n usage: settlement.usage,\n }\n const bytes = canonicalCandidateBytes(material)\n const digest = sha256Bytes(bytes)\n const artifact = await persistCandidateOutputArtifact(outputArtifacts, {\n executionId: identity.executionId,\n purpose: 'model-settlement',\n bytes,\n })\n return immutableCandidateValue(\n agentCandidateModelSettlementEvidenceSchema.parse({\n kind: 'agent-candidate-model-settlement',\n digest,\n material,\n artifact,\n }),\n ) as PersistedAgentCandidateModelSettlement\n}\n\n/** Verify once, persist the sealed capture once, and bind the resulting task evidence. */\nexport async function persistVerifiedAgentCandidateExecutorCapture(\n state: PreparedCandidateState,\n capture: SealedAgentCandidateExecutorFinalCapture,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n protectedValues: readonly string[],\n signal?: AbortSignal,\n): Promise<{\n persistedCapture: PersistedAgentCandidateExecutorCapture\n taskOutcome: VerifiedAgentCandidateTaskOutcome\n}> {\n signal?.throwIfAborted()\n const taskCapture = capture.taskOutcome\n if (!taskCapture) throw new Error('candidate final capture is missing the task outcome')\n if (capture.evidence) assertNoProtectedBytes(capture.evidence, protectedValues)\n const expected = state.benchmarkTask.outcome\n if (taskCapture.kind !== expected.kind) {\n throw new Error(\n `candidate captured ${taskCapture.kind} outcome does not match expected ${expected.kind} outcome`,\n )\n }\n const verified =\n taskCapture.kind === 'output' && expected.kind === 'output'\n ? verifyOutputTaskCapture(taskCapture.bytes, expected, protectedValues)\n : taskCapture.kind === 'workspace' && expected.kind === 'workspace'\n ? await verifyWorkspaceTaskCapture(state, taskCapture, protectedValues, signal)\n : undefined\n if (!verified) throw new Error('candidate task outcome kind could not be narrowed')\n await verifyMemoryCapture(state, capture, protectedValues, signal)\n\n const persistedCapture = await persistAgentCandidateExecutorCapture(\n {\n executionId: state.executionId,\n executionPlanDigest: state.executionPlan.value.digest,\n },\n expected,\n capture,\n outputArtifacts,\n signal,\n )\n const persisted = persistedCapture.taskOutcome\n if (!persisted || persisted.kind !== verified.kind) {\n throw new Error('persisted task capture kind changed')\n }\n const taskOutcome =\n verified.kind === 'output' && persisted.kind === 'output'\n ? await persistVerifiedOutputTaskOutcome(state, verified, persisted, outputArtifacts, signal)\n : verified.kind === 'workspace' && persisted.kind === 'workspace'\n ? await persistVerifiedWorkspaceTaskOutcome(\n state,\n verified,\n persisted,\n outputArtifacts,\n signal,\n )\n : undefined\n if (!taskOutcome) throw new Error('persisted task outcome kind could not be narrowed')\n return Object.freeze({ persistedCapture, taskOutcome })\n}\n\ninterface VerifiedWorkspaceTaskCapture {\n readonly kind: 'workspace'\n readonly patch: Uint8Array\n readonly archive: Uint8Array\n readonly afterState: Extract<\n AgentCandidateExecutorTaskOutcomeCapture,\n { kind: 'workspace' }\n >['afterState']\n readonly manifestBytes: Uint8Array\n readonly resultCommit: string\n readonly resultTree: string\n readonly repository: AgentCandidateTaskRepository\n}\n\nasync function verifyWorkspaceTaskCapture(\n state: PreparedCandidateState,\n capture: Extract<AgentCandidateExecutorTaskOutcomeCapture, { kind: 'workspace' }>,\n protectedValues: readonly string[],\n signal?: AbortSignal,\n): Promise<VerifiedWorkspaceTaskCapture> {\n const repository = state.benchmarkTask.repository\n if (!repository) throw new Error('workspace task outcome is missing repository identity')\n const patch = Uint8Array.from(capture.gitDiff)\n const archive = Uint8Array.from(capture.archive)\n if (archive.byteLength === 0) throw new Error('candidate task archive cannot be empty')\n assertNoProtectedBytes(patch, protectedValues)\n assertNoProtectedBytes(archive, protectedValues)\n const afterState = immutableCandidateValue(capture.afterState)\n const verified = await verifyTaskOutcomePatch({\n repositoryRoot: state.roots.staging.taskRoot,\n baseCommit: repository.baseCommit,\n baseTree: repository.baseTree,\n resultTree: capture.resultTree,\n patch,\n afterState,\n })\n signal?.throwIfAborted()\n const manifestBytes = canonicalCandidateBytes(afterState)\n assertNoProtectedBytes(manifestBytes, protectedValues)\n const provisionalSnapshot = agentCandidateWorkspaceSnapshotEvidenceSchema.parse({\n kind: 'agent-candidate-workspace-snapshot',\n digest: sha256Bytes(manifestBytes),\n material: afterState,\n manifest: embeddedCandidateArtifact(manifestBytes),\n archive: embeddedCandidateArtifact(archive),\n })\n await verifyTaskOutcomeArchive(state, provisionalSnapshot, archive, protectedValues)\n signal?.throwIfAborted()\n return {\n kind: 'workspace',\n patch,\n archive,\n afterState,\n manifestBytes,\n resultCommit: verified.resultCommit,\n resultTree: verified.resultTree,\n repository,\n }\n}\n\nasync function persistVerifiedWorkspaceTaskOutcome(\n state: PreparedCandidateState,\n verified: VerifiedWorkspaceTaskCapture,\n persisted: Extract<PersistedAgentCandidateTaskCapture, { kind: 'workspace' }>,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n signal?: AbortSignal,\n): Promise<VerifiedAgentCandidateTaskOutcome> {\n const { afterState, manifestBytes, patch, repository } = verified\n const snapshot = agentCandidateWorkspaceSnapshotEvidenceSchema.parse({\n kind: 'agent-candidate-workspace-snapshot',\n digest: sha256Bytes(manifestBytes),\n material: afterState,\n manifest: persisted.manifest,\n archive: persisted.archive,\n })\n const material = {\n kind: 'agent-candidate-task-outcome-material' as const,\n executionPlanDigest: state.executionPlan.value.digest,\n outcome: {\n kind: 'workspace' as const,\n baseRepository: {\n identity: repository.identity,\n rootIdentity: repository.rootIdentity,\n commit: repository.baseCommit,\n tree: repository.baseTree,\n },\n resultRepository: {\n identity: repository.identity,\n rootIdentity: repository.rootIdentity,\n commit: verified.resultCommit,\n tree: verified.resultTree,\n },\n afterState: snapshot,\n gitDiff: {\n format: 'git-diff-binary' as const,\n artifact: persisted.gitDiff,\n },\n },\n } satisfies AgentCandidateTaskOutcomeMaterial\n const evidence = await persistTaskOutcomeEvidence(state, material, outputArtifacts, signal)\n const storedPatch = Uint8Array.from(patch)\n return Object.freeze({\n kind: 'workspace' as const,\n evidence,\n get patch(): Uint8Array {\n return Uint8Array.from(storedPatch)\n },\n [verifiedTaskOutcomeBrand]: true as const,\n })\n}\n\ninterface VerifiedOutputTaskCapture {\n readonly kind: 'output'\n readonly bytes: Uint8Array\n readonly spec: AgentCandidateTaskOutputSpec\n}\n\nfunction verifyOutputTaskCapture(\n capturedBytes: Uint8Array,\n expected: Extract<AgentCandidateTaskOutcomeSpec, { kind: 'output' }>,\n protectedValues: readonly string[],\n): VerifiedOutputTaskCapture {\n if (capturedBytes.byteLength === 0) throw new Error('candidate task output cannot be empty')\n if (capturedBytes.byteLength > expected.maxBytes) {\n throw new Error(`candidate task output exceeds the frozen ${expected.maxBytes}-byte maximum`)\n }\n const output = Uint8Array.from(capturedBytes)\n assertNoProtectedBytes(output, protectedValues)\n return {\n kind: 'output',\n bytes: output,\n spec: { mediaType: expected.mediaType, maxBytes: expected.maxBytes },\n }\n}\n\nasync function persistVerifiedOutputTaskOutcome(\n state: PreparedCandidateState,\n verified: VerifiedOutputTaskCapture,\n persisted: Extract<PersistedAgentCandidateTaskCapture, { kind: 'output' }>,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n signal?: AbortSignal,\n): Promise<VerifiedAgentCandidateTaskOutcome> {\n if (\n persisted.spec.mediaType !== verified.spec.mediaType ||\n persisted.spec.maxBytes !== verified.spec.maxBytes\n ) {\n throw new Error('persisted task output changed the signed media constraints')\n }\n const material = {\n kind: 'agent-candidate-task-outcome-material' as const,\n executionPlanDigest: state.executionPlan.value.digest,\n outcome: {\n kind: 'output' as const,\n spec: verified.spec,\n artifact: persisted.artifact,\n },\n } satisfies AgentCandidateTaskOutcomeMaterial\n const evidence = await persistTaskOutcomeEvidence(state, material, outputArtifacts, signal)\n const storedOutput = Uint8Array.from(verified.bytes)\n return Object.freeze({\n kind: 'output' as const,\n evidence,\n spec: immutableCandidateValue(verified.spec),\n get bytes(): Uint8Array {\n return Uint8Array.from(storedOutput)\n },\n [verifiedTaskOutcomeBrand]: true as const,\n })\n}\n\nasync function persistTaskOutcomeEvidence<Material extends AgentCandidateTaskOutcomeMaterial>(\n state: PreparedCandidateState,\n material: Material,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n signal?: AbortSignal,\n): Promise<\n Omit<AgentCandidateTaskOutcomeEvidence, 'material'> & {\n material: Material\n artifact: AgentCandidateArtifactRef\n }\n> {\n const bytes = canonicalCandidateBytes(material)\n const digest = sha256Bytes(bytes)\n const artifact = await persistCandidateOutputArtifact(outputArtifacts, {\n executionId: state.executionId,\n purpose: 'task-outcome',\n bytes,\n signal,\n })\n return immutableCandidateValue(\n agentCandidateTaskOutcomeEvidenceSchema.parse({\n kind: 'agent-candidate-task-outcome',\n digest,\n material,\n artifact,\n }),\n ) as Omit<AgentCandidateTaskOutcomeEvidence, 'material'> & {\n material: Material\n artifact: AgentCandidateArtifactRef\n }\n}\n\n/** Grade only a runtime-verified outcome and persist both raw and normalized evidence. */\nexport async function persistCandidateBenchmarkResult(\n state: PreparedCandidateState,\n termination: AgentCandidateTermination,\n outcome: VerifiedAgentCandidateTaskOutcome,\n grader: AgentCandidateBenchmarkGraderPort,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n protectedValues: readonly string[],\n signal?: AbortSignal,\n): Promise<PersistedAgentCandidateBenchmarkResult> {\n signal?.throwIfAborted()\n const frozenTermination = immutableCandidateValue(termination)\n const graded = await runBoundCandidateBenchmarkGrader({\n executionId: state.executionId,\n termination: frozenTermination,\n outcome,\n expectedGrader: state.benchmarkTask.grader,\n grader,\n artifacts: outputArtifacts,\n signal,\n })\n signal?.throwIfAborted()\n const evaluation = normalizeEvaluation(graded.evaluation, frozenTermination)\n const rawEvidence = Uint8Array.from(graded.evidence)\n if (rawEvidence.byteLength === 0) throw new Error('candidate benchmark evidence cannot be empty')\n assertNoProtectedBytes(rawEvidence, protectedValues)\n const evidenceRef = await persistCandidateOutputArtifact(outputArtifacts, {\n executionId: state.executionId,\n purpose: 'grader-evidence',\n bytes: rawEvidence,\n signal,\n })\n const material = {\n kind: 'agent-candidate-benchmark-result-material' as const,\n executionPlanDigest: state.executionPlan.value.digest,\n taskOutcomeDigest: outcome.evidence.digest,\n grader: graded.grader,\n evidence: evidenceRef,\n grading: graded.grading,\n score: evaluation.score,\n passed: evaluation.passed,\n dimensions: evaluation.dimensions,\n }\n const bytes = canonicalCandidateBytes(material)\n const digest = sha256Bytes(bytes)\n const artifact = await persistCandidateOutputArtifact(outputArtifacts, {\n executionId: state.executionId,\n purpose: 'benchmark-result',\n bytes,\n signal,\n })\n return immutableCandidateValue(\n agentCandidateBenchmarkResultEvidenceSchema.parse({\n kind: 'agent-candidate-benchmark-result',\n digest,\n material,\n artifact,\n }),\n ) as PersistedAgentCandidateBenchmarkResult\n}\n\nasync function verifyTaskOutcomeArchive(\n state: PreparedCandidateState,\n snapshot: AgentCandidateWorkspaceSnapshotEvidence,\n archive: Uint8Array,\n protectedValues: readonly string[],\n): Promise<void> {\n const root = await mkdtemp(join(tmpdir(), 'agent-candidate-task-archive-'))\n try {\n await state.ports.workspaces.materialize({\n role: 'task',\n snapshot,\n archive: Uint8Array.from(archive),\n destination: root,\n })\n const files = await readMaterializedWorkspaceFiles(root, snapshot.material)\n for (const file of files) assertNoProtectedBytes(file.bytes, protectedValues)\n } finally {\n await rm(root, { recursive: true, force: true })\n }\n}\n\nasync function verifyMemoryCapture(\n state: PreparedCandidateState,\n capture: SealedAgentCandidateExecutorFinalCapture,\n protectedValues: readonly string[],\n signal?: AbortSignal,\n): Promise<void> {\n if (state.memory.mode === 'disabled') {\n if (capture.memoryAfter) throw new Error('disabled memory cannot return an after-state')\n return\n }\n const memory = capture.memoryAfter\n if (!memory) throw new Error('isolated memory is missing its protected after-state')\n if (memory.archive.byteLength === 0) throw new Error('isolated memory archive cannot be empty')\n const manifestBytes = canonicalCandidateBytes(memory.afterState)\n assertNoProtectedBytes(manifestBytes, protectedValues)\n assertNoProtectedBytes(memory.archive, protectedValues)\n const snapshot = agentCandidateWorkspaceSnapshotEvidenceSchema.parse({\n kind: 'agent-candidate-workspace-snapshot',\n digest: sha256Bytes(manifestBytes),\n material: memory.afterState,\n manifest: embeddedCandidateArtifact(manifestBytes),\n archive: embeddedCandidateArtifact(memory.archive),\n })\n const root = await mkdtemp(join(tmpdir(), 'agent-candidate-memory-after-'))\n try {\n await state.ports.workspaces.materialize({\n role: 'memory',\n snapshot,\n archive: Uint8Array.from(memory.archive),\n destination: root,\n })\n const files = await readMaterializedWorkspaceFiles(root, memory.afterState)\n for (const file of files) assertNoProtectedBytes(file.bytes, protectedValues)\n signal?.throwIfAborted()\n } finally {\n await rm(root, { recursive: true, force: true })\n }\n}\n\nfunction normalizeEvaluation(\n evaluation: BenchmarkEvaluation,\n termination: AgentCandidateTermination,\n): { score: number; passed: boolean; dimensions: Array<{ name: string; score: number }> } {\n if (!evaluation || typeof evaluation !== 'object' || Array.isArray(evaluation)) {\n throw new Error('candidate benchmark evaluation must be an object')\n }\n assertUnitScore(evaluation.score, 'candidate benchmark score')\n if (evaluation.passed !== undefined && typeof evaluation.passed !== 'boolean') {\n throw new Error('candidate benchmark passed must be boolean')\n }\n const cleanExit = termination.kind === 'exit' && termination.exitCode === 0\n const dimensions = Object.entries(evaluation.dimensions ?? {})\n .map(([name, score]) => {\n if (!/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/.test(name)) {\n throw new Error(`candidate benchmark dimension is not normalized: ${name}`)\n }\n assertUnitScore(score, `candidate benchmark dimension ${name}`)\n return { name, score: cleanExit ? score : 0 }\n })\n .sort((left, right) => left.name.localeCompare(right.name))\n return {\n score: cleanExit ? evaluation.score : 0,\n passed: cleanExit && (evaluation.passed ?? evaluation.score > 0),\n dimensions,\n }\n}\n\nfunction assertUnitScore(value: unknown, label: string): asserts value is number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {\n throw new Error(`${label} must be finite and within [0, 1]`)\n }\n}\n","import type { TraceStore } from '@tangle-network/agent-eval'\n\nimport {\n createProtectedRecordRedactor,\n type ProtectedRedactionReport,\n type ProtectedTraceIdentity,\n} from './protected-redaction'\n\nexport interface ProtectedAgentCandidateTraceAccess {\n readonly store: TraceStore\n closeWrites(): Promise<void>\n identity(trace: ProtectedTraceIdentity): ProtectedTraceIdentity\n report(): ProtectedRedactionReport\n}\n\n/** Keep the identity key in evaluator-owned closures and expose only the redacting store to code. */\nexport function createProtectedAgentCandidateTraceAccess(\n inner: TraceStore,\n protectedValues: readonly string[],\n): ProtectedAgentCandidateTraceAccess {\n const redactor = createProtectedRecordRedactor(protectedValues)\n const pendingWrites = new Set<Promise<void>>()\n let acceptsWrites = true\n const write = (operation: () => Promise<void>): Promise<void> => {\n if (!acceptsWrites) {\n return Promise.reject(new Error('candidate trace writes are closed'))\n }\n let started: Promise<void>\n try {\n started = operation()\n } catch (error) {\n return Promise.reject(error)\n }\n let tracked: Promise<void>\n tracked = started.finally(() => pendingWrites.delete(tracked))\n pendingWrites.add(tracked)\n return tracked\n }\n const store = Object.freeze<TraceStore>({\n appendRun: (run) => write(() => inner.appendRun(redactor.record(run))),\n updateRun: (runId, patch) =>\n write(() => inner.updateRun(redactor.identifier(runId), redactor.record(patch))),\n appendSpan: (span) =>\n write(async () => {\n if (span.kind === 'llm') {\n throw new Error('candidate executors cannot author protected model spans')\n }\n await inner.appendSpan(redactor.record(span))\n }),\n updateSpan: (spanId, patch) =>\n write(async () => {\n if (patch.kind === 'llm') {\n throw new Error('candidate executors cannot author protected model spans')\n }\n await inner.updateSpan(redactor.identifier(spanId), redactor.record(patch))\n }),\n appendEvent: (event) => write(() => inner.appendEvent(redactor.record(event))),\n appendArtifact: (artifact) => write(() => inner.appendArtifact(redactor.record(artifact))),\n appendBudgetEntry: (entry) => write(() => inner.appendBudgetEntry(redactor.record(entry))),\n getRun: async (runId) => inner.getRun(redactor.identifier(runId)),\n listRuns: async (filter) => inner.listRuns(filter ? redactor.query(filter) : undefined),\n spans: async (filter) => inner.spans(filter ? redactor.query(filter) : undefined),\n events: async (filter) => inner.events(filter ? redactor.query(filter) : undefined),\n budget: async (runId) => inner.budget(redactor.identifier(runId)),\n artifacts: async (runId) => inner.artifacts(redactor.identifier(runId)),\n })\n return Object.freeze({\n store,\n closeWrites: async () => {\n acceptsWrites = false\n await Promise.all([...pendingWrites])\n },\n identity: (trace: ProtectedTraceIdentity) => redactor.traceIdentity(trace),\n report: () => redactor.report(),\n })\n}\n\n/** Recovery can read existing trace state but must never accept new unredactable writes. */\nexport class RecoveryAgentCandidateTraceStore implements TraceStore {\n constructor(private readonly inner: TraceStore) {}\n\n appendRun(): Promise<void> {\n return this.rejectWrite()\n }\n\n updateRun(): Promise<void> {\n return this.rejectWrite()\n }\n\n appendSpan(): Promise<void> {\n return this.rejectWrite()\n }\n\n updateSpan(): Promise<void> {\n return this.rejectWrite()\n }\n\n appendEvent(): Promise<void> {\n return this.rejectWrite()\n }\n\n appendArtifact(): Promise<void> {\n return this.rejectWrite()\n }\n\n appendBudgetEntry(): Promise<void> {\n return this.rejectWrite()\n }\n\n getRun(...args: Parameters<TraceStore['getRun']>): ReturnType<TraceStore['getRun']> {\n return this.inner.getRun(...args)\n }\n\n listRuns(...args: Parameters<TraceStore['listRuns']>): ReturnType<TraceStore['listRuns']> {\n return this.inner.listRuns(...args)\n }\n\n spans(...args: Parameters<TraceStore['spans']>): ReturnType<TraceStore['spans']> {\n return this.inner.spans(...args)\n }\n\n events(...args: Parameters<TraceStore['events']>): ReturnType<TraceStore['events']> {\n return this.inner.events(...args)\n }\n\n budget(...args: Parameters<TraceStore['budget']>): ReturnType<TraceStore['budget']> {\n return this.inner.budget(...args)\n }\n\n artifacts(...args: Parameters<TraceStore['artifacts']>): ReturnType<TraceStore['artifacts']> {\n return this.inner.artifacts(...args)\n }\n\n private rejectWrite(): Promise<never> {\n return Promise.reject(new Error('expired candidate recovery cannot append trace evidence'))\n }\n}\n","import type { TraceStore } from '@tangle-network/agent-eval'\nimport type {\n AgentCandidateTaskOutcomeSpec,\n AgentCandidateTermination,\n} from '@tangle-network/agent-interface'\n\nimport type {\n AgentCandidateExecutionClaim,\n AgentCandidateExecutionClaimStore,\n AgentCandidateExecutionFailureClass,\n AgentCandidateExecutionLease,\n AgentCandidateExecutionTerminalResult,\n} from './claim'\nimport { candidateExecutionClaim } from './claim-plan'\nimport {\n candidateCleanupDeadline,\n candidateCleanupTimeout,\n candidateResultTimeout,\n withinCandidateCleanupDeadline,\n withinCandidateResultDeadline,\n} from './cleanup'\nimport { canonicalCandidateBytes } from './digest'\nimport { candidatePostRunWindowMs, candidateTerminalWindowMs } from './execution-window'\nimport {\n type SealedAgentCandidateExecutorFinalCapture,\n sealAgentCandidateExecutorFinalCapture,\n sealAgentCandidateExecutorStopAcknowledgement,\n sealAgentCandidateProtectedRunCapture,\n} from './executor-capture'\nimport { failedAgentCandidateRun, finalizeAgentCandidateRun } from './finalize'\nimport {\n appendAuthoritativeModelSettlementSpans,\n type SealedAgentCandidateModelSettlement,\n sealAgentCandidateModelSettlement,\n} from './model-settlement'\nimport {\n type PersistedAgentCandidateModelSettlement,\n persistCandidateBenchmarkResult,\n persistCandidateModelSettlement,\n persistVerifiedAgentCandidateExecutorCapture,\n} from './outcome-evidence'\nimport { persistCandidateOutputArtifact } from './output-artifacts'\nimport {\n assertPreparedCandidateIntegrity,\n assertPreparedCandidateWorkspaces,\n beginPreparedCandidateClaim,\n beginPreparedCandidateRun,\n beginPreparedCandidateSettlement,\n consumePreparedCandidateExecution,\n markPreparedCandidateClaimed,\n type PreparedCandidateState,\n} from './prepared-state'\nimport { redactProtectedReason } from './protected-redaction'\nimport { createProtectedAgentCandidateTraceAccess } from './protected-trace-store'\nimport type {\n AgentCandidateBenchmarkGraderPort,\n AgentCandidateExecutorPort,\n AgentCandidateExecutorRequest,\n AgentCandidateOutputArtifactPort,\n AgentCandidateProtectedModelActivation,\n AgentCandidateProtectedRunCapture,\n AgentCandidateRunFinalization,\n PreparedAgentCandidateExecution,\n} from './types'\n\nexport interface ExecutePreparedAgentCandidateOptions {\n executor: AgentCandidateExecutorPort\n grader: AgentCandidateBenchmarkGraderPort\n outputArtifacts: AgentCandidateOutputArtifactPort\n traceStore: TraceStore\n /** Long-lived evaluator-owned store shared by every process that can run this benchmark. */\n claimStore: AgentCandidateExecutionClaimStore\n /** Maximum time to prove process death and revoke protected access after a run ends. */\n cleanupTimeoutMs?: number\n /** Maximum time for task verification, executable grading, and receipt construction. */\n resultTimeoutMs?: number\n}\n\n/** Executes and finalizes one durably claimed candidate without exposing an unproven result. */\nexport async function executePreparedAgentCandidate(\n prepared: PreparedAgentCandidateExecution,\n options: ExecutePreparedAgentCandidateOptions,\n): Promise<AgentCandidateRunFinalization> {\n const initialState = assertPreparedCandidateIntegrity(prepared)\n const cleanupTimeoutMs = candidateCleanupTimeout(\n options.cleanupTimeoutMs ?? initialState.cleanupTimeoutMs,\n )\n if (cleanupTimeoutMs > initialState.cleanupTimeoutMs) {\n throw new Error('execution cleanup timeout exceeds the frozen preparation bound')\n }\n const resultTimeoutMs = candidateResultTimeout(\n options.resultTimeoutMs ?? initialState.resultTimeoutMs,\n initialState.resultTimeoutMs,\n )\n if (resultTimeoutMs > initialState.resultTimeoutMs) {\n throw new Error('execution result timeout exceeds the frozen preparation bound')\n }\n let state: PreparedCandidateState\n try {\n state = beginPreparedCandidateClaim(prepared)\n } catch (error) {\n return failedAgentCandidateRun(initialState, errorMessage(error))\n }\n\n try {\n // Mutable staging is only a preparation check. The executor receives the\n // detached file bytes sealed in private state, never these host paths.\n await assertPreparedCandidateWorkspaces(state)\n } catch (error) {\n return await failBeforeActivation(prepared, state, error, 'failed', cleanupTimeoutMs)\n }\n\n let preparationEvidence: AgentCandidateExecutionClaim['preparationEvidence']\n try {\n const [executionPlan, materializationReceipt] = await Promise.all([\n persistCandidateOutputArtifact(options.outputArtifacts, {\n executionId: state.executionId,\n purpose: 'execution-plan',\n bytes: state.executionPlan.bytes,\n }),\n persistCandidateOutputArtifact(options.outputArtifacts, {\n executionId: state.executionId,\n purpose: 'materialization-receipt',\n bytes: state.materializationReceipt.bytes,\n }),\n ])\n preparationEvidence = Object.freeze({ executionPlan, materializationReceipt })\n } catch (error) {\n return await failBeforeActivation(prepared, state, error, 'failed', cleanupTimeoutMs)\n }\n\n let acquired: Awaited<ReturnType<AgentCandidateExecutionClaimStore['tryClaim']>>\n try {\n acquired = await options.claimStore.tryClaim(\n candidateExecutionClaim(prepared, preparationEvidence),\n )\n } catch (error) {\n return await failBeforeActivation(prepared, state, error, 'failed', cleanupTimeoutMs)\n }\n if (!acquired.acquired) {\n return await failBeforeActivation(\n prepared,\n state,\n new Error(\n acquired.reason === 'retry-not-eligible'\n ? `candidate execution retry is not eligible: ${acquired.detail}`\n : 'candidate execution attempt is already claimed',\n ),\n 'replayed',\n cleanupTimeoutMs,\n )\n }\n\n markPreparedCandidateClaimed(prepared)\n const postRunWindowMs = candidatePostRunWindowMs(cleanupTimeoutMs, resultTimeoutMs)\n // A caller may shorten cleanup for this invocation, but that must never buy\n // the candidate more execution time. The claim was frozen with the prepared\n // cleanup window, so recover the original task deadline from that value.\n const deadlineAtMs =\n acquired.claim.leaseExpiresAtMs -\n candidatePostRunWindowMs(state.cleanupTimeoutMs, state.resultTimeoutMs)\n const requiredLeaseExpiry = deadlineAtMs + postRunWindowMs\n if (\n Date.now() >= deadlineAtMs ||\n deadlineAtMs > state.reservationExpiresAtMs ||\n requiredLeaseExpiry > acquired.lease.expiresAtMs\n ) {\n return await failClaimedExecution(\n prepared,\n state,\n acquired.lease,\n options.claimStore,\n options.outputArtifacts,\n new Error('candidate claim no longer covers its full execution and cleanup window'),\n 'failed',\n cleanupTimeoutMs,\n 'pre-model-infrastructure',\n )\n }\n let activation: AgentCandidateProtectedModelActivation\n try {\n const activated = await withinCandidateCleanupDeadline(\n () =>\n state.ports.models.activateGrant({\n executionId: state.executionId,\n preparationId: state.preparationId,\n grantDigest: state.modelReservation.digest,\n resolved: state.resolvedModel,\n deadlineAtMs,\n }),\n Math.min(deadlineAtMs, candidateCleanupDeadline(cleanupTimeoutMs)),\n 'protected model activation',\n )\n activation = Object.freeze({ env: Object.freeze({ ...activated.env }) })\n } catch (error) {\n return await failClaimedExecution(\n prepared,\n state,\n acquired.lease,\n options.claimStore,\n options.outputArtifacts,\n new Error('protected model activation failed', { cause: error }),\n 'failed',\n cleanupTimeoutMs,\n 'pre-model-infrastructure',\n )\n }\n\n let memoryActivation: { env: Readonly<Record<string, string>> } | undefined\n if (state.memory.mode === 'isolated') {\n try {\n const reservation = state.memoryReservation\n if (!reservation) throw new Error('isolated memory reservation is missing')\n const activated = await withinCandidateCleanupDeadline(\n () =>\n state.ports.memory.activate({\n executionId: state.executionId,\n preparationId: reservation.preparationId,\n accessDigest: reservation.accessDigest,\n effectiveNamespace: reservation.effectiveNamespace,\n deadlineAtMs,\n }),\n Math.min(deadlineAtMs, candidateCleanupDeadline(cleanupTimeoutMs)),\n 'isolated memory activation',\n )\n memoryActivation = Object.freeze({ env: Object.freeze({ ...activated.env }) })\n } catch (error) {\n return await failClaimedExecution(\n prepared,\n state,\n acquired.lease,\n options.claimStore,\n options.outputArtifacts,\n new Error('isolated memory activation failed', { cause: error }),\n 'failed',\n cleanupTimeoutMs,\n 'pre-model-infrastructure',\n activation,\n )\n }\n }\n\n let request: AgentCandidateExecutorRequest\n try {\n request = beginPreparedCandidateRun(prepared, activation, memoryActivation).request\n } catch (error) {\n return await failClaimedExecution(\n prepared,\n state,\n acquired.lease,\n options.claimStore,\n options.outputArtifacts,\n error,\n 'failed',\n cleanupTimeoutMs,\n 'pre-model-infrastructure',\n activation,\n memoryActivation,\n )\n }\n\n try {\n const phase = await options.claimStore.markCandidateMayRun(acquired.lease)\n if (phase.phase !== 'candidate-may-run') {\n throw new Error('candidate claim did not persist the candidate-may-run phase')\n }\n } catch (error) {\n return await failClaimedExecution(\n prepared,\n state,\n acquired.lease,\n options.claimStore,\n options.outputArtifacts,\n new Error('candidate execution phase persistence failed', { cause: error }),\n 'failed',\n cleanupTimeoutMs,\n 'pre-model-infrastructure',\n activation,\n memoryActivation,\n )\n }\n if (Date.now() >= deadlineAtMs) {\n return await failClaimedExecution(\n prepared,\n state,\n acquired.lease,\n options.claimStore,\n options.outputArtifacts,\n new Error('candidate execution deadline elapsed while persisting its launch phase'),\n 'failed',\n cleanupTimeoutMs,\n 'unknown',\n activation,\n memoryActivation,\n )\n }\n\n const protectedValues = protectedEnvironmentValues(activation, memoryActivation)\n const protectedTrace = createProtectedAgentCandidateTraceAccess(\n options.traceStore,\n protectedValues,\n )\n const persistedTrace = protectedTrace.identity(state.trace)\n const execution = await runAndStopExecutor(\n options.executor,\n request,\n state.benchmarkTask.outcome,\n protectedTrace.store,\n deadlineAtMs,\n cleanupTimeoutMs,\n )\n beginPreparedCandidateSettlement(prepared)\n const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs)\n\n const accessReason =\n execution.kind === 'timeout' || execution.termination?.kind === 'timeout'\n ? 'timeout'\n : execution.kind === 'capture'\n ? 'completed'\n : 'failed'\n const traceClosure = withinCandidateCleanupDeadline(\n () => protectedTrace.closeWrites(),\n cleanupDeadlineAtMs,\n 'candidate trace write closure',\n ).then(\n () => ({ closed: true as const, error: undefined }),\n (error: unknown) => ({ closed: false as const, error }),\n )\n const [traceClose, memoryClose, settlementResult] = await Promise.all([\n traceClosure,\n closeMemoryAccess(state, accessReason, cleanupDeadlineAtMs),\n settleModelGrant(state, accessReason, cleanupDeadlineAtMs),\n ])\n if (\n !execution.processStopped ||\n !traceClose.closed ||\n !settlementResult.settlement ||\n !memoryClose.closed\n ) {\n consumePreparedCandidateExecution(prepared, 'failed')\n return failedAgentCandidateRun(\n state,\n redactProtectedReason(\n joinErrors(\n execution.error,\n !execution.processStopped\n ? new Error('candidate process termination is not proven')\n : undefined,\n traceClose.error,\n memoryClose.error,\n settlementResult.error ??\n (!settlementResult.settlement ? new Error('model settlement failed') : undefined),\n new Error('candidate claim remains recoverable until protected cleanup is proven'),\n ),\n protectedValues,\n ),\n execution.termination,\n settlementResult.settlement?.usage ?? null,\n )\n }\n\n let modelSettlement: PersistedAgentCandidateModelSettlement\n try {\n modelSettlement = await withinCandidateCleanupDeadline(\n () =>\n persistCandidateModelSettlement(\n state,\n settlementResult.settlement as SealedAgentCandidateModelSettlement,\n options.outputArtifacts,\n ),\n candidateCleanupDeadline(cleanupTimeoutMs),\n 'candidate model settlement persistence',\n )\n } catch (error) {\n consumePreparedCandidateExecution(prepared, 'failed')\n return failedAgentCandidateRun(\n state,\n redactProtectedReason(\n joinErrors(\n error,\n new Error('candidate claim remains recoverable until settlement evidence is durable'),\n ),\n protectedValues,\n ),\n execution.termination,\n settlementResult.settlement.usage,\n )\n }\n\n let result: AgentCandidateRunFinalization\n const failureClass: AgentCandidateExecutionFailureClass =\n execution.kind === 'error' ? 'execution' : 'post-model-infrastructure'\n if (execution.kind === 'error') {\n result = failedAgentCandidateRun(\n state,\n redactProtectedReason(errorMessage(execution.error), protectedValues),\n execution.termination,\n settlementResult.settlement.usage,\n )\n } else if (!execution.finalCapture.taskOutcome) {\n result = failedAgentCandidateRun(\n state,\n 'candidate executor stopped without a captured task outcome',\n execution.termination,\n settlementResult.settlement.usage,\n )\n } else {\n const capture =\n execution.kind === 'capture'\n ? execution.capture\n : {\n executionId: state.executionId,\n termination: execution.termination,\n }\n try {\n const resultDeadlineAtMs = Math.min(\n Date.now() + resultTimeoutMs,\n acquired.lease.expiresAtMs - candidateTerminalWindowMs(cleanupTimeoutMs),\n )\n result = await withinCandidateResultDeadline(\n async (signal) => {\n await appendAuthoritativeModelSettlementSpans(\n options.traceStore,\n persistedTrace.runId,\n settlementResult.settlement as SealedAgentCandidateModelSettlement,\n )\n const { persistedCapture, taskOutcome } =\n await persistVerifiedAgentCandidateExecutorCapture(\n state,\n execution.finalCapture,\n options.outputArtifacts,\n protectedValues,\n signal,\n )\n const benchmarkResult = await persistCandidateBenchmarkResult(\n state,\n capture.termination,\n taskOutcome,\n options.grader,\n options.outputArtifacts,\n protectedValues,\n signal,\n )\n return await finalizeAgentCandidateRun(\n state,\n capture,\n options.traceStore,\n persistedTrace,\n settlementResult.settlement as SealedAgentCandidateModelSettlement,\n {\n finalCapture: execution.finalCapture,\n persistedCapture,\n modelSettlement,\n taskOutcome,\n benchmarkResult,\n outputArtifacts: options.outputArtifacts,\n },\n protectedValues,\n protectedTrace.report(),\n signal,\n )\n },\n resultDeadlineAtMs,\n 'candidate evidence finalization',\n )\n } catch (error) {\n result = failedAgentCandidateRun(\n state,\n redactProtectedReason(errorMessage(error), protectedValues),\n execution.termination,\n settlementResult.settlement.usage,\n )\n }\n }\n\n let terminal: AgentCandidateExecutionTerminalResult\n try {\n terminal = result.succeeded\n ? {\n status: 'succeeded',\n usage: settlementResult.settlement.usage,\n modelSettlement: result.artifacts.modelSettlement,\n taskOutcome: result.artifacts.taskOutcome,\n benchmarkResult: result.artifacts.benchmarkResult,\n runReceipt: result.artifacts.runReceipt,\n }\n : {\n status: 'failed',\n failureClass,\n usage: settlementResult.settlement.usage,\n modelSettlement: modelSettlement.artifact,\n failureEvidence: await withinCandidateCleanupDeadline(\n () =>\n persistFailureEvidence(\n state,\n result.reason,\n failureClass,\n execution.termination,\n options.outputArtifacts,\n ),\n acquired.lease.expiresAtMs,\n 'candidate failure-evidence persistence',\n ),\n }\n } catch (error) {\n consumePreparedCandidateExecution(prepared, 'failed')\n return failedAgentCandidateRun(\n state,\n redactProtectedReason(\n joinErrors(\n error,\n new Error('candidate claim remains recoverable until terminal evidence is durable'),\n ),\n protectedValues,\n ),\n execution.termination,\n settlementResult.settlement.usage,\n )\n }\n\n const finished = await finishClaim(\n options.claimStore,\n acquired.lease,\n terminal,\n acquired.lease.expiresAtMs,\n )\n if (finished) {\n consumePreparedCandidateExecution(prepared, result.succeeded ? 'succeeded' : 'failed')\n return result\n }\n\n consumePreparedCandidateExecution(prepared, 'failed')\n return failedAgentCandidateRun(\n state,\n 'candidate execution terminal record could not be persisted',\n execution.termination,\n settlementResult.settlement.usage,\n )\n}\n\ntype ExecutorOutcome =\n | {\n kind: 'capture'\n capture: AgentCandidateProtectedRunCapture\n termination: AgentCandidateTermination\n finalCapture: SealedAgentCandidateExecutorFinalCapture\n processStopped: true\n error?: undefined\n }\n | {\n kind: 'timeout'\n termination: AgentCandidateTermination & { kind: 'timeout' }\n finalCapture: SealedAgentCandidateExecutorFinalCapture\n processStopped: true\n error?: undefined\n }\n | {\n kind: 'error'\n error: unknown\n termination?: AgentCandidateTermination\n finalCapture?: SealedAgentCandidateExecutorFinalCapture\n processStopped: boolean\n }\n\nasync function runAndStopExecutor(\n executor: AgentCandidateExecutorPort,\n request: AgentCandidateExecutorRequest,\n expectedOutcome: AgentCandidateTaskOutcomeSpec,\n traceStore: TraceStore,\n deadlineAtMs: number,\n cleanupTimeoutMs: number,\n): Promise<ExecutorOutcome> {\n const timeoutMs = request.hardLimits.timeoutMs\n const timeoutError = new CandidateExecutionDeadlineError(timeoutMs)\n if (Date.now() >= deadlineAtMs) {\n return {\n kind: 'error',\n error: timeoutError,\n termination: { kind: 'timeout', timeoutMs },\n processStopped: true,\n }\n }\n const controller = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n let timedOut = false\n let capture: AgentCandidateProtectedRunCapture | undefined\n let executionError: unknown\n const executionPromise = Promise.resolve().then(() =>\n executor.execute(request, {\n traceStore,\n signal: controller.signal,\n deadlineAtMs,\n }),\n )\n // A stopped process may still leave a buggy adapter promise pending. Attach a\n // terminal handler now so the deadline path cannot create an unhandled rejection.\n void executionPromise.catch(() => undefined)\n const deadlinePromise = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(\n () => {\n timedOut = true\n controller.abort(timeoutError)\n reject(timeoutError)\n },\n Math.max(0, deadlineAtMs - Date.now()),\n )\n })\n void deadlinePromise.catch(() => undefined)\n try {\n capture = sealAgentCandidateProtectedRunCapture(\n await Promise.race([executionPromise, deadlinePromise]),\n )\n } catch (error) {\n executionError = error\n }\n\n if (!timedOut && capture && capture.executionId !== request.executionId) {\n executionError = new Error('candidate execution capture id does not match the request')\n capture = undefined\n } else if (!timedOut && capture && Date.now() >= deadlineAtMs) {\n // Promise resolution at the boundary is ambiguous under event-loop delay.\n // Fail closed unless completion is observed strictly before the deadline.\n timedOut = true\n executionError = timeoutError\n capture = undefined\n } else if (!timedOut && capture?.termination.kind === 'timeout') {\n executionError = new Error('candidate executor cannot declare the runtime-owned timeout')\n capture = undefined\n }\n\n if (!capture || timedOut) controller.abort(executionError)\n const stopReason = timedOut ? 'timeout' : capture ? 'completed' : 'failed'\n const cleanupDeadlineAtMs = Date.now() + cleanupTimeoutMs\n try {\n const stopped = await withinCandidateCleanupDeadline(\n (cleanupSignal) =>\n executor.stop(\n {\n executionId: request.executionId,\n executionPlanDigest: request.executionPlan.value.digest,\n },\n {\n traceStore,\n reason: stopReason,\n signal: cleanupSignal,\n deadlineAtMs: cleanupDeadlineAtMs,\n },\n ),\n cleanupDeadlineAtMs,\n 'candidate process termination',\n )\n sealAgentCandidateExecutorStopAcknowledgement(stopped)\n } catch (stopError) {\n let disposalError: unknown\n try {\n await disposeExecutor(executor, request, cleanupDeadlineAtMs)\n } catch (error) {\n disposalError = error\n }\n if (timer) clearTimeout(timer)\n controller.abort(stopError)\n return {\n kind: 'error',\n error: new Error(joinErrors(executionError, stopError, disposalError)),\n ...(timedOut ? { termination: { kind: 'timeout', timeoutMs } } : {}),\n processStopped: false,\n }\n }\n\n let finalCapture: SealedAgentCandidateExecutorFinalCapture | undefined\n let finalCaptureError: unknown\n try {\n finalCapture = sealAgentCandidateExecutorFinalCapture(\n await withinCandidateCleanupDeadline(\n (cleanupSignal) =>\n executor.capture(\n {\n executionId: request.executionId,\n executionPlanDigest: request.executionPlan.value.digest,\n },\n {\n traceStore,\n signal: cleanupSignal,\n },\n ),\n cleanupDeadlineAtMs,\n 'candidate final evidence capture',\n ),\n expectedOutcome,\n )\n } catch (captureError) {\n finalCaptureError = captureError\n }\n\n let disposalError: unknown\n try {\n await disposeExecutor(executor, request, cleanupDeadlineAtMs)\n } catch (disposeError) {\n disposalError = disposeError\n }\n if (finalCaptureError || disposalError || !finalCapture) {\n if (timer) clearTimeout(timer)\n controller.abort(finalCaptureError ?? disposalError)\n return {\n kind: 'error',\n error: new Error(joinErrors(executionError, finalCaptureError, disposalError)),\n ...(timedOut ? { termination: { kind: 'timeout', timeoutMs } } : {}),\n processStopped: true,\n }\n }\n\n if (Date.now() >= deadlineAtMs) {\n timedOut = true\n executionError = timeoutError\n capture = undefined\n controller.abort(timeoutError)\n }\n if (timer) clearTimeout(timer)\n\n if (timedOut) {\n return {\n kind: 'timeout',\n termination: { kind: 'timeout', timeoutMs },\n finalCapture,\n processStopped: true,\n }\n }\n if (executionError || !capture) {\n return {\n kind: 'error',\n error: executionError ?? new Error('candidate executor returned no capture'),\n finalCapture,\n processStopped: true,\n }\n }\n return {\n kind: 'capture',\n capture,\n termination: capture.termination,\n finalCapture,\n processStopped: true,\n }\n}\n\nasync function disposeExecutor(\n executor: AgentCandidateExecutorPort,\n request: AgentCandidateExecutorRequest,\n cleanupDeadlineAtMs: number,\n): Promise<void> {\n const dispose = executor.dispose\n if (!dispose) return\n const disposed = await withinCandidateCleanupDeadline(\n (cleanupSignal) =>\n dispose.call(\n executor,\n {\n executionId: request.executionId,\n executionPlanDigest: request.executionPlan.value.digest,\n },\n { signal: cleanupSignal },\n ),\n cleanupDeadlineAtMs,\n 'candidate execution resource disposal',\n )\n if (disposed?.disposed !== true || Object.keys(disposed).some((key) => key !== 'disposed')) {\n throw new Error('candidate executor did not acknowledge resource disposal')\n }\n}\n\nasync function failBeforeActivation(\n prepared: PreparedAgentCandidateExecution,\n state: PreparedCandidateState,\n error: unknown,\n reason: 'failed' | 'replayed',\n cleanupTimeoutMs: number,\n): Promise<AgentCandidateRunFinalization> {\n beginPreparedCandidateSettlement(prepared)\n const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs)\n const [memoryClose, settled] = await Promise.all([\n closeMemoryAccess(state, reason, cleanupDeadlineAtMs),\n settleModelGrant(state, reason, cleanupDeadlineAtMs),\n ])\n const cleanupProven = memoryClose.closed && settled.settlement !== undefined\n consumePreparedCandidateExecution(prepared, cleanupProven ? 'failed' : 'cleanup-failed')\n return failedAgentCandidateRun(\n state,\n redactProtectedReason(\n joinErrors(\n error,\n memoryClose.error,\n settled.error,\n !cleanupProven\n ? new Error('prepared access cleanup remains incomplete and may be retried by disposal')\n : undefined,\n ),\n [],\n ),\n undefined,\n settled.settlement?.usage ?? null,\n )\n}\n\nasync function failClaimedExecution(\n prepared: PreparedAgentCandidateExecution,\n state: PreparedCandidateState,\n lease: AgentCandidateExecutionLease,\n claimStore: AgentCandidateExecutionClaimStore,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n error: unknown,\n reason: 'failed',\n cleanupTimeoutMs: number,\n failureClass: AgentCandidateExecutionFailureClass,\n activation?: AgentCandidateProtectedModelActivation,\n memoryActivation?: { env: Readonly<Record<string, string>> },\n): Promise<AgentCandidateRunFinalization> {\n beginPreparedCandidateSettlement(prepared)\n const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs)\n const [memoryClose, settled] = await Promise.all([\n closeMemoryAccess(state, reason, cleanupDeadlineAtMs),\n settleModelGrant(state, reason, cleanupDeadlineAtMs),\n ])\n const protectedValues = protectedEnvironmentValues(activation, memoryActivation)\n const safeReason = redactProtectedReason(\n joinErrors(error, memoryClose.error, settled.error),\n protectedValues,\n )\n let finishFailed = false\n let persistenceFailure: unknown\n if (settled.settlement && memoryClose.closed) {\n try {\n const modelSettlement = await withinCandidateCleanupDeadline(\n () => persistCandidateModelSettlement(state, settled.settlement!, outputArtifacts),\n lease.expiresAtMs,\n 'candidate pre-run model-settlement persistence',\n )\n const failureEvidence = await withinCandidateCleanupDeadline(\n () => persistFailureEvidence(state, safeReason, failureClass, undefined, outputArtifacts),\n lease.expiresAtMs,\n 'candidate pre-run failure-evidence persistence',\n )\n finishFailed = !(await finishClaim(\n claimStore,\n lease,\n {\n status: 'failed',\n failureClass,\n usage: settled.settlement.usage,\n modelSettlement: modelSettlement.artifact,\n failureEvidence,\n },\n lease.expiresAtMs,\n ))\n } catch (persistenceError) {\n finishFailed = true\n persistenceFailure = persistenceError\n }\n }\n consumePreparedCandidateExecution(prepared, 'failed')\n return failedAgentCandidateRun(\n state,\n redactProtectedReason(\n joinErrors(\n safeReason,\n persistenceFailure,\n memoryClose.error,\n settled.error,\n !memoryClose.closed || !settled.settlement\n ? new Error('candidate claim remains recoverable until protected cleanup is proven')\n : undefined,\n finishFailed\n ? new Error('candidate execution terminal record could not be persisted')\n : undefined,\n ),\n protectedValues,\n ),\n undefined,\n settled.settlement?.usage ?? null,\n )\n}\n\nasync function closeMemoryAccess(\n state: PreparedCandidateState,\n reason: 'completed' | 'failed' | 'timeout' | 'replayed',\n cleanupDeadlineAtMs: number,\n): Promise<{ closed: true; error?: undefined } | { closed: false; error: unknown }> {\n if (state.memory.mode === 'disabled') return { closed: true }\n try {\n const reservation = state.memoryReservation\n if (!reservation) throw new Error('isolated memory reservation is missing')\n const closed = await withinCandidateCleanupDeadline(\n () =>\n state.ports.memory.close({\n executionId: state.executionId,\n preparationId: reservation.preparationId,\n accessDigest: reservation.accessDigest,\n effectiveNamespace: reservation.effectiveNamespace,\n reason,\n }),\n cleanupDeadlineAtMs,\n 'isolated memory closure',\n )\n if (closed.closed !== true || Object.keys(closed).some((key) => key !== 'closed')) {\n throw new Error('isolated memory access did not acknowledge closure')\n }\n return { closed: true }\n } catch (error) {\n return { closed: false, error }\n }\n}\n\nasync function settleModelGrant(\n state: PreparedCandidateState,\n reason: 'completed' | 'failed' | 'timeout' | 'replayed',\n cleanupDeadlineAtMs: number,\n): Promise<{\n settlement?: SealedAgentCandidateModelSettlement\n error?: unknown\n}> {\n try {\n const value = await withinCandidateCleanupDeadline(\n () =>\n state.ports.models.settleGrant({\n executionId: state.executionId,\n preparationId: state.preparationId,\n grantDigest: state.modelReservation.digest,\n resolved: state.resolvedModel,\n reason,\n }),\n cleanupDeadlineAtMs,\n 'protected model settlement',\n )\n return {\n settlement: sealAgentCandidateModelSettlement(value, {\n preparationId: state.preparationId,\n grantDigest: state.modelReservation.digest,\n model: state.resolvedModel.model,\n }),\n }\n } catch (error) {\n return { error: new Error('protected model settlement failed', { cause: error }) }\n }\n}\n\nasync function finishClaim(\n store: AgentCandidateExecutionClaimStore,\n lease: AgentCandidateExecutionLease,\n terminal: AgentCandidateExecutionTerminalResult,\n deadlineAtMs?: number,\n): Promise<boolean> {\n try {\n const staged = await withinCandidateCleanupDeadline(\n () => store.stageTerminal(lease, terminal),\n deadlineAtMs ?? lease.expiresAtMs,\n 'candidate terminal staging',\n )\n if (!staged.staged && !staged.exactReplay) return false\n const result = await withinCandidateCleanupDeadline(\n () => store.finish(lease, staged.terminal.terminalDigest),\n deadlineAtMs ?? lease.expiresAtMs,\n 'candidate terminal publication',\n )\n return result.finished || result.exactReplay\n } catch {\n return false\n }\n}\n\nasync function persistFailureEvidence(\n state: PreparedCandidateState,\n reason: string,\n failureClass: AgentCandidateExecutionFailureClass,\n termination: AgentCandidateTermination | undefined,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n) {\n const bytes = canonicalCandidateBytes({\n kind: 'agent-candidate-execution-failure',\n executionId: state.executionId,\n bundleDigest: state.bundle.digest,\n executionPlanDigest: state.executionPlan.value.digest,\n failureClass,\n reason,\n ...(termination ? { termination } : {}),\n })\n return await persistCandidateOutputArtifact(outputArtifacts, {\n executionId: state.executionId,\n purpose: 'failure-evidence',\n bytes,\n })\n}\n\nfunction protectedEnvironmentValues(\n activation?: AgentCandidateProtectedModelActivation,\n memoryActivation?: { env: Readonly<Record<string, string>> },\n): string[] {\n return [...Object.values(activation?.env ?? {}), ...Object.values(memoryActivation?.env ?? {})]\n}\n\nfunction joinErrors(...errors: unknown[]): string {\n return errors\n .filter((error) => error !== undefined)\n .map(errorMessage)\n .join('; ')\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nclass CandidateExecutionDeadlineError extends Error {\n constructor(timeoutMs: number) {\n super(`candidate execution reached its frozen ${timeoutMs}ms deadline`)\n this.name = 'CandidateExecutionDeadlineError'\n }\n}\n","import type {\n AgentCandidateBundle,\n AgentCandidateCapturedArtifact,\n AgentCandidateResourceRef,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { agentCandidateBundleSchema } from '@tangle-network/agent-interface'\n\nimport {\n artifactCacheKey,\n readVerifiedArtifact,\n verifyBytes,\n verifyWorkspaceSnapshotArtifacts,\n} from './artifacts'\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDigest,\n deepFreezeCandidate,\n omitTopLevelDigest,\n} from './digest'\nimport { readCandidateGitHubResource, verifyCandidateCode } from './git-materialize'\nimport { assertCandidateProfileExecutionSupport } from './profile'\nimport {\n type AgentCandidateVerificationPorts,\n type VerifiedAgentCandidate,\n verifiedCandidateBrand,\n} from './types'\n\ninterface VerifiedCandidateState {\n ports: AgentCandidateVerificationPorts\n artifactBytes: Map<string, Uint8Array>\n resourceBytes: Map<string, Uint8Array>\n}\n\nconst verifiedCandidateState = new WeakMap<VerifiedAgentCandidate, VerifiedCandidateState>()\n\n/** Surfaces admitted by Runtime's verifier before an environment adapter is selected. */\nexport const AGENT_CANDIDATE_EXECUTION_SUPPORT = Object.freeze({\n outcomes: Object.freeze(['workspace', 'output'] as const),\n code: Object.freeze(['disabled', 'no-op', 'git-patch'] as const),\n memory: Object.freeze(['disabled', 'isolated'] as const),\n knowledge: true,\n profile: Object.freeze({\n mcpTransports: Object.freeze(['stdio'] as const),\n remoteMcp: false,\n tools: false,\n permissions: false,\n modes: false,\n confidential: false,\n }),\n})\n\n/** Verifies every digest, resource, workspace, and Git object in a candidate bundle. */\nexport async function verifyAgentCandidateBundle(\n input: unknown,\n ports: AgentCandidateVerificationPorts,\n): Promise<VerifiedAgentCandidate> {\n const parsed = agentCandidateBundleSchema.parse(input)\n const withoutDigest = omitTopLevelDigest(parsed)\n const actualDigest = canonicalCandidateDigest(withoutDigest)\n if (actualDigest !== parsed.digest) {\n throw new Error(`candidate bundle digest ${parsed.digest} does not match ${actualDigest}`)\n }\n const canonicalBytes = canonicalCandidateBytes(withoutDigest)\n verifyBytes(canonicalBytes, parsed.digest, canonicalBytes.byteLength, 'candidate bundle')\n assertCandidateProfileExecutionSupport(parsed.profile)\n\n const artifactBytes = new Map<string, Uint8Array>()\n const readArtifact = async (artifact: AgentCandidateCapturedArtifact): Promise<Uint8Array> => {\n const key = artifactCacheKey(artifact)\n const existing = artifactBytes.get(key)\n if (existing) return Uint8Array.from(existing)\n const bytes = await readVerifiedArtifact(artifact, ports.artifacts)\n artifactBytes.set(key, Uint8Array.from(bytes))\n return bytes\n }\n\n let patchBytes: Uint8Array | undefined\n if (parsed.code.kind === 'git-patch') {\n patchBytes = await readArtifact(parsed.code.patch.artifact)\n }\n const materializedTree = await verifyCandidateCode(parsed.code, ports.repositories, patchBytes)\n\n const resourceBytes = new Map<string, Uint8Array>()\n for (const resource of candidateResources(parsed)) {\n const bytes =\n resource.kind === 'inline'\n ? Buffer.from(resource.content, 'utf8')\n : await readCandidateGitHubResource(resource, ports.repositories)\n verifyBytes(\n bytes,\n resource.sha256,\n resource.byteLength,\n `candidate resource ${resource.name ?? (resource.kind === 'github' ? resource.path : '<unnamed>')}`,\n )\n resourceBytes.set(resourceKey(resource), Uint8Array.from(bytes))\n resourceBytes.set(resource.sha256, Uint8Array.from(bytes))\n }\n\n if (parsed.execution.workspace) {\n const workspace = await verifyWorkspaceSnapshotArtifacts(\n parsed.execution.workspace,\n ports.artifacts,\n )\n artifactBytes.set(artifactCacheKey(parsed.execution.workspace.manifest), workspace.manifest)\n artifactBytes.set(artifactCacheKey(parsed.execution.workspace.archive), workspace.archive)\n }\n if (parsed.knowledge) {\n const knowledge = await verifyWorkspaceSnapshotArtifacts(\n parsed.knowledge.snapshot,\n ports.artifacts,\n )\n artifactBytes.set(artifactCacheKey(parsed.knowledge.snapshot.manifest), knowledge.manifest)\n artifactBytes.set(artifactCacheKey(parsed.knowledge.snapshot.archive), knowledge.archive)\n if (parsed.knowledge.retrievalConfig) await readArtifact(parsed.knowledge.retrievalConfig)\n await readArtifact(parsed.knowledge.evaluation)\n }\n if (parsed.memory.mode === 'isolated' && parsed.memory.seed)\n await readArtifact(parsed.memory.seed)\n\n deepFreezeCandidate(parsed)\n const verified = Object.freeze({\n bundle: parsed,\n ...(materializedTree === undefined ? {} : { materializedTree }),\n [verifiedCandidateBrand]: true as const,\n })\n verifiedCandidateState.set(verified, { ports, artifactBytes, resourceBytes })\n return verified\n}\n\nexport function getVerifiedCandidateState(\n candidate: VerifiedAgentCandidate,\n): VerifiedCandidateState {\n const state = verifiedCandidateState.get(candidate)\n if (!state || candidate[verifiedCandidateBrand] !== true) {\n throw new Error('candidate must come from verifyAgentCandidateBundle')\n }\n return state\n}\n\nexport async function verifiedArtifactBytes(\n candidate: VerifiedAgentCandidate,\n artifact: AgentCandidateCapturedArtifact,\n): Promise<Uint8Array> {\n const state = getVerifiedCandidateState(candidate)\n const key = artifactCacheKey(artifact)\n const existing = state.artifactBytes.get(key)\n if (existing) return Uint8Array.from(existing)\n const bytes = await readVerifiedArtifact(artifact, state.ports.artifacts)\n state.artifactBytes.set(key, Uint8Array.from(bytes))\n return bytes\n}\n\nexport function verifiedResourceBytes(\n candidate: VerifiedAgentCandidate,\n resource: AgentCandidateResourceRef,\n): Uint8Array {\n const bytes = getVerifiedCandidateState(candidate).resourceBytes.get(resourceKey(resource))\n if (!bytes) {\n throw new Error(\n `candidate resource was not verified: ${resource.name ?? (resource.kind === 'github' ? resource.path : '<unnamed>')}`,\n )\n }\n return Uint8Array.from(bytes)\n}\n\nexport function verifiedResourceTextByDigest(\n candidate: VerifiedAgentCandidate,\n): ReadonlyMap<Sha256Digest, string> {\n const output = new Map<Sha256Digest, string>()\n for (const resource of candidateResources(candidate.bundle)) {\n const bytes = getVerifiedCandidateState(candidate).resourceBytes.get(resource.sha256)\n if (!bytes) throw new Error(`candidate resource digest was not verified: ${resource.sha256}`)\n output.set(resource.sha256, new TextDecoder('utf-8', { fatal: true }).decode(bytes))\n }\n return output\n}\n\nfunction candidateResources(bundle: AgentCandidateBundle): AgentCandidateResourceRef[] {\n const resources = bundle.profile.resources\n if (!resources) return []\n const output: AgentCandidateResourceRef[] = []\n for (const mount of resources.files ?? []) output.push(mount.resource)\n output.push(...(resources.tools ?? []))\n output.push(...(resources.skills ?? []))\n output.push(...(resources.agents ?? []))\n output.push(...(resources.commands ?? []))\n if (typeof resources.instructions === 'object') output.push(resources.instructions)\n return output\n}\n\nfunction resourceKey(resource: AgentCandidateResourceRef): string {\n return canonicalCandidateDigest(resource)\n}\n","import { mkdtemp, rm } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join, posix } from 'node:path'\n\nimport type { AgentCandidateRunCell } from '@tangle-network/agent-interface'\nimport { hashKnowledgeBase } from '@tangle-network/agent-knowledge'\n\nimport { readMaterializedWorkspaceFiles } from './artifacts'\nimport type {\n AgentCandidateExecutionPorts,\n PreparedAgentCandidateKnowledge,\n VerifiedAgentCandidate,\n} from './types'\nimport { verifiedArtifactBytes } from './verify'\n\n/** Environment variable containing the materialized candidate knowledge root. */\nexport const CANDIDATE_KNOWLEDGE_ROOT_ENV = 'TANGLE_CANDIDATE_KNOWLEDGE_ROOT'\n/** Environment variable containing the materialized retrieval configuration path. */\nexport const CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV =\n 'TANGLE_CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG'\n\n/** Deterministic, signed locations used by every candidate executor. */\nexport function candidateKnowledgeExecutionPaths(\n taskRoot: string,\n hasRetrievalConfig: boolean,\n): { root: string; retrievalConfig?: string } {\n if (!posix.isAbsolute(taskRoot) || posix.normalize(taskRoot) !== taskRoot) {\n throw new Error('candidate knowledge requires a normalized absolute task root')\n }\n const parent = posix.join(taskRoot, '.tangle')\n return {\n root: posix.join(parent, 'knowledge'),\n ...(hasRetrievalConfig\n ? { retrievalConfig: posix.join(parent, 'knowledge-retrieval-config.json') }\n : {}),\n }\n}\n\n/** Verify and detach the exact file-backed knowledge admitted by the bundle. */\nexport async function prepareAgentCandidateKnowledge(\n candidate: VerifiedAgentCandidate,\n ports: AgentCandidateExecutionPorts,\n arm: AgentCandidateRunCell['arm'],\n): Promise<PreparedAgentCandidateKnowledge | undefined> {\n const knowledge = candidate.bundle.knowledge\n if (!knowledge) return undefined\n\n const archive = await verifiedArtifactBytes(candidate, knowledge.snapshot.archive)\n const retrievalConfig = knowledge.retrievalConfig\n ? await verifiedArtifactBytes(candidate, knowledge.retrievalConfig)\n : undefined\n const root = await mkdtemp(join(tmpdir(), 'agent-candidate-knowledge-'))\n try {\n await ports.workspaces.materialize({\n role: 'knowledge',\n snapshot: knowledge.snapshot,\n archive,\n destination: root,\n })\n const expectedHash =\n arm === 'baseline' ? knowledge.candidate.baseHash : knowledge.candidate.candidateHash\n const actualHash = `sha256:${await hashKnowledgeBase(root, knowledge.stateScope)}`\n if (actualHash !== expectedHash) {\n throw new Error(\n `materialized ${arm} knowledge does not match its measured content: expected ${expectedHash}, got ${actualHash}`,\n )\n }\n const files = await readMaterializedWorkspaceFiles(root, knowledge.snapshot.material)\n return Object.freeze({\n candidate: knowledge.candidate,\n ...(knowledge.stateScope ? { stateScope: Object.freeze({ ...knowledge.stateScope }) } : {}),\n snapshot: knowledge.snapshot,\n files: Object.freeze(\n files.map((file) =>\n Object.freeze({ path: file.path, mode: file.mode, bytes: Uint8Array.from(file.bytes) }),\n ),\n ),\n ...(retrievalConfig ? { retrievalConfig: Uint8Array.from(retrievalConfig) } : {}),\n })\n } finally {\n await rm(root, { recursive: true, force: true })\n }\n}\n","import { randomBytes } from 'node:crypto'\nimport { lstat, mkdtemp, readdir, rm } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { isAbsolute, join, posix, relative, resolve as resolveHostPath } from 'node:path'\nimport type {\n AgentCandidateConfigValue,\n AgentCandidateEffectiveMemory,\n AgentCandidateExecutionLimits,\n AgentCandidateExecutionPlanEvidence,\n AgentCandidateExecutionPlanMaterial,\n AgentCandidateMaterializationReceipt,\n AgentCandidateModelAccessNetwork,\n AgentCandidateResolvedModel,\n} from '@tangle-network/agent-interface'\nimport {\n agentCandidateBenchmarkSuiteSchema,\n agentCandidateBenchmarkTaskSchema,\n agentCandidateContainerSchema,\n agentCandidateExecutionLimitsSchema,\n agentCandidateExecutionPlanEvidenceSchema,\n agentCandidateExecutionPlanMaterialSchema,\n agentCandidateMaterializationReceiptSchema,\n agentCandidateModelAccessNetworkSchema,\n agentCandidateRunCellSchema,\n agentCandidateTaskOutcomeSpecSchema,\n agentCandidateWorkspaceSnapshotEvidenceSchema,\n sha256DigestSchema,\n} from '@tangle-network/agent-interface'\nimport { applyAgentCandidateWorkspacePlan } from '@tangle-network/agent-profile-materialize'\nimport {\n readMaterializedWorkspaceFiles,\n readVerifiedArtifact,\n verifyMaterializedProfileWorkspace,\n verifyMaterializedWorkspace,\n verifyWorkspaceSnapshotArtifacts,\n} from './artifacts'\nimport {\n candidateCleanupDeadline,\n candidateCleanupTimeout,\n candidateResultTimeout,\n MAX_CANDIDATE_TIMER_INTERVAL_MS,\n withinCandidateCleanupDeadline,\n} from './cleanup'\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n embeddedCandidateArtifact,\n omitTopLevelDigest,\n sha256Bytes,\n} from './digest'\nimport { isWellFormedUnicode } from './exact-object'\nimport { assertAgentCandidateExecutionRoots, executionPathsOverlap } from './execution-roots'\nimport { candidateExecutionOwnerWindowMs } from './execution-window'\nimport { verifyTaskCheckout } from './git-materialize'\nimport {\n CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV,\n CANDIDATE_KNOWLEDGE_ROOT_ENV,\n candidateKnowledgeExecutionPaths,\n prepareAgentCandidateKnowledge,\n} from './knowledge'\nimport { sealAgentCandidateModelSettlement, usdToNanos } from './model-settlement'\nimport { createPreparedCandidateExecution } from './prepared-state'\nimport {\n candidateProfileAgentPaths,\n materializeAgentCandidateProfilePlan,\n PI_CANDIDATE_AGENT_DIR_ENV,\n PI_CANDIDATE_SESSION_DIR_ENV,\n} from './profile'\nimport {\n type AgentCandidateExecutionPorts,\n type AgentCandidateTaskExecution,\n CANDIDATE_TRACE_ENV,\n CANDIDATE_TRACE_TAGS,\n type PreparedAgentCandidateExecution,\n type ResolvedAgentCandidateContainer,\n type VerifiedAgentCandidate,\n} from './types'\nimport {\n getVerifiedCandidateState,\n verifiedArtifactBytes,\n verifiedResourceTextByDigest,\n} from './verify'\n\nconst MIN_RESERVATION_TTL_MS = 15 * 60_000\nconst PREPARED_HOLD_MARGIN_MS = 5 * 60_000\n\nexport interface PrepareAgentCandidateExecutionOptions {\n cleanupTimeoutMs?: number\n /** Maximum time for task verification, executable grading, and receipt construction. */\n resultTimeoutMs?: number\n}\n\n/** Materializes a verified candidate into one immutable evaluator-owned execution plan. */\nexport async function prepareAgentCandidateExecution(\n candidate: VerifiedAgentCandidate,\n task: AgentCandidateTaskExecution,\n ports: AgentCandidateExecutionPorts,\n options: PrepareAgentCandidateExecutionOptions = {},\n): Promise<PreparedAgentCandidateExecution> {\n const cleanupTimeoutMs = candidateCleanupTimeout(options.cleanupTimeoutMs)\n const verifiedState = getVerifiedCandidateState(candidate)\n assertSameVerificationPorts(verifiedState.ports, ports)\n const bundle = candidate.bundle\n if (task.runCell.bundleDigest !== bundle.digest) {\n throw new Error('candidate experiment cell does not bind the verified bundle')\n }\n const benchmarkTask = task.task\n const attempt = {\n number: task.runCell.attempt,\n maxAttempts: benchmarkTask.attempt.maxAttempts,\n retryPolicy: benchmarkTask.attempt.retryPolicy,\n } as const\n assertTaskInput(task, bundle.execution.instructionDelivery)\n const resultTimeoutMs = candidateResultTimeout(\n options.resultTimeoutMs,\n benchmarkTask.limits.timeoutMs,\n )\n const ownerWindowMs = candidateExecutionOwnerWindowMs(\n benchmarkTask.limits.timeoutMs,\n cleanupTimeoutMs,\n resultTimeoutMs,\n )\n const reservationWindowMs = ownerWindowMs + PREPARED_HOLD_MARGIN_MS\n if (reservationWindowMs > MAX_CANDIDATE_TIMER_INTERVAL_MS) {\n throw new Error('candidate reservation window exceeds the supported timer range')\n }\n assertDisjointHostStagingRoots(task)\n\n const instructionBytes = Buffer.from(benchmarkTask.instruction, 'utf8')\n\n const taskArtifacts = await verifyWorkspaceSnapshotArtifacts(\n benchmarkTask.workspace,\n ports.artifacts,\n )\n await ports.workspaces.materialize({\n role: 'task',\n snapshot: benchmarkTask.workspace,\n archive: taskArtifacts.archive,\n destination: task.stagingRoots.taskRoot,\n })\n await verifyMaterializedWorkspace(task.stagingRoots.taskRoot, benchmarkTask.workspace.material, {\n ignoredProtectedRootEntries: ['.git', '.sidecar'],\n })\n if (benchmarkTask.repository) {\n await verifyTaskCheckout(task.stagingRoots.taskRoot, benchmarkTask.repository)\n }\n const taskExecutorFiles = await readMaterializedWorkspaceFiles(\n task.stagingRoots.taskRoot,\n benchmarkTask.workspace.material,\n { ignoredProtectedRootEntries: ['.git', '.sidecar'] },\n )\n\n let candidateArchive: Uint8Array | undefined\n let candidateExecutorFiles:\n | ReadonlyArray<{ path: string; mode: number; bytes: Uint8Array }>\n | undefined\n if (bundle.execution.workspace) {\n if (!task.stagingRoots.candidateRoot || !task.executionRoots.candidateRoot) {\n throw new Error('active candidate execution requires host and container candidate roots')\n }\n candidateArchive = await verifiedArtifactBytes(candidate, bundle.execution.workspace.archive)\n await ports.workspaces.materialize({\n role: 'candidate',\n snapshot: bundle.execution.workspace,\n archive: candidateArchive,\n destination: task.stagingRoots.candidateRoot,\n })\n await verifyMaterializedWorkspace(\n task.stagingRoots.candidateRoot,\n bundle.execution.workspace.material,\n )\n candidateExecutorFiles = await readMaterializedWorkspaceFiles(\n task.stagingRoots.candidateRoot,\n bundle.execution.workspace.material,\n )\n } else if (task.stagingRoots.candidateRoot || task.executionRoots.candidateRoot) {\n throw new Error('disabled code cannot receive a candidate workspace root')\n }\n\n await assertEmptyDirectory(task.stagingRoots.profileRoot)\n const profileWorkspacePlan = materializeAgentCandidateProfilePlan({\n profile: bundle.profile,\n harness: bundle.execution.harness,\n launch: bundle.execution.launch,\n workspace: bundle.execution.cwd.workspace,\n workspaces: {\n taskRoot: task.executionRoots.taskRoot,\n ...(task.executionRoots.candidateRoot\n ? { candidateRoot: task.executionRoots.candidateRoot }\n : {}),\n },\n resolvedResources: verifiedResourceTextByDigest(candidate),\n })\n const profileAgentPaths = candidateProfileAgentPaths(\n profileWorkspacePlan,\n task.executionRoots.profileRoot,\n )\n const profileAgentStagingRoot = profileWorkspacePlan.files.some((file) => file.root === 'agent')\n ? await mkdtemp(join(tmpdir(), 'tangle-candidate-profile-agent-'))\n : undefined\n let profileApplication: ReturnType<typeof applyAgentCandidateWorkspacePlan>\n try {\n profileApplication = applyAgentCandidateWorkspacePlan(\n profileWorkspacePlan,\n task.stagingRoots.profileRoot,\n bundle.execution.cwd.workspace,\n profileAgentStagingRoot ? { agentDir: profileAgentStagingRoot } : undefined,\n )\n await verifyMaterializedProfileWorkspace(\n task.stagingRoots.profileRoot,\n profileApplication.profileActivation.profilePlan.material,\n )\n if (profileAgentStagingRoot) {\n await verifyMaterializedProfileWorkspace(\n profileAgentStagingRoot,\n profileApplication.profileActivation.profilePlan.material,\n 'agent',\n )\n }\n } finally {\n if (profileAgentStagingRoot) {\n await rm(profileAgentStagingRoot, { recursive: true, force: true })\n }\n }\n const profilePlanBytes = await readVerifiedArtifact(\n profileApplication.profileActivation.profilePlan.artifact,\n ports.artifacts,\n )\n if (\n !Buffer.from(profilePlanBytes).equals(\n Buffer.from(\n canonicalCandidateBytes(profileApplication.profileActivation.profilePlan.material),\n ),\n )\n ) {\n throw new Error('profile materializer did not capture exact canonical plan bytes')\n }\n const profileActivation = profileApplication.profileActivation\n\n const container = await resolveContainer(candidate, task, ports)\n const resolvedModel = await resolveModel(candidate, task, ports)\n const preparationId = `candidate-preparation.${randomBytes(32).toString('base64url')}`\n const reservationExpiresAtMs = Date.now() + Math.max(MIN_RESERVATION_TTL_MS, reservationWindowMs)\n const modelReservation = await withinCandidateCleanupDeadline(\n () =>\n ports.models.reserveGrant({\n executionId: task.executionId,\n preparationId,\n expiresAtMs: reservationExpiresAtMs,\n attempt,\n bundleDigest: bundle.digest,\n resolved: resolvedModel,\n limits: modelLimits(benchmarkTask.limits),\n }),\n candidateCleanupDeadline(cleanupTimeoutMs),\n 'protected model reservation',\n )\n let preparedMemory: Awaited<ReturnType<typeof prepareMemory>> | undefined\n try {\n validateProtectedModelReservation(\n modelReservation,\n benchmarkTask.limits,\n preparationId,\n reservationExpiresAtMs,\n )\n preparedMemory = await prepareMemory(\n candidate,\n task,\n ports,\n preparationId,\n reservationExpiresAtMs,\n cleanupTimeoutMs,\n )\n const memory = preparedMemory.value\n const knowledge = await prepareAgentCandidateKnowledge(candidate, ports, task.runCell.arm)\n const knowledgePaths = knowledge\n ? candidateKnowledgeExecutionPaths(\n task.executionRoots.taskRoot,\n knowledge.retrievalConfig !== undefined,\n )\n : undefined\n const baseLaunch = buildLaunch(candidate, task, profileApplication.flags)\n const publicEnv = mergePublicEnvironment(\n bundle.execution.env ?? {},\n profileApplication.env,\n profileAgentPaths\n ? {\n [PI_CANDIDATE_AGENT_DIR_ENV]: {\n kind: 'public' as const,\n value: profileAgentPaths.agentDir,\n },\n [PI_CANDIDATE_SESSION_DIR_ENV]: {\n kind: 'public' as const,\n value: profileAgentPaths.sessionDir,\n },\n }\n : {},\n bundle.execution.instructionDelivery.kind === 'utf8-file'\n ? {\n [bundle.execution.instructionDelivery.env]: {\n kind: 'public',\n value: bundle.execution.instructionDelivery.path,\n },\n }\n : {},\n knowledgePaths\n ? {\n [CANDIDATE_KNOWLEDGE_ROOT_ENV]: {\n kind: 'public',\n value: knowledgePaths.root,\n },\n ...(knowledgePaths.retrievalConfig\n ? {\n [CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV]: {\n kind: 'public' as const,\n value: knowledgePaths.retrievalConfig,\n },\n }\n : {}),\n }\n : {},\n )\n const routes = modelRoutes(bundle.profile, benchmarkTask.model.requested)\n const executionMaterial: AgentCandidateExecutionPlanMaterial = {\n kind: 'agent-candidate-execution-plan-material',\n runCell: task.runCell,\n executionId: task.executionId,\n workspaces: {\n taskRoot: task.executionRoots.taskRoot,\n ...(task.executionRoots.candidateRoot\n ? { candidateRoot: task.executionRoots.candidateRoot }\n : {}),\n },\n codeKind: bundle.code.kind,\n ...(bundle.execution.workspace ? { candidateWorkspace: bundle.execution.workspace } : {}),\n profile: profileApplication.application,\n harness: bundle.execution.harness,\n harnessVersion: bundle.execution.harnessVersion,\n instructionDelivery: bundle.execution.instructionDelivery,\n limits: benchmarkTask.limits,\n container,\n model: {\n policy: 'single',\n resolved: resolvedModel,\n access: {\n kind: 'evaluator-mediated',\n grantDigest: modelReservation.digest,\n network: modelReservation.network,\n },\n routes,\n },\n launch: {\n executable: baseLaunch.executable,\n args: baseLaunch.args,\n env: publicEnv,\n cwd: bundle.execution.cwd,\n },\n ...(bundle.knowledge ? { knowledgeManifestDigest: bundle.knowledge.snapshot.digest } : {}),\n memory,\n network: { mode: 'disabled' },\n }\n agentCandidateExecutionPlanMaterialSchema.parse(executionMaterial)\n const executionBytes = canonicalCandidateBytes(executionMaterial)\n const executionDigest = canonicalCandidateDigest(executionMaterial)\n if (sha256Bytes(executionBytes) !== executionDigest) {\n throw new Error('execution plan canonical serializers disagree')\n }\n const executionPlan: AgentCandidateExecutionPlanEvidence =\n agentCandidateExecutionPlanEvidenceSchema.parse({\n kind: 'agent-candidate-execution-plan',\n digest: executionDigest,\n material: executionMaterial,\n artifact: embeddedCandidateArtifact(executionBytes),\n })\n\n const entrypoint = candidateEntrypointReceipt(candidate)\n const materializationReceipt = canonicalCandidateDocument<AgentCandidateMaterializationReceipt>(\n {\n kind: 'agent-candidate-materialization',\n digestAlgorithm: 'rfc8785-sha256',\n bundleDigest: bundle.digest,\n benchmark: {\n suite: {\n digest: task.benchmarkSuite.digest,\n material: embeddedCandidateArtifact(\n canonicalCandidateBytes(omitTopLevelDigest(task.benchmarkSuite)),\n ),\n },\n task: {\n digest: benchmarkTask.digest,\n material: embeddedCandidateArtifact(\n canonicalCandidateBytes(omitTopLevelDigest(benchmarkTask)),\n ),\n },\n },\n profileActivation,\n executionPlan,\n ...(bundle.execution.workspace ? { candidateWorkspace: bundle.execution.workspace } : {}),\n codeKind: bundle.code.kind,\n ...(candidate.materializedTree ? { materializedTree: candidate.materializedTree } : {}),\n harness: bundle.execution.harness,\n harnessVersion: bundle.execution.harnessVersion,\n container,\n resolvedModel,\n ...(bundle.knowledge ? { knowledgeManifestDigest: bundle.knowledge.snapshot.digest } : {}),\n ...(entrypoint ? { entrypoint } : {}),\n },\n )\n agentCandidateMaterializationReceiptSchema.parse(materializationReceipt.value)\n\n const traceRunId = `${task.executionId}:attempt-${attempt.number}:${canonicalCandidateDigest({ preparationId }).slice(7, 23)}`\n const traceTags = {\n [CANDIDATE_TRACE_TAGS.executionId]: task.executionId,\n [CANDIDATE_TRACE_TAGS.bundleDigest]: bundle.digest,\n [CANDIDATE_TRACE_TAGS.executionPlanDigest]: executionPlan.digest,\n [CANDIDATE_TRACE_TAGS.materializationReceiptDigest]: materializationReceipt.digest,\n }\n const traceEnv = {\n [CANDIDATE_TRACE_ENV.executionId]: task.executionId,\n [CANDIDATE_TRACE_ENV.bundleDigest]: bundle.digest,\n [CANDIDATE_TRACE_ENV.executionPlanDigest]: executionPlan.digest,\n [CANDIDATE_TRACE_ENV.materializationReceiptDigest]: materializationReceipt.digest,\n [CANDIDATE_TRACE_ENV.traceRunId]: traceRunId,\n }\n assertEnvironmentDisjoint(publicEnv, traceEnv)\n\n return createPreparedCandidateExecution({\n ports,\n bundle,\n benchmarkSuite: task.benchmarkSuite,\n benchmarkTask,\n executionId: task.executionId,\n roots: {\n execution: { ...task.executionRoots },\n staging: { ...task.stagingRoots },\n },\n profilePlan: {\n value: profileApplication.profileActivation.profilePlan,\n bytes: profilePlanBytes,\n written: [...profileApplication.application.mountPaths],\n },\n profileActivation,\n executionPlan: { value: executionPlan, bytes: executionBytes },\n materializationReceipt,\n launch: {\n executable: baseLaunch.executable,\n args: baseLaunch.args.map((value) => value.value),\n env: unwrapPublicEnvironment(publicEnv),\n flags: profileApplication.flags.map((value) => value.value),\n cwd: absoluteExecutionCwd(bundle.execution.cwd, task.executionRoots),\n },\n instruction: {\n bytes: Uint8Array.from(instructionBytes),\n delivery: bundle.execution.instructionDelivery,\n },\n resolvedModel,\n preparationId,\n reservationExpiresAtMs,\n cleanupTimeoutMs,\n resultTimeoutMs,\n modelReservation: {\n preparationId: modelReservation.preparationId,\n digest: modelReservation.digest,\n expiresAtMs: modelReservation.expiresAtMs,\n enforcedLimits: modelReservation.enforcedLimits,\n network: modelReservation.network,\n },\n executorInputs: {\n taskFiles: taskExecutorFiles,\n ...(candidateExecutorFiles ? { candidateFiles: candidateExecutorFiles } : {}),\n profileFiles: exactProfileExecutorFiles(\n profileWorkspacePlan.files,\n profileApplication.profileActivation.profilePlan.material.files,\n ),\n },\n ...(preparedMemory.accessDigest && preparedMemory.value.mode === 'isolated'\n ? {\n memoryReservation: {\n preparationId,\n accessDigest: preparedMemory.accessDigest,\n expiresAtMs: reservationExpiresAtMs,\n effectiveNamespace: preparedMemory.value.effectiveNamespace,\n },\n }\n : {}),\n ...(knowledge ? { knowledge } : {}),\n trace: { runId: traceRunId, tags: traceTags, env: traceEnv },\n memory,\n })\n } catch (error) {\n const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs)\n const cleanup: Array<Promise<unknown>> = []\n if (preparedMemory?.value.mode === 'isolated') {\n const accessDigest = preparedMemory.accessDigest\n const effectiveNamespace = preparedMemory.value.effectiveNamespace\n if (!accessDigest) throw new Error('isolated memory preparation is missing access identity')\n cleanup.push(\n withinCandidateCleanupDeadline(\n async () => {\n const closed = await ports.memory.close({\n executionId: task.executionId,\n preparationId,\n accessDigest,\n effectiveNamespace,\n reason: 'preparation-failed',\n })\n if (closed.closed !== true || Object.keys(closed).some((key) => key !== 'closed')) {\n throw new Error('failed preparation did not close isolated memory access')\n }\n },\n cleanupDeadlineAtMs,\n 'failed preparation memory cleanup',\n ),\n )\n }\n cleanup.push(\n withinCandidateCleanupDeadline(\n async () => {\n const settlement = sealAgentCandidateModelSettlement(\n await ports.models.settleGrant({\n executionId: task.executionId,\n preparationId,\n grantDigest: modelReservation.digest,\n resolved: resolvedModel,\n reason: 'preparation-failed',\n }),\n {\n preparationId,\n grantDigest: modelReservation.digest,\n model: resolvedModel.model,\n },\n )\n if (settlement.usage.modelCalls !== 0) {\n throw new Error('failed preparation unexpectedly contains model calls')\n }\n },\n cleanupDeadlineAtMs,\n 'failed preparation model cleanup',\n ),\n )\n const cleanupResults = await Promise.allSettled(cleanup)\n const cleanupErrors = cleanupResults\n .filter((result): result is PromiseRejectedResult => result.status === 'rejected')\n .map((result) => result.reason)\n if (cleanupErrors.length > 0) {\n throw new Error(\n `candidate preparation failed and protected access cleanup failed: ${cleanupErrors.map(errorMessage).join('; ')}`,\n { cause: error },\n )\n }\n throw error\n }\n}\n\nfunction assertSameVerificationPorts(\n verified: AgentCandidateExecutionPorts | { artifacts: unknown; repositories: unknown },\n execution: AgentCandidateExecutionPorts,\n): void {\n if (\n verified.artifacts !== execution.artifacts ||\n verified.repositories !== execution.repositories\n ) {\n throw new Error(\n 'prepare must use the same artifact and repository ports that verified the bundle',\n )\n }\n}\n\nfunction assertTaskInput(\n task: AgentCandidateTaskExecution,\n delivery: VerifiedAgentCandidate['bundle']['execution']['instructionDelivery'],\n): void {\n const benchmarkTask = agentCandidateBenchmarkTaskSchema.parse(task.task)\n const benchmarkSuite = agentCandidateBenchmarkSuiteSchema.parse(task.benchmarkSuite)\n const runCell = agentCandidateRunCellSchema.parse(task.runCell)\n const requiredStrings: Array<[string, string]> = [\n ['executionId', task.executionId],\n ['benchmark', benchmarkTask.benchmark.name],\n ['benchmarkVersion', benchmarkTask.benchmark.version],\n ['taskId', benchmarkTask.scenario.id],\n ]\n if (benchmarkTask.outcome.kind === 'workspace' && !benchmarkTask.repository) {\n throw new Error('workspace task outcome requires repository identity')\n }\n if (benchmarkTask.repository) {\n requiredStrings.push(\n ['repository identity', benchmarkTask.repository.identity],\n ['repository root identity', benchmarkTask.repository.rootIdentity],\n )\n }\n for (const [name, value] of requiredStrings) {\n if (!value.trim()) throw new Error(`${name} must be non-empty`)\n }\n if (!/^[A-Za-z0-9._:-]{1,200}$/.test(task.executionId)) {\n throw new Error('executionId must be a stable filesystem-neutral identifier')\n }\n if (!benchmarkTask.instruction || !isWellFormedUnicode(benchmarkTask.instruction)) {\n throw new Error('task instruction must be non-empty well-formed Unicode')\n }\n if (\n canonicalCandidateDigest(omitTopLevelDigest(benchmarkTask)) !== benchmarkTask.digest ||\n canonicalCandidateDigest(omitTopLevelDigest(benchmarkSuite)) !== benchmarkSuite.digest ||\n canonicalCandidateDigest(omitTopLevelDigest(runCell)) !== runCell.digest\n ) {\n throw new Error('candidate experiment cell contains an invalid content digest')\n }\n const cellIndex = runCell.taskIndex * benchmarkSuite.reps + runCell.repetition\n if (\n runCell.suiteDigest !== benchmarkSuite.digest ||\n runCell.taskDigest !== benchmarkTask.digest ||\n benchmarkSuite.taskDigests[runCell.taskIndex] !== benchmarkTask.digest ||\n runCell.repetition >= benchmarkSuite.reps ||\n benchmarkSuite.seeds[cellIndex] !== runCell.seed ||\n runCell.attempt > benchmarkTask.attempt.maxAttempts\n ) {\n throw new Error('candidate experiment cell does not match its signed suite and task')\n }\n sha256DigestSchema.parse(benchmarkTask.benchmark.splitDigest)\n agentCandidateTaskOutcomeSpecSchema.parse(benchmarkTask.outcome)\n agentCandidateWorkspaceSnapshotEvidenceSchema.parse(benchmarkTask.workspace)\n agentCandidateExecutionLimitsSchema.parse(benchmarkTask.limits)\n if (benchmarkTask.repository) {\n if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(benchmarkTask.repository.baseCommit)) {\n throw new Error('task repository base commit is not a full Git object id')\n }\n if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(benchmarkTask.repository.baseTree)) {\n throw new Error('task repository base tree is not a full Git object id')\n }\n if (benchmarkTask.repository.baseCommit.length !== benchmarkTask.repository.baseTree.length) {\n throw new Error('task repository Git object formats disagree')\n }\n }\n assertAgentCandidateExecutionRoots(task.executionRoots)\n for (const [name, root] of [\n ['staging task root', task.stagingRoots.taskRoot],\n ['staging candidate root', task.stagingRoots.candidateRoot],\n ['staging profile root', task.stagingRoots.profileRoot],\n ] as const) {\n if (root === undefined) continue\n const canonical = isAbsolute(root) && resolveHostPath(root) === root\n if (!canonical) throw new Error(`${name} must be a canonical absolute path`)\n }\n if (\n !Number.isInteger(runCell.attempt) ||\n !Number.isInteger(benchmarkTask.attempt.maxAttempts) ||\n runCell.attempt < 1 ||\n runCell.attempt > benchmarkTask.attempt.maxAttempts ||\n (benchmarkTask.attempt.retryPolicy === 'none' && benchmarkTask.attempt.maxAttempts !== 1)\n ) {\n throw new Error('task attempt policy is invalid')\n }\n const limits = benchmarkTask.limits\n if (\n !Number.isInteger(limits.timeoutMs) ||\n limits.timeoutMs <= 0 ||\n limits.timeoutMs > MAX_CANDIDATE_TIMER_INTERVAL_MS ||\n !Number.isInteger(limits.maxSteps) ||\n limits.maxSteps <= 0 ||\n !Number.isInteger(limits.maxModelCalls) ||\n limits.maxModelCalls < 0 ||\n !Number.isInteger(limits.maxInputTokens) ||\n limits.maxInputTokens < 0 ||\n !Number.isInteger(limits.maxOutputTokens) ||\n limits.maxOutputTokens < 0 ||\n !Number.isFinite(limits.maxCostUsd) ||\n limits.maxCostUsd < 0\n ) {\n throw new Error('task execution limits are invalid')\n }\n usdToNanos(limits.maxCostUsd, 'task maxCostUsd')\n if (!benchmarkTask.model.requested.trim()) {\n throw new Error('evaluator model request must be non-empty')\n }\n if (!benchmarkTask.grader.name.trim() || !benchmarkTask.grader.version.trim()) {\n throw new Error('evaluator benchmark grader identity must be non-empty')\n }\n if (\n !Number.isInteger(benchmarkTask.grader.artifact.byteLength) ||\n benchmarkTask.grader.artifact.byteLength <= 0\n ) {\n throw new Error('evaluator benchmark grader artifact must be non-empty')\n }\n sha256DigestSchema.parse(benchmarkTask.grader.artifact.sha256)\n if (benchmarkTask.evaluatorTaskContainer) {\n if (\n benchmarkTask.evaluatorTaskContainer.source !== 'evaluator-task-container' ||\n !benchmarkTask.evaluatorTaskContainer.image.trim() ||\n !benchmarkTask.evaluatorTaskContainer.platform.os.trim() ||\n !benchmarkTask.evaluatorTaskContainer.platform.architecture.trim()\n ) {\n throw new Error('evaluator task container evidence is incomplete')\n }\n sha256DigestSchema.parse(benchmarkTask.evaluatorTaskContainer.indexDigest)\n sha256DigestSchema.parse(benchmarkTask.evaluatorTaskContainer.manifestDigest)\n agentCandidateContainerSchema.parse({\n image: benchmarkTask.evaluatorTaskContainer.image,\n indexDigest: benchmarkTask.evaluatorTaskContainer.indexDigest,\n })\n }\n if (delivery.kind === 'utf8-file') {\n if (\n [\n task.executionRoots.taskRoot,\n task.executionRoots.candidateRoot,\n task.executionRoots.profileRoot,\n ].some((root) => root !== undefined && executionPathsOverlap(root, delivery.path))\n ) {\n throw new Error('task instruction file must remain outside execution workspaces')\n }\n }\n}\n\nfunction assertDisjointHostStagingRoots(task: AgentCandidateTaskExecution): void {\n const roots = [\n task.stagingRoots.taskRoot,\n task.stagingRoots.candidateRoot,\n task.stagingRoots.profileRoot,\n ]\n .filter((value): value is string => value !== undefined)\n .map((value) => resolveHostPath(value))\n for (let left = 0; left < roots.length; left++) {\n for (let right = left + 1; right < roots.length; right++) {\n const a = roots[left]\n const b = roots[right]\n if (a && b && (a === b || isContainedPath(a, b) || isContainedPath(b, a))) {\n throw new Error('host task, candidate, and profile staging roots must be disjoint')\n }\n }\n }\n}\n\nfunction isContainedPath(parent: string, child: string): boolean {\n const path = relative(parent, child)\n return path !== '' && !path.startsWith('..') && !isAbsolute(path)\n}\n\nasync function assertEmptyDirectory(path: string): Promise<void> {\n const stats = await lstat(path)\n if (!stats.isDirectory() || stats.isSymbolicLink()) {\n throw new Error('profile staging root must be a real directory')\n }\n if ((await readdir(path)).length !== 0) {\n throw new Error('profile staging root must be empty before materialization')\n }\n}\n\nasync function resolveContainer(\n candidate: VerifiedAgentCandidate,\n task: AgentCandidateTaskExecution,\n ports: AgentCandidateExecutionPorts,\n): Promise<ResolvedAgentCandidateContainer> {\n const environment = candidate.bundle.execution.environment\n const evaluatorTaskContainer = task.task.evaluatorTaskContainer\n const pinned = environment.kind === 'pinned-container' ? environment.container : undefined\n if (environment.kind === 'evaluator-task-container' && !evaluatorTaskContainer) {\n throw new Error('evaluator-task-container candidate requires an evaluator-owned task image')\n }\n if (environment.kind === 'pinned-container' && evaluatorTaskContainer) {\n throw new Error('pinned candidate containers cannot be replaced by a task image')\n }\n const resolved = await ports.containers.resolve({\n candidate: pinned,\n evaluatorTaskContainer,\n })\n if (resolved.source !== environment.kind) throw new Error('resolved container source drifted')\n if (pinned && (resolved.image !== pinned.image || resolved.indexDigest !== pinned.indexDigest)) {\n throw new Error('resolved pinned container does not match the candidate image index')\n }\n if (\n evaluatorTaskContainer &&\n canonicalCandidateDigest(resolved) !== canonicalCandidateDigest(evaluatorTaskContainer)\n ) {\n throw new Error('resolved task container does not match evaluator-owned image evidence')\n }\n return resolved\n}\n\nasync function resolveModel(\n candidate: VerifiedAgentCandidate,\n task: AgentCandidateTaskExecution,\n ports: AgentCandidateExecutionPorts,\n): Promise<AgentCandidateResolvedModel> {\n const hints = candidate.bundle.profile.model\n const expected = task.task.model\n if (hints?.default !== undefined && hints.default !== expected.requested) {\n throw new Error('candidate model preference conflicts with the evaluator-owned model')\n }\n if (hints?.reasoningEffort !== undefined && hints.reasoningEffort !== expected.reasoningEffort) {\n throw new Error('candidate reasoning effort conflicts with the evaluator-owned effort')\n }\n const resolved = await ports.models.resolve({\n requested: expected.requested,\n harness: candidate.bundle.execution.harness,\n reasoningEffort: expected.reasoningEffort,\n })\n if (canonicalCandidateDigest(resolved) !== canonicalCandidateDigest(expected)) {\n throw new Error('model resolver drifted from the signed benchmark model')\n }\n return resolved\n}\n\nasync function prepareMemory(\n candidate: VerifiedAgentCandidate,\n task: AgentCandidateTaskExecution,\n ports: AgentCandidateExecutionPorts,\n preparationId: string,\n expiresAtMs: number,\n cleanupTimeoutMs: number,\n): Promise<{\n value: AgentCandidateEffectiveMemory\n accessDigest?: `sha256:${string}`\n}> {\n const policy = candidate.bundle.memory\n if (policy.mode === 'disabled') return { value: { mode: 'disabled' } }\n const seed = policy.seed ? await verifiedArtifactBytes(candidate, policy.seed) : undefined\n const executionSegment = canonicalCandidateDigest({ executionId: task.executionId }).slice(7)\n const taskSegment = canonicalCandidateDigest({ taskDigest: task.task.digest }).slice(7)\n const preparationSegment = canonicalCandidateDigest({ preparationId }).slice(7, 23)\n const effectiveNamespace = `candidate/${candidate.bundle.digest.slice(7, 23)}/${executionSegment}/${taskSegment}/${preparationSegment}`\n const reset = await withinCandidateCleanupDeadline(\n () =>\n ports.memory.reset({\n executionId: task.executionId,\n preparationId,\n expiresAtMs,\n effectiveNamespace,\n ...(seed ? { seed } : {}),\n ...(policy.seed ? { seedDigest: policy.seed.sha256 } : {}),\n }),\n candidateCleanupDeadline(cleanupTimeoutMs),\n 'isolated memory reset',\n )\n try {\n if (\n reset.preparationId !== preparationId ||\n reset.expiresAtMs !== expiresAtMs ||\n !/^sha256:[a-f0-9]{64}$/.test(reset.accessDigest)\n ) {\n throw new Error('isolated memory reservation is not scoped to this preparation')\n }\n await readVerifiedArtifact(reset.evidence, ports.artifacts)\n await verifyWorkspaceSnapshotArtifacts(reset.beforeState, ports.artifacts)\n return {\n value: {\n mode: 'isolated',\n scope: 'task',\n effectiveNamespace,\n reset: {\n kind: 'fresh',\n evidence: reset.evidence,\n emptyStateDigest: reset.emptyStateDigest,\n },\n beforeState: reset.beforeState,\n ...(policy.seed ? { seedDigest: policy.seed.sha256 } : {}),\n },\n accessDigest: reset.accessDigest,\n }\n } catch (error) {\n try {\n const closed = await withinCandidateCleanupDeadline(\n () =>\n ports.memory.close({\n executionId: task.executionId,\n preparationId,\n accessDigest: reset.accessDigest,\n effectiveNamespace,\n reason: 'preparation-failed',\n }),\n candidateCleanupDeadline(cleanupTimeoutMs),\n 'invalid isolated memory reset cleanup',\n )\n if (closed.closed !== true || Object.keys(closed).some((key) => key !== 'closed')) {\n throw new Error('invalid isolated memory reset did not acknowledge closure')\n }\n } catch (closeError) {\n throw new Error('isolated memory preparation and cleanup both failed', {\n cause: new AggregateError([error, closeError]),\n })\n }\n throw error\n }\n}\n\nfunction buildLaunch(\n candidate: VerifiedAgentCandidate,\n task: AgentCandidateTaskExecution,\n profileFlags: AgentCandidateConfigValue[],\n): { executable: string; args: AgentCandidateConfigValue[] } {\n const launch = candidate.bundle.execution.launch\n if (launch.kind === 'container-command') {\n return { executable: launch.executable, args: [...(launch.args ?? []), ...profileFlags] }\n }\n const candidateRoot = task.executionRoots.candidateRoot\n if (!candidateRoot) throw new Error('candidate entrypoint requires a container candidate root')\n const entrypoint = posix.join(candidateRoot, launch.entrypoint)\n const candidateArgs = launch.args ?? []\n if (launch.interpreter) {\n return {\n executable: launch.interpreter,\n args: [{ kind: 'public', value: entrypoint }, ...candidateArgs, ...profileFlags],\n }\n }\n return { executable: entrypoint, args: [...candidateArgs, ...profileFlags] }\n}\n\nfunction mergePublicEnvironment(\n ...records: Array<Record<string, AgentCandidateConfigValue>>\n): Record<string, AgentCandidateConfigValue> {\n const output: Record<string, AgentCandidateConfigValue> = {}\n for (const record of records) {\n for (const [name, value] of Object.entries(record)) {\n const previous = output[name]\n if (previous && previous.value !== value.value) {\n throw new Error(`candidate and profile environment disagree on ${name}`)\n }\n output[name] = value\n }\n }\n return output\n}\n\nfunction unwrapPublicEnvironment(\n values: Record<string, AgentCandidateConfigValue>,\n): Record<string, string> {\n return Object.fromEntries(Object.entries(values).map(([name, value]) => [name, value.value]))\n}\n\nfunction modelRoutes(\n profile: VerifiedAgentCandidate['bundle']['profile'],\n requested: string,\n): AgentCandidateExecutionPlanMaterial['model']['routes'] {\n const routes: AgentCandidateExecutionPlanMaterial['model']['routes'] = [\n { kind: 'primary', requested },\n ]\n if (profile.model?.small) routes.push({ kind: 'small', requested })\n for (const name of Object.keys(profile.modes ?? {}).sort()) {\n if (profile.modes?.[name]?.model) routes.push({ kind: 'mode', name, requested })\n }\n for (const name of Object.keys(profile.subagents ?? {}).sort()) {\n if (profile.subagents?.[name]?.model) routes.push({ kind: 'subagent', name, requested })\n }\n return routes\n}\n\nfunction candidateEntrypointReceipt(\n candidate: VerifiedAgentCandidate,\n): { path: string; sha256: `sha256:${string}`; byteLength: number } | undefined {\n const launch = candidate.bundle.execution.launch\n const workspace = candidate.bundle.execution.workspace\n if (launch.kind !== 'candidate-entrypoint' || !workspace) return undefined\n const file = workspace.material.files.find((entry) => entry.path === launch.entrypoint)\n if (!file) throw new Error('candidate entrypoint is absent from the verified workspace')\n return { path: file.path, sha256: file.sha256, byteLength: file.byteLength }\n}\n\nfunction absoluteExecutionCwd(\n cwd: VerifiedAgentCandidate['bundle']['execution']['cwd'],\n roots: AgentCandidateTaskExecution['executionRoots'],\n): string {\n const root = workspaceExecutionRoot(cwd.workspace, roots)\n const absolute = cwd.path === '.' ? root : posix.join(root, cwd.path)\n if (absolute !== root && !absolute.startsWith(`${root}/`)) {\n throw new Error('candidate cwd escapes its execution workspace')\n }\n return absolute\n}\n\nfunction workspaceExecutionRoot(\n workspace: 'task' | 'candidate',\n roots: AgentCandidateTaskExecution['executionRoots'],\n): string {\n const root = workspace === 'task' ? roots.taskRoot : roots.candidateRoot\n if (!root) throw new Error(`candidate ${workspace} workspace root is missing`)\n return root\n}\n\nfunction validateProtectedModelReservation(\n reservation: {\n preparationId: string\n digest: string\n expiresAtMs: number\n enforcedLimits: {\n maxModelCalls: number\n maxInputTokens: number\n maxOutputTokens: number\n maxCostUsd: number\n }\n network: AgentCandidateModelAccessNetwork\n },\n expectedLimits: AgentCandidateExecutionLimits,\n preparationId: string,\n expiresAtMs: number,\n): void {\n if (!/^sha256:[a-f0-9]{64}$/.test(reservation.digest)) {\n throw new Error('protected model reservation has an invalid identity digest')\n }\n if (reservation.preparationId !== preparationId || reservation.expiresAtMs !== expiresAtMs) {\n throw new Error('protected model reservation is not scoped to this preparation')\n }\n const limits = modelLimits(expectedLimits)\n if (canonicalCandidateDigest(reservation.enforcedLimits) !== canonicalCandidateDigest(limits)) {\n throw new Error('protected model reservation does not enforce the frozen model limits')\n }\n const expectedNetworkMode = limits.maxModelCalls === 0 ? 'disabled' : 'gateway-only'\n const network = agentCandidateModelAccessNetworkSchema.parse(reservation.network)\n if (network.mode !== expectedNetworkMode) {\n throw new Error('protected model reservation has the wrong network policy for its call limit')\n }\n}\n\nfunction assertEnvironmentDisjoint(\n publicEnv: Record<string, AgentCandidateConfigValue>,\n traceEnv: Record<string, string>,\n): void {\n const seen = new Set(Object.keys(publicEnv))\n for (const name of Object.keys(traceEnv)) {\n if (seen.has(name)) throw new Error(`evaluator environment binding collides with ${name}`)\n seen.add(name)\n }\n}\n\nfunction modelLimits(limits: AgentCandidateExecutionLimits): {\n maxModelCalls: number\n maxInputTokens: number\n maxOutputTokens: number\n maxCostUsd: number\n} {\n return {\n maxModelCalls: limits.maxModelCalls,\n maxInputTokens: limits.maxInputTokens,\n maxOutputTokens: limits.maxOutputTokens,\n maxCostUsd: limits.maxCostUsd,\n }\n}\n\nfunction exactProfileExecutorFiles(\n sourceFiles: ReadonlyArray<{\n relPath: string\n content: string\n mode?: number\n root?: 'agent' | 'workspace'\n }>,\n expectedFiles: ReadonlyArray<{\n relPath: string\n mode: number\n contentSha256: string\n root?: 'agent'\n }>,\n): Array<{ path: string; mode: number; root?: 'agent'; bytes: Uint8Array }> {\n const byIdentity = new Map(\n sourceFiles.map((file) => [profileFileIdentity(file.root, file.relPath), file]),\n )\n if (byIdentity.size !== sourceFiles.length || sourceFiles.length !== expectedFiles.length) {\n throw new Error('profile source files do not match the signed profile plan')\n }\n return expectedFiles.map((expected) => {\n const source = byIdentity.get(profileFileIdentity(expected.root, expected.relPath))\n const mode = source?.mode ?? 0o644\n const bytes = Buffer.from(source?.content ?? '', 'utf8')\n if (\n !source ||\n !Number.isInteger(mode) ||\n mode < 0 ||\n mode > 0o777 ||\n mode !== expected.mode ||\n sha256Bytes(bytes) !== expected.contentSha256\n ) {\n throw new Error('profile source files do not match the signed profile plan')\n }\n return {\n path: expected.relPath,\n mode,\n ...(expected.root === 'agent' ? { root: 'agent' as const } : {}),\n bytes: Uint8Array.from(bytes),\n }\n })\n}\n\nfunction profileFileIdentity(root: 'agent' | 'workspace' | undefined, relPath: string): string {\n return `${root ?? 'workspace'}\\0${relPath}`\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n"],"mappings":";;;;;;;;;;;;AAeA,SAAgB,iCACd,OACA,qBACmC;CACnC,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GACpE,MAAM,IAAI,MAAM,4DAA4D;CAE9E,MAAM,SAAS;CACf,sBACE,QACA,CAAC,iBAAiB,wBAAwB,GAC1C,0CACF;CACA,MAAM,gBAAgB,wBACpB,gCAAgC,MAAM,OAAO,aAAa,CAC5D;CACA,MAAM,yBAAyB,wBAC7B,gCAAgC,MAAM,OAAO,sBAAsB,CACrE;CACA,IAAI,cAAc,WAAW,qBAC3B,MAAM,IAAI,MAAM,mEAAmE;CAErF,OAAO,OAAO,OAAO;EAAE;EAAe;CAAuB,CAAC;AAChE;;;ACjBA,MAAMA,mBAAiB;AAEvB,SAAgB,eACd,OACA,QACuC;CACvC,MAAM,WAAW,mBAAmB,MAAM;CAC1C,MAAM,QAAQ;EACZ,aAAa,MAAM;EACnB,SAAS,MAAM;EACf,cAAc,MAAM;EACpB,qBAAqB,MAAM;EAC3B,qBAAqB,MAAM;EAC3B,GAAG;CACL;CACA,OAAO,wBAAwB;EAC7B,GAAG;EACH,gBAAgBC,2BAAyB,KAAK;CAChD,CA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