@tangle-network/agent-eval 1.0.18 → 1.0.20

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 (305) hide show
  1. package/CHANGELOG.md +20 -21
  2. package/dist/adapters/http.d.ts +2 -2
  3. package/dist/{agent-profile-CPv4tENR.d.ts → agent-profile-BO8ruI6R.d.ts} +3 -3
  4. package/dist/{agent-profile-CPv4tENR.d.ts.map → agent-profile-BO8ruI6R.d.ts.map} +1 -1
  5. package/dist/analyst/index.d.ts +14 -14
  6. package/dist/analyst/index.js +13 -14
  7. package/dist/analyst/index.js.map +1 -1
  8. package/dist/{analyze-runs-pJ4fhnYg.d.ts → analyze-runs-DicleUI_.d.ts} +4 -4
  9. package/dist/{analyze-runs-pJ4fhnYg.d.ts.map → analyze-runs-DicleUI_.d.ts.map} +1 -1
  10. package/dist/{analyze-runs-C7vWBDhl.js → analyze-runs-e9vfXY--.js} +6 -110
  11. package/dist/analyze-runs-e9vfXY--.js.map +1 -0
  12. package/dist/app-grade/index.d.ts +12 -7
  13. package/dist/app-grade/index.d.ts.map +1 -1
  14. package/dist/app-grade/index.js +14 -10
  15. package/dist/app-grade/index.js.map +1 -1
  16. package/dist/{benchmark-command-Bqqvv9Tk.js → benchmark-command-BGZD77Un.js} +16 -17
  17. package/dist/benchmark-command-BGZD77Un.js.map +1 -0
  18. package/dist/benchmarks/index.d.ts +4 -4
  19. package/dist/benchmarks/index.js +4 -5
  20. package/dist/benchmarks/index.js.map +1 -1
  21. package/dist/builder-eval/index.js +1 -1
  22. package/dist/{calibration-CbZPApIO.js → calibration-Ze7SjhT9.js} +2 -2
  23. package/dist/{calibration-CbZPApIO.js.map → calibration-Ze7SjhT9.js.map} +1 -1
  24. package/dist/campaign/index.d.ts +7 -7
  25. package/dist/campaign/index.js +13 -13
  26. package/dist/{campaign-DzLlT0So.js → campaign-BfDMncQN.js} +16 -17
  27. package/dist/{campaign-DzLlT0So.js.map → campaign-BfDMncQN.js.map} +1 -1
  28. package/dist/{campaign-evidence-CcA7a67m.js → campaign-evidence-BuKlRzSA.js} +4 -4
  29. package/dist/{campaign-evidence-CcA7a67m.js.map → campaign-evidence-BuKlRzSA.js.map} +1 -1
  30. package/dist/{chat-client-D0me8iwq.js → chat-client-Zz97O3NB.js} +2 -2
  31. package/dist/{chat-client-D0me8iwq.js.map → chat-client-Zz97O3NB.js.map} +1 -1
  32. package/dist/{chat-json-call-C473CwTt.js → chat-json-call-Dgi7-RH-.js} +2 -2
  33. package/dist/{chat-json-call-C473CwTt.js.map → chat-json-call-Dgi7-RH-.js.map} +1 -1
  34. package/dist/cli.js +9 -9
  35. package/dist/{types-0KglnQ9o.d.ts → cluster-Cd0MRbr9.d.ts} +44 -2
  36. package/dist/cluster-Cd0MRbr9.d.ts.map +1 -0
  37. package/dist/cluster-bootstrap-BYIW7QJ4.js +24 -0
  38. package/dist/cluster-bootstrap-BYIW7QJ4.js.map +1 -0
  39. package/dist/{completion-verifier-7KEfroqx.d.ts → completion-verifier-BEpsr3N4.d.ts} +2 -2
  40. package/dist/{completion-verifier-7KEfroqx.d.ts.map → completion-verifier-BEpsr3N4.d.ts.map} +1 -1
  41. package/dist/{completion-verifier-ClmJV_Yc.js → completion-verifier-DFyYFezn.js} +3 -3
  42. package/dist/{completion-verifier-ClmJV_Yc.js.map → completion-verifier-DFyYFezn.js.map} +1 -1
  43. package/dist/contract/index.d.ts +10 -10
  44. package/dist/contract/index.js +15 -16
  45. package/dist/contract/index.js.map +1 -1
  46. package/dist/{cost-ledger-CS8R3IZj.js → cost-ledger-DfhStGcZ.js} +2 -2
  47. package/dist/{cost-ledger-CS8R3IZj.js.map → cost-ledger-DfhStGcZ.js.map} +1 -1
  48. package/dist/{decision-point-CNyoKOkz.js → decision-point-DJWievVw.js} +4 -4
  49. package/dist/{decision-point-CNyoKOkz.js.map → decision-point-DJWievVw.js.map} +1 -1
  50. package/dist/{default-registry-BNv7eB1C.d.ts → default-registry-BpGFsSpZ.d.ts} +7 -7
  51. package/dist/{default-registry-BNv7eB1C.d.ts.map → default-registry-BpGFsSpZ.d.ts.map} +1 -1
  52. package/dist/{default-registry-BB9_jzyH.js → default-registry-CdMtoY-s.js} +5 -5
  53. package/dist/{default-registry-BB9_jzyH.js.map → default-registry-CdMtoY-s.js.map} +1 -1
  54. package/dist/{define-agent-eval-DKVYlm-T.d.ts → define-agent-eval-DcK8mg63.d.ts} +7 -7
  55. package/dist/{define-agent-eval-DKVYlm-T.d.ts.map → define-agent-eval-DcK8mg63.d.ts.map} +1 -1
  56. package/dist/{define-agent-eval-CjF2nTA3.js → define-agent-eval-DuQNZajG.js} +7 -7
  57. package/dist/{define-agent-eval-CjF2nTA3.js.map → define-agent-eval-DuQNZajG.js.map} +1 -1
  58. package/dist/diagnosis/index.d.ts +2 -2
  59. package/dist/diagnosis/index.js +1 -1
  60. package/dist/{dspy-rlm-engine-_MEe2jIO.js → dspy-rlm-engine-cWyn8G1a.js} +4 -4
  61. package/dist/{dspy-rlm-engine-_MEe2jIO.js.map → dspy-rlm-engine-cWyn8G1a.js.map} +1 -1
  62. package/dist/{engine-rfV8Ff8V.d.ts → engine-BF8naBn7.d.ts} +2 -2
  63. package/dist/{engine-rfV8Ff8V.d.ts.map → engine-BF8naBn7.d.ts.map} +1 -1
  64. package/dist/{eval-campaign-CZSCjxVb.js → eval-campaign-LmpC_5fm.js} +2 -2
  65. package/dist/{eval-campaign-CZSCjxVb.js.map → eval-campaign-LmpC_5fm.js.map} +1 -1
  66. package/dist/{evaluation-DYAIkPQB.d.ts → evaluation-BCejQgkV.d.ts} +4 -4
  67. package/dist/{evaluation-DYAIkPQB.d.ts.map → evaluation-BCejQgkV.d.ts.map} +1 -1
  68. package/dist/{evaluation-BBI37mRe.js → evaluation-bU_bhlv-.js} +2 -2
  69. package/dist/{evaluation-BBI37mRe.js.map → evaluation-bU_bhlv-.js.map} +1 -1
  70. package/dist/evaluation.d.ts +1 -1
  71. package/dist/evaluation.js +1 -1
  72. package/dist/{exact-types-CaLLU1Pz.d.ts → exact-types-VAFjtOQN.d.ts} +2 -2
  73. package/dist/{exact-types-CaLLU1Pz.d.ts.map → exact-types-VAFjtOQN.d.ts.map} +1 -1
  74. package/dist/experiment/index.d.ts +3 -5
  75. package/dist/experiment/index.d.ts.map +1 -1
  76. package/dist/experiment/index.js +7 -12
  77. package/dist/experiment/index.js.map +1 -1
  78. package/dist/{exporters-BYBG9b1n.d.ts → exporters-dQKYD_Zo.d.ts} +2 -2
  79. package/dist/{exporters-BYBG9b1n.d.ts.map → exporters-dQKYD_Zo.d.ts.map} +1 -1
  80. package/dist/{external-optimizer-process-za-SsIap.js → external-optimizer-process-2ImGH_LR.js} +2 -2
  81. package/dist/{external-optimizer-process-za-SsIap.js.map → external-optimizer-process-2ImGH_LR.js.map} +1 -1
  82. package/dist/{external-optimizer-subprocess-B44kOfZb.js → external-optimizer-subprocess-_C_2yriN.js} +4 -4
  83. package/dist/{external-optimizer-subprocess-B44kOfZb.js.map → external-optimizer-subprocess-_C_2yriN.js.map} +1 -1
  84. package/dist/{feedback-trajectory-P37ju-gW.d.ts → feedback-trajectory-DTj8eVTR.d.ts} +3 -3
  85. package/dist/{feedback-trajectory-P37ju-gW.d.ts.map → feedback-trajectory-DTj8eVTR.d.ts.map} +1 -1
  86. package/dist/{findings-store-DWiBvJVM.js → findings-store-BSuaV3dN.js} +8 -25
  87. package/dist/findings-store-BSuaV3dN.js.map +1 -0
  88. package/dist/fuzz.js +2 -2
  89. package/dist/hosted/index.js +1 -1
  90. package/dist/{index-BJM4rwP2.d.ts → index-Bc8BZfzb.d.ts} +10 -9
  91. package/dist/index-Bc8BZfzb.d.ts.map +1 -0
  92. package/dist/index-BdLmBInV.d.ts +1099 -0
  93. package/dist/index-BdLmBInV.d.ts.map +1 -0
  94. package/dist/{index-BAPkHt5H.d.ts → index-CeYLLnfi.d.ts} +28 -128
  95. package/dist/index-CeYLLnfi.d.ts.map +1 -0
  96. package/dist/{index-C3t17kHu.d.ts → index-CzfdjM6o.d.ts} +7 -100
  97. package/dist/index-CzfdjM6o.d.ts.map +1 -0
  98. package/dist/{index-f09MX_H_.d.ts → index-DYNHOTTB.d.ts} +5 -5
  99. package/dist/{index-f09MX_H_.d.ts.map → index-DYNHOTTB.d.ts.map} +1 -1
  100. package/dist/{index-Dt6E4BHX.d.ts → index-D_eAFB3T.d.ts} +8 -8
  101. package/dist/{index-Dt6E4BHX.d.ts.map → index-D_eAFB3T.d.ts.map} +1 -1
  102. package/dist/{index-chNyKroE.d.ts → index-gSu9DUiw.d.ts} +8 -8
  103. package/dist/{index-chNyKroE.d.ts.map → index-gSu9DUiw.d.ts.map} +1 -1
  104. package/dist/{index-B1Bm9oJA.d.ts → index-lRKqfyg4.d.ts} +3 -7
  105. package/dist/index-lRKqfyg4.d.ts.map +1 -0
  106. package/dist/index.d.ts +29 -31
  107. package/dist/index.js +28 -164
  108. package/dist/index.js.map +1 -1
  109. package/dist/{integrity-BAdVzT8u.d.ts → integrity-CrmnGB2T.d.ts} +2 -2
  110. package/dist/{integrity-BAdVzT8u.d.ts.map → integrity-CrmnGB2T.d.ts.map} +1 -1
  111. package/dist/{journal-C1uLJi0w.js → journal-CTX5uK-n.js} +36 -26
  112. package/dist/journal-CTX5uK-n.js.map +1 -0
  113. package/dist/{judge-gate-CIlBrn6q.js → judge-gate-BliY81A0.js} +3 -3
  114. package/dist/{judge-gate-CIlBrn6q.js.map → judge-gate-BliY81A0.js.map} +1 -1
  115. package/dist/{kind-factory-Cfz8DUCc.js → kind-factory-CV0FNCMM.js} +2 -2
  116. package/dist/{kind-factory-Cfz8DUCc.js.map → kind-factory-CV0FNCMM.js.map} +1 -1
  117. package/dist/ledger-core/index.d.ts +1 -1
  118. package/dist/ledger-core/index.js +2 -2
  119. package/dist/{ledger-core-CfT-FzPf.js → ledger-core-24IxvmVY.js} +2 -2
  120. package/dist/{ledger-core-CfT-FzPf.js.map → ledger-core-24IxvmVY.js.map} +1 -1
  121. package/dist/{llm-client-BdSiZ4qz.js → llm-client-DMMSg-Ro.js} +2 -2
  122. package/dist/{llm-client-BdSiZ4qz.js.map → llm-client-DMMSg-Ro.js.map} +1 -1
  123. package/dist/{llm-judge-CHLvjbVR.js → llm-judge-Bnxuwjxl.js} +15 -16
  124. package/dist/{llm-judge-CHLvjbVR.js.map → llm-judge-Bnxuwjxl.js.map} +1 -1
  125. package/dist/{matrix-Cy3oy7Rq.d.ts → matrix-D6zEwLvE.d.ts} +2 -2
  126. package/dist/{matrix-Cy3oy7Rq.d.ts.map → matrix-D6zEwLvE.d.ts.map} +1 -1
  127. package/dist/meta-eval/index.d.ts +2 -2
  128. package/dist/meta-eval/index.js +7 -7
  129. package/dist/{metrics-DNCAUtuB.js → metrics-zALlR17s.js} +16 -17
  130. package/dist/metrics-zALlR17s.js.map +1 -0
  131. package/dist/multishot/golden/index.d.ts +1 -1
  132. package/dist/multishot/index.d.ts +2 -2
  133. package/dist/multishot/index.js +1 -1
  134. package/dist/openapi.json +1 -1
  135. package/dist/{outcome-observations-DZu5hLYF.js → outcome-observations-BpicIVQi.js} +2 -3
  136. package/dist/{outcome-observations-DZu5hLYF.js.map → outcome-observations-BpicIVQi.js.map} +1 -1
  137. package/dist/paired-arms-Dep5tbsw.js +338 -0
  138. package/dist/paired-arms-Dep5tbsw.js.map +1 -0
  139. package/dist/{paired-promotion-decision-BDnqepZ1.d.ts → paired-promotion-decision-BNzPfXDw.d.ts} +3 -113
  140. package/dist/paired-promotion-decision-BNzPfXDw.d.ts.map +1 -0
  141. package/dist/{paired-promotion-decision-CiueaTTj.js → paired-promotion-decision-Nt4CkkOT.js} +2 -3
  142. package/dist/{paired-promotion-decision-CiueaTTj.js.map → paired-promotion-decision-Nt4CkkOT.js.map} +1 -1
  143. package/dist/{pareto-B34N-vnn.js → pareto-C445lnEH.js} +6 -9
  144. package/dist/{pareto-B34N-vnn.js.map → pareto-C445lnEH.js.map} +1 -1
  145. package/dist/pipelines/index.js +1 -1
  146. package/dist/{prime-protocol-DKRk4l4U.d.ts → prime-protocol-D1NkJRuD.d.ts} +2 -2
  147. package/dist/{prime-protocol-DKRk4l4U.d.ts.map → prime-protocol-D1NkJRuD.d.ts.map} +1 -1
  148. package/dist/{promotion-gate-DOkgJcLW.d.ts → promotion-gate-DjAsmBSZ.d.ts} +3 -67
  149. package/dist/promotion-gate-DjAsmBSZ.d.ts.map +1 -0
  150. package/dist/{promotion-policy-DLPcEnCf.js → promotion-policy-CUWOv01m.js} +4 -4
  151. package/dist/{promotion-policy-DLPcEnCf.js.map → promotion-policy-CUWOv01m.js.map} +1 -1
  152. package/dist/{proposal-findings-CZJkS_GY.js → proposal-findings-DWs94yT8.js} +2 -2
  153. package/dist/{proposal-findings-CZJkS_GY.js.map → proposal-findings-DWs94yT8.js.map} +1 -1
  154. package/dist/{registry-Ck7w-rr5.d.ts → registry-BAcEbzKm.d.ts} +4 -4
  155. package/dist/{registry-Ck7w-rr5.d.ts.map → registry-BAcEbzKm.d.ts.map} +1 -1
  156. package/dist/{release-confidence-nfQNh3eb.js → release-confidence-DDrkmWxT.js} +2 -2
  157. package/dist/{release-confidence-nfQNh3eb.js.map → release-confidence-DDrkmWxT.js.map} +1 -1
  158. package/dist/reporting.d.ts +4 -5
  159. package/dist/reporting.d.ts.map +1 -1
  160. package/dist/reporting.js +5 -7
  161. package/dist/reporting.js.map +1 -1
  162. package/dist/{researcher-CLnNJ7Or.d.ts → researcher-D35yo0B8.d.ts} +4 -4
  163. package/dist/{researcher-CLnNJ7Or.d.ts.map → researcher-D35yo0B8.d.ts.map} +1 -1
  164. package/dist/{reward-hacking-B88f-Kh7.js → reward-hacking-DRb8K6N1.js} +2 -3
  165. package/dist/{reward-hacking-B88f-Kh7.js.map → reward-hacking-DRb8K6N1.js.map} +1 -1
  166. package/dist/rl.d.ts +9 -8
  167. package/dist/rl.d.ts.map +1 -1
  168. package/dist/rl.js +8 -10
  169. package/dist/rl.js.map +1 -1
  170. package/dist/rollout/index.d.ts +4 -4
  171. package/dist/rollout/index.js +1 -1
  172. package/dist/{rollout-Cu7kHGIe.js → rollout-DKa54qer.js} +2 -2
  173. package/dist/{rollout-Cu7kHGIe.js.map → rollout-DKa54qer.js.map} +1 -1
  174. package/dist/{rubric-predictive-validity-D_6ZPTNR.js → rubric-predictive-validity-BMS7SUyh.js} +2 -2
  175. package/dist/{rubric-predictive-validity-D_6ZPTNR.js.map → rubric-predictive-validity-BMS7SUyh.js.map} +1 -1
  176. package/dist/{run-record-CbUi2adH.js → run-record-CIflWk6i.js} +2 -2
  177. package/dist/{run-record-CbUi2adH.js.map → run-record-CIflWk6i.js.map} +1 -1
  178. package/dist/{runtime-rollouts-kGn1K5ut.js → runtime-rollouts-CfRyjk60.js} +2 -2
  179. package/dist/{runtime-rollouts-kGn1K5ut.js.map → runtime-rollouts-CfRyjk60.js.map} +1 -1
  180. package/dist/{schema-CfoA9U_U.d.ts → schema-PDKQ_iNE.d.ts} +2 -131
  181. package/dist/schema-PDKQ_iNE.d.ts.map +1 -0
  182. package/dist/search/index.d.ts +2 -2
  183. package/dist/search/index.js +2 -2
  184. package/dist/{search-kernel-kwO-sgCq.d.ts → search-kernel-Ds2zILpY.d.ts} +4 -4
  185. package/dist/{search-kernel-kwO-sgCq.d.ts.map → search-kernel-Ds2zILpY.d.ts.map} +1 -1
  186. package/dist/{search-ledger-CV_bQQed.js → search-ledger-Dk-yk5Li.js} +4 -4
  187. package/dist/{search-ledger-CV_bQQed.js.map → search-ledger-Dk-yk5Li.js.map} +1 -1
  188. package/dist/{search-ledger-file-DTBD6X-y.js → search-ledger-file-BhOdgYIt.js} +3 -3
  189. package/dist/{search-ledger-file-DTBD6X-y.js.map → search-ledger-file-BhOdgYIt.js.map} +1 -1
  190. package/dist/{search-shipper-CA3ooBbC.js → search-shipper-Dm-_Dtvy.js} +3 -3
  191. package/dist/{search-shipper-CA3ooBbC.js.map → search-shipper-Dm-_Dtvy.js.map} +1 -1
  192. package/dist/{search-summary-DBMjdecs.js → search-summary-BSftVrGY.js} +5 -5
  193. package/dist/{search-summary-DBMjdecs.js.map → search-summary-BSftVrGY.js.map} +1 -1
  194. package/dist/{sequential-Bb_pdTqG.d.ts → sequential-B9p6uoV8.d.ts} +9 -2
  195. package/dist/{sequential-Bb_pdTqG.d.ts.map → sequential-B9p6uoV8.d.ts.map} +1 -1
  196. package/dist/{sequential-Bjs5roiK.js → sequential-CAksw6EU.js} +32 -2
  197. package/dist/{sequential-Bjs5roiK.js.map → sequential-CAksw6EU.js.map} +1 -1
  198. package/dist/{sequential-BPbvgzfe.js → sequential-CqG6aLWS.js} +3 -3
  199. package/dist/{sequential-BPbvgzfe.js.map → sequential-CqG6aLWS.js.map} +1 -1
  200. package/dist/{server-CPKyf3bz.js → server-DFVwfoZq.js} +3 -3
  201. package/dist/{server-CPKyf3bz.js.map → server-DFVwfoZq.js.map} +1 -1
  202. package/dist/{single-run-lock-BGlW3OSk.js → single-run-lock-CUj2tjxT.js} +2 -2
  203. package/dist/{single-run-lock-BGlW3OSk.js.map → single-run-lock-CUj2tjxT.js.map} +1 -1
  204. package/dist/{skillopt-optimization-method-D72XZZfR.js → skillopt-optimization-method-DYwEndON.js} +12 -12
  205. package/dist/{skillopt-optimization-method-D72XZZfR.js.map → skillopt-optimization-method-DYwEndON.js.map} +1 -1
  206. package/dist/{statistical-heldout-_dXihc9T.d.ts → statistical-heldout--0b1lgx4.d.ts} +6 -282
  207. package/dist/statistical-heldout--0b1lgx4.d.ts.map +1 -0
  208. package/dist/{statistical-heldout-NBxC7jGo.js → statistical-heldout-D6i58CJ5.js} +3 -3
  209. package/dist/{statistical-heldout-NBxC7jGo.js.map → statistical-heldout-D6i58CJ5.js.map} +1 -1
  210. package/dist/statistics-DCZIC-qT.js +2627 -0
  211. package/dist/statistics-DCZIC-qT.js.map +1 -0
  212. package/dist/statistics.d.ts +3 -0
  213. package/dist/statistics.js +3 -0
  214. package/dist/{store-otlp-BfPRa2p8.js → store-otlp-C-jyj3WX.js} +2 -2
  215. package/dist/{store-otlp-BfPRa2p8.js.map → store-otlp-C-jyj3WX.js.map} +1 -1
  216. package/dist/{store-tool-spans-BgwVHXma.d.ts → store-tool-spans-B3z_Qb5u.d.ts} +5 -5
  217. package/dist/{store-tool-spans-BgwVHXma.d.ts.map → store-tool-spans-B3z_Qb5u.d.ts.map} +1 -1
  218. package/dist/{store-tool-spans-BrSWHB9O.js → store-tool-spans-DalWlKY8.js} +3 -3
  219. package/dist/{store-tool-spans-BrSWHB9O.js.map → store-tool-spans-DalWlKY8.js.map} +1 -1
  220. package/dist/{summary-report-0La5vejY.d.ts → summary-report-Cv1AC-iv.d.ts} +2 -2
  221. package/dist/{summary-report-0La5vejY.d.ts.map → summary-report-Cv1AC-iv.d.ts.map} +1 -1
  222. package/dist/{summary-report-C3IJvp0i.js → summary-report-D_uussI3.js} +4 -52
  223. package/dist/summary-report-D_uussI3.js.map +1 -0
  224. package/dist/supervisor-run/index.d.ts +2 -2
  225. package/dist/supervisor-run/index.js +1 -1
  226. package/dist/{systemone-CBvL1gx-.d.ts → systemone-C3xyEKvG.d.ts} +7 -7
  227. package/dist/{systemone-CBvL1gx-.d.ts.map → systemone-C3xyEKvG.d.ts.map} +1 -1
  228. package/dist/{systemone-review-nbuMxxmi.d.ts → systemone-review-CToBl1oa.d.ts} +2 -2
  229. package/dist/{systemone-review-nbuMxxmi.d.ts.map → systemone-review-CToBl1oa.d.ts.map} +1 -1
  230. package/dist/systemone.d.ts +3 -3
  231. package/dist/systemone.js +2 -2
  232. package/dist/{tool-groups-BQsjZD9F.d.ts → tool-groups-R5RO9OHn.d.ts} +3 -3
  233. package/dist/tool-groups-R5RO9OHn.d.ts.map +1 -0
  234. package/dist/{tool-waste-Czt3aWID.js → tool-waste-DEhKfiIE.js} +2 -3
  235. package/dist/{tool-waste-Czt3aWID.js.map → tool-waste-DEhKfiIE.js.map} +1 -1
  236. package/dist/{trace-questions-CpTrtEcm.d.ts → trace-questions-BY6taxnl.d.ts} +3 -3
  237. package/dist/{trace-questions-CpTrtEcm.d.ts.map → trace-questions-BY6taxnl.d.ts.map} +1 -1
  238. package/dist/trace-repair/index.d.ts +1 -1
  239. package/dist/trace-repair/index.js +1 -2
  240. package/dist/trace-repair/index.js.map +1 -1
  241. package/dist/traces.d.ts +5 -5
  242. package/dist/traces.js +3 -3
  243. package/dist/{tree-DPwgM2LX.js → tree-B2y1UR8o.js} +5 -7
  244. package/dist/{tree-DPwgM2LX.js.map → tree-B2y1UR8o.js.map} +1 -1
  245. package/dist/{types-DNB9hIXa.d.ts → types-BAJ2Hb-d.d.ts} +3 -2
  246. package/dist/types-BAJ2Hb-d.d.ts.map +1 -0
  247. package/dist/{types-D91tnhzf.d.ts → types-BwF--ZRz.d.ts} +2 -2
  248. package/dist/{types-D91tnhzf.d.ts.map → types-BwF--ZRz.d.ts.map} +1 -1
  249. package/dist/{types-CBkDo7ja.d.ts → types-CeMZYsNF.d.ts} +6 -5
  250. package/dist/types-CeMZYsNF.d.ts.map +1 -0
  251. package/dist/{types-B9s9Xo5_.d.ts → types-kBMNdo1X.d.ts} +3 -9
  252. package/dist/types-kBMNdo1X.d.ts.map +1 -0
  253. package/dist/wire/index.d.ts +4 -4
  254. package/dist/wire/index.js +1 -1
  255. package/docs/design/statistics-decisions.md +38 -364
  256. package/docs/design.md +1 -1
  257. package/docs/research-report-methodology.md +1 -1
  258. package/package.json +6 -1
  259. package/dist/agreement-irr-DXcXEt4I.js +0 -182
  260. package/dist/agreement-irr-DXcXEt4I.js.map +0 -1
  261. package/dist/analyze-runs-C7vWBDhl.js.map +0 -1
  262. package/dist/benchmark-command-Bqqvv9Tk.js.map +0 -1
  263. package/dist/cluster-bootstrap-BteuR1hg.js +0 -65
  264. package/dist/cluster-bootstrap-BteuR1hg.js.map +0 -1
  265. package/dist/descriptive-B3Eb7tX0.js +0 -229
  266. package/dist/descriptive-B3Eb7tX0.js.map +0 -1
  267. package/dist/findings-store-DWiBvJVM.js.map +0 -1
  268. package/dist/index-B1Bm9oJA.d.ts.map +0 -1
  269. package/dist/index-BAPkHt5H.d.ts.map +0 -1
  270. package/dist/index-BJM4rwP2.d.ts.map +0 -1
  271. package/dist/index-C3t17kHu.d.ts.map +0 -1
  272. package/dist/journal-C1uLJi0w.js.map +0 -1
  273. package/dist/judge-calibration-DKR6Xi-w.js +0 -319
  274. package/dist/judge-calibration-DKR6Xi-w.js.map +0 -1
  275. package/dist/judge-calibration-DnrbQaXI.d.ts +0 -144
  276. package/dist/judge-calibration-DnrbQaXI.d.ts.map +0 -1
  277. package/dist/mean-D1d6gedE.js +0 -284
  278. package/dist/mean-D1d6gedE.js.map +0 -1
  279. package/dist/metrics-DNCAUtuB.js.map +0 -1
  280. package/dist/multiplicity-DAd4xaDC.js +0 -100
  281. package/dist/multiplicity-DAd4xaDC.js.map +0 -1
  282. package/dist/multiplicity-D_SEsc5j.d.ts +0 -41
  283. package/dist/multiplicity-D_SEsc5j.d.ts.map +0 -1
  284. package/dist/paired-arms-3-tsXvvC.js +0 -740
  285. package/dist/paired-arms-3-tsXvvC.js.map +0 -1
  286. package/dist/paired-binary-CMzmSSd5.js +0 -372
  287. package/dist/paired-binary-CMzmSSd5.js.map +0 -1
  288. package/dist/paired-promotion-decision-BDnqepZ1.d.ts.map +0 -1
  289. package/dist/paired-tests-Buh6feJ4.js +0 -211
  290. package/dist/paired-tests-Buh6feJ4.js.map +0 -1
  291. package/dist/power-and-mde-g3vOn0XK.js +0 -99
  292. package/dist/power-and-mde-g3vOn0XK.js.map +0 -1
  293. package/dist/promotion-gate-DOkgJcLW.d.ts.map +0 -1
  294. package/dist/random-BN150Q_X.d.ts +0 -79
  295. package/dist/random-BN150Q_X.d.ts.map +0 -1
  296. package/dist/schema-CfoA9U_U.d.ts.map +0 -1
  297. package/dist/sequential-eprocess-C1YLwFaz.js +0 -129
  298. package/dist/sequential-eprocess-C1YLwFaz.js.map +0 -1
  299. package/dist/statistical-heldout-_dXihc9T.d.ts.map +0 -1
  300. package/dist/summary-report-C3IJvp0i.js.map +0 -1
  301. package/dist/tool-groups-BQsjZD9F.d.ts.map +0 -1
  302. package/dist/types-0KglnQ9o.d.ts.map +0 -1
  303. package/dist/types-B9s9Xo5_.d.ts.map +0 -1
  304. package/dist/types-CBkDo7ja.d.ts.map +0 -1
  305. package/dist/types-DNB9hIXa.d.ts.map +0 -1
