@tangle-network/agent-eval 0.132.0 → 0.133.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +1 -1
  3. package/dist/agent-profile-cell-OhuTee9n.js +335 -0
  4. package/dist/agent-profile-cell-OhuTee9n.js.map +1 -0
  5. package/dist/analyst/index.js +3 -3
  6. package/dist/{analyze-runs-BjPn_fOS.js → analyze-runs-B-afTpCv.js} +6 -19
  7. package/dist/analyze-runs-B-afTpCv.js.map +1 -0
  8. package/dist/{analyze-runs-AFDI5RI0.d.ts → analyze-runs-DZr7JW-m.d.ts} +2 -2
  9. package/dist/{analyze-runs-AFDI5RI0.d.ts.map → analyze-runs-DZr7JW-m.d.ts.map} +1 -1
  10. package/dist/{baseline-HsBvw_dk.js → baseline-DcX5hQDv.js} +2 -70
  11. package/dist/{baseline-HsBvw_dk.js.map → baseline-DcX5hQDv.js.map} +1 -1
  12. package/dist/baseline-hG3K85h4.d.ts.map +1 -1
  13. package/dist/benchmarks/index.d.ts +1 -1
  14. package/dist/benchmarks/index.js +1 -1
  15. package/dist/{benchmarks-DTrT3UH-.js → benchmarks-BU7P6PCW.js} +3 -3
  16. package/dist/{benchmarks-DTrT3UH-.js.map → benchmarks-BU7P6PCW.js.map} +1 -1
  17. package/dist/builder-eval/index.js +1 -1
  18. package/dist/campaign/index.d.ts +3 -3
  19. package/dist/campaign/index.js +2 -2
  20. package/dist/{campaign-Cx6CfMR4.js → campaign-CnzHQndg.js} +21 -15
  21. package/dist/{campaign-Cx6CfMR4.js.map → campaign-CnzHQndg.js.map} +1 -1
  22. package/dist/cli.js +1 -1
  23. package/dist/{client-aZDHJiKO.d.ts → client-D4F9hdzR.d.ts} +2 -2
  24. package/dist/{client-aZDHJiKO.d.ts.map → client-D4F9hdzR.d.ts.map} +1 -1
  25. package/dist/contract/index.d.ts +145 -6
  26. package/dist/contract/index.d.ts.map +1 -1
  27. package/dist/contract/index.js +1395 -11
  28. package/dist/contract/index.js.map +1 -1
  29. package/dist/control.js +1 -1
  30. package/dist/{cost-ledger-ZAa_P4r0.js → cost-ledger-BrJxbrMy.js} +238 -3
  31. package/dist/cost-ledger-BrJxbrMy.js.map +1 -0
  32. package/dist/{default-registry-B1JcpnRv.js → default-registry-D3T9XbuY.js} +3 -3
  33. package/dist/{default-registry-B1JcpnRv.js.map → default-registry-D3T9XbuY.js.map} +1 -1
  34. package/dist/{eval-campaign-mDKhkdUq.js → eval-campaign-DXhpZghy.js} +5 -6
  35. package/dist/{eval-campaign-mDKhkdUq.js.map → eval-campaign-DXhpZghy.js.map} +1 -1
  36. package/dist/{task-failure-attributes-CQZlB3et.js → extract-usage-2j25whHw.js} +154 -2
  37. package/dist/extract-usage-2j25whHw.js.map +1 -0
  38. package/dist/fuzz.js +1 -1
  39. package/dist/hosted/index.d.ts +1 -1
  40. package/dist/{index-3cdlURSk2.d.ts → index-3cdlURSk.d.ts} +1 -1
  41. package/dist/index-3cdlURSk.d.ts.map +1 -0
  42. package/dist/{index-FpfWFsKm.d.ts → index-Ba636PKl.d.ts} +29 -6
  43. package/dist/{index-FpfWFsKm.d.ts.map → index-Ba636PKl.d.ts.map} +1 -1
  44. package/dist/{index-p2TR_iWJ.d.ts → index-Wek5mU0y.d.ts} +3 -3
  45. package/dist/{index-p2TR_iWJ.d.ts.map → index-Wek5mU0y.d.ts.map} +1 -1
  46. package/dist/{index-BAvgST_9.d.ts → index-nhIYz9hn.d.ts} +67 -9
  47. package/dist/index-nhIYz9hn.d.ts.map +1 -0
  48. package/dist/index.d.ts +55 -9
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +111 -24
  51. package/dist/index.js.map +1 -1
  52. package/dist/ledger-core/index.d.ts +2 -2
  53. package/dist/ledger-core/index.js +2 -2
  54. package/dist/ledger-core-CPZfcrC2.js +620 -0
  55. package/dist/ledger-core-CPZfcrC2.js.map +1 -0
  56. package/dist/{llm-client-BNcP4v08.js → llm-client-ClPW-dWB.js} +2 -2
  57. package/dist/{llm-client-BNcP4v08.js.map → llm-client-ClPW-dWB.js.map} +1 -1
  58. package/dist/meta-eval/index.d.ts +215 -2
  59. package/dist/{index-CXs7QlR5.d.ts.map → meta-eval/index.d.ts.map} +1 -1
  60. package/dist/meta-eval/index.js +93 -3
  61. package/dist/meta-eval/index.js.map +1 -1
  62. package/dist/{mint-D5_87M5L.js → mint-BvkwcYZU.js} +2 -2
  63. package/dist/{mint-D5_87M5L.js.map → mint-BvkwcYZU.js.map} +1 -1
  64. package/dist/openapi.json +1 -1
  65. package/dist/{paired-arms-D9D0wXj2.js → paired-arms-6XItKzd1.js} +2 -2
  66. package/dist/{paired-arms-D9D0wXj2.js.map → paired-arms-6XItKzd1.js.map} +1 -1
  67. package/dist/pipelines/index.js +2 -2
  68. package/dist/profile-cell.js +1 -242
  69. package/dist/{propose-review-control-Bqb7daEJ.js → propose-review-control-SQ-n9-We.js} +2 -2
  70. package/dist/{propose-review-control-Bqb7daEJ.js.map → propose-review-control-SQ-n9-We.js.map} +1 -1
  71. package/dist/{release-report-oWt9f2k-.js → release-report-wuilQkvK.js} +3 -3
  72. package/dist/{release-report-oWt9f2k-.js.map → release-report-wuilQkvK.js.map} +1 -1
  73. package/dist/{replay-D18-pBAA.js → replay-CJfGLdx4.js} +4 -5
  74. package/dist/{replay-D18-pBAA.js.map → replay-CJfGLdx4.js.map} +1 -1
  75. package/dist/reporting.d.ts +1 -1
  76. package/dist/reporting.js +4 -4
  77. package/dist/{reward-hacking-BEvjdUtD.js → reward-hacking-Dl2UBzej.js} +3 -3
  78. package/dist/{reward-hacking-BEvjdUtD.js.map → reward-hacking-Dl2UBzej.js.map} +1 -1
  79. package/dist/rl.d.ts +153 -3
  80. package/dist/rl.d.ts.map +1 -1
  81. package/dist/rl.js +222 -7
  82. package/dist/rl.js.map +1 -1
  83. package/dist/rollout/index.d.ts +1 -1
  84. package/dist/rollout/index.js +2 -2
  85. package/dist/{rollout-VEo41J0N.js → rollout-CeTlDrf6.js} +2 -2
  86. package/dist/{rollout-VEo41J0N.js.map → rollout-CeTlDrf6.js.map} +1 -1
  87. package/dist/{rubric-predictive-validity-B3xmbmS1.js → rubric-predictive-validity-QG7ydk0s.js} +2 -2
  88. package/dist/{rubric-predictive-validity-B3xmbmS1.js.map → rubric-predictive-validity-QG7ydk0s.js.map} +1 -1
  89. package/dist/{run-record-CN8Zd21B.js → run-record-BIwU2wdV.js} +2 -2
  90. package/dist/{run-record-CN8Zd21B.js.map → run-record-BIwU2wdV.js.map} +1 -1
  91. package/dist/{semantic-concept-judge-DKCtoOz8.js → semantic-concept-judge-BypLt6Fw.js} +4 -4
  92. package/dist/{semantic-concept-judge-DKCtoOz8.js.map → semantic-concept-judge-BypLt6Fw.js.map} +1 -1
  93. package/dist/{server-Dc_lsOYd.js → server-BPqlDBWK.js} +3 -3
  94. package/dist/{server-Dc_lsOYd.js.map → server-BPqlDBWK.js.map} +1 -1
  95. package/dist/{skillopt-optimization-method-CQlz8GQM.js → skillopt-optimization-method-BoIzh7Dl.js} +6 -6
  96. package/dist/{skillopt-optimization-method-CQlz8GQM.js.map → skillopt-optimization-method-BoIzh7Dl.js.map} +1 -1
  97. package/dist/{skillopt-optimization-method-C9M_lxdo.d.ts → skillopt-optimization-method-CAASpcS3.d.ts} +3 -3
  98. package/dist/{skillopt-optimization-method-C9M_lxdo.d.ts.map → skillopt-optimization-method-CAASpcS3.d.ts.map} +1 -1
  99. package/dist/{statistics-CnnxdpOg.js → statistics-DWM_AyLe.js} +90 -76
  100. package/dist/statistics-DWM_AyLe.js.map +1 -0
  101. package/dist/statistics-DbvkkDPa.d.ts.map +1 -1
  102. package/dist/{summary-report-BNs5nmXI.js → summary-report-Ci17nIdU.js} +4 -4
  103. package/dist/{summary-report-BNs5nmXI.js.map → summary-report-Ci17nIdU.js.map} +1 -1
  104. package/dist/traces.js +2 -2
  105. package/dist/wire/index.js +1 -1
  106. package/package.json +2 -7
  107. package/dist/analyze-runs-BjPn_fOS.js.map +0 -1
  108. package/dist/belief-state/index.d.ts +0 -622
  109. package/dist/belief-state/index.d.ts.map +0 -1
  110. package/dist/belief-state/index.js +0 -1819
  111. package/dist/belief-state/index.js.map +0 -1
  112. package/dist/calibration-CNWWA6K8.js +0 -94
  113. package/dist/calibration-CNWWA6K8.js.map +0 -1
  114. package/dist/code-agent-session-BjkMTQ7H.js +0 -1390
  115. package/dist/code-agent-session-BjkMTQ7H.js.map +0 -1
  116. package/dist/code-agent-session-D5URqc3_.d.ts +0 -143
  117. package/dist/code-agent-session-D5URqc3_.d.ts.map +0 -1
  118. package/dist/cost-ledger-ZAa_P4r0.js.map +0 -1
  119. package/dist/extract-usage-BrQ8mCLX.js +0 -155
  120. package/dist/extract-usage-BrQ8mCLX.js.map +0 -1
  121. package/dist/index-3cdlURSk2.d.ts.map +0 -1
  122. package/dist/index-BAvgST_9.d.ts.map +0 -1
  123. package/dist/index-CXs7QlR5.d.ts +0 -217
  124. package/dist/ledger-core-eqaI3PCD.js +0 -388
  125. package/dist/ledger-core-eqaI3PCD.js.map +0 -1
  126. package/dist/metrics-C9YY1OcL.js +0 -239
  127. package/dist/metrics-C9YY1OcL.js.map +0 -1
  128. package/dist/off-policy-DvgzvtIx.js +0 -220
  129. package/dist/off-policy-DvgzvtIx.js.map +0 -1
  130. package/dist/off-policy-mskQw8Mb.d.ts +0 -153
  131. package/dist/off-policy-mskQw8Mb.d.ts.map +0 -1
  132. package/dist/pre-registration-DakwTRXk.js +0 -96
  133. package/dist/pre-registration-DakwTRXk.js.map +0 -1
  134. package/dist/profile-cell.js.map +0 -1
  135. package/dist/runtime-trajectory-1gyaTOoC.js +0 -93
  136. package/dist/runtime-trajectory-1gyaTOoC.js.map +0 -1
  137. package/dist/runtime-trajectory-BW9Wszb-.d.ts +0 -50
  138. package/dist/runtime-trajectory-BW9Wszb-.d.ts.map +0 -1
  139. package/dist/statistics-CnnxdpOg.js.map +0 -1
  140. package/dist/task-failure-attributes-CQZlB3et.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { s as ValidationError } from "./errors-8YnH8WlF.js";
