@seanhogg/builderforce-memory 2026.10.70 → 2026.10.72

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 (214) hide show
  1. package/dist/knowledge/build.d.ts +3 -1
  2. package/dist/knowledge/build.d.ts.map +1 -1
  3. package/dist/knowledge/build.js +5 -1
  4. package/dist/knowledge/build.js.map +1 -1
  5. package/dist/knowledge/coChange.d.ts +106 -0
  6. package/dist/knowledge/coChange.d.ts.map +1 -0
  7. package/dist/knowledge/coChange.js +309 -0
  8. package/dist/knowledge/coChange.js.map +1 -0
  9. package/dist/knowledge/communities.d.ts +2 -0
  10. package/dist/knowledge/communities.d.ts.map +1 -1
  11. package/dist/knowledge/communities.js +5 -1
  12. package/dist/knowledge/communities.js.map +1 -1
  13. package/dist/knowledge/extractFile.d.ts +10 -0
  14. package/dist/knowledge/extractFile.d.ts.map +1 -1
  15. package/dist/knowledge/extractFile.js +16 -5
  16. package/dist/knowledge/extractFile.js.map +1 -1
  17. package/dist/knowledge/extractJob.d.ts +18 -1
  18. package/dist/knowledge/extractJob.d.ts.map +1 -1
  19. package/dist/knowledge/extractJob.js +10 -4
  20. package/dist/knowledge/extractJob.js.map +1 -1
  21. package/dist/knowledge/facts/extractorVersion.d.ts +45 -0
  22. package/dist/knowledge/facts/extractorVersion.d.ts.map +1 -0
  23. package/dist/knowledge/facts/extractorVersion.js +56 -0
  24. package/dist/knowledge/facts/extractorVersion.js.map +1 -0
  25. package/dist/knowledge/facts/fileFacts.d.ts +166 -0
  26. package/dist/knowledge/facts/fileFacts.d.ts.map +1 -0
  27. package/dist/knowledge/facts/fileFacts.js +156 -0
  28. package/dist/knowledge/facts/fileFacts.js.map +1 -0
  29. package/dist/knowledge/findings.d.ts +17 -14
  30. package/dist/knowledge/findings.d.ts.map +1 -1
  31. package/dist/knowledge/findings.js +29 -129
  32. package/dist/knowledge/findings.js.map +1 -1
  33. package/dist/knowledge/index.d.ts +17 -1
  34. package/dist/knowledge/index.d.ts.map +1 -1
  35. package/dist/knowledge/index.js +10 -1
  36. package/dist/knowledge/index.js.map +1 -1
  37. package/dist/knowledge/model.d.ts +6 -0
  38. package/dist/knowledge/model.d.ts.map +1 -1
  39. package/dist/knowledge/outline.d.ts.map +1 -1
  40. package/dist/knowledge/outline.js +2 -0
  41. package/dist/knowledge/outline.js.map +1 -1
  42. package/dist/knowledge/owedFiles.d.ts +14 -4
  43. package/dist/knowledge/owedFiles.d.ts.map +1 -1
  44. package/dist/knowledge/owedFiles.js +30 -8
  45. package/dist/knowledge/owedFiles.js.map +1 -1
  46. package/dist/knowledge/plan.d.ts +10 -1
  47. package/dist/knowledge/plan.d.ts.map +1 -1
  48. package/dist/knowledge/plan.js +9 -4
  49. package/dist/knowledge/plan.js.map +1 -1
  50. package/dist/knowledge/refs.d.ts.map +1 -1
  51. package/dist/knowledge/refs.js +3 -1
  52. package/dist/knowledge/refs.js.map +1 -1
  53. package/dist/knowledge/review.js +1 -0
  54. package/dist/knowledge/review.js.map +1 -1
  55. package/dist/knowledge/reviewContext.d.ts.map +1 -1
  56. package/dist/knowledge/reviewContext.js +5 -2
  57. package/dist/knowledge/reviewContext.js.map +1 -1
  58. package/dist/knowledge/reviewFinish.d.ts.map +1 -1
  59. package/dist/knowledge/reviewFinish.js +3 -1
  60. package/dist/knowledge/reviewFinish.js.map +1 -1
  61. package/dist/knowledge/reviewModel.d.ts +12 -0
  62. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  63. package/dist/knowledge/reviewPrefetch.d.ts +2 -0
  64. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
  65. package/dist/knowledge/reviewPrefetch.js +1 -0
  66. package/dist/knowledge/reviewPrefetch.js.map +1 -1
  67. package/dist/knowledge/rules/cloneGroup.d.ts +10 -0
  68. package/dist/knowledge/rules/cloneGroup.d.ts.map +1 -0
  69. package/dist/knowledge/rules/cloneGroup.js +46 -0
  70. package/dist/knowledge/rules/cloneGroup.js.map +1 -0
  71. package/dist/knowledge/rules/components.d.ts +8 -0
  72. package/dist/knowledge/rules/components.d.ts.map +1 -0
  73. package/dist/knowledge/rules/components.js +34 -0
  74. package/dist/knowledge/rules/components.js.map +1 -0
  75. package/dist/knowledge/rules/cycle.d.ts +7 -0
  76. package/dist/knowledge/rules/cycle.d.ts.map +1 -0
  77. package/dist/knowledge/rules/cycle.js +18 -0
  78. package/dist/knowledge/rules/cycle.js.map +1 -0
  79. package/dist/knowledge/rules/duplicateCopy.d.ts +7 -0
  80. package/dist/knowledge/rules/duplicateCopy.d.ts.map +1 -0
  81. package/dist/knowledge/rules/duplicateCopy.js +18 -0
  82. package/dist/knowledge/rules/duplicateCopy.js.map +1 -0
  83. package/dist/knowledge/rules/evaluateRules.d.ts +60 -0
  84. package/dist/knowledge/rules/evaluateRules.d.ts.map +1 -0
  85. package/dist/knowledge/rules/evaluateRules.js +164 -0
  86. package/dist/knowledge/rules/evaluateRules.js.map +1 -0
  87. package/dist/knowledge/rules/factGraph.d.ts +51 -0
  88. package/dist/knowledge/rules/factGraph.d.ts.map +1 -0
  89. package/dist/knowledge/rules/factGraph.js +77 -0
  90. package/dist/knowledge/rules/factGraph.js.map +1 -0
  91. package/dist/knowledge/rules/factRule.d.ts +56 -0
  92. package/dist/knowledge/rules/factRule.d.ts.map +1 -0
  93. package/dist/knowledge/rules/factRule.js +46 -0
  94. package/dist/knowledge/rules/factRule.js.map +1 -0
  95. package/dist/knowledge/rules/godModule.d.ts +8 -0
  96. package/dist/knowledge/rules/godModule.d.ts.map +1 -0
  97. package/dist/knowledge/rules/godModule.js +16 -0
  98. package/dist/knowledge/rules/godModule.js.map +1 -0
  99. package/dist/knowledge/rules/knowledgeInput.d.ts +35 -0
  100. package/dist/knowledge/rules/knowledgeInput.d.ts.map +1 -0
  101. package/dist/knowledge/rules/knowledgeInput.js +33 -0
  102. package/dist/knowledge/rules/knowledgeInput.js.map +1 -0
  103. package/dist/knowledge/rules/nearDuplicate.d.ts +7 -0
  104. package/dist/knowledge/rules/nearDuplicate.d.ts.map +1 -0
  105. package/dist/knowledge/rules/nearDuplicate.js +20 -0
  106. package/dist/knowledge/rules/nearDuplicate.js.map +1 -0
  107. package/dist/knowledge/rules/partitionViolation.d.ts +10 -0
  108. package/dist/knowledge/rules/partitionViolation.d.ts.map +1 -0
  109. package/dist/knowledge/rules/partitionViolation.js +27 -0
  110. package/dist/knowledge/rules/partitionViolation.js.map +1 -0
  111. package/dist/knowledge/rules/possibleSame.d.ts +7 -0
  112. package/dist/knowledge/rules/possibleSame.d.ts.map +1 -0
  113. package/dist/knowledge/rules/possibleSame.js +15 -0
  114. package/dist/knowledge/rules/possibleSame.js.map +1 -0
  115. package/dist/knowledge/rules/stale.d.ts +7 -0
  116. package/dist/knowledge/rules/stale.d.ts.map +1 -0
  117. package/dist/knowledge/rules/stale.js +28 -0
  118. package/dist/knowledge/rules/stale.js.map +1 -0
  119. package/dist/knowledge/rules/unpartitioned.d.ts +7 -0
  120. package/dist/knowledge/rules/unpartitioned.d.ts.map +1 -0
  121. package/dist/knowledge/rules/unpartitioned.js +26 -0
  122. package/dist/knowledge/rules/unpartitioned.js.map +1 -0
  123. package/dist/knowledge/sources.d.ts +14 -1
  124. package/dist/knowledge/sources.d.ts.map +1 -1
  125. package/dist/knowledge/sources.js +17 -1
  126. package/dist/knowledge/sources.js.map +1 -1
  127. package/dist/knowledge/transitions.d.ts +59 -0
  128. package/dist/knowledge/transitions.d.ts.map +1 -0
  129. package/dist/knowledge/transitions.js +90 -0
  130. package/dist/knowledge/transitions.js.map +1 -0
  131. package/dist/retrieval/knowledge-index/sha256.d.ts.map +1 -1
  132. package/dist/retrieval/knowledge-index/sha256.js +2 -2
  133. package/dist/retrieval/knowledge-index/sha256.js.map +1 -1
  134. package/dist/stats/distributions.d.ts +40 -2
  135. package/dist/stats/distributions.d.ts.map +1 -1
  136. package/dist/stats/distributions.js +128 -20
  137. package/dist/stats/distributions.js.map +1 -1
  138. package/dist/stats/fitting.d.ts.map +1 -1
  139. package/dist/stats/fitting.js +1 -6
  140. package/dist/stats/fitting.js.map +1 -1
  141. package/dist/stats/index.d.ts +10 -3
  142. package/dist/stats/index.d.ts.map +1 -1
  143. package/dist/stats/index.js +10 -3
  144. package/dist/stats/index.js.map +1 -1
  145. package/dist/stats/logistic.d.ts +30 -0
  146. package/dist/stats/logistic.d.ts.map +1 -0
  147. package/dist/stats/logistic.js +43 -0
  148. package/dist/stats/logistic.js.map +1 -0
  149. package/dist/stats/multivariate.d.ts +8 -13
  150. package/dist/stats/multivariate.d.ts.map +1 -1
  151. package/dist/stats/multivariate.js +7 -53
  152. package/dist/stats/multivariate.js.map +1 -1
  153. package/dist/stats/policies.d.ts.map +1 -1
  154. package/dist/stats/policies.js +4 -22
  155. package/dist/stats/policies.js.map +1 -1
  156. package/package.json +4 -3
  157. package/src/contract/exports.snapshot.json +57 -1
  158. package/src/contract/regression.assets.test.ts +4 -0
  159. package/src/contract/regression.extractorKey.test.ts +202 -0
  160. package/src/contract/regression.statsEngineFree.test.ts +70 -0
  161. package/src/contract/regression.thompsonDeterminism.test.ts +23 -0
  162. package/src/contract/types.contract.test.ts +104 -1
  163. package/src/knowledge/build.ts +5 -1
  164. package/src/knowledge/coChange.test.ts +310 -0
  165. package/src/knowledge/coChange.ts +345 -0
  166. package/src/knowledge/communities.ts +6 -1
  167. package/src/knowledge/extractFile.ts +27 -5
  168. package/src/knowledge/extractJob.ts +24 -5
  169. package/src/knowledge/facts/extractorVersion.ts +73 -0
  170. package/src/knowledge/facts/fileFacts.test.ts +157 -0
  171. package/src/knowledge/facts/fileFacts.ts +305 -0
  172. package/src/knowledge/findings.ts +30 -127
  173. package/src/knowledge/index.ts +26 -0
  174. package/src/knowledge/model.ts +6 -0
  175. package/src/knowledge/outline.ts +2 -0
  176. package/src/knowledge/owedFiles.ts +36 -8
  177. package/src/knowledge/plan.ts +16 -4
  178. package/src/knowledge/refs.ts +4 -1
  179. package/src/knowledge/review.ts +1 -0
  180. package/src/knowledge/reviewContext.ts +5 -2
  181. package/src/knowledge/reviewFinish.ts +3 -1
  182. package/src/knowledge/reviewModel.ts +12 -0
  183. package/src/knowledge/reviewPrefetch.ts +3 -0
  184. package/src/knowledge/rules/cloneGroup.ts +45 -0
  185. package/src/knowledge/rules/components.ts +31 -0
  186. package/src/knowledge/rules/cycle.ts +20 -0
  187. package/src/knowledge/rules/duplicateCopy.ts +22 -0
  188. package/src/knowledge/rules/evaluateRules.test.ts +172 -0
  189. package/src/knowledge/rules/evaluateRules.ts +186 -0
  190. package/src/knowledge/rules/factGraph.oracle.test.ts +174 -0
  191. package/src/knowledge/rules/factGraph.ts +107 -0
  192. package/src/knowledge/rules/factRule.ts +74 -0
  193. package/src/knowledge/rules/godModule.ts +18 -0
  194. package/src/knowledge/rules/knowledgeInput.ts +60 -0
  195. package/src/knowledge/rules/knowledgeRules.test.ts +78 -0
  196. package/src/knowledge/rules/nearDuplicate.ts +22 -0
  197. package/src/knowledge/rules/partitionViolation.ts +31 -0
  198. package/src/knowledge/rules/possibleSame.ts +17 -0
  199. package/src/knowledge/rules/rules.testkit.test-util.ts +78 -0
  200. package/src/knowledge/rules/stale.ts +31 -0
  201. package/src/knowledge/rules/unpartitioned.ts +27 -0
  202. package/src/knowledge/sources.ts +19 -1
  203. package/src/knowledge/transitions.test.ts +135 -0
  204. package/src/knowledge/transitions.ts +115 -0
  205. package/src/retrieval/knowledge-index/sha256.test.ts +25 -0
  206. package/src/retrieval/knowledge-index/sha256.ts +2 -1
  207. package/src/stats/distributions.ts +132 -22
  208. package/src/stats/fitting.ts +1 -6
  209. package/src/stats/index.ts +15 -2
  210. package/src/stats/logistic.test.ts +89 -0
  211. package/src/stats/logistic.ts +49 -0
  212. package/src/stats/multivariate.ts +8 -59
  213. package/src/stats/policies.ts +4 -24
  214. package/src/stats/stats.test.ts +89 -0
