@tangle-network/agent-eval 0.174.0 → 0.175.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +1 -1
  3. package/dist/analyst/index.d.ts +2 -2
  4. package/dist/analyst/index.js +2 -2
  5. package/dist/{benchmark-command-mZIlR-ra.js → benchmark-command-D_5xG9LG.js} +2 -2
  6. package/dist/{benchmark-command-mZIlR-ra.js.map → benchmark-command-D_5xG9LG.js.map} +1 -1
  7. package/dist/{opencode-sqlite-eK6HW6dr.js → claude-jsonl-CxZZrDJ3.js} +9 -149
  8. package/dist/claude-jsonl-CxZZrDJ3.js.map +1 -0
  9. package/dist/cli.js +9 -2
  10. package/dist/cli.js.map +1 -1
  11. package/dist/contract/index.js +1 -1
  12. package/dist/{default-registry-CrAp0pYq.js → default-registry-DBqVI4pq.js} +2 -2
  13. package/dist/{default-registry-CrAp0pYq.js.map → default-registry-DBqVI4pq.js.map} +1 -1
  14. package/dist/{index-Bn-nlnSV.d.ts → index-BAAiSF3_.d.ts} +2 -2
  15. package/dist/{index-Bn-nlnSV.d.ts.map → index-BAAiSF3_.d.ts.map} +1 -1
  16. package/dist/index.d.ts +1 -1
  17. package/dist/index.js +2 -2
  18. package/dist/{integrity-BWywb34E.js → integrity-DsHWCebQ.js} +11 -435
  19. package/dist/integrity-DsHWCebQ.js.map +1 -0
  20. package/dist/openapi.json +1 -1
  21. package/dist/opencode-sqlite-CNw3vubS.js +145 -0
  22. package/dist/opencode-sqlite-CNw3vubS.js.map +1 -0
  23. package/dist/report-command-DKlXfU5r.js +1528 -0
  24. package/dist/report-command-DKlXfU5r.js.map +1 -0
  25. package/dist/rollout/index.js +3 -2
  26. package/dist/{rollout-C-znbbYg.js → rollout-CGlDq1GI.js} +3 -2
  27. package/dist/{rollout-C-znbbYg.js.map → rollout-CGlDq1GI.js.map} +1 -1
  28. package/dist/supervisor-run/index.d.ts +71 -6
  29. package/dist/supervisor-run/index.d.ts.map +1 -1
  30. package/dist/supervisor-run/index.js +6 -1357
  31. package/dist/supervisor-run/index.js.map +1 -1
  32. package/dist/terminal-record-Ce9_UjRz.js +539 -0
  33. package/dist/terminal-record-Ce9_UjRz.js.map +1 -0
  34. package/dist/{types-CoPUTiXb.d.ts → types-vUdAx2Cj.d.ts} +65 -3
  35. package/dist/types-vUdAx2Cj.d.ts.map +1 -0
  36. package/package.json +1 -1
  37. package/dist/integrity-BWywb34E.js.map +0 -1
  38. package/dist/opencode-sqlite-eK6HW6dr.js.map +0 -1
  39. package/dist/types-CoPUTiXb.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["readMaybe"],"sources":["../../src/supervisor-run/types.ts","../../src/supervisor-run/analyze.ts","../../src/supervisor-run/claude-code-reader.ts","../../src/supervisor-run/render.ts","../../src/supervisor-run/runtime-reader.ts","../../src/supervisor-run/loops-reader.ts"],"sourcesContent":["/**\n * Supervisor-run analysis — the multi-agent analogue of single-rollout trace\n * analysis. A solo rollout is one invocation with a transcript; a supervisor\n * run is a TREE of invocations (a brain that spawns, steers, and settles\n * workers) plus the event timeline that connects them. `src/trace-analyst`\n * answers \"what happened inside one session\"; this module answers \"what did\n * the tree do\" — did the brain steer anyone mid-task, how many spawn waves,\n * how concurrent, how idle, what did each role cost, what came back.\n *\n * The nodes of that tree are NOT a new shape: they are `tangle.rollout.v1`\n * rows (`src/rollout`), keyed by `parent_rollout_id`, with `role` already\n * spanning `supervisor` / `worker`. `supervisorRunRolloutLines` mints them.\n * What rollout rows deliberately do NOT carry is the inter-invocation event\n * timeline (spawn/settle/steer instants), which is what every structural\n * metric here is computed from — so the reader consumes the journal event\n * stream and emits rollout rows, rather than maintaining a parallel node type.\n *\n * ## UNAVAILABLE ≠ ZERO\n *\n * Every metric whose backing artifact can be missing is typed\n * `Measured<T> = T | { unavailable: reason }`. A supervisor that steered\n * nobody reports `steers: 0`; a supervisor whose worker logs were never\n * written reports `steers: unavailable — <reason>`. The two have driven\n * opposite conclusions about the same architecture, so they never collapse.\n */\n\nimport type { RolloutLine } from '../rollout/schema'\nimport type { SeriesDistribution } from '../statistics'\n\n// ---------------------------------------------------------------------------\n// Unavailable-aware metric type.\n// ---------------------------------------------------------------------------\n\n/** A metric that could not be computed, with the reason its artifact was missing. */\nexport interface Unavailable {\n readonly unavailable: string\n}\n\n/** A metric value, or the reason it is unknown. NEVER collapse `unavailable` to 0. */\nexport type Measured<T> = T | Unavailable\n\nexport function unavailable(reason: string): Unavailable {\n return { unavailable: reason }\n}\n\nexport function isUnavailable(v: unknown): v is Unavailable {\n return typeof v === 'object' && v !== null && typeof (v as Unavailable).unavailable === 'string'\n}\n\n/** Render a measured scalar for the markdown/headline: `0` and `unavailable` stay distinct. */\nexport function showMeasured(v: Measured<number | string | boolean | null>): string {\n if (isUnavailable(v)) return `unavailable — ${v.unavailable}`\n if (v === null) return 'null'\n return String(v)\n}\n\n// ---------------------------------------------------------------------------\n// Source contract — deliberately source-agnostic.\n// ---------------------------------------------------------------------------\n\n/** The two invocation roles a recursive supervision tree can contain. */\nexport type SupervisorRunNodeRole = 'supervisor' | 'worker'\n\n/**\n * One worker's logs, as read. `null` means the artifact did not exist; `''`\n * means the artifact was captured and contained no rows.\n */\nexport interface WorkerLogSource {\n /**\n * Stable journal node id. Readers should set this whenever their source has\n * one; `label` remains the compatibility join for older stores.\n */\n readonly workerId?: string\n /** Human-readable task label. It is not required to be unique. */\n readonly label: string\n /** Worker event stream — started / progress / finished / message events (JSONL). */\n readonly events: string | null\n /** The durable steer queue — one line per steer request (JSONL). */\n readonly inbox: string | null\n /** Worker patch byte length, or null when absent. */\n readonly patchBytes: number | null\n /** Where this worker's transcript lives, for the rollout row. Null = no such artifact. */\n readonly transcriptRef?: string | null\n /** Where this worker's delivered patch lives. Null = the store keeps no patch per worker. */\n readonly patchPath?: string | null\n /** This worker's own inference tokens, when the store records them per worker. */\n readonly tokensIn?: number | null\n readonly tokensOut?: number | null\n readonly cacheRead?: number | null\n readonly cacheWrite?: number | null\n}\n\n/**\n * Facts a SOURCE structurally cannot express, each with the reason.\n *\n * The difference between \"the artifact is missing\" and \"this store never\n * records that fact\" is the difference between a run that spent $0 and a\n * harness that does not price inference — and the second harness is where a\n * loops-shaped assumption becomes a fabricated zero. A reader declares its\n * limits once; the analyzer reports `unavailable` for everything downstream.\n *\n * `null` on a field means the source DOES carry that fact.\n */\nexport interface SourceLimits {\n /** Reason manager input/output token totals are unavailable (null = recorded). */\n readonly managerTokens: string | null\n /** Reason worker input/output token totals are unavailable (null = recorded). */\n readonly workerTokens: string | null\n /** Reason inference spend has no price in this store (null = the store prices it). */\n readonly spendUsd: string | null\n /** Reason workers carry no pass/fail verdict (null = verdicts are recorded). */\n readonly workerVerdicts: string | null\n /** Reason no delivered artifact (patch/diff) is retained per worker (null = retained). */\n readonly deliverables: string | null\n}\n\n/** A source that carries every fact the analyzer can use. */\nexport const NO_SOURCE_LIMITS: SourceLimits = {\n managerTokens: null,\n workerTokens: null,\n spendUsd: null,\n workerVerdicts: null,\n deliverables: null,\n}\n\n/**\n * Everything the pure analyzer reads — already-read bytes, never paths. Each\n * field is `null` when its artifact was absent, which is what turns the\n * dependent metrics into `unavailable` rather than 0.\n *\n * This is the whole input contract. Any store that can produce these strings\n * (an on-disk loops run, an object-store archive, a database, a test fixture)\n * is a valid source; `loopsSupervisorRunReader` is ONE implementation.\n */\nexport interface SupervisorRunSources {\n /** Stable identity of the run being analyzed (a directory, a run id, a URL). */\n readonly runRef: string\n readonly instanceId: string | null\n /** Which arm/variant of a comparison this run is, when the run belongs to one. */\n readonly arm: string | null\n /** Identity of the supervision-tree store this was read from; null = none found. */\n readonly supRunDir: string | null\n /**\n * Supervision journal — spawned / settled / cancelled / metered events (JSONL).\n * Recursive readers put `role: 'supervisor' | 'worker'` on spawned rows;\n * settled `verdict` may be a legacy string or `{ valid, score, ... }`.\n */\n readonly journal: string | null\n /**\n * Source-specific reason `journal` is null. The analyzer uses it verbatim as\n * the `unavailable` reason on every journal-dependent metric, so a non-loops\n * layout names its own journal file instead of inheriting the loops paths.\n */\n readonly journalMissingReason?: string\n /** Per-brain-call tap (JSONL): finish_reason, completion tokens, requested max tokens. */\n readonly brainLog: string | null\n /** Source-specific reason `brainLog` is absent. */\n readonly brainLogMissingReason?: string\n /** Supervisor state document (JSON). */\n readonly state: string | null\n /** Supervisor progress stream (JSONL). */\n readonly progress: string | null\n /** Per-worker logs; `null` = the worker log store itself was missing. */\n readonly workers: readonly WorkerLogSource[] | null\n /** Why `workers` is null (only set when it is). */\n readonly workersMissingReason: string | null\n /** Run result document (JSON). */\n readonly result: string | null\n /**\n * Judge verdict document (JSON), or the matching ledger row re-encoded as\n * one. Runners that write the verdict straight to a ledger leave no judge\n * document, so the ledger row is the same fact from the same run — not a\n * substitute measurement.\n */\n readonly judge: string | null\n /** Where `judge` came from, for the report's provenance line. */\n readonly judgeSource: string | null\n /** Delivered unified-diff patch text. */\n readonly patch: string | null\n /** Outer-driver log (used for the driver's steer verbs + deadline evidence). */\n readonly driverLog: string | null\n /**\n * Worker tokens recovered from a harness session store; null = store unavailable.\n * `store` names the store in the report's provenance line (e.g. `opencode`).\n */\n readonly harnessWorkerTokens: {\n store: string\n sessions: number\n input: number\n output: number\n /** Cached prompt tokens, when the store counts them separately. */\n cacheRead?: number\n cacheWrite?: number\n } | null\n readonly harnessMissingReason: string | null\n /** What this store structurally cannot record. See `SourceLimits`. */\n readonly limits: SourceLimits\n /**\n * Where the ROOT invocation's transcript lives. Undefined lets the rollout\n * minter fall back to the loops layout (`<supRunDir>/journal.jsonl`); any\n * other store must say, or the row points at a path that never existed.\n */\n readonly rootTranscriptRef?: string | null\n /**\n * The `traces` CLI command that covers this run's harness-session layer.\n * Null falls back to the analyzer's default (an opencode worker fleet).\n */\n readonly traceCommand: string | null\n}\n\n/**\n * A source of supervisor-run bytes. Implementations own their storage layout;\n * the analyzer only ever sees `SupervisorRunSources`.\n */\nexport interface SupervisorRunReader {\n /** Stable identity of what this reader points at (for logs and report labels). */\n readonly runRef: string\n read(): Promise<SupervisorRunSources>\n}\n\n// ---------------------------------------------------------------------------\n// Report shape.\n// ---------------------------------------------------------------------------\n\nexport const SUPERVISOR_RUN_SCHEMA = 'tangle.supervisor-run@1'\nexport const SUPERVISOR_RUN_ROLLUP_SCHEMA = 'tangle.supervisor-run-rollup@1'\n\nexport interface SteerBreakdown {\n /** Stable journal node id when the reader retained one. */\n readonly workerId: string | null\n readonly worker: string\n /** Steer requests durably queued to this worker's inbox. */\n readonly queued: number\n /** Steers the worker's executor actually accepted (control event `delivered:true`). */\n readonly delivered: number\n}\n\nexport interface OrchestrationMetrics {\n readonly workersSpawned: Measured<number>\n readonly workersSettled: Measured<number>\n readonly workersCancelled: Measured<number>\n /** THE HEADLINE: mid-task steers the brain sent to live workers. 0 ≠ unavailable. */\n readonly steers: Measured<number>\n readonly steersDelivered: Measured<number>\n readonly steersByWorker: Measured<readonly SteerBreakdown[]>\n /** Outer-driver `supervisor_steer` tool calls seen in the driver log (a second steer path). */\n readonly driverSteerCalls: Measured<number>\n /**\n * Spawn waves. A wave is a maximal run of worker spawns with no settle/cancel between\n * them: wave N+1 begins at the first spawn issued after at least one worker from an\n * earlier wave has settled. Structural, not a time threshold — no tunable constant.\n */\n readonly waves: Measured<number>\n readonly waveSizes: Measured<readonly number[]>\n readonly maxConcurrency: Measured<number>\n /** Direct-child spawns issued after that parent's first direct-child settlement. */\n readonly respawns: Measured<number>\n /** Labels spawned more than once by the same parent. */\n readonly repeatedLabels: Measured<readonly string[]>\n /** Longest parent chain below the root, in worker hops. */\n readonly delegationDepth: Measured<number>\n readonly timeToFirstSpawnMs: Measured<number>\n readonly supervisorWallMs: Measured<number>\n /**\n * Which measurement `supervisorWallMs` holds — never a silent substitution.\n * `stamps`: explicit start and completion stamps. `journal-span`: the start\n * stamp (or first stamped event) to the last stamped journal event — a\n * lower bound, derived when the store wrote no completion stamp. `idleMs`,\n * `idlePct`, and `workerUtilization` cover the same span. Unavailable\n * exactly when `supervisorWallMs` is, with the same reason.\n */\n readonly supervisorWallSource: Measured<'stamps' | 'journal-span'>\n /** Wall time inside the supervisor run with ZERO live workers. */\n readonly idleMs: Measured<number>\n readonly idlePct: Measured<number>\n /** sum(worker wall) / supervisor wall. >1 means real parallelism. */\n readonly workerUtilization: Measured<number>\n}\n\nexport interface DecisionMetrics {\n readonly settledByStatus: Measured<Record<string, number>>\n readonly settledVerdicts: Measured<Record<string, number>>\n /**\n * Workers whose recorded verdict was green. A store that retains a delivered patch also\n * requires patch bytes; a store that retains none accepts the verdict alone, because the\n * verdict IS the acceptance decision that store recorded. `emptyPass` — the split that\n * needs patch bytes — is what reads unavailable there.\n */\n readonly accepted: Measured<number>\n /** Worker settled with a failing verify. */\n readonly rejected: Measured<number>\n /** Worker verified green but delivered no patch bytes — output with nothing to accept. */\n readonly emptyPass: Measured<number>\n /** Direct-child settlements a parent observed before issuing its next direct-child spawn. */\n readonly observeThenRespawn: Measured<number>\n /** Parent-local respawns with no direct-child settlement in front of them. */\n readonly respawnWithoutEvidence: Measured<number>\n /** Steer + question traffic on the live down/up legs — the only \"review while running\" signal. */\n readonly reviewActions: Measured<number>\n readonly workerEvidenceBytes: Measured<number>\n}\n\nexport interface RoleSpend {\n readonly tokensIn: Measured<number>\n readonly tokensOut: Measured<number>\n /**\n * Cached prompt tokens read/written. On a harness that caches aggressively\n * these dwarf `tokensIn`, so a report that omits them understates the context\n * each invocation actually consumed. `unavailable` = the store has no such counter.\n */\n readonly cacheRead: Measured<number>\n readonly cacheWrite: Measured<number>\n readonly usd: Measured<number>\n readonly source: string\n}\n\nexport interface PerWorkerRow {\n /** Stable journal node id when the reader retained one. */\n readonly workerId: string | null\n readonly worker: string\n /** Explicit journal role after the worker source was joined to its spawn. */\n readonly role: SupervisorRunNodeRole | null\n /** Exact execution runtime tag from the spawn event. */\n readonly runtime: string | null\n /** Exact canonical AgentProfile digest from the spawn event. */\n readonly profileDigest: string | null\n /** Terminal lifecycle status exactly as recorded. */\n readonly status: string | null\n /** Terminal failure detail exactly as recorded. */\n readonly failure: string | null\n /** Runtime infrastructure classification, when recorded. */\n readonly infra: boolean | null\n readonly wallMs: number | null\n /** `null` = this store does not attribute tokens per worker (NOT \"zero tokens\"). */\n readonly tokensIn: number | null\n readonly tokensOut: number | null\n readonly usd: number | null\n readonly patchBytes: number | null\n readonly passed: boolean | null\n /** Numeric verdict score exactly as recorded; null means no score was recorded. */\n readonly score: number | null\n}\n\n/**\n * `SeriesDistribution` (from `../statistics`) over per-worker wall\n * milliseconds. The fold itself is `summarizeNumberSeries`, exported for any\n * series — fleet wall medians, tokens-per-claim spreads — not only wall.\n */\nexport type WallDistribution = SeriesDistribution\n\n/** One spend measurement and the number of source records behind it. */\nexport interface SpendMeasurement {\n readonly usd: Measured<number>\n /** Source records folded into `usd`; 0 when the measurement is unavailable. */\n readonly records: number\n /**\n * Records the store wrote with `usdKnown: false` — work that HAPPENED at a price the\n * provider never reported. Those records are NOT folded into `usd`, so a run with any\n * of them has a `usd` that is a floor on real spend, never the measured total. Dropping\n * the whole channel instead would discard the records that DID carry a price.\n */\n readonly unknownRecords: number\n /** True exactly when `unknownRecords > 0`: `usd` covers some of the run, not all of it. */\n readonly partial: boolean\n /** Node ids behind `unknownRecords`, in journal order. Empty when none. */\n readonly unknownNodes: readonly string[]\n}\n\n/**\n * The run's total inference spend, measured two ways.\n *\n * `closeRecord` is the spend the store recorded as settled when the run\n * closed (loops `state.json` `result.spentUsd`; Runtime `result.json`\n * `spentTotal.usd`) — the billing-shaped answer. `journalDerived` is the\n * spend execution observably consumed (journal `metered` + `settled` rows) —\n * the execution-accounting answer. Neither is canonical for the other's\n * question. The two cover different records at different moments, so\n * divergence between them is itself a signal (a dropped settlement, a\n * double meter, spend after the close) — read it, never average it away.\n */\nexport interface SpendMeasurements {\n readonly journalDerived: SpendMeasurement\n readonly closeRecord: SpendMeasurement\n}\n\nexport interface EconomicsMetrics {\n /** Driver/brain inference — journal `metered` events. */\n readonly brain: RoleSpend\n /**\n * Brain completions that came back `finish_reason: \"length\"` — output TRUNCATED. Any value\n * above 0 means the supervisor planned into a wall and then acted on the half-written plan,\n * which is a defect and not a cost figure. The journal's `metered` rows carry token counts\n * but no finish reason, so this reads the per-call brain tap; a run whose supervisor\n * predates that tap reports `unavailable`, never 0.\n */\n readonly brainTruncations: Measured<number>\n /** Worker inference — journal `settled` spend plus the harness session join. */\n readonly workers: RoleSpend\n /** Both total-spend measurements, each with its own record count. */\n readonly spend: SpendMeasurements\n /**\n * One collapsed number kept for existing consumers: the close record when\n * the store wrote one, else the journal-derived sum. `totalUsdSource` names\n * the pick, and says so when the number is a partial floor because some\n * records carried `usdKnown: false`. Prefer `spend` — the collapse hides\n * which accounting question the number answers and how much of it is priced.\n */\n readonly totalUsd: Measured<number>\n /**\n * Where `totalUsd` came from. CLI-backend workers never price their own inference into\n * the journal, so on those arms the total is BRAIN-ONLY and the worker row's token\n * counts (recovered from the harness store) are the honest worker-side figure.\n */\n readonly totalUsdSource: string\n readonly costPerAcceptedPatchUsd: Measured<number>\n readonly workerWallMsDistribution: Measured<WallDistribution>\n readonly perWorker: Measured<readonly PerWorkerRow[]>\n}\n\nexport interface PatchStats {\n readonly files: number\n readonly linesAdded: number\n readonly linesRemoved: number\n readonly testFilesTouched: readonly string[]\n}\n\nexport interface OutcomeMetrics {\n readonly supStatus: Measured<string>\n readonly supVerdict: Measured<string>\n readonly delivered: Measured<boolean>\n readonly judgeResolved: Measured<boolean | null>\n readonly judgeScore: Measured<number | null>\n readonly judgePassed: Measured<number | null>\n readonly judgeTotal: Measured<number | null>\n readonly verifyPass: Measured<boolean>\n readonly verifyRc: Measured<number>\n readonly patch: Measured<PatchStats>\n /** Which document the judge fields came from (a judge file, a ledger row, or nothing). */\n readonly judgeSource: string | null\n}\n\nexport interface SupervisorRunReport {\n readonly schema: typeof SUPERVISOR_RUN_SCHEMA\n /** The `runRef` of the sources this report was computed from. */\n readonly runRef: string\n readonly instanceId: string | null\n readonly arm: string | null\n readonly supervisorId: Measured<string>\n readonly supervisorProfileDigest: Measured<string>\n readonly generatedAt: string\n readonly orchestration: OrchestrationMetrics\n readonly decision: DecisionMetrics\n readonly economics: EconomicsMetrics\n readonly outcome: OutcomeMetrics\n /** Artifacts that were missing, in read order — the provenance of every `unavailable`. */\n readonly gaps: readonly string[]\n /** The `traces` CLI command that covers the harness-session layer for this run. */\n readonly traceCommand: string\n}\n\nexport interface RollupCellRow {\n readonly instanceId: string | null\n readonly arm: string | null\n readonly steers: Measured<number>\n readonly waves: Measured<number>\n readonly utilization: Measured<number>\n readonly idlePct: Measured<number>\n readonly resolved: Measured<boolean | null>\n readonly usd: Measured<number>\n}\n\nexport interface SupervisorRunRollup {\n readonly schema: typeof SUPERVISOR_RUN_ROLLUP_SCHEMA\n readonly cells: number\n readonly steersTotal: Measured<number>\n readonly cellsWithSteers: Measured<number>\n readonly cellsWithUnavailableSteers: number\n readonly wavesMean: Measured<number>\n readonly maxConcurrencyMax: Measured<number>\n readonly utilizationMean: Measured<number>\n readonly idlePctMean: Measured<number>\n readonly workersSpawnedTotal: Measured<number>\n readonly acceptedTotal: Measured<number>\n /**\n * Sum of the per-run collapsed `totalUsd`. Prefer `spendUsd`: this total\n * mixes close-record and journal-derived cells without saying which.\n */\n readonly usdTotal: Measured<number>\n /**\n * Fleet spend measured two ways. `runs` is each measurement's own\n * denominator — the cells where that measurement was available. The two\n * sums cover different run sets, so comparing the values without their\n * denominators manufactures a phantom divergence.\n */\n readonly spendUsd: {\n readonly journalDerived: { readonly value: Measured<number>; readonly runs: number }\n readonly closeRecord: { readonly value: Measured<number>; readonly runs: number }\n }\n readonly resolvedCount: Measured<number>\n readonly perCell: readonly RollupCellRow[]\n}\n\n/**\n * A supervision tree expressed in the canonical rollout row type: one\n * `RolloutLine` per invocation, joined by `parent_rollout_id`. The root row\n * carries `role: 'supervisor'`; nested supervisors retain that role and leaf\n * invocations carry `role: 'worker'`.\n */\nexport interface SupervisorRunTree {\n readonly rootId: string | null\n readonly nodes: readonly RolloutLine[]\n /** Typed reasons a rollout field could not be recovered, in read order. */\n readonly gaps: readonly SupervisorRunTreeGap[]\n}\n\n/** Stable machine-readable reasons emitted while minting a supervisor tree. */\nexport type SupervisorRunTreeGapCode =\n | 'journal-unavailable'\n | 'source-row-malformed'\n | 'root-spawn-unavailable'\n | 'root-reward-unavailable'\n | 'child-reward-unavailable'\n | 'node-role-unavailable'\n | 'node-schema-invalid'\n\nexport interface SupervisorRunTreeGap {\n readonly code: SupervisorRunTreeGapCode\n readonly message: string\n readonly nodeId?: string\n readonly count?: number\n}\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 * (`loops-reader.ts` is one).\n */\n\nimport { summarizeNumberSeries } from '../statistics'\nimport {\n asRecord,\n parseJson,\n parseJsonl,\n parseSupervisorTree,\n type SpawnRow,\n type WorkerLogFacts,\n workerSourceKey,\n} from './source-facts'\nimport {\n type DecisionMetrics,\n type EconomicsMetrics,\n isUnavailable,\n type Measured,\n type OrchestrationMetrics,\n type OutcomeMetrics,\n type PatchStats,\n type PerWorkerRow,\n type RollupCellRow,\n type SpendMeasurements,\n type SteerBreakdown,\n SUPERVISOR_RUN_ROLLUP_SCHEMA,\n SUPERVISOR_RUN_SCHEMA,\n type SupervisorRunReport,\n type SupervisorRunRollup,\n type SupervisorRunSources,\n type Unavailable,\n unavailable,\n} from './types'\n\nexport {\n asRecord,\n type CloseRow,\n parseJson,\n parseJsonl,\n parseSupervisorTree,\n type SpawnRow,\n type SteerAcknowledgementFact,\n type SteerRequestFact,\n type SupervisorJournalDialect,\n type SupervisorTreeFacts,\n type WorkerLogFacts,\n} from './source-facts'\n\nconst NO_CACHE_COUNTERS = 'the journal carries no cache-token counters for this role'\nconst NO_CACHE_BREAKDOWN =\n 'Runtime recorded cacheBreakdownKnown:false — the provider reported a total without splitting cache reads from writes'\n\n// ---------------------------------------------------------------------------\n// The analyzer.\n// ---------------------------------------------------------------------------\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 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\n ? 'no supervisor run dir under <ws>/.agent/supervisor (or legacy <ws>/.loops/supervisor)'\n : 'journal.jsonl absent')\n const haveJournal = src.journal !== null\n const tree = parseSupervisorTree(src)\n const state = tree.state\n const result = parseJson(src.result)\n const judge = parseJson(src.judge)\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\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\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 workersGapReason = src.workersMissingReason ?? 'workers/ directory absent'\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\n // ── waves / concurrency / idle ─────────────────────────────────────────\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\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 const closeById = new Map(workerCloses.map((close) => [close.id, close]))\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\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\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\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\n // ── economics ──────────────────────────────────────────────────────────\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 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\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\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\n const perWorker: PerWorkerRow[] = (src.workers ?? []).map((w) => {\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 }\n })\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 const managerTokenLimit = src.limits.managerTokens\n const economics: EconomicsMetrics = {\n brain: {\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 brainTruncations:\n src.brainLog === null\n ? gap(\n 'brain.brainTruncations',\n src.brainLogMissingReason ??\n (src.supRunDir === null\n ? 'no supervisor run dir under <ws>/.agent/supervisor (or legacy <ws>/.loops/supervisor)'\n : 'brain.jsonl absent — loops predates the brain-call tap, so truncation cannot be ruled out'),\n )\n : brainCalls.filter((c) => c.finish_reason === 'length').length,\n workers: {\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 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 // ── outcome ────────────────────────────────────────────────────────────\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:\n pickString(state, 'status') ??\n pickString(result, 'sup_status') ??\n gap('supStatus', 'no state.json / result.json status'),\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\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 gaps,\n traceCommand:\n src.traceCommand ??\n 'npx --yes @tangle-network/traces@latest analyze --harness opencode --cwd <worker-clone-cwd>',\n }\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\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\nexport function round(v: number, digits: number): number {\n const f = 10 ** digits\n return Math.round(v * f) / f\n}\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\n// ---------------------------------------------------------------------------\n// Rollup across runs.\n// ---------------------------------------------------------------------------\n\n/**\n * Aggregate many supervisor-run reports. A metric no run could measure stays\n * `unavailable` rather than becoming a 0-valued mean, and cells whose steer\n * count was unavailable are counted separately from cells that measured zero.\n */\nexport function rollupSupervisorRuns(reports: readonly SupervisorRunReport[]): SupervisorRunRollup {\n const known = <T>(vals: readonly Measured<T>[]): T[] =>\n vals.filter((v): v is T => !isUnavailable(v))\n const steerVals = known(reports.map((r) => r.orchestration.steers))\n const waveVals = known(reports.map((r) => r.orchestration.waves))\n const concVals = known(reports.map((r) => r.orchestration.maxConcurrency))\n const utilVals = known(reports.map((r) => r.orchestration.workerUtilization))\n const idleVals = known(reports.map((r) => r.orchestration.idlePct))\n const spawnVals = known(reports.map((r) => r.orchestration.workersSpawned))\n const acceptVals = known(reports.map((r) => r.decision.accepted))\n const usdVals = known(reports.map((r) => r.economics.totalUsd))\n const journalSpendVals = known(reports.map((r) => r.economics.spend.journalDerived.usd))\n const closeSpendVals = known(reports.map((r) => r.economics.spend.closeRecord.usd))\n const resolvedVals = known(reports.map((r) => r.outcome.judgeResolved))\n const sum = (xs: readonly number[]): number => xs.reduce((a, b) => a + b, 0)\n const mean = (xs: readonly number[]): Measured<number> =>\n xs.length === 0 ? unavailable('no cell reported this metric') : round(sum(xs) / xs.length, 3)\n\n const perCell: RollupCellRow[] = reports.map((r) => ({\n instanceId: r.instanceId,\n arm: r.arm,\n steers: r.orchestration.steers,\n waves: r.orchestration.waves,\n utilization: r.orchestration.workerUtilization,\n idlePct: r.orchestration.idlePct,\n resolved: r.outcome.judgeResolved,\n usd: r.economics.totalUsd,\n }))\n\n return {\n schema: SUPERVISOR_RUN_ROLLUP_SCHEMA,\n cells: reports.length,\n steersTotal:\n steerVals.length === 0 ? unavailable('no cell reported a steer count') : sum(steerVals),\n cellsWithSteers:\n steerVals.length === 0\n ? unavailable('no cell reported a steer count')\n : steerVals.filter((n) => n > 0).length,\n cellsWithUnavailableSteers: reports.filter((r) => isUnavailable(r.orchestration.steers)).length,\n wavesMean: mean(waveVals),\n maxConcurrencyMax:\n concVals.length === 0 ? unavailable('no cell reported concurrency') : Math.max(...concVals),\n utilizationMean: mean(utilVals),\n idlePctMean: mean(idleVals),\n workersSpawnedTotal:\n spawnVals.length === 0 ? unavailable('no cell reported spawns') : sum(spawnVals),\n acceptedTotal:\n acceptVals.length === 0 ? unavailable('no cell reported acceptance') : sum(acceptVals),\n usdTotal: usdVals.length === 0 ? unavailable('no cell reported spend') : round(sum(usdVals), 6),\n spendUsd: {\n journalDerived: {\n value:\n journalSpendVals.length === 0\n ? unavailable('no cell measured journal-derived spend')\n : round(sum(journalSpendVals), 6),\n runs: journalSpendVals.length,\n },\n closeRecord: {\n value:\n closeSpendVals.length === 0\n ? unavailable('no cell carried a close record')\n : round(sum(closeSpendVals), 6),\n runs: closeSpendVals.length,\n },\n },\n resolvedCount:\n resolvedVals.length === 0\n ? unavailable('no cell reported a judge verdict')\n : resolvedVals.filter((v) => v === true).length,\n perCell,\n }\n}\n","/**\n * Supervision-tree reader over a THIRD-PARTY harness: Claude Code.\n *\n * `loops-reader.ts` reads a supervisor we wrote, whose journal was designed\n * for this analysis. This reader reads a harness we do not control, whose\n * transcript was designed for replaying a chat — and recovers the same tree\n * from it. If both produce a `SupervisorRunSources`, the tree model is a\n * property of multi-agent runs, not of our journal format.\n *\n * ## Where the tree hides in a Claude Code transcript\n *\n * | Tree fact | Claude Code evidence |\n * |---|---|\n * | spawn | assistant `tool_use` (`Agent` / `Task`), answered by a `tool_result` whose `toolUseResult.agentId` names the child |\n * | settle | a `<task-notification>` block in a later user line: `<task-id>` = agentId, `<status>` |\n * | steer | assistant `tool_use` (`SendMessage`) with `input.to` = agentId — mid-task, to a LIVE child |\n * | delivered | that steer's `tool_result` carrying `success` / `resumedAgentId` |\n * | cancel | assistant `tool_use` (`TaskStop`) targeting an agentId |\n * | brain spend| `message.usage` on the main thread's assistant lines |\n * | worker spend| `message.usage` inside `<session>/subagents/agent-<id>.jsonl` |\n * | depth | a child transcript that itself contains `Agent` tool_use lines |\n *\n * Every one of those is read through `parseClaudeEntries` — the SAME line\n * parser `src/rollout/readers/claude-jsonl.ts` uses for solo rollouts. There\n * is no second transcript parser.\n *\n * ## What Claude Code cannot say\n *\n * It records tokens but never a price, runs no per-worker verify, and keeps no\n * per-worker patch. Those are declared once in `limits`, so the analyzer\n * reports `unavailable — <reason>` instead of the $0 / 0-accepted that summing\n * an empty field would produce. See `SourceLimits`.\n *\n * ## Metric coverage vs the loops journal\n *\n * Measured on a real 52-agent session (fixture:\n * `tests/fixtures/supervisor-run/claude-code-session-*`).\n *\n * | Metric | loops | Claude Code | Why |\n * |---|---|---|---|\n * | workersSpawned / Settled / Cancelled | full | full | spawn tool_use + task-notification + TaskStop |\n * | steers / steersDelivered / steersByWorker | full | full | `SendMessage`; delivery from its tool_result |\n * | waves / waveSizes / maxConcurrency | full | full | derived from spawn/settle instants |\n * | respawns / repeatedLabels | full | full | same derivation |\n * | delegationDepth | full | full | a child transcript's own spawn calls |\n * | timeToFirstSpawn / supervisorWall | full | full | transcript instants |\n * | idleMs / idlePct / workerUtilization | full | PARTIAL | an agent that never notifies is counted live to the end of the transcript |\n * | observeThenRespawn / respawnWithoutEvidence | full | full | ordering of spawn vs settle instants |\n * | workerEvidenceBytes | full | PARTIAL | the child's closing message; 0 for pruned transcripts |\n * | brain tokens in/out + cache | full | full | main-thread `message.usage` |\n * | worker tokens in/out + cache | via harness join | full or unavailable | totals are refused if any spawned transcript was pruned; retained per-worker rows remain available |\n * | perWorker wall | full | full | spawn → settle instants |\n * | accepted / rejected / emptyPass / settledVerdicts | full | NONE | no per-worker verify step exists |\n * | brain/worker/total usd, costPerAcceptedPatch | full | NONE | transcripts carry no price |\n * | patch stats, delivered, verifyPass/Rc | full | NONE | no diff is handed back |\n * | judgeResolved / Score / Passed / Total | full | NONE | no judge in the loop |\n * | driverSteerCalls, brainTruncations | full | NONE | no outer driver log, no per-call finish_reason tap |\n */\n\nimport { readdir, readFile } from 'node:fs/promises'\nimport { basename, dirname, join } from 'node:path'\nimport {\n type ClaudeEntry,\n parseClaudeEntries,\n transcriptFromEntries,\n} from '../rollout/readers/claude-jsonl'\nimport type { SupervisorRunReader, SupervisorRunSources, WorkerLogSource } from './types'\n\n/** Tool names that spawn a child agent. `Task` is the older name for `Agent`. */\nconst DEFAULT_SPAWN_TOOLS = ['Agent', 'Task'] as const\n/** Tool names that deliver a message to an ALREADY-RUNNING child agent. */\nconst DEFAULT_STEER_TOOLS = ['SendMessage'] as const\n/** Tool names that stop a running child agent. */\nconst DEFAULT_CANCEL_TOOLS = ['TaskStop', 'KillAgent'] as const\n\nconst SPEND_UNPRICED =\n 'Claude Code transcripts record token usage but never a price — usd is not in the store'\nconst NO_VERDICTS =\n 'Claude Code runs no per-worker verify step — a subagent reports prose, not pass/fail'\nconst NO_DELIVERABLES =\n 'Claude Code retains no per-worker patch — subagents commit to git, they do not hand back a diff'\n\nexport interface ClaudeCodeReaderOptions {\n /** The main session transcript: `~/.claude/projects/<slug>/<sessionId>.jsonl`. */\n readonly transcriptPath: string\n /**\n * Directory of child transcripts. Defaults to `<transcript-dir>/<sessionId>/subagents`.\n * `null` skips the join, and every per-worker token count becomes unavailable.\n */\n readonly subagentsDir?: string | null\n readonly runRef?: string\n readonly instanceId?: string | null\n readonly arm?: string | null\n readonly spawnTools?: readonly string[]\n readonly steerTools?: readonly string[]\n readonly cancelTools?: readonly string[]\n}\n\nconst isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v)\n\nconst str = (v: unknown): string | null => (typeof v === 'string' ? v : null)\n\ninterface ToolUse {\n readonly id: string\n readonly name: string\n readonly input: Record<string, unknown>\n readonly at: string | null\n}\n\ninterface ToolResult {\n readonly id: string\n readonly at: string | null\n readonly structured: unknown\n readonly text: string\n}\n\n/** Every tool call and tool result on one thread, in order, with instants. */\ninterface ThreadCalls {\n readonly uses: ToolUse[]\n readonly results: Map<string, ToolResult>\n readonly notifications: TaskNotification[]\n readonly firstAt: string | null\n readonly lastAt: string | null\n}\n\ninterface TaskNotification {\n readonly taskId: string\n readonly toolUseId: string | null\n readonly status: string\n readonly summary: string | null\n readonly at: string | null\n}\n\nfunction blockText(content: unknown): string {\n if (typeof content === 'string') return content\n if (!Array.isArray(content)) return ''\n const parts: string[] = []\n for (const b of content) {\n if (isRecord(b) && b.type === 'text' && typeof b.text === 'string') parts.push(b.text)\n }\n return parts.join('\\n')\n}\n\nconst tag = (xml: string, name: string): string | null => {\n const m = xml.match(new RegExp(`<${name}>([\\\\s\\\\S]*?)</${name}>`))\n return m === null ? null : (m[1] as string)\n}\n\n/**\n * Task notifications are the settle instants. A notification fires each time an\n * agent stops, so a resumed agent produces several — they are kept in order and\n * the LAST one is the settle the analyzer sees, with the earlier ones acting as\n * the intermediate stops they actually were.\n */\nfunction parseNotifications(text: string, at: string | null): TaskNotification[] {\n const out: TaskNotification[] = []\n for (const m of text.matchAll(/<task-notification>[\\s\\S]*?<\\/task-notification>/g)) {\n const xml = m[0]\n const taskId = tag(xml, 'task-id')\n if (taskId === null) continue\n out.push({\n taskId: taskId.trim(),\n toolUseId: tag(xml, 'tool-use-id')?.trim() ?? null,\n status: tag(xml, 'status')?.trim() ?? 'unknown',\n summary: tag(xml, 'summary')?.trim() ?? null,\n at,\n })\n }\n return out\n}\n\n/** Project entries of ONE thread (main or a single sidechain) into tool traffic. */\nfunction threadCalls(entries: readonly ClaudeEntry[]): ThreadCalls {\n const uses: ToolUse[] = []\n const results = new Map<string, ToolResult>()\n const notifications: TaskNotification[] = []\n let firstAt: string | null = null\n let lastAt: string | null = null\n\n for (const entry of entries) {\n if (entry.timestamp !== null) {\n if (firstAt === null) firstAt = entry.timestamp\n lastAt = entry.timestamp\n }\n const content = entry.message.content\n if (entry.type === 'assistant') {\n if (!Array.isArray(content)) continue\n for (const block of content) {\n if (!isRecord(block) || block.type !== 'tool_use') continue\n const id = str(block.id)\n const name = str(block.name)\n if (id === null || name === null) continue\n uses.push({\n id,\n name,\n input: isRecord(block.input) ? block.input : {},\n at: entry.timestamp,\n })\n }\n continue\n }\n if (typeof content === 'string') {\n notifications.push(...parseNotifications(content, entry.timestamp))\n continue\n }\n if (!Array.isArray(content)) continue\n for (const block of content) {\n if (!isRecord(block)) continue\n if (block.type === 'tool_result' && typeof block.tool_use_id === 'string') {\n results.set(block.tool_use_id, {\n id: block.tool_use_id,\n at: entry.timestamp,\n structured: entry.toolUseResult,\n text: blockText(block.content),\n })\n } else if (block.type === 'text' && typeof block.text === 'string') {\n notifications.push(...parseNotifications(block.text, entry.timestamp))\n }\n }\n }\n return { uses, results, notifications, firstAt, lastAt }\n}\n\n/**\n * The agent id a spawn produced. Claude Code puts it in the structured\n * `toolUseResult`; the same id is echoed in the result text for transcripts\n * written before that field existed, so both are tried before giving up.\n */\nfunction spawnedAgentId(result: ToolResult | undefined): string | null {\n if (result === undefined) return null\n if (isRecord(result.structured)) {\n const id = str(result.structured.agentId)\n if (id !== null) return id\n }\n return result.text.match(/agentId:\\s*([A-Za-z0-9_-]+)/)?.[1] ?? null\n}\n\ninterface ChildTranscript {\n readonly agentId: string\n readonly path: string\n readonly description: string | null\n readonly spawnToolUseId: string | null\n readonly spawnDepth: number | null\n readonly entries: ClaudeEntry[]\n readonly tokensIn: number\n readonly tokensOut: number\n readonly cacheRead: number\n readonly cacheWrite: number\n readonly firstAt: string | null\n readonly lastAt: string | null\n readonly model: string | null\n /**\n * The child's closing assistant message — what it actually handed back. This\n * is the Claude Code analogue of a worker's `evidence` blob.\n */\n readonly finalReport: string | null\n}\n\nasync function readChildren(dir: string): Promise<ChildTranscript[]> {\n const names = await readdir(dir).catch(() => null)\n if (names === null) return []\n const out: ChildTranscript[] = []\n for (const name of names.filter((n) => n.endsWith('.jsonl')).sort()) {\n const path = join(dir, name)\n const raw = await readFile(path, 'utf8').catch(() => null)\n if (raw === null) continue\n const entries = parseClaudeEntries(raw)\n // A subagent transcript is sidechain end to end — that flag is what marks it\n // a separate invocation rather than a turn of the parent.\n const projected = transcriptFromEntries(entries, { includeSidechain: true })\n const metaRaw = await readFile(path.replace(/\\.jsonl$/, '.meta.json'), 'utf8').catch(() => null)\n let meta: Record<string, unknown> = {}\n if (metaRaw !== null) {\n try {\n const parsed: unknown = JSON.parse(metaRaw)\n if (isRecord(parsed)) meta = parsed\n } catch {\n meta = {}\n }\n }\n const agentId =\n entries.find((e) => e.agentId !== null)?.agentId ??\n name.replace(/^agent-/, '').replace(/\\.jsonl$/, '')\n out.push({\n agentId,\n path,\n description: str(meta.description),\n spawnToolUseId: str(meta.toolUseId),\n spawnDepth: typeof meta.spawnDepth === 'number' ? meta.spawnDepth : null,\n entries,\n tokensIn: projected.usage.tokensIn,\n tokensOut: projected.usage.tokensOut,\n cacheRead: projected.usage.cacheRead,\n cacheWrite: projected.usage.cacheWrite,\n firstAt: projected.startedAt,\n lastAt: projected.endedAt,\n model: projected.model,\n finalReport:\n [...projected.messages]\n .reverse()\n .find((m) => m.role === 'assistant' && typeof m.content === 'string')?.content ?? null,\n })\n }\n return out\n}\n\ninterface SpawnFact {\n readonly agentId: string\n readonly parentId: string\n readonly label: string\n readonly at: string | null\n readonly model: string | null\n}\n\n/** A journal line in the dialect `parseSupervisorTree` reads. */\nconst line = (obj: Record<string, unknown>): string => JSON.stringify(obj)\n\n/**\n * Read a Claude Code session (plus its subagent transcripts) as supervision-tree\n * source bytes. Never throws on a missing artifact.\n */\nexport async function readClaudeCodeSupervisorRun(\n opts: ClaudeCodeReaderOptions,\n): Promise<SupervisorRunSources> {\n const spawnTools = new Set(opts.spawnTools ?? DEFAULT_SPAWN_TOOLS)\n const steerTools = new Set(opts.steerTools ?? DEFAULT_STEER_TOOLS)\n const cancelTools = new Set(opts.cancelTools ?? DEFAULT_CANCEL_TOOLS)\n\n const raw = await readFile(opts.transcriptPath, 'utf8').catch(() => null)\n const sessionId = basename(opts.transcriptPath).replace(/\\.jsonl$/, '')\n const runRef = opts.runRef ?? opts.transcriptPath\n const limits = {\n managerTokens: null,\n workerTokens: null,\n spendUsd: SPEND_UNPRICED,\n workerVerdicts: NO_VERDICTS,\n deliverables: null,\n }\n const traceCommand = `npx --yes @tangle-network/traces@latest analyze --harness claude-code --session ${sessionId}`\n\n if (raw === null) {\n return {\n runRef,\n instanceId: opts.instanceId ?? sessionId,\n arm: opts.arm ?? null,\n supRunDir: null,\n journal: null,\n brainLog: null,\n state: null,\n progress: null,\n workers: null,\n workersMissingReason: `session transcript unreadable at ${opts.transcriptPath}`,\n result: null,\n judge: null,\n judgeSource: null,\n patch: null,\n driverLog: null,\n harnessWorkerTokens: null,\n harnessMissingReason: `session transcript unreadable at ${opts.transcriptPath}`,\n limits: {\n ...limits,\n managerTokens: `session transcript unreadable at ${opts.transcriptPath}`,\n workerTokens: `session transcript unreadable at ${opts.transcriptPath}`,\n deliverables: NO_DELIVERABLES,\n },\n traceCommand,\n }\n }\n\n const allEntries = parseClaudeEntries(raw)\n const main = threadCalls(allEntries.filter((e) => !e.isSidechain))\n const mainTranscript = transcriptFromEntries(allEntries)\n\n const subagentsDir =\n opts.subagentsDir === undefined\n ? join(dirname(opts.transcriptPath), sessionId, 'subagents')\n : opts.subagentsDir\n const children = subagentsDir === null ? [] : await readChildren(subagentsDir)\n const childByAgentId = new Map(children.map((c) => [c.agentId, c]))\n const childBySpawnToolUseId = new Map(\n children.filter((c) => c.spawnToolUseId !== null).map((c) => [c.spawnToolUseId as string, c]),\n )\n\n // Every thread that can spawn: the session itself, plus each child transcript\n // (a child that calls the spawn tool is a second delegation level).\n const threads: Array<{ id: string; calls: ThreadCalls }> = [{ id: sessionId, calls: main }]\n for (const child of children) {\n threads.push({ id: child.agentId, calls: threadCalls(child.entries) })\n }\n\n const spawns: SpawnFact[] = []\n const steersByTarget = new Map<\n string,\n Array<{ requestId: string; at: string | null; delivered: boolean }>\n >()\n const cancels: Array<{ agentId: string; at: string | null }> = []\n const settles: TaskNotification[] = []\n\n for (const thread of threads) {\n for (const use of thread.calls.uses) {\n if (spawnTools.has(use.name)) {\n const result = thread.calls.results.get(use.id)\n const agentId = spawnedAgentId(result) ?? childBySpawnToolUseId.get(use.id)?.agentId ?? null\n if (agentId === null) continue\n const label =\n str(use.input.description) ?? childByAgentId.get(agentId)?.description ?? agentId\n spawns.push({\n agentId,\n parentId: thread.id,\n label,\n // The spawn is complete when the launch call is answered; the tool_use\n // instant is the fallback for a call that never got a result line.\n at: result?.at ?? use.at,\n model: isRecord(result?.structured) ? str(result.structured.resolvedModel) : null,\n })\n continue\n }\n if (steerTools.has(use.name)) {\n const target = str(use.input.to) ?? str(use.input.recipient)\n if (target === null) continue\n const result = thread.calls.results.get(use.id)\n const structured = isRecord(result?.structured) ? result.structured : null\n // `success` is the harness confirming the message reached a live agent;\n // absent, the steer is counted queued but not delivered.\n const delivered = structured?.success === true || str(structured?.resumedAgentId) === target\n const rows = steersByTarget.get(target) ?? []\n rows.push({ requestId: use.id, at: use.at, delivered })\n steersByTarget.set(target, rows)\n continue\n }\n if (cancelTools.has(use.name)) {\n const target = str(use.input.agentId) ?? str(use.input.to) ?? str(use.input.taskId)\n if (target !== null) cancels.push({ agentId: target, at: use.at })\n }\n }\n settles.push(...thread.calls.notifications)\n }\n\n const spawnedIds = new Set(spawns.map((s) => s.agentId))\n const cancelledIds = new Set(\n cancels.filter((c) => spawnedIds.has(c.agentId)).map((c) => c.agentId),\n )\n const startedAt = main.firstAt\n const completedAt = main.lastAt\n\n const journalLines: string[] = [\n line({\n kind: 'spawned',\n id: sessionId,\n parent: null,\n label: `session:${sessionId}`,\n role: 'supervisor',\n at: startedAt,\n }),\n ]\n for (const s of spawns) {\n journalLines.push(\n line({\n kind: 'spawned',\n id: s.agentId,\n parent: s.parentId,\n label: s.label,\n role: 'worker',\n at: s.at,\n }),\n )\n }\n\n // Only the LAST notification per agent is its settle; an earlier one is a stop\n // the supervisor resumed from, which the steer count already records.\n const lastNotification = new Map<string, TaskNotification>()\n for (const n of settles) {\n if (!spawnedIds.has(n.taskId)) continue\n lastNotification.set(n.taskId, n)\n }\n for (const [agentId, n] of lastNotification) {\n if (cancelledIds.has(agentId)) continue\n journalLines.push(\n line({\n kind: 'settled',\n id: agentId,\n status: n.status,\n verdict: n.summary,\n at: n.at,\n // No `spent` key: Claude Code prices nothing, and a zeroed spend object\n // would read as a $0 worker. `limits.spendUsd` carries the reason.\n }),\n )\n }\n // One cancel per agent: Claude Code can emit a stop then a retry-stop for the\n // same agentId, and each raw entry would otherwise mint a duplicate `cancelled`\n // line that double-counts in `workersCancelled`. Keep the last, mirroring the\n // last-notification dedup the settle path already does.\n const lastCancel = new Map<string, { agentId: string; at: string | null }>()\n for (const c of cancels) {\n if (!spawnedIds.has(c.agentId)) continue\n lastCancel.set(c.agentId, c)\n }\n for (const c of lastCancel.values()) {\n journalLines.push(\n line({ kind: 'cancelled', id: c.agentId, reason: 'stopped by supervisor', at: c.at }),\n )\n }\n // `metered` carries the brain's own inference. The token counts are real; the\n // usd stays absent and `limits.spendUsd` explains why.\n journalLines.push(\n line({\n kind: 'metered',\n id: sessionId,\n spend: {\n tokens: {\n input: mainTranscript.usage.tokensIn,\n output: mainTranscript.usage.tokensOut,\n cacheRead: mainTranscript.usage.cacheRead,\n cacheWrite: mainTranscript.usage.cacheWrite,\n },\n },\n at: completedAt,\n }),\n )\n\n const settleAtByAgent = new Map(\n [...lastNotification.entries()].map(([id, n]) => [id, n.at] as const),\n )\n const spawnAtByAgent = new Map(spawns.map((s) => [s.agentId, s.at] as const))\n\n const workers: WorkerLogSource[] = []\n for (const spawn of spawns) {\n const { agentId, label } = spawn\n const events: string[] = []\n const inbox: string[] = []\n const child = childByAgentId.get(agentId) ?? null\n const startAt = child?.firstAt ?? spawnAtByAgent.get(agentId) ?? null\n const endAt = settleAtByAgent.get(agentId) ?? child?.lastAt ?? null\n if (startAt !== null) events.push(line({ kind: 'started', label, at: startAt, agentId }))\n for (const steer of steersByTarget.get(agentId) ?? []) {\n inbox.push(line({ id: steer.requestId, at: steer.at, worker: label, message: 'steer' }))\n events.push(\n line({\n kind: 'message',\n label,\n direction: 'down',\n at: steer.at,\n requestId: steer.requestId,\n delivered: steer.delivered,\n }),\n )\n }\n if (endAt !== null) {\n events.push(\n line({\n kind: 'finished',\n label,\n at: endAt,\n agentId,\n // No `passed` / `patchBytes`: this harness has neither. Emitting\n // `passed: false` here would invent a failed worker.\n // `evidence` is the child's closing message — what it handed back.\n ...(child?.finalReport === null || child?.finalReport === undefined\n ? {}\n : { evidence: child.finalReport }),\n }),\n )\n }\n workers.push({\n workerId: agentId,\n label,\n events: events.length === 0 ? '' : `${events.join('\\n')}\\n`,\n inbox: inbox.length === 0 ? '' : `${inbox.join('\\n')}\\n`,\n patchBytes: null,\n transcriptRef: child?.path ?? null,\n patchPath: null,\n tokensIn: child?.tokensIn ?? null,\n tokensOut: child?.tokensOut ?? null,\n cacheRead: child?.cacheRead ?? null,\n cacheWrite: child?.cacheWrite ?? null,\n })\n }\n\n const joined = children.length\n const harnessWorkerTokens =\n joined === 0\n ? null\n : {\n store: 'claude-code subagent transcripts',\n sessions: joined,\n input: children.reduce((a, c) => a + c.tokensIn, 0),\n output: children.reduce((a, c) => a + c.tokensOut, 0),\n cacheRead: children.reduce((a, c) => a + c.cacheRead, 0),\n cacheWrite: children.reduce((a, c) => a + c.cacheWrite, 0),\n }\n\n const missingChildren = spawns.filter((s) => !childByAgentId.has(s.agentId)).length\n const harnessMissingReason =\n subagentsDir === null\n ? 'subagent transcript join disabled'\n : joined === 0\n ? `no subagent transcripts under ${subagentsDir}`\n : missingChildren === 0\n ? null\n : `${missingChildren}/${spawns.length} spawned agents have no retained transcript under ${subagentsDir} (Claude Code prunes them; their tokens are unrecoverable)`\n\n const liveWorkers = spawns.filter(\n (s) => !lastNotification.has(s.agentId) && !cancelledIds.has(s.agentId),\n ).length\n const state = JSON.stringify({\n id: sessionId,\n // Derived, not asserted: a spawned agent with no notification and no stop\n // is still running, which is exactly what a live transcript looks like.\n status: liveWorkers > 0 ? 'running' : 'idle',\n startedAt,\n completedAt,\n result: { delivered: null },\n })\n\n return {\n runRef,\n instanceId: opts.instanceId ?? sessionId,\n arm: opts.arm ?? null,\n supRunDir: subagentsDir,\n journal: `${journalLines.join('\\n')}\\n`,\n brainLog: null,\n state,\n progress: null,\n workers,\n workersMissingReason: null,\n result: null,\n judge: null,\n judgeSource: null,\n patch: null,\n driverLog: null,\n harnessWorkerTokens,\n harnessMissingReason,\n limits: {\n ...limits,\n workerTokens: spawns.length === 0 ? null : harnessMissingReason,\n deliverables: NO_DELIVERABLES,\n },\n rootTranscriptRef: opts.transcriptPath,\n traceCommand,\n }\n}\n\n/** A `SupervisorRunReader` over a Claude Code session — the same contract loops implements. */\nexport function claudeCodeSupervisorRunReader(opts: ClaudeCodeReaderOptions): SupervisorRunReader {\n return {\n runRef: opts.runRef ?? opts.transcriptPath,\n read: () => readClaudeCodeSupervisorRun(opts),\n }\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 { round } from './analyze'\nimport {\n isUnavailable,\n type Measured,\n type SupervisorRunReport,\n type SupervisorRunRollup,\n showMeasured,\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 ` 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\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 — legacy label join' : `\\`${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 — legacy label join' : `\\`${w.workerId}\\``} | \\`${w.worker}\\` | ${w.role ?? 'unavailable — source recorded no role'} | ${w.runtime ?? 'unavailable — source recorded no runtime'} | ${w.profileDigest === null ? 'unavailable — source recorded no profile digest' : `\\`${w.profileDigest}\\``} | ${w.status ?? 'unavailable — no terminal event'} | ${w.failure ?? 'none recorded'} | ${w.infra ?? 'unavailable'} | ${w.wallMs === null ? 'unavailable — no spawn/finish pair' : fmtMs(w.wallMs)} | ${w.tokensIn ?? 'unavailable — store does not attribute tokens per worker'} | ${w.tokensOut ?? 'unavailable — store does not attribute tokens per worker'} | ${w.patchBytes ?? 'unavailable — no worker patch file'} | ${w.passed === null ? 'unavailable — no verdict' : String(w.passed)} | ${w.score ?? 'unavailable — no numeric score'} |`,\n )\n }\n out.push('')\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(`| 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 return out.join('\\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 and repeat the spawn as a parentless\n * marker when no owned tree is recorded. Descendant spawns must occur in the\n * tree their parent owns. This reader removes a duplicate marker and preserves\n * the other 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 * The run's terminal status is Runtime's own `result.json` `kind` — `winner`,\n * `no-winner`, or whatever a later arm is called — read verbatim. The reader\n * does not decide which kinds count: a kind it refuses is a run that recorded\n * its outcome and got reported as having none.\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 { readFile, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport {\n NO_SOURCE_LIMITS,\n type SourceLimits,\n type SupervisorRunReader,\n type SupervisorRunSources,\n type WorkerLogSource,\n} from './types'\n\nconst JOURNAL_FILE = 'spawn-journal.jsonl'\nconst RESULT_FILE = 'result.json'\nconst TRAJECTORY_FILE = 'trajectory.json'\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\nasync function readMaybe(path: string): Promise<string | null> {\n return readFile(path, 'utf8').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\nfunction record(value: unknown): Record<string, unknown> | null {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null\n}\n\nfunction nonEmptyString(value: unknown): string | null {\n return typeof value === 'string' && value.length > 0 ? value : null\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') {\n throw formatError(path, line, \"kind must be 'begin' or 'event'\")\n }\n if (!begun.has(root)) {\n throw formatError(path, line, `event for tree ${JSON.stringify(root)} precedes begin`)\n }\n const event = record(envelope.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 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 const rootMarkersByTree = 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 if (entry.root === id && (entry.event.parent === undefined || entry.event.parent === null)) {\n const markers = rootMarkersByTree.get(entry.root) ?? []\n markers.push(entry)\n rootMarkersByTree.set(entry.root, markers)\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 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(\n (entry) =>\n !(\n nestedRoots.has(entry.root) &&\n entry.event.kind === 'spawned' &&\n entry.event.id === entry.root &&\n (entry.event.parent === undefined || entry.event.parent === null)\n ),\n )\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\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\nfunction 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\nfunction runtimeState(\n root: string,\n startedAt: string,\n result: Record<string, unknown> | null,\n trajectory: Record<string, unknown> | null,\n resultPath: string,\n trajectoryPath: string,\n): string {\n // Runtime's own terminal discriminant, read verbatim: `winner` when a child delivered,\n // `no-winner` when none did, and whatever a later arm is named. The reader translates the\n // envelope; it does not decide which kinds count, because a kind it fails to recognize is\n // reported as a missing status on a run that recorded one.\n const resultKind = result === null ? null : nonEmptyString(result.kind)\n if (resultKind !== null && result !== null) {\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 if (trajectory !== null && nonEmptyString(trajectory.root) === null) {\n throw new Error(`${trajectoryPath}: Runtime trajectory has no root`)\n }\n if (typeof trajectory?.root === 'string' && trajectory.root !== root) {\n throw new Error(\n `${trajectoryPath}: root ${JSON.stringify(trajectory.root)} does not match journal root ${JSON.stringify(root)}`,\n )\n }\n if (trajectory !== null && !Array.isArray(trajectory.nodes)) {\n throw new Error(`${trajectoryPath}: Runtime trajectory nodes must be an array`)\n }\n\n let status: string | null = resultKind\n if (status === null && Array.isArray(trajectory?.nodes)) {\n const rootNodes = trajectory.nodes\n .map((node) => record(node))\n .filter((node) => node?.id === root)\n if (rootNodes.length > 1) {\n throw new Error(`${trajectoryPath}: Runtime trajectory contains duplicate root nodes`)\n }\n status = nonEmptyString(rootNodes[0]?.status)\n }\n\n return JSON.stringify({\n id: root,\n startedAt,\n ...(status === null ? {} : { status }),\n })\n}\n\nexport interface RuntimeReaderOptions {\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 * Sources for a run dir whose spawn journal does not exist. Mirrors the\n * absent shape `readLoopsSupervisorRun` returns for a missing store: every\n * journal-dependent metric downstream reads `unavailable`, never 0.\n */\nfunction absentRuntimeSupervisorRun(\n runDir: string,\n resultText: string | null,\n): SupervisorRunSources {\n const reason = `no Runtime spawn journal (${JOURNAL_FILE}) under ${runDir}`\n return {\n runRef: runDir,\n instanceId: null,\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 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 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 `readLoopsSupervisorRun` 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. Pass `strict: true` to throw on\n * the missing journal instead. A journal that exists but cannot be parsed\n * always throws: a corrupt journal is a defect, not an 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 journalPath = join(runDir, JOURNAL_FILE)\n const rawJournal =\n opts.strict === true ? await readFile(journalPath, 'utf8') : await readMaybe(journalPath)\n if (rawJournal === null) {\n return absentRuntimeSupervisorRun(runDir, await readMaybe(join(runDir, RESULT_FILE)))\n }\n const normalized = parseEnvelopeJournal(rawJournal, journalPath)\n const resultText = await readMaybe(join(runDir, RESULT_FILE))\n const trajectoryText = await readMaybe(join(runDir, TRAJECTORY_FILE))\n const result = parseOptionalRecord(resultText, join(runDir, RESULT_FILE))\n const trajectory = parseOptionalRecord(trajectoryText, join(runDir, TRAJECTORY_FILE))\n const resultPath = join(runDir, RESULT_FILE)\n const trajectoryPath = join(runDir, TRAJECTORY_FILE)\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 workers: WorkerLogSource[] = childSpawns.map((event) => ({\n workerId: nonEmptyString(event.id) as string,\n label: nonEmptyString(event.label) ?? String(event.id),\n events: null,\n inbox: null,\n patchBytes: null,\n transcriptRef: null,\n patchPath: null,\n }))\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: runtimeState(\n normalized.root,\n normalized.startedAt,\n result,\n trajectory,\n resultPath,\n trajectoryPath,\n ),\n progress: null,\n workers,\n workersMissingReason: null,\n result: resultText,\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: sourceLimits(normalized.root, normalized.events, workerIds),\n rootTranscriptRef: null,\n traceCommand: 'unavailable — Runtime FileRunContext records no provider-session trace identity',\n }\n}\n\n/** The agent-runtime file-backed layout as a `SupervisorRunReader`. */\nexport function runtimeSupervisorRunReader(\n runDir: string,\n opts: RuntimeReaderOptions = {},\n): SupervisorRunReader {\n return { runRef: runDir, read: () => readRuntimeSupervisorRun(runDir, opts) }\n}\n\n/** True when a directory contains Runtime's canonical file-backed journal. */\nexport async function isRuntimeSupervisorRunDir(runDir: string): Promise<boolean> {\n return stat(join(runDir, JOURNAL_FILE))\n .then((entry) => entry.isFile())\n .catch((error: unknown) => {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n ((error as { code: unknown }).code === 'ENOENT' ||\n (error as { code: unknown }).code === 'ENOTDIR')\n ) {\n return false\n }\n throw error\n })\n}\n","/**\n * ONE implementation of `SupervisorRunReader`: the on-disk layout the loops\n * supervisor writes — `<runDir>/ws/.agent/supervisor/<id>/{journal.jsonl,\n * state.json, progress.ndjson, workers/*.ndjson}` alongside the run's\n * `result.json` / `judge.json` / `driver.log` / delivered patch. Runs written\n * before the `.agent` rename live under `<ws>/.loops/supervisor/<id>` and are\n * still found via fallback.\n *\n * Nothing in `analyze.ts` knows this layout exists. A different store (an\n * archive, an object bucket, a database) implements the same interface and\n * gets the same report.\n *\n * Worker token recovery reuses the rollout module's opencode reader rather\n * than opening a second sqlite path — one store client, one corruption policy.\n */\n\nimport { appendFile, mkdir, readdir, readFile, writeFile } from 'node:fs/promises'\nimport { basename, join } from 'node:path'\nimport {\n DEFAULT_OPENCODE_DB,\n findOpencodeSessionsByDirectory,\n openOpencodeDb,\n} from '../rollout/readers/opencode-sqlite'\nimport { analyzeSupervisorRunSources, parseJson, parseJsonl, rollupSupervisorRuns } from './analyze'\nimport {\n renderSupervisorRollupMarkdown,\n renderSupervisorRunHeadline,\n renderSupervisorRunMarkdown,\n} from './render'\nimport { isRuntimeSupervisorRunDir, readRuntimeSupervisorRun } from './runtime-reader'\nimport {\n NO_SOURCE_LIMITS,\n type SupervisorRunReader,\n type SupervisorRunReport,\n type SupervisorRunRollup,\n type SupervisorRunSources,\n type WorkerLogSource,\n} from './types'\n\nasync function readMaybe(path: string): Promise<string | null> {\n return readFile(path, 'utf8').catch(() => null)\n}\n\n/**\n * Locate the (single) supervisor run dir under `<ws>/.agent/supervisor`, falling back to the\n * pre-rename `<ws>/.loops/supervisor` so runs written by older supervisors stay analyzable.\n */\nexport async function findSupervisorRunDirIn(ws: string): Promise<string | null> {\n for (const stateDir of ['.agent', '.loops']) {\n const root = join(ws, stateDir, 'supervisor')\n const entries = await readdir(root, { withFileTypes: true }).catch(() => [])\n const dirs = entries.filter((e) => e.isDirectory()).map((e) => join(root, e.name))\n if (dirs[0] !== undefined) return dirs[0]\n }\n return null\n}\n\nexport interface LoopsReaderOptions {\n /** Override the workspace dir (default `<runDir>/ws`). */\n readonly ws?: string\n /** Delivered patch path (default: `patchPath` from result.json). */\n readonly patchPath?: string\n /** opencode sqlite store; set to `null` to skip the worker-token join entirely. */\n readonly opencodeDb?: string | null\n /** Ledger to fall back to when the run has no `judge.json` (matched on iid + arm + runDir). */\n readonly ledgerPath?: string\n}\n\n/**\n * Read a loops supervisor run directory into source bytes. Never throws on a\n * missing artifact — an absent file becomes a `null` field, which is what makes\n * the dependent metric `unavailable` instead of 0.\n */\nexport async function readLoopsSupervisorRun(\n runDir: string,\n opts: LoopsReaderOptions = {},\n): Promise<SupervisorRunSources> {\n const ws = opts.ws ?? join(runDir, 'ws')\n const supRunDir = await findSupervisorRunDirIn(ws)\n const result = await readMaybe(join(runDir, 'result.json'))\n const resultObj = parseJson(result)\n const journal = supRunDir === null ? null : await readMaybe(join(supRunDir, 'journal.jsonl'))\n const journalWorkerSpawns = parseJsonl(journal).filter(\n (event) =>\n event.kind === 'spawned' && typeof event.parent === 'string' && event.role !== 'supervisor',\n ).length\n\n let workers: WorkerLogSource[] | null = null\n let workersMissingReason: string | null = null\n const workerCwds: string[] = []\n let workerStarts = 0\n if (supRunDir === null) {\n workersMissingReason = `no supervisor run dir under ${join(ws, '.agent', 'supervisor')} (or legacy ${join(ws, '.loops', 'supervisor')})`\n } else {\n const workersDir = join(supRunDir, 'workers')\n const entries = await readdir(workersDir).catch(() => null)\n if (entries === null) {\n workersMissingReason = `workers/ directory absent under ${supRunDir}`\n } else {\n const labels = [\n ...new Set(\n entries\n .filter((f) => f.endsWith('.ndjson'))\n .map((f) => f.replace(/\\.inbox\\.ndjson$/, '').replace(/\\.ndjson$/, '')),\n ),\n ].sort()\n workers = []\n for (const label of labels) {\n const events = await readMaybe(join(workersDir, `${label}.ndjson`))\n const inbox = await readMaybe(join(workersDir, `${label}.inbox.ndjson`))\n const patch = await readMaybe(join(workersDir, `${label}.patch`))\n const eventRows = parseJsonl(events)\n const startedRows = eventRows.filter((event) => event.kind === 'started')\n workerStarts += startedRows.length\n const startedIds = startedRows\n .map((event) =>\n typeof event.workerId === 'string'\n ? event.workerId\n : typeof event.agentId === 'string'\n ? event.agentId\n : null,\n )\n .filter((id): id is string => id !== null)\n const distinctStartedIds = new Set(startedIds)\n const workerId =\n startedRows.length > 0 &&\n startedIds.length === startedRows.length &&\n distinctStartedIds.size === 1\n ? startedIds[0]\n : undefined\n workers.push({\n ...(workerId === undefined ? {} : { workerId }),\n label,\n events,\n inbox,\n patchBytes: patch === null ? null : Buffer.byteLength(patch),\n })\n for (const ev of startedRows) {\n if (ev.kind === 'started' && typeof ev.cwd === 'string') workerCwds.push(ev.cwd)\n }\n }\n }\n }\n\n let harnessWorkerTokens: SupervisorRunSources['harnessWorkerTokens'] = null\n let harnessMissingReason: string | null = null\n let workerCwdsWithoutSessions = 0\n if (opts.opencodeDb === null) {\n harnessMissingReason = 'opencode join disabled'\n } else if (workerCwds.length === 0) {\n harnessMissingReason = 'no worker clone cwds in workers/*.ndjson (nothing to join)'\n } else {\n const db = await openOpencodeDb(opts.opencodeDb ?? DEFAULT_OPENCODE_DB)\n if (db === null) {\n harnessMissingReason = `opencode session store unreadable at ${opts.opencodeDb ?? DEFAULT_OPENCODE_DB}`\n } else {\n try {\n const seen = new Set<string>()\n let sessions = 0\n let input = 0\n let output = 0\n const distinctWorkerCwds = new Set(workerCwds)\n for (const cwd of distinctWorkerCwds) {\n const rows = findOpencodeSessionsByDirectory(db, cwd)\n if (rows.length === 0) workerCwdsWithoutSessions += 1\n for (const row of rows) {\n if (seen.has(row.id)) continue\n seen.add(row.id)\n sessions += 1\n input += row.tokensInput\n output += row.tokensOutput + row.tokensReasoning\n }\n }\n harnessWorkerTokens = { store: 'opencode', sessions, input, output }\n if (workerCwdsWithoutSessions > 0) {\n harnessMissingReason = `${workerCwdsWithoutSessions}/${distinctWorkerCwds.size} worker clone cwds have no opencode session`\n }\n } finally {\n db.close()\n }\n }\n }\n\n const workerInvocations = Math.max(journalWorkerSpawns, workerStarts)\n const workerTokenGaps: string[] = []\n if (workerCwds.length < workerInvocations) {\n workerTokenGaps.push(\n `${workerInvocations - workerCwds.length}/${workerInvocations} worker invocations have no clone cwd for the opencode token join`,\n )\n }\n if (workerInvocations > 0 && harnessWorkerTokens === null) {\n workerTokenGaps.push(harnessMissingReason ?? 'worker harness token join unavailable')\n } else if (workerCwdsWithoutSessions > 0 && harnessMissingReason !== null) {\n workerTokenGaps.push(harnessMissingReason)\n }\n const workerTokenLimit = workerTokenGaps.length === 0 ? null : workerTokenGaps.join('; ')\n\n const patchPath =\n opts.patchPath ?? (typeof resultObj?.patchPath === 'string' ? resultObj.patchPath : null)\n\n let judge = await readMaybe(join(runDir, 'judge.json'))\n let judgeSource = judge === null ? null : join(runDir, 'judge.json')\n if (judge === null && opts.ledgerPath !== undefined) {\n const row = await findLedgerRow(opts.ledgerPath, runDir)\n if (row !== null) {\n judge = JSON.stringify(row)\n judgeSource = `${opts.ledgerPath} (ledger row)`\n }\n }\n\n return {\n runRef: runDir,\n instanceId: typeof resultObj?.iid === 'string' ? resultObj.iid : instanceIdFromPath(runDir),\n arm: typeof resultObj?.arm === 'string' ? resultObj.arm : basename(runDir),\n supRunDir,\n journal,\n brainLog: supRunDir === null ? null : await readMaybe(join(supRunDir, 'brain.jsonl')),\n state: supRunDir === null ? null : await readMaybe(join(supRunDir, 'state.json')),\n progress: supRunDir === null ? null : await readMaybe(join(supRunDir, 'progress.ndjson')),\n workers,\n workersMissingReason,\n result,\n judge,\n judgeSource,\n patch: patchPath === null ? null : await readMaybe(patchPath),\n driverLog: await readMaybe(join(runDir, 'driver.log')),\n harnessWorkerTokens,\n harnessMissingReason,\n // loops prices its own inference, runs a verify per worker, and keeps each\n // worker's patch. A missing external-harness join is declared explicitly.\n limits: {\n ...NO_SOURCE_LIMITS,\n workerTokens: workerTokenLimit,\n },\n traceCommand: null,\n }\n}\n\n/** The loops on-disk layout, as a `SupervisorRunReader`. */\nexport function loopsSupervisorRunReader(\n runDir: string,\n opts: LoopsReaderOptions = {},\n): SupervisorRunReader {\n return { runRef: runDir, read: () => readLoopsSupervisorRun(runDir, opts) }\n}\n\n/** The ledger row whose `runDir` is this run (falling back to iid + arm match). */\nasync function findLedgerRow(\n ledgerPath: string,\n runDir: string,\n): Promise<Record<string, unknown> | null> {\n const rows = parseJsonl(await readMaybe(ledgerPath))\n const exact = rows.find((r) => r.runDir === runDir)\n if (exact !== undefined) return exact\n const iid = instanceIdFromPath(runDir)\n const arm = basename(runDir)\n return rows.find((r) => r.iid === iid && r.arm === arm) ?? null\n}\n\n/** `<outDir>/runs/<iid>/<arm>` → `<iid>`. */\nfunction instanceIdFromPath(runDir: string): string | null {\n const parts = runDir.split('/').filter(Boolean)\n const armIdx = parts.length - 1\n const iid = parts[armIdx - 1]\n return parts[armIdx - 2] === 'runs' && iid !== undefined ? iid : null\n}\n\n// ---------------------------------------------------------------------------\n// Entry point + write helpers.\n// ---------------------------------------------------------------------------\n\n/**\n * Analyze a supervisor run. Accepts a run directory (read through the loops\n * reader), any `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 opts: LoopsReaderOptions = {},\n): Promise<SupervisorRunReport> {\n if (typeof input === 'string') {\n return analyzeSupervisorRunSources(\n (await isRuntimeSupervisorRunDir(input))\n ? await readRuntimeSupervisorRun(input)\n : await readLoopsSupervisorRun(input, opts),\n )\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 extends LoopsReaderOptions {\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 * Read a completed run, write `run-report.json` + `run-report.md` beside its\n * artifacts, and append the headline block to the run log. Never throws on a\n * missing artifact — a run that produced nothing still yields a report whose\n * every metric says why.\n */\nexport async function writeSupervisorRunReport(\n runDir: string,\n opts: WriteSupervisorRunOptions = {},\n): Promise<SupervisorRunReport> {\n const sources = (await isRuntimeSupervisorRunDir(runDir))\n ? await readRuntimeSupervisorRun(runDir)\n : await readLoopsSupervisorRun(runDir, opts)\n const report = analyzeSupervisorRunSources(sources)\n const md = renderSupervisorRunMarkdown(report)\n const dest = opts.reportDir ?? runDir\n const stem = opts.reportDir === undefined ? 'run-report' : supervisorReportStem(runDir)\n if (opts.reportDir !== undefined) await mkdir(opts.reportDir, { recursive: true }).catch(() => {})\n await writeFile(join(dest, `${stem}.json`), JSON.stringify(report, null, 1)).catch(() => {})\n await writeFile(join(dest, `${stem}.md`), md).catch(() => {})\n const headline = renderSupervisorRunHeadline(report)\n if (opts.appendHeadlineTo !== undefined) {\n await appendFile(opts.appendHeadlineTo, `${headline}\\n`).catch(() => {})\n }\n if (opts.echo !== false) console.log(headline)\n return report\n}\n\n/**\n * File stem for out-of-tree reports. Built from the run path's identifying\n * segments — candidate tag (the segment under `arm-runs/`), rep, instance, arm\n * — so two runs of the same instance from different candidates/reps never\n * overwrite each other.\n */\nfunction supervisorReportStem(runDir: string): string {\n const parts = runDir.split('/').filter(Boolean)\n const arm = parts[parts.length - 1] ?? 'cell'\n const iid = parts[parts.length - 2] ?? 'instance'\n const rep = parts.find((p) => /^rep-\\d+$/.test(p))\n const armRunsIdx = parts.indexOf('arm-runs')\n const tag = armRunsIdx >= 0 ? parts[armRunsIdx + 1] : undefined\n return [tag, rep, iid, arm]\n .filter((s): s is string => s !== undefined && s !== 'runs')\n .join('.')\n .replace(/[^A-Za-z0-9._-]/g, '_')\n}\n\n/**\n * Best-effort wrapper for a hot path: a reporting failure must never kill a run\n * that already produced real work. Returns null and logs the reason instead.\n */\nexport async function writeSupervisorRunReportSafe(\n runDir: string,\n opts: WriteSupervisorRunOptions = {},\n): Promise<SupervisorRunReport | null> {\n try {\n return await writeSupervisorRunReport(runDir, opts)\n } catch (err) {\n console.log(\n `RUN-REPORT failed for ${runDir}: ${err instanceof Error ? err.message : String(err)}`,\n )\n return null\n }\n}\n\n/**\n * Report every run under an experiment `outDir` (any depth of\n * `runs/<iid>/<arm>`), write each run's report, and write the rollup at\n * `<outDir>/run-report-round.{json,md}`.\n */\nexport async function reportSupervisorRound(\n outDir: string,\n opts: WriteSupervisorRunOptions & { title?: string } = {},\n): Promise<SupervisorRunRollup> {\n const runDirs = await findSupervisorRunDirs(outDir)\n const reports: SupervisorRunReport[] = []\n for (const runDir of runDirs) {\n const r = await writeSupervisorRunReportSafe(runDir, { ...opts, echo: opts.echo ?? false })\n if (r !== null) reports.push(r)\n }\n const rollup = rollupSupervisorRuns(reports)\n const md = renderSupervisorRollupMarkdown(\n rollup,\n opts.title ?? `Round rollup — ${basename(outDir)}`,\n )\n const dest = opts.reportDir ?? outDir\n if (opts.reportDir !== undefined) await mkdir(opts.reportDir, { recursive: true }).catch(() => {})\n await writeFile(join(dest, 'run-report-round.json'), JSON.stringify(rollup, null, 1)).catch(\n () => {},\n )\n await writeFile(join(dest, 'run-report-round.md'), md).catch(() => {})\n if (opts.appendHeadlineTo !== undefined) {\n await appendFile(opts.appendHeadlineTo, `${md}\\n`).catch(() => {})\n }\n if (opts.echo !== false) console.log(md)\n return rollup\n}\n\n/**\n * Every loops or 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 (\n (await isRuntimeSupervisorRunDir(root)) ||\n (await findSupervisorRunDirIn(join(root, 'ws'))) !== null\n ) {\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 (\n (await isRuntimeSupervisorRunDir(full)) ||\n (await findSupervisorRunDirIn(join(full, 'ws'))) !== null\n ) {\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"],"mappings":";;;;;;AAyCA,SAAgB,YAAY,QAA6B;CACvD,OAAO,EAAE,aAAa,OAAO;AAC/B;AAEA,SAAgB,cAAc,GAA8B;CAC1D,OAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,OAAQ,EAAkB,gBAAgB;AAC1F;;AAGA,SAAgB,aAAa,GAAuD;CAClF,IAAI,cAAc,CAAC,GAAG,OAAO,iBAAiB,EAAE;CAChD,IAAI,MAAM,MAAM,OAAO;CACvB,OAAO,OAAO,CAAC;AACjB;;AA+DA,MAAa,mBAAiC;CAC5C,eAAe;CACf,cAAc;CACd,UAAU;CACV,gBAAgB;CAChB,cAAc;AAChB;AAqGA,MAAa,wBAAwB;AACrC,MAAa,+BAA+B;;;;;;;;;AC7K5C,MAAM,oBAAoB;AAC1B,MAAM,qBACJ;;;;;AAUF,SAAgB,4BACd,KACA,MAAoB,KAAK,KACJ;CACrB,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,OACf,0FACA;CACN,MAAM,cAAc,IAAI,YAAY;CACpC,MAAM,OAAO,oBAAoB,GAAG;CACpC,MAAM,QAAQ,KAAK;CACnB,MAAM,SAAS,UAAU,IAAI,MAAM;CACnC,MAAM,QAAQ,UAAU,IAAI,KAAK;CACjC,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,C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,MAAM,IAAI,CAAC,MAAO,MACrD;IACA,MAAM,KAAK,IAAI;IACf;GACF;GACA,MAAM,KAAK,MAAM,QAAQ,CAAC;EAC5B;CACF;CACA,MAAM,KAAK,MAAM,CAAC;CAClB,OAAO,MAAM,KAAK;AACpB"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/supervisor-run/claude-code-reader.ts"],"sourcesContent":["/**\n * Supervision-tree reader over a THIRD-PARTY harness: Claude Code.\n *\n * `loops-reader.ts` reads a supervisor we wrote, whose journal was designed\n * for this analysis. This reader reads a harness we do not control, whose\n * transcript was designed for replaying a chat — and recovers the same tree\n * from it. If both produce a `SupervisorRunSources`, the tree model is a\n * property of multi-agent runs, not of our journal format.\n *\n * ## Where the tree hides in a Claude Code transcript\n *\n * | Tree fact | Claude Code evidence |\n * |---|---|\n * | spawn | assistant `tool_use` (`Agent` / `Task`), answered by a `tool_result` whose `toolUseResult.agentId` names the child |\n * | settle | a `<task-notification>` block in a later user line: `<task-id>` = agentId, `<status>` |\n * | steer | assistant `tool_use` (`SendMessage`) with `input.to` = agentId — mid-task, to a LIVE child |\n * | delivered | that steer's `tool_result` carrying `success` / `resumedAgentId` |\n * | cancel | assistant `tool_use` (`TaskStop`) targeting an agentId |\n * | brain spend| `message.usage` on the main thread's assistant lines |\n * | worker spend| `message.usage` inside `<session>/subagents/agent-<id>.jsonl` |\n * | depth | a child transcript that itself contains `Agent` tool_use lines |\n *\n * Every one of those is read through `parseClaudeEntries` — the SAME line\n * parser `src/rollout/readers/claude-jsonl.ts` uses for solo rollouts. There\n * is no second transcript parser.\n *\n * ## What Claude Code cannot say\n *\n * It records tokens but never a price, runs no per-worker verify, and keeps no\n * per-worker patch. Those are declared once in `limits`, so the analyzer\n * reports `unavailable — <reason>` instead of the $0 / 0-accepted that summing\n * an empty field would produce. See `SourceLimits`.\n *\n * ## Metric coverage vs the loops journal\n *\n * Measured on a real 52-agent session (fixture:\n * `tests/fixtures/supervisor-run/claude-code-session-*`).\n *\n * | Metric | loops | Claude Code | Why |\n * |---|---|---|---|\n * | workersSpawned / Settled / Cancelled | full | full | spawn tool_use + task-notification + TaskStop |\n * | steers / steersDelivered / steersByWorker | full | full | `SendMessage`; delivery from its tool_result |\n * | waves / waveSizes / maxConcurrency | full | full | derived from spawn/settle instants |\n * | respawns / repeatedLabels | full | full | same derivation |\n * | delegationDepth | full | full | a child transcript's own spawn calls |\n * | timeToFirstSpawn / supervisorWall | full | full | transcript instants |\n * | idleMs / idlePct / workerUtilization | full | PARTIAL | an agent that never notifies is counted live to the end of the transcript |\n * | observeThenRespawn / respawnWithoutEvidence | full | full | ordering of spawn vs settle instants |\n * | workerEvidenceBytes | full | PARTIAL | the child's closing message; 0 for pruned transcripts |\n * | brain tokens in/out + cache | full | full | main-thread `message.usage` |\n * | worker tokens in/out + cache | via harness join | full or unavailable | totals are refused if any spawned transcript was pruned; retained per-worker rows remain available |\n * | perWorker wall | full | full | spawn → settle instants |\n * | accepted / rejected / emptyPass / settledVerdicts | full | NONE | no per-worker verify step exists |\n * | brain/worker/total usd, costPerAcceptedPatch | full | NONE | transcripts carry no price |\n * | patch stats, delivered, verifyPass/Rc | full | NONE | no diff is handed back |\n * | judgeResolved / Score / Passed / Total | full | NONE | no judge in the loop |\n * | driverSteerCalls, brainTruncations | full | NONE | no outer driver log, no per-call finish_reason tap |\n */\n\nimport { readdir, readFile } from 'node:fs/promises'\nimport { basename, dirname, join } from 'node:path'\nimport {\n type ClaudeEntry,\n parseClaudeEntries,\n transcriptFromEntries,\n} from '../rollout/readers/claude-jsonl'\nimport type { SupervisorRunReader, SupervisorRunSources, WorkerLogSource } from './types'\n\n/** Tool names that spawn a child agent. `Task` is the older name for `Agent`. */\nconst DEFAULT_SPAWN_TOOLS = ['Agent', 'Task'] as const\n/** Tool names that deliver a message to an ALREADY-RUNNING child agent. */\nconst DEFAULT_STEER_TOOLS = ['SendMessage'] as const\n/** Tool names that stop a running child agent. */\nconst DEFAULT_CANCEL_TOOLS = ['TaskStop', 'KillAgent'] as const\n\nconst SPEND_UNPRICED =\n 'Claude Code transcripts record token usage but never a price — usd is not in the store'\nconst NO_VERDICTS =\n 'Claude Code runs no per-worker verify step — a subagent reports prose, not pass/fail'\nconst NO_DELIVERABLES =\n 'Claude Code retains no per-worker patch — subagents commit to git, they do not hand back a diff'\n\nexport interface ClaudeCodeReaderOptions {\n /** The main session transcript: `~/.claude/projects/<slug>/<sessionId>.jsonl`. */\n readonly transcriptPath: string\n /**\n * Directory of child transcripts. Defaults to `<transcript-dir>/<sessionId>/subagents`.\n * `null` skips the join, and every per-worker token count becomes unavailable.\n */\n readonly subagentsDir?: string | null\n readonly runRef?: string\n readonly instanceId?: string | null\n readonly arm?: string | null\n readonly spawnTools?: readonly string[]\n readonly steerTools?: readonly string[]\n readonly cancelTools?: readonly string[]\n}\n\nconst isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v)\n\nconst str = (v: unknown): string | null => (typeof v === 'string' ? v : null)\n\ninterface ToolUse {\n readonly id: string\n readonly name: string\n readonly input: Record<string, unknown>\n readonly at: string | null\n}\n\ninterface ToolResult {\n readonly id: string\n readonly at: string | null\n readonly structured: unknown\n readonly text: string\n}\n\n/** Every tool call and tool result on one thread, in order, with instants. */\ninterface ThreadCalls {\n readonly uses: ToolUse[]\n readonly results: Map<string, ToolResult>\n readonly notifications: TaskNotification[]\n readonly firstAt: string | null\n readonly lastAt: string | null\n}\n\ninterface TaskNotification {\n readonly taskId: string\n readonly toolUseId: string | null\n readonly status: string\n readonly summary: string | null\n readonly at: string | null\n}\n\nfunction blockText(content: unknown): string {\n if (typeof content === 'string') return content\n if (!Array.isArray(content)) return ''\n const parts: string[] = []\n for (const b of content) {\n if (isRecord(b) && b.type === 'text' && typeof b.text === 'string') parts.push(b.text)\n }\n return parts.join('\\n')\n}\n\nconst tag = (xml: string, name: string): string | null => {\n const m = xml.match(new RegExp(`<${name}>([\\\\s\\\\S]*?)</${name}>`))\n return m === null ? null : (m[1] as string)\n}\n\n/**\n * Task notifications are the settle instants. A notification fires each time an\n * agent stops, so a resumed agent produces several — they are kept in order and\n * the LAST one is the settle the analyzer sees, with the earlier ones acting as\n * the intermediate stops they actually were.\n */\nfunction parseNotifications(text: string, at: string | null): TaskNotification[] {\n const out: TaskNotification[] = []\n for (const m of text.matchAll(/<task-notification>[\\s\\S]*?<\\/task-notification>/g)) {\n const xml = m[0]\n const taskId = tag(xml, 'task-id')\n if (taskId === null) continue\n out.push({\n taskId: taskId.trim(),\n toolUseId: tag(xml, 'tool-use-id')?.trim() ?? null,\n status: tag(xml, 'status')?.trim() ?? 'unknown',\n summary: tag(xml, 'summary')?.trim() ?? null,\n at,\n })\n }\n return out\n}\n\n/** Project entries of ONE thread (main or a single sidechain) into tool traffic. */\nfunction threadCalls(entries: readonly ClaudeEntry[]): ThreadCalls {\n const uses: ToolUse[] = []\n const results = new Map<string, ToolResult>()\n const notifications: TaskNotification[] = []\n let firstAt: string | null = null\n let lastAt: string | null = null\n\n for (const entry of entries) {\n if (entry.timestamp !== null) {\n if (firstAt === null) firstAt = entry.timestamp\n lastAt = entry.timestamp\n }\n const content = entry.message.content\n if (entry.type === 'assistant') {\n if (!Array.isArray(content)) continue\n for (const block of content) {\n if (!isRecord(block) || block.type !== 'tool_use') continue\n const id = str(block.id)\n const name = str(block.name)\n if (id === null || name === null) continue\n uses.push({\n id,\n name,\n input: isRecord(block.input) ? block.input : {},\n at: entry.timestamp,\n })\n }\n continue\n }\n if (typeof content === 'string') {\n notifications.push(...parseNotifications(content, entry.timestamp))\n continue\n }\n if (!Array.isArray(content)) continue\n for (const block of content) {\n if (!isRecord(block)) continue\n if (block.type === 'tool_result' && typeof block.tool_use_id === 'string') {\n results.set(block.tool_use_id, {\n id: block.tool_use_id,\n at: entry.timestamp,\n structured: entry.toolUseResult,\n text: blockText(block.content),\n })\n } else if (block.type === 'text' && typeof block.text === 'string') {\n notifications.push(...parseNotifications(block.text, entry.timestamp))\n }\n }\n }\n return { uses, results, notifications, firstAt, lastAt }\n}\n\n/**\n * The agent id a spawn produced. Claude Code puts it in the structured\n * `toolUseResult`; the same id is echoed in the result text for transcripts\n * written before that field existed, so both are tried before giving up.\n */\nfunction spawnedAgentId(result: ToolResult | undefined): string | null {\n if (result === undefined) return null\n if (isRecord(result.structured)) {\n const id = str(result.structured.agentId)\n if (id !== null) return id\n }\n return result.text.match(/agentId:\\s*([A-Za-z0-9_-]+)/)?.[1] ?? null\n}\n\ninterface ChildTranscript {\n readonly agentId: string\n readonly path: string\n readonly description: string | null\n readonly spawnToolUseId: string | null\n readonly spawnDepth: number | null\n readonly entries: ClaudeEntry[]\n readonly tokensIn: number\n readonly tokensOut: number\n readonly cacheRead: number\n readonly cacheWrite: number\n readonly firstAt: string | null\n readonly lastAt: string | null\n readonly model: string | null\n /**\n * The child's closing assistant message — what it actually handed back. This\n * is the Claude Code analogue of a worker's `evidence` blob.\n */\n readonly finalReport: string | null\n}\n\nasync function readChildren(dir: string): Promise<ChildTranscript[]> {\n const names = await readdir(dir).catch(() => null)\n if (names === null) return []\n const out: ChildTranscript[] = []\n for (const name of names.filter((n) => n.endsWith('.jsonl')).sort()) {\n const path = join(dir, name)\n const raw = await readFile(path, 'utf8').catch(() => null)\n if (raw === null) continue\n const entries = parseClaudeEntries(raw)\n // A subagent transcript is sidechain end to end — that flag is what marks it\n // a separate invocation rather than a turn of the parent.\n const projected = transcriptFromEntries(entries, { includeSidechain: true })\n const metaRaw = await readFile(path.replace(/\\.jsonl$/, '.meta.json'), 'utf8').catch(() => null)\n let meta: Record<string, unknown> = {}\n if (metaRaw !== null) {\n try {\n const parsed: unknown = JSON.parse(metaRaw)\n if (isRecord(parsed)) meta = parsed\n } catch {\n meta = {}\n }\n }\n const agentId =\n entries.find((e) => e.agentId !== null)?.agentId ??\n name.replace(/^agent-/, '').replace(/\\.jsonl$/, '')\n out.push({\n agentId,\n path,\n description: str(meta.description),\n spawnToolUseId: str(meta.toolUseId),\n spawnDepth: typeof meta.spawnDepth === 'number' ? meta.spawnDepth : null,\n entries,\n tokensIn: projected.usage.tokensIn,\n tokensOut: projected.usage.tokensOut,\n cacheRead: projected.usage.cacheRead,\n cacheWrite: projected.usage.cacheWrite,\n firstAt: projected.startedAt,\n lastAt: projected.endedAt,\n model: projected.model,\n finalReport:\n [...projected.messages]\n .reverse()\n .find((m) => m.role === 'assistant' && typeof m.content === 'string')?.content ?? null,\n })\n }\n return out\n}\n\ninterface SpawnFact {\n readonly agentId: string\n readonly parentId: string\n readonly label: string\n readonly at: string | null\n readonly model: string | null\n}\n\n/** A journal line in the dialect `parseSupervisorTree` reads. */\nconst line = (obj: Record<string, unknown>): string => JSON.stringify(obj)\n\n/**\n * Read a Claude Code session (plus its subagent transcripts) as supervision-tree\n * source bytes. Never throws on a missing artifact.\n */\nexport async function readClaudeCodeSupervisorRun(\n opts: ClaudeCodeReaderOptions,\n): Promise<SupervisorRunSources> {\n const spawnTools = new Set(opts.spawnTools ?? DEFAULT_SPAWN_TOOLS)\n const steerTools = new Set(opts.steerTools ?? DEFAULT_STEER_TOOLS)\n const cancelTools = new Set(opts.cancelTools ?? DEFAULT_CANCEL_TOOLS)\n\n const raw = await readFile(opts.transcriptPath, 'utf8').catch(() => null)\n const sessionId = basename(opts.transcriptPath).replace(/\\.jsonl$/, '')\n const runRef = opts.runRef ?? opts.transcriptPath\n const limits = {\n managerTokens: null,\n workerTokens: null,\n spendUsd: SPEND_UNPRICED,\n workerVerdicts: NO_VERDICTS,\n deliverables: null,\n }\n const traceCommand = `npx --yes @tangle-network/traces@latest analyze --harness claude-code --session ${sessionId}`\n\n if (raw === null) {\n return {\n runRef,\n instanceId: opts.instanceId ?? sessionId,\n arm: opts.arm ?? null,\n supRunDir: null,\n journal: null,\n brainLog: null,\n state: null,\n progress: null,\n workers: null,\n workersMissingReason: `session transcript unreadable at ${opts.transcriptPath}`,\n result: null,\n judge: null,\n judgeSource: null,\n patch: null,\n driverLog: null,\n harnessWorkerTokens: null,\n harnessMissingReason: `session transcript unreadable at ${opts.transcriptPath}`,\n limits: {\n ...limits,\n managerTokens: `session transcript unreadable at ${opts.transcriptPath}`,\n workerTokens: `session transcript unreadable at ${opts.transcriptPath}`,\n deliverables: NO_DELIVERABLES,\n },\n traceCommand,\n }\n }\n\n const allEntries = parseClaudeEntries(raw)\n const main = threadCalls(allEntries.filter((e) => !e.isSidechain))\n const mainTranscript = transcriptFromEntries(allEntries)\n\n const subagentsDir =\n opts.subagentsDir === undefined\n ? join(dirname(opts.transcriptPath), sessionId, 'subagents')\n : opts.subagentsDir\n const children = subagentsDir === null ? [] : await readChildren(subagentsDir)\n const childByAgentId = new Map(children.map((c) => [c.agentId, c]))\n const childBySpawnToolUseId = new Map(\n children.filter((c) => c.spawnToolUseId !== null).map((c) => [c.spawnToolUseId as string, c]),\n )\n\n // Every thread that can spawn: the session itself, plus each child transcript\n // (a child that calls the spawn tool is a second delegation level).\n const threads: Array<{ id: string; calls: ThreadCalls }> = [{ id: sessionId, calls: main }]\n for (const child of children) {\n threads.push({ id: child.agentId, calls: threadCalls(child.entries) })\n }\n\n const spawns: SpawnFact[] = []\n const steersByTarget = new Map<\n string,\n Array<{ requestId: string; at: string | null; delivered: boolean }>\n >()\n const cancels: Array<{ agentId: string; at: string | null }> = []\n const settles: TaskNotification[] = []\n\n for (const thread of threads) {\n for (const use of thread.calls.uses) {\n if (spawnTools.has(use.name)) {\n const result = thread.calls.results.get(use.id)\n const agentId = spawnedAgentId(result) ?? childBySpawnToolUseId.get(use.id)?.agentId ?? null\n if (agentId === null) continue\n const label =\n str(use.input.description) ?? childByAgentId.get(agentId)?.description ?? agentId\n spawns.push({\n agentId,\n parentId: thread.id,\n label,\n // The spawn is complete when the launch call is answered; the tool_use\n // instant is the fallback for a call that never got a result line.\n at: result?.at ?? use.at,\n model: isRecord(result?.structured) ? str(result.structured.resolvedModel) : null,\n })\n continue\n }\n if (steerTools.has(use.name)) {\n const target = str(use.input.to) ?? str(use.input.recipient)\n if (target === null) continue\n const result = thread.calls.results.get(use.id)\n const structured = isRecord(result?.structured) ? result.structured : null\n // `success` is the harness confirming the message reached a live agent;\n // absent, the steer is counted queued but not delivered.\n const delivered = structured?.success === true || str(structured?.resumedAgentId) === target\n const rows = steersByTarget.get(target) ?? []\n rows.push({ requestId: use.id, at: use.at, delivered })\n steersByTarget.set(target, rows)\n continue\n }\n if (cancelTools.has(use.name)) {\n const target = str(use.input.agentId) ?? str(use.input.to) ?? str(use.input.taskId)\n if (target !== null) cancels.push({ agentId: target, at: use.at })\n }\n }\n settles.push(...thread.calls.notifications)\n }\n\n const spawnedIds = new Set(spawns.map((s) => s.agentId))\n const cancelledIds = new Set(\n cancels.filter((c) => spawnedIds.has(c.agentId)).map((c) => c.agentId),\n )\n const startedAt = main.firstAt\n const completedAt = main.lastAt\n\n const journalLines: string[] = [\n line({\n kind: 'spawned',\n id: sessionId,\n parent: null,\n label: `session:${sessionId}`,\n role: 'supervisor',\n at: startedAt,\n }),\n ]\n for (const s of spawns) {\n journalLines.push(\n line({\n kind: 'spawned',\n id: s.agentId,\n parent: s.parentId,\n label: s.label,\n role: 'worker',\n at: s.at,\n }),\n )\n }\n\n // Only the LAST notification per agent is its settle; an earlier one is a stop\n // the supervisor resumed from, which the steer count already records.\n const lastNotification = new Map<string, TaskNotification>()\n for (const n of settles) {\n if (!spawnedIds.has(n.taskId)) continue\n lastNotification.set(n.taskId, n)\n }\n for (const [agentId, n] of lastNotification) {\n if (cancelledIds.has(agentId)) continue\n journalLines.push(\n line({\n kind: 'settled',\n id: agentId,\n status: n.status,\n verdict: n.summary,\n at: n.at,\n // No `spent` key: Claude Code prices nothing, and a zeroed spend object\n // would read as a $0 worker. `limits.spendUsd` carries the reason.\n }),\n )\n }\n // One cancel per agent: Claude Code can emit a stop then a retry-stop for the\n // same agentId, and each raw entry would otherwise mint a duplicate `cancelled`\n // line that double-counts in `workersCancelled`. Keep the last, mirroring the\n // last-notification dedup the settle path already does.\n const lastCancel = new Map<string, { agentId: string; at: string | null }>()\n for (const c of cancels) {\n if (!spawnedIds.has(c.agentId)) continue\n lastCancel.set(c.agentId, c)\n }\n for (const c of lastCancel.values()) {\n journalLines.push(\n line({ kind: 'cancelled', id: c.agentId, reason: 'stopped by supervisor', at: c.at }),\n )\n }\n // `metered` carries the brain's own inference. The token counts are real; the\n // usd stays absent and `limits.spendUsd` explains why.\n journalLines.push(\n line({\n kind: 'metered',\n id: sessionId,\n spend: {\n tokens: {\n input: mainTranscript.usage.tokensIn,\n output: mainTranscript.usage.tokensOut,\n cacheRead: mainTranscript.usage.cacheRead,\n cacheWrite: mainTranscript.usage.cacheWrite,\n },\n },\n at: completedAt,\n }),\n )\n\n const settleAtByAgent = new Map(\n [...lastNotification.entries()].map(([id, n]) => [id, n.at] as const),\n )\n const spawnAtByAgent = new Map(spawns.map((s) => [s.agentId, s.at] as const))\n\n const workers: WorkerLogSource[] = []\n for (const spawn of spawns) {\n const { agentId, label } = spawn\n const events: string[] = []\n const inbox: string[] = []\n const child = childByAgentId.get(agentId) ?? null\n const startAt = child?.firstAt ?? spawnAtByAgent.get(agentId) ?? null\n const endAt = settleAtByAgent.get(agentId) ?? child?.lastAt ?? null\n if (startAt !== null) events.push(line({ kind: 'started', label, at: startAt, agentId }))\n for (const steer of steersByTarget.get(agentId) ?? []) {\n inbox.push(line({ id: steer.requestId, at: steer.at, worker: label, message: 'steer' }))\n events.push(\n line({\n kind: 'message',\n label,\n direction: 'down',\n at: steer.at,\n requestId: steer.requestId,\n delivered: steer.delivered,\n }),\n )\n }\n if (endAt !== null) {\n events.push(\n line({\n kind: 'finished',\n label,\n at: endAt,\n agentId,\n // No `passed` / `patchBytes`: this harness has neither. Emitting\n // `passed: false` here would invent a failed worker.\n // `evidence` is the child's closing message — what it handed back.\n ...(child?.finalReport === null || child?.finalReport === undefined\n ? {}\n : { evidence: child.finalReport }),\n }),\n )\n }\n workers.push({\n workerId: agentId,\n label,\n events: events.length === 0 ? '' : `${events.join('\\n')}\\n`,\n inbox: inbox.length === 0 ? '' : `${inbox.join('\\n')}\\n`,\n patchBytes: null,\n transcriptRef: child?.path ?? null,\n patchPath: null,\n tokensIn: child?.tokensIn ?? null,\n tokensOut: child?.tokensOut ?? null,\n cacheRead: child?.cacheRead ?? null,\n cacheWrite: child?.cacheWrite ?? null,\n })\n }\n\n const joined = children.length\n const harnessWorkerTokens =\n joined === 0\n ? null\n : {\n store: 'claude-code subagent transcripts',\n sessions: joined,\n input: children.reduce((a, c) => a + c.tokensIn, 0),\n output: children.reduce((a, c) => a + c.tokensOut, 0),\n cacheRead: children.reduce((a, c) => a + c.cacheRead, 0),\n cacheWrite: children.reduce((a, c) => a + c.cacheWrite, 0),\n }\n\n const missingChildren = spawns.filter((s) => !childByAgentId.has(s.agentId)).length\n const harnessMissingReason =\n subagentsDir === null\n ? 'subagent transcript join disabled'\n : joined === 0\n ? `no subagent transcripts under ${subagentsDir}`\n : missingChildren === 0\n ? null\n : `${missingChildren}/${spawns.length} spawned agents have no retained transcript under ${subagentsDir} (Claude Code prunes them; their tokens are unrecoverable)`\n\n const liveWorkers = spawns.filter(\n (s) => !lastNotification.has(s.agentId) && !cancelledIds.has(s.agentId),\n ).length\n const state = JSON.stringify({\n id: sessionId,\n // Derived, not asserted: a spawned agent with no notification and no stop\n // is still running, which is exactly what a live transcript looks like.\n status: liveWorkers > 0 ? 'running' : 'idle',\n startedAt,\n completedAt,\n result: { delivered: null },\n })\n\n return {\n runRef,\n instanceId: opts.instanceId ?? sessionId,\n arm: opts.arm ?? null,\n supRunDir: subagentsDir,\n journal: `${journalLines.join('\\n')}\\n`,\n brainLog: null,\n state,\n progress: null,\n workers,\n workersMissingReason: null,\n result: null,\n judge: null,\n judgeSource: null,\n patch: null,\n driverLog: null,\n harnessWorkerTokens,\n harnessMissingReason,\n limits: {\n ...limits,\n workerTokens: spawns.length === 0 ? null : harnessMissingReason,\n deliverables: NO_DELIVERABLES,\n },\n rootTranscriptRef: opts.transcriptPath,\n traceCommand,\n }\n}\n\n/** A `SupervisorRunReader` over a Claude Code session — the same contract loops implements. */\nexport function claudeCodeSupervisorRunReader(opts: ClaudeCodeReaderOptions): SupervisorRunReader {\n return {\n runRef: opts.runRef ?? opts.transcriptPath,\n read: () => readClaudeCodeSupervisorRun(opts),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqEA,MAAM,sBAAsB,CAAC,SAAS,MAAM;;AAE5C,MAAM,sBAAsB,CAAC,aAAa;;AAE1C,MAAM,uBAAuB,CAAC,YAAY,WAAW;AAErD,MAAM,iBACJ;AACF,MAAM,cACJ;AACF,MAAM,kBACJ;AAkBF,MAAM,YAAY,MAChB,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AAEzD,MAAM,OAAO,MAA+B,OAAO,MAAM,WAAW,IAAI;AAiCxE,SAAS,UAAU,SAA0B;CAC3C,IAAI,OAAO,YAAY,UAAU,OAAO;CACxC,IAAI,CAAC,MAAM,QAAQ,OAAO,GAAG,OAAO;CACpC,MAAM,QAAkB,CAAC;CACzB,KAAK,MAAM,KAAK,SACd,IAAI,SAAS,CAAC,KAAK,EAAE,SAAS,UAAU,OAAO,EAAE,SAAS,UAAU,MAAM,KAAK,EAAE,IAAI;CAEvF,OAAO,MAAM,KAAK,IAAI;AACxB;AAEA,MAAM,OAAO,KAAa,SAAgC;CACxD,MAAM,IAAI,IAAI,MAAM,IAAI,OAAO,IAAI,KAAK,iBAAiB,KAAK,EAAE,CAAC;CACjE,OAAO,MAAM,OAAO,OAAQ,EAAE;AAChC;;;;;;;AAQA,SAAS,mBAAmB,MAAc,IAAuC;CAC/E,MAAM,MAA0B,CAAC;CACjC,KAAK,MAAM,KAAK,KAAK,SAAS,mDAAmD,GAAG;EAClF,MAAM,MAAM,EAAE;EACd,MAAM,SAAS,IAAI,KAAK,SAAS;EACjC,IAAI,WAAW,MAAM;EACrB,IAAI,KA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