@seanhogg/builderforce-memory 2026.10.69 → 2026.10.71

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 (62) 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 +104 -0
  6. package/dist/knowledge/coChange.d.ts.map +1 -0
  7. package/dist/knowledge/coChange.js +297 -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/comparability.d.ts +3 -1
  14. package/dist/knowledge/comparability.d.ts.map +1 -1
  15. package/dist/knowledge/comparability.js +2 -1
  16. package/dist/knowledge/comparability.js.map +1 -1
  17. package/dist/knowledge/index.d.ts +5 -1
  18. package/dist/knowledge/index.d.ts.map +1 -1
  19. package/dist/knowledge/index.js +3 -1
  20. package/dist/knowledge/index.js.map +1 -1
  21. package/dist/knowledge/outline.d.ts.map +1 -1
  22. package/dist/knowledge/outline.js +2 -0
  23. package/dist/knowledge/outline.js.map +1 -1
  24. package/dist/knowledge/refs.d.ts.map +1 -1
  25. package/dist/knowledge/refs.js +3 -1
  26. package/dist/knowledge/refs.js.map +1 -1
  27. package/dist/knowledge/sources.d.ts +1 -1
  28. package/dist/knowledge/sources.d.ts.map +1 -1
  29. package/dist/knowledge/sources.js +3 -1
  30. package/dist/knowledge/sources.js.map +1 -1
  31. package/dist/knowledge/transitions.d.ts +59 -0
  32. package/dist/knowledge/transitions.d.ts.map +1 -0
  33. package/dist/knowledge/transitions.js +90 -0
  34. package/dist/knowledge/transitions.js.map +1 -0
  35. package/dist/stats/distributions.d.ts +23 -1
  36. package/dist/stats/distributions.d.ts.map +1 -1
  37. package/dist/stats/distributions.js +102 -19
  38. package/dist/stats/distributions.js.map +1 -1
  39. package/dist/stats/index.d.ts +1 -1
  40. package/dist/stats/index.d.ts.map +1 -1
  41. package/dist/stats/index.js +1 -1
  42. package/dist/stats/index.js.map +1 -1
  43. package/package.json +1 -1
  44. package/src/contract/exports.snapshot.json +21 -0
  45. package/src/contract/regression.analysisTruncated.test.ts +32 -0
  46. package/src/contract/regression.assets.test.ts +4 -0
  47. package/src/contract/types.contract.test.ts +50 -1
  48. package/src/knowledge/build.ts +5 -1
  49. package/src/knowledge/coChange.test.ts +297 -0
  50. package/src/knowledge/coChange.ts +333 -0
  51. package/src/knowledge/communities.ts +6 -1
  52. package/src/knowledge/comparability.analysis.test.ts +16 -1
  53. package/src/knowledge/comparability.ts +4 -1
  54. package/src/knowledge/index.ts +8 -1
  55. package/src/knowledge/outline.ts +2 -0
  56. package/src/knowledge/refs.ts +4 -1
  57. package/src/knowledge/sources.ts +3 -1
  58. package/src/knowledge/transitions.test.ts +135 -0
  59. package/src/knowledge/transitions.ts +115 -0
  60. package/src/stats/distributions.ts +103 -20
  61. package/src/stats/index.ts +3 -0
  62. package/src/stats/stats.test.ts +89 -0
