@seanhogg/builderforce-memory 2026.10.72 → 2026.10.74
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.
- package/dist/knowledge/index.d.ts +1 -1
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/model.d.ts +17 -0
- package/dist/knowledge/model.d.ts.map +1 -1
- package/dist/knowledge/pack/sections/index.d.ts +4 -1
- package/dist/knowledge/pack/sections/index.d.ts.map +1 -1
- package/dist/knowledge/pack/sections/index.js +7 -3
- package/dist/knowledge/pack/sections/index.js.map +1 -1
- package/dist/knowledge/pack/sections/rows.d.ts +9 -0
- package/dist/knowledge/pack/sections/rows.d.ts.map +1 -1
- package/dist/knowledge/pack/sections/rows.js +46 -1
- package/dist/knowledge/pack/sections/rows.js.map +1 -1
- package/dist/knowledge/reviewFinish.d.ts.map +1 -1
- package/dist/knowledge/reviewFinish.js +4 -1
- package/dist/knowledge/reviewFinish.js.map +1 -1
- package/dist/knowledge/reviewModel.d.ts +6 -1
- package/dist/knowledge/reviewModel.d.ts.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.js +5 -0
- package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
- package/dist/stats/distributions.d.ts +6 -0
- package/dist/stats/distributions.d.ts.map +1 -1
- package/dist/stats/distributions.js +10 -0
- package/dist/stats/distributions.js.map +1 -1
- package/dist/stats/index.d.ts +1 -1
- package/dist/stats/index.d.ts.map +1 -1
- package/dist/stats/tests.d.ts +50 -7
- package/dist/stats/tests.d.ts.map +1 -1
- package/dist/stats/tests.js +241 -64
- package/dist/stats/tests.js.map +1 -1
- package/package.json +1 -1
- package/src/contract/regression.scopeMeasured.test.ts +121 -0
- package/src/contract/regression.wilcoxon.test.ts +180 -0
- package/src/contract/types.contract.test.ts +7 -0
- package/src/knowledge/index.ts +1 -1
- package/src/knowledge/model.ts +18 -0
- package/src/knowledge/pack/pack.testkit.test-util.ts +4 -1
- package/src/knowledge/pack/sections/index.ts +7 -3
- package/src/knowledge/pack/sections/rows.ts +39 -1
- package/src/knowledge/reviewFinish.ts +4 -1
- package/src/knowledge/reviewModel.ts +6 -1
- package/src/knowledge/stores/localSnapshotStore.ts +4 -0
- package/src/stats/distributions.ts +10 -0
- package/src/stats/index.ts +1 -1
- package/src/stats/tests.ts +238 -64
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/contract/regression.scopeMeasured.test.ts — `ScopeRecord.measured` (PRD 41 §C9): what a review was measured with is
|
|
3
|
+
* recorded WHEN THE REVIEW RUNS and carried by the BFKP pack in its own MEAS section, never re-derived when the pack is
|
|
4
|
+
* built. Before, a host stated its versions at pack-build time, so a review queued offline across an upgrade was stored
|
|
5
|
+
* with the newer versions and compared as "the same" against a review it was not measured like.
|
|
6
|
+
*
|
|
7
|
+
* Compatibility, both directions:
|
|
8
|
+
* - BACKWARD: a pack without MEAS (every pack written before this release) decodes with no `measured` — unknown;
|
|
9
|
+
* - FORWARD: MEAS is a new tag, so a reader of before this release skips it and decodes the same scope, unmeasured.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { readFrame, writeFrame, writeSection } from '../knowledge/pack/frame.js';
|
|
13
|
+
import { TAG } from '../knowledge/pack/sections/index.js';
|
|
14
|
+
import { ByteReader, ByteWriter } from '../knowledge/pack/varint.js';
|
|
15
|
+
import { decodePack, encodePack, PackFormatError, ZERO_DIGEST, type Pack } from '../knowledge/pack/index.js';
|
|
16
|
+
import type { MeasuredWith } from '../knowledge/index.js';
|
|
17
|
+
import { reviewDirectory } from '../knowledge/review.js';
|
|
18
|
+
import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
|
|
19
|
+
import { args, FILES, memSource, memStore, ROOT } from '../knowledge/testkit.test-util.js';
|
|
20
|
+
|
|
21
|
+
const HEAD = { rootId: ROOT, baseGeneration: 0, targetDigest: ZERO_DIGEST };
|
|
22
|
+
const V5: MeasuredWith = { extractorVersion: '5', toolVersions: { knip: '5.30.0', jscpd: '4.0.5' } };
|
|
23
|
+
const V6: MeasuredWith = { extractorVersion: '6', toolVersions: { knip: '5.31.0', jscpd: '4.0.5' } };
|
|
24
|
+
const scoped = (measured?: MeasuredWith): Pack => ({
|
|
25
|
+
...HEAD, scope: { rootId: ROOT, title: 'R', packs: ['code'], lastDigest: 'abcdef12', ...(measured ? { measured } : {}) },
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
function sectionsOf(bytes: Uint8Array): Map<number, Uint8Array> {
|
|
29
|
+
const r = new ByteReader(readFrame(bytes).stored);
|
|
30
|
+
const out = new Map<number, Uint8Array>();
|
|
31
|
+
while (!r.done) { const tag = r.u8(); out.set(tag, r.bytes(r.varint())); }
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
function frameOf(sections: Map<number, Uint8Array>): Uint8Array {
|
|
35
|
+
const body = new ByteWriter();
|
|
36
|
+
for (const [tag, b] of sections) writeSection(body, tag, b);
|
|
37
|
+
const plain = body.finish();
|
|
38
|
+
return writeFrame({ flags: 0, ...HEAD }, plain, plain);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
describe('regression: a review is stored with the versions it was measured with (PRD 41 §C9)', () => {
|
|
42
|
+
it('regression: the review records `measured` on its scope when it runs, and a pack carries THAT record — not the versions of the host that later syncs it', async () => {
|
|
43
|
+
const store = memStore();
|
|
44
|
+
const manifest = new InMemoryIngestManifest();
|
|
45
|
+
await reviewDirectory(args(memSource(FILES), store, manifest, { measured: V5 }));
|
|
46
|
+
const [scope] = await store.scopes();
|
|
47
|
+
expect(scope).toMatchObject({ rootId: ROOT, lastDigest: expect.any(String), measured: V5 });
|
|
48
|
+
|
|
49
|
+
// The host upgraded while the review sat in its queue: the pack still says what the review was measured with.
|
|
50
|
+
const back = await decodePack(await encodePack({ ...HEAD, scope: scope! }));
|
|
51
|
+
expect(back.scope!.measured).toEqual(V5);
|
|
52
|
+
|
|
53
|
+
// A later review that states nothing moves the digest: the old versions do not describe it (unknown, never V5).
|
|
54
|
+
await reviewDirectory(args(memSource({ ...FILES, 'd.md': '# D\ndelta\n' }), store, manifest));
|
|
55
|
+
const [again] = await store.scopes();
|
|
56
|
+
expect(again!.lastDigest).not.toBe(scope!.lastDigest);
|
|
57
|
+
expect(again).not.toHaveProperty('measured');
|
|
58
|
+
|
|
59
|
+
// And one that states V6 records V6.
|
|
60
|
+
await reviewDirectory(args(memSource(FILES), store, manifest, { measured: V6 }));
|
|
61
|
+
expect((await store.scopes())[0]!.measured).toEqual(V6);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it('the store: a digest write replaces `measured` (even the same digest), a write without a digest keeps it', async () => {
|
|
65
|
+
const store = memStore();
|
|
66
|
+
const base = { rootId: ROOT, title: 'R', packs: ['code'] };
|
|
67
|
+
const scope = async () => (await store.scopes())[0]!;
|
|
68
|
+
await store.write({ scope: { ...base, lastDigest: 'd1', measured: V5 }, facts: [], relations: [] });
|
|
69
|
+
await store.write({ scope: base, facts: [], relations: [] }); // mid-run / aborted: no digest
|
|
70
|
+
expect((await scope()).measured).toEqual(V5);
|
|
71
|
+
await store.write({ scope: { ...base, lastDigest: 'd1' }, facts: [], relations: [] }); // re-review, same digest, unmeasured
|
|
72
|
+
expect(await scope()).not.toHaveProperty('measured');
|
|
73
|
+
await store.write({ scope: { ...base, lastDigest: 'd2', measured: V6 }, facts: [], relations: [] });
|
|
74
|
+
expect((await scope()).measured).toEqual(V6);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it('encode refuses a `measured` its own decoder would refuse (an unvalidated JSON snapshot)', async () => {
|
|
78
|
+
const bad = [
|
|
79
|
+
{ extractorVersion: 5, toolVersions: {} },
|
|
80
|
+
{ extractorVersion: '5', toolVersions: { knip: 5 } },
|
|
81
|
+
{ extractorVersion: '5', toolVersions: JSON.parse('{"__proto__":"x"}') },
|
|
82
|
+
] as unknown as MeasuredWith[];
|
|
83
|
+
for (const m of bad) await expect(encodePack(scoped(m))).rejects.toBeInstanceOf(PackFormatError);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('encode → decode keeps `measured`, deflated or plain, and re-encodes to the same bytes whatever the tool order', async () => {
|
|
87
|
+
const reordered: MeasuredWith = { extractorVersion: '5', toolVersions: { jscpd: '4.0.5', knip: '5.30.0' } };
|
|
88
|
+
for (const deflate of [true, false]) {
|
|
89
|
+
const bytes = await encodePack(scoped(V5), { deflate });
|
|
90
|
+
const back = await decodePack(bytes);
|
|
91
|
+
expect(back.scope!.measured).toEqual(V5);
|
|
92
|
+
expect(Buffer.from(await encodePack(scoped(reordered), { deflate })).equals(Buffer.from(bytes))).toBe(true);
|
|
93
|
+
}
|
|
94
|
+
expect((await decodePack(await encodePack(scoped({ extractorVersion: '5', toolVersions: {} })))).scope!.measured).toEqual({ extractorVersion: '5', toolVersions: {} });
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('BACKWARD: a pack without MEAS decodes with no `measured` (unknown), and writes no MEAS section', async () => {
|
|
98
|
+
const bytes = await encodePack(scoped(), { deflate: false });
|
|
99
|
+
expect(sectionsOf(bytes).has(TAG.MEAS)).toBe(false);
|
|
100
|
+
expect((await decodePack(bytes)).scope).not.toHaveProperty('measured');
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it('FORWARD: SCOPE is unchanged and MEAS is a new tag, so an older reader (which skips it) decodes the same scope, unmeasured', async () => {
|
|
104
|
+
const withMeas = sectionsOf(await encodePack(scoped(V5), { deflate: false }));
|
|
105
|
+
withMeas.delete(TAG.MEAS); // what a reader that does not know the tag does (its strings stay in STR, unreferenced)
|
|
106
|
+
expect(await decodePack(frameOf(withMeas))).toEqual(scoped());
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it('a MEAS section without a SCOPE, a tool named twice, or trailing bytes is a malformed pack', async () => {
|
|
110
|
+
const sections = sectionsOf(await encodePack(scoped(V5), { deflate: false }));
|
|
111
|
+
const noScope = new Map(sections); noScope.delete(TAG.SCOPE);
|
|
112
|
+
await expect(decodePack(frameOf(noScope))).rejects.toBeInstanceOf(PackFormatError);
|
|
113
|
+
const trailing = new Map(sections); trailing.set(TAG.MEAS, new Uint8Array([...sections.get(TAG.MEAS)!, 0]));
|
|
114
|
+
await expect(decodePack(frameOf(trailing))).rejects.toBeInstanceOf(PackFormatError);
|
|
115
|
+
const meas = new ByteReader(sections.get(TAG.MEAS)!);
|
|
116
|
+
const extractor = meas.varint(); meas.varint(); const tool = meas.varint(); const version = meas.varint();
|
|
117
|
+
const twice = new ByteWriter(); twice.varint(extractor); twice.varint(2); for (let i = 0; i < 2; i++) { twice.varint(tool); twice.varint(version); }
|
|
118
|
+
const dup = new Map(sections); dup.set(TAG.MEAS, twice.finish());
|
|
119
|
+
await expect(decodePack(frameOf(dup))).rejects.toBeInstanceOf(PackFormatError);
|
|
120
|
+
});
|
|
121
|
+
});
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/contract/regression.wilcoxon.test.ts — the stats module's Wilcoxon signed-rank, paired Hodges–Lehmann and paired
|
|
3
|
+
* bootstrap (shipped wrong in 2026.10.72):
|
|
4
|
+
* - the exact null CDF was built ONCE for n = 60 and indexed with W+ for every n, so p ≈ 0 for any n ≤ 60 (a null
|
|
5
|
+
* 10-pair series gave 2.2e-15); the n > 60 branch used exp(−z²/2) instead of a normal tail;
|
|
6
|
+
* - the Hodges–Lehmann estimate dropped zero differences, biasing it away from 0;
|
|
7
|
+
* - the paired bootstrap could only resample the MEAN, not the Hodges–Lehmann estimate PRD 41 C6.2 reports.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { describe, expect, it } from '@jest/globals';
|
|
11
|
+
import { pairedBootstrapCi, wilcoxonSignedRank } from '../stats/index.js';
|
|
12
|
+
import { exactSignedRankPValue, normalSignedRankPValue } from '../stats/tests.js';
|
|
13
|
+
import { createRng } from '../stats/prng.js';
|
|
14
|
+
|
|
15
|
+
/** The textbook paired Hodges–Lehmann: materialise every Walsh average, sort, take the median. */
|
|
16
|
+
function bruteHodgesLehmann(d: readonly number[]): number {
|
|
17
|
+
const w: number[] = [];
|
|
18
|
+
for (let p = 0; p < d.length; p++) for (let q = p; q < d.length; q++) w.push((d[p]! + d[q]!) / 2);
|
|
19
|
+
w.sort((a, b) => a - b);
|
|
20
|
+
const m = w.length;
|
|
21
|
+
return m % 2 === 1 ? w[(m - 1) / 2]! : (w[m / 2 - 1]! + w[m / 2]!) / 2;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Paired data with distinct |d| = 1..n and W+ = w exactly (greedy subset of 1..n summing to w). */
|
|
25
|
+
function pairsWithWPlus(n: number, w: number): { before: number[]; after: number[] } {
|
|
26
|
+
let remaining = w;
|
|
27
|
+
const positive = new Set<number>();
|
|
28
|
+
for (let r = n; r >= 1; r--) if (r <= remaining) { positive.add(r); remaining -= r; }
|
|
29
|
+
if (remaining !== 0) throw new Error(`no subset of 1..${n} sums to ${w}`);
|
|
30
|
+
const before = Array.from({ length: n }, () => 100);
|
|
31
|
+
const after = before.map((b, i) => b + (positive.has(i + 1) ? i + 1 : -(i + 1)));
|
|
32
|
+
return { before, after };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Two-sided α = 0.05 critical values of the signed-rank statistic (min(W+, W−) ≤ T rejects), standard tables. */
|
|
36
|
+
const CRITICAL_05: Record<number, number> = {
|
|
37
|
+
6: 0, 7: 2, 8: 3, 9: 5, 10: 8, 11: 10, 12: 13, 13: 17, 14: 21, 15: 25, 16: 29, 17: 34, 18: 40, 19: 46, 20: 52,
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
describe('regression: wilcoxon signed-rank p-values are right for every n', () => {
|
|
41
|
+
it('regression: null data gives p ≈ 1, not ≈ 0', () => {
|
|
42
|
+
const before = Array.from({ length: 10 }, () => 50);
|
|
43
|
+
const after = [51, 49, 52, 48, 53, 47, 54, 46, 55, 45]; // ±1..±5, symmetric: W+ = W− = 27.5
|
|
44
|
+
const r = wilcoxonSignedRank(before, after);
|
|
45
|
+
expect(r.n).toBe(10);
|
|
46
|
+
expect(r.wPlus).toBe(27.5);
|
|
47
|
+
expect(r.pValue).toBe(1);
|
|
48
|
+
const small = wilcoxonSignedRank([0, 0, 0], [1, -2, 3]);
|
|
49
|
+
expect(small.pValue).toBeGreaterThan(0.5);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it('regression: all-positive n = 10 gives the exact two-sided p = 2/1024', () => {
|
|
53
|
+
const before = Array.from({ length: 10 }, (_, i) => i);
|
|
54
|
+
const after = before.map((b, i) => b + i + 1);
|
|
55
|
+
const r = wilcoxonSignedRank(before, after);
|
|
56
|
+
expect(r.wPlus).toBe(55);
|
|
57
|
+
expect(r.pValue).toBeCloseTo(2 / 1024, 15);
|
|
58
|
+
// n = 5 all positive cannot reach 0.05 two-sided: 2/32.
|
|
59
|
+
expect(wilcoxonSignedRank([0, 0, 0, 0, 0], [1, 2, 3, 4, 5]).pValue).toBeCloseTo(2 / 32, 15);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('regression: matches the textbook α = 0.05 critical values for n = 5..20', () => {
|
|
63
|
+
// n = 5: no critical value exists at α = 0.05 two-sided (the most extreme W gives 0.0625).
|
|
64
|
+
expect(wilcoxonSignedRank(pairsWithWPlus(5, 0).before, pairsWithWPlus(5, 0).after).pValue).toBeGreaterThan(0.05);
|
|
65
|
+
for (const [nKey, t] of Object.entries(CRITICAL_05)) {
|
|
66
|
+
const n = Number(nKey);
|
|
67
|
+
const at = pairsWithWPlus(n, t);
|
|
68
|
+
const past = pairsWithWPlus(n, t + 1);
|
|
69
|
+
expect({ n, p: wilcoxonSignedRank(at.before, at.after).pValue <= 0.05 }).toEqual({ n, p: true });
|
|
70
|
+
expect({ n, p: wilcoxonSignedRank(past.before, past.after).pValue > 0.05 }).toEqual({ n, p: true });
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it('regression: at n = 50 the normal approximation matches the exact distribution (same n, same W+)', () => {
|
|
75
|
+
const n = 50;
|
|
76
|
+
const doubledRanks = Array.from({ length: n }, (_, i) => 2 * (i + 1));
|
|
77
|
+
// Within 0.001 where decisions are made (p < 0.1), within 0.005 in the body of the distribution.
|
|
78
|
+
for (const w of [300, 400, 450, 500, 560, 600, 637]) {
|
|
79
|
+
const exact = exactSignedRankPValue(doubledRanks, 2 * w);
|
|
80
|
+
const normal = normalSignedRankPValue(n, w, []);
|
|
81
|
+
const tolerance = exact < 0.1 ? 0.001 : 0.005;
|
|
82
|
+
expect({ w, close: Math.abs(exact - normal) < tolerance }).toEqual({ w, close: true });
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('regression: the large-n branch is a real two-sided normal tail, centred and far-tail', () => {
|
|
87
|
+
const n = 60;
|
|
88
|
+
const sym = pairsWithWPlus(n, (n * (n + 1)) / 4);
|
|
89
|
+
expect(wilcoxonSignedRank(sym.before, sym.after).pValue).toBeGreaterThan(0.95);
|
|
90
|
+
const allUp = wilcoxonSignedRank(Array.from({ length: n }, () => 0), Array.from({ length: n }, (_, i) => i + 1));
|
|
91
|
+
expect(allUp.pValue).toBeLessThan(1e-9);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it('regression: a far tail does not underflow to 0 (n = 100 all positive ≈ 4e-18)', () => {
|
|
95
|
+
const n = 100;
|
|
96
|
+
const r = wilcoxonSignedRank(Array.from({ length: n }, () => 0), Array.from({ length: n }, (_, i) => i + 1));
|
|
97
|
+
expect(r.pValue).toBeGreaterThan(1e-19);
|
|
98
|
+
expect(r.pValue).toBeLessThan(1e-16);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('regression: ties share mid-ranks and the exact p-value conditions on them', () => {
|
|
102
|
+
// |d| = 1,1,2,2 all positive: W+ = 1.5+1.5+3.5+3.5 = 10 = the maximum; P = 1/16 one-sided.
|
|
103
|
+
const r = wilcoxonSignedRank([0, 0, 0, 0], [1, 1, 2, 2]);
|
|
104
|
+
expect(r.wPlus).toBe(10);
|
|
105
|
+
expect(r.pValue).toBeCloseTo(2 / 16, 15);
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
describe('regression: the paired Hodges–Lehmann estimate counts zero differences', () => {
|
|
110
|
+
it('regression: zeros are Walsh-averaged, not dropped', () => {
|
|
111
|
+
// d = 0, 0, 0, 1: Walsh averages are six 0s, three 0.5s and one 1 → median 0 (dropping zeros gave 1).
|
|
112
|
+
const r = wilcoxonSignedRank([5, 5, 5, 5], [5, 5, 5, 6]);
|
|
113
|
+
expect(r.n).toBe(1);
|
|
114
|
+
expect(r.hodgesLehmann).toBe(0);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('regression: the O(n log n) selection returns exactly the brute-force median (ties, zeros, clusters)', () => {
|
|
118
|
+
const rng = createRng(17);
|
|
119
|
+
for (let trial = 0; trial < 200; trial++) {
|
|
120
|
+
const n = 1 + Math.floor(rng() * 40);
|
|
121
|
+
const kind = trial % 4;
|
|
122
|
+
const d = Array.from({ length: n }, () => {
|
|
123
|
+
const u = rng();
|
|
124
|
+
if (kind === 0) return u * 10 - 5; // continuous
|
|
125
|
+
if (kind === 1) return Math.round(u * 6) - 3; // heavy ties and zeros
|
|
126
|
+
if (kind === 2) return u < 0.6 ? 0 : u * 1e-12; // a big cluster of zeros next to tiny values
|
|
127
|
+
return u < 0.5 ? 1e9 : -1e-9 * u; // wildly mixed scales
|
|
128
|
+
});
|
|
129
|
+
const zeros = d.map(() => 0);
|
|
130
|
+
expect({ trial, hl: wilcoxonSignedRank(zeros, d).hodgesLehmann }).toEqual({ trial, hl: bruteHodgesLehmann(d) });
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
describe('regression: non-finite differences are dropped and counted', () => {
|
|
136
|
+
it('regression: NaN / Infinity pairs never reach the ranks or the estimate', () => {
|
|
137
|
+
const r = wilcoxonSignedRank([0, 0, 0, 0, Number.NaN, 0], [1, 2, 3, 4, 5, Number.POSITIVE_INFINITY]);
|
|
138
|
+
expect(r.nonFinite).toBe(2);
|
|
139
|
+
expect(r.n).toBe(4);
|
|
140
|
+
expect(r.pValue).toBeCloseTo(2 / 16, 15);
|
|
141
|
+
expect(Number.isFinite(r.hodgesLehmann)).toBe(true);
|
|
142
|
+
expect(wilcoxonSignedRank([1, 2], [2, 3]).nonFinite).toBe(0);
|
|
143
|
+
const ci = pairedBootstrapCi([0, 0, Number.NaN], [1, 1, 1], { seed: 1, statistic: 'hodges-lehmann' });
|
|
144
|
+
expect(ci).toEqual({ low: 1, high: 1, estimate: 1 });
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
describe('regression: the paired bootstrap can resample the Hodges–Lehmann estimate', () => {
|
|
149
|
+
it('regression: statistic "hodges-lehmann" is seeded, fixed-count and centred on the HL estimate', () => {
|
|
150
|
+
const before = [10, 12, 11, 13, 15, 9, 14, 10, 12, 11];
|
|
151
|
+
const after = [11, 13, 12, 14, 16, 10, 15, 11, 30, 11];
|
|
152
|
+
const hl = pairedBootstrapCi(before, after, { seed: 3, statistic: 'hodges-lehmann' });
|
|
153
|
+
expect(pairedBootstrapCi(before, after, { seed: 3, statistic: 'hodges-lehmann' })).toEqual(hl);
|
|
154
|
+
expect(hl.estimate).toBe(wilcoxonSignedRank(before, after).hodgesLehmann);
|
|
155
|
+
expect(hl.low).toBeLessThanOrEqual(hl.estimate);
|
|
156
|
+
expect(hl.high).toBeGreaterThanOrEqual(hl.estimate);
|
|
157
|
+
// The outlier drags the mean, not the HL estimate.
|
|
158
|
+
const mean = pairedBootstrapCi(before, after, { seed: 3 });
|
|
159
|
+
expect(mean.estimate).toBeGreaterThan(hl.estimate);
|
|
160
|
+
expect(pairedBootstrapCi(before, after, { seed: 3, statistic: 'mean' })).toEqual(mean);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it('regression: the HL bootstrap is O(B·n log n), not O(B·n² log n) — within a small factor of the mean bootstrap', () => {
|
|
164
|
+
// Relative, so it holds on any machine: at n = 200 the old n² Walsh list cost ~50× the mean bootstrap.
|
|
165
|
+
const rng = createRng(5);
|
|
166
|
+
const before = Array.from({ length: 200 }, () => 100 + rng() * 10);
|
|
167
|
+
const after = before.map((b) => b + 1 + rng() * 4);
|
|
168
|
+
const time = (statistic: 'mean' | 'hodges-lehmann') => {
|
|
169
|
+
const started = performance.now();
|
|
170
|
+
const ci = pairedBootstrapCi(before, after, { seed: 9, statistic });
|
|
171
|
+
return { ms: performance.now() - started, ci };
|
|
172
|
+
};
|
|
173
|
+
time('hodges-lehmann'); // warm both paths
|
|
174
|
+
const mean = time('mean');
|
|
175
|
+
const hl = time('hodges-lehmann');
|
|
176
|
+
expect(hl.ms).toBeLessThan(10 * Math.max(mean.ms, 5));
|
|
177
|
+
expect(hl.ci.low).toBeLessThanOrEqual(hl.ci.estimate);
|
|
178
|
+
expect(hl.ci.high).toBeGreaterThanOrEqual(hl.ci.estimate);
|
|
179
|
+
});
|
|
180
|
+
});
|
|
@@ -29,6 +29,7 @@ import type {
|
|
|
29
29
|
comparable, compareAnalysis, identityOf, matchLineage, isBinaryBytes,
|
|
30
30
|
} from '../knowledge/index.js';
|
|
31
31
|
import { placementOf } from '../knowledge/index.js';
|
|
32
|
+
import type { MeasuredWith } from '../knowledge/index.js';
|
|
32
33
|
import type {
|
|
33
34
|
applyCoChangeHidden, coChangePartners, coChangeRecallAtK, decodeCoChange, encodeCoChange, mostLikelyWalk, stationTransitions, transitionOf,
|
|
34
35
|
transitionsFromSequences, transitionsFromWeights, CoChangeBadgeEntry, CoChangeCommit, CoChangeOptions, CoChangePartner, CoChangeRecall,
|
|
@@ -59,6 +60,12 @@ export type KnowledgeSnapshot_rows_are_required = Expect<Equal<
|
|
|
59
60
|
export const snapshotWithoutExtracted = { version: 1, scopes: [], facts: {}, relations: {} } satisfies KnowledgeSnapshot;
|
|
60
61
|
export const readsThroughTheEntriesPort = (store: LocalSnapshotStore): Promise<Record<string, Extracted[]>> => store.extractedEntries();
|
|
61
62
|
|
|
63
|
+
/* ── ScopeRecord.measured (PRD 41 §C9): recorded when the review runs, carried by the pack's MEAS section ───────────── */
|
|
64
|
+
export type MeasuredWith_shape = Expect<Equal<MeasuredWith, { extractorVersion: string; toolVersions: Record<string, string> }>>;
|
|
65
|
+
export type ScopeRecord_measured_is_optional = Expect<Equal<IsOptional<ScopeRecord, 'measured'>, true>>;
|
|
66
|
+
export type ScopeRecord_measured_shape = Expect<Equal<ScopeRecord['measured'], MeasuredWith | undefined>>;
|
|
67
|
+
export type ReviewArgs_measured = Expect<Equal<Pick<import('../knowledge/index.js').ReviewArgs, 'measured'>, { measured?: MeasuredWith }>>;
|
|
68
|
+
|
|
62
69
|
/* ── ReviewReport ──────────────────────────────────────────────────────────────────────────────────────────── */
|
|
63
70
|
export type ReviewReport_judging_fields = Expect<Equal<
|
|
64
71
|
Pick<ReviewReport, 'awaitingJudge' | 'awaitingJudgeCount' | 'judgedFiles' | 'judgeStopped' | 'failures'>,
|
package/src/knowledge/index.ts
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
export type {
|
|
10
10
|
NodeRef, Origin, StoredOrigin, KNode, EdgeVerdict, KEdge, Extracted, ExtractContext, Finding, FindingRule,
|
|
11
11
|
PartitionRule, PartitionRegistry, JudgementSpec, JudgementRequest, JudgedClaim, JudgedEntity, JudgementResult,
|
|
12
|
-
JudgementPort, AnalyzerPort, AnalyzerProgress, KnowledgeParser, KnowledgePack, StoredFact, StoredRelation, Scope, ScopeRecord,
|
|
12
|
+
JudgementPort, AnalyzerPort, AnalyzerProgress, KnowledgeParser, KnowledgePack, StoredFact, StoredRelation, Scope, ScopeRecord, MeasuredWith,
|
|
13
13
|
KnowledgeStore, DirectorySource, LiveOverlay, KnowledgeGraph, ReviewPlan, ReviewProgress, ReviewReport,
|
|
14
14
|
ReviewArgs, BuildGraphInput, BuildGraphOptions, TraceStep, Trace, GraphOutline, OutlineFile, OutlineCommunity,
|
|
15
15
|
GraphSystem, GraphApp, GraphReadSkip, CallSite,
|
package/src/knowledge/model.ts
CHANGED
|
@@ -211,12 +211,30 @@ export interface Scope {
|
|
|
211
211
|
rootId: string;
|
|
212
212
|
}
|
|
213
213
|
|
|
214
|
+
/**
|
|
215
|
+
* What a review was measured with (PRD 41 §C9): the extractor version and the analyzers, name → version. Both sides of a
|
|
216
|
+
* compare state it; memory's `comparable()` reads them as `ComparabilityMeta.extractorVersion` / `tools`. The packs are
|
|
217
|
+
* NOT in `toolVersions`: they are `ScopeRecord.packs`.
|
|
218
|
+
*/
|
|
219
|
+
export interface MeasuredWith {
|
|
220
|
+
/** The extractor version, as text (`ComparabilityMeta.extractorVersion` compares it as a string). */
|
|
221
|
+
extractorVersion: string;
|
|
222
|
+
/** Analyzer name → version; empty when no analyzer measured the root. */
|
|
223
|
+
toolVersions: Record<string, string>;
|
|
224
|
+
}
|
|
225
|
+
|
|
214
226
|
export interface ScopeRecord {
|
|
215
227
|
rootId: string;
|
|
216
228
|
title: string;
|
|
217
229
|
packs: string[];
|
|
218
230
|
lastDigest?: string;
|
|
219
231
|
lastReviewedAt?: string;
|
|
232
|
+
/**
|
|
233
|
+
* What the review at `lastDigest` was measured with, recorded when that review ran (`ReviewArgs.measured`) — never
|
|
234
|
+
* re-derived later, so a review queued offline across an upgrade keeps the versions it was made with. A write that
|
|
235
|
+
* moves `lastDigest` replaces it (absent ⇒ unknown); the BFKP pack carries it (its own section, PRD 41 §C9).
|
|
236
|
+
*/
|
|
237
|
+
measured?: MeasuredWith;
|
|
220
238
|
}
|
|
221
239
|
|
|
222
240
|
/** Where knowledge is persisted: the platform API adapter or the local snapshot adapter. */
|
|
@@ -81,7 +81,10 @@ export function genPack(seed: number, o: GenOptions): Pack {
|
|
|
81
81
|
return r;
|
|
82
82
|
});
|
|
83
83
|
}
|
|
84
|
-
if (rich && g.chance(0.5))
|
|
84
|
+
if (rich && g.chance(0.5)) {
|
|
85
|
+
pack.scope = { rootId: ROOT, title: 'Gen', packs: ['code', 'docs'], lastDigest: g.hex64().slice(0, 32), lastReviewedAt: '2026-11-07T00:00:00.000Z' };
|
|
86
|
+
if (g.chance(0.5)) pack.scope.measured = { extractorVersion: String(g.int(9)), toolVersions: g.chance(0.5) ? { knip: '5.30.0', jscpd: '4.0.5' } : {} };
|
|
87
|
+
}
|
|
85
88
|
if (rich && g.chance(0.5)) pack.analysis = { version: 1, nodes: ['a'], edges: [] };
|
|
86
89
|
if (o.hashes) pack.hashes = [g.hex64(), '~tag:odd-id', g.hex64()];
|
|
87
90
|
return pack;
|
|
@@ -1,14 +1,18 @@
|
|
|
1
1
|
/** knowledge/pack/sections/index.ts — every row section of BFKP v1, in the order they are written (STR and HASH are written first by encode.ts). */
|
|
2
2
|
|
|
3
|
-
import { deleteSection, analysisSection, bucketSection, fileSection, leafSection, scopeSection, staleSection } from './rows.js';
|
|
3
|
+
import { deleteSection, analysisSection, bucketSection, fileSection, leafSection, measuredSection, scopeSection, staleSection } from './rows.js';
|
|
4
4
|
import { extrSection } from './extr.js';
|
|
5
5
|
import { factSection, relationSection } from './facts.js';
|
|
6
6
|
import { siteSection } from './sites.js';
|
|
7
7
|
import type { SectionCodec } from './columns.js';
|
|
8
8
|
|
|
9
|
-
/**
|
|
9
|
+
/**
|
|
10
|
+
* SITE comes right after EXTR: it attaches call sites to the edges EXTR decoded; MEAS right after SCOPE, whose `measured` it
|
|
11
|
+
* sets (a reader runs these in this order).
|
|
12
|
+
*/
|
|
10
13
|
export const ROW_SECTIONS: readonly SectionCodec[] = [
|
|
11
|
-
fileSection, extrSection, siteSection, factSection, relationSection, staleSection, deleteSection, scopeSection,
|
|
14
|
+
fileSection, extrSection, siteSection, factSection, relationSection, staleSection, deleteSection, scopeSection, measuredSection, analysisSection,
|
|
15
|
+
leafSection, bucketSection,
|
|
12
16
|
];
|
|
13
17
|
|
|
14
18
|
export { TAG } from './rows.js';
|
|
@@ -11,7 +11,7 @@ import type { Pack } from '../types.js';
|
|
|
11
11
|
import type { SectionCodec } from './columns.js';
|
|
12
12
|
import { MANIFEST_BUCKETS } from '../manifest.js';
|
|
13
13
|
|
|
14
|
-
export const TAG = { STR: 1, HASH: 2, FILE: 3, EXTR: 4, FACT: 5, REL: 6, STALE: 7, DEL: 8, SCOPE: 9, ANALYSIS: 10, LEAF: 11, BKT: 12, SITE: 13 } as const;
|
|
14
|
+
export const TAG = { STR: 1, HASH: 2, FILE: 3, EXTR: 4, FACT: 5, REL: 6, STALE: 7, DEL: 8, SCOPE: 9, ANALYSIS: 10, LEAF: 11, BKT: 12, SITE: 13, MEAS: 14 } as const;
|
|
15
15
|
|
|
16
16
|
export const fileSection: SectionCodec = {
|
|
17
17
|
tag: TAG.FILE,
|
|
@@ -126,6 +126,44 @@ export const scopeSection: SectionCodec = {
|
|
|
126
126
|
},
|
|
127
127
|
};
|
|
128
128
|
|
|
129
|
+
/**
|
|
130
|
+
* MEAS — the scope's `measured` (PRD 41 §C9): what its review was measured with. SCOPE is a CLOSED section (frame.ts), so
|
|
131
|
+
* this is a NEW tag: a reader older than this release skips it and decodes the scope unmeasured (unknown — never "the
|
|
132
|
+
* same"). Read after SCOPE (ROW_SECTIONS order); a MEAS without a SCOPE is malformed.
|
|
133
|
+
*
|
|
134
|
+
* extractorVersion STR · n varint · n × (tool STR · version STR), tools in sorted order
|
|
135
|
+
*/
|
|
136
|
+
export const measuredSection: SectionCodec = {
|
|
137
|
+
tag: TAG.MEAS,
|
|
138
|
+
write(pack, t) {
|
|
139
|
+
const m = pack.scope?.measured;
|
|
140
|
+
if (!m) return undefined;
|
|
141
|
+
// A scope may come from an unvalidated JSON snapshot: never write what this decoder would refuse.
|
|
142
|
+
if (typeof m.extractorVersion !== 'string' || !m.toolVersions || typeof m.toolVersions !== 'object') throw new PackFormatError('scope.measured is malformed');
|
|
143
|
+
const tools = Object.keys(m.toolVersions).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
144
|
+
if (tools.some((tool) => tool === '__proto__' || typeof m.toolVersions[tool] !== 'string')) throw new PackFormatError('scope.measured.toolVersions is malformed');
|
|
145
|
+
const w = new ByteWriter();
|
|
146
|
+
w.varint(t.str(m.extractorVersion));
|
|
147
|
+
w.varint(tools.length);
|
|
148
|
+
for (const tool of tools) { w.varint(t.str(tool)); w.varint(t.str(m.toolVersions[tool]!)); }
|
|
149
|
+
return w.finish();
|
|
150
|
+
},
|
|
151
|
+
read(bytes, t, limits, into) {
|
|
152
|
+
if (!into.scope) throw new PackFormatError('MEAS section without a SCOPE');
|
|
153
|
+
const r = new ByteReader(bytes);
|
|
154
|
+
const extractorVersion = t.str(r.varint());
|
|
155
|
+
const n = boundedCount(r, limits.budget, 'measured tools');
|
|
156
|
+
const toolVersions: Record<string, string> = {};
|
|
157
|
+
for (let i = 0; i < n; i++) {
|
|
158
|
+
const tool = t.str(r.varint());
|
|
159
|
+
if (tool === '__proto__' || Object.prototype.hasOwnProperty.call(toolVersions, tool)) throw new PackFormatError(`MEAS names ${tool} twice or as __proto__`);
|
|
160
|
+
toolVersions[tool] = t.str(r.varint());
|
|
161
|
+
}
|
|
162
|
+
assertConsumed(r, 'MEAS section');
|
|
163
|
+
into.scope.measured = { extractorVersion, toolVersions };
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
|
|
129
167
|
/** Object keys in sorted order, recursively: equal documents become equal bytes however their keys were built. */
|
|
130
168
|
const canonical = (v: unknown): unknown => {
|
|
131
169
|
if (Array.isArray(v)) return v.map(canonical);
|
|
@@ -58,7 +58,10 @@ export async function finishReview(c: ReviewContext, flush: () => Promise<void>)
|
|
|
58
58
|
}), c.failures, c.detail.extractor.documentsNow,
|
|
59
59
|
// An aborted run keeps the key the root was last reviewed under: every file stays owed until a run under the new key finishes.
|
|
60
60
|
report.aborted ? c.detail.extractor.extractorKey : c.detail.extractor.extractorKeyNow);
|
|
61
|
-
|
|
61
|
+
// What the review was measured with is recorded NOW, with its digest (PRD 41 §C9): never re-derived when it is synced.
|
|
62
|
+
await writeBatch(c, report.aborted ? c.scopeRecord : {
|
|
63
|
+
...c.scopeRecord, lastDigest: report.digest, lastReviewedAt: new Date(c.now()).toISOString(), ...(args.measured ? { measured: args.measured } : {}),
|
|
64
|
+
});
|
|
62
65
|
report.durationMs = c.now() - c.started;
|
|
63
66
|
c.progress({ phase: 'done', done: c.work.length, total: c.work.length });
|
|
64
67
|
return report;
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import type { IngestManifest, SourceDocument } from '../ingest/types.js';
|
|
7
7
|
import type { SimilarPair } from '../retrieval/knowledge-index/types.js';
|
|
8
|
-
import type { JudgementPort, KnowledgePack, KnowledgeStore } from './model.js';
|
|
8
|
+
import type { JudgementPort, KnowledgePack, KnowledgeStore, MeasuredWith } from './model.js';
|
|
9
9
|
import type { PlanDetail } from './plan.js';
|
|
10
10
|
import type { ExtractPool } from './extractJob.js';
|
|
11
11
|
import type { ReviewFailure, ReviewPhase, ReviewStep } from './reviewRunModel.js';
|
|
@@ -120,6 +120,11 @@ export interface ReviewArgs {
|
|
|
120
120
|
*/
|
|
121
121
|
similar?: (ids: string[], texts?: ReadonlyMap<string, string>) => Promise<SimilarPair[]>;
|
|
122
122
|
budget: { modelCalls: number; ms: number };
|
|
123
|
+
/**
|
|
124
|
+
* What this review is measured with (PRD 41 §C9): the host's extractor and analyzer versions NOW. A finished run
|
|
125
|
+
* stamps it on the scope with `lastDigest` (`ScopeRecord.measured`); absent ⇒ the scope's review is unknown-measured.
|
|
126
|
+
*/
|
|
127
|
+
measured?: MeasuredWith;
|
|
123
128
|
/** *Continue*: the plan the person confirmed. Reused without a re-walk; `changed` is re-read from the manifest. */
|
|
124
129
|
plan?: PlanDetail;
|
|
125
130
|
/** *Re-review all*: every file is reviewed whatever its hash (see `PlanOptions.force`). Ignored with `plan`. */
|
|
@@ -264,6 +264,10 @@ export class LocalSnapshotStore implements KnowledgeStore {
|
|
|
264
264
|
const rootId = batch.scope.rootId;
|
|
265
265
|
const prior = this.mem.scopes.find((x) => x.rootId === rootId);
|
|
266
266
|
const merged: ScopeRecord = { ...(prior ?? {}), ...stripUndefined(batch.scope) } as ScopeRecord;
|
|
267
|
+
// `measured` describes the review at `lastDigest` (PRD 41 §C9): a write that records a digest (a finished review,
|
|
268
|
+
// even one whose digest did not move) replaces it, so an unmeasured review never inherits the versions of the one
|
|
269
|
+
// before it. A write without a digest (mid-run, aborted) keeps it.
|
|
270
|
+
if (batch.scope.lastDigest !== undefined && !batch.scope.measured) delete merged.measured;
|
|
267
271
|
this.mem.scopes = [...this.mem.scopes.filter((x) => x.rootId !== rootId), merged];
|
|
268
272
|
this.delta?.mark('scopes', [rootId]);
|
|
269
273
|
|
|
@@ -230,6 +230,16 @@ export function regularizedIncompleteGamma(a: number, x: number): number {
|
|
|
230
230
|
return 1 - gammaQ(a, x);
|
|
231
231
|
}
|
|
232
232
|
|
|
233
|
+
/**
|
|
234
|
+
* Regularized UPPER incomplete gamma Q(a, x) = 1 − P(a, x), computed directly in the
|
|
235
|
+
* tail (continued fraction) so a tiny Q does not underflow to 0 through 1 − P. Module-
|
|
236
|
+
* internal to `./stats` (the normal tail of the Wilcoxon large-n branch); not a public export.
|
|
237
|
+
*/
|
|
238
|
+
export function regularizedUpperIncompleteGamma(a: number, x: number): number {
|
|
239
|
+
if (x <= 0) return 1;
|
|
240
|
+
return x < a + 1 ? 1 - regularizedIncompleteGamma(a, x) : gammaQ(a, x);
|
|
241
|
+
}
|
|
242
|
+
|
|
233
243
|
/** Gamma(shape, scale) quantile by bisection on the CDF. Deterministic. */
|
|
234
244
|
export function gammaQuantile(p: number, shape: number, scale = 1): number {
|
|
235
245
|
if (p <= 0) return 0;
|
package/src/stats/index.ts
CHANGED
|
@@ -40,7 +40,7 @@ export {
|
|
|
40
40
|
signTestSprt,
|
|
41
41
|
wilcoxonSignedRank,
|
|
42
42
|
} from "./tests.js";
|
|
43
|
-
export type { SprtResult, WilcoxonResult } from "./tests.js";
|
|
43
|
+
export type { PairedStatistic, SprtResult, WilcoxonResult } from "./tests.js";
|
|
44
44
|
|
|
45
45
|
export { bayesianOnlineChangePoint, cusum } from "./timeSeries.js";
|
|
46
46
|
export type { ChangePointResult, CusumResult } from "./timeSeries.js";
|