@tangle-network/agent-eval 0.133.1 → 0.133.3
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 +165 -0
- package/dist/{analyze-runs-DZr7JW-m.d.ts → analyze-runs-BClW9OSe.d.ts} +3 -3
- package/dist/{analyze-runs-DZr7JW-m.d.ts.map → analyze-runs-BClW9OSe.d.ts.map} +1 -1
- package/dist/{analyze-runs-B-afTpCv.js → analyze-runs-qk8op0tN.js} +63 -42
- package/dist/analyze-runs-qk8op0tN.js.map +1 -0
- package/dist/baseline-BaPxoROc.js +149 -0
- package/dist/baseline-BaPxoROc.js.map +1 -0
- package/dist/{baseline-hG3K85h4.d.ts → baseline-D_fT6277.d.ts} +43 -11
- package/dist/baseline-D_fT6277.d.ts.map +1 -0
- package/dist/benchmarks/index.d.ts +1 -1
- package/dist/benchmarks/index.js +1 -1
- package/dist/{benchmarks-BU7P6PCW.js → benchmarks-BP9sgMia.js} +3 -3
- package/dist/{benchmarks-BU7P6PCW.js.map → benchmarks-BP9sgMia.js.map} +1 -1
- package/dist/builder-eval/index.js +1 -1
- package/dist/campaign/index.d.ts +2 -2
- package/dist/campaign/index.js +2 -2
- package/dist/{campaign-CnzHQndg.js → campaign--V4ffEKR.js} +12 -6
- package/dist/{campaign-CnzHQndg.js.map → campaign--V4ffEKR.js.map} +1 -1
- package/dist/{client-D4F9hdzR.d.ts → client-Du7B81wW.d.ts} +28 -14
- package/dist/client-Du7B81wW.d.ts.map +1 -0
- package/dist/{client-CYzbdJOZ.js → client-LIuo-KPv.js} +19 -7
- package/dist/client-LIuo-KPv.js.map +1 -0
- package/dist/contract/index.d.ts +3 -3
- package/dist/contract/index.d.ts.map +1 -1
- package/dist/contract/index.js +9 -8
- package/dist/contract/index.js.map +1 -1
- package/dist/{eval-campaign-DXhpZghy.js → eval-campaign-CvPcvqXC.js} +2 -2
- package/dist/{eval-campaign-DXhpZghy.js.map → eval-campaign-CvPcvqXC.js.map} +1 -1
- package/dist/hosted/index.d.ts +1 -1
- package/dist/hosted/index.d.ts.map +1 -1
- package/dist/hosted/index.js +1 -1
- package/dist/index-3cdlURSk.d.ts.map +1 -1
- package/dist/{index-Wek5mU0y.d.ts → index-B5MNN1f1.d.ts} +3 -3
- package/dist/{index-Wek5mU0y.d.ts.map → index-B5MNN1f1.d.ts.map} +1 -1
- package/dist/{index-Ba636PKl.d.ts → index-DOqvIJ8I.d.ts} +27 -10
- package/dist/index-DOqvIJ8I.d.ts.map +1 -0
- package/dist/{index-DSC51roc.d.ts → index-DSC51roc2.d.ts} +1 -1
- package/dist/index-DSC51roc2.d.ts.map +1 -0
- package/dist/{index-nhIYz9hn.d.ts → index-DuhJaaiH.d.ts} +68 -7
- package/dist/index-DuhJaaiH.d.ts.map +1 -0
- package/dist/index.d.ts +56 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +39 -22
- package/dist/index.js.map +1 -1
- package/dist/ledger-core/index.d.ts +2 -2
- package/dist/ledger-core/index.js +2 -2
- package/dist/{ledger-core-CPZfcrC2.js → ledger-core-DAKFKRzi.js} +136 -18
- package/dist/ledger-core-DAKFKRzi.js.map +1 -0
- package/dist/matrix/index.d.ts +1 -1
- package/dist/meta-eval/index.d.ts +1 -1
- package/dist/meta-eval/index.js +2 -2
- package/dist/multishot/index.d.ts +1 -1
- package/dist/openapi.json +1 -1
- package/dist/{opencode-sqlite-BGrHeDu3.js → opencode-sqlite-8r6WUfHc.js} +2 -3
- package/dist/opencode-sqlite-8r6WUfHc.js.map +1 -0
- package/dist/{paired-arms-6XItKzd1.js → paired-arms-CA_8pN01.js} +2 -2
- package/dist/{paired-arms-6XItKzd1.js.map → paired-arms-CA_8pN01.js.map} +1 -1
- package/dist/pipelines/index.d.ts +1 -1
- package/dist/pipelines/index.js +3 -2
- package/dist/pipelines/index.js.map +1 -1
- package/dist/{release-report-wuilQkvK.js → release-report-BVZBmRZp.js} +2 -2
- package/dist/{release-report-wuilQkvK.js.map → release-report-BVZBmRZp.js.map} +1 -1
- package/dist/{release-report-DfmKSIEE.d.ts → release-report-DKBtegGt.d.ts} +2 -2
- package/dist/{release-report-DfmKSIEE.d.ts.map → release-report-DKBtegGt.d.ts.map} +1 -1
- package/dist/reporting.d.ts +3 -3
- package/dist/reporting.js +4 -4
- package/dist/{researcher-DMimgHtN.d.ts → researcher-BtD5U1Up.d.ts} +2 -2
- package/dist/{researcher-DMimgHtN.d.ts.map → researcher-BtD5U1Up.d.ts.map} +1 -1
- package/dist/{reward-hacking-Dl2UBzej.js → reward-hacking-DCdRK9TY.js} +2 -2
- package/dist/{reward-hacking-Dl2UBzej.js.map → reward-hacking-DCdRK9TY.js.map} +1 -1
- package/dist/rl.d.ts +1 -1
- package/dist/rl.js +4 -4
- package/dist/rollout/index.js +2 -2
- package/dist/{rollout-CeTlDrf6.js → rollout-CreDz__7.js} +2 -2
- package/dist/{rollout-CeTlDrf6.js.map → rollout-CreDz__7.js.map} +1 -1
- package/dist/{rubric-predictive-validity-QG7ydk0s.js → rubric-predictive-validity-D6Q6n9oq.js} +2 -2
- package/dist/{rubric-predictive-validity-QG7ydk0s.js.map → rubric-predictive-validity-D6Q6n9oq.js.map} +1 -1
- package/dist/{skillopt-optimization-method-CAASpcS3.d.ts → skillopt-optimization-method-Dxr8pdZd.d.ts} +12 -7
- package/dist/{skillopt-optimization-method-CAASpcS3.d.ts.map → skillopt-optimization-method-Dxr8pdZd.d.ts.map} +1 -1
- package/dist/{skillopt-optimization-method-BoIzh7Dl.js → skillopt-optimization-method-vvJ4bMNI.js} +123 -24
- package/dist/skillopt-optimization-method-vvJ4bMNI.js.map +1 -0
- package/dist/{statistics-DbvkkDPa.d.ts → statistics-D_4Snl-5.d.ts} +158 -30
- package/dist/statistics-D_4Snl-5.d.ts.map +1 -0
- package/dist/{statistics-DWM_AyLe.js → statistics-RwRNu2__.js} +546 -98
- package/dist/statistics-RwRNu2__.js.map +1 -0
- package/dist/{summary-report-Ci17nIdU.js → summary-report-BxtossFi.js} +3 -3
- package/dist/{summary-report-Ci17nIdU.js.map → summary-report-BxtossFi.js.map} +1 -1
- package/dist/{summary-report-DnUcjVpV.d.ts → summary-report-DyOhItws.d.ts} +4 -3
- package/dist/summary-report-DyOhItws.d.ts.map +1 -0
- package/dist/supervisor-run/index.js +1 -1
- package/dist/{supervisor-run-_lnTLM3z.js → supervisor-run-B7lUGoyZ.js} +2 -2
- package/dist/{supervisor-run-_lnTLM3z.js.map → supervisor-run-B7lUGoyZ.js.map} +1 -1
- package/dist/{baseline-DcX5hQDv.js → tool-use-metrics-DEGMKycK.js} +2 -114
- package/dist/tool-use-metrics-DEGMKycK.js.map +1 -0
- package/docs/design/statistics-decisions.md +271 -0
- package/docs/design.md +1 -0
- package/docs/insight-report.md +1 -1
- package/docs/research-report-methodology.md +4 -1
- package/package.json +2 -1
- package/dist/analyze-runs-B-afTpCv.js.map +0 -1
- package/dist/baseline-DcX5hQDv.js.map +0 -1
- package/dist/baseline-hG3K85h4.d.ts.map +0 -1
- package/dist/client-CYzbdJOZ.js.map +0 -1
- package/dist/client-D4F9hdzR.d.ts.map +0 -1
- package/dist/index-Ba636PKl.d.ts.map +0 -1
- package/dist/index-DSC51roc.d.ts.map +0 -1
- package/dist/index-nhIYz9hn.d.ts.map +0 -1
- package/dist/ledger-core-CPZfcrC2.js.map +0 -1
- package/dist/opencode-sqlite-BGrHeDu3.js.map +0 -1
- package/dist/skillopt-optimization-method-BoIzh7Dl.js.map +0 -1
- package/dist/statistics-DWM_AyLe.js.map +0 -1
- package/dist/statistics-DbvkkDPa.d.ts.map +0 -1
- package/dist/summary-report-DnUcjVpV.d.ts.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"analyze-runs-B-afTpCv.js","names":[],"sources":["../src/contamination-guard.ts","../src/contract/analyze-runs.ts"],"sourcesContent":["/**\n * ContaminationGuard — ensures held-out scenarios don't leak into\n * training/prompt paths, and flags model memorization.\n *\n * Three probes:\n * 1. `checkCanaries(output, scenario)` — if the scenario carries a\n * canary token, it MUST NOT appear in the agent's output.\n * Canaries are strings that are statistically impossible to\n * reconstruct from the scenario description alone — so if they\n * echo back, the model memorized them.\n * 2. `canaryLeakView(store)` — cross-corpus view of every run whose\n * output contained a canary, with the offending scenario + run.\n * 3. `HoldoutAuditor` — wraps a Dataset and emits a structured error\n * on any code path that reads holdout scenarios but doesn't flag\n * `purpose: 'evaluation'`. Keeps engineers honest.\n */\n\nimport type { DatasetScenario } from './dataset'\nimport { llmSpans } from './trace/query'\nimport type { TraceStore } from './trace/store'\n\nexport interface CanaryLeak {\n scenarioId: string\n canary: string\n runId?: string\n evidence: string\n}\n\nexport function checkCanaries(output: string, scenarios: DatasetScenario[]): CanaryLeak[] {\n const leaks: CanaryLeak[] = []\n for (const s of scenarios) {\n if (!s.canary) continue\n if (output.includes(s.canary)) {\n leaks.push({ scenarioId: s.id, canary: s.canary, evidence: excerpt(output, s.canary) })\n }\n }\n return leaks\n}\n\n/**\n * Behavioral canary: tests the AGENT, not the eval grep.\n *\n * - `forbiddenPattern` PRESENT in output ⇒ AGENT EMITTED BAD CONTENT ⇒ LEAK.\n * - `forbiddenPattern` ABSENT from output ⇒ AGENT HELD THE LINE ⇒ PASS.\n *\n * Use when running known-bad-prompt scenarios against the agent under\n * test and you want to know if the agent misbehaved. The classical\n * {@link checkCanaries} / {@link import('./canary').runCanaries | runCanaries}\n * test whether the eval check fires when the bad output is forced\n * into the eval flow — different question, different answer.\n *\n * Pattern resolution order (first match wins):\n * 1. `scenario.forbiddenPattern` — if it parses as `/body/flags`,\n * treated as a regex; otherwise a literal substring.\n * 2. `scenario.canary` — literal substring fallback so the helper\n * works on existing scenario fixtures.\n *\n * Returns `null` when nothing forbidden was found OR the scenario\n * declared no pattern.\n */\nexport function checkBehavioralCanary(\n output: string,\n scenario: DatasetScenario,\n): CanaryLeak | null {\n const pattern = scenario.forbiddenPattern ?? scenario.canary\n if (!pattern) return null\n const hit = matchForbidden(output, pattern)\n if (!hit) return null\n return {\n scenarioId: scenario.id,\n canary: pattern,\n evidence: excerpt(output, hit),\n }\n}\n\n/**\n * Behavioral canary over many (scenario, output) pairs. Sibling to\n * {@link import('./canary').runCanaries | runCanaries} — same idea\n * (run-many → report) but the question being answered is \"did the\n * AGENT misbehave?\" rather than \"did the EVAL grep fire?\".\n *\n * Returns one `CanaryLeak` per pair where the agent's output\n * contained its scenario's `forbiddenPattern` (or `canary` fallback).\n */\nexport function runBehavioralCanaries(\n cases: Array<{ scenario: DatasetScenario; output: string; runId?: string }>,\n): CanaryLeak[] {\n const leaks: CanaryLeak[] = []\n for (const c of cases) {\n const leak = checkBehavioralCanary(c.output, c.scenario)\n if (leak) leaks.push({ ...leak, runId: c.runId ?? leak.runId })\n }\n return leaks\n}\n\n/**\n * Resolve a forbidden-pattern string to the matched substring inside\n * `output`. `/body/flags` notation is interpreted as a regex; anything\n * else is a literal substring.\n */\nfunction matchForbidden(output: string, pattern: string): string | null {\n const re = tryParseRegex(pattern)\n if (re) {\n const m = output.match(re)\n return m && m[0].length > 0 ? m[0] : null\n }\n return output.includes(pattern) ? pattern : null\n}\n\nfunction tryParseRegex(pattern: string): RegExp | null {\n if (pattern.length < 2 || pattern[0] !== '/') return null\n const last = pattern.lastIndexOf('/')\n if (last <= 0) return null\n const body = pattern.slice(1, last)\n const flags = pattern.slice(last + 1)\n if (!/^[gimsuy]*$/.test(flags)) return null\n try {\n return new RegExp(body, flags)\n } catch {\n return null\n }\n}\n\n/**\n * Scan the LLM-output history in a corpus; returns every case where a\n * canary from a known scenario appeared in agent output. Pass the full\n * set of scenarios whose canaries you care about (typically the whole\n * held-out slice).\n */\nexport async function canaryLeakView(\n store: TraceStore,\n scenarios: DatasetScenario[],\n): Promise<CanaryLeak[]> {\n const targets = scenarios.filter((s) => !!s.canary)\n if (targets.length === 0) return []\n const spans = await llmSpans(store)\n const leaks: CanaryLeak[] = []\n for (const span of spans) {\n const output = span.output ?? ''\n for (const s of targets) {\n if (s.canary && output.includes(s.canary)) {\n leaks.push({\n scenarioId: s.id,\n canary: s.canary,\n runId: span.runId,\n evidence: excerpt(output, s.canary),\n })\n }\n }\n }\n return leaks\n}\n\nexport class HoldoutAuditor {\n private scenarios: DatasetScenario[]\n private accessLog: Array<{ scenarioId: string; purpose: string; at: number }> = []\n\n constructor(scenarios: DatasetScenario[]) {\n this.scenarios = scenarios\n }\n\n /** Retrieve a holdout scenario for a declared purpose. Non-'evaluation' throws. */\n get(scenarioId: string, purpose: 'evaluation' | 'debugging'): DatasetScenario {\n if (purpose !== 'evaluation' && purpose !== 'debugging') {\n throw new Error(\n `HoldoutAuditor.get: purpose must be 'evaluation' or 'debugging', got ${purpose}`,\n )\n }\n const s = this.scenarios.find((x) => x.id === scenarioId)\n if (!s) throw new Error(`holdout scenario \"${scenarioId}\" not found`)\n this.accessLog.push({ scenarioId, purpose, at: Date.now() })\n return s\n }\n\n getAccessLog(): ReadonlyArray<{ scenarioId: string; purpose: string; at: number }> {\n return this.accessLog\n }\n}\n\nfunction excerpt(source: string, needle: string): string {\n const at = source.indexOf(needle)\n if (at < 0) return ''\n const start = Math.max(0, at - 30)\n const end = Math.min(source.length, at + needle.length + 30)\n return (start > 0 ? '…' : '') + source.slice(start, end) + (end < source.length ? '…' : '')\n}\n","/**\n * # `analyzeRuns()` — turn a set of agent runs into an actionable decision packet.\n *\n * Wires the substrate's statistical, calibration, clustering, Pareto, and\n * release-confidence primitives into one `InsightReport`. Two top-level\n * entry points use this function:\n *\n * - `selfImprove()` calls it on the campaign output to attach a packet\n * to every run.\n * - Consumers with observed `RunRecord[]` (production traces, gold\n * corpora, approve/reject tables) call it directly via `analyzeRuns()`\n * for analysis without a closed loop.\n *\n * Every section is opt-in based on what the input data supports — the\n * function never invents signal. If runs carry no judge scores, `judges`\n * is empty. If there's no baseline/candidate split, `lift` is undefined.\n * If no `analyst` is wired, `failureClusters` is undefined.\n *\n * The `recommendations` array is the human-readable layer; everything\n * else is the evidence backing each recommendation.\n */\n\nimport type { AnalystRegistry } from '../analyst/registry'\nimport type { AnalystFinding } from '../analyst/types'\nimport { checkCanaries } from '../contamination-guard'\nimport type { DatasetScenario } from '../dataset'\nimport { continuousAgreement } from '../judge-calibration'\nimport { normalCdf } from '../math/normal'\nimport { pairRunRecords } from '../paired-arms'\nimport { observedSplitScore } from '../rollout/reward'\nimport {\n type RunRecord,\n type RunTerminalOutcome,\n type RunTokenUsage,\n validateRunRecord,\n} from '../run-record'\nimport {\n pairedBootstrap,\n pairedCohensDz,\n pairedMde,\n pairedTTest,\n pearsonR,\n requiredPairedSampleSize,\n spearmanR,\n} from '../statistics'\nimport { type ParetoFigureSpec, paretoChart } from '../summary-report'\nimport type { FailureClass } from '../trace/schema'\n\nimport type {\n CostProvenanceSummary,\n ExecutionInsight,\n FailureClassTally,\n FailureClusterInsight,\n InsightReport,\n InterRaterInsight,\n JudgeInsight,\n LiftInsight,\n MetricDelta,\n OutcomeCorrelationInsight,\n PriorPeriodComparison,\n Recommendation,\n ScalarDistribution,\n TokenUsageInsight,\n} from './insight-report'\n\n// ── Public API ───────────────────────────────────────────────────────\n\nexport interface AnalyzeRunsOptions {\n /** The runs to analyze. */\n runs: RunRecord[]\n /** Which split to score against when reading composite from RunOutcome.\n * Default: holdout when ANY run has a `holdoutScore`, else search. */\n split?: 'search' | 'holdout' | 'auto'\n /** Pairwise analysis configuration. When both `baselineCandidateId` and\n * `candidateCandidateId` are present, lift is computed on paired\n * (experimentId, scenarioId, seed) identities shared between the two sides.\n * Unmatched rows remain visible in the lift result. */\n baselineCandidateId?: string\n candidateCandidateId?: string\n /** Canary scenarios — checked against every run's raw output for\n * holdout contamination. */\n canaryScenarios?: DatasetScenario[]\n /** Analyst registry for failure clustering. When omitted, the\n * `failureClusters` section is left undefined. */\n analyst?: AnalystRegistry\n /** Downstream outcome metric per run (e.g. engagement rate, approval\n * rate, downstream pass rate). When present, the report includes\n * `outcomeCorrelation` + a simple linear reward model fit. */\n outcomeSignal?: {\n metric: string\n valueByRunId: Record<string, number>\n }\n /** Multi-rater feedback for inter-rater agreement. Each entry is one\n * rater's score for one run. Two or more raters → kappa + disagreement\n * triage list. */\n raterScores?: Array<{ runId: string; rater: string; score: number }>\n /** Number of histogram bins for distributional summaries. Default 12. */\n histogramBins?: number\n /** Decision threshold — the smallest composite lift the caller cares\n * about. Used by the recommendations engine to call ship vs hold.\n * Default 0.02. */\n decisionThreshold?: number\n /** Optional prior-period runs. When set, the report includes\n * `priorPeriodComparison` with per-metric Welch-CI deltas and\n * recommendations fire on statistically significant regressions.\n * The two windows do NOT have to share scenarios — the comparison\n * is two-sample unpaired (the substrate's `lift` field uses paired\n * bootstrap on shared (experimentId, scenarioId, seed) identities; this is the\n * shape for \"this week vs last week\" rather than \"candidate vs\n * baseline within a campaign\"). */\n baselineRuns?: RunRecord[]\n /** Human-readable label for the baseline window, e.g. \"vs prior 7\n * days\", \"vs v3.1 release\". Surfaces in recommendations + UI. */\n baselineLabel?: string\n}\n\nexport interface SummarizeExecutionOptions {\n runs: RunRecord[]\n histogramBins?: number\n}\n\nexport interface ExecutionReport {\n execution: ExecutionInsight\n costProvenance: CostProvenanceSummary\n}\n\n/** Summarize runtime facts without interpreting task quality or promotion readiness. */\nexport function summarizeExecution(opts: SummarizeExecutionOptions): ExecutionReport {\n const runs = opts.runs.map(validateRunRecord)\n const bins = opts.histogramBins ?? 12\n return {\n execution: computeExecutionInsight(runs, bins),\n costProvenance: summarizeCostProvenance(runs),\n }\n}\n\nexport async function analyzeRuns(opts: AnalyzeRunsOptions): Promise<InsightReport> {\n const runs = opts.runs.map(validateRunRecord)\n const bins = opts.histogramBins ?? 12\n const threshold = opts.decisionThreshold ?? 0.02\n const split = resolveSplit(runs, opts.split ?? 'auto')\n\n const compositeWithIds = runs\n .map((r) => ({ runId: r.runId, score: compositeOf(r, split) }))\n .filter((p) => Number.isFinite(p.score))\n const composite = distributionOf(\n compositeWithIds.map((p) => p.score),\n bins,\n compositeWithIds,\n )\n\n const perDimension = computePerDimension(runs, bins)\n const { execution, costProvenance: provenance } = summarizeExecution({\n runs,\n histogramBins: bins,\n })\n const knownCostRuns = runs.filter((run) => run.costProvenance.kind !== 'uncaptured')\n const costs = knownCostRuns.map((r) => r.costUsd).filter(isFiniteNumber)\n const costDist = distributionOf(costs, bins)\n const pareto = paretoChart(knownCostRuns, { split })\n const degraded: { cost?: string; pareto?: string } = {}\n if (provenance.uncaptured.n > 0) {\n degraded.cost = diagnoseCostCoverage(runs, provenance)\n } else if (costs.length === 0 || costs.every((c) => c === 0)) {\n degraded.cost = `all ${runs.length} explicitly observed or estimated USD values are $0`\n }\n if (pareto.points.length < 2) {\n degraded.pareto =\n pareto.points.length === 0\n ? 'no candidates — Pareto unavailable'\n : 'single candidate — Pareto is a single point, not a frontier'\n }\n const costQuality = {\n cost: costDist,\n pareto,\n provenance,\n ...(degraded.cost || degraded.pareto ? { degraded } : {}),\n }\n\n const judges = computeJudgeInsights(runs)\n\n const interRater = opts.raterScores ? computeInterRater(opts.raterScores) : undefined\n\n const lift = computeLift(runs, opts.baselineCandidateId, opts.candidateCandidateId, split)\n\n const failureClusters = opts.analyst\n ? await computeFailureClusters(runs, opts.analyst, split)\n : undefined\n\n const failureClasses = computeFailureClasses(runs, split)\n\n const contamination = opts.canaryScenarios\n ? computeContamination(runs, opts.canaryScenarios)\n : undefined\n\n const outcomeCorrelation = opts.outcomeSignal\n ? computeOutcomeCorrelation(runs, opts.outcomeSignal, split)\n : undefined\n\n const release = buildReleaseScorecard(composite, lift, contamination)\n\n const priorPeriodComparison = opts.baselineRuns\n ? computePriorPeriodComparison(runs, opts.baselineRuns, split, opts.baselineLabel)\n : undefined\n\n const recommendations = buildRecommendations({\n composite,\n judges,\n interRater,\n lift,\n failureClusters,\n failureClasses,\n contamination,\n outcomeCorrelation,\n priorPeriodComparison,\n threshold,\n })\n\n return {\n n: runs.length,\n execution,\n composite,\n perDimension,\n costQuality,\n judges,\n interRater,\n lift,\n failureClusters,\n contamination,\n outcomeCorrelation,\n release,\n ...(failureClasses ? { failureClasses } : {}),\n ...(priorPeriodComparison ? { priorPeriodComparison } : {}),\n recommendations,\n }\n}\n\nfunction computeExecutionInsight(runs: RunRecord[], bins: number): ExecutionInsight {\n const aggregateRows = runs.flatMap((run) => {\n const usage = aggregateTokenUsage(run)\n return usage ? [{ usage, costUsd: finiteRaw(run, 'aggregate_cost_usd') }] : []\n })\n const aggregateCosts = aggregateRows.flatMap((row) =>\n row.costUsd !== undefined ? [row.costUsd] : [],\n )\n const modelCounts = new Map<string, number>()\n let executionErrorRuns = 0\n let executionErrorEvents = 0\n let errorReportingRuns = 0\n let errorSpanEvents = 0\n let errorSpanReportingRuns = 0\n const terminalOutcomes: Record<RunTerminalOutcome, number> = {\n succeeded: 0,\n failed: 0,\n cancelled: 0,\n incomplete: 0,\n unknown: 0,\n }\n const errorsByTerminalOutcome: ExecutionInsight['executionErrors']['byTerminalOutcome'] = {\n succeeded: { withErrors: 0, withoutErrors: 0, unreported: 0 },\n failed: { withErrors: 0, withoutErrors: 0, unreported: 0 },\n cancelled: { withErrors: 0, withoutErrors: 0, unreported: 0 },\n incomplete: { withErrors: 0, withoutErrors: 0, unreported: 0 },\n unknown: { withErrors: 0, withoutErrors: 0, unreported: 0 },\n }\n let modelCallRuns = 0\n let modelCallEvents = 0\n let modelCallReportingRuns = 0\n\n for (const run of runs) {\n modelCounts.set(run.model, (modelCounts.get(run.model) ?? 0) + 1)\n const terminalOutcome = run.terminalOutcome\n terminalOutcomes[terminalOutcome] += 1\n const modelCalls = nonNegativeCountRaw(run, 'llm_span_count')\n if (modelCalls !== undefined) {\n modelCallEvents += modelCalls\n modelCallReportingRuns += 1\n }\n const usage = run.tokenUsage\n if (\n (modelCalls ?? 0) > 0 ||\n usage.input > 0 ||\n usage.output > 0 ||\n (usage.cached ?? 0) > 0 ||\n (usage.cacheWrite ?? 0) > 0\n ) {\n modelCallRuns += 1\n }\n const errorEvents = reportedExecutionErrorEvents(run)\n if (errorEvents !== undefined) {\n executionErrorEvents += errorEvents\n errorReportingRuns += 1\n if (errorEvents > 0) {\n executionErrorRuns += 1\n errorsByTerminalOutcome[terminalOutcome].withErrors += 1\n } else errorsByTerminalOutcome[terminalOutcome].withoutErrors += 1\n } else errorsByTerminalOutcome[terminalOutcome].unreported += 1\n const reportedErrorSpans = nonNegativeCountRaw(run, 'error_span_count')\n if (reportedErrorSpans !== undefined) {\n errorSpanEvents += reportedErrorSpans\n errorSpanReportingRuns += 1\n }\n }\n\n return {\n durationMs: distributionOf(\n runs.map((run) => run.wallMs),\n bins,\n ),\n queueMs: distributionOf(\n runs.filter((run) => run.queueMs !== undefined).map((run) => run.queueMs!),\n bins,\n ),\n tokenUsage: summarizeTokenUsage(\n runs.map((run) => run.tokenUsage),\n bins,\n ),\n aggregateUsage: {\n runs: aggregateRows.length,\n tokenUsage: summarizeTokenUsage(\n aggregateRows.map((row) => row.usage),\n bins,\n ),\n costUsd: distributionOf(aggregateCosts, bins),\n totalCostUsd: aggregateCosts.reduce((total, value) => total + value, 0),\n },\n models: [...modelCounts.entries()]\n .map(([model, count]) => ({ model, runs: count }))\n .sort((left, right) => right.runs - left.runs || left.model.localeCompare(right.model)),\n modelCalls: {\n runs: modelCallRuns,\n events: modelCallEvents,\n reportingRuns: modelCallReportingRuns,\n },\n executionErrors: {\n runs: executionErrorRuns,\n fraction: errorReportingRuns > 0 ? executionErrorRuns / errorReportingRuns : null,\n events: executionErrorEvents,\n reportingRuns: errorReportingRuns,\n errorSpanEvents,\n errorSpanReportingRuns,\n byTerminalOutcome: errorsByTerminalOutcome,\n },\n terminalOutcomes,\n }\n}\n\nfunction reportedExecutionErrorEvents(run: RunRecord): number | undefined {\n return nonNegativeCountRaw(run, 'execution_error_count')\n}\n\nfunction nonNegativeCountRaw(run: RunRecord, key: string): number | undefined {\n const value = finiteRaw(run, key)\n return value !== undefined && Number.isInteger(value) && value >= 0 ? value : undefined\n}\n\nfunction summarizeTokenUsage(usages: RunTokenUsage[], bins: number): TokenUsageInsight {\n const reasoning = usages.flatMap((usage) =>\n usage.reasoning !== undefined ? [usage.reasoning] : [],\n )\n const cached = usages.flatMap((usage) => (usage.cached !== undefined ? [usage.cached] : []))\n const cacheWrite = usages.flatMap((usage) =>\n usage.cacheWrite !== undefined ? [usage.cacheWrite] : [],\n )\n return {\n input: distributionOf(\n usages.map((usage) => usage.input),\n bins,\n ),\n output: distributionOf(\n usages.map((usage) => usage.output),\n bins,\n ),\n reasoning: distributionOf(reasoning, bins),\n cached: distributionOf(cached, bins),\n cacheWrite: distributionOf(cacheWrite, bins),\n totals: {\n input: usages.reduce((total, usage) => total + usage.input, 0),\n output: usages.reduce((total, usage) => total + usage.output, 0),\n reasoning: reasoning.reduce((total, value) => total + value, 0),\n cached: cached.reduce((total, value) => total + value, 0),\n cacheWrite: cacheWrite.reduce((total, value) => total + value, 0),\n },\n }\n}\n\nfunction aggregateTokenUsage(run: RunRecord): RunTokenUsage | undefined {\n const input = finiteRaw(run, 'aggregate_prompt_tokens')\n const output = finiteRaw(run, 'aggregate_completion_tokens')\n const reasoning = finiteRaw(run, 'aggregate_reasoning_tokens')\n const cached = finiteRaw(run, 'aggregate_cached_tokens')\n const cacheWrite = finiteRaw(run, 'aggregate_cache_write_tokens')\n if (\n input === undefined &&\n output === undefined &&\n reasoning === undefined &&\n cached === undefined &&\n cacheWrite === undefined\n )\n return undefined\n return {\n input: input ?? 0,\n output: output ?? 0,\n ...(reasoning !== undefined ? { reasoning } : {}),\n ...(cached !== undefined ? { cached } : {}),\n ...(cacheWrite !== undefined ? { cacheWrite } : {}),\n }\n}\n\nfunction finiteRaw(run: RunRecord, key: string): number | undefined {\n const value = run.outcome.raw[key]\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined\n}\n\nfunction summarizeCostProvenance(runs: RunRecord[]): CostProvenanceSummary {\n const summary: CostProvenanceSummary = {\n observed: { n: 0, totalUsd: 0 },\n estimated: { n: 0, totalUsd: 0 },\n uncaptured: { n: 0 },\n knownFraction: 0,\n }\n for (const run of runs) {\n const cost = run.costProvenance\n if (cost.kind === 'uncaptured') {\n summary.uncaptured.n += 1\n } else {\n summary[cost.kind].n += 1\n summary[cost.kind].totalUsd += cost.usd\n }\n }\n const known = summary.observed.n + summary.estimated.n\n summary.knownFraction = runs.length > 0 ? known / runs.length : 0\n return summary\n}\n\nfunction diagnoseCostCoverage(runs: RunRecord[], provenance: CostProvenanceSummary): string {\n const uncaptured = provenance.uncaptured.n\n const known = provenance.observed.n + provenance.estimated.n\n if (uncaptured === runs.length) {\n return `USD cost uncaptured for all ${runs.length} runs — no observed or estimated USD values; token and wall-time metrics remain available.`\n }\n return `USD cost uncaptured for ${uncaptured}/${runs.length} runs; excluded those rows from cost statistics (${known}/${runs.length} retained: ${provenance.observed.n} observed, ${provenance.estimated.n} estimated).`\n}\n\n/**\n * Model-free task-failure tally.\n *\n * Explicit non-success classes are task-failure evidence.\n * A low task score without a class is counted as `unknown`.\n */\nfunction computeFailureClasses(\n runs: RunRecord[],\n split: 'search' | 'holdout',\n): FailureClassTally[] | undefined {\n const counts = new Map<FailureClass, number>()\n for (const r of runs) {\n if (!isTaskFailure(r, split)) continue\n const key =\n r.failureClass !== undefined && r.failureClass !== 'success' ? r.failureClass : 'unknown'\n counts.set(key, (counts.get(key) ?? 0) + 1)\n }\n if (counts.size === 0) return undefined\n const n = runs.length\n return [...counts.entries()]\n .map(([failureClass, count]) => ({\n failureClass,\n count,\n share: n > 0 ? count / n : 0,\n }))\n .sort((a, b) => b.count - a.count || a.failureClass.localeCompare(b.failureClass))\n}\n\n// ── Prior-period comparison ─────────────────────────────────────────\n\n/** Direction of the metric — does \"higher current\" mean better or worse?\n * Composite + judge dimensions: higher is better. Cost + duration: lower\n * is better. The recommendations engine flips the sign before judging\n * regressed vs improved. */\ntype MetricDirection = 'higher-is-better' | 'lower-is-better'\n\nfunction computePriorPeriodComparison(\n current: RunRecord[],\n baseline: RunRecord[],\n split: 'search' | 'holdout',\n windowLabel: string | undefined,\n): PriorPeriodComparison | undefined {\n if (current.length === 0 || baseline.length === 0) return undefined\n\n const metrics: Record<string, MetricDelta> = {}\n const directions: Record<string, MetricDirection> = {}\n\n const compositeCurrent = current\n .map((r) => compositeOf(r, split))\n .filter(Number.isFinite) as number[]\n const compositeBaseline = baseline\n .map((r) => compositeOf(r, split))\n .filter(Number.isFinite) as number[]\n if (compositeCurrent.length > 0 && compositeBaseline.length > 0) {\n metrics.composite = welchCompare(compositeBaseline, compositeCurrent)\n directions.composite = 'higher-is-better'\n }\n\n const costCurrent = knownCostValues(current)\n const costBaseline = knownCostValues(baseline)\n if (costCurrent.length > 0 && costBaseline.length > 0) {\n metrics.cost = welchCompare(costBaseline, costCurrent)\n directions.cost = 'lower-is-better'\n }\n\n const durCurrent = current.map((r) => r.wallMs).filter(Number.isFinite)\n const durBaseline = baseline.map((r) => r.wallMs).filter(Number.isFinite)\n if (durCurrent.length > 0 && durBaseline.length > 0) {\n metrics.duration = welchCompare(durBaseline, durCurrent)\n directions.duration = 'lower-is-better'\n }\n\n const tokCurrent = current\n .map((r) => (r.tokenUsage.input ?? 0) + (r.tokenUsage.output ?? 0))\n .filter(Number.isFinite)\n const tokBaseline = baseline\n .map((r) => (r.tokenUsage.input ?? 0) + (r.tokenUsage.output ?? 0))\n .filter(Number.isFinite)\n if (tokCurrent.length > 0 && tokBaseline.length > 0) {\n metrics.tokenUsage = welchCompare(tokBaseline, tokCurrent)\n directions.tokenUsage = 'lower-is-better'\n }\n\n // Per-dimension judge comparisons — only for dimensions present in BOTH\n // windows. We use perDimMean since per-judge nesting is finicky for\n // two-sample comparisons across different judge configurations.\n const dimsCurrent = collectPerDimension(current)\n const dimsBaseline = collectPerDimension(baseline)\n for (const dim of Object.keys(dimsCurrent)) {\n const b = dimsBaseline[dim]\n const c = dimsCurrent[dim]\n if (!b || b.length === 0 || !c || c.length === 0) continue\n metrics[`dim.${dim}`] = welchCompare(b, c)\n directions[`dim.${dim}`] = 'higher-is-better'\n }\n\n const regressedMetrics: string[] = []\n const improvedMetrics: string[] = []\n for (const [name, delta] of Object.entries(metrics)) {\n if (!delta.significant) continue\n const dir = directions[name] ?? 'higher-is-better'\n const better = dir === 'higher-is-better' ? delta.delta > 0 : delta.delta < 0\n if (better) improvedMetrics.push(name)\n else regressedMetrics.push(name)\n }\n\n return {\n baselineN: baseline.length,\n currentN: current.length,\n ...(windowLabel ? { windowLabel } : {}),\n metrics,\n regressedMetrics,\n improvedMetrics,\n }\n}\n\nfunction knownCostValues(runs: RunRecord[]): number[] {\n return runs\n .filter((run) => run.costProvenance.kind !== 'uncaptured')\n .map((run) => run.costUsd)\n .filter(isFiniteNumber)\n}\n\nfunction isFiniteNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value)\n}\n\n/** Collect per-dimension values across runs (from outcome.judgeScores.perDimMean). */\nfunction collectPerDimension(runs: RunRecord[]): Record<string, number[]> {\n const out: Record<string, number[]> = {}\n for (const r of runs) {\n const perDim = r.outcome.judgeScores?.perDimMean\n if (!perDim) continue\n for (const [dim, value] of Object.entries(perDim)) {\n if (!Number.isFinite(value)) continue\n if (!out[dim]) out[dim] = []\n out[dim].push(value as number)\n }\n }\n return out\n}\n\n/** Two-sample Welch comparison: unequal-variance t-test + CI on the delta\n * + Cohen's d (pooled stddev). Significance = p < 0.05 AND |d| >= 0.2. */\nfunction welchCompare(baseline: number[], current: number[]): MetricDelta {\n const baselineMean = mean(baseline)\n const currentMean = mean(current)\n const baselineVar = sampleVariance(baseline, baselineMean)\n const currentVar = sampleVariance(current, currentMean)\n const baselineN = baseline.length\n const currentN = current.length\n const delta = currentMean - baselineMean\n\n // Welch standard error\n const se = Math.sqrt(baselineVar / baselineN + currentVar / currentN)\n // For 95% CI we use z=1.96 (large-n approximation). Customers running\n // analyzeRuns will typically have n >= 30; the t-correction is\n // negligible vs the practical noise floor.\n const halfWidth = 1.96 * (se > 0 ? se : 0)\n const ci95: [number, number] = [delta - halfWidth, delta + halfWidth]\n\n // p-value via normal approximation to the t-statistic.\n const t = se > 0 ? delta / se : 0\n const pValue = se > 0 ? 2 * (1 - normalCdf(Math.abs(t))) : 1\n\n // Cohen's d — pooled stddev.\n const pooledStddev = Math.sqrt(\n ((baselineN - 1) * baselineVar + (currentN - 1) * currentVar) /\n Math.max(1, baselineN + currentN - 2),\n )\n const cohensD = pooledStddev > 0 ? delta / pooledStddev : 0\n\n // Significance: BOTH p < 0.05 AND |d| >= 0.2 (small-effect threshold).\n const significant = pValue < 0.05 && Math.abs(cohensD) >= 0.2\n\n return {\n current: currentMean,\n baseline: baselineMean,\n delta,\n ci95,\n pValue,\n cohensD,\n baselineN,\n currentN,\n significant,\n }\n}\n\nfunction sampleVariance(xs: number[], xsMean: number): number {\n if (xs.length < 2) return 0\n let s = 0\n for (const x of xs) s += (x - xsMean) ** 2\n return s / (xs.length - 1)\n}\n\n// ── Composite + split selection ─────────────────────────────────────\n\nfunction resolveSplit(\n runs: RunRecord[],\n pref: 'search' | 'holdout' | 'auto',\n): 'search' | 'holdout' {\n if (pref !== 'auto') return pref\n const hasHoldout = runs.some((r) => Number.isFinite(observedSplitScore(r, 'holdout')))\n return hasHoldout ? 'holdout' : 'search'\n}\n\n/**\n * RAW (`observedSplitScore`): `analyzeRuns` describes what a set of runs\n * reported, and every downstream reader of this composite — distributions,\n * per-candidate summaries, the reward-hacking correlation — needs the ungated\n * number to see an inflated run at all.\n */\nfunction compositeOf(run: RunRecord, split: 'search' | 'holdout'): number {\n // Split-exact, no cross-split fallthrough: answering \"what did this run\n // score on the split I am summarising\" with the other split's number\n // silently mixes populations.\n const score = observedSplitScore(run, split)\n return Number.isFinite(score) ? (score as number) : Number.NaN\n}\n\n// ── Distribution helpers ────────────────────────────────────────────\n\nfunction distributionOf(\n values: number[],\n bins: number,\n withIds?: Array<{ runId: string; score: number }>,\n): ScalarDistribution {\n if (values.length === 0) {\n return {\n n: 0,\n mean: null,\n p50: null,\n p95: null,\n stddev: null,\n min: null,\n max: null,\n histogram: [],\n }\n }\n const sorted = [...values].sort((a, b) => a - b)\n const n = sorted.length\n const mean = sorted.reduce((s, v) => s + v, 0) / n\n const variance = sorted.reduce((s, v) => s + (v - mean) ** 2, 0) / n\n const stddev = Math.sqrt(variance)\n const tailRuns = withIds\n ? [...withIds].sort((a, b) => a.score - b.score).slice(0, Math.min(5, withIds.length))\n : undefined\n return {\n n,\n mean,\n p50: percentile(sorted, 0.5),\n p95: percentile(sorted, 0.95),\n stddev,\n min: sorted[0]!,\n max: sorted[n - 1]!,\n histogram: histogram(sorted, bins),\n ...(tailRuns ? { tailRuns } : {}),\n }\n}\n\nfunction percentile(sorted: number[], q: number): number {\n if (sorted.length === 0) return 0\n if (sorted.length === 1) return sorted[0]!\n const idx = (sorted.length - 1) * q\n const lo = Math.floor(idx)\n const hi = Math.ceil(idx)\n if (lo === hi) return sorted[lo]!\n const w = idx - lo\n return sorted[lo]! * (1 - w) + sorted[hi]! * w\n}\n\n/** Even-width histogram over the value range. Returns inclusive-lo /\n * exclusive-hi bins (closed on right for the last bin) compatible with\n * the substrate's `GainDistributionBin` shape. */\nfunction histogram(sorted: number[], bins: number): ScalarDistribution['histogram'] {\n if (sorted.length === 0 || bins < 1) return []\n const min = sorted[0]!\n const max = sorted[sorted.length - 1]!\n if (min === max) return [{ lo: min, hi: max, count: sorted.length }]\n const width = (max - min) / bins\n const out: ScalarDistribution['histogram'] = []\n for (let i = 0; i < bins; i++) {\n const lo = min + i * width\n const hi = i === bins - 1 ? max : lo + width\n out.push({ lo, hi, count: 0 })\n }\n for (const v of sorted) {\n const idx = Math.min(bins - 1, Math.floor((v - min) / width))\n out[idx]!.count++\n }\n return out\n}\n\nfunction computePerDimension(runs: RunRecord[], bins: number): Record<string, ScalarDistribution> {\n // JudgeScoresRecord pre-aggregates `perDimMean` (mean across judges per\n // dimension). We collect those means across runs to produce a per-dim\n // distribution at the corpus level. Consumers who want per-judge\n // dimension values reach into `perJudge[judgeId][dim]` themselves.\n const byDim = new Map<string, number[]>()\n for (const run of runs) {\n const scores = run.outcome.judgeScores\n if (!scores) continue\n for (const [dim, value] of Object.entries(scores.perDimMean ?? {})) {\n if (!Number.isFinite(value)) continue\n const arr = byDim.get(dim) ?? []\n arr.push(value)\n byDim.set(dim, arr)\n }\n }\n const out: Record<string, ScalarDistribution> = {}\n for (const [dim, values] of byDim) out[dim] = distributionOf(values, bins)\n return out\n}\n\n// ── Judge insights ──────────────────────────────────────────────────\n\nfunction computeJudgeInsights(runs: RunRecord[]): Record<string, JudgeInsight> {\n // Each judge's per-run mean is the average of its per-dimension scores\n // for that run. We aggregate those means across all runs each judge\n // scored — giving consumers a \"this judge's typical verdict\" reading.\n const out: Record<string, JudgeInsight> = {}\n const byJudge = new Map<string, number[]>()\n for (const run of runs) {\n const scores = run.outcome.judgeScores\n if (!scores?.perJudge) continue\n for (const [judgeId, dims] of Object.entries(scores.perJudge)) {\n const dimValues = Object.values(dims).filter(Number.isFinite) as number[]\n if (dimValues.length === 0) continue\n const judgeMean = dimValues.reduce((s, v) => s + v, 0) / dimValues.length\n const arr = byJudge.get(judgeId) ?? []\n arr.push(judgeMean)\n byJudge.set(judgeId, arr)\n }\n }\n for (const [judgeId, values] of byJudge) {\n out[judgeId] = {\n n: values.length,\n meanScore: values.reduce((s, v) => s + v, 0) / values.length,\n }\n }\n return out\n}\n\n// ── Inter-rater agreement ───────────────────────────────────────────\n\nfunction computeInterRater(\n ratings: Array<{ runId: string; rater: string; score: number }>,\n): InterRaterInsight | undefined {\n const byRun = new Map<string, Array<{ rater: string; score: number }>>()\n for (const r of ratings) {\n if (!Number.isFinite(r.score)) continue\n const list = byRun.get(r.runId) ?? []\n list.push({ rater: r.rater, score: r.score })\n byRun.set(r.runId, list)\n }\n const raters = new Set(ratings.map((r) => r.rater))\n const jointlyRated: string[] = []\n for (const [runId, ratersForRun] of byRun) {\n const seen = new Set(ratersForRun.map((r) => r.rater))\n let all = true\n for (const r of raters) if (!seen.has(r)) all = false\n if (all) jointlyRated.push(runId)\n }\n if (raters.size < 2 || jointlyRated.length === 0) return undefined\n\n const raterList = [...raters].sort()\n const perPair: Record<string, number> = {}\n for (let i = 0; i < raterList.length; i++) {\n for (let j = i + 1; j < raterList.length; j++) {\n const a = raterList[i]!\n const b = raterList[j]!\n const aScores: number[] = []\n const bScores: number[] = []\n for (const runId of jointlyRated) {\n const ratersForRun = byRun.get(runId)!\n const sa = ratersForRun.find((r) => r.rater === a)?.score\n const sb = ratersForRun.find((r) => r.rater === b)?.score\n if (sa !== undefined && sb !== undefined) {\n aScores.push(sa)\n bScores.push(sb)\n }\n }\n const agreement = continuousAgreement(\n aScores.map((score, index) => [score, bScores[index]!]),\n { bootstrap: 0 },\n )\n perPair[`${a}::${b}`] = agreement.weightedKappa\n }\n }\n const matrix = jointlyRated.map((runId) => {\n const ratingsByRater = new Map(byRun.get(runId)!.map((rating) => [rating.rater, rating.score]))\n return raterList.map((rater) => ratingsByRater.get(rater)!)\n })\n const agreement = continuousAgreement(matrix, { bootstrap: 0 })\n\n const disagreementCases = jointlyRated\n .map((runId) => {\n const ratersForRun = byRun.get(runId)!\n const scores = ratersForRun.map((r) => r.score)\n const range = Math.max(...scores) - Math.min(...scores)\n return { runId, ratings: ratersForRun, range }\n })\n .sort((a, b) => b.range - a.range)\n .slice(0, 20)\n\n return {\n raters: raters.size,\n jointlyRated: jointlyRated.length,\n kappa: Number.isFinite(agreement.weightedKappa) ? agreement.weightedKappa : 0,\n icc: agreement.icc,\n pearson: agreement.pearson,\n spearman: agreement.spearman,\n perPair,\n disagreementCases,\n }\n}\n\n// ── Lift ────────────────────────────────────────────────────────────\n\nfunction computeLift(\n runs: RunRecord[],\n baselineId: string | undefined,\n candidateId: string | undefined,\n split: 'search' | 'holdout',\n): LiftInsight | undefined {\n let bId = baselineId\n let cId = candidateId\n if (!bId || !cId) {\n // Auto-detect: when exactly two distinct candidateIds appear, treat the\n // lower-mean side as baseline.\n const ids = [...new Set(runs.map((r) => r.candidateId))]\n if (ids.length !== 2) return undefined\n const [idA, idB] = ids as [string, string]\n const scoresA = finiteCompositeScores(\n runs.filter((run) => run.candidateId === idA),\n split,\n )\n const scoresB = finiteCompositeScores(\n runs.filter((run) => run.candidateId === idB),\n split,\n )\n if (scoresA.length === 0 || scoresB.length === 0) return undefined\n const meanA = mean(scoresA)\n const meanB = mean(scoresB)\n bId = meanA <= meanB ? idA : idB\n cId = meanA <= meanB ? idB : idA\n }\n\n const baseline = runs.filter((r) => r.candidateId === bId)\n const candidate = runs.filter((r) => r.candidateId === cId)\n if (baseline.length === 0 || candidate.length === 0) return undefined\n\n const scoredBaseline = baseline.filter((run) => Number.isFinite(compositeOf(run, split)))\n const scoredCandidate = candidate.filter((run) => Number.isFinite(compositeOf(run, split)))\n const pairing = pairRunRecords(scoredBaseline, scoredCandidate)\n const pairedBaseline = pairing.pairs.map((pair) => compositeOf(pair.baseline, split))\n const pairedCandidate = pairing.pairs.map((pair) => compositeOf(pair.treatment, split))\n if (pairedBaseline.length === 0) return undefined\n\n const baselineMean = mean(pairedBaseline)\n const candidateMean = mean(pairedCandidate)\n const delta = candidateMean - baselineMean\n\n const bootstrap = pairedBootstrap(pairedBaseline, pairedCandidate, {\n confidence: 0.95,\n resamples: 2000,\n statistic: 'mean',\n })\n const tTest = pairedTTest(pairedBaseline, pairedCandidate)\n const d = pairedCohensDz(pairedBaseline, pairedCandidate)\n const mde = pairedMde({ nPaired: pairedBaseline.length, power: 0.8, alpha: 0.05 })\n const requiredN =\n d === null || d === 0\n ? null\n : requiredPairedSampleSize({\n effect: Math.abs(d),\n power: 0.8,\n alpha: 0.05,\n })\n\n return {\n baselineMean,\n candidateMean,\n delta,\n ci95: [bootstrap.low, bootstrap.high],\n pValue: tTest.p,\n n: pairedBaseline.length,\n unpairedBaseline: pairing.unpairedBaseline.length,\n unpairedCandidate: pairing.unpairedTreatment.length,\n cohensD: d,\n mde,\n requiredN,\n }\n}\n\nfunction mean(arr: number[]): number {\n return arr.length === 0 ? 0 : arr.reduce((s, v) => s + v, 0) / arr.length\n}\n\n// ── Failure clustering ──────────────────────────────────────────────\n\nasync function computeFailureClusters(\n runs: RunRecord[],\n analyst: AnalystRegistry,\n split: 'search' | 'holdout',\n): Promise<FailureClusterInsight | undefined> {\n const failed = runs.filter((run) => isTaskFailure(run, split))\n if (failed.length === 0) return { clusters: [], totalFailures: 0 }\n\n const clusters = new Map<string, { exemplars: string[]; share: number }>()\n for (const run of failed) {\n try {\n // AnalystRunInputs routes by field name: run-record analysts read\n // `runRecord`. Any other shape makes every analyst skip with\n // \"missing input\" and the clusters come back silently empty.\n const result = await analyst.run(run.runId, { runRecord: run })\n for (const finding of result.findings as AnalystFinding[]) {\n const key = finding.area || finding.analyst_id || 'unclassified'\n const c = clusters.get(key) ?? { exemplars: [], share: 0 }\n if (c.exemplars.length < 5) c.exemplars.push(run.runId)\n clusters.set(key, c)\n }\n } catch {\n const c = clusters.get('analyst-error') ?? { exemplars: [], share: 0 }\n if (c.exemplars.length < 5) c.exemplars.push(run.runId)\n clusters.set('analyst-error', c)\n }\n }\n const clusterList = [...clusters.entries()].map(([id, c]) => ({\n id,\n name: id,\n share: c.exemplars.length / failed.length,\n exemplars: c.exemplars,\n }))\n clusterList.sort((a, b) => b.share - a.share)\n return { clusters: clusterList, totalFailures: failed.length }\n}\n\nfunction finiteCompositeScores(runs: readonly RunRecord[], split: 'search' | 'holdout'): number[] {\n return runs.map((run) => compositeOf(run, split)).filter(Number.isFinite)\n}\n\nfunction isTaskFailure(run: RunRecord, split: 'search' | 'holdout'): boolean {\n if (run.failureClass !== undefined && run.failureClass !== 'success') return true\n const score = compositeOf(run, split)\n return Number.isFinite(score) && score < 0.5\n}\n\n// ── Contamination ──────────────────────────────────────────────────\n\nfunction computeContamination(\n runs: RunRecord[],\n canaries: DatasetScenario[],\n): InsightReport['contamination'] {\n let leaks = 0\n const details: Array<{ runId: string; canary: string; matched: string }> = []\n for (const run of runs) {\n const output = stringifyOutput(run)\n if (!output) continue\n const leaksHere = checkCanaries(output, canaries)\n for (const leak of leaksHere) {\n leaks++\n details.push({ runId: run.runId, canary: leak.canary, matched: leak.evidence })\n }\n }\n return { leaks, holdoutAuditPassed: leaks === 0, details }\n}\n\nfunction stringifyOutput(run: RunRecord): string | undefined {\n // RunRecord doesn't fix where \"the agent's output\" lives — different\n // consumers stash it differently. We probe the common shapes: the\n // outcome.raw map (numeric only by design — unlikely to contain text),\n // and any string-valued fields tucked under metadata via type casting.\n // Consumers with bespoke shapes pass canaryScenarios only when they\n // know their runs carry a stringifiable surface.\n const metadata = (run as unknown as { metadata?: Record<string, unknown> }).metadata\n if (typeof metadata?.output === 'string') return metadata.output\n if (typeof metadata?.text === 'string') return metadata.text\n return undefined\n}\n\n// ── Outcome correlation + linear reward model ──────────────────────\n\nfunction computeOutcomeCorrelation(\n runs: RunRecord[],\n outcome: { metric: string; valueByRunId: Record<string, number> },\n split: 'search' | 'holdout',\n): OutcomeCorrelationInsight | undefined {\n const xs: number[] = []\n const ys: number[] = []\n for (const run of runs) {\n const y = outcome.valueByRunId[run.runId]\n if (y === undefined || !Number.isFinite(y)) continue\n const x = compositeOf(run, split)\n if (!Number.isFinite(x)) continue\n xs.push(x)\n ys.push(y)\n }\n if (xs.length < 3) return undefined\n\n const p = pearsonR(xs, ys)\n const s = spearmanR(xs, ys)\n const meanX = mean(xs)\n const meanY = mean(ys)\n let num = 0\n let denom = 0\n for (let i = 0; i < xs.length; i++) {\n num += (xs[i]! - meanX) * (ys[i]! - meanY)\n denom += (xs[i]! - meanX) ** 2\n }\n const slope = denom === 0 ? 0 : num / denom\n const intercept = meanY - slope * meanX\n const ssTot = ys.reduce((a, y) => a + (y - meanY) ** 2, 0)\n const ssRes = ys.reduce((a, y, i) => a + (y - (intercept + slope * xs[i]!)) ** 2, 0)\n const r2 = ssTot === 0 ? 0 : 1 - ssRes / ssTot\n\n return {\n metric: outcome.metric,\n n: xs.length,\n pearson: p,\n spearman: s,\n rewardModel: { intercept, slope, r2 },\n }\n}\n\n// ── Release confidence scorecard ───────────────────────────────────\n\nfunction buildReleaseScorecard(\n composite: ScalarDistribution,\n lift: LiftInsight | undefined,\n contamination: InsightReport['contamination'],\n): InsightReport['release'] {\n // Synthesise a minimal scorecard from the rolled-up signal. The\n // substrate's `evaluateReleaseConfidence` primitive consumes a richer\n // input shape that callers can produce by wiring SLO definitions; the\n // shape here is the contract `selfImprove`/`analyzeRuns` consumers\n // receive automatically. They can call `evaluateReleaseConfidence`\n // directly when they want SLO-based axis evaluation.\n const axes: InsightReport['release']['axes'] = []\n const liftPass =\n lift === undefined\n ? ('not_evaluated' as const)\n : lift.ci95[0] > 0\n ? ('pass' as const)\n : lift.delta > 0\n ? ('warn' as const)\n : ('fail' as const)\n axes.push({\n name: 'quality-lift',\n status: liftPass,\n detail: lift\n ? `delta=${lift.delta.toFixed(3)}, CI95=[${lift.ci95[0].toFixed(3)}, ${lift.ci95[1].toFixed(3)}], n=${lift.n}`\n : 'no baseline/candidate pair available',\n })\n const contamPass =\n contamination === undefined\n ? ('not_evaluated' as const)\n : contamination.leaks === 0\n ? ('pass' as const)\n : ('fail' as const)\n axes.push({\n name: 'contamination',\n status: contamPass,\n detail: contamination ? `${contamination.leaks} canary leak(s)` : 'no canaries supplied',\n })\n axes.push(\n composite.n === 0\n ? {\n name: 'composite-distribution',\n status: 'not_evaluated',\n detail: 'no task-quality scores available',\n }\n : {\n name: 'composite-distribution',\n status:\n composite.mean !== null && composite.mean >= 0.5\n ? 'pass'\n : composite.mean !== null && composite.mean >= 0.3\n ? 'warn'\n : 'fail',\n detail:\n composite.mean === null || composite.p50 === null || composite.p95 === null\n ? 'task-quality distribution is internally incomplete'\n : `mean=${composite.mean.toFixed(3)}, p50=${composite.p50.toFixed(3)}, p95=${composite.p95.toFixed(3)} over n=${composite.n}`,\n },\n )\n const status = axes.some((a) => a.status === 'fail')\n ? 'fail'\n : axes.some((a) => a.status === 'warn' || a.status === 'not_evaluated')\n ? 'warn'\n : 'pass'\n return {\n status,\n axes,\n issues: [],\n }\n}\n\n// ── Recommendations engine ─────────────────────────────────────────\n\ninterface RecommendationContext {\n composite: ScalarDistribution\n judges: Record<string, JudgeInsight>\n interRater?: InterRaterInsight\n lift?: LiftInsight\n failureClusters?: FailureClusterInsight\n failureClasses?: FailureClassTally[]\n contamination?: InsightReport['contamination']\n outcomeCorrelation?: OutcomeCorrelationInsight\n priorPeriodComparison?: PriorPeriodComparison\n threshold: number\n}\n\nfunction buildRecommendations(ctx: RecommendationContext): Recommendation[] {\n const out: Recommendation[] = []\n\n // Prior-period regressions — highest customer-impact signal when present.\n // \"Did my last change help?\" with a falsifiable answer.\n if (ctx.priorPeriodComparison) {\n const ppc = ctx.priorPeriodComparison\n const label = ppc.windowLabel ?? 'baseline period'\n for (const name of ppc.regressedMetrics) {\n const d = ppc.metrics[name]\n if (!d) continue\n out.push({\n priority: 'critical',\n kind: 'investigate',\n title: `${name} regressed from ${d.baseline.toFixed(3)} → ${d.current.toFixed(3)} vs ${label}`,\n detail: `Welch CI95 = [${d.ci95[0].toFixed(3)}, ${d.ci95[1].toFixed(3)}], p=${d.pValue.toFixed(4)}, Cohen's d=${d.cohensD.toFixed(2)} (n_current=${d.currentN}, n_baseline=${d.baselineN}). The regression is statistically significant at p<0.05 with at-least-small effect size.`,\n evidencePath: `priorPeriodComparison.metrics.${name}`,\n })\n }\n for (const name of ppc.improvedMetrics) {\n const d = ppc.metrics[name]\n if (!d) continue\n out.push({\n priority: 'low',\n kind: 'ship',\n title: `${name} improved from ${d.baseline.toFixed(3)} → ${d.current.toFixed(3)} vs ${label}`,\n detail: `Welch CI95 = [${d.ci95[0].toFixed(3)}, ${d.ci95[1].toFixed(3)}], p=${d.pValue.toFixed(4)}, Cohen's d=${d.cohensD.toFixed(2)} (n_current=${d.currentN}, n_baseline=${d.baselineN}). Statistically significant improvement worth flagging.`,\n evidencePath: `priorPeriodComparison.metrics.${name}`,\n })\n }\n }\n\n // Composite-distribution branch. Fires when the overall quality signal is\n // poor regardless of lift / contamination / clusters — the customer needs\n // to know they have a problem AND which specific runs to inspect.\n if (\n ctx.composite.n > 0 &&\n ctx.composite.mean !== null &&\n ctx.composite.p50 !== null &&\n ctx.composite.p95 !== null\n ) {\n if (ctx.composite.mean < 0.3) {\n const tail = ctx.composite.tailRuns ?? []\n const names = tail\n .slice(0, 5)\n .map((t) => `${t.runId}=${t.score.toFixed(3)}`)\n .join(', ')\n out.push({\n priority: 'critical',\n kind: 'investigate',\n title: `Composite mean ${ctx.composite.mean.toFixed(3)} is below the 0.3 floor — the agent is broken on this corpus`,\n detail:\n tail.length > 0\n ? `Worst ${tail.length} run${tail.length === 1 ? '' : 's'} to inspect first: ${names}. Histogram p50=${ctx.composite.p50.toFixed(3)}, p95=${ctx.composite.p95.toFixed(3)}.`\n : `Histogram p50=${ctx.composite.p50.toFixed(3)}, p95=${ctx.composite.p95.toFixed(3)}.`,\n evidencePath: 'composite.tailRuns',\n })\n } else if (ctx.composite.mean < 0.5) {\n const tail = ctx.composite.tailRuns ?? []\n const names = tail\n .slice(0, 3)\n .map((t) => `${t.runId}=${t.score.toFixed(3)}`)\n .join(', ')\n out.push({\n priority: 'high',\n kind: 'investigate',\n title: `Composite mean ${ctx.composite.mean.toFixed(3)} is below 0.5 — investigate the lower tail before claiming the agent is healthy`,\n detail:\n tail.length > 0\n ? `Worst ${tail.length} run${tail.length === 1 ? '' : 's'}: ${names}. Histogram p50=${ctx.composite.p50.toFixed(3)}, p95=${ctx.composite.p95.toFixed(3)}.`\n : `Histogram p50=${ctx.composite.p50.toFixed(3)}, p95=${ctx.composite.p95.toFixed(3)}.`,\n evidencePath: 'composite.tailRuns',\n })\n }\n }\n\n // A healthy-looking mean can hide a group of failed tasks sharing one\n // producer-reported cause. This path does not require an analyst.\n if (ctx.failureClasses && ctx.failureClasses.length > 0) {\n const top = ctx.failureClasses[0]!\n if (top.count >= 3 && top.share >= 0.15) {\n out.push({\n priority: top.share >= 0.25 ? 'high' : 'medium',\n kind: 'investigate',\n title: `'${top.failureClass}' is the dominant failure class — ${top.count} runs (${(top.share * 100).toFixed(0)}% of the corpus)`,\n detail: `The mean composite can look acceptable while one failure class dominates the lower tail. ${top.count} of ${ctx.composite.n} runs failed with '${top.failureClass}'${ctx.failureClasses.length > 1 ? ` (next: '${ctx.failureClasses[1]!.failureClass}' ×${ctx.failureClasses[1]!.count})` : ''}. Fix this cause first.`,\n evidencePath: 'failureClasses',\n })\n }\n }\n\n // Missing-judges branch. The report can't surface per-dimension or\n // calibration signal when `outcome.judgeScores` is empty across the\n // corpus. Tell the customer how to enrich.\n if (Object.keys(ctx.judges).length === 0 && ctx.composite.n > 0) {\n out.push({\n priority: 'medium',\n kind: 'expand-corpus',\n title: 'No judge scores recorded — per-dimension + calibration insights unavailable',\n detail:\n 'Records have no `outcome.judgeScores`. To unlock perDimension, judges, and calibration, attach a Judge run during your eval pass and populate `outcome.judgeScores.perJudge[judgeName][dimension] = score`. See `docs/insight-report.md` for the expected shape.',\n evidencePath: 'judges',\n })\n }\n\n if (ctx.lift) {\n const pairedEffect =\n ctx.lift.cohensD === null ? 'undefined (zero delta variance)' : ctx.lift.cohensD.toFixed(2)\n const requiredRuns =\n ctx.lift.requiredN === null ? 'not estimable' : `~${ctx.lift.requiredN} paired runs`\n const decisive = ctx.lift.ci95[0] > ctx.threshold\n const inconclusive = ctx.lift.ci95[0] <= ctx.threshold && ctx.lift.ci95[1] > ctx.threshold\n if (decisive) {\n out.push({\n priority: 'critical',\n kind: 'ship',\n title: `Ship — lift ${ctx.lift.delta.toFixed(3)} (95% CI ${ctx.lift.ci95[0].toFixed(3)}..${ctx.lift.ci95[1].toFixed(3)})`,\n detail: `Holdout lift exceeds threshold ${ctx.threshold} with 95% bootstrap confidence (n=${ctx.lift.n}, p=${ctx.lift.pValue.toFixed(4)}, paired d=${pairedEffect}).`,\n evidencePath: 'lift',\n })\n } else if (inconclusive) {\n out.push({\n priority: 'high',\n kind: 'expand-corpus',\n title: `Inconclusive — required sample is ${requiredRuns} (have ${ctx.lift.n}) at current effect size`,\n detail: `CI straddles threshold. Current MDE at 80% power is ${ctx.lift.mde.toFixed(3)}; observed delta is ${ctx.lift.delta.toFixed(3)}.`,\n evidencePath: 'lift',\n })\n } else {\n out.push({\n priority: 'critical',\n kind: 'hold',\n title: `Hold — lift CI lower bound ${ctx.lift.ci95[0].toFixed(3)} is at or below threshold ${ctx.threshold}`,\n detail: `Bootstrap CI provides no statistical evidence the candidate is better. Consider tightening the mutation or expanding the holdout.`,\n evidencePath: 'lift',\n })\n }\n }\n\n if (ctx.contamination && ctx.contamination.leaks > 0) {\n out.push({\n priority: 'critical',\n kind: 'fix',\n title: `${ctx.contamination.leaks} canary leak${ctx.contamination.leaks === 1 ? '' : 's'} detected`,\n detail: `Holdout integrity is compromised. The lift number is unreliable until you investigate.`,\n evidencePath: 'contamination',\n })\n }\n\n if (ctx.interRater && ctx.interRater.kappa < 0.5) {\n out.push({\n priority: 'high',\n kind: 'recalibrate',\n title: `Inter-rater weighted kappa ${ctx.interRater.kappa.toFixed(2)} is below 0.5`,\n detail:\n 'Raters disagree on what good looks like. Review the largest disagreement cases and refine the rubric before automating these decisions.',\n evidencePath: 'interRater',\n })\n }\n\n if (ctx.failureClusters && ctx.failureClusters.clusters.length > 0) {\n const top = ctx.failureClusters.clusters[0]!\n out.push({\n priority: 'high',\n kind: 'investigate',\n title: `Top failure cluster: ${top.name} (${(top.share * 100).toFixed(0)}% of failures)`,\n detail: `${ctx.failureClusters.totalFailures} runs failed. The largest cluster groups ${top.exemplars.length} exemplars under '${top.name}'.`,\n evidencePath: 'failureClusters.clusters[0]',\n })\n }\n\n if (ctx.outcomeCorrelation && Math.abs(ctx.outcomeCorrelation.spearman) < 0.3) {\n out.push({\n priority: 'medium',\n kind: 'recalibrate',\n title: `Judge scores decoupled from ${ctx.outcomeCorrelation.metric} (Spearman ρ=${ctx.outcomeCorrelation.spearman.toFixed(2)})`,\n detail: `Your judges score what they were trained to score, but it isn't predicting downstream ${ctx.outcomeCorrelation.metric}. Consider retraining the judge against ${ctx.outcomeCorrelation.metric} as the gold signal.`,\n evidencePath: 'outcomeCorrelation',\n })\n }\n\n return out\n}\n\n// ── Re-export pareto figure spec for hosted-side rendering ─────────\n\nexport type { ParetoFigureSpec }\n"],"mappings":";;;;;;;AA4BA,SAAgB,cAAc,QAAgB,WAA4C;CACxF,MAAM,QAAsB,CAAC;CAC7B,KAAK,MAAM,KAAK,WAAW;EACzB,IAAI,CAAC,EAAE,QAAQ;EACf,IAAI,OAAO,SAAS,EAAE,MAAM,GAC1B,MAAM,KAAK;GAAE,YAAY,EAAE;GAAI,QAAQ,EAAE;GAAQ,UAAU,QAAQ,QAAQ,EAAE,MAAM;EAAE,CAAC;CAE1F;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,sBACd,QACA,UACmB;CACnB,MAAM,UAAU,SAAS,oBAAoB,SAAS;CACtD,IAAI,CAAC,SAAS,OAAO;CACrB,MAAM,MAAM,eAAe,QAAQ,OAAO;CAC1C,IAAI,CAAC,KAAK,OAAO;CACjB,OAAO;EACL,YAAY,SAAS;EACrB,QAAQ;EACR,UAAU,QAAQ,QAAQ,GAAG;CAC/B;AACF;;;;;;;;;;AAWA,SAAgB,sBACd,OACc;CACd,MAAM,QAAsB,CAAC;CAC7B,KAAK,MAAM,KAAK,OAAO;EACrB,MAAM,OAAO,sBAAsB,EAAE,QAAQ,EAAE,QAAQ;EACvD,IAAI,MAAM,MAAM,KAAK;GAAE,GAAG;GAAM,OAAO,EAAE,SAAS,KAAK;EAAM,CAAC;CAChE;CACA,OAAO;AACT;;;;;;AAOA,SAAS,eAAe,QAAgB,SAAgC;CACtE,MAAM,KAAK,cAAc,OAAO;CAChC,IAAI,IAAI;EACN,MAAM,IAAI,OAAO,MAAM,EAAE;EACzB,OAAO,KAAK,EAAE,EAAE,CAAC,SAAS,IAAI,EAAE,KAAK;CACvC;CACA,OAAO,OAAO,SAAS,OAAO,IAAI,UAAU;AAC9C;AAEA,SAAS,cAAc,SAAgC;CACr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sB,KAAK,IAAI,IAAI,mBAAmB,QAAQ,IAAI,IACxE,IAAI,KAAK;EACP,UAAU;EACV,MAAM;EACN,OAAO,+BAA+B,IAAI,mBAAmB,OAAO,eAAe,IAAI,mBAAmB,SAAS,QAAQ,CAAC,EAAE;EAC9H,QAAQ,yFAAyF,IAAI,mBAAmB,OAAO,0CAA0C,IAAI,mBAAmB,OAAO;EACvM,cAAc;CAChB,CAAC;CAGH,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"baseline-DcX5hQDv.js","names":[],"sources":["../src/failure-taxonomy.ts","../src/tool-use-metrics.ts","../src/baseline.ts"],"sourcesContent":["/**\n * Failure taxonomy — canonical classes + a default classifier.\n *\n * Every failed run should end up in a named class. The classifier here\n * is rule-based (fast, deterministic); an LLM fallback can be added by\n * the consumer for novel cases and trained into the rule base over time.\n *\n * Consumers call `classifyFailure(run, spans, events)` and persist the\n * returned class as `Run.outcome.failureClass`.\n */\n\nimport type { FailureClass, Run, Span, TraceEvent } from './trace/schema'\nimport { FAILURE_CLASSES } from './trace/schema'\n\nexport { FAILURE_CLASSES, type FailureClass }\n\nexport interface FailureContext {\n run: Run\n spans: Span[]\n events: TraceEvent[]\n}\n\nexport interface FailureClassification {\n failureClass: FailureClass\n reason: string\n triggerSpanId?: string\n triggerEventId?: string\n}\n\n/** Ordered rules — first match wins. */\nexport interface FailureRule {\n id: string\n match: (ctx: FailureContext) => {\n failureClass: FailureClass\n reason: string\n triggerSpanId?: string\n triggerEventId?: string\n } | null\n}\n\nexport const DEFAULT_RULES: FailureRule[] = [\n // Outcome already named? Respect it.\n {\n id: 'explicit-outcome',\n match: ({ run }) => {\n const fc = run.outcome?.failureClass\n if (fc && fc !== 'unknown')\n return { failureClass: fc, reason: 'outcome.failureClass set explicitly' }\n return null\n },\n },\n {\n id: 'knowledge-readiness-blocked',\n match: ({ events }) => {\n const event = events.find(\n (e) =>\n e.kind === 'custom' &&\n e.payload.kind === 'readiness_scored' &&\n e.payload.passed === false,\n )\n return event\n ? {\n failureClass: 'knowledge_readiness_blocked',\n reason: 'knowledge readiness report blocked execution',\n triggerEventId: event.eventId,\n }\n : null\n },\n },\n {\n id: 'bad-integration-manifest',\n match: ({ events }) => {\n const event = events.find(\n (e) =>\n e.kind === 'custom' &&\n ((e.payload.kind === 'integration_manifest_validated' && e.payload.valid === false) ||\n (e.payload.kind === 'integration_invoke_failed' &&\n e.payload.code === 'manifest_invalid')),\n )\n return event\n ? {\n failureClass: 'bad_integration_manifest',\n reason: 'integration manifest validation failed before launch',\n triggerEventId: event.eventId,\n }\n : null\n },\n },\n {\n id: 'missing-integration-connection',\n match: ({ events }) => {\n const event = events.find(\n (e) =>\n e.kind === 'custom' &&\n e.payload.kind === 'integration_manifest_resolved' &&\n hasResolutionStatus(e.payload, 'missing_connection'),\n )\n return event\n ? {\n failureClass: 'missing_integration_connection',\n reason: 'required integration connection was missing',\n triggerEventId: event.eventId,\n }\n : null\n },\n },\n {\n id: 'missing-integration-scope',\n match: ({ events }) => {\n const event = events.find(\n (e) =>\n e.kind === 'custom' &&\n ((e.payload.kind === 'integration_manifest_resolved' && hasMissingScopes(e.payload)) ||\n (e.payload.kind === 'integration_invoke_failed' && e.payload.code === 'scope_denied')),\n )\n return event\n ? {\n failureClass: 'missing_integration_scope',\n reason: 'integration grant or connection lacks required scopes',\n triggerEventId: event.eventId,\n }\n : null\n },\n },\n {\n id: 'integration-approval-required',\n match: ({ events }) => {\n const event = events.find(\n (e) =>\n e.kind === 'custom' &&\n ((e.payload.kind === 'integration_invoke' && e.payload.status === 'approval_required') ||\n (e.payload.kind === 'integration_invoke_failed' &&\n e.payload.code === 'approval_required') ||\n e.payload.kind === 'integration_approval_required'),\n )\n return event\n ? {\n failureClass: 'integration_approval_required',\n reason: 'integration write paused for user approval',\n triggerEventId: event.eventId,\n }\n : null\n },\n },\n {\n id: 'integration-auth-expired',\n match: ({ events }) => {\n const event = events.find(\n (e) =>\n e.kind === 'custom' &&\n e.payload.kind === 'integration_invoke_failed' &&\n (e.payload.code === 'auth_expired' ||\n e.payload.code === 'connection_not_active' ||\n e.payload.code === 'capability_expired' ||\n e.payload.status === 'expired'),\n )\n return event\n ? {\n failureClass: 'integration_auth_expired',\n reason: 'integration connection or capability expired',\n triggerEventId: event.eventId,\n }\n : null\n },\n },\n {\n id: 'unsafe-integration-write-denied',\n match: ({ events }) => {\n const event = events.find(\n (e) =>\n e.kind === 'custom' &&\n e.payload.kind === 'integration_invoke_failed' &&\n (e.payload.code === 'unsafe_write_denied' ||\n e.payload.code === 'policy_denied' ||\n e.payload.code === 'action_denied'),\n )\n return event\n ? {\n failureClass: 'unsafe_integration_write_denied',\n reason: 'integration write was denied by policy or capability scope',\n triggerEventId: event.eventId,\n }\n : null\n },\n },\n {\n id: 'integration-provider-failure',\n match: ({ events }) => {\n const event = events.find(\n (e) =>\n e.kind === 'custom' &&\n e.payload.kind === 'integration_invoke_failed' &&\n ![\n 'scope_denied',\n 'approval_required',\n 'auth_expired',\n 'connection_not_active',\n 'capability_expired',\n 'unsafe_write_denied',\n 'policy_denied',\n 'action_denied',\n 'manifest_invalid',\n ].includes(String(e.payload.code)),\n )\n return event\n ? {\n failureClass: 'integration_provider_failure',\n reason: 'integration provider invocation failed',\n triggerEventId: event.eventId,\n }\n : null\n },\n },\n {\n id: 'missing-credentials',\n match: ({ events }) => {\n const event = events.find(\n (e) =>\n e.kind === 'custom' &&\n e.payload.kind === 'knowledge_gap' &&\n e.payload.category === 'credential_or_secret',\n )\n return event\n ? {\n failureClass: 'missing_credentials',\n reason: 'required credential or secret was missing',\n triggerEventId: event.eventId,\n }\n : null\n },\n },\n {\n id: 'bad-retrieval',\n match: ({ run, spans }) => {\n if (run.outcome?.pass !== false) return null\n const retrieval = spans.find(\n (s) =>\n s.kind === 'retrieval' && (s.hits.length === 0 || s.hits.every((hit) => hit.score <= 0)),\n )\n return retrieval\n ? {\n failureClass: 'bad_retrieval',\n reason: 'retrieval returned no useful hits for a failed run',\n triggerSpanId: retrieval.spanId,\n }\n : null\n },\n },\n {\n id: 'insufficient-evidence',\n match: ({ events }) => {\n const event = events.find(\n (e) =>\n e.kind === 'custom' &&\n e.payload.kind === 'knowledge_gap' &&\n e.payload.reason === 'insufficient_evidence',\n )\n return event\n ? {\n failureClass: 'insufficient_evidence',\n reason: 'task proceeded with insufficient supporting evidence',\n triggerEventId: event.eventId,\n }\n : null\n },\n },\n {\n id: 'contradictory-evidence',\n match: ({ events }) => {\n const event = events.find(\n (e) =>\n e.kind === 'custom' &&\n e.payload.kind === 'knowledge_gap' &&\n e.payload.reason === 'contradictory_evidence',\n )\n return event\n ? {\n failureClass: 'contradictory_evidence',\n reason: 'supporting evidence contradicted itself',\n triggerEventId: event.eventId,\n }\n : null\n },\n },\n // Budget breach events\n {\n id: 'budget-breach',\n match: ({ events }) => {\n const breach = events.find((e) => e.kind === 'budget_breach')\n return breach\n ? {\n failureClass: 'budget_exceeded',\n reason: `budget breached on ${breach.payload.dimension ?? 'unknown dimension'}`,\n triggerEventId: breach.eventId,\n }\n : null\n },\n },\n // Policy violations\n {\n id: 'policy-violation',\n match: ({ events }) => {\n const e = events.find((x) => x.kind === 'policy_violation')\n return e\n ? {\n failureClass: 'policy_violation',\n reason: 'policy_violation event emitted',\n triggerEventId: e.eventId,\n }\n : null\n },\n },\n // Sandbox non-zero exit code\n {\n id: 'sandbox-failure',\n match: ({ spans }) => {\n const s = spans.find(\n (x) => x.kind === 'sandbox' && typeof x.exitCode === 'number' && x.exitCode !== 0,\n )\n if (!s) return null\n return {\n failureClass: 'sandbox_failure',\n reason: `sandbox exited ${(s as Extract<Span, { kind: 'sandbox' }>).exitCode}`,\n triggerSpanId: s.spanId,\n }\n },\n },\n // Timeout: run aborted by external signal\n {\n id: 'timeout',\n match: ({ run, events }) => {\n if (run.status !== 'aborted') return null\n const hasTimeout = events.some(\n (e) =>\n e.kind === 'error' &&\n String(e.payload.reason ?? '')\n .toLowerCase()\n .includes('timeout'),\n )\n const note = (run.outcome?.notes ?? '').toLowerCase()\n if (hasTimeout || note.includes('timeout') || note.includes('deadline')) {\n return { failureClass: 'timeout', reason: 'timeout signal observed' }\n }\n return null\n },\n },\n // Tool recovery failure: many consecutive tool errors on the same tool\n {\n id: 'tool-recovery-failure',\n match: ({ spans }) => {\n const tools = spans.filter((s) => s.kind === 'tool')\n const byTool = new Map<string, Span[]>()\n for (const t of tools) {\n const name = (t as Extract<Span, { kind: 'tool' }>).toolName\n const arr = byTool.get(name) ?? []\n arr.push(t)\n byTool.set(name, arr)\n }\n for (const [name, arr] of byTool) {\n const errs = arr.filter((s) => s.status === 'error')\n if (errs.length >= 3 && errs.length === arr.length) {\n return {\n failureClass: 'tool_recovery_failure',\n reason: `${errs.length} consecutive errors on tool \"${name}\"`,\n triggerSpanId: errs[errs.length - 1]!.spanId,\n }\n }\n }\n return null\n },\n },\n // Tool selection error: the run failed and agent called zero tools despite having them\n {\n id: 'tool-selection-error',\n match: ({ run, spans }) => {\n if (run.outcome?.pass !== false) return null\n const hasToolsAvailable = spans.some(\n (s) =>\n s.kind === 'agent' &&\n (s.attributes?.toolsAvailable as number | undefined) !== undefined &&\n (s.attributes?.toolsAvailable as number) > 0,\n )\n const tools = spans.filter((s) => s.kind === 'tool')\n if (hasToolsAvailable && tools.length === 0) {\n return {\n failureClass: 'tool_selection_error',\n reason: 'tools were available but none were called',\n }\n }\n return null\n },\n },\n // Format drift: scored by a judge with dimension='format' below threshold\n {\n id: 'format-drift',\n match: ({ spans }) => {\n const judge = spans.find(\n (s) =>\n s.kind === 'judge' &&\n (s as Extract<Span, { kind: 'judge' }>).dimension === 'format' &&\n (s as Extract<Span, { kind: 'judge' }>).score < 0.5,\n )\n return judge\n ? {\n failureClass: 'format_drift',\n reason: 'format judge scored below 0.5',\n triggerSpanId: judge.spanId,\n }\n : null\n },\n },\n]\n\nfunction hasResolutionStatus(payload: Record<string, unknown>, status: string): boolean {\n if (status === 'missing_connection' && stringArray(payload.missingConnections).length > 0)\n return true\n return resolutionItems(payload).some((item) => item.status === status)\n}\n\nfunction hasMissingScopes(payload: Record<string, unknown>): boolean {\n if (stringArray(payload.missingScopes).length > 0) return true\n return resolutionItems(payload).some(\n (item) => Array.isArray(item.missingScopes) && item.missingScopes.length > 0,\n )\n}\n\nfunction resolutionItems(payload: Record<string, unknown>): Array<Record<string, unknown>> {\n return [\n ...records(payload.missing),\n ...records(payload.optionalMissing),\n ...records(payload.ready),\n ]\n}\n\nfunction records(value: unknown): Array<Record<string, unknown>> {\n if (!Array.isArray(value)) return []\n return value.filter(\n (item): item is Record<string, unknown> =>\n Boolean(item) && typeof item === 'object' && !Array.isArray(item),\n )\n}\n\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string')\n : []\n}\n\n/** Classify the failure mode of a run using an ordered rule list. */\nexport function classifyFailure(\n ctx: FailureContext,\n rules: FailureRule[] = DEFAULT_RULES,\n): FailureClassification {\n if (ctx.run.outcome?.pass !== false && ctx.run.status === 'completed') {\n return { failureClass: 'success', reason: 'run completed with pass=true (or no explicit fail)' }\n }\n for (const rule of rules) {\n const hit = rule.match(ctx)\n if (hit) return hit\n }\n return { failureClass: 'unknown', reason: 'no rule matched; run failed for unclassified reason' }\n}\n","/**\n * Tool-use metrics — derived purely from trace data.\n *\n * No scoring assumptions: consumers supply optional ground-truth tool\n * selections per turn + optional \"information used downstream\" signals.\n * Without those, we still compute descriptive metrics (error rate,\n * retry rate, duplicate-call rate) that are useful on their own.\n */\n\nimport { argHash, groupBy, hasCapturedToolArgs, toolSpans } from './trace/query'\nimport type { Span } from './trace/schema'\nimport type { TraceStore } from './trace/store'\n\nexport interface ToolUseMetrics {\n runId: string\n totalCalls: number\n /** Calls whose arguments were captured and can be compared for duplication. */\n callsWithCapturedArgs: number\n byTool: Record<string, ToolStats>\n errorRate: number\n /** Ratio of captured-argument calls already seen with the same tool name and arguments. */\n duplicateRate: number\n /** Ratio of error calls followed by ≥1 retry on same tool. */\n retryRate: number\n /** Optional: of the calls agent made, fraction the evaluator marked as \"correct selection\". */\n selectionAccuracy?: number\n}\n\nexport interface ToolStats {\n calls: number\n callsWithCapturedArgs: number\n errors: number\n avgLatencyMs: number\n duplicates: number\n}\n\nexport interface ToolUseOptions {\n /** Map of spanId → whether the evaluator judged the tool selection correct. Optional. */\n selectionLabels?: Record<string, boolean>\n}\n\nexport async function computeToolUseMetrics(\n store: TraceStore,\n runId: string,\n options: ToolUseOptions = {},\n): Promise<ToolUseMetrics> {\n const tools = await toolSpans(store, runId)\n if (tools.length === 0) {\n return {\n runId,\n totalCalls: 0,\n callsWithCapturedArgs: 0,\n byTool: {},\n errorRate: 0,\n duplicateRate: 0,\n retryRate: 0,\n }\n }\n\n const byTool: Record<string, ToolStats> = {}\n let totalErrors = 0\n let totalDuplicates = 0\n let callsWithCapturedArgs = 0\n const sortedTools = [...tools].sort((a, b) => a.startedAt - b.startedAt)\n const seenSignatures = new Set<string>()\n\n // duplicate detection + per-tool aggregation\n for (const t of sortedTools) {\n byTool[t.toolName] ??= {\n calls: 0,\n callsWithCapturedArgs: 0,\n errors: 0,\n avgLatencyMs: 0,\n duplicates: 0,\n }\n const stat = byTool[t.toolName]!\n stat.calls += 1\n if (t.status === 'error') {\n stat.errors += 1\n totalErrors += 1\n }\n if (typeof t.latencyMs === 'number') stat.avgLatencyMs += t.latencyMs\n if (hasCapturedToolArgs(t)) {\n callsWithCapturedArgs += 1\n stat.callsWithCapturedArgs += 1\n const sig = `${t.toolName}|${argHash(t.args)}`\n if (seenSignatures.has(sig)) {\n stat.duplicates += 1\n totalDuplicates += 1\n }\n seenSignatures.add(sig)\n }\n }\n\n for (const stat of Object.values(byTool)) {\n stat.avgLatencyMs = stat.calls > 0 ? stat.avgLatencyMs / stat.calls : 0\n }\n\n // retry detection: per-tool chronological adjacency where error → next same-tool call\n let retryOpportunities = 0\n let retriesFollowed = 0\n for (const [, arr] of groupBy(sortedTools, (t) => t.toolName)) {\n for (let i = 0; i < arr.length; i++) {\n if (arr[i]!.status !== 'error') continue\n retryOpportunities += 1\n if (arr[i + 1]) retriesFollowed += 1\n }\n }\n const retryRate = retryOpportunities > 0 ? retriesFollowed / retryOpportunities : 0\n\n let selectionAccuracy: number | undefined\n if (options.selectionLabels) {\n const labeled = sortedTools.filter((t) => t.spanId in options.selectionLabels!)\n if (labeled.length > 0) {\n selectionAccuracy =\n labeled.filter((t) => options.selectionLabels![t.spanId]).length / labeled.length\n }\n }\n\n return {\n runId,\n totalCalls: sortedTools.length,\n callsWithCapturedArgs,\n byTool,\n errorRate: totalErrors / sortedTools.length,\n duplicateRate: callsWithCapturedArgs > 0 ? totalDuplicates / callsWithCapturedArgs : 0,\n retryRate,\n selectionAccuracy,\n }\n}\n\nexport type { Span }\n","/**\n * Baseline regression detection.\n *\n * Lifted from ADC baseline.ts. Every promotion-blocking signal boils down\n * to: \"is this run measurably worse than baseline?\" — with enough\n * statistical rigor to distinguish noise from drift.\n *\n * Uses:\n * - Welch's t-test (unequal variance) for per-metric mean comparison\n * - Cohen's d for effect size magnitude\n * - IQR for stability flag (unstable samples can't be trusted for comparisons)\n *\n * Returns a structured verdict: improved | regressed | stable | unstable.\n */\n\nimport { studentTCdf } from './math/student-t'\nimport { cohensD } from './statistics'\n\nexport interface MetricSamples {\n /** Stable metric key (e.g. \"overallScore\", \"firstTokenMs\"). */\n metric: string\n /** Whether higher values are better. */\n higherIsBetter: boolean\n baseline: number[]\n candidate: number[]\n}\n\nexport interface MetricVerdict {\n metric: string\n baselineMean: number\n candidateMean: number\n delta: number\n cohensD: number\n welchT: number\n welchDf: number\n welchP: number\n stable: boolean\n /** IQR of the combined samples — used as a rough stability indicator. */\n iqr: number\n verdict: 'improved' | 'regressed' | 'stable' | 'unstable'\n}\n\nexport interface BaselineReport {\n metrics: MetricVerdict[]\n /** True if any critical metric regressed. */\n hasRegression: boolean\n /** True if any metric is unstable (too noisy to judge). */\n hasUnstable: boolean\n}\n\nexport interface BaselineOptions {\n /** Effect size threshold for meaningful delta (default 0.5 — medium effect). */\n effectThreshold?: number\n /** p-value threshold for statistical significance (default 0.05). */\n alpha?: number\n /** IQR/mean ratio above which samples are flagged unstable (default 0.30). */\n unstableCvThreshold?: number\n}\n\n/**\n * Compare candidate samples against baseline per metric. Verdict logic:\n * - unstable: IQR/|mean| > threshold on either set — not enough signal\n * - improved: meaningful effect in the \"better\" direction AND p < alpha\n * - regressed: meaningful effect in the \"worse\" direction AND p < alpha\n * - stable: otherwise (no significant change)\n */\nexport function compareToBaseline(\n samples: MetricSamples[],\n options: BaselineOptions = {},\n): BaselineReport {\n const effectThreshold = options.effectThreshold ?? 0.5\n const alpha = options.alpha ?? 0.05\n const cvThreshold = options.unstableCvThreshold ?? 0.3\n\n const metrics: MetricVerdict[] = samples.map((s) => {\n if (s.baseline.length < 2 || s.candidate.length < 2) {\n throw new Error(`compareToBaseline: need ≥2 samples per side for \"${s.metric}\"`)\n }\n const bMean = mean(s.baseline)\n const cMean = mean(s.candidate)\n const delta = cMean - bMean\n const d = cohensD(s.baseline, s.candidate) // positive = candidate higher\n const { t, df, p } = welchsTTest(s.baseline, s.candidate)\n // Stability is per-side: a comparison is trustworthy only when BOTH\n // samples are internally consistent. Combining the sides would flag\n // large-but-real deltas as \"unstable\" which is exactly what we want\n // to detect.\n const baselineIqr = iqr(s.baseline)\n const candidateIqr = iqr(s.candidate)\n const baselineStable = baselineIqr / Math.max(Math.abs(bMean), 1e-9) <= cvThreshold\n const candidateStable = candidateIqr / Math.max(Math.abs(cMean), 1e-9) <= cvThreshold\n const stable = baselineStable && candidateStable\n const reportedIqr = Math.max(baselineIqr, candidateIqr)\n\n let verdict: MetricVerdict['verdict']\n if (!stable) {\n verdict = 'unstable'\n } else if (p < alpha && Math.abs(d) >= effectThreshold) {\n const candidateIsBetter = s.higherIsBetter ? delta > 0 : delta < 0\n verdict = candidateIsBetter ? 'improved' : 'regressed'\n } else {\n verdict = 'stable'\n }\n\n return {\n metric: s.metric,\n baselineMean: bMean,\n candidateMean: cMean,\n delta,\n cohensD: d,\n welchT: t,\n welchDf: df,\n welchP: p,\n stable,\n iqr: reportedIqr,\n verdict,\n }\n })\n\n return {\n metrics,\n hasRegression: metrics.some((m) => m.verdict === 'regressed'),\n hasUnstable: metrics.some((m) => m.verdict === 'unstable'),\n }\n}\n\nfunction mean(xs: number[]): number {\n return xs.reduce((a, b) => a + b, 0) / xs.length\n}\n\n/** Inter-quartile range; 0 when the sample has no spread. */\nexport function iqr(xs: number[]): number {\n if (xs.length === 0) return 0\n const sorted = [...xs].sort((a, b) => a - b)\n const q = (p: number) => {\n const idx = p * (sorted.length - 1)\n const lo = Math.floor(idx)\n const hi = Math.ceil(idx)\n return sorted[lo]! + (sorted[hi]! - sorted[lo]!) * (idx - lo)\n }\n return q(0.75) - q(0.25)\n}\n\n/**\n * Welch's t-test — unequal-variance two-sample t. Uses the same Student-t\n * CDF as `pairedTTest` (via incomplete beta); falls back to normal tail\n * when df is large.\n */\nexport function welchsTTest(a: number[], b: number[]): { t: number; df: number; p: number } {\n if (a.length < 2 || b.length < 2) return { t: 0, df: 0, p: 1 }\n const mA = mean(a)\n const mB = mean(b)\n const vA = variance(a, mA)\n const vB = variance(b, mB)\n const seSquared = vA / a.length + vB / b.length\n if (seSquared === 0) return { t: mA === mB ? 0 : Infinity, df: 0, p: mA === mB ? 1 : 0 }\n const t = (mB - mA) / Math.sqrt(seSquared)\n const df =\n (seSquared * seSquared) /\n ((vA / a.length) ** 2 / (a.length - 1) + (vB / b.length) ** 2 / (b.length - 1))\n const p = 2 * (1 - studentTCdf(Math.abs(t), df))\n return { t, df, p }\n}\n\nfunction variance(xs: number[], m: number): number {\n return xs.reduce((acc, x) => acc + (x - m) ** 2, 0) / (xs.length - 1)\n}\n"],"mappings":";;;AAwCA,MAAa,gBAA+B;CAE1C;EACE,IAAI;EACJ,QAAQ,EAAE,UAAU;GAClB,MAAM,KAAK,IAAI,SAAS;GACxB,IAAI,MAAM,OAAO,WACf,OAAO;IAA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ACA;EACA;;UAGe;;EAEf,kBAAkB;;iBAGE,sBACpB,OAAO,YACP,eACA,UAAS,iBACR,QAAQ;;;UChCM;EACf;EACA,MAAM;;EAEN;;EAEA,QAAQ;;UAGO;EACf;EACA,OAAO;EACP;EACA;EACA;EACA;EACA;;iBAGoB,gBAAgB,OAAO,YAAY,gBAAgB,QAAQ;;;;;;;;;;;;;;;;;UCdhE;;EAEf;;EAEA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;EACA;;UAGe;EACf,SAAS;;EAET;;EAEA;;UAGe;;EAEf;;EAEA;;EAEA;;;;;;;;;iBAUc,kBACd,SAAS,iBACT,UAAS,kBACR;;iBA8Da,IAAI;;;;;;iBAiBJ,YAAY,aAAa;EAAgB;EAAW;EAAY"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"client-CYzbdJOZ.js","names":[],"sources":["../src/hosted/types.ts","../src/hosted/schemas.ts","../src/hosted/client.ts"],"sourcesContent":["/**\n * # Hosted-tier wire format — the schema that EVERY orchestrator (ours,\n * a partner's self-hosted one, a future open implementation) must accept.\n *\n * This package implements exactly one wire version. Servers reject every\n * other version instead of translating old payloads.\n *\n * The wire format is two event streams in one transport:\n *\n * 1. **Eval-run events** (`POST /v1/ingest/eval-runs`). Posted when a\n * campaign / improvement-loop completes (or per-generation if\n * streaming). Carries the structured result + per-cell scores +\n * surface diffs the orchestrator stores for the dashboard.\n *\n * 2. **Trace spans** (`POST /v1/ingest/traces`). Standard OTLP-shaped\n * spans with a few additional attributes so the orchestrator can\n * pivot from eval-run → underlying execution. Compatible with any\n * OTel collector.\n *\n * Both endpoints are authenticated with a bearer token + a tenant id\n * header. Tenants isolate everything downstream of ingest; no tenant\n * ever sees another tenant's data.\n */\n\nimport type { GateDecision, MutableSurface } from '../campaign/types'\nimport type { InsightReport } from '../contract/insight-report'\nimport type { RunTerminalOutcome } from '../run-record'\n\n// re-export so wire-format consumers can import the optional payload type\n// from `@tangle-network/agent-eval/hosted` without reaching into /contract.\nexport type { InsightReport } from '../contract/insight-report'\n\nexport const HOSTED_WIRE_VERSION = '2026-07-24.v1' as const\nexport type HostedWireVersion = typeof HOSTED_WIRE_VERSION\n\n// ── Transport headers ───────────────────────────────────────────────\n\n/** Every ingest request carries these. */\nexport interface HostedIngestHeaders {\n /** Bearer token. The orchestrator validates against the tenant key. */\n authorization: `Bearer ${string}`\n /** Stable tenant id (the orchestrator-side primary key for the tenant). */\n 'x-tangle-tenant-id': string\n /** Wire-version pin so the server can reject incompatible payloads. */\n 'x-tangle-wire-version': HostedWireVersion\n /** Stable request key generated once and reused across retries. */\n 'idempotency-key': string\n}\n\n// ── Eval-run event ──────────────────────────────────────────────────\n\n/** Lifecycle stages of an eval-run as the substrate reports them. */\nexport type EvalRunStatus =\n | 'started'\n | 'baseline-complete'\n | 'generation-complete'\n | 'gate-decided'\n | 'finished'\n | 'errored'\n\nexport interface EvalRunCellScore {\n /** Stable scenario id from the consumer's scenario set. */\n scenarioId: string\n /** Repetition index when reps > 1; 0 for the default. */\n rep: number\n /** Composite score across successful judges, or null when unscored. */\n compositeMean: number | null\n /** Per-judge and per-dimension scores; failed or missing judges are absent. */\n dimensions: Record<string, Record<string, number>>\n /** Root execution result, kept separate from task quality. */\n terminalOutcome: RunTerminalOutcome\n /** Canonical execution-error count, or null when the producer did not measure it. */\n executionErrorCount: number | null\n /** Per-cell dispatch or judge error. Missing on success. */\n errorMessage?: string\n}\n\nexport interface EvalRunGenerationSnapshot {\n /** Generation index. 0 is baseline. */\n index: number\n /** Candidate surface fingerprint (stable hash) — pivot key into the\n * trace stream to fetch the underlying execution. */\n surfaceHash: string\n /** The candidate surface itself. May be omitted to avoid PII when the\n * consumer prefers not to ship verbatim prompts. */\n surface?: MutableSurface\n /** Per-cell scores for this generation. */\n cells: EvalRunCellScore[]\n /** Mean across scored cells, or null when no cell has a task-quality label. */\n compositeMean: number | null\n /** Total $ spent across this generation. */\n costUsd: number\n /** Wall-clock duration of this generation. */\n durationMs: number\n}\n\n/**\n * The top-level eval-run event. One ingest call per logical eval-run;\n * generations stream in incrementally via repeated calls with the same\n * `runId`. The orchestrator deduplicates by `(runId, generation.index)`.\n */\nexport interface EvalRunEvent {\n /** Stable run id (the substrate's `runId`). UUID or substrate-generated. */\n runId: string\n /** Where this run was happening — derived from `RunCampaignOptions.runDir`. */\n runDir: string\n /** ISO-8601 timestamp the substrate recorded the event. */\n timestamp: string\n /** Lifecycle stage this event represents. */\n status: EvalRunStatus\n /** Free-form consumer tags (env, branch, model id, etc.). Searchable. */\n labels: Record<string, string>\n /** Baseline campaign snapshot. Present when status >= baseline-complete. */\n baseline?: EvalRunGenerationSnapshot\n /** Per-generation snapshots. Streams in; orchestrator appends. */\n generations: EvalRunGenerationSnapshot[]\n /** Final gate decision. Present when status >= gate-decided. */\n gateDecision?: GateDecision\n /** Held-out lift = winner-on-holdout - baseline-on-holdout. */\n holdoutLift?: number\n /** Total $ spent across baseline + every generation. */\n totalCostUsd: number\n /** Total wall-clock duration. */\n totalDurationMs: number\n /** Error message if status === 'errored'. */\n errorMessage?: string\n /** Rigor packet emitted alongside the run — distributional summary,\n * paired-bootstrap lift CI, judge stats, inter-rater agreement,\n * contamination check, failure clusters (when an analyst is wired),\n * outcome correlation (when downstream signal is supplied), and the\n * recommendations the dashboard surfaces verbatim. */\n insightReport?: InsightReport\n}\n\n// ── Trace span event ────────────────────────────────────────────────\n\n/**\n * Canonical unsigned 64-bit integer encoded as a base-10 string.\n * JSON numbers cannot represent OTLP nanosecond timestamps exactly.\n */\nexport type UnixNanoTimestamp = string\n\n/**\n * OTel-shape span with a few additional attributes for eval-run pivoting.\n * Compatible with any OTLP collector — `name`, `traceId`, `spanId`,\n * `startTimeUnixNano`, `endTimeUnixNano`, `attributes` are stock OTel.\n */\nexport interface TraceSpanEvent {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n startTimeUnixNano: UnixNanoTimestamp\n endTimeUnixNano: UnixNanoTimestamp\n attributes: Record<string, string | number | boolean>\n events?: Array<{\n timeUnixNano: UnixNanoTimestamp\n name: string\n attributes?: Record<string, string | number | boolean>\n }>\n status?: { code: 'OK' | 'ERROR' | 'UNSET'; message?: string }\n /** Pivot back into the eval-run stream. */\n 'tangle.runId'?: string\n /** Pivot to the specific generation. */\n 'tangle.generation'?: number\n /** Pivot to the specific cell. */\n 'tangle.cellId'?: string\n /** Pivot to the specific scenario. */\n 'tangle.scenarioId'?: string\n}\n\n// ── Ingest request bodies ───────────────────────────────────────────\n\nexport interface IngestEvalRunsRequest {\n wireVersion: HostedWireVersion\n events: EvalRunEvent[]\n}\n\nexport interface IngestTracesRequest {\n wireVersion: HostedWireVersion\n spans: TraceSpanEvent[]\n}\n\nexport interface IngestResponse {\n /** Accepted events / spans count. */\n accepted: number\n /** Rejected events with reasons (validation failures, dup idempotency key, etc.). */\n rejected: Array<{ index: number; reason: string }>\n}\n","import { z } from 'zod'\nimport type { MutableSurface } from '../campaign/types'\nimport type { InsightReport } from '../contract/insight-report'\nimport { FAILURE_CLASSES, type FailureClass } from '../trace/schema'\nimport type {\n EvalRunCellScore,\n EvalRunEvent,\n EvalRunGenerationSnapshot,\n IngestEvalRunsRequest,\n IngestResponse,\n IngestTracesRequest,\n TraceSpanEvent,\n UnixNanoTimestamp,\n} from './types'\nimport { HOSTED_WIRE_VERSION } from './types'\n\nconst finiteNumber = z.number().finite()\nconst nonNegativeNumber = finiteNumber.nonnegative()\nconst nonNegativeInteger = z.number().int().nonnegative()\nconst nonEmptyString = z\n .string()\n .min(1)\n .refine((value) => value.trim().length > 0, 'must not be blank')\nconst attributeValue = z.union([z.string(), finiteNumber, z.boolean()])\nconst attributes = z.record(z.string(), attributeValue)\nconst FailureClassSchema = z.custom<FailureClass>(\n (value) => typeof value === 'string' && FAILURE_CLASSES.includes(value as FailureClass),\n `expected one of ${FAILURE_CLASSES.join(', ')}`,\n)\nconst UINT64_MAX = 18_446_744_073_709_551_615n\n\nexport const UnixNanoTimestampSchema: z.ZodType<UnixNanoTimestamp> = z\n .string()\n .regex(/^(0|[1-9][0-9]*)$/, 'expected an unsigned base-10 integer string')\n .refine((value) => BigInt(value) <= UINT64_MAX, 'must fit in an unsigned 64-bit integer')\n\nconst GainDistributionBinSchema = z\n .object({\n lo: finiteNumber,\n hi: finiteNumber,\n count: nonNegativeInteger,\n })\n .strict()\n\nconst ScalarDistributionSchema = z\n .object({\n n: nonNegativeInteger,\n mean: finiteNumber.nullable(),\n p50: finiteNumber.nullable(),\n p95: finiteNumber.nullable(),\n stddev: nonNegativeNumber.nullable(),\n min: finiteNumber.nullable(),\n max: finiteNumber.nullable(),\n histogram: z.array(GainDistributionBinSchema),\n tailRuns: z\n .array(\n z\n .object({\n runId: nonEmptyString,\n score: finiteNumber,\n })\n .strict(),\n )\n .optional(),\n })\n .strict()\n .superRefine((distribution, ctx) => {\n const values = [\n distribution.mean,\n distribution.p50,\n distribution.p95,\n distribution.stddev,\n distribution.min,\n distribution.max,\n ]\n if (distribution.n === 0 && values.some((value) => value !== null)) {\n ctx.addIssue({\n code: 'custom',\n message: 'distribution values must be null when n is 0',\n })\n }\n if (distribution.n > 0 && values.some((value) => value === null)) {\n ctx.addIssue({\n code: 'custom',\n message: 'distribution values must be numbers when n is greater than 0',\n })\n }\n if (\n distribution.min !== null &&\n distribution.max !== null &&\n distribution.min > distribution.max\n ) {\n ctx.addIssue({ code: 'custom', path: ['min'], message: 'min must not exceed max' })\n }\n })\n\nconst TokenUsageInsightSchema = z\n .object({\n input: ScalarDistributionSchema,\n output: ScalarDistributionSchema,\n reasoning: ScalarDistributionSchema,\n cached: ScalarDistributionSchema,\n cacheWrite: ScalarDistributionSchema,\n totals: z\n .object({\n input: nonNegativeNumber,\n output: nonNegativeNumber,\n reasoning: nonNegativeNumber,\n cached: nonNegativeNumber,\n cacheWrite: nonNegativeNumber,\n })\n .strict(),\n })\n .strict()\n\nconst ExecutionErrorOutcomeCellSchema = z\n .object({\n withErrors: nonNegativeInteger,\n withoutErrors: nonNegativeInteger,\n unreported: nonNegativeInteger,\n })\n .strict()\n\nconst ExecutionInsightSchema = z\n .object({\n durationMs: ScalarDistributionSchema,\n queueMs: ScalarDistributionSchema,\n tokenUsage: TokenUsageInsightSchema,\n aggregateUsage: z\n .object({\n runs: nonNegativeInteger,\n tokenUsage: TokenUsageInsightSchema,\n costUsd: ScalarDistributionSchema,\n totalCostUsd: nonNegativeNumber,\n })\n .strict(),\n models: z.array(\n z\n .object({\n model: nonEmptyString,\n runs: nonNegativeInteger,\n })\n .strict(),\n ),\n modelCalls: z\n .object({\n runs: nonNegativeInteger,\n events: nonNegativeInteger,\n reportingRuns: nonNegativeInteger,\n })\n .strict(),\n executionErrors: z\n .object({\n runs: nonNegativeInteger,\n fraction: finiteNumber.min(0).max(1).nullable(),\n events: nonNegativeInteger,\n reportingRuns: nonNegativeInteger,\n errorSpanEvents: nonNegativeInteger,\n errorSpanReportingRuns: nonNegativeInteger,\n byTerminalOutcome: z\n .object({\n succeeded: ExecutionErrorOutcomeCellSchema,\n failed: ExecutionErrorOutcomeCellSchema,\n cancelled: ExecutionErrorOutcomeCellSchema,\n incomplete: ExecutionErrorOutcomeCellSchema,\n unknown: ExecutionErrorOutcomeCellSchema,\n })\n .strict(),\n })\n .strict(),\n terminalOutcomes: z\n .object({\n succeeded: nonNegativeInteger,\n failed: nonNegativeInteger,\n cancelled: nonNegativeInteger,\n incomplete: nonNegativeInteger,\n unknown: nonNegativeInteger,\n })\n .strict(),\n })\n .strict()\n\nconst CostProvenanceSummarySchema = z\n .object({\n observed: z\n .object({\n n: nonNegativeInteger,\n totalUsd: nonNegativeNumber,\n })\n .strict(),\n estimated: z\n .object({\n n: nonNegativeInteger,\n totalUsd: nonNegativeNumber,\n })\n .strict(),\n uncaptured: z.object({ n: nonNegativeInteger }).strict(),\n knownFraction: finiteNumber.min(0).max(1),\n })\n .strict()\n\nconst ParetoFigureSpecSchema = z\n .object({\n kind: z.literal('pareto-cost-quality'),\n split: z.enum(['search', 'holdout']),\n points: z.array(\n z\n .object({\n candidateId: nonEmptyString,\n cost: nonNegativeNumber,\n quality: finiteNumber,\n n: nonNegativeInteger,\n onFrontier: z.boolean(),\n gate: z.enum(['promote', 'reject']).optional(),\n })\n .strict(),\n ),\n axes: z.object({ x: z.literal('costUsd'), y: z.literal('score') }).strict(),\n })\n .strict()\n\nconst ContinuousAgreementSchema = z\n .object({\n weightedKappa: finiteNumber,\n icc: finiteNumber,\n pearson: finiteNumber,\n spearman: finiteNumber,\n ci: z\n .object({\n icc: z.tuple([finiteNumber, finiteNumber]),\n weightedKappa: z.tuple([finiteNumber, finiteNumber]),\n })\n .strict(),\n n: nonNegativeInteger,\n raters: nonNegativeInteger,\n })\n .strict()\n\nconst JudgeInsightSchema = z\n .object({\n n: nonNegativeInteger,\n meanScore: finiteNumber,\n calibration: ContinuousAgreementSchema.optional(),\n positionalBias: finiteNumber.optional(),\n selfPreference: finiteNumber.optional(),\n verbosityBias: finiteNumber.optional(),\n })\n .strict()\n\nconst InterRaterInsightSchema = z\n .object({\n raters: nonNegativeInteger,\n jointlyRated: nonNegativeInteger,\n kappa: finiteNumber,\n icc: finiteNumber,\n pearson: finiteNumber,\n spearman: finiteNumber,\n perPair: z.record(z.string(), finiteNumber),\n disagreementCases: z.array(\n z\n .object({\n runId: nonEmptyString,\n ratings: z.array(\n z\n .object({\n rater: nonEmptyString,\n score: finiteNumber,\n })\n .strict(),\n ),\n range: nonNegativeNumber,\n })\n .strict(),\n ),\n })\n .strict()\n\nconst LiftInsightSchema = z\n .object({\n baselineMean: finiteNumber,\n candidateMean: finiteNumber,\n delta: finiteNumber,\n ci95: z.tuple([finiteNumber, finiteNumber]),\n pValue: finiteNumber.min(0).max(1),\n n: nonNegativeInteger,\n unpairedBaseline: nonNegativeInteger,\n unpairedCandidate: nonNegativeInteger,\n cohensD: finiteNumber.nullable(),\n mde: nonNegativeNumber,\n requiredN: nonNegativeInteger.nullable(),\n })\n .strict()\n\nconst FailureClusterInsightSchema = z\n .object({\n clusters: z.array(\n z\n .object({\n id: nonEmptyString,\n name: nonEmptyString,\n share: finiteNumber.min(0).max(1),\n exemplars: z.array(nonEmptyString).max(5),\n suggestedFix: nonEmptyString.optional(),\n })\n .strict(),\n ),\n totalFailures: nonNegativeInteger,\n })\n .strict()\n\nconst ContaminationInsightSchema = z\n .object({\n leaks: nonNegativeInteger,\n holdoutAuditPassed: z.boolean(),\n details: z\n .array(\n z\n .object({\n runId: nonEmptyString,\n canary: nonEmptyString,\n matched: nonEmptyString,\n })\n .strict(),\n )\n .optional(),\n })\n .strict()\n\nconst OutcomeCorrelationInsightSchema = z\n .object({\n metric: nonEmptyString,\n n: nonNegativeInteger,\n pearson: finiteNumber,\n spearman: finiteNumber,\n rewardModel: z\n .object({\n intercept: finiteNumber,\n slope: finiteNumber,\n r2: finiteNumber,\n })\n .strict()\n .optional(),\n })\n .strict()\n\nconst ReleaseSummarySchema = z\n .object({\n status: z.enum(['pass', 'warn', 'fail']),\n axes: z.array(\n z\n .object({\n name: z.enum(['quality-lift', 'contamination', 'composite-distribution']),\n status: z.enum(['pass', 'warn', 'fail', 'not_evaluated']),\n detail: nonEmptyString,\n })\n .strict(),\n ),\n issues: z.array(z.string()),\n })\n .strict()\n\nconst MetricDeltaSchema = z\n .object({\n current: finiteNumber,\n baseline: finiteNumber,\n delta: finiteNumber,\n ci95: z.tuple([finiteNumber, finiteNumber]),\n pValue: finiteNumber.min(0).max(1),\n cohensD: finiteNumber,\n baselineN: nonNegativeInteger,\n currentN: nonNegativeInteger,\n significant: z.boolean(),\n })\n .strict()\n\nconst PriorPeriodComparisonSchema = z\n .object({\n baselineN: nonNegativeInteger,\n currentN: nonNegativeInteger,\n windowLabel: nonEmptyString.optional(),\n metrics: z.record(z.string(), MetricDeltaSchema),\n regressedMetrics: z.array(nonEmptyString),\n improvedMetrics: z.array(nonEmptyString),\n })\n .strict()\n\nconst RecommendationSchema = z\n .object({\n priority: z.enum(['critical', 'high', 'medium', 'low']),\n kind: z.enum(['ship', 'hold', 'investigate', 'fix', 'recalibrate', 'expand-corpus']),\n title: nonEmptyString,\n detail: nonEmptyString,\n evidencePath: nonEmptyString.optional(),\n })\n .strict()\n\nexport const InsightReportSchema: z.ZodType<InsightReport> = z\n .object({\n n: nonNegativeInteger,\n execution: ExecutionInsightSchema,\n composite: ScalarDistributionSchema,\n perDimension: z.record(z.string(), ScalarDistributionSchema),\n costQuality: z\n .object({\n cost: ScalarDistributionSchema,\n pareto: ParetoFigureSpecSchema,\n provenance: CostProvenanceSummarySchema.optional(),\n degraded: z\n .object({\n cost: nonEmptyString.optional(),\n pareto: nonEmptyString.optional(),\n })\n .strict()\n .optional(),\n })\n .strict(),\n judges: z.record(z.string(), JudgeInsightSchema),\n interRater: InterRaterInsightSchema.optional(),\n lift: LiftInsightSchema.optional(),\n failureClusters: FailureClusterInsightSchema.optional(),\n contamination: ContaminationInsightSchema.optional(),\n outcomeCorrelation: OutcomeCorrelationInsightSchema.optional(),\n release: ReleaseSummarySchema,\n priorPeriodComparison: PriorPeriodComparisonSchema.optional(),\n failureClasses: z\n .array(\n z\n .object({\n failureClass: FailureClassSchema,\n count: nonNegativeInteger,\n share: finiteNumber.min(0).max(1),\n })\n .strict(),\n )\n .optional(),\n recommendations: z.array(RecommendationSchema),\n })\n .strict()\n\nconst sha256Digest = z.custom<`sha256:${string}`>(\n (value) => typeof value === 'string' && /^sha256:[0-9a-f]{64}$/.test(value),\n 'expected sha256:<64 lowercase hex characters>',\n)\n\nexport const MutableSurfaceSchema: z.ZodType<MutableSurface> = z.union([\n z.string(),\n z\n .object({\n kind: z.literal('components'),\n components: z.record(z.string(), z.string()),\n })\n .strict(),\n z\n .object({\n kind: z.literal('code'),\n worktreeRef: nonEmptyString,\n baseRef: nonEmptyString,\n baseCommit: nonEmptyString,\n baseTree: nonEmptyString,\n candidateCommit: nonEmptyString,\n candidateTree: nonEmptyString,\n patch: z\n .object({\n format: z.literal('git-diff-binary'),\n sha256: sha256Digest,\n byteLength: nonNegativeInteger,\n })\n .strict(),\n summary: z.string().optional(),\n })\n .strict(),\n])\n\nexport const RunTerminalOutcomeSchema = z.enum([\n 'succeeded',\n 'failed',\n 'cancelled',\n 'incomplete',\n 'unknown',\n])\n\nexport const EvalRunCellScoreSchema: z.ZodType<EvalRunCellScore> = z\n .object({\n scenarioId: nonEmptyString,\n rep: nonNegativeInteger,\n compositeMean: finiteNumber.nullable(),\n dimensions: z.record(z.string(), z.record(z.string(), finiteNumber)),\n terminalOutcome: RunTerminalOutcomeSchema,\n executionErrorCount: nonNegativeInteger.nullable(),\n errorMessage: z.string().optional(),\n })\n .strict()\n\nexport const EvalRunGenerationSnapshotSchema: z.ZodType<EvalRunGenerationSnapshot> = z\n .object({\n index: nonNegativeInteger,\n surfaceHash: nonEmptyString,\n surface: MutableSurfaceSchema.optional(),\n cells: z.array(EvalRunCellScoreSchema),\n compositeMean: finiteNumber.nullable(),\n costUsd: nonNegativeNumber,\n durationMs: nonNegativeNumber,\n })\n .strict()\n\nconst EvalRunStatusSchema = z.enum([\n 'started',\n 'baseline-complete',\n 'generation-complete',\n 'gate-decided',\n 'finished',\n 'errored',\n])\n\nconst GateDecisionSchema = z.enum([\n 'ship',\n 'hold',\n 'need_more_work',\n 'model_ceiling',\n 'arch_ceiling',\n])\n\nexport const EvalRunEventSchema: z.ZodType<EvalRunEvent> = z\n .object({\n runId: nonEmptyString,\n runDir: nonEmptyString,\n timestamp: z.string().datetime({ offset: true }),\n status: EvalRunStatusSchema,\n labels: z.record(z.string(), z.string()),\n baseline: EvalRunGenerationSnapshotSchema.optional(),\n generations: z.array(EvalRunGenerationSnapshotSchema),\n gateDecision: GateDecisionSchema.optional(),\n holdoutLift: finiteNumber.optional(),\n totalCostUsd: nonNegativeNumber,\n totalDurationMs: nonNegativeNumber,\n errorMessage: z.string().optional(),\n insightReport: InsightReportSchema.optional(),\n })\n .strict()\n .superRefine((event, ctx) => {\n if (event.baseline && event.baseline.index !== 0) {\n ctx.addIssue({\n code: 'custom',\n path: ['baseline', 'index'],\n message: 'baseline index must be 0',\n })\n }\n\n const seen = new Set<number>()\n for (let i = 0; i < event.generations.length; i++) {\n const index = event.generations[i]!.index\n if (seen.has(index)) {\n ctx.addIssue({\n code: 'custom',\n path: ['generations', i, 'index'],\n message: `duplicate generation index ${index}`,\n })\n }\n seen.add(index)\n }\n\n if (event.status === 'errored' && !event.errorMessage?.trim()) {\n ctx.addIssue({\n code: 'custom',\n path: ['errorMessage'],\n message: 'errorMessage is required when status is errored',\n })\n }\n })\n\nconst TraceSpanEventEntrySchema = z\n .object({\n timeUnixNano: UnixNanoTimestampSchema,\n name: nonEmptyString,\n attributes: attributes.optional(),\n })\n .strict()\n\nexport const TraceSpanEventSchema: z.ZodType<TraceSpanEvent> = z\n .object({\n traceId: nonEmptyString,\n spanId: nonEmptyString,\n parentSpanId: nonEmptyString.optional(),\n name: nonEmptyString,\n startTimeUnixNano: UnixNanoTimestampSchema,\n endTimeUnixNano: UnixNanoTimestampSchema,\n attributes,\n events: z.array(TraceSpanEventEntrySchema).optional(),\n status: z\n .object({\n code: z.enum(['OK', 'ERROR', 'UNSET']),\n message: z.string().optional(),\n })\n .strict()\n .optional(),\n 'tangle.runId': nonEmptyString.optional(),\n 'tangle.generation': nonNegativeInteger.optional(),\n 'tangle.cellId': nonEmptyString.optional(),\n 'tangle.scenarioId': nonEmptyString.optional(),\n })\n .strict()\n .refine((span) => BigInt(span.endTimeUnixNano) >= BigInt(span.startTimeUnixNano), {\n path: ['endTimeUnixNano'],\n message: 'endTimeUnixNano must be greater than or equal to startTimeUnixNano',\n })\n\nexport const IngestEvalRunsEnvelopeSchema = z\n .object({\n wireVersion: z.literal(HOSTED_WIRE_VERSION),\n events: z.array(z.unknown()),\n })\n .strict()\n\nexport const IngestTracesEnvelopeSchema = z\n .object({\n wireVersion: z.literal(HOSTED_WIRE_VERSION),\n spans: z.array(z.unknown()),\n })\n .strict()\n\nexport const IngestEvalRunsRequestSchema: z.ZodType<IngestEvalRunsRequest> = z\n .object({\n wireVersion: z.literal(HOSTED_WIRE_VERSION),\n events: z.array(EvalRunEventSchema),\n })\n .strict()\n\nexport const IngestTracesRequestSchema: z.ZodType<IngestTracesRequest> = z\n .object({\n wireVersion: z.literal(HOSTED_WIRE_VERSION),\n spans: z.array(TraceSpanEventSchema),\n })\n .strict()\n\nexport const IngestResponseSchema: z.ZodType<IngestResponse> = z\n .object({\n accepted: nonNegativeInteger,\n rejected: z.array(\n z\n .object({\n index: nonNegativeInteger,\n reason: nonEmptyString,\n })\n .strict(),\n ),\n })\n .strict()\n","/**\n * # Hosted-tier ingest client.\n *\n * Ships eval-run events + trace spans to any orchestrator (ours, a\n * partner's self-hosted one, or a future open implementation) that\n * speaks the wire format in `./types.ts`.\n *\n * Three modes:\n * - **Ours:** point at `https://orchestrator.tangle.tools` (the host root —\n * the client appends the versioned `/v1/ingest/...` path itself; a trailing\n * `/v1` on the endpoint is tolerated and normalized away). We handle ingest\n * + storage + dashboard.\n * - **Self-hosted:** point at whatever URL runs the reference receiver\n * from `examples/hosted-ingest-server/`.\n * - **Off (default):** when `hostedTenant` is unset, nothing is sent.\n * Everything stays local.\n */\n\nimport {\n IngestEvalRunsRequestSchema,\n IngestResponseSchema,\n IngestTracesRequestSchema,\n} from './schemas'\nimport {\n type EvalRunEvent,\n HOSTED_WIRE_VERSION,\n type HostedWireVersion,\n type IngestEvalRunsRequest,\n type IngestResponse,\n type IngestTracesRequest,\n type TraceSpanEvent,\n} from './types'\n\nexport interface HostedTenant {\n /** Orchestrator endpoint base URL (no trailing slash). Required. */\n endpoint: string\n /** Bearer token issued by the orchestrator. Required. */\n apiKey: string\n /** Tenant id — the orchestrator's primary key for this consumer. Required. */\n tenantId: string\n /** Optional `fetch` override (auth wrappers, custom agent, test mocks). */\n fetchImpl?: typeof fetch\n /** Per-call timeout in ms. Default 30s. */\n timeoutMs?: number\n /** Retries on 5xx / network errors. Default 2. */\n retries?: number\n}\n\nexport interface HostedClient {\n ingestEvalRun(event: EvalRunEvent, idempotencyKey?: string): Promise<IngestResponse>\n ingestEvalRuns(events: EvalRunEvent[], idempotencyKey?: string): Promise<IngestResponse>\n ingestTraces(spans: TraceSpanEvent[], idempotencyKey?: string): Promise<IngestResponse>\n readonly tenant: HostedTenant\n readonly wireVersion: HostedWireVersion\n}\n\ninterface RequestOptions {\n idempotencyKey?: string\n signal?: AbortSignal\n}\n\nconst MAX_IDEMPOTENCY_KEY_LENGTH = 256\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction normalizeHostedBase(endpoint: string): string {\n return endpoint.trim().replace(/\\/+$/, '').replace(/\\/v1$/, '')\n}\n\nfunction resolveIdempotencyKey(key: string | undefined): string {\n const resolved = key ?? globalThis.crypto.randomUUID()\n if (resolved.trim().length === 0) throw new Error('idempotency key must not be blank')\n if (resolved.length > MAX_IDEMPOTENCY_KEY_LENGTH) {\n throw new Error(`idempotency key must be at most ${MAX_IDEMPOTENCY_KEY_LENGTH} characters`)\n }\n return resolved\n}\n\nfunction responseValidationReason(error: {\n issues: Array<{ path: PropertyKey[]; message: string }>\n}) {\n return error.issues\n .map(\n (issue) =>\n `${issue.path.length > 0 ? issue.path.map(String).join('.') : 'value'}: ${issue.message}`,\n )\n .join('; ')\n}\n\nasync function post<TReq>(\n tenant: HostedTenant,\n path: string,\n body: TReq,\n opts: RequestOptions = {},\n): Promise<IngestResponse> {\n const timeoutMs = tenant.timeoutMs ?? 30_000\n const maxRetries = tenant.retries ?? 2\n const f: typeof fetch = tenant.fetchImpl ?? ((...args) => fetch(...args))\n const base = normalizeHostedBase(tenant.endpoint)\n const url = `${base}${path}`\n const idempotencyKey = resolveIdempotencyKey(opts.idempotencyKey)\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n authorization: `Bearer ${tenant.apiKey}`,\n 'x-tangle-tenant-id': tenant.tenantId,\n 'x-tangle-wire-version': HOSTED_WIRE_VERSION,\n 'idempotency-key': idempotencyKey,\n }\n\n let lastError: unknown\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const ourTimeout = AbortSignal.timeout(timeoutMs)\n const combinedSignal = opts.signal ? AbortSignal.any([opts.signal, ourTimeout]) : ourTimeout\n let res: Response\n try {\n res = await f(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal: combinedSignal,\n })\n } catch (err) {\n if (opts.signal?.aborted) throw err\n lastError = err\n if (attempt === maxRetries) throw err\n await sleep(2 ** attempt * 200 + Math.random() * 200)\n continue\n }\n\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n const error = new Error(`hosted ingest ${url} failed (${res.status}): ${text.slice(0, 500)}`)\n const retryable = res.status >= 500 || res.status === 408 || res.status === 429\n if (!retryable || attempt === maxRetries) throw error\n lastError = error\n await sleep(2 ** attempt * 200 + Math.random() * 200)\n continue\n }\n\n let rawResponse: unknown\n try {\n rawResponse = await res.json()\n } catch (error) {\n throw new Error(`hosted ingest ${url} returned invalid JSON`, { cause: error })\n }\n const parsed = IngestResponseSchema.safeParse(rawResponse)\n if (!parsed.success) {\n throw new Error(\n `hosted ingest ${url} returned an invalid response: ${responseValidationReason(parsed.error)}`,\n )\n }\n return parsed.data\n }\n throw lastError ?? new Error('hosted ingest exhausted retries')\n}\n\nexport function createHostedClient(tenant: HostedTenant): HostedClient {\n if (normalizeHostedBase(tenant.endpoint).length === 0) throw new Error('endpoint is required')\n if (tenant.apiKey.trim().length === 0) throw new Error('apiKey is required')\n if (tenant.tenantId.trim().length === 0) throw new Error('tenantId is required')\n if (\n tenant.timeoutMs !== undefined &&\n (!Number.isFinite(tenant.timeoutMs) || tenant.timeoutMs <= 0)\n ) {\n throw new Error('timeoutMs must be greater than 0')\n }\n if (tenant.retries !== undefined && (!Number.isInteger(tenant.retries) || tenant.retries < 0)) {\n throw new Error('retries must be a non-negative integer')\n }\n\n return {\n tenant,\n wireVersion: HOSTED_WIRE_VERSION,\n\n async ingestEvalRun(event, idempotencyKey) {\n return this.ingestEvalRuns([event], idempotencyKey)\n },\n\n async ingestEvalRuns(events, idempotencyKey) {\n const body: IngestEvalRunsRequest = IngestEvalRunsRequestSchema.parse({\n wireVersion: HOSTED_WIRE_VERSION,\n events,\n })\n return post<IngestEvalRunsRequest>(tenant, '/v1/ingest/eval-runs', body, {\n idempotencyKey,\n })\n },\n\n async ingestTraces(spans, idempotencyKey) {\n const body: IngestTracesRequest = IngestTracesRequestSchema.parse({\n wireVersion: HOSTED_WIRE_VERSION,\n spans,\n })\n return post<IngestTracesRequest>(tenant, '/v1/ingest/traces', body, {\n idempotencyKey,\n })\n },\n }\n}\n\n/**\n * Build a `HostedClient` from environment, or `undefined` when ingest is not\n * configured — the canonical, fail-soft wiring every product uses so eval-run +\n * trace provenance lands in the Intelligence dashboard with ONE call:\n *\n * const hosted = hostedClientFromEnv()\n * // ...run the loop...\n * await emitLoopProvenance({ ..., hostedClient: hosted }) // no-op if undefined\n *\n * Returns `undefined` (NOT an error) when any of endpoint / apiKey / tenantId is\n * missing — so a product wires the ship call unconditionally and it stays a\n * no-op until the env is set. Env precedence:\n * - endpoint: `TANGLE_INGEST_URL` → `TANGLE_ORCHESTRATOR_URL`\n * - apiKey: `TANGLE_INGEST_API_KEY` → `TANGLE_API_KEY`\n * - tenantId: `TANGLE_TENANT_ID`\n * A trailing slash on the endpoint is stripped. Pass `overrides` to supply any\n * field directly (e.g. a fixed `tenantId` per product) — overrides win over env.\n */\n/**\n * Build a {@link HostedTenant} config from env — the input `selfImprove`'s\n * `hostedTenant` and `emitLoopProvenance` take. Same env precedence + overrides\n * as {@link hostedClientFromEnv}; returns `undefined` (not an error) when any of\n * endpoint / apiKey / tenantId is missing, so a product wires\n * `hostedTenant: hostedTenantFromEnv({ tenantId: 'my-agent' })` unconditionally\n * and it stays off until the env is set.\n */\nexport function hostedTenantFromEnv(\n overrides: Partial<HostedTenant> & { env?: Record<string, string | undefined> } = {},\n): HostedTenant | undefined {\n const env = overrides.env ?? process.env\n const endpoint = (\n overrides.endpoint ??\n env.TANGLE_INGEST_URL ??\n env.TANGLE_ORCHESTRATOR_URL\n )?.trim()\n const apiKey = (overrides.apiKey ?? env.TANGLE_INGEST_API_KEY ?? env.TANGLE_API_KEY)?.trim()\n const tenantId = (overrides.tenantId ?? env.TANGLE_TENANT_ID)?.trim()\n if (!endpoint || !apiKey || !tenantId) return undefined\n const tenant: HostedTenant = { endpoint: endpoint.replace(/\\/+$/, ''), apiKey, tenantId }\n if (overrides.fetchImpl) tenant.fetchImpl = overrides.fetchImpl\n if (overrides.timeoutMs !== undefined) tenant.timeoutMs = overrides.timeoutMs\n if (overrides.retries !== undefined) tenant.retries = overrides.retries\n return tenant\n}\n\nexport function hostedClientFromEnv(\n overrides: Partial<HostedTenant> & { env?: Record<string, string | undefined> } = {},\n): HostedClient | undefined {\n const tenant = hostedTenantFromEnv(overrides)\n return tenant ? createHostedClient(tenant) : undefined\n}\n"],"mappings":";;;AAgCA,MAAa,sBAAsB;;;AChBnC,MAAM,eAAe,EAAE,OAAO,CAAC,CAAC,OAAO;AACvC,MAAM,oBAAoB,aAAa,YAAY;AACnD,MAAM,qBAAqB,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,YAAY;AACxD,MAAM,iBAAiB,EACpB,OAAO,CAAC,CACR,IAAI,CAAC,CAAC,CACN,QAAQ,UAAU,MAAM,KAAK,CAAC,CAAC,SAAS,GAAG,mBAAmB;AACjE,MAAM,iBAAiB,EAAE,MAAM;CAAC,EAAE,OAAO;CAAG;CAAc,EAAE,QAAQ;AAAC,CAAC;AACtE,MAAM,aAAa,EAAE,OAAO,EAAE,OAAO,GAAG,cAAc;AACtD,MAAM,qBAAqB,EAAE,QAC1B,UAAU,OAAO,UAAU,YAAY,gBAAgB,SAAS,KAAqB,GACtF,mBAAmB,gBAAgB,KAAK,IAAI,GAC9C;AACA,MAAM,aAAa;AAEnB,MAAa,0BAAwD,EAClE,OAAO,CAAC,CACR,MAAM,qBAAqB,6CAA6C,CAAC,CAC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E3B,iBAAiB;;EAEjB;;EAEA;;UAGe;;EAEf;;;EAGA;;;EAGA,UAAU;;EAEV,OAAO;;EAEP;;EAEA;;EAEA;;;;;;;UAQe;;EAEf;;EAEA;;EAEA;;EAEA,QAAQ;;EAER,QAAQ;;EAER,WAAW;;EAEX,aAAa;;EAEb,eAAe;;EAEf;;EAEA;;EAEA;;EAEA;;;;;;EAMA,gBAAgB;;;;;;KASN;;;;;;UAOK;EACf;EACA;EACA;EACA;EACA,mBAAmB;EACnB,iBAAiB;EACjB,YAAY;EACZ,SAAS;IACP,cAAc;IACd;IACA,aAAa;;EAEf;IAAW;IAAgC;;;EAE3C;;EAEA;;EAEA;;EAEA;;UAKe;EACf,aAAa;EACb,QAAQ;;UAGO;EACf,aAAa;EACb,OAAO;;UAGQ;;EAEf;;EAEA,UAAU;IAAQ;IAAe;;;;;UC1JlB;;EAEf;;EAEA;;EAEA;;EAEA,mBAAmB;;EAEnB;;EAEA;;UAGe;EACf,cAAc,OAAO,cAAc,0BAA0B,QAAQ;EACrE,eAAe,QAAQ,gBAAgB,0BAA0B,QAAQ;EACzE,aAAa,OAAO,kBAAkB,0BAA0B,QAAQ;WAC/D,QAAQ;WACR,aAAa;;iBAyGR,mBAAmB,QAAQ,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsE1C,oBACd,YAAW,QAAQ;EAAkB,MAAM;IAC1C;iBAiBa,oBACd,YAAW,QAAQ;EAAkB,MAAM;IAC1C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-Ba636PKl.d.ts","names":[],"sources":["../src/campaign/analyst-surface.ts","../src/paired-arms.ts","../src/campaign/cross-surface-types.ts","../src/campaign/cross-surface-interaction.ts","../src/campaign/fixtures.ts","../src/campaign/gates/neutralization-gate.ts","../src/pre-registration.ts","../src/campaign/gates/sequential.ts","../src/campaign/gates/statistical-heldout.ts","../src/campaign/grounded-reflection.ts","../src/campaign/labeled-store/fs-adapter.ts","../src/campaign/neutralize.ts","../src/artifact-validator.ts","../src/completion-verifier.ts","../src/produced-state.ts","../src/agent-profile.ts","../src/integrity/backend-integrity.ts","../src/campaign/presets/run-profile-matrix.ts","../src/campaign/presets/playback.ts","../src/campaign/run-dir.ts","../src/campaign/scenario-selection.ts","../src/campaign/score-utils.ts","../src/campaign/search-ledger-errors.ts","../src/campaign/search-ledger.ts","../src/campaign/single-run-lock.ts","../src/campaign/surface-identity.ts","../src/campaign/transient-failure.ts","../src/campaign/worktree/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;UAoCiB,wBAAwB;EACvC;;EAEA,QAAQ;;;EAGR;;;;;;;EAOA,sBAAsB;IAAQ;IAAY;;;;;;;EAM1C;;;UAIe;EACf;EACA;;;EAGA;;UAGe;;;;;;EAMf,gBAAgB,KAAK;;EAErB,WACE,OAAO,oBACP,SAAS,yBACN,QAAQ;;;;;;;iBAkBC,4BACd,MAAM,sCAEN,SAAS,gBACT,UAAU,iBACV,KAAK,oBACF,QAAQ;UAgBI;;;EAGf;;;;;;;;;iBAUc,uBACd,OAAM,gCACL,YAAY,iBAAiB;;;;;UC7Ff;;;EAGf;;;;;EAKA;;EAEA;;EAEA;;EAEA,UAAU;;UAGK;;EAEf;;EAEA;;;UAIe;EACf;;;;EAIA;EACA,UAAU;EACV,WAAW;;UAGI;;EAEf,OAAO;;;EAGP,kBAAkB;;EAElB,mBAAmB;;;;;;;;;;;;;;;;;;;;iBAqBL,SAAS,eAAe,gBAAgB,MAAM,kBAAkB;;UA8G/D;;EAEf;;EAEA;;EAEA,SAAS;;EAET,gBAAgB;;;UAID;EACf;;EAEA;;EAEA;;EAEA;;EAEA;;;;EAIA,aAAa;;EAEb;IAAY;IAAW;;;UAGR,iCAAiC;;;;EAIhD;;EAEA,YAAY;;UAGG;EACf;EACA;EACA;;;EAGA,aAAa;EACb,cAAc;;;;;;;;;;;;;;;iBAgBA,kBACd,eAAe,gBACf,MAAM,2BACL;UAmEc;EACf;EACA;EACA,UAAU;EACV,WAAW;;UAGI;EACf,OAAO;EACP,kBAAkB;EAClB,mBAAmB;;;;;;;;;iBAeL,eACd,uBAAuB,aACvB,wBAAwB,cACvB;;;;KCjXS;;UAGK;EACf;EACA;;EAEA;;;UAIe;EACf;EACA;EACA;EACA;;;UAIe;EACf;;EAEA;;EAEA;;;;;;;UAQe;EACf;EACA;;EAEA;EACA,cAAc;EACd;EACA;;;;;;EAMA,MAAM;EACN,mBAAmB;;EAEnB;;UAGe;EACf;EACA;EACA;;;UAIe;EACf;EACA;EACA;EACA;;EAEA,kCAAkC;;EAElC;;UAGe,qCACf,aAAa,sBAAsB;EAEnC,qBAAqB;EACrB,qBAAqB;EACrB,eAAe;EACf;;EAEA;;EAEA;;EAEA;;EAEA;EACA,WAAW;EACX,WAAW;;UAGI;EACf;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;;UAGe;EACf,aAAa;EACb;EACA;EACA;EACA;;KAGU;UAWK;EACf;EACA,SAAS;;UAGM;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf,WAAW;EACX,SAAS;EACT,OAAO;EACP,OAAO,eAAe;EACtB,QAAQ;EACR,QAAQ;;EAER,sBAAsB;;EAEtB,aAAa;;UAGE;EACf;EACA;EACA;;EAEA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA,QAAQ;EACR,cAAc,eAAe;;UAGd;EACf;EACA;EACA;EACA;EACA;;UAGe;EACf;;EAEA;EACA;;UAGe;EACf,SAAS;EACT;EACA;EACA;EACA;EACA,eAAe;EACf,gBAAgB;;KAGN;UAYK;EACf;EACA,SAAS;EACT;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA,4BAA4B,iCAAiC;EAC7D,wBAAwB,eAAe;EACvC,QAAQ;EACR,QAAQ;EACR,aAAa;EACb,eAAe;;UAGA;EACf;EACA;EACA;;UAGe;EACf;EACA;EACA,SAAS;;UAGM;;EAEf;EACA;;KAGU;UAaK;EACf;EACA;EACA;EACA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 @@
|
|
|
1
|
-
{"version":3,"file":"index-DSC51roc.d.ts","names":[],"sources":["../src/matrix/types.ts","../src/matrix/runner.ts"],"mappings":";;;;UAgBiB,WAAW;;EAE1B;;EAEA,QAAQ;IAAQ;IAAY,OAAO;;;;EAGnC,SAAS,OAAO,GAAG;;;UAIJ;EACf,MAAM;IAAiB;IAAY;;;EAEnC;;EAEA;;UAGe,WAAW;EAC1B,QAAQ;EACR,SAAS;EACT;EACA;EACA;;;EAGA;IAAU;IAAiB;;;UAGZ;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe,aAAa;EAC5B,OAAO;IAAQ,MAAM;IAAY,MAAM,WAAW;;;;EAGlD,QAAQ,eAAe,eAAe;EACtC;IACE;IACA;;;IAGA;IACA;IACA;IACA;IACA;;;EAGF;;UAGe,sBAAsB;EACrC,MAAM;;;EAGN,UAAU,MAAM,eAAe,QAAQ,WAAW;;EAElD;;EAEA,UAAU,MAAM,KAAK;;EAErB;;EAEA;;;;EAIA;;EAEA,kBAAkB,MAAM,YAAY,QAAQ,WAAW;;;EAGvD,SAAS;;;;iBCjBW,eAAe,QACnC,MAAM,sBAAsB,UAC3B,QAAQ,aAAa"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-nhIYz9hn.d.ts","names":[],"sources":["../src/ledger-core/atomic-file-lock.ts","../src/ledger-core/canonical.ts","../src/ledger-core/journal-file.ts","../src/ledger-core/trusted-head.ts","../src/ledger-core/journal.ts"],"mappings":";;;UAiBiB;WACN;WACA;WACA;;UAGM;WACN,OAAO;EAChB;;KAGU;WACG;WAA0B;WAAyB,QAAQ;;WAC3D;WAA0B;;KAE7B;WACG;WAAyB,MAAM;IAC1C;UAEa;WACN;WACA;;cAGE,4BAA4B;WACrB;;;iBASJ,oBACd,SAAS,wBACR;;;;;;;iBAea,yBACd,SAAS,wBACR;;;KCjDS;;cAGC,qBAAmB;;cAGnB,oCAAoC;;;;iBAKjC,gBAAgB;iBA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Q,QAAQ;;EA2CtD,eAAe,QAAQ;;;;EAWvB,kBAAkB,QAAQ;UAqBxB;UAUA;UAkBA;UAgDA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ledger-core-CPZfcrC2.js","names":[],"sources":["../src/ledger-core/atomic-file-lock.ts","../src/ledger-core/canonical.ts","../src/ledger-core/journal-file.ts","../src/ledger-core/trusted-head.ts","../src/ledger-core/journal.ts"],"sourcesContent":["/** Crash-safe filesystem lock shared by campaign persistence and run exclusion. */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n constants,\n existsSync,\n fsyncSync,\n linkSync,\n openSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport { hostname } from 'node:os'\n\nexport interface AtomicFileLockOwner {\n readonly pid: number\n readonly host: string\n readonly nonce: string\n}\n\nexport interface AtomicFileLock {\n readonly owner: AtomicFileLockOwner\n release(): void\n}\n\nexport type AtomicFileLockUnavailable =\n | { readonly acquired: false; readonly reason: 'held'; readonly holder: AtomicFileLockOwner }\n | { readonly acquired: false; readonly reason: 'recovery' }\n\nexport type AtomicFileLockAcquisition =\n | { readonly acquired: true; readonly lock: AtomicFileLock }\n | AtomicFileLockUnavailable\n\nexport interface AtomicFileLockOptions {\n readonly lockPath: string\n readonly pid?: number\n}\n\nexport class AtomicFileLockError extends Error {\n override readonly name = 'AtomicFileLockError'\n}\n\ntype OwnerState =\n | { readonly state: 'missing' }\n | { readonly state: 'stale'; readonly owner: AtomicFileLockOwner }\n | { readonly state: 'held'; readonly owner: AtomicFileLockOwner }\n\n/** Report whether another lock path prevents acquisition without modifying it. */\nexport function probeAtomicFileLock(\n options: AtomicFileLockOptions,\n): AtomicFileLockUnavailable | null {\n if (existsSync(recoveryPath(options.lockPath))) return { acquired: false, reason: 'recovery' }\n const state = ownerState(options.lockPath)\n if (state.state === 'held') {\n return { acquired: false, reason: 'held', holder: state.owner }\n }\n return null\n}\n\n/**\n * Try to acquire a complete, uniquely-owned lock inode.\n *\n * A hard link publishes fully-written owner metadata atomically. Stale-owner\n * removal is serialized so one reclaimer cannot delete a new owner's lock.\n */\nexport function tryAcquireAtomicFileLock(\n options: AtomicFileLockOptions,\n): AtomicFileLockAcquisition {\n const pid = options.pid ?? process.pid\n if (!Number.isSafeInteger(pid) || pid <= 0) {\n throw new AtomicFileLockError('atomic file lock pid must be a positive integer')\n }\n const owner: AtomicFileLockOwner = { pid, host: hostname(), nonce: randomUUID() }\n for (let attempt = 0; attempt < 8; attempt += 1) {\n if (existsSync(recoveryPath(options.lockPath))) {\n return { acquired: false, reason: 'recovery' }\n }\n if (tryLinkOwner(options.lockPath, owner, `acquire.${attempt}`)) {\n return acquired(options.lockPath, owner)\n }\n\n const holder = ownerState(options.lockPath)\n if (holder.state === 'missing') continue\n if (holder.state === 'held') {\n return { acquired: false, reason: 'held', holder: holder.owner }\n }\n\n const reclaimPath = recoveryPath(options.lockPath)\n if (!tryLinkOwner(reclaimPath, owner, `reclaim.${attempt}`)) {\n return { acquired: false, reason: 'recovery' }\n }\n try {\n const current = ownerState(options.lockPath)\n if (current.state === 'held') {\n return { acquired: false, reason: 'held', holder: current.owner }\n }\n if (current.state === 'stale') {\n const tombstone = `${options.lockPath}.stale.${owner.nonce}.${attempt}`\n try {\n renameSync(options.lockPath, tombstone)\n unlinkSync(tombstone)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n }\n if (tryLinkOwner(options.lockPath, owner, `recovered.${attempt}`)) {\n return acquired(options.lockPath, owner)\n }\n } finally {\n releaseOwnedPath(reclaimPath, owner)\n }\n }\n\n throw new AtomicFileLockError(`could not acquire atomic file lock ${options.lockPath}`)\n}\n\nfunction acquired(lockPath: string, owner: AtomicFileLockOwner): AtomicFileLockAcquisition {\n return {\n acquired: true,\n lock: {\n owner,\n release: () => releaseOwnedPath(lockPath, owner),\n },\n }\n}\n\nfunction tryLinkOwner(lockPath: string, owner: AtomicFileLockOwner, suffix: string): boolean {\n const ownerPath = `${lockPath}.${owner.pid}.${owner.nonce}.${suffix}.owner`\n const descriptor = openSync(\n ownerPath,\n constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,\n 0o600,\n )\n try {\n writeFileSync(descriptor, `${canonicalOwner(owner)}\\n`, 'utf8')\n fsyncSync(descriptor)\n } catch (error) {\n closeSync(descriptor)\n unlinkIfExists(ownerPath)\n throw error\n }\n closeSync(descriptor)\n\n try {\n linkSync(ownerPath, lockPath)\n return true\n } catch (error) {\n if (!isAlreadyExists(error)) throw error\n return false\n } finally {\n unlinkIfExists(ownerPath)\n }\n}\n\nfunction ownerState(lockPath: string): OwnerState {\n const owner = readOwner(lockPath)\n if (!owner) return { state: 'missing' }\n if (owner.host !== hostname()) return { state: 'held', owner }\n try {\n process.kill(owner.pid, 0)\n return { state: 'held', owner }\n } catch (error) {\n if (isNoSuchProcess(error)) return { state: 'stale', owner }\n return { state: 'held', owner }\n }\n}\n\nfunction readOwner(lockPath: string): AtomicFileLockOwner | undefined {\n let contents: string\n try {\n contents = readFileSync(lockPath, 'utf8').trim()\n } catch (error) {\n if (isMissing(error)) return undefined\n throw error\n }\n\n let value: unknown\n try {\n value = JSON.parse(contents)\n } catch (error) {\n throw invalidOwner(lockPath, error)\n }\n if (!isOwner(value)) throw invalidOwner(lockPath)\n return value\n}\n\nfunction isOwner(value: unknown): value is AtomicFileLockOwner {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const record = value as Record<string, unknown>\n return (\n Object.keys(record).length === 3 &&\n Number.isSafeInteger(record.pid) &&\n Number(record.pid) > 0 &&\n typeof record.host === 'string' &&\n record.host.trim().length > 0 &&\n typeof record.nonce === 'string' &&\n record.nonce.trim().length > 0\n )\n}\n\nfunction invalidOwner(lockPath: string, cause?: unknown): AtomicFileLockError {\n const error = new AtomicFileLockError(\n `atomic file lock has an invalid owner (${lockPath}); refusing unsafe recovery`,\n )\n if (cause !== undefined) Object.defineProperty(error, 'cause', { value: cause })\n return error\n}\n\nfunction releaseOwnedPath(lockPath: string, owner: AtomicFileLockOwner): void {\n const current = readOwner(lockPath)\n if (!current) return\n if (canonicalOwner(current) !== canonicalOwner(owner)) {\n throw new AtomicFileLockError(`atomic file lock owner changed before release (${lockPath})`)\n }\n try {\n unlinkSync(lockPath)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n}\n\nfunction canonicalOwner(owner: AtomicFileLockOwner): string {\n return JSON.stringify({ host: owner.host, nonce: owner.nonce, pid: owner.pid })\n}\n\nfunction recoveryPath(lockPath: string): string {\n return `${lockPath}.reclaim`\n}\n\nfunction isAlreadyExists(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'EEXIST'\n}\n\nfunction isMissing(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'ENOENT'\n}\n\nfunction isNoSuchProcess(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'ESRCH'\n}\n\nfunction unlinkIfExists(path: string): void {\n try {\n unlinkSync(path)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n}\n","/**\n * Canonical bytes and digests for durable journal rows.\n *\n * Serialization is RFC 8785 through `@tangle-network/agent-interface` — the\n * stack's single identity scheme — so a value carries the same digest in every\n * package that produces or verifies one.\n *\n * Values canonical JSON cannot represent faithfully are refused, never coerced.\n * `NaN`, `Infinity`, `undefined`, class instances, cycles, and unpaired\n * surrogates each have a lossy encoding that maps distinct records onto one\n * digest, and in a hash chain the digest IS the record's identity: a coercion\n * there is a collision, not a convenience.\n */\n\nimport {\n canonicalCandidateBytes,\n canonicalCandidateJson,\n sha256Bytes,\n} from '@tangle-network/agent-interface'\nimport { ValidationError } from '../errors'\n\nexport type LedgerHash = `sha256:${string}`\n\n/** Shape of every ledger digest: `sha256:` followed by 64 lowercase hex chars. */\nexport const LEDGER_HASH_PATTERN = /^sha256:[a-f0-9]{64}$/\n\n/** A value has no faithful canonical-JSON form, so it cannot be stored or hashed. */\nexport class LedgerCanonicalizationError extends ValidationError {}\n\n/** Canonical JSON encoding (RFC 8785): object keys sorted by UTF-16 code unit,\n * recursively. This is the byte form that is hashed and stored, so equal values\n * always encode identically. */\nexport function canonicalString(value: unknown): string {\n try {\n return canonicalCandidateJson(value)\n } catch (error) {\n throw canonicalizationError(value, error)\n }\n}\n\nexport function hashCanonical(value: unknown): LedgerHash {\n try {\n return sha256Bytes(canonicalCandidateBytes(value))\n } catch (error) {\n throw canonicalizationError(value, error)\n }\n}\n\n/** Name the offending value and path so a refusal is actionable. The RFC 8785\n * encoder above is the sole authority on acceptance; this walk only explains a\n * rejection it already made. */\nfunction canonicalizationError(value: unknown, cause: unknown): LedgerCanonicalizationError {\n const defect = firstNonCanonicalDefect(value, '$', new Set())\n const reason = defect !== '' ? defect : cause instanceof Error ? cause.message : String(cause)\n return new LedgerCanonicalizationError(`value has no canonical JSON form: ${reason}`, {\n cause,\n })\n}\n\nfunction firstNonCanonicalDefect(value: unknown, path: string, ancestors: Set<object>): string {\n if (value === null) return ''\n if (value === undefined) return `${path} is undefined`\n const type = typeof value\n if (type === 'number') {\n return Number.isFinite(value) ? '' : `${path} is ${String(value)}`\n }\n if (type === 'string') {\n return isWellFormedUtf16(value as string) ? '' : `${path} contains an unpaired surrogate`\n }\n if (type === 'boolean') return ''\n if (type !== 'object') return `${path} is a ${type}`\n const object = value as object\n if (ancestors.has(object)) return `${path} closes a reference cycle`\n const prototype = Object.getPrototypeOf(object)\n if (!Array.isArray(object) && prototype !== Object.prototype && prototype !== null) {\n return `${path} is a ${object.constructor?.name ?? 'non-plain'} instance, not plain JSON data`\n }\n const nested = new Set(ancestors).add(object)\n if (Array.isArray(object)) {\n for (let index = 0; index < object.length; index += 1) {\n const defect = firstNonCanonicalDefect(object[index], `${path}[${index}]`, nested)\n if (defect !== '') return defect\n }\n return ''\n }\n for (const [key, entry] of Object.entries(object)) {\n if (!isWellFormedUtf16(key)) return `${path}.${key} has a key with an unpaired surrogate`\n const defect = firstNonCanonicalDefect(entry, `${path}.${key}`, nested)\n if (defect !== '') return defect\n }\n return ''\n}\n\nfunction isWellFormedUtf16(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index)\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(index + 1)\n if (!(next >= 0xdc00 && next <= 0xdfff)) return false\n index += 1\n } else if (code >= 0xdc00 && code <= 0xdfff) {\n return false\n }\n }\n return true\n}\n","/** Filesystem durability and cross-process exclusion for append-only journal files. */\n\nimport {\n closeSync,\n constants,\n fsyncSync,\n mkdirSync,\n openSync,\n renameSync,\n writeSync,\n} from 'node:fs'\nimport { dirname } from 'node:path'\nimport { AtomicFileLockError, tryAcquireAtomicFileLock } from './atomic-file-lock'\n\n/** How a journal binding reports file-layer faults in its own error taxonomy. */\nexport interface LedgerFileContext {\n /** Noun used in error messages, e.g. 'search ledger'. */\n subject: string\n integrityError(message: string, options?: { cause?: unknown }): Error\n}\n\n/** Append one already-serialized line; the write is fsynced (file and directory)\n * before returning so an acknowledged append survives a crash. */\nexport function appendLedgerLine(path: string, line: string, context: LedgerFileContext): void {\n mkdirSync(dirname(path), { recursive: true })\n const fd = openSync(path, constants.O_CREAT | constants.O_WRONLY | constants.O_APPEND, 0o600)\n try {\n writeAll(fd, Buffer.from(line, 'utf8'), context)\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n fsyncDirectory(dirname(path))\n}\n\n/** Replace a small sidecar file whole: write a temporary sibling, fsync it,\n * then rename over the target. A reader therefore sees the previous contents\n * or the new ones, never a partial file. */\nexport function writeLedgerFileAtomically(\n path: string,\n contents: string,\n context: LedgerFileContext,\n): void {\n const directory = dirname(path)\n mkdirSync(directory, { recursive: true })\n const temporaryPath = `${path}.tmp`\n const fd = openSync(\n temporaryPath,\n constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC,\n 0o600,\n )\n try {\n writeAll(fd, Buffer.from(contents, 'utf8'), context)\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n renameSync(temporaryPath, path)\n fsyncDirectory(directory)\n}\n\nexport function withLedgerFileLock<T>(path: string, context: LedgerFileContext, run: () => T): T {\n const result = tryWithLedgerFileLock(path, context, run)\n if (!result.acquired) {\n throw context.integrityError(`${context.subject} lock is held (${path})`)\n }\n return result.value\n}\n\nexport type FileLockResult<T> = { acquired: true; value: T } | { acquired: false }\n\nexport function tryWithLedgerFileLock<T>(\n path: string,\n context: LedgerFileContext,\n run: () => T,\n): FileLockResult<T> {\n mkdirSync(dirname(path), { recursive: true })\n const lockPath = `${path}.lock`\n try {\n const acquisition = tryAcquireAtomicFileLock({ lockPath })\n if (!acquisition.acquired) return { acquired: false }\n try {\n return { acquired: true, value: run() }\n } finally {\n acquisition.lock.release()\n }\n } catch (error) {\n if (error instanceof AtomicFileLockError) {\n throw context.integrityError(error.message, { cause: error })\n }\n throw error\n }\n}\n\nfunction writeAll(fd: number, bytes: Buffer, context: LedgerFileContext): void {\n let offset = 0\n while (offset < bytes.byteLength) {\n const written = writeSync(fd, bytes, offset, bytes.byteLength - offset)\n if (written <= 0) throw context.integrityError('filesystem wrote zero bytes')\n offset += written\n }\n}\n\nfunction fsyncDirectory(path: string): void {\n const fd = openSync(path, constants.O_RDONLY)\n try {\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n","/**\n * Trusted head — the pin that makes deletion detectable.\n *\n * ## What the chain binds\n *\n * Every entry hashes the journal header, its sequence, the previous entry's\n * hash, and its event, so editing, reordering, or removing an entry in the\n * middle of a journal invalidates every hash after it. What a hash chain\n * cannot bind is its own length. Dropping entries off the END leaves a shorter\n * journal that is internally perfect, and rebuilding a journal from sequence 0\n * with recomputed hashes produces a different, equally perfect chain. For an\n * audit log of candidate registrations and promotion decisions that is the\n * difference between a record of a search that happened and a record of one\n * that did not.\n *\n * ## What the pin binds\n *\n * `<journal>.head` holds `{sequence, entryHash}` for one entry a writer\n * actually appended, in a file separate from the journal it attests. Each\n * entry hash commits to the entire prefix before it, so checking that the\n * entry at exactly `sequence` still carries `entryHash` proves two things at\n * once: the journal is at least `sequence + 1` entries long, and those entries\n * are byte-for-byte the ones the writer saw. A journal that merely grew past\n * the pin still verifies; a truncated, rolled-back, or wholesale-rewritten one\n * cannot.\n *\n * ## What the pin does NOT defend against\n *\n * The pin is a second file, not a signature. A writer with access to BOTH the\n * journal and its pin can rewrite both consistently, and the result verifies.\n * Pinning raises the cost of undetected tampering from one file to two and\n * nothing more; defending against a writer who holds both requires an anchor\n * outside this store entirely — a signed head, or a digest published to an\n * append-only service the tamperer does not control.\n *\n * Deleting the pin file downgrades a pinned journal to an unpinned one, which\n * cannot be distinguished from a journal written before pinning existed. That\n * is what `requireTrustedHead` is for: a journal opened under it refuses to\n * read at all once a non-empty journal has no pin.\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { canonicalString, LEDGER_HASH_PATTERN, type LedgerHash } from './canonical'\nimport { type LedgerFileContext, writeLedgerFileAtomically } from './journal-file'\n\n/** A `(sequence, entryHash)` pair a writer pinned outside the journal. */\nexport interface LedgerTrustedHead {\n sequence: number\n entryHash: LedgerHash\n}\n\n/** Minimum entry shape the anchor check needs. */\nexport interface LedgerAnchoredEntry {\n sequence: number\n entryHash: LedgerHash\n}\n\n/** Sibling pin file for a journal — deliberately NOT the journal, so rewriting\n * the log is not enough to rewrite the trust recorded about it. */\nexport function trustedHeadPathFor(journalPath: string): string {\n return `${journalPath}.head`\n}\n\n/** The pin, or null when this journal has never been pinned. A pin that exists\n * but does not parse is corruption or tamper of the trust record itself and\n * fails loudly: reporting it as \"no pin\" would silently downgrade what the\n * journal can prove. */\nexport function readTrustedHeadFile(\n path: string,\n context: LedgerFileContext,\n): LedgerTrustedHead | null {\n if (!existsSync(path)) return null\n const text = readFileSync(path, 'utf8')\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n throw context.integrityError(`${context.subject} trusted head ${path} is not valid JSON`, {\n cause: error,\n })\n }\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n throw context.integrityError(`${context.subject} trusted head ${path} is not an object`)\n }\n const record = raw as Record<string, unknown>\n const keys = Object.keys(record).sort()\n if (keys.length !== 2 || keys[0] !== 'entryHash' || keys[1] !== 'sequence') {\n throw context.integrityError(\n `${context.subject} trusted head ${path} has keys [${keys.join(', ')}], expected [entryHash, sequence]`,\n )\n }\n const { sequence, entryHash } = record\n if (typeof sequence !== 'number' || !Number.isSafeInteger(sequence) || sequence < 0) {\n throw context.integrityError(\n `${context.subject} trusted head ${path} sequence is not a non-negative integer`,\n )\n }\n if (typeof entryHash !== 'string' || !LEDGER_HASH_PATTERN.test(entryHash)) {\n throw context.integrityError(\n `${context.subject} trusted head ${path} entryHash is not a sha256 digest`,\n )\n }\n return { sequence, entryHash: entryHash as LedgerHash }\n}\n\n/** Publish a pin by write-then-rename, so a crash leaves either the previous\n * pin or the new one and never a torn file that would lock a journal out of\n * its own trust record. */\nexport function writeTrustedHeadFile(\n path: string,\n head: LedgerTrustedHead,\n context: LedgerFileContext,\n): void {\n writeLedgerFileAtomically(path, `${canonicalString(head)}\\n`, context)\n}\n\n/** The entry at exactly `head.sequence` must still carry `head.entryHash`.\n * Entries must already have passed chain verification, which is what makes\n * index and sequence interchangeable here. */\nexport function verifyEntriesAgainstTrustedHead(\n entries: readonly LedgerAnchoredEntry[],\n head: LedgerTrustedHead,\n context: LedgerFileContext,\n subject: string,\n): void {\n const pinned = entries[head.sequence]\n if (pinned === undefined) {\n throw context.integrityError(\n `${subject} trusted head pins sequence ${head.sequence} (${head.entryHash}) but the journal has ${entries.length} entries — pinned history is missing (truncation, rollback, or rewrite)`,\n )\n }\n if (pinned.sequence !== head.sequence) {\n throw context.integrityError(\n `${subject} entry at index ${head.sequence} carries sequence ${pinned.sequence}; the chain was not verified before the trusted head`,\n )\n }\n if (pinned.entryHash !== head.entryHash) {\n throw context.integrityError(\n `${subject} entry at pinned sequence ${head.sequence} carries ${pinned.entryHash} but the trusted head recorded ${head.entryHash} — the journal was rewritten`,\n )\n }\n}\n","/**\n * Generic durable append-only journal with a SHA-256 hash chain.\n *\n * The file format is canonical JSONL: every row is the canonical JSON encoding\n * (RFC 8785, object keys sorted recursively) of one entry, and every entry\n * hashes the previous entry's hash so the log is tamper-evident. Appends are\n * serialized in-process per path and across processes via a lock file, fsynced\n * before acknowledgement, and idempotent by `eventId`. A malformed,\n * non-canonical, truncated, reordered, or conflicting log fails loudly; a bad\n * row is never skipped.\n *\n * A hash chain binds each entry to its predecessor, which cannot prove that no\n * entry was removed from the end: a valid shorter prefix is still a valid\n * chain. `pinHead` records the appended entry in a sibling `<journal>.head`\n * file and every read re-verifies the journal against a pin that is present,\n * so truncation and wholesale rewrite are refused. `trusted-head.ts` carries\n * the full threat model, including what a pin does not defend against.\n *\n * Domain vocabulary lives entirely in the consumer's codec: entry schema\n * validation, the constant header fields stamped into every entry, the error\n * taxonomy, and the state machine replayed over verified entries.\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { Mutex } from '../concurrency'\nimport { canonicalString, hashCanonical, type LedgerHash } from './canonical'\nimport { appendLedgerLine, type LedgerFileContext, withLedgerFileLock } from './journal-file'\nimport {\n type LedgerTrustedHead,\n readTrustedHeadFile,\n trustedHeadPathFor,\n verifyEntriesAgainstTrustedHead,\n writeTrustedHeadFile,\n} from './trusted-head'\n\n/** Minimum shape of a journal event: the idempotency key. */\nexport interface LedgerEventBase {\n eventId: string\n}\n\n/** Chain envelope every entry carries in addition to the journal's constant\n * header fields. `entryHash` covers the header, sequence, previous hash, and\n * event, so any rewrite of history invalidates every later entry. */\nexport interface LedgerChainFields<Event extends LedgerEventBase> {\n sequence: number\n previousHash: LedgerHash | null\n event: Event\n entryHash: LedgerHash\n}\n\nexport type LedgerEntryOf<Header extends object, Event extends LedgerEventBase> = Header &\n LedgerChainFields<Event>\n\nexport interface LedgerLineContext {\n path: string\n line: number\n}\n\n/** Domain state machine replayed over chain-verified entries in order.\n * `apply` throws (via the codec's error taxonomy) on an invalid transition;\n * `finish` builds the consumer's projection once every entry was applied. */\nexport interface LedgerProjector<Entry, Projection> {\n apply(entry: Entry, index: number): void\n finish(entries: Entry[]): Projection\n}\n\nexport interface LedgerJournalCodec<\n Header extends object,\n Event extends LedgerEventBase,\n Projection,\n> extends LedgerFileContext {\n /** Constant fields stamped into every entry and covered by its hash. */\n header: Header\n conflictError(message: string): Error\n /** Validate one parsed JSON row into a typed entry. Must reject malformed\n * rows and non-canonical event encodings with the binding's own errors;\n * the journal itself verifies the stored bytes and the hash chain. */\n parseEntry(raw: unknown, context: LedgerLineContext): LedgerEntryOf<Header, Event>\n /** Reject an entry whose constant header fields do not match this journal. */\n checkEntryHeader(entry: LedgerEntryOf<Header, Event>, index: number): void\n createProjector(): LedgerProjector<LedgerEntryOf<Header, Event>, Projection>\n}\n\nexport interface LedgerReplayResult<Entry, Projection> {\n entries: Entry[]\n projection: Projection\n}\n\nexport interface LedgerAppendResult<Entry, Projection> {\n entry: Entry\n /** False when the exact event was already durably present. */\n appended: boolean\n projection: Projection\n}\n\nexport interface LedgerAppendOptions {\n /** Record the appended entry as this journal's trusted head, so a later read\n * can prove nothing was deleted from the end. Ignored on the idempotent\n * path: acknowledging an event that was already durable writes nothing, and\n * moving the pin there would jump trust forward past entries this caller\n * never saw. */\n pinHead?: boolean\n}\n\nexport interface FileLedgerJournalOptions {\n /** Refuse to read a non-empty journal that has no trusted head.\n *\n * Off by default because journals written before pinning have no pin and\n * must keep opening. Turn it on for a journal this process pins: without it,\n * deleting the sibling pin file silently downgrades the journal back to a\n * chain that cannot detect deletion. */\n requireTrustedHead?: boolean\n}\n\n// One async mutex per resolved journal path so concurrent appends from a single\n// process queue up instead of failing on the held cross-process lock file.\nconst journalMutexes = new Map<string, Mutex>()\n\nfunction mutexFor(path: string): Mutex {\n const existing = journalMutexes.get(path)\n if (existing) return existing\n const mutex = new Mutex()\n journalMutexes.set(path, mutex)\n return mutex\n}\n\n/** Durable filesystem journal. Construction performs no I/O; `append` and\n * `replay` validate the complete existing file under the locks. */\nexport class FileLedgerJournal<Header extends object, Event extends LedgerEventBase, Projection> {\n readonly path: string\n /** Sibling file holding this journal's trusted head. */\n readonly trustedHeadPath: string\n private readonly codec: LedgerJournalCodec<Header, Event, Projection>\n private readonly mutex: Mutex\n private readonly requireTrustedHead: boolean\n\n constructor(\n path: string,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n options: FileLedgerJournalOptions = {},\n ) {\n this.path = resolve(path)\n this.trustedHeadPath = trustedHeadPathFor(this.path)\n this.codec = codec\n this.mutex = mutexFor(this.path)\n this.requireTrustedHead = options.requireTrustedHead === true\n }\n\n async replay(): Promise<LedgerReplayResult<LedgerEntryOf<Header, Event>, Projection>> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () => this.replayLocked()),\n )\n }\n\n async append(\n event: Event,\n options: LedgerAppendOptions = {},\n ): Promise<LedgerAppendResult<LedgerEntryOf<Header, Event>, Projection>> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () => {\n const before = this.replayLocked()\n const existing = before.entries.find((entry) => entry.event.eventId === event.eventId)\n if (existing) {\n if (canonicalString(existing.event) !== canonicalString(event)) {\n throw this.codec.conflictError(\n `eventId ${event.eventId} already exists with different content`,\n )\n }\n return { entry: existing, appended: false, projection: before.projection }\n }\n\n const material = {\n ...this.codec.header,\n sequence: before.entries.length,\n previousHash: before.entries.at(-1)?.entryHash ?? null,\n event,\n }\n const entry = { ...material, entryHash: hashCanonical(material) }\n\n // Apply the state transition before spending an append: an entry the\n // projector rejects must never reach the durable file.\n const projection = this.project([...before.entries, entry])\n appendLedgerLine(this.path, `${canonicalString(entry)}\\n`, this.codec)\n if (options.pinHead === true) {\n // Journal first, pin second: a crash between them leaves the pin one\n // entry behind, which still verifies and is healed by the next\n // pinning append. The reverse order would leave a pin naming an\n // entry the journal does not carry, locking the journal out.\n writeTrustedHeadFile(\n this.trustedHeadPath,\n { sequence: entry.sequence, entryHash: entry.entryHash },\n this.codec,\n )\n }\n return { entry, appended: true, projection }\n }),\n )\n }\n\n /** The pinned head, or null when this journal has never been pinned. */\n async trustedHead(): Promise<LedgerTrustedHead | null> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () =>\n readTrustedHeadFile(this.trustedHeadPath, this.codec),\n ),\n )\n }\n\n /** Pin the current verified head. The chain and any existing pin are checked\n * first, so the pin only ever moves forward along a journal that still\n * carries the history it already recorded. */\n async pinTrustedHead(): Promise<LedgerTrustedHead> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () => {\n const entries = this.readEntries()\n this.project(entries)\n // `requireTrustedHead` is deliberately not applied here: pinning is how\n // a journal that lacks a pin acquires one.\n this.verifyTrustedHead(entries, false)\n const last = entries.at(-1)\n if (last === undefined) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} is empty; there is no head to pin`,\n )\n }\n const head: LedgerTrustedHead = { sequence: last.sequence, entryHash: last.entryHash }\n writeTrustedHeadFile(this.trustedHeadPath, head, this.codec)\n return head\n }),\n )\n }\n\n private replayLocked(): LedgerReplayResult<LedgerEntryOf<Header, Event>, Projection> {\n const entries = this.readEntries()\n const projection = this.project(entries)\n // The anchor is meaningful only over a chain that already verified, so it\n // is checked last — and on every read path, so a violated pin is refused\n // before an append can extend the journal over it.\n this.verifyTrustedHead(entries, this.requireTrustedHead)\n return { entries, projection }\n }\n\n private verifyTrustedHead(entries: LedgerEntryOf<Header, Event>[], requirePin: boolean): void {\n const pinned = readTrustedHeadFile(this.trustedHeadPath, this.codec)\n if (pinned === null) {\n if (requirePin && entries.length > 0) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has ${entries.length} entries but no trusted head at ${this.trustedHeadPath} — without its pin the journal cannot prove nothing was deleted`,\n )\n }\n return\n }\n verifyEntriesAgainstTrustedHead(\n entries,\n pinned,\n this.codec,\n `${this.codec.subject} ${this.path}`,\n )\n }\n\n private readEntries(): LedgerEntryOf<Header, Event>[] {\n if (!existsSync(this.path)) return []\n const text = readFileSync(this.path, 'utf8')\n if (text.length === 0) return []\n if (!text.endsWith('\\n')) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has a truncated final record (missing newline)`,\n )\n }\n\n const lines = text.slice(0, -1).split('\\n')\n const entries: LedgerEntryOf<Header, Event>[] = []\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index]!\n if (line.length === 0) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has a blank row at line ${index + 1}`,\n )\n }\n let raw: unknown\n try {\n raw = JSON.parse(line)\n } catch (error) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has invalid JSON at line ${index + 1}`,\n { cause: error },\n )\n }\n const entry = this.codec.parseEntry(raw, { path: this.path, line: index + 1 })\n let canonical: string\n try {\n canonical = canonicalString(entry)\n } catch (error) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has a row with no canonical JSON form at line ${index + 1}`,\n { cause: error },\n )\n }\n if (line !== canonical) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has non-canonical bytes at line ${index + 1}`,\n )\n }\n entries.push(entry)\n }\n return entries\n }\n\n private project(entries: LedgerEntryOf<Header, Event>[]): Projection {\n const projector = this.codec.createProjector()\n const eventIds = new Set<string>()\n let expectedPrevious: LedgerHash | null = null\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index]!\n this.codec.checkEntryHeader(entry, index)\n if (entry.sequence !== index) {\n throw this.codec.integrityError(\n `entry ${entry.event.eventId} has sequence ${entry.sequence}, expected ${index}`,\n )\n }\n if (entry.previousHash !== expectedPrevious) {\n throw this.codec.integrityError(\n `entry ${entry.event.eventId} does not extend the previous hash`,\n )\n }\n const { entryHash: _entryHash, ...material } = entry\n const expectedHash = hashCanonical(material)\n if (entry.entryHash !== expectedHash) {\n throw this.codec.integrityError(\n `entry ${entry.event.eventId} hash mismatch: expected ${expectedHash}, got ${entry.entryHash}`,\n )\n }\n expectedPrevious = entry.entryHash\n if (eventIds.has(entry.event.eventId)) {\n throw this.codec.integrityError(\n `duplicate eventId ${entry.event.eventId} in durable ledger`,\n )\n }\n eventIds.add(entry.event.eventId)\n projector.apply(entry, index)\n }\n return projector.finish(entries)\n }\n}\n"],"mappings":";;;;;;;;;AAyCA,IAAa,sBAAb,cAAyC,MAAM;CAC7C,OAAyB;AAC3B;;AAQA,SAAgB,oBACd,SACkC;CAClC,IAAI,WAAW,aAAa,QAAQ,QAAQ,CAAC,GAAG,OAAO;EAAE,UAAU;EAAO,QAAQ;CAAW;CAC7F,MAAM,QAAQ,WAAW,QAAQ,QAAQ;CACzC,IAAI,MAAM,UAAU,QAClB,OAAO;EAAE,UAAU;EAAO,QAAQ;EAAQ,QAAQ,MAAM;CAAM;CAEhE,OAAO;AACT;;;;;;;AAQA,SAAgB,yBACd,SAC2B;CAC3B,MAAM,MAAM,QAAQ,OAAO,QAAQ;CACnC,IAAI,CAAC,OAAO,cAAc,GAAG,KAAK,OAAO,GACvC,MAAM,IAAI,oBAAoB,iDAAiD;CAEjF,MAAM,QAA6B;EAAE;EAAK,MAAM,SAAS;EAAG,OAAO,WAAW;CAAE;CAChF,KAAK,IAAI,UAAU,GAAG,UAAU,GAAG,WAAW,GAAG;EAC/C,IAAI,WAAW,aAAa,QAAQ,QAAQ,CAAC,GAC3C,OAAO;GAAE,UAAU;GAAO,QAAQ;EAAW;EAE/C,IAAI,aAAa,QAAQ,UAAU,OAAO,WAAW,SAAS,GAC5D,OAAO,SAAS,QAAQ,UAAU,KAAK;EAGzC,MAAM,SAAS,WAAW,QAAQ,QAAQ;EAC1C,IAAI,OAAO,UAAU,WAAW;EAChC,IAAI,OAAO,UAAU,QACnB,OAAO;GAAE,UAAU;GAAO,QAAQ;GAAQ,QAAQ,OAAO;EAAM;EAGjE,MAAM,cAAc,aAAa,QAAQ,QAAQ;EACjD,IAAI,CAAC,aAAa,aAAa,OAAO,WAAW,SAAS,GACxD,OAAO;GAAE,UAAU;GAAO,QAAQ;EAAW;EAE/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