@@ -0,0 +1,297 @@
1
+ /**
2
+ * src/knowledge/coChange.test.ts
3
+ * PRD 38 P4: co-change association — the support / lift thresholds at their boundaries, the bulk-commit cut (distinct refs
4
+ * and whole-repo `fileCount`), the commit cap, the partner cap and ranking, determinism, the versioned badge codec, recall@k
5
+ * on a history with known coupling (and without leakage), and the hidden-coupling badge through `buildGraph` and the outline.
6
+ * Hand computations are in the comments.
7
+ */
8
+
9
+ import {
10
+ applyCoChangeHidden, coChangePartners, coChangeRecallAtK, COCHANGE_MAX_COMMIT_FILES, COCHANGE_MAX_COMMITS, COCHANGE_MAX_PARTNERS,
11
+ COCHANGE_MIN_LIFT, COCHANGE_MIN_SUPPORT, decodeCoChange, encodeCoChange, type CoChangeCommit, type CoChangePartner,
12
+ } from './coChange.js';
13
+ import { buildGraph } from './build.js';
14
+ import { buildOutline } from './outline.js';
15
+ import type { BuildGraphInput, KEdge } from './model.js';
16
+ import { rateInterval } from '../stats/index.js';
17
+ import { round6 } from './refs.js';
18
+ import { edge, extractedOf, fileNode, ref } from './testkit.test-util.js';
19
+
20
+ const C = (...paths: string[]): CoChangeCommit => ({ refs: paths.map(ref) });
21
+ const times = (n: number, c: CoChangeCommit): CoChangeCommit[] => Array.from({ length: n }, () => c);
22
+ /** n commits that each touch one file of their own (they only raise N). */
23
+ const fillers = (n: number, tag = 'z'): CoChangeCommit[] => Array.from({ length: n }, (_, i) => C(`${tag}${String(i).padStart(4, '0')}.ts`));
24
+ const same = (a: unknown, b: unknown) => expect(JSON.stringify(a)).toBe(JSON.stringify(b));
25
+ /** The counted fields of a partner (the interval is checked on its own). */
26
+ const counts = (ps: readonly CoChangePartner[] | undefined) => ps?.map(({ ref: r, together, ofSelf, confidence, lift }) => ({ ref: r, together, ofSelf, confidence, lift }));
27
+
28
+ describe('coChangePartners — thresholds', () => {
29
+ it('exposes the PRD constants', () => {
30
+ expect([COCHANGE_MIN_SUPPORT, COCHANGE_MIN_LIFT, COCHANGE_MAX_COMMIT_FILES, COCHANGE_MAX_PARTNERS, COCHANGE_MAX_COMMITS]).toEqual([3, 2, 50, 8, 5000]);
31
+ });
32
+
33
+ it('keeps a pair at exactly lift 2 and drops it just below', () => {
34
+ // a, b together 3 times, never apart: lift = 3·N / (3·3) = N/3. N = 6 → 2 (kept); N = 5 → 1.666… (dropped).
35
+ const at2 = coChangePartners([...times(3, C('a.ts', 'b.ts')), ...fillers(3)]);
36
+ expect(counts(at2.get(ref('a.ts')))).toEqual([{ ref: ref('b.ts'), together: 3, ofSelf: 3, confidence: 1, lift: 2 }]);
37
+ expect(counts(at2.get(ref('b.ts')))).toEqual([{ ref: ref('a.ts'), together: 3, ofSelf: 3, confidence: 1, lift: 2 }]);
38
+ expect(coChangePartners([...times(3, C('a.ts', 'b.ts')), ...fillers(2)]).size).toBe(0);
39
+ });
40
+
41
+ it('keeps a pair at support 3 and drops it at 2, however high the lift', () => {
42
+ expect(coChangePartners([...times(3, C('a.ts', 'b.ts')), ...fillers(50)]).size).toBe(2);
43
+ expect(coChangePartners([...times(2, C('a.ts', 'b.ts')), ...fillers(50)]).size).toBe(0);
44
+ });
45
+
46
+ it('confidence is P(B|A), asymmetric, and carries the rate interval of together / ofSelf', () => {
47
+ // a in 6 commits (3 with b), b in 3. N = 6 + 20 = 26. lift = 3·26/(6·3) = 4.333333.
48
+ const r = coChangePartners([...times(3, C('a.ts', 'b.ts')), ...times(3, C('a.ts')), ...fillers(20)]);
49
+ const ab = r.get(ref('a.ts'))![0]!;
50
+ expect(counts([ab])).toEqual([{ ref: ref('b.ts'), together: 3, ofSelf: 6, confidence: 0.5, lift: 4.333333 }]);
51
+ const i = rateInterval(3, 6);
52
+ expect([ab.low, ab.high]).toEqual([round6(i.low), round6(i.high)]);
53
+ expect(ab.low).toBeLessThan(0.5);
54
+ expect(ab.high).toBeGreaterThan(0.5);
55
+ // b → a is 3 of 3: the interval's upper end is pinned to 1.
56
+ expect(r.get(ref('b.ts'))![0]).toMatchObject({ ofSelf: 3, confidence: 1, lift: 4.333333, high: 1 });
57
+ });
58
+ });
59
+
60
+ describe('coChangePartners — bulk commits and the commit cap', () => {
61
+ const bulk = (size: number) => C('a.ts', 'b.ts', ...Array.from({ length: size - 2 }, (_, i) => `bulk${i}.ts`));
62
+ const base = [...times(2, C('a.ts', 'b.ts')), ...fillers(10)];
63
+
64
+ it('a commit of exactly 50 files counts; one of 51 is excluded', () => {
65
+ // Two ordinary a+b commits and one bulk commit with a and b: support 3 with the bulk commit, 2 without it.
66
+ expect(coChangePartners([...base, bulk(50)]).get(ref('a.ts'))!.map((p) => [p.ref, p.together])).toEqual([[ref('b.ts'), 3]]);
67
+ expect(coChangePartners([...base, bulk(51)]).size).toBe(0);
68
+ });
69
+
70
+ it('counts distinct refs: duplicates in a commit do not push it over the cap', () => {
71
+ const dupes: CoChangeCommit = { refs: [...bulk(50).refs, ref('a.ts'), ref('b.ts')] };
72
+ expect(coChangePartners([...base, dupes]).size).toBe(2);
73
+ });
74
+
75
+ it('uses the whole-repo fileCount: 300 files touched with only 40 in the root is still bulk', () => {
76
+ expect(coChangePartners([...base, { ...bulk(40), fileCount: 300 }]).size).toBe(0);
77
+ // A fileCount below the distinct refs never lets a bulk commit through, and one at the cap keeps it.
78
+ expect(coChangePartners([...base, { ...bulk(51), fileCount: 10 }]).size).toBe(0);
79
+ expect(coChangePartners([...base, { ...bulk(40), fileCount: 50 }]).size).toBe(2);
80
+ });
81
+
82
+ it('keeps the newest maxCommits by `at`', () => {
83
+ // Old a+b coupling (3 commits) then 10 newer fillers. With maxCommits 10 only the fillers are counted.
84
+ const dated = [...times(3, C('a.ts', 'b.ts')), ...fillers(10)].map((c, i) => ({ ...c, at: new Date(Date.UTC(2026, 0, 1 + i)).toISOString() }));
85
+ expect(coChangePartners(dated).size).toBe(2);
86
+ expect(coChangePartners([...dated].reverse(), { maxCommits: 10 }).size).toBe(0);
87
+ expect(coChangePartners([...dated].reverse(), { maxCommits: 13 }).size).toBe(2);
88
+ });
89
+ });
90
+
91
+ describe('coChangePartners — partner cap and ranking', () => {
92
+ // Hub h changes with p0..p8 three times each and with p9 four times: ofSelf(h) = 31; 31 fillers make N = 62, so every lift is
93
+ // t·62/(31·t) = 2. Confidence ranks p9 (4/31) first; p0..p8 tie (3/31) on confidence and lift, so the ref breaks the tie.
94
+ const history = [
95
+ ...Array.from({ length: 9 }, (_, i) => times(3, C('h.ts', `p${i}.ts`))).flat(),
96
+ ...times(4, C('h.ts', 'p9.ts')),
97
+ ...fillers(31),
98
+ ];
99
+ const r = coChangePartners(history);
100
+
101
+ it('keeps at most 8 partners, ranked confidence desc, lift desc, ref asc', () => {
102
+ const hub = r.get(ref('h.ts'))!;
103
+ expect(hub).toHaveLength(8);
104
+ expect(hub.map((p) => p.ref)).toEqual(['p9', 'p0', 'p1', 'p2', 'p3', 'p4', 'p5', 'p6'].map((p) => ref(`${p}.ts`)));
105
+ expect(counts([hub[0]!])).toEqual([{ ref: ref('p9.ts'), together: 4, ofSelf: 31, confidence: 0.129032, lift: 2 }]);
106
+ expect(hub[1]!.confidence).toBe(0.096774);
107
+ });
108
+
109
+ it('the cap is per file: a spoke still lists the hub', () => {
110
+ expect(counts(r.get(ref('p8.ts')))).toEqual([{ ref: ref('h.ts'), together: 3, ofSelf: 3, confidence: 1, lift: 2 }]);
111
+ });
112
+
113
+ it('lift ranks before ref when confidence ties', () => {
114
+ // x with y and w three times each; w also changes alone 3 times, so lift(x,w) < lift(x,y) while P(·|x) ties at 0.5.
115
+ const t = coChangePartners([...times(3, C('x.ts', 'w.ts')), ...times(3, C('x.ts', 'y.ts')), ...times(3, C('w.ts')), ...fillers(30)]);
116
+ // N = 39. lift(x,y) = 3·39/(6·3) = 6.5; lift(x,w) = 3·39/(6·6) = 3.25.
117
+ expect(t.get(ref('x.ts'))!.map((p) => [p.ref, p.confidence, p.lift])).toEqual([[ref('y.ts'), 0.5, 6.5], [ref('w.ts'), 0.5, 3.25]]);
118
+ });
119
+
120
+ it('options override the defaults', () => {
121
+ expect(coChangePartners(history, { maxPartners: 2 }).get(ref('h.ts'))).toHaveLength(2);
122
+ expect(coChangePartners(history, { minLift: 2.5 }).size).toBe(0);
123
+ });
124
+
125
+ it('computes intervals only for the kept partners', () => {
126
+ // Every kept partner carries its interval; the cut ones (p7, p8 of the hub) never reach the output.
127
+ for (const list of r.values()) for (const p of list) expect([p.low, p.high]).toEqual([round6(rateInterval(p.together, p.ofSelf).low), round6(rateInterval(p.together, p.ofSelf).high)]);
128
+ });
129
+
130
+ it('shuffled commits and refs give identical output', () => {
131
+ const shuffled = [...history].reverse().map((c) => ({ refs: [...c.refs].reverse() }));
132
+ same([...coChangePartners(shuffled)], [...r]);
133
+ expect([...r.keys()]).toEqual([...r.keys()].sort());
134
+ });
135
+ });
136
+
137
+ describe('coChangePartners — cost', () => {
138
+ // A loose guard: ~1–2 s here; the regression it catches (an interval solve per candidate pair) took hours.
139
+ it('2000 commits × 50 files over 4000 refs runs in under 10 s', () => {
140
+ // 80 clusters of 50 files, each committed 25 times: 98,000 kept pairs, 2.45M pair increments, every file at the cap.
141
+ const commits = Array.from({ length: 2000 }, (_, c) => ({ refs: Array.from({ length: 50 }, (_, i) => ref(`f${(c % 80) * 50 + i}.ts`)) }));
142
+ const t0 = Date.now();
143
+ const r = coChangePartners(commits);
144
+ const ms = Date.now() - t0;
145
+ expect(r.size).toBe(4000);
146
+ expect(r.get(ref('f0.ts'))).toHaveLength(COCHANGE_MAX_PARTNERS);
147
+ expect(ms).toBeLessThan(10_000);
148
+ });
149
+ });
150
+
151
+ describe('co-change badge codec (v1)', () => {
152
+ const partners = coChangePartners([...times(3, C('a.ts', 'b.ts')), ...times(3, C('a.ts', 'c d.ts')), ...fillers(20)]).get(ref('a.ts'))!;
153
+ const { low, high } = partners[0]!;
154
+
155
+ it('round-trips refs, counts, the interval and order behind a version line', () => {
156
+ const value = encodeCoChange(partners);
157
+ expect(value).toBe(`v1\n3\t6\t${low}\t${high}\t${ref('b.ts')}\n3\t6\t${low}\t${high}\t${ref('c d.ts')}`);
158
+ expect(decodeCoChange(value)).toEqual(partners.map((p) => ({ ref: p.ref, together: p.together, ofSelf: p.ofSelf, low: p.low, high: p.high })));
159
+ });
160
+
161
+ it.each([['a carriage return', 'c\r.ts'], ['U+2028', 'c
.ts'], ['U+2029', 'c
.ts']])('round-trips a ref holding %s', (_name, path) => {
162
+ // One bad line voids the badge, so a ref the line pattern rejected would drop every partner (and coChangeHidden with them).
163
+ const odd = [partners[0]!, { ...partners[0]!, ref: ref(path) }];
164
+ expect(decodeCoChange(encodeCoChange(odd)).map((e) => e.ref)).toEqual([ref('b.ts'), ref(path)]);
165
+ });
166
+
167
+ it('an empty list is the bare version line, which decodes to nothing', () => {
168
+ expect(encodeCoChange([])).toBe('v1');
169
+ expect(decodeCoChange('v1')).toEqual([]);
170
+ });
171
+
172
+ it.each([
173
+ ['a number', 3], ['undefined', undefined], ['an object', { a: 1 }], ['the empty string', ''],
174
+ ['no version line', `3\t6\t0.2\t0.8\t${ref('b.ts')}`], ['an unknown version', `v2\n3\t6\t0.2\t0.8\t${ref('b.ts')}`],
175
+ ['a non-numeric count', `v1\nx\t6\t0.2\t0.8\t${ref('b.ts')}`], ['a missing ref', 'v1\n3\t6\t0.2\t0.8\t'],
176
+ ['the old three-field line', `v1\n3\t6\t${ref('b.ts')}`],
177
+ ['together above ofSelf', `v1\n7\t6\t0.2\t0.8\t${ref('b.ts')}`], ['together 0', `v1\n0\t6\t0\t0.3\t${ref('b.ts')}`],
178
+ ['ofSelf 0', `v1\n0\t0\t0\t1\t${ref('b.ts')}`], ['low above high', `v1\n3\t6\t0.9\t0.8\t${ref('b.ts')}`],
179
+ ['high above 1', `v1\n3\t6\t0.2\t1.5\t${ref('b.ts')}`], ['one bad line among good ones', `v1\n3\t6\t0.2\t0.8\t${ref('b.ts')}\nnope`],
180
+ ])('decodes %s to []', (_name, value) => {
181
+ expect(decodeCoChange(value)).toEqual([]);
182
+ });
183
+ });
184
+
185
+ describe('coChangeRecallAtK', () => {
186
+ // 21 commits by `at`: i % 3 = 0 → {a,b}, 1 → {c,d}, 2 → a filler; commit 18 also touches e. 20% held out = the last 4
187
+ // (17..20). Fit on 0..16: a+b 6 times, c+d 6, 5 fillers, N = 17 (lift 6·17/36 = 2.83). Held-out cases: commit 18 {a,b,e}
188
+ // a → [b] covers 1 of {b,e} = 0.5, b → [a] 0.5, e has no partners (skipped); commit 19 {c,d}: 1 and 1. Mean 0.75 over 4.
189
+ const at = (i: number) => `2026-01-${String(i + 1).padStart(2, '0')}T00:00:00Z`;
190
+ const history: CoChangeCommit[] = Array.from({ length: 21 }, (_, i) => {
191
+ const paths = i % 3 === 0 ? ['a.ts', 'b.ts', ...(i === 18 ? ['e.ts'] : [])] : i % 3 === 1 ? ['c.ts', 'd.ts'] : [`z${i}.ts`];
192
+ return { at: at(i), refs: paths.map(ref) };
193
+ });
194
+
195
+ it('is the mean recall over held-out (commit, file) cases, counting the unpredicted ones as skipped', () => {
196
+ expect(coChangeRecallAtK(history)).toEqual({ recall: 0.75, cases: 4, skipped: 1 });
197
+ });
198
+
199
+ it('orders by the parsed time, not the input order nor the string', () => {
200
+ expect(coChangeRecallAtK([...history].reverse())).toEqual({ recall: 0.75, cases: 4, skipped: 1 });
201
+ // Hourly instants, the odd ones written at +05:00: as strings they would sort out of order ("T06:00+05:00" after "T02:00Z"),
202
+ // as times they keep the history's order.
203
+ const hourly = history.map((c, i) => {
204
+ const t = Date.UTC(2026, 0, 1) + i * 3_600_000;
205
+ return { ...c, at: i % 2 === 0 ? new Date(t).toISOString() : new Date(t + 5 * 3_600_000).toISOString().replace('Z', '+05:00') };
206
+ });
207
+ expect(hourly[1]!.at > hourly[2]!.at).toBe(true);
208
+ expect(coChangeRecallAtK([...hourly].reverse())).toEqual({ recall: 0.75, cases: 4, skipped: 1 });
209
+ });
210
+
211
+ it('undated input is taken oldest first, as given', () => {
212
+ expect(coChangeRecallAtK(history.map(({ refs }) => ({ refs })))).toEqual({ recall: 0.75, cases: 4, skipped: 1 });
213
+ });
214
+
215
+ it('is insufficient-data with nothing to hold out or nothing predicted', () => {
216
+ expect(coChangeRecallAtK(history.slice(0, 4))).toEqual({ status: 'insufficient-data' });
217
+ expect(coChangeRecallAtK(fillers(30))).toEqual({ status: 'insufficient-data' });
218
+ });
219
+
220
+ it('does not leak: coupling seen only in held-out commits is never predicted', () => {
221
+ // 16 training fillers, then 4 held-out a+b commits. The fit never sees a+b, so no case can be scored.
222
+ expect(coChangeRecallAtK([...fillers(16), ...times(4, C('a.ts', 'b.ts'))])).toEqual({ status: 'insufficient-data' });
223
+ });
224
+ });
225
+
226
+ describe('applyCoChangeHidden / buildGraph', () => {
227
+ const badge = (...paths: string[]) => encodeCoChange(paths.map((p) => ({ ref: ref(p), together: 3, ofSelf: 3, confidence: 1, lift: 2, low: 0.5, high: 1 })));
228
+
229
+ it('counts graph-node partners no live reference explains, either direction', () => {
230
+ const nodes = [
231
+ fileNode('a.ts', { badges: { coChange: badge('b.ts', 'c.ts', 'd.ts', 'gone.ts') } }),
232
+ fileNode('b.ts', { badges: { coChange: badge('a.ts') } }),
233
+ fileNode('c.ts', { badges: { coChange: badge('a.ts'), coChangeHidden: 9 } }),
234
+ fileNode('d.ts', { badges: { complexity: 2 } }),
235
+ ];
236
+ // b → a explains a~b both ways; the a → c edge is stale; d has no edge; gone.ts is no node, so it is not counted.
237
+ applyCoChangeHidden(nodes, [edge('b.ts', 'a.ts', 'references'), edge('a.ts', 'c.ts', 'references', { stale: true })]);
238
+ expect(nodes[0]!.badges!['coChangeHidden']).toBe(2);
239
+ expect(nodes[1]!.badges).toEqual({ coChange: badge('a.ts') });
240
+ expect(nodes[2]!.badges!['coChangeHidden']).toBe(1);
241
+ expect(nodes[3]!.badges).toEqual({ complexity: 2 });
242
+ });
243
+
244
+ it('is absent (never 0) when every partner is referenced, and on a malformed badge', () => {
245
+ const nodes = [fileNode('a.ts', { badges: { coChange: badge('b.ts') } }), fileNode('b.ts', { badges: { coChange: 'junk' } })];
246
+ applyCoChangeHidden(nodes, [edge('a.ts', 'b.ts', 'links')]);
247
+ expect(nodes.map((n) => n.badges!['coChangeHidden'])).toEqual([undefined, undefined]);
248
+ });
249
+
250
+ it('clears a stale coChangeHidden from a file that no longer carries coChange', () => {
251
+ const nodes = [fileNode('a.ts', { badges: { coChangeHidden: 3, complexity: 1 } }), fileNode('b.ts', { badges: { coChangeHidden: 2 } })];
252
+ applyCoChangeHidden(nodes, []);
253
+ expect(nodes[0]!.badges).toEqual({ complexity: 1 });
254
+ expect(nodes[1]!.badges).toBeUndefined();
255
+ });
256
+
257
+ it('a symbol-level reference rolls up to its file and explains the coupling', () => {
258
+ const nodes = [fileNode('a.ts', { badges: { coChange: badge('b.ts') } }), fileNode('b.ts')];
259
+ const symbolEdge: KEdge = { from: ref('a.ts#x'), to: ref('b.ts'), kind: 'references', weight: 1, origin: 'extracted' };
260
+ applyCoChangeHidden(nodes, [symbolEdge]);
261
+ expect(nodes[0]!.badges!['coChangeHidden']).toBeUndefined();
262
+ });
263
+
264
+ it('an edge to a node that is not a file (an out-of-root placeholder) explains the coupling too', () => {
265
+ const pkg = ref('node_modules/x/index.js');
266
+ const nodes = [
267
+ fileNode('a.ts', { badges: { coChange: encodeCoChange([{ ref: pkg, together: 3, ofSelf: 3, confidence: 1, lift: 2, low: 0.5, high: 1 }]) } }),
268
+ { ...fileNode('node_modules/x/index.js'), kind: 'missing' },
269
+ ];
270
+ applyCoChangeHidden(nodes, [edge('a.ts', 'node_modules/x/index.js', 'references')]);
271
+ expect(nodes[0]!.badges!['coChangeHidden']).toBeUndefined();
272
+ applyCoChangeHidden(nodes, []);
273
+ expect(nodes[0]!.badges!['coChangeHidden']).toBe(1);
274
+ });
275
+
276
+ function input(): BuildGraphInput {
277
+ return {
278
+ rootId: 'r', packs: [], facts: [], relations: [],
279
+ extracted: [
280
+ extractedOf(fileNode('a.ts', { badges: { coChange: badge('b.ts', 'c.ts') } }), [edge('a.ts', 'b.ts', 'references')]),
281
+ extractedOf(fileNode('b.ts')),
282
+ extractedOf(fileNode('c.ts', { badges: { coChange: badge('a.ts') } })),
283
+ ],
284
+ };
285
+ }
286
+
287
+ it('buildGraph stamps coChangeHidden and the outline carries both badges', () => {
288
+ const g = buildGraph(input());
289
+ const node = (p: string) => g.nodes.find((n) => n.ref === ref(p))!;
290
+ expect(node('a.ts').badges).toMatchObject({ coChange: badge('b.ts', 'c.ts'), coChangeHidden: 1 });
291
+ expect(node('c.ts').badges).toMatchObject({ coChangeHidden: 1 });
292
+ const o = buildOutline(g);
293
+ const file = (p: string) => o.files.find((f) => f.path.endsWith(p))!;
294
+ expect(file('a.ts').badges).toMatchObject({ coChange: badge('b.ts', 'c.ts'), coChangeHidden: 1 });
295
+ expect(decodeCoChange(file('a.ts').badges!['coChange']).map((e) => e.ref)).toEqual([ref('b.ts'), ref('c.ts')]);
296
+ });
297
+ });
@@ -0,0 +1,333 @@
1
+ /**
2
+ * knowledge/coChange.ts — co-change association over git history (PRD 38 P4: impact prediction).
3
+ *
4
+ * For files A and B over the N kept commits:
5
+ * support = together(A, B) (commits touching both; kept when ≥ COCHANGE_MIN_SUPPORT)
6
+ * confidence = P(B|A) = together / ofSelf(A), with its credible interval (`rateInterval`, ../stats)
7
+ * lift = P(A∧B) / (P(A)P(B)) = together·N / (ofSelf(A)·ofSelf(B)) (kept when ≥ COCHANGE_MIN_LIFT)
8
+ *
9
+ * A commit touching more than COCHANGE_MAX_COMMIT_FILES files (its whole-repo `fileCount` when given, else its distinct
10
+ * refs) is a bulk change and is dropped before anything is counted (it is not in N either); so is a commit touching no
11
+ * ref. Of the rest, the newest COCHANGE_MAX_COMMITS are kept. Each file keeps at most COCHANGE_MAX_PARTNERS partners,
12
+ * ranked confidence desc, lift desc, ref asc.
13
+ *
14
+ * History order: by `Date.parse(at)` (stable) when every commit has a parseable `at`; otherwise the input order, which
15
+ * must then be oldest first.
16
+ *
17
+ * Determinism: refs are deduped per commit and numbered in sorted order; pair counts are integers keyed by index;
18
+ * thresholds compare integers. Same commits in any order ⇒ identical output (when dated, or under the commit cap).
19
+ *
20
+ * The badge `coChange` is a string written ONLY by {@link encodeCoChange} and read ONLY by {@link decodeCoChange}.
21
+ * The caller (it holds the git history) stamps it; `buildGraph` then stamps `coChangeHidden`
22
+ * ({@link applyCoChangeHidden}): the partners that no reference explains.
23
+ */
24
+
25
+ import { rateInterval, type InsufficientData } from '../stats/index.js';
26
+ import { isReferenceEdge } from './communities.js';
27
+ import type { KEdge, KNode, NodeRef } from './model.js';
28
+ import { compareStr, fileRefOf, round6 } from './refs.js';
29
+
30
+ /** Commits a pair must share to be kept. */
31
+ export const COCHANGE_MIN_SUPPORT = 3;
32
+ /** Lift a pair must reach to be kept. */
33
+ export const COCHANGE_MIN_LIFT = 2;
34
+ /** A commit touching more files than this is a bulk change and is excluded. */
35
+ export const COCHANGE_MAX_COMMIT_FILES = 50;
36
+ /** Partners kept per file. */
37
+ export const COCHANGE_MAX_PARTNERS = 8;
38
+ /** At most this many (newest) commits are counted. */
39
+ export const COCHANGE_MAX_COMMITS = 5000;
40
+ /** The badge keys: the encoded partner list, and how many of them no reference explains. */
41
+ export const COCHANGE_BADGE = 'coChange';
42
+ export const COCHANGE_HIDDEN_BADGE = 'coChangeHidden';
43
+ /** First line of a badge value; a reader returns nothing for any other version. */
44
+ const BADGE_VERSION = 'v1';
45
+
46
+ export interface CoChangeCommit {
47
+ /** ISO time of the commit; orders the history. */
48
+ at?: string;
49
+ /** File node refs the commit touched (the caller maps paths to refs). */
50
+ refs: readonly NodeRef[];
51
+ /** Files the commit touched in the whole repo (refs only cover the root); the bulk cut uses the larger. */
52
+ fileCount?: number;
53
+ }
54
+
55
+ export interface CoChangePartner {
56
+ ref: NodeRef;
57
+ /** Kept commits touching both files. */
58
+ together: number;
59
+ /** Kept commits touching the file itself. */
60
+ ofSelf: number;
61
+ /** P(partner | self) = together / ofSelf, round6. */
62
+ confidence: number;
63
+ /** P(self ∧ partner) / (P(self) P(partner)), round6. */
64
+ lift: number;
65
+ /** Credible interval of the confidence (`rateInterval(together, ofSelf)`), round6. */
66
+ low: number;
67
+ high: number;
68
+ }
69
+
70
+ /** What the `coChange` badge carries per partner. */
71
+ export interface CoChangeBadgeEntry {
72
+ ref: NodeRef;
73
+ together: number;
74
+ ofSelf: number;
75
+ low: number;
76
+ high: number;
77
+ }
78
+
79
+ export interface CoChangeOptions {
80
+ minSupport?: number;
81
+ minLift?: number;
82
+ maxCommitFiles?: number;
83
+ maxPartners?: number;
84
+ maxCommits?: number;
85
+ }
86
+
87
+ /** `skipped`: held-out (commit, file) cases whose file had no partners to predict with. */
88
+ export type CoChangeRecall = { recall: number; cases: number; skipped: number } | InsufficientData;
89
+
90
+ type KeptCommit = { refs: NodeRef[] };
91
+
92
+ /** The history oldest first: by parsed `at` (stable) when every commit is dated, else as given. */
93
+ function chronological(commits: ReadonlyArray<CoChangeCommit>): CoChangeCommit[] {
94
+ const times = commits.map((c) => (c.at === undefined ? Number.NaN : Date.parse(c.at)));
95
+ if (!times.every(Number.isFinite)) return [...commits];
96
+ return commits.map((c, i) => ({ c, i, t: times[i]! })).sort((a, b) => a.t - b.t || a.i - b.i).map((x) => x.c);
97
+ }
98
+
99
+ /** Oldest first: each commit's distinct refs (sorted), bulk and empty commits dropped, the newest `maxCommits` kept. */
100
+ function historyOf(commits: ReadonlyArray<CoChangeCommit>, opts: CoChangeOptions): KeptCommit[] {
101
+ const maxFiles = opts.maxCommitFiles ?? COCHANGE_MAX_COMMIT_FILES;
102
+ const out: KeptCommit[] = [];
103
+ for (const c of chronological(commits)) {
104
+ const refs = [...new Set(c.refs)].sort(compareStr);
105
+ if (refs.length === 0 || Math.max(c.fileCount ?? 0, refs.length) > maxFiles) continue;
106
+ out.push({ refs });
107
+ }
108
+ const max = opts.maxCommits ?? COCHANGE_MAX_COMMITS;
109
+ return out.length > max ? out.slice(out.length - max) : out;
110
+ }
111
+
112
+ const imul = Math.imul;
113
+
114
+ /**
115
+ * Counts (i, j) index pairs in an open-addressing table: one Int32Array of [i, j, count] slots (i = -1 is empty), so a probe
116
+ * touches one cache line and no pair allocates or boxes a key — where a `Map` spent most of the time on a 50-file commit's
117
+ * 1,225 pairs. Linear probing, grown at half load.
118
+ */
119
+ class PairCounter {
120
+ private cap = 1 << 12;
121
+ private slots = PairCounter.empty(this.cap);
122
+ private size = 0;
123
+
124
+ add(i: number, j: number): void {
125
+ if ((this.size + 1) * 2 > this.cap) this.grow();
126
+ const mask = this.cap - 1;
127
+ const slots = this.slots;
128
+ for (let s = PairCounter.hash(i, j) & mask; ; s = (s + 1) & mask) {
129
+ const at = s * 3;
130
+ const si = slots[at]!;
131
+ if (si === -1) {
132
+ slots[at] = i; slots[at + 1] = j; slots[at + 2] = 1; this.size += 1;
133
+ return;
134
+ }
135
+ if (si === i && slots[at + 1] === j) { slots[at + 2]! += 1; return; }
136
+ }
137
+ }
138
+
139
+ forEach(fn: (i: number, j: number, count: number) => void): void {
140
+ const slots = this.slots;
141
+ for (let at = 0; at < slots.length; at += 3) if (slots[at] !== -1) fn(slots[at]!, slots[at + 1]!, slots[at + 2]!);
142
+ }
143
+
144
+ private grow(): void {
145
+ const old = this.slots;
146
+ this.cap *= 2;
147
+ this.slots = PairCounter.empty(this.cap);
148
+ const mask = this.cap - 1;
149
+ for (let from = 0; from < old.length; from += 3) {
150
+ if (old[from] === -1) continue;
151
+ let s = PairCounter.hash(old[from]!, old[from + 1]!) & mask;
152
+ while (this.slots[s * 3] !== -1) s = (s + 1) & mask;
153
+ this.slots.set(old.subarray(from, from + 3), s * 3);
154
+ }
155
+ }
156
+
157
+ private static empty(cap: number): Int32Array {
158
+ const slots = new Int32Array(cap * 3);
159
+ for (let at = 0; at < slots.length; at += 3) slots[at] = -1;
160
+ return slots;
161
+ }
162
+
163
+ /** murmur3's 32-bit finaliser over the two indexes. */
164
+ private static hash(i: number, j: number): number {
165
+ let h = imul(i, 0x9e3779b1) ^ j;
166
+ h ^= h >>> 16; h = imul(h, 0x85ebca6b);
167
+ h ^= h >>> 13; h = imul(h, 0xc2b2ae35);
168
+ return (h ^ (h >>> 16)) >>> 0;
169
+ }
170
+ }
171
+
172
+ const byRank = (a: Pick<CoChangePartner, 'confidence' | 'lift' | 'ref'>, b: Pick<CoChangePartner, 'confidence' | 'lift' | 'ref'>): number =>
173
+ b.confidence - a.confidence || b.lift - a.lift || compareStr(a.ref, b.ref);
174
+
175
+ /** Partners over an already-kept history. */
176
+ function partnersOf(kept: readonly KeptCommit[], opts: CoChangeOptions): Map<NodeRef, CoChangePartner[]> {
177
+ const minSupport = opts.minSupport ?? COCHANGE_MIN_SUPPORT;
178
+ const minLift = opts.minLift ?? COCHANGE_MIN_LIFT;
179
+ const maxPartners = opts.maxPartners ?? COCHANGE_MAX_PARTNERS;
180
+ const n = kept.length;
181
+
182
+ // Pass 1: ofSelf. A file seen in fewer than minSupport commits can be in no kept pair, so pass 2 skips it.
183
+ const order = [...new Set(kept.flatMap((c) => c.refs))].sort(compareStr);
184
+ const index = new Map(order.map((r, i) => [r, i] as const));
185
+ const m = order.length;
186
+ const ofSelf = new Array<number>(m).fill(0);
187
+ for (const c of kept) for (const r of c.refs) ofSelf[index.get(r)!]! += 1;
188
+
189
+ // Pass 2: pair counts over index pairs (i < j).
190
+ const pairs = new PairCounter();
191
+ for (const c of kept) {
192
+ const ids = c.refs.map((r) => index.get(r)!).filter((i) => ofSelf[i]! >= minSupport); // sorted refs ⇒ ascending ids
193
+ for (let x = 0; x < ids.length; x++) {
194
+ for (let y = x + 1; y < ids.length; y++) pairs.add(ids[x]!, ids[y]!);
195
+ }
196
+ }
197
+
198
+ // Candidates carry only counts and the ranking keys; the interval (an iterative inverse-beta solve) is computed after the
199
+ // cap, for at most maxPartners per file, and memoised by (together, ofSelf) for this call.
200
+ type Candidate = Omit<CoChangePartner, 'low' | 'high'>;
201
+ const lists = new Map<number, Candidate[]>();
202
+ const add = (self: number, other: number, together: number, lift: number) => {
203
+ const list = lists.get(self) ?? [];
204
+ list.push({ ref: order[other]!, together, ofSelf: ofSelf[self]!, confidence: round6(together / ofSelf[self]!), lift });
205
+ lists.set(self, list);
206
+ };
207
+ // Slot order is arbitrary; every list is fully sorted (ref breaks the last tie), so the output is not.
208
+ pairs.forEach((i, j, together) => {
209
+ if (together < minSupport) return;
210
+ // lift ≥ minLift ⇔ together·N ≥ minLift·ofSelf(i)·ofSelf(j): no float at the threshold.
211
+ if (together * n < minLift * ofSelf[i]! * ofSelf[j]!) return;
212
+ const lift = round6((together * n) / (ofSelf[i]! * ofSelf[j]!));
213
+ add(i, j, together, lift);
214
+ add(j, i, together, lift);
215
+ });
216
+
217
+ const intervals = new Map<number, { low: number; high: number }>();
218
+ const intervalOf = (k: number, total: number) => {
219
+ const key = k * (n + 1) + total; // k, total ≤ n
220
+ let hit = intervals.get(key);
221
+ if (!hit) {
222
+ const { low, high } = rateInterval(k, total);
223
+ hit = { low: round6(low), high: round6(high) };
224
+ intervals.set(key, hit);
225
+ }
226
+ return hit;
227
+ };
228
+ const out = new Map<NodeRef, CoChangePartner[]>();
229
+ for (const i of [...lists.keys()].sort((a, b) => a - b)) {
230
+ const kept = lists.get(i)!.sort(byRank).slice(0, maxPartners);
231
+ out.set(order[i]!, kept.map((c) => ({ ...c, ...intervalOf(c.together, c.ofSelf) })));
232
+ }
233
+ return out;
234
+ }
235
+
236
+ /** Every file's co-change partners (only files with at least one kept partner appear), keys in ref order. */
237
+ export function coChangePartners(commits: ReadonlyArray<CoChangeCommit>, opts: CoChangeOptions = {}): Map<NodeRef, CoChangePartner[]> {
238
+ return partnersOf(historyOf(commits, opts), opts);
239
+ }
240
+
241
+ /**
242
+ * The `coChange` badge value: the line `v1`, then `${together}\t${ofSelf}\t${low}\t${high}\t${ref}` per partner, '\n'-joined
243
+ * (the ref is the line remainder). A ref holding a newline cannot be carried and is skipped.
244
+ */
245
+ export function encodeCoChange(partners: readonly CoChangePartner[]): string {
246
+ const lines = partners.filter((p) => !p.ref.includes('\n')).map((p) => `${p.together}\t${p.ofSelf}\t${p.low}\t${p.high}\t${p.ref}`);
247
+ return [BADGE_VERSION, ...lines].join('\n');
248
+ }
249
+
250
+ const NUM = String.raw`(\d+(?:\.\d+)?(?:e-\d+)?)`;
251
+ // `s`: the ref is the line remainder and may hold '\r', U+2028 or U+2029 (the value is already split on '\n').
252
+ const LINE = new RegExp(String.raw`^(\d+)\t(\d+)\t${NUM}\t${NUM}\t(.+)$`, 's');
253
+
254
+ /** The partners of a `coChange` badge; [] for anything that is not a well-formed v1 value (one bad line voids it). */
255
+ export function decodeCoChange(value: unknown): CoChangeBadgeEntry[] {
256
+ if (typeof value !== 'string') return [];
257
+ const [version, ...lines] = value.split('\n');
258
+ if (version !== BADGE_VERSION) return [];
259
+ const out: CoChangeBadgeEntry[] = [];
260
+ for (const line of lines) {
261
+ const hit = LINE.exec(line);
262
+ if (!hit) return [];
263
+ const together = Number(hit[1]), ofSelf = Number(hit[2]), low = Number(hit[3]), high = Number(hit[4]);
264
+ if (!Number.isSafeInteger(together) || !Number.isSafeInteger(ofSelf) || together < 1 || together > ofSelf) return [];
265
+ if (!(low >= 0 && low <= high && high <= 1)) return [];
266
+ out.push({ ref: hit[5]! as NodeRef, together, ofSelf, low, high });
267
+ }
268
+ return out;
269
+ }
270
+
271
+ /**
272
+ * The PRD's accept measure: fit on the older (1 − heldOutShare) kept commits, then for each held-out commit and each file A
273
+ * in it that has partners, recall = |top-k partners ∩ (commit − A)| / |commit − A|; the mean over those cases. A held-out
274
+ * file with no partners is counted in `skipped`. Insufficient data when nothing can be held out or no case is predicted.
275
+ */
276
+ export function coChangeRecallAtK(
277
+ commits: ReadonlyArray<CoChangeCommit>, k: number = COCHANGE_MAX_PARTNERS, heldOutShare = 0.2, opts: CoChangeOptions = {},
278
+ ): CoChangeRecall {
279
+ const insufficient: InsufficientData = { status: 'insufficient-data' };
280
+ const kept = historyOf(commits, opts);
281
+ const held = Math.floor(kept.length * heldOutShare);
282
+ if (held < 1 || held >= kept.length || k < 1) return insufficient;
283
+ const model = partnersOf(kept.slice(0, kept.length - held), { ...opts, maxPartners: k });
284
+ let sum = 0, cases = 0, skipped = 0;
285
+ for (const c of kept.slice(kept.length - held)) {
286
+ if (c.refs.length < 2) continue;
287
+ for (const a of c.refs) {
288
+ const predicted = model.get(a);
289
+ if (!predicted || predicted.length === 0) { skipped += 1; continue; }
290
+ const others = new Set(c.refs.filter((r) => r !== a));
291
+ sum += predicted.filter((p) => others.has(p.ref)).length / others.size;
292
+ cases += 1;
293
+ }
294
+ }
295
+ return cases === 0 ? insufficient : { recall: round6(sum / cases), cases, skipped };
296
+ }
297
+
298
+ /**
299
+ * The one call `buildGraph` makes: on every file node carrying a `coChange` badge, `coChangeHidden` = how many of its
300
+ * partners (that are nodes of the graph) share no reference with it — a live COMMUNITY_EDGE_KINDS edge in either direction,
301
+ * both ends rolled up to their file (a symbol or section ref counts for its file; an out-of-root placeholder explains too).
302
+ * Absent when 0, and removed from a file that no longer carries `coChange`.
303
+ */
304
+ export function applyCoChangeHidden(nodes: Iterable<KNode>, edges: Iterable<KEdge>): void {
305
+ const all = new Map<NodeRef, KNode>();
306
+ for (const n of nodes) all.set(n.ref, n);
307
+ const explained = new Map<NodeRef, Set<NodeRef>>();
308
+ const link = (a: NodeRef, b: NodeRef) => {
309
+ const set = explained.get(a) ?? new Set<NodeRef>();
310
+ set.add(b);
311
+ explained.set(a, set);
312
+ };
313
+ for (const e of edges) {
314
+ if (!isReferenceEdge(e)) continue;
315
+ const a = fileRefOf(e.from), b = fileRefOf(e.to);
316
+ if (a === b) continue;
317
+ link(a, b);
318
+ link(b, a);
319
+ }
320
+ for (const n of all.values()) {
321
+ if (n.kind !== 'file' || !n.badges) continue;
322
+ const value = n.badges[COCHANGE_BADGE];
323
+ const near = explained.get(n.ref);
324
+ const hidden = value === undefined
325
+ ? 0
326
+ : decodeCoChange(value).filter((p) => p.ref !== n.ref && all.has(p.ref) && !near?.has(p.ref)).length;
327
+ const badges = { ...n.badges };
328
+ if (hidden > 0) badges[COCHANGE_HIDDEN_BADGE] = hidden;
329
+ else delete badges[COCHANGE_HIDDEN_BADGE];
330
+ if (Object.keys(badges).length > 0) n.badges = badges;
331
+ else delete n.badges;
332
+ }
333
+ }
@@ -77,6 +77,11 @@ export function detectCommunities(
77
77
  return { members, modularity: modularityOf(adj, comm), method };
78
78
  }
79
79
 
80
+ /** THE test of "this edge is a reference between files" (a live edge of COMMUNITY_EDGE_KINDS); coChange.ts reads it too. */
81
+ export function isReferenceEdge(e: Pick<KEdge, 'kind' | 'stale'>): boolean {
82
+ return COMMUNITY_EDGE_KINDS.includes(e.kind) && !e.stale;
83
+ }
84
+
80
85
  /**
81
86
  * File-to-file links of the chosen kinds, merged per ordered pair. The weights of a pair are summed in ascending
82
87
  * order, so the total never depends on the order the edges arrive in (the sort across pairs is `buildAdjacency`'s).
@@ -84,7 +89,7 @@ export function detectCommunities(
84
89
  function fileLinks(files: ReadonlySet<NodeRef>, edges: Iterable<KEdge>): Array<{ from: NodeRef; to: NodeRef; weight: number }> {
85
90
  const pairs = new Map<string, { from: NodeRef; to: NodeRef; weights: number[] }>();
86
91
  for (const e of edges) {
87
- if (!COMMUNITY_EDGE_KINDS.includes(e.kind) || e.stale) continue;
92
+ if (!isReferenceEdge(e)) continue;
88
93
  const from = fileRefOf(e.from), to = fileRefOf(e.to);
89
94
  if (!files.has(from) || !files.has(to)) continue;
90
95
  const key = `${from}\u0000${to}`;