@tangle-network/agent-eval 1.0.20 → 1.0.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -6
- package/dist/adapters/http.d.ts +2 -2
- package/dist/{agent-profile-Dngk3LZ0.js → agent-profile-4j6f2n-x.js} +4 -4
- package/dist/agent-profile-4j6f2n-x.js.map +1 -0
- package/dist/{agent-profile-BO8ruI6R.d.ts → agent-profile-DU5InUT9.d.ts} +4 -4
- package/dist/{agent-profile-BO8ruI6R.d.ts.map → agent-profile-DU5InUT9.d.ts.map} +1 -1
- package/dist/analyst/index.d.ts +6 -6
- package/dist/analyst/index.js +5 -5
- package/dist/{analyze-runs-DicleUI_.d.ts → analyze-runs-DYYe18Gw.d.ts} +3 -3
- package/dist/{analyze-runs-DicleUI_.d.ts.map → analyze-runs-DYYe18Gw.d.ts.map} +1 -1
- package/dist/{analyze-runs-e9vfXY--.js → analyze-runs-jLTRKuoK.js} +5 -5
- package/dist/{analyze-runs-e9vfXY--.js.map → analyze-runs-jLTRKuoK.js.map} +1 -1
- package/dist/app-grade/index.d.ts +2 -2
- package/dist/app-grade/index.js +1 -1
- package/dist/{benchmark-command-BGZD77Un.js → benchmark-command-DkUpd9Q6.js} +4 -4
- package/dist/{benchmark-command-BGZD77Un.js.map → benchmark-command-DkUpd9Q6.js.map} +1 -1
- package/dist/benchmarks/index.d.ts +4 -4
- package/dist/benchmarks/index.js +3 -3
- package/dist/builder-eval/index.js +1 -1
- package/dist/{calibration-Ze7SjhT9.js → calibration-Cf-wpqqO.js} +2 -2
- package/dist/{calibration-Ze7SjhT9.js.map → calibration-Cf-wpqqO.js.map} +1 -1
- package/dist/campaign/index.d.ts +6 -6
- package/dist/campaign/index.js +9 -9
- package/dist/{campaign-BfDMncQN.js → campaign-C2mmydmx.js} +12 -12
- package/dist/{campaign-BfDMncQN.js.map → campaign-C2mmydmx.js.map} +1 -1
- package/dist/{campaign-evidence-BuKlRzSA.js → campaign-evidence-NtH29ctt.js} +3 -3
- package/dist/{campaign-evidence-BuKlRzSA.js.map → campaign-evidence-NtH29ctt.js.map} +1 -1
- package/dist/cli.js +5 -5
- package/dist/{cluster-bootstrap-BYIW7QJ4.js → cluster-bootstrap-B0MTOBRU.js} +2 -2
- package/dist/{cluster-bootstrap-BYIW7QJ4.js.map → cluster-bootstrap-B0MTOBRU.js.map} +1 -1
- package/dist/contract/index.d.ts +8 -8
- package/dist/contract/index.js +10 -10
- package/dist/{decision-point-DJWievVw.js → decision-point-Di2LATNH.js} +3 -3
- package/dist/{decision-point-DJWievVw.js.map → decision-point-Di2LATNH.js.map} +1 -1
- package/dist/{default-registry-CdMtoY-s.js → default-registry-CdFbxPnr.js} +2 -2
- package/dist/{default-registry-CdMtoY-s.js.map → default-registry-CdFbxPnr.js.map} +1 -1
- package/dist/{default-registry-BpGFsSpZ.d.ts → default-registry-aPvwtzEM.d.ts} +2 -2
- package/dist/{default-registry-BpGFsSpZ.d.ts.map → default-registry-aPvwtzEM.d.ts.map} +1 -1
- package/dist/{define-agent-eval-DuQNZajG.js → define-agent-eval-BROmIwn1.js} +5 -5
- package/dist/{define-agent-eval-DuQNZajG.js.map → define-agent-eval-BROmIwn1.js.map} +1 -1
- package/dist/{define-agent-eval-DcK8mg63.d.ts → define-agent-eval-DGWBgCid.d.ts} +6 -6
- package/dist/{define-agent-eval-DcK8mg63.d.ts.map → define-agent-eval-DGWBgCid.d.ts.map} +1 -1
- package/dist/diagnosis/index.d.ts +1 -1
- package/dist/diagnosis/index.js +1 -1
- package/dist/{eval-campaign-LmpC_5fm.js → eval-campaign-Dq8DEKmy.js} +2 -2
- package/dist/{eval-campaign-LmpC_5fm.js.map → eval-campaign-Dq8DEKmy.js.map} +1 -1
- package/dist/{evaluation-BCejQgkV.d.ts → evaluation-CFKj_IlJ.d.ts} +2 -2
- package/dist/{evaluation-BCejQgkV.d.ts.map → evaluation-CFKj_IlJ.d.ts.map} +1 -1
- package/dist/evaluation.d.ts +1 -1
- package/dist/experiment/index.d.ts +2 -2
- package/dist/experiment/index.js +6 -6
- package/dist/fuzz.js +1 -1
- package/dist/{index-CzfdjM6o.d.ts → index-B62BaRzH.d.ts} +2 -2
- package/dist/{index-CzfdjM6o.d.ts.map → index-B62BaRzH.d.ts.map} +1 -1
- package/dist/{index-DYNHOTTB.d.ts → index-BlTbxHlY.d.ts} +2 -2
- package/dist/{index-DYNHOTTB.d.ts.map → index-BlTbxHlY.d.ts.map} +1 -1
- package/dist/{index-Bc8BZfzb.d.ts → index-Bp3w4fWc.d.ts} +7 -7
- package/dist/{index-Bc8BZfzb.d.ts.map → index-Bp3w4fWc.d.ts.map} +1 -1
- package/dist/{index-BdLmBInV.d.ts → index-DNXFzSpc.d.ts} +23 -21
- package/dist/{index-BdLmBInV.d.ts.map → index-DNXFzSpc.d.ts.map} +1 -1
- package/dist/{index-gSu9DUiw.d.ts → index-DX87wzX3.d.ts} +7 -7
- package/dist/{index-gSu9DUiw.d.ts.map → index-DX87wzX3.d.ts.map} +1 -1
- package/dist/{index-D_eAFB3T.d.ts → index-QLDWZTxI.d.ts} +4 -4
- package/dist/{index-D_eAFB3T.d.ts.map → index-QLDWZTxI.d.ts.map} +1 -1
- package/dist/{index-CeYLLnfi.d.ts → index-YS58LHlx.d.ts} +17 -17
- package/dist/{index-CeYLLnfi.d.ts.map → index-YS58LHlx.d.ts.map} +1 -1
- package/dist/index.d.ts +17 -17
- package/dist/index.js +15 -15
- package/dist/{judge-gate-BliY81A0.js → judge-gate-CrN0PaAL.js} +2 -2
- package/dist/{judge-gate-BliY81A0.js.map → judge-gate-CrN0PaAL.js.map} +1 -1
- package/dist/{llm-judge-Bnxuwjxl.js → llm-judge-C813vmpc.js} +9 -9
- package/dist/{llm-judge-Bnxuwjxl.js.map → llm-judge-C813vmpc.js.map} +1 -1
- package/dist/{matrix-D6zEwLvE.d.ts → matrix-C-GxIgeJ.d.ts} +2 -2
- package/dist/{matrix-D6zEwLvE.d.ts.map → matrix-C-GxIgeJ.d.ts.map} +1 -1
- package/dist/meta-eval/index.d.ts +2 -2
- package/dist/meta-eval/index.js +6 -6
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +2 -2
- package/dist/openapi.json +1 -1
- package/dist/{outcome-observations-BpicIVQi.js → outcome-observations-DPkH-LHQ.js} +2 -2
- package/dist/{outcome-observations-BpicIVQi.js.map → outcome-observations-DPkH-LHQ.js.map} +1 -1
- package/dist/{paired-arms-Dep5tbsw.js → paired-arms-DjMEtYI9.js} +2 -2
- package/dist/{paired-arms-Dep5tbsw.js.map → paired-arms-DjMEtYI9.js.map} +1 -1
- package/dist/{paired-promotion-decision-Nt4CkkOT.js → paired-promotion-decision-Bi9__RQS.js} +2 -2
- package/dist/{paired-promotion-decision-Nt4CkkOT.js.map → paired-promotion-decision-Bi9__RQS.js.map} +1 -1
- package/dist/{paired-promotion-decision-BNzPfXDw.d.ts → paired-promotion-decision-DJU3fZxH.d.ts} +2 -2
- package/dist/{paired-promotion-decision-BNzPfXDw.d.ts.map → paired-promotion-decision-DJU3fZxH.d.ts.map} +1 -1
- package/dist/{pareto-C445lnEH.js → pareto-fJZg8pXm.js} +3 -3
- package/dist/{pareto-C445lnEH.js.map → pareto-fJZg8pXm.js.map} +1 -1
- package/dist/pipelines/index.js +1 -1
- package/dist/{promotion-gate-DjAsmBSZ.d.ts → promotion-gate-Da0xV4sa.d.ts} +2 -2
- package/dist/{promotion-gate-DjAsmBSZ.d.ts.map → promotion-gate-Da0xV4sa.d.ts.map} +1 -1
- package/dist/{promotion-policy-CUWOv01m.js → promotion-policy-DCgftbnd.js} +4 -4
- package/dist/{promotion-policy-CUWOv01m.js.map → promotion-policy-DCgftbnd.js.map} +1 -1
- package/dist/{release-confidence-DDrkmWxT.js → release-confidence-DGtuPDxJ.js} +2 -2
- package/dist/{release-confidence-DDrkmWxT.js.map → release-confidence-DGtuPDxJ.js.map} +1 -1
- package/dist/reporting.d.ts +3 -3
- package/dist/reporting.js +4 -4
- package/dist/{researcher-D35yo0B8.d.ts → researcher-CSlc84Bp.d.ts} +2 -2
- package/dist/{researcher-D35yo0B8.d.ts.map → researcher-CSlc84Bp.d.ts.map} +1 -1
- package/dist/{reward-hacking-DRb8K6N1.js → reward-hacking-BYiDFbIl.js} +2 -2
- package/dist/{reward-hacking-DRb8K6N1.js.map → reward-hacking-BYiDFbIl.js.map} +1 -1
- package/dist/rl.d.ts +4 -4
- package/dist/rl.js +7 -7
- package/dist/rollout/index.d.ts +2 -2
- package/dist/{rubric-predictive-validity-BMS7SUyh.js → rubric-predictive-validity-DL7gJ51F.js} +2 -2
- package/dist/{rubric-predictive-validity-BMS7SUyh.js.map → rubric-predictive-validity-DL7gJ51F.js.map} +1 -1
- package/dist/{run-record-CIflWk6i.js → run-record-CFbnkE1K.js} +2 -2
- package/dist/{run-record-CIflWk6i.js.map → run-record-CFbnkE1K.js.map} +1 -1
- package/dist/{runtime-rollouts-CfRyjk60.js → runtime-rollouts-BNrm5nC_.js} +2 -2
- package/dist/{runtime-rollouts-CfRyjk60.js.map → runtime-rollouts-BNrm5nC_.js.map} +1 -1
- package/dist/search/index.d.ts +2 -2
- package/dist/search/index.js +2 -2
- package/dist/{search-kernel-Ds2zILpY.d.ts → search-kernel-CQGLbmgn.d.ts} +3 -3
- package/dist/{search-kernel-Ds2zILpY.d.ts.map → search-kernel-CQGLbmgn.d.ts.map} +1 -1
- package/dist/{search-summary-BSftVrGY.js → search-summary-sPWiYtSl.js} +4 -4
- package/dist/{search-summary-BSftVrGY.js.map → search-summary-sPWiYtSl.js.map} +1 -1
- package/dist/{sequential-CqG6aLWS.js → sequential-9TVb5Nu5.js} +3 -3
- package/dist/{sequential-CqG6aLWS.js.map → sequential-9TVb5Nu5.js.map} +1 -1
- package/dist/{skillopt-optimization-method-DYwEndON.js → skillopt-optimization-method-QO1nU8Kz.js} +6 -6
- package/dist/{skillopt-optimization-method-DYwEndON.js.map → skillopt-optimization-method-QO1nU8Kz.js.map} +1 -1
- package/dist/{statistical-heldout--0b1lgx4.d.ts → statistical-heldout-CvOwNqt9.d.ts} +4 -4
- package/dist/{statistical-heldout--0b1lgx4.d.ts.map → statistical-heldout-CvOwNqt9.d.ts.map} +1 -1
- package/dist/{statistical-heldout-D6i58CJ5.js → statistical-heldout-DLO4Ebos.js} +3 -3
- package/dist/{statistical-heldout-D6i58CJ5.js.map → statistical-heldout-DLO4Ebos.js.map} +1 -1
- package/dist/{statistics-DCZIC-qT.js → statistics-CvvC-MPv.js} +28 -21
- package/dist/statistics-CvvC-MPv.js.map +1 -0
- package/dist/statistics.d.ts +2 -2
- package/dist/statistics.js +2 -2
- package/dist/{summary-report-D_uussI3.js → summary-report-BEhqoxrA.js} +3 -3
- package/dist/{summary-report-D_uussI3.js.map → summary-report-BEhqoxrA.js.map} +1 -1
- package/dist/{summary-report-Cv1AC-iv.d.ts → summary-report-DyZquTaH.d.ts} +2 -2
- package/dist/{summary-report-Cv1AC-iv.d.ts.map → summary-report-DyZquTaH.d.ts.map} +1 -1
- package/dist/supervisor-run/index.d.ts +1 -1
- package/dist/supervisor-run/index.js +1 -1
- package/dist/{systemone-C3xyEKvG.d.ts → systemone-DVk-Crtu.d.ts} +4 -4
- package/dist/{systemone-C3xyEKvG.d.ts.map → systemone-DVk-Crtu.d.ts.map} +1 -1
- package/dist/systemone.d.ts +2 -2
- package/dist/systemone.js +1 -1
- package/dist/{tool-waste-DEhKfiIE.js → tool-waste-BqSmmPUz.js} +2 -2
- package/dist/{tool-waste-DEhKfiIE.js.map → tool-waste-BqSmmPUz.js.map} +1 -1
- package/dist/trace-repair/index.js +1 -1
- package/dist/{tree-B2y1UR8o.js → tree-C-N2kP-8.js} +4 -4
- package/dist/{tree-B2y1UR8o.js.map → tree-C-N2kP-8.js.map} +1 -1
- package/dist/{types-BwF--ZRz.d.ts → types-BsdcSWnf.d.ts} +2 -2
- package/dist/{types-BwF--ZRz.d.ts.map → types-BsdcSWnf.d.ts.map} +1 -1
- package/dist/{types-BAJ2Hb-d.d.ts → types-DUVhW5V1.d.ts} +2 -2
- package/dist/{types-BAJ2Hb-d.d.ts.map → types-DUVhW5V1.d.ts.map} +1 -1
- package/dist/{types-CeMZYsNF.d.ts → types-ip2D3-Ib.d.ts} +2 -2
- package/dist/{types-CeMZYsNF.d.ts.map → types-ip2D3-Ib.d.ts.map} +1 -1
- package/docs/design/statistics-decisions.md +7 -0
- package/package.json +5 -5
- package/dist/agent-profile-Dngk3LZ0.js.map +0 -1
- package/dist/statistics-DCZIC-qT.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-rollouts-CfRyjk60.js","names":["round","round","round","record","record","round","record"],"sources":["../src/supervisor-run/analyze-context.ts","../src/supervisor-run/analyze-decision.ts","../src/supervisor-run/analyze-economics.ts","../src/supervisor-run/analyze-orchestration.ts","../src/supervisor-run/patch-stats.ts","../src/supervisor-run/analyze-outcome.ts","../src/supervisor-run/analyze-spend.ts","../src/supervisor-run/analyze.ts","../src/supervisor-run/coordination-reader.ts","../src/supervisor-run/runtime-source-limits.ts","../src/supervisor-run/runtime-reader.ts","../src/supervisor-run/reader.ts","../src/supervisor-run/render.ts","../src/supervisor-run/runtime-rollouts.ts"],"sourcesContent":["import { parseJsonRecord, parseSupervisorTree, type SpawnRow } from './source-facts'\nimport { readTerminalRecord } from './terminal-record'\nimport { type SupervisorRunSources, type Unavailable, unavailable } from './types'\n\n/** The parsed sources and shared lookups every metric group reads. `gap` records an unavailable measurement on the report. */\nexport function createAnalysis(src: SupervisorRunSources) {\n const gaps: string[] = []\n const gap = (what: string, reason: string): Unavailable => {\n gaps.push(`${what}: ${reason}`)\n return unavailable(reason)\n }\n\n const journalMissing =\n src.journalMissingReason ??\n (src.supRunDir === null ? 'no Runtime supervisor run directory' : 'journal.jsonl absent')\n const haveJournal = src.journal !== null\n const tree = parseSupervisorTree(src)\n const state = tree.state\n const result = parseJsonRecord(src.result)\n const judge = parseJsonRecord(src.judge)\n // Runtime's terminal record is named on the report so a status never arrives unlabeled.\n const terminal = readTerminalRecord({\n state,\n result,\n failure: src.failure === undefined ? undefined : parseJsonRecord(src.failure),\n })\n const { rootId, workerSpawns, workerCloses, startedAt, completedAt } = tree\n const rootSpawn =\n rootId === null ? null : (tree.spawns.find((spawn) => spawn.id === rootId) ?? null)\n const spawnById = new Map(workerSpawns.map((spawn) => [spawn.id, spawn]))\n const spawnsByLabel = new Map<string, SpawnRow[]>()\n for (const spawn of workerSpawns) {\n const matches = spawnsByLabel.get(spawn.label) ?? []\n matches.push(spawn)\n spawnsByLabel.set(spawn.label, matches)\n }\n const spawnsForSource = (\n worker: NonNullable<SupervisorRunSources['workers']>[number],\n ): readonly SpawnRow[] => {\n if (worker.workerId === undefined) return spawnsByLabel.get(worker.label) ?? []\n const spawn = spawnById.get(worker.workerId)\n return spawn === undefined ? [] : [spawn]\n }\n const spawnForSource = (\n worker: NonNullable<SupervisorRunSources['workers']>[number],\n ): SpawnRow | null => {\n const matches = spawnsForSource(worker)\n return matches.length === 1 ? (matches[0] ?? null) : null\n }\n const closeById = new Map(workerCloses.map((close) => [close.id, close]))\n const workersGapReason = src.workersMissingReason ?? 'workers/ directory absent'\n return {\n src,\n gaps,\n gap,\n journalMissing,\n haveJournal,\n tree,\n state,\n result,\n judge,\n terminal,\n rootId,\n rootSpawn,\n workerSpawns,\n workerCloses,\n startedAt,\n completedAt,\n spawnsForSource,\n spawnForSource,\n closeById,\n workersGapReason,\n }\n}\n\nexport type Analysis = ReturnType<typeof createAnalysis>\n","import type { Analysis } from './analyze-context'\nimport type { StepFacts } from './analyze-orchestration'\nimport { workerSourceKey } from './source-facts'\nimport { type DecisionMetrics, unavailable } from './types'\n\n/** Settled verdicts, acceptance and review effort, with a named gap wherever the store never said. */\nexport function measureDecision(a: Analysis, m: StepFacts): DecisionMetrics {\n const {\n src,\n gap,\n journalMissing,\n haveJournal,\n tree,\n workerCloses,\n spawnForSource,\n closeById,\n workersGapReason,\n } = a\n const {\n steerQueuedTotal,\n upLegMessages,\n queuedGapReason,\n workerEventsGapReason,\n observeThenRespawn,\n respawnWithoutEvidence,\n } = m\n // ── decision quality ───────────────────────────────────────────────────\n const settledByStatus: Record<string, number> = {}\n const settledVerdicts: Record<string, number> = {}\n for (const c of workerCloses) {\n const key = c.status ?? 'unknown'\n settledByStatus[key] = (settledByStatus[key] ?? 0) + 1\n if (c.verdict !== null) settledVerdicts[c.verdict] = (settledVerdicts[c.verdict] ?? 0) + 1\n }\n\n // A store with no verify step never says pass or fail. Counting its silent\n // workers as `rejected: 0 / accepted: 0` would read as \"nothing was accepted\".\n const verdictLimit = src.limits.workerVerdicts\n // A store that retains no delivered patch still SETTLES a verdict, and that verdict is\n // the acceptance decision it recorded. Only the split between a green verdict backed by\n // a patch and a green verdict with nothing behind it needs patch bytes, so the\n // deliverables limit takes `emptyPass` and leaves `accepted` measured.\n const deliverablesLimit = src.limits.deliverables\n let accepted = 0\n let emptyPass = 0\n let evidenceBytes = 0\n const sourceVerdicts: boolean[] = []\n for (const w of src.workers ?? []) {\n const f = tree.workerLogs.get(workerSourceKey(w))\n if (f?.finished) evidenceBytes += f.evidenceBytes\n const spawn = spawnForSource(w)\n const close = spawn === null ? null : (closeById.get(spawn.id) ?? null)\n const passed = close?.valid ?? f?.passed ?? null\n if (passed !== null) sourceVerdicts.push(passed)\n if (passed === true) {\n if (deliverablesLimit !== null || (w.patchBytes ?? f?.finishedPatchBytes ?? 0) > 0) {\n accepted += 1\n } else {\n emptyPass += 1\n }\n }\n }\n const settledCloses = workerCloses.filter((close) => close.kind === 'settled')\n const structuredVerdicts = settledCloses\n .map((close) => close.valid)\n .filter((valid): valid is boolean => valid !== null)\n const journalVerdictsComplete =\n settledCloses.length > 0 && structuredVerdicts.length === settledCloses.length\n const sourceVerdictsComplete =\n sourceVerdicts.length > 0 && sourceVerdicts.length >= settledCloses.length\n const rejected = journalVerdictsComplete\n ? structuredVerdicts.filter((valid) => !valid).length\n : sourceVerdictsComplete\n ? sourceVerdicts.filter((valid) => !valid).length\n : 0\n const rejectedLimit =\n journalVerdictsComplete || sourceVerdictsComplete\n ? null\n : settledCloses.length > 0\n ? (verdictLimit ?? 'a settled journal verdict has no validity and no matched worker log')\n : verdictLimit !== null\n ? verdictLimit\n : !haveJournal && src.workers === null\n ? workersGapReason\n : null\n\n const decision: DecisionMetrics = {\n settledByStatus: haveJournal ? settledByStatus : gap('settledByStatus', journalMissing),\n settledVerdicts:\n verdictLimit !== null\n ? unavailable(verdictLimit)\n : haveJournal\n ? settledVerdicts\n : unavailable(journalMissing),\n accepted:\n verdictLimit !== null\n ? gap('accepted', verdictLimit)\n : src.workers === null\n ? unavailable(workersGapReason)\n : accepted,\n rejected: rejectedLimit === null ? rejected : unavailable(rejectedLimit),\n emptyPass:\n verdictLimit !== null\n ? gap('emptyPass', verdictLimit)\n : deliverablesLimit !== null\n ? gap('emptyPass', deliverablesLimit)\n : src.workers === null\n ? unavailable(workersGapReason)\n : emptyPass,\n observeThenRespawn: haveJournal ? observeThenRespawn : unavailable(journalMissing),\n respawnWithoutEvidence: haveJournal ? respawnWithoutEvidence : unavailable(journalMissing),\n reviewActions:\n src.workers === null\n ? unavailable(workersGapReason)\n : queuedGapReason === null\n ? steerQueuedTotal + upLegMessages\n : unavailable(queuedGapReason),\n workerEvidenceBytes:\n src.workers === null\n ? unavailable(workersGapReason)\n : workerEventsGapReason === null\n ? evidenceBytes\n : unavailable(workerEventsGapReason),\n }\n return decision\n}\n","import { roundDecimal as round } from '../math/round-decimal'\nimport { summarizeNumberSeries } from '../statistics'\nimport type { Analysis } from './analyze-context'\nimport type { SpendFacts, TotalUsd, WorkerTokens } from './analyze-spend'\nimport { parseJsonl, workerSourceKey } from './source-facts'\nimport {\n type DecisionMetrics,\n type EconomicsMetrics,\n isUnavailable,\n type PerWorkerRow,\n type SpendMeasurements,\n type SupervisorRunSources,\n unavailable,\n} from './types'\n\nconst NO_CACHE_COUNTERS = 'the journal carries no cache-token counters for this role'\n\nconst NO_CACHE_BREAKDOWN =\n 'Runtime recorded cacheBreakdownKnown:false — the provider reported a total without splitting cache reads from writes'\n\n/** One row per worker log, plus the capture gaps of the root and every worker. */\nexport function buildPerWorker(a: Analysis, f: SpendFacts, t: TotalUsd): PerWorkerRow[] {\n const { src, gaps, tree, rootId, spawnsForSource, spawnForSource, closeById } = a\n const { workerUsdById, workerUsdByLabel } = f\n const { usdLimit } = t\n const noteCaptureGaps = (\n owner: string,\n captures: SupervisorRunSources['rootWorkspaceCaptures'],\n ): void => {\n if (captures === null || captures?.length === 0) {\n gaps.push(`${owner} workspaceCapture: no retained output capture evidence`)\n } else if (captures !== undefined) {\n for (const [index, capture] of captures.entries()) {\n const source = `${owner} workspaceCapture[${index + 1}]`\n if (capture.projectionGap !== null) gaps.push(`${source}: ${capture.projectionGap}`)\n if (capture.coverageComplete === false) {\n gaps.push(\n `${source}: ${capture.incompleteReason ?? 'provider reported incomplete coverage'}`,\n )\n }\n if (capture.coverageComplete === null && capture.projectionGap === null) {\n gaps.push(`${source}: capture coverage was not recorded`)\n }\n }\n }\n }\n noteCaptureGaps(`root ${rootId ?? src.runRef}`, src.rootWorkspaceCaptures)\n const perWorker: PerWorkerRow[] = (src.workers ?? []).map((w) => {\n noteCaptureGaps(`worker ${w.workerId ?? w.label}`, w.workspaceCaptures)\n const f = tree.workerLogs.get(workerSourceKey(w))\n const matchingSpawns = spawnsForSource(w)\n const spawn = spawnForSource(w)\n const close = spawn === null ? null : (closeById.get(spawn.id) ?? null)\n const passed = close?.valid ?? f?.passed ?? null\n const matchingRoles = new Set(matchingSpawns.map((candidate) => candidate.role))\n const matchingRuntimes = new Set(matchingSpawns.map((candidate) => candidate.runtime))\n const matchingProfiles = new Set(matchingSpawns.map((candidate) => candidate.profileDigest))\n const journalWallMs =\n spawn?.at !== null &&\n spawn?.at !== undefined &&\n close?.at !== null &&\n close?.at !== undefined &&\n close.at >= spawn.at\n ? close.at - spawn.at\n : null\n return {\n workerId: w.workerId ?? null,\n worker: w.label,\n role: matchingRoles.size === 1 ? (matchingSpawns[0]?.role ?? null) : null,\n runtime: matchingRuntimes.size === 1 ? (matchingSpawns[0]?.runtime ?? null) : null,\n profileDigest:\n matchingProfiles.size === 1 ? (matchingSpawns[0]?.profileDigest ?? null) : null,\n status: close?.status ?? null,\n failure: close?.reason ?? null,\n infra: close?.infra ?? null,\n wallMs: f?.started != null && f.finishedAt != null ? f.finishedAt - f.started : journalWallMs,\n tokensIn:\n w.tokensIn ??\n (close?.hasSpend === true && close.spend.tokensKnown ? close.spend.tokens.input : null),\n tokensOut:\n w.tokensOut ??\n (close?.hasSpend === true && close.spend.tokensKnown ? close.spend.tokens.output : null),\n usd:\n usdLimit !== null\n ? null\n : w.workerId === undefined\n ? (workerUsdByLabel.get(w.label) ?? null)\n : (workerUsdById.get(w.workerId) ?? null),\n patchBytes: w.patchBytes ?? f?.finishedPatchBytes ?? null,\n passed,\n score: close?.score ?? f?.score ?? null,\n workspaceCaptures: w.workspaceCaptures ?? null,\n }\n })\n return perWorker\n}\n\n/** The supervisor brain's tokens, cache and USD. */\nfunction buildBrainSpend(\n a: Analysis,\n f: SpendFacts,\n t: TotalUsd,\n): EconomicsMetrics['brain'] {\n const { src, gap, journalMissing, haveJournal, tree } = a\n const { brainTokensUnreported, brainUsdUnreported } = f\n const { usdLimit } = t\n const managerTokenLimit = src.limits.managerTokens\n return {\n tokensIn:\n managerTokenLimit !== null\n ? gap('brain.tokensIn', managerTokenLimit)\n : !haveJournal\n ? gap('brain.tokensIn', journalMissing)\n : brainTokensUnreported !== null\n ? gap('brain.tokensIn', brainTokensUnreported)\n : tree.brain.tokensIn,\n tokensOut:\n managerTokenLimit !== null\n ? unavailable(managerTokenLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : brainTokensUnreported !== null\n ? unavailable(brainTokensUnreported)\n : tree.brain.tokensOut,\n usd:\n usdLimit !== null\n ? unavailable(usdLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : brainUsdUnreported !== null\n ? unavailable(brainUsdUnreported)\n : round(tree.brain.usd, 6),\n cacheRead:\n managerTokenLimit !== null\n ? unavailable(managerTokenLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : brainTokensUnreported !== null\n ? unavailable(brainTokensUnreported)\n : !tree.brain.hasCache\n ? unavailable(NO_CACHE_COUNTERS)\n : tree.brain.cacheBreakdownKnown\n ? tree.brain.cacheRead\n : unavailable(NO_CACHE_BREAKDOWN),\n cacheWrite:\n managerTokenLimit !== null\n ? unavailable(managerTokenLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : brainTokensUnreported !== null\n ? unavailable(brainTokensUnreported)\n : !tree.brain.hasCache\n ? unavailable(NO_CACHE_COUNTERS)\n : tree.brain.cacheBreakdownKnown\n ? tree.brain.cacheWrite\n : unavailable(NO_CACHE_BREAKDOWN),\n source:\n managerTokenLimit ??\n (haveJournal\n ? `journal metered events (n=${tree.brain.meteredCount})${\n tree.brain.usdKnownCount > 0 && tree.brain.usdUnknownCount > 0\n ? ` — ${tree.brain.usdUnknownCount} unpriced`\n : ''\n }`\n : journalMissing),\n }\n}\n\n/** The workers' tokens, cache and USD. */\nfunction buildWorkerSpend(\n a: Analysis,\n f: SpendFacts,\n t: TotalUsd,\n w: WorkerTokens,\n): EconomicsMetrics['workers'] {\n const { src, journalMissing, haveJournal } = a\n const { rootChildSpends, workerUsdUnknownNodes, journalWorkerUsd, workerUsdUnreported } = f\n const { usdLimit } = t\n const { sq, workerTokenLimit, workerIn, workerOut } = w\n return {\n tokensIn: workerIn,\n tokensOut: workerOut,\n cacheRead:\n workerTokenLimit !== null\n ? unavailable(workerTokenLimit)\n : sq?.cacheRead !== undefined\n ? sq.cacheRead\n : unavailable(NO_CACHE_COUNTERS),\n cacheWrite:\n workerTokenLimit !== null\n ? unavailable(workerTokenLimit)\n : sq?.cacheWrite !== undefined\n ? sq.cacheWrite\n : unavailable(NO_CACHE_COUNTERS),\n usd:\n usdLimit !== null\n ? unavailable(usdLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : workerUsdUnreported !== null\n ? unavailable(workerUsdUnreported)\n : round(journalWorkerUsd, 6),\n source: `${\n workerTokenLimit !== null\n ? workerTokenLimit\n : sq !== null\n ? `journal settled spend + ${sq.store} sessions (n=${sq.sessions})`\n : `journal settled spend only — ${src.harnessMissingReason ?? 'harness session store unavailable'}`\n }${\n workerUsdUnknownNodes.length > 0 && workerUsdUnknownNodes.length < rootChildSpends.length\n ? ` — ${workerUsdUnknownNodes.length} unpriced`\n : ''\n }`,\n }\n}\n\nexport function buildEconomics(\n a: Analysis,\n f: SpendFacts,\n t: TotalUsd,\n w: WorkerTokens,\n e: EconomicsParts,\n): EconomicsMetrics {\n const { src, gap, journalMissing, haveJournal, tree, workersGapReason } = a\n const { rootChildCloses, journalWorkerUsd, usdUnknownRecords } = f\n const { stateUsd, usdLimit, totalUsd, usdUnreportedReason } = t\n const { decision, spend, perWorker } = e\n const wallDistribution = summarizeNumberSeries(\n perWorker.map((w) => w.wallMs).filter((w): w is number => w !== null),\n )\n\n const brainCalls = parseJsonl(src.brainLog)\n return {\n resourceRecords:\n src.journal === null && !tree.resourceRecords?.length\n ? unavailable(journalMissing)\n : (tree.resourceRecords ?? []),\n brain: buildBrainSpend(a, f, t),\n brainTruncations:\n src.brainLog === null\n ? gap(\n 'brain.brainTruncations',\n src.brainLogMissingReason ??\n (src.supRunDir === null\n ? 'no Runtime supervisor run directory'\n : 'brain.jsonl absent — this source has no brain-call tap, so truncation cannot be ruled out'),\n )\n : brainCalls.filter((c) => c.finish_reason === 'length').length,\n workers: buildWorkerSpend(a, f, t, w),\n spend,\n totalUsd,\n totalUsdSource:\n usdLimit !== null\n ? usdLimit\n : stateUsd !== null\n ? `state.json result.spentUsd${rootChildCloses.length > 0 && journalWorkerUsd === 0 ? ' — brain-priced only; worker CLI inference is unpriced (see worker token counts)' : ''}`\n : !haveJournal\n ? journalMissing\n : usdUnknownRecords > 0\n ? usdUnreportedReason\n : 'journal metered + settled usd',\n costPerAcceptedPatchUsd: isUnavailable(totalUsd)\n ? unavailable(totalUsd.unavailable)\n : isUnavailable(decision.accepted)\n ? unavailable(decision.accepted.unavailable)\n : decision.accepted === 0\n ? unavailable('no accepted worker patch (cost has no denominator)')\n : round(totalUsd / decision.accepted, 6),\n workerWallMsDistribution:\n wallDistribution === null\n ? unavailable(\n src.workers === null ? workersGapReason : 'no worker start/finish pairs captured',\n )\n : wallDistribution,\n perWorker: src.workers === null ? unavailable(workersGapReason) : perWorker,\n }\n}\n\nexport interface EconomicsParts {\n decision: DecisionMetrics\n spend: SpendMeasurements\n perWorker: PerWorkerRow[]\n}\n","import { roundDecimal as round } from '../math/round-decimal'\nimport type { Analysis } from './analyze-context'\nimport { type SpawnRow, type WorkerLogFacts, workerSourceKey } from './source-facts'\nimport {\n isUnavailable,\n type Measured,\n type OrchestrationMetrics,\n type SteerBreakdown,\n unavailable,\n} from './types'\n\n/** Supervisor wall time and where it ends. Explicit stamps win; the journal span is a lower bound; an inverted stamp pair stays unavailable. */\nexport function measureWall(a: Analysis) {\n const { gap, journalMissing, haveJournal, tree, startedAt, completedAt } = a\n // Wall provenance: explicit stamps when the store wrote both; otherwise the\n // journal event span (a lower bound) when there is no completion stamp at\n // all. A present-but-inverted stamp pair is corruption, not absence, and\n // stays unavailable.\n const wallSpanStart = startedAt ?? tree.firstEventAt\n const wallSpanEnd = tree.lastEventAt\n let supervisorWallMs: Measured<number>\n let supervisorWallSource: Measured<'stamps' | 'journal-span'>\n if (startedAt !== null && completedAt !== null && completedAt >= startedAt) {\n supervisorWallMs = completedAt - startedAt\n supervisorWallSource = 'stamps'\n } else if (\n completedAt === null &&\n wallSpanStart !== null &&\n wallSpanEnd !== null &&\n wallSpanEnd >= wallSpanStart\n ) {\n supervisorWallMs = wallSpanEnd - wallSpanStart\n supervisorWallSource = 'journal-span'\n } else {\n const reason = !haveJournal\n ? journalMissing\n : 'no parseable start/complete timestamps in state.json or journal'\n supervisorWallMs = gap('supervisorWallMs', reason)\n supervisorWallSource = unavailable(reason)\n }\n // Where the measured wall ends — the completion stamp, or the last stamped\n // journal event on the journal-span path. Idle and utilization integrate to\n // this bound so their denominator is the wall they are reported against.\n const wallEndAt = completedAt ?? (supervisorWallSource === 'journal-span' ? wallSpanEnd : null)\n return { supervisorWallMs, supervisorWallSource, wallEndAt }\n}\n\n/** Steer counts from worker inboxes and the driver log. */\nexport function measureSteers(a: Analysis) {\n const { src, gap, tree, workersGapReason } = a\n // ── steers (worker inbox + control events) ─────────────────────────────\n const steerRows: SteerBreakdown[] = []\n let steerQueuedTotal = 0\n let steerDeliveredTotal = 0\n let upLegMessages = 0\n if (src.workers !== null) {\n for (const w of src.workers) {\n const facts = tree.workerLogs.get(workerSourceKey(w))\n const queued = facts?.steersQueued ?? null\n const delivered = facts?.steersDelivered ?? null\n upLegMessages += facts?.questions ?? 0\n if (queued !== null && delivered !== null) {\n steerRows.push({ workerId: w.workerId ?? null, worker: w.label, queued, delivered })\n }\n if (queued !== null) steerQueuedTotal += queued\n if (delivered !== null) steerDeliveredTotal += delivered\n }\n }\n const unavailableReasons = (pick: (facts: WorkerLogFacts) => string | null): string | null => {\n const reasons = tree.workerLogRows\n .map((facts) => pick(facts))\n .filter((reason): reason is string => reason !== null)\n return reasons.length === 0\n ? null\n : `exact steer accounting unavailable for ${reasons.length} worker row(s): ${[...new Set(reasons)].join(' | ')}`\n }\n const queuedGapReason = unavailableReasons((facts) => facts.steersQueuedUnavailable)\n const deliveredGapReason = unavailableReasons((facts) => facts.steersDeliveredUnavailable)\n const workerEventsGapReason = unavailableReasons((facts) =>\n !facts.eventsCaptured\n ? 'events absent'\n : facts.eventsInvalidRows > 0\n ? 'events contain malformed rows'\n : null,\n )\n const steers: Measured<number> =\n src.workers === null\n ? gap('steers', workersGapReason)\n : queuedGapReason === null\n ? steerQueuedTotal\n : gap('steers', queuedGapReason)\n const steersDelivered: Measured<number> =\n src.workers === null\n ? unavailable(workersGapReason)\n : deliveredGapReason === null\n ? steerDeliveredTotal\n : unavailable(deliveredGapReason)\n const steersByWorker: Measured<readonly SteerBreakdown[]> =\n src.workers === null\n ? unavailable(workersGapReason)\n : queuedGapReason === null && deliveredGapReason === null\n ? steerRows\n : unavailable(queuedGapReason ?? deliveredGapReason ?? workersGapReason)\n\n // The `[driver] registered tools: …supervisor_steer…` banner names the verb without\n // invoking it, so banner lines are subtracted from the raw mention count.\n const driverSteerCalls: Measured<number> =\n src.driverLog === null\n ? gap('driverSteerCalls', 'driver.log absent')\n : Math.max(\n 0,\n (src.driverLog.match(/supervisor_steer/g) ?? []).length -\n registrationMentions(src.driverLog),\n )\n return {\n steers,\n steersDelivered,\n steersByWorker,\n driverSteerCalls,\n steerQueuedTotal,\n upLegMessages,\n queuedGapReason,\n workerEventsGapReason,\n }\n}\n\n/** Waves, peak concurrency, idle time and summed worker wall from the spawn/close timeline. */\nexport function measureConcurrency(a: Analysis, wallEndAt: number | null) {\n const { workerSpawns, workerCloses, startedAt } = a\n const timeline: { at: number; delta: 1 | -1 }[] = []\n for (const s of workerSpawns) if (s.at !== null) timeline.push({ at: s.at, delta: 1 })\n for (const c of workerCloses) if (c.at !== null) timeline.push({ at: c.at, delta: -1 })\n timeline.sort((a, b) => a.at - b.at || a.delta - b.delta)\n\n let waves = 0\n const waveSizes: number[] = []\n let closedSinceWaveStart = true\n for (const step of timeline) {\n if (step.delta === 1) {\n if (closedSinceWaveStart) {\n waves += 1\n waveSizes.push(0)\n closedSinceWaveStart = false\n }\n waveSizes[waveSizes.length - 1] = (waveSizes[waveSizes.length - 1] ?? 0) + 1\n } else {\n closedSinceWaveStart = true\n }\n }\n\n let live = 0\n let maxConcurrency = 0\n let idleMs = 0\n let sumWorkerWallMs = 0\n let prev = startedAt\n for (const step of timeline) {\n if (prev !== null && step.at >= prev) {\n const span = step.at - prev\n if (live === 0) idleMs += span\n sumWorkerWallMs += span * live\n }\n live += step.delta\n if (live > maxConcurrency) maxConcurrency = live\n prev = step.at\n }\n if (prev !== null && wallEndAt !== null && wallEndAt >= prev) {\n const span = wallEndAt - prev\n if (live === 0) idleMs += span\n sumWorkerWallMs += span * live\n }\n return { waves, waveSizes, maxConcurrency, idleMs, sumWorkerWallMs }\n}\n\n/** Respawn counts per parent, split by whether a sibling closed in between. */\nexport function measureRespawns(a: Analysis) {\n const { workerSpawns, closeById } = a\n const childSpawnsByParent = new Map<string, SpawnRow[]>()\n for (const spawn of workerSpawns) {\n if (spawn.parent === null) continue\n const siblings = childSpawnsByParent.get(spawn.parent) ?? []\n siblings.push(spawn)\n childSpawnsByParent.set(spawn.parent, siblings)\n }\n\n let respawns = 0\n let observeThenRespawn = 0\n let respawnWithoutEvidence = 0\n const repeatedLabelSet = new Set<string>()\n for (const siblings of childSpawnsByParent.values()) {\n const labelCounts = new Map<string, number>()\n for (const spawn of siblings) {\n labelCounts.set(spawn.label, (labelCounts.get(spawn.label) ?? 0) + 1)\n }\n for (const [label, count] of labelCounts) {\n if (count > 1) repeatedLabelSet.add(label)\n }\n\n const orderedSpawns = siblings\n .map((spawn, index) => ({ spawn, index }))\n .filter(\n (row): row is { spawn: SpawnRow & { at: number }; index: number } => row.spawn.at !== null,\n )\n .sort((a, b) => a.spawn.at - b.spawn.at || a.index - b.index)\n const directCloseTimes = siblings\n .map((spawn) => closeById.get(spawn.id)?.at ?? null)\n .filter((at): at is number => at !== null)\n .sort((a, b) => a - b)\n const firstDirectClose = directCloseTimes[0] ?? null\n\n for (let i = 1; i < orderedSpawns.length; i += 1) {\n const previous = orderedSpawns[i - 1]?.spawn.at\n const current = orderedSpawns[i]?.spawn.at\n if (previous === undefined || current === undefined) continue\n if (firstDirectClose === null || current <= firstDirectClose) continue\n respawns += 1\n const sawEvidence = hasNumberBetween(directCloseTimes, previous, current)\n if (sawEvidence) observeThenRespawn += 1\n else respawnWithoutEvidence += 1\n }\n }\n const repeatedLabels = [...repeatedLabelSet]\n return { respawns, observeThenRespawn, respawnWithoutEvidence, repeatedLabels }\n}\n\n/** The deepest chain of spawns below the root. */\nexport function measureDelegationDepth(a: Analysis) {\n const { tree, rootId, workerSpawns } = a\n const parentOf = new Map(tree.spawns.map((s) => [s.id, s.parent]))\n let delegationDepth = 0\n for (const s of workerSpawns) {\n let d = 0\n let cur: string | null = s.id\n const seen = new Set<string>()\n while (cur !== null && cur !== rootId && !seen.has(cur)) {\n seen.add(cur)\n d += 1\n cur = parentOf.get(cur) ?? null\n }\n if (d > delegationDepth) delegationDepth = d\n }\n return delegationDepth\n}\n\nexport function buildOrchestration(a: Analysis, m: StepFacts): OrchestrationMetrics {\n const { gap, journalMissing, haveJournal, workerSpawns, workerCloses, startedAt } = a\n const {\n supervisorWallMs,\n supervisorWallSource,\n steers,\n steersDelivered,\n steersByWorker,\n driverSteerCalls,\n waves,\n waveSizes,\n maxConcurrency,\n idleMs,\n sumWorkerWallMs,\n respawns,\n repeatedLabels,\n delegationDepth,\n } = m\n const firstWorkerSpawnAt = workerSpawns.reduce<number | null>(\n (acc, s) => (s.at === null ? acc : acc === null ? s.at : Math.min(acc, s.at)),\n null,\n )\n\n const orchestration: OrchestrationMetrics = {\n workersSpawned: haveJournal ? workerSpawns.length : gap('workersSpawned', journalMissing),\n workersSettled: haveJournal\n ? workerCloses.filter((c) => c.kind === 'settled').length\n : unavailable(journalMissing),\n workersCancelled: haveJournal\n ? workerCloses.filter((c) => c.kind === 'cancelled').length\n : unavailable(journalMissing),\n steers,\n steersDelivered,\n steersByWorker,\n driverSteerCalls,\n waves: haveJournal ? waves : unavailable(journalMissing),\n waveSizes: haveJournal ? waveSizes : unavailable(journalMissing),\n maxConcurrency: haveJournal ? maxConcurrency : unavailable(journalMissing),\n respawns: haveJournal ? respawns : unavailable(journalMissing),\n repeatedLabels: haveJournal ? repeatedLabels : unavailable(journalMissing),\n delegationDepth: haveJournal ? delegationDepth : unavailable(journalMissing),\n timeToFirstSpawnMs:\n startedAt !== null && firstWorkerSpawnAt !== null\n ? firstWorkerSpawnAt - startedAt\n : haveJournal\n ? unavailable('no worker spawn timestamps')\n : unavailable(journalMissing),\n supervisorWallMs,\n supervisorWallSource,\n idleMs: isUnavailable(supervisorWallMs) ? unavailable(supervisorWallMs.unavailable) : idleMs,\n idlePct:\n isUnavailable(supervisorWallMs) || supervisorWallMs === 0\n ? isUnavailable(supervisorWallMs)\n ? unavailable(supervisorWallMs.unavailable)\n : unavailable('supervisor wall is 0ms')\n : round((idleMs / supervisorWallMs) * 100, 1),\n workerUtilization:\n isUnavailable(supervisorWallMs) || supervisorWallMs === 0\n ? isUnavailable(supervisorWallMs)\n ? unavailable(supervisorWallMs.unavailable)\n : unavailable('supervisor wall is 0ms')\n : round(sumWorkerWallMs / supervisorWallMs, 3),\n }\n return orchestration\n}\n\n/** Whether sorted values contain one value in the inclusive interval. */\nfunction hasNumberBetween(sorted: readonly number[], low: number, high: number): boolean {\n let left = 0\n let right = sorted.length\n while (left < right) {\n const middle = left + Math.floor((right - left) / 2)\n if ((sorted[middle] as number) < low) left = middle + 1\n else right = middle\n }\n return left < sorted.length && (sorted[left] as number) <= high\n}\n\n/** `[driver] registered tools: …supervisor_steer…` is a banner, not an invocation. */\nfunction registrationMentions(driverLog: string): number {\n let n = 0\n for (const line of driverLog.split('\\n')) {\n if (line.includes('registered tools:') && line.includes('supervisor_steer')) n += 1\n }\n return n\n}\n\nexport type StepFacts = ReturnType<typeof measureWall> &\n ReturnType<typeof measureSteers> &\n ReturnType<typeof measureConcurrency> &\n ReturnType<typeof measureRespawns> & { delegationDepth: number }\n","/** Unified-diff target, line, and test-file touch counts. */\nimport type { PatchStats } from './types'\n\n/** Unified-diff stats. Counts `+++ b/<path>` targets, body +/- lines, and test-file touches. */\nexport function parsePatch(text: string): PatchStats {\n const files = new Set<string>()\n const testFiles = new Set<string>()\n let added = 0\n let removed = 0\n for (const line of text.split('\\n')) {\n if (line.startsWith('+++ ')) {\n const p = line.slice(4).trim().replace(/^b\\//, '')\n if (p !== '/dev/null') {\n files.add(p)\n if (isTestPath(p)) testFiles.add(p)\n }\n continue\n }\n if (line.startsWith('--- ') || line.startsWith('diff --git') || line.startsWith('index ')) {\n continue\n }\n if (line.startsWith('+')) added += 1\n else if (line.startsWith('-')) removed += 1\n }\n return {\n files: files.size,\n linesAdded: added,\n linesRemoved: removed,\n testFilesTouched: [...testFiles].sort(),\n }\n}\n\nfunction isTestPath(p: string): boolean {\n const base = p.split('/').pop() ?? p\n return (\n /(^|\\/)(tests?|__tests__|testing|spec)(\\/|$)/.test(p) ||\n /\\.(test|spec)\\.[cm]?[jt]sx?$/.test(base) ||\n /^test_.*\\.py$/.test(base) ||\n /_test\\.py$/.test(base)\n )\n}\n","import type { Analysis } from './analyze-context'\nimport type { TotalUsd } from './analyze-spend'\nimport { parsePatch } from './patch-stats'\nimport {\n isUnavailable,\n type Measured,\n type OutcomeMetrics,\n type PatchStats,\n unavailable,\n} from './types'\n\n/** Terminal status, verdicts, judge result and the delivered patch. */\nexport function buildOutcome(a: Analysis, t: TotalUsd): OutcomeMetrics {\n const { src, gap, state, result, judge, terminal } = a\n const { stateResult } = t\n const patchStats: Measured<PatchStats> =\n src.patch === null\n ? gap('patch', src.limits.deliverables ?? 'delivered patch file absent')\n : parsePatch(src.patch)\n\n const outcome: OutcomeMetrics = {\n supStatus: isUnavailable(terminal.supStatus)\n ? gap('supStatus', terminal.supStatus.unavailable)\n : terminal.supStatus,\n supStatusSource: terminal.supStatusSource,\n supReason: terminal.supReason,\n failure: terminal.failure,\n supVerdict:\n pickString(state, 'verdict') ??\n pickString(result, 'sup_verdict') ??\n unavailable('no state.json / result.json verdict'),\n delivered:\n typeof stateResult.delivered === 'boolean'\n ? stateResult.delivered\n : typeof result?.delivered === 'boolean'\n ? result.delivered\n : unavailable('no delivered flag in state.json or result.json'),\n judgeResolved:\n judge === null\n ? gap('judge', 'judge.json absent')\n : typeof judge.resolved === 'boolean'\n ? judge.resolved\n : null,\n judgeScore:\n judge === null\n ? unavailable('judge.json absent')\n : typeof judge.score === 'number'\n ? judge.score\n : null,\n judgePassed:\n judge === null\n ? unavailable('judge.json absent')\n : typeof judge.passed === 'number'\n ? judge.passed\n : null,\n judgeTotal:\n judge === null\n ? unavailable('judge.json absent')\n : typeof judge.total === 'number'\n ? judge.total\n : null,\n verifyPass:\n typeof result?.verify_pass === 'boolean'\n ? result.verify_pass\n : gap('verifyPass', 'result.json absent or has no verify_pass'),\n verifyRc:\n typeof result?.verify_rc === 'number'\n ? result.verify_rc\n : unavailable('result.json absent or has no verify_rc'),\n patch: patchStats,\n judgeSource: src.judgeSource,\n }\n return outcome\n}\n\nfunction pickString(rec: Record<string, unknown> | null, key: string): string | null {\n const v = rec?.[key]\n return typeof v === 'string' ? v : null\n}\n","import { roundDecimal as round } from '../math/round-decimal'\nimport type { Analysis } from './analyze-context'\nimport { asRecord } from './source-facts'\nimport { type Measured, type SpendMeasurements, unavailable } from './types'\n\n/** Spend records of the root and its children, split into reporting and unreporting. */\nexport function collectSpendFacts(a: Analysis) {\n const { tree, rootId, workerSpawns, workerCloses } = a\n const rootChildIds = new Set(\n workerSpawns.filter((spawn) => spawn.parent === rootId).map((spawn) => spawn.id),\n )\n const rootChildCloses = workerCloses.filter((close) => rootChildIds.has(close.id))\n // Runtime marks a spend record `usdKnown: false` / `tokensKnown: false` when the work\n // HAPPENED but no provider receipt covered its price or its tokens. Folding such a record\n // in prices unreported work at zero; dropping the whole channel discards every record that\n // DID report. So each channel sums only the reporting records and names the rest.\n const rootChildSpends = rootChildCloses.filter((close) => close.hasSpend)\n const workerUsdUnknownNodes = rootChildSpends\n .filter((close) => !close.spend.usdKnown)\n .map((close) => close.id)\n const workerTokensUnknownNodes = rootChildSpends\n .filter((close) => !close.spend.tokensKnown)\n .map((close) => close.id)\n const workerTokenSpends = rootChildSpends.filter((close) => close.spend.tokensKnown)\n const journalWorkerIn = workerTokenSpends.reduce((a, c) => a + c.spend.tokens.input, 0)\n const journalWorkerOut = workerTokenSpends.reduce((a, c) => a + c.spend.tokens.output, 0)\n const journalWorkerUsd = rootChildSpends\n .filter((close) => close.spend.usdKnown)\n .reduce((a, c) => a + c.spend.usd, 0)\n const usdUnknownIds = new Set(\n workerCloses.filter((close) => close.hasSpend && !close.spend.usdKnown).map((c) => c.id),\n )\n const workerUsdById = new Map<string, number>()\n for (const c of workerCloses) {\n if (usdUnknownIds.has(c.id)) continue\n workerUsdById.set(c.id, (workerUsdById.get(c.id) ?? 0) + c.spend.usd)\n }\n const labelById = new Map(workerSpawns.map((spawn) => [spawn.id, spawn.label]))\n const usdUnknownLabels = new Set(\n [...usdUnknownIds].map((id) => labelById.get(id)).filter((l): l is string => l !== undefined),\n )\n const workerUsdByLabel = new Map<string, number>()\n for (const close of workerCloses) {\n const label = labelById.get(close.id)\n if (label === undefined || usdUnknownLabels.has(label)) continue\n workerUsdByLabel.set(label, (workerUsdByLabel.get(label) ?? 0) + close.spend.usd)\n }\n const brainUsdUnknownNodes =\n tree.brain.usdUnknownCount > 0 && rootId !== null ? ([rootId] as const) : []\n const brainTokensUnknownNodes =\n tree.brain.tokensUnknownCount > 0 && rootId !== null ? ([rootId] as const) : []\n const usdKnownRecords =\n tree.brain.usdKnownCount + rootChildSpends.filter((close) => close.spend.usdKnown).length\n const usdUnknownRecords = tree.brain.usdUnknownCount + workerUsdUnknownNodes.length\n const usdUnknownNodes = [...brainUsdUnknownNodes, ...workerUsdUnknownNodes]\n // The named nodes are what makes the gap actionable, but a fleet run can have hundreds,\n // and this string lands in a report line. Name the first few and count the rest.\n const NAMED_NODE_LIMIT = 5\n const nameNodes = (nodes: readonly string[]): string => {\n if (nodes.length === 0) return ''\n const shown = nodes.slice(0, NAMED_NODE_LIMIT)\n const rest = nodes.length - shown.length\n return ` (${shown.join(', ')}${rest === 0 ? '' : ` +${rest} more`})`\n }\n const unpriced = (unknown: number, total: number, nodes: readonly string[]): string =>\n `Runtime recorded usdKnown:false on ${unknown} of ${total} spend record(s)${nameNodes(nodes)}`\n // A token total is a bare `Measured<number>` with no record denominator beside it, so a\n // partial sum there would be an unlabelled floor — the exact collapse this module refuses.\n // Spend has `SpendMeasurement.records`/`unknownRecords` to carry the split, so it stays\n // partial; tokens go absent with the unreporting nodes named.\n const unreportedTokens = (unknown: number, total: number, nodes: readonly string[]): string =>\n `Runtime recorded tokensKnown:false on ${unknown} of ${total} spend record(s)${nameNodes(nodes)}`\n const usdPartial = usdKnownRecords > 0 && usdUnknownRecords > 0\n const usdAllUnknown = usdKnownRecords === 0 && usdUnknownRecords > 0\n // A role whose records are ALL unreported has nothing measured to report, so it stays\n // unavailable. A role with some of each keeps its sum and labels it in `source`.\n const brainTokensUnreported =\n tree.brain.tokensUnknownCount === 0\n ? null\n : unreportedTokens(\n tree.brain.tokensUnknownCount,\n tree.brain.meteredCount,\n brainTokensUnknownNodes,\n )\n const brainUsdUnreported =\n tree.brain.usdKnownCount > 0 || tree.brain.usdUnknownCount === 0\n ? null\n : unpriced(tree.brain.usdUnknownCount, tree.brain.meteredCount, brainUsdUnknownNodes)\n const workerUsdUnreported =\n workerUsdUnknownNodes.length === 0 || workerUsdUnknownNodes.length < rootChildSpends.length\n ? null\n : unpriced(workerUsdUnknownNodes.length, rootChildSpends.length, workerUsdUnknownNodes)\n return {\n rootChildCloses,\n rootChildSpends,\n workerUsdUnknownNodes,\n workerTokensUnknownNodes,\n journalWorkerIn,\n journalWorkerOut,\n journalWorkerUsd,\n workerUsdById,\n workerUsdByLabel,\n usdKnownRecords,\n usdUnknownRecords,\n usdUnknownNodes,\n brainUsdUnknownNodes,\n brainTokensUnknownNodes,\n unpriced,\n unreportedTokens,\n usdPartial,\n usdAllUnknown,\n brainTokensUnreported,\n brainUsdUnreported,\n workerUsdUnreported,\n }\n}\n\n/** Worker token totals: journal spend plus harness session counts, or the reason they are absent. */\nexport function measureWorkerTokens(a: Analysis, f: SpendFacts) {\n const { src, gap, haveJournal } = a\n const {\n rootChildSpends,\n workerTokensUnknownNodes,\n journalWorkerIn,\n journalWorkerOut,\n unreportedTokens,\n } = f\n const sq = src.harnessWorkerTokens\n const harnessGapReason =\n src.harnessMissingReason ?? 'harness session store unavailable and journal settled spend is 0'\n const workerTokenLimit = src.limits.workerTokens\n const workerTokensUnreported =\n workerTokensUnknownNodes.length === 0\n ? null\n : unreportedTokens(\n workerTokensUnknownNodes.length,\n rootChildSpends.length,\n workerTokensUnknownNodes,\n )\n const workerIn: Measured<number> =\n workerTokenLimit !== null\n ? gap('workers.tokensIn', workerTokenLimit)\n : workerTokensUnreported !== null\n ? gap('workers.tokensIn', workerTokensUnreported)\n : sq !== null\n ? journalWorkerIn + sq.input\n : haveJournal\n ? journalWorkerIn\n : gap('workers.tokensIn', harnessGapReason)\n const workerOut: Measured<number> =\n workerTokenLimit !== null\n ? unavailable(workerTokenLimit)\n : workerTokensUnreported !== null\n ? unavailable(workerTokensUnreported)\n : sq !== null\n ? journalWorkerOut + sq.output\n : haveJournal\n ? journalWorkerOut\n : unavailable(harnessGapReason)\n return { sq, workerTokenLimit, workerIn, workerOut }\n}\n\n/** Total USD and the close record it is read against. */\nexport function measureTotalUsd(a: Analysis, f: SpendFacts) {\n const { src, gap, journalMissing, haveJournal, tree, state, result } = a\n const { journalWorkerUsd, usdKnownRecords, usdUnknownRecords, usdUnknownNodes, unpriced } = f\n const stateResult = asRecord(state?.result)\n const stateUsd = typeof stateResult.spentUsd === 'number' ? stateResult.spentUsd : null\n const resultSpentTotal = asRecord(result?.spentTotal)\n const resultCloseUsd =\n typeof resultSpentTotal.usd === 'number' && Number.isFinite(resultSpentTotal.usd)\n ? resultSpentTotal.usd\n : null\n // The close record: what the store wrote as settled when the run closed.\n const closeUsd = stateUsd ?? resultCloseUsd\n // A store that logs tokens but never a price yields usd 0 from every sum. That\n // 0 is the store's silence, not a free run, so the limit outranks the sum.\n const usdLimit = src.limits.spendUsd\n // The close record carries its own completeness flag: `spentTotal.usdKnown: false` means\n // Runtime priced part of the run from a catalog, so the number is a floor, not a total.\n const closeUsdUnreported =\n stateUsd === null && resultCloseUsd !== null && resultSpentTotal.usdKnown === false\n const usdUnreportedReason = unpriced(\n usdUnknownRecords,\n usdKnownRecords + usdUnknownRecords,\n usdUnknownNodes,\n )\n // Which numbers may be partial, and which must go absent: a number may be a floor only\n // when its own record carries the known/unknown split beside it — `SpendMeasurement`\n // has `records`/`unknownRecords`, and `RoleSpend` has `source`. `totalUsd` is a bare\n // scalar, so a floor there is an unlabelled understatement and stays unavailable; the\n // partial sum with its denominators lives in `spend.journalDerived`, which this type's\n // own doc already names as the field to prefer.\n const totalUsd: Measured<number> =\n usdLimit !== null\n ? gap('totalUsd', usdLimit)\n : stateUsd !== null\n ? round(stateUsd, 6)\n : !haveJournal\n ? gap('totalUsd', journalMissing)\n : usdUnknownRecords > 0\n ? gap('totalUsd', usdUnreportedReason)\n : round(tree.brain.usd + journalWorkerUsd, 6)\n return {\n stateResult,\n stateUsd,\n usdLimit,\n totalUsd,\n closeUsd,\n closeUsdUnreported,\n usdUnreportedReason,\n }\n}\n\nexport function buildSpend(a: Analysis, f: SpendFacts, t: TotalUsd): SpendMeasurements {\n const { journalMissing, haveJournal, tree, rootId } = a\n const {\n journalWorkerUsd,\n usdKnownRecords,\n usdUnknownRecords,\n usdUnknownNodes,\n usdPartial,\n usdAllUnknown,\n } = f\n const { usdLimit, closeUsd, closeUsdUnreported, usdUnreportedReason } = t\n const journalSpendRecords = usdKnownRecords\n // `journalDerived` keeps its partial sum: `records` and `unknownRecords` state exactly\n // how much of the run it covers. Only an all-unreported channel has nothing to report.\n const journalDerivedAvailable = usdLimit === null && haveJournal && !usdAllUnknown\n const closeRecordAvailable = usdLimit === null && closeUsd !== null && !closeUsdUnreported\n const spend: SpendMeasurements = {\n journalDerived: {\n usd: journalDerivedAvailable\n ? round(tree.brain.usd + journalWorkerUsd, 6)\n : unavailable(usdLimit ?? (haveJournal ? usdUnreportedReason : journalMissing)),\n records: journalDerivedAvailable ? journalSpendRecords : 0,\n unknownRecords: usdLimit === null && haveJournal ? usdUnknownRecords : 0,\n partial: journalDerivedAvailable && usdPartial,\n unknownNodes: usdLimit === null && haveJournal ? usdUnknownNodes : [],\n },\n closeRecord: {\n usd: closeRecordAvailable\n ? round(closeUsd as number, 6)\n : unavailable(\n usdLimit ??\n (closeUsdUnreported\n ? 'close record incomplete: result.json spentTotal.usdKnown is false'\n : 'no close record: neither state.json result.spentUsd nor result.json spentTotal.usd is present'),\n ),\n records: closeRecordAvailable ? 1 : 0,\n unknownRecords: closeUsdUnreported ? 1 : 0,\n partial: false,\n unknownNodes: closeUsdUnreported && rootId !== null ? [rootId] : [],\n },\n }\n return spend\n}\n\nexport type SpendFacts = ReturnType<typeof collectSpendFacts>\nexport type WorkerTokens = ReturnType<typeof measureWorkerTokens>\nexport type TotalUsd = ReturnType<typeof measureTotalUsd>\n","/**\n * The pure analyzer. Takes already-read bytes (`SupervisorRunSources`) and\n * returns the report — every metric derivable from a synthetic journal string\n * with no filesystem, no process, and no network. All I/O lives in a reader\n * (`reader.ts` is one).\n *\n * The metric groups live in `analyze-*.ts`; this file only runs them in the\n * order the report's `gaps` list is written.\n */\n\nimport { createAnalysis } from './analyze-context'\nimport { measureDecision } from './analyze-decision'\nimport { buildEconomics, buildPerWorker } from './analyze-economics'\nimport {\n buildOrchestration,\n measureConcurrency,\n measureDelegationDepth,\n measureRespawns,\n measureSteers,\n measureWall,\n} from './analyze-orchestration'\nimport { buildOutcome } from './analyze-outcome'\nimport {\n buildSpend,\n collectSpendFacts,\n measureTotalUsd,\n measureWorkerTokens,\n} from './analyze-spend'\nimport {\n SUPERVISOR_RUN_SCHEMA,\n type SupervisorRunReport,\n type SupervisorRunSources,\n unavailable,\n} from './types'\n\n/**\n * Analyze already-read supervisor-run bytes. Pure and synchronous: same bytes\n * in, same report out (modulo `generatedAt`, which `now` pins in tests).\n */\nexport function analyzeSupervisorRunSources(\n src: SupervisorRunSources,\n now: () => number = Date.now,\n): SupervisorRunReport {\n const a = createAnalysis(src)\n const { gap, gaps, rootId, rootSpawn, journalMissing } = a\n // Measurements record their gaps as they run, so the order below is the order of `report.gaps`.\n const wall = measureWall(a)\n const steerFacts = measureSteers(a)\n const concurrency = measureConcurrency(a, wall.wallEndAt)\n const respawns = measureRespawns(a)\n const steps = {\n ...wall,\n ...steerFacts,\n ...concurrency,\n ...respawns,\n delegationDepth: measureDelegationDepth(a),\n }\n const orchestration = buildOrchestration(a, steps)\n const decision = measureDecision(a, steps)\n const spendFacts = collectSpendFacts(a)\n const tokens = measureWorkerTokens(a, spendFacts)\n const totals = measureTotalUsd(a, spendFacts)\n const spend = buildSpend(a, spendFacts, totals)\n const perWorker = buildPerWorker(a, spendFacts, totals)\n const economics = buildEconomics(a, spendFacts, totals, tokens, { decision, spend, perWorker })\n const outcome = buildOutcome(a, totals)\n return {\n schema: SUPERVISOR_RUN_SCHEMA,\n runRef: src.runRef,\n instanceId: src.instanceId,\n arm: src.arm,\n supervisorId: rootId !== null ? rootId : unavailable(journalMissing),\n supervisorProfileDigest:\n rootSpawn?.profileDigest !== null && rootSpawn?.profileDigest !== undefined\n ? rootSpawn.profileDigest\n : gap('supervisorProfileDigest', 'root spawned event has no profile digest'),\n generatedAt: new Date(now()).toISOString(),\n orchestration,\n decision,\n economics,\n outcome,\n rootWorkspaceCaptures: src.rootWorkspaceCaptures ?? null,\n gaps,\n traceCommand:\n src.traceCommand ??\n 'npx --yes @tangle-network/traces@latest analyze --harness opencode --cwd <worker-clone-cwd>',\n }\n}\n","/**\n * Optional Runtime run-dir files, read as bytes.\n *\n * `coordination-log.jsonl` is Runtime's JSONL of `{ runId, seq, at, event }`:\n * questions, steers, answers and peer mail between nodes. The `team-shape`\n * analyst reads communication and steer edges from it.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nconst COORDINATION_FILE = 'coordination-log.jsonl'\nexport const readFileText = (path: string): Promise<string> => readFile(path, 'utf8')\n\n/** File text, or null when the file does not exist. Any other read error throws. */\nexport async function readMaybe(path: string, read = readFileText): Promise<string | null> {\n return read(path).catch((error: unknown) => {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code: unknown }).code === 'ENOENT'\n ) {\n return null\n }\n throw error\n })\n}\n\n/** The run's coordination log, or null when Runtime wrote none. */\nexport function readCoordinationLog(runDir: string, read = readFileText): Promise<string | null> {\n return readMaybe(join(runDir, COORDINATION_FILE), read)\n}\n","import { nonEmptyString, recordOrNull as record } from './source-facts'\nimport type { SourceLimits } from './types'\n\nfunction spendRecord(value: unknown): Record<string, unknown> | null {\n const spend = record(value)\n if (spend === null) return null\n const tokens = record(spend.tokens)\n if (\n tokens === null ||\n typeof tokens.input !== 'number' ||\n !Number.isFinite(tokens.input) ||\n tokens.input < 0 ||\n typeof tokens.output !== 'number' ||\n !Number.isFinite(tokens.output) ||\n tokens.output < 0 ||\n typeof spend.usd !== 'number' ||\n !Number.isFinite(spend.usd) ||\n spend.usd < 0 ||\n (spend.usdKnown !== undefined && typeof spend.usdKnown !== 'boolean')\n ) {\n return null\n }\n return spend\n}\n\nexport function sourceLimits(\n root: string,\n events: readonly Record<string, unknown>[],\n workerIds: ReadonlySet<string>,\n): SourceLimits {\n const rootMeters = events.filter((event) => event.kind === 'metered' && event.id === root)\n const invalidRootMeters = rootMeters.filter((event) => spendRecord(event.spend) === null)\n const rootMeterReason =\n rootMeters.length === 0\n ? 'Runtime journal has no root metered event'\n : invalidRootMeters.length > 0\n ? `${invalidRootMeters.length} root metered event(s) lack complete spend`\n : null\n const closes = events.filter(\n (event) =>\n workerIds.has(nonEmptyString(event.id) ?? '') &&\n (event.kind === 'settled' || event.kind === 'cancelled'),\n )\n const settledById = new Map<string, Record<string, unknown>[]>()\n for (const event of closes) {\n const id = nonEmptyString(event.id)\n if (id === null) continue\n const matches = settledById.get(id) ?? []\n matches.push(event)\n settledById.set(id, matches)\n }\n const incompleteWorkers = [...workerIds].filter((id) => {\n const terminal = settledById.get(id)\n return (\n terminal?.length !== 1 ||\n terminal[0]?.kind !== 'settled' ||\n spendRecord(terminal[0]?.spent) === null\n )\n })\n const missingVerdicts = [...workerIds].filter((id) => {\n const terminal = settledById.get(id)?.[0]\n if (terminal?.kind !== 'settled') return true\n const verdict = record(terminal.verdict)\n return typeof verdict?.valid !== 'boolean'\n })\n\n return {\n managerTokens: rootMeterReason,\n workerTokens:\n incompleteWorkers.length === 0\n ? null\n : `${incompleteWorkers.length}/${workerIds.size} child invocation(s) lack one settled spend record`,\n // `usdKnown: false` on ONE record is not a limit of this store: the store priced every\n // other record, and a limit here discards them all. The analyzer folds the flag per\n // record instead, and reports a partial total with the unpriced nodes named.\n spendUsd:\n rootMeterReason !== null\n ? rootMeterReason\n : incompleteWorkers.length > 0\n ? 'at least one child invocation lacks a settled spend record'\n : null,\n workerVerdicts:\n missingVerdicts.length === 0\n ? null\n : `${missingVerdicts.length}/${workerIds.size} child invocation(s) lack a structured validity verdict`,\n deliverables:\n workerIds.size === 0\n ? null\n : 'Runtime FileRunContext does not retain per-child delivered patches',\n }\n}\n","/**\n * Reader for agent-runtime's file-backed supervision context.\n *\n * Runtime stores multiple recursive trees in one `spawn-journal.jsonl`.\n * Each line is an envelope whose `root` identifies the local tree. A journal\n * can connect a nested tree with `spawned.ownedTreeRoot`. It can also use the\n * spawned child id as the nested root when no owned tree is recorded. Either\n * way the nested tree may repeat its owner's spawn as a parentless marker: the\n * owner's id, not the tree key, identifies it (an owned tree's key is a path\n * such as `root/root:s0`). Descendant spawns must occur in the tree their\n * parent owns. This reader removes a duplicate marker and preserves the other\n * envelopes for the supervisor-run analyzer. Runtime stores profile\n * identity below `identity` and does not emit Eval's role field. This boundary\n * projects those fields without changing Runtime's dialect.\n *\n * Transcripts come from Runtime's own records too: `root-stream.jsonl` is the root's, each\n * worker's turn outputs and native-session receipt are read from the journal, and every blob\n * a record names is checked on disk (see `nodeTranscripts`).\n *\n * The run's terminal record is Runtime's own: `result.json` is the\n * `SupervisedResult` that `supervise()` returned, verbatim, and its `kind`\n * (`winner`, `no-winner`, or whatever a later arm is called) is the status.\n * `failure.json` (`{ runId, pursuitId, at, error: { name, message } }`) is the\n * record Runtime writes when `supervise()` threw before a result landed. Both\n * pass through as bytes; `terminal-record.ts` reads them. The reader does not\n * decide which kinds count: a kind it refuses is a run that recorded its\n * outcome and got reported as having none. The reader does not synthesize status fields. The analyzer names the Runtime\n * record that supplied a status, so status provenance cannot be mislabelled.\n *\n * `usdKnown: false` / `tokensKnown: false` on ONE record is not a limit of this\n * store. The store recorded every other record completely, so the flags travel\n * through to the analyzer per record, which reports the measured nodes and\n * names the unreported ones.\n */\n\nimport { stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { hashCanonical } from '../ledger-core/canonical'\nimport type { RolloutWorkspaceCapture } from '../rollout/schema'\nimport { readCoordinationLog, readFileText, readMaybe } from './coordination-reader'\nimport { expandJournalEventGroup } from './journal-event-group'\nimport { sourceLimits } from './runtime-source-limits'\nimport { nonEmptyString, recordOrNull as record } from './source-facts'\nimport {\n NO_SOURCE_LIMITS,\n type SupervisorRunSources,\n type WorkerLogSource,\n type WorkerNativeSession,\n} from './types'\n\nconst JOURNAL_FILE = 'spawn-journal.jsonl'\nconst OBSERVER_FILE = 'observer.jsonl'\nconst ROOT_STREAM_FILE = 'root-stream.jsonl'\nconst BLOB_DIR = 'blobs'\nconst RESULT_FILE = 'result.json'\nconst FAILURE_FILE = 'failure.json'\n\n/**\n * The files only Runtime's durable layer writes. Any one of them marks a\n * Runtime run directory: `supervise()` opens the spawn journal on its first\n * event, and `supervisePursuit` appends the observer's `before` event and, on\n * a throw, the failure record before any spawn.\n *\n * Measured motive (discovery-lab recursive smoke r1, 2026-09-06): the first\n * attempt threw on a caller input error 16 minutes before the corrected attempt\n * opened the spawn journal. At that instant the directory held `observer.jsonl`\n * (2 records) and the failure record and no journal, so a journal-only test\n * routed it to an unrelated reader, which reads neither file, and the recorded\n * throw was reported as no run at all.\n */\nconst RUNTIME_RUN_DIR_MARKERS: readonly string[] = [JOURNAL_FILE, OBSERVER_FILE, FAILURE_FILE]\n\ninterface BeginRecord {\n readonly root: string\n readonly at: string\n readonly line: number\n}\n\ninterface EventRecord {\n readonly root: string\n readonly event: Record<string, unknown>\n readonly line: number\n}\n\ninterface NormalizedRuntimeJournal {\n readonly root: string\n readonly startedAt: string\n readonly journal: string\n readonly events: readonly Record<string, unknown>[]\n}\n\nfunction profileDigest(event: Record<string, unknown>): string | null {\n const direct = nonEmptyString(event.profileDigest)\n if (direct !== null) return direct\n const identity = record(event.identity)\n return identity === null ? null : nonEmptyString(identity.profileDigest)\n}\n\nfunction formatError(path: string, line: number, detail: string): Error {\n return new Error(`${path}:${line}: invalid Runtime spawn journal: ${detail}`)\n}\n\nfunction parseEnvelopeJournal(text: string, path: string): NormalizedRuntimeJournal {\n const begins: BeginRecord[] = []\n const events: EventRecord[] = []\n const begun = new Map<string, BeginRecord>()\n\n for (const [index, sourceLine] of text.split('\\n').entries()) {\n const line = index + 1\n const trimmed = sourceLine.trim()\n if (trimmed.length === 0) continue\n let parsed: unknown\n try {\n parsed = JSON.parse(trimmed)\n } catch {\n throw formatError(path, line, 'line is not JSON')\n }\n const envelope = record(parsed)\n if (envelope === null) throw formatError(path, line, 'line is not an object')\n const kind = nonEmptyString(envelope.kind)\n const root = nonEmptyString(envelope.root)\n if (root === null) throw formatError(path, line, 'root must be a non-empty string')\n\n if (kind === 'begin') {\n const at = nonEmptyString(envelope.at)\n if (at === null || !Number.isFinite(Date.parse(at))) {\n throw formatError(path, line, 'begin.at must be an ISO timestamp')\n }\n if (begun.has(root)) throw formatError(path, line, `tree ${JSON.stringify(root)} began twice`)\n const begin = { root, at, line }\n begun.set(root, begin)\n begins.push(begin)\n continue\n }\n\n if (kind !== 'event' && kind !== 'events') {\n throw formatError(path, line, \"kind must be 'begin', 'event' or 'events'\")\n }\n if (!begun.has(root)) {\n throw formatError(path, line, `event for tree ${JSON.stringify(root)} precedes begin`)\n }\n const expanded = expandJournalEventGroup(envelope)\n if (!expanded.succeeded) throw formatError(path, line, expanded.error)\n for (const row of expanded.value) {\n const event = record(row.event)\n if (event === null) throw formatError(path, line, 'event must be an object')\n if (nonEmptyString(event.kind) === null) {\n throw formatError(path, line, 'event.kind must be a non-empty string')\n }\n events.push({ root, event: { ...event }, line })\n }\n }\n\n if (begins.length === 0) throw formatError(path, 1, 'no begin record')\n\n const parentSpawnsById = new Map<string, EventRecord[]>()\n const parentSpawnsByOwnedTreeRoot = new Map<string, EventRecord[]>()\n for (const entry of events) {\n if (entry.event.kind !== 'spawned') continue\n const id = nonEmptyString(entry.event.id)\n if (id === null) continue\n if (nonEmptyString(entry.event.parent) !== null) {\n const ownedTreeRoot = nonEmptyString(entry.event.ownedTreeRoot)\n if (ownedTreeRoot !== null) {\n const owners = parentSpawnsByOwnedTreeRoot.get(ownedTreeRoot) ?? []\n owners.push(entry)\n parentSpawnsByOwnedTreeRoot.set(ownedTreeRoot, owners)\n } else {\n const matches = parentSpawnsById.get(id) ?? []\n matches.push(entry)\n parentSpawnsById.set(id, matches)\n }\n }\n }\n\n const nestedRoots = new Set<string>()\n const nestedParentSpawns = new Map<string, EventRecord>()\n for (const begin of begins) {\n const parentSpawns = [\n ...new Set([\n ...(parentSpawnsByOwnedTreeRoot.get(begin.root) ?? []),\n ...(parentSpawnsById.get(begin.root) ?? []),\n ]),\n ].filter((entry) => entry.root !== begin.root)\n if (parentSpawns.length > 1) {\n throw formatError(\n path,\n begin.line,\n `tree ${JSON.stringify(begin.root)} has ${parentSpawns.length} parent spawns`,\n )\n }\n if (parentSpawns.length === 1) {\n nestedRoots.add(begin.root)\n nestedParentSpawns.set(begin.root, parentSpawns[0] as EventRecord)\n }\n }\n\n const topRoots = begins.filter((begin) => !nestedRoots.has(begin.root))\n if (topRoots.length !== 1) {\n throw formatError(\n path,\n topRoots[0]?.line ?? 1,\n `expected one top-level tree, found ${topRoots.length}`,\n )\n }\n const top = topRoots[0] as BeginRecord\n\n // A tree's root marker is a parentless spawn of the node that owns the tree: the top root\n // itself, or the parent spawn that owns a nested tree. An owned tree's key is a path, so\n // the owner's id is compared, never the tree key.\n const ownerIdByTree = new Map<string, string>([[top.root, top.root]])\n for (const [nestedRoot, parentSpawn] of nestedParentSpawns) {\n const ownerId = nonEmptyString(parentSpawn.event.id)\n if (ownerId !== null) ownerIdByTree.set(nestedRoot, ownerId)\n }\n const isRootMarker = (entry: EventRecord): boolean =>\n entry.event.kind === 'spawned' &&\n (entry.event.parent === undefined || entry.event.parent === null) &&\n nonEmptyString(entry.event.id) !== null &&\n entry.event.id === ownerIdByTree.get(entry.root)\n const rootMarkersByTree = new Map<string, EventRecord[]>()\n for (const entry of events) {\n if (!isRootMarker(entry)) continue\n const markers = rootMarkersByTree.get(entry.root) ?? []\n markers.push(entry)\n rootMarkersByTree.set(entry.root, markers)\n }\n\n for (const nestedRoot of nestedRoots) {\n const markers = rootMarkersByTree.get(nestedRoot) ?? []\n if (markers.length > 1) {\n throw formatError(\n path,\n begun.get(nestedRoot)?.line ?? 1,\n `nested tree ${JSON.stringify(nestedRoot)} contains ${markers.length} root markers`,\n )\n }\n const parentSpawn = nestedParentSpawns.get(nestedRoot)\n if (parentSpawn === undefined) {\n throw formatError(\n path,\n begun.get(nestedRoot)?.line ?? 1,\n `nested tree ${JSON.stringify(nestedRoot)} has no parent spawn`,\n )\n }\n const markerDigest = profileDigest(markers[0]?.event ?? {})\n const parentDigest = profileDigest(parentSpawn.event)\n if (markerDigest !== null && parentDigest !== null && markerDigest !== parentDigest) {\n throw formatError(\n path,\n markers[0]?.line ?? 1,\n `nested tree ${JSON.stringify(nestedRoot)} disagrees with its parent profile digest`,\n )\n }\n if (parentDigest === null && markerDigest !== null) {\n parentSpawn.event.profileDigest = markerDigest\n }\n }\n\n const ownedTreeBySupervisorId = new Map<string, string>([[top.root, top.root]])\n for (const [nestedRoot, parentSpawn] of nestedParentSpawns) {\n const supervisorId = nonEmptyString(parentSpawn.event.id)\n if (supervisorId === null) continue\n const priorTree = ownedTreeBySupervisorId.get(supervisorId)\n if (priorTree !== undefined && priorTree !== nestedRoot) {\n throw formatError(\n path,\n parentSpawn.line,\n `spawn ${JSON.stringify(supervisorId)} owns both ${JSON.stringify(priorTree)} and ${JSON.stringify(nestedRoot)}`,\n )\n }\n ownedTreeBySupervisorId.set(supervisorId, nestedRoot)\n }\n for (const entry of events) {\n if (entry.event.kind !== 'spawned') continue\n const parentId = nonEmptyString(entry.event.parent)\n if (parentId === null) continue\n const parentTree = ownedTreeBySupervisorId.get(parentId)\n if (parentTree === undefined) {\n throw formatError(\n path,\n entry.line,\n `spawn ${JSON.stringify(entry.event.id)} names parent ${JSON.stringify(parentId)}, which owns no journal tree`,\n )\n }\n if (entry.root !== parentTree) {\n throw formatError(\n path,\n entry.line,\n `spawn ${JSON.stringify(entry.event.id)} is in tree ${JSON.stringify(entry.root)}, but parent ${JSON.stringify(parentId)} owns tree ${JSON.stringify(parentTree)}`,\n )\n }\n }\n\n // Runtime's recursive atom has no supervisor/worker role field. A tree root\n // is a supervisor; a child without its own tree is a worker.\n const supervisorIds = new Set([\n top.root,\n ...[...nestedParentSpawns.values()]\n .map((entry) => nonEmptyString(entry.event.id))\n .filter((id): id is string => id !== null),\n ])\n const normalized = events\n .filter((entry) => !(nestedRoots.has(entry.root) && isRootMarker(entry)))\n .map((entry) => {\n const event = { ...entry.event }\n if (event.kind === 'spawned') {\n const digest = profileDigest(event)\n if (event.profileDigest === undefined && digest !== null) {\n event.profileDigest = digest\n }\n if (event.role === undefined) {\n event.role = supervisorIds.has(nonEmptyString(event.id) ?? '') ? 'supervisor' : 'worker'\n }\n }\n return { root: entry.root, event }\n })\n\n const rootMarkers = rootMarkersByTree.get(top.root) ?? []\n if (rootMarkers.length !== 1) {\n throw formatError(\n path,\n top.line,\n `top-level tree ${JSON.stringify(top.root)} must contain one root marker`,\n )\n }\n\n return {\n root: top.root,\n startedAt: top.at,\n // Keep Runtime's event envelope intact. The pure source parser uses the envelope to\n // distinguish an understood-but-unmodeled Runtime event from an unreadable flat record.\n journal: `${normalized\n .map((entry) => JSON.stringify({ kind: 'event', root: entry.root, event: entry.event }))\n .join('\\n')}\\n`,\n events: normalized.map((entry) => entry.event),\n }\n}\n\nfunction parseOptionalRecord(text: string | null, path: string): Record<string, unknown> | null {\n if (text === null) return null\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n throw new Error(`${path}: invalid JSON`)\n }\n const value = record(parsed)\n if (value === null) throw new Error(`${path}: expected a JSON object`)\n return value\n}\n\n/**\n * Refuse a `result.json` that belongs to another run. Runtime's result carries\n * its own `tree.root`; a settled record with a different root is a copied or\n * misplaced file, and reading its status onto this journal misreports the run.\n */\nfunction assertResultMatchesJournal(\n root: string,\n result: Record<string, unknown> | null,\n resultPath: string,\n): void {\n const resultKind = result === null ? null : nonEmptyString(result.kind)\n if (resultKind === null || result === null) return\n const resultRoot = nonEmptyString(record(result.tree)?.root)\n if (resultRoot === null) {\n throw new Error(`${resultPath}: Runtime ${resultKind} result has no tree.root`)\n }\n if (resultRoot !== root) {\n throw new Error(\n `${resultPath}: root ${JSON.stringify(resultRoot)} does not match journal root ${JSON.stringify(root)}`,\n )\n }\n}\n\n/**\n * Refuse a `failure.json` that is not a failure record. Runtime writes\n * `{ runId, pursuitId, at, error: { name, message } }`; a document without an\n * `error` object is not one, and reading it as a failure invents a terminal\n * state the run never recorded. The record carries no tree root, so its\n * identity is not checked against the journal.\n */\nfunction assertFailureRecord(failure: Record<string, unknown> | null, failurePath: string): void {\n if (failure === null) return\n if (record(failure.error) === null) {\n throw new Error(`${failurePath}: Runtime failure record has no error object`)\n }\n}\n\n/**\n * The journal's begin stamp in the analyzer's state-document shape. It carries\n * the run identity and start instant only; the terminal status lives in\n * Runtime's own `result.json` / `failure.json`, which the analyzer reads by\n * name, so no synthetic status field is fabricated here.\n */\nfunction runtimeBeginState(root: string, startedAt: string): string {\n return JSON.stringify({ id: root, startedAt })\n}\n\n/**\n * The file Runtime's `FileResultBlobStore` writes for one content address\n * (`sha256:<hex>` → `blobs/sha256-<hex>.json`), or null for anything that is not one.\n */\nfunction blobFile(runDir: string, ref: unknown): string | null {\n return typeof ref === 'string' && /^sha256:[0-9a-f]{64}$/u.test(ref)\n ? join(runDir, BLOB_DIR, `${ref.replace(':', '-')}.json`)\n : null\n}\n\ntype NodeTranscript = Pick<\n WorkerLogSource,\n 'transcriptRef' | 'turns' | 'nativeSession' | 'workspaceCaptures'\n>\n\ninterface NodeTranscriptFacts {\n dispatched: number\n readonly outputRefs: { value: unknown; turn: boolean }[]\n readonly outputPositions: Map<string, number>\n receipt: Record<string, unknown> | null\n}\n\n/** A later receipt replaces an earlier one, except that an absence never replaces an available one. */\nfunction keepReceipt(fact: NodeTranscriptFacts, receipt: Record<string, unknown> | null): void {\n if (receipt === null) return\n if (fact.receipt?.status === 'available' && receipt.status !== 'available') return\n fact.receipt = receipt\n}\n\n/**\n * The files each harness writes its conversation to. A receipt can be available and complete\n * while holding none of them: on the 2026-10-04 trace proof a Pi worker that never wrote a session\n * stored only `.pi/agent/models-store.json`, and this summary counted it as a transcript.\n */\nconst HARNESS_SESSION_FILE: Readonly<Record<string, RegExp>> = {\n 'claude-code': /(^|\\/)\\.claude\\/projects\\/.+\\.jsonl$/u,\n codex: /(^|\\/)\\.codex\\/sessions\\/.+\\.jsonl$/u,\n pi: /(^|\\/)\\.pi\\/agent\\/sessions\\/.+\\.jsonl$/u,\n opencode:\n /(^|\\/)(\\.local\\/share\\/opencode\\/(opencode\\.db|storage\\/session\\/.+\\.json|export\\/.+\\.json)|\\.opencode\\/sessions\\/.+)$/u,\n}\n\n/** Session files the receipt's transcript blob lists, or undefined when it cannot say. */\nasync function receiptSessionFiles(\n file: string,\n read: typeof readFileText,\n): Promise<number | undefined> {\n let descriptor: unknown\n try {\n descriptor = JSON.parse(await read(file))\n } catch {\n return undefined\n }\n const harness = record(descriptor)?.harness\n const files = record(descriptor)?.files\n const pattern = typeof harness === 'string' ? HARNESS_SESSION_FILE[harness] : undefined\n if (pattern === undefined || !Array.isArray(files)) return undefined\n return files.filter((entry) => {\n const path = record(entry)?.path\n return typeof path === 'string' && pattern.test(path)\n }).length\n}\n\ntype NativeSessionState = 'complete' | 'partial' | 'no-session-file' | 'unavailable' | 'none'\n\nfunction nativeSessionState(session: WorkerNativeSession | null | undefined): NativeSessionState {\n if (session === null || session === undefined) return 'none'\n if (session.status !== 'available') return 'unavailable'\n if (session.coverageComplete === false) return 'partial'\n if (session.sessionFiles === 0) return 'no-session-file'\n return 'complete'\n}\n\n/**\n * What this reader can say about harness-session traces. Every spawned worker counts, including\n * one that recorded nothing; the root is reported apart because its receipt lives in result.json\n * (`rootHarnessTranscript`), not on a worker. Runtime records the session identity on each\n * receipt, so the sessions are read per node, not through one command. A receipt counts as a\n * session only when its copy is complete and holds a file the harness writes its conversation to.\n */\nfunction nativeTraceSummary(\n workers: readonly WorkerLogSource[],\n root: NodeTranscript | undefined,\n): string {\n const states = workers.map((worker) => nativeSessionState(worker.nativeSession))\n const count = (state: NativeSessionState): number => states.filter((s) => s === state).length\n const rootSession = root?.nativeSession ?? null\n const rootState = nativeSessionState(rootSession)\n const rootText =\n rootSession === null\n ? 'no receipt'\n : rootSession.status === 'unavailable'\n ? `unavailable (${rootSession.reason})`\n : rootState === 'complete'\n ? 'complete'\n : rootState === 'partial'\n ? 'partial copy'\n : 'no session file'\n if (rootSession === null && states.every((state) => state === 'none'))\n return 'unavailable — no node carries a Runtime harness transcript receipt'\n const gaps = [\n count('partial') > 0 ? `${count('partial')} only a partial copy` : null,\n count('no-session-file') > 0\n ? `${count('no-session-file')} a receipt with no session file`\n : null,\n ].filter((gap): gap is string => gap !== null)\n return `per node — ${count('complete')} of ${workers.length} workers carry a complete native session receipt (workers[].nativeSession)${gaps.length > 0 ? `; ${gaps.join('; ')}` : ''}; root: ${rootText} (result.json rootHarnessTranscript)`\n}\n\nasync function workspaceCapturesFromOutput(\n runDir: string,\n ref: unknown,\n read: typeof readFileText,\n): Promise<RolloutWorkspaceCapture[]> {\n const outRef = typeof ref === 'string' ? ref : null\n const blobPath = blobFile(runDir, ref)\n const missing = (projectionGap: string): RolloutWorkspaceCapture => ({\n outRef,\n blobPath,\n receiptPointer: null,\n receipt: null,\n attempts: null,\n coverageComplete: null,\n incompleteReason: null,\n projectionGap,\n })\n if (blobPath === null) return [missing('Runtime output has no valid content address')]\n if (!(await isFile(blobPath))) return [missing('Runtime output blob is missing or not a file')]\n const raw = await readMaybe(blobPath, read)\n if (raw === null) return [missing('Runtime output blob is missing')]\n let output: unknown\n try {\n output = JSON.parse(raw)\n } catch {\n return [missing('Runtime output blob is not JSON')]\n }\n let addressGap: string | null = null\n try {\n if (hashCanonical(output) !== outRef) {\n addressGap = 'Runtime output content address does not match output blob'\n }\n } catch {\n addressGap = 'Runtime output cannot be canonically hashed'\n }\n const project = (rawReceipt: unknown, receiptPointer: string | null): RolloutWorkspaceCapture => {\n const receipt = record(rawReceipt)\n if (receipt === null) {\n return {\n ...missing(\n `workspaceCapture receipt is absent or malformed${addressGap === null ? '' : `; ${addressGap}`}`,\n ),\n receiptPointer,\n receipt: rawReceipt,\n }\n }\n const provenance = record(receipt.provenance)\n const attempts = Array.isArray(provenance?.attempts) ? provenance.attempts : null\n const coverageComplete =\n typeof receipt.coverageComplete === 'boolean' ? receipt.coverageComplete : null\n const incompleteReason =\n typeof receipt.incompleteReason === 'string' ? receipt.incompleteReason : null\n const gaps: string[] = []\n if (addressGap !== null) gaps.push(addressGap)\n if (coverageComplete === null) gaps.push('workspaceCapture.coverageComplete is absent')\n if (record(receipt.snapshot) === null) gaps.push('workspaceCapture.snapshot is absent')\n if (provenance === null) gaps.push('workspaceCapture.provenance is absent')\n if (attempts === null) gaps.push('workspaceCapture.provenance.attempts is absent')\n else if (attempts.length === 0 || attempts.some((attempt) => record(attempt) === null)) {\n gaps.push('workspaceCapture.provenance.attempts is empty or malformed')\n }\n return {\n outRef,\n blobPath,\n receiptPointer,\n receipt,\n attempts,\n coverageComplete,\n incompleteReason,\n projectionGap: gaps.length > 0 ? gaps.join('; ') : null,\n }\n }\n const result = record(output)\n const captures: RolloutWorkspaceCapture[] = []\n // Use the record's field order and each array's order so every retained source stays ordered.\n for (const key of Object.keys(result ?? {})) {\n if (key === 'workspaceCapture') {\n captures.push(project(result?.[key], '/workspaceCapture'))\n } else if (key === 'workspaceCaptures') {\n const receipts = result?.[key]\n if (Array.isArray(receipts) && receipts.length > 0) {\n for (const [index, receipt] of receipts.entries()) {\n captures.push(project(receipt, `/workspaceCaptures/${index}`))\n }\n } else {\n captures.push({\n ...missing(\n `workspaceCaptures is empty or malformed${addressGap === null ? '' : `; ${addressGap}`}`,\n ),\n receiptPointer: '/workspaceCaptures',\n receipt: receipts ?? null,\n })\n }\n }\n }\n return captures.length > 0 ? captures : [project(null, null)]\n}\n\n/**\n * What Runtime retained of each node's decisions, from its own records.\n *\n * - A turn is one `execution-admitted` event in the `dispatched` phase. Its `execution-result`\n * names an output blob holding that turn's provider event stream (reasoning, tool calls and\n * results as the harness reported them). A dispatched turn with no retained output lost its\n * record, which is how a worker that went down mid-turn shows up.\n * - Every event's `outRef` enters the same collector, once per node and address. Terminal\n * records retain ordinary and steerable results; they are not counted as dispatched turns.\n * - The terminal event's `harnessTranscript` receipt covers the harness's native session files.\n * Those are the only record of the harness's own subagents, so an unavailable receipt is a\n * separate gap from a missing turn, and its reason is Runtime's, verbatim. `settled`,\n * `cancelled` and `reconciled` all carry one; an available receipt is never replaced by a later\n * absence. The root has no terminal event, so its receipt is the settle record's\n * `rootHarnessTranscript`.\n *\n * Blob files are checked on disk: a receipt that names a blob the directory no longer holds is\n * not a retained transcript.\n */\nasync function nodeTranscripts(\n runDir: string,\n events: readonly Record<string, unknown>[],\n nodeIds: ReadonlySet<string>,\n read: typeof readFileText,\n root?: { readonly id: string; readonly receipt: Record<string, unknown> | null },\n): Promise<Map<string, NodeTranscript>> {\n const facts = new Map<string, NodeTranscriptFacts>()\n const entry = (id: string): NodeTranscriptFacts => {\n let found = facts.get(id)\n if (found === undefined) {\n found = { dispatched: 0, outputRefs: [], outputPositions: new Map(), receipt: null }\n facts.set(id, found)\n }\n return found\n }\n for (const event of events) {\n const id = nonEmptyString(event.id)\n if (id === null || !nodeIds.has(id)) continue\n if (Object.hasOwn(event, 'outRef')) {\n const fact = entry(id)\n const ref = event.outRef\n const position = typeof ref === 'string' ? fact.outputPositions.get(ref) : undefined\n if (position !== undefined) {\n if (event.kind === 'execution-result') fact.outputRefs[position]!.turn = true\n } else {\n if (typeof ref === 'string') fact.outputPositions.set(ref, fact.outputRefs.length)\n fact.outputRefs.push({ value: ref, turn: event.kind === 'execution-result' })\n }\n }\n if (event.kind === 'execution-admitted' && record(event.admission)?.phase === 'dispatched') {\n entry(id).dispatched += 1\n } else if (\n event.kind === 'settled' ||\n event.kind === 'cancelled' ||\n event.kind === 'reconciled'\n ) {\n // A reconciled node carries its receipt on `reconciled`, which 15 available transcripts of\n // the 2026-10-04 Discovery archives did and this reader once skipped.\n keepReceipt(entry(id), record(event.harnessTranscript))\n }\n }\n if (root !== undefined && nodeIds.has(root.id)) keepReceipt(entry(root.id), root.receipt)\n const out = new Map<string, NodeTranscript>()\n for (const [id, fact] of facts) {\n const retained: string[] = []\n let retainedTurns = 0\n const workspaceCaptures: RolloutWorkspaceCapture[] = []\n for (const { value: ref, turn } of fact.outputRefs) {\n const file = blobFile(runDir, ref)\n if (file !== null && (await isFile(file))) {\n retained.push(file)\n if (turn) retainedTurns += 1\n }\n workspaceCaptures.push(...(await workspaceCapturesFromOutput(runDir, ref, read)))\n }\n let nativeSession: WorkerNativeSession | null = null\n if (fact.receipt !== null) {\n if (fact.receipt.status === 'available') {\n const file = blobFile(runDir, fact.receipt.transcriptRef)\n if (file !== null && (await isFile(file))) {\n const sessionFiles = await receiptSessionFiles(file, read)\n const coverageComplete = fact.receipt.coverageComplete\n nativeSession = {\n status: 'available',\n ref: file,\n ...(typeof coverageComplete === 'boolean' ? { coverageComplete } : {}),\n ...(sessionFiles === undefined ? {} : { sessionFiles }),\n }\n } else {\n nativeSession = { status: 'unavailable', reason: 'receipt-blob-missing' }\n }\n } else {\n nativeSession = {\n status: 'unavailable',\n reason: nonEmptyString(fact.receipt.reason) ?? 'unavailable',\n }\n }\n }\n out.set(id, {\n // The native session is the fuller record; the newest turn output is the next best.\n transcriptRef:\n nativeSession?.status === 'available' ? nativeSession.ref : (retained.at(-1) ?? null),\n turns: { dispatched: fact.dispatched, retained: retainedTurns },\n nativeSession,\n workspaceCaptures: workspaceCaptures.length > 0 ? workspaceCaptures : null,\n })\n }\n return out\n}\n\nexport interface RuntimeReaderOptions {\n /** Read original UTF-8 bytes at logical run paths. Only ENOENT means absence; other failures propagate. */\n readonly readFile?: typeof readFileText\n /**\n * Throw on a missing spawn journal instead of returning absent-shaped\n * sources. The default (false) models a journal-less run dir — a\n * pre-supervise death, a backfilled zombie — as a readable absence.\n */\n readonly strict?: boolean\n}\n\n/**\n * The run identity a terminal record names when no journal exists yet: the\n * settle record's `tree.root`, else the failure record's `runId`. Both are\n * Runtime's own `runId`, so the report names the run the record is about\n * instead of `?`.\n */\nfunction recordedRunId(\n result: Record<string, unknown> | null,\n failure: Record<string, unknown> | null,\n): string | null {\n return nonEmptyString(record(result?.tree)?.root) ?? nonEmptyString(failure?.runId)\n}\n\nfunction absentRuntimeSupervisorRun(\n runDir: string,\n resultText: string | null,\n failureText: string | null,\n instanceId: string | null,\n): SupervisorRunSources {\n const reason = `no Runtime spawn journal (${JOURNAL_FILE}) under ${runDir}`\n return {\n runRef: runDir,\n instanceId,\n arm: null,\n supRunDir: null,\n journal: null,\n journalMissingReason: reason,\n brainLog: null,\n brainLogMissingReason:\n 'Runtime FileRunContext records spend but not model completion finish reasons',\n state: null,\n progress: null,\n workers: null,\n workersMissingReason: reason,\n result: resultText,\n failure: failureText,\n judge: null,\n judgeSource: null,\n patch: null,\n driverLog: null,\n harnessWorkerTokens: null,\n harnessMissingReason: 'Runtime FileRunContext has no external worker-token join',\n limits: NO_SOURCE_LIMITS,\n rootTranscriptRef: null,\n rootWorkspaceCaptures: null,\n traceCommand: 'unavailable — Runtime FileRunContext records no provider-session trace identity',\n }\n}\n\n/**\n * Read one agent-runtime `createFileRunContext(dir)` directory.\n *\n * A run dir without `spawn-journal.jsonl` returns the same absent-shaped\n * sources the reader returns for a missing store: `journal` and\n * `workers` null, each with its reason, so every dependent metric reads\n * `unavailable` — never 0 and never a throw. Its `result.json` and\n * `failure.json` are still read, so a run that died before its first spawn\n * reports the failure Runtime recorded. Pass `strict: true` to throw on the\n * missing journal instead. A journal, result, or failure document that exists\n * but cannot be parsed always throws: a corrupt record is a defect, not an\n * absence.\n *\n * The reader translates storage envelopes only. It does not assign research\n * roles, interpret artifacts, or turn process completion into a quality\n * verdict.\n */\nexport async function readRuntimeSupervisorRun(\n runDir: string,\n opts: RuntimeReaderOptions = {},\n): Promise<SupervisorRunSources> {\n const read = opts.readFile ?? readFileText\n const journalPath = join(runDir, JOURNAL_FILE)\n const rawJournal =\n opts.strict === true ? await read(journalPath) : await readMaybe(journalPath, read)\n const resultPath = join(runDir, RESULT_FILE)\n const failurePath = join(runDir, FAILURE_FILE)\n const resultText = await readMaybe(resultPath, read)\n const failureText = await readMaybe(failurePath, read)\n const failure = parseOptionalRecord(failureText, failurePath)\n assertFailureRecord(failure, failurePath)\n const result = parseOptionalRecord(resultText, resultPath)\n if (rawJournal === null) {\n return absentRuntimeSupervisorRun(\n runDir,\n resultText,\n failureText,\n recordedRunId(result, failure),\n )\n }\n const normalized = parseEnvelopeJournal(rawJournal, journalPath)\n assertResultMatchesJournal(normalized.root, result, resultPath)\n\n const spawns = normalized.events.filter(\n (event) => event.kind === 'spawned' && nonEmptyString(event.id) !== null,\n )\n const childSpawns = spawns.filter((event) => event.id !== normalized.root)\n const workerIds = new Set(\n childSpawns.map((event) => nonEmptyString(event.id)).filter((id): id is string => id !== null),\n )\n const transcripts = await nodeTranscripts(\n runDir,\n normalized.events,\n new Set([normalized.root, ...workerIds]),\n read,\n { id: normalized.root, receipt: record(result?.rootHarnessTranscript) },\n )\n const workers: WorkerLogSource[] = childSpawns.map((event) => {\n const workerId = nonEmptyString(event.id) as string\n const transcript = transcripts.get(workerId)\n return {\n workerId,\n label: nonEmptyString(event.label) ?? String(event.id),\n events: null,\n inbox: null,\n patchBytes: null,\n transcriptRef: transcript?.transcriptRef ?? null,\n turns: transcript?.turns ?? { dispatched: 0, retained: 0 },\n nativeSession: transcript?.nativeSession ?? null,\n workspaceCaptures: transcript?.workspaceCaptures ?? null,\n patchPath: null,\n }\n })\n // Runtime appends every root provider event to the root stream as it arrives.\n const rootStream = join(runDir, ROOT_STREAM_FILE)\n\n return {\n runRef: runDir,\n instanceId: normalized.root,\n arm: null,\n supRunDir: runDir,\n journal: normalized.journal,\n brainLog: null,\n brainLogMissingReason:\n 'Runtime FileRunContext records spend but not model completion finish reasons',\n state: runtimeBeginState(normalized.root, normalized.startedAt),\n progress: null,\n workers,\n workersMissingReason: null,\n result: resultText,\n failure: failureText,\n judge: null,\n judgeSource: null,\n patch: null,\n driverLog: null,\n coordinationLog: await readCoordinationLog(runDir, read),\n harnessWorkerTokens: null,\n harnessMissingReason: 'Runtime FileRunContext has no external worker-token join',\n limits: sourceLimits(normalized.root, normalized.events, workerIds),\n rootTranscriptRef: (await isFile(rootStream)) ? rootStream : null,\n rootWorkspaceCaptures: transcripts.get(normalized.root)?.workspaceCaptures ?? null,\n traceCommand: nativeTraceSummary(workers, transcripts.get(normalized.root)),\n }\n}\n\n/**\n * True when a directory holds any file only Runtime's durable layer writes:\n * the spawn journal, the observer journal, or the failure record. A run that\n * threw before its first spawn has no journal yet and is still a Runtime run.\n */\nexport async function isRuntimeSupervisorRunDir(runDir: string): Promise<boolean> {\n for (const marker of RUNTIME_RUN_DIR_MARKERS) {\n if (await isFile(join(runDir, marker))) return true\n }\n return false\n}\n\nasync function isFile(path: string): Promise<boolean> {\n try {\n return (await stat(path)).isFile()\n } catch (error: unknown) {\n const code = error !== null && typeof error === 'object' && 'code' in error ? error.code : null\n if (code === 'ENOENT' || code === 'ENOTDIR') return false\n throw error\n }\n}\n","/**\n * Runtime supervisor-run reader and report writers.\n *\n * Runtime's file-backed supervision context is the only live on-disk contract.\n * Other stores implement `SupervisorRunReader` and feed the same pure analyzer;\n * this module owns path discovery and report output for Runtime runs.\n */\n\nimport { readdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { analyzeSupervisorRunSources } from './analyze'\n\nimport { isRuntimeSupervisorRunDir, readRuntimeSupervisorRun } from './runtime-reader'\nimport type { SupervisorRunReader, SupervisorRunReport, SupervisorRunSources } from './types'\n\n/**\n * Analyze a supervisor run. Accepts a Runtime run directory, any\n * `SupervisorRunReader`, or already-read source bytes — so a\n * caller with its own store never has to touch the filesystem layout.\n */\nexport async function analyzeSupervisorRun(\n input: string | SupervisorRunReader | SupervisorRunSources,\n): Promise<SupervisorRunReport> {\n if (typeof input === 'string') {\n return analyzeSupervisorRunSources(await readRuntimeSupervisorRun(input))\n }\n if (isReader(input)) return analyzeSupervisorRunSources(await input.read())\n return analyzeSupervisorRunSources(input)\n}\n\nfunction isReader(input: SupervisorRunReader | SupervisorRunSources): input is SupervisorRunReader {\n return typeof (input as SupervisorRunReader).read === 'function'\n}\n\nexport interface WriteSupervisorRunOptions {\n /** Append the headline block here (the experiment's run log). */\n readonly appendHeadlineTo?: string\n /** Also console.log the headline (default true). */\n readonly echo?: boolean\n /**\n * Write `run-report.{json,md}` here instead of into the run dir. Set when\n * reporting over a run directory that must stay READ-ONLY (a live run, an\n * archived generation).\n */\n readonly reportDir?: string\n}\n\n\n\n\n\n\n\n/**\n * Every Runtime supervisor run below `root`.\n *\n * When `root` itself is one run, return no children so callers can distinguish\n * a single report from a parent-directory rollup.\n */\nexport async function findSupervisorRunDirs(root: string): Promise<string[]> {\n if (await isRuntimeSupervisorRunDir(root)) {\n return []\n }\n const found: string[] = []\n const walk = async (dir: string, depth: number): Promise<void> => {\n if (depth > 8) return\n const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])\n for (const e of entries) {\n if (!e.isDirectory()) continue\n if (e.name === 'node_modules' || e.name === '.git') continue\n const full = join(dir, e.name)\n if (await isRuntimeSupervisorRunDir(full)) {\n found.push(full)\n continue\n }\n await walk(full, depth + 1)\n }\n }\n await walk(root, 0)\n return found.sort()\n}\n","/**\n * Human-readable renderings of a supervisor-run report. Zero and unavailable\n * render differently on purpose (`0` vs `unavailable — <reason>`), because the\n * two have driven opposite conclusions about the same architecture.\n */\n\nimport { roundDecimal as round } from '../math/round-decimal'\nimport {\n isUnavailable,\n type Measured,\n type ResourceSpendRecord,\n type SupervisorRunReport,\n type SupervisorRunRollup,\n showMeasured,\n type TerminalFailure,\n} from './types'\n\n/**\n * The block appended to a run log after every run — the answers an operator asks\n * for, in the log tail, with no extra command.\n */\nexport function renderSupervisorRunHeadline(r: SupervisorRunReport): string {\n const o = r.orchestration\n const steerNote = isUnavailable(o.steers)\n ? `unavailable — ${o.steers.unavailable}`\n : o.steers === 0\n ? '0 (spawn→wait→respawn only; no mid-task steering)'\n : `${o.steers} queued / ${showMeasured(o.steersDelivered)} delivered`\n return [\n `RUN-REPORT ${r.instanceId ?? '?'} [${r.arm ?? '?'}]`,\n ` status=${showMeasured(r.outcome.supStatus)} source=${showMeasured(r.outcome.supStatusSource)}` +\n ` reason=${showMeasured(r.outcome.supReason)} failure=${fmtFailure(r.outcome.failure)}`,\n ` steers=${steerNote}`,\n ` waves=${showMeasured(o.waves)} sizes=${isUnavailable(o.waveSizes) ? `unavailable — ${o.waveSizes.unavailable}` : `[${o.waveSizes.join(',')}]`}` +\n ` workers=${showMeasured(o.workersSpawned)} settled=${showMeasured(o.workersSettled)} cancelled=${showMeasured(o.workersCancelled)}`,\n ` concurrency max=${showMeasured(o.maxConcurrency)} utilization=${showMeasured(o.workerUtilization)}` +\n ` idle=${fmtMs(o.idleMs)} (${showMeasured(o.idlePct)}%) wall=${fmtMs(o.supervisorWallMs)}` +\n `${o.supervisorWallSource === 'journal-span' ? ' (journal-span lower bound)' : ''}`,\n ` respawns=${showMeasured(o.respawns)} evidence→respawn=${showMeasured(r.decision.observeThenRespawn)}` +\n ` blind-respawn=${showMeasured(r.decision.respawnWithoutEvidence)} depth=${showMeasured(o.delegationDepth)}`,\n ` accepted=${showMeasured(r.decision.accepted)} rejected=${showMeasured(r.decision.rejected)} empty-pass=${showMeasured(r.decision.emptyPass)}`,\n ` brain=$${showMeasured(r.economics.brain.usd)} total=$${showMeasured(r.economics.totalUsd)}` +\n ` judge.resolved=${showMeasured(r.outcome.judgeResolved)} score=${showMeasured(r.outcome.judgeScore)}` +\n ` verify=${showMeasured(r.outcome.verifyPass)}`,\n r.gaps.length > 0 ? ` gaps(${r.gaps.length}): ${r.gaps.join('; ')}` : ' gaps: none',\n ].join('\\n')\n}\n\n/**\n * The recorded error on one line; `none recorded` and `unavailable` stay\n * distinct, and a throw the run outlived is labeled so it is not read as the\n * outcome of the settled result beside it.\n */\nfunction fmtFailure(v: Measured<TerminalFailure | null>): string {\n if (isUnavailable(v)) return `unavailable — ${v.unavailable}`\n if (v === null) return 'none recorded'\n const name = v.name ?? 'unavailable — record has no error.name'\n const message = v.message ?? 'unavailable — record has no error.message'\n const attempt = v.earlierAttempt ? ', earlier attempt' : ''\n return `${name}: ${message} [${v.source}${v.at === null ? '' : ` at ${v.at}`}${attempt}]`\n}\n\nfunction resourceRows(records: Measured<readonly ResourceSpendRecord[]>): string[] {\n if (isUnavailable(records)) return [`unavailable — ${records.unavailable}`, '']\n const out = [\n 'Receipts are source records, not additive totals.',\n 'A false completeness flag means the amount is a recorded subtotal, not complete usage.',\n '',\n '| Node | Source | Resource | Unit | Amount | Known |',\n '|---|---|---|---|---:|---|',\n ]\n const cell = (value: string) => value.replace(/\\|/g, '\\\\|').replace(/\\r?\\n/g, ' ')\n for (const record of records) {\n const prefix = `| ${cell(record.nodeId ?? 'unavailable')} | ${cell(record.source)} |`\n if (isUnavailable(record.resources)) {\n out.push(`${prefix} ${cell(showMeasured(record.resources))} | — | — | — |`)\n } else if (record.resources.length === 0) {\n out.push(`${prefix} recorded empty map | — | — | — |`)\n } else {\n for (const receipt of record.resources) {\n out.push(\n `${prefix} ${cell(showMeasured(receipt.name))} | ${cell(showMeasured(receipt.unit))} | ${cell(showMeasured(receipt.amount))} | ${cell(showMeasured(receipt.known))} |`,\n )\n }\n }\n }\n if (!records.length) out.push('| — | — | no spend records | — | — | — |')\n out.push('')\n return out\n}\n\nfunction fmtMs(v: Measured<number>): string {\n if (isUnavailable(v)) return `unavailable — ${v.unavailable}`\n if (v < 1000) return `${v}ms`\n const s = v / 1000\n if (s < 120) return `${round(s, 1)}s`\n return `${round(s / 60, 1)}min`\n}\n\nexport function renderSupervisorRunMarkdown(r: SupervisorRunReport): string {\n const o = r.orchestration\n const d = r.decision\n const e = r.economics\n const out: string[] = []\n out.push(`# Run report — ${r.instanceId ?? 'unknown instance'} [${r.arm ?? 'unknown arm'}]`)\n out.push('')\n out.push('```')\n out.push(renderSupervisorRunHeadline(r))\n out.push('```')\n out.push('')\n out.push(`- Run: \\`${r.runRef}\\``)\n out.push(`- Supervisor: \\`${showMeasured(r.supervisorId)}\\``)\n out.push(`- Supervisor profile: \\`${showMeasured(r.supervisorProfileDigest)}\\``)\n out.push(`- Generated: ${r.generatedAt}`)\n out.push('')\n\n out.push('## Orchestration')\n out.push('')\n out.push('| Metric | Value |')\n out.push('|---|---|')\n out.push(`| Workers spawned | ${showMeasured(o.workersSpawned)} |`)\n out.push(`| Workers settled | ${showMeasured(o.workersSettled)} |`)\n out.push(`| Workers cancelled | ${showMeasured(o.workersCancelled)} |`)\n out.push(`| **Steers (mid-task messages to live workers)** | **${showMeasured(o.steers)}** |`)\n out.push(`| Steers delivered | ${showMeasured(o.steersDelivered)} |`)\n out.push(`| Outer-driver \\`supervisor_steer\\` calls | ${showMeasured(o.driverSteerCalls)} |`)\n out.push(`| Spawn waves | ${showMeasured(o.waves)} |`)\n out.push(\n `| Wave sizes | ${isUnavailable(o.waveSizes) ? showMeasured(o.waveSizes) : `[${o.waveSizes.join(', ')}]`} |`,\n )\n out.push(`| Max concurrency | ${showMeasured(o.maxConcurrency)} |`)\n out.push(`| Respawns (after same parent's first settle) | ${showMeasured(o.respawns)} |`)\n out.push(\n `| Repeated labels | ${isUnavailable(o.repeatedLabels) ? showMeasured(o.repeatedLabels) : o.repeatedLabels.length === 0 ? 'none' : o.repeatedLabels.join(', ')} |`,\n )\n out.push(`| Delegation depth | ${showMeasured(o.delegationDepth)} |`)\n out.push(`| Time to first spawn | ${fmtMs(o.timeToFirstSpawnMs)} |`)\n out.push(\n `| Supervisor wall | ${fmtMs(o.supervisorWallMs)}${isUnavailable(o.supervisorWallSource) ? '' : ` (source: ${o.supervisorWallSource}${o.supervisorWallSource === 'journal-span' ? ', lower bound' : ''})`} |`,\n )\n out.push(`| Idle (zero live workers) | ${fmtMs(o.idleMs)} (${showMeasured(o.idlePct)}%) |`)\n out.push(\n `| Worker utilization (Σ worker wall ÷ supervisor wall) | ${showMeasured(o.workerUtilization)} |`,\n )\n out.push('')\n\n if (!isUnavailable(o.steersByWorker) && o.steersByWorker.length > 0) {\n out.push('### Steers per worker')\n out.push('')\n out.push('| Worker id | Label | Queued | Delivered |')\n out.push('|---|---|---:|---:|')\n for (const s of o.steersByWorker) {\n out.push(\n `| ${s.workerId === null ? 'unavailable — worker id absent; label join used' : `\\`${s.workerId}\\``} | \\`${s.worker}\\` | ${s.queued} | ${s.delivered} |`,\n )\n }\n out.push('')\n } else if (isUnavailable(o.steersByWorker)) {\n out.push(`### Steers per worker\\n\\nunavailable — ${o.steersByWorker.unavailable}\\n`)\n }\n\n out.push('## Decision quality')\n out.push('')\n out.push('| Metric | Value |')\n out.push('|---|---|')\n out.push(`| Settled by status | ${fmtCounts(d.settledByStatus)} |`)\n out.push(`| Settled verdicts | ${fmtCounts(d.settledVerdicts)} |`)\n out.push(`| Accepted (verify green + patch bytes) | ${showMeasured(d.accepted)} |`)\n out.push(`| Rejected (verify red) | ${showMeasured(d.rejected)} |`)\n out.push(`| Empty pass (green, no patch) | ${showMeasured(d.emptyPass)} |`)\n out.push(`| Evidence → respawn sequences | ${showMeasured(d.observeThenRespawn)} |`)\n out.push(\n `| Respawn with no same-parent settled evidence in front | ${showMeasured(d.respawnWithoutEvidence)} |`,\n )\n out.push(`| Review actions (steers + worker questions) | ${showMeasured(d.reviewActions)} |`)\n out.push(\n `| Worker evidence returned | ${isUnavailable(d.workerEvidenceBytes) ? showMeasured(d.workerEvidenceBytes) : `${d.workerEvidenceBytes} bytes`} |`,\n )\n out.push('')\n\n out.push('## Economics')\n out.push('')\n out.push('| Role | Tokens in | Tokens out | Cache read | Cache write | USD | Source |')\n out.push('|---|---:|---:|---:|---:|---:|---|')\n out.push(\n `| brain | ${showMeasured(e.brain.tokensIn)} | ${showMeasured(e.brain.tokensOut)} | ${showMeasured(e.brain.cacheRead)} | ${showMeasured(e.brain.cacheWrite)} | ${showMeasured(e.brain.usd)} | ${e.brain.source} |`,\n )\n out.push(\n `| workers | ${showMeasured(e.workers.tokensIn)} | ${showMeasured(e.workers.tokensOut)} | ${showMeasured(e.workers.cacheRead)} | ${showMeasured(e.workers.cacheWrite)} | ${showMeasured(e.workers.usd)} | ${e.workers.source} |`,\n )\n out.push('')\n if (!isUnavailable(e.brainTruncations) && e.brainTruncations > 0) {\n out.push(\n `- **BRAIN OUTPUT TRUNCATED: ${e.brainTruncations} completion(s) hit \\`finish_reason: \"length\"\\`** — the supervisor ` +\n 'acted on a half-written plan. Its output ceiling is too low; see `brain.jsonl` for the per-call `req_max_tokens`.',\n )\n } else {\n out.push(\n `- Brain completions truncated (finish_reason=length): ${showMeasured(e.brainTruncations)}`,\n )\n }\n out.push(`- Total USD: ${showMeasured(e.totalUsd)} (source: ${e.totalUsdSource})`)\n out.push(\n `- Spend measured two ways: journal-derived $${showMeasured(e.spend.journalDerived.usd)} over ${e.spend.journalDerived.records} journal record(s) (execution accounting) · ` +\n `close-record $${showMeasured(e.spend.closeRecord.usd)} over ${e.spend.closeRecord.records} close record(s) (billing-shaped). Divergence is a signal, not an error.`,\n )\n out.push(`- Cost per accepted patch: ${showMeasured(e.costPerAcceptedPatchUsd)}`)\n if (isUnavailable(e.workerWallMsDistribution)) {\n out.push(`- Worker wall distribution: unavailable — ${e.workerWallMsDistribution.unavailable}`)\n } else {\n const w = e.workerWallMsDistribution\n out.push(\n `- Worker wall (n=${w.n}): min ${fmtMs(w.min)} / p50 ${fmtMs(w.p50)} / p90 ${fmtMs(w.p90)} / max ${fmtMs(w.max)} / Σ ${fmtMs(w.sum)}`,\n )\n }\n out.push('')\n if (!isUnavailable(e.perWorker) && e.perWorker.length > 0) {\n out.push(\n '| Worker id | Label | Role | Runtime | Profile digest | Status | Failure | Infra | Wall | Tokens in | Tokens out | Patch bytes | Verify passed | Score |',\n )\n out.push('|---|---|---|---|---|---|---|---|---:|---:|---:|---:|---|---:|')\n for (const w of e.perWorker) {\n out.push(\n `| ${w.workerId === null ? 'unavailable — worker id absent; label join used' : `\\`${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'} |`,\n )\n }\n out.push('')\n }\n\n if (e.resourceRecords !== undefined) {\n out.push('## Named resource receipts', '', ...resourceRows(e.resourceRecords))\n }\n\n out.push('## Outcome')\n out.push('')\n out.push('| Metric | Value |')\n out.push('|---|---|')\n out.push(`| Supervisor status | ${showMeasured(r.outcome.supStatus)} |`)\n out.push(`| Status source | ${showMeasured(r.outcome.supStatusSource)} |`)\n out.push(`| Terminal reason | ${showMeasured(r.outcome.supReason)} |`)\n out.push(`| Failure | ${fmtFailure(r.outcome.failure)} |`)\n out.push(`| Supervisor verdict | ${showMeasured(r.outcome.supVerdict)} |`)\n out.push(`| Delivered | ${showMeasured(r.outcome.delivered)} |`)\n out.push(`| Judge resolved | ${showMeasured(r.outcome.judgeResolved)} |`)\n out.push(`| Judge score | ${showMeasured(r.outcome.judgeScore)} |`)\n out.push(\n `| Judge passed / total | ${showMeasured(r.outcome.judgePassed)} / ${showMeasured(r.outcome.judgeTotal)} |`,\n )\n out.push(\n `| Judge source | ${r.outcome.judgeSource ?? 'unavailable — no judge.json and no ledger row'} |`,\n )\n out.push(\n `| Verify gate | pass=${showMeasured(r.outcome.verifyPass)} rc=${showMeasured(r.outcome.verifyRc)} |`,\n )\n if (isUnavailable(r.outcome.patch)) {\n out.push(`| Patch | unavailable — ${r.outcome.patch.unavailable} |`)\n } else {\n const p = r.outcome.patch\n out.push(\n `| Patch | ${p.files} file(s), +${p.linesAdded}/-${p.linesRemoved}, test files touched: ${p.testFilesTouched.length === 0 ? 'none' : p.testFilesTouched.join(', ')} |`,\n )\n }\n out.push('')\n out.push('## Gaps')\n out.push('')\n if (r.gaps.length === 0) out.push('None — every metric above is backed by a present artifact.')\n else for (const g of r.gaps) out.push(`- ${g}`)\n out.push('')\n out.push(\n `> Harness-session view of the same run (model calls, stuck loops, tool errors): \\`${r.traceCommand}\\``,\n )\n out.push('')\n return out.join('\\n')\n}\n\nfunction fmtCounts(v: Measured<Record<string, number>>): string {\n if (isUnavailable(v)) return showMeasured(v as unknown as Measured<string>)\n const entries = Object.entries(v)\n return entries.length === 0 ? 'none' : entries.map(([k, n]) => `${k}=${n}`).join(', ')\n}\n\nexport function renderSupervisorRollupMarkdown(\n rollup: SupervisorRunRollup,\n title = 'Round rollup',\n): string {\n const out: string[] = []\n out.push(`# ${title}`)\n out.push('')\n out.push(`- Cells: ${rollup.cells}`)\n out.push(\n `- **Steers across all cells: ${showMeasured(rollup.steersTotal)}** (cells with ≥1 steer: ${showMeasured(rollup.cellsWithSteers)}; cells where the steer count is unavailable: ${rollup.cellsWithUnavailableSteers})`,\n )\n out.push(`- Waves per cell (mean): ${showMeasured(rollup.wavesMean)}`)\n out.push(`- Max concurrency observed: ${showMeasured(rollup.maxConcurrencyMax)}`)\n out.push(`- Worker utilization (mean): ${showMeasured(rollup.utilizationMean)}`)\n out.push(`- Idle share (mean): ${showMeasured(rollup.idlePctMean)}%`)\n out.push(\n `- Workers spawned: ${showMeasured(rollup.workersSpawnedTotal)} · accepted: ${showMeasured(rollup.acceptedTotal)}`,\n )\n out.push(\n `- Spend: $${showMeasured(rollup.usdTotal)} · judged resolved: ${showMeasured(rollup.resolvedCount)}/${rollup.cells}`,\n )\n out.push(\n `- Spend measured two ways: journal-derived $${showMeasured(rollup.spendUsd.journalDerived.value)} over ${rollup.spendUsd.journalDerived.runs}/${rollup.cells} runs (execution accounting) · ` +\n `close-record $${showMeasured(rollup.spendUsd.closeRecord.value)} over ${rollup.spendUsd.closeRecord.runs}/${rollup.cells} runs (billing-shaped)`,\n )\n out.push('')\n out.push('| Instance | Arm | Steers | Waves | Utilization | Idle % | Resolved | USD |')\n out.push('|---|---|---:|---:|---:|---:|---|---:|')\n for (const c of rollup.perCell) {\n out.push(\n `| ${c.instanceId ?? '?'} | ${c.arm ?? '?'} | ${showMeasured(c.steers)} | ${showMeasured(c.waves)} | ${showMeasured(c.utilization)} | ${showMeasured(c.idlePct)} | ${showMeasured(c.resolved)} | ${showMeasured(c.usd)} |`,\n )\n }\n out.push('')\n for (const cell of rollup.perCell) {\n if (cell.resourceRecords !== undefined) {\n out.push(\n `## Resource receipts — ${cell.instanceId ?? '?'} [${cell.arm ?? '?'}]`,\n '',\n ...resourceRows(cell.resourceRecords),\n )\n }\n }\n return out.join('\\n')\n}\n","/**\n * A Runtime run directory as `tangle.rollout.v1` rows: the supervision tree\n * `supervisorRunRolloutLines` mints, with each node's whole episode.\n *\n * - Producer: each node's `materialized` receipt names the model it ran on\n * (`opencode/zai-coding-plan/glm-5.3` → harness, provider, model), and the\n * root's `root-segment` names the root's. The license class follows.\n * - Episode: each execution's input (`execution-input.taskRef`) and result\n * (`execution-result.outRef`, a `{content, events}` blob), read as Sandbox\n * sessions in order, so a node steered twice keeps both turns and every tool\n * call. A node with no event stream stays a lossy projection.\n * - A node respawned under the same id (a reopened run) is one row.\n * - Reward: the caller's `RunVerdict` on the root row. The caller owns what\n * its check means; this reader owns how a reward is screened and when a\n * stopped episode is whole.\n *\n * Every read is of files Runtime already wrote; nothing in the run dir is changed.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { basename, join } from 'node:path'\nimport type { HarnessSession } from '@tangle-network/harness-sessions'\nimport { sandboxEventsSession, toChatMessages, toOtlpSpans } from '@tangle-network/harness-sessions'\nimport { licenseClassOfName } from '../rollout/license'\nimport { screenedRewardFields, unscreenedRewardFields } from '../rollout/reward'\nimport type { RolloutLine } from '../rollout/schema'\nimport { expandJournalEventGroup } from './journal-event-group'\nimport { supervisorRunRolloutLinesFromFacts } from './rollout-nodes'\nimport { readRuntimeSupervisorRun } from './runtime-reader'\nimport { parseJsonl, parseSupervisorTree, recordOrNull as record } from './source-facts'\nimport type { SupervisorRunTreeGap } from './types'\n\ninterface NodeFacts {\n model?: string\n taskRef?: string\n outRef?: string\n /** The node's newest input, which the next result answers. */\n inputRef?: string\n unansweredSince?: string\n executions?: Array<{ taskRef?: string; outRef: string }>\n}\n\n/** `opencode/zai-coding-plan/glm-5.3` → harness, provider, model. */\nfunction producerOf(id: string): Record<'harness' | 'provider' | 'model', string | null> {\n const parts = id.split('/')\n if (parts.length >= 3) {\n return { harness: parts[0]!, provider: parts[1]!, model: parts.slice(2).join('/') }\n }\n if (parts.length === 2) return { harness: null, provider: parts[0]!, model: parts[1]! }\n return { harness: null, provider: null, model: id }\n}\n\n/** A row holding the agent's whole stream is no longer lossy; a workspace capture gap still stands. */\nfunction wholeEpisode({ lossy_projection: _, gap, ...kept }: RolloutLine['provenance']) {\n const workspace = gap?.match(/workspace capture evidence \\w+/u)?.[0]\n return workspace === undefined ? kept : { ...kept, gap: workspace }\n}\n\nconst text = (v: unknown): string | undefined =>\n typeof v === 'string' && v.length > 0 ? v : undefined\n\nasync function journalFacts(runDir: string): Promise<Map<string, NodeFacts>> {\n const facts = new Map<string, NodeFacts>()\n const raw = await readFile(join(runDir, 'spawn-journal.jsonl'), 'utf8').catch(() => '')\n const node = (id: string): NodeFacts => {\n const fact = facts.get(id) ?? {}\n facts.set(id, fact)\n return fact\n }\n for (const row of parseJsonl(raw)) {\n const expanded = expandJournalEventGroup(row)\n if (!expanded.succeeded) continue\n for (const entry of expanded.value) {\n const event = record(entry.event)\n const id = text(event?.id)\n if (event === null || id === undefined) continue\n if (event.kind === 'spawned') {\n node(id).taskRef ??= text(record(event.identity)?.taskDigest)\n } else if (event.kind === 'materialized') {\n const model = record(record(event.receipt)?.model)\n if (model?.status === 'known' && text(model.id)) node(id).model = text(model.id)\n } else if (event.kind === 'root-segment') {\n const to = record(event.to)\n const model = text(to?.model)\n if (model) node(id).model = [text(to?.harness), text(to?.provider), model].join('/')\n } else if (event.kind === 'settled' && text(event.outRef)) {\n node(id).outRef = text(event.outRef)\n } else if (event.kind === 'execution-input') {\n const fact = node(id)\n fact.inputRef = text(event.taskRef)\n fact.unansweredSince ??= text(event.at)\n } else if (event.kind === 'execution-result' && text(event.outRef)) {\n const fact = node(id)\n fact.unansweredSince = undefined\n const taskRef = fact.inputRef ?? fact.taskRef\n ;(fact.executions ??= []).push({ taskRef, outRef: event.outRef as string })\n }\n }\n }\n return facts\n}\n\nconst readJson = (path: string): Promise<unknown> =>\n readFile(path, 'utf8').then(JSON.parse).catch(() => undefined)\n\nasync function blobValue(runDir: string, ref: string | undefined): Promise<unknown> {\n if (ref === undefined || !/^sha256:[0-9a-f]{64}$/u.test(ref)) return undefined\n return readJson(join(runDir, 'blobs', `${ref.replace(':', '-')}.json`))\n}\n\n/** One Sandbox session per execution, oldest first; older runs keep only the settled result. */\nasync function nodeSessions(runDir: string, harness: string, id: string, fact: NodeFacts) {\n const executions = fact.executions ?? [{ taskRef: fact.taskRef, outRef: fact.outRef }]\n const sessions: HarnessSession[] = []\n for (const [index, { taskRef, outRef }] of executions.entries()) {\n const [input, result] = await Promise.all([blobValue(runDir, taskRef), blobValue(runDir, outRef)])\n const task = text(input) ?? text(record(input)?.prompt) ?? text(record(input)?.instruction)\n const answer = text(result) ?? text(record(result)?.content)\n const stream = record(result)?.events\n const events = Array.isArray(stream) ? stream : []\n if (task === undefined || (answer === undefined && events.length === 0)) continue\n const nativeSessionId = `${id}:${index}`\n sessions.push(sandboxEventsSession({ harness, nativeSessionId, task, answer: answer ?? '', events }))\n }\n return sessions\n}\n\n/** A caller's verdict on a run, applied to its root row. */\nexport interface RunVerdict {\n /** In [0, 1]; 1 is full success. */\n reward: number\n /** The check behind the reward was validated (a fixture that must fail it did). */\n screened: boolean\n /** An independent review contradicted the reward, so it trains nothing. */\n gated?: boolean\n /** Who produced the reward, such as `my-suite/check`. */\n source: string\n /** When a controller stopped the run on this verdict. */\n stoppedAt?: string\n at?: string\n commit?: string | null\n detail?: string\n}\n\n/**\n * The root's outcome under the caller's verdict. A run stopped on its success reads `cancelled`;\n * its episode is whole if no input was pending when it was stopped.\n */\nfunction judged(node: RolloutLine, verdict: RunVerdict | null, pending: string | undefined) {\n if (verdict === null || node.parent_rollout_id !== null) return node.outcome\n const { reward, screened, gated = false, source, stoppedAt = '', commit = null } = verdict\n const ended = reward === 1 && !gated && (!pending || Date.parse(stoppedAt) <= Date.parse(pending))\n return {\n ...node.outcome,\n ...(screened || gated ? screenedRewardFields(reward, gated) : unscreenedRewardFields(reward)),\n ...(ended ? { is_completed: true, error: null } : {}),\n reward_source: source,\n verdict: { at: verdict.at ?? '', commit, detail: (verdict.detail ?? '').slice(0, 500) },\n }\n}\n\nexport interface RuntimeRunRollouts {\n runDir: string\n lines: RolloutLine[]\n gaps: SupervisorRunTreeGap[]\n /** Each row's session as OTLP-JSONL, by rollout id. */\n otlp: Map<string, string>\n}\n\n/** Read one Runtime run directory into rollout rows; `suite` defaults to `runtime/<run>`. */\nexport async function runtimeRunRolloutLines(\n runDir: string,\n options: { suite?: string; capturedAt?: string; verdict?: RunVerdict | null } = {},\n): Promise<RuntimeRunRollouts> {\n const verdict = options.verdict ?? null\n const src = await readRuntimeSupervisorRun(runDir)\n const facts0 = parseSupervisorTree(src)\n const seen = new Set<string>()\n const workerSpawns = facts0.workerSpawns.filter(\n (spawn) => !seen.has(spawn.id) && seen.add(spawn.id),\n )\n const tree = supervisorRunRolloutLinesFromFacts(\n src,\n { ...facts0, workerSpawns },\n {\n suite: options.suite ?? `runtime/${basename(runDir)}`,\n runId: basename(runDir),\n ...(options.capturedAt === undefined ? {} : { capturedAt: options.capturedAt }),\n },\n )\n const facts = await journalFacts(runDir)\n const lines: RolloutLine[] = []\n const otlp = new Map<string, string>()\n for (const node of tree.nodes) {\n const fact = facts.get(node.rollout_id) ?? {}\n const producer = fact.model === undefined ? null : producerOf(fact.model)\n const license = licenseClassOfName(producer?.model) ?? licenseClassOfName(producer?.harness)\n const harness = producer?.harness ?? node.policy.harness ?? 'sandbox'\n const sessions = await nodeSessions(runDir, harness, node.rollout_id, fact)\n const messages = sessions.flatMap((session) => toChatMessages(session))\n // A session with no stream has only its root span, which `traces` rightly calls unread.\n const spans = sessions.map((session) => toOtlpSpans(session)).filter((s) => s.length > 1).flat()\n otlp.set(node.rollout_id, spans.map((span) => `${JSON.stringify(span)}\\n`).join(''))\n lines.push({\n ...node,\n policy: {\n ...node.policy,\n ...(producer === null\n ? {}\n : {\n harness: producer.harness ?? node.policy.harness,\n provider: producer.provider,\n model: producer.model,\n }),\n ...(license === null ? {} : { license_class: license }),\n },\n messages: sessions.length === 0 ? node.messages : messages,\n provenance: messages.some((m) => m.role === 'tool') ? wholeEpisode(node.provenance) : node.provenance,\n outcome: judged(node, verdict, fact.unansweredSince),\n })\n }\n // The verdict is the root's reward, so the tree's \"no judge verdict\" gap no longer holds.\n const gaps = tree.gaps.filter((gap) => verdict === null || gap.code !== 'root-reward-unavailable')\n return { runDir, lines, gaps, otlp }\n}\n"],"mappings":";;;;;;;;;;;AAKA,SAAgB,eAAe,KAA2B;CACxD,MAAM,OAAiB,CAAC;CACxB,MAAM,OAAO,MAAc,WAAgC;EACzD,KAAK,KAAK,GAAG,KAAK,IAAI,QAAQ;EAC9B,OAAO,YAAY,MAAM;CAC3B;CAEA,MAAM,iBACJ,IAAI,yBACH,IAAI,cAAc,OAAO,wCAAwC;CACpE,MAAM,cAAc,IAAI,YAAY;CACpC,MAAM,OAAO,oBAAoB,GAAG;CACpC,MAAM,QAAQ,KAAK;CACnB,MAAM,SAAS,gBAAgB,IAAI,MAAM;CACzC,MAAM,QAAQ,gBAAgB,IAAI,KAAK;CAEvC,MAAM,WAAW,mBAAmB;EAClC;EACA;EACA,SAAS,IAAI,YAAY,KAAA,IAAY,KAAA,IAAY,gBAAgB,IAAI,OAAO;CAC9E,CAAC;CACD,MAAM,EAAE,QAAQ,cAAc,cAAc,WAAW,gBAAgB;CACvE,MAAM,YACJ,WAAW,OAAO,OAAQ,KAAK,OAAO,MAAM,UAAU,MAAM,OAAO,MAAM,KAAK;CAChF,MAAM,YAAY,IAAI,IAAI,aAAa,KAAK,UAAU,CAAC,MAAM,IAAI,KAAK,CAAC,CAAC;CACxE,MAAM,gCAAgB,IAAI,IAAwB;CAClD,KAAK,MAAM,SAAS,cAAc;EAChC,MAAM,UAAU,cAAc,IAAI,MAAM,KAAK,KAAK,CAAC;EACnD,QAAQ,KAAK,KAAK;EAClB,cAAc,IAAI,MAAM,OAAO,OAAO;CACxC;CACA,MAAM,mBACJ,WACwB;EACxB,IAAI,OAAO,aAAa,KAAA,GAAW,OAAO,cAAc,IAAI,OAAO,KAAK,KAAK,CAAC;EAC9E,MAAM,QAAQ,UAAU,IAAI,OAAO,QAAQ;EAC3C,OAAO,UAAU,KAAA,IAAY,CAAC,I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5nC_.js","names":["round","round","round","record","record","round","record"],"sources":["../src/supervisor-run/analyze-context.ts","../src/supervisor-run/analyze-decision.ts","../src/supervisor-run/analyze-economics.ts","../src/supervisor-run/analyze-orchestration.ts","../src/supervisor-run/patch-stats.ts","../src/supervisor-run/analyze-outcome.ts","../src/supervisor-run/analyze-spend.ts","../src/supervisor-run/analyze.ts","../src/supervisor-run/coordination-reader.ts","../src/supervisor-run/runtime-source-limits.ts","../src/supervisor-run/runtime-reader.ts","../src/supervisor-run/reader.ts","../src/supervisor-run/render.ts","../src/supervisor-run/runtime-rollouts.ts"],"sourcesContent":["import { parseJsonRecord, parseSupervisorTree, type SpawnRow } from './source-facts'\nimport { readTerminalRecord } from './terminal-record'\nimport { type SupervisorRunSources, type Unavailable, unavailable } from './types'\n\n/** The parsed sources and shared lookups every metric group reads. `gap` records an unavailable measurement on the report. */\nexport function createAnalysis(src: SupervisorRunSources) {\n const gaps: string[] = []\n const gap = (what: string, reason: string): Unavailable => {\n gaps.push(`${what}: ${reason}`)\n return unavailable(reason)\n }\n\n const journalMissing =\n src.journalMissingReason ??\n (src.supRunDir === null ? 'no Runtime supervisor run directory' : 'journal.jsonl absent')\n const haveJournal = src.journal !== null\n const tree = parseSupervisorTree(src)\n const state = tree.state\n const result = parseJsonRecord(src.result)\n const judge = parseJsonRecord(src.judge)\n // Runtime's terminal record is named on the report so a status never arrives unlabeled.\n const terminal = readTerminalRecord({\n state,\n result,\n failure: src.failure === undefined ? undefined : parseJsonRecord(src.failure),\n })\n const { rootId, workerSpawns, workerCloses, startedAt, completedAt } = tree\n const rootSpawn =\n rootId === null ? null : (tree.spawns.find((spawn) => spawn.id === rootId) ?? null)\n const spawnById = new Map(workerSpawns.map((spawn) => [spawn.id, spawn]))\n const spawnsByLabel = new Map<string, SpawnRow[]>()\n for (const spawn of workerSpawns) {\n const matches = spawnsByLabel.get(spawn.label) ?? []\n matches.push(spawn)\n spawnsByLabel.set(spawn.label, matches)\n }\n const spawnsForSource = (\n worker: NonNullable<SupervisorRunSources['workers']>[number],\n ): readonly SpawnRow[] => {\n if (worker.workerId === undefined) return spawnsByLabel.get(worker.label) ?? []\n const spawn = spawnById.get(worker.workerId)\n return spawn === undefined ? [] : [spawn]\n }\n const spawnForSource = (\n worker: NonNullable<SupervisorRunSources['workers']>[number],\n ): SpawnRow | null => {\n const matches = spawnsForSource(worker)\n return matches.length === 1 ? (matches[0] ?? null) : null\n }\n const closeById = new Map(workerCloses.map((close) => [close.id, close]))\n const workersGapReason = src.workersMissingReason ?? 'workers/ directory absent'\n return {\n src,\n gaps,\n gap,\n journalMissing,\n haveJournal,\n tree,\n state,\n result,\n judge,\n terminal,\n rootId,\n rootSpawn,\n workerSpawns,\n workerCloses,\n startedAt,\n completedAt,\n spawnsForSource,\n spawnForSource,\n closeById,\n workersGapReason,\n }\n}\n\nexport type Analysis = ReturnType<typeof createAnalysis>\n","import type { Analysis } from './analyze-context'\nimport type { StepFacts } from './analyze-orchestration'\nimport { workerSourceKey } from './source-facts'\nimport { type DecisionMetrics, unavailable } from './types'\n\n/** Settled verdicts, acceptance and review effort, with a named gap wherever the store never said. */\nexport function measureDecision(a: Analysis, m: StepFacts): DecisionMetrics {\n const {\n src,\n gap,\n journalMissing,\n haveJournal,\n tree,\n workerCloses,\n spawnForSource,\n closeById,\n workersGapReason,\n } = a\n const {\n steerQueuedTotal,\n upLegMessages,\n queuedGapReason,\n workerEventsGapReason,\n observeThenRespawn,\n respawnWithoutEvidence,\n } = m\n // ── decision quality ───────────────────────────────────────────────────\n const settledByStatus: Record<string, number> = {}\n const settledVerdicts: Record<string, number> = {}\n for (const c of workerCloses) {\n const key = c.status ?? 'unknown'\n settledByStatus[key] = (settledByStatus[key] ?? 0) + 1\n if (c.verdict !== null) settledVerdicts[c.verdict] = (settledVerdicts[c.verdict] ?? 0) + 1\n }\n\n // A store with no verify step never says pass or fail. Counting its silent\n // workers as `rejected: 0 / accepted: 0` would read as \"nothing was accepted\".\n const verdictLimit = src.limits.workerVerdicts\n // A store that retains no delivered patch still SETTLES a verdict, and that verdict is\n // the acceptance decision it recorded. Only the split between a green verdict backed by\n // a patch and a green verdict with nothing behind it needs patch bytes, so the\n // deliverables limit takes `emptyPass` and leaves `accepted` measured.\n const deliverablesLimit = src.limits.deliverables\n let accepted = 0\n let emptyPass = 0\n let evidenceBytes = 0\n const sourceVerdicts: boolean[] = []\n for (const w of src.workers ?? []) {\n const f = tree.workerLogs.get(workerSourceKey(w))\n if (f?.finished) evidenceBytes += f.evidenceBytes\n const spawn = spawnForSource(w)\n const close = spawn === null ? null : (closeById.get(spawn.id) ?? null)\n const passed = close?.valid ?? f?.passed ?? null\n if (passed !== null) sourceVerdicts.push(passed)\n if (passed === true) {\n if (deliverablesLimit !== null || (w.patchBytes ?? f?.finishedPatchBytes ?? 0) > 0) {\n accepted += 1\n } else {\n emptyPass += 1\n }\n }\n }\n const settledCloses = workerCloses.filter((close) => close.kind === 'settled')\n const structuredVerdicts = settledCloses\n .map((close) => close.valid)\n .filter((valid): valid is boolean => valid !== null)\n const journalVerdictsComplete =\n settledCloses.length > 0 && structuredVerdicts.length === settledCloses.length\n const sourceVerdictsComplete =\n sourceVerdicts.length > 0 && sourceVerdicts.length >= settledCloses.length\n const rejected = journalVerdictsComplete\n ? structuredVerdicts.filter((valid) => !valid).length\n : sourceVerdictsComplete\n ? sourceVerdicts.filter((valid) => !valid).length\n : 0\n const rejectedLimit =\n journalVerdictsComplete || sourceVerdictsComplete\n ? null\n : settledCloses.length > 0\n ? (verdictLimit ?? 'a settled journal verdict has no validity and no matched worker log')\n : verdictLimit !== null\n ? verdictLimit\n : !haveJournal && src.workers === null\n ? workersGapReason\n : null\n\n const decision: DecisionMetrics = {\n settledByStatus: haveJournal ? settledByStatus : gap('settledByStatus', journalMissing),\n settledVerdicts:\n verdictLimit !== null\n ? unavailable(verdictLimit)\n : haveJournal\n ? settledVerdicts\n : unavailable(journalMissing),\n accepted:\n verdictLimit !== null\n ? gap('accepted', verdictLimit)\n : src.workers === null\n ? unavailable(workersGapReason)\n : accepted,\n rejected: rejectedLimit === null ? rejected : unavailable(rejectedLimit),\n emptyPass:\n verdictLimit !== null\n ? gap('emptyPass', verdictLimit)\n : deliverablesLimit !== null\n ? gap('emptyPass', deliverablesLimit)\n : src.workers === null\n ? unavailable(workersGapReason)\n : emptyPass,\n observeThenRespawn: haveJournal ? observeThenRespawn : unavailable(journalMissing),\n respawnWithoutEvidence: haveJournal ? respawnWithoutEvidence : unavailable(journalMissing),\n reviewActions:\n src.workers === null\n ? unavailable(workersGapReason)\n : queuedGapReason === null\n ? steerQueuedTotal + upLegMessages\n : unavailable(queuedGapReason),\n workerEvidenceBytes:\n src.workers === null\n ? unavailable(workersGapReason)\n : workerEventsGapReason === null\n ? evidenceBytes\n : unavailable(workerEventsGapReason),\n }\n return decision\n}\n","import { roundDecimal as round } from '../math/round-decimal'\nimport { summarizeNumberSeries } from '../statistics'\nimport type { Analysis } from './analyze-context'\nimport type { SpendFacts, TotalUsd, WorkerTokens } from './analyze-spend'\nimport { parseJsonl, workerSourceKey } from './source-facts'\nimport {\n type DecisionMetrics,\n type EconomicsMetrics,\n isUnavailable,\n type PerWorkerRow,\n type SpendMeasurements,\n type SupervisorRunSources,\n unavailable,\n} from './types'\n\nconst NO_CACHE_COUNTERS = 'the journal carries no cache-token counters for this role'\n\nconst NO_CACHE_BREAKDOWN =\n 'Runtime recorded cacheBreakdownKnown:false — the provider reported a total without splitting cache reads from writes'\n\n/** One row per worker log, plus the capture gaps of the root and every worker. */\nexport function buildPerWorker(a: Analysis, f: SpendFacts, t: TotalUsd): PerWorkerRow[] {\n const { src, gaps, tree, rootId, spawnsForSource, spawnForSource, closeById } = a\n const { workerUsdById, workerUsdByLabel } = f\n const { usdLimit } = t\n const noteCaptureGaps = (\n owner: string,\n captures: SupervisorRunSources['rootWorkspaceCaptures'],\n ): void => {\n if (captures === null || captures?.length === 0) {\n gaps.push(`${owner} workspaceCapture: no retained output capture evidence`)\n } else if (captures !== undefined) {\n for (const [index, capture] of captures.entries()) {\n const source = `${owner} workspaceCapture[${index + 1}]`\n if (capture.projectionGap !== null) gaps.push(`${source}: ${capture.projectionGap}`)\n if (capture.coverageComplete === false) {\n gaps.push(\n `${source}: ${capture.incompleteReason ?? 'provider reported incomplete coverage'}`,\n )\n }\n if (capture.coverageComplete === null && capture.projectionGap === null) {\n gaps.push(`${source}: capture coverage was not recorded`)\n }\n }\n }\n }\n noteCaptureGaps(`root ${rootId ?? src.runRef}`, src.rootWorkspaceCaptures)\n const perWorker: PerWorkerRow[] = (src.workers ?? []).map((w) => {\n noteCaptureGaps(`worker ${w.workerId ?? w.label}`, w.workspaceCaptures)\n const f = tree.workerLogs.get(workerSourceKey(w))\n const matchingSpawns = spawnsForSource(w)\n const spawn = spawnForSource(w)\n const close = spawn === null ? null : (closeById.get(spawn.id) ?? null)\n const passed = close?.valid ?? f?.passed ?? null\n const matchingRoles = new Set(matchingSpawns.map((candidate) => candidate.role))\n const matchingRuntimes = new Set(matchingSpawns.map((candidate) => candidate.runtime))\n const matchingProfiles = new Set(matchingSpawns.map((candidate) => candidate.profileDigest))\n const journalWallMs =\n spawn?.at !== null &&\n spawn?.at !== undefined &&\n close?.at !== null &&\n close?.at !== undefined &&\n close.at >= spawn.at\n ? close.at - spawn.at\n : null\n return {\n workerId: w.workerId ?? null,\n worker: w.label,\n role: matchingRoles.size === 1 ? (matchingSpawns[0]?.role ?? null) : null,\n runtime: matchingRuntimes.size === 1 ? (matchingSpawns[0]?.runtime ?? null) : null,\n profileDigest:\n matchingProfiles.size === 1 ? (matchingSpawns[0]?.profileDigest ?? null) : null,\n status: close?.status ?? null,\n failure: close?.reason ?? null,\n infra: close?.infra ?? null,\n wallMs: f?.started != null && f.finishedAt != null ? f.finishedAt - f.started : journalWallMs,\n tokensIn:\n w.tokensIn ??\n (close?.hasSpend === true && close.spend.tokensKnown ? close.spend.tokens.input : null),\n tokensOut:\n w.tokensOut ??\n (close?.hasSpend === true && close.spend.tokensKnown ? close.spend.tokens.output : null),\n usd:\n usdLimit !== null\n ? null\n : w.workerId === undefined\n ? (workerUsdByLabel.get(w.label) ?? null)\n : (workerUsdById.get(w.workerId) ?? null),\n patchBytes: w.patchBytes ?? f?.finishedPatchBytes ?? null,\n passed,\n score: close?.score ?? f?.score ?? null,\n workspaceCaptures: w.workspaceCaptures ?? null,\n }\n })\n return perWorker\n}\n\n/** The supervisor brain's tokens, cache and USD. */\nfunction buildBrainSpend(\n a: Analysis,\n f: SpendFacts,\n t: TotalUsd,\n): EconomicsMetrics['brain'] {\n const { src, gap, journalMissing, haveJournal, tree } = a\n const { brainTokensUnreported, brainUsdUnreported } = f\n const { usdLimit } = t\n const managerTokenLimit = src.limits.managerTokens\n return {\n tokensIn:\n managerTokenLimit !== null\n ? gap('brain.tokensIn', managerTokenLimit)\n : !haveJournal\n ? gap('brain.tokensIn', journalMissing)\n : brainTokensUnreported !== null\n ? gap('brain.tokensIn', brainTokensUnreported)\n : tree.brain.tokensIn,\n tokensOut:\n managerTokenLimit !== null\n ? unavailable(managerTokenLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : brainTokensUnreported !== null\n ? unavailable(brainTokensUnreported)\n : tree.brain.tokensOut,\n usd:\n usdLimit !== null\n ? unavailable(usdLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : brainUsdUnreported !== null\n ? unavailable(brainUsdUnreported)\n : round(tree.brain.usd, 6),\n cacheRead:\n managerTokenLimit !== null\n ? unavailable(managerTokenLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : brainTokensUnreported !== null\n ? unavailable(brainTokensUnreported)\n : !tree.brain.hasCache\n ? unavailable(NO_CACHE_COUNTERS)\n : tree.brain.cacheBreakdownKnown\n ? tree.brain.cacheRead\n : unavailable(NO_CACHE_BREAKDOWN),\n cacheWrite:\n managerTokenLimit !== null\n ? unavailable(managerTokenLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : brainTokensUnreported !== null\n ? unavailable(brainTokensUnreported)\n : !tree.brain.hasCache\n ? unavailable(NO_CACHE_COUNTERS)\n : tree.brain.cacheBreakdownKnown\n ? tree.brain.cacheWrite\n : unavailable(NO_CACHE_BREAKDOWN),\n source:\n managerTokenLimit ??\n (haveJournal\n ? `journal metered events (n=${tree.brain.meteredCount})${\n tree.brain.usdKnownCount > 0 && tree.brain.usdUnknownCount > 0\n ? ` — ${tree.brain.usdUnknownCount} unpriced`\n : ''\n }`\n : journalMissing),\n }\n}\n\n/** The workers' tokens, cache and USD. */\nfunction buildWorkerSpend(\n a: Analysis,\n f: SpendFacts,\n t: TotalUsd,\n w: WorkerTokens,\n): EconomicsMetrics['workers'] {\n const { src, journalMissing, haveJournal } = a\n const { rootChildSpends, workerUsdUnknownNodes, journalWorkerUsd, workerUsdUnreported } = f\n const { usdLimit } = t\n const { sq, workerTokenLimit, workerIn, workerOut } = w\n return {\n tokensIn: workerIn,\n tokensOut: workerOut,\n cacheRead:\n workerTokenLimit !== null\n ? unavailable(workerTokenLimit)\n : sq?.cacheRead !== undefined\n ? sq.cacheRead\n : unavailable(NO_CACHE_COUNTERS),\n cacheWrite:\n workerTokenLimit !== null\n ? unavailable(workerTokenLimit)\n : sq?.cacheWrite !== undefined\n ? sq.cacheWrite\n : unavailable(NO_CACHE_COUNTERS),\n usd:\n usdLimit !== null\n ? unavailable(usdLimit)\n : !haveJournal\n ? unavailable(journalMissing)\n : workerUsdUnreported !== null\n ? unavailable(workerUsdUnreported)\n : round(journalWorkerUsd, 6),\n source: `${\n workerTokenLimit !== null\n ? workerTokenLimit\n : sq !== null\n ? `journal settled spend + ${sq.store} sessions (n=${sq.sessions})`\n : `journal settled spend only — ${src.harnessMissingReason ?? 'harness session store unavailable'}`\n }${\n workerUsdUnknownNodes.length > 0 && workerUsdUnknownNodes.length < rootChildSpends.length\n ? ` — ${workerUsdUnknownNodes.length} unpriced`\n : ''\n }`,\n }\n}\n\nexport function buildEconomics(\n a: Analysis,\n f: SpendFacts,\n t: TotalUsd,\n w: WorkerTokens,\n e: EconomicsParts,\n): EconomicsMetrics {\n const { src, gap, journalMissing, haveJournal, tree, workersGapReason } = a\n const { rootChildCloses, journalWorkerUsd, usdUnknownRecords } = f\n const { stateUsd, usdLimit, totalUsd, usdUnreportedReason } = t\n const { decision, spend, perWorker } = e\n const wallDistribution = summarizeNumberSeries(\n perWorker.map((w) => w.wallMs).filter((w): w is number => w !== null),\n )\n\n const brainCalls = parseJsonl(src.brainLog)\n return {\n resourceRecords:\n src.journal === null && !tree.resourceRecords?.length\n ? unavailable(journalMissing)\n : (tree.resourceRecords ?? []),\n brain: buildBrainSpend(a, f, t),\n brainTruncations:\n src.brainLog === null\n ? gap(\n 'brain.brainTruncations',\n src.brainLogMissingReason ??\n (src.supRunDir === null\n ? 'no Runtime supervisor run directory'\n : 'brain.jsonl absent — this source has no brain-call tap, so truncation cannot be ruled out'),\n )\n : brainCalls.filter((c) => c.finish_reason === 'length').length,\n workers: buildWorkerSpend(a, f, t, w),\n spend,\n totalUsd,\n totalUsdSource:\n usdLimit !== null\n ? usdLimit\n : stateUsd !== null\n ? `state.json result.spentUsd${rootChildCloses.length > 0 && journalWorkerUsd === 0 ? ' — brain-priced only; worker CLI inference is unpriced (see worker token counts)' : ''}`\n : !haveJournal\n ? journalMissing\n : usdUnknownRecords > 0\n ? usdUnreportedReason\n : 'journal metered + settled usd',\n costPerAcceptedPatchUsd: isUnavailable(totalUsd)\n ? unavailable(totalUsd.unavailable)\n : isUnavailable(decision.accepted)\n ? unavailable(decision.accepted.unavailable)\n : decision.accepted === 0\n ? unavailable('no accepted worker patch (cost has no denominator)')\n : round(totalUsd / decision.accepted, 6),\n workerWallMsDistribution:\n wallDistribution === null\n ? unavailable(\n src.workers === null ? workersGapReason : 'no worker start/finish pairs captured',\n )\n : wallDistribution,\n perWorker: src.workers === null ? unavailable(workersGapReason) : perWorker,\n }\n}\n\nexport interface EconomicsParts {\n decision: DecisionMetrics\n spend: SpendMeasurements\n perWorker: PerWorkerRow[]\n}\n","import { roundDecimal as round } from '../math/round-decimal'\nimport type { Analysis } from './analyze-context'\nimport { type SpawnRow, type WorkerLogFacts, workerSourceKey } from './source-facts'\nimport {\n isUnavailable,\n type Measured,\n type OrchestrationMetrics,\n type SteerBreakdown,\n unavailable,\n} from './types'\n\n/** Supervisor wall time and where it ends. Explicit stamps win; the journal span is a lower bound; an inverted stamp pair stays unavailable. */\nexport function measureWall(a: Analysis) {\n const { gap, journalMissing, haveJournal, tree, startedAt, completedAt } = a\n // Wall provenance: explicit stamps when the store wrote both; otherwise the\n // journal event span (a lower bound) when there is no completion stamp at\n // all. A present-but-inverted stamp pair is corruption, not absence, and\n // stays unavailable.\n const wallSpanStart = startedAt ?? tree.firstEventAt\n const wallSpanEnd = tree.lastEventAt\n let supervisorWallMs: Measured<number>\n let supervisorWallSource: Measured<'stamps' | 'journal-span'>\n if (startedAt !== null && completedAt !== null && completedAt >= startedAt) {\n supervisorWallMs = completedAt - startedAt\n supervisorWallSource = 'stamps'\n } else if (\n completedAt === null &&\n wallSpanStart !== null &&\n wallSpanEnd !== null &&\n wallSpanEnd >= wallSpanStart\n ) {\n supervisorWallMs = wallSpanEnd - wallSpanStart\n supervisorWallSource = 'journal-span'\n } else {\n const reason = !haveJournal\n ? journalMissing\n : 'no parseable start/complete timestamps in state.json or journal'\n supervisorWallMs = gap('supervisorWallMs', reason)\n supervisorWallSource = unavailable(reason)\n }\n // Where the measured wall ends — the completion stamp, or the last stamped\n // journal event on the journal-span path. Idle and utilization integrate to\n // this bound so their denominator is the wall they are reported against.\n const wallEndAt = completedAt ?? (supervisorWallSource === 'journal-span' ? wallSpanEnd : null)\n return { supervisorWallMs, supervisorWallSource, wallEndAt }\n}\n\n/** Steer counts from worker inboxes and the driver log. */\nexport function measureSteers(a: Analysis) {\n const { src, gap, tree, workersGapReason } = a\n // ── steers (worker inbox + control events) ─────────────────────────────\n const steerRows: SteerBreakdown[] = []\n let steerQueuedTotal = 0\n let steerDeliveredTotal = 0\n let upLegMessages = 0\n if (src.workers !== null) {\n for (const w of src.workers) {\n const facts = tree.workerLogs.get(workerSourceKey(w))\n const queued = facts?.steersQueued ?? null\n const delivered = facts?.steersDelivered ?? null\n upLegMessages += facts?.questions ?? 0\n if (queued !== null && delivered !== null) {\n steerRows.push({ workerId: w.workerId ?? null, worker: w.label, queued, delivered })\n }\n if (queued !== null) steerQueuedTotal += queued\n if (delivered !== null) steerDeliveredTotal += delivered\n }\n }\n const unavailableReasons = (pick: (facts: WorkerLogFacts) => string | null): string | null => {\n const reasons = tree.workerLogRows\n .map((facts) => pick(facts))\n .filter((reason): reason is string => reason !== null)\n return reasons.length === 0\n ? null\n : `exact steer accounting unavailable for ${reasons.length} worker row(s): ${[...new Set(reasons)].join(' | ')}`\n }\n const queuedGapReason = unavailableReasons((facts) => facts.steersQueuedUnavailable)\n const deliveredGapReason = unavailableReasons((facts) => facts.steersDeliveredUnavailable)\n const workerEventsGapReason = unavailableReasons((facts) =>\n !facts.eventsCaptured\n ? 'events absent'\n : facts.eventsInvalidRows > 0\n ? 'events contain malformed rows'\n : null,\n )\n const steers: Measured<number> =\n src.workers === null\n ? gap('steers', workersGapReason)\n : queuedGapReason === null\n ? steerQueuedTotal\n : gap('steers', queuedGapReason)\n const steersDelivered: Measured<number> =\n src.workers === null\n ? unavailable(workersGapReason)\n : deliveredGapReason === null\n ? steerDeliveredTotal\n : unavailable(deliveredGapReason)\n const steersByWorker: Measured<readonly SteerBreakdown[]> =\n src.workers === null\n ? unavailable(workersGapReason)\n : queuedGapReason === null && deliveredGapReason === null\n ? steerRows\n : unavailable(queuedGapReason ?? deliveredGapReason ?? workersGapReason)\n\n // The `[driver] registered tools: …supervisor_steer…` banner names the verb without\n // invoking it, so banner lines are subtracted from the raw mention count.\n const driverSteerCalls: Measured<number> =\n src.driverLog === null\n ? gap('driverSteerCalls', 'driver.log absent')\n : Math.max(\n 0,\n (src.driverLog.match(/supervisor_steer/g) ?? []).length -\n registrationMentions(src.driverLog),\n )\n return {\n steers,\n steersDelivered,\n steersByWorker,\n driverSteerCalls,\n steerQueuedTotal,\n upLegMessages,\n queuedGapReason,\n workerEventsGapReason,\n }\n}\n\n/** Waves, peak concurrency, idle time and summed worker wall from the spawn/close timeline. */\nexport function measureConcurrency(a: Analysis, wallEndAt: number | null) {\n const { workerSpawns, workerCloses, startedAt } = a\n const timeline: { at: number; delta: 1 | -1 }[] = []\n for (const s of workerSpawns) if (s.at !== null) timeline.push({ at: s.at, delta: 1 })\n for (const c of workerCloses) if (c.at !== null) timeline.push({ at: c.at, delta: -1 })\n timeline.sort((a, b) => a.at - b.at || a.delta - b.delta)\n\n let waves = 0\n const waveSizes: number[] = []\n let closedSinceWaveStart = true\n for (const step of timeline) {\n if (step.delta === 1) {\n if (closedSinceWaveStart) {\n waves += 1\n waveSizes.push(0)\n closedSinceWaveStart = false\n }\n waveSizes[waveSizes.length - 1] = (waveSizes[waveSizes.length - 1] ?? 0) + 1\n } else {\n closedSinceWaveStart = true\n }\n }\n\n let live = 0\n let maxConcurrency = 0\n let idleMs = 0\n let sumWorkerWallMs = 0\n let prev = startedAt\n for (const step of timeline) {\n if (prev !== null && step.at >= prev) {\n const span = step.at - prev\n if (live === 0) idleMs += span\n sumWorkerWallMs += span * live\n }\n live += step.delta\n if (live > maxConcurrency) maxConcurrency = live\n prev = step.at\n }\n if (prev !== null && wallEndAt !== null && wallEndAt >= prev) {\n const span = wallEndAt - prev\n if (live === 0) idleMs += span\n sumWorkerWallMs += span * live\n }\n return { waves, waveSizes, maxConcurrency, idleMs, sumWorkerWallMs }\n}\n\n/** Respawn counts per parent, split by whether a sibling closed in between. */\nexport function measureRespawns(a: Analysis) {\n const { workerSpawns, closeById } = a\n const childSpawnsByParent = new Map<string, SpawnRow[]>()\n for (const spawn of workerSpawns) {\n if (spawn.parent === null) continue\n const siblings = childSpawnsByParent.get(spawn.parent) ?? []\n siblings.push(spawn)\n childSpawnsByParent.set(spawn.parent, siblings)\n }\n\n let respawns = 0\n let observeThenRespawn = 0\n let respawnWithoutEvidence = 0\n const repeatedLabelSet = new Set<string>()\n for (const siblings of childSpawnsByParent.values()) {\n const labelCounts = new Map<string, number>()\n for (const spawn of siblings) {\n labelCounts.set(spawn.label, (labelCounts.get(spawn.label) ?? 0) + 1)\n }\n for (const [label, count] of labelCounts) {\n if (count > 1) repeatedLabelSet.add(label)\n }\n\n const orderedSpawns = siblings\n .map((spawn, index) => ({ spawn, index }))\n .filter(\n (row): row is { spawn: SpawnRow & { at: number }; index: number } => row.spawn.at !== null,\n )\n .sort((a, b) => a.spawn.at - b.spawn.at || a.index - b.index)\n const directCloseTimes = siblings\n .map((spawn) => closeById.get(spawn.id)?.at ?? null)\n .filter((at): at is number => at !== null)\n .sort((a, b) => a - b)\n const firstDirectClose = directCloseTimes[0] ?? null\n\n for (let i = 1; i < orderedSpawns.length; i += 1) {\n const previous = orderedSpawns[i - 1]?.spawn.at\n const current = orderedSpawns[i]?.spawn.at\n if (previous === undefined || current === undefined) continue\n if (firstDirectClose === null || current <= firstDirectClose) continue\n respawns += 1\n const sawEvidence = hasNumberBetween(directCloseTimes, previous, current)\n if (sawEvidence) observeThenRespawn += 1\n else respawnWithoutEvidence += 1\n }\n }\n const repeatedLabels = [...repeatedLabelSet]\n return { respawns, observeThenRespawn, respawnWithoutEvidence, repeatedLabels }\n}\n\n/** The deepest chain of spawns below the root. */\nexport function measureDelegationDepth(a: Analysis) {\n const { tree, rootId, workerSpawns } = a\n const parentOf = new Map(tree.spawns.map((s) => [s.id, s.parent]))\n let delegationDepth = 0\n for (const s of workerSpawns) {\n let d = 0\n let cur: string | null = s.id\n const seen = new Set<string>()\n while (cur !== null && cur !== rootId && !seen.has(cur)) {\n seen.add(cur)\n d += 1\n cur = parentOf.get(cur) ?? null\n }\n if (d > delegationDepth) delegationDepth = d\n }\n return delegationDepth\n}\n\nexport function buildOrchestration(a: Analysis, m: StepFacts): OrchestrationMetrics {\n const { gap, journalMissing, haveJournal, workerSpawns, workerCloses, startedAt } = a\n const {\n supervisorWallMs,\n supervisorWallSource,\n steers,\n steersDelivered,\n steersByWorker,\n driverSteerCalls,\n waves,\n waveSizes,\n maxConcurrency,\n idleMs,\n sumWorkerWallMs,\n respawns,\n repeatedLabels,\n delegationDepth,\n } = m\n const firstWorkerSpawnAt = workerSpawns.reduce<number | null>(\n (acc, s) => (s.at === null ? acc : acc === null ? s.at : Math.min(acc, s.at)),\n null,\n )\n\n const orchestration: OrchestrationMetrics = {\n workersSpawned: haveJournal ? workerSpawns.length : gap('workersSpawned', journalMissing),\n workersSettled: haveJournal\n ? workerCloses.filter((c) => c.kind === 'settled').length\n : unavailable(journalMissing),\n workersCancelled: haveJournal\n ? workerCloses.filter((c) => c.kind === 'cancelled').length\n : unavailable(journalMissing),\n steers,\n steersDelivered,\n steersByWorker,\n driverSteerCalls,\n waves: haveJournal ? waves : unavailable(journalMissing),\n waveSizes: haveJournal ? waveSizes : unavailable(journalMissing),\n maxConcurrency: haveJournal ? maxConcurrency : unavailable(journalMissing),\n respawns: haveJournal ? respawns : unavailable(journalMissing),\n repeatedLabels: haveJournal ? repeatedLabels : unavailable(journalMissing),\n delegationDepth: haveJournal ? delegationDepth : unavailable(journalMissing),\n timeToFirstSpawnMs:\n startedAt !== null && firstWorkerSpawnAt !== null\n ? firstWorkerSpawnAt - startedAt\n : haveJournal\n ? unavailable('no worker spawn timestamps')\n : unavailable(journalMissing),\n supervisorWallMs,\n supervisorWallSource,\n idleMs: isUnavailable(supervisorWallMs) ? unavailable(supervisorWallMs.unavailable) : idleMs,\n idlePct:\n isUnavailable(supervisorWallMs) || supervisorWallMs === 0\n ? isUnavailable(supervisorWallMs)\n ? unavailable(supervisorWallMs.unavailable)\n : unavailable('supervisor wall is 0ms')\n : round((idleMs / supervisorWallMs) * 100, 1),\n workerUtilization:\n isUnavailable(supervisorWallMs) || supervisorWallMs === 0\n ? isUnavailable(supervisorWallMs)\n ? unavailable(supervisorWallMs.unavailable)\n : unavailable('supervisor wall is 0ms')\n : round(sumWorkerWallMs / supervisorWallMs, 3),\n }\n return orchestration\n}\n\n/** Whether sorted values contain one value in the inclusive interval. */\nfunction hasNumberBetween(sorted: readonly number[], low: number, high: number): boolean {\n let left = 0\n let right = sorted.length\n while (left < right) {\n const middle = left + Math.floor((right - left) / 2)\n if ((sorted[middle] as number) < low) left = middle + 1\n else right = middle\n }\n return left < sorted.length && (sorted[left] as number) <= high\n}\n\n/** `[driver] registered tools: …supervisor_steer…` is a banner, not an invocation. */\nfunction registrationMentions(driverLog: string): number {\n let n = 0\n for (const line of driverLog.split('\\n')) {\n if (line.includes('registered tools:') && line.includes('supervisor_steer')) n += 1\n }\n return n\n}\n\nexport type StepFacts = ReturnType<typeof measureWall> &\n ReturnType<typeof measureSteers> &\n ReturnType<typeof measureConcurrency> &\n ReturnType<typeof measureRespawns> & { delegationDepth: number }\n","/** Unified-diff target, line, and test-file touch counts. */\nimport type { PatchStats } from './types'\n\n/** Unified-diff stats. Counts `+++ b/<path>` targets, body +/- lines, and test-file touches. */\nexport function parsePatch(text: string): PatchStats {\n const files = new Set<string>()\n const testFiles = new Set<string>()\n let added = 0\n let removed = 0\n for (const line of text.split('\\n')) {\n if (line.startsWith('+++ ')) {\n const p = line.slice(4).trim().replace(/^b\\//, '')\n if (p !== '/dev/null') {\n files.add(p)\n if (isTestPath(p)) testFiles.add(p)\n }\n continue\n }\n if (line.startsWith('--- ') || line.startsWith('diff --git') || line.startsWith('index ')) {\n continue\n }\n if (line.startsWith('+')) added += 1\n else if (line.startsWith('-')) removed += 1\n }\n return {\n files: files.size,\n linesAdded: added,\n linesRemoved: removed,\n testFilesTouched: [...testFiles].sort(),\n }\n}\n\nfunction isTestPath(p: string): boolean {\n const base = p.split('/').pop() ?? p\n return (\n /(^|\\/)(tests?|__tests__|testing|spec)(\\/|$)/.test(p) ||\n /\\.(test|spec)\\.[cm]?[jt]sx?$/.test(base) ||\n /^test_.*\\.py$/.test(base) ||\n /_test\\.py$/.test(base)\n )\n}\n","import type { Analysis } from './analyze-context'\nimport type { TotalUsd } from './analyze-spend'\nimport { parsePatch } from './patch-stats'\nimport {\n isUnavailable,\n type Measured,\n type OutcomeMetrics,\n type PatchStats,\n unavailable,\n} from './types'\n\n/** Terminal status, verdicts, judge result and the delivered patch. */\nexport function buildOutcome(a: Analysis, t: TotalUsd): OutcomeMetrics {\n const { src, gap, state, result, judge, terminal } = a\n const { stateResult } = t\n const patchStats: Measured<PatchStats> =\n src.patch === null\n ? gap('patch', src.limits.deliverables ?? 'delivered patch file absent')\n : parsePatch(src.patch)\n\n const outcome: OutcomeMetrics = {\n supStatus: isUnavailable(terminal.supStatus)\n ? gap('supStatus', terminal.supStatus.unavailable)\n : terminal.supStatus,\n supStatusSource: terminal.supStatusSource,\n supReason: terminal.supReason,\n failure: terminal.failure,\n supVerdict:\n pickString(state, 'verdict') ??\n pickString(result, 'sup_verdict') ??\n unavailable('no state.json / result.json verdict'),\n delivered:\n typeof stateResult.delivered === 'boolean'\n ? stateResult.delivered\n : typeof result?.delivered === 'boolean'\n ? result.delivered\n : unavailable('no delivered flag in state.json or result.json'),\n judgeResolved:\n judge === null\n ? gap('judge', 'judge.json absent')\n : typeof judge.resolved === 'boolean'\n ? judge.resolved\n : null,\n judgeScore:\n judge === null\n ? unavailable('judge.json absent')\n : typeof judge.score === 'number'\n ? judge.score\n : null,\n judgePassed:\n judge === null\n ? unavailable('judge.json absent')\n : typeof judge.passed === 'number'\n ? judge.passed\n : null,\n judgeTotal:\n judge === null\n ? unavailable('judge.json absent')\n : typeof judge.total === 'number'\n ? judge.total\n : null,\n verifyPass:\n typeof result?.verify_pass === 'boolean'\n ? result.verify_pass\n : gap('verifyPass', 'result.json absent or has no verify_pass'),\n verifyRc:\n typeof result?.verify_rc === 'number'\n ? result.verify_rc\n : unavailable('result.json absent or has no verify_rc'),\n patch: patchStats,\n judgeSource: src.judgeSource,\n }\n return outcome\n}\n\nfunction pickString(rec: Record<string, unknown> | null, key: string): string | null {\n const v = rec?.[key]\n return typeof v === 'string' ? v : null\n}\n","import { roundDecimal as round } from '../math/round-decimal'\nimport type { Analysis } from './analyze-context'\nimport { asRecord } from './source-facts'\nimport { type Measured, type SpendMeasurements, unavailable } from './types'\n\n/** Spend records of the root and its children, split into reporting and unreporting. */\nexport function collectSpendFacts(a: Analysis) {\n const { tree, rootId, workerSpawns, workerCloses } = a\n const rootChildIds = new Set(\n workerSpawns.filter((spawn) => spawn.parent === rootId).map((spawn) => spawn.id),\n )\n const rootChildCloses = workerCloses.filter((close) => rootChildIds.has(close.id))\n // Runtime marks a spend record `usdKnown: false` / `tokensKnown: false` when the work\n // HAPPENED but no provider receipt covered its price or its tokens. Folding such a record\n // in prices unreported work at zero; dropping the whole channel discards every record that\n // DID report. So each channel sums only the reporting records and names the rest.\n const rootChildSpends = rootChildCloses.filter((close) => close.hasSpend)\n const workerUsdUnknownNodes = rootChildSpends\n .filter((close) => !close.spend.usdKnown)\n .map((close) => close.id)\n const workerTokensUnknownNodes = rootChildSpends\n .filter((close) => !close.spend.tokensKnown)\n .map((close) => close.id)\n const workerTokenSpends = rootChildSpends.filter((close) => close.spend.tokensKnown)\n const journalWorkerIn = workerTokenSpends.reduce((a, c) => a + c.spend.tokens.input, 0)\n const journalWorkerOut = workerTokenSpends.reduce((a, c) => a + c.spend.tokens.output, 0)\n const journalWorkerUsd = rootChildSpends\n .filter((close) => close.spend.usdKnown)\n .reduce((a, c) => a + c.spend.usd, 0)\n const usdUnknownIds = new Set(\n workerCloses.filter((close) => close.hasSpend && !close.spend.usdKnown).map((c) => c.id),\n )\n const workerUsdById = new Map<string, number>()\n for (const c of workerCloses) {\n if (usdUnknownIds.has(c.id)) continue\n workerUsdById.set(c.id, (workerUsdById.get(c.id) ?? 0) + c.spend.usd)\n }\n const labelById = new Map(workerSpawns.map((spawn) => [spawn.id, spawn.label]))\n const usdUnknownLabels = new Set(\n [...usdUnknownIds].map((id) => labelById.get(id)).filter((l): l is string => l !== undefined),\n )\n const workerUsdByLabel = new Map<string, number>()\n for (const close of workerCloses) {\n const label = labelById.get(close.id)\n if (label === undefined || usdUnknownLabels.has(label)) continue\n workerUsdByLabel.set(label, (workerUsdByLabel.get(label) ?? 0) + close.spend.usd)\n }\n const brainUsdUnknownNodes =\n tree.brain.usdUnknownCount > 0 && rootId !== null ? ([rootId] as const) : []\n const brainTokensUnknownNodes =\n tree.brain.tokensUnknownCount > 0 && rootId !== null ? ([rootId] as const) : []\n const usdKnownRecords =\n tree.brain.usdKnownCount + rootChildSpends.filter((close) => close.spend.usdKnown).length\n const usdUnknownRecords = tree.brain.usdUnknownCount + workerUsdUnknownNodes.length\n const usdUnknownNodes = [...brainUsdUnknownNodes, ...workerUsdUnknownNodes]\n // The named nodes are what makes the gap actionable, but a fleet run can have hundreds,\n // and this string lands in a report line. Name the first few and count the rest.\n const NAMED_NODE_LIMIT = 5\n const nameNodes = (nodes: readonly string[]): string => {\n if (nodes.length === 0) return ''\n const shown = nodes.slice(0, NAMED_NODE_LIMIT)\n const rest = nodes.length - shown.length\n return ` (${shown.join(', ')}${rest === 0 ? '' : ` +${rest} more`})`\n }\n const unpriced = (unknown: number, total: number, nodes: readonly string[]): string =>\n `Runtime recorded usdKnown:false on ${unknown} of ${total} spend record(s)${nameNodes(nodes)}`\n // A token total is a bare `Measured<number>` with no record denominator beside it, so a\n // partial sum there would be an unlabelled floor — the exact collapse this module refuses.\n // Spend has `SpendMeasurement.records`/`unknownRecords` to carry the split, so it stays\n // partial; tokens go absent with the unreporting nodes named.\n const unreportedTokens = (unknown: number, total: number, nodes: readonly string[]): string =>\n `Runtime recorded tokensKnown:false on ${unknown} of ${total} spend record(s)${nameNodes(nodes)}`\n const usdPartial = usdKnownRecords > 0 && usdUnknownRecords > 0\n const usdAllUnknown = usdKnownRecords === 0 && usdUnknownRecords > 0\n // A role whose records are ALL unreported has nothing measured to report, so it stays\n // unavailable. A role with some of each keeps its sum and labels it in `source`.\n const brainTokensUnreported =\n tree.brain.tokensUnknownCount === 0\n ? null\n : unreportedTokens(\n tree.brain.tokensUnknownCount,\n tree.brain.meteredCount,\n brainTokensUnknownNodes,\n )\n const brainUsdUnreported =\n tree.brain.usdKnownCount > 0 || tree.brain.usdUnknownCount === 0\n ? null\n : unpriced(tree.brain.usdUnknownCount, tree.brain.meteredCount, brainUsdUnknownNodes)\n const workerUsdUnreported =\n workerUsdUnknownNodes.length === 0 || workerUsdUnknownNodes.length < rootChildSpends.length\n ? null\n : unpriced(workerUsdUnknownNodes.length, rootChildSpends.length, workerUsdUnknownNodes)\n return {\n rootChildCloses,\n rootChildSpends,\n workerUsdUnknownNodes,\n workerTokensUnknownNodes,\n journalWorkerIn,\n journalWorkerOut,\n journalWorkerUsd,\n workerUsdById,\n workerUsdByLabel,\n usdKnownRecords,\n usdUnknownRecords,\n usdUnknownNodes,\n brainUsdUnknownNodes,\n brainTokensUnknownNodes,\n unpriced,\n unreportedTokens,\n usdPartial,\n usdAllUnknown,\n brainTokensUnreported,\n brainUsdUnreported,\n workerUsdUnreported,\n }\n}\n\n/** Worker token totals: journal spend plus harness session counts, or the reason they are absent. */\nexport function measureWorkerTokens(a: Analysis, f: SpendFacts) {\n const { src, gap, haveJournal } = a\n const {\n rootChildSpends,\n workerTokensUnknownNodes,\n journalWorkerIn,\n journalWorkerOut,\n unreportedTokens,\n } = f\n const sq = src.harnessWorkerTokens\n const harnessGapReason =\n src.harnessMissingReason ?? 'harness session store unavailable and journal settled spend is 0'\n const workerTokenLimit = src.limits.workerTokens\n const workerTokensUnreported =\n workerTokensUnknownNodes.length === 0\n ? null\n : unreportedTokens(\n workerTokensUnknownNodes.length,\n rootChildSpends.length,\n workerTokensUnknownNodes,\n )\n const workerIn: Measured<number> =\n workerTokenLimit !== null\n ? gap('workers.tokensIn', workerTokenLimit)\n : workerTokensUnreported !== null\n ? gap('workers.tokensIn', workerTokensUnreported)\n : sq !== null\n ? journalWorkerIn + sq.input\n : haveJournal\n ? journalWorkerIn\n : gap('workers.tokensIn', harnessGapReason)\n const workerOut: Measured<number> =\n workerTokenLimit !== null\n ? unavailable(workerTokenLimit)\n : workerTokensUnreported !== null\n ? unavailable(workerTokensUnreported)\n : sq !== null\n ? journalWorkerOut + sq.output\n : haveJournal\n ? journalWorkerOut\n : unavailable(harnessGapReason)\n return { sq, workerTokenLimit, workerIn, workerOut }\n}\n\n/** Total USD and the close record it is read against. */\nexport function measureTotalUsd(a: Analysis, f: SpendFacts) {\n const { src, gap, journalMissing, haveJournal, tree, state, result } = a\n const { journalWorkerUsd, usdKnownRecords, usdUnknownRecords, usdUnknownNodes, unpriced } = f\n const stateResult = asRecord(state?.result)\n const stateUsd = typeof stateResult.spentUsd === 'number' ? stateResult.spentUsd : null\n const resultSpentTotal = asRecord(result?.spentTotal)\n const resultCloseUsd =\n typeof resultSpentTotal.usd === 'number' && Number.isFinite(resultSpentTotal.usd)\n ? resultSpentTotal.usd\n : null\n // The close record: what the store wrote as settled when the run closed.\n const closeUsd = stateUsd ?? resultCloseUsd\n // A store that logs tokens but never a price yields usd 0 from every sum. That\n // 0 is the store's silence, not a free run, so the limit outranks the sum.\n const usdLimit = src.limits.spendUsd\n // The close record carries its own completeness flag: `spentTotal.usdKnown: false` means\n // Runtime priced part of the run from a catalog, so the number is a floor, not a total.\n const closeUsdUnreported =\n stateUsd === null && resultCloseUsd !== null && resultSpentTotal.usdKnown === false\n const usdUnreportedReason = unpriced(\n usdUnknownRecords,\n usdKnownRecords + usdUnknownRecords,\n usdUnknownNodes,\n )\n // Which numbers may be partial, and which must go absent: a number may be a floor only\n // when its own record carries the known/unknown split beside it — `SpendMeasurement`\n // has `records`/`unknownRecords`, and `RoleSpend` has `source`. `totalUsd` is a bare\n // scalar, so a floor there is an unlabelled understatement and stays unavailable; the\n // partial sum with its denominators lives in `spend.journalDerived`, which this type's\n // own doc already names as the field to prefer.\n const totalUsd: Measured<number> =\n usdLimit !== null\n ? gap('totalUsd', usdLimit)\n : stateUsd !== null\n ? round(stateUsd, 6)\n : !haveJournal\n ? gap('totalUsd', journalMissing)\n : usdUnknownRecords > 0\n ? gap('totalUsd', usdUnreportedReason)\n : round(tree.brain.usd + journalWorkerUsd, 6)\n return {\n stateResult,\n stateUsd,\n usdLimit,\n totalUsd,\n closeUsd,\n closeUsdUnreported,\n usdUnreportedReason,\n }\n}\n\nexport function buildSpend(a: Analysis, f: SpendFacts, t: TotalUsd): SpendMeasurements {\n const { journalMissing, haveJournal, tree, rootId } = a\n const {\n journalWorkerUsd,\n usdKnownRecords,\n usdUnknownRecords,\n usdUnknownNodes,\n usdPartial,\n usdAllUnknown,\n } = f\n const { usdLimit, closeUsd, closeUsdUnreported, usdUnreportedReason } = t\n const journalSpendRecords = usdKnownRecords\n // `journalDerived` keeps its partial sum: `records` and `unknownRecords` state exactly\n // how much of the run it covers. Only an all-unreported channel has nothing to report.\n const journalDerivedAvailable = usdLimit === null && haveJournal && !usdAllUnknown\n const closeRecordAvailable = usdLimit === null && closeUsd !== null && !closeUsdUnreported\n const spend: SpendMeasurements = {\n journalDerived: {\n usd: journalDerivedAvailable\n ? round(tree.brain.usd + journalWorkerUsd, 6)\n : unavailable(usdLimit ?? (haveJournal ? usdUnreportedReason : journalMissing)),\n records: journalDerivedAvailable ? journalSpendRecords : 0,\n unknownRecords: usdLimit === null && haveJournal ? usdUnknownRecords : 0,\n partial: journalDerivedAvailable && usdPartial,\n unknownNodes: usdLimit === null && haveJournal ? usdUnknownNodes : [],\n },\n closeRecord: {\n usd: closeRecordAvailable\n ? round(closeUsd as number, 6)\n : unavailable(\n usdLimit ??\n (closeUsdUnreported\n ? 'close record incomplete: result.json spentTotal.usdKnown is false'\n : 'no close record: neither state.json result.spentUsd nor result.json spentTotal.usd is present'),\n ),\n records: closeRecordAvailable ? 1 : 0,\n unknownRecords: closeUsdUnreported ? 1 : 0,\n partial: false,\n unknownNodes: closeUsdUnreported && rootId !== null ? [rootId] : [],\n },\n }\n return spend\n}\n\nexport type SpendFacts = ReturnType<typeof collectSpendFacts>\nexport type WorkerTokens = ReturnType<typeof measureWorkerTokens>\nexport type TotalUsd = ReturnType<typeof measureTotalUsd>\n","/**\n * The pure analyzer. Takes already-read bytes (`SupervisorRunSources`) and\n * returns the report — every metric derivable from a synthetic journal string\n * with no filesystem, no process, and no network. All I/O lives in a reader\n * (`reader.ts` is one).\n *\n * The metric groups live in `analyze-*.ts`; this file only runs them in the\n * order the report's `gaps` list is written.\n */\n\nimport { createAnalysis } from './analyze-context'\nimport { measureDecision } from './analyze-decision'\nimport { buildEconomics, buildPerWorker } from './analyze-economics'\nimport {\n buildOrchestration,\n measureConcurrency,\n measureDelegationDepth,\n measureRespawns,\n measureSteers,\n measureWall,\n} from './analyze-orchestration'\nimport { buildOutcome } from './analyze-outcome'\nimport {\n buildSpend,\n collectSpendFacts,\n measureTotalUsd,\n measureWorkerTokens,\n} from './analyze-spend'\nimport {\n SUPERVISOR_RUN_SCHEMA,\n type SupervisorRunReport,\n type SupervisorRunSources,\n unavailable,\n} from './types'\n\n/**\n * Analyze already-read supervisor-run bytes. Pure and synchronous: same bytes\n * in, same report out (modulo `generatedAt`, which `now` pins in tests).\n */\nexport function analyzeSupervisorRunSources(\n src: SupervisorRunSources,\n now: () => number = Date.now,\n): SupervisorRunReport {\n const a = createAnalysis(src)\n const { gap, gaps, rootId, rootSpawn, journalMissing } = a\n // Measurements record their gaps as they run, so the order below is the order of `report.gaps`.\n const wall = measureWall(a)\n const steerFacts = measureSteers(a)\n const concurrency = measureConcurrency(a, wall.wallEndAt)\n const respawns = measureRespawns(a)\n const steps = {\n ...wall,\n ...steerFacts,\n ...concurrency,\n ...respawns,\n delegationDepth: measureDelegationDepth(a),\n }\n const orchestration = buildOrchestration(a, steps)\n const decision = measureDecision(a, steps)\n const spendFacts = collectSpendFacts(a)\n const tokens = measureWorkerTokens(a, spendFacts)\n const totals = measureTotalUsd(a, spendFacts)\n const spend = buildSpend(a, spendFacts, totals)\n const perWorker = buildPerWorker(a, spendFacts, totals)\n const economics = buildEconomics(a, spendFacts, totals, tokens, { decision, spend, perWorker })\n const outcome = buildOutcome(a, totals)\n return {\n schema: SUPERVISOR_RUN_SCHEMA,\n runRef: src.runRef,\n instanceId: src.instanceId,\n arm: src.arm,\n supervisorId: rootId !== null ? rootId : unavailable(journalMissing),\n supervisorProfileDigest:\n rootSpawn?.profileDigest !== null && rootSpawn?.profileDigest !== undefined\n ? rootSpawn.profileDigest\n : gap('supervisorProfileDigest', 'root spawned event has no profile digest'),\n generatedAt: new Date(now()).toISOString(),\n orchestration,\n decision,\n economics,\n outcome,\n rootWorkspaceCaptures: src.rootWorkspaceCaptures ?? null,\n gaps,\n traceCommand:\n src.traceCommand ??\n 'npx --yes @tangle-network/traces@latest analyze --harness opencode --cwd <worker-clone-cwd>',\n }\n}\n","/**\n * Optional Runtime run-dir files, read as bytes.\n *\n * `coordination-log.jsonl` is Runtime's JSONL of `{ runId, seq, at, event }`:\n * questions, steers, answers and peer mail between nodes. The `team-shape`\n * analyst reads communication and steer edges from it.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nconst COORDINATION_FILE = 'coordination-log.jsonl'\nexport const readFileText = (path: string): Promise<string> => readFile(path, 'utf8')\n\n/** File text, or null when the file does not exist. Any other read error throws. */\nexport async function readMaybe(path: string, read = readFileText): Promise<string | null> {\n return read(path).catch((error: unknown) => {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code: unknown }).code === 'ENOENT'\n ) {\n return null\n }\n throw error\n })\n}\n\n/** The run's coordination log, or null when Runtime wrote none. */\nexport function readCoordinationLog(runDir: string, read = readFileText): Promise<string | null> {\n return readMaybe(join(runDir, COORDINATION_FILE), read)\n}\n","import { nonEmptyString, recordOrNull as record } from './source-facts'\nimport type { SourceLimits } from './types'\n\nfunction spendRecord(value: unknown): Record<string, unknown> | null {\n const spend = record(value)\n if (spend === null) return null\n const tokens = record(spend.tokens)\n if (\n tokens === null ||\n typeof tokens.input !== 'number' ||\n !Number.isFinite(tokens.input) ||\n tokens.input < 0 ||\n typeof tokens.output !== 'number' ||\n !Number.isFinite(tokens.output) ||\n tokens.output < 0 ||\n typeof spend.usd !== 'number' ||\n !Number.isFinite(spend.usd) ||\n spend.usd < 0 ||\n (spend.usdKnown !== undefined && typeof spend.usdKnown !== 'boolean')\n ) {\n return null\n }\n return spend\n}\n\nexport function sourceLimits(\n root: string,\n events: readonly Record<string, unknown>[],\n workerIds: ReadonlySet<string>,\n): SourceLimits {\n const rootMeters = events.filter((event) => event.kind === 'metered' && event.id === root)\n const invalidRootMeters = rootMeters.filter((event) => spendRecord(event.spend) === null)\n const rootMeterReason =\n rootMeters.length === 0\n ? 'Runtime journal has no root metered event'\n : invalidRootMeters.length > 0\n ? `${invalidRootMeters.length} root metered event(s) lack complete spend`\n : null\n const closes = events.filter(\n (event) =>\n workerIds.has(nonEmptyString(event.id) ?? '') &&\n (event.kind === 'settled' || event.kind === 'cancelled'),\n )\n const settledById = new Map<string, Record<string, unknown>[]>()\n for (const event of closes) {\n const id = nonEmptyString(event.id)\n if (id === null) continue\n const matches = settledById.get(id) ?? []\n matches.push(event)\n settledById.set(id, matches)\n }\n const incompleteWorkers = [...workerIds].filter((id) => {\n const terminal = settledById.get(id)\n return (\n terminal?.length !== 1 ||\n terminal[0]?.kind !== 'settled' ||\n spendRecord(terminal[0]?.spent) === null\n )\n })\n const missingVerdicts = [...workerIds].filter((id) => {\n const terminal = settledById.get(id)?.[0]\n if (terminal?.kind !== 'settled') return true\n const verdict = record(terminal.verdict)\n return typeof verdict?.valid !== 'boolean'\n })\n\n return {\n managerTokens: rootMeterReason,\n workerTokens:\n incompleteWorkers.length === 0\n ? null\n : `${incompleteWorkers.length}/${workerIds.size} child invocation(s) lack one settled spend record`,\n // `usdKnown: false` on ONE record is not a limit of this store: the store priced every\n // other record, and a limit here discards them all. The analyzer folds the flag per\n // record instead, and reports a partial total with the unpriced nodes named.\n spendUsd:\n rootMeterReason !== null\n ? rootMeterReason\n : incompleteWorkers.length > 0\n ? 'at least one child invocation lacks a settled spend record'\n : null,\n workerVerdicts:\n missingVerdicts.length === 0\n ? null\n : `${missingVerdicts.length}/${workerIds.size} child invocation(s) lack a structured validity verdict`,\n deliverables:\n workerIds.size === 0\n ? null\n : 'Runtime FileRunContext does not retain per-child delivered patches',\n }\n}\n","/**\n * Reader for agent-runtime's file-backed supervision context.\n *\n * Runtime stores multiple recursive trees in one `spawn-journal.jsonl`.\n * Each line is an envelope whose `root` identifies the local tree. A journal\n * can connect a nested tree with `spawned.ownedTreeRoot`. It can also use the\n * spawned child id as the nested root when no owned tree is recorded. Either\n * way the nested tree may repeat its owner's spawn as a parentless marker: the\n * owner's id, not the tree key, identifies it (an owned tree's key is a path\n * such as `root/root:s0`). Descendant spawns must occur in the tree their\n * parent owns. This reader removes a duplicate marker and preserves the other\n * envelopes for the supervisor-run analyzer. Runtime stores profile\n * identity below `identity` and does not emit Eval's role field. This boundary\n * projects those fields without changing Runtime's dialect.\n *\n * Transcripts come from Runtime's own records too: `root-stream.jsonl` is the root's, each\n * worker's turn outputs and native-session receipt are read from the journal, and every blob\n * a record names is checked on disk (see `nodeTranscripts`).\n *\n * The run's terminal record is Runtime's own: `result.json` is the\n * `SupervisedResult` that `supervise()` returned, verbatim, and its `kind`\n * (`winner`, `no-winner`, or whatever a later arm is called) is the status.\n * `failure.json` (`{ runId, pursuitId, at, error: { name, message } }`) is the\n * record Runtime writes when `supervise()` threw before a result landed. Both\n * pass through as bytes; `terminal-record.ts` reads them. The reader does not\n * decide which kinds count: a kind it refuses is a run that recorded its\n * outcome and got reported as having none. The reader does not synthesize status fields. The analyzer names the Runtime\n * record that supplied a status, so status provenance cannot be mislabelled.\n *\n * `usdKnown: false` / `tokensKnown: false` on ONE record is not a limit of this\n * store. The store recorded every other record completely, so the flags travel\n * through to the analyzer per record, which reports the measured nodes and\n * names the unreported ones.\n */\n\nimport { stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { hashCanonical } from '../ledger-core/canonical'\nimport type { RolloutWorkspaceCapture } from '../rollout/schema'\nimport { readCoordinationLog, readFileText, readMaybe } from './coordination-reader'\nimport { expandJournalEventGroup } from './journal-event-group'\nimport { sourceLimits } from './runtime-source-limits'\nimport { nonEmptyString, recordOrNull as record } from './source-facts'\nimport {\n NO_SOURCE_LIMITS,\n type SupervisorRunSources,\n type WorkerLogSource,\n type WorkerNativeSession,\n} from './types'\n\nconst JOURNAL_FILE = 'spawn-journal.jsonl'\nconst OBSERVER_FILE = 'observer.jsonl'\nconst ROOT_STREAM_FILE = 'root-stream.jsonl'\nconst BLOB_DIR = 'blobs'\nconst RESULT_FILE = 'result.json'\nconst FAILURE_FILE = 'failure.json'\n\n/**\n * The files only Runtime's durable layer writes. Any one of them marks a\n * Runtime run directory: `supervise()` opens the spawn journal on its first\n * event, and `supervisePursuit` appends the observer's `before` event and, on\n * a throw, the failure record before any spawn.\n *\n * Measured motive (discovery-lab recursive smoke r1, 2026-09-06): the first\n * attempt threw on a caller input error 16 minutes before the corrected attempt\n * opened the spawn journal. At that instant the directory held `observer.jsonl`\n * (2 records) and the failure record and no journal, so a journal-only test\n * routed it to an unrelated reader, which reads neither file, and the recorded\n * throw was reported as no run at all.\n */\nconst RUNTIME_RUN_DIR_MARKERS: readonly string[] = [JOURNAL_FILE, OBSERVER_FILE, FAILURE_FILE]\n\ninterface BeginRecord {\n readonly root: string\n readonly at: string\n readonly line: number\n}\n\ninterface EventRecord {\n readonly root: string\n readonly event: Record<string, unknown>\n readonly line: number\n}\n\ninterface NormalizedRuntimeJournal {\n readonly root: string\n readonly startedAt: string\n readonly journal: string\n readonly events: readonly Record<string, unknown>[]\n}\n\nfunction profileDigest(event: Record<string, unknown>): string | null {\n const direct = nonEmptyString(event.profileDigest)\n if (direct !== null) return direct\n const identity = record(event.identity)\n return identity === null ? null : nonEmptyString(identity.profileDigest)\n}\n\nfunction formatError(path: string, line: number, detail: string): Error {\n return new Error(`${path}:${line}: invalid Runtime spawn journal: ${detail}`)\n}\n\nfunction parseEnvelopeJournal(text: string, path: string): NormalizedRuntimeJournal {\n const begins: BeginRecord[] = []\n const events: EventRecord[] = []\n const begun = new Map<string, BeginRecord>()\n\n for (const [index, sourceLine] of text.split('\\n').entries()) {\n const line = index + 1\n const trimmed = sourceLine.trim()\n if (trimmed.length === 0) continue\n let parsed: unknown\n try {\n parsed = JSON.parse(trimmed)\n } catch {\n throw formatError(path, line, 'line is not JSON')\n }\n const envelope = record(parsed)\n if (envelope === null) throw formatError(path, line, 'line is not an object')\n const kind = nonEmptyString(envelope.kind)\n const root = nonEmptyString(envelope.root)\n if (root === null) throw formatError(path, line, 'root must be a non-empty string')\n\n if (kind === 'begin') {\n const at = nonEmptyString(envelope.at)\n if (at === null || !Number.isFinite(Date.parse(at))) {\n throw formatError(path, line, 'begin.at must be an ISO timestamp')\n }\n if (begun.has(root)) throw formatError(path, line, `tree ${JSON.stringify(root)} began twice`)\n const begin = { root, at, line }\n begun.set(root, begin)\n begins.push(begin)\n continue\n }\n\n if (kind !== 'event' && kind !== 'events') {\n throw formatError(path, line, \"kind must be 'begin', 'event' or 'events'\")\n }\n if (!begun.has(root)) {\n throw formatError(path, line, `event for tree ${JSON.stringify(root)} precedes begin`)\n }\n const expanded = expandJournalEventGroup(envelope)\n if (!expanded.succeeded) throw formatError(path, line, expanded.error)\n for (const row of expanded.value) {\n const event = record(row.event)\n if (event === null) throw formatError(path, line, 'event must be an object')\n if (nonEmptyString(event.kind) === null) {\n throw formatError(path, line, 'event.kind must be a non-empty string')\n }\n events.push({ root, event: { ...event }, line })\n }\n }\n\n if (begins.length === 0) throw formatError(path, 1, 'no begin record')\n\n const parentSpawnsById = new Map<string, EventRecord[]>()\n const parentSpawnsByOwnedTreeRoot = new Map<string, EventRecord[]>()\n for (const entry of events) {\n if (entry.event.kind !== 'spawned') continue\n const id = nonEmptyString(entry.event.id)\n if (id === null) continue\n if (nonEmptyString(entry.event.parent) !== null) {\n const ownedTreeRoot = nonEmptyString(entry.event.ownedTreeRoot)\n if (ownedTreeRoot !== null) {\n const owners = parentSpawnsByOwnedTreeRoot.get(ownedTreeRoot) ?? []\n owners.push(entry)\n parentSpawnsByOwnedTreeRoot.set(ownedTreeRoot, owners)\n } else {\n const matches = parentSpawnsById.get(id) ?? []\n matches.push(entry)\n parentSpawnsById.set(id, matches)\n }\n }\n }\n\n const nestedRoots = new Set<string>()\n const nestedParentSpawns = new Map<string, EventRecord>()\n for (const begin of begins) {\n const parentSpawns = [\n ...new Set([\n ...(parentSpawnsByOwnedTreeRoot.get(begin.root) ?? []),\n ...(parentSpawnsById.get(begin.root) ?? []),\n ]),\n ].filter((entry) => entry.root !== begin.root)\n if (parentSpawns.length > 1) {\n throw formatError(\n path,\n begin.line,\n `tree ${JSON.stringify(begin.root)} has ${parentSpawns.length} parent spawns`,\n )\n }\n if (parentSpawns.length === 1) {\n nestedRoots.add(begin.root)\n nestedParentSpawns.set(begin.root, parentSpawns[0] as EventRecord)\n }\n }\n\n const topRoots = begins.filter((begin) => !nestedRoots.has(begin.root))\n if (topRoots.length !== 1) {\n throw formatError(\n path,\n topRoots[0]?.line ?? 1,\n `expected one top-level tree, found ${topRoots.length}`,\n )\n }\n const top = topRoots[0] as BeginRecord\n\n // A tree's root marker is a parentless spawn of the node that owns the tree: the top root\n // itself, or the parent spawn that owns a nested tree. An owned tree's key is a path, so\n // the owner's id is compared, never the tree key.\n const ownerIdByTree = new Map<string, string>([[top.root, top.root]])\n for (const [nestedRoot, parentSpawn] of nestedParentSpawns) {\n const ownerId = nonEmptyString(parentSpawn.event.id)\n if (ownerId !== null) ownerIdByTree.set(nestedRoot, ownerId)\n }\n const isRootMarker = (entry: EventRecord): boolean =>\n entry.event.kind === 'spawned' &&\n (entry.event.parent === undefined || entry.event.parent === null) &&\n nonEmptyString(entry.event.id) !== null &&\n entry.event.id === ownerIdByTree.get(entry.root)\n const rootMarkersByTree = new Map<string, EventRecord[]>()\n for (const entry of events) {\n if (!isRootMarker(entry)) continue\n const markers = rootMarkersByTree.get(entry.root) ?? []\n markers.push(entry)\n rootMarkersByTree.set(entry.root, markers)\n }\n\n for (const nestedRoot of nestedRoots) {\n const markers = rootMarkersByTree.get(nestedRoot) ?? []\n if (markers.length > 1) {\n throw formatError(\n path,\n begun.get(nestedRoot)?.line ?? 1,\n `nested tree ${JSON.stringify(nestedRoot)} contains ${markers.length} root markers`,\n )\n }\n const parentSpawn = nestedParentSpawns.get(nestedRoot)\n if (parentSpawn === undefined) {\n throw formatError(\n path,\n begun.get(nestedRoot)?.line ?? 1,\n `nested tree ${JSON.stringify(nestedRoot)} has no parent spawn`,\n )\n }\n const markerDigest = profileDigest(markers[0]?.event ?? {})\n const parentDigest = profileDigest(parentSpawn.event)\n if (markerDigest !== null && parentDigest !== null && markerDigest !== parentDigest) {\n throw formatError(\n path,\n markers[0]?.line ?? 1,\n `nested tree ${JSON.stringify(nestedRoot)} disagrees with its parent profile digest`,\n )\n }\n if (parentDigest === null && markerDigest !== null) {\n parentSpawn.event.profileDigest = markerDigest\n }\n }\n\n const ownedTreeBySupervisorId = new Map<string, string>([[top.root, top.root]])\n for (const [nestedRoot, parentSpawn] of nestedParentSpawns) {\n const supervisorId = nonEmptyString(parentSpawn.event.id)\n if (supervisorId === null) continue\n const priorTree = ownedTreeBySupervisorId.get(supervisorId)\n if (priorTree !== undefined && priorTree !== nestedRoot) {\n throw formatError(\n path,\n parentSpawn.line,\n `spawn ${JSON.stringify(supervisorId)} owns both ${JSON.stringify(priorTree)} and ${JSON.stringify(nestedRoot)}`,\n )\n }\n ownedTreeBySupervisorId.set(supervisorId, nestedRoot)\n }\n for (const entry of events) {\n if (entry.event.kind !== 'spawned') continue\n const parentId = nonEmptyString(entry.event.parent)\n if (parentId === null) continue\n const parentTree = ownedTreeBySupervisorId.get(parentId)\n if (parentTree === undefined) {\n throw formatError(\n path,\n entry.line,\n `spawn ${JSON.stringify(entry.event.id)} names parent ${JSON.stringify(parentId)}, which owns no journal tree`,\n )\n }\n if (entry.root !== parentTree) {\n throw formatError(\n path,\n entry.line,\n `spawn ${JSON.stringify(entry.event.id)} is in tree ${JSON.stringify(entry.root)}, but parent ${JSON.stringify(parentId)} owns tree ${JSON.stringify(parentTree)}`,\n )\n }\n }\n\n // Runtime's recursive atom has no supervisor/worker role field. A tree root\n // is a supervisor; a child without its own tree is a worker.\n const supervisorIds = new Set([\n top.root,\n ...[...nestedParentSpawns.values()]\n .map((entry) => nonEmptyString(entry.event.id))\n .filter((id): id is string => id !== null),\n ])\n const normalized = events\n .filter((entry) => !(nestedRoots.has(entry.root) && isRootMarker(entry)))\n .map((entry) => {\n const event = { ...entry.event }\n if (event.kind === 'spawned') {\n const digest = profileDigest(event)\n if (event.profileDigest === undefined && digest !== null) {\n event.profileDigest = digest\n }\n if (event.role === undefined) {\n event.role = supervisorIds.has(nonEmptyString(event.id) ?? '') ? 'supervisor' : 'worker'\n }\n }\n return { root: entry.root, event }\n })\n\n const rootMarkers = rootMarkersByTree.get(top.root) ?? []\n if (rootMarkers.length !== 1) {\n throw formatError(\n path,\n top.line,\n `top-level tree ${JSON.stringify(top.root)} must contain one root marker`,\n )\n }\n\n return {\n root: top.root,\n startedAt: top.at,\n // Keep Runtime's event envelope intact. The pure source parser uses the envelope to\n // distinguish an understood-but-unmodeled Runtime event from an unreadable flat record.\n journal: `${normalized\n .map((entry) => JSON.stringify({ kind: 'event', root: entry.root, event: entry.event }))\n .join('\\n')}\\n`,\n events: normalized.map((entry) => entry.event),\n }\n}\n\nfunction parseOptionalRecord(text: string | null, path: string): Record<string, unknown> | null {\n if (text === null) return null\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n throw new Error(`${path}: invalid JSON`)\n }\n const value = record(parsed)\n if (value === null) throw new Error(`${path}: expected a JSON object`)\n return value\n}\n\n/**\n * Refuse a `result.json` that belongs to another run. Runtime's result carries\n * its own `tree.root`; a settled record with a different root is a copied or\n * misplaced file, and reading its status onto this journal misreports the run.\n */\nfunction assertResultMatchesJournal(\n root: string,\n result: Record<string, unknown> | null,\n resultPath: string,\n): void {\n const resultKind = result === null ? null : nonEmptyString(result.kind)\n if (resultKind === null || result === null) return\n const resultRoot = nonEmptyString(record(result.tree)?.root)\n if (resultRoot === null) {\n throw new Error(`${resultPath}: Runtime ${resultKind} result has no tree.root`)\n }\n if (resultRoot !== root) {\n throw new Error(\n `${resultPath}: root ${JSON.stringify(resultRoot)} does not match journal root ${JSON.stringify(root)}`,\n )\n }\n}\n\n/**\n * Refuse a `failure.json` that is not a failure record. Runtime writes\n * `{ runId, pursuitId, at, error: { name, message } }`; a document without an\n * `error` object is not one, and reading it as a failure invents a terminal\n * state the run never recorded. The record carries no tree root, so its\n * identity is not checked against the journal.\n */\nfunction assertFailureRecord(failure: Record<string, unknown> | null, failurePath: string): void {\n if (failure === null) return\n if (record(failure.error) === null) {\n throw new Error(`${failurePath}: Runtime failure record has no error object`)\n }\n}\n\n/**\n * The journal's begin stamp in the analyzer's state-document shape. It carries\n * the run identity and start instant only; the terminal status lives in\n * Runtime's own `result.json` / `failure.json`, which the analyzer reads by\n * name, so no synthetic status field is fabricated here.\n */\nfunction runtimeBeginState(root: string, startedAt: string): string {\n return JSON.stringify({ id: root, startedAt })\n}\n\n/**\n * The file Runtime's `FileResultBlobStore` writes for one content address\n * (`sha256:<hex>` → `blobs/sha256-<hex>.json`), or null for anything that is not one.\n */\nfunction blobFile(runDir: string, ref: unknown): string | null {\n return typeof ref === 'string' && /^sha256:[0-9a-f]{64}$/u.test(ref)\n ? join(runDir, BLOB_DIR, `${ref.replace(':', '-')}.json`)\n : null\n}\n\ntype NodeTranscript = Pick<\n WorkerLogSource,\n 'transcriptRef' | 'turns' | 'nativeSession' | 'workspaceCaptures'\n>\n\ninterface NodeTranscriptFacts {\n dispatched: number\n readonly outputRefs: { value: unknown; turn: boolean }[]\n readonly outputPositions: Map<string, number>\n receipt: Record<string, unknown> | null\n}\n\n/** A later receipt replaces an earlier one, except that an absence never replaces an available one. */\nfunction keepReceipt(fact: NodeTranscriptFacts, receipt: Record<string, unknown> | null): void {\n if (receipt === null) return\n if (fact.receipt?.status === 'available' && receipt.status !== 'available') return\n fact.receipt = receipt\n}\n\n/**\n * The files each harness writes its conversation to. A receipt can be available and complete\n * while holding none of them: on the 2026-10-04 trace proof a Pi worker that never wrote a session\n * stored only `.pi/agent/models-store.json`, and this summary counted it as a transcript.\n */\nconst HARNESS_SESSION_FILE: Readonly<Record<string, RegExp>> = {\n 'claude-code': /(^|\\/)\\.claude\\/projects\\/.+\\.jsonl$/u,\n codex: /(^|\\/)\\.codex\\/sessions\\/.+\\.jsonl$/u,\n pi: /(^|\\/)\\.pi\\/agent\\/sessions\\/.+\\.jsonl$/u,\n opencode:\n /(^|\\/)(\\.local\\/share\\/opencode\\/(opencode\\.db|storage\\/session\\/.+\\.json|export\\/.+\\.json)|\\.opencode\\/sessions\\/.+)$/u,\n}\n\n/** Session files the receipt's transcript blob lists, or undefined when it cannot say. */\nasync function receiptSessionFiles(\n file: string,\n read: typeof readFileText,\n): Promise<number | undefined> {\n let descriptor: unknown\n try {\n descriptor = JSON.parse(await read(file))\n } catch {\n return undefined\n }\n const harness = record(descriptor)?.harness\n const files = record(descriptor)?.files\n const pattern = typeof harness === 'string' ? HARNESS_SESSION_FILE[harness] : undefined\n if (pattern === undefined || !Array.isArray(files)) return undefined\n return files.filter((entry) => {\n const path = record(entry)?.path\n return typeof path === 'string' && pattern.test(path)\n }).length\n}\n\ntype NativeSessionState = 'complete' | 'partial' | 'no-session-file' | 'unavailable' | 'none'\n\nfunction nativeSessionState(session: WorkerNativeSession | null | undefined): NativeSessionState {\n if (session === null || session === undefined) return 'none'\n if (session.status !== 'available') return 'unavailable'\n if (session.coverageComplete === false) return 'partial'\n if (session.sessionFiles === 0) return 'no-session-file'\n return 'complete'\n}\n\n/**\n * What this reader can say about harness-session traces. Every spawned worker counts, including\n * one that recorded nothing; the root is reported apart because its receipt lives in result.json\n * (`rootHarnessTranscript`), not on a worker. Runtime records the session identity on each\n * receipt, so the sessions are read per node, not through one command. A receipt counts as a\n * session only when its copy is complete and holds a file the harness writes its conversation to.\n */\nfunction nativeTraceSummary(\n workers: readonly WorkerLogSource[],\n root: NodeTranscript | undefined,\n): string {\n const states = workers.map((worker) => nativeSessionState(worker.nativeSession))\n const count = (state: NativeSessionState): number => states.filter((s) => s === state).length\n const rootSession = root?.nativeSession ?? null\n const rootState = nativeSessionState(rootSession)\n const rootText =\n rootSession === null\n ? 'no receipt'\n : rootSession.status === 'unavailable'\n ? `unavailable (${rootSession.reason})`\n : rootState === 'complete'\n ? 'complete'\n : rootState === 'partial'\n ? 'partial copy'\n : 'no session file'\n if (rootSession === null && states.every((state) => state === 'none'))\n return 'unavailable — no node carries a Runtime harness transcript receipt'\n const gaps = [\n count('partial') > 0 ? `${count('partial')} only a partial copy` : null,\n count('no-session-file') > 0\n ? `${count('no-session-file')} a receipt with no session file`\n : null,\n ].filter((gap): gap is string => gap !== null)\n return `per node — ${count('complete')} of ${workers.length} workers carry a complete native session receipt (workers[].nativeSession)${gaps.length > 0 ? `; ${gaps.join('; ')}` : ''}; root: ${rootText} (result.json rootHarnessTranscript)`\n}\n\nasync function workspaceCapturesFromOutput(\n runDir: string,\n ref: unknown,\n read: typeof readFileText,\n): Promise<RolloutWorkspaceCapture[]> {\n const outRef = typeof ref === 'string' ? ref : null\n const blobPath = blobFile(runDir, ref)\n const missing = (projectionGap: string): RolloutWorkspaceCapture => ({\n outRef,\n blobPath,\n receiptPointer: null,\n receipt: null,\n attempts: null,\n coverageComplete: null,\n incompleteReason: null,\n projectionGap,\n })\n if (blobPath === null) return [missing('Runtime output has no valid content address')]\n if (!(await isFile(blobPath))) return [missing('Runtime output blob is missing or not a file')]\n const raw = await readMaybe(blobPath, read)\n if (raw === null) return [missing('Runtime output blob is missing')]\n let output: unknown\n try {\n output = JSON.parse(raw)\n } catch {\n return [missing('Runtime output blob is not JSON')]\n }\n let addressGap: string | null = null\n try {\n if (hashCanonical(output) !== outRef) {\n addressGap = 'Runtime output content address does not match output blob'\n }\n } catch {\n addressGap = 'Runtime output cannot be canonically hashed'\n }\n const project = (rawReceipt: unknown, receiptPointer: string | null): RolloutWorkspaceCapture => {\n const receipt = record(rawReceipt)\n if (receipt === null) {\n return {\n ...missing(\n `workspaceCapture receipt is absent or malformed${addressGap === null ? '' : `; ${addressGap}`}`,\n ),\n receiptPointer,\n receipt: rawReceipt,\n }\n }\n const provenance = record(receipt.provenance)\n const attempts = Array.isArray(provenance?.attempts) ? provenance.attempts : null\n const coverageComplete =\n typeof receipt.coverageComplete === 'boolean' ? receipt.coverageComplete : null\n const incompleteReason =\n typeof receipt.incompleteReason === 'string' ? receipt.incompleteReason : null\n const gaps: string[] = []\n if (addressGap !== null) gaps.push(addressGap)\n if (coverageComplete === null) gaps.push('workspaceCapture.coverageComplete is absent')\n if (record(receipt.snapshot) === null) gaps.push('workspaceCapture.snapshot is absent')\n if (provenance === null) gaps.push('workspaceCapture.provenance is absent')\n if (attempts === null) gaps.push('workspaceCapture.provenance.attempts is absent')\n else if (attempts.length === 0 || attempts.some((attempt) => record(attempt) === null)) {\n gaps.push('workspaceCapture.provenance.attempts is empty or malformed')\n }\n return {\n outRef,\n blobPath,\n receiptPointer,\n receipt,\n attempts,\n coverageComplete,\n incompleteReason,\n projectionGap: gaps.length > 0 ? gaps.join('; ') : null,\n }\n }\n const result = record(output)\n const captures: RolloutWorkspaceCapture[] = []\n // Use the record's field order and each array's order so every retained source stays ordered.\n for (const key of Object.keys(result ?? {})) {\n if (key === 'workspaceCapture') {\n captures.push(project(result?.[key], '/workspaceCapture'))\n } else if (key === 'workspaceCaptures') {\n const receipts = result?.[key]\n if (Array.isArray(receipts) && receipts.length > 0) {\n for (const [index, receipt] of receipts.entries()) {\n captures.push(project(receipt, `/workspaceCaptures/${index}`))\n }\n } else {\n captures.push({\n ...missing(\n `workspaceCaptures is empty or malformed${addressGap === null ? '' : `; ${addressGap}`}`,\n ),\n receiptPointer: '/workspaceCaptures',\n receipt: receipts ?? null,\n })\n }\n }\n }\n return captures.length > 0 ? captures : [project(null, null)]\n}\n\n/**\n * What Runtime retained of each node's decisions, from its own records.\n *\n * - A turn is one `execution-admitted` event in the `dispatched` phase. Its `execution-result`\n * names an output blob holding that turn's provider event stream (reasoning, tool calls and\n * results as the harness reported them). A dispatched turn with no retained output lost its\n * record, which is how a worker that went down mid-turn shows up.\n * - Every event's `outRef` enters the same collector, once per node and address. Terminal\n * records retain ordinary and steerable results; they are not counted as dispatched turns.\n * - The terminal event's `harnessTranscript` receipt covers the harness's native session files.\n * Those are the only record of the harness's own subagents, so an unavailable receipt is a\n * separate gap from a missing turn, and its reason is Runtime's, verbatim. `settled`,\n * `cancelled` and `reconciled` all carry one; an available receipt is never replaced by a later\n * absence. The root has no terminal event, so its receipt is the settle record's\n * `rootHarnessTranscript`.\n *\n * Blob files are checked on disk: a receipt that names a blob the directory no longer holds is\n * not a retained transcript.\n */\nasync function nodeTranscripts(\n runDir: string,\n events: readonly Record<string, unknown>[],\n nodeIds: ReadonlySet<string>,\n read: typeof readFileText,\n root?: { readonly id: string; readonly receipt: Record<string, unknown> | null },\n): Promise<Map<string, NodeTranscript>> {\n const facts = new Map<string, NodeTranscriptFacts>()\n const entry = (id: string): NodeTranscriptFacts => {\n let found = facts.get(id)\n if (found === undefined) {\n found = { dispatched: 0, outputRefs: [], outputPositions: new Map(), receipt: null }\n facts.set(id, found)\n }\n return found\n }\n for (const event of events) {\n const id = nonEmptyString(event.id)\n if (id === null || !nodeIds.has(id)) continue\n if (Object.hasOwn(event, 'outRef')) {\n const fact = entry(id)\n const ref = event.outRef\n const position = typeof ref === 'string' ? fact.outputPositions.get(ref) : undefined\n if (position !== undefined) {\n if (event.kind === 'execution-result') fact.outputRefs[position]!.turn = true\n } else {\n if (typeof ref === 'string') fact.outputPositions.set(ref, fact.outputRefs.length)\n fact.outputRefs.push({ value: ref, turn: event.kind === 'execution-result' })\n }\n }\n if (event.kind === 'execution-admitted' && record(event.admission)?.phase === 'dispatched') {\n entry(id).dispatched += 1\n } else if (\n event.kind === 'settled' ||\n event.kind === 'cancelled' ||\n event.kind === 'reconciled'\n ) {\n // A reconciled node carries its receipt on `reconciled`, which 15 available transcripts of\n // the 2026-10-04 Discovery archives did and this reader once skipped.\n keepReceipt(entry(id), record(event.harnessTranscript))\n }\n }\n if (root !== undefined && nodeIds.has(root.id)) keepReceipt(entry(root.id), root.receipt)\n const out = new Map<string, NodeTranscript>()\n for (const [id, fact] of facts) {\n const retained: string[] = []\n let retainedTurns = 0\n const workspaceCaptures: RolloutWorkspaceCapture[] = []\n for (const { value: ref, turn } of fact.outputRefs) {\n const file = blobFile(runDir, ref)\n if (file !== null && (await isFile(file))) {\n retained.push(file)\n if (turn) retainedTurns += 1\n }\n workspaceCaptures.push(...(await workspaceCapturesFromOutput(runDir, ref, read)))\n }\n let nativeSession: WorkerNativeSession | null = null\n if (fact.receipt !== null) {\n if (fact.receipt.status === 'available') {\n const file = blobFile(runDir, fact.receipt.transcriptRef)\n if (file !== null && (await isFile(file))) {\n const sessionFiles = await receiptSessionFiles(file, read)\n const coverageComplete = fact.receipt.coverageComplete\n nativeSession = {\n status: 'available',\n ref: file,\n ...(typeof coverageComplete === 'boolean' ? { coverageComplete } : {}),\n ...(sessionFiles === undefined ? {} : { sessionFiles }),\n }\n } else {\n nativeSession = { status: 'unavailable', reason: 'receipt-blob-missing' }\n }\n } else {\n nativeSession = {\n status: 'unavailable',\n reason: nonEmptyString(fact.receipt.reason) ?? 'unavailable',\n }\n }\n }\n out.set(id, {\n // The native session is the fuller record; the newest turn output is the next best.\n transcriptRef:\n nativeSession?.status === 'available' ? nativeSession.ref : (retained.at(-1) ?? null),\n turns: { dispatched: fact.dispatched, retained: retainedTurns },\n nativeSession,\n workspaceCaptures: workspaceCaptures.length > 0 ? workspaceCaptures : null,\n })\n }\n return out\n}\n\nexport interface RuntimeReaderOptions {\n /** Read original UTF-8 bytes at logical run paths. Only ENOENT means absence; other failures propagate. */\n readonly readFile?: typeof readFileText\n /**\n * Throw on a missing spawn journal instead of returning absent-shaped\n * sources. The default (false) models a journal-less run dir — a\n * pre-supervise death, a backfilled zombie — as a readable absence.\n */\n readonly strict?: boolean\n}\n\n/**\n * The run identity a terminal record names when no journal exists yet: the\n * settle record's `tree.root`, else the failure record's `runId`. Both are\n * Runtime's own `runId`, so the report names the run the record is about\n * instead of `?`.\n */\nfunction recordedRunId(\n result: Record<string, unknown> | null,\n failure: Record<string, unknown> | null,\n): string | null {\n return nonEmptyString(record(result?.tree)?.root) ?? nonEmptyString(failure?.runId)\n}\n\nfunction absentRuntimeSupervisorRun(\n runDir: string,\n resultText: string | null,\n failureText: string | null,\n instanceId: string | null,\n): SupervisorRunSources {\n const reason = `no Runtime spawn journal (${JOURNAL_FILE}) under ${runDir}`\n return {\n runRef: runDir,\n instanceId,\n arm: null,\n supRunDir: null,\n journal: null,\n journalMissingReason: reason,\n brainLog: null,\n brainLogMissingReason:\n 'Runtime FileRunContext records spend but not model completion finish reasons',\n state: null,\n progress: null,\n workers: null,\n workersMissingReason: reason,\n result: resultText,\n failure: failureText,\n judge: null,\n judgeSource: null,\n patch: null,\n driverLog: null,\n harnessWorkerTokens: null,\n harnessMissingReason: 'Runtime FileRunContext has no external worker-token join',\n limits: NO_SOURCE_LIMITS,\n rootTranscriptRef: null,\n rootWorkspaceCaptures: null,\n traceCommand: 'unavailable — Runtime FileRunContext records no provider-session trace identity',\n }\n}\n\n/**\n * Read one agent-runtime `createFileRunContext(dir)` directory.\n *\n * A run dir without `spawn-journal.jsonl` returns the same absent-shaped\n * sources the reader returns for a missing store: `journal` and\n * `workers` null, each with its reason, so every dependent metric reads\n * `unavailable` — never 0 and never a throw. Its `result.json` and\n * `failure.json` are still read, so a run that died before its first spawn\n * reports the failure Runtime recorded. Pass `strict: true` to throw on the\n * missing journal instead. A journal, result, or failure document that exists\n * but cannot be parsed always throws: a corrupt record is a defect, not an\n * absence.\n *\n * The reader translates storage envelopes only. It does not assign research\n * roles, interpret artifacts, or turn process completion into a quality\n * verdict.\n */\nexport async function readRuntimeSupervisorRun(\n runDir: string,\n opts: RuntimeReaderOptions = {},\n): Promise<SupervisorRunSources> {\n const read = opts.readFile ?? readFileText\n const journalPath = join(runDir, JOURNAL_FILE)\n const rawJournal =\n opts.strict === true ? await read(journalPath) : await readMaybe(journalPath, read)\n const resultPath = join(runDir, RESULT_FILE)\n const failurePath = join(runDir, FAILURE_FILE)\n const resultText = await readMaybe(resultPath, read)\n const failureText = await readMaybe(failurePath, read)\n const failure = parseOptionalRecord(failureText, failurePath)\n assertFailureRecord(failure, failurePath)\n const result = parseOptionalRecord(resultText, resultPath)\n if (rawJournal === null) {\n return absentRuntimeSupervisorRun(\n runDir,\n resultText,\n failureText,\n recordedRunId(result, failure),\n )\n }\n const normalized = parseEnvelopeJournal(rawJournal, journalPath)\n assertResultMatchesJournal(normalized.root, result, resultPath)\n\n const spawns = normalized.events.filter(\n (event) => event.kind === 'spawned' && nonEmptyString(event.id) !== null,\n )\n const childSpawns = spawns.filter((event) => event.id !== normalized.root)\n const workerIds = new Set(\n childSpawns.map((event) => nonEmptyString(event.id)).filter((id): id is string => id !== null),\n )\n const transcripts = await nodeTranscripts(\n runDir,\n normalized.events,\n new Set([normalized.root, ...workerIds]),\n read,\n { id: normalized.root, receipt: record(result?.rootHarnessTranscript) },\n )\n const workers: WorkerLogSource[] = childSpawns.map((event) => {\n const workerId = nonEmptyString(event.id) as string\n const transcript = transcripts.get(workerId)\n return {\n workerId,\n label: nonEmptyString(event.label) ?? String(event.id),\n events: null,\n inbox: null,\n patchBytes: null,\n transcriptRef: transcript?.transcriptRef ?? null,\n turns: transcript?.turns ?? { dispatched: 0, retained: 0 },\n nativeSession: transcript?.nativeSession ?? null,\n workspaceCaptures: transcript?.workspaceCaptures ?? null,\n patchPath: null,\n }\n })\n // Runtime appends every root provider event to the root stream as it arrives.\n const rootStream = join(runDir, ROOT_STREAM_FILE)\n\n return {\n runRef: runDir,\n instanceId: normalized.root,\n arm: null,\n supRunDir: runDir,\n journal: normalized.journal,\n brainLog: null,\n brainLogMissingReason:\n 'Runtime FileRunContext records spend but not model completion finish reasons',\n state: runtimeBeginState(normalized.root, normalized.startedAt),\n progress: null,\n workers,\n workersMissingReason: null,\n result: resultText,\n failure: failureText,\n judge: null,\n judgeSource: null,\n patch: null,\n driverLog: null,\n coordinationLog: await readCoordinationLog(runDir, read),\n harnessWorkerTokens: null,\n harnessMissingReason: 'Runtime FileRunContext has no external worker-token join',\n limits: sourceLimits(normalized.root, normalized.events, workerIds),\n rootTranscriptRef: (await isFile(rootStream)) ? rootStream : null,\n rootWorkspaceCaptures: transcripts.get(normalized.root)?.workspaceCaptures ?? null,\n traceCommand: nativeTraceSummary(workers, transcripts.get(normalized.root)),\n }\n}\n\n/**\n * True when a directory holds any file only Runtime's durable layer writes:\n * the spawn journal, the observer journal, or the failure record. A run that\n * threw before its first spawn has no journal yet and is still a Runtime run.\n */\nexport async function isRuntimeSupervisorRunDir(runDir: string): Promise<boolean> {\n for (const marker of RUNTIME_RUN_DIR_MARKERS) {\n if (await isFile(join(runDir, marker))) return true\n }\n return false\n}\n\nasync function isFile(path: string): Promise<boolean> {\n try {\n return (await stat(path)).isFile()\n } catch (error: unknown) {\n const code = error !== null && typeof error === 'object' && 'code' in error ? error.code : null\n if (code === 'ENOENT' || code === 'ENOTDIR') return false\n throw error\n }\n}\n","/**\n * Runtime supervisor-run reader and report writers.\n *\n * Runtime's file-backed supervision context is the only live on-disk contract.\n * Other stores implement `SupervisorRunReader` and feed the same pure analyzer;\n * this module owns path discovery and report output for Runtime runs.\n */\n\nimport { readdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { analyzeSupervisorRunSources } from './analyze'\n\nimport { isRuntimeSupervisorRunDir, readRuntimeSupervisorRun } from './runtime-reader'\nimport type { SupervisorRunReader, SupervisorRunReport, SupervisorRunSources } from './types'\n\n/**\n * Analyze a supervisor run. Accepts a Runtime run directory, any\n * `SupervisorRunReader`, or already-read source bytes — so a\n * caller with its own store never has to touch the filesystem layout.\n */\nexport async function analyzeSupervisorRun(\n input: string | SupervisorRunReader | SupervisorRunSources,\n): Promise<SupervisorRunReport> {\n if (typeof input === 'string') {\n return analyzeSupervisorRunSources(await readRuntimeSupervisorRun(input))\n }\n if (isReader(input)) return analyzeSupervisorRunSources(await input.read())\n return analyzeSupervisorRunSources(input)\n}\n\nfunction isReader(input: SupervisorRunReader | SupervisorRunSources): input is SupervisorRunReader {\n return typeof (input as SupervisorRunReader).read === 'function'\n}\n\nexport interface WriteSupervisorRunOptions {\n /** Append the headline block here (the experiment's run log). */\n readonly appendHeadlineTo?: string\n /** Also console.log the headline (default true). */\n readonly echo?: boolean\n /**\n * Write `run-report.{json,md}` here instead of into the run dir. Set when\n * reporting over a run directory that must stay READ-ONLY (a live run, an\n * archived generation).\n */\n readonly reportDir?: string\n}\n\n\n\n\n\n\n\n/**\n * Every Runtime supervisor run below `root`.\n *\n * When `root` itself is one run, return no children so callers can distinguish\n * a single report from a parent-directory rollup.\n */\nexport async function findSupervisorRunDirs(root: string): Promise<string[]> {\n if (await isRuntimeSupervisorRunDir(root)) {\n return []\n }\n const found: string[] = []\n const walk = async (dir: string, depth: number): Promise<void> => {\n if (depth > 8) return\n const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])\n for (const e of entries) {\n if (!e.isDirectory()) continue\n if (e.name === 'node_modules' || e.name === '.git') continue\n const full = join(dir, e.name)\n if (await isRuntimeSupervisorRunDir(full)) {\n found.push(full)\n continue\n }\n await walk(full, depth + 1)\n }\n }\n await walk(root, 0)\n return found.sort()\n}\n","/**\n * Human-readable renderings of a supervisor-run report. Zero and unavailable\n * render differently on purpose (`0` vs `unavailable — <reason>`), because the\n * two have driven opposite conclusions about the same architecture.\n */\n\nimport { roundDecimal as round } from '../math/round-decimal'\nimport {\n isUnavailable,\n type Measured,\n type ResourceSpendRecord,\n type SupervisorRunReport,\n type SupervisorRunRollup,\n showMeasured,\n type TerminalFailure,\n} from './types'\n\n/**\n * The block appended to a run log after every run — the answers an operator asks\n * for, in the log tail, with no extra command.\n */\nexport function renderSupervisorRunHeadline(r: SupervisorRunReport): string {\n const o = r.orchestration\n const steerNote = isUnavailable(o.steers)\n ? `unavailable — ${o.steers.unavailable}`\n : o.steers === 0\n ? '0 (spawn→wait→respawn only; no mid-task steering)'\n : `${o.steers} queued / ${showMeasured(o.steersDelivered)} delivered`\n return [\n `RUN-REPORT ${r.instanceId ?? '?'} [${r.arm ?? '?'}]`,\n ` status=${showMeasured(r.outcome.supStatus)} source=${showMeasured(r.outcome.supStatusSource)}` +\n ` reason=${showMeasured(r.outcome.supReason)} failure=${fmtFailure(r.outcome.failure)}`,\n ` steers=${steerNote}`,\n ` waves=${showMeasured(o.waves)} sizes=${isUnavailable(o.waveSizes) ? `unavailable — ${o.waveSizes.unavailable}` : `[${o.waveSizes.join(',')}]`}` +\n ` workers=${showMeasured(o.workersSpawned)} settled=${showMeasured(o.workersSettled)} cancelled=${showMeasured(o.workersCancelled)}`,\n ` concurrency max=${showMeasured(o.maxConcurrency)} utilization=${showMeasured(o.workerUtilization)}` +\n ` idle=${fmtMs(o.idleMs)} (${showMeasured(o.idlePct)}%) wall=${fmtMs(o.supervisorWallMs)}` +\n `${o.supervisorWallSource === 'journal-span' ? ' (journal-span lower bound)' : ''}`,\n ` respawns=${showMeasured(o.respawns)} evidence→respawn=${showMeasured(r.decision.observeThenRespawn)}` +\n ` blind-respawn=${showMeasured(r.decision.respawnWithoutEvidence)} depth=${showMeasured(o.delegationDepth)}`,\n ` accepted=${showMeasured(r.decision.accepted)} rejected=${showMeasured(r.decision.rejected)} empty-pass=${showMeasured(r.decision.emptyPass)}`,\n ` brain=$${showMeasured(r.economics.brain.usd)} total=$${showMeasured(r.economics.totalUsd)}` +\n ` judge.resolved=${showMeasured(r.outcome.judgeResolved)} score=${showMeasured(r.outcome.judgeScore)}` +\n ` verify=${showMeasured(r.outcome.verifyPass)}`,\n r.gaps.length > 0 ? ` gaps(${r.gaps.length}): ${r.gaps.join('; ')}` : ' gaps: none',\n ].join('\\n')\n}\n\n/**\n * The recorded error on one line; `none recorded` and `unavailable` stay\n * distinct, and a throw the run outlived is labeled so it is not read as the\n * outcome of the settled result beside it.\n */\nfunction fmtFailure(v: Measured<TerminalFailure | null>): string {\n if (isUnavailable(v)) return `unavailable — ${v.unavailable}`\n if (v === null) return 'none recorded'\n const name = v.name ?? 'unavailable — record has no error.name'\n const message = v.message ?? 'unavailable — record has no error.message'\n const attempt = v.earlierAttempt ? ', earlier attempt' : ''\n return `${name}: ${message} [${v.source}${v.at === null ? '' : ` at ${v.at}`}${attempt}]`\n}\n\nfunction resourceRows(records: Measured<readonly ResourceSpendRecord[]>): string[] {\n if (isUnavailable(records)) return [`unavailable — ${records.unavailable}`, '']\n const out = [\n 'Receipts are source records, not additive totals.',\n 'A false completeness flag means the amount is a recorded subtotal, not complete usage.',\n '',\n '| Node | Source | Resource | Unit | Amount | Known |',\n '|---|---|---|---|---:|---|',\n ]\n const cell = (value: string) => value.replace(/\\|/g, '\\\\|').replace(/\\r?\\n/g, ' ')\n for (const record of records) {\n const prefix = `| ${cell(record.nodeId ?? 'unavailable')} | ${cell(record.source)} |`\n if (isUnavailable(record.resources)) {\n out.push(`${prefix} ${cell(showMeasured(record.resources))} | — | — | — |`)\n } else if (record.resources.length === 0) {\n out.push(`${prefix} recorded empty map | — | — | — |`)\n } else {\n for (const receipt of record.resources) {\n out.push(\n `${prefix} ${cell(showMeasured(receipt.name))} | ${cell(showMeasured(receipt.unit))} | ${cell(showMeasured(receipt.amount))} | ${cell(showMeasured(receipt.known))} |`,\n )\n }\n }\n }\n if (!records.length) out.push('| — | — | no spend records | — | — | — |')\n out.push('')\n return out\n}\n\nfunction fmtMs(v: Measured<number>): string {\n if (isUnavailable(v)) return `unavailable — ${v.unavailable}`\n if (v < 1000) return `${v}ms`\n const s = v / 1000\n if (s < 120) return `${round(s, 1)}s`\n return `${round(s / 60, 1)}min`\n}\n\nexport function renderSupervisorRunMarkdown(r: SupervisorRunReport): string {\n const o = r.orchestration\n const d = r.decision\n const e = r.economics\n const out: string[] = []\n out.push(`# Run report — ${r.instanceId ?? 'unknown instance'} [${r.arm ?? 'unknown arm'}]`)\n out.push('')\n out.push('```')\n out.push(renderSupervisorRunHeadline(r))\n out.push('```')\n out.push('')\n out.push(`- Run: \\`${r.runRef}\\``)\n out.push(`- Supervisor: \\`${showMeasured(r.supervisorId)}\\``)\n out.push(`- Supervisor profile: \\`${showMeasured(r.supervisorProfileDigest)}\\``)\n out.push(`- Generated: ${r.generatedAt}`)\n out.push('')\n\n out.push('## Orchestration')\n out.push('')\n out.push('| Metric | Value |')\n out.push('|---|---|')\n out.push(`| Workers spawned | ${showMeasured(o.workersSpawned)} |`)\n out.push(`| Workers settled | ${showMeasured(o.workersSettled)} |`)\n out.push(`| Workers cancelled | ${showMeasured(o.workersCancelled)} |`)\n out.push(`| **Steers (mid-task messages to live workers)** | **${showMeasured(o.steers)}** |`)\n out.push(`| Steers delivered | ${showMeasured(o.steersDelivered)} |`)\n out.push(`| Outer-driver \\`supervisor_steer\\` calls | ${showMeasured(o.driverSteerCalls)} |`)\n out.push(`| Spawn waves | ${showMeasured(o.waves)} |`)\n out.push(\n `| Wave sizes | ${isUnavailable(o.waveSizes) ? showMeasured(o.waveSizes) : `[${o.waveSizes.join(', ')}]`} |`,\n )\n out.push(`| Max concurrency | ${showMeasured(o.maxConcurrency)} |`)\n out.push(`| Respawns (after same parent's first settle) | ${showMeasured(o.respawns)} |`)\n out.push(\n `| Repeated labels | ${isUnavailable(o.repeatedLabels) ? showMeasured(o.repeatedLabels) : o.repeatedLabels.length === 0 ? 'none' : o.repeatedLabels.join(', ')} |`,\n )\n out.push(`| Delegation depth | ${showMeasured(o.delegationDepth)} |`)\n out.push(`| Time to first spawn | ${fmtMs(o.timeToFirstSpawnMs)} |`)\n out.push(\n `| Supervisor wall | ${fmtMs(o.supervisorWallMs)}${isUnavailable(o.supervisorWallSource) ? '' : ` (source: ${o.supervisorWallSource}${o.supervisorWallSource === 'journal-span' ? ', lower bound' : ''})`} |`,\n )\n out.push(`| Idle (zero live workers) | ${fmtMs(o.idleMs)} (${showMeasured(o.idlePct)}%) |`)\n out.push(\n `| Worker utilization (Σ worker wall ÷ supervisor wall) | ${showMeasured(o.workerUtilization)} |`,\n )\n out.push('')\n\n if (!isUnavailable(o.steersByWorker) && o.steersByWorker.length > 0) {\n out.push('### Steers per worker')\n out.push('')\n out.push('| Worker id | Label | Queued | Delivered |')\n out.push('|---|---|---:|---:|')\n for (const s of o.steersByWorker) {\n out.push(\n `| ${s.workerId === null ? 'unavailable — worker id absent; label join used' : `\\`${s.workerId}\\``} | \\`${s.worker}\\` | ${s.queued} | ${s.delivered} |`,\n )\n }\n out.push('')\n } else if (isUnavailable(o.steersByWorker)) {\n out.push(`### Steers per worker\\n\\nunavailable — ${o.steersByWorker.unavailable}\\n`)\n }\n\n out.push('## Decision quality')\n out.push('')\n out.push('| Metric | Value |')\n out.push('|---|---|')\n out.push(`| Settled by status | ${fmtCounts(d.settledByStatus)} |`)\n out.push(`| Settled verdicts | ${fmtCounts(d.settledVerdicts)} |`)\n out.push(`| Accepted (verify green + patch bytes) | ${showMeasured(d.accepted)} |`)\n out.push(`| Rejected (verify red) | ${showMeasured(d.rejected)} |`)\n out.push(`| Empty pass (green, no patch) | ${showMeasured(d.emptyPass)} |`)\n out.push(`| Evidence → respawn sequences | ${showMeasured(d.observeThenRespawn)} |`)\n out.push(\n `| Respawn with no same-parent settled evidence in front | ${showMeasured(d.respawnWithoutEvidence)} |`,\n )\n out.push(`| Review actions (steers + worker questions) | ${showMeasured(d.reviewActions)} |`)\n out.push(\n `| Worker evidence returned | ${isUnavailable(d.workerEvidenceBytes) ? showMeasured(d.workerEvidenceBytes) : `${d.workerEvidenceBytes} bytes`} |`,\n )\n out.push('')\n\n out.push('## Economics')\n out.push('')\n out.push('| Role | Tokens in | Tokens out | Cache read | Cache write | USD | Source |')\n out.push('|---|---:|---:|---:|---:|---:|---|')\n out.push(\n `| brain | ${showMeasured(e.brain.tokensIn)} | ${showMeasured(e.brain.tokensOut)} | ${showMeasured(e.brain.cacheRead)} | ${showMeasured(e.brain.cacheWrite)} | ${showMeasured(e.brain.usd)} | ${e.brain.source} |`,\n )\n out.push(\n `| workers | ${showMeasured(e.workers.tokensIn)} | ${showMeasured(e.workers.tokensOut)} | ${showMeasured(e.workers.cacheRead)} | ${showMeasured(e.workers.cacheWrite)} | ${showMeasured(e.workers.usd)} | ${e.workers.source} |`,\n )\n out.push('')\n if (!isUnavailable(e.brainTruncations) && e.brainTruncations > 0) {\n out.push(\n `- **BRAIN OUTPUT TRUNCATED: ${e.brainTruncations} completion(s) hit \\`finish_reason: \"length\"\\`** — the supervisor ` +\n 'acted on a half-written plan. Its output ceiling is too low; see `brain.jsonl` for the per-call `req_max_tokens`.',\n )\n } else {\n out.push(\n `- Brain completions truncated (finish_reason=length): ${showMeasured(e.brainTruncations)}`,\n )\n }\n out.push(`- Total USD: ${showMeasured(e.totalUsd)} (source: ${e.totalUsdSource})`)\n out.push(\n `- Spend measured two ways: journal-derived $${showMeasured(e.spend.journalDerived.usd)} over ${e.spend.journalDerived.records} journal record(s) (execution accounting) · ` +\n `close-record $${showMeasured(e.spend.closeRecord.usd)} over ${e.spend.closeRecord.records} close record(s) (billing-shaped). Divergence is a signal, not an error.`,\n )\n out.push(`- Cost per accepted patch: ${showMeasured(e.costPerAcceptedPatchUsd)}`)\n if (isUnavailable(e.workerWallMsDistribution)) {\n out.push(`- Worker wall distribution: unavailable — ${e.workerWallMsDistribution.unavailable}`)\n } else {\n const w = e.workerWallMsDistribution\n out.push(\n `- Worker wall (n=${w.n}): min ${fmtMs(w.min)} / p50 ${fmtMs(w.p50)} / p90 ${fmtMs(w.p90)} / max ${fmtMs(w.max)} / Σ ${fmtMs(w.sum)}`,\n )\n }\n out.push('')\n if (!isUnavailable(e.perWorker) && e.perWorker.length > 0) {\n out.push(\n '| Worker id | Label | Role | Runtime | Profile digest | Status | Failure | Infra | Wall | Tokens in | Tokens out | Patch bytes | Verify passed | Score |',\n )\n out.push('|---|---|---|---|---|---|---|---|---:|---:|---:|---:|---|---:|')\n for (const w of e.perWorker) {\n out.push(\n `| ${w.workerId === null ? 'unavailable — worker id absent; label join used' : `\\`${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'} |`,\n )\n }\n out.push('')\n }\n\n if (e.resourceRecords !== undefined) {\n out.push('## Named resource receipts', '', ...resourceRows(e.resourceRecords))\n }\n\n out.push('## Outcome')\n out.push('')\n out.push('| Metric | Value |')\n out.push('|---|---|')\n out.push(`| Supervisor status | ${showMeasured(r.outcome.supStatus)} |`)\n out.push(`| Status source | ${showMeasured(r.outcome.supStatusSource)} |`)\n out.push(`| Terminal reason | ${showMeasured(r.outcome.supReason)} |`)\n out.push(`| Failure | ${fmtFailure(r.outcome.failure)} |`)\n out.push(`| Supervisor verdict | ${showMeasured(r.outcome.supVerdict)} |`)\n out.push(`| Delivered | ${showMeasured(r.outcome.delivered)} |`)\n out.push(`| Judge resolved | ${showMeasured(r.outcome.judgeResolved)} |`)\n out.push(`| Judge score | ${showMeasured(r.outcome.judgeScore)} |`)\n out.push(\n `| Judge passed / total | ${showMeasured(r.outcome.judgePassed)} / ${showMeasured(r.outcome.judgeTotal)} |`,\n )\n out.push(\n `| Judge source | ${r.outcome.judgeSource ?? 'unavailable — no judge.json and no ledger row'} |`,\n )\n out.push(\n `| Verify gate | pass=${showMeasured(r.outcome.verifyPass)} rc=${showMeasured(r.outcome.verifyRc)} |`,\n )\n if (isUnavailable(r.outcome.patch)) {\n out.push(`| Patch | unavailable — ${r.outcome.patch.unavailable} |`)\n } else {\n const p = r.outcome.patch\n out.push(\n `| Patch | ${p.files} file(s), +${p.linesAdded}/-${p.linesRemoved}, test files touched: ${p.testFilesTouched.length === 0 ? 'none' : p.testFilesTouched.join(', ')} |`,\n )\n }\n out.push('')\n out.push('## Gaps')\n out.push('')\n if (r.gaps.length === 0) out.push('None — every metric above is backed by a present artifact.')\n else for (const g of r.gaps) out.push(`- ${g}`)\n out.push('')\n out.push(\n `> Harness-session view of the same run (model calls, stuck loops, tool errors): \\`${r.traceCommand}\\``,\n )\n out.push('')\n return out.join('\\n')\n}\n\nfunction fmtCounts(v: Measured<Record<string, number>>): string {\n if (isUnavailable(v)) return showMeasured(v as unknown as Measured<string>)\n const entries = Object.entries(v)\n return entries.length === 0 ? 'none' : entries.map(([k, n]) => `${k}=${n}`).join(', ')\n}\n\nexport function renderSupervisorRollupMarkdown(\n rollup: SupervisorRunRollup,\n title = 'Round rollup',\n): string {\n const out: string[] = []\n out.push(`# ${title}`)\n out.push('')\n out.push(`- Cells: ${rollup.cells}`)\n out.push(\n `- **Steers across all cells: ${showMeasured(rollup.steersTotal)}** (cells with ≥1 steer: ${showMeasured(rollup.cellsWithSteers)}; cells where the steer count is unavailable: ${rollup.cellsWithUnavailableSteers})`,\n )\n out.push(`- Waves per cell (mean): ${showMeasured(rollup.wavesMean)}`)\n out.push(`- Max concurrency observed: ${showMeasured(rollup.maxConcurrencyMax)}`)\n out.push(`- Worker utilization (mean): ${showMeasured(rollup.utilizationMean)}`)\n out.push(`- Idle share (mean): ${showMeasured(rollup.idlePctMean)}%`)\n out.push(\n `- Workers spawned: ${showMeasured(rollup.workersSpawnedTotal)} · accepted: ${showMeasured(rollup.acceptedTotal)}`,\n )\n out.push(\n `- Spend: $${showMeasured(rollup.usdTotal)} · judged resolved: ${showMeasured(rollup.resolvedCount)}/${rollup.cells}`,\n )\n out.push(\n `- Spend measured two ways: journal-derived $${showMeasured(rollup.spendUsd.journalDerived.value)} over ${rollup.spendUsd.journalDerived.runs}/${rollup.cells} runs (execution accounting) · ` +\n `close-record $${showMeasured(rollup.spendUsd.closeRecord.value)} over ${rollup.spendUsd.closeRecord.runs}/${rollup.cells} runs (billing-shaped)`,\n )\n out.push('')\n out.push('| Instance | Arm | Steers | Waves | Utilization | Idle % | Resolved | USD |')\n out.push('|---|---|---:|---:|---:|---:|---|---:|')\n for (const c of rollup.perCell) {\n out.push(\n `| ${c.instanceId ?? '?'} | ${c.arm ?? '?'} | ${showMeasured(c.steers)} | ${showMeasured(c.waves)} | ${showMeasured(c.utilization)} | ${showMeasured(c.idlePct)} | ${showMeasured(c.resolved)} | ${showMeasured(c.usd)} |`,\n )\n }\n out.push('')\n for (const cell of rollup.perCell) {\n if (cell.resourceRecords !== undefined) {\n out.push(\n `## Resource receipts — ${cell.instanceId ?? '?'} [${cell.arm ?? '?'}]`,\n '',\n ...resourceRows(cell.resourceRecords),\n )\n }\n }\n return out.join('\\n')\n}\n","/**\n * A Runtime run directory as `tangle.rollout.v1` rows: the supervision tree\n * `supervisorRunRolloutLines` mints, with each node's whole episode.\n *\n * - Producer: each node's `materialized` receipt names the model it ran on\n * (`opencode/zai-coding-plan/glm-5.3` → harness, provider, model), and the\n * root's `root-segment` names the root's. The license class follows.\n * - Episode: each execution's input (`execution-input.taskRef`) and result\n * (`execution-result.outRef`, a `{content, events}` blob), read as Sandbox\n * sessions in order, so a node steered twice keeps both turns and every tool\n * call. A node with no event stream stays a lossy projection.\n * - A node respawned under the same id (a reopened run) is one row.\n * - Reward: the caller's `RunVerdict` on the root row. The caller owns what\n * its check means; this reader owns how a reward is screened and when a\n * stopped episode is whole.\n *\n * Every read is of files Runtime already wrote; nothing in the run dir is changed.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { basename, join } from 'node:path'\nimport type { HarnessSession } from '@tangle-network/harness-sessions'\nimport { sandboxEventsSession, toChatMessages, toOtlpSpans } from '@tangle-network/harness-sessions'\nimport { licenseClassOfName } from '../rollout/license'\nimport { screenedRewardFields, unscreenedRewardFields } from '../rollout/reward'\nimport type { RolloutLine } from '../rollout/schema'\nimport { expandJournalEventGroup } from './journal-event-group'\nimport { supervisorRunRolloutLinesFromFacts } from './rollout-nodes'\nimport { readRuntimeSupervisorRun } from './runtime-reader'\nimport { parseJsonl, parseSupervisorTree, recordOrNull as record } from './source-facts'\nimport type { SupervisorRunTreeGap } from './types'\n\ninterface NodeFacts {\n model?: string\n taskRef?: string\n outRef?: string\n /** The node's newest input, which the next result answers. */\n inputRef?: string\n unansweredSince?: string\n executions?: Array<{ taskRef?: string; outRef: string }>\n}\n\n/** `opencode/zai-coding-plan/glm-5.3` → harness, provider, model. */\nfunction producerOf(id: string): Record<'harness' | 'provider' | 'model', string | null> {\n const parts = id.split('/')\n if (parts.length >= 3) {\n return { harness: parts[0]!, provider: parts[1]!, model: parts.slice(2).join('/') }\n }\n if (parts.length === 2) return { harness: null, provider: parts[0]!, model: parts[1]! }\n return { harness: null, provider: null, model: id }\n}\n\n/** A row holding the agent's whole stream is no longer lossy; a workspace capture gap still stands. */\nfunction wholeEpisode({ lossy_projection: _, gap, ...kept }: RolloutLine['provenance']) {\n const workspace = gap?.match(/workspace capture evidence \\w+/u)?.[0]\n return workspace === undefined ? kept : { ...kept, gap: workspace }\n}\n\nconst text = (v: unknown): string | undefined =>\n typeof v === 'string' && v.length > 0 ? v : undefined\n\nasync function journalFacts(runDir: string): Promise<Map<string, NodeFacts>> {\n const facts = new Map<string, NodeFacts>()\n const raw = await readFile(join(runDir, 'spawn-journal.jsonl'), 'utf8').catch(() => '')\n const node = (id: string): NodeFacts => {\n const fact = facts.get(id) ?? {}\n facts.set(id, fact)\n return fact\n }\n for (const row of parseJsonl(raw)) {\n const expanded = expandJournalEventGroup(row)\n if (!expanded.succeeded) continue\n for (const entry of expanded.value) {\n const event = record(entry.event)\n const id = text(event?.id)\n if (event === null || id === undefined) continue\n if (event.kind === 'spawned') {\n node(id).taskRef ??= text(record(event.identity)?.taskDigest)\n } else if (event.kind === 'materialized') {\n const model = record(record(event.receipt)?.model)\n if (model?.status === 'known' && text(model.id)) node(id).model = text(model.id)\n } else if (event.kind === 'root-segment') {\n const to = record(event.to)\n const model = text(to?.model)\n if (model) node(id).model = [text(to?.harness), text(to?.provider), model].join('/')\n } else if (event.kind === 'settled' && text(event.outRef)) {\n node(id).outRef = text(event.outRef)\n } else if (event.kind === 'execution-input') {\n const fact = node(id)\n fact.inputRef = text(event.taskRef)\n fact.unansweredSince ??= text(event.at)\n } else if (event.kind === 'execution-result' && text(event.outRef)) {\n const fact = node(id)\n fact.unansweredSince = undefined\n const taskRef = fact.inputRef ?? fact.taskRef\n ;(fact.executions ??= []).push({ taskRef, outRef: event.outRef as string })\n }\n }\n }\n return facts\n}\n\nconst readJson = (path: string): Promise<unknown> =>\n readFile(path, 'utf8').then(JSON.parse).catch(() => undefined)\n\nasync function blobValue(runDir: string, ref: string | undefined): Promise<unknown> {\n if (ref === undefined || !/^sha256:[0-9a-f]{64}$/u.test(ref)) return undefined\n return readJson(join(runDir, 'blobs', `${ref.replace(':', '-')}.json`))\n}\n\n/** One Sandbox session per execution, oldest first; older runs keep only the settled result. */\nasync function nodeSessions(runDir: string, harness: string, id: string, fact: NodeFacts) {\n const executions = fact.executions ?? [{ taskRef: fact.taskRef, outRef: fact.outRef }]\n const sessions: HarnessSession[] = []\n for (const [index, { taskRef, outRef }] of executions.entries()) {\n const [input, result] = await Promise.all([blobValue(runDir, taskRef), blobValue(runDir, outRef)])\n const task = text(input) ?? text(record(input)?.prompt) ?? text(record(input)?.instruction)\n const answer = text(result) ?? text(record(result)?.content)\n const stream = record(result)?.events\n const events = Array.isArray(stream) ? stream : []\n if (task === undefined || (answer === undefined && events.length === 0)) continue\n const nativeSessionId = `${id}:${index}`\n sessions.push(sandboxEventsSession({ harness, nativeSessionId, task, answer: answer ?? '', events }))\n }\n return sessions\n}\n\n/** A caller's verdict on a run, applied to its root row. */\nexport interface RunVerdict {\n /** In [0, 1]; 1 is full success. */\n reward: number\n /** The check behind the reward was validated (a fixture that must fail it did). */\n screened: boolean\n /** An independent review contradicted the reward, so it trains nothing. */\n gated?: boolean\n /** Who produced the reward, such as `my-suite/check`. */\n source: string\n /** When a controller stopped the run on this verdict. */\n stoppedAt?: string\n at?: string\n commit?: string | null\n detail?: string\n}\n\n/**\n * The root's outcome under the caller's verdict. A run stopped on its success reads `cancelled`;\n * its episode is whole if no input was pending when it was stopped.\n */\nfunction judged(node: RolloutLine, verdict: RunVerdict | null, pending: string | undefined) {\n if (verdict === null || node.parent_rollout_id !== null) return node.outcome\n const { reward, screened, gated = false, source, stoppedAt = '', commit = null } = verdict\n const ended = reward === 1 && !gated && (!pending || Date.parse(stoppedAt) <= Date.parse(pending))\n return {\n ...node.outcome,\n ...(screened || gated ? screenedRewardFields(reward, gated) : unscreenedRewardFields(reward)),\n ...(ended ? { is_completed: true, error: null } : {}),\n reward_source: source,\n verdict: { at: verdict.at ?? '', commit, detail: (verdict.detail ?? '').slice(0, 500) },\n }\n}\n\nexport interface RuntimeRunRollouts {\n runDir: string\n lines: RolloutLine[]\n gaps: SupervisorRunTreeGap[]\n /** Each row's session as OTLP-JSONL, by rollout id. */\n otlp: Map<string, string>\n}\n\n/** Read one Runtime run directory into rollout rows; `suite` defaults to `runtime/<run>`. */\nexport async function runtimeRunRolloutLines(\n runDir: string,\n options: { suite?: string; capturedAt?: string; verdict?: RunVerdict | null } = {},\n): Promise<RuntimeRunRollouts> {\n const verdict = options.verdict ?? null\n const src = await readRuntimeSupervisorRun(runDir)\n const facts0 = parseSupervisorTree(src)\n const seen = new Set<string>()\n const workerSpawns = facts0.workerSpawns.filter(\n (spawn) => !seen.has(spawn.id) && seen.add(spawn.id),\n )\n const tree = supervisorRunRolloutLinesFromFacts(\n src,\n { ...facts0, workerSpawns },\n {\n suite: options.suite ?? `runtime/${basename(runDir)}`,\n runId: basename(runDir),\n ...(options.capturedAt === undefined ? {} : { capturedAt: options.capturedAt }),\n },\n )\n const facts = await journalFacts(runDir)\n const lines: RolloutLine[] = []\n const otlp = new Map<string, string>()\n for (const node of tree.nodes) {\n const fact = facts.get(node.rollout_id) ?? {}\n const producer = fact.model === undefined ? null : producerOf(fact.model)\n const license = licenseClassOfName(producer?.model) ?? licenseClassOfName(producer?.harness)\n const harness = producer?.harness ?? node.policy.harness ?? 'sandbox'\n const sessions = await nodeSessions(runDir, harness, node.rollout_id, fact)\n const messages = sessions.flatMap((session) => toChatMessages(session))\n // A session with no stream has only its root span, which `traces` rightly calls unread.\n const spans = sessions.map((session) => toOtlpSpans(session)).filter((s) => s.length > 1).flat()\n otlp.set(node.rollout_id, spans.map((span) => `${JSON.stringify(span)}\\n`).join(''))\n lines.push({\n ...node,\n policy: {\n ...node.policy,\n ...(producer === null\n ? {}\n : {\n harness: producer.harness ?? node.policy.harness,\n provider: producer.provider,\n model: producer.model,\n }),\n ...(license === null ? {} : { license_class: license }),\n },\n messages: sessions.length === 0 ? node.messages : messages,\n provenance: messages.some((m) => m.role === 'tool') ? wholeEpisode(node.provenance) : node.provenance,\n outcome: judged(node, verdict, fact.unansweredSince),\n })\n }\n // The verdict is the root's reward, so the tree's \"no judge verdict\" gap no longer holds.\n const gaps = tree.gaps.filter((gap) => verdict === null || gap.code !== 'root-reward-unavailable')\n return { runDir, lines, gaps, otlp }\n}\n"],"mappings":";;;;;;;;;;;AAKA,SAAgB,eAAe,KAA2B;CACxD,MAAM,OAAiB,CAAC;CACxB,MAAM,OAAO,MAAc,WAAgC;EACzD,KAAK,KAAK,GAAG,KAAK,IAAI,QAAQ;EAC9B,OAAO,YAAY,MAAM;CAC3B;CAEA,MAAM,iBACJ,IAAI,yBACH,IAAI,cAAc,OAAO,wCAAwC;CACpE,MAAM,cAAc,IAAI,YAAY;CACpC,MAAM,OAA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