@seanhogg/builderforce-memory 2026.10.80 → 2026.10.82

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 (79) hide show
  1. package/dist/knowledge/build.d.ts.map +1 -1
  2. package/dist/knowledge/build.js +40 -3
  3. package/dist/knowledge/build.js.map +1 -1
  4. package/dist/knowledge/cooperative.d.ts +51 -0
  5. package/dist/knowledge/cooperative.d.ts.map +1 -0
  6. package/dist/knowledge/cooperative.js +58 -0
  7. package/dist/knowledge/cooperative.js.map +1 -0
  8. package/dist/knowledge/ignoreMatcher.d.ts +25 -0
  9. package/dist/knowledge/ignoreMatcher.d.ts.map +1 -0
  10. package/dist/knowledge/ignoreMatcher.js +121 -0
  11. package/dist/knowledge/ignoreMatcher.js.map +1 -0
  12. package/dist/knowledge/index.d.ts +5 -1
  13. package/dist/knowledge/index.d.ts.map +1 -1
  14. package/dist/knowledge/index.js +3 -0
  15. package/dist/knowledge/index.js.map +1 -1
  16. package/dist/knowledge/merkle.d.ts +20 -5
  17. package/dist/knowledge/merkle.d.ts.map +1 -1
  18. package/dist/knowledge/merkle.js +25 -7
  19. package/dist/knowledge/merkle.js.map +1 -1
  20. package/dist/knowledge/plan.d.ts +6 -0
  21. package/dist/knowledge/plan.d.ts.map +1 -1
  22. package/dist/knowledge/plan.js +18 -4
  23. package/dist/knowledge/plan.js.map +1 -1
  24. package/dist/knowledge/reviewAnalyse.d.ts.map +1 -1
  25. package/dist/knowledge/reviewAnalyse.js +6 -1
  26. package/dist/knowledge/reviewAnalyse.js.map +1 -1
  27. package/dist/knowledge/reviewFinish.d.ts.map +1 -1
  28. package/dist/knowledge/reviewFinish.js +7 -1
  29. package/dist/knowledge/reviewFinish.js.map +1 -1
  30. package/dist/knowledge/reviewModel.d.ts +10 -0
  31. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  32. package/dist/knowledge/rules/factStore.d.ts.map +1 -1
  33. package/dist/knowledge/rules/factStore.js +24 -1
  34. package/dist/knowledge/rules/factStore.js.map +1 -1
  35. package/dist/knowledge/rules/fixpointRules.d.ts +68 -0
  36. package/dist/knowledge/rules/fixpointRules.d.ts.map +1 -0
  37. package/dist/knowledge/rules/fixpointRules.js +0 -0
  38. package/dist/knowledge/rules/fixpointRules.js.map +1 -0
  39. package/dist/knowledge/sources.d.ts +9 -9
  40. package/dist/knowledge/sources.d.ts.map +1 -1
  41. package/dist/knowledge/sources.js +11 -50
  42. package/dist/knowledge/sources.js.map +1 -1
  43. package/dist/knowledge/statManifest.d.ts +89 -0
  44. package/dist/knowledge/statManifest.d.ts.map +1 -0
  45. package/dist/knowledge/statManifest.js +125 -0
  46. package/dist/knowledge/statManifest.js.map +1 -0
  47. package/dist/stats/estimators.d.ts +8 -1
  48. package/dist/stats/estimators.d.ts.map +1 -1
  49. package/dist/stats/estimators.js +18 -7
  50. package/dist/stats/estimators.js.map +1 -1
  51. package/package.json +1 -1
  52. package/src/contract/exports.snapshot.json +11 -0
  53. package/src/contract/regression.assets.test.ts +3 -3
  54. package/src/contract/regression.contentHash.test.ts +2 -2
  55. package/src/contract/regression.factStoreBatchedLoad.test.ts +62 -0
  56. package/src/contract/regression.ignoreMatcher.test.ts +116 -0
  57. package/src/contract/regression.listing.test.ts +1 -1
  58. package/src/contract/regression.merkleCooperative.test.ts +79 -0
  59. package/src/contract/types.contract.test.ts +9 -5
  60. package/src/knowledge/build.ts +32 -3
  61. package/src/knowledge/cooperative.test.ts +57 -0
  62. package/src/knowledge/cooperative.ts +76 -0
  63. package/src/knowledge/docs.test.ts +30 -0
  64. package/src/knowledge/ignoreMatcher.ts +143 -0
  65. package/src/knowledge/index.ts +8 -1
  66. package/src/knowledge/merkle.test.ts +84 -47
  67. package/src/knowledge/merkle.ts +38 -8
  68. package/src/knowledge/plan.ts +22 -4
  69. package/src/knowledge/review.readAhead.test.ts +4 -1
  70. package/src/knowledge/reviewAnalyse.ts +6 -1
  71. package/src/knowledge/reviewFinish.ts +7 -1
  72. package/src/knowledge/reviewModel.ts +6 -0
  73. package/src/knowledge/rules/factStore.ts +22 -1
  74. package/src/knowledge/rules/fixpointRules.test.ts +94 -0
  75. package/src/knowledge/rules/fixpointRules.ts +0 -0
  76. package/src/knowledge/sources.ts +12 -46
  77. package/src/knowledge/statManifest.test.ts +122 -0
  78. package/src/knowledge/statManifest.ts +176 -0
  79. package/src/stats/estimators.ts +18 -7
