@tangle-network/agent-runtime 3.0.14 → 3.0.16

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 (57) hide show
  1. package/dist/{activation-qzYpKuLp.js → activation-DJ40anIr.js} +2 -2
  2. package/dist/{activation-qzYpKuLp.js.map → activation-DJ40anIr.js.map} +1 -1
  3. package/dist/agent.js +3 -3
  4. package/dist/{coordination-manager-CNSEGgvn.js → coordination-manager-CFfarnFh.js} +4 -4
  5. package/dist/{coordination-manager-CNSEGgvn.js.map → coordination-manager-CFfarnFh.js.map} +1 -1
  6. package/dist/{delegate-upnducQd.js → delegate-Byo3YB6N.js} +2 -2
  7. package/dist/{delegate-upnducQd.js.map → delegate-Byo3YB6N.js.map} +1 -1
  8. package/dist/durable.js +6 -6
  9. package/dist/{graph-gYLSR7wJ.js → graph-DuUW-LNW.js} +5 -5
  10. package/dist/{graph-gYLSR7wJ.js.map → graph-DuUW-LNW.js.map} +1 -1
  11. package/dist/{improve-B5s94UEb.js → improve-K6AzvHcf.js} +6 -6
  12. package/dist/{improve-B5s94UEb.js.map → improve-K6AzvHcf.js.map} +1 -1
  13. package/dist/index.js +8 -8
  14. package/dist/intelligence.js +4 -4
  15. package/dist/kernel.js +11 -11
  16. package/dist/{loop-runner-Chy2Fxfy.js → loop-runner-DwepGENE.js} +2 -2
  17. package/dist/{loop-runner-Chy2Fxfy.js.map → loop-runner-DwepGENE.js.map} +1 -1
  18. package/dist/loop-runner-bin.js +1 -1
  19. package/dist/mcp/bin.js +3 -3
  20. package/dist/mcp/index.js +5 -5
  21. package/dist/{provision-supervisor-r_0BoNs7.js → provision-supervisor-DOgH75Qk.js} +4 -4
  22. package/dist/{provision-supervisor-r_0BoNs7.js.map → provision-supervisor-DOgH75Qk.js.map} +1 -1
  23. package/dist/{run-cancellation-DIJXvIRr.js → run-cancellation-pmPWcMy0.js} +2 -2
  24. package/dist/{run-cancellation-DIJXvIRr.js.map → run-cancellation-pmPWcMy0.js.map} +1 -1
  25. package/dist/{runtime-DUKNg2rS.js → runtime-5CO88Rt2.js} +11 -11
  26. package/dist/{runtime-DUKNg2rS.js.map → runtime-5CO88Rt2.js.map} +1 -1
  27. package/dist/{scope-DlsCaLrX.js → scope-BKJ_SdfW.js} +12 -8
  28. package/dist/scope-BKJ_SdfW.js.map +1 -0
  29. package/dist/{search-executor-DPbqmita.js → search-executor-BX2Wwftx.js} +3 -3
  30. package/dist/{search-executor-DPbqmita.js.map → search-executor-BX2Wwftx.js.map} +1 -1
  31. package/dist/{server-Bde00T0D.js → server-wdjqe8et.js} +3 -3
  32. package/dist/{server-Bde00T0D.js.map → server-wdjqe8et.js.map} +1 -1
  33. package/dist/{structural-rollout-B9YW_iTZ.js → structural-rollout-oXgpKkEo.js} +3 -3
  34. package/dist/{structural-rollout-B9YW_iTZ.js.map → structural-rollout-oXgpKkEo.js.map} +1 -1
  35. package/dist/{supervise-z-h64T2Y.js → supervise-BpvUVtSI.js} +21 -16
  36. package/dist/supervise-BpvUVtSI.js.map +1 -0
  37. package/dist/{supervision-discovery-Cqv9QGnN.js → supervision-discovery-D3RjhxX4.js} +13 -16
  38. package/dist/supervision-discovery-D3RjhxX4.js.map +1 -0
  39. package/dist/{supervisor-PARoR3aR.js → supervisor-XWLIHK-U.js} +30 -41
  40. package/dist/supervisor-XWLIHK-U.js.map +1 -0
  41. package/dist/testing.js +11 -11
  42. package/dist/{top-web-CW_n7kil.js → top-web-BYx8LLQ7.js} +4 -4
  43. package/dist/{top-web-CW_n7kil.js.map → top-web-BYx8LLQ7.js.map} +1 -1
  44. package/dist/tui/bin.js +3 -3
  45. package/dist/tui/index.js +2 -2
  46. package/dist/viewer/report-viewer.js +126 -86
  47. package/dist/viewer/runtime-viewer/{AgentGraphCanvas-CcBWMidO-DIW8tof6.js → AgentGraphCanvas-DGq7_u8--C6yDfIUT.js} +2179 -2206
  48. package/dist/viewer/runtime-viewer/latest-events-CRq9sGkK-CfoBl1dP.js +9592 -0
  49. package/dist/viewer/runtime-viewer/{sandbox-ui-CUj4Q1P_.css → sandbox-ui-BEziPi7D.css} +1 -1
  50. package/dist/viewer/styles.css +99 -29
  51. package/dist/viewer/workspace-viewer.js +10742 -10828
  52. package/package.json +2 -2
  53. package/dist/scope-DlsCaLrX.js.map +0 -1
  54. package/dist/supervise-z-h64T2Y.js.map +0 -1
  55. package/dist/supervision-discovery-Cqv9QGnN.js.map +0 -1
  56. package/dist/supervisor-PARoR3aR.js.map +0 -1
  57. package/dist/viewer/runtime-viewer/latest-events-BfRc-7l9-QhJD89rn.js +0 -3808
