@tangle-network/agent-runtime 10.0.1 → 10.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/{activation-s6dGGify.d.ts → activation-DbSxPRUW.d.ts} +2 -2
  3. package/dist/{activation-C_BenzIu.js → activation-kitznAHo.js} +2 -2
  4. package/dist/{activation-C_BenzIu.js.map → activation-kitznAHo.js.map} +1 -1
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +3 -3
  7. package/dist/{continuation-CZaeHEzQ.js → continuation-BDeKJgV3.js} +3 -3
  8. package/dist/{continuation-CZaeHEzQ.js.map → continuation-BDeKJgV3.js.map} +1 -1
  9. package/dist/{delegate-BOren4c7.js → delegate-D8yX_2K7.js} +2 -2
  10. package/dist/{delegate-BOren4c7.js.map → delegate-D8yX_2K7.js.map} +1 -1
  11. package/dist/{driver-control-acknowledgers-ByKwAgCI.js → driver-control-acknowledgers-BTSr3Znq.js} +50 -12
  12. package/dist/driver-control-acknowledgers-BTSr3Znq.js.map +1 -0
  13. package/dist/durable-file-DUcTDWJD.js +498 -0
  14. package/dist/durable-file-DUcTDWJD.js.map +1 -0
  15. package/dist/durable-file-XqOyDf7q.js +1 -0
  16. package/dist/durable-writer-thread.d.ts +1 -0
  17. package/dist/durable-writer-thread.js +86 -0
  18. package/dist/durable-writer-thread.js.map +1 -0
  19. package/dist/durable.d.ts +1 -1
  20. package/dist/durable.js +15 -128
  21. package/dist/durable.js.map +1 -1
  22. package/dist/{graph-BXONYT1o.js → graph-4ep9laIH.js} +8 -8
  23. package/dist/{graph-BXONYT1o.js.map → graph-4ep9laIH.js.map} +1 -1
  24. package/dist/{graph-registry-DxhlgHdA.js → graph-registry-B-EGvJ-3.js} +1 -1
  25. package/dist/{graph-registry-j9t9J0KT.js → graph-registry-BxEBeihr.js} +4 -4
  26. package/dist/{graph-registry-j9t9J0KT.js.map → graph-registry-BxEBeihr.js.map} +1 -1
  27. package/dist/{improve-CS2GIF5O.js → improve-CJf87tBs.js} +8 -8
  28. package/dist/{improve-CS2GIF5O.js.map → improve-CJf87tBs.js.map} +1 -1
  29. package/dist/index.d.ts +3 -3
  30. package/dist/index.js +10 -10
  31. package/dist/intelligence.d.ts +2 -2
  32. package/dist/intelligence.js +4 -4
  33. package/dist/{jsonl-file-BhuxeejY.js → jsonl-file-CVAWegN-.js} +53 -11
  34. package/dist/jsonl-file-CVAWegN-.js.map +1 -0
  35. package/dist/kernel.d.ts +2 -2
  36. package/dist/kernel.js +19 -17
  37. package/dist/{loop-runner-C0B3PexH.d.ts → loop-runner-CayC8e9K.d.ts} +2 -2
  38. package/dist/{loop-runner-ftyZP4st.js → loop-runner-Ckj-Zz3-.js} +2 -2
  39. package/dist/{loop-runner-ftyZP4st.js.map → loop-runner-Ckj-Zz3-.js.map} +1 -1
  40. package/dist/loop-runner-bin.d.ts +1 -1
  41. package/dist/loop-runner-bin.js +1 -1
  42. package/dist/mcp/bin.js +3 -3
  43. package/dist/mcp/index.d.ts +1 -1
  44. package/dist/mcp/index.js +6 -6
  45. package/dist/{model-policy-CqDuBTq-.js → model-policy-DZnL8Yj9.js} +13 -2
  46. package/dist/{model-policy-CqDuBTq-.js.map → model-policy-DZnL8Yj9.js.map} +1 -1
  47. package/dist/profiles.d.ts +1 -1
  48. package/dist/profiles.js +1 -1
  49. package/dist/{provision-supervisor-CauovUHn.js → provision-supervisor-NjROV7AQ.js} +7 -7
  50. package/dist/{provision-supervisor-CauovUHn.js.map → provision-supervisor-NjROV7AQ.js.map} +1 -1
  51. package/dist/result-blob-store-BR-BVZrg.js +76 -0
  52. package/dist/result-blob-store-BR-BVZrg.js.map +1 -0
  53. package/dist/{run-cancellation-NMNVuYiO.js → run-cancellation-C9V1lYhq.js} +5 -209
  54. package/dist/run-cancellation-C9V1lYhq.js.map +1 -0
  55. package/dist/run-lock-Y3u9kwM0.js +193 -0
  56. package/dist/run-lock-Y3u9kwM0.js.map +1 -0
  57. package/dist/run-reopen-CHYTHk7x.js +134 -0
  58. package/dist/run-reopen-CHYTHk7x.js.map +1 -0
  59. package/dist/run-state-DgKo8_tO.js +180 -0
  60. package/dist/run-state-DgKo8_tO.js.map +1 -0
  61. package/dist/{runtime-DYaRDLKn.js → runtime-CdthBQUs.js} +22 -20
  62. package/dist/{runtime-DYaRDLKn.js.map → runtime-CdthBQUs.js.map} +1 -1
  63. package/dist/{search-executor-Drd_N9YO.js → search-executor-Bb0WuI_Z.js} +4 -4
  64. package/dist/{search-executor-Drd_N9YO.js.map → search-executor-Bb0WuI_Z.js.map} +1 -1
  65. package/dist/{server-Dk9B1WFf.js → server-BCtyL7jH.js} +3 -3
  66. package/dist/{server-Dk9B1WFf.js.map → server-BCtyL7jH.js.map} +1 -1
  67. package/dist/{settle-record-YdkkHzqw.js → settle-record-Beh-sXBW.js} +5 -4
  68. package/dist/settle-record-Beh-sXBW.js.map +1 -0
  69. package/dist/{structural-rollout-DbZAkHTq.js → structural-rollout-BRfSDPkv.js} +5 -5
  70. package/dist/{structural-rollout-DbZAkHTq.js.map → structural-rollout-BRfSDPkv.js.map} +1 -1
  71. package/dist/{supervise-B5hb0my3.js → supervise-DTUYxnoJ.js} +10 -9
  72. package/dist/{supervise-B5hb0my3.js.map → supervise-DTUYxnoJ.js.map} +1 -1
  73. package/dist/supervise-identity-eMF-h1uP.js +210 -0
  74. package/dist/supervise-identity-eMF-h1uP.js.map +1 -0
  75. package/dist/{supervision-discovery-ChkTxilL.js → supervision-discovery-CAUsSDno.js} +3 -3
  76. package/dist/{supervision-discovery-ChkTxilL.js.map → supervision-discovery-CAUsSDno.js.map} +1 -1
  77. package/dist/{supervisor-DpwcTrTh.js → supervisor-BtRRFbgF.js} +32 -187
  78. package/dist/supervisor-BtRRFbgF.js.map +1 -0
  79. package/dist/{supervisor-accounting-QiXnF-EW.js → supervisor-accounting-Cuehs4te.js} +60 -113
  80. package/dist/supervisor-accounting-Cuehs4te.js.map +1 -0
  81. package/dist/supervisor-root-contract-CmFKzPps.js +165 -0
  82. package/dist/supervisor-root-contract-CmFKzPps.js.map +1 -0
  83. package/dist/testing.d.ts +1 -1
  84. package/dist/testing.js +11 -11
  85. package/dist/{top-web-E85Fk8pH.js → top-web-D-wuEVdM.js} +7 -6
  86. package/dist/{top-web-E85Fk8pH.js.map → top-web-D-wuEVdM.js.map} +1 -1
  87. package/dist/tui/bin.js +3 -3
  88. package/dist/tui/index.d.ts +1 -1
  89. package/dist/tui/index.js +2 -2
  90. package/dist/{types-dv295cpm.d.ts → types-PBoTtcbX.d.ts} +15 -2
  91. package/package.json +1 -1
  92. package/dist/driver-control-acknowledgers-ByKwAgCI.js.map +0 -1
  93. package/dist/durable-file-CksURHlH.js +0 -1
  94. package/dist/durable-file-DstVeHcj.js +0 -228
  95. package/dist/durable-file-DstVeHcj.js.map +0 -1
  96. package/dist/jsonl-file-BhuxeejY.js.map +0 -1
  97. package/dist/run-cancellation-NMNVuYiO.js.map +0 -1
  98. package/dist/run-state-COyIVOVb.js +0 -357
  99. package/dist/run-state-COyIVOVb.js.map +0 -1
  100. package/dist/settle-record-YdkkHzqw.js.map +0 -1
  101. package/dist/supervisor-DpwcTrTh.js.map +0 -1
  102. package/dist/supervisor-accounting-QiXnF-EW.js.map +0 -1
