@tangle-network/agent-eval 0.204.0 → 0.205.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/analyst/index.d.ts +1 -1
  3. package/dist/analyst/index.d.ts.map +1 -1
  4. package/dist/analyst/index.js +1 -1
  5. package/dist/{analyze-runs-BrIibNd0.js → analyze-runs-d5dcMlxi.js} +9 -9
  6. package/dist/{analyze-runs-BrIibNd0.js.map → analyze-runs-d5dcMlxi.js.map} +1 -1
  7. package/dist/baseline-Dm8966du.js +259 -0
  8. package/dist/baseline-Dm8966du.js.map +1 -0
  9. package/dist/{benchmark-command-Jv_puUGM.js → benchmark-command-BQhi_BVO.js} +6 -3
  10. package/dist/benchmark-command-BQhi_BVO.js.map +1 -0
  11. package/dist/benchmarks/index.js +2 -2
  12. package/dist/builder-eval/index.js +1 -1
  13. package/dist/campaign/index.js +9 -9
  14. package/dist/{campaign-DYhg4SjN.js → campaign-0lmkAMpE.js} +11 -11
  15. package/dist/{campaign-DYhg4SjN.js.map → campaign-0lmkAMpE.js.map} +1 -1
  16. package/dist/{campaign-evidence-Dt_rWPk2.js → campaign-evidence-C__cUpCt.js} +2 -2
  17. package/dist/{campaign-evidence-Dt_rWPk2.js.map → campaign-evidence-C__cUpCt.js.map} +1 -1
  18. package/dist/cli.js +5 -5
  19. package/dist/contract/index.js +9 -9
  20. package/dist/{define-agent-eval-B25Cc3ki.js → define-agent-eval-CeYrXpl7.js} +4 -4
  21. package/dist/{define-agent-eval-B25Cc3ki.js.map → define-agent-eval-CeYrXpl7.js.map} +1 -1
  22. package/dist/{descriptive-D9LUFk1-.js → descriptive-CnU8Yq29.js} +2 -2
  23. package/dist/{descriptive-D9LUFk1-.js.map → descriptive-CnU8Yq29.js.map} +1 -1
  24. package/dist/diagnosis/index.js +1 -1
  25. package/dist/{eval-campaign-ha_aWtk7.js → eval-campaign-DsRmYsQI.js} +2 -2
  26. package/dist/{eval-campaign-ha_aWtk7.js.map → eval-campaign-DsRmYsQI.js.map} +1 -1
  27. package/dist/experiment/index.js +9 -9
  28. package/dist/index.d.ts +60 -2
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +96 -19
  31. package/dist/index.js.map +1 -1
  32. package/dist/{internal-BOe3zmjQ.js → internal-CRHwS9iz.js} +3 -3
  33. package/dist/internal-CRHwS9iz.js.map +1 -0
  34. package/dist/jev.js +1 -1
  35. package/dist/judge-calibration-DFtEMlde.d.ts.map +1 -1
  36. package/dist/{judge-calibration-C5zgtiJT.js → judge-calibration-N44V04Se.js} +7 -17
  37. package/dist/judge-calibration-N44V04Se.js.map +1 -0
  38. package/dist/{llm-judge-DyZdrp6I.js → llm-judge-Bka5q-ds.js} +8 -8
  39. package/dist/{llm-judge-DyZdrp6I.js.map → llm-judge-Bka5q-ds.js.map} +1 -1
  40. package/dist/matrix/index.js +1 -1
  41. package/dist/{matrix-DnlHn5x1.js → matrix-_BV9-Lk5.js} +12 -9
  42. package/dist/matrix-_BV9-Lk5.js.map +1 -0
  43. package/dist/meta-eval/index.js +2 -2
  44. package/dist/multishot/golden/index.js +1 -1
  45. package/dist/multishot/index.js +1 -1
  46. package/dist/normal-DsJZtrJc.js +25 -0
  47. package/dist/normal-DsJZtrJc.js.map +1 -0
  48. package/dist/openapi.json +1 -1
  49. package/dist/{paired-arms-DpS_h8ON.js → paired-arms-Dsu-r6xd.js} +6 -27
  50. package/dist/paired-arms-Dsu-r6xd.js.map +1 -0
  51. package/dist/{paired-binary-OMBVRtc-.js → paired-binary-DpwwK1fU.js} +2 -2
  52. package/dist/{paired-binary-OMBVRtc-.js.map → paired-binary-DpwwK1fU.js.map} +1 -1
  53. package/dist/{paired-promotion-decision-DhrmjdV8.js → paired-promotion-decision-CO0kA0bq.js} +3 -3
  54. package/dist/{paired-promotion-decision-DhrmjdV8.js.map → paired-promotion-decision-CO0kA0bq.js.map} +1 -1
  55. package/dist/{paired-tests-Ccr16gcW.js → paired-tests-jbwPdSz5.js} +3 -3
  56. package/dist/{paired-tests-Ccr16gcW.js.map → paired-tests-jbwPdSz5.js.map} +1 -1
  57. package/dist/pipelines/index.d.ts +1 -1
  58. package/dist/pipelines/index.js +2 -2
  59. package/dist/{power-and-mde-bie6i965.js → power-and-mde-fK5Qocwo.js} +3 -3
  60. package/dist/{power-and-mde-bie6i965.js.map → power-and-mde-fK5Qocwo.js.map} +1 -1
  61. package/dist/{produced-state-DLToUXrD.js → produced-state-FdbE-88t.js} +3 -3
  62. package/dist/{produced-state-DLToUXrD.js.map → produced-state-FdbE-88t.js.map} +1 -1
  63. package/dist/{promotion-policy-BI1RxzwD.js → promotion-policy-BSbTAMtE.js} +4 -4
  64. package/dist/{promotion-policy-BI1RxzwD.js.map → promotion-policy-BSbTAMtE.js.map} +1 -1
  65. package/dist/quantile--0yb07pD.js +15 -0
  66. package/dist/quantile--0yb07pD.js.map +1 -0
  67. package/dist/{report-command-D0XL2Cvi.js → report-command-JrjiWReS.js} +2 -2
  68. package/dist/{report-command-D0XL2Cvi.js.map → report-command-JrjiWReS.js.map} +1 -1
  69. package/dist/reporting.js +4 -4
  70. package/dist/{reward-hacking-C-a__ShZ.js → reward-hacking-BFcQgkux.js} +2 -2
  71. package/dist/{reward-hacking-C-a__ShZ.js.map → reward-hacking-BFcQgkux.js.map} +1 -1
  72. package/dist/rl.js +7 -7
  73. package/dist/{rubric-predictive-validity-B0Pg-3I5.js → rubric-predictive-validity-BsgkBfT0.js} +3 -3
  74. package/dist/{rubric-predictive-validity-B0Pg-3I5.js.map → rubric-predictive-validity-BsgkBfT0.js.map} +1 -1
  75. package/dist/search/index.js +2 -2
  76. package/dist/{search-kernel-Dpniloks.js → search-kernel-CsISc5t8.js} +5 -5
  77. package/dist/{search-kernel-Dpniloks.js.map → search-kernel-CsISc5t8.js.map} +1 -1
  78. package/dist/{search-summary-C1nAHgkB.js → search-summary-BZkoLwbB.js} +4 -4
  79. package/dist/{search-summary-C1nAHgkB.js.map → search-summary-BZkoLwbB.js.map} +1 -1
  80. package/dist/{sequential-DWn_np6P.js → sequential-7uxpO0Vm.js} +2 -2
  81. package/dist/{sequential-DWn_np6P.js.map → sequential-7uxpO0Vm.js.map} +1 -1
  82. package/dist/{skillopt-optimization-method-Dz5CGZb8.js → skillopt-optimization-method-bEm4jYV4.js} +4 -4
  83. package/dist/{skillopt-optimization-method-Dz5CGZb8.js.map → skillopt-optimization-method-bEm4jYV4.js.map} +1 -1
  84. package/dist/{statistical-heldout-CNLOvRq_.js → statistical-heldout-C26hOFWD.js} +3 -3
  85. package/dist/{statistical-heldout-CNLOvRq_.js.map → statistical-heldout-C26hOFWD.js.map} +1 -1
  86. package/dist/{student-t-BBZYka0E.js → student-t-BQeKJx2N.js} +2 -2
  87. package/dist/{student-t-BBZYka0E.js.map → student-t-BQeKJx2N.js.map} +1 -1
  88. package/dist/{summary-report-DLzptLSA.js → summary-report-BG6-hOkm.js} +6 -6
  89. package/dist/{summary-report-DLzptLSA.js.map → summary-report-BG6-hOkm.js.map} +1 -1
  90. package/dist/supervisor-run/index.js +1 -1
  91. package/dist/{tool-waste-CP5DO383.d.ts → tool-waste-DxlebQkx.d.ts} +42 -2
  92. package/dist/tool-waste-DxlebQkx.d.ts.map +1 -0
  93. package/dist/{tool-waste-B-u3rzCz.js → tool-waste-x_E8h9Ih.js} +3 -3
  94. package/dist/{tool-waste-B-u3rzCz.js.map → tool-waste-x_E8h9Ih.js.map} +1 -1
  95. package/dist/trace-repair/index.js +1 -1
  96. package/dist/{tree-D48IJUK0.js → tree-CAQflhLR.js} +5 -5
  97. package/dist/{tree-D48IJUK0.js.map → tree-CAQflhLR.js.map} +1 -1
  98. package/docs/concepts.md +21 -0
  99. package/package.json +1 -1
  100. package/dist/baseline-CVKsfWTg.js +0 -150
  101. package/dist/baseline-CVKsfWTg.js.map +0 -1
  102. package/dist/benchmark-command-Jv_puUGM.js.map +0 -1
  103. package/dist/internal-BOe3zmjQ.js.map +0 -1
  104. package/dist/judge-calibration-C5zgtiJT.js.map +0 -1
  105. package/dist/matrix-DnlHn5x1.js.map +0 -1
  106. package/dist/paired-arms-DpS_h8ON.js.map +0 -1
  107. package/dist/tool-waste-CP5DO383.d.ts.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"internal-BOe3zmjQ.js","names":[],"sources":["../src/math/special-functions.ts","../src/statistics/internal.ts"],"sourcesContent":["/** Lanczos approximation to ln Gamma(z). */\nexport function lnGamma(z: number): number {\n const g = 7\n const coefficients = [\n 0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313,\n -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6,\n 1.5056327351493116e-7,\n ]\n if (z < 0.5) {\n return Math.log(Math.PI / Math.sin(Math.PI * z)) - lnGamma(1 - z)\n }\n z -= 1\n let x = coefficients[0]!\n for (let i = 1; i < g + 2; i++) x += coefficients[i]! / (z + i)\n const t = z + g + 0.5\n return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(x)\n}\n\n/**\n * Regularized incomplete beta function I_x(a, b).\n *\n * The Lentz continued fraction converges only for `x < (a+1)/(a+b+2)`; outside\n * that domain it must be reached through the symmetry `I_x(a,b) = 1 −\n * I_{1−x}(b,a)`. `studentTCdf` drives `x → 1` as `|t| → 0`, so the mirrored\n * branch is the one every near-null t-statistic takes.\n */\nexport function regularizedIncompleteBeta(x: number, a: number, b: number): number {\n if (x <= 0) return 0\n if (x >= 1) return 1\n const logBeta = lnGamma(a) + lnGamma(b) - lnGamma(a + b)\n // x^a·(1−x)^b / B(a,b) — symmetric under (x,a,b) → (1−x,b,a), so the\n // mirrored branch reuses it unchanged.\n const front = Math.exp(Math.log(x) * a + Math.log(1 - x) * b - logBeta)\n if (x < (a + 1) / (a + b + 2)) {\n return (front * betaContinuedFraction(x, a, b)) / a\n }\n return 1 - (front * betaContinuedFraction(1 - x, b, a)) / b\n}\n\n/** Modified Lentz evaluation of the beta continued fraction at `x`. */\nfunction betaContinuedFraction(x: number, a: number, b: number): number {\n const maxIterations = 300\n const epsilon = 3e-15\n let c = 1\n let d = 1 - ((a + b) * x) / (a + 1)\n if (Math.abs(d) < 1e-30) d = 1e-30\n d = 1 / d\n let fraction = d\n for (let m = 1; m <= maxIterations; m++) {\n const m2 = 2 * m\n let numerator = (m * (b - m) * x) / ((a + m2 - 1) * (a + m2))\n d = 1 + numerator * d\n if (Math.abs(d) < 1e-30) d = 1e-30\n c = 1 + numerator / c\n if (Math.abs(c) < 1e-30) c = 1e-30\n d = 1 / d\n fraction *= d * c\n numerator = -((a + m) * (a + b + m) * x) / ((a + m2) * (a + m2 + 1))\n d = 1 + numerator * d\n if (Math.abs(d) < 1e-30) d = 1e-30\n c = 1 + numerator / c\n if (Math.abs(c) < 1e-30) c = 1e-30\n d = 1 / d\n const delta = d * c\n fraction *= delta\n if (Math.abs(delta - 1) < epsilon) break\n }\n return fraction\n}\n","/**\n * Shared internals for the statistics modules. Nothing here is part of the\n * public statistics surface — `./index` does not re-export this module.\n */\n\nimport { ValidationError } from '../errors'\nimport { lnGamma } from '../math/special-functions'\nimport { mulberry32 } from './random'\n\n/** Every rank test refuses non-finite input. Beyond the arithmetic being\n * undefined, the tie-grouping scan compares values with `===`, and\n * `NaN === NaN` is false, so a NaN would leave the group boundary unable to\n * advance and spin the loop forever. */\nexport function assertFiniteSample(fn: string, label: string, xs: readonly number[]): void {\n for (let i = 0; i < xs.length; i++) {\n if (!Number.isFinite(xs[i])) {\n throw new ValidationError(`${fn}: ${label}[${i}] must be finite, got ${xs[i]}`)\n }\n }\n}\n\n/**\n * Two-sided exact p-value for b successes out of (b + c) Bernoulli(0.5) trials —\n * the exact-binomial core of {@link mcnemar}. `min(1, 2·P(X ≤ min(b,c)))`. No\n * discordant pairs ⇒ no evidence ⇒ p = 1. Summed in log space (lnGamma) so it\n * stays exact at large discordant counts without overflow.\n */\nexport function binomialSignTwoSided(b: number, c: number): number {\n const nd = b + c\n if (nd === 0) return 1\n return Math.min(1, 2 * binomialHalfLowerTail(Math.min(b, c), nd))\n}\n\n/** P(X >= successes) for X ~ Binomial(n, 0.5). */\nexport function binomialHalfUpperTail(successes: number, n: number): number {\n if (successes <= 0) return 1\n if (successes > n) return 0\n\n // Use the smaller side of the distribution. For lower thresholds the\n // complement sums at most half the mass; for upper thresholds symmetry\n // maps the upper tail to a lower tail without subtraction.\n if (successes <= n / 2) {\n return Math.max(0, 1 - binomialHalfLowerTail(successes - 1, n))\n }\n return binomialHalfLowerTail(n - successes, n)\n}\n\n/** P(X <= maxSuccesses) for X ~ Binomial(n, 0.5), accumulated in log space. */\nfunction binomialHalfLowerTail(maxSuccesses: number, n: number): number {\n if (maxSuccesses < 0) return 0\n if (maxSuccesses >= n) return 1\n if (maxSuccesses === 0) return 2 ** -n\n\n const logHalfN = n * Math.log(0.5)\n let logTail = Number.NEGATIVE_INFINITY\n for (let i = 0; i <= maxSuccesses; i++) {\n const logChoose = lnGamma(n + 1) - lnGamma(i + 1) - lnGamma(n - i + 1)\n logTail = logAddExp(logTail, logChoose + logHalfN)\n }\n return Math.min(1, Math.exp(logTail))\n}\n\nfunction logAddExp(a: number, b: number): number {\n if (a === Number.NEGATIVE_INFINITY) return b\n if (b === Number.NEGATIVE_INFINITY) return a\n const max = Math.max(a, b)\n const min = Math.min(a, b)\n return max + Math.log1p(Math.exp(min - max))\n}\n\n/** Standard-normal inverse CDF (Acklam approximation). */\nexport function zQuantile(p: number): number {\n if (p <= 0 || p >= 1) {\n if (p === 0) return -Infinity\n if (p === 1) return Infinity\n return NaN\n }\n const a = [\n -3.969683028665376e1, 2.209460984245205e2, -2.759285104469687e2, 1.38357751867269e2,\n -3.066479806614716e1, 2.506628277459239,\n ]\n const b = [\n -5.447609879822406e1, 1.615858368580409e2, -1.556989798598866e2, 6.680131188771972e1,\n -1.328068155288572e1,\n ]\n const c = [\n -7.784894002430293e-3, -3.223964580411365e-1, -2.400758277161838, -2.549732539343734,\n 4.374664141464968, 2.938163982698783,\n ]\n const d = [7.784695709041462e-3, 3.224671290700398e-1, 2.445134137142996, 3.754408661907416]\n const pLow = 0.02425\n const pHigh = 1 - pLow\n let q: number\n let r: number\n if (p < pLow) {\n q = Math.sqrt(-2 * Math.log(p))\n return (\n (((((c[0]! * q + c[1]!) * q + c[2]!) * q + c[3]!) * q + c[4]!) * q + c[5]!) /\n ((((d[0]! * q + d[1]!) * q + d[2]!) * q + d[3]!) * q + 1)\n )\n }\n if (p <= pHigh) {\n q = p - 0.5\n r = q * q\n return (\n ((((((a[0]! * r + a[1]!) * r + a[2]!) * r + a[3]!) * r + a[4]!) * r + a[5]!) * q) /\n (((((b[0]! * r + b[1]!) * r + b[2]!) * r + b[3]!) * r + b[4]!) * r + 1)\n )\n }\n q = Math.sqrt(-2 * Math.log(1 - p))\n return (\n -(((((c[0]! * q + c[1]!) * q + c[2]!) * q + c[3]!) * q + c[4]!) * q + c[5]!) /\n ((((d[0]! * q + d[1]!) * q + d[2]!) * q + d[3]!) * q + 1)\n )\n}\n\nexport function medianInPlace(xs: number[]): number {\n if (xs.length === 0) return 0\n xs.sort((a, b) => a - b)\n const mid = Math.floor(xs.length / 2)\n return xs.length % 2 === 0 ? (xs[mid - 1]! + xs[mid]!) / 2 : xs[mid]!\n}\n\n/**\n * PRNG for every resampling path in this module.\n *\n * With no caller seed the seed is DERIVED FROM THE DATA rather than taken from\n * `Math.random`, so re-running the same input reproduces the same interval —\n * a gate verdict that cannot be re-derived is not evidence. Distinct data\n * still gets a distinct stream. Same pattern as `promotion-gate.ts`.\n */\nexport function makeRng(\n seed: number | undefined,\n ...series: readonly (readonly number[])[]\n): () => number {\n return mulberry32(seed ?? seedFromData(series))\n}\n\n/** FNV-1a over the IEEE-754 bytes of every observation. */\nfunction seedFromData(series: readonly (readonly number[])[]): number {\n const view = new DataView(new ArrayBuffer(8))\n // 32-bit FNV-1a over the IEEE-754 BYTES of each observation, not over a\n // string. Frozen: it seeds the unseeded bootstrap from the data itself, so a\n // change moves every interval this package has already published. The\n // string-input variants elsewhere cannot be substituted here.\n let hash = 0x811c9dc5\n for (const xs of series) {\n for (const x of xs) {\n view.setFloat64(0, x)\n for (let byte = 0; byte < 8; byte++) {\n hash = Math.imul(hash ^ view.getUint8(byte), 0x01000193)\n }\n }\n // Separator, so ([1],[2]) and ([1,2],[]) do not collide.\n hash = Math.imul(hash ^ 0xff, 0x01000193)\n }\n return hash | 0\n}\n\n/** Order-independent seed for a symmetric two-sample statistic. */\nexport function symmetricTwoSampleSeed(a: readonly number[], b: readonly number[]): number {\n const sortedA = [...a].sort((left, right) => left - right)\n const sortedB = [...b].sort((left, right) => left - right)\n const forward = seedFromData([sortedA, sortedB]) >>> 0\n const reversed = seedFromData([sortedB, sortedA]) >>> 0\n return Math.min(forward, reversed)\n}\n"],"mappings":";;;;AACA,SAAgB,QAAQ,GAAmB;CACzC,MAAM,IAAI;CACV,MAAM,eAAe;EACnB;EAAqB;EAAmB;EAAqB;EAC7D;EAAqB;EAAoB;EAAsB;EAC/D;CACF;CACA,IAAI,IAAI,IACN,OAAO,KAAK,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,CAAC,CAAC,IAAI,QAAQ,IAAI,CAAC;CAElE,KAAK;CACL,IAAI,IAAI,aAAa;CACrB,KAAK,IAAI,IAAI,GAAG,IAAI,GAAO,KAAK,KAAK,aAAa,MAAO,IAAI;CAC7D,MAAM,IAAI,IAAI,IAAI;CAClB,OAAO,KAAM,KAAK,IAAI,IAAI,KAAK,EAAE,KAAK,IAAI,MAAO,KAAK,IAAI,CAAC,IAAI,IAAI,KAAK,IAAI,CAAC;AAC/E;;;;;;;;;AAUA,SAAgB,0BAA0B,GAAW,GAAW,GAAmB;CACjF,IAAI,KAAK,GAAG,OAAO;CACnB,IAAI,KAAK,GAAG,OAAO;CACnB,MAAM,UAAU,QAAQ,CAAC,IAAI,QAAQ,CAAC,IAAI,QAAQ,IAAI,CAAC;CAGvD,MAAM,QAAQ,KA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AO,IAAI,EAAE,MAAO,IAAI,EAAE,MAAO,IAAI;AAE3D;AAEA,SAAgB,cAAc,IAAsB;CAClD,IAAI,GAAG,WAAW,GAAG,OAAO;CAC5B,GAAG,MAAM,GAAG,MAAM,IAAI,CAAC;CACvB,MAAM,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;CACpC,OAAO,GAAG,SAAS,MAAM,KAAK,GAAG,MAAM,KAAM,GAAG,QAAS,IAAI,GAAG;AAClE;;;;;;;;;AAUA,SAAgB,QACd,MACA,GAAG,QACW;CACd,OAAO,WAAW,QAAQ,aAAa,MAAM,CAAC;AAChD;;AAGA,SAAS,aAAa,QAAgD;CACpE,MAAM,uBAAO,IAAI,yBAAS,IAAI,YAAY,CAAC,CAAC;CAK5C,IAAI,OAAO;CACX,KAAK,MAAM,MAAM,QAAQ;EACvB,KAAK,MAAM,KAAK,IAAI;GAClB,KAAK,WAAW,GAAG,CAAC;GACpB,KAAK,IAAI,OAAO,GAAG,OAAO,GAAG,QAC3B,OAAO,KAAK,KAAK,OAAO,KAAK,SAAS,IAAI,GAAG,QAAU;EAE3D;EAEA,OAAO,KAAK,KAAK,OAAO,KAAM,QAAU;CAC1C;CACA,OAAO,OAAO;AAChB;;AAGA,SAAgB,uBAAuB,GAAsB,GAA8B;CACzF,MAAM,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,MAAM,UAAU,OAAO,KAAK;CACzD,MAAM,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,MAAM,UAAU,OAAO,KAAK;CACzD,MAAM,UAAU,aAAa,CAAC,SAAS,OAAO,CAAC,MAAM;CACrD,MAAM,WAAW,aAAa,CAAC,SAAS,OAAO,CAAC,MAAM;CACtD,OAAO,KAAK,IAAI,SAAS,QAAQ;AACnC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"judge-calibration-C5zgtiJT.js","names":[],"sources":["../src/judge-calibration.ts"],"sourcesContent":["/**\n * Judge calibration — measure judge quality against human gold + bias.\n *\n * Workflow:\n * 1. Build a golden set: {itemId, humanScore}[].\n * 2. Run candidate judges; each produces {itemId, score}.\n * 3. `calibrateJudge(golden, candidate)` reports κ + Pearson + MAE.\n * 4. `calibrateJudgeContinuous(golden, candidate)` adds quadratic-weighted\n * κ over the un-rounded [0,1] scores plus ICC(2,1), Pearson, Spearman,\n * and bootstrap CIs — use this for fine-grained judges where rounding\n * to int discards information (e.g. 0.78 vs 0.81 both round to 1 and\n * look \"perfectly agreed\" to integer κ).\n * 5. Run bias probes (positional, verbosity, self-preference) to\n * detect systematic score inflation.\n * 6. For N≥2 judges on the same items, `continuousAgreement(scores)`\n * reports ICC(2,1) + κ_w + Pearson + Spearman with bootstrap CIs.\n *\n * Returns actionable diagnostics, not a single number. Consumers then\n * decide whether to trust the judge, retrain it, or add a tie-breaker.\n */\n\nimport { pearsonR, spearmanR } from './statistics/descriptive'\nimport { mulberry32 } from './statistics/random'\n\nexport interface GoldenItem {\n itemId: string\n humanScore: number\n /** Optional group used for per-group bias audits (e.g. model-of-output family). */\n group?: string\n}\n\nexport interface CandidateScore {\n itemId: string\n score: number\n /** Optional — enables positional-bias analysis (did order matter?). */\n positionOfAInput?: 'first' | 'second'\n}\n\nexport interface CalibrationResult {\n n: number\n pearson: number\n /** Cohen's κ with quadratic weights over integer-rounded scores. */\n kappa: number\n /** Mean absolute error vs human. */\n mae: number\n /** Worst-5 miscalibrations (largest |judge - human|). */\n worstItems: Array<{ itemId: string; judge: number; human: number; delta: number }>\n}\n\n/**\n * Measure judge quality against human gold labels: computes Cohen's κ, Pearson correlation, and MAE over matched item ids.\n */\nexport function calibrateJudge(\n golden: GoldenItem[],\n candidate: CandidateScore[],\n): CalibrationResult {\n const map = new Map<string, { h: number; j: number }>()\n for (const g of golden) map.set(g.itemId, { h: g.humanScore, j: NaN })\n for (const c of candidate) {\n const entry = map.get(c.itemId)\n if (entry) entry.j = c.score\n }\n const common = [...map.values()].filter((v) => Number.isFinite(v.j))\n const n = common.length\n if (n < 2) {\n return { n, pearson: NaN, kappa: NaN, mae: NaN, worstItems: [] }\n }\n const humans = common.map((c) => c.h)\n const judges = common.map((c) => c.j)\n const pearson = pearsonR(humans, judges)\n const kappa = weightedKappa(humans.map(Math.round), judges.map(Math.round))\n const absDiffs = common.map((c) => Math.abs(c.j - c.h))\n const mae = absDiffs.reduce((a, b) => a + b, 0) / n\n const worst = [...map.entries()]\n .filter(([, v]) => Number.isFinite(v.j))\n .map(([itemId, v]) => ({ itemId, judge: v.j, human: v.h, delta: Math.abs(v.j - v.h) }))\n .sort((a, b) => b.delta - a.delta)\n .slice(0, 5)\n return { n, pearson, kappa, mae, worstItems: worst }\n}\n\nexport interface PositionalBiasResult {\n /**\n * Score delta (first-position - second-position) averaged across items\n * presented in both positions. Non-zero = positional bias.\n */\n avgDelta: number\n n: number\n}\n\n/**\n * Feed the same items to the judge twice with A/B swapped and pass all\n * results here. Items that don't appear in both positions are ignored.\n */\nexport function positionalBias(scores: CandidateScore[]): PositionalBiasResult {\n const pairs = new Map<string, { first?: number; second?: number }>()\n for (const s of scores) {\n const slot = pairs.get(s.itemId) ?? {}\n if (s.positionOfAInput === 'first') slot.first = s.score\n else if (s.positionOfAInput === 'second') slot.second = s.score\n pairs.set(s.itemId, slot)\n }\n const deltas: number[] = []\n for (const { first, second } of pairs.values()) {\n if (first !== undefined && second !== undefined) deltas.push(first - second)\n }\n if (deltas.length === 0) return { avgDelta: 0, n: 0 }\n return { avgDelta: deltas.reduce((a, b) => a + b, 0) / deltas.length, n: deltas.length }\n}\n\nexport interface VerbosityBiasResult {\n /** Pearson correlation between output length and score. Strong positive = verbosity bias. */\n pearson: number\n n: number\n}\n\nexport function verbosityBias(\n samples: Array<{ outputLen: number; score: number }>,\n): VerbosityBiasResult {\n const n = samples.length\n if (n < 3) return { pearson: NaN, n }\n return {\n pearson: pearsonR(\n samples.map((s) => s.outputLen),\n samples.map((s) => s.score),\n ),\n n,\n }\n}\n\nexport interface SelfPreferenceResult {\n /** Mean judge score when judge's family matches output's family. */\n inFamilyMean: number\n outOfFamilyMean: number\n deltaMean: number\n n: number\n}\n\n/**\n * Pass the same scenarios scored with judge-model X grading outputs from\n * model X (in-family) and model Y (out-of-family). Non-zero delta\n * indicates self-preference.\n */\nexport function selfPreference(\n samples: Array<{ score: number; inFamily: boolean }>,\n): SelfPreferenceResult {\n const inF = samples.filter((s) => s.inFamily).map((s) => s.score)\n const outF = samples.filter((s) => !s.inFamily).map((s) => s.score)\n if (inF.length === 0 || outF.length === 0)\n return { inFamilyMean: 0, outOfFamilyMean: 0, deltaMean: 0, n: 0 }\n const inMean = inF.reduce((a, b) => a + b, 0) / inF.length\n const outMean = outF.reduce((a, b) => a + b, 0) / outF.length\n return {\n inFamilyMean: inMean,\n outOfFamilyMean: outMean,\n deltaMean: inMean - outMean,\n n: samples.length,\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────\n\n/** Quadratic weighted Cohen's κ over bounded integer scores. */\nfunction weightedKappa(a: number[], b: number[]): number {\n if (a.length !== b.length || a.length === 0) return NaN\n const min = Math.min(...a, ...b)\n const max = Math.max(...a, ...b)\n const K = max - min + 1\n if (K < 2) return 1\n const observed: number[][] = Array.from({ length: K }, () => new Array(K).fill(0))\n const rowMarg = new Array(K).fill(0)\n const colMarg = new Array(K).fill(0)\n for (let i = 0; i < a.length; i++) {\n const ai = a[i]! - min\n const bi = b[i]! - min\n const row = observed[ai]!\n row[bi] = (row[bi] ?? 0) + 1\n rowMarg[ai]++\n colMarg[bi]++\n }\n let num = 0\n let den = 0\n for (let i = 0; i < K; i++) {\n for (let j = 0; j < K; j++) {\n const w = (i - j) ** 2 / (K - 1) ** 2\n const expected = (rowMarg[i] * colMarg[j]) / a.length\n num += w * observed[i]![j]!\n den += w * expected\n }\n }\n if (den === 0) return 1\n return 1 - num / den\n}\n\n// ── Continuous-value inter-rater agreement ──────────────────────────\n//\n// `weightedKappa` above quantises to integers. For [0,1] judges that is\n// lossy: 0.78 and 0.81 both round to 1 and look identical to integer κ.\n// `continuousAgreement` keeps the original magnitudes:\n//\n// - κ_w : Cohen's weighted κ generalised to continuous scores. For two\n// raters, weighted κ = 1 − Σ w_ij·o_ij / Σ w_ij·e_ij collapses\n// into the closed form below when each \"category\" is the score\n// itself (Janson & Olsson 2001; Cohen 1968 quadratic weights).\n// - ICC : Intraclass Correlation Coefficient, ICC(2,1) per Shrout &\n// Fleiss (1979) — two-way random effects, absolute agreement,\n// single rater. The right reliability coefficient when judges\n// are a random sample of the judge population.\n// - r, ρ : Pearson + Spearman for sanity-check. Pearson catches linear\n// association regardless of scale; Spearman catches monotone\n// association regardless of distribution.\n// - CIs : Bootstrap percentile CIs over items (rows). Bias is preserved\n// because we resample the full row, i.e. a judge's vector\n// stays internally consistent within each bootstrap replicate.\n//\n// References:\n// - Shrout, P. E. & Fleiss, J. L. (1979). Intraclass correlations: uses\n// in assessing rater reliability. Psychological Bulletin, 86(2), 420.\n// - McGraw, K. O. & Wong, S. P. (1996). Forming inferences about some\n// intraclass correlation coefficients. Psychological Methods, 1, 30.\n// - Janson, H. & Olsson, U. (2001). A measure of agreement for interval\n// or nominal multivariate observations. Educ. Psychol. Meas., 61, 277.\n\nexport interface ContinuousAgreement {\n /** Cohen's κ_w with quadratic weights, computed on raw [0,1] scores. */\n weightedKappa: number\n /** ICC(2,1): two-way random effects, absolute agreement, single rater. */\n icc: number\n /** Pearson product-moment correlation (averaged over rater pairs if N>2). */\n pearson: number\n /** Spearman rank correlation (averaged over rater pairs if N>2). */\n spearman: number\n /** 95% bootstrap percentile CIs over items. */\n ci: {\n icc: [number, number]\n weightedKappa: [number, number]\n }\n /** Number of complete items (no NaN across raters). */\n n: number\n /** Number of raters. */\n raters: number\n}\n\nexport interface ContinuousAgreementOptions {\n /** Bootstrap iterations. Default 1000. Set to 0 to skip CIs (CI = [NaN, NaN]). */\n bootstrap?: number\n /** κ weighting scheme. Default 'quadratic'. */\n weights?: 'linear' | 'quadratic'\n /** PRNG seed for reproducible bootstrap. Default 0xC0FFEE. */\n seed?: number\n /** Confidence level for percentile CI. Default 0.95. */\n ciLevel?: number\n}\n\n/**\n * Inter-rater agreement on continuous (typically [0,1]) scores.\n *\n * `scores` has shape [n_items][n_raters]. Rows with any non-finite entry\n * are dropped. Returns NaN metrics if fewer than 2 raters or 2 complete\n * items remain.\n */\nexport function continuousAgreement(\n scores: number[][],\n opts: ContinuousAgreementOptions = {},\n): ContinuousAgreement {\n const bootstrap = opts.bootstrap ?? 1000\n const weights = opts.weights ?? 'quadratic'\n const seed = opts.seed ?? 0xc0ffee\n const ciLevel = opts.ciLevel ?? 0.95\n\n const matrix = scores.filter((row) => row.length >= 2 && row.every((v) => Number.isFinite(v)))\n const raters = matrix[0]?.length ?? 0\n // All rows must have the same rater count, else drop the offenders.\n const clean = matrix.filter((row) => row.length === raters)\n const nClean = clean.length\n\n if (nClean < 2 || raters < 2) {\n return {\n weightedKappa: NaN,\n icc: NaN,\n pearson: NaN,\n spearman: NaN,\n ci: { icc: [NaN, NaN], weightedKappa: [NaN, NaN] },\n n: nClean,\n raters,\n }\n }\n\n const kappa = continuousWeightedKappa(clean, weights)\n const icc = icc21(clean)\n const pearson = avgPairwise(clean, pearsonR)\n const spearman = avgPairwise(clean, spearmanR)\n\n const ciIcc: [number, number] = [NaN, NaN]\n const ciKappa: [number, number] = [NaN, NaN]\n if (bootstrap > 0) {\n const rng = mulberry32(seed)\n const iccs: number[] = []\n const kappas: number[] = []\n for (let b = 0; b < bootstrap; b++) {\n const sample: number[][] = new Array(nClean)\n for (let i = 0; i < nClean; i++) {\n sample[i] = clean[Math.floor(rng() * nClean)]!\n }\n const iccB = icc21(sample)\n const kB = continuousWeightedKappa(sample, weights)\n if (Number.isFinite(iccB)) iccs.push(iccB)\n if (Number.isFinite(kB)) kappas.push(kB)\n }\n const [lo, hi] = percentileBounds(ciLevel)\n if (iccs.length > 0) {\n iccs.sort((a, b) => a - b)\n ciIcc[0] = quantile(iccs, lo)\n ciIcc[1] = quantile(iccs, hi)\n }\n if (kappas.length > 0) {\n kappas.sort((a, b) => a - b)\n ciKappa[0] = quantile(kappas, lo)\n ciKappa[1] = quantile(kappas, hi)\n }\n }\n\n return {\n weightedKappa: kappa,\n icc,\n pearson,\n spearman,\n ci: { icc: ciIcc, weightedKappa: ciKappa },\n n: nClean,\n raters,\n }\n}\n\nexport interface ContinuousCalibrationResult extends CalibrationResult {\n /** Cohen's κ_w computed on raw (un-rounded) scores. */\n weightedKappaContinuous: number\n /** ICC(2,1) treating golden + candidate as two raters. */\n icc: number\n spearman: number\n ci: {\n icc: [number, number]\n weightedKappa: [number, number]\n }\n}\n\n/**\n * Extends `calibrateJudge` with continuous-value agreement metrics while\n * retaining its base calibration summary.\n */\nexport function calibrateJudgeContinuous(\n golden: GoldenItem[],\n candidate: CandidateScore[],\n opts: ContinuousAgreementOptions = {},\n): ContinuousCalibrationResult {\n const base = calibrateJudge(golden, candidate)\n const map = new Map<string, { h: number; j: number }>()\n for (const g of golden) map.set(g.itemId, { h: g.humanScore, j: NaN })\n for (const c of candidate) {\n const entry = map.get(c.itemId)\n if (entry) entry.j = c.score\n }\n const rows: number[][] = []\n for (const v of map.values()) {\n if (Number.isFinite(v.j)) rows.push([v.h, v.j])\n }\n const agreement = continuousAgreement(rows, opts)\n return {\n ...base,\n weightedKappaContinuous: agreement.weightedKappa,\n icc: agreement.icc,\n spearman: agreement.spearman,\n ci: agreement.ci,\n }\n}\n\n// ── Continuous-agreement internals ──────────────────────────────────\n\n/**\n * Quadratic-weighted κ on continuous scores. With weights w(x,y) = (x-y)^2\n * (or |x-y| for linear) the formula collapses to:\n *\n * κ_w = 1 − E_obs[w] / E_exp[w]\n *\n * where E_obs averages w over paired (a_i, b_i) and E_exp averages w over\n * the independent product distribution (sum_{i,j} w(a_i, b_j) / n^2).\n * The normalisation by (max-min)^2 in the integer version cancels in the\n * ratio, so we don't need it here. Generalises to N raters by averaging κ_w\n * over all rater pairs (mean pairwise weighted agreement).\n */\nfunction continuousWeightedKappa(rows: number[][], scheme: 'linear' | 'quadratic'): number {\n if (rows.length === 0) return NaN\n const raters = rows[0]!.length\n if (raters < 2) return NaN\n const wFn =\n scheme === 'linear'\n ? (x: number, y: number) => Math.abs(x - y)\n : (x: number, y: number) => (x - y) ** 2\n let sum = 0\n let pairs = 0\n for (let r1 = 0; r1 < raters; r1++) {\n for (let r2 = r1 + 1; r2 < raters; r2++) {\n const a = rows.map((row) => row[r1]!)\n const b = rows.map((row) => row[r2]!)\n const n = a.length\n let obs = 0\n for (let i = 0; i < n; i++) obs += wFn(a[i]!, b[i]!)\n obs /= n\n // Expected under independence: average of w over all i,j cross pairs.\n let exp = 0\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) exp += wFn(a[i]!, b[j]!)\n }\n exp /= n * n\n if (exp === 0) {\n // Degenerate: at least one rater is constant. Convention: perfect\n // agreement iff observed disagreement is also zero, else 0.\n sum += obs === 0 ? 1 : 0\n } else {\n sum += 1 - obs / exp\n }\n pairs++\n }\n }\n return pairs === 0 ? NaN : sum / pairs\n}\n\n/**\n * ICC(2,1) — two-way random effects, absolute agreement, single rater.\n *\n * ICC(2,1) = (MSR − MSE) / (MSR + (k−1)·MSE + k·(MSC − MSE)/n)\n *\n * where MSR = between-rows MS, MSC = between-columns MS, MSE = residual MS,\n * n = rows (items), k = columns (raters).\n */\nfunction icc21(rows: number[][]): number {\n const n = rows.length\n if (n < 2) return NaN\n const k = rows[0]!.length\n if (k < 2) return NaN\n\n // Row means.\n const rowMeans = rows.map((row) => row.reduce((s, v) => s + v, 0) / k)\n // Column means.\n const colMeans = new Array(k).fill(0)\n for (let j = 0; j < k; j++) {\n let s = 0\n for (let i = 0; i < n; i++) s += rows[i]![j]!\n colMeans[j] = s / n\n }\n // Grand mean.\n let grand = 0\n for (let i = 0; i < n; i++) grand += rowMeans[i]!\n grand /= n\n\n let ssR = 0\n for (let i = 0; i < n; i++) ssR += (rowMeans[i]! - grand) ** 2\n ssR *= k\n let ssC = 0\n for (let j = 0; j < k; j++) ssC += (colMeans[j]! - grand) ** 2\n ssC *= n\n let ssT = 0\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < k; j++) ssT += (rows[i]![j]! - grand) ** 2\n }\n const ssE = ssT - ssR - ssC\n\n const dfR = n - 1\n const dfC = k - 1\n const dfE = (n - 1) * (k - 1)\n const msR = ssR / dfR\n const msC = ssC / dfC\n const msE = dfE > 0 ? ssE / dfE : 0\n\n const denom = msR + (k - 1) * msE + (k * (msC - msE)) / n\n if (denom === 0) {\n // Degenerate (all values equal): convention = 1 if rows identical,\n // else 0. Identical rows ⇒ msR = 0 too, so msR − msE near 0.\n return msR === 0 && msE === 0 ? 1 : 0\n }\n return (msR - msE) / denom\n}\n\n/** Average pairwise statistic over all rater pairs. */\nfunction avgPairwise(rows: number[][], fn: (a: number[], b: number[]) => number): number {\n const k = rows[0]?.length ?? 0\n if (k < 2) return NaN\n let sum = 0\n let pairs = 0\n for (let i = 0; i < k; i++) {\n for (let j = i + 1; j < k; j++) {\n const a = rows.map((row) => row[i]!)\n const b = rows.map((row) => row[j]!)\n const r = fn(a, b)\n if (Number.isFinite(r)) {\n sum += r\n pairs++\n }\n }\n }\n return pairs === 0 ? NaN : sum / pairs\n}\n\nfunction percentileBounds(ciLevel: number): [number, number] {\n const tail = (1 - ciLevel) / 2\n return [tail, 1 - tail]\n}\n\n/** Linear-interpolated quantile of a pre-sorted ascending array. */\nfunction quantile(sorted: number[], q: number): number {\n if (sorted.length === 0) return NaN\n if (sorted.length === 1) return sorted[0]!\n const pos = q * (sorted.length - 1)\n const lo = Math.floor(pos)\n const hi = Math.ceil(pos)\n if (lo === hi) return sorted[lo]!\n const frac = pos - lo\n return sorted[lo]! * (1 - frac) + sorted[hi]! * frac\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAgB,eACd,QACA,WACmB;CACnB,MAAM,sBAAM,IAAI,IAAsC;CACtD,KAAK,MAAM,KAAK,QAAQ,IAAI,IAAI,EAAE,QAAQ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AM,IAAI,IAAI;AACxB;;AAGA,SAAS,SAAS,QAAkB,GAAmB;CACrD,IAAI,OAAO,WAAW,GAAG,OAAO;CAChC,IAAI,OAAO,WAAW,GAAG,OAAO,OAAO;CACvC,MAAM,MAAM,KAAK,OAAO,SAAS;CACjC,MAAM,KAAK,KAAK,MAAM,GAAG;CACzB,MAAM,KAAK,KAAK,KAAK,GAAG;CACxB,IAAI,OAAO,IAAI,OAAO,OAAO;CAC7B,MAAM,OAAO,MAAM;CACnB,OAAO,OAAO,OAAQ,IAAI,QAAQ,OAAO,MAAO;AAClD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"matrix-DnlHn5x1.js","names":[],"sources":["../src/matrix/cell-spend.ts","../src/matrix/aggregation.ts","../src/matrix/runner.ts"],"sourcesContent":["/**\n * Spend carrier for a cell that fails after it has already spent money.\n *\n * `runCell` reports what a cell cost by returning a `CellResult`. A throw\n * carries no result, so the runner cannot know what the cell spent before it\n * failed: the cumulative sum the cost ceiling reads, and `totalCostUsd`, both\n * miss that money. A throw that carries a `CellSpend` closes the gap — the\n * runner bills the failed cell for the spend the carrier declares, and records\n * a cell that declared nothing as `uncaptured` instead of a zero that reads\n * like \"this cell spent nothing\".\n *\n * The carrier is read structurally, never by `instanceof`, so a throw that\n * crosses a package or realm boundary still bills.\n */\n\n/** Property key the carrier occupies on a thrown object. Stable across\n * versions — two copies of this package must agree on it. */\nconst CELL_SPEND_KEY = '__agentEvalCellSpend'\n\n/** Money and wall time a cell consumed before it threw. */\nexport interface CellSpend {\n /** KNOWN subtotal in USD. When `kind` is `uncaptured` the cell spent this\n * much AND an unknown amount more, so the value must not be read as the\n * cell's total. */\n costUsd: number\n /** Wall time the cell consumed before the throw, in milliseconds. */\n durationMs: number\n /** `observed` = provider-reported amounts, `estimated` = computed from token\n * prices, `uncaptured` = `costUsd` is a subtotal and part of the spend\n * could not be measured. */\n kind: 'observed' | 'estimated' | 'uncaptured'\n}\n\n/**\n * Return `error` carrying `spend`, for a throw site inside `runCell`:\n * `throw withCellSpend(err, { costUsd, durationMs, kind })`.\n *\n * A value that cannot hold the carrier — a thrown string or number, or a\n * frozen, sealed, or otherwise non-extensible object — is wrapped in an\n * `Error` that keeps the original as `cause`, so the spend is never dropped.\n * A later call overwrites an earlier carrier — the outer frame knows more\n * than the inner one.\n *\n * Throws `TypeError` on a non-finite or negative amount. A poisoned amount\n * would reach `cumulativeCost` and disable the cost ceiling for the whole run,\n * because `NaN >= ceiling` is false.\n */\nexport function withCellSpend(error: unknown, spend: CellSpend): unknown {\n assertAmount(spend.costUsd, 'costUsd')\n assertAmount(spend.durationMs, 'durationMs')\n if (spend.kind !== 'observed' && spend.kind !== 'estimated' && spend.kind !== 'uncaptured') {\n throw new TypeError(\n `withCellSpend: kind must be observed, estimated or uncaptured, received ${String(spend.kind)}`,\n )\n }\n const carrier: CellSpend = {\n costUsd: spend.costUsd,\n durationMs: spend.durationMs,\n kind: spend.kind,\n }\n if (typeof error === 'object' && error !== null && attach(error, carrier)) return error\n // A primitive cannot hold a property, and a frozen or sealed object refuses\n // one. Carry the spend on a fresh Error that keeps the original as `cause`\n // rather than lose it — a dropped carrier bills the cell as uncaptured,\n // which is the under-billing this module exists to prevent.\n const wrapper = new Error(`cell failed: ${messageOf(error)}`, { cause: error })\n attach(wrapper, carrier)\n return wrapper\n}\n\n/** True when the carrier landed. `defineProperty` throws on a non-extensible\n * target, so the caller must be able to fall back. */\nfunction attach(target: object, carrier: CellSpend): boolean {\n try {\n Object.defineProperty(target, CELL_SPEND_KEY, {\n value: carrier,\n enumerable: false,\n configurable: true,\n writable: true,\n })\n return true\n } catch {\n return false\n }\n}\n\nfunction messageOf(error: unknown): string {\n if (error instanceof Error) return error.message\n return String(error)\n}\n\n/** Read the spend a thrown value carries. `undefined` when the value carries\n * none, or carries one that does not satisfy `CellSpend` — the runner records\n * both as `uncaptured`. */\nexport function readCellSpend(error: unknown): CellSpend | undefined {\n if (typeof error !== 'object' || error === null) return undefined\n const raw = (error as Record<string, unknown>)[CELL_SPEND_KEY]\n if (typeof raw !== 'object' || raw === null) return undefined\n const candidate = raw as Record<string, unknown>\n if (!isAmount(candidate.costUsd) || !isAmount(candidate.durationMs)) return undefined\n const kind = candidate.kind\n if (kind !== 'observed' && kind !== 'estimated' && kind !== 'uncaptured') return undefined\n return { costUsd: candidate.costUsd, durationMs: candidate.durationMs, kind }\n}\n\n/** A number the matrix can add to a running cost or duration: finite and not\n * negative. Anything else would poison a sum the cost ceiling reads. */\nexport function isAmount(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0\n}\n\nfunction assertAmount(value: number, field: string): void {\n if (!isAmount(value)) {\n throw new TypeError(\n `withCellSpend: ${field} must be a finite number >= 0, received ${String(value)}`,\n )\n }\n}\n","/**\n * Per-axis aggregation of cell runs into `AxisSummary` rows.\n *\n * Pure: consumes the final `cells: [{cell, runs}]` array and returns the\n * `byAxis` table. Error runs contribute 0 to passRate and meanScore. Cost and\n * duration always count — the budget was spent regardless. A run whose cost is\n * a subtotal rather than a total raises `costUncapturedCells` for its bucket,\n * so a per-axis cost row says when it under-counts.\n */\n\nimport type { AxisSummary, CellResult, MatrixAxis, MatrixCell, MatrixResult } from './types'\n\ninterface Row<Output> {\n cell: MatrixCell\n result: CellResult<Output>\n}\n\nfunction flattenRuns<Output>(cells: MatrixResult<Output>['cells']): Row<Output>[] {\n const rows: Row<Output>[] = []\n for (const { cell, runs } of cells) {\n for (const result of runs) rows.push({ cell, result })\n }\n return rows\n}\n\nfunction quantile(sorted: number[], q: number): number {\n if (sorted.length === 0) return 0\n if (sorted.length === 1) return sorted[0] as number\n const pos = (sorted.length - 1) * q\n const lo = Math.floor(pos)\n const hi = Math.ceil(pos)\n if (lo === hi) return sorted[lo] as number\n const frac = pos - lo\n return (sorted[lo] as number) * (1 - frac) + (sorted[hi] as number) * frac\n}\n\nexport function summariseRows<Output>(\n rows: Row<Output>[],\n axisName: string,\n axisValue: string,\n): AxisSummary {\n if (rows.length === 0) {\n return {\n axisName,\n axisValue,\n cells: 0,\n passRate: 0,\n meanScore: 0,\n p50Score: 0,\n p90Score: 0,\n totalCostUsd: 0,\n costUncapturedCells: 0,\n meanDurationMs: 0,\n }\n }\n let pass = 0\n let scoreSum = 0\n let costSum = 0\n let durSum = 0\n let costUncapturedCells = 0\n const scores: number[] = []\n for (const { result } of rows) {\n const errored = result.error !== undefined\n const score = errored ? 0 : result.verdict.score\n const valid = !errored && result.verdict.valid\n if (valid) pass++\n scoreSum += score\n scores.push(score)\n costSum += result.costUsd\n durSum += result.durationMs\n if (result.costProvenance?.kind === 'uncaptured') costUncapturedCells++\n }\n scores.sort((a, b) => a - b)\n return {\n axisName,\n axisValue,\n cells: rows.length,\n passRate: pass / rows.length,\n meanScore: scoreSum / rows.length,\n p50Score: quantile(scores, 0.5),\n p90Score: quantile(scores, 0.9),\n totalCostUsd: costSum,\n costUncapturedCells,\n meanDurationMs: durSum / rows.length,\n }\n}\n\nfunction bucketBy<Output>(\n rows: Row<Output>[],\n axisName: string,\n labelFor: (id: string) => string,\n): Record<string, AxisSummary> {\n const buckets = new Map<string, Row<Output>[]>()\n for (const row of rows) {\n const slot = row.cell.axes[axisName]\n if (!slot) continue\n const id = slot.id\n let arr = buckets.get(id)\n if (!arr) {\n arr = []\n buckets.set(id, arr)\n }\n arr.push(row)\n }\n const out: Record<string, AxisSummary> = {}\n // Sorted keys for deterministic JSON serialisation.\n for (const id of [...buckets.keys()].sort()) {\n out[id] = summariseRows(buckets.get(id) as Row<Output>[], axisName, labelFor(id))\n }\n return out\n}\n\nexport function buildByAxis<Output>(\n cells: MatrixResult<Output>['cells'],\n axes: MatrixAxis<unknown>[],\n aggregateBy: string[],\n): Record<string, Record<string, AxisSummary>> {\n const rows = flattenRuns(cells)\n const byName = new Map(axes.map((a) => [a.name, a]))\n const byAxis: Record<string, Record<string, AxisSummary>> = {}\n for (const name of aggregateBy) {\n const axis = byName.get(name)\n const labelFor = (id: string): string => {\n if (!axis?.label) return id\n const found = axis.values.find((v) => v.id === id)\n if (!found) return id\n return axis.label(found.value, id)\n }\n byAxis[name] = bucketBy(rows, name, labelFor)\n }\n return byAxis\n}\n","/**\n * N-axis cartesian runner.\n *\n * Expansion order: cartesian over `axes` in declared order, then `reps` as the\n * inner-most dim → `ordinal = (cartIdx * reps) + rep`. The returned\n * `cells[]` is sorted by `ordinal` so concurrent execution does not reorder\n * the output.\n *\n * Scheduling is a sliding window of in-flight promises capped at\n * `maxConcurrency`. The window stops admitting new cells when the cost\n * ceiling trips or the abort signal fires; in-flight cells finish.\n */\n\nimport { buildByAxis } from './aggregation'\nimport { isAmount, readCellSpend } from './cell-spend'\nimport type {\n CellResult,\n CostProvenance,\n MatrixAxis,\n MatrixCell,\n MatrixResult,\n RunAgentMatrixOptions,\n} from './types'\n\ninterface BaseCell {\n axes: Record<string, { id: string; value: unknown }>\n}\n\nfunction cartesian(axes: MatrixAxis<unknown>[]): BaseCell[] {\n // Empty axes (`values=[]`) collapse the whole product to zero cells. An\n // empty `axes` array yields a single empty-axes cell — degenerate but\n // valid (caller is iterating only reps).\n if (axes.length === 0) return [{ axes: {} }]\n for (const a of axes) if (a.values.length === 0) return []\n const out: BaseCell[] = []\n const idx = new Array(axes.length).fill(0)\n while (true) {\n const slot: Record<string, { id: string; value: unknown }> = {}\n for (let i = 0; i < axes.length; i++) {\n const axis = axes[i] as MatrixAxis<unknown>\n const v = axis.values[idx[i] as number] as { id: string; value: unknown }\n slot[axis.name] = { id: v.id, value: v.value }\n }\n out.push({ axes: slot })\n // Increment like an odometer, left-most axis is fastest.\n let i = 0\n while (i < axes.length) {\n const next = (idx[i] as number) + 1\n const axis = axes[i] as MatrixAxis<unknown>\n if (next < axis.values.length) {\n idx[i] = next\n break\n }\n idx[i] = 0\n i++\n }\n if (i === axes.length) break\n }\n return out\n}\n\nfunction makeMatrixId(): string {\n // Stable id-like string: time + 8 random hex chars. Avoids node:crypto\n // import to keep the matrix dep-free.\n const t = Date.now().toString(36)\n let r = ''\n for (let i = 0; i < 8; i++) r += Math.floor(Math.random() * 16).toString(16)\n return `mtx_${t}_${r}`\n}\n\n/** Fresh per result — a shared object would let one consumer's mutation reach\n * every other cell in the run. */\nfunction uncaptured(): CostProvenance {\n return { kind: 'uncaptured', usd: null }\n}\n\nfunction makeErrorResult<Output>(err: unknown): CellResult<Output> {\n const e = err as { message?: string; name?: string }\n const spend = readCellSpend(err)\n return {\n output: undefined as unknown as Output,\n verdict: { valid: false, score: 0 },\n costUsd: spend?.costUsd ?? 0,\n durationMs: spend?.durationMs ?? 0,\n costProvenance:\n spend === undefined || spend.kind === 'uncaptured'\n ? uncaptured()\n : { kind: spend.kind, usd: spend.costUsd },\n error: {\n message: typeof e?.message === 'string' ? e.message : String(err),\n kind: typeof e?.name === 'string' ? e.name : 'Error',\n },\n }\n}\n\n/** Make a result safe to sum.\n *\n * A `costUsd` that cannot be summed fails the cell: `NaN` in `cumulativeCost`\n * makes `>= costCeiling` false forever, so one bad cell would disable the\n * ceiling for every cell after it.\n *\n * A bad `durationMs` reaches only `meanDurationMs`, never the ceiling, so it\n * cannot justify throwing away a real verdict and a real cost. It is reported\n * as 0 and warned about, and the rest of the result stands. A wall clock that\n * steps back mid-cell makes `Date.now() - startedAt` negative, so this is a\n * reachable state, not only a caller bug. */\nfunction billableResult<Output>(\n result: CellResult<Output>,\n onBadDuration: (reported: unknown) => void,\n): CellResult<Output> {\n if (!isAmount(result.costUsd)) {\n return makeErrorResult<Output>(\n new RangeError(\n `runCell reported costUsd=${String(result.costUsd)}; a cell cost must be a finite number >= 0 so the cost ceiling stays enforceable`,\n ),\n )\n }\n if (isAmount(result.durationMs)) return result\n onBadDuration(result.durationMs)\n return { ...result, durationMs: 0 }\n}\n\nexport async function runAgentMatrix<Output>(\n opts: RunAgentMatrixOptions<Output>,\n): Promise<MatrixResult<Output>> {\n const startedAt = Date.now()\n const reps = Math.max(1, opts.reps ?? 1)\n const maxConcurrency = Math.max(1, opts.maxConcurrency ?? 4)\n const costCeiling = opts.costCeiling ?? Number.POSITIVE_INFINITY\n const aggregateBy = opts.aggregateBy ?? opts.axes.map((a) => a.name)\n if (opts.maxCellCostUsd !== undefined && !isAmount(opts.maxCellCostUsd)) {\n throw new RangeError(\n `runAgentMatrix: maxCellCostUsd must be a finite number >= 0, received ${String(opts.maxCellCostUsd)}`,\n )\n }\n\n const base = cartesian(opts.axes)\n const filtered = opts.filter\n ? base.filter((c) => (opts.filter as (b: BaseCell) => boolean)(c))\n : base\n const filteredOut = base.length - filtered.length\n\n const planned: MatrixCell[] = []\n for (let i = 0; i < filtered.length; i++) {\n for (let r = 0; r < reps; r++) {\n planned.push({\n axes: (filtered[i] as BaseCell).axes,\n rep: r,\n ordinal: i * reps + r,\n })\n }\n }\n\n const cellRecords: Array<{ cell: MatrixCell; runs: CellResult<Output>[] }> = []\n // What the ceiling reads. It runs ahead of the reported total whenever a\n // cell's cost is a subtotal and `maxCellCostUsd` bounds what it could have\n // been — a budget must assume the worst about spend it cannot see.\n let cumulativeCost = 0\n let costCeilingReached = false\n let runsExecuted = 0\n let cellsUnscheduled = 0\n let costUncapturedCells = 0\n let badDurationCells = 0\n\n const aborted = (): boolean => opts.signal?.aborted === true\n\n // Per-run abort controller forwards the external signal so cell executors\n // see cancellation. We don't expose it on `MatrixCell` — the signature on\n // `runCell` per the public API is `(cell) => Promise<...>`. Executors that\n // need cancellation use the external signal directly via closure.\n\n let inFlight = 0\n let cursor = 0\n let resolveAll: (() => void) | undefined\n const done = new Promise<void>((res) => {\n resolveAll = res\n })\n\n const pump = (): void => {\n while (inFlight < maxConcurrency && cursor < planned.length) {\n if (aborted() || costCeilingReached) {\n // Drain remaining as unscheduled.\n const left = planned.length - cursor\n cellsUnscheduled += left\n cursor = planned.length\n break\n }\n const cell = planned[cursor++] as MatrixCell\n inFlight++\n // Lazily allocate the record so cells appear in `cells[]` in any\n // arrival order; we sort by ordinal at the end.\n const record = { cell, runs: [] as CellResult<Output>[] }\n cellRecords.push(record)\n const promise: Promise<CellResult<Output>> = (async () => {\n try {\n return await opts.runCell(cell)\n } catch (err) {\n return makeErrorResult<Output>(err)\n }\n })()\n promise.then((settled) => {\n const result = billableResult(settled, (reported) => {\n badDurationCells++\n if (badDurationCells === 1) {\n // eslint-disable-next-line no-console\n console.warn(\n `[matrix] a cell reported durationMs=${String(reported)}; recorded as 0 — meanDurationMs under-reports this run`,\n )\n }\n })\n record.runs.push(result)\n runsExecuted++\n const uncapturedCost = result.costProvenance?.kind === 'uncaptured'\n cumulativeCost +=\n uncapturedCost && opts.maxCellCostUsd !== undefined\n ? Math.max(result.costUsd, opts.maxCellCostUsd)\n : result.costUsd\n if (uncapturedCost) {\n costUncapturedCells++\n if (costUncapturedCells === 1) {\n // eslint-disable-next-line no-console\n console.warn(\n \"[matrix] a cell's cost is a subtotal, not a total — totalCostUsd and the cost ceiling under-count this run\",\n )\n }\n }\n if (cumulativeCost >= costCeiling && !costCeilingReached) {\n costCeilingReached = true\n // eslint-disable-next-line no-console\n console.warn('[matrix] cost ceiling reached')\n }\n try {\n opts.onCellComplete?.(cell, result)\n } catch {\n // onCellComplete is observational — swallow throws so a noisy\n // callback can't tank the run.\n }\n inFlight--\n if (cursor < planned.length) {\n pump()\n } else if (inFlight === 0) {\n resolveAll?.()\n }\n })\n }\n if (cursor >= planned.length && inFlight === 0) resolveAll?.()\n }\n\n const onAbort = (): void => {\n // External abort: stop scheduling. In-flight cells finish; their\n // executors observe `opts.signal.aborted` directly via closure.\n if (cursor < planned.length) {\n cellsUnscheduled += planned.length - cursor\n cursor = planned.length\n }\n if (inFlight === 0) resolveAll?.()\n }\n if (opts.signal) {\n if (opts.signal.aborted) {\n cellsUnscheduled = planned.length\n cursor = planned.length\n resolveAll?.()\n } else {\n opts.signal.addEventListener('abort', onAbort, { once: true })\n }\n }\n\n if (planned.length === 0) {\n resolveAll?.()\n } else {\n pump()\n }\n\n await done\n if (opts.signal) opts.signal.removeEventListener('abort', onAbort)\n\n cellRecords.sort((a, b) => a.cell.ordinal - b.cell.ordinal)\n\n let pass = 0\n let scoreSum = 0\n let totalCost = 0\n let runCount = 0\n for (const { runs } of cellRecords) {\n for (const r of runs) {\n runCount++\n const errored = r.error !== undefined\n if (!errored && r.verdict.valid) pass++\n scoreSum += errored ? 0 : r.verdict.score\n totalCost += r.costUsd\n }\n }\n\n const byAxis = buildByAxis(cellRecords, opts.axes, aggregateBy)\n\n return {\n cells: cellRecords,\n byAxis,\n summary: {\n totalCells: planned.length,\n runsExecuted,\n cellsSkipped: cellsUnscheduled + filteredOut * reps,\n overallPassRate: runCount === 0 ? 0 : pass / runCount,\n overallMeanScore: runCount === 0 ? 0 : scoreSum / runCount,\n totalCostUsd: totalCost,\n costUncapturedCells,\n ceilingChargedUsd: cumulativeCost,\n durationMs: Date.now() - startedAt,\n },\n matrixId: makeMatrixId(),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,MAAM,iBAAiB;;;;;;;;;;;;;;;AA8BvB,SAAgB,cAAc,OAAgB,OAA2B;CACvE,aAAa,MAAM,SAAS,SAAS;CACrC,aAAa,MAAM,YAAY,YAAY;CAC3C,IAAI,MAAM,SAAS,cAAc,MAAM,SAAS,eAAe,MAAM,SAAS,cAC5E,MAAM,IAAI,UACR,2EAA2E,OAAO,MAAM,IAAI,GAC9F;CAEF,MAAM,UAAqB;EACzB,SAAS,MAAM;EACf,YAAY,MAAM;EAClB,MAAM,MAAM;CACd;CACA,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAO,OAAO,OAAO,GAAG,OAAO;CAKlF,MAAM,UAAU,IAAI,MAAM,gBAAgB,UAAU,KAAK,KAAK,EAAE,OAAO,MAAM,CAAC;CAC9E,OAAO,SAAS,OAAO;CACvB,OAAO;AACT;;;AAIA,SAAS,OAAO,QAAgB,SAA6B;CAC3D,IAAI;EACF,OAAO,eAAe,QAAQ,gBAAgB;GAC5C,OAAO;GACP,YAAY;GACZ,cAAc;GACd,UAAU;EACZ,CAAC;EACD,OAAO;CACT,QAAQ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SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CAEjE;CAEA,IAAI,QAAQ,WAAW,GACrB,aAAa;MAEb,KAAK;CAGP,MAAM;CACN,IAAI,KAAK,QAAQ,KAAK,OAAO,oBAAoB,SAAS,OAAO;CAEjE,YAAY,MAAM,GAAG,MAAM,EAAE,KAAK,UAAU,EAAE,KAAK,OAAO;CAE1D,IAAI,OAAO;CACX,IAAI,WAAW;CACf,IAAI,YAAY;CAChB,IAAI,WAAW;CACf,KAAK,MAAM,EAAE,UAAU,aACrB,KAAK,MAAM,KAAK,MAAM;EACpB;EACA,MAAM,UAAU,EAAE,UAAU,KAAA;EAC5B,IAAI,CAAC,WAAW,EAAE,QAAQ,OAAO;EACjC,YAAY,UAAU,IAAI,EAAE,QAAQ;EACpC,aAAa,EAAE;CACjB;CAKF,OAAO;EACL,OAAO;EACP,QAJa,YAAY,aAAa,KAAK,MAAM,WAI5C;EACL,SAAS;GACP,YAAY,QAAQ;GACpB;GACA,cAAc,mBAAmB,cAAc;GAC/C,iBAAiB,aAAa,IAAI,IAAI,OAAO;GAC7C,kBAAkB,aAAa,IAAI,IAAI,WAAW;GAClD,cAAc;GACd;GACA,mBAAmB;GACnB,YAAY,KAAK,IAAI,IAAI;EAC3B;EACA,UAAU,aAAa;CACzB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"paired-arms-DpS_h8ON.js","names":[],"sources":["../src/math/normal.ts","../src/statistics/rank-tests.ts","../src/paired-arms.ts"],"sourcesContent":["/**\n * Standard normal cumulative distribution using Abramowitz and Stegun 7.1.26.\n *\n * The approximation is evaluated as erf(x / sqrt(2)). Computing the negative\n * tail from the complementary term avoids cancellation when x is far below 0.\n * The maximum absolute CDF error is approximately 7.5e-8.\n */\nexport function normalCdf(x: number): number {\n if (x === 0) return 0.5\n\n const a1 = 0.254829592\n const a2 = -0.284496736\n const a3 = 1.421413741\n const a4 = -1.453152027\n const a5 = 1.061405429\n const p = 0.3275911\n\n const scaled = Math.abs(x) / Math.SQRT2\n const t = 1 / (1 + p * scaled)\n const complement = ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-scaled * scaled)\n\n return x < 0 ? complement / 2 : 1 - complement / 2\n}\n","import { ValidationError } from '../errors'\nimport { normalCdf } from '../math/normal'\nimport { lnGamma } from '../math/special-functions'\nimport {\n assertFiniteSample,\n binomialSignTwoSided,\n makeRng,\n symmetricTwoSampleSeed,\n} from './internal'\n\n// ── Rank tests: exact by default ─────────────────────────────────────\n//\n// At 3–10 repetitions per arm the binding constraint on a rank test is\n// combinatorial, not numerical. Three versus three admits only 20 splits, so\n// the attainable two-sided p-grid starts at 0.1000 and α = 0.05 is out of\n// reach at that design; a normal approximation reports 0.0495, a p-value that\n// describes no attainable outcome. No better approximation fixes this — adding\n// the tie correction moves `[0,0,0]` versus `[1,1,1]` from 0.0495 to 0.0469,\n// further from its exact 0.1000, not closer.\n//\n// So both null distributions are enumerated exactly inside bounded state and\n// work budgets, by convolution over the observed midranks (identical to\n// enumerating every split / sign pattern, and cheaper), which conditions on the\n// realised tie pattern for free. Above those budgets the default is a seeded\n// Monte Carlo permutation. The asymptotic path is never chosen automatically,\n// and asking for it inside the exact-feasible range throws.\n//\n// Every result carries `method` and `pFloor` so a downstream gate can SEE the\n// discreteness rather than infer it: a gate handed data whose `pFloor` exceeds\n// its alpha is underpowered by construction, which is a true statement about\n// the experiment, not a false one about the effect.\n\n/** How a rank test's p-value was actually computed. */\nexport type RankTestMethod = 'exact' | 'permutation' | 'asymptotic'\n\n/**\n * What the caller asks for. `'auto'` selects `'exact'` inside the enumeration\n * threshold and `'permutation'` above it, and never selects `'asymptotic'`.\n */\nexport type RankTestMethodRequest = 'auto' | 'exact' | 'asymptotic'\n\nexport interface RankTestOptions {\n /** Default `'auto'`. `'asymptotic'` inside the exact-feasible range throws. */\n method?: RankTestMethodRequest\n /** Resamples on the Monte Carlo permutation path. Default 100000. */\n permutations?: number\n /** Seed for the permutation path. Omitted ⇒ derived from the data itself, so\n * the result is reproducible either way. */\n seed?: number\n}\n\n/** Maximum dynamic-programming cells used by an exact two-sample rank test. */\nexport const MANN_WHITNEY_EXACT_MAX_STATES = 8_192\n/** Maximum inner-loop transitions used by an exact two-sample rank test. */\nexport const MANN_WHITNEY_EXACT_MAX_WORK = 250_000\n/** Non-zero differences up to which the signed-rank null is enumerated exactly. */\nexport const WILCOXON_EXACT_MAX_N = 20\n/** Resamples used when a rank test falls back to Monte Carlo permutation. */\nexport const DEFAULT_PERMUTATIONS = 100_000\n\nexport interface MannWhitneyResult {\n /** `min(U_a, U_b)` — the conventional reported statistic. */\n u: number\n /** U for sample `a`. Carries the direction of the effect, which `u` discards. */\n uA: number\n /** Two-sided p-value. */\n p: number\n /** How `p` was computed. */\n method: RankTestMethod\n /** Smallest two-sided p this design can produce. `p` can never be below it. */\n pFloor: number\n}\n\n/**\n * Mann-Whitney U — two independent samples, no distributional assumption.\n *\n * Exact conditional (permutation) p by default when the dynamic program fits\n * {@link MANN_WHITNEY_EXACT_MAX_STATES} cells and\n * {@link MANN_WHITNEY_EXACT_MAX_WORK} transitions, seeded Monte Carlo\n * permutation above those limits. This keeps imbalanced designs such as 1+24\n * exact without admitting expensive balanced designs merely because they have\n * the same total size. Throws on non-finite input and on `method:\n * 'asymptotic'` where an exact answer is available. Empty input yields `p = 1,\n * pFloor = 1` — no design, no attainable evidence.\n */\nexport function mannWhitneyU(\n a: number[],\n b: number[],\n opts: RankTestOptions = {},\n): MannWhitneyResult {\n assertFiniteSample('mannWhitneyU', 'a', a)\n assertFiniteSample('mannWhitneyU', 'b', b)\n\n const n1 = a.length\n const n2 = b.length\n if (n1 === 0 || n2 === 0) return { u: 0, uA: 0, p: 1, method: 'exact', pFloor: 1 }\n\n const total = n1 + n2\n const combined = [\n ...a.map((v) => ({ v, fromA: true })),\n ...b.map((v) => ({ v, fromA: false })),\n ].sort((x, y) => x.v - y.v)\n\n const { midranks, tieTerm } = midranksWithTieTerm(combined.map((entry) => entry.v))\n let rankSumA = 0\n for (let k = 0; k < total; k++) {\n if (combined[k]!.fromA) rankSumA += midranks[k]!\n }\n\n const uA = rankSumA - (n1 * (n1 + 1)) / 2\n const u = Math.min(uA, n1 * n2 - uA)\n // Midranks are integers or halves, so doubling makes the null convolution\n // integral. U is centred on n₁n₂/2, hence a doubled centre of n₁n₂.\n const doubled = midranks.map((rank) => Math.round(rank * 2))\n const doubledDeviation = Math.abs(2 * uA - n1 * n2)\n const selectedN = Math.min(n1, n2)\n const otherN = total - selectedN\n const exactCost = exactTwoSampleCost(doubled, selectedN)\n\n const designFloor = exactTwoSampleFloor(doubled, selectedN)\n const method = selectRankTestMethod(\n 'mannWhitneyU',\n opts.method ?? 'auto',\n `n1=${n1}, n2=${n2}`,\n exactCost.states <= MANN_WHITNEY_EXACT_MAX_STATES &&\n exactCost.work <= MANN_WHITNEY_EXACT_MAX_WORK,\n designFloor,\n `${MANN_WHITNEY_EXACT_MAX_STATES.toLocaleString('en-US')} states and ` +\n `${MANN_WHITNEY_EXACT_MAX_WORK.toLocaleString('en-US')} transitions`,\n )\n\n if (method === 'exact') {\n const { p, pFloor } = exactTwoSampleP(doubled, selectedN, otherN, doubledDeviation)\n return { u, uA, p, method, pFloor }\n }\n\n if (method === 'asymptotic') {\n return {\n u,\n uA,\n p: asymptoticTwoSidedP(doubledDeviation / 2, twoSampleSigma(n1, n2, total, tieTerm)),\n method,\n pFloor: designFloor,\n }\n }\n\n const permutations = resolvePermutations('mannWhitneyU', opts.permutations)\n const rng = opts.seed === undefined ? makeRng(symmetricTwoSampleSeed(a, b)) : makeRng(opts.seed)\n let atLeastAsExtreme = 0\n const pool = [...doubled]\n for (let iteration = 0; iteration < permutations; iteration++) {\n let doubledRankSum = 0\n for (let k = 0; k < selectedN; k++) {\n const pick = k + Math.floor(rng() * (total - k))\n const swapped = pool[pick]!\n pool[pick] = pool[k]!\n pool[k] = swapped\n doubledRankSum += swapped\n }\n if (\n Math.abs(doubledRankSum - selectedN * (selectedN + 1) - selectedN * otherN) >=\n doubledDeviation\n ) {\n atLeastAsExtreme++\n }\n }\n const pFloor = Math.max(1 / (permutations + 1), designFloor)\n return {\n u,\n uA,\n p: Math.max((1 + atLeastAsExtreme) / (permutations + 1), pFloor),\n method,\n pFloor,\n }\n}\n\nexport interface WilcoxonSignedRankResult {\n /** W⁺, the rank sum of the positive differences. (scipy reports\n * `min(W⁺, W⁻)`; compare statistics only after converting.) */\n w: number\n /** Two-sided p-value. */\n p: number\n /** How `p` was computed. */\n method: RankTestMethod\n /** Smallest two-sided p this design can produce. */\n pFloor: number\n /** Non-zero differences — zero differences are dropped and carry no rank. */\n nNonZero: number\n}\n\n/**\n * Wilcoxon signed-rank — paired, no distributional assumption on the deltas.\n *\n * Exact conditional (sign-flip) p by default at `n ≤\n * {@link WILCOXON_EXACT_MAX_N}` non-zero differences, seeded Monte Carlo\n * permutation above it. Throws on non-finite input and on `method:\n * 'asymptotic'` where an exact answer is available.\n *\n * `n` is the count of NON-ZERO differences: exact ties are dropped before\n * ranking, so a run of tied pairs shrinks the design and raises `pFloor`.\n * All-tied input yields `p = 1, pFloor = 1` — no attainable evidence, which\n * `pFloor` states rather than leaving `p = 1` to be read as a measured null.\n */\nexport function wilcoxonSignedRank(\n before: number[],\n after: number[],\n opts: RankTestOptions = {},\n): WilcoxonSignedRankResult {\n if (before.length !== after.length) {\n throw new ValidationError(\n `wilcoxonSignedRank: unequal sample sizes (${before.length} vs ${after.length})`,\n )\n }\n assertFiniteSample('wilcoxonSignedRank', 'before', before)\n assertFiniteSample('wilcoxonSignedRank', 'after', after)\n\n const diffs = before.map((b, i) => after[i]! - b).filter((d) => d !== 0)\n const n = diffs.length\n if (n === 0) return { w: 0, p: 1, method: 'exact', pFloor: 1, nNonZero: 0 }\n\n // When every non-zero difference has the same magnitude, the signed-rank\n // null reduces exactly to a binomial sign distribution. This is the common\n // pass/fail shape ({-1, 0, +1}); recognizing it avoids a 100k-draw\n // permutation for every repeated gate evaluation while preserving the exact\n // p-value and attainable floor. Explicit method requests still retain their\n // documented behavior.\n const abs = Math.abs(diffs[0]!)\n const allEqualAbs = diffs.every((d) => Math.abs(d) === abs)\n if ((opts.method === undefined || opts.method === 'auto') && allEqualAbs) {\n const positive = diffs.filter((d) => d > 0).length\n const negative = n - positive\n return {\n w: (positive * (n + 1)) / 2,\n p: binomialSignTwoSided(positive, negative),\n method: 'exact',\n pFloor: Math.min(1, 2 ** (1 - n)),\n nNonZero: n,\n }\n }\n\n const order = diffs.map((d, i) => ({ abs: Math.abs(d), i })).sort((x, y) => x.abs - y.abs)\n const { midranks, tieTerm } = midranksWithTieTerm(order.map((entry) => entry.abs))\n const ranks: number[] = new Array(n)\n for (let k = 0; k < n; k++) ranks[order[k]!.i] = midranks[k]!\n\n let wPlus = 0\n for (let k = 0; k < n; k++) if (diffs[k]! > 0) wPlus += ranks[k]!\n\n // Midranks are integers or halves; doubling makes the convolution integral.\n // Σ midranks = n(n+1)/2 whatever the tie pattern, so E[W⁺] = n(n+1)/4 and\n // the doubled centre is n(n+1)/2.\n const doubled = midranks.map((rank) => Math.round(rank * 2))\n const doubledDeviation = Math.abs(2 * wPlus - (n * (n + 1)) / 2)\n\n const designFloor = Math.min(1, 2 ** (1 - n))\n const method = selectRankTestMethod(\n 'wilcoxonSignedRank',\n opts.method ?? 'auto',\n `n=${n} non-zero differences`,\n n <= WILCOXON_EXACT_MAX_N,\n designFloor,\n `${WILCOXON_EXACT_MAX_N} non-zero differences`,\n )\n\n if (method === 'exact') {\n const { p, pFloor } = exactSignedRankP(doubled, doubledDeviation)\n return { w: wPlus, p, method, pFloor, nNonZero: n }\n }\n\n if (method === 'asymptotic') {\n const variance = (n * (n + 1) * (2 * n + 1)) / 24 - tieTerm / 48\n return {\n w: wPlus,\n p: asymptoticTwoSidedP(doubledDeviation / 2, Math.sqrt(variance)),\n method,\n pFloor: designFloor,\n nNonZero: n,\n }\n }\n\n const permutations = resolvePermutations('wilcoxonSignedRank', opts.permutations)\n const rng = makeRng(opts.seed, before, after)\n const doubledCentre = (n * (n + 1)) / 2\n let atLeastAsExtreme = 0\n for (let iteration = 0; iteration < permutations; iteration++) {\n let doubledWPlus = 0\n for (let k = 0; k < n; k++) if (rng() < 0.5) doubledWPlus += doubled[k]!\n if (Math.abs(doubledWPlus - doubledCentre) >= doubledDeviation) atLeastAsExtreme++\n }\n return {\n w: wPlus,\n p: (1 + atLeastAsExtreme) / (permutations + 1),\n method,\n pFloor: Math.max(1 / (permutations + 1), designFloor),\n nNonZero: n,\n }\n}\n\n/**\n * Average ranks over an ASCENDING-sorted array, plus `Σ(t³ − t)` over tie\n * groups of size `t` — the correction term both asymptotic rank-test variances\n * need.\n */\nfunction midranksWithTieTerm(sorted: readonly number[]): { midranks: number[]; tieTerm: number } {\n const midranks = new Array<number>(sorted.length)\n let tieTerm = 0\n let i = 0\n while (i < sorted.length) {\n let j = i\n while (j < sorted.length && sorted[j] === sorted[i]) j++\n const average = (i + 1 + j) / 2\n for (let k = i; k < j; k++) midranks[k] = average\n const groupSize = j - i\n if (groupSize > 1) tieTerm += groupSize ** 3 - groupSize\n i = j\n }\n return { midranks, tieTerm }\n}\n\nfunction selectRankTestMethod(\n fn: string,\n request: RankTestMethodRequest,\n design: string,\n exactFeasible: boolean,\n designFloor: number,\n threshold: string,\n): RankTestMethod {\n if (request === 'auto') return exactFeasible ? 'exact' : 'permutation'\n if (request === 'exact') {\n if (exactFeasible) return 'exact'\n throw new ValidationError(\n `${fn}: method 'exact' is out of range at ${design} — enumeration is bounded by ` +\n `${threshold}. Use 'auto' for the seeded Monte Carlo permutation, which converges ` +\n 'to the same answer.',\n )\n }\n if (exactFeasible) {\n throw new ValidationError(\n `${fn}: method 'asymptotic' is refused at ${design} — the exact p-grid at this design ` +\n `starts at ${formatProbability(designFloor)}, so an asymptotic p below it describes no ` +\n `attainable outcome. Use method 'exact' (the default) or add repetitions past ` +\n `${threshold}.`,\n )\n }\n return 'asymptotic'\n}\n\nfunction resolvePermutations(fn: string, permutations: number | undefined): number {\n if (permutations === undefined) return DEFAULT_PERMUTATIONS\n if (!Number.isInteger(permutations) || permutations < 1) {\n throw new ValidationError(`${fn}: permutations must be a positive integer, got ${permutations}`)\n }\n return permutations\n}\n\n/** Two-sided normal-approximation tail with the continuity correction. */\nfunction asymptoticTwoSidedP(deviation: number, sigma: number): number {\n if (!(sigma > 0)) return 1\n return Math.min(1, 2 * (1 - normalCdf(Math.max(0, deviation - 0.5) / sigma)))\n}\n\n/** SD of U under the permutation null, corrected for the realised ties. The\n * tie term reduces (N+1) and reaches it exactly when every value is tied, so\n * the variance floors at 0 rather than going negative. */\nfunction twoSampleSigma(n1: number, n2: number, total: number, tieTerm: number): number {\n if (total < 2) return 0\n const variance = ((n1 * n2) / 12) * (total + 1 - tieTerm / (total * (total - 1)))\n return Math.sqrt(Math.max(0, variance))\n}\n\nfunction logChoose(n: number, k: number): number {\n return lnGamma(n + 1) - lnGamma(k + 1) - lnGamma(n - k + 1)\n}\n\nfunction formatProbability(value: number): string {\n return value >= 1e-4 || value === 0 ? value.toFixed(4) : value.toExponential(3)\n}\n\n/**\n * Exact DP allocation and loop count for this observed rank vector.\n *\n * The smaller arm is sufficient because selecting its complement produces the\n * same two-sided U deviation while using fewer rows in the state table.\n */\nfunction exactTwoSampleCost(\n doubledRanks: readonly number[],\n selectedN: number,\n): { states: number; work: number } {\n const maxSum = doubledRanks.reduce((sum, rank) => sum + rank, 0)\n let work = 0\n for (let placed = 0; placed < doubledRanks.length; placed++) {\n work += Math.min(selectedN, placed + 1) * (maxSum - doubledRanks[placed]! + 1)\n }\n return {\n states: (selectedN + 1) * (maxSum + 1),\n work,\n }\n}\n\n/**\n * Smallest attainable two-sided p under the observed ties.\n *\n * Only subsets with the minimum or maximum rank sum can attain the largest\n * deviation. Their multiplicity is the number of ways to choose within the\n * tie group at each boundary, so this calculation is exact without allocating\n * the full null distribution.\n */\nfunction exactTwoSampleFloor(doubledRanks: readonly number[], selectedN: number): number {\n const total = doubledRanks.length\n const otherN = total - selectedN\n const minimumSum = doubledRanks.slice(0, selectedN).reduce((sum, rank) => sum + rank, 0)\n const maximumSum = doubledRanks.slice(total - selectedN).reduce((sum, rank) => sum + rank, 0)\n if (minimumSum === maximumSum) return 1\n\n const centre = selectedN * (selectedN + 1) + selectedN * otherN\n const minimumDeviation = Math.abs(minimumSum - centre)\n const maximumDeviation = Math.abs(maximumSum - centre)\n const totalLogWays = logChoose(total, selectedN)\n const minimumMass = Math.exp(\n logExtremeSubsetWays(doubledRanks, selectedN, 'minimum') - totalLogWays,\n )\n const maximumMass = Math.exp(\n logExtremeSubsetWays(doubledRanks, selectedN, 'maximum') - totalLogWays,\n )\n\n if (minimumDeviation > maximumDeviation) return minimumMass\n if (maximumDeviation > minimumDeviation) return maximumMass\n return Math.min(1, minimumMass + maximumMass)\n}\n\nfunction logExtremeSubsetWays(\n sortedRanks: readonly number[],\n selectedN: number,\n side: 'minimum' | 'maximum',\n): number {\n const boundaryIndex = side === 'minimum' ? selectedN - 1 : sortedRanks.length - selectedN\n const boundary = sortedRanks[boundaryIndex]!\n let first = boundaryIndex\n let afterLast = boundaryIndex + 1\n while (first > 0 && sortedRanks[first - 1] === boundary) first--\n while (afterLast < sortedRanks.length && sortedRanks[afterLast] === boundary) afterLast++\n\n const tieSize = afterLast - first\n const fixed = side === 'minimum' ? first : sortedRanks.length - afterLast\n return logChoose(tieSize, selectedN - fixed)\n}\n\n/**\n * Exact conditional two-sided p for the two-sample rank test.\n *\n * Convolves the observed doubled midranks into the null distribution of group\n * a's rank sum over every `C(n₁+n₂, n₁)` split — identical to enumerating the\n * splits, but `O(N·n₁·ΣR)` instead of `O(C(N,n₁)·n₁n₂)`. Conditioning on the\n * realised multiset makes the tie handling exact rather than a correction.\n *\n * The null is symmetric about `n₁n₂/2` (negating every value maps `U → n₁n₂ −\n * U` and permutes the split set onto itself), so the two-sided p is the mass\n * at least as far from the centre as the observation.\n */\nfunction exactTwoSampleP(\n doubledRanks: readonly number[],\n n1: number,\n n2: number,\n doubledDeviation: number,\n): { p: number; pFloor: number } {\n const maxSum = doubledRanks.reduce((sum, rank) => sum + rank, 0)\n const width = maxSum + 1\n // ways[k][s] = number of size-k subsets whose doubled rank sum is s.\n const ways: Float64Array[] = Array.from({ length: n1 + 1 }, () => new Float64Array(width))\n ways[0]![0] = 1\n let placed = 0\n for (const rank of doubledRanks) {\n for (let k = Math.min(n1, placed + 1); k >= 1; k--) {\n const from = ways[k - 1]!\n const into = ways[k]!\n for (let sum = maxSum - rank; sum >= 0; sum--) {\n const count = from[sum]!\n if (count !== 0) into[sum + rank]! += count\n }\n }\n placed++\n }\n\n // U = rankSum − n₁(n₁+1)/2, so doubled U = s − n₁(n₁+1), and the doubled\n // centre 2·(n₁n₂/2) is n₁n₂.\n const shift = n1 * (n1 + 1) + n1 * n2\n const chosen = ways[n1]!\n let totalWays = 0\n let extremeWays = 0\n let tailWays = 0\n let maxDeviation = -1\n for (let sum = 0; sum < width; sum++) {\n const count = chosen[sum]!\n if (count === 0) continue\n totalWays += count\n const deviation = Math.abs(sum - shift)\n if (deviation >= doubledDeviation) tailWays += count\n if (deviation > maxDeviation) {\n maxDeviation = deviation\n extremeWays = count\n } else if (deviation === maxDeviation) {\n extremeWays += count\n }\n }\n return { p: tailWays / totalWays, pFloor: extremeWays / totalWays }\n}\n\n/**\n * Exact conditional two-sided p for the paired signed-rank test.\n *\n * Convolves the observed doubled absolute midranks over all `2ⁿ` sign\n * assignments in `O(n·ΣR)`. Probabilities rather than counts keep `2ⁿ` off the\n * arithmetic. The null is symmetric about `n(n+1)/4`.\n */\nfunction exactSignedRankP(\n doubledRanks: readonly number[],\n doubledDeviation: number,\n): { p: number; pFloor: number } {\n const maxSum = doubledRanks.reduce((sum, rank) => sum + rank, 0)\n const width = maxSum + 1\n let mass = new Float64Array(width)\n mass[0] = 1\n for (const rank of doubledRanks) {\n const next = new Float64Array(width)\n for (let sum = 0; sum < width; sum++) {\n const probability = mass[sum]!\n if (probability === 0) continue\n next[sum]! += probability * 0.5\n next[sum + rank]! += probability * 0.5\n }\n mass = next\n }\n\n const centre = maxSum / 2\n let tail = 0\n let extreme = 0\n let maxDeviation = -1\n for (let sum = 0; sum < width; sum++) {\n const probability = mass[sum]!\n if (probability === 0) continue\n const deviation = Math.abs(sum - centre)\n if (deviation >= doubledDeviation) tail += probability\n if (deviation > maxDeviation) {\n maxDeviation = deviation\n extreme = probability\n } else if (deviation === maxDeviation) {\n extreme += probability\n }\n }\n return { p: Math.min(1, tail), pFloor: Math.min(1, extreme) }\n}\n","/**\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":";;;;;;;;;;;;AAOA,SAAgB,UAAU,GAAmB;CAC3C,IAAI,MAAM,GAAG,OAAO;CAEpB,MAAM,KAAK;CACX,MAAM,KAAK;CACX,MAAM,KAAK;CACX,MAAM,KAAK;CACX,MAAM,KAAK;CACX,MAAM,IAAI;CAEV,MAAM,SAAS,KAAK,IAAI,CAAC,IAAI,KAAK;CAClC,MAAM,IAAI,KAAK,IAAI,IAAI;CACvB,MAAM,iBAAiB,KAAK,IAAI,MAAM,IAAI,MAAM,IAAI,MAAM,IAAI,MAAM,IAAI,KAAK,IAAI,CAAC,SAAS,MAAM;CAEjG,OAAO,IAAI,IAAI,aAAa,IAAI,IAAI,aAAa;AACnD;;;;AC8BA,MAAa,gCAAgC;;AAE7C,MAAa,8BAA8B;;AAE3C,MAAa,uBAAuB;;AAEpC,MAAa,uBAAuB;;;;;;;;;;;;;AA2BpC,SAAgB,aACd,GACA,GACA,OAAwB,CAAC,GACN;CACnB,mBAAmB,gBAAgB,KAAK,CAAC;CACzC,mBAAmB,gBAAgB,KAAK,CAAC;CAEzC,MAAM,KAAK,EAAE;CACb,MAAM,KAAK,EAAE;CACb,IAAI,OAAO,KAAK,OAAO,GAAG,OAAO;EAAE,GAAG;EAAG,IAAI;EAAG,GAAG;EAAG,QAAQ;EAAS,QAAQ;CAAE;CAEjF,MAAM,QAAQ,KAAK;CACnB,MAAM,WAAW,CACf,GAAG,EAAE,KAAK,OAAO;EAAE;EAAG,OAAO;CAAK,EAAE,GACpC,GAAG,EAAE,KAAK,OAAO;EAAE;EAAG,OAAO;CAAM,EAAE,CACvC,CAAC,CAAC,MAAM,GAAG,M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,gBACR,mDAAmD,KAAK,gBAAgB,IAAI,QAAQ,UAAU,IAAI,IAAI,MAAM,GAC9G;CAEF,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"tool-waste-CP5DO383.d.ts","names":[],"sources":["../src/baseline.ts","../src/pipelines/budget-breach.ts","../src/pipelines/judge-agreement.ts","../src/tool-use-metrics.ts","../src/pipelines/tool-waste.ts"],"mappings":";;;;UA2BiB;EACf;EACA;EACA;EACA;;;EAGA;EACA;EACA;EACA;EACA;;EAEA;EACA;;UAGe;EACf,SAAS;;EAET;;EAEA;;UAGe;;EAEf;;EAEA;;EAEA;;;iBAiHc,IAAI;;;UCjKH;EACf;EACA;EACA;EACA,iBAAiB;EACjB;EACA;EACA;EACA;;UAGe;EACf,UAAU;EACV,aAAa;EACb,YAAY;EACZ,WAAW;EACX;EACA;;iBAGoB,iBACpB,OAAO,YACP;EAAW;EAAqB;IAC/B,QAAQ;;;UCnBM;EACf;EACA;EACA;;EAEA;EACA;EACA;;UAGe;EACf,OAAO;EACP;EACA;;iBAGoB,mBAAmB,OAAO,aAAa,QAAQ;;;UCjBpD;EACf;EACA;;EAEA;EACA,QAAQ,eAAe;EACvB;;EAEA;;EAEA;;EAEA;;UAGe;EACf;EACA;EACA;EACA;EACA;;UAGe;;EAEf,kBAAkB;;iBAGE,sBACpB,OAAO,YACP,eACA,UAAS,iBACR,QAAQ;;;UC5BM;EACf;EACA;EACA;EACA;;UAGe;EACf,OAAO;EACP;;UAGe;EACf;EACA,eAAe,MAAM,UAAU;IAAS,KAAK,QAAQ,kBAAkB;;;iBAGnD,cACpB,OAAO,YACP,UAAS,mBACR,QAAQ"}