@tangle-network/agent-eval 0.174.0 → 0.176.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +1 -1
  3. package/dist/adapters/http.d.ts +1 -1
  4. package/dist/agent-profile-cell-0gSi5ffD.js +374 -0
  5. package/dist/agent-profile-cell-0gSi5ffD.js.map +1 -0
  6. package/dist/analyst/index.d.ts +3 -3
  7. package/dist/analyst/index.js +4 -4
  8. package/dist/{benchmark-command-mZIlR-ra.js → benchmark-command-yPqjcZnC.js} +7 -7
  9. package/dist/{benchmark-command-mZIlR-ra.js.map → benchmark-command-yPqjcZnC.js.map} +1 -1
  10. package/dist/benchmarks/index.d.ts +1 -1
  11. package/dist/benchmarks/index.js +3 -3
  12. package/dist/campaign/index.d.ts +3 -3
  13. package/dist/campaign/index.js +9 -9
  14. package/dist/{campaign-BzMSCejE.js → campaign-85igdlgG.js} +12 -12
  15. package/dist/{campaign-BzMSCejE.js.map → campaign-85igdlgG.js.map} +1 -1
  16. package/dist/campaign-evidence-D8DBLqLI.js +2083 -0
  17. package/dist/campaign-evidence-D8DBLqLI.js.map +1 -0
  18. package/dist/{opencode-sqlite-eK6HW6dr.js → claude-jsonl-CxZZrDJ3.js} +9 -149
  19. package/dist/claude-jsonl-CxZZrDJ3.js.map +1 -0
  20. package/dist/cli.js +9 -2
  21. package/dist/cli.js.map +1 -1
  22. package/dist/contract/index.d.ts +4 -4
  23. package/dist/contract/index.js +9 -9
  24. package/dist/{default-registry-CrAp0pYq.js → default-registry-DBqVI4pq.js} +2 -2
  25. package/dist/{default-registry-CrAp0pYq.js.map → default-registry-DBqVI4pq.js.map} +1 -1
  26. package/dist/{define-agent-eval-V1jQyCDR.d.ts → define-agent-eval-CCbl8k2E.d.ts} +11 -4
  27. package/dist/define-agent-eval-CCbl8k2E.d.ts.map +1 -0
  28. package/dist/{define-agent-eval-ox5McL6e.js → define-agent-eval-DEMsu5eA.js} +54 -36
  29. package/dist/define-agent-eval-DEMsu5eA.js.map +1 -0
  30. package/dist/{dspy-rlm-engine-Caz2pl4L.js → dspy-rlm-engine-DqjER2sV.js} +2 -2
  31. package/dist/{dspy-rlm-engine-Caz2pl4L.js.map → dspy-rlm-engine-DqjER2sV.js.map} +1 -1
  32. package/dist/{eval-campaign-BeAjdhzC.js → eval-campaign-Cs-7MiCs.js} +4 -5
  33. package/dist/{eval-campaign-BeAjdhzC.js.map → eval-campaign-Cs-7MiCs.js.map} +1 -1
  34. package/dist/experiment/index.d.ts +3 -68
  35. package/dist/experiment/index.d.ts.map +1 -1
  36. package/dist/experiment/index.js +6 -128
  37. package/dist/experiment/index.js.map +1 -1
  38. package/dist/{attestation-XSUpbc4o.js → experiment-tracker-BKEumQug.js} +2 -96
  39. package/dist/experiment-tracker-BKEumQug.js.map +1 -0
  40. package/dist/{attestation-c1QvaBdX.d.ts → experiment-tracker-CNwqCZFD.d.ts} +2 -78
  41. package/dist/experiment-tracker-CNwqCZFD.d.ts.map +1 -0
  42. package/dist/{external-optimizer-process-CxnFL1hd.js → external-optimizer-process-Dlz8YxrT.js} +3 -3
  43. package/dist/{external-optimizer-process-CxnFL1hd.js.map → external-optimizer-process-Dlz8YxrT.js.map} +1 -1
  44. package/dist/{external-optimizer-subprocess-CQi27uEI.js → external-optimizer-subprocess-q3VzlGAO.js} +2 -2
  45. package/dist/{external-optimizer-subprocess-CQi27uEI.js.map → external-optimizer-subprocess-q3VzlGAO.js.map} +1 -1
  46. package/dist/{index-Bn-nlnSV.d.ts → index-BAAiSF3_.d.ts} +2 -2
  47. package/dist/{index-Bn-nlnSV.d.ts.map → index-BAAiSF3_.d.ts.map} +1 -1
  48. package/dist/{index-DKXuBPXf.d.ts → index-Bg6OT2Dd.d.ts} +23 -10
  49. package/dist/{index-DKXuBPXf.d.ts.map → index-Bg6OT2Dd.d.ts.map} +1 -1
  50. package/dist/{index-BTrx5s8m.d.ts → index-DBkcm_9H.d.ts} +4 -4
  51. package/dist/{index-BTrx5s8m.d.ts.map → index-DBkcm_9H.d.ts.map} +1 -1
  52. package/dist/{index-D-UdhAmg.d.ts → index-u0d1Jp4F.d.ts} +4 -2
  53. package/dist/{index-D-UdhAmg.d.ts.map → index-u0d1Jp4F.d.ts.map} +1 -1
  54. package/dist/index.d.ts +5 -5
  55. package/dist/index.js +15 -16
  56. package/dist/index.js.map +1 -1
  57. package/dist/{integrity-BWywb34E.js → integrity-DsHWCebQ.js} +11 -435
  58. package/dist/integrity-DsHWCebQ.js.map +1 -0
  59. package/dist/ledger-core/index.d.ts +2 -2
  60. package/dist/ledger-core/index.js +2 -2
  61. package/dist/{ledger-core-PIfjCbKn.js → ledger-core-Cs9f7385.js} +60 -47
  62. package/dist/{ledger-core-PIfjCbKn.js.map → ledger-core-Cs9f7385.js.map} +1 -1
  63. package/dist/{llm-judge-DmNaBrXB.js → llm-judge-DliimmRb.js} +994 -1517
  64. package/dist/llm-judge-DliimmRb.js.map +1 -0
  65. package/dist/{mint-vWOdD8Ae.js → mint-Cc1_zwRQ.js} +2 -2
  66. package/dist/{mint-vWOdD8Ae.js.map → mint-Cc1_zwRQ.js.map} +1 -1
  67. package/dist/openapi.json +1 -1
  68. package/dist/opencode-sqlite-CNw3vubS.js +145 -0
  69. package/dist/opencode-sqlite-CNw3vubS.js.map +1 -0
  70. package/dist/{produced-state-B8mw6zj9.js → produced-state-DrMqa2HD.js} +3 -2
  71. package/dist/{produced-state-B8mw6zj9.js.map → produced-state-DrMqa2HD.js.map} +1 -1
  72. package/dist/profile-cell.js +1 -268
  73. package/dist/{promotion-policy-LY9mVQ7W.js → promotion-policy-DWOm70gx.js} +2 -2
  74. package/dist/{promotion-policy-LY9mVQ7W.js.map → promotion-policy-DWOm70gx.js.map} +1 -1
  75. package/dist/{release-confidence-BsGEg_xg.js → release-confidence-BcGCclTB.js} +2 -2
  76. package/dist/{release-confidence-BsGEg_xg.js.map → release-confidence-BcGCclTB.js.map} +1 -1
  77. package/dist/report-command-DKlXfU5r.js +1528 -0
  78. package/dist/report-command-DKlXfU5r.js.map +1 -0
  79. package/dist/reporting.js +2 -2
  80. package/dist/{reward-hacking-CKW4teig.js → reward-hacking-D0XwhVWE.js} +2 -215
  81. package/dist/reward-hacking-D0XwhVWE.js.map +1 -0
  82. package/dist/rl.js +5 -4
  83. package/dist/rl.js.map +1 -1
  84. package/dist/rollout/index.js +4 -3
  85. package/dist/{rollout-C-znbbYg.js → rollout-DmoJVqrF.js} +4 -3
  86. package/dist/{rollout-C-znbbYg.js.map → rollout-DmoJVqrF.js.map} +1 -1
  87. package/dist/run-record-CR63CpHK.js +216 -0
  88. package/dist/run-record-CR63CpHK.js.map +1 -0
  89. package/dist/{run-record-ZIsR9Fif.js → run-record-DQpSf7t-.js} +2 -2
  90. package/dist/{run-record-ZIsR9Fif.js.map → run-record-DQpSf7t-.js.map} +1 -1
  91. package/dist/{semantic-concept-judge-E3s_fEjB.js → semantic-concept-judge-Dw-f7TEs.js} +3 -3
  92. package/dist/{semantic-concept-judge-E3s_fEjB.js.map → semantic-concept-judge-Dw-f7TEs.js.map} +1 -1
  93. package/dist/{sequential-B51qAYE4.js → sequential-B5gXgcyp.js} +3 -3
  94. package/dist/{sequential-B51qAYE4.js.map → sequential-B5gXgcyp.js.map} +1 -1
  95. package/dist/{skillopt-optimization-method-f7399oGb.js → skillopt-optimization-method-CV7go7ex.js} +6 -749
  96. package/dist/skillopt-optimization-method-CV7go7ex.js.map +1 -0
  97. package/dist/{statistical-heldout-Cqb73yE9.d.ts → statistical-heldout-Z9NROFFS.d.ts} +156 -3
  98. package/dist/statistical-heldout-Z9NROFFS.d.ts.map +1 -0
  99. package/dist/{summary-report-Bgh8CpNK.js → summary-report-B16xy9Kd.js} +2 -2
  100. package/dist/{summary-report-Bgh8CpNK.js.map → summary-report-B16xy9Kd.js.map} +1 -1
  101. package/dist/supervisor-run/index.d.ts +71 -6
  102. package/dist/supervisor-run/index.d.ts.map +1 -1
  103. package/dist/supervisor-run/index.js +6 -1357
  104. package/dist/supervisor-run/index.js.map +1 -1
  105. package/dist/terminal-record-Ce9_UjRz.js +539 -0
  106. package/dist/terminal-record-Ce9_UjRz.js.map +1 -0
  107. package/dist/traces.js +1 -1
  108. package/dist/{types-CoPUTiXb.d.ts → types-vUdAx2Cj.d.ts} +65 -3
  109. package/dist/types-vUdAx2Cj.d.ts.map +1 -0
  110. package/docs/public-api.md +62 -39
  111. package/docs/search-history-receipts.md +48 -1
  112. package/package.json +1 -1
  113. package/dist/attestation-XSUpbc4o.js.map +0 -1
  114. package/dist/attestation-c1QvaBdX.d.ts.map +0 -1
  115. package/dist/define-agent-eval-V1jQyCDR.d.ts.map +0 -1
  116. package/dist/define-agent-eval-ox5McL6e.js.map +0 -1
  117. package/dist/integrity-BWywb34E.js.map +0 -1
  118. package/dist/llm-judge-DmNaBrXB.js.map +0 -1
  119. package/dist/opencode-sqlite-eK6HW6dr.js.map +0 -1
  120. package/dist/power-preflight-CFXm0Vjo.js +0 -502
  121. package/dist/power-preflight-CFXm0Vjo.js.map +0 -1
  122. package/dist/pre-registration-D94b7Of5.js +0 -110
  123. package/dist/pre-registration-D94b7Of5.js.map +0 -1
  124. package/dist/profile-cell.js.map +0 -1
  125. package/dist/reward-hacking-CKW4teig.js.map +0 -1
  126. package/dist/skillopt-optimization-method-f7399oGb.js.map +0 -1
  127. package/dist/statistical-heldout-Cqb73yE9.d.ts.map +0 -1
  128. package/dist/types-CoPUTiXb.d.ts.map +0 -1
@@ -1,544 +1,9 @@
1
- import { o as summarizeNumberSeries } from "../descriptive-1V17A-qa.js";
2
- import { c as parseClaudeEntries, n as findOpencodeSessionsByDirectory, r as openOpencodeDb, t as DEFAULT_OPENCODE_DB, u as transcriptFromEntries } from "../opencode-sqlite-eK6HW6dr.js";
3
- import { a as parseJsonl, c as SUPERVISOR_RUN_INTEGRITY_SCHEMA, i as parseJson, n as supervisorRunRolloutLines, o as parseSupervisorTree, r as asRecord, s as workerSourceKey, t as analyzeSupervisorRunIntegrity } from "../integrity-BWywb34E.js";
1
+ import { i as parseClaudeEntries, o as transcriptFromEntries } from "../claude-jsonl-CxZZrDJ3.js";
2
+ import { n as supervisorRunRolloutLines, r as SUPERVISOR_RUN_INTEGRITY_SCHEMA, t as analyzeSupervisorRunIntegrity } from "../integrity-DsHWCebQ.js";
3
+ import { a as SUPERVISOR_RUN_ROLLUP_SCHEMA, c as showMeasured, i as NO_SOURCE_LIMITS, l as unavailable, n as RUNTIME_FAILED_STATUS, o as SUPERVISOR_RUN_SCHEMA, p as parseSupervisorTree, r as readTerminalRecord, s as isUnavailable, t as NO_TERMINAL_RECORD } from "../terminal-record-Ce9_UjRz.js";
4
+ import { _ as parsePatch, a as loopsSupervisorRunReader, c as writeSupervisorRunReport, d as readRuntimeSupervisorRun, f as runtimeSupervisorRunReader, g as analyzeSupervisorRunSources, h as renderSupervisorRunMarkdown, i as findSupervisorRunDirs, l as writeSupervisorRunReportSafe, m as renderSupervisorRunHeadline, n as analyzeSupervisorRun, o as readLoopsSupervisorRun, p as renderSupervisorRollupMarkdown, r as findSupervisorRunDirIn, s as reportSupervisorRound, t as runSupervisorRunCommand, u as isRuntimeSupervisorRunDir, v as rollupSupervisorRuns } from "../report-command-DKlXfU5r.js";
4
5
  import { basename, dirname, join } from "node:path";