@@ -0,0 +1,210 @@
1
+ import { tt as deriveNodeExecutionIdentity } from "./supervisor-accounting-Cuehs4te.js";
2
+ import { m as ValidationError } from "./errors-DG8yufqX.js";
3
+ import { l as appendCommittedJsonLine, o as readCommittedJsonLines } from "./jsonl-file-CVAWegN-.js";
4
+ import { n as detachedSnapshot } from "./snapshot-BKI_w3JD.js";
5
+ import { y as captureRunWriteContext } from "./durable-file-DUcTDWJD.js";
6
+ import { agentProfileSchema, canonicalCandidateDigest } from "@tangle-network/agent-interface";
7
+ import { randomUUID } from "node:crypto";
8
+ import { resolve } from "node:path";
9
+ // src/runtime/supervise/coordination-log.ts
10
+ /**
11
+ * Durable side-log for coordination evidence the spawn journal does not own: questions, analyst
12
+ * findings, answer decisions, authorized continuation receipts, delivery-attempt markers, and
13
+ * delivery outcomes. A durable run
14
+ * (`supervise({ runDir })`) appends them as they publish and loads them on resume, so a restarted
15
+ * coordinator retains the exact evidence produced by prior processes.
16
+ *
17
+ * Answer down-events also fold status on load: a question answered before the crash reloads as
18
+ * `answered`, not as a re-blocking `open`. Settled events are skipped (the spawn journal is their
19
+ * ledger). A receipt followed by an attempt but no outcome proves the process died in the delivery
20
+ * window; that outcome remains unknown and no prior instruction is auto-delivered.
21
+ *
22
+ * JSONL, one fsynced record per event, keyed by `runId` — several runs may share one log file
23
+ * exactly as they share one spawn-journal file.
24
+ *
25
+ * @experimental
26
+ */
27
+ /** Persist prior context plus exact continuation authorization, attempt, and result evidence.
28
+ * Settlements have their own journal. */
29
+ function persisted(event) {
30
+ return event.type !== "settled";
31
+ }
32
+ /** FS-backed `CoordinationLog`: append-only JSONL, fsynced per record. */
33
+ var FileCoordinationLog = class {
34
+ path;
35
+ writeContext = captureRunWriteContext();
36
+ appendTail = Promise.resolve();
37
+ constructor(path) {
38
+ this.path = path;
39
+ }
40
+ async append(runId, record, ownerId) {
41
+ if (!persisted(record.event)) return;
42
+ const append = this.appendTail.then(() => this.writeContext(() => this.appendRecord(runId, record, ownerId)));
43
+ this.appendTail = append.catch(() => void 0);
44
+ return append;
45
+ }
46
+ async appendRecord(runId, busRecord, ownerId) {
47
+ const fs = await import("node:fs/promises");
48
+ const { dirname } = await import("node:path");
49
+ await fs.mkdir(dirname(this.path), { recursive: true });
50
+ const record = {
51
+ runId,
52
+ ...ownerId !== void 0 ? { ownerId } : {},
53
+ ...busRecord
54
+ };
55
+ await appendCommittedJsonLine(this.path, record);
56
+ }
57
+ async load(runId, ownerId) {
58
+ return foldCoordinationRecords(readCommittedJsonLines(this.path, { allowMissing: true }), runId, ownerId);
59
+ }
60
+ };
61
+ /** @internal Shared replay semantics for file and SQL coordination evidence. */
62
+ async function foldCoordinationRecords(source, runId, ownerId) {
63
+ const byId = /* @__PURE__ */ new Map();
64
+ const findings = [];
65
+ const escalations = [];
66
+ const analystDefinitions = [];
67
+ const continuations = [];
68
+ const deliveryEvidence = [];
69
+ const mail = [];
70
+ const records = [];
71
+ let legacySeq = 0;
72
+ for await (const stored of source) {
73
+ if (stored.runId !== runId) continue;
74
+ if (ownerId !== void 0 && stored.ownerId !== ownerId) continue;
75
+ const record = "seq" in stored ? {
76
+ seq: stored.seq,
77
+ at: stored.at,
78
+ priority: stored.priority,
79
+ event: stored.event
80
+ } : {
81
+ seq: legacySeq++,
82
+ at: Date.parse(stored.at),
83
+ priority: 0,
84
+ event: stored.event
85
+ };
86
+ records.push(record);
87
+ const ev = record.event;
88
+ if (ev.type === "delivery-attempt" || ev.type === "steer" || ev.type === "answer") deliveryEvidence.push(ev);
89
+ if (ev.type === "question") byId.set(ev.question.id, ev.question);
90
+ else if (ev.type === "finding") findings.push(ev.finding);
91
+ else if (ev.type === "answer") {
92
+ const prior = byId.get(ev.questionId);
93
+ if (prior && ev.down.delivered) byId.set(ev.questionId, {
94
+ ...prior,
95
+ status: "answered",
96
+ decision: {
97
+ kind: "answer",
98
+ answer: ev.down.instruction,
99
+ by: "prior-run"
100
+ }
101
+ });
102
+ } else if (ev.type === "instruction") continuations.push(ev.instruction);
103
+ else if (ev.type === "mail") mail.push(ev.mail);
104
+ else if (ev.type === "escalation") escalations.push(ev.escalation);
105
+ else if (ev.type === "analyst-defined") analystDefinitions.push(ev.analyst);
106
+ }
107
+ return {
108
+ ...ownerId !== void 0 ? { ownerId } : {},
109
+ questions: [...byId.values()],
110
+ findings,
111
+ escalations,
112
+ analystDefinitions,
113
+ continuations,
114
+ deliveryEvidence,
115
+ mail,
116
+ records
117
+ };
118
+ }
119
+ // src/runtime/supervise/supervise-identity.ts
120
+ function externalExecutionId(kind, identity) {
121
+ return `${kind}-${canonicalCandidateDigest({
122
+ kind,
123
+ identity
124
+ }).slice(7)}`;
125
+ }
126
+ function freezeDetached(value) {
127
+ return detachedSnapshot(value, "supervise");
128
+ }
129
+ function freezeDetachedProfile(value) {
130
+ return freezeDetached(agentProfileSchema.parse(value));
131
+ }
132
+ function canonicalExecution(profile, task, rawExecution, context) {
133
+ const execution = rawExecution === void 0 ? void 0 : freezeDetached(rawExecution);
134
+ if (execution !== void 0) {
135
+ if (typeof execution !== "object" || execution === null || Array.isArray(execution)) throw new ValidationError(`${context}: execution must be an object`);
136
+ const unknown = Object.keys(execution).filter((key) => key !== "candidateDigest" && key !== "correlation");
137
+ if (unknown.length > 0) throw new ValidationError(`${context}: unknown execution fields: ${unknown.join(", ")}`);
138
+ }
139
+ const identity = deriveNodeExecutionIdentity({
140
+ profile,
141
+ execution
142
+ }, task);
143
+ if (!identity?.profileDigest || !identity.taskDigest) throw new ValidationError(`${context}: profile and task must be finite, acyclic canonical JSON for durable identity`);
144
+ const ref = identity.candidateDigest || identity.correlation ? Object.freeze({
145
+ ...identity.candidateDigest ? { candidateDigest: identity.candidateDigest } : {},
146
+ ...identity.correlation ? { correlation: identity.correlation } : {}
147
+ }) : void 0;
148
+ return {
149
+ identity,
150
+ ...ref ? { ref } : {}
151
+ };
152
+ }
153
+ function rootCoordinationOwner(identity) {
154
+ return canonicalCandidateDigest({
155
+ kind: "supervisor-root",
156
+ identity
157
+ });
158
+ }
159
+ function childCoordinationOwner(parentOwnerId, identity, context, depth) {
160
+ return canonicalCandidateDigest({
161
+ kind: "supervisor-child",
162
+ parentOwnerId,
163
+ identity,
164
+ assignment: {
165
+ id: context.assignmentId,
166
+ label: context.label,
167
+ key: context.key ?? null,
168
+ depth
169
+ }
170
+ });
171
+ }
172
+ function supervisionRunNamespace(runDir, runId) {
173
+ return canonicalCandidateDigest(runDir === void 0 ? {
174
+ kind: "supervise-ephemeral-run",
175
+ runId,
176
+ nonce: randomUUID()
177
+ } : {
178
+ kind: "supervise-durable-run",
179
+ runId,
180
+ runDir: resolve(runDir)
181
+ });
182
+ }
183
+ function workerAssignmentNamespace(runNamespace, parentOwnerId, assignmentId) {
184
+ return canonicalCandidateDigest({
185
+ kind: "supervise-worker-assignment",
186
+ runNamespace,
187
+ parentOwnerId,
188
+ assignmentId
189
+ });
190
+ }
191
+ /** Hash only durable coordination meaning. Bus sequence/timestamp are delivery metadata and a
192
+ * resumed projection's marker describes the reader, not the original settlement. */
193
+ function coordinationEventId(context, event) {
194
+ const durableEvent = event.type === "settled" && event.worker.resumed === true ? (() => {
195
+ const { resumed: _resumed, ...worker } = event.worker;
196
+ return {
197
+ type: "settled",
198
+ worker
199
+ };
200
+ })() : event;
201
+ return canonicalCandidateDigest({
202
+ kind: "supervise-coordination-event",
203
+ runNamespace: context.runNamespace,
204
+ ownerId: context.ownerId,
205
+ event: detachedSnapshot(durableEvent, "supervise coordination event identity")
206
+ });
207
+ }
208
+ export { freezeDetached as a, supervisionRunNamespace as c, foldCoordinationRecords as d, externalExecutionId as i, workerAssignmentNamespace as l, childCoordinationOwner as n, freezeDetachedProfile as o, coordinationEventId as r, rootCoordinationOwner as s, canonicalExecution as t, FileCoordinationLog as u };
209
+
210
+ //# sourceMappingURL=supervise-identity-eMF-h1uP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"supervise-identity-eMF-h1uP.js","names":[],"sources":["../src/runtime/supervise/coordination-log.ts","../src/runtime/supervise/supervise-identity.ts"],"sourcesContent":["/**\n * Durable side-log for coordination evidence the spawn journal does not own: questions, analyst\n * findings, answer decisions, authorized continuation receipts, delivery-attempt markers, and\n * delivery outcomes. A durable run\n * (`supervise({ runDir })`) appends them as they publish and loads them on resume, so a restarted\n * coordinator retains the exact evidence produced by prior processes.\n *\n * Answer down-events also fold status on load: a question answered before the crash reloads as\n * `answered`, not as a re-blocking `open`. Settled events are skipped (the spawn journal is their\n * ledger). A receipt followed by an attempt but no outcome proves the process died in the delivery\n * window; that outcome remains unknown and no prior instruction is auto-delivered.\n *\n * JSONL, one fsynced record per event, keyed by `runId` — several runs may share one log file\n * exactly as they share one spawn-journal file.\n *\n * @experimental\n */\n\nimport { appendCommittedJsonLine, readCommittedJsonLines } from '../../durable/jsonl-file'\nimport { captureRunWriteContext } from '../../durable/run-fence'\nimport type {\n AnalystFindingEvent,\n DefinedAnalystRecord,\n} from '../../mcp/tools/coordination-analysts'\nimport type { CoordinationEvent } from '../../mcp/tools/coordination-events'\nimport type { ContinuationInstruction } from '../../mcp/tools/coordination-messages'\nimport type {\n QuestionEscalationRecord,\n QuestionRecord,\n} from '../../mcp/tools/coordination-questions'\nimport type { BusRecord } from './event-bus'\nimport type { PeerMailEvent } from './peer-mail'\n\n/** Stable identity of the supervisor that owns one coordination stream. High-level supervision\n * derives it from the exact root/child execution identity plus its parent assignment. */\nexport type CoordinationOwnerId = string\n\n/** Durable delivery evidence retained in commit order. An attempt without a later event carrying\n * the same `receiptId` has an unknown outcome after a crash and is never replayed. */\nexport type CoordinationDeliveryEvidence = Extract<\n CoordinationEvent,\n { readonly type: 'delivery-attempt' | 'steer' | 'answer' }\n>\n\n/** Coordination evidence loaded from prior processes of one durable supervised run. */\nexport interface PriorCoordination {\n /** The owner filter used for this replay. Omitted only for the compatibility all-owner read. */\n readonly ownerId?: CoordinationOwnerId\n /** Every question the prior process raised, with answer-status folded in, raise order. */\n readonly questions: ReadonlyArray<QuestionRecord>\n /** Every analyst finding the prior process published, publish order. */\n readonly findings: ReadonlyArray<AnalystFindingEvent>\n /** Every `ask_parent` escalation the prior process made, raise order. An undelivered one names a\n * question the run raised that nothing above it received — retained so a resuming operator sees\n * it, never auto-redelivered. */\n readonly escalations: ReadonlyArray<QuestionEscalationRecord>\n /** Every lens the prior process DEFINED at run time, definition order. The exact authored bytes\n * and their digest, so an invented lens can be re-registered and any finding it produced can be\n * traced to the words that produced it. Re-registration is the owner's decision, never automatic:\n * the registry may have changed between processes. */\n readonly analystDefinitions: ReadonlyArray<DefinedAnalystRecord>\n /** Every authorized continuation, in commit order. These are evidence, never replayed to a new\n * worker automatically. */\n readonly continuations: ReadonlyArray<ContinuationInstruction>\n /** Delivery intent and result records in commit order, linked to receipts by `receiptId`. */\n readonly deliveryEvidence: ReadonlyArray<CoordinationDeliveryEvidence>\n /** Every peer-mail attempt the prior process made, delivered and refused alike, in commit order.\n * Evidence of what siblings told each other; never replayed into a new worker's inbox. */\n readonly mail: ReadonlyArray<PeerMailEvent>\n /** Exact source-bus stamps in durable append order. Bus `seq` restarts with each process; append\n * order remains the cross-process replay order. */\n readonly records: ReadonlyArray<BusRecord<CoordinationEvent>>\n}\n\n/** The durable coordination side-log seam. `append` records one bus event (kinds it does not\n * persist are ignored); `load` replays a run's prior records folded into `PriorCoordination`. */\nexport interface CoordinationLog {\n append(\n runId: string,\n record: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void>\n load(runId: string, ownerId?: CoordinationOwnerId): Promise<PriorCoordination>\n}\n\ntype CoordinationLogRecord = {\n readonly runId: string\n readonly ownerId?: CoordinationOwnerId\n readonly seq: number\n readonly at: number\n readonly priority: number\n readonly event: CoordinationEvent\n}\n\ntype LegacyCoordinationLogRecord = {\n readonly runId: string\n readonly ownerId?: CoordinationOwnerId\n readonly at: string\n readonly event: CoordinationEvent\n}\n\n/** Persist prior context plus exact continuation authorization, attempt, and result evidence.\n * Settlements have their own journal. */\nfunction persisted(event: CoordinationEvent): boolean {\n return event.type !== 'settled'\n}\n\n/** FS-backed `CoordinationLog`: append-only JSONL, fsynced per record. */\nexport class FileCoordinationLog implements CoordinationLog {\n private readonly writeContext = captureRunWriteContext()\n private appendTail: Promise<void> = Promise.resolve()\n\n constructor(private readonly path: string) {}\n\n async append(\n runId: string,\n record: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void> {\n if (!persisted(record.event)) return\n const append = this.appendTail.then(() =>\n this.writeContext(() => this.appendRecord(runId, record, ownerId)),\n )\n this.appendTail = append.catch(() => undefined)\n return append\n }\n\n private async appendRecord(\n runId: string,\n busRecord: BusRecord<CoordinationEvent>,\n ownerId?: CoordinationOwnerId,\n ): Promise<void> {\n const fs = await import('node:fs/promises')\n const { dirname } = await import('node:path')\n await fs.mkdir(dirname(this.path), { recursive: true })\n const record: CoordinationLogRecord = {\n runId,\n ...(ownerId !== undefined ? { ownerId } : {}),\n ...busRecord,\n }\n await appendCommittedJsonLine(this.path, record)\n }\n\n async load(runId: string, ownerId?: CoordinationOwnerId): Promise<PriorCoordination> {\n return foldCoordinationRecords(\n readCommittedJsonLines<CoordinationLogRecord | LegacyCoordinationLogRecord>(this.path, {\n allowMissing: true,\n }),\n runId,\n ownerId,\n )\n }\n}\n\n/** @internal Shared replay semantics for file and SQL coordination evidence. */\nexport async function foldCoordinationRecords(\n source:\n | Iterable<CoordinationLogRecord | LegacyCoordinationLogRecord>\n | AsyncIterable<CoordinationLogRecord | LegacyCoordinationLogRecord>,\n runId: string,\n ownerId?: CoordinationOwnerId,\n): Promise<PriorCoordination> {\n const byId = new Map<string, QuestionRecord>()\n const findings: AnalystFindingEvent[] = []\n const escalations: QuestionEscalationRecord[] = []\n const analystDefinitions: DefinedAnalystRecord[] = []\n const continuations: ContinuationInstruction[] = []\n const deliveryEvidence: CoordinationDeliveryEvidence[] = []\n const mail: PeerMailEvent[] = []\n const records: BusRecord<CoordinationEvent>[] = []\n let legacySeq = 0\n for await (const stored of source) {\n if (stored.runId !== runId) continue\n // Omitting ownerId preserves the historical all-run read for direct consumers. Runtime always\n // supplies one, so root and nested supervisors never receive one another's evidence.\n if (ownerId !== undefined && stored.ownerId !== ownerId) continue\n const record: BusRecord<CoordinationEvent> =\n 'seq' in stored\n ? {\n seq: stored.seq,\n at: stored.at,\n priority: stored.priority,\n event: stored.event,\n }\n : {\n seq: legacySeq++,\n at: Date.parse(stored.at),\n priority: 0,\n event: stored.event,\n }\n records.push(record)\n const ev = record.event\n if (ev.type === 'delivery-attempt' || ev.type === 'steer' || ev.type === 'answer') {\n deliveryEvidence.push(ev)\n }\n if (ev.type === 'question') {\n byId.set(ev.question.id, ev.question)\n } else if (ev.type === 'finding') {\n findings.push(ev.finding)\n } else if (ev.type === 'answer') {\n // Only accepted delivery resolves a blocking question. Authorization and an attempted\n // refusal remain evidence, but cannot turn \"worker never received the answer\" into answered\n // state on replay. `by` is not on the wire; prior-run is the honest attribution.\n const prior = byId.get(ev.questionId)\n if (prior && ev.down.delivered) {\n byId.set(ev.questionId, {\n ...prior,\n status: 'answered',\n decision: { kind: 'answer', answer: ev.down.instruction, by: 'prior-run' },\n })\n }\n } else if (ev.type === 'instruction') {\n continuations.push(ev.instruction)\n } else if (ev.type === 'mail') {\n mail.push(ev.mail)\n } else if (ev.type === 'escalation') {\n escalations.push(ev.escalation)\n } else if (ev.type === 'analyst-defined') {\n analystDefinitions.push(ev.analyst)\n }\n }\n return {\n ...(ownerId !== undefined ? { ownerId } : {}),\n questions: [...byId.values()],\n findings,\n escalations,\n analystDefinitions,\n continuations,\n deliveryEvidence,\n mail,\n records,\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { resolve } from 'node:path'\nimport {\n type AgentProfile,\n agentProfileSchema,\n canonicalCandidateDigest,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { ValidationError } from '../../errors'\nimport type { WorkerSpawnContext } from '../../mcp/tools/coordination-contracts'\nimport type { CoordinationEvent } from '../../mcp/tools/coordination-events'\nimport { deriveNodeExecutionIdentity } from './scope'\nimport { detachedSnapshot } from './snapshot'\nimport type { SupervisorNodeContext } from './supervisor-agent'\nimport type { AgentExecutionRef, NodeExecutionIdentity } from './types'\n\nexport function externalExecutionId(kind: string, identity: unknown): string {\n const digest = canonicalCandidateDigest({ kind, identity })\n return `${kind}-${digest.slice('sha256:'.length)}`\n}\n\nexport function freezeDetached<T>(value: T): T {\n return detachedSnapshot(value, 'supervise')\n}\n\nexport function freezeDetachedProfile(value: unknown): AgentProfile {\n return freezeDetached(agentProfileSchema.parse(value))\n}\n\nexport function canonicalExecution(\n profile: AgentProfile,\n task: unknown,\n rawExecution: AgentExecutionRef | undefined,\n context: string,\n): { readonly identity: NodeExecutionIdentity; readonly ref?: AgentExecutionRef } {\n const execution = rawExecution === undefined ? undefined : freezeDetached(rawExecution)\n if (execution !== undefined) {\n if (typeof execution !== 'object' || execution === null || Array.isArray(execution)) {\n throw new ValidationError(`${context}: execution must be an object`)\n }\n const unknown = Object.keys(execution).filter(\n (key) => key !== 'candidateDigest' && key !== 'correlation',\n )\n if (unknown.length > 0) {\n throw new ValidationError(`${context}: unknown execution fields: ${unknown.join(', ')}`)\n }\n }\n const identity = deriveNodeExecutionIdentity({ profile, execution }, task)\n if (!identity?.profileDigest || !identity.taskDigest) {\n throw new ValidationError(\n `${context}: profile and task must be finite, acyclic canonical JSON for durable identity`,\n )\n }\n const ref: AgentExecutionRef | undefined =\n identity.candidateDigest || identity.correlation\n ? Object.freeze({\n ...(identity.candidateDigest ? { candidateDigest: identity.candidateDigest } : {}),\n ...(identity.correlation ? { correlation: identity.correlation } : {}),\n })\n : undefined\n return { identity, ...(ref ? { ref } : {}) }\n}\n\nexport function rootCoordinationOwner(identity: NodeExecutionIdentity): string {\n return canonicalCandidateDigest({ kind: 'supervisor-root', identity })\n}\n\nexport function childCoordinationOwner(\n parentOwnerId: string,\n identity: NodeExecutionIdentity,\n context: WorkerSpawnContext,\n depth: number,\n): string {\n return canonicalCandidateDigest({\n kind: 'supervisor-child',\n parentOwnerId,\n identity,\n assignment: {\n id: context.assignmentId,\n label: context.label,\n key: context.key ?? null,\n depth,\n },\n })\n}\n\nexport function supervisionRunNamespace(runDir: string | undefined, runId: string): string {\n return canonicalCandidateDigest(\n runDir === undefined\n ? { kind: 'supervise-ephemeral-run', runId, nonce: randomUUID() }\n : { kind: 'supervise-durable-run', runId, runDir: resolve(runDir) },\n )\n}\n\nexport function workerAssignmentNamespace(\n runNamespace: string,\n parentOwnerId: string,\n assignmentId: string,\n): string {\n return canonicalCandidateDigest({\n kind: 'supervise-worker-assignment',\n runNamespace,\n parentOwnerId,\n assignmentId,\n })\n}\n\n/** Hash only durable coordination meaning. Bus sequence/timestamp are delivery metadata and a\n * resumed projection's marker describes the reader, not the original settlement. */\nexport function coordinationEventId(\n context: SupervisorNodeContext,\n event: CoordinationEvent,\n): Sha256Digest {\n const durableEvent =\n event.type === 'settled' && event.worker.resumed === true\n ? (() => {\n const { resumed: _resumed, ...worker } = event.worker\n return { type: 'settled' as const, worker }\n })()\n : event\n return canonicalCandidateDigest({\n kind: 'supervise-coordination-event',\n runNamespace: context.runNamespace,\n ownerId: context.ownerId,\n event: detachedSnapshot(durableEvent, 'supervise coordination event identity'),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuGA,SAAS,UAAU,OAAmC;CACpD,OAAO,MAAM,SAAS;AACxB;;AAGA,IAAa,sBAAb,MAA4D;CAI7B;CAH7B,eAAgC,uBAAuB;CACvD,aAAoC,QAAQ,QAAQ;CAEpD,YAAY,MAA+B;EAAd,KAAA,OAAA;CAAe;CAE5C,MAAM,OACJ,OACA,QACA,SACe;EACf,IAAI,CAAC,UAAU,OAAO,KAAK,GAAG;EAC9B,MAAM,SAAS,KAAK,WAAW,WAC7B,KAAK,mBAAmB,KAAK,aAAa,OAAO,QAAQ,OAAO,CAAC,CACnE;EACA,KAAK,aAAa,OAAO,YAAY,KAAA,CAAS;EAC9C,OAAO;CACT;CAEA,MAAc,aACZ,OACA,WACA,SACe;EACf,MAAM,KAAK,MAAM,OAAO;EACxB,MAAM,EAAE,YAAY,MAAM,OAAO;EACjC,MAAM,GAAG,MAAM,QAAQ,KAAK,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;EACtD,MAAM,SAAgC;GACpC;GACA,GAAI,YAAY,KAAA,IAAY,EAAE,QAAQ,IAAI,CAAC;GAC3C,GAAG;EACL;EACA,MAAM,wBAAwB,KAAK,MAAM,MAAM;CACjD;CAEA,MAAM,KAAK,OAAe,SAA2D;EACnF,OAAO,wBACL,uBAA4E,KAAK,MAAM,EACrF,cAAc,KAChB,CAAC,GACD,OACA,OACF;CACF;AACF;;AAGA,e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AAc,EAAE,aAAa,SAAS,YAAY,IAAI,CAAC;CACtE,CAAC,IACD,KAAA;CACN,OAAO;EAAE;EAAU,GAAI,MAAM,EAAE,IAAI,IAAI,CAAC;CAAG;AAC7C;AAEA,SAAgB,sBAAsB,UAAyC;CAC7E,OAAO,yBAAyB;EAAE,MAAM;EAAmB;CAAS,CAAC;AACvE;AAEA,SAAgB,uBACd,eACA,UACA,SACA,OACQ;CACR,OAAO,yBAAyB;EAC9B,MAAM;EACN;EACA;EACA,YAAY;GACV,IAAI,QAAQ;GACZ,OAAO,QAAQ;GACf,KAAK,QAAQ,OAAO;GACpB;EACF;CACF,CAAC;AACH;AAEA,SAAgB,wBAAwB,QAA4B,OAAuB;CACzF,OAAO,yBACL,WAAW,KAAA,IACP;EAAE,MAAM;EAA2B;EAAO,OAAO,WAAW;CAAE,IAC9D;EAAE,MAAM;EAAyB;EAAO,QAAQ,QAAQ,MAAM;CAAE,CACtE;AACF;AAEA,SAAgB,0BACd,cACA,eACA,cACQ;CACR,OAAO,yBAAyB;EAC9B,MAAM;EACN;EACA;EACA;CACF,CAAC;AACH;;;AAIA,SAAgB,oBACd,SACA,OACc;CACd,MAAM,eACJ,MAAM,SAAS,aAAa,MAAM,OAAO,YAAY,cAC1C;EACL,MAAM,EAAE,SAAS,UAAU,GAAG,WAAW,MAAM;EAC/C,OAAO;GAAE,MAAM;GAAoB;EAAO;CAC5C,EAAA,CAAG,IACH;CACN,OAAO,yBAAyB;EAC9B,MAAM;EACN,cAAc,QAAQ;EACtB,SAAS,QAAQ;EACjB,OAAO,iBAAiB,cAAc,uCAAuC;CAC/E,CAAC;AACH"}
@@ -1,5 +1,5 @@
1
- import { K as spawnJournalRecordEvents, Pn as verifyObserverRecords, jn as FileObserverJournal } from "./supervisor-accounting-QiXnF-EW.js";
2
- import { a as readCommittedJsonLines } from "./jsonl-file-BhuxeejY.js";
1
+ import { In as verifyObserverRecords, Nn as FileObserverJournal, X as spawnJournalRecordEvents } from "./supervisor-accounting-Cuehs4te.js";
2
+ import { o as readCommittedJsonLines } from "./jsonl-file-CVAWegN-.js";
3
3
  import { T as zeroSpend, a as cloneSpend, n as addSpend } from "./util-qsH5cC9S.js";