2
- import { N as wilcoxonSignedRank, p as mcnemar, v as pairedBootstrap, x as pairedRiskDifference } from "./statistics-CnnxdpOg.js";
2
+ import { N as wilcoxonSignedRank, p as mcnemar, v as pairedBootstrap, x as pairedRiskDifference } from "./statistics-DWM_AyLe.js";
3
3
  //#region src/paired-arms.ts
4
4
  /**
5
5
  * Matched-pair arm comparison — "did the treatment arm beat the baseline arm
@@ -257,4 +257,4 @@ function metricValue(row, name) {
257
257
  //#endregion
258
258
  export { pairArms as n, pairRunRecords as r, comparePairedArms as t };
259
259
 
260
- //# sourceMappingURL=paired-arms-D9D0wXj2.js.map
260
+ //# sourceMappingURL=paired-arms-6XItKzd1.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"paired-arms-D9D0wXj2.js","names":[],"sources":["../src/paired-arms.ts"],"sourcesContent":["/**\n * Matched-pair arm comparison — \"did the treatment arm beat the baseline arm\n * on the SAME work items?\"\n *\n * An arm A/B over run records is only trustworthy when it is PAIRED: the same\n * task/scenario/seed evaluated under both arms, compared item-by-item, so\n * inter-item difficulty variance cancels instead of masquerading as an arm\n * effect. This module owns the two error-prone steps every consumer otherwise\n * hand-rolls:\n *\n * 1. Pairing — matching rows across arms by `pairKey` (and by `repKey`\n * within multi-rep items), with leftovers REPORTED rather than silently\n * dropped (a silently unbalanced pairing biases every paired statistic\n * downstream). Pairing never keys on outcome content: matching reps by\n * their outcomes deflates discordant-pair counts and makes McNemar\n * anti-conservative, so reps pair only by (`pairKey`, `repKey`) identity.\n * 2. Composition — feeding the matched pairs to the correct paired\n * estimators that already live in `statistics`: `mcnemar` +\n * `pairedRiskDifference` for pass/fail, `pairedBootstrap` +\n * `wilcoxonSignedRank` for continuous metrics. No statistic is\n * re-implemented here.\n *\n * The row shape is deliberately structural — callers project a `RunRecord`\n * (or any record) into `{ pairKey, arm, pass?, metrics? }`. Arm names are\n * caller-supplied parameters; the module ships no domain literal.\n */\n\nimport { ValidationError } from './errors'\nimport type { RunRecord } from './run-record'\nimport type { McNemarResult, PairedBootstrapOptions, PairedBootstrapResult } from './statistics'\nimport {\n mcnemar,\n pairedBootstrap,\n pairedRiskDifference,\n type RiskDifferenceResult,\n wilcoxonSignedRank,\n} from './statistics'\n\n/** One arm observation of one work item. Structural on purpose: callers\n * project their own record type (e.g. a `RunRecord`) into this shape. */\nexport interface PairedArmRow {\n /** Matching key — rows sharing a `pairKey` across both arms form pairs\n * (typically the task/scenario/seed identity). */\n pairKey: string\n /** Rep identity within a `pairKey` (e.g. a seed or rep number). Required on\n * every row of a `pairKey` that has more than one rep in either arm; reps\n * then pair only on exact (`pairKey`, `repKey`) match, never on outcome\n * content. Optional when each arm has at most one rep of the item. */\n repKey?: string\n /** Arm label this row was produced under. */\n arm: string\n /** Binary outcome; omit when the comparison has no pass/fail notion. */\n pass?: boolean\n /** Named numeric measurements (score, cost, latency, …). */\n metrics?: Record<string, number>\n}\n\nexport interface PairArmsOptions {\n /** Arm treated as the control side of every pair. */\n baselineArm: string\n /** Arm treated as the treatment side of every pair. */\n treatmentArm: string\n}\n\n/** One matched (baseline, treatment) observation of the same work item. */\nexport interface MatchedPair {\n pairKey: string\n /** 0-based position of this pair within its `pairKey`, ordered by sorted\n * `repKey` (always 0 for a single-rep item). The rep identity itself is on\n * the rows (`baseline.repKey` / `treatment.repKey`). */\n repIndex: number\n baseline: PairedArmRow\n treatment: PairedArmRow\n}\n\nexport interface PairArmsResult {\n /** Matched pairs, ordered by (`pairKey`, `repIndex`). */\n pairs: MatchedPair[]\n /** Baseline rows left without a treatment counterpart — reported, never\n * silently dropped. */\n unpairedBaseline: PairedArmRow[]\n /** Treatment rows left without a baseline counterpart. */\n unpairedTreatment: PairedArmRow[]\n}\n\n/**\n * Match rows across two arms into (baseline, treatment) pairs by `pairKey`.\n *\n * A `pairKey` with at most one row per arm pairs directly, no `repKey`\n * needed. A `pairKey` with multiple reps in either arm requires `repKey` on\n * every one of its rows, and reps pair only on exact (`pairKey`, `repKey`)\n * match — pairing is keyed purely on row identity, never on outcome content\n * (outcome-keyed matching deflates discordant counts and biases McNemar), and\n * is therefore independent of input order. Reps whose `repKey` has no\n * counterpart in the other arm, and items present in only one arm, land in\n * the unpaired lists — reported, never truncated.\n *\n * Fail-loud: throws when either named arm has zero rows (an unknown arm\n * name would otherwise read as \"everything unpaired\"), when the two arm\n * names are equal, when a multi-rep `pairKey` has a row without `repKey`, or\n * when a (`pairKey`, arm) group repeats a `repKey` (the match would be\n * ambiguous).\n */\nexport function pairArms(rows: readonly PairedArmRow[], opts: PairArmsOptions): PairArmsResult {\n const { baselineArm, treatmentArm } = opts\n if (baselineArm === treatmentArm) {\n throw new ValidationError(\n `pairArms: baselineArm and treatmentArm are both '${baselineArm}' — an arm cannot be compared to itself`,\n )\n }\n\n // arm → pairKey → rows\n const byArm = new Map<string, Map<string, PairedArmRow[]>>()\n const armsSeen = new Set<string>()\n for (const row of rows) {\n armsSeen.add(row.arm)\n if (row.arm !== baselineArm && row.arm !== treatmentArm) continue\n const byKey = byArm.get(row.arm) ?? new Map<string, PairedArmRow[]>()\n const group = byKey.get(row.pairKey) ?? []\n group.push(row)\n byKey.set(row.pairKey, group)\n byArm.set(row.arm, byKey)\n }\n\n for (const arm of [baselineArm, treatmentArm]) {\n if (!byArm.has(arm)) {\n const seen = [...armsSeen].sort().join(', ') || '<none>'\n throw new ValidationError(`pairArms: no rows for arm '${arm}' (arms present: ${seen})`)\n }\n }\n\n const baselineByKey = byArm.get(baselineArm)!\n const treatmentByKey = byArm.get(treatmentArm)!\n\n const allKeys = [...new Set([...baselineByKey.keys(), ...treatmentByKey.keys()])].sort()\n const pairs: MatchedPair[] = []\n const unpairedBaseline: PairedArmRow[] = []\n const unpairedTreatment: PairedArmRow[] = []\n for (const pairKey of allKeys) {\n const b = baselineByKey.get(pairKey) ?? []\n const t = treatmentByKey.get(pairKey) ?? []\n\n if (b.length <= 1 && t.length <= 1) {\n if (b.length === 1 && t.length === 1) {\n const baseline = b[0]!\n const treatment = t[0]!\n if (baseline.repKey !== undefined || treatment.repKey !== undefined) {\n if (\n baseline.repKey === undefined ||\n treatment.repKey === undefined ||\n baseline.repKey !== treatment.repKey\n ) {\n unpairedBaseline.push(baseline)\n unpairedTreatment.push(treatment)\n continue\n }\n }\n pairs.push({ pairKey, repIndex: 0, baseline, treatment })\n } else {\n unpairedBaseline.push(...b)\n unpairedTreatment.push(...t)\n }\n continue\n }\n\n const bByRep = indexByRepKey(b, pairKey, baselineArm)\n const tByRep = indexByRepKey(t, pairKey, treatmentArm)\n const repKeys = [...new Set([...bByRep.keys(), ...tByRep.keys()])].sort()\n let repIndex = 0\n for (const repKey of repKeys) {\n const baseline = bByRep.get(repKey)\n const treatment = tByRep.get(repKey)\n if (baseline !== undefined && treatment !== undefined) {\n pairs.push({ pairKey, repIndex: repIndex++, baseline, treatment })\n } else if (baseline !== undefined) {\n unpairedBaseline.push(baseline)\n } else if (treatment !== undefined) {\n unpairedTreatment.push(treatment)\n }\n }\n }\n\n return { pairs, unpairedBaseline, unpairedTreatment }\n}\n\n/** Index a multi-rep (pairKey, arm) group by `repKey`, enforcing that every\n * row carries one and that no repKey repeats within the group. */\nfunction indexByRepKey(\n group: readonly PairedArmRow[],\n pairKey: string,\n arm: string,\n): Map<string, PairedArmRow> {\n const byRep = new Map<string, PairedArmRow>()\n for (const row of group) {\n if (row.repKey === undefined) {\n throw new ValidationError(\n `pairArms: pairKey '${pairKey}' has multiple reps in an arm, but a row in arm '${arm}' ` +\n `is missing repKey — multi-rep items require an explicit repKey on every row so reps ` +\n `pair by identity (pairing reps by outcome or by index would bias the paired statistics)`,\n )\n }\n if (byRep.has(row.repKey)) {\n throw new ValidationError(\n `pairArms: duplicate repKey '${row.repKey}' for pairKey '${pairKey}' in arm '${arm}' — ` +\n `(pairKey, repKey) must uniquely identify a rep within an arm`,\n )\n }\n byRep.set(row.repKey, row)\n }\n return byRep\n}\n\n/** Paired pass/fail comparison over the pairs where BOTH sides carry `pass`. */\nexport interface PairedCorrectness {\n /** Discordant pairs where the treatment passed and the baseline failed. */\n b10: number\n /** Discordant pairs where the baseline passed and the treatment failed. */\n b01: number\n /** Exact McNemar significance over the paired outcomes (`b === b10`, `c === b01`). */\n mcnemar: McNemarResult\n /** Paired effect size: p(treatment) − p(baseline) with a paired-variance CI. */\n riskDifference: RiskDifferenceResult\n}\n\n/** Paired delta summary for one named metric (delta = treatment − baseline). */\nexport interface PairedMetricDelta {\n name: string\n /** Pairs where BOTH sides carry a finite value for this metric. */\n n: number\n /** Pairs where at least one side does not carry the metric. */\n nMissing: number\n /** Median paired delta, or null when `n === 0`. */\n medianDelta: number | null\n /** Mean paired delta, or null when `n === 0`. */\n meanDelta: number | null\n /** Bootstrap CI on the paired delta (`pairedBootstrap`); null when\n * `n === 0` — a zero-width [0, 0] interval on no data would read as a\n * measured tight null. */\n bootstrapCi: PairedBootstrapResult | null\n /** Wilcoxon signed-rank test on the paired deltas; null when `n === 0`. */\n wilcoxon: { w: number; p: number } | null\n}\n\nexport interface ComparePairedArmsOptions extends PairArmsOptions {\n /** Metrics to compare. Default: every metric name observed on any matched\n * pair, sorted. A name that appears on no pair is still reported (with\n * `n = 0`) so a misspelled metric is visible instead of vanishing. */\n metricNames?: string[]\n /** Passed through to `pairedBootstrap` — set `seed` for reproducible CIs. */\n bootstrap?: PairedBootstrapOptions\n}\n\nexport interface PairedArmsComparison {\n nPairs: number\n nUnpairedBaseline: number\n nUnpairedTreatment: number\n /** null when no matched pair carries `pass` on both sides — a pass/fail\n * verdict over rows that never measured pass/fail would be fabricated. */\n correctness: PairedCorrectness | null\n metricDeltas: PairedMetricDelta[]\n}\n\n/**\n * Full matched-pair arm comparison: pair via {@link pairArms}, then compose\n * the paired estimators from `statistics` over the matched pairs.\n *\n * Correctness uses only the pairs where both sides carry `pass` (`mcnemar.n`\n * is that subset's size); each metric uses only the pairs where both sides\n * carry a finite value for it, with the remainder counted in `nMissing`.\n * Deltas are treatment − baseline throughout.\n *\n * Fail-loud: inherits {@link pairArms}'s unknown-arm throw, and throws on a\n * non-finite metric value — silently treating corrupt telemetry as \"metric\n * absent\" would misreport it as missing coverage.\n */\nexport function comparePairedArms(\n rows: readonly PairedArmRow[],\n opts: ComparePairedArmsOptions,\n): PairedArmsComparison {\n const { pairs, unpairedBaseline, unpairedTreatment } = pairArms(rows, opts)\n\n let correctness: PairedCorrectness | null = null\n const baselinePass: number[] = []\n const treatmentPass: number[] = []\n for (const pair of pairs) {\n if (pair.baseline.pass === undefined || pair.treatment.pass === undefined) continue\n baselinePass.push(pair.baseline.pass ? 1 : 0)\n treatmentPass.push(pair.treatment.pass ? 1 : 0)\n }\n if (baselinePass.length > 0) {\n const mc = mcnemar(baselinePass, treatmentPass)\n correctness = {\n b10: mc.b,\n b01: mc.c,\n mcnemar: mc,\n riskDifference: pairedRiskDifference(baselinePass, treatmentPass),\n }\n }\n\n const metricNames =\n opts.metricNames ??\n [\n ...new Set(\n pairs.flatMap((p) => [\n ...Object.keys(p.baseline.metrics ?? {}),\n ...Object.keys(p.treatment.metrics ?? {}),\n ]),\n ),\n ].sort()\n\n const metricDeltas: PairedMetricDelta[] = metricNames.map((name) => {\n const before: number[] = []\n const after: number[] = []\n let nMissing = 0\n for (const pair of pairs) {\n const b = metricValue(pair.baseline, name)\n const t = metricValue(pair.treatment, name)\n if (b === undefined || t === undefined) {\n nMissing++\n continue\n }\n before.push(b)\n after.push(t)\n }\n const bootstrapCi = before.length === 0 ? null : pairedBootstrap(before, after, opts.bootstrap)\n return {\n name,\n n: before.length,\n nMissing,\n medianDelta: bootstrapCi?.median ?? null,\n meanDelta: bootstrapCi?.mean ?? null,\n bootstrapCi,\n wilcoxon: before.length === 0 ? null : wilcoxonSignedRank(before, after),\n }\n })\n\n return {\n nPairs: pairs.length,\n nUnpairedBaseline: unpairedBaseline.length,\n nUnpairedTreatment: unpairedTreatment.length,\n correctness,\n metricDeltas,\n }\n}\n\nexport interface MatchedRunRecordPair {\n pairKey: string\n repKey: string\n baseline: RunRecord\n treatment: RunRecord\n}\n\nexport interface PairRunRecordsResult {\n pairs: MatchedRunRecordPair[]\n unpairedBaseline: RunRecord[]\n unpairedTreatment: RunRecord[]\n}\n\ninterface RunRecordArmRow extends PairedArmRow {\n run: RunRecord\n repKey: string\n}\n\n/**\n * Pair two RunRecord arms by the identity of the evaluated work:\n * `(experimentId, scenarioId, seed)`.\n *\n * Falling back to array order, candidate id, or experiment id can compare\n * different tasks and fabricate lift. Duplicate identities throw.\n */\nexport function pairRunRecords(\n baselineRuns: readonly RunRecord[],\n treatmentRuns: readonly RunRecord[],\n): PairRunRecordsResult {\n const baselineRows = runRecordArmRows(baselineRuns, 'baseline')\n const treatmentRows = runRecordArmRows(treatmentRuns, 'treatment')\n validateRunRecordArmRows(baselineRows, 'baseline')\n validateRunRecordArmRows(treatmentRows, 'treatment')\n if (baselineRows.length === 0 || treatmentRows.length === 0) {\n return {\n pairs: [],\n unpairedBaseline: baselineRows.map((row) => row.run),\n unpairedTreatment: treatmentRows.map((row) => row.run),\n }\n }\n\n const result = pairArms([...baselineRows, ...treatmentRows], {\n baselineArm: 'baseline',\n treatmentArm: 'treatment',\n })\n return {\n pairs: result.pairs.map((pair) => {\n const baseline = pair.baseline as RunRecordArmRow\n const treatment = pair.treatment as RunRecordArmRow\n return {\n pairKey: pair.pairKey,\n repKey: baseline.repKey,\n baseline: baseline.run,\n treatment: treatment.run,\n }\n }),\n unpairedBaseline: result.unpairedBaseline.map((row) => (row as RunRecordArmRow).run),\n unpairedTreatment: result.unpairedTreatment.map((row) => (row as RunRecordArmRow).run),\n }\n}\n\nfunction runRecordArmRows(runs: readonly RunRecord[], arm: string): RunRecordArmRow[] {\n return runs.map((run) => {\n const scenarioId = run.scenarioId.trim()\n if (!scenarioId) {\n throw new ValidationError(\n `pairRunRecords: run '${run.runId}' is missing scenarioId; paired comparisons require explicit scenario identity`,\n )\n }\n return {\n pairKey: JSON.stringify([run.experimentId, scenarioId]),\n repKey: String(run.seed),\n arm,\n run,\n }\n })\n}\n\nfunction validateRunRecordArmRows(rows: readonly RunRecordArmRow[], arm: string): void {\n const byPairKey = new Map<string, RunRecordArmRow[]>()\n for (const row of rows) {\n const group = byPairKey.get(row.pairKey) ?? []\n group.push(row)\n byPairKey.set(row.pairKey, group)\n }\n for (const [pairKey, group] of byPairKey) {\n if (group.length > 1) indexByRepKey(group, pairKey, arm)\n }\n}\n\nfunction metricValue(row: PairedArmRow, name: string): number | undefined {\n const v = row.metrics?.[name]\n if (v === undefined) return undefined\n if (!Number.isFinite(v)) {\n throw new ValidationError(\n `comparePairedArms: non-finite value for metric '${name}' on pairKey '${row.pairKey}' (arm '${row.arm}'): ${v}`,\n )\n }\n return v\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuGA,SAAgB,SAAS,MAA+B,MAAuC;CAC7F,MAAM,EAAE,aAAa,iBAAiB;CACtC,IAAI,gBAAgB,cAClB,MAAM,IAAI,gBACR,oDAAoD,YAAY,wCAClE;CAIF,MAAM,wBAAQ,IAAI,IAAyC;CAC3D,MAAM,2BAAW,IAAI,IAAY;CACjC,KAAK,MAAM,OAAO,MAAM;EACtB,SAAS,IAAI,IAAI,GAAG;EACpB,IAAI,IAAI,QAAQ,eAAe,IAAI,QAAQ,cAAc;EACzD,MAAM,QAAQ,MAAM,IAAI,IAAI,GAAG,qBAAK,IAAI,IAA4B;EACpE,MAAM,QAAQ,MAAM,IAAI,IAAI,OAAO,KAAK,CAAC;EACzC,MAAM,KAAK,GAAG;EACd,MAAM,IAAI,IAAI,SAAS,KAAK;EAC5B,MAAM,IAAI,IAAI,KAAK,KAAK;CAC1B;CAEA,KAAK,MAAM,OAAO,CAAC,aAAa,YAAY,GAC1C,IAAI,CAAC,MAAM,IAAI,GAAG,GAEhB,MAAM,IAAI,gBAAgB,8BAA8B,IAAI,mBAD/C,CAAC,GAAG,QAAQ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,KAAK,gBAAgB,IAAI,QAAQ,UAAU,IAAI,IAAI,MAAM,GAC9G;CAEF,OAAO;AACT"}
1
+ {"version":3,"file":"paired-arms-6XItKzd1.js","names":[],"sources":["../src/paired-arms.ts"],"sourcesContent":["/**\n * Matched-pair arm comparison — \"did the treatment arm beat the baseline arm\n * on the SAME work items?\"\n *\n * An arm A/B over run records is only trustworthy when it is PAIRED: the same\n * task/scenario/seed evaluated under both arms, compared item-by-item, so\n * inter-item difficulty variance cancels instead of masquerading as an arm\n * effect. This module owns the two error-prone steps every consumer otherwise\n * hand-rolls:\n *\n * 1. Pairing — matching rows across arms by `pairKey` (and by `repKey`\n * within multi-rep items), with leftovers REPORTED rather than silently\n * dropped (a silently unbalanced pairing biases every paired statistic\n * downstream). Pairing never keys on outcome content: matching reps by\n * their outcomes deflates discordant-pair counts and makes McNemar\n * anti-conservative, so reps pair only by (`pairKey`, `repKey`) identity.\n * 2. Composition — feeding the matched pairs to the correct paired\n * estimators that already live in `statistics`: `mcnemar` +\n * `pairedRiskDifference` for pass/fail, `pairedBootstrap` +\n * `wilcoxonSignedRank` for continuous metrics. No statistic is\n * re-implemented here.\n *\n * The row shape is deliberately structural — callers project a `RunRecord`\n * (or any record) into `{ pairKey, arm, pass?, metrics? }`. Arm names are\n * caller-supplied parameters; the module ships no domain literal.\n */\n\nimport { ValidationError } from './errors'\nimport type { RunRecord } from './run-record'\nimport type { McNemarResult, PairedBootstrapOptions, PairedBootstrapResult } from './statistics'\nimport {\n mcnemar,\n pairedBootstrap,\n pairedRiskDifference,\n type RiskDifferenceResult,\n wilcoxonSignedRank,\n} from './statistics'\n\n/** One arm observation of one work item. Structural on purpose: callers\n * project their own record type (e.g. a `RunRecord`) into this shape. */\nexport interface PairedArmRow {\n /** Matching key — rows sharing a `pairKey` across both arms form pairs\n * (typically the task/scenario/seed identity). */\n pairKey: string\n /** Rep identity within a `pairKey` (e.g. a seed or rep number). Required on\n * every row of a `pairKey` that has more than one rep in either arm; reps\n * then pair only on exact (`pairKey`, `repKey`) match, never on outcome\n * content. Optional when each arm has at most one rep of the item. */\n repKey?: string\n /** Arm label this row was produced under. */\n arm: string\n /** Binary outcome; omit when the comparison has no pass/fail notion. */\n pass?: boolean\n /** Named numeric measurements (score, cost, latency, …). */\n metrics?: Record<string, number>\n}\n\nexport interface PairArmsOptions {\n /** Arm treated as the control side of every pair. */\n baselineArm: string\n /** Arm treated as the treatment side of every pair. */\n treatmentArm: string\n}\n\n/** One matched (baseline, treatment) observation of the same work item. */\nexport interface MatchedPair {\n pairKey: string\n /** 0-based position of this pair within its `pairKey`, ordered by sorted\n * `repKey` (always 0 for a single-rep item). The rep identity itself is on\n * the rows (`baseline.repKey` / `treatment.repKey`). */\n repIndex: number\n baseline: PairedArmRow\n treatment: PairedArmRow\n}\n\nexport interface PairArmsResult {\n /** Matched pairs, ordered by (`pairKey`, `repIndex`). */\n pairs: MatchedPair[]\n /** Baseline rows left without a treatment counterpart — reported, never\n * silently dropped. */\n unpairedBaseline: PairedArmRow[]\n /** Treatment rows left without a baseline counterpart. */\n unpairedTreatment: PairedArmRow[]\n}\n\n/**\n * Match rows across two arms into (baseline, treatment) pairs by `pairKey`.\n *\n * A `pairKey` with at most one row per arm pairs directly, no `repKey`\n * needed. A `pairKey` with multiple reps in either arm requires `repKey` on\n * every one of its rows, and reps pair only on exact (`pairKey`, `repKey`)\n * match — pairing is keyed purely on row identity, never on outcome content\n * (outcome-keyed matching deflates discordant counts and biases McNemar), and\n * is therefore independent of input order. Reps whose `repKey` has no\n * counterpart in the other arm, and items present in only one arm, land in\n * the unpaired lists — reported, never truncated.\n *\n * Fail-loud: throws when either named arm has zero rows (an unknown arm\n * name would otherwise read as \"everything unpaired\"), when the two arm\n * names are equal, when a multi-rep `pairKey` has a row without `repKey`, or\n * when a (`pairKey`, arm) group repeats a `repKey` (the match would be\n * ambiguous).\n */\nexport function pairArms(rows: readonly PairedArmRow[], opts: PairArmsOptions): PairArmsResult {\n const { baselineArm, treatmentArm } = opts\n if (baselineArm === treatmentArm) {\n throw new ValidationError(\n `pairArms: baselineArm and treatmentArm are both '${baselineArm}' — an arm cannot be compared to itself`,\n )\n }\n\n // arm → pairKey → rows\n const byArm = new Map<string, Map<string, PairedArmRow[]>>()\n const armsSeen = new Set<string>()\n for (const row of rows) {\n armsSeen.add(row.arm)\n if (row.arm !== baselineArm && row.arm !== treatmentArm) continue\n const byKey = byArm.get(row.arm) ?? new Map<string, PairedArmRow[]>()\n const group = byKey.get(row.pairKey) ?? []\n group.push(row)\n byKey.set(row.pairKey, group)\n byArm.set(row.arm, byKey)\n }\n\n for (const arm of [baselineArm, treatmentArm]) {\n if (!byArm.has(arm)) {\n const seen = [...armsSeen].sort().join(', ') || '<none>'\n throw new ValidationError(`pairArms: no rows for arm '${arm}' (arms present: ${seen})`)\n }\n }\n\n const baselineByKey = byArm.get(baselineArm)!\n const treatmentByKey = byArm.get(treatmentArm)!\n\n const allKeys = [...new Set([...baselineByKey.keys(), ...treatmentByKey.keys()])].sort()\n const pairs: MatchedPair[] = []\n const unpairedBaseline: PairedArmRow[] = []\n const unpairedTreatment: PairedArmRow[] = []\n for (const pairKey of allKeys) {\n const b = baselineByKey.get(pairKey) ?? []\n const t = treatmentByKey.get(pairKey) ?? []\n\n if (b.length <= 1 && t.length <= 1) {\n if (b.length === 1 && t.length === 1) {\n const baseline = b[0]!\n const treatment = t[0]!\n if (baseline.repKey !== undefined || treatment.repKey !== undefined) {\n if (\n baseline.repKey === undefined ||\n treatment.repKey === undefined ||\n baseline.repKey !== treatment.repKey\n ) {\n unpairedBaseline.push(baseline)\n unpairedTreatment.push(treatment)\n continue\n }\n }\n pairs.push({ pairKey, repIndex: 0, baseline, treatment })\n } else {\n unpairedBaseline.push(...b)\n unpairedTreatment.push(...t)\n }\n continue\n }\n\n const bByRep = indexByRepKey(b, pairKey, baselineArm)\n const tByRep = indexByRepKey(t, pairKey, treatmentArm)\n const repKeys = [...new Set([...bByRep.keys(), ...tByRep.keys()])].sort()\n let repIndex = 0\n for (const repKey of repKeys) {\n const baseline = bByRep.get(repKey)\n const treatment = tByRep.get(repKey)\n if (baseline !== undefined && treatment !== undefined) {\n pairs.push({ pairKey, repIndex: repIndex++, baseline, treatment })\n } else if (baseline !== undefined) {\n unpairedBaseline.push(baseline)\n } else if (treatment !== undefined) {\n unpairedTreatment.push(treatment)\n }\n }\n }\n\n return { pairs, unpairedBaseline, unpairedTreatment }\n}\n\n/** Index a multi-rep (pairKey, arm) group by `repKey`, enforcing that every\n * row carries one and that no repKey repeats within the group. */\nfunction indexByRepKey(\n group: readonly PairedArmRow[],\n pairKey: string,\n arm: string,\n): Map<string, PairedArmRow> {\n const byRep = new Map<string, PairedArmRow>()\n for (const row of group) {\n if (row.repKey === undefined) {\n throw new ValidationError(\n `pairArms: pairKey '${pairKey}' has multiple reps in an arm, but a row in arm '${arm}' ` +\n `is missing repKey — multi-rep items require an explicit repKey on every row so reps ` +\n `pair by identity (pairing reps by outcome or by index would bias the paired statistics)`,\n )\n }\n if (byRep.has(row.repKey)) {\n throw new ValidationError(\n `pairArms: duplicate repKey '${row.repKey}' for pairKey '${pairKey}' in arm '${arm}' — ` +\n `(pairKey, repKey) must uniquely identify a rep within an arm`,\n )\n }\n byRep.set(row.repKey, row)\n }\n return byRep\n}\n\n/** Paired pass/fail comparison over the pairs where BOTH sides carry `pass`. */\nexport interface PairedCorrectness {\n /** Discordant pairs where the treatment passed and the baseline failed. */\n b10: number\n /** Discordant pairs where the baseline passed and the treatment failed. */\n b01: number\n /** Exact McNemar significance over the paired outcomes (`b === b10`, `c === b01`). */\n mcnemar: McNemarResult\n /** Paired effect size: p(treatment) − p(baseline) with a paired-variance CI. */\n riskDifference: RiskDifferenceResult\n}\n\n/** Paired delta summary for one named metric (delta = treatment − baseline). */\nexport interface PairedMetricDelta {\n name: string\n /** Pairs where BOTH sides carry a finite value for this metric. */\n n: number\n /** Pairs where at least one side does not carry the metric. */\n nMissing: number\n /** Median paired delta, or null when `n === 0`. */\n medianDelta: number | null\n /** Mean paired delta, or null when `n === 0`. */\n meanDelta: number | null\n /** Bootstrap CI on the paired delta (`pairedBootstrap`); null when\n * `n === 0` — a zero-width [0, 0] interval on no data would read as a\n * measured tight null. */\n bootstrapCi: PairedBootstrapResult | null\n /** Wilcoxon signed-rank test on the paired deltas; null when `n === 0`. */\n wilcoxon: { w: number; p: number } | null\n}\n\nexport interface ComparePairedArmsOptions extends PairArmsOptions {\n /** Metrics to compare. Default: every metric name observed on any matched\n * pair, sorted. A name that appears on no pair is still reported (with\n * `n = 0`) so a misspelled metric is visible instead of vanishing. */\n metricNames?: string[]\n /** Passed through to `pairedBootstrap` — set `seed` for reproducible CIs. */\n bootstrap?: PairedBootstrapOptions\n}\n\nexport interface PairedArmsComparison {\n nPairs: number\n nUnpairedBaseline: number\n nUnpairedTreatment: number\n /** null when no matched pair carries `pass` on both sides — a pass/fail\n * verdict over rows that never measured pass/fail would be fabricated. */\n correctness: PairedCorrectness | null\n metricDeltas: PairedMetricDelta[]\n}\n\n/**\n * Full matched-pair arm comparison: pair via {@link pairArms}, then compose\n * the paired estimators from `statistics` over the matched pairs.\n *\n * Correctness uses only the pairs where both sides carry `pass` (`mcnemar.n`\n * is that subset's size); each metric uses only the pairs where both sides\n * carry a finite value for it, with the remainder counted in `nMissing`.\n * Deltas are treatment − baseline throughout.\n *\n * Fail-loud: inherits {@link pairArms}'s unknown-arm throw, and throws on a\n * non-finite metric value — silently treating corrupt telemetry as \"metric\n * absent\" would misreport it as missing coverage.\n */\nexport function comparePairedArms(\n rows: readonly PairedArmRow[],\n opts: ComparePairedArmsOptions,\n): PairedArmsComparison {\n const { pairs, unpairedBaseline, unpairedTreatment } = pairArms(rows, opts)\n\n let correctness: PairedCorrectness | null = null\n const baselinePass: number[] = []\n const treatmentPass: number[] = []\n for (const pair of pairs) {\n if (pair.baseline.pass === undefined || pair.treatment.pass === undefined) continue\n baselinePass.push(pair.baseline.pass ? 1 : 0)\n treatmentPass.push(pair.treatment.pass ? 1 : 0)\n }\n if (baselinePass.length > 0) {\n const mc = mcnemar(baselinePass, treatmentPass)\n correctness = {\n b10: mc.b,\n b01: mc.c,\n mcnemar: mc,\n riskDifference: pairedRiskDifference(baselinePass, treatmentPass),\n }\n }\n\n const metricNames =\n opts.metricNames ??\n [\n ...new Set(\n pairs.flatMap((p) => [\n ...Object.keys(p.baseline.metrics ?? {}),\n ...Object.keys(p.treatment.metrics ?? {}),\n ]),\n ),\n ].sort()\n\n const metricDeltas: PairedMetricDelta[] = metricNames.map((name) => {\n const before: number[] = []\n const after: number[] = []\n let nMissing = 0\n for (const pair of pairs) {\n const b = metricValue(pair.baseline, name)\n const t = metricValue(pair.treatment, name)\n if (b === undefined || t === undefined) {\n nMissing++\n continue\n }\n before.push(b)\n after.push(t)\n }\n const bootstrapCi = before.length === 0 ? null : pairedBootstrap(before, after, opts.bootstrap)\n return {\n name,\n n: before.length,\n nMissing,\n medianDelta: bootstrapCi?.median ?? null,\n meanDelta: bootstrapCi?.mean ?? null,\n bootstrapCi,\n wilcoxon: before.length === 0 ? null : wilcoxonSignedRank(before, after),\n }\n })\n\n return {\n nPairs: pairs.length,\n nUnpairedBaseline: unpairedBaseline.length,\n nUnpairedTreatment: unpairedTreatment.length,\n correctness,\n metricDeltas,\n }\n}\n\nexport interface MatchedRunRecordPair {\n pairKey: string\n repKey: string\n baseline: RunRecord\n treatment: RunRecord\n}\n\nexport interface PairRunRecordsResult {\n pairs: MatchedRunRecordPair[]\n unpairedBaseline: RunRecord[]\n unpairedTreatment: RunRecord[]\n}\n\ninterface RunRecordArmRow extends PairedArmRow {\n run: RunRecord\n repKey: string\n}\n\n/**\n * Pair two RunRecord arms by the identity of the evaluated work:\n * `(experimentId, scenarioId, seed)`.\n *\n * Falling back to array order, candidate id, or experiment id can compare\n * different tasks and fabricate lift. Duplicate identities throw.\n */\nexport function pairRunRecords(\n baselineRuns: readonly RunRecord[],\n treatmentRuns: readonly RunRecord[],\n): PairRunRecordsResult {\n const baselineRows = runRecordArmRows(baselineRuns, 'baseline')\n const treatmentRows = runRecordArmRows(treatmentRuns, 'treatment')\n validateRunRecordArmRows(baselineRows, 'baseline')\n validateRunRecordArmRows(treatmentRows, 'treatment')\n if (baselineRows.length === 0 || treatmentRows.length === 0) {\n return {\n pairs: [],\n unpairedBaseline: baselineRows.map((row) => row.run),\n unpairedTreatment: treatmentRows.map((row) => row.run),\n }\n }\n\n const result = pairArms([...baselineRows, ...treatmentRows], {\n baselineArm: 'baseline',\n treatmentArm: 'treatment',\n })\n return {\n pairs: result.pairs.map((pair) => {\n const baseline = pair.baseline as RunRecordArmRow\n const treatment = pair.treatment as RunRecordArmRow\n return {\n pairKey: pair.pairKey,\n repKey: baseline.repKey,\n baseline: baseline.run,\n treatment: treatment.run,\n }\n }),\n unpairedBaseline: result.unpairedBaseline.map((row) => (row as RunRecordArmRow).run),\n unpairedTreatment: result.unpairedTreatment.map((row) => (row as RunRecordArmRow).run),\n }\n}\n\nfunction runRecordArmRows(runs: readonly RunRecord[], arm: string): RunRecordArmRow[] {\n return runs.map((run) => {\n const scenarioId = run.scenarioId.trim()\n if (!scenarioId) {\n throw new ValidationError(\n `pairRunRecords: run '${run.runId}' is missing scenarioId; paired comparisons require explicit scenario identity`,\n )\n }\n return {\n pairKey: JSON.stringify([run.experimentId, scenarioId]),\n repKey: String(run.seed),\n arm,\n run,\n }\n })\n}\n\nfunction validateRunRecordArmRows(rows: readonly RunRecordArmRow[], arm: string): void {\n const byPairKey = new Map<string, RunRecordArmRow[]>()\n for (const row of rows) {\n const group = byPairKey.get(row.pairKey) ?? []\n group.push(row)\n byPairKey.set(row.pairKey, group)\n }\n for (const [pairKey, group] of byPairKey) {\n if (group.length > 1) indexByRepKey(group, pairKey, arm)\n }\n}\n\nfunction metricValue(row: PairedArmRow, name: string): number | undefined {\n const v = row.metrics?.[name]\n if (v === undefined) return undefined\n if (!Number.isFinite(v)) {\n throw new ValidationError(\n `comparePairedArms: non-finite value for metric '${name}' on pairKey '${row.pair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F;AAEA,SAAS,iBAAiB,MAA4B,KAAgC;CACpF,OAAO,KAAK,KAAK,QAAQ;EACvB,MAAM,aAAa,IAAI,WAAW,KAAK;EACvC,IAAI,CAAC,YACH,MAAM,IAAI,gBACR,wBAAwB,IAAI,MAAM,+EACpC;EAEF,OAAO;GACL,SAAS,KAAK,UAAU,CAAC,IAAI,cAAc,UAAU,CAAC;GACtD,QAAQ,OAAO,IAAI,IAAI;GACvB;GACA;EACF;CACF,CAAC;AACH;AAEA,SAAS,yBAAyB,MAAkC,KAAmB;CACrF,MAAM,4BAAY,IAAI,IAA+B;CACrD,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,QAAQ,UAAU,IAAI,IAAI,OAAO,KAAK,CAAC;EAC7C,MAAM,KAAK,GAAG;EACd,UAAU,IAAI,IAAI,SAAS,KAAK;CAClC;CACA,KAAK,MAAM,CAAC,SAAS,UAAU,WAC7B,IAAI,MAAM,SAAS,GAAG,cAAc,OAAO,SAAS,GAAG;AAE3D;AAEA,SAAS,YAAY,KAAmB,MAAkC;CACxE,MAAM,IAAI,IAAI,UAAU;CACxB,IAAI,MAAM,KAAA,GAAW,OAAO,KAAA;CAC5B,IAAI,CAAC,OAAO,SAAS,CAAC,GACpB,MAAM,IAAI,gBACR,mDAAmD,KAAK,gBAAgB,IAAI,QAAQ,UAAU,IAAI,IAAI,MAAM,GAC9G;CAEF,OAAO;AACT"}
@@ -1,9 +1,9 @@
1
1
  import { t as executionTrackByLane } from "../execution-tracks-CpgFPpS5.js";
2
- import { E as pearsonR, u as interRaterReliability } from "../statistics-CnnxdpOg.js";
2
+ import { E as pearsonR, u as interRaterReliability } from "../statistics-DWM_AyLe.js";
3
3
  import { s as isToolSpan } from "../schema-CRhEY1SO.js";
4
4
  import { t as buildTrajectory } from "../trajectory-D_7rLrvE.js";
5
5
  import { i as hasCapturedToolArgs, l as toolSpans, n as argHash, o as llmSpans, s as runFailureClass, t as aggregateLlm } from "../query-Di7eEQ79.js";
6
- import { a as DEFAULT_RULES, i as computeToolUseMetrics, o as classifyFailure, t as compareToBaseline } from "../baseline-HsBvw_dk.js";
6
+ import { a as DEFAULT_RULES, i as computeToolUseMetrics, o as classifyFailure, t as compareToBaseline } from "../baseline-DcX5hQDv.js";
7
7
  //#region src/pipelines/budget-breach.ts
8
8
  async function budgetBreachView(store, options = {}) {
9
9
  const runs = await store.listRuns({
@@ -1,243 +1,2 @@
1
- import { s as ValidationError } from "./errors-8YnH8WlF.js";
2
- import { r as hashJson } from "./pre-registration-DakwTRXk.js";
3
- //#region src/agent-profile-cell.ts
4
- var AgentProfileCellValidationError = class extends ValidationError {
5
- path;
6
- constructor(message, path = "") {
7
- super(path ? `${message} (at ${path})` : message);
8
- this.path = path;
9
- }
10
- };
11
- const SHA256_HEX = /^[0-9a-f]{64}$/;
12
- const CELL_ID = /^agent-profile-cell:sha256:[0-9a-f]{64}$/;
13
- async function buildAgentProfileCell(input) {
14
- const material = await normalizeAgentProfileCellInput(input);
15
- const cellId = `agent-profile-cell:sha256:${await hashJson(material)}`;
16
- return {
17
- ...material,
18
- cellId
19
- };
20
- }
21
- function agentProfileCellHashMaterial(cell) {
22
- const { cellId: _cellId, ...material } = cell;
23
- return normalizeAgentProfileCell(material);
24
- }
25
- /**
26
- * Verify an `AgentProfileCell`'s `cellId` matches the sha256 of its hash-material fields, confirming the record has not been tampered with.
27
- */
28
- async function verifyAgentProfileCell(cell) {
29
- validateAgentProfileCell(cell);
30
- return cell.cellId === `agent-profile-cell:sha256:${await hashJson(agentProfileCellHashMaterial(cell))}`;
31
- }
32
- function validateAgentProfileCell(input) {
33
- if (input === null || typeof input !== "object") throw new AgentProfileCellValidationError("expected object");
34
- const obj = input;
35
- expectLiteral(obj.schemaVersion, "agent-profile-cell/v1", "schemaVersion");
36
- if (typeof obj.cellId !== "string" || !CELL_ID.test(obj.cellId)) throw new AgentProfileCellValidationError("cellId must match agent-profile-cell:sha256:<64 lowercase hex chars>", "cellId");
37
- expectString(obj.profileId, "profileId");
38
- validateSource(obj.sourceProfile, "sourceProfile");
39
- if (obj.harness !== void 0) validateHarness(obj.harness, "harness");
40
- if (obj.model !== void 0) expectString(obj.model, "model");
41
- if (obj.promptHash !== void 0) expectString(obj.promptHash, "promptHash");
42
- if (obj.dimensions !== void 0) validateDimensions(obj.dimensions, "dimensions");
43
- return input;
44
- }
45
- function requireAgentProfileCell(record) {
46
- if (!record.agentProfile) throw new AgentProfileCellValidationError(`run "${record.runId}" is missing agentProfile; profile-cell grouping requires explicit profile identity`, "agentProfile");
47
- return validateAgentProfileCell(record.agentProfile);
48
- }
49
- function agentProfileCellKey(record) {
50
- return requireAgentProfileCell(record).cellId;
51
- }
52
- async function assertRunAgentProfileCell(record) {
53
- const profile = requireAgentProfileCell(record);
54
- if (!await verifyAgentProfileCell(profile)) throw new AgentProfileCellValidationError(`run "${record.runId}" has an agentProfile.cellId that does not match its content`, "agentProfile.cellId");
55
- if (profile.model !== void 0 && profile.model !== record.model) throw new AgentProfileCellValidationError(`run "${record.runId}" agentProfile.model "${profile.model}" does not match model "${record.model}"`, "agentProfile.model");
56
- if (profile.promptHash !== void 0 && profile.promptHash !== record.promptHash) throw new AgentProfileCellValidationError(`run "${record.runId}" agentProfile.promptHash "${profile.promptHash}" does not match promptHash "${record.promptHash}"`, "agentProfile.promptHash");
57
- return profile;
58
- }
59
- function groupRunsByAgentProfileCell(records) {
60
- const groups = /* @__PURE__ */ new Map();
61
- for (const record of records) {
62
- const key = agentProfileCellKey(record);
63
- const bucket = groups.get(key);
64
- if (bucket) bucket.push(record);
65
- else groups.set(key, [record]);
66
- }
67
- return groups;
68
- }
69
- async function normalizeAgentProfileCellInput(input) {
70
- return normalizeAgentProfileCell({
71
- schemaVersion: "agent-profile-cell/v1",
72
- profileId: input.profileId,
73
- sourceProfile: await normalizeSourceInput(input.sourceProfile),
74
- harness: input.harness,
75
- model: input.model,
76
- promptHash: input.promptHash,
77
- dimensions: input.dimensions
78
- });
79
- }
80
- function normalizeAgentProfileCell(input) {
81
- return compactObject({
82
- schemaVersion: "agent-profile-cell/v1",
83
- profileId: requireNonEmpty(input.profileId, "profileId"),
84
- sourceProfile: normalizeSource(input.sourceProfile),
85
- harness: input.harness ? normalizeHarness(input.harness, "harness") : void 0,
86
- model: optionalNonEmpty(input.model, "model"),
87
- promptHash: optionalNonEmpty(input.promptHash, "promptHash"),
88
- dimensions: input.dimensions ? nonEmptyRecord(normalizeDimensions(input.dimensions)) : void 0
89
- });
90
- }
91
- async function normalizeSourceInput(input) {
92
- const kind = requireNonEmpty(input.kind, "sourceProfile.kind");
93
- if (input.hash !== void 0 && input.profile !== void 0) throw new AgentProfileCellValidationError("sourceProfile must provide either hash or profile, not both", "sourceProfile");
94
- if (input.hash !== void 0) return {
95
- kind,
96
- hash: requireSha256Hex(input.hash, "sourceProfile.hash")
97
- };
98
- if (input.profile === void 0) throw new AgentProfileCellValidationError("sourceProfile must provide hash or profile", "sourceProfile");
99
- assertJson(input.profile, "sourceProfile.profile");
100
- return {
101
- kind,
102
- hash: await hashJson(input.profile)
103
- };
104
- }
105
- function normalizeSource(input) {
106
- return {
107
- kind: requireNonEmpty(input.kind, "sourceProfile.kind"),
108
- hash: requireSha256Hex(input.hash, "sourceProfile.hash")
109
- };
110
- }
111
- function normalizeHarness(input, path) {
112
- return compactObject({
113
- id: requireNonEmpty(input.id, `${path}.id`),
114
- version: optionalNonEmpty(input.version, `${path}.version`),
115
- hash: optionalNonEmpty(input.hash, `${path}.hash`)
116
- });
117
- }
118
- function normalizeDimensions(input) {
119
- const out = {};
120
- for (const key of Object.keys(input).sort()) {
121
- const value = input[key];
122
- requireNonEmpty(key, "dimensions.<key>");
123
- if (value !== null && typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") throw new AgentProfileCellValidationError("expected primitive dimension value", `dimensions.${key}`);
124
- if (typeof value === "number" && !Number.isFinite(value)) throw new AgentProfileCellValidationError("expected finite number", `dimensions.${key}`);
125
- out[key] = value;
126
- }
127
- return out;
128
- }
129
- function compactObject(input) {
130
- const out = {};
131
- for (const [key, value] of Object.entries(input)) if (value !== void 0) out[key] = value;
132
- return out;
133
- }
134
- function nonEmptyRecord(input) {
135
- return Object.keys(input).length > 0 ? input : void 0;
136
- }
137
- function validateSource(value, path) {
138
- if (value === null || typeof value !== "object" || Array.isArray(value)) throw new AgentProfileCellValidationError("expected object", path);
139
- const rec = value;
140
- expectString(rec.kind, `${path}.kind`);
141
- requireSha256Hex(rec.hash, `${path}.hash`);
142
- }
143
- function validateHarness(value, path) {
144
- if (value === null || typeof value !== "object" || Array.isArray(value)) throw new AgentProfileCellValidationError("expected object", path);
145
- const rec = value;
146
- expectString(rec.id, `${path}.id`);
147
- if (rec.version !== void 0) expectString(rec.version, `${path}.version`);
148
- if (rec.hash !== void 0) expectString(rec.hash, `${path}.hash`);
149
- }
150
- function validateDimensions(value, path) {
151
- if (value === null || typeof value !== "object" || Array.isArray(value)) throw new AgentProfileCellValidationError("expected object", path);
152
- normalizeDimensions(value);
153
- }
154
- function assertJson(value, path) {
155
- if (value === null) return;
156
- const type = typeof value;
157
- if (type === "string" || type === "boolean") return;
158
- if (type === "number") {
159
- if (!Number.isFinite(value)) throw new AgentProfileCellValidationError("expected finite number", path);
160
- return;
161
- }
162
- if (Array.isArray(value)) {
163
- value.forEach((item, index) => {
164
- assertJson(item, `${path}[${index}]`);
165
- });
166
- return;
167
- }
168
- if (type === "object") {
169
- for (const [key, nested] of Object.entries(value)) {
170
- requireNonEmpty(key, `${path}.<key>`);
171
- assertJson(nested, `${path}.${key}`);
172
- }
173
- return;
174
- }
175
- throw new AgentProfileCellValidationError("expected JSON-compatible value", path);
176
- }
177
- function expectLiteral(value, expected, path) {
178
- if (value !== expected) throw new AgentProfileCellValidationError(`expected ${expected}`, path);
179
- }
180
- function expectString(value, path) {
181
- if (typeof value !== "string" || value.length === 0) throw new AgentProfileCellValidationError("expected non-empty string", path);
182
- }
183
- function requireNonEmpty(value, path) {
184
- if (typeof value !== "string" || value.length === 0) throw new AgentProfileCellValidationError("expected non-empty string", path);
185
- return value;
186
- }
187
- function optionalNonEmpty(value, path) {
188
- if (value === void 0) return void 0;
189
- return requireNonEmpty(value, path);
190
- }
191
- function requireSha256Hex(value, path) {
192
- if (typeof value !== "string" || !SHA256_HEX.test(value)) throw new AgentProfileCellValidationError("expected 64 lowercase sha256 hex chars", path);
193
- return value;
194
- }
195
- /** Canonical `sourceProfile.kind` values. Two products fingerprinting the
196
- * same canonical profile MUST use the same kind for their cells to share
197
- * `sourceProfile.hash`. Extend rather than create new strings — adding a
198
- * new kind is a deliberate cross-product schema change. */
199
- const AGENT_PROFILE_KINDS = {
200
- /** A profile declared via `defineAgentProfile(...)` from
201
- * `@tangle-network/agent-interface`. The default kind for router-backed
202
- * and sandbox-backed products. */
203
- AGENT_INTERFACE_PROFILE: "agent-interface-profile" };
204
- /** Canonicalize an arbitrary value into `AgentProfileJson` by JSON
205
- * round-trip. Throws when the value contains anything not representable
206
- * as JSON (functions, BigInt, cycles) — non-portable profiles fail loud
207
- * rather than silently dropping fields. */
208
- function toAgentProfileJson(value) {
209
- let serialized;
210
- try {
211
- serialized = JSON.stringify(value);
212
- } catch (err) {
213
- throw new AgentProfileCellValidationError(`agent profile must be JSON-serializable: ${err instanceof Error ? err.message : String(err)}`, "sourceProfile.profile");
214
- }
215
- if (serialized === void 0) throw new AgentProfileCellValidationError("agent profile must be JSON-serializable (got undefined after JSON.stringify)", "sourceProfile.profile");
216
- return JSON.parse(serialized);
217
- }
218
- /** Higher-level helper that hard-codes the canonical
219
- * `agent-interface-profile` kind plus the JSON canonicalization. Equivalent
220
- * to calling `buildAgentProfileCell` with `profileId = \`${name}@${version}\``
221
- * and `sourceProfile = { kind: AGENT_INTERFACE_PROFILE, profile: <round-tripped> }`.
222
- *
223
- * Use this from any product consuming an agent-interface `AgentProfile`; the
224
- * manual `buildAgentProfileCell` call is reserved for advanced cases
225
- * (custom kinds, pre-computed source hashes, alternate profileId
226
- * conventions). */
227
- async function buildAgentInterfaceProfileCell(profile, input) {
228
- if (!profile || typeof profile !== "object") throw new AgentProfileCellValidationError("AgentProfile must be an object", "profile");
229
- if (typeof profile.name !== "string" || profile.name.length === 0) throw new AgentProfileCellValidationError("AgentProfile must have a non-empty `name`", "profile.name");
230
- if (typeof profile.version !== "string" || profile.version.length === 0) throw new AgentProfileCellValidationError("AgentProfile must have a non-empty `version`", "profile.version");
231
- return buildAgentProfileCell({
232
- ...input,
233
- profileId: `${profile.name}@${profile.version}`,
234
- sourceProfile: {
235
- kind: AGENT_PROFILE_KINDS.AGENT_INTERFACE_PROFILE,
236
- profile: toAgentProfileJson(profile)
237
- }
238
- });
239
- }
240
- //#endregion
1
+ import { a as assertRunAgentProfileCell, c as groupRunsByAgentProfileCell, d as validateAgentProfileCell, f as verifyAgentProfileCell, i as agentProfileCellKey, l as requireAgentProfileCell, n as AgentProfileCellValidationError, o as buildAgentInterfaceProfileCell, r as agentProfileCellHashMaterial, s as buildAgentProfileCell, t as AGENT_PROFILE_KINDS, u as toAgentProfileJson } from "./agent-profile-cell-OhuTee9n.js";
241
2
  export { AGENT_PROFILE_KINDS, AgentProfileCellValidationError, agentProfileCellHashMaterial, agentProfileCellKey, assertRunAgentProfileCell, buildAgentInterfaceProfileCell, buildAgentProfileCell, groupRunsByAgentProfileCell, requireAgentProfileCell, toAgentProfileJson, validateAgentProfileCell, verifyAgentProfileCell };
242
-
243
- //# sourceMappingURL=profile-cell.js.map
@@ -1,5 +1,5 @@
1
1
  import { t as TraceEmitter } from "./emitter-CPBAhxum.js";
2
- import { s as validateRunRecord } from "./run-record-CN8Zd21B.js";
2
+ import { s as validateRunRecord } from "./run-record-BIwU2wdV.js";
3
3
  import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
4
4
  import { dirname } from "node:path";
5
5
  //#region src/action-policy.ts
@@ -1455,4 +1455,4 @@ function controlFailureClassFromVerification(verification) {
1455
1455
  //#endregion
1456
1456
  export { observeAll as _, jsonlReviewStore as a, scoreFromEvals as c, runAgentControlLoop as d, stopOnNoProgress as f, noProgressDetector as g, errorStreakDetector as h, inMemoryReviewStore as i, allCriticalPassed as l, subjectiveEval as m, runProposeReviewAsControlLoop as n, runProposeReview as o, stopOnRepeatedAction as p, createLlmReviewer as r, controlRunToRunRecord as s, controlFailureClassFromVerification as t, objectiveEval as u, repeatedActionDetector as v, evaluateActionPolicy as y };
1457
1457
 
1458
- //# sourceMappingURL=propose-review-control-Bqb7daEJ.js.map
1458
+ //# sourceMappingURL=propose-review-control-SQ-n9-We.js.map