@@ -0,0 +1,143 @@
1
+ /**
2
+ * knowledge/ignoreMatcher.ts — THE `.gitignore`-style matcher of a review (plan.ts asks it about every listed file).
3
+ *
4
+ * Semantics (unchanged since it lived in sources.ts): `#` comments, `!` negation, a trailing `/` for directories only, a
5
+ * `/` elsewhere anchors the pattern (to its base), otherwise any depth. A path's CANDIDATES are its ancestor folders, plus
6
+ * the path itself for a rule that is not directory-only; the LAST rule that matches any candidate decides (a negation
7
+ * re-includes). Unlike git, a negation may re-include a file under an excluded folder.
8
+ *
9
+ * Cost: "the last rule that matches any candidate" is the largest index of a matching rule over the candidates, and the
10
+ * candidates of a path are its parent folder's candidates plus one more. So the matcher keeps, per folder, the largest
11
+ * index of a rule matching that folder or an ancestor, and the rules whose literal prefix can still match below it
12
+ * ({@link IGNORE_DIR_CACHE_LIMIT} folders at most). It tests only those rules ABOVE the index — each folder once per walk,
13
+ * each file only against its folder's remaining non-directory rules — and a literal prefix/suffix check skips the regex for
14
+ * a candidate that cannot match (a nested `.gitignore`'s rules all start with `base/`). Same answers as testing every rule
15
+ * against every candidate (regression.ignoreMatcher.test.ts).
16
+ */
17
+
18
+ import { globToRegExp } from './partitions.js';
19
+
20
+ /**
21
+ * Always ignored: VCS internals, installed dependencies, builderforce config, and lockfiles (`yarn.lock`, `Cargo.lock` …): generated,
22
+ * huge, and plain text — extracted they would cost judgement calls for nothing; they were never stored (once skipped as binary).
23
+ * A `.builderforce/ignore` rule can still re-include one (`!yarn.lock`).
24
+ */
25
+ const DEFAULT_IGNORES = ['.git/', 'node_modules/', '.builderforce/', '.gitignore', '*.lock'];
26
+
27
+ /** How many folders' answers a matcher remembers; past it the memo starts over (answers stay exact, only work repeats). */
28
+ const IGNORE_DIR_CACHE_LIMIT = 100_000;
29
+
30
+ interface IgnoreRule {
31
+ glob: string;
32
+ negate: boolean;
33
+ dirOnly: boolean;
34
+ /** The literal text every match starts with / ends with ('' when the glob starts / ends with a wildcard). */
35
+ prefix: string;
36
+ suffix: string;
37
+ re: RegExp;
38
+ }
39
+
40
+ /** Characters with a meaning in a glob (partitions.ts globToRegExp): everything else is literal. */
41
+ const SPECIAL = new Set(['*', '?', '{', '}', '\\']);
42
+
43
+ function literalPrefix(glob: string): string {
44
+ let i = 0;
45
+ while (i < glob.length && !SPECIAL.has(glob[i]!)) i++;
46
+ return glob.slice(0, i);
47
+ }
48
+
49
+ function literalSuffix(glob: string): string {
50
+ let i = glob.length;
51
+ while (i > 0 && !SPECIAL.has(glob[i - 1]!)) i--;
52
+ // `**/` may match nothing (`**/x` matches `x`), so the slash after a `**` is not a required literal.
53
+ if (glob[i] === '/' && glob.slice(i - 2, i) === '**') i++;
54
+ return glob.slice(i);
55
+ }
56
+
57
+ /**
58
+ * What the matcher remembers of a folder: `top`, the largest index of a rule matching the folder or an ancestor (-1: none),
59
+ * and `live`, the indices (ascending) of the rules that can still match the folder's descendants — those whose literal
60
+ * prefix agrees with `folder/` (a nested `.gitignore`'s rules drop out everywhere outside its base).
61
+ */
62
+ interface DirEntry {
63
+ top: number;
64
+ live: readonly number[];
65
+ }
66
+
67
+ const matches = (r: IgnoreRule, candidate: string): boolean =>
68
+ candidate.startsWith(r.prefix) && candidate.endsWith(r.suffix) && r.re.test(candidate);
69
+
70
+ /** The rules of the ignore texts, in precedence order (the defaults first). */
71
+ function parseRules(texts: ReadonlyArray<string | { text: string; base: string }>): IgnoreRule[] {
72
+ const rules: IgnoreRule[] = [];
73
+ const lines = [
74
+ ...DEFAULT_IGNORES.map((line) => ({ line, base: '' })),
75
+ ...texts.flatMap((t) => {
76
+ const { text, base } = typeof t === 'string' ? { text: t, base: '' } : t;
77
+ return text.split(/\r?\n/).map((line) => ({ line, base }));
78
+ }),
79
+ ];
80
+ for (const { line, base } of lines) {
81
+ let p = line.replace(/\s+$/, '');
82
+ if (!p || p.startsWith('#')) continue;
83
+ const negate = p.startsWith('!');
84
+ if (negate) p = p.slice(1);
85
+ const dirOnly = p.endsWith('/');
86
+ if (dirOnly) p = p.slice(0, -1);
87
+ const anchored = p.includes('/');
88
+ p = p.replace(/^\//, '');
89
+ // A nested `.gitignore` scopes its patterns to its own folder.
90
+ const prefix = base ? `${base}/` : '';
91
+ if (!p) continue;
92
+ const glob = anchored ? `${prefix}${p}` : `${prefix}**/${p}`;
93
+ rules.push({ glob, negate, dirOnly, prefix: literalPrefix(glob), suffix: literalSuffix(glob), re: globToRegExp(glob) });
94
+ }
95
+ return rules;
96
+ }
97
+
98
+ /**
99
+ * A `.gitignore`-style matcher: `#` comments, `!` negation (last match wins), a trailing
100
+ * `/` for directories only, a `/` elsewhere anchors to the root, otherwise any depth.
101
+ */
102
+ export function ignoreMatcher(texts: ReadonlyArray<string | { text: string; base: string }>): (path: string) => boolean {
103
+ const rules = parseRules(texts);
104
+ const root: DirEntry = { top: -1, live: rules.map((_, i) => i) };
105
+ const dirs = new Map<string, DirEntry>();
106
+
107
+ /** The largest index above `floor` among `live` of a rule (all, or only non-directory ones) matching `candidate`, else `floor`. */
108
+ const topAbove = (candidate: string, live: readonly number[], floor: number, dirOnlyToo: boolean): number => {
109
+ for (let k = live.length - 1; k >= 0; k--) {
110
+ const i = live[k]!;
111
+ if (i <= floor) break;
112
+ const r = rules[i]!;
113
+ if ((dirOnlyToo || !r.dirOnly) && matches(r, candidate)) return i;
114
+ }
115
+ return floor;
116
+ };
117
+
118
+ /** The entry of `dir`, from its parent's: the rules that can still match below it are those whose literal prefix agrees with `dir/`. */
119
+ const entryOf = (dir: string, parent: DirEntry): DirEntry => {
120
+ const top = topAbove(dir, parent.live, parent.top, true);
121
+ const below = `${dir}/`;
122
+ const live = parent.live.filter((i) => { const p = rules[i]!.prefix; return p.startsWith(below) || below.startsWith(p); });
123
+ return { top, live: live.length === parent.live.length ? parent.live : live };
124
+ };
125
+
126
+ return (path) => {
127
+ const segments = path.split('/');
128
+ let entry = root;
129
+ let dir = '';
130
+ for (let i = 0; i < segments.length - 1; i++) {
131
+ dir = i === 0 ? segments[0]! : `${dir}/${segments[i]!}`;
132
+ let next = dirs.get(dir);
133
+ if (!next) {
134
+ next = entryOf(dir, entry);
135
+ if (dirs.size >= IGNORE_DIR_CACHE_LIMIT) dirs.clear();
136
+ dirs.set(dir, next);
137
+ }
138
+ entry = next;
139
+ }
140
+ const top = topAbove(path, entry.live, entry.top, false);
141
+ return top >= 0 && !rules[top]!.negate;
142
+ };
143
+ }
@@ -66,6 +66,8 @@ export { defineRule, DEFAULT_RULE_HOPS, MAX_RULE_HOPS } from './rules/factRule.j
66
66
  export type { FactRule, RuleInput, RuleScope } from './rules/factRule.js';
67
67
  export { evaluateRules, importNeighbours, derivedRowKey } from './rules/evaluateRules.js';
68
68
  export type { RuleWorld, DerivedRow, DerivedRows, RuleTraceEntry, RuleEvaluation } from './rules/evaluateRules.js';
69
+ export { evaluateRulesFixpoint, isRowSourceInput, MAX_FIXPOINT_ITERATIONS } from './rules/fixpointRules.js';
70
+ export type { FixpointResult, RowSourceInput } from './rules/fixpointRules.js';
69
71
  export { emptyFactGraph, updateFactGraph, buildFactGraph, factGraphDump, FACT_GRAPH_DUMP_VERSION } from './rules/factGraph.js';
70
72
  export type { FactGraph, FactManifestEntry, FactChange, FactGraphOptions, FactGraphUpdate } from './rules/factGraph.js';
71
73
  export { knowledgeFacts, knowledgeInputHash, runKnowledgeRules, packOfRef, KNOWLEDGE_INPUT } from './rules/knowledgeInput.js';
@@ -106,7 +108,12 @@ export type { PlanOptions, PlannedFile, PlanDetail } from './plan.js';
106
108
  export type { ExtractorState } from './owedFiles.js';
107
109
  export { contentHash, CONTENT_HASH_RULE, BASELINE_CONTENT_HASH_RULE, contentHashRuleOf } from './contentHash.js';
108
110
  export { merkleTree, changedPaths, canonicalListing } from './merkle.js';
109
- export type { MerkleTree, MerkleEntry, MerkleKind, ListingSkipReason } from './merkle.js';
111
+ export type { MerkleTree, MerkleEntry, MerkleKind, ListingSkipReason, MerkleOptions } from './merkle.js';
112
+ // PRD 41 §B2 steps 1–2: the stat prefilter (size + mtimeNs + fileId, BigInt) with git's racy-file rule.
113
+ export {
114
+ RACY_WINDOW_MS, statManifestKey, statMatches, isRacy, prefilterStats, createStatPrefilter, loadStatManifest, saveStatManifest,
115
+ } from './statManifest.js';
116
+ export type { StatRecord, StatManifestEntry, PrefilterDecision } from './statManifest.js';
110
117
  export { normalizePath, isRootFilePath } from './refs.js';
111
118
  export { reviewDirectory, assertStoredBatch } from './review.js';
112
119
  export { orderForJudging } from './judgePriority.js';
@@ -18,28 +18,28 @@ const FILES = [
18
18
  const edited = (files: typeof FILES, path: string, hash: string) => files.map((f) => (f.path === path ? { path, hash } : f));
19
19
 
20
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());
21
+ it('gives the same root and dirs for any input order', async () => {
22
+ const a = await merkleTree(FILES);
23
+ const b = await merkleTree([...FILES].reverse());
24
24
  expect(b.root).toBe(a.root);
25
25
  expect([...b.dirs]).toEqual([...a.dirs]);
26
26
  expect(a.dirs.get('')).toBe(a.root);
27
27
  expect([...a.dirs.keys()].sort()).toEqual(['', 'docs', 'docs/guide', 'docs/guide/deep', 'src', 'src/lib']);
28
28
  });
29
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);
30
+ it('normalizes paths: backslashes, a leading ./, NFC', async () => {
31
+ const a = await merkleTree([{ path: 'src/café.ts', hash: 'h' }]);
32
+ expect((await merkleTree([{ path: '.\\src\\café.ts', hash: 'h' }])).root).toBe(a.root);
33
33
  });
