@tangle-network/agent-runtime 0.92.1 → 0.93.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -4
- package/dist/candidate-execution/index.d.ts +48 -4
- package/dist/candidate-execution/index.js +6 -2
- package/dist/{chunk-A62TP7SK.js → chunk-26WCEARH.js} +295 -40
- package/dist/chunk-26WCEARH.js.map +1 -0
- package/dist/{chunk-PH65PR4F.js → chunk-3VU2OWOY.js} +106 -2
- package/dist/chunk-3VU2OWOY.js.map +1 -0
- package/dist/{chunk-4FPXIMSI.js → chunk-VMHKMNEU.js} +38 -9
- package/dist/chunk-VMHKMNEU.js.map +1 -0
- package/dist/{improve-CUVCq7xg.d.ts → improve-DDhQaaJT.d.ts} +17 -5
- package/dist/index.d.ts +3 -3
- package/dist/index.js +7 -3
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +6 -8
- package/dist/intelligence.js +23 -131
- package/dist/intelligence.js.map +1 -1
- package/dist/{prepare-Z08a4heC.d.ts → prepare-DiVGKcwS.d.ts} +7 -2
- package/package.json +4 -4
- package/skills/build-with-agent-runtime/SKILL.md +2 -1
- package/dist/chunk-4FPXIMSI.js.map +0 -1
- package/dist/chunk-A62TP7SK.js.map +0 -1
- package/dist/chunk-PH65PR4F.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/candidate-execution/bundle.ts","../src/candidate-execution/digest.ts","../src/candidate-execution/types.ts","../src/candidate-execution/claim.ts","../src/candidate-execution/claim-file-formats.ts","../src/candidate-execution/claim-terminal.ts","../src/candidate-execution/exact-object.ts","../src/candidate-execution/cleanup.ts","../src/candidate-execution/execution-window.ts","../src/candidate-execution/prepared-state.ts","../src/candidate-execution/artifacts.ts","../src/candidate-execution/git-materialize.ts","../src/candidate-execution/claim-plan.ts","../src/candidate-execution/output-artifacts.ts","../src/candidate-execution/executor-capture.ts","../src/candidate-execution/finalize.ts","../src/candidate-execution/model-settlement.ts","../src/candidate-execution/protected-redaction.ts","../src/candidate-execution/outcome-evidence.ts","../src/candidate-execution/benchmark-grader.ts","../src/candidate-execution/protected-trace-store.ts","../src/candidate-execution/execute.ts","../src/candidate-execution/verify.ts","../src/candidate-execution/prepare.ts","../src/candidate-execution/profile.ts"],"sourcesContent":["import type { AgentCandidateBundle } from '@tangle-network/agent-interface'\nimport { agentCandidateBundleSchema } from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue, omitTopLevelDigest } from './digest'\n\n/** Exact candidate wire shape before the runtime computes its canonical digest. */\nexport type AgentCandidateBundleInput = Omit<AgentCandidateBundle, 'digest'>\n\n/** Validate and content-address a candidate bundle before it crosses an approval boundary. */\nexport function sealAgentCandidateBundle(input: AgentCandidateBundleInput): AgentCandidateBundle {\n const digest = canonicalCandidateDigest(input)\n const parsed = agentCandidateBundleSchema.parse({ ...input, digest })\n const parsedDigest = canonicalCandidateDigest(omitTopLevelDigest(parsed))\n if (parsedDigest !== digest) {\n throw new Error('candidate bundle changed while validating its canonical wire shape')\n }\n return immutableCandidateValue(parsed)\n}\n","import { createHash } from 'node:crypto'\nimport { canonicalJson } from '@tangle-network/agent-eval'\nimport type { AgentCandidateEmbeddedArtifact, Sha256Digest } from '@tangle-network/agent-interface'\n\nimport { contentAddress } from '../durable/spawn-journal'\nimport type { CanonicalCandidateDocument } from './types'\n\nexport function sha256Bytes(bytes: Uint8Array): Sha256Digest {\n return `sha256:${createHash('sha256').update(bytes).digest('hex')}`\n}\n\nexport function canonicalCandidateBytes(value: unknown): Uint8Array {\n return Buffer.from(canonicalJson(value), 'utf8')\n}\n\nexport function canonicalCandidateDigest(value: unknown): Sha256Digest {\n return contentAddress(value) as Sha256Digest\n}\n\n/** Returns a detached, deeply frozen JSON value with canonical number normalization. */\nexport function immutableCandidateValue<T>(value: T): T {\n return deepFreezeCandidate(\n JSON.parse(Buffer.from(canonicalCandidateBytes(value)).toString('utf8')) as T,\n )\n}\n\nexport function canonicalCandidateDocument<T extends { digest: Sha256Digest }>(\n valueWithoutDigest: Omit<T, 'digest'>,\n): CanonicalCandidateDocument<T> {\n const bytes = canonicalCandidateBytes(valueWithoutDigest)\n const digest = canonicalCandidateDigest(valueWithoutDigest)\n if (sha256Bytes(bytes) !== digest) {\n throw new Error('canonical candidate serializers disagree on document digest')\n }\n const storedBytes = Uint8Array.from(bytes)\n const value = immutableCandidateValue({ ...valueWithoutDigest, digest }) as T\n return Object.freeze({\n value,\n get bytes(): Uint8Array {\n return Uint8Array.from(storedBytes)\n },\n digest,\n })\n}\n\nexport function embeddedCandidateArtifact(bytes: Uint8Array): AgentCandidateEmbeddedArtifact {\n return {\n encoding: 'base64',\n content: Buffer.from(bytes).toString('base64'),\n sha256: sha256Bytes(bytes),\n byteLength: bytes.byteLength,\n }\n}\n\nexport function omitTopLevelDigest<T extends { digest: Sha256Digest }>(\n value: T,\n): Omit<T, 'digest'> {\n const { digest: _digest, ...rest } = value\n return rest\n}\n\nexport function deepFreezeCandidate<T>(value: T, seen = new Set<object>()): T {\n if (\n value === null ||\n typeof value !== 'object' ||\n ArrayBuffer.isView(value) ||\n seen.has(value as object)\n ) {\n return value\n }\n seen.add(value as object)\n for (const child of Object.values(value as Record<string, unknown>)) {\n deepFreezeCandidate(child, seen)\n }\n return Object.freeze(value)\n}\n","import type { BenchmarkEvaluation, TraceStore } from '@tangle-network/agent-eval'\nimport type {\n AgentCandidateArtifactRef,\n AgentCandidateAttemptPolicy,\n AgentCandidateBundle,\n AgentCandidateCapturedArtifact,\n AgentCandidateContainer,\n AgentCandidateEffectiveMemory,\n AgentCandidateExecutionLimits,\n AgentCandidateExecutionPlanEvidence,\n AgentCandidateGitHubRepository,\n AgentCandidateInstructionDelivery,\n AgentCandidateMaterializationReceipt,\n AgentCandidateMemoryReceipt,\n AgentCandidateModelAccessNetwork,\n AgentCandidateOciPlatform,\n AgentCandidateProfilePlanEvidence,\n AgentCandidateResolvedModel,\n AgentCandidateRunReceiptV2,\n AgentCandidateSpend,\n AgentCandidateTaskOutcomeEvidence,\n AgentCandidateTermination,\n AgentCandidateWorkspaceManifestMaterialV1,\n AgentCandidateWorkspaceSnapshotEvidence,\n ReasoningEffort,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\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}\n\nexport type AgentCandidateOutputPurpose =\n | 'task-manifest'\n | 'task-archive'\n | 'task-patch'\n | 'task-outcome'\n | 'memory-after-manifest'\n | 'memory-after-archive'\n | 'grader-evidence'\n | 'benchmark-result'\n | 'model-settlement'\n | 'trace'\n | 'run-receipt'\n | 'failure-evidence'\n\n/** Durable content-addressed evidence store controlled only by the evaluator. */\nexport interface AgentCandidateOutputArtifactPort extends AgentCandidateArtifactPort {\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' | '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\nexport interface AgentCandidateBenchmarkGraderIdentity {\n name: string\n version: string\n artifact: AgentCandidateArtifactRef\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 one of these limits 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\n/** One evaluator-gateway call in the final, revoked model-access ledger. */\nexport interface AgentCandidateProtectedModelCall {\n callId: string\n /** Router-generated public response identity. */\n generationId: string\n /** Exact protected agent-eval LLM span produced from the router ledger. */\n traceSpanId: string\n status: 'succeeded' | 'failed'\n model: string\n startedAtMs: number\n endedAtMs: number\n inputTokens: number\n outputTokens: number\n cachedInputTokens: number\n reasoningTokens: number\n /** Integer billionths of one US dollar; avoids floating-point ledger drift. */\n costUsdNanos: number\n}\n\nexport interface AgentCandidateProtectedModelSettlement {\n preparationId: string\n grantDigest: Sha256Digest\n closed: true\n calls: readonly AgentCandidateProtectedModelCall[]\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\nexport interface AgentCandidateTaskExecution {\n executionId: string\n benchmark: string\n benchmarkVersion: string\n taskId: string\n splitDigest: Sha256Digest\n /** Exact agent-visible task instruction. The runtime rejects malformed Unicode. */\n instruction: string\n repository: {\n identity: string\n rootIdentity: string\n baseCommit: string\n baseTree: string\n }\n attempt: AgentCandidateAttemptPolicy\n model: {\n requested: string\n reasoningEffort: ReasoningEffort\n }\n grader: AgentCandidateBenchmarkGraderIdentity\n /** Absolute paths inside the evaluator-owned execution environment. */\n executionRoots: {\n taskRoot: string\n candidateRoot?: string\n }\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 workspace: AgentCandidateWorkspaceSnapshotEvidence\n evaluatorTaskContainer?: ResolvedAgentCandidateContainer\n limits: AgentCandidateExecutionLimits\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\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 executionId: string\n readonly roots: {\n execution: {\n taskRoot: string\n candidateRoot?: string\n }\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 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?: {\n snapshotId: string\n manifestDigest: Sha256Digest\n manifest: Uint8Array\n }\n readonly trace: PreparedAgentCandidateTrace\n readonly memory: AgentCandidateEffectiveMemory\n readonly [preparedCandidateBrand]: true\n}\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 interface AgentCandidateExecutorTaskOutcomeCapture {\n /** Claimed final tree. The runtime recomputes it independently from `gitDiff`. */\n resultTree: string\n /** Complete evaluator-captured workspace description after candidate execution. */\n afterState: AgentCandidateWorkspaceManifestMaterialV1\n /** Reproducible workspace archive corresponding to `afterState`. */\n archive: Uint8Array\n /** Exact binary patch from the signed task base to `afterState`. */\n gitDiff: Uint8Array\n}\n\n/** Raw isolated-memory capture made only after access has been revoked. */\nexport interface AgentCandidateExecutorMemoryCapture {\n readonly afterState: AgentCandidateWorkspaceManifestMaterialV1\n readonly archive: Uint8Array\n}\n\n/** Idempotent executor result after process death and trace drain. */\nexport interface AgentCandidateExecutorFinalCapture {\n readonly stopped: true\n readonly taskOutcome?: AgentCandidateExecutorTaskOutcomeCapture\n /** Required only when the prepared candidate uses isolated task memory. */\n readonly memoryAfter?: AgentCandidateExecutorMemoryCapture\n}\n\n/** Branded task outcome that has survived independent patch and tree verification. */\nexport interface VerifiedAgentCandidateTaskOutcome {\n readonly evidence: AgentCandidateTaskOutcomeEvidence & {\n readonly artifact: AgentCandidateArtifactRef\n }\n readonly patch: 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 /** 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 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?: PreparedAgentCandidateExecution['knowledge']\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 /**\n * Kill any process/container still associated with the request, drain trace\n * writes, and capture the final task workspace before teardown.\n * The runtime calls this on success, failure, and timeout before model settlement.\n * Implementations must be idempotent and concurrency-safe for this exact\n * execution/plan pair because a fresh worker may repeat crash recovery.\n */\n stopAndCapture(\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<AgentCandidateExecutorFinalCapture>\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: 0o644 | 0o755\n readonly bytes: Uint8Array\n}\n\nexport interface AgentCandidateExecutorProfileFile {\n readonly path: string\n readonly mode: 0o644 | 0o755\n readonly bytes: Uint8Array\n}\n\nexport type AgentCandidateRunFinalization =\n | {\n succeeded: true\n receipt: CanonicalCandidateDocument<AgentCandidateRunReceiptV2>\n artifacts: {\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: AgentCandidateSpend | 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","/** 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 AgentCandidateResolvedModel,\n agentCandidateResolvedModelSchema,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n CLAIM_FORMAT_VERSION,\n PENDING_FORMAT_VERSION,\n type PersistedAgentCandidateExecutionClaim,\n type PersistedAgentCandidateExecutionPending,\n type PersistedAgentCandidateExecutionPhase,\n type PersistedAgentCandidateExecutionTerminal,\n PHASE_FORMAT_VERSION,\n TERMINAL_FORMAT_VERSION,\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 /** 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/** Exact fixed-point usage proven by the closed evaluator model ledger. */\nexport interface AgentCandidateExecutionUsage {\n readonly costUsdNanos: number\n readonly inputTokens: number\n readonly outputTokens: number\n readonly cachedInputTokens: number\n readonly reasoningTokens: number\n readonly modelCalls: number\n}\n\n/** Evaluator-owned terminal facts staged durably before the terminal CAS. */\nexport type AgentCandidateExecutionTerminalResult =\n | {\n readonly schemaVersion: 1\n readonly status: 'succeeded'\n readonly usage: AgentCandidateExecutionUsage\n readonly modelSettlement: AgentCandidateArtifactRef\n readonly taskOutcome: AgentCandidateArtifactRef\n readonly benchmarkResult: AgentCandidateArtifactRef\n readonly runReceipt: AgentCandidateArtifactRef\n }\n | {\n readonly schemaVersion: 1\n readonly status: 'failed'\n readonly failureClass: AgentCandidateExecutionFailureClass\n readonly usage: AgentCandidateExecutionUsage\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 /** 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: AgentCandidateExecutionUsage\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-v1\\.[A-Za-z0-9_-]{43}$/\nconst PREPARATION_ID_PATTERN = /^candidate-preparation-v1\\.[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 '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 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 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-v1.${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 if (record.version !== CLAIM_FORMAT_VERSION) {\n throw new Error(`candidate execution claim at ${path} has unsupported version`)\n }\n assertExactKeys(\n parsed,\n [\n 'version',\n 'executionId',\n 'attempt',\n 'maxAttempts',\n 'retryPolicy',\n 'bundleDigest',\n 'executionPlanDigest',\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 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 if (record.version !== TERMINAL_FORMAT_VERSION) {\n throw new Error(`candidate execution terminal record at ${path} has unsupported version`)\n }\n assertExactKeys(parsed, ['version', '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 if (record.version !== PHASE_FORMAT_VERSION) {\n throw new Error(`candidate execution phase record at ${path} has unsupported version`)\n }\n assertExactKeys(\n parsed,\n ['version', '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 if (record.version !== PENDING_FORMAT_VERSION) {\n throw new Error(`candidate execution pending record at ${path} has unsupported version`)\n }\n assertExactKeys(\n parsed,\n ['version', 'kind', 'terminal'],\n `candidate execution pending record at ${path}`,\n )\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 type { Sha256Digest } from '@tangle-network/agent-interface'\n\nimport type { AgentCandidateExecutionClaim, AgentCandidateExecutionTerminalRecord } from './claim'\n\nexport const CLAIM_FORMAT_VERSION = 7\nexport const PENDING_FORMAT_VERSION = 1\nexport const TERMINAL_FORMAT_VERSION = 3\nexport const PHASE_FORMAT_VERSION = 1\n\nexport interface PersistedAgentCandidateExecutionClaim extends AgentCandidateExecutionClaim {\n version: typeof CLAIM_FORMAT_VERSION\n phase: 'claimed'\n leaseDigest: Sha256Digest\n}\n\nexport interface PersistedAgentCandidateExecutionPending {\n version: typeof PENDING_FORMAT_VERSION\n kind: 'candidate-execution-pending-terminal'\n terminal: AgentCandidateExecutionTerminalRecord\n}\n\nexport interface PersistedAgentCandidateExecutionPhase {\n version: typeof PHASE_FORMAT_VERSION\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 version: typeof TERMINAL_FORMAT_VERSION\n terminal: AgentCandidateExecutionTerminalRecord\n}\n","import type { AgentCandidateArtifactRef, Sha256Digest } 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 AgentCandidateExecutionUsage,\n} from './claim'\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 ...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 schemaVersion: 1,\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 'terminalDigest',\n 'schemaVersion',\n 'status',\n 'usage',\n 'modelSettlement',\n 'taskOutcome',\n 'benchmarkResult',\n 'runReceipt',\n ]\n : [\n 'executionId',\n 'attempt',\n 'bundleDigest',\n 'executionPlanDigest',\n 'terminalDigest',\n 'schemaVersion',\n 'status',\n 'failureClass',\n 'usage',\n 'modelSettlement',\n ...(value.failureEvidence ? ['failureEvidence'] : []),\n ],\n label,\n )\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: requireString(\n value.executionPlanDigest,\n label,\n 'executionPlanDigest',\n ) as Sha256Digest,\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 const result = sealTerminalResult(\n status === 'succeeded'\n ? {\n schemaVersion: requireNumber(value.schemaVersion, label, 'schemaVersion') as 1,\n status,\n usage: requireObject(\n value.usage,\n label,\n 'usage',\n ) as unknown as AgentCandidateExecutionUsage,\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 schemaVersion: requireNumber(value.schemaVersion, label, 'schemaVersion') as 1,\n status,\n failureClass: requireFailureClass(value.failureClass, label),\n usage: requireObject(\n value.usage,\n label,\n 'usage',\n ) as unknown as AgentCandidateExecutionUsage,\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 ) {\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 ? [\n 'schemaVersion',\n 'status',\n 'usage',\n 'modelSettlement',\n 'taskOutcome',\n 'benchmarkResult',\n 'runReceipt',\n ]\n : [\n 'schemaVersion',\n 'status',\n 'failureClass',\n 'usage',\n 'modelSettlement',\n ...(result.failureEvidence ? ['failureEvidence'] : []),\n ],\n 'candidate execution terminal result',\n )\n if (result.schemaVersion !== 1) {\n throw new Error('candidate execution terminal schemaVersion must be 1')\n }\n const usage = sealUsage(result.usage)\n const modelSettlement = sealArtifactRef(result.modelSettlement, 'modelSettlement')\n if (result.status === 'succeeded') {\n return Object.freeze({\n schemaVersion: 1,\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 schemaVersion: 1,\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: AgentCandidateExecutionUsage): AgentCandidateExecutionUsage {\n assertExactKeys(\n usage,\n [\n 'costUsdNanos',\n 'inputTokens',\n 'outputTokens',\n 'cachedInputTokens',\n 'reasoningTokens',\n 'modelCalls',\n ],\n 'candidate execution terminal usage',\n )\n for (const [field, value] of Object.entries(usage)) {\n assertCount(value, `terminal usage ${field}`)\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 })\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","/** Reject unknown fields while requiring every declared non-optional field. */\nexport function assertExactObjectKeys(\n value: unknown,\n required: readonly string[],\n label: string,\n optional: readonly string[] = [],\n): void {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`)\n }\n const allowed = new Set([...required, ...optional])\n if (allowed.size !== required.length + optional.length) {\n throw new Error(`${label} exact-key contract contains duplicate fields`)\n }\n for (const key of Object.keys(value)) {\n if (!allowed.has(key)) throw new Error(`${label} contains unknown field ${key}`)\n }\n for (const key of required) {\n if (!(key in value)) throw new Error(`${label} is missing field ${key}`)\n }\n}\n","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 while keeping late rejection observed. */\nexport async function withinCandidateCleanupDeadline<T>(\n operation: () => Promise<T>,\n deadlineAtMs: number,\n label: string,\n): Promise<T> {\n const remainingMs = deadlineAtMs - Date.now()\n if (remainingMs <= 0) throw new CandidateCleanupTimeoutError(label)\n\n const pending = Promise.resolve().then(operation)\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(() => reject(new CandidateCleanupTimeoutError(label)), remainingMs)\n }),\n ])\n // Exact-boundary completion is ambiguous under event-loop delay.\n if (Date.now() >= deadlineAtMs) throw new CandidateCleanupTimeoutError(label)\n return result\n } finally {\n if (timer) clearTimeout(timer)\n }\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 const remainingMs = deadlineAtMs - Date.now()\n if (remainingMs <= 0) throw new CandidateResultTimeoutError(label)\n\n const controller = new AbortController()\n const timeoutError = new CandidateResultTimeoutError(label)\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","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 {\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 { verifyTaskCheckout } from './git-materialize'\nimport type {\n AgentCandidateExecutionPorts,\n AgentCandidateExecutorRequest,\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 executionId: string\n roots: PreparedAgentCandidateExecution['roots']\n profilePlan: PreparedAgentCandidateExecution['profilePlan']\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: 0o644 | 0o755\n bytes: Uint8Array\n }>\n candidateFiles?: ReadonlyArray<{\n path: string\n mode: 0o644 | 0o755\n bytes: Uint8Array\n }>\n profileFiles: ReadonlyArray<{\n path: string\n mode: 0o644 | 0o755\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 executionId: state.executionId,\n roots: state.roots,\n profilePlan: evidenceView(state.profilePlan),\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 inputs: Object.freeze({\n task: workspaceInputView(material.task.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 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\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(state.roots.staging.taskRoot, plan.task.workspace.material, {\n ignoredProtectedRootEntries: ['.git', '.sidecar'],\n })\n await verifyTaskCheckout(state.roots.staging.taskRoot, plan.task.repository)\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 profilePlan = immutableCandidateValue(\n agentCandidateProfilePlanEvidenceSchema.parse(input.profilePlan.value),\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 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 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: Object.freeze(\n input.executorInputs.profileFiles.map((file) =>\n Object.freeze({ ...file, bytes: Uint8Array.from(file.bytes) }),\n ),\n ),\n }),\n ...(input.memoryReservation\n ? { memoryReservation: immutableCandidateValue(input.memoryReservation) }\n : {}),\n ...(input.knowledge\n ? {\n knowledge: Object.freeze({\n snapshotId: input.knowledge.snapshotId,\n manifestDigest: input.knowledge.manifestDigest,\n manifest: Uint8Array.from(input.knowledge.manifest),\n }),\n }\n : {}),\n trace: immutableCandidateValue(input.trace),\n memory: immutableCandidateValue(input.memory),\n })\n}\n\nfunction assertPrivateCandidateIntegrity(state: PreparedCandidateState): void {\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 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 const instruction = state.executionPlan.value.material.task.instruction\n if (\n sha256Bytes(state.instruction.bytes) !== instruction.sha256 ||\n state.instruction.bytes.byteLength !== instruction.byteLength ||\n JSON.stringify(state.instruction.delivery) !== JSON.stringify(instruction.delivery)\n ) {\n throw new Error('prepared instruction no longer matches the signed execution plan')\n }\n if (\n !/^candidate-preparation-v1\\.[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 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.attempt.number}:`,\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 manifest = Uint8Array.from(knowledge.manifest)\n return Object.freeze({\n snapshotId: knowledge.snapshotId,\n manifestDigest: knowledge.manifestDigest,\n get manifest(): Uint8Array {\n return Uint8Array.from(manifest)\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) => profileFileView(file))),\n })\n}\n\nfunction profileFileView(\n source: PreparedCandidateState['executorInputs']['profileFiles'][number],\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 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(state.executorInputs.taskFiles, material.task.workspace.material)\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.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 assertWorkspaceExecutorFiles(\n actualFiles: PreparedCandidateState['executorInputs']['taskFiles'],\n expected: PreparedAgentCandidateExecution['executionPlan']['value']['material']['task']['workspace']['material'],\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 immutableExecutorFiles(\n files: PreparedCandidateState['executorInputs']['taskFiles'],\n): ReadonlyArray<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }> {\n return Object.freeze(\n files.map((file) => Object.freeze({ ...file, bytes: Uint8Array.from(file.bytes) })),\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 { constants as fsConstants } from 'node:fs'\nimport { lstat, open, readdir, realpath } from 'node:fs/promises'\nimport { relative, resolve, sep } from 'node:path'\n\nimport type {\n AgentCandidateArtifactRef,\n AgentCandidateCapturedArtifact,\n AgentCandidateProfilePlanMaterialV1,\n AgentCandidateWorkspaceManifestMaterialV1,\n AgentCandidateWorkspaceSnapshotEvidence,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateBytes, sha256Bytes } from './digest'\nimport type { AgentCandidateArtifactPort } from './types'\n\nexport function artifactCacheKey(artifact: AgentCandidateCapturedArtifact): string {\n return `${artifact.sha256}:${artifact.byteLength}`\n}\n\nexport async function readVerifiedArtifact(\n artifact: AgentCandidateCapturedArtifact,\n port: AgentCandidateArtifactPort,\n): Promise<Uint8Array> {\n const bytes =\n 'content' in artifact\n ? Buffer.from(artifact.content, 'base64')\n : await port.read(artifact as AgentCandidateArtifactRef)\n verifyBytes(bytes, artifact.sha256, artifact.byteLength, 'candidate artifact')\n return Uint8Array.from(bytes)\n}\n\nexport function verifyBytes(\n bytes: Uint8Array,\n digest: string,\n byteLength: number,\n label: string,\n): void {\n if (bytes.byteLength !== byteLength) {\n throw new Error(`${label} byte length ${bytes.byteLength} does not match ${byteLength}`)\n }\n const actual = sha256Bytes(bytes)\n if (actual !== digest) {\n throw new Error(`${label} digest ${actual} does not match ${digest}`)\n }\n}\n\nexport async function verifyWorkspaceSnapshotArtifacts(\n snapshot: AgentCandidateWorkspaceSnapshotEvidence,\n port: AgentCandidateArtifactPort,\n): Promise<{ manifest: Uint8Array; archive: Uint8Array }> {\n const [manifest, archive] = await Promise.all([\n readVerifiedArtifact(snapshot.manifest, port),\n readVerifiedArtifact(snapshot.archive, port),\n ])\n const canonicalManifest = canonicalCandidateBytes(snapshot.material)\n if (!Buffer.from(manifest).equals(Buffer.from(canonicalManifest))) {\n throw new Error('workspace manifest artifact is not the exact canonical manifest material')\n }\n if (sha256Bytes(canonicalManifest) !== snapshot.digest) {\n throw new Error('workspace snapshot digest does not match its canonical manifest material')\n }\n return { manifest, archive }\n}\n\nexport async function verifyMaterializedWorkspace(\n root: string,\n expected: AgentCandidateWorkspaceManifestMaterialV1,\n options: { ignoredProtectedRootEntries?: readonly ('.git' | '.sidecar')[] } = {},\n): Promise<void> {\n const observed = await scanWorkspace(root, new Set(options.ignoredProtectedRootEntries ?? []))\n assertWorkspaceManifest(observed.manifest, expected)\n}\n\n/** Capture exact verified regular-file bytes for fresh isolated materialization. */\nexport async function readMaterializedWorkspaceFiles(\n root: string,\n expected: AgentCandidateWorkspaceManifestMaterialV1,\n options: { ignoredProtectedRootEntries?: readonly ('.git' | '.sidecar')[] } = {},\n): Promise<ReadonlyArray<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }>> {\n const observed = await scanWorkspace(root, new Set(options.ignoredProtectedRootEntries ?? []))\n assertWorkspaceManifest(observed.manifest, expected)\n return observed.files.map((file) =>\n Object.freeze({ path: file.path, mode: file.mode, bytes: Uint8Array.from(file.bytes) }),\n )\n}\n\nfunction assertWorkspaceManifest(\n observed: AgentCandidateWorkspaceManifestMaterialV1,\n expected: AgentCandidateWorkspaceManifestMaterialV1,\n): void {\n if (!Buffer.from(canonicalCandidateBytes(observed)).equals(canonicalCandidateBytes(expected))) {\n throw new Error(\n 'materialized workspace files, modes, or bytes do not match the signed manifest',\n )\n }\n}\n\nexport async function verifyMaterializedProfileWorkspace(\n root: string,\n expected: AgentCandidateProfilePlanMaterialV1,\n): Promise<void> {\n const observed = await scanWorkspace(root, new Set())\n const observedProfile = observed.manifest.files.map(({ path, mode, sha256 }) => ({\n relPath: path,\n mode,\n contentSha256: sha256,\n }))\n if (\n !Buffer.from(canonicalCandidateBytes(observedProfile)).equals(\n canonicalCandidateBytes(expected.files),\n )\n ) {\n throw new Error('profile staging files, modes, or bytes do not match the signed profile plan')\n }\n}\n\nasync function scanWorkspace(\n root: string,\n ignoredProtectedRootEntries: ReadonlySet<string>,\n): Promise<{\n manifest: AgentCandidateWorkspaceManifestMaterialV1\n files: Array<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }>\n}> {\n const absoluteRoot = resolve(root)\n const rootStats = await lstat(absoluteRoot)\n if (!rootStats.isDirectory() || rootStats.isSymbolicLink()) {\n throw new Error('workspace root must be a real directory')\n }\n if ((await realpath(absoluteRoot)) !== absoluteRoot) {\n throw new Error('workspace root has a symlinked path component')\n }\n const files: AgentCandidateWorkspaceManifestMaterialV1['files'] = []\n const capturedFiles: Array<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }> = []\n\n async function visit(directory: string): Promise<void> {\n const entries = await readdir(directory, { withFileTypes: true })\n entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n for (const entry of entries) {\n if (directory === absoluteRoot && ignoredProtectedRootEntries.has(entry.name)) {\n continue\n }\n const absolute = resolve(directory, entry.name)\n const relPath = relative(absoluteRoot, absolute).split(sep).join('/')\n if (!relPath || relPath.startsWith('../') || relPath.includes('/../')) {\n throw new Error(`workspace entry escapes root: ${relPath}`)\n }\n const stats = await lstat(absolute)\n if (stats.isSymbolicLink()) {\n throw new Error(`workspace contains a symlink: ${relPath}`)\n }\n if (stats.isDirectory()) {\n await visit(absolute)\n continue\n }\n if (!stats.isFile()) {\n throw new Error(`workspace contains a non-regular entry: ${relPath}`)\n }\n const descriptor = await open(\n absolute,\n fsConstants.O_RDONLY |\n (typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0),\n )\n try {\n const openedStats = await descriptor.stat()\n if (!openedStats.isFile()) {\n throw new Error(`workspace contains a non-regular entry: ${relPath}`)\n }\n if (openedStats.nlink !== 1) {\n throw new Error(`workspace contains a hard-linked file: ${relPath}`)\n }\n const mode = openedStats.mode & 0o777\n if (mode !== 0o644 && mode !== 0o755) {\n throw new Error(`workspace file has unsupported mode ${mode.toString(8)}: ${relPath}`)\n }\n const bytes = await descriptor.readFile()\n const supportedMode = mode as 0o644 | 0o755\n files.push({\n path: relPath,\n mode: supportedMode,\n sha256: sha256Bytes(bytes),\n byteLength: bytes.byteLength,\n })\n capturedFiles.push({ path: relPath, mode: supportedMode, bytes: Uint8Array.from(bytes) })\n } finally {\n await descriptor.close()\n }\n }\n }\n\n await visit(absoluteRoot)\n files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))\n capturedFiles.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))\n return {\n manifest: {\n schemaVersion: 1,\n kind: 'agent-candidate-workspace-manifest',\n files,\n },\n files: capturedFiles,\n }\n}\n","import { spawn } from 'node:child_process'\nimport { mkdir, mkdtemp, readFile, realpath, rm, stat } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join, resolve } from 'node:path'\n\nimport type {\n AgentCandidateCode,\n AgentCandidateGitHubRepository,\n AgentCandidateGitHubResource,\n AgentCandidateWorkspaceManifestMaterialV1,\n} from '@tangle-network/agent-interface'\n\nimport { verifyBytes } from './artifacts'\nimport { canonicalCandidateBytes, sha256Bytes } from './digest'\nimport type { AgentCandidateRepositoryPort } from './types'\n\ninterface GitResult {\n stdout: Buffer\n stderr: Buffer\n}\n\nexport async function verifyCandidateCode(\n code: AgentCandidateCode,\n repositories: AgentCandidateRepositoryPort,\n patchBytes?: Uint8Array,\n): Promise<string | undefined> {\n if (code.kind === 'disabled') return undefined\n const repositoryRoot = await verifiedRepositoryRoot(code.repository, repositories)\n await assertCommitAndBaseTree(repositoryRoot, code.baseCommit, code.baseTree)\n\n if (code.kind === 'no-op') {\n await assertSafeTree(repositoryRoot, code.baseTree)\n return code.baseTree\n }\n if (!patchBytes) throw new Error('git-patch candidate is missing verified patch bytes')\n\n const temporary = await mkdtemp(join(tmpdir(), 'agent-candidate-git-'))\n try {\n const indexFile = join(temporary, 'index')\n await git(repositoryRoot, ['read-tree', code.baseTree], undefined, {\n GIT_INDEX_FILE: indexFile,\n })\n await git(\n repositoryRoot,\n ['apply', '--cached', '--binary', '--whitespace=nowarn', '-'],\n patchBytes,\n { GIT_INDEX_FILE: indexFile },\n )\n const candidateTree = (\n await git(repositoryRoot, ['write-tree'], undefined, { GIT_INDEX_FILE: indexFile })\n ).stdout\n .toString('utf8')\n .trim()\n if (candidateTree !== code.candidateTree) {\n throw new Error(\n `git patch materialized tree ${candidateTree} does not match ${code.candidateTree}`,\n )\n }\n await assertSafeTree(repositoryRoot, candidateTree)\n return candidateTree\n } finally {\n await rm(temporary, { recursive: true, force: true })\n }\n}\n\nexport async function readCandidateGitHubResource(\n resource: AgentCandidateGitHubResource,\n repositories: AgentCandidateRepositoryPort,\n): Promise<Uint8Array> {\n const repositoryRoot = await verifiedRepositoryRoot(resource.repository, repositories)\n const commitType = (await git(repositoryRoot, ['cat-file', '-t', resource.commit])).stdout\n .toString('utf8')\n .trim()\n if (commitType !== 'commit') {\n throw new Error(`GitHub resource commit is not a commit object: ${resource.commit}`)\n }\n const listing = (\n await git(repositoryRoot, ['ls-tree', '-z', resource.commit, '--', resource.path])\n ).stdout\n const entries = parseTreeEntries(listing)\n if (entries.length !== 1 || entries[0]?.path !== resource.path) {\n throw new Error(`GitHub resource path is not one exact file: ${resource.path}`)\n }\n const entry = entries[0]\n if (!entry || entry.type !== 'blob' || (entry.mode !== '100644' && entry.mode !== '100755')) {\n throw new Error(`GitHub resource path is not a regular Git blob: ${resource.path}`)\n }\n const bytes = (await git(repositoryRoot, ['cat-file', 'blob', entry.object])).stdout\n verifyBytes(bytes, resource.sha256, resource.byteLength, `GitHub resource ${resource.path}`)\n return Uint8Array.from(bytes)\n}\n\nexport async function verifyTaskCheckout(\n taskRoot: string,\n expected: { baseCommit: string; baseTree: string },\n): Promise<void> {\n const root = resolve(taskRoot)\n const head = (await git(root, ['rev-parse', 'HEAD'])).stdout.toString('utf8').trim()\n if (head !== expected.baseCommit) {\n throw new Error(`task checkout HEAD ${head} does not match ${expected.baseCommit}`)\n }\n const tree = (await git(root, ['rev-parse', 'HEAD^{tree}'])).stdout.toString('utf8').trim()\n if (tree !== expected.baseTree) {\n throw new Error(`task checkout base tree ${tree} does not match ${expected.baseTree}`)\n }\n}\n\n/**\n * Apply an evaluator-captured binary diff in a detached object database and\n * prove its result tree exactly matches the captured after-state manifest.\n */\nexport async function verifyTaskOutcomePatch(input: {\n repositoryRoot: string\n baseCommit: string\n baseTree: string\n resultTree: string\n patch: Uint8Array\n afterState: AgentCandidateWorkspaceManifestMaterialV1\n}): Promise<{ resultTree: string; resultCommit: string }> {\n const repositoryRoot = resolve(input.repositoryRoot)\n await verifyTaskCheckout(repositoryRoot, input)\n const gitDir = resolve(\n (await git(repositoryRoot, ['rev-parse', '--absolute-git-dir'])).stdout.toString('utf8').trim(),\n )\n if ((await realpath(gitDir)) !== gitDir || gitDir.includes(':')) {\n throw new Error('task Git object store has an unsupported path')\n }\n await assertNoGitIndirection(repositoryRoot, gitDir, 'task repository')\n\n const temporary = await mkdtemp(join(tmpdir(), 'agent-candidate-task-outcome-'))\n try {\n const objectDirectory = join(temporary, 'objects')\n const indexFile = join(temporary, 'index')\n await mkdir(objectDirectory)\n const gitEnvironment = {\n GIT_INDEX_FILE: indexFile,\n GIT_OBJECT_DIRECTORY: objectDirectory,\n GIT_ALTERNATE_OBJECT_DIRECTORIES: join(gitDir, 'objects'),\n }\n await git(repositoryRoot, ['read-tree', input.baseTree], undefined, gitEnvironment)\n if (input.patch.byteLength > 0) {\n await git(\n repositoryRoot,\n ['apply', '--cached', '--binary', '--whitespace=nowarn', '-'],\n input.patch,\n gitEnvironment,\n )\n }\n const resultTree = (await git(repositoryRoot, ['write-tree'], undefined, gitEnvironment)).stdout\n .toString('utf8')\n .trim()\n if (resultTree !== input.resultTree) {\n throw new Error(\n `task outcome patch materialized tree ${resultTree} does not match ${input.resultTree}`,\n )\n }\n await assertSafeTree(repositoryRoot, resultTree, gitEnvironment)\n const observed = await workspaceManifestFromGitTree(repositoryRoot, resultTree, gitEnvironment)\n if (\n !Buffer.from(canonicalCandidateBytes(observed)).equals(\n Buffer.from(canonicalCandidateBytes(input.afterState)),\n )\n ) {\n throw new Error('task outcome after-state does not match the materialized result tree')\n }\n const resultCommit = (\n await git(\n repositoryRoot,\n ['commit-tree', resultTree, '-p', input.baseCommit],\n Buffer.from('candidate task outcome\\n', 'utf8'),\n {\n ...gitEnvironment,\n GIT_AUTHOR_NAME: 'Tangle Evaluator',\n GIT_AUTHOR_EMAIL: 'evaluator@tangle.tools',\n GIT_AUTHOR_DATE: '2000-01-01T00:00:00Z',\n GIT_COMMITTER_NAME: 'Tangle Evaluator',\n GIT_COMMITTER_EMAIL: 'evaluator@tangle.tools',\n GIT_COMMITTER_DATE: '2000-01-01T00:00:00Z',\n },\n )\n ).stdout\n .toString('utf8')\n .trim()\n const committedTree = (\n await git(repositoryRoot, ['rev-parse', `${resultCommit}^{tree}`], undefined, gitEnvironment)\n ).stdout\n .toString('utf8')\n .trim()\n if (committedTree !== resultTree) {\n throw new Error('task outcome evaluator commit does not bind the verified result tree')\n }\n return { resultTree, resultCommit }\n } finally {\n await rm(temporary, { recursive: true, force: true })\n }\n}\n\nasync function verifiedRepositoryRoot(\n repository: AgentCandidateGitHubRepository,\n repositories: AgentCandidateRepositoryPort,\n): Promise<string> {\n const repositoryRoot = resolve(await repositories.resolve(repository))\n const rootStats = await stat(repositoryRoot)\n if (!rootStats.isDirectory()) throw new Error('candidate repository path is not a directory')\n\n const origin = (await git(repositoryRoot, ['remote', 'get-url', 'origin'])).stdout\n .toString('utf8')\n .trim()\n const actual = parseGitHubRemote(origin)\n if (!actual || actual.owner !== repository.owner || actual.repo !== repository.repo) {\n throw new Error(\n `local repository origin ${origin || '<missing>'} does not match github.com/${repository.owner}/${repository.repo}`,\n )\n }\n\n const gitDirText = (await git(repositoryRoot, ['rev-parse', '--absolute-git-dir'])).stdout\n .toString('utf8')\n .trim()\n const gitDir = resolve(gitDirText)\n await assertNoGitIndirection(repositoryRoot, gitDir, 'candidate repository')\n return repositoryRoot\n}\n\nasync function assertNoGitIndirection(\n repositoryRoot: string,\n gitDir: string,\n label: string,\n): Promise<void> {\n const replacements = (\n await git(repositoryRoot, ['for-each-ref', '--format=%(refname)', 'refs/replace'])\n ).stdout\n .toString('utf8')\n .trim()\n if (replacements) throw new Error(`${label} contains Git replace refs`)\n for (const name of ['alternates', 'http-alternates']) {\n const path = join(gitDir, 'objects', 'info', name)\n try {\n const contents = await readFile(path, 'utf8')\n if (contents.trim()) throw new Error(`${label} uses forbidden Git ${name}`)\n } catch (error) {\n if (!isNoEntry(error)) throw error\n }\n }\n}\n\nasync function assertCommitAndBaseTree(\n repositoryRoot: string,\n commit: string,\n expectedTree: string,\n): Promise<void> {\n const type = (await git(repositoryRoot, ['cat-file', '-t', commit])).stdout\n .toString('utf8')\n .trim()\n if (type !== 'commit') throw new Error(`candidate base object is not a commit: ${commit}`)\n const actualTree = (await git(repositoryRoot, ['rev-parse', `${commit}^{tree}`])).stdout\n .toString('utf8')\n .trim()\n if (actualTree !== expectedTree) {\n throw new Error(`candidate base commit tree ${actualTree} does not match ${expectedTree}`)\n }\n}\n\nasync function assertSafeTree(\n repositoryRoot: string,\n tree: string,\n environment: Record<string, string> = {},\n): Promise<void> {\n const listing = (\n await git(repositoryRoot, ['ls-tree', '-rz', '--full-tree', tree], undefined, environment)\n ).stdout\n const entries = parseTreeEntries(listing)\n if (entries.length === 0) throw new Error('candidate Git tree cannot be empty')\n for (const entry of entries) {\n if (entry.type !== 'blob' || (entry.mode !== '100644' && entry.mode !== '100755')) {\n throw new Error(\n `candidate Git tree contains a symlink, submodule, or non-blob: ${entry.path}`,\n )\n }\n assertSafeGitPath(entry.path)\n }\n}\n\nasync function workspaceManifestFromGitTree(\n repositoryRoot: string,\n tree: string,\n environment: Record<string, string>,\n): Promise<AgentCandidateWorkspaceManifestMaterialV1> {\n const listing = (\n await git(repositoryRoot, ['ls-tree', '-rz', '--full-tree', tree], undefined, environment)\n ).stdout\n const entries = parseTreeEntries(listing)\n const files = await Promise.all(\n entries.map(async (entry) => {\n if (entry.type !== 'blob' || (entry.mode !== '100644' && entry.mode !== '100755')) {\n throw new Error(`task outcome tree contains a non-regular file: ${entry.path}`)\n }\n const bytes = (\n await git(repositoryRoot, ['cat-file', 'blob', entry.object], undefined, environment)\n ).stdout\n return {\n path: entry.path,\n mode: entry.mode === '100755' ? (0o755 as const) : (0o644 as const),\n sha256: sha256Bytes(bytes),\n byteLength: bytes.byteLength,\n }\n }),\n )\n files.sort((left, right) => left.path.localeCompare(right.path))\n return {\n schemaVersion: 1,\n kind: 'agent-candidate-workspace-manifest',\n files,\n }\n}\n\nfunction parseTreeEntries(bytes: Uint8Array): Array<{\n mode: string\n type: string\n object: string\n path: string\n}> {\n const raw = Buffer.from(bytes)\n const decoded = raw.toString('utf8')\n if (!Buffer.from(decoded, 'utf8').equals(raw)) {\n throw new Error('candidate Git tree contains a non-UTF-8 path')\n }\n const rows = decoded.split('\\0').filter(Boolean)\n return rows.map((row) => {\n const tab = row.indexOf('\\t')\n const header = row.slice(0, tab).split(' ')\n const path = row.slice(tab + 1)\n const [mode, type, object] = header\n if (tab < 1 || !mode || !type || !object || !path) {\n throw new Error('malformed Git tree entry')\n }\n return { mode, type, object, path }\n })\n}\n\nfunction assertSafeGitPath(path: string): void {\n if (\n !path ||\n path.startsWith('/') ||\n path.includes('\\\\') ||\n path.includes('\\0') ||\n hasControlCharacter(path) ||\n path.split('/').some((part) => !part || part === '.' || part === '..') ||\n path.split('/')[0]?.toLowerCase() === '.git'\n ) {\n throw new Error(`candidate Git tree contains an unsafe path: ${path}`)\n }\n}\n\nfunction 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 parseGitHubRemote(value: string): { owner: string; repo: string } | undefined {\n const match = value.match(\n /^(?:https?:\\/\\/github\\.com\\/|ssh:\\/\\/git@github\\.com\\/|git@github\\.com:)([^/]+)\\/([^/]+?)(?:\\.git)?$/,\n )\n if (!match?.[1] || !match[2]) return undefined\n return { owner: match[1], repo: match[2] }\n}\n\nasync function git(\n repositoryRoot: string,\n args: string[],\n input?: Uint8Array,\n extraEnv: Record<string, string> = {},\n): Promise<GitResult> {\n const env = Object.fromEntries(\n Object.entries(process.env).filter(([name]) => !name.startsWith('GIT_')),\n ) as Record<string, string>\n Object.assign(env, {\n GIT_CONFIG_NOSYSTEM: '1',\n GIT_CONFIG_GLOBAL: '/dev/null',\n GIT_CONFIG_SYSTEM: '/dev/null',\n GIT_TERMINAL_PROMPT: '0',\n GIT_NO_REPLACE_OBJECTS: '1',\n LC_ALL: 'C',\n ...extraEnv,\n })\n const fullArgs = [\n '-c',\n 'core.hooksPath=/dev/null',\n '-c',\n 'protocol.file.allow=never',\n '-C',\n repositoryRoot,\n ...args,\n ]\n return await new Promise((resolveResult, reject) => {\n const child = spawn('git', fullArgs, { env, stdio: ['pipe', 'pipe', 'pipe'] })\n const stdout: Buffer[] = []\n const stderr: Buffer[] = []\n child.stdout.on('data', (chunk: Buffer) => stdout.push(chunk))\n child.stderr.on('data', (chunk: Buffer) => stderr.push(chunk))\n child.on('error', reject)\n child.on('close', (code, signal) => {\n const out = Buffer.concat(stdout)\n const err = Buffer.concat(stderr)\n if (code !== 0) {\n reject(\n new Error(\n `git ${args[0] ?? '<command>'} failed (${signal ?? code}): ${err.toString('utf8').trim()}`,\n ),\n )\n return\n }\n resolveResult({ stdout: out, stderr: err })\n })\n if (input) child.stdin.end(input)\n else child.stdin.end()\n })\n}\n\nfunction isNoEntry(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: string }).code === 'ENOENT'\n )\n}\n","import type { 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): AgentCandidateExecutionClaim {\n const state = assertPreparedCandidateIntegrity(prepared)\n const material = prepared.executionPlan.value.material\n const attempt = material.attempt\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 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 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 attempt: { ...material.attempt, number: 0 },\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 AgentCandidateArtifactRef,\n agentCandidateArtifactRefSchema,\n} from '@tangle-network/agent-interface'\n\nimport { verifyBytes } from './artifacts'\nimport { immutableCandidateValue, sha256Bytes } from './digest'\nimport type { AgentCandidateOutputArtifactPort, AgentCandidateOutputPurpose } from './types'\n\n/** Persist evaluator evidence, read it back, and bind the returned locator to the exact bytes. */\nexport async function persistCandidateOutputArtifact(\n port: AgentCandidateOutputArtifactPort,\n input: {\n executionId: string\n purpose: AgentCandidateOutputPurpose\n bytes: Uint8Array\n signal?: AbortSignal\n },\n): Promise<AgentCandidateArtifactRef> {\n input.signal?.throwIfAborted()\n const bytes = Uint8Array.from(input.bytes)\n const expectedDigest = sha256Bytes(bytes)\n const ref = agentCandidateArtifactRefSchema.parse(\n await port.put({\n executionId: input.executionId,\n purpose: input.purpose,\n bytes: Uint8Array.from(bytes),\n ...(input.signal ? { signal: input.signal } : {}),\n }),\n )\n input.signal?.throwIfAborted()\n if (ref.sha256 !== expectedDigest || ref.byteLength !== bytes.byteLength) {\n throw new Error('candidate output locator does not identify the submitted bytes')\n }\n const stored = await port.read(ref)\n input.signal?.throwIfAborted()\n verifyBytes(stored, expectedDigest, bytes.byteLength, 'persisted candidate output')\n return immutableCandidateValue(ref)\n}\n","import {\n agentCandidateTerminationSchema,\n agentCandidateWorkspaceManifestMaterialSchema,\n} from '@tangle-network/agent-interface'\nimport { assertExactObjectKeys as assertExactKeys } from './exact-object'\nimport type { AgentCandidateExecutorFinalCapture, AgentCandidateProtectedRunCapture } from './types'\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): AgentCandidateExecutorFinalCapture {\n const capture = requireRecord(value, 'candidate final capture')\n assertExactKeys(capture, ['stopped'], 'candidate final capture', ['taskOutcome', 'memoryAfter'])\n if (capture.stopped !== true) {\n throw new Error('candidate final capture does not prove process death')\n }\n\n const taskOutcome = capture.taskOutcome ? sealTaskOutcomeCapture(capture.taskOutcome) : undefined\n const memoryAfter = capture.memoryAfter ? sealMemoryCapture(capture.memoryAfter) : undefined\n return Object.freeze({\n stopped: true,\n ...(taskOutcome ? { taskOutcome } : {}),\n ...(memoryAfter ? { memoryAfter: Object.freeze(memoryAfter) } : {}),\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): NonNullable<AgentCandidateExecutorFinalCapture['taskOutcome']> {\n const capture = requireRecord(value, 'candidate task capture')\n assertExactKeys(\n capture,\n ['resultTree', 'afterState', 'archive', 'gitDiff'],\n 'candidate task capture',\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 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 { mkdtemp, rm } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\n\nimport type { Span, TraceStore } from '@tangle-network/agent-eval'\nimport { isLlmSpan, REDACTION_VERSION } from '@tangle-network/agent-eval'\nimport type {\n AgentCandidateBenchmarkResultEvidence,\n AgentCandidateMemoryReceipt,\n AgentCandidateModelSettlementEvidence,\n AgentCandidateRunReceiptV2,\n AgentCandidateSpend,\n AgentCandidateTermination,\n} from '@tangle-network/agent-interface'\nimport {\n agentCandidateRunReceiptV2Schema,\n agentCandidateWorkspaceSnapshotEvidenceSchema,\n} from '@tangle-network/agent-interface'\n\nimport { readMaterializedWorkspaceFiles } from './artifacts'\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDocument,\n embeddedCandidateArtifact,\n sha256Bytes,\n} from './digest'\nimport {\n sealAgentCandidateExecutorFinalCapture,\n sealAgentCandidateProtectedRunCapture,\n} from './executor-capture'\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 redactProtectedReason,\n redactProtectedValue,\n} from './protected-redaction'\nimport {\n type AgentCandidateExecutorFinalCapture,\n type AgentCandidateOutputArtifactPort,\n type AgentCandidateProtectedRunCapture,\n type AgentCandidateRunFinalization,\n CANDIDATE_TRACE_TAGS,\n type VerifiedAgentCandidateTaskOutcome,\n} from './types'\n\ninterface CandidateFinalizationEvidence {\n finalCapture: AgentCandidateExecutorFinalCapture\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 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 const protectedCapture = sealAgentCandidateProtectedRunCapture(capture)\n if (protectedCapture.executionId !== state.executionId) {\n throw new Error('protected capture execution id does not match the prepared execution')\n }\n termination = protectedCapture.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(state.trace.runId)\n if (!run) throw new Error(`protected trace run is missing: ${state.trace.runId}`)\n if (run.status === 'running' || run.endedAt === undefined) {\n throw new Error('protected trace run is not terminal')\n }\n assertTraceBindings(run.tags, state)\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 usage = settlement.usage\n enforceLimits(state, run.startedAt, run.endedAt, orderedSpans, settlement)\n const finalCapture = sealAgentCandidateExecutorFinalCapture(evidence.finalCapture)\n const memory = await memoryReceipt(\n state,\n finalCapture,\n evidence.outputArtifacts,\n protectedValues,\n signal,\n )\n\n const redacted = redactProtectedValue(\n {\n schemaVersion: 1,\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 schemaVersion: 1 as const,\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<AgentCandidateRunReceiptV2>({\n schemaVersion: 2,\n kind: 'agent-candidate-run',\n digestAlgorithm: 'rfc8785-sha256',\n bundleDigest: state.bundle.digest,\n materializationReceiptDigest: state.materializationReceipt.digest,\n executionPlanDigest: state.executionPlan.value.digest,\n memory,\n usage,\n modelUsage: { resolved: state.resolvedModel, usage },\n trace,\n termination,\n fixedUsage: settlement.fixedUsage,\n modelSettlement: evidence.modelSettlement,\n taskOutcome: evidence.taskOutcome.evidence,\n benchmarkResult: evidence.benchmarkResult,\n })\n agentCandidateRunReceiptV2Schema.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 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 state: PreparedCandidateState,\n): void {\n const expected = state.trace.tags\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): void {\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 (settlement.costUsdNanos > usdToNanos(limits.maxCostUsd, 'frozen maxCostUsd')) {\n throw new Error(`protected cost USD ${usage.costUsd} exceeds ${limits.maxCostUsd}`)\n }\n}\n\nasync function memoryReceipt(\n state: PreparedCandidateState,\n capture: AgentCandidateExecutorFinalCapture,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n protectedValues: readonly string[],\n signal?: AbortSignal,\n): Promise<AgentCandidateMemoryReceipt> {\n signal?.throwIfAborted()\n if (state.memory.mode === 'disabled') {\n if (capture.memoryAfter !== 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 const afterState = capture.memoryAfter.afterState\n const archive = Uint8Array.from(capture.memoryAfter.archive)\n if (archive.byteLength === 0) throw new Error('isolated memory archive cannot be empty')\n const manifestBytes = canonicalCandidateBytes(afterState)\n assertNoProtectedBytes(manifestBytes, protectedValues)\n assertNoProtectedBytes(archive, protectedValues)\n const provisionalSnapshot = agentCandidateWorkspaceSnapshotEvidenceSchema.parse({\n schemaVersion: 1,\n kind: 'agent-candidate-workspace-snapshot',\n digest: sha256Bytes(manifestBytes),\n material: afterState,\n manifest: embeddedCandidateArtifact(manifestBytes),\n archive: embeddedCandidateArtifact(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: provisionalSnapshot,\n archive: Uint8Array.from(archive),\n destination: root,\n })\n const files = await readMaterializedWorkspaceFiles(root, 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 const [manifest, archiveRef] = await Promise.all([\n persistCandidateOutputArtifact(outputArtifacts, {\n executionId: state.executionId,\n purpose: 'memory-after-manifest',\n bytes: manifestBytes,\n signal,\n }),\n persistCandidateOutputArtifact(outputArtifacts, {\n executionId: state.executionId,\n purpose: 'memory-after-archive',\n bytes: archive,\n signal,\n }),\n ])\n const snapshot = agentCandidateWorkspaceSnapshotEvidenceSchema.parse({\n schemaVersion: 1,\n kind: 'agent-candidate-workspace-snapshot',\n digest: sha256Bytes(manifestBytes),\n material: afterState,\n manifest,\n archive: archiveRef,\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: AgentCandidateSpend | 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 { isLlmSpan, type LlmSpan, type TraceStore } from '@tangle-network/agent-eval'\nimport type { AgentCandidateSpend } from '@tangle-network/agent-interface'\nimport type { AgentCandidateExecutionUsage } from './claim'\nimport { assertExactObjectKeys } from './exact-object'\nimport type {\n AgentCandidateProtectedModelCall,\n AgentCandidateProtectedModelSettlement,\n} from './types'\n\nconst USD_NANOS = 1_000_000_000\n\nexport interface SealedAgentCandidateModelSettlement {\n readonly value: AgentCandidateProtectedModelSettlement\n readonly usage: AgentCandidateSpend\n readonly fixedUsage: AgentCandidateExecutionUsage\n readonly costUsdNanos: number\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', 'calls'],\n 'model settlement',\n )\n if (settlement.closed !== true) throw new Error('protected model grant is not closed')\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 inputTokens = 0\n let outputTokens = 0\n let cachedInputTokens = 0\n let reasoningTokens = 0\n let hasCachedInput = false\n let costUsdNanos = 0\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 'outputTokens',\n 'cachedInputTokens',\n 'reasoningTokens',\n 'costUsdNanos',\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.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 hasCachedInput = true\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 inputTokens = safeAdd(inputTokens, source.inputTokens, 'input token total')\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 costUsd: costUsdNanos / USD_NANOS,\n inputTokens,\n outputTokens,\n ...(hasCachedInput ? { cachedInputTokens } : {}),\n modelCalls: calls.length,\n })\n const fixedUsage = Object.freeze({\n costUsdNanos,\n inputTokens,\n outputTokens,\n cachedInputTokens,\n reasoningTokens,\n modelCalls: calls.length,\n })\n return Object.freeze({\n value: Object.freeze({\n preparationId: settlement.preparationId,\n grantDigest: settlement.grantDigest,\n closed: true as const,\n calls: Object.freeze(calls),\n }),\n usage,\n fixedUsage,\n costUsdNanos,\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: AgentCandidateProtectedModelCall): 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 {\n DEFAULT_REDACTION_RULES,\n REDACTION_VERSION,\n type RedactionRule,\n redactString,\n} from '@tangle-network/agent-eval'\n\nexport interface ProtectedRedactionReport {\n version: string\n redactionCount: number\n byRule: Record<string, number>\n}\n\n/** Redact protected values at the first persistence boundary, including object keys and bytes. */\nexport function redactProtectedValue<T>(\n value: T,\n protectedValues: readonly string[],\n): { value: T; report: ProtectedRedactionReport } {\n const report: ProtectedRedactionReport = {\n version: REDACTION_VERSION,\n redactionCount: 0,\n byRule: {},\n }\n const rules = protectedRedactionRules(protectedValues)\n const redacted = redactNode(value, protectedValues, rules, report) as T\n assertNoProtectedEvidence(redacted, protectedValues)\n return { value: redacted, report }\n}\n\nexport function redactProtectedReason(reason: string, protectedValues: readonly string[]): string {\n try {\n return redactProtectedValue(reason, protectedValues).value\n } catch {\n return 'candidate execution failed with a protected error'\n }\n}\n\nexport function assertNoProtectedEvidence(\n value: unknown,\n protectedValues: readonly string[],\n): void {\n if (value instanceof Uint8Array) {\n assertNoProtectedBytes(value, protectedValues)\n return\n }\n if (typeof value === 'string') {\n for (const protectedValue of protectedValueVariants(protectedValues)) {\n if (value.includes(protectedValue)) {\n throw new Error('protected value survived candidate evidence redaction')\n }\n }\n if (decodedBase64ContainsProtectedValue(value, protectedValues)) {\n throw new Error('base64 protected value survived candidate evidence redaction')\n }\n return\n }\n if (Array.isArray(value)) {\n for (const entry of value) assertNoProtectedEvidence(entry, protectedValues)\n return\n }\n if (value && typeof value === 'object') {\n for (const [key, entry] of Object.entries(value)) {\n assertNoProtectedEvidence(key, protectedValues)\n assertNoProtectedEvidence(entry, protectedValues)\n }\n }\n}\n\nexport function assertNoProtectedBytes(\n bytes: Uint8Array,\n protectedValues: readonly string[],\n): void {\n if (containsProtectedBytes(bytes, protectedValues)) {\n throw new Error('protected value survived candidate evidence byte redaction')\n }\n}\n\nfunction redactNode(\n value: unknown,\n protectedValues: readonly string[],\n rules: readonly RedactionRule[],\n report: ProtectedRedactionReport,\n): unknown {\n if (value instanceof Uint8Array) {\n if (containsProtectedBytes(value, protectedValues)) {\n recordRedaction(report, 'candidate-access-binary', 1)\n return Uint8Array.from(Buffer.from('[redacted:candidate-access-binary]', 'utf8'))\n }\n return Uint8Array.from(value)\n }\n if (typeof value === 'string') {\n if (decodedBase64ContainsProtectedValue(value, protectedValues)) {\n recordRedaction(report, 'candidate-access-binary', 1)\n return '[redacted:candidate-access-binary]'\n }\n const redacted = redactString(value, [...rules])\n for (const [rule, count] of Object.entries(redacted.report.byRule)) {\n recordRedaction(report, rule, count)\n }\n return redacted.output\n }\n if (Array.isArray(value)) {\n return value.map((entry) => redactNode(entry, protectedValues, rules, report))\n }\n if (value && typeof value === 'object') {\n const entries: Array<[string, unknown]> = []\n const seenKeys = new Set<string>()\n for (const [key, entry] of Object.entries(value)) {\n const redactedKey = redactNode(key, protectedValues, rules, report)\n if (typeof redactedKey !== 'string' || seenKeys.has(redactedKey)) {\n throw new Error('protected evidence redaction produced an ambiguous object key')\n }\n seenKeys.add(redactedKey)\n entries.push([redactedKey, redactNode(entry, protectedValues, rules, report)])\n }\n return Object.fromEntries(entries)\n }\n return value\n}\n\nfunction protectedRedactionRules(protectedValues: readonly string[]): RedactionRule[] {\n const exactRules = protectedValueVariants(protectedValues)\n .sort((left, right) => right.length - left.length || left.localeCompare(right))\n .map((value, index) => ({\n id: `candidate-access-${index}`,\n pattern: new RegExp(escapeRegularExpression(value), 'g'),\n replacement: '[redacted:candidate-access]',\n }))\n return [...exactRules, ...DEFAULT_REDACTION_RULES]\n}\n\nfunction recordRedaction(report: ProtectedRedactionReport, rule: string, count: number): void {\n if (count <= 0) return\n report.redactionCount += count\n report.byRule[rule] = (report.byRule[rule] ?? 0) + count\n}\n\nfunction containsProtectedBytes(bytes: Uint8Array, protectedValues: readonly string[]): boolean {\n const source = Buffer.from(bytes)\n return protectedValueVariants(protectedValues).some((value) =>\n source.includes(Buffer.from(value, 'utf8')),\n )\n}\n\nfunction decodedBase64ContainsProtectedValue(\n value: string,\n protectedValues: readonly string[],\n): boolean {\n if (value.length < 4 || value.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value)) {\n return false\n }\n try {\n return containsProtectedBytes(Buffer.from(value, 'base64'), protectedValues)\n } catch {\n return false\n }\n}\n\nfunction protectedValueVariants(protectedValues: readonly string[]): string[] {\n const variants = new Set<string>()\n for (const value of normalizedProtectedValues(protectedValues)) {\n variants.add(value)\n variants.add(Buffer.from(value, 'utf8').toString('base64'))\n variants.add(Buffer.from(value, 'utf8').toString('base64url'))\n variants.add(encodeURIComponent(value))\n }\n return [...variants]\n}\n\nfunction normalizedProtectedValues(values: readonly string[]): string[] {\n return [...new Set(values.filter((value) => value.length > 0))]\n}\n\nfunction escapeRegularExpression(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\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 AgentCandidateTermination,\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 { 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 V2 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 schemaVersion: 2 as const,\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 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 outputTokens: call.outputTokens,\n cachedInputTokens: call.cachedInputTokens ?? 0,\n reasoningTokens: call.reasoningTokens ?? 0,\n costUsdNanos: call.costUsdNanos,\n })),\n usage: settlement.fixedUsage,\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 schemaVersion: 1,\n kind: 'agent-candidate-model-settlement',\n digest,\n material,\n artifact,\n }),\n ) as PersistedAgentCandidateModelSettlement\n}\n\n/** Recompute the result tree from the patch, then persist its exact task evidence. */\nexport async function persistVerifiedCandidateTaskOutcome(\n state: PreparedCandidateState,\n capture: AgentCandidateExecutorTaskOutcomeCapture,\n outputArtifacts: AgentCandidateOutputArtifactPort,\n protectedValues: readonly string[],\n signal?: AbortSignal,\n): Promise<VerifiedAgentCandidateTaskOutcome> {\n signal?.throwIfAborted()\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 repository = state.executionPlan.value.material.task.repository\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 schemaVersion: 1,\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 const [manifest, archiveRef, gitDiff] = await Promise.all([\n persistCandidateOutputArtifact(outputArtifacts, {\n executionId: state.executionId,\n purpose: 'task-manifest',\n bytes: manifestBytes,\n signal,\n }),\n persistCandidateOutputArtifact(outputArtifacts, {\n executionId: state.executionId,\n purpose: 'task-archive',\n bytes: archive,\n signal,\n }),\n persistCandidateOutputArtifact(outputArtifacts, {\n executionId: state.executionId,\n purpose: 'task-patch',\n bytes: patch,\n signal,\n }),\n ])\n const snapshot = agentCandidateWorkspaceSnapshotEvidenceSchema.parse({\n schemaVersion: 1,\n kind: 'agent-candidate-workspace-snapshot',\n digest: sha256Bytes(manifestBytes),\n material: afterState,\n manifest,\n archive: archiveRef,\n })\n const material = {\n schemaVersion: 1 as const,\n kind: 'agent-candidate-task-outcome-material' as const,\n executionPlanDigest: state.executionPlan.value.digest,\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: gitDiff,\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 const evidence = immutableCandidateValue(\n agentCandidateTaskOutcomeEvidenceSchema.parse({\n schemaVersion: 1,\n kind: 'agent-candidate-task-outcome',\n digest,\n material,\n artifact,\n }),\n ) as AgentCandidateTaskOutcomeEvidence & { artifact: AgentCandidateArtifactRef }\n const storedPatch = Uint8Array.from(patch)\n return Object.freeze({\n evidence,\n get patch(): Uint8Array {\n return Uint8Array.from(storedPatch)\n },\n [verifiedTaskOutcomeBrand]: true as const,\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 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 task = state.executionPlan.value.material.task\n const material = {\n schemaVersion: 1 as const,\n kind: 'agent-candidate-benchmark-result-material' as const,\n executionPlanDigest: state.executionPlan.value.digest,\n taskOutcomeDigest: outcome.evidence.digest,\n benchmark: {\n name: task.benchmark,\n version: task.benchmarkVersion,\n taskId: task.taskId,\n splitDigest: task.splitDigest,\n },\n grader: {\n name: graded.grader.name,\n version: graded.grader.version,\n artifact: graded.grader.artifact,\n },\n evidence: evidenceRef,\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 schemaVersion: 1,\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: ReturnType<typeof agentCandidateWorkspaceSnapshotEvidenceSchema.parse>,\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\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 { BenchmarkEvaluation } from '@tangle-network/agent-eval'\nimport type {\n AgentCandidateArtifactRef,\n AgentCandidateTermination,\n} from '@tangle-network/agent-interface'\n\nimport { readVerifiedArtifact } from './artifacts'\nimport { immutableCandidateValue, sha256Bytes } from './digest'\nimport type {\n AgentCandidateBenchmarkGraderPort,\n AgentCandidateOutputArtifactPort,\n VerifiedAgentCandidateTaskOutcome,\n} from './types'\n\nexport interface BoundAgentCandidateBenchmarkRun {\n readonly grader: {\n readonly name: string\n readonly version: string\n readonly artifact: AgentCandidateArtifactRef\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 grader: AgentCandidateBenchmarkGraderPort\n artifacts: AgentCandidateOutputArtifactPort\n signal?: AbortSignal\n}): Promise<BoundAgentCandidateBenchmarkRun> {\n input.signal?.throwIfAborted()\n const descriptor = snapshotGraderDescriptor(input.grader)\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 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 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 evaluation: result.evaluation,\n evidence,\n })\n}\n\nfunction snapshotGraderDescriptor(\n grader: AgentCandidateBenchmarkGraderPort,\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 return immutableCandidateValue({\n name: grader.name,\n version: grader.version,\n artifact: grader.artifact,\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 { REDACTION_VERSION, type TraceStore } from '@tangle-network/agent-eval'\n\nimport { type ProtectedRedactionReport, redactProtectedValue } from './protected-redaction'\n\n/** Trace-store proxy that removes live credentials before any write reaches durable storage. */\nexport class ProtectedAgentCandidateTraceStore implements TraceStore {\n private readonly aggregate: ProtectedRedactionReport = {\n version: REDACTION_VERSION,\n redactionCount: 0,\n byRule: {},\n }\n\n constructor(\n private readonly inner: TraceStore,\n private readonly protectedValues: readonly string[],\n ) {}\n\n report(): ProtectedRedactionReport {\n return {\n version: this.aggregate.version,\n redactionCount: this.aggregate.redactionCount,\n byRule: { ...this.aggregate.byRule },\n }\n }\n\n async appendRun(run: Parameters<TraceStore['appendRun']>[0]): Promise<void> {\n await this.inner.appendRun(this.redact(run))\n }\n\n async updateRun(\n runId: Parameters<TraceStore['updateRun']>[0],\n patch: Parameters<TraceStore['updateRun']>[1],\n ): Promise<void> {\n await this.inner.updateRun(this.redact(runId), this.redact(patch))\n }\n\n async appendSpan(span: Parameters<TraceStore['appendSpan']>[0]): Promise<void> {\n if (span.kind === 'llm') {\n throw new Error('candidate executors cannot author protected model spans')\n }\n await this.inner.appendSpan(this.redact(span))\n }\n\n async updateSpan(\n spanId: Parameters<TraceStore['updateSpan']>[0],\n patch: Parameters<TraceStore['updateSpan']>[1],\n ): Promise<void> {\n if (patch.kind === 'llm') {\n throw new Error('candidate executors cannot author protected model spans')\n }\n await this.inner.updateSpan(this.redact(spanId), this.redact(patch))\n }\n\n async appendEvent(event: Parameters<TraceStore['appendEvent']>[0]): Promise<void> {\n await this.inner.appendEvent(this.redact(event))\n }\n\n async appendArtifact(artifact: Parameters<TraceStore['appendArtifact']>[0]): Promise<void> {\n await this.inner.appendArtifact(this.redact(artifact))\n }\n\n async appendBudgetEntry(entry: Parameters<TraceStore['appendBudgetEntry']>[0]): Promise<void> {\n await this.inner.appendBudgetEntry(this.redact(entry))\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 redact<T>(value: T): T {\n const redacted = redactProtectedValue(value, this.protectedValues)\n this.aggregate.version = redacted.report.version\n this.aggregate.redactionCount += redacted.report.redactionCount\n for (const [rule, count] of Object.entries(redacted.report.byRule)) {\n this.aggregate.byRule[rule] = (this.aggregate.byRule[rule] ?? 0) + count\n }\n return redacted.value\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 { AgentCandidateTermination } from '@tangle-network/agent-interface'\n\nimport type {\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 sealAgentCandidateExecutorFinalCapture,\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 persistVerifiedCandidateTaskOutcome,\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 { ProtectedAgentCandidateTraceStore } from './protected-trace-store'\nimport type {\n AgentCandidateBenchmarkGraderPort,\n AgentCandidateExecutorFinalCapture,\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 acquired: Awaited<ReturnType<AgentCandidateExecutionClaimStore['tryClaim']>>\n try {\n acquired = await options.claimStore.tryClaim(candidateExecutionClaim(prepared))\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 protectedTraceStore = new ProtectedAgentCandidateTraceStore(\n options.traceStore,\n protectedValues,\n )\n const execution = await runAndStopExecutor(\n options.executor,\n request,\n protectedTraceStore,\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 [memoryClose, settlementResult] = await Promise.all([\n closeMemoryAccess(state, accessReason, cleanupDeadlineAtMs),\n settleModelGrant(state, accessReason, cleanupDeadlineAtMs),\n ])\n if (!execution.processStopped || !settlementResult.settlement || !memoryClose.closed) {\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 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 state.trace.runId,\n settlementResult.settlement as SealedAgentCandidateModelSettlement,\n )\n const taskOutcome = await persistVerifiedCandidateTaskOutcome(\n state,\n execution.finalCapture.taskOutcome!,\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 settlementResult.settlement as SealedAgentCandidateModelSettlement,\n {\n finalCapture: execution.finalCapture,\n modelSettlement,\n taskOutcome,\n benchmarkResult,\n outputArtifacts: options.outputArtifacts,\n },\n protectedValues,\n protectedTraceStore.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 schemaVersion: 1,\n status: 'succeeded',\n usage: settlementResult.settlement.fixedUsage,\n modelSettlement: result.artifacts.modelSettlement,\n taskOutcome: result.artifacts.taskOutcome,\n benchmarkResult: result.artifacts.benchmarkResult,\n runReceipt: result.artifacts.runReceipt,\n }\n : {\n schemaVersion: 1,\n status: 'failed',\n failureClass,\n usage: settlementResult.settlement.fixedUsage,\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: AgentCandidateExecutorFinalCapture\n processStopped: true\n error?: undefined\n }\n | {\n kind: 'timeout'\n termination: AgentCandidateTermination & { kind: 'timeout' }\n finalCapture: AgentCandidateExecutorFinalCapture\n processStopped: true\n error?: undefined\n }\n | {\n kind: 'error'\n error: unknown\n termination?: AgentCandidateTermination\n finalCapture?: AgentCandidateExecutorFinalCapture\n processStopped: boolean\n }\n\nasync function runAndStopExecutor(\n executor: AgentCandidateExecutorPort,\n request: AgentCandidateExecutorRequest,\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 let stopped: unknown\n try {\n stopped = await withinCandidateCleanupDeadline(\n () =>\n executor.stopAndCapture(\n {\n executionId: request.executionId,\n executionPlanDigest: request.executionPlan.value.digest,\n },\n {\n traceStore,\n reason: stopReason,\n signal: controller.signal,\n deadlineAtMs,\n },\n ),\n Date.now() + cleanupTimeoutMs,\n 'candidate process termination',\n )\n if (\n !stopped ||\n typeof stopped !== 'object' ||\n (stopped as { stopped?: unknown }).stopped !== true\n ) {\n throw new Error('candidate executor did not acknowledge exact process termination')\n }\n } catch (stopError) {\n if (timer) clearTimeout(timer)\n controller.abort(stopError)\n return {\n kind: 'error',\n error: new Error(joinErrors(executionError, stopError)),\n ...(timedOut ? { termination: { kind: 'timeout', timeoutMs } } : {}),\n processStopped: false,\n }\n }\n\n let finalCapture: AgentCandidateExecutorFinalCapture\n try {\n finalCapture = sealAgentCandidateExecutorFinalCapture(stopped)\n } catch (captureError) {\n if (timer) clearTimeout(timer)\n controller.abort(captureError)\n return {\n kind: 'error',\n error: new Error(joinErrors(executionError, captureError)),\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 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 schemaVersion: 1,\n status: 'failed',\n failureClass,\n usage: settled.settlement.fixedUsage,\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 schemaVersion: 1,\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 {\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/** 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\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) await readArtifact(parsed.knowledge.manifest)\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 { randomBytes } from 'node:crypto'\nimport { lstat, readdir } from 'node:fs/promises'\nimport { isAbsolute, posix, relative, resolve as resolveHostPath } from 'node:path'\n\nimport type {\n AgentCandidateConfigValue,\n AgentCandidateEffectiveMemory,\n AgentCandidateExecutionLimits,\n AgentCandidateExecutionPlanEvidence,\n AgentCandidateExecutionPlanMaterialV1,\n AgentCandidateMaterializationReceipt,\n AgentCandidateModelAccessNetwork,\n AgentCandidateResolvedModel,\n HarnessType,\n} from '@tangle-network/agent-interface'\nimport {\n agentCandidateContainerSchema,\n agentCandidateExecutionLimitsSchema,\n agentCandidateExecutionPlanEvidenceSchema,\n agentCandidateExecutionPlanMaterialSchema,\n agentCandidateMaterializationReceiptSchema,\n agentCandidateModelAccessNetworkSchema,\n agentCandidateWorkspaceSnapshotEvidenceSchema,\n sha256DigestSchema,\n} from '@tangle-network/agent-interface'\nimport {\n applyAgentCandidateWorkspacePlan,\n type HarnessId,\n materializeCandidateProfile,\n} from '@tangle-network/agent-profile-materialize'\n\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 sha256Bytes,\n} from './digest'\nimport { candidateExecutionOwnerWindowMs } from './execution-window'\nimport { verifyTaskCheckout } from './git-materialize'\nimport { sealAgentCandidateModelSettlement, usdToNanos } from './model-settlement'\nimport { createPreparedCandidateExecution } from './prepared-state'\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 MATERIALIZER_HARNESSES = new Set<HarnessType>([\n 'claude-code',\n 'claude',\n 'claudish',\n 'nanoclaw',\n 'codex',\n 'opencode',\n 'kimi-code',\n 'kimi',\n 'pi',\n 'gemini',\n 'hermes',\n 'openclaw',\n])\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 const harness = materializerHarness(bundle.execution.harness)\n assertTaskInput(task, bundle.execution.instructionDelivery)\n const resultTimeoutMs = candidateResultTimeout(options.resultTimeoutMs, task.limits.timeoutMs)\n const ownerWindowMs = candidateExecutionOwnerWindowMs(\n task.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(task.instruction, 'utf8')\n const instructionDigest = sha256Bytes(instructionBytes)\n\n const taskArtifacts = await verifyWorkspaceSnapshotArtifacts(task.workspace, ports.artifacts)\n await ports.workspaces.materialize({\n role: 'task',\n snapshot: task.workspace,\n archive: taskArtifacts.archive,\n destination: task.stagingRoots.taskRoot,\n })\n await verifyMaterializedWorkspace(task.stagingRoots.taskRoot, task.workspace.material, {\n ignoredProtectedRootEntries: ['.git', '.sidecar'],\n })\n await verifyTaskCheckout(task.stagingRoots.taskRoot, task.repository)\n const taskExecutorFiles = await readMaterializedWorkspaceFiles(\n task.stagingRoots.taskRoot,\n task.workspace.material,\n { ignoredProtectedRootEntries: ['.git', '.sidecar'] },\n )\n\n let candidateArchive: Uint8Array | undefined\n let candidateExecutorFiles:\n | ReadonlyArray<{ path: string; mode: 0o644 | 0o755; 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 = materializeCandidateProfile(bundle.profile, harness, {\n resolvedResources: verifiedResourceTextByDigest(candidate),\n })\n const profileApplication = applyAgentCandidateWorkspacePlan(\n profileWorkspacePlan,\n task.stagingRoots.profileRoot,\n bundle.execution.cwd.workspace,\n )\n await verifyMaterializedProfileWorkspace(\n task.stagingRoots.profileRoot,\n profileApplication.profilePlan.material,\n )\n const profilePlanBytes = await readVerifiedArtifact(\n profileApplication.profilePlan.artifact,\n ports.artifacts,\n )\n if (\n !Buffer.from(profilePlanBytes).equals(\n Buffer.from(canonicalCandidateBytes(profileApplication.profilePlan.material)),\n )\n ) {\n throw new Error('profile materializer did not capture exact canonical plan bytes')\n }\n\n const container = await resolveContainer(candidate, task, ports)\n const resolvedModel = await resolveModel(candidate, task, ports)\n const preparationId = `candidate-preparation-v1.${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: task.attempt,\n bundleDigest: bundle.digest,\n resolved: resolvedModel,\n limits: modelLimits(task.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 task.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 = bundle.knowledge\n ? {\n snapshotId: bundle.knowledge.snapshotId,\n manifestDigest: bundle.knowledge.manifest.sha256,\n manifest: await verifiedArtifactBytes(candidate, bundle.knowledge.manifest),\n }\n : undefined\n\n const baseLaunch = buildLaunch(candidate, task, profileApplication.flags)\n const publicEnv = mergePublicEnvironment(\n bundle.execution.env ?? {},\n profileApplication.env,\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 )\n const routes = modelRoutes(bundle.profile, task.model.requested)\n const executionMaterial: AgentCandidateExecutionPlanMaterialV1 = {\n schemaVersion: 1,\n kind: 'agent-candidate-execution-plan-material',\n bundleDigest: bundle.digest,\n executionId: task.executionId,\n attempt: task.attempt,\n task: {\n benchmark: task.benchmark,\n benchmarkVersion: task.benchmarkVersion,\n taskId: task.taskId,\n splitDigest: task.splitDigest,\n instruction: {\n encoding: 'utf8',\n sha256: instructionDigest,\n byteLength: instructionBytes.byteLength,\n delivery: bundle.execution.instructionDelivery,\n },\n repository: task.repository,\n workspace: task.workspace,\n },\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 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 grader: task.grader,\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.manifest.sha256 } : {}),\n memory,\n limits: task.limits,\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 schemaVersion: 1,\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 schemaVersion: 1,\n kind: 'agent-candidate-materialization',\n digestAlgorithm: 'rfc8785-sha256',\n bundleDigest: bundle.digest,\n profilePlan: profileApplication.profilePlan,\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.manifest.sha256 } : {}),\n ...(entrypoint ? { entrypoint } : {}),\n },\n )\n agentCandidateMaterializationReceiptSchema.parse(materializationReceipt.value)\n\n const traceRunId = `${task.executionId}:attempt-${task.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 executionId: task.executionId,\n roots: {\n execution: { ...task.executionRoots },\n staging: { ...task.stagingRoots },\n },\n profilePlan: {\n value: profileApplication.profilePlan,\n bytes: profilePlanBytes,\n written: [...profileApplication.application.mountPaths],\n },\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.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 requiredStrings: Array<[string, string]> = [\n ['executionId', task.executionId],\n ['benchmark', task.benchmark],\n ['benchmarkVersion', task.benchmarkVersion],\n ['taskId', task.taskId],\n ['repository identity', task.repository.identity],\n ['repository root identity', task.repository.rootIdentity],\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 (!task.instruction || !isWellFormedUnicode(task.instruction)) {\n throw new Error('task instruction must be non-empty well-formed Unicode')\n }\n sha256DigestSchema.parse(task.splitDigest)\n agentCandidateWorkspaceSnapshotEvidenceSchema.parse(task.workspace)\n agentCandidateExecutionLimitsSchema.parse(task.limits)\n if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(task.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(task.repository.baseTree)) {\n throw new Error('task repository base tree is not a full Git object id')\n }\n if (task.repository.baseCommit.length !== task.repository.baseTree.length) {\n throw new Error('task repository Git object formats disagree')\n }\n for (const [name, root] of [\n ['execution task root', task.executionRoots.taskRoot],\n ['execution candidate root', task.executionRoots.candidateRoot],\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 = name.startsWith('execution')\n ? posix.isAbsolute(root) && posix.normalize(root) === root\n : isAbsolute(root) && resolveHostPath(root) === root\n if (!canonical) throw new Error(`${name} must be a canonical absolute path`)\n }\n if (\n !Number.isInteger(task.attempt.number) ||\n !Number.isInteger(task.attempt.maxAttempts) ||\n task.attempt.number < 1 ||\n task.attempt.number > task.attempt.maxAttempts ||\n (task.attempt.retryPolicy === 'none' && task.attempt.maxAttempts !== 1)\n ) {\n throw new Error('task attempt policy is invalid')\n }\n const limits = task.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 (!task.model.requested.trim()) throw new Error('evaluator model request must be non-empty')\n if (!task.grader.name.trim() || !task.grader.version.trim()) {\n throw new Error('evaluator benchmark grader identity must be non-empty')\n }\n if (!Number.isInteger(task.grader.artifact.byteLength) || task.grader.artifact.byteLength <= 0) {\n throw new Error('evaluator benchmark grader artifact must be non-empty')\n }\n sha256DigestSchema.parse(task.grader.artifact.sha256)\n if (task.evaluatorTaskContainer) {\n if (\n task.evaluatorTaskContainer.source !== 'evaluator-task-container' ||\n !task.evaluatorTaskContainer.image.trim() ||\n !task.evaluatorTaskContainer.platform.os.trim() ||\n !task.evaluatorTaskContainer.platform.architecture.trim()\n ) {\n throw new Error('evaluator task container evidence is incomplete')\n }\n sha256DigestSchema.parse(task.evaluatorTaskContainer.indexDigest)\n sha256DigestSchema.parse(task.evaluatorTaskContainer.manifestDigest)\n agentCandidateContainerSchema.parse({\n image: task.evaluatorTaskContainer.image,\n indexDigest: task.evaluatorTaskContainer.indexDigest,\n })\n }\n if (delivery.kind === 'utf8-file') {\n if (\n executionPathsOverlap(task.executionRoots.taskRoot, delivery.path) ||\n (task.executionRoots.candidateRoot !== undefined &&\n executionPathsOverlap(task.executionRoots.candidateRoot, delivery.path))\n ) {\n throw new Error('task instruction file must remain outside execution workspaces')\n }\n }\n}\n\nfunction 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\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\nfunction materializerHarness(harness: HarnessType): HarnessId {\n if (!MATERIALIZER_HARNESSES.has(harness)) {\n throw new Error(\n `sealed candidate profile materialization is unsupported for harness ${harness}`,\n )\n }\n return harness as HarnessId\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 pinned = environment.kind === 'pinned-container' ? environment.container : undefined\n if (environment.kind === 'evaluator-task-container' && !task.evaluatorTaskContainer) {\n throw new Error('evaluator-task-container candidate requires an evaluator-owned task image')\n }\n if (environment.kind === 'pinned-container' && task.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: task.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 task.evaluatorTaskContainer &&\n JSON.stringify(resolved) !== JSON.stringify(task.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 if (hints?.default !== undefined && hints.default !== task.model.requested) {\n throw new Error('candidate model preference conflicts with the evaluator-owned model')\n }\n if (\n hints?.reasoningEffort !== undefined &&\n hints.reasoningEffort !== task.model.reasoningEffort\n ) {\n throw new Error('candidate reasoning effort conflicts with the evaluator-owned effort')\n }\n const resolved = await ports.models.resolve({\n requested: task.model.requested,\n harness: candidate.bundle.execution.harness,\n reasoningEffort: task.model.reasoningEffort,\n })\n if (\n resolved.requested !== task.model.requested ||\n resolved.reasoningEffort !== task.model.reasoningEffort\n ) {\n throw new Error('model resolver drifted from the evaluator-owned request')\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({ taskId: task.taskId }).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): AgentCandidateExecutionPlanMaterialV1['model']['routes'] {\n const routes: AgentCandidateExecutionPlanMaterialV1['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 = cwd.workspace === 'task' ? roots.taskRoot : roots.candidateRoot\n if (!root) throw new Error('candidate cwd is missing its execution workspace root')\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 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<{ relPath: string; content: string; mode?: number }>,\n expectedFiles: ReadonlyArray<{ relPath: string; mode: number; contentSha256: string }>,\n): Array<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }> {\n const byPath = new Map(sourceFiles.map((file) => [file.relPath, file]))\n if (byPath.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 = byPath.get(expected.relPath)\n const mode = source?.mode ?? 0o644\n const bytes = Buffer.from(source?.content ?? '', 'utf8')\n if (\n !source ||\n (mode !== 0o644 && mode !== 0o755) ||\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 { path: expected.relPath, mode, bytes: Uint8Array.from(bytes) }\n })\n}\n\nfunction isWellFormedUnicode(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index)\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(index + 1)\n if (!(next >= 0xdc00 && next <= 0xdfff)) return false\n index++\n } else if (code >= 0xdc00 && code <= 0xdfff) {\n return false\n }\n }\n return true\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","import type {\n AgentCandidateConfigValue,\n AgentCandidateProfile,\n AgentCandidateResourceRef,\n AgentProfile,\n AgentProfileMcpServer,\n AgentProfileResourceRef,\n} from '@tangle-network/agent-interface'\nimport { agentCandidateProfileSchema, agentProfileSchema } from '@tangle-network/agent-interface'\n\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDigest,\n embeddedCandidateArtifact,\n} from './digest'\n\nconst CANDIDATE_PROFILE_DIRECT_FIELDS = [\n 'name',\n 'description',\n 'version',\n 'tags',\n 'prompt',\n 'harness',\n 'permissions',\n 'tools',\n 'confidential',\n] as const\n\n/** Convert only behavior-preserving generic profile fields into the closed candidate contract. */\nexport function freezeGenericAgentCandidateProfile(input: AgentProfile): AgentCandidateProfile {\n const profile = parseExactAgentProfile(input, 'profile')\n if (profile.connections !== undefined) unsupportedProfileField('connections')\n if (profile.metadata !== undefined) unsupportedProfileField('metadata')\n if (profile.extensions !== undefined) unsupportedProfileField('extensions')\n if (profile.model?.metadata !== undefined) unsupportedProfileField('model.metadata')\n\n const candidate: Record<string, unknown> = {}\n copyDirectProfileFields(candidate, profile as Record<string, unknown>)\n if (profile.model) {\n const { metadata: _metadata, ...model } = profile.model\n candidate.model = model\n }\n if (profile.mcp) candidate.mcp = freezeMcpServers(profile.mcp)\n if (profile.subagents) {\n candidate.subagents = Object.fromEntries(\n Object.entries(profile.subagents).map(([name, subagent]) => {\n if (subagent.metadata !== undefined) unsupportedProfileField(`subagents.${name}.metadata`)\n const { metadata: _metadata, ...value } = subagent\n return [name, value]\n }),\n )\n }\n if (profile.resources) candidate.resources = freezeResources(profile.resources)\n if (profile.hooks && Object.values(profile.hooks).some((commands) => commands.length > 0)) {\n throw new Error(\n 'generic AgentProfile hooks cannot be safely tokenized; use a candidate-profile source with executable/args',\n )\n }\n if (profile.hooks) candidate.hooks = profile.hooks\n if (profile.modes) {\n candidate.modes = Object.fromEntries(\n Object.entries(profile.modes).map(([name, mode]) => {\n if (mode.metadata !== undefined) unsupportedProfileField(`modes.${name}.metadata`)\n const { metadata: _metadata, ...value } = mode\n return [name, value]\n }),\n )\n }\n const parsed = parseExactCandidateProfile(candidate)\n assertCandidateProfileBinding(profile, parsed)\n return parsed\n}\n\n/** Prove the measured generic profile and sealed candidate profile describe the same behavior. */\nexport function assertCandidateProfileBinding(\n measuredInput: AgentProfile,\n bundled: AgentCandidateProfile,\n): void {\n const measured = parseExactAgentProfile(measuredInput, 'proposal candidate profile')\n if (measured.connections || measured.metadata || measured.extensions) {\n throw new Error('proposal candidate profile contains fields unsupported by sealed candidates')\n }\n const normalized = candidateProfileAsAgentProfile(bundled)\n if (canonicalCandidateDigest(measured) !== canonicalCandidateDigest(normalized)) {\n throw new Error('proposal candidateProfile does not match candidateBundle.profile')\n }\n}\n\nexport function parseExactAgentProfile(input: unknown, label: string): AgentProfile {\n const parsed = agentProfileSchema.parse(input) as AgentProfile\n assertCanonicalParse(input, parsed, label)\n return parsed\n}\n\nexport function parseExactCandidateProfile(input: unknown): AgentCandidateProfile {\n const parsed = agentCandidateProfileSchema.parse(input)\n assertCanonicalParse(input, parsed, 'candidate profile')\n return parsed\n}\n\nfunction candidateProfileAsAgentProfile(candidate: AgentCandidateProfile): AgentProfile {\n const output: Record<string, unknown> = {}\n copyDirectProfileFields(output, candidate as unknown as Record<string, unknown>)\n if (candidate.model) output.model = { ...candidate.model }\n if (candidate.mcp) {\n output.mcp = Object.fromEntries(\n Object.entries(candidate.mcp).map(([name, server]) => [\n name,\n {\n ...server,\n ...(server.args ? { args: server.args.map(publicValue) } : {}),\n ...(server.env ? { env: mapPublicValues(server.env) } : {}),\n },\n ]),\n )\n }\n if (candidate.subagents) output.subagents = cloneRecord(candidate.subagents)\n if (candidate.modes) output.modes = cloneRecord(candidate.modes)\n if (candidate.hooks) {\n output.hooks = Object.fromEntries(\n Object.entries(candidate.hooks).map(([event, hooks]) => [\n event,\n hooks.map(({ executable, args, env, ...hook }) => ({\n ...hook,\n command: [executable, ...(args ?? []).map(publicValue)].map(shellQuote).join(' '),\n ...(env ? { env: mapPublicValues(env) } : {}),\n })),\n ]),\n )\n }\n if (candidate.resources) {\n if (candidate.resources.failOnError !== true) {\n throw new Error('proposal candidate profile contains fields unsupported by sealed candidates')\n }\n output.resources = {\n failOnError: true,\n ...(candidate.resources.files\n ? {\n files: candidate.resources.files.map((file) => ({\n ...file,\n resource: publicResource(file.resource),\n })),\n }\n : {}),\n ...(candidate.resources.tools\n ? { tools: candidate.resources.tools.map(publicResource) }\n : {}),\n ...(candidate.resources.skills\n ? { skills: candidate.resources.skills.map(publicResource) }\n : {}),\n ...(candidate.resources.agents\n ? { agents: candidate.resources.agents.map(publicResource) }\n : {}),\n ...(candidate.resources.commands\n ? { commands: candidate.resources.commands.map(publicResource) }\n : {}),\n ...(candidate.resources.instructions !== undefined\n ? {\n instructions:\n typeof candidate.resources.instructions === 'string'\n ? candidate.resources.instructions\n : publicResource(candidate.resources.instructions),\n }\n : {}),\n }\n }\n return output as AgentProfile\n}\n\nfunction freezeMcpServers(servers: Record<string, AgentProfileMcpServer>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(servers).map(([name, server]) => {\n if (server.transport !== undefined && server.transport !== 'stdio') {\n unsupportedProfileField(`mcp.${name}.transport=${server.transport}`)\n }\n if (server.url !== undefined) unsupportedProfileField(`mcp.${name}.url`)\n if (server.headers !== undefined) unsupportedProfileField(`mcp.${name}.headers`)\n if (server.metadata !== undefined) unsupportedProfileField(`mcp.${name}.metadata`)\n return [\n name,\n {\n ...(server.transport ? { transport: server.transport } : {}),\n ...(server.command ? { command: server.command } : {}),\n ...(server.args ? { args: server.args.map(candidatePublicValue) } : {}),\n ...(server.env ? { env: mapCandidatePublicValues(server.env) } : {}),\n ...(server.cwd ? { cwd: server.cwd } : {}),\n ...(server.enabled === undefined ? {} : { enabled: server.enabled }),\n },\n ]\n }),\n )\n}\n\nfunction freezeResources(resources: NonNullable<AgentProfile['resources']>): unknown {\n if (resources.failOnError !== true) {\n throw new Error('candidate profile resources require failOnError: true')\n }\n return {\n failOnError: true,\n ...(resources.files\n ? {\n files: resources.files.map((file) => ({\n ...file,\n resource: freezeResource(file.resource),\n })),\n }\n : {}),\n ...(resources.tools ? { tools: resources.tools.map(freezeResource) } : {}),\n ...(resources.skills ? { skills: resources.skills.map(freezeResource) } : {}),\n ...(resources.agents ? { agents: resources.agents.map(freezeResource) } : {}),\n ...(resources.commands ? { commands: resources.commands.map(freezeResource) } : {}),\n ...(resources.instructions === undefined\n ? {}\n : {\n instructions:\n typeof resources.instructions === 'string'\n ? resources.instructions\n : freezeResource(resources.instructions),\n }),\n }\n}\n\nfunction freezeResource(resource: AgentProfileResourceRef): AgentCandidateResourceRef {\n if (resource.kind === 'github') {\n throw new Error(\n 'generic GitHub profile resources do not carry byte identity; use a candidate-profile source with a pinned commit, digest, and byte length',\n )\n }\n const bytes = Buffer.from(resource.content, 'utf8')\n return {\n ...resource,\n sha256: embeddedCandidateArtifact(bytes).sha256,\n byteLength: bytes.byteLength,\n }\n}\n\nfunction copyDirectProfileFields(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n): void {\n for (const key of CANDIDATE_PROFILE_DIRECT_FIELDS) {\n if (source[key] !== undefined) target[key] = source[key]\n }\n}\n\nfunction assertCanonicalParse(input: unknown, parsed: unknown, label: string): void {\n if (!Buffer.from(canonicalCandidateBytes(input)).equals(canonicalCandidateBytes(parsed))) {\n throw new Error(`${label} contains unsupported or non-canonical fields`)\n }\n}\n\nfunction publicResource(resource: AgentCandidateResourceRef): unknown {\n if (resource.kind === 'inline') {\n return { kind: 'inline', name: resource.name, content: resource.content }\n }\n return {\n kind: 'github',\n repository: `${resource.repository.owner}/${resource.repository.repo}`,\n path: resource.path,\n ref: resource.commit,\n ...(resource.name ? { name: resource.name } : {}),\n }\n}\n\nfunction candidatePublicValue(value: string): { kind: 'public'; value: string } {\n return { kind: 'public', value }\n}\n\nfunction mapCandidatePublicValues(\n values: Record<string, string>,\n): Record<string, { kind: 'public'; value: string }> {\n return Object.fromEntries(\n Object.entries(values).map(([name, value]) => [name, candidatePublicValue(value)]),\n )\n}\n\nfunction publicValue(value: AgentCandidateConfigValue): string {\n return value.value\n}\n\nfunction mapPublicValues(\n values: Record<string, AgentCandidateConfigValue>,\n): Record<string, string> {\n return Object.fromEntries(Object.entries(values).map(([key, value]) => [key, publicValue(value)]))\n}\n\nfunction cloneRecord<T>(values: Record<string, T>): Record<string, T> {\n return Object.fromEntries(\n Object.entries(values).map(([key, value]) => [key, { ...value }]),\n ) as Record<string, T>\n}\n\nfunction shellQuote(value: string): string {\n return /^[A-Za-z0-9_./:@%+=,-]+$/.test(value) ? value : `'${value.replaceAll(\"'\", `'\"'\"'`)}'`\n}\n\nfunction unsupportedProfileField(path: string): never {\n throw new Error(\n `generic AgentProfile field ${path} is not representable in a sealed candidate profile`,\n )\n}\n"],"mappings":";;;;;AACA,SAAS,kCAAkC;;;ACD3C,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB;AAMvB,SAAS,YAAY,OAAiC;AAC3D,SAAO,UAAU,WAAW,QAAQ,EAAE,OAAO,KAAK,EAAE,OAAO,KAAK,CAAC;AACnE;AAEO,SAAS,wBAAwB,OAA4B;AAClE,SAAO,OAAO,KAAK,cAAc,KAAK,GAAG,MAAM;AACjD;AAEO,SAAS,yBAAyB,OAA8B;AACrE,SAAO,eAAe,KAAK;AAC7B;AAGO,S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AO;AAAA,IACZ,OAAO,QAAQ,MAAM,EAAE,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC,MAAM,qBAAqB,KAAK,CAAC,CAAC;AAAA,EACnF;AACF;AAEA,SAAS,YAAY,OAA0C;AAC7D,SAAO,MAAM;AACf;AAEA,SAAS,gBACP,QACwB;AACxB,SAAO,OAAO,YAAY,OAAO,QAAQ,MAAM,EAAE,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM,CAAC,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC;AACnG;AAEA,SAAS,YAAe,QAA8C;AACpE,SAAO,OAAO;AAAA,IACZ,OAAO,QAAQ,MAAM,EAAE,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM,CAAC,KAAK,EAAE,GAAG,MAAM,CAAC,CAAC;AAAA,EAClE;AACF;AAEA,SAAS,WAAW,OAAuB;AACzC,SAAO,2BAA2B,KAAK,KAAK,IAAI,QAAQ,IAAI,MAAM,WAAW,KAAK,OAAO,CAAC;AAC5F;AAEA,SAAS,wBAAwB,MAAqB;AACpD,QAAM,IAAI;AAAA,IACR,8BAA8B,IAAI;AAAA,EACpC;AACF;","names":["createHash","retryRejection","SHA256_PATTERN","assertExecutionId","assertSha256Digest","createHash","requireString","requireNumber","requireObject","sha256","readFile","realpath","resolve","resolve","realpath","readFile","hasControlCharacter","agentCandidateArtifactRefSchema","agentCandidateArtifactRefSchema","mkdtemp","rm","tmpdir","join","isLlmSpan","REDACTION_VERSION","assertCount","isLlmSpan","REDACTION_VERSION","mkdtemp","join","tmpdir","rm","mkdtemp","rm","tmpdir","join","agentCandidateWorkspaceSnapshotEvidenceSchema","agentCandidateWorkspaceSnapshotEvidenceSchema","mkdtemp","join","tmpdir","rm","REDACTION_VERSION","REDACTION_VERSION","agentCandidateBundleSchema","agentCandidateBundleSchema","randomBytes","lstat","readdir","relative","agentCandidateExecutionPlanEvidenceSchema","agentCandidateMaterializationReceiptSchema","agentCandidateWorkspaceSnapshotEvidenceSchema","randomBytes","modelLimits","agentCandidateExecutionPlanEvidenceSchema","agentCandidateMaterializationReceiptSchema","errorMessage","agentCandidateWorkspaceSnapshotEvidenceSchema","relative","lstat","readdir"]}
|