@@ -6,6 +6,11 @@
6
6
  * shape ranges Part D uses (posterior counts and sample sizes).
7
7
  */
8
8
 
9
+ // Bound once at module scope: a bare `Math.x` is a global lookup on every call, which inside a vm context (the jest
10
+ // runner) costs ~1 µs each and made the inverse beta ~100× slower there; a module binding is free everywhere.
11
+ const { abs, exp, log, max, min, pow, sin, sqrt, PI } = Math;
12
+ const isFiniteNumber = Number.isFinite;
13
+
9
14
  const MAX_ITER = 200;
10
15
  const EPS = 3e-14;
11
16
  const FPMIN = 1e-300;
@@ -17,13 +22,13 @@ function logGamma(x: number): number {
17
22
  12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7,
18
23
  ];
19
24
  if (x < 0.5) {
20
- return Math.log(Math.PI / Math.sin(Math.PI * x)) - logGamma(1 - x);
25
+ return log(PI / sin(PI * x)) - logGamma(1 - x);
21
26
  }
22
27
  const z = x - 1;
23
28
  let sum = 0.99999999999980993;
24
29
  for (let i = 0; i < p.length; i++) sum += p[i]! / (z + i + 1);
25
30
  const t = z + p.length - 0.5;
26
- return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(sum);
31
+ return 0.5 * log(2 * PI) + (z + 0.5) * log(t) - t + log(sum);
27
32
  }
