@tangle-network/agent-runtime 0.295.2 → 0.295.3

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-Bcx8STGY.js","names":["positiveInteger","fsConstants","isAsyncIterable","DIGEST","sha256Bytes","canonicalCandidateDigest","sha256Bytes","fsConstants"],"sources":["../src/runtime/tangle-sandbox-exact-process-provider.ts","../src/runtime/key-provider.ts","../src/runtime/mcp-environment.ts","../src/runtime/stdio-mcp-client.ts","../src/durable/spawn-journal-sql.ts","../src/durable/sql-run-store.ts","../src/runtime/audit-intent.ts","../src/runtime/benchmark-report.ts","../src/runtime/completion.ts","../src/runtime/isolated-checker.ts","../src/runtime/declared-check.ts","../src/runtime/loop-dispatch.ts","../src/runtime/inline-sandbox-client.ts","../src/runtime/local-sandbox-client.ts","../src/runtime/resolve-sandbox-client.ts","../src/runtime/define-leaderboard.ts","../src/runtime/harvest-corpus.ts","../src/runtime/in-process-sandbox-client.ts","../src/runtime/observation-registry.ts","../src/runtime/personify/analyst.ts","../src/runtime/personify/combinators.ts","../src/runtime/personify/corpus.ts","../src/runtime/personify/registry.ts","../src/runtime/personify/persona.ts","../src/runtime/personify/trajectory.ts","../src/runtime/private-cas.ts","../src/runtime/run-benchmark.ts","../src/runtime/s3-private-cas-store.ts","../src/runtime/box-read-retry.ts","../src/runtime/sandbox-run.ts","../src/runtime/authored-code.ts","../src/runtime/strategy-author.ts","../src/runtime/strategy-evolution.ts","../src/runtime/supervise/chat-transport-executor.ts","../src/runtime/supervise/code-mode.ts","../src/runtime/supervise/patch-checks.ts","../src/runtime/supervise/patch-deliverable.ts","../src/runtime/supervise/run-context-sql.ts","../src/runtime/supervise/sql-run-context.ts","../src/runtime/supervise/trajectory-recorder.ts","../src/runtime/supervise/untracked-clone.ts","../src/runtime/supervise/worker-evidence.ts","../src/runtime/supervise/worktree-fanout.ts","../src/runtime/supervise-surface.ts","../src/runtime/surface-diff.ts","../src/runtime/verifier-environment.ts","../src/runtime/waterfall.ts","../src/runtime/workspace.ts"],"sourcesContent":["import { isDeepStrictEqual } from 'node:util'\n\nimport type { AgentCandidateTermination } from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironmentCapabilities,\n AgentEnvironmentProvider,\n AgentExactProcess,\n AgentExactProcessEnvironment,\n AgentExactProcessEnvironmentQuery,\n AgentExactProcessProvider,\n AgentExactProcessStatus,\n CreateAgentExactProcessEnvironmentInput,\n} from '@tangle-network/agent-interface/environment-provider'\nimport type {\n Process,\n ProcessStatus,\n Sandbox,\n SandboxInstance,\n SandboxResources,\n} from '@tangle-network/sandbox'\n\nexport type SandboxControlClient = Pick<Sandbox, 'create' | 'get' | 'list'>\n\ntype ExactSandboxEgressPolicy =\n | { mode: 'blocked' }\n | { mode: 'strict'; allowDomains: string[]; includeImplicitDomains: false }\n\nexport interface CreateTangleSandboxExactProcessProviderOptions {\n name?: string\n}\n\nconst exactProcessProviderMarker = 'agent-runtime.exact-process-provider'\nconst exactProcessEgressMarker = 'agent-runtime.exact-process-egress'\n\n/**\n * Adapt Tangle Sandbox's managed control runtime to Runtime's exact-process provider.\n *\n * The adapter deliberately exposes no ordinary agent environment: an exact experiment\n * must start a fresh Sandbox with no managed agent and launch its declared argv directly.\n */\nexport function createTangleSandboxExactProcessProvider(\n client: SandboxControlClient,\n options: CreateTangleSandboxExactProcessProviderOptions = {},\n): AgentEnvironmentProvider {\n const name = options.name ?? 'tangle-sandbox-exact-process'\n if (!name.trim()) throw new Error('Tangle Sandbox exact-process provider name must not be empty')\n\n const exactProcess: AgentExactProcessProvider = {\n async create(input: CreateAgentExactProcessEnvironmentInput) {\n throwIfAborted(input.signal)\n assertNoProviderOptions(input.providerOptions)\n const egressPolicy = sandboxEgressPolicy(input.egress)\n const metadata = exactMetadata(input.metadata, name, egressPolicy)\n const sandbox = await client.create(\n {\n environment: requiredText(input.image, 'exact-process image'),\n agent: false,\n bare: false,\n ephemeral: true,\n egressPolicy,\n resources: sandboxResources(input),\n maxLifetimeSeconds: sandboxLifetimeSeconds(input.maxLifetimeMs),\n metadata,\n idempotencyKey: requiredText(input.idempotencyKey, 'exact-process idempotency key'),\n },\n {\n ...(input.provisionTimeoutMs === undefined\n ? {}\n : { timeoutMs: positiveInteger(input.provisionTimeoutMs, 'provision timeout') }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n },\n )\n try {\n throwIfAborted(input.signal)\n assertExactSandboxMetadata(sandbox, metadata)\n await assertExactSandboxEgress(sandbox, egressPolicy)\n } catch (error) {\n await discardInvalidSandbox(sandbox, error)\n }\n return sandboxAsExactProcessEnvironment(sandbox, name)\n },\n async get(id: string) {\n const sandbox = await client.get(id)\n if (!sandbox || !isExactSandbox(sandbox, name)) return null\n await assertExactSandboxEgress(sandbox, egressFromMetadata(sandbox.metadata))\n return sandboxAsExactProcessEnvironment(sandbox, name)\n },\n async list(query?: AgentExactProcessEnvironmentQuery) {\n assertNoProviderOptions(query?.providerOptions)\n const sandboxes = await client.list()\n return Promise.all(\n sandboxes\n .filter((sandbox) => isExactSandbox(sandbox, name))\n .filter((sandbox) => metadataMatches(sandbox.metadata, query?.metadata))\n .map(async (sandbox) => {\n await assertExactSandboxEgress(sandbox, egressFromMetadata(sandbox.metadata))\n return sandboxAsExactProcessEnvironment(sandbox, name)\n }),\n )\n },\n }\n\n return {\n name,\n exactProcess,\n capabilities: exactProcessOnlyCapabilities,\n async create() {\n throw new Error(`agent environment provider \"${name}\" supports exactProcess.create() only`)\n },\n }\n}\n\nfunction sandboxAsExactProcessEnvironment(\n sandbox: SandboxInstance,\n provider: string,\n): AgentExactProcessEnvironment {\n return {\n id: requiredText(sandbox.id, 'Sandbox id'),\n provider,\n ...(sandbox.metadata ? { metadata: sandbox.metadata } : {}),\n process: {\n async list(): Promise<AgentExactProcessStatus[]> {\n return (await sandbox.process.list()).map((status) => exactProcessStatus(status))\n },\n async get(pid: number): Promise<AgentExactProcess | null> {\n const process = await sandbox.process.get(pid)\n return process ? sandboxProcessAsExactProcess(process) : null\n },\n async spawn(input, options): Promise<AgentExactProcess> {\n const process = await afterAbortCheck(options?.signal, () =>\n sandbox.process.spawnExact(input.executable, [...input.args], {\n cwd: input.cwd,\n env: { ...input.env },\n inheritEnv: false,\n ...(input.stdin === undefined ? {} : { stdin: input.stdin }),\n timeoutMs: input.timeoutMs,\n }),\n )\n return sandboxProcessAsExactProcess(process)\n },\n },\n async writeFile(path, bytes, options): Promise<void> {\n if (sandbox.fs.supportsWriteMode !== true) {\n throw new Error('Tangle Sandbox does not declare exact file-mode support')\n }\n await afterAbortCheck(options.signal, () =>\n sandbox.fs.write(path, Buffer.from(bytes).toString('base64'), {\n encoding: 'base64',\n mode: fileMode(options.mode),\n }),\n )\n },\n async readFile(path, options): Promise<Uint8Array> {\n const maxBytes = nonnegativeInteger(options.maxBytes, 'exact-process file read maximum')\n const initialSize = nonnegativeInteger(\n (await afterAbortCheck(options.signal, () => sandbox.fs.stat(path))).size,\n `Tangle Sandbox file size for \"${path}\"`,\n )\n if (initialSize > maxBytes) {\n throw new Error(\n `Tangle Sandbox file \"${path}\" exceeds the ${maxBytes}-byte exact read maximum`,\n )\n }\n const result = await afterAbortCheck(options.signal, () =>\n sandbox.fs.readBatch([path], { encoding: 'base64' }),\n )\n const failure = result.errors.find((entry) => entry.path === path)\n if (failure) {\n throw new Error(`Tangle Sandbox failed to read \"${path}\": ${failure.error}`)\n }\n const files = result.files.filter((entry) => entry.path === path)\n if (files.length !== 1) {\n throw new Error(`Tangle Sandbox returned ${files.length} files for exact read \"${path}\"`)\n }\n const file = files[0]!\n if (file.encoding !== 'base64') {\n throw new Error(`Tangle Sandbox returned non-binary content for exact read \"${path}\"`)\n }\n const size = nonnegativeInteger(file.size, `Tangle Sandbox file size for \"${path}\"`)\n if (size !== initialSize) {\n throw new Error(`Tangle Sandbox file \"${path}\" changed during exact read`)\n }\n if (size > maxBytes) {\n throw new Error(\n `Tangle Sandbox file \"${path}\" exceeds the ${maxBytes}-byte exact read maximum`,\n )\n }\n const bytes = Buffer.from(file.content, 'base64')\n if (bytes.byteLength !== size || bytes.toString('base64') !== file.content) {\n throw new Error(\n `Tangle Sandbox returned an invalid binary payload for exact read \"${path}\"`,\n )\n }\n return Uint8Array.from(bytes)\n },\n async destroy(): Promise<void> {\n await sandbox.delete()\n },\n }\n}\n\nfunction sandboxProcessAsExactProcess(process: Process): AgentExactProcess {\n const pid = positiveInteger(process.pid, 'Tangle Sandbox process pid')\n return {\n pid,\n async status(): Promise<AgentExactProcessStatus> {\n return exactProcessStatus(await process.status(), pid)\n },\n async wait(): Promise<AgentCandidateTermination> {\n const waitExitCode = await process.wait()\n if (!Number.isSafeInteger(waitExitCode)) {\n throw new Error('Tangle Sandbox process wait returned an invalid exit code')\n }\n const status = exactProcessStatus(await process.status(), pid)\n if (status.running || !status.termination) {\n throw new Error('Tangle Sandbox process wait returned before terminal status')\n }\n if (status.termination.kind === 'exit' && status.termination.exitCode !== waitExitCode) {\n throw new Error('Tangle Sandbox process wait and status disagree on exit code')\n }\n return status.termination\n },\n async kill(): Promise<void> {\n await process.kill('SIGKILL', { tree: true })\n },\n async *stdout(): AsyncIterable<string> {\n yield* process.stdout()\n },\n async *stderr(): AsyncIterable<string> {\n yield* process.stderr()\n },\n }\n}\n\nfunction exactProcessStatus(status: ProcessStatus, expectedPid?: number): AgentExactProcessStatus {\n const pid = positiveInteger(status.pid, 'Tangle Sandbox process pid')\n if (expectedPid !== undefined && pid !== expectedPid) {\n throw new Error('Tangle Sandbox process status changed process identity')\n }\n if (typeof status.running !== 'boolean') {\n throw new Error('Tangle Sandbox process status is missing running state')\n }\n if (!Number.isSafeInteger(status.exitCode)) {\n throw new Error('Tangle Sandbox process status is missing an integer exit code')\n }\n const exitSignal = optionalText(status.exitSignal, 'Tangle Sandbox process exit signal')\n if (status.running) {\n if (status.exitCode !== -1) {\n throw new Error('Tangle Sandbox running process must report exit code -1')\n }\n if (exitSignal) {\n throw new Error('Tangle Sandbox running process must not report an exit signal')\n }\n return {\n pid,\n running: true,\n exitCode: -1,\n }\n }\n const termination = exitSignal\n ? ({ kind: 'signal', signal: exitSignal } as const)\n : status.exitCode >= 0\n ? ({ kind: 'exit', exitCode: status.exitCode } as const)\n : undefined\n if (!termination) {\n throw new Error('Tangle Sandbox stopped process has no terminal reason')\n }\n return {\n pid,\n running: false,\n exitCode: status.exitCode,\n ...(exitSignal ? { exitSignal } : {}),\n termination,\n }\n}\n\nfunction exactMetadata(\n metadata: Record<string, unknown>,\n provider: string,\n egressPolicy: ExactSandboxEgressPolicy,\n): Record<string, unknown> {\n for (const marker of [exactProcessProviderMarker, exactProcessEgressMarker]) {\n if (Object.hasOwn(metadata, marker)) {\n throw new Error(`exact-process metadata must not set \"${marker}\"`)\n }\n }\n return {\n ...metadata,\n [exactProcessProviderMarker]: provider,\n [exactProcessEgressMarker]: serializeEgressPolicy(egressPolicy),\n }\n}\n\nfunction isExactSandbox(sandbox: SandboxInstance, provider: string): boolean {\n return sandbox.metadata?.[exactProcessProviderMarker] === provider\n}\n\nfunction metadataMatches(\n metadata: Record<string, unknown> | undefined,\n expected: Record<string, unknown> | undefined,\n): boolean {\n return (\n expected === undefined ||\n Object.entries(expected).every(([key, value]) => isDeepStrictEqual(metadata?.[key], value))\n )\n}\n\nfunction assertExactSandboxMetadata(\n sandbox: SandboxInstance,\n expected: Record<string, unknown>,\n): void {\n if (!metadataMatches(sandbox.metadata, expected)) {\n throw new Error('Tangle Sandbox did not persist exact-process metadata')\n }\n}\n\nfunction egressFromMetadata(\n metadata: Record<string, unknown> | undefined,\n): ExactSandboxEgressPolicy {\n const encoded = metadata?.[exactProcessEgressMarker]\n if (typeof encoded !== 'string') {\n throw new Error('Tangle Sandbox exact-process environment is missing egress metadata')\n }\n try {\n const parsed: unknown = JSON.parse(encoded)\n if (!parsed || typeof parsed !== 'object') throw new Error('expected egress object')\n const policy = parsed as {\n mode?: unknown\n allowDomains?: unknown\n includeImplicitDomains?: unknown\n }\n if (policy.mode === 'blocked' && policy.allowDomains === undefined) return { mode: 'blocked' }\n if (\n policy.mode === 'strict' &&\n policy.includeImplicitDomains === false &&\n Array.isArray(policy.allowDomains) &&\n policy.allowDomains.every((domain): domain is string => typeof domain === 'string')\n ) {\n const allowDomains = sortedDomains(policy.allowDomains)\n if (new Set(allowDomains).size === allowDomains.length) {\n return { mode: 'strict', allowDomains, includeImplicitDomains: false }\n }\n }\n } catch {\n throw new Error('Tangle Sandbox exact-process environment has invalid egress metadata')\n }\n throw new Error('Tangle Sandbox exact-process environment has invalid egress metadata')\n}\n\nasync function assertExactSandboxEgress(\n sandbox: SandboxInstance,\n expected: ExactSandboxEgressPolicy,\n): Promise<void> {\n const actual = (await sandbox.egress.get()).policy\n if (actual.mode !== expected.mode) {\n throw new Error(\n `Tangle Sandbox egress mismatch: expected ${expected.mode}, received ${actual.mode}`,\n )\n }\n if (expected.mode === 'blocked') {\n const allowDomains = (actual as { allowDomains?: unknown }).allowDomains\n if (\n actual.mode === 'blocked' &&\n (allowDomains === undefined || (Array.isArray(allowDomains) && allowDomains.length === 0))\n ) {\n return\n }\n throw new Error('Tangle Sandbox blocked egress retained an allowlist')\n }\n if (actual.mode !== 'strict') {\n throw new Error('Tangle Sandbox did not return strict egress policy')\n }\n const expectedDomains = sortedDomains(expected.allowDomains)\n const actualDomains = sortedDomains(actual.allowDomains ?? [])\n if (!isDeepStrictEqual(actualDomains, expectedDomains)) {\n throw new Error('Tangle Sandbox strict egress differs from the exact allowlist')\n }\n if (actual.includeImplicitDomains !== false) {\n throw new Error('Tangle Sandbox strict egress retained implicit domains')\n }\n}\n\nfunction sandboxEgressPolicy(\n input: CreateAgentExactProcessEnvironmentInput['egress'],\n): ExactSandboxEgressPolicy {\n if (input.mode === 'blocked') return { mode: 'blocked' }\n const allowDomains = input.allowDomains.map((domain) =>\n requiredText(domain, 'strict egress domain'),\n )\n if (new Set(allowDomains).size !== allowDomains.length) {\n throw new Error('strict egress domains must not contain duplicates')\n }\n return { mode: 'strict', allowDomains, includeImplicitDomains: false }\n}\n\nfunction serializeEgressPolicy(policy: ExactSandboxEgressPolicy): string {\n return JSON.stringify(\n policy.mode === 'blocked'\n ? { mode: 'blocked' }\n : {\n mode: 'strict',\n allowDomains: sortedDomains(policy.allowDomains),\n includeImplicitDomains: false,\n },\n )\n}\n\nfunction sandboxResources(input: CreateAgentExactProcessEnvironmentInput): SandboxResources {\n const cpuCores = positiveNumber(input.resources.cpu, 'exact-process cpu')\n const memoryMB = positiveInteger(input.resources.memoryMb, 'exact-process memory')\n const diskMb = positiveInteger(input.resources.diskMb, 'exact-process disk')\n if (diskMb % 1024 !== 0) {\n throw new Error('Tangle Sandbox exact-process disk must be a whole GiB')\n }\n return { cpuCores, memoryMB, diskGB: diskMb / 1024 }\n}\n\nfunction sandboxLifetimeSeconds(maxLifetimeMs: number): number {\n const milliseconds = positiveInteger(maxLifetimeMs, 'exact-process maximum lifetime')\n if (milliseconds % 1_000 !== 0) {\n throw new Error(\n 'Tangle Sandbox exact-process maximum lifetime must be a whole number of seconds',\n )\n }\n return milliseconds / 1_000\n}\n\nfunction fileMode(value: number): number {\n const mode = nonnegativeInteger(value, 'exact-process file mode')\n if (mode > 0o7777) throw new Error('exact-process file mode exceeds POSIX mode bits')\n return mode\n}\n\nfunction assertNoProviderOptions(providerOptions: Record<string, unknown> | undefined): void {\n if (providerOptions && Object.keys(providerOptions).length > 0) {\n throw new Error('Tangle Sandbox exact-process provider does not accept providerOptions')\n }\n}\n\nfunction exactProcessOnlyCapabilities(): AgentEnvironmentCapabilities {\n return {\n profile: {\n namedProfiles: false,\n // Exact-process runs a command as given and interprets no part of a profile, so neither\n // spelling is honored and a profile carrying one is refused rather than silently dropped.\n systemPrompt: { replace: false, append: false },\n instructions: false,\n tools: false,\n permissions: false,\n mcp: false,\n subagents: false,\n resources: {\n files: false,\n instructions: false,\n tools: false,\n skills: false,\n agents: false,\n commands: false,\n },\n hooks: false,\n modes: false,\n runtimeUpdate: false,\n validation: false,\n },\n streaming: { live: false, replay: false, detach: false, turnIdempotency: false },\n sessions: { continue: false, list: false, messages: false },\n workspace: {\n read: false,\n write: false,\n exec: false,\n git: false,\n upload: false,\n download: false,\n },\n branching: { checkpoint: false, fork: false },\n placement: false,\n usage: false,\n confidential: false,\n exactProcess: { egress: ['blocked', 'strict'] },\n }\n}\n\nasync function discardInvalidSandbox(sandbox: SandboxInstance, cause: unknown): Promise<never> {\n try {\n await sandbox.delete()\n } catch (destroyError) {\n throw new AggregateError(\n [cause, destroyError],\n 'Tangle Sandbox exact-process creation failed and cleanup failed',\n )\n }\n throw cause\n}\n\nfunction sortedDomains(domains: readonly string[]): string[] {\n return [...domains].sort((left, right) => left.localeCompare(right))\n}\n\nfunction requiredText(value: string, label: string): string {\n if (typeof value !== 'string' || !value.trim())\n throw new Error(`${label} must be a non-empty string`)\n return value\n}\n\nfunction optionalText(value: string | undefined, label: string): string | undefined {\n if (value === undefined) return undefined\n return requiredText(value, label)\n}\n\nfunction positiveNumber(value: number, label: string): number {\n if (!Number.isFinite(value) || value <= 0) throw new Error(`${label} must be positive`)\n return value\n}\n\nfunction positiveInteger(value: number, label: string): number {\n if (!Number.isSafeInteger(value) || value < 1)\n throw new Error(`${label} must be a positive integer`)\n return value\n}\n\nfunction nonnegativeInteger(value: number, label: string): number {\n if (!Number.isSafeInteger(value) || value < 0)\n throw new Error(`${label} must be a non-negative integer`)\n return value\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n signal?.throwIfAborted()\n}\n\nasync function afterAbortCheck<T>(\n signal: AbortSignal | undefined,\n operation: () => Promise<T>,\n): Promise<T> {\n throwIfAborted(signal)\n const result = await operation()\n throwIfAborted(signal)\n return result\n}\n","/**\n * `KeyProvider` — API-key provisioning for adopted external MCP servers.\n *\n * An adopted server (a `connection` artifact, or a `buildableGenerator` remote\n * emit) usually needs a credential. The credential must never ride the profile\n * or the artifact — both are logged, diffed, and stored as audit records — so\n * the profile carries only a DECLARATIVE reference, on either channel:\n *\n * - interface ≥0.40 canonical: `profile.mcp[key].env.ENV_VAR_NAME`\n * = `{ kind: 'secret-ref', key: 'PROVIDER_KEY_NAME', format? }`\n * - legacy metadata channel: `profile.mcp[key].metadata[mcpSecretEnvMetadataKey]`\n * = { ENV_VAR_NAME: 'PROVIDER_KEY_NAME', … }\n *\n * and the VALUE is resolved at materialize time (`materializeLocalMcp`'s\n * `keys` option) and injected straight into the spawned server child's env.\n * Values exist only in the child process env — never in the profile, the\n * artifact registry, an error message, or a log line (errors name the KEY\n * NAME only).\n *\n * Fail-closed at every hop: a declared secret with no provider, or a provider\n * that does not hold the named key, THROWS — booting an external server\n * keyless would fail opaquely mid-eval or silently score a broken candidate.\n *\n * `envKeyProvider` is the same-host default: it reads the process env, which\n * the operator loads via dotenvx (the secrets files never touch the repo).\n *\n * >>> REAL SECRET STORES PLUG IN HERE (flagged): the sandbox SDK's\n * `client.secrets` (`SecretsManager.get(name)`) and the platform hub's\n * short-lived capability tokens (`PlatformHubClient.mintToken` →\n * `{ ENV: token }`) both satisfy `KeyProvider` with a one-line adapter; both\n * need a live service, so neither is constructed here.\n */\n\nimport type {\n AgentProfileConfigValue,\n AgentProfileMcpServer,\n AgentProfileSecretRef,\n} from '@tangle-network/agent-interface'\nimport { ValidationError } from '../errors'\n\n/** Resolve named secrets. The ONE seam every secret store adapts to. */\nexport interface KeyProvider {\n /** The value for `name`, or `undefined` when this provider does not hold it. */\n get(name: string): Promise<string | undefined>\n}\n\n/** The env-backed provider: reads the (dotenvx-loaded) process env. Empty /\n * whitespace-only values count as absent — fail loud, not with a blank key. */\nexport function envKeyProvider(env: Record<string, string | undefined> = process.env): KeyProvider {\n return {\n async get(name: string): Promise<string | undefined> {\n const value = env[name]\n return value !== undefined && value.trim().length > 0 ? value : undefined\n },\n }\n}\n\n/** The `AgentProfileMcpServer.metadata` key the declarative secret-env map\n * rides under: `{ ENV_VAR_NAME: 'PROVIDER_KEY_NAME' }`. Names only — values\n * are resolved at materialize time and never stored. */\nexport const mcpSecretEnvMetadataKey = 'secretEnv'\n\n/** Read (and validate) a server entry's declared secret-env map, if any.\n * Malformed metadata throws — a half-declared secret must never half-boot. */\nexport function secretEnvOfMcpServer(\n server: AgentProfileMcpServer,\n): Record<string, string> | undefined {\n const raw = server.metadata?.[mcpSecretEnvMetadataKey]\n if (raw === undefined || raw === null) return undefined\n if (typeof raw !== 'object' || Array.isArray(raw)) {\n throw new ValidationError(\n `secretEnvOfMcpServer: metadata.${mcpSecretEnvMetadataKey} must be an object mapping env var name -> key name`,\n )\n }\n const entries = Object.entries(raw as Record<string, unknown>)\n if (entries.length === 0) return undefined\n for (const [envName, keyName] of entries) {\n if (!envName.trim() || typeof keyName !== 'string' || !keyName.trim()) {\n throw new ValidationError(\n `secretEnvOfMcpServer: metadata.${mcpSecretEnvMetadataKey}['${envName}'] must name a non-empty provider key`,\n )\n }\n }\n return raw as Record<string, string>\n}\n\n/**\n * Resolve a declared secret-env map into the real env entries for a server\n * spawn. Fail-closed: no provider or a missing key throws, naming the KEY\n * NAME only (the value never appears in any message). `label` names the\n * server for the error (e.g. `profile.mcp['exa']`).\n */\nexport async function resolveSecretEnv(\n secretEnv: Record<string, string>,\n keys: KeyProvider | undefined,\n label: string,\n): Promise<Record<string, string>> {\n const entries = Object.entries(secretEnv)\n if (entries.length === 0) return {}\n if (!keys) {\n throw new ValidationError(\n `${label} declares secret env (${entries.map(([e]) => e).join(', ')}) but no KeyProvider was supplied — refusing to boot an external server keyless`,\n )\n }\n const resolved: Record<string, string> = {}\n for (const [envName, keyName] of entries) {\n const value = await keys.get(keyName)\n if (value === undefined) {\n throw new ValidationError(\n `${label}: the KeyProvider holds no value for '${keyName}' (wanted for env ${envName}) — provision the key or drop the grant`,\n )\n }\n resolved[envName] = value\n }\n return resolved\n}\n\n/** Apply a secret-ref's declared decoration to its resolved raw value. */\nfunction formatSecretValue(value: string, format: AgentProfileSecretRef['format']): string {\n return format === 'bearer' ? `Bearer ${value}` : value\n}\n\n/** The spawn-ready strings for one stdio MCP server: profile config values\n * resolved, secrets separated so the client can redact them. */\nexport interface ResolvedMcpServerLaunch {\n args?: string[]\n /** Public env, safe to appear in diagnostics. */\n env?: Record<string, string>\n /** Resolved secret env. Reaches only the child process; redacted everywhere else. */\n protectedEnv?: Record<string, string>\n}\n\n/**\n * Resolve a profile MCP server's `args`/`env` config values (interface ≥0.40\n * `AgentProfileConfigValue`) plus the legacy `metadata.secretEnv` channel into\n * the plain strings a spawn needs.\n *\n * Rules, all fail-closed:\n * - `args` must be public values. A secret-ref in argv is refused: argv is\n * readable by every host process (/proc/PID/cmdline) and outside the\n * protected-value redaction channel, so a secret there cannot be contained.\n * - `env` secret-refs resolve through the KeyProvider (missing provider or key\n * throws, naming the KEY NAME only) and land in `protectedEnv`.\n * - An env var declared secret on BOTH channels (env secret-ref and\n * metadata.secretEnv) is ambiguous configuration and throws.\n * - A public `env` entry shadowed by a legacy metadata secret keeps the\n * pre-0.40 spawn precedence: the secret value wins in the child env.\n */\nexport async function resolveMcpServerLaunch(\n server: AgentProfileMcpServer,\n keys: KeyProvider | undefined,\n label: string,\n): Promise<ResolvedMcpServerLaunch> {\n const args = server.args?.map((value: AgentProfileConfigValue, index: number): string => {\n if (value.kind !== 'public') {\n throw new ValidationError(\n `${label}.args[${index}] is a secret-ref ('${value.key}') — argv is readable by every host process and exempt from redaction; declare the secret in env instead`,\n )\n }\n return value.value\n })\n\n const publicEnv: Record<string, string> = {}\n const envSecretRefs: Record<string, string> = {}\n const envSecretFormats: Record<string, AgentProfileSecretRef['format']> = {}\n for (const [envName, value] of Object.entries(server.env ?? {})) {\n if (value.kind === 'public') {\n publicEnv[envName] = value.value\n } else {\n envSecretRefs[envName] = value.key\n envSecretFormats[envName] = value.format\n }\n }\n\n const legacySecretEnv = secretEnvOfMcpServer(server)\n for (const envName of Object.keys(legacySecretEnv ?? {})) {\n if (envName in envSecretRefs) {\n throw new ValidationError(\n `${label}: env ${envName} is declared secret twice — once as an env secret-ref and once in metadata.${mcpSecretEnvMetadataKey}; keep exactly one declaration`,\n )\n }\n }\n\n const resolvedRefs = await resolveSecretEnv(envSecretRefs, keys, label)\n const protectedEnv: Record<string, string> = {\n ...(legacySecretEnv ? await resolveSecretEnv(legacySecretEnv, keys, label) : {}),\n ...Object.fromEntries(\n Object.entries(resolvedRefs).map(([envName, raw]) => [\n envName,\n formatSecretValue(raw, envSecretFormats[envName]),\n ]),\n ),\n }\n\n return {\n ...(args ? { args } : {}),\n ...(server.env ? { env: publicEnv } : {}),\n ...(Object.keys(protectedEnv).length > 0 ? { protectedEnv } : {}),\n }\n}\n","/**\n * createMcpEnvironment — wrap any MCP server as an `Environment` (the product-adoption\n * primitive: a product's agent tools are usually already an MCP surface, so the domain\n * only writes the lifecycle hooks — open a scoped artifact, score it with a deployable\n * check, close it — and the tool plumbing is derived from the server).\n *\n * What the helper owns (the generic 80%, hardened on the EnterpriseOps gym):\n * - JSON-RPC `tools/list` → `AgenticTool[]`, with schemas coerced to the\n * OpenAI-tool-valid shape (top-level oneOf/anyOf/allOf/enum/not are rejected by\n * tool-calling providers; nested combinators are fine).\n * - JSON-RPC `tools/call` → the tool's text content (errors surfaced as `ERROR: …`\n * strings — a bad call is the agent's outcome, not an infra fault).\n * - SSE response parsing (streamable-HTTP MCP servers answer with `data:` lines).\n * - Bounded retry with backoff on thrown fetches (transient network ≠ task failure).\n *\n * What the domain supplies: `open` (create/seed the per-task artifact and return its\n * MCP endpoint — url + headers carry the per-artifact scoping, e.g. a database id\n * header), `score` (the deployable check), and optional `close`/`selectTools`.\n */\n\nimport type { Environment } from './run-benchmark'\nimport type { AgenticTask, AgenticTool, ArtifactHandle, SurfaceScore } from './strategy'\n\n/** Where a handle's MCP server lives; headers carry per-artifact scoping. */\nexport interface McpEndpoint {\n url: string\n headers?: Record<string, string>\n}\n\nexport interface McpEnvironmentOptions {\n name: string\n /** Create/seed the per-task artifact; return its handle + the MCP endpoint scoped to it. */\n open(task: AgenticTask): Promise<{ handle: ArtifactHandle; endpoint: McpEndpoint }>\n /** The deployable check over the artifact's current state. */\n score(task: AgenticTask, handle: ArtifactHandle): Promise<SurfaceScore>\n /** Teardown (delete the seeded artifact). Optional — omit for stateless servers. */\n close?(handle: ArtifactHandle): Promise<void>\n /** Restrict/order the server's tools per task (e.g. the task's selected_tools). Default: all. */\n selectTools?(task: AgenticTask, all: AgenticTool[]): AgenticTool[]\n /** Cap on a tool result's text fed back to the worker. Default 1500 chars. */\n maxResultChars?: number\n}\n\n/** POST JSON-RPC and parse a JSON body OR the last `data:` line of an SSE stream.\n * Retries thrown fetches (transient network) with linear backoff; HTTP status and\n * JSON-RPC errors are returned to the caller, not retried. */\nasync function rpc(\n endpoint: McpEndpoint,\n body: unknown,\n): Promise<{ status: number; json: unknown }> {\n let lastErr: unknown\n for (let attempt = 0; attempt < 4; attempt += 1) {\n try {\n const r = await fetch(endpoint.url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...(endpoint.headers ?? {}) },\n body: JSON.stringify(body),\n })\n const text = await r.text()\n const dataLines = text\n .split('\\n')\n .filter((l) => l.startsWith('data:'))\n .map((l) => l.slice(5).trim())\n const payload = dataLines.length ? dataLines[dataLines.length - 1] : text\n try {\n return { status: r.status, json: JSON.parse(payload ?? 'null') }\n } catch {\n return { status: r.status, json: text }\n }\n } catch (err) {\n lastErr = err\n await new Promise((res) => setTimeout(res, 1000 * (attempt + 1)))\n }\n }\n throw new Error(\n `mcp rpc ${endpoint.url} failed after 4 attempts: ${lastErr instanceof Error ? lastErr.message : String(lastErr)}`,\n )\n}\n\n/** Coerce an MCP inputSchema to an OpenAI-tool-valid top-level object schema.\n * Shared with the same-host stdio client (`materializeLocalMcp`) — one coercion\n * rule for every MCP tool a worker sees, regardless of transport. */\nexport function sanitizeMcpToolSchema(s: unknown): Record<string, unknown> {\n const o = s && typeof s === 'object' ? (s as Record<string, unknown>) : {}\n const banned = o.oneOf || o.anyOf || o.allOf || o.not || o.enum\n if (o.type === 'object' && !banned && o.properties && typeof o.properties === 'object') {\n return {\n type: 'object',\n properties: o.properties as Record<string, unknown>,\n ...(Array.isArray(o.required) ? { required: o.required as string[] } : {}),\n }\n }\n return { type: 'object', properties: {} }\n}\n\n/** Wrap any MCP server as an `Environment`: `tools/list` becomes `AgenticTool[]` with provider-safe schemas; the domain supplies only the artifact lifecycle hooks. */\nexport function createMcpEnvironment(opts: McpEnvironmentOptions): Environment {\n const endpoints = new Map<string, McpEndpoint>()\n const maxChars = opts.maxResultChars ?? 1500\n\n return {\n name: opts.name,\n\n async open(task) {\n const { handle, endpoint } = await opts.open(task)\n endpoints.set(handle.id, endpoint)\n return handle\n },\n\n async tools(task, handle) {\n const endpoint = endpoints.get(handle.id)\n if (!endpoint) throw new Error(`${opts.name}: tools() before open() for ${handle.id}`)\n const { json } = await rpc(endpoint, {\n jsonrpc: '2.0',\n id: 1,\n method: 'tools/list',\n params: {},\n })\n const all = (\n (\n json as {\n result?: {\n tools?: Array<{ name: string; description?: string; inputSchema?: unknown }>\n }\n }\n ).result?.tools ?? []\n ).map(\n (t): AgenticTool => ({\n type: 'function',\n function: {\n name: t.name,\n description: (t.description ?? '').slice(0, 1000),\n parameters: sanitizeMcpToolSchema(t.inputSchema),\n },\n }),\n )\n return opts.selectTools ? opts.selectTools(task, all) : all\n },\n\n async call(handle, name, args) {\n const endpoint = endpoints.get(handle.id)\n if (!endpoint) return 'ERROR: workspace closed'\n const { json } = await rpc(endpoint, {\n jsonrpc: '2.0',\n id: 2,\n method: 'tools/call',\n params: { name, arguments: args },\n })\n const result =\n (json as {\n result?: { content?: Array<{ text?: string }>; isError?: boolean }\n error?: unknown\n }) ?? {}\n if (result.error) return `ERROR: ${JSON.stringify(result.error).slice(0, 300)}`\n const text =\n result.result?.content?.map((c) => c.text ?? '').join('\\n') ??\n JSON.stringify(result.result ?? json)\n return text.slice(0, maxChars)\n },\n\n score: (task, handle) => opts.score(task, handle),\n\n async close(handle) {\n endpoints.delete(handle.id)\n await opts.close?.(handle)\n },\n }\n}\n","/**\n * Same-host stdio MCP: the ONE persistent newline-delimited JSON-RPC 2.0\n * connection to a spawned MCP server child process. This is the handshake\n * `mcpServeVerifier` boots for its probe (`initialize` →\n * `notifications/initialized` → `tools/list`), extracted so a trusted\n * same-host consumer can keep the server running and route `tools/call` to it.\n * This module does not isolate the child: callers must use a real sandbox for\n * user- or model-authored code.\n *\n * Two layers:\n * - `connectStdioMcp` — spawn ONE server at its cwd, run the real MCP\n * handshake, return a live connection: the listed tools, `callTool`, `close`.\n * - `materializeLocalMcp` — spawn EVERY enabled stdio server in\n * `profile.mcp`, namespace each server's tools as `<server>__<tool>` so\n * they can share a worker's tool list with a domain surface's tools, and\n * expose one route/close facade over the set. Fail-CLOSED: a declared\n * server that cannot boot throws — silently scoring the profile as if it\n * had no MCP surface would fake the with/without ablation.\n *\n * Failure taxonomy (mirrors `commandVerifier`/`mcpServeVerifier`): a missing\n * start binary or spawn fault is a SETUP bug (`McpSpawnFault` — candidate\n * graders must rethrow it, never score it); a server that crashes, errors the\n * handshake, or times out is an ordinary `Error` carrying the stderr tail; a\n * JSON-RPC error on `tools/call` is the AGENT's outcome — returned as an\n * `ERROR: …` string, never thrown (the `createMcpEnvironment` convention).\n *\n * Protocol matches the runtime's own stdio MCP server (src/mcp/server.ts):\n * newline-delimited JSON-RPC 2.0, protocol version 2024-11-05.\n */\n\nimport { spawn } from 'node:child_process'\nimport { createInterface } from 'node:readline'\nimport {\n type AgentProfile,\n type AgentProfileSecurityPolicy,\n validateAgentProfileSecurity,\n} from '@tangle-network/agent-interface'\nimport {\n redactProtectedReason,\n redactProtectedValue,\n} from '../candidate-execution/protected-redaction'\nimport { ValidationError } from '../errors'\nimport { type KeyProvider, resolveMcpServerLaunch } from './key-provider'\nimport { sanitizeMcpToolSchema } from './mcp-environment'\nimport type { AgenticTool } from './strategy'\nimport { armDeadlineTimer } from './supervise/deadline'\n\nconst PROTOCOL_VERSION = '2024-11-05'\n\n/** Non-sensitive process settings a stdio child may inherit without receiving\n * credentials, agent settings, provider configuration, or tracing state. */\nconst SAFE_INHERITED_ENV_NAMES = [\n 'PATH',\n 'LANG',\n 'LC_ALL',\n 'LC_CTYPE',\n 'TZ',\n 'SYSTEMROOT',\n 'WINDIR',\n 'COMSPEC',\n 'PATHEXT',\n] as const\n\nfunction inheritedStdioEnv(source: NodeJS.ProcessEnv = process.env): Record<string, string> {\n const env: Record<string, string> = {}\n for (const name of SAFE_INHERITED_ENV_NAMES) {\n const value = source[name]\n if (value !== undefined) env[name] = value\n }\n return env\n}\n\nexport interface StdioMcpServerSpec {\n /** Command that starts the MCP server (stdio transport). */\n command: string\n args?: string[]\n /** Working directory the server starts in (a built candidate's worktree, typically). */\n cwd?: string\n /** Declared public env for the server process. Only a minimal non-sensitive\n * subset of the parent env is inherited. */\n env?: Record<string, string>\n /** Sensitive env for the server process. These values override `env` and are\n * redacted from child-supplied errors, tool metadata, and tool results. */\n protectedEnv?: Record<string, string>\n /** Handshake AND per-request timeout (ms). Default 30s. */\n timeoutMs?: number\n}\n\n/** A missing start binary / spawn fault: a SETUP bug, never a failed candidate.\n * Graders (the serve verifier) must rethrow this instead of scoring it. */\nexport class McpSpawnFault extends Error {}\n\nexport interface McpToolDescriptor {\n name: string\n description?: string\n inputSchema?: unknown\n}\n\nexport interface StdioMcpConnection {\n /** The tools the server exposed at connect time (`tools/list`). */\n readonly tools: readonly McpToolDescriptor[]\n /** `tools/call` → the result's text content. A JSON-RPC error / `isError`\n * result becomes an `ERROR: …` string (the agent's outcome); a dead\n * transport or timeout throws (an infra fault). */\n callTool(name: string, args: Record<string, unknown>): Promise<string>\n /** Kill the server child. Idempotent. */\n close(): Promise<void>\n}\n\ninterface JsonRpcResponse {\n jsonrpc?: string\n id?: number | string | null\n result?: unknown\n error?: { code: number; message: string }\n}\n\n/** Spawn a trusted host command, complete the stdio MCP handshake, and return\n * the live connection. This low-level function provides no process isolation. */\nexport async function connectStdioMcp(spec: StdioMcpServerSpec): Promise<StdioMcpConnection> {\n const timeoutMs = spec.timeoutMs ?? 30_000\n const protectedValues = Object.values(spec.protectedEnv ?? {})\n const redactReason = (value: string): string => redactProtectedReason(value, protectedValues)\n const child = spawn(spec.command, spec.args ?? [], {\n ...(spec.cwd ? { cwd: spec.cwd } : {}),\n stdio: ['pipe', 'pipe', 'pipe'],\n env: { ...inheritedStdioEnv(), ...spec.env, ...spec.protectedEnv },\n })\n\n const stderr: string[] = []\n child.stderr.on('data', (d) => stderr.push(String(d)))\n const stderrTail = () =>\n stderr.length > 0 ? `\\nstderr:\\n${redactReason(stderr.join('')).slice(-2000)}` : ''\n let nextId = 1\n let spawnFault: McpSpawnFault | undefined\n let closed = false\n const pending = new Map<\n number,\n { resolve: (r: JsonRpcResponse) => void; reject: (e: Error) => void; clearTimer: () => void }\n >()\n\n const failAllPending = (err: Error) => {\n for (const p of pending.values()) {\n p.clearTimer()\n p.reject(err)\n }\n pending.clear()\n }\n\n child.on('error', (err) => {\n const code = (err as NodeJS.ErrnoException).code\n spawnFault =\n code === 'ENOENT'\n ? new McpSpawnFault(\n `'${spec.command}' not found in PATH (setup bug, not a failed candidate)`,\n )\n : new McpSpawnFault(`'${spec.command}' failed to spawn: ${err.message}`)\n failAllPending(spawnFault)\n })\n // Pipe failures normally arrive asynchronously, OUTSIDE send()'s try/catch —\n // a server that closes stdin mid-handshake (EPIPE) must fail the pending\n // request immediately with the same wording as a synchronous write failure,\n // not wait out the handshake timeout.\n child.stdin.on('error', (err) => {\n failAllPending(\n new Error(redactReason(`writing to MCP server stdin failed: ${err.message}${stderrTail()}`)),\n )\n })\n // 'close' (not 'exit'): it fires after stdio flushes, so the stderr tail in\n // the failure message is complete. After our own SIGKILL in close(), pending\n // is already empty and this is a no-op.\n child.on('close', (code, signal) => {\n failAllPending(\n spawnFault ??\n new Error(\n redactReason(\n `MCP server exited (code ${code}, signal ${signal}) before serving${stderrTail()}`,\n ),\n ),\n )\n })\n\n const rl = createInterface({ input: child.stdout })\n rl.on('line', (line) => {\n let msg: JsonRpcResponse | undefined\n try {\n msg = JSON.parse(line) as JsonRpcResponse\n } catch {\n return // servers log to stdout too; skip non-JSON lines\n }\n if (!msg || typeof msg !== 'object' || typeof msg.id !== 'number') return\n const p = pending.get(msg.id)\n if (!p) return\n pending.delete(msg.id)\n p.clearTimer()\n p.resolve(msg)\n })\n\n const send = (msg: Record<string, unknown>): void => {\n child.stdin.write(`${JSON.stringify(msg)}\\n`)\n }\n\n const request = (\n method: string,\n params?: Record<string, unknown>,\n // The handshake-phase timeout keeps the verifier's long-standing feedback\n // wording; live tools/call timeouts name the method instead.\n timeoutMessage = `MCP server did not answer '${method}' within ${timeoutMs}ms`,\n ): Promise<JsonRpcResponse> =>\n new Promise<JsonRpcResponse>((resolve, reject) => {\n if (spawnFault) return reject(spawnFault)\n if (closed) return reject(new Error('MCP connection closed'))\n const id = nextId++\n const clearTimer = armDeadlineTimer(\n timeoutMs,\n () => {\n pending.delete(id)\n reject(new Error(redactReason(`${timeoutMessage}${stderrTail()}`)))\n },\n true,\n )\n pending.set(id, { resolve, reject, clearTimer })\n try {\n send({ jsonrpc: '2.0', id, method, ...(params ? { params } : {}) })\n } catch (err) {\n pending.delete(id)\n clearTimer()\n reject(\n new Error(\n redactReason(\n `writing to MCP server stdin failed: ${err instanceof Error ? err.message : String(err)}${stderrTail()}`,\n ),\n ),\n )\n }\n })\n\n const close = async (): Promise<void> => {\n if (closed) return\n closed = true\n rl.close()\n failAllPending(new Error('MCP connection closed'))\n child.kill('SIGKILL')\n }\n\n const handshakeTimeout = `MCP server did not complete the handshake within ${timeoutMs}ms`\n try {\n const init = await request(\n 'initialize',\n {\n protocolVersion: PROTOCOL_VERSION,\n capabilities: {},\n clientInfo: { name: 'agent-runtime-local-mcp', version: '0' },\n },\n handshakeTimeout,\n )\n if (init.error)\n throw new Error(\n redactReason(`initialize errored: ${JSON.stringify(init.error)}${stderrTail()}`),\n )\n send({ jsonrpc: '2.0', method: 'notifications/initialized' })\n const list = await request('tools/list', undefined, handshakeTimeout)\n if (list.error)\n throw new Error(\n redactReason(`tools/list errored: ${JSON.stringify(list.error)}${stderrTail()}`),\n )\n const rawTools = (list.result as { tools?: McpToolDescriptor[] } | undefined)?.tools\n if (!Array.isArray(rawTools))\n throw new Error(`tools/list result has no tools array${stderrTail()}`)\n const tools = redactProtectedValue(rawTools, protectedValues).value\n\n const callTool = async (name: string, args: Record<string, unknown>): Promise<string> => {\n const res = await request('tools/call', { name, arguments: args })\n if (res.error) return `ERROR: ${redactReason(JSON.stringify(res.error)).slice(0, 300)}`\n const result = res.result as\n | { content?: Array<{ text?: string }>; isError?: boolean }\n | undefined\n const chunks = result?.content?.map((c) => c.text ?? '')\n const joined = chunks?.join('\\n') ?? JSON.stringify(result ?? null)\n // MCP content blocks are joined with newlines for the worker. Also scan\n // their raw concatenation so a protected value split across two blocks\n // cannot evade exact-value redaction at the inserted newline.\n const collapsed = chunks?.join('')\n let text = joined\n if (collapsed !== undefined) {\n const collapsedRedacted = redactReason(collapsed)\n if (collapsedRedacted !== collapsed) text = collapsedRedacted\n }\n return redactReason(result?.isError ? `ERROR: ${text}` : text)\n }\n\n return { tools, callTool, close }\n } catch (err) {\n await close()\n throw err\n }\n}\n\nexport interface MaterializeLocalMcpOptions {\n /** Handshake / per-request timeout per server (ms). Default 30s. */\n timeoutMs?: number\n /** Cap on a tool result's text fed back to the worker. Default 2000 chars. */\n maxResultChars?: number\n /** Resolves a server's DECLARED secrets at spawn time — env entries of kind\n * `secret-ref` (interface ≥0.40) and the legacy `metadata.secretEnv` map\n * (env var name → provider key name). The resolved values reach ONLY the\n * child process env — never the profile, the logs, or an error message.\n * Fail-closed: a server declaring secrets without a provider (or with a\n * missing key) throws instead of booting keyless. */\n keys?: KeyProvider\n /** Required trust decision for profiles that declare local MCP processes.\n * Omit to refuse all profile-controlled host execution. Passing\n * `allowLocalMcp: true` is only safe for an author-controlled profile: the\n * process receives this Runtime's filesystem and network privileges. */\n profileSecurityPolicy?: AgentProfileSecurityPolicy\n}\n\n/** The live same-host materialization of a profile's `mcp` surface. */\nexport interface LocalMcpMaterialization {\n /** Worker-facing tool specs: namespaced `<server>__<tool>`, provider-safe schemas. */\n tools: AgenticTool[]\n /** Whether `name` is one of this materialization's namespaced tools. */\n owns(name: string): boolean\n /** Route a namespaced call to its server's live stdio child. */\n call(name: string, args: Record<string, unknown>): Promise<string>\n /** Kill every spawned server. Idempotent. */\n close(): Promise<void>\n}\n\n/**\n * Spawn every explicitly trusted stdio server in `profile.mcp` as a same-host\n * child and expose its tools under `<server>__<tool>` names. The default policy\n * refuses local processes. A profile with no MCP surface returns zero tools.\n */\nexport async function materializeLocalMcp(\n profile: AgentProfile,\n opts: MaterializeLocalMcpOptions = {},\n): Promise<LocalMcpMaterialization> {\n const security = validateAgentProfileSecurity(profile, opts.profileSecurityPolicy)\n if (!security.ok) {\n const reasons = security.issues\n .filter((issue) => issue.level === 'error')\n .map((issue) => issue.message)\n .join('; ')\n throw new ValidationError(`materializeLocalMcp: profile host execution refused: ${reasons}`)\n }\n const maxResultChars = opts.maxResultChars ?? 2000\n const connections: StdioMcpConnection[] = []\n const routes = new Map<string, { conn: StdioMcpConnection; tool: string }>()\n const tools: AgenticTool[] = []\n\n const close = async (): Promise<void> => {\n await Promise.all(connections.map((c) => c.close()))\n }\n\n try {\n for (const [key, server] of Object.entries(profile.mcp ?? {})) {\n if (server.enabled === false) continue\n const transport = server.transport ?? 'stdio'\n if (transport !== 'stdio') {\n throw new ValidationError(\n `materializeLocalMcp: profile.mcp['${key}'] has transport '${transport}' — the same-host client only spawns stdio servers; a remote (http/sse) server needs an http MCP client (not yet built here) or the sandbox backend. Failing loud: scoring this profile without its declared server would fake the with/without ablation`,\n )\n }\n if (!server.command || server.command.trim().length === 0) {\n throw new ValidationError(\n `materializeLocalMcp: profile.mcp['${key}'] declares a stdio server with no command`,\n )\n }\n // Resolve profile config values (public args/env, env secret-refs, and\n // the legacy metadata.secretEnv channel) into spawn strings NOW. The\n // resolved secret values live in this local and the child env — nowhere\n // else — and every resolution failure aborts the whole materialization.\n const launch = await resolveMcpServerLaunch(\n server,\n opts.keys,\n `materializeLocalMcp: profile.mcp['${key}']`,\n )\n const conn = await connectStdioMcp({\n command: server.command,\n ...(launch.args ? { args: launch.args } : {}),\n ...(server.cwd ? { cwd: server.cwd } : {}),\n ...(launch.env ? { env: launch.env } : {}),\n ...(launch.protectedEnv ? { protectedEnv: launch.protectedEnv } : {}),\n ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),\n })\n connections.push(conn)\n const prefix = key.replace(/[^a-zA-Z0-9_-]/g, '_')\n for (const t of conn.tools) {\n const name = `${prefix}__${t.name.replace(/[^a-zA-Z0-9_-]/g, '_')}`\n if (routes.has(name)) {\n throw new ValidationError(\n `materializeLocalMcp: namespaced tool '${name}' collides across servers — rename the profile.mcp keys`,\n )\n }\n routes.set(name, { conn, tool: t.name })\n tools.push({\n type: 'function',\n function: {\n name,\n description: (t.description ?? '').slice(0, 1000),\n parameters: sanitizeMcpToolSchema(t.inputSchema),\n },\n })\n }\n }\n } catch (err) {\n // Fail CLOSED: never hand back a partial materialization of a profile\n // whose declared server could not boot — that would fake the ablation.\n await close()\n throw err\n }\n\n return {\n tools,\n owns: (name) => routes.has(name),\n call: async (name, args) => {\n const route = routes.get(name)\n if (!route) throw new Error(`materializeLocalMcp: unknown tool '${name}'`)\n const out = await route.conn.callTool(route.tool, args)\n return out.length > maxResultChars ? out.slice(0, maxResultChars) : out\n },\n close,\n }\n}\n","/**\n * SQL-backed durable stores for supervised runs — `SqlSpawnJournal` and `SqlResultBlobStore`\n * over the same minimal statement seam `SqlConversationJournal` uses (D1, postgres, sqlite,\n * libSQL; positional `?` placeholders). This closes the orchestration-durability gap recorded in\n * `conformance/durability/STATUS.md`: until now the spawn layer was file-only.\n *\n * Parity with the JSONL file stores, by construction:\n * • same corruption guards — `beginTree` precedes events (enforced by the schema: an event row\n * names a tree row), duplicate cursor seqs and duplicate materialization receipts are refused\n * by the same `SpawnEventIndex` the file journal replays through, on both append and load;\n * • same content-address law for blobs — a `put` whose ref does not hash to the artifact is\n * refused, a re-put of the same ref asserts the identical bytes;\n * • load order is insertion order (`INTEGER PRIMARY KEY AUTOINCREMENT`), the SQL analogue of\n * the JSONL append-only spine.\n *\n * Durability note: this suite and its process-kill test run against `node:sqlite`, whose\n * autocommit commits survive SIGKILL (process death, not OS crash). A deployment that must\n * survive power loss sets its driver's synchronous mode (`PRAGMA synchronous=FULL` + WAL) at the\n * adapter; agent-runtime takes no opinion.\n *\n * @experimental — draft: cross-process ownership is single-writer by convention (the same\n * limitation `createFileRunContext` documents); a machine-visible ownership lease is follow-up.\n */\n\nimport { detachedSnapshot } from '../runtime/supervise/snapshot'\nimport type { NodeId, ResultBlobStore, SpawnEvent, SpawnJournal } from '../runtime/supervise/types'\nimport { assertContentAddress, encodeResultBlob, SpawnEventIndex } from './spawn-journal'\n\n/** The minimal statement seam; structurally the same shape `SqlConversationJournal` accepts. */\nexport interface SqlStatements {\n /** Execute a write statement (INSERT/UPDATE/DELETE/DDL). */\n exec(sql: string, params?: readonly unknown[]): Promise<{ rowsAffected: number }>\n /** Execute a read statement (SELECT). Returns rows as plain objects. */\n query<TRow = Record<string, unknown>>(sql: string, params?: readonly unknown[]): Promise<TRow[]>\n}\n\nconst TREES_DDL = (table: string) => `\n CREATE TABLE IF NOT EXISTS ${table}_trees (\n root TEXT PRIMARY KEY,\n begun_at TEXT NOT NULL\n )\n`\nconst EVENTS_DDL = (table: string) => `\n CREATE TABLE IF NOT EXISTS ${table}_events (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n root TEXT NOT NULL REFERENCES ${table}_trees (root),\n body TEXT NOT NULL\n )\n`\nconst BLOBS_DDL = (table: string) => `\n CREATE TABLE IF NOT EXISTS ${table}_blobs (\n ref TEXT PRIMARY KEY,\n body TEXT NOT NULL\n )\n`\n\n/** SQL-backed `SpawnJournal`. One row per event; insertion order is replay order. */\nexport class SqlSpawnJournal implements SpawnJournal {\n private readonly table: string\n // Rebuildable validation state, lazily keyed by the tree's max event id (the SQL analogue of\n // the file journal's stamp check): an unacknowledged append cannot advance it.\n private readonly cache = new Map<NodeId, { maxId: number; index: SpawnEventIndex }>()\n private appendTail: Promise<void> = Promise.resolve()\n\n constructor(\n private readonly db: SqlStatements,\n table = 'runtime_spawn_journal',\n ) {\n this.table = table\n }\n\n /** Create the journal's tables if absent. Idempotent. */\n async migrate(): Promise<void> {\n await this.db.exec(TREES_DDL(this.table))\n await this.db.exec(EVENTS_DDL(this.table))\n }\n\n async loadTree(root: NodeId): Promise<SpawnEvent[] | undefined> {\n const trees = await this.db.query<{ begun_at: string }>(\n `SELECT begun_at FROM ${this.table}_trees WHERE root = ?`,\n [root],\n )\n if (trees.length === 0) return undefined\n const rows = await this.db.query<{ id: number; body: string }>(\n `SELECT id, body FROM ${this.table}_events WHERE root = ? ORDER BY id`,\n [root],\n )\n const index = new SpawnEventIndex(root)\n const events: SpawnEvent[] = []\n for (const row of rows) {\n const event = JSON.parse(row.body) as SpawnEvent\n index.assert(event)\n index.add(event)\n events.push(event)\n }\n return events\n }\n\n async beginTree(root: NodeId, at: string): Promise<void> {\n return this.serializeAppend(async () => {\n await this.ensureMigrated()\n const existing = await this.db.query<{ begun_at: string }>(\n `SELECT begun_at FROM ${this.table}_trees WHERE root = ?`,\n [root],\n )\n if (existing.length > 0) {\n const begunAt = existing[0]?.begun_at\n if (begunAt !== at) {\n throw new Error(\n `spawn tree '${root}' already begun in SQL at ${begunAt}; refusing to overwrite with ${at}`,\n )\n }\n return\n }\n await this.db.exec(`INSERT INTO ${this.table}_trees (root, begun_at) VALUES (?, ?)`, [\n root,\n at,\n ])\n this.cache.set(root, { maxId: 0, index: new SpawnEventIndex(root) })\n })\n }\n\n async appendEvent(root: NodeId, ev: SpawnEvent): Promise<void> {\n const event = detachedSnapshot(ev, 'spawn event')\n return this.serializeAppend(async () => {\n await this.ensureMigrated()\n const state = await this.validationIndex(root)\n // Assert BEFORE the write, exactly as the file journal does: a refused event must never\n // reach the table, or a later replay would find the corruption it refused.\n state.index.assert(event)\n const written = await this.db.exec(\n `INSERT INTO ${this.table}_events (root, body) VALUES (?, ?)`,\n [root, JSON.stringify(event)],\n )\n if (written.rowsAffected !== 1) {\n throw new Error(`spawn journal SQL: append of an event for tree '${root}' affected no rows`)\n }\n state.index.add(event)\n state.maxId = await this.maxEventId(root)\n })\n }\n\n private async validationIndex(root: NodeId): Promise<{ maxId: number; index: SpawnEventIndex }> {\n const begun = await this.db.query<{ begun_at: string }>(\n `SELECT begun_at FROM ${this.table}_trees WHERE root = ?`,\n [root],\n )\n if (begun.length === 0) {\n throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`)\n }\n const max = await this.maxEventId(root)\n const cached = this.cache.get(root)\n if (cached && cached.maxId === max) return cached\n const index = new SpawnEventIndex(root)\n if (max > 0) {\n const rows = await this.db.query<{ body: string }>(\n `SELECT body FROM ${this.table}_events WHERE root = ? ORDER BY id`,\n [root],\n )\n for (const row of rows) {\n const event = JSON.parse(row.body) as SpawnEvent\n index.assert(event)\n index.add(event)\n }\n }\n const state = { maxId: max, index }\n this.cache.set(root, state)\n return state\n }\n\n private async maxEventId(root: NodeId): Promise<number> {\n const rows = await this.db.query<{ max: number | null }>(\n `SELECT MAX(id) AS max FROM ${this.table}_events WHERE root = ?`,\n [root],\n )\n return rows[0]?.max ?? 0\n }\n\n private migrated = false\n\n private async ensureMigrated(): Promise<void> {\n if (this.migrated) return\n await this.migrate()\n this.migrated = true\n }\n\n private serializeAppend(operation: () => Promise<void>): Promise<void> {\n const append = this.appendTail.then(operation)\n this.appendTail = append.catch(() => undefined)\n return append\n }\n}\n\n/** SQL-backed `ResultBlobStore`. One content-addressed row per settled result. */\nexport class SqlResultBlobStore implements ResultBlobStore {\n private migrated = false\n\n constructor(\n private readonly db: SqlStatements,\n private readonly table = 'runtime_result_blobs',\n ) {}\n\n async migrate(): Promise<void> {\n await this.db.exec(BLOBS_DDL(this.table))\n }\n\n async put(outRef: string, artifact: unknown): Promise<void> {\n await this.ensureMigrated()\n const { text } = encodeResultBlob(outRef, artifact)\n const written = await this.db.exec(\n `INSERT OR IGNORE INTO ${this.table}_blobs (ref, body) VALUES (?, ?)`,\n [outRef, text],\n )\n if (written.rowsAffected === 1) return\n // Same ref seen twice: the content-address law must hold for BOTH writers.\n assertContentAddress(outRef, await this.get(outRef))\n }\n\n async get(outRef: string): Promise<unknown | undefined> {\n await this.ensureMigrated()\n const rows = await this.db.query<{ body: string }>(\n `SELECT body FROM ${this.table}_blobs WHERE ref = ?`,\n [outRef],\n )\n if (rows.length === 0) return undefined\n const artifact: unknown = JSON.parse(rows[0]?.body ?? 'null')\n assertContentAddress(outRef, artifact)\n return artifact\n }\n\n private async ensureMigrated(): Promise<void> {\n if (this.migrated) return\n await this.migrate()\n this.migrated = true\n }\n}\n","import { createHash, randomUUID } from 'node:crypto'\nimport type { SqlAdapter } from '../conversation/journal-sql'\n\n/** @internal The SQL run context owns the payload schema; this store owns publication. */\nexport interface SqlRunStoreOptions {\n readonly tablePrefix?: string\n readonly leaseMs?: number\n readonly heartbeatMs?: number\n}\n\ninterface Head {\n run_id: string\n owner: string\n generation: number\n pulse: number\n head: string\n revision: number\n lease_ms: number\n namespace: string\n}\n\ninterface RecordRow {\n id: string\n parent: string\n revision: number\n payload: string\n}\n\n/** Refuses a competing or stale SQL run owner before it can publish new work. */\nexport class SqlRunOwnershipError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'SqlRunOwnershipError'\n }\n}\n\n/** @internal An immutable ownership capability. Never rebound to a later generation. */\nexport interface SqlRunLease<Payload> {\n readonly signal: AbortSignal\n readonly records: readonly Payload[]\n append(payload: Payload): Promise<void>\n release(): Promise<void>\n}\n\n/**\n * Append-only immutable records, published by ONE compare-and-set of the run's head.\n *\n * SqlAdapter has no pinned-connection transaction API. INSERT ... SELECT owner is NOT a\n * fence on MVCC databases: its snapshot can outlive a takeover. Here both publication and\n * takeover UPDATE the SAME row. Unpublished records are harmless, unreachable staging.\n * Healthy appends write only their new payload and one fixed-size head, never the history.\n *\n * Liveness uses a persisted progress counter, not incomparable host clocks. A contender must\n * observe the SAME generation/counter for leaseMs before replacing it with a CAS. Every\n * heartbeat and publication advances that counter. The interval is stored per run so a\n * differently configured contender cannot shorten an existing owner's lease.\n * @internal\n */\nexport async function openSqlRunStore<Payload>(\n db: SqlAdapter,\n runId: string,\n options: SqlRunStoreOptions = {},\n): Promise<{\n readonly namespace: string\n read(): Promise<readonly Payload[]>\n acquire(signal?: AbortSignal): Promise<SqlRunLease<Payload>>\n}> {\n const prefix = options.tablePrefix ?? 'agent_run'\n const leaseMs = options.leaseMs ?? 30_000\n const heartbeatMs = options.heartbeatMs ?? Math.floor(leaseMs / 3)\n if (!/^[A-Za-z_][A-Za-z0-9_]{0,39}$/.test(prefix)) {\n throw new Error('SQL run context tablePrefix must be a SQL identifier of at most 40 characters')\n }\n if (typeof runId !== 'string' || runId.length === 0) throw new Error('SQL runId must be nonempty')\n if (!Number.isSafeInteger(leaseMs) || leaseMs < 100 || leaseMs > 2_147_483_647) {\n throw new Error('SQL leaseMs must be an integer between 100 and 2147483647')\n }\n if (!Number.isSafeInteger(heartbeatMs) || heartbeatMs < 1 || heartbeatMs > leaseMs / 3) {\n throw new Error('SQL heartbeatMs must be a positive integer no greater than leaseMs / 3')\n }\n const heads = `${prefix}_heads`\n const records = `${prefix}_records`\n await db.exec(`CREATE TABLE IF NOT EXISTS ${heads} (\n run_id TEXT PRIMARY KEY,\n owner TEXT NOT NULL,\n generation INTEGER NOT NULL,\n pulse INTEGER NOT NULL,\n head TEXT NOT NULL,\n revision INTEGER NOT NULL,\n lease_ms INTEGER NOT NULL,\n namespace TEXT NOT NULL\n )`)\n await db.exec(`CREATE TABLE IF NOT EXISTS ${records} (\n run_id TEXT NOT NULL,\n id TEXT NOT NULL,\n parent TEXT NOT NULL,\n revision INTEGER NOT NULL,\n payload TEXT NOT NULL,\n PRIMARY KEY (run_id, id)\n )`)\n await db.exec(\n `INSERT INTO ${heads} (run_id, owner, generation, pulse, head, revision, lease_ms, namespace)\n VALUES (?, '', 0, 0, '', 0, ?, ?) ON CONFLICT (run_id) DO NOTHING`,\n [runId, leaseMs, randomUUID()],\n )\n\n async function readHead(): Promise<Head> {\n const [row] = await db.query<Head>(`SELECT * FROM ${heads} WHERE run_id = ?`, [runId])\n if (!row) throw new Error(`SQL run '${runId}' has no head`)\n for (const key of ['generation', 'pulse', 'revision', 'lease_ms'] as const) {\n row[key] = Number(row[key])\n if (!Number.isSafeInteger(row[key]) || row[key] < 0) {\n throw new Error(`SQL run '${runId}' has an invalid ${key}`)\n }\n }\n if (\n typeof row.namespace !== 'string' ||\n row.namespace.length === 0 ||\n typeof row.head !== 'string' ||\n typeof row.owner !== 'string' ||\n (row.head === '') !== (row.revision === 0)\n ) {\n throw new Error(`SQL run '${runId}' has an invalid head`)\n }\n if (row.lease_ms !== leaseMs) {\n throw new Error(\n `SQL run '${runId}' lease configuration differs: recorded ${row.lease_ms}ms, requested ${leaseMs}ms`,\n )\n }\n return row\n }\n\n async function load(head: Head): Promise<Payload[]> {\n if (head.revision === 0) return []\n // The head was committed AFTER every node it reaches. This reads a consistent immutable\n // cut without a multi-statement read transaction, even if another process appends now.\n const rows = await db.query<RecordRow>(\n `SELECT id, parent, revision, payload FROM ${records} WHERE run_id = ? AND revision <= ?`,\n [runId, head.revision],\n )\n const byId = new Map(rows.map((row) => [row.id, row]))\n const history: Payload[] = []\n let id = head.head\n for (let revision = head.revision; revision > 0; revision -= 1) {\n const row = byId.get(id)\n if (\n !row ||\n Number(row.revision) !== revision ||\n recordId(row.parent, revision, row.payload) !== id\n ) {\n throw new Error(\n `SQL run '${runId}' has a missing or corrupt committed record at revision ${revision}`,\n )\n }\n history.push(JSON.parse(row.payload) as Payload)\n id = row.parent\n }\n if (id !== '') throw new Error(`SQL run '${runId}' has an invalid history origin`)\n return history.reverse()\n }\n\n // Validate the shared policy at construction, before any caller can take ownership.\n const initial = await readHead()\n\n return {\n namespace: initial.namespace,\n async read() {\n return load(await readHead())\n },\n async acquire(signal) {\n signal?.throwIfAborted()\n const observed = await readHead()\n if (observed.owner !== '') await wait(leaseMs, signal)\n signal?.throwIfAborted()\n const owner = randomUUID()\n let claimed = false\n try {\n const result = await db.exec(\n `UPDATE ${heads} SET owner = ?, generation = generation + 1, pulse = pulse + 1\n WHERE run_id = ? AND owner = ? AND generation = ? AND pulse = ?`,\n [owner, runId, observed.owner, observed.generation, observed.pulse],\n )\n claimed = result.rowsAffected === 1\n } catch (error) {\n // A lost claim acknowledgement must not leak or accidentally mint two capabilities.\n const current = await readHead().catch(() => undefined)\n if (current?.owner !== owner) throw error\n claimed = true\n }\n if (!claimed)\n throw new SqlRunOwnershipError(`SQL run '${runId}' is owned by another live process`)\n const generation = observed.generation + 1\n const controller = new AbortController()\n let accepting = true\n let released: Promise<void> | undefined\n let tail: Promise<void> = Promise.resolve()\n let heartbeat: Promise<void> | undefined\n let progressAt = performance.now()\n let head = observed.head\n let revision = observed.revision\n let history: Payload[] = []\n const lose = (error: unknown) => {\n accepting = false\n clearInterval(timer)\n controller.abort(error)\n }\n const timer = setInterval(() => {\n if (controller.signal.aborted) return\n if (performance.now() - progressAt >= leaseMs) {\n lose(new SqlRunOwnershipError(`SQL run '${runId}' lease heartbeat expired`))\n return\n }\n if (heartbeat) return\n heartbeat = db\n .exec(\n `UPDATE ${heads} SET pulse = pulse + 1 WHERE run_id = ? AND owner = ? AND generation = ?`,\n [runId, owner, generation],\n )\n .then((result) => {\n if (result.rowsAffected !== 1)\n throw new SqlRunOwnershipError(`SQL run '${runId}' lease was replaced`)\n progressAt = performance.now()\n })\n .catch(lose)\n .finally(() => {\n heartbeat = undefined\n })\n }, heartbeatMs)\n timer.unref()\n\n const lease: SqlRunLease<Payload> = {\n signal: controller.signal,\n get records() {\n return JSON.parse(JSON.stringify(history)) as Payload[]\n },\n append(payload) {\n if (!accepting)\n return Promise.reject(\n controller.signal.reason ??\n new SqlRunOwnershipError(`SQL run '${runId}' lease is released`),\n )\n // Detach BEFORE queueing. Caller mutation cannot change a promised record.\n let encoded: string\n try {\n encoded = JSON.stringify(payload)\n if (encoded === undefined) throw new Error('SQL run records must be JSON serializable')\n } catch (error) {\n return Promise.reject(error)\n }\n const write = tail.then(async () => {\n controller.signal.throwIfAborted()\n const nextRevision = revision + 1\n const id = recordId(head, nextRevision, encoded)\n try {\n await db.exec(\n `INSERT INTO ${records} (run_id, id, parent, revision, payload) VALUES (?, ?, ?, ?, ?)\n ON CONFLICT (run_id, id) DO NOTHING`,\n [runId, id, head, nextRevision, encoded],\n )\n } catch (error) {\n const [staged] = await db\n .query<RecordRow>(\n `SELECT id, parent, revision, payload FROM ${records} WHERE run_id = ? AND id = ?`,\n [runId, id],\n )\n .catch(() => [])\n if (\n !staged ||\n staged.payload !== encoded ||\n staged.parent !== head ||\n Number(staged.revision) !== nextRevision\n )\n throw error\n }\n controller.signal.throwIfAborted()\n let published = false\n let failure: unknown\n try {\n const result = await db.exec(\n `UPDATE ${heads} SET head = ?, revision = ?, pulse = pulse + 1\n WHERE run_id = ? AND owner = ? AND generation = ? AND head = ? AND revision = ?`,\n [id, nextRevision, runId, owner, generation, head, revision],\n )\n published = result.rowsAffected === 1\n } catch (error) {\n failure = error\n }\n if (!published) {\n const current = await readHead()\n if (current.owner !== owner || current.generation !== generation) {\n throw new SqlRunOwnershipError(\n `SQL run '${runId}' lease was replaced before publication`,\n )\n }\n // The same committed head is the receipt for a lost UPDATE acknowledgement.\n if (current.head !== id || current.revision !== nextRevision) {\n throw (\n failure ?? new SqlRunOwnershipError(`SQL run '${runId}' publication conflicted`)\n )\n }\n }\n controller.signal.throwIfAborted()\n head = id\n revision = nextRevision\n history.push(JSON.parse(encoded) as Payload)\n progressAt = performance.now()\n })\n tail = write.catch(lose)\n return write\n },\n release() {\n if (released) return released\n accepting = false\n released = (async () => {\n // Finish already-admitted writes while the heartbeat still protects their owner.\n await tail\n clearInterval(timer)\n // A stalled heartbeat cannot extend this capability after release: its UPDATE is fenced.\n try {\n await db.exec(\n `UPDATE ${heads} SET owner = '', pulse = pulse + 1 WHERE run_id = ? AND owner = ? AND generation = ?`,\n [runId, owner, generation],\n )\n } finally {\n controller.abort(new SqlRunOwnershipError(`SQL run '${runId}' lease is released`))\n }\n })()\n return released\n },\n }\n try {\n history = await load(observed)\n signal?.throwIfAborted()\n controller.signal.throwIfAborted()\n return lease\n } catch (error) {\n await lease.release().catch(() => undefined)\n throw error\n }\n },\n }\n}\n\nfunction recordId(parent: string, revision: number, payload: string): string {\n return createHash('sha256').update(`${revision}\\0${parent}\\0${payload}`).digest('hex')\n}\n\nfunction wait(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const cleanup = () => signal?.removeEventListener('abort', abort)\n const timer = setTimeout(() => {\n cleanup()\n resolve()\n }, ms)\n const abort = () => {\n clearTimeout(timer)\n cleanup()\n reject(signal?.reason)\n }\n if (signal?.aborted) abort()\n else signal?.addEventListener('abort', abort, { once: true })\n })\n}\n","/**\n * auditIntent — the route-rigor analyst: is this trajectory even going the RIGHT WAY?\n *\n * `observe()` critiques execution quality (\"what's unfinished\"). This audits ALIGNMENT —\n * a different failure class the score can't see until it's too late: an agent can be\n * executing flawlessly down the wrong route. The auditor reads the trajectory and\n * compares three intents:\n *\n * declared — what the task says to do (the prompt / acceptance criteria)\n * revealed — what the agent is ACTUALLY optimizing, inferred from its action pattern\n * (the inverse-inference move: actions reveal objectives)\n * user — what the principal actually wants (the contract, when it differs from\n * the literal task text), plus where the user's own trajectory is heading\n *\n * and returns a verdict (aligned / drifting / diverged) with evidence and ONE\n * recommended intervention. FIREWALLED like every analyst: input is the trajectory and\n * the intents — never the verifier or its data (zero check-leakage, so route auditing\n * is always Goodhart-safe to run online).\n *\n * Where it runs: between shots (steer the next one), as a watchdog over the lifecycle\n * stream (abort-and-refund a diverged rollout — the budget pool makes early abort\n * strictly valuable), or post-hoc over a whole BenchmarkReport (the meta-intent pass:\n * is the LOOP optimizing the right thing — degenerate submissions, check-gaming shapes,\n * objective drift across tasks).\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { profileChatClient } from './profile-chat-client'\nimport type { ExecutorConfig } from './supervise/runtime'\n\nexport interface AuditIntentInput {\n /** The declared intent: the task text / acceptance criteria the agent was given. */\n declaredIntent: string\n /** The trajectory so far — tool calls + results + assistant turns (any event shapes). */\n trace: ReadonlyArray<unknown>\n /** The principal's actual intent when it differs from the literal task (the contract). */\n userIntent?: string\n /** The loop-level purpose (meta-intent): what the WHOLE run is for — lets the auditor\n * flag locally-sensible work that serves the wrong larger objective. */\n metaIntent?: string\n runId?: string\n}\n\nexport interface AuditIntentOptions {\n /** Exact auditor identity. */\n profile: AgentProfile\n /** Execution substrate. All behavior comes from the profile. */\n executor: ExecutorConfig\n /** Cap trace lines fed to the auditor. Default 80. */\n maxTraceLines?: number\n signal?: AbortSignal\n}\n\nexport interface IntentAudit {\n /** What the agent's actions reveal it is actually optimizing — one sentence. */\n revealedIntent: string\n verdict: 'aligned' | 'drifting' | 'diverged'\n /** Trajectory-grounded evidence for the verdict (specific calls/patterns). */\n evidence: string\n /** The single recommended intervention. */\n recommendation: 'continue' | 'steer' | 'abort'\n /** When recommendation is 'steer': the corrective instruction to inject. */\n steer?: string\n confidence: number\n}\n\n/** Default system instruction for intent-auditor agents: diagnose diverged/drifting trajectories. */\nexport const defaultAuditorInstruction =\n 'You audit whether an AI agent is on the RIGHT ROUTE — not whether it works hard, but whether its ' +\n 'actions serve the stated intents. Infer the REVEALED intent from the action pattern (what the ' +\n 'trajectory is actually optimizing). Compare against the declared task intent, the user intent when ' +\n 'given, and the meta-intent when given. Flawless execution down the wrong route is DIVERGED. ' +\n 'Busy-work that neither advances nor harms is DRIFTING. Judge only from the trajectory — be specific ' +\n 'about which actions ground your verdict. Recommend abort only when continuing cannot serve the intent.'\n\nfunction summarize(trace: ReadonlyArray<unknown>, maxLines: number): string {\n const lines: string[] = []\n for (const ev of trace) {\n const e = ev as Record<string, unknown>\n const role = e.role as string | undefined\n if (role === 'tool') lines.push(`RESULT ${String(e.content).slice(0, 200)}`)\n else if (role === 'assistant') {\n const calls = (\n e.tool_calls as Array<{ function?: { name?: string; arguments?: string } }> | undefined\n )\n ?.map((c) => `${c.function?.name}(${(c.function?.arguments ?? '').slice(0, 120)})`)\n .join(', ')\n lines.push(calls ? `CALL ${calls}` : `SAY ${String(e.content).slice(0, 160)}`)\n } else if (role === 'user') lines.push(`USER ${String(e.content).slice(0, 160)}`)\n }\n return lines.slice(-maxLines).join('\\n')\n}\n\nconst auditSchema = {\n name: 'intent_audit',\n schema: {\n type: 'object',\n additionalProperties: false,\n required: ['revealedIntent', 'verdict', 'evidence', 'recommendation', 'confidence'],\n properties: {\n revealedIntent: { type: 'string' },\n verdict: { type: 'string', enum: ['aligned', 'drifting', 'diverged'] },\n evidence: { type: 'string' },\n recommendation: { type: 'string', enum: ['continue', 'steer', 'abort'] },\n steer: { type: 'string' },\n confidence: { type: 'number' },\n },\n },\n}\n\n/** The route-rigor analyst: compare declared vs revealed vs user intent over a trajectory and return aligned / drifting / diverged with evidence and one recommended intervention. */\nexport async function auditIntent(\n input: AuditIntentInput,\n opts: AuditIntentOptions,\n): Promise<IntentAudit> {\n const res = await profileChatClient({\n profile: opts.profile,\n executor: opts.executor,\n context: 'intent auditor',\n }).chat(\n {\n jsonSchema: auditSchema as unknown as { name: string; schema: Record<string, unknown> },\n messages: [\n {\n role: 'user',\n content:\n `DECLARED INTENT (the task):\\n${input.declaredIntent}\\n\\n` +\n (input.userIntent\n ? `USER INTENT (the principal's actual goal):\\n${input.userIntent}\\n\\n`\n : '') +\n (input.metaIntent\n ? `META-INTENT (what the whole run is for):\\n${input.metaIntent}\\n\\n`\n : '') +\n `TRAJECTORY (in order):\\n${summarize(input.trace, opts.maxTraceLines ?? 80)}\\n\\n` +\n 'Audit the route: revealed intent, verdict, evidence, one recommendation.',\n },\n ],\n },\n { ...(opts.signal ? { signal: opts.signal } : {}) },\n )\n let parsed: Partial<IntentAudit>\n try {\n parsed = JSON.parse(res.content) as Partial<IntentAudit>\n } catch {\n throw new Error(`auditIntent: auditor returned non-JSON: ${res.content.slice(0, 200)}`)\n }\n if (!parsed.verdict || !parsed.recommendation) {\n throw new Error(`auditIntent: missing verdict/recommendation: ${res.content.slice(0, 200)}`)\n }\n return {\n revealedIntent: parsed.revealedIntent ?? '',\n verdict: parsed.verdict,\n evidence: parsed.evidence ?? '',\n recommendation: parsed.recommendation,\n ...(parsed.steer ? { steer: parsed.steer } : {}),\n confidence: typeof parsed.confidence === 'number' ? parsed.confidence : 0.5,\n }\n}\n","/**\n * benchmark-report — turn a fleet of `RunRecord`s into a publishable, multi-axis benchmark report:\n * a ranked leaderboard, the full profile×axis score matrix, the cost/latency/token columns, and\n * embeddable charts (SVG) + a self-contained HTML page. Domain-agnostic by construction — it reads ONLY\n * the universal `RunRecord` currency (model, scenario, score, cost, tokens, latency, the `outcome.raw`\n * metric bag), so the SAME engine reports any benchmark in any domain: coding, search, agents, multimodal.\n *\n * This is the surface a hosted leaderboard (à la vals.ai) renders: for every harness×model profile, its\n * score on every axis, not a curated subset. It pairs with `runProfileMatrix` (whose `result.records`\n * feed straight in) but takes the records directly, so it is independent of how they were produced.\n *\n * An AXIS is any way to slice the score into columns — by default one column per scenario group\n * (`groupOf`, default = the scenario id), so the matrix is profile × scenario. Pass `axisScoresOf` to\n * score along judge dimensions or any custom decomposition instead. The reporter never invents a number:\n * a missing cell renders blank, never zero.\n */\nimport {\n benjaminiHochberg,\n confidenceInterval,\n pairedBootstrap,\n type RankTestMethod,\n type RunRecord,\n wilcoxonSignedRank,\n wilson,\n} from '@tangle-network/agent-eval'\n\n/** Pull the headline score in [0,1] from a record. Default: the held-out split, else the search split,\n * else a `composite`/`passed`/`score` entry in the raw bag. Override to score a domain differently. */\nexport type ScoreOf = (record: RunRecord) => number | undefined\n/** The profile (matrix row) a record belongs to — default `harness·model` from the record's profile cell,\n * falling back to the model. This is the leaderboard's unit of comparison. */\nexport type ProfileKeyOf = (record: RunRecord) => string\n/** The axis (matrix column) a record contributes to — default the scenario group. */\nexport type GroupOf = (record: RunRecord) => string\n/** Decompose ONE record into per-axis scores (e.g. judge dimensions). When set, it REPLACES the\n * scenario-group axes: the column set is the union of returned keys. */\nexport type AxisScoresOf = (record: RunRecord) => Record<string, number>\n\nexport interface LeaderboardOptions {\n readonly title?: string\n readonly scoreOf?: ScoreOf\n readonly profileKeyOf?: ProfileKeyOf\n readonly groupOf?: GroupOf\n readonly axisScoresOf?: AxisScoresOf\n /** Display label for a profile key (default: the key itself). */\n readonly labelOf?: (profileKey: string) => string\n /** Commit SHA / dataset / dates surfaced in the provenance block. */\n readonly meta?: Record<string, string>\n /** Compute per-row confidence intervals (bootstrap on score, Wilson on pass rate). Needs a\n * `scenarioId` on every record (reps are collapsed per scenario for the honest n). Default off. */\n readonly stats?: boolean\n /** A score ≥ this counts as a \"pass\" for the pass-rate proportion + its Wilson CI. Default 0.999\n * (fully solved). Lower it (e.g. 0.6) for a partial-credit domain. */\n readonly passThreshold?: number\n}\n\n/** A 95%-by-default confidence interval. */\nexport interface Interval {\n readonly lower: number\n readonly upper: number\n}\n\n/** One leaderboard row — a harness×model profile, every measured column. */\nexport interface LeaderboardRow {\n readonly profileKey: string\n readonly label: string\n readonly model: string\n readonly n: number\n readonly meanScore: number\n /** Fraction of records scoring ≥ `passThreshold` (default 0.999) — the binary pass rate. */\n readonly solveRate: number\n /** axis → mean score for this profile (blank in render when the profile never ran that axis). */\n readonly perAxis: Record<string, number>\n /** Exact total when every run captured cost; otherwise `null`. */\n readonly costUsd: number | null\n /** Sum of captured cost only. This is a lower bound when `uncapturedCostRuns > 0`. */\n readonly capturedCostUsd: number\n /** Runs whose cost was unavailable, never treated as free. */\n readonly uncapturedCostRuns: number\n readonly tokensIn: number\n readonly tokensOut: number\n readonly latencyP50Ms: number\n readonly latencyP90Ms: number\n /** Bootstrap CI on the mean score — present only when `opts.stats` is set. Computed over\n * per-scenario means (reps collapsed first), so identical reps can't fake a narrow interval. */\n readonly scoreCi?: Interval\n /** Wilson CI on the pass rate — present only when `opts.stats` is set. */\n readonly passCi?: Interval\n}\n\nexport interface Leaderboard {\n readonly title: string\n /** Column order — scenario groups (default) or dimension keys (`axisScoresOf`). */\n readonly axes: readonly string[]\n /** Rows ranked by `meanScore` desc (ties → lower cost, then label). */\n readonly profiles: readonly LeaderboardRow[]\n readonly meta: Record<string, string>\n /** Provenance counts — the denominators every honest report leads with. */\n readonly provenance: {\n readonly records: number\n readonly profiles: number\n readonly axes: number\n readonly models: readonly string[]\n /** Exact total when every record captured cost; otherwise `null`. */\n readonly totalCostUsd: number | null\n /** Sum of captured cost only. */\n readonly capturedCostUsd: number\n /** Records whose cost was unavailable. */\n readonly uncapturedCostRecords: number\n }\n}\n\nconst defaultScoreOf: ScoreOf = (r) => {\n const o = r.outcome\n if (typeof o.holdoutScore === 'number') return o.holdoutScore\n if (typeof o.searchScore === 'number') return o.searchScore\n const raw = o.raw ?? {}\n for (const k of ['composite', 'score', 'passed', 'resolved']) {\n if (typeof raw[k] === 'number') return raw[k]\n }\n return undefined\n}\n\nconst defaultProfileKeyOf: ProfileKeyOf = (r) => {\n const harness = r.agentProfile?.harness?.id\n const model = r.agentProfile?.model ?? r.model\n return harness ? `${harness}·${model}` : model\n}\n\nconst defaultGroupOf: GroupOf = (r) => r.scenarioId ?? r.experimentId\n\nfunction quantile(sorted: number[], q: number): number {\n if (sorted.length === 0) return 0\n const idx = Math.min(sorted.length - 1, Math.floor(q * (sorted.length - 1)))\n return sorted[idx] ?? 0\n}\n\nfunction mean(xs: readonly number[]): number {\n return xs.length === 0 ? 0 : xs.reduce((a, b) => a + b, 0) / xs.length\n}\n\n/** Collapse reps to ONE mean score per scenario — the honest unit for a CI or a paired test. Reps\n * tighten the per-(profile, scenario) estimate but are NOT independent samples, so feeding raw reps into\n * a CI lets identical reps fake a narrower interval. Fails LOUD on a record missing `scenarioId`: an\n * empty-string fallback would silently merge distinct scenarios into one bucket. */\nfunction meanByScenario(records: readonly RunRecord[], scoreOf: ScoreOf): Map<string, number> {\n const sums = new Map<string, { total: number; n: number }>()\n for (const r of records) {\n const s = scoreOf(r)\n if (typeof s !== 'number') continue\n const id = r.scenarioId\n if (!id) {\n throw new Error(\n `benchmark-report: RunRecord (candidate ${r.candidateId ?? 'unknown'}) is missing scenarioId — ` +\n 'cannot pair or interval it honestly. Pass opts.stats only on a scenario-tagged corpus.',\n )\n }\n const acc = sums.get(id) ?? { total: 0, n: 0 }\n acc.total += s\n acc.n += 1\n sums.set(id, acc)\n }\n const out = new Map<string, number>()\n for (const [id, acc] of sums) out.set(id, acc.n ? acc.total / acc.n : 0)\n return out\n}\n\n/** Aggregate a fleet of records into the ranked, multi-axis report. Pure — no IO, deterministic. */\nexport function leaderboard(\n records: readonly RunRecord[],\n opts: LeaderboardOptions = {},\n): Leaderboard {\n const scoreOf = opts.scoreOf ?? defaultScoreOf\n const profileKeyOf = opts.profileKeyOf ?? defaultProfileKeyOf\n const groupOf = opts.groupOf ?? defaultGroupOf\n const labelOf = opts.labelOf ?? ((k: string) => k)\n\n // Column set: explicit axis decomposition, else the scenario groups present in the data.\n const axisSet = new Set<string>()\n if (opts.axisScoresOf) {\n for (const r of records) for (const k of Object.keys(opts.axisScoresOf(r))) axisSet.add(k)\n } else {\n for (const r of records) axisSet.add(groupOf(r))\n }\n const axes = [...axisSet].sort()\n\n // Bucket records by profile.\n const byProfile = new Map<string, RunRecord[]>()\n for (const r of records) {\n const key = profileKeyOf(r)\n const bucket = byProfile.get(key)\n if (bucket) bucket.push(r)\n else byProfile.set(key, [r])\n }\n\n const rows: LeaderboardRow[] = []\n for (const [profileKey, recs] of byProfile) {\n const scores = recs.map(scoreOf).filter((s): s is number => typeof s === 'number')\n // Per-axis means.\n const axisBuckets = new Map<string, number[]>()\n for (const r of recs) {\n if (opts.axisScoresOf) {\n for (const [axis, s] of Object.entries(opts.axisScoresOf(r))) {\n const b = axisBuckets.get(axis) ?? []\n b.push(s)\n axisBuckets.set(axis, b)\n }\n } else {\n const s = scoreOf(r)\n if (typeof s === 'number') {\n const axis = groupOf(r)\n const b = axisBuckets.get(axis) ?? []\n b.push(s)\n axisBuckets.set(axis, b)\n }\n }\n }\n const perAxis: Record<string, number> = {}\n for (const [axis, b] of axisBuckets) perAxis[axis] = mean(b)\n\n const latencies = recs.map((r) => r.wallMs).sort((a, b) => a - b)\n const pass = opts.passThreshold ?? 0.999\n // Confidence intervals (opt-in) over per-scenario means — the honest n is #scenarios, not #reps.\n let scoreCi: Interval | undefined\n let passCi: Interval | undefined\n if (opts.stats) {\n const collapsed = [...meanByScenario(recs, scoreOf).values()]\n if (collapsed.length > 0) {\n const ci = confidenceInterval(collapsed, 0.95, { seed: 7 })\n scoreCi = { lower: ci.lower, upper: ci.upper }\n const w = wilson(collapsed.filter((s) => s >= pass).length, collapsed.length, 0.95)\n passCi = { lower: w.lower, upper: w.upper }\n }\n }\n const cost = summarizeCost(recs)\n rows.push({\n profileKey,\n label: labelOf(profileKey),\n model: recs[0]?.model ?? profileKey,\n n: recs.length,\n meanScore: mean(scores),\n solveRate: scores.length === 0 ? 0 : scores.filter((s) => s >= pass).length / scores.length,\n perAxis,\n costUsd: cost.uncapturedRecords === 0 ? cost.capturedUsd : null,\n capturedCostUsd: cost.capturedUsd,\n uncapturedCostRuns: cost.uncapturedRecords,\n tokensIn: recs.reduce((a, r) => a + (r.tokenUsage?.input ?? 0), 0),\n tokensOut: recs.reduce((a, r) => a + (r.tokenUsage?.output ?? 0), 0),\n latencyP50Ms: quantile(latencies, 0.5),\n latencyP90Ms: quantile(latencies, 0.9),\n ...(scoreCi ? { scoreCi } : {}),\n ...(passCi ? { passCi } : {}),\n })\n }\n\n // Rank: score desc, then complete cost before unknown cost, then lower cost and label.\n rows.sort(\n (a, b) =>\n b.meanScore - a.meanScore ||\n compareCompleteCost(a.costUsd, b.costUsd) ||\n a.label.localeCompare(b.label),\n )\n\n const models = [...new Set(records.map((r) => r.model))].sort()\n const totalCost = summarizeCost(records)\n return {\n title: opts.title ?? 'Benchmark report',\n axes,\n profiles: rows,\n meta: opts.meta ?? {},\n provenance: {\n records: records.length,\n profiles: rows.length,\n axes: axes.length,\n models,\n totalCostUsd: totalCost.uncapturedRecords === 0 ? totalCost.capturedUsd : null,\n capturedCostUsd: totalCost.capturedUsd,\n uncapturedCostRecords: totalCost.uncapturedRecords,\n },\n }\n}\n\nfunction summarizeCost(records: readonly RunRecord[]): {\n capturedUsd: number\n uncapturedRecords: number\n} {\n return records.reduce(\n (summary, record) => {\n if (record.costUsd === null) {\n summary.uncapturedRecords += 1\n } else {\n summary.capturedUsd += record.costUsd\n }\n return summary\n },\n { capturedUsd: 0, uncapturedRecords: 0 },\n )\n}\n\nfunction compareCompleteCost(left: number | null, right: number | null): number {\n if (left === null) return right === null ? 0 : 1\n if (right === null) return -1\n return left - right\n}\n\n/** One profile pair compared on the scenarios they BOTH ran — the \"who actually beat whom\" verdict. */\nexport interface PairwiseVerdict {\n readonly a: string\n readonly b: string\n /** Paired unit count (shared scenarios). The significance is suppressed below `minPairs`. */\n readonly pairs: number\n /** Median paired delta (b − a) and its bootstrap CI. */\n readonly delta: number\n readonly ciLow: number\n readonly ciHigh: number\n /** Non-zero paired differences used by the signed-rank test. */\n readonly nonZeroPairs: number\n /** How the signed-rank p-value was computed. */\n readonly testMethod: RankTestMethod\n /** Smallest p-value attainable by this paired design. */\n readonly pFloor: number\n /** Raw two-sided signed-rank p-value. */\n readonly p: number\n /** Benjamini-Hochberg adjusted q-value across every profile pair. */\n readonly q: number\n /** BH-significant and above the `minPairs` observation floor. */\n readonly significant: boolean\n}\n\nexport interface PairwiseOptions {\n readonly scoreOf?: ScoreOf\n readonly profileKeyOf?: ProfileKeyOf\n readonly labelOf?: (profileKey: string) => string\n /** False-discovery rate for the Benjamini–Hochberg correction. Default 0.05. */\n readonly fdr?: number\n /** Below this many shared scenarios a paired test can't defensibly separate two profiles, so the\n * `significant` tag is suppressed regardless of p (small-n mirage protection). Default 12. */\n readonly minPairs?: number\n}\n\n/** Compare EVERY profile pair on the scenarios they both ran — paired-bootstrap effect + CI, a real\n * paired-test p-value, BH-corrected across all pairs. This is the honest \"did A beat B\" table the\n * leaderboard's point ranking cannot answer. Reuses the agent-eval statistics substrate. */\nexport function pairwiseSignificance(\n records: readonly RunRecord[],\n opts: PairwiseOptions = {},\n): PairwiseVerdict[] {\n const scoreOf = opts.scoreOf ?? defaultScoreOf\n const profileKeyOf = opts.profileKeyOf ?? defaultProfileKeyOf\n const labelOf = opts.labelOf ?? ((k: string) => k)\n const minPairs = opts.minPairs ?? 12\n\n const byProfile = new Map<string, RunRecord[]>()\n for (const r of records) {\n const k = profileKeyOf(r)\n const b = byProfile.get(k)\n if (b) b.push(r)\n else byProfile.set(k, [r])\n }\n const keys = [...byProfile.keys()].sort()\n const collapsed = new Map(keys.map((k) => [k, meanByScenario(byProfile.get(k) ?? [], scoreOf)]))\n\n const raw: Array<Omit<PairwiseVerdict, 'q' | 'significant'>> = []\n for (let i = 0; i < keys.length; i += 1) {\n for (let j = i + 1; j < keys.length; j += 1) {\n const ka = keys[i] as string\n const kb = keys[j] as string\n const am = collapsed.get(ka) as Map<string, number>\n const bm = collapsed.get(kb) as Map<string, number>\n const aScores: number[] = []\n const bScores: number[] = []\n for (const sid of [...am.keys()].sort()) {\n const bv = bm.get(sid)\n if (bv !== undefined) {\n aScores.push(am.get(sid) as number)\n bScores.push(bv)\n }\n }\n if (aScores.length === 0) continue\n const boot = pairedBootstrap(aScores, bScores, { seed: 7, statistic: 'median' })\n const test = wilcoxonSignedRank(aScores, bScores, { seed: 7 })\n raw.push({\n a: labelOf(ka),\n b: labelOf(kb),\n pairs: aScores.length,\n delta: boot.median,\n ciLow: boot.low,\n ciHigh: boot.high,\n nonZeroPairs: test.nNonZero,\n testMethod: test.method,\n pFloor: test.pFloor,\n p: test.p,\n })\n }\n }\n const { qValues, significant } = benjaminiHochberg(\n raw.map((result) => result.p),\n opts.fdr ?? 0.05,\n )\n return raw.map((r, i) => ({\n ...r,\n q: qValues[i] ?? 1,\n significant: (significant[i] ?? false) && r.pairs >= minPairs,\n }))\n}\n\nconst pct = (x: number): string => `${(100 * x).toFixed(1)}%`\nconst ci = (iv: Interval | undefined): string => (iv ? ` [${pct(iv.lower)}, ${pct(iv.upper)}]` : '')\nconst cost = (\n totalUsd: number | null,\n capturedUsd: number,\n uncapturedRecords: number,\n digits: number,\n): string =>\n totalUsd === null\n ? `at least $${capturedUsd.toFixed(digits)} (${uncapturedRecords} uncaptured)`\n : `$${totalUsd.toFixed(digits)}`\n\n/** Render the report as a publishable Markdown document: provenance → leaderboard → the full profile×axis\n * matrix → cost/latency/token columns. Every axis is shown — a curated subset is a reporting failure. */\nexport function renderLeaderboardMarkdown(report: Leaderboard): string {\n const lines: string[] = []\n lines.push(`# ${report.title}`, '')\n const p = report.provenance\n lines.push(\n `**${p.profiles} profiles × ${p.axes} axes**, ${p.records} runs, ${p.models.length} models · total ${cost(p.totalCostUsd, p.capturedCostUsd, p.uncapturedCostRecords, 2)}`,\n '',\n )\n for (const [k, v] of Object.entries(report.meta)) lines.push(`- **${k}:** ${v}`)\n if (Object.keys(report.meta).length) lines.push('')\n\n // Leaderboard — the headline ranking with every measured column (+ CIs when computed).\n lines.push('## Leaderboard', '')\n lines.push(\n '| # | Profile | Score (95% CI) | Solved (95% CI) | Runs | Cost | Tok in/out | p50 | p90 |',\n )\n lines.push('|---|---|--:|--:|--:|--:|--:|--:|--:|')\n report.profiles.forEach((r, i) => {\n lines.push(\n `| ${i + 1} | ${r.label} | ${pct(r.meanScore)}${ci(r.scoreCi)} | ${pct(r.solveRate)}${ci(r.passCi)} | ${r.n} | ${cost(r.costUsd, r.capturedCostUsd, r.uncapturedCostRuns, 3)} | ${r.tokensIn}/${r.tokensOut} | ${(r.latencyP50Ms / 1000).toFixed(1)}s | ${(r.latencyP90Ms / 1000).toFixed(1)}s |`,\n )\n })\n lines.push('')\n\n // The full matrix — profile × every axis.\n lines.push('## Score matrix — profile × axis', '')\n lines.push(`| Profile | ${report.axes.join(' | ')} |`)\n lines.push(`|---|${report.axes.map(() => '--:').join('|')}|`)\n for (const r of report.profiles) {\n const cells = report.axes.map((a) => {\n const v = r.perAxis[a]\n return v === undefined ? '·' : pct(v)\n })\n lines.push(`| ${r.label} | ${cells.join(' | ')} |`)\n }\n lines.push('')\n lines.push('> `·` = the profile never ran that axis (blank, never zero).')\n return lines.join('\\n')\n}\n\n/** Render the pairwise-significance table — every profile pair's paired delta, CI, and BH-corrected\n * verdict. Feed it `pairwiseSignificance(records)`. This is the \"did A really beat B\" evidence the point\n * ranking cannot give. */\nexport function renderPairwiseMarkdown(\n verdicts: readonly PairwiseVerdict[],\n title = 'Pairwise significance (paired, BH-corrected)',\n): string {\n const lines: string[] = [`## ${title}`, '']\n if (verdicts.length === 0) return lines.concat('_no comparable pairs_').join('\\n')\n lines.push(\n '| A vs B | Δ(b−a) median | 95% CI | pairs | changed | test | p | p floor | q | verdict |',\n )\n lines.push('|---|--:|--:|--:|--:|---|--:|--:|--:|---|')\n for (const v of verdicts) {\n const verdict =\n v.nonZeroPairs === 0 ? 'tie' : v.significant ? `**${v.delta >= 0 ? v.b : v.a} wins**` : 'ns'\n lines.push(\n `| ${v.a} vs ${v.b} | ${v.delta >= 0 ? '+' : ''}${pct(v.delta)} | [${pct(v.ciLow)}, ${pct(v.ciHigh)}] | ${v.pairs} | ${v.nonZeroPairs} | ${v.testMethod} | ${formatProbability(v.p)} | ${formatProbability(v.pFloor)} | ${formatProbability(v.q)} | ${verdict} |`,\n )\n }\n lines.push(\n '',\n '> `changed` excludes exact ties. `p` is the raw two-sided signed-rank probability; `q` is Benjamini-Hochberg adjusted. `ns` means q did not clear the target or the pair count was below the configured minimum.',\n )\n return lines.join('\\n')\n}\n\nfunction formatProbability(value: number): string {\n return value > 0 && value < 0.001 ? value.toExponential(2) : value.toFixed(3)\n}\n\nfunction esc(s: string): string {\n return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n}\n\n// A score → color ramp (red→amber→green) for the heatmap, deterministic and dependency-free.\nfunction ramp(score: number): string {\n const x = Math.max(0, Math.min(1, score))\n const r = Math.round(x < 0.5 ? 220 : 220 - (x - 0.5) * 2 * 160)\n const g = Math.round(x < 0.5 ? x * 2 * 170 : 170)\n return `rgb(${r},${g},60)`\n}\n\n/** Render a self-contained SVG: a ranked score bar chart on top, the profile×axis heatmap below. No deps,\n * embeddable anywhere (README, HTML page, hosted leaderboard). */\nexport function renderLeaderboardSvg(report: Leaderboard): string {\n const rowH = 26\n const labelW = 220\n const cellW = 54\n const pad = 16\n const barAreaW = 360\n const profiles = report.profiles\n const barsH = profiles.length * rowH + pad\n const heatTop = barsH + 48\n const heatW = labelW + report.axes.length * cellW + pad\n const heatH = profiles.length * rowH + pad\n const width = Math.max(labelW + barAreaW + pad * 2, heatW)\n const height = heatTop + heatH + pad\n\n const out: string[] = []\n out.push(\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\" font-family=\"ui-sans-serif,system-ui,sans-serif\" font-size=\"12\">`,\n )\n out.push(`<rect width=\"${width}\" height=\"${height}\" fill=\"white\"/>`)\n out.push(\n `<text x=\"${pad}\" y=\"${pad + 4}\" font-weight=\"700\" font-size=\"14\">${esc(report.title)} — score</text>`,\n )\n\n // Bar chart (ranked).\n profiles.forEach((r, i) => {\n const y = pad + 12 + i * rowH\n out.push(`<text x=\"${pad}\" y=\"${y + 14}\">${esc(r.label)}</text>`)\n const w = Math.round(r.meanScore * barAreaW)\n out.push(`<rect x=\"${labelW}\" y=\"${y + 4}\" width=\"${barAreaW}\" height=\"16\" fill=\"#eef0f2\"/>`)\n out.push(\n `<rect x=\"${labelW}\" y=\"${y + 4}\" width=\"${w}\" height=\"16\" fill=\"${ramp(r.meanScore)}\"/>`,\n )\n out.push(`<text x=\"${labelW + barAreaW + 6}\" y=\"${y + 16}\">${pct(r.meanScore)}</text>`)\n })\n\n // Heatmap.\n out.push(\n `<text x=\"${pad}\" y=\"${heatTop - 12}\" font-weight=\"700\" font-size=\"14\">profile × axis</text>`,\n )\n report.axes.forEach((a, c) => {\n const x = labelW + c * cellW\n out.push(\n `<text x=\"${x + cellW / 2}\" y=\"${heatTop}\" text-anchor=\"middle\" fill=\"#555\">${esc(a.length > 8 ? `${a.slice(0, 7)}…` : a)}</text>`,\n )\n })\n profiles.forEach((r, i) => {\n const y = heatTop + 8 + i * rowH\n out.push(`<text x=\"${pad}\" y=\"${y + 16}\">${esc(r.label)}</text>`)\n report.axes.forEach((a, c) => {\n const x = labelW + c * cellW\n const s = r.perAxis[a]\n if (s !== undefined) {\n out.push(\n `<rect x=\"${x}\" y=\"${y}\" width=\"${cellW - 3}\" height=\"${rowH - 4}\" fill=\"${ramp(s)}\"/>`,\n )\n out.push(\n `<text x=\"${x + (cellW - 3) / 2}\" y=\"${y + 15}\" text-anchor=\"middle\" fill=\"white\" font-size=\"10\">${Math.round(100 * s)}</text>`,\n )\n } else {\n out.push(\n `<rect x=\"${x}\" y=\"${y}\" width=\"${cellW - 3}\" height=\"${rowH - 4}\" fill=\"#f3f4f6\"/>`,\n )\n }\n })\n })\n out.push('</svg>')\n return out.join('\\n')\n}\n\n/** Render a self-contained HTML leaderboard page (the hosted surface): the SVG charts + the full Markdown\n * matrix as a table. Single file, no assets, opens in any browser. */\nexport function renderLeaderboardHtml(report: Leaderboard): string {\n const svg = renderLeaderboardSvg(report)\n const p = report.provenance\n const rows = report.profiles\n .map(\n (r, i) =>\n `<tr><td>${i + 1}</td><td>${esc(r.label)}</td><td class=\"n\">${pct(r.meanScore)}</td><td class=\"n\">${pct(r.solveRate)}</td><td class=\"n\">${r.n}</td><td class=\"n\">${cost(r.costUsd, r.capturedCostUsd, r.uncapturedCostRuns, 3)}</td>${report.axes\n .map((a) => {\n const v = r.perAxis[a]\n return `<td class=\"n\">${v === undefined ? '·' : pct(v)}</td>`\n })\n .join('')}</tr>`,\n )\n .join('\\n')\n const axisHead = report.axes.map((a) => `<th>${esc(a)}</th>`).join('')\n return `<!doctype html><html><head><meta charset=\"utf-8\"><title>${esc(report.title)}</title>\n<style>\nbody{font:14px ui-sans-serif,system-ui,sans-serif;margin:2rem;color:#111}\nh1{font-size:1.4rem}.sub{color:#555;margin:.2rem 0 1.2rem}\ntable{border-collapse:collapse;margin-top:1rem}td,th{border:1px solid #e5e7eb;padding:.35rem .6rem}\nth{background:#f9fafb;text-align:left}.n{text-align:right;font-variant-numeric:tabular-nums}\ntr:first-child td{font-weight:600}\n</style></head><body>\n<h1>${esc(report.title)}</h1>\n<div class=\"sub\">${p.profiles} profiles × ${p.axes} axes · ${p.records} runs · ${p.models.length} models · total ${cost(p.totalCostUsd, p.capturedCostUsd, p.uncapturedCostRecords, 2)}</div>\n${svg}\n<table><thead><tr><th>#</th><th>Profile</th><th>Score</th><th>Solved</th><th>Runs</th><th>Cost</th>${axisHead}</tr></thead>\n<tbody>\n${rows}\n</tbody></table>\n</body></html>`\n}\n","/**\n *\n * Completion / satisfiability — the OTHER output of the pluggable analyst (the steer output\n * is `AnalystFinding[]` via the `analyze` hook; this is the \"is it done?\" output via the\n * `complete` hook). A `CompletionAnalyst` reads a node's trace and returns a `CompletionVerdict`\n * the PARENT (driver) acts on: end the node, or keep going. It fits ANY node and composes to\n * any depth — a 1-deep loop has one; an N-deep tree has one per node.\n *\n * The verdict's authority scales with its DETERMINISM (the thing that varies by task):\n * - `deterministic` — build/test/lint pass, a proof checks, every claim's citation resolves:\n * ground truth, the driver TRUSTS it and ends. Not an opinion.\n * - `probabilistic` — a quality/soundness judgment (marketing, \"the experiment is sound\"):\n * ADVISORY. It passes to the driver with its reasons; the driver validates (here: a\n * confidence threshold; a richer driver may re-examine the reasons) before ending.\n *\n * Two stop-signal mechanisms, by node mode, both → one `CompletionVerdict`:\n * - sandbox-agent (text stream): a unique per-node STOP SENTINEL the agent emits when done\n * (`stopSentinel` / `sentinelCompletion`) — ralph-loop style; the seed makes it\n * unguessable + attributable, so it can't be spuriously emitted or confused with content.\n * - deterministic check (compile/test/citation/proof): `deterministicCompletion(check)` —\n * a verifier over the output, never the judge verdict (selector ≠ judge holds).\n *\n * @experimental\n */\n\nimport type { Iteration } from './types'\n\n/** Trace-derived evidence for a completion claim — an artifact (output) or a verifier metric,\n * never the judge's own verdict. Mirrors the steer-firewall's provenance discipline. */\nexport interface CompletionEvidence {\n kind: 'artifact' | 'metric'\n uri: string\n}\n\n/** The \"is it done?\" verdict an analyst returns to the parent. */\nexport interface CompletionVerdict {\n done: boolean\n /** How verifiable the claim is — sets whether the driver trusts it or validates it. */\n determinism: 'deterministic' | 'probabilistic'\n /** Why the analyst believes it is (or isn't) done — what the driver validates. */\n reasons?: string\n /** 0..1, for probabilistic verdicts; the driver's validation threshold reads this. */\n confidence?: number\n evidence?: ReadonlyArray<CompletionEvidence>\n}\n\n/** Reads a node's trace → a completion verdict. Same input shape as the `analyze` hook, so\n * ONE analyst node can back both channels (findings for steer, a verdict for stop). */\nexport interface CompletionAnalyst<Task, Output> {\n assess(input: {\n task: Task\n history: ReadonlyArray<Iteration<Task, Output>>\n }): CompletionVerdict | Promise<CompletionVerdict>\n}\n\n/** When a verdict authorizes the driver to END. Deterministic → trust (ground truth);\n * probabilistic → validate by confidence threshold (the driver's check). */\nexport interface CompletionPolicy {\n /** Minimum confidence a PROBABILISTIC verdict must clear to end. Default 0.8. */\n minConfidence?: number\n}\n\n/** Decide whether a `CompletionVerdict` may end the node under the policy: authority scales with the verdict's determinism, and probabilistic verdicts must clear `minConfidence`. */\nexport function completionAuthorizes(v: CompletionVerdict, policy?: CompletionPolicy): boolean {\n if (!v?.done) return false\n if (v.determinism === 'deterministic') return true\n return (v.confidence ?? 0) >= (policy?.minConfidence ?? 0.8)\n}\n\n/**\n * A unique, attributable stop sentinel for a node (ralph-loop style). Deterministic from the\n * seed (no Math.random — reproducible + attributable to the node); the agent is instructed to\n * emit it VERBATIM when it judges itself done. Unguessable enough that content never trips it.\n */\nexport function stopSentinel(seed: string): string {\n let h = 0x811c9dc5\n for (let i = 0; i < seed.length; i += 1) {\n h ^= seed.charCodeAt(i)\n h = Math.imul(h, 0x01000193)\n }\n return `<<<{{STOP:${(h >>> 0).toString(16).padStart(8, '0')}}}>>>`\n}\n\n/**\n * Completion for a sandbox-agent node: done iff the latest output carries the node's stop\n * sentinel. PROBABILISTIC (the agent's own self-judgment) — the driver validates it.\n */\nexport function sentinelCompletion<Task>(\n sentinel: string,\n opts?: { confidence?: number },\n): CompletionAnalyst<Task, string> {\n return {\n assess({ history }) {\n const last = history[history.length - 1]\n const out = typeof last?.output === 'string' ? last.output : ''\n const done = out.includes(sentinel)\n return {\n done,\n determinism: 'probabilistic',\n confidence: done ? (opts?.confidence ?? 0.9) : 0,\n reasons: done ? 'agent emitted its assigned stop sentinel' : undefined,\n evidence: done && last ? [{ kind: 'artifact', uri: `attempt:${last.index}` }] : [],\n }\n },\n }\n}\n\n/**\n * Completion for a DETERMINISTIC check (build/test/lint/citation/proof): done iff the check\n * passes. Ground truth — the driver ends directly, no validation. The check reads the output\n * (a verifier), never the judge verdict — selector ≠ judge stays intact.\n */\nexport function deterministicCompletion<Task, Output>(\n check: (\n output: Output,\n history: ReadonlyArray<Iteration<Task, Output>>,\n ) => { passed: boolean; reasons?: string },\n): CompletionAnalyst<Task, Output> {\n return {\n assess({ history }) {\n const last = history[history.length - 1]\n if (last?.output === undefined) {\n return { done: false, determinism: 'deterministic', reasons: 'no output yet' }\n }\n const r = check(last.output, history)\n return {\n done: r.passed,\n determinism: 'deterministic',\n reasons: r.reasons,\n evidence: [{ kind: 'artifact', uri: `attempt:${last.index}` }],\n }\n },\n }\n}\n","import { execFile, spawn } from 'node:child_process'\nimport { randomUUID } from 'node:crypto'\nimport { constants as fsConstants } from 'node:fs'\nimport {\n chmod,\n lstat,\n mkdir,\n mkdtemp,\n open,\n opendir,\n readlink,\n realpath,\n stat,\n symlink,\n} from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join, relative, sep } from 'node:path'\nimport { promisify } from 'node:util'\nimport {\n type AgentCandidateWorkspaceManifestMaterial,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport type {\n CreateSandboxOptions,\n SandboxInstance,\n SandboxResources,\n} from '@tangle-network/sandbox'\nimport {\n captureMaterializedWorkspace,\n WorkspaceScanLimitError,\n} from '../candidate-execution/artifacts'\nimport { armDeadlineTimer } from './supervise/deadline'\n\nexport interface IsolatedCheckOptions {\n /** Trusted workspace boundary containing the untrusted tree. */\n workspaceRoot: string\n tree: string\n /** Executable and arguments, without host shell interpretation. */\n command: readonly [string, ...string[]]\n timeoutMs?: number\n maxOutputBytes?: number\n /** Maximum regular-file bytes copied or captured from the input tree when set. */\n maxInputBytes?: number\n /** Maximum entries in the input tree when set. */\n maxInputEntries?: number\n signal?: AbortSignal\n /** Run the check in its own Sandbox box instead of Linux Bubblewrap on this host. */\n box?: IsolatedCheckBox\n /** Environment the command receives beside PATH, HOME and LANG: a declared check's named\n * secrets and its own settings. Nothing else of this process's environment reaches it. */\n env?: Readonly<Record<string, string>>\n}\n\n/**\n * A fresh Sandbox box for one check, owned by an account the judged run holds no key to.\n *\n * Any key of a Sandbox account can read, write, and execute in every box of that account.\n * A check box on the run's own account is therefore reachable by the run it judges.\n * The check refuses before it creates a box when its account is one of `builderAccounts`.\n */\nexport interface IsolatedCheckBox {\n /**\n * Client authenticated with the check's own key: a `Sandbox` from SDK 0.46 or later.\n * Written as its two methods because the Runtime peer range admits SDKs without `createIsolated`.\n */\n client: {\n getIdentity(): Promise<{ customerId: string }>\n createIsolated(\n options: Omit<CreateSandboxOptions, 'ownerContext'>,\n requestOptions?: { signal?: AbortSignal },\n ): Promise<SandboxInstance>\n }\n /** `customerId` from `Sandbox.getIdentity()` for every Sandbox key the judged run holds. */\n builderAccounts: readonly [string, ...string[]]\n /** Sandbox environment or image that holds the check's toolchain. */\n environment: string\n /** Set `memoryMB` to require the API to report a finite granted limit before upload. */\n resources?: SandboxResources\n /** Domains the check may reach, such as a knowledge store or a git host. Empty or absent: the\n * box's egress is blocked. Otherwise strict: these domains only, with no implicit list. */\n egress?: readonly string[]\n /**\n * The check runs containers. Sandbox starts a box's rootless container daemon only with its\n * managed agent runtime, so this box is created with `agent: true`; it still receives no owner\n * secret, which its create receipt must confirm. It is not `ephemeral`, so its home is a disk\n * sized by `resources.diskGB` instead of a small in-memory home that image layers overflow.\n */\n containers?: boolean\n}\n\n/** The box a check ran in and the exact bytes it received. */\nexport interface IsolatedCheckBoxEvidence {\n sandboxId: string\n /** `customerId` of the check's key. */\n account: string\n /** API-reported granted memory limit in MiB, when explicitly requested. */\n memoryMB?: number\n /** Every file the box received; each sha256 is also the digest the box computed on receipt. */\n input: AgentCandidateWorkspaceManifestMaterial\n /** Canonical digest of `input`. */\n inputDigest: Sha256Digest\n}\n\nexport type IsolatedCheckResult =\n | { succeeded: true; value: { stdout: string; stderr: string }; box?: IsolatedCheckBoxEvidence }\n | {\n succeeded: false\n reason:\n | 'refused'\n | 'failed'\n | 'timeout'\n | 'cancelled'\n | 'output-limit'\n | 'input-limit'\n | 'cleanup-failed'\n diagnostic: string\n /** Bounded command evidence, when a process was launched. */\n stdout?: string\n stderr?: string\n exitCode?: number | null\n /** Cleanup failures never replace the primary command failure. */\n cleanupDiagnostic?: string\n /** Present once a check box received its complete input. */\n box?: IsolatedCheckBoxEvidence\n }\n\nconst toolchains = ['/usr', '/bin', '/lib', '/lib64']\nconst contains = (parent: string, child: string) => {\n const path = relative(parent, child)\n return path === '' || (path !== '..' && !path.startsWith(`..${sep}`) && !path.startsWith(sep))\n}\n\n/**\n * Run an untrusted check in Linux Bubblewrap, or in its own Sandbox box when `box` is set.\n * Never falls back to host execution.\n *\n * Bubblewrap requires /usr/bin/bwrap and permission to create Linux namespaces.\n * Only trusted system toolchains, private proc/dev/tmp, and the writable copy are mounted.\n * The canonical input path remains the working directory; copy writes are discarded.\n * Time and output are bounded; input copy bytes and entries are bounded when requested.\n * The command's memory and generated files require a resource-limited placement.\n * Callers must keep the input and trusted toolchains stable while preparing the check.\n *\n * A box check creates one fresh box with no owner secrets and blocked egress (or strict egress to\n * the placement's named domains), delivers the tree's regular files verified by sha256, runs the\n * command there with only the environment `env` names, and deletes the box.\n */\nexport async function runIsolatedCheck(\n options: IsolatedCheckOptions,\n): Promise<IsolatedCheckResult> {\n if (options.box) return runInBox(options, options.box)\n let scratch: string | undefined\n let result: IsolatedCheckResult\n try {\n if (process.platform !== 'linux') throw new Error('Linux Bubblewrap namespaces are required')\n const { timeoutMs, maxOutputBytes, maxInputBytes, maxInputEntries } = checkLimits(options)\n if (options.signal?.aborted)\n return { succeeded: false, reason: 'cancelled', diagnostic: 'Check cancelled' }\n const { workspace, tree } = await protectedTree(options)\n const binds: string[] = []\n for (const path of toolchains) {\n let actual: string\n try {\n actual = await realpath(path)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue\n throw error\n }\n for (const mount of [path, actual]) {\n if (\n contains(mount, workspace) ||\n contains(workspace, mount) ||\n contains(mount, tree) ||\n contains(tree, mount)\n ) {\n throw new Error(`Toolchain overlaps protected workspace: ${path}`)\n }\n }\n binds.push('--ro-bind', actual, path)\n }\n // Fixed mount destinations must not cover or be covered by the evidence tree.\n if (['/proc', '/dev'].some((path) => contains(path, tree) || contains(tree, path))) {\n throw new Error('Tree overlaps a reserved namespace mount')\n }\n scratch = await mkdtemp(join(tmpdir(), 'runtime-check-'))\n if (contains(tree, scratch)) throw new Error('Temporary storage must be outside the input tree')\n const copy = join(scratch, 'tree')\n await copyBoundedTree(tree, copy, maxInputBytes, maxInputEntries)\n const args = [\n '--unshare-all',\n '--die-with-parent',\n '--new-session',\n '--cap-drop',\n 'ALL',\n '--clearenv',\n '--setenv',\n 'PATH',\n '/usr/bin:/bin',\n '--setenv',\n 'HOME',\n '/tmp',\n '--setenv',\n 'LANG',\n 'C',\n ...Object.entries(options.env ?? {}).flatMap(([name, value]) => ['--setenv', name, value]),\n ...binds,\n '--proc',\n '/proc',\n '--dev',\n '/dev',\n '--tmpfs',\n '/tmp',\n '--bind',\n copy,\n tree,\n '--chdir',\n tree,\n '--',\n ...options.command,\n ]\n result = await execute(args, timeoutMs, maxOutputBytes, options.signal)\n } catch (error) {\n result = {\n succeeded: false,\n reason: error instanceof InputLimitError ? 'input-limit' : 'refused',\n diagnostic: String(error),\n }\n }\n if (scratch) {\n try {\n await removeScratch(scratch)\n } catch (error) {\n const cleanupDiagnostic = String(error)\n result = result.succeeded\n ? {\n succeeded: false,\n reason: 'cleanup-failed',\n diagnostic: cleanupDiagnostic,\n stdout: result.value.stdout,\n stderr: result.value.stderr,\n exitCode: 0,\n }\n : { ...result, cleanupDiagnostic }\n }\n }\n return result\n}\n\nfunction checkLimits(options: IsolatedCheckOptions): {\n timeoutMs: number\n maxOutputBytes: number\n maxInputBytes?: number\n maxInputEntries?: number\n} {\n const timeoutMs = options.timeoutMs ?? 30_000\n const maxOutputBytes = options.maxOutputBytes ?? 1_048_576\n const maxInputBytes = options.maxInputBytes\n const maxInputEntries = options.maxInputEntries\n if (\n !Number.isSafeInteger(timeoutMs) ||\n timeoutMs < 1 ||\n timeoutMs > 2_147_483_647 ||\n !Number.isSafeInteger(maxOutputBytes) ||\n maxOutputBytes < 1 ||\n (maxInputBytes !== undefined && (!Number.isSafeInteger(maxInputBytes) || maxInputBytes < 1)) ||\n (maxInputEntries !== undefined &&\n (!Number.isSafeInteger(maxInputEntries) || maxInputEntries < 1))\n )\n throw new Error('Invalid execution limits')\n if (!options.command.length || !options.command[0]) throw new Error('A command is required')\n return { timeoutMs, maxOutputBytes, maxInputBytes, maxInputEntries }\n}\n\nclass InputLimitError extends Error {}\n\n/** Copy in bounded chunks, preserving symlink text without reading its target. */\nasync function copyBoundedTree(\n source: string,\n destination: string,\n maxBytes: number | undefined,\n maxEntries: number | undefined,\n): Promise<void> {\n let bytes = 0\n let entries = 0\n const buffer = Buffer.allocUnsafe(1024 * 1024)\n const visit = async (from: string, to: string, isRoot = false): Promise<void> => {\n if (!isRoot && ++entries > (maxEntries ?? Number.MAX_SAFE_INTEGER))\n throw new InputLimitError('Input tree exceeds maxInputEntries')\n const info = await lstat(from)\n if (info.isSymbolicLink()) {\n await symlink(await readlink(from), to)\n } else if (info.isDirectory()) {\n await mkdir(to, { mode: 0o700 })\n for await (const entry of await opendir(from))\n await visit(join(from, entry.name), join(to, entry.name))\n await chmod(to, info.mode & 0o777)\n } else if (info.isFile()) {\n if (maxBytes !== undefined && info.size > maxBytes - bytes)\n throw new InputLimitError('Input tree exceeds maxInputBytes')\n const input = await open(from, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW)\n try {\n const output = await open(to, 'wx', info.mode & 0o777)\n try {\n while (true) {\n const { bytesRead } = await input.read(\n buffer,\n 0,\n maxBytes === undefined\n ? buffer.length\n : Math.min(buffer.length, maxBytes - bytes + 1),\n null,\n )\n if (bytesRead === 0) break\n bytes += bytesRead\n if (maxBytes !== undefined && bytes > maxBytes)\n throw new InputLimitError('Input tree exceeds maxInputBytes')\n let written = 0\n while (written < bytesRead) {\n const result = await output.write(buffer, written, bytesRead - written)\n if (result.bytesWritten === 0) throw new Error('Input copy made no write progress')\n written += result.bytesWritten\n }\n }\n } finally {\n await output.close()\n }\n await chmod(to, info.mode & 0o777)\n } finally {\n await input.close()\n }\n } else {\n throw new Error(`Input tree contains an unsupported entry: ${from}`)\n }\n }\n await visit(source, destination, true)\n}\n\nasync function checkInputEntries(root: string, maxEntries: number): Promise<void> {\n let count = 0\n const visit = async (path: string, isRoot = false): Promise<void> => {\n if (!isRoot && ++count > maxEntries)\n throw new InputLimitError('Input tree exceeds maxInputEntries')\n if (!(await lstat(path)).isDirectory()) return\n for await (const entry of await opendir(path)) await visit(join(path, entry.name))\n }\n await visit(root, true)\n}\n\nasync function protectedTree(\n options: IsolatedCheckOptions,\n): Promise<{ workspace: string; tree: string }> {\n const workspace = await realpath(options.workspaceRoot)\n const tree = await realpath(options.tree)\n if (!contains(workspace, tree) || !(await stat(tree)).isDirectory())\n throw new Error('Tree must be a directory inside the workspace')\n return { workspace, tree }\n}\n\n/** Box-workspace-relative directory that receives the tree and is the command's cwd. */\nconst BOX_TREE = 'tree'\n/** Bound on provisioning, delivery, and deletion; the box expires even if this process dies. */\nconst BOX_SETUP_SECONDS = 900\n/** The box's own process timeout is a backstop behind this module's deadline. */\nconst BOX_PROCESS_BACKSTOP_MS = 30_000\n/** Concurrent file deliveries into one check box. */\nconst BOX_UPLOADS = 4\n/** The box's process supervisor prefixes this to stderr when it cannot start the executable. */\nconst BOX_EXEC_FAILURE = 'process-supervisor: exec failed'\n\nasync function runInBox(\n options: IsolatedCheckOptions,\n placement: IsolatedCheckBox,\n): Promise<IsolatedCheckResult> {\n let box: SandboxInstance | undefined\n let evidence: IsolatedCheckBoxEvidence | undefined\n let result: IsolatedCheckResult\n try {\n const { timeoutMs, maxOutputBytes, maxInputBytes, maxInputEntries } = checkLimits(options)\n if (options.signal?.aborted)\n return { succeeded: false, reason: 'cancelled', diagnostic: 'Check cancelled' }\n const { tree } = await protectedTree(options)\n if (maxInputEntries !== undefined) await checkInputEntries(tree, maxInputEntries)\n // Read each file once: the digest recorded is the digest of the bytes sent.\n const captured = await captureMaterializedWorkspace(tree, {\n limits: {\n maxFiles: maxInputEntries ?? Number.MAX_SAFE_INTEGER,\n maxFileBytes: maxInputBytes ?? Number.MAX_SAFE_INTEGER,\n maxTotalFileBytes: maxInputBytes ?? Number.MAX_SAFE_INTEGER,\n },\n })\n if (placement.builderAccounts.length === 0 || placement.builderAccounts.some((id) => !id))\n throw new Error('builderAccounts must name the account of every key the judged run holds')\n const memoryMB = placement.resources?.memoryMB\n if (\n memoryMB !== undefined &&\n (!Number.isSafeInteger(memoryMB) ||\n memoryMB < 1 ||\n placement.resources?.advisory === true ||\n placement.resources?.advisoryFields?.includes('memoryMB'))\n )\n throw new Error('Check box requires an explicit finite resources.memoryMB limit')\n const account = (await placement.client.getIdentity()).customerId\n if (!account) throw new Error('Sandbox returned no account for the check key')\n if (placement.builderAccounts.includes(account))\n throw new Error(\n `Check account ${account} is an account the judged run holds a key to, so the run can reach the check box`,\n )\n options.signal?.throwIfAborted()\n box = await placement.client.createIsolated(\n {\n environment: placement.environment,\n agent: placement.containers === true,\n bare: false,\n ephemeral: placement.containers !== true,\n egressPolicy: egressFor(placement),\n ...(placement.resources ? { resources: placement.resources } : {}),\n maxLifetimeSeconds: Math.ceil(timeoutMs / 1_000) + BOX_SETUP_SECONDS,\n // A new identity per call: a replayed create could return a box another caller used.\n idempotencyKey: `agent-runtime-check-${randomUUID()}`,\n },\n options.signal ? { signal: options.signal } : undefined,\n )\n const receipt = box.createReceipt()\n if (\n receipt?.outcome !== 'created' ||\n receipt.ownerContext !== 'isolated' ||\n !Array.isArray(receipt.injectedSecrets) ||\n receipt.injectedSecrets.length !== 0\n )\n throw new Error('Sandbox did not confirm a fresh box with no owner secrets')\n const grantedMemoryMB = box.resources?.memoryMB\n if (\n memoryMB !== undefined &&\n (typeof grantedMemoryMB !== 'number' ||\n !Number.isSafeInteger(grantedMemoryMB) ||\n grantedMemoryMB < 1 ||\n grantedMemoryMB > memoryMB)\n )\n throw new Error('Sandbox did not confirm the requested finite memory cgroup limit')\n const egress = (await box.egress.get()).policy\n const wanted = egressFor(placement)\n if (\n egress.mode !== wanted.mode ||\n (wanted.mode === 'strict' &&\n (egress.includeImplicitDomains === true ||\n [...(egress.allowDomains ?? [])].sort().join(',') !==\n [...(wanted.allowDomains ?? [])].sort().join(',')))\n )\n throw new Error(\n `Check box egress is ${egress.mode} ${JSON.stringify(egress.allowDomains ?? [])}, not ${wanted.mode} ${JSON.stringify(wanted.allowDomains ?? [])}`,\n )\n await box.fs.mkdir(BOX_TREE, { recursive: true })\n const digests = new Map(captured.manifest.files.map((entry) => [entry.path, entry.sha256]))\n const target = box\n const pending = [...captured.files]\n const deliver = async () => {\n try {\n for (let file = pending.shift(); file; file = pending.shift()) {\n options.signal?.throwIfAborted()\n const received = await target.fs.uploadData(`${BOX_TREE}/${file.path}`, file.bytes, {\n mode: file.mode,\n })\n const receivedDigest = `sha256:${received.hash.replace(/^sha256:/, '').toLowerCase()}`\n if (receivedDigest !== digests.get(file.path) || received.size !== file.bytes.byteLength)\n throw new Error(`Check box received different bytes for ${file.path}`)\n }\n } catch (error) {\n // One failed delivery ends every other one before the box is deleted.\n pending.length = 0\n throw error\n }\n }\n await Promise.all(Array.from({ length: BOX_UPLOADS }, deliver))\n evidence = {\n sandboxId: box.id,\n account,\n ...(memoryMB === undefined ? {} : { memoryMB: grantedMemoryMB }),\n input: captured.manifest,\n inputDigest: canonicalCandidateDigest(captured.manifest),\n }\n result = await executeInBox(\n box,\n options.command,\n timeoutMs,\n maxOutputBytes,\n options.env ?? {},\n options.signal,\n )\n } catch (error) {\n result = {\n succeeded: false,\n reason: options.signal?.aborted\n ? 'cancelled'\n : error instanceof InputLimitError || error instanceof WorkspaceScanLimitError\n ? 'input-limit'\n : 'refused',\n diagnostic: String(error),\n }\n }\n if (box) {\n try {\n await box.delete()\n } catch (error) {\n const cleanupDiagnostic = `Check box ${box.id} was not deleted: ${String(error)}`\n result = result.succeeded\n ? {\n succeeded: false,\n reason: 'cleanup-failed',\n diagnostic: cleanupDiagnostic,\n stdout: result.value.stdout,\n stderr: result.value.stderr,\n exitCode: 0,\n }\n : { ...result, cleanupDiagnostic }\n }\n }\n return evidence ? { ...result, box: evidence } : result\n}\n\n/** Blocked unless the placement names domains; then strict, with no implicit domain list. */\nfunction egressFor(placement: IsolatedCheckBox): {\n mode: 'blocked' | 'strict'\n allowDomains?: string[]\n includeImplicitDomains?: false\n} {\n const domains = [...new Set(placement.egress ?? [])].filter((domain) => domain.trim() !== '')\n return domains.length === 0\n ? { mode: 'blocked' }\n : { mode: 'strict', allowDomains: domains, includeImplicitDomains: false }\n}\n\nasync function executeInBox(\n box: SandboxInstance,\n command: readonly [string, ...string[]],\n timeoutMs: number,\n limit: number,\n env: Readonly<Record<string, string>>,\n signal?: AbortSignal,\n): Promise<IsolatedCheckResult> {\n const [executable, ...args] = command\n const child = await box.process.spawnExact(executable, args, {\n cwd: BOX_TREE,\n env: { PATH: '/usr/bin:/bin', HOME: '/tmp', LANG: 'C', ...env },\n inheritEnv: false,\n timeoutMs: timeoutMs + BOX_PROCESS_BACKSTOP_MS,\n })\n const stdout: Buffer[] = []\n const stderr: Buffer[] = []\n let bytes = 0\n let failure: 'timeout' | 'cancelled' | 'output-limit' | undefined\n let stopping: Promise<void> | undefined\n const stop = (reason: typeof failure) => {\n failure ??= reason\n stopping ??= child.kill('SIGKILL', { tree: true }).catch(() => undefined)\n }\n const clearTimer = armDeadlineTimer(timeoutMs, () => stop('timeout'), true)\n const cancel = () => stop('cancelled')\n signal?.addEventListener('abort', cancel, { once: true })\n if (signal?.aborted) cancel()\n const capture = async (stream: AsyncIterable<string>, target: Buffer[]) => {\n for await (const text of stream) {\n const chunk = Buffer.from(text)\n const remaining = Math.max(0, limit - bytes)\n bytes += chunk.length\n if (remaining) target.push(chunk.subarray(0, remaining))\n if (bytes > limit) stop('output-limit')\n }\n }\n let exitCode: number\n let exitSignal: string | undefined\n try {\n await Promise.all([capture(child.stdout(), stdout), capture(child.stderr(), stderr)])\n exitCode = await child.wait()\n exitSignal = (await child.status()).exitSignal\n } finally {\n clearTimer()\n signal?.removeEventListener('abort', cancel)\n await stopping\n }\n const out = Buffer.concat(stdout).toString()\n const err = Buffer.concat(stderr).toString()\n const evidence = { stdout: out, stderr: err, exitCode: exitSignal ? null : exitCode }\n if (failure) return { succeeded: false, reason: failure, diagnostic: err || failure, ...evidence }\n if (exitCode === 127 && err.startsWith(BOX_EXEC_FAILURE))\n return { succeeded: false, reason: 'refused', diagnostic: err, ...evidence }\n if (exitSignal)\n return {\n succeeded: false,\n reason: 'failed',\n diagnostic: err || `Check killed by ${exitSignal}`,\n ...evidence,\n }\n if (exitCode !== 0)\n return {\n succeeded: false,\n reason: 'failed',\n diagnostic: err || out || `Check exited ${exitCode}`,\n ...evidence,\n }\n return { succeeded: true, value: { stdout: out, stderr: err } }\n}\n\nfunction execute(\n args: string[],\n timeoutMs: number,\n limit: number,\n signal?: AbortSignal,\n): Promise<IsolatedCheckResult> {\n return new Promise((done) => {\n const child = spawn('/usr/bin/bwrap', ['--json-status-fd', '3', ...args], {\n env: {},\n stdio: ['ignore', 'pipe', 'pipe', 'pipe'],\n detached: true,\n })\n const stdout: Buffer[] = []\n const stderr: Buffer[] = []\n let bytes = 0\n let status = ''\n let failure: 'timeout' | 'cancelled' | 'output-limit' | undefined\n const stop = (reason: typeof failure) => {\n failure ??= reason\n if (child.pid) {\n try {\n process.kill(-child.pid, 'SIGKILL')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ESRCH') child.kill('SIGKILL')\n }\n }\n }\n const clearTimer = armDeadlineTimer(timeoutMs, () => stop('timeout'), true)\n const cancel = () => stop('cancelled')\n signal?.addEventListener('abort', cancel, { once: true })\n if (signal?.aborted) cancel()\n const capture = (target: Buffer[]) => (chunk: Buffer) => {\n const remaining = Math.max(0, limit - bytes)\n bytes += chunk.length\n if (remaining) target.push(chunk.subarray(0, remaining))\n if (bytes > limit) stop('output-limit')\n }\n child.stdio[3]?.on('data', (chunk: Buffer) => {\n if (status.length + chunk.length > 16_384) {\n stop('output-limit')\n return\n }\n status += chunk.toString()\n })\n child.stdout!.on('data', capture(stdout))\n child.stderr!.on('data', capture(stderr))\n let spawnError: Error | undefined\n child.on('error', (error) => {\n spawnError = error\n })\n child.on('close', (code) => {\n clearTimer()\n signal?.removeEventListener('abort', cancel)\n const out = Buffer.concat(stdout).toString()\n const err = Buffer.concat(stderr).toString()\n const evidence = { stdout: out, stderr: err, exitCode: code }\n // Only Bubblewrap writes this private pipe; command stderr cannot forge setup status.\n const executed = status.split('\\n').some((line) => {\n try {\n const record: unknown = JSON.parse(line)\n return (\n record !== null &&\n typeof record === 'object' &&\n 'exit-code' in record &&\n typeof record['exit-code'] === 'number' &&\n record['exit-code'] === code\n )\n } catch {\n return false\n }\n })\n if (failure)\n done({ succeeded: false, reason: failure, diagnostic: err || failure, ...evidence })\n else if (spawnError)\n done({ succeeded: false, reason: 'refused', diagnostic: String(spawnError), ...evidence })\n else if (!executed)\n done({\n succeeded: false,\n reason: 'refused',\n diagnostic: err || 'Bubblewrap did not confirm command execution',\n ...evidence,\n })\n else if (code !== 0)\n done({\n succeeded: false,\n reason: 'failed',\n diagnostic: err || out || `Check exited ${code}`,\n ...evidence,\n })\n else done({ succeeded: true, value: { stdout: out, stderr: err } })\n })\n })\n}\n\nconst executeFile = promisify(execFile)\n\n/** GNU tools traverse relative to open directories, including trees deeper than PATH_MAX.\n * Recursive chmod ignores encountered symlinks; rm never follows their targets. */\nasync function removeScratch(path: string): Promise<void> {\n const options = { env: {}, timeout: 10_000, maxBuffer: 16_384 }\n let permissionError: unknown\n try {\n await executeFile(\n '/bin/chmod',\n ['--recursive', '--preserve-root', 'u+rwX', '--', path],\n options,\n )\n } catch (error) {\n permissionError = error\n }\n try {\n await executeFile(\n '/bin/rm',\n ['--recursive', '--force', '--one-file-system', '--', path],\n options,\n )\n } catch (error) {\n throw new Error(\n [permissionError, error]\n .filter((value) => value !== undefined)\n .map(String)\n .join('; '),\n )\n }\n}\n","/**\n * A declared check: the one frozen evaluator program that decides \"done\" for a run, named by\n * digest, run by Runtime in a fresh box on the check account.\n *\n * The same program is read three times (discovery `docs/38-one-loop-and-continuation.md`, section\n * 1): inside the run on every `submit_result` and at a turn end with no accepted result, after the\n * run to score it, and after each version to rank versions. Before this, each play wrote its own\n * check as Lab code in a method bundle — an exact-check judge, a sealed-cases judge, a product\n * judge — and the in-run check was a separate, weaker \"shape and persistence\" test, so 22 directors\n * passed their own check and then failed the outside one.\n *\n * The program prints one agent-eval `JudgeScore` as JSON on its last line of stdout: each checked\n * item is a dimension, `composite` is the score, and `notes` holds one `FAIL <item> <where>:\n * <reason>` line per failed item. The record states the pass threshold. A program that does not\n * run, or prints no score, gives no verdict: it is {@link CheckUnavailableError}, and the loop\n * pauses instead of blaming the director.\n *\n * The box receives the program's files at its working directory, the submitted result at\n * `_input/result.json` when there is one, the run's state at `_input/state/` when the host\n * captures it, and the sealed cases at `_sealed/` only when the read scores a run or a version.\n * `CHECK_SET` is `development` or `sealed`; `CHECK_RESULT` names the result file and\n * `CHECK_STATE` the state directory when present. Sealed cases never reach an in-run read, so\n * their lines never reach the director.\n *\n * The state is what a check reads when the work is not in the submitted value. A Terminal-Bench\n * task is done when its container holds the right files, and the box that holds that container is\n * the run's, which the check box cannot reach. So the host copies the declared paths out before\n * each read ({@link DeclaredCheckStateCapture}), and the check reads those bytes.\n */\n\nimport { mkdir, mkdtemp, readdir, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport {\n canonicalCandidateDigest,\n type Sha256Digest,\n sha256Bytes,\n} from '@tangle-network/agent-interface'\nimport type { SandboxResources } from '@tangle-network/sandbox'\nimport { captureMaterializedWorkspace } from '../candidate-execution/artifacts'\nimport type { VersionJudge } from '../durable/pursuit-versions'\nimport { ValidationError } from '../errors'\nimport {\n type IsolatedCheckBox,\n type IsolatedCheckResult,\n runIsolatedCheck,\n} from './isolated-checker'\nimport type { DeliverableSpec } from './supervise/completion-gate'\nimport {\n CheckUnavailableError,\n type CheckVerdict,\n verdictFromJudgeScore,\n} from './supervise/continuation'\n\n/** A check program as a record declares it. */\nexport interface DeclaredCheck {\n /** The evaluator program's files. A directory whose canonical digest differs is refused. */\n readonly program: { readonly dir: string; readonly digest: Sha256Digest }\n /** Executable and arguments, run in the program's directory. */\n readonly command: readonly [string, ...string[]]\n /** The box environment or image that holds the program's toolchain. */\n readonly environment: string\n /** Domains the program may reach. Absent or empty: egress is blocked. */\n readonly egress?: readonly string[]\n /** Names of this process's environment variables the program receives. A missing one refuses. */\n readonly secrets?: readonly string[]\n /** The pass threshold on the score's `composite`. */\n readonly pass: number\n /** `pass-only` keeps the FAIL lines from the director, for a check whose tests stay hidden. */\n readonly feedback: 'verbatim' | 'pass-only'\n /** Cases the director never sees. They score a run and a version, never an in-run read. */\n readonly sealed?: { readonly dir: string; readonly digest: Sha256Digest }\n /** What the run owes, for the director's tools and the note. */\n readonly describe?: string\n /** Bound on one read. Default 15 minutes. */\n readonly timeoutMs?: number\n /** The check box's size. With `containers`, `diskGB` sizes the disk that holds the images. */\n readonly resources?: SandboxResources\n /**\n * The program runs containers, as a benchmark's own verifier does. The check box then runs a\n * rootless container daemon, whose socket is `/run/user/<uid>/docker.sock` once it starts, and its\n * home is on a disk rather than in memory. Absent: neither, and the box starts faster.\n */\n readonly containers?: boolean\n}\n\n/** Where a declared check's boxes are created: a client on the check account, and every account\n * the judged run holds a key to, so the check refuses a box the run could reach. */\nexport interface DeclaredCheckPlacement {\n readonly client: IsolatedCheckBox['client']\n readonly builderAccounts: IsolatedCheckBox['builderAccounts']\n /** The environment the secrets are read from. Default `process.env`. */\n readonly env?: Readonly<Record<string, string | undefined>>\n}\n\n/**\n * Write the run's state into `into`, an empty directory Runtime created and removes after the read.\n * The host decides what the state is and reads it from the run's live environment, for example\n * the declared output files of a task's container. A capture that throws gives no verdict: the read\n * is {@link CheckUnavailableError}, never a failure blamed on the run.\n */\nexport type DeclaredCheckStateCapture = (into: string) => Promise<void>\n\nconst INPUT_DIR = '_input'\nconst STATE_DIR = 'state'\nconst SEALED_DIR = '_sealed'\nconst DEFAULT_TIMEOUT_MS = 15 * 60_000\n\n/** Refuse a malformed declaration before any compute. */\nexport function assertDeclaredCheck(check: DeclaredCheck, context: string): void {\n const fail = (message: string): never => {\n throw new ValidationError(`${context}: check ${message}`)\n }\n if (typeof check !== 'object' || check === null) fail('must be an object')\n if (typeof check.program?.dir !== 'string' || check.program.dir.trim() === '') {\n fail('program.dir must name the evaluator directory')\n }\n if (!/^sha256:[0-9a-f]{64}$/u.test(check.program?.digest ?? '')) {\n fail('program.digest must be a sha256 digest')\n }\n if (!Array.isArray(check.command) || check.command.length === 0 || !check.command[0]) {\n fail('command must name an executable')\n }\n if (typeof check.environment !== 'string' || check.environment.trim() === '') {\n fail('environment must name the box image')\n }\n if (typeof check.pass !== 'number' || !Number.isFinite(check.pass)) {\n fail('pass must be a finite threshold on the composite')\n }\n if (check.feedback !== 'verbatim' && check.feedback !== 'pass-only') {\n fail(\"feedback must be 'verbatim' or 'pass-only'\")\n }\n if (check.sealed !== undefined && !/^sha256:[0-9a-f]{64}$/u.test(check.sealed.digest ?? '')) {\n fail('sealed.digest must be a sha256 digest')\n }\n for (const name of check.secrets ?? []) {\n if (!/^[A-Z_][A-Z0-9_]*$/u.test(name))\n fail(`secret name ${JSON.stringify(name)} is not an env name`)\n }\n if (check.containers !== undefined && typeof check.containers !== 'boolean') {\n fail('containers must be a boolean')\n }\n}\n\n/** The canonical digest of a directory's files: the digest a record names a program by. */\nexport async function checkProgramDigest(dir: string): Promise<Sha256Digest> {\n return canonicalCandidateDigest((await captureMaterializedWorkspace(dir)).manifest)\n}\n\n/** The digest a version judge records: the program, the sealed cases, and how they are run. */\nexport function declaredCheckDigest(check: DeclaredCheck): Sha256Digest {\n return sha256Bytes(\n Buffer.from(\n JSON.stringify({\n program: check.program.digest,\n sealed: check.sealed?.digest ?? null,\n command: check.command,\n environment: check.environment,\n pass: check.pass,\n // Only when set, so a digest recorded before the field existed still matches.\n ...(check.containers === true ? { containers: true } : {}),\n }),\n ),\n )\n}\n\n/**\n * Read the check once. `result` is the submitted result, absent for a read of the run's state.\n * `state` is a local directory of the run's state; the box receives a copy of its files at\n * `_input/state/`. `set: 'sealed'` adds the sealed cases. Throws {@link CheckUnavailableError} when\n * the program could not run or printed no score.\n */\nexport async function readDeclaredCheck(\n check: DeclaredCheck,\n placement: DeclaredCheckPlacement,\n read: {\n readonly result?: unknown\n readonly state?: string\n readonly set: 'development' | 'sealed'\n readonly signal?: AbortSignal\n },\n): Promise<CheckVerdict> {\n if (read.set === 'sealed' && check.sealed === undefined) {\n throw new ValidationError('readDeclaredCheck: a sealed read needs check.sealed')\n }\n const environment = placement.env ?? process.env\n const secrets: Record<string, string> = {}\n for (const name of check.secrets ?? []) {\n const value = environment[name]\n if (value === undefined || value === '') {\n throw new CheckUnavailableError(`the check's secret ${name} is not set on this host`)\n }\n secrets[name] = value\n }\n const workspace = await mkdtemp(join(tmpdir(), 'declared-check-'))\n try {\n const tree = join(workspace, 'tree')\n await copyVerified(check.program.dir, check.program.digest, tree, 'program')\n const entries = await readdir(tree)\n if (entries.includes(INPUT_DIR) || entries.includes(SEALED_DIR)) {\n throw new ValidationError(\n `readDeclaredCheck: the program may not hold ${INPUT_DIR}/ or ${SEALED_DIR}/; Runtime mounts them`,\n )\n }\n const env: Record<string, string> = { ...secrets, CHECK_SET: read.set }\n if (read.result !== undefined) {\n await mkdir(join(tree, INPUT_DIR), { recursive: true })\n await writeFile(join(tree, INPUT_DIR, 'result.json'), `${JSON.stringify(read.result)}\\n`)\n env.CHECK_RESULT = `${INPUT_DIR}/result.json`\n }\n if (read.state !== undefined) {\n await mkdir(join(tree, INPUT_DIR, STATE_DIR), { recursive: true })\n await writeFiles(\n (await captureMaterializedWorkspace(read.state)).files,\n join(tree, INPUT_DIR, STATE_DIR),\n )\n env.CHECK_STATE = `${INPUT_DIR}/${STATE_DIR}`\n }\n if (read.set === 'sealed' && check.sealed !== undefined) {\n await copyVerified(\n check.sealed.dir,\n check.sealed.digest,\n join(tree, SEALED_DIR),\n 'sealed cases',\n )\n }\n const outcome = await runIsolatedCheck({\n workspaceRoot: workspace,\n tree,\n command: check.command,\n timeoutMs: check.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n env,\n ...(read.signal === undefined ? {} : { signal: read.signal }),\n box: {\n client: placement.client,\n builderAccounts: placement.builderAccounts,\n environment: check.environment,\n ...(check.egress === undefined ? {} : { egress: check.egress }),\n ...(check.resources === undefined ? {} : { resources: check.resources }),\n ...(check.containers === true ? { containers: true } : {}),\n },\n })\n return verdictOf(outcome, check.pass)\n } finally {\n await rm(workspace, { recursive: true, force: true })\n }\n}\n\n/**\n * The declared check as a manager's completion check: every in-run read uses development cases.\n * With `state`, each read first captures the run's state and the check reads it beside the\n * submitted result, on `submit_result` and at a turn end alike.\n */\nexport function declaredCheckDeliverable(\n check: DeclaredCheck,\n placement: DeclaredCheckPlacement,\n options: { readonly state?: DeclaredCheckStateCapture } = {},\n): DeliverableSpec<unknown> {\n assertDeclaredCheck(check, 'declaredCheckDeliverable')\n const { state } = options\n if (state !== undefined && typeof state !== 'function') {\n throw new ValidationError('declaredCheckDeliverable: state must be a capture function')\n }\n const read = async (result?: unknown): Promise<CheckVerdict> => {\n if (state === undefined)\n return readDeclaredCheck(check, placement, { result, set: 'development' })\n const into = await mkdtemp(join(tmpdir(), 'declared-check-state-'))\n try {\n try {\n await state(into)\n } catch (error) {\n throw new CheckUnavailableError(\n `the run's state could not be captured: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n )\n }\n return await readDeclaredCheck(check, placement, { result, state: into, set: 'development' })\n } finally {\n await rm(into, { recursive: true, force: true })\n }\n }\n return {\n check: (result) => read(result),\n checkState: () => read(),\n feedback: check.feedback,\n ...(check.sealed === undefined ? {} : { sealed: true }),\n ...(check.describe === undefined ? {} : { describe: check.describe }),\n }\n}\n\n/**\n * The declared check as a version chain's judge: it scores a settled version on its sealed cases\n * when the record has them, and on its development cases otherwise. The per-item verdict rides in\n * the ledger, so the next version's review names each item. A read that could not run scores\n * `null`, which never counts as an improvement.\n */\nexport function declaredCheckJudge(\n check: DeclaredCheck,\n placement: DeclaredCheckPlacement,\n): VersionJudge {\n assertDeclaredCheck(check, 'declaredCheckJudge')\n const digest = declaredCheckDigest(check)\n return {\n digest,\n async judge(version, signal) {\n try {\n const verdict = await readDeclaredCheck(check, placement, {\n ...(version.result.kind === 'winner' ? { result: version.result.out } : {}),\n set: check.sealed === undefined ? 'development' : 'sealed',\n signal,\n })\n return {\n score: verdict.composite ?? (verdict.pass ? 1 : 0),\n judgeDigest: digest,\n check: verdict,\n }\n } catch (error) {\n if (!(error instanceof CheckUnavailableError)) throw error\n return { score: null, judgeDigest: digest, detail: { unavailable: error.message } }\n }\n },\n }\n}\n\nfunction verdictOf(outcome: IsolatedCheckResult, pass: number): CheckVerdict {\n if (!outcome.succeeded) {\n throw new CheckUnavailableError(\n `the check program ${outcome.reason}: ${outcome.diagnostic.slice(0, 2_000)}`,\n )\n }\n const lines = outcome.value.stdout.trimEnd().split('\\n')\n const last = lines.at(-1) ?? ''\n let score: unknown\n try {\n score = JSON.parse(last)\n } catch {\n throw new CheckUnavailableError('the check program printed no JudgeScore on its last line')\n }\n const raw = score as {\n dimensions?: unknown\n composite?: unknown\n notes?: unknown\n failed?: unknown\n }\n if (\n typeof raw !== 'object' ||\n raw === null ||\n typeof raw.dimensions !== 'object' ||\n raw.dimensions === null ||\n typeof raw.composite !== 'number' ||\n typeof raw.notes !== 'string'\n ) {\n throw new CheckUnavailableError('the check program printed a line that is not a JudgeScore')\n }\n return verdictFromJudgeScore(\n {\n dimensions: raw.dimensions as Record<string, number>,\n composite: raw.composite,\n notes: raw.notes,\n ...(raw.failed === true ? { failed: true as const } : {}),\n },\n pass,\n )\n}\n\n/** Copy exactly the bytes whose digest was checked: the files are read once, verified, and those\n * bytes are written, so a file changed after the check cannot reach the box. */\nasync function copyVerified(\n from: string,\n digest: Sha256Digest,\n to: string,\n label: string,\n): Promise<void> {\n const captured = await captureMaterializedWorkspace(from)\n const actual = canonicalCandidateDigest(captured.manifest)\n if (actual !== digest) {\n throw new ValidationError(\n `readDeclaredCheck: the ${label} at ${from} is ${actual}; the record names ${digest}`,\n )\n }\n await writeFiles(captured.files, to)\n}\n\nasync function writeFiles(\n files: ReadonlyArray<{\n readonly path: string\n readonly mode: number\n readonly bytes: Uint8Array\n }>,\n to: string,\n): Promise<void> {\n for (const file of files) {\n const path = join(to, file.path)\n await mkdir(dirname(path), { recursive: true })\n await writeFile(path, file.bytes, { mode: file.mode })\n }\n}\n","/**\n * `loopDispatch` — turn `runAgentRounds` into an agent-eval campaign dispatch.\n *\n * Without this adapter a consumer wiring `runAgentRounds` into `runProfileMatrix` /\n * `runCampaign` has to, by hand, every time: (a) build an `ExecCtx` with a\n * sandbox client, (b) adapt the campaign `DispatchContext.trace` into a\n * `LoopTraceEmitter` (or lose all loop trace correlation), and (c) remember to\n * forward the loop's cost + tokens via `ctx.cost` (forgetting it yields a\n * `{0,0}` cell the backend-integrity guard reads as a stub). Three foot-guns,\n * the third silent. The fleet's products skipped (c) and fell back to a\n * `workerRecords[]` side-channel — the exact anti-pattern the substrate exists\n * to kill.\n *\n * `loopDispatch` collapses all three into one typed call:\n *\n * const dispatch = loopDispatch({\n * sandboxClient,\n * toLoopOptions: (scenario, profile) => ({ driver, agentRun, output, validator, task }),\n * })\n * await runProfileMatrix({ profiles, scenarios, dispatch, judges, commitSha })\n *\n * The complete Runtime cell starts inside `ctx.cost.runPaidCall` before any\n * sandbox work begins. Its provider-reported usage becomes the paid-call\n * receipt before Eval settles the call. A completed `LoopResult` cannot be\n * attached afterward because it cannot prove pre-execution admission.\n * Trace events are forwarded automatically and the Runtime context is built\n * automatically.\n *\n * Typed structurally against the campaign `DispatchContext` (imported type-only\n * from `@tangle-network/agent-eval/campaign`) — a downward dependency, never an\n * inversion.\n */\n\n// agent-eval's AgentProfile (the eval-harness unit of variation, `model: string`)\n// — NOT sandbox's AgentProfile. ProfileDispatchFn is keyed on the former.\nimport type { AgentProfile, CostReceiptInput, MaximumCharge } from '@tangle-network/agent-eval'\nimport type {\n CampaignTraceWriter,\n DispatchContext,\n DispatchFn,\n ProfileDispatchFn,\n Scenario,\n} from '@tangle-network/agent-eval/campaign'\nimport type { PromptOptions } from '@tangle-network/sandbox'\nimport { canonicalObservedModelParts } from './model-identity'\nimport { type RunAgentRoundsOptions, runAgentRounds } from './run-loop'\nimport { type SuperviseOptions, supervise } from './supervise/supervise'\nimport type { ProviderModelExecutionEvidence, SupervisedResult } from './supervise/types'\nimport type { LoopResult, LoopTokenUsage, LoopTraceEmitter, SandboxClient } from './types'\nimport { hasCompleteCacheBreakdown } from './util'\n\n/** runAgentRounds options minus the `ctx` (loopDispatch builds the ctx). */\nexport type LoopOptionsForDispatch<Task, Output, Decision> = Omit<\n RunAgentRoundsOptions<Task, Output, Decision>,\n 'ctx'\n>\n\nexport interface LoopDispatchOptions<\n Task,\n Output,\n Decision,\n TScenario extends Scenario,\n TArtifact,\n> {\n /** Sandbox client used for every cell's `runAgentRounds`. Supplied once. */\n sandboxClient: SandboxClient\n /**\n * Per-prompt sandbox SDK options for every cell, forwarded verbatim into EVERY `streamPrompt`\n * of every iteration the dispatch runs. The kernel owns `sessionId` and `signal`: both are\n * removed from the supplied value and applied last. A value that is present but is not an\n * object is a `ValidationError`, raised before any box is created.\n *\n * Typical use: `backend.model` credentials (`authMode` / `authFiles`) so every cell runs on a\n * caller-supplied subscription credential, `timeoutMs`, and `context`.\n */\n promptOptions?: Omit<PromptOptions, 'signal' | 'sessionId'>\n /** Build the per-cell runAgentRounds options from the scenario (+ profile, when\n * used with `runProfileMatrix`). */\n toLoopOptions: (\n scenario: TScenario,\n profile: AgentProfile,\n ) => LoopOptionsForDispatch<Task, Output, Decision>\n /** Map the finished loop to the artifact the judges score. Default:\n * `result.winner?.output`. A loop with no winner yields `undefined` (judges\n * skip the cell) — but the loop's token usage is STILL reported, so the\n * integrity guard sees real activity. */\n toArtifact?: (result: LoopResult<Task, Output, Decision>) => TArtifact\n /** Forward `loop.*` trace events into the campaign's scoped trace so loop\n * spans correlate with the cell. Default true. */\n forwardTrace?: boolean\n /** Cost-meter source label for the loop's spend. Default `'loop'`. */\n costSource?: string\n /** Provider- or executor-enforced maximum for this whole cell dispatch.\n * Required by agent-eval before execution when the campaign is cost-capped. */\n maximumCharge?:\n | MaximumCharge\n | ((scenario: TScenario, profile: AgentProfile) => MaximumCharge | undefined)\n /** Resolve the model actually served from the completed loop. */\n resolveCostModel?: (\n result: LoopResult<Task, Output, Decision>,\n scenario: TScenario,\n profile: AgentProfile,\n ) => string | undefined\n}\n\n/** Bridge a campaign `DispatchContext.trace` to a `LoopTraceEmitter` so every\n * `loop.*` event lands as a span under the cell's scoped trace. */\nfunction campaignTraceToLoopEmitter(trace: CampaignTraceWriter): LoopTraceEmitter {\n return {\n emit(event) {\n trace\n .span(event.kind, { runId: event.runId, timestamp: event.timestamp, ...event.payload })\n .end()\n },\n }\n}\n\nasync function runLoopForCell<Task, Output, Decision, TScenario extends Scenario, TArtifact>(\n opts: LoopDispatchOptions<Task, Output, Decision, TScenario, TArtifact>,\n scenario: TScenario,\n profile: AgentProfile,\n ctx: DispatchContext,\n): Promise<TArtifact> {\n const loopOptions = opts.toLoopOptions(scenario, profile)\n return runLoopWithCampaignContext(opts, loopOptions, ctx, {\n model: profile.model?.default ?? modelFromLoopOptions(loopOptions),\n maximumCharge:\n typeof opts.maximumCharge === 'function'\n ? opts.maximumCharge(scenario, profile)\n : opts.maximumCharge,\n resolveModel: opts.resolveCostModel\n ? (result) => opts.resolveCostModel?.(result, scenario, profile)\n : undefined,\n })\n}\n\nasync function runLoopWithCampaignContext<Task, Output, Decision, TArtifact>(\n opts: {\n sandboxClient: SandboxClient\n promptOptions?: Omit<PromptOptions, 'signal' | 'sessionId'>\n toArtifact?: (result: LoopResult<Task, Output, Decision>) => TArtifact\n forwardTrace?: boolean\n costSource?: string\n },\n loopOptions: LoopOptionsForDispatch<Task, Output, Decision>,\n ctx: DispatchContext,\n cost: {\n model: string\n maximumCharge?: MaximumCharge\n resolveModel?: (result: LoopResult<Task, Output, Decision>) => string | undefined\n },\n): Promise<TArtifact> {\n const paid = await ctx.cost.runPaidCall({\n channel: 'agent',\n actor: opts.costSource ?? 'loop',\n model: cost.model,\n signal: ctx.signal,\n ...(cost.maximumCharge ? { maximumCharge: cost.maximumCharge } : {}),\n execute: (executionSignal) =>\n runAgentRounds<Task, Output, Decision>({\n ...loopOptions,\n ctx: {\n sandboxClient: opts.sandboxClient,\n // Forwarded unvalidated: `runAgentRounds` reads it through the one shared reader, so\n // a bad value fails there rather than at a second checking site with its own rules.\n ...(opts.promptOptions === undefined ? {} : { promptOptions: opts.promptOptions }),\n signal: executionSignal,\n traceEmitter:\n opts.forwardTrace === false ? undefined : campaignTraceToLoopEmitter(ctx.trace),\n },\n }),\n receipt: (result) => loopCostReceipt(result, cost.resolveModel?.(result) ?? cost.model),\n })\n if (!paid.succeeded) {\n throw paid.error\n }\n const result = paid.value\n const toArtifact =\n opts.toArtifact ?? ((r: LoopResult<Task, Output, Decision>) => r.winner?.output as TArtifact)\n return toArtifact(result)\n}\n\nfunction loopCostReceipt<Task, Output, Decision>(\n result: LoopResult<Task, Output, Decision>,\n model: string,\n): CostReceiptInput {\n return costReceiptFromUsage(result.tokenUsage, model, {\n usageUnknown: result.tokenUsage.tokensKnown === false,\n actualCostUsd: result.costUsdKnown !== false ? result.costUsd : undefined,\n costUnknown: result.costUsdKnown === false,\n estimatedCostUsd: result.estimatedCostUsd,\n })\n}\n\n/** Map Runtime usage into Eval's canonical paid-call receipt without inventing cache classes. */\nfunction costReceiptFromUsage(\n usage: LoopTokenUsage,\n model: string,\n cost: {\n usageUnknown?: boolean\n actualCostUsd?: number\n costUnknown?: boolean\n estimatedCostUsd?: number\n },\n): CostReceiptInput {\n const cacheComplete =\n hasCompleteCacheBreakdown(usage) &&\n (usage.freshInput !== undefined ||\n usage.cacheRead !== undefined ||\n usage.cacheWrite !== undefined)\n const cacheRead = cacheComplete ? (usage.cacheRead ?? 0) : undefined\n const cacheWrite = cacheComplete ? (usage.cacheWrite ?? 0) : undefined\n const classified = (cacheRead ?? 0) + (cacheWrite ?? 0)\n return {\n model,\n // Eval prices fresh prompt input separately. A partial cache split remains one total input\n // number, rather than pretending omitted classes were zero.\n inputTokens: cacheComplete ? usage.input - classified : usage.input,\n outputTokens: usage.output,\n ...(cacheComplete ? { cachedTokens: cacheRead, cacheWriteTokens: cacheWrite } : {}),\n ...(usage.tokensKnown === false || cost.usageUnknown ? { usageUnknown: true } : {}),\n ...(cost.actualCostUsd !== undefined ? { actualCostUsd: cost.actualCostUsd } : {}),\n ...(cost.costUnknown ? { costUnknown: true } : {}),\n ...(cost.estimatedCostUsd !== undefined ? { estimatedCostUsd: cost.estimatedCostUsd } : {}),\n }\n}\n\n/** `supervise` options minus Eval-owned cancellation. */\nexport type SuperviseOptionsForDispatch = Omit<SuperviseOptions, 'signal'>\n\n/**\n * Adapt a recursive Runtime `supervise()` tree to one Agent Eval profile-matrix cell.\n *\n * The adapter starts Eval's paid-call record before the tree starts. Runtime remains the sole\n * owner of recursive execution, budgets, and the journal; Eval remains the sole owner of the\n * paid-call admission and resulting receipt.\n */\nexport interface SuperviseDispatchOptions<TScenario extends Scenario, TArtifact> {\n /** Build the task passed to the root supervisor for this profile/scenario cell. */\n toTask: (scenario: TScenario, profile: AgentProfile) => unknown\n /** Build the Runtime-owned recursive-run options for this profile/scenario cell. */\n toSuperviseOptions: (scenario: TScenario, profile: AgentProfile) => SuperviseOptionsForDispatch\n /** Map the terminal tree result to the artifact judges score. Default: winner output. */\n toArtifact?: (result: SupervisedResult<unknown>) => TArtifact\n /** Cost-meter source label. Default `'supervise'`. */\n costSource?: string\n /** Provider- or executor-enforced maximum for the complete supervised tree. */\n maximumCharge?:\n | MaximumCharge\n | ((scenario: TScenario, profile: AgentProfile) => MaximumCharge | undefined)\n}\n\ntype SupervisedTreeModel =\n | { readonly kind: 'known'; readonly model: string }\n | { readonly kind: 'mixed'; readonly models: readonly string[] }\n | { readonly kind: 'unknown' }\n\n/** Eval has one pre-admitted paid call for this dispatch. A tree can settle that call only when\n * Runtime has provider-served identity for every inference attempt that actually started. Plan\n * materialization is deliberately ignored: it describes what Runtime requested, not what the\n * provider served. Every visible terminal child must carry provider attempt evidence; a missing\n * evidence record stays unknown, including zero-valued or incomplete spend.\n * @internal Testable identity projection used by superviseDispatch. */\nexport function supervisedTreeModelForDispatch(\n result: SupervisedResult<unknown>,\n rootProfile: AgentProfile,\n): SupervisedTreeModel {\n void rootProfile\n const canonicalModels = new Set<string>()\n const observedModels: string[] = []\n const wholeTreeEvidence = result.providerModel\n if (\n wholeTreeEvidence === undefined ||\n (wholeTreeEvidence.status !== 'known' &&\n wholeTreeEvidence.reason !== 'provider-model-conflict') ||\n wholeTreeEvidence.attempts.length === 0\n ) {\n return { kind: 'unknown' }\n }\n // Runtime validates each configured executor against its own profile before this boundary. The\n // whole-tree reducer intentionally erases ownership, so this final pass checks only that every\n // served attempt has one homogeneous canonical identity.\n const wholeTreeIdentity = collectProviderModels(wholeTreeEvidence, () => true)\n if (wholeTreeIdentity.kind !== 'known') return wholeTreeIdentity\n for (const model of wholeTreeIdentity.observed) {\n observedModels.push(model.raw)\n canonicalModels.add(model.canonical)\n }\n if (canonicalModels.size === 0) return { kind: 'unknown' }\n if (canonicalModels.size !== 1) {\n return { kind: 'mixed', models: [...canonicalModels].sort() }\n }\n return { kind: 'known', model: observedModels[0] as string }\n}\n\ntype CollectedProviderModel = { readonly raw: string; readonly canonical: string }\n\ntype ProviderModelCollection =\n | { readonly kind: 'known'; readonly observed: ReadonlyArray<CollectedProviderModel> }\n | { readonly kind: 'mixed'; readonly models: ReadonlyArray<string> }\n | { readonly kind: 'unknown' }\n\nfunction collectProviderModels(\n evidence: ProviderModelExecutionEvidence,\n validate: (model: string) => boolean,\n): ProviderModelCollection {\n if (\n (evidence.status !== 'known' && evidence.reason !== 'provider-model-conflict') ||\n !Array.isArray(evidence.attempts) ||\n evidence.attempts.length === 0 ||\n !Array.isArray(evidence.models)\n ) {\n return { kind: 'unknown' }\n }\n const observed: CollectedProviderModel[] = []\n const canonical = new Set<string>()\n const observedRaw = new Set<string>()\n for (const attempt of evidence.attempts) {\n if (attempt.providerDispatch === 'not_started') {\n // Router proved that this attempt stopped at admission. It contributes no served\n // identity, but it must not poison a different attempt that did reach a provider.\n if (attempt.observations.length > 0 || attempt.identityConflict === true) {\n return { kind: 'unknown' }\n }\n continue\n }\n // An attempt entry is created immediately before provider execution. Empty means that\n // execution started but no trusted served model arrived, including an abort after spend.\n if (\n attempt === null ||\n typeof attempt !== 'object' ||\n !Array.isArray(attempt.observations) ||\n attempt.observations.length === 0 ||\n attempt.identityConflict === true\n ) {\n return { kind: 'unknown' }\n }\n let attemptBase: string | undefined\n let attemptSnapshot: string | undefined\n let attemptSnapshotKind: 'date' | 'opaque' | undefined\n let representative: string | undefined\n for (const model of attempt.observations) {\n if (typeof model !== 'string' || !validate(model)) return { kind: 'unknown' }\n const identity = canonicalObservedModelParts(model)\n if (identity === undefined) return { kind: 'unknown' }\n const base = identity.base\n const snapshot = identity.snapshot\n if (attemptBase !== undefined && attemptBase !== base) {\n return {\n kind: 'mixed',\n models: [...new Set([...(attemptBase ? [attemptBase] : []), identity.canonical])],\n }\n }\n if (\n attemptSnapshot !== undefined &&\n snapshot !== undefined &&\n (attemptSnapshot !== snapshot || attemptSnapshotKind !== identity.snapshotKind)\n ) {\n if (attemptBase === undefined || attemptSnapshotKind === undefined) {\n return { kind: 'unknown' }\n }\n return {\n kind: 'mixed',\n models: [\n attemptIdentityText(attemptBase, attemptSnapshot, attemptSnapshotKind),\n identity.canonical,\n ],\n }\n }\n attemptBase = base\n attemptSnapshot ??= snapshot\n attemptSnapshotKind ??= identity.snapshotKind\n if (snapshot !== undefined) representative = model\n observedRaw.add(model)\n }\n if (\n attemptBase === undefined ||\n attemptSnapshot === undefined ||\n attemptSnapshotKind === undefined ||\n representative === undefined\n ) {\n // A bare route name is useful only as a prefix observation. Exact identity still requires\n // one qualified snapshot from the same provider attempt.\n return { kind: 'unknown' }\n }\n const attemptIdentity = attemptIdentityText(attemptBase, attemptSnapshot, attemptSnapshotKind)\n observed.push({ raw: representative, canonical: attemptIdentity })\n canonical.add(attemptIdentity)\n }\n if (observed.length === 0) return { kind: 'unknown' }\n const declaredRaw = new Set<string>()\n for (const model of evidence.models) {\n if (typeof model !== 'string') return { kind: 'unknown' }\n declaredRaw.add(model)\n }\n if (\n declaredRaw.size !== observedRaw.size ||\n [...declaredRaw].some((model) => !observedRaw.has(model))\n ) {\n return { kind: 'unknown' }\n }\n return canonical.size > 1\n ? { kind: 'mixed', models: [...canonical].sort() }\n : { kind: 'known', observed }\n}\n\nfunction attemptIdentityText(base: string, snapshot: string, kind: 'date' | 'opaque'): string {\n return kind === 'date' ? `${base}-${snapshot}` : `${base}@${snapshot}`\n}\n\n/** The Eval receipt surface has no pre-admitted per-model recursive-tree receipt bundle yet. */\nclass SupervisedTreeModelIdentityError extends Error {\n constructor(identity: Exclude<SupervisedTreeModel, { readonly kind: 'known' }>) {\n const detail =\n identity.kind === 'mixed'\n ? `multiple models (${identity.models.join(', ')})`\n : 'an unknown materialized model'\n super(`superviseDispatch: cannot settle one Eval paid-call receipt for a tree with ${detail}`)\n this.name = 'SupervisedTreeModelIdentityError'\n }\n}\n\nfunction unknownSupervisedTreeReceipt(): CostReceiptInput {\n return {\n model: 'unknown',\n inputTokens: 0,\n outputTokens: 0,\n usageUnknown: true,\n costUnknown: true,\n }\n}\n\n/** Run one recursive supervised tree inside Eval's pre-execution paid-call lifecycle. */\nexport function superviseDispatch<TScenario extends Scenario, TArtifact>(\n opts: SuperviseDispatchOptions<TScenario, TArtifact>,\n): ProfileDispatchFn<TScenario, TArtifact> {\n return async (profile, scenario, ctx) => {\n const superviseOptions = opts.toSuperviseOptions(scenario, profile)\n const task = opts.toTask(scenario, profile)\n const maximumCharge =\n typeof opts.maximumCharge === 'function'\n ? opts.maximumCharge(scenario, profile)\n : opts.maximumCharge\n const paid = await ctx.cost.runPaidCall({\n channel: 'agent',\n actor: opts.costSource ?? 'supervise',\n // A child profile can choose a different model after this call has been admitted. Until the\n // finished tree proves one uniform materialized model, naming the root model would be false.\n model: 'unknown',\n signal: ctx.signal,\n ...(maximumCharge ? { maximumCharge } : {}),\n // The execution signal is written last so a caller cannot bypass Eval cancellation.\n execute: async (executionSignal) => {\n const result = await supervise(profile, task, {\n ...superviseOptions,\n signal: executionSignal,\n })\n const identity = supervisedTreeModelForDispatch(result, profile)\n if (identity.kind !== 'known') throw new SupervisedTreeModelIdentityError(identity)\n return result\n },\n receipt: (result) => {\n const identity = supervisedTreeModelForDispatch(result, profile)\n if (identity.kind !== 'known') throw new SupervisedTreeModelIdentityError(identity)\n return costReceiptFromUsage(result.spentTotal.tokens, identity.model, {\n usageUnknown: result.spentTotal.tokensKnown === false,\n actualCostUsd: result.spentTotal.usdKnown !== false ? result.spentTotal.usd : undefined,\n costUnknown: result.spentTotal.usdKnown === false,\n })\n },\n receiptFromError: (error) =>\n error instanceof SupervisedTreeModelIdentityError\n ? unknownSupervisedTreeReceipt()\n : undefined,\n })\n if (!paid.succeeded) throw paid.error\n const toArtifact =\n opts.toArtifact ??\n ((result: SupervisedResult<unknown>) => {\n if (result.kind !== 'winner') {\n throw new Error(\n `superviseDispatch: supervised tree ended without a winner (${result.reason})`,\n )\n }\n return result.out as TArtifact\n })\n return toArtifact(paid.value)\n }\n}\n\nfunction modelFromLoopOptions<Task, Output, Decision>(\n options: LoopOptionsForDispatch<Task, Output, Decision>,\n): string {\n const profiles = options.agentRun\n ? [options.agentRun.profile]\n : (options.agentRuns?.map((run) => run.profile) ?? [])\n const models = new Set(\n profiles.map((profile) => profile.model?.default).filter((model): model is string => !!model),\n )\n if (models.size === 1) return [...models][0] as string\n return models.size > 1 ? 'mixed' : 'unknown'\n}\n\n/** Options for adapting plain agent-eval campaign scenarios into Runtime cells. */\nexport interface LoopCampaignDispatchOptions<\n Task,\n Output,\n Decision,\n TScenario extends Scenario,\n TArtifact,\n> {\n /** Sandbox client used for every campaign cell's `runAgentRounds`. */\n sandboxClient: SandboxClient\n /**\n * Per-prompt sandbox SDK options for every cell, forwarded verbatim into EVERY `streamPrompt`\n * of every iteration the dispatch runs. The kernel owns `sessionId` and `signal`: both are\n * removed from the supplied value and applied last. A value that is present but is not an\n * object is a `ValidationError`, raised before any box is created.\n */\n promptOptions?: Omit<PromptOptions, 'signal' | 'sessionId'>\n /** Build the per-cell runAgentRounds options from the campaign scenario. */\n toLoopOptions: (scenario: TScenario) => LoopOptionsForDispatch<Task, Output, Decision>\n /** Map the finished loop to the artifact the campaign judges score. */\n toArtifact?: (result: LoopResult<Task, Output, Decision>) => TArtifact\n /** Forward `loop.*` trace events into the campaign's scoped trace. Default true. */\n forwardTrace?: boolean\n /** Cost-meter source label for the loop's spend. Default `'loop'`. */\n costSource?: string\n /** Provider- or executor-enforced maximum for this whole cell dispatch. */\n maximumCharge?: MaximumCharge | ((scenario: TScenario) => MaximumCharge | undefined)\n /** Resolve the model actually served from the completed loop. */\n resolveCostModel?: (\n result: LoopResult<Task, Output, Decision>,\n scenario: TScenario,\n ) => string | undefined\n}\n\n/**\n * Adapter for plain `runCampaign` scenarios. This is the Runtime-side pair for\n * agent-eval fixture scenarios: load fixtures in `agent-eval/campaign`, build\n * the Runtime cell here, and keep paid-call admission, receipts, and traces\n * automatic.\n */\nexport function loopCampaignDispatch<Task, Output, Decision, TScenario extends Scenario, TArtifact>(\n opts: LoopCampaignDispatchOptions<Task, Output, Decision, TScenario, TArtifact>,\n): DispatchFn<TScenario, TArtifact> {\n return (scenario, ctx) => {\n const loopOptions = opts.toLoopOptions(scenario)\n return runLoopWithCampaignContext(opts, loopOptions, ctx, {\n model: modelFromLoopOptions(loopOptions),\n maximumCharge:\n typeof opts.maximumCharge === 'function'\n ? opts.maximumCharge(scenario)\n : opts.maximumCharge,\n resolveModel: opts.resolveCostModel\n ? (result) => opts.resolveCostModel?.(result, scenario)\n : undefined,\n })\n }\n}\n\n/**\n * Adapter for `runProfileMatrix` (profile is an axis). Returns a\n * `ProfileDispatchFn` that runs `runAgentRounds` per (profile, scenario) cell\n * inside Eval's paid-call lifecycle.\n */\nexport function loopDispatch<Task, Output, Decision, TScenario extends Scenario, TArtifact>(\n opts: LoopDispatchOptions<Task, Output, Decision, TScenario, TArtifact>,\n): ProfileDispatchFn<TScenario, TArtifact> {\n return (profile, scenario, ctx) => runLoopForCell(opts, scenario, profile, ctx)\n}\n","/**\n * The ONE pseudo-box adapter: present any one-shot `Executor` (router / bridge /\n * BYO) as a `SandboxClient` so the round-synchronous `runAgentRounds` can drive it\n * without each call site re-faking a box. This is the single shell that\n * `bench/src/router-executor.ts`, generate-eval's old `bridgeSandboxClient`, and\n * the search-bench bridge transport were each re-implementing.\n *\n * It is deliberately for NON-box executors only — a real sandbox harness already\n * IS a `SandboxClient` (boxes, sessions, fs, fork are real there). Here each\n * `streamPrompt` runs the executor once and emits its result plus the canonical\n * `done` event. The result carries output and usage; `done` confirms execution settled.\n * There are no sessions, no fs,\n * no fork (those degrade gracefully via the optional `SandboxClient` methods).\n */\n\nimport { type AgentProfile, agentProfileSchema } from '@tangle-network/agent-interface'\nimport type { CreateSandboxOptions, SandboxEvent, SandboxInstance } from '@tangle-network/sandbox'\nimport { assertBoxlessPromptOptions } from './prompt-options'\nimport type { AgentSpec, Executor, ExecutorFactory, ExecutorResult } from './supervise/types'\nimport type { SandboxClient } from './types'\n\nfunction isAsyncIterable(v: unknown): v is AsyncIterable<unknown> {\n return typeof v === 'object' && v !== null && Symbol.asyncIterator in v\n}\n\n/** Drive a (possibly streaming) executor to its terminal artifact. */\nasync function settle(\n exec: Executor<unknown>,\n task: unknown,\n signal: AbortSignal,\n): Promise<ExecutorResult<unknown>> {\n const r = exec.execute(task, signal)\n if (isAsyncIterable(r)) {\n for await (const _ of r) {\n // streaming executors meter as they run; the artifact is read after drain.\n }\n return exec.resultArtifact()\n }\n return r\n}\n\n/**\n * Adapt an `ExecutorFactory` into a `SandboxClient` for `runAgentRounds`. The factory is\n * instantiated fresh per `streamPrompt` (mirrors the per-spawn executor lifecycle):\n * run once on the prompt, emit the terminal result event, tear down.\n *\n * There is no box, so a per-prompt `backend` or `model` override is refused rather than dropped;\n * other per-prompt options (`timeoutMs`, `context`) are accepted and ignored.\n */\nexport function inlineSandboxClient(\n factory: ExecutorFactory<unknown>,\n defaults: { profile?: AgentProfile } = {},\n): SandboxClient {\n const capturedDefaultProfile =\n defaults.profile === undefined\n ? undefined\n : agentProfileSchema.parse(structuredClone(defaults.profile))\n let seq = 0\n return {\n async create(options?: CreateSandboxOptions): Promise<SandboxInstance> {\n const id = `inline-${seq++}`\n // The requested backend remains visible so Runtime can reject a conflicting redundant\n // declaration. The exact profile below remains the sole behavioral source.\n const createOptions = options\n return {\n id,\n async *streamPrompt(\n message: string,\n opts?: { signal?: AbortSignal },\n ): AsyncGenerator<SandboxEvent> {\n assertBoxlessPromptOptions(opts, 'inlineSandboxClient')\n // Chain the caller's turn signal into the executor's spawn signal so\n // an abort reaches `exec.execute` — a cooperative executor settles\n // (throws) instead of running to completion after cancellation.\n const controller = new AbortController()\n const callerSignal = opts?.signal\n const onAbort = () =>\n controller.abort(callerSignal?.reason ?? new Error('prompt aborted'))\n if (callerSignal) {\n if (callerSignal.aborted) onAbort()\n else callerSignal.addEventListener('abort', onAbort, { once: true })\n }\n const requestedProfile =\n (options?.backend && typeof options.backend === 'object'\n ? (options.backend as { profile?: unknown }).profile\n : undefined) ?? capturedDefaultProfile\n const parsedProfile = agentProfileSchema.safeParse(requestedProfile)\n if (!parsedProfile.success) {\n throw new Error(\n 'inlineSandboxClient: an exact AgentProfile is required; pass defaults.profile or create({ backend: { profile } })',\n )\n }\n const spec: AgentSpec = { profile: parsedProfile.data, harness: null }\n const exec = factory(spec, { signal: controller.signal, seams: { createOptions } })\n try {\n const artifact = await settle(exec, message, controller.signal)\n const out = artifact.out as\n | {\n content?: string\n estimatedCostUsd?: number\n promptCache?: Readonly<Record<string, number | string>>\n }\n | undefined\n // Speak the runtime's metering protocol: `extractLlmCallEvent` reads\n // flat `llm_call` events, not the nested result payload — without\n // this the kernel meters the iteration as a fabricated $0 / 0 tokens.\n const tokensIn = artifact.spent.tokens.input\n const tokensOut = artifact.spent.tokens.output\n const costUsd = artifact.spent.usd\n const estimatedCostUsd = out?.estimatedCostUsd\n if (\n artifact.spent.iterations > 0 ||\n artifact.spent.tokensKnown === false ||\n artifact.spent.usdKnown === false ||\n tokensIn > 0 ||\n tokensOut > 0 ||\n costUsd > 0 ||\n estimatedCostUsd !== undefined\n ) {\n yield {\n type: 'llm_call',\n data: {\n ...(artifact.spent.tokensKnown === false ? {} : { tokensIn, tokensOut }),\n ...(artifact.spent.usdKnown !== false ? { costUsd } : {}),\n ...(artifact.spent.tokensKnown === false ? { tokensKnown: false } : {}),\n ...(artifact.spent.usdKnown === false ? { costKnown: false } : {}),\n ...(artifact.spent.usdKnown !== false\n ? {\n costKnown: true,\n costProvenance: 'provider-receipt',\n }\n : {}),\n ...(estimatedCostUsd !== undefined ? { estimatedCostUsd } : {}),\n ...(out?.promptCache ? { promptCache: out.promptCache } : {}),\n },\n } as unknown as SandboxEvent\n }\n yield {\n type: 'result',\n data: {\n finalText: out?.content ?? '',\n ...(artifact.spent.tokensKnown === false\n ? { tokensKnown: false }\n : {\n tokenUsage: {\n inputTokens: tokensIn,\n outputTokens: tokensOut,\n },\n }),\n ...(artifact.spent.usdKnown === false\n ? { costKnown: false, ...(costUsd > 0 ? { costUsd } : {}) }\n : {\n costUsd,\n costKnown: true,\n costProvenance: 'provider-receipt',\n }),\n ...(estimatedCostUsd !== undefined ? { estimatedCostUsd } : {}),\n ...(out?.promptCache ? { promptCache: out.promptCache } : {}),\n },\n } as unknown as SandboxEvent\n // A returned ExecutorResult is settled execution; its optional evaluation\n // verdict describes artifact quality and does not change completion.\n yield { type: 'done', data: { outcome: { type: 'completed' } } }\n } finally {\n callerSignal?.removeEventListener('abort', onAbort)\n await exec.teardown('brutalKill').catch(() => {})\n }\n },\n async delete(): Promise<void> {},\n } as unknown as SandboxInstance\n },\n }\n}\n","/**\n * `localSandboxClient` — the SAME-HOST pseudo-box: a `SandboxClient` whose\n * `create()` MATERIALIZES the profile's stdio MCP servers as local child\n * processes (`materializeLocalMcp`) and whose `streamPrompt` drives a real\n * tool loop (`runBrainLoop` over the router brain) with those live tools.\n *\n * Despite the interface name, this does NOT isolate processes. It is only for\n * author-controlled profiles whose local MCP commands a caller explicitly\n * trusts; user- or model-authored code belongs in a real sandbox. `delete()`\n * kills the children.\n *\n * A per-create profile may change the prompt surface. Permission to start a\n * local MCP process applies only when its full canonical bytes match the fixed\n * constructor profile; a different generated profile is refused.\n *\n * Event protocol matches `inlineSandboxClient`: known token usage is emitted as one `llm_call`;\n * Router catalog cost remains a separately-labelled estimate, never billed spend.\n */\n\nimport {\n type AgentProfile,\n type AgentProfileSecurityPolicy,\n canonicalAgentProfileDigest,\n} from '@tangle-network/agent-interface'\nimport type { CreateSandboxOptions, SandboxEvent, SandboxInstance } from '@tangle-network/sandbox'\nimport { ValidationError } from '../errors'\nimport type { KeyProvider } from './key-provider'\nimport { assertBoxlessPromptOptions } from './prompt-options'\nimport { routerBrain } from './router-client'\nimport { materializeLocalMcp } from './stdio-mcp-client'\nimport { executableAgentProfileSnapshot } from './supervise/executable-spec'\nimport {\n enforceTokenLimits,\n profileModelExecutionSettings,\n profileProviderModel,\n} from './supervise/model-policy'\nimport { runBrainLoop, type ToolLoopChat } from './tool-loop'\nimport type { SandboxClient } from './types'\n\nexport interface LocalSandboxClientOptions {\n /** Router endpoint/auth. The exact per-create profile owns model and loop behavior. */\n router: { baseUrl: string; key: string }\n /** Fallback profile when `create(options)` carries none on `backend.profile`. */\n profile?: AgentProfile\n /** Resolves profile-declared MCP secret names at child-process spawn time. */\n keys?: KeyProvider\n /** Explicit trust decision for the exact `profile` bytes supplied here.\n * Omit to refuse local processes. A permissive policy never transfers to a\n * different per-create profile and provides no host isolation. */\n profileSecurityPolicy?: AgentProfileSecurityPolicy\n}\n\n/** A same-host `SandboxClient` adapter with no process isolation. Local MCP is\n * refused unless the caller explicitly supplies a policy that allows it.\n *\n * There is no box, so a per-prompt `backend` or `model` override is refused rather than dropped;\n * other per-prompt options (`timeoutMs`, `context`) are accepted and ignored. */\nexport function localSandboxClient(opts: LocalSandboxClientOptions): SandboxClient {\n const defaultProfile =\n opts.profile === undefined\n ? undefined\n : executableAgentProfileSnapshot(opts.profile, 'localSandboxClient default profile')\n const router = Object.freeze({ ...opts.router })\n if (opts.profileSecurityPolicy?.allowLocalMcp && defaultProfile === undefined) {\n throw new ValidationError(\n 'localSandboxClient: allowLocalMcp requires a fixed author-controlled profile; dynamic profiles need a real sandbox',\n )\n }\n const trustedProfileDigest =\n opts.profileSecurityPolicy?.allowLocalMcp && defaultProfile !== undefined\n ? canonicalAgentProfileDigest(defaultProfile)\n : undefined\n let seq = 0\n return {\n async create(options?: CreateSandboxOptions): Promise<SandboxInstance> {\n const profile = executableAgentProfileSnapshot(\n (options?.backend as { profile?: AgentProfile } | undefined)?.profile ?? defaultProfile,\n 'localSandboxClient',\n )\n const profileModel = profileProviderModel(profile)\n const model = profileModel!\n const settings = profileModelExecutionSettings(profile, 'localSandboxClient')\n const policyApplies =\n opts.profileSecurityPolicy !== undefined &&\n (!opts.profileSecurityPolicy.allowLocalMcp ||\n (trustedProfileDigest !== undefined &&\n canonicalAgentProfileDigest(profile) === trustedProfileDigest))\n // Materialize NOW: a declared server that cannot boot fails the create,\n // not the first prompt — matching the real sandbox backend, where a box\n // whose MCP cannot start never comes up.\n const mcp = await materializeLocalMcp(profile, {\n ...(opts.keys ? { keys: opts.keys } : {}),\n ...(policyApplies ? { profileSecurityPolicy: opts.profileSecurityPolicy } : {}),\n })\n const brain: ToolLoopChat = routerBrain(\n {\n routerBaseUrl: router.baseUrl,\n routerKey: router.key,\n model,\n ...(settings.retry !== undefined ? { retry: settings.retry } : {}),\n ...enforceTokenLimits(settings.tokenLimits, 'router', 'localSandboxClient').applied,\n ...(settings.stream !== undefined ? { stream: settings.stream } : {}),\n },\n {\n ...(settings.temperature !== undefined ? { temperature: settings.temperature } : {}),\n ...(settings.seed !== undefined ? { seed: settings.seed } : {}),\n ...(settings.toolChoice !== undefined ? { toolChoice: settings.toolChoice } : {}),\n ...(settings.extraBody !== undefined ? { extraBody: settings.extraBody } : {}),\n ...(profile.model?.reasoningEffort\n ? { reasoningEffort: profile.model.reasoningEffort }\n : {}),\n },\n )\n const system = [profile.prompt?.systemPrompt, ...(profile.prompt?.instructions ?? [])]\n .filter((s): s is string => typeof s === 'string' && s.trim().length > 0)\n .join('\\n\\n')\n const id = `local-${seq++}`\n return {\n id,\n async *streamPrompt(\n message: string,\n popts?: { signal?: AbortSignal },\n ): AsyncGenerator<SandboxEvent> {\n assertBoxlessPromptOptions(popts, 'localSandboxClient')\n let estimatedCostUsd = 0\n let sawEstimatedCost = false\n const chat: ToolLoopChat = async (messages, tools) => {\n const r = await brain(messages, tools)\n if (r.costProvenance === 'catalog-estimate' && r.costUsd !== undefined) {\n estimatedCostUsd += r.costUsd\n sawEstimatedCost = true\n }\n return r\n }\n const r = await runBrainLoop({\n chat,\n tools: mcp.tools,\n execute: (name, args) => mcp.call(name, args),\n initialMessages: [\n ...(system ? [{ role: 'system', content: system }] : []),\n { role: 'user', content: message },\n ],\n maxTurns: settings.maxTurns ?? 0,\n hooks: { stopBefore: () => popts?.signal?.aborted === true },\n })\n // RouterClient prices locally. Emit measured tokens only when every turn reported them;\n // never project the catalog estimate into SandboxEvent.costUsd.\n if (r.turns > 0) {\n yield {\n type: 'llm_call',\n data: {\n model,\n // The full offered set was right here in `mcp.tools` — record it so a\n // `tools.enforced` contract gate on this trace can tell \"offered nothing\" from\n // \"the offered set was never recorded\" (review finding on rows 13/14).\n tools: mcp.tools.map((t) => t.function.name),\n ...(r.tokensKnown === false\n ? { tokensKnown: false }\n : { tokensIn: r.usage.input, tokensOut: r.usage.output }),\n costKnown: false,\n ...(sawEstimatedCost ? { estimatedCostUsd } : {}),\n },\n } as unknown as SandboxEvent\n }\n yield {\n type: 'result',\n data: {\n finalText: r.final,\n ...(r.tokensKnown === false\n ? { tokensKnown: false }\n : { tokenUsage: { inputTokens: r.usage.input, outputTokens: r.usage.output } }),\n costKnown: false,\n ...(sawEstimatedCost ? { estimatedCostUsd } : {}),\n },\n } as unknown as SandboxEvent\n },\n async delete(): Promise<void> {\n await mcp.close()\n },\n } as unknown as SandboxInstance\n },\n }\n}\n","/**\n * The product-facing backend selector: one call picks the execution transport a\n * `runAgentRounds` (or any consumer that drives a `SandboxClient`) runs on, from the\n * package a product already depends on. It is pure sugar over the existing\n * primitives — `createExecutor({ backend })` + `inlineSandboxClient` — and adds\n * ZERO transport code (the node:http cli-bridge transport lives in `bridgeExecutor`).\n *\n * The heavy `resolveBenchClient` in `@tangle-network/agent-bench` is the bench-side\n * sibling: it layers router/search specifics a product should not have to depend on.\n * This is the generic, dep-light core products call to switch backends:\n *\n * - `backend: 'sandbox'` → IN-BOX: return the caller's real Sandbox-backed\n * `sandboxClient` unchanged. Fail loud if absent — a\n * product on the sandbox backend already holds its box.\n * - `backend: 'bridge'` → OFF-BOX: a local cli-bridge fronting a harness CLI\n * (opencode / kimi-code / …) as the leaf executor, wired\n * through the resumable `bridgeExecutor`.\n * - `backend: 'router'` → OFF-BOX: a router chat-completion as the leaf executor,\n * presented as a `SandboxClient` (no sandbox dependency).\n * - `backend: 'local'` → SAME-HOST: a router-brain tool loop with the\n * profile's stdio MCP servers spawned as LOCAL child\n * processes — the only backend that can reach an MCP\n * server built into a host worktree.\n */\n\nimport { inlineSandboxClient } from './inline-sandbox-client'\nimport { type LocalSandboxClientOptions, localSandboxClient } from './local-sandbox-client'\nimport { createExecutor } from './supervise/runtime'\nimport type { SandboxClient } from './types'\n\nexport interface ResolveSandboxClientOptions {\n /** The execution transport for the driven loop. */\n backend: 'sandbox' | 'bridge' | 'router' | 'local'\n /** `sandbox` backend: the caller's real Sandbox-backed client. Required for that backend. */\n sandboxClient?: SandboxClient\n /** `bridge` backend: local cli-bridge transport. The per-create profile owns the model. */\n bridge?: {\n /** cli-bridge base URL. Defaults to `http://127.0.0.1:3355`. */\n url?: string\n bearer: string\n /** Per-turn deadline (ms). */\n timeoutMs?: number\n }\n /** `router` backend: endpoint/auth only; the per-create profile owns behavior. */\n router?: {\n baseUrl: string\n key: string\n }\n /** `local` backend: same-host pseudo-box — the router brain drives a tool loop\n * with the profile's stdio MCP servers spawned as local children. */\n local?: LocalSandboxClientOptions\n}\n\n/**\n * Resolve a `SandboxClient` for the chosen backend. The generic, dep-light core\n * that `resolveBenchClient` builds on — reuse this instead of hand-rolling the\n * `createExecutor`/`inlineSandboxClient` branch in each product.\n */\nexport function resolveSandboxClient(opts: ResolveSandboxClientOptions): SandboxClient {\n switch (opts.backend) {\n case 'sandbox': {\n if (!opts.sandboxClient) {\n throw new Error(\"resolveSandboxClient: backend 'sandbox' requires opts.sandboxClient\")\n }\n return opts.sandboxClient\n }\n case 'bridge': {\n const bridge = opts.bridge\n if (!bridge?.bearer) {\n throw new Error(\"resolveSandboxClient: backend 'bridge' requires bridge.bearer\")\n }\n return inlineSandboxClient(\n createExecutor({\n backend: 'bridge',\n bridgeUrl: bridge.url ?? 'http://127.0.0.1:3355',\n bridgeBearer: bridge.bearer,\n timeoutMs: bridge.timeoutMs,\n }),\n )\n }\n case 'router': {\n const router = opts.router\n if (!router?.baseUrl || !router.key) {\n throw new Error(\n \"resolveSandboxClient: backend 'router' requires router.baseUrl and router.key\",\n )\n }\n return inlineSandboxClient(\n createExecutor({\n backend: 'router',\n routerBaseUrl: router.baseUrl,\n routerKey: router.key,\n }),\n )\n }\n case 'local': {\n const local = opts.local\n if (!local?.router?.baseUrl || !local.router.key) {\n throw new Error(\n \"resolveSandboxClient: backend 'local' requires local.router.baseUrl and local.router.key\",\n )\n }\n return localSandboxClient(local)\n }\n }\n}\n","/**\n * `defineLeaderboard` — the declarative eval-leaderboard facade.\n *\n * A product's harness×model leaderboard is always the same assembly: expand a\n * base profile across the harness×model axes (`expandProfileAxes`), run every\n * (profile, case) cell as a driven loop (`loopDispatch` + the naive retry driver), score\n * with the domain's grader, and emit ONE `runProfileMatrix` call. Each product\n * hand-rolled that assembly (~650 lines each) and re-hit the same footguns:\n * stale cell-cache reuse, zero-token stub cells, missing model snapshots.\n *\n * This facade IS that assembly, once, with the domain reduced to a declarative\n * spec: `cases` + `prompt` + `score`. It contains NO execution, judging, or\n * metering logic of its own — every moving part is an existing primitive, and\n * every default is overridable:\n *\n * - LEVEL 0 (declarative): `cases` / `prompt` / `score` / `axis`.\n * - LEVEL 1 (seams): `backends`, `flags`, `parseOutput`, `onCellEvents`,\n * `resolveModel`, `setup`/`teardown`, `export`, `matrix`\n * passthrough.\n * - LEVEL 2 (replacement): `dispatch` and `judges` swap out the whole\n * loop wiring or scoring; `runProfileMatrix` itself stays public as the\n * escape floor — a product overriding everything just writes what it has\n * today, no capability removed.\n *\n * `toBenchmarkAdapter()` exposes the same domain surface in the structural\n * `BenchmarkAdapter` shape (`name`/`preflight`/`loadTasks`/`judge`/\n * `goldArtifact`) so a product leaderboard can register into a benchmark\n * registry without this module depending on one.\n *\n * @experimental\n */\nimport { execFileSync } from 'node:child_process'\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport {\n type AgentProfile,\n CODING_HARNESSES,\n expandProfileAxes,\n type HarnessType,\n type MaximumCharge,\n} from '@tangle-network/agent-eval'\nimport {\n type JudgeConfig,\n type ProfileDispatchFn,\n type RunProfileMatrixOptions,\n type RunProfileMatrixResult,\n runProfileMatrix,\n type Scenario,\n} from '@tangle-network/agent-eval/campaign'\nimport { collectAgentResponseText, type SandboxEvent } from '@tangle-network/sandbox'\nimport { leaderboard, renderLeaderboardMarkdown } from './benchmark-report'\nimport { loopDispatch } from './loop-dispatch'\nimport { resolveSandboxClient } from './resolve-sandbox-client'\nimport { assertExecutableAgentProfile } from './supervise/model-policy'\nimport type { Driver, LoopResult, SandboxClient } from './types'\n\n/** Structured per-case verdict a `score` function may return (a bare number is\n * shorthand for `{ composite }`). `composite` is the [0,1] leaderboard score;\n * `dimensions` are recorded as extra judge dimensions. */\nexport interface LeaderboardScore {\n composite: number\n dimensions?: Record<string, number>\n notes?: string\n}\n\n/** The campaign scenario a case is wrapped into: the case rides along so\n * judges and hooks can reach the full domain payload, not just its id. */\nexport interface LeaderboardScenario<TCase> extends Scenario {\n case: TCase\n}\n\n/** Terminal-or-continue decision set of {@link naiveRetryDriver}: the non-terminal `'refine'`\n * requests another shot; `'pick-winner'`/`'fail'` stop the loop (`isTerminalDecision` in\n * run-loop.ts treats them as terminal). */\nexport type NaiveRetryDecision = 'refine' | 'pick-winner' | 'fail'\n\n/**\n * The no-signal retry floor as a bare `Driver` literal: re-run the case VERBATIM as an\n * independent attempt until one shot scores (`verdict.valid`) or the shot cap. It reads ONLY\n * `verdict.valid` — never `notes`/`scores` — so a leaderboard cell's retries carry no grader\n * findings into the next shot (the leak-free firewall). Steering POLICY texts are registry data\n * (`delegates/naive-continuation` and siblings in the kernel prompt registry) attached to graph\n * edges; this loop-kernel control folds no text in — each shot is the same task object, and the\n * per-shot nonce in `taskToPrompt` keeps the attempts independent at the router.\n */\nexport function naiveRetryDriver<TCase, TArtifact>(\n shots: number,\n): Driver<LeaderboardScenario<TCase>, TArtifact, NaiveRetryDecision> {\n return {\n name: 'naive',\n plan(task, history) {\n if (history.length === 0) return Promise.resolve([task])\n const last = history[history.length - 1]\n if (last?.verdict?.valid === true) return Promise.resolve([])\n if (history.length >= shots) return Promise.resolve([])\n return Promise.resolve([task])\n },\n decide(history) {\n if (history.some((it) => it.verdict?.valid)) return 'pick-winner'\n return history.length < shots ? 'refine' : 'fail'\n },\n describePlan() {\n return { kind: 'refine', rationale: 'naive fixed continuation (no grade signal)' }\n },\n }\n}\n\n/** One extra CLI flag a spec declares. Parsed by `run()` as `--<name> <value>`\n * and surfaced to every hook via `ctx.args`. */\nexport interface LeaderboardFlagSpec {\n default?: string\n description: string\n}\n\n/** Resolved run configuration handed to `setup` / `teardown` / `export`. */\nexport interface LeaderboardRunContext {\n name: string\n /** Execution backend name (`--backend`), a key of `backends`. */\n backend: string\n runDir: string\n exportDir: string\n /** Every parsed flag (standard + `spec.flags`), by name without `--`. */\n args: Record<string, string | undefined>\n harnesses: readonly HarnessType[]\n /** Snapshot-stamped model ids (`name@snapshot`) — the eval identity models. */\n models: readonly string[]\n caseIds: readonly string[]\n shots: number\n reps: number\n}\n\n/** Structurally `BenchTask` (bench registry shape) — declared locally so this\n * module adds no dependency on a benchmark package. */\nexport interface LeaderboardBenchTask {\n id: string\n prompt: string\n split?: string\n metadata?: Record<string, unknown>\n}\n\n/** Structurally `BenchScore` (bench registry shape). */\nexport interface LeaderboardBenchScore {\n resolved: boolean\n score: number\n detail?: string\n}\n\n/** Structurally `BenchmarkAdapter` (bench registry shape): `name`,\n * `preflight()`, `loadTasks()`, deterministic `judge()`, `goldArtifact()`.\n * Generic over the artifact channel; the `string` default IS the registry\n * shape, so a default-artifact adapter registers unchanged. */\nexport interface LeaderboardBenchmarkAdapter<TArtifact = string> {\n readonly name: string\n preflight(): Promise<void>\n loadTasks(opts?: {\n limit?: number\n split?: string\n ids?: string[]\n }): Promise<LeaderboardBenchTask[]>\n judge(task: LeaderboardBenchTask, artifact: TArtifact): Promise<LeaderboardBenchScore>\n goldArtifact(task: LeaderboardBenchTask): Promise<string | undefined>\n}\n\n/** Per-shot outcome context passed as `onCellEvents`'s third argument — how a\n * thrown shot (which never reaches `parseOutput`) stays visible through the\n * facade instead of surfacing only as an empty zero-token cell. */\nexport interface LeaderboardIterationInfo {\n /** 0-based shot index within the cell. */\n index: number\n /** The shot's thrown error message, when the shot failed before scoring. */\n error?: string\n /** The shot's validator verdict, when the shot reached scoring. */\n verdict?: { score?: number }\n}\n\n/**\n * The declarative leaderboard spec. `TArtifact` is the artifact channel the\n * dispatch produces and the judges score — `string` (the default) is the plain\n * agent-response-text path; a structured artifact type flows natively once the\n * spec supplies `parseOutput` (or a LEVEL-2 `dispatch`) producing it.\n */\nexport interface LeaderboardSpec<TCase, TArtifact = string> {\n /** Leaderboard name — the scenario `kind`, default profile name, and report title. */\n name: string\n /** The case corpus. Every case needs a stable string id (see `caseId`). */\n cases: TCase[]\n /** Stable id extractor. Default: the case's own `id` property (fail-loud\n * when absent or not a string). */\n caseId?: (c: TCase) => string\n /** The per-case task prompt. May be async (e.g. built by shelling out to a\n * reference implementation); resolved ONCE per case before dispatch. */\n prompt: (c: TCase) => string | Promise<string>\n /** The domain grader: agent output artifact → score. Used BOTH as the\n * per-shot validator (a shot with `composite > 0` stops the naive retry\n * loop) and, wrapped as a campaign judge, as the recorded leaderboard score. */\n score: (output: TArtifact, c: TCase) => number | LeaderboardScore\n /** Harness × model axes for `expandProfileAxes`. Defaults: the canonical\n * `CODING_HARNESSES` × the base profile's `model.default`. `--harnesses` /\n * `--models` override per run. */\n axis?: { harnesses?: readonly HarnessType[]; models?: readonly string[] }\n /** Exact base profile the axes expand over (prompt/tools/skills held fixed).\n * Its provider remains authoritative while each axis cell replaces the\n * harness and concrete model. */\n baseProfile: AgentProfile\n /**\n * Execution-backend registry: `--backend <name>` picks the factory that\n * yields the `SandboxClient` every cell runs on. Merged over the defaults:\n * - `sandbox` — throws with guidance (a product must supply its real\n * Sandbox-backed client; the facade has no credentials).\n * - `cli-bridge` — `resolveSandboxClient({ backend: 'bridge' })` reading\n * `CLI_BRIDGE_URL` + `BRIDGE_BEARER`/`CLI_BRIDGE_BEARER`; the per-cell\n * harness/model ride in via `sandboxOverrides.backend`.\n */\n backends?: Record<string, (() => SandboxClient) | undefined>\n /** Extra `--flag value` CLI args `run()` parses and surfaces via `ctx.args`. */\n flags?: Record<string, LeaderboardFlagSpec>\n /** Runs once before the matrix (fetch fixtures, warm caches). */\n setup?: (ctx: LeaderboardRunContext) => Promise<void> | void\n /** Runs once after the matrix, even on failure (reap boxes, close handles). */\n teardown?: (ctx: LeaderboardRunContext) => Promise<void> | void\n /** Per-cell event tap: the raw sandbox events of EVERY shot, with the case —\n * the seam for domain metric capture (search counts, citations) without a\n * substrate change. Fires once per shot after the cell's loop settles, in\n * shot order, including thrown shots (whose events may be partial or empty);\n * the third argument carries the shot's index + error/verdict outcome. */\n onCellEvents?: (\n events: readonly SandboxEvent[],\n c: TCase,\n iteration?: LeaderboardIterationInfo,\n ) => void\n /** Output decode override: raw events → the scored artifact. Default: the\n * sandbox SDK's `collectAgentResponseText` (final answer text; empty string\n * when the stream carried none — which then scores 0). The default only\n * produces `string`, so a spec with a structured `TArtifact` MUST supply\n * this (or a LEVEL-2 `dispatch`). */\n parseOutput?: (events: readonly SandboxEvent[], c: TCase) => TArtifact\n /**\n * Resolve the model the backend actually served from a shot's raw events.\n * When this returns a value the default dispatch records it on the paid-call\n * receipt. It cannot complete an inexact planning profile: every expanded\n * cell must already declare a concrete model before backend work starts.\n */\n resolveModel?: (events: readonly SandboxEvent[]) => string | undefined\n /** Result export. Default: write `matrix-result.json` under the run dir and\n * print (+ write) the ranked leaderboard markdown under the export dir. */\n export?: (\n result: RunProfileMatrixResult<TArtifact, LeaderboardScenario<TCase>>,\n ctx: LeaderboardRunContext,\n ) => Promise<void> | void\n /** LEVEL 2 — full dispatch replacement (in-process products bring their own).\n * The default is `loopDispatch` + the naive retry driver over the resolved backend. */\n dispatch?: ProfileDispatchFn<LeaderboardScenario<TCase>, TArtifact>\n /** LEVEL 2 — full judge replacement. Default: `score` wrapped as one judge. */\n judges?: JudgeConfig<TArtifact, LeaderboardScenario<TCase>>[]\n /** Naive-retry shot cap per cell (`--shots`). Default 1. */\n shots?: number\n /** Replicates per cell (`--reps`). Default 1. */\n reps?: number\n /** Provider- or executor-enforced maximum for one cell dispatch. Required\n * before execution when `matrix.costCeiling` is configured. */\n maximumCharge?:\n | MaximumCharge\n | ((profile: AgentProfile, scenario: LeaderboardScenario<TCase>) => MaximumCharge | undefined)\n /** Passthrough overrides spread onto the final `runProfileMatrix` call\n * (e.g. `maxConcurrency`, `costCeiling`, `integrity`, `storage`) — spread\n * LAST, so anything the facade wired can be overridden. */\n matrix?: Partial<RunProfileMatrixOptions<LeaderboardScenario<TCase>, TArtifact>>\n}\n\nexport interface DefinedLeaderboard<TCase, TArtifact = string> {\n /**\n * Parse flags, run the matrix, export, and return the raw result.\n *\n * Standard flags: `--backend <name>` (default `sandbox`), `--harnesses a,b`,\n * `--models m1,m2`, `--cases id1,id2`, `--shots N`, `--reps N`,\n * `--model-snapshot <tag>`, `--run-dir <path>`, `--export-dir <path>`,\n * plus every `spec.flags` entry. `argv` defaults to `process.argv.slice(2)`.\n *\n * The default run dir is FRESH per invocation (timestamp+pid under the OS\n * tmpdir). `runProfileMatrix` caches cells by run dir, and a stable default\n * would silently reuse a prior FAILED zero-token cell and skip dispatch —\n * only an explicit `--run-dir` opts into that resume behavior.\n */\n run(argv?: string[]): Promise<RunProfileMatrixResult<TArtifact, LeaderboardScenario<TCase>>>\n /** The same domain surface in the structural `BenchmarkAdapter` shape. */\n toBenchmarkAdapter(): LeaderboardBenchmarkAdapter<TArtifact>\n}\n\n/** Read `--name <value>` from an argv array. */\nfunction argOf(argv: readonly string[], name: string): string | undefined {\n const i = argv.indexOf(`--${name}`)\n if (i >= 0 && i + 1 < argv.length) return argv[i + 1]\n return undefined\n}\n\nfunction splitList(v: string | undefined): string[] | undefined {\n if (v === undefined) return undefined\n const parts = v\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n return parts.length > 0 ? parts : undefined\n}\n\n/** RunRecords reject a bare model id — the eval IDENTITY model must carry a\n * snapshot (`name@<snapshot>`). Unchanged when already stamped. */\nfunction withSnapshot(model: string, snapshot: string): string {\n return model.includes('@') ? model : `${model}@${snapshot}`\n}\n\nfunction gitSha(): string {\n try {\n return execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim()\n } catch {\n return 'unknown'\n }\n}\n\nfunction normalizeScore(s: number | LeaderboardScore): LeaderboardScore {\n return typeof s === 'number' ? { composite: s } : s\n}\n\n/**\n * Assemble a declarative spec (`cases` + `prompt` + `score`) into a runnable\n * harness×model leaderboard — `run()` executes the matrix, `toBenchmarkAdapter()`\n * exposes the same domain as a structural `BenchmarkAdapter`.\n */\nexport function defineLeaderboard<TCase, TArtifact = string>(\n spec: LeaderboardSpec<TCase, TArtifact>,\n): DefinedLeaderboard<TCase, TArtifact> {\n const caseId = (c: TCase): string => {\n const id = spec.caseId ? spec.caseId(c) : (c as { id?: unknown }).id\n if (typeof id !== 'string' || id.length === 0) {\n throw new Error(\n `defineLeaderboard(${spec.name}): every case needs a stable string id — ` +\n 'give cases an `id` property or supply spec.caseId',\n )\n }\n return id\n }\n\n const selectCases = (ids?: readonly string[]): TCase[] => {\n if (!ids) return spec.cases\n const byId = new Map(spec.cases.map((c) => [caseId(c), c]))\n return ids.map((id) => {\n const c = byId.get(id)\n if (c === undefined) {\n throw new Error(\n `defineLeaderboard(${spec.name}): unknown case \"${id}\" (have: ${[...byId.keys()].join(', ')})`,\n )\n }\n return c\n })\n }\n\n const scoreJudge: JudgeConfig<TArtifact, LeaderboardScenario<TCase>> = {\n name: `${spec.name}-score`,\n dimensions: [{ key: 'composite', description: `${spec.name} case score` }],\n score({ artifact, scenario }) {\n const s = normalizeScore(spec.score(artifact, scenario.case))\n return {\n composite: s.composite,\n dimensions: { composite: s.composite, ...s.dimensions },\n notes: s.notes ?? '',\n }\n },\n }\n\n async function run(\n argv: string[] = process.argv.slice(2),\n ): Promise<RunProfileMatrixResult<TArtifact, LeaderboardScenario<TCase>>> {\n const args: Record<string, string | undefined> = {}\n for (const name of [\n 'backend',\n 'harnesses',\n 'models',\n 'cases',\n 'shots',\n 'reps',\n 'model-snapshot',\n 'run-dir',\n 'export-dir',\n ]) {\n args[name] = argOf(argv, name)\n }\n for (const [name, flag] of Object.entries(spec.flags ?? {})) {\n args[name] = argOf(argv, name) ?? flag.default\n }\n\n const backendName = args.backend ?? 'sandbox'\n const shots = Number(args.shots ?? spec.shots ?? 1)\n const reps = Number(args.reps ?? spec.reps ?? 1)\n const snapshot = args['model-snapshot'] ?? 'leaderboard'\n // FRESH run dir per invocation: runProfileMatrix caches cells by run dir,\n // and a stable default resumes a prior FAILED zero-token cell without\n // re-dispatching. Only an explicit --run-dir opts into resume.\n const runDir =\n args['run-dir'] ?? join(tmpdir(), `leaderboard-${spec.name}-${Date.now()}-${process.pid}`)\n const exportDir = args['export-dir'] ?? join(runDir, 'export')\n mkdirSync(runDir, { recursive: true })\n\n const cases = selectCases(splitList(args.cases))\n if (cases.length === 0) throw new Error(`defineLeaderboard(${spec.name}): no cases to run`)\n const scenarios: LeaderboardScenario<TCase>[] = cases.map((c) => ({\n id: caseId(c),\n kind: spec.name,\n case: c,\n }))\n\n const harnesses =\n (splitList(args.harnesses) as HarnessType[] | undefined) ??\n spec.axis?.harnesses ??\n CODING_HARNESSES\n const rawModels =\n splitList(args.models) ??\n spec.axis?.models ??\n (spec.baseProfile?.model?.default !== undefined\n ? [spec.baseProfile.model.default]\n : undefined)\n if (!rawModels || rawModels.length === 0) {\n throw new Error(\n `defineLeaderboard(${spec.name}): no models — pass --models, set spec.axis.models, ` +\n 'or give spec.baseProfile a model.default',\n )\n }\n const models = rawModels.map((m) => withSnapshot(m, snapshot))\n\n const profiles = expandProfileAxes({ base: spec.baseProfile, harnesses, models })\n for (const profile of profiles) {\n assertExecutableAgentProfile(profile, `defineLeaderboard(${spec.name})`)\n }\n\n const ctx: LeaderboardRunContext = {\n name: spec.name,\n backend: backendName,\n runDir,\n exportDir,\n args,\n harnesses,\n models,\n caseIds: scenarios.map((s) => s.id),\n shots,\n reps,\n }\n\n // Backend registry: defaults + spec overrides (spec wins). Factories are\n // lazy so an unused backend never resolves credentials.\n const backends: Record<string, (() => SandboxClient) | undefined> = {\n sandbox: () => {\n throw new Error(\n `defineLeaderboard(${spec.name}): the 'sandbox' backend needs your product's real ` +\n 'Sandbox client — supply spec.backends.sandbox (e.g. () => new Sandbox({ apiKey, baseUrl }))',\n )\n },\n 'cli-bridge': () => {\n const bearer = process.env.BRIDGE_BEARER ?? process.env.CLI_BRIDGE_BEARER\n if (!bearer) {\n throw new Error(\n `defineLeaderboard(${spec.name}): backend 'cli-bridge' needs BRIDGE_BEARER or CLI_BRIDGE_BEARER set`,\n )\n }\n return resolveSandboxClient({\n backend: 'bridge',\n bridge: {\n url: process.env.CLI_BRIDGE_URL,\n bearer,\n timeoutMs: 900_000,\n },\n })\n },\n ...spec.backends,\n }\n const makeClient = backends[backendName]\n if (!makeClient) {\n throw new Error(\n `defineLeaderboard(${spec.name}): unknown backend \"${backendName}\" (have: ${Object.keys(backends).join(', ')})`,\n )\n }\n const sandboxClient = makeClient()\n\n // Prompts resolve ONCE per case, up front — spec.prompt may be async\n // (shelling out to a reference implementation) but the loop kernel's\n // taskToPrompt is sync.\n const promptById = new Map<string, string>()\n for (const s of scenarios) promptById.set(s.id, await spec.prompt(s.case))\n const promptOf = (s: LeaderboardScenario<TCase>): string => {\n const p = promptById.get(s.id)\n if (p === undefined)\n throw new Error(`defineLeaderboard(${spec.name}): no prompt for case \"${s.id}\"`)\n return p\n }\n\n // Monotonic per-shot nonce appended to each shot's prompt — defeats router\n // response-caching of byte-identical prompts across naive-retry shots.\n let shotNonce = 0\n\n // The default dispatch wraps loopDispatch per cell (closures only — no\n // per-cell resource cost) so the loop's finished iterations can be joined\n // with the campaign ctx: onCellEvents gets EVERY shot's outcome (a thrown\n // shot never reaches parse, so parse-time tapping would hide it), and a\n // the cost receipt records the spec-resolved served model.\n const maximumCharge = spec.maximumCharge\n const dispatch: ProfileDispatchFn<LeaderboardScenario<TCase>, TArtifact> = spec.dispatch ??\n ((profile, scenario, dispatchCtx) => {\n const cellDispatch = loopDispatch<\n LeaderboardScenario<TCase>,\n TArtifact,\n NaiveRetryDecision,\n LeaderboardScenario<TCase>,\n TArtifact\n >({\n sandboxClient,\n maximumCharge:\n typeof maximumCharge === 'function'\n ? (cellScenario, cellProfile) => maximumCharge(cellProfile, cellScenario)\n : maximumCharge,\n resolveCostModel: (result, _cellScenario, cellProfile) => {\n if (!spec.resolveModel) return cellProfile.model?.default\n const served = new Set(\n result.iterations\n .map((iteration) => spec.resolveModel?.(iteration.events))\n .filter((model): model is string => model !== undefined),\n )\n if (served.size > 1) {\n throw new Error(\n `defineLeaderboard(${spec.name}): one cell reported multiple served models: ${[...served].join(', ')}`,\n )\n }\n return [...served][0] ?? cellProfile.model?.default\n },\n toLoopOptions: (cellScenario, cellProfile) => {\n return {\n // The no-signal retry floor: re-run the same case as an independent attempt until\n // one scores (>0) or the shot cap. The task is re-run verbatim — no grader findings\n // cross into the next shot.\n driver: naiveRetryDriver<TCase, TArtifact>(shots),\n agentRun: {\n profile: cellProfile,\n taskToPrompt: (s) => `${promptOf(s)}\\n\\n<!-- independent-attempt:${shotNonce++} -->`,\n },\n output: {\n parse: (events) =>\n spec.parseOutput\n ? spec.parseOutput(events, cellScenario.case)\n : // The default decode produces string — the TArtifact\n // default. A structured-TArtifact spec supplies parseOutput\n // (documented on the field), so this cast never lies.\n ((collectAgentResponseText(events) ?? '') as TArtifact),\n },\n validator: {\n validate: async (output: TArtifact) => {\n const s = normalizeScore(spec.score(output, cellScenario.case))\n return { valid: s.composite > 0, score: s.composite }\n },\n },\n task: cellScenario,\n maxIterations: shots,\n }\n },\n toArtifact: (result: LoopResult<LeaderboardScenario<TCase>, TArtifact, unknown>) => {\n for (const iter of result.iterations) {\n spec.onCellEvents?.(iter.events, scenario.case, {\n index: iter.index,\n ...(iter.error ? { error: iter.error.message } : {}),\n ...(iter.verdict ? { verdict: { score: iter.verdict.score } } : {}),\n })\n }\n // Same as loopDispatch's default: no winner → undefined artifact\n // (judges skip the cell; usage is still reported).\n return result.winner?.output as TArtifact\n },\n })\n return cellDispatch(profile, scenario, dispatchCtx)\n })\n\n await spec.setup?.(ctx)\n try {\n const result = await runProfileMatrix<LeaderboardScenario<TCase>, TArtifact>({\n profiles,\n scenarios,\n dispatch,\n judges: spec.judges ?? [scoreJudge],\n runDir,\n commitSha: gitSha(),\n reps,\n ...spec.matrix,\n })\n\n if (spec.export) {\n await spec.export(result, ctx)\n } else {\n mkdirSync(exportDir, { recursive: true })\n writeFileSync(join(runDir, 'matrix-result.json'), `${JSON.stringify(result, null, 2)}\\n`)\n const table = renderLeaderboardMarkdown(\n leaderboard(result.records, { title: spec.name, meta: { backend: backendName } }),\n )\n writeFileSync(join(exportDir, 'leaderboard.md'), table)\n console.log(table)\n }\n return result\n } finally {\n await spec.teardown?.(ctx)\n }\n }\n\n function toBenchmarkAdapter(): LeaderboardBenchmarkAdapter<TArtifact> {\n return {\n name: spec.name,\n async preflight(): Promise<void> {\n // Case-id integrity is the cheap, real check: duplicate or missing ids\n // corrupt every downstream join.\n const seen = new Set<string>()\n for (const c of spec.cases) {\n const id = caseId(c)\n if (seen.has(id)) {\n throw new Error(`defineLeaderboard(${spec.name}): duplicate case id \"${id}\"`)\n }\n seen.add(id)\n }\n },\n async loadTasks(opts): Promise<LeaderboardBenchTask[]> {\n const selected = selectCases(opts?.ids)\n const limited = opts?.limit !== undefined ? selected.slice(0, opts.limit) : selected\n return Promise.all(\n limited.map(async (c) => ({\n id: caseId(c),\n prompt: await spec.prompt(c),\n metadata: { case: c },\n })),\n )\n },\n async judge(task, artifact): Promise<LeaderboardBenchScore> {\n const [c] = selectCases([task.id])\n if (c === undefined)\n throw new Error(`defineLeaderboard(${spec.name}): no case \"${task.id}\"`)\n const s = normalizeScore(spec.score(artifact, c))\n return { resolved: s.composite > 0, score: s.composite, detail: s.notes }\n },\n async goldArtifact(): Promise<string | undefined> {\n return undefined\n },\n }\n }\n\n return { run, toBenchmarkAdapter }\n}\n","/**\n * Analyze completed runs through the selected observer and retain findings in a corpus.\n *\n * Store-agnostic by design: the caller maps its trace store's rows (a\n * `ProductionTraceSink` ndjson, OTLP spans, RunRecords) to `ObserveInput` — task text,\n * final output, the event trace, terminal outcome.\n * The default observer reads execution evidence; an injected analysis owns its admitted sources.\n *\n * The nightly product job is then three lines:\n * const runs = mapSinkRowsToObserveInputs(await readSink(yesterday))\n * const report = await harvestCorpus({ runs, profile, executor, corpus })\n * log(report) // runsObserved / findings / learned / failures\n *\n * Consumers choose how retained findings inform later work and how to assess their value.\n */\n\nimport {\n type Observation,\n ObservationError,\n type ObserveInput,\n type ObserveOptions,\n observe,\n} from './observe'\nimport type { Corpus } from './personify/wave-types'\n\nexport type HarvestCorpusOptions = ObserveOptions & {\n /** The completed runs to analyze — map your store's rows to `ObserveInput`. */\n runs: AsyncIterable<ObserveInput> | Iterable<ObserveInput>\n /** The durable corpus the facts accrete into. */\n corpus: Corpus\n /** Tags written onto learned facts (the product/domain key the read side queries by). */\n tags?: ReadonlyArray<string>\n /** Runs analyzed in parallel. Default 4. */\n concurrency?: number\n /** Hard cap on runs consumed from the stream (a cost guard for unbounded stores). */\n maxRuns?: number\n signal?: AbortSignal\n}\n\nexport interface HarvestFailure {\n runId: string\n error: string\n}\n\nexport interface HarvestReport {\n runsObserved: number\n /** Total findings the analyst produced (including ones already known). */\n findings: number\n /** NEW facts actually appended (idempotent dedup excludes re-learned ones). */\n learned: number\n /** Per-run analysis failures — reported, never silently dropped. */\n failures: HarvestFailure[]\n /** Measured analyst tokens; a failed or unmetered analysis leaves the subtotal incomplete. */\n usage: Observation['usage']\n}\n\n/** The completed batch evidence remains available even when every analysis failed. */\nexport class HarvestError extends Error {\n constructor(readonly report: HarvestReport) {\n super(\n `harvestCorpus: every run failed analysis (${report.failures.length}) — first: ${report.failures[0]?.error}`,\n )\n this.name = 'HarvestError'\n }\n}\n\n/** Batch the selected observation implementation over completed runs and retain its findings. */\nexport async function harvestCorpus(opts: HarvestCorpusOptions): Promise<HarvestReport> {\n const concurrency = opts.concurrency ?? 4\n if (\n !Number.isSafeInteger(concurrency) ||\n concurrency < 1 ||\n (opts.maxRuns !== undefined && (!Number.isSafeInteger(opts.maxRuns) || opts.maxRuns < 0))\n ) {\n throw new TypeError(\n 'harvest limits require positive integer concurrency and nonnegative integer maxRuns',\n )\n }\n const report: HarvestReport = {\n runsObserved: 0,\n findings: 0,\n learned: 0,\n failures: [],\n usage: { input: 0, output: 0, known: true },\n }\n\n // Normalize to an async iterator and pull cooperatively from N workers.\n const iterator = (\n Symbol.asyncIterator in Object(opts.runs)\n ? (opts.runs as AsyncIterable<ObserveInput>)[Symbol.asyncIterator]()\n : (async function* () {\n yield* opts.runs as Iterable<ObserveInput>\n })()\n ) as AsyncIterator<ObserveInput>\n\n let consumed = 0\n let done = false\n const next = async (): Promise<{ input: ObserveInput; sequence: number } | null> => {\n if (done || opts.signal?.aborted || (opts.maxRuns !== undefined && consumed >= opts.maxRuns))\n return null\n // Reserve before awaiting so concurrent workers cannot exceed the requested cap.\n const sequence = ++consumed\n let r: IteratorResult<ObserveInput>\n try {\n r = await iterator.next()\n } catch (error) {\n done = true\n report.failures.push({\n runId: `source-${sequence}`,\n error: `trace source: ${error instanceof Error ? error.message.slice(0, 300) : String(error)}`,\n })\n return null\n }\n if (r.done) {\n done = true\n return null\n }\n return { input: r.value, sequence }\n }\n\n const workers = Array.from({ length: concurrency }, async () => {\n for (let run = await next(); run !== null; run = await next()) {\n const { input, sequence } = run\n if (opts.signal?.aborted) return\n try {\n const obs: Observation = await observe(input, opts)\n report.runsObserved += 1\n report.findings += obs.findings.length\n report.learned += obs.learned.length\n report.usage.input += obs.usage.input\n report.usage.output += obs.usage.output\n report.usage.known &&= obs.usage.known\n } catch (e) {\n report.usage.known &&= e instanceof ObservationError && e.usage.known\n if (e instanceof ObservationError) {\n report.usage.input += e.usage.input\n report.usage.output += e.usage.output\n }\n report.failures.push({\n runId: input.runId ?? `run-${sequence}`,\n error: e instanceof Error ? e.message.slice(0, 300) : String(e),\n })\n }\n }\n })\n await Promise.all(workers)\n\n // Fail loud when the whole batch failed — that's an infra problem, not a quiet no-op.\n if (report.runsObserved === 0 && report.failures.length > 0) {\n throw new HarvestError(report)\n }\n return report\n}\n","/**\n * The ONE in-process pseudo-box: present a plain user callback as a\n * `SandboxClient` so an example or test can drive `runAgentRounds` / `openSandboxRun`\n * with zero credentials and zero network — without re-faking a box at each call\n * site via `as unknown as SandboxInstance`.\n *\n * It is the structural sibling of {@link inlineSandboxClient}: that one adapts an\n * `Executor` (router / bridge / BYO) into a box; this one adapts a single\n * `onPrompt(prompt, round)` callback into a box. Both exist because\n * `SandboxInstance` is a `declare class` with private fields — a plain object\n * literal can NEVER structurally satisfy it, so every offline seam was forced to\n * write `as unknown as SandboxInstance`. The one unavoidable cast now lives HERE,\n * documented and tested, instead of in every example.\n *\n * What the box implements is exactly the subset `runAgentRounds` + `openSandboxRun`\n * actually call on a box:\n * - `id` — stable per box, used for trace correlation.\n * - `streamPrompt(prompt, opts?)` — runs `onPrompt` and streams its events.\n * - `fs.read` / `fs.write` — over the optional real `workdir` (the deliverable\n * artifact + any seeded fixtures live there). Present only when a `workdir`\n * is given.\n * - `exec(command)` — runs the command in `workdir`. Present only when a\n * `workdir` is given.\n * - `delete()` — removes the per-box temp dir (when one was minted) and is a\n * no-op otherwise; `deleteBoxSafe` calls it at teardown.\n *\n * The `SandboxEvent` shape the callback returns — `{ type, data }` — is the\n * runtime metering protocol the kernel reads: emit a flat `llm_call`\n * (`{ tokensIn, tokensOut, costUsd }`) or a terminal `done`\n * (`{ tokenUsage, totalCostUsd }`) / `result` event and the kernel's cost ledger\n * picks it up. No cast is needed on the events (the union is structural); only\n * the box object is cast, once, inside this file.\n */\nimport { mkdtempSync, rmSync } from 'node:fs'\nimport { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport type { CreateSandboxOptions, SandboxEvent, SandboxInstance } from '@tangle-network/sandbox'\nimport { assertBoxlessPromptOptions } from './prompt-options'\nimport type { SandboxClient } from './types'\n\n/** Context handed to each `onPrompt` call. */\nexport interface InProcessPromptCtx {\n /** 0-based round index — increments per `streamPrompt` on the same box.\n * Fresh boxes start at 0. */\n round: number\n /** Absolute path of this box's workspace, when a `workdir` was configured.\n * Write the deliverable / fixtures here; `fs.read`/`fs.write`/`exec` operate\n * over it. `undefined` for pure event-only boxes. */\n workdir?: string\n /** Cooperative cancellation channel for this turn. */\n signal: AbortSignal\n /** The verbatim per-call options the caller passed to the box verb (minus\n * `signal`, surfaced above) — lets an offline test assert an options\n * passthrough (`model`, `sessionId`, …) actually arrived. */\n options?: Record<string, unknown>\n}\n\n/**\n * The user callback: given a prompt and its round, produce the box's event\n * stream for that turn. Return a plain `SandboxEvent[]` (the common case) or an\n * async iterable for streaming. The callback may also write files into\n * `ctx.workdir` (read back via `fs.read` or graded by `exec`).\n */\nexport type InProcessOnPrompt = (\n prompt: string,\n ctx: InProcessPromptCtx,\n) => SandboxEvent[] | AsyncIterable<SandboxEvent> | Promise<SandboxEvent[]>\n\n/** @experimental */\nexport interface InProcessSandboxClientOptions {\n /** The per-turn behavior — see {@link InProcessOnPrompt}. */\n onPrompt: InProcessOnPrompt\n /**\n * Opt in to a REAL filesystem-backed box. When set, each `create()` mints a\n * fresh temp directory (prefixed `<workdir>-`) and the box exposes\n * `fs.read`/`fs.write` and `exec` over it; `delete()` removes the dir. Omit\n * for a pure event-only box (no `fs`/`exec` members), which is all a driver\n * or fanout loop needs.\n */\n workdir?: string\n /**\n * Override the box `id`. A string is used verbatim; a function receives the\n * 0-based create-sequence and returns the id (e.g. machine-keyed placement\n * demos). Default `in-process-<seq>`. The id is the value `describePlacement`\n * tags, so set it when a demo's output reads on a meaningful sandbox id.\n */\n id?: string | ((seq: number) => string)\n}\n\nfunction isAsyncIterable(v: unknown): v is AsyncIterable<SandboxEvent> {\n return typeof v === 'object' && v !== null && Symbol.asyncIterator in v\n}\n\n/**\n * Adapt a single `onPrompt(prompt, ctx)` callback into a `SandboxClient` for\n * `runAgentRounds` / `openSandboxRun`. Returns a PROPERLY-TYPED `SandboxClient`: the\n * lone `SandboxInstance` cast (object literal → `declare class`) lives inside\n * this function, so call sites stay cast-free.\n *\n * There is no box, so a per-prompt `backend` override is refused rather than dropped. A per-turn\n * `model` IS delivered, because `onPrompt` receives the verbatim options and is free to honor it.\n * Other per-prompt options (`timeoutMs`, `context`) are accepted and ignored.\n *\n * @experimental\n */\nexport function inProcessSandboxClient(options: InProcessSandboxClientOptions): SandboxClient {\n const { onPrompt, workdir: workdirPrefix, id: idOption } = options\n let seq = 0\n return {\n async create(_options?: CreateSandboxOptions): Promise<SandboxInstance> {\n const current = seq++\n const id =\n typeof idOption === 'function' ? idOption(current) : (idOption ?? `in-process-${current}`)\n const boxWorkdir =\n workdirPrefix !== undefined ? mkdtempSync(join(tmpdir(), `${workdirPrefix}-`)) : undefined\n let round = 0\n\n const fsMembers =\n boxWorkdir !== undefined\n ? {\n fs: {\n async read(path: string): Promise<string> {\n return readFile(join(boxWorkdir, path), 'utf8')\n },\n async write(path: string, content: string): Promise<void> {\n const abs = join(boxWorkdir, path)\n await mkdir(dirname(abs), { recursive: true })\n await writeFile(abs, content, 'utf8')\n },\n },\n async exec(\n command: string,\n ): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n const { exec: execCb } = await import('node:child_process')\n const { promisify } = await import('node:util')\n const execAsync = promisify(execCb)\n try {\n const { stdout, stderr } = await execAsync(command, {\n cwd: boxWorkdir,\n timeout: 30_000,\n })\n return { exitCode: 0, stdout, stderr }\n } catch (err) {\n const e = err as {\n code?: number\n stdout?: string\n stderr?: string\n message?: string\n }\n return {\n exitCode: e.code ?? 1,\n stdout: e.stdout ?? '',\n stderr: e.stderr ?? e.message ?? '',\n }\n }\n },\n }\n : {}\n\n async function* drive(\n behavior: InProcessOnPrompt,\n message: string | unknown[],\n opts?: { signal?: AbortSignal } & Record<string, unknown>,\n ): AsyncGenerator<SandboxEvent> {\n const prompt = typeof message === 'string' ? message : JSON.stringify(message)\n const { signal: optSignal, ...rest } = opts ?? {}\n const signal = optSignal ?? new AbortController().signal\n const ctx: InProcessPromptCtx = {\n round,\n workdir: boxWorkdir,\n signal,\n ...(Object.keys(rest).length > 0 ? { options: rest } : {}),\n }\n round += 1\n const produced = await behavior(prompt, ctx)\n if (isAsyncIterable(produced)) {\n for await (const ev of produced) yield ev\n } else {\n for (const ev of produced) yield ev\n }\n }\n\n const box = {\n id,\n streamPrompt(\n message: string | unknown[],\n opts?: { signal?: AbortSignal } & Record<string, unknown>,\n ): AsyncGenerator<SandboxEvent> {\n // `model` is deliberately NOT refused here: this seam surfaces the verbatim per-call\n // options to `onPrompt` (see InProcessPromptContext.options), so the caller's own\n // callback is the executor that may honor a per-turn model.\n assertBoxlessPromptOptions(opts, 'inProcessSandboxClient', ['backend'])\n return drive(onPrompt, message, opts)\n },\n ...fsMembers,\n async delete(): Promise<void> {\n if (boxWorkdir !== undefined) rmSync(boxWorkdir, { recursive: true, force: true })\n },\n }\n // The ONE unavoidable cast: `SandboxInstance` is a `declare class` with\n // private fields, so an object implementing only the called subset cannot\n // structurally satisfy it. Contained here so call sites never cast.\n return box as unknown as SandboxInstance\n },\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport type { ProposalFinding } from '@tangle-network/agent-eval'\nimport type {\n AnalystRegistry,\n AnalystRunInputs,\n AnalystRunResult,\n RegistryRunOpts,\n} from '@tangle-network/agent-eval/analyst'\nimport {\n type ObservationAnalysis,\n ObservationError,\n type ObserveInput,\n renderReport,\n} from './observe'\n\n/** Adapt any Eval analyst registry, including recursive engines, to observation and harvesting. */\nexport function observationFromRegistry(\n registry: Pick<AnalystRegistry, 'run'>,\n options: {\n inputs:\n | AnalystRunInputs\n | ((input: ObserveInput) => AnalystRunInputs | Promise<AnalystRunInputs>)\n /** The caller identifies the evidence admitted for this investigation. */\n proposalOrigin: ProposalFinding['proposal_origin']\n runOptions?: RegistryRunOpts\n /** Retain the complete registry result, including unsuccessful analysts, in caller-owned storage. */\n record?: (result: AnalystRunResult, input: ObserveInput) => void | Promise<void>\n },\n): ObservationAnalysis {\n if (!['production', 'search'].includes(options.proposalOrigin)) {\n throw new TypeError('registry observation requires an explicit production or search origin')\n }\n return async (input, context) => {\n const signals = [context.signal, options.runOptions?.signal].filter(\n (signal): signal is AbortSignal => signal !== undefined,\n )\n const result = await registry.run(\n input.runId ?? randomUUID(),\n typeof options.inputs === 'function' ? await options.inputs(input) : options.inputs,\n { ...options.runOptions, ...(signals.length ? { signal: AbortSignal.any(signals) } : {}) },\n )\n const usage = { input: 0, output: 0, known: true }\n for (const analyst of result.per_analyst) {\n const receipt = analyst.usage\n usage.input += receipt.tokens?.input ?? receipt.partialTokens?.input ?? 0\n usage.output += receipt.tokens?.output ?? receipt.partialTokens?.output ?? 0\n usage.known &&=\n receipt.tokens !== null &&\n receipt.tokens.tokensKnown !== false &&\n receipt.tokensEstimated !== true\n }\n try {\n await options.record?.(result, input)\n const incomplete = result.per_analyst.filter((analyst) => analyst.status !== 'ok')\n if (incomplete.length) {\n throw new Error(\n incomplete\n .map(\n (analyst) =>\n `${analyst.analyst_id}: ${analyst.error?.message ?? analyst.reason ?? analyst.status}`,\n )\n .join('; '),\n )\n }\n const findings = result.findings.map(\n (finding): ProposalFinding => ({\n ...finding,\n proposal_origin: options.proposalOrigin,\n }),\n )\n return { findings, report: renderReport(findings), usage }\n } catch (cause) {\n throw new ObservationError(cause instanceof Error ? cause.message : String(cause), usage, {\n cause,\n })\n }\n }\n}\n","/**\n *\n * Analyst-on-scope (G1) — the analyze→findings→steer wire over the reactive `Scope`.\n *\n * The analyst runs over the children drained so far and hands its findings to the steer\n * decision behind a provenance firewall (`assertTraceDerivedFindings`) that keeps the external\n * write-only judge out of that decision (selector ≠ judge). The reactive `Scope` has no rounds:\n * a combinator's `act` asks a `ScopeAnalyst` to turn the children it has drained off\n * `scope.next()` SO FAR into `AnalystFinding[]`, and steers from THOSE findings through a single\n * `SteerContext`.\n *\n * The analyst itself is not a new type — it is \"just an `Agent<unknown, AnalystFinding[]>`\" the\n * combinator spawns over a child's trace (harness `null`/`cli`). `createScopeAnalyst` spawns that\n * agent through `Scope.spawn` (so its compute is metered by the conserved pool like any child),\n * drains its settlement, then enforces the firewall on the way out — a judge-derived finding\n * ABORTS, it is never filtered. Fail loud: a down analyst, a non-array result, or a tainted finding\n * throws; there is no silent empty-findings path that would let a combinator steer on nothing.\n *\n * @experimental\n */\n\nimport type { AnalystFinding, AnalystRunInputs } from '@tangle-network/agent-eval'\nimport type { AnalystRegistryLike } from '../../analyst-loop/types'\nimport { AnalystError, PlannerError } from '../../errors'\nimport type { Agent, Budget, DefaultVerdict, NodeId, Scope, Settled } from '../supervise/types'\nimport { stringifySafe } from '../util'\nimport type {\n AssertTraceDerivedFindings,\n Outcome,\n ScopeAnalyst,\n ScopeAnalyzeInput,\n SteerContext,\n} from './wave-types'\n\n// ── The steer firewall (selector ≠ judge) — the single canonical impl ───────\n\n/**\n * The diagnosis a combinator steers from must be TRACE-derived, never JUDGE-derived. A finding\n * whose evidence is a judge/verdict score (an `EvidenceRef` of `kind:'metric'` with a\n * verdict/judge/score uri scheme) would smuggle the external write-only judge back into steering —\n * the one coupling the architecture forbids. This is a PROVENANCE check, not a content check:\n * span/event/artifact/finding refs and empty-evidence findings are allowed; only a judge-scheme\n * metric ref is rejected. Fail loud — a tainted finding aborts.\n */\nconst judgeEvidenceUri = /^(verdict|judge|score)\\b/i\n\n/** Reject analyst findings derived from evaluation scores instead of execution traces. */\nexport const assertTraceDerivedFindings: AssertTraceDerivedFindings = (findings) => {\n for (const f of findings) {\n for (const ref of f.evidence_refs ?? []) {\n if (ref.kind === 'metric' && judgeEvidenceUri.test(ref.uri)) {\n throw new PlannerError(\n `steer-firewall: finding ${stringifySafe(f.finding_id)} cites judge-derived evidence ` +\n `(${stringifySafe(ref.uri)}); findings fed to a combinator's steer decision must be ` +\n 'trace-derived, not judge-derived (selector ≠ judge)',\n )\n }\n }\n }\n}\n\n// ── The reactive analyst — an Agent the combinator spawns over the trace so far ───────\n\n/**\n * The analyst run an `Agent<unknown, AnalystFinding[]>` performs over the children settled so far.\n * The combinator supplies the analyst's task projection (how to frame the drained settlements as\n * the analyst's input) — the analyst's `act` reads the trace and returns its raw findings; the\n * firewall is enforced afterwards by `createScopeAnalyst`, not by the analyst itself.\n */\nexport interface CreateScopeAnalystOptions<D> {\n /** The analyst agent the combinator spawns over the trace. `harness` is the persona's choice\n * (`null` for an inline router analyst, a `BackendType` for a sandboxed one). Its `act` returns\n * the RAW findings; this module asserts the firewall on them before returning. */\n readonly analyst: Agent<unknown, ReadonlyArray<AnalystFinding>>\n /** Build the analyst agent's task from the analyze input (the root-task framing + the children\n * drained so far). Pure projection — the analyst interprets it, this never reads it. */\n buildTask(input: ScopeAnalyzeInput<D>): unknown\n /** The conserved budget reserved for one analyst spawn. The pool reserves against it and fails\n * closed; an analyst that cannot be admitted is a fail-loud abort, never silent empty findings. */\n readonly budget: Budget\n /** Trace/journal label for the spawned analyst child. Default `'analyst'`. */\n readonly label?: string\n}\n\n/**\n * Build a `ScopeAnalyst` that spawns the analyst agent through `Scope.spawn` (so its compute is\n * metered by the conserved pool), drains its single settlement, and enforces the trace-derived\n * firewall before returning. The `scope` is the SAME scope the combinator is draining its children\n * from — the analyst is spawned as a sibling and its result is read off `scope.next()` in cursor\n * order, replay-safe like any other child.\n *\n * Fail loud (no silent empty findings):\n * - the pool refuses the analyst spawn → `AnalystError` (the steer would otherwise run on nothing)\n * - the analyst settles `down` → `AnalystError` (a broken capture path, not a verdict)\n * - the analyst returns a non-array → `PlannerError`\n * - any finding cites judge-derived metric evidence → `PlannerError` via the firewall\n */\nexport function createScopeAnalyst<D>(\n scope: Scope<Outcome<D>>,\n options: CreateScopeAnalystOptions<D>,\n): ScopeAnalyst<D> {\n if (!options.analyst || typeof options.analyst.act !== 'function') {\n throw new AnalystError('createScopeAnalyst: analyst must be an Agent with an act() method')\n }\n const label = options.label ?? 'analyst'\n return {\n async analyze(input: ScopeAnalyzeInput<D>): Promise<ReadonlyArray<AnalystFinding>> {\n const task = options.buildTask(input)\n // The analyst is spawned into the combinator's own scope so its tokens are charged to the\n // conserved pool. The pool fails closed; an analyst it cannot admit is a hard abort, not an\n // excuse to steer on an empty diagnosis. The analyst's `Out` is `AnalystFinding[]`, not the\n // scope's `Outcome<D>` — a genuinely heterogeneous child; the cast through `unknown` mirrors\n // the keystone `spawnChild` seam, and the settlement is narrowed back by `readAnalystFindings`.\n const spawned = scope.spawn(options.analyst as unknown as Agent<unknown, Outcome<D>>, task, {\n budget: options.budget,\n label,\n })\n if (!spawned.ok) {\n throw new AnalystError(\n `createScopeAnalyst: analyst spawn refused by the conserved pool (${spawned.reason}); ` +\n `cannot steer node ${stringifySafe(input.nodeId)} on an unrun analyst`,\n )\n }\n const settled = await drainAnalystSettlement(scope, spawned.handle.id)\n const findings = readAnalystFindings(settled)\n assertTraceDerivedFindings(findings)\n return findings\n },\n }\n}\n\n/**\n * Drain `scope.next()` until the analyst child's own settlement is yielded, matching on its node\n * id so an unrelated sibling that settles first is skipped, not mistaken for the analyst. A\n * `ScopeAnalyst` is invoked AFTER a combinator has drained its workers, so in practice the analyst\n * is the only live child; the id match keeps it correct even when it is not. Fails loud if the\n * scope empties before the analyst settles (the steer would otherwise run on nothing).\n */\nasync function drainAnalystSettlement<D>(\n scope: Scope<Outcome<D>>,\n analystId: NodeId,\n): Promise<Settled<Outcome<D>>> {\n for (;;) {\n const settled = await scope.next()\n if (settled === null) {\n throw new AnalystError(\n `createScopeAnalyst: scope drained before analyst ${stringifySafe(analystId)} settled`,\n )\n }\n if (settled.handle.id === analystId) return settled\n }\n}\n\n/**\n * Read the analyst child's settlement into its `AnalystFinding[]`. A `down` analyst is a broken\n * capture path (fail loud — not \"no findings\"); a `done` analyst whose `out` is not an array is a\n * malformed analyst (fail loud — the dynamic driver's `runAnalyze` contract, carried across).\n */\nfunction readAnalystFindings<D>(settled: Settled<Outcome<D>>): ReadonlyArray<AnalystFinding> {\n if (settled.kind === 'down') {\n throw new AnalystError(\n `createScopeAnalyst: analyst ${stringifySafe(settled.handle.id)} settled down ` +\n `(${settled.infra ? 'infra' : 'result'}): ${stringifySafe(settled.reason)}`,\n )\n }\n const out = settled.out as unknown\n if (!Array.isArray(out)) {\n throw new PlannerError(\n `createScopeAnalyst: analyst ${stringifySafe(settled.handle.id)} must return ` +\n `AnalystFinding[], got ${stringifySafe(out)}`,\n )\n }\n return out as ReadonlyArray<AnalystFinding>\n}\n\n// ── The panel-of-analysts adapter — N analyst KINDS merged into one ScopeAnalyst ───────\n\n/**\n * Project a `ScopeAnalyzeInput` into the `AnalystRegistry.run` arguments. The registry runs over a\n * `runId` + `AnalystRunInputs` (a trace store / run record / artifact dir), NOT in-memory scope\n * settlements — so the CALLER owns the projection from the combinator's drained children to the\n * registry's inputs (e.g. the trace store the run already wrote). This adapter never invents that\n * bridge; it only runs the projected inputs and firewalls the merged findings.\n */\nexport interface RegistryAnalyzeProjection {\n readonly runId: string\n readonly inputs: AnalystRunInputs\n /** Optional `run` opts (e.g. `priorFindings`, `chainFindings`) forwarded verbatim to the registry. */\n readonly opts?: Parameters<AnalystRegistryLike['run']>[2]\n}\n\n/**\n * A `ScopeAnalyst` backed by an `AnalystRegistry` — the panel-of-analysts seam. The registry merges\n * N analyst KINDS into one `AnalystRunResult.findings`; `analyze` runs it over the caller-projected\n * `{ runId, inputs }` and pipes the merged findings through the SAME `assertTraceDerivedFindings`\n * firewall `createScopeAnalyst` uses (single-sourced selector≠judge). Distinct from `panel()`\n * (judges-vs-one-artifact) — this is analysts-over-a-trace, the diagnosis side of the wire.\n *\n * Fail loud: a registry that throws propagates; a judge-derived finding aborts via the firewall.\n * The projection is the caller's (`buildInputs`) — if the scope settlements do not cleanly map to\n * the registry's `AnalystRunInputs`, that is a caller-side contract gap, surfaced there, not papered\n * over with a fabricated input here.\n */\nexport function registryScopeAnalyst<D>(\n registry: AnalystRegistryLike,\n buildInputs: (input: ScopeAnalyzeInput<D>) => RegistryAnalyzeProjection,\n): ScopeAnalyst<D> {\n return {\n async analyze(input: ScopeAnalyzeInput<D>): Promise<ReadonlyArray<AnalystFinding>> {\n const projection = buildInputs(input)\n const result = await registry.run(projection.runId, projection.inputs, projection.opts)\n const findings = result.findings\n assertTraceDerivedFindings(findings)\n return findings\n },\n }\n}\n\n// ── The single firewalled steer surface every combinator funnels through ──────────────\n\n/**\n * Build the `SteerContext` a combinator reads to steer (its `loopUntil.until`, `widen` gate, any\n * future steer). One place enforces the firewall: `findings` is asserted trace-derived before it is\n * surfaced, and `lastValidScore` is provided for OBSERVABILITY only — a combinator that steers off\n * it re-introduces selector = judge, the coupling the architecture forbids.\n *\n * `findings` is re-asserted here even when it came from `createScopeAnalyst` (which already asserted\n * it): the assertion is cheap and idempotent, and a `SteerContext` may be built from findings that\n * arrived by another path (a caller-supplied diagnosis). Belt-and-suspenders on the one coupling\n * that must never leak.\n */\nexport function buildSteerContext<D>(\n findings: ReadonlyArray<AnalystFinding>,\n settledSoFar: ReadonlyArray<Settled<Outcome<D>>>,\n): SteerContext<D> {\n assertTraceDerivedFindings(findings)\n const lastValidScore = observedBestScore(settledSoFar)\n return {\n findings,\n settledSoFar,\n ...(lastValidScore !== undefined ? { lastValidScore } : {}),\n }\n}\n\n/**\n * The best valid score among the drained children — OBSERVABILITY ONLY. Read for rendering/traces,\n * never to make a steer decision (that is the selector = judge coupling). Reads `verdict.score` off\n * `done` settlements whose verdict is `valid`; a `down` child carries no verdict and contributes\n * nothing.\n */\nfunction observedBestScore<D>(\n settledSoFar: ReadonlyArray<Settled<Outcome<D>>>,\n): number | undefined {\n let best: number | undefined\n for (const s of settledSoFar) {\n if (s.kind !== 'done') continue\n const v: DefaultVerdict | undefined = s.verdict\n if (v?.valid !== true || typeof v.score !== 'number') continue\n if (best === undefined || v.score > best) best = v.score\n }\n return best\n}\n","/**\n *\n * The generic combinator library — the content-free act-bodies the wave's §1 contract froze.\n *\n * Each export is a `CombinatorShape<Task, D>` (an alias of `LoopShape<Task, D>`): a factory\n * `(ShapeContext) => Agent<Task, Outcome<D>>` whose `act` runs ONE composition shape over the\n * keystone `Scope` — spawn children through `ctx.spawnChild` + `scope.spawn`, drain settlements\n * via `scope.next()`, select across `done` children with the SINGLE-SOURCED `settledToIteration`\n * + `defaultSelectWinner` (selector≠judge — never a re-rank behind the driver), and synthesize a\n * terminal `Outcome<D>`.\n *\n * The shapes carry NO domain: a \"research sweep over angles\" is `fanout(angles, { synthesize })`\n * under a research persona; a \"code build test\" is `pipeline([plan, implement, integrate])` under\n * a coder persona. The SHAPE is here; the model/prompt/role/goal live on the `Persona` + task,\n * threaded to each child verbatim by the spec-objects the builders take. No model name, prompt,\n * role, or domain noun appears below.\n *\n * Two fail-loud invariants every combinator honors: a child the conserved pool cannot admit is a\n * CONCRETE blocker (never an eager over-fan, never a silent drop), and a `blocked` outcome always\n * names at least one blocker (a shape that cannot finish MUST say why — `blocked([])` throws).\n *\n * @stable\n */\n\nimport { ValidationError } from '../../errors'\nimport { defaultSelectWinner } from '../run-loop'\nimport { type DispatchUnit, rollingDispatch } from '../supervise/dispatch'\nimport { settledToIteration } from '../supervise/scope'\nimport type { Agent, Scope, Settled } from '../supervise/types'\nimport type { Iteration } from '../types'\nimport type { Outcome, ShapeContext } from './types'\nimport type {\n CombinatorShape,\n FanoutOptions,\n FanoutWinnerSelector,\n LoopUntilSpec,\n LoopUntilState,\n PanelJudge,\n PanelSpec,\n PanelVerdict,\n PipelineStage,\n ScopeWidenGate,\n VerifySpec,\n WidenDecision,\n WidenSpec,\n WinnerStrategy,\n} from './wave-types'\n\n// ── selectValidWinner — the one shared valid-only fanout selector ─────────────────\n\n/**\n * The single content-free valid-only winner selector. Among the gated-VALID children only\n * (`verdict.valid === true`), pick by `strategy` — best score / smallest delivered artifact /\n * earliest — ties broken by earliest index; returns `undefined` when NONE is valid (an ungated\n * output can never win — the deliverable gate is the point). `sizeOf` (for `'smallest-artifact'`)\n * reads the child's settled deliverable — the raw value a leaf settles, or the unwrapped `Outcome<D>`\n * a delegate path produces; a domain passes e.g. patch diff-lines. This is the de-duplicated home of\n * the selection logic previously copied per role.\n */\nexport function selectValidWinner<D>(opts?: {\n strategy?: WinnerStrategy\n sizeOf?: (deliverable: D) => number\n}): FanoutWinnerSelector<D> {\n const strategy = opts?.strategy ?? 'highest-score'\n const sizeOfIter = (iter: Iteration<unknown, Outcome<D>>): number => {\n const out = iter.output\n if (out === undefined || opts?.sizeOf === undefined) return Number.POSITIVE_INFINITY\n // The worktree-CLI leaf settles the RAW deliverable as iter.output (settledToIteration sets\n // `output = settled.out`); the MCP delegate path wraps it in an Outcome<D>. Accept both: unwrap\n // a `done` Outcome, else the settled value IS the deliverable. A raw artifact carries no `kind`\n // discriminant, so the branch is unambiguous.\n const deliverable = out.kind === 'done' ? out.deliverable : (out as unknown as D)\n return opts.sizeOf(deliverable)\n }\n return (iterations) => {\n const valid = iterations.filter(\n (iter) => iter.output !== undefined && !iter.error && iter.verdict?.valid === true,\n )\n if (valid.length === 0) return undefined\n switch (strategy) {\n case 'first-valid':\n return [...valid].sort((a, b) => a.index - b.index)[0]\n case 'smallest-artifact':\n return [...valid].sort((a, b) => sizeOfIter(a) - sizeOfIter(b) || a.index - b.index)[0]\n default:\n return [...valid].sort(\n (a, b) => (b.verdict?.score ?? 0) - (a.verdict?.score ?? 0) || a.index - b.index,\n )[0]\n }\n }\n}\n\n// ── pipeline — sequential composition, first blocked stage short-circuits ─────────\n\n/**\n * `pipeline(stages)` — run the stages in order, feeding each stage's `done` deliverable into the\n * next stage's task. The first stage that ends `blocked` (a child that went down, a child the\n * pool would not admit, or a stage whose `collect` chose to block) short-circuits — its blockers\n * ARE the pipeline's blockers, never coerced past a failed stage. The terminal stage's `done`\n * deliverable is the pipeline's deliverable.\n *\n * @stable\n */\nexport function pipeline<Task, D>(\n stages: ReadonlyArray<PipelineStage<Task, unknown, unknown>>,\n): CombinatorShape<Task, D> {\n if (stages.length === 0) {\n throw new ValidationError('pipeline: at least one stage is required')\n }\n return (ctx: ShapeContext<D>): Agent<Task, Outcome<D>> => ({\n name: `${ctx.persona.name}/pipeline`,\n async act(task, scope): Promise<Outcome<D>> {\n let carry: unknown = task\n for (const stage of stages) {\n const child = ctx.spawnChild(stage.label, ctx.persona.root)\n const res = scope.spawn(child, stage.feed(carry, ctx, task), {\n budget: ctx.budget.perChild,\n label: stage.label,\n })\n if (!res.ok) {\n return blocked([`${stage.label}: not admitted (${res.reason})`])\n }\n const settled = await drainOne(scope, stage.label)\n const out = stage.collect(settled as Settled<Outcome<unknown>>)\n if (out.kind === 'blocked') return out\n carry = out.deliverable\n }\n return { kind: 'done', deliverable: carry as D }\n },\n })\n}\n\n// ── fanout — N children in one round, optional single synthesis child ─────────────\n\n/**\n * `fanout(items, opts)` — spawn one child per item in a single round (bounded by the conserved\n * pool's fail-closed admission), drain via `scope.next()`, then either synthesize over the\n * gathered settlements (one SEPARATE synthesis child) or return the best-valid child via the\n * single-sourced selector. A round that admitted zero children, or whose synthesis child could\n * not be admitted, is a concrete blocker.\n *\n * `opts.width` swaps the single round for `rollingDispatch`: at most `width` items live at once,\n * refilled the instant one settles. Selection, blockers, and the conserved pool are unchanged —\n * the refill behavior lives in the existing combinator rather than in a rival primitive.\n *\n * @stable\n */\nexport function fanout<Task, Item, D>(\n items: ReadonlyArray<Item>,\n opts: FanoutOptions<Item, D>,\n): CombinatorShape<Task, D> {\n if (opts.synthesize && opts.selectWinner) {\n throw new ValidationError('fanout: pass at most one of `synthesize` or `selectWinner`')\n }\n return (ctx: ShapeContext<D>): Agent<Task, Outcome<D>> => ({\n name: `${ctx.persona.name}/fanout`,\n async act(_task, scope): Promise<Outcome<D>> {\n const rejected: string[] = []\n // One unit per item — the same child, task, label, and per-child budget either dispatch\n // path uses, so batch and rolling differ ONLY in when each unit is admitted.\n const unitAt = (i: number): DispatchUnit<Outcome<D>> | undefined => {\n const item = items[i]\n if (item === undefined) return undefined\n const label = opts.label ? opts.label(item, i) : `item:${i}`\n const spec = opts.itemSpec ? opts.itemSpec(item, i, ctx) : ctx.persona.root\n return {\n agent: ctx.spawnChild(label, spec),\n task: opts.itemTask(item, i, ctx),\n opts: { budget: ctx.budget.perChild, label },\n }\n }\n\n let opened = 0\n let drained: DrainedRound<D>\n if (opts.width !== undefined) {\n // Rolling: hold `width` items in flight, refill on each settle. `rollingDispatch` owns the\n // admission ledger, so its settlements are projected into the same drained shape the batch\n // path produces and everything downstream (selection, synthesis, blockers) is untouched.\n let next = 0\n const report = await rollingDispatch<Outcome<D>>(scope, {\n width: opts.width,\n nextUnit: () => {\n const unit = unitAt(next)\n next += 1\n return unit\n },\n })\n opened = report.admitted\n for (const r of report.rejected) {\n const [label, reason] = splitOnce(r, ': ')\n rejected.push(`${label}: not admitted (${reason})`)\n }\n drained = projectDrain<D>(report.settled)\n } else {\n for (let i = 0; i < items.length; i += 1) {\n const unit = unitAt(i)\n if (unit === undefined) continue\n const res = scope.spawn(unit.agent, unit.task, unit.opts)\n if (res.ok) opened += 1\n else rejected.push(`${unit.opts.label}: not admitted (${res.reason})`)\n }\n drained = opened === 0 ? emptyRound<D>() : await drain<D>(scope)\n }\n if (opened === 0) {\n return blocked(\n rejected.length > 0\n ? rejected\n : ['fanout: budget admitted no item (fanout fully rejected)'],\n )\n }\n\n if (drained.done.length === 0) {\n return blocked(\n orderedBlockers(\n drained.blockers,\n rejected,\n 'fanout: every item settled without a usable result',\n ),\n )\n }\n\n if (!opts.synthesize) {\n const select = opts.selectWinner ?? defaultSelectWinner\n const winner = select(drained.iterations)\n if (!winner || winner.output === undefined) {\n return blocked(\n orderedBlockers(drained.blockers, rejected, 'fanout: no item survived selection'),\n )\n }\n return { kind: 'done', deliverable: winner.output as D }\n }\n\n const synthLabel = 'synthesize'\n const synthChild = ctx.spawnChild(synthLabel, ctx.persona.root)\n const synthRes = scope.spawn(synthChild, opts.synthesize.synthesisTask(drained.done, ctx), {\n budget: ctx.budget.perChild,\n label: synthLabel,\n })\n if (!synthRes.ok) {\n return blocked([...drained.blockers, `${synthLabel}: not admitted (${synthRes.reason})`])\n }\n const synthSettled = await drainOne(scope, synthLabel)\n const out = opts.synthesize.collect(synthSettled)\n if (out.kind === 'blocked') return out\n return out\n },\n })\n}\n\n// ── loopUntil — budget-bounded iterative deepening, deployable non-oracle stop ────\n\n/**\n * `loopUntil(seed, spec)` — one `step` child per round; `fold` accumulates each settlement into\n * the running state; `until` (reading the round's trace findings, NOT a fresh raw verdict) is\n * the deployable stop. The conserved pool IS the loop bound: once `spawn` fails closed the loop\n * stops. A loop that exhausted the pool without `until` ever satisfying is a concrete blocker.\n *\n * When `ctx.analyst` is set, each round runs it over the children settled so far and steers\n * `until` on the resulting trace-derived findings (the analyst spawns into THIS scope, so its\n * compute is conserved-pooled — equal-k holds by construction). Absent an analyst the findings\n * argument is the empty array — never a fabricated finding (fail-loud honesty over a silent default).\n *\n * @stable\n */\nexport function loopUntil<Task, State, D>(\n seed: State,\n spec: LoopUntilSpec<Task, State, D>,\n): CombinatorShape<Task, D> {\n return (ctx: ShapeContext<D>): Agent<Task, Outcome<D>> => ({\n name: `${ctx.persona.name}/loopUntil`,\n async act(task, scope): Promise<Outcome<D>> {\n let state: LoopUntilState<State> = { round: 0, value: seed }\n const blockers: string[] = []\n const settledSoFar: Settled<Outcome<D>>[] = []\n for (;;) {\n const label = spec.label ? spec.label(state.round) : `step:${state.round}`\n const child = ctx.spawnChild(label, ctx.persona.root)\n const res = scope.spawn(child, spec.step(task, state, ctx), {\n budget: ctx.budget.perChild,\n label,\n })\n if (!res.ok) {\n if (state.round === 0) return blocked([`${label}: not admitted (${res.reason})`])\n break\n }\n const settled = await drainOne(scope, label)\n if (settled.kind === 'down') blockers.push(blockerFromDown(settled))\n settledSoFar.push(settled)\n state = spec.fold(state, settled)\n // Wired analyst ⇒ steer `until` on trace-derived findings; absent ⇒ the dormant empty\n // default (the analyst spawns into THIS scope, so its compute is conserved-pooled).\n const findings = ctx.analyst\n ? await ctx.analyst.analyze({ task, settledSoFar, nodeId: scope.view.root })\n : []\n const reached = spec.until(state, findings)\n if (reached) return reached\n state = { round: state.round + 1, value: state.value }\n }\n return blocked(\n blockers.length > 0\n ? blockers\n : ['loopUntil: budget exhausted before the satisfiability gate was reached'],\n )\n },\n })\n}\n\n// ── panel — M judges over ONE artifact, write-only merge (selector≠judge limit) ───\n\n/**\n * `panel(spec)` — spawn the M judge children over the SAME artifact, drain their settlements,\n * and fold them into a panel verdict via the pure WRITE-ONLY `merge` (a judge's output never\n * reaches another judge's task; the merge never spawns or re-ranks). A `down` judge carries no\n * verdict and is excluded from the merge denominator. A panel that admitted no judge is a\n * concrete blocker before `merge` is consulted.\n *\n * @stable\n */\nexport function panel<Task, Artifact, D>(spec: PanelSpec<Artifact, D>): CombinatorShape<Task, D> {\n if (spec.judges.length === 0) {\n throw new ValidationError('panel: at least one judge is required')\n }\n return (ctx: ShapeContext<D>): Agent<Task, Outcome<D>> => ({\n name: `${ctx.persona.name}/panel`,\n async act(task, scope): Promise<Outcome<D>> {\n const artifact = task as unknown as Artifact\n const byLabel = new Map<string, PanelJudge>()\n const rejected: string[] = []\n let opened = 0\n for (const judge of spec.judges) {\n const child = ctx.spawnChild(judge.label, ctx.persona.root)\n const res = scope.spawn(child, spec.judgeTask(artifact, judge, ctx), {\n budget: ctx.budget.perChild,\n label: judge.label,\n })\n if (res.ok) {\n byLabel.set(judge.label, judge)\n opened += 1\n } else {\n rejected.push(`${judge.label}: not admitted (${res.reason})`)\n }\n }\n if (opened === 0) {\n return blocked(rejected.length > 0 ? rejected : ['panel: budget admitted no judge'])\n }\n\n const verdicts: PanelVerdict[] = []\n for (let s = await scope.next(); s !== null; s = await scope.next()) {\n const judge = byLabel.get(s.handle.label)\n if (!judge) {\n throw new ValidationError(\n `panel: settled child \"${s.handle.label}\" has no judge descriptor`,\n )\n }\n if (s.kind === 'down') {\n verdicts.push({ judge, down: true })\n continue\n }\n verdicts.push({\n judge,\n down: false,\n ...(s.verdict ? { verdict: s.verdict } : {}),\n output: s.out,\n })\n }\n return spec.merge(verdicts, artifact)\n },\n })\n}\n\n// ── verify — 2-node implement→verifier gate (selector≠judge) ──────────────────────\n\n/**\n * `verify(spec)` — an IMPLEMENT child produces a candidate, then a SEPARATE VERIFIER child grades\n * it; only a `valid` verifier verdict ships. Any other outcome (implement down, verifier down,\n * verifier verdict absent or not `valid`) is a concrete blocker carrying the failure verbatim —\n * never a coerced \"done\". The implement child does not grade itself.\n *\n * @stable\n */\nexport function verify<Task, Candidate, D>(\n spec: VerifySpec<Task, Candidate, D>,\n): CombinatorShape<Task, D> {\n return (ctx: ShapeContext<D>): Agent<Task, Outcome<D>> => ({\n name: `${ctx.persona.name}/verify`,\n async act(task, scope): Promise<Outcome<D>> {\n const implementLabel = spec.implementLabel ?? 'implement'\n const implChild = ctx.spawnChild(implementLabel, ctx.persona.root)\n const implRes = scope.spawn(implChild, spec.implement(task, ctx), {\n budget: ctx.budget.perChild,\n label: implementLabel,\n })\n if (!implRes.ok) return blocked([`${implementLabel}: not admitted (${implRes.reason})`])\n const candidate = await drainOne(scope, implementLabel)\n if (candidate.kind === 'down') return blocked([blockerFromDown(candidate)])\n\n const verifierLabel = spec.verifierLabel ?? 'verify'\n const verifierChild = ctx.spawnChild(verifierLabel, ctx.persona.root)\n const verifierRes = scope.spawn(\n verifierChild,\n spec.verifier(candidate as Settled<Outcome<Candidate>>, ctx),\n { budget: ctx.budget.perChild, label: verifierLabel },\n )\n if (!verifierRes.ok)\n return blocked([`${verifierLabel}: not admitted (${verifierRes.reason})`])\n const gate = await drainOne(scope, verifierLabel)\n if (gate.kind === 'down') return blocked([blockerFromDown(gate)])\n if (gate.verdict?.valid !== true) {\n return blocked([`${verifierLabel}: gate rejected the candidate (${verdictDetail(gate)})`])\n }\n return spec.collect(candidate as Settled<Outcome<Candidate>>, gate.verdict)\n },\n })\n}\n\n// ── widen — streaming progressive widening (G5), FLAT by default ──────────────────\n\n/**\n * `widen(spec)` — the streaming spawn-on-completion driver. Spawns the seed lineages, then REACTS\n * to each `scope.next()`: on every settled child it consults `spec.gate.decide` and, when the gate\n * returns `widen`, spawns AT MOST ONE more child toward the chosen lineage under the remaining\n * conserved pool. `promising` is derived from the round's trace findings (the analyst seam),\n * never a child's raw `verdict` — and the default gate (`flatWidenGate`) never widens, so the R2\n * firewall stays dormant. Terminal selection is `spec.synthesize` over every settled lineage.\n *\n * When `ctx.analyst` is set, `decide` is consulted with that round's trace-derived findings;\n * absent an analyst the findings argument is the empty array a flat gate ignores. The analyst\n * spawns into THIS scope (conserved-pooled, so equal-k holds). Streaming caveat: a wired analyst\n * drains its own child off the SHARED cursor by id-match, so on a NON-flat gate (which spawns\n * widen children that are live concurrently) the analyst can consume a sibling's settlement before\n * the widen loop sees it. The shipped default (`flatWidenGate`) never widens, so no widen child is\n * ever live when the analyst runs and the wire is exact; a non-flat gate must drive the analyst on\n * a scope whose siblings are quiesced, or read findings without the shared-cursor drain.\n *\n * @stable\n */\nexport function widen<Task, Seed, D>(spec: WidenSpec<Seed, D>): CombinatorShape<Task, D> {\n return (ctx: ShapeContext<D>): Agent<Task, Outcome<D>> => ({\n name: `${ctx.persona.name}/widen`,\n async act(_task, scope): Promise<Outcome<D>> {\n let opened = 0\n for (const [i, seed] of spec.seeds.entries()) {\n const label = `seed:${i}`\n const child = ctx.spawnChild(label, ctx.persona.root)\n const res = scope.spawn(child, spec.seedTask(seed, i, ctx), {\n budget: ctx.budget.perChild,\n label,\n })\n if (res.ok) opened += 1\n }\n if (opened === 0) {\n return blocked(['widen: budget admitted no seed lineage'])\n }\n\n const gathered: Settled<Outcome<D>>[] = []\n let widenIndex = 0\n for (let s = await scope.next(); s !== null; s = await scope.next()) {\n gathered.push(s)\n // Wired analyst ⇒ steer the gate on trace-derived findings; absent ⇒ the dormant empty\n // default the flat gate ignores. The analyst spawns into THIS scope (conserved-pooled).\n const findings = ctx.analyst\n ? await ctx.analyst.analyze({\n task: _task,\n settledSoFar: gathered,\n nodeId: scope.view.root,\n })\n : []\n const decision: WidenDecision<D> = spec.gate.decide(s, findings, scope.budget)\n if (decision.kind !== 'widen') continue\n const label = `widen:${widenIndex}`\n widenIndex += 1\n const child = ctx.spawnChild(label, ctx.persona.root)\n // Fail-closed admission bounds the widening — a rejected widen is simply not opened\n // (the gate may widen again off a later settlement); the budget is the breadth bound.\n scope.spawn(child, spec.widenTask(decision.toward, ctx), {\n budget: ctx.budget.perChild,\n label,\n })\n }\n\n const done = gathered.filter(isDone)\n if (done.length === 0) {\n return blocked(\n orderedBlockers(\n gathered.filter(isDown).map(blockerFromDown),\n [],\n 'widen: every lineage settled without a usable result',\n ),\n )\n }\n return spec.synthesize(done, ctx)\n },\n })\n}\n\n/**\n * The flat default `ScopeWidenGate` — never widens, keeping the R2 selector≠judge collision\n * dormant. A gate run passes this explicitly; a test asserts the default is flat.\n */\nexport function flatWidenGate<D>(): ScopeWidenGate<D> {\n return {\n decide(): WidenDecision<D> {\n return { kind: 'stop' }\n },\n }\n}\n\n// ── Shared drain / select / blocker microstructure ────────────────────────────────\n\n/** Drain every remaining settlement: project `done` children into kernel `Iteration`s for the\n * single-sourced selector + keep the `done` settlements (for a synthesis child), and collect\n * `down` children as concrete blockers (their reason surfaced verbatim). */\n/** The gathered result of one fanout round: the selector's candidates, the `done` settlements the\n * synthesis task reads, and the concrete blockers from every `down` child. */\ninterface DrainedRound<D> {\n iterations: Iteration<unknown, Outcome<D>>[]\n done: Settled<Outcome<D>>[]\n blockers: string[]\n}\n\nfunction emptyRound<D>(): DrainedRound<D> {\n return { iterations: [], done: [], blockers: [] }\n}\n\n/** Fold an already-collected settlement list into the same shape `drain` produces, so the rolling\n * dispatch path and the batch path hand identical evidence to selection/synthesis. */\nfunction projectDrain<D>(settled: ReadonlyArray<Settled<Outcome<D>>>): DrainedRound<D> {\n const round = emptyRound<D>()\n for (const s of settled) {\n if (s.kind === 'down') {\n round.blockers.push(blockerFromDown(s))\n continue\n }\n round.iterations.push(settledToIteration(s))\n round.done.push(s)\n }\n return round\n}\n\n/** Split on the FIRST occurrence of `sep`, keeping any later occurrences in the tail — a reason\n * string may itself contain the separator. */\nfunction splitOnce(text: string, sep: string): [string, string] {\n const at = text.indexOf(sep)\n if (at < 0) return [text, '']\n return [text.slice(0, at), text.slice(at + sep.length)]\n}\n\nasync function drain<D>(scope: Scope<Outcome<D>>): Promise<DrainedRound<D>> {\n const iterations: Iteration<unknown, Outcome<D>>[] = []\n const done: Settled<Outcome<D>>[] = []\n const blockers: string[] = []\n for (let s = await scope.next(); s !== null; s = await scope.next()) {\n if (s.kind === 'down') {\n blockers.push(blockerFromDown(s))\n continue\n }\n iterations.push(settledToIteration(s))\n done.push(s)\n }\n return { iterations, done, blockers }\n}\n\n/**\n * Drain exactly one settlement off a scope whose prior children are fully drained, so `next()`\n * yields precisely the child just spawned. Fail loud if it yields nothing — a spawned child that\n * never settles is a keystone invariant violation, not a result the combinator may swallow.\n */\nasync function drainOne<D>(scope: Scope<Outcome<D>>, label: string): Promise<Settled<Outcome<D>>> {\n const s = await scope.next()\n if (s === null) {\n throw new ValidationError(`combinator: child \"${label}\" was spawned but never settled`)\n }\n return s\n}\n\nfunction isDone<D>(s: Settled<Outcome<D>>): s is Extract<Settled<Outcome<D>>, { kind: 'done' }> {\n return s.kind === 'done'\n}\n\nfunction isDown<D>(s: Settled<Outcome<D>>): s is Extract<Settled<Outcome<D>>, { kind: 'down' }> {\n return s.kind === 'down'\n}\n\nfunction blockerFromDown<D>(s: Extract<Settled<Outcome<D>>, { kind: 'down' }>): string {\n return `${s.handle.label}: ${s.infra ? 'infra' : 'failed'} — ${s.reason}`\n}\n\nfunction verdictDetail<D>(s: Extract<Settled<Outcome<D>>, { kind: 'done' }>): string {\n if (!s.verdict) return 'no verdict'\n return s.verdict.notes ?? `score ${s.verdict.score}`\n}\n\n/** Compose the round's drained blockers + rejected-admission reasons, falling back to a named\n * default ONLY when neither produced a reason — a `blocked` outcome must never be vacuous. */\nfunction orderedBlockers(drained: string[], rejected: string[], fallback: string): string[] {\n const all = [...drained, ...rejected]\n return all.length > 0 ? all : [fallback]\n}\n\n/** Build a `blocked` outcome, failing loud on the empty-blocker contract violation (a shape that\n * cannot finish MUST name at least one concrete blocker — never a vacuous block). */\nfunction blocked<D>(blockers: string[]): Extract<Outcome<D>, { kind: 'blocked' }> {\n if (blockers.length === 0) {\n throw new ValidationError('combinator: a blocked outcome must name at least one blocker')\n }\n return { kind: 'blocked', blockers }\n}\n","/**\n *\n * The cross-run corpus (G2) — the learning-flywheel's durable accreted-fact store.\n *\n * `Corpus` is DISTINCT from the per-run `SpawnJournal` (decisions/replay) and `ResultBlobStore`\n * (payloads): a `CorpusRecord` is a FACT one run LEARNED that a FUTURE run reads back (the\n * world-model), not a replay input. This module owns the two impls the wave surface pins —\n * `InMemoryCorpus` and `FileCorpus` (JSONL, append-only) — plus `renderCorpusToInstructions`,\n * the READ side that projects accreted facts into a fresh `AgentProfile`'s instruction seams.\n *\n * The boundary is fail-loud, typed-outcome: `append` is idempotent on an identical record and\n * returns a typed error (never throws, never a silent overwrite) on a conflicting re-append under\n * the same `id`. Malformed records — a structurally-invalid `CorpusRecord` from disk or a caller —\n * fail loud (the validator throws), since a corpus that silently accepts garbage would poison\n * every downstream run that reads it back.\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { prepareJsonlAppend, readCommittedJsonLines, writeAllBytes } from '../../durable/jsonl-file'\nimport { detachedFrozen } from '../supervise/snapshot'\nimport type {\n Corpus,\n CorpusFilter,\n CorpusRecord,\n RenderCorpusToInstructionsOptions,\n} from './wave-types'\n\n// ── Record validation ────────────────────────────────────────────────────────\n\nconst corpusSchemaVersion = '1.0.0'\n\n/**\n * Assert a value is a well-formed `CorpusRecord`. A PROVENANCE-and-shape check: every\n * identity/render-gating field must be present and typed, `confidence` must be a finite 0..1,\n * `evidence` (when present) must be `{ kind, uri }[]`. Throws on any violation — a corpus that\n * silently accepted a malformed fact would project garbage into a future run's prompt. The\n * thrown message names the offending field so a bad on-disk line is diagnosable.\n */\nexport function assertCorpusRecord(value: unknown, where: string): asserts value is CorpusRecord {\n if (typeof value !== 'object' || value === null) {\n throw new Error(`${where}: corpus record is not an object`)\n }\n const r = value as Record<string, unknown>\n if (r.schemaVersion !== corpusSchemaVersion) {\n throw new Error(\n `${where}: corpus record schemaVersion '${String(r.schemaVersion)}' != '${corpusSchemaVersion}'`,\n )\n }\n requireNonEmptyString(r.id, `${where}.id`)\n requireNonEmptyString(r.runId, `${where}.runId`)\n requireNonEmptyString(r.producedAt, `${where}.producedAt`)\n requireNonEmptyString(r.area, `${where}.area`)\n requireNonEmptyString(r.claim, `${where}.claim`)\n if (r.rationale !== undefined && typeof r.rationale !== 'string') {\n throw new Error(`${where}.rationale: expected string, got ${typeof r.rationale}`)\n }\n if (!Array.isArray(r.tags) || r.tags.some((t) => typeof t !== 'string')) {\n throw new Error(`${where}.tags: expected string[]`)\n }\n if (typeof r.confidence !== 'number' || !Number.isFinite(r.confidence)) {\n throw new Error(`${where}.confidence: expected a finite number, got ${String(r.confidence)}`)\n }\n if (r.confidence < 0 || r.confidence > 1) {\n throw new Error(`${where}.confidence: ${r.confidence} is outside the [0, 1] range`)\n }\n if (r.evidence !== undefined) {\n if (!Array.isArray(r.evidence)) {\n throw new Error(`${where}.evidence: expected an array`)\n }\n for (let i = 0; i < r.evidence.length; i++) {\n const ev = r.evidence[i] as Record<string, unknown> | null\n if (typeof ev !== 'object' || ev === null) {\n throw new Error(`${where}.evidence[${i}]: not an object`)\n }\n requireNonEmptyString(ev.kind, `${where}.evidence[${i}].kind`)\n requireNonEmptyString(ev.uri, `${where}.evidence[${i}].uri`)\n }\n }\n}\n\nfunction requireNonEmptyString(value: unknown, where: string): void {\n if (typeof value !== 'string' || value.length === 0) {\n throw new Error(`${where}: expected a non-empty string, got ${describe(value)}`)\n }\n}\n\nfunction describe(value: unknown): string {\n if (value === undefined) return 'undefined'\n if (value === null) return 'null'\n if (typeof value === 'string') return `'${value}'`\n return typeof value\n}\n\n// ── Identity + idempotence ───────────────────────────────────────────────────\n\n/**\n * Two records collide IFF they share an `id`. An append under an already-stored `id` is idempotent\n * only when the new record is byte-identical to the stored one (same fact, re-learned); any other\n * field differing under the same `id` is a CONFLICT — a typed-error append, never a silent\n * overwrite. The identity field is `id`; the producer mints it over its identity-defining fields\n * (claim + tags) so a re-learned fact dedups.\n */\nfunction recordsEqual(a: CorpusRecord, b: CorpusRecord): boolean {\n return stableStringify(a) === stableStringify(b)\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([x], [y]) => (x < y ? -1 : x > y ? 1 : 0))\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`\n}\n\n// ── Query ─────────────────────────────────────────────────────────────────────\n\n/**\n * Apply a `CorpusFilter` as an AND-narrowing over a record list and sort most-confident first\n * (ties → most-recent `producedAt`, so the freshest of two equally-confident facts wins). Pure —\n * the in-mem and file impls both route their reads through this so query semantics are\n * single-sourced. An empty result is valid (not an error).\n */\nfunction applyFilter(\n records: ReadonlyArray<CorpusRecord>,\n filter: CorpusFilter,\n): ReadonlyArray<CorpusRecord> {\n const matched = records.filter((r) => {\n if (filter.area !== undefined && r.area !== filter.area) return false\n if (filter.runId !== undefined && r.runId !== filter.runId) return false\n if (filter.minConfidence !== undefined && r.confidence < filter.minConfidence) return false\n if (filter.tags !== undefined && !filter.tags.every((t) => r.tags.includes(t))) return false\n return true\n })\n const ordered = [...matched].sort((a, b) =>\n b.confidence !== a.confidence\n ? b.confidence - a.confidence\n : b.producedAt < a.producedAt\n ? -1\n : b.producedAt > a.producedAt\n ? 1\n : 0,\n )\n if (filter.limit !== undefined) {\n if (!Number.isInteger(filter.limit) || filter.limit < 0) {\n throw new Error(\n `corpus query: filter.limit must be a non-negative integer, got ${filter.limit}`,\n )\n }\n return ordered.slice(0, filter.limit)\n }\n return ordered\n}\n\n// ── In-memory corpus ────────────────────────────────────────────────────────\n\n/**\n * In-memory `Corpus`. Keyed by record `id`; `append` validates the record, is idempotent on an\n * identical re-append, and returns a typed `{ succeeded: false }` on a conflicting re-append under\n * the same `id` (never overwrites). `query` routes through the single-sourced `applyFilter`.\n */\nexport class InMemoryCorpus implements Corpus {\n private readonly byId = new Map<string, CorpusRecord>()\n\n async append(\n record: CorpusRecord,\n ): Promise<{ succeeded: true } | { succeeded: false; error: string }> {\n let snapshot: CorpusRecord\n try {\n assertCorpusRecord(record, 'append: record')\n snapshot = detachedFrozen(record)\n } catch (err) {\n return { succeeded: false, error: err instanceof Error ? err.message : String(err) }\n }\n const existing = this.byId.get(snapshot.id)\n if (existing) {\n if (recordsEqual(existing, snapshot)) return { succeeded: true }\n return {\n succeeded: false,\n error:\n `corpus conflict: id '${record.id}' is already stored with a different record; ` +\n 'a learned fact is append-only — re-mint the id or reconcile before re-appending',\n }\n }\n this.byId.set(snapshot.id, snapshot)\n return { succeeded: true }\n }\n\n async query(filter: CorpusFilter): Promise<ReadonlyArray<CorpusRecord>> {\n return applyFilter([...this.byId.values()], filter)\n }\n}\n\n// ── File corpus (JSONL, append-only) ──────────────────────────────────────────\n\n/**\n * JSONL on disk — one validated `CorpusRecord` per line, append-only. `query` replays the whole\n * file, validating every line (a malformed line fails loud — a corrupted corpus must never read\n * back silently) and folding by `id`: a later identical line dedups, a later conflicting line\n * under the same `id` is a corruption (fail loud). `append` first replays to enforce the same\n * idempotence/conflict contract as the in-mem impl, then fsyncs the new line so a crash between\n * writes never loses an acknowledged fact. Reads and appends over the shared append-only\n * spine (`durable/jsonl-file`) — the same one the spawn journal uses — but the interface stays\n * separate (a learned fact is not a replay record).\n */\nexport class FileCorpus implements Corpus {\n constructor(private readonly path: string) {}\n\n async append(\n record: CorpusRecord,\n ): Promise<{ succeeded: true } | { succeeded: false; error: string }> {\n try {\n assertCorpusRecord(record, 'append: record')\n const snapshot = detachedFrozen(record)\n const fs = await import('node:fs/promises')\n const { dirname } = await import('node:path')\n const { tryAcquireAtomicFileLock } = await import('@tangle-network/agent-eval/ledger-core')\n await fs.mkdir(dirname(this.path), { recursive: true })\n // Create the file before resolving it so aliases share a lock on the first append too.\n const file = await fs.open(this.path, 'a')\n await file.close()\n const canonicalPath = await fs.realpath(this.path)\n const deadline = Date.now() + 5000\n for (;;) {\n const acquisition = tryAcquireAtomicFileLock({ lockPath: `${canonicalPath}.lock` })\n if (!acquisition.acquired) {\n if (Date.now() >= deadline) {\n throw new Error(`corpus append lock unavailable after 5000ms: ${canonicalPath}`)\n }\n await new Promise((resolve) => setTimeout(resolve, 25))\n continue\n }\n try {\n const stored = await this.load(canonicalPath)\n const existing = stored.get(snapshot.id)\n if (existing) {\n if (recordsEqual(existing, snapshot)) return { succeeded: true }\n return {\n succeeded: false,\n error:\n `corpus conflict: id '${snapshot.id}' is already stored in ${canonicalPath} with a different ` +\n 'record; a learned fact is append-only — re-mint the id or reconcile before re-appending',\n }\n }\n await this.appendLine(canonicalPath, snapshot)\n return { succeeded: true }\n } finally {\n acquisition.lock.release()\n }\n }\n } catch (err) {\n return { succeeded: false, error: err instanceof Error ? err.message : String(err) }\n }\n }\n\n async query(filter: CorpusFilter): Promise<ReadonlyArray<CorpusRecord>> {\n const stored = await this.load()\n return applyFilter([...stored.values()], filter)\n }\n\n private async load(path = this.path): Promise<Map<string, CorpusRecord>> {\n const byId = new Map<string, CorpusRecord>()\n let recordNumber = 0\n for await (const parsed of readCommittedJsonLines<unknown>(path, { allowMissing: true })) {\n assertCorpusRecord(parsed, `corpus ${this.path} line ${++recordNumber}`)\n const existing = byId.get(parsed.id)\n if (existing && !recordsEqual(existing, parsed)) {\n throw new Error(\n `corpus corrupted: ${this.path} has two different records for id '${parsed.id}'; ` +\n 'an append-only corpus must never hold a conflicting re-append under one id',\n )\n }\n byId.set(parsed.id, detachedFrozen(parsed))\n }\n return byId\n }\n\n private async appendLine(path: string, record: CorpusRecord): Promise<void> {\n const fs = await import('node:fs/promises')\n const needsSeparator = await prepareJsonlAppend(path)\n const fh = await fs.open(path, 'a')\n try {\n await writeAllBytes(fh, `${needsSeparator ? '\\n' : ''}${JSON.stringify(record)}\\n`)\n await fh.sync()\n } finally {\n await fh.close()\n }\n }\n}\n\n// ── Render-back: project accreted facts into a profile's instruction seams ─────\n\n/**\n * The learning-flywheel READ side. Queries the corpus through `filter`, renders the matching facts\n * (most-confident first, capped by `maxLines`) into instruction lines, and returns a FRESH\n * `AgentProfile` with them merged in — never mutates the input profile. Default `target: 'prompt'`\n * appends the lines to `prompt.instructions[]` (the additive append-line seam); `target:\n * 'resources'` folds them into the single-blob `resources.instructions` string (preserving any\n * existing blob, but failing loud on a non-string existing blob — a `resources.instructions` that\n * was already an `AgentProfileResourceRef` cannot be string-appended without dropping it).\n *\n * An empty query result returns a fresh COPY of the profile with no instruction change (a valid\n * \"nothing learned yet\" read, not an error).\n */\nexport async function renderCorpusToInstructions(\n opts: RenderCorpusToInstructionsOptions,\n): Promise<AgentProfile> {\n const { corpus, filter, profile, target = 'prompt', maxLines } = opts\n if (maxLines !== undefined && (!Number.isInteger(maxLines) || maxLines < 0)) {\n throw new Error(\n `renderCorpusToInstructions: maxLines must be a non-negative integer, got ${maxLines}`,\n )\n }\n const matched = await corpus.query(filter)\n const capped = maxLines !== undefined ? matched.slice(0, maxLines) : matched\n const lines = capped.map(renderLine)\n\n if (lines.length === 0) return structuredClone(profile)\n\n const next = structuredClone(profile)\n if (target === 'resources') {\n const resources = next.resources ?? {}\n const prior = resources.instructions\n if (prior !== undefined && typeof prior !== 'string') {\n throw new Error(\n 'renderCorpusToInstructions: resources.instructions is an AgentProfileResourceRef, not a ' +\n 'string; cannot string-append corpus facts without dropping the ref (pass target: ' +\n \"'prompt' or pre-resolve the ref)\",\n )\n }\n const blob = [prior, ...lines].filter((s): s is string => typeof s === 'string' && s.length > 0)\n next.resources = { ...resources, instructions: blob.join('\\n') }\n return next\n }\n\n const prompt = next.prompt ?? {}\n next.prompt = { ...prompt, instructions: [...(prompt.instructions ?? []), ...lines] }\n return next\n}\n\n/** One corpus fact → one instruction line. The claim is the line; a rationale (when present) is\n * appended in parentheses so a reader sees the why without a second line. Content-only — no\n * metric/score/verdict text is synthesized (the corpus holds facts, not selector evidence). */\nfunction renderLine(record: CorpusRecord): string {\n return record.rationale ? `${record.claim} (${record.rationale})` : record.claim\n}\n","/**\n *\n * The loop-shape registry — the OPEN, content-free extension point for the personify layer.\n *\n * A `LoopShape` is reusable STRUCTURE (how to decompose / fan out / verify / synthesize),\n * parameterized by a persona's CONTENT. The registry lets a caller resolve a composed shape by\n * NAME: register a factory once, then `runPersonified({ shape: '<name>' })` resolves it with zero\n * edits elsewhere. `register` fails loud on a duplicate; `resolve` returns a typed outcome so an\n * unknown name is a named error, never a silent default.\n *\n * No shape is pre-registered: the generic combinators (`pipeline`/`fanout`/`loopUntil`/`panel`/\n * `verify`/`widen`) take spec arguments, so they are not bare zero-arg factories — a caller that\n * wants name-resolution registers its own COMPOSED shape (a combinator already applied to its\n * spec) on a registry instance. The registry carries SHAPE only; the domain lives on the persona.\n *\n * @experimental\n */\n\nimport { ValidationError } from '../../errors'\nimport type { LoopShape, ShapeRegistry } from './types'\n\n/**\n * Build a fresh open `ShapeRegistry`. A factory is stored type-erased and re-cast on resolve — the\n * caller asserts the `<Task, D>` it expects, exactly as the executor registry stores its factories.\n */\nexport function createShapeRegistry(): ShapeRegistry {\n const shapes = new Map<string, LoopShape<unknown, unknown>>()\n return {\n register<Task, D>(name: string, factory: LoopShape<Task, D>): void {\n if (shapes.has(name)) {\n throw new ValidationError(`shape registry: shape \"${name}\" already registered`)\n }\n shapes.set(name, factory as LoopShape<unknown, unknown>)\n },\n resolve<Task, D>(name: string) {\n const factory = shapes.get(name)\n if (!factory) {\n return { succeeded: false as const, error: `shape registry: unknown shape \"${name}\"` }\n }\n return { succeeded: true as const, value: factory as LoopShape<Task, D> }\n },\n names(): string[] {\n return [...shapes.keys()]\n },\n }\n}\n\n/** The default registry `runPersonified` resolves a shape name against. Empty by construction —\n * a caller registers its own composed shapes; the engine ships no domain shape. */\nexport const builtinShapes: ShapeRegistry = createShapeRegistry()\n\n/** Register a composed shape on the default `builtinShapes` registry — the one-call extension\n * point a caller invokes so its shape is resolvable by name with zero edits to the engine. */\nexport function registerShape<Task, D>(name: string, factory: LoopShape<Task, D>): void {\n builtinShapes.register(name, factory)\n}\n","/**\n *\n * The personify layer impl — `definePersona` (the thin builder) + `runPersonified` (composes\n * the persona + chosen shape onto the keystone `Supervisor`), plus `createShapeContext`, the\n * seam that hands a shape its spawn helpers without it touching the registry.\n *\n * This file adds NO engine: `runPersonified` is `createSupervisor().run(rootAgent, task, …)`\n * where `rootAgent` is the persona's chosen `LoopShape` applied to a `ShapeContext`. All the\n * conserved-budget / journal / abort / typed-result machinery is the keystone's; this layer\n * only wires the persona's CONTENT (root spec + directive + context + seams) into it.\n *\n * One non-obvious invariant it must honor: `createSupervisor().run` builds the root `Scope`\n * with an EMPTY seam bag (`seams: {}`), so the built-in metered runtimes (router/sandbox/cli)\n * cannot read their seams off `ExecutorContext` through the default supervisor path. A persona\n * that supplies raw `seams` is therefore wrapped here into a registry whose resolved factories\n * receive a ctx with the persona seams merged in — so a persona never has to pre-close its\n * factories by hand. A persona may instead supply a fully-built `registry` and skip the wrap.\n *\n * @stable\n */\n\nimport { InMemoryResultBlobStore, InMemorySpawnJournal } from '../../durable/spawn-journal'\nimport { ValidationError } from '../../errors'\nimport { withDriverExecutor } from '../supervise/driver-executor'\nimport { executableAgentSpecSnapshot } from '../supervise/executable-spec'\nimport { createExecutorRegistry } from '../supervise/runtime'\nimport { createSupervisor } from '../supervise/supervisor'\nimport type {\n Agent,\n AgentSpec,\n Budget,\n ExecutorContext,\n ExecutorFactory,\n ExecutorRegistry,\n Runtime,\n SupervisedResult,\n SupervisorOpts,\n} from '../supervise/types'\nimport { builtinShapes } from './registry'\nimport type {\n DefinePersonaInput,\n LoopShape,\n Outcome,\n Persona,\n RunPersonifiedOptions,\n ShapeBudget,\n ShapeContext,\n} from './types'\nimport type { ScopeAnalyst } from './wave-types'\n\n// ── definePersona ─────────────────────────────────────────────────────────────\n\n/**\n * Build a frozen `Persona`. Fails loud on the executors-supplied invariant: a persona with\n * neither a pre-built registry nor a seam bag cannot resolve its built-in runtimes, so it is\n * unrunnable — refuse it at definition time, not at the first spawn. Pure; no I/O.\n *\n * @stable\n */\nexport function definePersona<D = unknown>(input: DefinePersonaInput<D>): Persona<D> {\n if (!input.executors.registry && !input.executors.seams) {\n throw new ValidationError(\n `definePersona(\"${input.name}\"): executors must supply a registry or a seams bag ` +\n '(built-in runtimes read their seams off ExecutorContext; neither was provided)',\n )\n }\n if (!input.root || typeof input.root !== 'object' || !('harness' in input.root)) {\n throw new ValidationError(`definePersona(\"${input.name}\"): root must be an AgentSpec`)\n }\n const root = executableAgentSpecSnapshot(input.root, `definePersona(\"${input.name}\")`)\n return Object.freeze({\n name: input.name,\n root,\n directive: input.directive,\n context: input.context,\n executors: input.executors,\n ...(input.extensions ? { extensions: input.extensions } : {}),\n }) as Persona<D>\n}\n\n// ── ShapeContext construction ───────────────────────────────────────────────────\n\n/**\n * Build the `ShapeContext` a `LoopShape` factory consumes. `spawnChild` wraps an `AgentSpec`\n * into a leaf `Agent` carrying it as `executorSpec` (the structural field `scope.spawn`\n * reads); `childSpec` derives a narrower child spec from the persona's root by overriding the\n * profile. The shape never touches the registry — resolution stays single-sourced in the\n * scope/registry the supervisor owns.\n */\nexport function createShapeContext<D>(\n persona: Persona<D>,\n budget: ShapeBudget,\n analyst?: ScopeAnalyst<D>,\n): ShapeContext<D> {\n return {\n persona,\n budget,\n ...(analyst ? { analyst } : {}),\n spawnChild(name, spec): Agent<unknown, Outcome<D>> {\n // The wrapped agent is SPAWNED, not run — the resolved Executor drives it. The\n // executor is a LEAF for a plain spec OR the recursive driver-executor for a\n // `role:'driver'` spec (a child that is itself a driver — agents drive agents). `act`\n // is never invoked by the keystone for a spawned child (the executor drives it); it\n // throws if mis-used as a root (fail loud), never a vacuous outcome.\n const agent = {\n name,\n executorSpec: spec,\n act(): Promise<Outcome<D>> {\n throw new ValidationError(\n `personify: spawned child \"${name}\" was run directly; its executorSpec drives it ` +\n '(a leaf, or — for a driver child — a nested scope through the recursive driver-executor)',\n )\n },\n }\n return agent as Agent<unknown, Outcome<D>> & { executorSpec: AgentSpec }\n },\n childSpec(profile, harness): AgentSpec {\n return {\n profile,\n harness: harness === undefined ? persona.root.harness : harness,\n ...(persona.root.executor ? { executor: persona.root.executor } : {}),\n }\n },\n }\n}\n\n// ── runPersonified ──────────────────────────────────────────────────────────────\n\n/**\n * Compose the persona + chosen shape onto a fresh keystone `Supervisor`. Resolves the shape\n * (a factory verbatim, or a registered name through `builtinShapes`), applies it to a\n * `ShapeContext`, and runs the resulting root `Agent` to a typed `SupervisedResult<Outcome>`.\n * Fail loud on an unknown shape name or an unresolvable persona registry — never a silent\n * default-shape fallback.\n *\n * @stable\n */\nexport async function runPersonified<Task, D>(\n options: RunPersonifiedOptions<Task, D>,\n): Promise<SupervisedResult<Outcome<D>>> {\n const { persona } = options\n const shape = resolveShape<Task, D>(options.shape)\n const shapeBudget = resolveShapeBudget(options.budget, options.shapeBudget)\n const ctx = createShapeContext(persona, shapeBudget, options.analyst)\n const rootAgent = shape(ctx)\n\n const executors = personaRegistry(persona)\n const supervisor = createSupervisor<Task, Outcome<D>>()\n if (options.handle) supervisor.attach(options.handle)\n\n const supervisorOpts: SupervisorOpts = {\n budget: options.budget,\n runId: options.runId ?? `${persona.name}:${shapeName(options.shape, shape)}`,\n journal: options.journal ?? new InMemorySpawnJournal(),\n blobs: options.blobs ?? new InMemoryResultBlobStore(),\n executors,\n ...(options.rootIdentity !== undefined ? { rootIdentity: options.rootIdentity } : {}),\n ...(options.maxDepth !== undefined ? { maxDepth: options.maxDepth } : {}),\n ...(options.workerSlots !== undefined ? { workerSlots: options.workerSlots } : {}),\n ...(options.maxRestarts !== undefined ? { maxRestarts: options.maxRestarts } : {}),\n ...(options.withinMs !== undefined ? { withinMs: options.withinMs } : {}),\n ...(options.teardownConfirmMs !== undefined\n ? { teardownConfirmMs: options.teardownConfirmMs }\n : {}),\n ...(options.resume !== undefined ? { resume: options.resume } : {}),\n ...(options.now ? { now: options.now } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n ...(options.hooks ? { hooks: options.hooks } : {}),\n }\n return supervisor.run(rootAgent, options.task, supervisorOpts)\n}\n\n// ── Resolution helpers ──────────────────────────────────────────────────────────\n\nfunction resolveShape<Task, D>(shape: LoopShape<Task, D> | string): LoopShape<Task, D> {\n if (typeof shape !== 'string') return shape\n const resolved = builtinShapes.resolve<Task, D>(shape)\n if (!resolved.succeeded) {\n throw new ValidationError(\n `runPersonified: ${resolved.error} (registered: ${builtinShapes.names().join(', ')})`,\n )\n }\n return resolved.value\n}\n\nfunction shapeName<Task, D>(\n shape: LoopShape<Task, D> | string,\n _resolved: LoopShape<Task, D>,\n): string {\n return typeof shape === 'string' ? shape : shape.name || 'shape'\n}\n\n/**\n * Default the shape's per-child sizing + fanout width from the root budget when the caller\n * omits them. The per-child token ceiling is the root divided across the fanout so the\n * conserved pool can admit a full round; iterations default to the root's. A caller override\n * wins per-field.\n */\nfunction resolveShapeBudget(root: Budget, over?: Partial<ShapeBudget>): ShapeBudget {\n const fanout = over?.fanout ?? defaultFanout\n const perChild: Budget = over?.perChild ?? {\n ...(root.resources === undefined\n ? {}\n : {\n resources: Object.fromEntries(\n Object.entries(root.resources).map(([name, resource]) => [\n name,\n { ...resource, limit: Math.floor(resource.limit / fanout) },\n ]),\n ),\n }),\n maxIterations: Math.max(1, Math.floor(root.maxIterations / fanout)),\n maxTokens: Math.max(1, Math.floor(root.maxTokens / fanout)),\n ...(root.maxUsd !== undefined ? { maxUsd: root.maxUsd / fanout } : {}),\n ...(root.deadlineMs !== undefined ? { deadlineMs: root.deadlineMs } : {}),\n }\n return { perChild, fanout }\n}\n\nconst defaultFanout = 3\n\n/**\n * Resolve the persona's executor resolution into a single `ExecutorRegistry`. A pre-built\n * `registry` is used verbatim; otherwise the persona's raw `seams` are wrapped so resolved\n * factories receive an `ExecutorContext` with the persona seams merged in — the supervisor\n * threads an empty bag, so this is the one place the persona seams reach the built-ins.\n */\nfunction personaRegistry<D>(persona: Persona<D>): ExecutorRegistry {\n const { registry, seams } = persona.executors\n // `withDriverExecutor` routes a `role:'driver'` child to the recursive driver-executor\n // (a child that drives its own children) BEFORE the base leaf resolution — so a persona\n // shape can spawn a driver child and the recursion composes. A plain leaf child falls\n // through to the base registry unchanged.\n if (registry) return withDriverExecutor(registry)\n if (!seams) {\n throw new ValidationError(\n `personify: persona \"${persona.name}\" supplies neither a registry nor seams`,\n )\n }\n return withDriverExecutor(withSeams(createExecutorRegistry(), seams))\n}\n\n/**\n * Wrap a registry so every resolved `ExecutorFactory` receives a ctx whose `seams` are\n * the persona seams merged over whatever the scope threaded (the scope threads `{}`, so the\n * persona seams win). A BYO `spec.executor` still resolves to a trivial factory that ignores\n * ctx — so this wrap is transparent for BYO and only matters for the metered built-ins.\n */\nfunction withSeams(\n base: ExecutorRegistry,\n seams: Readonly<Record<string, unknown>>,\n): ExecutorRegistry {\n return {\n register<Out>(runtime: Runtime, factory: ExecutorFactory<Out>): void {\n base.register(runtime, factory)\n },\n resolve<Out>(spec: AgentSpec) {\n const resolved = base.resolve<Out>(spec)\n if (!resolved.succeeded) return resolved\n const inner = resolved.value\n const wrapped: ExecutorFactory<Out> = (s, ctx) => inner(s, mergeSeams(ctx, seams))\n return { succeeded: true, value: wrapped }\n },\n }\n}\n\nfunction mergeSeams(\n ctx: ExecutorContext,\n seams: Readonly<Record<string, unknown>>,\n): ExecutorContext {\n return { signal: ctx.signal, seams: { ...seams, ...ctx.seams } }\n}\n","/**\n *\n * Trajectory trace + cost ledger — the post-hoc tree reconstructor (§4 of `wave-types`).\n *\n * `trajectoryReport` rebuilds the WHOLE realized spawn tree from the durable\n * `SpawnJournal` (+ optionally the `ResultBlobStore` for `done` artifacts): every node\n * (driver AND leaf), the real parent/child edges, each node's terminal status, its OWN\n * conserved `Spend`, and the `Spend` ROLLED UP over its subtree. Roll-up is a post-order\n * fold over the parent edges: a node's `rolledUpSpend` is its own spend plus every\n * descendant's, so a driver is charged for the fanout it caused — the root's roll-up is\n * the whole run's conserved total (tokens + usd + iterations + ms).\n *\n * `equalKOnCost` compares separate runs (arms) on that conserved COST, not on raw\n * iteration COUNT. The sandbox executor reports tokens/usd INCLUSIVE of a leaf's internal\n * sub-agent fanout, so charging an arm by `total.tokens`/`total.usd` (not by how many\n * `next()` cursors it logged) closes the leaf-fanout confound: a treatment leaf that fanned\n * out internally pays for it in cost, where a per-iteration count would hide it. The\n * within-run conserved pool already guarantees `Σk` equal by construction; this check is the\n * CROSS-run analogue the pool cannot reach — proving equal compute before any win is claimed.\n *\n * Pure over the journal/blobs — no live agent calls; safe to run on a finished run's log.\n *\n * @experimental\n */\n\nimport { insideCursorNamespace } from '../../durable/spawn-journal'\nimport type {\n DefaultVerdict,\n NodeId,\n ResultBlobStore,\n SpawnEvent,\n SpawnJournal,\n Spend,\n} from '../supervise/types'\nimport { addSpend, chargedTokens, cloneSpend, zeroSpend } from '../util'\nimport type {\n EqualKArm,\n EqualKOnCostOptions,\n EqualKVerdict,\n TrajectoryNode,\n TrajectoryReport,\n TrajectoryReportOptions,\n} from './wave-types'\n\nconst defaultEqualKTolerance = 0.05\n\n/**\n * Reconstruct the whole spawn tree for `root` with per-node + rolled-up `Spend`. Reads the\n * journal for structure + spend and, when `withOutputs`, the blob store for each `done`\n * node's artifact. Fail loud on a tree that was never journaled, a settle/cancel for an\n * un-spawned node (a corrupted log), or — under `withOutputs` — a `done` node whose blob the\n * store cannot rehydrate (a silent gap would mis-cost or mis-evidence the tree).\n */\nexport async function trajectoryReport(\n journal: SpawnJournal,\n blobs: ResultBlobStore,\n root: NodeId,\n options: TrajectoryReportOptions = {},\n): Promise<TrajectoryReport> {\n const events = await journal.loadTree(root)\n if (events === undefined) {\n throw new Error(`trajectoryReport: no journaled tree for root '${root}'`)\n }\n\n // Spawns (ordinal seq) create the nodes; settlements/cancellations (cursor seq) close\n // them. The two seq namespaces overlap, so create every node from its `spawned` event\n // first, then apply settlements/cancellations — mirrors `materializeTreeView`.\n const spawns = events.filter(isNodeCreation).sort(bySeq)\n // `metered` events (driver inference) are folded onto each node in a separate pass below, so\n // they accumulate ONTO the settled child-work base regardless of seq order; closes are the\n // settlements/cancellations that set node status.\n const closes = events.filter(insideCursorNamespace).sort(bySeq)\n\n const nodes = new Map<NodeId, MutableNode>()\n for (const ev of spawns) {\n nodes.set(ev.id, {\n id: ev.id,\n parent: ev.parent,\n label: ev.label,\n // A wait-state has no executor, so it has no runtime in the executor sense — it is tagged\n // `'wait'` so a reader can separate zero-cost waiting from paid work in the trajectory.\n runtime: ev.kind === 'waiting' ? 'wait' : ev.runtime,\n status: ev.kind === 'waiting' ? 'waiting' : 'pending',\n ownSpend: zeroSpend(),\n children: [],\n })\n }\n for (const ev of closes) {\n const node = requireNode(nodes, ev.id, root)\n if (ev.kind === 'cancelled') {\n node.status = 'cancelled'\n continue\n }\n if (ev.kind === 'woken') {\n // A wait's spend stays zero by construction — it never reserved and never reconciled.\n node.status = ev.by === 'cancelled' ? 'cancelled' : 'done'\n node.outRef = ev.outRef\n continue\n }\n node.status = ev.status === 'done' ? 'done' : 'failed'\n node.ownSpend = cloneSpend(ev.spent)\n node.verdict = ev.verdict\n node.outRef = ev.outRef\n }\n // Driver inference: add each `metered` event onto its node's ownSpend. Because a driver re-homes\n // its nested subtree's inference up the tree, this single tree's events already carry the whole\n // sub-tree's driver cost — so `total` matches `SupervisedResult.spentTotal` directly, with no\n // caller plumbing.\n for (const ev of events) {\n if (ev.kind !== 'metered') continue\n const node = requireNode(nodes, ev.id, root)\n node.ownSpend = addSpend(node.ownSpend, ev.spend)\n }\n\n if (!nodes.has(root)) {\n throw new Error(\n `trajectoryReport: root '${root}' has no spawned event in its journaled tree (corrupted log)`,\n )\n }\n\n // Wire the realized parent/child edges in spawn order, then roll spend up the tree.\n for (const ev of spawns) {\n if (ev.parent === undefined) continue\n requireNode(nodes, ev.parent, root).children.push(ev.id)\n }\n const rolledUp = rollUpSpend(nodes, root)\n\n if (options.withOutputs) {\n await attachOutputs(nodes, blobs)\n }\n\n // Emit in spawn order so the node list reads as the realized tree, root first.\n const ordered = spawns.map((ev) => nodes.get(ev.id)).filter(isNode)\n const reported: TrajectoryNode[] = ordered.map((node) =>\n freezeNode(node, requireSpend(rolledUp, node.id, root)),\n )\n\n return {\n root,\n nodes: reported,\n total: requireSpend(rolledUp, root, root),\n statusCounts: countStatuses(reported),\n }\n}\n\n/**\n * Assert the arms are comparable at EQUAL conserved COST (tokens + usd), NOT raw iteration\n * count. Compares each arm's root-rolled-up `total` on the two conserved channels: an arm is\n * within-tolerance when the per-channel spread (max − min across arms) over the median is\n * `≤ tolerance`. Pure over the reports — no I/O. Fails loud on an empty arm list (nothing to\n * compare) so a vacuous \"equal\" is never returned.\n *\n * The token channel uses `chargedTokens`, the same unit the conserved pool spends, so the cross-run\n * check and the within-run pool cannot disagree about what an arm cost. Charging the rolled-up\n * prompt total instead would rate an arm by how often it re-read a cached prefix: two arms given\n * identical work would read as unequal compute whenever their cache hit rates differed.\n */\nexport function equalKOnCost(\n arms: ReadonlyArray<EqualKArm>,\n options: EqualKOnCostOptions = {},\n): EqualKVerdict {\n if (arms.length === 0) {\n throw new Error('equalKOnCost: no arms to compare')\n }\n const tolerance = options.tolerance ?? defaultEqualKTolerance\n\n const armCosts = arms.map((arm) => ({\n label: arm.label,\n tokens: chargedTokens(arm.report.total.tokens),\n usd: arm.report.total.usd,\n iterations: arm.report.total.iterations,\n }))\n\n const tokenValues = armCosts.map((a) => a.tokens)\n const usdValues = armCosts.map((a) => a.usd)\n const spread = {\n tokens: spreadOf(tokenValues),\n usd: spreadOf(usdValues),\n }\n const withinTolerance =\n fractionalSpread(tokenValues) <= tolerance && fractionalSpread(usdValues) <= tolerance\n\n return {\n withinTolerance,\n arms: armCosts,\n spread,\n tolerance,\n }\n}\n\n// ── Tree fold internals ────────────────────────────────────────────────────────\n\ninterface MutableNode {\n id: NodeId\n parent?: NodeId\n label: string\n runtime: string\n status: TrajectoryNode['status']\n ownSpend: Spend\n children: NodeId[]\n verdict?: DefaultVerdict\n output?: unknown\n outRef?: string\n}\n\n/**\n * Post-order fold: a node's rolled-up spend is its own spend plus every child's rolled-up\n * spend. Iterative (an explicit stack) so a deep tree never overflows the call stack; a node\n * is finalized only after all its children are, so the parent edges are honored exactly.\n */\nfunction rollUpSpend(nodes: Map<NodeId, MutableNode>, root: NodeId): Map<NodeId, Spend> {\n const rolled = new Map<NodeId, Spend>()\n const stack: { id: NodeId; expanded: boolean }[] = [{ id: root, expanded: false }]\n while (stack.length > 0) {\n const frame = stack.pop()\n if (frame === undefined) continue\n const node = requireNode(nodes, frame.id, root)\n if (!frame.expanded) {\n stack.push({ id: frame.id, expanded: true })\n for (const child of node.children) stack.push({ id: child, expanded: false })\n continue\n }\n let sum = cloneSpend(node.ownSpend)\n for (const child of node.children) sum = addSpend(sum, requireSpend(rolled, child, root))\n rolled.set(frame.id, sum)\n }\n return rolled\n}\n\n/**\n * Rehydrate each `done` node's artifact from the blob store. Fail loud on a `done` node whose\n * blob the store cannot resolve — a missing payload under `withOutputs` is a corrupted store,\n * not an absent output (a `down`/`cancelled` node legitimately has none).\n */\nasync function attachOutputs(\n nodes: Map<NodeId, MutableNode>,\n blobs: ResultBlobStore,\n): Promise<void> {\n for (const node of nodes.values()) {\n if (node.status !== 'done' || node.outRef === undefined) continue\n const out = await blobs.get(node.outRef)\n if (out === undefined) {\n throw new Error(\n `trajectoryReport: blob store has no artifact for outRef '${node.outRef}' (node '${node.id}')`,\n )\n }\n node.output = out\n }\n}\n\nfunction freezeNode(node: MutableNode, rolledUpSpend: Spend): TrajectoryNode {\n return {\n id: node.id,\n parent: node.parent,\n children: [...node.children],\n label: node.label,\n runtime: node.runtime,\n status: node.status,\n ownSpend: node.ownSpend,\n rolledUpSpend,\n verdict: node.verdict,\n output: node.output,\n outRef: node.outRef,\n }\n}\n\nfunction countStatuses(\n reported: ReadonlyArray<TrajectoryNode>,\n): Readonly<Record<TrajectoryNode['status'], number>> {\n const counts: Record<TrajectoryNode['status'], number> = {\n done: 0,\n failed: 0,\n cancelled: 0,\n pending: 0,\n waiting: 0,\n }\n for (const node of reported) counts[node.status] += 1\n return counts\n}\n\n// ── Cross-arm spread ─────────────────────────────────────────────────────────────\n\nfunction spreadOf(values: ReadonlyArray<number>): number {\n if (values.length === 0) return 0\n return Math.max(...values) - Math.min(...values)\n}\n\n/**\n * Fractional spread on one channel: `(max − min) / median`. A zero-median channel (every arm\n * spent zero on it) is trivially equal — spread is also zero, so it never trips the tolerance.\n */\nfunction fractionalSpread(values: ReadonlyArray<number>): number {\n const spread = spreadOf(values)\n if (spread === 0) return 0\n const median = medianOf(values)\n if (median === 0) {\n throw new Error(\n 'equalKOnCost: arms have a non-zero cost spread on a zero-median channel; cannot express it as a fraction',\n )\n }\n return spread / median\n}\n\nfunction medianOf(values: ReadonlyArray<number>): number {\n if (values.length === 0) {\n throw new Error('equalKOnCost: cannot take the median of an empty channel')\n }\n const sorted = [...values].sort((a, b) => a - b)\n const mid = Math.floor(sorted.length / 2)\n const hi = sorted[mid] as number\n if (sorted.length % 2 !== 0) return hi\n const lo = sorted[mid - 1] as number\n return (lo + hi) / 2\n}\n\n// ── Guards + narrowers ───────────────────────────────────────────────────────────\n\n/** Node-CREATION events — a spawned child or an armed wait-state. Both mint a node in the\n * ordinal namespace; their settlements (`settled` / `woken`) close them in the cursor namespace. */\nfunction isNodeCreation(\n ev: SpawnEvent,\n): ev is Extract<SpawnEvent, { kind: 'spawned' | 'waiting' }> {\n return ev.kind === 'spawned' || ev.kind === 'waiting'\n}\n\nfunction isNode(node: MutableNode | undefined): node is MutableNode {\n return node !== undefined\n}\n\nfunction bySeq(a: SpawnEvent, b: SpawnEvent): number {\n return a.seq - b.seq\n}\n\nfunction requireNode(nodes: Map<NodeId, MutableNode>, id: NodeId, root: NodeId): MutableNode {\n const node = nodes.get(id)\n if (!node) {\n throw new Error(\n `trajectoryReport: tree '${root}' references node '${id}' with no prior spawn (corrupted log)`,\n )\n }\n return node\n}\n\nfunction requireSpend(rolled: Map<NodeId, Spend>, id: NodeId, root: NodeId): Spend {\n const spend = rolled.get(id)\n if (!spend) {\n throw new Error(\n `trajectoryReport: node '${id}' was never rolled up in tree '${root}' (unreachable from root)`,\n )\n }\n return spend\n}\n","import { createHash, randomUUID } from 'node:crypto'\nimport { constants } from 'node:fs'\nimport { link, lstat, mkdir, open, readdir, rename, unlink } from 'node:fs/promises'\nimport { isAbsolute, join, resolve, sep } from 'node:path'\nimport type { AgentCandidateArtifactRef, Sha256Digest } from '@tangle-network/agent-interface'\nimport type { AgentCandidateOutputArtifactPort } from '../candidate-execution/types'\n\nconst DIGEST = /^sha256:([0-9a-f]{64})$/u\nconst HEX = /^[0-9a-f]{64}$/u\nconst SHARD = /^[0-9a-f]{2}$/u\nconst SAFE_NAMESPACE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/u\nconst RECEIPT_SCHEMA = 'agent-runtime.private-cas-durable-receipt.v1'\nconst DURABLE_ATTEMPTS = 3\n\n/**\n * Off-host storage that holds a private CAS's bytes after the host deletes its local copy.\n * Keys are the run namespace and the content digest, so a retry stores the same object again.\n */\nexport interface PrivateCasDurableStore {\n /** Store a known digest and length without retaining all bytes. */\n putStream?(object: {\n namespace: string\n digest: Sha256Digest\n byteLength: number\n chunks: AsyncIterable<Uint8Array>\n signal?: AbortSignal\n }): Promise<void>\n /** Open stored bytes without materializing the object. */\n getStream?(object: {\n namespace: string\n digest: Sha256Digest\n signal?: AbortSignal\n }): Promise<AsyncIterable<Uint8Array> | undefined>\n\n /** Where the bytes live, recorded in every durable receipt, for example `s3://bucket/prefix/`. */\n readonly location: string\n /**\n * Store exactly these bytes. Resolve only after the store confirms that it holds an object of\n * this digest and length; storing an object that already exists is a success.\n */\n put(object: {\n namespace: string\n digest: Sha256Digest\n bytes: Uint8Array\n signal?: AbortSignal\n }): Promise<void>\n /** The stored bytes, or undefined when the store holds no object for this digest. */\n get(object: {\n namespace: string\n digest: Sha256Digest\n signal?: AbortSignal\n }): Promise<Uint8Array | undefined>\n}\n\nexport interface PrivateCasOptions {\n /** Copy every object off the host as it is written. */\n readonly durable?: PrivateCasDurableStore\n /**\n * Local bytes to keep. Only objects with a durable receipt are deleted, oldest first, so a\n * store outage keeps every byte on the host. Requires `durable`.\n */\n readonly localBudgetBytes?: number\n}\n\n/** One offload pass: what reached the durable store and what the host still holds. */\nexport interface PrivateCasOffloadReport {\n /** Local and evicted objects with a durable receipt after this pass. */\n readonly durable: number\n /** Objects this pass copied to the durable store. */\n readonly uploaded: number\n /** Objects without a durable receipt, including in-progress uploads and store refusals. */\n readonly pending: ReadonlyArray<{ readonly digest: Sha256Digest; readonly error: string }>\n /** Local copies this pass deleted; their bytes remain in the durable store. */\n readonly evicted: number\n readonly localObjects: number\n readonly localBytes: number\n}\n\nexport interface PrivateCasArtifactPort extends AgentCandidateOutputArtifactPort {\n /**\n * Copy every local object that has no durable receipt, then delete the oldest durable local\n * copies above the budget. Without a durable store this only reports local usage. Store\n * refusals are reported, not thrown; local filesystem failures throw.\n */\n offload(signal?: AbortSignal): Promise<PrivateCasOffloadReport>\n}\n\nasync function realDirectory(path: string): Promise<void> {\n const entry = await lstat(path)\n if (!entry.isDirectory() || entry.isSymbolicLink())\n throw new Error(`private CAS directory is not a real directory: ${path}`)\n}\n\nasync function checkDirectories(path: string, create: boolean): Promise<void> {\n const parts = resolve(path).split(sep)\n let current: string = sep\n for (const part of parts) {\n if (!part) continue\n current = join(current, part)\n if (create) {\n try {\n await mkdir(current, { mode: 0o700 })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n }\n }\n await realDirectory(current)\n }\n}\n\nconst missing = (error: unknown): boolean => (error as NodeJS.ErrnoException)?.code === 'ENOENT'\nconst message = (error: unknown): string => (error instanceof Error ? error.message : String(error))\nconst sha256 = (bytes: Uint8Array): Sha256Digest =>\n `sha256:${createHash('sha256').update(bytes).digest('hex')}` as Sha256Digest\n\nasync function syncDirectory(directory: string): Promise<void> {\n const handle = await open(\n directory,\n constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW,\n )\n try {\n await handle.sync()\n } finally {\n await handle.close()\n }\n}\n\n/** Read one local object, or undefined when the host no longer holds it. */\nasync function readLocal(path: string): Promise<Uint8Array | undefined> {\n let file: Awaited<ReturnType<typeof open>>\n try {\n file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)\n } catch (error) {\n if (missing(error)) return undefined\n throw error\n }\n try {\n return await file.readFile()\n } finally {\n await file.close()\n }\n}\n\n/**\n * Private content-addressed storage scoped to one recorded run identity.\n *\n * Bytes are written to the host first. With a durable store, every object is also copied off the\n * host as it is written, and `localBudgetBytes` bounds what the host keeps: an object's local copy\n * is deleted only after its durable receipt exists, and reads fall back to the durable store.\n */\nexport function createPrivateCasArtifactPort(\n root: string,\n namespace: string,\n options: PrivateCasOptions = {},\n): PrivateCasArtifactPort {\n if (!isAbsolute(root)) throw new Error('private CAS root must be absolute')\n if (!SAFE_NAMESPACE.test(namespace) || namespace === '.' || namespace === '..')\n throw new Error('private CAS namespace must be one safe identifier')\n const { durable, localBudgetBytes } = options\n if (\n localBudgetBytes !== undefined &&\n (durable === undefined || !Number.isSafeInteger(localBudgetBytes) || localBudgetBytes < 0)\n )\n throw new Error('private CAS localBudgetBytes needs a durable store and a non-negative integer')\n const store = join(resolve(root), 'sha256')\n const receipts = join(resolve(root), 'durable', 'sha256')\n const hexOf = (digest: string): string => {\n const match = DIGEST.exec(digest)\n if (!match) throw new Error('private CAS digest must be sha256:<64 lowercase hex>')\n return match[1]!\n }\n const destination = (digest: string): string => {\n const hex = hexOf(digest)\n return join(store, hex.slice(0, 2), hex)\n }\n\n const hasReceipt = async (hex: string): Promise<boolean> => {\n try {\n return (await lstat(join(receipts, hex))).isFile()\n } catch (error) {\n if (missing(error)) return false\n throw error\n }\n }\n\n const writeReceipt = async (digest: Sha256Digest, byteLength: number): Promise<void> => {\n await checkDirectories(receipts, true)\n const hex = hexOf(digest)\n const temporary = join(receipts, `.${hex}.${randomUUID()}.tmp`)\n const file = await open(\n temporary,\n constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,\n 0o600,\n )\n try {\n await file.writeFile(\n `${JSON.stringify({ schema: RECEIPT_SCHEMA, location: durable!.location, namespace, digest, byteLength, storedAt: new Date().toISOString() })}\\n`,\n )\n await file.sync()\n } finally {\n await file.close()\n }\n await rename(temporary, join(receipts, hex))\n await syncDirectory(receipts)\n }\n\n // A transient store failure must not leave an object host-only while the next try would succeed.\n const storeDurably = async (digest: Sha256Digest, bytes: Uint8Array, signal?: AbortSignal) => {\n let failure: unknown\n for (let attempt = 1; attempt <= DURABLE_ATTEMPTS; attempt++) {\n signal?.throwIfAborted()\n try {\n await durable!.put({\n namespace,\n digest,\n bytes,\n ...(signal === undefined ? {} : { signal }),\n })\n await writeReceipt(digest, bytes.byteLength)\n return\n } catch (error) {\n failure = error\n if (signal?.aborted) throw error\n if (attempt < DURABLE_ATTEMPTS)\n await new Promise((settle) => setTimeout(settle, 1_000 * 4 ** (attempt - 1)))\n }\n }\n throw failure\n }\n\n const localObjects = async (): Promise<\n Array<{ hex: string; path: string; size: number; modifiedMs: number }>\n > => {\n let shards: string[]\n try {\n shards = await readdir(store)\n } catch (error) {\n if (missing(error)) return []\n throw error\n }\n const objects: Array<{ hex: string; path: string; size: number; modifiedMs: number }> = []\n for (const shard of shards.filter((name) => SHARD.test(name))) {\n for (const hex of await readdir(join(store, shard))) {\n if (!HEX.test(hex) || hex.slice(0, 2) !== shard) continue\n const path = join(store, shard, hex)\n try {\n const entry = await lstat(path)\n if (entry.isFile())\n objects.push({ hex, path, size: entry.size, modifiedMs: entry.mtimeMs })\n } catch (error) {\n if (!missing(error)) throw error\n }\n }\n }\n return objects\n }\n\n // Digests a buffered put has linked and is still copying to the durable store with the bytes it\n // holds. A pass leaves them to that put; copying them again doubles the upload and, for a\n // buffered store, holds a second copy of the same archive in memory.\n const uploading = new Map<string, number>()\n const sweep = async (signal?: AbortSignal): Promise<PrivateCasOffloadReport> => {\n const objects = await localObjects()\n const pending: Array<{ digest: Sha256Digest; error: string }> = []\n let uploaded = 0\n let refusal: string | undefined\n const durableHex = new Set<string>()\n for (const object of objects) {\n if (await hasReceipt(object.hex)) {\n durableHex.add(object.hex)\n continue\n }\n if (durable === undefined) continue\n const digest = `sha256:${object.hex}` as Sha256Digest\n if (uploading.has(object.hex)) {\n pending.push({ digest, error: 'durable upload in progress' })\n continue\n }\n // After one refusal the store is likely down; the next pass retries instead of this one\n // spending its backoff on every remaining object.\n if (refusal !== undefined) {\n pending.push({ digest, error: `not attempted after an earlier refusal: ${refusal}` })\n continue\n }\n try {\n if (durable.putStream && durable.getStream) {\n const ref: AgentCandidateArtifactRef = {\n locator: { kind: 'private-cas', namespace, digest },\n sha256: digest,\n byteLength: object.size,\n }\n let failure: unknown\n for (let attempt = 1; attempt <= DURABLE_ATTEMPTS; attempt++) {\n signal?.throwIfAborted()\n const chunks = readObject(object.path, ref, signal)\n try {\n await durable.putStream({\n namespace,\n digest,\n byteLength: object.size,\n chunks,\n signal,\n })\n await writeReceipt(digest, object.size)\n failure = undefined\n break\n } catch (error) {\n failure = error\n if (signal?.aborted) throw error\n if (attempt < DURABLE_ATTEMPTS)\n await new Promise((settle) => setTimeout(settle, 1_000 * 4 ** (attempt - 1)))\n } finally {\n await chunks.return(undefined)\n }\n }\n if (failure !== undefined) throw failure\n } else {\n const bytes = await readLocal(object.path)\n if (bytes === undefined) continue\n if (sha256(bytes) !== digest) {\n pending.push({\n digest,\n error: 'local object failed digest verification; it stays on the host',\n })\n continue\n }\n await storeDurably(digest, bytes, signal)\n }\n durableHex.add(object.hex)\n uploaded++\n } catch (error) {\n if (signal?.aborted) throw error\n refusal = message(error)\n pending.push({ digest, error: refusal })\n }\n }\n let localBytes = objects.reduce((total, object) => total + object.size, 0)\n let evicted = 0\n if (localBudgetBytes !== undefined) {\n for (const object of [...objects].sort((a, b) => a.modifiedMs - b.modifiedMs)) {\n if (localBytes <= localBudgetBytes) break\n if (!durableHex.has(object.hex) || !(await hasReceipt(object.hex))) continue\n try {\n await unlink(object.path)\n } catch (error) {\n if (!missing(error)) throw error\n }\n localBytes -= object.size\n evicted++\n }\n }\n let receiptCount = 0\n try {\n receiptCount = (await readdir(receipts)).filter((name) => HEX.test(name)).length\n } catch (error) {\n if (!missing(error)) throw error\n }\n return {\n durable: receiptCount,\n uploaded,\n pending,\n evicted,\n localObjects: objects.length - evicted,\n localBytes,\n }\n }\n\n // One pass at a time: a pass never deletes a copy that another pass is still uploading.\n let passes: Promise<unknown> = Promise.resolve()\n const offload = (signal?: AbortSignal): Promise<PrivateCasOffloadReport> => {\n const pass = passes.then(() => sweep(signal))\n passes = pass.catch(() => undefined)\n return pass\n }\n\n const verified = (bytes: Uint8Array, ref: AgentCandidateArtifactRef): Uint8Array => {\n if (sha256(bytes) !== ref.sha256 || bytes.byteLength !== ref.byteLength)\n throw new Error('private CAS object failed digest or length verification')\n return bytes\n }\n\n async function* readStream(\n ref: AgentCandidateArtifactRef,\n options: { signal?: AbortSignal } = {},\n ): AsyncGenerator<Uint8Array> {\n const { signal } = options\n signal?.throwIfAborted()\n if (\n ref.locator.kind !== 'private-cas' ||\n ref.locator.namespace !== namespace ||\n ref.locator.digest !== ref.sha256\n )\n throw new Error('private CAS locator does not match its digest and namespace')\n const path = destination(ref.sha256)\n try {\n await checkDirectories(join(store, hexOf(ref.sha256).slice(0, 2)), false)\n yield* readObject(path, ref, signal)\n return\n } catch (error) {\n if (!missing(error)) throw error\n }\n if (!durable?.getStream)\n throw new Error(\n `private CAS object is not on this host; streaming durable reads are unavailable: ${ref.sha256}`,\n )\n const chunks = await durable.getStream({ namespace, digest: ref.sha256, signal })\n if (!chunks)\n throw new Error(\n `private CAS object is neither on this host nor in ${durable.location}: ${ref.sha256}`,\n )\n yield* checkedChunks(chunks, ref, signal)\n }\n\n async function* readObject(\n path: string,\n ref: AgentCandidateArtifactRef,\n signal?: AbortSignal,\n ): AsyncGenerator<Uint8Array> {\n signal?.throwIfAborted()\n const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)\n try {\n const stats = await file.stat()\n if (!stats.isFile() || stats.size !== ref.byteLength)\n throw new Error('private CAS object failed digest or length verification')\n yield* checkedChunks(\n file.createReadStream({ autoClose: false, highWaterMark: 64 * 1024 }),\n ref,\n signal,\n )\n } finally {\n await file.close()\n }\n }\n\n async function* checkedChunks(\n chunks: AsyncIterable<Uint8Array>,\n ref: AgentCandidateArtifactRef,\n signal?: AbortSignal,\n ): AsyncGenerator<Uint8Array> {\n const hash = createHash('sha256')\n let byteLength = 0\n for await (const chunk of chunks) {\n signal?.throwIfAborted()\n if (!(chunk instanceof Uint8Array)) throw new Error('private CAS emitted a non-byte chunk')\n byteLength += chunk.byteLength\n if (byteLength > ref.byteLength)\n throw new Error('private CAS object failed digest or length verification')\n hash.update(chunk)\n yield chunk\n }\n signal?.throwIfAborted()\n if (`sha256:${hash.digest('hex')}` !== ref.sha256 || byteLength !== ref.byteLength)\n throw new Error('private CAS object failed digest or length verification')\n }\n\n async function putStream(input: {\n chunks: AsyncIterable<Uint8Array>\n signal?: AbortSignal\n }): Promise<AgentCandidateArtifactRef> {\n const { signal } = input\n signal?.throwIfAborted()\n await checkDirectories(store, true)\n const temporary = join(store, `.${randomUUID()}.tmp`)\n try {\n const file = await open(\n temporary,\n constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,\n 0o600,\n )\n const hash = createHash('sha256')\n let byteLength = 0\n try {\n for await (const chunk of input.chunks) {\n signal?.throwIfAborted()\n if (!(chunk instanceof Uint8Array))\n throw new Error('private CAS received a non-byte chunk')\n hash.update(chunk)\n byteLength += chunk.byteLength\n if (!Number.isSafeInteger(byteLength)) throw new Error('private CAS object is too large')\n await file.writeFile(chunk)\n }\n signal?.throwIfAborted()\n await file.sync()\n } finally {\n await file.close()\n }\n const sha = hash.digest('hex')\n const digest = `sha256:${sha}` as AgentCandidateArtifactRef['sha256']\n const ref: AgentCandidateArtifactRef = {\n locator: { kind: 'private-cas', namespace, digest },\n sha256: digest,\n byteLength,\n }\n for await (const _chunk of readObject(temporary, ref, signal)) {\n // Verify the staged inode before it can become another writer's deduplicated object.\n }\n const path = destination(digest)\n const directory = join(store, sha.slice(0, 2))\n await checkDirectories(directory, true)\n signal?.throwIfAborted()\n try {\n // The link commits publication. Later cancellation must not delete a shared CAS object.\n await link(temporary, path)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n for await (const _chunk of readStream(ref, { signal })) {\n // An existing object must independently match, even when our staged bytes were valid.\n }\n }\n const dir = await open(\n directory,\n constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW,\n )\n try {\n await dir.sync()\n } finally {\n await dir.close()\n }\n if (durable !== undefined) await offload(signal)\n return ref\n } finally {\n await unlink(temporary).catch((error: NodeJS.ErrnoException) => {\n if (error.code !== 'ENOENT') throw error\n })\n }\n }\n\n const port: PrivateCasArtifactPort = {\n // A buffered remote store cannot satisfy the streaming capture contract.\n ...(durable === undefined || (durable.putStream && durable.getStream)\n ? { putStream, readStream }\n : {}),\n async put({ bytes, signal }) {\n signal?.throwIfAborted()\n const digest = sha256(bytes)\n const sha = hexOf(digest)\n if (durable !== undefined) uploading.set(sha, (uploading.get(sha) ?? 0) + 1)\n try {\n return await putBuffered(bytes, digest, sha, signal)\n } finally {\n if (durable !== undefined) {\n const count = (uploading.get(sha) ?? 1) - 1\n if (count === 0) uploading.delete(sha)\n else uploading.set(sha, count)\n }\n }\n },\n async read(ref) {\n return readRef(ref)\n },\n offload,\n }\n\n async function putBuffered(\n bytes: Uint8Array,\n digest: Sha256Digest,\n sha: string,\n signal?: AbortSignal,\n ): Promise<AgentCandidateArtifactRef> {\n const path = destination(digest)\n const directory = join(store, sha.slice(0, 2))\n await checkDirectories(directory, true)\n const temporary = join(directory, `.${sha}.${randomUUID()}.tmp`)\n const file = await open(\n temporary,\n constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,\n 0o600,\n )\n try {\n await file.writeFile(bytes)\n await file.sync()\n } finally {\n await file.close()\n }\n try {\n signal?.throwIfAborted()\n try {\n await link(temporary, path)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n }\n await syncDirectory(directory)\n } finally {\n await unlink(temporary).catch(() => undefined)\n }\n const ref: AgentCandidateArtifactRef = {\n locator: { kind: 'private-cas', namespace, digest },\n sha256: digest,\n byteLength: bytes.byteLength,\n }\n await readRef(ref)\n if (durable !== undefined) {\n // The bytes are already in memory, so this put copies them itself; the pass that follows\n // skips this digest and only evicts and retries others.\n if (!(await hasReceipt(sha))) await storeDurably(digest, bytes, signal).catch(() => undefined)\n await offload(signal)\n }\n return ref\n }\n\n async function readRef(ref: AgentCandidateArtifactRef): Promise<Uint8Array> {\n if (\n ref.locator.kind !== 'private-cas' ||\n ref.locator.namespace !== namespace ||\n ref.locator.digest !== ref.sha256\n ) {\n throw new Error('private CAS locator does not match its digest and namespace')\n }\n const path = destination(ref.sha256)\n const shard = join(store, hexOf(ref.sha256).slice(0, 2))\n let local: Uint8Array | undefined\n try {\n await checkDirectories(shard, false)\n local = await readLocal(path)\n } catch (error) {\n if (!missing(error)) throw error\n }\n if (local !== undefined) return verified(local, ref)\n if (durable === undefined)\n throw new Error(`private CAS object is not on this host: ${ref.sha256}`)\n const stored = await durable.get({ namespace, digest: ref.sha256 })\n if (stored === undefined)\n throw new Error(\n `private CAS object is neither on this host nor in ${durable.location}: ${ref.sha256}`,\n )\n return verified(stored, ref)\n }\n return port\n}\n","/**\n * runBenchmark — the packaged optimization suite. Define a domain by implementing an\n * `Environment` (open / tools / call / score / close); get the optimization strategies\n * compared, scored by your own deployable check, with a paired-bootstrap report — free.\n *\n * The mental model: you have a TASK + a deployable CHECK + a compute BUDGET. A strategy\n * is how you spend the budget to beat the check. Two built-ins:\n *\n * sample — N independent attempts, keep the best-verifying one. (best-of-N / resample)\n * refine — attempt → a critic reads the trace → steer the next → repeat. (iterate-with-feedback)\n *\n * Both run at equal budget through the Supervisor's conserved pool; the headline is the\n * paired lift of refine over sample. Author your own strategy with `defineStrategy`.\n */\n\nimport { pairedBootstrap, paretoFrontier } from '@tangle-network/agent-eval'\nimport type { RuntimeHooks } from '../runtime-hooks'\nimport { profileChatClient } from './profile-chat-client'\nimport {\n type AgenticOptions,\n type AgenticSurface,\n type AgenticTask,\n refine,\n runAgentic,\n type Strategy,\n sample,\n} from './strategy'\nimport { armDeadlineTimer } from './supervise/deadline'\nimport { concreteModelId } from './supervise/model-policy'\n\n/** A checkable task domain — implement these 5 hooks and the suite does the rest. The\n * same seam as `AgenticSurface`; `Environment` is the RL/gym-standard name for it. */\nexport type Environment = AgenticSurface\n\nexport interface BenchmarkConfig {\n /** The task domain (5 hooks). */\n environment: Environment\n /** The tasks to score across. */\n tasks: AgenticTask[]\n /** The worker: model + router + (optional) the critic's instruction (the steerer knob). */\n worker: AgenticOptions\n /** Which strategies to compare. Pass the built-ins (`refine`, `sample`) or your own.\n * Default: [sample, refine]. */\n strategies?: Strategy[]\n /** Shots (refine) / width (sample) — the equal compute budget per strategy. Default 3. */\n budget?: number\n /** Tasks scored in parallel. Default 3. */\n concurrency?: number\n /** Progress hook — fires as each task settles (the live-monitoring seam: append to a\n * progress file, render a tree, stream to a dashboard). `done` counts settled tasks. */\n onTask?: (row: BenchmarkTaskRow, done: number, total: number) => void\n /** Lifecycle observability — every spawn/settle of every cell's shots/analysts streams\n * here live (the watchdog/route-auditor seam, passed through to `runAgentic`). */\n hooks?: RuntimeHooks\n /**\n * Model availability check before tasks start.\n *\n * By default, live router workers send one one-token request per unique worker and analyst\n * model. Injected `worker.complete` transports skip the check. Pass `false` to disable it or a\n * callback to check each unique model through a custom transport.\n */\n modelPreflight?:\n | false\n | ((model: string, worker: Readonly<AgenticOptions>, signal: AbortSignal) => Promise<void>)\n /** Maximum time for each model availability check. Default 30 seconds. */\n modelPreflightTimeoutMs?: number\n}\n\nexport interface BenchmarkLift {\n /** Mean of paired deltas (refine − sample). */\n mean: number\n low: number\n high: number\n n: number\n}\n\n/** One strategy's outcome on one task — the per-task cell an optimizer consumes. */\nexport interface BenchmarkCell {\n score: number\n resolved: boolean\n /** The progress curve (refine: score per shot; sample: best-so-far per rollout). */\n progression: number[]\n usd: number\n usdKnown: boolean\n ms: number\n tokens: { input: number; output: number }\n tokensKnown: boolean\n}\n\nexport interface BenchmarkTaskRow {\n taskId: string\n /** Per-strategy cells; absent when the task errored before completing all strategies. */\n cells?: Record<string, BenchmarkCell>\n /** Per-strategy failures on this task: the strategy competed, threw, and scored an\n * honest zero — it loses, it does not poison the row. The message is kept so a later\n * generation's author can see WHY a candidate died. */\n errors?: Record<string, string>\n /** Why the task was excluded (infra/setup failure) — never silently dropped. */\n error?: string\n}\n\nexport interface BenchmarkStrategySummary {\n /** Mean verifier score (0..1). */\n score: number\n /** Fraction of tasks fully resolved. */\n resolved: number\n /** Mean cost vector per task. */\n usd: number\n /** Fraction of task cells whose billed-dollar total was complete. */\n usdKnownRate: number\n ms: number\n}\n\n/** Benchmark output: per-strategy means plus the full per-task × per-strategy losses table an optimizer mines. */\nexport interface BenchmarkReport {\n n: number\n excluded: number\n /** Per-strategy means (keyed by strategy.name). */\n perStrategy: Record<string, BenchmarkStrategySummary>\n /** The full per-task × per-strategy table — the LOSSES an optimizer (GEPA, a\n * strategy-author, an operator) consumes. Includes errored tasks with the reason. */\n perTask: BenchmarkTaskRow[]\n /** The non-dominated strategies on (score ↑, $/task ↓) — collapse-last, per the canon:\n * a strategy that ties on score at half the cost WINS and a scalar would hide it. */\n pareto: string[]\n /** The headline when both `refine` and `sample` ran: paired-bootstrap lift of refine over sample. */\n refineVsSample?: BenchmarkLift\n}\n\n/** Bounded-concurrency map preserving order. */\nasync function pool<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T, i: number) => Promise<R>,\n): Promise<R[]> {\n const out: R[] = new Array(items.length)\n let next = 0\n const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {\n while (next < items.length) {\n const i = next\n next += 1\n out[i] = await fn(items[i] as T, i)\n }\n })\n await Promise.all(workers)\n return out\n}\n\n/** @internal Check each unique worker and analyst model once before any task runs, as\n * `BenchmarkConfig.modelPreflight` describes. `runStrategyEvolution` checks the same way. */\nexport async function preflightModels(\n cfg: Pick<BenchmarkConfig, 'worker' | 'modelPreflight' | 'modelPreflightTimeoutMs'>,\n): Promise<void> {\n if (cfg.modelPreflight === false) return\n if (cfg.worker.complete && !cfg.modelPreflight) return\n\n const profiles = [cfg.worker.workerProfile, cfg.worker.analystProfile ?? cfg.worker.workerProfile]\n const profilesByModel = new Map<string, (typeof profiles)[number]>()\n for (const [index, profile] of profiles.entries()) {\n const model = concreteModelId(profile.model?.default)\n if (!model) {\n throw new Error(\n `Benchmark ${index === 0 ? 'worker' : 'analyst'} AgentProfile.model.default must name an exact model`,\n )\n }\n if (!profilesByModel.has(model)) profilesByModel.set(model, profile)\n }\n const models = [...profilesByModel.keys()]\n const timeoutMs = cfg.modelPreflightTimeoutMs ?? 30_000\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)\n throw new Error('modelPreflightTimeoutMs must be a positive finite number')\n const check =\n cfg.modelPreflight ??\n (async (model: string, worker: Readonly<AgenticOptions>, signal: AbortSignal) => {\n const profile = profilesByModel.get(model)\n if (!profile) throw new Error(`Benchmark preflight has no AgentProfile for model ${model}`)\n await profileChatClient({\n profile,\n context: `runBenchmark model preflight (${model})`,\n executor: {\n backend: 'router',\n routerBaseUrl: worker.routerBaseUrl,\n routerKey: worker.routerKey,\n },\n }).chat({ model, messages: [{ role: 'user', content: 'Reply OK.' }] }, { signal })\n })\n\n const results = await Promise.allSettled(\n models.map(async (model) => {\n const controller = new AbortController()\n let timeoutError: Error | undefined\n let clearTimer: (() => void) | undefined\n try {\n await Promise.race([\n check(model, cfg.worker, controller.signal),\n new Promise<never>((_, reject) => {\n clearTimer = armDeadlineTimer(\n timeoutMs,\n () => {\n timeoutError = new Error(`timed out after ${timeoutMs} ms`)\n controller.abort(timeoutError)\n reject(timeoutError)\n },\n true,\n )\n }),\n ])\n } catch (cause) {\n const reported = timeoutError ?? cause\n const message = reported instanceof Error ? reported.message : String(reported)\n throw new Error(`Benchmark model \"${model}\" preflight failed: ${message}`, {\n cause: reported,\n })\n } finally {\n clearTimer?.()\n }\n }),\n )\n\n const failures = results.flatMap((result) =>\n result.status === 'rejected' ? [result.reason] : [],\n )\n if (failures.length === 1) throw failures[0]\n if (failures.length > 1) {\n const message = failures\n .map((failure) => (failure instanceof Error ? failure.message : String(failure)))\n .join('; ')\n throw new AggregateError(failures, message)\n }\n}\n\n/** Run the requested strategies over the tasks, scored by the Environment's own check.\n * Resilient: a task whose rollouts fail (transient infra) is excluded from the stats but\n * reported in `perTask` with the error — never silently dropped. */\nexport async function runBenchmark(cfg: BenchmarkConfig): Promise<BenchmarkReport> {\n const strategies = cfg.strategies ?? [sample, refine]\n const budget = cfg.budget ?? 3\n const concurrency = cfg.concurrency ?? 3\n\n await preflightModels(cfg)\n\n let settled = 0\n const perTask = await pool(cfg.tasks, concurrency, async (task): Promise<BenchmarkTaskRow> => {\n const cells: Record<string, BenchmarkCell> = {}\n const errors: Record<string, string> = {}\n let row: BenchmarkTaskRow\n try {\n // Per-strategy isolation: one strategy throwing (a broken authored candidate, a\n // hallucinated tool name) must not destroy the other strategies' cells for the\n // task. The thrower scores an honest zero — it competed, it failed, it loses.\n for (const s of strategies) {\n try {\n const r = await runAgentic({\n ...cfg.worker,\n surface: cfg.environment,\n task,\n strategy: s,\n budget,\n ...(cfg.hooks ? { hooks: cfg.hooks } : {}),\n })\n cells[s.name] = {\n score: r.score,\n resolved: r.resolved,\n progression: r.progression,\n usd: r.usd,\n usdKnown: r.usdKnown,\n ms: r.ms,\n tokens: r.tokens,\n tokensKnown: r.tokensKnown,\n }\n } catch (e) {\n errors[s.name] = e instanceof Error ? e.message.slice(0, 300) : String(e)\n // The cell threw, so nothing about its spend was measured. Zeros here are the absence\n // of a reading, not a free cell: mark both channels unknown so a comparison cannot sum\n // them as measured zero.\n cells[s.name] = {\n score: 0,\n resolved: false,\n progression: [],\n usd: 0,\n usdKnown: false,\n ms: 0,\n tokens: { input: 0, output: 0 },\n tokensKnown: false,\n }\n }\n }\n row = {\n taskId: task.id,\n cells,\n ...(Object.keys(errors).length > 0 ? { errors } : {}),\n }\n } catch (e) {\n row = { taskId: task.id, error: e instanceof Error ? e.message.slice(0, 300) : String(e) }\n }\n settled += 1\n cfg.onTask?.(row, settled, cfg.tasks.length)\n return row\n })\n\n const ok = perTask.filter(\n (r): r is BenchmarkTaskRow & { cells: Record<string, BenchmarkCell> } => !!r.cells,\n )\n const mean = (xs: number[]) => (xs.length ? xs.reduce((s, x) => s + x, 0) / xs.length : 0)\n const perStrategy: Record<string, BenchmarkStrategySummary> = {}\n for (const s of strategies) {\n const cells = ok.map((r) => r.cells[s.name]).filter((c): c is BenchmarkCell => !!c)\n perStrategy[s.name] = {\n score: mean(cells.map((c) => c.score)),\n resolved: mean(cells.map((c) => (c.resolved ? 1 : 0))),\n usd: mean(cells.map((c) => c.usd)),\n usdKnownRate: mean(cells.map((c) => (c.usdKnown ? 1 : 0))),\n ms: mean(cells.map((c) => c.ms)),\n }\n }\n\n const frontier = paretoFrontier(\n Object.entries(perStrategy).map(([name, v]) => ({ name, score: v.score, usd: v.usd })),\n [\n { name: 'score', direction: 'maximize', value: (c) => c.score },\n { name: 'usd', direction: 'minimize', value: (c) => c.usd },\n ],\n ).frontier.map((c) => c.name)\n\n const report: BenchmarkReport = {\n n: ok.length,\n excluded: perTask.length - ok.length,\n perStrategy,\n perTask,\n pareto: frontier,\n }\n const names = strategies.map((s) => s.name)\n if (names.includes('refine') && names.includes('sample') && ok.length >= 2) {\n const b = pairedBootstrap(\n ok.map((r) => r.cells.sample?.score ?? 0),\n ok.map((r) => r.cells.refine?.score ?? 0),\n )\n report.refineVsSample = { mean: b.mean, low: b.low, high: b.high, n: b.n }\n }\n return report\n}\n\n/** Pretty-print a report — the \"free optimization\" verdict, with the cost vector. */\nexport function printBenchmarkReport(report: BenchmarkReport): void {\n const pct = (x: number) => `${(x * 100).toFixed(1)}%`\n const pp = (x: number) => `${x >= 0 ? '+' : ''}${(x * 100).toFixed(1)}pp`\n console.log(\n `\\n=== benchmark · n=${report.n}${report.excluded ? ` (excluded ${report.excluded})` : ''} ===`,\n )\n console.log(\n ` ${'strategy'.padEnd(16)} ${'score'.padStart(7)} ${'resolved'.padStart(9)} ${'$/task'.padStart(8)} ${'s/task'.padStart(7)}`,\n )\n for (const [s, v] of Object.entries(report.perStrategy))\n console.log(\n ` ${(report.pareto.includes(s) ? `${s} *` : s).padEnd(16)} ${pct(v.score).padStart(7)} ${pct(v.resolved).padStart(9)} ${`$${v.usd.toFixed(3)}`.padStart(8)} ${(v.ms / 1000).toFixed(0).padStart(6)}s`,\n )\n if (report.pareto.length) console.log(` * = on the (score, $) Pareto frontier`)\n for (const row of report.perTask)\n if (row.error) console.log(` ⚠ ${row.taskId}: ${row.error.slice(0, 120)}`)\n const l = report.refineVsSample\n if (l) {\n const sig = l.low > 0 ? 'SIGNIF +' : l.high < 0 ? 'SIGNIF -' : 'n.s.'\n console.log(` refine − sample: ${pp(l.mean)} CI [${pp(l.low)}, ${pp(l.high)}] (${sig})`)\n }\n}\n","import { createHash, createHmac } from 'node:crypto'\nimport { Readable } from 'node:stream'\nimport type { Sha256Digest } from '@tangle-network/agent-interface'\nimport type { PrivateCasDurableStore } from './private-cas'\n\nconst DIGEST = /^sha256:([0-9a-f]{64})$/u\nconst BUCKET = /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/u\nconst PREFIX = /^(?:[A-Za-z0-9._-]+\\/)*$/u\nconst NAMESPACE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/u\nconst EMPTY_PAYLOAD = createHash('sha256').update('').digest('hex')\nconst CONTENT_TYPE = 'application/octet-stream'\nconst METADATA_DIGEST = 'x-amz-meta-sha256'\n\n/** An S3-compatible bucket (Amazon S3, Cloudflare R2) addressed with path-style requests. */\nexport interface S3PrivateCasStoreOptions {\n /** HTTPS origin of the S3 API, for example `https://<account>.r2.cloudflarestorage.com`. */\n readonly endpoint: string\n readonly bucket: string\n /** Signing region. R2 uses `auto`. */\n readonly region?: string\n readonly accessKeyId: string\n readonly secretAccessKey: string\n /** Key prefix: empty, or path segments that end in `/`. */\n readonly prefix?: string\n /** Minimum time for one request; large bodies get one more second per MiB. */\n readonly timeoutMs?: number\n readonly fetch?: typeof fetch\n}\n\nconst hex = (value: string | Uint8Array): string => createHash('sha256').update(value).digest('hex')\nconst hmac = (key: string | Buffer, value: string): Buffer =>\n createHmac('sha256', key).update(value).digest()\nconst encode = (segment: string): string =>\n encodeURIComponent(segment).replace(\n /[!'()*]/gu,\n (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,\n )\n\n/**\n * Durable private CAS bytes in one S3-compatible bucket under `<prefix><namespace>/sha256/<hex>`.\n *\n * Every write declares its SHA-256 as the signed payload hash, so the store refuses bytes that\n * do not match the digest. A write is confirmed by reading back the object's length and digest\n * metadata. Reads return raw bytes; the private CAS port verifies them.\n */\nexport function createS3PrivateCasStore(options: S3PrivateCasStoreOptions): PrivateCasDurableStore {\n const endpoint = new URL(options.endpoint)\n if (\n endpoint.protocol !== 'https:' ||\n endpoint.username ||\n endpoint.password ||\n endpoint.search ||\n endpoint.hash ||\n (endpoint.pathname !== '/' && endpoint.pathname !== '')\n )\n throw new Error('S3 private CAS endpoint must be a bare https origin')\n if (!BUCKET.test(options.bucket)) throw new Error('S3 private CAS bucket name is invalid')\n const prefix = options.prefix ?? ''\n if (!PREFIX.test(prefix)) throw new Error('S3 private CAS prefix must be empty or end in /')\n if (!options.accessKeyId || !options.secretAccessKey)\n throw new Error('S3 private CAS needs an access key id and secret')\n const region = options.region ?? 'auto'\n const timeoutMs = options.timeoutMs ?? 120_000\n const send = options.fetch ?? fetch\n\n const key = (namespace: string, digest: Sha256Digest): string => {\n if (!NAMESPACE.test(namespace)) throw new Error('S3 private CAS namespace is invalid')\n const match = DIGEST.exec(digest)\n if (!match) throw new Error('S3 private CAS digest must be sha256:<64 lowercase hex>')\n return `${prefix}${namespace}/sha256/${match[1]}`\n }\n\n const request = async (\n method: 'GET' | 'HEAD' | 'PUT',\n objectKey: string,\n {\n body,\n byteLength,\n payloadHash = EMPTY_PAYLOAD,\n headers = {},\n signal,\n }: {\n body?: Uint8Array | ReadableStream<Uint8Array>\n byteLength?: number\n payloadHash?: string\n headers?: Record<string, string>\n signal?: AbortSignal\n } = {},\n ): Promise<Response> => {\n const path = `/${[options.bucket, ...objectKey.split('/')].map(encode).join('/')}`\n const url = new URL(path, endpoint)\n const amzDate = new Date().toISOString().replace(/[:-]|\\.\\d{3}/gu, '')\n const day = amzDate.slice(0, 8)\n const signed: Record<string, string> = {\n host: url.host,\n 'x-amz-content-sha256': payloadHash,\n 'x-amz-date': amzDate,\n ...Object.fromEntries(\n Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]),\n ),\n }\n const names = Object.keys(signed).sort()\n const canonical = [\n method,\n path,\n '',\n names.map((name) => `${name}:${signed[name]!.trim()}\\n`).join(''),\n names.join(';'),\n payloadHash,\n ].join('\\n')\n const scope = `${day}/${region}/s3/aws4_request`\n const signingKey = hmac(\n hmac(hmac(hmac(`AWS4${options.secretAccessKey}`, day), region), 's3'),\n 'aws4_request',\n )\n const signature = createHmac('sha256', signingKey)\n .update(['AWS4-HMAC-SHA256', amzDate, scope, hex(canonical)].join('\\n'))\n .digest('hex')\n const { host: _host, ...sent } = signed\n const deadline = AbortSignal.timeout(\n timeoutMs +\n Math.ceil(\n (byteLength ?? (body instanceof Uint8Array ? body.byteLength : 0)) / (1024 * 1024),\n ) *\n 1_000,\n )\n return await send(url, {\n method,\n headers: {\n ...sent,\n authorization: `AWS4-HMAC-SHA256 Credential=${options.accessKeyId}/${scope}, SignedHeaders=${names.join(';')}, Signature=${signature}`,\n },\n ...(body === undefined ? {} : { body }),\n ...(body instanceof ReadableStream ? { duplex: 'half' as const } : {}),\n signal: signal === undefined ? deadline : AbortSignal.any([signal, deadline]),\n })\n }\n\n const refusal = async (response: Response, action: string): Promise<Error> => {\n const reader = response.body?.getReader()\n let detail = ''\n try {\n while (reader && detail.length < 300) {\n const { done, value } = await reader.read()\n if (done) break\n detail += new TextDecoder().decode(value.subarray(0, 300))\n }\n } catch {\n /* A refused response may close before its diagnostic body arrives. */\n } finally {\n await reader?.cancel().catch(() => undefined)\n }\n detail = detail.replace(/\\s+/gu, ' ').slice(0, 300)\n return new Error(\n `S3 private CAS ${action} returned ${response.status}${detail ? `: ${detail}` : ''}`,\n )\n }\n\n /** Whether the bucket holds this exact object; refuses a same-key object of other bytes. */\n const holds = async (\n objectKey: string,\n digest: Sha256Digest,\n byteLength: number,\n signal?: AbortSignal,\n ) => {\n const response = await request('HEAD', objectKey, signal === undefined ? {} : { signal })\n if (response.status === 404) return false\n if (!response.ok) throw await refusal(response, 'HEAD')\n const length = Number(response.headers.get('content-length'))\n const recorded = response.headers.get(METADATA_DIGEST)\n if (length !== byteLength || (recorded !== null && recorded !== digest))\n throw new Error(`S3 private CAS object ${objectKey} has another length or digest`)\n return recorded === digest\n }\n\n return {\n location: `s3://${options.bucket}/${prefix}`,\n async putStream({ namespace, digest, byteLength, chunks, signal }) {\n const objectKey = key(namespace, digest)\n if (await holds(objectKey, digest, byteLength, signal)) return\n async function* checked(): AsyncGenerator<Uint8Array> {\n const hash = createHash('sha256')\n let total = 0\n for await (const chunk of chunks) {\n signal?.throwIfAborted()\n total += chunk.byteLength\n if (total > byteLength)\n throw new Error('S3 private CAS stream exceeds its declared length')\n hash.update(chunk)\n yield chunk\n }\n if (total !== byteLength || `sha256:${hash.digest('hex')}` !== digest)\n throw new Error('S3 private CAS stream failed digest or length verification')\n }\n const body = Readable.from(checked())\n try {\n const response = await request('PUT', objectKey, {\n body: Readable.toWeb(body) as ReadableStream<Uint8Array>,\n byteLength,\n payloadHash: DIGEST.exec(digest)![1]!,\n headers: {\n 'content-type': CONTENT_TYPE,\n 'content-length': String(byteLength),\n [METADATA_DIGEST]: digest,\n },\n ...(signal === undefined ? {} : { signal }),\n })\n if (!response.ok) throw await refusal(response, 'PUT')\n await response.body?.cancel().catch(() => undefined)\n if (!(await holds(objectKey, digest, byteLength, signal)))\n throw new Error(`S3 private CAS object ${objectKey} is absent after its write`)\n } finally {\n body.destroy()\n }\n },\n async getStream({ namespace, digest, signal }) {\n const response = await request(\n 'GET',\n key(namespace, digest),\n signal === undefined ? {} : { signal },\n )\n if (response.status === 404) {\n await response.body?.cancel().catch(() => undefined)\n return undefined\n }\n if (!response.ok) throw await refusal(response, 'GET')\n if (!response.body) throw new Error('S3 private CAS GET returned no body')\n return (async function* () {\n const reader = response.body!.getReader()\n try {\n while (true) {\n signal?.throwIfAborted()\n const { done, value } = await reader.read()\n if (done) break\n yield value\n }\n } finally {\n await reader.cancel().catch(() => undefined)\n }\n })()\n },\n async put({ namespace, digest, bytes, signal }) {\n const objectKey = key(namespace, digest)\n if (await holds(objectKey, digest, bytes.byteLength, signal)) return\n const response = await request('PUT', objectKey, {\n body: bytes,\n payloadHash: DIGEST.exec(digest)![1]!,\n headers: { 'content-type': CONTENT_TYPE, [METADATA_DIGEST]: digest },\n ...(signal === undefined ? {} : { signal }),\n })\n if (!response.ok) throw await refusal(response, 'PUT')\n await response.body?.cancel().catch(() => undefined)\n if (!(await holds(objectKey, digest, bytes.byteLength, signal)))\n throw new Error(`S3 private CAS object ${objectKey} is absent after its write`)\n },\n async get({ namespace, digest, signal }) {\n const response = await request(\n 'GET',\n key(namespace, digest),\n signal === undefined ? {} : { signal },\n )\n if (response.status === 404) {\n await response.body?.cancel().catch(() => undefined)\n return undefined\n }\n if (!response.ok) throw await refusal(response, 'GET')\n return new Uint8Array(await response.arrayBuffer())\n },\n }\n}\n","/**\n * One bounded-retry read over a sandbox box's filesystem, shared by every caller that reads a\n * path the agent may have just written.\n *\n * The box data plane can transiently 404 a file that exists: the write is not yet flushed, or an\n * edge read lands on a stale view. A first-attempt failure is therefore not evidence of absence,\n * and a caller that treats it as such records a lie — \"the agent produced nothing\" for a\n * deliverable, or \"the agent deleted this surface\" for a mounted profile file.\n *\n * Retries wait `delayMs × attempt` (linear), so the total wait for n attempts is\n * `delayMs × n(n-1)/2`. Set `delayMs` to 0 to retry without waiting (tests).\n */\n\nimport { sleep } from './util'\n\n/** Text read from the box, or the last error after every attempt failed. */\nexport type BoxReadAttemptResult =\n | { succeeded: true; text: string }\n | { succeeded: false; error: unknown }\n\nexport interface BoxReadRetryOptions {\n /** Total read attempts, including the first. Values below 1 are treated as 1. */\n attempts: number\n /** Linear backoff base in ms; the i-th retry waits `delayMs × i`. 0 disables the wait. */\n delayMs: number\n /** Stops the retries once aborted: the pending wait ends and no further attempt is spent on an\n * abandoned run. The last error is still returned, so a caller that must raise its own abort\n * error keeps that authority through `beforeAttempt`. */\n signal?: AbortSignal\n /** Runs before every attempt, carrying the previous attempt's error (`undefined` on the first).\n * Throw from here to abandon the read — the way an aborting caller cancels with an error only\n * it can construct. */\n beforeAttempt?: (lastError: unknown) => void\n}\n\n/** The diagnostic for a failed attempt. `undefined` in, `undefined` out — so a caller can pass the\n * \"no attempt has failed yet\" state through without inventing a message for it. */\nexport function boxReadErrorMessage(error: unknown): string | undefined {\n if (error === undefined) return undefined\n return error instanceof Error ? error.message : String(error)\n}\n\nexport async function readBoxPathWithRetry(\n read: (path: string) => Promise<string>,\n path: string,\n options: BoxReadRetryOptions,\n): Promise<BoxReadAttemptResult> {\n const attempts = Math.max(1, options.attempts)\n let lastError: unknown\n for (let attempt = 1; attempt <= attempts; attempt += 1) {\n options.beforeAttempt?.(lastError)\n // An abandoned run earns no further reads. The guard sits AFTER `beforeAttempt` so a caller\n // that raises its own abort error keeps that authority, and BEFORE the read so an already\n // cancelled run spends nothing.\n if (options.signal?.aborted) {\n lastError ??= new Error(\n `readBoxPathWithRetry: aborted before reading ${JSON.stringify(path)}`,\n )\n break\n }\n try {\n return { succeeded: true, text: await read(path) }\n } catch (err) {\n lastError = err\n if (attempt < attempts && options.delayMs > 0)\n await sleep(options.delayMs * attempt, options.signal)\n }\n }\n return { succeeded: false, error: lastError }\n}\n","/**\n * `openSandboxRun` — the ONE harness-agnostic seam for running an agent in a\n * sandbox over a persistent artifact: run it, stream it, RESUME the same session\n * across turns. Domain-agnostic: a coding agent, a research agent, a tax/legal\n * agent — all flow through this; the domain lives only in the `Deliverable<Out>`\n * the caller supplies, never in a per-domain copy of this function.\n *\n * It is a thin facade (NOT a new layer) over code that already exists and is\n * already hardened:\n * - `acquireSandbox` — cold-start / 502-503-504 / gateway-timeout recovery,\n * - `buildBackendOptions` — the harness IS `backend.type` (opencode / codex /\n * claude-code / kimi-code / hermes / pi); the only \"which agent\" knob,\n * - `createSandboxLineage` — `start` mints a session; `resume` continues the\n * SAME server-side session with a fail-loud `assertSessionLive`.\n *\n * The one genuinely-new piece is {@link Deliverable}: it widens the pure\n * `OutputAdapter.parse(events)` to ALSO admit a post-turn read off the box FS —\n * the structural gap that made the bench gates hand-roll `box.fs.read`, because a\n * large produced file (a git diff, a generated document) truncates in the chat\n * stream and a pure events-parser cannot reach the workspace. Per the SDK, a\n * RELATIVE `deliverable.path` resolves from the workspace root and an ABSOLUTE one\n * (e.g. `/tmp/solution.patch`) reads the container filesystem directly — both are\n * valid; pick the one the agent actually wrote to. Avoid `..` traversal segments.\n *\n * What this deliberately does NOT do (so it stays a facade, not slop): no custom\n * reconnect/replay (the SDK + platform own per-session buffering + `Last-Event-ID`);\n * no fork verb (fanout lives in `runAgentRounds`; `SandboxLineage.fork` keeps\n * live Sandbox branching and the legacy CRIU fallback behind one internal seam).\n * It is also distinct from `runAgentRounds`: `runAgentRounds` is the multi-round, driver-driven\n * kernel (fresh box per round, events deliverable); this is a SINGLE rollout +\n * artifact-or-events deliverable + resume over ONE persistent box.\n */\n\nimport type { PromptOptions, SandboxEvent, SandboxInstance } from '@tangle-network/sandbox'\nimport { type AgentRunOutcome, createAgentRunOutcomeTracker } from '@tangle-network/sandbox/runtime'\nimport type { RuntimeHooks, RuntimeHookTarget } from '../runtime-hooks'\nimport { notifyRuntimeHookEvent } from '../runtime-hooks'\nimport { boxReadErrorMessage, readBoxPathWithRetry } from './box-read-retry'\nimport { readPromptOptions } from './prompt-options'\nimport { probeSandboxCapabilities } from './sandbox-capabilities'\nimport { notifySandboxEventObserver } from './sandbox-events'\nimport { createSandboxLineage, type SandboxLineageHandle } from './sandbox-lineage'\nimport type { AgentRunSpec, SandboxClient } from './types'\nimport { isAbortError, randomSuffix } from './util'\n\n/**\n * How a typed deliverable `Out` is materialized from a finished turn.\n * - `events` — pure parse over the event array (identical to `OutputAdapter`).\n * - `artifact` — read a file off the box AFTER the turn drains, then map it (+ the\n * events). For diffs/codebases/documents that don't fit the chat\n * stream. `path` relative ⇒ workspace root; absolute ⇒ container FS.\n *\n * @experimental\n */\nexport type Deliverable<Out> =\n | { kind: 'events'; fromEvents: (events: SandboxEvent[]) => Out }\n | { kind: 'artifact'; path: string; fromArtifact: (raw: string, events: SandboxEvent[]) => Out }\n\n/**\n * One finished turn over the artifact. A failed FS read is surfaced in `readError`\n * (never masked as an empty deliverable) so a caller distinguishes \"agent produced\n * nothing\" from a transport/FS fault.\n *\n * @experimental\n */\nexport interface TurnResult<Out> {\n out: Out\n events: SandboxEvent[]\n /** Outcome settled by the public Sandbox tracker after the stream drained. */\n outcome: AgentRunOutcome\n readError?: string\n}\n\n/**\n * Thrown when a turn is aborted/timed-out mid-settle. Carries the events drained\n * BEFORE the abort fired (and any in-progress `readError`) so an aborted run is\n * DIAGNOSABLE — the caller can tell never-started (`events: []`) from looped\n * (many events, no terminal `result`) from produced-nothing-then-cancelled.\n *\n * `name === 'AbortError'`, so existing `err.name === 'AbortError'` callers (the\n * loop kernel, scope, supervise runtime) keep matching it unchanged.\n *\n * @experimental\n */\nexport class SandboxRunAbortError extends Error {\n override readonly name = 'AbortError'\n /** Events drained from the stream before the abort interrupted the turn. */\n readonly events: SandboxEvent[]\n /** The last artifact read error, if the abort fired during the retry loop. */\n readonly readError?: string\n constructor(events: SandboxEvent[], readError?: string) {\n super('aborted')\n this.events = events\n if (readError !== undefined) this.readError = readError\n }\n}\n\n/** @experimental A live run over ONE persistent artifact (box + session). Close it\n * when done — `close()` tears the box down. */\nexport interface SandboxRun<Out> {\n readonly box: SandboxInstance\n readonly sessionId: string\n /** First turn over the fresh box (mints the session). Throws if already started. */\n start(prompt: string): Promise<TurnResult<Out>>\n /** Continue THE SAME session over THE SAME artifact — a resumed turn/rollout. */\n resume(prompt: string): Promise<TurnResult<Out>>\n close(): Promise<void>\n}\n\n/** Prompt options forwarded to every sandbox prompt turn in this run. The\n * runtime owns `sessionId` and `signal` so callers cannot accidentally break\n * resume or cancellation semantics while still setting backend-level prompt\n * controls such as `timeoutMs`.\n *\n * @experimental\n */\nexport type OpenSandboxRunPromptOptions = Omit<PromptOptions, 'signal' | 'sessionId'>\n\n/** Context available after the box/session exists and before the first prompt is\n * drained. Intended for benchmark-owned workspace setup such as cloning a repo\n * into a fixed path. */\nexport interface OpenSandboxRunBeforeStartContext {\n readonly box: SandboxInstance\n readonly sessionId: string\n readonly signal: AbortSignal\n}\n\n/** @experimental */\nexport interface OpenSandboxRunOptions {\n /** Profile + sandbox env/overrides. `sandboxOverrides.backend.type` is the harness. */\n agentRun: AgentRunSpec<string>\n signal: AbortSignal\n /** Optional execution-scoped observers. Hook failures never fail the run. */\n hooks?: RuntimeHooks\n /** Stable run id for trace joins. Defaults to a short runtime-minted id. */\n runId?: string\n /** Optional benchmark/scenario id carried into emitted hook events. */\n scenarioId?: string\n /** Per-prompt sandbox SDK options forwarded to both `start()` and `resume()`.\n * The runtime still owns the session id and abort signal for each turn. */\n promptOptions?: OpenSandboxRunPromptOptions\n /** Optional pre-start workspace setup. Runs after `lineage.start()` creates the\n * box/session and before the first prompt stream is consumed. A thrown error\n * fails the turn before the agent spends tokens. */\n beforeStart?: (ctx: OpenSandboxRunBeforeStartContext) => Promise<void> | void\n /** Receives a defensive copy of every streamed event. Observer work is\n * non-blocking; synchronous throws and rejected promises never fail the run. */\n onSandboxEvent?: (\n event: SandboxEvent,\n meta: {\n turnIndex: number\n turnKind: 'start' | 'resume'\n agentRunName: string\n },\n ) => void | PromiseLike<void>\n /** Test seam for deterministic hook timestamps. Defaults to `Date.now`. */\n now?: () => number\n /** Bounds box-creation bursts inside lineage fanout. Default from lineage. */\n maxConcurrency?: number\n /** Base backoff (ms) for retrying a transient artifact `fs.read` failure; the i-th\n * retry waits `readRetryDelayMs * i`. Default 1000. Set 0 to disable the wait (tests). */\n readRetryDelayMs?: number\n}\n\n/**\n * Open a sandbox run. Harness-agnostic: the harness lives in\n * `options.agentRun.sandboxOverrides.backend.type`, so opencode/codex/claude-code/\n * kimi-code all flow through this one entrypoint with identical env/auth wiring.\n *\n * @experimental\n */\nexport async function openSandboxRun<Out>(\n client: SandboxClient,\n options: OpenSandboxRunOptions,\n deliverable: Deliverable<Out>,\n): Promise<SandboxRun<Out>> {\n const runId = options.runId ?? `sandbox-run-${randomSuffix()}`\n const now = options.now ?? Date.now\n const agentRunName = options.agentRun.name ?? options.agentRun.profile.name ?? 'agent'\n // Read once, before the box exists, so the run owns the session id and abort signal this\n // type promises: the Omit does not reject a value that carries them, and an untyped host\n // is not checked at all.\n const promptOptions = readPromptOptions(options.promptOptions, 'openSandboxRun: promptOptions')\n const capabilities = await probeSandboxCapabilities(client)\n const lineage = createSandboxLineage(client, capabilities, {\n ...(options.maxConcurrency !== undefined ? { maxConcurrency: options.maxConcurrency } : {}),\n })\n let handle: SandboxLineageHandle | undefined\n let started = false\n let runStartedAt: number | undefined\n let failed = false\n let turnCount = 0\n\n function emit(event: {\n target: RuntimeHookTarget\n phase: 'before' | 'after' | 'error'\n timestamp: number\n stepIndex?: number\n payload?: Record<string, unknown>\n }): void {\n notifyRuntimeHookEvent(\n options.hooks,\n {\n id: `${runId}:${event.target}:${event.phase}${\n event.stepIndex === undefined ? '' : `:${event.stepIndex}`\n }`,\n runId,\n scenarioId: options.scenarioId,\n target: event.target,\n phase: event.phase,\n timestamp: event.timestamp,\n stepIndex: event.stepIndex,\n payload: event.payload,\n metadata: { producer: 'openSandboxRun' },\n },\n { signal: options.signal },\n )\n }\n\n const runPayload = (): Record<string, unknown> => ({\n agentName: agentRunName,\n profileName: options.agentRun.profile.name,\n backendType: backendType(options.agentRun),\n deliverableKind: deliverable.kind,\n ...(deliverable.kind === 'artifact' ? { deliverablePath: deliverable.path } : {}),\n ...(handle ? { sessionId: handle.sessionId, sandboxId: handle.box.id } : {}),\n })\n\n const turnPayload = (\n prompt: string,\n turnKind: 'start' | 'resume',\n startedAt: number,\n result?: TurnResult<Out>,\n error?: unknown,\n ): Record<string, unknown> => ({\n ...runPayload(),\n turnKind,\n promptChars: prompt.length,\n promptHash: hashText(prompt),\n ...(result !== undefined || error !== undefined\n ? { durationMs: Math.max(0, now() - startedAt) }\n : {}),\n ...(result\n ? {\n eventCount: result.events.length,\n eventTypes: eventTypeCounts(result.events),\n ...(result.readError !== undefined ? { readError: result.readError } : {}),\n }\n : {}),\n ...(error !== undefined ? { error: errorMessage(error) } : {}),\n })\n\n // `box` is passed in (not read from the closed-over `handle`) so the invariant\n // is type-level, not call-order discipline.\n async function settle(\n box: SandboxInstance,\n events: AsyncIterable<SandboxEvent>,\n turnIndex: number,\n turnKind: 'start' | 'resume',\n ): Promise<TurnResult<Out>> {\n const collected: SandboxEvent[] = []\n const outcomeTracker = createAgentRunOutcomeTracker()\n // The stream itself can throw an AbortError when the run is cancelled mid-drain;\n // re-throw it carrying the events drained so far so the partial trace is not lost.\n try {\n for await (const ev of events) {\n collected.push(ev)\n outcomeTracker.observe(ev)\n notifySandboxEventObserver(ev, options.onSandboxEvent, {\n turnIndex,\n turnKind,\n agentRunName,\n })\n }\n } catch (err) {\n if (isAbortError(err)) throw new SandboxRunAbortError(collected)\n throw err\n }\n const outcome = outcomeTracker.finish()\n if (deliverable.kind === 'events') {\n return { out: deliverable.fromEvents(collected), events: collected, outcome }\n }\n if (options.signal.aborted) throw new SandboxRunAbortError(collected)\n // The data plane can transiently 404 a just-written artifact (write not yet\n // flushed, or an edge-read blip) — retry a few times with backoff before\n // declaring the deliverable empty, so a transient read failure is not recorded\n // as \"the agent produced nothing\".\n const attempted = await readBoxPathWithRetry(box.fs.read.bind(box.fs), deliverable.path, {\n attempts: 4,\n delayMs: options.readRetryDelayMs ?? 1000,\n signal: options.signal,\n beforeAttempt: (lastError) => {\n if (options.signal.aborted)\n throw new SandboxRunAbortError(collected, boxReadErrorMessage(lastError))\n },\n })\n const raw = attempted.succeeded ? attempted.text : ''\n const readError = attempted.succeeded ? undefined : boxReadErrorMessage(attempted.error)\n return {\n out: deliverable.fromArtifact(raw, collected),\n events: collected,\n outcome,\n ...(readError !== undefined ? { readError } : {}),\n }\n }\n\n return {\n get box(): SandboxInstance {\n if (!handle) throw new Error('openSandboxRun: box unavailable before start()')\n return handle.box\n },\n get sessionId(): string {\n if (!handle) throw new Error('openSandboxRun: sessionId unavailable before start()')\n return handle.sessionId\n },\n async start(prompt) {\n if (started)\n throw new Error(\n 'openSandboxRun: start() already called — use resume() to continue the session',\n )\n started = true\n runStartedAt = now()\n emit({\n target: 'agent.run',\n phase: 'before',\n timestamp: runStartedAt,\n payload: { ...runPayload(), turnCount: 0 },\n })\n const stepIndex = turnCount\n const turnStartedAt = now()\n emit({\n target: 'agent.turn',\n phase: 'before',\n timestamp: turnStartedAt,\n stepIndex,\n payload: turnPayload(prompt, 'start', turnStartedAt),\n })\n // lineage.start uses only spec.profile + sandboxOverrides (the prompt is passed\n // directly, not via taskToPrompt), so the task type is irrelevant here.\n try {\n const r = await lineage.start(\n options.agentRun as AgentRunSpec<unknown>,\n prompt,\n options.signal,\n promptOptions,\n )\n handle = r.handle\n await options.beforeStart?.({\n box: handle.box,\n sessionId: handle.sessionId,\n signal: options.signal,\n })\n const result = await settle(handle.box, r.events, stepIndex, 'start')\n turnCount += 1\n emit({\n target: 'agent.turn',\n phase: 'after',\n timestamp: now(),\n stepIndex,\n payload: turnPayload(prompt, 'start', turnStartedAt, result),\n })\n return result\n } catch (error) {\n failed = true\n emit({\n target: 'agent.turn',\n phase: 'error',\n timestamp: now(),\n stepIndex,\n payload: turnPayload(prompt, 'start', turnStartedAt, undefined, error),\n })\n emit({\n target: 'agent.run',\n phase: 'error',\n timestamp: now(),\n payload: { ...runPayload(), turnCount, error: errorMessage(error) },\n })\n throw error\n }\n },\n async resume(prompt) {\n if (!handle) throw new Error('openSandboxRun: resume() called before start()')\n const stepIndex = turnCount\n const turnStartedAt = now()\n emit({\n target: 'agent.turn',\n phase: 'before',\n timestamp: turnStartedAt,\n stepIndex,\n payload: turnPayload(prompt, 'resume', turnStartedAt),\n })\n try {\n const result = await settle(\n handle.box,\n await lineage.continue(handle, prompt, options.signal, promptOptions),\n stepIndex,\n 'resume',\n )\n turnCount += 1\n emit({\n target: 'agent.turn',\n phase: 'after',\n timestamp: now(),\n stepIndex,\n payload: turnPayload(prompt, 'resume', turnStartedAt, result),\n })\n return result\n } catch (error) {\n failed = true\n emit({\n target: 'agent.turn',\n phase: 'error',\n timestamp: now(),\n stepIndex,\n payload: turnPayload(prompt, 'resume', turnStartedAt, undefined, error),\n })\n emit({\n target: 'agent.run',\n phase: 'error',\n timestamp: now(),\n payload: { ...runPayload(), turnCount, error: errorMessage(error) },\n })\n throw error\n }\n },\n async close() {\n await lineage.teardown()\n if (runStartedAt !== undefined) {\n emit({\n target: 'agent.run',\n phase: 'after',\n timestamp: now(),\n payload: {\n ...runPayload(),\n turnCount,\n status: failed ? 'error' : 'completed',\n durationMs: Math.max(0, now() - runStartedAt),\n },\n })\n }\n },\n }\n}\n\nfunction backendType<Task>(spec: AgentRunSpec<Task>): unknown {\n const backend = spec.sandboxOverrides?.backend as { type?: unknown } | undefined\n return backend?.type\n}\n\nfunction eventTypeCounts(events: SandboxEvent[]): Record<string, number> {\n const counts: Record<string, number> = {}\n for (const event of events) counts[event.type] = (counts[event.type] ?? 0) + 1\n return counts\n}\n\nfunction hashText(value: string): string {\n let hash = 2166136261\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i)\n hash = Math.imul(hash, 16777619)\n }\n return (hash >>> 0).toString(16).padStart(8, '0')\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","/**\n * The ONE lint over model-authored source.\n *\n * Two features have a model write code the runtime then runs: `authorStrategy` (an authored\n * optimization strategy, since 0.60) and code mode's `execute` (a program over the coordination\n * verbs). Both need the same refusals; this module is the single copy both import.\n *\n * A LINT, NOT A SANDBOX — it reads text and cannot constrain what running code does, and trivial\n * concatenation defeats any token match. Its only job is refusing the obvious escapes so a typo or\n * a lazy model does not run; it is never the security boundary. Isolation, where required, is the\n * execution boundary's job (a jailed runner, a sandboxed loader), never this check's.\n */\nimport { ValidationError } from '../errors'\n\nexport interface AuthoredCodeOptions {\n /** Import specifiers an authored module may name. Empty (the default) bans every import. A\n * specifier admits ANY import form of that module (named, namespace, default) — the lint\n * gates WHICH module, not the syntax used to reach it. */\n readonly allowedImports?: ReadonlyArray<string>\n /** Names the refusal, e.g. `code mode (node-1)`. Defaults to `authored code`. */\n readonly context?: string\n}\n\n/** Refuse the obvious escapes in authored source. See the module doc for what this is NOT. */\nexport function assertAuthoredCode(code: string, options: AuthoredCodeOptions = {}): void {\n const context = options.context ?? 'authored code'\n const allowed = options.allowedImports ?? []\n for (const line of code.split('\\n')) {\n if (!/^\\s*import\\s/.test(line)) continue\n const named = allowed.some(\n (specifier) => line.includes(`'${specifier}'`) || line.includes(`\"${specifier}\"`),\n )\n if (!named) {\n throw new ValidationError(\n `${context} rejected: foreign import — ${line.trim().slice(0, 120)}${\n allowed.length === 0\n ? ' (no import is allowed here)'\n : ` (allowed: ${allowed.join(', ')})`\n }`,\n )\n }\n }\n const banned: ReadonlyArray<readonly [RegExp, string]> = [\n [/\\brequire\\s*\\(/, 'require()'],\n [/\\bimport\\s*\\(/, 'dynamic import()'],\n [/\\beval\\s*\\(/, 'eval()'],\n [/new\\s+Function\\s*\\(/, 'new Function()'],\n [/\\bprocess\\s*[.[]/, 'process access'],\n [/\\bglobalThis\\s*[.[]/, 'globalThis access'],\n [/\\bfetch\\s*\\(/, 'network access'],\n [/child_process|node:fs|node:net|node:http|worker_threads/, 'node builtin access'],\n ]\n for (const [pattern, what] of banned) {\n if (pattern.test(code)) throw new ValidationError(`${context} rejected: ${what}`)\n }\n}\n","/**\n * authorStrategy — the agent-authored layer as a package primitive (software-3.0): an\n * LLM reads a benchmark's per-task LOSSES + the defineStrategy contract and writes a NEW\n * optimization strategy as code; the caller gates it like any human-built candidate\n * (runBenchmark + a frozen holdout).\n *\n * Brokered shot()/critique() calls spend through the Supervisor's conserved pool.\n * Source validation checks obvious forbidden operations; it is not an execution sandbox.\n * Code that uses other execution paths can access state or spend outside that pool.\n * Callers must provide isolation when authored code requires an enforced boundary.\n *\n * The authored module is written to `outDir` and dynamically imported — run under a\n * TS-capable loader (tsx) since models often emit type annotations.\n */\n\nimport { existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { sha256Bytes } from '../candidate-execution/digest'\nimport { strategyAuthorMethod } from '../improvement/optimizer-prompt'\nimport { assertAuthoredCode } from './authored-code'\nimport { profileChatClient } from './profile-chat-client'\nimport type { Strategy } from './strategy'\nimport type { ExecutorConfig } from './supervise/runtime'\n\n/** The compressed consumable a skill carries: everything an author needs to emit a loop. */\nexport const strategyAuthorContract = `\nYou author an OPTIMIZATION STRATEGY for an agentic loop system. A strategy decides how to\nspend a compute budget to beat a task's deployable check. You compose exactly two steps:\n\n shot(spec?: { handle?, messages?, steer?, profile?, tools? }): Promise<ShotResult | null>\n Runs ONE worker attempt (a bounded tool loop) over an artifact.\n - omit handle => the shot opens its OWN fresh artifact and closes it after (a sample).\n - pass handle => the shot CONTINUES that artifact (state accumulates across shots).\n - messages => the carried conversation (pass the previous ShotResult.messages to continue).\n - steer => a corrective instruction injected before the shot.\n - profile => a complete AgentProfile — give THIS shot its own instructions,\n model, skills, tools, hooks, and subagents. Include name, harness, and\n model: { provider, default }; put standing instructions in prompt.systemPrompt.\n For example: { ...opts.workerProfile, name: 'researcher',\n prompt: { ...opts.workerProfile.prompt,\n systemPrompt: 'Inspect the evidence before proposing a change.' } }.\n Choose an available model from the current execution setup. Omit profile to use\n the worker's exact profile. Every shot spends from the same conserved budget.\n - tools => string[] — restrict THIS shot to a subset of the task's tools by\n name (focus an explore shot on read-only tools, an execute shot on write tools).\n Restriction-only; unknown names make the shot fail. ALWAYS select from\n await listTools(handle) — never hardcode. Omitted => the shot sees every tool.\n ShotResult = { messages, score (0..1 on the task's check), passes, total, completions, toolErrors }\n Returns null if the attempt failed infra-wise.\n\n critique(messages): Promise<string | null>\n A firewalled trace-analyst reads the attempt's trajectory and returns ONE corrective\n instruction (or null when it judges the work complete). Costs ~1 completion.\n\n consult(messages, instruction): Promise<string | null>\n The RAW analyst channel: the same firewalled critic answers YOUR instruction over the\n trajectory verbatim (no reformatting) — use it when you need a specific reply format\n (a decision, a prediction). Costs ~1 completion.\n\n surface.open(task) / surface.close(handle)\n Open a persistent artifact you manage yourself (remember to close in a finally).\n close is idempotent — closing an already-closed handle is a safe no-op.\n\n listTools(handle): Promise<Array<{ name, description? }>>\n The tools THIS task actually offers. TOOL SETS VARY PER TASK — if you restrict a\n shot with \\`tools\\`, you MUST pick names from await listTools(handle); hardcoding\n names from an example kills your shots on every task whose tools differ.\n\nRules:\n- ALWAYS await every shot/critique/surface call — a floating promise that rejects\n crashes the whole benchmark run.\n- Stay within ~budget total shots; every shot/critique spends from a conserved pool.\n- For a FRESH attempt OMIT \\`messages\\` entirely (never pass \\`[]\\` — an empty array is a\n fresh conversation too, but be explicit). To CONTINUE, pass the previous\n ShotResult.messages unchanged.\n- Return { score, resolved, completions, progression, shots } — score = the BEST checkpoint\n you reached (keep-best, never final-state), progression = score after each shot.\n- The module must be EXACTLY this shape (no other imports, no commentary outside code):\n\nimport { defineStrategy } from '@tangle-network/agent-runtime/kernel'\nexport default defineStrategy('your-strategy-name', async ({ surface, task, opts, budget, shot, critique, listTools }) => {\n // your composition (listTools comes from the destructured context — it is NOT a global)\n})\n`\n\nexport interface AuthorStrategyOptions {\n /** Exact author identity. Runtime binds it to every authoring turn. */\n profile: AgentProfile\n /** Execution substrate for the author. Behavioral settings are forbidden here. */\n executor: ExecutorConfig\n /** An exact fallback author tried once when the primary call fails or returns no code\n * block (thinking models time out at the edge on long authoring prompts, or return\n * empty content without `maxTokens`). Opt-in — absent means the primary's failure\n * propagates. */\n fallbackProfile?: AgentProfile\n /** The contract text shown to the author. Default `strategyAuthorContract`. The\n * meta-optimization coordinate: a GEPA/skill loop can evolve this text and gate each\n * variant on the same frozen holdout as any strategy. */\n contract?: string\n /** The environment the losses came from (orientation only — never the verifiers). */\n environmentName: string\n /** The per-task losses table (e.g. JSON.stringify(report.perTask)) — the gradient. */\n lossesJson: string\n /** The budget the strategy must respect (shots/width). */\n budget: number\n /** Where the authored module file is written (created if missing). */\n outDir: string\n signal?: AbortSignal\n}\n\n/** Standing behavior callers put in the strategy-author AgentProfile. */\nexport const strategyAuthorSystemPrompt =\n 'You are a senior researcher authoring optimization strategies for agent loops: you read ' +\n 'per-task losses like experimental data, form a mechanism-level hypothesis, and author the ' +\n 'one composition that tests it. Output exactly one fenced ```ts code block and nothing else.'\n\n/** Static CONTRACT lint over an authored strategy module — the module-boundary\n * enforcement of the harness's two measurement invariants:\n * - author blindness: the only import allowed is the kernel surface. A body that could\n * reach the filesystem, network, or process could read or mutate verifier/artifact\n * state outside the brokered shots, and the harness-verified score would stop\n * meaning \"what the shots achieved\".\n * - conserved dose: no out-of-band compute (fetch/require/eval) — every unit a\n * strategy spends is metered by the Supervisor's pool, which is what makes\n * equal-budget comparisons between strategies valid.\n * A lint, not a sandbox: its job is keeping the benchmark numbers interpretable. */\nexport function assertStrategyContract(code: string): void {\n // The shared authored-code lint, with this contract's one allowed import. Marginally looser\n // than the pre-0.169.1 check on purpose: any import FORM of the kernel module passes (the lint\n // gates which module, not the syntax), and the refusal is a ValidationError.\n assertAuthoredCode(code, { allowedImports: ['@tangle-network/agent-runtime/kernel'] })\n}\n\nexport interface AuthoredStrategy {\n strategy: Strategy\n file: string\n code: string\n}\n\n/** One authoring turn: the author's reply and what the call reported spending. */\nexport interface StrategyAuthorTurn {\n content: string\n /** The model the provider reported answering. */\n model: string\n inputTokens: number\n outputTokens: number\n /** False when the call reported no token usage. */\n tokensKnown: boolean\n /** Provider-billed dollars; null when the call reported none. */\n costUsd: number | null\n}\n\n/** What an author wrote: the fenced module, or null when no reply carried one, and every\n * authoring turn that ran (the primary, then the fallback when the primary failed). */\nexport interface StrategySource {\n code: string | null\n turns: StrategyAuthorTurn[]\n}\n\n/** Ask the author for a strategy module. A failed call throws; a reply without a fenced\n * module is `code: null`. With `fallbackProfile`, the fallback gets one attempt when the\n * primary call fails or its reply carries no module. */\nexport async function requestStrategySource(opts: AuthorStrategyOptions): Promise<StrategySource> {\n const turns: StrategyAuthorTurn[] = []\n const attempt = async (profile: AgentProfile): Promise<string | null> => {\n const res = await profileChatClient({\n profile,\n executor: opts.executor,\n context: 'strategy author',\n }).chat(\n {\n messages: [\n {\n role: 'user',\n content: `${opts.contract ?? strategyAuthorContract}\\n\\nBASELINE RESULTS on the \"${opts.environmentName}\" environment (budget=${opts.budget}) — the per-task losses are your gradient:\\n${opts.lossesJson}\\n\\nAuthor ONE new strategy that you expect to beat the baselines on THIS environment at the same budget.\\n${strategyAuthorMethod}\\n\\nOutput only the module code block.`,\n },\n ],\n },\n { ...(opts.signal ? { signal: opts.signal } : {}) },\n )\n turns.push({\n content: res.content,\n model: res.model,\n inputTokens: res.usage.promptTokens,\n outputTokens: res.usage.completionTokens,\n tokensKnown: res.usage.captured !== false,\n costUsd: res.costUsd,\n })\n return res.content.match(/```(?:ts|typescript)?\\s*\\n([\\s\\S]*?)```/)?.[1] ?? null\n }\n try {\n const code = await attempt(opts.profile)\n if (code !== null || !opts.fallbackProfile) return { code, turns }\n } catch (primaryError) {\n if (!opts.fallbackProfile) throw primaryError\n }\n return { code: await attempt(opts.fallbackProfile), turns }\n}\n\n/** Lint an authored module, write it under `outDir` at a name its content fixes, and import\n * its default Strategy. The same source always loads from the same file. Throws when the\n * module breaks the contract or exports no Strategy. */\nexport async function loadAuthoredStrategy(\n code: string,\n outDir: string,\n): Promise<{ strategy: Strategy; file: string }> {\n assertStrategyContract(code)\n const digest = sha256Bytes(Buffer.from(code, 'utf8')).slice('sha256:'.length)\n const file = join(outDir, `strategy-${digest}.mts`)\n if (!existsSync(file)) {\n mkdirSync(outDir, { recursive: true })\n const partial = `${file}.${process.pid}.tmp`\n writeFileSync(partial, code)\n renameSync(partial, file)\n }\n const mod = (await import(pathToFileURL(file).href)) as { default?: Strategy }\n if (!mod.default || typeof mod.default.driver !== 'function' || !mod.default.name) {\n throw new Error(`authorStrategy: ${file} does not export a default Strategy`)\n }\n return { strategy: mod.default, file }\n}\n\n/** Author + load a strategy from losses. Throws when the author emits no loadable module;\n * with `fallbackProfile` set, the fallback gets one attempt first. */\nexport async function authorStrategy(opts: AuthorStrategyOptions): Promise<AuthoredStrategy> {\n const { code, turns } = await requestStrategySource(opts)\n if (code === null) {\n throw new Error(\n `authorStrategy: no code block in the author's reply: ${(turns.at(-1)?.content ?? '').slice(0, 300)}`,\n )\n }\n return { ...(await loadAuthoredStrategy(code, opts.outDir)), code }\n}\n","/**\n * runStrategyEvolution: strategy search on Eval's search kernel (`runSearch`).\n *\n * Every node is a strategy: the caller's root, or a module an author model wrote from the\n * train results of the parent the policy chose. The default policy is `beam({ width: 2 })`\n * and the default allocator `asha()`, so a strategy is screened on a few selection tasks and\n * earns more tasks only by ranking well. Each cell is one `runAgentic` run of one strategy on\n * one task, scored by the environment's own check.\n *\n * Measurement follows the kernel's splits. The author reads train results only; the policy\n * and allocator rank on the private selection split; the claim runs the root and at most 3\n * finalists together on the sealed test split, once, with a power check and a Bonferroni\n * decision. The report is a projection of the ledger, and the ledger is the only checkpoint:\n * calling again with the same inputs continues an interrupted search and returns a finished\n * one without running anything.\n *\n * @experimental\n */\n\nimport { mkdirSync } from 'node:fs'\nimport { gzipSync } from 'node:zlib'\nimport {\n asha,\n beam,\n createRunCostLedger,\n estimateNode,\n fsCampaignStorage,\n type NodeEstimate,\n openSearchLedger,\n renderSearchSummary,\n runSearch,\n type SearchAllocator,\n type SearchArtifactCodec,\n type SearchAttemptAccounting,\n type SearchCellResult,\n type SearchClaim,\n type SearchClaimVerification,\n type SearchCloseReason,\n type SearchExecutionIdentity,\n type SearchNodeStatus,\n type SearchPolicy,\n type SearchProposerPort,\n SearchRecorder,\n type SearchSourceRef,\n type SearchSplit,\n type SearchStateView,\n type SearchTask,\n searchClaimReserveUsd,\n searchModelIdentity,\n surfaceDiff,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n defineEvaluationClaim,\n type EvaluationClaim,\n summarizeEvaluationUnits,\n} from '@tangle-network/agent-eval/experiment'\nimport { redact } from '@tangle-network/agent-eval/traces'\nimport {\n type AgentProfile,\n canonicalAgentProfileDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n canonicalCandidateDigest,\n immutableCandidateValue,\n sha256Bytes,\n} from '../candidate-execution/digest'\nimport { ConfigError } from '../errors'\nimport {\n dedicatedLane,\n reconcileInterruptedSearchCalls,\n searchExecutor,\n} from '../improvement/search-executor'\nimport { runtimeShipDecision } from '../improvement/search-method'\nimport type { RuntimeHooks } from '../runtime-hooks'\nimport { type BenchmarkConfig, type Environment, preflightModels } from './run-benchmark'\nimport {\n type AgenticOptions,\n type AgenticTask,\n refine,\n runAgentic,\n type Strategy,\n} from './strategy'\nimport {\n loadAuthoredStrategy,\n requestStrategySource,\n type StrategyAuthorTurn,\n strategyAuthorContract,\n} from './strategy-author'\nimport { concreteModelId } from './supervise/model-policy'\nimport type { ExecutorConfig } from './supervise/runtime'\nimport type { WorkerSlots } from './supervise/worker-slots'\n\nexport interface EvolutionAuthor {\n /** Exact author identity. */\n profile: AgentProfile\n /** Execution substrate. All behavior comes from the profile. */\n executor: ExecutorConfig\n /** Exact fallback identity, tried once when the primary call fails or writes no module. */\n fallbackProfile?: AgentProfile\n}\n\nexport interface StrategyEvolutionConfig {\n environment: Environment\n /** Tasks the author learns from: it reads every strategy's results on them. */\n train: AgenticTask[]\n /** Private tasks the policy and allocator rank strategies on. The author never sees them. */\n selection: AgenticTask[]\n /** Sealed tasks: the claim runs the root and at most 3 finalists on them, together, once. */\n test: AgenticTask[]\n /** What the numbers may claim. `independentUnit` is a path into each task, for example\n * `id`, or `meta.repo` when tasks from one repository are not independent. The power\n * check needs `minimumEffect`. */\n claim: EvaluationClaim\n /** Digest of what the ledger cannot see: the environment's code and state, the root's\n * code, transports and callbacks. Change it whenever one of them changes. */\n executionRef: Sha256Digest\n worker: AgenticOptions\n author: EvolutionAuthor\n /** The strategy to beat and the tree's root. Default `refine`. */\n root?: Strategy\n /** Rollouts (sample) or shots (refine) per strategy per task. Default 3. */\n budget?: number\n /** Strategies the author writes. Default 4. */\n maxExpansions?: number\n /** Which strategy each authoring extends. Default `beam({ width: 2 })`. */\n policy?: SearchPolicy\n /** Where cells go. Default `asha()`. `uniform()` runs every strategy on every train and\n * selection task. The allocator's `reps` are every split's repeats, the claim's included. */\n allocation?: SearchAllocator\n /** Cells that run at once. Default 3. */\n concurrency?: number\n /** Dollar cap on committed spend plus open holds. Default none. */\n maxUsd?: number\n /** Prior dollar hold for one cell, until 20 cells settle. Default 0. */\n cellUsd?: number\n /** ISO time after which the search stops authoring and claims. */\n deadline?: string\n /** Attempts per cell when the environment faults. Default 3. */\n maxAttempts?: number\n /** Seeds the allocator's task permutation. Default 42. */\n seed?: number\n /** The search's directory is `<outDir>/<searchId>`: its ledger, blobs and authored\n * modules. Authored modules import `@tangle-network/agent-runtime/kernel`, so `outDir`\n * must sit inside a project that resolves it, under a TypeScript-capable loader. */\n outDir: string\n /** Model availability check before the search runs. See `BenchmarkConfig.modelPreflight`. */\n modelPreflight?: BenchmarkConfig['modelPreflight']\n /** Maximum time for each model availability check. Default 30 seconds. */\n modelPreflightTimeoutMs?: BenchmarkConfig['modelPreflightTimeoutMs']\n hooks?: RuntimeHooks\n /** Bound working cells across every search that shares this allocator. */\n workerSlots?: WorkerSlots\n /** Aborting pauses the search once running cells settle; call again to continue. */\n signal?: AbortSignal\n}\n\n/** One strategy the search registered, as the ledger records it. */\nexport interface EvolutionStrategy {\n /** Unique within the report: the strategy's name, suffixed `~<ordinal>` on a collision. */\n name: string\n nodeId: string\n /** The name of the strategy it was authored from; null for the root. */\n parent: string | null\n source: 'root' | 'authored'\n /** The node's latest decision; null while undecided. */\n status: SearchNodeStatus | null\n /** The authored module's source; null for the root. */\n code: string | null\n /** Description length of the authored source in gzip bits; null for the root. */\n gzipBits: number | null\n /** Why admission refused the module; null when admitted. */\n refusal: string | null\n /** Paired contrast against the root on the selection split; null for the root. */\n selection: NodeEstimate | null\n}\n\n/** One strategy on one task at one repeat: the settled cell's final attempt. */\nexport interface TournamentCell {\n /** Null when the cell ended unscored (an environment fault with no attempt left). */\n score: number | null\n outcome: 'passed' | 'failed' | 'errored'\n /** Known dollars plus proven floors of unknown ones. */\n usd: number\n usdKnown: boolean\n}\n\nexport interface TournamentRow {\n taskId: string\n unitId: string\n rep: number\n cells: Record<string, TournamentCell>\n}\n\n/** Every settled cell of one split, by task and strategy. Strategies measured on different\n * tasks have unpaired means; compare them with the paired `selection` estimates. */\nexport interface StrategyTournament {\n split: SearchSplit\n rows: TournamentRow[]\n perStrategy: Record<\n string,\n { cells: number; scored: number; score: number | null; usd: number; usdKnown: boolean }\n >\n}\n\nexport interface EvolutionReport {\n searchId: string\n /** The search ledger: the only record and checkpoint. */\n ledger: string\n closeReason: SearchCloseReason\n /** Root first, in registration order. */\n strategies: EvolutionStrategy[]\n /** The strategy the search keeps: the claim's selection, else the root. */\n selected: EvolutionStrategy\n claim: SearchClaim\n claimVerification: SearchClaimVerification\n /** `ship` only when the claim shipped, re-derives from the ledger, every cost is known, and\n * the shipped finalist's test lower bound is above zero. */\n decision: 'ship' | 'hold'\n reason: string\n tournament: Record<SearchSplit, StrategyTournament>\n /** Known dollars, proven floors of unknown ones, and how many cells and operations (an\n * authoring an interrupted process lost, for example) have an unknown cost. */\n spend: {\n knownUsd: number\n floorUsd: number\n unknownCostCells: number\n unknownCostOperations: number\n }\n}\n\n/** A search node: the caller's root, or an authored module and why admission refused it. */\ntype StrategyNode =\n | { kind: 'root'; name: string }\n | { kind: 'authored'; name: string | null; code: string; refusal: string | null }\n\n/** The rules `runStrategyEvolution` adds to the kernel's; its digest is the process\n * revision every evolution ledger records. */\nconst STRATEGY_EVOLUTION_DEFINITION = {\n name: 'agent-runtime.strategy-evolution.2026-09',\n node: 'the root strategy by name under the caller executionRef, or an authored module content-addressed by the sha256 of its source',\n edge: 'a text diff from the parent module source to the child; unknown from the root, which has no source here',\n admission:\n 'a module is refused when the reply carries none, it breaks the author contract, or it does not load a default Strategy',\n cell: 'one runAgentic run on one task, metered as one paid call on the search cost ledger through the Runtime search executor; an environment fault during it is errored and retried, a thrown strategy is failed at score 0, anything else passed at its harness-verified score',\n proposer:\n 'the author reads the strategy contract, the task tools, the train summary, the train results of every strategy and the parent source',\n ship: 'the claim shipped, re-derives from the ledger, cost accounting is complete, and the shipped finalist test lower bound exceeds 0',\n} as const\n\nconst STRATEGY_EVOLUTION_SOURCE: SearchSourceRef = {\n uri: 'npm:@tangle-network/agent-runtime#runStrategyEvolution',\n revision: canonicalCandidateDigest(STRATEGY_EVOLUTION_DEFINITION),\n}\n\nconst NO_MODULE = 'the author reply carried no fenced ts module'\n\n/** Evolve a strategy on the search kernel and claim once on the sealed test split. */\nexport async function runStrategyEvolution(cfg: StrategyEvolutionConfig): Promise<EvolutionReport> {\n const root = cfg.root ?? refine\n const budget = positiveInteger('budget', cfg.budget ?? 3)\n const concurrency = positiveInteger('concurrency', cfg.concurrency ?? 3)\n const maxExpansions = nonNegativeInteger('maxExpansions', cfg.maxExpansions ?? 4)\n const maxAttempts = positiveInteger('maxAttempts', cfg.maxAttempts ?? 3)\n const seed = nonNegativeInteger('seed', cfg.seed ?? 42)\n const cellUsd = dollars('cellUsd', cfg.cellUsd) ?? 0\n const maxUsd = dollars('maxUsd', cfg.maxUsd)\n const policy = cfg.policy ?? beam({ width: 2 })\n const allocation = cfg.allocation ?? asha()\n if (cfg.deadline !== undefined && !Number.isFinite(Date.parse(cfg.deadline))) {\n throw new ConfigError('evolution: deadline must be an ISO time')\n }\n if (!/^sha256:[0-9a-f]{64}$/.test(cfg.executionRef)) {\n throw new ConfigError('evolution: executionRef must be a lowercase sha256:<64 hex> digest')\n }\n if (!root.name.trim() || typeof root.driver !== 'function') {\n throw new ConfigError('evolution: root must be a named Strategy')\n }\n const claim = defineEvaluationClaim(cfg.claim)\n if (claim.minimumEffect === undefined) {\n throw new ConfigError('evolution: the claim needs minimumEffect for its power check')\n }\n const taskIds = new Set<string>()\n const splitTasks = (label: string, tasks: AgenticTask[]): AgenticTask[] => {\n if (!Array.isArray(tasks) || tasks.length === 0) {\n throw new ConfigError(`evolution: ${label} needs at least one task`)\n }\n for (const task of tasks) {\n if (typeof task.id !== 'string' || !task.id.trim() || taskIds.has(task.id)) {\n throw new ConfigError(`evolution: task IDs must be non-empty and unique across splits`)\n }\n taskIds.add(task.id)\n }\n return immutableCandidateValue(tasks)\n }\n const train = splitTasks('train', cfg.train)\n const selection = splitTasks('selection', cfg.selection)\n const test = splitTasks('test', cfg.test)\n const taskById = new Map([...train, ...selection, ...test].map((task) => [task.id, task]))\n const searchTasks = (tasks: AgenticTask[]): SearchTask[] =>\n tasks.map((task) => ({\n taskId: task.id,\n unitId: summarizeEvaluationUnits(claim, [task]).units[0]!.id,\n source: { uri: `task://${task.id}`, revision: canonicalCandidateDigest(task) },\n }))\n const splits = {\n train: searchTasks(train),\n selection: searchTasks(selection),\n test: searchTasks(test),\n }\n const developmentUnits = new Set(\n [...splits.train, ...splits.selection].map((task) => task.unitId),\n )\n\n const workerProfile = cfg.worker.workerProfile\n const analystProfile = cfg.worker.analystProfile ?? workerProfile\n const workerModel = concreteModelId(workerProfile.model?.default)\n if (!workerModel) {\n throw new ConfigError('evolution: worker AgentProfile.model.default must name an exact model')\n }\n const authorModel = concreteModelId(cfg.author.profile.model?.default)\n if (!authorModel) {\n throw new ConfigError('evolution: author AgentProfile.model.default must name an exact model')\n }\n const workerSource: SearchSourceRef = {\n uri: 'npm:@tangle-network/agent-runtime#runAgentic',\n revision: canonicalCandidateDigest({\n worker: canonicalAgentProfileDigest(workerProfile),\n analyst: canonicalAgentProfileDigest(analystProfile),\n routerBaseUrl: cfg.worker.routerBaseUrl,\n corpusTags: cfg.worker.corpusTags ?? [],\n corpusReadback: cfg.worker.corpusReadback ?? null,\n budget,\n }),\n }\n const authorSource: SearchSourceRef = {\n uri: `agent-profile:${cfg.author.profile.name}`,\n revision: canonicalCandidateDigest({\n profile: canonicalAgentProfileDigest(cfg.author.profile),\n fallback: cfg.author.fallbackProfile\n ? canonicalAgentProfileDigest(cfg.author.fallbackProfile)\n : null,\n backend: cfg.author.executor.backend,\n contract: strategyAuthorContract,\n }),\n }\n const environmentSource: SearchSourceRef = {\n uri: `environment:${cfg.environment.name}`,\n revision: cfg.executionRef,\n }\n const execution: SearchExecutionIdentity = {\n model: searchModelIdentity(workerModel, workerProfile.model?.provider ?? 'unknown'),\n agent: workerSource,\n benchmark: environmentSource,\n }\n const searchKey = canonicalCandidateDigest({\n process: STRATEGY_EVOLUTION_SOURCE,\n executionRef: cfg.executionRef,\n root: root.name,\n worker: workerSource,\n author: authorSource,\n claim,\n splits,\n policy: policy.name,\n allocation: allocation.name,\n reps: allocation.reps,\n maxExpansions,\n concurrency,\n maxUsd,\n cellUsd,\n deadline: cfg.deadline ?? null,\n maxAttempts,\n seed,\n }).slice('sha256:'.length, 'sha256:'.length + 24)\n const searchId = `evolution-${searchKey}`\n const searchDir = `${cfg.outDir}/${searchId}`\n const modulesDir = `${searchDir}/strategies`\n const ledgerPath = `${searchDir}/ledger.jsonl`\n\n mkdirSync(searchDir, { recursive: true })\n const recorder = await SearchRecorder.open(\n { ledger: openSearchLedger({ path: ledgerPath, searchId }) },\n {\n subject: `strategy/${cfg.environment.name}`,\n process: { name: 'strategy-evolution', executionRef: STRATEGY_EVOLUTION_SOURCE },\n artifactKind: 'code',\n objective: { metric: 'score', direction: 'maximize', judge: environmentSource, claim },\n splits: {\n ...splits,\n heldOutUnits: splits.test.every((task) => !developmentUnits.has(task.unitId)),\n },\n policy: { expansion: policy.name, allocation: allocation.name, seed },\n budget: {\n maxUsd,\n maxCells: null,\n maxNodes: 1 + maxExpansions,\n deadline: cfg.deadline === undefined ? null : new Date(cfg.deadline).toISOString(),\n maxConcurrency: concurrency,\n reservedClaimUsd:\n maxUsd === null\n ? 0\n : searchClaimReserveUsd({\n testTasks: splits.test.length,\n reps: allocation.reps,\n cellUsd,\n }),\n },\n containment: null,\n derivedFrom: null,\n identity: execution,\n },\n )\n if (!(await recorder.state()).closed) {\n await preflightModels({\n worker: cfg.worker,\n modelPreflight: cfg.modelPreflight,\n modelPreflightTimeoutMs: cfg.modelPreflightTimeoutMs,\n })\n }\n\n const rootNode: StrategyNode = { kind: 'root', name: root.name }\n const codec: SearchArtifactCodec<StrategyNode> = {\n node(rec, node) {\n const artifact = rec.blob('strategy', { ...node })\n return {\n artifactDigest:\n node.kind === 'root'\n ? canonicalCandidateDigest({ kind: 'root', name: node.name })\n : sha256Bytes(Buffer.from(node.code, 'utf8')),\n artifact,\n surfaces: [{ surfaceId: 'strategy', kind: 'code', artifact }],\n }\n },\n diff(rec, parent, child) {\n if (parent.kind === 'root' || child.kind === 'root') {\n return { unknown: 'the root is a caller-supplied strategy with no source here' }\n }\n return surfaceDiff(rec, parent.code, child.code)\n },\n load(rec, node) {\n const stored = rec.readBlob(node.artifact) as StrategyNode\n if (stored.kind === 'root') {\n if (stored.name !== root.name) {\n throw new Error(\n `evolution: node ${node.nodeId} is root '${stored.name}', not '${root.name}'`,\n )\n }\n return rootNode\n }\n if (stored.kind === 'authored' && typeof stored.code === 'string') return stored\n throw new Error(`evolution: node ${node.nodeId} holds no strategy`)\n },\n }\n\n const loaded = new Map<string, Promise<Strategy>>()\n const strategyOf = (node: StrategyNode): Promise<Strategy> => {\n if (node.kind === 'root') return Promise.resolve(root)\n let strategy = loaded.get(node.code)\n if (!strategy) {\n strategy = loadAuthoredStrategy(node.code, modulesDir).then((module) => module.strategy)\n loaded.set(node.code, strategy)\n }\n return strategy\n }\n\n // Cells run in this process on one dedicated lane of Runtime's search executor, which\n // records each finished attempt under its run id (a restarted search adopts it instead of\n // running it again), meters it through the search's cost ledger, and traces it.\n const storage = fsCampaignStorage()\n const costLedger = createRunCostLedger({ storage, runDir: searchDir })\n const lanes = [dedicatedLane({ name: 'in-process', capacity: concurrency, cellUsd })]\n await reconcileInterruptedSearchCalls(costLedger, searchId, lanes)\n const executor = searchExecutor<StrategyNode>({\n lanes,\n profileOf: () => workerProfile,\n costLedger,\n identity: execution,\n storage,\n dir: searchDir,\n ...(cfg.workerSlots ? { workerSlots: cfg.workerSlots } : {}),\n async runAttempt({ work, lane, costLedger: cellLedger }): Promise<SearchCellResult> {\n if (work.artifact.kind === 'authored' && work.artifact.refusal !== null) {\n throw new Error(`evolution: refused node ${work.nodeId} was given a cell`)\n }\n const strategy = await strategyOf(work.artifact)\n const task = taskById.get(work.taskId)\n if (!task) throw new Error(`evolution: cell ${work.cellId} names unknown task ${work.taskId}`)\n const faults: string[] = []\n const environment = faultRecording(cfg.environment, faults)\n // The whole run is one paid call on the attempt's ledger, so its measured spend is the\n // attempt's accounting, and a run a killed process left pending settles as unknown.\n const paid = await cellLedger.runPaidCall({\n channel: 'agent',\n phase: `search.${work.stage}`,\n actor: `strategy:${strategy.name}`,\n model: workerModel,\n signal: work.signal,\n execute: () =>\n runAgentic({\n ...cfg.worker,\n surface: environment,\n task,\n strategy,\n budget,\n ...(cfg.hooks ? { hooks: cfg.hooks } : {}),\n }),\n receipt: (run) => ({\n model: workerModel,\n inputTokens: run.tokens.input,\n outputTokens: run.tokens.output,\n ...(run.usdKnown ? { actualCostUsd: run.usd } : { costUnknown: true }),\n ...(run.tokensKnown ? {} : { usageUnknown: true }),\n }),\n receiptFromError: () => ({\n model: workerModel,\n inputTokens: 0,\n outputTokens: 0,\n costUnknown: true,\n usageUnknown: true,\n }),\n })\n const settled = {\n identity: execution,\n placement: { lane: lane.name, boxId: null },\n // The executor replaces this with the receipts the ledger holds for the attempt.\n accounting: unknownAccounting('replaced by the attempt receipts'),\n ...(paid.succeeded ? { wallMs: paid.value.ms } : {}),\n }\n if (faults.length > 0) return { ...settled, ...environmentFault(faults) }\n if (!paid.succeeded) {\n return {\n ...settled,\n outcome: {\n status: 'failed',\n score: 0,\n metrics: {},\n failure: { code: 'strategy-threw', message: shareText(paid.error) },\n },\n }\n }\n const run = paid.value\n return {\n ...settled,\n outcome: {\n status: 'passed',\n score: run.score,\n metrics: { resolved: run.resolved ? 1 : 0, shots: run.shots },\n },\n }\n },\n })\n\n let toolCatalog: Promise<string> | undefined\n const catalog = (): Promise<string> => {\n toolCatalog ??= listToolCatalog(cfg.environment, train[0]!)\n return toolCatalog\n }\n const authorProvider = cfg.author.profile.model?.provider ?? 'unknown'\n const proposer: SearchProposerPort<StrategyNode> = {\n name: 'strategy-author',\n kind: 'frontier-author',\n source: authorSource,\n execution: {\n kind: 'model',\n model: searchModelIdentity(authorModel, authorProvider),\n source: authorSource,\n },\n childrenPerProposal: 1,\n async propose(request) {\n // Read the ledger once, synchronously, before any await: the kernel retires a state\n // view when it appends.\n const state = await recorder.state()\n const names = strategyNames(state, recorder, codec)\n const losses = JSON.stringify(\n strategyTournament(state, 'train', names).rows.map((row) => ({\n task: row.taskId,\n ...(row.rep > 0 ? { rep: row.rep } : {}),\n cells: row.cells,\n })),\n ).slice(0, 12_000)\n const summary = renderSearchSummary(state, { split: 'train' })\n const parent = request.parents[0]!\n const parentName = names.get(parent.nodeId) ?? parent.nodeId\n const tried = [...names.values()].join(', ')\n const parentSource =\n parent.artifact.kind === 'authored'\n ? `\\n\\nPARENT STRATEGY \"${parentName}\" (improve on it):\\n${parent.artifact.code}`\n : `\\n\\nPARENT STRATEGY \"${parentName}\" is the built-in baseline; improve on it.`\n const contract = `${strategyAuthorContract}\\n\\nEXAMPLE TOOLS FROM ONE TASK (tool sets VARY per task on this domain — a strategy MUST select tool names from await listTools(handle) at runtime; hardcoding these example names will zero your score on most tasks):\\n${await catalog()}\\n\\nTHE SEARCH SO FAR (train split):\\n${summary}\\n\\nSTRATEGIES ALREADY TRIED (author something MEANINGFULLY different — a new composition, not a rename): ${tried}${parentSource}`\n const source = await requestStrategySource({\n profile: cfg.author.profile,\n executor: cfg.author.executor,\n ...(cfg.author.fallbackProfile ? { fallbackProfile: cfg.author.fallbackProfile } : {}),\n contract,\n environmentName: cfg.environment.name,\n lossesJson: losses,\n budget,\n outDir: modulesDir,\n signal: request.signal,\n })\n let child: StrategyNode = { kind: 'authored', name: null, code: '', refusal: NO_MODULE }\n if (source.code !== null) {\n try {\n const { strategy } = await loadAuthoredStrategy(source.code, modulesDir)\n child = { kind: 'authored', name: strategy.name, code: source.code, refusal: null }\n } catch (error) {\n child = { kind: 'authored', name: null, code: source.code, refusal: shareText(error) }\n }\n }\n const answered = source.turns.at(-1)\n return {\n children: [\n {\n artifact: child,\n label: child.name ?? 'refused module',\n rationale: `authored from the train results of ${parentName} and ${names.size - 1} other strategies`,\n },\n ],\n accounting: authorAccounting(source.turns),\n ...(answered\n ? {\n execution: {\n kind: 'model' as const,\n model: searchModelIdentity(answered.model, authorProvider),\n source: authorSource,\n },\n }\n : {}),\n }\n },\n }\n\n const result = await runSearch({\n recorder,\n root: rootNode,\n codec,\n policy,\n allocation,\n proposer,\n executor,\n admit: (node) => (node.kind === 'authored' ? node.refusal : null),\n maxExpansions,\n maxAttempts,\n ...(cfg.signal ? { signal: cfg.signal } : {}),\n })\n if (!result.claim || !result.claimVerification) {\n throw new Error(`evolution: search ${searchId} closed without a claim`)\n }\n const { state } = result\n const names = strategyNames(state, recorder, codec)\n const rootId = state.rootNodeId!\n const strategies = state.nodes().map((node): EvolutionStrategy => {\n const artifact = codec.load(recorder, node)\n const authored = artifact.kind === 'authored' ? artifact : null\n return {\n name: names.get(node.nodeId)!,\n nodeId: node.nodeId,\n parent: node.primaryParentId === null ? null : names.get(node.primaryParentId)!,\n source: artifact.kind,\n status: node.status,\n code: authored?.code ?? null,\n gzipBits: authored ? gzipSync(Buffer.from(authored.code)).length * 8 : null,\n refusal: authored?.refusal ?? null,\n selection:\n node.nodeId === rootId\n ? null\n : estimateNode(state, node.nodeId, { against: rootId, split: 'selection' }),\n }\n })\n const claimResult = result.claim\n const shipped = claimResult.finalists.find(\n (finalist) => finalist.nodeId === claimResult.selected && finalist.test !== null,\n )\n const { spend } = state.audit\n const { decision, reason } = runtimeShipDecision({\n claim: claimResult,\n verified: result.claimVerification.status === 'verified',\n accountingComplete: spend.unknownCostCells === 0 && spend.unknownCostOperations === 0,\n lowerBound: shipped?.test?.interval[0] ?? null,\n minimumLift: 0,\n })\n return {\n searchId,\n ledger: ledgerPath,\n closeReason: result.reason,\n strategies,\n selected: strategies.find((strategy) => strategy.nodeId === result.leader)!,\n claim: claimResult,\n claimVerification: result.claimVerification,\n decision,\n reason,\n tournament: {\n train: strategyTournament(state, 'train', names),\n selection: strategyTournament(state, 'selection', names),\n test: strategyTournament(state, 'test', names),\n },\n spend: {\n knownUsd: spend.knownUsd,\n floorUsd: spend.floorUsd,\n unknownCostCells: spend.unknownCostCells,\n unknownCostOperations: spend.unknownCostOperations,\n },\n }\n}\n\n/**\n * The tournament on one split, projected from the ledger: each settled cell's final attempt,\n * by task and repeat, keyed by strategy name. `names` maps node ids to report names.\n */\nexport function strategyTournament(\n state: SearchStateView,\n split: SearchSplit,\n names: ReadonlyMap<string, string>,\n): StrategyTournament {\n const rows = new Map<string, TournamentRow>()\n const perStrategy: StrategyTournament['perStrategy'] = {}\n for (const nodeId of state.nodeIds()) {\n const name = names.get(nodeId)\n if (name === undefined) throw new Error(`strategyTournament: node ${nodeId} has no name`)\n perStrategy[name] = { cells: 0, scored: 0, score: null, usd: 0, usdKnown: true }\n }\n const sums = new Map<string, number>()\n const cells = state\n .cells()\n .filter((cell) => cell.split === split && cell.outcome !== null)\n .sort((left, right) => compare(left.taskId, right.taskId) || left.rep - right.rep)\n for (const cell of cells) {\n const name = names.get(cell.nodeId)!\n const key = `${cell.taskId}\\u0000${cell.rep}`\n let row = rows.get(key)\n if (!row) {\n row = { taskId: cell.taskId, unitId: cell.unitId, rep: cell.rep, cells: {} }\n rows.set(key, row)\n }\n const outcome = cell.outcome as TournamentCell['outcome']\n row.cells[name] = { score: cell.score, outcome, usd: cell.spentUsd, usdKnown: cell.costKnown }\n const summary = perStrategy[name]!\n summary.cells += 1\n summary.usd += cell.spentUsd\n summary.usdKnown &&= cell.costKnown\n if (cell.score !== null) {\n summary.scored += 1\n sums.set(name, (sums.get(name) ?? 0) + cell.score)\n }\n }\n for (const [name, summary] of Object.entries(perStrategy)) {\n summary.score = summary.scored === 0 ? null : sums.get(name)! / summary.scored\n }\n return { split, rows: [...rows.values()], perStrategy }\n}\n\n/** Report names: each node's strategy name, suffixed `~<ordinal>` when an earlier node has it. */\nfunction strategyNames(\n state: SearchStateView,\n recorder: SearchRecorder,\n codec: SearchArtifactCodec<StrategyNode>,\n): Map<string, string> {\n const names = new Map<string, string>()\n const taken = new Set<string>()\n for (const node of state.nodes()) {\n const artifact = codec.load(recorder, node)\n const base = artifact.name ?? 'refused-module'\n const name = taken.has(base) ? `${base}~${node.ordinal}` : base\n taken.add(name)\n names.set(node.nodeId, name)\n }\n return names\n}\n\n/** The environment as one attempt sees it, recording each throw from `open`, `tools`,\n * `score` or `close`: those are the environment's faults. A `call` that throws is a tool\n * error the agent's loop handles. */\nfunction faultRecording(environment: Environment, faults: string[]): Environment {\n const recorded =\n <A extends unknown[], R>(name: string, method: (...args: A) => Promise<R>) =>\n async (...args: A): Promise<R> => {\n try {\n return await method(...args)\n } catch (error) {\n faults.push(`${name}: ${shareText(error)}`)\n throw error\n }\n }\n return {\n name: environment.name,\n open: recorded('open', (task) => environment.open(task)),\n tools: recorded('tools', (task, handle) => environment.tools(task, handle)),\n call: (handle, name, args) => environment.call(handle, name, args),\n score: recorded('score', (task, handle) => environment.score(task, handle)),\n close: recorded('close', (handle) => environment.close(handle)),\n }\n}\n\nfunction environmentFault(faults: string[]): Pick<SearchCellResult, 'outcome'> {\n return {\n outcome: {\n status: 'errored',\n metrics: {},\n error: { code: 'environment-fault', message: faults[0]!, retryable: true },\n },\n }\n}\n\nfunction authorAccounting(turns: readonly StrategyAuthorTurn[]): SearchAttemptAccounting {\n let usd = 0\n let costKnown = true\n for (const turn of turns) {\n if (turn.costUsd === null) costKnown = false\n else usd += turn.costUsd\n }\n return {\n tokens: turns.every((turn) => turn.tokensKnown)\n ? {\n status: 'known',\n inputTokens: turns.reduce((sum, turn) => sum + turn.inputTokens, 0),\n outputTokens: turns.reduce((sum, turn) => sum + turn.outputTokens, 0),\n cachedTokens: 0,\n }\n : { status: 'unknown', reason: 'an authoring call reported no token usage' },\n cost: costKnown\n ? { status: 'known', usd, source: usd === 0 ? 'free' : 'provider' }\n : {\n status: 'unknown',\n knownLowerBoundUsd: usd,\n reason: 'an authoring call reported no billed cost',\n },\n }\n}\n\nfunction unknownAccounting(reason: string): SearchAttemptAccounting {\n return {\n tokens: { status: 'unknown', reason },\n cost: { status: 'unknown', knownLowerBoundUsd: 0, reason },\n }\n}\n\n/** One probe round-trip lists the domain's tools so the author can focus shots, names and\n * descriptions only, never the implementations. */\nasync function listToolCatalog(environment: Environment, task: AgenticTask): Promise<string> {\n const handle = await environment.open(task)\n try {\n return (await environment.tools(task, handle))\n .map(\n (tool) =>\n `- ${tool.function.name}${tool.function.description ? ` — ${tool.function.description.slice(0, 120)}` : ''}`,\n )\n .join('\\n')\n } finally {\n await environment.close(handle)\n }\n}\n\n/** Free text as the ledger stores it: redacted with the share profile and bounded. */\nfunction shareText(error: unknown): string {\n const text = error instanceof Error ? error.message : String(error)\n return redact(text, { profile: 'share' }).value.slice(0, 300)\n}\n\nfunction compare(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n\nfunction positiveInteger(name: string, value: number): number {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new ConfigError(`evolution: ${name} must be a positive integer`)\n }\n return value\n}\n\nfunction nonNegativeInteger(name: string, value: number): number {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new ConfigError(`evolution: ${name} must be a non-negative integer`)\n }\n return value\n}\n\nfunction dollars(name: string, value: number | undefined): number | null {\n if (value === undefined) return null\n if (!Number.isFinite(value) || value < 0) {\n throw new ConfigError(`evolution: ${name} must be a finite non-negative number`)\n }\n return value\n}\n","/**\n * A session-owning composition over Runtime's canonical Router tool-loop executor.\n *\n * This module adds conversation persistence for graph-edge `resume` continuity. It does not own\n * model selection, prompts, generation controls, retries, tool policy, or provider accounting:\n * those are lowered from one exact `AgentProfile` by `createExecutor({ backend: 'router-tools' })`.\n *\n * @experimental\n */\n\nimport { type AgentProfile, agentProfileSchema } from '@tangle-network/agent-interface'\nimport { contentAddress } from '../../durable/content-address'\nimport { ValidationError } from '../../errors'\nimport type {\n MakeWorkerAgent,\n WorkerResumeContext,\n WorkerSpawnContext,\n} from '../../mcp/tools/coordination'\nimport type { ToolSpec } from '../router-client'\nimport { type DeliverableSpec, gateOnDeliverable, mapExecutorResult } from './completion-gate'\nimport { assertExecutableAgentProfile } from './model-policy'\nimport { createExecutor, type RouterToolsSeam } from './runtime'\nimport type { Agent, AgentSpec, Executor, ExecutorContext, ExecutorResult } from './types'\n\n/** Buffered OpenAI-compatible completion port used only for offline execution. */\nexport type ChatCompletionsTransport = NonNullable<RouterToolsSeam['complete']>\n\n/** Conversation history keyed by the settled Runtime worker id. */\nexport interface ChatSessionStore {\n load(workerId: string): ReadonlyArray<Readonly<Record<string, unknown>>> | undefined\n save(workerId: string, messages: ReadonlyArray<Readonly<Record<string, unknown>>>): void\n}\n\n/** In-memory, process-local conversation store with detached reads and writes. */\nexport function createChatSessionStore(): ChatSessionStore {\n const sessions = new Map<string, ReadonlyArray<Readonly<Record<string, unknown>>>>()\n return {\n load(workerId) {\n const messages = sessions.get(workerId)\n return messages === undefined\n ? undefined\n : (structuredClone(messages) as ReadonlyArray<Readonly<Record<string, unknown>>>)\n },\n save(workerId, messages) {\n sessions.set(\n workerId,\n structuredClone(messages) as ReadonlyArray<Readonly<Record<string, unknown>>>,\n )\n },\n }\n}\n\n/** One profile-authorized function tool and its host implementation. */\nexport interface ChatTransportTool {\n readonly spec: ToolSpec\n readonly execute: (args: Record<string, unknown>, task: unknown) => Promise<string>\n}\n\n/**\n * Transport and session data for one exact profile-driven conversation.\n * Behavioral controls belong only in `profile.model.metadata`.\n */\nexport interface ChatTransportExecutorOptions {\n readonly profile: AgentProfile\n readonly url?: string\n readonly bearer?: string\n readonly tools?: ReadonlyArray<ChatTransportTool>\n readonly complete?: ChatCompletionsTransport\n readonly sessions?: ChatSessionStore\n readonly sessionKey?: string\n readonly resume?: WorkerResumeContext\n}\n\nfunction exactProfile(profile: AgentProfile, context: string): AgentProfile {\n const parsed = agentProfileSchema.safeParse(profile)\n if (!parsed.success)\n throw new ValidationError(`${context}: invalid AgentProfile: ${parsed.error.message}`)\n assertExecutableAgentProfile(parsed.data, context)\n return parsed.data\n}\n\nfunction initialMessages(\n opts: ChatTransportExecutorOptions,\n): ReadonlyArray<Readonly<Record<string, unknown>>> | undefined {\n if (!opts.resume) return undefined\n if (!opts.sessions) {\n throw new ValidationError(\n \"chat transport: a 'resume' spawn needs the session store holding the prior conversation\",\n )\n }\n const prior = opts.sessions.load(opts.resume.ofWorker)\n if (prior === undefined) {\n throw new ValidationError(\n `chat transport: no recorded conversation for worker '${opts.resume.ofWorker}'`,\n )\n }\n return prior\n}\n\nfunction executorConfig(opts: ChatTransportExecutorOptions): {\n config: { backend: 'router-tools' } & RouterToolsSeam\n profile: AgentProfile\n} {\n const profile = exactProfile(opts.profile, 'chat transport')\n if (!opts.complete && !opts.url) {\n throw new ValidationError('chat transport: url required unless complete is injected')\n }\n const tools = opts.tools ?? []\n for (const tool of tools) {\n if (!tool.spec.function.name || typeof tool.execute !== 'function') {\n throw new ValidationError('chat transport: every tool needs spec.function.name and execute')\n }\n }\n const resumed = initialMessages(opts)\n return {\n profile,\n config: {\n backend: 'router-tools',\n routerBaseUrl: opts.url ?? 'http://injected.invalid',\n routerKey: opts.bearer ?? (opts.complete ? 'injected-transport' : ''),\n tools: tools.map((tool) => tool.spec),\n executeToolCall: async (name, args, task) => {\n const tool = tools.find((candidate) => candidate.spec.function.name === name)\n if (!tool) throw new ValidationError(`chat transport: unknown tool ${JSON.stringify(name)}`)\n return tool.execute(args, task)\n },\n ...(opts.complete ? { complete: opts.complete } : {}),\n ...(resumed ? { initialMessages: resumed } : {}),\n ...(opts.sessions && opts.sessionKey\n ? {\n onMessages: (messages: ReadonlyArray<Readonly<Record<string, unknown>>>) => {\n opts.sessions?.save(opts.sessionKey as string, messages)\n },\n }\n : {}),\n },\n }\n}\n\nfunction buildChatTransportExecutor(\n opts: ChatTransportExecutorOptions,\n context: ExecutorContext,\n): Executor<string> {\n const { config, profile } = executorConfig(opts)\n const spec: AgentSpec = { profile, harness: null }\n const inner = createExecutor(config)(spec, context) as Executor<unknown>\n return mapExecutorResult(inner, (result: ExecutorResult<unknown>) => {\n const raw = result.out as { content?: unknown }\n const content = typeof raw?.content === 'string' ? raw.content : ''\n return {\n outRef: contentAddress({ kind: 'chat-transport', profile, content }),\n out: content,\n ...(result.verdict ? { verdict: result.verdict } : {}),\n }\n })\n}\n\n/**\n * Build one exact profile-driven chat executor through `createExecutor`.\n * Prefer `chatWorkerSeam` for supervised work because it supplies trusted node identity.\n */\nexport function chatTransportExecutor(opts: ChatTransportExecutorOptions): Executor<string> {\n return buildChatTransportExecutor(opts, {\n signal: new AbortController().signal,\n seams: {},\n })\n}\n\n/** Transport/session configuration shared by every spawned exact profile. */\nexport interface ChatWorkerSeamOptions {\n readonly url?: string\n readonly bearer?: string\n readonly tools?: ReadonlyArray<ChatTransportTool>\n readonly complete?: ChatCompletionsTransport\n readonly sessions?: ChatSessionStore\n readonly deliverable?: DeliverableSpec<unknown>\n}\n\n/** Session-owning worker factory for graph continuity. */\nexport function chatWorkerSeam(opts: ChatWorkerSeamOptions): MakeWorkerAgent {\n if (!opts.complete && !opts.url) {\n throw new ValidationError('chatWorkerSeam: url required unless complete is injected')\n }\n const sessions = opts.sessions ?? createChatSessionStore()\n return (rawProfile, spawnContext?: WorkerSpawnContext) => {\n const profile = exactProfile(rawProfile, 'chatWorkerSeam')\n const name = profile.name ?? 'chat-worker'\n const spec: AgentSpec = {\n profile,\n harness: null,\n executorFactory: (executorSpec, context) => {\n const executor = buildChatTransportExecutor(\n {\n profile: executorSpec.profile,\n ...(opts.url ? { url: opts.url } : {}),\n ...(opts.bearer ? { bearer: opts.bearer } : {}),\n ...(opts.tools ? { tools: opts.tools } : {}),\n ...(opts.complete ? { complete: opts.complete } : {}),\n sessions,\n ...(context.node?.nodeId ? { sessionKey: context.node.nodeId } : {}),\n ...(spawnContext?.resume ? { resume: spawnContext.resume } : {}),\n },\n context,\n )\n return opts.deliverable ? gateOnDeliverable(executor, opts.deliverable) : executor\n },\n }\n return { name, act: async () => undefined, executorSpec: spec } as Agent<unknown, unknown> & {\n executorSpec: AgentSpec\n }\n }\n}\n","/**\n * Code mode — the pattern Cloudflare (\"Code Mode\") and Anthropic (\"code execution with MCP\")\n * define, over this runtime's coordination verbs: generate a typed API from the tools' schemas,\n * expose exactly two tools (`search`, `execute`), and run model-written code whose only intended\n * capability is the API bindings. One model turn where the tool-calling loop pays one round trip\n * per call; intermediates live in the program, not the context window.\n *\n * WHAT THIS RUNTIME OWNS AND THE SOURCES' CENTRAL PROPERTY — read this before choosing a runner.\n * The sources isolate execution in a REAL boundary: Cloudflare runs the code in a V8 isolate with\n * a separate heap; Anthropic runs it out of process. That is not a detail — it is the whole reason\n * \"let the model write code\" is safe. This runtime does NOT ship an isolate, so `execute`'s\n * execution boundary is a SEAM you must fill: `codeModeSupervisorTools(runner)` REQUIRES a\n * `CodeModeRunner`, and there is no default. For untrusted model output, supply a jailed runner\n * (a sub-sandbox, a worker isolate). {@link unsafeInProcessRunner} is provided for TRUSTED output\n * only — your own eval harness, an offline test, a model you control — and is named for what it is:\n * `node:vm` shares the host realm, so host code is reachable from inside it and it is not a\n * security boundary. Choosing it for a hostile model is remote code execution, by construction.\n *\n * WHAT IS GENUINELY THIS RUNTIME'S CONTRIBUTION, and survives audit: every call the program makes\n * crosses the IDENTICAL kernel path an MCP verb crosses. Bindings dispatch through `context.verbs`\n * → the live coordination descriptor's own handler → authorization, the conserved pool, the\n * journal (\"there is no second spawn path\"). The model authors a workflow as code at runtime and\n * the kernel still meters and records every edge of it — a dynamic workflow system, not a bypass.\n * Verb RESULTS are detached (JSON round-trip) before they re-enter the program, so in-code calls\n * cannot mutate live coordination state the MCP transport would have copied.\n *\n * WHAT STAYS THE MODEL'S: `submit_result`, `stop`, `ask_parent` are never in the API — a program\n * that could settle the run would be a second brain. `search` names them and says why. Code does\n * the mechanics; the model keeps the judgment, the same split the sources draw.\n *\n * THE GRANT CANNOT DRIFT FROM THE DOCS: `search` renders from `context.coordinationTools()`, the\n * same descriptor objects the verbs are served from — never prose written beside them.\n */\n\nimport { createContext, runInContext } from 'node:vm'\nimport { ValidationError } from '../../errors'\nimport { assertAuthoredCode } from '../authored-code'\nimport { armDeadlineTimer } from './deadline'\nimport type {\n CoordinationToolFace,\n ResolveSupervisorTools,\n SupervisorToolInvocationContext,\n} from './supervisor-agent'\n\n/** The coordination verbs callable in code, and the `context.verbs` member each maps to. */\nconst CODE_CALLABLE_VERBS = {\n spawn_worker: 'spawnAgent',\n await_event: 'awaitEvent',\n steer_agent: 'steerAgent',\n observe_agent: 'observeAgent',\n list_questions: 'listQuestions',\n answer_question: 'answerQuestion',\n run_analyst: 'runAnalyst',\n read_journal: 'readJournal',\n define_analyst: 'defineAnalyst',\n} as const\n\n/** The manager's own lifecycle verbs — never callable from code; `search` names them and why. */\nconst LIFECYCLE_VERBS = ['submit_result', 'stop', 'ask_parent'] as const\n\n// ── JSON Schema → TypeScript, for the generated API ─────────────────────────────\n\n/** Render a JSON Schema as TypeScript type text. Bounded and structural: enough for tool input\n * schemas (objects, enums, arrays, unions); anything unrecognized renders `unknown`, never a\n * guess. Module-level (not root) export: consumed by `renderCodeModeApi` and its tests only. */\nexport function renderJsonSchemaType(schema: unknown, depth = 0): string {\n if (depth > 6 || typeof schema !== 'object' || schema === null) return 'unknown'\n const node = schema as Record<string, unknown>\n if (node.const !== undefined) return JSON.stringify(node.const)\n if (Array.isArray(node.enum)) return node.enum.map((value) => JSON.stringify(value)).join(' | ')\n const variants = (node.anyOf ?? node.oneOf) as unknown[] | undefined\n if (Array.isArray(variants)) {\n return variants.map((variant) => renderJsonSchemaType(variant, depth + 1)).join(' | ')\n }\n const type = Array.isArray(node.type) ? node.type : [node.type]\n if (type.includes('object') || (node.type === undefined && node.properties !== undefined)) {\n const properties = (node.properties ?? {}) as Record<string, unknown>\n const required = new Set(Array.isArray(node.required) ? (node.required as string[]) : [])\n const fields = Object.entries(properties).map(([name, property]) => {\n const doc = describeSchema(property)\n const optional = required.has(name) ? '' : '?'\n return `${doc}${JSON.stringify(name).slice(1, -1)}${optional}: ${renderJsonSchemaType(property, depth + 1)}`\n })\n if (fields.length === 0) return 'Record<string, unknown>'\n const indent = ' '.repeat(depth + 1)\n return `{\\n${fields.map((field) => `${indent}${field}`).join('\\n')}\\n${' '.repeat(depth)}}`\n }\n if (type.includes('array')) {\n return `Array<${renderJsonSchemaType(node.items, depth + 1)}>`\n }\n const primitives = type\n .map((entry) =>\n entry === 'integer' ? 'number' : typeof entry === 'string' ? entry : undefined,\n )\n .filter(\n (entry): entry is string =>\n entry === 'string' || entry === 'number' || entry === 'boolean' || entry === 'null',\n )\n return primitives.length > 0 ? primitives.join(' | ') : 'unknown'\n}\n\nfunction describeSchema(schema: unknown): string {\n const description =\n typeof schema === 'object' && schema !== null\n ? (schema as Record<string, unknown>).description\n : undefined\n if (typeof description !== 'string' || description.length === 0) return ''\n const first = description.split('\\n')[0] ?? ''\n return `/** ${first.length > 140 ? `${first.slice(0, 140)}…` : first} */ `\n}\n\n/** Render the callable API from tool faces — `declare function` per tool, doc from its own\n * description. This is the text `search` answers; generated, never hand-written. Module-level\n * export for tests. */\nexport function renderCodeModeApi(\n tools: ReadonlyArray<CoordinationToolFace>,\n query?: string,\n): string {\n const needle = query?.trim().toLowerCase()\n const matches = tools.filter(\n (tool) =>\n !needle ||\n tool.name.toLowerCase().includes(needle) ||\n (tool.description ?? '').toLowerCase().includes(needle),\n )\n const blocks = matches.map((tool) => {\n const doc = (tool.description ?? '').split('\\n')[0] ?? ''\n const args = tool.inputSchema === undefined ? 'unknown' : renderJsonSchemaType(tool.inputSchema)\n return `/** ${doc} */\\ndeclare function ${tool.name}(args: ${args}): Promise<unknown>`\n })\n const header = [\n '// Call these as `api.<name>(args)` from code passed to `execute`.',\n '// Results are the same JSON the tools return. Intermediates stay in your program;',\n '// return only what the next decision needs.',\n `// NOT callable from code: ${LIFECYCLE_VERBS.join(', ')} — those are your own tools,`,\n '// because a program that could settle the run would be a second brain.',\n ].join('\\n')\n if (blocks.length === 0) {\n return `${header}\\n\\n// No API member matches ${JSON.stringify(query ?? '')}. Call search with no query for the full API.`\n }\n return `${header}\\n\\n${blocks.join('\\n\\n')}`\n}\n\n// ── The execution seam ──────────────────────────────────────────────────────────\n\n/** Where model-written code runs. THE isolation boundary — see the module doc: this runtime ships\n * no default, so a caller chooses trusted-in-process or a real jail deliberately. */\nexport interface CodeModeRunner {\n run(args: {\n readonly code: string\n /** The granted operations, already cancellation-gated and result-detached by the caller. The\n * runner exposes these to the program as `api.<name>` and adds nothing else reachable. */\n readonly bindings: Readonly<Record<string, (args: unknown) => Promise<unknown>>>\n /** Aborts when the manager cancels or a caller-authored deadline passes. */\n readonly signal: AbortSignal\n }): Promise<{ readonly result: unknown; readonly logs: ReadonlyArray<string> }>\n}\n\n/**\n * An in-process runner for TRUSTED model output ONLY. NOT a security boundary.\n *\n * It runs the program in a `node:vm` context whose globals are the bindings (`api`) and a\n * capturing `console`, with code generation disabled and inherited properties stripped. Those are\n * capability discipline, not containment: `node:vm` shares the host realm, and a host function's\n * `.constructor` is the host `Function`, so code that WANTS out can get out\n * (`api.<binding>.constructor('return process')()`). Use this for your own eval harness, offline\n * tests, or a model you trust; for untrusted output supply a jailed `CodeModeRunner` instead.\n */\nexport function unsafeInProcessRunner(): CodeModeRunner {\n return {\n async run({ code, bindings, signal }) {\n const logs: string[] = []\n const capture =\n (level: string) =>\n (...args: unknown[]) => {\n const line = args\n .map((value) => (typeof value === 'string' ? value : safeJson(value)))\n .join(' ')\n if (logs.length < 200) logs.push(level === 'log' ? line : `[${level}] ${line}`)\n }\n // Own-only, null-prototype target: `api.constructor` / `api.toString` do not resolve to\n // inherited host intrinsics. (This closes the api.constructor route; it does NOT make vm a\n // boundary — api.<binding>.constructor still reaches host Function. See the doc.)\n const target = Object.create(null) as Record<string, unknown>\n for (const [name, fn] of Object.entries(bindings)) target[name] = fn\n const sandbox = Object.create(null) as Record<string, unknown>\n sandbox.api = new Proxy(Object.freeze(target), {\n get(owned, member) {\n if (typeof member !== 'string') return undefined\n if (Object.hasOwn(owned, member)) return (owned as Record<string, unknown>)[member]\n const lifecycle = (LIFECYCLE_VERBS as ReadonlyArray<string>).includes(member)\n throw new ValidationError(\n lifecycle\n ? `code mode: api.${member} is not callable from code — it is the manager's own lifecycle verb; return from your program and call it as a tool`\n : `code mode: api.${member} is not in the granted API — call search to see what is`,\n )\n },\n })\n sandbox.console = Object.freeze({\n log: capture('log'),\n warn: capture('warn'),\n error: capture('error'),\n })\n const context = createContext(sandbox, { codeGeneration: { strings: false, wasm: false } })\n const program = runInContext(`(async () => {\\n${code}\\n})()`, context) as Promise<unknown>\n const aborted = new Promise<never>((_resolve, reject) => {\n if (signal.aborted) reject(abortReason(signal))\n else signal.addEventListener('abort', () => reject(abortReason(signal)), { once: true })\n })\n const result = await Promise.race([program, aborted])\n return { result: result ?? null, logs }\n },\n }\n}\n\nfunction abortReason(signal: AbortSignal): Error {\n const reason = signal.reason\n return reason instanceof Error ? reason : new ValidationError('code mode: program aborted')\n}\n\nfunction safeJson(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n\n/** Detach a verb result before it re-enters the program — the deep copy the MCP transport makes,\n * so in-code calls cannot mutate live coordination state. Matches the MCP path exactly (both\n * JSON round-trip); a non-serializable result degrades to a marker rather than leaking a live\n * reference. */\nfunction detach(value: unknown): unknown {\n if (value === undefined) return undefined\n try {\n return JSON.parse(JSON.stringify(value))\n } catch {\n return { nonSerializable: true }\n }\n}\n\n// ── The two tools ───────────────────────────────────────────────────────────────\n\nexport interface CodeModeOptions {\n /** Optional caller-authored deadline for one `execute` call. Omit it to run until the manager\n * cancels. A declared deadline aborts the runner and refuses later `api` calls. */\n readonly timeoutMs?: number | null\n}\n\n/**\n * Put a supervisor in code mode: its product tool surface becomes exactly `search` and `execute`.\n *\n * `runner` is REQUIRED and has no default — this runtime ships no isolate, so the execution\n * boundary is the caller's explicit choice (see the module doc). Use {@link unsafeInProcessRunner}\n * for trusted output; a jailed runner for untrusted models.\n *\n * Pass the result as `SuperviseOptions.resolveSupervisorTools` (which `runGraph` forwards to its\n * root supervisor). The graph engine's `supervisorKind` does not accept it yet, so a graph\n * supervisor node cannot be put in code mode through node config today.\n */\nexport function codeModeSupervisorTools(\n runner: CodeModeRunner,\n options: CodeModeOptions = {},\n): ResolveSupervisorTools {\n if (runner === undefined || typeof runner.run !== 'function') {\n throw new ValidationError(\n 'codeModeSupervisorTools: a CodeModeRunner is required (no default) — pass unsafeInProcessRunner() for trusted output, or a jailed runner for untrusted models',\n )\n }\n const timeoutMs = options.timeoutMs ?? null\n if (timeoutMs !== null && (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0)) {\n throw new ValidationError(\n 'codeModeSupervisorTools: timeoutMs must be a positive safe integer or null',\n )\n }\n\n const faces = (context: SupervisorToolInvocationContext): ReadonlyArray<CoordinationToolFace> =>\n context\n .coordinationTools()\n .filter((tool) => (CODE_CALLABLE_VERBS as Record<string, unknown>)[tool.name] !== undefined)\n\n return () => [\n {\n name: 'search',\n description:\n 'Search the callable API. Returns TypeScript declarations for the operations your code ' +\n 'may call, generated from the live grant. Optional `query` filters by name or ' +\n 'description; omit it for the full API.',\n inputSchema: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Substring filter over names and descriptions.' },\n },\n },\n handler: async (raw, context) => {\n const query =\n typeof raw === 'object' && raw !== null ? (raw as { query?: unknown }).query : undefined\n return renderCodeModeApi(faces(context), typeof query === 'string' ? query : undefined)\n },\n },\n {\n name: 'execute',\n description:\n 'Run JavaScript against the API from `search`. Write the BODY of an async function: ' +\n 'call `api.<name>(args)` (await each call), use loops and Promise.all for fan-out, keep ' +\n 'intermediates in variables, `return` only what the next decision needs. `console.log` ' +\n 'lines come back beside the result. No imports, no network, no filesystem — the API is ' +\n 'the intended capability.',\n inputSchema: {\n type: 'object',\n properties: { code: { type: 'string', description: 'The async function body to run.' } },\n required: ['code'],\n },\n handler: async (raw, context) => {\n const code =\n typeof raw === 'object' && raw !== null ? (raw as { code?: unknown }).code : undefined\n if (typeof code !== 'string' || code.trim().length === 0) {\n throw new ValidationError('code mode: execute needs { code: string }')\n }\n // A lint, never the boundary: it refuses obvious escapes so a typo does not run, but the\n // runner is what isolates. See the module doc.\n assertAuthoredCode(code, { context: `code mode (${context.nodeId})` })\n\n // Link execution to the manager's cancellation signal. Add a timer only when the caller\n // declared one. After either signal fires, every binding fails closed.\n const execution = new AbortController()\n let timedOut = false\n const onScopeAbort = () => execution.abort(abortReason(context.signal))\n const clearTimer =\n timeoutMs === null\n ? undefined\n : armDeadlineTimer(\n timeoutMs,\n () => {\n if (!execution.signal.aborted) {\n timedOut = true\n execution.abort(\n new ValidationError(`code mode: program timed out after ${timeoutMs}ms`),\n )\n }\n },\n true,\n )\n if (context.signal.aborted) execution.abort(abortReason(context.signal))\n else context.signal.addEventListener('abort', onScopeAbort, { once: true })\n\n const bindings: Record<string, (args: unknown) => Promise<unknown>> = {}\n for (const face of faces(context)) {\n const member = CODE_CALLABLE_VERBS[face.name as keyof typeof CODE_CALLABLE_VERBS]\n if (member === undefined) continue\n bindings[face.name] = async (args: unknown) => {\n if (execution.signal.aborted) {\n if (!timedOut) throw abortReason(execution.signal)\n throw new ValidationError(\n `code mode: the execute deadline passed; api.${face.name} is refused so no work outlives the call`,\n )\n }\n return detach(await context.verbs[member](args))\n }\n }\n try {\n return await runner.run({ code, bindings, signal: execution.signal })\n } finally {\n clearTimer?.()\n context.signal.removeEventListener('abort', onScopeAbort)\n }\n },\n },\n ]\n}\n","/**\n *\n * The mechanical patch gate — the SINGLE source of the no-op / always-on secret-path floor /\n * forbidden-path / diff-size / test / typecheck checks over a captured diff. No I/O: it scores a\n * patch plus its already-derived test/typecheck PASS signals. The generic worktree-CLI deliverable\n * (`patchDelivered`, which runs the commands itself) calls this, so the gate logic never forks.\n *\n * The always-on safety floors (no-op rejection + secret-path) are also exported standalone\n * (`isNonEmptyPatch` / `touchesSecretPath`) for reuse outside the full scorer.\n *\n * @experimental\n */\n\nimport type { DefaultVerdict } from '../types'\n\nconst DEFAULT_MAX_DIFF_LINES = 400\n\n/**\n * Default-on credential-path floor: a patch that touches a credential-shaped path is rejected\n * regardless of the per-task `forbiddenPaths` config. Catches `.env`, private keys, keystores,\n * wallets, and the common secret/credential JSON files.\n */\nconst secretPathPattern =\n /(^|\\/)(\\.env(\\.|$)|.*\\.(pem|key|p12|pfx|keystore|wallet)|id_rsa|id_ed25519|secrets?\\.json|credentials?\\.json)$/i\n\n/** @experimental The patch + its derived PASS signals the mechanical gate decides on. */\nexport interface CoderCheckInput {\n /** The unified diff produced by the run. */\n patch: string\n /** Did `testCmd` exit clean? */\n testsPassed: boolean\n /** Did `typecheckCmd` exit clean? */\n typecheckPassed: boolean\n}\n\n/** @experimental The per-task constraints the mechanical gate enforces. */\nexport interface CoderCheckConstraints {\n /** Default 400. Hard cap; gate fails when exceeded. */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch. */\n forbiddenPaths?: string[]\n}\n\n/** The unified-diff paths the patch touches — the `+++`/`---` headers, de-`a/`/`b/`-prefixed,\n * with `/dev/null` (a delete's other side) dropped. */\nexport function touchedPathsFromPatch(patch: string): string[] {\n const out = new Set<string>()\n for (const line of patch.split(/\\r?\\n/)) {\n if (line.startsWith('+++ ') || line.startsWith('--- ')) {\n const rest = line.slice(4).trim()\n if (rest === '/dev/null') continue\n const stripped = rest.startsWith('a/') || rest.startsWith('b/') ? rest.slice(2) : rest\n out.add(stripped)\n }\n }\n return [...out]\n}\n\n/** Count the added/removed content lines in a unified diff (excludes the `+++`/`---` headers). */\nexport function countDiffLines(patch: string): number {\n let count = 0\n for (const line of patch.split(/\\r?\\n/)) {\n if (\n (line.startsWith('+') || line.startsWith('-')) &&\n !line.startsWith('+++') &&\n !line.startsWith('---')\n ) {\n count += 1\n }\n }\n return count\n}\n\n/** True when the patch actually changes something — at least one touched path AND non-blank body.\n * An empty patch can trivially \"pass\" tests/typecheck (nothing changed) yet does no work. */\nexport function isNonEmptyPatch(patch: string): boolean {\n return touchedPathsFromPatch(patch).length > 0 && patch.trim().length > 0\n}\n\n/** The credential-shaped paths the patch touches (always-on floor, independent of `forbiddenPaths`). */\nexport function touchesSecretPath(patch: string): string[] {\n return touchedPathsFromPatch(patch).filter((p) => secretPathPattern.test(p))\n}\n\n/**\n *\n * The pure mechanical gate — the SINGLE source of the no-op / always-on secret-path floor /\n * diff-size / forbidden-path / test / typecheck checks. No I/O: it scores a patch + its\n * already-derived pass signals.\n *\n * Checks in order: (1) no-op rejection, (2) always-on secret-path floor (independent of\n * `forbiddenPaths`), (3) forbidden-path, (4) diff-size cap, (5) tests, (6) typecheck.\n * Aggregate score: `0.5*tests + 0.3*typecheck + 0.2*(1 - diffLines/maxDiff)`; `valid` is the\n * conjunction of all six.\n *\n * @experimental\n */\nexport function runCoderChecks(\n input: CoderCheckInput,\n constraints: CoderCheckConstraints = {},\n): DefaultVerdict {\n const maxDiff = constraints.maxDiffLines ?? DEFAULT_MAX_DIFF_LINES\n const forbidden = constraints.forbiddenPaths ?? []\n const scores: Record<string, number> = {}\n const notes: string[] = []\n let pass = true\n\n const touched = touchedPathsFromPatch(input.patch)\n\n // No-op rejection: an empty patch can trivially \"pass\" tests/typecheck (nothing changed) yet\n // does no work — never a valid result.\n if (touched.length === 0 || input.patch.trim().length === 0) {\n pass = false\n scores.nonEmpty = 0\n notes.push('empty patch — no files changed')\n } else {\n scores.nonEmpty = 1\n }\n\n // Secret-path floor: always-on, independent of `forbiddenPaths`.\n const touchedSecrets = touched.filter((p) => secretPathPattern.test(p))\n if (touchedSecrets.length > 0) {\n pass = false\n scores.noSecrets = 0\n notes.push(`touched secret-shaped paths: ${touchedSecrets.join(', ')}`)\n } else {\n scores.noSecrets = 1\n }\n\n const touchedForbidden = forbidden.filter((path) => {\n const prefix = path.endsWith('/') ? path : `${path}/`\n const exact = prefix.slice(0, -1)\n return touched.some((p) => p === exact || p.startsWith(prefix))\n })\n if (touchedForbidden.length > 0) {\n pass = false\n scores.forbiddenPath = 0\n notes.push(`touched forbidden paths: ${touchedForbidden.join(', ')}`)\n } else {\n scores.forbiddenPath = 1\n }\n\n const diffLines = countDiffLines(input.patch)\n if (diffLines > maxDiff) {\n pass = false\n scores.diffSize = 0\n notes.push(`diff ${diffLines} lines exceeds cap ${maxDiff}`)\n } else {\n scores.diffSize = maxDiff === 0 ? 0 : Math.max(0, 1 - diffLines / maxDiff)\n }\n\n scores.tests = input.testsPassed ? 1 : 0\n scores.typecheck = input.typecheckPassed ? 1 : 0\n if (!input.testsPassed) {\n pass = false\n notes.push('tests failed')\n }\n if (!input.typecheckPassed) {\n pass = false\n notes.push('typecheck failed')\n }\n\n const score = 0.5 * scores.tests + 0.3 * scores.typecheck + 0.2 * scores.diffSize\n const verdict: DefaultVerdict = {\n valid: pass,\n score: Number.isFinite(score) ? score : 0,\n scores,\n }\n if (notes.length > 0) verdict.notes = notes.join('; ')\n return verdict\n}\n","/**\n *\n * `patchDelivered` — the mechanical patch gate as a generic `DeliverableSpec` over the worktree-CLI\n * artifact. It is one construction of a `DeliverableSpec` (a plain `check(artifact) => boolean`\n * function); a domain customizes \"is it done\" by building its own spec, not by extending this one.\n * The canonical use: a `fanout(createWorktreeCliExecutor)` of authored harness profiles, each\n * `gateOnDeliverable(patchDelivered(...))`.\n *\n * The checks themselves are NOT re-implemented here — `runCoderChecks` (`./patch-checks`) is the\n * single source of the no-op / always-on secret-path floor / forbidden-path / diff-size / test /\n * typecheck logic. This factory only adapts the `WorktreePatchArtifact` shape (its `checks` carry\n * the test/typecheck PASS signals the executor derived in the live worktree) into the check inputs\n * and returns the boolean the gate consumes.\n *\n * Test/typecheck enforcement is OPT-IN per `require`: when a command was not run in the worktree\n * (the executor's `testCmd`/`typecheckCmd` were omitted) the corresponding signal is treated as\n * passed UNLESS `require` lists it — so a gate that demands a tests-pass on an artifact that never\n * ran tests fails closed (the honest outcome) rather than passing on a missing signal.\n *\n * @experimental\n */\n\nimport type { DeliverableSpec } from './completion-gate'\nimport { type CoderCheckConstraints, type CoderCheckInput, runCoderChecks } from './patch-checks'\nimport type { WorktreePatchArtifact } from './worktree-cli-executor'\n\n/** @experimental */\nexport interface PatchDeliverableOptions extends CoderCheckConstraints {\n /**\n * Which verification signals the gate REQUIRES to be present-and-passing. A required signal\n * that the artifact never derived (the command was not configured on the executor) fails the\n * gate closed. Unlisted signals default to passed-when-absent (the executor simply didn't run\n * that command). Default `[]` — gate on no-op / secret / forbidden / diff-size only.\n */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n}\n\n/**\n * Build the `DeliverableSpec<WorktreePatchArtifact>`: `check(artifact)` runs the shared mechanical\n * gate (`runCoderChecks`) over the captured patch + the worktree-derived pass signals and returns\n * whether the patch is DELIVERED (the `valid` conjunction).\n *\n * @experimental\n */\nexport function patchDelivered(\n options: PatchDeliverableOptions = {},\n): DeliverableSpec<WorktreePatchArtifact> {\n const require = new Set(options.require ?? [])\n const constraints: CoderCheckConstraints = {\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n }\n return {\n describe: 'patch: no-op/secret/forbidden/diff-size + required test/typecheck pass',\n check(artifact) {\n const input: CoderCheckInput = {\n patch: artifact.patch,\n testsPassed: signalPass(artifact.checks?.tests?.passed, require.has('tests')),\n typecheckPassed: signalPass(artifact.checks?.typecheck?.passed, require.has('typecheck')),\n }\n return runCoderChecks(input, constraints).valid === true\n },\n }\n}\n\n/**\n * Resolve a derived PASS signal into the boolean the gate folds in:\n * - signal present → its value (true/false).\n * - signal absent + required → false (fail closed: the gate demanded a signal that was never run).\n * - signal absent + not required → true (the executor simply didn't run that command).\n */\nfunction signalPass(value: boolean | undefined, required: boolean): boolean {\n if (value !== undefined) return value\n return !required\n}\n","/**\n *\n * `createSqlRunContext` — the SQL-backed durable bundle a `createSupervisor().run` (or a\n * `runGraph`/`supervise` call that accepts injected stores) needs: a `SqlSpawnJournal`, a\n * `SqlResultBlobStore` (both over one `SqlStatements` seam — the same adapter shape\n * `SqlConversationJournal` takes), and a fresh `createExecutorRegistry()`, with `resume: true`\n * so spreading the context makes the run loadTree-first.\n *\n * The SQL analogue of `createFileRunContext`: where that bundle owns a directory, this one owns\n * tables in a database the caller already operates. The durable coordination side-log and\n * cancellation observers remain file-based behind `runDir`; a SQL coordination log is follow-up.\n *\n * @experimental\n */\n\nimport {\n SqlResultBlobStore,\n SqlSpawnJournal,\n type SqlStatements,\n} from '../../durable/spawn-journal-sql'\nimport { createExecutorRegistry } from './runtime'\nimport type { ExecutorRegistry, ResultBlobStore, SpawnJournal } from './types'\n\nexport interface SqlRunContext {\n readonly journal: SpawnJournal\n readonly blobs: ResultBlobStore\n readonly executors: ExecutorRegistry\n /** Always `true` — a SQL context is durable by construction, so runs resume-first. */\n readonly resume: true\n}\n\n/** Build a durable run context over one SQL statement seam. Tables are created on first use. */\nexport function createSqlRunContext(db: SqlStatements): SqlRunContext {\n return {\n journal: new SqlSpawnJournal(db),\n blobs: new SqlResultBlobStore(db),\n executors: createExecutorRegistry(),\n resume: true,\n }\n}\n","import type { SqlAdapter } from '../../conversation/journal-sql'\nimport { InMemoryResultBlobStore, InMemorySpawnJournal } from '../../durable/spawn-journal'\nimport {\n openSqlRunStore,\n SqlRunOwnershipError,\n type SqlRunStoreOptions,\n} from '../../durable/sql-run-store'\nimport type { CoordinationEvent } from '../../mcp/tools/coordination'\nimport { type CoordinationOwnerId, foldCoordinationRecords } from './coordination-log'\nimport type { BusRecord } from './event-bus'\nimport {\n createInMemoryRunContext,\n type InMemoryRunContextOptions,\n type RunContext,\n type RunContextLease,\n} from './run-context'\nimport { detachedSnapshot } from './snapshot'\nimport type { SpawnEvent } from './types'\n\nexport { SqlRunOwnershipError } from '../../durable/sql-run-store'\n\nexport interface SqlRunContextOptions extends SqlRunStoreOptions, InMemoryRunContextOptions {}\n\n/** SQL stores are read-only outside an acquired ownership capability. runGraph acquires it. */\n/** A `RunContext` bound to one fenced SQL ownership generation; read-only until acquired. */\nexport interface FencedSqlRunContext extends RunContext {\n readonly durability: 'sql'\n readonly runId: string\n acquire(signal?: AbortSignal): Promise<RunContextLease>\n}\n\ntype Entry =\n | { kind: 'begin'; root: string; at: string }\n | { kind: 'events'; root: string; events: SpawnEvent[] }\n | { kind: 'blobs'; ref: string; value: unknown }\n | {\n kind: 'coordination'\n runId: string\n ownerId?: CoordinationOwnerId\n record: BusRecord<CoordinationEvent>\n }\n\ntype CoordinationRecord = Extract<Entry, { kind: 'coordination' }>\n\n/**\n * A cross-machine run context on the existing autocommit SqlAdapter. Reuse the same database,\n * tablePrefix and runId on every host; no runDir or shared filesystem is required.\n *\n * Each ownership generation gets fresh store capabilities. The public context can inspect SQL\n * at any time, but cannot write without acquire(). runGraph/supervise acquire and release it.\n * Retained provider execution supplies external admission/result idempotency; SQL does not turn\n * an arbitrary unkeyed network effect into an exactly-once operation.\n * @experimental\n */\nexport async function createFencedSqlRunContext(\n db: SqlAdapter,\n runId: string,\n options: SqlRunContextOptions = {},\n): Promise<FencedSqlRunContext> {\n const store = await openSqlRunStore<Entry>(db, runId, options)\n const { executors } = createInMemoryRunContext({ withDriver: options.withDriver ?? true })\n const cold = async () => projection(await store.read())\n const unowned = async (): Promise<never> => {\n throw new SqlRunOwnershipError(`SQL run '${runId}' requires an acquired lease before writing`)\n }\n const context: FencedSqlRunContext = {\n durability: 'sql',\n runId,\n namespace: store.namespace,\n resume: true,\n executors,\n journal: {\n loadTree: async (root) => (await cold()).journal.loadTree(root),\n beginTree: unowned,\n appendEvent: unowned,\n appendEvents: unowned,\n },\n blobs: {\n get: async (ref) => (await cold()).blobs.get(ref),\n put: unowned,\n },\n coordinationLog: {\n load: async (id, owner) => (await cold()).loadCoordination(id, owner),\n append: unowned,\n },\n async acquire(signal) {\n const lease = await store.acquire(signal)\n try {\n const failureController = new AbortController()\n const leaseSignal = AbortSignal.any([lease.signal, failureController.signal])\n const view = await projection(lease.records)\n let tail: Promise<void> = Promise.resolve()\n let accepting = true\n let failed: unknown\n let hasFailed = false\n const check = () => {\n leaseSignal.throwIfAborted()\n if (hasFailed) throw failed\n }\n const read = async <T>(operation: () => Promise<T>): Promise<T> => {\n await tail\n check()\n return operation()\n }\n const commit = (entry: Entry): Promise<void> => {\n if (!accepting) return unowned()\n // Reuse the in-memory stores' validation and snapshots. Their projection is not\n // observable while a publication is pending; a failed publication poisons this lease.\n const captured = detachedSnapshot(entry, 'SQL run record')\n const write = tail.then(async () => {\n check()\n if (await view.apply(captured)) await lease.append(captured)\n })\n tail = write.catch((error) => {\n hasFailed = true\n failed = error\n failureController.abort(error)\n })\n return write\n }\n const bound: RunContext = {\n durability: 'sql',\n runId,\n namespace: store.namespace,\n resume: true,\n executors,\n journal: {\n loadTree: (root) => read(() => view.journal.loadTree(root)),\n beginTree: (root, at) => commit({ kind: 'begin', root, at }),\n appendEvent: (root, event) => commit({ kind: 'events', root, events: [event] }),\n appendEvents: (root, events) => commit({ kind: 'events', root, events: [...events] }),\n },\n blobs: {\n get: (ref) => read(() => view.blobs.get(ref)),\n put: (ref, value) => commit({ kind: 'blobs', ref, value }),\n },\n coordinationLog: {\n load: (id, owner) => read(() => view.loadCoordination(id, owner)),\n append: (id, record, ownerId) =>\n commit({\n kind: 'coordination',\n runId: id,\n record,\n ...(ownerId === undefined ? {} : { ownerId }),\n }),\n },\n }\n return {\n context: Object.freeze(bound),\n signal: leaseSignal,\n async release() {\n accepting = false\n await tail\n await lease.release()\n },\n }\n } catch (error) {\n await lease.release().catch(() => undefined)\n throw error\n }\n },\n }\n return Object.freeze(context)\n}\n\n/** Reuse the existing journal's uniqueness/sequence rules and blob hash validation verbatim. */\nasync function projection(entries: readonly Entry[]) {\n const journal = new InMemorySpawnJournal()\n const blobs = new InMemoryResultBlobStore()\n const beginnings = new Map<string, string>()\n const coordination: CoordinationRecord[] = []\n const apply = async (entry: Entry): Promise<boolean> => {\n switch (entry.kind) {\n case 'begin': {\n const prior = beginnings.get(entry.root)\n await journal.beginTree(entry.root, entry.at)\n beginnings.set(entry.root, entry.at)\n return prior === undefined\n }\n case 'events':\n for (const event of entry.events) await journal.appendEvent(entry.root, event)\n return entry.events.length > 0\n case 'blobs': {\n const existing = await blobs.get(entry.ref)\n await blobs.put(entry.ref, entry.value)\n return existing === undefined\n }\n case 'coordination':\n if (entry.record.event.type === 'settled') return false\n coordination.push(entry)\n return true\n default:\n throw new Error('Unknown SQL run record kind')\n }\n }\n for (const entry of entries) await apply(entry)\n return {\n journal,\n blobs,\n apply,\n loadCoordination(id: string, ownerId?: CoordinationOwnerId) {\n return foldCoordinationRecords(\n coordination.map(({ runId, ownerId, record }) => ({\n runId,\n ...record,\n ...(ownerId === undefined ? {} : { ownerId }),\n })),\n id,\n ownerId,\n )\n },\n }\n}\n","/**\n *\n * The SETTLE-time analyst: when a worker finishes, collect its tool spans from a `TraceSource` and run\n * agent-eval's PUBLISHED batch analyzers over them — `buildTrajectory` (structured run summary),\n * `stuckLoopView` (full-run repeated-call view, complementing the online consecutive detector), and\n * `toolWasteView`. Substrate-agnostic: the spans come from any source (an owned loop's buffer OR a\n * sandbox box session). No analysis reimplemented — this is the thin bridge into agent-eval's analyzers.\n *\n * @experimental\n */\n\nimport { buildTrajectory, InMemoryTraceStore } from '@tangle-network/agent-eval'\nimport { stuckLoopView, toolWasteView } from '@tangle-network/agent-eval/pipelines'\nimport type { TraceSource } from './trace-source'\n\nexport interface TrajectoryAnalysis {\n /** Structured run summary (tool-call count, step order). Steps carry a single timestamp, so per-span\n * duration is 0; loop/waste detection keys on call PATTERNS + cross-span windows, not durations. */\n readonly trajectory: Awaited<ReturnType<typeof buildTrajectory>>\n /** Full-run repeated-call view (total occurrences + window) — allows one intervening call so it\n * catches a loop the online consecutive detector interleaves past. */\n readonly stuckLoop: Awaited<ReturnType<typeof stuckLoopView>>\n /** Wasted-vs-total tool-call ratio for the run. */\n readonly toolWaste: Awaited<ReturnType<typeof toolWasteView>>\n}\n\n/** Collect the source's spans and run the agent-eval batch analyzers over them under one `runId`. */\nexport async function analyzeTrace(\n source: TraceSource,\n runId = 'worker',\n): Promise<TrajectoryAnalysis> {\n const spans = await source.collect()\n const store = new InMemoryTraceStore()\n const laneSpanId = `${runId}-session-lane`\n if (spans.length > 0) {\n const startedAt = Math.min(...spans.map((span) => span.startedAt))\n const endedAt = Math.max(...spans.map((span) => span.endedAt ?? span.startedAt))\n const agentSpanId = `${runId}-agent`\n await store.appendSpan({\n spanId: agentSpanId,\n runId,\n kind: 'agent',\n name: 'trace-source-agent',\n startedAt,\n endedAt,\n })\n await store.appendSpan({\n spanId: laneSpanId,\n parentSpanId: agentSpanId,\n runId,\n kind: 'custom',\n name: 'trace-source-session',\n startedAt,\n endedAt,\n })\n }\n // Re-stamp onto one runId so the runId-filtered analyzers see the whole trace regardless of the\n // source's own id scheme. A TraceSource carries tool spans only, so attach\n // them to one explicit session lane; 0.117's analyzer uses ancestry plus\n // overlap times to distinguish serial repeats from parallel siblings.\n for (let i = 0; i < spans.length; i += 1) {\n const s = spans[i]\n if (s) {\n await store.appendSpan({\n ...s,\n runId,\n spanId: `${runId}-t${i}`,\n parentSpanId: laneSpanId,\n })\n }\n }\n const [trajectory, stuckLoop, toolWaste] = await Promise.all([\n buildTrajectory(store, runId),\n stuckLoopView(store, { runId, maxInterveningToolCalls: 1 }),\n toolWasteView(store, { runId }),\n ])\n return { trajectory, stuckLoop, toolWaste }\n}\n","import { spawnSync } from 'node:child_process'\nimport {\n appendFileSync,\n chmodSync,\n copyFileSync,\n constants as fsConstants,\n lstatSync,\n mkdirSync,\n readlinkSync,\n rmSync,\n symlinkSync,\n} from 'node:fs'\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport type { Workspace } from '../workspace'\n\n/**\n * Worker-clone preparation: make each worker's fresh clone a FAITHFUL copy of the\n * shared workspace's working tree, not just of its git history.\n *\n * `runInWorkspace` materializes a worker dir via `git clone`, which carries only\n * COMMITTED files. Real workspaces (SWE-bench instance images: astropy,\n * matplotlib) hold compiled extension modules (.so/.pyd) as UNTRACKED build\n * artifacts — inside a bare clone `import astropy` dies with \"cannot import name\n * '_compiler'\" before the worker's first edit, so its verify gate is physically\n * unpassable regardless of patch quality (observed: 7/7 astropy and 6/6\n * matplotlib workers failed exactly this way while the shared workspace verified\n * fine). The fix copies the source tree's untracked files — including git-ignored\n * build outputs — into the clone right after materialize and before the worker\n * starts.\n *\n * Isolation is preserved: artifacts are COPIED (copy-on-write via FICLONE where\n * the filesystem supports it — never hardlinked, a worker rebuild opening an\n * artifact with O_TRUNC on a shared inode would corrupt the source workspace for\n * every sibling), and an absolute symlink pointing inside the source tree is\n * rewritten to the clone-local path so no worker holds a live handle back into\n * shared mutable state.\n *\n * Fidelity stops at git history: every copied path is appended to the clone's\n * `.git/info/exclude`, so the clone-side `git add -A` (both the local delegate's\n * diff capture and `gitWorkspace.commit`) can never stage pre-existing build\n * artifacts into the shared ref — in the source they are untracked, and a\n * delivery must not silently start tracking them.\n *\n * Promoted verbatim from `loops/src/worker-clone.ts` (see agent-dev-container#4519): any harness\n * that materializes workers via `git clone` needs the working tree, not just the history.\n *\n * @experimental\n */\n\n/** Agent-infra dirs living inside a workspace; orchestration state, never build inputs. `.loops` is the pre-rename location of `.agent` supervisor state. */\nconst SKIPPED_TOP_LEVEL = new Set(['.agent', '.loops', '.evolve', '.agent-worktrees', '.claude'])\n\n/** Warn (and copy anyway) past this untracked payload size. */\nconst DEFAULT_WARN_BYTES = 2 * 1024 * 1024 * 1024\n\nexport interface UntrackedCopyStats {\n /** Files + symlinks that landed in the clone. */\n copied: number\n /** Total regular-file bytes enumerated (pre-copy, so the size warning fires first). */\n bytes: number\n}\n\nexport interface CopyOptions {\n warnBytes?: number\n log?: (message: string) => void\n}\n\ninterface PlannedEntry {\n rel: string\n kind: 'file' | 'symlink'\n size: number\n mode: number\n}\n\n/**\n * Copy every untracked file of `sourceDir`'s working tree — including git-ignored\n * build outputs (`git ls-files --others` with NO exclude flags lists both) — into\n * `cloneDir`, then shield the copied paths from the clone's `git add -A` via\n * `.git/info/exclude`. Nested git repos (listed as bare `dir/` entries), any path\n * containing a `.git` segment, and loop-infra dirs are skipped.\n */\nexport function copyUntrackedIntoClone(\n sourceDir: string,\n cloneDir: string,\n opts: CopyOptions = {},\n): UntrackedCopyStats {\n const warnBytes = opts.warnBytes ?? DEFAULT_WARN_BYTES\n const log = opts.log ?? ((message: string) => console.warn(message))\n const src = resolve(sourceDir)\n const dst = resolve(cloneDir)\n\n const ls = spawnSync('git', ['-C', src, 'ls-files', '--others', '-z'], {\n encoding: 'utf8',\n maxBuffer: 256 * 1024 * 1024,\n })\n if (ls.status !== 0) {\n throw new Error(\n `git ls-files --others failed in ${src}: ${(ls.stderr ?? '').trim() || `exit ${ls.status}`}`,\n )\n }\n\n // Enumerate + stat BEFORE copying so the payload-size warning precedes the work.\n const plan: PlannedEntry[] = []\n for (const rel of (ls.stdout ?? '').split('\\0')) {\n if (!rel || rel.endsWith('/')) continue // '' from split; 'dir/' = nested git repo, skip\n const segments = rel.split('/')\n if (segments.includes('.git')) continue\n if (SKIPPED_TOP_LEVEL.has(segments[0] ?? '')) continue\n let stat: ReturnType<typeof lstatSync>\n try {\n stat = lstatSync(join(src, rel))\n } catch {\n continue // vanished between enumerate and stat — a live workspace is allowed to move\n }\n if (stat.isSymbolicLink()) plan.push({ rel, kind: 'symlink', size: 0, mode: stat.mode })\n else if (stat.isFile()) plan.push({ rel, kind: 'file', size: stat.size, mode: stat.mode })\n // sockets/FIFOs/devices are not copyable artifacts — skip silently\n }\n\n const bytes = plan.reduce((sum, entry) => sum + entry.size, 0)\n if (bytes > warnBytes) {\n log(\n `worker clone: untracked payload in ${src} is ${(bytes / 1024 / 1024).toFixed(0)}MB ` +\n `(> ${(warnBytes / 1024 / 1024).toFixed(0)}MB) — copying anyway so the clone stays runnable`,\n )\n }\n\n let copied = 0\n const excludeLines: string[] = []\n for (const entry of plan) {\n const from = join(src, entry.rel)\n const to = join(dst, entry.rel)\n try {\n mkdirSync(dirname(to), { recursive: true })\n if (entry.kind === 'symlink') {\n let target = readlinkSync(from)\n if (isAbsolute(target)) {\n // Never let a clone hold a live path back into the shared source tree.\n const resolved = resolve(target)\n if (resolved === src || resolved.startsWith(src + sep))\n target = join(dst, relative(src, resolved))\n }\n rmSync(to, { force: true })\n symlinkSync(target, to)\n } else {\n // FICLONE = copy-on-write clone when the fs supports it, plain copy otherwise.\n copyFileSync(from, to, fsConstants.COPYFILE_FICLONE)\n chmodSync(to, entry.mode & 0o7777)\n }\n copied += 1\n excludeLines.push(toExcludePattern(entry.rel))\n } catch (err) {\n // One uncopyable artifact must not kill the worker before it starts; for that\n // file alone the clone degrades to the pre-fix (history-only) state.\n log(\n `worker clone: failed to copy untracked ${entry.rel}: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n }\n\n if (excludeLines.length > 0) {\n const infoDir = join(dst, '.git', 'info')\n mkdirSync(infoDir, { recursive: true })\n appendFileSync(\n join(infoDir, 'exclude'),\n `# untracked artifacts copied from the shared workspace — never commit them back\\n${excludeLines.join('\\n')}\\n`,\n 'utf8',\n )\n }\n\n return { copied, bytes }\n}\n\n/** Root-anchored literal exclude pattern: glob metachars and trailing spaces escaped. */\nfunction toExcludePattern(rel: string): string {\n const escaped = rel\n .replace(/([\\\\*?[\\]])/g, '\\\\$1')\n .replace(/ +$/, (spaces) => '\\\\ '.repeat(spaces.length))\n return `/${escaped}`\n}\n\n/**\n * Wrap a `Workspace` so every `materialize` (the per-worker `git clone` inside\n * `runInWorkspace`) is followed by the untracked-artifact copy above — the clone\n * the worker starts in matches the source WORKING TREE, not just its history.\n * `commit`/`head` pass through untouched, so delivery semantics are unchanged.\n */\nexport function withUntrackedArtifacts(\n ws: Workspace,\n sourceDir: string,\n log?: (message: string) => void,\n): Workspace {\n return {\n ref: ws.ref,\n materialize: async (dir: string) => {\n await ws.materialize(dir)\n copyUntrackedIntoClone(sourceDir, dir, log ? { log } : {})\n },\n commit: (dir: string, message: string) => ws.commit(dir, message),\n head: () => ws.head(),\n }\n}\n","/**\n * Evidence-rich worker settlement.\n *\n * The supervisor BRAIN decides respawn/steer/stop from what a settled worker\n * shows it. A bare `finished passed=false patchBytes=6138` starves that\n * decision: the brain cannot quote the failing assertion, so its next worker\n * goal is authored blind. This module composes the bounded evidence block a\n * settling worker appends to its event stream and — on failure — returns as\n * its output artifact, so `observe_agent` hands the brain the failing verify\n * tail, a diff summary, and the worker's final note instead of counters.\n */\n\n/** Hard cap on one worker's evidence block so the brain's context cannot blow up. */\nexport const EVIDENCE_MAX_CHARS = 3000\n/** Tail of the verify output — the failing assertion lives at the END of a test log. */\nexport const VERIFY_TAIL_CHARS = 1200\nconst TYPECHECK_TAIL_CHARS = 400\nconst PATCH_HEAD_LINES = 40\nconst PATCH_LINE_MAX_CHARS = 200\n/** Cap on the worker's closing note inside the evidence block. */\nexport const NOTE_MAX_CHARS = 300\n\nexport interface WorkerEvidenceInput {\n readonly passed: boolean\n readonly testPassed: boolean\n readonly typecheckPassed: boolean\n /** Combined stdout+stderr of the verify/test command (already backend-capped). */\n readonly testOutput: string\n readonly typecheckOutput: string\n readonly patch: string\n /** The worker's own closing commentary, when the backend surfaces one. */\n readonly reviewerNotes?: string\n}\n\n/**\n * Compose the settle evidence block. Section order is priority order under the\n * hard cap: the verify tail (what failed) survives before the diff head (what\n * was tried) and the worker note — a truncated diff is recoverable from the\n * persisted patch file, a truncated failing assertion is not recoverable at all.\n */\nexport function composeWorkerEvidence(input: WorkerEvidenceInput): string {\n const sections: string[] = []\n const failures = [\n ...(input.testPassed ? [] : ['tests failed']),\n ...(input.typecheckPassed ? [] : ['typecheck failed']),\n ]\n sections.push(\n input.passed ? 'verify PASSED' : `verify FAILED (${failures.join(', ') || 'gate not passed'})`,\n )\n const testTail = input.testOutput.trim().slice(-VERIFY_TAIL_CHARS)\n if (testTail) sections.push(`--- verify output (tail) ---\\n${testTail}`)\n if (!input.typecheckPassed) {\n const typecheckTail = input.typecheckOutput.trim().slice(-TYPECHECK_TAIL_CHARS)\n if (typecheckTail) sections.push(`--- typecheck output (tail) ---\\n${typecheckTail}`)\n }\n sections.push(diffSummary(input.patch))\n const note = input.reviewerNotes?.trim()\n if (note) sections.push(`--- worker note ---\\n${note.slice(0, NOTE_MAX_CHARS)}`)\n return sections.join('\\n').slice(0, EVIDENCE_MAX_CHARS)\n}\n\n/**\n * What a settled worker exposes as its output artifact (the blob the brain's\n * `observe_agent` reads). A passing worker's output is its patch — the\n * deliverable. A failing worker's output is its evidence block. A passing\n * worker with NO edits — the post-delivery read-only reviewer: the workspace\n * already holds a delivered fix, so the gate stays green under an empty diff —\n * would otherwise settle with an EMPTY output and its review would be lost, so\n * it exposes its evidence block instead (the worker note carries the review).\n */\nexport function settledWorkerOut(input: {\n readonly passed: boolean\n readonly patch: string\n readonly evidence: string\n}): string {\n if (input.evidence.length === 0) return input.patch\n if (!input.passed) return input.evidence\n return input.patch.trim().length > 0 ? input.patch : input.evidence\n}\n\n/**\n * The worker's closing commentary off a local harness run: the TAIL of its\n * stdout (falling back to stderr), bounded to the note cap so a reviewer's\n * final verdict line — written last — survives into the evidence block\n * (`composeWorkerEvidence` keeps the note's FIRST `NOTE_MAX_CHARS` chars).\n */\nexport function closingWorkerNote(stdout: string, stderr: string): string | undefined {\n const source = stdout.trim() || stderr.trim()\n if (!source) return undefined\n return source.slice(-NOTE_MAX_CHARS)\n}\n\nfunction diffSummary(patch: string): string {\n const trimmed = patch.trim()\n if (!trimmed) return '--- diff: EMPTY (the worker produced no edits) ---'\n const lines = trimmed.split('\\n')\n const filesChanged = lines.filter((line) => line.startsWith('diff --git ')).length\n const head = lines\n .slice(0, PATCH_HEAD_LINES)\n .map((line) =>\n line.length > PATCH_LINE_MAX_CHARS ? `${line.slice(0, PATCH_LINE_MAX_CHARS)}~` : line,\n )\n const omitted = lines.length - head.length\n const header = `--- diff: ${filesChanged} file(s) changed, ${Buffer.byteLength(patch)} bytes; first ${head.length} line(s) ---`\n return `${header}\\n${head.join('\\n')}${omitted > 0 ? `\\n... (${omitted} more patch lines; full patch persisted per worker)` : ''}`\n}\n","/**\n *\n * `worktreeFanout` — the GENERIC coding combinator: a `fanout` of N supervisor-authored harness\n * profiles, each on its OWN worktree-CLI leaf, each `gateOnDeliverable(deliverable)`, winner via the\n * shared `selectValidWinner` (valid-only — an ungated patch never wins, the deliverable gate is the\n * point). The `deliverable` is passed as DATA: it defaults to `patchDelivered(opts)` but any\n * `DeliverableSpec<WorktreePatchArtifact>` a domain authors slots in unchanged.\n *\n * The shape is content-free at the `fanout` layer; this builder only assembles the pieces (the\n * worktree-CLI executor + the injected deliverable + the diff-size selector) into the generic\n * combinator's `itemSpec`/`selectWinner` seams. Nothing here re-implements selection, gating, or\n * fanout — it composes the existing primitives.\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { fanout, selectValidWinner } from '../personify/combinators'\nimport type { CombinatorShape, WinnerStrategy } from '../personify/wave-types'\nimport { type DeliverableSpec, gateOnDeliverable } from './completion-gate'\nimport { type PatchDeliverableOptions, patchDelivered } from './patch-deliverable'\nimport type { AgentSpec, ExecutorFactory } from './types'\nimport {\n createWorktreeCliExecutor,\n type WorktreeCliExecutorOptions,\n type WorktreePatchArtifact,\n} from './worktree-cli-executor'\n\n/** @experimental One authored profile in a worktree fanout. Its exact `harness` field chooses the\n * local CLI; the supervisor authors the complete profile per sub-task. */\nexport interface AuthoredHarness {\n /** A short label for the worktree branch + trace node. */\n name: string\n /** The supervisor-authored `AgentProfile` (systemPrompt + model reach the harness via §1.5). */\n profile: AgentProfile\n /** Require measured usage from this leaf. Budgeted supervision refuses the default unmetered\n * local-CLI mode; set false only when the selected runner actually returns token usage. */\n budgetExempt?: WorktreeCliExecutorOptions['budgetExempt']\n /** Run Codex through its measured, isolated JSONL path. This implies `budgetExempt: false`. */\n codexReproducible?: WorktreeCliExecutorOptions['codexReproducible']\n /** Host paths denied to a reproducible Codex leaf. */\n codexReadDeniedPaths?: WorktreeCliExecutorOptions['codexReadDeniedPaths']\n /** Per-harness model/runId/baseRef overrides flow through the profile + these. */\n runId?: string\n baseRef?: string\n}\n\n/** @experimental */\nexport interface WorktreeFanoutOptions extends PatchDeliverableOptions {\n /** Absolute path to the git checkout each worktree is cut from. */\n repoRoot: string\n /** The per-task instruction handed to every harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The authored harness profiles — one fanout item (and one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /**\n * The completion check each leaf is gated on. Defaults to `patchDelivered(opts)` (the mechanical\n * no-op/secret/forbidden/diff-size + required test/typecheck gate). Pass any\n * `DeliverableSpec<WorktreePatchArtifact>` to customize \"is it delivered\" as DATA.\n */\n deliverable?: DeliverableSpec<WorktreePatchArtifact>\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Wall-clock cap per harness subprocess (ms). */\n harnessTimeoutMs?: number\n /** Winner-selection strategy. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to every worktree-CLI leaf (inject git/harness/command runners so the\n * whole fanout runs offline). Production callers leave these unset. */\n runGit?: WorktreeCliExecutorOptions['runGit']\n runHarness?: WorktreeCliExecutorOptions['runHarness']\n runCommand?: WorktreeCliExecutorOptions['runCommand']\n}\n\n/**\n * Build the worktree fanout combinator. Run it with `runPersonified({ persona, shape, task, budget })`\n * — equal-k holds by construction (the conserved budget pool bounds the N leaves), and selection is\n * the shared valid-only `selectValidWinner` (never a judge).\n *\n * @experimental\n */\nexport function worktreeFanout<Task>(\n options: WorktreeFanoutOptions,\n): CombinatorShape<Task, WorktreePatchArtifact> {\n const deliverable =\n options.deliverable ??\n patchDelivered({\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n })\n\n const itemSpec = (item: AuthoredHarness): AgentSpec => {\n const executorFactory: ExecutorFactory<WorktreePatchArtifact> = (_spec, ctx) => {\n if (!ctx.node) {\n throw new Error('worktreeFanout: supervised node context required')\n }\n return gateOnDeliverable(\n createWorktreeCliExecutor({\n repoRoot: options.repoRoot,\n profile: item.profile,\n taskPrompt: options.taskPrompt,\n executionAttemptId: ctx.node.attemptId,\n ...(item.budgetExempt !== undefined ? { budgetExempt: item.budgetExempt } : {}),\n ...(item.codexReproducible !== undefined\n ? { codexReproducible: item.codexReproducible }\n : {}),\n ...(item.codexReadDeniedPaths !== undefined\n ? { codexReadDeniedPaths: item.codexReadDeniedPaths }\n : {}),\n ...(item.runId ? { runId: item.runId } : {}),\n ...(item.baseRef ? { baseRef: item.baseRef } : {}),\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.harnessTimeoutMs !== undefined\n ? { harnessTimeoutMs: options.harnessTimeoutMs }\n : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n }),\n deliverable,\n )\n }\n return { profile: item.profile, harness: null, executorFactory }\n }\n\n const selectWinner = selectValidWinner<WorktreePatchArtifact>({\n strategy: options.winnerStrategy ?? 'highest-score',\n sizeOf: (a) => a.stats.insertions + a.stats.deletions,\n })\n\n return fanout<Task, AuthoredHarness, WorktreePatchArtifact>(options.harnesses, {\n itemTask: () => options.taskPrompt,\n label: (item, i) => `${item.name}:${i}`,\n itemSpec: (item) => itemSpec(item),\n selectWinner,\n })\n}\n","/**\n * superviseSurface — drive a team of agents to solve a graded `AgenticSurface` task. ONE capability that\n * replaces the worker-seam + \"self-improving supervisor\" wrapper pair: the driver (`profile`) spawns\n * workers that each run `runAgentic` over the surface (`refine` by default), settle on the surface's OWN\n * check (settled ⟺ resolved — a worker that ran but didn't pass settles invalid, so a keep-best driver\n * never counts it done), and feed the driver a self-improvement lens (the still-FAILING tests, by default)\n * so the next spawn targets the persistently-hard cases. Returns the deployable outcome + the full\n * conserved spend.\n *\n * WHY this lives here and not as a `supervise()` backend: `runAgentic` depends on the supervise core\n * (`strategy.ts` → `supervise/`), so a surface-solving worker cannot be a supervise built-in without an\n * import cycle. It is therefore a COMPOSITION of `supervise()` + `runAgentic` at the layer above both —\n * the right home for \"supervise over a graded surface\". The within-run self-improvement is the analyst\n * (authored content, swap `analysts`); the across-run kind wraps this call in `improve()`.\n */\nimport { randomUUID } from 'node:crypto'\nimport {\n createTraceAnalyst,\n DEFAULT_TRACE_ANALYST_KINDS,\n OUTPUT_VALUE,\n type RegistryRunOpts,\n type TraceAnalysisEngine,\n type TraceAnalysisStore,\n type TraceAnalystDefinition,\n} from '@tangle-network/agent-eval'\nimport { type AgentProfile, canonicalCandidateDigest } from '@tangle-network/agent-interface'\nimport type { AnalystRegistryAuthoringLike, AnalystRegistryLike } from '../analyst-loop/types'\nimport { ValidationError } from '../errors'\nimport type {\n AnalystKind,\n AnalystRegistry,\n AuthoredAnalystDefinition,\n MakeWorkerAgent,\n} from '../mcp/tools/coordination'\nimport type { RouterTransportConfig } from './router-client'\nimport {\n type AgenticSurface,\n type AgenticTask,\n refine,\n runAgentic,\n type Strategy,\n} from './strategy'\nimport type { DeliverableSpec } from './supervise/completion-gate'\nimport { supervise } from './supervise/supervise'\nimport type { SupervisorProfile } from './supervise/supervisor-agent'\nimport { isTraceAnalysisStore } from './supervise/trace-evidence'\nimport { createPushTraceSource, type TraceSource } from './supervise/trace-source'\nimport type { Agent, AgentSpec, Budget, Executor, ExecutorResult, Spend } from './supervise/types'\n\n/** What a surface worker settles with — the surface verdict the driver + deliverable read. `resolved` is\n * the surface check's pass/fail (settled ⟺ resolved); `score` is the partial-credit fraction; `failing`\n * carries the tests this worker left red (so the analyst can target them). */\nexport interface SurfaceWorkerOut {\n readonly resolved: boolean\n readonly score: number\n readonly shots: number\n readonly summary: string\n readonly failing?: readonly string[]\n}\n\n/** Instrument every real surface call with the shared push trace source. The last test report remains\n * available on `SurfaceWorkerOut` for compatibility, but analysts read only the persisted spans. */\nexport function traceSurfaceCalls(base: AgenticSurface): {\n surface: AgenticSurface\n failing: () => string[]\n traceSource: TraceSource\n} {\n let lastReport = ''\n const trace = createPushTraceSource()\n const surface: AgenticSurface = {\n name: base.name,\n open: (t) => base.open(t),\n tools: (t, h) => base.tools(t, h),\n async call(h, name, args) {\n const startedAt = Date.now()\n const recordedArgs = structuredClone(args)\n try {\n const out = await base.call(h, name, args)\n trace.record({\n toolName: name,\n args: recordedArgs,\n result: out,\n status: out.startsWith('ERROR:') ? 'error' : 'ok',\n startedAt,\n endedAt: Date.now(),\n })\n if (name === 'run_tests') lastReport = out\n return out\n } catch (error) {\n trace.record({\n toolName: name,\n args: recordedArgs,\n result: `ERROR: ${error instanceof Error ? error.message : String(error)}`,\n status: 'error',\n startedAt,\n endedAt: Date.now(),\n })\n throw error\n }\n },\n score: (t, h) => base.score(t, h),\n close: (h) => base.close(h),\n }\n return { surface, failing: () => failingTestNames(lastReport), traceSource: trace.source }\n}\n\n/**\n * Adapt an `agent-eval` `AnalystRegistry` into the lens shape `supervise({ analysts })` takes.\n *\n * The two registries were never structurally compatible: eval's class exposes `list()` and\n * `run(runId, inputs, opts)` and returns an `AnalystRunResult`, while `supervise` wants `kinds`\n * and `run(kindId, trace)`. So `'kinds' in buildDefaultAnalystRegistry()` is `false` and the five\n * calibrated lenses in `DEFAULT_TRACE_ANALYST_KINDS` were unreachable from any supervised run —\n * every consumer hand-rolled a lens instead (#630).\n *\n * The adapter lives HERE, not in eval, for one reason: eval must never import runtime, and runtime\n * already owns both shapes — it consumes `AnalystFinding` / `AnalystRunResult` from eval for its\n * analyst loop and defines the supervise lens itself. Writing it in eval would mean eval declaring\n * a duck-typed copy of a type this package already exports.\n *\n * `kinds` is the DEFINITION list, not `registry.list()`, because `Analyst` carries no `area` while\n * `TraceAnalystDefinition` does — `list()` cannot supply the field the lens shape requires. Every\n * id must be registered: an unknown kind throws at adapt time rather than returning nothing at run\n * time, when the driver would read the silence as \"no findings\".\n */\nexport function analystsFromRegistry(\n registry: AnalystRegistryLike,\n kinds: ReadonlyArray<{\n id: string\n description: string\n area: string\n }> = DEFAULT_TRACE_ANALYST_KINDS,\n opts?: { runOpts?: RegistryRunOpts; authoring?: AnalystAuthoring },\n): AnalystRegistry {\n const registered = new Set(registry.list().map((analyst) => analyst.id))\n const missing = kinds.map((kind) => kind.id).filter((id) => !registered.has(id))\n if (missing.length > 0) {\n throw new ValidationError(\n `analystsFromRegistry: ${missing.map((id) => JSON.stringify(id)).join(', ')} ${missing.length === 1 ? 'is' : 'are'} not registered; the registry has ${[...registered].map((id) => JSON.stringify(id)).join(', ') || '<none>'}`,\n )\n }\n const adapted = kinds.map((kind) => ({\n id: kind.id,\n description: kind.description,\n area: kind.area,\n }))\n const authoring = opts?.authoring\n if (\n authoring !== undefined &&\n typeof (registry as Partial<AnalystRegistryAuthoringLike>).register !== 'function'\n ) {\n throw new ValidationError(\n 'analystsFromRegistry: `authoring` needs a registry with `register`; pass the agent-eval AnalystRegistry itself, not a read-only shim',\n )\n }\n const authoringRegistry = registry as AnalystRegistryAuthoringLike\n return {\n kinds: adapted,\n run: async (kindId, trace) => {\n const result = await registry.run(\n `supervise-analyst-${kindId}-${randomUUID()}`,\n { traceStore: trace },\n { ...opts?.runOpts, only: [kindId] },\n )\n // Registry failures are isolated, not successful reviews with zero findings.\n const summary = result.per_analyst.find((entry) => entry.analyst_id === kindId)\n if (summary?.status !== 'ok') {\n throw new ValidationError(\n `analyst ${JSON.stringify(kindId)} did not complete: ${summary?.status ?? 'missing result'}`,\n )\n }\n return result.findings\n },\n ...(authoring === undefined\n ? {}\n : {\n register: (definition: AuthoredAnalystDefinition): AnalystKind => {\n // The seat is a REQUEST. `resolveEngine` is the authority: it returns the engine for a\n // model this run can serve and THROWS for one it cannot, and the coordination layer\n // turns that message into the manager's refusal reason.\n const engine = authoring.resolveEngine(definition.model)\n const analyst = createTraceAnalyst(traceAnalystFromAuthored(definition), {\n engine,\n ...(authoring.settlementTimeoutMs === undefined\n ? {}\n : { settlementTimeoutMs: authoring.settlementTimeoutMs }),\n })\n try {\n authoringRegistry.register(analyst)\n } catch (error) {\n // The registry is shared by every manager of the run, so an id is unique across the\n // whole tree, not just this manager's menu. Say that, or the manager reads a library\n // message about a lens it has never been shown and cannot tell what to change.\n throw new ValidationError(\n `the lens id ${JSON.stringify(definition.id)} is already registered for this run — analyst ids are shared by every manager in the tree, so pick a more specific id: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n return { id: definition.id, description: definition.description, area: definition.area }\n },\n }),\n }\n}\n\n/**\n * What `analystsFromRegistry` needs before a manager may define its own lens.\n *\n * Only the ENGINE is asked for, because everything else about a defined lens is already in the\n * manager's own words. The engine is the model seat plus the recursive investigation loop, and it\n * cannot come from a tool argument: an `AgentProfile` names a model the run's own model policy has\n * already fenced, but an analyst engine is host-constructed with host credentials.\n */\nexport interface AnalystAuthoring {\n /**\n * Resolve the investigation engine for the seat a definition asked for. `undefined` means the\n * definition named no seat and wants the run's default engine. THROW to refuse a seat this run\n * cannot serve — the message is what the manager reads and re-authors from.\n */\n readonly resolveEngine: (model: string | undefined) => TraceAnalysisEngine\n /** Forwarded to `createTraceAnalyst`; omit for its default. */\n readonly settlementTimeoutMs?: number\n}\n\n/**\n * Map an authored definition onto the eval definition `createTraceAnalyst` compiles.\n *\n * The version is DERIVED from the definition's own canonical digest, never supplied by the manager.\n * That is what makes an invented lens reproducible: the same authored words always compile to the\n * same version, two different wordings can never share one, and a finding's `analyst_id`\n * plus version names the exact text that produced it.\n */\nfunction traceAnalystFromAuthored(definition: AuthoredAnalystDefinition): TraceAnalystDefinition {\n return {\n id: definition.id,\n description: definition.description,\n area: definition.area,\n version: `1.0.0+authored.${canonicalCandidateDigest(definition).slice(-12)}`,\n question: definition.question,\n instructions: definition.instructions,\n toolGroup: definition.toolGroup,\n ...(definition.limits === undefined ? {} : { limits: definition.limits }),\n ...(definition.minimumEvidenceCitations === undefined\n ? {}\n : { minimumEvidenceCitations: definition.minimumEvidenceCitations }),\n }\n}\n\n/** The default self-improvement LENS — authored content, not a code path. On each settled worker it hands\n * the driver the still-FAILING tests (not just a score), so the next spawn targets the persistently-hard\n * cases. Swap `analysts` to change what the driver improves from — that's the one knob. */\nexport function failuresAnalyst(): AnalystRegistry {\n return {\n kinds: [\n {\n id: 'failures',\n description: \"Surface the worker's still-failing tests so the driver targets them next.\",\n area: 'progress',\n },\n ],\n run: async (_kindId: string, trace: TraceAnalysisStore) => {\n if (!isTraceAnalysisStore(trace)) return missingRunTestsEvidence()\n const report = await latestRunTestsReport(trace)\n if (report === undefined) return missingRunTestsEvidence()\n const failing = failingTestNames(report)\n return {\n summary: failing.length\n ? `Latest structured run_tests evidence reports STILL FAILING (${failing.length}): ${failing.join(', ')}. Spawn the next worker to fix exactly these; if a test keeps failing across workers, give it concrete guidance about that case.`\n : allTestsPassed(report)\n ? 'Latest structured run_tests evidence reports every test passed; stop.'\n : `Latest structured run_tests evidence contains no parseable failing-test names. Refusing to infer them from worker prose. run_tests output: ${report.slice(0, 300)}`,\n }\n },\n }\n}\n\nasync function latestRunTestsReport(store: TraceAnalysisStore): Promise<string | undefined> {\n const overview = await store.getOverview({ tool_names: ['run_tests'] })\n const candidates: Array<{ output: string; endedAt: string; ordinal: number }> = []\n let ordinal = 0\n for (const traceId of overview.sample_trace_ids) {\n const view = await store.viewTrace({ trace_id: traceId, per_attribute_byte_cap: 16_384 })\n let spans = view.spans\n if (spans === undefined) {\n const matches = await store.searchTrace({\n trace_id: traceId,\n regex_pattern: 'run_tests',\n max_matches: 100,\n })\n const spanIds = [\n ...new Set(\n matches.hits.filter((hit) => hit.span_name === 'run_tests').map((hit) => hit.span_id),\n ),\n ]\n spans = spanIds.length\n ? (\n await store.viewSpans({\n trace_id: traceId,\n span_ids: spanIds,\n per_attribute_byte_cap: 16_384,\n })\n ).spans\n : []\n }\n for (const span of spans) {\n if (span.tool_name !== 'run_tests') continue\n const output = span.attributes[OUTPUT_VALUE]\n if (typeof output !== 'string') continue\n candidates.push({ output, endedAt: span.end_time, ordinal: ordinal++ })\n }\n }\n candidates.sort(\n (left, right) =>\n Date.parse(left.endedAt) - Date.parse(right.endedAt) || left.ordinal - right.ordinal,\n )\n return candidates.at(-1)?.output\n}\n\nfunction failingTestNames(report: string): string[] {\n const body = /FAILING:\\s*([^\\n]+)/iu.exec(report)?.[1]\n if (body === undefined) return []\n return body\n .replace(/\\.\\s+COLLECTION-BLOCKED:.*$/iu, '')\n .replace(/\\s*\\(\\+\\d+\\s+more\\)\\s*$/iu, '')\n .split(',')\n .map((name) => name.trim())\n .filter(Boolean)\n}\n\nfunction allTestsPassed(report: string): boolean {\n const fraction = /(\\d+)\\s*\\/\\s*(\\d+)\\s+tests?\\s+passed/iu.exec(report)\n return fraction !== null && Number(fraction[1]) === Number(fraction[2])\n}\n\nfunction missingRunTestsEvidence(): { summary: string } {\n return {\n summary:\n 'Missing structured run_tests span evidence. Refusing to infer failing-test names from worker prose.',\n }\n}\n\n/** How a worker runs the surface task (its router substrate + per-attempt bounds). */\nexport interface SurfaceWorkerConfig {\n readonly routerBaseUrl: string\n readonly routerKey: string\n /** Exact worker behavior, tools, and model. */\n readonly profile: AgentProfile\n readonly analystProfile?: AgentProfile\n readonly innerTurns?: number\n /** Refine-shot budget for ONE worker attempt (max steered shots). Default 1. */\n readonly budget?: number\n}\n\n/** One spawned worker = one `runAgentic` attempt over the surface task. The driver's brief is threaded\n * into the attempt (so a re-spawn can take a targeted angle, not an identical retry); `runAgentic` stamps\n * real tokens/usd/ms, forwarded as `Spend`; the still-failing tests are captured for the analyst. */\nfunction surfaceWorkerExecutor(\n surface: AgenticSurface,\n task: AgenticTask,\n worker: SurfaceWorkerConfig,\n strategy: Strategy,\n): Executor<SurfaceWorkerOut> {\n let artifact: ExecutorResult<SurfaceWorkerOut> | undefined\n const traced = traceSurfaceCalls(surface)\n return {\n runtime: 'surface-worker',\n async execute(brief: unknown): Promise<ExecutorResult<SurfaceWorkerOut>> {\n const guidance = typeof brief === 'string' ? brief.trim() : brief ? JSON.stringify(brief) : ''\n const attemptTask: AgenticTask = guidance\n ? {\n ...task,\n userPrompt: `${task.userPrompt}\\n\\n— Supervisor guidance for THIS attempt (incorporate it; do not just repeat a prior approach) —\\n${guidance}`,\n }\n : task\n const r = await runAgentic({\n surface: traced.surface,\n task: attemptTask,\n strategy,\n budget: worker.budget ?? 1,\n routerBaseUrl: worker.routerBaseUrl,\n routerKey: worker.routerKey,\n workerProfile: worker.profile,\n ...(worker.analystProfile ? { analystProfile: worker.analystProfile } : {}),\n ...(worker.innerTurns !== undefined ? { innerTurns: worker.innerTurns } : {}),\n })\n const out: SurfaceWorkerOut = {\n resolved: r.resolved,\n score: r.score,\n shots: r.shots,\n summary: `${strategy.name} ${r.shots} shot(s) → ${(100 * r.score).toFixed(0)}% (${r.resolved ? 'resolved' : 'unresolved'})`,\n failing: r.resolved ? [] : traced.failing(),\n }\n const spent: Spend = {\n iterations: r.completions,\n tokens: r.tokens,\n ...(r.tokensKnown ? {} : { tokensKnown: false }),\n usd: r.usd,\n ...(r.usdKnown ? {} : { usdKnown: false }),\n ms: r.ms,\n }\n artifact = {\n outRef: `surface-worker:${task.id}:${r.shots}:${r.resolved ? 'ok' : 'no'}`,\n out,\n verdict: { valid: r.resolved, score: r.score },\n spent,\n }\n return artifact\n },\n traceSource: () => traced.traceSource,\n teardown: () => Promise.resolve({ destroyed: true }),\n resultArtifact() {\n if (!artifact) throw new Error('surfaceWorkerExecutor: resultArtifact before execute')\n return artifact\n },\n }\n}\n\nexport interface SuperviseSurfaceOptions {\n /** The graded surface workers solve (open/tools/call/score/close). */\n readonly surface: AgenticSurface\n /** Where/how each worker runs the surface task. */\n readonly worker: SurfaceWorkerConfig\n /** The conserved compute pool for the whole supervised run. Default: sized off the worker's inner-loop\n * bounds for a handful of worker spawns — raise it to let the driver try more. */\n readonly budget?: Budget\n /** The driver brain's Router endpoint/auth. Model and behavior remain owned by `profile`. */\n readonly router?: RouterTransportConfig\n /** The self-improvement lens fed to the driver on each settled worker. Default `failuresAnalyst()`\n * (target the still-failing tests). Pass a custom registry to change it, or `null` to turn the\n * within-run self-improvement OFF (the driver sees raw settled outputs). */\n readonly analysts?: AnalystRegistry | null\n /** The strategy each worker runs over the surface. Default `refine` (iterate-with-feedback). */\n readonly strategy?: Strategy\n /** Max workers working at once; later spawns queue. Default 1 (serial — required when workers share\n * a persistent artifact, so they continue each other instead of racing the file). */\n readonly workerSlots?: number\n}\n\n/** The deployable outcome of a supervised surface run. */\nexport interface SuperviseSurfaceResult {\n readonly resolved: boolean\n readonly score: number\n readonly usd: number\n readonly tokensIn: number\n readonly tokensOut: number\n readonly ms: number\n /** Total conserved-pool iterations = the driver + worker LLM rounds the run actually spent. */\n readonly completions: number\n}\n\n/** Drive a team of agents (spawned + steered by `profile`) to solve a graded `AgenticSurface` task, and\n * report the deployable outcome + the full conserved spend. This is `supervise()` configured for surfaces\n * — there is no other entrypoint to learn. */\nexport async function superviseSurface(\n profile: SupervisorProfile,\n task: AgenticTask,\n opts: SuperviseSurfaceOptions,\n): Promise<SuperviseSurfaceResult> {\n const strategy = opts.strategy ?? refine\n const innerTurns = opts.worker.innerTurns ?? 6\n // Default the driver to the worker's router (one router unless separated) and the pool to a handful of\n // worker spawns sized off the worker bounds — so the minimal call is\n // `superviseSurface(profile, task, { surface, worker })`.\n const router: RouterTransportConfig = opts.router ?? {\n routerBaseUrl: opts.worker.routerBaseUrl,\n routerKey: opts.worker.routerKey,\n }\n const budget = opts.budget ?? {\n maxIterations: (innerTurns + 2) * 5 + 16,\n maxTokens: 1_000_000_000,\n }\n // A worker's share of the conserved pool. It is deliberately not read from the profile: the\n // profile's ceilings bound ONE completion, while this bounds everything a worker may spend.\n const workerMaxTokens = Math.max(1, Math.floor(budget.maxTokens / 8))\n\n // Every spawned worker is a BYO executor that runs the surface task; the deliverable is the completion\n // oracle (delivered ⟺ the surface check passed).\n const makeWorkerAgent: MakeWorkerAgent = (rawProfile) => {\n const p = (rawProfile ?? {}) as { name?: unknown }\n const name = typeof p.name === 'string' && p.name.length > 0 ? p.name : 'surface-worker'\n const spec: AgentSpec = {\n profile: rawProfile as AgentProfile,\n harness: null,\n executor: surfaceWorkerExecutor(\n opts.surface,\n task,\n opts.worker,\n strategy,\n ) as Executor<unknown>,\n }\n return { name, act: async () => '', executorSpec: spec } as Agent<unknown, unknown> & {\n executorSpec: AgentSpec\n }\n }\n const deliverable: DeliverableSpec<unknown> = {\n describe: `resolve the surface task ${task.id} (every required check passes)`,\n check: (out) => (out as SurfaceWorkerOut | undefined)?.resolved === true,\n }\n\n // `null` analysts → self-improvement off; otherwise default to the failures lens and fire every kind it\n // declares on each settled worker.\n const analysts = opts.analysts === null ? undefined : (opts.analysts ?? failuresAnalyst())\n\n const result = await supervise(profile, task, {\n makeWorkerAgent,\n deliverable,\n budget,\n workerSlots: opts.workerSlots ?? 1,\n // A SMALL per-worker reservation so MULTIPLE workers fit the pool (the default reserves the whole pool\n // per worker → only one ever spawns, defeating the spawn-a-targeted-worker steering).\n perWorker: { maxIterations: innerTurns + 2, maxTokens: workerMaxTokens },\n router,\n ...(analysts ? { analysts, analyzeOnSettle: analysts.kinds.map((k) => k.id) } : {}),\n })\n\n const out = result.kind === 'winner' ? (result.out as SurfaceWorkerOut | undefined) : undefined\n const sp = result.spentTotal\n return {\n resolved: out?.resolved ?? false,\n score: out?.score ?? 0,\n usd: sp.usd,\n tokensIn: sp.tokens.input,\n tokensOut: sp.tokens.output,\n ms: sp.ms,\n completions: sp.iterations,\n }\n}\n","/**\n *\n * Settle-time surface-diff harvest — the read-back dual of the mount manifest.\n *\n * `RunProvenance.mounts` records what the caller placed INTO a run's workspace before the agent saw\n * it (instructions, skills, memory files — the profile surfaces the substrate materialized). This\n * module answers the reverse question at settle: **which of those mounted surfaces did the agent\n * itself change while working?** Harnesses mutate their own profile-adjacent surfaces as a matter of\n * course — a memory file appended to, an instructions file edited, a skill rewritten — and that\n * self-mutation is improvement-relevant evidence: an OBSERVED, session-scoped edit that may later be\n * lifted into the measured proposal pipeline (`proposeAgentImprovement`), never auto-promoted.\n *\n * The harvest is harness-agnostic by construction: it compares content hashes against the mount\n * manifest, so it needs no harness event format, no refinement protocol, and no knowledge of WHY a\n * surface changed. A harness that additionally reports structured self-edit events can enrich this\n * signal; nothing requires it to.\n *\n * The kernel never reads workspace contents itself — the caller supplies the read seam (a box\n * `fs.read`, a worktree read, a test double), mirroring how `recordMount` keeps mount hashing with\n * the byte owner. Reads return typed outcomes; a failed read is reported as an `unreadable` diff\n * carrying the error, never silently dropped.\n *\n * @experimental\n */\n\nimport { createHash } from 'node:crypto'\nimport { readFile, realpath } from 'node:fs/promises'\nimport { isAbsolute, resolve, sep } from 'node:path'\nimport { readBoxPathWithRetry } from './box-read-retry'\nimport type { MountManifestEntry } from './types'\n\n/** Outcome of reading one surface back at settle. `missing: true` means the path no longer exists\n * (a deletion — a valid, reportable outcome); any other failure carries its diagnostic. */\nexport type SurfaceReadOutcome =\n | { succeeded: true; value: Uint8Array }\n | { succeeded: false; missing: boolean; error: string }\n\n/** The read seam: fetch the current bytes at a mounted path. Implemented by a sandbox box's\n * `fs.read`, a local worktree read ({@link fsSurfaceReader}), or a test double. */\nexport type SurfaceReader = (path: string) => Promise<SurfaceReadOutcome>\n\n/**\n * One watched surface whose settled state differs from what was mounted (or from absence).\n *\n * - `modified` — the surface exists with different bytes (`settledSha256`/`settledBytes` present).\n * - `removed` — the surface no longer exists at its mounted path.\n * - `created` — a watched path that was never mounted now exists (`settledSha256`/`settledBytes`\n * present, no `mountedSha256`) — the shape a harness's new memory/skill file takes.\n * - `unreadable` — the read seam failed for a reason other than absence; `error` carries the\n * diagnostic. Reported rather than dropped so a permissions or transport failure cannot\n * masquerade as \"nothing changed\".\n */\nexport interface SurfaceDiff {\n /** The mounted/watched path, exactly as recorded. */\n path: string\n status: 'modified' | 'removed' | 'created' | 'unreadable'\n /** Hex SHA-256 of the bytes that were mounted (from the manifest). Absent for `created`. */\n mountedSha256?: string\n /** Free-form origin: the manifest entry's `source`, or the watch entry's `source`. */\n source: string\n /** Hex SHA-256 of the settled bytes. Present for `modified` and `created`. */\n settledSha256?: string\n /** Size of the settled bytes. Present for `modified` and `created`. */\n settledBytes?: number\n /** The read seam's diagnostic. Present only for `unreadable`. */\n error?: string\n}\n\n/** A path to check at settle that was NOT necessarily mounted — where a harness is known to write\n * self-authored surfaces (a memory dir's files, a refinement log). A watched path that was also\n * mounted compares against its mount; one that wasn't reports `created` if it now exists.\n * `created` is an inference from the mount manifest, not a proof of authorship: a file the box\n * IMAGE shipped at a never-mounted path also reports `created`. Watch paths known absent at run\n * start (or enumerate the tree at start AND settle and watch the difference) to make the label\n * mean what it says. */\nexport interface WatchedSurface {\n path: string\n /** Origin label carried onto the diff (default `'watched'`). */\n source?: string\n}\n\n/** Inputs to {@link harvestSurfaceDiffs}: the run's mount manifest, the read seam, and optional\n * watch paths for surfaces the agent may have created. */\nexport interface HarvestSurfaceDiffsOptions {\n /** The run's mount manifest (`RunProvenance.mounts`). Entries sharing a path are collapsed to the\n * LAST entry — the bytes the agent actually saw at start. */\n mounts: readonly MountManifestEntry[]\n /** How to read a mounted path's current bytes. */\n read: SurfaceReader\n /** Additional paths to check that may not have been mounted (see {@link WatchedSurface}). The\n * caller enumerates them (it knows the harness's state layout — e.g. via the box's file tree);\n * the harvest stays layout-agnostic. */\n watch?: readonly WatchedSurface[]\n}\n\nconst sha256Hex = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex')\n\n/** Contain a reader that violates its typed-outcome contract by THROWING: the module's law is that\n * a failed read becomes an `unreadable` diff, so one bad path must not reject the whole harvest\n * and silently drop every other diff. */\nconst readOutcome = async (read: SurfaceReader, path: string): Promise<SurfaceReadOutcome> => {\n try {\n return await read(path)\n } catch (err) {\n return {\n succeeded: false,\n missing: false,\n error: err instanceof Error ? err.message : String(err),\n }\n }\n}\n\n/** The collision/dedup key for a path: a leading `./` stripped, so `./AGENTS.md` (a mount\n * recorder's form) and `AGENTS.md` (a file-tree enumeration's form) are one surface. Absolute vs\n * relative cannot be reconciled here — keep those forms consistent between mounts and watches. */\nconst pathKey = (p: string): string => p.replace(/^\\.\\//, '')\n\n/**\n * Re-read every mounted (and watched) surface and report the ones whose settled state differs from\n * the manifest — modified, removed, or created. Unchanged surfaces and still-absent watched paths\n * produce no entry; reads run concurrently; output preserves record order, mounts before\n * watch-only paths. Mounts and watches sharing a path key are each collapsed to the LAST entry,\n * and a watched path that was also mounted compares against its mount (never reports `created`).\n *\n * The harvest takes no `AbortSignal`: it is pure fan-out over the read seam and waits on nothing\n * itself, so every cancellable moment belongs to the reader. Pass a signal to the reader instead\n * ({@link BoxSurfaceReaderOptions.signal}, or close over one in a custom {@link SurfaceReader}) —\n * that cuts the backoff waits, and the harvest still returns the diffs it did establish rather\n * than discarding settle-time evidence on a late cancellation.\n */\nexport async function harvestSurfaceDiffs(\n options: HarvestSurfaceDiffsOptions,\n): Promise<SurfaceDiff[]> {\n const byPath = new Map<string, MountManifestEntry>()\n for (const entry of options.mounts) byPath.set(pathKey(entry.path), entry)\n const watchByPath = new Map<string, WatchedSurface>()\n for (const watched of options.watch ?? []) {\n if (byPath.has(pathKey(watched.path))) continue\n watchByPath.set(pathKey(watched.path), watched)\n }\n const mountDiffs = await Promise.all(\n [...byPath.values()].map(async (entry): Promise<SurfaceDiff | undefined> => {\n const outcome = await readOutcome(options.read, entry.path)\n if (!outcome.succeeded) {\n return outcome.missing\n ? {\n path: entry.path,\n status: 'removed',\n mountedSha256: entry.sha256,\n source: entry.source,\n }\n : {\n path: entry.path,\n status: 'unreadable',\n mountedSha256: entry.sha256,\n source: entry.source,\n error: outcome.error,\n }\n }\n const settledSha256 = sha256Hex(outcome.value)\n if (settledSha256 === entry.sha256.toLowerCase()) return undefined\n return {\n path: entry.path,\n status: 'modified',\n mountedSha256: entry.sha256,\n source: entry.source,\n settledSha256,\n settledBytes: outcome.value.byteLength,\n }\n }),\n )\n const watchDiffs = await Promise.all(\n [...watchByPath.values()].map(async (watched): Promise<SurfaceDiff | undefined> => {\n const outcome = await readOutcome(options.read, watched.path)\n if (!outcome.succeeded) {\n // A still-absent watched path is the expected no-op; a failing read is not.\n if (outcome.missing) return undefined\n return {\n path: watched.path,\n status: 'unreadable',\n source: watched.source ?? 'watched',\n error: outcome.error,\n }\n }\n return {\n path: watched.path,\n status: 'created',\n source: watched.source ?? 'watched',\n settledSha256: sha256Hex(outcome.value),\n settledBytes: outcome.value.byteLength,\n }\n }),\n )\n return [...mountDiffs, ...watchDiffs].filter((d): d is SurfaceDiff => d !== undefined)\n}\n\n/** The minimal box surface the box-backed reader needs — structurally typed so the real\n * `@tangle-network/sandbox` box and a test double both satisfy it, no SDK import. */\nexport interface SurfaceReadBox {\n fs: { read(path: string): Promise<string> }\n}\n\n/** Retry and cancellation controls for {@link boxSurfaceReader}. */\nexport interface BoxSurfaceReaderOptions {\n /** Read attempts per path before settling on a failed outcome. The data plane can transiently\n * 404 a just-written file (the same blip `openSandboxRun`'s deliverable read retries for), and a\n * first-attempt 404 taken at face value turns a fresh self-edit into a false `removed`/dropped\n * `created`. Default 3. */\n attempts?: number\n /** Linear backoff base between attempts (delay = base × attempt). Default 250. */\n retryDelayMs?: number\n /** Cuts the retry waits short when the run is abandoned. The reader still returns a typed\n * outcome — the harvest reports what it managed to read rather than rejecting. */\n signal?: AbortSignal\n}\n\n/**\n * A {@link SurfaceReader} over a sandbox box's filesystem — the same `box.fs.read` seam\n * `openSandboxRun` reads deliverables through, with the same transient-404 posture (bounded\n * retry). The box wire returns UTF-8 TEXT (the SDK's binary path is `download()`), which profile\n * surfaces are; hashes are computed over the UTF-8 encoding, and content the wire had to\n * lossy-decode (a U+FFFD replacement character) is reported `unreadable` rather than hashed as\n * mojibake. The SDK's not-found error is detected structurally (`err.name === 'NotFoundError'`)\n * and maps to `missing: true` — unless its `resourceType` names something other than a file/path\n * (the BOX or session being gone), which is a transport failure, not an absent surface.\n */\nexport function boxSurfaceReader(\n box: SurfaceReadBox,\n options: BoxSurfaceReaderOptions = {},\n): SurfaceReader {\n return async (path) => {\n const result = await readBoxPathWithRetry(box.fs.read.bind(box.fs), path, {\n attempts: options.attempts ?? 3,\n delayMs: options.retryDelayMs ?? 250,\n signal: options.signal,\n })\n if (result.succeeded) {\n // A lossy decode is deterministic — retrying cannot recover the bytes, so this is a final\n // outcome rather than another attempt.\n if (result.text.includes('�')) {\n return {\n succeeded: false,\n missing: false,\n error: `boxSurfaceReader: content at ${JSON.stringify(path)} is not valid UTF-8 text (the box text wire lossy-decoded it); binary surfaces need a byte-faithful reader`,\n }\n }\n return { succeeded: true, value: new TextEncoder().encode(result.text) }\n }\n const err = result.error\n const notFound = err instanceof Error && err.name === 'NotFoundError'\n const resourceType =\n err && typeof err === 'object' && 'resourceType' in err\n ? String((err as { resourceType: unknown }).resourceType)\n : undefined\n // A NotFoundError naming the BOX or the session means the TRANSPORT is gone — calling that\n // `missing` would read as \"the agent deleted every surface\". Anything else is the file: the\n // SDK's HTTP mapper defaults `resourceType` to `'Resource'` when the server does not name one,\n // so matching only file-ish names would classify an ordinary deletion as `unreadable` and the\n // harvest would never report `removed`.\n const transportGone = resourceType !== undefined && /sandbox|session/i.test(resourceType)\n return {\n succeeded: false,\n missing: notFound && !transportGone,\n error: err instanceof Error ? err.message : String(err),\n }\n }\n}\n\n/**\n * A {@link SurfaceReader} over the local filesystem, for worktree/local workers. Every path —\n * relative or absolute — must resolve INSIDE `root`: a path that escapes it (`../`, an absolute\n * path elsewhere) fails as a contained non-missing outcome rather than reading outside the\n * worktree, so a persisted or mistyped manifest path cannot turn the harvest into an\n * existence/hash oracle over the host filesystem. Containment is checked twice — once on the\n * lexical path, then again on the symlink-resolved path, because `readFile` follows a link and a\n * link planted inside the root would otherwise read host bytes through a contained-looking name.\n * Absence maps to `missing: true`; every other failure carries the error message.\n */\nexport function fsSurfaceReader(root: string): SurfaceReader {\n const lexicalRoot = resolve(root)\n let resolvedRoot: string | undefined\n const escapes = (candidate: string, boundary: string): boolean =>\n candidate !== boundary && !candidate.startsWith(boundary + sep)\n const outside = (path: string, boundary: string): SurfaceReadOutcome => ({\n succeeded: false,\n missing: false,\n error: `fsSurfaceReader: path ${JSON.stringify(path)} resolves outside the reader root ${JSON.stringify(boundary)}`,\n })\n return async (path) => {\n const target = isAbsolute(path) ? resolve(path) : resolve(lexicalRoot, path)\n if (escapes(target, lexicalRoot)) return outside(path, lexicalRoot)\n try {\n // The root itself may be reached through a link (a worktree, a temp dir); compare\n // link-resolved against link-resolved so a legitimate mount is not read as an escape.\n resolvedRoot ??= await realpath(lexicalRoot)\n } catch (err) {\n // The WORKSPACE is gone, not the surface. Calling this `missing` would report every mount as\n // a deliberate agent deletion — the filesystem twin of a dead box answering for each path.\n return {\n succeeded: false,\n missing: false,\n error: `fsSurfaceReader: reader root ${JSON.stringify(lexicalRoot)} is unreadable (${err instanceof Error ? err.message : String(err)})`,\n }\n }\n try {\n const resolvedTarget = await realpath(target)\n if (escapes(resolvedTarget, resolvedRoot)) return outside(path, resolvedRoot)\n return { succeeded: true, value: new Uint8Array(await readFile(resolvedTarget)) }\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n return {\n succeeded: false,\n missing: code === 'ENOENT' || code === 'ENOTDIR',\n error: err instanceof Error ? err.message : String(err),\n }\n }\n }\n}\n","/**\n * createVerifierEnvironment — ANY checkable task as an `Environment`, no tool surface\n * required. The generalization piece: EOPS/commit0-style domains have tools that mutate\n * an external artifact, but math problems, legal drafts, creative briefs, GTM copy, and\n * QA tasks have a different shape — the artifact IS the worker's answer, and the domain\n * is defined by one function: the deployable check over that answer.\n *\n * const gsm8k = createVerifierEnvironment({\n * name: 'gsm8k',\n * check: (task, answer) => ({\n * passes: extractFinalNumber(answer) === task.meta?.answer ? 1 : 0,\n * total: 1,\n * errored: 0,\n * }),\n * })\n * await runBenchmark({ environment: gsm8k, tasks, worker }) // sample vs refine on math\n *\n * The worker gets one built-in tool — `submit_answer` — plus any read-only domain tools\n * the caller adds (a calculator, a retrieval call, a style guide lookup). Every\n * submission is kept; `score()` checks the BEST submission (keep-best is the measured\n * law: workers reach correct answers then revise past them). The refine strategy's\n * critic reads the submission trajectory like any other trace, so iterate-with-feedback\n * works unchanged on answer domains.\n *\n * The check can be graded (passes/total expresses partial credit — rubric points,\n * sub-answers, unit-test counts), and MUST be deployable (computable without an oracle\n * at serve time): exact/numeric match, schema validation, a compiled rubric — not a\n * peek at held-out labels the production system wouldn't have.\n */\n\nimport type { Environment } from './run-benchmark'\nimport type { AgenticTask, AgenticTool, ArtifactHandle, SurfaceScore } from './strategy'\n\nexport interface VerifierEnvironmentOptions {\n name: string\n /** The deployable check over a submitted answer. Graded via passes/total. */\n check(task: AgenticTask, answer: string): Promise<SurfaceScore> | SurfaceScore\n /** Extra domain tools (read-only helpers: calculator, retrieval, style lookup). */\n extraTools?: AgenticTool[]\n /** Executes the extra tools. Required when `extraTools` is set. */\n callExtra?(\n task: AgenticTask,\n name: string,\n args: Record<string, unknown>,\n ): Promise<string> | string\n}\n\ninterface AnswerState {\n task: AgenticTask\n submissions: string[]\n}\n\nconst submitTool: AgenticTool = {\n type: 'function',\n function: {\n name: 'submit_answer',\n description:\n 'Submit your answer for evaluation. You may submit more than once — the best-scoring submission counts. Submit the COMPLETE final answer, not a fragment.',\n parameters: {\n type: 'object',\n properties: { answer: { type: 'string', description: 'The complete final answer.' } },\n required: ['answer'],\n },\n },\n}\n\n/** Any checkable task as an `Environment`, no tool surface required: the artifact is the worker's answer and the domain is one deployable `check` over it. */\nexport function createVerifierEnvironment(opts: VerifierEnvironmentOptions): Environment {\n if (opts.extraTools?.length && !opts.callExtra) {\n throw new Error(`${opts.name}: extraTools requires callExtra`)\n }\n const states = new Map<string, AnswerState>()\n let seq = 0\n\n return {\n name: opts.name,\n\n async open(task) {\n seq += 1\n const handle: ArtifactHandle = { id: `${opts.name}-${seq}`, surface: opts.name }\n states.set(handle.id, { task, submissions: [] })\n return handle\n },\n\n async tools() {\n return [submitTool, ...(opts.extraTools ?? [])]\n },\n\n async call(handle, name, args) {\n const state = states.get(handle.id)\n if (!state) return 'ERROR: workspace closed'\n if (name === 'submit_answer') {\n const answer = String(args.answer ?? '').trim()\n if (!answer) return 'ERROR: empty answer'\n state.submissions.push(answer)\n return `submission ${state.submissions.length} recorded`\n }\n if (opts.callExtra && opts.extraTools?.some((t) => t.function.name === name)) {\n try {\n return await opts.callExtra(state.task, name, args)\n } catch (e) {\n return `ERROR: ${e instanceof Error ? e.message : String(e)}`\n }\n }\n return `ERROR: unknown tool ${name}`\n },\n\n // Keep-best across submissions — the measured law (workers reach correct answers,\n // then revise past them; final-state scoring undersells every strategy).\n async score(task, handle) {\n const state = states.get(handle.id)\n if (!state || state.submissions.length === 0) return { passes: 0, total: 1, errored: 0 }\n let best: SurfaceScore = { passes: 0, total: 1, errored: 0 }\n const ratio = (s: SurfaceScore) => (s.total > 0 ? s.passes / s.total : 0)\n for (const answer of state.submissions) {\n const s = await opts.check(task, answer)\n if (ratio(s) > ratio(best)) best = s\n }\n return best\n },\n\n async close(handle) {\n states.delete(handle.id)\n },\n }\n}\n","/**\n * createWaterfallCollector — 100% trajectory observability from the lifecycle stream:\n * every spawn/settle (shots, analysts, nested agents) becomes one timed, billed span.\n * The sum of spans IS the run's cost story — what each step cost in dollars, tokens,\n * and wall-clock, rendered as a text waterfall or exported as structured rows for any\n * chart. Attach the collector's `hooks` to `runAgentic`/`runBenchmark`; spans accumulate\n * across every task the hooks observe.\n */\nimport type { RuntimeHookEvent, RuntimeHooks } from '../runtime-hooks'\n\nexport interface WaterfallSpan {\n id: string\n /** The spawn label (`shot:0`, `analyst:1`, a nested agent's label) — the row name. */\n label: string\n runId: string\n parentId?: string\n startMs: number\n endMs?: number\n status: 'running' | 'done' | 'down'\n usd: number\n tokens: { input: number; output: number }\n score?: number\n}\n\nexport interface WaterfallReport {\n spans: WaterfallSpan[]\n /** Wall-clock of the observed window (first spawn → last settle). */\n totalMs: number\n totalUsd: number\n totalTokens: { input: number; output: number }\n /** Rollup by label prefix (the part before ':') — shots vs analysts vs anything else. */\n byKind: Record<\n string,\n { count: number; ms: number; usd: number; tokens: { input: number; output: number } }\n >\n}\n\ninterface SpawnPayload {\n childId?: string\n label?: string\n}\ninterface SettlePayload {\n childId?: string\n status?: string\n retainedExecution?: string\n score?: number\n spent?: { usd?: number; tokens?: { input?: number; output?: number } }\n}\n\nexport interface WaterfallCollector {\n /** Attach these to RunAgenticOptions.hooks / BenchmarkConfig.hooks. */\n hooks: RuntimeHooks\n report(): WaterfallReport\n /** The text waterfall — one row per span, bars scaled to the observed window. */\n render(opts?: { width?: number; maxRows?: number }): string\n reset(): void\n}\n\n/** Build a `WaterfallCollector` that records agent spans and renders them as an ASCII timeline. */\nexport function createWaterfallCollector(): WaterfallCollector {\n let spans = new Map<string, WaterfallSpan>()\n\n const onEvent = (event: RuntimeHookEvent): void => {\n if (event.target === 'agent.spawn') {\n const p = (event.payload ?? {}) as SpawnPayload\n const id = p.childId ?? event.id\n spans.set(id, {\n id,\n label: p.label ?? id,\n runId: event.runId,\n ...(event.parentId !== undefined ? { parentId: event.parentId } : {}),\n startMs: event.timestamp,\n status: 'running',\n usd: 0,\n tokens: { input: 0, output: 0 },\n })\n return\n }\n if (event.target === 'agent.child') {\n const p = (event.payload ?? {}) as SettlePayload\n const id = p.childId\n if (!id) return\n const span = spans.get(id)\n if (!span) return\n // The release event's timestamp is the release instant, not the settlement; without this\n // guard a released child's bar would stretch to root settlement.\n if (span.endMs !== undefined && p.retainedExecution === 'released') return\n span.endMs = event.timestamp\n span.status = p.status === 'down' ? 'down' : 'done'\n span.usd = p.spent?.usd ?? 0\n span.tokens = {\n input: p.spent?.tokens?.input ?? 0,\n output: p.spent?.tokens?.output ?? 0,\n }\n if (typeof p.score === 'number') span.score = p.score\n }\n }\n\n const report = (): WaterfallReport => {\n const all = [...spans.values()].sort((a, b) => a.startMs - b.startMs)\n const start = all[0]?.startMs ?? 0\n const end = Math.max(start, ...all.map((s) => s.endMs ?? s.startMs))\n const byKind: WaterfallReport['byKind'] = {}\n let totalUsd = 0\n const totalTokens = { input: 0, output: 0 }\n for (const s of all) {\n totalUsd += s.usd\n totalTokens.input += s.tokens.input\n totalTokens.output += s.tokens.output\n const kind = s.label.includes(':') ? (s.label.split(':')[0] as string) : s.label\n let k = byKind[kind]\n if (!k) {\n k = { count: 0, ms: 0, usd: 0, tokens: { input: 0, output: 0 } }\n byKind[kind] = k\n }\n k.count += 1\n k.ms += (s.endMs ?? s.startMs) - s.startMs\n k.usd += s.usd\n k.tokens.input += s.tokens.input\n k.tokens.output += s.tokens.output\n }\n return { spans: all, totalMs: end - start, totalUsd, totalTokens, byKind }\n }\n\n const render = (opts?: { width?: number; maxRows?: number }): string => {\n const { spans: all, totalMs, totalUsd, byKind } = report()\n if (all.length === 0) return '(no spans observed)'\n const width = opts?.width ?? 48\n const maxRows = opts?.maxRows ?? 60\n const start = all[0]?.startMs ?? 0\n const scale = totalMs > 0 ? width / totalMs : 0\n const lines: string[] = []\n const labelWidth = Math.min(24, Math.max(...all.map((s) => s.label.length)) + 1)\n for (const s of all.slice(0, maxRows)) {\n const offset = Math.round((s.startMs - start) * scale)\n const dur = (s.endMs ?? s.startMs) - s.startMs\n const len = Math.max(1, Math.round(dur * scale))\n const bar = `${' '.repeat(Math.min(offset, width))}${(s.status === 'down' ? '░' : '█').repeat(Math.max(1, Math.min(len, width - Math.min(offset, width) + 1)))}`\n const mark =\n s.status === 'down'\n ? ' DOWN'\n : s.score !== undefined\n ? ` ${(s.score * 100).toFixed(0)}%`\n : ''\n lines.push(\n `${s.label.padEnd(labelWidth)}|${bar.padEnd(width + 1)}| ${(dur / 1000).toFixed(1)}s $${s.usd.toFixed(4)} ${s.tokens.input}/${s.tokens.output}tok${mark}`,\n )\n }\n if (all.length > maxRows) lines.push(`… ${all.length - maxRows} more spans`)\n lines.push('—'.repeat(labelWidth + width + 2))\n for (const [kind, k] of Object.entries(byKind)) {\n lines.push(\n `${kind.padEnd(labelWidth)} ×${k.count} ${(k.ms / 1000).toFixed(1)}s busy $${k.usd.toFixed(4)} ${k.tokens.input}/${k.tokens.output}tok`,\n )\n }\n lines.push(\n `TOTAL${' '.repeat(labelWidth - 5)} ${(totalMs / 1000).toFixed(1)}s wall $${totalUsd.toFixed(4)}`,\n )\n return lines.join('\\n')\n }\n\n return {\n hooks: { onEvent },\n report,\n render,\n reset: () => {\n spans = new Map()\n },\n }\n}\n","/** Command runner seam. Host code can use `localShell`; sandbox code can wrap `box.exec`. */\nexport type Shell = (\n args: ReadonlyArray<string>,\n cwd?: string,\n) => Promise<{ stdout: string; stderr: string; code: number }>\n\nexport type WorkspaceCommit =\n | { readonly ok: true; readonly rev: string }\n | { readonly ok: false; readonly conflict: string }\n\nexport interface Workspace {\n readonly ref: string\n materialize(dir: string): Promise<void>\n commit(dir: string, message: string): Promise<WorkspaceCommit>\n head(): Promise<string>\n}\n\n/** Host-process `Shell`: run a command via `execFile`, resolving `{ stdout, stderr, code }` (never throws on non-zero exit). */\nexport function localShell(): Shell {\n return async (args, cwd) => {\n const { execFile } = await import('node:child_process')\n const [bin, ...rest] = args\n return new Promise((resolve) => {\n execFile(\n bin ?? '',\n rest,\n { cwd, encoding: 'utf-8', maxBuffer: 64 * 1024 * 1024 },\n (err: Error | null, stdout: string, stderr: string) => {\n resolve({\n stdout: stdout ?? '',\n stderr: stderr ?? '',\n code: err ? ((err as { code?: number }).code ?? 1) : 0,\n })\n },\n )\n })\n }\n}\n\nexport interface GitWorkspaceOptions {\n readonly ref: string\n readonly shell?: Shell\n readonly branch?: string\n readonly noHooks?: boolean\n}\n\n/** A `Workspace` over a git checkout: materialize an isolated worktree at `ref`, commit produced changes (conflict-aware), and read `head` — hooks disabled, identity pinned. */\nexport function gitWorkspace(opts: GitWorkspaceOptions): Workspace {\n const shell = opts.shell ?? localShell()\n const branch = opts.branch ?? 'main'\n const cfg = opts.noHooks === false ? [] : ['-c', 'core.hooksPath=/dev/null']\n const ident = ['-c', 'user.email=workspace@tangle.local', '-c', 'user.name=workspace']\n\n const run = async (args: string[], cwd?: string): Promise<string> => {\n const res = await shell(['git', ...cfg, ...ident, ...args], cwd)\n if (res.code !== 0) {\n throw new Error(\n `git ${args.join(' ')} failed (${res.code}): ${tail(res.stderr || res.stdout)}`,\n )\n }\n return res.stdout\n }\n\n return {\n ref: opts.ref,\n materialize: (dir) => run(['clone', '--branch', branch, opts.ref, dir]).then(() => {}),\n async commit(dir, message) {\n await run(['add', '-A'], dir)\n const status = await run(['status', '--porcelain'], dir)\n if (!status.trim()) return { ok: true, rev: (await run(['rev-parse', 'HEAD'], dir)).trim() }\n await run(['commit', '-m', message], dir)\n const pull = await shell(['git', ...cfg, ...ident, 'pull', '--rebase', 'origin', branch], dir)\n if (pull.code !== 0) {\n await shell(['git', ...cfg, 'rebase', '--abort'], dir).catch(() => {})\n return { ok: false, conflict: tail(pull.stderr || pull.stdout) }\n }\n const push = await shell(['git', ...cfg, ...ident, 'push', 'origin', branch], dir)\n if (push.code !== 0) return { ok: false, conflict: tail(push.stderr || push.stdout) }\n return { ok: true, rev: (await run(['rev-parse', 'HEAD'], dir)).trim() }\n },\n async head() {\n const out = await run(['ls-remote', opts.ref, `refs/heads/${branch}`])\n return out.split(/\\s+/)[0] ?? ''\n },\n }\n}\n\n/** A jj-backed `Workspace` (Jujutsu, colocated with git for the durable remote).\n * Same port, same `Shell` — a drop-in for `gitWorkspace`. jj suits agent loops:\n * no staging area, and a first-class operation log (native resume/undo). Live use\n * requires `jj` on the `Shell`'s host. */\nexport function jjWorkspace(opts: GitWorkspaceOptions): Workspace {\n const shell = opts.shell ?? localShell()\n const branch = opts.branch ?? 'main'\n // jj reads its author identity from config, not per-call flags like git's `-c\n // user.*`; inject it via --config-toml so a throwaway clone is self-contained\n // (parallels gitWorkspace's `ident`). Global flags must precede the subcommand.\n const ident = [\n '--config-toml',\n 'user.name=\"workspace\"',\n '--config-toml',\n 'user.email=\"workspace@tangle.local\"',\n ]\n\n const jj = async (args: string[], cwd?: string): Promise<string> => {\n const res = await shell(['jj', ...ident, ...args], cwd)\n if (res.code !== 0) {\n throw new Error(\n `jj ${args.join(' ')} failed (${res.code}): ${tail(res.stderr || res.stdout)}`,\n )\n }\n return res.stdout\n }\n\n return {\n ref: opts.ref,\n // Colocated clone: jj manages history, git holds the durable remote.\n materialize: (dir) => jj(['git', 'clone', '--colocate', opts.ref, dir]).then(() => {}),\n async commit(dir, message) {\n // jj auto-snapshots the working copy; describe the change, then open a fresh\n // empty change so the next commit doesn't amend this one. A rejected push is\n // surfaced as a typed blocker (conflicts are first-class in jj, not aborted).\n await jj(['describe', '-m', message], dir)\n await jj(['new'], dir)\n const push = await shell(['jj', ...ident, 'git', 'push', '--branch', branch], dir)\n if (push.code !== 0) return { ok: false, conflict: tail(push.stderr || push.stdout) }\n const rev = (await jj(['log', '--no-graph', '-r', '@-', '-T', 'commit_id'], dir)).trim()\n return { ok: true, rev }\n },\n async head() {\n const out = await shell(['git', 'ls-remote', opts.ref, `refs/heads/${branch}`])\n return out.stdout.split(/\\s+/)[0] ?? ''\n },\n }\n}\n\nexport interface WorkspaceRun<T> {\n readonly valid: boolean\n readonly value: T\n /** Present when a commit was attempted (valid, or `commitOnInvalid`). */\n readonly commit?: WorkspaceCommit\n}\n\n/**\n * Run a worker `body` inside a FRESH clone of a shared `Workspace`, then commit its work back\n * so the next worker (or the supervisor) builds on it. This is the seam that turns isolated\n * per-worker cwds into one compounding artifact — `body` gets a real materialized dir, its\n * delivery is committed to the shared ref iff it's valid (a conflict is returned, never thrown).\n * The clone is removed after; durable state lives only in the ref.\n */\nexport async function runInWorkspace<T>(\n ws: Workspace,\n body: (cwd: string) => Promise<{ valid: boolean; value: T; message?: string }>,\n opts: { tmpPrefix?: string; commitOnInvalid?: boolean } = {},\n): Promise<WorkspaceRun<T>> {\n const { mkdtempSync, rmSync } = await import('node:fs')\n const { tmpdir } = await import('node:os')\n const { join } = await import('node:path')\n const dir = mkdtempSync(join(tmpdir(), opts.tmpPrefix ?? 'ws-run-'))\n try {\n await ws.materialize(dir)\n const r = await body(dir)\n if (r.valid || opts.commitOnInvalid) {\n const message = r.message ?? (r.valid ? 'worker: delivered' : 'worker: wip')\n const commit = await ws.commit(dir, message)\n return { valid: r.valid, value: r.value, commit }\n }\n return { valid: r.valid, value: r.value }\n } finally {\n rmSync(dir, { recursive: true, force: true })\n }\n}\n\nfunction tail(s: string): string {\n return s.slice(-400)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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