@seanhogg/builderforce-memory 2026.10.62 → 2026.10.66

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 (177) hide show
  1. package/dist/knowledge/pack/frame.d.ts +12 -3
  2. package/dist/knowledge/pack/frame.d.ts.map +1 -1
  3. package/dist/knowledge/pack/frame.js +18 -4
  4. package/dist/knowledge/pack/frame.js.map +1 -1
  5. package/dist/knowledge/pack/manifest.d.ts +11 -3
  6. package/dist/knowledge/pack/manifest.d.ts.map +1 -1
  7. package/dist/knowledge/pack/manifest.js +26 -12
  8. package/dist/knowledge/pack/manifest.js.map +1 -1
  9. package/dist/knowledge/pack/sections/extr.d.ts.map +1 -1
  10. package/dist/knowledge/pack/sections/extr.js +16 -4
  11. package/dist/knowledge/pack/sections/extr.js.map +1 -1
  12. package/dist/knowledge/pack/sections/extrLists.d.ts +0 -1
  13. package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -1
  14. package/dist/knowledge/pack/sections/extrLists.js +5 -6
  15. package/dist/knowledge/pack/sections/extrLists.js.map +1 -1
  16. package/dist/knowledge/pack/sections/facts.d.ts.map +1 -1
  17. package/dist/knowledge/pack/sections/facts.js +3 -2
  18. package/dist/knowledge/pack/sections/facts.js.map +1 -1
  19. package/dist/knowledge/pack/sections/rows.d.ts.map +1 -1
  20. package/dist/knowledge/pack/sections/rows.js +11 -2
  21. package/dist/knowledge/pack/sections/rows.js.map +1 -1
  22. package/dist/knowledge/pack/strings.d.ts.map +1 -1
  23. package/dist/knowledge/pack/strings.js +6 -1
  24. package/dist/knowledge/pack/strings.js.map +1 -1
  25. package/dist/knowledge/pack/varint.d.ts +14 -0
  26. package/dist/knowledge/pack/varint.d.ts.map +1 -1
  27. package/dist/knowledge/pack/varint.js +32 -1
  28. package/dist/knowledge/pack/varint.js.map +1 -1
  29. package/dist/knowledge/review.d.ts +6 -6
  30. package/dist/knowledge/review.d.ts.map +1 -1
  31. package/dist/knowledge/review.js +56 -329
  32. package/dist/knowledge/review.js.map +1 -1
  33. package/dist/knowledge/reviewAnalyse.d.ts +17 -0
  34. package/dist/knowledge/reviewAnalyse.d.ts.map +1 -0
  35. package/dist/knowledge/reviewAnalyse.js +61 -0
  36. package/dist/knowledge/reviewAnalyse.js.map +1 -0
  37. package/dist/knowledge/reviewApply.d.ts +33 -0
  38. package/dist/knowledge/reviewApply.d.ts.map +1 -0
  39. package/dist/knowledge/reviewApply.js +121 -0
  40. package/dist/knowledge/reviewApply.js.map +1 -0
  41. package/dist/knowledge/reviewContext.d.ts +77 -0
  42. package/dist/knowledge/reviewContext.d.ts.map +1 -0
  43. package/dist/knowledge/reviewContext.js +111 -0
  44. package/dist/knowledge/reviewContext.js.map +1 -0
  45. package/dist/knowledge/reviewFinish.d.ts +9 -0
  46. package/dist/knowledge/reviewFinish.d.ts.map +1 -0
  47. package/dist/knowledge/reviewFinish.js +62 -0
  48. package/dist/knowledge/reviewFinish.js.map +1 -0
  49. package/dist/knowledge/reviewRunModel.d.ts +3 -0
  50. package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
  51. package/dist/knowledge/reviewRunModel.js.map +1 -1
  52. package/dist/knowledge/stores/extractLogWriter.d.ts +16 -3
  53. package/dist/knowledge/stores/extractLogWriter.d.ts.map +1 -1
  54. package/dist/knowledge/stores/extractLogWriter.js +38 -13
  55. package/dist/knowledge/stores/extractLogWriter.js.map +1 -1
  56. package/dist/knowledge/stores/extractRefs.d.ts +68 -0
  57. package/dist/knowledge/stores/extractRefs.d.ts.map +1 -0
  58. package/dist/knowledge/stores/extractRefs.js +168 -0
  59. package/dist/knowledge/stores/extractRefs.js.map +1 -0
  60. package/dist/knowledge/stores/localSnapshotStore.d.ts +5 -0
  61. package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
  62. package/dist/knowledge/stores/localSnapshotStore.js +25 -5
  63. package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
  64. package/dist/knowledge/stores/rowDelta.d.ts +6 -0
  65. package/dist/knowledge/stores/rowDelta.d.ts.map +1 -1
  66. package/dist/knowledge/stores/rowDelta.js.map +1 -1
  67. package/dist/knowledge/stores/rowMemory.d.ts +30 -0
  68. package/dist/knowledge/stores/rowMemory.d.ts.map +1 -1
  69. package/dist/knowledge/stores/rowMemory.js +46 -1
  70. package/dist/knowledge/stores/rowMemory.js.map +1 -1
  71. package/dist/knowledge/stores/rowSync.d.ts.map +1 -1
  72. package/dist/knowledge/stores/rowSync.js +2 -1
  73. package/dist/knowledge/stores/rowSync.js.map +1 -1
  74. package/dist/knowledge/stores/snapshotFormat.d.ts +13 -2
  75. package/dist/knowledge/stores/snapshotFormat.d.ts.map +1 -1
  76. package/dist/knowledge/stores/snapshotFormat.js +22 -9
  77. package/dist/knowledge/stores/snapshotFormat.js.map +1 -1
  78. package/dist/stats/distributions.d.ts +34 -0
  79. package/dist/stats/distributions.d.ts.map +1 -0
  80. package/dist/stats/distributions.js +180 -0
  81. package/dist/stats/distributions.js.map +1 -0
  82. package/dist/stats/estimators.d.ts +53 -0
  83. package/dist/stats/estimators.d.ts.map +1 -0
  84. package/dist/stats/estimators.js +79 -0
  85. package/dist/stats/estimators.js.map +1 -0
  86. package/dist/stats/fitting.d.ts +48 -0
  87. package/dist/stats/fitting.d.ts.map +1 -0
  88. package/dist/stats/fitting.js +209 -0
  89. package/dist/stats/fitting.js.map +1 -0
  90. package/dist/stats/index.d.ts +26 -0
  91. package/dist/stats/index.d.ts.map +1 -0
  92. package/dist/stats/index.js +18 -0
  93. package/dist/stats/index.js.map +1 -0
  94. package/dist/stats/information.d.ts +9 -0
  95. package/dist/stats/information.d.ts.map +1 -0
  96. package/dist/stats/information.js +21 -0
  97. package/dist/stats/information.js.map +1 -0
  98. package/dist/stats/multivariate.d.ts +25 -0
  99. package/dist/stats/multivariate.d.ts.map +1 -0
  100. package/dist/stats/multivariate.js +89 -0
  101. package/dist/stats/multivariate.js.map +1 -0
  102. package/dist/stats/policies.d.ts +19 -0
  103. package/dist/stats/policies.d.ts.map +1 -0
  104. package/dist/stats/policies.js +75 -0
  105. package/dist/stats/policies.js.map +1 -0
  106. package/dist/stats/prng.d.ts +11 -0
  107. package/dist/stats/prng.d.ts.map +1 -0
  108. package/dist/stats/prng.js +41 -0
  109. package/dist/stats/prng.js.map +1 -0
  110. package/dist/stats/scores.d.ts +33 -0
  111. package/dist/stats/scores.d.ts.map +1 -0
  112. package/dist/stats/scores.js +134 -0
  113. package/dist/stats/scores.js.map +1 -0
  114. package/dist/stats/tests.d.ts +48 -0
  115. package/dist/stats/tests.d.ts.map +1 -0
  116. package/dist/stats/tests.js +143 -0
  117. package/dist/stats/tests.js.map +1 -0
  118. package/dist/stats/timeSeries.d.ts +34 -0
  119. package/dist/stats/timeSeries.d.ts.map +1 -0
  120. package/dist/stats/timeSeries.js +71 -0
  121. package/dist/stats/timeSeries.js.map +1 -0
  122. package/dist/working/fold.d.ts +65 -0
  123. package/dist/working/fold.d.ts.map +1 -0
  124. package/dist/working/fold.js +228 -0
  125. package/dist/working/fold.js.map +1 -0
  126. package/dist/working/index.d.ts +3 -0
  127. package/dist/working/index.d.ts.map +1 -1
  128. package/dist/working/index.js +2 -0
  129. package/dist/working/index.js.map +1 -1
  130. package/dist/working/textSummary.d.ts +46 -0
  131. package/dist/working/textSummary.d.ts.map +1 -0
  132. package/dist/working/textSummary.js +142 -0
  133. package/dist/working/textSummary.js.map +1 -0
  134. package/package.json +5 -1
  135. package/src/contract/exports.snapshot.json +48 -1
  136. package/src/contract/regression.extractEviction.test.ts +162 -0
  137. package/src/contract/regression.fixCommits.test.ts +112 -0
  138. package/src/contract/regression.packWire.test.ts +174 -0
  139. package/src/contract/types.contract.test.ts +2 -1
  140. package/src/knowledge/pack/frame.ts +21 -5
  141. package/src/knowledge/pack/manifest.ts +26 -11
  142. package/src/knowledge/pack/sections/extr.ts +14 -4
  143. package/src/knowledge/pack/sections/extrLists.ts +4 -6
  144. package/src/knowledge/pack/sections/facts.ts +3 -2
  145. package/src/knowledge/pack/sections/rows.ts +11 -2
  146. package/src/knowledge/pack/strings.ts +5 -1
  147. package/src/knowledge/pack/varint.ts +33 -1
  148. package/src/knowledge/review.ts +58 -311
  149. package/src/knowledge/reviewAnalyse.ts +59 -0
  150. package/src/knowledge/reviewApply.ts +128 -0
  151. package/src/knowledge/reviewContext.ts +158 -0
  152. package/src/knowledge/reviewFinish.ts +63 -0
  153. package/src/knowledge/reviewRunModel.ts +3 -0
  154. package/src/knowledge/stores/extractLogWriter.ts +36 -12
  155. package/src/knowledge/stores/extractRefs.ts +161 -0
  156. package/src/knowledge/stores/localSnapshotStore.ts +22 -5
  157. package/src/knowledge/stores/rowDelta.ts +6 -0
  158. package/src/knowledge/stores/rowMemory.ts +50 -1
  159. package/src/knowledge/stores/rowSync.ts +2 -1
  160. package/src/knowledge/stores/snapshotFormat.ts +27 -10
  161. package/src/stats/distributions.ts +180 -0
  162. package/src/stats/estimators.ts +101 -0
  163. package/src/stats/fitting.ts +252 -0
  164. package/src/stats/index.ts +59 -0
  165. package/src/stats/information.ts +20 -0
  166. package/src/stats/multivariate.ts +93 -0
  167. package/src/stats/policies.ts +84 -0
  168. package/src/stats/prng.ts +45 -0
  169. package/src/stats/scores.ts +135 -0
  170. package/src/stats/stats.test.ts +294 -0
  171. package/src/stats/tests.ts +164 -0
  172. package/src/stats/timeSeries.ts +92 -0
  173. package/src/working/fold.test.ts +196 -0
  174. package/src/working/fold.ts +252 -0
  175. package/src/working/index.ts +13 -0
  176. package/src/working/textSummary.test.ts +113 -0
  177. package/src/working/textSummary.ts +156 -0
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Multivariate summaries for the stats module (PRD 41 Part D / D13): Ledoit–Wolf
3
+ * shrinkage covariance and the population stability index (PSI). Pure and
4
+ * deterministic.
5
+ */
6
+
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
+ }
66
+
67
+ /**
68
+ * Population stability index, Σ (aᵢ − eᵢ) ln(aᵢ / eᵢ), over `bins` equal-width bins
69
+ * spanning [min, max] of the pooled data. Zero-count bins contribute 0 (the
70
+ * convention PS ≈ 0 uses). PSI above 0.2 signals drift (PRD 41 D12).
71
+ */
72
+ export function psi(actual: readonly number[], expected: readonly number[], bins = 10): number {
73
+ if (!actual.length || !expected.length) return 0;
74
+ const lo = Math.min(...actual, ...expected);
75
+ const hi = Math.max(...actual, ...expected);
76
+ if (hi === lo) return 0;
77
+ const width = (hi - lo) / bins;
78
+ const count = (values: readonly number[]) => {
79
+ const counts = new Array<number>(bins).fill(0);
80
+ for (const v of values) {
81
+ const idx = Math.min(bins - 1, Math.floor((v - lo) / width));
82
+ counts[idx]!++;
83
+ }
84
+ return counts.map((c) => c / values.length);
85
+ };
86
+ const a = count(actual);
87
+ const e = count(expected);
88
+ let sum = 0;
89
+ for (let i = 0; i < bins; i++) {
90
+ if (a[i]! > 0 && e[i]! > 0) sum += (a[i]! - e[i]!) * Math.log(a[i]! / e[i]!);
91
+ }
92
+ return sum;
93
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Policies for the stats module (PRD 41 Part D / D13): Thompson sampling over
3
+ * Beta-bandit arms. Draws are made from the caller-supplied seeded RNG (prng.ts),
4
+ * so a schedule is reproducible under its seed. State-free: the RNG is the only
5
+ * source of randomness.
6
+ */
7
+
8
+ import { type Rng } from "./prng.js";
9
+
10
+ export interface BetaArm {
11
+ alpha: number;
12
+ beta: number;
13
+ }
14
+
15
+ /** Beta draw by the Gamma-ratio method. */
16
+ function betaDraw(alpha: number, beta: number, rng: Rng): number {
17
+ const x = gammaDraw(alpha, rng);
18
+ const y = gammaDraw(beta, rng);
19
+ return x / (x + y);
20
+ }
21
+
22
+ /** Gamma(shape, 1) draw by Marsaglia's method; shape < 1 boosted by a fractional power. */
23
+ function gammaDraw(shape: number, rng: Rng): number {
24
+ if (shape < 1) {
25
+ const u = Math.max(rng(), 1e-12);
26
+ return gammaDraw(shape + 1, rng) * Math.pow(u, 1 / shape);
27
+ }
28
+ const d = shape - 1 / 3;
29
+ const c = 1 / Math.sqrt(9 * d);
30
+ for (;;) {
31
+ const z = normalZ(rng);
32
+ const v = Math.pow(1 + c * z, 3);
33
+ if (v <= 0) continue;
34
+ const u = rng();
35
+ if (Math.log(u) < 0.5 * z * z + d - d * v + d * Math.log(v)) return d * v;
36
+ }
37
+ }
38
+
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
+ /**
62
+ * Sample one arm index by Thompson sampling: draw θᵢ ~ Beta(αᵢ, βᵢ) per arm and
63
+ * return the argmax. Deterministic under the supplied `rng`.
64
+ */
65
+ export function thompsonSample(arms: readonly BetaArm[], rng: Rng): number {
66
+ let best = 0;
67
+ let bestDraw = -1;
68
+ for (let i = 0; i < arms.length; i++) {
69
+ const draw = betaDraw(arms[i]!.alpha, arms[i]!.beta, rng);
70
+ if (draw > bestDraw) {
71
+ bestDraw = draw;
72
+ best = i;
73
+ }
74
+ }
75
+ return best;
76
+ }
77
+
78
+ /** Rank all arms by one Thompson draw each, descending. Deterministic under `rng`. */
79
+ export function thompsonRank(arms: readonly BetaArm[], rng: Rng): number[] {
80
+ const draws = arms.map((arm) => betaDraw(arm.alpha, arm.beta, rng));
81
+ return arms
82
+ .map((_, i) => i)
83
+ .sort((a, b) => draws[b]! - draws[a]! || a - b);
84
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Deterministic seeded PRNG for the stats module (PRD 41 Part D, D13/B8): every
3
+ * stochastic routine here draws from THIS generator, seeded by the caller, so the
4
+ * same inputs give byte-identical outputs on any machine. Algorithm: xoshiro128**.
5
+ */
6
+
7
+ export type Rng = () => number;
8
+
9
+ /** SplitMix32-style seed expansion to four uint32 words. */
10
+ function seedWords(seed: number): [number, number, number, number] {
11
+ let s = seed >>> 0;
12
+ const next = () => {
13
+ s = (s + 0x9e3779b9) >>> 0;
14
+ let z = s;
15
+ z = Math.imul(z ^ (z >>> 16), 0x21f0aaad) >>> 0;
16
+ z = Math.imul(z ^ (z >>> 15), 0x735a2d97) >>> 0;
17
+ z = (z ^ (z >>> 15)) >>> 0;
18
+ return z;
19
+ };
20
+ return [next(), next(), next(), next()];
21
+ }
22
+
23
+ /** A deterministic RNG in [0, 1), seeded once. `seed = 0` is a valid seed. */
24
+ export function createRng(seed: number): Rng {
25
+ let [a, b, c, d] = seedWords(seed);
26
+ return () => {
27
+ const result = (Math.imul(b, 5) << 7 | Math.imul(b, 5) >>> 25) >>> 0;
28
+ const out = ((result * 9) >>> 0) / 4294967296;
29
+ const t = (b << 9 | b >>> 23) >>> 0;
30
+ c = (c ^ a) >>> 0;
31
+ d = (d ^ b) >>> 0;
32
+ b = (b ^ c) >>> 0;
33
+ a = (a ^ d) >>> 0;
34
+ c = (c ^ t) >>> 0;
35
+ d = ((d << 11) | (d >>> 21)) >>> 0;
36
+ return out;
37
+ };
38
+ }
39
+
40
+ /** Box–Muller standard-normal draw from a uniform RNG (deterministic under seed). */
41
+ export function normalDraw(rng: Rng): number {
42
+ const u1 = Math.max(rng(), Number.EPSILON);
43
+ const u2 = rng();
44
+ return Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
45
+ }
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Scoring functions for the stats module (PRD 41 Part D / D13): Brier, expected
3
+ * calibration error, PR-AUC, NDCG, Popt and effort-aware recall. All are pure,
4
+ * deterministic orderings on their inputs.
5
+ */
6
+
7
+ /** Brier score: mean squared error of probabilistic predictions. Lower is better. */
8
+ export function brierScore(probabilities: readonly number[], outcomes: readonly number[]): number {
9
+ const n = Math.min(probabilities.length, outcomes.length);
10
+ if (n === 0) return 0;
11
+ let sum = 0;
12
+ for (let i = 0; i < n; i++) sum += (probabilities[i]! - outcomes[i]!) ** 2;
13
+ return sum / n;
14
+ }
15
+
16
+ /**
17
+ * Expected calibration error over `bins` equal-width probability bins: the weighted
18
+ * mean of |accuracy − confidence| per bin.
19
+ */
20
+ export function expectedCalibrationError(
21
+ probabilities: readonly number[],
22
+ outcomes: readonly number[],
23
+ bins = 10,
24
+ ): number {
25
+ const n = Math.min(probabilities.length, outcomes.length);
26
+ if (n === 0) return 0;
27
+ let ece = 0;
28
+ for (let b = 0; b < bins; b++) {
29
+ const lo = b / bins;
30
+ const hi = (b + 1) / bins;
31
+ let count = 0;
32
+ let confSum = 0;
33
+ let accSum = 0;
34
+ for (let i = 0; i < n; i++) {
35
+ const p = probabilities[i]!;
36
+ if (p >= lo && (p < hi || (b === bins - 1 && p === 1))) {
37
+ count++;
38
+ confSum += p;
39
+ accSum += outcomes[i]!;
40
+ }
41
+ }
42
+ if (count > 0) {
43
+ ece += (count / n) * Math.abs(accSum / count - confSum / count);
44
+ }
45
+ }
46
+ return ece;
47
+ }
48
+
49
+ /** Area under the precision–recall curve (trapezoid over the full recall range). */
50
+ export function prAuc(scores: readonly number[], labels: readonly number[]): number {
51
+ const n = Math.min(scores.length, labels.length);
52
+ if (n === 0) return 0;
53
+ const order = Array.from({ length: n }, (_, i) => i).sort((a, b) => scores[b]! - scores[a]!);
54
+ const totalPos = labels.reduce((a, _, i) => a + (i < n && labels[i] === 1 ? 1 : 0), 0);
55
+ if (totalPos === 0) return 0;
56
+ let tp = 0;
57
+ let fp = 0;
58
+ let prevRecall = 0;
59
+ let prevPrecision = 1;
60
+ let auc = 0;
61
+ for (const i of order) {
62
+ if (labels[i] === 1) tp++;
63
+ else fp++;
64
+ const recall = tp / totalPos;
65
+ const precision = tp / (tp + fp);
66
+ auc += (recall - prevRecall) * ((precision + prevPrecision) / 2);
67
+ prevRecall = recall;
68
+ prevPrecision = precision;
69
+ }
70
+ return auc;
71
+ }
72
+
73
+ /**
74
+ * NDCG@k from graded relevance, with the log2 discount (position 1 = 1). The ideal
75
+ * DCG orders by relevance descending.
76
+ */
77
+ export function ndcgAtK(relevances: readonly number[], k: number): number {
78
+ const take = relevances.slice(0, k);
79
+ const dcg = take.reduce((acc, rel, i) => acc + rel / Math.log2(i + 2), 0);
80
+ const ideal = [...relevances].sort((a, b) => b - a).slice(0, k)
81
+ .reduce((acc, rel, i) => acc + rel / Math.log2(i + 2), 0);
82
+ return ideal > 0 ? dcg / ideal : 0;
83
+ }
84
+
85
+ /**
86
+ * Popt (performance optimum): the area under the effort–accuracy curve achieved in
87
+ * the given order, normalized by the area of the optimal ordering (items sorted by
88
+ * score descending). `efforts` are per-item costs, `scores` are per-item values.
89
+ * Returns a value in (0, 1], 1 for the optimal order.
90
+ */
91
+ export function popt(efforts: readonly number[], scores: readonly number[]): number {
92
+ const n = Math.min(efforts.length, scores.length);
93
+ if (n === 0) return 0;
94
+ const area = (order: readonly number[]) => {
95
+ let acc = 0;
96
+ let cumEffort = 0;
97
+ let cumScore = 0;
98
+ let prevScore = 0;
99
+ for (const i of order) {
100
+ cumEffort += efforts[i]!;
101
+ cumScore += scores[i]!;
102
+ acc += efforts[i]! * (cumScore + prevScore) / 2;
103
+ prevScore = cumScore;
104
+ }
105
+ void cumEffort;
106
+ return acc;
107
+ };
108
+ const optimal = area(scores.map((_, i) => i).sort((a, b) => scores[b]! - scores[a]!));
109
+ if (optimal <= 0) return 0;
110
+ return area(scores.map((_, i) => i)) / optimal;
111
+ }
112
+
113
+ /**
114
+ * Effort-aware recall: the share of the target found after spending `effortBudget`
115
+ * fraction of the total effort, where items are examined in the given order.
116
+ * `efforts` are per-item costs.
117
+ */
118
+ export function effortAwareRecall(
119
+ relevant: readonly boolean[],
120
+ efforts: readonly number[],
121
+ effortBudget: number,
122
+ ): number {
123
+ const totalRelevant = relevant.filter(Boolean).length;
124
+ if (totalRelevant === 0) return 0;
125
+ const totalEffort = efforts.reduce((a, b) => a + b, 0);
126
+ const budget = totalEffort * effortBudget;
127
+ let spent = 0;
128
+ let found = 0;
129
+ for (let i = 0; i < relevant.length; i++) {
130
+ if (spent + efforts[i]! > budget) break;
131
+ spent += efforts[i]!;
132
+ if (relevant[i]) found++;
133
+ }
134
+ return found / totalRelevant;
135
+ }
@@ -0,0 +1,294 @@
1
+ /**
2
+ * Tests for the stats module (PRD 41 Part D / D13). The done-checks these cover:
3
+ * - Chapman estimate against textbook values; m < 3 style degenerate inputs give
4
+ * `insufficient-data` (no recaptures).
5
+ * - Rule precision shapes (Beta posterior quantiles) and calibration (ECE, Brier).
6
+ * - The SPRT stops early on a fixture with a 20% regression and runs to the
7
+ * maximum on a no-change fixture.
8
+ * - Determinism: the same seed gives byte-identical draws and schedules.
9
+ */
10
+
11
+ import { describe, expect, it } from "@jest/globals";
12
+ import {
13
+ bayesianOnlineChangePoint,
14
+ betaPosterior,
15
+ brierScore,
16
+ chapmanEstimate,
17
+ createRng,
18
+ cusum,
19
+ effortAwareRecall,
20
+ entropyOfCounts,
21
+ expectedCalibrationError,
22
+ fitBayesianLogistic,
23
+ fitIsotonic,
24
+ fitPlattScaling,
25
+ gammaPoissonPosterior,
26
+ gammaQuantile,
27
+ garwoodPoissonInterval,
28
+ goelOkumotoMLE,
29
+ kaplanMeier,
30
+ ledoitWolfCovariance,
31
+ lincolnPetersenEstimate,
32
+ ndcgAtK,
33
+ pairedBootstrapCi,
34
+ popt,
35
+ prAuc,
36
+ psi,
37
+ shannonEntropy,
38
+ signTestSprt,
39
+ thompsonRank,
40
+ thompsonSample,
41
+ wilcoxonSignedRank,
42
+ } from "./index.js";
43
+
44
+ describe("prng", () => {
45
+ it("is deterministic under its seed", () => {
46
+ const a = createRng(42);
47
+ const b = createRng(42);
48
+ const seqA = Array.from({ length: 8 }, () => a());
49
+ const seqB = Array.from({ length: 8 }, () => b());
50
+ expect(seqA).toEqual(seqB);
51
+ expect(seqA.every((v) => v >= 0 && v < 1)).toBe(true);
52
+ });
53
+
54
+ it("differs across seeds", () => {
55
+ const a = createRng(1);
56
+ const b = createRng(2);
57
+ expect(a()).not.toEqual(b());
58
+ });
59
+ });
60
+
61
+ describe("distributions", () => {
62
+ it("beta posterior mean and quantiles bracket sensibly", () => {
63
+ const post = betaPosterior(1, 1, 30, 100); // observed 30/100
64
+ expect(post.mean).toBeCloseTo(31 / 102, 5);
65
+ const lo = post.quantile(0.025);
66
+ const hi = post.quantile(0.975);
67
+ expect(lo).toBeGreaterThan(0);
68
+ expect(hi).toBeLessThan(1);
69
+ expect(lo).toBeLessThan(post.mean);
70
+ expect(hi).toBeGreaterThan(post.mean);
71
+ });
72
+
73
+ it("gamma quantile inverts the CDF", () => {
74
+ // median of Gamma(2, 1) ≈ 1.678
75
+ expect(gammaQuantile(0.5, 2, 1)).toBeCloseTo(1.678, 2);
76
+ expect(gammaQuantile(0, 2)).toBe(0);
77
+ });
78
+
79
+ it("garwood interval contains the point estimate and handles zero", () => {
80
+ const interval = garwoodPoissonInterval(10, 1);
81
+ expect(interval.low).toBeLessThan(10);
82
+ expect(interval.high).toBeGreaterThan(10);
83
+ const zero = garwoodPoissonInterval(0, 1);
84
+ expect(zero.low).toBe(0);
85
+ expect(zero.rateLow).toBe(0);
86
+ });
87
+ });
88
+
89
+ describe("fitting", () => {
90
+ it("bayesian logistic recovers a monotone relationship", () => {
91
+ const xs = [-3, -2, -1.5, -1, 0, 1, 1.5, 2, 3, 3.5];
92
+ const ys = [0, 0, 0, 1, 0, 1, 1, 1, 1, 1];
93
+ const fit = fitBayesianLogistic(xs, ys);
94
+ expect(fit.predict(-3)).toBeLessThan(fit.predict(0));
95
+ expect(fit.predict(0)).toBeLessThan(fit.predict(3));
96
+ expect(fit.slope).toBeGreaterThan(0);
97
+ });
98
+
99
+ it("platt scaling maps low scores low and high scores high", () => {
100
+ const scores = [-2, -1, -0.5, 0.5, 1, 2];
101
+ const labels = [0, 0, 0, 1, 1, 1];
102
+ const platt = fitPlattScaling(scores, labels);
103
+ expect(platt.predict(-2)).toBeLessThan(0.2);
104
+ expect(platt.predict(2)).toBeGreaterThan(0.8);
105
+ });
106
+
107
+ it("isotonic regression is monotone non-decreasing", () => {
108
+ const xs = [1, 2, 3, 4, 5];
109
+ const ys = [0.1, 0.4, 0.2, 0.9, 0.8]; // a dip and a peak to pool
110
+ const iso = fitIsotonic(xs, ys);
111
+ let prev = -Infinity;
112
+ for (const x of xs) {
113
+ const v = iso.predict(x);
114
+ expect(v).toBeGreaterThanOrEqual(prev - 1e-12);
115
+ prev = v;
116
+ }
117
+ });
118
+ });
119
+
120
+ describe("statistical tests", () => {
121
+ it("wilcoxon signed-rank detects a consistent shift", () => {
122
+ const before = Array.from({ length: 12 }, (_, i) => 100 + i * 7);
123
+ const after = before.map((v) => v + 5);
124
+ const result = wilcoxonSignedRank(before, after);
125
+ expect(result.n).toBe(12);
126
+ expect(result.pValue).toBeLessThan(0.01);
127
+ expect(result.hodgesLehmann).toBeCloseTo(5, 5);
128
+ });
129
+
130
+ it("wilcoxon on a zero shift does not reject", () => {
131
+ const values = Array.from({ length: 10 }, (_, i) => 50 + (i % 3));
132
+ const result = wilcoxonSignedRank(values, [...values]);
133
+ expect(result.n).toBe(0);
134
+ expect(result.pValue).toBe(1);
135
+ });
136
+
137
+ it("paired bootstrap CI is deterministic under its seed and contains the estimate", () => {
138
+ const before = [10, 12, 11, 13, 15, 9, 14, 10];
139
+ const after = [11, 13, 12, 14, 16, 10, 15, 11];
140
+ const a = pairedBootstrapCi(before, after, { seed: 7 });
141
+ const b = pairedBootstrapCi(before, after, { seed: 7 });
142
+ expect(a).toEqual(b);
143
+ expect(a.low).toBeLessThanOrEqual(a.estimate);
144
+ expect(a.high).toBeGreaterThanOrEqual(a.estimate);
145
+ });
146
+
147
+ it("SPRT stops early on a clear regression and continues on no change", () => {
148
+ const regression = Array.from({ length: 40 }, () => [1, 1.25] as const); // 20%+ slower
149
+ const stop = signTestSprt(regression, { p0: 0.5, p1: 0.7, alpha: 0.05, beta: 0.1 });
150
+ expect(stop.decision).toBe("reject-null");
151
+ expect(stop.observations).toBeLessThan(40);
152
+
153
+ // No-change fixture: 3 improvements per 2 regressions keeps the cumulative
154
+ // LLR wandering inside the boundaries, so the test runs to its maximum.
155
+ const none: ReadonlyArray<readonly [number, number]> = Array.from(
156
+ { length: 12 },
157
+ () => [[1, 1.05], [1, 1.02], [1, 0.98], [1, 1.01], [1, 0.97]] as const,
158
+ ).flat();
159
+ const run = signTestSprt(none, { p0: 0.5, p1: 0.7, alpha: 0.05, beta: 0.1 });
160
+ expect(run.decision).toBe("continue");
161
+ expect(run.observations).toBe(60);
162
+ });
163
+ });
164
+
165
+ describe("time series", () => {
166
+ it("cusum alarms after a sustained shift", () => {
167
+ const values = [...Array.from({ length: 30 }, () => 0), ...Array.from({ length: 30 }, () => 2.5)];
168
+ const result = cusum(values, 0, { sigma: 1, threshold: 5 });
169
+ expect(result.alarmIndex).toBeGreaterThanOrEqual(30);
170
+ expect(result.alarmIndex).toBeLessThan(45);
171
+ });
172
+
173
+ it("bayesian change point flags the shift index", () => {
174
+ const values = [...Array.from({ length: 40 }, () => 0), ...Array.from({ length: 40 }, () => 3)];
175
+ const result = bayesianOnlineChangePoint(values, { hazard: 0.05 });
176
+ expect(result.currentRunLength).toBeGreaterThanOrEqual(0);
177
+ // The change-point probability near the shift should exceed the background.
178
+ const nearShift = result.changePointProbabilities[41]!;
179
+ const background = result.changePointProbabilities[10]!;
180
+ expect(nearShift).toBeGreaterThan(background);
181
+ });
182
+ });
183
+
184
+ describe("multivariate", () => {
185
+ it("ledoit-wolf covariance recovers the diagonal of a near-identity", () => {
186
+ const rng = createRng(11);
187
+ const data = Array.from({ length: 200 }, () => [rng() < 0.5 ? 0 : 1, rng() < 0.5 ? 0 : 1]);
188
+ const { covariance, shrinkage } = ledoitWolfCovariance(data);
189
+ expect(shrinkage).toBeGreaterThanOrEqual(0);
190
+ expect(shrinkage).toBeLessThanOrEqual(1);
191
+ expect(covariance[0]![0]!).toBeGreaterThan(0);
192
+ });
193
+
194
+ it("psi is zero for identical distributions and positive for drift", () => {
195
+ const a = Array.from({ length: 500 }, (_, i) => i / 500);
196
+ expect(psi(a, a, 10)).toBeCloseTo(0, 6);
197
+ const drifted = a.map((v) => v * 0.5 + 0.5);
198
+ expect(psi(a, drifted, 10)).toBeGreaterThan(0.2);
199
+ });
200
+ });
201
+
202
+ describe("information", () => {
203
+ it("entropy is maximal for uniform and zero for a point mass", () => {
204
+ expect(shannonEntropy([1])).toBeCloseTo(0, 10);
205
+ expect(shannonEntropy([0.5, 0.5])).toBeCloseTo(Math.log(2), 10);
206
+ expect(entropyOfCounts([2, 2, 2, 2])).toBeCloseTo(Math.log(4), 10);
207
+ });
208
+ });
209
+
210
+ describe("estimators", () => {
211
+ it("chapman estimate matches the textbook value; no recaptures is insufficient", () => {
212
+ // Textbook: m = 20, c = 15, r = 5 → n̂ = (21·16)/6 − 1 = 55
213
+ const estimate = chapmanEstimate(20, 15, 5);
214
+ expect(estimate).toEqual({ estimate: 55 });
215
+ expect(chapmanEstimate(20, 15, 0)).toEqual({ status: "insufficient-data" });
216
+ expect(lincolnPetersenEstimate(20, 15, 5)).toEqual({ estimate: 60 });
217
+ });
218
+
219
+ it("kaplan-meier drops at event times and honors censoring", () => {
220
+ const km = kaplanMeier([
221
+ { time: 1, event: 1 },
222
+ { time: 2, event: 0 },
223
+ { time: 3, event: 1 },
224
+ { time: 4, event: 0 },
225
+ ]);
226
+ expect(km.curve[0]!.survival).toBeCloseTo(0.75, 6);
227
+ expect(km.survival).toBeCloseTo(0.75 * (1 - 1 / 2), 6);
228
+ expect(km.variance).toBeGreaterThanOrEqual(0);
229
+ });
230
+
231
+ it("goel-okumoto MLE needs at least two times", () => {
232
+ expect(goelOkumotoMLE([1])).toEqual({ status: "insufficient-data" });
233
+ const fit = goelOkumotoMLE([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
234
+ if (fit.status === "insufficient-data") throw new Error("expected a fit");
235
+ expect(fit.a).toBeGreaterThan(0);
236
+ expect(fit.b).toBeGreaterThan(0);
237
+ });
238
+
239
+ it("gamma-poisson posterior mean sits between prior and data at small n", () => {
240
+ const prior = gammaPoissonPosterior(2, 4, 0, 0); // Gamma(2, 4), mean 0.5
241
+ const updated = gammaPoissonPosterior(2, 4, 2, 1); // Gamma(4, 5), mean 0.8
242
+ expect(prior.mean).toBeCloseTo(0.5, 6);
243
+ expect(updated.mean).toBeGreaterThan(prior.mean);
244
+ expect(updated.variance).toBeGreaterThan(0);
245
+ });
246
+ });
247
+
248
+ describe("scores", () => {
249
+ it("brier and ECE penalize miscalibration", () => {
250
+ expect(brierScore([1, 1, 1, 1], [1, 1, 1, 1])).toBeCloseTo(0, 10);
251
+ expect(brierScore([1, 0], [0, 1])).toBeCloseTo(1, 10);
252
+ expect(expectedCalibrationError([1, 1, 1, 1], [1, 1, 1, 1])).toBeCloseTo(0, 10);
253
+ expect(expectedCalibrationError([0.9, 0.9, 0.1, 0.1], [0, 0, 1, 1])).toBeGreaterThan(0.7);
254
+ });
255
+
256
+ it("pr-auc is 1 for a perfect ranking and ndcg penalizes bad order", () => {
257
+ expect(prAuc([0.9, 0.8, 0.1, 0.05], [1, 1, 0, 0])).toBeCloseTo(1, 6);
258
+ expect(ndcgAtK([3, 2, 1], 3)).toBeCloseTo(1, 6);
259
+ expect(ndcgAtK([1, 2, 3], 3)).toBeLessThan(1);
260
+ });
261
+
262
+ it("popt and effort-aware recall reward good ordering", () => {
263
+ const efforts = [0.1, 0.2, 0.3, 0.4];
264
+ const goodOrder = [0.9, 0.8, 0.2, 0.1];
265
+ expect(popt(efforts, goodOrder)).toBeGreaterThan(0.5);
266
+ expect(
267
+ effortAwareRecall([true, true, false, false], efforts, 0.5),
268
+ ).toBeCloseTo(1, 6);
269
+ });
270
+ });
271
+
272
+ describe("policies", () => {
273
+ it("thompson sampling favors the better arm and is deterministic under seed", () => {
274
+ const arms = [
275
+ { alpha: 30, beta: 10 }, // ~75%
276
+ { alpha: 10, beta: 30 }, // ~25%
277
+ ];
278
+ const picksA = Array.from({ length: 200 }, () => thompsonSample(arms, createRng(99)));
279
+ const picksB = Array.from({ length: 200 }, () => thompsonSample(arms, createRng(99)));
280
+ expect(picksA).toEqual(picksB);
281
+ const betterPicks = picksA.filter((i) => i === 0).length;
282
+ expect(betterPicks).toBeGreaterThan(150);
283
+ });
284
+
285
+ it("thompson rank is a permutation of all arms", () => {
286
+ const arms = [
287
+ { alpha: 5, beta: 5 },
288
+ { alpha: 20, beta: 5 },
289
+ { alpha: 5, beta: 20 },
290
+ ];
291
+ const rank = thompsonRank(arms, createRng(3));
292
+ expect([...rank].sort()).toEqual([0, 1, 2]);
293
+ });
294
+ });