28
33
 
29
34
  function betaCf(a: number, b: number, x: number): number {
@@ -32,27 +37,27 @@ function betaCf(a: number, b: number, x: number): number {
32
37
  const qam = a - 1;
33
38
  let c = 1;
34
39
  let d = 1 - (qab * x) / qap;
35
- if (Math.abs(d) < FPMIN) d = FPMIN;
40
+ if (abs(d) < FPMIN) d = FPMIN;
36
41
  d = 1 / d;
37
42
  let h = d;
38
43
  for (let m = 1; m <= MAX_ITER; m++) {
39
44
  const m2 = 2 * m;
40
45
  let aa = (m * (b - m) * x) / ((qam + m2) * (a + m2));
41
46
  d = 1 + aa * d;
42
- if (Math.abs(d) < FPMIN) d = FPMIN;
47
+ if (abs(d) < FPMIN) d = FPMIN;
43
48
  c = 1 + aa / c;
44
- if (Math.abs(c) < FPMIN) c = FPMIN;
49
+ if (abs(c) < FPMIN) c = FPMIN;
45
50
  d = 1 / d;
46
51
  h *= d * c;
47
52
  aa = (-(a + m) * (qab + m) * x) / ((a + m2) * (qap + m2));
48
53
  d = 1 + aa * d;
49
- if (Math.abs(d) < FPMIN) d = FPMIN;
54
+ if (abs(d) < FPMIN) d = FPMIN;
50
55
  c = 1 + aa / c;
51
- if (Math.abs(c) < FPMIN) c = FPMIN;
56
+ if (abs(c) < FPMIN) c = FPMIN;
52
57
  d = 1 / d;
53
58
  const del = d * c;
54
59
  h *= del;
55
- if (Math.abs(del - 1) < EPS) break;
60
+ if (abs(del - 1) < EPS) break;
56
61
  }
57
62
  return h;
58
63
  }
@@ -61,46 +66,132 @@ function betaCf(a: number, b: number, x: number): number {
61
66
  export function regularizedIncompleteBeta(x: number, a: number, b: number): number {
62
67
  if (x <= 0) return 0;
63
68
  if (x >= 1) return 1;
64
- const bt = Math.exp(
65
- logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log(1 - x),
69
+ const bt = exp(
70
+ logGamma(a + b) - logGamma(a) - logGamma(b) + a * log(x) + b * log(1 - x),
66
71
  );
67
72
  if (x < (a + 1) / (a + b + 2)) return (bt * betaCf(a, b, x)) / a;
68
73
  return 1 - (bt * betaCf(b, a, 1 - x)) / b;
69
74
  }
70
75
 
71
- /** Inverse of the regularized incomplete beta, by bisection. Deterministic. */
76
+ /** The inverse stops when its Newton step is below this RELATIVE to the nearer end's distance, min(x, 1 − x). */
77
+ const INVERSE_BETA_TOL = 1e-10;
78
+ /** Hard cap on the inverse's steps (each costs one I_x evaluation). */
79
+ const INVERSE_BETA_MAX_STEPS = 100;
80
+
81
+ /** Starting point of the inverse (Numerical Recipes 3e §6.14 `invbetai`): a normal approximation, or the tail power law below a, b = 1. */
82
+ function inverseBetaGuess(p: number, a: number, b: number): number {
83
+ if (a >= 1 && b >= 1) {
84
+ const pp = p < 0.5 ? p : 1 - p;
85
+ const t = sqrt(-2 * log(pp));
86
+ let x = (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t;
87
+ if (p < 0.5) x = -x;
88
+ const al = (x * x - 3) / 6;
89
+ const h = 2 / (1 / (2 * a - 1) + 1 / (2 * b - 1));
90
+ const w = (x * sqrt(al + h)) / h - (1 / (2 * b - 1) - 1 / (2 * a - 1)) * (al + 5 / 6 - 2 / (3 * h));
91
+ return a / (a + b * exp(2 * w));
92
+ }
93
+ const lna = log(a / (a + b));
94
+ const lnb = log(b / (a + b));
95
+ const t = exp(a * lna) / a;
96
+ const u = exp(b * lnb) / b;
97
+ const w = t + u;
98
+ return p < t / w ? pow(a * w * p, 1 / a) : 1 - pow(b * w * (1 - p), 1 / b);
99
+ }
100
+
101
+ /** The scale a tolerance is relative to: the distance to the nearer end of (0, 1), so both tails keep their digits. */
102
+ const nearEnd = (x: number): number => max(min(x, 1 - x), 1e-300);
103
+
104
+ /**
105
+ * Inverse of the regularized incomplete beta: Halley steps on I_x(a, b) − p, kept inside a shrinking bracket [lo, hi].
106
+ * - Converged when the Newton step |f / density| is below INVERSE_BETA_TOL · min(x, 1 − x) (relative, so a quantile near 0
107
+ * or 1 keeps its accuracy); the step is then applied and clamped to the bracket. The test runs on the RAW step, before any
108
+ * bracket fallback, and a step landing exactly on a bracket end is converged too (a step under 1 ulp).
109
+ * - A step that leaves the bracket, or a degenerate density, falls back to the bracket's midpoint.
110
+ * - If INVERSE_BETA_MAX_STEPS pass without converging, plain bisection finishes the bracket to tolerance (or to the last
111
+ * representable midpoint): an unconverged x is never returned.
112
+ * Deterministic: a fixed start and a fixed sequence of steps.
113
+ */
72
114
  export function inverseRegularizedIncompleteBeta(p: number, a: number, b: number): number {
73
115
  if (p <= 0) return 0;
74
116
  if (p >= 1) return 1;
117
+ const lnBeta = logGamma(a) + logGamma(b) - logGamma(a + b);
75
118
  let lo = 0;
76
119
  let hi = 1;
77
- for (let i = 0; i < 100; i++) {
120
+ const guess = inverseBetaGuess(p, a, b);
121
+ let x = guess > 0 && guess < 1 ? guess : 0.5;
122
+ for (let i = 0; i < INVERSE_BETA_MAX_STEPS; i++) {
123
+ const f = regularizedIncompleteBeta(x, a, b) - p;
124
+ if (f === 0) return x;
125
+ if (f < 0) lo = x;
126
+ else hi = x;
127
+ const density = exp((a - 1) * log(x) + (b - 1) * log(1 - x) - lnBeta);
128
+ let next = -1; // outside every bracket: falls back to bisection
129
+ if (density > 0 && isFiniteNumber(density)) {
130
+ const newton = f / density;
131
+ next = x - newton / (1 - 0.5 * min(1, newton * ((a - 1) / x - (b - 1) / (1 - x))));
132
+ // Converged: judged on the undamped Newton distance (a Halley damping can shrink a far step), before any fallback.
133
+ if (abs(newton) < INVERSE_BETA_TOL * nearEnd(x) || next === lo || next === hi) {
134
+ return min(max(next, lo), hi);
135
+ }
136
+ }
137
+ if (!(next > lo && next < hi)) next = (lo + hi) / 2;
138
+ x = next;
139
+ }
140
+ // Step cap hit: bisect the bracket to tolerance.
141
+ for (;;) {
78
142
  const mid = (lo + hi) / 2;
143
+ if (mid <= lo || mid >= hi || hi - lo < INVERSE_BETA_TOL * nearEnd(mid)) return mid;
79
144
  if (regularizedIncompleteBeta(mid, a, b) < p) lo = mid;
80
145
  else hi = mid;
81
146
  }
82
- return (lo + hi) / 2;
83
147
  }
84
148
 
85
- /** Posterior Beta(α₀ + k, β₀ + n − k): mean and credible quantiles. */
149
+ /** Posterior Beta(α₀ + k, β₀ + n − k): mean, variance and credible quantiles. */
86
150
  export interface BetaPosterior {
87
151
  alpha: number;
88
152
  beta: number;
89
153
  mean: number;
154
+ variance: number;
90
155
  quantile(p: number): number;
91
156
  }
92
157
 
158
+ /** Mean α/(α+β) and variance αβ/((α+β)²(α+β+1)) of Beta(α, β). */
159
+ export function betaMoments(alpha: number, beta: number): { mean: number; variance: number } {
160
+ const total = alpha + beta;
161
+ return { mean: alpha / total, variance: (alpha * beta) / (total * total * (total + 1)) };
162
+ }
163
+
93
164
  export function betaPosterior(alpha0: number, beta0: number, k: number, n: number): BetaPosterior {
94
165
  const alpha = alpha0 + k;
95
166
  const beta = beta0 + (n - k);
96
167
  return {
97
168
  alpha,
98
169
  beta,
99
- mean: alpha / (alpha + beta),
170
+ ...betaMoments(alpha, beta),
100
171
  quantile: (p) => inverseRegularizedIncompleteBeta(p, alpha, beta),
101
172
  };
102
173
  }
103
174
 
175
+ /** Two-sided 95% standard-normal critical value. */
176
+ const Z_95 = 1.96;
177
+
178
+ /**
179
+ * Wilson score interval of `successes / n` at critical value `z` (default 95%): stays
180
+ * inside [0, 1] and keeps a non-zero width at 0 or n successes, where the Wald interval
181
+ * collapses. `n` not > 0 (including NaN) or a non-finite `successes` is no evidence:
182
+ * [0, 1]. A `z` that is not a finite positive number is a caller error and throws.
183
+ */
184
+ export function wilsonInterval(successes: number, n: number, z: number = Z_95): { low: number; high: number } {
185
+ if (!(z > 0) || !isFiniteNumber(z)) throw new RangeError(`wilsonInterval: z must be a finite positive number, got ${z}`);
186
+ if (!(n > 0) || !isFiniteNumber(successes)) return { low: 0, high: 1 };
187
+ const p = min(1, max(0, successes / n));
188
+ const z2 = z * z;
189
+ const denom = 1 + z2 / n;
190
+ const centre = (p + z2 / (2 * n)) / denom;
191
+ const half = (z * sqrt((p * (1 - p)) / n + z2 / (4 * n * n))) / denom;
192
+ return { low: max(0, centre - half), high: min(1, centre + half) };
193
+ }
194
+
104
195
  function gammaQ(a: number, x: number): number {
105
196
  // Regularized upper incomplete gamma Q(a, x) via continued fraction.
106
197
  let b = x + 1 - a;
@@ -111,15 +202,15 @@ function gammaQ(a: number, x: number): number {
111
202
  const an = -i * (i - a);
112
203
  b += 2;
113
204
  d = an * d + b;
114
- if (Math.abs(d) < FPMIN) d = FPMIN;
205
+ if (abs(d) < FPMIN) d = FPMIN;
115
206
  c = b + an / c;
116
- if (Math.abs(c) < FPMIN) c = FPMIN;
207
+ if (abs(c) < FPMIN) c = FPMIN;
117
208
  d = 1 / d;
118
209
  const del = d * c;
119
210
  h *= del;
120
- if (Math.abs(del - 1) < EPS) break;
211
+ if (abs(del - 1) < EPS) break;
121
212
  }
122
- return Math.exp(-x + a * Math.log(x) - logGamma(a)) * h;
213
+ return exp(-x + a * log(x) - logGamma(a)) * h;
123
214
  }
124
215
 
125
216
  /** Regularized lower incomplete gamma P(a, x). */
@@ -132,9 +223,9 @@ export function regularizedIncompleteGamma(a: number, x: number): number {
132
223
  for (let n = 1; n <= MAX_ITER; n++) {
133
224
  term *= x / (a + n);
134
225
  sum += term;
135
- if (Math.abs(term) < Math.abs(sum) * EPS) break;
226
+ if (abs(term) < abs(sum) * EPS) break;
136
227
  }
137
- return Math.exp(-x + a * Math.log(x) - logGamma(a)) * sum;
228
+ return exp(-x + a * log(x) - logGamma(a)) * sum;
138
229
  }
139
230
  return 1 - gammaQ(a, x);
140
231
  }
@@ -144,7 +235,7 @@ export function gammaQuantile(p: number, shape: number, scale = 1): number {
144
235
  if (p <= 0) return 0;
145
236
  if (p >= 1) return Infinity;
146
237
  let lo = 0;
147
- let hi = Math.max(shape * scale * 2, scale, 1e-9);
238
+ let hi = max(shape * scale * 2, scale, 1e-9);
148
239
  while (regularizedIncompleteGamma(shape, hi / scale) < p) {
149
240
  hi *= 2;
150
241
  if (hi > 1e12) break;
@@ -178,3 +269,22 @@ export function garwoodPoissonInterval(
178
269
  rateHigh: high / (2 * exposure),
179
270
  };
180
271
  }
272
+
273
+ /** The Jeffreys prior Beta(½, ½) of {@link rateInterval}. */
274
+ export const RATE_PRIOR = 0.5;
275
+ /** Mass of {@link rateInterval}: an equal-tailed 90% interval. */
276
+ export const RATE_CREDIBLE_MASS = 0.9;
277
+
278
+ /**
279
+ * The credible interval of an observed rate k of n: the equal-tailed RATE_CREDIBLE_MASS interval of the Jeffreys
280
+ * posterior Beta(½ + k, ½ + n − k), with Brown–Cai–DasGupta's boundary rule (low = 0 at k = 0, high = 1 at k = n) so
281
+ * the interval always holds k/n. THE interval of every rate a graph badge or a hop shows (PRD 38, PRD 41 D3).
282
+ */
283
+ export function rateInterval(k: number, n: number): { low: number; high: number } {
284
+ const post = betaPosterior(RATE_PRIOR, RATE_PRIOR, k, n);
285
+ const tail = (1 - RATE_CREDIBLE_MASS) / 2;
286
+ return {
287
+ low: k <= 0 ? 0 : post.quantile(tail),
288
+ high: k >= n ? 1 : post.quantile(1 - tail),
289
+ };
290
+ }
@@ -5,6 +5,7 @@
5
5
  * calibration shapes the classical catalog does not carry.
6
6
  */
7
7
 
8
+ import { sigmoid } from "./logistic.js";
8
9
  import { createRng, normalDraw, type Rng } from "./prng.js";
9
10
 
10
11
  export interface LaplaceApproximation {
@@ -12,12 +13,6 @@ export interface LaplaceApproximation {
12
13
  covariance: number[][];
13
14
  }
14
15
 
15
- function sigmoid(x: number): number {
16
- if (x >= 0) return 1 / (1 + Math.exp(-x));
17
- const e = Math.exp(x);
18
- return e / (1 + e);
19
- }
20
-
21
16
  function invert2x2(m: number[][]): number[][] {
22
17
  const det = m[0]![0]! * m[1]![1]! - m[0]![1]! * m[1]![0]!;
23
18
  if (Math.abs(det) < 1e-12) {
@@ -2,23 +2,36 @@
2
2
  * The stats module (PRD 41 Part D / D13): the ONE home for the predicted-measure
3
3
  * maths. Pure and deterministic — seeded PRNG, fixed iteration caps, quantized
4
4
  * outputs. It holds only what the memory-engine `ml/classical` catalog lacks and
5
- * imports (never re-implements) those primitives; EWMA and the classical models
6
- * stay in `ml/classical`.
5
+ * imports (never re-implements) those primitives; EWMA, Ledoit–Wolf and the
6
+ * classical models stay in `ml/classical` (Ledoit–Wolf is re-exported here).
7
+ *
8
+ * One deliberate exception: the BINARY logistic head (`logistic.ts` — `sigmoid`,
9
+ * `logisticProbability`, `onlineLogisticStep`) is float64 and engine-free, not the
10
+ * engine's softmax `LogisticModel` (Float32 weights, batch fits). Device code scores a
11
+ * stored head and folds in one outcome at a time; batch fitting (gradient descent or
12
+ * IRLS) stays in the engine.
7
13
  */
8
14
 
9
15
  export { createRng, normalDraw } from "./prng.js";
10
16
  export type { Rng } from "./prng.js";
11
17
 
12
18
  export {
19
+ betaMoments,
13
20
  betaPosterior,
14
21
  gammaQuantile,
15
22
  garwoodPoissonInterval,
16
23
  inverseRegularizedIncompleteBeta,
24
+ RATE_CREDIBLE_MASS,
25
+ RATE_PRIOR,
26
+ rateInterval,
17
27
  regularizedIncompleteBeta,
18
28
  regularizedIncompleteGamma,
29
+ wilsonInterval,
19
30
  } from "./distributions.js";
20
31
  export type { BetaPosterior } from "./distributions.js";
21
32
 
33
+ export { logisticProbability, onlineLogisticStep, sigmoid } from "./logistic.js";
34
+
22
35
  export { fitBayesianLogistic, fitIsotonic, fitPlattScaling } from "./fitting.js";
23
36
  export type { BayesianLogisticOptions, IsotonicFit } from "./fitting.js";
24
37
 
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The PRD 41 D13 consolidation primitives: the ONE stable sigmoid and logistic head
3
+ * (prefetch's online calibration, the difficulty head, the pipeline router), the Wilson
4
+ * interval (replay impact and issue clusters, the canvas proportion card) and the Beta
5
+ * moments (the learned-routing Thompson draw).
6
+ */
7
+
8
+ import { describe, expect, it } from "@jest/globals";
9
+ import {
10
+ betaMoments,
11
+ betaPosterior,
12
+ logisticProbability,
13
+ onlineLogisticStep,
14
+ sigmoid,
15
+ wilsonInterval,
16
+ } from "./index.js";
17
+
18
+ describe("sigmoid", () => {
19
+ it("is ½ at 0, symmetric, and finite in both tails", () => {
20
+ expect(sigmoid(0)).toBe(0.5);
21
+ for (const z of [0.3, 2, 9]) expect(sigmoid(-z)).toBeCloseTo(1 - sigmoid(z), 12);
22
+ expect(sigmoid(-800)).toBe(0);
23
+ expect(sigmoid(800)).toBe(1);
24
+ expect(Number.isNaN(sigmoid(-1e308))).toBe(false);
25
+ });
26
+ });
27
+
28
+ describe("logistic head", () => {
29
+ it("scores σ(b + w·x)", () => {
30
+ expect(logisticProbability([6, 2, 2], -5, [1, 0, 0])).toBeCloseTo(sigmoid(1), 15);
31
+ expect(logisticProbability([1, -1], 0.5, [2, 3])).toBeCloseTo(sigmoid(-0.5), 15);
32
+ });
33
+
34
+ it("one SGD step moves toward the label and leaves its input untouched", () => {
35
+ const weights = [0, 0];
36
+ const x = [1, 0.5];
37
+ const before = logisticProbability(weights, 0, x);
38
+ const up = onlineLogisticStep(weights, 0, x, 1, 0.1);
39
+ expect(logisticProbability(up.weights, up.bias, x)).toBeGreaterThan(before);
40
+ expect(up.weights).toEqual([0.05, 0.025]);
41
+ expect(up.bias).toBeCloseTo(0.05, 15);
42
+ const down = onlineLogisticStep(weights, 0, x, 0, 0.1);
43
+ expect(logisticProbability(down.weights, down.bias, x)).toBeLessThan(before);
44
+ expect(weights).toEqual([0, 0]);
45
+ });
46
+ });
47
+
48
+ describe("wilsonInterval", () => {
49
+ it("matches the textbook 95% interval", () => {
50
+ const { low, high } = wilsonInterval(50, 1_000);
51
+ expect(low).toBeCloseTo(0.0381, 4);
52
+ expect(high).toBeCloseTo(0.0653, 4);
53
+ });
54
+
55
+ it("keeps a width at the boundary and stays in [0, 1]", () => {
56
+ const none = wilsonInterval(0, 40);
57
+ expect(none.low).toBeCloseTo(0, 12);
58
+ expect(none.high).toBeGreaterThan(0.05);
59
+ expect(wilsonInterval(10, 10).high).toBeCloseTo(1, 12);
60
+ });
61
+
62
+ it("no evidence (n ≤ 0 or NaN, or non-finite successes) is [0, 1]", () => {
63
+ expect(wilsonInterval(0, 0)).toEqual({ low: 0, high: 1 });
64
+ expect(wilsonInterval(3, Number.NaN)).toEqual({ low: 0, high: 1 });
65
+ expect(wilsonInterval(Number.NaN, 10)).toEqual({ low: 0, high: 1 });
66
+ expect(wilsonInterval(Number.POSITIVE_INFINITY, 10)).toEqual({ low: 0, high: 1 });
67
+ });
68
+
69
+ it("a z that is not a finite positive number throws", () => {
70
+ for (const z of [0, -1.96, Number.NaN, Number.POSITIVE_INFINITY]) {
71
+ expect(() => wilsonInterval(3, 10, z)).toThrow(RangeError);
72
+ }
73
+ });
74
+
75
+ it("a wider z gives a wider interval", () => {
76
+ const a = wilsonInterval(30, 100);
77
+ const b = wilsonInterval(30, 100, 2.576);
78
+ expect(b.high - b.low).toBeGreaterThan(a.high - a.low);
79
+ });
80
+ });
81
+
82
+ describe("betaMoments", () => {
83
+ it("gives the Beta mean and variance, and the posterior carries them", () => {
84
+ expect(betaMoments(2, 3)).toEqual({ mean: 0.4, variance: 0.04 });
85
+ const post = betaPosterior(1, 1, 1, 3);
86
+ expect(post.mean).toBe(betaMoments(2, 3).mean);
87
+ expect(post.variance).toBe(betaMoments(2, 3).variance);
88
+ });
89
+ });
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The binary logistic head for the stats module (PRD 41 Part D / D13): the ONE
3
+ * numerically stable sigmoid, the probability of a stored head `σ(w·x + b)`, and one
4
+ * online SGD step on the log-loss. Pure: every function returns new values and never
5
+ * mutates its input.
6
+ *
7
+ * Batch fitting stays in memory-engine `ml/classical/logistic.ts` (gradient descent or
8
+ * IRLS, L2, sample and class weights) and the Laplace/Platt fits in `fitting.ts`; this
9
+ * is what a device needs to SCORE a fitted head and fold in one outcome at a time.
10
+ */
11
+
12
+ /**
13
+ * σ(z) = 1 / (1 + e^−z), evaluated so neither tail overflows. The engine's training
14
+ * kernels keep their own (`memory-engine/src/training/cpu_ops.ts` `sigmoid`).
15
+ */
16
+ export function sigmoid(z: number): number {
17
+ if (z >= 0) return 1 / (1 + Math.exp(-z));
18
+ const e = Math.exp(z);
19
+ return e / (1 + e);
20
+ }
21
+
22
+ /**
23
+ * σ(b + Σᵢ wᵢ·xᵢ) over the features of `x` (accumulated in index order from the bias).
24
+ * The caller owns the shape check: a head whose weights do not match its features has
25
+ * no meaningful probability, and what to return then (0, ½, …) is the caller's policy.
26
+ */
27
+ export function logisticProbability(weights: readonly number[], bias: number, x: readonly number[]): number {
28
+ let z = bias;
29
+ for (let i = 0; i < x.length; i++) z += weights[i]! * x[i]!;
30
+ return sigmoid(z);
31
+ }
32
+
33
+ /**
34
+ * One online SGD step on the log-loss for a single labelled example:
35
+ * err = y − σ(w·x + b); wᵢ ← wᵢ + η·err·xᵢ; b ← b + η·err. Returns the new head.
36
+ */
37
+ export function onlineLogisticStep(
38
+ weights: readonly number[],
39
+ bias: number,
40
+ x: readonly number[],
41
+ label: 0 | 1,
42
+ learningRate: number,
43
+ ): { weights: number[]; bias: number } {
44
+ const err = label - logisticProbability(weights, bias, x);
45
+ return {
46
+ weights: weights.map((w, i) => w + learningRate * err * x[i]!),
47
+ bias: bias + learningRate * err,
48
+ };
49
+ }
@@ -2,67 +2,16 @@
2
2
  * Multivariate summaries for the stats module (PRD 41 Part D / D13): Ledoit–Wolf
3
3
  * shrinkage covariance and the population stability index (PSI). Pure and
4
4
  * deterministic.
5
+ *
6
+ * Ledoit–Wolf lives in memory-engine `ml/classical/covariance.ts` (the anomaly
7
+ * composite's Mahalanobis term fits on it) and is re-exported here, never copied. It
8
+ * comes through the engine's light `./ml/classical` subpath, NEVER the engine root:
9
+ * browser bundles import `./stats`, and the root carries WebGPU kernels and training
10
+ * (`src/contract/regression.statsEngineFree.test.ts` holds this).
5
11
  */
6
12
 
7
- export interface CovarianceResult {
8
- /** Column means of the input matrix (rows = observations). */
9
- means: number[];
10
- covariance: number[][];
11
- /** Shrinkage intensity in [0, 1]. */
12
- shrinkage: number;
13
- }
14
-
15
- /**
16
- * Ledoit–Wolf shrunk covariance estimator. `data` is an n×d matrix (rows are
17
- * observations). The optimal shrinkage intensity follows the Ledoit–Wolf formula
18
- * toward the scaled-identity target (tr(S)/d)·I.
19
- */
20
- export function ledoitWolfCovariance(data: readonly (readonly number[])[]): CovarianceResult {
21
- const n = data.length;
22
- const d = data[0]?.length ?? 0;
23
- if (n === 0 || d === 0) return { means: new Array(d).fill(0), covariance: [], shrinkage: 0 };
24
- const means = new Array<number>(d).fill(0);
25
- for (const row of data) for (let j = 0; j < d; j++) means[j]! += row[j]! / n;
26
- const center = data.map((row) => row.map((v, j) => v - means[j]!));
27
- const scale = 1 / n; // MLE denominator, matching the LW derivation
28
- const s: number[][] = [];
29
- for (let i = 0; i < d; i++) {
30
- s.push(new Array<number>(d).fill(0));
31
- for (let j = 0; j < d; j++) {
32
- let acc = 0;
33
- for (let r = 0; r < n; r++) acc += center[r]![i]! * center[r]![j]!;
34
- s[i]![j] = acc * scale;
35
- }
36
- }
37
- const trace = s.reduce((acc, row, i) => acc + row[i]!, 0);
38
- const mu = trace / d;
39
- // Sum of asymptotic variances of the off-diagonal (and diagonal) entries.
40
- let deltaSum = 0;
41
- for (let i = 0; i < d; i++) {
42
- for (let j = 0; j < d; j++) {
43
- let acc = 0;
44
- for (let r = 0; r < n; r++) {
45
- acc += (center[r]![i]! * center[r]![j]! - (i === j ? s[i]![i]! : s[i]![j]!)) ** 2;
46
- }
47
- deltaSum += acc / n;
48
- }
49
- }
50
- deltaSum *= scale * scale;
51
- // Squared distance from S to the target.
52
- let targetDist = 0;
53
- for (let i = 0; i < d; i++) {
54
- for (let j = 0; j < d; j++) {
55
- const target = i === j ? mu : 0;
56
- targetDist += (s[i]![j]! - target) ** 2;
57
- }
58
- }
59
- const beta = Math.min(deltaSum, targetDist);
60
- const shrinkage = targetDist > 0 ? beta / targetDist : 0;
61
- const covariance = s.map((row, i) =>
62
- row.map((v, j) => (1 - shrinkage) * v + (i === j ? shrinkage * mu : 0)),
63
- );
64
- return { means, covariance, shrinkage };
65
- }
13
+ export { ledoitWolfCovariance } from "@seanhogg/builderforce-memory-engine/ml/classical";
14
+ export type { CovarianceResult } from "@seanhogg/builderforce-memory-engine/ml/classical";
66
15
 
67
16
  /**
68
17
  * Population stability index, Σ (aᵢ − eᵢ) ln(aᵢ / eᵢ), over `bins` equal-width bins
@@ -5,7 +5,7 @@
5
5
  * source of randomness.
6
6
  */
7
7
 
8
- import { type Rng } from "./prng.js";
8
+ import { normalDraw, type Rng } from "./prng.js";
9
9
 
10
10
  export interface BetaArm {
11
11
  alpha: number;
@@ -28,7 +28,9 @@ function gammaDraw(shape: number, rng: Rng): number {
28
28
  const d = shape - 1 / 3;
29
29
  const c = 1 / Math.sqrt(9 * d);
30
30
  for (;;) {
31
- const z = normalZ(rng);
31
+ // The module's ONE normal (prng.ts), stateless: a spare cached across calls would
32
+ // leak one caller's draw into the next, and the same seed would not give the same pick.
33
+ const z = normalDraw(rng);
32
34
  const v = Math.pow(1 + c * z, 3);
33
35
  if (v <= 0) continue;
34
36
  const u = rng();
@@ -36,28 +38,6 @@ function gammaDraw(shape: number, rng: Rng): number {
36
38
  }
37
39
  }
38
40
 
39
- /** Standard-normal draw via the polar form of Box–Muller (caches its spare). */
40
- function makeNormalZ() {
41
- let spare: number | null = null;
42
- return (rng: Rng): number => {
43
- if (spare !== null) {
44
- const z = spare;
45
- spare = null;
46
- return z;
47
- }
48
- let u: number, v: number, s: number;
49
- do {
50
- u = rng() * 2 - 1;
51
- v = rng() * 2 - 1;
52
- s = u * u + v * v;
53
- } while (s >= 1 || s === 0);
54
- const mul = Math.sqrt((-2 * Math.log(s)) / s);
55
- spare = v * mul;
56
- return u * mul;
57
- };
58
- }
59
- const normalZ = makeNormalZ();
60
-
61
41
  /**
62
42
  * Sample one arm index by Thompson sampling: draw θᵢ ~ Beta(αᵢ, βᵢ) per arm and
63
43
  * return the argmax. Deterministic under the supplied `rng`.