@seanhogg/builderforce-memory 2026.10.67 → 2026.10.68

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 (105) hide show
  1. package/dist/knowledge/comparability.d.ts +100 -0
  2. package/dist/knowledge/comparability.d.ts.map +1 -0
  3. package/dist/knowledge/comparability.js +149 -0
  4. package/dist/knowledge/comparability.js.map +1 -0
  5. package/dist/knowledge/contentHash.d.ts +28 -0
  6. package/dist/knowledge/contentHash.d.ts.map +1 -0
  7. package/dist/knowledge/contentHash.js +54 -0
  8. package/dist/knowledge/contentHash.js.map +1 -0
  9. package/dist/knowledge/extractFile.d.ts +2 -0
  10. package/dist/knowledge/extractFile.d.ts.map +1 -1
  11. package/dist/knowledge/extractFile.js +1 -1
  12. package/dist/knowledge/extractFile.js.map +1 -1
  13. package/dist/knowledge/extractJob.d.ts +5 -2
  14. package/dist/knowledge/extractJob.d.ts.map +1 -1
  15. package/dist/knowledge/extractJob.js +1 -1
  16. package/dist/knowledge/extractJob.js.map +1 -1
  17. package/dist/knowledge/findingBuilder.d.ts +12 -2
  18. package/dist/knowledge/findingBuilder.d.ts.map +1 -1
  19. package/dist/knowledge/findingBuilder.js +9 -2
  20. package/dist/knowledge/findingBuilder.js.map +1 -1
  21. package/dist/knowledge/findingIdentity.d.ts +52 -0
  22. package/dist/knowledge/findingIdentity.d.ts.map +1 -0
  23. package/dist/knowledge/findingIdentity.js +70 -0
  24. package/dist/knowledge/findingIdentity.js.map +1 -0
  25. package/dist/knowledge/findingModel.d.ts +30 -0
  26. package/dist/knowledge/findingModel.d.ts.map +1 -0
  27. package/dist/knowledge/findingModel.js +6 -0
  28. package/dist/knowledge/findingModel.js.map +1 -0
  29. package/dist/knowledge/findings.d.ts.map +1 -1
  30. package/dist/knowledge/findings.js +17 -9
  31. package/dist/knowledge/findings.js.map +1 -1
  32. package/dist/knowledge/godModule.js +2 -2
  33. package/dist/knowledge/godModule.js.map +1 -1
  34. package/dist/knowledge/index.d.ts +11 -0
  35. package/dist/knowledge/index.d.ts.map +1 -1
  36. package/dist/knowledge/index.js +7 -0
  37. package/dist/knowledge/index.js.map +1 -1
  38. package/dist/knowledge/lineage.d.ts +35 -0
  39. package/dist/knowledge/lineage.d.ts.map +1 -0
  40. package/dist/knowledge/lineage.js +114 -0
  41. package/dist/knowledge/lineage.js.map +1 -0
  42. package/dist/knowledge/merkle.d.ts +65 -0
  43. package/dist/knowledge/merkle.d.ts.map +1 -0
  44. package/dist/knowledge/merkle.js +158 -0
  45. package/dist/knowledge/merkle.js.map +1 -0
  46. package/dist/knowledge/model.d.ts +3 -16
  47. package/dist/knowledge/model.d.ts.map +1 -1
  48. package/dist/knowledge/owedFiles.d.ts +5 -2
  49. package/dist/knowledge/owedFiles.d.ts.map +1 -1
  50. package/dist/knowledge/owedFiles.js +20 -5
  51. package/dist/knowledge/owedFiles.js.map +1 -1
  52. package/dist/knowledge/plan.d.ts +8 -0
  53. package/dist/knowledge/plan.d.ts.map +1 -1
  54. package/dist/knowledge/plan.js +20 -6
  55. package/dist/knowledge/plan.js.map +1 -1
  56. package/dist/knowledge/refs.d.ts +4 -0
  57. package/dist/knowledge/refs.d.ts.map +1 -1
  58. package/dist/knowledge/refs.js +8 -0
  59. package/dist/knowledge/refs.js.map +1 -1
  60. package/dist/knowledge/resolve.d.ts.map +1 -1
  61. package/dist/knowledge/resolve.js +2 -0
  62. package/dist/knowledge/resolve.js.map +1 -1
  63. package/dist/knowledge/reviewModel.d.ts +8 -1
  64. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  65. package/dist/knowledge/reviewPrefetch.d.ts +2 -1
  66. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
  67. package/dist/knowledge/reviewPrefetch.js +8 -4
  68. package/dist/knowledge/reviewPrefetch.js.map +1 -1
  69. package/dist/knowledge/sources.d.ts +10 -1
  70. package/dist/knowledge/sources.d.ts.map +1 -1
  71. package/dist/knowledge/sources.js +17 -2
  72. package/dist/knowledge/sources.js.map +1 -1
  73. package/package.json +1 -1
  74. package/src/contract/exports.snapshot.json +28 -0
  75. package/src/contract/regression.contentHash.test.ts +30 -0
  76. package/src/contract/regression.lineage.test.ts +27 -0
  77. package/src/contract/regression.listing.test.ts +85 -0
  78. package/src/contract/types.contract.test.ts +57 -0
  79. package/src/knowledge/comparability.analysis.test.ts +73 -0
  80. package/src/knowledge/comparability.test.ts +44 -0
  81. package/src/knowledge/comparability.ts +182 -0
  82. package/src/knowledge/contentHash.test.ts +81 -0
  83. package/src/knowledge/contentHash.ts +55 -0
  84. package/src/knowledge/extractFile.ts +4 -2
  85. package/src/knowledge/extractJob.ts +5 -3
  86. package/src/knowledge/findingBuilder.ts +17 -2
  87. package/src/knowledge/findingIdentity.test.ts +102 -0
  88. package/src/knowledge/findingIdentity.ts +92 -0
  89. package/src/knowledge/findingModel.ts +32 -0
  90. package/src/knowledge/findings.ts +17 -9
  91. package/src/knowledge/godModule.ts +2 -2
  92. package/src/knowledge/index.ts +17 -0
  93. package/src/knowledge/lineage.test.ts +106 -0
  94. package/src/knowledge/lineage.ts +123 -0
  95. package/src/knowledge/merkle.test.ts +137 -0
  96. package/src/knowledge/merkle.ts +164 -0
  97. package/src/knowledge/model.ts +4 -18
  98. package/src/knowledge/owedFiles.contentHash.test.ts +58 -0
  99. package/src/knowledge/owedFiles.ts +23 -5
  100. package/src/knowledge/plan.ts +28 -6
  101. package/src/knowledge/refs.ts +10 -0
  102. package/src/knowledge/resolve.ts +2 -0
  103. package/src/knowledge/reviewModel.ts +8 -1
  104. package/src/knowledge/reviewPrefetch.ts +10 -6
  105. package/src/knowledge/sources.ts +20 -2
