@tangle-network/agent-runtime 0.353.3 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{activation-CFS31SWI.d.ts → activation-BuK2H7qx.d.ts} +2 -2
- package/dist/{activation-DTgC0RvI.js → activation-ZQWz04u8.js} +4 -4
- package/dist/{activation-DTgC0RvI.js.map → activation-ZQWz04u8.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +4 -3
- package/dist/agent.js.map +1 -1
- package/dist/{bundle-DeDkJbsr.js → bundle-PDYNXIEf.js} +2 -2
- package/dist/{bundle-DeDkJbsr.js.map → bundle-PDYNXIEf.js.map} +1 -1
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{coordination-manager-D-J0Osf4.js → coordination-manager-BZLp9qpE.js} +8 -363
- package/dist/coordination-manager-BZLp9qpE.js.map +1 -0
- package/dist/coordination-map-routing-CUvwHAtv.js +362 -0
- package/dist/coordination-map-routing-CUvwHAtv.js.map +1 -0
- package/dist/{delegate-DfRQSGVk.js → delegate-C-MUU6ML.js} +2 -2
- package/dist/{delegate-DfRQSGVk.js.map → delegate-C-MUU6ML.js.map} +1 -1
- package/dist/durable-file-CksURHlH.js +1 -0
- package/dist/durable-file-DstVeHcj.js +228 -0
- package/dist/durable-file-DstVeHcj.js.map +1 -0
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +10 -8
- package/dist/durable.js.map +1 -1
- package/dist/{graph-BtGsqcOF.js → graph-CM-6CV_K.js} +6 -5
- package/dist/{graph-BtGsqcOF.js.map → graph-CM-6CV_K.js.map} +1 -1
- package/dist/graph-registry-72DlMnUl.js +585 -0
- package/dist/graph-registry-72DlMnUl.js.map +1 -0
- package/dist/graph-registry-CAX15LO6.js +1 -0
- package/dist/{improve-CL-Dsf63.js → improve-BuZ-I8DP.js} +9 -8
- package/dist/{improve-CL-Dsf63.js.map → improve-BuZ-I8DP.js.map} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +12 -11
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +2 -2
- package/dist/intelligence.js +7 -7
- package/dist/{journal-store-BJPMUydp.js → journal-store-BpCOCDoO.js} +208 -635
- package/dist/journal-store-BpCOCDoO.js.map +1 -0
- package/dist/jsonl-file-BBP9Dz9w.js +429 -0
- package/dist/jsonl-file-BBP9Dz9w.js.map +1 -0
- package/dist/kernel.d.ts +1 -1
- package/dist/kernel.js +13 -12
- package/dist/{loop-runner-B1Xpgp2w.js → loop-runner-BWD6v1rd.js} +2 -2
- package/dist/{loop-runner-B1Xpgp2w.js.map → loop-runner-BWD6v1rd.js.map} +1 -1
- package/dist/{loop-runner-D9rcTNf2.d.ts → loop-runner-BpLTU_J4.d.ts} +2 -2
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +5 -5
- package/dist/{prepare-XWwsOh8O.js → prepare-Bv6X2Wnx.js} +4 -4
- package/dist/{prepare-XWwsOh8O.js.map → prepare-Bv6X2Wnx.js.map} +1 -1
- package/dist/{profile-C01SQZKa.js → profile-Dir2A1_2.js} +2 -2
- package/dist/{profile-C01SQZKa.js.map → profile-Dir2A1_2.js.map} +1 -1
- package/dist/profiles.d.ts +1 -1
- package/dist/{provision-supervisor-CzCFHTxe.js → provision-supervisor-BWEeWag1.js} +8 -6
- package/dist/{provision-supervisor-CzCFHTxe.js.map → provision-supervisor-BWEeWag1.js.map} +1 -1
- package/dist/{run-cancellation-CoJRKvih.js → run-cancellation-Cpm-BIUu.js} +3 -2
- package/dist/{run-cancellation-CoJRKvih.js.map → run-cancellation-Cpm-BIUu.js.map} +1 -1
- package/dist/{runtime-DmdhgaTH.js → runtime-Cnr3213E.js} +18 -15
- package/dist/{runtime-DmdhgaTH.js.map → runtime-Cnr3213E.js.map} +1 -1
- package/dist/{sandbox-profile-compat-CXjozdWL.js → sandbox-profile-compat-DRiz9kME.js} +2 -2
- package/dist/{sandbox-profile-compat-CXjozdWL.js.map → sandbox-profile-compat-DRiz9kME.js.map} +1 -1
- package/dist/{search-executor-Djo4ssci.js → search-executor-__X1VKnU.js} +5 -5
- package/dist/{search-executor-Djo4ssci.js.map → search-executor-__X1VKnU.js.map} +1 -1
- package/dist/{server-DAanPY7z.js → server-CntFSTpW.js} +4 -4
- package/dist/{server-DAanPY7z.js.map → server-CntFSTpW.js.map} +1 -1
- package/dist/{structural-rollout-qqsbQW8M.js → structural-rollout-s8W19Mws.js} +5 -5
- package/dist/{structural-rollout-qqsbQW8M.js.map → structural-rollout-s8W19Mws.js.map} +1 -1
- package/dist/{supervise-DKwnVruI.js → supervise-Cl0F57m9.js} +13 -601
- package/dist/supervise-Cl0F57m9.js.map +1 -0
- package/dist/{supervision-discovery-CewADdEs.js → supervision-discovery-C3t0Xw-T.js} +5 -158
- package/dist/supervision-discovery-C3t0Xw-T.js.map +1 -0
- package/dist/{supervisor-C3JhrVVU.js → supervisor-L7u3pQ1j.js} +84 -140
- package/dist/supervisor-L7u3pQ1j.js.map +1 -0
- package/dist/task-queue-DbpZAp6C.js +49 -0
- package/dist/task-queue-DbpZAp6C.js.map +1 -0
- package/dist/task-queue.js +1 -49
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +13 -13
- package/dist/top-web-CkXPPXjI.js +1114 -0
- package/dist/top-web-CkXPPXjI.js.map +1 -0
- package/dist/tui/bin.js +4 -3
- package/dist/tui/bin.js.map +1 -1
- package/dist/tui/index.d.ts +22 -2
- package/dist/tui/index.js +3 -3
- package/dist/{types-DTHxh4X9.d.ts → types-BfnQq-_k.d.ts} +17 -21
- package/dist/{util-ebWMWzY0.js → util-BX20UJ9X.js} +2 -2
- package/dist/{util-ebWMWzY0.js.map → util-BX20UJ9X.js.map} +1 -1
- package/package.json +11 -11
- package/skills/agent-graphs/references/authoring.md +1 -0
- package/dist/coordination-manager-D-J0Osf4.js.map +0 -1
- package/dist/journal-store-BJPMUydp.js.map +0 -1
- package/dist/supervise-DKwnVruI.js.map +0 -1
- package/dist/supervision-discovery-CewADdEs.js.map +0 -1
- package/dist/supervisor-C3JhrVVU.js.map +0 -1
- package/dist/task-queue.js.map +0 -1
- package/dist/top-snapshot-DcV7VG4m.js +0 -520
- package/dist/top-snapshot-DcV7VG4m.js.map +0 -1
package/dist/durable.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"durable.js","names":["delay"],"sources":["../src/durable/settle-record.ts","../src/durable/pursuit-version-evidence.ts","../src/durable/pursuit-version-review.ts","../src/durable/pursuit-version-run.ts","../src/durable/pursuit-versions.ts","../src/durable/run-fork.ts","../src/durable/run-lock.ts","../src/durable/pursuit-observer-delivery.ts","../src/durable/run-reopen.ts","../src/durable/supervise-pursuit.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { canonicalCandidateDigest, canonicalCandidateJson } from '@tangle-network/agent-interface'\nimport {\n publishExclusiveDurableFile,\n writeAtomicDurableFile,\n} from '../runtime/supervise/durable-file'\nimport type { RootStreamReceipt, SupervisedResult } from '../runtime/supervise/types'\nimport { isNoEntError } from './jsonl-file'\n\n/*\n * The terminal records `supervisePursuit` leaves in a run directory.\n *\n * Measured motive (discovery-lab recursive smoke r1): Runtime settled `no-winner`\n * at 06:27:51Z with a terminal `agent.run` event and returned the result to the caller, and the\n * directory held no terminal record. agent-eval's supervisor-run reader names `result.json` as\n * Runtime's own terminal record and reported `supStatus: unavailable` for that run and for every\n * run on that path. The Lab's re-entry guard checked `result.json`, so it never fired, and a\n * second `run` or `resume` on the settled directory re-entered `supervise` and spent again.\n *\n * `result.json` is the JSON value of the `SupervisedResult` the call returned, as canonical JSON\n * (RFC 8785, stable key order), so its bytes hash to `settleRecordDigest(result)`. A result that\n * carries a value JSON cannot represent faithfully (a Map, a Set, a Date, a typed array, a class\n * instance) is refused rather than silently rewritten, because the file is raw terminal evidence.\n * It is written once per segment with\n * `O_EXCL`, fsynced, and never replaced: a second settle in the same directory is refused before\n * any compute. An explicit reopen (`supervisePursuit`'s `reopen`, `./run-reopen.ts`) archives it\n * byte for byte to `settles/<n>.json` and removes it, and the reopened segment writes its own. `failure.json` records the most recent throw and is replaced by a later throw; the\n * history of every attempt stays in `observer.jsonl`. A failure record alone never blocks\n * re-entry, because r1's first attempt threw on a caller input error before any spawn and the\n * corrected attempt on the same directory produced all of the run's evidence.\n */\n\n/** The settle record: the returned `SupervisedResult` as canonical JSON, written once. */\nexport const SETTLE_RECORD_FILE = 'result.json'\n/** The failure record: the most recent throw, replaced by a later throw. */\nexport const FAILURE_RECORD_FILE = 'failure.json'\n\n/** What `failure.json` records about the most recent throw. */\nexport interface DurableFailureRecord {\n readonly runId: string\n readonly pursuitId: string\n /** ISO instant the throw was recorded. */\n readonly at: string\n readonly error: { readonly name: string; readonly message: string }\n /** The root's retained provider stream at the time of the throw, when the directory holds one:\n * a root that died mid-turn keeps what it had streamed, and this names it. */\n readonly rootStream?: RootStreamReceipt\n}\n\n/** The directory already holds a settle record, so the run it records must not be re-entered. */\nexport class SettledRunDirectoryError extends Error {\n readonly path: string\n /** The root of the recorded run, which is its `runId`. */\n readonly recordedRunId: string\n\n constructor(path: string, recordedRunId: string, requestedRunId: string) {\n super(\n recordedRunId === requestedRunId\n ? `supervisePursuit: ${path} records that run '${recordedRunId}' already settled; a settled run is not re-entered unless the call passes reopen: { operator, reason, operationId }`\n : `supervisePursuit: ${path} records that run '${recordedRunId}' already settled in this directory; a directory holds one settle record, so run '${requestedRunId}' needs its own runDir`,\n )\n this.name = 'SettledRunDirectoryError'\n this.path = path\n this.recordedRunId = recordedRunId\n }\n}\n\n/** A result member whose JSON form would misstate it. */\nclass UnrecordableSettleValueError extends TypeError {\n readonly path: string\n\n constructor(path: string, kind: string) {\n super(\n `supervisePursuit: result${path} is a ${kind}, which JSON cannot record faithfully; a settle record holds plain data only`,\n )\n this.name = 'UnrecordableSettleValueError'\n this.path = path\n }\n}\n\nconst PLAIN_PROTOTYPES = new Set<unknown>([Object.prototype, Array.prototype, null])\n\n/**\n * The JSON value of a result, or a throw naming the first member JSON would misstate. An\n * `undefined` member and a function are dropped, exactly as any JSON consumer drops them; a Map,\n * a Set, a Date, a typed array, or a class instance would be rewritten to `{}` or a string and\n * so is refused.\n */\nfunction jsonValue(result: unknown): unknown {\n const seen: unknown[] = []\n const visit = (value: unknown, path: string): void => {\n if (value === null || typeof value !== 'object') return\n if (value instanceof Map) throw new UnrecordableSettleValueError(path, 'Map')\n if (value instanceof Set) throw new UnrecordableSettleValueError(path, 'Set')\n if (value instanceof Date) throw new UnrecordableSettleValueError(path, 'Date')\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n throw new UnrecordableSettleValueError(path, 'binary buffer')\n }\n if (!PLAIN_PROTOTYPES.has(Object.getPrototypeOf(value))) {\n throw new UnrecordableSettleValueError(path, 'class instance')\n }\n if (seen.includes(value)) throw new UnrecordableSettleValueError(path, 'cycle')\n seen.push(value)\n if (Array.isArray(value)) {\n for (const [index, item] of value.entries()) visit(item, `${path}[${index}]`)\n } else {\n for (const [key, item] of Object.entries(value)) visit(item, `${path}.${key}`)\n }\n seen.pop()\n }\n visit(result, '')\n return JSON.parse(JSON.stringify(result))\n}\n\n/**\n * The exact bytes `result.json` holds for a result: its JSON value serialized as RFC 8785\n * canonical JSON. Throws `UnrecordableSettleValueError` before any byte is written when the\n * result carries a value JSON would misstate.\n */\nexport function settleRecordJson(result: unknown): string {\n return canonicalCandidateJson(jsonValue(result))\n}\n\n/** The digest the settle record's bytes hash to: the candidate digest of the result's JSON value. */\nexport function settleRecordDigest(result: unknown): string {\n return canonicalCandidateDigest(jsonValue(result))\n}\n\n/** Publish `result.json` in the run directory once. Throws when a record is already there. */\nexport async function writeSettleRecord(runDir: string, result: unknown): Promise<string> {\n const path = resolve(runDir, SETTLE_RECORD_FILE)\n if (!publishExclusiveDurableFile(path, settleRecordJson(result))) {\n throw new Error(`supervisePursuit: ${path} already exists; a settle record is written once`)\n }\n return path\n}\n\n/** Replace `failure.json` in the run directory with the most recent throw. */\nexport async function writeFailureRecord(\n runDir: string,\n record: DurableFailureRecord,\n): Promise<string> {\n const path = resolve(runDir, FAILURE_RECORD_FILE)\n writeAtomicDurableFile(path, `${JSON.stringify(record, null, 2)}\\n`)\n return path\n}\n\n/**\n * Read the settle record a run directory holds, or `undefined` when it holds none. A file that\n * is present but is not a settle record is corruption and fails loud.\n */\nexport async function readSettleRecord(\n runDir: string,\n): Promise<SupervisedResult<unknown> | undefined> {\n const path = resolve(runDir, SETTLE_RECORD_FILE)\n let text: string\n try {\n text = await readFile(path, 'utf8')\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\n }\n return parseSettleRecord(text, path)\n}\n\n/** Parse settle-record bytes already read, so a caller hashes and parses the same bytes. */\nexport function parseSettleRecord(text: string, path: string): SupervisedResult<unknown> {\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch (cause) {\n throw new Error(`supervisePursuit: ${path} is not valid JSON`, { cause })\n }\n const record = parsed as { kind?: unknown; tree?: { root?: unknown } }\n if (\n typeof record !== 'object' ||\n record === null ||\n typeof record.kind !== 'string' ||\n typeof record.tree !== 'object' ||\n record.tree === null ||\n typeof record.tree.root !== 'string'\n ) {\n throw new Error(`supervisePursuit: ${path} is not a settle record (no kind or tree.root)`)\n }\n return parsed as SupervisedResult<unknown>\n}\n\n/** Read the most recent failure record, or `undefined` when the directory holds none. */\nexport async function readFailureRecord(runDir: string): Promise<DurableFailureRecord | undefined> {\n const path = resolve(runDir, FAILURE_RECORD_FILE)\n let text: string\n try {\n text = await readFile(path, 'utf8')\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch (cause) {\n throw new Error(`supervisePursuit: ${path} is not valid JSON`, { cause })\n }\n const record = parsed as Partial<DurableFailureRecord>\n if (\n typeof record !== 'object' ||\n record === null ||\n typeof record.runId !== 'string' ||\n typeof record.pursuitId !== 'string' ||\n typeof record.at !== 'string' ||\n typeof record.error?.name !== 'string' ||\n typeof record.error.message !== 'string' ||\n (record.rootStream !== undefined &&\n (typeof record.rootStream.ref !== 'string' || typeof record.rootStream.events !== 'number'))\n ) {\n throw new Error(`supervisePursuit: ${path} is not a failure record`)\n }\n return parsed as DurableFailureRecord\n}\n","// Sealed pursuit-version results, identity checks and settled outcome evidence.\n\nimport { access, readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport type {\n SearchArtifactRef,\n SearchAttemptAccounting,\n SearchNode,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { RuntimeRunStateError, ValidationError } from '../errors'\nimport { isFiniteNumber } from '../finite-number'\nimport type { Spend, SupervisedResult } from '../runtime/supervise/types'\nimport { errorMessage } from '../runtime/util'\nimport { isNoEntError } from './jsonl-file'\nimport type { JudgedPursuitVersion, VersionVerdict } from './pursuit-versions'\nimport { parseSettleRecord, SETTLE_RECORD_FILE } from './settle-record'\n\n/** The chain's directory beside the first version's: the ledger and its content blobs. */\nexport function pursuitVersionsLedgerPath(runDir: string): string {\n return resolve(`${resolve(runDir.trim())}.search`, 'ledger.jsonl')\n}\n\n/** A search node's artifact: a version's profile, or a change that did not apply. */\nexport interface VersionNode {\n readonly profile: AgentProfile | null\n /** The change from the parent; set on a node a proposal returned in this process. */\n readonly change?: AgentProfileDiff\n readonly parentDigest?: Sha256Digest\n readonly refusal: string | null\n}\n\n/** One node of the chain, as the ledger records it. */\nexport interface VersionRecord {\n readonly nodeId: string\n readonly version: number\n readonly runId: string\n readonly runDir: string\n /** Null for a change that did not apply. */\n readonly profile: AgentProfile | null\n readonly parentNodeId: string | null\n /** The change from the parent, from the node's first edge. */\n readonly change?: AgentProfileDiff\n /** The settled attempt's seal and verdict. */\n readonly seal?: SearchArtifactRef\n readonly verdict?: VersionVerdict\n}\n\n/** The bytes of a version's sealed `result.json` and the record they hold, parsed from the same\n * bytes that are hashed. */\nexport async function readSealed(\n runDir: string,\n version: number,\n): Promise<{ bytes: Uint8Array; result: SupervisedResult<unknown> }> {\n const path = resolve(runDir, SETTLE_RECORD_FILE)\n let bytes: Uint8Array\n try {\n bytes = await readFile(path)\n } catch (error) {\n if (!isNoEntError(error)) throw error\n throw new RuntimeRunStateError(\n `supervisePursuit versions: version ${version} has no settle record in ${runDir}`,\n )\n }\n return { bytes, result: parseSettleRecord(Buffer.from(bytes).toString('utf8'), path) }\n}\n\n/** A profile as the JSON the ledger stores: validated, with undefined entries absent. */\nexport function jsonProfile(profile: unknown): AgentProfile {\n canonicalAgentProfileDigest(profile as AgentProfile)\n return JSON.parse(JSON.stringify(agentProfileSchema.parse(profile))) as AgentProfile\n}\n\nexport function loadNode(\n store: { readBlob(ref: SearchArtifactRef): unknown },\n node: SearchNode,\n): VersionNode {\n const stored = store.readBlob(node.artifact) as {\n kind?: unknown\n profile?: unknown\n change?: AgentProfileDiff | null\n parentDigest?: Sha256Digest | null\n refusal?: string | null\n }\n if (stored.kind === 'agent-profile') {\n const parsed = agentProfileSchema.safeParse(stored.profile)\n if (!parsed.success) {\n throw new RuntimeRunStateError(`version node ${node.nodeId} holds an invalid AgentProfile`)\n }\n return { profile: parsed.data as AgentProfile, refusal: null }\n }\n if (stored.kind === 'unapplied-change') {\n return {\n profile: null,\n ...(stored.change ? { change: stored.change } : {}),\n ...(stored.parentDigest ? { parentDigest: stored.parentDigest } : {}),\n refusal: stored.refusal ?? 'the change did not apply',\n }\n }\n throw new RuntimeRunStateError(`version node ${node.nodeId} holds no version artifact`)\n}\n\n/** The `<runDir>.v<n>` directory and `<runId>.v<n>` id of version `n`, beside the first. */\nexport function versionRun(runDir: string, runId: string, version: number) {\n return version === 1\n ? { runDir, runId }\n : { runDir: `${runDir}.v${version}`, runId: `${runId}.v${version}` }\n}\n\n/** A version's settled spend as the ledger's accounting. Unknown dollars carry the part a\n * provider is known to have billed as their floor. */\nexport function versionAccounting(spent: Spend | undefined): SearchAttemptAccounting {\n const tokensKnown =\n spent !== undefined &&\n spent.tokensKnown !== false &&\n spent.tokens?.tokensKnown !== false &&\n Number.isSafeInteger(spent.tokens?.input) &&\n Number.isSafeInteger(spent.tokens?.output) &&\n Number.isSafeInteger(spent.tokens?.cacheRead)\n const usdKnown = spent !== undefined && spent.usdKnown !== false && isFiniteNumber(spent.usd)\n return {\n tokens: tokensKnown\n ? {\n status: 'known',\n inputTokens: spent.tokens.input,\n outputTokens: spent.tokens.output,\n cachedTokens: spent.tokens.cacheRead!,\n }\n : {\n status: 'unknown',\n reason: `the version's settled spend reports no complete token count with its cache split (input ${spent?.tokens?.input ?? 'none'}, output ${spent?.tokens?.output ?? 'none'})`,\n },\n cost: usdKnown\n ? { status: 'known', usd: spent.usd, source: 'provider' }\n : {\n status: 'unknown',\n knownLowerBoundUsd: Math.max(\n 0,\n isFiniteNumber(spent?.usd) ? spent.usd - (spent.usdEstimated ?? 0) : 0,\n ),\n reason: \"the version's settled spend names unpriced or unreported work\",\n },\n }\n}\n\n/** How long a version that settled before its chain opened ran, from its settle record. */\nexport function settledElapsed(settled: SupervisedResult<unknown> | undefined): number {\n const elapsed = settled?.spentTotal?.ms\n return isFiniteNumber(elapsed) ? elapsed : 0\n}\n\nexport const FREE: SearchAttemptAccounting = {\n tokens: { status: 'known', inputTokens: 0, outputTokens: 0, cachedTokens: 0 },\n cost: { status: 'known', usd: 0, source: 'free' },\n}\n\n/**\n * What a version that did no work failed with: a driver error, by its name and its message with\n * the parts that differ between runs (digits, hex runs, absolute paths) normalized, or an unscored\n * verdict. Null for a version that ran, won or not.\n */\nexport function versionFailure(version: JudgedPursuitVersion): string | null {\n if (version.verdict.score === null) return 'unscored by the judge'\n const { result } = version\n if (result.kind !== 'no-winner' || result.reason !== 'driver-failed') return null\n const message = result.error.message\n .replace(/(?:\\/[\\w.@~+-]+){2,}/gu, '<path>')\n .replace(/\\b[0-9a-f]{8,}\\b/giu, '<hex>')\n .replace(/\\d+/gu, '<n>')\n .slice(0, 500)\n return `driver-failed: ${result.error.name}: ${message}`\n}\n\nexport function pursuitValueDigest(value: unknown, name: string): Sha256Digest {\n try {\n return canonicalCandidateDigest(value)\n } catch (error) {\n throw new ValidationError(\n `supervisePursuit versions: the ${name} must be canonical JSON to pin the chain: ${errorMessage(error)}`,\n )\n }\n}\n\nexport async function exists(path: string): Promise<boolean> {\n try {\n await access(path)\n return true\n } catch (error) {\n if (isNoEntError(error)) return false\n throw error\n }\n}\n\nexport function isSha256(value: unknown): value is Sha256Digest {\n return typeof value === 'string' && /^sha256:[0-9a-f]{64}$/u.test(value)\n}\n","// Profile review instructions and their mounted verdict page.\n\nimport type { AgentProfileDiff } from '@tangle-network/agent-interface'\nimport type { CheckVerdict } from '../runtime/supervise/completion-gate'\nimport { failedItems } from '../runtime/supervise/continuation'\nimport type { NextPursuitVersion } from './pursuit-versions'\n\n/** Where `'review-of-best'` mounts a review: `inputs/review/version-<n>.md`. One review lives in\n * a profile at a time. */\nconst REVIEW_DIR = 'inputs/review/'\n\n/**\n * `'review-of-best'`: fork from the kept version with its check's verdict mounted under\n * {@link REVIEW_DIR} and the profile's review words as one instruction. The previous review's\n * mount and instruction are removed, so a profile carries one review.\n */\nexport function reviewOfBest(runId: string, words: string): NextPursuitVersion {\n return ({ best, versions }) => {\n const n = versions.length + 1\n const verdict = best.verdict.check\n const path = `${REVIEW_DIR}version-${best.version}.md`\n const instruction = words\n .replaceAll('{version}', String(best.version))\n .replaceAll('{path}', path)\n .replaceAll('{score}', best.verdict.score === null ? 'none' : String(best.verdict.score))\n .trim()\n const page = reviewPage(best.version, best.verdict.score, verdict)\n // Instructions are set and removed by value: an earlier review instruction equal to this one\n // stays as it is, and every other earlier one is removed.\n const earlier = best.change?.set?.prompt?.instructions ?? []\n const earlierInstructions = earlier.filter((text) => text !== instruction)\n const earlierMounts = (best.profile.resources?.files ?? [])\n .map((file) => file.path)\n .filter((mounted) => mounted.startsWith(REVIEW_DIR) && mounted !== path)\n return {\n kind: 'agent-profile-diff',\n id: `${runId}-v${n}-review-of-v${best.version}`,\n title: `Version ${n}: review of version ${best.version}`,\n source: {\n kind: 'optimizer',\n notes: [`review-of-best: version ${best.version}`, `judge ${best.verdict.judgeDigest}`],\n },\n set: {\n ...(earlier.includes(instruction) ? {} : { prompt: { instructions: [instruction] } }),\n resources: {\n files: [{ path, resource: { kind: 'inline', name: path, content: page } }],\n },\n },\n ...(earlierInstructions.length > 0 || earlierMounts.length > 0\n ? {\n remove: {\n ...(earlierInstructions.length > 0\n ? { prompt: { instructions: [...earlierInstructions] } }\n : {}),\n ...(earlierMounts.length > 0 ? { resources: { files: earlierMounts } } : {}),\n },\n }\n : {}),\n } as AgentProfileDiff\n }\n}\n\n/** The review page: facts only, in the check's own lines. */\nfunction reviewPage(\n version: number,\n score: number | null,\n verdict: CheckVerdict | undefined,\n): string {\n if (verdict === undefined) {\n return [\n `# Version ${version}`,\n '',\n `Score: ${score ?? 'none'}. The judge reported no per-item verdict.`,\n '',\n ].join('\\n')\n }\n const failing = failedItems(verdict)\n return [\n `# Version ${version}`,\n '',\n `Score: ${score ?? 'none'}.${verdict.threshold === undefined ? '' : ` The check passes at ${verdict.threshold}.`}`,\n '',\n '## Items',\n '',\n ...Object.entries(verdict.items ?? {}).map(\n ([item, value]) => `- ${item}: ${value >= 1 ? 'passes' : `fails (${value})`}`,\n ),\n '',\n ...(failing.length === 0 ? [] : ['## Failures', '', ...(verdict.failures ?? []), '']),\n ...(verdict.review === undefined ? [] : [\"## The check's review\", '', verdict.review, '']),\n ].join('\\n')\n}\n","/**\n * One pursuit version chain at run time: running a version in its directory, reading it back\n * and checking it is this node's run, judging it, turning it into the kernel's cell result, and\n * reading the chain back from its search ledger.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport {\n parseSearchLedgerLine,\n type SearchCellResult,\n type SearchCellSettledEvent,\n type SearchCellWork,\n type SearchExecutionIdentity,\n type SearchRecorder,\n type SearchTaskOutcome,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n canonicalAgentProfileDigest,\n type Sha256Digest,\n sha256Bytes,\n} from '@tangle-network/agent-interface'\nimport { RuntimeRunStateError, ValidationError } from '../errors'\nimport { isFiniteNumber } from '../finite-number'\nimport { authoredProfileDigest } from '../runtime/supervise/materialization'\nimport { superviseRootProfile } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { SpawnEvent, SupervisedResult } from '../runtime/supervise/types'\nimport { errorMessage } from '../runtime/util'\nimport { contentAddress } from './content-address'\nimport {\n loadNode,\n readSealed,\n type VersionNode,\n type VersionRecord,\n versionAccounting,\n versionRun,\n} from './pursuit-version-evidence'\nimport type {\n JudgedPursuitVersion,\n SettledPursuitVersion,\n VersionJudge,\n VersionVerdict,\n} from './pursuit-versions'\nimport type { PursuitFork } from './run-fork'\nimport { readSettleRecord, SETTLE_RECORD_FILE } from './settle-record'\nimport { FileSpawnJournal } from './spawn-journal/journal-store'\nimport type { SupervisedPursuitResult, SupervisePursuitOptions } from './supervise-pursuit'\n\nexport type RunOne = (\n profile: SupervisorProfile,\n task: unknown,\n opts: SupervisePursuitOptions,\n) => Promise<SupervisedPursuitResult<SupervisedResult<unknown>>>\n\n/** What one chain's versions share. */\nexport interface VersionChainContext {\n readonly profile: SupervisorProfile\n readonly task: unknown\n /** The call's options without the fields each version sets for itself. */\n readonly base: Omit<SupervisePursuitOptions, 'versions' | 'fork' | 'signal'>\n readonly firstFork: PursuitFork | undefined\n readonly runOne: RunOne\n readonly judge: VersionJudge\n readonly recorder: SearchRecorder\n /** Aborts a running version when the chain reaches its deadline. */\n readonly expired: AbortSignal\n readonly pursuitId: string\n readonly runDir: string\n readonly runId: string\n readonly ledgerPath: string\n readonly searchId: string\n readonly taskRevision: string\n}\n\n/** The execution identity a version's node and cell record. */\nexport function versionExecutionIdentity(\n pursuitId: string,\n taskRevision: string,\n nodeProfile: AgentProfile,\n): SearchExecutionIdentity {\n return {\n model: {\n provider: 'agent-runtime',\n alias: 'supervisePursuit',\n unknown: \"a version runs every model its tree chose; the version's settle record names them\",\n },\n agent: {\n uri: `agent-profile:${pursuitId}`,\n revision: canonicalAgentProfileDigest(nodeProfile),\n },\n benchmark: { uri: `pursuit:${pursuitId}`, revision: taskRevision },\n }\n}\n\n/** A version as the judge and `next` read it. */\nfunction versionOf(\n record: VersionRecord,\n parent: VersionRecord | undefined,\n settleDigest: Sha256Digest,\n result: SupervisedResult<unknown>,\n): SettledPursuitVersion {\n return Object.freeze({\n version: record.version,\n nodeId: record.nodeId,\n runId: record.runId,\n runDir: record.runDir,\n settleDigest,\n result,\n profile: record.profile!,\n ...(parent?.seal === undefined\n ? {}\n : {\n parent: {\n version: parent.version,\n runId: parent.runId,\n settleDigest: parent.seal.sha256 as Sha256Digest,\n },\n }),\n ...(record.change === undefined ? {} : { change: record.change }),\n })\n}\n\nfunction outcomeOf(settled: SettledPursuitVersion, verdict: VersionVerdict): SearchTaskOutcome {\n if (verdict.score === null) {\n return {\n status: 'errored',\n metrics: {},\n error: {\n code: 'unscored',\n message: `the judge could not score version ${settled.version}`,\n retryable: false,\n },\n }\n }\n if (settled.result.kind === 'winner') {\n return { status: 'passed', score: verdict.score, metrics: {} }\n }\n return {\n status: 'failed',\n score: verdict.score,\n metrics: {},\n failure: {\n code: settled.result.reason,\n message: `version ${settled.version} settled without a winner: ${settled.result.reason}`,\n },\n }\n}\n\nexport class VersionChainRun {\n // Each sealed result.json is read and hashed once per call.\n private readonly sealed = new Map<Sha256Digest, SupervisedResult<unknown>>()\n\n constructor(private readonly ctx: VersionChainContext) {}\n\n /** Run a version if its directory holds no settle record, read it back, and judge it. */\n async runCell(work: SearchCellWork<VersionNode>): Promise<SearchCellResult> {\n const chain = await this.versionsOf()\n const record = chain.get(work.nodeId)\n if (record?.profile == null) {\n throw new RuntimeRunStateError(`version node ${work.nodeId} has no profile to run`)\n }\n const parent = record.parentNodeId === null ? undefined : chain.get(record.parentNodeId)\n if (parent !== undefined && (parent.seal === undefined || parent.profile === null)) {\n throw new RuntimeRunStateError(`version ${record.version}'s parent has no sealed result`)\n }\n // A version whose run throws fails the call and leaves its cell open: Runtime's driver\n // retry already ran, and calling again resumes the version in its own directory.\n if ((await readSettleRecord(record.runDir)) === undefined) {\n const signal = AbortSignal.any([work.signal, this.ctx.expired])\n if (signal.aborted) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: version ${record.version} was not started: ${errorMessage(signal.reason)}`,\n )\n }\n await this.runVersion(record, parent, signal)\n }\n const { settled, byteLength } = await this.readVersion(record, parent)\n const verdict = await this.judgeVersion(settled, work.signal)\n return this.cellResult(settled, byteLength, verdict, work.lane)\n }\n\n /** Run one version: the first as the call's own run, a later one as a fork of its parent. */\n private async runVersion(\n record: VersionRecord,\n parent: VersionRecord | undefined,\n signal: AbortSignal,\n ): Promise<void> {\n const { profile, task, base, firstFork, runOne } = this.ctx\n if (parent === undefined || record.change === undefined) {\n await runOne(profile, task, {\n ...base,\n runId: record.runId,\n runDir: record.runDir,\n ...(firstFork === undefined ? {} : { fork: firstFork }),\n signal,\n })\n return\n }\n // A version starts a new tree and never replays its parent's children, so a parent that\n // settled with a child still in doubt (a deadline or a driver failure leaves them) is forked,\n // and the version's root records those nodes.\n const fork: PursuitFork = {\n runDir: parent.runDir,\n settleDigest: parent.seal!.sha256 as Sha256Digest,\n change: record.change,\n acceptUncertain: true,\n }\n // The version's continuation note states the bar against the version it forks from.\n const check = parent.verdict?.check\n await runOne(parent.profile!, task, {\n ...base,\n ...(base.continuation !== undefined && check !== undefined\n ? {\n continuation: {\n ...base.continuation,\n best: { label: `v${parent.version}`, verdict: check },\n },\n }\n : {}),\n runId: record.runId,\n runDir: record.runDir,\n fork,\n signal,\n })\n }\n\n /**\n * Read a settled version back and check it is this node's run: its root ran the node's profile\n * and, for a fork, recorded the parent's seal and the change. A directory that holds another\n * run is refused, never adopted.\n */\n private async readVersion(\n record: VersionRecord,\n parent: VersionRecord | undefined,\n ): Promise<{ settled: SettledPursuitVersion; byteLength: number }> {\n const { base, firstFork, taskRevision } = this.ctx\n const { bytes, result } = await readSealed(record.runDir, record.version)\n if (result.tree.root !== record.runId) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: ${record.runDir} holds run '${result.tree.root}', not version ${record.version}'s '${record.runId}'`,\n )\n }\n const events = await new FileSpawnJournal(\n resolve(record.runDir, 'spawn-journal.jsonl'),\n ).loadTree(record.runId)\n const root = events?.find(\n (event): event is Extract<SpawnEvent, { kind: 'spawned' }> =>\n event.kind === 'spawned' && event.parent === undefined,\n )\n const ran = root?.identity?.profileDigest\n const expected = authoredProfileDigest(\n superviseRootProfile(record.profile!, base.profileGuidance),\n )\n const ranTask = root?.identity?.taskDigest\n const correlation = root?.identity?.correlation\n const fork =\n parent !== undefined\n ? { settleDigest: parent.seal?.sha256, changeId: record.change?.id }\n : firstFork === undefined\n ? undefined\n : { settleDigest: firstFork.settleDigest, changeId: firstFork.change.id }\n const mismatch = [\n ran !== expected ? `its root ran profile ${ran}, not ${expected}` : undefined,\n ranTask !== taskRevision ? `its root ran task ${ranTask}, not ${taskRevision}` : undefined,\n contentAddress(root?.budget) !== contentAddress(base.budget)\n ? 'its root ran under another budget'\n : undefined,\n fork !== undefined && correlation?.forkParentSettleDigest !== fork.settleDigest\n ? `its root forked from seal ${correlation?.forkParentSettleDigest}, not ${fork.settleDigest}`\n : undefined,\n fork !== undefined && correlation?.forkProfileDiffId !== fork.changeId\n ? `its root applied change ${correlation?.forkProfileDiffId}, not ${fork.changeId}`\n : undefined,\n ].filter((item): item is string => item !== undefined)\n if (mismatch.length > 0) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: version ${record.version} at ${record.runDir} is not this chain's run: ${mismatch.join('; ')}`,\n )\n }\n const settled = versionOf(record, parent, sha256Bytes(bytes), result)\n this.sealed.set(settled.settleDigest, result)\n return { settled, byteLength: bytes.byteLength }\n }\n\n private async judgeVersion(\n settled: SettledPursuitVersion,\n signal: AbortSignal,\n ): Promise<VersionVerdict> {\n const { judge } = this.ctx\n const verdict = await judge.judge(settled, signal)\n if (typeof verdict !== 'object' || verdict === null) {\n throw new ValidationError('supervisePursuit versions: the judge returned no verdict')\n }\n if (verdict.judgeDigest !== judge.digest) {\n throw new ValidationError(\n `supervisePursuit versions: the verdict for version ${settled.version} carries ${String(verdict.judgeDigest)}, not the pinned judge ${judge.digest}`,\n )\n }\n if (verdict.score !== null && !isFiniteNumber(verdict.score)) {\n throw new ValidationError(\n 'supervisePursuit versions: a verdict score must be a finite number or null',\n )\n }\n // The ledger keeps the verdict as JSON; a value JSON cannot hold is refused here.\n return JSON.parse(JSON.stringify(verdict)) as VersionVerdict\n }\n\n private cellResult(\n settled: SettledPursuitVersion,\n byteLength: number,\n verdict: VersionVerdict,\n lane: string,\n ): SearchCellResult {\n const spent = settled.result.spentTotal\n const settlePath = resolve(settled.runDir, SETTLE_RECORD_FILE)\n return {\n outcome: outcomeOf(settled, verdict),\n accounting: versionAccounting(spent),\n identity: versionExecutionIdentity(\n this.ctx.pursuitId,\n this.ctx.taskRevision,\n settled.profile,\n ),\n boxMinutes:\n isFiniteNumber(spent.boxMinutes) && spent.boxMinutesKnown !== false\n ? spent.boxMinutes\n : null,\n wallMs: isFiniteNumber(spent.ms) ? Math.max(0, Math.round(spent.ms)) : null,\n placement: { lane, boxId: null },\n traceRef: {\n unknown: `version ${settled.version} is run ${settled.runId}; the chain records no trace id`,\n },\n artifacts: [\n {\n role: 'settle-record',\n uri: pathToFileURL(settlePath).href,\n sha256: settled.settleDigest,\n byteLength,\n },\n this.ctx.recorder.blob('verdict', {\n kind: 'version-verdict',\n version: settled.version,\n runId: settled.runId,\n verdict,\n }),\n ],\n }\n }\n\n /** Every version whose latest settled cell carries a verdict, first first, each read back from\n * its sealed `result.json`. */\n async judgedVersions(chain: ReadonlyMap<string, VersionRecord>): Promise<JudgedPursuitVersion[]> {\n const judged: JudgedPursuitVersion[] = []\n for (const record of chain.values()) {\n if (record.seal === undefined || record.verdict === undefined) continue\n const seal = record.seal.sha256 as Sha256Digest\n let result = this.sealed.get(seal)\n if (result === undefined) {\n const read = await readSealed(record.runDir, record.version)\n if (sha256Bytes(read.bytes) !== seal) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: version ${record.version}'s result.json changed after it was judged`,\n )\n }\n result = read.result\n this.sealed.set(seal, result)\n }\n const parent = record.parentNodeId === null ? undefined : chain.get(record.parentNodeId)\n judged.push(\n Object.freeze({ ...versionOf(record, parent, seal, result), verdict: record.verdict }),\n )\n }\n return judged\n }\n\n /**\n * Every node of the chain, in registration order, from the ledger. The state holds cells, not\n * their events' artifacts, so each cell's seal and verdict are read from the ledger lines the\n * state verified, through Eval's own line parser.\n */\n async versionsOf(): Promise<Map<string, VersionRecord>> {\n const { recorder, ledgerPath, searchId, runDir, runId } = this.ctx\n // Take what the state holds before any await: an append retires the view.\n const state = await recorder.state()\n const head = state.head?.sequence ?? -1\n const nodes = state.nodes().map((node) => ({\n node,\n cellId: state.cells({ nodeId: node.nodeId })[0]?.cellId,\n diff: node.edgeIds[0] === undefined ? undefined : state.edge(node.edgeIds[0])?.diffs[0],\n }))\n const settledCells = new Map<string, SearchCellSettledEvent>()\n const text = await readFile(ledgerPath, 'utf8')\n for (const [index, line] of text.split('\\n').entries()) {\n if (line.length === 0) continue\n const entry = parseSearchLedgerLine(line, searchId, { path: ledgerPath, line: index + 1 })\n if (entry.sequence > head) break\n if (entry.event.kind === 'cell-settled') settledCells.set(entry.event.cellId, entry.event)\n }\n const chain = new Map<string, VersionRecord>()\n for (const { node, cellId, diff } of nodes) {\n const settled = cellId === undefined ? undefined : settledCells.get(cellId)\n const artifact = (role: string) =>\n settled?.artifacts.find((candidate) => candidate.role === role)\n const seal = artifact('settle-record')\n const verdict = artifact('verdict')\n chain.set(node.nodeId, {\n nodeId: node.nodeId,\n version: node.ordinal + 1,\n ...versionRun(runDir, runId, node.ordinal + 1),\n profile: loadNode(recorder, node).profile,\n parentNodeId: node.primaryParentId,\n ...(diff === undefined || 'unknown' in diff\n ? {}\n : { change: (recorder.readBlob(diff) as { diffs: AgentProfileDiff[] }).diffs[0]! }),\n ...(seal === undefined ? {} : { seal }),\n ...(verdict === undefined\n ? {}\n : { verdict: (recorder.readBlob(verdict) as { verdict: VersionVerdict }).verdict }),\n })\n }\n return chain\n }\n}\n","/**\n * The pursuit version chain, on Eval's search kernel (`runSearch`).\n *\n * A version is a search node: the exact AgentProfile it executes, content-addressed by\n * `canonicalAgentProfileDigest`. Every later version is an edge from the version the chain keeps,\n * whose diff is the one change `next` returned, and one cell: a `supervisePursuit` run of the\n * version, forked from its parent's sealed `result.json`, then scored by the outside judge. The\n * policy is the kernel's hill climb, `incumbent({ patience, minImprovement })`. The search ledger\n * at `<runDir>.search/ledger.jsonl` is the chain's only record and its only checkpoint: a call on\n * a closed chain reads it back, and a call on an open chain continues it.\n */\n\nimport { resolve } from 'node:path'\nimport {\n developmentClaim,\n incumbent,\n openSearchLedger,\n runSearch,\n type SearchArtifactCodec,\n type SearchAudit,\n type SearchCloseReason,\n type SearchExecutor,\n type SearchHistoryReceipt,\n type SearchProposerPort,\n SearchRecorder,\n type SearchSourceRef,\n uniform,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { applyExactAgentProfileDiff } from '../candidate-execution/profile'\nimport { RuntimeRunStateError, ValidationError } from '../errors'\nimport { isFiniteNumber } from '../finite-number'\nimport type { CheckVerdict } from '../runtime/supervise/completion-gate'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { SupervisedResult } from '../runtime/supervise/types'\nimport { errorMessage } from '../runtime/util'\nimport { FileObserverJournal } from './observer-journal'\nimport { projectPursuit } from './observer-projection'\nimport {\n exists,\n FREE,\n isSha256,\n jsonProfile,\n loadNode,\n pursuitValueDigest,\n pursuitVersionsLedgerPath,\n settledElapsed,\n type VersionNode,\n versionFailure,\n} from './pursuit-version-evidence'\nimport { reviewOfBest } from './pursuit-version-review'\nimport { type RunOne, VersionChainRun, versionExecutionIdentity } from './pursuit-version-run'\nimport { readSettleRecord, SETTLE_RECORD_FILE } from './settle-record'\nimport type { SupervisedPursuitResult, SupervisePursuitOptions } from './supervise-pursuit'\n\n/**\n * Continue a pursuit across versions: after each version settles, an outside judge scores it, and\n * the next version forks from the version the chain keeps with one change, until the stop rule\n * ends the chain.\n */\nexport interface PursuitVersions {\n /** Scores each settled version from outside its tree: the run's declared check\n * (`declaredCheckJudge`), or any judge with a digest. */\n readonly judge: VersionJudge\n /** The change the next version applies to the kept version's profile. `'review-of-best'`\n * mounts the kept version's verdict under `inputs/review/`, replaces any earlier review, and\n * gives the next version's continuation note the kept version's per-item verdict as its bar. */\n readonly next: NextPursuitVersion | 'review-of-best'\n /** When the chain stops. Every cap is required: a chain without one is refused. */\n readonly stop: PursuitVersionStop\n}\n\n/** The chain's stop rule. The chain starts no version its caps do not admit. */\nexport interface PursuitVersionStop {\n /** Stop after this many proposed versions in a row that did not take the lead. */\n readonly patience: number\n /** At most this many versions, the first included. A change the chain refuses counts as one. */\n readonly maxVersions: number\n /**\n * The chain's dollars: a version starts only while settled spend plus a hold for it stays\n * within this. A version's unknown spend counts as its proven floor. The hold is the version's\n * own `budget.maxUsd`, which bounds it in flight; without one it is 0 until 20 versions\n * settled, then 1.5 times the p99 of their spend.\n */\n readonly maxUsd: number\n /** The chain's wall clock, from its first version's start. A running version is aborted at it. */\n readonly deadlineMs: number\n /** A version takes the lead when its score beats the kept version's by more than this.\n * Default 0. */\n readonly minImprovement?: number\n /**\n * Stop after this many versions in a row failed identically: each run ended `driver-failed`\n * with the same error, or the judge could not score it. Such a failure repeats whatever the\n * next change is (a refused workspace file, a broken credential), so neither patience nor a\n * version cap should be what stops it. Default 3.\n */\n readonly identicalFailures?: number\n}\n\n/** An outside judge. Runtime calls it after a version's settle record exists, never inside the\n * version's tree, and gives it no handle into that tree. Place it where you like, such as its own\n * sandbox through `runIsolatedCheck({ box })`. */\nexport interface VersionJudge {\n /** The sha256 of the judge's code and configuration. Every verdict must carry it, and a chain\n * whose ledger was opened under another digest is refused. */\n readonly digest: Sha256Digest\n judge(version: SettledPursuitVersion, signal: AbortSignal): Promise<VersionVerdict>\n}\n\nexport interface VersionVerdict {\n /** Higher is better. `null` when the judge could not score the version: the cell is recorded\n * unscored, and an unscored version never takes the lead. */\n readonly score: number | null\n /** Must equal `VersionJudge.digest`. */\n readonly judgeDigest: Sha256Digest\n /** What the judge measured, retained verbatim in the ledger. JSON values only. */\n readonly detail?: unknown\n /** The check's per-item verdict, when the judge is a check: what `'review-of-best'` mounts and\n * what the next version's bar compares against. */\n readonly check?: CheckVerdict\n}\n\n/** A settled version, as the judge and `next` read it. */\nexport interface SettledPursuitVersion {\n /** 1 for the first version: the node's registration ordinal plus 1. */\n readonly version: number\n /** The version's node in the chain's search ledger. */\n readonly nodeId: string\n readonly runId: string\n readonly runDir: string\n /** The sha256 of the version's `result.json` bytes: its seal. */\n readonly settleDigest: Sha256Digest\n readonly result: SupervisedResult<unknown>\n /** The profile the version executed: the first version's, or its parent's plus its change. */\n readonly profile: AgentProfile\n /** The version it forked from. Absent for the first version. */\n readonly parent?: {\n readonly version: number\n readonly runId: string\n readonly settleDigest: Sha256Digest\n }\n readonly change?: AgentProfileDiff\n}\n\nexport interface JudgedPursuitVersion extends SettledPursuitVersion {\n readonly verdict: VersionVerdict\n}\n\nexport interface NextPursuitVersionInput {\n /** The version the next one forks from: the version the chain keeps. */\n readonly best: JudgedPursuitVersion\n /** The most recently judged version. */\n readonly last: JudgedPursuitVersion\n /** Every judged version, first first. */\n readonly versions: readonly JudgedPursuitVersion[]\n}\n\n/** Build the one change the next version applies to `best.profile`. Its `id` must be non-empty. */\nexport type NextPursuitVersion = (\n input: NextPursuitVersionInput,\n signal: AbortSignal,\n) => AgentProfileDiff | Promise<AgentProfileDiff>\n\n/** The chain as its search ledger records it, returned beside the kept version's result. */\nexport interface PursuitVersionChain {\n /** `<runDir>.search/ledger.jsonl`: the chain's only record and checkpoint. */\n readonly ledgerPath: string\n readonly searchId: string\n /** Why the chain stopped: the kernel's close reason (`patience`, `max-nodes`, `budget`,\n * `deadline` or `converged`). */\n readonly reason: SearchCloseReason\n /** Present when the chain stopped because its last `versions` versions failed identically\n * (`stop.identicalFailures`); `reason` is then `converged`. */\n readonly identicalFailures?: { readonly versions: number; readonly failure: string }\n /** The kept version's number: the kernel's leader when the chain closed. */\n readonly best: number\n /** Every judged version, first first. */\n readonly versions: readonly JudgedPursuitVersion[]\n /** Known dollars, proven floors of unknown ones, and the counts of each. */\n readonly spend: SearchAudit['spend']\n /** A bounded receipt over the exact ledger bytes. */\n readonly receipt: SearchHistoryReceipt\n}\n\n/**\n * Validate a `versions` option before any compute. The same check runs inside `supervisePursuit`;\n * a caller that records the option as data can run it at preflight.\n */\nexport function assertPursuitVersions(versions: unknown): asserts versions is PursuitVersions {\n const fail = (message: string): never => {\n throw new ValidationError(`supervisePursuit versions: ${message}`)\n }\n if (typeof versions !== 'object' || versions === null) fail('must be an object')\n const option = versions as Record<string, unknown>\n const extra = Object.keys(option).filter((key) => !['judge', 'next', 'stop'].includes(key))\n if (extra.length > 0) fail(`unknown fields: ${extra.join(', ')}`)\n const { judge, next, stop } = option\n if (\n typeof judge !== 'object' ||\n judge === null ||\n typeof (judge as VersionJudge).judge !== 'function'\n ) {\n fail('judge must be a VersionJudge, such as declaredCheckJudge(check)')\n } else if (!isSha256((judge as VersionJudge).digest)) {\n fail('judge.digest must be a sha256 digest (sha256:<64 hex>)')\n }\n if (next !== 'review-of-best' && typeof next !== 'function') {\n fail(\"next must be a function or 'review-of-best'\")\n }\n if (typeof stop !== 'object' || stop === null) fail('stop must be an object')\n const rule = stop as Record<string, unknown>\n const known = new Set([\n 'patience',\n 'maxVersions',\n 'maxUsd',\n 'deadlineMs',\n 'minImprovement',\n 'identicalFailures',\n ])\n const unknown = Object.keys(rule).filter((key) => !known.has(key))\n if (unknown.length > 0) fail(`stop has unknown fields: ${unknown.join(', ')}`)\n for (const key of ['patience', 'maxVersions'] as const) {\n if (!Number.isInteger(rule[key]) || (rule[key] as number) < 1) {\n fail(`stop.${key} must be an integer of at least 1`)\n }\n }\n if (\n rule.identicalFailures !== undefined &&\n (!Number.isInteger(rule.identicalFailures) || (rule.identicalFailures as number) < 1)\n ) {\n fail('stop.identicalFailures must be an integer of at least 1')\n }\n for (const key of ['maxUsd', 'deadlineMs'] as const) {\n if (!isFiniteNumber(rule[key]) || (rule[key] as number) <= 0) {\n fail(`stop.${key} must be a finite number above 0`)\n }\n }\n if (\n rule.minImprovement !== undefined &&\n (!isFiniteNumber(rule.minImprovement) || rule.minImprovement < 0)\n ) {\n fail('stop.minImprovement must be a finite number of at least 0')\n }\n}\n\n/** Every rule the chain adds to the kernel's. Its digest, with the stop rule, is the process\n * revision the ledger records, so a changed rule or stop rule is a different search. */\nconst VERSION_CHAIN_DEFINITION = {\n name: 'agent-runtime.pursuit-versions.2026-09',\n node: 'the exact AgentProfile a version executes, content-addressed by canonicalAgentProfileDigest; a change that does not apply is a node addressed by its parent digest and change, and refused',\n edge: 'one change from the kept version, stored as its Interface profile diff',\n cell: 'one supervisePursuit run of the version on the pursuit task, forked from its parent sealed result.json, then scored by the outside judge; a settled version directory is read back after its root identity and fork seal are checked',\n outcome:\n 'a scored winner passes; a scored no-winner fails with its reason; an unscored version is a final error; a run that throws fails the call and leaves its cell open',\n deadline: 'the chain deadline aborts a running version; its judge still runs',\n failures:\n 'before proposing, the chain closes converged when its last stop.identicalFailures judged versions failed identically: driver-failed with the same error name and message, digits, hex runs and absolute paths normalized, or unscored by the judge',\n directories: 'version n runs at <runDir>.v<n> with run id <runId>.v<n>; version 1 at <runDir>',\n} as const\n\nconst VERSION_CHAIN_URI = 'npm:@tangle-network/agent-runtime#supervisePursuit.versions'\n/** The pursuit task's one train task. */\nconst TASK_ID = 'pursuit'\nconst LANE = 'in-process'\n/** The longest delay Node's setTimeout honors. */\nconst MAX_TIMER_MS = 2_147_483_647\n/** 9999-12-31T23:59:59.999Z: the latest instant the ledger's four-digit-year timestamps hold, so\n * a deadline such as `Number.MAX_SAFE_INTEGER` means no deadline rather than an invalid date. */\nconst LATEST_DEADLINE_MS = 253_402_300_799_999\n\ntype ChainBase = Omit<SupervisePursuitOptions, 'versions' | 'fork' | 'signal'>\n\n/** Refuse a chain call that no version could satisfy, before any compute. */\nfunction assertChainCall(versions: PursuitVersions, base: ChainBase): void {\n assertPursuitVersions(versions)\n for (const key of ['journal', 'blobs', 'rootHandle', 'steerDir'] as const) {\n if (base[key] !== undefined) {\n throw new ValidationError(\n `supervisePursuit versions: ${key} names one run, and a version chain has one per version; omit it`,\n )\n }\n }\n if (versions.next === 'review-of-best' && base.continuation?.profile.review === undefined) {\n throw new ValidationError(\n \"supervisePursuit versions: next 'review-of-best' needs continuation.profile.review, the words the next version reads about its review\",\n )\n }\n const { stop } = versions\n if (base.budget.maxUsd !== undefined && base.budget.maxUsd > stop.maxUsd) {\n throw new ValidationError(\n `supervisePursuit versions: budget.maxUsd ${base.budget.maxUsd} is above stop.maxUsd ${stop.maxUsd}, so no version could start`,\n )\n }\n}\n\n/** Run a version chain. `supervisePursuit` calls this when `versions` is set. */\nexport async function runPursuitVersions(\n profile: SupervisorProfile,\n task: unknown,\n opts: SupervisePursuitOptions & { readonly versions: PursuitVersions },\n runOne: RunOne,\n): Promise<SupervisedPursuitResult<SupervisedResult<unknown>> & { versions: PursuitVersionChain }> {\n const { versions, fork: firstFork, signal: callerSignal, ...base } = opts\n assertChainCall(versions, base)\n const { judge, stop } = versions\n const next: NextPursuitVersion =\n versions.next === 'review-of-best'\n ? reviewOfBest(base.runId ?? 'supervise', base.continuation?.profile.review ?? '')\n : versions.next\n const now = base.now ?? Date.now\n const pursuitId = base.pursuitId.trim()\n const runDir = resolve(base.runDir.trim())\n const runId = base.runId ?? 'supervise'\n const ledgerPath = pursuitVersionsLedgerPath(runDir)\n const searchId = `versions:${pursuitId}:${runId}`\n const retired = resolve(`${runDir}.versions`, 'versions.jsonl')\n if (await exists(retired)) {\n throw new ValidationError(\n `supervisePursuit versions: ${retired} holds a chain in the retired versions.jsonl format; finish it on the agent-runtime release that wrote it, or start a new chain in another runDir`,\n )\n }\n\n // The first version's executed profile; later versions derive theirs from their parent's.\n const firstProfile = jsonProfile(\n firstFork === undefined\n ? profile\n : applyExactAgentProfileDiff(profile, firstFork.change, 'supervisePursuit versions'),\n )\n const taskRevision = pursuitValueDigest(task, 'task')\n const ledger = openSearchLedger({ path: ledgerPath, searchId })\n const deadline = await chainDeadline((await ledger.state()).header, now, runDir, stop)\n const policy = incumbent({\n patience: stop.patience,\n ...(stop.minImprovement === undefined ? {} : { minImprovement: stop.minImprovement }),\n })\n const allocation = uniform()\n const recorder = await openVersionRecorder({\n ledger,\n now,\n pursuitId,\n taskRevision,\n judge,\n stop,\n policy,\n allocation,\n deadline,\n firstProfile,\n })\n\n const clock = armChainDeadline(deadline, now)\n const chain = new VersionChainRun({\n profile,\n task,\n base,\n firstFork,\n runOne,\n judge,\n recorder,\n expired: clock.signal,\n pursuitId,\n runDir,\n runId,\n ledgerPath,\n searchId,\n taskRevision,\n })\n const failureLimit = stop.identicalFailures ?? DEFAULT_IDENTICAL_FAILURES\n try {\n const closed = await runSearch({\n recorder,\n root: { profile: firstProfile, refusal: null },\n codec: versionCodec,\n policy,\n allocation,\n proposer: versionProposer(versions.next, next, chain, failureLimit),\n executor: versionExecutor(chain, base.budget.maxUsd),\n admit: (node) => node.refusal,\n ...(callerSignal === undefined ? {} : { signal: callerSignal }),\n now,\n })\n const judged = await chain.judgedVersions(await chain.versionsOf())\n // A converged chain whose last versions share a failure stopped by the identical-failure rule.\n const failed =\n closed.reason === 'converged' ? identicalFailureStreak(judged, failureLimit) : null\n const stopped = failed === null ? null : { versions: failureLimit, failure: failed }\n const best = judged.find((version) => version.nodeId === closed.leader)\n if (best === undefined) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: the chain in ${ledgerPath} closed (${closed.reason}) without a judged version to keep`,\n )\n }\n const observerPath = resolve(best.runDir, 'observer.jsonl')\n return Object.freeze({\n result: best.result,\n pursuit: projectPursuit(await new FileObserverJournal(observerPath, pursuitId).read()),\n observerPath,\n settlePath: resolve(best.runDir, SETTLE_RECORD_FILE),\n versions: Object.freeze({\n ledgerPath,\n searchId,\n reason: closed.reason,\n ...(stopped === null ? {} : { identicalFailures: stopped }),\n best: best.version,\n versions: Object.freeze(judged),\n spend: closed.state.audit.spend,\n receipt: recorder.receipt({ producerId: 'pursuit-versions', runId }),\n }),\n })\n } finally {\n clock.cancel()\n }\n}\n\ninterface VersionRecorderInput {\n ledger: ReturnType<typeof openSearchLedger>\n now: () => number\n pursuitId: string\n taskRevision: string\n judge: VersionJudge\n stop: PursuitVersionStop\n policy: { name: string }\n allocation: { name: string }\n deadline: string\n firstProfile: AgentProfile\n}\n\n/** Open the chain's search recorder: its subject, process revision, splits, policy and budget. */\nfunction openVersionRecorder(input: VersionRecorderInput): Promise<SearchRecorder> {\n const { ledger, now, pursuitId, taskRevision, judge, stop, policy, allocation, deadline } = input\n return SearchRecorder.open(\n { ledger, now },\n {\n subject: pursuitId,\n process: {\n name: 'pursuit-versions',\n executionRef: {\n uri: VERSION_CHAIN_URI,\n revision: canonicalCandidateDigest({\n ...VERSION_CHAIN_DEFINITION,\n stop: canonicalStop(stop),\n }),\n },\n },\n artifactKind: 'agent-profile',\n objective: {\n metric: 'version-judge-score',\n direction: 'maximize',\n judge: { uri: 'agent-runtime:version-judge', revision: judge.digest },\n claim: developmentClaim(pursuitId),\n },\n splits: {\n train: [\n {\n taskId: TASK_ID,\n unitId: TASK_ID,\n source: { uri: `pursuit:${pursuitId}`, revision: taskRevision },\n },\n ],\n selection: [],\n test: [],\n heldOutUnits: true,\n },\n policy: { expansion: policy.name, allocation: allocation.name, seed: 0 },\n budget: {\n maxUsd: stop.maxUsd,\n maxCells: null,\n maxNodes: stop.maxVersions,\n deadline,\n maxConcurrency: 1,\n reservedClaimUsd: 0,\n },\n containment: null,\n derivedFrom: null,\n identity: versionExecutionIdentity(pursuitId, taskRevision, input.firstProfile),\n },\n )\n}\n\n/**\n * The chain's clock starts with its first version, or when the chain opened on a first version\n * that had already settled. A resumed chain keeps the deadline its ledger recorded.\n */\nasync function chainDeadline(\n opened: { budget: { deadline: string | null } } | null | undefined,\n now: () => number,\n runDir: string,\n stop: PursuitVersionStop,\n): Promise<string> {\n return (\n opened?.budget.deadline ??\n new Date(\n Math.min(\n now() - settledElapsed(await readSettleRecord(runDir)) + stop.deadlineMs,\n LATEST_DEADLINE_MS,\n ),\n ).toISOString()\n )\n}\n\n/**\n * The chain's deadline aborts a running version. A timer longer than 2^31 - 1 ms fires at once\n * in Node, so a long chain re-arms in steps.\n */\nfunction armChainDeadline(\n deadline: string,\n now: () => number,\n): { signal: AbortSignal; cancel(): void } {\n const deadlineAt = Date.parse(deadline)\n const expired = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const arm = () => {\n const remaining = deadlineAt - now()\n if (remaining <= 0) {\n expired.abort(new Error('the version chain reached its deadline'))\n return\n }\n timer = setTimeout(arm, Math.min(remaining, MAX_TIMER_MS))\n timer.unref?.()\n }\n arm()\n return {\n signal: expired.signal,\n cancel() {\n if (timer !== undefined) clearTimeout(timer)\n },\n }\n}\n\nconst versionCodec: SearchArtifactCodec<VersionNode> = {\n node(store, node) {\n if (node.profile !== null) {\n const artifact = store.blob('agent-profile', {\n kind: 'agent-profile',\n profile: node.profile,\n })\n return {\n artifactDigest: canonicalAgentProfileDigest(node.profile),\n artifact,\n surfaces: [{ surfaceId: 'profile', kind: 'agent-profile', artifact }],\n }\n }\n const refused = {\n kind: 'unapplied-change',\n parentDigest: node.parentDigest ?? null,\n change: node.change ?? null,\n }\n const artifact = store.blob('change', { ...refused, refusal: node.refusal })\n return {\n artifactDigest: canonicalCandidateDigest(refused),\n artifact,\n surfaces: [{ surfaceId: 'profile', kind: 'agent-profile', artifact }],\n }\n },\n diff(store, parent, child) {\n if (parent.profile === null || child.profile === null || child.change === undefined) {\n return { unknown: 'a refused change has no profile to diff' }\n }\n const from = canonicalAgentProfileDigest(parent.profile)\n if (child.parentDigest !== from) {\n return { unknown: 'the change was written against another parent' }\n }\n return store.blob('diff', {\n kind: 'agent-profile-diff',\n from,\n to: canonicalAgentProfileDigest(child.profile),\n diffs: [child.change],\n })\n },\n load(store, node) {\n return loadNode(store, node)\n },\n}\n\nfunction versionExecutor(\n chain: VersionChainRun,\n maxUsd: number | undefined,\n): SearchExecutor<VersionNode> {\n return {\n // A version's budget.maxUsd bounds it in flight, so it is the hard hold. Without one the\n // hold is the kernel's estimate: 0 until 20 versions settled, then 1.5 times their p99.\n lanes: () => [\n maxUsd === undefined\n ? { name: LANE, capacity: 1, costCap: 'estimate', cellUsd: 0 }\n : { name: LANE, capacity: 1, costCap: 'hard', cellUsd: maxUsd },\n ],\n place: () => LANE,\n // A version that settled is read back from its directory by `run`, so nothing is adopted.\n adopt: async () => null,\n run: (work) => chain.runCell(work),\n }\n}\n\n/** The proposer: the caller's `next` (or the review of the kept version) as the one edge. */\nfunction versionProposer(\n nextOption: PursuitVersions['next'],\n next: NextPursuitVersion,\n chain: VersionChainRun,\n failureLimit: number,\n): SearchProposerPort<VersionNode> {\n const reviewing = nextOption === 'review-of-best'\n const proposerSource: SearchSourceRef = {\n uri: reviewing ? `${VERSION_CHAIN_URI}.review-of-best` : `${VERSION_CHAIN_URI}.next`,\n revision: canonicalCandidateDigest({\n next: reviewing ? 'review-of-best' : Function.prototype.toString.call(nextOption),\n }),\n }\n return {\n name: reviewing ? 'review-of-best' : 'next',\n kind: 'optimizer',\n source: proposerSource,\n execution: { kind: 'deterministic', source: proposerSource },\n childrenPerProposal: 1,\n async propose(request) {\n const parent = request.parents[0]!\n const judged = await chain.judgedVersions(await chain.versionsOf())\n const failure = identicalFailureStreak(judged, failureLimit)\n if (failure !== null) {\n return {\n children: [],\n stop: `the last ${failureLimit} versions failed identically: ${failure}`,\n accounting: FREE,\n }\n }\n const best = judged.find((version) => version.nodeId === parent.nodeId)\n if (best === undefined || parent.artifact.profile === null) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: the kept version ${parent.nodeId} has no judged run to fork from`,\n )\n }\n const returned = await next(\n { best, last: judged.at(-1)!, versions: Object.freeze(judged) },\n request.signal,\n )\n if (typeof returned?.id !== 'string' || returned.id.trim().length === 0) {\n throw new ValidationError('supervisePursuit versions: next must return a change with an id')\n }\n // The ledger stores the change as JSON, so it is taken as JSON: an undefined entry is absent.\n const change = JSON.parse(JSON.stringify(returned)) as AgentProfileDiff\n const child = childNode(parent.artifact.profile, change)\n return {\n children: [\n {\n artifact: child,\n label: change.title ?? returned.id,\n rationale: (change.source?.notes ?? []).join('\\n'),\n },\n ],\n accounting: reviewing\n ? FREE\n : {\n tokens: { status: 'unknown', reason: \"the caller's next reports no usage\" },\n cost: {\n status: 'unknown',\n knownLowerBoundUsd: 0,\n reason: \"the caller's next reports no spend\",\n },\n },\n }\n },\n }\n}\n\n/** The node a change makes, or the refused node when it does not apply to the parent. */\nfunction childNode(parentProfile: AgentProfile, change: AgentProfileDiff): VersionNode {\n const parentDigest = canonicalAgentProfileDigest(parentProfile)\n try {\n return {\n profile: applyExactAgentProfileDiff(parentProfile, change, 'supervisePursuit versions'),\n change,\n parentDigest,\n refusal: null,\n }\n } catch (error) {\n return { profile: null, change, parentDigest, refusal: errorMessage(error) }\n }\n}\n\nfunction canonicalStop(stop: PursuitVersionStop): PursuitVersionStop {\n return {\n patience: stop.patience,\n maxVersions: stop.maxVersions,\n maxUsd: stop.maxUsd,\n deadlineMs: stop.deadlineMs,\n ...(stop.minImprovement === undefined ? {} : { minImprovement: stop.minImprovement }),\n identicalFailures: stop.identicalFailures ?? DEFAULT_IDENTICAL_FAILURES,\n }\n}\n\nconst DEFAULT_IDENTICAL_FAILURES = 3\n\n/** The failure the last `count` judged versions share, or null when they do not all share one. */\nexport function identicalFailureStreak(\n versions: readonly JudgedPursuitVersion[],\n count: number,\n): string | null {\n if (versions.length < count) return null\n const failures = versions.slice(-count).map(versionFailure)\n const [first] = failures\n return first !== null && first !== undefined && failures.every((failure) => failure === first)\n ? first\n : null\n}\n","import { readFile, realpath } from 'node:fs/promises'\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n canonicalCandidateDigest,\n type Sha256Digest,\n sha256Bytes,\n} from '@tangle-network/agent-interface'\nimport { applyExactAgentProfileDiff } from '../candidate-execution/profile'\nimport { RuntimeRunStateError, ValidationError } from '../errors'\nimport { authoredProfileDigest } from '../runtime/supervise/materialization'\nimport { type SuperviseOptions, superviseRootProfile } from '../runtime/supervise/supervise'\nimport type { AgentExecutionRef, SpawnEvent } from '../runtime/supervise/types'\nimport { contentAddress } from './content-address'\nimport { isNoEntError } from './jsonl-file'\nimport { readSettleRecord, SETTLE_RECORD_FILE } from './settle-record'\nimport { FileSpawnJournal } from './spawn-journal/journal-store'\nimport { loadSpawnForest } from './spawn-journal/spawn-forest'\n\n/**\n * Start a run as a version of a settled run: the parent's recorded root inputs plus one change.\n *\n * The call's `profile`, `task` and `budget` must be the parent's, byte for byte, as its sealed\n * journal records them. Runtime applies `change` to that profile and runs the result in a new\n * run directory. The parent directory is read and never written.\n */\nexport interface PursuitFork {\n /** The settled parent's run directory. */\n readonly runDir: string\n /** The sha256 of the parent's `result.json` bytes: the sealed point the fork starts from. */\n readonly settleDigest: Sha256Digest\n /** The one change, applied to the parent's root profile. Its `id` is recorded. */\n readonly change: AgentProfileDiff\n /**\n * Fork a parent whose journal holds a node without a terminal record, an unbegun owned tree, an\n * unconfirmed teardown, or work in flight. Such a node may still act, and a fork never replays\n * the parent's children, so it can only duplicate work outside the fork's tree. The root then\n * records those node ids as `forkParentUncertainNodes`. Omit it to refuse such a parent.\n */\n readonly acceptUncertain?: boolean\n}\n\n/**\n * The `execution.correlation` keys a fork records on its root. Runtime writes them; a caller that\n * supplies one is refused. `lineageRootRunId` is the first run of the chain of parents, so the\n * spend of every version of one lineage groups under one id.\n */\nexport const RUN_FORK_CORRELATION_KEYS = Object.freeze([\n 'forkParentRunId',\n 'forkParentSettleDigest',\n 'forkProfileDiffId',\n 'lineageRootRunId',\n] as const)\n\n/** The correlation key an accepted uncertain parent adds: its uncertain node ids, comma-joined. */\nconst FORK_PARENT_UNCERTAIN_NODES_KEY = 'forkParentUncertainNodes'\n\n/** What `supervisePursuit` executes for a fork: the changed profile and the attributed execution. */\ninterface PreparedRunFork {\n readonly profile: AgentProfile\n readonly execution: AgentExecutionRef\n}\n\ntype SpawnedEvent = Extract<SpawnEvent, { kind: 'spawned' }>\n\n/**\n * Verify the parent and derive the fork's profile and attribution. It reads only the parent, so\n * a refused fork spends nothing and writes nothing.\n */\nexport async function prepareRunFork(\n profile: AgentProfile,\n task: unknown,\n opts: SuperviseOptions & { readonly runId?: string; readonly runDir: string },\n fork: PursuitFork,\n): Promise<PreparedRunFork> {\n const change = fork.change\n if (typeof change?.id !== 'string' || change.id.trim().length === 0) {\n throw new ValidationError('supervisePursuit fork: change.id must be a non-empty string')\n }\n const parentDir = await realDirectory(fork.runDir, 'fork.runDir')\n const forkDir = await realDirectory(opts.runDir, 'runDir', true)\n // A fork at, inside or around the parent's directory would write into the parent.\n if (contains(parentDir, forkDir) || contains(forkDir, parentDir)) {\n throw new ValidationError(\n `supervisePursuit fork: runDir ${forkDir} overlaps the parent's runDir ${parentDir}; a fork needs its own directory outside the parent's`,\n )\n }\n\n // The seal: the exact bytes Runtime wrote once at the parent's settle.\n let bytes: Uint8Array\n try {\n bytes = await readFile(resolve(parentDir, SETTLE_RECORD_FILE))\n } catch (error) {\n if (!isNoEntError(error)) throw error\n throw new RuntimeRunStateError(\n `supervisePursuit fork: ${parentDir} holds no ${SETTLE_RECORD_FILE}; only a settled run is forked`,\n )\n }\n const observed = sha256Bytes(bytes)\n if (observed !== fork.settleDigest) {\n throw new RuntimeRunStateError(\n `supervisePursuit fork: ${SETTLE_RECORD_FILE} hashes to ${observed}, not the requested ${fork.settleDigest}`,\n )\n }\n const settled = await readSettleRecord(parentDir)\n if (settled === undefined) {\n throw new RuntimeRunStateError(`supervisePursuit fork: ${parentDir} lost its settle record`)\n }\n const parentRunId = settled.tree.root\n if ((opts.runId ?? 'supervise') === parentRunId) {\n throw new ValidationError(\n `supervisePursuit fork: runId '${parentRunId}' is the parent's; a fork needs its own runId`,\n )\n }\n\n // Certainty: a node the parent never settled may still act, so a fork could duplicate it.\n const forest = await loadSpawnForest(\n new FileSpawnJournal(resolve(parentDir, 'spawn-journal.jsonl')),\n parentRunId,\n )\n const uncertain = [\n ...forest.inDoubt.map((node) => `${node.nodeId} (no terminal record)`),\n ...forest.missingTrees.map((tree) => `${tree.ownerNodeId} (tree ${tree.root} never begun)`),\n ...(settled.teardownUnconfirmed ?? []).map((node) => `${node.id} (teardown unconfirmed)`),\n ]\n if (settled.tree.inFlight > 0 && uncertain.length === 0) {\n uncertain.push(`${settled.tree.inFlight} in flight`)\n }\n if (uncertain.length > 0 && fork.acceptUncertain !== true) {\n throw new RuntimeRunStateError(\n `supervisePursuit fork: run '${parentRunId}' has uncertain nodes: ${uncertain.join(', ')}; set fork.acceptUncertain to fork it anyway`,\n )\n }\n\n // Inputs: the fork differs from its parent by the change alone.\n const root = forest.trees[0]?.events.find(\n (event): event is SpawnedEvent => event.kind === 'spawned' && event.parent === undefined,\n )\n const recorded = root?.identity\n if (recorded?.profileDigest === undefined || recorded.taskDigest === undefined) {\n throw new RuntimeRunStateError(\n `supervisePursuit fork: run '${parentRunId}' records no root profile and task digest`,\n )\n }\n const mismatches = [\n authoredProfileDigest(superviseRootProfile(profile, opts.profileGuidance)) !==\n recorded.profileDigest\n ? `profile is not the parent's ${recorded.profileDigest}`\n : undefined,\n digestOrUndefined(task) !== recorded.taskDigest\n ? `task is not the parent's ${recorded.taskDigest}`\n : undefined,\n contentAddress(root?.budget) !== contentAddress(opts.budget)\n ? \"budget is not the parent's\"\n : undefined,\n ].filter((mismatch): mismatch is string => mismatch !== undefined)\n if (mismatches.length > 0) {\n throw new ValidationError(`supervisePursuit fork: ${mismatches.join('; ')}`)\n }\n\n const forked = applyExactAgentProfileDiff(profile, change, 'supervisePursuit fork')\n if (\n authoredProfileDigest(superviseRootProfile(forked, opts.profileGuidance)) ===\n recorded.profileDigest\n ) {\n throw new ValidationError(\n `supervisePursuit fork: change '${change.id}' leaves the parent's profile unchanged`,\n )\n }\n\n const supplied = opts.execution?.correlation ?? {}\n const owned = [...RUN_FORK_CORRELATION_KEYS, FORK_PARENT_UNCERTAIN_NODES_KEY].filter((key) =>\n Object.hasOwn(supplied, key),\n )\n if (owned.length > 0) {\n throw new ValidationError(\n `supervisePursuit fork: execution.correlation cannot set ${owned.join(', ')}; Runtime records them`,\n )\n }\n return Object.freeze({\n profile: forked,\n execution: Object.freeze({\n ...opts.execution,\n correlation: Object.freeze({\n ...supplied,\n forkParentRunId: parentRunId,\n forkParentSettleDigest: fork.settleDigest,\n forkProfileDiffId: change.id,\n lineageRootRunId: recorded.correlation?.lineageRootRunId ?? parentRunId,\n ...(uncertain.length === 0\n ? {}\n : { [FORK_PARENT_UNCERTAIN_NODES_KEY]: uncertain.join(', ') }),\n }),\n }),\n })\n}\n\nfunction digestOrUndefined(value: unknown): Sha256Digest | undefined {\n try {\n return canonicalCandidateDigest(value)\n } catch {\n return undefined\n }\n}\n\n/**\n * Resolve a directory through symlinks. The fork's own directory may not exist yet; it resolves\n * through its nearest existing ancestor, so a symlinked ancestor cannot hide an overlap.\n */\nasync function realDirectory(path: string, name: string, mayBeAbsent = false): Promise<string> {\n if (typeof path !== 'string' || path.trim().length === 0) {\n throw new ValidationError(`supervisePursuit fork: ${name} must be a non-empty string`)\n }\n const absolute = resolve(path.trim())\n try {\n return await realpath(absolute)\n } catch (error) {\n const ancestor = dirname(absolute)\n if (!mayBeAbsent || !isNoEntError(error) || ancestor === absolute) throw error\n return join(await realDirectory(ancestor, name, true), basename(absolute))\n }\n}\n\n/** Whether `inner` is `outer` or lies beneath it. */\nfunction contains(outer: string, inner: string): boolean {\n const path = relative(outer, inner)\n return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith(`..${sep}`))\n}\n","import {\n closeSync,\n existsSync,\n fstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n unlinkSync,\n} from 'node:fs'\nimport { resolve } from 'node:path'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport {\n type LockHolderRecord,\n type LockIdentity,\n lockHolderVerdict,\n lockIdentity,\n parseLockHolderRecord,\n readLockHolderIdentity,\n} from '@tangle-network/agent-eval/lock-holder'\nimport {\n publishExclusiveDurableFile,\n writeAtomicDurableFile,\n} from '../runtime/supervise/durable-file'\nimport { isNoEntError } from './jsonl-file'\nimport { mutateRunClaim, runGenerationPath, runWithWriteClaim } from './run-fence'\n\n/*\n * Exclusive ownership of one durable run directory for the life of one `supervisePursuit` call.\n *\n * Measured motive (discovery-lab recursive smoke r1): the recovery protocol is\n * `SIGKILL` the runner while a child is live, then resume on the same directory. PID 1527 was\n * killed at 06:20:27Z and PID 2058 resumed at 06:24:59Z. Nothing refused a second process while\n * the first was still alive; two processes on one directory both append to `spawn-journal.jsonl`\n * and `observer.jsonl`, and the recorded assignment keys and settlements stop being one sequence.\n * The operator relied on timing. This lock makes the second process refuse and name the holder.\n *\n * The holder is identified by its pid and the OS's start token for that pid. r1 ran in a\n * container whose pids are small (1527, 2058) and restart from 1, so a pid alone names the wrong\n * process after enough spawns: a lock left by a killed run would then match an unrelated live\n * process and hold the directory until an operator removed the file. Whether a holder is dead is\n * agent-eval's one dead-owner rule (`@tangle-network/agent-eval/lock-holder`): the record carries\n * the start token, host, boot id, pid namespace and the lock file's own inode identity, and a\n * holder is reclaimed only when those prove it gone or its pid reused. A record that cannot prove\n * that, such as one written before these fields existed, is refused and is removed by hand.\n *\n * The lock is operational state, not evidence: replay, projection, and the settle record ignore\n * it. A holder whose process is gone is reclaimed through Eval's crash-recoverable mutation lock.\n */\n\n/** The lock file `supervisePursuit` holds inside a run directory for the life of one call. */\nexport const RUN_DIRECTORY_LOCK_FILE = 'supervise.lock'\n\n/** What the lock file records about its holder. */\nexport interface RunDirectoryLockHolder {\n readonly pid: number\n /** Monotonic acquisition generation; absent on legacy lock records. */\n readonly generation?: number\n /** ISO instant the holder took the lock. */\n readonly startedAt: string\n readonly runId: string\n /** The OS's start token for `pid` when the host reports one. A holder without one is never proved dead. */\n readonly processStart?: string\n /** Hostname of the holder. Records written before it existed are never proved dead. */\n readonly host?: string\n readonly bootId?: string\n readonly pidNamespace?: string\n /** Inode identity of the lock file this record was written into. */\n readonly lock?: LockIdentity\n}\n\n/** A held lock. `release()` removes the file; it is safe to call more than once. */\nexport interface RunDirectoryLock extends RunDirectoryLockHolder {\n readonly generation: number\n readonly path: string\n /** Bind durable writes to this acquisition, including work queued before release. */\n run<T>(operation: () => T): T\n release(): Promise<void>\n}\n\n/** The directory is held by a live process. `holder` is what that process recorded. */\nexport class RunDirectoryLockedError extends Error {\n readonly path: string\n readonly holder: RunDirectoryLockHolder\n\n constructor(path: string, holder: RunDirectoryLockHolder) {\n super(\n `supervisePursuit: ${path} is held by pid ${holder.pid} (run '${holder.runId}', since ${holder.startedAt}); one process drives a run directory at a time`,\n )\n this.name = 'RunDirectoryLockedError'\n this.path = path\n this.holder = holder\n }\n}\n\n/**\n * Take `runDir/supervise.lock`, or refuse.\n *\n * The file is published with its full content or not at all, so a contender never reads a\n * half-written holder. A lock whose holder is proved dead (its pid no longer exists, the pid now\n * belongs to a process with a different start token, or the host rebooted) is stale and is removed\n * under the mutation guard; a holder that is alive or cannot be proved dead refuses. An empty file\n * names no holder and is reclaimed. A file with unreadable content is left in place and refused:\n * reclaiming it could evict a live holder written by something other than this module.\n */\nexport async function acquireRunDirectoryLock(\n runDir: string,\n runId: string,\n now: () => number = Date.now,\n): Promise<RunDirectoryLock> {\n const dir = resolve(runDir)\n const path = resolve(dir, RUN_DIRECTORY_LOCK_FILE)\n mkdirSync(dir, { recursive: true })\n const { pid, ...identity } = readLockHolderIdentity(process.pid)\n const owner = { pid, startedAt: new Date(now()).toISOString(), runId, ...identity }\n return mutateRunClaim(path, () => {\n const existing = readLockFile(path)\n if (existing.state === 'holder' && !holderIsDead(existing)) {\n throw new RunDirectoryLockedError(path, existing.holder)\n }\n let previousGeneration = 0\n try {\n previousGeneration = Number(readFileSync(runGenerationPath(dir), 'utf8'))\n if (!Number.isSafeInteger(previousGeneration) || previousGeneration < 1) {\n throw new Error('invalid run directory generation counter')\n }\n } catch (error) {\n if (!isNoEntError(error)) throw error\n }\n const generation =\n Math.max(\n previousGeneration,\n existing.state === 'holder' ? (existing.holder.generation ?? 0) : 0,\n ) + 1\n if (!Number.isSafeInteger(generation)) throw new Error('run directory generation exhausted')\n writeAtomicDurableFile(runGenerationPath(dir), `${generation}\\n`)\n if (existing.state !== 'missing') removeIfPresent(path)\n const written: { holder?: RunDirectoryLockHolder } = {}\n // The lock file is a hard link of the temporary file, so the temporary file's inode identity\n // is the lock's, and a later verdict can prove this record was written for this very lock.\n const published = publishExclusiveDurableFile(path, (file) => {\n written.holder = Object.freeze({ ...owner, generation, lock: lockIdentity(file) })\n return `${JSON.stringify(written.holder)}\\n`\n })\n const holder = written.holder\n if (!published || holder === undefined) {\n throw new Error(`supervisePursuit: could not take ${path}`)\n }\n let released = false\n return Object.freeze({\n ...holder,\n generation,\n path,\n run: <T>(operation: () => T): T => {\n if (holder.lock === undefined) throw new Error('run lock has no inode identity')\n return runWithWriteClaim({ path, generation, lock: holder.lock }, operation)\n },\n release: async () => {\n if (released) return\n await releaseHolder(path, holder)\n released = true\n },\n })\n })\n}\n\n/** Read the holder a lock file names, or `undefined` when no lock file names one. */\nexport async function readRunDirectoryLock(\n runDir: string,\n): Promise<RunDirectoryLockHolder | undefined> {\n const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE))\n return existing.state === 'holder' ? existing.holder : undefined\n}\n\n/** What {@link runDirectoryHolderIsLive} proved about a run directory's recorded holder. */\nexport interface RunDirectoryHolderLiveness {\n /** False only when the holder that took the lock is proved dead; a holder that cannot be proved dead reads as live. */\n readonly live: boolean\n /** The holder the lock file names. Absent when no lock file names one, which reads as not live. */\n readonly holder?: RunDirectoryLockHolder\n}\n\n/**\n * Whether a run directory is still held by the live process that took its lock.\n *\n * The same rule `acquireRunDirectoryLock` applies to decide whether a lock is stale, exposed so a\n * caller — a supervisor picking up an abandoned directory, an operator tool listing runs — asks\n * the question instead of hand-rolling `process.kill(pid, 0)`. A bare signal probe cannot tell a\n * live holder from an unrelated process that later took the same pid, which is the failure this\n * lock's start token exists to prevent.\n *\n * The answer is ADVISORY: it is read outside the mutation guard `acquireRunDirectoryLock` holds,\n * so a `false` can be stale by the time the caller acts on it and a concurrent acquire can take\n * the directory in between. Reporting and listing are what this is for. A caller that intends to\n * TAKE the directory calls `acquireRunDirectoryLock`, which evaluates the same rule under the\n * guard and refuses atomically.\n */\nexport async function runDirectoryHolderIsLive(\n runDir: string,\n): Promise<RunDirectoryHolderLiveness> {\n const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE))\n if (existing.state !== 'holder') return { live: false }\n return { live: !holderIsDead(existing), holder: existing.holder }\n}\n\ntype LockFileState =\n | { readonly state: 'missing' }\n | { readonly state: 'empty' }\n | {\n readonly state: 'holder'\n readonly holder: RunDirectoryLockHolder\n /** The holder as agent-eval's rule reads it; absent when the record names no host. */\n readonly record: LockHolderRecord | undefined\n /** Inode identity of the file the holder was read from. */\n readonly current: LockIdentity\n }\n\nfunction readLockFile(path: string): LockFileState {\n let text: string\n let current: LockIdentity\n try {\n const file = openSync(path, 'r')\n try {\n current = lockIdentity(fstatSync(file, { bigint: true }))\n text = readFileSync(file, 'utf8')\n } finally {\n closeSync(file)\n }\n } catch (error) {\n if (isNoEntError(error)) return { state: 'missing' }\n throw error\n }\n // This module publishes the file with its full content or not at all, so an empty file was\n // not left by a live holder.\n if (text.trim().length === 0) return { state: 'empty' }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch (cause) {\n throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`, {\n cause,\n })\n }\n const record = parsed as Partial<RunDirectoryLockHolder> | null\n if (\n typeof record !== 'object' ||\n record === null ||\n typeof record.pid !== 'number' ||\n !Number.isInteger(record.pid) ||\n record.pid <= 0 ||\n typeof record.startedAt !== 'string' ||\n typeof record.runId !== 'string' ||\n (record.processStart !== undefined && typeof record.processStart !== 'string') ||\n (record.generation !== undefined &&\n (!Number.isSafeInteger(record.generation) || record.generation < 1))\n ) {\n throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`)\n }\n const { pid, startedAt, runId, processStart } = record\n // A missing or malformed identity field is dropped, which leaves the holder never provably dead.\n const verdictRecord = parseLockHolderRecord(parsed)\n const { pid: _pid, ...identity } = verdictRecord ?? { pid }\n return {\n state: 'holder',\n holder: Object.freeze({\n pid,\n startedAt,\n runId,\n ...(record.generation === undefined ? {} : { generation: record.generation }),\n ...(processStart === undefined ? {} : { processStart }),\n ...identity,\n }),\n record: verdictRecord,\n current,\n }\n}\n\n/** agent-eval's dead-owner rule: only a holder proved dead is stale; alive or unknown stays held. */\nfunction holderIsDead(existing: Extract<LockFileState, { state: 'holder' }>): boolean {\n return lockHolderVerdict(existing.record, existing.current).liveness === 'dead'\n}\n\n/** Remove the lock only while it still names this holder; a reclaimed lock belongs to its new owner. */\nasync function releaseHolder(path: string, holder: RunDirectoryLockHolder): Promise<void> {\n const deadline = performance.now() + 1_000\n while (existsSync(`${path}.guard`) && performance.now() < deadline) await delay(10)\n mutateRunClaim(path, () => {\n const existing = readLockFile(path)\n if (existing.state !== 'holder') return\n if (\n existing.holder.pid !== holder.pid ||\n existing.holder.startedAt !== holder.startedAt ||\n existing.holder.runId !== holder.runId ||\n existing.holder.processStart !== holder.processStart ||\n existing.holder.generation !== holder.generation ||\n existing.holder.lock?.dev !== holder.lock?.dev ||\n existing.holder.lock?.ino !== holder.lock?.ino ||\n existing.holder.lock?.birthtimeNs !== holder.lock?.birthtimeNs\n )\n return\n removeIfPresent(path)\n })\n}\n\nfunction removeIfPresent(path: string): void {\n try {\n unlinkSync(path)\n } catch (error) {\n if (!isNoEntError(error)) throw error\n }\n}\n","import type { PursuitProjection } from './observer-projection'\n\n/**\n * Where a pursuit's observer projection is delivered while it runs, so a run started anywhere is\n * findable in one place by its pursuit id.\n *\n * Intelligence persists the projection on its run spine (`runtime-observer:pursuit:<pursuitId>`)\n * and records the id of the API key that delivered it, which joins the run to that key's spend.\n * Delivery is an observation, never a dependency: a refused, slow or unreachable endpoint is\n * reported once and the run continues exactly as it would without it.\n */\nexport interface PursuitObserverDelivery {\n /** Intelligence base URL, e.g. `https://intelligence.tangle.tools`. */\n readonly baseUrl: string\n /** Platform API key presented as the Bearer; Intelligence resolves the tenant from it. */\n readonly apiKey: string\n /** The Intelligence subject (project) the pursuit belongs to. */\n readonly subjectKey: string\n readonly subjectName?: string\n /**\n * Flat facts the caller owns about the run, recorded on the pursuit row unchanged, such as the\n * program and idea a registration names. Runtime neither reads nor validates their meaning.\n */\n readonly attributes?: Readonly<Record<string, string>>\n /** How often a live run re-delivers its projection. Default 60 s; the last delivery is liveness. */\n readonly intervalMs?: number\n /** Per-request bound. Default 10 s. */\n readonly timeoutMs?: number\n readonly fetch?: typeof fetch\n}\n\n/** The execution state Runtime reports. It never claims the pursuit's semantic success. */\nexport type PursuitObserverState = 'running' | 'done' | 'failed'\n\nexport type PursuitObserverDeliveryOutcome =\n | { readonly succeeded: true; readonly status: number }\n | { readonly succeeded: false; readonly reason: string }\n\n/** The Intelligence route that persists a delivered projection on its run spine. */\nexport const PURSUIT_OBSERVER_DELIVERY_PATH = '/v1/ingest/pursuit-observer'\n\nconst DEFAULT_INTERVAL_MS = 60_000\nconst DEFAULT_TIMEOUT_MS = 10_000\n\n/** POST one projection. Never throws; the outcome says whether Intelligence accepted it. */\nasync function deliverPursuitObserver(\n delivery: PursuitObserverDelivery,\n state: PursuitObserverState,\n projection: PursuitProjection,\n): Promise<PursuitObserverDeliveryOutcome> {\n const send = delivery.fetch ?? globalThis.fetch\n const url = `${delivery.baseUrl.replace(/\\/+$/u, '')}${PURSUIT_OBSERVER_DELIVERY_PATH}`\n try {\n const response = await send(url, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${delivery.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n subjectKey: delivery.subjectKey,\n ...(delivery.subjectName === undefined ? {} : { subjectName: delivery.subjectName }),\n state,\n ...(delivery.attributes === undefined ? {} : { attributes: delivery.attributes }),\n projection,\n }),\n signal: AbortSignal.timeout(delivery.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n })\n if (response.ok) return { succeeded: true, status: response.status }\n const detail = (await response.text().catch(() => '')).slice(0, 300)\n return { succeeded: false, reason: `HTTP ${response.status}${detail ? `: ${detail}` : ''}` }\n } catch (error) {\n return { succeeded: false, reason: error instanceof Error ? error.message : String(error) }\n }\n}\n\nexport interface PursuitObserverDeliverer {\n /** Queue a delivery of the current projection. Deliveries never overlap; a burst collapses to one. */\n push(state: PursuitObserverState): void\n /** Stop liveness delivery and deliver the final snapshot. A parked run remains nonterminal. */\n close(state: PursuitObserverState): Promise<PursuitObserverDeliveryOutcome>\n}\n\n/**\n * Deliver a live run's projection at start, on an interval, and at settlement. `read` projects\n * the run's own journal at the moment of each delivery, so every delivery is the whole record.\n */\nexport function startPursuitObserverDelivery(\n delivery: PursuitObserverDelivery,\n read: () => Promise<PursuitProjection>,\n warn: (message: string) => void = (message) => console.warn(message),\n): PursuitObserverDeliverer {\n let chain: Promise<PursuitObserverDeliveryOutcome | undefined> = Promise.resolve(undefined)\n let pending: PursuitObserverState | undefined\n let warned = false\n let closed = false\n\n const deliver = async (state: PursuitObserverState) => {\n let projection: PursuitProjection\n try {\n projection = await read()\n } catch (error) {\n return report({\n succeeded: false,\n reason: `observer projection unreadable: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n return report(await deliverPursuitObserver(delivery, state, projection))\n }\n const report = (outcome: PursuitObserverDeliveryOutcome) => {\n if (!outcome.succeeded && !warned) {\n warned = true\n warn(\n `supervisePursuit: pursuit observer delivery to ${delivery.baseUrl} failed (${outcome.reason}); the run continues and later deliveries retry`,\n )\n }\n return outcome\n }\n const push = (state: PursuitObserverState) => {\n if (closed) return\n if (pending !== undefined) return\n pending = state\n chain = chain.then(() => {\n const next = pending as PursuitObserverState\n pending = undefined\n return deliver(next)\n })\n }\n\n const timer = setInterval(() => push('running'), delivery.intervalMs ?? DEFAULT_INTERVAL_MS)\n timer.unref?.()\n push('running')\n\n return {\n push,\n async close(state) {\n closed = true\n clearInterval(timer)\n const terminal = chain.then(() => deliver(state))\n chain = terminal\n const bound = delivery.timeoutMs ?? DEFAULT_TIMEOUT_MS\n let timeout: ReturnType<typeof setTimeout> | undefined\n const expired = new Promise<PursuitObserverDeliveryOutcome>((resolve) => {\n timeout = setTimeout(\n () => resolve({ succeeded: false, reason: `terminal delivery exceeded ${bound} ms` }),\n bound * 2,\n )\n timeout.unref?.()\n })\n try {\n return await Promise.race([terminal, expired])\n } finally {\n clearTimeout(timeout)\n }\n },\n }\n}\n","import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync } from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport {\n publishExclusiveDurableFile,\n syncDurableDirectory,\n} from '../runtime/supervise/durable-file'\nimport { runCancellationFile, runCancelRequestFile } from '../runtime/supervise/run-cancellation'\nimport { workerCancellationsDir } from '../runtime/supervise/run-layout'\nimport { assertValidBudget } from '../runtime/supervise/spend-validation'\nimport { assertResumeLimits } from '../runtime/supervise/supervisor-root-contract'\nimport type { Budget, SpawnEvent, SpawnJournal, SupervisorOpts } from '../runtime/supervise/types'\nimport type { FileObserverJournal } from './observer-journal'\nimport { fenceRunWrite } from './run-fence'\nimport { SETTLE_RECORD_FILE, settleRecordDigest } from './settle-record'\nimport { FileSpawnJournal } from './spawn-journal/journal-store'\n\n/*\n * Reopening a settled run under its own run id.\n *\n * A wrong settle used to be final: `supervisePursuit` refuses a directory that holds `result.json`,\n * and `fork` and `versions` each start a new run id in a new directory. Magnetar used 21 run ids\n * from 2026-10-16 to 10-21 for one solve; 16 of those runs settled, 11 of them in under 5 hours.\n *\n * A reopen archives the settled segment and resumes the same journal. Before it writes anything it\n * checks the resume limits (`assertResumeLimits`): a reopen refused for its budget or reservation\n * policy leaves `result.json`, the cancel files and the journal as they were. The profile's identity\n * and materialization are checked by `supervise` itself, after these steps. Every step is\n * idempotent, so a later call with the same `operationId` finishes a reopen that crashed partway:\n * 1. copy `result.json` byte for byte to `settles/<n>.json`;\n * 2. append one `reopened` spawn-journal row naming the operator, the reason and the archive;\n * 3. append one observer event, so the pursuit projection shows one lineage;\n * 4. move the run's cancel request and acknowledgement aside under this reopen's and that\n * request's operation ids, so a new `cancelRun` is accepted (one run carries one run-scoped\n * cancel operation) and no later reopen overwrites an earlier segment's cancel;\n * 5. last, remove `result.json`.\n * The caller then runs `supervise` with `resume: true`: settled children replay by key, the pool\n * is restored from the journal, and the next settle writes `result.json` again.\n */\n\n/** `supervisePursuit`'s `reopen` option: reopen this settled run under its own run id. */\nexport interface RunReopen {\n /** Who reopens the run. Required and non-empty. */\n readonly operator: string\n /** Why. Required and non-empty. */\n readonly reason: string\n /** Idempotency key: calling again with it finishes a reopen that crashed partway. */\n readonly operationId: string\n /**\n * The budget the reopened run is held to, recorded on its `reopened` row, which a later resume\n * must then match. Omit and the call's `budget` must equal the recorded one: the root's, or the\n * last budget a reopen recorded. A run that settled `budget-exhausted` and reopens without a\n * larger budget pauses at once (with `driverRetry.pauseRootStops`) or settles\n * `budget-exhausted` again. A deadline is measured from the original root instant, so a run\n * whose recorded deadline has passed settles `deadline` at once unless this budget drops the\n * deadline or moves it.\n */\n readonly budget?: Budget\n}\n\n/** The directory that holds a run's archived settle records. */\nexport const SETTLE_ARCHIVE_DIR = 'settles'\n\n/** Refuse a reopen that names no operator or reason, or that is combined with a fork or versions. */\nexport function assertRunReopen(\n reopen: RunReopen,\n opts: { readonly fork?: unknown; readonly versions?: unknown },\n): void {\n if (reopen.operator.trim().length === 0) {\n throw new TypeError('supervisePursuit: reopen.operator must be non-empty')\n }\n if (reopen.reason.trim().length === 0) {\n throw new TypeError('supervisePursuit: reopen.reason must be non-empty')\n }\n if (reopen.operationId.trim().length === 0) {\n throw new TypeError('supervisePursuit: reopen.operationId must be non-empty')\n }\n if (reopen.budget !== undefined) assertValidBudget(reopen.budget, 'reopen.budget')\n if (opts.fork !== undefined || opts.versions !== undefined) {\n throw new TypeError(\n 'supervisePursuit: reopen continues this run under its own id; fork and versions start new runs',\n )\n }\n}\n\n/**\n * Archive the settled segment of the run at `runDir` and clear it for a resume. Runs under the\n * directory lock. Throws when there is nothing to reopen, or when `operationId` already reopened a\n * segment that has since settled again.\n */\nexport async function reopenSettledRun(input: {\n readonly runDir: string\n readonly runId: string\n readonly reopen: RunReopen\n readonly journal: SpawnJournal | undefined\n /** The call's budget and reservation policy, checked against the recorded ones before any write. */\n readonly limits: Pick<SupervisorOpts, 'budget' | 'reservationPolicy'>\n readonly observer: FileObserverJournal\n readonly pursuitId: string\n readonly now: () => number\n}): Promise<void> {\n const { runDir, runId, reopen, observer, pursuitId, now } = input\n const operationId = reopen.operationId.trim()\n const settlePath = resolve(runDir, SETTLE_RECORD_FILE)\n const journal = input.journal ?? new FileSpawnJournal(resolve(runDir, 'spawn-journal.jsonl'))\n const events = (await journal.loadTree(runId)) ?? []\n const reopened = events.filter(\n (event): event is Extract<SpawnEvent, { kind: 'reopened' }> =>\n event.kind === 'reopened' && event.id === runId,\n )\n const mine = reopened.find((event) => event.operationId === operationId)\n const settled = await readBytes(settlePath)\n if (settled === undefined) {\n // Removing result.json is the last step, so a recorded reopen without it is complete.\n if (mine !== undefined) return\n throw new Error(\n `supervisePursuit: ${runDir} holds no ${SETTLE_RECORD_FILE}; nothing to reopen; resume it`,\n )\n }\n assertResumeLimits(\n events,\n {\n runId,\n budget: reopen.budget ?? input.limits.budget,\n ...(input.limits.reservationPolicy === undefined\n ? {}\n : { reservationPolicy: input.limits.reservationPolicy }),\n },\n mine === undefined ? reopen.budget : undefined,\n )\n const result = JSON.parse(settled) as { readonly kind?: unknown; readonly reason?: unknown }\n const digest = settleRecordDigest(result)\n if (mine !== undefined && mine.prior.digest !== digest) {\n throw new Error(\n `supervisePursuit: reopen '${operationId}' already reopened run '${runId}', which has settled again; reopen it under a new operationId`,\n )\n }\n const archivedAs = mine?.prior.archivedAs ?? (await archiveName(runDir, settled))\n const archivePath = resolve(runDir, archivedAs)\n if (\n !publishExclusiveDurableFile(archivePath, settled) &&\n (await readBytes(archivePath)) !== settled\n ) {\n throw new Error(\n `supervisePursuit: ${archivePath} already holds a different settle record; reopen refused`,\n )\n }\n const at = new Date(now()).toISOString()\n if (mine === undefined) {\n await journal.appendEvent(runId, {\n kind: 'reopened',\n id: runId,\n operator: reopen.operator,\n reason: reopen.reason,\n operationId,\n prior: {\n kind: String(result.kind),\n ...(typeof result.reason === 'string' ? { reason: result.reason } : {}),\n digest,\n archivedAs,\n },\n ...(reopen.budget === undefined ? {} : { budget: reopen.budget }),\n seq: reopened.length,\n at,\n })\n }\n const eventId = `${runId}:pursuit:reopened:${operationId}`\n if (!(await observer.read()).some((record) => record.event?.id === eventId)) {\n await observer.appendEvent({\n id: eventId,\n pursuitId,\n runId,\n target: 'agent.run',\n phase: 'event',\n timestamp: now(),\n payload: { reopened: { operator: reopen.operator, reason: reopen.reason, archivedAs } },\n })\n }\n fenceRunWrite(() => {\n setCancellationAside(runDir, operationId)\n unlinkSync(settlePath)\n syncDurableDirectory(runDir)\n })\n}\n\n/** The next free `settles/<n>.json`, or the archive that already holds these bytes (a reopen that\n * crashed after archiving and before its journal row). */\nasync function archiveName(runDir: string, settled: string): Promise<string> {\n const dir = resolve(runDir, SETTLE_ARCHIVE_DIR)\n fenceRunWrite(() => mkdirSync(dir, { recursive: true }))\n const numbers = readdirSync(dir)\n .map((name) => /^(\\d+)\\.json$/u.exec(name)?.[1])\n .filter((n): n is string => n !== undefined)\n .map(Number)\n .sort((a, b) => a - b)\n for (const n of numbers) {\n if ((await readBytes(join(dir, `${n}.json`))) === settled)\n return `${SETTLE_ARCHIVE_DIR}/${n}.json`\n }\n return `${SETTLE_ARCHIVE_DIR}/${(numbers.at(-1) ?? 0) + 1}.json`\n}\n\n/** Move the settled run's cancel request and acknowledgement aside under the reopen's and the\n * request's operation ids, so the reopened run accepts a new `cancelRun`. Idempotent: an absent\n * file is skipped. A reopen's operation id names one segment, so a later segment cancelled under\n * the same cancel operation id lands beside this one instead of over it. */\nfunction setCancellationAside(runDir: string, reopenOperationId: string): void {\n const requestFile = runCancelRequestFile(runDir)\n const ackFile = runCancellationFile(runDir)\n if (!existsSync(requestFile) && !existsSync(ackFile)) return\n const source = existsSync(requestFile) ? requestFile : ackFile\n const { operationId } = JSON.parse(readFileSync(source, 'utf8')) as {\n readonly operationId: string\n }\n const reopenedDir = join(workerCancellationsDir(runDir), 'reopened')\n const aside = join(\n reopenedDir,\n encodeURIComponent(reopenOperationId),\n encodeURIComponent(operationId),\n )\n mkdirSync(aside, { recursive: true })\n if (existsSync(ackFile)) renameSync(ackFile, join(aside, 'run.json'))\n if (existsSync(requestFile)) renameSync(requestFile, join(aside, 'run.request.json'))\n syncDurableDirectory(aside)\n syncDurableDirectory(join(reopenedDir, encodeURIComponent(reopenOperationId)))\n syncDurableDirectory(reopenedDir)\n syncDurableDirectory(workerCancellationsDir(runDir))\n}\n\nasync function readBytes(path: string): Promise<string | undefined> {\n try {\n return await readFile(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw error\n }\n}\n","import { resolve } from 'node:path'\nimport { runtimeFailureCause } from '../runtime/failure-cause'\nimport {\n type AgentGraph,\n type GraphResult,\n type RunGraphOptions,\n superviseAgentGraph,\n} from '../runtime/supervise/graph'\nimport { graphExecutionOptions } from '../runtime/supervise/graph-backend'\nimport { readRootStreamReceipt } from '../runtime/supervise/root-stream'\nimport { supervisorRunDir } from '../runtime/supervise/run-layout'\nimport { RunParkedError } from '../runtime/supervise/run-parking'\nimport { type SuperviseOptions, supervise } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { SupervisedResult } from '../runtime/supervise/types'\nimport { errorMessage } from '../runtime/util'\nimport {\n composeRuntimeHooks,\n type RuntimeHookEvent,\n type RuntimeHooks,\n withPursuitContext,\n} from '../runtime-hooks'\nimport { createFileObserverHooks, type FileObserverJournal } from './observer-journal'\nimport { type PursuitProjection, projectPursuit } from './observer-projection'\nimport {\n type PursuitObserverDeliverer,\n type PursuitObserverDelivery,\n startPursuitObserverDelivery,\n} from './pursuit-observer-delivery'\nimport {\n type PursuitVersionChain,\n type PursuitVersions,\n runPursuitVersions,\n} from './pursuit-versions'\nimport { type PursuitFork, prepareRunFork } from './run-fork'\nimport { acquireRunDirectoryLock } from './run-lock'\nimport { assertRunReopen, type RunReopen, reopenSettledRun } from './run-reopen'\nimport {\n FAILURE_RECORD_FILE,\n readSettleRecord,\n SETTLE_RECORD_FILE,\n SettledRunDirectoryError,\n writeFailureRecord,\n writeSettleRecord,\n} from './settle-record'\n\nexport interface SupervisePursuitOptions extends SuperviseOptions {\n /** Stable objective identity spanning concrete Runtime runs. */\n readonly pursuitId: string\n /**\n * One concrete Runtime execution owns one durable directory and observer journal.\n * A pursuit spanning several runs reuses `pursuitId` across distinct `runDir`s;\n * Intelligence joins those isolated projections without a shared write head.\n */\n readonly runDir: string\n /**\n * Always `'release'`. A settle record is written once per segment and refuses re-entry, so no\n * later call resumes a settled pursuit unless an explicit `reopen` archives it; nothing else\n * would release the provider environments its retained children hold. `'keep'` is refused\n * rather than ignored.\n */\n readonly retainedAtSettlement?: 'release'\n /**\n * Run this pursuit as a version of a settled run: `profile`, `task` and `budget` must equal the\n * parent's recorded root, and Runtime executes the parent's profile with `fork.change` applied.\n * The root's `execution.correlation` records the parent, its sealed digest, the change and the\n * lineage (`RUN_FORK_CORRELATION_KEYS`). The fork's `runDir` must lie outside the parent's, and\n * the parent's outside it. The parent's directory is never written, and a refused fork, such as\n * one whose parent has an uncertain node, writes nothing.\n */\n readonly fork?: PursuitFork\n /**\n * Continue this pursuit across versions, on Eval's search kernel. The first version runs at\n * `runDir` as usual, or is read back when that directory already settled. After each version\n * settles, `versions.judge` scores it from outside its tree; unless `versions.stop` ends the\n * chain, the next version forks from the version the chain keeps with the change\n * `versions.next` returns, at `<runDir>.v<n>` with run id `<runId>.v<n>`. The search ledger at\n * `<runDir>.search/ledger.jsonl` records every version as a node, every change as an edge, and\n * every run and verdict as a cell; it is the chain's only record and checkpoint. A call on a\n * closed chain reads it back; a call on an open chain continues it without re-running or\n * re-judging a settled version. Aborting `signal` pauses the chain: the call rejects and a later\n * call continues it. The call returns the kept version's result with the chain.\n */\n readonly versions?: PursuitVersions\n /**\n * Deliver this run's observer projection to Intelligence at start, every `intervalMs` while it\n * runs, and at settlement or failure, so the run is findable by its pursuit id from wherever it\n * was started. Optional and fail-open: a delivery that fails is reported once and never changes\n * the run. Each version of a `versions` chain delivers its own run under the same pursuit.\n */\n readonly observerDelivery?: PursuitObserverDelivery\n /**\n * Reopen this settled run under its own run id instead of refusing it (`./run-reopen.ts`).\n * Under the directory lock, `result.json` is archived byte for byte to `settles/<n>.json`, one\n * `reopened` journal row names the operator and reason, the run's settled cancel operation is\n * moved aside, and the run resumes from its journal (`resume: true`): settled children replay by\n * key and spend from before the reopen is debited once. `reopen.budget`, when set, replaces the\n * call's `budget` and is recorded for later resumes. Refused with `fork` or `versions`, and on a\n * directory with no `result.json` (\"nothing to reopen; resume it\"); a reopen whose budget or\n * reservation policy the recorded run refuses (\"resume budget mismatch\") writes nothing.\n */\n readonly reopen?: RunReopen\n}\n\nexport interface SupervisedPursuitResult<Result> {\n readonly result: Result\n readonly pursuit: PursuitProjection\n readonly observerPath: string\n /** `result.json` in the run directory: `result` as canonical JSON, written once at settle. */\n readonly settlePath: string\n /** The version chain, when the call set `versions`. */\n readonly versions?: PursuitVersionChain\n}\n\n/** A failed Runtime execution whose complete third-person projection was retained. */\nexport class SupervisePursuitError extends Error {\n readonly pursuit: PursuitProjection\n readonly observerPath: string\n /** `failure.json` in the run directory: the record of this throw. */\n readonly failurePath: string\n\n constructor(\n cause: unknown,\n pursuit: PursuitProjection,\n observerPath: string,\n failurePath: string,\n ) {\n super(`supervisePursuit: ${errorMessage(cause)}`, { cause })\n this.name = 'SupervisePursuitError'\n this.pursuit = pursuit\n this.observerPath = observerPath\n this.failurePath = failurePath\n }\n}\n\n/**\n * One-call durable pursuit execution over the canonical `supervise()` kernel.\n *\n * This is an adapter, not a second executor: it composes a durable third-person\n * observer into Runtime's existing recursive hook stream and then rebuilds the\n * operator projection after the same `supervise()` call settles. Agents never\n * receive the observer path or projection and their behavior does not depend on it.\n *\n * Every concrete execution writes only inside its own `runDir`. Cross-run pursuit\n * aggregation is therefore lock-free at the observer layer: reuse `pursuitId` across\n * run directories and let Intelligence join the independently verified projections.\n *\n * The directory's terminal state is recorded beside `observer.jsonl`: `result.json` holds the\n * returned result once the run settles and `failure.json` the most recent throw. A directory\n * whose `result.json` exists refuses re-entry before any compute; a failure record alone does\n * not, because a caller can correct its input and drive the same run again. For the life of the\n * call the directory is held by `supervise.lock`, so a second process on the same directory\n * refuses and names the holder instead of sharing one journal.\n * An abandoned `supervise.lock.guard` requires removal after confirming no lock mutation is active.\n */\nexport async function supervisePursuit(\n profile: SupervisorProfile,\n task: unknown,\n opts: SupervisePursuitOptions,\n): Promise<SupervisedPursuitResult<Awaited<ReturnType<typeof supervise>>>> {\n assertPursuitDirectory(opts, 'supervisePursuit')\n if (opts.reopen !== undefined) assertRunReopen(opts.reopen, opts)\n\n if (opts.versions !== undefined) {\n return runPursuitVersions(\n profile,\n task,\n opts as SupervisePursuitOptions & { readonly versions: PursuitVersions },\n supervisePursuit,\n ) as Promise<SupervisedPursuitResult<Awaited<ReturnType<typeof supervise>>>>\n }\n\n const {\n pursuitId: _pursuitId,\n hooks: _hooks,\n fork,\n versions: _versions,\n observerDelivery: _observerDelivery,\n reopen,\n ...superviseOptions\n } = opts\n\n // A fork is verified on every entry, a resume included, so the recorded root identity it\n // derives is the one the Supervisor's resume contract compares against. It reads only the\n // settled parent, and runs before the lock so a refused fork writes nothing, not even runDir.\n const forked =\n fork === undefined ? undefined : await prepareRunFork(profile, task, superviseOptions, fork)\n\n return runDurablePursuit(\n opts,\n ({ hooks, steerDir }) =>\n supervise(forked?.profile ?? profile, task, {\n ...superviseOptions,\n ...(forked === undefined ? {} : { execution: forked.execution }),\n ...(reopen === undefined\n ? {}\n : { resume: true, ...(reopen.budget === undefined ? {} : { budget: reopen.budget }) }),\n steerDir,\n // The settle record written at settlement makes this settlement final, so the\n // environments a retained child holds are released at the barrier instead of kept for a\n // resume that the record will refuse (18 of a 60-slot fleet held 19\n // to 37 hours).\n retainedAtSettlement: 'release',\n hooks,\n }),\n (result) => result,\n reopen === undefined\n ? undefined\n : (observer) =>\n reopenSettledRun({\n runDir: opts.runDir.trim(),\n runId: opts.runId ?? 'supervise',\n reopen,\n journal: opts.journal,\n limits: {\n budget: opts.budget,\n ...(opts.reservationPolicy === undefined\n ? {}\n : { reservationPolicy: opts.reservationPolicy }),\n },\n observer,\n pursuitId: opts.pursuitId.trim(),\n now: opts.now ?? Date.now,\n }),\n )\n}\n\n/** Options for {@link superviseGraphPursuit}: every `runGraph` option, plus the pursuit identity,\n * the run directory this execution owns, and optional observer delivery. */\nexport interface SuperviseGraphPursuitOptions extends RunGraphOptions {\n /** Stable objective identity spanning concrete Runtime runs. */\n readonly pursuitId: string\n /** The directory this execution owns: journal, blobs, observer journal, lock and terminal\n * records. Re-running the same `runDir` and `runId` resumes an unsettled graph; a settled\n * graph requires an explicit `reopen`. */\n readonly runDir: string\n /** Always `'release'`: a reopened segment reuses its journal, not retired environments. */\n readonly retainedAtSettlement?: 'release'\n /** As for {@link supervisePursuit}. */\n readonly observerDelivery?: PursuitObserverDelivery\n /** Explicitly reopen a settled segment under this graph's existing run id and journal. */\n readonly reopen?: RunReopen\n}\n\n/**\n * One-call durable execution of an `AgentGraph`: the graph twin of {@link supervisePursuit}.\n *\n * It owns the run directory exactly as `supervisePursuit` does — `supervise.lock` for the life of\n * the call, `observer.jsonl`, `result.json` once the graph settles, `failure.json` for the most\n * recent throw, and refusal of a settled directory before any compute — and runs the graph through\n * `runGraph`'s own path, so the root node is a `supervise()` root and a restarted process resumes\n * the graph from its spawn journal. `result.json` holds the graph's supervised result, the same\n * record every supervised run leaves; the edge ledger is the journal's `edge` events and the\n * returned `result.ledger`. Version chains and forks are `supervisePursuit` features and are not\n * offered here. An explicit `reopen` uses the same archived-settle and resume contract as\n * `supervisePursuit`; ordinary re-entry of a settled graph stays refused.\n */\nexport async function superviseGraphPursuit(\n graph: AgentGraph,\n opts: SuperviseGraphPursuitOptions,\n): Promise<SupervisedPursuitResult<GraphResult>> {\n assertPursuitDirectory(opts, 'superviseGraphPursuit')\n if (opts.reopen !== undefined) assertRunReopen(opts.reopen, {})\n const {\n pursuitId: _pursuitId,\n hooks: _hooks,\n observerDelivery: _observerDelivery,\n brain,\n reopen,\n ...graphOptions\n } = opts\n return runDurablePursuit(\n opts,\n ({ hooks, steerDir }) =>\n superviseAgentGraph(\n reopen?.budget === undefined ? graph : { ...graph, budget: reopen.budget },\n graphExecutionOptions({\n ...graphOptions,\n // The lock, the settle record and the journal name one run, so the graph takes the\n // directory's run id rather than its own digest-derived default.\n runId: graphOptions.runId ?? 'supervise',\n ...(reopen === undefined ? {} : { resume: true }),\n steerDir,\n retainedAtSettlement: 'release',\n hooks,\n }),\n brain,\n ),\n (result) => result.result,\n reopen === undefined\n ? undefined\n : (observer) =>\n reopenSettledRun({\n runDir: opts.runDir.trim(),\n runId: opts.runId ?? 'supervise',\n reopen,\n journal: opts.journal,\n limits: {\n budget: graph.budget,\n ...(opts.reservationPolicy === undefined\n ? {}\n : { reservationPolicy: opts.reservationPolicy }),\n },\n observer,\n pursuitId: opts.pursuitId.trim(),\n now: opts.now ?? Date.now,\n }),\n )\n}\n\n/** The pursuit identity and run directory both durable entries require. */\nfunction assertPursuitDirectory(\n opts: {\n readonly pursuitId: string\n readonly runDir: string\n readonly retainedAtSettlement?: string\n },\n entry: string,\n): void {\n for (const field of ['pursuitId', 'runDir'] as const) {\n if (opts[field].trim().length === 0) throw new TypeError(`${entry}: ${field} must be non-empty`)\n }\n if (opts.retainedAtSettlement === 'keep') {\n throw new TypeError(\n `${entry}: retainedAtSettlement 'keep' cannot hold, because a settled pursuit is never re-entered`,\n )\n }\n}\n\n/**\n * The run directory's lifecycle around one execution: lock, settled-directory refusal, observer\n * journal, failure record and settle record. `execute` receives the observer-composed hooks and\n * the steer directory the run's control plane uses; `settled` names the value `result.json` holds.\n */\nasync function runDurablePursuit<Result>(\n opts: Pick<\n SupervisePursuitOptions,\n 'pursuitId' | 'runDir' | 'runId' | 'now' | 'hooks' | 'steerDir' | 'observerDelivery'\n >,\n execute: (seams: { readonly hooks: RuntimeHooks; readonly steerDir: string }) => Promise<Result>,\n settled: (result: Result) => SupervisedResult<unknown>,\n reopen?: (observer: FileObserverJournal) => Promise<void>,\n): Promise<SupervisedPursuitResult<Result>> {\n const pursuitId = opts.pursuitId.trim()\n const runDir = opts.runDir.trim()\n const observerPath = resolve(runDir, 'observer.jsonl')\n const settlePath = resolve(runDir, SETTLE_RECORD_FILE)\n const failurePath = resolve(runDir, FAILURE_RECORD_FILE)\n const runId = opts.runId ?? 'supervise'\n const now = opts.now ?? Date.now\n\n // The lock is taken before the settle record is read so a run that settles between the read\n // and the lock cannot be re-entered; both refusals happen before the observer journal is touched.\n const lock = await acquireRunDirectoryLock(runDir, runId, now)\n return lock.run(async () => {\n let delivery: PursuitObserverDeliverer | undefined\n let terminalState: 'done' | 'failed' | 'running' = 'failed'\n try {\n const observer = createFileObserverHooks(observerPath, pursuitId)\n if (reopen !== undefined) await reopen(observer.journal)\n else {\n const prior = await readSettleRecord(runDir)\n if (prior !== undefined) {\n throw new SettledRunDirectoryError(settlePath, prior.tree.root, runId)\n }\n }\n\n // Root lifecycle is an observer-plane fact, not something the manager has to\n // narrate about itself. This also makes a zero-spawn/single-agent run observable.\n await observer.journal.appendEvent(rootEvent(pursuitId, runId, 'before', now()))\n delivery =\n opts.observerDelivery === undefined\n ? undefined\n : startPursuitObserverDelivery(opts.observerDelivery, async () =>\n projectPursuit(await observer.journal.read()),\n )\n\n let result: Result\n try {\n result = await execute({\n // The observer runs first so a caller hook that throws cannot prevent the\n // canonical lifecycle fact from entering the durable journal.\n hooks: withPursuitContext(pursuitId, composeRuntimeHooks(observer.hooks, opts.hooks)),\n // `runDir` owns the pursuit journal and terminal records. The public steer writer\n // addresses the canonical per-run event directory beneath that root, so keep its control\n // plane there without moving the durable pursuit records.\n steerDir: opts.steerDir ?? supervisorRunDir(runDir, runId),\n })\n } catch (error) {\n if (error instanceof RunParkedError && error.runId === runId) {\n terminalState = 'running'\n throw error\n }\n let pursuit: PursuitProjection\n try {\n // The journal fact is raw evidence and lands first; the failure record summarizes it.\n await observer.journal.appendEvent(\n rootEvent(pursuitId, runId, 'error', now(), {\n status: 'failed',\n error: errorMessage(error),\n failure: runtimeFailureCause(error),\n }),\n )\n pursuit = projectPursuit(await observer.journal.read())\n } catch (observerError) {\n throw new Error(\n 'supervisePursuit: Runtime failed and durable observer completeness could not be proven',\n { cause: new AggregateError([error, observerError]) },\n )\n }\n // A failure record that cannot be written must not hide the journal fact above; it is\n // reported as its own cause beside the run's error.\n try {\n // The root's stream is already on disk whether or not the run settled; the record names\n // it so a root that died mid-turn keeps what it had streamed.\n const rootStream = await readRootStreamReceipt(runDir)\n await writeFailureRecord(runDir, {\n runId,\n pursuitId,\n at: new Date(now()).toISOString(),\n error: { name: errorName(error), message: errorMessage(error) },\n ...(rootStream === undefined ? {} : { rootStream }),\n })\n } catch (recordError) {\n throw new Error(\n `supervisePursuit: Runtime failed and the failure record ${failurePath} could not be written`,\n { cause: new AggregateError([error, recordError]) },\n )\n }\n throw new SupervisePursuitError(error, pursuit, observerPath, failurePath)\n }\n\n // The settle record is the re-entry guard, so it is durable before the journal says `done`.\n // A record that cannot be written leaves the attempt open in the journal and the run\n // re-enterable, which replays the settled children and settles again.\n const terminal = settled(result)\n try {\n await writeSettleRecord(runDir, terminal)\n } catch (cause) {\n throw new Error(\n `supervisePursuit: Runtime settled but the settle record ${settlePath} could not be written`,\n { cause },\n )\n }\n await observer.journal.appendEvent(\n rootEvent(pursuitId, runId, 'after', now(), {\n status: 'done',\n ...(terminal.kind === 'no-winner' &&\n terminal.reason === 'driver-failed' &&\n terminal.error.failure\n ? { error: terminal.error.message, failure: terminal.error.failure }\n : {}),\n }),\n )\n terminalState = 'done'\n return Object.freeze({\n result,\n pursuit: projectPursuit(await observer.journal.read()),\n observerPath,\n settlePath,\n })\n } finally {\n // The terminal delivery reads the journal after its last fact, and is bounded so an\n // unreachable Intelligence delays the return by at most twice its timeout.\n await delivery?.close(terminalState)\n await lock.release()\n }\n })\n}\n\nfunction rootEvent(\n pursuitId: string,\n runId: string,\n phase: 'before' | 'after' | 'error',\n timestamp: number,\n payload?: Record<string, unknown>,\n): RuntimeHookEvent {\n return Object.freeze({\n id: `${runId}:pursuit:${phase}:${timestamp}`,\n pursuitId,\n runId,\n target: 'agent.run',\n phase,\n timestamp,\n ...(payload ? { payload: Object.freeze({ ...payload }) } : {}),\n })\n}\n\nfunction errorName(error: unknown): string {\n return error instanceof Error ? error.name : 'NonError'\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAkCA,MAA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AM,SAAS,QAAQ,KAAK,CAAC;IACrD;IACA;GACF,CAAC;EACH,UAAU;GAGR,MAAM,UAAU,MAAM,aAAa;GACnC,MAAM,KAAK,QAAQ;EACrB;CACF,CAAC;AACH;AAEA,SAAS,UACP,WACA,OACA,OACA,WACA,SACkB;CAClB,OAAO,OAAO,OAAO;EACnB,IAAI,GAAG,MAAM,WAAW,MAAM,GAAG;EACjC;EACA;EACA,QAAQ;EACR;EACA;EACA,GAAI,UAAU,EAAE,SAAS,OAAO,OAAO,EAAE,GAAG,QAAQ,CAAC,EAAE,IAAI,CAAC;CAC9D,CAAC;AACH;AAEA,SAAS,UAAU,OAAwB;CACzC,OAAO,iBAAiB,QAAQ,MAAM,OAAO;AAC/C"}
|
|
1
|
+
{"version":3,"file":"durable.js","names":["delay"],"sources":["../src/durable/settle-record.ts","../src/durable/pursuit-version-evidence.ts","../src/durable/pursuit-version-review.ts","../src/durable/pursuit-version-run.ts","../src/durable/pursuit-versions.ts","../src/durable/run-fork.ts","../src/durable/run-lock.ts","../src/durable/pursuit-observer-delivery.ts","../src/durable/run-reopen.ts","../src/durable/supervise-pursuit.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { canonicalCandidateDigest, canonicalCandidateJson } from '@tangle-network/agent-interface'\nimport {\n publishExclusiveDurableFile,\n writeAtomicDurableFile,\n} from '../runtime/supervise/durable-file'\nimport type { RootStreamReceipt, SupervisedResult } from '../runtime/supervise/types'\nimport { isNoEntError } from './jsonl-file'\n\n/*\n * The terminal records `supervisePursuit` leaves in a run directory.\n *\n * Measured motive (discovery-lab recursive smoke r1): Runtime settled `no-winner`\n * at 06:27:51Z with a terminal `agent.run` event and returned the result to the caller, and the\n * directory held no terminal record. agent-eval's supervisor-run reader names `result.json` as\n * Runtime's own terminal record and reported `supStatus: unavailable` for that run and for every\n * run on that path. The Lab's re-entry guard checked `result.json`, so it never fired, and a\n * second `run` or `resume` on the settled directory re-entered `supervise` and spent again.\n *\n * `result.json` is the JSON value of the `SupervisedResult` the call returned, as canonical JSON\n * (RFC 8785, stable key order), so its bytes hash to `settleRecordDigest(result)`. A result that\n * carries a value JSON cannot represent faithfully (a Map, a Set, a Date, a typed array, a class\n * instance) is refused rather than silently rewritten, because the file is raw terminal evidence.\n * It is written once per segment with\n * `O_EXCL`, fsynced, and never replaced: a second settle in the same directory is refused before\n * any compute. An explicit reopen (`supervisePursuit`'s `reopen`, `./run-reopen.ts`) archives it\n * byte for byte to `settles/<n>.json` and removes it, and the reopened segment writes its own. `failure.json` records the most recent throw and is replaced by a later throw; the\n * history of every attempt stays in `observer.jsonl`. A failure record alone never blocks\n * re-entry, because r1's first attempt threw on a caller input error before any spawn and the\n * corrected attempt on the same directory produced all of the run's evidence.\n */\n\n/** The settle record: the returned `SupervisedResult` as canonical JSON, written once. */\nexport const SETTLE_RECORD_FILE = 'result.json'\n/** The failure record: the most recent throw, replaced by a later throw. */\nexport const FAILURE_RECORD_FILE = 'failure.json'\n\n/** What `failure.json` records about the most recent throw. */\nexport interface DurableFailureRecord {\n readonly runId: string\n readonly pursuitId: string\n /** ISO instant the throw was recorded. */\n readonly at: string\n readonly error: { readonly name: string; readonly message: string }\n /** The root's retained provider stream at the time of the throw, when the directory holds one:\n * a root that died mid-turn keeps what it had streamed, and this names it. */\n readonly rootStream?: RootStreamReceipt\n}\n\n/** The directory already holds a settle record, so the run it records must not be re-entered. */\nexport class SettledRunDirectoryError extends Error {\n readonly path: string\n /** The root of the recorded run, which is its `runId`. */\n readonly recordedRunId: string\n\n constructor(path: string, recordedRunId: string, requestedRunId: string) {\n super(\n recordedRunId === requestedRunId\n ? `supervisePursuit: ${path} records that run '${recordedRunId}' already settled; a settled run is not re-entered unless the call passes reopen: { operator, reason, operationId }`\n : `supervisePursuit: ${path} records that run '${recordedRunId}' already settled in this directory; a directory holds one settle record, so run '${requestedRunId}' needs its own runDir`,\n )\n this.name = 'SettledRunDirectoryError'\n this.path = path\n this.recordedRunId = recordedRunId\n }\n}\n\n/** A result member whose JSON form would misstate it. */\nclass UnrecordableSettleValueError extends TypeError {\n readonly path: string\n\n constructor(path: string, kind: string) {\n super(\n `supervisePursuit: result${path} is a ${kind}, which JSON cannot record faithfully; a settle record holds plain data only`,\n )\n this.name = 'UnrecordableSettleValueError'\n this.path = path\n }\n}\n\nconst PLAIN_PROTOTYPES = new Set<unknown>([Object.prototype, Array.prototype, null])\n\n/**\n * The JSON value of a result, or a throw naming the first member JSON would misstate. An\n * `undefined` member and a function are dropped, exactly as any JSON consumer drops them; a Map,\n * a Set, a Date, a typed array, or a class instance would be rewritten to `{}` or a string and\n * so is refused.\n */\nfunction jsonValue(result: unknown): unknown {\n const seen: unknown[] = []\n const visit = (value: unknown, path: string): void => {\n if (value === null || typeof value !== 'object') return\n if (value instanceof Map) throw new UnrecordableSettleValueError(path, 'Map')\n if (value instanceof Set) throw new UnrecordableSettleValueError(path, 'Set')\n if (value instanceof Date) throw new UnrecordableSettleValueError(path, 'Date')\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n throw new UnrecordableSettleValueError(path, 'binary buffer')\n }\n if (!PLAIN_PROTOTYPES.has(Object.getPrototypeOf(value))) {\n throw new UnrecordableSettleValueError(path, 'class instance')\n }\n if (seen.includes(value)) throw new UnrecordableSettleValueError(path, 'cycle')\n seen.push(value)\n if (Array.isArray(value)) {\n for (const [index, item] of value.entries()) visit(item, `${path}[${index}]`)\n } else {\n for (const [key, item] of Object.entries(value)) visit(item, `${path}.${key}`)\n }\n seen.pop()\n }\n visit(result, '')\n return JSON.parse(JSON.stringify(result))\n}\n\n/**\n * The exact bytes `result.json` holds for a result: its JSON value serialized as RFC 8785\n * canonical JSON. Throws `UnrecordableSettleValueError` before any byte is written when the\n * result carries a value JSON would misstate.\n */\nexport function settleRecordJson(result: unknown): string {\n return canonicalCandidateJson(jsonValue(result))\n}\n\n/** The digest the settle record's bytes hash to: the candidate digest of the result's JSON value. */\nexport function settleRecordDigest(result: unknown): string {\n return canonicalCandidateDigest(jsonValue(result))\n}\n\n/** Publish `result.json` in the run directory once. Throws when a record is already there. */\nexport async function writeSettleRecord(runDir: string, result: unknown): Promise<string> {\n const path = resolve(runDir, SETTLE_RECORD_FILE)\n if (!publishExclusiveDurableFile(path, settleRecordJson(result))) {\n throw new Error(`supervisePursuit: ${path} already exists; a settle record is written once`)\n }\n return path\n}\n\n/** Replace `failure.json` in the run directory with the most recent throw. */\nexport async function writeFailureRecord(\n runDir: string,\n record: DurableFailureRecord,\n): Promise<string> {\n const path = resolve(runDir, FAILURE_RECORD_FILE)\n writeAtomicDurableFile(path, `${JSON.stringify(record, null, 2)}\\n`)\n return path\n}\n\n/**\n * Read the settle record a run directory holds, or `undefined` when it holds none. A file that\n * is present but is not a settle record is corruption and fails loud.\n */\nexport async function readSettleRecord(\n runDir: string,\n): Promise<SupervisedResult<unknown> | undefined> {\n const path = resolve(runDir, SETTLE_RECORD_FILE)\n let text: string\n try {\n text = await readFile(path, 'utf8')\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\n }\n return parseSettleRecord(text, path)\n}\n\n/** Parse settle-record bytes already read, so a caller hashes and parses the same bytes. */\nexport function parseSettleRecord(text: string, path: string): SupervisedResult<unknown> {\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch (cause) {\n throw new Error(`supervisePursuit: ${path} is not valid JSON`, { cause })\n }\n const record = parsed as { kind?: unknown; tree?: { root?: unknown } }\n if (\n typeof record !== 'object' ||\n record === null ||\n typeof record.kind !== 'string' ||\n typeof record.tree !== 'object' ||\n record.tree === null ||\n typeof record.tree.root !== 'string'\n ) {\n throw new Error(`supervisePursuit: ${path} is not a settle record (no kind or tree.root)`)\n }\n return parsed as SupervisedResult<unknown>\n}\n\n/** Read the most recent failure record, or `undefined` when the directory holds none. */\nexport async function readFailureRecord(runDir: string): Promise<DurableFailureRecord | undefined> {\n const path = resolve(runDir, FAILURE_RECORD_FILE)\n let text: string\n try {\n text = await readFile(path, 'utf8')\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch (cause) {\n throw new Error(`supervisePursuit: ${path} is not valid JSON`, { cause })\n }\n const record = parsed as Partial<DurableFailureRecord>\n if (\n typeof record !== 'object' ||\n record === null ||\n typeof record.runId !== 'string' ||\n typeof record.pursuitId !== 'string' ||\n typeof record.at !== 'string' ||\n typeof record.error?.name !== 'string' ||\n typeof record.error.message !== 'string' ||\n (record.rootStream !== undefined &&\n (typeof record.rootStream.ref !== 'string' || typeof record.rootStream.events !== 'number'))\n ) {\n throw new Error(`supervisePursuit: ${path} is not a failure record`)\n }\n return parsed as DurableFailureRecord\n}\n","// Sealed pursuit-version results, identity checks and settled outcome evidence.\n\nimport { access, readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport type {\n SearchArtifactRef,\n SearchAttemptAccounting,\n SearchNode,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n agentProfileSchema,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { RuntimeRunStateError, ValidationError } from '../errors'\nimport { isFiniteNumber } from '../finite-number'\nimport type { Spend, SupervisedResult } from '../runtime/supervise/types'\nimport { errorMessage } from '../runtime/util'\nimport { isNoEntError } from './jsonl-file'\nimport type { JudgedPursuitVersion, VersionVerdict } from './pursuit-versions'\nimport { parseSettleRecord, SETTLE_RECORD_FILE } from './settle-record'\n\n/** The chain's directory beside the first version's: the ledger and its content blobs. */\nexport function pursuitVersionsLedgerPath(runDir: string): string {\n return resolve(`${resolve(runDir.trim())}.search`, 'ledger.jsonl')\n}\n\n/** A search node's artifact: a version's profile, or a change that did not apply. */\nexport interface VersionNode {\n readonly profile: AgentProfile | null\n /** The change from the parent; set on a node a proposal returned in this process. */\n readonly change?: AgentProfileDiff\n readonly parentDigest?: Sha256Digest\n readonly refusal: string | null\n}\n\n/** One node of the chain, as the ledger records it. */\nexport interface VersionRecord {\n readonly nodeId: string\n readonly version: number\n readonly runId: string\n readonly runDir: string\n /** Null for a change that did not apply. */\n readonly profile: AgentProfile | null\n readonly parentNodeId: string | null\n /** The change from the parent, from the node's first edge. */\n readonly change?: AgentProfileDiff\n /** The settled attempt's seal and verdict. */\n readonly seal?: SearchArtifactRef\n readonly verdict?: VersionVerdict\n}\n\n/** The bytes of a version's sealed `result.json` and the record they hold, parsed from the same\n * bytes that are hashed. */\nexport async function readSealed(\n runDir: string,\n version: number,\n): Promise<{ bytes: Uint8Array; result: SupervisedResult<unknown> }> {\n const path = resolve(runDir, SETTLE_RECORD_FILE)\n let bytes: Uint8Array\n try {\n bytes = await readFile(path)\n } catch (error) {\n if (!isNoEntError(error)) throw error\n throw new RuntimeRunStateError(\n `supervisePursuit versions: version ${version} has no settle record in ${runDir}`,\n )\n }\n return { bytes, result: parseSettleRecord(Buffer.from(bytes).toString('utf8'), path) }\n}\n\n/** A profile as the JSON the ledger stores: validated, with undefined entries absent. */\nexport function jsonProfile(profile: unknown): AgentProfile {\n canonicalAgentProfileDigest(profile as AgentProfile)\n return JSON.parse(JSON.stringify(agentProfileSchema.parse(profile))) as AgentProfile\n}\n\nexport function loadNode(\n store: { readBlob(ref: SearchArtifactRef): unknown },\n node: SearchNode,\n): VersionNode {\n const stored = store.readBlob(node.artifact) as {\n kind?: unknown\n profile?: unknown\n change?: AgentProfileDiff | null\n parentDigest?: Sha256Digest | null\n refusal?: string | null\n }\n if (stored.kind === 'agent-profile') {\n const parsed = agentProfileSchema.safeParse(stored.profile)\n if (!parsed.success) {\n throw new RuntimeRunStateError(`version node ${node.nodeId} holds an invalid AgentProfile`)\n }\n return { profile: parsed.data as AgentProfile, refusal: null }\n }\n if (stored.kind === 'unapplied-change') {\n return {\n profile: null,\n ...(stored.change ? { change: stored.change } : {}),\n ...(stored.parentDigest ? { parentDigest: stored.parentDigest } : {}),\n refusal: stored.refusal ?? 'the change did not apply',\n }\n }\n throw new RuntimeRunStateError(`version node ${node.nodeId} holds no version artifact`)\n}\n\n/** The `<runDir>.v<n>` directory and `<runId>.v<n>` id of version `n`, beside the first. */\nexport function versionRun(runDir: string, runId: string, version: number) {\n return version === 1\n ? { runDir, runId }\n : { runDir: `${runDir}.v${version}`, runId: `${runId}.v${version}` }\n}\n\n/** A version's settled spend as the ledger's accounting. Unknown dollars carry the part a\n * provider is known to have billed as their floor. */\nexport function versionAccounting(spent: Spend | undefined): SearchAttemptAccounting {\n const tokensKnown =\n spent !== undefined &&\n spent.tokensKnown !== false &&\n spent.tokens?.tokensKnown !== false &&\n Number.isSafeInteger(spent.tokens?.input) &&\n Number.isSafeInteger(spent.tokens?.output) &&\n Number.isSafeInteger(spent.tokens?.cacheRead)\n const usdKnown = spent !== undefined && spent.usdKnown !== false && isFiniteNumber(spent.usd)\n return {\n tokens: tokensKnown\n ? {\n status: 'known',\n inputTokens: spent.tokens.input,\n outputTokens: spent.tokens.output,\n cachedTokens: spent.tokens.cacheRead!,\n }\n : {\n status: 'unknown',\n reason: `the version's settled spend reports no complete token count with its cache split (input ${spent?.tokens?.input ?? 'none'}, output ${spent?.tokens?.output ?? 'none'})`,\n },\n cost: usdKnown\n ? { status: 'known', usd: spent.usd, source: 'provider' }\n : {\n status: 'unknown',\n knownLowerBoundUsd: Math.max(\n 0,\n isFiniteNumber(spent?.usd) ? spent.usd - (spent.usdEstimated ?? 0) : 0,\n ),\n reason: \"the version's settled spend names unpriced or unreported work\",\n },\n }\n}\n\n/** How long a version that settled before its chain opened ran, from its settle record. */\nexport function settledElapsed(settled: SupervisedResult<unknown> | undefined): number {\n const elapsed = settled?.spentTotal?.ms\n return isFiniteNumber(elapsed) ? elapsed : 0\n}\n\nexport const FREE: SearchAttemptAccounting = {\n tokens: { status: 'known', inputTokens: 0, outputTokens: 0, cachedTokens: 0 },\n cost: { status: 'known', usd: 0, source: 'free' },\n}\n\n/**\n * What a version that did no work failed with: a driver error, by its name and its message with\n * the parts that differ between runs (digits, hex runs, absolute paths) normalized, or an unscored\n * verdict. Null for a version that ran, won or not.\n */\nexport function versionFailure(version: JudgedPursuitVersion): string | null {\n if (version.verdict.score === null) return 'unscored by the judge'\n const { result } = version\n if (result.kind !== 'no-winner' || result.reason !== 'driver-failed') return null\n const message = result.error.message\n .replace(/(?:\\/[\\w.@~+-]+){2,}/gu, '<path>')\n .replace(/\\b[0-9a-f]{8,}\\b/giu, '<hex>')\n .replace(/\\d+/gu, '<n>')\n .slice(0, 500)\n return `driver-failed: ${result.error.name}: ${message}`\n}\n\nexport function pursuitValueDigest(value: unknown, name: string): Sha256Digest {\n try {\n return canonicalCandidateDigest(value)\n } catch (error) {\n throw new ValidationError(\n `supervisePursuit versions: the ${name} must be canonical JSON to pin the chain: ${errorMessage(error)}`,\n )\n }\n}\n\nexport async function exists(path: string): Promise<boolean> {\n try {\n await access(path)\n return true\n } catch (error) {\n if (isNoEntError(error)) return false\n throw error\n }\n}\n\nexport function isSha256(value: unknown): value is Sha256Digest {\n return typeof value === 'string' && /^sha256:[0-9a-f]{64}$/u.test(value)\n}\n","// Profile review instructions and their mounted verdict page.\n\nimport type { AgentProfileDiff } from '@tangle-network/agent-interface'\nimport type { CheckVerdict } from '../runtime/supervise/completion-gate'\nimport { failedItems } from '../runtime/supervise/continuation'\nimport type { NextPursuitVersion } from './pursuit-versions'\n\n/** Where `'review-of-best'` mounts a review: `inputs/review/version-<n>.md`. One review lives in\n * a profile at a time. */\nconst REVIEW_DIR = 'inputs/review/'\n\n/**\n * `'review-of-best'`: fork from the kept version with its check's verdict mounted under\n * {@link REVIEW_DIR} and the profile's review words as one instruction. The previous review's\n * mount and instruction are removed, so a profile carries one review.\n */\nexport function reviewOfBest(runId: string, words: string): NextPursuitVersion {\n return ({ best, versions }) => {\n const n = versions.length + 1\n const verdict = best.verdict.check\n const path = `${REVIEW_DIR}version-${best.version}.md`\n const instruction = words\n .replaceAll('{version}', String(best.version))\n .replaceAll('{path}', path)\n .replaceAll('{score}', best.verdict.score === null ? 'none' : String(best.verdict.score))\n .trim()\n const page = reviewPage(best.version, best.verdict.score, verdict)\n // Instructions are set and removed by value: an earlier review instruction equal to this one\n // stays as it is, and every other earlier one is removed.\n const earlier = best.change?.set?.prompt?.instructions ?? []\n const earlierInstructions = earlier.filter((text) => text !== instruction)\n const earlierMounts = (best.profile.resources?.files ?? [])\n .map((file) => file.path)\n .filter((mounted) => mounted.startsWith(REVIEW_DIR) && mounted !== path)\n return {\n kind: 'agent-profile-diff',\n id: `${runId}-v${n}-review-of-v${best.version}`,\n title: `Version ${n}: review of version ${best.version}`,\n source: {\n kind: 'optimizer',\n notes: [`review-of-best: version ${best.version}`, `judge ${best.verdict.judgeDigest}`],\n },\n set: {\n ...(earlier.includes(instruction) ? {} : { prompt: { instructions: [instruction] } }),\n resources: {\n files: [{ path, resource: { kind: 'inline', name: path, content: page } }],\n },\n },\n ...(earlierInstructions.length > 0 || earlierMounts.length > 0\n ? {\n remove: {\n ...(earlierInstructions.length > 0\n ? { prompt: { instructions: [...earlierInstructions] } }\n : {}),\n ...(earlierMounts.length > 0 ? { resources: { files: earlierMounts } } : {}),\n },\n }\n : {}),\n } as AgentProfileDiff\n }\n}\n\n/** The review page: facts only, in the check's own lines. */\nfunction reviewPage(\n version: number,\n score: number | null,\n verdict: CheckVerdict | undefined,\n): string {\n if (verdict === undefined) {\n return [\n `# Version ${version}`,\n '',\n `Score: ${score ?? 'none'}. The judge reported no per-item verdict.`,\n '',\n ].join('\\n')\n }\n const failing = failedItems(verdict)\n return [\n `# Version ${version}`,\n '',\n `Score: ${score ?? 'none'}.${verdict.threshold === undefined ? '' : ` The check passes at ${verdict.threshold}.`}`,\n '',\n '## Items',\n '',\n ...Object.entries(verdict.items ?? {}).map(\n ([item, value]) => `- ${item}: ${value >= 1 ? 'passes' : `fails (${value})`}`,\n ),\n '',\n ...(failing.length === 0 ? [] : ['## Failures', '', ...(verdict.failures ?? []), '']),\n ...(verdict.review === undefined ? [] : [\"## The check's review\", '', verdict.review, '']),\n ].join('\\n')\n}\n","/**\n * One pursuit version chain at run time: running a version in its directory, reading it back\n * and checking it is this node's run, judging it, turning it into the kernel's cell result, and\n * reading the chain back from its search ledger.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport {\n parseSearchLedgerLine,\n type SearchCellResult,\n type SearchCellSettledEvent,\n type SearchCellWork,\n type SearchExecutionIdentity,\n type SearchRecorder,\n type SearchTaskOutcome,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n canonicalAgentProfileDigest,\n type Sha256Digest,\n sha256Bytes,\n} from '@tangle-network/agent-interface'\nimport { RuntimeRunStateError, ValidationError } from '../errors'\nimport { isFiniteNumber } from '../finite-number'\nimport { authoredProfileDigest } from '../runtime/supervise/materialization'\nimport { superviseRootProfile } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { SpawnEvent, SupervisedResult } from '../runtime/supervise/types'\nimport { errorMessage } from '../runtime/util'\nimport { contentAddress } from './content-address'\nimport {\n loadNode,\n readSealed,\n type VersionNode,\n type VersionRecord,\n versionAccounting,\n versionRun,\n} from './pursuit-version-evidence'\nimport type {\n JudgedPursuitVersion,\n SettledPursuitVersion,\n VersionJudge,\n VersionVerdict,\n} from './pursuit-versions'\nimport type { PursuitFork } from './run-fork'\nimport { readSettleRecord, SETTLE_RECORD_FILE } from './settle-record'\nimport { FileSpawnJournal } from './spawn-journal/journal-store'\nimport type { SupervisedPursuitResult, SupervisePursuitOptions } from './supervise-pursuit'\n\nexport type RunOne = (\n profile: SupervisorProfile,\n task: unknown,\n opts: SupervisePursuitOptions,\n) => Promise<SupervisedPursuitResult<SupervisedResult<unknown>>>\n\n/** What one chain's versions share. */\nexport interface VersionChainContext {\n readonly profile: SupervisorProfile\n readonly task: unknown\n /** The call's options without the fields each version sets for itself. */\n readonly base: Omit<SupervisePursuitOptions, 'versions' | 'fork' | 'signal'>\n readonly firstFork: PursuitFork | undefined\n readonly runOne: RunOne\n readonly judge: VersionJudge\n readonly recorder: SearchRecorder\n /** Aborts a running version when the chain reaches its deadline. */\n readonly expired: AbortSignal\n readonly pursuitId: string\n readonly runDir: string\n readonly runId: string\n readonly ledgerPath: string\n readonly searchId: string\n readonly taskRevision: string\n}\n\n/** The execution identity a version's node and cell record. */\nexport function versionExecutionIdentity(\n pursuitId: string,\n taskRevision: string,\n nodeProfile: AgentProfile,\n): SearchExecutionIdentity {\n return {\n model: {\n provider: 'agent-runtime',\n alias: 'supervisePursuit',\n unknown: \"a version runs every model its tree chose; the version's settle record names them\",\n },\n agent: {\n uri: `agent-profile:${pursuitId}`,\n revision: canonicalAgentProfileDigest(nodeProfile),\n },\n benchmark: { uri: `pursuit:${pursuitId}`, revision: taskRevision },\n }\n}\n\n/** A version as the judge and `next` read it. */\nfunction versionOf(\n record: VersionRecord,\n parent: VersionRecord | undefined,\n settleDigest: Sha256Digest,\n result: SupervisedResult<unknown>,\n): SettledPursuitVersion {\n return Object.freeze({\n version: record.version,\n nodeId: record.nodeId,\n runId: record.runId,\n runDir: record.runDir,\n settleDigest,\n result,\n profile: record.profile!,\n ...(parent?.seal === undefined\n ? {}\n : {\n parent: {\n version: parent.version,\n runId: parent.runId,\n settleDigest: parent.seal.sha256 as Sha256Digest,\n },\n }),\n ...(record.change === undefined ? {} : { change: record.change }),\n })\n}\n\nfunction outcomeOf(settled: SettledPursuitVersion, verdict: VersionVerdict): SearchTaskOutcome {\n if (verdict.score === null) {\n return {\n status: 'errored',\n metrics: {},\n error: {\n code: 'unscored',\n message: `the judge could not score version ${settled.version}`,\n retryable: false,\n },\n }\n }\n if (settled.result.kind === 'winner') {\n return { status: 'passed', score: verdict.score, metrics: {} }\n }\n return {\n status: 'failed',\n score: verdict.score,\n metrics: {},\n failure: {\n code: settled.result.reason,\n message: `version ${settled.version} settled without a winner: ${settled.result.reason}`,\n },\n }\n}\n\nexport class VersionChainRun {\n // Each sealed result.json is read and hashed once per call.\n private readonly sealed = new Map<Sha256Digest, SupervisedResult<unknown>>()\n\n constructor(private readonly ctx: VersionChainContext) {}\n\n /** Run a version if its directory holds no settle record, read it back, and judge it. */\n async runCell(work: SearchCellWork<VersionNode>): Promise<SearchCellResult> {\n const chain = await this.versionsOf()\n const record = chain.get(work.nodeId)\n if (record?.profile == null) {\n throw new RuntimeRunStateError(`version node ${work.nodeId} has no profile to run`)\n }\n const parent = record.parentNodeId === null ? undefined : chain.get(record.parentNodeId)\n if (parent !== undefined && (parent.seal === undefined || parent.profile === null)) {\n throw new RuntimeRunStateError(`version ${record.version}'s parent has no sealed result`)\n }\n // A version whose run throws fails the call and leaves its cell open: Runtime's driver\n // retry already ran, and calling again resumes the version in its own directory.\n if ((await readSettleRecord(record.runDir)) === undefined) {\n const signal = AbortSignal.any([work.signal, this.ctx.expired])\n if (signal.aborted) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: version ${record.version} was not started: ${errorMessage(signal.reason)}`,\n )\n }\n await this.runVersion(record, parent, signal)\n }\n const { settled, byteLength } = await this.readVersion(record, parent)\n const verdict = await this.judgeVersion(settled, work.signal)\n return this.cellResult(settled, byteLength, verdict, work.lane)\n }\n\n /** Run one version: the first as the call's own run, a later one as a fork of its parent. */\n private async runVersion(\n record: VersionRecord,\n parent: VersionRecord | undefined,\n signal: AbortSignal,\n ): Promise<void> {\n const { profile, task, base, firstFork, runOne } = this.ctx\n if (parent === undefined || record.change === undefined) {\n await runOne(profile, task, {\n ...base,\n runId: record.runId,\n runDir: record.runDir,\n ...(firstFork === undefined ? {} : { fork: firstFork }),\n signal,\n })\n return\n }\n // A version starts a new tree and never replays its parent's children, so a parent that\n // settled with a child still in doubt (a deadline or a driver failure leaves them) is forked,\n // and the version's root records those nodes.\n const fork: PursuitFork = {\n runDir: parent.runDir,\n settleDigest: parent.seal!.sha256 as Sha256Digest,\n change: record.change,\n acceptUncertain: true,\n }\n // The version's continuation note states the bar against the version it forks from.\n const check = parent.verdict?.check\n await runOne(parent.profile!, task, {\n ...base,\n ...(base.continuation !== undefined && check !== undefined\n ? {\n continuation: {\n ...base.continuation,\n best: { label: `v${parent.version}`, verdict: check },\n },\n }\n : {}),\n runId: record.runId,\n runDir: record.runDir,\n fork,\n signal,\n })\n }\n\n /**\n * Read a settled version back and check it is this node's run: its root ran the node's profile\n * and, for a fork, recorded the parent's seal and the change. A directory that holds another\n * run is refused, never adopted.\n */\n private async readVersion(\n record: VersionRecord,\n parent: VersionRecord | undefined,\n ): Promise<{ settled: SettledPursuitVersion; byteLength: number }> {\n const { base, firstFork, taskRevision } = this.ctx\n const { bytes, result } = await readSealed(record.runDir, record.version)\n if (result.tree.root !== record.runId) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: ${record.runDir} holds run '${result.tree.root}', not version ${record.version}'s '${record.runId}'`,\n )\n }\n const events = await new FileSpawnJournal(\n resolve(record.runDir, 'spawn-journal.jsonl'),\n ).loadTree(record.runId)\n const root = events?.find(\n (event): event is Extract<SpawnEvent, { kind: 'spawned' }> =>\n event.kind === 'spawned' && event.parent === undefined,\n )\n const ran = root?.identity?.profileDigest\n const expected = authoredProfileDigest(\n superviseRootProfile(record.profile!, base.profileGuidance),\n )\n const ranTask = root?.identity?.taskDigest\n const correlation = root?.identity?.correlation\n const fork =\n parent !== undefined\n ? { settleDigest: parent.seal?.sha256, changeId: record.change?.id }\n : firstFork === undefined\n ? undefined\n : { settleDigest: firstFork.settleDigest, changeId: firstFork.change.id }\n const mismatch = [\n ran !== expected ? `its root ran profile ${ran}, not ${expected}` : undefined,\n ranTask !== taskRevision ? `its root ran task ${ranTask}, not ${taskRevision}` : undefined,\n contentAddress(root?.budget) !== contentAddress(base.budget)\n ? 'its root ran under another budget'\n : undefined,\n fork !== undefined && correlation?.forkParentSettleDigest !== fork.settleDigest\n ? `its root forked from seal ${correlation?.forkParentSettleDigest}, not ${fork.settleDigest}`\n : undefined,\n fork !== undefined && correlation?.forkProfileDiffId !== fork.changeId\n ? `its root applied change ${correlation?.forkProfileDiffId}, not ${fork.changeId}`\n : undefined,\n ].filter((item): item is string => item !== undefined)\n if (mismatch.length > 0) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: version ${record.version} at ${record.runDir} is not this chain's run: ${mismatch.join('; ')}`,\n )\n }\n const settled = versionOf(record, parent, sha256Bytes(bytes), result)\n this.sealed.set(settled.settleDigest, result)\n return { settled, byteLength: bytes.byteLength }\n }\n\n private async judgeVersion(\n settled: SettledPursuitVersion,\n signal: AbortSignal,\n ): Promise<VersionVerdict> {\n const { judge } = this.ctx\n const verdict = await judge.judge(settled, signal)\n if (typeof verdict !== 'object' || verdict === null) {\n throw new ValidationError('supervisePursuit versions: the judge returned no verdict')\n }\n if (verdict.judgeDigest !== judge.digest) {\n throw new ValidationError(\n `supervisePursuit versions: the verdict for version ${settled.version} carries ${String(verdict.judgeDigest)}, not the pinned judge ${judge.digest}`,\n )\n }\n if (verdict.score !== null && !isFiniteNumber(verdict.score)) {\n throw new ValidationError(\n 'supervisePursuit versions: a verdict score must be a finite number or null',\n )\n }\n // The ledger keeps the verdict as JSON; a value JSON cannot hold is refused here.\n return JSON.parse(JSON.stringify(verdict)) as VersionVerdict\n }\n\n private cellResult(\n settled: SettledPursuitVersion,\n byteLength: number,\n verdict: VersionVerdict,\n lane: string,\n ): SearchCellResult {\n const spent = settled.result.spentTotal\n const settlePath = resolve(settled.runDir, SETTLE_RECORD_FILE)\n return {\n outcome: outcomeOf(settled, verdict),\n accounting: versionAccounting(spent),\n identity: versionExecutionIdentity(\n this.ctx.pursuitId,\n this.ctx.taskRevision,\n settled.profile,\n ),\n boxMinutes:\n isFiniteNumber(spent.boxMinutes) && spent.boxMinutesKnown !== false\n ? spent.boxMinutes\n : null,\n wallMs: isFiniteNumber(spent.ms) ? Math.max(0, Math.round(spent.ms)) : null,\n placement: { lane, boxId: null },\n traceRef: {\n unknown: `version ${settled.version} is run ${settled.runId}; the chain records no trace id`,\n },\n artifacts: [\n {\n role: 'settle-record',\n uri: pathToFileURL(settlePath).href,\n sha256: settled.settleDigest,\n byteLength,\n },\n this.ctx.recorder.blob('verdict', {\n kind: 'version-verdict',\n version: settled.version,\n runId: settled.runId,\n verdict,\n }),\n ],\n }\n }\n\n /** Every version whose latest settled cell carries a verdict, first first, each read back from\n * its sealed `result.json`. */\n async judgedVersions(chain: ReadonlyMap<string, VersionRecord>): Promise<JudgedPursuitVersion[]> {\n const judged: JudgedPursuitVersion[] = []\n for (const record of chain.values()) {\n if (record.seal === undefined || record.verdict === undefined) continue\n const seal = record.seal.sha256 as Sha256Digest\n let result = this.sealed.get(seal)\n if (result === undefined) {\n const read = await readSealed(record.runDir, record.version)\n if (sha256Bytes(read.bytes) !== seal) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: version ${record.version}'s result.json changed after it was judged`,\n )\n }\n result = read.result\n this.sealed.set(seal, result)\n }\n const parent = record.parentNodeId === null ? undefined : chain.get(record.parentNodeId)\n judged.push(\n Object.freeze({ ...versionOf(record, parent, seal, result), verdict: record.verdict }),\n )\n }\n return judged\n }\n\n /**\n * Every node of the chain, in registration order, from the ledger. The state holds cells, not\n * their events' artifacts, so each cell's seal and verdict are read from the ledger lines the\n * state verified, through Eval's own line parser.\n */\n async versionsOf(): Promise<Map<string, VersionRecord>> {\n const { recorder, ledgerPath, searchId, runDir, runId } = this.ctx\n // Take what the state holds before any await: an append retires the view.\n const state = await recorder.state()\n const head = state.head?.sequence ?? -1\n const nodes = state.nodes().map((node) => ({\n node,\n cellId: state.cells({ nodeId: node.nodeId })[0]?.cellId,\n diff: node.edgeIds[0] === undefined ? undefined : state.edge(node.edgeIds[0])?.diffs[0],\n }))\n const settledCells = new Map<string, SearchCellSettledEvent>()\n const text = await readFile(ledgerPath, 'utf8')\n for (const [index, line] of text.split('\\n').entries()) {\n if (line.length === 0) continue\n const entry = parseSearchLedgerLine(line, searchId, { path: ledgerPath, line: index + 1 })\n if (entry.sequence > head) break\n if (entry.event.kind === 'cell-settled') settledCells.set(entry.event.cellId, entry.event)\n }\n const chain = new Map<string, VersionRecord>()\n for (const { node, cellId, diff } of nodes) {\n const settled = cellId === undefined ? undefined : settledCells.get(cellId)\n const artifact = (role: string) =>\n settled?.artifacts.find((candidate) => candidate.role === role)\n const seal = artifact('settle-record')\n const verdict = artifact('verdict')\n chain.set(node.nodeId, {\n nodeId: node.nodeId,\n version: node.ordinal + 1,\n ...versionRun(runDir, runId, node.ordinal + 1),\n profile: loadNode(recorder, node).profile,\n parentNodeId: node.primaryParentId,\n ...(diff === undefined || 'unknown' in diff\n ? {}\n : { change: (recorder.readBlob(diff) as { diffs: AgentProfileDiff[] }).diffs[0]! }),\n ...(seal === undefined ? {} : { seal }),\n ...(verdict === undefined\n ? {}\n : { verdict: (recorder.readBlob(verdict) as { verdict: VersionVerdict }).verdict }),\n })\n }\n return chain\n }\n}\n","/**\n * The pursuit version chain, on Eval's search kernel (`runSearch`).\n *\n * A version is a search node: the exact AgentProfile it executes, content-addressed by\n * `canonicalAgentProfileDigest`. Every later version is an edge from the version the chain keeps,\n * whose diff is the one change `next` returned, and one cell: a `supervisePursuit` run of the\n * version, forked from its parent's sealed `result.json`, then scored by the outside judge. The\n * policy is the kernel's hill climb, `incumbent({ patience, minImprovement })`. The search ledger\n * at `<runDir>.search/ledger.jsonl` is the chain's only record and its only checkpoint: a call on\n * a closed chain reads it back, and a call on an open chain continues it.\n */\n\nimport { resolve } from 'node:path'\nimport {\n developmentClaim,\n incumbent,\n openSearchLedger,\n runSearch,\n type SearchArtifactCodec,\n type SearchAudit,\n type SearchCloseReason,\n type SearchExecutor,\n type SearchHistoryReceipt,\n type SearchProposerPort,\n SearchRecorder,\n type SearchSourceRef,\n uniform,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n canonicalAgentProfileDigest,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { applyExactAgentProfileDiff } from '../candidate-execution/profile'\nimport { RuntimeRunStateError, ValidationError } from '../errors'\nimport { isFiniteNumber } from '../finite-number'\nimport type { CheckVerdict } from '../runtime/supervise/completion-gate'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { SupervisedResult } from '../runtime/supervise/types'\nimport { errorMessage } from '../runtime/util'\nimport { FileObserverJournal } from './observer-journal'\nimport { projectPursuit } from './observer-projection'\nimport {\n exists,\n FREE,\n isSha256,\n jsonProfile,\n loadNode,\n pursuitValueDigest,\n pursuitVersionsLedgerPath,\n settledElapsed,\n type VersionNode,\n versionFailure,\n} from './pursuit-version-evidence'\nimport { reviewOfBest } from './pursuit-version-review'\nimport { type RunOne, VersionChainRun, versionExecutionIdentity } from './pursuit-version-run'\nimport { readSettleRecord, SETTLE_RECORD_FILE } from './settle-record'\nimport type { SupervisedPursuitResult, SupervisePursuitOptions } from './supervise-pursuit'\n\n/**\n * Continue a pursuit across versions: after each version settles, an outside judge scores it, and\n * the next version forks from the version the chain keeps with one change, until the stop rule\n * ends the chain.\n */\nexport interface PursuitVersions {\n /** Scores each settled version from outside its tree: the run's declared check\n * (`declaredCheckJudge`), or any judge with a digest. */\n readonly judge: VersionJudge\n /** The change the next version applies to the kept version's profile. `'review-of-best'`\n * mounts the kept version's verdict under `inputs/review/`, replaces any earlier review, and\n * gives the next version's continuation note the kept version's per-item verdict as its bar. */\n readonly next: NextPursuitVersion | 'review-of-best'\n /** When the chain stops. Every cap is required: a chain without one is refused. */\n readonly stop: PursuitVersionStop\n}\n\n/** The chain's stop rule. The chain starts no version its caps do not admit. */\nexport interface PursuitVersionStop {\n /** Stop after this many proposed versions in a row that did not take the lead. */\n readonly patience: number\n /** At most this many versions, the first included. A change the chain refuses counts as one. */\n readonly maxVersions: number\n /**\n * The chain's dollars: a version starts only while settled spend plus a hold for it stays\n * within this. A version's unknown spend counts as its proven floor. The hold is the version's\n * own `budget.maxUsd`, which bounds it in flight; without one it is 0 until 20 versions\n * settled, then 1.5 times the p99 of their spend.\n */\n readonly maxUsd: number\n /** The chain's wall clock, from its first version's start. A running version is aborted at it. */\n readonly deadlineMs: number\n /** A version takes the lead when its score beats the kept version's by more than this.\n * Default 0. */\n readonly minImprovement?: number\n /**\n * Stop after this many versions in a row failed identically: each run ended `driver-failed`\n * with the same error, or the judge could not score it. Such a failure repeats whatever the\n * next change is (a refused workspace file, a broken credential), so neither patience nor a\n * version cap should be what stops it. Default 3.\n */\n readonly identicalFailures?: number\n}\n\n/** An outside judge. Runtime calls it after a version's settle record exists, never inside the\n * version's tree, and gives it no handle into that tree. Place it where you like, such as its own\n * sandbox through `runIsolatedCheck({ box })`. */\nexport interface VersionJudge {\n /** The sha256 of the judge's code and configuration. Every verdict must carry it, and a chain\n * whose ledger was opened under another digest is refused. */\n readonly digest: Sha256Digest\n judge(version: SettledPursuitVersion, signal: AbortSignal): Promise<VersionVerdict>\n}\n\nexport interface VersionVerdict {\n /** Higher is better. `null` when the judge could not score the version: the cell is recorded\n * unscored, and an unscored version never takes the lead. */\n readonly score: number | null\n /** Must equal `VersionJudge.digest`. */\n readonly judgeDigest: Sha256Digest\n /** What the judge measured, retained verbatim in the ledger. JSON values only. */\n readonly detail?: unknown\n /** The check's per-item verdict, when the judge is a check: what `'review-of-best'` mounts and\n * what the next version's bar compares against. */\n readonly check?: CheckVerdict\n}\n\n/** A settled version, as the judge and `next` read it. */\nexport interface SettledPursuitVersion {\n /** 1 for the first version: the node's registration ordinal plus 1. */\n readonly version: number\n /** The version's node in the chain's search ledger. */\n readonly nodeId: string\n readonly runId: string\n readonly runDir: string\n /** The sha256 of the version's `result.json` bytes: its seal. */\n readonly settleDigest: Sha256Digest\n readonly result: SupervisedResult<unknown>\n /** The profile the version executed: the first version's, or its parent's plus its change. */\n readonly profile: AgentProfile\n /** The version it forked from. Absent for the first version. */\n readonly parent?: {\n readonly version: number\n readonly runId: string\n readonly settleDigest: Sha256Digest\n }\n readonly change?: AgentProfileDiff\n}\n\nexport interface JudgedPursuitVersion extends SettledPursuitVersion {\n readonly verdict: VersionVerdict\n}\n\nexport interface NextPursuitVersionInput {\n /** The version the next one forks from: the version the chain keeps. */\n readonly best: JudgedPursuitVersion\n /** The most recently judged version. */\n readonly last: JudgedPursuitVersion\n /** Every judged version, first first. */\n readonly versions: readonly JudgedPursuitVersion[]\n}\n\n/** Build the one change the next version applies to `best.profile`. Its `id` must be non-empty. */\nexport type NextPursuitVersion = (\n input: NextPursuitVersionInput,\n signal: AbortSignal,\n) => AgentProfileDiff | Promise<AgentProfileDiff>\n\n/** The chain as its search ledger records it, returned beside the kept version's result. */\nexport interface PursuitVersionChain {\n /** `<runDir>.search/ledger.jsonl`: the chain's only record and checkpoint. */\n readonly ledgerPath: string\n readonly searchId: string\n /** Why the chain stopped: the kernel's close reason (`patience`, `max-nodes`, `budget`,\n * `deadline` or `converged`). */\n readonly reason: SearchCloseReason\n /** Present when the chain stopped because its last `versions` versions failed identically\n * (`stop.identicalFailures`); `reason` is then `converged`. */\n readonly identicalFailures?: { readonly versions: number; readonly failure: string }\n /** The kept version's number: the kernel's leader when the chain closed. */\n readonly best: number\n /** Every judged version, first first. */\n readonly versions: readonly JudgedPursuitVersion[]\n /** Known dollars, proven floors of unknown ones, and the counts of each. */\n readonly spend: SearchAudit['spend']\n /** A bounded receipt over the exact ledger bytes. */\n readonly receipt: SearchHistoryReceipt\n}\n\n/**\n * Validate a `versions` option before any compute. The same check runs inside `supervisePursuit`;\n * a caller that records the option as data can run it at preflight.\n */\nexport function assertPursuitVersions(versions: unknown): asserts versions is PursuitVersions {\n const fail = (message: string): never => {\n throw new ValidationError(`supervisePursuit versions: ${message}`)\n }\n if (typeof versions !== 'object' || versions === null) fail('must be an object')\n const option = versions as Record<string, unknown>\n const extra = Object.keys(option).filter((key) => !['judge', 'next', 'stop'].includes(key))\n if (extra.length > 0) fail(`unknown fields: ${extra.join(', ')}`)\n const { judge, next, stop } = option\n if (\n typeof judge !== 'object' ||\n judge === null ||\n typeof (judge as VersionJudge).judge !== 'function'\n ) {\n fail('judge must be a VersionJudge, such as declaredCheckJudge(check)')\n } else if (!isSha256((judge as VersionJudge).digest)) {\n fail('judge.digest must be a sha256 digest (sha256:<64 hex>)')\n }\n if (next !== 'review-of-best' && typeof next !== 'function') {\n fail(\"next must be a function or 'review-of-best'\")\n }\n if (typeof stop !== 'object' || stop === null) fail('stop must be an object')\n const rule = stop as Record<string, unknown>\n const known = new Set([\n 'patience',\n 'maxVersions',\n 'maxUsd',\n 'deadlineMs',\n 'minImprovement',\n 'identicalFailures',\n ])\n const unknown = Object.keys(rule).filter((key) => !known.has(key))\n if (unknown.length > 0) fail(`stop has unknown fields: ${unknown.join(', ')}`)\n for (const key of ['patience', 'maxVersions'] as const) {\n if (!Number.isInteger(rule[key]) || (rule[key] as number) < 1) {\n fail(`stop.${key} must be an integer of at least 1`)\n }\n }\n if (\n rule.identicalFailures !== undefined &&\n (!Number.isInteger(rule.identicalFailures) || (rule.identicalFailures as number) < 1)\n ) {\n fail('stop.identicalFailures must be an integer of at least 1')\n }\n for (const key of ['maxUsd', 'deadlineMs'] as const) {\n if (!isFiniteNumber(rule[key]) || (rule[key] as number) <= 0) {\n fail(`stop.${key} must be a finite number above 0`)\n }\n }\n if (\n rule.minImprovement !== undefined &&\n (!isFiniteNumber(rule.minImprovement) || rule.minImprovement < 0)\n ) {\n fail('stop.minImprovement must be a finite number of at least 0')\n }\n}\n\n/** Every rule the chain adds to the kernel's. Its digest, with the stop rule, is the process\n * revision the ledger records, so a changed rule or stop rule is a different search. */\nconst VERSION_CHAIN_DEFINITION = {\n name: 'agent-runtime.pursuit-versions.2026-09',\n node: 'the exact AgentProfile a version executes, content-addressed by canonicalAgentProfileDigest; a change that does not apply is a node addressed by its parent digest and change, and refused',\n edge: 'one change from the kept version, stored as its Interface profile diff',\n cell: 'one supervisePursuit run of the version on the pursuit task, forked from its parent sealed result.json, then scored by the outside judge; a settled version directory is read back after its root identity and fork seal are checked',\n outcome:\n 'a scored winner passes; a scored no-winner fails with its reason; an unscored version is a final error; a run that throws fails the call and leaves its cell open',\n deadline: 'the chain deadline aborts a running version; its judge still runs',\n failures:\n 'before proposing, the chain closes converged when its last stop.identicalFailures judged versions failed identically: driver-failed with the same error name and message, digits, hex runs and absolute paths normalized, or unscored by the judge',\n directories: 'version n runs at <runDir>.v<n> with run id <runId>.v<n>; version 1 at <runDir>',\n} as const\n\nconst VERSION_CHAIN_URI = 'npm:@tangle-network/agent-runtime#supervisePursuit.versions'\n/** The pursuit task's one train task. */\nconst TASK_ID = 'pursuit'\nconst LANE = 'in-process'\n/** The longest delay Node's setTimeout honors. */\nconst MAX_TIMER_MS = 2_147_483_647\n/** 9999-12-31T23:59:59.999Z: the latest instant the ledger's four-digit-year timestamps hold, so\n * a deadline such as `Number.MAX_SAFE_INTEGER` means no deadline rather than an invalid date. */\nconst LATEST_DEADLINE_MS = 253_402_300_799_999\n\ntype ChainBase = Omit<SupervisePursuitOptions, 'versions' | 'fork' | 'signal'>\n\n/** Refuse a chain call that no version could satisfy, before any compute. */\nfunction assertChainCall(versions: PursuitVersions, base: ChainBase): void {\n assertPursuitVersions(versions)\n for (const key of ['journal', 'blobs', 'rootHandle', 'steerDir'] as const) {\n if (base[key] !== undefined) {\n throw new ValidationError(\n `supervisePursuit versions: ${key} names one run, and a version chain has one per version; omit it`,\n )\n }\n }\n if (versions.next === 'review-of-best' && base.continuation?.profile.review === undefined) {\n throw new ValidationError(\n \"supervisePursuit versions: next 'review-of-best' needs continuation.profile.review, the words the next version reads about its review\",\n )\n }\n const { stop } = versions\n if (base.budget.maxUsd !== undefined && base.budget.maxUsd > stop.maxUsd) {\n throw new ValidationError(\n `supervisePursuit versions: budget.maxUsd ${base.budget.maxUsd} is above stop.maxUsd ${stop.maxUsd}, so no version could start`,\n )\n }\n}\n\n/** Run a version chain. `supervisePursuit` calls this when `versions` is set. */\nexport async function runPursuitVersions(\n profile: SupervisorProfile,\n task: unknown,\n opts: SupervisePursuitOptions & { readonly versions: PursuitVersions },\n runOne: RunOne,\n): Promise<SupervisedPursuitResult<SupervisedResult<unknown>> & { versions: PursuitVersionChain }> {\n const { versions, fork: firstFork, signal: callerSignal, ...base } = opts\n assertChainCall(versions, base)\n const { judge, stop } = versions\n const next: NextPursuitVersion =\n versions.next === 'review-of-best'\n ? reviewOfBest(base.runId ?? 'supervise', base.continuation?.profile.review ?? '')\n : versions.next\n const now = base.now ?? Date.now\n const pursuitId = base.pursuitId.trim()\n const runDir = resolve(base.runDir.trim())\n const runId = base.runId ?? 'supervise'\n const ledgerPath = pursuitVersionsLedgerPath(runDir)\n const searchId = `versions:${pursuitId}:${runId}`\n const retired = resolve(`${runDir}.versions`, 'versions.jsonl')\n if (await exists(retired)) {\n throw new ValidationError(\n `supervisePursuit versions: ${retired} holds a chain in the retired versions.jsonl format; finish it on the agent-runtime release that wrote it, or start a new chain in another runDir`,\n )\n }\n\n // The first version's executed profile; later versions derive theirs from their parent's.\n const firstProfile = jsonProfile(\n firstFork === undefined\n ? profile\n : applyExactAgentProfileDiff(profile, firstFork.change, 'supervisePursuit versions'),\n )\n const taskRevision = pursuitValueDigest(task, 'task')\n const ledger = openSearchLedger({ path: ledgerPath, searchId })\n const deadline = await chainDeadline((await ledger.state()).header, now, runDir, stop)\n const policy = incumbent({\n patience: stop.patience,\n ...(stop.minImprovement === undefined ? {} : { minImprovement: stop.minImprovement }),\n })\n const allocation = uniform()\n const recorder = await openVersionRecorder({\n ledger,\n now,\n pursuitId,\n taskRevision,\n judge,\n stop,\n policy,\n allocation,\n deadline,\n firstProfile,\n })\n\n const clock = armChainDeadline(deadline, now)\n const chain = new VersionChainRun({\n profile,\n task,\n base,\n firstFork,\n runOne,\n judge,\n recorder,\n expired: clock.signal,\n pursuitId,\n runDir,\n runId,\n ledgerPath,\n searchId,\n taskRevision,\n })\n const failureLimit = stop.identicalFailures ?? DEFAULT_IDENTICAL_FAILURES\n try {\n const closed = await runSearch({\n recorder,\n root: { profile: firstProfile, refusal: null },\n codec: versionCodec,\n policy,\n allocation,\n proposer: versionProposer(versions.next, next, chain, failureLimit),\n executor: versionExecutor(chain, base.budget.maxUsd),\n admit: (node) => node.refusal,\n ...(callerSignal === undefined ? {} : { signal: callerSignal }),\n now,\n })\n const judged = await chain.judgedVersions(await chain.versionsOf())\n // A converged chain whose last versions share a failure stopped by the identical-failure rule.\n const failed =\n closed.reason === 'converged' ? identicalFailureStreak(judged, failureLimit) : null\n const stopped = failed === null ? null : { versions: failureLimit, failure: failed }\n const best = judged.find((version) => version.nodeId === closed.leader)\n if (best === undefined) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: the chain in ${ledgerPath} closed (${closed.reason}) without a judged version to keep`,\n )\n }\n const observerPath = resolve(best.runDir, 'observer.jsonl')\n return Object.freeze({\n result: best.result,\n pursuit: projectPursuit(await new FileObserverJournal(observerPath, pursuitId).read()),\n observerPath,\n settlePath: resolve(best.runDir, SETTLE_RECORD_FILE),\n versions: Object.freeze({\n ledgerPath,\n searchId,\n reason: closed.reason,\n ...(stopped === null ? {} : { identicalFailures: stopped }),\n best: best.version,\n versions: Object.freeze(judged),\n spend: closed.state.audit.spend,\n receipt: recorder.receipt({ producerId: 'pursuit-versions', runId }),\n }),\n })\n } finally {\n clock.cancel()\n }\n}\n\ninterface VersionRecorderInput {\n ledger: ReturnType<typeof openSearchLedger>\n now: () => number\n pursuitId: string\n taskRevision: string\n judge: VersionJudge\n stop: PursuitVersionStop\n policy: { name: string }\n allocation: { name: string }\n deadline: string\n firstProfile: AgentProfile\n}\n\n/** Open the chain's search recorder: its subject, process revision, splits, policy and budget. */\nfunction openVersionRecorder(input: VersionRecorderInput): Promise<SearchRecorder> {\n const { ledger, now, pursuitId, taskRevision, judge, stop, policy, allocation, deadline } = input\n return SearchRecorder.open(\n { ledger, now },\n {\n subject: pursuitId,\n process: {\n name: 'pursuit-versions',\n executionRef: {\n uri: VERSION_CHAIN_URI,\n revision: canonicalCandidateDigest({\n ...VERSION_CHAIN_DEFINITION,\n stop: canonicalStop(stop),\n }),\n },\n },\n artifactKind: 'agent-profile',\n objective: {\n metric: 'version-judge-score',\n direction: 'maximize',\n judge: { uri: 'agent-runtime:version-judge', revision: judge.digest },\n claim: developmentClaim(pursuitId),\n },\n splits: {\n train: [\n {\n taskId: TASK_ID,\n unitId: TASK_ID,\n source: { uri: `pursuit:${pursuitId}`, revision: taskRevision },\n },\n ],\n selection: [],\n test: [],\n heldOutUnits: true,\n },\n policy: { expansion: policy.name, allocation: allocation.name, seed: 0 },\n budget: {\n maxUsd: stop.maxUsd,\n maxCells: null,\n maxNodes: stop.maxVersions,\n deadline,\n maxConcurrency: 1,\n reservedClaimUsd: 0,\n },\n containment: null,\n derivedFrom: null,\n identity: versionExecutionIdentity(pursuitId, taskRevision, input.firstProfile),\n },\n )\n}\n\n/**\n * The chain's clock starts with its first version, or when the chain opened on a first version\n * that had already settled. A resumed chain keeps the deadline its ledger recorded.\n */\nasync function chainDeadline(\n opened: { budget: { deadline: string | null } } | null | undefined,\n now: () => number,\n runDir: string,\n stop: PursuitVersionStop,\n): Promise<string> {\n return (\n opened?.budget.deadline ??\n new Date(\n Math.min(\n now() - settledElapsed(await readSettleRecord(runDir)) + stop.deadlineMs,\n LATEST_DEADLINE_MS,\n ),\n ).toISOString()\n )\n}\n\n/**\n * The chain's deadline aborts a running version. A timer longer than 2^31 - 1 ms fires at once\n * in Node, so a long chain re-arms in steps.\n */\nfunction armChainDeadline(\n deadline: string,\n now: () => number,\n): { signal: AbortSignal; cancel(): void } {\n const deadlineAt = Date.parse(deadline)\n const expired = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n const arm = () => {\n const remaining = deadlineAt - now()\n if (remaining <= 0) {\n expired.abort(new Error('the version chain reached its deadline'))\n return\n }\n timer = setTimeout(arm, Math.min(remaining, MAX_TIMER_MS))\n timer.unref?.()\n }\n arm()\n return {\n signal: expired.signal,\n cancel() {\n if (timer !== undefined) clearTimeout(timer)\n },\n }\n}\n\nconst versionCodec: SearchArtifactCodec<VersionNode> = {\n node(store, node) {\n if (node.profile !== null) {\n const artifact = store.blob('agent-profile', {\n kind: 'agent-profile',\n profile: node.profile,\n })\n return {\n artifactDigest: canonicalAgentProfileDigest(node.profile),\n artifact,\n surfaces: [{ surfaceId: 'profile', kind: 'agent-profile', artifact }],\n }\n }\n const refused = {\n kind: 'unapplied-change',\n parentDigest: node.parentDigest ?? null,\n change: node.change ?? null,\n }\n const artifact = store.blob('change', { ...refused, refusal: node.refusal })\n return {\n artifactDigest: canonicalCandidateDigest(refused),\n artifact,\n surfaces: [{ surfaceId: 'profile', kind: 'agent-profile', artifact }],\n }\n },\n diff(store, parent, child) {\n if (parent.profile === null || child.profile === null || child.change === undefined) {\n return { unknown: 'a refused change has no profile to diff' }\n }\n const from = canonicalAgentProfileDigest(parent.profile)\n if (child.parentDigest !== from) {\n return { unknown: 'the change was written against another parent' }\n }\n return store.blob('diff', {\n kind: 'agent-profile-diff',\n from,\n to: canonicalAgentProfileDigest(child.profile),\n diffs: [child.change],\n })\n },\n load(store, node) {\n return loadNode(store, node)\n },\n}\n\nfunction versionExecutor(\n chain: VersionChainRun,\n maxUsd: number | undefined,\n): SearchExecutor<VersionNode> {\n return {\n // A version's budget.maxUsd bounds it in flight, so it is the hard hold. Without one the\n // hold is the kernel's estimate: 0 until 20 versions settled, then 1.5 times their p99.\n lanes: () => [\n maxUsd === undefined\n ? { name: LANE, capacity: 1, costCap: 'estimate', cellUsd: 0 }\n : { name: LANE, capacity: 1, costCap: 'hard', cellUsd: maxUsd },\n ],\n place: () => LANE,\n // A version that settled is read back from its directory by `run`, so nothing is adopted.\n adopt: async () => null,\n run: (work) => chain.runCell(work),\n }\n}\n\n/** The proposer: the caller's `next` (or the review of the kept version) as the one edge. */\nfunction versionProposer(\n nextOption: PursuitVersions['next'],\n next: NextPursuitVersion,\n chain: VersionChainRun,\n failureLimit: number,\n): SearchProposerPort<VersionNode> {\n const reviewing = nextOption === 'review-of-best'\n const proposerSource: SearchSourceRef = {\n uri: reviewing ? `${VERSION_CHAIN_URI}.review-of-best` : `${VERSION_CHAIN_URI}.next`,\n revision: canonicalCandidateDigest({\n next: reviewing ? 'review-of-best' : Function.prototype.toString.call(nextOption),\n }),\n }\n return {\n name: reviewing ? 'review-of-best' : 'next',\n kind: 'optimizer',\n source: proposerSource,\n execution: { kind: 'deterministic', source: proposerSource },\n childrenPerProposal: 1,\n async propose(request) {\n const parent = request.parents[0]!\n const judged = await chain.judgedVersions(await chain.versionsOf())\n const failure = identicalFailureStreak(judged, failureLimit)\n if (failure !== null) {\n return {\n children: [],\n stop: `the last ${failureLimit} versions failed identically: ${failure}`,\n accounting: FREE,\n }\n }\n const best = judged.find((version) => version.nodeId === parent.nodeId)\n if (best === undefined || parent.artifact.profile === null) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: the kept version ${parent.nodeId} has no judged run to fork from`,\n )\n }\n const returned = await next(\n { best, last: judged.at(-1)!, versions: Object.freeze(judged) },\n request.signal,\n )\n if (typeof returned?.id !== 'string' || returned.id.trim().length === 0) {\n throw new ValidationError('supervisePursuit versions: next must return a change with an id')\n }\n // The ledger stores the change as JSON, so it is taken as JSON: an undefined entry is absent.\n const change = JSON.parse(JSON.stringify(returned)) as AgentProfileDiff\n const child = childNode(parent.artifact.profile, change)\n return {\n children: [\n {\n artifact: child,\n label: change.title ?? returned.id,\n rationale: (change.source?.notes ?? []).join('\\n'),\n },\n ],\n accounting: reviewing\n ? FREE\n : {\n tokens: { status: 'unknown', reason: \"the caller's next reports no usage\" },\n cost: {\n status: 'unknown',\n knownLowerBoundUsd: 0,\n reason: \"the caller's next reports no spend\",\n },\n },\n }\n },\n }\n}\n\n/** The node a change makes, or the refused node when it does not apply to the parent. */\nfunction childNode(parentProfile: AgentProfile, change: AgentProfileDiff): VersionNode {\n const parentDigest = canonicalAgentProfileDigest(parentProfile)\n try {\n return {\n profile: applyExactAgentProfileDiff(parentProfile, change, 'supervisePursuit versions'),\n change,\n parentDigest,\n refusal: null,\n }\n } catch (error) {\n return { profile: null, change, parentDigest, refusal: errorMessage(error) }\n }\n}\n\nfunction canonicalStop(stop: PursuitVersionStop): PursuitVersionStop {\n return {\n patience: stop.patience,\n maxVersions: stop.maxVersions,\n maxUsd: stop.maxUsd,\n deadlineMs: stop.deadlineMs,\n ...(stop.minImprovement === undefined ? {} : { minImprovement: stop.minImprovement }),\n identicalFailures: stop.identicalFailures ?? DEFAULT_IDENTICAL_FAILURES,\n }\n}\n\nconst DEFAULT_IDENTICAL_FAILURES = 3\n\n/** The failure the last `count` judged versions share, or null when they do not all share one. */\nexport function identicalFailureStreak(\n versions: readonly JudgedPursuitVersion[],\n count: number,\n): string | null {\n if (versions.length < count) return null\n const failures = versions.slice(-count).map(versionFailure)\n const [first] = failures\n return first !== null && first !== undefined && failures.every((failure) => failure === first)\n ? first\n : null\n}\n","import { readFile, realpath } from 'node:fs/promises'\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n canonicalCandidateDigest,\n type Sha256Digest,\n sha256Bytes,\n} from '@tangle-network/agent-interface'\nimport { applyExactAgentProfileDiff } from '../candidate-execution/profile'\nimport { RuntimeRunStateError, ValidationError } from '../errors'\nimport { authoredProfileDigest } from '../runtime/supervise/materialization'\nimport { type SuperviseOptions, superviseRootProfile } from '../runtime/supervise/supervise'\nimport type { AgentExecutionRef, SpawnEvent } from '../runtime/supervise/types'\nimport { contentAddress } from './content-address'\nimport { isNoEntError } from './jsonl-file'\nimport { readSettleRecord, SETTLE_RECORD_FILE } from './settle-record'\nimport { FileSpawnJournal } from './spawn-journal/journal-store'\nimport { loadSpawnForest } from './spawn-journal/spawn-forest'\n\n/**\n * Start a run as a version of a settled run: the parent's recorded root inputs plus one change.\n *\n * The call's `profile`, `task` and `budget` must be the parent's, byte for byte, as its sealed\n * journal records them. Runtime applies `change` to that profile and runs the result in a new\n * run directory. The parent directory is read and never written.\n */\nexport interface PursuitFork {\n /** The settled parent's run directory. */\n readonly runDir: string\n /** The sha256 of the parent's `result.json` bytes: the sealed point the fork starts from. */\n readonly settleDigest: Sha256Digest\n /** The one change, applied to the parent's root profile. Its `id` is recorded. */\n readonly change: AgentProfileDiff\n /**\n * Fork a parent whose journal holds a node without a terminal record, an unbegun owned tree, an\n * unconfirmed teardown, or work in flight. Such a node may still act, and a fork never replays\n * the parent's children, so it can only duplicate work outside the fork's tree. The root then\n * records those node ids as `forkParentUncertainNodes`. Omit it to refuse such a parent.\n */\n readonly acceptUncertain?: boolean\n}\n\n/**\n * The `execution.correlation` keys a fork records on its root. Runtime writes them; a caller that\n * supplies one is refused. `lineageRootRunId` is the first run of the chain of parents, so the\n * spend of every version of one lineage groups under one id.\n */\nexport const RUN_FORK_CORRELATION_KEYS = Object.freeze([\n 'forkParentRunId',\n 'forkParentSettleDigest',\n 'forkProfileDiffId',\n 'lineageRootRunId',\n] as const)\n\n/** The correlation key an accepted uncertain parent adds: its uncertain node ids, comma-joined. */\nconst FORK_PARENT_UNCERTAIN_NODES_KEY = 'forkParentUncertainNodes'\n\n/** What `supervisePursuit` executes for a fork: the changed profile and the attributed execution. */\ninterface PreparedRunFork {\n readonly profile: AgentProfile\n readonly execution: AgentExecutionRef\n}\n\ntype SpawnedEvent = Extract<SpawnEvent, { kind: 'spawned' }>\n\n/**\n * Verify the parent and derive the fork's profile and attribution. It reads only the parent, so\n * a refused fork spends nothing and writes nothing.\n */\nexport async function prepareRunFork(\n profile: AgentProfile,\n task: unknown,\n opts: SuperviseOptions & { readonly runId?: string; readonly runDir: string },\n fork: PursuitFork,\n): Promise<PreparedRunFork> {\n const change = fork.change\n if (typeof change?.id !== 'string' || change.id.trim().length === 0) {\n throw new ValidationError('supervisePursuit fork: change.id must be a non-empty string')\n }\n const parentDir = await realDirectory(fork.runDir, 'fork.runDir')\n const forkDir = await realDirectory(opts.runDir, 'runDir', true)\n // A fork at, inside or around the parent's directory would write into the parent.\n if (contains(parentDir, forkDir) || contains(forkDir, parentDir)) {\n throw new ValidationError(\n `supervisePursuit fork: runDir ${forkDir} overlaps the parent's runDir ${parentDir}; a fork needs its own directory outside the parent's`,\n )\n }\n\n // The seal: the exact bytes Runtime wrote once at the parent's settle.\n let bytes: Uint8Array\n try {\n bytes = await readFile(resolve(parentDir, SETTLE_RECORD_FILE))\n } catch (error) {\n if (!isNoEntError(error)) throw error\n throw new RuntimeRunStateError(\n `supervisePursuit fork: ${parentDir} holds no ${SETTLE_RECORD_FILE}; only a settled run is forked`,\n )\n }\n const observed = sha256Bytes(bytes)\n if (observed !== fork.settleDigest) {\n throw new RuntimeRunStateError(\n `supervisePursuit fork: ${SETTLE_RECORD_FILE} hashes to ${observed}, not the requested ${fork.settleDigest}`,\n )\n }\n const settled = await readSettleRecord(parentDir)\n if (settled === undefined) {\n throw new RuntimeRunStateError(`supervisePursuit fork: ${parentDir} lost its settle record`)\n }\n const parentRunId = settled.tree.root\n if ((opts.runId ?? 'supervise') === parentRunId) {\n throw new ValidationError(\n `supervisePursuit fork: runId '${parentRunId}' is the parent's; a fork needs its own runId`,\n )\n }\n\n // Certainty: a node the parent never settled may still act, so a fork could duplicate it.\n const forest = await loadSpawnForest(\n new FileSpawnJournal(resolve(parentDir, 'spawn-journal.jsonl')),\n parentRunId,\n )\n const uncertain = [\n ...forest.inDoubt.map((node) => `${node.nodeId} (no terminal record)`),\n ...forest.missingTrees.map((tree) => `${tree.ownerNodeId} (tree ${tree.root} never begun)`),\n ...(settled.teardownUnconfirmed ?? []).map((node) => `${node.id} (teardown unconfirmed)`),\n ]\n if (settled.tree.inFlight > 0 && uncertain.length === 0) {\n uncertain.push(`${settled.tree.inFlight} in flight`)\n }\n if (uncertain.length > 0 && fork.acceptUncertain !== true) {\n throw new RuntimeRunStateError(\n `supervisePursuit fork: run '${parentRunId}' has uncertain nodes: ${uncertain.join(', ')}; set fork.acceptUncertain to fork it anyway`,\n )\n }\n\n // Inputs: the fork differs from its parent by the change alone.\n const root = forest.trees[0]?.events.find(\n (event): event is SpawnedEvent => event.kind === 'spawned' && event.parent === undefined,\n )\n const recorded = root?.identity\n if (recorded?.profileDigest === undefined || recorded.taskDigest === undefined) {\n throw new RuntimeRunStateError(\n `supervisePursuit fork: run '${parentRunId}' records no root profile and task digest`,\n )\n }\n const mismatches = [\n authoredProfileDigest(superviseRootProfile(profile, opts.profileGuidance)) !==\n recorded.profileDigest\n ? `profile is not the parent's ${recorded.profileDigest}`\n : undefined,\n digestOrUndefined(task) !== recorded.taskDigest\n ? `task is not the parent's ${recorded.taskDigest}`\n : undefined,\n contentAddress(root?.budget) !== contentAddress(opts.budget)\n ? \"budget is not the parent's\"\n : undefined,\n ].filter((mismatch): mismatch is string => mismatch !== undefined)\n if (mismatches.length > 0) {\n throw new ValidationError(`supervisePursuit fork: ${mismatches.join('; ')}`)\n }\n\n const forked = applyExactAgentProfileDiff(profile, change, 'supervisePursuit fork')\n if (\n authoredProfileDigest(superviseRootProfile(forked, opts.profileGuidance)) ===\n recorded.profileDigest\n ) {\n throw new ValidationError(\n `supervisePursuit fork: change '${change.id}' leaves the parent's profile unchanged`,\n )\n }\n\n const supplied = opts.execution?.correlation ?? {}\n const owned = [...RUN_FORK_CORRELATION_KEYS, FORK_PARENT_UNCERTAIN_NODES_KEY].filter((key) =>\n Object.hasOwn(supplied, key),\n )\n if (owned.length > 0) {\n throw new ValidationError(\n `supervisePursuit fork: execution.correlation cannot set ${owned.join(', ')}; Runtime records them`,\n )\n }\n return Object.freeze({\n profile: forked,\n execution: Object.freeze({\n ...opts.execution,\n correlation: Object.freeze({\n ...supplied,\n forkParentRunId: parentRunId,\n forkParentSettleDigest: fork.settleDigest,\n forkProfileDiffId: change.id,\n lineageRootRunId: recorded.correlation?.lineageRootRunId ?? parentRunId,\n ...(uncertain.length === 0\n ? {}\n : { [FORK_PARENT_UNCERTAIN_NODES_KEY]: uncertain.join(', ') }),\n }),\n }),\n })\n}\n\nfunction digestOrUndefined(value: unknown): Sha256Digest | undefined {\n try {\n return canonicalCandidateDigest(value)\n } catch {\n return undefined\n }\n}\n\n/**\n * Resolve a directory through symlinks. The fork's own directory may not exist yet; it resolves\n * through its nearest existing ancestor, so a symlinked ancestor cannot hide an overlap.\n */\nasync function realDirectory(path: string, name: string, mayBeAbsent = false): Promise<string> {\n if (typeof path !== 'string' || path.trim().length === 0) {\n throw new ValidationError(`supervisePursuit fork: ${name} must be a non-empty string`)\n }\n const absolute = resolve(path.trim())\n try {\n return await realpath(absolute)\n } catch (error) {\n const ancestor = dirname(absolute)\n if (!mayBeAbsent || !isNoEntError(error) || ancestor === absolute) throw error\n return join(await realDirectory(ancestor, name, true), basename(absolute))\n }\n}\n\n/** Whether `inner` is `outer` or lies beneath it. */\nfunction contains(outer: string, inner: string): boolean {\n const path = relative(outer, inner)\n return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith(`..${sep}`))\n}\n","import {\n closeSync,\n existsSync,\n fstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n unlinkSync,\n} from 'node:fs'\nimport { resolve } from 'node:path'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport {\n type LockHolderRecord,\n type LockIdentity,\n lockHolderVerdict,\n lockIdentity,\n parseLockHolderRecord,\n readLockHolderIdentity,\n} from '@tangle-network/agent-eval/lock-holder'\nimport {\n publishExclusiveDurableFile,\n writeAtomicDurableFile,\n} from '../runtime/supervise/durable-file'\nimport { isNoEntError } from './jsonl-file'\nimport { mutateRunClaim, runGenerationPath, runWithWriteClaim } from './run-fence'\n\n/*\n * Exclusive ownership of one durable run directory for the life of one `supervisePursuit` call.\n *\n * Measured motive (discovery-lab recursive smoke r1): the recovery protocol is\n * `SIGKILL` the runner while a child is live, then resume on the same directory. PID 1527 was\n * killed at 06:20:27Z and PID 2058 resumed at 06:24:59Z. Nothing refused a second process while\n * the first was still alive; two processes on one directory both append to `spawn-journal.jsonl`\n * and `observer.jsonl`, and the recorded assignment keys and settlements stop being one sequence.\n * The operator relied on timing. This lock makes the second process refuse and name the holder.\n *\n * The holder is identified by its pid and the OS's start token for that pid. r1 ran in a\n * container whose pids are small (1527, 2058) and restart from 1, so a pid alone names the wrong\n * process after enough spawns: a lock left by a killed run would then match an unrelated live\n * process and hold the directory until an operator removed the file. Whether a holder is dead is\n * agent-eval's one dead-owner rule (`@tangle-network/agent-eval/lock-holder`): the record carries\n * the start token, host, boot id, pid namespace and the lock file's own inode identity, and a\n * holder is reclaimed only when those prove it gone or its pid reused. A record that cannot prove\n * that, such as one written before these fields existed, is refused and is removed by hand.\n *\n * The lock is operational state, not evidence: replay, projection, and the settle record ignore\n * it. A holder whose process is gone is reclaimed through Eval's crash-recoverable mutation lock.\n */\n\n/** The lock file `supervisePursuit` holds inside a run directory for the life of one call. */\nexport const RUN_DIRECTORY_LOCK_FILE = 'supervise.lock'\n\n/** What the lock file records about its holder. */\nexport interface RunDirectoryLockHolder {\n readonly pid: number\n /** Monotonic acquisition generation; absent on legacy lock records. */\n readonly generation?: number\n /** ISO instant the holder took the lock. */\n readonly startedAt: string\n readonly runId: string\n /** The OS's start token for `pid` when the host reports one. A holder without one is never proved dead. */\n readonly processStart?: string\n /** Hostname of the holder. Records written before it existed are never proved dead. */\n readonly host?: string\n readonly bootId?: string\n readonly pidNamespace?: string\n /** Inode identity of the lock file this record was written into. */\n readonly lock?: LockIdentity\n}\n\n/** A held lock. `release()` removes the file; it is safe to call more than once. */\nexport interface RunDirectoryLock extends RunDirectoryLockHolder {\n readonly generation: number\n readonly path: string\n /** Bind durable writes to this acquisition, including work queued before release. */\n run<T>(operation: () => T): T\n release(): Promise<void>\n}\n\n/** The directory is held by a live process. `holder` is what that process recorded. */\nexport class RunDirectoryLockedError extends Error {\n readonly path: string\n readonly holder: RunDirectoryLockHolder\n\n constructor(path: string, holder: RunDirectoryLockHolder) {\n super(\n `supervisePursuit: ${path} is held by pid ${holder.pid} (run '${holder.runId}', since ${holder.startedAt}); one process drives a run directory at a time`,\n )\n this.name = 'RunDirectoryLockedError'\n this.path = path\n this.holder = holder\n }\n}\n\n/**\n * Take `runDir/supervise.lock`, or refuse.\n *\n * The file is published with its full content or not at all, so a contender never reads a\n * half-written holder. A lock whose holder is proved dead (its pid no longer exists, the pid now\n * belongs to a process with a different start token, or the host rebooted) is stale and is removed\n * under the mutation guard; a holder that is alive or cannot be proved dead refuses. An empty file\n * names no holder and is reclaimed. A file with unreadable content is left in place and refused:\n * reclaiming it could evict a live holder written by something other than this module.\n */\nexport async function acquireRunDirectoryLock(\n runDir: string,\n runId: string,\n now: () => number = Date.now,\n): Promise<RunDirectoryLock> {\n const dir = resolve(runDir)\n const path = resolve(dir, RUN_DIRECTORY_LOCK_FILE)\n mkdirSync(dir, { recursive: true })\n const { pid, ...identity } = readLockHolderIdentity(process.pid)\n const owner = { pid, startedAt: new Date(now()).toISOString(), runId, ...identity }\n return mutateRunClaim(path, () => {\n const existing = readLockFile(path)\n if (existing.state === 'holder' && !holderIsDead(existing)) {\n throw new RunDirectoryLockedError(path, existing.holder)\n }\n let previousGeneration = 0\n try {\n previousGeneration = Number(readFileSync(runGenerationPath(dir), 'utf8'))\n if (!Number.isSafeInteger(previousGeneration) || previousGeneration < 1) {\n throw new Error('invalid run directory generation counter')\n }\n } catch (error) {\n if (!isNoEntError(error)) throw error\n }\n const generation =\n Math.max(\n previousGeneration,\n existing.state === 'holder' ? (existing.holder.generation ?? 0) : 0,\n ) + 1\n if (!Number.isSafeInteger(generation)) throw new Error('run directory generation exhausted')\n writeAtomicDurableFile(runGenerationPath(dir), `${generation}\\n`)\n if (existing.state !== 'missing') removeIfPresent(path)\n const written: { holder?: RunDirectoryLockHolder } = {}\n // The lock file is a hard link of the temporary file, so the temporary file's inode identity\n // is the lock's, and a later verdict can prove this record was written for this very lock.\n const published = publishExclusiveDurableFile(path, (file) => {\n written.holder = Object.freeze({ ...owner, generation, lock: lockIdentity(file) })\n return `${JSON.stringify(written.holder)}\\n`\n })\n const holder = written.holder\n if (!published || holder === undefined) {\n throw new Error(`supervisePursuit: could not take ${path}`)\n }\n let released = false\n return Object.freeze({\n ...holder,\n generation,\n path,\n run: <T>(operation: () => T): T => {\n if (holder.lock === undefined) throw new Error('run lock has no inode identity')\n return runWithWriteClaim({ path, generation, lock: holder.lock }, operation)\n },\n release: async () => {\n if (released) return\n await releaseHolder(path, holder)\n released = true\n },\n })\n })\n}\n\n/** Read the holder a lock file names, or `undefined` when no lock file names one. */\nexport async function readRunDirectoryLock(\n runDir: string,\n): Promise<RunDirectoryLockHolder | undefined> {\n const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE))\n return existing.state === 'holder' ? existing.holder : undefined\n}\n\n/** What {@link runDirectoryHolderIsLive} proved about a run directory's recorded holder. */\nexport interface RunDirectoryHolderLiveness {\n /** False only when the holder that took the lock is proved dead; a holder that cannot be proved dead reads as live. */\n readonly live: boolean\n /** The holder the lock file names. Absent when no lock file names one, which reads as not live. */\n readonly holder?: RunDirectoryLockHolder\n}\n\n/**\n * Whether a run directory is still held by the live process that took its lock.\n *\n * The same rule `acquireRunDirectoryLock` applies to decide whether a lock is stale, exposed so a\n * caller — a supervisor picking up an abandoned directory, an operator tool listing runs — asks\n * the question instead of hand-rolling `process.kill(pid, 0)`. A bare signal probe cannot tell a\n * live holder from an unrelated process that later took the same pid, which is the failure this\n * lock's start token exists to prevent.\n *\n * The answer is ADVISORY: it is read outside the mutation guard `acquireRunDirectoryLock` holds,\n * so a `false` can be stale by the time the caller acts on it and a concurrent acquire can take\n * the directory in between. Reporting and listing are what this is for. A caller that intends to\n * TAKE the directory calls `acquireRunDirectoryLock`, which evaluates the same rule under the\n * guard and refuses atomically.\n */\nexport async function runDirectoryHolderIsLive(\n runDir: string,\n): Promise<RunDirectoryHolderLiveness> {\n const existing = await readLockFile(resolve(runDir, RUN_DIRECTORY_LOCK_FILE))\n if (existing.state !== 'holder') return { live: false }\n return { live: !holderIsDead(existing), holder: existing.holder }\n}\n\ntype LockFileState =\n | { readonly state: 'missing' }\n | { readonly state: 'empty' }\n | {\n readonly state: 'holder'\n readonly holder: RunDirectoryLockHolder\n /** The holder as agent-eval's rule reads it; absent when the record names no host. */\n readonly record: LockHolderRecord | undefined\n /** Inode identity of the file the holder was read from. */\n readonly current: LockIdentity\n }\n\nfunction readLockFile(path: string): LockFileState {\n let text: string\n let current: LockIdentity\n try {\n const file = openSync(path, 'r')\n try {\n current = lockIdentity(fstatSync(file, { bigint: true }))\n text = readFileSync(file, 'utf8')\n } finally {\n closeSync(file)\n }\n } catch (error) {\n if (isNoEntError(error)) return { state: 'missing' }\n throw error\n }\n // This module publishes the file with its full content or not at all, so an empty file was\n // not left by a live holder.\n if (text.trim().length === 0) return { state: 'empty' }\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch (cause) {\n throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`, {\n cause,\n })\n }\n const record = parsed as Partial<RunDirectoryLockHolder> | null\n if (\n typeof record !== 'object' ||\n record === null ||\n typeof record.pid !== 'number' ||\n !Number.isInteger(record.pid) ||\n record.pid <= 0 ||\n typeof record.startedAt !== 'string' ||\n typeof record.runId !== 'string' ||\n (record.processStart !== undefined && typeof record.processStart !== 'string') ||\n (record.generation !== undefined &&\n (!Number.isSafeInteger(record.generation) || record.generation < 1))\n ) {\n throw new Error(`supervisePursuit: ${path} is not a readable lock file; remove it by hand`)\n }\n const { pid, startedAt, runId, processStart } = record\n // A missing or malformed identity field is dropped, which leaves the holder never provably dead.\n const verdictRecord = parseLockHolderRecord(parsed)\n const { pid: _pid, ...identity } = verdictRecord ?? { pid }\n return {\n state: 'holder',\n holder: Object.freeze({\n pid,\n startedAt,\n runId,\n ...(record.generation === undefined ? {} : { generation: record.generation }),\n ...(processStart === undefined ? {} : { processStart }),\n ...identity,\n }),\n record: verdictRecord,\n current,\n }\n}\n\n/** agent-eval's dead-owner rule: only a holder proved dead is stale; alive or unknown stays held. */\nfunction holderIsDead(existing: Extract<LockFileState, { state: 'holder' }>): boolean {\n return lockHolderVerdict(existing.record, existing.current).liveness === 'dead'\n}\n\n/** Remove the lock only while it still names this holder; a reclaimed lock belongs to its new owner. */\nasync function releaseHolder(path: string, holder: RunDirectoryLockHolder): Promise<void> {\n const deadline = performance.now() + 1_000\n while (existsSync(`${path}.guard`) && performance.now() < deadline) await delay(10)\n mutateRunClaim(path, () => {\n const existing = readLockFile(path)\n if (existing.state !== 'holder') return\n if (\n existing.holder.pid !== holder.pid ||\n existing.holder.startedAt !== holder.startedAt ||\n existing.holder.runId !== holder.runId ||\n existing.holder.processStart !== holder.processStart ||\n existing.holder.generation !== holder.generation ||\n existing.holder.lock?.dev !== holder.lock?.dev ||\n existing.holder.lock?.ino !== holder.lock?.ino ||\n existing.holder.lock?.birthtimeNs !== holder.lock?.birthtimeNs\n )\n return\n removeIfPresent(path)\n })\n}\n\nfunction removeIfPresent(path: string): void {\n try {\n unlinkSync(path)\n } catch (error) {\n if (!isNoEntError(error)) throw error\n }\n}\n","import type { PursuitProjection } from './observer-projection'\n\n/**\n * Where a pursuit's observer projection is delivered while it runs, so a run started anywhere is\n * findable in one place by its pursuit id.\n *\n * Intelligence persists the projection on its run spine (`runtime-observer:pursuit:<pursuitId>`)\n * and records the id of the API key that delivered it, which joins the run to that key's spend.\n * Delivery is an observation, never a dependency: a refused, slow or unreachable endpoint is\n * reported once and the run continues exactly as it would without it.\n */\nexport interface PursuitObserverDelivery {\n /** Intelligence base URL, e.g. `https://intelligence.tangle.tools`. */\n readonly baseUrl: string\n /** Platform API key presented as the Bearer; Intelligence resolves the tenant from it. */\n readonly apiKey: string\n /** The Intelligence subject (project) the pursuit belongs to. */\n readonly subjectKey: string\n readonly subjectName?: string\n /**\n * Flat facts the caller owns about the run, recorded on the pursuit row unchanged, such as the\n * program and idea a registration names. Runtime neither reads nor validates their meaning.\n */\n readonly attributes?: Readonly<Record<string, string>>\n /** How often a live run re-delivers its projection. Default 60 s; the last delivery is liveness. */\n readonly intervalMs?: number\n /** Per-request bound. Default 10 s. */\n readonly timeoutMs?: number\n readonly fetch?: typeof fetch\n}\n\n/** The execution state Runtime reports. It never claims the pursuit's semantic success. */\nexport type PursuitObserverState = 'running' | 'done' | 'failed'\n\nexport type PursuitObserverDeliveryOutcome =\n | { readonly succeeded: true; readonly status: number }\n | { readonly succeeded: false; readonly reason: string }\n\n/** The Intelligence route that persists a delivered projection on its run spine. */\nexport const PURSUIT_OBSERVER_DELIVERY_PATH = '/v1/ingest/pursuit-observer'\n\nconst DEFAULT_INTERVAL_MS = 60_000\nconst DEFAULT_TIMEOUT_MS = 10_000\n\n/** POST one projection. Never throws; the outcome says whether Intelligence accepted it. */\nasync function deliverPursuitObserver(\n delivery: PursuitObserverDelivery,\n state: PursuitObserverState,\n projection: PursuitProjection,\n): Promise<PursuitObserverDeliveryOutcome> {\n const send = delivery.fetch ?? globalThis.fetch\n const url = `${delivery.baseUrl.replace(/\\/+$/u, '')}${PURSUIT_OBSERVER_DELIVERY_PATH}`\n try {\n const response = await send(url, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${delivery.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n subjectKey: delivery.subjectKey,\n ...(delivery.subjectName === undefined ? {} : { subjectName: delivery.subjectName }),\n state,\n ...(delivery.attributes === undefined ? {} : { attributes: delivery.attributes }),\n projection,\n }),\n signal: AbortSignal.timeout(delivery.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n })\n if (response.ok) return { succeeded: true, status: response.status }\n const detail = (await response.text().catch(() => '')).slice(0, 300)\n return { succeeded: false, reason: `HTTP ${response.status}${detail ? `: ${detail}` : ''}` }\n } catch (error) {\n return { succeeded: false, reason: error instanceof Error ? error.message : String(error) }\n }\n}\n\nexport interface PursuitObserverDeliverer {\n /** Queue a delivery of the current projection. Deliveries never overlap; a burst collapses to one. */\n push(state: PursuitObserverState): void\n /** Stop liveness delivery and deliver the final snapshot. A parked run remains nonterminal. */\n close(state: PursuitObserverState): Promise<PursuitObserverDeliveryOutcome>\n}\n\n/**\n * Deliver a live run's projection at start, on an interval, and at settlement. `read` projects\n * the run's own journal at the moment of each delivery, so every delivery is the whole record.\n */\nexport function startPursuitObserverDelivery(\n delivery: PursuitObserverDelivery,\n read: () => Promise<PursuitProjection>,\n warn: (message: string) => void = (message) => console.warn(message),\n): PursuitObserverDeliverer {\n let chain: Promise<PursuitObserverDeliveryOutcome | undefined> = Promise.resolve(undefined)\n let pending: PursuitObserverState | undefined\n let warned = false\n let closed = false\n\n const deliver = async (state: PursuitObserverState) => {\n let projection: PursuitProjection\n try {\n projection = await read()\n } catch (error) {\n return report({\n succeeded: false,\n reason: `observer projection unreadable: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n return report(await deliverPursuitObserver(delivery, state, projection))\n }\n const report = (outcome: PursuitObserverDeliveryOutcome) => {\n if (!outcome.succeeded && !warned) {\n warned = true\n warn(\n `supervisePursuit: pursuit observer delivery to ${delivery.baseUrl} failed (${outcome.reason}); the run continues and later deliveries retry`,\n )\n }\n return outcome\n }\n const push = (state: PursuitObserverState) => {\n if (closed) return\n if (pending !== undefined) return\n pending = state\n chain = chain.then(() => {\n const next = pending as PursuitObserverState\n pending = undefined\n return deliver(next)\n })\n }\n\n const timer = setInterval(() => push('running'), delivery.intervalMs ?? DEFAULT_INTERVAL_MS)\n timer.unref?.()\n push('running')\n\n return {\n push,\n async close(state) {\n closed = true\n clearInterval(timer)\n const terminal = chain.then(() => deliver(state))\n chain = terminal\n const bound = delivery.timeoutMs ?? DEFAULT_TIMEOUT_MS\n let timeout: ReturnType<typeof setTimeout> | undefined\n const expired = new Promise<PursuitObserverDeliveryOutcome>((resolve) => {\n timeout = setTimeout(\n () => resolve({ succeeded: false, reason: `terminal delivery exceeded ${bound} ms` }),\n bound * 2,\n )\n timeout.unref?.()\n })\n try {\n return await Promise.race([terminal, expired])\n } finally {\n clearTimeout(timeout)\n }\n },\n }\n}\n","import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync } from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport {\n publishExclusiveDurableFile,\n syncDurableDirectory,\n} from '../runtime/supervise/durable-file'\nimport { runCancellationFile, runCancelRequestFile } from '../runtime/supervise/run-cancellation'\nimport { workerCancellationsDir } from '../runtime/supervise/run-layout'\nimport { assertValidBudget } from '../runtime/supervise/spend-validation'\nimport { assertResumeLimits } from '../runtime/supervise/supervisor-root-contract'\nimport type { Budget, SpawnEvent, SpawnJournal, SupervisorOpts } from '../runtime/supervise/types'\nimport type { FileObserverJournal } from './observer-journal'\nimport { fenceRunWrite } from './run-fence'\nimport { SETTLE_RECORD_FILE, settleRecordDigest } from './settle-record'\nimport { FileSpawnJournal } from './spawn-journal/journal-store'\n\n/*\n * Reopening a settled run under its own run id.\n *\n * A wrong settle used to be final: `supervisePursuit` refuses a directory that holds `result.json`,\n * and `fork` and `versions` each start a new run id in a new directory. Magnetar used 21 run ids\n * from 2026-10-16 to 10-21 for one solve; 16 of those runs settled, 11 of them in under 5 hours.\n *\n * A reopen archives the settled segment and resumes the same journal. Before it writes anything it\n * checks the resume limits (`assertResumeLimits`): a reopen refused for its budget or reservation\n * policy leaves `result.json`, the cancel files and the journal as they were. The profile's identity\n * and materialization are checked by `supervise` itself, after these steps. Every step is\n * idempotent, so a later call with the same `operationId` finishes a reopen that crashed partway:\n * 1. copy `result.json` byte for byte to `settles/<n>.json`;\n * 2. append one `reopened` spawn-journal row naming the operator, the reason and the archive;\n * 3. append one observer event, so the pursuit projection shows one lineage;\n * 4. move the run's cancel request and acknowledgement aside under this reopen's and that\n * request's operation ids, so a new `cancelRun` is accepted (one run carries one run-scoped\n * cancel operation) and no later reopen overwrites an earlier segment's cancel;\n * 5. last, remove `result.json`.\n * The caller then runs `supervise` with `resume: true`: settled children replay by key, the pool\n * is restored from the journal, and the next settle writes `result.json` again.\n */\n\n/** `supervisePursuit`'s `reopen` option: reopen this settled run under its own run id. */\nexport interface RunReopen {\n /** Who reopens the run. Required and non-empty. */\n readonly operator: string\n /** Why. Required and non-empty. */\n readonly reason: string\n /** Idempotency key: calling again with it finishes a reopen that crashed partway. */\n readonly operationId: string\n /**\n * The budget the reopened run is held to, recorded on its `reopened` row, which a later resume\n * must then match. Omit and the call's `budget` must equal the recorded one: the root's, or the\n * last budget a reopen recorded. A run that settled `budget-exhausted` and reopens without a\n * larger budget pauses at once (with `driverRetry.pauseRootStops`) or settles\n * `budget-exhausted` again. A deadline is measured from the original root instant, so a run\n * whose recorded deadline has passed settles `deadline` at once unless this budget drops the\n * deadline or moves it.\n */\n readonly budget?: Budget\n}\n\n/** The directory that holds a run's archived settle records. */\nexport const SETTLE_ARCHIVE_DIR = 'settles'\n\n/** Refuse a reopen that names no operator or reason, or that is combined with a fork or versions. */\nexport function assertRunReopen(\n reopen: RunReopen,\n opts: { readonly fork?: unknown; readonly versions?: unknown },\n): void {\n if (reopen.operator.trim().length === 0) {\n throw new TypeError('supervisePursuit: reopen.operator must be non-empty')\n }\n if (reopen.reason.trim().length === 0) {\n throw new TypeError('supervisePursuit: reopen.reason must be non-empty')\n }\n if (reopen.operationId.trim().length === 0) {\n throw new TypeError('supervisePursuit: reopen.operationId must be non-empty')\n }\n if (reopen.budget !== undefined) assertValidBudget(reopen.budget, 'reopen.budget')\n if (opts.fork !== undefined || opts.versions !== undefined) {\n throw new TypeError(\n 'supervisePursuit: reopen continues this run under its own id; fork and versions start new runs',\n )\n }\n}\n\n/**\n * Archive the settled segment of the run at `runDir` and clear it for a resume. Runs under the\n * directory lock. Throws when there is nothing to reopen, or when `operationId` already reopened a\n * segment that has since settled again.\n */\nexport async function reopenSettledRun(input: {\n readonly runDir: string\n readonly runId: string\n readonly reopen: RunReopen\n readonly journal: SpawnJournal | undefined\n /** The call's budget and reservation policy, checked against the recorded ones before any write. */\n readonly limits: Pick<SupervisorOpts, 'budget' | 'reservationPolicy'>\n readonly observer: FileObserverJournal\n readonly pursuitId: string\n readonly now: () => number\n}): Promise<void> {\n const { runDir, runId, reopen, observer, pursuitId, now } = input\n const operationId = reopen.operationId.trim()\n const settlePath = resolve(runDir, SETTLE_RECORD_FILE)\n const journal = input.journal ?? new FileSpawnJournal(resolve(runDir, 'spawn-journal.jsonl'))\n const events = (await journal.loadTree(runId)) ?? []\n const reopened = events.filter(\n (event): event is Extract<SpawnEvent, { kind: 'reopened' }> =>\n event.kind === 'reopened' && event.id === runId,\n )\n const mine = reopened.find((event) => event.operationId === operationId)\n const settled = await readBytes(settlePath)\n if (settled === undefined) {\n // Removing result.json is the last step, so a recorded reopen without it is complete.\n if (mine !== undefined) return\n throw new Error(\n `supervisePursuit: ${runDir} holds no ${SETTLE_RECORD_FILE}; nothing to reopen; resume it`,\n )\n }\n assertResumeLimits(\n events,\n {\n runId,\n budget: reopen.budget ?? input.limits.budget,\n ...(input.limits.reservationPolicy === undefined\n ? {}\n : { reservationPolicy: input.limits.reservationPolicy }),\n },\n mine === undefined ? reopen.budget : undefined,\n )\n const result = JSON.parse(settled) as { readonly kind?: unknown; readonly reason?: unknown }\n const digest = settleRecordDigest(result)\n if (mine !== undefined && mine.prior.digest !== digest) {\n throw new Error(\n `supervisePursuit: reopen '${operationId}' already reopened run '${runId}', which has settled again; reopen it under a new operationId`,\n )\n }\n const archivedAs = mine?.prior.archivedAs ?? (await archiveName(runDir, settled))\n const archivePath = resolve(runDir, archivedAs)\n if (\n !publishExclusiveDurableFile(archivePath, settled) &&\n (await readBytes(archivePath)) !== settled\n ) {\n throw new Error(\n `supervisePursuit: ${archivePath} already holds a different settle record; reopen refused`,\n )\n }\n const at = new Date(now()).toISOString()\n if (mine === undefined) {\n await journal.appendEvent(runId, {\n kind: 'reopened',\n id: runId,\n operator: reopen.operator,\n reason: reopen.reason,\n operationId,\n prior: {\n kind: String(result.kind),\n ...(typeof result.reason === 'string' ? { reason: result.reason } : {}),\n digest,\n archivedAs,\n },\n ...(reopen.budget === undefined ? {} : { budget: reopen.budget }),\n seq: reopened.length,\n at,\n })\n }\n const eventId = `${runId}:pursuit:reopened:${operationId}`\n if (!(await observer.read()).some((record) => record.event?.id === eventId)) {\n await observer.appendEvent({\n id: eventId,\n pursuitId,\n runId,\n target: 'agent.run',\n phase: 'event',\n timestamp: now(),\n payload: { reopened: { operator: reopen.operator, reason: reopen.reason, archivedAs } },\n })\n }\n fenceRunWrite(() => {\n setCancellationAside(runDir, operationId)\n unlinkSync(settlePath)\n syncDurableDirectory(runDir)\n })\n}\n\n/** The next free `settles/<n>.json`, or the archive that already holds these bytes (a reopen that\n * crashed after archiving and before its journal row). */\nasync function archiveName(runDir: string, settled: string): Promise<string> {\n const dir = resolve(runDir, SETTLE_ARCHIVE_DIR)\n fenceRunWrite(() => mkdirSync(dir, { recursive: true }))\n const numbers = readdirSync(dir)\n .map((name) => /^(\\d+)\\.json$/u.exec(name)?.[1])\n .filter((n): n is string => n !== undefined)\n .map(Number)\n .sort((a, b) => a - b)\n for (const n of numbers) {\n if ((await readBytes(join(dir, `${n}.json`))) === settled)\n return `${SETTLE_ARCHIVE_DIR}/${n}.json`\n }\n return `${SETTLE_ARCHIVE_DIR}/${(numbers.at(-1) ?? 0) + 1}.json`\n}\n\n/** Move the settled run's cancel request and acknowledgement aside under the reopen's and the\n * request's operation ids, so the reopened run accepts a new `cancelRun`. Idempotent: an absent\n * file is skipped. A reopen's operation id names one segment, so a later segment cancelled under\n * the same cancel operation id lands beside this one instead of over it. */\nfunction setCancellationAside(runDir: string, reopenOperationId: string): void {\n const requestFile = runCancelRequestFile(runDir)\n const ackFile = runCancellationFile(runDir)\n if (!existsSync(requestFile) && !existsSync(ackFile)) return\n const source = existsSync(requestFile) ? requestFile : ackFile\n const { operationId } = JSON.parse(readFileSync(source, 'utf8')) as {\n readonly operationId: string\n }\n const reopenedDir = join(workerCancellationsDir(runDir), 'reopened')\n const aside = join(\n reopenedDir,\n encodeURIComponent(reopenOperationId),\n encodeURIComponent(operationId),\n )\n mkdirSync(aside, { recursive: true })\n if (existsSync(ackFile)) renameSync(ackFile, join(aside, 'run.json'))\n if (existsSync(requestFile)) renameSync(requestFile, join(aside, 'run.request.json'))\n syncDurableDirectory(aside)\n syncDurableDirectory(join(reopenedDir, encodeURIComponent(reopenOperationId)))\n syncDurableDirectory(reopenedDir)\n syncDurableDirectory(workerCancellationsDir(runDir))\n}\n\nasync function readBytes(path: string): Promise<string | undefined> {\n try {\n return await readFile(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw error\n }\n}\n","import { resolve } from 'node:path'\nimport { runtimeFailureCause } from '../runtime/failure-cause'\nimport {\n type AgentGraph,\n type GraphResult,\n type RunGraphOptions,\n superviseAgentGraph,\n} from '../runtime/supervise/graph'\nimport { graphExecutionOptions } from '../runtime/supervise/graph-backend'\nimport { readRootStreamReceipt } from '../runtime/supervise/root-stream'\nimport { supervisorRunDir } from '../runtime/supervise/run-layout'\nimport { RunParkedError } from '../runtime/supervise/run-parking'\nimport { type SuperviseOptions, supervise } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { SupervisedResult } from '../runtime/supervise/types'\nimport { errorMessage } from '../runtime/util'\nimport {\n composeRuntimeHooks,\n type RuntimeHookEvent,\n type RuntimeHooks,\n withPursuitContext,\n} from '../runtime-hooks'\nimport { createFileObserverHooks, type FileObserverJournal } from './observer-journal'\nimport { type PursuitProjection, projectPursuit } from './observer-projection'\nimport {\n type PursuitObserverDeliverer,\n type PursuitObserverDelivery,\n startPursuitObserverDelivery,\n} from './pursuit-observer-delivery'\nimport {\n type PursuitVersionChain,\n type PursuitVersions,\n runPursuitVersions,\n} from './pursuit-versions'\nimport { type PursuitFork, prepareRunFork } from './run-fork'\nimport { acquireRunDirectoryLock } from './run-lock'\nimport { assertRunReopen, type RunReopen, reopenSettledRun } from './run-reopen'\nimport {\n FAILURE_RECORD_FILE,\n readSettleRecord,\n SETTLE_RECORD_FILE,\n SettledRunDirectoryError,\n writeFailureRecord,\n writeSettleRecord,\n} from './settle-record'\n\nexport interface SupervisePursuitOptions extends SuperviseOptions {\n /** Stable objective identity spanning concrete Runtime runs. */\n readonly pursuitId: string\n /**\n * One concrete Runtime execution owns one durable directory and observer journal.\n * A pursuit spanning several runs reuses `pursuitId` across distinct `runDir`s;\n * Intelligence joins those isolated projections without a shared write head.\n */\n readonly runDir: string\n /**\n * Always `'release'`. A settle record is written once per segment and refuses re-entry, so no\n * later call resumes a settled pursuit unless an explicit `reopen` archives it; nothing else\n * would release the provider environments its retained children hold. `'keep'` is refused\n * rather than ignored.\n */\n readonly retainedAtSettlement?: 'release'\n /**\n * Run this pursuit as a version of a settled run: `profile`, `task` and `budget` must equal the\n * parent's recorded root, and Runtime executes the parent's profile with `fork.change` applied.\n * The root's `execution.correlation` records the parent, its sealed digest, the change and the\n * lineage (`RUN_FORK_CORRELATION_KEYS`). The fork's `runDir` must lie outside the parent's, and\n * the parent's outside it. The parent's directory is never written, and a refused fork, such as\n * one whose parent has an uncertain node, writes nothing.\n */\n readonly fork?: PursuitFork\n /**\n * Continue this pursuit across versions, on Eval's search kernel. The first version runs at\n * `runDir` as usual, or is read back when that directory already settled. After each version\n * settles, `versions.judge` scores it from outside its tree; unless `versions.stop` ends the\n * chain, the next version forks from the version the chain keeps with the change\n * `versions.next` returns, at `<runDir>.v<n>` with run id `<runId>.v<n>`. The search ledger at\n * `<runDir>.search/ledger.jsonl` records every version as a node, every change as an edge, and\n * every run and verdict as a cell; it is the chain's only record and checkpoint. A call on a\n * closed chain reads it back; a call on an open chain continues it without re-running or\n * re-judging a settled version. Aborting `signal` pauses the chain: the call rejects and a later\n * call continues it. The call returns the kept version's result with the chain.\n */\n readonly versions?: PursuitVersions\n /**\n * Deliver this run's observer projection to Intelligence at start, every `intervalMs` while it\n * runs, and at settlement or failure, so the run is findable by its pursuit id from wherever it\n * was started. Optional and fail-open: a delivery that fails is reported once and never changes\n * the run. Each version of a `versions` chain delivers its own run under the same pursuit.\n */\n readonly observerDelivery?: PursuitObserverDelivery\n /**\n * Reopen this settled run under its own run id instead of refusing it (`./run-reopen.ts`).\n * Under the directory lock, `result.json` is archived byte for byte to `settles/<n>.json`, one\n * `reopened` journal row names the operator and reason, the run's settled cancel operation is\n * moved aside, and the run resumes from its journal (`resume: true`): settled children replay by\n * key and spend from before the reopen is debited once. `reopen.budget`, when set, replaces the\n * call's `budget` and is recorded for later resumes. Refused with `fork` or `versions`, and on a\n * directory with no `result.json` (\"nothing to reopen; resume it\"); a reopen whose budget or\n * reservation policy the recorded run refuses (\"resume budget mismatch\") writes nothing.\n */\n readonly reopen?: RunReopen\n}\n\nexport interface SupervisedPursuitResult<Result> {\n readonly result: Result\n readonly pursuit: PursuitProjection\n readonly observerPath: string\n /** `result.json` in the run directory: `result` as canonical JSON, written once at settle. */\n readonly settlePath: string\n /** The version chain, when the call set `versions`. */\n readonly versions?: PursuitVersionChain\n}\n\n/** A failed Runtime execution whose complete third-person projection was retained. */\nexport class SupervisePursuitError extends Error {\n readonly pursuit: PursuitProjection\n readonly observerPath: string\n /** `failure.json` in the run directory: the record of this throw. */\n readonly failurePath: string\n\n constructor(\n cause: unknown,\n pursuit: PursuitProjection,\n observerPath: string,\n failurePath: string,\n ) {\n super(`supervisePursuit: ${errorMessage(cause)}`, { cause })\n this.name = 'SupervisePursuitError'\n this.pursuit = pursuit\n this.observerPath = observerPath\n this.failurePath = failurePath\n }\n}\n\n/**\n * One-call durable pursuit execution over the canonical `supervise()` kernel.\n *\n * This is an adapter, not a second executor: it composes a durable third-person\n * observer into Runtime's existing recursive hook stream and then rebuilds the\n * operator projection after the same `supervise()` call settles. Agents never\n * receive the observer path or projection and their behavior does not depend on it.\n *\n * Every concrete execution writes only inside its own `runDir`. Cross-run pursuit\n * aggregation is therefore lock-free at the observer layer: reuse `pursuitId` across\n * run directories and let Intelligence join the independently verified projections.\n *\n * The directory's terminal state is recorded beside `observer.jsonl`: `result.json` holds the\n * returned result once the run settles and `failure.json` the most recent throw. A directory\n * whose `result.json` exists refuses re-entry before any compute; a failure record alone does\n * not, because a caller can correct its input and drive the same run again. For the life of the\n * call the directory is held by `supervise.lock`, so a second process on the same directory\n * refuses and names the holder instead of sharing one journal.\n * An abandoned `supervise.lock.guard` requires removal after confirming no lock mutation is active.\n */\nexport async function supervisePursuit(\n profile: SupervisorProfile,\n task: unknown,\n opts: SupervisePursuitOptions,\n): Promise<SupervisedPursuitResult<Awaited<ReturnType<typeof supervise>>>> {\n assertPursuitDirectory(opts, 'supervisePursuit')\n if (opts.reopen !== undefined) assertRunReopen(opts.reopen, opts)\n\n if (opts.versions !== undefined) {\n return runPursuitVersions(\n profile,\n task,\n opts as SupervisePursuitOptions & { readonly versions: PursuitVersions },\n supervisePursuit,\n ) as Promise<SupervisedPursuitResult<Awaited<ReturnType<typeof supervise>>>>\n }\n\n const {\n pursuitId: _pursuitId,\n hooks: _hooks,\n fork,\n versions: _versions,\n observerDelivery: _observerDelivery,\n reopen,\n ...superviseOptions\n } = opts\n\n // A fork is verified on every entry, a resume included, so the recorded root identity it\n // derives is the one the Supervisor's resume contract compares against. It reads only the\n // settled parent, and runs before the lock so a refused fork writes nothing, not even runDir.\n const forked =\n fork === undefined ? undefined : await prepareRunFork(profile, task, superviseOptions, fork)\n\n return runDurablePursuit(\n opts,\n ({ hooks, steerDir }) =>\n supervise(forked?.profile ?? profile, task, {\n ...superviseOptions,\n ...(forked === undefined ? {} : { execution: forked.execution }),\n ...(reopen === undefined\n ? {}\n : { resume: true, ...(reopen.budget === undefined ? {} : { budget: reopen.budget }) }),\n steerDir,\n // The settle record written at settlement makes this settlement final, so the\n // environments a retained child holds are released at the barrier instead of kept for a\n // resume that the record will refuse (18 of a 60-slot fleet held 19\n // to 37 hours).\n retainedAtSettlement: 'release',\n hooks,\n }),\n (result) => result,\n reopen === undefined\n ? undefined\n : (observer) =>\n reopenSettledRun({\n runDir: opts.runDir.trim(),\n runId: opts.runId ?? 'supervise',\n reopen,\n journal: opts.journal,\n limits: {\n budget: opts.budget,\n ...(opts.reservationPolicy === undefined\n ? {}\n : { reservationPolicy: opts.reservationPolicy }),\n },\n observer,\n pursuitId: opts.pursuitId.trim(),\n now: opts.now ?? Date.now,\n }),\n )\n}\n\n/** Options for {@link superviseGraphPursuit}: every `runGraph` option, plus the pursuit identity,\n * the run directory this execution owns, and optional observer delivery. */\nexport interface SuperviseGraphPursuitOptions extends RunGraphOptions {\n /** Stable objective identity spanning concrete Runtime runs. */\n readonly pursuitId: string\n /** The directory this execution owns: journal, blobs, observer journal, lock and terminal\n * records. Re-running the same `runDir` and `runId` resumes an unsettled graph; a settled\n * graph requires an explicit `reopen`. */\n readonly runDir: string\n /** Always `'release'`: a reopened segment reuses its journal, not retired environments. */\n readonly retainedAtSettlement?: 'release'\n /** As for {@link supervisePursuit}. */\n readonly observerDelivery?: PursuitObserverDelivery\n /** Explicitly reopen a settled segment under this graph's existing run id and journal. */\n readonly reopen?: RunReopen\n}\n\n/**\n * One-call durable execution of an `AgentGraph`: the graph twin of {@link supervisePursuit}.\n *\n * It owns the run directory exactly as `supervisePursuit` does — `supervise.lock` for the life of\n * the call, `observer.jsonl`, `result.json` once the graph settles, `failure.json` for the most\n * recent throw, and refusal of a settled directory before any compute — and runs the graph through\n * `runGraph`'s own path, so the root node is a `supervise()` root and a restarted process resumes\n * the graph from its spawn journal. `result.json` holds the graph's supervised result, the same\n * record every supervised run leaves; the edge ledger is the journal's `edge` events and the\n * returned `result.ledger`. Version chains and forks are `supervisePursuit` features and are not\n * offered here. An explicit `reopen` uses the same archived-settle and resume contract as\n * `supervisePursuit`; ordinary re-entry of a settled graph stays refused.\n */\nexport async function superviseGraphPursuit(\n graph: AgentGraph,\n opts: SuperviseGraphPursuitOptions,\n): Promise<SupervisedPursuitResult<GraphResult>> {\n assertPursuitDirectory(opts, 'superviseGraphPursuit')\n if (opts.reopen !== undefined) assertRunReopen(opts.reopen, {})\n const {\n pursuitId: _pursuitId,\n hooks: _hooks,\n observerDelivery: _observerDelivery,\n brain,\n reopen,\n ...graphOptions\n } = opts\n return runDurablePursuit(\n opts,\n ({ hooks, steerDir }) =>\n superviseAgentGraph(\n reopen?.budget === undefined ? graph : { ...graph, budget: reopen.budget },\n graphExecutionOptions({\n ...graphOptions,\n // The lock, the settle record and the journal name one run, so the graph takes the\n // directory's run id rather than its own digest-derived default.\n runId: graphOptions.runId ?? 'supervise',\n ...(reopen === undefined ? {} : { resume: true }),\n steerDir,\n retainedAtSettlement: 'release',\n hooks,\n }),\n brain,\n ),\n (result) => result.result,\n reopen === undefined\n ? undefined\n : (observer) =>\n reopenSettledRun({\n runDir: opts.runDir.trim(),\n runId: opts.runId ?? 'supervise',\n reopen,\n journal: opts.journal,\n limits: {\n budget: graph.budget,\n ...(opts.reservationPolicy === undefined\n ? {}\n : { reservationPolicy: opts.reservationPolicy }),\n },\n observer,\n pursuitId: opts.pursuitId.trim(),\n now: opts.now ?? Date.now,\n }),\n )\n}\n\n/** The pursuit identity and run directory both durable entries require. */\nfunction assertPursuitDirectory(\n opts: {\n readonly pursuitId: string\n readonly runDir: string\n readonly retainedAtSettlement?: string\n },\n entry: string,\n): void {\n for (const field of ['pursuitId', 'runDir'] as const) {\n if (opts[field].trim().length === 0) throw new TypeError(`${entry}: ${field} must be non-empty`)\n }\n if (opts.retainedAtSettlement === 'keep') {\n throw new TypeError(\n `${entry}: retainedAtSettlement 'keep' cannot hold, because a settled pursuit is never re-entered`,\n )\n }\n}\n\n/**\n * The run directory's lifecycle around one execution: lock, settled-directory refusal, observer\n * journal, failure record and settle record. `execute` receives the observer-composed hooks and\n * the steer directory the run's control plane uses; `settled` names the value `result.json` holds.\n */\nasync function runDurablePursuit<Result>(\n opts: Pick<\n SupervisePursuitOptions,\n 'pursuitId' | 'runDir' | 'runId' | 'now' | 'hooks' | 'steerDir' | 'observerDelivery'\n >,\n execute: (seams: { readonly hooks: RuntimeHooks; readonly steerDir: string }) => Promise<Result>,\n settled: (result: Result) => SupervisedResult<unknown>,\n reopen?: (observer: FileObserverJournal) => Promise<void>,\n): Promise<SupervisedPursuitResult<Result>> {\n const pursuitId = opts.pursuitId.trim()\n const runDir = opts.runDir.trim()\n const observerPath = resolve(runDir, 'observer.jsonl')\n const settlePath = resolve(runDir, SETTLE_RECORD_FILE)\n const failurePath = resolve(runDir, FAILURE_RECORD_FILE)\n const runId = opts.runId ?? 'supervise'\n const now = opts.now ?? Date.now\n\n // The lock is taken before the settle record is read so a run that settles between the read\n // and the lock cannot be re-entered; both refusals happen before the observer journal is touched.\n const lock = await acquireRunDirectoryLock(runDir, runId, now)\n return lock.run(async () => {\n let delivery: PursuitObserverDeliverer | undefined\n let terminalState: 'done' | 'failed' | 'running' = 'failed'\n try {\n const observer = createFileObserverHooks(observerPath, pursuitId)\n if (reopen !== undefined) await reopen(observer.journal)\n else {\n const prior = await readSettleRecord(runDir)\n if (prior !== undefined) {\n throw new SettledRunDirectoryError(settlePath, prior.tree.root, runId)\n }\n }\n\n // Root lifecycle is an observer-plane fact, not something the manager has to\n // narrate about itself. This also makes a zero-spawn/single-agent run observable.\n await observer.journal.appendEvent(rootEvent(pursuitId, runId, 'before', now()))\n delivery =\n opts.observerDelivery === undefined\n ? undefined\n : startPursuitObserverDelivery(opts.observerDelivery, async () =>\n projectPursuit(await observer.journal.read()),\n )\n\n let result: Result\n try {\n result = await execute({\n // The observer runs first so a caller hook that throws cannot prevent the\n // canonical lifecycle fact from entering the durable journal.\n hooks: withPursuitContext(pursuitId, composeRuntimeHooks(observer.hooks, opts.hooks)),\n // `runDir` owns the pursuit journal and terminal records. The public steer writer\n // addresses the canonical per-run event directory beneath that root, so keep its control\n // plane there without moving the durable pursuit records.\n steerDir: opts.steerDir ?? supervisorRunDir(runDir, runId),\n })\n } catch (error) {\n if (error instanceof RunParkedError && error.runId === runId) {\n terminalState = 'running'\n throw error\n }\n let pursuit: PursuitProjection\n try {\n // The journal fact is raw evidence and lands first; the failure record summarizes it.\n await observer.journal.appendEvent(\n rootEvent(pursuitId, runId, 'error', now(), {\n status: 'failed',\n error: errorMessage(error),\n failure: runtimeFailureCause(error),\n }),\n )\n pursuit = projectPursuit(await observer.journal.read())\n } catch (observerError) {\n throw new Error(\n 'supervisePursuit: Runtime failed and durable observer completeness could not be proven',\n { cause: new AggregateError([error, observerError]) },\n )\n }\n // A failure record that cannot be written must not hide the journal fact above; it is\n // reported as its own cause beside the run's error.\n try {\n // The root's stream is already on disk whether or not the run settled; the record names\n // it so a root that died mid-turn keeps what it had streamed.\n const rootStream = await readRootStreamReceipt(runDir)\n await writeFailureRecord(runDir, {\n runId,\n pursuitId,\n at: new Date(now()).toISOString(),\n error: { name: errorName(error), message: errorMessage(error) },\n ...(rootStream === undefined ? {} : { rootStream }),\n })\n } catch (recordError) {\n throw new Error(\n `supervisePursuit: Runtime failed and the failure record ${failurePath} could not be written`,\n { cause: new AggregateError([error, recordError]) },\n )\n }\n throw new SupervisePursuitError(error, pursuit, observerPath, failurePath)\n }\n\n // The settle record is the re-entry guard, so it is durable before the journal says `done`.\n // A record that cannot be written leaves the attempt open in the journal and the run\n // re-enterable, which replays the settled children and settles again.\n const terminal = settled(result)\n try {\n await writeSettleRecord(runDir, terminal)\n } catch (cause) {\n throw new Error(\n `supervisePursuit: Runtime settled but the settle record ${settlePath} could not be written`,\n { cause },\n )\n }\n await observer.journal.appendEvent(\n rootEvent(pursuitId, runId, 'after', now(), {\n status: 'done',\n ...(terminal.kind === 'no-winner' &&\n terminal.reason === 'driver-failed' &&\n terminal.error.failure\n ? { error: terminal.error.message, failure: terminal.error.failure }\n : {}),\n }),\n )\n terminalState = 'done'\n return Object.freeze({\n result,\n pursuit: projectPursuit(await observer.journal.read()),\n observerPath,\n settlePath,\n })\n } finally {\n // The terminal delivery reads the journal after its last fact, and is bounded so an\n // unreachable Intelligence delays the return by at most twice its timeout.\n await delivery?.close(terminalState)\n await lock.release()\n }\n })\n}\n\nfunction rootEvent(\n pursuitId: string,\n runId: string,\n phase: 'before' | 'after' | 'error',\n timestamp: number,\n payload?: Record<string, unknown>,\n): RuntimeHookEvent {\n return Object.freeze({\n id: `${runId}:pursuit:${phase}:${timestamp}`,\n pursuitId,\n runId,\n target: 'agent.run',\n phase,\n timestamp,\n ...(payload ? { payload: Object.freeze({ ...payload }) } : {}),\n })\n}\n\nfunction errorName(error: unknown): string {\n return error instanceof Error ? error.name : 'NonError'\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,qBAAqB;;AAElC,MAAa,sBAAsB;;AAenC,IAAa,2BAAb,cAA8C,MAAM;CAClD;;CAEA;CAEA,YAAY,MAAc,eAAuB,gBAAwB;EACvE,MACE,kBAAkB,iBACd,qBAAqB,KAAK,qBAAqB,cAAc,uHAC7D,qBAAqB,KAAK,qBAAqB,cAAc,oFAAoF,eAAe,uBACtK;EACA,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,gBAAgB;CACvB;AACF;;AAGA,IAAM,+BAAN,cAA2C,UAAU;CACnD;CAEA,YAAY,MAAc,MAAc;EACtC,MACE,2BAA2B,KAAK,QAAQ,KAAK,6EAC/C;EACA,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;AAEA,MAAM,mCAAmB,IAAI,IAAa;CAAC,OAAO;CAAW,MAAM;CAAW;AAAI,CAAC;;;;;;;AAQnF,SAAS,UAAU,QAA0B;CAC3C,MAAM,OAAkB,CAAC;CACzB,MAAM,SAAS,OAAgB,SAAuB;EACpD,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;EACjD,IAAI,iBAAiB,KAAK,MAAM,IAAI,6BAA6B,MAAM,KAAK;EAC5E,IAAI,iBAAiB,KAAK,MAAM,IAAI,6BAA6B,MAAM,KAAK;EAC5E,IAAI,iBAAiB,MAAM,MAAM,IAAI,6BAA6B,MAAM,MAAM;EAC9E,IAAI,YAAY,OAAO,KAAK,KAAK,iBAAiB,aAChD,MAAM,IAAI,6BAA6B,MAAM,eAAe;EAE9D,IAAI,CAAC,iBAAiB,IAAI,OAAO,eAAe,KAAK,CAAC,GACpD,MAAM,IAAI,6BAA6B,MAAM,gBAAgB;EAE/D,IAAI,KAAK,SAAS,KAAK,GAAG,M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