4
4
  import { Ot as recordValue, r as runtimeFailureCauseSchema } from "./failure-cause-DoCCGLDH.js";
5
5
  import { isRecord } from "@tangle-network/agent-core";
@@ -614,4 +614,4 @@ function compareText(left, right) {
614
614
  }
615
615
  export { projectPursuit as n, discoverDurableSupervisionRun as t };
616
616
 
617
- //# sourceMappingURL=supervision-discovery-ChkTxilL.js.map
617
+ //# sourceMappingURL=supervision-discovery-CAUsSDno.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"supervision-discovery-ChkTxilL.js","names":[],"sources":["../src/durable/observer-projection.ts","../src/durable/supervision-discovery.ts"],"sourcesContent":["import { recordValue } from '../record-value'\nimport { 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 = recordValue(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 = recordValue(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 = recordValue(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 = recordValue(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 = recordValue(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 recordValue(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 = recordValue(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\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 = recordValue(value?.[key])\n if (!field) return undefined\n const tokens = recordValue(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 = recordValue(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 = recordValue(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 { 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":";;;;;;;;;;;;;;;;;;;;;;;;;AAsUA,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,MAAM;GAC9B,iBAAiB,OAAO,QAAQ,IAAI,YAAY;GAChD,oBAAoB,OAAO,MAAM;GACjC,YAAY,KAAK,OAAO,MAAM;GAC9B,YAAY,KAAK,OAAO,MAAM;EAChC,OAAO,IAAI,OAAO,UAAU;GAC1B,iBAAiB;GACjB,IAAI,iBAAiB;GACrB,UAAU,IAAI,WAAW,OAAO,SAAS,IAAI;EAC/C;CACF;CAEA,MAAM,4BAAY,IAAI,IAA2B;CACjD,KAAK,MAAM,QAAQ,MAAM,OAAO,GAAG;EACjC,MAAM,MAAM,WAAW,KAAK,OAAO,KAAK,YAAY;EACpD,MAAM,OAAO,U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AO,mBAAmB;CACxD,CAAC;AACH;AAEA,SAAS,YAAY,MAAc,OAAuB;CACxD,OAAO,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI;AAChD"}
1
+ {"version":3,"file":"supervision-discovery-CAUsSDno.js","names":[],"sources":["../src/durable/observer-projection.ts","../src/durable/supervision-discovery.ts"],"sourcesContent":["import { recordValue } from '../record-value'\nimport { 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 = recordValue(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 = recordValue(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 = recordValue(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 = recordValue(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 = recordValue(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 recordValue(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 = recordValue(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\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 = recordValue(value?.[key])\n if (!field) return undefined\n const tokens = recordValue(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 = recordValue(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 = recordValue(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 { 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":";;;;;;;;;;;;;;;;;;;;;;;;;AAsUA,SAAgB,eAAe,SAAuD;CACpF,IAAI,QAAQ,WAAW,GACrB,MAAM,IAAI,UAAU,0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