@tangle-network/agent-runtime 0.281.0 → 0.281.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/agent.d.ts +1 -1
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +71 -45
- package/dist/durable.js.map +1 -1
- package/dist/{index-BSSGMvUd.d.ts → index-C4ygxavE.d.ts} +7 -6
- package/dist/index.d.ts +2 -2
- package/dist/kernel.d.ts +1 -1
- package/dist/{loop-runner-bin-DgeZHpWJ.d.ts → loop-runner-bin-B9dTzFL3.d.ts} +2 -2
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/mcp/index.d.ts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +8 -8
- package/dist/tui/index.d.ts +1 -1
- package/package.json +1 -1
package/dist/durable.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"durable.js","names":["errorMessage","delay"],"sources":["../src/durable/chat-engine.ts","../src/durable/execution-handle.ts","../src/durable/observer-journal.ts","../src/durable/observer-projection.ts","../src/durable/settle-record.ts","../src/durable/pursuit-versions.ts","../src/durable/run-fork.ts","../src/durable/run-lock.ts","../src/durable/supervise-pursuit.ts","../src/durable/supervision-discovery.ts"],"sourcesContent":["/**\n * `handleChatTurn` is a framework-neutral chat-turn HTTP orchestrator.\n * Owns the NDJSON `ChatStreamEvent` line protocol, the `session.run.*`\n * lifecycle vocabulary, and the persist / post-process / trace-flush\n * hook order. Returns a `ReadableStream` body the product hands to its\n * platform `Response`.\n *\n * Sandbox owns long-running execution, reconnect, and replay.\n * The producer this engine wraps already speaks that protocol; this\n * engine frames the events and orders product callbacks.\n *\n * Hooks (`ChatTurnHooks`):\n * - `produce`: build the backend event stream\n * - `persistAssistantMessage`: write the assistant turn to the product DB\n * - `onTurnComplete?`: post-process proposals, citations, and similar work\n * - `onEvent?`: send each event to another consumer\n * - `transformFinalText?`: transform text before persistence\n * - `traceFlush?`: let `waitUntil` keep the worker alive for export\n *\n * Framework neutrality: takes already-resolved values (`identity` tuple,\n * a `waitUntil`), never a `Request` or a `Context`. The product's thin\n * route adapter does auth + parse + access-control, then calls\n * `handleChatTurn(...)` and returns `result.body` as its platform `Response`.\n */\n\n/** The NDJSON line protocol every product chat client already speaks. */\nexport interface ChatStreamEvent {\n type: string\n data?: Record<string, unknown>\n}\n\n/** Identity of a chat turn. `tenantId` is the workspace id for workspace-\n * scoped products and the user id for session-scoped products. */\nexport interface ChatTurnIdentity {\n tenantId: string\n /** Thread / session id. */\n sessionId: string\n userId: string\n /** Monotonic 0-based turn index within the session. */\n turnIndex: number\n}\n\n/** The live side of a turn returned by the product's `produce` hook. */\nexport interface ChatTurnProducer<TEvent extends ChatStreamEvent = ChatStreamEvent> {\n /** The turn's events. The engine emits completion after persistence. */\n stream: AsyncGenerator<TEvent, void, unknown>\n /** The turn's final assistant text. Read once, after `stream` drains. */\n finalText(): string\n}\n\n/** Product callbacks invoked while one chat turn runs. */\nexport interface ChatTurnHooks {\n /** Build the backend stream. The engine forwards nonterminal events and\n * reads `finalText()` once the stream drains. Reported errors fail the turn. */\n produce(): ChatTurnProducer\n /** Persist the assistant message to the product's own store. Called\n * once, after drain, with the assembled (transform-applied) text. */\n persistAssistantMessage(input: { identity: ChatTurnIdentity; finalText: string }): Promise<void>\n /** Optional post-processing for proposals, citations, or credit metering.\n * Errors are logged without failing a turn that already streamed. */\n onTurnComplete?(input: { identity: ChatTurnIdentity; finalText: string }): Promise<void>\n /** Optional per-event side channel, such as a Durable Object broadcast.\n * Runs for every emitted event, including the lifecycle envelope.\n * Errors are logged without breaking the chat stream. */\n onEvent?(event: ChatStreamEvent): void | Promise<void>\n /** Optional pre-persist transform of the final text (e.g. PII\n * redaction). Affects only what is persisted; the live stream is\n * never altered. */\n transformFinalText?(text: string): string | Promise<string>\n /** Optional trace flush. Handed to `waitUntil` so the worker stays alive\n * until export completes. */\n traceFlush?(): Promise<void>\n}\n\n/** Inputs for one streamed product chat turn. */\nexport interface RunChatTurnInput {\n identity: ChatTurnIdentity\n hooks: ChatTurnHooks\n /** Worker liveness hook. When omitted, trace flush is awaited inline\n * before the stream closes. */\n waitUntil?: (p: Promise<unknown>) => void\n /** Structured logger for swallowed hook errors. Defaults to\n * `console.error` so failures surface without product wiring. */\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** HTTP response values returned for one chat turn. */\nexport interface ChatTurnResult {\n /** NDJSON body to return as the platform `Response` body. */\n body: ReadableStream<Uint8Array>\n /** Content type for the response. */\n contentType: 'application/x-ndjson'\n}\n\nconst encoder = new TextEncoder()\n\nfunction encodeLine(event: ChatStreamEvent): Uint8Array {\n return encoder.encode(`${JSON.stringify(event)}\\n`)\n}\n\nfunction defaultLog(message: string, meta?: Record<string, unknown>): void {\n if (meta) console.error(message, meta)\n else console.error(message)\n}\n\n/**\n * Preserve the useful part of a thrown HTTP Response at the stream boundary.\n *\n * Product routes commonly throw a typed Response for an upstream failure. A\n * Response is not an Error, so String(response) produces the unusable\n * \"[object Response]\" and hides the status that decides the next action.\n * Read a clone so the caller's response body remains available to its owner.\n */\nasync function thrownErrorMessage(error: unknown): Promise<string> {\n if (!(error instanceof Response)) {\n return error instanceof Error ? error.message : String(error)\n }\n\n const prefix = `HTTP ${error.status}`\n try {\n const text = await error.clone().text()\n if (!text.trim()) return prefix\n try {\n const body = JSON.parse(text) as {\n error?: { code?: unknown; message?: unknown } | string\n message?: unknown\n }\n const nested =\n typeof body.error === 'object' && body.error !== null ? body.error.message : body.error\n const message =\n typeof nested === 'string'\n ? nested\n : typeof body.message === 'string'\n ? body.message\n : undefined\n if (message) return `${prefix}: ${message.slice(0, 500)}`\n } catch {\n // Fall through to the status. Arbitrary upstream HTML or text is not a\n // stable product error contract and should not be copied into a chat.\n }\n } catch {\n // A consumed or unavailable body still has a useful HTTP status.\n }\n return prefix\n}\n\n/**\n * Run one chat turn. Returns immediately with a `ReadableStream` body;\n * execution starts while the stream is constructed. Backend\n * failures surface as `error` + `session.run.failed` events.\n */\nexport function handleChatTurn(input: RunChatTurnInput): ChatTurnResult {\n const log = input.log ?? defaultLog\n const { identity, hooks } = input\n\n const body = new ReadableStream<Uint8Array>({\n start: async (controller) => {\n const emit = async (event: ChatStreamEvent): Promise<void> => {\n controller.enqueue(encodeLine(event))\n if (hooks.onEvent) {\n try {\n await hooks.onEvent(event)\n } catch (err) {\n log('[chat-engine] onEvent hook threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n }\n\n try {\n await emit({\n type: 'session.run.started',\n data: {\n sessionId: identity.sessionId,\n tenantId: identity.tenantId,\n turnIndex: identity.turnIndex,\n },\n })\n\n const producer = hooks.produce()\n let failureData: Record<string, unknown> | undefined\n for await (const event of producer.stream) {\n if (event.type === 'session.run.failed') {\n if (!failureData) await emit({ type: 'error', data: event.data })\n failureData = { ...failureData, ...event.data }\n continue\n }\n if (event.type === 'error') failureData = { ...failureData, ...event.data }\n // A drained error stream is still a failed turn. Completion belongs\n // to this engine, after persistence, even when an upstream emits it.\n if (event.type === 'session.run.completed') continue\n await emit(event)\n }\n const rawFinal = producer.finalText()\n const finalText = hooks.transformFinalText\n ? await hooks.transformFinalText(rawFinal)\n : rawFinal\n\n await hooks.persistAssistantMessage({ identity, finalText })\n if (hooks.onTurnComplete) {\n try {\n await hooks.onTurnComplete({ identity, finalText })\n } catch (err) {\n log('[chat-engine] onTurnComplete threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n await emit({\n type: failureData ? 'session.run.failed' : 'session.run.completed',\n data: { ...failureData, sessionId: identity.sessionId },\n })\n } catch (err) {\n const message = await thrownErrorMessage(err)\n log('[chat-engine] turn failed', { error: message })\n await emit({ type: 'error', data: { message } })\n await emit({\n type: 'session.run.failed',\n data: { sessionId: identity.sessionId, message },\n })\n } finally {\n if (hooks.traceFlush) {\n const flush = hooks.traceFlush().catch((err) =>\n log('[chat-engine] traceFlush threw', {\n error: err instanceof Error ? err.message : String(err),\n }),\n )\n if (input.waitUntil) input.waitUntil(flush)\n else await flush\n }\n controller.close()\n }\n },\n })\n\n return { body, contentType: 'application/x-ndjson' }\n}\n","/**\n * Derive a stable execution id from the run identity.\n * The same `(projectId, sessionId, turnIndex)` tuple yields the same id.\n *\n * Use the result as both `PromptOptions.executionId` and\n * `PromptOptions.turnId` on the first dispatch.\n * The execution id addresses the server-side execution for reconnect and\n * replay; the turn id makes a repeated dispatch idempotent.\n * An execution id alone does not make a repeated POST idempotent.\n *\n * Format is readable, not hashed: operators grepping orchestrator logs\n * for `gtm-agent:thread-abc:3` find the run without translating an\n * opaque id. Components are URL-encoded so delimiters inside caller ids\n * cannot collapse distinct tuples. The final id is limited to the\n * orchestrator replay route's 256-byte maximum. Execution ids are not a\n * secrecy boundary.\n *\n * Wire integration:\n * - Initial dispatch: pass the result as `executionId` and `turnId`.\n * - Stream replay: pass it as `executionId` with `lastEventId`.\n *\n * @throws `TypeError` when either string id is blank.\n * @throws `RangeError` when `turnIndex` is invalid or the result exceeds 256 bytes.\n */\nexport function deriveExecutionId(input: {\n projectId: string\n sessionId: string\n turnIndex: number\n}): string {\n if (input.projectId.trim().length === 0) {\n throw new TypeError('projectId must be a non-empty string')\n }\n if (input.sessionId.trim().length === 0) {\n throw new TypeError('sessionId must be a non-empty string')\n }\n if (!Number.isSafeInteger(input.turnIndex) || input.turnIndex < 0) {\n throw new RangeError('turnIndex must be a non-negative safe integer')\n }\n\n const executionId = [\n encodeURIComponent(input.projectId),\n encodeURIComponent(input.sessionId),\n String(input.turnIndex),\n ].join(':')\n if (executionId.length > 256) {\n throw new RangeError('derived execution id must not exceed 256 bytes')\n }\n return executionId\n}\n","import { createHash } from 'node:crypto'\nimport { resolve } from 'node:path'\nimport { detachedSnapshot } from '../runtime/supervise/snapshot'\nimport {\n type RuntimeDecisionPoint,\n type RuntimeHookEvent,\n type RuntimeHooks,\n withPursuitContext,\n} from '../runtime-hooks'\nimport { prepareJsonlAppend, readCommittedJsonLines, writeAllBytes } from './jsonl-file'\n\nexport type ObserverRecordKind = 'event' | 'decision'\n\n/**\n * One immutable record in the observer plane. `sequence` is journal order, not\n * execution order; causal/runtime order remains available on the underlying event.\n * `previousDigest` + `digest` make deletion, reordering, or mutation detectable.\n */\nexport interface ObserverRecord {\n readonly schemaVersion: 1\n readonly pursuitId: string\n readonly sequence: number\n readonly kind: ObserverRecordKind\n readonly observedAt: number\n readonly previousDigest?: string\n readonly event?: RuntimeHookEvent\n readonly decision?: RuntimeDecisionPoint\n readonly digest: string\n}\n\nexport interface ObserverJournal {\n appendEvent(event: RuntimeHookEvent): Promise<ObserverRecord>\n appendDecision(point: RuntimeDecisionPoint): Promise<ObserverRecord>\n read(): Promise<readonly ObserverRecord[]>\n hooks(): RuntimeHooks\n}\n\ntype UnsignedObserverRecord = Omit<ObserverRecord, 'digest'>\n\n/**\n * Durable, append-only third-person history for one concrete Runtime execution.\n * It consumes Runtime's existing hook stream and does not participate in execution\n * decisions. A broken observer therefore cannot change what an agent is allowed to do.\n *\n * The write discipline deliberately matches `FileSpawnJournal`: serialized appends,\n * torn-tail recovery, short-write handling, and fsync before acknowledgement. One\n * execution owns one journal file; higher-level pursuit aggregation joins isolated\n * journals by `pursuitId` instead of making independent processes share a write head.\n */\nexport class FileObserverJournal implements ObserverJournal {\n readonly path: string\n readonly pursuitId: string\n private tail: Promise<void> = Promise.resolve()\n private initialized = false\n private sequence = 0\n private previousDigest: string | undefined\n private appendFailure: Error | undefined\n\n constructor(path: string, pursuitId: string) {\n const stableId = pursuitId.trim()\n if (stableId.length === 0) {\n throw new TypeError('FileObserverJournal: pursuitId must be non-empty')\n }\n this.path = resolve(path)\n this.pursuitId = stableId\n }\n\n hooks(): RuntimeHooks {\n return withPursuitContext(this.pursuitId, {\n onEvent: (event) => this.appendEvent(event).then(() => undefined),\n onDecisionPoint: (point) => this.appendDecision(point).then(() => undefined),\n })\n }\n\n appendEvent(event: RuntimeHookEvent): Promise<ObserverRecord> {\n return this.enqueue('event', event)\n }\n\n appendDecision(point: RuntimeDecisionPoint): Promise<ObserverRecord> {\n return this.enqueue('decision', point)\n }\n\n async read(): Promise<readonly ObserverRecord[]> {\n await this.tail\n this.assertComplete()\n const records: ObserverRecord[] = []\n const verify = observerVerifier(this.pursuitId)\n for await (const record of this.readExistingUnsafe()) {\n verify(record)\n records.push(record)\n }\n return Object.freeze(records)\n }\n\n private enqueue(\n kind: ObserverRecordKind,\n value: RuntimeHookEvent | RuntimeDecisionPoint,\n ): Promise<ObserverRecord> {\n if (value.pursuitId !== this.pursuitId) {\n return Promise.reject(\n new Error(\n `FileObserverJournal: ${kind} pursuitId ${String(value.pursuitId)} does not match ${this.pursuitId}`,\n ),\n )\n }\n\n // Other hooks receive this same input and may mutate it before queued I/O runs.\n // Detach now, not after awaiting the previous append or computing the digest.\n let snapshot: typeof value\n try {\n snapshot = detachedSnapshot(value, 'observer record')\n } catch (error) {\n return Promise.reject(error)\n }\n\n let result: ObserverRecord | undefined\n const operation = this.tail.then(async () => {\n this.assertComplete()\n try {\n await this.initialize()\n } catch (error) {\n this.appendFailure ??= toError(error)\n throw error\n }\n\n const unsigned: UnsignedObserverRecord = {\n schemaVersion: 1,\n pursuitId: this.pursuitId,\n sequence: this.sequence + 1,\n kind,\n observedAt: Date.now(),\n ...(this.previousDigest ? { previousDigest: this.previousDigest } : {}),\n ...(kind === 'event'\n ? { event: snapshot as RuntimeHookEvent }\n : { decision: snapshot as RuntimeDecisionPoint }),\n }\n const record: ObserverRecord = Object.freeze({\n ...unsigned,\n digest: observerRecordDigest(unsigned),\n })\n try {\n await this.writeRecord(record)\n } catch (error) {\n this.appendFailure ??= toError(error)\n throw error\n }\n this.sequence = record.sequence\n this.previousDigest = record.digest\n result = record\n })\n this.tail = operation.then(\n () => undefined,\n () => undefined,\n )\n return operation.then(() => {\n if (!result) throw new Error('FileObserverJournal: append completed without a record')\n return result\n })\n }\n\n private async initialize(): Promise<void> {\n if (this.initialized) return\n const verify = observerVerifier(this.pursuitId)\n let tail: ObserverRecord | undefined\n for await (const record of this.readExistingUnsafe()) {\n verify(record)\n tail = record\n }\n this.sequence = tail?.sequence ?? 0\n this.previousDigest = tail?.digest\n // Only latch after recovery + verification succeed. A transient read error or\n // corruption must never leave an instance pretending it initialized cleanly.\n this.initialized = true\n }\n\n private readExistingUnsafe(): AsyncGenerator<ObserverRecord> {\n return readCommittedJsonLines<ObserverRecord>(this.path, { allowMissing: true })\n }\n\n private async writeRecord(record: ObserverRecord): Promise<void> {\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n await fs.mkdir(path.dirname(this.path), { recursive: true })\n const needsSeparator = await prepareJsonlAppend(this.path)\n const handle = await fs.open(this.path, 'a')\n try {\n await writeAllBytes(handle, `${needsSeparator ? '\\n' : ''}${JSON.stringify(record)}\\n`)\n await handle.sync()\n } finally {\n await handle.close()\n }\n }\n\n private assertComplete(): void {\n if (!this.appendFailure) return\n throw new Error(\n 'FileObserverJournal: a prior durable append failed; observer completeness is unknown',\n { cause: this.appendFailure },\n )\n }\n}\n\n/** Verify identity, monotonic sequence, payload shape, and the complete digest chain. */\nexport function verifyObserverRecords(\n records: readonly ObserverRecord[],\n pursuitId?: string,\n): readonly ObserverRecord[] {\n const verify = observerVerifier(pursuitId)\n for (const record of records) verify(record)\n return Object.freeze([...records])\n}\n\n/** The same full chain validation is used for replay, startup and in-memory evidence. */\nfunction observerVerifier(pursuitId?: string): (record: ObserverRecord) => void {\n let previousDigest: string | undefined\n let expectedSequence = 1\n return (record) => {\n if (record.schemaVersion !== 1) throw new Error('observer journal: unsupported schemaVersion')\n if (pursuitId !== undefined && record.pursuitId !== pursuitId) {\n throw new Error(`observer journal: pursuit identity mismatch at sequence ${record.sequence}`)\n }\n if (record.sequence !== expectedSequence) {\n throw new Error(\n `observer journal: non-contiguous sequence ${record.sequence}; expected ${expectedSequence}`,\n )\n }\n if (record.previousDigest !== previousDigest) {\n throw new Error(`observer journal: digest-chain break at sequence ${record.sequence}`)\n }\n if ((record.kind === 'event') === (record.event === undefined)) {\n throw new Error(`observer journal: invalid event payload at sequence ${record.sequence}`)\n }\n if ((record.kind === 'decision') === (record.decision === undefined)) {\n throw new Error(`observer journal: invalid decision payload at sequence ${record.sequence}`)\n }\n if (record.event !== undefined && record.event.pursuitId !== record.pursuitId) {\n throw new Error(\n `observer journal: nested event pursuit mismatch at sequence ${record.sequence}`,\n )\n }\n if (record.decision !== undefined && record.decision.pursuitId !== record.pursuitId) {\n throw new Error(\n `observer journal: nested decision pursuit mismatch at sequence ${record.sequence}`,\n )\n }\n const { digest, ...unsigned } = record\n const expected = observerRecordDigest(unsigned)\n if (digest !== expected) {\n throw new Error(`observer journal: digest mismatch at sequence ${record.sequence}`)\n }\n previousDigest = digest\n expectedSequence += 1\n }\n}\n\n/** Compute the canonical SHA-256 digest for an unsigned observer record. */\nexport function observerRecordDigest(record: Omit<ObserverRecord, 'digest'>): string {\n return createHash('sha256').update(JSON.stringify(record)).digest('hex')\n}\n\n/** Build the canonical durable observer hook in one call. */\nexport function createFileObserverHooks(\n path: string,\n pursuitId: string,\n): {\n readonly journal: FileObserverJournal\n readonly hooks: RuntimeHooks\n} {\n const journal = new FileObserverJournal(path, pursuitId)\n return { journal, hooks: journal.hooks() }\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error))\n}\n","import type {\n BudgetOverspend,\n BudgetViolation,\n ExecutionBindingReceipt,\n ProfileMaterializationReceipt,\n ProviderModelExecutionEvidence,\n RetainedExecutionState,\n RetainedPendingCause,\n Spend,\n SpendChannel,\n SpendGap,\n WorkerTraceEvidence,\n} from '../runtime/supervise/types'\nimport { addSpend, cloneSpend, zeroSpend } from '../runtime/util'\nimport type { RuntimeDecisionKind, RuntimeHookTarget } from '../runtime-hooks'\nimport { type ObserverRecord, verifyObserverRecords } from './observer-journal'\n\n/**\n * One settled projection status, shared by runs and nodes. `down` is the journal's own word for a\n * failure (a settlement is journaled as `kind: 'down'`, cancellation included), so a consumer can\n * join run rows to node rows on `status` and read one failure population instead of two.\n */\nexport type PursuitStatus = 'running' | 'done' | 'down'\n\n/**\n * Where a node's dollar figure came from. `reported` = a provider billed all of it; `estimated` =\n * a model catalog priced all of it; `partial` = a provider billed part and a catalog priced the\n * rest; `unknown` = nothing priced it, so `usd` is a floor and never the cost.\n */\nexport type PursuitCostProvenance = 'reported' | 'estimated' | 'partial' | 'unknown'\n\n/**\n * One node's token usage by class. Cache and reasoning classes are absent when the provider did\n * not report them — absence is not zero. `tokensKnown` is `false` when work happened whose token\n * count no provider reported, which makes `input`/`output` a floor.\n */\nexport interface PursuitNodeUsage {\n readonly input: number\n readonly output: number\n readonly cacheRead?: number\n readonly cacheWrite?: number\n readonly reasoning?: number\n readonly tokensKnown: boolean\n}\n\n/**\n * One node's PLATFORM consumption — box wall time, the resource a subscription seat really pays.\n *\n * Kept apart from `PursuitNodeCost` because the two answer different questions and fail\n * independently: a seat run reports a truthful `$0` and real minutes, a caller-account run\n * reports real dollars and may report no minutes at all. Collapsing them into one \"spend known\"\n * figure hides which one is missing.\n *\n * Absent on a node that ran no box. `boxMinutes` absent WITH the block present says a box ran and\n * nothing measured it — a missing measurement is never a zero.\n */\nexport interface PursuitNodePlatform {\n readonly boxMinutes?: number\n /** `false` when a box ran whose time could not be closed, so `boxMinutes` is a floor. */\n readonly boxMinutesKnown: boolean\n /** `observed` = the platform billed the minutes; `estimated` = Runtime derived them from the box\n * lifetime it watched; `uncaptured` = a box ran and nothing measured it. */\n readonly provenance: 'observed' | 'estimated' | 'uncaptured'\n}\n\n/** One node's dollar cost with the provenance that decides whether it may be compared or summed. */\nexport interface PursuitNodeCost {\n readonly usd: number\n readonly usdKnown: boolean\n /** The part of `usd` a model catalog priced because no provider receipt covered it. */\n readonly usdEstimated?: number\n readonly provenance: PursuitCostProvenance\n}\n\n/**\n * One node's clock. `wallMs` is `settledAt - startedAt` and is deliberately distinct from the\n * executor-reported `spent.ms` sums, which under-report and overlap across parallel children.\n * `firstTokenAt` stays absent unless a provider reports that instant; it is never inferred from\n * `firstOutputAt`, which is when the node first reported usage for a turn.\n */\nexport interface PursuitNodeTiming {\n readonly startedAt: number\n readonly firstOutputAt?: number\n readonly firstTokenAt?: number\n readonly settledAt?: number\n readonly wallMs?: number\n}\n\n/** Where and how a node's execution was placed, read off its execution-binding receipt. */\nexport type PursuitNodePlacement = Readonly<Record<string, string | number | boolean | null>>\n\n/**\n * One run's spend counted once, and each node's own share of it. `inclusive` and the entries of\n * `exclusiveByNode` are the two views a client needs to show a tree without double counting.\n */\nexport interface PursuitRunTotals {\n /**\n * The whole run counted once. A node's settled `spent` already contains the child work its own\n * nested tree reported, so summing only the run's top-level nodes plus every node's own\n * inference counts each model call exactly once.\n */\n readonly inclusive: Spend\n /**\n * Each node's own share: its reported spend and own inference minus what its direct children\n * reported. Keyed by node id, plus the run root when the root itself metered inference. The\n * entries sum to `inclusive` by construction.\n */\n readonly exclusiveByNode: Readonly<Record<string, Spend>>\n}\n\n/**\n * One attempt at one concrete Runtime run: the stretch of `agent.run` lifecycle from a `before`\n * to the `after` or `error` that settles it. A run whose first attempt threw and whose corrected\n * attempt settled is two rows, so `error` names only the attempt that failed.\n *\n * A `before` observed while an attempt is still open does not open another: it is a process\n * that resumed the run after the previous process died without a terminal record, and the row\n * counts it in `resumeCount`. The alternative, a row per process start, would leave the killed\n * process's row `running` for the rest of history.\n */\nexport interface PursuitRunProjection {\n readonly runId: string\n /** Zero-based position of this attempt among the run's attempts, in journal order. */\n readonly attemptIndex: number\n /** How many times a process resumed this attempt after a predecessor died mid-run. */\n readonly resumeCount: number\n readonly status: PursuitStatus\n readonly settledAt?: number\n readonly error?: string\n readonly firstSequence: number\n readonly lastSequence: number\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly eventCount: number\n readonly decisionCount: number\n readonly targets: Readonly<Record<string, number>>\n readonly decisions: Readonly<Record<string, number>>\n readonly totals: PursuitRunTotals\n /** The nodes whose accounting is incomplete. Present exactly when non-empty. */\n readonly spendGaps?: ReadonlyArray<SpendGap>\n}\n\nexport interface PursuitNodeProjection {\n readonly id: string\n readonly parentId?: string\n /** Node ids are scoped to this concrete Runtime tree; `(runId,id)` is identity. */\n readonly runId: string\n readonly label?: string\n /** The runner that executed this node — the executor's own name, not a harness guess. */\n readonly runtime?: string\n readonly depth?: number\n readonly assignmentId?: string\n /** The settled sibling this node replaced, as its manager's spawn named it. Absent on a node\n * that replaced nothing. */\n readonly successorOf?: string\n readonly identity?: unknown\n readonly budget?: unknown\n readonly status: PursuitStatus\n readonly settledAt?: number\n /** The child work this node reported at settlement. Absent until a terminal record lands. */\n readonly spent?: Spend\n /** This node's OWN inference, re-homed from its nested tree. Absent when it drove no turns. */\n readonly ownInference?: Spend\n /** Absent until a spend record lands; the run's `spendGaps` then names the node. */\n readonly usage?: PursuitNodeUsage\n /** Absent until a spend record lands; the run's `spendGaps` then names the node. */\n readonly cost?: PursuitNodeCost\n /** What the node consumed on the PLATFORM. Absent on a node that ran no box. */\n readonly platform?: PursuitNodePlatform\n readonly timing?: PursuitNodeTiming\n /** The kernel-minted attempt this node's execution binding is keyed on. */\n readonly attemptId?: string\n /** The runner-native execution the node bound to: a request, session, run, process, or tree. */\n readonly execution?: { readonly kind: string; readonly id: string }\n /** The model the materialization receipt names, when the runner reported one. */\n readonly model?: string\n /** The concrete backend the profile materialized onto. */\n readonly backend?: string\n readonly placement?: PursuitNodePlacement\n /** Model-call identifiers this node's own turns reported, in order, deduplicated. */\n readonly modelCalls?: ReadonlyArray<string>\n readonly materialization?: ProfileMaterializationReceipt\n readonly executionBindings?: ReadonlyArray<ExecutionBindingReceipt>\n /** What the provider itself reported serving, and why it is unknown when it is. */\n readonly providerModel?: ProviderModelExecutionEvidence\n /** Content-addressed pointer to this node's persisted tool trace, or why there is none. */\n readonly trace?: WorkerTraceEvidence\n readonly outRef?: string\n readonly score?: number\n readonly valid?: boolean\n readonly reason?: string\n readonly infra?: boolean\n /** Recorded by Runtime on the `agent.child` payload: `'pending'` at a retained child's\n * settlement, `'released'` when root settlement destroyed its environment without recovery,\n * `'release-unconfirmed'` when a final settlement closed its slot without confirming that.\n * The status stays `down` — the split is a sibling fact, not a fourth status. A second\n * `agent.child` for one node is already how a live-recovered child flips down→done, so the\n * fold overwrites in observed order; that event's `settledAt` is the original settlement, so\n * `settledAt` and `timing` do not move. */\n readonly retainedExecution?: RetainedExecutionState\n /** Why a retained child has no accepted result; see `RetainedPendingCause`. */\n readonly retainedPendingCause?: RetainedPendingCause\n /** When a final settlement closed a retained node's slot; absent while it is `'pending'`. */\n readonly releasedAt?: number\n /** Each channel on which the settled spend exceeded the node's reservation. The status is the\n * node's own outcome: a `done` node that overspent still delivered its output. */\n readonly budgetViolation?: BudgetViolation\n readonly wait?: unknown\n readonly firstSequence: number\n readonly lastSequence: number\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly eventCount: number\n readonly turnCount: number\n}\n\nexport interface PursuitProjection {\n readonly pursuitId: string\n /** Number of records in this concrete execution journal. */\n readonly sequence: number\n /** Digest-chain tip for this concrete execution journal. */\n readonly chainTip: string\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly runs: readonly PursuitRunProjection[]\n readonly nodes: readonly PursuitNodeProjection[]\n readonly eventCount: number\n readonly decisionCount: number\n}\n\ntype MutableRun = {\n runId: string\n attemptIndex: number\n resumeCount: number\n /** Whether this attempt has seen its own `before`; an attempt a journal opens without one\n * treats the first `before` it meets as its start, not as a resume. */\n started: boolean\n status: PursuitStatus\n settledAt?: number\n error?: string\n firstSequence: number\n lastSequence: number\n firstObservedAt: number\n lastObservedAt: number\n eventCount: number\n decisionCount: number\n targets: Record<string, number>\n decisions: Record<string, number>\n /** Inference the run root drove itself, attributable to no spawned node. */\n rootInference?: Spend\n}\n\ntype MutableNode = {\n id: string\n parentId?: string\n runId: string\n /** The attempt whose process spawned this node; totals and gaps are folded per attempt. */\n attemptIndex: number\n label?: string\n runtime?: string\n depth?: number\n assignmentId?: string\n successorOf?: string\n identity?: unknown\n budget?: unknown\n status: PursuitStatus\n startedAt?: number\n settledAt?: number\n spent?: Spend\n ownInference?: Spend\n reasoningTokens?: number\n firstOutputAt?: number\n firstTokenAt?: number\n attemptId?: string\n execution?: { kind: string; id: string }\n model?: string\n backend?: string\n placement?: PursuitNodePlacement\n modelCalls: string[]\n materialization?: ProfileMaterializationReceipt\n executionBindings?: ReadonlyArray<ExecutionBindingReceipt>\n providerModel?: ProviderModelExecutionEvidence\n trace?: WorkerTraceEvidence\n outRef?: string\n score?: number\n valid?: boolean\n reason?: string\n infra?: boolean\n retainedExecution?: RetainedExecutionState\n retainedPendingCause?: RetainedPendingCause\n releasedAt?: number\n budgetViolation?: BudgetViolation\n wait?: unknown\n firstSequence: number\n lastSequence: number\n firstObservedAt: number\n lastObservedAt: number\n eventCount: number\n turnCount: number\n}\n\n/**\n * Fold one append-only execution journal into a deterministic operator projection.\n *\n * This is intentionally a READ model, not another state machine: it does not own\n * execution, cannot steer agents, and can be rebuilt from the journal at any time.\n * Projection verifies the complete hash chain first, so an operator view can never\n * silently render a mutated or reordered observer history as trustworthy state.\n *\n * Topology comes only from Runtime's canonical `agent.spawn` facts. Terminal node\n * state comes only from `agent.child`; concrete run state comes only from the root\n * `agent.run` lifecycle emitted by `supervisePursuit`, one row per attempt. Node identity is\n * scoped to the concrete Runtime run so independent trees may both contain `root:s0` without\n * aliasing, and a node belongs to the attempt that spawned it.\n *\n * Usage, cost and timing are reported at the class the runtime measured them at. A missing\n * class stays ABSENT and the run names the node in `spendGaps`; nothing here converts an\n * unmeasured channel into a zero, because a fabricated zero is indistinguishable from free work.\n */\nexport function projectPursuit(records: readonly ObserverRecord[]): PursuitProjection {\n if (records.length === 0) {\n throw new TypeError('projectPursuit: at least one observer record is required')\n }\n const pursuitId = records[0]!.pursuitId\n const verified = verifyObserverRecords(records, pursuitId)\n const attempts = new Map<string, MutableRun[]>()\n const nodes = new Map<string, MutableNode>()\n let eventCount = 0\n let decisionCount = 0\n\n for (const record of verified) {\n const observed = record.event ?? record.decision\n if (!observed) throw new Error(`projectPursuit: record ${record.sequence} has no observation`)\n const run = currentAttempt(attempts, observed.runId, record)\n run.lastSequence = record.sequence\n run.lastObservedAt = record.observedAt\n\n if (record.event) {\n eventCount += 1\n run.eventCount += 1\n increment(run.targets, record.event.target)\n projectRunActivity(run, record)\n projectSpawnNode(nodes, record, run.attemptIndex)\n projectNodeActivity(nodes, record)\n projectTurn(run, nodes, record)\n } else if (record.decision) {\n decisionCount += 1\n run.decisionCount += 1\n increment(run.decisions, record.decision.kind)\n }\n }\n\n const byAttempt = new Map<string, MutableNode[]>()\n for (const node of nodes.values()) {\n const key = attemptKey(node.runId, node.attemptIndex)\n const list = byAttempt.get(key)\n if (list) list.push(node)\n else byAttempt.set(key, [node])\n }\n\n const first = verified[0]!\n const last = verified.at(-1)!\n return Object.freeze({\n pursuitId,\n sequence: last.sequence,\n chainTip: last.digest,\n firstObservedAt: first.observedAt,\n lastObservedAt: last.observedAt,\n runs: Object.freeze(\n [...attempts.values()]\n .flat()\n .sort((a, b) => a.firstSequence - b.firstSequence || a.runId.localeCompare(b.runId))\n .map((run) => freezeRun(run, byAttempt.get(attemptKey(run.runId, run.attemptIndex)) ?? [])),\n ),\n nodes: Object.freeze(\n [...nodes.values()]\n .sort(\n (a, b) =>\n a.firstSequence - b.firstSequence ||\n a.runId.localeCompare(b.runId) ||\n a.id.localeCompare(b.id),\n )\n .map(freezeNode),\n ),\n eventCount,\n decisionCount,\n })\n}\n\nfunction attemptKey(runId: string, attemptIndex: number): string {\n return `${runId}\\u0000${attemptIndex}`\n}\n\n/**\n * The attempt a record belongs to. An `agent.run` `before` opens a new attempt when the run has\n * none or its latest attempt already settled; on an open attempt it is a resume. Every other\n * record joins the latest attempt, and a journal that never emitted `before` gets attempt 0.\n */\nfunction currentAttempt(\n attempts: Map<string, MutableRun[]>,\n runId: string,\n record: ObserverRecord,\n): MutableRun {\n const list = attempts.get(runId) ?? []\n if (list.length === 0) attempts.set(runId, list)\n const latest = list.at(-1)\n const isStart = record.event?.target === 'agent.run' && record.event.phase === 'before'\n if (latest !== undefined && (!isStart || latest.status === 'running')) {\n if (isStart) {\n if (latest.started) latest.resumeCount += 1\n latest.started = true\n }\n return latest\n }\n const created: MutableRun = {\n runId,\n attemptIndex: list.length,\n resumeCount: 0,\n started: isStart,\n status: 'running',\n firstSequence: record.sequence,\n lastSequence: record.sequence,\n firstObservedAt: record.observedAt,\n lastObservedAt: record.observedAt,\n eventCount: 0,\n decisionCount: 0,\n targets: {},\n decisions: {},\n }\n list.push(created)\n return created\n}\n\nfunction projectRunActivity(run: MutableRun, record: ObserverRecord): void {\n const event = record.event\n if (event?.target !== 'agent.run') return\n const payload = objectRecord(event.payload)\n const status = stringField(payload, 'status')\n if (event.phase === 'after' || status === 'done') {\n run.status = 'done'\n run.settledAt = record.observedAt\n return\n }\n // The `agent.run` hook payload spells a failure `failed`; the projection spells every\n // settled failure `down`, the journal's word, so run and node rows join on one vocabulary.\n if (event.phase !== 'error' && status !== 'failed') return\n run.status = 'down'\n run.settledAt = record.observedAt\n const error = stringField(payload, 'error')\n if (error) run.error = error\n}\n\nfunction nodeKey(runId: string, nodeId: string): string {\n return `${runId}\\u0000${nodeId}`\n}\n\nfunction projectSpawnNode(\n nodes: Map<string, MutableNode>,\n record: ObserverRecord,\n attemptIndex: number,\n): void {\n const event = record.event\n if (event?.target !== 'agent.spawn') return\n const payload = objectRecord(event.payload)\n const childId = stringField(payload, 'childId')\n if (!childId) return\n const key = nodeKey(event.runId, childId)\n const existing = nodes.get(key)\n if (existing) {\n existing.lastSequence = record.sequence\n existing.lastObservedAt = record.observedAt\n existing.eventCount += 1\n return\n }\n const label = stringField(payload, 'label')\n const runtime = stringField(payload, 'runtime')\n const depth = numberField(payload, 'depth')\n const assignmentId = stringField(payload, 'assignmentId')\n const successorOf = stringField(payload, 'successorOf')\n const attemptId = stringField(payload, 'attemptId')\n const startedAt = numberField(payload, 'startedAt')\n nodes.set(key, {\n id: childId,\n ...(event.parentId ? { parentId: event.parentId } : {}),\n runId: event.runId,\n attemptIndex,\n ...(label ? { label } : {}),\n ...(runtime ? { runtime } : {}),\n ...(depth !== undefined ? { depth } : {}),\n ...(assignmentId ? { assignmentId } : {}),\n ...(successorOf ? { successorOf } : {}),\n ...(attemptId ? { attemptId } : {}),\n // A spawn that predates the `startedAt` fact falls back to when the record was observed:\n // the spawn event is emitted synchronously with the spawn, so the two agree to the ms.\n startedAt: startedAt ?? record.observedAt,\n ...(payload && Object.hasOwn(payload, 'identity') ? { identity: payload.identity } : {}),\n ...(payload && Object.hasOwn(payload, 'budget') ? { budget: payload.budget } : {}),\n status: 'running',\n modelCalls: [],\n firstSequence: record.sequence,\n lastSequence: record.sequence,\n firstObservedAt: record.observedAt,\n lastObservedAt: record.observedAt,\n eventCount: 1,\n turnCount: 0,\n })\n}\n\nfunction projectNodeActivity(nodes: Map<string, MutableNode>, record: ObserverRecord): void {\n const event = record.event\n if (event === undefined) return\n if (event.target === 'agent.spawn') return\n const payload = objectRecord(event.payload)\n const nodeId =\n stringField(payload, 'childId') ??\n stringField(payload, 'nodeId') ??\n stringField(payload, 'workerId')\n if (!nodeId) return\n const node = nodes.get(nodeKey(event.runId, nodeId))\n if (!node) return\n node.lastSequence = record.sequence\n node.lastObservedAt = record.observedAt\n node.eventCount += 1\n\n if (event.target !== 'agent.child') return\n const status = stringField(payload, 'status')\n if (status !== 'done' && status !== 'down') return\n node.status = status\n node.settledAt = numberField(payload, 'settledAt') ?? record.observedAt\n const startedAt = numberField(payload, 'startedAt')\n if (startedAt !== undefined) node.startedAt = startedAt\n if (payload && Object.hasOwn(payload, 'spent')) node.spent = spendField(payload, 'spent')\n const metered = spendField(payload, 'metered')\n if (metered)\n node.ownInference = node.ownInference ? addSpend(node.ownInference, metered) : metered\n const runtime = stringField(payload, 'runtime')\n if (runtime) node.runtime = runtime\n const outRef = stringField(payload, 'outRef')\n if (outRef) node.outRef = outRef\n const score = numberField(payload, 'score')\n if (score !== undefined) node.score = score\n const valid = booleanField(payload, 'valid')\n if (valid !== undefined) node.valid = valid\n const reason = stringField(payload, 'reason')\n if (reason) node.reason = reason\n const infra = booleanField(payload, 'infra')\n if (infra !== undefined) node.infra = infra\n const retained = stringField(payload, 'retainedExecution')\n if (retained === 'pending' || retained === 'released' || retained === 'release-unconfirmed') {\n node.retainedExecution = retained\n }\n const cause = stringField(payload, 'retainedPendingCause')\n if (\n cause === 'unobservable' ||\n cause === 'provider-contract' ||\n cause === 'request-rejected' ||\n cause === 'transport' ||\n cause === 'nested-recovery'\n )\n node.retainedPendingCause = cause\n const releasedAt = numberField(payload, 'releasedAt')\n if (releasedAt !== undefined) node.releasedAt = releasedAt\n const budgetViolation = budgetViolationField(payload)\n if (budgetViolation) node.budgetViolation = budgetViolation\n if (payload && Object.hasOwn(payload, 'wait')) node.wait = payload.wait\n attachSettlementEvidence(node, payload)\n}\n\n/**\n * Read the receipts a settlement carries. Each is taken as reported: an `unknown` receipt keeps\n * its `status` and `reason` so a client can show WHY a model or backend is missing instead of\n * showing nothing, and a receipt that never landed leaves every derived field absent.\n */\nfunction attachSettlementEvidence(\n node: MutableNode,\n payload: Record<string, unknown> | undefined,\n): void {\n const providerModel = payload?.providerModel as ProviderModelExecutionEvidence | undefined\n if (providerModel && typeof providerModel === 'object') node.providerModel = providerModel\n const trace = payload?.trace as WorkerTraceEvidence | undefined\n if (trace && typeof trace === 'object') node.trace = trace\n const bindings = payload?.executionBindings\n if (Array.isArray(bindings) && bindings.length > 0) {\n node.executionBindings = bindings as ReadonlyArray<ExecutionBindingReceipt>\n const known = bindings.find(\n (binding): binding is Extract<ExecutionBindingReceipt, { status: 'known' }> =>\n objectRecord(binding)?.status === 'known',\n )\n if (known) {\n node.placement = known.descriptor\n node.attemptId ??= known.attemptId\n }\n }\n const receipt = payload?.materialization as ProfileMaterializationReceipt | undefined\n if (!receipt || typeof receipt !== 'object') return\n node.materialization = receipt\n if (receipt.status !== 'known') return\n node.backend = receipt.backend\n if (receipt.model.status === 'known') node.model = receipt.model.id\n node.execution = { kind: receipt.execution.kind, id: receipt.execution.id }\n}\n\n/**\n * Fold one metered turn onto whoever drove it. `agent.turn` names its subject in `parentId` — the\n * node making the call — not in the payload, because the caller IS the subject. A turn the run\n * root drove belongs to no spawned node and lands on the run instead, so the run's totals stay\n * complete without inventing a node for the root.\n */\nfunction projectTurn(\n run: MutableRun,\n nodes: Map<string, MutableNode>,\n record: ObserverRecord,\n): void {\n const event = record.event\n if (event?.target !== 'agent.turn') return\n const payload = objectRecord(event.payload)\n const spend = spendField(payload, 'spend')\n const subject = event.parentId\n if (subject === undefined) return\n const node = nodes.get(nodeKey(event.runId, subject))\n if (!node) {\n if (!spend) return\n run.rootInference = run.rootInference ? addSpend(run.rootInference, spend) : spend\n return\n }\n node.turnCount += 1\n node.lastSequence = record.sequence\n node.lastObservedAt = record.observedAt\n if (spend) {\n node.ownInference = node.ownInference ? addSpend(node.ownInference, spend) : spend\n node.firstOutputAt ??= record.observedAt\n }\n const reasoning = numberField(payload, 'reasoningTokens')\n if (reasoning !== undefined) node.reasoningTokens = (node.reasoningTokens ?? 0) + reasoning\n const firstTokenAt = numberField(payload, 'firstTokenAt')\n if (firstTokenAt !== undefined) node.firstTokenAt ??= firstTokenAt\n const model = stringField(payload, 'model')\n if (model) node.model ??= model\n const callId = stringField(payload, 'callId')\n if (callId && !node.modelCalls.includes(callId)) node.modelCalls.push(callId)\n}\n\n/**\n * A node's whole reported cost: the child work its settlement reported plus the inference it drove\n * itself. `undefined` when neither landed — the run's `spendGaps` then names the node, so an\n * unaccounted node is visible instead of reading as free.\n */\nfunction nodeTotal(node: MutableNode): Spend | undefined {\n if (node.spent && node.ownInference) return addSpend(node.spent, node.ownInference)\n if (node.spent) return cloneSpend(node.spent)\n if (node.ownInference) return cloneSpend(node.ownInference)\n return undefined\n}\n\n/**\n * The run counted once, and each node's own share of it.\n *\n * A settled node's `spent` already contains the child work its nested tree reported, so summing\n * every node would count a driver's descendants twice. Inclusive therefore sums only the run's\n * TOP-LEVEL nodes — those whose parent is not another node of this run — plus the root's own\n * turns. Exclusive subtracts each node's direct children from its own total, which telescopes:\n * the exclusive entries sum back to `inclusive` exactly.\n */\nfunction runTotals(run: MutableRun, nodes: readonly MutableNode[]): PursuitRunTotals {\n const present = new Set(nodes.map((node) => node.id))\n const children = new Map<string, MutableNode[]>()\n for (const node of nodes) {\n if (node.parentId === undefined || !present.has(node.parentId)) continue\n const list = children.get(node.parentId)\n if (list) list.push(node)\n else children.set(node.parentId, [node])\n }\n const exclusiveByNode: Record<string, Spend> = {}\n let inclusive = run.rootInference ? cloneSpend(run.rootInference) : zeroSpend()\n if (run.rootInference) exclusiveByNode[run.runId] = cloneSpend(run.rootInference)\n for (const node of nodes) {\n const total = nodeTotal(node)\n if (total === undefined) continue\n if (node.parentId === undefined || !present.has(node.parentId)) {\n inclusive = addSpend(inclusive, total)\n }\n let exclusive = total\n for (const child of children.get(node.id) ?? []) {\n const childTotal = nodeTotal(child)\n if (childTotal !== undefined) exclusive = subtractSpend(exclusive, childTotal)\n }\n exclusiveByNode[node.id] = exclusive\n }\n return Object.freeze({\n inclusive: Object.freeze(inclusive),\n exclusiveByNode: Object.freeze(exclusiveByNode),\n })\n}\n\n/**\n * Remove a child's reported total from its parent's. Per channel, never below zero: a parent whose\n * executor reported less than its children did is a reporting gap, and a negative exclusive share\n * would be a fabricated number rather than a measurement.\n */\nfunction subtractSpend(a: Spend, b: Spend): Spend {\n const tokens = { ...a.tokens }\n tokens.input = Math.max(0, tokens.input - b.tokens.input)\n tokens.output = Math.max(0, tokens.output - b.tokens.output)\n if (a.tokens.cacheRead !== undefined)\n tokens.cacheRead = Math.max(0, a.tokens.cacheRead - (b.tokens.cacheRead ?? 0))\n if (a.tokens.cacheWrite !== undefined)\n tokens.cacheWrite = Math.max(0, a.tokens.cacheWrite - (b.tokens.cacheWrite ?? 0))\n if (a.tokens.freshInput !== undefined)\n tokens.freshInput = Math.max(0, a.tokens.freshInput - (b.tokens.freshInput ?? 0))\n return {\n iterations: Math.max(0, a.iterations - b.iterations),\n tokens,\n ...(a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: Math.max(0, a.usd - b.usd),\n ...(a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {}),\n ...(a.usdEstimated !== undefined\n ? { usdEstimated: Math.max(0, a.usdEstimated - (b.usdEstimated ?? 0)) }\n : {}),\n ms: Math.max(0, a.ms - b.ms),\n }\n}\n\n/** The nodes of one run whose accounting is incomplete, in the vocabulary the supervisor already\n * uses: `never-settled` = no terminal record, so every channel is unaccounted; `unreported` = a\n * record landed with a channel the provider did not report, so that channel is a floor. */\nfunction runSpendGaps(nodes: readonly MutableNode[]): SpendGap[] {\n const gaps: SpendGap[] = []\n for (const node of nodes) {\n const label = node.label\n if (node.status === 'running') {\n gaps.push({\n id: node.id,\n ...(label !== undefined ? { label } : {}),\n kind: 'never-settled',\n channels: ['tokens', 'usd'],\n })\n continue\n }\n const total = nodeTotal(node)\n const channels: SpendChannel[] = []\n if (total === undefined || total.tokensKnown === false) channels.push('tokens')\n if (total === undefined || total.usdKnown === false) channels.push('usd')\n if (channels.length === 0) continue\n gaps.push({\n id: node.id,\n ...(label !== undefined ? { label } : {}),\n kind: 'unreported',\n channels,\n })\n }\n return gaps\n}\n\nfunction usageOf(total: Spend, reasoning: number | undefined): PursuitNodeUsage {\n return {\n input: total.tokens.input,\n output: total.tokens.output,\n ...(total.tokens.cacheRead !== undefined ? { cacheRead: total.tokens.cacheRead } : {}),\n ...(total.tokens.cacheWrite !== undefined ? { cacheWrite: total.tokens.cacheWrite } : {}),\n ...(reasoning !== undefined ? { reasoning } : {}),\n tokensKnown: total.tokensKnown !== false && total.tokens.tokensKnown !== false,\n }\n}\n\nfunction costOf(total: Spend): PursuitNodeCost {\n const usdKnown = total.usdKnown !== false\n const estimated = total.usdEstimated\n const provenance: PursuitCostProvenance = usdKnown\n ? estimated === undefined || estimated === 0\n ? 'reported'\n : 'partial'\n : estimated === undefined\n ? 'unknown'\n : estimated >= total.usd\n ? 'estimated'\n : 'partial'\n return {\n usd: total.usd,\n usdKnown,\n ...(estimated !== undefined ? { usdEstimated: estimated } : {}),\n provenance,\n }\n}\n\n/** The platform block, or nothing at all when the node's spend names no box channel. */\nfunction platformOf(total: Spend): PursuitNodePlatform | undefined {\n if (total.boxMinutesProvenance === undefined) return undefined\n return {\n ...(total.boxMinutes !== undefined ? { boxMinutes: total.boxMinutes } : {}),\n boxMinutesKnown: total.boxMinutesKnown === true,\n provenance: total.boxMinutesProvenance,\n }\n}\n\nfunction timingOf(node: MutableNode): PursuitNodeTiming | undefined {\n if (node.startedAt === undefined) return undefined\n return {\n startedAt: node.startedAt,\n ...(node.firstOutputAt !== undefined ? { firstOutputAt: node.firstOutputAt } : {}),\n ...(node.firstTokenAt !== undefined ? { firstTokenAt: node.firstTokenAt } : {}),\n ...(node.settledAt !== undefined ? { settledAt: node.settledAt } : {}),\n ...(node.settledAt !== undefined\n ? { wallMs: Math.max(0, node.settledAt - node.startedAt) }\n : {}),\n }\n}\n\nfunction freezeRun(run: MutableRun, nodes: readonly MutableNode[]): PursuitRunProjection {\n const gaps = runSpendGaps(nodes)\n const { rootInference: _rootInference, started: _started, ...rest } = run\n return Object.freeze({\n ...rest,\n targets: Object.freeze({ ...run.targets }),\n decisions: Object.freeze({ ...run.decisions }),\n totals: runTotals(run, nodes),\n ...(gaps.length > 0 ? { spendGaps: Object.freeze(gaps) } : {}),\n })\n}\n\nfunction freezeNode(node: MutableNode): PursuitNodeProjection {\n const {\n modelCalls,\n reasoningTokens,\n startedAt: _startedAt,\n attemptIndex: _attemptIndex,\n ...rest\n } = node\n const total = nodeTotal(node)\n const timing = timingOf(node)\n return Object.freeze({\n ...rest,\n ...(modelCalls.length > 0 ? { modelCalls: Object.freeze([...modelCalls]) } : {}),\n ...(total !== undefined ? { usage: usageOf(total, reasoningTokens), cost: costOf(total) } : {}),\n ...(total !== undefined && platformOf(total) !== undefined\n ? { platform: platformOf(total) }\n : {}),\n ...(timing !== undefined ? { timing } : {}),\n })\n}\n\nfunction increment(\n target: Record<string, number>,\n key: RuntimeHookTarget | RuntimeDecisionKind,\n): void {\n target[key] = (target[key] ?? 0) + 1\n}\n\nfunction objectRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\n/** Read a journaled `Spend` without trusting the wire: a record missing the conserved channels is\n * not a zero-cost turn, it is an unparseable one, and it must not enter a total. */\nfunction spendField(value: Record<string, unknown> | undefined, key: string): Spend | undefined {\n const field = objectRecord(value?.[key])\n if (!field) return undefined\n const tokens = objectRecord(field.tokens)\n if (typeof field.usd !== 'number' || !Number.isFinite(field.usd)) return undefined\n if (!tokens || typeof tokens.input !== 'number' || typeof tokens.output !== 'number') {\n return undefined\n }\n return cloneSpend(field as unknown as Spend)\n}\n\n/** Read a journaled overspend without trusting the wire: one malformed channel drops the record,\n * so an unparseable entry is never reported as an overspend of some size. */\nfunction budgetViolationField(\n value: Record<string, unknown> | undefined,\n): BudgetViolation | undefined {\n const overspent = objectRecord(value?.budgetViolation)?.overspent\n if (!Array.isArray(overspent) || overspent.length === 0) return undefined\n const entries: BudgetOverspend[] = []\n for (const raw of overspent) {\n const entry = objectRecord(raw)\n const channel = stringField(entry, 'channel')\n const reserved = numberField(entry, 'reserved')\n const spent = numberField(entry, 'spent')\n if (channel === undefined || reserved === undefined || spent === undefined) return undefined\n entries.push({ channel: channel as BudgetOverspend['channel'], reserved, spent })\n }\n return { overspent: entries }\n}\n\nfunction stringField(value: Record<string, unknown> | undefined, key: string): string | undefined {\n const field = value?.[key]\n return typeof field === 'string' && field.length > 0 ? field : undefined\n}\n\nfunction numberField(value: Record<string, unknown> | undefined, key: string): number | undefined {\n const field = value?.[key]\n return typeof field === 'number' && Number.isFinite(field) ? field : undefined\n}\n\nfunction booleanField(\n value: Record<string, unknown> | undefined,\n key: string,\n): boolean | undefined {\n const field = value?.[key]\n return typeof field === 'boolean' ? field : undefined\n}\n","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, 2026-09-06): 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 with\n * `O_EXCL`, fsynced, and never replaced: a second settle in the same directory is refused before\n * any compute. `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`\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. */\nexport class 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 `runDir/result.json` 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 `runDir/failure.json` 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 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","/**\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 { access, readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport {\n developmentClaim,\n incumbent,\n openSearchLedger,\n parseSearchLedgerLine,\n runSearch,\n type SearchArtifactCodec,\n type SearchArtifactRef,\n type SearchAttemptAccounting,\n type SearchAudit,\n type SearchCellResult,\n type SearchCellSettledEvent,\n type SearchCloseReason,\n type SearchExecutionIdentity,\n type SearchExecutor,\n type SearchHistoryReceipt,\n type SearchNode,\n type SearchProposerPort,\n SearchRecorder,\n type SearchSourceRef,\n type SearchTaskOutcome,\n uniform,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n agentProfileSchema,\n canonicalAgentProfileDigest,\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 { type CheckVerdict, failedItems } from '../runtime/supervise/continuation'\nimport { authoredProfileDigest } from '../runtime/supervise/materialization'\nimport { superviseRootProfile } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { SpawnEvent, Spend, SupervisedResult } from '../runtime/supervise/types'\nimport { isNoEntError } from './jsonl-file'\nimport { FileObserverJournal } from './observer-journal'\nimport { projectPursuit } from './observer-projection'\nimport type { PursuitFork } from './run-fork'\nimport { readSettleRecord, SETTLE_RECORD_FILE } from './settle-record'\nimport { FileSpawnJournal } from './spawn-journal'\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 never starts a version once a cap is reached. */\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: settled versions' spend plus a hold for the next one. A version's\n * unknown spend counts as its proven floor. A version's own `budget.maxUsd` is the hold, and\n * bounds that version in flight; without it the hold is 0.\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\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 retried, 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 /** 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/** Where `'review-of-best'` mounts a review: `inputs/review/version-<n>.md`. One review lives in\n * a profile at a time. */\nexport const REVIEW_DIR = 'inputs/review/'\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/**\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(['patience', 'maxVersions', 'maxUsd', 'deadlineMs', 'minImprovement'])\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 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 retryable 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 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\ntype RunOne = (\n profile: SupervisorProfile,\n task: unknown,\n opts: SupervisePursuitOptions,\n) => Promise<SupervisedPursuitResult<SupervisedResult<unknown>>>\n\n/** A search node's artifact: a version's profile, or a change that did not apply. */\ninterface 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. */\ninterface 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 latest settled attempt's seal and verdict. */\n readonly seal?: SearchArtifactRef\n readonly verdict?: VersionVerdict\n /** Every seal an attempt recorded: a version's spend is recorded once, by the first. */\n readonly seals: ReadonlySet<string>\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 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 { judge, 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 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 = (\n firstFork === undefined\n ? profile\n : applyExactAgentProfileDiff(profile, firstFork.change, 'supervisePursuit versions')\n ) as AgentProfile\n const taskRevision = digestOf(task, 'task')\n const identity = (nodeProfile: AgentProfile): SearchExecutionIdentity => ({\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 const ledger = openSearchLedger({ path: ledgerPath, searchId })\n const opened = (await ledger.state()).header\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 const deadline =\n opened?.budget.deadline ??\n new Date(now() - settledElapsed(await readSettleRecord(runDir)) + stop.deadlineMs).toISOString()\n const policy = incumbent({\n patience: stop.patience,\n ...(stop.minImprovement === undefined ? {} : { minImprovement: stop.minImprovement }),\n })\n const allocation = uniform()\n const recorder = await 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: identity(firstProfile),\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 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\n const codec: 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\n const executor: SearchExecutor<VersionNode> = {\n lanes: () => [\n { name: LANE, capacity: 1, costCap: 'estimate', cellUsd: base.budget.maxUsd ?? 0 },\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 async run(work) {\n const chain = await 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 await runVersion(record, parent, AbortSignal.any([work.signal, expired.signal]))\n }\n const { settled, byteLength } = await readVersion(record, parent)\n // A retried cell reads the same sealed run back and only judges it again; the run's spend\n // was recorded by the attempt that first recorded its seal.\n const charged = !record.seals.has(settled.settleDigest)\n const verdict = await judgeVersion(settled, work.signal)\n return cellResult(settled, byteLength, verdict, work.lane, charged)\n },\n }\n\n const proposerSource: SearchSourceRef = {\n uri:\n versions.next === 'review-of-best'\n ? `${VERSION_CHAIN_URI}.review-of-best`\n : `${VERSION_CHAIN_URI}.next`,\n revision: canonicalCandidateDigest({\n next:\n versions.next === 'review-of-best'\n ? 'review-of-best'\n : Function.prototype.toString.call(versions.next),\n }),\n }\n const proposer: SearchProposerPort<VersionNode> = {\n name: versions.next === 'review-of-best' ? '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 judgedVersions(await versionsOf())\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 change = await next(\n { best, last: judged.at(-1)!, versions: Object.freeze(judged) },\n request.signal,\n )\n if (typeof change?.id !== 'string' || change.id.trim().length === 0) {\n throw new ValidationError('supervisePursuit versions: next must return a change with an id')\n }\n const parentDigest = canonicalAgentProfileDigest(parent.artifact.profile)\n let child: VersionNode\n try {\n child = {\n profile: applyExactAgentProfileDiff(\n parent.artifact.profile,\n change,\n 'supervisePursuit versions',\n ),\n change,\n parentDigest,\n refusal: null,\n }\n } catch (error) {\n child = { profile: null, change, parentDigest, refusal: errorMessage(error) }\n }\n return {\n children: [\n {\n artifact: child,\n label: change.title ?? change.id,\n rationale: (change.source?.notes ?? []).join('\\n'),\n },\n ],\n accounting:\n versions.next === 'review-of-best'\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 try {\n const closed = await runSearch({\n recorder,\n root: { profile: firstProfile, refusal: null },\n codec,\n policy,\n allocation,\n proposer,\n executor,\n admit: (node) => node.refusal,\n ...(callerSignal === undefined ? {} : { signal: callerSignal }),\n now,\n })\n const judged = await judgedVersions(await versionsOf())\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 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 if (timer !== undefined) clearTimeout(timer)\n }\n\n /** Run one version: the first as the call's own run, a later one as a fork of its parent. */\n async function runVersion(\n record: VersionRecord,\n parent: VersionRecord | undefined,\n signal: AbortSignal,\n ): Promise<void> {\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 async function readVersion(\n record: VersionRecord,\n parent: VersionRecord | undefined,\n ): Promise<{ settled: SettledPursuitVersion; byteLength: number }> {\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 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 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, bytes, result)\n return { settled, byteLength: bytes.byteLength }\n }\n\n async function judgeVersion(\n settled: SettledPursuitVersion,\n signal: AbortSignal,\n ): Promise<VersionVerdict> {\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 function cellResult(\n settled: SettledPursuitVersion,\n byteLength: number,\n verdict: VersionVerdict,\n lane: string,\n charged: boolean,\n ): SearchCellResult {\n const spent = settled.result.spentTotal\n const settlePath = resolve(settled.runDir, SETTLE_RECORD_FILE)\n const outcome: SearchTaskOutcome =\n verdict.score === null\n ? {\n status: 'errored',\n metrics: {},\n error: {\n code: 'unscored',\n message: `the judge could not score version ${settled.version}`,\n retryable: true,\n },\n }\n : settled.result.kind === 'winner'\n ? { status: 'passed', score: verdict.score, metrics: {} }\n : {\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 return {\n outcome,\n accounting: charged ? versionAccounting(spent) : FREE,\n identity: identity(settled.profile),\n boxMinutes:\n charged && isFiniteNumber(spent.boxMinutes) && spent.boxMinutesKnown !== false\n ? spent.boxMinutes\n : null,\n wallMs: charged && 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 recorder.blob('verdict', {\n kind: 'version-verdict',\n version: settled.version,\n runId: settled.runId,\n verdict,\n }),\n ],\n }\n }\n\n /** A version as the judge and `next` read it. */\n function versionOf(\n record: VersionRecord,\n parent: VersionRecord | undefined,\n bytes: Uint8Array,\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: sha256Bytes(bytes),\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\n /** Every version whose latest settled cell carries a verdict, first first, each read back from\n * its sealed `result.json`. */\n async function judgedVersions(\n chain: ReadonlyMap<string, VersionRecord>,\n ): Promise<JudgedPursuitVersion[]> {\n const judged: JudgedPursuitVersion[] = []\n for (const record of chain.values()) {\n if (record.seal === undefined || record.verdict === undefined) continue\n const { bytes, result } = await readSealed(record.runDir, record.version)\n if (sha256Bytes(bytes) !== record.seal.sha256) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: version ${record.version}'s result.json changed after it was judged`,\n )\n }\n const parent = record.parentNodeId === null ? undefined : chain.get(record.parentNodeId)\n judged.push(\n Object.freeze({ ...versionOf(record, parent, bytes, 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 function versionsOf(): Promise<Map<string, VersionRecord>> {\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 attempts = new Map<string, { latest: SearchCellSettledEvent; seals: Set<string> }>()\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 const { event } = entry\n if (event.kind !== 'cell-settled') continue\n const seals = attempts.get(event.cellId)?.seals ?? new Set<string>()\n const seal = event.artifacts.find((artifact) => artifact.role === 'settle-record')\n if (seal !== undefined) seals.add(seal.sha256)\n attempts.set(event.cellId, { latest: event, seals })\n }\n const chain = new Map<string, VersionRecord>()\n for (const { node, cellId, diff } of nodes) {\n const settled = cellId === undefined ? undefined : attempts.get(cellId)\n const artifact = (role: string) =>\n settled?.latest.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 seals: settled?.seals ?? new Set(),\n })\n }\n return chain\n }\n}\n\n/** The bytes of a version's sealed `result.json` and the record they hold. */\nasync function readSealed(\n runDir: string,\n version: number,\n): Promise<{ bytes: Uint8Array; result: SupervisedResult<unknown> }> {\n let bytes: Uint8Array\n try {\n bytes = await readFile(resolve(runDir, SETTLE_RECORD_FILE))\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 const result = (await readSettleRecord(runDir)) as SupervisedResult<unknown>\n return { bytes, result }\n}\n\nfunction 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. */\nfunction 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. */\nfunction versionAccounting(spent: Spend | undefined): SearchAttemptAccounting {\n const tokensKnown =\n spent !== undefined &&\n spent.tokensKnown !== false &&\n Number.isSafeInteger(spent.tokens?.input) &&\n Number.isSafeInteger(spent.tokens?.output)\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 ?? 0,\n }\n : { status: 'unknown', reason: \"the version's settled spend names unreported tokens\" },\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. */\nfunction settledElapsed(settled: SupervisedResult<unknown> | undefined): number {\n const elapsed = settled?.spentTotal?.ms\n return isFiniteNumber(elapsed) ? elapsed : 0\n}\n\nconst FREE: SearchAttemptAccounting = {\n tokens: { status: 'known', inputTokens: 0, outputTokens: 0, cachedTokens: 0 },\n cost: { status: 'known', usd: 0, source: 'free' },\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 }\n}\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 */\nfunction 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 const earlierInstructions = best.change?.set?.prompt?.instructions ?? []\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 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\nfunction digestOf(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\nasync 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\nfunction isSha256(value: unknown): value is Sha256Digest {\n return typeof value === 'string' && /^sha256:[0-9a-f]{64}$/u.test(value)\n}\n\nfunction isFiniteNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value)\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\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, loadSpawnForest } from './spawn-journal'\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. */\nexport const FORK_PARENT_UNCERTAIN_NODES_KEY = 'forkParentUncertainNodes'\n\n/** What `supervisePursuit` executes for a fork: the changed profile and the attributed execution. */\nexport interface 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 { execFile } from 'node:child_process'\nimport { mkdir, readFile, rmdir, unlink } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport { promisify } from 'node:util'\nimport { publishExclusiveDurableFile } from '../runtime/supervise/durable-file'\nimport { isNoEntError } from './jsonl-file'\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, 2026-09-06): 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. The start token (Linux\n * `/proc/<pid>/stat` starttime, otherwise `ps` lstart) is the same for a process's whole life\n * and differs for every later holder of its pid, so a reused pid is reclaimed like a dead one.\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, except when it dies during a guarded mutation; that guard requires manual recovery.\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 /** ISO instant the holder took the lock. */\n readonly startedAt: string\n readonly runId: string\n /**\n * The OS's start token for `pid` when the host reports one (`readProcessStart`). A holder\n * without one is judged by pid liveness alone, which cannot detect a reused pid.\n */\n readonly processStart?: string\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 path: string\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 gone (its pid no longer exists, or the pid now\n * belongs to a process with a different start token) is stale and is removed under the mutation guard;\n * a pid this process may not signal (`EPERM`) is alive and refuses. An empty file names no\n * 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 await mkdir(dir, { recursive: true })\n const processStart = await readProcessStart(process.pid)\n const holder: RunDirectoryLockHolder = Object.freeze({\n pid: process.pid,\n startedAt: new Date(now()).toISOString(),\n runId,\n ...(processStart === undefined ? {} : { processStart }),\n })\n return withMutationGuard(path, async () => {\n const existing = await readLockFile(path)\n if (existing.state === 'holder' && (await holderIsLive(existing.holder))) {\n throw new RunDirectoryLockedError(path, existing.holder)\n }\n if (existing.state !== 'missing') await removeIfPresent(path)\n if (!publishExclusiveDurableFile(path, `${JSON.stringify(holder)}\\n`)) {\n throw new Error(`supervisePursuit: could not take ${path}`)\n }\n let released = false\n return Object.freeze({\n ...holder,\n path,\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 /** True only while the process that took the lock is still the process that holds the pid. */\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: await holderIsLive(existing.holder), holder: existing.holder }\n}\n\nconst execFileAsync = promisify(execFile)\n\n/**\n * The OS's start token for a live pid: on Linux the `starttime` field of `/proc/<pid>/stat`\n * (clock ticks since boot), elsewhere the `ps` `lstart` column. The same process reports the\n * same token for its whole life and a later holder of the pid reports a different one.\n * `undefined` when the host cannot report one: the pid is gone, there is no `/proc` and no\n * `ps`, or the platform is Windows.\n */\nexport async function readProcessStart(pid: number): Promise<string | undefined> {\n if (!Number.isInteger(pid) || pid <= 0 || process.platform === 'win32') return undefined\n if (process.platform === 'linux') {\n let stat: string\n try {\n stat = await readFile(`/proc/${pid}/stat`, 'utf8')\n } catch {\n return undefined\n }\n // The comm field is parenthesized and may hold spaces, so fields are counted after its close.\n const fields = stat\n .slice(stat.lastIndexOf(')') + 1)\n .trim()\n .split(/\\s+/u)\n const startTime = fields[19]\n return startTime !== undefined && /^\\d+$/u.test(startTime) ? startTime : undefined\n }\n try {\n const { stdout } = await execFileAsync('ps', ['-o', 'lstart=', '-p', String(pid)])\n const token = stdout.trim()\n return token.length === 0 ? undefined : token\n } catch {\n return undefined\n }\n}\n\ntype LockFileState =\n | { readonly state: 'missing' }\n | { readonly state: 'empty' }\n | { readonly state: 'holder'; readonly holder: RunDirectoryLockHolder }\n\nasync function readLockFile(path: string): Promise<LockFileState> {\n let text: string\n try {\n text = await readFile(path, 'utf8')\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 ) {\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 return {\n state: 'holder',\n holder: Object.freeze({\n pid,\n startedAt,\n runId,\n ...(processStart === undefined ? {} : { processStart }),\n }),\n }\n}\n\nasync function holderIsLive(holder: RunDirectoryLockHolder): Promise<boolean> {\n if (!processExists(holder.pid)) return false\n if (holder.processStart === undefined) return true\n const current = await readProcessStart(holder.pid)\n // A pid that exists but reports no token cannot be shown to be reused, so it stays live.\n return current === undefined || current === holder.processStart\n}\n\nfunction processExists(pid: number): boolean {\n if (!Number.isInteger(pid) || pid <= 0) return false\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n // EPERM means the process exists but belongs to another user; only ESRCH means gone.\n return (error as { code?: unknown }).code !== 'ESRCH'\n }\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 await withMutationGuard(\n path,\n async () => {\n const existing = await 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 )\n return\n await removeIfPresent(path)\n },\n true,\n )\n}\n\n/** Serialize stale reclamation and release; an abandoned guard requires operator recovery. */\nasync function withMutationGuard<T>(\n path: string,\n mutate: () => Promise<T>,\n waitForRelease = false,\n): Promise<T> {\n const guard = `${path}.guard`\n const deadline = performance.now() + (waitForRelease ? 1_000 : 0)\n for (;;) {\n try {\n await mkdir(guard)\n break\n } catch (cause) {\n if (\n waitForRelease &&\n (cause as { code?: unknown }).code === 'EEXIST' &&\n performance.now() < deadline\n ) {\n await delay(10)\n continue\n }\n throw new Error(\n `supervisePursuit: cannot mutate ${path}; inspect ${guard} and remove it only after confirming no lock mutation is active`,\n { cause },\n )\n }\n }\n try {\n return await mutate()\n } finally {\n await rmdir(guard)\n }\n}\n\nasync function removeIfPresent(path: string): Promise<void> {\n try {\n await unlink(path)\n } catch (error) {\n if (!isNoEntError(error)) throw error\n }\n}\n","import { resolve } from 'node:path'\nimport { readRootStreamReceipt } from '../runtime/supervise/root-stream'\nimport { supervisorRunDir } from '../runtime/supervise/run-layout'\nimport { type SuperviseOptions, supervise } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport { composeRuntimeHooks, type RuntimeHookEvent, withPursuitContext } from '../runtime-hooks'\nimport { createFileObserverHooks } from './observer-journal'\nimport { type PursuitProjection, projectPursuit } from './observer-projection'\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 {\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'`. The settle record refuses re-entry, so no later call resumes a settled\n * pursuit and nothing else would release the provider environments its retained children hold.\n * `'keep'` is refused 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\nexport interface SupervisedPursuitResult<Result> {\n readonly result: Result\n readonly pursuit: PursuitProjection\n readonly observerPath: string\n /** `runDir/result.json`: `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 /** `runDir/failure.json`: 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 const pursuitId = opts.pursuitId.trim()\n if (pursuitId.length === 0) {\n throw new TypeError('supervisePursuit: pursuitId must be non-empty')\n }\n const runDir = opts.runDir.trim()\n if (runDir.length === 0) {\n throw new TypeError('supervisePursuit: runDir must be non-empty')\n }\n if ((opts.retainedAtSettlement as string | undefined) === 'keep') {\n throw new TypeError(\n \"supervisePursuit: retainedAtSettlement 'keep' cannot hold, because a settled pursuit is never re-entered\",\n )\n }\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 observerPath = resolve(runDir, 'observer.jsonl')\n const settlePath = resolve(runDir, SETTLE_RECORD_FILE)\n const failurePath = resolve(runDir, FAILURE_RECORD_FILE)\n const { pursuitId: _pursuitId, hooks, fork, versions: _versions, ...superviseOptions } = opts\n const runId = superviseOptions.runId ?? 'supervise'\n const now = superviseOptions.now ?? Date.now\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 // 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 try {\n const settled = await readSettleRecord(runDir)\n if (settled !== undefined) {\n throw new SettledRunDirectoryError(settlePath, settled.tree.root, runId)\n }\n\n const observer = createFileObserverHooks(observerPath, pursuitId)\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\n let result: Awaited<ReturnType<typeof supervise>>\n try {\n result = await supervise(forked?.profile ?? profile, task, {\n ...superviseOptions,\n ...(forked === undefined ? {} : { execution: forked.execution }),\n // `runDir` owns the pursuit journal and terminal records. The public steer writer addresses\n // the canonical per-run event directory beneath that root, so keep its control plane there\n // without moving the durable pursuit records.\n steerDir: superviseOptions.steerDir ?? supervisorRunDir(runDir, runId),\n // The settle record written below makes this settlement final, so the environments a\n // retained child holds are released at the barrier instead of kept for a resume that the\n // record will refuse (measured 2026-09-11: 18 of a 60-slot fleet held 19 to 37 hours).\n retainedAtSettlement: 'release',\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, hooks)),\n })\n } catch (error) {\n let pursuit: PursuitProjection | undefined\n let observerError: unknown\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 }),\n )\n pursuit = projectPursuit(await observer.journal.read())\n } catch (failure) {\n observerError = failure\n }\n if (observerError !== undefined || pursuit === undefined) {\n const causes = observerError === undefined ? [error] : [error, observerError]\n throw new Error(\n 'supervisePursuit: Runtime failed and durable observer completeness could not be proven',\n { cause: new AggregateError(causes) },\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 try {\n await writeSettleRecord(runDir, result)\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(), { status: 'done' }),\n )\n return Object.freeze({\n result,\n pursuit: projectPursuit(await observer.journal.read()),\n observerPath,\n settlePath,\n })\n } finally {\n await lock.release()\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 errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nfunction errorName(error: unknown): string {\n return error instanceof Error ? error.name : 'NonError'\n}\n","import { resolve } from 'node:path'\nimport type { NodeId } from '../runtime/supervise/types'\nimport { readCommittedJsonLines } from './jsonl-file'\n\nexport interface DurableCoordinationStreamIdentity {\n readonly runId: string\n /** Exact owner ids present in the side-log, sorted for deterministic display. */\n readonly ownerIds: readonly string[]\n /** Records written before owner-scoped coordination identities were introduced. */\n readonly unscopedRecords: number\n readonly recordCount: number\n}\n\n/**\n * Identities discoverable from one `supervise({ runDir })` directory without\n * already knowing the root node or coordination run id stored inside it.\n */\nexport interface DurableSupervisionDiscovery {\n readonly runDir: string\n readonly spawnJournalPath: string\n readonly coordinationLogPath: string\n readonly roots: readonly NodeId[]\n /** `at` from each top-level root's `begin` record, index-aligned with `roots`. */\n readonly rootsBegunAt: readonly (string | null)[]\n readonly coordinationStreams: readonly DurableCoordinationStreamIdentity[]\n}\n\ntype SpawnJournalIdentityRecord = {\n readonly kind?: unknown\n readonly root?: unknown\n readonly at?: unknown\n readonly event?: unknown\n}\n\ntype CoordinationIdentityRecord = {\n readonly runId?: unknown\n readonly ownerId?: unknown\n}\n\n/**\n * Discover the stable identities recorded by Runtime's durable supervision\n * files. This is the developer-facing first step before calling\n * `FileSpawnJournal.loadTree(root)`, `loadSpawnForest(journal, root)`, or\n * `FileCoordinationLog.load(runId, ownerId)`.\n *\n * Missing files produce empty collections. A malformed committed JSONL record\n * still fails loud through the same parser used by the runtime; a torn final\n * append is ignored because it was never acknowledged as committed.\n */\nexport async function discoverDurableSupervisionRun(\n runDir: string,\n): Promise<DurableSupervisionDiscovery> {\n if (typeof runDir !== 'string' || runDir.trim().length === 0) {\n throw new TypeError('discoverDurableSupervisionRun: runDir must be a non-empty string')\n }\n\n const canonicalRunDir = resolve(runDir)\n const spawnJournalPath = `${canonicalRunDir}/spawn-journal.jsonl`\n const coordinationLogPath = `${canonicalRunDir}/coordination-log.jsonl`\n const allRoots = new Set<NodeId>()\n const nestedRoots = new Set<NodeId>()\n const rootsBegunAt = new Map<NodeId, string | null>()\n for await (const record of readCommittedJsonLines<SpawnJournalIdentityRecord>(spawnJournalPath, {\n allowMissing: true,\n })) {\n if (record.kind === 'begin') {\n if (typeof record.root !== 'string' || record.root.length === 0) {\n throw new Error(`${spawnJournalPath}: begin record has no non-empty string root identity`)\n }\n allRoots.add(record.root as NodeId)\n rootsBegunAt.set(record.root as NodeId, typeof record.at === 'string' ? record.at : null)\n continue\n }\n if (record.kind !== 'event') continue\n const event = record.event\n if (!isRecord(event) || event.kind !== 'spawned') continue\n if (!Object.hasOwn(event, 'ownedTreeRoot')) continue\n if (typeof event.ownedTreeRoot !== 'string' || event.ownedTreeRoot.length === 0) {\n throw new Error(\n `${spawnJournalPath}: spawned event ownedTreeRoot must be a non-empty string when present`,\n )\n }\n nestedRoots.add(event.ownedTreeRoot as NodeId)\n }\n\n const streams = new Map<\n string,\n { owners: Set<string>; unscopedRecords: number; recordCount: number }\n >()\n for await (const record of readCommittedJsonLines<CoordinationIdentityRecord>(\n coordinationLogPath,\n { allowMissing: true },\n )) {\n if (typeof record.runId !== 'string' || record.runId.length === 0) {\n throw new Error(`${coordinationLogPath}: record has no non-empty string runId identity`)\n }\n const stream = streams.get(record.runId) ?? {\n owners: new Set<string>(),\n unscopedRecords: 0,\n recordCount: 0,\n }\n stream.recordCount += 1\n if (record.ownerId === undefined) {\n stream.unscopedRecords += 1\n } else if (typeof record.ownerId === 'string' && record.ownerId.length > 0) {\n stream.owners.add(record.ownerId)\n } else {\n throw new Error(`${coordinationLogPath}: ownerId must be a non-empty string when present`)\n }\n streams.set(record.runId, stream)\n }\n\n const coordinationStreams = [...streams.entries()]\n .sort(([left], [right]) => compareText(left, right))\n .map(([runId, stream]) =>\n Object.freeze({\n runId,\n ownerIds: Object.freeze([...stream.owners].sort(compareText)),\n unscopedRecords: stream.unscopedRecords,\n recordCount: stream.recordCount,\n }),\n )\n\n const roots = [...allRoots].filter((root) => !nestedRoots.has(root)).sort(compareText)\n return Object.freeze({\n runDir: canonicalRunDir,\n spawnJournalPath,\n coordinationLogPath,\n roots: Object.freeze(roots),\n rootsBegunAt: Object.freeze(roots.map((root) => rootsBegunAt.get(root) ?? null)),\n coordinationStreams: Object.freeze(coordinationStreams),\n })\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA8FA,MAAM,UAAU,IAAI,YAAY;AAEhC,SAAS,WAAW,OAAoC;CACtD,OAAO,QAAQ,OAAO,GAAG,KAAK,UAAU,KAAK,EAAE,GAAG;AACpD;AAEA,SAAS,WAAW,SAAiB,MAAsC;CACzE,IAAI,MAAM,QAAQ,MAAM,SAAS,IAAI;MAChC,QAAQ,MAAM,OAAO;AAC5B;;;;;;;;;AAUA,eAAe,mBAAmB,OAAiC;CACjE,IAAI,EAAE,iBAAiB,WACrB,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CAG9D,MAAM,SAAS,QAAQ,MAAM;CAC7B,IAAI;EACF,MAAM,OAAO,MAAM,MAAM,MAAM,CAAC,CAAC,KAAK;EACtC,IAAI,CAAC,KAAK,KAAK,GAAG,OAAO;EACzB,IAAI;GACF,MAAM,OAAO,KAAK,MAAM,IAAI;GAI5B,MAAM,SACJ,OAAO,KAAK,UAAU,YAAY,KAAK,UAAU,OAAO,KAAK,MAAM,UAAU,KAAK;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ACH;CAEF,MAAM,QAAQ,CAAC,GAAG,QAAQ,CAAC,CAAC,QAAQ,SAAS,CAAC,YAAY,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,WAAW;CACrF,OAAO,OAAO,OAAO;EACnB,QAAQ;EACR;EACA;EACA,OAAO,OAAO,OAAO,KAAK;EAC1B,cAAc,OAAO,OAAO,MAAM,KAAK,SAAS,aAAa,IAAI,IAAI,KAAK,IAAI,CAAC;EAC/E,qBAAqB,OAAO,OAAO,mBAAmB;CACxD,CAAC;AACH;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,YAAY,MAAc,OAAuB;CACxD,OAAO,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAChD"}
|
|
1
|
+
{"version":3,"file":"durable.js","names":["errorMessage","delay"],"sources":["../src/durable/chat-engine.ts","../src/durable/execution-handle.ts","../src/durable/observer-journal.ts","../src/durable/observer-projection.ts","../src/durable/settle-record.ts","../src/durable/pursuit-versions.ts","../src/durable/run-fork.ts","../src/durable/run-lock.ts","../src/durable/supervise-pursuit.ts","../src/durable/supervision-discovery.ts"],"sourcesContent":["/**\n * `handleChatTurn` is a framework-neutral chat-turn HTTP orchestrator.\n * Owns the NDJSON `ChatStreamEvent` line protocol, the `session.run.*`\n * lifecycle vocabulary, and the persist / post-process / trace-flush\n * hook order. Returns a `ReadableStream` body the product hands to its\n * platform `Response`.\n *\n * Sandbox owns long-running execution, reconnect, and replay.\n * The producer this engine wraps already speaks that protocol; this\n * engine frames the events and orders product callbacks.\n *\n * Hooks (`ChatTurnHooks`):\n * - `produce`: build the backend event stream\n * - `persistAssistantMessage`: write the assistant turn to the product DB\n * - `onTurnComplete?`: post-process proposals, citations, and similar work\n * - `onEvent?`: send each event to another consumer\n * - `transformFinalText?`: transform text before persistence\n * - `traceFlush?`: let `waitUntil` keep the worker alive for export\n *\n * Framework neutrality: takes already-resolved values (`identity` tuple,\n * a `waitUntil`), never a `Request` or a `Context`. The product's thin\n * route adapter does auth + parse + access-control, then calls\n * `handleChatTurn(...)` and returns `result.body` as its platform `Response`.\n */\n\n/** The NDJSON line protocol every product chat client already speaks. */\nexport interface ChatStreamEvent {\n type: string\n data?: Record<string, unknown>\n}\n\n/** Identity of a chat turn. `tenantId` is the workspace id for workspace-\n * scoped products and the user id for session-scoped products. */\nexport interface ChatTurnIdentity {\n tenantId: string\n /** Thread / session id. */\n sessionId: string\n userId: string\n /** Monotonic 0-based turn index within the session. */\n turnIndex: number\n}\n\n/** The live side of a turn returned by the product's `produce` hook. */\nexport interface ChatTurnProducer<TEvent extends ChatStreamEvent = ChatStreamEvent> {\n /** The turn's events. The engine emits completion after persistence. */\n stream: AsyncGenerator<TEvent, void, unknown>\n /** The turn's final assistant text. Read once, after `stream` drains. */\n finalText(): string\n}\n\n/** Product callbacks invoked while one chat turn runs. */\nexport interface ChatTurnHooks {\n /** Build the backend stream. The engine forwards nonterminal events and\n * reads `finalText()` once the stream drains. Reported errors fail the turn. */\n produce(): ChatTurnProducer\n /** Persist the assistant message to the product's own store. Called\n * once, after drain, with the assembled (transform-applied) text. */\n persistAssistantMessage(input: { identity: ChatTurnIdentity; finalText: string }): Promise<void>\n /** Optional post-processing for proposals, citations, or credit metering.\n * Errors are logged without failing a turn that already streamed. */\n onTurnComplete?(input: { identity: ChatTurnIdentity; finalText: string }): Promise<void>\n /** Optional per-event side channel, such as a Durable Object broadcast.\n * Runs for every emitted event, including the lifecycle envelope.\n * Errors are logged without breaking the chat stream. */\n onEvent?(event: ChatStreamEvent): void | Promise<void>\n /** Optional pre-persist transform of the final text (e.g. PII\n * redaction). Affects only what is persisted; the live stream is\n * never altered. */\n transformFinalText?(text: string): string | Promise<string>\n /** Optional trace flush. Handed to `waitUntil` so the worker stays alive\n * until export completes. */\n traceFlush?(): Promise<void>\n}\n\n/** Inputs for one streamed product chat turn. */\nexport interface RunChatTurnInput {\n identity: ChatTurnIdentity\n hooks: ChatTurnHooks\n /** Worker liveness hook. When omitted, trace flush is awaited inline\n * before the stream closes. */\n waitUntil?: (p: Promise<unknown>) => void\n /** Structured logger for swallowed hook errors. Defaults to\n * `console.error` so failures surface without product wiring. */\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** HTTP response values returned for one chat turn. */\nexport interface ChatTurnResult {\n /** NDJSON body to return as the platform `Response` body. */\n body: ReadableStream<Uint8Array>\n /** Content type for the response. */\n contentType: 'application/x-ndjson'\n}\n\nconst encoder = new TextEncoder()\n\nfunction encodeLine(event: ChatStreamEvent): Uint8Array {\n return encoder.encode(`${JSON.stringify(event)}\\n`)\n}\n\nfunction defaultLog(message: string, meta?: Record<string, unknown>): void {\n if (meta) console.error(message, meta)\n else console.error(message)\n}\n\n/**\n * Preserve the useful part of a thrown HTTP Response at the stream boundary.\n *\n * Product routes commonly throw a typed Response for an upstream failure. A\n * Response is not an Error, so String(response) produces the unusable\n * \"[object Response]\" and hides the status that decides the next action.\n * Read a clone so the caller's response body remains available to its owner.\n */\nasync function thrownErrorMessage(error: unknown): Promise<string> {\n if (!(error instanceof Response)) {\n return error instanceof Error ? error.message : String(error)\n }\n\n const prefix = `HTTP ${error.status}`\n try {\n const text = await error.clone().text()\n if (!text.trim()) return prefix\n try {\n const body = JSON.parse(text) as {\n error?: { code?: unknown; message?: unknown } | string\n message?: unknown\n }\n const nested =\n typeof body.error === 'object' && body.error !== null ? body.error.message : body.error\n const message =\n typeof nested === 'string'\n ? nested\n : typeof body.message === 'string'\n ? body.message\n : undefined\n if (message) return `${prefix}: ${message.slice(0, 500)}`\n } catch {\n // Fall through to the status. Arbitrary upstream HTML or text is not a\n // stable product error contract and should not be copied into a chat.\n }\n } catch {\n // A consumed or unavailable body still has a useful HTTP status.\n }\n return prefix\n}\n\n/**\n * Run one chat turn. Returns immediately with a `ReadableStream` body;\n * execution starts while the stream is constructed. Backend\n * failures surface as `error` + `session.run.failed` events.\n */\nexport function handleChatTurn(input: RunChatTurnInput): ChatTurnResult {\n const log = input.log ?? defaultLog\n const { identity, hooks } = input\n\n const body = new ReadableStream<Uint8Array>({\n start: async (controller) => {\n const emit = async (event: ChatStreamEvent): Promise<void> => {\n controller.enqueue(encodeLine(event))\n if (hooks.onEvent) {\n try {\n await hooks.onEvent(event)\n } catch (err) {\n log('[chat-engine] onEvent hook threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n }\n\n try {\n await emit({\n type: 'session.run.started',\n data: {\n sessionId: identity.sessionId,\n tenantId: identity.tenantId,\n turnIndex: identity.turnIndex,\n },\n })\n\n const producer = hooks.produce()\n let failureData: Record<string, unknown> | undefined\n for await (const event of producer.stream) {\n if (event.type === 'session.run.failed') {\n if (!failureData) await emit({ type: 'error', data: event.data })\n failureData = { ...failureData, ...event.data }\n continue\n }\n if (event.type === 'error') failureData = { ...failureData, ...event.data }\n // A drained error stream is still a failed turn. Completion belongs\n // to this engine, after persistence, even when an upstream emits it.\n if (event.type === 'session.run.completed') continue\n await emit(event)\n }\n const rawFinal = producer.finalText()\n const finalText = hooks.transformFinalText\n ? await hooks.transformFinalText(rawFinal)\n : rawFinal\n\n await hooks.persistAssistantMessage({ identity, finalText })\n if (hooks.onTurnComplete) {\n try {\n await hooks.onTurnComplete({ identity, finalText })\n } catch (err) {\n log('[chat-engine] onTurnComplete threw', {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n await emit({\n type: failureData ? 'session.run.failed' : 'session.run.completed',\n data: { ...failureData, sessionId: identity.sessionId },\n })\n } catch (err) {\n const message = await thrownErrorMessage(err)\n log('[chat-engine] turn failed', { error: message })\n await emit({ type: 'error', data: { message } })\n await emit({\n type: 'session.run.failed',\n data: { sessionId: identity.sessionId, message },\n })\n } finally {\n if (hooks.traceFlush) {\n const flush = hooks.traceFlush().catch((err) =>\n log('[chat-engine] traceFlush threw', {\n error: err instanceof Error ? err.message : String(err),\n }),\n )\n if (input.waitUntil) input.waitUntil(flush)\n else await flush\n }\n controller.close()\n }\n },\n })\n\n return { body, contentType: 'application/x-ndjson' }\n}\n","/**\n * Derive a stable execution id from the run identity.\n * The same `(projectId, sessionId, turnIndex)` tuple yields the same id.\n *\n * Use the result as both `PromptOptions.executionId` and\n * `PromptOptions.turnId` on the first dispatch.\n * The execution id addresses the server-side execution for reconnect and\n * replay; the turn id makes a repeated dispatch idempotent.\n * An execution id alone does not make a repeated POST idempotent.\n *\n * Format is readable, not hashed: operators grepping orchestrator logs\n * for `gtm-agent:thread-abc:3` find the run without translating an\n * opaque id. Components are URL-encoded so delimiters inside caller ids\n * cannot collapse distinct tuples. The final id is limited to the\n * orchestrator replay route's 256-byte maximum. Execution ids are not a\n * secrecy boundary.\n *\n * Wire integration:\n * - Initial dispatch: pass the result as `executionId` and `turnId`.\n * - Stream replay: pass it as `executionId` with `lastEventId`.\n *\n * @throws `TypeError` when either string id is blank.\n * @throws `RangeError` when `turnIndex` is invalid or the result exceeds 256 bytes.\n */\nexport function deriveExecutionId(input: {\n projectId: string\n sessionId: string\n turnIndex: number\n}): string {\n if (input.projectId.trim().length === 0) {\n throw new TypeError('projectId must be a non-empty string')\n }\n if (input.sessionId.trim().length === 0) {\n throw new TypeError('sessionId must be a non-empty string')\n }\n if (!Number.isSafeInteger(input.turnIndex) || input.turnIndex < 0) {\n throw new RangeError('turnIndex must be a non-negative safe integer')\n }\n\n const executionId = [\n encodeURIComponent(input.projectId),\n encodeURIComponent(input.sessionId),\n String(input.turnIndex),\n ].join(':')\n if (executionId.length > 256) {\n throw new RangeError('derived execution id must not exceed 256 bytes')\n }\n return executionId\n}\n","import { createHash } from 'node:crypto'\nimport { resolve } from 'node:path'\nimport { detachedSnapshot } from '../runtime/supervise/snapshot'\nimport {\n type RuntimeDecisionPoint,\n type RuntimeHookEvent,\n type RuntimeHooks,\n withPursuitContext,\n} from '../runtime-hooks'\nimport { prepareJsonlAppend, readCommittedJsonLines, writeAllBytes } from './jsonl-file'\n\nexport type ObserverRecordKind = 'event' | 'decision'\n\n/**\n * One immutable record in the observer plane. `sequence` is journal order, not\n * execution order; causal/runtime order remains available on the underlying event.\n * `previousDigest` + `digest` make deletion, reordering, or mutation detectable.\n */\nexport interface ObserverRecord {\n readonly schemaVersion: 1\n readonly pursuitId: string\n readonly sequence: number\n readonly kind: ObserverRecordKind\n readonly observedAt: number\n readonly previousDigest?: string\n readonly event?: RuntimeHookEvent\n readonly decision?: RuntimeDecisionPoint\n readonly digest: string\n}\n\nexport interface ObserverJournal {\n appendEvent(event: RuntimeHookEvent): Promise<ObserverRecord>\n appendDecision(point: RuntimeDecisionPoint): Promise<ObserverRecord>\n read(): Promise<readonly ObserverRecord[]>\n hooks(): RuntimeHooks\n}\n\ntype UnsignedObserverRecord = Omit<ObserverRecord, 'digest'>\n\n/**\n * Durable, append-only third-person history for one concrete Runtime execution.\n * It consumes Runtime's existing hook stream and does not participate in execution\n * decisions. A broken observer therefore cannot change what an agent is allowed to do.\n *\n * The write discipline deliberately matches `FileSpawnJournal`: serialized appends,\n * torn-tail recovery, short-write handling, and fsync before acknowledgement. One\n * execution owns one journal file; higher-level pursuit aggregation joins isolated\n * journals by `pursuitId` instead of making independent processes share a write head.\n */\nexport class FileObserverJournal implements ObserverJournal {\n readonly path: string\n readonly pursuitId: string\n private tail: Promise<void> = Promise.resolve()\n private initialized = false\n private sequence = 0\n private previousDigest: string | undefined\n private appendFailure: Error | undefined\n\n constructor(path: string, pursuitId: string) {\n const stableId = pursuitId.trim()\n if (stableId.length === 0) {\n throw new TypeError('FileObserverJournal: pursuitId must be non-empty')\n }\n this.path = resolve(path)\n this.pursuitId = stableId\n }\n\n hooks(): RuntimeHooks {\n return withPursuitContext(this.pursuitId, {\n onEvent: (event) => this.appendEvent(event).then(() => undefined),\n onDecisionPoint: (point) => this.appendDecision(point).then(() => undefined),\n })\n }\n\n appendEvent(event: RuntimeHookEvent): Promise<ObserverRecord> {\n return this.enqueue('event', event)\n }\n\n appendDecision(point: RuntimeDecisionPoint): Promise<ObserverRecord> {\n return this.enqueue('decision', point)\n }\n\n async read(): Promise<readonly ObserverRecord[]> {\n await this.tail\n this.assertComplete()\n const records: ObserverRecord[] = []\n const verify = observerVerifier(this.pursuitId)\n for await (const record of this.readExistingUnsafe()) {\n verify(record)\n records.push(record)\n }\n return Object.freeze(records)\n }\n\n private enqueue(\n kind: ObserverRecordKind,\n value: RuntimeHookEvent | RuntimeDecisionPoint,\n ): Promise<ObserverRecord> {\n if (value.pursuitId !== this.pursuitId) {\n return Promise.reject(\n new Error(\n `FileObserverJournal: ${kind} pursuitId ${String(value.pursuitId)} does not match ${this.pursuitId}`,\n ),\n )\n }\n\n // Other hooks receive this same input and may mutate it before queued I/O runs.\n // Detach now, not after awaiting the previous append or computing the digest.\n let snapshot: typeof value\n try {\n snapshot = detachedSnapshot(value, 'observer record')\n } catch (error) {\n return Promise.reject(error)\n }\n\n let result: ObserverRecord | undefined\n const operation = this.tail.then(async () => {\n this.assertComplete()\n try {\n await this.initialize()\n } catch (error) {\n this.appendFailure ??= toError(error)\n throw error\n }\n\n const unsigned: UnsignedObserverRecord = {\n schemaVersion: 1,\n pursuitId: this.pursuitId,\n sequence: this.sequence + 1,\n kind,\n observedAt: Date.now(),\n ...(this.previousDigest ? { previousDigest: this.previousDigest } : {}),\n ...(kind === 'event'\n ? { event: snapshot as RuntimeHookEvent }\n : { decision: snapshot as RuntimeDecisionPoint }),\n }\n const record: ObserverRecord = Object.freeze({\n ...unsigned,\n digest: observerRecordDigest(unsigned),\n })\n try {\n await this.writeRecord(record)\n } catch (error) {\n this.appendFailure ??= toError(error)\n throw error\n }\n this.sequence = record.sequence\n this.previousDigest = record.digest\n result = record\n })\n this.tail = operation.then(\n () => undefined,\n () => undefined,\n )\n return operation.then(() => {\n if (!result) throw new Error('FileObserverJournal: append completed without a record')\n return result\n })\n }\n\n private async initialize(): Promise<void> {\n if (this.initialized) return\n const verify = observerVerifier(this.pursuitId)\n let tail: ObserverRecord | undefined\n for await (const record of this.readExistingUnsafe()) {\n verify(record)\n tail = record\n }\n this.sequence = tail?.sequence ?? 0\n this.previousDigest = tail?.digest\n // Only latch after recovery + verification succeed. A transient read error or\n // corruption must never leave an instance pretending it initialized cleanly.\n this.initialized = true\n }\n\n private readExistingUnsafe(): AsyncGenerator<ObserverRecord> {\n return readCommittedJsonLines<ObserverRecord>(this.path, { allowMissing: true })\n }\n\n private async writeRecord(record: ObserverRecord): Promise<void> {\n const fs = await import('node:fs/promises')\n const path = await import('node:path')\n await fs.mkdir(path.dirname(this.path), { recursive: true })\n const needsSeparator = await prepareJsonlAppend(this.path)\n const handle = await fs.open(this.path, 'a')\n try {\n await writeAllBytes(handle, `${needsSeparator ? '\\n' : ''}${JSON.stringify(record)}\\n`)\n await handle.sync()\n } finally {\n await handle.close()\n }\n }\n\n private assertComplete(): void {\n if (!this.appendFailure) return\n throw new Error(\n 'FileObserverJournal: a prior durable append failed; observer completeness is unknown',\n { cause: this.appendFailure },\n )\n }\n}\n\n/** Verify identity, monotonic sequence, payload shape, and the complete digest chain. */\nexport function verifyObserverRecords(\n records: readonly ObserverRecord[],\n pursuitId?: string,\n): readonly ObserverRecord[] {\n const verify = observerVerifier(pursuitId)\n for (const record of records) verify(record)\n return Object.freeze([...records])\n}\n\n/** The same full chain validation is used for replay, startup and in-memory evidence. */\nfunction observerVerifier(pursuitId?: string): (record: ObserverRecord) => void {\n let previousDigest: string | undefined\n let expectedSequence = 1\n return (record) => {\n if (record.schemaVersion !== 1) throw new Error('observer journal: unsupported schemaVersion')\n if (pursuitId !== undefined && record.pursuitId !== pursuitId) {\n throw new Error(`observer journal: pursuit identity mismatch at sequence ${record.sequence}`)\n }\n if (record.sequence !== expectedSequence) {\n throw new Error(\n `observer journal: non-contiguous sequence ${record.sequence}; expected ${expectedSequence}`,\n )\n }\n if (record.previousDigest !== previousDigest) {\n throw new Error(`observer journal: digest-chain break at sequence ${record.sequence}`)\n }\n if ((record.kind === 'event') === (record.event === undefined)) {\n throw new Error(`observer journal: invalid event payload at sequence ${record.sequence}`)\n }\n if ((record.kind === 'decision') === (record.decision === undefined)) {\n throw new Error(`observer journal: invalid decision payload at sequence ${record.sequence}`)\n }\n if (record.event !== undefined && record.event.pursuitId !== record.pursuitId) {\n throw new Error(\n `observer journal: nested event pursuit mismatch at sequence ${record.sequence}`,\n )\n }\n if (record.decision !== undefined && record.decision.pursuitId !== record.pursuitId) {\n throw new Error(\n `observer journal: nested decision pursuit mismatch at sequence ${record.sequence}`,\n )\n }\n const { digest, ...unsigned } = record\n const expected = observerRecordDigest(unsigned)\n if (digest !== expected) {\n throw new Error(`observer journal: digest mismatch at sequence ${record.sequence}`)\n }\n previousDigest = digest\n expectedSequence += 1\n }\n}\n\n/** Compute the canonical SHA-256 digest for an unsigned observer record. */\nexport function observerRecordDigest(record: Omit<ObserverRecord, 'digest'>): string {\n return createHash('sha256').update(JSON.stringify(record)).digest('hex')\n}\n\n/** Build the canonical durable observer hook in one call. */\nexport function createFileObserverHooks(\n path: string,\n pursuitId: string,\n): {\n readonly journal: FileObserverJournal\n readonly hooks: RuntimeHooks\n} {\n const journal = new FileObserverJournal(path, pursuitId)\n return { journal, hooks: journal.hooks() }\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error))\n}\n","import type {\n BudgetOverspend,\n BudgetViolation,\n ExecutionBindingReceipt,\n ProfileMaterializationReceipt,\n ProviderModelExecutionEvidence,\n RetainedExecutionState,\n RetainedPendingCause,\n Spend,\n SpendChannel,\n SpendGap,\n WorkerTraceEvidence,\n} from '../runtime/supervise/types'\nimport { addSpend, cloneSpend, zeroSpend } from '../runtime/util'\nimport type { RuntimeDecisionKind, RuntimeHookTarget } from '../runtime-hooks'\nimport { type ObserverRecord, verifyObserverRecords } from './observer-journal'\n\n/**\n * One settled projection status, shared by runs and nodes. `down` is the journal's own word for a\n * failure (a settlement is journaled as `kind: 'down'`, cancellation included), so a consumer can\n * join run rows to node rows on `status` and read one failure population instead of two.\n */\nexport type PursuitStatus = 'running' | 'done' | 'down'\n\n/**\n * Where a node's dollar figure came from. `reported` = a provider billed all of it; `estimated` =\n * a model catalog priced all of it; `partial` = a provider billed part and a catalog priced the\n * rest; `unknown` = nothing priced it, so `usd` is a floor and never the cost.\n */\nexport type PursuitCostProvenance = 'reported' | 'estimated' | 'partial' | 'unknown'\n\n/**\n * One node's token usage by class. Cache and reasoning classes are absent when the provider did\n * not report them — absence is not zero. `tokensKnown` is `false` when work happened whose token\n * count no provider reported, which makes `input`/`output` a floor.\n */\nexport interface PursuitNodeUsage {\n readonly input: number\n readonly output: number\n readonly cacheRead?: number\n readonly cacheWrite?: number\n readonly reasoning?: number\n readonly tokensKnown: boolean\n}\n\n/**\n * One node's PLATFORM consumption — box wall time, the resource a subscription seat really pays.\n *\n * Kept apart from `PursuitNodeCost` because the two answer different questions and fail\n * independently: a seat run reports a truthful `$0` and real minutes, a caller-account run\n * reports real dollars and may report no minutes at all. Collapsing them into one \"spend known\"\n * figure hides which one is missing.\n *\n * Absent on a node that ran no box. `boxMinutes` absent WITH the block present says a box ran and\n * nothing measured it — a missing measurement is never a zero.\n */\nexport interface PursuitNodePlatform {\n readonly boxMinutes?: number\n /** `false` when a box ran whose time could not be closed, so `boxMinutes` is a floor. */\n readonly boxMinutesKnown: boolean\n /** `observed` = the platform billed the minutes; `estimated` = Runtime derived them from the box\n * lifetime it watched; `uncaptured` = a box ran and nothing measured it. */\n readonly provenance: 'observed' | 'estimated' | 'uncaptured'\n}\n\n/** One node's dollar cost with the provenance that decides whether it may be compared or summed. */\nexport interface PursuitNodeCost {\n readonly usd: number\n readonly usdKnown: boolean\n /** The part of `usd` a model catalog priced because no provider receipt covered it. */\n readonly usdEstimated?: number\n readonly provenance: PursuitCostProvenance\n}\n\n/**\n * One node's clock. `wallMs` is `settledAt - startedAt` and is deliberately distinct from the\n * executor-reported `spent.ms` sums, which under-report and overlap across parallel children.\n * `firstTokenAt` stays absent unless a provider reports that instant; it is never inferred from\n * `firstOutputAt`, which is when the node first reported usage for a turn.\n */\nexport interface PursuitNodeTiming {\n readonly startedAt: number\n readonly firstOutputAt?: number\n readonly firstTokenAt?: number\n readonly settledAt?: number\n readonly wallMs?: number\n}\n\n/** Where and how a node's execution was placed, read off its execution-binding receipt. */\nexport type PursuitNodePlacement = Readonly<Record<string, string | number | boolean | null>>\n\n/**\n * One run's spend counted once, and each node's own share of it. `inclusive` and the entries of\n * `exclusiveByNode` are the two views a client needs to show a tree without double counting.\n */\nexport interface PursuitRunTotals {\n /**\n * The whole run counted once. A node's settled `spent` already contains the child work its own\n * nested tree reported, so summing only the run's top-level nodes plus every node's own\n * inference counts each model call exactly once.\n */\n readonly inclusive: Spend\n /**\n * Each node's own share: its reported spend and own inference minus what its direct children\n * reported. Keyed by node id, plus the run root when the root itself metered inference. The\n * entries sum to `inclusive` by construction.\n */\n readonly exclusiveByNode: Readonly<Record<string, Spend>>\n}\n\n/**\n * One attempt at one concrete Runtime run: the stretch of `agent.run` lifecycle from a `before`\n * to the `after` or `error` that settles it. A run whose first attempt threw and whose corrected\n * attempt settled is two rows, so `error` names only the attempt that failed.\n *\n * A `before` observed while an attempt is still open does not open another: it is a process\n * that resumed the run after the previous process died without a terminal record, and the row\n * counts it in `resumeCount`. The alternative, a row per process start, would leave the killed\n * process's row `running` for the rest of history.\n */\nexport interface PursuitRunProjection {\n readonly runId: string\n /** Zero-based position of this attempt among the run's attempts, in journal order. */\n readonly attemptIndex: number\n /** How many times a process resumed this attempt after a predecessor died mid-run. */\n readonly resumeCount: number\n readonly status: PursuitStatus\n readonly settledAt?: number\n readonly error?: string\n readonly firstSequence: number\n readonly lastSequence: number\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly eventCount: number\n readonly decisionCount: number\n readonly targets: Readonly<Record<string, number>>\n readonly decisions: Readonly<Record<string, number>>\n readonly totals: PursuitRunTotals\n /** The nodes whose accounting is incomplete. Present exactly when non-empty. */\n readonly spendGaps?: ReadonlyArray<SpendGap>\n}\n\nexport interface PursuitNodeProjection {\n readonly id: string\n readonly parentId?: string\n /** Node ids are scoped to this concrete Runtime tree; `(runId,id)` is identity. */\n readonly runId: string\n readonly label?: string\n /** The runner that executed this node — the executor's own name, not a harness guess. */\n readonly runtime?: string\n readonly depth?: number\n readonly assignmentId?: string\n /** The settled sibling this node replaced, as its manager's spawn named it. Absent on a node\n * that replaced nothing. */\n readonly successorOf?: string\n readonly identity?: unknown\n readonly budget?: unknown\n readonly status: PursuitStatus\n readonly settledAt?: number\n /** The child work this node reported at settlement. Absent until a terminal record lands. */\n readonly spent?: Spend\n /** This node's OWN inference, re-homed from its nested tree. Absent when it drove no turns. */\n readonly ownInference?: Spend\n /** Absent until a spend record lands; the run's `spendGaps` then names the node. */\n readonly usage?: PursuitNodeUsage\n /** Absent until a spend record lands; the run's `spendGaps` then names the node. */\n readonly cost?: PursuitNodeCost\n /** What the node consumed on the PLATFORM. Absent on a node that ran no box. */\n readonly platform?: PursuitNodePlatform\n readonly timing?: PursuitNodeTiming\n /** The kernel-minted attempt this node's execution binding is keyed on. */\n readonly attemptId?: string\n /** The runner-native execution the node bound to: a request, session, run, process, or tree. */\n readonly execution?: { readonly kind: string; readonly id: string }\n /** The model the materialization receipt names, when the runner reported one. */\n readonly model?: string\n /** The concrete backend the profile materialized onto. */\n readonly backend?: string\n readonly placement?: PursuitNodePlacement\n /** Model-call identifiers this node's own turns reported, in order, deduplicated. */\n readonly modelCalls?: ReadonlyArray<string>\n readonly materialization?: ProfileMaterializationReceipt\n readonly executionBindings?: ReadonlyArray<ExecutionBindingReceipt>\n /** What the provider itself reported serving, and why it is unknown when it is. */\n readonly providerModel?: ProviderModelExecutionEvidence\n /** Content-addressed pointer to this node's persisted tool trace, or why there is none. */\n readonly trace?: WorkerTraceEvidence\n readonly outRef?: string\n readonly score?: number\n readonly valid?: boolean\n readonly reason?: string\n readonly infra?: boolean\n /** Recorded by Runtime on the `agent.child` payload: `'pending'` at a retained child's\n * settlement, `'released'` when root settlement destroyed its environment without recovery,\n * `'release-unconfirmed'` when a final settlement closed its slot without confirming that.\n * The status stays `down` — the split is a sibling fact, not a fourth status. A second\n * `agent.child` for one node is already how a live-recovered child flips down→done, so the\n * fold overwrites in observed order; that event's `settledAt` is the original settlement, so\n * `settledAt` and `timing` do not move. */\n readonly retainedExecution?: RetainedExecutionState\n /** Why a retained child has no accepted result; see `RetainedPendingCause`. */\n readonly retainedPendingCause?: RetainedPendingCause\n /** When a final settlement closed a retained node's slot; absent while it is `'pending'`. */\n readonly releasedAt?: number\n /** Each channel on which the settled spend exceeded the node's reservation. The status is the\n * node's own outcome: a `done` node that overspent still delivered its output. */\n readonly budgetViolation?: BudgetViolation\n readonly wait?: unknown\n readonly firstSequence: number\n readonly lastSequence: number\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly eventCount: number\n readonly turnCount: number\n}\n\nexport interface PursuitProjection {\n readonly pursuitId: string\n /** Number of records in this concrete execution journal. */\n readonly sequence: number\n /** Digest-chain tip for this concrete execution journal. */\n readonly chainTip: string\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly runs: readonly PursuitRunProjection[]\n readonly nodes: readonly PursuitNodeProjection[]\n readonly eventCount: number\n readonly decisionCount: number\n}\n\ntype MutableRun = {\n runId: string\n attemptIndex: number\n resumeCount: number\n /** Whether this attempt has seen its own `before`; an attempt a journal opens without one\n * treats the first `before` it meets as its start, not as a resume. */\n started: boolean\n status: PursuitStatus\n settledAt?: number\n error?: string\n firstSequence: number\n lastSequence: number\n firstObservedAt: number\n lastObservedAt: number\n eventCount: number\n decisionCount: number\n targets: Record<string, number>\n decisions: Record<string, number>\n /** Inference the run root drove itself, attributable to no spawned node. */\n rootInference?: Spend\n}\n\ntype MutableNode = {\n id: string\n parentId?: string\n runId: string\n /** The attempt whose process spawned this node; totals and gaps are folded per attempt. */\n attemptIndex: number\n label?: string\n runtime?: string\n depth?: number\n assignmentId?: string\n successorOf?: string\n identity?: unknown\n budget?: unknown\n status: PursuitStatus\n startedAt?: number\n settledAt?: number\n spent?: Spend\n ownInference?: Spend\n reasoningTokens?: number\n firstOutputAt?: number\n firstTokenAt?: number\n attemptId?: string\n execution?: { kind: string; id: string }\n model?: string\n backend?: string\n placement?: PursuitNodePlacement\n modelCalls: string[]\n materialization?: ProfileMaterializationReceipt\n executionBindings?: ReadonlyArray<ExecutionBindingReceipt>\n providerModel?: ProviderModelExecutionEvidence\n trace?: WorkerTraceEvidence\n outRef?: string\n score?: number\n valid?: boolean\n reason?: string\n infra?: boolean\n retainedExecution?: RetainedExecutionState\n retainedPendingCause?: RetainedPendingCause\n releasedAt?: number\n budgetViolation?: BudgetViolation\n wait?: unknown\n firstSequence: number\n lastSequence: number\n firstObservedAt: number\n lastObservedAt: number\n eventCount: number\n turnCount: number\n}\n\n/**\n * Fold one append-only execution journal into a deterministic operator projection.\n *\n * This is intentionally a READ model, not another state machine: it does not own\n * execution, cannot steer agents, and can be rebuilt from the journal at any time.\n * Projection verifies the complete hash chain first, so an operator view can never\n * silently render a mutated or reordered observer history as trustworthy state.\n *\n * Topology comes only from Runtime's canonical `agent.spawn` facts. Terminal node\n * state comes only from `agent.child`; concrete run state comes only from the root\n * `agent.run` lifecycle emitted by `supervisePursuit`, one row per attempt. Node identity is\n * scoped to the concrete Runtime run so independent trees may both contain `root:s0` without\n * aliasing, and a node belongs to the attempt that spawned it.\n *\n * Usage, cost and timing are reported at the class the runtime measured them at. A missing\n * class stays ABSENT and the run names the node in `spendGaps`; nothing here converts an\n * unmeasured channel into a zero, because a fabricated zero is indistinguishable from free work.\n */\nexport function projectPursuit(records: readonly ObserverRecord[]): PursuitProjection {\n if (records.length === 0) {\n throw new TypeError('projectPursuit: at least one observer record is required')\n }\n const pursuitId = records[0]!.pursuitId\n const verified = verifyObserverRecords(records, pursuitId)\n const attempts = new Map<string, MutableRun[]>()\n const nodes = new Map<string, MutableNode>()\n let eventCount = 0\n let decisionCount = 0\n\n for (const record of verified) {\n const observed = record.event ?? record.decision\n if (!observed) throw new Error(`projectPursuit: record ${record.sequence} has no observation`)\n const run = currentAttempt(attempts, observed.runId, record)\n run.lastSequence = record.sequence\n run.lastObservedAt = record.observedAt\n\n if (record.event) {\n eventCount += 1\n run.eventCount += 1\n increment(run.targets, record.event.target)\n projectRunActivity(run, record)\n projectSpawnNode(nodes, record, run.attemptIndex)\n projectNodeActivity(nodes, record)\n projectTurn(run, nodes, record)\n } else if (record.decision) {\n decisionCount += 1\n run.decisionCount += 1\n increment(run.decisions, record.decision.kind)\n }\n }\n\n const byAttempt = new Map<string, MutableNode[]>()\n for (const node of nodes.values()) {\n const key = attemptKey(node.runId, node.attemptIndex)\n const list = byAttempt.get(key)\n if (list) list.push(node)\n else byAttempt.set(key, [node])\n }\n\n const first = verified[0]!\n const last = verified.at(-1)!\n return Object.freeze({\n pursuitId,\n sequence: last.sequence,\n chainTip: last.digest,\n firstObservedAt: first.observedAt,\n lastObservedAt: last.observedAt,\n runs: Object.freeze(\n [...attempts.values()]\n .flat()\n .sort((a, b) => a.firstSequence - b.firstSequence || a.runId.localeCompare(b.runId))\n .map((run) => freezeRun(run, byAttempt.get(attemptKey(run.runId, run.attemptIndex)) ?? [])),\n ),\n nodes: Object.freeze(\n [...nodes.values()]\n .sort(\n (a, b) =>\n a.firstSequence - b.firstSequence ||\n a.runId.localeCompare(b.runId) ||\n a.id.localeCompare(b.id),\n )\n .map(freezeNode),\n ),\n eventCount,\n decisionCount,\n })\n}\n\nfunction attemptKey(runId: string, attemptIndex: number): string {\n return `${runId}\\u0000${attemptIndex}`\n}\n\n/**\n * The attempt a record belongs to. An `agent.run` `before` opens a new attempt when the run has\n * none or its latest attempt already settled; on an open attempt it is a resume. Every other\n * record joins the latest attempt, and a journal that never emitted `before` gets attempt 0.\n */\nfunction currentAttempt(\n attempts: Map<string, MutableRun[]>,\n runId: string,\n record: ObserverRecord,\n): MutableRun {\n const list = attempts.get(runId) ?? []\n if (list.length === 0) attempts.set(runId, list)\n const latest = list.at(-1)\n const isStart = record.event?.target === 'agent.run' && record.event.phase === 'before'\n if (latest !== undefined && (!isStart || latest.status === 'running')) {\n if (isStart) {\n if (latest.started) latest.resumeCount += 1\n latest.started = true\n }\n return latest\n }\n const created: MutableRun = {\n runId,\n attemptIndex: list.length,\n resumeCount: 0,\n started: isStart,\n status: 'running',\n firstSequence: record.sequence,\n lastSequence: record.sequence,\n firstObservedAt: record.observedAt,\n lastObservedAt: record.observedAt,\n eventCount: 0,\n decisionCount: 0,\n targets: {},\n decisions: {},\n }\n list.push(created)\n return created\n}\n\nfunction projectRunActivity(run: MutableRun, record: ObserverRecord): void {\n const event = record.event\n if (event?.target !== 'agent.run') return\n const payload = objectRecord(event.payload)\n const status = stringField(payload, 'status')\n if (event.phase === 'after' || status === 'done') {\n run.status = 'done'\n run.settledAt = record.observedAt\n return\n }\n // The `agent.run` hook payload spells a failure `failed`; the projection spells every\n // settled failure `down`, the journal's word, so run and node rows join on one vocabulary.\n if (event.phase !== 'error' && status !== 'failed') return\n run.status = 'down'\n run.settledAt = record.observedAt\n const error = stringField(payload, 'error')\n if (error) run.error = error\n}\n\nfunction nodeKey(runId: string, nodeId: string): string {\n return `${runId}\\u0000${nodeId}`\n}\n\nfunction projectSpawnNode(\n nodes: Map<string, MutableNode>,\n record: ObserverRecord,\n attemptIndex: number,\n): void {\n const event = record.event\n if (event?.target !== 'agent.spawn') return\n const payload = objectRecord(event.payload)\n const childId = stringField(payload, 'childId')\n if (!childId) return\n const key = nodeKey(event.runId, childId)\n const existing = nodes.get(key)\n if (existing) {\n existing.lastSequence = record.sequence\n existing.lastObservedAt = record.observedAt\n existing.eventCount += 1\n return\n }\n const label = stringField(payload, 'label')\n const runtime = stringField(payload, 'runtime')\n const depth = numberField(payload, 'depth')\n const assignmentId = stringField(payload, 'assignmentId')\n const successorOf = stringField(payload, 'successorOf')\n const attemptId = stringField(payload, 'attemptId')\n const startedAt = numberField(payload, 'startedAt')\n nodes.set(key, {\n id: childId,\n ...(event.parentId ? { parentId: event.parentId } : {}),\n runId: event.runId,\n attemptIndex,\n ...(label ? { label } : {}),\n ...(runtime ? { runtime } : {}),\n ...(depth !== undefined ? { depth } : {}),\n ...(assignmentId ? { assignmentId } : {}),\n ...(successorOf ? { successorOf } : {}),\n ...(attemptId ? { attemptId } : {}),\n // A spawn that predates the `startedAt` fact falls back to when the record was observed:\n // the spawn event is emitted synchronously with the spawn, so the two agree to the ms.\n startedAt: startedAt ?? record.observedAt,\n ...(payload && Object.hasOwn(payload, 'identity') ? { identity: payload.identity } : {}),\n ...(payload && Object.hasOwn(payload, 'budget') ? { budget: payload.budget } : {}),\n status: 'running',\n modelCalls: [],\n firstSequence: record.sequence,\n lastSequence: record.sequence,\n firstObservedAt: record.observedAt,\n lastObservedAt: record.observedAt,\n eventCount: 1,\n turnCount: 0,\n })\n}\n\nfunction projectNodeActivity(nodes: Map<string, MutableNode>, record: ObserverRecord): void {\n const event = record.event\n if (event === undefined) return\n if (event.target === 'agent.spawn') return\n const payload = objectRecord(event.payload)\n const nodeId =\n stringField(payload, 'childId') ??\n stringField(payload, 'nodeId') ??\n stringField(payload, 'workerId')\n if (!nodeId) return\n const node = nodes.get(nodeKey(event.runId, nodeId))\n if (!node) return\n node.lastSequence = record.sequence\n node.lastObservedAt = record.observedAt\n node.eventCount += 1\n\n if (event.target !== 'agent.child') return\n const status = stringField(payload, 'status')\n if (status !== 'done' && status !== 'down') return\n node.status = status\n node.settledAt = numberField(payload, 'settledAt') ?? record.observedAt\n const startedAt = numberField(payload, 'startedAt')\n if (startedAt !== undefined) node.startedAt = startedAt\n if (payload && Object.hasOwn(payload, 'spent')) node.spent = spendField(payload, 'spent')\n const metered = spendField(payload, 'metered')\n if (metered)\n node.ownInference = node.ownInference ? addSpend(node.ownInference, metered) : metered\n const runtime = stringField(payload, 'runtime')\n if (runtime) node.runtime = runtime\n const outRef = stringField(payload, 'outRef')\n if (outRef) node.outRef = outRef\n const score = numberField(payload, 'score')\n if (score !== undefined) node.score = score\n const valid = booleanField(payload, 'valid')\n if (valid !== undefined) node.valid = valid\n const reason = stringField(payload, 'reason')\n if (reason) node.reason = reason\n const infra = booleanField(payload, 'infra')\n if (infra !== undefined) node.infra = infra\n const retained = stringField(payload, 'retainedExecution')\n if (retained === 'pending' || retained === 'released' || retained === 'release-unconfirmed') {\n node.retainedExecution = retained\n }\n const cause = stringField(payload, 'retainedPendingCause')\n if (\n cause === 'unobservable' ||\n cause === 'provider-contract' ||\n cause === 'request-rejected' ||\n cause === 'transport' ||\n cause === 'nested-recovery'\n )\n node.retainedPendingCause = cause\n const releasedAt = numberField(payload, 'releasedAt')\n if (releasedAt !== undefined) node.releasedAt = releasedAt\n const budgetViolation = budgetViolationField(payload)\n if (budgetViolation) node.budgetViolation = budgetViolation\n if (payload && Object.hasOwn(payload, 'wait')) node.wait = payload.wait\n attachSettlementEvidence(node, payload)\n}\n\n/**\n * Read the receipts a settlement carries. Each is taken as reported: an `unknown` receipt keeps\n * its `status` and `reason` so a client can show WHY a model or backend is missing instead of\n * showing nothing, and a receipt that never landed leaves every derived field absent.\n */\nfunction attachSettlementEvidence(\n node: MutableNode,\n payload: Record<string, unknown> | undefined,\n): void {\n const providerModel = payload?.providerModel as ProviderModelExecutionEvidence | undefined\n if (providerModel && typeof providerModel === 'object') node.providerModel = providerModel\n const trace = payload?.trace as WorkerTraceEvidence | undefined\n if (trace && typeof trace === 'object') node.trace = trace\n const bindings = payload?.executionBindings\n if (Array.isArray(bindings) && bindings.length > 0) {\n node.executionBindings = bindings as ReadonlyArray<ExecutionBindingReceipt>\n const known = bindings.find(\n (binding): binding is Extract<ExecutionBindingReceipt, { status: 'known' }> =>\n objectRecord(binding)?.status === 'known',\n )\n if (known) {\n node.placement = known.descriptor\n node.attemptId ??= known.attemptId\n }\n }\n const receipt = payload?.materialization as ProfileMaterializationReceipt | undefined\n if (!receipt || typeof receipt !== 'object') return\n node.materialization = receipt\n if (receipt.status !== 'known') return\n node.backend = receipt.backend\n if (receipt.model.status === 'known') node.model = receipt.model.id\n node.execution = { kind: receipt.execution.kind, id: receipt.execution.id }\n}\n\n/**\n * Fold one metered turn onto whoever drove it. `agent.turn` names its subject in `parentId` — the\n * node making the call — not in the payload, because the caller IS the subject. A turn the run\n * root drove belongs to no spawned node and lands on the run instead, so the run's totals stay\n * complete without inventing a node for the root.\n */\nfunction projectTurn(\n run: MutableRun,\n nodes: Map<string, MutableNode>,\n record: ObserverRecord,\n): void {\n const event = record.event\n if (event?.target !== 'agent.turn') return\n const payload = objectRecord(event.payload)\n const spend = spendField(payload, 'spend')\n const subject = event.parentId\n if (subject === undefined) return\n const node = nodes.get(nodeKey(event.runId, subject))\n if (!node) {\n if (!spend) return\n run.rootInference = run.rootInference ? addSpend(run.rootInference, spend) : spend\n return\n }\n node.turnCount += 1\n node.lastSequence = record.sequence\n node.lastObservedAt = record.observedAt\n if (spend) {\n node.ownInference = node.ownInference ? addSpend(node.ownInference, spend) : spend\n node.firstOutputAt ??= record.observedAt\n }\n const reasoning = numberField(payload, 'reasoningTokens')\n if (reasoning !== undefined) node.reasoningTokens = (node.reasoningTokens ?? 0) + reasoning\n const firstTokenAt = numberField(payload, 'firstTokenAt')\n if (firstTokenAt !== undefined) node.firstTokenAt ??= firstTokenAt\n const model = stringField(payload, 'model')\n if (model) node.model ??= model\n const callId = stringField(payload, 'callId')\n if (callId && !node.modelCalls.includes(callId)) node.modelCalls.push(callId)\n}\n\n/**\n * A node's whole reported cost: the child work its settlement reported plus the inference it drove\n * itself. `undefined` when neither landed — the run's `spendGaps` then names the node, so an\n * unaccounted node is visible instead of reading as free.\n */\nfunction nodeTotal(node: MutableNode): Spend | undefined {\n if (node.spent && node.ownInference) return addSpend(node.spent, node.ownInference)\n if (node.spent) return cloneSpend(node.spent)\n if (node.ownInference) return cloneSpend(node.ownInference)\n return undefined\n}\n\n/**\n * The run counted once, and each node's own share of it.\n *\n * A settled node's `spent` already contains the child work its nested tree reported, so summing\n * every node would count a driver's descendants twice. Inclusive therefore sums only the run's\n * TOP-LEVEL nodes — those whose parent is not another node of this run — plus the root's own\n * turns. Exclusive subtracts each node's direct children from its own total, which telescopes:\n * the exclusive entries sum back to `inclusive` exactly.\n */\nfunction runTotals(run: MutableRun, nodes: readonly MutableNode[]): PursuitRunTotals {\n const present = new Set(nodes.map((node) => node.id))\n const children = new Map<string, MutableNode[]>()\n for (const node of nodes) {\n if (node.parentId === undefined || !present.has(node.parentId)) continue\n const list = children.get(node.parentId)\n if (list) list.push(node)\n else children.set(node.parentId, [node])\n }\n const exclusiveByNode: Record<string, Spend> = {}\n let inclusive = run.rootInference ? cloneSpend(run.rootInference) : zeroSpend()\n if (run.rootInference) exclusiveByNode[run.runId] = cloneSpend(run.rootInference)\n for (const node of nodes) {\n const total = nodeTotal(node)\n if (total === undefined) continue\n if (node.parentId === undefined || !present.has(node.parentId)) {\n inclusive = addSpend(inclusive, total)\n }\n let exclusive = total\n for (const child of children.get(node.id) ?? []) {\n const childTotal = nodeTotal(child)\n if (childTotal !== undefined) exclusive = subtractSpend(exclusive, childTotal)\n }\n exclusiveByNode[node.id] = exclusive\n }\n return Object.freeze({\n inclusive: Object.freeze(inclusive),\n exclusiveByNode: Object.freeze(exclusiveByNode),\n })\n}\n\n/**\n * Remove a child's reported total from its parent's. Per channel, never below zero: a parent whose\n * executor reported less than its children did is a reporting gap, and a negative exclusive share\n * would be a fabricated number rather than a measurement.\n */\nfunction subtractSpend(a: Spend, b: Spend): Spend {\n const tokens = { ...a.tokens }\n tokens.input = Math.max(0, tokens.input - b.tokens.input)\n tokens.output = Math.max(0, tokens.output - b.tokens.output)\n if (a.tokens.cacheRead !== undefined)\n tokens.cacheRead = Math.max(0, a.tokens.cacheRead - (b.tokens.cacheRead ?? 0))\n if (a.tokens.cacheWrite !== undefined)\n tokens.cacheWrite = Math.max(0, a.tokens.cacheWrite - (b.tokens.cacheWrite ?? 0))\n if (a.tokens.freshInput !== undefined)\n tokens.freshInput = Math.max(0, a.tokens.freshInput - (b.tokens.freshInput ?? 0))\n return {\n iterations: Math.max(0, a.iterations - b.iterations),\n tokens,\n ...(a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: Math.max(0, a.usd - b.usd),\n ...(a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {}),\n ...(a.usdEstimated !== undefined\n ? { usdEstimated: Math.max(0, a.usdEstimated - (b.usdEstimated ?? 0)) }\n : {}),\n ms: Math.max(0, a.ms - b.ms),\n }\n}\n\n/** The nodes of one run whose accounting is incomplete, in the vocabulary the supervisor already\n * uses: `never-settled` = no terminal record, so every channel is unaccounted; `unreported` = a\n * record landed with a channel the provider did not report, so that channel is a floor. */\nfunction runSpendGaps(nodes: readonly MutableNode[]): SpendGap[] {\n const gaps: SpendGap[] = []\n for (const node of nodes) {\n const label = node.label\n if (node.status === 'running') {\n gaps.push({\n id: node.id,\n ...(label !== undefined ? { label } : {}),\n kind: 'never-settled',\n channels: ['tokens', 'usd'],\n })\n continue\n }\n const total = nodeTotal(node)\n const channels: SpendChannel[] = []\n if (total === undefined || total.tokensKnown === false) channels.push('tokens')\n if (total === undefined || total.usdKnown === false) channels.push('usd')\n if (channels.length === 0) continue\n gaps.push({\n id: node.id,\n ...(label !== undefined ? { label } : {}),\n kind: 'unreported',\n channels,\n })\n }\n return gaps\n}\n\nfunction usageOf(total: Spend, reasoning: number | undefined): PursuitNodeUsage {\n return {\n input: total.tokens.input,\n output: total.tokens.output,\n ...(total.tokens.cacheRead !== undefined ? { cacheRead: total.tokens.cacheRead } : {}),\n ...(total.tokens.cacheWrite !== undefined ? { cacheWrite: total.tokens.cacheWrite } : {}),\n ...(reasoning !== undefined ? { reasoning } : {}),\n tokensKnown: total.tokensKnown !== false && total.tokens.tokensKnown !== false,\n }\n}\n\nfunction costOf(total: Spend): PursuitNodeCost {\n const usdKnown = total.usdKnown !== false\n const estimated = total.usdEstimated\n const provenance: PursuitCostProvenance = usdKnown\n ? estimated === undefined || estimated === 0\n ? 'reported'\n : 'partial'\n : estimated === undefined\n ? 'unknown'\n : estimated >= total.usd\n ? 'estimated'\n : 'partial'\n return {\n usd: total.usd,\n usdKnown,\n ...(estimated !== undefined ? { usdEstimated: estimated } : {}),\n provenance,\n }\n}\n\n/** The platform block, or nothing at all when the node's spend names no box channel. */\nfunction platformOf(total: Spend): PursuitNodePlatform | undefined {\n if (total.boxMinutesProvenance === undefined) return undefined\n return {\n ...(total.boxMinutes !== undefined ? { boxMinutes: total.boxMinutes } : {}),\n boxMinutesKnown: total.boxMinutesKnown === true,\n provenance: total.boxMinutesProvenance,\n }\n}\n\nfunction timingOf(node: MutableNode): PursuitNodeTiming | undefined {\n if (node.startedAt === undefined) return undefined\n return {\n startedAt: node.startedAt,\n ...(node.firstOutputAt !== undefined ? { firstOutputAt: node.firstOutputAt } : {}),\n ...(node.firstTokenAt !== undefined ? { firstTokenAt: node.firstTokenAt } : {}),\n ...(node.settledAt !== undefined ? { settledAt: node.settledAt } : {}),\n ...(node.settledAt !== undefined\n ? { wallMs: Math.max(0, node.settledAt - node.startedAt) }\n : {}),\n }\n}\n\nfunction freezeRun(run: MutableRun, nodes: readonly MutableNode[]): PursuitRunProjection {\n const gaps = runSpendGaps(nodes)\n const { rootInference: _rootInference, started: _started, ...rest } = run\n return Object.freeze({\n ...rest,\n targets: Object.freeze({ ...run.targets }),\n decisions: Object.freeze({ ...run.decisions }),\n totals: runTotals(run, nodes),\n ...(gaps.length > 0 ? { spendGaps: Object.freeze(gaps) } : {}),\n })\n}\n\nfunction freezeNode(node: MutableNode): PursuitNodeProjection {\n const {\n modelCalls,\n reasoningTokens,\n startedAt: _startedAt,\n attemptIndex: _attemptIndex,\n ...rest\n } = node\n const total = nodeTotal(node)\n const timing = timingOf(node)\n return Object.freeze({\n ...rest,\n ...(modelCalls.length > 0 ? { modelCalls: Object.freeze([...modelCalls]) } : {}),\n ...(total !== undefined ? { usage: usageOf(total, reasoningTokens), cost: costOf(total) } : {}),\n ...(total !== undefined && platformOf(total) !== undefined\n ? { platform: platformOf(total) }\n : {}),\n ...(timing !== undefined ? { timing } : {}),\n })\n}\n\nfunction increment(\n target: Record<string, number>,\n key: RuntimeHookTarget | RuntimeDecisionKind,\n): void {\n target[key] = (target[key] ?? 0) + 1\n}\n\nfunction objectRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\n/** Read a journaled `Spend` without trusting the wire: a record missing the conserved channels is\n * not a zero-cost turn, it is an unparseable one, and it must not enter a total. */\nfunction spendField(value: Record<string, unknown> | undefined, key: string): Spend | undefined {\n const field = objectRecord(value?.[key])\n if (!field) return undefined\n const tokens = objectRecord(field.tokens)\n if (typeof field.usd !== 'number' || !Number.isFinite(field.usd)) return undefined\n if (!tokens || typeof tokens.input !== 'number' || typeof tokens.output !== 'number') {\n return undefined\n }\n return cloneSpend(field as unknown as Spend)\n}\n\n/** Read a journaled overspend without trusting the wire: one malformed channel drops the record,\n * so an unparseable entry is never reported as an overspend of some size. */\nfunction budgetViolationField(\n value: Record<string, unknown> | undefined,\n): BudgetViolation | undefined {\n const overspent = objectRecord(value?.budgetViolation)?.overspent\n if (!Array.isArray(overspent) || overspent.length === 0) return undefined\n const entries: BudgetOverspend[] = []\n for (const raw of overspent) {\n const entry = objectRecord(raw)\n const channel = stringField(entry, 'channel')\n const reserved = numberField(entry, 'reserved')\n const spent = numberField(entry, 'spent')\n if (channel === undefined || reserved === undefined || spent === undefined) return undefined\n entries.push({ channel: channel as BudgetOverspend['channel'], reserved, spent })\n }\n return { overspent: entries }\n}\n\nfunction stringField(value: Record<string, unknown> | undefined, key: string): string | undefined {\n const field = value?.[key]\n return typeof field === 'string' && field.length > 0 ? field : undefined\n}\n\nfunction numberField(value: Record<string, unknown> | undefined, key: string): number | undefined {\n const field = value?.[key]\n return typeof field === 'number' && Number.isFinite(field) ? field : undefined\n}\n\nfunction booleanField(\n value: Record<string, unknown> | undefined,\n key: string,\n): boolean | undefined {\n const field = value?.[key]\n return typeof field === 'boolean' ? field : undefined\n}\n","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, 2026-09-06): 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 with\n * `O_EXCL`, fsynced, and never replaced: a second settle in the same directory is refused before\n * any compute. `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`\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. */\nexport class 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 `runDir/result.json` 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 `runDir/failure.json` 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","/**\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 { access, readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport {\n developmentClaim,\n incumbent,\n openSearchLedger,\n parseSearchLedgerLine,\n runSearch,\n type SearchArtifactCodec,\n type SearchArtifactRef,\n type SearchAttemptAccounting,\n type SearchAudit,\n type SearchCellResult,\n type SearchCellSettledEvent,\n type SearchCloseReason,\n type SearchExecutionIdentity,\n type SearchExecutor,\n type SearchHistoryReceipt,\n type SearchNode,\n type SearchProposerPort,\n SearchRecorder,\n type SearchSourceRef,\n type SearchTaskOutcome,\n uniform,\n} from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfile,\n type AgentProfileDiff,\n agentProfileSchema,\n canonicalAgentProfileDigest,\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 { type CheckVerdict, failedItems } from '../runtime/supervise/continuation'\nimport { authoredProfileDigest } from '../runtime/supervise/materialization'\nimport { superviseRootProfile } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { SpawnEvent, Spend, SupervisedResult } from '../runtime/supervise/types'\nimport { contentAddress } from './content-address'\nimport { isNoEntError } from './jsonl-file'\nimport { FileObserverJournal } from './observer-journal'\nimport { projectPursuit } from './observer-projection'\nimport type { PursuitFork } from './run-fork'\nimport { parseSettleRecord, readSettleRecord, SETTLE_RECORD_FILE } from './settle-record'\nimport { FileSpawnJournal } from './spawn-journal'\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\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 /** 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/** Where `'review-of-best'` mounts a review: `inputs/review/version-<n>.md`. One review lives in\n * a profile at a time. */\nexport const REVIEW_DIR = 'inputs/review/'\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/**\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(['patience', 'maxVersions', 'maxUsd', 'deadlineMs', 'minImprovement'])\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 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 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 RunOne = (\n profile: SupervisorProfile,\n task: unknown,\n opts: SupervisePursuitOptions,\n) => Promise<SupervisedPursuitResult<SupervisedResult<unknown>>>\n\n/** A search node's artifact: a version's profile, or a change that did not apply. */\ninterface 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. */\ninterface 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/** 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 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 { judge, 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 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 = digestOf(task, 'task')\n const identity = (nodeProfile: AgentProfile): SearchExecutionIdentity => ({\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 const ledger = openSearchLedger({ path: ledgerPath, searchId })\n const opened = (await ledger.state()).header\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 const deadline =\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 const policy = incumbent({\n patience: stop.patience,\n ...(stop.minImprovement === undefined ? {} : { minImprovement: stop.minImprovement }),\n })\n const allocation = uniform()\n const recorder = await 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: identity(firstProfile),\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 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\n // Each sealed result.json is read and hashed once per call.\n const sealed = new Map<Sha256Digest, SupervisedResult<unknown>>()\n\n const codec: 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\n const executor: SearchExecutor<VersionNode> = {\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 base.budget.maxUsd === undefined\n ? { name: LANE, capacity: 1, costCap: 'estimate', cellUsd: 0 }\n : { name: LANE, capacity: 1, costCap: 'hard', cellUsd: base.budget.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 async run(work) {\n const chain = await 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, expired.signal])\n if (signal.aborted) {\n throw new RuntimeRunStateError(\n `supervisePursuit versions: version ${record.version} was not started: ${errorMessage(signal.reason)}`,\n )\n }\n await runVersion(record, parent, signal)\n }\n const { settled, byteLength } = await readVersion(record, parent)\n const verdict = await judgeVersion(settled, work.signal)\n return cellResult(settled, byteLength, verdict, work.lane)\n },\n }\n\n const proposerSource: SearchSourceRef = {\n uri:\n versions.next === 'review-of-best'\n ? `${VERSION_CHAIN_URI}.review-of-best`\n : `${VERSION_CHAIN_URI}.next`,\n revision: canonicalCandidateDigest({\n next:\n versions.next === 'review-of-best'\n ? 'review-of-best'\n : Function.prototype.toString.call(versions.next),\n }),\n }\n const proposer: SearchProposerPort<VersionNode> = {\n name: versions.next === 'review-of-best' ? '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 judgedVersions(await versionsOf())\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 parentDigest = canonicalAgentProfileDigest(parent.artifact.profile)\n let child: VersionNode\n try {\n child = {\n profile: applyExactAgentProfileDiff(\n parent.artifact.profile,\n change,\n 'supervisePursuit versions',\n ),\n change,\n parentDigest,\n refusal: null,\n }\n } catch (error) {\n child = { profile: null, change, parentDigest, refusal: errorMessage(error) }\n }\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:\n versions.next === 'review-of-best'\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 try {\n const closed = await runSearch({\n recorder,\n root: { profile: firstProfile, refusal: null },\n codec,\n policy,\n allocation,\n proposer,\n executor,\n admit: (node) => node.refusal,\n ...(callerSignal === undefined ? {} : { signal: callerSignal }),\n now,\n })\n const judged = await judgedVersions(await versionsOf())\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 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 if (timer !== undefined) clearTimeout(timer)\n }\n\n /** Run one version: the first as the call's own run, a later one as a fork of its parent. */\n async function runVersion(\n record: VersionRecord,\n parent: VersionRecord | undefined,\n signal: AbortSignal,\n ): Promise<void> {\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 async function readVersion(\n record: VersionRecord,\n parent: VersionRecord | undefined,\n ): Promise<{ settled: SettledPursuitVersion; byteLength: number }> {\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 sealed.set(settled.settleDigest, result)\n return { settled, byteLength: bytes.byteLength }\n }\n\n async function judgeVersion(\n settled: SettledPursuitVersion,\n signal: AbortSignal,\n ): Promise<VersionVerdict> {\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 function 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 const outcome: SearchTaskOutcome =\n verdict.score === null\n ? {\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 : settled.result.kind === 'winner'\n ? { status: 'passed', score: verdict.score, metrics: {} }\n : {\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 return {\n outcome,\n accounting: versionAccounting(spent),\n identity: identity(settled.profile),\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 recorder.blob('verdict', {\n kind: 'version-verdict',\n version: settled.version,\n runId: settled.runId,\n verdict,\n }),\n ],\n }\n }\n\n /** A version as the judge and `next` read it. */\n function 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\n /** Every version whose latest settled cell carries a verdict, first first, each read back from\n * its sealed `result.json`. */\n async function judgedVersions(\n chain: ReadonlyMap<string, VersionRecord>,\n ): 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 = 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 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 function versionsOf(): Promise<Map<string, VersionRecord>> {\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 bytes of a version's sealed `result.json` and the record they hold, parsed from the same\n * bytes that are hashed. */\nasync 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. */\nfunction jsonProfile(profile: unknown): AgentProfile {\n canonicalAgentProfileDigest(profile as AgentProfile)\n return JSON.parse(JSON.stringify(agentProfileSchema.parse(profile))) as AgentProfile\n}\n\nfunction 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. */\nfunction 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. */\nfunction 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. */\nfunction settledElapsed(settled: SupervisedResult<unknown> | undefined): number {\n const elapsed = settled?.spentTotal?.ms\n return isFiniteNumber(elapsed) ? elapsed : 0\n}\n\nconst FREE: SearchAttemptAccounting = {\n tokens: { status: 'known', inputTokens: 0, outputTokens: 0, cachedTokens: 0 },\n cost: { status: 'known', usd: 0, source: 'free' },\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 }\n}\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 */\nfunction 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\nfunction digestOf(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\nasync 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\nfunction isSha256(value: unknown): value is Sha256Digest {\n return typeof value === 'string' && /^sha256:[0-9a-f]{64}$/u.test(value)\n}\n\nfunction isFiniteNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value)\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\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, loadSpawnForest } from './spawn-journal'\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. */\nexport const FORK_PARENT_UNCERTAIN_NODES_KEY = 'forkParentUncertainNodes'\n\n/** What `supervisePursuit` executes for a fork: the changed profile and the attributed execution. */\nexport interface 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 { execFile } from 'node:child_process'\nimport { mkdir, readFile, rmdir, unlink } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport { promisify } from 'node:util'\nimport { publishExclusiveDurableFile } from '../runtime/supervise/durable-file'\nimport { isNoEntError } from './jsonl-file'\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, 2026-09-06): 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. The start token (Linux\n * `/proc/<pid>/stat` starttime, otherwise `ps` lstart) is the same for a process's whole life\n * and differs for every later holder of its pid, so a reused pid is reclaimed like a dead one.\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, except when it dies during a guarded mutation; that guard requires manual recovery.\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 /** ISO instant the holder took the lock. */\n readonly startedAt: string\n readonly runId: string\n /**\n * The OS's start token for `pid` when the host reports one (`readProcessStart`). A holder\n * without one is judged by pid liveness alone, which cannot detect a reused pid.\n */\n readonly processStart?: string\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 path: string\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 gone (its pid no longer exists, or the pid now\n * belongs to a process with a different start token) is stale and is removed under the mutation guard;\n * a pid this process may not signal (`EPERM`) is alive and refuses. An empty file names no\n * 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 await mkdir(dir, { recursive: true })\n const processStart = await readProcessStart(process.pid)\n const holder: RunDirectoryLockHolder = Object.freeze({\n pid: process.pid,\n startedAt: new Date(now()).toISOString(),\n runId,\n ...(processStart === undefined ? {} : { processStart }),\n })\n return withMutationGuard(path, async () => {\n const existing = await readLockFile(path)\n if (existing.state === 'holder' && (await holderIsLive(existing.holder))) {\n throw new RunDirectoryLockedError(path, existing.holder)\n }\n if (existing.state !== 'missing') await removeIfPresent(path)\n if (!publishExclusiveDurableFile(path, `${JSON.stringify(holder)}\\n`)) {\n throw new Error(`supervisePursuit: could not take ${path}`)\n }\n let released = false\n return Object.freeze({\n ...holder,\n path,\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 /** True only while the process that took the lock is still the process that holds the pid. */\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: await holderIsLive(existing.holder), holder: existing.holder }\n}\n\nconst execFileAsync = promisify(execFile)\n\n/**\n * The OS's start token for a live pid: on Linux the `starttime` field of `/proc/<pid>/stat`\n * (clock ticks since boot), elsewhere the `ps` `lstart` column. The same process reports the\n * same token for its whole life and a later holder of the pid reports a different one.\n * `undefined` when the host cannot report one: the pid is gone, there is no `/proc` and no\n * `ps`, or the platform is Windows.\n */\nexport async function readProcessStart(pid: number): Promise<string | undefined> {\n if (!Number.isInteger(pid) || pid <= 0 || process.platform === 'win32') return undefined\n if (process.platform === 'linux') {\n let stat: string\n try {\n stat = await readFile(`/proc/${pid}/stat`, 'utf8')\n } catch {\n return undefined\n }\n // The comm field is parenthesized and may hold spaces, so fields are counted after its close.\n const fields = stat\n .slice(stat.lastIndexOf(')') + 1)\n .trim()\n .split(/\\s+/u)\n const startTime = fields[19]\n return startTime !== undefined && /^\\d+$/u.test(startTime) ? startTime : undefined\n }\n try {\n const { stdout } = await execFileAsync('ps', ['-o', 'lstart=', '-p', String(pid)])\n const token = stdout.trim()\n return token.length === 0 ? undefined : token\n } catch {\n return undefined\n }\n}\n\ntype LockFileState =\n | { readonly state: 'missing' }\n | { readonly state: 'empty' }\n | { readonly state: 'holder'; readonly holder: RunDirectoryLockHolder }\n\nasync function readLockFile(path: string): Promise<LockFileState> {\n let text: string\n try {\n text = await readFile(path, 'utf8')\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 ) {\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 return {\n state: 'holder',\n holder: Object.freeze({\n pid,\n startedAt,\n runId,\n ...(processStart === undefined ? {} : { processStart }),\n }),\n }\n}\n\nasync function holderIsLive(holder: RunDirectoryLockHolder): Promise<boolean> {\n if (!processExists(holder.pid)) return false\n if (holder.processStart === undefined) return true\n const current = await readProcessStart(holder.pid)\n // A pid that exists but reports no token cannot be shown to be reused, so it stays live.\n return current === undefined || current === holder.processStart\n}\n\nfunction processExists(pid: number): boolean {\n if (!Number.isInteger(pid) || pid <= 0) return false\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n // EPERM means the process exists but belongs to another user; only ESRCH means gone.\n return (error as { code?: unknown }).code !== 'ESRCH'\n }\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 await withMutationGuard(\n path,\n async () => {\n const existing = await 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 )\n return\n await removeIfPresent(path)\n },\n true,\n )\n}\n\n/** Serialize stale reclamation and release; an abandoned guard requires operator recovery. */\nasync function withMutationGuard<T>(\n path: string,\n mutate: () => Promise<T>,\n waitForRelease = false,\n): Promise<T> {\n const guard = `${path}.guard`\n const deadline = performance.now() + (waitForRelease ? 1_000 : 0)\n for (;;) {\n try {\n await mkdir(guard)\n break\n } catch (cause) {\n if (\n waitForRelease &&\n (cause as { code?: unknown }).code === 'EEXIST' &&\n performance.now() < deadline\n ) {\n await delay(10)\n continue\n }\n throw new Error(\n `supervisePursuit: cannot mutate ${path}; inspect ${guard} and remove it only after confirming no lock mutation is active`,\n { cause },\n )\n }\n }\n try {\n return await mutate()\n } finally {\n await rmdir(guard)\n }\n}\n\nasync function removeIfPresent(path: string): Promise<void> {\n try {\n await unlink(path)\n } catch (error) {\n if (!isNoEntError(error)) throw error\n }\n}\n","import { resolve } from 'node:path'\nimport { readRootStreamReceipt } from '../runtime/supervise/root-stream'\nimport { supervisorRunDir } from '../runtime/supervise/run-layout'\nimport { type SuperviseOptions, supervise } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport { composeRuntimeHooks, type RuntimeHookEvent, withPursuitContext } from '../runtime-hooks'\nimport { createFileObserverHooks } from './observer-journal'\nimport { type PursuitProjection, projectPursuit } from './observer-projection'\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 {\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'`. The settle record refuses re-entry, so no later call resumes a settled\n * pursuit and nothing else would release the provider environments its retained children hold.\n * `'keep'` is refused 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\nexport interface SupervisedPursuitResult<Result> {\n readonly result: Result\n readonly pursuit: PursuitProjection\n readonly observerPath: string\n /** `runDir/result.json`: `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 /** `runDir/failure.json`: 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 const pursuitId = opts.pursuitId.trim()\n if (pursuitId.length === 0) {\n throw new TypeError('supervisePursuit: pursuitId must be non-empty')\n }\n const runDir = opts.runDir.trim()\n if (runDir.length === 0) {\n throw new TypeError('supervisePursuit: runDir must be non-empty')\n }\n if ((opts.retainedAtSettlement as string | undefined) === 'keep') {\n throw new TypeError(\n \"supervisePursuit: retainedAtSettlement 'keep' cannot hold, because a settled pursuit is never re-entered\",\n )\n }\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 observerPath = resolve(runDir, 'observer.jsonl')\n const settlePath = resolve(runDir, SETTLE_RECORD_FILE)\n const failurePath = resolve(runDir, FAILURE_RECORD_FILE)\n const { pursuitId: _pursuitId, hooks, fork, versions: _versions, ...superviseOptions } = opts\n const runId = superviseOptions.runId ?? 'supervise'\n const now = superviseOptions.now ?? Date.now\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 // 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 try {\n const settled = await readSettleRecord(runDir)\n if (settled !== undefined) {\n throw new SettledRunDirectoryError(settlePath, settled.tree.root, runId)\n }\n\n const observer = createFileObserverHooks(observerPath, pursuitId)\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\n let result: Awaited<ReturnType<typeof supervise>>\n try {\n result = await supervise(forked?.profile ?? profile, task, {\n ...superviseOptions,\n ...(forked === undefined ? {} : { execution: forked.execution }),\n // `runDir` owns the pursuit journal and terminal records. The public steer writer addresses\n // the canonical per-run event directory beneath that root, so keep its control plane there\n // without moving the durable pursuit records.\n steerDir: superviseOptions.steerDir ?? supervisorRunDir(runDir, runId),\n // The settle record written below makes this settlement final, so the environments a\n // retained child holds are released at the barrier instead of kept for a resume that the\n // record will refuse (measured 2026-09-11: 18 of a 60-slot fleet held 19 to 37 hours).\n retainedAtSettlement: 'release',\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, hooks)),\n })\n } catch (error) {\n let pursuit: PursuitProjection | undefined\n let observerError: unknown\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 }),\n )\n pursuit = projectPursuit(await observer.journal.read())\n } catch (failure) {\n observerError = failure\n }\n if (observerError !== undefined || pursuit === undefined) {\n const causes = observerError === undefined ? [error] : [error, observerError]\n throw new Error(\n 'supervisePursuit: Runtime failed and durable observer completeness could not be proven',\n { cause: new AggregateError(causes) },\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 try {\n await writeSettleRecord(runDir, result)\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(), { status: 'done' }),\n )\n return Object.freeze({\n result,\n pursuit: projectPursuit(await observer.journal.read()),\n observerPath,\n settlePath,\n })\n } finally {\n await lock.release()\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 errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nfunction errorName(error: unknown): string {\n return error instanceof Error ? error.name : 'NonError'\n}\n","import { resolve } from 'node:path'\nimport type { NodeId } from '../runtime/supervise/types'\nimport { readCommittedJsonLines } from './jsonl-file'\n\nexport interface DurableCoordinationStreamIdentity {\n readonly runId: string\n /** Exact owner ids present in the side-log, sorted for deterministic display. */\n readonly ownerIds: readonly string[]\n /** Records written before owner-scoped coordination identities were introduced. */\n readonly unscopedRecords: number\n readonly recordCount: number\n}\n\n/**\n * Identities discoverable from one `supervise({ runDir })` directory without\n * already knowing the root node or coordination run id stored inside it.\n */\nexport interface DurableSupervisionDiscovery {\n readonly runDir: string\n readonly spawnJournalPath: string\n readonly coordinationLogPath: string\n readonly roots: readonly NodeId[]\n /** `at` from each top-level root's `begin` record, index-aligned with `roots`. */\n readonly rootsBegunAt: readonly (string | null)[]\n readonly coordinationStreams: readonly DurableCoordinationStreamIdentity[]\n}\n\ntype SpawnJournalIdentityRecord = {\n readonly kind?: unknown\n readonly root?: unknown\n readonly at?: unknown\n readonly event?: unknown\n}\n\ntype CoordinationIdentityRecord = {\n readonly runId?: unknown\n readonly ownerId?: unknown\n}\n\n/**\n * Discover the stable identities recorded by Runtime's durable supervision\n * files. This is the developer-facing first step before calling\n * `FileSpawnJournal.loadTree(root)`, `loadSpawnForest(journal, root)`, or\n * `FileCoordinationLog.load(runId, ownerId)`.\n *\n * Missing files produce empty collections. A malformed committed JSONL record\n * still fails loud through the same parser used by the runtime; a torn final\n * append is ignored because it was never acknowledged as committed.\n */\nexport async function discoverDurableSupervisionRun(\n runDir: string,\n): Promise<DurableSupervisionDiscovery> {\n if (typeof runDir !== 'string' || runDir.trim().length === 0) {\n throw new TypeError('discoverDurableSupervisionRun: runDir must be a non-empty string')\n }\n\n const canonicalRunDir = resolve(runDir)\n const spawnJournalPath = `${canonicalRunDir}/spawn-journal.jsonl`\n const coordinationLogPath = `${canonicalRunDir}/coordination-log.jsonl`\n const allRoots = new Set<NodeId>()\n const nestedRoots = new Set<NodeId>()\n const rootsBegunAt = new Map<NodeId, string | null>()\n for await (const record of readCommittedJsonLines<SpawnJournalIdentityRecord>(spawnJournalPath, {\n allowMissing: true,\n })) {\n if (record.kind === 'begin') {\n if (typeof record.root !== 'string' || record.root.length === 0) {\n throw new Error(`${spawnJournalPath}: begin record has no non-empty string root identity`)\n }\n allRoots.add(record.root as NodeId)\n rootsBegunAt.set(record.root as NodeId, typeof record.at === 'string' ? record.at : null)\n continue\n }\n if (record.kind !== 'event') continue\n const event = record.event\n if (!isRecord(event) || event.kind !== 'spawned') continue\n if (!Object.hasOwn(event, 'ownedTreeRoot')) continue\n if (typeof event.ownedTreeRoot !== 'string' || event.ownedTreeRoot.length === 0) {\n throw new Error(\n `${spawnJournalPath}: spawned event ownedTreeRoot must be a non-empty string when present`,\n )\n }\n nestedRoots.add(event.ownedTreeRoot as NodeId)\n }\n\n const streams = new Map<\n string,\n { owners: Set<string>; unscopedRecords: number; recordCount: number }\n >()\n for await (const record of readCommittedJsonLines<CoordinationIdentityRecord>(\n coordinationLogPath,\n { allowMissing: true },\n )) {\n if (typeof record.runId !== 'string' || record.runId.length === 0) {\n throw new Error(`${coordinationLogPath}: record has no non-empty string runId identity`)\n }\n const stream = streams.get(record.runId) ?? {\n owners: new Set<string>(),\n unscopedRecords: 0,\n recordCount: 0,\n }\n stream.recordCount += 1\n if (record.ownerId === undefined) {\n stream.unscopedRecords += 1\n } else if (typeof record.ownerId === 'string' && record.ownerId.length > 0) {\n stream.owners.add(record.ownerId)\n } else {\n throw new Error(`${coordinationLogPath}: ownerId must be a non-empty string when present`)\n }\n streams.set(record.runId, stream)\n }\n\n const coordinationStreams = [...streams.entries()]\n .sort(([left], [right]) => compareText(left, right))\n .map(([runId, stream]) =>\n Object.freeze({\n runId,\n ownerIds: Object.freeze([...stream.owners].sort(compareText)),\n unscopedRecords: stream.unscopedRecords,\n recordCount: stream.recordCount,\n }),\n )\n\n const roots = [...allRoots].filter((root) => !nestedRoots.has(root)).sort(compareText)\n return Object.freeze({\n runDir: canonicalRunDir,\n spawnJournalPath,\n coordinationLogPath,\n roots: Object.freeze(roots),\n rootsBegunAt: Object.freeze(roots.map((root) => rootsBegunAt.get(root) ?? null)),\n coordinationStreams: Object.freeze(coordinationStreams),\n })\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA8FA,MAAM,UAAU,IAAI,YAAY;AAEhC,SAAS,WAAW,OAAoC;CACtD,OAAO,QAAQ,OAAO,GAAG,KAAK,UAAU,KAAK,EAAE,GAAG;AACpD;AAEA,SAAS,WAAW,SAAiB,MAAsC;CACzE,IAAI,MAAM,QAAQ,MAAM,SAAS,IAAI;MAChC,QAAQ,MAAM,OAAO;AAC5B;;;;;;;;;AAUA,eAAe,mBAAmB,OAAiC;CACjE,IAAI,EAAE,iBAAiB,WACrB,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CAG9D,MAAM,SAAS,QAAQ,MAAM;CAC7B,IAAI;EACF,MAAM,OAAO,MAAM,MAAM,MAAM,CAAC,CAAC,KAAK;EACtC,IAAI,CAAC,KAAK,KAAK,GAAG,OAAO;EACzB,IAAI;GACF,MAAM,OAAO,KAAK,MAAM,IAAI;GAI5B,MAAM,SACJ,OAAO,KAAK,UAAU,YAAY,KAAK,UAAU,OAAO,KAAK,MAAM,UAAU,KAAK;GACpF,MAAM,UACJ,OAAO,WAAW,WACd,SACA,OAAO,KAAK,YAAY,WACtB,KAAK,UACL,KAAA;GACR,IAAI,SAAS,OAAO,GAAG,OAAO,IAAI,QAAQ,MAAM,GAAG,GAAG;EACxD,QAAQ,CAGR;CACF,QAAQ,CAER;CACA,OAAO;AACT;;;;;;AAOA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