@tangle-network/agent-runtime 0.225.5 → 0.226.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/{activation-Boyh7-Bk.js → activation-BOIqqsCw.js} +2 -2
  2. package/dist/{activation-Boyh7-Bk.js.map → activation-BOIqqsCw.js.map} +1 -1
  3. package/dist/{activation-CsfCkAdZ.d.ts → activation-Dv8TBXAS.d.ts} +2 -2
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +2 -2
  6. package/dist/{coordination-driver-B5NtPTE1.js → coordination-driver-DxHQLK8i.js} +2 -2
  7. package/dist/{coordination-driver-B5NtPTE1.js.map → coordination-driver-DxHQLK8i.js.map} +1 -1
  8. package/dist/{delegate-DRVxCsVg.js → delegate-DHpAEq6-.js} +2 -2
  9. package/dist/{delegate-DRVxCsVg.js.map → delegate-DHpAEq6-.js.map} +1 -1
  10. package/dist/durable.d.ts +39 -3
  11. package/dist/durable.js +7 -5
  12. package/dist/durable.js.map +1 -1
  13. package/dist/{graph-BweGIXuL.js → graph-BkeA7dEi.js} +3 -3
  14. package/dist/{graph-BweGIXuL.js.map → graph-BkeA7dEi.js.map} +1 -1
  15. package/dist/{improvement-cycle-DCKn8HT0.js → improvement-cycle-B9gBkr_0.js} +3 -3
  16. package/dist/{improvement-cycle-DCKn8HT0.js.map → improvement-cycle-B9gBkr_0.js.map} +1 -1
  17. package/dist/{index-ClXIBpKe.d.ts → index-DAIij88v.d.ts} +10 -2
  18. package/dist/index.d.ts +4 -4
  19. package/dist/index.js +7 -7
  20. package/dist/intelligence.d.ts +2 -2
  21. package/dist/intelligence.js +3 -3
  22. package/dist/kernel.d.ts +3 -3
  23. package/dist/kernel.js +8 -8
  24. package/dist/{loop-runner-bin-DXzs4Rjq.js → loop-runner-bin-B0nQvskW.js} +3 -3
  25. package/dist/{loop-runner-bin-DXzs4Rjq.js.map → loop-runner-bin-B0nQvskW.js.map} +1 -1
  26. package/dist/{loop-runner-bin-BRfsk-9d.d.ts → loop-runner-bin-CN1rstwC.d.ts} +3 -3
  27. package/dist/loop-runner-bin.d.ts +1 -1
  28. package/dist/loop-runner-bin.js +1 -1
  29. package/dist/mcp/bin.js +3 -3
  30. package/dist/mcp/index.d.ts +2 -2
  31. package/dist/mcp/index.js +4 -4
  32. package/dist/{provision-supervisor-B0BFvUQ1.js → provision-supervisor-Dfuc4gK0.js} +3 -3
  33. package/dist/{provision-supervisor-B0BFvUQ1.js.map → provision-supervisor-Dfuc4gK0.js.map} +1 -1
  34. package/dist/{runtime-BuAJH9FK.js → runtime-Dqik43o3.js} +8 -8
  35. package/dist/{runtime-BuAJH9FK.js.map → runtime-Dqik43o3.js.map} +1 -1
  36. package/dist/{server-_U6iIJkV.js → server-C12kUoSM.js} +3 -3
  37. package/dist/{server-_U6iIJkV.js.map → server-C12kUoSM.js.map} +1 -1
  38. package/dist/{stream-agent-turn-wlsHQiUv.d.ts → stream-agent-turn-Dy-QleSb.d.ts} +22 -2
  39. package/dist/{structural-rollout-DDjlhogU.js → structural-rollout-Zog2WEZo.js} +2 -2
  40. package/dist/{structural-rollout-DDjlhogU.js.map → structural-rollout-Zog2WEZo.js.map} +1 -1
  41. package/dist/{supervise-qYms7HSb.js → supervise-CtXJ-lWb.js} +180 -10
  42. package/dist/supervise-CtXJ-lWb.js.map +1 -0
  43. package/dist/{supervisor-D1j1RRJy.js → supervisor-DCQxXRR8.js} +1 -6
  44. package/dist/supervisor-DCQxXRR8.js.map +1 -0
  45. package/dist/testing.d.ts +2 -2
  46. package/dist/testing.js +12 -12
  47. package/dist/tui/index.d.ts +1 -1
  48. package/dist/tui/index.js +1 -1
  49. package/package.json +1 -1
  50. package/dist/supervise-qYms7HSb.js.map +0 -1
  51. package/dist/supervisor-D1j1RRJy.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"durable.js","names":["delay"],"sources":["../src/durable/chat-engine.ts","../src/durable/execution-handle.ts","../src/durable/observer-journal.ts","../src/durable/observer-projection.ts","../src/durable/run-lock.ts","../src/durable/settle-record.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 { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport {\n type RuntimeDecisionPoint,\n type RuntimeHookEvent,\n type RuntimeHooks,\n withPursuitContext,\n} from '../runtime-hooks'\nimport { parseCommittedJsonLines, prepareJsonlAppend, 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 let text: string\n try {\n text = await readFile(this.path, 'utf8')\n } catch (error) {\n if (isNoEnt(error)) return []\n throw error\n }\n return verifyObserverRecords(\n parseCommittedJsonLines<ObserverRecord>(text, this.path),\n this.pursuitId,\n )\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 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: value as RuntimeHookEvent }\n : { decision: value 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 records = await this.readExistingUnsafe()\n const verified = verifyObserverRecords(records, this.pursuitId)\n const tail = verified.at(-1)\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 async readExistingUnsafe(): Promise<ObserverRecord[]> {\n let text: string\n try {\n text = await readFile(this.path, 'utf8')\n } catch (error) {\n if (isNoEnt(error)) return []\n throw error\n }\n return parseCommittedJsonLines<ObserverRecord>(text, this.path)\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 let previousDigest: string | undefined\n let expectedSequence = 1\n for (const record of records) {\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 return Object.freeze([...records])\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 isNoEnt(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ENOENT'\n )\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 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 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 /** 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 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 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 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 ...(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 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 { 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 { 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 { 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}\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 ) {\n throw new Error(`supervisePursuit: ${path} is not a failure record`)\n }\n return parsed as DurableFailureRecord\n}\n","import { resolve } from 'node:path'\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 { 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\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}\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 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, ...superviseOptions } = opts\n const runId = superviseOptions.runId ?? 'supervise'\n const now = superviseOptions.now ?? Date.now\n\n // The lock is taken before the settle record is read so a run that settles between the read\n // and the lock cannot be re-entered; both refusals happen before the observer journal is touched.\n const lock = await acquireRunDirectoryLock(runDir, runId, now)\n 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(profile, task, {\n ...superviseOptions,\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 await writeFailureRecord(runDir, {\n runId,\n pursuitId,\n at: new Date(now()).toISOString(),\n error: { name: errorName(error), message: errorMessage(error) },\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 { isNoEntError, parseCommittedJsonLines } 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 [spawnText, coordinationText] = await Promise.all([\n readOptionalText(spawnJournalPath),\n readOptionalText(coordinationLogPath),\n ])\n\n const allRoots = new Set<NodeId>()\n const nestedRoots = new Set<NodeId>()\n const rootsBegunAt = new Map<NodeId, string | null>()\n if (spawnText !== undefined) {\n for (const record of parseCommittedJsonLines<SpawnJournalIdentityRecord>(\n spawnText,\n spawnJournalPath,\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\n const streams = new Map<\n string,\n { owners: Set<string>; unscopedRecords: number; recordCount: number }\n >()\n if (coordinationText !== undefined) {\n for (const record of parseCommittedJsonLines<CoordinationIdentityRecord>(\n coordinationText,\n coordinationLogPath,\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\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\nasync function readOptionalText(path: string): Promise<string | undefined> {\n const fs = await import('node:fs/promises')\n try {\n return await fs.readFile(path, 'utf8')\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\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,MA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AO,CAAC,WAAW,YAAY,MAAM,KAAK,CAAC,CAAC,CACnD,KAAK,CAAC,OAAO,YACZ,OAAO,OAAO;EACZ;EACA,UAAU,OAAO,OAAO,CAAC,GAAG,OAAO,MAAM,CAAC,CAAC,KAAK,WAAW,CAAC;EAC5D,iBAAiB,OAAO;EACxB,aAAa,OAAO;CACtB,CAAC,CACH;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,eAAe,iBAAiB,MAA2C;CACzE,MAAM,KAAK,MAAM,OAAO;CACxB,IAAI;EACF,OAAO,MAAM,GAAG,SAAS,MAAM,MAAM;CACvC,SAAS,OAAO;EACd,IAAI,aAAa,KAAK,GAAG,OAAO,KAAA;EAChC,MAAM;CACR;AACF;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":["delay"],"sources":["../src/durable/chat-engine.ts","../src/durable/execution-handle.ts","../src/durable/observer-journal.ts","../src/durable/observer-projection.ts","../src/durable/run-lock.ts","../src/durable/settle-record.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 { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport {\n type RuntimeDecisionPoint,\n type RuntimeHookEvent,\n type RuntimeHooks,\n withPursuitContext,\n} from '../runtime-hooks'\nimport { parseCommittedJsonLines, prepareJsonlAppend, 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 let text: string\n try {\n text = await readFile(this.path, 'utf8')\n } catch (error) {\n if (isNoEnt(error)) return []\n throw error\n }\n return verifyObserverRecords(\n parseCommittedJsonLines<ObserverRecord>(text, this.path),\n this.pursuitId,\n )\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 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: value as RuntimeHookEvent }\n : { decision: value 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 records = await this.readExistingUnsafe()\n const verified = verifyObserverRecords(records, this.pursuitId)\n const tail = verified.at(-1)\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 async readExistingUnsafe(): Promise<ObserverRecord[]> {\n let text: string\n try {\n text = await readFile(this.path, 'utf8')\n } catch (error) {\n if (isNoEnt(error)) return []\n throw error\n }\n return parseCommittedJsonLines<ObserverRecord>(text, this.path)\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 let previousDigest: string | undefined\n let expectedSequence = 1\n for (const record of records) {\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 return Object.freeze([...records])\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 isNoEnt(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ENOENT'\n )\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 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 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 /** 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 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 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 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 ...(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 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 { 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 { 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","import { resolve } from 'node:path'\nimport { readRootStreamReceipt } from '../runtime/supervise/root-stream'\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 { 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\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}\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 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, ...superviseOptions } = opts\n const runId = superviseOptions.runId ?? 'supervise'\n const now = superviseOptions.now ?? Date.now\n\n // The lock is taken before the settle record is read so a run that settles between the read\n // and the lock cannot be re-entered; both refusals happen before the observer journal is touched.\n const lock = await acquireRunDirectoryLock(runDir, runId, now)\n 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(profile, task, {\n ...superviseOptions,\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 { isNoEntError, parseCommittedJsonLines } 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 [spawnText, coordinationText] = await Promise.all([\n readOptionalText(spawnJournalPath),\n readOptionalText(coordinationLogPath),\n ])\n\n const allRoots = new Set<NodeId>()\n const nestedRoots = new Set<NodeId>()\n const rootsBegunAt = new Map<NodeId, string | null>()\n if (spawnText !== undefined) {\n for (const record of parseCommittedJsonLines<SpawnJournalIdentityRecord>(\n spawnText,\n spawnJournalPath,\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\n const streams = new Map<\n string,\n { owners: Set<string>; unscopedRecords: number; recordCount: number }\n >()\n if (coordinationText !== undefined) {\n for (const record of parseCommittedJsonLines<CoordinationIdentityRecord>(\n coordinationText,\n coordinationLogPath,\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\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\nasync function readOptionalText(path: string): Promise<string | undefined> {\n const fs = await import('node:fs/promises')\n try {\n return await fs.readFile(path, 'utf8')\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\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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