@@ -0,0 +1,2627 @@
1
+ import { s as ValidationError } from "./errors-DeEEV9Vx.js";
2
+ import { t as interpolatedQuantile } from "./quantile-CncXP-Ss.js";
3
+ import { t as mulberry32 } from "./random-DrzcgC7F.js";
4
+ // src/math/special-functions.ts
5
+ /** Lanczos approximation to ln Gamma(z). */
6
+ function lnGamma(z) {
7
+ const g = 7;
8
+ const coefficients = [
9
+ .9999999999998099,
10
+ 676.5203681218851,
11
+ -1259.1392167224028,
12
+ 771.3234287776531,
13
+ -176.6150291621406,
14
+ 12.507343278686905,
15
+ -.13857109526572012,
16
+ 9984369578019572e-21,
17
+ 1.5056327351493116e-7
18
+ ];
19
+ if (z < .5) return Math.log(Math.PI / Math.sin(Math.PI * z)) - lnGamma(1 - z);
20
+ z -= 1;
21
+ let x = coefficients[0];
22
+ for (let i = 1; i < 9; i++) x += coefficients[i] / (z + i);
23
+ const t = z + g + .5;
24
+ return .5 * Math.log(2 * Math.PI) + (z + .5) * Math.log(t) - t + Math.log(x);
25
+ }
26
+ /**
27
+ * Regularized incomplete beta function I_x(a, b).
28
+ *
29
+ * The Lentz continued fraction converges only for `x < (a+1)/(a+b+2)`; outside
30
+ * that domain it must be reached through the symmetry `I_x(a,b) = 1 −
31
+ * I_{1−x}(b,a)`. `studentTCdf` drives `x → 1` as `|t| → 0`, so the mirrored
32
+ * branch is the one every near-null t-statistic takes.
33
+ */
34
+ function regularizedIncompleteBeta(x, a, b) {
35
+ if (x <= 0) return 0;
36
+ if (x >= 1) return 1;
37
+ const logBeta = lnGamma(a) + lnGamma(b) - lnGamma(a + b);
38
+ const front = Math.exp(Math.log(x) * a + Math.log(1 - x) * b - logBeta);
39
+ if (x < (a + 1) / (a + b + 2)) return front * betaContinuedFraction(x, a, b) / a;
40
+ return 1 - front * betaContinuedFraction(1 - x, b, a) / b;
41
+ }
42
+ /** Modified Lentz evaluation of the beta continued fraction at `x`. */
43
+ function betaContinuedFraction(x, a, b) {
44
+ const maxIterations = 300;
45
+ const epsilon = 3e-15;
46
+ let c = 1;
47
+ let d = 1 - (a + b) * x / (a + 1);
48
+ if (Math.abs(d) < 1e-30) d = 1e-30;
49
+ d = 1 / d;
50
+ let fraction = d;
51
+ for (let m = 1; m <= maxIterations; m++) {
52
+ const m2 = 2 * m;
53
+ let numerator = m * (b - m) * x / ((a + m2 - 1) * (a + m2));
54
+ d = 1 + numerator * d;
55
+ if (Math.abs(d) < 1e-30) d = 1e-30;
56
+ c = 1 + numerator / c;
57
+ if (Math.abs(c) < 1e-30) c = 1e-30;
58
+ d = 1 / d;
59
+ fraction *= d * c;
60
+ numerator = -((a + m) * (a + b + m) * x) / ((a + m2) * (a + m2 + 1));
61
+ d = 1 + numerator * d;
62
+ if (Math.abs(d) < 1e-30) d = 1e-30;
63
+ c = 1 + numerator / c;
64
+ if (Math.abs(c) < 1e-30) c = 1e-30;
65
+ d = 1 / d;
66
+ const delta = d * c;
67
+ fraction *= delta;
68
+ if (Math.abs(delta - 1) < epsilon) break;
69
+ }
70
+ return fraction;
71
+ }
72
+ // src/math/student-t.ts
73
+ /**
74
+ * Student-t CDF via the regularized incomplete beta function.
75
+ */
76
+ function studentTCdf(t, degreesOfFreedom) {
77
+ if (degreesOfFreedom <= 0) return .5;
78
+ const beta = regularizedIncompleteBeta(degreesOfFreedom / (degreesOfFreedom + t * t), degreesOfFreedom / 2, .5);
79
+ return t >= 0 ? 1 - .5 * beta : .5 * beta;
80
+ }
81
+ /**
82
+ * Inverse Student-t CDF, solved against {@link studentTCdf}.
83
+ *
84
+ * The CDF is monotone, so bracket expansion followed by bisection is stable
85
+ * across fractional degrees of freedom and does not need a separate
86
+ * approximation with a different error profile.
87
+ */
88
+ function studentTQuantile(probability, degreesOfFreedom) {
89
+ if (!Number.isFinite(probability) || probability < 0 || probability > 1) throw new RangeError(`studentTQuantile: probability must be in [0,1], got ${probability}`);
90
+ if (!Number.isFinite(degreesOfFreedom) || degreesOfFreedom <= 0) throw new RangeError(`studentTQuantile: degreesOfFreedom must be positive and finite, got ${degreesOfFreedom}`);
91
+ if (probability === 0) return Number.NEGATIVE_INFINITY;
92
+ if (probability === 1) return Number.POSITIVE_INFINITY;
93
+ if (probability === .5) return 0;
94
+ if (probability < .5) return -studentTQuantile(1 - probability, degreesOfFreedom);
95
+ let low = 0;
96
+ let high = 1;
97
+ while (studentTCdf(high, degreesOfFreedom) < probability) high *= 2;
98
+ for (let iteration = 0; iteration < 64; iteration++) {
99
+ const middle = (low + high) / 2;
100
+ if (studentTCdf(middle, degreesOfFreedom) < probability) low = middle;
101
+ else high = middle;
102
+ }
103
+ return (low + high) / 2;
104
+ }
105
+ // src/statistics/cluster.ts
106
+ const DEFAULT_BOOTSTRAP_SEED = 12648430;
107
+ /** Percentile bootstrap; degenerate resamples are omitted, with NaN bounds if none remain. */
108
+ function clusterBootstrap(items, cluster, statistic, { resamples = 2e3, seed = DEFAULT_BOOTSTRAP_SEED, level = .95, strata } = {}) {
109
+ if (!Number.isSafeInteger(resamples) || resamples < 0 || !(level > 0 && level < 1)) throw new ValidationError("clusterBootstrap: requires nonnegative resamples and level in (0,1)");
110
+ const groups = /* @__PURE__ */ new Map();
111
+ items.forEach((item, index) => {
112
+ const key = cluster(item, index), stratum = strata?.(item, index) ?? "";
113
+ if (typeof key !== "string" || !key || typeof stratum !== "string") throw new ValidationError("clusterBootstrap: requires string cluster id and stratum");
114
+ const group = groups.get(key) ?? {
115
+ stratum,
116
+ rows: []
117
+ };
118
+ if (group.stratum !== stratum) throw new ValidationError("clusterBootstrap: cluster crosses strata");
119
+ group.rows.push(item);
120
+ groups.set(key, group);
121
+ });
122
+ const cells = /* @__PURE__ */ new Map();
123
+ for (const { stratum, rows } of groups.values()) {
124
+ if (!cells.has(stratum)) cells.set(stratum, []);
125
+ cells.get(stratum).push(rows);
126
+ }
127
+ const rng = mulberry32(seed), values = [];
128
+ for (let b = 0; b < resamples; b++) {
129
+ const value = statistic([...cells.values()].flatMap((clusters) => Array.from({ length: clusters.length }, () => clusters[Math.floor(rng() * clusters.length)]).flat()));
130
+ if (Number.isFinite(value)) values.push(value);
131
+ }
132
+ values.sort((a, b) => a - b);
133
+ return {
134
+ low: interpolatedQuantile(values, (1 - level) / 2),
135
+ high: interpolatedQuantile(values, (1 + level) / 2),
136
+ resamples,
137
+ clusters: groups.size
138
+ };
139
+ }
140
+ function placeboBand(history, options) {
141
+ const { timestamp, cluster, statistic, clustersPerArm, delta, steps = [] } = options;
142
+ if (!Number.isSafeInteger(clustersPerArm) || clustersPerArm < 1 || !Number.isFinite(delta) || steps.some((t) => !Number.isFinite(t))) throw new ValidationError("placeboBand: invalid cluster count, delta or step");
143
+ const groups = /* @__PURE__ */ new Map();
144
+ for (const row of history) {
145
+ const ts = timestamp(row), key = cluster(row);
146
+ if (!Number.isFinite(ts) || typeof key !== "string" || !key) throw new ValidationError("placeboBand: invalid timestamp or cluster");
147
+ const group = groups.get(key) ?? {
148
+ start: ts,
149
+ end: ts,
150
+ rows: []
151
+ };
152
+ group.start = Math.min(group.start, ts);
153
+ group.end = Math.max(group.end, ts);
154
+ group.rows.push(row);
155
+ groups.set(key, group);
156
+ }
157
+ const ordered = [...groups.values()].sort((a, b) => a.start - b.start);
158
+ const start = ordered[0]?.start ?? 0, end = Math.max(start, ...ordered.map((g) => g.end));
159
+ const hour = 36e5;
160
+ const candidates = [...options.boundaries ?? Array.from({ length: Math.max(0, Math.floor(end / hour) - Math.ceil(start / hour) + 1) }, (_, i) => (Math.ceil(start / hour) + i) * hour)].sort((a, b) => a - b);
161
+ if (candidates.some((t, i) => !Number.isFinite(t) || i > 0 && t - candidates[i - 1] < hour)) throw new ValidationError("placeboBand: boundaries must be at least one hour apart");
162
+ const deltas = [], boundaries = [];
163
+ if (end - start >= 72 * hour) for (const boundary of candidates) {
164
+ if (ordered.some((g) => g.start < boundary && g.end >= boundary)) continue;
165
+ const before = ordered.filter((g) => g.end < boundary).slice(-clustersPerArm);
166
+ const after = ordered.filter((g) => g.start >= boundary).slice(0, clustersPerArm);
167
+ if (before.length !== clustersPerArm || after.length !== clustersPerArm) continue;
168
+ const windowEnd = Math.max(...after.map((g) => g.end));
169
+ if (steps.some((t) => t >= before[0].start && t <= windowEnd)) continue;
170
+ const value = statistic(before.flatMap((g) => g.rows), after.flatMap((g) => g.rows));
171
+ if (!Number.isFinite(value)) throw new ValidationError("placeboBand: statistic must be finite");
172
+ boundaries.push(boundary);
173
+ deltas.push(value);
174
+ }
175
+ const calibrated = deltas.length >= 39, sorted = [...deltas].sort((a, b) => a - b);
176
+ const q025 = calibrated ? interpolatedQuantile(sorted, .025) : null, q975 = calibrated ? interpolatedQuantile(sorted, .975) : null;
177
+ return {
178
+ status: calibrated ? "calibrated" : "uncalibrated",
179
+ n: history.length,
180
+ K: deltas.length,
181
+ clustersPerArm,
182
+ boundaries,
183
+ deltas,
184
+ q025,
185
+ q975,
186
+ low: q975 === null ? null : delta - q975,
187
+ high: q025 === null ? null : delta - q025
188
+ };
189
+ }
190
+ // src/statistics/internal.ts
191
+ /**
192
+ * Shared internals for the statistics modules. Nothing here is part of the
193
+ * public statistics surface — `./index` does not re-export this module.
194
+ */
195
+ /** Every rank test refuses non-finite input. Beyond the arithmetic being
196
+ * undefined, the tie-grouping scan compares values with `===`, and
197
+ * `NaN === NaN` is false, so a NaN would leave the group boundary unable to
198
+ * advance and spin the loop forever. */
199
+ function assertFiniteSample(fn, label, xs) {
200
+ for (let i = 0; i < xs.length; i++) if (!Number.isFinite(xs[i])) throw new ValidationError(`${fn}: ${label}[${i}] must be finite, got ${xs[i]}`);
201
+ }
202
+ /**
203
+ * Two-sided exact p-value for b successes out of (b + c) Bernoulli(0.5) trials —
204
+ * the exact-binomial core of {@link mcnemar}. `min(1, 2·P(X ≤ min(b,c)))`. No
205
+ * discordant pairs ⇒ no evidence ⇒ p = 1. Summed in log space (lnGamma) so it
206
+ * stays exact at large discordant counts without overflow.
207
+ */
208
+ function binomialSignTwoSided(b, c) {
209
+ const nd = b + c;
210
+ if (nd === 0) return 1;
211
+ return Math.min(1, 2 * binomialHalfLowerTail(Math.min(b, c), nd));
212
+ }
213
+ /** P(X >= successes) for X ~ Binomial(n, 0.5). */
214
+ function binomialHalfUpperTail(successes, n) {
215
+ if (successes <= 0) return 1;
216
+ if (successes > n) return 0;
217
+ if (successes <= n / 2) return Math.max(0, 1 - binomialHalfLowerTail(successes - 1, n));
218
+ return binomialHalfLowerTail(n - successes, n);
219
+ }
220
+ /** P(X <= maxSuccesses) for X ~ Binomial(n, 0.5), accumulated in log space. */
221
+ function binomialHalfLowerTail(maxSuccesses, n) {
222
+ if (maxSuccesses < 0) return 0;
223
+ if (maxSuccesses >= n) return 1;
224
+ if (maxSuccesses === 0) return 2 ** -n;
225
+ const logHalfN = n * Math.log(.5);
226
+ let logTail = Number.NEGATIVE_INFINITY;
227
+ for (let i = 0; i <= maxSuccesses; i++) {
228
+ const logChoose = lnGamma(n + 1) - lnGamma(i + 1) - lnGamma(n - i + 1);
229
+ logTail = logAddExp(logTail, logChoose + logHalfN);
230
+ }
231
+ return Math.min(1, Math.exp(logTail));
232
+ }
233
+ function logAddExp(a, b) {
234
+ if (a === Number.NEGATIVE_INFINITY) return b;
235
+ if (b === Number.NEGATIVE_INFINITY) return a;
236
+ const max = Math.max(a, b);
237
+ return max + Math.log1p(Math.exp(Math.min(a, b) - max));
238
+ }
239
+ /** Standard-normal inverse CDF (Acklam approximation). */
240
+ function zQuantile(p) {
241
+ if (p <= 0 || p >= 1) {
242
+ if (p === 0) return -Infinity;
243
+ if (p === 1) return Infinity;
244
+ return NaN;
245
+ }
246
+ const a = [
247
+ -39.69683028665376,
248
+ 220.9460984245205,
249
+ -275.9285104469687,
250
+ 138.357751867269,
251
+ -30.66479806614716,
252
+ 2.506628277459239
253
+ ];
254
+ const b = [
255
+ -54.47609879822406,
256
+ 161.5858368580409,
257
+ -155.6989798598866,
258
+ 66.80131188771972,
259
+ -13.28068155288572
260
+ ];
261
+ const c = [
262
+ -.007784894002430293,
263
+ -.3223964580411365,
264
+ -2.400758277161838,
265
+ -2.549732539343734,
266
+ 4.374664141464968,
267
+ 2.938163982698783
268
+ ];
269
+ const d = [
270
+ .007784695709041462,
271
+ .3224671290700398,
272
+ 2.445134137142996,
273
+ 3.754408661907416
274
+ ];
275
+ const pLow = .02425;
276
+ const pHigh = .97575;
277
+ let q;
278
+ let r;
279
+ if (p < pLow) {
280
+ q = Math.sqrt(-2 * Math.log(p));
281
+ return (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1);
282
+ }
283
+ if (p <= pHigh) {
284
+ q = p - .5;
285
+ r = q * q;
286
+ return (((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q / (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1);
287
+ }
288
+ q = Math.sqrt(-2 * Math.log(1 - p));
289
+ return -(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1);
290
+ }
291
+ function medianInPlace(xs) {
292
+ if (xs.length === 0) return 0;
293
+ xs.sort((a, b) => a - b);
294
+ return interpolatedQuantile(xs, .5);
295
+ }
296
+ /**
297
+ * PRNG for every resampling path in this module.
298
+ *
299
+ * With no caller seed the seed is DERIVED FROM THE DATA rather than taken from
300
+ * `Math.random`, so re-running the same input reproduces the same interval —
301
+ * a gate verdict that cannot be re-derived is not evidence. Distinct data
302
+ * still gets a distinct stream. Same pattern as `promotion-gate.ts`.
303
+ */
304
+ function makeRng(seed, ...series) {
305
+ return mulberry32(seed ?? seedFromData(series));
306
+ }
307
+ /** FNV-1a over the IEEE-754 bytes of every observation. */
308
+ function seedFromData(series) {
309
+ const view = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));
310
+ let hash = 2166136261;
311
+ for (const xs of series) {
312
+ for (const x of xs) {
313
+ view.setFloat64(0, x);
314
+ for (let byte = 0; byte < 8; byte++) hash = Math.imul(hash ^ view.getUint8(byte), 16777619);
315
+ }
316
+ hash = Math.imul(hash ^ 255, 16777619);
317
+ }
318
+ return hash | 0;
319
+ }
320
+ /** Order-independent seed for a symmetric two-sample statistic. */
321
+ function symmetricTwoSampleSeed(a, b) {
322
+ const sortedA = [...a].sort((left, right) => left - right);
323
+ const sortedB = [...b].sort((left, right) => left - right);
324
+ const forward = seedFromData([sortedA, sortedB]) >>> 0;
325
+ const reversed = seedFromData([sortedB, sortedA]) >>> 0;
326
+ return Math.min(forward, reversed);
327
+ }
328
+ // src/statistics/mean.ts
329
+ /** Arithmetic mean. An empty input has no mean and returns NaN. */
330
+ function mean(values) {
331
+ return values.reduce((sum, value) => sum + value, 0) / values.length;
332
+ }
333
+ /** Arithmetic mean, or null for an empty input. */
334
+ function meanOrNull(values) {
335
+ return values.length === 0 ? null : mean(values);
336
+ }
337
+ /** Arithmetic mean, or 0 for an empty input. */
338
+ function meanOrZero(values) {
339
+ return values.length === 0 ? 0 : mean(values);
340
+ }
341
+ // src/statistics/descriptive.ts
342
+ /**
343
+ * Descriptive statistics: means, bootstrap spread, correlation, and the
344
+ * weighted judge-dimension composite. Nothing here is a significance test.
345
+ */
346
+ /** Weighted mean — falls back to uniform weights when omitted */
347
+ function weightedMean(scores) {
348
+ if (scores.length === 0) return 0;
349
+ let totalWeight = 0;
350
+ let weightedSum = 0;
351
+ for (const { score, weight } of scores) {
352
+ const w = weight ?? 1;
353
+ weightedSum += score * w;
354
+ totalWeight += w;
355
+ }
356
+ return totalWeight > 0 ? weightedSum / totalWeight : 0;
357
+ }
358
+ /**
359
+ * Percentile bootstrap confidence interval on the mean of `scores`.
360
+ *
361
+ * Descriptive spread. It is not a significance test, and at small n its bounds
362
+ * are anti-conservative in the same way {@link pairedBootstrap}'s are — see
363
+ * {@link BOOTSTRAP_GATE_MIN_N}. With no `seed` the resampling is seeded from
364
+ * the scores themselves, so the interval is reproducible either way.
365
+ */
366
+ function confidenceInterval(scores, confidence = .95, opts = {}) {
367
+ if (scores.length === 0) return {
368
+ mean: 0,
369
+ lower: 0,
370
+ upper: 0
371
+ };
372
+ if (scores.length === 1) return {
373
+ mean: scores[0],
374
+ lower: scores[0],
375
+ upper: scores[0]
376
+ };
377
+ const n = scores.length;
378
+ const mean = scores.reduce((a, b) => a + b, 0) / n;
379
+ const B = opts.resamples ?? 1e3;
380
+ const rng = makeRng(opts.seed, scores);
381
+ const bootstrapMeans = [];
382
+ for (let i = 0; i < B; i++) {
383
+ let sum = 0;
384
+ for (let j = 0; j < n; j++) sum += scores[Math.floor(rng() * n)];
385
+ bootstrapMeans.push(sum / n);
386
+ }
387
+ bootstrapMeans.sort((a, b) => a - b);
388
+ const alpha = 1 - confidence;
389
+ const lowerIdx = Math.floor(alpha / 2 * B);
390
+ const upperIdx = Math.floor((1 - alpha / 2) * B) - 1;
391
+ return {
392
+ mean,
393
+ lower: bootstrapMeans[lowerIdx],
394
+ upper: bootstrapMeans[Math.min(upperIdx, B - 1)]
395
+ };
396
+ }
397
+ /**
398
+ * Two-sided Student-t critical value: the `t` with `P(|T| ≤ t) = confidence`
399
+ * for `df` degrees of freedom. Exact, from {@link studentTQuantile}, so any
400
+ * confidence in (0, 1) and fractional `df` are supported.
401
+ */
402
+ function studentTCritical(df, confidence = .95) {
403
+ if (!Number.isFinite(confidence) || confidence <= 0 || confidence >= 1) throw new ValidationError(`studentTCritical: confidence must be in (0, 1), got ${confidence}`);
404
+ if (!Number.isFinite(df) || df <= 0) throw new ValidationError(`studentTCritical: df must be positive and finite, got ${df}`);
405
+ return studentTQuantile(1 - (1 - confidence) / 2, df);
406
+ }
407
+ /**
408
+ * Student-t confidence interval on the mean of one sample:
409
+ * `mean ± t(df = n − 1) · s / √n`. Below two samples there is no spread to
410
+ * estimate, so the bounds are null rather than a zero-width interval that
411
+ * would read as certainty. Unlike {@link confidenceInterval} (a percentile
412
+ * bootstrap), the width keeps the small-n t penalty that z = 1.96 drops.
413
+ */
414
+ function meanConfidenceInterval(samples, confidence = .95) {
415
+ assertFiniteSample("meanConfidenceInterval", "samples", samples);
416
+ const n = samples.length;
417
+ if (!Number.isFinite(confidence) || confidence <= 0 || confidence >= 1) throw new ValidationError(`meanConfidenceInterval: confidence must be in (0, 1), got ${confidence}`);
418
+ if (n < 2) return {
419
+ n,
420
+ mean: n === 0 ? null : samples[0],
421
+ stdev: null,
422
+ low: null,
423
+ high: null,
424
+ criticalValue: null
425
+ };
426
+ const center = mean(samples);
427
+ const sumSquares = samples.reduce((sum, value) => sum + (value - center) ** 2, 0);
428
+ const stdev = Math.sqrt(sumSquares / (n - 1));
429
+ const criticalValue = studentTCritical(n - 1, confidence);
430
+ const halfWidth = criticalValue * stdev / Math.sqrt(n);
431
+ return {
432
+ n,
433
+ mean: center,
434
+ stdev,
435
+ low: center - halfWidth,
436
+ high: center + halfWidth,
437
+ criticalValue
438
+ };
439
+ }
440
+ /** Partial credit: returns 0-1 ratio of current toward target */
441
+ function partialCredit(current, target) {
442
+ if (target <= 0) return 1;
443
+ return Math.min(1, Math.max(0, current / target));
444
+ }
445
+ /**
446
+ * Fold a number series into its distribution summary. Quantiles use the
447
+ * nearest-rank definition — the `ceil(q·n)`-th order statistic — so every
448
+ * reported quantile is a value from the series. Returns `null` for an empty
449
+ * series: an empty series has no distribution, and a zero-filled summary
450
+ * would read as a measured all-zero series.
451
+ */
452
+ function summarizeNumberSeries(values, options) {
453
+ const criticalValue = options?.medianInterval?.criticalValue;
454
+ if (options) {
455
+ assertFiniteSample("summarizeNumberSeries", "values", values);
456
+ for (const percentile of options.percentiles ?? []) if (!Number.isFinite(percentile) || percentile < 0 || percentile > 100) throw new ValidationError("summarizeNumberSeries: percentiles must be finite and between 0 and 100");
457
+ if (options.medianInterval && (criticalValue === void 0 || !Number.isFinite(criticalValue) || criticalValue < 0)) throw new ValidationError("summarizeNumberSeries: median criticalValue must be finite and nonnegative");
458
+ }
459
+ if (values.length === 0) return null;
460
+ const sorted = [...values].sort((a, b) => a - b);
461
+ const n = sorted.length;
462
+ const rank = (q) => sorted[Math.min(n - 1, Math.max(0, Math.ceil(q * n) - 1))];
463
+ const sum = sorted.reduce((a, b) => a + b, 0);
464
+ if (options && !Number.isFinite(sum)) throw new ValidationError("summarizeNumberSeries: sample sum exceeded finite range");
465
+ const spread = criticalValue === void 0 ? void 0 : criticalValue / 2 * Math.sqrt(n);
466
+ const lowRank = spread === void 0 ? 1 : Math.max(1, Math.floor(n / 2 - spread));
467
+ const highRank = spread === void 0 ? n : Math.min(n, Math.ceil(n / 2 + 1 + spread));
468
+ return {
469
+ n,
470
+ min: sorted[0],
471
+ p50: rank(.5),
472
+ p90: rank(.9),
473
+ max: sorted[sorted.length - 1],
474
+ sum,
475
+ ...options?.percentiles === void 0 ? {} : { percentiles: Object.fromEntries(options.percentiles.map((percentile) => [percentile, rank(percentile / 100)])) },
476
+ ...criticalValue === void 0 ? {} : { medianInterval: {
477
+ method: "normal-order-statistics",
478
+ criticalValue,
479
+ sampleSize: n,
480
+ lowRank,
481
+ highRank,
482
+ low: sorted[lowRank - 1],
483
+ high: sorted[highRank - 1]
484
+ } }
485
+ };
486
+ }
487
+ /**
488
+ * Average-rank-with-ties transform (1-indexed). Tied values receive the mean
489
+ * of the ranks they span, the standard correction for Spearman's ρ.
490
+ */
491
+ function ranks(xs) {
492
+ const indexed = xs.map((v, i) => ({
493
+ v,
494
+ i
495
+ })).sort((a, b) => a.v - b.v);
496
+ const r = new Array(xs.length);
497
+ let i = 0;
498
+ while (i < indexed.length) {
499
+ let j = i;
500
+ while (j + 1 < indexed.length && indexed[j + 1].v === indexed[i].v) j++;
501
+ const avg = (i + j) / 2 + 1;
502
+ for (let k = i; k <= j; k++) r[indexed[k].i] = avg;
503
+ i = j + 1;
504
+ }
505
+ return r;
506
+ }
507
+ /**
508
+ * Pearson product-moment correlation coefficient r ∈ [-1, 1] between two
509
+ * equal-length series. See the edge-case contract above: NaN for n < 2 or
510
+ * unequal lengths, 1 when both series are constant, 0 when exactly one is.
511
+ */
512
+ function pearsonR(a, b) {
513
+ if (a.length !== b.length || a.length < 2) return NaN;
514
+ const n = a.length;
515
+ const meanA = a.reduce((s, v) => s + v, 0) / n;
516
+ const meanB = b.reduce((s, v) => s + v, 0) / n;
517
+ let num = 0;
518
+ let varA = 0;
519
+ let varB = 0;
520
+ for (let i = 0; i < n; i++) {
521
+ const da = a[i] - meanA;
522
+ const db = b[i] - meanB;
523
+ num += da * db;
524
+ varA += da * da;
525
+ varB += db * db;
526
+ }
527
+ if (varA === 0 || varB === 0) return varA === 0 && varB === 0 ? 1 : 0;
528
+ return num / Math.sqrt(varA * varB);
529
+ }
530
+ /**
531
+ * Spearman's rank correlation ρ — Pearson over the average-rank-with-ties
532
+ * transform of each series. Same edge-case contract as {@link pearsonR}.
533
+ */
534
+ function spearmanR(a, b) {
535
+ if (a.length !== b.length || a.length < 2) return NaN;
536
+ return pearsonR(ranks(a), ranks(b));
537
+ }
538
+ /**
539
+ * Weighted composite over judge dimensions: `Σ(score_d · w_d) / Σ(w_d)` across
540
+ * the weighted dimensions. The canonical replacement for the per-consumer
541
+ * hand-rolled composite math (tax/legal/creative/gtm each ship a copy).
542
+ *
543
+ * Fail-loud: throws if a weighted dimension is missing from `dims`, if any
544
+ * weight is negative, or if the weights sum to 0 — none of which can produce
545
+ * a meaningful composite.
546
+ */
547
+ function weightedComposite(input) {
548
+ const entries = Object.entries(input.weights);
549
+ if (entries.length === 0) throw new Error("weightedComposite: `weights` is empty — nothing to combine");
550
+ let weightedSum = 0;
551
+ let weightTotal = 0;
552
+ for (const [dim, weight] of entries) {
553
+ if (weight < 0) throw new Error(`weightedComposite: weight for '${dim}' is negative (${weight})`);
554
+ if (!(dim in input.dims)) throw new Error(`weightedComposite: weighted dimension '${dim}' is absent from \`dims\` — refusing to renormalise onto a different denominator`);
555
+ weightedSum += input.dims[dim] * weight;
556
+ weightTotal += weight;
557
+ }
558
+ if (weightTotal === 0) throw new Error("weightedComposite: weights sum to 0 — composite is undefined");
559
+ const composite = weightedSum / weightTotal;
560
+ return input.threshold === void 0 ? { composite } : {
561
+ composite,
562
+ pass: composite >= input.threshold
563
+ };
564
+ }
565
+ // src/judge-calibration.ts
566
+ /**
567
+ * Judge calibration — measure judge quality against human gold + bias.
568
+ *
569
+ * Workflow:
570
+ * 1. Build a golden set: {itemId, humanScore}[].
571
+ * 2. Run candidate judges; each produces {itemId, score}.
572
+ * 3. `calibrateJudge(golden, candidate)` reports κ + Pearson + MAE.
573
+ * 4. `calibrateJudgeContinuous(golden, candidate)` adds quadratic-weighted
574
+ * κ over the un-rounded [0,1] scores plus ICC(2,1), Pearson, Spearman,
575
+ * and bootstrap CIs — use this for fine-grained judges where rounding
576
+ * to int discards information (e.g. 0.78 vs 0.81 both round to 1 and
577
+ * look "perfectly agreed" to integer κ).
578
+ * 5. Run bias probes (positional, verbosity, self-preference) to
579
+ * detect systematic score inflation.
580
+ * 6. For N≥2 judges on the same items, `continuousAgreement(scores)`
581
+ * reports ICC(2,1) + κ_w + Pearson + Spearman with bootstrap CIs.
582
+ *
583
+ * Returns actionable diagnostics, not a single number. Consumers then
584
+ * decide whether to trust the judge, retrain it, or add a tie-breaker.
585
+ */
586
+ /**
587
+ * Measure judge quality against human gold labels: computes Cohen's κ, Pearson correlation, and MAE over matched item ids.
588
+ */
589
+ function calibrateJudge(golden, candidate) {
590
+ const map = /* @__PURE__ */ new Map();
591
+ for (const g of golden) map.set(g.itemId, {
592
+ h: g.humanScore,
593
+ j: NaN
594
+ });
595
+ for (const c of candidate) {
596
+ const entry = map.get(c.itemId);
597
+ if (entry) entry.j = c.score;
598
+ }
599
+ const common = [...map.values()].filter((v) => Number.isFinite(v.j));
600
+ const n = common.length;
601
+ if (n < 2) return {
602
+ n,
603
+ pearson: NaN,
604
+ kappa: NaN,
605
+ mae: NaN,
606
+ worstItems: []
607
+ };
608
+ const humans = common.map((c) => c.h);
609
+ const judges = common.map((c) => c.j);
610
+ return {
611
+ n,
612
+ pearson: pearsonR(humans, judges),
613
+ kappa: weightedKappa(humans.map(Math.round), judges.map(Math.round)),
614
+ mae: common.map((c) => Math.abs(c.j - c.h)).reduce((a, b) => a + b, 0) / n,
615
+ worstItems: [...map.entries()].filter(([, v]) => Number.isFinite(v.j)).map(([itemId, v]) => ({
616
+ itemId,
617
+ judge: v.j,
618
+ human: v.h,
619
+ delta: Math.abs(v.j - v.h)
620
+ })).sort((a, b) => b.delta - a.delta).slice(0, 5)
621
+ };
622
+ }
623
+ /**
624
+ * Feed the same items to the judge twice with A/B swapped and pass all
625
+ * results here. Items that don't appear in both positions are ignored.
626
+ */
627
+ function positionalBias(scores) {
628
+ const pairs = /* @__PURE__ */ new Map();
629
+ for (const s of scores) {
630
+ const slot = pairs.get(s.itemId) ?? {};
631
+ if (s.positionOfAInput === "first") slot.first = s.score;
632
+ else if (s.positionOfAInput === "second") slot.second = s.score;
633
+ pairs.set(s.itemId, slot);
634
+ }
635
+ const deltas = [];
636
+ for (const { first, second } of pairs.values()) if (first !== void 0 && second !== void 0) deltas.push(first - second);
637
+ if (deltas.length === 0) return {
638
+ avgDelta: 0,
639
+ n: 0
640
+ };
641
+ return {
642
+ avgDelta: deltas.reduce((a, b) => a + b, 0) / deltas.length,
643
+ n: deltas.length
644
+ };
645
+ }
646
+ function verbosityBias(samples) {
647
+ const n = samples.length;
648
+ if (n < 3) return {
649
+ pearson: NaN,
650
+ n
651
+ };
652
+ return {
653
+ pearson: pearsonR(samples.map((s) => s.outputLen), samples.map((s) => s.score)),
654
+ n
655
+ };
656
+ }
657
+ /**
658
+ * Pass the same scenarios scored with judge-model X grading outputs from
659
+ * model X (in-family) and model Y (out-of-family). Non-zero delta
660
+ * indicates self-preference.
661
+ */
662
+ function selfPreference(samples) {
663
+ const inF = samples.filter((s) => s.inFamily).map((s) => s.score);
664
+ const outF = samples.filter((s) => !s.inFamily).map((s) => s.score);
665
+ if (inF.length === 0 || outF.length === 0) return {
666
+ inFamilyMean: 0,
667
+ outOfFamilyMean: 0,
668
+ deltaMean: 0,
669
+ n: 0
670
+ };
671
+ const inMean = inF.reduce((a, b) => a + b, 0) / inF.length;
672
+ const outMean = outF.reduce((a, b) => a + b, 0) / outF.length;
673
+ return {
674
+ inFamilyMean: inMean,
675
+ outOfFamilyMean: outMean,
676
+ deltaMean: inMean - outMean,
677
+ n: samples.length
678
+ };
679
+ }
680
+ /** Quadratic weighted Cohen's κ over bounded integer scores. */
681
+ function weightedKappa(a, b) {
682
+ if (a.length !== b.length || a.length === 0) return NaN;
683
+ const min = Math.min(...a, ...b);
684
+ const K = Math.max(...a, ...b) - min + 1;
685
+ if (K < 2) return 1;
686
+ const observed = Array.from({ length: K }, () => new Array(K).fill(0));
687
+ const rowMarg = new Array(K).fill(0);
688
+ const colMarg = new Array(K).fill(0);
689
+ for (let i = 0; i < a.length; i++) {
690
+ const ai = a[i] - min;
691
+ const bi = b[i] - min;
692
+ const row = observed[ai];
693
+ row[bi] = (row[bi] ?? 0) + 1;
694
+ rowMarg[ai]++;
695
+ colMarg[bi]++;
696
+ }
697
+ let num = 0;
698
+ let den = 0;
699
+ for (let i = 0; i < K; i++) for (let j = 0; j < K; j++) {
700
+ const w = (i - j) ** 2 / (K - 1) ** 2;
701
+ const expected = rowMarg[i] * colMarg[j] / a.length;
702
+ num += w * observed[i][j];
703
+ den += w * expected;
704
+ }
705
+ if (den === 0) return 1;
706
+ return 1 - num / den;
707
+ }
708
+ /**
709
+ * Inter-rater agreement on continuous (typically [0,1]) scores.
710
+ *
711
+ * `scores` has shape [n_items][n_raters]. Rows with any non-finite entry
712
+ * are dropped. Returns NaN metrics if fewer than 2 raters or 2 complete
713
+ * items remain.
714
+ */
715
+ function continuousAgreement(scores, opts = {}) {
716
+ const bootstrap = opts.bootstrap ?? 1e3;
717
+ const weights = opts.weights ?? "quadratic";
718
+ const seed = opts.seed ?? 12648430;
719
+ const ciLevel = opts.ciLevel ?? .95;
720
+ const matrix = scores.filter((row) => row.length >= 2 && row.every((v) => Number.isFinite(v)));
721
+ const raters = matrix[0]?.length ?? 0;
722
+ const clean = matrix.filter((row) => row.length === raters);
723
+ const nClean = clean.length;
724
+ if (nClean < 2 || raters < 2) return {
725
+ weightedKappa: NaN,
726
+ icc: NaN,
727
+ pearson: NaN,
728
+ spearman: NaN,
729
+ ci: {
730
+ icc: [NaN, NaN],
731
+ weightedKappa: [NaN, NaN]
732
+ },
733
+ n: nClean,
734
+ raters
735
+ };
736
+ const kappa = continuousWeightedKappa(clean, weights);
737
+ const icc = icc21(clean);
738
+ const pearson = avgPairwise(clean, pearsonR);
739
+ const spearman = avgPairwise(clean, spearmanR);
740
+ const interval = (statistic) => {
741
+ const ci = clusterBootstrap(clean, (_, i) => String(i), statistic, {
742
+ resamples: bootstrap,
743
+ seed,
744
+ level: ciLevel
745
+ });
746
+ return [ci.low, ci.high];
747
+ };
748
+ return {
749
+ weightedKappa: kappa,
750
+ icc,
751
+ pearson,
752
+ spearman,
753
+ ci: {
754
+ icc: interval(icc21),
755
+ weightedKappa: interval((sample) => continuousWeightedKappa(sample, weights))
756
+ },
757
+ n: nClean,
758
+ raters
759
+ };
760
+ }
761
+ /**
762
+ * Extends `calibrateJudge` with continuous-value agreement metrics while
763
+ * retaining its base calibration summary.
764
+ */
765
+ function calibrateJudgeContinuous(golden, candidate, opts = {}) {
766
+ const base = calibrateJudge(golden, candidate);
767
+ const map = /* @__PURE__ */ new Map();
768
+ for (const g of golden) map.set(g.itemId, {
769
+ h: g.humanScore,
770
+ j: NaN
771
+ });
772
+ for (const c of candidate) {
773
+ const entry = map.get(c.itemId);
774
+ if (entry) entry.j = c.score;
775
+ }
776
+ const rows = [];
777
+ for (const v of map.values()) if (Number.isFinite(v.j)) rows.push([v.h, v.j]);
778
+ const agreement = continuousAgreement(rows, opts);
779
+ return {
780
+ ...base,
781
+ weightedKappaContinuous: agreement.weightedKappa,
782
+ icc: agreement.icc,
783
+ spearman: agreement.spearman,
784
+ ci: agreement.ci
785
+ };
786
+ }
787
+ /**
788
+ * Quadratic-weighted κ on continuous scores. With weights w(x,y) = (x-y)^2
789
+ * (or |x-y| for linear) the formula collapses to:
790
+ *
791
+ * κ_w = 1 − E_obs[w] / E_exp[w]
792
+ *
793
+ * where E_obs averages w over paired (a_i, b_i) and E_exp averages w over
794
+ * the independent product distribution (sum_{i,j} w(a_i, b_j) / n^2).
795
+ * The normalisation by (max-min)^2 in the integer version cancels in the
796
+ * ratio, so we don't need it here. Generalises to N raters by averaging κ_w
797
+ * over all rater pairs (mean pairwise weighted agreement).
798
+ */
799
+ function continuousWeightedKappa(rows, scheme) {
800
+ if (rows.length === 0) return NaN;
801
+ const raters = rows[0].length;
802
+ if (raters < 2) return NaN;
803
+ const wFn = scheme === "linear" ? (x, y) => Math.abs(x - y) : (x, y) => (x - y) ** 2;
804
+ let sum = 0;
805
+ let pairs = 0;
806
+ for (let r1 = 0; r1 < raters; r1++) for (let r2 = r1 + 1; r2 < raters; r2++) {
807
+ const a = rows.map((row) => row[r1]);
808
+ const b = rows.map((row) => row[r2]);
809
+ const n = a.length;
810
+ let obs = 0;
811
+ for (let i = 0; i < n; i++) obs += wFn(a[i], b[i]);
812
+ obs /= n;
813
+ let exp = 0;
814
+ for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) exp += wFn(a[i], b[j]);
815
+ exp /= n * n;
816
+ if (exp === 0) sum += obs === 0 ? 1 : 0;
817
+ else sum += 1 - obs / exp;
818
+ pairs++;
819
+ }
820
+ return pairs === 0 ? NaN : sum / pairs;
821
+ }
822
+ /**
823
+ * ICC(2,1) — two-way random effects, absolute agreement, single rater.
824
+ *
825
+ * ICC(2,1) = (MSR − MSE) / (MSR + (k−1)·MSE + k·(MSC − MSE)/n)
826
+ *
827
+ * where MSR = between-rows MS, MSC = between-columns MS, MSE = residual MS,
828
+ * n = rows (items), k = columns (raters).
829
+ */
830
+ function icc21(rows) {
831
+ const n = rows.length;
832
+ if (n < 2) return NaN;
833
+ const k = rows[0].length;
834
+ if (k < 2) return NaN;
835
+ const rowMeans = rows.map((row) => row.reduce((s, v) => s + v, 0) / k);
836
+ const colMeans = new Array(k).fill(0);
837
+ for (let j = 0; j < k; j++) {
838
+ let s = 0;
839
+ for (let i = 0; i < n; i++) s += rows[i][j];
840
+ colMeans[j] = s / n;
841
+ }
842
+ let grand = 0;
843
+ for (let i = 0; i < n; i++) grand += rowMeans[i];
844
+ grand /= n;
845
+ let ssR = 0;
846
+ for (let i = 0; i < n; i++) ssR += (rowMeans[i] - grand) ** 2;
847
+ ssR *= k;
848
+ let ssC = 0;
849
+ for (let j = 0; j < k; j++) ssC += (colMeans[j] - grand) ** 2;
850
+ ssC *= n;
851
+ let ssT = 0;
852
+ for (let i = 0; i < n; i++) for (let j = 0; j < k; j++) ssT += (rows[i][j] - grand) ** 2;
853
+ const ssE = ssT - ssR - ssC;
854
+ const dfR = n - 1;
855
+ const dfC = k - 1;
856
+ const dfE = (n - 1) * (k - 1);
857
+ const msR = ssR / dfR;
858
+ const msC = ssC / dfC;
859
+ const msE = dfE > 0 ? ssE / dfE : 0;
860
+ const denom = msR + (k - 1) * msE + k * (msC - msE) / n;
861
+ if (denom === 0) return msR === 0 && msE === 0 ? 1 : 0;
862
+ return (msR - msE) / denom;
863
+ }
864
+ /** Average pairwise statistic over all rater pairs. */
865
+ function avgPairwise(rows, fn) {
866
+ const k = rows[0]?.length ?? 0;
867
+ if (k < 2) return NaN;
868
+ let sum = 0;
869
+ let pairs = 0;
870
+ for (let i = 0; i < k; i++) for (let j = i + 1; j < k; j++) {
871
+ const r = fn(rows.map((row) => row[i]), rows.map((row) => row[j]));
872
+ if (Number.isFinite(r)) {
873
+ sum += r;
874
+ pairs++;
875
+ }
876
+ }
877
+ return pairs === 0 ? NaN : sum / pairs;
878
+ }
879
+ // src/statistics/agreement-irr.ts
880
+ /**
881
+ * Inter-rater reliability — Krippendorff's α under the squared-difference
882
+ * metric, pooled across dimensions.
883
+ *
884
+ * Each inner array is one judge's scores. Items are matched by position
885
+ * WITHIN a dimension: the k-th score a judge supplies carrying dimension
886
+ * `d` is item k of `d`, and the ratings compared against each other are
887
+ * the ones different judges gave to the same item. Every judge that scores
888
+ * a dimension at all must supply the same number of scores for it —
889
+ * ragged input cannot be aligned into items and throws rather than
890
+ * comparing mismatched items.
891
+ *
892
+ * α = 1 − D_observed / D_expected: D_observed averages the squared
893
+ * difference over within-item judge pairs, D_expected over every pair of
894
+ * ratings irrespective of item. α = 1 is perfect agreement, 0 is chance,
895
+ * negative is systematic disagreement.
896
+ */
897
+ function interRaterReliability(judgeScores) {
898
+ if (judgeScores.length < 2) return 1;
899
+ const perDimension = /* @__PURE__ */ new Map();
900
+ for (let judgeIndex = 0; judgeIndex < judgeScores.length; judgeIndex++) for (const s of judgeScores[judgeIndex]) {
901
+ let byJudge = perDimension.get(s.dimension);
902
+ if (byJudge === void 0) {
903
+ byJudge = Array.from({ length: judgeScores.length }, () => []);
904
+ perDimension.set(s.dimension, byJudge);
905
+ }
906
+ byJudge[judgeIndex].push(s.score);
907
+ }
908
+ const allValues = [];
909
+ const pairDiffs = [];
910
+ for (const [dimension, byJudge] of perDimension) {
911
+ const scoring = byJudge.filter((scores) => scores.length > 0);
912
+ if (scoring.length < 2) continue;
913
+ const itemCount = scoring[0].length;
914
+ if (scoring.some((scores) => scores.length !== itemCount)) throw new ValidationError(`interRaterReliability: dimension '${dimension}' has judges supplying ${scoring.map((scores) => scores.length).join("/")} scores — items cannot be aligned`);
915
+ for (let item = 0; item < itemCount; item++) {
916
+ const ratings = scoring.map((scores) => scores[item]);
917
+ for (const v of ratings) allValues.push(v);
918
+ for (let i = 0; i < ratings.length; i++) for (let j = i + 1; j < ratings.length; j++) pairDiffs.push((ratings[i] - ratings[j]) ** 2);
919
+ }
920
+ }
921
+ if (pairDiffs.length === 0 || allValues.length < 2) return 1;
922
+ const observedDisagreement = pairDiffs.reduce((a, b) => a + b, 0) / pairDiffs.length;
923
+ let expectedDisagreement = 0;
924
+ let expectedCount = 0;
925
+ for (let i = 0; i < allValues.length; i++) for (let j = i + 1; j < allValues.length; j++) {
926
+ expectedDisagreement += (allValues[i] - allValues[j]) ** 2;
927
+ expectedCount++;
928
+ }
929
+ expectedDisagreement = expectedCount > 0 ? expectedDisagreement / expectedCount : 0;
930
+ if (expectedDisagreement === 0) return 1;
931
+ return 1 - observedDisagreement / expectedDisagreement;
932
+ }
933
+ /**
934
+ * Corpus-wide inter-rater agreement across N items × M judges × D dimensions, the
935
+ * question `interRaterReliability`'s within-item α cannot answer.
936
+ *
937
+ * For each dimension, builds the [n_items][n_judges] matrix of scores
938
+ * (keeping only items every judge rated on that dimension), then runs
939
+ * `continuousAgreement` to get ICC(2,1), κ_w, Pearson, Spearman, and
940
+ * bootstrap CIs. Reports a pooled mean across dimensions as a single
941
+ * "is this judge panel reliable on this corpus?" number. Empty input, fewer than 2 judges or
942
+ * items, a judge without scores on a dimension and duplicate records all throw: a silently
943
+ * shrunk matrix would corrupt the overall metric.
944
+ */
945
+ function corpusInterRaterAgreement(records, opts = {}) {
946
+ if (records.length === 0) throw new ValidationError("corpusInterRaterAgreement: no score records supplied");
947
+ const judgesSeen = /* @__PURE__ */ new Set();
948
+ const dimsSeen = /* @__PURE__ */ new Set();
949
+ const grid = /* @__PURE__ */ new Map();
950
+ for (const r of records) {
951
+ if (!Number.isFinite(r.score)) throw new ValidationError(`corpusInterRaterAgreement: non-finite score for (item=${r.itemId}, judge=${r.judgeName}, dim=${r.dimension})`);
952
+ judgesSeen.add(r.judgeName);
953
+ dimsSeen.add(r.dimension);
954
+ const byJudge = grid.get(r.dimension) ?? /* @__PURE__ */ new Map();
955
+ const byItem = byJudge.get(r.judgeName) ?? /* @__PURE__ */ new Map();
956
+ if (byItem.has(r.itemId)) throw new ValidationError(`corpusInterRaterAgreement: duplicate record for (item=${r.itemId}, judge=${r.judgeName}, dim=${r.dimension})`);
957
+ byItem.set(r.itemId, r.score);
958
+ byJudge.set(r.judgeName, byItem);
959
+ grid.set(r.dimension, byJudge);
960
+ }
961
+ const targetDims = opts.dimensions ?? [...dimsSeen].sort();
962
+ for (const d of targetDims) if (!dimsSeen.has(d)) throw new ValidationError(`corpusInterRaterAgreement: dimension '${d}' was requested but no records carry it`);
963
+ const targetJudges = opts.judges ? [...opts.judges] : [...judgesSeen].sort();
964
+ for (const j of targetJudges) if (!judgesSeen.has(j)) throw new ValidationError(`corpusInterRaterAgreement: judge '${j}' was requested but produced no records`);
965
+ if (targetJudges.length < 2) throw new ValidationError(`corpusInterRaterAgreement: need ≥2 judges, got ${targetJudges.length}`);
966
+ const perDimension = [];
967
+ const iccs = [];
968
+ const kappas = [];
969
+ for (const dim of targetDims) {
970
+ const byJudge = grid.get(dim);
971
+ const judgeItemCounts = Object.fromEntries(targetJudges.map((j) => [j, byJudge.get(j)?.size ?? 0]));
972
+ const emptyJudges = targetJudges.filter((j) => judgeItemCounts[j] === 0);
973
+ if (emptyJudges.length > 0) throw new ValidationError(`corpusInterRaterAgreement: dimension '${dim}' has no scores from judge(s) ${emptyJudges.join(", ")} (counts: ${JSON.stringify(judgeItemCounts)})`);
974
+ const sortedItems = targetJudges.map((j) => [...byJudge.get(j).keys()]).reduce((common, ids) => common.filter((x) => ids.includes(x))).sort();
975
+ if (sortedItems.length < 2) throw new ValidationError(`corpusInterRaterAgreement: dimension '${dim}' has ${sortedItems.length} item(s) rated by all ${targetJudges.length} judges (need ≥2)`);
976
+ const agreement = continuousAgreement(sortedItems.map((itemId) => targetJudges.map((j) => byJudge.get(j).get(itemId))), opts);
977
+ perDimension.push({
978
+ ...agreement,
979
+ dimension: dim,
980
+ itemIds: sortedItems,
981
+ judgeIds: [...targetJudges]
982
+ });
983
+ if (Number.isFinite(agreement.icc)) iccs.push(agreement.icc);
984
+ if (Number.isFinite(agreement.weightedKappa)) kappas.push(agreement.weightedKappa);
985
+ }
986
+ const mean = (xs) => xs.length === 0 ? NaN : xs.reduce((a, b) => a + b, 0) / xs.length;
987
+ return {
988
+ perDimension,
989
+ overallIcc: mean(iccs),
990
+ overallWeightedKappa: mean(kappas),
991
+ dimensions: targetDims,
992
+ judgeIds: targetJudges
993
+ };
994
+ }
995
+ /**
996
+ * Convenience adapter for `DimensionJudgeScore[]` data keyed externally by item.
997
+ *
998
+ * Use when you have per-item arrays of `DimensionJudgeScore[]` (e.g. one
999
+ * `ScenarioResult.judgeScores` per scenario) and want corpus-wide
1000
+ * agreement without manually flattening. `itemId` must be unique per
1001
+ * row of `itemsScores`.
1002
+ */
1003
+ function corpusInterRaterAgreementFromJudgeScores(itemsScores, opts = {}) {
1004
+ const records = [];
1005
+ const seen = /* @__PURE__ */ new Set();
1006
+ for (const { itemId, scores } of itemsScores) {
1007
+ if (seen.has(itemId)) throw new ValidationError(`corpusInterRaterAgreementFromJudgeScores: duplicate itemId '${itemId}'`);
1008
+ seen.add(itemId);
1009
+ for (const s of scores) records.push({
1010
+ itemId,
1011
+ judgeName: s.judgeName,
1012
+ dimension: s.dimension,
1013
+ score: s.score
1014
+ });
1015
+ }
1016
+ return corpusInterRaterAgreement(records, opts);
1017
+ }
1018
+ /**
1019
+ * Unweighted Cohen's κ for paired nominal labels. Labels carry no order, so a
1020
+ * near miss counts as a miss; use `calibrateJudge` for ordinal scores.
1021
+ */
1022
+ function nominalAgreement(pairs, options = {}) {
1023
+ if (options.clusters && options.clusters.length !== pairs.length) throw new ValidationError("nominalAgreement: one cluster per pair");
1024
+ const kappaCi = clusterBootstrap(pairs, (_, index) => options.clusters?.[index] ?? String(index), (sample) => cohenKappa(sample).kappa, options);
1025
+ return {
1026
+ n: pairs.length,
1027
+ ...cohenKappa(pairs),
1028
+ kappaCi
1029
+ };
1030
+ }
1031
+ function cohenKappa(pairs) {
1032
+ const n = pairs.length;
1033
+ if (n === 0) return {
1034
+ agreement: NaN,
1035
+ kappa: NaN
1036
+ };
1037
+ const left = /* @__PURE__ */ new Map();
1038
+ const right = /* @__PURE__ */ new Map();
1039
+ let same = 0;
1040
+ for (const [a, b] of pairs) {
1041
+ if (typeof a !== "string" || typeof b !== "string") throw new ValidationError("nominalAgreement: every label must be a string");
1042
+ if (a === b) same += 1;
1043
+ left.set(a, (left.get(a) ?? 0) + 1);
1044
+ right.set(b, (right.get(b) ?? 0) + 1);
1045
+ }
1046
+ const observed = same / n;
1047
+ let expected = 0;
1048
+ for (const [label, count] of left) expected += count / n * ((right.get(label) ?? 0) / n);
1049
+ return {
1050
+ agreement: observed,
1051
+ kappa: expected === 1 ? NaN : (observed - expected) / (1 - expected)
1052
+ };
1053
+ }
1054
+ // src/statistics/comparison-effects.ts
1055
+ function binary(values, name) {
1056
+ if (values.some((value) => value !== 0 && value !== 1)) throw new ValidationError(`${name}: expected binary 0/1 values`);
1057
+ }
1058
+ /** Mann–Whitney ROC area: ties count half; no observed member of either class means unknown. */
1059
+ function rocAuc(scores, labels) {
1060
+ assertFiniteSample("rocAuc", "scores", scores);
1061
+ binary(labels, "rocAuc.labels");
1062
+ if (scores.length !== labels.length) throw new ValidationError("rocAuc: scores and labels must have equal lengths");
1063
+ const ranked = ranks(scores);
1064
+ const positive = labels.reduce((sum, label) => sum + label, 0);
1065
+ const sum = labels.reduce((total, label, index) => total + label * ranked[index], 0);
1066
+ const negative = labels.length - positive;
1067
+ return positive && negative ? (sum - positive * (positive + 1) / 2) / (positive * negative) : null;
1068
+ }
1069
+ // src/statistics/distribution-summary.ts
1070
+ /** Nearest-rank percentile on a sorted, non-empty sample (0-100 scale). */
1071
+ function nearestRank(sorted, percentile) {
1072
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(percentile / 100 * sorted.length) - 1))];
1073
+ }
1074
+ /**
1075
+ * Nearest-rank percentile on an arbitrary sample, `percentile` on a 0-100
1076
+ * scale — the same rule `summarizeDistribution` applies, exposed for a single
1077
+ * percentile the summary struct does not carry (e.g. p99.9). Returns NaN for
1078
+ * an empty sample; callers that need a numeric floor guard it.
1079
+ */
1080
+ function percentileNearestRank(values, percentile) {
1081
+ if (!Array.isArray(values)) throw new ValidationError("percentileNearestRank: values must be an array");
1082
+ if (values.length === 0) return NaN;
1083
+ return nearestRank([...values].sort((a, b) => a - b), percentile);
1084
+ }
1085
+ function summarizeDistribution(values, options = {}) {
1086
+ if (values.some((value) => !Number.isFinite(value))) throw new ValidationError("summarizeDistribution: samples must be finite");
1087
+ const finite = options.lowerBound === void 0 ? values : values.filter((value) => value >= options.lowerBound);
1088
+ if (finite.length === 0) return {
1089
+ min: NaN,
1090
+ p50: NaN,
1091
+ p90: NaN,
1092
+ p95: NaN,
1093
+ p99: NaN,
1094
+ max: NaN,
1095
+ mean: NaN,
1096
+ n: 0,
1097
+ values: []
1098
+ };
1099
+ const sorted = [...finite].sort((a, b) => a - b);
1100
+ const n = sorted.length;
1101
+ const mean = sorted.reduce((sum, value) => sum + value / n, 0);
1102
+ const sumSquares = sorted.map((value) => value - mean).reduce((sum, value) => sum + value ** 2, 0);
1103
+ const summary = {
1104
+ min: sorted[0],
1105
+ p50: nearestRank(sorted, 50),
1106
+ p90: nearestRank(sorted, 90),
1107
+ p95: nearestRank(sorted, 95),
1108
+ p99: nearestRank(sorted, 99),
1109
+ max: sorted[n - 1],
1110
+ mean,
1111
+ n,
1112
+ values: sorted
1113
+ };
1114
+ if (n >= 2) {
1115
+ const stddev = Math.sqrt(sumSquares / (n - 1));
1116
+ const margin = studentTCritical(n - 1, .95) * stddev / Math.sqrt(n);
1117
+ summary.stddev = stddev;
1118
+ summary.ci95Low = mean - margin;
1119
+ summary.ci95High = mean + margin;
1120
+ }
1121
+ return summary;
1122
+ }
1123
+ // src/statistics/effect-sizes.ts
1124
+ /** Standardized effect sizes; undefined effects remain null. */
1125
+ /** Independent Cohen's d, oriented b − a; null below two samples or for an unbounded effect. */
1126
+ function cohensD(a, b) {
1127
+ if (a.length < 2 || b.length < 2) return null;
1128
+ const meanA = a.reduce((x, y) => x + y, 0) / a.length;
1129
+ const meanB = b.reduce((x, y) => x + y, 0) / b.length;
1130
+ const varA = a.reduce((acc, x) => acc + (x - meanA) ** 2, 0) / (a.length - 1);
1131
+ const varB = b.reduce((acc, x) => acc + (x - meanB) ** 2, 0) / (b.length - 1);
1132
+ const pooled = Math.sqrt(((a.length - 1) * varA + (b.length - 1) * varB) / (a.length + b.length - 2));
1133
+ if (pooled === 0) return meanB === meanA ? 0 : null;
1134
+ return (meanB - meanA) / pooled;
1135
+ }
1136
+ /** Paired Cohen's dz; constant nonzero deltas have no finite standardized effect. */
1137
+ function pairedCohensDz(before, after) {
1138
+ if (before.length !== after.length) throw new ValidationError(`pairedCohensDz: unequal sample sizes (${before.length} vs ${after.length})`);
1139
+ if (before.length < 2) return null;
1140
+ const deltas = before.map((value, index) => after[index] - value);
1141
+ if (deltas.some((value) => !Number.isFinite(value))) throw new ValidationError("pairedCohensDz: all paired values must be finite");
1142
+ const meanDelta = deltas.reduce((sum, value) => sum + value, 0) / deltas.length;
1143
+ const variance = deltas.reduce((sum, value) => sum + (value - meanDelta) ** 2, 0) / (deltas.length - 1);
1144
+ const standardDeviation = Math.sqrt(variance);
1145
+ const scale = Math.max(1, Math.abs(meanDelta), ...deltas.map(Math.abs));
1146
+ if (standardDeviation <= Number.EPSILON * scale) return meanDelta === 0 ? 0 : null;
1147
+ return meanDelta / standardDeviation;
1148
+ }
1149
+ /** Cliff's delta, oriented after − before; empty samples return zero. */
1150
+ function cliffsDelta(before, after) {
1151
+ const n = before.length * after.length;
1152
+ if (n === 0) return 0;
1153
+ let dominance = 0;
1154
+ for (const a of after) for (const b of before) if (a > b) dominance += 1;
1155
+ else if (a < b) dominance -= 1;
1156
+ return dominance / n;
1157
+ }
1158
+ /** Romano magnitude thresholds for the absolute Cliff's delta. */
1159
+ function interpretCliffs(delta) {
1160
+ const d = Math.abs(delta);
1161
+ if (d < .147) return "negligible";
1162
+ if (d < .33) return "small";
1163
+ if (d < .474) return "medium";
1164
+ return "large";
1165
+ }
1166
+ // src/math/normal.ts
1167
+ /**
1168
+ * Standard normal cumulative distribution using Abramowitz and Stegun 7.1.26.
1169
+ *
1170
+ * The approximation is evaluated as erf(x / sqrt(2)). Computing the negative
1171
+ * tail from the complementary term avoids cancellation when x is far below 0.
1172
+ * The maximum absolute CDF error is approximately 7.5e-8.
1173
+ */
1174
+ function normalCdf(x) {
1175
+ if (x === 0) return .5;
1176
+ const a1 = .254829592;
1177
+ const a2 = -.284496736;
1178
+ const a3 = 1.421413741;
1179
+ const a4 = -1.453152027;
1180
+ const a5 = 1.061405429;
1181
+ const p = .3275911;
1182
+ const scaled = Math.abs(x) / Math.SQRT2;
1183
+ const t = 1 / (1 + p * scaled);
1184
+ const complement = ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-scaled * scaled);
1185
+ return x < 0 ? complement / 2 : 1 - complement / 2;
1186
+ }
1187
+ // src/statistics/inference.ts
1188
+ /** Two-sided normal tail, evaluated without subtracting a near-one CDF. */
1189
+ function normalTwoSidedPValue(z) {
1190
+ if (Number.isNaN(z)) throw new ValidationError("normalTwoSidedPValue: z must not be NaN");
1191
+ return Math.min(1, 2 * normalCdf(-Math.abs(z)));
1192
+ }
1193
+ /** Two-sided Student-t tail, preserving small tail probabilities. */
1194
+ function studentTTwoSidedPValue(t, df) {
1195
+ if (Number.isNaN(t) || !Number.isFinite(df) || df <= 0) throw new ValidationError("studentTTwoSidedPValue: t must not be NaN and df must be positive and finite");
1196
+ return regularizedIncompleteBeta(df / (df + t * t), df / 2, .5);
1197
+ }
1198
+ function table(a, b, c, d) {
1199
+ if (![
1200
+ a,
1201
+ b,
1202
+ c,
1203
+ d
1204
+ ].every((value) => Number.isSafeInteger(value) && value >= 0) || !Number.isSafeInteger(a + b + c + d)) throw new ValidationError("contingency table: counts and total must be nonnegative safe integers");
1205
+ return a + b + c + d;
1206
+ }
1207
+ /** Pearson statistic for a 2x2 table; empty or fixed margins have statistic zero. */
1208
+ function chiSquared(a, b, c, d) {
1209
+ const n = table(a, b, c, d);
1210
+ if (!n) return 0;
1211
+ const expected = [
1212
+ (a + b) * (a + c) / n,
1213
+ (a + b) * (b + d) / n,
1214
+ (c + d) * (a + c) / n,
1215
+ (c + d) * (b + d) / n
1216
+ ];
1217
+ if (expected.some((value) => value === 0)) return 0;
1218
+ return [
1219
+ a,
1220
+ b,
1221
+ c,
1222
+ d
1223
+ ].reduce((sum, value, i) => sum + (value - expected[i]) ** 2 / expected[i], 0);
1224
+ }
1225
+ /** One-degree-of-freedom chi-squared survival probability. */
1226
+ function chiSquaredPValue(statistic) {
1227
+ if (Number.isNaN(statistic) || statistic < 0) throw new ValidationError("chiSquaredPValue: statistic must be nonnegative and not NaN");
1228
+ return normalTwoSidedPValue(Math.sqrt(statistic));
1229
+ }
1230
+ /** Fisher two-sided probability: sum all fixed-margin tables no likelier than the observed table. */
1231
+ function fisherExactTwoSided(a, b, c, d) {
1232
+ const n = table(a, b, c, d), row1 = a + b, row2 = c + d, col1 = a + c;
1233
+ if (!n || !row1 || !row2 || !col1 || col1 === n) return 1;
1234
+ const logChoose = (total, count) => lnGamma(total + 1) - lnGamma(count + 1) - lnGamma(total - count + 1);
1235
+ const denominator = logChoose(n, col1);
1236
+ const logP = (count) => logChoose(row1, count) + logChoose(row2, col1 - count) - denominator;
1237
+ const threshold = logP(a) + 1e-7;
1238
+ let p = 0;
1239
+ for (let k = Math.max(0, col1 - row2); k <= Math.min(row1, col1); k++) {
1240
+ const probability = logP(k);
1241
+ if (probability <= threshold) p += Math.exp(probability);
1242
+ }
1243
+ return Math.min(1, p);
1244
+ }
1245
+ /** Fisher when any expected count is below five; otherwise Pearson's chi-squared tail. */
1246
+ function twoByTwoPValue(a, b, c, d) {
1247
+ const n = table(a, b, c, d);
1248
+ if (!n) return 1;
1249
+ return Math.min((a + b) * (a + c), (a + b) * (b + d), (c + d) * (a + c), (c + d) * (b + d)) / n < 5 ? fisherExactTwoSided(a, b, c, d) : chiSquaredPValue(chiSquared(a, b, c, d));
1250
+ }
1251
+ /** Centered least-squares slope; null p-value means no slope test was possible. */
1252
+ function linearRegressionSlope(points) {
1253
+ assertFiniteSample("linearRegressionSlope", "x", points.map((point) => point.x));
1254
+ assertFiniteSample("linearRegressionSlope", "y", points.map((point) => point.y));
1255
+ if (points.length < 2) return {
1256
+ slope: 0,
1257
+ rSquared: 0,
1258
+ slopePValue: null
1259
+ };
1260
+ const n = points.length;
1261
+ const meanX = points.reduce((sum, point) => sum + point.x / n, 0);
1262
+ const meanY = points.reduce((sum, point) => sum + point.y / n, 0);
1263
+ const sxx = points.reduce((sum, point) => sum + (point.x - meanX) ** 2, 0);
1264
+ const syy = points.reduce((sum, point) => sum + (point.y - meanY) ** 2, 0);
1265
+ const sxy = points.reduce((sum, point) => sum + (point.x - meanX) * (point.y - meanY), 0);
1266
+ if (!sxx) return {
1267
+ slope: 0,
1268
+ rSquared: 0,
1269
+ slopePValue: null
1270
+ };
1271
+ const slope = sxy / sxx;
1272
+ const residual = points.reduce((sum, point) => sum + (point.y - meanY - slope * (point.x - meanX)) ** 2, 0);
1273
+ if (![
1274
+ slope,
1275
+ residual,
1276
+ sxx,
1277
+ sxy,
1278
+ syy
1279
+ ].every(Number.isFinite)) throw new ValidationError("linearRegressionSlope: sample arithmetic exceeded finite range");
1280
+ return {
1281
+ slope,
1282
+ rSquared: syy === 0 ? 0 : Math.max(0, 1 - residual / syy),
1283
+ slopePValue: n < 3 ? null : residual === 0 ? slope === 0 ? 1 : 0 : studentTTwoSidedPValue(slope / Math.sqrt(residual / (n - 2) / sxx), n - 2)
1284
+ };
1285
+ }
1286
+ // src/statistics/multiplicity.ts
1287
+ /**
1288
+ * Multiple-comparison corrections: family-wise error (Bonferroni, Holm) and
1289
+ * false discovery rate (Benjamini-Hochberg), with inclusive rejection
1290
+ * boundaries throughout.
1291
+ */
1292
+ /**
1293
+ * Bonferroni adjustment: multiply every p-value by the test count, clamp at 1.
1294
+ *
1295
+ * Rejects at `p_adjusted ≤ alpha` — the boundary is inclusive, matching
1296
+ * {@link holm}, which uniformly dominates this correction and must therefore
1297
+ * never reject less. Validates its inputs on the same terms.
1298
+ */
1299
+ function bonferroni(pValues, alpha = .05) {
1300
+ assertAlpha("bonferroni", "alpha", alpha);
1301
+ assertPValues("bonferroni", pValues);
1302
+ const k = pValues.length;
1303
+ const adjusted = pValues.map((p) => Math.min(1, p * k));
1304
+ return {
1305
+ adjusted,
1306
+ significant: adjusted.map((p) => p <= alpha)
1307
+ };
1308
+ }
1309
+ /**
1310
+ * Holm step-down family-wise error adjustment.
1311
+ *
1312
+ * P-values are sorted from smallest to largest, multiplied by their remaining
1313
+ * hypothesis count, and made monotonically non-decreasing before being mapped
1314
+ * back to input order. This uniformly dominates plain Bonferroni while keeping
1315
+ * strong family-wise error control under arbitrary dependence.
1316
+ */
1317
+ function holm(pValues, alpha = .05) {
1318
+ assertAlpha("holm", "alpha", alpha);
1319
+ assertPValues("holm", pValues);
1320
+ const count = pValues.length;
1321
+ if (count === 0) return {
1322
+ adjusted: [],
1323
+ significant: []
1324
+ };
1325
+ const ordered = pValues.map((pValue, index) => ({
1326
+ pValue,
1327
+ index
1328
+ })).sort((a, b) => a.pValue - b.pValue || a.index - b.index);
1329
+ const adjusted = new Array(count);
1330
+ let previous = 0;
1331
+ for (let rank = 0; rank < count; rank++) {
1332
+ const entry = ordered[rank];
1333
+ const stepAdjusted = Math.min(1, entry.pValue * (count - rank));
1334
+ previous = Math.max(previous, stepAdjusted);
1335
+ adjusted[entry.index] = previous;
1336
+ }
1337
+ return {
1338
+ adjusted,
1339
+ significant: adjusted.map((pValue) => pValue <= alpha)
1340
+ };
1341
+ }
1342
+ /**
1343
+ * Benjamini–Hochberg false discovery rate. Returns adjusted q-values and
1344
+ * significance at the target FDR; handles ties and preserves q monotonicity.
1345
+ *
1346
+ * Rejects at `q ≤ fdr` — the BH rule is inclusive at the boundary, so an
1347
+ * exactly-`fdr` q-value is a discovery.
1348
+ */
1349
+ function benjaminiHochberg(pValues, fdr = .05) {
1350
+ assertAlpha("benjaminiHochberg", "fdr", fdr);
1351
+ assertPValues("benjaminiHochberg", pValues);
1352
+ const n = pValues.length;
1353
+ if (n === 0) return {
1354
+ qValues: [],
1355
+ significant: []
1356
+ };
1357
+ const indexed = pValues.map((p, i) => ({
1358
+ p,
1359
+ i
1360
+ })).sort((a, b) => a.p - b.p);
1361
+ const q = new Array(n);
1362
+ let minRight = 1;
1363
+ for (let k = n - 1; k >= 0; k--) {
1364
+ const rank = k + 1;
1365
+ const entry = indexed[k];
1366
+ const raw = n / rank * entry.p;
1367
+ const bounded = Math.min(minRight, raw);
1368
+ minRight = bounded;
1369
+ q[entry.i] = Math.min(1, bounded);
1370
+ }
1371
+ return {
1372
+ qValues: q,
1373
+ significant: q.map((v) => v <= fdr)
1374
+ };
1375
+ }
1376
+ function assertAlpha(fn, label, value) {
1377
+ if (!Number.isFinite(value) || value <= 0 || value >= 1) throw new ValidationError(`${fn}: ${label} must be in (0,1), got ${value}`);
1378
+ }
1379
+ function assertPValues(fn, pValues) {
1380
+ for (const [index, pValue] of pValues.entries()) if (!Number.isFinite(pValue) || pValue < 0 || pValue > 1) throw new ValidationError(`${fn}: pValues[${index}] must be in [0,1], got ${pValue}`);
1381
+ }
1382
+ // src/statistics/paired-binary.ts
1383
+ /**
1384
+ * Wilson score interval for a binomial proportion. Correct at small n and near
1385
+ * 0/1, where the normal (Wald) approximation produces bounds outside [0, 1] and
1386
+ * understates coverage. Use this for any pass-rate / hit-rate / realness-rate
1387
+ * CI — the continuous `confidenceInterval` assumes the wrong distribution for a
1388
+ * proportion. Counts must be finite nonnegative integers, successes cannot exceed
1389
+ * n, and confidence must lie strictly between zero and one. With n = 0 the
1390
+ * interval is the full [0, 1] support: no rate is ruled out. The estimate stays
1391
+ * 0 for compatibility, not as a measured failure rate; retain n alongside it.
1392
+ */
1393
+ function wilson(successes, n, confidence = .95) {
1394
+ if (!Number.isSafeInteger(n) || n < 0) throw new Error("wilson: n must be a finite nonnegative integer");
1395
+ if (!Number.isSafeInteger(successes) || successes < 0 || successes > n) throw new Error(`wilson: successes (${successes}) must be in [0, ${n}]`);
1396
+ if (!Number.isFinite(confidence) || confidence <= 0 || confidence >= 1) throw new Error("wilson: confidence must be between zero and one");
1397
+ if (n === 0) return {
1398
+ estimate: 0,
1399
+ lower: 0,
1400
+ upper: 1
1401
+ };
1402
+ const z = zQuantile(1 - (1 - confidence) / 2);
1403
+ const p = successes / n;
1404
+ const z2 = z * z;
1405
+ const denom = 1 + z2 / n;
1406
+ const center = (p + z2 / (2 * n)) / denom;
1407
+ const half = z * Math.sqrt((p * (1 - p) + z2 / (4 * n)) / n) / denom;
1408
+ return {
1409
+ estimate: p,
1410
+ lower: Math.max(0, center - half),
1411
+ upper: Math.min(1, center + half)
1412
+ };
1413
+ }
1414
+ /**
1415
+ * McNemar's test for paired binary outcomes — the correct significance test for
1416
+ * "does treatment change the success rate vs control on the SAME items". Only
1417
+ * discordant pairs (one arm right, the other wrong) carry information; concordant
1418
+ * pairs are uninformative, so a paired t-test / two-proportion z-test on the raw
1419
+ * rates is wrong here. The p-value is exact: under H0 the b "treatment-wins" are
1420
+ * Binomial(b + c, 0.5), so the two-sided p is the doubled binomial tail — correct
1421
+ * at the small discordant counts typical of eval runs (no continuity-corrected
1422
+ * chi-square approximation needed, though it is returned as `statistic` for
1423
+ * reference). Inputs are paired 0/1 (or boolean) arrays, control first to match
1424
+ * the module's (before, after) convention. Throws on unequal lengths.
1425
+ */
1426
+ function mcnemar(control, treatment) {
1427
+ if (control.length !== treatment.length) throw new Error(`mcnemar: unequal sample sizes (${control.length} vs ${treatment.length})`);
1428
+ const n = control.length;
1429
+ let b = 0;
1430
+ let c = 0;
1431
+ for (let i = 0; i < n; i++) {
1432
+ const ctrl = control[i] ? 1 : 0;
1433
+ const treat = treatment[i] ? 1 : 0;
1434
+ if (treat === 1 && ctrl === 0) b++;
1435
+ else if (treat === 0 && ctrl === 1) c++;
1436
+ }
1437
+ const nDiscordant = b + c;
1438
+ const statistic = nDiscordant === 0 ? 0 : (Math.abs(b - c) - 1) ** 2 / nDiscordant;
1439
+ return {
1440
+ n,
1441
+ nDiscordant,
1442
+ b,
1443
+ c,
1444
+ statistic,
1445
+ pValue: binomialSignTwoSided(b, c)
1446
+ };
1447
+ }
1448
+ /**
1449
+ * Paired risk difference (the effect-size companion to {@link mcnemar}): the
1450
+ * change in success rate p(treatment) − p(control) on matched items, which for
1451
+ * paired binary data equals (b − c) / n. The CI uses the paired variance from
1452
+ * the discordant counts, not the independent-samples formula (which overstates
1453
+ * the interval by ignoring the pairing). Inputs are paired 0/1 (or boolean)
1454
+ * arrays, control first. Throws on unequal lengths. With no pairs, returns the
1455
+ * full [-1, 1] support and a compatibility point estimate of 0, not equivalence.
1456
+ *
1457
+ * REPORTING ONLY — do NOT decide a promotion on this interval. The CI is a Wald
1458
+ * normal approximation, which badly UNDERCOVERS when only a handful of pairs are
1459
+ * discordant: at n = 3 with b = 2, c = 0 it returns [0.133, 1.000], excluding 0,
1460
+ * while McNemar's exact test on the same data gives p = 0.50. A gate keying on
1461
+ * `lower > 0` would promote noise. Use {@link pairedRiskDifferenceExact}, whose
1462
+ * interval is dual to the exact test by construction, for any decision.
1463
+ */
1464
+ function pairedRiskDifference(control, treatment, confidence = .95) {
1465
+ if (control.length !== treatment.length) throw new Error(`pairedRiskDifference: unequal sample sizes (${control.length} vs ${treatment.length})`);
1466
+ const n = control.length;
1467
+ if (n === 0) return {
1468
+ n: 0,
1469
+ b: 0,
1470
+ c: 0,
1471
+ riskDifference: 0,
1472
+ lower: -1,
1473
+ upper: 1,
1474
+ confidence
1475
+ };
1476
+ let b = 0;
1477
+ let c = 0;
1478
+ for (let i = 0; i < n; i++) {
1479
+ const ctrl = control[i] ? 1 : 0;
1480
+ const treat = treatment[i] ? 1 : 0;
1481
+ if (treat === 1 && ctrl === 0) b++;
1482
+ else if (treat === 0 && ctrl === 1) c++;
1483
+ }
1484
+ const rd = (b - c) / n;
1485
+ const variance = (b + c - (b - c) ** 2 / n) / (n * n);
1486
+ const half = zQuantile(1 - (1 - confidence) / 2) * Math.sqrt(Math.max(0, variance));
1487
+ return {
1488
+ n,
1489
+ b,
1490
+ c,
1491
+ riskDifference: rd,
1492
+ lower: Math.max(-1, rd - half),
1493
+ upper: Math.min(1, rd + half),
1494
+ confidence
1495
+ };
1496
+ }
1497
+ /**
1498
+ * Paired risk difference with the EXACT CONDITIONAL interval — the estimator a
1499
+ * promotion gate may decide on.
1500
+ *
1501
+ * Conditional on the number of discordant pairs m = b + c, the treatment-win
1502
+ * count b is Binomial(m, π) with π = P(treatment wins | discordant), and the
1503
+ * risk difference is an exact reparameterisation: RD = (2π − 1)·m/n. So a
1504
+ * Clopper-Pearson exact interval for π maps straight onto RD. This buys the
1505
+ * property the Wald interval in {@link pairedRiskDifference} does not have:
1506
+ *
1507
+ * **`lower > 0` ⟺ McNemar's exact test rejects at α = 1 − confidence.**
1508
+ *
1509
+ * Clopper-Pearson excludes π = 0.5 exactly when the two-sided exact binomial
1510
+ * test of π = 0.5 rejects, and that test IS {@link mcnemar}'s p-value — so the
1511
+ * interval and the test can never disagree, and a gate keyed on `lower` cannot
1512
+ * promote what the exact test refuses. The exact p is returned in the same
1513
+ * object so the two are impossible to compute apart.
1514
+ *
1515
+ * The interval is conservative (exact intervals over-cover; conditioning on m
1516
+ * discards the concordant pairs' information about m itself). That is the
1517
+ * correct direction for a promotion gate: it refuses more often, never less.
1518
+ *
1519
+ * With n = 0, returns the full [-1, 1] support, p = 1, and a compatibility
1520
+ * point estimate of 0. With n > 0 and m = 0, π is not identified: the result
1521
+ * is the degenerate [0, 0] with p = 1. That is NOT evidence of equivalence —
1522
+ * callers must treat a zero-width interval as "cannot decide", not as "no
1523
+ * difference". Inputs are paired 0/1 (or boolean) arrays, control first.
1524
+ * Throws on unequal lengths.
1525
+ */
1526
+ function pairedRiskDifferenceExact(control, treatment, confidence = .95) {
1527
+ if (control.length !== treatment.length) throw new Error(`pairedRiskDifferenceExact: unequal sample sizes (${control.length} vs ${treatment.length})`);
1528
+ if (confidence <= 0 || confidence >= 1) throw new Error(`pairedRiskDifferenceExact: confidence must be in (0,1), got ${confidence}`);
1529
+ const n = control.length;
1530
+ if (n === 0) return {
1531
+ n: 0,
1532
+ b: 0,
1533
+ c: 0,
1534
+ nDiscordant: 0,
1535
+ riskDifference: 0,
1536
+ lower: -1,
1537
+ upper: 1,
1538
+ confidence,
1539
+ pValue: 1
1540
+ };
1541
+ let b = 0;
1542
+ let c = 0;
1543
+ for (let i = 0; i < n; i++) {
1544
+ const ctrl = control[i] ? 1 : 0;
1545
+ const treat = treatment[i] ? 1 : 0;
1546
+ if (treat === 1 && ctrl === 0) b++;
1547
+ else if (treat === 0 && ctrl === 1) c++;
1548
+ }
1549
+ const m = b + c;
1550
+ const riskDifference = (b - c) / n;
1551
+ const pValue = binomialSignTwoSided(b, c);
1552
+ if (m === 0) return {
1553
+ n,
1554
+ b,
1555
+ c,
1556
+ nDiscordant: 0,
1557
+ riskDifference: 0,
1558
+ lower: 0,
1559
+ upper: 0,
1560
+ confidence,
1561
+ pValue
1562
+ };
1563
+ const alpha = 1 - confidence;
1564
+ const piLow = b === 0 ? 0 : betaQuantile(alpha / 2, b, m - b + 1);
1565
+ const piHigh = b === m ? 1 : betaQuantile(1 - alpha / 2, b + 1, m - b);
1566
+ const scale = m / n;
1567
+ return {
1568
+ n,
1569
+ b,
1570
+ c,
1571
+ nDiscordant: m,
1572
+ riskDifference,
1573
+ lower: Math.max(-1, (2 * piLow - 1) * scale),
1574
+ upper: Math.min(1, (2 * piHigh - 1) * scale),
1575
+ confidence,
1576
+ pValue
1577
+ };
1578
+ }
1579
+ /** Inverse regularized incomplete beta by bisection on
1580
+ * {@link regularizedIncompleteBeta}, which is monotone increasing in x. 80
1581
+ * halvings of [0,1] resolve to ~8e-25, far past the continued fraction's own
1582
+ * 3e-15 tolerance, so the quantile is as exact as the CDF it inverts. */
1583
+ function betaQuantile(p, a, b) {
1584
+ if (p <= 0) return 0;
1585
+ if (p >= 1) return 1;
1586
+ let lo = 0;
1587
+ let hi = 1;
1588
+ for (let i = 0; i < 80; i++) {
1589
+ const mid = (lo + hi) / 2;
1590
+ if (regularizedIncompleteBeta(mid, a, b) < p) lo = mid;
1591
+ else hi = mid;
1592
+ }
1593
+ return (lo + hi) / 2;
1594
+ }
1595
+ /**
1596
+ * Constrained MLE of q = P(treatment loses) under the hypothesis RD = `delta`.
1597
+ *
1598
+ * Profiling the two concordant cells out of the multinomial leaves
1599
+ * `L(q) = b·log(q+delta) + c·log(q) + e·log(1 − 2q − delta)` with `e = n − b − c`,
1600
+ * whose stationary point is the positive root of
1601
+ * `2n·q² − [(b + c) − delta·(b + 3c + 2e)]·q − c·delta·(1 − delta) = 0`.
1602
+ * At `delta = 0` this returns `(b + c) / 2n`, the familiar null.
1603
+ */
1604
+ function constrainedLossRate(b, c, n, delta) {
1605
+ const e = n - b - c;
1606
+ const quadratic = 2 * n;
1607
+ const linear = -(b + c - delta * (b + 3 * c + 2 * e));
1608
+ const constant = -c * delta * (1 - delta);
1609
+ const discriminant = linear * linear - 4 * quadratic * constant;
1610
+ const root = discriminant > 0 ? Math.sqrt(discriminant) : 0;
1611
+ const q = (-linear + root) / (2 * quadratic);
1612
+ return Math.min(Math.max(q, Math.max(0, -delta)), Math.max(0, (1 - delta) / 2));
1613
+ }
1614
+ /** Tango's score statistic for H0: RD = `delta`. `Var(b − c) = n·(2q + delta −
1615
+ * delta²)` under that hypothesis, evaluated at the constrained MLE of q. */
1616
+ function tangoScore(b, c, n, delta) {
1617
+ const numerator = b - c - n * delta;
1618
+ const variance = n * (2 * constrainedLossRate(b, c, n, delta) + delta * (1 - delta));
1619
+ if (!(variance > 0)) {
1620
+ if (numerator === 0) return 0;
1621
+ return numerator > 0 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
1622
+ }
1623
+ return numerator / Math.sqrt(variance);
1624
+ }
1625
+ /**
1626
+ * Paired risk difference with TANGO'S (1998) SCORE INTERVAL — the estimator a
1627
+ * promotion gate may decide on **at a nonzero margin**.
1628
+ *
1629
+ * {@link pairedRiskDifferenceExact} conditions on the observed discordant count
1630
+ * `m = b + c`, builds a Clopper-Pearson interval for the win share among those
1631
+ * `m` pairs, and multiplies by the observed `m/n`. That is exact for testing
1632
+ * RD = 0 — it is dual to McNemar — but it is NOT a confidence interval for the
1633
+ * population risk difference at a nonzero margin, because the sampling
1634
+ * variability of `m/n` itself is discarded. The gap is not academic: with the
1635
+ * production caller's `pairedDeltaThreshold: -0.05`, a process whose true risk
1636
+ * difference sits exactly on that margin clears a nominal-95 % `lower > margin`
1637
+ * check 24.75 % of the time at n = 40 and 43.95 % at n = 76 (2000 replicates
1638
+ * each) when the conditional interval decides.
1639
+ *
1640
+ * Tango's interval inverts the score test of RD = delta, which estimates the
1641
+ * nuisance loss rate under each hypothesised delta instead of fixing it at the
1642
+ * observed value, so `m` contributes its own uncertainty. It is the method
1643
+ * `ratesci::scorepairci` uses for paired risk-difference noninferiority, and it
1644
+ * is not conditional, so it stays valid as the margin moves away from zero.
1645
+ *
1646
+ * The bounds are found by bisecting `tangoScore(delta) = ±z` — the score is
1647
+ * monotone decreasing in delta, so each crossing is unique. Inputs are paired
1648
+ * 0/1 (or boolean) arrays, control first. Throws on unequal lengths.
1649
+ */
1650
+ function pairedRiskDifferenceScore(control, treatment, confidence = .95) {
1651
+ if (control.length !== treatment.length) throw new Error(`pairedRiskDifferenceScore: unequal sample sizes (${control.length} vs ${treatment.length})`);
1652
+ if (confidence <= 0 || confidence >= 1) throw new Error(`pairedRiskDifferenceScore: confidence must be in (0,1), got ${confidence}`);
1653
+ const n = control.length;
1654
+ if (n === 0) return {
1655
+ n: 0,
1656
+ b: 0,
1657
+ c: 0,
1658
+ nDiscordant: 0,
1659
+ riskDifference: 0,
1660
+ lower: -1,
1661
+ upper: 1,
1662
+ confidence
1663
+ };
1664
+ let b = 0;
1665
+ let c = 0;
1666
+ for (let i = 0; i < n; i++) {
1667
+ const ctrl = control[i] ? 1 : 0;
1668
+ const treat = treatment[i] ? 1 : 0;
1669
+ if (treat === 1 && ctrl === 0) b++;
1670
+ else if (treat === 0 && ctrl === 1) c++;
1671
+ }
1672
+ const riskDifference = (b - c) / n;
1673
+ const z = zQuantile(1 - (1 - confidence) / 2);
1674
+ let lo = -1;
1675
+ let hi = riskDifference;
1676
+ for (let i = 0; i < 64; i++) {
1677
+ const mid = (lo + hi) / 2;
1678
+ if (tangoScore(b, c, n, mid) > z) lo = mid;
1679
+ else hi = mid;
1680
+ }
1681
+ const lower = (lo + hi) / 2;
1682
+ let ulo = riskDifference;
1683
+ let uhi = 1;
1684
+ for (let i = 0; i < 64; i++) {
1685
+ const mid = (ulo + uhi) / 2;
1686
+ if (tangoScore(b, c, n, mid) > -z) ulo = mid;
1687
+ else uhi = mid;
1688
+ }
1689
+ const upper = (ulo + uhi) / 2;
1690
+ return {
1691
+ n,
1692
+ b,
1693
+ c,
1694
+ nDiscordant: b + c,
1695
+ riskDifference,
1696
+ lower: Math.max(-1, lower),
1697
+ upper: Math.min(1, upper),
1698
+ confidence
1699
+ };
1700
+ }
1701
+ /**
1702
+ * The common positive level `s` such that EVERY value across both paired arms is
1703
+ * exactly 0 or `s` — i.e. the outcome is pass/fail, whatever encoding it arrived
1704
+ * in. Returns null when the outcomes are not two-point, when the two arms use
1705
+ * different levels, or when no positive value was observed at all (all-zero
1706
+ * arms: the level is not identified, and there is nothing to decide anyway).
1707
+ *
1708
+ * This is the scale-aware successor to {@link isBinaryOutcomeVector}, which only
1709
+ * recognises literal {0, 1}. Judges in this codebase emit dimensions on 0-100 as
1710
+ * well as [0,1] (see `detectScale` in `campaign/gates/statistical-heldout.ts`),
1711
+ * so a pass/fail dimension routinely arrives as {0, 100} and a {0,1}-only test
1712
+ * silently sends it down the median path that cannot see it. Any positive level
1713
+ * is accepted, not just 1 and 100: for a two-point {0, s} outcome the mean paired
1714
+ * delta is exactly s·(b − c)/n, so the binary estimators apply after dividing by
1715
+ * s and rescaling the result back into the caller's native units.
1716
+ *
1717
+ * Non-finite values ⇒ null: an unusable outcome must not be classified as a
1718
+ * clean pass/fail shape.
1719
+ */
1720
+ function pairedBinaryScale(before, after) {
1721
+ let level = null;
1722
+ for (const arm of [before, after]) for (let i = 0; i < arm.length; i++) {
1723
+ const v = arm[i];
1724
+ if (!Number.isFinite(v)) return null;
1725
+ if (v === 0) continue;
1726
+ if (v < 0) return null;
1727
+ if (level === null) level = v;
1728
+ else if (v !== level) return null;
1729
+ }
1730
+ return level;
1731
+ }
1732
+ /**
1733
+ * Unbiased pass@k for code generation (Chen et al. 2021, "Evaluating Large
1734
+ * Language Models Trained on Code"). Given `n` independent samples for one
1735
+ * problem of which `c` pass, the probability that at least one of a random k of
1736
+ * them passes is 1 − C(n−c, k) / C(n, k). Estimating pass@k as "did any of the
1737
+ * first k pass" is biased high at small n; this is the variance-reduced estimator
1738
+ * averaged implicitly over all k-subsets. Average the per-problem values across
1739
+ * the suite for the corpus pass@k. Computed in the numerically stable product
1740
+ * form. Requires 1 ≤ k ≤ n and 0 ≤ c ≤ n.
1741
+ */
1742
+ function passAtK(n, c, k) {
1743
+ if (!Number.isInteger(n) || !Number.isInteger(c) || !Number.isInteger(k)) throw new Error(`passAtK: n, c, k must be integers (got n=${n}, c=${c}, k=${k})`);
1744
+ if (k < 1 || k > n || c < 0 || c > n) throw new Error(`passAtK: require 1 ≤ k ≤ n and 0 ≤ c ≤ n (got n=${n}, c=${c}, k=${k})`);
1745
+ if (n - c < k) return 1;
1746
+ let prob = 1;
1747
+ for (let i = n - c + 1; i <= n; i++) prob *= 1 - k / i;
1748
+ return 1 - prob;
1749
+ }
1750
+ // src/statistics/paired-tests.ts
1751
+ /**
1752
+ * Paired significance tests on continuous scores: the paired t-test, the
1753
+ * promotion-gate paired bootstrap, the exact sign test, and the package-wide
1754
+ * paired-delta decision statistic.
1755
+ */
1756
+ /**
1757
+ * Paired t-test — before/after measurements on the SAME items.
1758
+ * Pairing removes inter-item variance, giving tighter significance than
1759
+ * an unpaired test when comparing prompt v1 vs prompt v2 on identical
1760
+ * scenarios.
1761
+ *
1762
+ * Returns `t = p = null` where the statistic is undefined: fewer than two
1763
+ * pairs, or a non-zero constant delta whose observed variance is zero. A
1764
+ * constant shift carries no information about the variance it would have to
1765
+ * be compared against, so the honest answer is "undefined", not `p = 0` —
1766
+ * three observations cannot buy absolute certainty. This is the same contract
1767
+ * {@link pairedCohensDz} states for the same condition. An all-zero delta is
1768
+ * different: it is a measured null, and returns `t = 0, p = 1`.
1769
+ */
1770
+ function pairedTTest(before, after) {
1771
+ if (before.length !== after.length) throw new ValidationError(`pairedTTest: unequal sample sizes (${before.length} vs ${after.length})`);
1772
+ assertFiniteSample("pairedTTest", "before", before);
1773
+ assertFiniteSample("pairedTTest", "after", after);
1774
+ const n = before.length;
1775
+ if (n < 2) return {
1776
+ t: null,
1777
+ df: 0,
1778
+ p: null
1779
+ };
1780
+ const diffs = before.map((b, i) => after[i] - b);
1781
+ const mean = diffs.reduce((a, b) => a + b, 0) / n;
1782
+ const variance = diffs.reduce((acc, d) => acc + (d - mean) ** 2, 0) / (n - 1);
1783
+ const se = Math.sqrt(variance / n);
1784
+ if (se === 0) return mean === 0 ? {
1785
+ t: 0,
1786
+ df: n - 1,
1787
+ p: 1
1788
+ } : {
1789
+ t: null,
1790
+ df: n - 1,
1791
+ p: null
1792
+ };
1793
+ const t = mean / se;
1794
+ const df = n - 1;
1795
+ return {
1796
+ t,
1797
+ df,
1798
+ p: 2 * (1 - studentTCdf(Math.abs(t), df))
1799
+ };
1800
+ }
1801
+ /**
1802
+ * Pairs below which a percentile bootstrap interval is descriptive spread only.
1803
+ *
1804
+ * `P(low > 0)` under a true null, against a nominal 2.5 %, measured over 4000
1805
+ * seeded trials: 13.53 % at n = 3, 3.52 % at n = 10, 3.10 % at n = 20 on the
1806
+ * median; 13.85 %, 4.90 %, 3.80 % on the mean. This is intrinsic to resampling
1807
+ * three points, not an implementation error — scipy's BCa gives 16.0 % on the
1808
+ * same n = 3 data — so no change to the estimator moves it. Below this floor
1809
+ * the decision belongs to the exact sign test or exact signed-rank test.
1810
+ */
1811
+ const BOOTSTRAP_GATE_MIN_N = 20;
1812
+ /**
1813
+ * Paired bootstrap on (after − before) deltas. Returns a CI on the chosen
1814
+ * statistic (median by default); pairs are resampled with replacement. Throws
1815
+ * on unequal sample sizes.
1816
+ *
1817
+ * `low > threshold` carries the stated confidence ONLY at `n ≥
1818
+ * {@link BOOTSTRAP_GATE_MIN_N}`, which `gateEligible` reports. Below it the
1819
+ * check fires under a true null several times more often than nominal, so the
1820
+ * interval is descriptive spread and a promotion must not turn on it.
1821
+ */
1822
+ function pairedBootstrap(before, after, opts = {}) {
1823
+ if (before.length !== after.length) throw new Error(`pairedBootstrap: unequal sample sizes (${before.length} vs ${after.length})`);
1824
+ const confidence = opts.confidence ?? .95;
1825
+ const resamples = opts.resamples ?? 2e3;
1826
+ const statistic = opts.statistic ?? "median";
1827
+ if (confidence <= 0 || confidence >= 1) throw new Error(`pairedBootstrap: confidence must be in (0,1), got ${confidence}`);
1828
+ const n = before.length;
1829
+ const deltas = before.map((b, i) => after[i] - b);
1830
+ const gateEligible = n >= 20;
1831
+ if (n === 0) return {
1832
+ n: 0,
1833
+ median: 0,
1834
+ mean: 0,
1835
+ low: 0,
1836
+ high: 0,
1837
+ confidence,
1838
+ resamples,
1839
+ gateEligible
1840
+ };
1841
+ if (n === 1) {
1842
+ const d = deltas[0];
1843
+ return {
1844
+ n: 1,
1845
+ median: d,
1846
+ mean: d,
1847
+ low: d,
1848
+ high: d,
1849
+ confidence,
1850
+ resamples,
1851
+ gateEligible
1852
+ };
1853
+ }
1854
+ const rng = makeRng(opts.seed, deltas);
1855
+ const samples = new Array(resamples);
1856
+ for (let b = 0; b < resamples; b++) if (statistic === "mean") {
1857
+ let sum = 0;
1858
+ for (let k = 0; k < n; k++) sum += deltas[Math.floor(rng() * n)];
1859
+ samples[b] = sum / n;
1860
+ } else {
1861
+ const acc = new Array(n);
1862
+ for (let k = 0; k < n; k++) acc[k] = deltas[Math.floor(rng() * n)];
1863
+ samples[b] = medianInPlace(acc);
1864
+ }
1865
+ samples.sort((a, b) => a - b);
1866
+ const alpha = 1 - confidence;
1867
+ const lowIdx = Math.floor(alpha / 2 * resamples);
1868
+ const highIdx = Math.min(resamples - 1, Math.ceil((1 - alpha / 2) * resamples) - 1);
1869
+ return {
1870
+ n,
1871
+ median: medianInPlace([...deltas]),
1872
+ mean: deltas.reduce((s, x) => s + x, 0) / n,
1873
+ low: samples[lowIdx],
1874
+ high: samples[Math.max(highIdx, lowIdx)],
1875
+ confidence,
1876
+ resamples,
1877
+ gateEligible
1878
+ };
1879
+ }
1880
+ /**
1881
+ * Exact one-sided sign test over paired differences.
1882
+ *
1883
+ * Pass `after[i] - before[i]` for each matched item. `alternative = 'greater'`
1884
+ * tests whether positive signs are more likely than negative signs and returns
1885
+ * `P(Binomial(nNonTies, 0.5) >= positive)`. `alternative = 'less'` treats
1886
+ * negative signs as successes instead. With a continuous difference
1887
+ * distribution this is the usual directional median test. Exact zero
1888
+ * differences are ties and do not enter the binomial denominator. All-tie and
1889
+ * empty inputs return p = 1. Every input difference must be finite, and the
1890
+ * direction must be chosen explicitly so a caller cannot select it after
1891
+ * seeing the signs.
1892
+ */
1893
+ function pairedSignTest(differences, alternative) {
1894
+ if (alternative !== "greater" && alternative !== "less") throw new ValidationError(`pairedSignTest: alternative must be 'greater' or 'less', got ${alternative}`);
1895
+ let positive = 0;
1896
+ let negative = 0;
1897
+ let ties = 0;
1898
+ for (let i = 0; i < differences.length; i++) {
1899
+ const difference = differences[i];
1900
+ if (!Number.isFinite(difference)) throw new ValidationError(`pairedSignTest: difference at index ${i} must be finite, got ${difference}`);
1901
+ if (difference > 0) positive++;
1902
+ else if (difference < 0) negative++;
1903
+ else ties++;
1904
+ }
1905
+ const nNonTies = positive + negative;
1906
+ const successes = alternative === "greater" ? positive : negative;
1907
+ return {
1908
+ n: differences.length,
1909
+ positive,
1910
+ negative,
1911
+ ties,
1912
+ nNonTies,
1913
+ alternative,
1914
+ pValue: binomialHalfUpperTail(successes, nNonTies)
1915
+ };
1916
+ }
1917
+ /** Fraction of paired observations whose delta is an exact tie (|after − before|
1918
+ * < 1e-9). Throws on unequal sample sizes; 0 pairs ⇒ 0. */
1919
+ function pairedDeltaTieFraction(before, after) {
1920
+ if (before.length !== after.length) throw new Error(`pairedDeltaTieFraction: unequal sample sizes (${before.length} vs ${after.length})`);
1921
+ const n = before.length;
1922
+ if (n === 0) return 0;
1923
+ let ties = 0;
1924
+ for (let i = 0; i < n; i++) if (Math.abs(after[i] - before[i]) < 1e-9) ties++;
1925
+ return ties / n;
1926
+ }
1927
+ /**
1928
+ * The paired-delta statistic a DECISION is computed on, package-wide.
1929
+ *
1930
+ * The mean paired delta is the estimator that answers the question a promotion
1931
+ * gate asks — "by how much did the candidate move the score" — in the caller's
1932
+ * own units, and it equals the aggregate lift everyone quotes. The MEDIAN
1933
+ * answers a different question and loses the answer to this one in every regime
1934
+ * eval data actually lands in:
1935
+ * - TWO-POINT (pass/fail) outcomes on any encoding: the delta vector lives in
1936
+ * {−s, 0, +s} dominated by zeros, so the median and its whole bootstrap CI
1937
+ * are pinned at exactly 0 however large the shift. (Decide these on
1938
+ * {@link pairedRiskDifferenceExact} instead — same estimand, exact interval.)
1939
+ * - TIE-DOMINATED outcomes: at half the pairs tied the sample median is 0 by
1940
+ * construction, and `ci.low > threshold` then answers "no" forever at a
1941
+ * non-negative threshold and "yes" forever at a negative one.
1942
+ * - LOW-CARDINALITY outcomes, even well below half ties: judge dimensions on
1943
+ * integer 0-100, and block scores like {⅔, 1} from averaging pass/fail
1944
+ * leaves, put the median on a coarse lattice whose bootstrap percentiles
1945
+ * land on atoms. Measured: 26 blocks of 3 pass/fail leaves carrying a real
1946
+ * +12.8pp lift, only 23% of pairs tied, gives a median CI of [0, 0.333] —
1947
+ * lower bound exactly 0, so a gate at threshold 0 refuses a real lift.
1948
+ * That last case is why there is no tie-fraction threshold here: any cutoff on
1949
+ * ties leaves the lattice case open on the other side of it.
1950
+ *
1951
+ * `heldoutSignificance` has defaulted to the mean since #316 for the same
1952
+ * reason. The median remains available per call site for callers who
1953
+ * specifically want outlier robustness and accept the blindness.
1954
+ */
1955
+ const DECISION_PAIRED_DELTA_STATISTIC = "mean";
1956
+ // src/statistics/power-and-mde.ts
1957
+ /**
1958
+ * Required N per arm for a two-sample comparison at target effect size,
1959
+ * alpha, and power. Normal-approximation formula:
1960
+ * n = 2 * ( (z_{1-α/2} + z_{1-β}) / d )^2
1961
+ * where d is Cohen's d. Returns Infinity for effect ≤ 0.
1962
+ */
1963
+ function requiredSampleSize(opts) {
1964
+ const effect = opts.effect;
1965
+ if (!Number.isFinite(effect) || effect <= 0) return Infinity;
1966
+ const alpha = opts.alpha ?? .05;
1967
+ const power = opts.power ?? .8;
1968
+ const n = 2 * ((zQuantile(opts.twoSided ?? true ? 1 - alpha / 2 : 1 - alpha) + zQuantile(power)) / effect) ** 2;
1969
+ return Math.ceil(n);
1970
+ }
1971
+ /**
1972
+ * Required number of paired observations for a target Cohen's dz.
1973
+ * Unlike the independent-groups formula, this has no two-arm factor of two.
1974
+ *
1975
+ * Normal quantiles with no t correction, so treat the result as a LOWER bound:
1976
+ * it returns 32 where the exact t-based answer is 34 at dz = 0.5, and 13 where
1977
+ * it is 15 at dz = 0.8 — a 6–13 % shortfall precisely in the range a caller
1978
+ * consults to decide whether 3–10 repetitions suffice.
1979
+ */
1980
+ function requiredPairedSampleSize(opts) {
1981
+ const effect = opts.effect;
1982
+ if (!Number.isFinite(effect) || effect <= 0) return Infinity;
1983
+ const alpha = opts.alpha ?? .05;
1984
+ const power = opts.power ?? .8;
1985
+ const zAlpha = zQuantile(opts.twoSided ?? true ? 1 - alpha / 2 : 1 - alpha);
1986
+ const zBeta = zQuantile(power);
1987
+ return Math.ceil(((zAlpha + zBeta) / effect) ** 2);
1988
+ }
1989
+ /**
1990
+ * Minimum detectable paired effect (standardised units) for a target paired
1991
+ * sample size: d_min = (z_{1-α/2} + z_β) / sqrt(n_paired). Multiply by
1992
+ * sd(deltas) for score units; treat as a lower bound — Wilcoxon and bootstrap
1993
+ * have asymptotic relative efficiency below 1 vs the t-test on heavy tails.
1994
+ */
1995
+ function pairedMde(opts) {
1996
+ if (!Number.isFinite(opts.nPaired) || opts.nPaired <= 0) return Infinity;
1997
+ const alpha = opts.alpha ?? .05;
1998
+ const power = opts.power ?? .8;
1999
+ return (zQuantile(opts.twoSided ?? true ? 1 - alpha / 2 : 1 - alpha) + zQuantile(power)) / Math.sqrt(opts.nPaired);
2000
+ }
2001
+ /**
2002
+ * Number of paired observations needed for a McNemar test to reach a target
2003
+ * power — the pre-registration companion to {@link mcnemar}. Parametrised by the
2004
+ * expected discordant-cell probabilities `p10` (P[treatment wins on a pair]) and
2005
+ * `p01` (P[control wins]); concordant pairs carry no information, so the count
2006
+ * is driven entirely by the discordant rate. Lachin's (1992) asymptotic normal
2007
+ * approximation: with discordant rate `pDisc = p10 + p01` and marginal effect
2008
+ * `δ = p10 − p01`,
2009
+ * n = ( z_{1-α/2}·√pDisc + z_{1-β}·√(pDisc − δ²) )² / δ².
2010
+ * Returns Infinity when there is no effect (p10 === p01). Asymptotic — at the
2011
+ * tiny discordant counts where the exact {@link mcnemar} differs from the normal
2012
+ * approximation, treat the result as a lower bound and prefer the discordant-pair
2013
+ * floor.
2014
+ */
2015
+ function mcnemarRequiredN(opts) {
2016
+ const { p10, p01 } = opts;
2017
+ if (p10 < 0 || p01 < 0 || p10 + p01 > 1) throw new Error(`mcnemarRequiredN: require p10,p01 ≥ 0 and p10+p01 ≤ 1 (got ${p10}, ${p01})`);
2018
+ const delta = p10 - p01;
2019
+ if (delta === 0) return Infinity;
2020
+ const alpha = opts.alpha ?? .05;
2021
+ const power = opts.power ?? .8;
2022
+ const twoSided = opts.twoSided ?? true;
2023
+ const pDisc = p10 + p01;
2024
+ const zAlpha = zQuantile(twoSided ? 1 - alpha / 2 : 1 - alpha);
2025
+ const zBeta = zQuantile(power);
2026
+ const n = (zAlpha * Math.sqrt(pDisc) + zBeta * Math.sqrt(Math.max(0, pDisc - delta * delta))) ** 2 / (delta * delta);
2027
+ return Math.ceil(n);
2028
+ }
2029
+ /**
2030
+ * Power of a McNemar test at a given number of paired observations, the inverse
2031
+ * of {@link mcnemarRequiredN} (same Lachin asymptotic model, same parameters).
2032
+ * Returns a value in [0, 1]; equals `alpha` when there is no effect.
2033
+ */
2034
+ function mcnemarPower(opts) {
2035
+ const { p10, p01, nPairs } = opts;
2036
+ if (p10 < 0 || p01 < 0 || p10 + p01 > 1) throw new Error(`mcnemarPower: require p10,p01 ≥ 0 and p10+p01 ≤ 1 (got ${p10}, ${p01})`);
2037
+ const alpha = opts.alpha ?? .05;
2038
+ const twoSided = opts.twoSided ?? true;
2039
+ const delta = p10 - p01;
2040
+ if (delta === 0 || nPairs <= 0) return alpha;
2041
+ const pDisc = p10 + p01;
2042
+ const zAlpha = zQuantile(twoSided ? 1 - alpha / 2 : 1 - alpha);
2043
+ const denom = Math.sqrt(Math.max(1e-12, pDisc - delta * delta));
2044
+ const zBeta = (Math.sqrt(nPairs) * Math.abs(delta) - zAlpha * Math.sqrt(pDisc)) / denom;
2045
+ return Math.min(1, Math.max(0, normalCdf(zBeta)));
2046
+ }
2047
+ // src/statistics/rank-tests.ts
2048
+ /** Maximum dynamic-programming cells used by an exact two-sample rank test. */
2049
+ const MANN_WHITNEY_EXACT_MAX_STATES = 8192;
2050
+ /** Maximum inner-loop transitions used by an exact two-sample rank test. */
2051
+ const MANN_WHITNEY_EXACT_MAX_WORK = 25e4;
2052
+ /** Non-zero differences up to which the signed-rank null is enumerated exactly. */
2053
+ const WILCOXON_EXACT_MAX_N = 20;
2054
+ /** Resamples used when a rank test falls back to Monte Carlo permutation. */
2055
+ const DEFAULT_PERMUTATIONS = 1e5;
2056
+ /**
2057
+ * Mann-Whitney U — two independent samples, no distributional assumption.
2058
+ *
2059
+ * Exact conditional (permutation) p by default when the dynamic program fits
2060
+ * {@link MANN_WHITNEY_EXACT_MAX_STATES} cells and
2061
+ * {@link MANN_WHITNEY_EXACT_MAX_WORK} transitions, seeded Monte Carlo
2062
+ * permutation above those limits. This keeps imbalanced designs such as 1+24
2063
+ * exact without admitting expensive balanced designs merely because they have
2064
+ * the same total size. Throws on non-finite input and on `method:
2065
+ * 'asymptotic'` where an exact answer is available. Empty input yields `p = 1,
2066
+ * pFloor = 1` — no design, no attainable evidence.
2067
+ */
2068
+ function mannWhitneyU(a, b, opts = {}) {
2069
+ assertFiniteSample("mannWhitneyU", "a", a);
2070
+ assertFiniteSample("mannWhitneyU", "b", b);
2071
+ const n1 = a.length;
2072
+ const n2 = b.length;
2073
+ if (n1 === 0 || n2 === 0) return {
2074
+ u: 0,
2075
+ uA: 0,
2076
+ p: 1,
2077
+ method: "exact",
2078
+ pFloor: 1
2079
+ };
2080
+ const total = n1 + n2;
2081
+ const combined = [...a.map((v) => ({
2082
+ v,
2083
+ fromA: true
2084
+ })), ...b.map((v) => ({
2085
+ v,
2086
+ fromA: false
2087
+ }))].sort((x, y) => x.v - y.v);
2088
+ const { midranks, tieTerm } = midranksWithTieTerm(combined.map((entry) => entry.v));
2089
+ let rankSumA = 0;
2090
+ for (let k = 0; k < total; k++) if (combined[k].fromA) rankSumA += midranks[k];
2091
+ const uA = rankSumA - n1 * (n1 + 1) / 2;
2092
+ const u = Math.min(uA, n1 * n2 - uA);
2093
+ const doubled = midranks.map((rank) => Math.round(rank * 2));
2094
+ const doubledDeviation = Math.abs(2 * uA - n1 * n2);
2095
+ const selectedN = Math.min(n1, n2);
2096
+ const otherN = total - selectedN;
2097
+ const exactCost = exactTwoSampleCost(doubled, selectedN);
2098
+ const designFloor = exactTwoSampleFloor(doubled, selectedN);
2099
+ const method = selectRankTestMethod("mannWhitneyU", opts.method ?? "auto", `n1=${n1}, n2=${n2}`, exactCost.states <= MANN_WHITNEY_EXACT_MAX_STATES && exactCost.work <= MANN_WHITNEY_EXACT_MAX_WORK, designFloor, `${MANN_WHITNEY_EXACT_MAX_STATES.toLocaleString("en-US")} states and ${MANN_WHITNEY_EXACT_MAX_WORK.toLocaleString("en-US")} transitions`);
2100
+ if (method === "exact") {
2101
+ const { p, pFloor } = exactTwoSampleP(doubled, selectedN, otherN, doubledDeviation);
2102
+ return {
2103
+ u,
2104
+ uA,
2105
+ p,
2106
+ method,
2107
+ pFloor
2108
+ };
2109
+ }
2110
+ if (method === "asymptotic") return {
2111
+ u,
2112
+ uA,
2113
+ p: asymptoticTwoSidedP(doubledDeviation / 2, twoSampleSigma(n1, n2, total, tieTerm)),
2114
+ method,
2115
+ pFloor: designFloor
2116
+ };
2117
+ const permutations = resolvePermutations("mannWhitneyU", opts.permutations);
2118
+ const rng = opts.seed === void 0 ? makeRng(symmetricTwoSampleSeed(a, b)) : makeRng(opts.seed);
2119
+ let atLeastAsExtreme = 0;
2120
+ const pool = [...doubled];
2121
+ for (let iteration = 0; iteration < permutations; iteration++) {
2122
+ let doubledRankSum = 0;
2123
+ for (let k = 0; k < selectedN; k++) {
2124
+ const pick = k + Math.floor(rng() * (total - k));
2125
+ const swapped = pool[pick];
2126
+ pool[pick] = pool[k];
2127
+ pool[k] = swapped;
2128
+ doubledRankSum += swapped;
2129
+ }
2130
+ if (Math.abs(doubledRankSum - selectedN * (selectedN + 1) - selectedN * otherN) >= doubledDeviation) atLeastAsExtreme++;
2131
+ }
2132
+ const pFloor = Math.max(1 / (permutations + 1), designFloor);
2133
+ return {
2134
+ u,
2135
+ uA,
2136
+ p: Math.max((1 + atLeastAsExtreme) / (permutations + 1), pFloor),
2137
+ method,
2138
+ pFloor
2139
+ };
2140
+ }
2141
+ /**
2142
+ * Wilcoxon signed-rank — paired, no distributional assumption on the deltas.
2143
+ *
2144
+ * Exact conditional (sign-flip) p by default at `n ≤
2145
+ * {@link WILCOXON_EXACT_MAX_N}` non-zero differences, seeded Monte Carlo
2146
+ * permutation above it. Throws on non-finite input and on `method:
2147
+ * 'asymptotic'` where an exact answer is available.
2148
+ *
2149
+ * `n` is the count of NON-ZERO differences: exact ties are dropped before
2150
+ * ranking, so a run of tied pairs shrinks the design and raises `pFloor`.
2151
+ * All-tied input yields `p = 1, pFloor = 1` — no attainable evidence, which
2152
+ * `pFloor` states rather than leaving `p = 1` to be read as a measured null.
2153
+ */
2154
+ function wilcoxonSignedRank(before, after, opts = {}) {
2155
+ if (before.length !== after.length) throw new ValidationError(`wilcoxonSignedRank: unequal sample sizes (${before.length} vs ${after.length})`);
2156
+ assertFiniteSample("wilcoxonSignedRank", "before", before);
2157
+ assertFiniteSample("wilcoxonSignedRank", "after", after);
2158
+ const diffs = before.map((b, i) => after[i] - b).filter((d) => d !== 0);
2159
+ const n = diffs.length;
2160
+ if (n === 0) return {
2161
+ w: 0,
2162
+ p: 1,
2163
+ method: "exact",
2164
+ pFloor: 1,
2165
+ nNonZero: 0
2166
+ };
2167
+ const abs = Math.abs(diffs[0]);
2168
+ const allEqualAbs = diffs.every((d) => Math.abs(d) === abs);
2169
+ if ((opts.method === void 0 || opts.method === "auto") && allEqualAbs) {
2170
+ const positive = diffs.filter((d) => d > 0).length;
2171
+ const negative = n - positive;
2172
+ return {
2173
+ w: positive * (n + 1) / 2,
2174
+ p: binomialSignTwoSided(positive, negative),
2175
+ method: "exact",
2176
+ pFloor: Math.min(1, 2 ** (1 - n)),
2177
+ nNonZero: n
2178
+ };
2179
+ }
2180
+ const order = diffs.map((d, i) => ({
2181
+ abs: Math.abs(d),
2182
+ i
2183
+ })).sort((x, y) => x.abs - y.abs);
2184
+ const { midranks, tieTerm } = midranksWithTieTerm(order.map((entry) => entry.abs));
2185
+ const ranks = new Array(n);
2186
+ for (let k = 0; k < n; k++) ranks[order[k].i] = midranks[k];
2187
+ let wPlus = 0;
2188
+ for (let k = 0; k < n; k++) if (diffs[k] > 0) wPlus += ranks[k];
2189
+ const doubled = midranks.map((rank) => Math.round(rank * 2));
2190
+ const doubledDeviation = Math.abs(2 * wPlus - n * (n + 1) / 2);
2191
+ const designFloor = Math.min(1, 2 ** (1 - n));
2192
+ const method = selectRankTestMethod("wilcoxonSignedRank", opts.method ?? "auto", `n=${n} non-zero differences`, n <= WILCOXON_EXACT_MAX_N, designFloor, `${WILCOXON_EXACT_MAX_N} non-zero differences`);
2193
+ if (method === "exact") {
2194
+ const { p, pFloor } = exactSignedRankP(doubled, doubledDeviation);
2195
+ return {
2196
+ w: wPlus,
2197
+ p,
2198
+ method,
2199
+ pFloor,
2200
+ nNonZero: n
2201
+ };
2202
+ }
2203
+ if (method === "asymptotic") {
2204
+ const variance = n * (n + 1) * (2 * n + 1) / 24 - tieTerm / 48;
2205
+ return {
2206
+ w: wPlus,
2207
+ p: asymptoticTwoSidedP(doubledDeviation / 2, Math.sqrt(variance)),
2208
+ method,
2209
+ pFloor: designFloor,
2210
+ nNonZero: n
2211
+ };
2212
+ }
2213
+ const permutations = resolvePermutations("wilcoxonSignedRank", opts.permutations);
2214
+ const rng = makeRng(opts.seed, before, after);
2215
+ const doubledCentre = n * (n + 1) / 2;
2216
+ let atLeastAsExtreme = 0;
2217
+ for (let iteration = 0; iteration < permutations; iteration++) {
2218
+ let doubledWPlus = 0;
2219
+ for (let k = 0; k < n; k++) if (rng() < .5) doubledWPlus += doubled[k];
2220
+ if (Math.abs(doubledWPlus - doubledCentre) >= doubledDeviation) atLeastAsExtreme++;
2221
+ }
2222
+ return {
2223
+ w: wPlus,
2224
+ p: (1 + atLeastAsExtreme) / (permutations + 1),
2225
+ method,
2226
+ pFloor: Math.max(1 / (permutations + 1), designFloor),
2227
+ nNonZero: n
2228
+ };
2229
+ }
2230
+ /**
2231
+ * Average ranks over an ASCENDING-sorted array, plus `Σ(t³ − t)` over tie
2232
+ * groups of size `t` — the correction term both asymptotic rank-test variances
2233
+ * need.
2234
+ */
2235
+ function midranksWithTieTerm(sorted) {
2236
+ const midranks = new Array(sorted.length);
2237
+ let tieTerm = 0;
2238
+ let i = 0;
2239
+ while (i < sorted.length) {
2240
+ let j = i;
2241
+ while (j < sorted.length && sorted[j] === sorted[i]) j++;
2242
+ const average = (i + 1 + j) / 2;
2243
+ for (let k = i; k < j; k++) midranks[k] = average;
2244
+ const groupSize = j - i;
2245
+ if (groupSize > 1) tieTerm += groupSize ** 3 - groupSize;
2246
+ i = j;
2247
+ }
2248
+ return {
2249
+ midranks,
2250
+ tieTerm
2251
+ };
2252
+ }
2253
+ function selectRankTestMethod(fn, request, design, exactFeasible, designFloor, threshold) {
2254
+ if (request === "auto") return exactFeasible ? "exact" : "permutation";
2255
+ if (request === "exact") {
2256
+ if (exactFeasible) return "exact";
2257
+ throw new ValidationError(`${fn}: method 'exact' is out of range at ${design} — enumeration is bounded by ${threshold}. Use 'auto' for the seeded Monte Carlo permutation, which converges to the same answer.`);
2258
+ }
2259
+ if (exactFeasible) throw new ValidationError(`${fn}: method 'asymptotic' is refused at ${design} — the exact p-grid at this design starts at ${formatProbability(designFloor)}, so an asymptotic p below it describes no attainable outcome. Use method 'exact' (the default) or add repetitions past ${threshold}.`);
2260
+ return "asymptotic";
2261
+ }
2262
+ function resolvePermutations(fn, permutations) {
2263
+ if (permutations === void 0) return DEFAULT_PERMUTATIONS;
2264
+ if (!Number.isInteger(permutations) || permutations < 1) throw new ValidationError(`${fn}: permutations must be a positive integer, got ${permutations}`);
2265
+ return permutations;
2266
+ }
2267
+ /** Two-sided normal-approximation tail with the continuity correction. */
2268
+ function asymptoticTwoSidedP(deviation, sigma) {
2269
+ if (!(sigma > 0)) return 1;
2270
+ return Math.min(1, 2 * (1 - normalCdf(Math.max(0, deviation - .5) / sigma)));
2271
+ }
2272
+ /** SD of U under the permutation null, corrected for the realised ties. The
2273
+ * tie term reduces (N+1) and reaches it exactly when every value is tied, so
2274
+ * the variance floors at 0 rather than going negative. */
2275
+ function twoSampleSigma(n1, n2, total, tieTerm) {
2276
+ if (total < 2) return 0;
2277
+ const variance = n1 * n2 / 12 * (total + 1 - tieTerm / (total * (total - 1)));
2278
+ return Math.sqrt(Math.max(0, variance));
2279
+ }
2280
+ function logChoose(n, k) {
2281
+ return lnGamma(n + 1) - lnGamma(k + 1) - lnGamma(n - k + 1);
2282
+ }
2283
+ function formatProbability(value) {
2284
+ return value >= 1e-4 || value === 0 ? value.toFixed(4) : value.toExponential(3);
2285
+ }
2286
+ /**
2287
+ * Exact DP allocation and loop count for this observed rank vector.
2288
+ *
2289
+ * The smaller arm is sufficient because selecting its complement produces the
2290
+ * same two-sided U deviation while using fewer rows in the state table.
2291
+ */
2292
+ function exactTwoSampleCost(doubledRanks, selectedN) {
2293
+ const maxSum = doubledRanks.reduce((sum, rank) => sum + rank, 0);
2294
+ let work = 0;
2295
+ for (let placed = 0; placed < doubledRanks.length; placed++) work += Math.min(selectedN, placed + 1) * (maxSum - doubledRanks[placed] + 1);
2296
+ return {
2297
+ states: (selectedN + 1) * (maxSum + 1),
2298
+ work
2299
+ };
2300
+ }
2301
+ /**
2302
+ * Smallest attainable two-sided p under the observed ties.
2303
+ *
2304
+ * Only subsets with the minimum or maximum rank sum can attain the largest
2305
+ * deviation. Their multiplicity is the number of ways to choose within the
2306
+ * tie group at each boundary, so this calculation is exact without allocating
2307
+ * the full null distribution.
2308
+ */
2309
+ function exactTwoSampleFloor(doubledRanks, selectedN) {
2310
+ const total = doubledRanks.length;
2311
+ const otherN = total - selectedN;
2312
+ const minimumSum = doubledRanks.slice(0, selectedN).reduce((sum, rank) => sum + rank, 0);
2313
+ const maximumSum = doubledRanks.slice(total - selectedN).reduce((sum, rank) => sum + rank, 0);
2314
+ if (minimumSum === maximumSum) return 1;
2315
+ const centre = selectedN * (selectedN + 1) + selectedN * otherN;
2316
+ const minimumDeviation = Math.abs(minimumSum - centre);
2317
+ const maximumDeviation = Math.abs(maximumSum - centre);
2318
+ const totalLogWays = logChoose(total, selectedN);
2319
+ const minimumMass = Math.exp(logExtremeSubsetWays(doubledRanks, selectedN, "minimum") - totalLogWays);
2320
+ const maximumMass = Math.exp(logExtremeSubsetWays(doubledRanks, selectedN, "maximum") - totalLogWays);
2321
+ if (minimumDeviation > maximumDeviation) return minimumMass;
2322
+ if (maximumDeviation > minimumDeviation) return maximumMass;
2323
+ return Math.min(1, minimumMass + maximumMass);
2324
+ }
2325
+ function logExtremeSubsetWays(sortedRanks, selectedN, side) {
2326
+ const boundaryIndex = side === "minimum" ? selectedN - 1 : sortedRanks.length - selectedN;
2327
+ const boundary = sortedRanks[boundaryIndex];
2328
+ let first = boundaryIndex;
2329
+ let afterLast = boundaryIndex + 1;
2330
+ while (first > 0 && sortedRanks[first - 1] === boundary) first--;
2331
+ while (afterLast < sortedRanks.length && sortedRanks[afterLast] === boundary) afterLast++;
2332
+ return logChoose(afterLast - first, selectedN - (side === "minimum" ? first : sortedRanks.length - afterLast));
2333
+ }
2334
+ /**
2335
+ * Exact conditional two-sided p for the two-sample rank test.
2336
+ *
2337
+ * Convolves the observed doubled midranks into the null distribution of group
2338
+ * a's rank sum over every `C(n₁+n₂, n₁)` split — identical to enumerating the
2339
+ * splits, but `O(N·n₁·ΣR)` instead of `O(C(N,n₁)·n₁n₂)`. Conditioning on the
2340
+ * realised multiset makes the tie handling exact rather than a correction.
2341
+ *
2342
+ * The null is symmetric about `n₁n₂/2` (negating every value maps `U → n₁n₂ −
2343
+ * U` and permutes the split set onto itself), so the two-sided p is the mass
2344
+ * at least as far from the centre as the observation.
2345
+ */
2346
+ function exactTwoSampleP(doubledRanks, n1, n2, doubledDeviation) {
2347
+ const maxSum = doubledRanks.reduce((sum, rank) => sum + rank, 0);
2348
+ const width = maxSum + 1;
2349
+ const ways = Array.from({ length: n1 + 1 }, () => new Float64Array(width));
2350
+ ways[0][0] = 1;
2351
+ let placed = 0;
2352
+ for (const rank of doubledRanks) {
2353
+ for (let k = Math.min(n1, placed + 1); k >= 1; k--) {
2354
+ const from = ways[k - 1];
2355
+ const into = ways[k];
2356
+ for (let sum = maxSum - rank; sum >= 0; sum--) {
2357
+ const count = from[sum];
2358
+ if (count !== 0) into[sum + rank] += count;
2359
+ }
2360
+ }
2361
+ placed++;
2362
+ }
2363
+ const shift = n1 * (n1 + 1) + n1 * n2;
2364
+ const chosen = ways[n1];
2365
+ let totalWays = 0;
2366
+ let extremeWays = 0;
2367
+ let tailWays = 0;
2368
+ let maxDeviation = -1;
2369
+ for (let sum = 0; sum < width; sum++) {
2370
+ const count = chosen[sum];
2371
+ if (count === 0) continue;
2372
+ totalWays += count;
2373
+ const deviation = Math.abs(sum - shift);
2374
+ if (deviation >= doubledDeviation) tailWays += count;
2375
+ if (deviation > maxDeviation) {
2376
+ maxDeviation = deviation;
2377
+ extremeWays = count;
2378
+ } else if (deviation === maxDeviation) extremeWays += count;
2379
+ }
2380
+ return {
2381
+ p: tailWays / totalWays,
2382
+ pFloor: extremeWays / totalWays
2383
+ };
2384
+ }
2385
+ /**
2386
+ * Exact conditional two-sided p for the paired signed-rank test.
2387
+ *
2388
+ * Convolves the observed doubled absolute midranks over all `2ⁿ` sign
2389
+ * assignments in `O(n·ΣR)`. Probabilities rather than counts keep `2ⁿ` off the
2390
+ * arithmetic. The null is symmetric about `n(n+1)/4`.
2391
+ */
2392
+ function exactSignedRankP(doubledRanks, doubledDeviation) {
2393
+ const maxSum = doubledRanks.reduce((sum, rank) => sum + rank, 0);
2394
+ const width = maxSum + 1;
2395
+ let mass = new Float64Array(width);
2396
+ mass[0] = 1;
2397
+ for (const rank of doubledRanks) {
2398
+ const next = new Float64Array(width);
2399
+ for (let sum = 0; sum < width; sum++) {
2400
+ const probability = mass[sum];
2401
+ if (probability === 0) continue;
2402
+ next[sum] += probability * .5;
2403
+ next[sum + rank] += probability * .5;
2404
+ }
2405
+ mass = next;
2406
+ }
2407
+ const centre = maxSum / 2;
2408
+ let tail = 0;
2409
+ let extreme = 0;
2410
+ let maxDeviation = -1;
2411
+ for (let sum = 0; sum < width; sum++) {
2412
+ const probability = mass[sum];
2413
+ if (probability === 0) continue;
2414
+ const deviation = Math.abs(sum - centre);
2415
+ if (deviation >= doubledDeviation) tail += probability;
2416
+ if (deviation > maxDeviation) {
2417
+ maxDeviation = deviation;
2418
+ extreme = probability;
2419
+ } else if (deviation === maxDeviation) extreme += probability;
2420
+ }
2421
+ return {
2422
+ p: Math.min(1, tail),
2423
+ pFloor: Math.min(1, extreme)
2424
+ };
2425
+ }
2426
+ // src/statistics/samples.ts
2427
+ /** Interpolated sample median; an empty population has no measured median. */
2428
+ function sampleMedian(values) {
2429
+ assertFiniteSample("sampleMedian", "values", values);
2430
+ return values.length ? medianInPlace([...values]) : null;
2431
+ }
2432
+ /** Descriptive facts, not stability policy or a significance test. */
2433
+ function summarizeSample(values, options = {}) {
2434
+ assertFiniteSample("summarizeSample", "values", values);
2435
+ const confidence = options.confidence ?? .95;
2436
+ const resamples = options.resamples ?? 1e3;
2437
+ if (!Number.isFinite(confidence) || confidence <= 0 || confidence >= 1) throw new ValidationError("summarizeSample: confidence must be between zero and one");
2438
+ if (!Number.isSafeInteger(resamples) || resamples < 1) throw new ValidationError("summarizeSample: resamples must be a positive safe integer");
2439
+ const rng = makeRng(options.seed, [...values]);
2440
+ if (!values.length) return null;
2441
+ const sorted = [...values].sort((a, b) => a - b);
2442
+ const n = sorted.length;
2443
+ const mean = sorted.reduce((sum, value) => sum + value / n, 0);
2444
+ const centered = sorted.map((value) => value - mean);
2445
+ const sumSquares = centered.reduce((sum, value) => sum + value ** 2, 0);
2446
+ const stddev = n > 1 ? Math.sqrt(sumSquares / (n - 1)) : 0;
2447
+ const median = interpolatedQuantile(sorted, .5);
2448
+ const q1 = interpolatedQuantile(sorted, .25);
2449
+ const q3 = interpolatedQuantile(sorted, .75);
2450
+ const iqr = q3 - q1;
2451
+ const deviations = sorted.map((value) => Math.abs(value - median)).sort((a, b) => a - b);
2452
+ const skewness = n >= 3 && stddev > 0 ? n * centered.reduce((sum, value) => sum + (value / stddev) ** 3, 0) / ((n - 1) * (n - 2)) : null;
2453
+ const kurtosis = n >= 4 && stddev > 0 ? n * (n + 1) * centered.reduce((sum, value) => sum + (value / stddev) ** 4, 0) / ((n - 1) * (n - 2) * (n - 3)) - 3 * (n - 1) ** 2 / ((n - 2) * (n - 3)) : null;
2454
+ const bootstrap = [];
2455
+ if (n >= 3) {
2456
+ for (let i = 0; i < resamples; i++) {
2457
+ const sample = Array.from({ length: n }, () => sorted[Math.floor(rng() * n)]);
2458
+ bootstrap.push(medianInPlace(sample));
2459
+ }
2460
+ bootstrap.sort((a, b) => a - b);
2461
+ }
2462
+ const alpha = (1 - confidence) / 2;
2463
+ const summary = {
2464
+ n,
2465
+ median,
2466
+ mean,
2467
+ stddev,
2468
+ q1,
2469
+ q3,
2470
+ iqr,
2471
+ min: sorted[0],
2472
+ max: sorted[n - 1],
2473
+ range: sorted[n - 1] - sorted[0],
2474
+ cv: mean === 0 ? null : stddev / Math.abs(mean),
2475
+ skewness,
2476
+ kurtosis,
2477
+ mad: interpolatedQuantile(deviations, .5),
2478
+ outliers: sorted.filter((value) => value < q1 - 1.5 * iqr || value > q3 + 1.5 * iqr),
2479
+ medianInterval: n < 3 ? null : {
2480
+ low: interpolatedQuantile(bootstrap, alpha),
2481
+ high: interpolatedQuantile(bootstrap, 1 - alpha),
2482
+ confidence,
2483
+ resamples
2484
+ }
2485
+ };
2486
+ if ([
2487
+ mean,
2488
+ stddev,
2489
+ iqr,
2490
+ summary.range,
2491
+ summary.mad,
2492
+ summary.cv,
2493
+ skewness,
2494
+ kurtosis,
2495
+ summary.medianInterval?.low ?? null,
2496
+ summary.medianInterval?.high ?? null
2497
+ ].some((value) => value !== null && !Number.isFinite(value))) throw new ValidationError("summarizeSample: sample arithmetic exceeded finite range");
2498
+ return summary;
2499
+ }
2500
+ // src/statistics/sequential-eprocess.ts
2501
+ /**
2502
+ * Betting test-martingale for bounded observations — the e-process core of
2503
+ * anytime-valid sequential testing (Waudby-Smith & Ramdas, "Estimating means
2504
+ * of bounded random variables by betting", JRSS-B 2024).
2505
+ *
2506
+ * Observations x_i ∈ [0,1]; H0: E[x] ≤ m₀ (`nullMean`, default 1/2). Wealth
2507
+ *
2508
+ * W_t = Π_{i≤t} (1 + λ_i (x_i − m₀)), W_0 = 1
2509
+ *
2510
+ * with the truncated GROW-style plug-in bet computed from PRIOR observations:
2511
+ *
2512
+ * λ_i = clamp((μ̂_{i−1} − m₀) / (σ̂²_{i−1} + (μ̂_{i−1} − m₀)²), 0, maxBet)
2513
+ *
2514
+ * where μ̂/σ̂² are the shrunk running estimates μ̂_t = (1/2 + Σx_i)/(t+1),
2515
+ * σ̂²_t = (1/4 + Σ(x_i − μ̂_i)²)/(t+1).
2516
+ *
2517
+ * PREDICTABILITY INVARIANT (load-bearing): λ_i is a function of x_1..x_{i−1}
2518
+ * ONLY — it may never see x_i. With λ_i ≥ 0 predictable, each factor has
2519
+ * E[1 + λ_i(x_i − m₀) | past] ≤ 1 under H0, so W is a nonnegative
2520
+ * supermartingale and Ville's inequality gives P(∃t: W_t ≥ 1/α) ≤ α — the
2521
+ * type-I guarantee holds at ANY data-dependent stopping time. λ_1 is always 0
2522
+ * (no prior evidence), so the first observation never moves wealth.
2523
+ *
2524
+ * `decided` latches at the first crossing W_t ≥ 1/α and never un-latches;
2525
+ * wealth keeps updating after the crossing (the e-process remains valid), but
2526
+ * the decision time is the first crossing.
2527
+ */
2528
+ function eProcess(opts = {}) {
2529
+ const alpha = opts.alpha ?? .05;
2530
+ const maxBet = opts.maxBet ?? .5;
2531
+ const nullMean = opts.nullMean ?? .5;
2532
+ if (!Number.isFinite(alpha) || alpha <= 0 || alpha >= 1) throw new ValidationError(`eProcess: alpha must be in (0,1), got ${alpha}`);
2533
+ if (!Number.isFinite(nullMean) || nullMean <= 0 || nullMean >= 1) throw new ValidationError(`eProcess: nullMean must be in (0,1), got ${nullMean}`);
2534
+ if (!Number.isFinite(maxBet) || maxBet <= 0 || maxBet >= 1 / nullMean) throw new ValidationError(`eProcess: maxBet must be in (0, 1/nullMean=${(1 / nullMean).toFixed(4)}) so wealth factors stay positive, got ${maxBet}`);
2535
+ const threshold = 1 / alpha;
2536
+ let wealth = 1;
2537
+ let n = 0;
2538
+ let decided = false;
2539
+ let decidedAtN;
2540
+ let sumX = 0;
2541
+ let varSum = 0;
2542
+ if (opts.resume !== void 0) {
2543
+ const r = assertResumable(opts.resume, {
2544
+ alpha,
2545
+ maxBet,
2546
+ nullMean,
2547
+ threshold
2548
+ });
2549
+ wealth = r.wealth;
2550
+ n = r.n;
2551
+ decided = r.decided;
2552
+ decidedAtN = r.decidedAtN;
2553
+ sumX = r.sumX;
2554
+ varSum = r.varSum;
2555
+ }
2556
+ return {
2557
+ update(x) {
2558
+ if (typeof x !== "number" || !Number.isFinite(x) || x < 0 || x > 1) throw new ValidationError(`eProcess: observation must be a finite number in [0,1], got ${x}`);
2559
+ const muPrev = (.5 + sumX) / (n + 1);
2560
+ const varPrev = (.25 + varSum) / (n + 1);
2561
+ const edge = muPrev - nullMean;
2562
+ const lambda = Math.min(maxBet, Math.max(0, edge / (varPrev + edge * edge)));
2563
+ wealth *= 1 + lambda * (x - nullMean);
2564
+ n += 1;
2565
+ sumX += x;
2566
+ const muNow = (.5 + sumX) / (n + 1);
2567
+ varSum += (x - muNow) ** 2;
2568
+ if (!decided && wealth >= threshold) {
2569
+ decided = true;
2570
+ decidedAtN = n;
2571
+ }
2572
+ return {
2573
+ wealth,
2574
+ n,
2575
+ decided
2576
+ };
2577
+ },
2578
+ state() {
2579
+ return {
2580
+ wealth,
2581
+ n,
2582
+ decided,
2583
+ alpha,
2584
+ maxBet,
2585
+ nullMean,
2586
+ threshold,
2587
+ decidedAtN,
2588
+ sumX,
2589
+ varSum
2590
+ };
2591
+ }
2592
+ };
2593
+ }
2594
+ /**
2595
+ * Refuse a snapshot that was not produced by an e-process with exactly these
2596
+ * parameters, or whose fields cannot all be true at once. Every check names
2597
+ * the field, so a refused restart reports what disagrees.
2598
+ */
2599
+ function assertResumable(resume, params) {
2600
+ const fail = (detail) => {
2601
+ throw new ValidationError(`eProcess: cannot resume — ${detail}`);
2602
+ };
2603
+ if (typeof resume !== "object" || resume === null) fail(`resume must be an EProcessState object, got ${String(resume)}`);
2604
+ for (const key of [
2605
+ "alpha",
2606
+ "maxBet",
2607
+ "nullMean",
2608
+ "threshold"
2609
+ ]) if (resume[key] !== params[key]) fail(`snapshot ${key}=${resume[key]} differs from the process ${key}=${params[key]}; a snapshot continues only the process it was taken from`);
2610
+ const { wealth, n, decided, decidedAtN, sumX, varSum } = resume;
2611
+ if (!Number.isInteger(n) || n < 0) fail(`n must be a non-negative integer, got ${n}`);
2612
+ if (!Number.isFinite(wealth) || wealth <= 0) fail(`wealth must be a finite positive number, got ${wealth}`);
2613
+ if (!Number.isFinite(sumX) || sumX < 0 || sumX > n) fail(`sumX must lie in [0, n=${n}] for observations in [0,1], got ${sumX}`);
2614
+ if (!Number.isFinite(varSum) || varSum < 0) fail(`varSum must be a finite non-negative number, got ${varSum}`);
2615
+ if (typeof decided !== "boolean") fail(`decided must be a boolean, got ${String(decided)}`);
2616
+ if (n === 0 && (wealth !== 1 || sumX !== 0 || varSum !== 0 || decided)) fail("n=0 requires wealth=1, sumX=0, varSum=0, decided=false");
2617
+ if (decided) {
2618
+ if (decidedAtN === void 0 || !Number.isInteger(decidedAtN) || decidedAtN < 1 || decidedAtN > n) fail(`decided requires decidedAtN to be an integer in [1, n=${n}], got ${decidedAtN}`);
2619
+ } else {
2620
+ if (decidedAtN !== void 0) fail(`decidedAtN=${decidedAtN} is set while decided=false`);
2621
+ if (wealth >= params.threshold) fail(`wealth ${wealth} ≥ threshold ${params.threshold} while decided=false; decided latches at the first crossing`);
2622
+ }
2623
+ return resume;
2624
+ }
2625
+ export { partialCredit as $, linearRegressionSlope as A, rocAuc as B, wilson as C, chiSquared as D, holm as E, cohensD as F, calibrateJudge as G, corpusInterRaterAgreementFromJudgeScores as H, interpretCliffs as I, positionalBias as J, calibrateJudgeContinuous as K, pairedCohensDz as L, studentTTwoSidedPValue as M, twoByTwoPValue as N, chiSquaredPValue as O, cliffsDelta as P, meanConfidenceInterval as Q, percentileNearestRank as R, passAtK as S, bonferroni as T, interRaterReliability as U, corpusInterRaterAgreement as V, nominalAgreement as W, verbosityBias as X, selfPreference as Y, confidenceInterval as Z, mcnemar as _, studentTCdf as _t, wilcoxonSignedRank as a, weightedComposite as at, pairedRiskDifferenceExact as b, pairedMde as c, meanOrNull as ct, BOOTSTRAP_GATE_MIN_N as d, medianInPlace as dt, pearsonR as et, DECISION_PAIRED_DELTA_STATISTIC as f, seedFromData as ft, pairedTTest as g, placeboBand as gt, pairedSignTest as h, clusterBootstrap as ht, mannWhitneyU as i, summarizeNumberSeries as it, normalTwoSidedPValue as j, fisherExactTwoSided as k, requiredPairedSampleSize as l, meanOrZero as lt, pairedDeltaTieFraction as m, DEFAULT_BOOTSTRAP_SEED as mt, sampleMedian as n, spearmanR as nt, mcnemarPower as o, weightedMean as ot, pairedBootstrap as p, zQuantile as pt, continuousAgreement as q, summarizeSample as r, studentTCritical as rt, mcnemarRequiredN as s, mean as st, eProcess as t, ranks as tt, requiredSampleSize as u, makeRng as ut, pairedBinaryScale as v, studentTQuantile as vt, benjaminiHochberg as w, pairedRiskDifferenceScore as x, pairedRiskDifference as y, summarizeDistribution as z };
2626
+
2627
+ //# sourceMappingURL=statistics-DCZIC-qT.js.map