@tangle-network/agent-eval 1.0.13 → 1.0.15

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 (45) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/analyst/index.js +1 -1
  3. package/dist/cli.js +2 -2
  4. package/dist/contract/index.js +1 -1
  5. package/dist/{default-registry-eCkZFfuF.js → default-registry-BB9_jzyH.js} +2 -2
  6. package/dist/{default-registry-eCkZFfuF.js.map → default-registry-BB9_jzyH.js.map} +1 -1
  7. package/dist/diagnosis/index.d.ts.map +1 -1
  8. package/dist/diagnosis/index.js +19 -13
  9. package/dist/diagnosis/index.js.map +1 -1
  10. package/dist/{exporters-ByLcILYU.js → exporters-BKZLt1Px.js} +2 -2
  11. package/dist/{exporters-ByLcILYU.js.map → exporters-BKZLt1Px.js.map} +1 -1
  12. package/dist/{hf-dataset-DPVQXW5n.js → hf-dataset-Bv114tzB.js} +11 -11
  13. package/dist/{hf-dataset-DPVQXW5n.js.map → hf-dataset-Bv114tzB.js.map} +1 -1
  14. package/dist/index-f09MX_H_.d.ts.map +1 -1
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +6 -9
  17. package/dist/index.js.map +1 -1
  18. package/dist/{integrity-Vx5xgn3s.js → integrity-BHM4voOx.js} +3 -3
  19. package/dist/{integrity-Vx5xgn3s.js.map → integrity-BHM4voOx.js.map} +1 -1
  20. package/dist/{mint-BH_3Ak2x.js → mint-yF51iBgY.js} +2 -2
  21. package/dist/{mint-BH_3Ak2x.js.map → mint-yF51iBgY.js.map} +1 -1
  22. package/dist/multishot/golden/index.d.ts.map +1 -1
  23. package/dist/multishot/golden/index.js +3 -5
  24. package/dist/multishot/golden/index.js.map +1 -1
  25. package/dist/openapi.json +1 -1
  26. package/dist/{render-BVPfP7dc.js → render-CsHLoMUl.js} +70 -47
  27. package/dist/render-CsHLoMUl.js.map +1 -0
  28. package/dist/rl.js +3 -3
  29. package/dist/rollout/index.js +5 -5
  30. package/dist/{rollout-CbOGxuHl.js → rollout-Cu7kHGIe.js} +5 -5
  31. package/dist/{rollout-CbOGxuHl.js.map → rollout-Cu7kHGIe.js.map} +1 -1
  32. package/dist/{rollout-nodes-DKZ3vAYY.js → rollout-nodes-DhSPJ2X7.js} +4 -4
  33. package/dist/rollout-nodes-DhSPJ2X7.js.map +1 -0
  34. package/dist/{schema-YUIXT8iW.js → schema-ChIZfnqY.js} +37 -5
  35. package/dist/schema-ChIZfnqY.js.map +1 -0
  36. package/dist/supervisor-run/index.d.ts +1 -0
  37. package/dist/supervisor-run/index.d.ts.map +1 -1
  38. package/dist/supervisor-run/index.js +3 -3
  39. package/dist/trace-repair/index.d.ts.map +1 -1
  40. package/dist/trace-repair/index.js +2 -5
  41. package/dist/trace-repair/index.js.map +1 -1
  42. package/package.json +1 -1
  43. package/dist/render-BVPfP7dc.js.map +0 -1
  44. package/dist/rollout-nodes-DKZ3vAYY.js.map +0 -1
  45. package/dist/schema-YUIXT8iW.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"rollout-nodes-DKZ3vAYY.js","names":["unhandled","str"],"sources":["../src/supervisor-run/journal-event-group.ts","../src/supervisor-run/types.ts","../src/supervisor-run/source-facts.ts","../src/supervisor-run/terminal-record.ts","../src/supervisor-run/rollout-nodes.ts"],"sourcesContent":["import { isRecord } from '../llm-client/json'\n\ntype ExpandedJournalRow =\n | { succeeded: true; value: readonly Record<string, unknown>[] }\n | { succeeded: false; error: string }\n\n/** Expand a committed group only after every member is readable; never recover its prefix. */\nexport function expandJournalEventGroup(row: Record<string, unknown>): ExpandedJournalRow {\n if (row.kind !== 'events') return { succeeded: true, value: [row] }\n if (typeof row.root !== 'string' || row.root.length === 0) {\n return { succeeded: false, error: 'root must be a non-empty string' }\n }\n if (!Array.isArray(row.events)) {\n return { succeeded: false, error: 'events must be an array' }\n }\n for (const [index, event] of row.events.entries()) {\n if (!isRecord(event)) {\n return { succeeded: false, error: `events[${index}] must be an object` }\n }\n if (typeof event.kind !== 'string' || event.kind.length === 0) {\n return { succeeded: false, error: `events[${index}].kind must be a non-empty string` }\n }\n }\n return {\n succeeded: true,\n value: row.events.map((event) => ({ kind: 'event', root: row.root, event })),\n }\n}\n","/**\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, RolloutWorkspaceCapture } 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/** Turn-level transcript coverage for one worker. */\nexport interface WorkerTurnCoverage {\n readonly dispatched: number\n readonly retained: number\n}\n\n/** A native harness session receipt: the retained artifact, or the store's reason there is none. */\nexport type WorkerNativeSession =\n | {\n readonly status: 'available'\n readonly ref: string\n /** False when Runtime stored a partial copy (the session may continue past it). Absent on\n * receipts that do not say. */\n readonly coverageComplete?: boolean\n /** Stored files the harness writes its conversation to. Zero means the receipt holds other\n * native files only (a model cache, a config). Absent when the descriptor does not list\n * files or the harness has no known session layout. */\n readonly sessionFiles?: number\n }\n | { readonly status: 'unavailable'; readonly reason: string }\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 /**\n * Harness turns this worker dispatched, and how many left a retained output (the turn's own\n * event stream). A settled worker with fewer retained than dispatched lost those turns' record.\n * Null or absent = the store does not record turns.\n */\n readonly turns?: WorkerTurnCoverage | null\n /**\n * The store's receipt for this worker's native harness session: the harness's own session\n * files, which are the only record of what its native subagents did. Null or absent = the\n * store kept no receipt for this worker.\n */\n readonly nativeSession?: WorkerNativeSession | null\n /** Capture receipts in output order. Null means none were retained; absent means this reader has no channel. */\n readonly workspaceCaptures?: readonly RolloutWorkspaceCapture[] | 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 * store-specific 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 * (a Runtime run, an object-store archive, a database, or a test fixture) is a\n * valid source; the Runtime reader 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 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 another\n * layout names its own journal file instead of inheriting a path assumption.\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 /**\n * Runtime `result.json`, the `SupervisedResult` returned by `supervise()`.\n */\n readonly result: string | null\n /**\n * Runtime's terminal failure record (`failure.json`), written when\n * `supervise()` threw before a result landed. `null` = the store was read and\n * holds no such record; `undefined` = the store has no failure document.\n */\n readonly failure?: 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 * Runtime `coordination-log.jsonl` (JSONL of `{ runId, seq, at, event }`):\n * questions, steers, answers and peer mail between nodes. Absent for stores\n * that keep no coordination log; null when the Runtime run dir has none.\n */\n readonly coordinationLog?: 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. Any store that does not\n * retain one must set this to `null`, or omit the path entirely.\n */\n readonly rootTranscriptRef?: string | null\n /** Root capture receipts in output order; null means no retained receipt. */\n readonly rootWorkspaceCaptures?: readonly RolloutWorkspaceCapture[] | 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 /** Exact Runtime capture receipts in journal order; null means capture evidence is unknown. */\n readonly workspaceCaptures: readonly RolloutWorkspaceCapture[] | 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 (`result.json` `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\n/** One source receipt; unknown amounts remain lower bounds when known is false. */\nexport interface NamedResourceReceipt {\n readonly name: Measured<string>\n readonly unit: Measured<string>\n readonly amount: Measured<number>\n readonly known: Measured<boolean>\n}\n\n/** Recorded spend evidence. Inclusive parent and child records must not be summed together. */\nexport interface ResourceSpendRecord {\n readonly nodeId: string | null\n readonly source: string\n readonly kind: 'metered' | 'settled' | 'cancelled' | 'result'\n readonly resources: Measured<readonly NamedResourceReceipt[]>\n}\n\nexport interface EconomicsMetrics {\n /** Per-journal-record resource receipts, without cross-node aggregation. */\n readonly resourceRecords?: Measured<readonly ResourceSpendRecord[]>\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\n/** Which record a run's terminal status was read from, so no source is a silent substitution. */\nexport type SupervisorStatusSource =\n /** Runtime's `result.json` `kind`: the `SupervisedResult` discriminant, read verbatim. */\n | 'runtime-result'\n /** Runtime's `failure.json`: `supervise()` threw before a result landed. */\n | 'runtime-failure'\n\n/** The error a run directory recorded. */\nexport interface TerminalFailure {\n /**\n * Which record carried the error: Runtime's `failure.json`, or the driver\n * rejection inside a `driver-failed` no-winner `result.json`.\n */\n readonly source: 'runtime-failure' | 'runtime-result'\n /** `error.name` exactly as recorded; null when the record has none. */\n readonly name: string | null\n /** `error.message` exactly as recorded; null when the record has none. */\n readonly message: string | null\n /** ISO timestamp the record carries; null when it carries none. */\n readonly at: string | null\n /**\n * True when the directory also holds a settled `result.json`. Runtime writes\n * `failure.json` only when `supervise()` threw, never after a settle, and\n * refuses to re-enter a settled directory, so a failure beside a result is\n * the throw of an earlier attempt that a later attempt outlived. The status\n * is the settled result's; this record explains the retry, not the outcome.\n */\n readonly earlierAttempt: boolean\n}\n\nexport interface OutcomeMetrics {\n /**\n * The run's terminal status, exactly as its Runtime record spells it:\n * `winner` / `no-winner`, or `failed` for a Runtime failure record.\n * `supStatusSource` names the record it came from.\n */\n readonly supStatus: Measured<string>\n readonly supStatusSource: Measured<SupervisorStatusSource>\n /**\n * Runtime's `reason` on a `no-winner` result (`all-children-down`,\n * `budget-exhausted`, `aborted`, `driver-failed`). `null` = the terminal\n * record carries no reason (a winner or a failure record).\n */\n readonly supReason: Measured<string | null>\n /**\n * The recorded error: Runtime's `failure.json`, or the driver rejection a\n * `driver-failed` no-winner carries. `null` = the run recorded a result and\n * no error. A `failure.json` beside a settled result is reported with\n * `earlierAttempt: true`. Unavailable when the store has no terminal record.\n */\n readonly failure: Measured<TerminalFailure | null>\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 /** Exact root capture receipts; null means capture evidence is unknown. */\n readonly rootWorkspaceCaptures: readonly RolloutWorkspaceCapture[] | null\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 /** Per-source receipts remain attached to their comparison cell. */\n readonly resourceRecords?: Measured<readonly ResourceSpendRecord[]>\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 | 'workspace-capture-unavailable'\n | 'workspace-capture-incomplete'\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","import { expandJournalEventGroup } from './journal-event-group'\nimport {\n type Measured,\n type NamedResourceReceipt,\n type ResourceSpendRecord,\n type SupervisorRunNodeRole,\n type SupervisorRunSources,\n unavailable,\n} from './types'\n\n// ---------------------------------------------------------------------------\n// Journal shapes — structurally parsed. The journal is the contract, not the type.\n// ---------------------------------------------------------------------------\n\ninterface JournalEvent {\n kind?: unknown\n id?: unknown\n parent?: unknown\n label?: unknown\n role?: unknown\n profileDigest?: unknown\n runtime?: unknown\n status?: unknown\n verdict?: unknown\n reason?: unknown\n infra?: unknown\n seq?: unknown\n at?: unknown\n spend?: unknown\n spent?: unknown\n}\n\ninterface Tokens {\n input: number\n output: number\n cacheRead: number\n cacheWrite: number\n /** False when the event carried no cache counters at all — not \"zero cached\". */\n hasCache: boolean\n /**\n * False only when the record carried `cacheBreakdownKnown: false` — Runtime's mark for a\n * provider that reported a total without splitting cache reads from cache writes. The\n * counters that ARE present are then a partial split, never a measured \"zero cached\".\n */\n breakdownKnown: boolean\n}\n\ninterface SpendLike {\n readonly resources?: Measured<readonly NamedResourceReceipt[]>\n tokens: Tokens\n /**\n * False only when the record carried `tokensKnown: false` — Runtime's mark for work that\n * HAPPENED with an unreported token count. `tokens` then holds the known subtotal (often\n * zero), never the measured total. An absent flag means the record is complete.\n */\n tokensKnown: boolean\n usd: number\n /**\n * False only when the record carried `usdKnown: false` — work that HAPPENED at a price the\n * provider never reported. `usd` then holds a catalog estimate or zero, never a measured\n * price. An absent flag means the record is complete.\n */\n usdKnown: boolean\n}\n\nexport function asRecord(v: unknown): Record<string, unknown> {\n return typeof v === 'object' && v !== null ? (v as Record<string, unknown>) : {}\n}\n\nfunction num(v: unknown): number {\n return typeof v === 'number' && Number.isFinite(v) ? v : 0\n}\n\nfunction readResources(value: unknown): Measured<readonly NamedResourceReceipt[]> {\n if (value === undefined) return unavailable('resource map not recorded')\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n return unavailable('resource map is malformed')\n }\n return Object.entries(value).map(([name, raw]) => {\n const entry = asRecord(raw)\n return {\n name: name.trim() ? name : unavailable('resource name is empty'),\n unit:\n typeof entry.unit === 'string' && entry.unit.trim()\n ? entry.unit\n : unavailable('resource unit is missing or invalid'),\n amount:\n typeof entry.amount === 'number' && Number.isFinite(entry.amount) && entry.amount >= 0\n ? entry.amount\n : unavailable('resource amount is missing or invalid'),\n known:\n typeof entry.known === 'boolean'\n ? entry.known\n : unavailable('resource completeness is missing or invalid'),\n }\n })\n}\n\nfunction readSpend(v: unknown): SpendLike {\n const rec = asRecord(v)\n const tok = asRecord(rec.tokens)\n const cacheRead = tok.cacheRead ?? tok.cache_read\n const cacheWrite = tok.cacheWrite ?? tok.cache_write\n return {\n tokens: {\n input: num(tok.input),\n output: num(tok.output),\n cacheRead: num(cacheRead),\n cacheWrite: num(cacheWrite),\n hasCache: cacheRead !== undefined || cacheWrite !== undefined,\n breakdownKnown: tok.cacheBreakdownKnown !== false,\n },\n resources: readResources(rec.resources),\n tokensKnown: rec.tokensKnown !== false,\n usd: num(rec.usd),\n usdKnown: rec.usdKnown !== false,\n }\n}\n\nexport function parseJsonl(text: string | null): Record<string, unknown>[] {\n return parseJsonlWithDiagnostics(text).rows\n}\n\ninterface ParsedJsonl {\n readonly rows: Record<string, unknown>[]\n readonly invalidRows: number\n}\n\nfunction parseJsonlWithDiagnostics(text: string | null): ParsedJsonl {\n if (text === null) return { rows: [], invalidRows: 0 }\n const out: Record<string, unknown>[] = []\n let invalidRows = 0\n for (const line of text.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n try {\n const parsed: unknown = JSON.parse(trimmed)\n if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {\n out.push(parsed as Record<string, unknown>)\n } else {\n invalidRows += 1\n }\n } catch {\n invalidRows += 1\n }\n }\n return { rows: out, invalidRows }\n}\n\nexport function parseJsonRecord(text: string | null): Record<string, unknown> | null {\n if (text === null) return null\n try {\n const parsed: unknown = JSON.parse(text)\n return typeof parsed === 'object' && parsed !== null\n ? (parsed as Record<string, unknown>)\n : null\n } catch {\n return null\n }\n}\n\nfunction ms(at: unknown): number | null {\n if (typeof at !== 'string') return null\n const t = Date.parse(at)\n return Number.isFinite(t) ? t : null\n}\n\n// ---------------------------------------------------------------------------\n// The supervision tree, as parsed from the journal event stream.\n// ---------------------------------------------------------------------------\n\nexport interface SpawnRow {\n /** Zero-based row among parsed journal objects. */\n sourceRow: number\n id: string\n parent: string | null\n label: string\n /** Null when the source did not explicitly record a role. */\n role: SupervisorRunNodeRole | null\n /** Exact canonical AgentProfile digest, when the source recorded one. */\n profileDigest: string | null\n /** Exact execution runtime tag, when the source recorded one. */\n runtime: string | null\n at: number | null\n /** False when identity, parentage, label, or role was malformed. */\n valid: boolean\n invalidFields: readonly string[]\n}\n\nexport interface CloseRow {\n id: string\n kind: 'settled' | 'cancelled'\n status: string | null\n /** String verdict from flat journals, or valid/invalid for a structured verdict. */\n verdict: string | null\n /** Structured verdict validity, when recorded. */\n valid: boolean | null\n /** Structured verdict score, preserved without boolean coercion. */\n score: number | null\n /** The verdict exactly as the journal carried it. */\n rawVerdict: unknown | null\n /** Terminal failure detail exactly as recorded. */\n reason: string | null\n /** Whether Runtime classified the failure as infrastructure-caused. */\n infra: boolean | null\n at: number | null\n spend: SpendLike\n /** False when the close event carried no spend object — not \"spent nothing\". */\n hasSpend: boolean\n}\n\nexport interface WorkerLogFacts {\n /** Position in `SupervisorRunSources.workers`, retained for exact evidence paths. */\n sourceIndex: number\n workerId: string | null\n label: string\n /** `false` means the artifact was missing; a captured empty artifact is `true`. */\n inboxCaptured: boolean\n eventsCaptured: boolean\n inboxInvalidRows: number\n eventsInvalidRows: number\n started: number | null\n /** True once a `finished` event was seen — independent of whether its `at` parsed. */\n finished: boolean\n finishedAt: number | null\n passed: boolean | null\n /** Numeric score exactly as the finished event recorded it. */\n score: number | null\n /** `patchBytes` as reported by the finished event (not the patch file's size). */\n finishedPatchBytes: number | null\n evidenceBytes: number\n /** Unique queued request ids, or null when exact accounting is unavailable. */\n steersQueued: number | null\n /** Unique matched request ids acknowledged as delivered, or null when unavailable. */\n steersDelivered: number | null\n steersQueuedUnavailable: string | null\n steersDeliveredUnavailable: string | null\n questions: number\n steerRequests: SteerRequestFact[]\n steerAcknowledgements: SteerAcknowledgementFact[]\n}\n\nexport interface SteerRequestFact {\n /** Durable inbox request id; null when the row did not retain one. */\n requestId: string | null\n row: number\n}\n\nexport interface SteerAcknowledgementFact {\n /** Worker event request id; null when the event cannot be correlated. */\n requestId: string | null\n /** `null` means the acknowledgement omitted delivery status. */\n delivered: boolean | null\n row: number\n}\n\n/**\n * The tree + timeline the report is computed from, exposed because the rollout-row\n * minter needs exactly the same parse (one parser, two consumers).\n */\nexport interface SupervisorTreeFacts {\n readonly resourceRecords?: readonly ResourceSpendRecord[]\n readonly rootId: string | null\n readonly spawns: readonly SpawnRow[]\n readonly closes: readonly CloseRow[]\n readonly workerSpawns: readonly SpawnRow[]\n readonly workerCloses: readonly CloseRow[]\n readonly brain: {\n /**\n * Summed over the root's metered rows that reported a token count. A row Runtime marked\n * `tokensKnown: false` is EXCLUDED and counted in `tokensUnknownCount` instead, because\n * its `tokens` field holds a known subtotal — folding it in would price unreported work\n * at zero tokens.\n */\n tokensIn: number\n tokensOut: number\n cacheRead: number\n cacheWrite: number\n /** False when no metered event carried cache counters — not \"nothing cached\". */\n hasCache: boolean\n /** False when any folded metered row declared `cacheBreakdownKnown: false`. */\n cacheBreakdownKnown: boolean\n /** Root metered rows that reported a token count, and rows that did not. */\n tokensKnownCount: number\n tokensUnknownCount: number\n /** Summed over the root's metered rows that reported a price, on the same rule. */\n usd: number\n /** Root metered rows that reported a price, and rows Runtime marked `usdKnown: false`. */\n usdKnownCount: number\n usdUnknownCount: number\n /** Root-attributed metered events only — every row this object folded or counted. */\n meteredCount: number\n }\n readonly workerLogs: ReadonlyMap<string, WorkerLogFacts>\n /** Every worker source row, including duplicate identities that a map cannot retain. */\n readonly workerLogRows: readonly WorkerLogFacts[]\n /** Every non-empty input journal line; a group occupies one line regardless of its size. */\n readonly journalRows: number\n /**\n * Journal lines this parser could not interpret at all: invalid JSON, non-objects, and\n * JSON objects carrying no record shape it recognizes.\n *\n * This count is what separates \"the run was empty\" from \"the input was unreadable\".\n * Zero spawns with zero invalid rows is a positive claim that nothing happened; it must\n * only ever be made about bytes the parser actually understood.\n */\n readonly journalInvalidRows: number\n /** The `journalInvalidRows` subset that was not valid JSON, or not a JSON object. */\n readonly journalMalformedJsonRows: number\n /**\n * Records recognized but deliberately not folded into the tree, counted by kind — the\n * runtime envelope's `begin` header and the `waiting` / `woken` wait-node events. Kept\n * separate from `journalInvalidRows` because these rows were understood, not rejected.\n */\n readonly journalIgnoredRowsByKind: Readonly<Record<string, number>>\n /**\n * Every metered event read, root-attributed or not. `brain.meteredCount` covers only the\n * root's own spend; a nested driver's metered rows are understood but reach this tree\n * through that driver's settled close. Event counters count each group member, while\n * journalRows and journalInvalidRows count input lines. Without groups, journalRows equals\n * spawns + closes + journalMeteredRows + ignored + journalInvalidRows.\n */\n readonly journalMeteredRows: number\n /** Which dialect(s) the journal's rows were actually written in. */\n readonly journalDialect: SupervisorJournalDialect\n /** Parsed once with the journal and worker artifacts. */\n readonly state: Record<string, unknown> | null\n readonly startedAt: number | null\n readonly completedAt: number | null\n /**\n * First and last stamped tree events (spawned / settled / cancelled /\n * metered) in the journal — the bounds of observed activity. They derive a\n * lower-bound wall for a store that writes no completion stamp.\n */\n readonly firstEventAt: number | null\n readonly lastEventAt: number | null\n}\n\ninterface VerdictFacts {\n label: string | null\n valid: boolean | null\n score: number | null\n raw: unknown | null\n}\n\nfunction readVerdict(v: unknown): VerdictFacts {\n if (typeof v === 'string') return { label: v, valid: null, score: null, raw: v }\n if (typeof v !== 'object' || v === null) {\n return { label: null, valid: null, score: null, raw: null }\n }\n const rec = v as Record<string, unknown>\n const valid = typeof rec.valid === 'boolean' ? rec.valid : null\n return {\n label: valid === null ? null : valid ? 'valid' : 'invalid',\n valid,\n score: typeof rec.score === 'number' && Number.isFinite(rec.score) ? rec.score : null,\n raw: v,\n }\n}\n\nexport function workerSourceKey(\n worker: NonNullable<SupervisorRunSources['workers']>[number],\n): string {\n return worker.workerId ?? worker.label\n}\n\n// ---------------------------------------------------------------------------\n// Journal dialects — the two shapes a supervision journal is actually written in.\n// ---------------------------------------------------------------------------\n\n/**\n * How a journal's rows were shaped on disk.\n *\n * `flat` — one event object per line (`{kind:'spawned', id, ...}`). Claude Code\n * and other adapters may synthesize this shape for the pure analyzer.\n *\n * `runtime-envelope` — the records `agent-runtime`'s `FileSpawnJournal` writes:\n * a `{kind:'begin', root, at}` header followed by `{kind:'event', root, event}`\n * or atomic `{kind:'events', root, events:[...]}` envelopes. It is\n * the layout `createFileRunContext(dir)` produces at `<dir>/spawn-journal.jsonl`.\n * This dialect is READ, not tolerated: agent-runtime is the writer, so a reader\n * that could not interpret it was the defect, and `journalDialect` records which\n * shape the bytes actually had so an unexpected one is never invisible.\n *\n * `mixed` — rows of both shapes in one file. `none` — no interpretable row at all.\n */\nexport type SupervisorJournalDialect = 'none' | 'flat' | 'runtime-envelope' | 'mixed'\n\ntype JournalRowDialect = 'flat' | 'runtime-envelope'\n\n/** Event kinds this parser folds into the tree. */\nconst TREE_EVENT_KINDS = ['spawned', 'settled', 'cancelled', 'metered'] as const\ntype TreeEventKind = (typeof TREE_EVENT_KINDS)[number]\n\n/**\n * Event kinds `agent-runtime` journals that this parser recognizes but does not model as\n * tree nodes: `waiting` arms a wait node and `woken` settles it. They are counted by kind\n * rather than dropped, so \"understood, not modeled\" can never be mistaken for \"absent\".\n */\nconst UNMODELLED_EVENT_KINDS: readonly string[] = ['waiting', 'woken']\n\nfunction treeEventKind(value: unknown): TreeEventKind | null {\n return (TREE_EVENT_KINDS as readonly unknown[]).includes(value) ? (value as TreeEventKind) : null\n}\n\ntype JournalRowReading =\n | {\n outcome: 'event'\n dialect: JournalRowDialect\n kind: TreeEventKind\n event: JournalEvent\n }\n | { outcome: 'ignored'; dialect: JournalRowDialect; kind: string }\n | { outcome: 'unreadable' }\n\n/**\n * Classify one parsed journal row. Every row lands in exactly one outcome — interpreted,\n * recognized-but-not-modeled, or unreadable — because a row that falls through silently is\n * how a run with events reads as a run with none.\n */\nfunction readJournalRow(row: Record<string, unknown>): JournalRowReading {\n const kind = row.kind\n if (typeof kind !== 'string') return { outcome: 'unreadable' }\n\n // agent-runtime's FileSpawnJournal record header. It carries no event.\n if (kind === 'begin' && typeof row.root === 'string') {\n return { outcome: 'ignored', dialect: 'runtime-envelope', kind: 'begin' }\n }\n if (kind === 'event') {\n const inner = row.event\n if (typeof inner !== 'object' || inner === null || Array.isArray(inner)) {\n return { outcome: 'unreadable' }\n }\n const innerKind = (inner as Record<string, unknown>).kind\n if (typeof innerKind !== 'string') return { outcome: 'unreadable' }\n const tree = treeEventKind(innerKind)\n if (tree !== null) {\n return {\n outcome: 'event',\n dialect: 'runtime-envelope',\n kind: tree,\n event: inner as JournalEvent,\n }\n }\n // The envelope proves this IS a journaled event, so an unmodelled kind is recorded by\n // name rather than called unreadable — the caller sees exactly what went uncounted.\n return { outcome: 'ignored', dialect: 'runtime-envelope', kind: innerKind }\n }\n\n const tree = treeEventKind(kind)\n if (tree !== null) {\n return { outcome: 'event', dialect: 'flat', kind: tree, event: row as JournalEvent }\n }\n if (UNMODELLED_EVENT_KINDS.includes(kind)) {\n return { outcome: 'ignored', dialect: 'flat', kind }\n }\n // A bare object with an unknown `kind` could be any record at all — unlike the envelope\n // case there is no evidence it is a journal event, so it counts as unreadable (fail closed).\n return { outcome: 'unreadable' }\n}\n\nfunction summarizeDialect(seen: ReadonlySet<JournalRowDialect>): SupervisorJournalDialect {\n if (seen.size === 0) return 'none'\n if (seen.size > 1) return 'mixed'\n return seen.has('runtime-envelope') ? 'runtime-envelope' : 'flat'\n}\n\n/** One spawned event as a row; a field that is present but unusable marks the row invalid. */\nfunction spawnRowOf(\n ev: JournalEvent,\n id: string,\n sourceRow: number,\n rootId: string | null,\n): SpawnRow {\n const parent = typeof ev.parent === 'string' && ev.parent.length > 0 ? ev.parent : null\n const label = typeof ev.label === 'string' ? ev.label : ''\n const invalidFields: string[] = []\n if (id.length === 0) invalidFields.push('id')\n const parentOmittedForFirstRoot = ev.parent === undefined && rootId === null\n if (\n ev.parent !== null &&\n !parentOmittedForFirstRoot &&\n !(typeof ev.parent === 'string' && ev.parent.length > 0)\n ) {\n invalidFields.push('parent')\n }\n if (label.length === 0) invalidFields.push('label')\n if (ev.role !== undefined && ev.role !== 'supervisor' && ev.role !== 'worker') {\n invalidFields.push('role')\n }\n if (\n ev.profileDigest !== undefined &&\n !(typeof ev.profileDigest === 'string' && ev.profileDigest.length > 0)\n ) {\n invalidFields.push('profileDigest')\n }\n if (ev.runtime !== undefined && !(typeof ev.runtime === 'string' && ev.runtime.length > 0)) {\n invalidFields.push('runtime')\n }\n const role: SupervisorRunNodeRole | null =\n ev.role === 'supervisor' || ev.role === 'worker' ? ev.role : null\n const valid = invalidFields.length === 0\n if (valid && parent === null && rootId === null) rootId = id\n return {\n sourceRow,\n id,\n parent,\n label,\n role,\n profileDigest:\n typeof ev.profileDigest === 'string' && ev.profileDigest.length > 0 ? ev.profileDigest : null,\n runtime: typeof ev.runtime === 'string' && ev.runtime.length > 0 ? ev.runtime : null,\n at: ms(ev.at),\n valid,\n invalidFields,\n }\n}\n\n/** A settled event as a close row, with its verdict and spend. */\nfunction settledCloseOf(ev: JournalEvent, id: string): CloseRow {\n const verdict = readVerdict(ev.verdict)\n return {\n id,\n kind: 'settled',\n status: typeof ev.status === 'string' ? ev.status : null,\n verdict: verdict.label,\n valid: verdict.valid,\n score: verdict.score,\n rawVerdict: verdict.raw,\n reason: typeof ev.reason === 'string' ? ev.reason : null,\n infra: typeof ev.infra === 'boolean' ? ev.infra : null,\n at: ms(ev.at),\n spend: readSpend(ev.spent),\n hasSpend: asRecord(ev.spent).tokens !== undefined,\n }\n}\n\n/** A cancelled event as a close row: it carries no verdict and no spend. */\nfunction cancelledCloseOf(ev: JournalEvent, id: string): CloseRow {\n return {\n id,\n kind: 'cancelled',\n status: 'cancelled',\n verdict: typeof ev.reason === 'string' ? ev.reason : null,\n valid: null,\n score: null,\n rawVerdict: typeof ev.reason === 'string' ? ev.reason : null,\n reason: typeof ev.reason === 'string' ? ev.reason : null,\n infra: null,\n at: ms(ev.at),\n spend: {\n tokens: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n hasCache: false,\n breakdownKnown: true,\n },\n tokensKnown: true,\n usd: 0,\n usdKnown: true,\n },\n hasSpend: false,\n }\n}\n\n/** What the journal rows add up to: spawn and close rows, the root, and the rows set aside. */\ninterface JournalReading {\n spawns: SpawnRow[]\n closes: CloseRow[]\n rootId: string | null\n unreadableRows: number\n ignoredByKind: Map<string, number>\n dialectsSeen: Set<JournalRowDialect>\n resourceRecords: ResourceSpendRecord[]\n meteredRows: Array<{ id: string; spend: SpendLike; at: number | null }>\n}\n\nfunction readJournal(events: Record<string, unknown>[]): JournalReading {\n const spawns: SpawnRow[] = []\n const closes: CloseRow[] = []\n let rootId: string | null = null\n let unreadableRows = 0\n const ignoredByKind = new Map<string, number>()\n const dialectsSeen = new Set<JournalRowDialect>()\n const resourceRecords: ResourceSpendRecord[] = []\n const meteredRows: Array<{ id: string; spend: SpendLike; at: number | null }> = []\n for (const [sourceRow, row] of events.entries()) {\n const expanded = expandJournalEventGroup(row)\n if (!expanded.succeeded) {\n unreadableRows += 1\n continue\n }\n if (expanded.value.length === 0) {\n dialectsSeen.add('runtime-envelope')\n ignoredByKind.set('events', (ignoredByKind.get('events') ?? 0) + 1)\n }\n for (const [eventIndex, eventRow] of expanded.value.entries()) {\n const reading = readJournalRow(eventRow)\n if (reading.outcome === 'unreadable') {\n unreadableRows += 1\n continue\n }\n dialectsSeen.add(reading.dialect)\n if (reading.outcome === 'ignored') {\n ignoredByKind.set(reading.kind, (ignoredByKind.get(reading.kind) ?? 0) + 1)\n continue\n }\n const { kind, event: ev } = reading\n const id = typeof ev.id === 'string' ? ev.id : ''\n if (kind === 'metered' || kind === 'settled' || kind === 'cancelled') {\n const field = kind === 'metered' ? 'spend' : 'spent'\n const prefix =\n row.kind === 'events'\n ? `events[${eventIndex}].`\n : reading.dialect === 'runtime-envelope'\n ? 'event.'\n : ''\n resourceRecords.push({\n nodeId: id || null,\n kind,\n source: `journal.rows[${sourceRow}].${prefix}${field}.resources`,\n resources: readResources(asRecord(kind === 'metered' ? ev.spend : ev.spent).resources),\n })\n }\n if (kind === 'spawned') {\n const spawn = spawnRowOf(ev, id, sourceRow, rootId)\n if (spawn.valid && spawn.parent === null && rootId === null) rootId = id\n spawns.push(spawn)\n } else if (kind === 'settled') {\n closes.push(settledCloseOf(ev, id))\n } else if (kind === 'cancelled') {\n closes.push(cancelledCloseOf(ev, id))\n } else if (kind === 'metered') {\n // Deferred: rows are attributed after the loop, once the root is known, so a metered\n // event that precedes the root spawn is never misattributed.\n meteredRows.push({ id, spend: readSpend(ev.spend), at: ms(ev.at) })\n } else {\n // `TREE_EVENT_KINDS` and these branches are one contract: adding a kind to the set\n // without a branch here would silently drop its rows, which is the defect this\n // accounting exists to prevent. The compiler refuses the omission.\n const unhandled: never = kind\n throw new Error(`unhandled journal event kind ${JSON.stringify(unhandled)}`)\n }\n }\n }\n return {\n spawns,\n closes,\n rootId,\n unreadableRows,\n ignoredByKind,\n dialectsSeen,\n resourceRecords,\n meteredRows,\n }\n}\n\n/** Only root-attributed metered events are the supervisor brain's own spend. A nested driver meters under its own id; its spend reaches this tree through its settled close, so folding it into the brain here would count the same tokens twice. */\nfunction foldBrainSpend(\n meteredRows: JournalReading['meteredRows'],\n rootId: string | null,\n): SupervisorTreeFacts['brain'] {\n let brainIn = 0\n let brainOut = 0\n let brainCacheRead = 0\n let brainCacheWrite = 0\n let brainHasCache = false\n let brainCacheBreakdownKnown = true\n let brainTokensKnownCount = 0\n let brainTokensUnknownCount = 0\n let brainUsd = 0\n let brainUsdKnownCount = 0\n let brainUsdUnknownCount = 0\n let meteredCount = 0\n for (const row of meteredRows) {\n if (rootId === null || row.id !== rootId) continue\n if (row.spend.tokensKnown) {\n brainIn += row.spend.tokens.input\n brainOut += row.spend.tokens.output\n brainCacheRead += row.spend.tokens.cacheRead\n brainCacheWrite += row.spend.tokens.cacheWrite\n brainHasCache = brainHasCache || row.spend.tokens.hasCache\n brainCacheBreakdownKnown = brainCacheBreakdownKnown && row.spend.tokens.breakdownKnown\n brainTokensKnownCount += 1\n } else {\n brainTokensUnknownCount += 1\n }\n if (row.spend.usdKnown) {\n brainUsd += row.spend.usd\n brainUsdKnownCount += 1\n } else {\n brainUsdUnknownCount += 1\n }\n meteredCount += 1\n }\n return {\n tokensIn: brainIn,\n tokensOut: brainOut,\n cacheRead: brainCacheRead,\n cacheWrite: brainCacheWrite,\n hasCache: brainHasCache,\n cacheBreakdownKnown: brainCacheBreakdownKnown,\n tokensKnownCount: brainTokensKnownCount,\n tokensUnknownCount: brainTokensUnknownCount,\n usd: brainUsd,\n usdKnownCount: brainUsdKnownCount,\n usdUnknownCount: brainUsdUnknownCount,\n meteredCount,\n }\n}\n\n/** Steer counts from a worker's inbox and acknowledgements, or the reason they cannot be stated exactly. */\nfunction accountSteers(facts: WorkerLogFacts): void {\n const requestsById = new Map<string, number>()\n for (const request of facts.steerRequests) {\n if (request.requestId === null) continue\n requestsById.set(request.requestId, (requestsById.get(request.requestId) ?? 0) + 1)\n }\n const acknowledgementsById = new Map<string, SteerAcknowledgementFact[]>()\n for (const acknowledgement of facts.steerAcknowledgements) {\n if (acknowledgement.requestId === null) continue\n const matches = acknowledgementsById.get(acknowledgement.requestId) ?? []\n matches.push(acknowledgement)\n acknowledgementsById.set(acknowledgement.requestId, matches)\n }\n const queueProblems: string[] = []\n if (!facts.inboxCaptured) queueProblems.push('inbox absent')\n if (!facts.eventsCaptured) queueProblems.push('events absent')\n if (facts.inboxInvalidRows > 0) queueProblems.push('inbox contains malformed rows')\n if (facts.eventsInvalidRows > 0) queueProblems.push('events contain malformed rows')\n if (facts.steerRequests.some((request) => request.requestId === null)) {\n queueProblems.push('queued request id missing')\n }\n if ([...requestsById.values()].some((count) => count > 1)) {\n queueProblems.push('queued request id duplicated')\n }\n if (facts.steerAcknowledgements.some((acknowledgement) => acknowledgement.requestId === null)) {\n queueProblems.push('acknowledgement request id missing')\n }\n if ([...acknowledgementsById.keys()].some((id) => !requestsById.has(id))) {\n queueProblems.push('acknowledgement has no queued request')\n }\n if (queueProblems.length === 0) {\n facts.steersQueued = requestsById.size\n } else {\n facts.steersQueuedUnavailable = [...new Set(queueProblems)].join('; ')\n }\n\n const deliveryProblems = [...queueProblems]\n if ([...acknowledgementsById.values()].some((rows) => rows.length > 1)) {\n deliveryProblems.push('acknowledgement request id duplicated')\n }\n if (facts.steerAcknowledgements.some((acknowledgement) => acknowledgement.delivered === null)) {\n deliveryProblems.push('acknowledgement delivery status missing')\n }\n if (deliveryProblems.length === 0) {\n facts.steersDelivered = [...requestsById.keys()].filter((id) => {\n const acknowledgement = acknowledgementsById.get(id)\n return acknowledgement?.length === 1 && acknowledgement[0]?.delivered === true\n }).length\n } else {\n facts.steersDeliveredUnavailable = [...new Set(deliveryProblems)].join('; ')\n }\n}\n\n/** Everything one worker's inbox and event log say: timing, verdict, questions and steer accounting. */\nfunction readWorkerLog(\n w: NonNullable<SupervisorRunSources['workers']>[number],\n sourceIndex: number,\n): WorkerLogFacts {\n const facts: WorkerLogFacts = {\n sourceIndex,\n workerId: w.workerId ?? null,\n label: w.label,\n inboxCaptured: w.inbox !== null,\n eventsCaptured: w.events !== null,\n inboxInvalidRows: 0,\n eventsInvalidRows: 0,\n started: null,\n finished: false,\n finishedAt: null,\n passed: null,\n score: null,\n finishedPatchBytes: null,\n evidenceBytes: 0,\n steersQueued: null,\n steersDelivered: null,\n steersQueuedUnavailable: null,\n steersDeliveredUnavailable: null,\n questions: 0,\n steerRequests: [],\n steerAcknowledgements: [],\n }\n const parsedInbox = parseJsonlWithDiagnostics(w.inbox)\n const parsedEvents = parseJsonlWithDiagnostics(w.events)\n facts.inboxInvalidRows = parsedInbox.invalidRows\n facts.eventsInvalidRows = parsedEvents.invalidRows\n for (const [row, req] of parsedInbox.rows.entries()) {\n if (typeof req.message !== 'string' || req.message.trim().length === 0) continue\n facts.steerRequests.push({\n requestId: typeof req.id === 'string' && req.id.length > 0 ? req.id : null,\n row,\n })\n }\n for (const [row, ev] of parsedEvents.rows.entries()) {\n const kind = ev.kind\n if (kind === 'message') {\n if (ev.direction === 'up') {\n facts.questions += 1\n continue\n }\n facts.steerAcknowledgements.push({\n requestId:\n typeof ev.requestId === 'string' && ev.requestId.length > 0 ? ev.requestId : null,\n delivered: typeof ev.delivered === 'boolean' ? ev.delivered : null,\n row,\n })\n } else if (kind === 'started') {\n facts.started = ms(ev.at)\n } else if (kind === 'finished') {\n facts.finished = true\n facts.finishedAt = ms(ev.at)\n facts.passed = typeof ev.passed === 'boolean' ? ev.passed : null\n facts.score = typeof ev.score === 'number' && Number.isFinite(ev.score) ? ev.score : null\n facts.finishedPatchBytes = typeof ev.patchBytes === 'number' ? ev.patchBytes : null\n facts.evidenceBytes = typeof ev.evidence === 'string' ? ev.evidence.length : 0\n }\n }\n accountSteers(facts)\n return facts\n}\n\n/** The earliest and latest stamped event across spawns, closes and metered rows. */\nfunction eventSpan(\n spawns: SpawnRow[],\n closes: CloseRow[],\n meteredRows: JournalReading['meteredRows'],\n): { firstEventAt: number | null; lastEventAt: number | null } {\n let firstEventAt: number | null = null\n let lastEventAt: number | null = null\n const widenEventSpan = (at: number | null): void => {\n if (at === null) return\n if (firstEventAt === null || at < firstEventAt) firstEventAt = at\n if (lastEventAt === null || at > lastEventAt) lastEventAt = at\n }\n for (const spawn of spawns) widenEventSpan(spawn.at)\n for (const close of closes) widenEventSpan(close.at)\n for (const metered of meteredRows) widenEventSpan(metered.at)\n return { firstEventAt, lastEventAt }\n}\n\nexport function parseSupervisorTree(src: SupervisorRunSources): SupervisorTreeFacts {\n const parsedJournal = parseJsonlWithDiagnostics(src.journal)\n const events = parsedJournal.rows\n const state = parseJsonRecord(src.state)\n\n const {\n spawns,\n closes,\n rootId,\n unreadableRows,\n ignoredByKind,\n dialectsSeen,\n resourceRecords,\n meteredRows,\n } = readJournal(events)\n const brain = foldBrainSpend(meteredRows, rootId)\n\n const workerSpawns = spawns.filter((s) => s.valid && s.id !== rootId)\n const workerIds = new Set(workerSpawns.map((s) => s.id))\n const workerCloses = closes.filter((c) => workerIds.has(c.id))\n\n const workerLogs = new Map<string, WorkerLogFacts>()\n const workerLogRows: WorkerLogFacts[] = []\n for (const [sourceIndex, w] of (src.workers ?? []).entries()) {\n const facts = readWorkerLog(w, sourceIndex)\n workerLogRows.push(facts)\n workerLogs.set(workerSourceKey(w), facts)\n }\n\n const startedAt = ms(state?.startedAt) ?? spawns[0]?.at ?? null\n const rootClose = rootId === null ? null : closes.find((close) => close.id === rootId)\n const completedAt = ms(state?.completedAt) ?? rootClose?.at ?? null\n\n const { firstEventAt, lastEventAt } = eventSpan(spawns, closes, meteredRows)\n\n const result = parseJsonRecord(src.result)\n if (result && Object.hasOwn(result, 'spentTotal')) {\n resourceRecords.push({\n nodeId: rootId,\n kind: 'result',\n source: 'result.spentTotal.resources',\n resources: readResources(asRecord(result.spentTotal).resources),\n })\n }\n\n return {\n resourceRecords,\n rootId,\n spawns,\n closes,\n workerSpawns,\n workerCloses,\n brain,\n workerLogs,\n workerLogRows,\n journalRows: events.length + parsedJournal.invalidRows,\n journalInvalidRows: parsedJournal.invalidRows + unreadableRows,\n journalMalformedJsonRows: parsedJournal.invalidRows,\n journalIgnoredRowsByKind: Object.fromEntries(ignoredByKind),\n journalMeteredRows: meteredRows.length,\n journalDialect: summarizeDialect(dialectsSeen),\n state,\n startedAt,\n completedAt,\n firstEventAt,\n lastEventAt,\n }\n}\n\n/** A recorded non-empty string; whitespace is retained as source evidence. */\nexport function nonEmptyString(value: unknown): string | null {\n return typeof value === 'string' && value.length > 0 ? value : null\n}\n\nexport function recordOrNull(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","/**\n * The run's terminal record, read from the documents the store wrote when the\n * run ended. Runtime's own record outranks every other source: `result.json` is\n * the `SupervisedResult` that `supervise()` returned, verbatim, and its `kind`\n * is the run's status. `failure.json` is the record Runtime writes when\n * `supervise()` threw before a result landed. Runtime's result and failure\n * records are the only terminal status contract; state is timing metadata.\n *\n * Pure: takes already-parsed documents and returns `Measured` values. The\n * analyzer and the rollout minter share it so a run never has two statuses.\n */\n\nimport { asRecord, nonEmptyString as str } from './source-facts'\nimport {\n type Measured,\n type SupervisorStatusSource,\n type TerminalFailure,\n unavailable,\n} from './types'\n\n/** The reason every terminal field reads `unavailable` when no store wrote one. */\nexport const NO_TERMINAL_RECORD =\n 'no terminal record: Runtime result.json kind or Runtime failure.json'\n\n/** The status reported for a run whose directory holds Runtime's failure record and no result. */\nexport const RUNTIME_FAILED_STATUS = 'failed'\n\nexport interface TerminalRecordInput {\n /** Runtime state document, parsed; null when absent. */\n readonly state: Record<string, unknown> | null\n /** Runtime `result.json`, parsed; null when absent. */\n readonly result: Record<string, unknown> | null\n /**\n * Runtime's `failure.json`, parsed. `null` when the store was read and holds\n * none; `undefined` when the store has no such document type.\n */\n readonly failure: Record<string, unknown> | null | undefined\n}\n\nexport interface TerminalRecord {\n readonly supStatus: Measured<string>\n readonly supStatusSource: Measured<SupervisorStatusSource>\n /**\n * Runtime's `reason` on a `no-winner` result. `null` when the record carries\n * none (a winner or a failure record).\n */\n readonly supReason: Measured<string | null>\n /** The recorded error. `null` when the run recorded a result and no error. */\n readonly failure: Measured<TerminalFailure | null>\n /**\n * True when the run recorded a delivered Runtime `winner`; false on every\n * other recorded terminal state; null when no terminal record exists.\n */\n readonly completed: boolean | null\n}\n\nfunction errorRecord(\n doc: Record<string, unknown>,\n source: TerminalFailure['source'],\n earlierAttempt: boolean,\n): TerminalFailure | null {\n if (typeof doc.error !== 'object' || doc.error === null) return null\n const error = asRecord(doc.error)\n return {\n source,\n name: str(error.name),\n message: str(error.message),\n at: str(doc.at),\n earlierAttempt,\n }\n}\n\nexport function readTerminalRecord(input: TerminalRecordInput): TerminalRecord {\n const { result } = input\n const resultKind = str(result?.kind)\n const settled = resultKind !== null && result !== null\n const failureRecord =\n input.failure === null || input.failure === undefined\n ? null\n : errorRecord(input.failure, 'runtime-failure', settled)\n\n if (settled) {\n // Runtime's settle record is the status. A failure record beside it is an\n // earlier attempt's throw (Runtime never writes one after a settle), kept\n // as the recorded error with `earlierAttempt` set; a `driver-failed`\n // no-winner carries its own rejection instead.\n return {\n supStatus: resultKind,\n supStatusSource: 'runtime-result',\n supReason: str(result.reason),\n failure: failureRecord ?? errorRecord(result, 'runtime-result', false),\n completed: resultKind === 'winner',\n }\n }\n\n if (failureRecord !== null) {\n return {\n supStatus: RUNTIME_FAILED_STATUS,\n supStatusSource: 'runtime-failure',\n supReason: null,\n failure: failureRecord,\n completed: false,\n }\n }\n if (input.failure !== null && input.failure !== undefined) {\n // The document exists but carries no `error` object. The run still ended in\n // a failure; only the detail is missing, and it says so.\n return {\n supStatus: RUNTIME_FAILED_STATUS,\n supStatusSource: 'runtime-failure',\n supReason: null,\n failure: unavailable('Runtime failure.json carries no error record'),\n completed: false,\n }\n }\n\n return {\n supStatus: unavailable(NO_TERMINAL_RECORD),\n supStatusSource: unavailable(NO_TERMINAL_RECORD),\n supReason: unavailable(NO_TERMINAL_RECORD),\n failure: unavailable(NO_TERMINAL_RECORD),\n completed: null,\n }\n}\n","/**\n * The supervision tree as `tangle.rollout.v1` rows.\n *\n * A supervisor run IS a tree of rollouts, so its nodes are not a new shape:\n * the root becomes one `RolloutLine` with `role: 'supervisor'`, and every\n * spawned invocation keeps its explicit supervisor/worker role with\n * `parent_rollout_id` pointing at its spawner. The rows append to the same\n * ledger as solo-agent rollouts and join to them with the same keys.\n *\n * What the journal CANNOT supply is the transcript: a worker's messages live\n * in its harness store (opencode sqlite, Claude Code jsonl), which the\n * `src/rollout/readers/*` intake readers own. Rows minted here are therefore\n * GAP lines (`messages: []`, `provenance.gap` set) carrying identity,\n * structure, outcome and cost. Runtime workspace receipts remain attached in\n * `provenance.workspace_captures`; their archives stay at the recorded refs.\n * Hydrating messages is the intake readers' job, keyed on `artifacts.transcript_ref`.\n *\n * Timing lives in `outcome.metrics` (`spawned_at` / `settled_at` / `wall_ms`)\n * rather than a schema field: `tangle.rollout.v1` describes ONE invocation,\n * and the inter-invocation event timeline — which is what waves, concurrency,\n * idle and utilization are computed from — is a property of the journal, not\n * of any single row. The analyzer reads that timeline; these rows carry the\n * per-node facts.\n */\n\nimport { unscreenedRewardFields } from '../rollout/reward'\nimport {\n isRolloutLine,\n ROLLOUT_SCHEMA,\n type RolloutLine,\n type RolloutSplit,\n} from '../rollout/schema'\nimport {\n asRecord,\n parseJsonRecord,\n parseSupervisorTree,\n type SpawnRow,\n type SupervisorTreeFacts,\n} from './source-facts'\nimport { readTerminalRecord } from './terminal-record'\nimport {\n isUnavailable,\n type SupervisorRunSources,\n type SupervisorRunTree,\n type SupervisorRunTreeGap,\n type WorkerLogSource,\n} from './types'\n\nexport interface SupervisorRolloutOptions {\n /** Benchmark/suite id for `task.suite`. Defaults to `'supervisor-run'`. */\n readonly suite?: string\n /** `task.split`. Defaults to `'search'` (the trainable pool). */\n readonly split?: RolloutSplit\n /** Replicate index. Defaults to 0. */\n readonly rep?: number\n /** Sampling seed the campaign pinned. Defaults to null (not recorded). */\n readonly seed?: number | null\n /** `run_id` for every node. Defaults to the supervisor root id, else `runRef`. */\n readonly runId?: string\n /** Harness that drove the supervisor. */\n readonly supervisorHarness?: string | null\n /** Harness that drove the workers. */\n readonly workerHarness?: string | null\n /** Model the supervisor ran on. */\n readonly supervisorModel?: string | null\n /** Model the workers ran on. */\n readonly workerModel?: string | null\n readonly experimentId?: string | null\n readonly candidateId?: string | null\n readonly generation?: number | null\n readonly candidateIndex?: number | null\n /** Pins `provenance.captured_at`; defaults to now. */\n readonly capturedAt?: string\n}\n\nconst EMPTY_COST = {\n usd: null,\n tokens_in: null,\n tokens_out: null,\n tokens_reasoning: null,\n cache_read: null,\n cache_write: null,\n wall_s: null,\n} as const\n\nfunction hasWorkerId(\n worker: WorkerLogSource,\n): worker is WorkerLogSource & { readonly workerId: string } {\n return worker.workerId !== undefined\n}\n\n/**\n * Mint the supervision tree as rollout rows. Returns the rows plus the gaps\n * that made any of them incomplete — same unavailable-vs-zero discipline as\n * the report: a row with no transcript says WHY, it never pretends to be empty.\n */\nexport function supervisorRunRolloutLines(\n src: SupervisorRunSources,\n opts: SupervisorRolloutOptions = {},\n): SupervisorRunTree {\n return supervisorRunRolloutLinesFromFacts(src, parseSupervisorTree(src), opts)\n}\n\n/** What the root and worker rows share: the parsed run record, the row template and the gap collector. */\nfunction rolloutContext(\n src: SupervisorRunSources,\n tree: SupervisorTreeFacts,\n opts: SupervisorRolloutOptions,\n gaps: SupervisorRunTreeGap[],\n) {\n const state = tree.state\n const result = parseJsonRecord(src.result)\n const judge = parseJsonRecord(src.judge)\n const stateResult = asRecord(state?.result)\n // One derivation with the analyzer, so the root row and the report never\n // disagree about which record the status came from.\n const terminal = readTerminalRecord({\n state,\n result,\n failure: src.failure === undefined ? undefined : parseJsonRecord(src.failure),\n })\n\n const rootId = tree.rootId\n const runId = opts.runId ?? rootId ?? src.runRef\n const suite = opts.suite ?? 'supervisor-run'\n const instanceId = src.instanceId ?? src.runRef\n const split: RolloutSplit = opts.split ?? 'search'\n const capturedAt = opts.capturedAt ?? new Date().toISOString()\n\n const base = {\n schema: ROLLOUT_SCHEMA,\n run_id: runId,\n experiment_id: opts.experimentId ?? null,\n candidate_id: opts.candidateId ?? null,\n generation: opts.generation ?? null,\n candidate_index: opts.candidateIndex ?? null,\n task: {\n suite,\n instance_id: instanceId,\n split,\n seed: opts.seed ?? null,\n rep: opts.rep ?? 0,\n },\n messages: [] as RolloutLine['messages'],\n tool_defs: [] as RolloutLine['tool_defs'],\n } satisfies Partial<RolloutLine> & Record<string, unknown>\n\n const noteCaptureGaps = (\n owner: string,\n nodeId: string,\n captures: SupervisorRunSources['rootWorkspaceCaptures'],\n ): string | null => {\n if (captures === null || captures?.length === 0) {\n gaps.push({\n code: 'workspace-capture-unavailable',\n message: `${owner} has no retained output capture evidence`,\n nodeId,\n })\n return 'workspace capture evidence unavailable'\n }\n let incomplete = false\n for (const [index, capture] of captures?.entries() ?? []) {\n const reasons = [\n capture.projectionGap,\n capture.coverageComplete === false\n ? (capture.incompleteReason ?? 'provider reported incomplete coverage')\n : capture.coverageComplete === null\n ? 'capture coverage was not recorded'\n : null,\n ].filter((reason): reason is string => reason !== null)\n if (reasons.length > 0) {\n incomplete = true\n gaps.push({\n code: 'workspace-capture-incomplete',\n message: `${owner} result ${index + 1}: ${reasons.join('; ')}`,\n nodeId,\n })\n }\n }\n return incomplete ? 'workspace capture evidence incomplete' : null\n }\n return {\n src,\n tree,\n opts,\n gaps,\n state,\n result,\n judge,\n stateResult,\n terminal,\n rootId,\n capturedAt,\n base,\n noteCaptureGaps,\n }\n}\n\ntype RolloutContext = ReturnType<typeof rolloutContext>\n\n/** The supervisor invocation row, or nothing when the journal never named a root. */\nfunction rootRolloutNode(ctx: RolloutContext): RolloutLine | null {\n const {\n src,\n tree,\n opts,\n gaps,\n state,\n result,\n judge,\n stateResult,\n terminal,\n rootId,\n capturedAt,\n noteCaptureGaps,\n base,\n } = ctx\n if (rootId === null) {\n gaps.push({\n code: 'root-spawn-unavailable',\n message: 'no parentless spawned event in the journal',\n })\n return null\n }\n const rootSpawn = tree.spawns.find((spawn) => spawn.valid && spawn.id === rootId)\n const judgeResolved = typeof judge?.resolved === 'boolean' ? judge.resolved : null\n const judgeScore = typeof judge?.score === 'number' ? judge.score : null\n const reward = judgeScore ?? (judgeResolved === null ? null : judgeResolved ? 1 : 0)\n if (reward === null) {\n gaps.push({\n code: 'root-reward-unavailable',\n message: 'no judge verdict for this run',\n nodeId: rootId,\n })\n }\n const wallMs =\n tree.startedAt !== null && tree.completedAt !== null && tree.completedAt >= tree.startedAt\n ? tree.completedAt - tree.startedAt\n : null\n const captures = src.rootWorkspaceCaptures\n const captureGap = noteCaptureGaps(`root ${JSON.stringify(rootId)}`, rootId, captures)\n return {\n ...base,\n rollout_id: rootId,\n parent_rollout_id: null,\n role: rootSpawn?.role ?? 'supervisor',\n policy: {\n harness: opts.supervisorHarness ?? null,\n harness_version: null,\n model: opts.supervisorModel ?? null,\n provider: null,\n profile_commit: null,\n agent_profile_cell_id: rootSpawn?.profileDigest ?? null,\n sampling: null,\n },\n outcome: {\n // `reward` and `realness_gated` are written by one call, in the module\n // that owns the gate. This is the SECOND producer of rollout rewards —\n // the judge verdict in the supervision run dir, not `mintRolloutRows` —\n // and it wrote `reward` by hand while never stating the flag, so\n // `isLineRealnessGated` was structurally false for every supervisor and\n // worker row ever emitted here. `unscreenedRewardFields` is the honest\n // name for what this producer can claim: a supervision journal carries\n // no `RunRecord.outcome.realness`, so no authenticity gate has run on\n // this score, and `realness_gated: false` states that rather than\n // implying it by omission. These rows stay plain `RolloutLine`s, so a\n // caller feeding them to a training exporter must `assertMinted` first.\n ...unscreenedRewardFields(reward),\n reward_source: src.judgeSource,\n verdict: judge ?? null,\n metrics: {\n arm: src.arm,\n sup_status: isUnavailable(terminal.supStatus) ? null : terminal.supStatus,\n sup_verdict: typeof state?.verdict === 'string' ? state.verdict : null,\n delivered: typeof stateResult.delivered === 'boolean' ? stateResult.delivered : null,\n verify_pass: typeof result?.verify_pass === 'boolean' ? result.verify_pass : null,\n started_at: tree.startedAt,\n completed_at: tree.completedAt,\n workers_spawned: tree.workerSpawns.length,\n brain_metered_events: tree.brain.meteredCount,\n runtime: rootSpawn?.runtime ?? null,\n profile_digest: rootSpawn?.profileDigest ?? null,\n },\n is_completed: terminal.completed === true,\n is_truncated: false,\n // A recorded non-delivery names its cause: Runtime's no-winner reason,\n // else the recorded error's message. A run with no terminal record has\n // no error to report, and a delivered run has none.\n error:\n terminal.completed !== false\n ? null\n : !isUnavailable(terminal.supReason) && terminal.supReason !== null\n ? terminal.supReason\n : !isUnavailable(terminal.failure) && terminal.failure !== null\n ? (terminal.failure.message ?? terminal.failure.name)\n : null,\n realness_gated: false,\n },\n cost: {\n ...EMPTY_COST,\n usd:\n src.limits.spendUsd !== null\n ? null\n : typeof stateResult.spentUsd === 'number'\n ? stateResult.spentUsd\n : tree.brain.usd,\n tokens_in: src.limits.managerTokens === null ? tree.brain.tokensIn : null,\n tokens_out: src.limits.managerTokens === null ? tree.brain.tokensOut : null,\n cache_read:\n src.limits.managerTokens === null && tree.brain.hasCache ? tree.brain.cacheRead : null,\n cache_write:\n src.limits.managerTokens === null && tree.brain.hasCache ? tree.brain.cacheWrite : null,\n wall_s: wallMs === null ? null : wallMs / 1000,\n },\n artifacts: {\n patch_path: typeof result?.patchPath === 'string' ? result.patchPath : null,\n run_dir: src.supRunDir,\n // Only a reader's declared artifact: a guessed path would read as retained evidence.\n transcript_ref: src.rootTranscriptRef ?? null,\n },\n provenance: {\n captured_at: capturedAt,\n capture: 'backfill',\n lossy_projection: true,\n ...(captures === undefined ? {} : { workspace_captures: captures }),\n gap: [\n src.rootTranscriptRef == null\n ? 'supervision journal carries structure and spend, not the brain transcript'\n : 'brain transcript retained by reference; messages not inlined into this row',\n captureGap,\n ]\n .filter((reason): reason is string => reason !== null)\n .join('; '),\n },\n }\n}\n\n/** The journal closes and the reader's worker sources, joined to spawns by stable id first and by label only as a fallback. */\nfunction workerLookups(ctx: RolloutContext) {\n const { src, tree } = ctx\n const closeById = new Map(tree.closes.map((c) => [c.id, c]))\n const sourceById = new Map(\n (src.workers ?? []).filter(hasWorkerId).map((worker) => [worker.workerId, worker]),\n )\n const fallbackSourceByLabel = new Map(\n (src.workers ?? [])\n .filter((worker) => worker.workerId === undefined)\n .map((worker) => [worker.label, worker]),\n )\n return { closeById, sourceById, fallbackSourceByLabel }\n}\n\ntype WorkerLookups = ReturnType<typeof workerLookups>\n\n/** One worker row, or nothing when its spawn has no explicit role. */\nfunction workerRolloutNode(\n ctx: RolloutContext,\n lookups: WorkerLookups,\n spawn: SpawnRow,\n): RolloutLine | null {\n const { src, tree, opts, gaps, capturedAt, noteCaptureGaps, base } = ctx\n const { closeById, sourceById, fallbackSourceByLabel } = lookups\n if (spawn.role === null) {\n gaps.push({\n code: 'node-role-unavailable',\n message: `child ${JSON.stringify(spawn.label)} has no explicit invocation role`,\n nodeId: spawn.id,\n })\n return null\n }\n const close = closeById.get(spawn.id) ?? null\n const workerSource = sourceById.get(spawn.id) ?? fallbackSourceByLabel.get(spawn.label) ?? null\n const facts =\n tree.workerLogs.get(workerSource?.workerId ?? workerSource?.label ?? spawn.label) ?? null\n const wallMs =\n facts?.started != null && facts.finishedAt != null ? facts.finishedAt - facts.started : null\n const score = close?.score ?? facts?.score ?? null\n const passed = close?.valid ?? facts?.passed ?? null\n const reward = score ?? (passed === null ? null : passed ? 1 : 0)\n if (reward === null) {\n gaps.push({\n code: 'child-reward-unavailable',\n message: `child ${JSON.stringify(spawn.label)} has no verify verdict`,\n nodeId: spawn.id,\n })\n }\n const isSupervisor = spawn.role === 'supervisor'\n const captures = workerSource?.workspaceCaptures\n const captureGap = noteCaptureGaps(`child ${JSON.stringify(spawn.label)}`, spawn.id, captures)\n return {\n ...base,\n rollout_id: spawn.id,\n parent_rollout_id: spawn.parent,\n role: spawn.role,\n policy: {\n harness: isSupervisor ? (opts.supervisorHarness ?? null) : (opts.workerHarness ?? null),\n harness_version: null,\n model: isSupervisor ? (opts.supervisorModel ?? null) : (opts.workerModel ?? null),\n provider: null,\n profile_commit: null,\n agent_profile_cell_id: spawn.profileDigest,\n sampling: null,\n },\n outcome: {\n // Same producer, same claim: a child reward is a self-verify verdict\n // from the journal that no realness gate has seen.\n ...unscreenedRewardFields(reward),\n reward_source:\n reward === null ? null : score === null ? 'worker-self-verify' : 'worker-verdict-score',\n verdict:\n close === null\n ? null\n : {\n kind: close.kind,\n status: close.status,\n verdict: close.rawVerdict,\n valid: close.valid,\n score: close.score,\n },\n metrics: {\n label: spawn.label,\n spawned_at: spawn.at,\n settled_at: close?.at ?? null,\n started_at: facts?.started ?? null,\n finished_at: facts?.finishedAt ?? null,\n wall_ms: wallMs,\n patch_bytes: workerSource?.patchBytes ?? facts?.finishedPatchBytes ?? null,\n evidence_bytes: facts?.evidenceBytes ?? null,\n steers_queued: facts?.steersQueued ?? null,\n steers_delivered: facts?.steersDelivered ?? null,\n questions: facts?.questions ?? null,\n runtime: spawn.runtime,\n profile_digest: spawn.profileDigest,\n },\n is_completed: close?.kind === 'settled' && close.status === 'done',\n is_truncated: close?.kind === 'cancelled',\n error:\n close?.kind === 'cancelled'\n ? (close.reason ?? 'cancelled')\n : close?.status === 'down'\n ? (close.reason ?? 'child down')\n : null,\n realness_gated: false,\n },\n // `close.spend` is only a measurement when the close event carried one;\n // a store that never priced this worker must leave null, not 0.\n cost: {\n ...EMPTY_COST,\n usd: src.limits.spendUsd !== null || !close?.hasSpend ? null : close.spend.usd,\n tokens_in: workerSource?.tokensIn ?? (close?.hasSpend ? close.spend.tokens.input : null),\n tokens_out: workerSource?.tokensOut ?? (close?.hasSpend ? close.spend.tokens.output : null),\n // Mirror the tokens_in/out journal fallback so a source whose\n // `settled` spend carries cache counters is not reported as null cache\n // beside real tokens. Gate on `hasCache` — a spend object without cache\n // counters must stay null, not a fabricated 0.\n cache_read:\n workerSource?.cacheRead ??\n (close?.hasSpend && close.spend.tokens.hasCache ? close.spend.tokens.cacheRead : null),\n cache_write:\n workerSource?.cacheWrite ??\n (close?.hasSpend && close.spend.tokens.hasCache ? close.spend.tokens.cacheWrite : null),\n wall_s: wallMs === null ? null : wallMs / 1000,\n },\n // Only artifacts a reader declares: a guessed path would mint rows pointing at files that\n // never existed, and a transcript reference reads as retained evidence.\n artifacts: {\n patch_path: workerSource?.patchPath ?? null,\n run_dir: src.supRunDir,\n transcript_ref: workerSource?.transcriptRef ?? null,\n },\n provenance: {\n captured_at: capturedAt,\n capture: 'backfill',\n lossy_projection: true,\n ...(captures === undefined ? {} : { workspace_captures: captures }),\n gap: [\n workerSource?.transcriptRef == null\n ? 'no worker transcript was retained; messages unavailable'\n : 'worker transcript retained by reference; messages not inlined into this row',\n captureGap,\n ]\n .filter((reason): reason is string => reason !== null)\n .join('; '),\n },\n }\n}\n\n/** Mint rollout rows from an already parsed source without reading its JSONL again. */\nexport function supervisorRunRolloutLinesFromFacts(\n src: SupervisorRunSources,\n tree: SupervisorTreeFacts,\n opts: SupervisorRolloutOptions = {},\n): SupervisorRunTree {\n const gaps: SupervisorRunTreeGap[] = []\n if (src.journal === null) {\n gaps.push({\n code: 'journal-unavailable',\n message: `${src.supRunDir === null ? 'no supervisor run dir' : 'journal absent'}; no nodes recoverable`,\n })\n return { rootId: null, nodes: [], gaps }\n }\n // `journalInvalidRows` covers rows the parser could not interpret at all, including JSON\n // objects in a shape it does not recognize — so a journal it read but understood none of\n // reports an explicit gap instead of an empty tree.\n const malformedSourceRows =\n tree.journalInvalidRows + tree.spawns.filter((spawn) => !spawn.valid).length\n if (malformedSourceRows > 0) {\n gaps.push({\n code: 'source-row-malformed',\n message: `${malformedSourceRows} of ${tree.journalRows} journal row(s) were unusable and excluded from the tree`,\n count: malformedSourceRows,\n })\n }\n const ctx = rolloutContext(src, tree, opts, gaps)\n const nodes: RolloutLine[] = []\n const root = rootRolloutNode(ctx)\n if (root) nodes.push(root)\n const lookups = workerLookups(ctx)\n for (const spawn of tree.workerSpawns) {\n const node = workerRolloutNode(ctx, lookups, spawn)\n if (node) nodes.push(node)\n }\n\n const invalid = nodes.filter((n) => !isRolloutLine(n))\n if (invalid.length > 0) {\n gaps.push({\n code: 'node-schema-invalid',\n message: `${invalid.length} node(s) failed tangle.rollout.v1 validation`,\n count: invalid.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AAc,iBAAiB,OAC3B,4DACA,+EACJ,UACF,CAAC,CACE,QAAQ,WAA6B,WAAW,IAAI,CAAC,CACrD,KAAK,IAAI;EACd;CACF;AACF;;AAGA,SAAgB,mCACd,KACA,MACA,OAAiC,CAAC,GACf;CACnB,MAAM,OAA+B,CAAC;CACtC,IAAI,IAAI,YAAY,MAAM;EACxB,KAAK,KAAK;GACR,MAAM;GACN,SAAS,GAAG,IAAI,cAAc,OAAO,0BAA0B,iBAAiB;EAClF,CAAC;EACD,OAAO;GAAE,QAAQ;GAAM,OAAO,CAAC;GAAG;EAAK;CACzC;CAIA,MAAM,sBACJ,KAAK,qBAAqB,KAAK,OAAO,QAAQ,UAAU,CAAC,MAAM,KAAK,CAAC,CAAC;CACxE,IAAI,sBAAsB,GACxB,KAAK,KAAK;EACR,MAAM;EACN,SAAS,GAAG,oBAAoB,MAAM,KAAK,YAAY;EACvD,OAAO;CACT,CAAC;CAEH,MAAM,MAAM,eAAe,KAAK,MAAM,MAAM,IAAI;CAChD,MAAM,QAAuB,CAAC;CAC9B,MAAM,OAAO,gBAAgB,GAAG;CAChC,IAAI,MAAM,MAAM,KAAK,IAAI;CACzB,MAAM,UAAU,cAAc,GAAG;CACjC,KAAK,MAAM,SAAS,KAAK,cAAc;EACrC,MAAM,OAAO,kBAAkB,KAAK,SAAS,KAAK;EAClD,IAAI,MAAM,MAAM,KAAK,IAAI;CAC3B;CAEA,MAAM,UAAU,MAAM,QAAQ,MAAM,CAAC,cAAc,CAAC,CAAC;CACrD,IAAI,QAAQ,SAAS,GACnB,KAAK,KAAK;EACR,MAAM;EACN,SAAS,GAAG,QAAQ,OAAO;EAC3B,OAAO,QAAQ;CACjB,CAAC;CAEH,OAAO;EAAE,QAAQ,KAAK;EAAQ;EAAO;CAAK;AAC5C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"schema-YUIXT8iW.js","names":[],"sources":["../src/rollout/license.ts","../src/rollout/gate-checks.ts","../src/rollout/schema.ts"],"sourcesContent":["/**\n * The terms a rollout line's outputs carry, read from who produced it.\n *\n * `policy.model` and `policy.provider` already name the producer model and the\n * serving provider; `policy.license_class` states the terms those outputs carry:\n *\n * - `open-weight-api` — an open-weight model (GLM, DeepSeek, Kimi, Qwen…),\n * whichever API served it.\n * - `restricted` — Claude, Codex and Jev outputs, whose provider terms\n * restrict training a competing model.\n * - `evaluation-only` — data licensed for measurement.\n * - `human` — written by a person.\n *\n * Importers state the class. A line that does not is classified from its model\n * and harness names, restricted patterns first, so `claude-*` on any harness and\n * the `codex` harness on any model stay restricted. A line nothing classifies is\n * `null`.\n *\n * The class is provenance, not a default filter: every class trains unless a run\n * names the classes it accepts (Drew, 2026-10-25: train on everything), so a\n * dataset can be re-cut by class later without re-importing.\n */\n\nimport type { RolloutLine } from './schema'\n\nexport type LicenseClass = 'open-weight-api' | 'restricted' | 'evaluation-only' | 'human'\nexport const LICENSE_CLASSES: readonly LicenseClass[] = [\n 'open-weight-api',\n 'restricted',\n 'evaluation-only',\n 'human',\n]\n\nconst RESTRICTED = /claude|anthropic|\\b(?:opus|sonnet|haiku|fable)\\b|codex|\\bjev\\b/i\nconst OPEN_WEIGHT =\n /\\b(?:glm|deepseek|kimi|moonshot|qwen|llama|mistral|mixtral|gemma|minimax|gpt-oss|olmo|phi)/i\n\n/** Classify a model or harness name; `null` when it names no known family. */\nexport function licenseClassOfName(name: string | null | undefined): LicenseClass | null {\n if (!name) return null\n if (RESTRICTED.test(name)) return 'restricted'\n if (OPEN_WEIGHT.test(name)) return 'open-weight-api'\n return null\n}\n\n/** The line's stated class, else the class its model or harness implies. */\nexport function licenseClassOf(line: Pick<RolloutLine, 'policy'>): LicenseClass | null {\n const { license_class, model, harness } = line.policy\n if (license_class !== undefined) return license_class\n const byHarness = licenseClassOfName(harness)\n if (byHarness === 'restricted') return byHarness\n return licenseClassOfName(model) ?? byHarness\n}\n\n/** Every line passes without `allowed`; with it, the line's class must be listed. */\nexport function isLicenseEligible(\n line: Pick<RolloutLine, 'policy'>,\n allowed?: readonly LicenseClass[],\n): boolean {\n if (allowed === undefined) return true\n const license = licenseClassOf(line)\n return license !== null && allowed.includes(license)\n}\n","/**\n * THE canonical list of anti-Goodhart gate checks, plus the TOTAL policy every\n * entry point has to declare over it.\n *\n * Four rounds of adversarial review found the same defect four times, and it\n * was never the check itself: it was the COMPOSITION. `validateRolloutLine`\n * composed one check, `assertMinted` composed two, `assertRewardGate` composed\n * two of the three, `assertGateReport` composed its own pair — each by hand, in\n * its own file. So a check added to the package applied wherever its author\n * happened to remember, and the guard that forgot it looked exactly like the\n * guard that didn't. The last leak was literally that: `assertRewardGate`\n * composed `reward-relationship` + `gated-evidence` and not `unscreened-reward`,\n * so a never-screened positive reward that `assertMinted` correctly REFUSED\n * walked through all four waist exporters at full value.\n *\n * The fix is to make hand-composition impossible rather than to add a third\n * call to the two places that had two:\n *\n * - `GATE_CHECKS` is a TOTAL map over `GateCheckId`. A new id with no\n * implementation does not compile.\n * - `GatePolicy` is a TOTAL map over `GateCheckId`. Every entry point\n * declares one, so a new id makes EVERY entry point's policy a type error\n * until it is wired. Wiring it means writing `enforced`, `repairedBy(...)`\n * or `omittedBecause(...)` — and the last two force a written reason, so a\n * silent gap is not expressible.\n * - every check carries a `tripwire`: the minimal outcome it must refuse.\n * `gate-checks.test.ts` feeds each tripwire to every entry point that\n * declares `enforced` and requires a rejection, so wiring a check to the\n * wrong disposition is a TEST failure even when it type-checks.\n *\n * Adding a check is therefore: append the id, write the check, and the compiler\n * enumerates every place that has to decide about it.\n */\n\nimport type { GatedEvidence, RolloutOutcome, RolloutStep } from './schema'\n\n/**\n * Every gate check in the package, in the order they are applied.\n *\n * Order is load-bearing only for which message a caller sees first: a line that\n * trips two checks reports the earlier one, and `reward-relationship` is first\n * because it is the invariant the other three protect.\n */\nexport const GATE_CHECK_IDS = [\n 'reward-relationship',\n 'gated-evidence',\n 'undeclared-step-payload',\n 'unscreened-reward',\n] as const\n\nexport type GateCheckId = (typeof GATE_CHECK_IDS)[number]\n\n/**\n * An outcome as it reaches a check.\n *\n * Deliberately accepts a raw record as well as the typed shape: the checks are\n * the RUNTIME half of the gate, and the callers they exist for — JSON off a\n * ledger, a plain-JavaScript consumer of the published package — arrive with no\n * types at all. `Partial` because a tripwire states only the fields it trips on.\n */\nexport type GateCheckedOutcome = Partial<RolloutOutcome> | Readonly<Record<string, unknown>>\n\n/**\n * What a gate check reads: the reward-bearing surface of ONE LINE.\n *\n * For three rounds the subject was the OUTCOME alone, and that assumption is\n * what produced the next leak rather than any missing check: `steps[]` sits on\n * the LINE, outside `outcome`, so a per-step reward on a gated line was read by\n * no check at all while `toRewardRows` copied it out verbatim — through the\n * MINTED door, not merely the raw one. Widening the subject is what makes\n * \"somewhere else on the line\" a place the checks can see.\n *\n * `outcome` is REQUIRED, and that is the point: a bare `RolloutOutcome` is then\n * not assignable to a subject, so every call site that used to pass one is a\n * COMPILE error until it passes the line instead. A subject with an optional\n * `outcome` would have let the old call sites keep compiling while silently\n * checking nothing — the exact failure this module exists to make impossible.\n */\ninterface GateSubject {\n outcome: GateCheckedOutcome\n /** The line's trajectory steps, when it carries any. */\n steps?: unknown\n}\n\n/** One untyped field read off the outcome, so every check narrows from the same place. */\nconst field = (subject: GateSubject, name: string): unknown =>\n (subject.outcome as Readonly<Record<string, unknown>>)?.[name]\n\nexport interface GateCheck {\n id: GateCheckId\n /** One sentence: what this check refuses. */\n refuses: string\n /** One dotted-path message per defect; `[]` when the line is clean. */\n errors: (subject: GateSubject) => string[]\n /**\n * Every minimal subject that MUST trip `errors` — the executable form of\n * `refuses`, and the reason a check cannot be added without being provable.\n * The calibration test feeds each one to every entry point declaring\n * `enforced`.\n *\n * A LIST rather than one case: a check that refuses two distinct populations\n * (a positive reward AND a reward it cannot read as a number) proved able to\n * hold for the first while silently passing the second, so each population\n * states its own tripwire and each is exercised separately.\n */\n tripwires: GateSubject[]\n}\n\n// ---------------------------------------------------------------------------\n// Total readers. Every \"is this positive?\" / \"is this populated?\" question the\n// checks ask goes through one of these.\n// ---------------------------------------------------------------------------\n\n/**\n * How the gate reads one `outcome.reward`.\n *\n * TOTAL over `unknown`, with an explicit `unreadable` case, because the\n * recurring defect across four rounds was a hand-written type test whose\n * NEGATIVE branch silently passed: `typeof reward !== 'number' || !(reward > 0)`\n * returned \"clean\" for `reward: \"0.95\"`, so a plain-JavaScript producer that\n * stringifies its numbers — the exact population the runtime backstop exists\n * for — shipped a gamed run at full value through three waist exporters.\n *\n * A value the gate cannot read as a number is not evidence the reward is\n * cleared; it is the absence of that evidence, and the gate fails closed on it.\n */\ntype RewardReading =\n /** `null`/`undefined` — a labeled gap, which is never a positive signal. */\n | { kind: 'absent' }\n /** A number at or below zero: the gate's own verdict, applied. */\n | { kind: 'cleared' }\n /** A number above zero, `Infinity` and the 5e-324 denormal included. */\n | { kind: 'positive'; shown: string }\n /** Anything the wire format does not permit here, plus `NaN`. */\n | { kind: 'unreadable'; shown: string }\n\nfunction readReward(value: unknown): RewardReading {\n if (value === null || value === undefined) return { kind: 'absent' }\n if (typeof value === 'number') {\n if (Number.isNaN(value)) return { kind: 'unreadable', shown: 'NaN' }\n return value > 0 ? { kind: 'positive', shown: String(value) } : { kind: 'cleared' }\n }\n return {\n kind: 'unreadable',\n shown: `${JSON.stringify(value) ?? String(value)} (${typeof value})`,\n }\n}\n\nconst isPlainRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * Whether a reward-derived field carries anything at all.\n *\n * The previous emptiness test was `Object.keys(value).length > 0`, which reads\n * `[]` for a NUMBER, a BOOLEAN and the empty string — so `metrics: 0.95` on a\n * gated line counted as empty and shipped verbatim in the verifiers format's\n * per-rubric score dict. `Object.keys` being total over primitives is not the\n * same property as being CORRECT over them.\n *\n * The rule that has no such hole: only `undefined`, `null` and a record with no\n * keys are empty. Everything else is payload, whatever its type.\n */\nfunction payloadIsPopulated(value: unknown): boolean {\n if (value === undefined || value === null) return false\n if (isPlainRecord(value)) return Object.keys(value).length > 0\n return true\n}\n\n/**\n * Every key `tangle.rollout.v1` declares on a step, as a TOTAL map over the\n * interface: a field added to `RolloutStep` and not to this list does not\n * compile, so the list cannot silently fall behind the schema it mirrors.\n *\n * This is the producer's OWN classification, which is the only partition\n * `gatedEvidenceOf` accepts — a key-name heuristic (\"strip anything matching\n * /reward|score/\") holds until someone names a field `credit` and the next\n * per-step signal ships at full value.\n */\nconst DECLARED_STEP_KEYS: { readonly [K in keyof Required<RolloutStep>]: true } = {\n kind: true,\n name: true,\n input: true,\n output: true,\n status: true,\n durationMs: true,\n llm_call_count: true,\n prompt_token_ids: true,\n completion_token_ids: true,\n logprobs: true,\n}\n\n/**\n * The part of `steps` the wire format has no name for — a per-step reward, a\n * per-step score, whatever a producer decided to hang there.\n *\n * `undefined` when the steps carry nothing undeclared.\n */\nexport function undeclaredStepPayload(steps: unknown): unknown {\n if (steps === undefined || steps === null) return undefined\n // The format says `steps` is a list. Anything else is wholly unclassified.\n if (!Array.isArray(steps)) return steps\n const extras: Array<Record<string, unknown>> = []\n let found = false\n for (const step of steps) {\n const extra: Record<string, unknown> = {}\n if (isPlainRecord(step)) {\n for (const [key, value] of Object.entries(step)) {\n if (key in DECLARED_STEP_KEYS) continue\n extra[key] = value\n found = true\n }\n } else if (step !== undefined && step !== null) {\n // A step that is not even a record carries no declared key to keep.\n extras.push({ step } as Record<string, unknown>)\n found = true\n continue\n }\n extras.push(extra)\n }\n return found ? extras : undefined\n}\n\n/** `steps` projected down to the keys the wire format declares. */\nexport function declaredSteps(steps: unknown): RolloutStep[] | undefined {\n if (!Array.isArray(steps)) return undefined\n const kept: RolloutStep[] = []\n for (const step of steps) {\n if (!isPlainRecord(step)) continue\n const projected: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(step)) {\n if (key in DECLARED_STEP_KEYS) projected[key] = value\n }\n kept.push(projected as unknown as RolloutStep)\n }\n return kept\n}\n\n/**\n * THE anti-Goodhart invariant, checked as a RELATIONSHIP between two fields\n * rather than as two independent type checks.\n *\n * Everything upstream of a training export is allowed to be wrong; this is the\n * one thing that cannot be. `realness_gated: true` means the run faked its\n * success signal, so its reward is a fabrication, and a fabrication above zero\n * is precisely what a trainer would learn to reproduce. Validating only that\n * `reward` is a number and `realness_gated` is a boolean is what let a line\n * claiming `{reward: 0.95, realness_gated: true}` validate clean and walk\n * through every exporter.\n */\nconst rewardRelationship: GateCheck = {\n id: 'reward-relationship',\n refuses: 'a positive — or unreadable — reward on a line the authenticity screen flagged as gamed',\n tripwires: [\n { outcome: { reward: 0.95, realness_gated: true } },\n // The second population, stated separately because the check held for the\n // first while passing this one for a full round.\n { outcome: { reward: '0.95' as unknown as number, realness_gated: true } },\n ],\n errors: (subject) => {\n if (field(subject, 'realness_gated') !== true) return []\n const reading = readReward(field(subject, 'reward'))\n if (reading.kind === 'absent' || reading.kind === 'cleared') return []\n if (reading.kind === 'unreadable') {\n return [\n `outcome.reward: ${reading.shown} with outcome.realness_gated: true — the wire format ` +\n 'declares this field `number | null`, so the gate cannot read this value as a number ' +\n 'and cannot establish that the reward was cleared. On a run flagged as gamed that is ' +\n 'not evidence of a zero, it is the absence of it, and a consumer that coerces the ' +\n 'value (`\"0.95\"`, `\"2\"`) reads a positive reward off a faked success. Emit a number ' +\n 'or null — `trainingReward` / `trainingScore` from `rollout/reward.ts` produce one.',\n ]\n }\n return [\n `outcome.reward: ${reading.shown} with outcome.realness_gated: true — a run flagged as ` +\n 'gamed may not carry a positive reward. The anti-Goodhart gate forces the reward to 0 (a ' +\n 'real verdict: the gate decided) before the line is written, so a fine-tune cannot learn ' +\n 'from a faked success. Derive the reward with `trainingReward` / `trainingScore` from ' +\n '`rollout/reward.ts`, or drop the line.',\n ]\n },\n}\n\n/**\n * The reward-bearing outcome fields that are NOT the scalar: the numbers the\n * reward was computed from, and the verdict record that claimed it.\n *\n * Returned as one block rather than filtered key-by-key. A key-name heuristic\n * (\"zero anything matching `layer.*` or `/score/`\") is the same defect shape as\n * the line-oriented regex the AST score guard replaced: it holds until someone\n * names a metric `pass_fraction`, and the next reward-shaped key ships at full\n * value. The producer's OWN classification — \"this is the scalar, that is\n * everything else\" — is the only partition that cannot be out-guessed.\n */\nexport function gatedEvidenceOf(subject: GateSubject): GatedEvidence | undefined {\n const evidence: GatedEvidence = {}\n // `payloadIsPopulated`, not an inline key count: a plain-JavaScript caller can\n // hand any value here, and a non-record `metrics` is still reward-derived\n // payload. See that function for the primitives an `Object.keys` test missed.\n const metrics = field(subject, 'metrics')\n if (payloadIsPopulated(metrics)) evidence.metrics = metrics as Record<string, unknown>\n const verdict = field(subject, 'verdict')\n if (verdict !== null && verdict !== undefined) evidence.verdict = verdict\n const steps = undeclaredStepPayload(subject.steps)\n if (steps !== undefined) evidence.steps = steps\n return evidence.metrics === undefined && evidence.verdict === undefined && steps === undefined\n ? undefined\n : evidence\n}\n\n/**\n * The invariant is about the OUTCOME, not about one field of it.\n *\n * `mintRolloutRows` bulk-copied `RunRecord.outcome.raw` into `outcome.metrics`\n * with no gate, so a gated run exported `reward: 0` (correct) while the\n * deterministic per-layer scores that reward was COMPUTED FROM — the `layer.*`\n * keys `rl/verifiable-reward.ts` calls the RL training signal — shipped at 1.0,\n * in the top-level `metrics` dict of the Prime Intellect verifiers format, which\n * IS that format's per-rubric score dict. `verdict` leaks the same way into\n * `toRftItem`'s `reference.verdict`, where a grader author reads\n * `resolved: true` off a run that faked it.\n */\nconst gatedEvidence: GateCheck = {\n id: 'gated-evidence',\n refuses: 'the numbers a fabricated reward was computed from, riding along at reward 0',\n tripwires: [\n { outcome: { reward: 0, realness_gated: true, metrics: { 'layer.tests': 1 } } },\n // A PRIMITIVE `metrics`: `Object.keys(0.95)` is `[]`, so the emptiness test\n // this check used to run reported it clean and the verifiers format shipped\n // it as its per-rubric score dict.\n { outcome: { reward: 0, realness_gated: true, metrics: 0.95 as unknown as never } },\n ],\n errors: (subject) => {\n if (field(subject, 'realness_gated') !== true) return []\n const evidence = gatedEvidenceOf(subject)\n if (evidence === undefined) return []\n // Each check reports only the fields it owns; `steps` is `undeclared-step-payload`.\n if (evidence.metrics === undefined && evidence.verdict === undefined) return []\n const path = evidence.metrics !== undefined ? 'outcome.metrics' : 'outcome.verdict'\n return [\n `${path} is populated with outcome.realness_gated: true — a run flagged as gamed may not ` +\n 'ship the numbers its fabricated reward was computed from, even at reward 0. The ' +\n 'per-layer scores in `metrics` ARE the reward signal in the verifiers format, and ' +\n '`verdict` is the record that claimed the success. Mint through `assertMinted`, which ' +\n 'relocates both to `provenance.gated_evidence` (see `gateGamedOutcome`), or drop the line.',\n ]\n },\n}\n\n/**\n * A reward-bearing field hung on `steps[]`, where the gate was not looking.\n *\n * The first three checks all read `outcome`, so the whole apparatus was blind to\n * anything a producer wrote elsewhere on the line — and `toRewardRows` emits\n * `steps` verbatim beside the scalar it just forced to 0. A generated corpus\n * found it in twenty cases: a gated line carrying\n * `steps: [{kind, name, reward: 0.86}]` exported `{\"reward\": 0, \"steps\":\n * [{\"reward\": 0.86}]}`, which is the per-step credit assignment of a run that\n * faked its success, at full value, through the MINTED door.\n *\n * `RolloutStep` declares ten keys and none of them is a reward, so the partition\n * needs no judgement call: whatever the format does not name is unclassified\n * payload, and on a gated line unclassified payload is exactly what the gate\n * refuses. `assertMinted` relocates it rather than rejecting, like the sibling\n * check, so an already-published ledger stays readable.\n */\nconst undeclaredStepPayloadCheck: GateCheck = {\n id: 'undeclared-step-payload',\n refuses: 'per-step reward signal hung on a gated line’s steps, outside every field the gate read',\n tripwires: [\n {\n outcome: { reward: 0, realness_gated: true },\n steps: [{ kind: 'tool', name: 'edit', reward: 0.9 }],\n },\n ],\n errors: (subject) => {\n if (field(subject, 'realness_gated') !== true) return []\n const extra = undeclaredStepPayload(subject.steps)\n if (extra === undefined) return []\n return [\n `steps[] carries fields \\`${ROLLOUT_SCHEMA_NAME}\\` does not declare (${JSON.stringify(extra).slice(0, 120)}) ` +\n 'with outcome.realness_gated: true — a per-step reward is training signal exactly like ' +\n 'the scalar, and the exporters copy `steps` through verbatim, so zeroing `outcome.reward` ' +\n 'while leaving it in place ships the gamed run’s step-level credit assignment at full ' +\n 'value. Mint through `assertMinted`, which projects the steps down to the declared keys ' +\n 'and relocates the rest to `provenance.gated_evidence.steps` (see `gateGamedOutcome`).',\n ]\n },\n}\n\n/** Named here rather than imported, so `gate-checks` stays free of schema cycles. */\nconst ROLLOUT_SCHEMA_NAME = 'tangle.rollout.v1'\n\n/**\n * A positive reward whose producer DECLARED that no authenticity screen exists.\n *\n * `realness_gated: false` is the screen's VERDICT, so writing it with no screen\n * behind it claims \"we looked and nothing fired\" about a reward nobody looked\n * at. `realness_screened: false` is the producer saying so out loud, and a\n * positive reward carrying it is exactly the signal the gate exists to qualify\n * with nothing having qualified it.\n */\nconst unscreenedReward: GateCheck = {\n id: 'unscreened-reward',\n refuses: 'a positive reward whose producer declares that no authenticity screen ever ran',\n tripwires: [\n { outcome: { reward: 1, realness_gated: false, realness_screened: false } },\n {\n outcome: {\n reward: '2' as unknown as number,\n realness_gated: false,\n realness_screened: false,\n },\n },\n ],\n errors: (subject) => {\n if (field(subject, 'realness_screened') !== false) return []\n const reading = readReward(field(subject, 'reward'))\n if (reading.kind === 'absent' || reading.kind === 'cleared') return []\n return [\n `outcome.reward: ${reading.shown} with outcome.realness_screened: false — this producer declares ` +\n 'that NO authenticity screen ran on this reward, so nothing has established the success ' +\n 'is real, and an unscreened positive reward is exactly the signal the anti-Goodhart gate ' +\n 'exists to qualify. Screen the run and write the verdict (`rolloutRewardFields` from a ' +\n '`RunRecord` carrying `outcome.realness`), or emit `reward: null` — an unqualified ' +\n 'verdict is a labeled gap, not a measured success.',\n ]\n },\n}\n\n/**\n * The registry. Total over `GateCheckId`, so an id with no check does not\n * compile, and `GATE_CHECK_IDS` stays the single enumeration everything\n * iterates.\n */\nexport const GATE_CHECKS: { readonly [K in GateCheckId]: GateCheck } = {\n 'reward-relationship': rewardRelationship,\n 'gated-evidence': gatedEvidence,\n 'undeclared-step-payload': undeclaredStepPayloadCheck,\n 'unscreened-reward': unscreenedReward,\n}\n\n/**\n * What ONE entry point does about ONE check.\n *\n * `repair` and `omit` both carry a mandatory sentence, which is the mechanism\n * that keeps a legitimate omission distinguishable from a forgotten one: you\n * cannot skip a check without writing down why, and the reasons are readable\n * side by side in `GATE_POLICIES`.\n */\nexport type GateCheckDisposition =\n | { readonly kind: 'enforce' }\n /** Resolved by TRANSFORMING the line instead of rejecting it; `by` names the function. */\n | { readonly kind: 'repair'; readonly by: string }\n /** Deliberately not applied here; `because` states the reason. */\n | { readonly kind: 'omit'; readonly because: string }\n\nconst enforced: GateCheckDisposition = { kind: 'enforce' }\nconst repairedBy = (by: string): GateCheckDisposition => ({ kind: 'repair', by })\nconst omittedBecause = (because: string): GateCheckDisposition => ({\n kind: 'omit',\n because,\n})\n\n/** Total over `GateCheckId`: a new check makes every policy literal a type error. */\nexport type GatePolicy = { readonly [K in GateCheckId]: GateCheckDisposition }\n\n/**\n * Every entry point that decides about the gate, and what it decides.\n *\n * Read this as the package's gate policy in one screen. The four entry points\n * are not interchangeable — a validator that rejects, a mint funnel that\n * repairs, a runtime backstop for untyped callers, and a release certifier over\n * emitted rows — and the dispositions say which is which.\n */\nexport const GATE_POLICIES = {\n /**\n * The schema validator. Rejects the reward relationship and NOTHING ELSE, on\n * purpose: it runs on every line read off disk, and the other two conditions\n * describe artifacts that already exist.\n */\n validateRolloutLine: {\n // Stays a REJECTION rather than a transformation. A caller emitting\n // `{reward: 0.95, realness_gated: true}` is a producer defect and has to\n // fail loudly; laundering it into `reward: 0` here would hide the producer,\n // which is the actual bug.\n 'reward-relationship': enforced,\n 'gated-evidence': omittedBecause(\n 'a ledger written before the relocation existed carries `metrics` on its gated lines; ' +\n 'rejecting those would make every already-published artifact unreadable. The condition ' +\n 'is REPAIRED at `assertMinted` (`gateGamedOutcome`) instead, which is the only door into ' +\n 'the training path, so the artifact stays readable and the leak still closes.',\n ),\n 'undeclared-step-payload': omittedBecause(\n 'identical reasoning to `gated-evidence`, one field over: a foreign or pre-unification ' +\n 'ledger may carry producer-invented keys on its steps, and refusing to READ those files ' +\n 'buys nothing the relocation at `assertMinted` does not already buy. Promotion into ' +\n 'training is where it closes.',\n ),\n 'unscreened-reward': omittedBecause(\n 'supervision-journal rows legitimately carry an unscreened positive reward (there is no ' +\n '`RunRecord.outcome.realness` behind them) and must stay writable, readable and ' +\n 'reportable. Only PROMOTION into training is closed, at `assertMinted`.',\n ),\n },\n /**\n * The mint funnel — the single door every `MintedRolloutLine` passes. Validates\n * first (so the reward relationship has already been rejected), then refuses\n * what cannot be repaired, then repairs what can.\n */\n assertMinted: {\n // Re-run after `assertRolloutLine`, which already rejected it. Cheap, and it\n // makes this entry point independently complete rather than complete only\n // because of what it happens to call first.\n 'reward-relationship': enforced,\n 'gated-evidence': repairedBy('gateGamedOutcome'),\n 'undeclared-step-payload': repairedBy('gateGamedOutcome'),\n 'unscreened-reward': enforced,\n },\n /**\n * The runtime backstop, and the one entry point with no license to omit\n * anything: it exists for callers the type system never saw (plain JavaScript\n * handing an object literal to a published exporter), so a check it skips is a\n * check that does not run at all for them. This is where the fourth leak was.\n */\n assertRewardGate: {\n 'reward-relationship': enforced,\n 'gated-evidence': enforced,\n 'undeclared-step-payload': enforced,\n 'unscreened-reward': enforced,\n },\n /**\n * The release certifier. Same checks, measured over the rows a release is\n * ABOUT TO WRITE rather than over one line's outcome — see `REPORT_MEASURES`\n * in `release/gate-report.ts`, which is the second total map this policy\n * drives.\n */\n assertGateReport: {\n 'reward-relationship': enforced,\n 'gated-evidence': enforced,\n 'undeclared-step-payload': enforced,\n 'unscreened-reward': enforced,\n },\n} as const satisfies Record<string, GatePolicy>\n\n/** Every entry point that declares a gate policy. */\nexport type GateEntryPoint = keyof typeof GATE_POLICIES\n\n/**\n * Run the checks one entry point enforces. The ONLY way an entry point should\n * obtain gate errors — hand-composing two of the three is the bug this module\n * exists to remove.\n */\nexport function gateErrors(subject: GateSubject, policy: GatePolicy): string[] {\n const errors: string[] = []\n for (const id of GATE_CHECK_IDS) {\n if (policy[id].kind !== 'enforce') continue\n errors.push(...GATE_CHECKS[id].errors(subject))\n }\n return errors\n}\n","/**\n * `tangle.rollout.v1` — THE canonical rollout serialization, owned by\n * agent-eval. One JSONL line per agent invocation (a solo eval run, a\n * supervisor episode, a worker session, a proposer shot, a judge call, an\n * analyst pass), labeled with its task/split coordinates and a single\n * scalar reward, carrying the FULL message transcript inline.\n *\n * This schema is the reconciliation of two prior producers:\n * - agent-eval's RunRecord-joined rollout rows (PR #410): identity,\n * provenance hashes, the realness gate travelling into the reward,\n * trace-derived steps.\n * - the bench rollout-ledger (agent-runtime PR #591): the wire shape —\n * role, task.split/rep, parent_rollout_id, policy provenance, capture\n * provenance, inline canonical chat-with-tools messages.\n * Where the two conflicted, RunRecord-derived semantics won; the wire\n * field names follow the ledger (snake_case). See `docs/rollout.md` for\n * the field-by-field decision table.\n *\n * Messages are inlined — never referenced — because every harness store a\n * rollout can be recovered from is mutable or garbage-collected. A line\n * must stay a complete training/eval example on its own.\n *\n * `outcome.reward` is THE single scalar (null = no verdict exists — a\n * labeled gap, never 0). `outcome.realness_gated` is the anti-Goodhart\n * flag: a gated line must never export as a positive training example.\n *\n * That last sentence is enforced here, by `validateRolloutLine`, not merely\n * documented. Validating `reward` and `realness_gated` independently — each a\n * well-typed field, their COMBINATION unchecked — is what let a line claiming\n * `{reward: 0.95, realness_gated: true}` validate clean and walk into every\n * training export. The relationship between the two IS the invariant, so it is\n * checked where every other structural claim about a line is checked.\n *\n * The invariant is about the OUTCOME, not about one field of it. Zeroing\n * `reward` while `outcome.metrics` still carried the per-layer scores that\n * reward was computed from exported the gamed signal anyway, in the dict the\n * verifiers format reads as its per-rubric scores. So `gateGamedOutcome`\n * transforms the whole outcome once, at `assertMinted` — the funnel every\n * minted line passes — and the reward-bearing components are relocated to\n * `provenance.gated_evidence`, which no exporter projects.\n *\n * WHICH checks each door applies is not decided in this file. `./gate-checks`\n * owns the canonical list and the total per-entry-point policy; the three doors\n * below (`validateRolloutLine`, `assertRewardGate`, `assertMinted`) each call\n * `gateErrors` with their declared policy, so a check added to that list applies\n * here without anyone editing this file, and a check deliberately skipped has to\n * name itself there.\n */\n\nimport { isRecord } from '../llm-client/json'\nimport { declaredSteps, GATE_POLICIES, gatedEvidenceOf, gateErrors } from './gate-checks'\nimport { LICENSE_CLASSES, type LicenseClass } from './license'\nexport const ROLLOUT_SCHEMA = 'tangle.rollout.v1'\n\n/** `agent` = a solo evaluation run (no multi-agent topology). */\nexport type RolloutRole = 'agent' | 'supervisor' | 'worker' | 'proposer' | 'judge' | 'analyst'\nexport const ROLLOUT_ROLES: readonly RolloutRole[] = [\n 'agent',\n 'supervisor',\n 'worker',\n 'proposer',\n 'judge',\n 'analyst',\n]\n\n/** Split vocabulary follows `RunRecord.splitTag`, extended with `canary`. */\nexport type RolloutSplit = 'search' | 'dev' | 'holdout' | 'canary'\nexport const ROLLOUT_SPLITS: readonly RolloutSplit[] = ['search', 'dev', 'holdout', 'canary']\n/** Splits that may ship in training exports. Everything else is fail-closed excluded. */\nconst TRAINABLE_SPLITS: readonly RolloutSplit[] = ['search']\n\nexport function isTrainableSplit(split: RolloutSplit): boolean {\n return TRAINABLE_SPLITS.includes(split)\n}\n\n/** 'mint' = joined live from RunRecord + trace by `mintRolloutRows`. */\nexport type RolloutCapture = 'mint' | 'settle-time' | 'backfill'\nexport const ROLLOUT_CAPTURES: readonly RolloutCapture[] = ['mint', 'settle-time', 'backfill']\n\n// ---------------------------------------------------------------------------\n// Canonical message format — OpenAI chat-with-tools, full fidelity.\n// ---------------------------------------------------------------------------\n\nexport type ChatRole = 'system' | 'user' | 'assistant' | 'tool'\nconst CHAT_ROLES: readonly ChatRole[] = ['system', 'user', 'assistant', 'tool']\n\nexport interface ChatToolCall {\n id: string\n type: 'function'\n function: {\n name: string\n /** JSON-encoded argument object, exactly as the model emitted it. */\n arguments: string\n }\n}\n\nexport interface ChatMessage {\n role: ChatRole\n content: string | null\n /** Reasoning/thinking channel where the harness captured it (full fidelity). */\n reasoning_content?: string\n tool_calls?: ChatToolCall[]\n /** Required on role:\"tool\" — the ChatToolCall this result answers. */\n tool_call_id?: string\n name?: string\n /**\n * Harbor ATIF `is_copied_context` (RFC 0001 rule 7): this turn was COPIED IN\n * from another trajectory's context, not produced by the agent on this line.\n * The RFC makes excluding it from SFT a MUST, and `toSftRows` does — training\n * on it teaches the model to author text it never authored, and credits this\n * run for another one's work. Absent = false (authored here).\n */\n is_copied_context?: boolean\n}\n\nexport interface ToolDef {\n type: 'function'\n function: {\n name: string\n description?: string\n parameters?: Record<string, unknown>\n }\n}\n\n/**\n * Compact trace-span projection (llm/tool step) carried alongside the\n * conversation when the line was minted from a trace. Optional: lines\n * recovered from harness stores have no span structure.\n */\nexport interface RolloutStep {\n kind: string\n name: string\n /** llm: last-message summary · tool: stringified args. Scrubbed. */\n input?: string\n /** llm: output text · tool: stringified result. Scrubbed. */\n output?: string\n status?: 'ok' | 'error'\n durationMs?: number\n // The four fields below are lifted verbatim from Harbor ATIF's per-step\n // `metrics` (see `interchange/harbor.ts`); the wire names stay snake_case to\n // match that spec exactly, which is why they differ from `durationMs`.\n // All optional and never back-filled: an absent field means \"not captured\",\n // which is not the same claim as an empty array.\n /**\n * LLM inferences this span represents. 0 = deterministic dispatch with no\n * model call — distinct from absent, which means the producer did not track it.\n */\n llm_call_count?: number\n /** Exact prompt tokenization. Removes the ambiguity of re-tokenizing text at train time. */\n prompt_token_ids?: number[]\n /** Exact completion tokenization; aligns index-wise with `logprobs`. */\n completion_token_ids?: number[]\n /**\n * Per-completion-token log probabilities under the sampling policy. Required\n * for off-policy correction (importance weighting) when the rollout was\n * generated by a policy other than the one being trained.\n */\n logprobs?: number[]\n}\n\n// ---------------------------------------------------------------------------\n// Ledger line sections.\n// ---------------------------------------------------------------------------\n\nexport interface RolloutTask {\n /** Benchmark/suite id (e.g. \"swe-bench-verified\") or the experiment id. */\n suite: string\n instance_id: string\n split: RolloutSplit\n /** Sampling seed the campaign pinned; null = not recorded. */\n seed: number | null\n /** Replicate index (0-based). */\n rep: number\n}\n\nexport interface RolloutPolicy {\n /** Harness that drove the invocation (e.g. \"opencode\", \"claude\", \"pi-loops\"). */\n harness: string | null\n harness_version: string | null\n model: string | null\n provider: string | null\n /** Commit of the agent profile / candidate under evaluation. */\n profile_commit: string | null\n /** sha256 of the effective prompt (post-steering), when recorded. */\n prompt_hash?: string | null\n /** sha256 of the effective run config, when recorded. */\n config_hash?: string | null\n /** Canonical agent-profile cell identity, when the run carries one. */\n agent_profile_cell_id?: string | null\n /** Sampling params (temperature, top_p, max_tokens…); null = not recorded. */\n sampling: Record<string, unknown> | null\n /** Terms the producer's outputs carry; absent = inferred (see `./license`). */\n license_class?: LicenseClass\n}\n\nexport interface RolloutOutcome {\n /**\n * THE single scalar training signal — the official verdict.\n * null = no verdict exists for this invocation (a labeled gap, never 0).\n */\n reward: number | null\n /** Where the reward came from (judge id; \"/inherited\" = parent episode's). */\n reward_source: string | null\n /** Raw judge verdict record, verbatim. */\n verdict: unknown\n /** Everything that is NOT the scalar reward. */\n metrics: Record<string, unknown>\n is_completed: boolean\n is_truncated: boolean\n error: string | null\n /**\n * Anti-Goodhart flag from `RunRecord.outcome.realness.gated`: the run faked\n * its success signal. `true` requires `reward` to be 0 or null — the\n * validator rejects the line otherwise — and the line never qualifies for\n * SFT. Required on the wire: a line that does not state the flag does not\n * validate, so no producer can dodge the gate by omitting it.\n *\n * `true` ALSO requires `metrics` to be empty and `verdict` to be null: the\n * numbers the reward was computed from are relocated to\n * `provenance.gated_evidence` by `gateGamedOutcome`. See that function for\n * why zeroing the scalar alone was not enough.\n */\n realness_gated: boolean\n /**\n * Whether an authenticity SCREEN ever RAN on this reward — a different claim\n * from `realness_gated`, which is the screen's VERDICT.\n *\n * `realness_gated: false` reads as \"we looked and nothing fired\". A producer\n * with no screen at all was emitting exactly that, so a never-screened reward\n * was indistinguishable on the wire from a screened-clean one, and the whole\n * anti-Goodhart apparatus silently treated the first as the second. The two\n * claims are now separable:\n *\n * - `true` — a screen ran; `realness_gated` is its verdict.\n * - `false` — the producer declares it HAS no screen (`unscreenedRewardFields`).\n * `assertMinted` REFUSES such a line when its reward is above\n * zero: an unscreened positive reward is precisely the signal\n * the gate exists to qualify, and nothing has qualified it.\n * - absent — not stated. Pre-unification ledgers land here, as does a\n * `RunRecord` carrying no `outcome.realness` at all. Absent is\n * read as \"unknown\", never as `false` (which would refuse most\n * of the existing corpus) and never as `true`.\n */\n realness_screened?: boolean\n}\n\nexport interface RolloutCostBlock {\n usd: number | null\n tokens_in: number | null\n tokens_out: number | null\n tokens_reasoning: number | null\n cache_read: number | null\n cache_write: number | null\n wall_s: number | null\n /**\n * Total LLM inferences across the invocation (ATIF `llm_call_count`,\n * aggregated). Optional and additive: absent = not tracked, never 0.\n */\n llm_call_count?: number | null\n}\n\nexport interface RolloutArtifacts {\n patch_path: string | null\n run_dir: string | null\n /** Source-of-truth transcript pointer (session id / jsonl path) for audit.\n * Minted lines point at the run's trace as `trace:<traceId>`. */\n transcript_ref: string | null\n}\n\n/**\n * The reward-bearing half of a GATED line's outcome, moved off `outcome` and\n * parked here verbatim. Diagnostics, never training input — see\n * `gateGamedOutcome`.\n */\nexport interface GatedEvidence {\n /** `outcome.metrics` exactly as the producer measured it. */\n metrics?: Record<string, unknown>\n /** `outcome.verdict` verbatim — the judge record that claimed the success. */\n verdict?: unknown\n /**\n * The per-step fields `tangle.rollout.v1` does not declare, parked here when\n * the gate projected `steps[]` down to the schema's own key set.\n *\n * A per-step reward is training signal exactly like the scalar, and `steps`\n * rides through `toRewardRows` verbatim — so a gated line was shipping its\n * step-level credit assignment at full value beside a `reward` of 0.\n */\n steps?: unknown\n}\n\nexport interface RolloutEvidenceAttempt {\n executionId: string\n ordinal: number\n providerSessionId: string | null\n nativeSessionIds: string[]\n processIds: string[]\n outcome: 'succeeded' | 'failed' | 'cancelled' | 'unknown'\n missingReasons: string[]\n}\n\n/** One Runtime result blob and its unmodified provider capture receipt. */\nexport interface RolloutWorkspaceCapture {\n readonly outRef: string | null\n readonly blobPath: string | null\n /** JSON pointer to the receipt within its Runtime result. */\n readonly receiptPointer: string | null\n readonly receipt: unknown | null\n readonly attempts: readonly unknown[] | null\n /** The provider's claim, not an Eval verification of the archive bytes. */\n readonly coverageComplete: boolean | null\n readonly incompleteReason: string | null\n readonly projectionGap: string | null\n}\n\nexport interface RolloutProvenance {\n captured_at: string\n capture: RolloutCapture\n /** Exact search-cell attempt; absent outside a search. */\n search?: { searchId: string; nodeId: string; cellId: string; attempt: number }\n /** Run-bound provider attempts; absent means this source was not observed. */\n attempts?: RolloutEvidenceAttempt[]\n /** Exact per-result receipts in source order. Null means Runtime had no result evidence. */\n workspace_captures?: readonly RolloutWorkspaceCapture[] | null\n /** A known lossy semantic projection. Training sinks refuse this line. */\n lossy_projection?: true\n /**\n * Why this line is incomplete. Required when `messages` is empty and set\n * for lossy last-context or capped-step projections. Importers also use it to\n * name a MISSING LABEL — an imported trajectory carries no verdict, so\n * `outcome.reward` is null and this says why.\n */\n gap?: string\n /**\n * Present only on a realness-gated line: the outcome fields the gate\n * relocated, kept so an auditor can still see WHY the run was gated and what\n * it claimed. Deliberately OUTSIDE `outcome`, because every training exporter\n * reads `outcome` and none reads `provenance`.\n */\n gated_evidence?: GatedEvidence\n}\n\nexport interface RolloutLine {\n schema: typeof ROLLOUT_SCHEMA\n rollout_id: string\n /** Spawning invocation within the same episode (worker → supervisor); for a\n * nested search run, the run of the cell that contains the search. */\n parent_rollout_id: string | null\n run_id: string\n /** Logical experiment grouping from `RunRecord.experimentId`; null = not recorded. */\n experiment_id: string | null\n /** Stable candidate identity from `RunRecord.candidateId`; null = not recorded. */\n candidate_id: string | null\n /** Search depth of the run's node (0 = the search root); null = not a search run. */\n generation: number | null\n /** Registration order of the run's node in its search (0 = the root); null = not a search run. */\n candidate_index: number | null\n role: RolloutRole\n task: RolloutTask\n policy: RolloutPolicy\n /** Inline conversation projection. Check provenance.gap before treating it as complete. */\n messages: ChatMessage[]\n tool_defs: ToolDef[]\n /** Trace-span projections, when minted from a trace. */\n steps?: RolloutStep[]\n outcome: RolloutOutcome\n cost: RolloutCostBlock\n artifacts: RolloutArtifacts\n provenance: RolloutProvenance\n}\n\n// ---------------------------------------------------------------------------\n// Validation — pure TS, no runtime schema dependency, mirroring the\n// run-record validator's fail-loud discipline. Returns [] when the value\n// is a valid RolloutLine; otherwise one dotted-path error per defect.\n// ---------------------------------------------------------------------------\n\nconst isNumberOrNull = (v: unknown): boolean => v === null || typeof v === 'number'\nconst isNumberArray = (v: unknown): boolean =>\n Array.isArray(v) && v.every((n) => typeof n === 'number' && Number.isFinite(n))\nconst isIntegerArray = (v: unknown): boolean =>\n Array.isArray(v) && v.every((n) => Number.isInteger(n))\nconst isStringOrNull = (v: unknown): boolean => v === null || typeof v === 'string'\nconst isIntegerOrNull = (v: unknown): boolean => v === null || Number.isInteger(v)\n\nfunction validateChatMessage(value: unknown, path: string, errors: string[]): void {\n if (!isRecord(value)) {\n errors.push(`${path}: not an object`)\n return\n }\n if (!CHAT_ROLES.includes(value.role as ChatRole))\n errors.push(`${path}.role: invalid role ${String(value.role)}`)\n if (!isStringOrNull(value.content)) errors.push(`${path}.content: must be string|null`)\n if (value.reasoning_content !== undefined && typeof value.reasoning_content !== 'string') {\n errors.push(`${path}.reasoning_content: must be string when present`)\n }\n if (value.tool_call_id !== undefined && typeof value.tool_call_id !== 'string') {\n errors.push(`${path}.tool_call_id: must be string when present`)\n }\n if (value.role === 'tool' && typeof value.tool_call_id !== 'string') {\n errors.push(`${path}.tool_call_id: required on role:\"tool\"`)\n }\n if (value.is_copied_context !== undefined && typeof value.is_copied_context !== 'boolean') {\n errors.push(`${path}.is_copied_context: must be boolean when present`)\n }\n if (value.tool_calls !== undefined) {\n if (!Array.isArray(value.tool_calls)) {\n errors.push(`${path}.tool_calls: must be an array when present`)\n } else {\n value.tool_calls.forEach((call, i) => {\n if (!isRecord(call) || typeof call.id !== 'string' || call.type !== 'function') {\n errors.push(`${path}.tool_calls[${i}]: must be {id, type:\"function\", function}`)\n return\n }\n const fn = call.function\n if (!isRecord(fn) || typeof fn.name !== 'string' || typeof fn.arguments !== 'string') {\n errors.push(\n `${path}.tool_calls[${i}].function: must be {name: string, arguments: string}`,\n )\n }\n })\n }\n }\n}\n\nfunction validateSection(\n value: unknown,\n path: string,\n fields: Array<[name: string, check: (v: unknown) => boolean, expect: string]>,\n errors: string[],\n): void {\n if (!isRecord(value)) {\n errors.push(`${path}: not an object`)\n return\n }\n for (const [name, check, expect] of fields) {\n if (!check(value[name])) errors.push(`${path}.${name}: expected ${expect}`)\n }\n}\n\n/**\n * THE anti-Goodhart gate, applied to the WHOLE outcome as a TRANSFORMATION.\n *\n * Two prior rounds enforced the gate as a CHECK ON ONE FIELD at N call sites,\n * and each round the next reward-bearing field leaked. The one that shipped:\n * `mintRolloutRows` bulk-copied `RunRecord.outcome.raw` into `outcome.metrics`\n * with no gate, so a gated run exported `reward: 0` (correct) while the\n * deterministic per-layer scores that reward was COMPUTED FROM — the\n * `layer.*` keys `rl/verifiable-reward.ts` calls the RL training signal —\n * shipped at 1.0, in the top-level `metrics` dict of the Prime Intellect\n * verifiers format, which IS that format's per-rubric score dict. `verdict`\n * leaks the same way into `toRftItem`'s `reference.verdict`, where a grader\n * author reads `resolved: true` off a run that faked it.\n *\n * So the rule is no longer \"zero the field we remembered\". It is: if the gate\n * fired, the outcome that leaves here carries NOTHING positive that was derived\n * from the reward, whichever field a present or future exporter decides to\n * read. `reward` is already forced to 0 upstream (`trainingReward`) and\n * REJECTED here if it is not; `metrics` and `verdict` are relocated.\n *\n * WHERE they go, and why relocation rather than deletion: zeroing destroys the\n * audit trail that shows why the run was gated and what it claimed, which is\n * the row an auditor most wants and the labeled example a gaming DETECTOR\n * trains on. `provenance.gated_evidence` keeps every byte, at a path no\n * training exporter reads — all four release configs and every `rl/exporters`\n * shape project from `outcome`, `messages`, `cost` and `task`; none projects\n * `provenance`. Auditability preserved, training signal removed, and a future\n * exporter that reads a field nobody thought of is safe by construction because\n * the field is empty rather than because the exporter remembered to check.\n *\n * Idempotent: a second application finds nothing left to move and returns the\n * line unchanged, so re-minting a line read back off a ledger cannot clobber\n * the evidence it already carries.\n */\nexport function gateGamedOutcome(line: RolloutLine): RolloutLine {\n if (line.outcome.realness_gated !== true) return line\n const moved = gatedEvidenceOf(line)\n if (moved === undefined) return line\n const kept = line.provenance.gated_evidence\n const evidence: GatedEvidence = {}\n const metrics = { ...kept?.metrics, ...moved.metrics }\n if (Object.keys(metrics).length > 0) evidence.metrics = metrics\n if (moved.verdict !== undefined) evidence.verdict = moved.verdict\n else if (kept?.verdict !== undefined) evidence.verdict = kept.verdict\n if (moved.steps !== undefined) evidence.steps = moved.steps\n else if (kept?.steps !== undefined) evidence.steps = kept.steps\n // The trajectory itself STAYS: a gamed transcript is the labeled example a\n // gaming detector trains on, and the exporters are meant to ship it. Only the\n // fields the wire format does not declare come off, which is the same\n // partition `gatedEvidenceOf` applies to `metrics` — the producer's own,\n // never a key-name guess.\n const steps = moved.steps === undefined ? line.steps : declaredSteps(line.steps)\n return {\n ...line,\n ...(steps === undefined ? {} : { steps }),\n outcome: { ...line.outcome, metrics: {}, verdict: null },\n provenance: { ...line.provenance, gated_evidence: evidence },\n }\n}\n\n/**\n * EVERY gate check, for the export path — the runtime backstop.\n *\n * `validateRolloutLine` checks the reward relationship too, but an exporter\n * cannot afford to re-validate every field of every line, and more importantly\n * it is not the exporter's job to re-check the schema — it is its job never to\n * emit a signal it was told is fabricated. Thrown rather than filtered: an\n * exporter silently dropping a poisoned line would hide the producer that made\n * it, and the producer is the actual defect.\n *\n * This is the third layer, and it exists for exactly one caller: JavaScript.\n * The brand stops TypeScript callers at compile time and `assertMinted` fixes\n * data arriving from disk, but neither is present for a plain JS consumer of\n * the published package handing an object literal to `toRewardRows`. Which is\n * exactly why this entry point's policy omits nothing: a check it skips is a\n * check that never runs for those callers at all. It composed two of the three\n * for one round, and a never-screened positive reward walked through all four\n * waist exporters at full value. `GATE_POLICIES.assertRewardGate` is now the\n * only place that list is written down.\n */\nexport function assertRewardGate(line: RolloutLine, context: string): void {\n const errors = gateErrors(line, GATE_POLICIES.assertRewardGate)\n if (errors.length > 0) {\n throw new Error(`${context}: rollout ${line.rollout_id} — ${errors[0]}`)\n }\n}\n\n/** Check the line's identity fields and the policy section. */\nfunction validateRolloutIdentity(value: Record<string, unknown>, errors: string[]): void {\n if (value.schema !== ROLLOUT_SCHEMA) errors.push(`schema: expected \"${ROLLOUT_SCHEMA}\"`)\n if (typeof value.rollout_id !== 'string' || value.rollout_id.length === 0)\n errors.push('rollout_id: expected non-empty string')\n if (!isStringOrNull(value.parent_rollout_id))\n errors.push('parent_rollout_id: expected string|null')\n if (typeof value.run_id !== 'string' || value.run_id.length === 0)\n errors.push('run_id: expected non-empty string')\n if (!isStringOrNull(value.experiment_id)) errors.push('experiment_id: expected string|null')\n if (!isStringOrNull(value.candidate_id)) errors.push('candidate_id: expected string|null')\n if (!isIntegerOrNull(value.generation)) errors.push('generation: expected integer|null')\n if (!isIntegerOrNull(value.candidate_index)) errors.push('candidate_index: expected integer|null')\n if (!ROLLOUT_ROLES.includes(value.role as RolloutRole))\n errors.push(`role: invalid role ${String(value.role)}`)\n\n validateSection(\n value.task,\n 'task',\n [\n ['suite', (v) => typeof v === 'string' && v.length > 0, 'non-empty string'],\n ['instance_id', (v) => typeof v === 'string' && v.length > 0, 'non-empty string'],\n [\n 'split',\n (v) => ROLLOUT_SPLITS.includes(v as RolloutSplit),\n `one of ${ROLLOUT_SPLITS.join('|')}`,\n ],\n ['seed', isNumberOrNull, 'number|null'],\n ['rep', (v) => Number.isInteger(v), 'integer'],\n ],\n errors,\n )\n\n validateSection(\n value.policy,\n 'policy',\n [\n ['harness', isStringOrNull, 'string|null'],\n ['harness_version', isStringOrNull, 'string|null'],\n ['model', isStringOrNull, 'string|null'],\n ['provider', isStringOrNull, 'string|null'],\n ['profile_commit', isStringOrNull, 'string|null'],\n ['sampling', (v) => v === null || isRecord(v), 'object|null'],\n ],\n errors,\n )\n if (isRecord(value.policy)) {\n for (const key of ['prompt_hash', 'config_hash', 'agent_profile_cell_id'] as const) {\n if (value.policy[key] !== undefined && !isStringOrNull(value.policy[key])) {\n errors.push(`policy.${key}: expected string|null when present`)\n }\n }\n const license = value.policy.license_class\n if (license !== undefined && !LICENSE_CLASSES.includes(license as LicenseClass)) {\n errors.push(`policy.license_class: expected one of ${LICENSE_CLASSES.join('|')}`)\n }\n }\n}\n\n/** Check the messages, tool definitions and steps arrays. */\nfunction validateRolloutTranscript(value: Record<string, unknown>, errors: string[]): void {\n if (!Array.isArray(value.messages)) {\n errors.push('messages: expected array')\n } else {\n for (const [i, m] of value.messages.entries()) validateChatMessage(m, `messages[${i}]`, errors)\n }\n\n if (!Array.isArray(value.tool_defs)) {\n errors.push('tool_defs: expected array')\n } else {\n value.tool_defs.forEach((d, i) => {\n if (\n !isRecord(d) ||\n d.type !== 'function' ||\n !isRecord(d.function) ||\n typeof d.function.name !== 'string'\n ) {\n errors.push(`tool_defs[${i}]: must be {type:\"function\", function:{name}}`)\n }\n })\n }\n\n if (value.steps !== undefined) {\n if (!Array.isArray(value.steps)) {\n errors.push('steps: expected array when present')\n } else {\n value.steps.forEach((s, i) => {\n if (!isRecord(s) || typeof s.kind !== 'string' || typeof s.name !== 'string') {\n errors.push(`steps[${i}]: must be {kind: string, name: string, …}`)\n return\n }\n // ATIF-lifted optionals: absent on every line written before they\n // existed, so they are checked only when present — old ledgers stay valid.\n if (s.llm_call_count !== undefined && !Number.isInteger(s.llm_call_count)) {\n errors.push(`steps[${i}].llm_call_count: expected integer when present`)\n }\n for (const key of ['prompt_token_ids', 'completion_token_ids'] as const) {\n if (s[key] !== undefined && !isIntegerArray(s[key])) {\n errors.push(`steps[${i}].${key}: expected integer[] when present`)\n }\n }\n if (s.logprobs !== undefined && !isNumberArray(s.logprobs)) {\n errors.push(`steps[${i}].logprobs: expected number[] when present`)\n }\n })\n }\n }\n}\n\n/** Check the outcome section, the cost section and the reward gate. */\nfunction validateRolloutOutcomeAndCost(value: Record<string, unknown>, errors: string[]): void {\n validateSection(\n value.outcome,\n 'outcome',\n [\n ['reward', isNumberOrNull, 'number|null'],\n ['reward_source', isStringOrNull, 'string|null'],\n ['metrics', isRecord, 'object'],\n ['is_completed', (v) => typeof v === 'boolean', 'boolean'],\n ['is_truncated', (v) => typeof v === 'boolean', 'boolean'],\n ['error', isStringOrNull, 'string|null'],\n ],\n errors,\n )\n if (isRecord(value.outcome)) {\n if (!('verdict' in value.outcome)) errors.push('outcome.verdict: field required (may be null)')\n if (typeof value.outcome.realness_gated !== 'boolean') {\n errors.push('outcome.realness_gated: expected boolean')\n }\n if (\n value.outcome.realness_screened !== undefined &&\n typeof value.outcome.realness_screened !== 'boolean'\n ) {\n errors.push('outcome.realness_screened: expected boolean when present')\n }\n errors.push(\n ...gateErrors(\n { outcome: value.outcome, steps: value.steps },\n GATE_POLICIES.validateRolloutLine,\n ),\n )\n }\n\n validateSection(\n value.cost,\n 'cost',\n [\n ['usd', isNumberOrNull, 'number|null'],\n ['tokens_in', isNumberOrNull, 'number|null'],\n ['tokens_out', isNumberOrNull, 'number|null'],\n ['tokens_reasoning', isNumberOrNull, 'number|null'],\n ['cache_read', isNumberOrNull, 'number|null'],\n ['cache_write', isNumberOrNull, 'number|null'],\n ['wall_s', isNumberOrNull, 'number|null'],\n ],\n errors,\n )\n if (\n isRecord(value.cost) &&\n value.cost.llm_call_count !== undefined &&\n !(value.cost.llm_call_count === null || Number.isInteger(value.cost.llm_call_count))\n ) {\n errors.push('cost.llm_call_count: expected integer|null when present')\n }\n}\n\n/** Check the lossy-projection flag and its gap note. */\nfunction validateLossyProjection(provenance: Record<string, unknown>, errors: string[]): void {\n if (provenance.lossy_projection !== undefined && provenance.lossy_projection !== true) {\n errors.push('provenance.lossy_projection: expected true when present')\n }\n if (\n provenance.lossy_projection === true &&\n (typeof provenance.gap !== 'string' || provenance.gap.length === 0)\n ) {\n errors.push('provenance.gap: required for a lossy projection')\n }\n}\n\n/** Check the search coordinates of a search-produced rollout. */\nfunction validateProvenanceSearch(search: unknown, errors: string[]): void {\n if (search === undefined) return\n if (\n !isRecord(search) ||\n typeof search.searchId !== 'string' ||\n !search.searchId ||\n typeof search.nodeId !== 'string' ||\n !search.nodeId ||\n typeof search.cellId !== 'string' ||\n !search.cellId ||\n !Number.isSafeInteger(search.attempt) ||\n (search.attempt as number) < 1\n ) {\n errors.push('provenance.search: expected exact search, node, cell and positive attempt')\n }\n}\n\n/** Check each workspace capture's evidence fields. */\nfunction validateWorkspaceCaptures(captures: unknown, errors: string[]): void {\n if (captures === undefined || captures === null) return\n if (!Array.isArray(captures)) {\n errors.push('provenance.workspace_captures: expected array|null when present')\n return\n }\n for (const [i, capture] of captures.entries()) {\n if (\n !isRecord(capture) ||\n !isStringOrNull(capture.outRef) ||\n !isStringOrNull(capture.blobPath) ||\n !isStringOrNull(capture.receiptPointer) ||\n !('receipt' in capture) ||\n (capture.attempts !== null && !Array.isArray(capture.attempts)) ||\n (capture.coverageComplete !== null && typeof capture.coverageComplete !== 'boolean') ||\n !isStringOrNull(capture.incompleteReason) ||\n !isStringOrNull(capture.projectionGap)\n ) {\n errors.push(`provenance.workspace_captures[${i}]: invalid capture evidence`)\n }\n }\n}\n\n/** Check each attempt's evidence and that every execution's ordinals are unique and contiguous from 1. */\nfunction validateProvenanceAttempts(attempts: unknown, errors: string[]): void {\n if (attempts === undefined) return\n if (!Array.isArray(attempts)) {\n errors.push('provenance.attempts: expected array when present')\n return\n }\n const ordinalsByExecution = new Map<string, Set<number>>()\n for (const [i, attempt] of attempts.entries()) {\n if (\n !isRecord(attempt) ||\n typeof attempt.executionId !== 'string' ||\n !attempt.executionId ||\n !Number.isSafeInteger(attempt.ordinal) ||\n (attempt.ordinal as number) < 1 ||\n !isStringOrNull(attempt.providerSessionId) ||\n !Array.isArray(attempt.nativeSessionIds) ||\n !attempt.nativeSessionIds.every((id) => typeof id === 'string' && id.length > 0) ||\n !Array.isArray(attempt.processIds) ||\n !attempt.processIds.every((id) => typeof id === 'string' && id.length > 0) ||\n !['succeeded', 'failed', 'cancelled', 'unknown'].includes(attempt.outcome as string) ||\n !Array.isArray(attempt.missingReasons) ||\n !attempt.missingReasons.every((reason) => typeof reason === 'string' && reason.length > 0)\n ) {\n errors.push(`provenance.attempts[${i}]: invalid attempt evidence`)\n continue\n }\n const executionId = attempt.executionId as string\n const ordinal = attempt.ordinal as number\n const seen = ordinalsByExecution.get(executionId) ?? new Set<number>()\n if (seen.has(ordinal)) {\n errors.push(`provenance.attempts[${i}]: duplicate execution/ordinal`)\n }\n seen.add(ordinal)\n ordinalsByExecution.set(executionId, seen)\n }\n for (const [executionId, ordinals] of ordinalsByExecution) {\n for (let ordinal = 1; ordinal <= ordinals.size; ordinal++) {\n if (!ordinals.has(ordinal)) {\n errors.push(`provenance.attempts: ${executionId} is missing ordinal ${ordinal}`)\n }\n }\n }\n}\n\n/** Check the artifacts and provenance sections. */\nfunction validateRolloutProvenance(value: Record<string, unknown>, errors: string[]): void {\n validateSection(\n value.artifacts,\n 'artifacts',\n [\n ['patch_path', isStringOrNull, 'string|null'],\n ['run_dir', isStringOrNull, 'string|null'],\n ['transcript_ref', isStringOrNull, 'string|null'],\n ],\n errors,\n )\n\n validateSection(\n value.provenance,\n 'provenance',\n [\n [\n 'captured_at',\n (v) => typeof v === 'string' && !Number.isNaN(Date.parse(v)),\n 'ISO-8601 timestamp',\n ],\n [\n 'capture',\n (v) => ROLLOUT_CAPTURES.includes(v as RolloutCapture),\n `one of ${ROLLOUT_CAPTURES.join('|')}`,\n ],\n ],\n errors,\n )\n if (!isRecord(value.provenance)) return\n const provenance = value.provenance\n validateLossyProjection(provenance, errors)\n validateProvenanceSearch(provenance.search, errors)\n validateWorkspaceCaptures(provenance.workspace_captures, errors)\n validateProvenanceAttempts(provenance.attempts, errors)\n if (provenance.gap !== undefined && typeof provenance.gap !== 'string') {\n errors.push('provenance.gap: must be string when present')\n }\n const evidence = provenance.gated_evidence\n if (evidence !== undefined) {\n if (!isRecord(evidence)) {\n errors.push('provenance.gated_evidence: must be an object when present')\n } else if (evidence.metrics !== undefined && !isRecord(evidence.metrics)) {\n errors.push('provenance.gated_evidence.metrics: must be an object when present')\n }\n }\n}\n\nexport function validateRolloutLine(value: unknown): string[] {\n const errors: string[] = []\n if (!isRecord(value)) return ['line: not an object']\n\n validateRolloutIdentity(value, errors)\n validateRolloutTranscript(value, errors)\n validateRolloutOutcomeAndCost(value, errors)\n validateRolloutProvenance(value, errors)\n\n // A gap line must say WHY it is a gap; a full line must not carry a gap note.\n if (Array.isArray(value.messages) && isRecord(value.provenance)) {\n if (value.messages.length === 0 && typeof value.provenance.gap !== 'string') {\n errors.push('provenance.gap: required when messages is empty')\n }\n }\n\n return errors\n}\n\nexport function assertRolloutLine(\n value: unknown,\n context = 'rollout line',\n): asserts value is RolloutLine {\n const errors = validateRolloutLine(value)\n if (errors.length > 0) {\n throw new Error(`invalid ${context}:\\n ${errors.join('\\n ')}`)\n }\n}\n\nexport function isRolloutLine(value: unknown): value is RolloutLine {\n return validateRolloutLine(value).length === 0\n}\n\n// ---------------------------------------------------------------------------\n// The minted brand — the COMPILE-TIME half of the anti-Goodhart gate.\n// ---------------------------------------------------------------------------\n\n/**\n * Phantom property. `declare const` means it exists only in the type system:\n * nothing is written at runtime, so a branded line still serializes to exactly\n * the same JSON as a plain one.\n */\ndeclare const MINTED_ROLLOUT: unique symbol\n\n/**\n * A minted outcome states the gate verdict — it is not allowed to stay silent —\n * and, when that verdict is `true`, carries nothing else the reward was derived\n * from (`gateGamedOutcome` has run).\n */\nexport interface MintedRolloutOutcome extends RolloutOutcome {\n realness_gated: boolean\n}\n\n/**\n * A `RolloutLine` whose reward has been checked against the anti-Goodhart\n * invariant. The type every training-data exporter takes.\n *\n * Why a brand and not just the interface: `RolloutLine` is structural, so any\n * hand-built object literal of the right shape IS one — which is how a line\n * declaring `{reward: 0.95, realness_gated: true}` reached the exporters\n * despite them \"only accepting a minted line\". The phantom symbol makes the\n * type nominal: it cannot be produced by writing an object literal, only by\n * `mintRolloutRows` (which applies the gate), `readRolloutLedger` (which\n * validates every line off disk), or an explicit, greppable `assertMinted`.\n *\n * Belt and braces on purpose. The brand closes first-party call sites at\n * COMPILE time; `validateRolloutLine` closes data arriving at RUNTIME (ledger\n * files, foreign imports, JSON from another process) where types are absent.\n * Neither alone is enough.\n *\n * Assignable to `RolloutLine` in one direction only: readers, analysis, and\n * the ledger writer keep taking the plain type.\n */\nexport type MintedRolloutLine = Omit<RolloutLine, 'outcome'> & {\n readonly [MINTED_ROLLOUT]: true\n outcome: MintedRolloutOutcome\n}\n\n/**\n * Promote a line to the type the training exporters accept, applying the\n * anti-Goodhart gate to the WHOLE outcome on the way through. THE escape hatch\n * — grep `assertMinted` to enumerate every place a line enters the training\n * path without coming from mint or a ledger.\n *\n * The gate runs HERE, once, rather than at each producer, because this is the\n * single funnel every minted line passes: `mintRolloutRows` calls it,\n * `readRolloutLedger` calls it per line off disk, `scrubLines` calls it on the\n * way out of a release, and a hand-built line has no other door. One\n * transformation at the funnel means an already-published ledger holding a\n * gated line with populated `metrics` is RE-GATED when it is read, instead of\n * being rejected (which would make every such artifact unreadable) or trusted\n * (which is the leak). Three steps, in this order:\n *\n * 1. VALIDATE the schema.\n * 2. REFUSE every check `GATE_POLICIES.assertMinted` marks `enforce` — today\n * the reward relationship (which stays a REJECTION: a caller claiming\n * `{reward: 0.95, realness_gated: true}` is a producer defect and must fail\n * loudly, since laundering it into `reward: 0` here would hide the\n * producer) and a positive reward the producer declared it never screened.\n * 3. TRANSFORM the one check that policy marks `repair` — relocate the\n * reward's components off `outcome` (`gateGamedOutcome`), so no exporter\n * can leak them whichever field it reads.\n *\n * Step 2 enumerates nothing by hand: a check added to `GATE_CHECKS` is enforced\n * here the moment its disposition in that policy says so.\n *\n * Also normalizes the optional wire flag to an explicit boolean.\n * `realness_gated` is absent on pre-unification ledgers and absent means \"not\n * flagged\" per the schema, so filling it in states a claim the line was already\n * making, and makes the flag readable on every published row instead of most of\n * them. `realness_screened` is NOT filled in: absent means \"unknown\", and\n * inventing either value there would be the same overclaim this round removed.\n */\nexport function assertMinted(value: unknown, context = 'rollout line'): MintedRolloutLine {\n assertRolloutLine(value, context)\n const refused = gateErrors(value, GATE_POLICIES.assertMinted)\n if (refused.length > 0) {\n throw new Error(`invalid ${context}: rollout ${value.rollout_id} — ${refused[0]}`)\n }\n const gated = gateGamedOutcome(value)\n if (gated.outcome.realness_gated === undefined) {\n return {\n ...gated,\n outcome: { ...gated.outcome, realness_gated: false },\n } as MintedRolloutLine\n }\n return gated as MintedRolloutLine\n}\n\n/** `assertMinted` over a batch, naming the offending index in the error. */\nexport function assertMintedLines(\n values: readonly unknown[],\n context = 'rollout line',\n): MintedRolloutLine[] {\n return values.map((value, i) => assertMinted(value, `${context} [${i}]`))\n}\n"],"mappings":";;AA0BA,MAAa,kBAA2C;CACtD;CACA;CACA;CACA;AACF;AAEA,MAAM,aAAa;AACnB,MAAM,cACJ;;AAGF,SAAgB,mBAAmB,MAAsD;CACvF,IAAI,CAAC,MAAM,OAAO;CAClB,IAAI,WAAW,KAAK,IAAI,GAAG,OAAO;CAClC,IAAI,YAAY,KAAK,IAAI,GAAG,OAAO;CACnC,OAAO;AACT;;AAGA,SAAgB,eAAe,MAAwD;CACrF,MAAM,EAAE,eAAe,OAAO,YAAY,KAAK;CAC/C,IAAI,kBAAkB,KAAA,GAAW,OAAO;CACxC,MAAM,YAAY,mBAAmB,OAAO;CAC5C,IAAI,cAAc,cAAc,OAAO;CACvC,OAAO,mBAAmB,KAAK,KAAK;AACtC;;AAGA,SAAgB,kBACd,MACA,SACS;CACT,IAAI,YAAY,KAAA,GAAW,OAAO;CAClC,MAAM,UAAU,eAAe,IAAI;CACnC,OAAO,YAAY,QAAQ,QAAQ,SAAS,OAAO;AACrD;;;;;;;;;ACnBA,MAAa,iBAAiB;CAC5B;CACA;CACA;CACA;AACF;;AAq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