@@ -0,0 +1,123 @@
1
+ /**
2
+ * knowledge/lineage.ts — the ONE deterministic lineage matcher (PRD 41 §C3), between the findings of
3
+ * two sides of a run:
4
+ *
5
+ * 1. Exact `id` match → `persisting`.
6
+ * 2. Same `anchor` → `changed`, sub-kind `grew` / `shrank` (member count) or `moved` (equal counts,
7
+ * different members). Several findings on one anchor pair in ascending id order.
8
+ * 3. Same kind AND same anchor kind, TWO OR MORE members on both sides, member-set Jaccard ≥ 0.5 →
9
+ * `changed`. Pairs are taken greedily by descending Jaccard, then ascending before id, then
10
+ * ascending after id. A single-member finding never matches here, so two unrelated findings in
11
+ * one file are never "changed".
12
+ * 4. The rest → `introduced` (after only) or `resolved` (before only). Comparability (C9) is the
13
+ * caller's: a `not_comparable` kind must not be fed here.
14
+ *
15
+ * Input order never matters: each side is deduped by id (first kept) and sorted first. Jaccard is
16
+ * compared as exact integer ratios, so no float enters an ordering.
17
+ */
18
+
19
+ import type { FindingIdentity } from './findingIdentity.js';
20
+ import { kindOfAnchor } from './findingIdentity.js';
21
+ import { compareStr } from './refs.js';
22
+
23
+ export type Lineage = 'introduced' | 'resolved' | 'changed' | 'persisting';
24
+ export type LineageChange = 'grew' | 'shrank' | 'moved';
25
+
26
+ export interface LineageEntry {
27
+ lineage: Lineage;
28
+ /** Only on anchor (rule 2) matches whose members differ. */
29
+ change?: LineageChange;
30
+ /** The before finding's id (absent for `introduced`). */
31
+ before?: string;
32
+ /** The after finding's id (absent for `resolved`). */
33
+ after?: string;
34
+ }
35
+
36
+ /** Rule 3's member-set Jaccard floor (compared as `inter >= floor × union`, exact in binary). */
37
+ export const LINEAGE_MIN_JACCARD = 0.5;
38
+ /** Rule 3 needs at least this many members on BOTH sides. */
39
+ export const LINEAGE_MIN_MEMBERS = 2;
40
+
41
+ /** Orders two identities of one id by (anchor, members), so which one {@link uniqueSorted} keeps never depends on input order. */
42
+ const compareIdentity = (a: FindingIdentity, b: FindingIdentity): number =>
43
+ compareStr(a.anchor, b.anchor) || compareStr(JSON.stringify(a.members), JSON.stringify(b.members));
44
+
45
+ /** One identity per id — the minimum by (anchor, members) — sorted by id. */
46
+ function uniqueSorted(list: readonly FindingIdentity[]): FindingIdentity[] {
47
+ const byId = new Map<string, FindingIdentity>();
48
+ for (const f of list) {
49
+ const kept = byId.get(f.id);
50
+ if (!kept || compareIdentity(f, kept) < 0) byId.set(f.id, f);
51
+ }
52
+ return [...byId.values()].sort((a, b) => compareStr(a.id, b.id));
53
+ }
54
+
55
+ function changeOf(before: FindingIdentity, after: FindingIdentity): LineageChange | undefined {
56
+ const b = new Set(before.members), a = new Set(after.members);
57
+ if (a.size > b.size) return 'grew';
58
+ if (a.size < b.size) return 'shrank';
59
+ for (const m of a) if (!b.has(m)) return 'moved';
60
+ return undefined;
61
+ }
62
+
63
+ /** |A ∩ B| and |A ∪ B| of two member lists. */
64
+ function overlap(a: readonly string[], b: readonly string[]): { inter: number; union: number } {
65
+ const sa = new Set(a), sb = new Set(b);
66
+ let inter = 0;
67
+ for (const m of sa) if (sb.has(m)) inter++;
68
+ return { inter, union: sa.size + sb.size - inter };
69
+ }
70
+
71
+ interface Candidate { before: FindingIdentity; after: FindingIdentity; inter: number; union: number }
72
+
73
+ const groupKey = (f: FindingIdentity) => `${kindOfAnchor(f.anchor)}\u0000${f.anchorKind}`;
74
+
75
+ export function matchLineage(before: readonly FindingIdentity[], after: readonly FindingIdentity[]): LineageEntry[] {
76
+ const b = uniqueSorted(before), a = uniqueSorted(after);
77
+ const out: LineageEntry[] = [];
78
+ const usedB = new Set<string>(), usedA = new Set<string>();
79
+ const pair = (x: FindingIdentity, y: FindingIdentity, entry: LineageEntry) => { usedB.add(x.id); usedA.add(y.id); out.push(entry); };
80
+
81
+ // Rule 1: exact id.
82
+ const afterIds = new Set(a.map((f) => f.id));
83
+ for (const f of b) if (afterIds.has(f.id)) pair(f, f, { lineage: 'persisting', before: f.id, after: f.id });
84
+
85
+ // Rule 2: same anchor, paired in ascending id order within the anchor.
86
+ const byAnchor = (list: FindingIdentity[], used: Set<string>) => {
87
+ const m = new Map<string, FindingIdentity[]>();
88
+ for (const f of list) if (!used.has(f.id)) (m.get(f.anchor) ?? m.set(f.anchor, []).get(f.anchor)!).push(f);
89
+ return m;
90
+ };
91
+ const afterByAnchor = byAnchor(a, usedA);
92
+ for (const [anchor, olds] of [...byAnchor(b, usedB)].sort((x, y) => compareStr(x[0], y[0]))) {
93
+ const news = afterByAnchor.get(anchor) ?? [];
94
+ for (let i = 0; i < Math.min(olds.length, news.length); i++) {
95
+ const change = changeOf(olds[i]!, news[i]!);
96
+ pair(olds[i]!, news[i]!, { lineage: 'changed', ...(change ? { change } : {}), before: olds[i]!.id, after: news[i]!.id });
97
+ }
98
+ }
99
+
100
+ // Rule 3: same kind + anchor kind, ≥2 members both sides, Jaccard ≥ 0.5; greedy.
101
+ const eligible = (f: FindingIdentity) => new Set(f.members).size >= LINEAGE_MIN_MEMBERS;
102
+ const afterByGroup = new Map<string, FindingIdentity[]>();
103
+ for (const f of a) if (!usedA.has(f.id) && eligible(f)) (afterByGroup.get(groupKey(f)) ?? afterByGroup.set(groupKey(f), []).get(groupKey(f))!).push(f);
104
+ const candidates: Candidate[] = [];
105
+ for (const x of b) {
106
+ if (usedB.has(x.id) || !eligible(x)) continue;
107
+ for (const y of afterByGroup.get(groupKey(x)) ?? []) {
108
+ const { inter, union } = overlap(x.members, y.members);
109
+ if (union > 0 && inter >= LINEAGE_MIN_JACCARD * union) candidates.push({ before: x, after: y, inter, union });
110
+ }
111
+ }
112
+ candidates.sort((p, q) => q.inter * p.union - p.inter * q.union || compareStr(p.before.id, q.before.id) || compareStr(p.after.id, q.after.id));
113
+ for (const c of candidates) {
114
+ if (usedB.has(c.before.id) || usedA.has(c.after.id)) continue;
115
+ pair(c.before, c.after, { lineage: 'changed', before: c.before.id, after: c.after.id });
116
+ }
117
+
118
+ // Rule 4: the remainder.
119
+ for (const f of b) if (!usedB.has(f.id)) out.push({ lineage: 'resolved', before: f.id });
120
+ for (const f of a) if (!usedA.has(f.id)) out.push({ lineage: 'introduced', after: f.id });
121
+
122
+ return out.sort((p, q) => compareStr(p.after ?? p.before!, q.after ?? q.before!) || compareStr(p.before ?? '', q.before ?? ''));
123
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * src/knowledge/merkle.test.ts — directory Merkle hashes (PRD 41 §B2 step 4).
3
+ */
4
+
5
+ import { jest } from '@jest/globals';
6
+ import { canonicalListing, changedPaths, merkleTree, type MerkleTree } from './merkle.js';
7
+
8
+ const FILES = [
9
+ { path: 'README.md', hash: 'h-readme' },
10
+ { path: 'src/a.ts', hash: 'h-a' },
11
+ { path: 'src/lib/b.ts', hash: 'h-b' },
12
+ { path: 'src/lib/c.ts', hash: 'h-c' },
13
+ { path: 'docs/guide/intro.md', hash: 'h-intro' },
14
+ { path: 'docs/guide/deep/more.md', hash: 'h-more' },
15
+ ];
16
+
17
+ /** A copy of `files` with `path` at a new hash. */
18
+ const edited = (files: typeof FILES, path: string, hash: string) => files.map((f) => (f.path === path ? { path, hash } : f));
19
+
20
+ describe('merkleTree', () => {
21
+ it('gives the same root and dirs for any input order', () => {
22
+ const a = merkleTree(FILES);
23
+ const b = merkleTree([...FILES].reverse());
24
+ expect(b.root).toBe(a.root);
25
+ expect([...b.dirs]).toEqual([...a.dirs]);
26
+ expect(a.dirs.get('')).toBe(a.root);
27
+ expect([...a.dirs.keys()].sort()).toEqual(['', 'docs', 'docs/guide', 'docs/guide/deep', 'src', 'src/lib']);
28
+ });
29
+
30
+ it('normalizes paths: backslashes, a leading ./, NFC', () => {
31
+ const a = merkleTree([{ path: 'src/café.ts', hash: 'h' }]);
32
+ expect(merkleTree([{ path: '.\\src\\café.ts', hash: 'h' }]).root).toBe(a.root);
33
+ });
34
+
35
+ it('sorts entries bytewise (code-point order), not by UTF-16 unit', () => {
36
+ const tree = merkleTree([{ path: '\u{1F600}.md', hash: 'h1' }, { path: '~.md', hash: 'h2' }, { path: 'Z.md', hash: 'h3' }]);
37
+ expect(tree.entries.get('')!.map((e) => e.name)).toEqual(['Z.md', '~.md', '\u{1F600}.md']);
38
+ });
39
+
40
+ it('a file change changes only its ancestors', () => {
41
+ const before = merkleTree(FILES);
42
+ const after = merkleTree(edited(FILES, 'src/lib/b.ts', 'h-b2'));
43
+ expect(after.root).not.toBe(before.root);
44
+ for (const dir of before.dirs.keys()) {
45
+ const ancestor = dir === '' || dir === 'src' || dir === 'src/lib';
46
+ expect({ dir, changed: after.dirs.get(dir) !== before.dirs.get(dir) }).toEqual({ dir, changed: ancestor });
47
+ }
48
+ });
49
+
50
+ it('a file and a directory of one name differ in kind, so they never hash alike', () => {
51
+ expect(merkleTree([{ path: 'x', hash: 'h' }]).root).not.toBe(merkleTree([{ path: 'x/y', hash: 'h' }]).root);
52
+ });
53
+
54
+ it('refuses a path listed twice at different hashes, or as both a file and a directory', () => {
55
+ expect(() => merkleTree([{ path: 'a', hash: '1' }, { path: 'a', hash: '2' }])).toThrow(/listed twice/);
56
+ expect(() => merkleTree([{ path: 'a', hash: '1' }, { path: 'a/b', hash: '2' }])).toThrow(/file and a directory/);
57
+ expect(() => merkleTree([{ path: 'a/b', hash: '2' }, { path: 'a', hash: '1' }])).toThrow(/file and a directory/);
58
+ expect(() => merkleTree([{ path: 'a//b', hash: '1' }])).toThrow(/not a file path/);
59
+ expect(() => merkleTree([{ path: 'a/./b', hash: '1' }])).toThrow(/not a file path/);
60
+ expect(() => merkleTree([{ path: 'a/../b', hash: '1' }])).toThrow(/not a file path/);
61
+ expect(() => merkleTree([{ path: '..', hash: '1' }])).toThrow(/not a file path/);
62
+ expect(merkleTree([{ path: 'a', hash: '1' }, { path: 'a', hash: '1' }]).root).toBe(merkleTree([{ path: 'a', hash: '1' }]).root);
63
+ });
64
+
65
+ it('an empty listing has a root', () => {
66
+ expect(merkleTree([]).root).toMatch(/^[0-9a-f]{64}$/);
67
+ });
68
+ });
69
+
70
+ describe('canonicalListing', () => {
71
+ const NFC = 'café.md', NFD = 'café.md';
72
+
73
+ it('keeps the first of a colliding pair by (normalized, listed) bytewise, in any input order, and never makes merkleTree throw', () => {
74
+ const pair = [{ path: NFC, hash: 'h1' }, { path: NFD, hash: 'h2' }];
75
+ for (const input of [pair, [...pair].reverse()]) {
76
+ const { kept, skipped } = canonicalListing(input);
77
+ // NFD's 'e' (U+0065) sorts before NFC's 'é' (U+00E9): the NFD spelling is kept, under its NFC path.
78
+ expect(kept).toEqual([{ path: NFC, hash: 'h2', listedPath: NFD }]);
79
+ expect(skipped).toEqual([{ path: NFC, reason: 'duplicate-path' }]);
80
+ expect(() => merkleTree(kept)).not.toThrow();
81
+ }
82
+ });
83
+
84
+ it('skips invalid paths, a path listed twice, and a path below a kept file', () => {
85
+ const { kept, skipped } = canonicalListing([
86
+ { path: 'a', hash: '1' }, { path: 'a/b', hash: '2' }, { path: 'x.md', hash: '3' }, { path: './x.md', hash: '4' },
87
+ { path: '../up.md', hash: '5' }, { path: 'p/./q', hash: '6' }, { path: 'p//q', hash: '7' }, { path: '', hash: '8' }, { path: 'src\\k.ts', hash: '9' },
88
+ ]);
89
+ expect(kept).toEqual([{ path: 'a', hash: '1' }, { path: 'src/k.ts', hash: '9', listedPath: 'src\\k.ts' }, { path: 'x.md', hash: '4', listedPath: './x.md' }]);
90
+ expect(skipped).toEqual([
91
+ { path: '../up.md', reason: 'invalid-path' }, { path: 'p/./q', reason: 'invalid-path' }, { path: 'p//q', reason: 'invalid-path' },
92
+ { path: '', reason: 'invalid-path' }, { path: 'a/b', reason: 'duplicate-path' }, { path: 'x.md', reason: 'duplicate-path' },
93
+ ]);
94
+ });
95
+ });
96
+
97
+ /** `tree` with its `entries.get` spied, so a test can see which directories a walk opened. */
98
+ function spied(tree: MerkleTree) {
99
+ const entries = new Map(tree.entries);
100
+ const get = jest.spyOn(entries, 'get');
101
+ return { tree: { ...tree, entries } as MerkleTree, opened: () => new Set(get.mock.calls.map((c) => c[0])) };
102
+ }
103
+
104
+ describe('changedPaths', () => {
105
+ it('returns exactly the changed, added and removed files', () => {
106
+ const next = [
107
+ ...edited(FILES, 'src/lib/b.ts', 'h-b2').filter((f) => f.path !== 'docs/guide/deep/more.md'),
108
+ { path: 'src/lib/new.ts', hash: 'h-new' },
109
+ ];
110
+ expect(changedPaths(merkleTree(FILES), merkleTree(next))).toEqual(['docs/guide/deep/more.md', 'src/lib/b.ts', 'src/lib/new.ts']);
111
+ expect(changedPaths(merkleTree(next), merkleTree(FILES))).toEqual(['docs/guide/deep/more.md', 'src/lib/b.ts', 'src/lib/new.ts']);
112
+ });
113
+
114
+ it('is empty for equal trees and opens no directory', () => {
115
+ const after = spied(merkleTree(FILES));
116
+ expect(changedPaths(merkleTree(FILES), after.tree)).toEqual([]);
117
+ expect(after.opened().size).toBe(0);
118
+ });
119
+
120
+ it('never descends into a subtree whose hash is equal', () => {
121
+ const before = spied(merkleTree(FILES));
122
+ const after = spied(merkleTree(edited(FILES, 'src/lib/b.ts', 'h-b2')));
123
+ expect(changedPaths(before.tree, after.tree)).toEqual(['src/lib/b.ts']);
124
+ expect([...after.opened()].sort()).toEqual(['', 'src', 'src/lib']);
125
+ expect([...before.opened()].sort()).toEqual(['', 'src', 'src/lib']);
126
+ });
127
+
128
+ it('a file replaced by a directory reports both sides', () => {
129
+ const before = merkleTree([{ path: 'x', hash: 'h' }, { path: 'keep.md', hash: 'k' }]);
130
+ const after = merkleTree([{ path: 'x/y', hash: 'h' }, { path: 'x/z/w', hash: 'h2' }, { path: 'keep.md', hash: 'k' }]);
131
+ expect(changedPaths(before, after)).toEqual(['x', 'x/y', 'x/z/w']);
132
+ });
133
+
134
+ it('from an empty tree, every file is added', () => {
135
+ expect(changedPaths(merkleTree([]), merkleTree(FILES))).toEqual(FILES.map((f) => f.path).sort());
136
+ });
137
+ });
@@ -0,0 +1,164 @@
1
+ /**
2
+ * knowledge/merkle.ts — directory Merkle hashes over a root's file listing (PRD 41 §B2 step 4).
3
+ *
4
+ * A directory's hash is sha256 over the canonical JSON of its entries `{ name, kind, hash }`
5
+ * (`kind` 'file' | 'dir'), sorted by name. An equal directory hash means an equal subtree, so
6
+ * {@link changedPaths} skips it and two trees compare in O(changed).
7
+ *
8
+ * Paths go through the ONE `normalizePath` (refs.ts: POSIX, no leading `./` or `/`, NFC) and sort bytewise (§B8.1). The
9
+ * root directory's key is `""`; a nested one's is its path (`a`, `a/b`). Any input order gives
10
+ * the same tree.
11
+ */
12
+
13
+ import { sha256Hex } from '../retrieval/knowledge-index/sha256.js';
14
+ import { canonicalJson, isRootFilePath, normalizePath } from './refs.js';
15
+
16
+ export type MerkleKind = 'file' | 'dir';
17
+
18
+ export interface MerkleEntry {
19
+ name: string;
20
+ kind: MerkleKind;
21
+ /** A file's content hash, or a directory's Merkle hash. */
22
+ hash: string;
23
+ }
24
+
25
+ export interface MerkleTree {
26
+ /** The root directory's hash (`dirs.get('')`). */
27
+ root: string;
28
+ /** Directory path → its Merkle hash; the root is `""`. */
29
+ dirs: ReadonlyMap<string, string>;
30
+ /** Directory path → its entries, sorted by name. */
31
+ entries: ReadonlyMap<string, ReadonlyArray<MerkleEntry>>;
32
+ }
33
+
34
+ /** Bytewise UTF-8 order (code-point order), which UTF-16 `<` is not for astral characters. */
35
+ export function compareBytewise(a: string, b: string): number {
36
+ const n = Math.min(a.length, b.length);
37
+ for (let i = 0; i < n; i++) {
38
+ const x = a.codePointAt(i)!, y = b.codePointAt(i)!;
39
+ if (x !== y) return x < y ? -1 : 1;
40
+ if (x > 0xffff) i++;
41
+ }
42
+ return a.length - b.length;
43
+ }
44
+
45
+ const dirOf = (path: string): string => {
46
+ const at = path.lastIndexOf('/');
47
+ return at < 0 ? '' : path.slice(0, at);
48
+ };
49
+ const nameOf = (path: string): string => path.slice(path.lastIndexOf('/') + 1);
50
+ const joinPath = (dir: string, name: string): string => (dir === '' ? name : `${dir}/${name}`);
51
+
52
+ /** Why {@link canonicalListing} left a listed path out. */
53
+ export type ListingSkipReason = 'invalid-path' | 'duplicate-path';
54
+
55
+ /**
56
+ * A host listing made safe for {@link merkleTree} — which then never throws — without depending on input order:
57
+ * • every path goes through the ONE {@link normalizePath} (POSIX, NFC); the source's own spelling is kept as `listedPath`
58
+ * when it differs, so a read still opens the file the source listed;
59
+ * • a path that is empty or has an empty, `.` or `..` segment is skipped as `invalid-path`;
60
+ * • of paths that collide once normalized (an NFC/NFD pair, a path listed twice) the FIRST by (normalized path, listed path),
61
+ * bytewise, is kept and the rest are skipped as `duplicate-path`; so is a path below a kept FILE (`a` and `a/b`).
62
+ * Skipped entries carry the listed spelling. `kept` is sorted bytewise by normalized path.
63
+ */
64
+ export function canonicalListing<T extends { path: string }>(entries: readonly T[]): {
65
+ kept: Array<T & { listedPath?: string }>;
66
+ skipped: Array<{ path: string; reason: ListingSkipReason }>;
67
+ } {
68
+ const skipped: Array<{ path: string; reason: ListingSkipReason }> = [];
69
+ const candidates: Array<{ entry: T; path: string }> = [];
70
+ for (const entry of entries) {
71
+ const path = normalizePath(entry.path);
72
+ if (isRootFilePath(path)) candidates.push({ entry, path });
73
+ else skipped.push({ path: entry.path, reason: 'invalid-path' });
74
+ }
75
+ candidates.sort((a, b) => compareBytewise(a.path, b.path) || compareBytewise(a.entry.path, b.entry.path));
76
+ const files = new Set<string>();
77
+ const kept: Array<T & { listedPath?: string }> = [];
78
+ for (const { entry, path } of candidates) {
79
+ let clash = files.has(path);
80
+ for (let dir = dirOf(path); !clash && dir !== ''; dir = dirOf(dir)) clash = files.has(dir);
81
+ if (clash) { skipped.push({ path: entry.path, reason: 'duplicate-path' }); continue; }
82
+ files.add(path);
83
+ kept.push({ ...entry, path, ...(entry.path !== path ? { listedPath: entry.path } : {}) });
84
+ }
85
+ return { kept, skipped };
86
+ }
87
+
88
+ /**
89
+ * The Merkle tree of a file listing. Throws on an invalid path, a path listed twice with different hashes, or a path
90
+ * that is both a file and a directory — each would make the root depend on input order. {@link canonicalListing}
91
+ * first makes a host listing safe.
92
+ */
93
+ export function merkleTree(files: ReadonlyArray<{ path: string; hash: string }>): MerkleTree {
94
+ const children = new Map<string, Map<string, { kind: MerkleKind; hash?: string }>>([['', new Map()]]);
95
+ const childrenOf = (dir: string) => {
96
+ let c = children.get(dir);
97
+ if (!c) children.set(dir, (c = new Map()));
98
+ return c;
99
+ };
100
+ for (const f of files) {
101
+ const path = normalizePath(f.path);
102
+ if (!isRootFilePath(path)) throw new Error(`merkleTree: not a file path: ${JSON.stringify(f.path)}`);
103
+ const own = childrenOf(dirOf(path)).get(nameOf(path));
104
+ if (own && (own.kind !== 'file' || own.hash !== f.hash)) throw new Error(`merkleTree: ${path} listed twice or as a file and a directory`);
105
+ childrenOf(dirOf(path)).set(nameOf(path), { kind: 'file', hash: f.hash });
106
+ for (let dir = dirOf(path); dir !== ''; dir = dirOf(dir)) {
107
+ const slot = childrenOf(dirOf(dir));
108
+ const was = slot.get(nameOf(dir));
109
+ if (was?.kind === 'file') throw new Error(`merkleTree: ${dir} is both a file and a directory`);
110
+ if (was) break; // its ancestors are registered already
111
+ slot.set(nameOf(dir), { kind: 'dir' });
112
+ }
113
+ }
114
+
115
+ const dirs = new Map<string, string>();
116
+ const entries = new Map<string, MerkleEntry[]>();
117
+ // Deepest first, so every child directory is hashed before its parent.
118
+ const order = [...children.keys()].sort((a, b) => depth(b) - depth(a) || compareBytewise(a, b));
119
+ for (const dir of order) {
120
+ const list = [...children.get(dir)!].map(([name, c]): MerkleEntry => ({
121
+ name, kind: c.kind, hash: c.kind === 'file' ? c.hash! : dirs.get(joinPath(dir, name))!,
122
+ })).sort((a, b) => compareBytewise(a.name, b.name));
123
+ entries.set(dir, list);
124
+ dirs.set(dir, sha256Hex(canonicalJson(list)));
125
+ }
126
+ return { root: dirs.get('')!, dirs, entries };
127
+ }
128
+
129
+ const depth = (dir: string): number => (dir === '' ? 0 : dir.split('/').length);
130
+
131
+ /** Every file path under `dir` in `tree`, appended to `out`. */
132
+ function filesUnder(tree: MerkleTree, dir: string, out: string[]): void {
133
+ for (const e of tree.entries.get(dir) ?? []) {
134
+ const path = joinPath(dir, e.name);
135
+ if (e.kind === 'file') out.push(path);
136
+ else filesUnder(tree, path, out);
137
+ }
138
+ }
139
+
140
+ /**
141
+ * The file paths changed, added or removed between two trees, sorted bytewise. Walks top-down
142
+ * and never descends into a directory whose hash is equal on both sides.
143
+ */
144
+ export function changedPaths(before: MerkleTree, after: MerkleTree): string[] {
145
+ const out: string[] = [];
146
+ const walk = (dir: string): void => {
147
+ if (before.dirs.get(dir) === after.dirs.get(dir)) return;
148
+ const was = new Map((before.entries.get(dir) ?? []).map((e) => [e.name, e] as const));
149
+ const is = new Map((after.entries.get(dir) ?? []).map((e) => [e.name, e] as const));
150
+ for (const name of new Set([...was.keys(), ...is.keys()])) {
151
+ const a = was.get(name), b = is.get(name);
152
+ const path = joinPath(dir, name);
153
+ if (a?.kind === 'dir' && b?.kind === 'dir') { if (a.hash !== b.hash) walk(path); continue; }
154
+ if (a && b && a.kind === 'file' && b.kind === 'file') { if (a.hash !== b.hash) out.push(path); continue; }
155
+ // Added, removed, or a file replaced by a directory (or back): every file on either side.
156
+ for (const [side, e] of [[before, a], [after, b]] as const) {
157
+ if (e?.kind === 'file') out.push(path);
158
+ else if (e) filesUnder(side, path, out);
159
+ }
160
+ }
161
+ };
162
+ walk('');
163
+ return [...new Set(out)].sort(compareBytewise);
164
+ }
@@ -12,6 +12,10 @@
12
12
 
13
13
  import type { SourceDocument, ParsedSection } from '../ingest/types.js';
14
14
  import type { IndexDoc, SimilarPair } from '../retrieval/knowledge-index/types.js';
15
+ import type { Finding, FindingRule } from './findingModel.js';
16
+
17
+ /** The finding types live beside the rules (findingModel.ts); re-exported so one import serves. */
18
+ export type { Finding, FindingRule } from './findingModel.js';
15
19
 
16
20
  /** `src:${rootId}::${path}` · `ent:${pack}:${normalizedName}` · `fact:${key}` (claims are `fact:claim:${hash}`). */
17
21
  export type NodeRef = `src:${string}` | `ent:${string}` | `fact:${string}`;
@@ -85,24 +89,6 @@ export interface ExtractContext {
85
89
  resolvePath(fromPath: string, target: string): string | undefined;
86
90
  }
87
91
 
88
- /** A finding a person can act on. `kind` is pack-defined; `requestKey` names an i18n template. */
89
- export interface Finding {
90
- id: string;
91
- kind: string;
92
- pack: string;
93
- nodes: NodeRef[];
94
- severity: 'info' | 'warn' | 'error';
95
- /** Numbers/strings for the label and the Fix-with-agent template. */
96
- params: Record<string, string | number>;
97
- /** i18n key of the fixed Fix-with-agent request (e.g. 'knowledgeGraph.fix.cloneGroup'). */
98
- requestKey?: string;
99
- }
100
-
101
- export interface FindingRule {
102
- id: string;
103
- find(graph: KnowledgeGraph): Finding[];
104
- }
105
-
106
92
  export interface PartitionRule {
107
93
  id: string;
108
94
  /** 0 = top. */
@@ -0,0 +1,58 @@
1
+ /**
2
+ * src/knowledge/owedFiles.contentHash.test.ts — the content-hash rule in the extractor entry (PRD 41 §B2 step 0).
3
+ * The rule never owes a file by its ABSENCE: a host switching to `contentHash` moves the hash of every CRLF file, and
4
+ * those re-extract by content. Only a RECORDED rule that differs from today's owes every file one re-extraction.
5
+ */
6
+
7
+ import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
8
+ import { CONTENT_HASH_RULE } from './contentHash.js';
9
+ import { isOwed, loadExtractorState, owedCalls, saveExtractorState } from './owedFiles.js';
10
+ import { DOCS_PACK } from './packs/docs.js';
11
+ import { planDetail } from './plan.js';
12
+ import { reviewDirectory } from './review.js';
13
+ import { EXTRACTOR_VERSION, extractorManifestKey } from './sources.js';
14
+ import { ALL, args, fakeJudge, FILES, memSource, memStore, ROOT } from './testkit.test-util.js';
15
+
16
+ const key = extractorManifestKey(ROOT);
17
+
18
+ describe('the content-hash rule in the extractor entry', () => {
19
+ it("an entry without a rule record owes nothing by it, at today's version", async () => {
20
+ const manifest = new InMemoryIngestManifest();
21
+ await manifest.set(key, [{ id: 'version', hash: String(EXTRACTOR_VERSION) }]);
22
+ const state = await loadExtractorState(manifest, ROOT);
23
+ expect(state.contentHashRule).toBeUndefined();
24
+ expect(isOwed(state, 'a.md')).toBe(false);
25
+ expect(owedCalls(state, 'a.md')).toBe(0);
26
+ expect(isOwed({ version: EXTRACTOR_VERSION, owed: new Map() }, 'a.md')).toBe(false);
27
+ });
28
+
29
+ it("today's rule recorded is read back and owes nothing", async () => {
30
+ const manifest = new InMemoryIngestManifest();
31
+ await manifest.set(key, [{ id: 'version', hash: String(EXTRACTOR_VERSION) }, { id: 'contentHash', hash: CONTENT_HASH_RULE }]);
32
+ const state = await loadExtractorState(manifest, ROOT);
33
+ expect(state.contentHashRule).toBe(CONTENT_HASH_RULE);
34
+ expect(isOwed(state, 'a.md')).toBe(false);
35
+ });
36
+
37
+ it("saving today's (first) rule writes no record, so the entry keeps its pre-rule shape", async () => {
38
+ const manifest = new InMemoryIngestManifest();
39
+ await saveExtractorState(manifest, ROOT, new Map());
40
+ expect((await manifest.get(key))!.map((f) => f.id)).toEqual(['version']);
41
+ });
42
+
43
+ it("another recorded rule at today's version owes every file one re-extraction, once", async () => {
44
+ const source = memSource({ ...FILES });
45
+ const store = memStore();
46
+ const manifest = new InMemoryIngestManifest();
47
+ await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge() }));
48
+ const owedPaths = async () => (await planDetail(source, manifest, [DOCS_PACK])).files.filter((f) => f.owed).map((f) => f.path);
49
+ expect(await owedPaths()).toEqual([]);
50
+
51
+ await manifest.set(key, [{ id: 'version', hash: String(EXTRACTOR_VERSION) }, { id: 'contentHash', hash: 'eol-lf@0' }]);
52
+ expect(owedCalls(await loadExtractorState(manifest, ROOT), 'a.md')).toBe(1);
53
+ expect(await owedPaths()).toEqual(ALL);
54
+ await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge() }));
55
+ expect(await owedPaths()).toEqual([]);
56
+ expect((await manifest.get(key))!.map((f) => f.id)).toEqual(['version']);
57
+ });
58
+ });
@@ -12,7 +12,8 @@
12
12
  * retired it drops out.
