@tangle-network/agent-eval 0.202.2 → 0.203.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/dist/adapters/http.d.ts +2 -2
- package/dist/analyst/index.d.ts +5 -5
- package/dist/analyst/index.js +1 -1
- package/dist/benchmarks/index.d.ts +4 -4
- package/dist/campaign/index.d.ts +4 -4
- package/dist/cli.js +2 -2
- package/dist/contract/index.d.ts +7 -7
- package/dist/contract/index.js +1 -1
- package/dist/{default-registry-DesnDBvl.d.ts → default-registry-B-utjsmX.d.ts} +3 -3
- package/dist/{default-registry-DesnDBvl.d.ts.map → default-registry-B-utjsmX.d.ts.map} +1 -1
- package/dist/{default-registry-6QOiTzqi.js → default-registry-CpswV_S2.js} +2 -2
- package/dist/{default-registry-6QOiTzqi.js.map → default-registry-CpswV_S2.js.map} +1 -1
- package/dist/{define-agent-eval-BDPV3ieA.d.ts → define-agent-eval-MAc6BQrq.d.ts} +5 -5
- package/dist/{define-agent-eval-BDPV3ieA.d.ts.map → define-agent-eval-MAc6BQrq.d.ts.map} +1 -1
- package/dist/{engine-neXmlmTu.d.ts → engine-4_Q4oujc.d.ts} +2 -2
- package/dist/{engine-neXmlmTu.d.ts.map → engine-4_Q4oujc.d.ts.map} +1 -1
- package/dist/evaluation.d.ts +1 -1
- package/dist/experiment/index.d.ts +1 -1
- package/dist/{exporters-DjCu6-lX.d.ts → exporters-ChTnR90l.d.ts} +2 -2
- package/dist/{exporters-DjCu6-lX.d.ts.map → exporters-ChTnR90l.d.ts.map} +1 -1
- package/dist/{exporters-ISzpUY3e.js → exporters-X4xwla8A.js} +2 -2
- package/dist/{exporters-ISzpUY3e.js.map → exporters-X4xwla8A.js.map} +1 -1
- package/dist/{hf-dataset-DdT7nNkf.js → hf-dataset-BR2yhuNn.js} +3 -3
- package/dist/{hf-dataset-DdT7nNkf.js.map → hf-dataset-BR2yhuNn.js.map} +1 -1
- package/dist/{index-BCBpEreJ.d.ts → index-BoVEyQwH.d.ts} +4 -4
- package/dist/{index-BCBpEreJ.d.ts.map → index-BoVEyQwH.d.ts.map} +1 -1
- package/dist/{index-BPCdNSMW.d.ts → index-CAtNOBQY.d.ts} +4 -4
- package/dist/{index-BPCdNSMW.d.ts.map → index-CAtNOBQY.d.ts.map} +1 -1
- package/dist/{index-CnKgaHKA.d.ts → index-Cuhxk05B.d.ts} +6 -6
- package/dist/{index-CnKgaHKA.d.ts.map → index-Cuhxk05B.d.ts.map} +1 -1
- package/dist/{index-BtcxmabC.d.ts → index-DBk_4UPs.d.ts} +4 -4
- package/dist/{index-BtcxmabC.d.ts.map → index-DBk_4UPs.d.ts.map} +1 -1
- package/dist/index.d.ts +12 -12
- package/dist/index.js +3 -3
- package/dist/{integrity-atFlABhR.js → integrity-BV1ZDf42.js} +38 -6
- package/dist/{integrity-atFlABhR.js.map → integrity-BV1ZDf42.js.map} +1 -1
- package/dist/jev.d.ts +1 -1
- package/dist/{matrix-DRXCV70M.d.ts → matrix-BucOjLF1.d.ts} +2 -2
- package/dist/{matrix-DRXCV70M.d.ts.map → matrix-BucOjLF1.d.ts.map} +1 -1
- package/dist/{mint-BFTrlq4t.d.ts → mint-C1W8w5wo.d.ts} +2 -2
- package/dist/{mint-BFTrlq4t.d.ts.map → mint-C1W8w5wo.d.ts.map} +1 -1
- package/dist/{mint-DE6nQrX_.js → mint-CWG-s2mI.js} +2 -2
- package/dist/{mint-DE6nQrX_.js.map → mint-CWG-s2mI.js.map} +1 -1
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +2 -2
- package/dist/openapi.json +1 -1
- package/dist/{report-command-DzPpFgjB.js → report-command-D0XL2Cvi.js} +128 -15
- package/dist/report-command-D0XL2Cvi.js.map +1 -0
- package/dist/rl.d.ts +5 -5
- package/dist/rl.js +3 -3
- package/dist/rollout/index.d.ts +5 -5
- package/dist/rollout/index.js +5 -5
- package/dist/{rollout-DTunVdJE.js → rollout-BdCoWV9n.js} +5 -5
- package/dist/{rollout-DTunVdJE.js.map → rollout-BdCoWV9n.js.map} +1 -1
- package/dist/{schema-D08IIzui.js → schema-BuiujZ-g.js} +15 -5
- package/dist/schema-BuiujZ-g.js.map +1 -0
- package/dist/{schema-Bp8S20Ii.d.ts → schema-C-ziyJD7.d.ts} +17 -2
- package/dist/schema-C-ziyJD7.d.ts.map +1 -0
- package/dist/search/index.d.ts +2 -2
- package/dist/{search-kernel-zI-rsHoG.d.ts → search-kernel-B8RC6BlK.d.ts} +2 -2
- package/dist/{search-kernel-zI-rsHoG.d.ts.map → search-kernel-B8RC6BlK.d.ts.map} +1 -1
- package/dist/{statistical-heldout-BAbd_oXC.d.ts → statistical-heldout-DJtQAUZB.d.ts} +2 -2
- package/dist/{statistical-heldout-BAbd_oXC.d.ts.map → statistical-heldout-DJtQAUZB.d.ts.map} +1 -1
- package/dist/{store-tool-spans-CKRw7JHa.d.ts → store-tool-spans-fkNF7Q9Y.d.ts} +3 -3
- package/dist/{store-tool-spans-CKRw7JHa.d.ts.map → store-tool-spans-fkNF7Q9Y.d.ts.map} +1 -1
- package/dist/supervisor-run/index.d.ts +2 -2
- package/dist/supervisor-run/index.d.ts.map +1 -1
- package/dist/supervisor-run/index.js +2 -2
- package/dist/terminal-record-BHocwFw1.js.map +1 -1
- package/dist/{tool-groups-V23aGP_g.d.ts → tool-groups-Zm84Pqpk.d.ts} +2 -2
- package/dist/tool-groups-Zm84Pqpk.d.ts.map +1 -0
- package/dist/{trace-questions-B-Wf0W3Q.d.ts → trace-questions--lnJTaou.d.ts} +2 -2
- package/dist/{trace-questions-B-Wf0W3Q.d.ts.map → trace-questions--lnJTaou.d.ts.map} +1 -1
- package/dist/trace-repair/index.d.ts +1 -1
- package/dist/traces.d.ts +2 -2
- package/dist/{types-BbiT5NPH.d.ts → types-B6JadxWL.d.ts} +2 -2
- package/dist/{types-BbiT5NPH.d.ts.map → types-B6JadxWL.d.ts.map} +1 -1
- package/dist/{types-BR1LLIxm.d.ts → types-khIUQ0O5.d.ts} +2 -2
- package/dist/{types-BR1LLIxm.d.ts.map → types-khIUQ0O5.d.ts.map} +1 -1
- package/dist/{types-DUlbOCwL.d.ts → types-v6nRcIqg.d.ts} +11 -3
- package/dist/types-v6nRcIqg.d.ts.map +1 -0
- package/docs/rollout.md +32 -0
- package/package.json +1 -1
- package/dist/report-command-DzPpFgjB.js.map +0 -1
- package/dist/schema-Bp8S20Ii.d.ts.map +0 -1
- package/dist/schema-D08IIzui.js.map +0 -1
- package/dist/tool-groups-V23aGP_g.d.ts.map +0 -1
- package/dist/types-DUlbOCwL.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mint-DE6nQrX_.js","names":[],"sources":["../src/rollout/mint.ts"],"sourcesContent":["/**\n * Rollout minting — `tangle.rollout.v1` lines joined from the records the\n * substrate ALREADY keeps. There is no separate rollout store: a rollout\n * is the JOIN of a RunRecord (identity, provenance, cost, outcome) with\n * its trace (spans share `runId`), projected into the canonical line.\n *\n * Composition, not duplication:\n * - identity/provenance → `RunRecord` (candidateId, splitTag, agentProfile, hashes)\n * - step structure → `buildTrajectory` over the shared TraceStore\n * - preference-pair export → `feedbackTrajectoryToOptimizerRow` (feedback-trajectory.ts)\n * - PRM / reward-model → `reward-model-export.ts`\n * - search lineage → `searchLineage`, read from the run's search ledger\n *\n * Anti-Goodhart invariant: a run whose `outcome.realness.gated` is true is\n * never exported with a positive reward OR with any of the numbers that reward\n * was computed from. The gate travels into the training data (`reward` forced\n * to 0, `realness_gated: true`) and the whole outcome is transformed by\n * `gateGamedOutcome` inside `assertMinted` below, which relocates `metrics` and\n * `verdict` to `provenance.gated_evidence`. Mint returns\n * `MintedRolloutLine[]`: the brand the training exporters require, which only\n * this function, `readRolloutLedger`, and an explicit `assertMinted` can mint.\n *\n * A record carrying NEITHER split score is REJECTED (`ValidationError`), never\n * minted at 0 — \"nobody graded this\" is not the same claim as \"graded a total\n * failure\", and a trainer reading 0 learns the second. Lines that already\n * carry `reward: null` (interchange imports, existing ledgers) remain valid on\n * the wire; only the RunRecord→line door refuses.\n *\n * Records without spans or an explicit full capture become labeled GAP LINES (messages: [],\n * provenance.gap) — present in the output AND surfaced in\n * `missingTraces`; a capture gap is a finding, never a silent omission.\n */\n\nimport { ValidationError } from '../errors'\nimport { type RunRecord, type RunSearchCoordinates, runTaskScore } from '../run-record'\nimport type { LlmSpan, Span, ToolSpan } from '../trace/schema'\nimport type { TraceStore } from '../trace/store'\nimport { buildTrajectory } from '../trajectory'\nimport { rolloutRewardFields, scoreOrigin } from './reward'\nimport {\n assertMinted,\n type ChatMessage,\n type MintedRolloutLine,\n ROLLOUT_SCHEMA,\n type RolloutEvidenceAttempt,\n type RolloutRole,\n type RolloutSplit,\n type RolloutStep,\n} from './schema'\n\n/** Redactor for transcript/step payload text (secrets, PII), not opaque identity. */\nexport type RolloutScrubber = (text: string) => string\n\n/** A search cell's place in its search tree, read from the search ledger. */\nexport interface RolloutSearchLineage {\n /** Edges between the cell's node and the search root; the root is 0. */\n depth: number\n /** Order in which the node registered in its search; the root is 0. */\n ordinal: number\n /** Repeat index of the cell on its task, from 0. */\n rep: number\n /** Run id of the cell whose execution contains this search; null for a\n * top-level search. */\n containingRunId: string | null\n}\n\nexport interface MintRolloutOptions {\n scrub?: RolloutScrubber\n /**\n * Full canonical capture, including turns no longer in the model's context.\n * When supplied, missing/empty capture is refused, never replaced with a\n * span summary. Use the execution owner's capture or the existing harness\n * readers; reviewer traces and compacted histories are not full capture.\n */\n messagesOf?: (\n runId: string,\n ) => readonly ChatMessage[] | undefined | Promise<readonly ChatMessage[] | undefined>\n /** Provider attempts from a retained receipt bound to the exact run. */\n evidenceOf?: (\n runId: string,\n ) =>\n | { runId: string; attempts: readonly RolloutEvidenceAttempt[] }\n | undefined\n | Promise<{ runId: string; attempts: readonly RolloutEvidenceAttempt[] } | undefined>\n /** Cap steps per line (longest runs first drop middle steps). Default: no cap. */\n maxSteps?: number\n /** Role recorded on every minted line. Default 'agent' (a solo eval run). */\n role?: RolloutRole\n /** Task suite label. Default: the record's `experimentId`. */\n suite?: string\n /** Injected clock for deterministic output. */\n now?: () => Date\n /**\n * Lineage of a search run, read from its search ledger. It fills the line's\n * `generation` (node depth), `candidate_index` (node order), `task.rep` and\n * `parent_rollout_id` (the containing cell's run). Mint refuses a record\n * that carries `search` when this is absent, because a null `generation`\n * states that the run is not part of a search.\n */\n searchLineage?: (\n search: RunSearchCoordinates,\n ) => RolloutSearchLineage | Promise<RolloutSearchLineage>\n}\n\nexport interface MintRolloutResult {\n rows: MintedRolloutLine[]\n /** runIds that had a RunRecord but no spans — emitted as gap lines AND listed here. */\n missingTraces: string[]\n}\n\nconst asText = (v: unknown, scrub: RolloutScrubber): string => {\n const s = typeof v === 'string' ? v : JSON.stringify(v)\n return scrub(s ?? '')\n}\n\nfunction projectStep(span: Span, scrub: RolloutScrubber): RolloutStep {\n const base: RolloutStep = {\n kind: span.kind,\n name: scrub(span.name),\n status: span.status,\n durationMs: span.endedAt !== undefined ? span.endedAt - span.startedAt : undefined,\n }\n if (span.kind === 'llm') {\n const llm = span as LlmSpan\n const last = llm.messages[llm.messages.length - 1]\n if (last && last.content !== null) base.input = scrub(last.content)\n if (llm.output !== undefined) base.output = scrub(llm.output)\n } else if (span.kind === 'tool') {\n const tool = span as ToolSpan\n base.input = asText(tool.args, scrub)\n if (tool.result !== undefined) base.output = asText(tool.result, scrub)\n }\n return base\n}\n\n/** Preserve captured fields; invocation ids are opaque linkage, not generated text. */\nfunction projectMessage(message: ChatMessage, scrub: RolloutScrubber): ChatMessage {\n return {\n role: message.role,\n content: message.content === null ? null : scrub(message.content),\n ...(message.reasoning_content !== undefined\n ? { reasoning_content: scrub(message.reasoning_content) }\n : {}),\n ...(message.tool_calls !== undefined\n ? {\n tool_calls: message.tool_calls.map((call) => ({\n id: call.id,\n type: call.type,\n function: {\n name: call.function.name,\n arguments: scrub(call.function.arguments),\n },\n })),\n }\n : {}),\n ...(message.tool_call_id !== undefined ? { tool_call_id: message.tool_call_id } : {}),\n ...(message.name !== undefined ? { name: message.name } : {}),\n ...(message.is_copied_context !== undefined\n ? { is_copied_context: message.is_copied_context }\n : {}),\n }\n}\n\n/** Never recover missing calls from tool names, span order or argument summaries. */\nfunction requireToolLinkage(messages: readonly ChatMessage[], runId: string): void {\n const seen = new Set<string>()\n const pending = new Map<string, string>()\n const refuse: (detail: string) => never = (detail) => {\n throw new ValidationError(`Cannot mint rollout for run ${runId}: ${detail}`)\n }\n for (const message of messages) {\n if (message.tool_calls !== undefined) {\n if (message.role !== 'assistant' || !Array.isArray(message.tool_calls)) {\n refuse('tool calls must be captured on an assistant message')\n }\n if (pending.size > 0) refuse('new tool calls precede the prior invocation results')\n for (const call of message.tool_calls) {\n if (\n !call ||\n typeof call.id !== 'string' ||\n call.id.length === 0 ||\n seen.has(call.id) ||\n call.type !== 'function' ||\n !call.function ||\n typeof call.function.name !== 'string' ||\n call.function.name.length === 0 ||\n typeof call.function.arguments !== 'string'\n ) {\n refuse('missing, duplicate or malformed tool invocation')\n }\n seen.add(call.id)\n pending.set(call.id, call.function.name)\n }\n }\n if (message.role === 'tool') {\n const id = message.tool_call_id\n if (typeof id !== 'string' || !pending.has(id)) {\n refuse('tool result has no captured invocation (or answers it more than once)')\n }\n if (message.name !== undefined && message.name !== pending.get(id)) {\n refuse('tool result name does not match its invocation')\n }\n pending.delete(id)\n } else if (message.tool_call_id !== undefined) {\n refuse('tool_call_id is only valid on a tool result')\n } else if (pending.size > 0 && message.tool_calls === undefined) {\n refuse('conversation advances before all tool results were captured')\n }\n }\n if (pending.size > 0) refuse('tool invocation has no captured result')\n}\n\n/** Legacy span history; callers with compacted contexts supply messagesOf instead. */\nfunction finalConversation(spans: Span[]): ChatMessage[] {\n const llms = spans.filter((s): s is LlmSpan => s.kind === 'llm')\n const last = llms[llms.length - 1]\n if (!last) return []\n const messages: ChatMessage[] = [...last.messages]\n if (last.output !== undefined && last.output !== '') {\n messages.push({ role: 'assistant', content: last.output })\n }\n return messages\n}\n\n// The reward derivations live in the leaf module `./reward` so gate and\n// reporting code can import them without dragging in the trace store; they are\n// re-exported here because the derivations shipped from this path.\nexport {\n isRealnessGated,\n observedScore,\n observedSplitScore,\n type ScoreOrigin,\n type ScorePreference,\n scoreOrigin,\n trainingReward,\n trainingScore,\n} from './reward'\n\nconst REWARD_SOURCE: Record<ReturnType<typeof scoreOrigin>, string> = {\n holdout: 'run-record/holdout-score',\n search: 'run-record/search-score',\n unscored: 'run-record/unscored',\n}\n\n/**\n * The mint door refuses an execution-only record: a missing training label is\n * not a zero reward, and not a mintable line either. Lines that already carry\n * `reward: null` — interchange imports, existing ledgers — stay valid on the\n * wire and keep their labeled gap; this guard is only about the\n * RunRecord→line door, where the producer can still be told to go score the\n * run instead of shipping an unlabeled row.\n */\nfunction requireTaskScore(record: RunRecord): void {\n if (runTaskScore(record) === undefined) {\n throw new ValidationError(`Cannot mint rollout for run ${record.runId}: task score is missing`)\n }\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null\n\ninterface MintFieldCheck {\n /** The RunRecord path, spelled the way the caller has to fix it. */\n readonly field: string\n /** True when the record carries something the line can honestly be built from. */\n readonly present: (bag: Record<string, unknown>) => boolean\n /** What the caller writes onto the record, and why that value and not another. */\n readonly remedy: string\n}\n\n/**\n * The RunRecord fields mint reads that a record can be missing even though the\n * TYPE says it cannot. There are exactly two ways that happens:\n *\n * 1. The field was OPTIONAL when the record was serialized. `costProvenance`,\n * `terminalOutcome` and `scenarioId` were optional through agent-eval\n * 0.125 and became required in 0.126, with no on-disk migration — so every\n * ledger written before 0.126 is full of records the type calls complete.\n * 2. Mint reads a level DEEPER than the record's own type is checked at:\n * `outcome.raw`, `tokenUsage.input`, `tokenUsage.output`.\n *\n * Nothing else needs a check here. Every other field mint copies is a top-level\n * scalar landing in a typed slot on the line, where an absent value arrives as\n * `undefined` and `assertMinted` refuses it by name. These are the ones where an\n * absent value instead kills the join with `TypeError: Cannot read properties of\n * undefined`, or — worse — mints a line that reads as measured.\n *\n * This is deliberately NOT `validateRunRecord`. That validator answers \"is this\n * a valid RunRecord\", which is a wider question than \"can a rollout line be\n * built from this one\": it also enforces model-snapshot discipline, the\n * `terminalFailureReason` coupling, and the `costUsd === costProvenance.usd`\n * agreement. Routing the mint door through it would refuse records mint can\n * mint honestly today (a model alias with no snapshot date, for one), which is\n * a policy change with its own blast radius and not this bug. The door asks the\n * narrower question and answers it precisely.\n */\nconst MINT_FIELD_CHECKS: readonly MintFieldCheck[] = [\n {\n field: 'costProvenance',\n present: (bag) => isObject(bag.costProvenance) && typeof bag.costProvenance.kind === 'string',\n remedy:\n \"Records written before agent-eval 0.126 predate this field and carry `costUsd: 0` as the documented uncaptured sentinel, which is NOT an observed zero. Backfill it as costProvenance: { kind: 'uncaptured', usd: null } WITH costUsd: null — an uncaptured cost whose costUsd is non-null is rejected by validateRunRecord, so provenance alone leaves the record invalid.\",\n },\n {\n field: 'tokenUsage',\n present: (bag) => isObject(bag.tokenUsage),\n remedy:\n \"The line's cost.tokens_in and cost.tokens_out are read from it. Backfill it from the provider's usage report; mint will not write 0 for tokens nobody counted.\",\n },\n {\n field: 'tokenUsage.input',\n present: (bag) => !isObject(bag.tokenUsage) || typeof bag.tokenUsage.input === 'number',\n remedy: \"The line's cost.tokens_in is read from it, and a missing count is not a zero count.\",\n },\n {\n field: 'tokenUsage.output',\n present: (bag) => !isObject(bag.tokenUsage) || typeof bag.tokenUsage.output === 'number',\n remedy: \"The line's cost.tokens_out is read from it, and a missing count is not a zero count.\",\n },\n {\n field: 'outcome',\n present: (bag) => isObject(bag.outcome),\n remedy:\n \"The line's reward, reward_source and metrics are all read from it. A record with no outcome carries no training label at all, and mint refuses an unlabeled row.\",\n },\n {\n field: 'outcome.raw',\n // Reported only when `outcome` itself is present: one absent field should\n // produce one reason per CAUSE, not one per path that dereferences it.\n present: (bag) => !isObject(bag.outcome) || isObject(bag.outcome.raw),\n remedy:\n 'It is the metric bag copied verbatim into the line\\'s outcome.metrics. `{ ...undefined }` spreads to `{}` without complaint, so an absent bag would mint as \"this run reported no metrics\" — a different claim from \"this record predates the field\". Backfill it as {} only when that is what you mean.',\n },\n {\n field: 'terminalOutcome',\n present: (bag) => typeof bag.terminalOutcome === 'string',\n remedy:\n \"It became required in agent-eval 0.126. Backfill it from root-run or process evidence, or as 'unknown' when the producer has none — mint will not decide the line's is_completed and is_truncated for you.\",\n },\n {\n field: 'scenarioId',\n present: (bag) => typeof bag.scenarioId === 'string' && bag.scenarioId.length > 0,\n remedy:\n \"It became required in agent-eval 0.126 and becomes the line's task.instance_id, which must be a non-empty string. Backfill it from the scenario the run was dealt (pre-0.126 producers often left it in outcome.raw.scenario_id).\",\n },\n]\n\n/**\n * Why a record cannot be minted, one entry per missing field, empty when it can.\n *\n * Exported so a caller can partition a whole ledger — \"which of my 2742 records\n * predate 0.126\" — without catching an exception per record, and without\n * re-deriving the field list on their side. A re-derived list is a list that\n * drifts from the door it is supposed to predict.\n *\n * Takes a `RunRecord` because that is what the caller holds and what the\n * compiler agrees they hold. The type is precisely the thing that is wrong, so\n * the checks read the record as the untyped bag it actually is on disk.\n */\nexport function unmintableReasons(record: RunRecord): string[] {\n const bag = record as unknown as Record<string, unknown>\n return MINT_FIELD_CHECKS.filter((check) => !check.present(bag)).map(\n (check) => `${check.field} is missing. ${check.remedy}`,\n )\n}\n\n/**\n * The mint door THROWS on a record it cannot build a line from. It does NOT\n * normalise an absent `costProvenance` to `{kind:'uncaptured', usd:null}`, and\n * the choice is not stylistic:\n *\n * - Normalising cannot cover the record, only part of it. `terminalOutcome`\n * feeds `is_completed` and `is_truncated`, which the rollout schema requires\n * to be BOOLEAN — there is no null to fall back to, so every possible\n * default is a claim about how the run ended. A door that quietly fixes the\n * cost and invents the ending is a door no caller can predict.\n * - Normalising the cost requires knowing what `costUsd: 0` meant, and mint\n * cannot know. A genuinely free run and an uncaptured one are the same bytes\n * in a pre-0.126 record; only the producer can tell them apart. Guessing is\n * exactly the failure this guard exists to stop — the 0.125 optional chain\n * `record.costProvenance?.kind === 'uncaptured'` already made that guess,\n * silently, and every record it touched minted `cost.usd: 0`: an unmeasured\n * cost published as a measured zero, into a training dataset.\n * - `requireTaskScore`, directly above, already refuses an unlabeled record\n * for the same reason: \"nobody graded this\" is not \"graded zero\". \"Nobody\n * billed this\" is not \"billed zero\".\n *\n * The caller who wants historical records minted backfills them at their store,\n * in one pass, where `costUsd` can be corrected alongside `costProvenance` —\n * which is the only place that decision can be made correctly. The refusal names\n * the run, names every missing field, and spells the value to write.\n */\nfunction requireMintableRecord(record: RunRecord): void {\n const reasons = unmintableReasons(record)\n if (reasons.length === 0) return\n throw new ValidationError(`Cannot mint rollout for run ${record.runId}: ${reasons.join('\\n ')}`)\n}\n\n/** The search lineage a record's line is built from; undefined for a record outside a search. */\nasync function resolveSearchLineage(\n record: RunRecord,\n options: MintRolloutOptions,\n): Promise<RolloutSearchLineage | undefined> {\n if (record.search === undefined) return undefined\n const refuse: (detail: string) => never = (detail) => {\n throw new ValidationError(`Cannot mint rollout for search run ${record.runId}: ${detail}`)\n }\n if (!options.searchLineage) {\n refuse('pass searchLineage so generation, candidate_index, rep and parent come from its ledger')\n }\n const lineage = await options.searchLineage(record.search)\n const isCount = (value: unknown): boolean => Number.isSafeInteger(value) && (value as number) >= 0\n if (!isCount(lineage.depth)) refuse('lineage depth must be a non-negative integer')\n if (!isCount(lineage.ordinal)) refuse('lineage ordinal must be a non-negative integer')\n if (!isCount(lineage.rep)) refuse('lineage rep must be a non-negative integer')\n if (\n lineage.containingRunId !== null &&\n (typeof lineage.containingRunId !== 'string' || lineage.containingRunId.length === 0)\n ) {\n refuse('lineage containingRunId must be null or a non-empty run id')\n }\n if (lineage.containingRunId === record.runId) refuse('a run cannot contain itself')\n return lineage\n}\n\nconst SPLIT_FROM_TAG: Record<RunRecord['splitTag'], RolloutSplit> = {\n search: 'search',\n dev: 'dev',\n holdout: 'holdout',\n}\n\nfunction mintLine(\n record: RunRecord,\n lineage: RolloutSearchLineage | undefined,\n steps: RolloutStep[],\n messages: ChatMessage[],\n options: MintRolloutOptions,\n capturedAt: string,\n gap?: string,\n attempts?: readonly RolloutEvidenceAttempt[],\n lossyProjection = false,\n): MintedRolloutLine {\n // Field presence first, and BEFORE `requireTaskScore`: that guard reads\n // `record.outcome.searchScore` on its way to the answer, so an absent\n // `outcome` would throw a bare TypeError from inside the guard whose whole\n // job is to produce a clean refusal.\n //\n // Both branches of `mintRolloutRows` — the traced line and the gap line —\n // land here, which is the point: `mintLine` is the only constructor of a\n // `MintedRolloutLine` from a RunRecord, so there is no path into the waist\n // that skips the check and no way to get this wrong from the outside.\n requireMintableRecord(record)\n // A missing task score is refused before anything is built: an\n // execution-only record has no training label, and a missing label is\n // neither a zero reward nor a mintable row.\n requireTaskScore(record)\n // `reward` and `realness_gated` come out of one call, so neither door into\n // the waist can write one and forget the other.\n const rewardFields = rolloutRewardFields(record)\n // Only an observed or estimated amount is a total; a lower bound is not.\n const knownTotal =\n record.costProvenance.kind === 'observed' || record.costProvenance.kind === 'estimated'\n const terminalOutcome = record.terminalOutcome\n const isCompleted = terminalOutcome === 'succeeded' || terminalOutcome === 'failed'\n const isTruncated = terminalOutcome === 'cancelled' || terminalOutcome === 'incomplete'\n const terminalError =\n terminalOutcome === 'failed' ||\n terminalOutcome === 'cancelled' ||\n terminalOutcome === 'incomplete'\n ? (record.terminalFailureReason ?? `run ended ${terminalOutcome}`)\n : null\n // `assertMinted` rather than a cast: mint is the producer the whole gate\n // rests on, so it proves the line it just built is valid instead of asserting\n // it by fiat. The brand is unforgeable precisely because nobody casts to it.\n return assertMinted(\n {\n schema: ROLLOUT_SCHEMA,\n rollout_id: record.runId,\n parent_rollout_id: lineage?.containingRunId ?? null,\n run_id: record.runId,\n experiment_id: record.experimentId,\n candidate_id: record.candidateId,\n generation: lineage?.depth ?? null,\n candidate_index: lineage?.ordinal ?? null,\n role: options.role ?? 'agent',\n task: {\n suite: options.suite ?? record.experimentId,\n instance_id: record.scenarioId,\n split: SPLIT_FROM_TAG[record.splitTag],\n seed: record.seed,\n rep: lineage?.rep ?? 0,\n },\n policy: {\n harness: null,\n harness_version: null,\n model: record.model,\n provider: null,\n profile_commit: record.commitSha,\n prompt_hash: record.promptHash,\n config_hash: record.configHash,\n agent_profile_cell_id: record.agentProfile?.cellId ?? null,\n sampling: null,\n },\n messages,\n tool_defs: [],\n ...(steps.length > 0 ? { steps } : {}),\n outcome: {\n ...rewardFields,\n reward_source: REWARD_SOURCE[scoreOrigin(record)],\n verdict: null,\n // A verbatim bulk copy, deliberately UNFILTERED here. `outcome.raw`\n // holds the per-layer verifier scores (`layer.*`) that the reward was\n // derived from, so on a gated run this dict is the reward signal in\n // component form — but filtering it at this call site is the pattern\n // that has now leaked twice, because the next producer to write a\n // reward-bearing field forgets. The gate is applied to the whole\n // outcome once, in `assertMinted` below (`gateGamedOutcome`), which\n // moves the block to `provenance.gated_evidence` when the run is gated\n // and leaves it here untouched when it is not.\n metrics: { ...record.outcome.raw },\n is_completed: isCompleted,\n is_truncated: isTruncated,\n error: terminalError,\n },\n cost: {\n usd: knownTotal ? record.costUsd : null,\n tokens_in: record.tokenUsage.input,\n tokens_out: record.tokenUsage.output,\n tokens_reasoning: record.tokenUsage.reasoning ?? null,\n cache_read: record.tokenUsage.cached ?? null,\n cache_write: record.tokenUsage.cacheWrite ?? null,\n wall_s: Math.round(record.wallMs / 1000),\n },\n artifacts: {\n patch_path: null,\n run_dir: null,\n transcript_ref: record.traceRef ? `trace:${record.traceRef.traceId}` : null,\n },\n provenance: {\n captured_at: capturedAt,\n capture: 'mint',\n ...(record.search !== undefined ? { search: { ...record.search } } : {}),\n ...(attempts !== undefined ? { attempts: [...attempts] } : {}),\n ...(lossyProjection ? { lossy_projection: true } : {}),\n ...(gap !== undefined ? { gap } : {}),\n },\n },\n `minted rollout line for run ${record.runId}`,\n )\n}\n\n/**\n * Join RunRecords with their traces into canonical rollout lines. Records\n * without spans or an explicit capture are emitted as labeled gap lines and reported in\n * `missingTraces`. Execution-only records without a task score are rejected\n * because a missing training label is not a zero reward.\n */\nexport async function mintRolloutRows(\n records: RunRecord[],\n store: TraceStore,\n options: MintRolloutOptions = {},\n): Promise<MintRolloutResult> {\n const scrub = options.scrub ?? ((t) => t)\n const capturedAt = (options.now?.() ?? new Date()).toISOString()\n if (\n options.maxSteps !== undefined &&\n (!Number.isSafeInteger(options.maxSteps) || options.maxSteps < 1)\n ) {\n throw new ValidationError('maxSteps must be a positive integer')\n }\n const rows: MintedRolloutLine[] = []\n const missingTraces: string[] = []\n for (const record of records) {\n const trajectory = await buildTrajectory(store, record.runId)\n const captured = options.messagesOf ? await options.messagesOf(record.runId) : undefined\n const evidence = options.evidenceOf ? await options.evidenceOf(record.runId) : undefined\n if (evidence !== undefined && evidence?.runId !== record.runId) {\n throw new ValidationError(\n `Cannot mint rollout for run ${record.runId}: capture evidence belongs to another run`,\n )\n }\n if (\n options.evidenceOf &&\n (!evidence || !Array.isArray(evidence.attempts) || evidence.attempts.length === 0)\n ) {\n throw new ValidationError(\n `Cannot mint rollout for run ${record.runId}: provider attempt evidence is missing`,\n )\n }\n if (\n evidence?.attempts.some(\n (attempt) =>\n !attempt ||\n !Array.isArray(attempt.nativeSessionIds) ||\n !Array.isArray(attempt.processIds) ||\n !Array.isArray(attempt.missingReasons),\n )\n ) {\n throw new ValidationError(\n `Cannot mint rollout for run ${record.runId}: malformed provider attempt evidence`,\n )\n }\n const attempts = evidence?.attempts.map((attempt) => ({\n ...attempt,\n nativeSessionIds: [...attempt.nativeSessionIds],\n processIds: [...attempt.processIds],\n missingReasons: attempt.missingReasons.map(scrub),\n }))\n if (options.messagesOf && (!Array.isArray(captured) || captured.length === 0)) {\n throw new ValidationError(\n `Cannot mint rollout for run ${record.runId}: full capture is missing`,\n )\n }\n const lineage = await resolveSearchLineage(record, options)\n if (trajectory.steps.length === 0 && !options.messagesOf) {\n missingTraces.push(record.runId)\n rows.push(\n mintLine(\n record,\n lineage,\n [],\n [],\n options,\n capturedAt,\n 'no trace spans recorded for this runId',\n attempts,\n ),\n )\n continue\n }\n let steps = trajectory.steps.map((s) => projectStep(s.span, scrub))\n const omittedSteps =\n options.maxSteps !== undefined && steps.length > options.maxSteps\n ? steps.length - options.maxSteps\n : 0\n if (options.maxSteps !== undefined && omittedSteps > 0) {\n // Keep the head and tail — the middle of a long run is the least\n // informative for outcome attribution.\n const head = Math.ceil(options.maxSteps / 2)\n const tail = options.maxSteps - head\n steps = [...steps.slice(0, head), ...steps.slice(steps.length - tail)]\n }\n const spans = trajectory.steps.map((s) => s.span)\n const messages = captured ?? finalConversation(spans)\n requireToolLinkage(messages, record.runId)\n const conversation = messages.map((message) => projectMessage(message, scrub))\n // SFT drops copied context. That projection must not orphan a retained result.\n requireToolLinkage(\n conversation.filter((message) => message.is_copied_context !== true),\n record.runId,\n )\n const gaps: string[] = []\n if (conversation.length === 0) gaps.push('trace has no llm spans; no conversation to inline')\n else if (!options.messagesOf) {\n gaps.push('messages project only the last LLM context; full transcript was not captured')\n }\n if (omittedSteps > 0) gaps.push(`${omittedSteps} middle trace steps omitted by maxSteps`)\n for (const attempt of attempts ?? []) {\n if (attempt.missingReasons.length > 0) {\n gaps.push(`provider attempt ${attempt.ordinal}: ${attempt.missingReasons.join(', ')}`)\n }\n }\n rows.push(\n mintLine(\n record,\n lineage,\n steps,\n conversation,\n options,\n capturedAt,\n gaps.length > 0 ? gaps.join('; ') : undefined,\n attempts,\n (conversation.length > 0 && !options.messagesOf) ||\n omittedSteps > 0 ||\n (attempts?.some((attempt) => attempt.missingReasons.length > 0) ?? false),\n ),\n )\n }\n return { rows, missingTraces }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8GA,MAAM,UAAU,GAAY,UAAmC;CAE7D,OAAO,OADG,OAAO,MAAM,WAAW,IAAI,KAAK,UAAU,CAAC,MACpC,EAAE;AACtB;AAEA,SAAS,YAAY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C3C,MAAM,OAAO,QAAQ,WAAW;GAChC,QAAQ,CAAC,GAAG,MAAM,MAAM,GAAG,IAAI,GAAG,GAAG,MAAM,MAAM,MAAM,SAAS,IAAI,CAAC;EACvE;EACA,MAAM,QAAQ,WAAW,MAAM,KAAK,MAAM,EAAE,IAAI;EAChD,MAAM,WAAW,YAAY,kBAAkB,KAAK;EACpD,mBAAmB,UAAU,OAAO,KAAK;EACzC,MAAM,eAAe,SAAS,KAAK,YAAY,eAAe,SAAS,KAAK,CAAC;EAE7E,mBACE,aAAa,QAAQ,YAAY,QAAQ,sBAAsB,IAAI,GACnE,OAAO,KACT;EACA,MAAM,OAAiB,CAAC;EACxB,IAAI,aAAa,WAAW,GAAG,KAAK,KAAK,mDAAmD;OACvF,IAAI,CAAC,QAAQ,YAChB,KAAK,KAAK,8EAA8E;EAE1F,IAAI,eAAe,GAAG,KAAK,KAAK,GAAG,aAAa,wCAAwC;EACxF,KAAK,MAAM,WAAW,YAAY,CAAC,GACjC,IAAI,QAAQ,eAAe,SAAS,GAClC,KAAK,KAAK,oBAAoB,QAAQ,QAAQ,IAAI,QAAQ,eAAe,KAAK,IAAI,GAAG;EAGzF,KAAK,KACH,SACE,QACA,SACA,OACA,cACA,SACA,YACA,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,IAAI,KAAA,GACpC,UACC,aAAa,SAAS,KAAK,CAAC,QAAQ,cACnC,eAAe,MACd,UAAU,MAAM,YAAY,QAAQ,eAAe,SAAS,CAAC,KAAK,MACvE,CACF;CACF;CACA,OAAO;EAAE;EAAM;CAAc;AAC/B"}
|
|
1
|
+
{"version":3,"file":"mint-CWG-s2mI.js","names":[],"sources":["../src/rollout/mint.ts"],"sourcesContent":["/**\n * Rollout minting — `tangle.rollout.v1` lines joined from the records the\n * substrate ALREADY keeps. There is no separate rollout store: a rollout\n * is the JOIN of a RunRecord (identity, provenance, cost, outcome) with\n * its trace (spans share `runId`), projected into the canonical line.\n *\n * Composition, not duplication:\n * - identity/provenance → `RunRecord` (candidateId, splitTag, agentProfile, hashes)\n * - step structure → `buildTrajectory` over the shared TraceStore\n * - preference-pair export → `feedbackTrajectoryToOptimizerRow` (feedback-trajectory.ts)\n * - PRM / reward-model → `reward-model-export.ts`\n * - search lineage → `searchLineage`, read from the run's search ledger\n *\n * Anti-Goodhart invariant: a run whose `outcome.realness.gated` is true is\n * never exported with a positive reward OR with any of the numbers that reward\n * was computed from. The gate travels into the training data (`reward` forced\n * to 0, `realness_gated: true`) and the whole outcome is transformed by\n * `gateGamedOutcome` inside `assertMinted` below, which relocates `metrics` and\n * `verdict` to `provenance.gated_evidence`. Mint returns\n * `MintedRolloutLine[]`: the brand the training exporters require, which only\n * this function, `readRolloutLedger`, and an explicit `assertMinted` can mint.\n *\n * A record carrying NEITHER split score is REJECTED (`ValidationError`), never\n * minted at 0 — \"nobody graded this\" is not the same claim as \"graded a total\n * failure\", and a trainer reading 0 learns the second. Lines that already\n * carry `reward: null` (interchange imports, existing ledgers) remain valid on\n * the wire; only the RunRecord→line door refuses.\n *\n * Records without spans or an explicit full capture become labeled GAP LINES (messages: [],\n * provenance.gap) — present in the output AND surfaced in\n * `missingTraces`; a capture gap is a finding, never a silent omission.\n */\n\nimport { ValidationError } from '../errors'\nimport { type RunRecord, type RunSearchCoordinates, runTaskScore } from '../run-record'\nimport type { LlmSpan, Span, ToolSpan } from '../trace/schema'\nimport type { TraceStore } from '../trace/store'\nimport { buildTrajectory } from '../trajectory'\nimport { rolloutRewardFields, scoreOrigin } from './reward'\nimport {\n assertMinted,\n type ChatMessage,\n type MintedRolloutLine,\n ROLLOUT_SCHEMA,\n type RolloutEvidenceAttempt,\n type RolloutRole,\n type RolloutSplit,\n type RolloutStep,\n} from './schema'\n\n/** Redactor for transcript/step payload text (secrets, PII), not opaque identity. */\nexport type RolloutScrubber = (text: string) => string\n\n/** A search cell's place in its search tree, read from the search ledger. */\nexport interface RolloutSearchLineage {\n /** Edges between the cell's node and the search root; the root is 0. */\n depth: number\n /** Order in which the node registered in its search; the root is 0. */\n ordinal: number\n /** Repeat index of the cell on its task, from 0. */\n rep: number\n /** Run id of the cell whose execution contains this search; null for a\n * top-level search. */\n containingRunId: string | null\n}\n\nexport interface MintRolloutOptions {\n scrub?: RolloutScrubber\n /**\n * Full canonical capture, including turns no longer in the model's context.\n * When supplied, missing/empty capture is refused, never replaced with a\n * span summary. Use the execution owner's capture or the existing harness\n * readers; reviewer traces and compacted histories are not full capture.\n */\n messagesOf?: (\n runId: string,\n ) => readonly ChatMessage[] | undefined | Promise<readonly ChatMessage[] | undefined>\n /** Provider attempts from a retained receipt bound to the exact run. */\n evidenceOf?: (\n runId: string,\n ) =>\n | { runId: string; attempts: readonly RolloutEvidenceAttempt[] }\n | undefined\n | Promise<{ runId: string; attempts: readonly RolloutEvidenceAttempt[] } | undefined>\n /** Cap steps per line (longest runs first drop middle steps). Default: no cap. */\n maxSteps?: number\n /** Role recorded on every minted line. Default 'agent' (a solo eval run). */\n role?: RolloutRole\n /** Task suite label. Default: the record's `experimentId`. */\n suite?: string\n /** Injected clock for deterministic output. */\n now?: () => Date\n /**\n * Lineage of a search run, read from its search ledger. It fills the line's\n * `generation` (node depth), `candidate_index` (node order), `task.rep` and\n * `parent_rollout_id` (the containing cell's run). Mint refuses a record\n * that carries `search` when this is absent, because a null `generation`\n * states that the run is not part of a search.\n */\n searchLineage?: (\n search: RunSearchCoordinates,\n ) => RolloutSearchLineage | Promise<RolloutSearchLineage>\n}\n\nexport interface MintRolloutResult {\n rows: MintedRolloutLine[]\n /** runIds that had a RunRecord but no spans — emitted as gap lines AND listed here. */\n missingTraces: string[]\n}\n\nconst asText = (v: unknown, scrub: RolloutScrubber): string => {\n const s = typeof v === 'string' ? v : JSON.stringify(v)\n return scrub(s ?? '')\n}\n\nfunction projectStep(span: Span, scrub: RolloutScrubber): RolloutStep {\n const base: RolloutStep = {\n kind: span.kind,\n name: scrub(span.name),\n status: span.status,\n durationMs: span.endedAt !== undefined ? span.endedAt - span.startedAt : undefined,\n }\n if (span.kind === 'llm') {\n const llm = span as LlmSpan\n const last = llm.messages[llm.messages.length - 1]\n if (last && last.content !== null) base.input = scrub(last.content)\n if (llm.output !== undefined) base.output = scrub(llm.output)\n } else if (span.kind === 'tool') {\n const tool = span as ToolSpan\n base.input = asText(tool.args, scrub)\n if (tool.result !== undefined) base.output = asText(tool.result, scrub)\n }\n return base\n}\n\n/** Preserve captured fields; invocation ids are opaque linkage, not generated text. */\nfunction projectMessage(message: ChatMessage, scrub: RolloutScrubber): ChatMessage {\n return {\n role: message.role,\n content: message.content === null ? null : scrub(message.content),\n ...(message.reasoning_content !== undefined\n ? { reasoning_content: scrub(message.reasoning_content) }\n : {}),\n ...(message.tool_calls !== undefined\n ? {\n tool_calls: message.tool_calls.map((call) => ({\n id: call.id,\n type: call.type,\n function: {\n name: call.function.name,\n arguments: scrub(call.function.arguments),\n },\n })),\n }\n : {}),\n ...(message.tool_call_id !== undefined ? { tool_call_id: message.tool_call_id } : {}),\n ...(message.name !== undefined ? { name: message.name } : {}),\n ...(message.is_copied_context !== undefined\n ? { is_copied_context: message.is_copied_context }\n : {}),\n }\n}\n\n/** Never recover missing calls from tool names, span order or argument summaries. */\nfunction requireToolLinkage(messages: readonly ChatMessage[], runId: string): void {\n const seen = new Set<string>()\n const pending = new Map<string, string>()\n const refuse: (detail: string) => never = (detail) => {\n throw new ValidationError(`Cannot mint rollout for run ${runId}: ${detail}`)\n }\n for (const message of messages) {\n if (message.tool_calls !== undefined) {\n if (message.role !== 'assistant' || !Array.isArray(message.tool_calls)) {\n refuse('tool calls must be captured on an assistant message')\n }\n if (pending.size > 0) refuse('new tool calls precede the prior invocation results')\n for (const call of message.tool_calls) {\n if (\n !call ||\n typeof call.id !== 'string' ||\n call.id.length === 0 ||\n seen.has(call.id) ||\n call.type !== 'function' ||\n !call.function ||\n typeof call.function.name !== 'string' ||\n call.function.name.length === 0 ||\n typeof call.function.arguments !== 'string'\n ) {\n refuse('missing, duplicate or malformed tool invocation')\n }\n seen.add(call.id)\n pending.set(call.id, call.function.name)\n }\n }\n if (message.role === 'tool') {\n const id = message.tool_call_id\n if (typeof id !== 'string' || !pending.has(id)) {\n refuse('tool result has no captured invocation (or answers it more than once)')\n }\n if (message.name !== undefined && message.name !== pending.get(id)) {\n refuse('tool result name does not match its invocation')\n }\n pending.delete(id)\n } else if (message.tool_call_id !== undefined) {\n refuse('tool_call_id is only valid on a tool result')\n } else if (pending.size > 0 && message.tool_calls === undefined) {\n refuse('conversation advances before all tool results were captured')\n }\n }\n if (pending.size > 0) refuse('tool invocation has no captured result')\n}\n\n/** Legacy span history; callers with compacted contexts supply messagesOf instead. */\nfunction finalConversation(spans: Span[]): ChatMessage[] {\n const llms = spans.filter((s): s is LlmSpan => s.kind === 'llm')\n const last = llms[llms.length - 1]\n if (!last) return []\n const messages: ChatMessage[] = [...last.messages]\n if (last.output !== undefined && last.output !== '') {\n messages.push({ role: 'assistant', content: last.output })\n }\n return messages\n}\n\n// The reward derivations live in the leaf module `./reward` so gate and\n// reporting code can import them without dragging in the trace store; they are\n// re-exported here because the derivations shipped from this path.\nexport {\n isRealnessGated,\n observedScore,\n observedSplitScore,\n type ScoreOrigin,\n type ScorePreference,\n scoreOrigin,\n trainingReward,\n trainingScore,\n} from './reward'\n\nconst REWARD_SOURCE: Record<ReturnType<typeof scoreOrigin>, string> = {\n holdout: 'run-record/holdout-score',\n search: 'run-record/search-score',\n unscored: 'run-record/unscored',\n}\n\n/**\n * The mint door refuses an execution-only record: a missing training label is\n * not a zero reward, and not a mintable line either. Lines that already carry\n * `reward: null` — interchange imports, existing ledgers — stay valid on the\n * wire and keep their labeled gap; this guard is only about the\n * RunRecord→line door, where the producer can still be told to go score the\n * run instead of shipping an unlabeled row.\n */\nfunction requireTaskScore(record: RunRecord): void {\n if (runTaskScore(record) === undefined) {\n throw new ValidationError(`Cannot mint rollout for run ${record.runId}: task score is missing`)\n }\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null\n\ninterface MintFieldCheck {\n /** The RunRecord path, spelled the way the caller has to fix it. */\n readonly field: string\n /** True when the record carries something the line can honestly be built from. */\n readonly present: (bag: Record<string, unknown>) => boolean\n /** What the caller writes onto the record, and why that value and not another. */\n readonly remedy: string\n}\n\n/**\n * The RunRecord fields mint reads that a record can be missing even though the\n * TYPE says it cannot. There are exactly two ways that happens:\n *\n * 1. The field was OPTIONAL when the record was serialized. `costProvenance`,\n * `terminalOutcome` and `scenarioId` were optional through agent-eval\n * 0.125 and became required in 0.126, with no on-disk migration — so every\n * ledger written before 0.126 is full of records the type calls complete.\n * 2. Mint reads a level DEEPER than the record's own type is checked at:\n * `outcome.raw`, `tokenUsage.input`, `tokenUsage.output`.\n *\n * Nothing else needs a check here. Every other field mint copies is a top-level\n * scalar landing in a typed slot on the line, where an absent value arrives as\n * `undefined` and `assertMinted` refuses it by name. These are the ones where an\n * absent value instead kills the join with `TypeError: Cannot read properties of\n * undefined`, or — worse — mints a line that reads as measured.\n *\n * This is deliberately NOT `validateRunRecord`. That validator answers \"is this\n * a valid RunRecord\", which is a wider question than \"can a rollout line be\n * built from this one\": it also enforces model-snapshot discipline, the\n * `terminalFailureReason` coupling, and the `costUsd === costProvenance.usd`\n * agreement. Routing the mint door through it would refuse records mint can\n * mint honestly today (a model alias with no snapshot date, for one), which is\n * a policy change with its own blast radius and not this bug. The door asks the\n * narrower question and answers it precisely.\n */\nconst MINT_FIELD_CHECKS: readonly MintFieldCheck[] = [\n {\n field: 'costProvenance',\n present: (bag) => isObject(bag.costProvenance) && typeof bag.costProvenance.kind === 'string',\n remedy:\n \"Records written before agent-eval 0.126 predate this field and carry `costUsd: 0` as the documented uncaptured sentinel, which is NOT an observed zero. Backfill it as costProvenance: { kind: 'uncaptured', usd: null } WITH costUsd: null — an uncaptured cost whose costUsd is non-null is rejected by validateRunRecord, so provenance alone leaves the record invalid.\",\n },\n {\n field: 'tokenUsage',\n present: (bag) => isObject(bag.tokenUsage),\n remedy:\n \"The line's cost.tokens_in and cost.tokens_out are read from it. Backfill it from the provider's usage report; mint will not write 0 for tokens nobody counted.\",\n },\n {\n field: 'tokenUsage.input',\n present: (bag) => !isObject(bag.tokenUsage) || typeof bag.tokenUsage.input === 'number',\n remedy: \"The line's cost.tokens_in is read from it, and a missing count is not a zero count.\",\n },\n {\n field: 'tokenUsage.output',\n present: (bag) => !isObject(bag.tokenUsage) || typeof bag.tokenUsage.output === 'number',\n remedy: \"The line's cost.tokens_out is read from it, and a missing count is not a zero count.\",\n },\n {\n field: 'outcome',\n present: (bag) => isObject(bag.outcome),\n remedy:\n \"The line's reward, reward_source and metrics are all read from it. A record with no outcome carries no training label at all, and mint refuses an unlabeled row.\",\n },\n {\n field: 'outcome.raw',\n // Reported only when `outcome` itself is present: one absent field should\n // produce one reason per CAUSE, not one per path that dereferences it.\n present: (bag) => !isObject(bag.outcome) || isObject(bag.outcome.raw),\n remedy:\n 'It is the metric bag copied verbatim into the line\\'s outcome.metrics. `{ ...undefined }` spreads to `{}` without complaint, so an absent bag would mint as \"this run reported no metrics\" — a different claim from \"this record predates the field\". Backfill it as {} only when that is what you mean.',\n },\n {\n field: 'terminalOutcome',\n present: (bag) => typeof bag.terminalOutcome === 'string',\n remedy:\n \"It became required in agent-eval 0.126. Backfill it from root-run or process evidence, or as 'unknown' when the producer has none — mint will not decide the line's is_completed and is_truncated for you.\",\n },\n {\n field: 'scenarioId',\n present: (bag) => typeof bag.scenarioId === 'string' && bag.scenarioId.length > 0,\n remedy:\n \"It became required in agent-eval 0.126 and becomes the line's task.instance_id, which must be a non-empty string. Backfill it from the scenario the run was dealt (pre-0.126 producers often left it in outcome.raw.scenario_id).\",\n },\n]\n\n/**\n * Why a record cannot be minted, one entry per missing field, empty when it can.\n *\n * Exported so a caller can partition a whole ledger — \"which of my 2742 records\n * predate 0.126\" — without catching an exception per record, and without\n * re-deriving the field list on their side. A re-derived list is a list that\n * drifts from the door it is supposed to predict.\n *\n * Takes a `RunRecord` because that is what the caller holds and what the\n * compiler agrees they hold. The type is precisely the thing that is wrong, so\n * the checks read the record as the untyped bag it actually is on disk.\n */\nexport function unmintableReasons(record: RunRecord): string[] {\n const bag = record as unknown as Record<string, unknown>\n return MINT_FIELD_CHECKS.filter((check) => !check.present(bag)).map(\n (check) => `${check.field} is missing. ${check.remedy}`,\n )\n}\n\n/**\n * The mint door THROWS on a record it cannot build a line from. It does NOT\n * normalise an absent `costProvenance` to `{kind:'uncaptured', usd:null}`, and\n * the choice is not stylistic:\n *\n * - Normalising cannot cover the record, only part of it. `terminalOutcome`\n * feeds `is_completed` and `is_truncated`, which the rollout schema requires\n * to be BOOLEAN — there is no null to fall back to, so every possible\n * default is a claim about how the run ended. A door that quietly fixes the\n * cost and invents the ending is a door no caller can predict.\n * - Normalising the cost requires knowing what `costUsd: 0` meant, and mint\n * cannot know. A genuinely free run and an uncaptured one are the same bytes\n * in a pre-0.126 record; only the producer can tell them apart. Guessing is\n * exactly the failure this guard exists to stop — the 0.125 optional chain\n * `record.costProvenance?.kind === 'uncaptured'` already made that guess,\n * silently, and every record it touched minted `cost.usd: 0`: an unmeasured\n * cost published as a measured zero, into a training dataset.\n * - `requireTaskScore`, directly above, already refuses an unlabeled record\n * for the same reason: \"nobody graded this\" is not \"graded zero\". \"Nobody\n * billed this\" is not \"billed zero\".\n *\n * The caller who wants historical records minted backfills them at their store,\n * in one pass, where `costUsd` can be corrected alongside `costProvenance` —\n * which is the only place that decision can be made correctly. The refusal names\n * the run, names every missing field, and spells the value to write.\n */\nfunction requireMintableRecord(record: RunRecord): void {\n const reasons = unmintableReasons(record)\n if (reasons.length === 0) return\n throw new ValidationError(`Cannot mint rollout for run ${record.runId}: ${reasons.join('\\n ')}`)\n}\n\n/** The search lineage a record's line is built from; undefined for a record outside a search. */\nasync function resolveSearchLineage(\n record: RunRecord,\n options: MintRolloutOptions,\n): Promise<RolloutSearchLineage | undefined> {\n if (record.search === undefined) return undefined\n const refuse: (detail: string) => never = (detail) => {\n throw new ValidationError(`Cannot mint rollout for search run ${record.runId}: ${detail}`)\n }\n if (!options.searchLineage) {\n refuse('pass searchLineage so generation, candidate_index, rep and parent come from its ledger')\n }\n const lineage = await options.searchLineage(record.search)\n const isCount = (value: unknown): boolean => Number.isSafeInteger(value) && (value as number) >= 0\n if (!isCount(lineage.depth)) refuse('lineage depth must be a non-negative integer')\n if (!isCount(lineage.ordinal)) refuse('lineage ordinal must be a non-negative integer')\n if (!isCount(lineage.rep)) refuse('lineage rep must be a non-negative integer')\n if (\n lineage.containingRunId !== null &&\n (typeof lineage.containingRunId !== 'string' || lineage.containingRunId.length === 0)\n ) {\n refuse('lineage containingRunId must be null or a non-empty run id')\n }\n if (lineage.containingRunId === record.runId) refuse('a run cannot contain itself')\n return lineage\n}\n\nconst SPLIT_FROM_TAG: Record<RunRecord['splitTag'], RolloutSplit> = {\n search: 'search',\n dev: 'dev',\n holdout: 'holdout',\n}\n\nfunction mintLine(\n record: RunRecord,\n lineage: RolloutSearchLineage | undefined,\n steps: RolloutStep[],\n messages: ChatMessage[],\n options: MintRolloutOptions,\n capturedAt: string,\n gap?: string,\n attempts?: readonly RolloutEvidenceAttempt[],\n lossyProjection = false,\n): MintedRolloutLine {\n // Field presence first, and BEFORE `requireTaskScore`: that guard reads\n // `record.outcome.searchScore` on its way to the answer, so an absent\n // `outcome` would throw a bare TypeError from inside the guard whose whole\n // job is to produce a clean refusal.\n //\n // Both branches of `mintRolloutRows` — the traced line and the gap line —\n // land here, which is the point: `mintLine` is the only constructor of a\n // `MintedRolloutLine` from a RunRecord, so there is no path into the waist\n // that skips the check and no way to get this wrong from the outside.\n requireMintableRecord(record)\n // A missing task score is refused before anything is built: an\n // execution-only record has no training label, and a missing label is\n // neither a zero reward nor a mintable row.\n requireTaskScore(record)\n // `reward` and `realness_gated` come out of one call, so neither door into\n // the waist can write one and forget the other.\n const rewardFields = rolloutRewardFields(record)\n // Only an observed or estimated amount is a total; a lower bound is not.\n const knownTotal =\n record.costProvenance.kind === 'observed' || record.costProvenance.kind === 'estimated'\n const terminalOutcome = record.terminalOutcome\n const isCompleted = terminalOutcome === 'succeeded' || terminalOutcome === 'failed'\n const isTruncated = terminalOutcome === 'cancelled' || terminalOutcome === 'incomplete'\n const terminalError =\n terminalOutcome === 'failed' ||\n terminalOutcome === 'cancelled' ||\n terminalOutcome === 'incomplete'\n ? (record.terminalFailureReason ?? `run ended ${terminalOutcome}`)\n : null\n // `assertMinted` rather than a cast: mint is the producer the whole gate\n // rests on, so it proves the line it just built is valid instead of asserting\n // it by fiat. The brand is unforgeable precisely because nobody casts to it.\n return assertMinted(\n {\n schema: ROLLOUT_SCHEMA,\n rollout_id: record.runId,\n parent_rollout_id: lineage?.containingRunId ?? null,\n run_id: record.runId,\n experiment_id: record.experimentId,\n candidate_id: record.candidateId,\n generation: lineage?.depth ?? null,\n candidate_index: lineage?.ordinal ?? null,\n role: options.role ?? 'agent',\n task: {\n suite: options.suite ?? record.experimentId,\n instance_id: record.scenarioId,\n split: SPLIT_FROM_TAG[record.splitTag],\n seed: record.seed,\n rep: lineage?.rep ?? 0,\n },\n policy: {\n harness: null,\n harness_version: null,\n model: record.model,\n provider: null,\n profile_commit: record.commitSha,\n prompt_hash: record.promptHash,\n config_hash: record.configHash,\n agent_profile_cell_id: record.agentProfile?.cellId ?? null,\n sampling: null,\n },\n messages,\n tool_defs: [],\n ...(steps.length > 0 ? { steps } : {}),\n outcome: {\n ...rewardFields,\n reward_source: REWARD_SOURCE[scoreOrigin(record)],\n verdict: null,\n // A verbatim bulk copy, deliberately UNFILTERED here. `outcome.raw`\n // holds the per-layer verifier scores (`layer.*`) that the reward was\n // derived from, so on a gated run this dict is the reward signal in\n // component form — but filtering it at this call site is the pattern\n // that has now leaked twice, because the next producer to write a\n // reward-bearing field forgets. The gate is applied to the whole\n // outcome once, in `assertMinted` below (`gateGamedOutcome`), which\n // moves the block to `provenance.gated_evidence` when the run is gated\n // and leaves it here untouched when it is not.\n metrics: { ...record.outcome.raw },\n is_completed: isCompleted,\n is_truncated: isTruncated,\n error: terminalError,\n },\n cost: {\n usd: knownTotal ? record.costUsd : null,\n tokens_in: record.tokenUsage.input,\n tokens_out: record.tokenUsage.output,\n tokens_reasoning: record.tokenUsage.reasoning ?? null,\n cache_read: record.tokenUsage.cached ?? null,\n cache_write: record.tokenUsage.cacheWrite ?? null,\n wall_s: Math.round(record.wallMs / 1000),\n },\n artifacts: {\n patch_path: null,\n run_dir: null,\n transcript_ref: record.traceRef ? `trace:${record.traceRef.traceId}` : null,\n },\n provenance: {\n captured_at: capturedAt,\n capture: 'mint',\n ...(record.search !== undefined ? { search: { ...record.search } } : {}),\n ...(attempts !== undefined ? { attempts: [...attempts] } : {}),\n ...(lossyProjection ? { lossy_projection: true } : {}),\n ...(gap !== undefined ? { gap } : {}),\n },\n },\n `minted rollout line for run ${record.runId}`,\n )\n}\n\n/**\n * Join RunRecords with their traces into canonical rollout lines. Records\n * without spans or an explicit capture are emitted as labeled gap lines and reported in\n * `missingTraces`. Execution-only records without a task score are rejected\n * because a missing training label is not a zero reward.\n */\nexport async function mintRolloutRows(\n records: RunRecord[],\n store: TraceStore,\n options: MintRolloutOptions = {},\n): Promise<MintRolloutResult> {\n const scrub = options.scrub ?? ((t) => t)\n const capturedAt = (options.now?.() ?? new Date()).toISOString()\n if (\n options.maxSteps !== undefined &&\n (!Number.isSafeInteger(options.maxSteps) || options.maxSteps < 1)\n ) {\n throw new ValidationError('maxSteps must be a positive integer')\n }\n const rows: MintedRolloutLine[] = []\n const missingTraces: string[] = []\n for (const record of records) {\n const trajectory = await buildTrajectory(store, record.runId)\n const captured = options.messagesOf ? await options.messagesOf(record.runId) : undefined\n const evidence = options.evidenceOf ? await options.evidenceOf(record.runId) : undefined\n if (evidence !== undefined && evidence?.runId !== record.runId) {\n throw new ValidationError(\n `Cannot mint rollout for run ${record.runId}: capture evidence belongs to another run`,\n )\n }\n if (\n options.evidenceOf &&\n (!evidence || !Array.isArray(evidence.attempts) || evidence.attempts.length === 0)\n ) {\n throw new ValidationError(\n `Cannot mint rollout for run ${record.runId}: provider attempt evidence is missing`,\n )\n }\n if (\n evidence?.attempts.some(\n (attempt) =>\n !attempt ||\n !Array.isArray(attempt.nativeSessionIds) ||\n !Array.isArray(attempt.processIds) ||\n !Array.isArray(attempt.missingReasons),\n )\n ) {\n throw new ValidationError(\n `Cannot mint rollout for run ${record.runId}: malformed provider attempt evidence`,\n )\n }\n const attempts = evidence?.attempts.map((attempt) => ({\n ...attempt,\n nativeSessionIds: [...attempt.nativeSessionIds],\n processIds: [...attempt.processIds],\n missingReasons: attempt.missingReasons.map(scrub),\n }))\n if (options.messagesOf && (!Array.isArray(captured) || captured.length === 0)) {\n throw new ValidationError(\n `Cannot mint rollout for run ${record.runId}: full capture is missing`,\n )\n }\n const lineage = await resolveSearchLineage(record, options)\n if (trajectory.steps.length === 0 && !options.messagesOf) {\n missingTraces.push(record.runId)\n rows.push(\n mintLine(\n record,\n lineage,\n [],\n [],\n options,\n capturedAt,\n 'no trace spans recorded for this runId',\n attempts,\n ),\n )\n continue\n }\n let steps = trajectory.steps.map((s) => projectStep(s.span, scrub))\n const omittedSteps =\n options.maxSteps !== undefined && steps.length > options.maxSteps\n ? steps.length - options.maxSteps\n : 0\n if (options.maxSteps !== undefined && omittedSteps > 0) {\n // Keep the head and tail — the middle of a long run is the least\n // informative for outcome attribution.\n const head = Math.ceil(options.maxSteps / 2)\n const tail = options.maxSteps - head\n steps = [...steps.slice(0, head), ...steps.slice(steps.length - tail)]\n }\n const spans = trajectory.steps.map((s) => s.span)\n const messages = captured ?? finalConversation(spans)\n requireToolLinkage(messages, record.runId)\n const conversation = messages.map((message) => projectMessage(message, scrub))\n // SFT drops copied context. That projection must not orphan a retained result.\n requireToolLinkage(\n conversation.filter((message) => message.is_copied_context !== true),\n record.runId,\n )\n const gaps: string[] = []\n if (conversation.length === 0) gaps.push('trace has no llm spans; no conversation to inline')\n else if (!options.messagesOf) {\n gaps.push('messages project only the last LLM context; full transcript was not captured')\n }\n if (omittedSteps > 0) gaps.push(`${omittedSteps} middle trace steps omitted by maxSteps`)\n for (const attempt of attempts ?? []) {\n if (attempt.missingReasons.length > 0) {\n gaps.push(`provider attempt ${attempt.ordinal}: ${attempt.missingReasons.join(', ')}`)\n }\n }\n rows.push(\n mintLine(\n record,\n lineage,\n steps,\n conversation,\n options,\n capturedAt,\n gaps.length > 0 ? gaps.join('; ') : undefined,\n attempts,\n (conversation.length > 0 && !options.messagesOf) ||\n omittedSteps > 0 ||\n (attempts?.some((attempt) => attempt.missingReasons.length > 0) ?? false),\n ),\n )\n }\n return { rows, missingTraces }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8GA,MAAM,UAAU,GAAY,UAAmC;CAE7D,OAAO,OADG,OAAO,MAAM,WAAW,IAAI,KAAK,UAAU,CAAC,MACpC,EAAE;AACtB;AAEA,SAAS,YAAY,MAAY,OAAqC;CACpE,MAAM,OAAoB;EACxB,MAAM,KAAK;EACX,MAAM,MAAM,KAAK,IAAI;EACrB,QAAQ,KAAK;EACb,YAAY,KAAK,YAAY,KAAA,IAAY,KAAK,UAAU,KAAK,YAAY,KAAA;CAC3E;CACA,IAAI,KAAK,SAAS,OAAO;EACvB,MAAM,MAAM;EACZ,MAAM,OAAO,IAAI,SAAS,IAAI,SAAS,SAAS;EAChD,IAAI,QAAQ,KAAK,YAAY,MAAM,KAAK,QAAQ,MAAM,KAAK,OAAO;EAClE,IAAI,IAAI,WAAW,KAAA,GAAW,KAAK,SAAS,MAAM,IAAI,MAAM;CAC9D,OAAO,IAAI,KAAK,SAAS,QAAQ;EAC/B,MAAM,OAAO;EACb,KAAK,QAAQ,OAAO,KAAK,MAAM,KAAK;EACpC,IAAI,KAAK,WAAW,KAAA,GAAW,KAAK,SAAS,OAAO,KAAK,QAAQ,KAAK;CACxE;CACA,OAAO;AACT;;AAGA,SAAS,eAAe,SAAsB,OAAqC;CACjF,OAAO;EACL,MAAM,QAAQ;EACd,SAAS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AQ,QAAQ,IAAI,QAAQ,eAAe,KAAK,IAAI,GAAG;EAGzF,KAAK,KACH,SACE,QACA,SACA,OACA,cACA,SACA,YACA,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,IAAI,KAAA,GACpC,UACC,aAAa,SAAS,KAAK,CAAC,QAAQ,cACnC,eAAe,MACd,UAAU,MAAM,YAAY,QAAQ,eAAe,SAAS,CAAC,KAAK,MACvE,CACF;CACF;CACA,OAAO;EAAE;EAAM;CAAc;AAC/B"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { E as MultishotResult, M as MultishotTransportRequest, T as MultishotPersona, c as RunMultishotMatrixResult, f as RunMultishotOptions, k as MultishotToolDefinition, s as RunMultishotMatrixOptions } from "../../matrix-
|
|
1
|
+
import { E as MultishotResult, M as MultishotTransportRequest, T as MultishotPersona, c as RunMultishotMatrixResult, f as RunMultishotOptions, k as MultishotToolDefinition, s as RunMultishotMatrixOptions } from "../../matrix-BucOjLF1.js";
|
|
2
2
|
//#region src/multishot/golden/compare.d.ts
|
|
3
3
|
interface CompareOptions {
|
|
4
4
|
/** Stop after this many mismatches. A structural divergence high in the
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { w as JudgeScore } from "../types-
|
|
2
|
-
import { A as MultishotToolExecutor, C as MultishotFatalToolError, D as MultishotShape, E as MultishotResult, F as assertMultishotShotResult, M as MultishotTransportRequest, N as MultishotTransportResponse, O as MultishotShotResultError, P as MultishotTransportToolCall, S as MultishotDriverEmptyError, T as MultishotPersona, _ as JudgeRunResult, a as MultishotCellOutput, b as runJudge, c as RunMultishotMatrixResult, d as MultishotShot, f as RunMultishotOptions, g as JudgeDimension, h as JudgeConfig, i as ConversationJudgeInput, j as MultishotTransport, k as MultishotToolDefinition, l as computeCellComposite, m as DEFAULT_JUDGE_MODEL, n as CellCompositeInput, o as MultishotJudges, p as runMultishot, r as CellCompositeScore, s as RunMultishotMatrixOptions, t as ArtifactJudgeInput, u as runMultishotMatrix, v as renderDimensions, w as MultishotMessage, x as MultishotArtifact, y as renderJsonFooter } from "../matrix-
|
|
1
|
+
import { w as JudgeScore } from "../types-khIUQ0O5.js";
|
|
2
|
+
import { A as MultishotToolExecutor, C as MultishotFatalToolError, D as MultishotShape, E as MultishotResult, F as assertMultishotShotResult, M as MultishotTransportRequest, N as MultishotTransportResponse, O as MultishotShotResultError, P as MultishotTransportToolCall, S as MultishotDriverEmptyError, T as MultishotPersona, _ as JudgeRunResult, a as MultishotCellOutput, b as runJudge, c as RunMultishotMatrixResult, d as MultishotShot, f as RunMultishotOptions, g as JudgeDimension, h as JudgeConfig, i as ConversationJudgeInput, j as MultishotTransport, k as MultishotToolDefinition, l as computeCellComposite, m as DEFAULT_JUDGE_MODEL, n as CellCompositeInput, o as MultishotJudges, p as runMultishot, r as CellCompositeScore, s as RunMultishotMatrixOptions, t as ArtifactJudgeInput, u as runMultishotMatrix, v as renderDimensions, w as MultishotMessage, x as MultishotArtifact, y as renderJsonFooter } from "../matrix-BucOjLF1.js";
|
|
3
3
|
import { AgentProfile } from "@tangle-network/agent-interface";
|
|
4
4
|
//#region src/multishot/cost.d.ts
|
|
5
5
|
/**
|
package/dist/openapi.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"openapi": "3.1.0",
|
|
3
3
|
"info": {
|
|
4
4
|
"title": "@tangle-network/agent-eval — wire protocol",
|
|
5
|
-
"version": "0.
|
|
5
|
+
"version": "0.203.0",
|
|
6
6
|
"description": "HTTP and stdio RPC interface to agent-eval. The TypeScript runtime is the source of truth; this spec is the contract that cross-language clients (Python, Rust, Go) generate from.\n\nWire-protocol version: 1.1.0. Bumps on breaking changes to request/response schemas.",
|
|
7
7
|
"contact": {
|
|
8
8
|
"name": "Tangle Network",
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { a as hashCanonical } from "./canonical-BsZVgBhW.js";
|
|
1
2
|
import { o as summarizeNumberSeries } from "./descriptive-D9LUFk1-.js";
|
|
2
3
|
import { a as parseJson, c as workerSourceKey, d as SUPERVISOR_RUN_SCHEMA, f as isUnavailable, i as asRecord, l as NO_SOURCE_LIMITS, m as unavailable, o as parseJsonl, p as showMeasured, r as readTerminalRecord, s as parseSupervisorTree, u as SUPERVISOR_RUN_ROLLUP_SCHEMA } from "./terminal-record-BHocwFw1.js";
|
|
3
4
|
import { basename, join, resolve } from "node:path";
|
|
@@ -322,7 +323,18 @@ function analyzeSupervisorRunSources(src, now = Date.now) {
|
|
|
322
323
|
unknownNodes: closeUsdUnreported && rootId !== null ? [rootId] : []
|
|
323
324
|
}
|
|
324
325
|
};
|
|
326
|
+
const noteCaptureGaps = (owner, captures) => {
|
|
327
|
+
if (captures === null || captures?.length === 0) gaps.push(`${owner} workspaceCapture: no retained output capture evidence`);
|
|
328
|
+
else if (captures !== void 0) for (const [index, capture] of captures.entries()) {
|
|
329
|
+
const source = `${owner} workspaceCapture[${index + 1}]`;
|
|
330
|
+
if (capture.projectionGap !== null) gaps.push(`${source}: ${capture.projectionGap}`);
|
|
331
|
+
if (capture.coverageComplete === false) gaps.push(`${source}: ${capture.incompleteReason ?? "provider reported incomplete coverage"}`);
|
|
332
|
+
if (capture.coverageComplete === null && capture.projectionGap === null) gaps.push(`${source}: capture coverage was not recorded`);
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
noteCaptureGaps(`root ${rootId ?? src.runRef}`, src.rootWorkspaceCaptures);
|
|
325
336
|
const perWorker = (src.workers ?? []).map((w) => {
|
|
337
|
+
noteCaptureGaps(`worker ${w.workerId ?? w.label}`, w.workspaceCaptures);
|
|
326
338
|
const f = tree.workerLogs.get(workerSourceKey(w));
|
|
327
339
|
const matchingSpawns = spawnsForSource(w);
|
|
328
340
|
const spawn = spawnForSource(w);
|
|
@@ -347,7 +359,8 @@ function analyzeSupervisorRunSources(src, now = Date.now) {
|
|
|
347
359
|
usd: usdLimit !== null ? null : w.workerId === void 0 ? workerUsdByLabel.get(w.label) ?? null : workerUsdById.get(w.workerId) ?? null,
|
|
348
360
|
patchBytes: w.patchBytes ?? f?.finishedPatchBytes ?? null,
|
|
349
361
|
passed,
|
|
350
|
-
score: close?.score ?? f?.score ?? null
|
|
362
|
+
score: close?.score ?? f?.score ?? null,
|
|
363
|
+
workspaceCaptures: w.workspaceCaptures ?? null
|
|
351
364
|
};
|
|
352
365
|
});
|
|
353
366
|
const wallDistribution = summarizeNumberSeries(perWorker.map((w) => w.wallMs).filter((w) => w !== null));
|
|
@@ -408,6 +421,7 @@ function analyzeSupervisorRunSources(src, now = Date.now) {
|
|
|
408
421
|
decision,
|
|
409
422
|
economics,
|
|
410
423
|
outcome,
|
|
424
|
+
rootWorkspaceCaptures: src.rootWorkspaceCaptures ?? null,
|
|
411
425
|
gaps,
|
|
412
426
|
traceCommand: src.traceCommand ?? "npx --yes @tangle-network/traces@latest analyze --harness opencode --cwd <worker-clone-cwd>"
|
|
413
427
|
};
|
|
@@ -750,7 +764,7 @@ function renderSupervisorRollupMarkdown(rollup, title = "Round rollup") {
|
|
|
750
764
|
*
|
|
751
765
|
* Transcripts come from Runtime's own records too: `root-stream.jsonl` is the root's, each
|
|
752
766
|
* worker's turn outputs and native-session receipt are read from the journal, and every blob
|
|
753
|
-
* a record names is checked on disk (see `
|
|
767
|
+
* a record names is checked on disk (see `nodeTranscripts`).
|
|
754
768
|
*
|
|
755
769
|
* The run's terminal record is Runtime's own: `result.json` is the
|
|
756
770
|
* `SupervisedResult` that `supervise()` returned, verbatim, and its `kind`
|
|
@@ -1043,13 +1057,87 @@ function runtimeBeginState(root, startedAt) {
|
|
|
1043
1057
|
function blobFile(runDir, ref) {
|
|
1044
1058
|
return typeof ref === "string" && /^sha256:[0-9a-f]{64}$/u.test(ref) ? join(runDir, BLOB_DIR, `${ref.replace(":", "-")}.json`) : null;
|
|
1045
1059
|
}
|
|
1060
|
+
async function workspaceCapturesFromOutput(runDir, ref) {
|
|
1061
|
+
const outRef = typeof ref === "string" ? ref : null;
|
|
1062
|
+
const blobPath = blobFile(runDir, ref);
|
|
1063
|
+
const missing = (projectionGap) => ({
|
|
1064
|
+
outRef,
|
|
1065
|
+
blobPath,
|
|
1066
|
+
receiptPointer: null,
|
|
1067
|
+
receipt: null,
|
|
1068
|
+
attempts: null,
|
|
1069
|
+
coverageComplete: null,
|
|
1070
|
+
incompleteReason: null,
|
|
1071
|
+
projectionGap
|
|
1072
|
+
});
|
|
1073
|
+
if (blobPath === null) return [missing("Runtime output has no valid content address")];
|
|
1074
|
+
if (!await isFile(blobPath)) return [missing("Runtime output blob is missing or not a file")];
|
|
1075
|
+
const raw = await readMaybe(blobPath);
|
|
1076
|
+
if (raw === null) return [missing("Runtime output blob is missing")];
|
|
1077
|
+
let output;
|
|
1078
|
+
try {
|
|
1079
|
+
output = JSON.parse(raw);
|
|
1080
|
+
} catch {
|
|
1081
|
+
return [missing("Runtime output blob is not JSON")];
|
|
1082
|
+
}
|
|
1083
|
+
let addressGap = null;
|
|
1084
|
+
try {
|
|
1085
|
+
if (hashCanonical(output) !== outRef) addressGap = "Runtime output content address does not match output blob";
|
|
1086
|
+
} catch {
|
|
1087
|
+
addressGap = "Runtime output cannot be canonically hashed";
|
|
1088
|
+
}
|
|
1089
|
+
const project = (rawReceipt, receiptPointer) => {
|
|
1090
|
+
const receipt = record(rawReceipt);
|
|
1091
|
+
if (receipt === null) return {
|
|
1092
|
+
...missing(`workspaceCapture receipt is absent or malformed${addressGap === null ? "" : `; ${addressGap}`}`),
|
|
1093
|
+
receiptPointer,
|
|
1094
|
+
receipt: rawReceipt
|
|
1095
|
+
};
|
|
1096
|
+
const provenance = record(receipt.provenance);
|
|
1097
|
+
const attempts = Array.isArray(provenance?.attempts) ? provenance.attempts : null;
|
|
1098
|
+
const coverageComplete = typeof receipt.coverageComplete === "boolean" ? receipt.coverageComplete : null;
|
|
1099
|
+
const incompleteReason = typeof receipt.incompleteReason === "string" ? receipt.incompleteReason : null;
|
|
1100
|
+
const gaps = [];
|
|
1101
|
+
if (addressGap !== null) gaps.push(addressGap);
|
|
1102
|
+
if (coverageComplete === null) gaps.push("workspaceCapture.coverageComplete is absent");
|
|
1103
|
+
if (record(receipt.snapshot) === null) gaps.push("workspaceCapture.snapshot is absent");
|
|
1104
|
+
if (provenance === null) gaps.push("workspaceCapture.provenance is absent");
|
|
1105
|
+
if (attempts === null) gaps.push("workspaceCapture.provenance.attempts is absent");
|
|
1106
|
+
else if (attempts.length === 0 || attempts.some((attempt) => record(attempt) === null)) gaps.push("workspaceCapture.provenance.attempts is empty or malformed");
|
|
1107
|
+
return {
|
|
1108
|
+
outRef,
|
|
1109
|
+
blobPath,
|
|
1110
|
+
receiptPointer,
|
|
1111
|
+
receipt,
|
|
1112
|
+
attempts,
|
|
1113
|
+
coverageComplete,
|
|
1114
|
+
incompleteReason,
|
|
1115
|
+
projectionGap: gaps.length > 0 ? gaps.join("; ") : null
|
|
1116
|
+
};
|
|
1117
|
+
};
|
|
1118
|
+
const result = record(output);
|
|
1119
|
+
const captures = [];
|
|
1120
|
+
for (const key of Object.keys(result ?? {})) if (key === "workspaceCapture") captures.push(project(result?.[key], "/workspaceCapture"));
|
|
1121
|
+
else if (key === "workspaceCaptures") {
|
|
1122
|
+
const receipts = result?.[key];
|
|
1123
|
+
if (Array.isArray(receipts) && receipts.length > 0) for (const [index, receipt] of receipts.entries()) captures.push(project(receipt, `/workspaceCaptures/${index}`));
|
|
1124
|
+
else captures.push({
|
|
1125
|
+
...missing(`workspaceCaptures is empty or malformed${addressGap === null ? "" : `; ${addressGap}`}`),
|
|
1126
|
+
receiptPointer: "/workspaceCaptures",
|
|
1127
|
+
receipt: receipts ?? null
|
|
1128
|
+
});
|
|
1129
|
+
}
|
|
1130
|
+
return captures.length > 0 ? captures : [project(null, null)];
|
|
1131
|
+
}
|
|
1046
1132
|
/**
|
|
1047
|
-
* What Runtime retained of each
|
|
1133
|
+
* What Runtime retained of each node's decisions, from its own records.
|
|
1048
1134
|
*
|
|
1049
1135
|
* - A turn is one `execution-admitted` event in the `dispatched` phase. Its `execution-result`
|
|
1050
1136
|
* names an output blob holding that turn's provider event stream (reasoning, tool calls and
|
|
1051
1137
|
* results as the harness reported them). A dispatched turn with no retained output lost its
|
|
1052
1138
|
* record, which is how a worker that went down mid-turn shows up.
|
|
1139
|
+
* - Every event's `outRef` enters the same collector, once per node and address. Terminal
|
|
1140
|
+
* records retain ordinary and steerable results; they are not counted as dispatched turns.
|
|
1053
1141
|
* - The terminal event's `harnessTranscript` receipt covers the harness's native session files.
|
|
1054
1142
|
* Those are the only record of the harness's own subagents, so an unavailable receipt is a
|
|
1055
1143
|
* separate gap from a missing turn, and its reason is Runtime's, verbatim.
|
|
@@ -1057,14 +1145,15 @@ function blobFile(runDir, ref) {
|
|
|
1057
1145
|
* Blob files are checked on disk: a receipt that names a blob the directory no longer holds is
|
|
1058
1146
|
* not a retained transcript.
|
|
1059
1147
|
*/
|
|
1060
|
-
async function
|
|
1148
|
+
async function nodeTranscripts(runDir, events, nodeIds) {
|
|
1061
1149
|
const facts = /* @__PURE__ */ new Map();
|
|
1062
1150
|
const entry = (id) => {
|
|
1063
1151
|
let found = facts.get(id);
|
|
1064
1152
|
if (found === void 0) {
|
|
1065
1153
|
found = {
|
|
1066
1154
|
dispatched: 0,
|
|
1067
|
-
|
|
1155
|
+
outputRefs: [],
|
|
1156
|
+
outputPositions: /* @__PURE__ */ new Map(),
|
|
1068
1157
|
receipt: null
|
|
1069
1158
|
};
|
|
1070
1159
|
facts.set(id, found);
|
|
@@ -1073,12 +1162,23 @@ async function workerTranscripts(runDir, events, workerIds) {
|
|
|
1073
1162
|
};
|
|
1074
1163
|
for (const event of events) {
|
|
1075
1164
|
const id = nonEmptyString(event.id);
|
|
1076
|
-
if (id === null || !
|
|
1165
|
+
if (id === null || !nodeIds.has(id)) continue;
|
|
1166
|
+
if (Object.hasOwn(event, "outRef")) {
|
|
1167
|
+
const fact = entry(id);
|
|
1168
|
+
const ref = event.outRef;
|
|
1169
|
+
const position = typeof ref === "string" ? fact.outputPositions.get(ref) : void 0;
|
|
1170
|
+
if (position !== void 0) {
|
|
1171
|
+
if (event.kind === "execution-result") fact.outputRefs[position].turn = true;
|
|
1172
|
+
} else {
|
|
1173
|
+
if (typeof ref === "string") fact.outputPositions.set(ref, fact.outputRefs.length);
|
|
1174
|
+
fact.outputRefs.push({
|
|
1175
|
+
value: ref,
|
|
1176
|
+
turn: event.kind === "execution-result"
|
|
1177
|
+
});
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1077
1180
|
if (event.kind === "execution-admitted" && record(event.admission)?.phase === "dispatched") entry(id).dispatched += 1;
|
|
1078
|
-
else if (event.kind === "
|
|
1079
|
-
const file = blobFile(runDir, event.outRef);
|
|
1080
|
-
if (file !== null) entry(id).outputFiles.push(file);
|
|
1081
|
-
} else if (event.kind === "settled" || event.kind === "cancelled") {
|
|
1181
|
+
else if (event.kind === "settled" || event.kind === "cancelled") {
|
|
1082
1182
|
const receipt = record(event.harnessTranscript);
|
|
1083
1183
|
if (receipt !== null) entry(id).receipt = receipt;
|
|
1084
1184
|
}
|
|
@@ -1086,7 +1186,16 @@ async function workerTranscripts(runDir, events, workerIds) {
|
|
|
1086
1186
|
const out = /* @__PURE__ */ new Map();
|
|
1087
1187
|
for (const [id, fact] of facts) {
|
|
1088
1188
|
const retained = [];
|
|
1089
|
-
|
|
1189
|
+
let retainedTurns = 0;
|
|
1190
|
+
const workspaceCaptures = [];
|
|
1191
|
+
for (const { value: ref, turn } of fact.outputRefs) {
|
|
1192
|
+
const file = blobFile(runDir, ref);
|
|
1193
|
+
if (file !== null && await isFile(file)) {
|
|
1194
|
+
retained.push(file);
|
|
1195
|
+
if (turn) retainedTurns += 1;
|
|
1196
|
+
}
|
|
1197
|
+
workspaceCaptures.push(...await workspaceCapturesFromOutput(runDir, ref));
|
|
1198
|
+
}
|
|
1090
1199
|
let nativeSession = null;
|
|
1091
1200
|
if (fact.receipt !== null) {
|
|
1092
1201
|
if (fact.receipt.status === "available") {
|
|
@@ -1107,9 +1216,10 @@ async function workerTranscripts(runDir, events, workerIds) {
|
|
|
1107
1216
|
transcriptRef: nativeSession?.status === "available" ? nativeSession.ref : retained.at(-1) ?? null,
|
|
1108
1217
|
turns: {
|
|
1109
1218
|
dispatched: fact.dispatched,
|
|
1110
|
-
retained:
|
|
1219
|
+
retained: retainedTurns
|
|
1111
1220
|
},
|
|
1112
|
-
nativeSession
|
|
1221
|
+
nativeSession,
|
|
1222
|
+
workspaceCaptures: workspaceCaptures.length > 0 ? workspaceCaptures : null
|
|
1113
1223
|
});
|
|
1114
1224
|
}
|
|
1115
1225
|
return out;
|
|
@@ -1153,6 +1263,7 @@ function absentRuntimeSupervisorRun(runDir, resultText, failureText, instanceId)
|
|
|
1153
1263
|
harnessMissingReason: "Runtime FileRunContext has no external worker-token join",
|
|
1154
1264
|
limits: NO_SOURCE_LIMITS,
|
|
1155
1265
|
rootTranscriptRef: null,
|
|
1266
|
+
rootWorkspaceCaptures: null,
|
|
1156
1267
|
traceCommand: "unavailable — Runtime FileRunContext records no provider-session trace identity"
|
|
1157
1268
|
};
|
|
1158
1269
|
}
|
|
@@ -1188,7 +1299,7 @@ async function readRuntimeSupervisorRun(runDir, opts = {}) {
|
|
|
1188
1299
|
assertResultMatchesJournal(normalized.root, result, resultPath);
|
|
1189
1300
|
const childSpawns = normalized.events.filter((event) => event.kind === "spawned" && nonEmptyString(event.id) !== null).filter((event) => event.id !== normalized.root);
|
|
1190
1301
|
const workerIds = new Set(childSpawns.map((event) => nonEmptyString(event.id)).filter((id) => id !== null));
|
|
1191
|
-
const transcripts = await
|
|
1302
|
+
const transcripts = await nodeTranscripts(runDir, normalized.events, /* @__PURE__ */ new Set([normalized.root, ...workerIds]));
|
|
1192
1303
|
const workers = childSpawns.map((event) => {
|
|
1193
1304
|
const workerId = nonEmptyString(event.id);
|
|
1194
1305
|
const transcript = transcripts.get(workerId);
|
|
@@ -1204,6 +1315,7 @@ async function readRuntimeSupervisorRun(runDir, opts = {}) {
|
|
|
1204
1315
|
retained: 0
|
|
1205
1316
|
},
|
|
1206
1317
|
nativeSession: transcript?.nativeSession ?? null,
|
|
1318
|
+
workspaceCaptures: transcript?.workspaceCaptures ?? null,
|
|
1207
1319
|
patchPath: null
|
|
1208
1320
|
};
|
|
1209
1321
|
});
|
|
@@ -1230,6 +1342,7 @@ async function readRuntimeSupervisorRun(runDir, opts = {}) {
|
|
|
1230
1342
|
harnessMissingReason: "Runtime FileRunContext has no external worker-token join",
|
|
1231
1343
|
limits: sourceLimits(normalized.root, normalized.events, workerIds),
|
|
1232
1344
|
rootTranscriptRef: await isFile(rootStream) ? rootStream : null,
|
|
1345
|
+
rootWorkspaceCaptures: transcripts.get(normalized.root)?.workspaceCaptures ?? null,
|
|
1233
1346
|
traceCommand: "unavailable — Runtime FileRunContext records no provider-session trace identity"
|
|
1234
1347
|
};
|
|
1235
1348
|
}
|
|
@@ -1484,4 +1597,4 @@ async function runSupervisorRunCommand(argv, io = PROCESS_IO) {
|
|
|
1484
1597
|
//#endregion
|
|
1485
1598
|
export { writeSupervisorRunReport as a, readRuntimeSupervisorRun as c, renderSupervisorRunHeadline as d, renderSupervisorRunMarkdown as f, rollupSupervisorRuns as h, reportSupervisorRound as i, runtimeSupervisorRunReader as l, parsePatch as m, analyzeSupervisorRun as n, writeSupervisorRunReportSafe as o, analyzeSupervisorRunSources as p, findSupervisorRunDirs as r, isRuntimeSupervisorRunDir as s, runSupervisorRunCommand as t, renderSupervisorRollupMarkdown as u };
|
|
1486
1599
|
|
|
1487
|
-
//# sourceMappingURL=report-command-
|
|
1600
|
+
//# sourceMappingURL=report-command-D0XL2Cvi.js.map
|