5
- import { appendFile, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
6
- //#region src/supervisor-run/types.ts
7
- function unavailable(reason) {
8
- return { unavailable: reason };
9
- }
10
- function isUnavailable(v) {
11
- return typeof v === "object" && v !== null && typeof v.unavailable === "string";
12
- }
13
- /** Render a measured scalar for the markdown/headline: `0` and `unavailable` stay distinct. */
14
- function showMeasured(v) {
15
- if (isUnavailable(v)) return `unavailable — ${v.unavailable}`;
16
- if (v === null) return "null";
17
- return String(v);
18
- }
19
- /** A source that carries every fact the analyzer can use. */
20
- const NO_SOURCE_LIMITS = {
21
- managerTokens: null,
22
- workerTokens: null,
23
- spendUsd: null,
24
- workerVerdicts: null,
25
- deliverables: null
26
- };
27
- const SUPERVISOR_RUN_SCHEMA = "tangle.supervisor-run@1";
28
- const SUPERVISOR_RUN_ROLLUP_SCHEMA = "tangle.supervisor-run-rollup@1";
29
- //#endregion
30
- //#region src/supervisor-run/analyze.ts
31
- /**
32
- * The pure analyzer. Takes already-read bytes (`SupervisorRunSources`) and
33
- * returns the report — every metric derivable from a synthetic journal string
34
- * with no filesystem, no process, and no network. All I/O lives in a reader
35
- * (`loops-reader.ts` is one).
36
- */
37
- const NO_CACHE_COUNTERS = "the journal carries no cache-token counters for this role";
38
- const NO_CACHE_BREAKDOWN = "Runtime recorded cacheBreakdownKnown:false — the provider reported a total without splitting cache reads from writes";
39
- /**
40
- * Analyze already-read supervisor-run bytes. Pure and synchronous: same bytes
41
- * in, same report out (modulo `generatedAt`, which `now` pins in tests).
42
- */
43
- function analyzeSupervisorRunSources(src, now = Date.now) {
44
- const gaps = [];
45
- const gap = (what, reason) => {
46
- gaps.push(`${what}: ${reason}`);
47
- return unavailable(reason);
48
- };
49
- const journalMissing = src.journalMissingReason ?? (src.supRunDir === null ? "no supervisor run dir under <ws>/.agent/supervisor (or legacy <ws>/.loops/supervisor)" : "journal.jsonl absent");
50
- const haveJournal = src.journal !== null;
51
- const tree = parseSupervisorTree(src);
52
- const state = tree.state;
53
- const result = parseJson(src.result);
54
- const judge = parseJson(src.judge);
55
- const { rootId, workerSpawns, workerCloses, startedAt, completedAt } = tree;
56
- const rootSpawn = rootId === null ? null : tree.spawns.find((spawn) => spawn.id === rootId) ?? null;
57
- const spawnById = new Map(workerSpawns.map((spawn) => [spawn.id, spawn]));
58
- const spawnsByLabel = /* @__PURE__ */ new Map();
59
- for (const spawn of workerSpawns) {
60
- const matches = spawnsByLabel.get(spawn.label) ?? [];
61
- matches.push(spawn);
62
- spawnsByLabel.set(spawn.label, matches);
63
- }
64
- const spawnsForSource = (worker) => {
65
- if (worker.workerId === void 0) return spawnsByLabel.get(worker.label) ?? [];
66
- const spawn = spawnById.get(worker.workerId);
67
- return spawn === void 0 ? [] : [spawn];
68
- };
69
- const spawnForSource = (worker) => {
70
- const matches = spawnsForSource(worker);
71
- return matches.length === 1 ? matches[0] ?? null : null;
72
- };
73
- const wallSpanStart = startedAt ?? tree.firstEventAt;
74
- const wallSpanEnd = tree.lastEventAt;
75
- let supervisorWallMs;
76
- let supervisorWallSource;
77
- if (startedAt !== null && completedAt !== null && completedAt >= startedAt) {
78
- supervisorWallMs = completedAt - startedAt;
79
- supervisorWallSource = "stamps";
80
- } else if (completedAt === null && wallSpanStart !== null && wallSpanEnd !== null && wallSpanEnd >= wallSpanStart) {
81
- supervisorWallMs = wallSpanEnd - wallSpanStart;
82
- supervisorWallSource = "journal-span";
83
- } else {
84
- const reason = !haveJournal ? journalMissing : "no parseable start/complete timestamps in state.json or journal";
85
- supervisorWallMs = gap("supervisorWallMs", reason);
86
- supervisorWallSource = unavailable(reason);
87
- }
88
- const wallEndAt = completedAt ?? (supervisorWallSource === "journal-span" ? wallSpanEnd : null);
89
- const steerRows = [];
90
- let steerQueuedTotal = 0;
91
- let steerDeliveredTotal = 0;
92
- let upLegMessages = 0;
93
- if (src.workers !== null) for (const w of src.workers) {
94
- const facts = tree.workerLogs.get(workerSourceKey(w));
95
- const queued = facts?.steersQueued ?? null;
96
- const delivered = facts?.steersDelivered ?? null;
97
- upLegMessages += facts?.questions ?? 0;
98
- if (queued !== null && delivered !== null) steerRows.push({
99
- workerId: w.workerId ?? null,
100
- worker: w.label,
101
- queued,
102
- delivered
103
- });
104
- if (queued !== null) steerQueuedTotal += queued;
105
- if (delivered !== null) steerDeliveredTotal += delivered;
106
- }
107
- const workersGapReason = src.workersMissingReason ?? "workers/ directory absent";
108
- const unavailableReasons = (pick) => {
109
- const reasons = tree.workerLogRows.map((facts) => pick(facts)).filter((reason) => reason !== null);
110
- return reasons.length === 0 ? null : `exact steer accounting unavailable for ${reasons.length} worker row(s): ${[...new Set(reasons)].join(" | ")}`;
111
- };
112
- const queuedGapReason = unavailableReasons((facts) => facts.steersQueuedUnavailable);
113
- const deliveredGapReason = unavailableReasons((facts) => facts.steersDeliveredUnavailable);
114
- const workerEventsGapReason = unavailableReasons((facts) => !facts.eventsCaptured ? "events absent" : facts.eventsInvalidRows > 0 ? "events contain malformed rows" : null);
115
- const steers = src.workers === null ? gap("steers", workersGapReason) : queuedGapReason === null ? steerQueuedTotal : gap("steers", queuedGapReason);
116
- const steersDelivered = src.workers === null ? unavailable(workersGapReason) : deliveredGapReason === null ? steerDeliveredTotal : unavailable(deliveredGapReason);
117
- const steersByWorker = src.workers === null ? unavailable(workersGapReason) : queuedGapReason === null && deliveredGapReason === null ? steerRows : unavailable(queuedGapReason ?? deliveredGapReason ?? workersGapReason);
118
- const driverSteerCalls = src.driverLog === null ? gap("driverSteerCalls", "driver.log absent") : Math.max(0, (src.driverLog.match(/supervisor_steer/g) ?? []).length - registrationMentions(src.driverLog));
119
- const timeline = [];
120
- for (const s of workerSpawns) if (s.at !== null) timeline.push({
121
- at: s.at,
122
- delta: 1
123
- });
124
- for (const c of workerCloses) if (c.at !== null) timeline.push({
125
- at: c.at,
126
- delta: -1
127
- });
128
- timeline.sort((a, b) => a.at - b.at || a.delta - b.delta);
129
- let waves = 0;
130
- const waveSizes = [];
131
- let closedSinceWaveStart = true;
132
- for (const step of timeline) if (step.delta === 1) {
133
- if (closedSinceWaveStart) {
134
- waves += 1;
135
- waveSizes.push(0);
136
- closedSinceWaveStart = false;
137
- }
138
- waveSizes[waveSizes.length - 1] = (waveSizes[waveSizes.length - 1] ?? 0) + 1;
139
- } else closedSinceWaveStart = true;
140
- let live = 0;
141
- let maxConcurrency = 0;
142
- let idleMs = 0;
143
- let sumWorkerWallMs = 0;
144
- let prev = startedAt;
145
- for (const step of timeline) {
146
- if (prev !== null && step.at >= prev) {
147
- const span = step.at - prev;
148
- if (live === 0) idleMs += span;
149
- sumWorkerWallMs += span * live;
150
- }
151
- live += step.delta;
152
- if (live > maxConcurrency) maxConcurrency = live;
153
- prev = step.at;
154
- }
155
- if (prev !== null && wallEndAt !== null && wallEndAt >= prev) {
156
- const span = wallEndAt - prev;
157
- if (live === 0) idleMs += span;
158
- sumWorkerWallMs += span * live;
159
- }
160
- const firstWorkerSpawnAt = workerSpawns.reduce((acc, s) => s.at === null ? acc : acc === null ? s.at : Math.min(acc, s.at), null);
161
- const closeById = new Map(workerCloses.map((close) => [close.id, close]));
162
- const childSpawnsByParent = /* @__PURE__ */ new Map();
163
- for (const spawn of workerSpawns) {
164
- if (spawn.parent === null) continue;
165
- const siblings = childSpawnsByParent.get(spawn.parent) ?? [];
166
- siblings.push(spawn);
167
- childSpawnsByParent.set(spawn.parent, siblings);
168
- }
169
- let respawns = 0;
170
- let observeThenRespawn = 0;
171
- let respawnWithoutEvidence = 0;
172
- const repeatedLabelSet = /* @__PURE__ */ new Set();
173
- for (const siblings of childSpawnsByParent.values()) {
174
- const labelCounts = /* @__PURE__ */ new Map();
175
- for (const spawn of siblings) labelCounts.set(spawn.label, (labelCounts.get(spawn.label) ?? 0) + 1);
176
- for (const [label, count] of labelCounts) if (count > 1) repeatedLabelSet.add(label);
177
- const orderedSpawns = siblings.map((spawn, index) => ({
178
- spawn,
179
- index
180
- })).filter((row) => row.spawn.at !== null).sort((a, b) => a.spawn.at - b.spawn.at || a.index - b.index);
181
- const directCloseTimes = siblings.map((spawn) => closeById.get(spawn.id)?.at ?? null).filter((at) => at !== null).sort((a, b) => a - b);
182
- const firstDirectClose = directCloseTimes[0] ?? null;
183
- for (let i = 1; i < orderedSpawns.length; i += 1) {
184
- const previous = orderedSpawns[i - 1]?.spawn.at;
185
- const current = orderedSpawns[i]?.spawn.at;
186
- if (previous === void 0 || current === void 0) continue;
187
- if (firstDirectClose === null || current <= firstDirectClose) continue;
188
- respawns += 1;
189
- if (hasNumberBetween(directCloseTimes, previous, current)) observeThenRespawn += 1;
190
- else respawnWithoutEvidence += 1;
191
- }
192
- }
193
- const repeatedLabels = [...repeatedLabelSet];
194
- const parentOf = new Map(tree.spawns.map((s) => [s.id, s.parent]));
195
- let delegationDepth = 0;
196
- for (const s of workerSpawns) {
197
- let d = 0;
198
- let cur = s.id;
199
- const seen = /* @__PURE__ */ new Set();
200
- while (cur !== null && cur !== rootId && !seen.has(cur)) {
201
- seen.add(cur);
202
- d += 1;
203
- cur = parentOf.get(cur) ?? null;
204
- }
205
- if (d > delegationDepth) delegationDepth = d;
206
- }
207
- const orchestration = {
208
- workersSpawned: haveJournal ? workerSpawns.length : gap("workersSpawned", journalMissing),
209
- workersSettled: haveJournal ? workerCloses.filter((c) => c.kind === "settled").length : unavailable(journalMissing),
210
- workersCancelled: haveJournal ? workerCloses.filter((c) => c.kind === "cancelled").length : unavailable(journalMissing),
211
- steers,
212
- steersDelivered,
213
- steersByWorker,
214
- driverSteerCalls,
215
- waves: haveJournal ? waves : unavailable(journalMissing),
216
- waveSizes: haveJournal ? waveSizes : unavailable(journalMissing),
217
- maxConcurrency: haveJournal ? maxConcurrency : unavailable(journalMissing),
218
- respawns: haveJournal ? respawns : unavailable(journalMissing),
219
- repeatedLabels: haveJournal ? repeatedLabels : unavailable(journalMissing),
220
- delegationDepth: haveJournal ? delegationDepth : unavailable(journalMissing),
221
- timeToFirstSpawnMs: startedAt !== null && firstWorkerSpawnAt !== null ? firstWorkerSpawnAt - startedAt : haveJournal ? unavailable("no worker spawn timestamps") : unavailable(journalMissing),
222
- supervisorWallMs,
223
- supervisorWallSource,
224
- idleMs: isUnavailable(supervisorWallMs) ? unavailable(supervisorWallMs.unavailable) : idleMs,
225
- idlePct: isUnavailable(supervisorWallMs) || supervisorWallMs === 0 ? isUnavailable(supervisorWallMs) ? unavailable(supervisorWallMs.unavailable) : unavailable("supervisor wall is 0ms") : round(idleMs / supervisorWallMs * 100, 1),
226
- workerUtilization: isUnavailable(supervisorWallMs) || supervisorWallMs === 0 ? isUnavailable(supervisorWallMs) ? unavailable(supervisorWallMs.unavailable) : unavailable("supervisor wall is 0ms") : round(sumWorkerWallMs / supervisorWallMs, 3)
227
- };
228
- const settledByStatus = {};
229
- const settledVerdicts = {};
230
- for (const c of workerCloses) {
231
- const key = c.status ?? "unknown";
232
- settledByStatus[key] = (settledByStatus[key] ?? 0) + 1;
233
- if (c.verdict !== null) settledVerdicts[c.verdict] = (settledVerdicts[c.verdict] ?? 0) + 1;
234
- }
235
- const verdictLimit = src.limits.workerVerdicts;
236
- const deliverablesLimit = src.limits.deliverables;
237
- let accepted = 0;
238
- let emptyPass = 0;
239
- let evidenceBytes = 0;
240
- const sourceVerdicts = [];
241
- for (const w of src.workers ?? []) {
242
- const f = tree.workerLogs.get(workerSourceKey(w));
243
- if (f?.finished) evidenceBytes += f.evidenceBytes;
244
- const spawn = spawnForSource(w);
245
- const passed = (spawn === null ? null : closeById.get(spawn.id) ?? null)?.valid ?? f?.passed ?? null;
246
- if (passed !== null) sourceVerdicts.push(passed);
247
- if (passed === true) if (deliverablesLimit !== null || (w.patchBytes ?? f?.finishedPatchBytes ?? 0) > 0) accepted += 1;
248
- else emptyPass += 1;
249
- }
250
- const settledCloses = workerCloses.filter((close) => close.kind === "settled");
251
- const structuredVerdicts = settledCloses.map((close) => close.valid).filter((valid) => valid !== null);
252
- const journalVerdictsComplete = settledCloses.length > 0 && structuredVerdicts.length === settledCloses.length;
253
- const sourceVerdictsComplete = sourceVerdicts.length > 0 && sourceVerdicts.length >= settledCloses.length;
254
- const rejected = journalVerdictsComplete ? structuredVerdicts.filter((valid) => !valid).length : sourceVerdictsComplete ? sourceVerdicts.filter((valid) => !valid).length : 0;
255
- const rejectedLimit = journalVerdictsComplete || sourceVerdictsComplete ? null : settledCloses.length > 0 ? verdictLimit ?? "a settled journal verdict has no validity and no matched worker log" : verdictLimit !== null ? verdictLimit : !haveJournal && src.workers === null ? workersGapReason : null;
256
- const decision = {
257
- settledByStatus: haveJournal ? settledByStatus : gap("settledByStatus", journalMissing),
258
- settledVerdicts: verdictLimit !== null ? unavailable(verdictLimit) : haveJournal ? settledVerdicts : unavailable(journalMissing),
259
- accepted: verdictLimit !== null ? gap("accepted", verdictLimit) : src.workers === null ? unavailable(workersGapReason) : accepted,
260
- rejected: rejectedLimit === null ? rejected : unavailable(rejectedLimit),
261
- emptyPass: verdictLimit !== null ? gap("emptyPass", verdictLimit) : deliverablesLimit !== null ? gap("emptyPass", deliverablesLimit) : src.workers === null ? unavailable(workersGapReason) : emptyPass,
262
- observeThenRespawn: haveJournal ? observeThenRespawn : unavailable(journalMissing),
263
- respawnWithoutEvidence: haveJournal ? respawnWithoutEvidence : unavailable(journalMissing),
264
- reviewActions: src.workers === null ? unavailable(workersGapReason) : queuedGapReason === null ? steerQueuedTotal + upLegMessages : unavailable(queuedGapReason),
265
- workerEvidenceBytes: src.workers === null ? unavailable(workersGapReason) : workerEventsGapReason === null ? evidenceBytes : unavailable(workerEventsGapReason)
266
- };
267
- const rootChildIds = new Set(workerSpawns.filter((spawn) => spawn.parent === rootId).map((spawn) => spawn.id));
268
- const rootChildCloses = workerCloses.filter((close) => rootChildIds.has(close.id));
269
- const rootChildSpends = rootChildCloses.filter((close) => close.hasSpend);
270
- const workerUsdUnknownNodes = rootChildSpends.filter((close) => !close.spend.usdKnown).map((close) => close.id);
271
- const workerTokensUnknownNodes = rootChildSpends.filter((close) => !close.spend.tokensKnown).map((close) => close.id);
272
- const workerTokenSpends = rootChildSpends.filter((close) => close.spend.tokensKnown);
273
- const journalWorkerIn = workerTokenSpends.reduce((a, c) => a + c.spend.tokens.input, 0);
274
- const journalWorkerOut = workerTokenSpends.reduce((a, c) => a + c.spend.tokens.output, 0);
275
- const journalWorkerUsd = rootChildSpends.filter((close) => close.spend.usdKnown).reduce((a, c) => a + c.spend.usd, 0);
276
- const usdUnknownIds = new Set(workerCloses.filter((close) => close.hasSpend && !close.spend.usdKnown).map((c) => c.id));
277
- const workerUsdById = /* @__PURE__ */ new Map();
278
- for (const c of workerCloses) {
279
- if (usdUnknownIds.has(c.id)) continue;
280
- workerUsdById.set(c.id, (workerUsdById.get(c.id) ?? 0) + c.spend.usd);
281
- }
282
- const labelById = new Map(workerSpawns.map((spawn) => [spawn.id, spawn.label]));
283
- const usdUnknownLabels = new Set([...usdUnknownIds].map((id) => labelById.get(id)).filter((l) => l !== void 0));
284
- const workerUsdByLabel = /* @__PURE__ */ new Map();
285
- for (const close of workerCloses) {
286
- const label = labelById.get(close.id);
287
- if (label === void 0 || usdUnknownLabels.has(label)) continue;
288
- workerUsdByLabel.set(label, (workerUsdByLabel.get(label) ?? 0) + close.spend.usd);
289
- }
290
- const brainUsdUnknownNodes = tree.brain.usdUnknownCount > 0 && rootId !== null ? [rootId] : [];
291
- const brainTokensUnknownNodes = tree.brain.tokensUnknownCount > 0 && rootId !== null ? [rootId] : [];
292
- const usdKnownRecords = tree.brain.usdKnownCount + rootChildSpends.filter((close) => close.spend.usdKnown).length;
293
- const usdUnknownRecords = tree.brain.usdUnknownCount + workerUsdUnknownNodes.length;
294
- const usdUnknownNodes = [...brainUsdUnknownNodes, ...workerUsdUnknownNodes];
295
- const NAMED_NODE_LIMIT = 5;
296
- const nameNodes = (nodes) => {
297
- if (nodes.length === 0) return "";
298
- const shown = nodes.slice(0, NAMED_NODE_LIMIT);
299
- const rest = nodes.length - shown.length;
300
- return ` (${shown.join(", ")}${rest === 0 ? "" : ` +${rest} more`})`;
301
- };
302
- const unpriced = (unknown, total, nodes) => `Runtime recorded usdKnown:false on ${unknown} of ${total} spend record(s)${nameNodes(nodes)}`;
303
- const unreportedTokens = (unknown, total, nodes) => `Runtime recorded tokensKnown:false on ${unknown} of ${total} spend record(s)${nameNodes(nodes)}`;
304
- const usdPartial = usdKnownRecords > 0 && usdUnknownRecords > 0;
305
- const usdAllUnknown = usdKnownRecords === 0 && usdUnknownRecords > 0;
306
- const brainTokensUnreported = tree.brain.tokensUnknownCount === 0 ? null : unreportedTokens(tree.brain.tokensUnknownCount, tree.brain.meteredCount, brainTokensUnknownNodes);
307
- const brainUsdUnreported = tree.brain.usdKnownCount > 0 || tree.brain.usdUnknownCount === 0 ? null : unpriced(tree.brain.usdUnknownCount, tree.brain.meteredCount, brainUsdUnknownNodes);
308
- const workerUsdUnreported = workerUsdUnknownNodes.length === 0 || workerUsdUnknownNodes.length < rootChildSpends.length ? null : unpriced(workerUsdUnknownNodes.length, rootChildSpends.length, workerUsdUnknownNodes);
309
- const sq = src.harnessWorkerTokens;
310
- const harnessGapReason = src.harnessMissingReason ?? "harness session store unavailable and journal settled spend is 0";
311
- const workerTokenLimit = src.limits.workerTokens;
312
- const workerTokensUnreported = workerTokensUnknownNodes.length === 0 ? null : unreportedTokens(workerTokensUnknownNodes.length, rootChildSpends.length, workerTokensUnknownNodes);
313
- const workerIn = workerTokenLimit !== null ? gap("workers.tokensIn", workerTokenLimit) : workerTokensUnreported !== null ? gap("workers.tokensIn", workerTokensUnreported) : sq !== null ? journalWorkerIn + sq.input : haveJournal ? journalWorkerIn : gap("workers.tokensIn", harnessGapReason);
314
- const workerOut = workerTokenLimit !== null ? unavailable(workerTokenLimit) : workerTokensUnreported !== null ? unavailable(workerTokensUnreported) : sq !== null ? journalWorkerOut + sq.output : haveJournal ? journalWorkerOut : unavailable(harnessGapReason);
315
- const stateResult = asRecord(state?.result);
316
- const stateUsd = typeof stateResult.spentUsd === "number" ? stateResult.spentUsd : null;
317
- const resultSpentTotal = asRecord(result?.spentTotal);
318
- const resultCloseUsd = typeof resultSpentTotal.usd === "number" && Number.isFinite(resultSpentTotal.usd) ? resultSpentTotal.usd : null;
319
- const closeUsd = stateUsd ?? resultCloseUsd;
320
- const usdLimit = src.limits.spendUsd;
321
- const closeUsdUnreported = stateUsd === null && resultCloseUsd !== null && resultSpentTotal.usdKnown === false;
322
- const usdUnreportedReason = unpriced(usdUnknownRecords, usdKnownRecords + usdUnknownRecords, usdUnknownNodes);
323
- const totalUsd = usdLimit !== null ? gap("totalUsd", usdLimit) : stateUsd !== null ? round(stateUsd, 6) : !haveJournal ? gap("totalUsd", journalMissing) : usdUnknownRecords > 0 ? gap("totalUsd", usdUnreportedReason) : round(tree.brain.usd + journalWorkerUsd, 6);
324
- const journalSpendRecords = usdKnownRecords;
325
- const journalDerivedAvailable = usdLimit === null && haveJournal && !usdAllUnknown;
326
- const closeRecordAvailable = usdLimit === null && closeUsd !== null && !closeUsdUnreported;
327
- const spend = {
328
- journalDerived: {
329
- usd: journalDerivedAvailable ? round(tree.brain.usd + journalWorkerUsd, 6) : unavailable(usdLimit ?? (haveJournal ? usdUnreportedReason : journalMissing)),
330
- records: journalDerivedAvailable ? journalSpendRecords : 0,
331
- unknownRecords: usdLimit === null && haveJournal ? usdUnknownRecords : 0,
332
- partial: journalDerivedAvailable && usdPartial,
333
- unknownNodes: usdLimit === null && haveJournal ? usdUnknownNodes : []
334
- },
335
- closeRecord: {
336
- usd: closeRecordAvailable ? round(closeUsd, 6) : unavailable(usdLimit ?? (closeUsdUnreported ? "close record incomplete: result.json spentTotal.usdKnown is false" : "no close record: neither state.json result.spentUsd nor result.json spentTotal.usd is present")),
337
- records: closeRecordAvailable ? 1 : 0,
338
- unknownRecords: closeUsdUnreported ? 1 : 0,
339
- partial: false,
340
- unknownNodes: closeUsdUnreported && rootId !== null ? [rootId] : []
341
- }
342
- };
343
- const perWorker = (src.workers ?? []).map((w) => {
344
- const f = tree.workerLogs.get(workerSourceKey(w));
345
- const matchingSpawns = spawnsForSource(w);
346
- const spawn = spawnForSource(w);
347
- const close = spawn === null ? null : closeById.get(spawn.id) ?? null;
348
- const passed = close?.valid ?? f?.passed ?? null;
349
- const matchingRoles = new Set(matchingSpawns.map((candidate) => candidate.role));
350
- const matchingRuntimes = new Set(matchingSpawns.map((candidate) => candidate.runtime));
351
- const matchingProfiles = new Set(matchingSpawns.map((candidate) => candidate.profileDigest));
352
- const journalWallMs = spawn?.at !== null && spawn?.at !== void 0 && close?.at !== null && close?.at !== void 0 && close.at >= spawn.at ? close.at - spawn.at : null;
353
- return {
354
- workerId: w.workerId ?? null,
355
- worker: w.label,
356
- role: matchingRoles.size === 1 ? matchingSpawns[0]?.role ?? null : null,
357
- runtime: matchingRuntimes.size === 1 ? matchingSpawns[0]?.runtime ?? null : null,
358
- profileDigest: matchingProfiles.size === 1 ? matchingSpawns[0]?.profileDigest ?? null : null,
359
- status: close?.status ?? null,
360
- failure: close?.reason ?? null,
361
- infra: close?.infra ?? null,
362
- wallMs: f?.started != null && f.finishedAt != null ? f.finishedAt - f.started : journalWallMs,
363
- tokensIn: w.tokensIn ?? (close?.hasSpend === true && close.spend.tokensKnown ? close.spend.tokens.input : null),
364
- tokensOut: w.tokensOut ?? (close?.hasSpend === true && close.spend.tokensKnown ? close.spend.tokens.output : null),
365
- usd: usdLimit !== null ? null : w.workerId === void 0 ? workerUsdByLabel.get(w.label) ?? null : workerUsdById.get(w.workerId) ?? null,
366
- patchBytes: w.patchBytes ?? f?.finishedPatchBytes ?? null,
367
- passed,
368
- score: close?.score ?? f?.score ?? null
369
- };
370
- });
371
- const wallDistribution = summarizeNumberSeries(perWorker.map((w) => w.wallMs).filter((w) => w !== null));
372
- const brainCalls = parseJsonl(src.brainLog);
373
- const managerTokenLimit = src.limits.managerTokens;
374
- const economics = {
375
- brain: {
376
- tokensIn: managerTokenLimit !== null ? gap("brain.tokensIn", managerTokenLimit) : !haveJournal ? gap("brain.tokensIn", journalMissing) : brainTokensUnreported !== null ? gap("brain.tokensIn", brainTokensUnreported) : tree.brain.tokensIn,
377
- tokensOut: managerTokenLimit !== null ? unavailable(managerTokenLimit) : !haveJournal ? unavailable(journalMissing) : brainTokensUnreported !== null ? unavailable(brainTokensUnreported) : tree.brain.tokensOut,
378
- usd: usdLimit !== null ? unavailable(usdLimit) : !haveJournal ? unavailable(journalMissing) : brainUsdUnreported !== null ? unavailable(brainUsdUnreported) : round(tree.brain.usd, 6),
379
- cacheRead: managerTokenLimit !== null ? unavailable(managerTokenLimit) : !haveJournal ? unavailable(journalMissing) : brainTokensUnreported !== null ? unavailable(brainTokensUnreported) : !tree.brain.hasCache ? unavailable(NO_CACHE_COUNTERS) : tree.brain.cacheBreakdownKnown ? tree.brain.cacheRead : unavailable(NO_CACHE_BREAKDOWN),
380
- cacheWrite: managerTokenLimit !== null ? unavailable(managerTokenLimit) : !haveJournal ? unavailable(journalMissing) : brainTokensUnreported !== null ? unavailable(brainTokensUnreported) : !tree.brain.hasCache ? unavailable(NO_CACHE_COUNTERS) : tree.brain.cacheBreakdownKnown ? tree.brain.cacheWrite : unavailable(NO_CACHE_BREAKDOWN),
381
- source: managerTokenLimit ?? (haveJournal ? `journal metered events (n=${tree.brain.meteredCount})${tree.brain.usdKnownCount > 0 && tree.brain.usdUnknownCount > 0 ? ` — ${tree.brain.usdUnknownCount} unpriced` : ""}` : journalMissing)
382
- },
383
- brainTruncations: src.brainLog === null ? gap("brain.brainTruncations", src.brainLogMissingReason ?? (src.supRunDir === null ? "no supervisor run dir under <ws>/.agent/supervisor (or legacy <ws>/.loops/supervisor)" : "brain.jsonl absent — loops predates the brain-call tap, so truncation cannot be ruled out")) : brainCalls.filter((c) => c.finish_reason === "length").length,
384
- workers: {
385
- tokensIn: workerIn,
386
- tokensOut: workerOut,
387
- cacheRead: workerTokenLimit !== null ? unavailable(workerTokenLimit) : sq?.cacheRead !== void 0 ? sq.cacheRead : unavailable(NO_CACHE_COUNTERS),
388
- cacheWrite: workerTokenLimit !== null ? unavailable(workerTokenLimit) : sq?.cacheWrite !== void 0 ? sq.cacheWrite : unavailable(NO_CACHE_COUNTERS),
389
- usd: usdLimit !== null ? unavailable(usdLimit) : !haveJournal ? unavailable(journalMissing) : workerUsdUnreported !== null ? unavailable(workerUsdUnreported) : round(journalWorkerUsd, 6),
390
- source: `${workerTokenLimit !== null ? workerTokenLimit : sq !== null ? `journal settled spend + ${sq.store} sessions (n=${sq.sessions})` : `journal settled spend only — ${src.harnessMissingReason ?? "harness session store unavailable"}`}${workerUsdUnknownNodes.length > 0 && workerUsdUnknownNodes.length < rootChildSpends.length ? ` — ${workerUsdUnknownNodes.length} unpriced` : ""}`
391
- },
392
- spend,
393
- totalUsd,
394
- totalUsdSource: usdLimit !== null ? usdLimit : stateUsd !== null ? `state.json result.spentUsd${rootChildCloses.length > 0 && journalWorkerUsd === 0 ? " — brain-priced only; worker CLI inference is unpriced (see worker token counts)" : ""}` : !haveJournal ? journalMissing : usdUnknownRecords > 0 ? usdUnreportedReason : "journal metered + settled usd",
395
- costPerAcceptedPatchUsd: isUnavailable(totalUsd) ? unavailable(totalUsd.unavailable) : isUnavailable(decision.accepted) ? unavailable(decision.accepted.unavailable) : decision.accepted === 0 ? unavailable("no accepted worker patch (cost has no denominator)") : round(totalUsd / decision.accepted, 6),
396
- workerWallMsDistribution: wallDistribution === null ? unavailable(src.workers === null ? workersGapReason : "no worker start/finish pairs captured") : wallDistribution,
397
- perWorker: src.workers === null ? unavailable(workersGapReason) : perWorker
398
- };
399
- const patchStats = src.patch === null ? gap("patch", src.limits.deliverables ?? "delivered patch file absent") : parsePatch(src.patch);
400
- const outcome = {
401
- supStatus: pickString(state, "status") ?? pickString(result, "sup_status") ?? gap("supStatus", "no state.json / result.json status"),
402
- supVerdict: pickString(state, "verdict") ?? pickString(result, "sup_verdict") ?? unavailable("no state.json / result.json verdict"),
403
- delivered: typeof stateResult.delivered === "boolean" ? stateResult.delivered : typeof result?.delivered === "boolean" ? result.delivered : unavailable("no delivered flag in state.json or result.json"),
404
- judgeResolved: judge === null ? gap("judge", "judge.json absent") : typeof judge.resolved === "boolean" ? judge.resolved : null,
405
- judgeScore: judge === null ? unavailable("judge.json absent") : typeof judge.score === "number" ? judge.score : null,
406
- judgePassed: judge === null ? unavailable("judge.json absent") : typeof judge.passed === "number" ? judge.passed : null,
407
- judgeTotal: judge === null ? unavailable("judge.json absent") : typeof judge.total === "number" ? judge.total : null,
408
- verifyPass: typeof result?.verify_pass === "boolean" ? result.verify_pass : gap("verifyPass", "result.json absent or has no verify_pass"),
409
- verifyRc: typeof result?.verify_rc === "number" ? result.verify_rc : unavailable("result.json absent or has no verify_rc"),
410
- patch: patchStats,
411
- judgeSource: src.judgeSource
412
- };
413
- return {
414
- schema: SUPERVISOR_RUN_SCHEMA,
415
- runRef: src.runRef,
416
- instanceId: src.instanceId,
417
- arm: src.arm,
418
- supervisorId: rootId !== null ? rootId : unavailable(journalMissing),
419
- supervisorProfileDigest: rootSpawn?.profileDigest !== null && rootSpawn?.profileDigest !== void 0 ? rootSpawn.profileDigest : gap("supervisorProfileDigest", "root spawned event has no profile digest"),
420
- generatedAt: new Date(now()).toISOString(),
421
- orchestration,
422
- decision,
423
- economics,
424
- outcome,
425
- gaps,
426
- traceCommand: src.traceCommand ?? "npx --yes @tangle-network/traces@latest analyze --harness opencode --cwd <worker-clone-cwd>"
427
- };
428
- }
429
- /** Whether sorted values contain one value in the inclusive interval. */
430
- function hasNumberBetween(sorted, low, high) {
431
- let left = 0;
432
- let right = sorted.length;
433
- while (left < right) {
434
- const middle = left + Math.floor((right - left) / 2);
435
- if (sorted[middle] < low) left = middle + 1;
436
- else right = middle;
437
- }
438
- return left < sorted.length && sorted[left] <= high;
439
- }
440
- /** `[driver] registered tools: …supervisor_steer…` is a banner, not an invocation. */
441
- function registrationMentions(driverLog) {
442
- let n = 0;
443
- for (const line of driverLog.split("\n")) if (line.includes("registered tools:") && line.includes("supervisor_steer")) n += 1;
444
- return n;
445
- }
446
- function pickString(rec, key) {
447
- const v = rec?.[key];
448
- return typeof v === "string" ? v : null;
449
- }
450
- function round(v, digits) {
451
- const f = 10 ** digits;
452
- return Math.round(v * f) / f;
453
- }
454
- /** Unified-diff stats. Counts `+++ b/<path>` targets, body +/- lines, and test-file touches. */
455
- function parsePatch(text) {
456
- const files = /* @__PURE__ */ new Set();
457
- const testFiles = /* @__PURE__ */ new Set();
458
- let added = 0;
459
- let removed = 0;
460
- for (const line of text.split("\n")) {
461
- if (line.startsWith("+++ ")) {
462
- const p = line.slice(4).trim().replace(/^b\//, "");
463
- if (p !== "/dev/null") {
464
- files.add(p);
465
- if (isTestPath(p)) testFiles.add(p);
466
- }
467
- continue;
468
- }
469
- if (line.startsWith("--- ") || line.startsWith("diff --git") || line.startsWith("index ")) continue;
470
- if (line.startsWith("+")) added += 1;
471
- else if (line.startsWith("-")) removed += 1;
472
- }
473
- return {
474
- files: files.size,
475
- linesAdded: added,
476
- linesRemoved: removed,
477
- testFilesTouched: [...testFiles].sort()
478
- };
479
- }
480
- function isTestPath(p) {
481
- const base = p.split("/").pop() ?? p;
482
- return /(^|\/)(tests?|__tests__|testing|spec)(\/|$)/.test(p) || /\.(test|spec)\.[cm]?[jt]sx?$/.test(base) || /^test_.*\.py$/.test(base) || /_test\.py$/.test(base);
483
- }
484
- /**
485
- * Aggregate many supervisor-run reports. A metric no run could measure stays
486
- * `unavailable` rather than becoming a 0-valued mean, and cells whose steer
487
- * count was unavailable are counted separately from cells that measured zero.
488
- */
489
- function rollupSupervisorRuns(reports) {
490
- const known = (vals) => vals.filter((v) => !isUnavailable(v));
491
- const steerVals = known(reports.map((r) => r.orchestration.steers));
492
- const waveVals = known(reports.map((r) => r.orchestration.waves));
493
- const concVals = known(reports.map((r) => r.orchestration.maxConcurrency));
494
- const utilVals = known(reports.map((r) => r.orchestration.workerUtilization));
495
- const idleVals = known(reports.map((r) => r.orchestration.idlePct));
496
- const spawnVals = known(reports.map((r) => r.orchestration.workersSpawned));
497
- const acceptVals = known(reports.map((r) => r.decision.accepted));
498
- const usdVals = known(reports.map((r) => r.economics.totalUsd));
499
- const journalSpendVals = known(reports.map((r) => r.economics.spend.journalDerived.usd));
500
- const closeSpendVals = known(reports.map((r) => r.economics.spend.closeRecord.usd));
501
- const resolvedVals = known(reports.map((r) => r.outcome.judgeResolved));
502
- const sum = (xs) => xs.reduce((a, b) => a + b, 0);
503
- const mean = (xs) => xs.length === 0 ? unavailable("no cell reported this metric") : round(sum(xs) / xs.length, 3);
504
- const perCell = reports.map((r) => ({
505
- instanceId: r.instanceId,
506
- arm: r.arm,
507
- steers: r.orchestration.steers,
508
- waves: r.orchestration.waves,
509
- utilization: r.orchestration.workerUtilization,
510
- idlePct: r.orchestration.idlePct,
511
- resolved: r.outcome.judgeResolved,
512
- usd: r.economics.totalUsd
513
- }));
514
- return {
515
- schema: SUPERVISOR_RUN_ROLLUP_SCHEMA,
516
- cells: reports.length,
517
- steersTotal: steerVals.length === 0 ? unavailable("no cell reported a steer count") : sum(steerVals),
518
- cellsWithSteers: steerVals.length === 0 ? unavailable("no cell reported a steer count") : steerVals.filter((n) => n > 0).length,
519
- cellsWithUnavailableSteers: reports.filter((r) => isUnavailable(r.orchestration.steers)).length,
520
- wavesMean: mean(waveVals),
521
- maxConcurrencyMax: concVals.length === 0 ? unavailable("no cell reported concurrency") : Math.max(...concVals),
522
- utilizationMean: mean(utilVals),
523
- idlePctMean: mean(idleVals),
524
- workersSpawnedTotal: spawnVals.length === 0 ? unavailable("no cell reported spawns") : sum(spawnVals),
525
- acceptedTotal: acceptVals.length === 0 ? unavailable("no cell reported acceptance") : sum(acceptVals),
526
- usdTotal: usdVals.length === 0 ? unavailable("no cell reported spend") : round(sum(usdVals), 6),
527
- spendUsd: {
528
- journalDerived: {
529
- value: journalSpendVals.length === 0 ? unavailable("no cell measured journal-derived spend") : round(sum(journalSpendVals), 6),
530
- runs: journalSpendVals.length
531
- },
532
- closeRecord: {
533
- value: closeSpendVals.length === 0 ? unavailable("no cell carried a close record") : round(sum(closeSpendVals), 6),
534
- runs: closeSpendVals.length
535
- }
536
- },
537
- resolvedCount: resolvedVals.length === 0 ? unavailable("no cell reported a judge verdict") : resolvedVals.filter((v) => v === true).length,
538
- perCell
539
- };
540
- }
541
- //#endregion
6
+ import { readFile, readdir } from "node:fs/promises";
542
7
  //#region src/supervisor-run/claude-code-reader.ts
543
8
  /**
544
9
  * Supervision-tree reader over a THIRD-PARTY harness: Claude Code.
@@ -1017,822 +482,6 @@ function claudeCodeSupervisorRunReader(opts) {
1017
482
  };
1018
483
  }
1019
484
  //#endregion
1020
- //#region src/supervisor-run/render.ts
1021
- /**
1022
- * Human-readable renderings of a supervisor-run report. Zero and unavailable
1023
- * render differently on purpose (`0` vs `unavailable — <reason>`), because the
1024
- * two have driven opposite conclusions about the same architecture.
1025
- */
1026
- /**
1027
- * The block appended to a run log after every run — the answers an operator asks
1028
- * for, in the log tail, with no extra command.
1029
- */
1030
- function renderSupervisorRunHeadline(r) {
1031
- const o = r.orchestration;
1032
- const steerNote = isUnavailable(o.steers) ? `unavailable — ${o.steers.unavailable}` : o.steers === 0 ? "0 (spawn→wait→respawn only; no mid-task steering)" : `${o.steers} queued / ${showMeasured(o.steersDelivered)} delivered`;
1033
- return [
1034
- `RUN-REPORT ${r.instanceId ?? "?"} [${r.arm ?? "?"}]`,
1035
- ` steers=${steerNote}`,
1036
- ` waves=${showMeasured(o.waves)} sizes=${isUnavailable(o.waveSizes) ? `unavailable — ${o.waveSizes.unavailable}` : `[${o.waveSizes.join(",")}]`} workers=${showMeasured(o.workersSpawned)} settled=${showMeasured(o.workersSettled)} cancelled=${showMeasured(o.workersCancelled)}`,
1037
- ` concurrency max=${showMeasured(o.maxConcurrency)} utilization=${showMeasured(o.workerUtilization)} idle=${fmtMs(o.idleMs)} (${showMeasured(o.idlePct)}%) wall=${fmtMs(o.supervisorWallMs)}${o.supervisorWallSource === "journal-span" ? " (journal-span lower bound)" : ""}`,
1038
- ` respawns=${showMeasured(o.respawns)} evidence→respawn=${showMeasured(r.decision.observeThenRespawn)} blind-respawn=${showMeasured(r.decision.respawnWithoutEvidence)} depth=${showMeasured(o.delegationDepth)}`,
1039
- ` accepted=${showMeasured(r.decision.accepted)} rejected=${showMeasured(r.decision.rejected)} empty-pass=${showMeasured(r.decision.emptyPass)}`,
1040
- ` brain=$${showMeasured(r.economics.brain.usd)} total=$${showMeasured(r.economics.totalUsd)} judge.resolved=${showMeasured(r.outcome.judgeResolved)} score=${showMeasured(r.outcome.judgeScore)} verify=${showMeasured(r.outcome.verifyPass)}`,
1041
- r.gaps.length > 0 ? ` gaps(${r.gaps.length}): ${r.gaps.join("; ")}` : " gaps: none"
1042
- ].join("\n");
1043
- }
1044
- function fmtMs(v) {
1045
- if (isUnavailable(v)) return `unavailable — ${v.unavailable}`;
1046
- if (v < 1e3) return `${v}ms`;
1047
- const s = v / 1e3;
1048
- if (s < 120) return `${round(s, 1)}s`;
1049
- return `${round(s / 60, 1)}min`;
1050
- }
1051
- function renderSupervisorRunMarkdown(r) {
1052
- const o = r.orchestration;
1053
- const d = r.decision;
1054
- const e = r.economics;
1055
- const out = [];
1056
- out.push(`# Run report — ${r.instanceId ?? "unknown instance"} [${r.arm ?? "unknown arm"}]`);
1057
- out.push("");
1058
- out.push("```");
1059
- out.push(renderSupervisorRunHeadline(r));
1060
- out.push("```");
1061
- out.push("");
1062
- out.push(`- Run: \`${r.runRef}\``);
1063
- out.push(`- Supervisor: \`${showMeasured(r.supervisorId)}\``);
1064
- out.push(`- Supervisor profile: \`${showMeasured(r.supervisorProfileDigest)}\``);
1065
- out.push(`- Generated: ${r.generatedAt}`);
1066
- out.push("");
1067
- out.push("## Orchestration");
1068
- out.push("");
1069
- out.push("| Metric | Value |");
1070
- out.push("|---|---|");
1071
- out.push(`| Workers spawned | ${showMeasured(o.workersSpawned)} |`);
1072
- out.push(`| Workers settled | ${showMeasured(o.workersSettled)} |`);
1073
- out.push(`| Workers cancelled | ${showMeasured(o.workersCancelled)} |`);
1074
- out.push(`| **Steers (mid-task messages to live workers)** | **${showMeasured(o.steers)}** |`);
1075
- out.push(`| Steers delivered | ${showMeasured(o.steersDelivered)} |`);
1076
- out.push(`| Outer-driver \`supervisor_steer\` calls | ${showMeasured(o.driverSteerCalls)} |`);
1077
- out.push(`| Spawn waves | ${showMeasured(o.waves)} |`);
1078
- out.push(`| Wave sizes | ${isUnavailable(o.waveSizes) ? showMeasured(o.waveSizes) : `[${o.waveSizes.join(", ")}]`} |`);
1079
- out.push(`| Max concurrency | ${showMeasured(o.maxConcurrency)} |`);
1080
- out.push(`| Respawns (after same parent's first settle) | ${showMeasured(o.respawns)} |`);
1081
- out.push(`| Repeated labels | ${isUnavailable(o.repeatedLabels) ? showMeasured(o.repeatedLabels) : o.repeatedLabels.length === 0 ? "none" : o.repeatedLabels.join(", ")} |`);
1082
- out.push(`| Delegation depth | ${showMeasured(o.delegationDepth)} |`);
1083
- out.push(`| Time to first spawn | ${fmtMs(o.timeToFirstSpawnMs)} |`);
1084
- out.push(`| Supervisor wall | ${fmtMs(o.supervisorWallMs)}${isUnavailable(o.supervisorWallSource) ? "" : ` (source: ${o.supervisorWallSource}${o.supervisorWallSource === "journal-span" ? ", lower bound" : ""})`} |`);
1085
- out.push(`| Idle (zero live workers) | ${fmtMs(o.idleMs)} (${showMeasured(o.idlePct)}%) |`);
1086
- out.push(`| Worker utilization (Σ worker wall ÷ supervisor wall) | ${showMeasured(o.workerUtilization)} |`);
1087
- out.push("");
1088
- if (!isUnavailable(o.steersByWorker) && o.steersByWorker.length > 0) {
1089
- out.push("### Steers per worker");
1090
- out.push("");
1091
- out.push("| Worker id | Label | Queued | Delivered |");
1092
- out.push("|---|---|---:|---:|");
1093
- for (const s of o.steersByWorker) out.push(`| ${s.workerId === null ? "unavailable — legacy label join" : `\`${s.workerId}\``} | \`${s.worker}\` | ${s.queued} | ${s.delivered} |`);
1094
- out.push("");
1095
- } else if (isUnavailable(o.steersByWorker)) out.push(`### Steers per worker\n\nunavailable — ${o.steersByWorker.unavailable}\n`);
1096
- out.push("## Decision quality");
1097
- out.push("");
1098
- out.push("| Metric | Value |");
1099
- out.push("|---|---|");
1100
- out.push(`| Settled by status | ${fmtCounts(d.settledByStatus)} |`);
1101
- out.push(`| Settled verdicts | ${fmtCounts(d.settledVerdicts)} |`);
1102
- out.push(`| Accepted (verify green + patch bytes) | ${showMeasured(d.accepted)} |`);
1103
- out.push(`| Rejected (verify red) | ${showMeasured(d.rejected)} |`);
1104
- out.push(`| Empty pass (green, no patch) | ${showMeasured(d.emptyPass)} |`);
1105
- out.push(`| Evidence → respawn sequences | ${showMeasured(d.observeThenRespawn)} |`);
1106
- out.push(`| Respawn with no same-parent settled evidence in front | ${showMeasured(d.respawnWithoutEvidence)} |`);
1107
- out.push(`| Review actions (steers + worker questions) | ${showMeasured(d.reviewActions)} |`);
1108
- out.push(`| Worker evidence returned | ${isUnavailable(d.workerEvidenceBytes) ? showMeasured(d.workerEvidenceBytes) : `${d.workerEvidenceBytes} bytes`} |`);
1109
- out.push("");
1110
- out.push("## Economics");
1111
- out.push("");
1112
- out.push("| Role | Tokens in | Tokens out | Cache read | Cache write | USD | Source |");
1113
- out.push("|---|---:|---:|---:|---:|---:|---|");
1114
- out.push(`| brain | ${showMeasured(e.brain.tokensIn)} | ${showMeasured(e.brain.tokensOut)} | ${showMeasured(e.brain.cacheRead)} | ${showMeasured(e.brain.cacheWrite)} | ${showMeasured(e.brain.usd)} | ${e.brain.source} |`);
1115
- out.push(`| workers | ${showMeasured(e.workers.tokensIn)} | ${showMeasured(e.workers.tokensOut)} | ${showMeasured(e.workers.cacheRead)} | ${showMeasured(e.workers.cacheWrite)} | ${showMeasured(e.workers.usd)} | ${e.workers.source} |`);
1116
- out.push("");
1117
- if (!isUnavailable(e.brainTruncations) && e.brainTruncations > 0) out.push(`- **BRAIN OUTPUT TRUNCATED: ${e.brainTruncations} completion(s) hit \`finish_reason: "length"\`** — the supervisor acted on a half-written plan. Its output ceiling is too low; see \`brain.jsonl\` for the per-call \`req_max_tokens\`.`);
1118
- else out.push(`- Brain completions truncated (finish_reason=length): ${showMeasured(e.brainTruncations)}`);
1119
- out.push(`- Total USD: ${showMeasured(e.totalUsd)} (source: ${e.totalUsdSource})`);
1120
- out.push(`- Spend measured two ways: journal-derived $${showMeasured(e.spend.journalDerived.usd)} over ${e.spend.journalDerived.records} journal record(s) (execution accounting) · close-record $${showMeasured(e.spend.closeRecord.usd)} over ${e.spend.closeRecord.records} close record(s) (billing-shaped). Divergence is a signal, not an error.`);
1121
- out.push(`- Cost per accepted patch: ${showMeasured(e.costPerAcceptedPatchUsd)}`);
1122
- if (isUnavailable(e.workerWallMsDistribution)) out.push(`- Worker wall distribution: unavailable — ${e.workerWallMsDistribution.unavailable}`);
1123
- else {
1124
- const w = e.workerWallMsDistribution;
1125
- out.push(`- Worker wall (n=${w.n}): min ${fmtMs(w.min)} / p50 ${fmtMs(w.p50)} / p90 ${fmtMs(w.p90)} / max ${fmtMs(w.max)} / Σ ${fmtMs(w.sum)}`);
1126
- }
1127
- out.push("");
1128
- if (!isUnavailable(e.perWorker) && e.perWorker.length > 0) {
1129
- out.push("| Worker id | Label | Role | Runtime | Profile digest | Status | Failure | Infra | Wall | Tokens in | Tokens out | Patch bytes | Verify passed | Score |");
1130
- out.push("|---|---|---|---|---|---|---|---|---:|---:|---:|---:|---|---:|");
1131
- for (const w of e.perWorker) out.push(`| ${w.workerId === null ? "unavailable — legacy label join" : `\`${w.workerId}\``} | \`${w.worker}\` | ${w.role ?? "unavailable — source recorded no role"} | ${w.runtime ?? "unavailable — source recorded no runtime"} | ${w.profileDigest === null ? "unavailable — source recorded no profile digest" : `\`${w.profileDigest}\``} | ${w.status ?? "unavailable — no terminal event"} | ${w.failure ?? "none recorded"} | ${w.infra ?? "unavailable"} | ${w.wallMs === null ? "unavailable — no spawn/finish pair" : fmtMs(w.wallMs)} | ${w.tokensIn ?? "unavailable — store does not attribute tokens per worker"} | ${w.tokensOut ?? "unavailable — store does not attribute tokens per worker"} | ${w.patchBytes ?? "unavailable — no worker patch file"} | ${w.passed === null ? "unavailable — no verdict" : String(w.passed)} | ${w.score ?? "unavailable — no numeric score"} |`);
1132
- out.push("");
1133
- }
1134
- out.push("## Outcome");
1135
- out.push("");
1136
- out.push("| Metric | Value |");
1137
- out.push("|---|---|");
1138
- out.push(`| Supervisor status | ${showMeasured(r.outcome.supStatus)} |`);
1139
- out.push(`| Supervisor verdict | ${showMeasured(r.outcome.supVerdict)} |`);
1140
- out.push(`| Delivered | ${showMeasured(r.outcome.delivered)} |`);
1141
- out.push(`| Judge resolved | ${showMeasured(r.outcome.judgeResolved)} |`);
1142
- out.push(`| Judge score | ${showMeasured(r.outcome.judgeScore)} |`);
1143
- out.push(`| Judge passed / total | ${showMeasured(r.outcome.judgePassed)} / ${showMeasured(r.outcome.judgeTotal)} |`);
1144
- out.push(`| Judge source | ${r.outcome.judgeSource ?? "unavailable — no judge.json and no ledger row"} |`);
1145
- out.push(`| Verify gate | pass=${showMeasured(r.outcome.verifyPass)} rc=${showMeasured(r.outcome.verifyRc)} |`);
1146
- if (isUnavailable(r.outcome.patch)) out.push(`| Patch | unavailable — ${r.outcome.patch.unavailable} |`);
1147
- else {
1148
- const p = r.outcome.patch;
1149
- out.push(`| Patch | ${p.files} file(s), +${p.linesAdded}/-${p.linesRemoved}, test files touched: ${p.testFilesTouched.length === 0 ? "none" : p.testFilesTouched.join(", ")} |`);
1150
- }
1151
- out.push("");
1152
- out.push("## Gaps");
1153
- out.push("");
1154
- if (r.gaps.length === 0) out.push("None — every metric above is backed by a present artifact.");
1155
- else for (const g of r.gaps) out.push(`- ${g}`);
1156
- out.push("");
1157
- out.push(`> Harness-session view of the same run (model calls, stuck loops, tool errors): \`${r.traceCommand}\``);
1158
- out.push("");
1159
- return out.join("\n");
1160
- }
1161
- function fmtCounts(v) {
1162
- if (isUnavailable(v)) return showMeasured(v);
1163
- const entries = Object.entries(v);
1164
- return entries.length === 0 ? "none" : entries.map(([k, n]) => `${k}=${n}`).join(", ");
1165
- }
1166
- function renderSupervisorRollupMarkdown(rollup, title = "Round rollup") {
1167
- const out = [];
1168
- out.push(`# ${title}`);
1169
- out.push("");
1170
- out.push(`- Cells: ${rollup.cells}`);
1171
- out.push(`- **Steers across all cells: ${showMeasured(rollup.steersTotal)}** (cells with ≥1 steer: ${showMeasured(rollup.cellsWithSteers)}; cells where the steer count is unavailable: ${rollup.cellsWithUnavailableSteers})`);
1172
- out.push(`- Waves per cell (mean): ${showMeasured(rollup.wavesMean)}`);
1173
- out.push(`- Max concurrency observed: ${showMeasured(rollup.maxConcurrencyMax)}`);
1174
- out.push(`- Worker utilization (mean): ${showMeasured(rollup.utilizationMean)}`);
1175
- out.push(`- Idle share (mean): ${showMeasured(rollup.idlePctMean)}%`);
1176
- out.push(`- Workers spawned: ${showMeasured(rollup.workersSpawnedTotal)} · accepted: ${showMeasured(rollup.acceptedTotal)}`);
1177
- out.push(`- Spend: $${showMeasured(rollup.usdTotal)} · judged resolved: ${showMeasured(rollup.resolvedCount)}/${rollup.cells}`);
1178
- out.push(`- Spend measured two ways: journal-derived $${showMeasured(rollup.spendUsd.journalDerived.value)} over ${rollup.spendUsd.journalDerived.runs}/${rollup.cells} runs (execution accounting) · close-record $${showMeasured(rollup.spendUsd.closeRecord.value)} over ${rollup.spendUsd.closeRecord.runs}/${rollup.cells} runs (billing-shaped)`);
1179
- out.push("");
1180
- out.push("| Instance | Arm | Steers | Waves | Utilization | Idle % | Resolved | USD |");
1181
- out.push("|---|---|---:|---:|---:|---:|---|---:|");
1182
- for (const c of rollup.perCell) out.push(`| ${c.instanceId ?? "?"} | ${c.arm ?? "?"} | ${showMeasured(c.steers)} | ${showMeasured(c.waves)} | ${showMeasured(c.utilization)} | ${showMeasured(c.idlePct)} | ${showMeasured(c.resolved)} | ${showMeasured(c.usd)} |`);
1183
- out.push("");
1184
- return out.join("\n");
1185
- }
1186
- //#endregion
1187
- //#region src/supervisor-run/runtime-reader.ts
1188
- /**
1189
- * Reader for agent-runtime's file-backed supervision context.
1190
- *
1191
- * Runtime stores multiple recursive trees in one `spawn-journal.jsonl`.
1192
- * Each line is an envelope whose `root` identifies the local tree. A journal
1193
- * can connect a nested tree with `spawned.ownedTreeRoot`. It can also use the
1194
- * spawned child id as the nested root and repeat the spawn as a parentless
1195
- * marker when no owned tree is recorded. Descendant spawns must occur in the
1196
- * tree their parent owns. This reader removes a duplicate marker and preserves
1197
- * the other envelopes for the supervisor-run analyzer. Runtime stores profile
1198
- * identity below `identity` and does not emit Eval's role field. This boundary
1199
- * projects those fields without changing Runtime's dialect.
1200
- *
1201
- * The run's terminal status is Runtime's own `result.json` `kind` — `winner`,
1202
- * `no-winner`, or whatever a later arm is called — read verbatim. The reader
1203
- * does not decide which kinds count: a kind it refuses is a run that recorded
1204
- * its outcome and got reported as having none.
1205
- *
1206
- * `usdKnown: false` / `tokensKnown: false` on ONE record is not a limit of this
1207
- * store. The store recorded every other record completely, so the flags travel
1208
- * through to the analyzer per record, which reports the measured nodes and
1209
- * names the unreported ones.
1210
- */
1211
- const JOURNAL_FILE = "spawn-journal.jsonl";
1212
- const RESULT_FILE = "result.json";
1213
- const TRAJECTORY_FILE = "trajectory.json";
1214
- async function readMaybe$1(path) {
1215
- return readFile(path, "utf8").catch((error) => {
1216
- if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") return null;
1217
- throw error;
1218
- });
1219
- }
1220
- function record(value) {
1221
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
1222
- }
1223
- function nonEmptyString(value) {
1224
- return typeof value === "string" && value.length > 0 ? value : null;
1225
- }
1226
- function profileDigest(event) {
1227
- const direct = nonEmptyString(event.profileDigest);
1228
- if (direct !== null) return direct;
1229
- const identity = record(event.identity);
1230
- return identity === null ? null : nonEmptyString(identity.profileDigest);
1231
- }
1232
- function formatError(path, line, detail) {
1233
- return /* @__PURE__ */ new Error(`${path}:${line}: invalid Runtime spawn journal: ${detail}`);
1234
- }
1235
- function parseEnvelopeJournal(text, path) {
1236
- const begins = [];
1237
- const events = [];
1238
- const begun = /* @__PURE__ */ new Map();
1239
- for (const [index, sourceLine] of text.split("\n").entries()) {
1240
- const line = index + 1;
1241
- const trimmed = sourceLine.trim();
1242
- if (trimmed.length === 0) continue;
1243
- let parsed;
1244
- try {
1245
- parsed = JSON.parse(trimmed);
1246
- } catch {
1247
- throw formatError(path, line, "line is not JSON");
1248
- }
1249
- const envelope = record(parsed);
1250
- if (envelope === null) throw formatError(path, line, "line is not an object");
1251
- const kind = nonEmptyString(envelope.kind);
1252
- const root = nonEmptyString(envelope.root);
1253
- if (root === null) throw formatError(path, line, "root must be a non-empty string");
1254
- if (kind === "begin") {
1255
- const at = nonEmptyString(envelope.at);
1256
- if (at === null || !Number.isFinite(Date.parse(at))) throw formatError(path, line, "begin.at must be an ISO timestamp");
1257
- if (begun.has(root)) throw formatError(path, line, `tree ${JSON.stringify(root)} began twice`);
1258
- const begin = {
1259
- root,
1260
- at,
1261
- line
1262
- };
1263
- begun.set(root, begin);
1264
- begins.push(begin);
1265
- continue;
1266
- }
1267
- if (kind !== "event") throw formatError(path, line, "kind must be 'begin' or 'event'");
1268
- if (!begun.has(root)) throw formatError(path, line, `event for tree ${JSON.stringify(root)} precedes begin`);
1269
- const event = record(envelope.event);
1270
- if (event === null) throw formatError(path, line, "event must be an object");
1271
- if (nonEmptyString(event.kind) === null) throw formatError(path, line, "event.kind must be a non-empty string");
1272
- events.push({
1273
- root,
1274
- event: { ...event },
1275
- line
1276
- });
1277
- }
1278
- if (begins.length === 0) throw formatError(path, 1, "no begin record");
1279
- const parentSpawnsById = /* @__PURE__ */ new Map();
1280
- const parentSpawnsByOwnedTreeRoot = /* @__PURE__ */ new Map();
1281
- const rootMarkersByTree = /* @__PURE__ */ new Map();
1282
- for (const entry of events) {
1283
- if (entry.event.kind !== "spawned") continue;
1284
- const id = nonEmptyString(entry.event.id);
1285
- if (id === null) continue;
1286
- if (nonEmptyString(entry.event.parent) !== null) {
1287
- const ownedTreeRoot = nonEmptyString(entry.event.ownedTreeRoot);
1288
- if (ownedTreeRoot !== null) {
1289
- const owners = parentSpawnsByOwnedTreeRoot.get(ownedTreeRoot) ?? [];
1290
- owners.push(entry);
1291
- parentSpawnsByOwnedTreeRoot.set(ownedTreeRoot, owners);
1292
- } else {
1293
- const matches = parentSpawnsById.get(id) ?? [];
1294
- matches.push(entry);
1295
- parentSpawnsById.set(id, matches);
1296
- }
1297
- }
1298
- if (entry.root === id && (entry.event.parent === void 0 || entry.event.parent === null)) {
1299
- const markers = rootMarkersByTree.get(entry.root) ?? [];
1300
- markers.push(entry);
1301
- rootMarkersByTree.set(entry.root, markers);
1302
- }
1303
- }
1304
- const nestedRoots = /* @__PURE__ */ new Set();
1305
- const nestedParentSpawns = /* @__PURE__ */ new Map();
1306
- for (const begin of begins) {
1307
- const parentSpawns = [.../* @__PURE__ */ new Set([...parentSpawnsByOwnedTreeRoot.get(begin.root) ?? [], ...parentSpawnsById.get(begin.root) ?? []])].filter((entry) => entry.root !== begin.root);
1308
- if (parentSpawns.length > 1) throw formatError(path, begin.line, `tree ${JSON.stringify(begin.root)} has ${parentSpawns.length} parent spawns`);
1309
- if (parentSpawns.length === 1) {
1310
- nestedRoots.add(begin.root);
1311
- nestedParentSpawns.set(begin.root, parentSpawns[0]);
1312
- }
1313
- }
1314
- const topRoots = begins.filter((begin) => !nestedRoots.has(begin.root));
1315
- if (topRoots.length !== 1) throw formatError(path, topRoots[0]?.line ?? 1, `expected one top-level tree, found ${topRoots.length}`);
1316
- const top = topRoots[0];
1317
- for (const nestedRoot of nestedRoots) {
1318
- const markers = rootMarkersByTree.get(nestedRoot) ?? [];
1319
- if (markers.length > 1) throw formatError(path, begun.get(nestedRoot)?.line ?? 1, `nested tree ${JSON.stringify(nestedRoot)} contains ${markers.length} root markers`);
1320
- const parentSpawn = nestedParentSpawns.get(nestedRoot);
1321
- if (parentSpawn === void 0) throw formatError(path, begun.get(nestedRoot)?.line ?? 1, `nested tree ${JSON.stringify(nestedRoot)} has no parent spawn`);
1322
- const markerDigest = profileDigest(markers[0]?.event ?? {});
1323
- const parentDigest = profileDigest(parentSpawn.event);
1324
- if (markerDigest !== null && parentDigest !== null && markerDigest !== parentDigest) throw formatError(path, markers[0]?.line ?? 1, `nested tree ${JSON.stringify(nestedRoot)} disagrees with its parent profile digest`);
1325
- if (parentDigest === null && markerDigest !== null) parentSpawn.event.profileDigest = markerDigest;
1326
- }
1327
- const ownedTreeBySupervisorId = /* @__PURE__ */ new Map([[top.root, top.root]]);
1328
- for (const [nestedRoot, parentSpawn] of nestedParentSpawns) {
1329
- const supervisorId = nonEmptyString(parentSpawn.event.id);
1330
- if (supervisorId === null) continue;
1331
- const priorTree = ownedTreeBySupervisorId.get(supervisorId);
1332
- if (priorTree !== void 0 && priorTree !== nestedRoot) throw formatError(path, parentSpawn.line, `spawn ${JSON.stringify(supervisorId)} owns both ${JSON.stringify(priorTree)} and ${JSON.stringify(nestedRoot)}`);
1333
- ownedTreeBySupervisorId.set(supervisorId, nestedRoot);
1334
- }
1335
- for (const entry of events) {
1336
- if (entry.event.kind !== "spawned") continue;
1337
- const parentId = nonEmptyString(entry.event.parent);
1338
- if (parentId === null) continue;
1339
- const parentTree = ownedTreeBySupervisorId.get(parentId);
1340
- if (parentTree === void 0) throw formatError(path, entry.line, `spawn ${JSON.stringify(entry.event.id)} names parent ${JSON.stringify(parentId)}, which owns no journal tree`);
1341
- if (entry.root !== parentTree) throw formatError(path, entry.line, `spawn ${JSON.stringify(entry.event.id)} is in tree ${JSON.stringify(entry.root)}, but parent ${JSON.stringify(parentId)} owns tree ${JSON.stringify(parentTree)}`);
1342
- }
1343
- const supervisorIds = /* @__PURE__ */ new Set([top.root, ...[...nestedParentSpawns.values()].map((entry) => nonEmptyString(entry.event.id)).filter((id) => id !== null)]);
1344
- const normalized = events.filter((entry) => !(nestedRoots.has(entry.root) && entry.event.kind === "spawned" && entry.event.id === entry.root && (entry.event.parent === void 0 || entry.event.parent === null))).map((entry) => {
1345
- const event = { ...entry.event };
1346
- if (event.kind === "spawned") {
1347
- const digest = profileDigest(event);
1348
- if (event.profileDigest === void 0 && digest !== null) event.profileDigest = digest;
1349
- if (event.role === void 0) event.role = supervisorIds.has(nonEmptyString(event.id) ?? "") ? "supervisor" : "worker";
1350
- }
1351
- return {
1352
- root: entry.root,
1353
- event
1354
- };
1355
- });
1356
- if ((rootMarkersByTree.get(top.root) ?? []).length !== 1) throw formatError(path, top.line, `top-level tree ${JSON.stringify(top.root)} must contain one root marker`);
1357
- return {
1358
- root: top.root,
1359
- startedAt: top.at,
1360
- journal: `${normalized.map((entry) => JSON.stringify({
1361
- kind: "event",
1362
- root: entry.root,
1363
- event: entry.event
1364
- })).join("\n")}\n`,
1365
- events: normalized.map((entry) => entry.event)
1366
- };
1367
- }
1368
- function parseOptionalRecord(text, path) {
1369
- if (text === null) return null;
1370
- let parsed;
1371
- try {
1372
- parsed = JSON.parse(text);
1373
- } catch {
1374
- throw new Error(`${path}: invalid JSON`);
1375
- }
1376
- const value = record(parsed);
1377
- if (value === null) throw new Error(`${path}: expected a JSON object`);
1378
- return value;
1379
- }
1380
- function spendRecord(value) {
1381
- const spend = record(value);
1382
- if (spend === null) return null;
1383
- const tokens = record(spend.tokens);
1384
- if (tokens === null || typeof tokens.input !== "number" || !Number.isFinite(tokens.input) || tokens.input < 0 || typeof tokens.output !== "number" || !Number.isFinite(tokens.output) || tokens.output < 0 || typeof spend.usd !== "number" || !Number.isFinite(spend.usd) || spend.usd < 0 || spend.usdKnown !== void 0 && typeof spend.usdKnown !== "boolean") return null;
1385
- return spend;
1386
- }
1387
- function sourceLimits(root, events, workerIds) {
1388
- const rootMeters = events.filter((event) => event.kind === "metered" && event.id === root);
1389
- const invalidRootMeters = rootMeters.filter((event) => spendRecord(event.spend) === null);
1390
- const rootMeterReason = rootMeters.length === 0 ? "Runtime journal has no root metered event" : invalidRootMeters.length > 0 ? `${invalidRootMeters.length} root metered event(s) lack complete spend` : null;
1391
- const closes = events.filter((event) => workerIds.has(nonEmptyString(event.id) ?? "") && (event.kind === "settled" || event.kind === "cancelled"));
1392
- const settledById = /* @__PURE__ */ new Map();
1393
- for (const event of closes) {
1394
- const id = nonEmptyString(event.id);
1395
- if (id === null) continue;
1396
- const matches = settledById.get(id) ?? [];
1397
- matches.push(event);
1398
- settledById.set(id, matches);
1399
- }
1400
- const incompleteWorkers = [...workerIds].filter((id) => {
1401
- const terminal = settledById.get(id);
1402
- return terminal?.length !== 1 || terminal[0]?.kind !== "settled" || spendRecord(terminal[0]?.spent) === null;
1403
- });
1404
- const missingVerdicts = [...workerIds].filter((id) => {
1405
- const terminal = settledById.get(id)?.[0];
1406
- if (terminal?.kind !== "settled") return true;
1407
- return typeof record(terminal.verdict)?.valid !== "boolean";
1408
- });
1409
- return {
1410
- managerTokens: rootMeterReason,
1411
- workerTokens: incompleteWorkers.length === 0 ? null : `${incompleteWorkers.length}/${workerIds.size} child invocation(s) lack one settled spend record`,
1412
- spendUsd: rootMeterReason !== null ? rootMeterReason : incompleteWorkers.length > 0 ? "at least one child invocation lacks a settled spend record" : null,
1413
- workerVerdicts: missingVerdicts.length === 0 ? null : `${missingVerdicts.length}/${workerIds.size} child invocation(s) lack a structured validity verdict`,
1414
- deliverables: workerIds.size === 0 ? null : "Runtime FileRunContext does not retain per-child delivered patches"
1415
- };
1416
- }
1417
- function runtimeState(root, startedAt, result, trajectory, resultPath, trajectoryPath) {
1418
- const resultKind = result === null ? null : nonEmptyString(result.kind);
1419
- if (resultKind !== null && result !== null) {
1420
- const resultRoot = nonEmptyString(record(result.tree)?.root);
1421
- if (resultRoot === null) throw new Error(`${resultPath}: Runtime ${resultKind} result has no tree.root`);
1422
- if (resultRoot !== root) throw new Error(`${resultPath}: root ${JSON.stringify(resultRoot)} does not match journal root ${JSON.stringify(root)}`);
1423
- }
1424
- if (trajectory !== null && nonEmptyString(trajectory.root) === null) throw new Error(`${trajectoryPath}: Runtime trajectory has no root`);
1425
- if (typeof trajectory?.root === "string" && trajectory.root !== root) throw new Error(`${trajectoryPath}: root ${JSON.stringify(trajectory.root)} does not match journal root ${JSON.stringify(root)}`);
1426
- if (trajectory !== null && !Array.isArray(trajectory.nodes)) throw new Error(`${trajectoryPath}: Runtime trajectory nodes must be an array`);
1427
- let status = resultKind;
1428
- if (status === null && Array.isArray(trajectory?.nodes)) {
1429
- const rootNodes = trajectory.nodes.map((node) => record(node)).filter((node) => node?.id === root);
1430
- if (rootNodes.length > 1) throw new Error(`${trajectoryPath}: Runtime trajectory contains duplicate root nodes`);
1431
- status = nonEmptyString(rootNodes[0]?.status);
1432
- }
1433
- return JSON.stringify({
1434
- id: root,
1435
- startedAt,
1436
- ...status === null ? {} : { status }
1437
- });
1438
- }
1439
- /**
1440
- * Sources for a run dir whose spawn journal does not exist. Mirrors the
1441
- * absent shape `readLoopsSupervisorRun` returns for a missing store: every
1442
- * journal-dependent metric downstream reads `unavailable`, never 0.
1443
- */
1444
- function absentRuntimeSupervisorRun(runDir, resultText) {
1445
- const reason = `no Runtime spawn journal (${JOURNAL_FILE}) under ${runDir}`;
1446
- return {
1447
- runRef: runDir,
1448
- instanceId: null,
1449
- arm: null,
1450
- supRunDir: null,
1451
- journal: null,
1452
- journalMissingReason: reason,
1453
- brainLog: null,
1454
- brainLogMissingReason: "Runtime FileRunContext records spend but not model completion finish reasons",
1455
- state: null,
1456
- progress: null,
1457
- workers: null,
1458
- workersMissingReason: reason,
1459
- result: resultText,
1460
- judge: null,
1461
- judgeSource: null,
1462
- patch: null,
1463
- driverLog: null,
1464
- harnessWorkerTokens: null,
1465
- harnessMissingReason: "Runtime FileRunContext has no external worker-token join",
1466
- limits: NO_SOURCE_LIMITS,
1467
- rootTranscriptRef: null,
1468
- traceCommand: "unavailable — Runtime FileRunContext records no provider-session trace identity"
1469
- };
1470
- }
1471
- /**
1472
- * Read one agent-runtime `createFileRunContext(dir)` directory.
1473
- *
1474
- * A run dir without `spawn-journal.jsonl` returns the same absent-shaped
1475
- * sources `readLoopsSupervisorRun` returns for a missing store: `journal` and
1476
- * `workers` null, each with its reason, so every dependent metric reads
1477
- * `unavailable` — never 0 and never a throw. Pass `strict: true` to throw on
1478
- * the missing journal instead. A journal that exists but cannot be parsed
1479
- * always throws: a corrupt journal is a defect, not an absence.
1480
- *
1481
- * The reader translates storage envelopes only. It does not assign research
1482
- * roles, interpret artifacts, or turn process completion into a quality
1483
- * verdict.
1484
- */
1485
- async function readRuntimeSupervisorRun(runDir, opts = {}) {
1486
- const journalPath = join(runDir, JOURNAL_FILE);
1487
- const rawJournal = opts.strict === true ? await readFile(journalPath, "utf8") : await readMaybe$1(journalPath);
1488
- if (rawJournal === null) return absentRuntimeSupervisorRun(runDir, await readMaybe$1(join(runDir, RESULT_FILE)));
1489
- const normalized = parseEnvelopeJournal(rawJournal, journalPath);
1490
- const resultText = await readMaybe$1(join(runDir, RESULT_FILE));
1491
- const trajectoryText = await readMaybe$1(join(runDir, TRAJECTORY_FILE));
1492
- const result = parseOptionalRecord(resultText, join(runDir, RESULT_FILE));
1493
- const trajectory = parseOptionalRecord(trajectoryText, join(runDir, TRAJECTORY_FILE));
1494
- const resultPath = join(runDir, RESULT_FILE);
1495
- const trajectoryPath = join(runDir, TRAJECTORY_FILE);
1496
- const childSpawns = normalized.events.filter((event) => event.kind === "spawned" && nonEmptyString(event.id) !== null).filter((event) => event.id !== normalized.root);
1497
- const workerIds = new Set(childSpawns.map((event) => nonEmptyString(event.id)).filter((id) => id !== null));
1498
- const workers = childSpawns.map((event) => ({
1499
- workerId: nonEmptyString(event.id),
1500
- label: nonEmptyString(event.label) ?? String(event.id),
1501
- events: null,
1502
- inbox: null,
1503
- patchBytes: null,
1504
- transcriptRef: null,
1505
- patchPath: null
1506
- }));
1507
- return {
1508
- runRef: runDir,
1509
- instanceId: normalized.root,
1510
- arm: null,
1511
- supRunDir: runDir,
1512
- journal: normalized.journal,
1513
- brainLog: null,
1514
- brainLogMissingReason: "Runtime FileRunContext records spend but not model completion finish reasons",
1515
- state: runtimeState(normalized.root, normalized.startedAt, result, trajectory, resultPath, trajectoryPath),
1516
- progress: null,
1517
- workers,
1518
- workersMissingReason: null,
1519
- result: resultText,
1520
- judge: null,
1521
- judgeSource: null,
1522
- patch: null,
1523
- driverLog: null,
1524
- harnessWorkerTokens: null,
1525
- harnessMissingReason: "Runtime FileRunContext has no external worker-token join",
1526
- limits: sourceLimits(normalized.root, normalized.events, workerIds),
1527
- rootTranscriptRef: null,
1528
- traceCommand: "unavailable — Runtime FileRunContext records no provider-session trace identity"
1529
- };
1530
- }
1531
- /** The agent-runtime file-backed layout as a `SupervisorRunReader`. */
1532
- function runtimeSupervisorRunReader(runDir, opts = {}) {
1533
- return {
1534
- runRef: runDir,
1535
- read: () => readRuntimeSupervisorRun(runDir, opts)
1536
- };
1537
- }
1538
- /** True when a directory contains Runtime's canonical file-backed journal. */
1539
- async function isRuntimeSupervisorRunDir(runDir) {
1540
- return stat(join(runDir, JOURNAL_FILE)).then((entry) => entry.isFile()).catch((error) => {
1541
- if (typeof error === "object" && error !== null && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) return false;
1542
- throw error;
1543
- });
1544
- }
1545
- //#endregion
1546
- //#region src/supervisor-run/loops-reader.ts
1547
- /**
1548
- * ONE implementation of `SupervisorRunReader`: the on-disk layout the loops
1549
- * supervisor writes — `<runDir>/ws/.agent/supervisor/<id>/{journal.jsonl,
1550
- * state.json, progress.ndjson, workers/*.ndjson}` alongside the run's
1551
- * `result.json` / `judge.json` / `driver.log` / delivered patch. Runs written
1552
- * before the `.agent` rename live under `<ws>/.loops/supervisor/<id>` and are
1553
- * still found via fallback.
1554
- *
1555
- * Nothing in `analyze.ts` knows this layout exists. A different store (an
1556
- * archive, an object bucket, a database) implements the same interface and
1557
- * gets the same report.
1558
- *
1559
- * Worker token recovery reuses the rollout module's opencode reader rather
1560
- * than opening a second sqlite path — one store client, one corruption policy.
1561
- */
1562
- async function readMaybe(path) {
1563
- return readFile(path, "utf8").catch(() => null);
1564
- }
1565
- /**
1566
- * Locate the (single) supervisor run dir under `<ws>/.agent/supervisor`, falling back to the
1567
- * pre-rename `<ws>/.loops/supervisor` so runs written by older supervisors stay analyzable.
1568
- */
1569
- async function findSupervisorRunDirIn(ws) {
1570
- for (const stateDir of [".agent", ".loops"]) {
1571
- const root = join(ws, stateDir, "supervisor");
1572
- const dirs = (await readdir(root, { withFileTypes: true }).catch(() => [])).filter((e) => e.isDirectory()).map((e) => join(root, e.name));
1573
- if (dirs[0] !== void 0) return dirs[0];
1574
- }
1575
- return null;
1576
- }
1577
- /**
1578
- * Read a loops supervisor run directory into source bytes. Never throws on a
1579
- * missing artifact — an absent file becomes a `null` field, which is what makes
1580
- * the dependent metric `unavailable` instead of 0.
1581
- */
1582
- async function readLoopsSupervisorRun(runDir, opts = {}) {
1583
- const ws = opts.ws ?? join(runDir, "ws");
1584
- const supRunDir = await findSupervisorRunDirIn(ws);
1585
- const result = await readMaybe(join(runDir, "result.json"));
1586
- const resultObj = parseJson(result);
1587
- const journal = supRunDir === null ? null : await readMaybe(join(supRunDir, "journal.jsonl"));
1588
- const journalWorkerSpawns = parseJsonl(journal).filter((event) => event.kind === "spawned" && typeof event.parent === "string" && event.role !== "supervisor").length;
1589
- let workers = null;
1590
- let workersMissingReason = null;
1591
- const workerCwds = [];
1592
- let workerStarts = 0;
1593
- if (supRunDir === null) workersMissingReason = `no supervisor run dir under ${join(ws, ".agent", "supervisor")} (or legacy ${join(ws, ".loops", "supervisor")})`;
1594
- else {
1595
- const workersDir = join(supRunDir, "workers");
1596
- const entries = await readdir(workersDir).catch(() => null);
1597
- if (entries === null) workersMissingReason = `workers/ directory absent under ${supRunDir}`;
1598
- else {
1599
- const labels = [...new Set(entries.filter((f) => f.endsWith(".ndjson")).map((f) => f.replace(/\.inbox\.ndjson$/, "").replace(/\.ndjson$/, "")))].sort();
1600
- workers = [];
1601
- for (const label of labels) {
1602
- const events = await readMaybe(join(workersDir, `${label}.ndjson`));
1603
- const inbox = await readMaybe(join(workersDir, `${label}.inbox.ndjson`));
1604
- const patch = await readMaybe(join(workersDir, `${label}.patch`));
1605
- const startedRows = parseJsonl(events).filter((event) => event.kind === "started");
1606
- workerStarts += startedRows.length;
1607
- const startedIds = startedRows.map((event) => typeof event.workerId === "string" ? event.workerId : typeof event.agentId === "string" ? event.agentId : null).filter((id) => id !== null);
1608
- const distinctStartedIds = new Set(startedIds);
1609
- const workerId = startedRows.length > 0 && startedIds.length === startedRows.length && distinctStartedIds.size === 1 ? startedIds[0] : void 0;
1610
- workers.push({
1611
- ...workerId === void 0 ? {} : { workerId },
1612
- label,
1613
- events,
1614
- inbox,
1615
- patchBytes: patch === null ? null : Buffer.byteLength(patch)
1616
- });
1617
- for (const ev of startedRows) if (ev.kind === "started" && typeof ev.cwd === "string") workerCwds.push(ev.cwd);
1618
- }
1619
- }
1620
- }
1621
- let harnessWorkerTokens = null;
1622
- let harnessMissingReason = null;
1623
- let workerCwdsWithoutSessions = 0;
1624
- if (opts.opencodeDb === null) harnessMissingReason = "opencode join disabled";
1625
- else if (workerCwds.length === 0) harnessMissingReason = "no worker clone cwds in workers/*.ndjson (nothing to join)";
1626
- else {
1627
- const db = await openOpencodeDb(opts.opencodeDb ?? DEFAULT_OPENCODE_DB);
1628
- if (db === null) harnessMissingReason = `opencode session store unreadable at ${opts.opencodeDb ?? DEFAULT_OPENCODE_DB}`;
1629
- else try {
1630
- const seen = /* @__PURE__ */ new Set();
1631
- let sessions = 0;
1632
- let input = 0;
1633
- let output = 0;
1634
- const distinctWorkerCwds = new Set(workerCwds);
1635
- for (const cwd of distinctWorkerCwds) {
1636
- const rows = findOpencodeSessionsByDirectory(db, cwd);
1637
- if (rows.length === 0) workerCwdsWithoutSessions += 1;
1638
- for (const row of rows) {
1639
- if (seen.has(row.id)) continue;
1640
- seen.add(row.id);
1641
- sessions += 1;
1642
- input += row.tokensInput;
1643
- output += row.tokensOutput + row.tokensReasoning;
1644
- }
1645
- }
1646
- harnessWorkerTokens = {
1647
- store: "opencode",
1648
- sessions,
1649
- input,
1650
- output
1651
- };
1652
- if (workerCwdsWithoutSessions > 0) harnessMissingReason = `${workerCwdsWithoutSessions}/${distinctWorkerCwds.size} worker clone cwds have no opencode session`;
1653
- } finally {
1654
- db.close();
1655
- }
1656
- }
1657
- const workerInvocations = Math.max(journalWorkerSpawns, workerStarts);
1658
- const workerTokenGaps = [];
1659
- if (workerCwds.length < workerInvocations) workerTokenGaps.push(`${workerInvocations - workerCwds.length}/${workerInvocations} worker invocations have no clone cwd for the opencode token join`);
1660
- if (workerInvocations > 0 && harnessWorkerTokens === null) workerTokenGaps.push(harnessMissingReason ?? "worker harness token join unavailable");
1661
- else if (workerCwdsWithoutSessions > 0 && harnessMissingReason !== null) workerTokenGaps.push(harnessMissingReason);
1662
- const workerTokenLimit = workerTokenGaps.length === 0 ? null : workerTokenGaps.join("; ");
1663
- const patchPath = opts.patchPath ?? (typeof resultObj?.patchPath === "string" ? resultObj.patchPath : null);
1664
- let judge = await readMaybe(join(runDir, "judge.json"));
1665
- let judgeSource = judge === null ? null : join(runDir, "judge.json");
1666
- if (judge === null && opts.ledgerPath !== void 0) {
1667
- const row = await findLedgerRow(opts.ledgerPath, runDir);
1668
- if (row !== null) {
1669
- judge = JSON.stringify(row);
1670
- judgeSource = `${opts.ledgerPath} (ledger row)`;
1671
- }
1672
- }
1673
- return {
1674
- runRef: runDir,
1675
- instanceId: typeof resultObj?.iid === "string" ? resultObj.iid : instanceIdFromPath(runDir),
1676
- arm: typeof resultObj?.arm === "string" ? resultObj.arm : basename(runDir),
1677
- supRunDir,
1678
- journal,
1679
- brainLog: supRunDir === null ? null : await readMaybe(join(supRunDir, "brain.jsonl")),
1680
- state: supRunDir === null ? null : await readMaybe(join(supRunDir, "state.json")),
1681
- progress: supRunDir === null ? null : await readMaybe(join(supRunDir, "progress.ndjson")),
1682
- workers,
1683
- workersMissingReason,
1684
- result,
1685
- judge,
1686
- judgeSource,
1687
- patch: patchPath === null ? null : await readMaybe(patchPath),
1688
- driverLog: await readMaybe(join(runDir, "driver.log")),
1689
- harnessWorkerTokens,
1690
- harnessMissingReason,
1691
- limits: {
1692
- ...NO_SOURCE_LIMITS,
1693
- workerTokens: workerTokenLimit
1694
- },
1695
- traceCommand: null
1696
- };
1697
- }
1698
- /** The loops on-disk layout, as a `SupervisorRunReader`. */
1699
- function loopsSupervisorRunReader(runDir, opts = {}) {
1700
- return {
1701
- runRef: runDir,
1702
- read: () => readLoopsSupervisorRun(runDir, opts)
1703
- };
1704
- }
1705
- /** The ledger row whose `runDir` is this run (falling back to iid + arm match). */
1706
- async function findLedgerRow(ledgerPath, runDir) {
1707
- const rows = parseJsonl(await readMaybe(ledgerPath));
1708
- const exact = rows.find((r) => r.runDir === runDir);
1709
- if (exact !== void 0) return exact;
1710
- const iid = instanceIdFromPath(runDir);
1711
- const arm = basename(runDir);
1712
- return rows.find((r) => r.iid === iid && r.arm === arm) ?? null;
1713
- }
1714
- /** `<outDir>/runs/<iid>/<arm>` → `<iid>`. */
1715
- function instanceIdFromPath(runDir) {
1716
- const parts = runDir.split("/").filter(Boolean);
1717
- const armIdx = parts.length - 1;
1718
- const iid = parts[armIdx - 1];
1719
- return parts[armIdx - 2] === "runs" && iid !== void 0 ? iid : null;
1720
- }
1721
- /**
1722
- * Analyze a supervisor run. Accepts a run directory (read through the loops
1723
- * reader), any `SupervisorRunReader`, or already-read source bytes — so a
1724
- * caller with its own store never has to touch the filesystem layout.
1725
- */
1726
- async function analyzeSupervisorRun(input, opts = {}) {
1727
- if (typeof input === "string") return analyzeSupervisorRunSources(await isRuntimeSupervisorRunDir(input) ? await readRuntimeSupervisorRun(input) : await readLoopsSupervisorRun(input, opts));
1728
- if (isReader(input)) return analyzeSupervisorRunSources(await input.read());
1729
- return analyzeSupervisorRunSources(input);
1730
- }
1731
- function isReader(input) {
1732
- return typeof input.read === "function";
1733
- }
1734
- /**
1735
- * Read a completed run, write `run-report.json` + `run-report.md` beside its
1736
- * artifacts, and append the headline block to the run log. Never throws on a
1737
- * missing artifact — a run that produced nothing still yields a report whose
1738
- * every metric says why.
1739
- */
1740
- async function writeSupervisorRunReport(runDir, opts = {}) {
1741
- const report = analyzeSupervisorRunSources(await isRuntimeSupervisorRunDir(runDir) ? await readRuntimeSupervisorRun(runDir) : await readLoopsSupervisorRun(runDir, opts));
1742
- const md = renderSupervisorRunMarkdown(report);
1743
- const dest = opts.reportDir ?? runDir;
1744
- const stem = opts.reportDir === void 0 ? "run-report" : supervisorReportStem(runDir);
1745
- if (opts.reportDir !== void 0) await mkdir(opts.reportDir, { recursive: true }).catch(() => {});
1746
- await writeFile(join(dest, `${stem}.json`), JSON.stringify(report, null, 1)).catch(() => {});
1747
- await writeFile(join(dest, `${stem}.md`), md).catch(() => {});
1748
- const headline = renderSupervisorRunHeadline(report);
1749
- if (opts.appendHeadlineTo !== void 0) await appendFile(opts.appendHeadlineTo, `${headline}\n`).catch(() => {});
1750
- if (opts.echo !== false) console.log(headline);
1751
- return report;
1752
- }
1753
- /**
1754
- * File stem for out-of-tree reports. Built from the run path's identifying
1755
- * segments — candidate tag (the segment under `arm-runs/`), rep, instance, arm
1756
- * — so two runs of the same instance from different candidates/reps never
1757
- * overwrite each other.
1758
- */
1759
- function supervisorReportStem(runDir) {
1760
- const parts = runDir.split("/").filter(Boolean);
1761
- const arm = parts[parts.length - 1] ?? "cell";
1762
- const iid = parts[parts.length - 2] ?? "instance";
1763
- const rep = parts.find((p) => /^rep-\d+$/.test(p));
1764
- const armRunsIdx = parts.indexOf("arm-runs");
1765
- return [
1766
- armRunsIdx >= 0 ? parts[armRunsIdx + 1] : void 0,
1767
- rep,
1768
- iid,
1769
- arm
1770
- ].filter((s) => s !== void 0 && s !== "runs").join(".").replace(/[^A-Za-z0-9._-]/g, "_");
1771
- }
1772
- /**
1773
- * Best-effort wrapper for a hot path: a reporting failure must never kill a run
1774
- * that already produced real work. Returns null and logs the reason instead.
1775
- */
1776
- async function writeSupervisorRunReportSafe(runDir, opts = {}) {
1777
- try {
1778
- return await writeSupervisorRunReport(runDir, opts);
1779
- } catch (err) {
1780
- console.log(`RUN-REPORT failed for ${runDir}: ${err instanceof Error ? err.message : String(err)}`);
1781
- return null;
1782
- }
1783
- }
1784
- /**
1785
- * Report every run under an experiment `outDir` (any depth of
1786
- * `runs/<iid>/<arm>`), write each run's report, and write the rollup at
1787
- * `<outDir>/run-report-round.{json,md}`.
1788
- */
1789
- async function reportSupervisorRound(outDir, opts = {}) {
1790
- const runDirs = await findSupervisorRunDirs(outDir);
1791
- const reports = [];
1792
- for (const runDir of runDirs) {
1793
- const r = await writeSupervisorRunReportSafe(runDir, {
1794
- ...opts,
1795
- echo: opts.echo ?? false
1796
- });
1797
- if (r !== null) reports.push(r);
1798
- }
1799
- const rollup = rollupSupervisorRuns(reports);
1800
- const md = renderSupervisorRollupMarkdown(rollup, opts.title ?? `Round rollup — ${basename(outDir)}`);
1801
- const dest = opts.reportDir ?? outDir;
1802
- if (opts.reportDir !== void 0) await mkdir(opts.reportDir, { recursive: true }).catch(() => {});
1803
- await writeFile(join(dest, "run-report-round.json"), JSON.stringify(rollup, null, 1)).catch(() => {});
1804
- await writeFile(join(dest, "run-report-round.md"), md).catch(() => {});
1805
- if (opts.appendHeadlineTo !== void 0) await appendFile(opts.appendHeadlineTo, `${md}\n`).catch(() => {});
1806
- if (opts.echo !== false) console.log(md);
1807
- return rollup;
1808
- }
1809
- /**
1810
- * Every loops or Runtime supervisor run below `root`.
1811
- *
1812
- * When `root` itself is one run, return no children so callers can distinguish
1813
- * a single report from a parent-directory rollup.
1814
- */
1815
- async function findSupervisorRunDirs(root) {
1816
- if (await isRuntimeSupervisorRunDir(root) || await findSupervisorRunDirIn(join(root, "ws")) !== null) return [];
1817
- const found = [];
1818
- const walk = async (dir, depth) => {
1819
- if (depth > 8) return;
1820
- const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
1821
- for (const e of entries) {
1822
- if (!e.isDirectory()) continue;
1823
- if (e.name === "node_modules" || e.name === ".git") continue;
1824
- const full = join(dir, e.name);
1825
- if (await isRuntimeSupervisorRunDir(full) || await findSupervisorRunDirIn(join(full, "ws")) !== null) {
1826
- found.push(full);
1827
- continue;
1828
- }
1829
- await walk(full, depth + 1);
1830
- }
1831
- };
1832
- await walk(root, 0);
1833
- return found.sort();
1834
- }
1835
- //#endregion
1836
- export { NO_SOURCE_LIMITS, SUPERVISOR_RUN_INTEGRITY_SCHEMA, SUPERVISOR_RUN_ROLLUP_SCHEMA, SUPERVISOR_RUN_SCHEMA, analyzeSupervisorRun, analyzeSupervisorRunIntegrity, analyzeSupervisorRunSources, claudeCodeSupervisorRunReader, findSupervisorRunDirIn, findSupervisorRunDirs, isRuntimeSupervisorRunDir, isUnavailable, loopsSupervisorRunReader, parsePatch, parseSupervisorTree, readClaudeCodeSupervisorRun, readLoopsSupervisorRun, readRuntimeSupervisorRun, renderSupervisorRollupMarkdown, renderSupervisorRunHeadline, renderSupervisorRunMarkdown, reportSupervisorRound, rollupSupervisorRuns, runtimeSupervisorRunReader, showMeasured, supervisorRunRolloutLines, unavailable, writeSupervisorRunReport, writeSupervisorRunReportSafe };
485
+ export { NO_SOURCE_LIMITS, NO_TERMINAL_RECORD, RUNTIME_FAILED_STATUS, SUPERVISOR_RUN_INTEGRITY_SCHEMA, SUPERVISOR_RUN_ROLLUP_SCHEMA, SUPERVISOR_RUN_SCHEMA, analyzeSupervisorRun, analyzeSupervisorRunIntegrity, analyzeSupervisorRunSources, claudeCodeSupervisorRunReader, findSupervisorRunDirIn, findSupervisorRunDirs, isRuntimeSupervisorRunDir, isUnavailable, loopsSupervisorRunReader, parsePatch, parseSupervisorTree, readClaudeCodeSupervisorRun, readLoopsSupervisorRun, readRuntimeSupervisorRun, readTerminalRecord, renderSupervisorRollupMarkdown, renderSupervisorRunHeadline, renderSupervisorRunMarkdown, reportSupervisorRound, rollupSupervisorRuns, runSupervisorRunCommand, runtimeSupervisorRunReader, showMeasured, supervisorRunRolloutLines, unavailable, writeSupervisorRunReport, writeSupervisorRunReportSafe };
1837
486
 
1838
487
  //# sourceMappingURL=index.js.map