13
13
  *
14
14
  * Stored under {@link extractorManifestKey} as fingerprints: `{ id: 'version', hash: '<version>' }`
15
- * plus `{ id: 'documents', hash: '<pdf,docx|->' }` (the document types the packs claimed, see {@link withDocuments})
15
+ * plus `{ id: 'documents', hash: '<pdf,docx|->' }` (the document types the packs claimed, see {@link withDocuments}),
16
+ * `{ id: 'contentHash', hash: '<rule>' }` once {@link CONTENT_HASH_RULE} moves past {@link BASELINE_CONTENT_HASH_RULE} (no record reads as the baseline; another rule is an upgrade),
16
17
  * and one `{ id: 'owed:<path>', hash: '<calls>' }` per owed file, where `<calls>` is the
17
18
  * decimal number of model calls the file is still expected to cost (the plan's estimate):
18
19
  * • a file the run reached but did not finish: the sections the budget or a failed call left
@@ -27,11 +28,13 @@
27
28
  */
28
29
 
29
30
  import type { IngestManifest } from '../ingest/types.js';
31
+ import { BASELINE_CONTENT_HASH_RULE, CONTENT_HASH_RULE, contentHashRuleOf } from './contentHash.js';
30
32
  import { compareStr } from './refs.js';
31
33
  import { EXTRACTOR_VERSION, extOf, extractorManifestKey, isBinaryPath, isDocumentPath } from './sources.js';
32
34
 
33
35
  const VERSION_ID = 'version';
34
36
  const DOCUMENTS_ID = 'documents';
37
+ const CONTENT_HASH_ID = 'contentHash';
35
38
  /** No document type claimed — also what an entry with no `documents` record means, so a root that never had a host parser stores nothing extra. */
36
39
  const NO_DOCUMENTS = '-';
37
40
  const OWED_PREFIX = 'owed:';
@@ -42,6 +45,8 @@ const UPGRADE_CALLS = 1;
42
45
  export interface ExtractorState {
43
46
  /** The version the files were last reviewed with; undefined when never recorded. */
44
47
  version: number | undefined;
48
+ /** The content-hash rule (contentHash.ts) the files were hashed under, when the entry records one; absent for `eol-lf@1` and for every entry written before the rule existed. */
49
+ contentHashRule?: string;
45
50
  /** Paths a previous run left unfinished under that version → model calls each still costs. */
46
51
  owed: ReadonlyMap<string, number>;
47
52
  /** Consecutive transient failures of a path at one content hash (stored beside its owed entry); a success or a new hash resets it. Optional: a caller that builds a state by hand need not know it. */
@@ -82,6 +87,7 @@ export function withDocuments(state: ExtractorState, now: string | undefined): E
82
87
  export async function loadExtractorState(manifest: IngestManifest, rootId: string): Promise<ExtractorState> {
83
88
  let version: number | undefined;
84
89
  let documents: string | undefined;
90
+ let contentHashRule: string | undefined;
85
91
  const owed = new Map<string, number>();
86
92
  const failures = new Map<string, { hash: string; count: number }>();
87
93
  for (const { id, hash } of (await manifest.get(extractorManifestKey(rootId))) ?? []) {
@@ -90,6 +96,8 @@ export async function loadExtractorState(manifest: IngestManifest, rootId: strin
90
96
  if (Number.isFinite(v)) version = v;
91
97
  } else if (id === DOCUMENTS_ID) {
92
98
  documents = hash;
99
+ } else if (id === CONTENT_HASH_ID) {
100
+ contentHashRule = hash;
93
101
  } else if (id.startsWith(FAIL_PREFIX)) {
94
102
  const at = hash.indexOf(':');
95
103
  const count = Number(hash.slice(0, at));
@@ -99,15 +107,24 @@ export async function loadExtractorState(manifest: IngestManifest, rootId: strin
99
107
  owed.set(id.slice(OWED_PREFIX.length), Number.isFinite(calls) && calls >= 0 ? calls : UPGRADE_CALLS);
100
108
  }
101
109
  }
102
- return { version, owed, failures, documents: documents ?? NO_DOCUMENTS };
110
+ return { version, owed, failures, documents: documents ?? NO_DOCUMENTS, ...(contentHashRule !== undefined ? { contentHashRule } : {}) };
103
111
  }
104
112
 
113
+ /**
114
+ * True while the files were last reviewed under another extractor version than today's, or under another content-hash rule
115
+ * ({@link contentHashRuleOf}: no record is the baseline rule): every file owes one re-extraction. Adopting the baseline rule owes
116
+ * nothing by itself — a host switching to `contentHash` moves the hash of every CRLF file, and those re-extract by content
117
+ * (`contentChanged`, an extract-cache miss). The entry writes no record for the baseline; a later rule writes one.
118
+ */
119
+ const upgradePending = (state: ExtractorState): boolean =>
120
+ state.version !== EXTRACTOR_VERSION || contentHashRuleOf(state.contentHashRule) !== CONTENT_HASH_RULE;
121
+
105
122
  /** The file's document extension when its asset-ness flipped (a host parser arrived or left since the last run). */
106
123
  const isFlipped = (state: ExtractorState, path: string): boolean => !!state.flipped?.size && state.flipped.has(extOf(path));
107
124
 
108
- /** True when `path` is owed a re-extraction: another extractor version than today's, left unfinished before, or its asset-ness flipped. */
125
+ /** True when `path` is owed a re-extraction: another extractor version or recorded content-hash rule than today's, left unfinished before, or its asset-ness flipped. */
109
126
  export const isOwed = (state: ExtractorState, path: string): boolean =>
110
- state.version !== EXTRACTOR_VERSION || state.owed.has(path) || isFlipped(state, path);
127
+ upgradePending(state) || state.owed.has(path) || isFlipped(state, path);
111
128
 
112
129
  /** Whether `path` is an asset under the packs the plan was made with: binary, and not a document some parser claims. */
113
130
  const isAssetNow = (state: ExtractorState, path: string): boolean => {
@@ -123,7 +140,7 @@ const isAssetNow = (state: ExtractorState, path: string): boolean => {
123
140
  * An asset costs none (it is never read or judged); a file that flipped TO a document does.
124
141
  */
125
142
  export const owedCalls = (state: ExtractorState, path: string): number =>
126
- isAssetNow(state, path) ? 0 : (state.version !== EXTRACTOR_VERSION || isFlipped(state, path) ? UPGRADE_CALLS : 0) + (state.owed.get(path) ?? 0);
143
+ isAssetNow(state, path) ? 0 : (upgradePending(state) || isFlipped(state, path) ? UPGRADE_CALLS : 0) + (state.owed.get(path) ?? 0);
127
144
 
128
145
  /**
129
146
  * Paths in the files manifest that the plan does not list yet are owed: ignored, claimed by
@@ -169,6 +186,7 @@ export async function saveExtractorState(
169
186
  ): Promise<void> {
170
187
  await manifest.set(extractorManifestKey(rootId), [
171
188
  { id: VERSION_ID, hash: String(EXTRACTOR_VERSION) },
189
+ ...(CONTENT_HASH_RULE !== BASELINE_CONTENT_HASH_RULE ? [{ id: CONTENT_HASH_ID, hash: CONTENT_HASH_RULE }] : []),
172
190
  ...(documents !== undefined && documents !== NO_DOCUMENTS ? [{ id: DOCUMENTS_ID, hash: documents }] : []),
173
191
  ...[...owed].sort((a, b) => compareStr(a[0], b[0])).map(([path, calls]) => ({ id: `${OWED_PREFIX}${path}`, hash: String(calls) })),
174
192
  ...[...failures].filter(([path]) => owed.has(path)).sort((a, b) => compareStr(a[0], b[0])).map(([path, f]) => ({ id: `${FAIL_PREFIX}${path}`, hash: `${f.count}:${f.hash}` })),