@@ -1 +0,0 @@
1
- {"version":3,"file":"supervision-discovery-Cqv9QGnN.js","names":[],"sources":["../src/durable/observer-projection.ts","../src/durable/settle-record.ts","../src/durable/supervision-discovery.ts"],"sourcesContent":["import { type RuntimeFailureCause, runtimeFailureCauseSchema } from '../runtime/failure-cause'\nimport type { SeatSegment } from '../runtime/supervise/seat-chain'\nimport type {\n BudgetOverspend,\n BudgetViolation,\n ExecutionBindingReceipt,\n ProfileMaterializationReceipt,\n ProviderModelExecutionEvidence,\n RetainedExecutionState,\n RetainedPendingCause,\n Spend,\n SpendChannel,\n SpendGap,\n WorkerTraceEvidence,\n} from '../runtime/supervise/types'\nimport { addSpend, cloneSpend, zeroSpend } from '../runtime/util'\nimport type { RuntimeDecisionKind, RuntimeHookTarget } from '../runtime-hooks'\nimport { type ObserverRecord, verifyObserverRecords } from './observer-journal'\n\n/**\n * One settled projection status, shared by runs and nodes. `down` is the journal's own word for a\n * failure (a settlement is journaled as `kind: 'down'`, cancellation included), so a consumer can\n * join run rows to node rows on `status` and read one failure population instead of two.\n */\nexport type PursuitStatus = 'running' | 'done' | 'down'\n\n/**\n * Where a node's dollar figure came from. `reported` = a provider billed all of it; `estimated` =\n * a model catalog priced all of it; `partial` = a provider billed part and a catalog priced the\n * rest; `unknown` = nothing priced it, so `usd` is a floor and never the cost.\n */\nexport type PursuitCostProvenance = 'reported' | 'estimated' | 'partial' | 'unknown'\n\n/**\n * One node's token usage by class. Cache and reasoning classes are absent when the provider did\n * not report them — absence is not zero. `tokensKnown` is `false` when work happened whose token\n * count no provider reported, which makes `input`/`output` a floor.\n */\nexport interface PursuitNodeUsage {\n readonly input: number\n readonly output: number\n readonly cacheRead?: number\n readonly cacheWrite?: number\n readonly reasoning?: number\n readonly tokensKnown: boolean\n}\n\n/**\n * One node's PLATFORM consumption — box wall time, the resource a subscription seat really pays.\n *\n * Kept apart from `PursuitNodeCost` because the two answer different questions and fail\n * independently: a seat run reports a truthful `$0` and real minutes, a caller-account run\n * reports real dollars and may report no minutes at all. Collapsing them into one \"spend known\"\n * figure hides which one is missing.\n *\n * Absent on a node that ran no box. `boxMinutes` absent WITH the block present says a box ran and\n * nothing measured it — a missing measurement is never a zero.\n */\nexport interface PursuitNodePlatform {\n readonly boxMinutes?: number\n /** `false` when a box ran whose time could not be closed, so `boxMinutes` is a floor. */\n readonly boxMinutesKnown: boolean\n /** `observed` = the platform billed the minutes; `estimated` = Runtime derived them from the box\n * lifetime it watched; `uncaptured` = a box ran and nothing measured it. */\n readonly provenance: 'observed' | 'estimated' | 'uncaptured'\n}\n\n/** One node's dollar cost with the provenance that decides whether it may be compared or summed. */\nexport interface PursuitNodeCost {\n readonly usd: number\n readonly usdKnown: boolean\n /** The part of `usd` a model catalog priced because no provider receipt covered it. */\n readonly usdEstimated?: number\n readonly provenance: PursuitCostProvenance\n}\n\n/**\n * One node's clock. `wallMs` is `settledAt - startedAt` and is deliberately distinct from the\n * executor-reported `spent.ms` sums, which under-report and overlap across parallel children.\n * `firstTokenAt` stays absent unless a provider reports that instant; it is never inferred from\n * `firstOutputAt`, which is when the node first reported usage for a turn.\n */\nexport interface PursuitNodeTiming {\n readonly startedAt: number\n readonly firstOutputAt?: number\n readonly firstTokenAt?: number\n readonly settledAt?: number\n readonly wallMs?: number\n}\n\n/** Where and how a node's execution was placed, read off its execution-binding receipt. */\ntype 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 /** Runtime-classified root failure; absent in legacy observer history. */\n readonly failure?: RuntimeFailureCause\n /** Subscription execution of the root manager, ordered across seat changes. */\n readonly segments?: ReadonlyArray<SeatSegment>\n readonly resumeAt?: string\n readonly firstSequence: number\n readonly lastSequence: number\n readonly firstObservedAt: number\n readonly lastObservedAt: number\n readonly eventCount: number\n readonly decisionCount: number\n readonly targets: Readonly<Record<string, number>>\n readonly decisions: Readonly<Record<string, number>>\n readonly totals: PursuitRunTotals\n /** The nodes whose accounting is incomplete. Present exactly when non-empty. */\n readonly spendGaps?: ReadonlyArray<SpendGap>\n}\n\nexport interface PursuitNodeProjection {\n readonly id: string\n readonly parentId?: string\n /** Node ids are scoped to this concrete Runtime tree; `(runId,id)` is identity. */\n readonly runId: string\n readonly label?: string\n /** The runner that executed this node — the executor's own name, not a harness guess. */\n readonly runtime?: string\n readonly depth?: number\n readonly assignmentId?: string\n /** The settled sibling this node replaced, as its manager's spawn named it. Absent on a node\n * that replaced nothing. */\n readonly successorOf?: string\n readonly identity?: unknown\n readonly budget?: unknown\n readonly status: PursuitStatus\n readonly settledAt?: number\n /** The child work this node reported at settlement. Absent until a terminal record lands. */\n readonly spent?: Spend\n /** This node's OWN inference, re-homed from its nested tree. Absent when it drove no turns. */\n readonly ownInference?: Spend\n /** Absent until a spend record lands; the run's `spendGaps` then names the node. */\n readonly usage?: PursuitNodeUsage\n /** Absent until a spend record lands; the run's `spendGaps` then names the node. */\n readonly cost?: PursuitNodeCost\n /** What the node consumed on the PLATFORM. Absent on a node that ran no box. */\n readonly platform?: PursuitNodePlatform\n readonly timing?: PursuitNodeTiming\n /** The kernel-minted attempt this node's execution binding is keyed on. */\n readonly attemptId?: string\n /** The runner-native execution the node bound to: a request, session, run, process, or tree. */\n readonly execution?: { readonly kind: string; readonly id: string }\n /** The model the materialization receipt names, when the runner reported one. */\n readonly model?: string\n /** The concrete backend the profile materialized onto. */\n readonly backend?: string\n readonly placement?: PursuitNodePlacement\n /** Model-call identifiers this node's own turns reported, in order, deduplicated. */\n readonly modelCalls?: ReadonlyArray<string>\n readonly materialization?: ProfileMaterializationReceipt\n readonly executionBindings?: ReadonlyArray<ExecutionBindingReceipt>\n /** What the provider itself reported serving, and why it is unknown when it is. */\n readonly providerModel?: ProviderModelExecutionEvidence\n /** Content-addressed pointer to this node's persisted tool trace, or why there is none. */\n readonly trace?: WorkerTraceEvidence\n readonly outRef?: string\n readonly score?: number\n readonly valid?: boolean\n readonly reason?: string\n readonly failure?: RuntimeFailureCause\n /** Subscription execution of this logical child, ordered across seat changes. */\n readonly segments?: ReadonlyArray<SeatSegment>\n readonly resumeAt?: string\n readonly infra?: boolean\n /** Recorded by Runtime on the `agent.child` payload: `'pending'` at a retained child's\n * settlement, `'released'` when root settlement destroyed its environment without recovery,\n * `'release-unconfirmed'` when a final settlement closed its slot without confirming that.\n * The status stays `down` — the split is a sibling fact, not a fourth status. A second\n * `agent.child` for one node is already how a live-recovered child flips down→done, so the\n * fold overwrites in observed order; that event's `settledAt` is the original settlement, so\n * `settledAt` and `timing` do not move. */\n readonly retainedExecution?: RetainedExecutionState\n /** Why a retained child has no accepted result; see `RetainedPendingCause`. */\n readonly retainedPendingCause?: RetainedPendingCause\n /** When a final settlement closed a retained node's slot; absent while it is `'pending'`. */\n readonly releasedAt?: number\n /** Each channel on which the settled spend exceeded the node's reservation. The status is the\n * node's own outcome: a `done` node that overspent still delivered its output. */\n readonly budgetViolation?: BudgetViolation\n readonly 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 -readonly [K in keyof Omit<\n PursuitRunProjection,\n 'totals' | 'spendGaps' | 'segments' | 'targets' | 'decisions'\n >]: PursuitRunProjection[K]\n} & {\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 segments?: SeatSegment[]\n targets: Record<string, number>\n decisions: Record<string, number>\n /** Inference the run root drove itself, attributable to no spawned node. */\n rootInference?: Spend\n}\n\ntype MutableNode = {\n id: string\n parentId?: string\n runId: string\n /** The attempt whose process spawned this node; totals and gaps are folded per attempt. */\n attemptIndex: number\n label?: string\n runtime?: string\n depth?: number\n assignmentId?: string\n successorOf?: string\n identity?: unknown\n budget?: unknown\n status: PursuitStatus\n startedAt?: number\n settledAt?: number\n spent?: Spend\n ownInference?: Spend\n reasoningTokens?: number\n firstOutputAt?: number\n firstTokenAt?: number\n attemptId?: string\n execution?: { kind: string; id: string }\n model?: string\n backend?: string\n placement?: PursuitNodePlacement\n modelCalls: string[]\n materialization?: ProfileMaterializationReceipt\n executionBindings?: ReadonlyArray<ExecutionBindingReceipt>\n providerModel?: ProviderModelExecutionEvidence\n trace?: WorkerTraceEvidence\n outRef?: string\n score?: number\n valid?: boolean\n reason?: string\n failure?: RuntimeFailureCause\n segments?: SeatSegment[]\n resumeAt?: string\n infra?: boolean\n retainedExecution?: RetainedExecutionState\n retainedPendingCause?: RetainedPendingCause\n releasedAt?: number\n budgetViolation?: BudgetViolation\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 projectSeat(run, 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 projectSeat(\n run: MutableRun,\n nodes: Map<string, MutableNode>,\n record: ObserverRecord,\n): void {\n const event = record.event\n if (event?.target !== 'agent.seat') return\n const payload = objectRecord(event.payload)\n const phase = stringField(payload, 'phase')\n const node = nodes.get(nodeKey(event.runId, stringField(payload, 'nodeId') ?? ''))\n const owner = node ?? run\n if (phase === 'paused') {\n const resumeAt = stringField(payload, 'resumeAt')\n if (resumeAt) owner.resumeAt = resumeAt\n return\n }\n if (phase === 'resumed') {\n delete owner.resumeAt\n return\n }\n const raw = objectRecord(payload?.segment)\n const seat = stringField(raw, 'seat')\n const harness = stringField(raw, 'harness')\n const provider = stringField(raw, 'provider')\n const model = stringField(raw, 'model')\n const startedAt = stringField(raw, 'startedAt')\n if (!seat || !harness || !provider || !model || !startedAt) return\n if (owner.segments === undefined) owner.segments = []\n const segments = owner.segments\n if (phase === 'started') {\n if (!segments.some((segment) => segment.startedAt === startedAt && segment.seat === seat)) {\n segments.push({ seat, harness, provider, model, startedAt })\n }\n } else if (phase === 'ended') {\n const endedAt = stringField(raw, 'endedAt')\n const reason = stringField(raw, 'reason') as SeatSegment['reason']\n if (!endedAt || !reason) return\n const index = segments.findIndex(\n (segment) => segment.startedAt === startedAt && segment.seat === seat,\n )\n if (index >= 0) segments[index] = { seat, harness, provider, model, startedAt, endedAt, reason }\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 const done = event.phase === 'after' || status === 'done'\n if (!done && event.phase !== 'error' && status !== 'failed') return\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 run.status = done ? 'done' : 'down'\n run.settledAt = record.observedAt\n if (payload && Object.hasOwn(payload, 'failure'))\n run.failure = runtimeFailureCauseSchema.parse(payload.failure)\n const error = stringField(payload, 'error')\n if (error && (!done || run.failure !== undefined)) run.error = error\n}\n\nfunction nodeKey(runId: string, nodeId: string): string {\n return `${runId}\\u0000${nodeId}`\n}\n\nfunction projectSpawnNode(\n nodes: Map<string, MutableNode>,\n record: ObserverRecord,\n attemptIndex: number,\n): void {\n const event = record.event\n if (event?.target !== 'agent.spawn') return\n const payload = objectRecord(event.payload)\n const childId = stringField(payload, 'childId')\n if (!childId) return\n const key = nodeKey(event.runId, childId)\n const existing = nodes.get(key)\n if (existing) {\n existing.lastSequence = record.sequence\n existing.lastObservedAt = record.observedAt\n existing.eventCount += 1\n return\n }\n const label = stringField(payload, 'label')\n const runtime = stringField(payload, 'runtime')\n const depth = numberField(payload, 'depth')\n const assignmentId = stringField(payload, 'assignmentId')\n const successorOf = stringField(payload, 'successorOf')\n const attemptId = stringField(payload, 'attemptId')\n const startedAt = numberField(payload, 'startedAt')\n nodes.set(key, {\n id: childId,\n ...(event.parentId ? { parentId: event.parentId } : {}),\n runId: event.runId,\n attemptIndex,\n ...(label ? { label } : {}),\n ...(runtime ? { runtime } : {}),\n ...(depth !== undefined ? { depth } : {}),\n ...(assignmentId ? { assignmentId } : {}),\n ...(successorOf ? { successorOf } : {}),\n ...(attemptId ? { attemptId } : {}),\n // A spawn that predates the `startedAt` fact falls back to when the record was observed:\n // the spawn event is emitted synchronously with the spawn, so the two agree to the ms.\n startedAt: startedAt ?? record.observedAt,\n ...(payload && Object.hasOwn(payload, 'identity') ? { identity: payload.identity } : {}),\n ...(payload && Object.hasOwn(payload, 'budget') ? { budget: payload.budget } : {}),\n status: 'running',\n modelCalls: [],\n firstSequence: record.sequence,\n lastSequence: record.sequence,\n firstObservedAt: record.observedAt,\n lastObservedAt: record.observedAt,\n eventCount: 1,\n turnCount: 0,\n })\n}\n\nfunction projectNodeActivity(nodes: Map<string, MutableNode>, record: ObserverRecord): void {\n const event = record.event\n if (event === undefined) return\n if (event.target === 'agent.spawn') return\n const payload = objectRecord(event.payload)\n const nodeId =\n stringField(payload, 'childId') ??\n stringField(payload, 'nodeId') ??\n stringField(payload, 'workerId')\n if (!nodeId) return\n const node = nodes.get(nodeKey(event.runId, nodeId))\n if (!node) return\n node.lastSequence = record.sequence\n node.lastObservedAt = record.observedAt\n node.eventCount += 1\n\n if (event.target !== 'agent.child') return\n const status = stringField(payload, 'status')\n if (status !== 'done' && status !== 'down') return\n node.status = status\n node.settledAt = numberField(payload, 'settledAt') ?? record.observedAt\n const startedAt = numberField(payload, 'startedAt')\n if (startedAt !== undefined) node.startedAt = startedAt\n if (payload && Object.hasOwn(payload, 'spent')) node.spent = spendField(payload, 'spent')\n const metered = spendField(payload, 'metered')\n if (metered)\n node.ownInference = node.ownInference ? addSpend(node.ownInference, metered) : metered\n const runtime = stringField(payload, 'runtime')\n if (runtime) node.runtime = runtime\n const outRef = stringField(payload, 'outRef')\n if (outRef) node.outRef = outRef\n const score = numberField(payload, 'score')\n if (score !== undefined) node.score = score\n const valid = booleanField(payload, 'valid')\n if (valid !== undefined) node.valid = valid\n const reason = stringField(payload, 'reason')\n if (reason) node.reason = reason\n if (status === 'done') node.failure = undefined\n else if (payload && Object.hasOwn(payload, 'failure')) {\n node.failure = runtimeFailureCauseSchema.parse(payload.failure)\n }\n const infra = booleanField(payload, 'infra')\n if (infra !== undefined) node.infra = infra\n const retained = stringField(payload, 'retainedExecution')\n if (retained === 'pending' || retained === 'released' || retained === 'release-unconfirmed') {\n node.retainedExecution = retained\n }\n const cause = stringField(payload, 'retainedPendingCause')\n if (\n cause === 'unobservable' ||\n cause === 'provider-contract' ||\n cause === 'request-rejected' ||\n cause === 'transport' ||\n cause === 'nested-recovery'\n )\n node.retainedPendingCause = cause\n const releasedAt = numberField(payload, 'releasedAt')\n if (releasedAt !== undefined) node.releasedAt = releasedAt\n const budgetViolation = budgetViolationField(payload)\n if (budgetViolation) node.budgetViolation = budgetViolation\n 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, segments, ...rest } = run\n return Object.freeze({\n ...rest,\n ...(segments?.length\n ? { segments: Object.freeze(segments.map((segment) => Object.freeze(segment))) }\n : {}),\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 segments,\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 ...(segments?.length\n ? { segments: Object.freeze(segments.map((segment) => Object.freeze(segment))) }\n : {}),\n ...(modelCalls.length > 0 ? { modelCalls: Object.freeze([...modelCalls]) } : {}),\n ...(total !== undefined ? { usage: usageOf(total, reasoningTokens), cost: costOf(total) } : {}),\n ...(total !== undefined && platformOf(total) !== undefined\n ? { platform: platformOf(total) }\n : {}),\n ...(timing !== undefined ? { timing } : {}),\n })\n}\n\nfunction increment(\n target: Record<string, number>,\n key: RuntimeHookTarget | RuntimeDecisionKind,\n): void {\n target[key] = (target[key] ?? 0) + 1\n}\n\nfunction objectRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n}\n\n/** Read a journaled `Spend` without trusting the wire: a record missing the conserved channels is\n * not a zero-cost turn, it is an unparseable one, and it must not enter a total. */\nfunction spendField(value: Record<string, unknown> | undefined, key: string): Spend | undefined {\n const field = objectRecord(value?.[key])\n if (!field) return undefined\n const tokens = objectRecord(field.tokens)\n if (typeof field.usd !== 'number' || !Number.isFinite(field.usd)) return undefined\n if (!tokens || typeof tokens.input !== 'number' || typeof tokens.output !== 'number') {\n return undefined\n }\n return cloneSpend(field as unknown as Spend)\n}\n\n/** Read a journaled overspend without trusting the wire: one malformed channel drops the record,\n * so an unparseable entry is never reported as an overspend of some size. */\nfunction budgetViolationField(\n value: Record<string, unknown> | undefined,\n): BudgetViolation | undefined {\n const overspent = objectRecord(value?.budgetViolation)?.overspent\n if (!Array.isArray(overspent) || overspent.length === 0) return undefined\n const entries: BudgetOverspend[] = []\n for (const raw of overspent) {\n const entry = objectRecord(raw)\n const channel = stringField(entry, 'channel')\n const reserved = numberField(entry, 'reserved')\n const spent = numberField(entry, 'spent')\n if (channel === undefined || reserved === undefined || spent === undefined) return undefined\n entries.push({ channel: channel as BudgetOverspend['channel'], reserved, spent })\n }\n return { overspent: entries }\n}\n\nfunction stringField(value: Record<string, unknown> | undefined, key: string): string | undefined {\n const field = value?.[key]\n return typeof field === 'string' && field.length > 0 ? field : undefined\n}\n\nfunction numberField(value: Record<string, unknown> | undefined, key: string): number | undefined {\n const field = value?.[key]\n return typeof field === 'number' && Number.isFinite(field) ? field : undefined\n}\n\nfunction booleanField(\n value: Record<string, unknown> | undefined,\n key: string,\n): boolean | undefined {\n const field = value?.[key]\n return typeof field === 'boolean' ? field : undefined\n}\n","import { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { canonicalCandidateDigest, canonicalCandidateJson } from '@tangle-network/agent-interface'\nimport {\n publishExclusiveDurableFile,\n writeAtomicDurableFile,\n} from '../runtime/supervise/durable-file'\nimport type { RootStreamReceipt, SupervisedResult } from '../runtime/supervise/types'\nimport { isNoEntError } from './jsonl-file'\n\n/** Terminal evidence has one result per segment. Reopen archives that result byte for byte;\n * a failed attempt may resume because failure.json records only the latest throw.\n * Serialization, exclusive publication and validation stay with the record operations below.\n */\n\n/** The settle record: the returned `SupervisedResult` as canonical JSON, written once. */\nexport const SETTLE_RECORD_FILE = 'result.json'\n/** The failure record: the most recent throw, replaced by a later throw. */\nexport const FAILURE_RECORD_FILE = 'failure.json'\n\n/** What `failure.json` records about the most recent throw. */\nexport interface DurableFailureRecord {\n readonly runId: string\n readonly pursuitId: string\n /** ISO instant the throw was recorded. */\n readonly at: string\n readonly error: { readonly name: string; readonly message: string }\n /** The root's retained provider stream at the time of the throw, when the directory holds one:\n * a root that died mid-turn keeps what it had streamed, and this names it. */\n readonly rootStream?: RootStreamReceipt\n}\n\n/** The directory already holds a settle record, so the run it records must not be re-entered. */\nexport class SettledRunDirectoryError extends Error {\n readonly path: string\n /** The root of the recorded run, which is its `runId`. */\n readonly recordedRunId: string\n\n constructor(path: string, recordedRunId: string, requestedRunId: string) {\n super(\n recordedRunId === requestedRunId\n ? `supervisePursuit: ${path} records that run '${recordedRunId}' already settled; a settled run is not re-entered unless the call passes reopen: { operator, reason, operationId }`\n : `supervisePursuit: ${path} records that run '${recordedRunId}' already settled in this directory; a directory holds one settle record, so run '${requestedRunId}' needs its own runDir`,\n )\n this.name = 'SettledRunDirectoryError'\n this.path = path\n this.recordedRunId = recordedRunId\n }\n}\n\n/** A result member whose JSON form would misstate it. */\nclass UnrecordableSettleValueError extends TypeError {\n readonly path: string\n\n constructor(path: string, kind: string) {\n super(\n `supervisePursuit: result${path} is a ${kind}, which JSON cannot record faithfully; a settle record holds plain data only`,\n )\n this.name = 'UnrecordableSettleValueError'\n this.path = path\n }\n}\n\nconst PLAIN_PROTOTYPES = new Set<unknown>([Object.prototype, Array.prototype, null])\n\n/**\n * The JSON value of a result, or a throw naming the first member JSON would misstate. An\n * `undefined` member and a function are dropped, exactly as any JSON consumer drops them; a Map,\n * a Set, a Date, a typed array, or a class instance would be rewritten to `{}` or a string and\n * so is refused.\n */\nfunction jsonValue(result: unknown): unknown {\n const seen: unknown[] = []\n const visit = (value: unknown, path: string): void => {\n if (value === null || typeof value !== 'object') return\n if (value instanceof Map) throw new UnrecordableSettleValueError(path, 'Map')\n if (value instanceof Set) throw new UnrecordableSettleValueError(path, 'Set')\n if (value instanceof Date) throw new UnrecordableSettleValueError(path, 'Date')\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n throw new UnrecordableSettleValueError(path, 'binary buffer')\n }\n if (!PLAIN_PROTOTYPES.has(Object.getPrototypeOf(value))) {\n throw new UnrecordableSettleValueError(path, 'class instance')\n }\n if (seen.includes(value)) throw new UnrecordableSettleValueError(path, 'cycle')\n seen.push(value)\n if (Array.isArray(value)) {\n for (const [index, item] of value.entries()) visit(item, `${path}[${index}]`)\n } else {\n for (const [key, item] of Object.entries(value)) visit(item, `${path}.${key}`)\n }\n seen.pop()\n }\n visit(result, '')\n return JSON.parse(JSON.stringify(result))\n}\n\n/**\n * The exact bytes `result.json` holds for a result: its JSON value serialized as RFC 8785\n * canonical JSON. Throws `UnrecordableSettleValueError` before any byte is written when the\n * result carries a value JSON would misstate.\n */\nexport function settleRecordJson(result: unknown): string {\n return canonicalCandidateJson(jsonValue(result))\n}\n\n/** The digest the settle record's bytes hash to: the candidate digest of the result's JSON value. */\nexport function settleRecordDigest(result: unknown): string {\n return canonicalCandidateDigest(jsonValue(result))\n}\n\n/** Publish `result.json` in the run directory once. Throws when a record is already there. */\nexport async function writeSettleRecord(runDir: string, result: unknown): Promise<string> {\n const path = resolve(runDir, SETTLE_RECORD_FILE)\n if (!publishExclusiveDurableFile(path, settleRecordJson(result))) {\n throw new Error(`supervisePursuit: ${path} already exists; a settle record is written once`)\n }\n return path\n}\n\n/** Replace `failure.json` in the run directory with the most recent throw. */\nexport async function writeFailureRecord(\n runDir: string,\n record: DurableFailureRecord,\n): Promise<string> {\n const path = resolve(runDir, FAILURE_RECORD_FILE)\n writeAtomicDurableFile(path, `${JSON.stringify(record, null, 2)}\\n`)\n return path\n}\n\n/**\n * Read the settle record a run directory holds, or `undefined` when it holds none. A file that\n * is present but is not a settle record is corruption and fails loud.\n */\nexport async function readSettleRecord(\n runDir: string,\n): Promise<SupervisedResult<unknown> | undefined> {\n return readTerminalFile(runDir, SETTLE_RECORD_FILE, parseSettleRecord)\n}\n\nasync function readTerminalFile<T>(\n runDir: string,\n file: string,\n parse: (text: string, path: string) => T,\n): Promise<T | undefined> {\n const path = resolve(runDir, file)\n try {\n return parse(await readFile(path, 'utf8'), path)\n } catch (error) {\n if (isNoEntError(error)) return undefined\n throw error\n }\n}\n\nfunction parseTerminalJson(text: string, path: string): unknown {\n try {\n return JSON.parse(text)\n } catch (cause) {\n throw new Error(`supervisePursuit: ${path} is not valid JSON`, { cause })\n }\n}\n\n/** Parse settle-record bytes already read, so a caller hashes and parses the same bytes. */\nexport function parseSettleRecord(text: string, path: string): SupervisedResult<unknown> {\n const parsed = parseTerminalJson(text, path)\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 return readTerminalFile(runDir, FAILURE_RECORD_FILE, (text, path) => {\n const parsed = parseTerminalJson(text, path)\n const record = parsed as Partial<DurableFailureRecord>\n if (\n typeof record !== 'object' ||\n record === null ||\n typeof record.runId !== 'string' ||\n typeof record.pursuitId !== 'string' ||\n typeof record.at !== 'string' ||\n typeof record.error?.name !== 'string' ||\n typeof record.error.message !== 'string' ||\n (record.rootStream !== undefined &&\n (typeof record.rootStream.ref !== 'string' || typeof record.rootStream.events !== 'number'))\n ) {\n throw new Error(`supervisePursuit: ${path} is not a failure record`)\n }\n return parsed as DurableFailureRecord\n })\n}\n","import { resolve } from 'node:path'\nimport { isRecord } from '@tangle-network/agent-core'\nimport type { NodeId } from '../runtime/supervise/types'\nimport { readCommittedJsonLines } from './jsonl-file'\nimport { FileObserverJournal } from './observer-journal'\nimport { spawnJournalRecordEvents } from './spawn-journal/record-events'\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 observer?: { readonly path: string; readonly pursuitId: 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 = Readonly<\n Partial<Record<'kind' | 'root' | 'at' | 'event', unknown>>\n>\n\ntype CoordinationIdentityRecord = Readonly<Partial<Record<'runId' | 'ownerId', unknown>>>\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 nestedRoots = new Set<NodeId>()\n const rootsBegunAt = new Map<NodeId, string | null>()\n for await (const record of readCommittedJsonLines<SpawnJournalIdentityRecord>(spawnJournalPath, {\n allowMissing: true,\n })) {\n if (record.kind === 'begin') {\n if (typeof record.root !== 'string' || record.root.length === 0) {\n throw new Error(`${spawnJournalPath}: begin record has no non-empty string root identity`)\n }\n rootsBegunAt.set(record.root as NodeId, typeof record.at === 'string' ? record.at : null)\n continue\n }\n for (const event of spawnJournalRecordEvents(record)) {\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 for await (const record of readCommittedJsonLines<CoordinationIdentityRecord>(\n coordinationLogPath,\n { allowMissing: true },\n )) {\n if (typeof record.runId !== 'string' || record.runId.length === 0) {\n throw new Error(`${coordinationLogPath}: record has no non-empty string runId identity`)\n }\n const stream = streams.get(record.runId) ?? {\n owners: new Set<string>(),\n unscopedRecords: 0,\n recordCount: 0,\n }\n stream.recordCount += 1\n if (record.ownerId === undefined) {\n stream.unscopedRecords += 1\n } else if (typeof record.ownerId === 'string' && record.ownerId.length > 0) {\n stream.owners.add(record.ownerId)\n } else {\n throw new Error(`${coordinationLogPath}: ownerId must be a non-empty string when present`)\n }\n streams.set(record.runId, stream)\n }\n\n const coordinationStreams = [...streams.entries()]\n .sort(([left], [right]) => compareText(left, right))\n .map(([runId, stream]) =>\n Object.freeze({\n runId,\n ownerIds: Object.freeze([...stream.owners].sort(compareText)),\n unscopedRecords: stream.unscopedRecords,\n recordCount: stream.recordCount,\n }),\n )\n\n const observer = await FileObserverJournal.open(`${canonicalRunDir}/observer.jsonl`)\n const roots = [...rootsBegunAt.keys()].filter((root) => !nestedRoots.has(root)).sort(compareText)\n return Object.freeze({\n runDir: canonicalRunDir,\n ...(observer ? { observer: { path: observer.path, pursuitId: observer.pursuitId } } : {}),\n spawnJournalPath,\n coordinationLogPath,\n roots: Object.freeze(roots),\n rootsBegunAt: Object.freeze(roots.map((root) => rootsBegunAt.get(root) ?? null)),\n coordinationStreams: Object.freeze(coordinationStreams),\n })\n}\n\nfunction compareText(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAqUA,SAAgB,eAAe,SAAuD;CACpF,IAAI,QAAQ,WAAW,GACrB,MAAM,IAAI,UAAU,0DAA0D;CAEhF,MAAM,YAAY,QAAQ,EAAE,CAAE;CAC9B,MAAM,WAAW,sBAAsB,SAAS,SAAS;CACzD,MAAM,2BAAW,IAAI,IAA0B;CAC/C,MAAM,wBAAQ,IAAI,IAAyB;CAC3C,IAAI,aAAa;CACjB,IAAI,gBAAgB;CAEpB,KAAK,MAAM,UAAU,UAAU;EAC7B,MAAM,WAAW,OAAO,SAAS,OAAO;EACxC,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,0BAA0B,OAAO,SAAS,oBAAoB;EAC7F,MAAM,MAAM,eAAe,UAAU,SAAS,OAAO,MAAM;EAC3D,IAAI,eAAe,OAAO;EAC1B,IAAI,iBAAiB,OAAO;EAE5B,IAAI,OAAO,OAAO;GAChB,cAAc;GACd,IAAI,cAAc;GAClB,UAAU,IAAI,SAAS,OAAO,MAAM,MAAM;GAC1C,mBAAmB,KAAK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