34
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' }]);
35
+ it('sorts entries bytewise (code-point order), not by UTF-16 unit', async () => {
36
+ const tree = await merkleTree([{ path: '\u{1F600}.md', hash: 'h1' }, { path: '~.md', hash: 'h2' }, { path: 'Z.md', hash: 'h3' }]);
37
37
  expect(tree.entries.get('')!.map((e) => e.name)).toEqual(['Z.md', '~.md', '\u{1F600}.md']);
38
38
  });
39
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'));
40
+ it('a file change changes only its ancestors', async () => {
41
+ const before = await merkleTree(FILES);
42
+ const after = await merkleTree(edited(FILES, 'src/lib/b.ts', 'h-b2'));
43
43
  expect(after.root).not.toBe(before.root);
44
44
  for (const dir of before.dirs.keys()) {
45
45
  const ancestor = dir === '' || dir === 'src' || dir === 'src/lib';
@@ -47,42 +47,45 @@ describe('merkleTree', () => {
47
47
  }
48
48
  });
49
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);
50
+ it('a file and a directory of one name differ in kind, so they never hash alike', async () => {
51
+ expect((await merkleTree([{ path: 'x', hash: 'h' }])).root).not.toBe((await merkleTree([{ path: 'x/y', hash: 'h' }])).root);
52
52
  });
53
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);
54
+ it('refuses a path listed twice at different hashes, or as both a file and a directory', async () => {
55
+ await expect(merkleTree([{ path: 'a', hash: '1' }, { path: 'a', hash: '2' }])).rejects.toThrow(/listed twice/);
56
+ await expect(merkleTree([{ path: 'a', hash: '1' }, { path: 'a/b', hash: '2' }])).rejects.toThrow(/file and a directory/);
57
+ await expect(merkleTree([{ path: 'a/b', hash: '2' }, { path: 'a', hash: '1' }])).rejects.toThrow(/file and a directory/);
58
+ await expect(merkleTree([{ path: 'a//b', hash: '1' }])).rejects.toThrow(/not a file path/);
59
+ await expect(merkleTree([{ path: 'a/./b', hash: '1' }])).rejects.toThrow(/not a file path/);
60
+ await expect(merkleTree([{ path: 'a/../b', hash: '1' }])).rejects.toThrow(/not a file path/);
61
+ await expect(merkleTree([{ path: '..', hash: '1' }])).rejects.toThrow(/not a file path/);
62
+ expect((await merkleTree([{ path: 'a', hash: '1' }, { path: 'a', hash: '1' }])).root).toBe((await merkleTree([{ path: 'a', hash: '1' }])).root);
63
63
  });
64
64
 
65
- it('an empty listing has a root', () => {
66
- expect(merkleTree([]).root).toMatch(/^[0-9a-f]{64}$/);
65
+ it('an empty listing has a root', async () => {
66
+ expect((await merkleTree([])).root).toMatch(/^[0-9a-f]{64}$/);
67
67
  });
68
68
  });
69
69
 
70
70
  describe('canonicalListing', () => {
71
- const NFC = 'café.md', NFD = 'café.md';
71
+ // Written with escapes so the two spellings are guaranteed: NFC 'é' (U+00E9) vs NFD 'e' + combining acute (U+0065 U+0301).
72
+ const NFC = 'caf\u00e9.md', NFD = 'cafe\u0301.md';
72
73
 
73
- it('keeps the first of a colliding pair by (normalized, listed) bytewise, in any input order, and never makes merkleTree throw', () => {
74
+ it('keeps the first of a colliding pair by (normalized, listed) bytewise, in any input order, and never makes merkleTree throw', async () => {
74
75
  const pair = [{ path: NFC, hash: 'h1' }, { path: NFD, hash: 'h2' }];
75
76
  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.
77
+ const { kept, skipped } = await canonicalListing(input);
78
+ // Both normalize to the same NFC path; the tie-break is the listed spelling, bytewise —
79
+ // NFD's 'e' (U+0065) before NFC's 'é' (U+00E9) — so the NFD spelling is kept, stored under
80
+ // its NFC path with `listedPath` carrying the source spelling. The NFC spelling is skipped.
78
81
  expect(kept).toEqual([{ path: NFC, hash: 'h2', listedPath: NFD }]);
79
82
  expect(skipped).toEqual([{ path: NFC, reason: 'duplicate-path' }]);
80
- expect(() => merkleTree(kept)).not.toThrow();
83
+ await expect(merkleTree(kept)).resolves.toBeDefined();
81
84
  }
82
85
  });
83
86
 
84
- it('skips invalid paths, a path listed twice, and a path below a kept file', () => {
85
- const { kept, skipped } = canonicalListing([
87
+ it('skips invalid paths, a path listed twice, and a path below a kept file', async () => {
88
+ const { kept, skipped } = await canonicalListing([
86
89
  { path: 'a', hash: '1' }, { path: 'a/b', hash: '2' }, { path: 'x.md', hash: '3' }, { path: './x.md', hash: '4' },
87
90
  { 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
91
  ]);
@@ -102,36 +105,70 @@ function spied(tree: MerkleTree) {
102
105
  }
103
106
 
104
107
  describe('changedPaths', () => {
105
- it('returns exactly the changed, added and removed files', () => {
108
+ it('returns exactly the changed, added and removed files', async () => {
106
109
  const next = [
107
110
  ...edited(FILES, 'src/lib/b.ts', 'h-b2').filter((f) => f.path !== 'docs/guide/deep/more.md'),
108
111
  { path: 'src/lib/new.ts', hash: 'h-new' },
109
112
  ];
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']);
113
+ expect(await changedPaths(await merkleTree(FILES), await merkleTree(next))).toEqual(['docs/guide/deep/more.md', 'src/lib/b.ts', 'src/lib/new.ts']);
114
+ expect(await changedPaths(await merkleTree(next), await merkleTree(FILES))).toEqual(['docs/guide/deep/more.md', 'src/lib/b.ts', 'src/lib/new.ts']);
112
115
  });
113
116
 
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
+ it('is empty for equal trees and opens no directory', async () => {
118
+ const after = spied(await merkleTree(FILES));
119
+ expect(await changedPaths(await merkleTree(FILES), after.tree)).toEqual([]);
117
120
  expect(after.opened().size).toBe(0);
118
121
  });
119
122
 
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']);
123
+ it('never descends into a subtree whose hash is equal', async () => {
124
+ const before = spied(await merkleTree(FILES));
125
+ const after = spied(await merkleTree(edited(FILES, 'src/lib/b.ts', 'h-b2')));
126
+ expect(await changedPaths(before.tree, after.tree)).toEqual(['src/lib/b.ts']);
124
127
  expect([...after.opened()].sort()).toEqual(['', 'src', 'src/lib']);
125
128
  expect([...before.opened()].sort()).toEqual(['', 'src', 'src/lib']);
126
129
  });
127
130
 
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']);
131
+ it('a file replaced by a directory reports both sides', async () => {
132
+ const before = await merkleTree([{ path: 'x', hash: 'h' }, { path: 'keep.md', hash: 'k' }]);
133
+ const after = await merkleTree([{ path: 'x/y', hash: 'h' }, { path: 'x/z/w', hash: 'h2' }, { path: 'keep.md', hash: 'k' }]);
134
+ expect(await changedPaths(before, after)).toEqual(['x', 'x/y', 'x/z/w']);
132
135
  });
133
136
 
134
- it('from an empty tree, every file is added', () => {
135
- expect(changedPaths(merkleTree([]), merkleTree(FILES))).toEqual(FILES.map((f) => f.path).sort());
137
+ it('from an empty tree, every file is added', async () => {
138
+ expect(await changedPaths(await merkleTree([]), await merkleTree(FILES))).toEqual(FILES.map((f) => f.path).sort());
139
+ });
140
+ });
141
+
142
+ describe('cooperative yields', () => {
143
+ /** A budget that is always due and counts its pauses, so a test sees the yields without real timers. */
144
+ const countingBudget = () => {
145
+ let pauses = 0;
146
+ return { budget: { due: () => true, pause: async () => { pauses += 1; } }, pauses: () => pauses };
147
+ };
148
+
149
+ it('merkleTree yields on an injected budget while hashing a large listing', async () => {
150
+ const { budget, pauses } = countingBudget();
151
+ const files = Array.from({ length: 500 }, (_, i) => ({ path: `f${String(i).padStart(4, '0')}.ts`, hash: `h${i}` }));
152
+ const tree = await merkleTree(files, { budget });
153
+ expect(pauses()).toBeGreaterThan(0);
154
+ expect(tree.root).toMatch(/^[0-9a-f]{64}$/);
155
+ // The yields did not change the result.
156
+ expect(tree.root).toBe((await merkleTree(files)).root);
157
+ });
158
+
159
+ it('canonicalListing yields on an injected budget', async () => {
160
+ const { budget, pauses } = countingBudget();
161
+ const entries = Array.from({ length: 200 }, (_, i) => ({ path: `f${i}.ts` }));
162
+ const { kept } = await canonicalListing(entries, { budget });
163
+ expect(pauses()).toBeGreaterThan(0);
164
+ expect(kept).toHaveLength(200);
165
+ });
166
+
167
+ it('changedPaths yields on an injected budget', async () => {
168
+ const { budget, pauses } = countingBudget();
169
+ const before = await merkleTree(FILES);
170
+ const after = await merkleTree(edited(FILES, 'src/lib/b.ts', 'h-b2'));
171
+ expect(await changedPaths(before, after, { budget })).toEqual(['src/lib/b.ts']);
172
+ expect(pauses()).toBeGreaterThan(0);
136
173
  });
137
174
  });
@@ -11,6 +11,7 @@
11
11
  */
12
12
 
13
13
  import { sha256Hex } from '../retrieval/knowledge-index/sha256.js';
14
+ import { cooperativeBudget, type CooperativeBudget } from './cooperative.js';
14
15
  import { canonicalJson, isRootFilePath, normalizePath } from './refs.js';
15
16
 
16
17
  export type MerkleKind = 'file' | 'dir';
@@ -31,6 +32,17 @@ export interface MerkleTree {
31
32
  entries: ReadonlyMap<string, ReadonlyArray<MerkleEntry>>;
32
33
  }
33
34
 
35
+ /**
36
+ * Options for the cooperative Merkle helpers. A host that plans on its UI thread over tens of
37
+ * thousands of files passes its own {@link CooperativeBudget} (the plan shares its walk's budget,
38
+ * so the yields are one budget across the whole plan); the default yields to the event loop
39
+ * every ~12 ms ({@link cooperativeBudget}).
40
+ */
41
+ export interface MerkleOptions {
42
+ /** The work budget the long loops hand back to the event loop on. Default {@link cooperativeBudget}. */
43
+ budget?: CooperativeBudget;
44
+ }
45
+
34
46
  /** Bytewise UTF-8 order (code-point order), which UTF-16 `<` is not for astral characters. */
35
47
  export function compareBytewise(a: string, b: string): number {
36
48
  const n = Math.min(a.length, b.length);
@@ -61,13 +73,18 @@ export type ListingSkipReason = 'invalid-path' | 'duplicate-path';
61
73
  * bytewise, is kept and the rest are skipped as `duplicate-path`; so is a path below a kept FILE (`a` and `a/b`).
62
74
  * Skipped entries carry the listed spelling. `kept` is sorted bytewise by normalized path.
63
75
  */
64
- export function canonicalListing<T extends { path: string }>(entries: readonly T[]): {
76
+ export async function canonicalListing<T extends { path: string }>(
77
+ entries: readonly T[],
78
+ opts: MerkleOptions = {},
79
+ ): Promise<{
65
80
  kept: Array<T & { listedPath?: string }>;
66
81
  skipped: Array<{ path: string; reason: ListingSkipReason }>;
67
- } {
82
+ }> {
83
+ const budget = opts.budget ?? cooperativeBudget();
68
84
  const skipped: Array<{ path: string; reason: ListingSkipReason }> = [];
69
85
  const candidates: Array<{ entry: T; path: string }> = [];
70
86
  for (const entry of entries) {
87
+ if (budget.due()) await budget.pause();
71
88
  const path = normalizePath(entry.path);
72
89
  if (isRootFilePath(path)) candidates.push({ entry, path });
73
90
  else skipped.push({ path: entry.path, reason: 'invalid-path' });
@@ -76,6 +93,7 @@ export function canonicalListing<T extends { path: string }>(entries: readonly T
76
93
  const files = new Set<string>();
77
94
  const kept: Array<T & { listedPath?: string }> = [];
78
95
  for (const { entry, path } of candidates) {
96
+ if (budget.due()) await budget.pause();
79
97
  let clash = files.has(path);
80
98
  for (let dir = dirOf(path); !clash && dir !== ''; dir = dirOf(dir)) clash = files.has(dir);
81
99
  if (clash) { skipped.push({ path: entry.path, reason: 'duplicate-path' }); continue; }
@@ -89,8 +107,15 @@ export function canonicalListing<T extends { path: string }>(entries: readonly T
89
107
  * The Merkle tree of a file listing. Throws on an invalid path, a path listed twice with different hashes, or a path
90
108
  * that is both a file and a directory — each would make the root depend on input order. {@link canonicalListing}
91
109
  * first makes a host listing safe.
110
+ *
111
+ * Async and cooperative: over a large listing the loop yields to the event loop every ~12 ms (or on the
112
+ * caller's {@link MerkleOptions.budget}), so a UI-thread host stays responsive. Callers `await` the tree.
92
113
  */
93
- export function merkleTree(files: ReadonlyArray<{ path: string; hash: string }>): MerkleTree {
114
+ export async function merkleTree(
115
+ files: ReadonlyArray<{ path: string; hash: string }>,
116
+ opts: MerkleOptions = {},
117
+ ): Promise<MerkleTree> {
118
+ const budget = opts.budget ?? cooperativeBudget();
94
119
  const children = new Map<string, Map<string, { kind: MerkleKind; hash?: string }>>([['', new Map()]]);
95
120
  const childrenOf = (dir: string) => {
96
121
  let c = children.get(dir);
@@ -98,6 +123,7 @@ export function merkleTree(files: ReadonlyArray<{ path: string; hash: string }>)
98
123
  return c;
99
124
  };
100
125
  for (const f of files) {
126
+ if (budget.due()) await budget.pause();
101
127
  const path = normalizePath(f.path);
102
128
  if (!isRootFilePath(path)) throw new Error(`merkleTree: not a file path: ${JSON.stringify(f.path)}`);
103
129
  const own = childrenOf(dirOf(path)).get(nameOf(path));
@@ -117,6 +143,7 @@ export function merkleTree(files: ReadonlyArray<{ path: string; hash: string }>)
117
143
  // Deepest first, so every child directory is hashed before its parent.
118
144
  const order = [...children.keys()].sort((a, b) => depth(b) - depth(a) || compareBytewise(a, b));
119
145
  for (const dir of order) {
146
+ if (budget.due()) await budget.pause();
120
147
  const list = [...children.get(dir)!].map(([name, c]): MerkleEntry => ({
121
148
  name, kind: c.kind, hash: c.kind === 'file' ? c.hash! : dirs.get(joinPath(dir, name))!,
122
149
  })).sort((a, b) => compareBytewise(a.name, b.name));
@@ -139,18 +166,21 @@ function filesUnder(tree: MerkleTree, dir: string, out: string[]): void {
139
166
 
140
167
  /**
141
168
  * 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.
169
+ * and never descends into a directory whose hash is equal on both sides. Async and cooperative:
170
+ * the walk yields to the event loop on the caller's budget (default every ~12 ms).
143
171
  */
144
- export function changedPaths(before: MerkleTree, after: MerkleTree): string[] {
172
+ export async function changedPaths(before: MerkleTree, after: MerkleTree, opts: MerkleOptions = {}): Promise<string[]> {
173
+ const budget = opts.budget ?? cooperativeBudget();
145
174
  const out: string[] = [];
146
- const walk = (dir: string): void => {
175
+ const walk = async (dir: string): Promise<void> => {
147
176
  if (before.dirs.get(dir) === after.dirs.get(dir)) return;
177
+ if (budget.due()) await budget.pause();
148
178
  const was = new Map((before.entries.get(dir) ?? []).map((e) => [e.name, e] as const));
149
179
  const is = new Map((after.entries.get(dir) ?? []).map((e) => [e.name, e] as const));
150
180
  for (const name of new Set([...was.keys(), ...is.keys()])) {
151
181
  const a = was.get(name), b = is.get(name);
152
182
  const path = joinPath(dir, name);
153
- if (a?.kind === 'dir' && b?.kind === 'dir') { if (a.hash !== b.hash) walk(path); continue; }
183
+ if (a?.kind === 'dir' && b?.kind === 'dir') { if (a.hash !== b.hash) await walk(path); continue; }
154
184
  if (a && b && a.kind === 'file' && b.kind === 'file') { if (a.hash !== b.hash) out.push(path); continue; }
155
185
  // Added, removed, or a file replaced by a directory (or back): every file on either side.
156
186
  for (const [side, e] of [[before, a], [after, b]] as const) {
@@ -159,6 +189,6 @@ export function changedPaths(before: MerkleTree, after: MerkleTree): string[] {
159
189
  }
160
190
  }
161
191
  };
162
- walk('');
192
+ await walk('');
163
193
  return [...new Set(out)].sort(compareBytewise);
164
194
  }
@@ -18,6 +18,7 @@ import {
18
18
  isAssetPath, isDocumentPath, manifestMap, resolveDocument, stubSource,
19
19
  } from './sources.js';
20
20
  import { compareStr, FALLBACK_PACK_ID, sortBy } from './refs.js';
21
+ import { cooperativeBudget } from './cooperative.js';
21
22
 
22
23
  /** ≈ bytes per judged section, for the estimate (the plan does not read changed files). */
23
24
  export const AVG_SECTION_BYTES = 1500;
@@ -94,6 +95,12 @@ export interface PlanDetail {
94
95
  carried: string[];
95
96
  /** The directory Merkle tree over `files` (PRD 41 §B2 step 4): `plan.merkleRoot` is its root. Optional so a hand-built detail stays valid. */
96
97
  merkle?: MerkleTree;
98
+ /**
99
+ * Bumped whenever the manifest or PlanDetail shape changes (PRD 41 §B8: a result built from a mixed generation is
100
+ * discarded). The plan digest (`ReviewReport.digest`) includes it, so a shape change moves every scope's digest and
101
+ * the two sides of a run delta never compare across a shape change.
102
+ */
103
+ planShapeVersion: number;
97
104
  }
98
105
 
99
106
  /** The ONE classification of a listed file: did its content move, is it owed, is it re-processed. */
@@ -119,11 +126,16 @@ export async function planDetail(
119
126
  opts: PlanOptions = {},
120
127
  ): Promise<PlanDetail> {
121
128
  const maxBytes = opts.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
129
+ // A host may plan on its UI thread over tens of thousands of files: every long loop hands the event loop back (cooperative.ts).
130
+ const budget = cooperativeBudget();
122
131
  const listed: Array<{ path: string; hash: string; size: number }> = [];
123
- for await (const entry of source.list()) listed.push(entry);
132
+ for await (const entry of source.list()) {
133
+ listed.push(entry);
134
+ if (budget.due()) await budget.pause();
135
+ }
124
136
  // The ONE normalization (POSIX, NFC) — so plan paths are Merkle paths — and a listing that cannot break the plan: invalid and
125
- // colliding paths are skipped with a reason (merkle.ts canonicalListing), never thrown.
126
- const listing = canonicalListing(listed);
137
+ // colliding paths are skipped with a reason (merkle.ts canonicalListing), never thrown. One budget across the whole plan.
138
+ const listing = await canonicalListing(listed, { budget });
127
139
  const entries = sortBy(listing.kept, (e) => e.path);
128
140
  const listedOf = new Map(entries.filter((e) => e.listedPath !== undefined).map((e) => [e.path, e.listedPath!] as const));
129
141
 
@@ -153,6 +165,7 @@ export async function planDetail(
153
165
  let estimatedSections = 0;
154
166
  let compareSections = 0;
155
167
  for (const e of entries) {
168
+ if (budget.due()) await budget.pause();
156
169
  if (ignored(e.path)) { skipped.push({ path: e.path, reason: 'ignored' }); continue; }
157
170
  const document = isDocumentPath(e.path) ? resolveDocument(composed, e.path) : undefined;
158
171
  // An asset is never read, so the size cap does not apply: it is planned, hashed and diffed, and costs no model call.
@@ -196,7 +209,9 @@ export async function planDetail(
196
209
  const awaiting = compares ? (await manifestMap(manifest, compareManifestKey(source.rootId))).size : 0;
197
210
  const compareCalls = compares ? Math.ceil((compareSections + awaiting) / SECTIONS_PER_COMPARE) : 0;
198
211
  const sortedByPack = Object.fromEntries(Object.keys(byPack).sort(compareStr).map((k) => [k, byPack[k]!]));
199
- const merkle = merkleTree(files);
212
+ if (budget.due()) await budget.pause();
213
+ const merkle = await merkleTree(files, { budget });
214
+ const planShapeVersion = 2; // 2 (2026-11-14, PRD 41 B2): the plan gained the stat-manifest identity; bump on any PlanDetail/manifest-shape change
200
215
  return {
201
216
  plan: {
202
217
  rootId: source.rootId,
@@ -215,6 +230,7 @@ export async function planDetail(
215
230
  extractor,
216
231
  carried: carriedOwed(extractor, prior, files.map((f) => f.path)),
217
232
  merkle,
233
+ planShapeVersion,
218
234
  };
219
235
  }
220
236
 
@@ -244,5 +260,7 @@ export async function refreshPlan(detail: PlanDetail, manifest: IngestManifest,
244
260
  extractor,
245
261
  carried: carriedOwed(extractor, prior, files.map((f) => f.path)),
246
262
  ...(detail.merkle ? { merkle: detail.merkle } : {}),
263
+ // *Continue* is the same manifest generation: the shape of what it continues is the shape it had.
264
+ planShapeVersion: detail.planShapeVersion,
247
265
  };
248
266
  }
@@ -87,7 +87,10 @@ describe('read-ahead with a pool that reads', () => {
87
87
  const run = reviewDirectory(args(source, new LocalSnapshotStore(memPersistence()), new InMemoryIngestManifest(), {
88
88
  judgement: fakeJudge(), mechanical: true, extractPool: pool, deferRead: true, concurrency: 8, signal: ctl.signal,
89
89
  }));
90
- await jest.advanceTimersByTimeAsync(50);
90
+ // The cooperative plan (async merkleTree/canonicalListing, 2026-11-14) yields to the event loop over several real
91
+ // macrotasks before the pool opens; each advanceTimersByTimeAsync drains one round, and the count varies with the
92
+ // runner's load. Poll-advance until the pool has opened (bounded, so a real stall still fails the test).
93
+ for (let i = 0; started() === 0 && i < 20; i++) await jest.advanceTimersByTimeAsync(50);
91
94
  expect(started()).toBe(8);
92
95
  ctl.abort();
93
96
  // No timer is advanced past the 10 s extract deadline: the stop alone settles every in-flight and queued job.
@@ -38,7 +38,12 @@ export async function runAnalyzers(c: ReviewContext): Promise<void> {
38
38
  try {
39
39
  return await p.analyzers!.analyse(c.rootId, signal, onProgress);
40
40
  } catch (error) {
41
- c.report.failures.push({ kind: 'analyzer', path: analyzerFailurePath(p.id), phase: 'analyse', reason: reasonOf(error) });
41
+ // Never silent, never zero-findings: the run records the failure AND flags the pack's analysis as not
42
+ // measured, so the compare marks its findings `not_comparable` (`analyzer-failed:<id>`) instead of
43
+ // presenting a missing run as a fix (PRD 41 §8 Part B, §C9).
44
+ const reason = reasonOf(error);
45
+ c.report.failures.push({ kind: 'analyzer', path: analyzerFailurePath(p.id), phase: 'analyse', reason });
46
+ (c.report.analyzerStatus ??= []).push({ id: p.id, status: 'failed', reason });
42
47
  return [];
43
48
  } finally { settled = true; }
44
49
  }),
@@ -47,7 +47,13 @@ export async function finishReview(c: ReviewContext, flush: () => Promise<void>)
47
47
  report.judged = c.batch.judged;
48
48
  report.unjudged = c.batch.unjudged;
49
49
  report.invalidJudgements = c.batch.invalid;
50
- report.digest = sha256Hex(canonicalJson({ rootId: c.rootId, packs: c.packIds, files: [...c.filesNow].sort((a, b) => compareStr(a[0], b[0])) }));
50
+ // The digest covers the root, the packs, the files manifest AND the plan/manifest shape version (PRD 41 §B8.4): a shape
51
+ // change moves every scope's digest, so two sides of a run delta never compare across one.
52
+ report.digest = sha256Hex(canonicalJson({
53
+ rootId: c.rootId, packs: c.packIds,
54
+ files: [...c.filesNow].sort((a, b) => compareStr(a[0], b[0])),
55
+ planShapeVersion: c.detail.planShapeVersion ?? 1,
56
+ }));
51
57
  await saveManifestMap(manifest, filesManifestKey(c.rootId), c.filesNow);
52
58
  await saveManifestMap(manifest, judgedManifestKey(c.rootId), c.judgedNow);
53
59
  // After every run: today's version and every file still owed a re-extraction — the unfinished ones,
@@ -99,6 +99,12 @@ export interface ReviewReport {
99
99
  awaitingJudgeCount?: number;
100
100
  /** Pass 2 (`only`): files of the slice judged to completion. */
101
101
  judgedFiles?: number;
102
+ /**
103
+ * Analyzers that did not complete (PRD 41 §8, C9): status `'failed'` when it ran and errored, `'not_measured'` when it did
104
+ * not run at all. A failed analyzer is NEVER presented as zero findings — the compare marks that tool's findings
105
+ * `not_comparable` (reason `analyzer-failed:<tool>`) rather than resolving them.
106
+ */
107
+ analyzerStatus?: Array<{ id: string; status: 'failed' | 'not_measured'; reason?: string }>;
102
108
  /** Judging was stopped for this run after consecutive provider failures (A10 rule 9); the files stay owed. */
103
109
  judgeStopped?: string;
104
110
  aborted: boolean;