@seanhogg/builderforce-memory 2026.10.45 → 2026.10.46

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 (173) hide show
  1. package/dist/knowledge/build.d.ts.map +1 -1
  2. package/dist/knowledge/build.js +13 -7
  3. package/dist/knowledge/build.js.map +1 -1
  4. package/dist/knowledge/extractFile.d.ts +9 -1
  5. package/dist/knowledge/extractFile.d.ts.map +1 -1
  6. package/dist/knowledge/extractFile.js +22 -5
  7. package/dist/knowledge/extractFile.js.map +1 -1
  8. package/dist/knowledge/extractJob.d.ts +30 -5
  9. package/dist/knowledge/extractJob.d.ts.map +1 -1
  10. package/dist/knowledge/extractJob.js +9 -1
  11. package/dist/knowledge/extractJob.js.map +1 -1
  12. package/dist/knowledge/index.d.ts +5 -3
  13. package/dist/knowledge/index.d.ts.map +1 -1
  14. package/dist/knowledge/index.js +2 -1
  15. package/dist/knowledge/index.js.map +1 -1
  16. package/dist/knowledge/jobDeadline.d.ts +17 -0
  17. package/dist/knowledge/jobDeadline.d.ts.map +1 -0
  18. package/dist/knowledge/jobDeadline.js +46 -0
  19. package/dist/knowledge/jobDeadline.js.map +1 -0
  20. package/dist/knowledge/judgeCalls.d.ts +16 -0
  21. package/dist/knowledge/judgeCalls.d.ts.map +1 -1
  22. package/dist/knowledge/judgeCalls.js +20 -1
  23. package/dist/knowledge/judgeCalls.js.map +1 -1
  24. package/dist/knowledge/judgePriority.d.ts +22 -0
  25. package/dist/knowledge/judgePriority.d.ts.map +1 -0
  26. package/dist/knowledge/judgePriority.js +28 -0
  27. package/dist/knowledge/judgePriority.js.map +1 -0
  28. package/dist/knowledge/pack/crc32.d.ts +3 -0
  29. package/dist/knowledge/pack/crc32.d.ts.map +1 -0
  30. package/dist/knowledge/pack/crc32.js +18 -0
  31. package/dist/knowledge/pack/crc32.js.map +1 -0
  32. package/dist/knowledge/pack/decode.d.ts +14 -0
  33. package/dist/knowledge/pack/decode.d.ts.map +1 -0
  34. package/dist/knowledge/pack/decode.js +64 -0
  35. package/dist/knowledge/pack/decode.js.map +1 -0
  36. package/dist/knowledge/pack/deflate.d.ts +9 -0
  37. package/dist/knowledge/pack/deflate.d.ts.map +1 -0
  38. package/dist/knowledge/pack/deflate.js +45 -0
  39. package/dist/knowledge/pack/deflate.js.map +1 -0
  40. package/dist/knowledge/pack/encode.d.ts +17 -0
  41. package/dist/knowledge/pack/encode.d.ts.map +1 -0
  42. package/dist/knowledge/pack/encode.js +79 -0
  43. package/dist/knowledge/pack/encode.js.map +1 -0
  44. package/dist/knowledge/pack/extrDiff.d.ts +23 -0
  45. package/dist/knowledge/pack/extrDiff.d.ts.map +1 -0
  46. package/dist/knowledge/pack/extrDiff.js +0 -0
  47. package/dist/knowledge/pack/extrDiff.js.map +1 -0
  48. package/dist/knowledge/pack/frame.d.ts +37 -0
  49. package/dist/knowledge/pack/frame.d.ts.map +1 -0
  50. package/dist/knowledge/pack/frame.js +94 -0
  51. package/dist/knowledge/pack/frame.js.map +1 -0
  52. package/dist/knowledge/pack/index.d.ts +19 -0
  53. package/dist/knowledge/pack/index.d.ts.map +1 -0
  54. package/dist/knowledge/pack/index.js +17 -0
  55. package/dist/knowledge/pack/index.js.map +1 -0
  56. package/dist/knowledge/pack/jsonSize.d.ts +5 -0
  57. package/dist/knowledge/pack/jsonSize.d.ts.map +1 -0
  58. package/dist/knowledge/pack/jsonSize.js +8 -0
  59. package/dist/knowledge/pack/jsonSize.js.map +1 -0
  60. package/dist/knowledge/pack/manifest.d.ts +66 -0
  61. package/dist/knowledge/pack/manifest.d.ts.map +1 -0
  62. package/dist/knowledge/pack/manifest.js +104 -0
  63. package/dist/knowledge/pack/manifest.js.map +1 -0
  64. package/dist/knowledge/pack/sections/columns.d.ts +32 -0
  65. package/dist/knowledge/pack/sections/columns.d.ts.map +1 -0
  66. package/dist/knowledge/pack/sections/columns.js +53 -0
  67. package/dist/knowledge/pack/sections/columns.js.map +1 -0
  68. package/dist/knowledge/pack/sections/extr.d.ts +8 -0
  69. package/dist/knowledge/pack/sections/extr.d.ts.map +1 -0
  70. package/dist/knowledge/pack/sections/extr.js +99 -0
  71. package/dist/knowledge/pack/sections/extr.js.map +1 -0
  72. package/dist/knowledge/pack/sections/extrLists.d.ts +23 -0
  73. package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -0
  74. package/dist/knowledge/pack/sections/extrLists.js +194 -0
  75. package/dist/knowledge/pack/sections/extrLists.js.map +1 -0
  76. package/dist/knowledge/pack/sections/facts.d.ts +8 -0
  77. package/dist/knowledge/pack/sections/facts.d.ts.map +1 -0
  78. package/dist/knowledge/pack/sections/facts.js +167 -0
  79. package/dist/knowledge/pack/sections/facts.js.map +1 -0
  80. package/dist/knowledge/pack/sections/index.d.ts +6 -0
  81. package/dist/knowledge/pack/sections/index.d.ts.map +1 -0
  82. package/dist/knowledge/pack/sections/index.js +9 -0
  83. package/dist/knowledge/pack/sections/index.js.map +1 -0
  84. package/dist/knowledge/pack/sections/rows.d.ts +31 -0
  85. package/dist/knowledge/pack/sections/rows.d.ts.map +1 -0
  86. package/dist/knowledge/pack/sections/rows.js +226 -0
  87. package/dist/knowledge/pack/sections/rows.js.map +1 -0
  88. package/dist/knowledge/pack/strings.d.ts +39 -0
  89. package/dist/knowledge/pack/strings.d.ts.map +1 -0
  90. package/dist/knowledge/pack/strings.js +115 -0
  91. package/dist/knowledge/pack/strings.js.map +1 -0
  92. package/dist/knowledge/pack/types.d.ts +109 -0
  93. package/dist/knowledge/pack/types.d.ts.map +1 -0
  94. package/dist/knowledge/pack/types.js +17 -0
  95. package/dist/knowledge/pack/types.js.map +1 -0
  96. package/dist/knowledge/pack/varint.d.ts +50 -0
  97. package/dist/knowledge/pack/varint.d.ts.map +1 -0
  98. package/dist/knowledge/pack/varint.js +141 -0
  99. package/dist/knowledge/pack/varint.js.map +1 -0
  100. package/dist/knowledge/partitions.d.ts +1 -1
  101. package/dist/knowledge/partitions.d.ts.map +1 -1
  102. package/dist/knowledge/partitions.js +6 -1
  103. package/dist/knowledge/partitions.js.map +1 -1
  104. package/dist/knowledge/review.d.ts.map +1 -1
  105. package/dist/knowledge/review.js +58 -16
  106. package/dist/knowledge/review.js.map +1 -1
  107. package/dist/knowledge/reviewJudge.d.ts +8 -1
  108. package/dist/knowledge/reviewJudge.d.ts.map +1 -1
  109. package/dist/knowledge/reviewJudge.js +14 -8
  110. package/dist/knowledge/reviewJudge.js.map +1 -1
  111. package/dist/knowledge/reviewModel.d.ts +35 -1
  112. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  113. package/dist/knowledge/reviewPrefetch.d.ts +8 -2
  114. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
  115. package/dist/knowledge/reviewPrefetch.js +50 -25
  116. package/dist/knowledge/reviewPrefetch.js.map +1 -1
  117. package/dist/knowledge/reviewRun.d.ts +15 -3
  118. package/dist/knowledge/reviewRun.d.ts.map +1 -1
  119. package/dist/knowledge/reviewRun.js +19 -2
  120. package/dist/knowledge/reviewRun.js.map +1 -1
  121. package/dist/knowledge/reviewRunModel.d.ts +8 -1
  122. package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
  123. package/dist/knowledge/reviewRunModel.js.map +1 -1
  124. package/dist/knowledge/stores/localSnapshotStore.d.ts +72 -6
  125. package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
  126. package/dist/knowledge/stores/localSnapshotStore.js +279 -75
  127. package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
  128. package/package.json +7 -3
  129. package/src/knowledge/build.ts +11 -5
  130. package/src/knowledge/extractFile.ts +26 -6
  131. package/src/knowledge/extractJob.ts +26 -7
  132. package/src/knowledge/index.ts +5 -3
  133. package/src/knowledge/jobDeadline.ts +43 -0
  134. package/src/knowledge/judgeCalls.ts +19 -2
  135. package/src/knowledge/judgePriority.ts +36 -0
  136. package/src/knowledge/pack/crc32.ts +17 -0
  137. package/src/knowledge/pack/decode.ts +58 -0
  138. package/src/knowledge/pack/deflate.ts +43 -0
  139. package/src/knowledge/pack/encode.ts +81 -0
  140. package/src/knowledge/pack/extrDiff.ts +0 -0
  141. package/src/knowledge/pack/frame.ts +86 -0
  142. package/src/knowledge/pack/index.ts +26 -0
  143. package/src/knowledge/pack/jsonSize.ts +11 -0
  144. package/src/knowledge/pack/manifest.ts +128 -0
  145. package/src/knowledge/pack/pack.guards.test.ts +77 -0
  146. package/src/knowledge/pack/pack.reconcile.test.ts +96 -0
  147. package/src/knowledge/pack/pack.roundtrip.test.ts +50 -0
  148. package/src/knowledge/pack/pack.size.test.ts +22 -0
  149. package/src/knowledge/pack/pack.testkit.test-util.ts +90 -0
  150. package/src/knowledge/pack/sections/columns.ts +61 -0
  151. package/src/knowledge/pack/sections/extr.ts +90 -0
  152. package/src/knowledge/pack/sections/extrLists.ts +147 -0
  153. package/src/knowledge/pack/sections/facts.ts +123 -0
  154. package/src/knowledge/pack/sections/index.ts +13 -0
  155. package/src/knowledge/pack/sections/rows.ts +184 -0
  156. package/src/knowledge/pack/strings.ts +123 -0
  157. package/src/knowledge/pack/types.ts +89 -0
  158. package/src/knowledge/pack/varint.ts +138 -0
  159. package/src/knowledge/partitions.test.ts +4 -0
  160. package/src/knowledge/partitions.ts +3 -1
  161. package/src/knowledge/review.throughput.test.ts +122 -0
  162. package/src/knowledge/review.ts +54 -16
  163. package/src/knowledge/review.twoPass.test.ts +224 -0
  164. package/src/knowledge/reviewJudge.ts +19 -8
  165. package/src/knowledge/reviewModel.ts +32 -1
  166. package/src/knowledge/reviewPrefetch.ts +51 -24
  167. package/src/knowledge/reviewRun.test.ts +20 -3
  168. package/src/knowledge/reviewRun.ts +33 -6
  169. package/src/knowledge/reviewRunModel.ts +4 -1
  170. package/src/knowledge/stores/localSnapshotStore.batched.test.ts +25 -3
  171. package/src/knowledge/stores/localSnapshotStore.extractedLog.test.ts +280 -0
  172. package/src/knowledge/stores/localSnapshotStore.ts +283 -76
  173. package/src/knowledge/systems.test.ts +12 -0
@@ -0,0 +1,138 @@
1
+ /**
2
+ * knowledge/pack/varint.ts — the byte-level primitives of BFKP v1 (PRD 41 A11): a growable byte
3
+ * writer and a bounds-checked reader over unsigned LEB128 varints, raw bytes, UTF-8 strings, and
4
+ * a compact number codec. Pure TypeScript — no Buffer, no node: imports.
5
+ */
6
+
7
+ /** A malformed pack: the server answers 422 `bad_pack`. */
8
+ export class PackFormatError extends Error {
9
+ constructor(message: string) { super(message); this.name = 'PackFormatError'; }
10
+ }
11
+
12
+ const ENCODER = new TextEncoder();
13
+ const DECODER = new TextDecoder('utf-8', { fatal: true });
14
+
15
+ export const utf8 = (s: string): Uint8Array => ENCODER.encode(s);
16
+
17
+ /** Largest integer a varint carries (2^53 - 1, JS's safe integer). */
18
+ export const MAX_VARINT = Number.MAX_SAFE_INTEGER;
19
+
20
+ export class ByteWriter {
21
+ private buf = new Uint8Array(1024);
22
+ private len = 0;
23
+
24
+ private room(n: number): void {
25
+ if (this.len + n <= this.buf.length) return;
26
+ let cap = this.buf.length;
27
+ while (cap < this.len + n) cap *= 2;
28
+ const next = new Uint8Array(cap);
29
+ next.set(this.buf.subarray(0, this.len));
30
+ this.buf = next;
31
+ }
32
+
33
+ get length(): number { return this.len; }
34
+
35
+ u8(v: number): void { this.room(1); this.buf[this.len++] = v & 0xff; }
36
+
37
+ /** Unsigned LEB128. */
38
+ varint(v: number): void {
39
+ if (!Number.isSafeInteger(v) || v < 0) throw new PackFormatError(`not an unsigned varint: ${v}`);
40
+ this.room(8);
41
+ while (v >= 0x80) { this.buf[this.len++] = (v % 0x80) | 0x80; v = Math.floor(v / 0x80); }
42
+ this.buf[this.len++] = v;
43
+ }
44
+
45
+ bytes(b: Uint8Array): void { this.room(b.length); this.buf.set(b, this.len); this.len += b.length; }
46
+
47
+ /** A varint length, then the UTF-8 bytes. */
48
+ str(s: string): void { const b = utf8(s); this.varint(b.length); this.bytes(b); }
49
+
50
+ u32le(v: number): void { this.room(4); for (let i = 0; i < 4; i++) this.buf[this.len++] = (v >>> (8 * i)) & 0xff; }
51
+
52
+ f64(v: number): void {
53
+ this.room(8);
54
+ new DataView(this.buf.buffer, this.buf.byteOffset + this.len, 8).setFloat64(0, v, true);
55
+ this.len += 8;
56
+ }
57
+
58
+ /**
59
+ * A finite number, as small as it can be and always exactly recoverable: a non-negative integer
60
+ * (tag 0), a non-negative decimal of at most 6 places (tag 1, scaled), or a raw float64 (tag 2).
61
+ */
62
+ num(v: number): void {
63
+ if (Number.isSafeInteger(v) && v >= 0 && v < 2 ** 50) { this.varint(v * 4); return; }
64
+ if (v >= 0 && v < 2 ** 30) {
65
+ const scaled = Math.round(v * 1e6);
66
+ if (scaled / 1e6 === v) { this.varint(scaled * 4 + 1); return; }
67
+ }
68
+ this.varint(2);
69
+ this.f64(v);
70
+ }
71
+
72
+ finish(): Uint8Array { return this.buf.slice(0, this.len); }
73
+ }
74
+
75
+ export class ByteReader {
76
+ private pos = 0;
77
+ constructor(private readonly buf: Uint8Array) {}
78
+
79
+ get offset(): number { return this.pos; }
80
+ get done(): boolean { return this.pos >= this.buf.length; }
81
+ get remaining(): number { return this.buf.length - this.pos; }
82
+
83
+ u8(): number {
84
+ if (this.pos >= this.buf.length) throw new PackFormatError('unexpected end of data');
85
+ return this.buf[this.pos++]!;
86
+ }
87
+
88
+ varint(): number {
89
+ let result = 0, scale = 1;
90
+ for (let i = 0; i < 8; i++) {
91
+ const b = this.u8();
92
+ result += (b & 0x7f) * scale;
93
+ if ((b & 0x80) === 0) return result;
94
+ scale *= 0x80;
95
+ }
96
+ throw new PackFormatError('varint too long');
97
+ }
98
+
99
+ bytes(n: number): Uint8Array {
100
+ if (!Number.isSafeInteger(n) || n < 0 || this.pos + n > this.buf.length) throw new PackFormatError('unexpected end of data');
101
+ const out = this.buf.subarray(this.pos, this.pos + n);
102
+ this.pos += n;
103
+ return out;
104
+ }
105
+
106
+ str(): string {
107
+ try { return DECODER.decode(this.bytes(this.varint())); } catch (e) {
108
+ if (e instanceof PackFormatError) throw e;
109
+ throw new PackFormatError('invalid UTF-8');
110
+ }
111
+ }
112
+
113
+ u32le(): number {
114
+ const b = this.bytes(4);
115
+ return (b[0]! | (b[1]! << 8) | (b[2]! << 16) | (b[3]! << 24)) >>> 0;
116
+ }
117
+
118
+ f64(): number {
119
+ const b = this.bytes(8);
120
+ return new DataView(b.buffer, b.byteOffset, 8).getFloat64(0, true);
121
+ }
122
+
123
+ num(): number {
124
+ const v = this.varint();
125
+ const tag = v % 4;
126
+ if (tag === 0) return v / 4;
127
+ if (tag === 1) return (v - 1) / 4 / 1e6;
128
+ if (v === 2) return this.f64();
129
+ throw new PackFormatError('bad number tag');
130
+ }
131
+ }
132
+
133
+ /** A count that is bounded before anything is allocated for it. */
134
+ export function boundedCount(r: ByteReader, max: number, what: string): number {
135
+ const n = r.varint();
136
+ if (n > max) throw new PackFormatError(`${what}: ${n} exceeds the bound ${max}`);
137
+ return n;
138
+ }
@@ -54,6 +54,10 @@ describe('globs and partitionOf', () => {
54
54
  expect(matchGlob('b.md', '*')).toBe(true);
55
55
  expect(matchGlob('x.ts', '*.{ts,tsx}')).toBe(true);
56
56
  expect(globToRegExp('a.b').test('aXb')).toBe(false);
57
+ // A backslash makes the next character literal.
58
+ expect(matchGlob('copy*/x.ts', 'copy\\*/**')).toBe(true);
59
+ expect(matchGlob('copyabc/x.ts', 'copy\\*/**')).toBe(false);
60
+ expect(matchGlob('a[1]', 'a\\[1\\]')).toBe(true);
57
61
  });
58
62
 
59
63
  it('takes the first matching rule', () => {
@@ -19,7 +19,7 @@ const globCache = new Map<string, RegExp>();
19
19
 
20
20
  /**
21
21
  * A glob as a RegExp over `/`-separated paths: `**` spans folders (`**\/` may match none),
22
- * `*` and `?` stay within one segment, `{a,b}` is alternation.
22
+ * `*` and `?` stay within one segment, `{a,b}` is alternation, `\x` is the literal `x`.
23
23
  */
24
24
  export function globToRegExp(glob: string): RegExp {
25
25
  const cached = globCache.get(glob);
@@ -27,6 +27,8 @@ export function globToRegExp(glob: string): RegExp {
27
27
  let re = '';
28
28
  for (let i = 0; i < glob.length; i++) {
29
29
  const ch = glob[i]!;
30
+ // A backslash makes the next character literal (`copy\*` is the folder named `copy*`), as in `.gitignore`.
31
+ if (ch === '\\' && i + 1 < glob.length) { re += escapeRe(glob[++i]!); continue; }
30
32
  if (ch === '*') {
31
33
  if (glob[i + 1] === '*') {
32
34
  const slashAfter = glob[i + 2] === '/';
@@ -0,0 +1,122 @@
1
+ /**
2
+ * src/knowledge/review.throughput.test.ts — PRD 41 A10 Accept: a 20,000-file folder is MAPPED by pass 1
3
+ * (`mechanical`) without a model call, through a pool of width 4, in time that measures the pipeline's own overhead (60 s is the CI ceiling,
4
+ * not the goal), and neither a slow snapshot checkpoint nor a 30,000-op replica queue with a slow durable write is waited on inside a file's step.
5
+ */
6
+
7
+ import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
8
+ import { extractJob, type ExtractPool } from './extractJob.js';
9
+ import { DOCS_PACK } from './packs/docs.js';
10
+ import type { KnowledgePack, KnowledgeStore, ReviewProgress } from './model.js';
11
+ import { reviewDirectory } from './review.js';
12
+ import { LocalSnapshotStore } from './stores/localSnapshotStore.js';
13
+ import { args, fakeJudge, memPersistence, memSource } from './testkit.test-util.js';
14
+
15
+ const TS_FILES = 19_800;
16
+ const MD_FILES = 200;
17
+ const TOTAL = TS_FILES + MD_FILES;
18
+ const CEILING_MS = 60_000;
19
+
20
+ /** A code-ish pack with no judgement: every `.ts` is one file node. */
21
+ const TS_PACK: KnowledgePack = {
22
+ id: 'ts', parsers: [{ id: 'ts', accepts: (s) => s.id.endsWith('.ts'), parse: () => [] }],
23
+ };
24
+
25
+ function fixture(): Record<string, string> {
26
+ const out: Record<string, string> = {};
27
+ for (let i = 0; i < TS_FILES; i++) out[`src/m${Math.floor(i / 100)}/f${i}.ts`] = `export const v${i} = ${i};\n`;
28
+ for (let i = 0; i < MD_FILES; i++) out[`docs/d${i}.md`] = `# D${i}\nbody ${i}\n`;
29
+ return out;
30
+ }
31
+
32
+ /** A pool of width 4 that extracts in-process, one job per tick, and records how many jobs it held at once. */
33
+ function fakePool(): { pool: ExtractPool; peak: () => number; calls: () => number } {
34
+ let busy = 0, peak = 0, calls = 0;
35
+ const packs = [TS_PACK, DOCS_PACK];
36
+ return {
37
+ peak: () => peak, calls: () => calls,
38
+ pool: async (job) => {
39
+ busy += 1; calls += 1; peak = Math.max(peak, busy);
40
+ await Promise.resolve();
41
+ const out = extractJob(job, packs);
42
+ busy -= 1;
43
+ return out;
44
+ },
45
+ };
46
+ }
47
+
48
+ describe('pass 1 throughput (PRD 41 A10)', () => {
49
+ it('maps 20,000 files with no model call through a pool of width 4 within the CI ceiling', async () => {
50
+ const judge = fakeJudge();
51
+ const { pool, peak, calls } = fakePool();
52
+ const phases: string[] = [];
53
+ const events: ReviewProgress[] = [];
54
+ const t0 = Date.now();
55
+ const report = await reviewDirectory(args(memSource(fixture()), new LocalSnapshotStore(memPersistence()), new InMemoryIngestManifest(), {
56
+ packs: [TS_PACK, DOCS_PACK], judgement: judge, mechanical: true, extractPool: pool, concurrency: 4,
57
+ onProgress: (p) => { events.push(p); if (phases[phases.length - 1] !== p.phase) phases.push(p.phase); },
58
+ }));
59
+ const elapsed = Date.now() - t0;
60
+
61
+ expect(judge.requests).toHaveLength(0);
62
+ expect(report.aborted).toBe(false);
63
+ expect(report.failures).toEqual([]);
64
+ expect(report.extracted).toBe(TOTAL);
65
+ expect(calls()).toBe(TOTAL);
66
+ expect(peak()).toBeLessThanOrEqual(4);
67
+ expect(report.awaitingJudge).toHaveLength(MD_FILES); // the docs are judged later; code never is
68
+ expect(report.awaitingJudgeCount).toBe(MD_FILES);
69
+ // The map is complete: memory's last word is `done` after every file reached extract and write.
70
+ expect(phases[phases.length - 1]).toBe('done');
71
+ expect(events.filter((e) => e.phase === 'write')).toHaveLength(TOTAL);
72
+ expect(elapsed).toBeLessThan(CEILING_MS);
73
+ }, 120_000);
74
+
75
+ it('does not wait for a snapshot checkpoint or a 30,000-op replica queue inside a file\'s step', async () => {
76
+ let release!: () => void;
77
+ const gate = new Promise<void>((r) => { release = r; });
78
+ const durable = memPersistence();
79
+ const write = durable.write;
80
+ let started = 0;
81
+ // Every durable write (the snapshot's checkpoints, the queue's saves) hangs until the run has applied its last file.
82
+ durable.write = async (s) => { started += 1; await gate; await write(s); };
83
+ const local = new LocalSnapshotStore(durable, { checkpointMs: 1 });
84
+
85
+ // The replica queue as the A7 wrapper uses it: 30,000 ops already queued, a durable save that is slow, and an `enqueue` that only appends.
86
+ const queue = { ops: Array.from({ length: 30_000 }, (_, i) => `op${i}`), saves: 0, enqueues: 0 };
87
+ const save = async (): Promise<void> => { queue.saves += 1; await gate; };
88
+ let saving: Promise<void> | undefined;
89
+ const enqueue = (op: string): void => {
90
+ queue.ops.push(op); queue.enqueues += 1;
91
+ saving ??= save().finally(() => { saving = undefined; }); // at most one save in flight; never awaited by a step
92
+ };
93
+ const replicated: KnowledgeStore = {
94
+ scopes: () => local.scopes(), facts: (s) => local.facts(s), relations: (s) => local.relations(s),
95
+ getExtracted: (h) => local.getExtracted(h),
96
+ batched: (work) => local.batched(work),
97
+ async write(batch) { await local.write(batch); enqueue(`w:${batch.facts.length}`); },
98
+ async markStale(scope, ref, hash) { await local.markStale(scope, ref, hash); enqueue(`s:${ref}`); },
99
+ async putExtracted(hash, ex) { await local.putExtracted(hash, ex); enqueue(`x:${hash}`); },
100
+ };
101
+
102
+ const files = fixture();
103
+ const small = Object.fromEntries(Object.entries(files).slice(0, 3_000));
104
+ const { pool } = fakePool();
105
+ let lastWrite = 0;
106
+ const total = Object.keys(small).length;
107
+ const report = await reviewDirectory(args(memSource(small), replicated, new InMemoryIngestManifest(), {
108
+ packs: [TS_PACK, DOCS_PACK], judgement: fakeJudge(), mechanical: true, extractPool: pool, concurrency: 4,
109
+ onProgress: (p) => {
110
+ if (p.phase !== 'write') return;
111
+ lastWrite = p.done + 1;
112
+ if (lastWrite === total) release(); // had a step awaited a pending durable write, this would never be reached
113
+ },
114
+ }));
115
+
116
+ expect(lastWrite).toBe(total);
117
+ expect(report.extracted).toBe(total);
118
+ expect(started).toBeGreaterThan(0); // checkpoints really were pending while files were applied
119
+ expect(queue.enqueues).toBeGreaterThan(total);
120
+ expect(queue.saves).toBeLessThanOrEqual(1 + Math.ceil(queue.enqueues / 500)); // saves are batched, not per op
121
+ }, 120_000);
122
+ });
@@ -38,7 +38,8 @@ import {
38
38
  type CompareOutcome, type JudgeBudget,
39
39
  } from './judge.js';
40
40
  import { createModelLimiter } from './modelLimiter.js';
41
- import { applyJudge, startJudge, type JudgeJob } from './reviewJudge.js';
41
+ import { JudgeBreaker } from './judgeCalls.js';
42
+ import { applyJudge, judgesPack, splitSections, startJudge, type JudgeJob } from './reviewJudge.js';
42
43
  import { createPrefetch, type Prefetch } from './reviewPrefetch.js';
43
44
  import { Lanes } from './reviewRunModel.js';
44
45
  import { compareNew, pendingClaims, saveAwaiting } from './reviewCompare.js';
@@ -76,7 +77,7 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
76
77
  const progress = (p: Parameters<NonNullable<ReviewArgs['onProgress']>>[0]) => args.onProgress?.(p);
77
78
  const report: ReviewReport = {
78
79
  rootId, digest: '', extracted: 0, judged: 0, unjudged: 0, invalidJudgements: 0,
79
- factsWritten: 0, relationsWritten: 0, staleMarked: 0, readErrors: 0, extractErrors: 0, failures: [], aborted: false, durationMs: 0,
80
+ factsWritten: 0, relationsWritten: 0, staleMarked: 0, readErrors: 0, extractErrors: 0, failures: [], awaitingJudge: [], aborted: false, durationMs: 0,
80
81
  };
81
82
 
82
83
  const detail = args.plan
@@ -96,6 +97,8 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
96
97
  used: 0, now,
97
98
  };
98
99
  const batch = new JudgedBatch();
100
+ const breaker = new JudgeBreaker();
101
+ const owedJudge: string[] = [];
99
102
  const judgedPrior = await manifestMap(manifest, judgedManifestKey(rootId));
100
103
  const judgedNow = new Map(judgedPrior);
101
104
  const filesNow = new Map(detail.prior);
@@ -134,17 +137,25 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
134
137
  };
135
138
 
136
139
  const changed = detail.files.filter((f) => f.changed);
140
+ // `only` (pass 2) narrows what this run works on; the other changed files are untouched and stay owed (owedAfterRun sees them all).
141
+ // Pass 2 works in the order it was given (priority), so a model-call ceiling is spent on the most important files first.
142
+ const byPath = new Map(changed.map((f) => [f.path, f] as const));
143
+ const work = args.only ? args.only.flatMap((p) => byPath.get(p) ?? []) : changed;
137
144
  // Changed files this run finished (or had nothing to do for); an owed file not in it stays owed,
138
145
  // at the model calls it still costs where this run could measure that (see owedFiles.ts).
139
146
  const finished = new Set<string>();
140
147
  const measured = new Map<string, number>();
141
148
  // One bulk fetch of the extract cache for the whole run instead of a round trip per file.
142
- const hashes = [...new Set(changed.map((f) => f.hash))];
149
+ const hashes = [...new Set(work.map((f) => f.hash))];
143
150
  if (hashes.length > 0) await store.preloadExtracted?.(hashes);
144
151
  // Read + binary check + extract run ahead with bounded concurrency (extraction only reads `knownKeys`,
145
152
  // fixed above, and the content-hash extract cache); with `args.extractPool` the width is the pool's.
146
153
  // Judging runs `judgeWidth` files at once; ONE writer (`applyFile`) consumes them strictly in plan order.
147
154
  const concurrency = Math.min(32, Math.max(1, Math.floor(args.concurrency ?? DEFAULT_REVIEW_CONCURRENCY) || 1));
155
+ // Read-ahead is wider than the pool (PRD 41 A10 rule 8) so workers never wait for the ordered writer.
156
+ const readAhead = args.extractPool
157
+ ? Math.min(64, Math.max(concurrency, Math.floor(args.readAhead ?? Math.max(32, concurrency * 4)) || concurrency))
158
+ : concurrency;
148
159
  const judgeWidth = Math.min(concurrency, Math.min(16, Math.max(1, Math.floor(args.judgeConcurrency ?? DEFAULT_REVIEW_JUDGE_CONCURRENCY) || 1)));
149
160
  // The run's own stop: the caller's abort relays into it, and a thrown error (a local store failure) aborts it,
150
161
  // so queued and in-flight judge calls and pool jobs stop and nothing outlives the run.
@@ -156,9 +167,10 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
156
167
  const relay = () => { if (inWriter) cut = true; stopper.abort(signal?.reason); };
157
168
  if (signal?.aborted) relay(); else signal?.addEventListener('abort', relay, { once: true });
158
169
  const runSignal = stopper.signal;
159
- const prefetch = createPrefetch({ args, signal: runSignal, rootId, packs, store, composed, knownKeys, width: concurrency });
170
+ const prefetch = createPrefetch({ args, signal: runSignal, rootId, packs, store, composed, knownKeys, width: readAhead, extractWidth: concurrency });
160
171
  const dispatch = {
161
- port: args.judgement, signal: runSignal, budget, judgedPrior, lanes: new Lanes(judgeWidth),
172
+ // A mechanical run (pass 1) makes no model call: judged files stay owed.
173
+ port: args.mechanical ? undefined : args.judgement, signal: runSignal, breaker, budget, judgedPrior, lanes: new Lanes(judgeWidth),
162
174
  limiter: createModelLimiter(args.maxModelCalls ?? JUDGE_CONCURRENCY),
163
175
  };
164
176
  const judgeCtx = { batch, entities, stored, judgedNow, newClaims, measured, detail, report, ...(args.onStep ? { onStep: args.onStep } : {}) };
@@ -170,7 +182,7 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
170
182
  * applied even after an abort — the work is done, so it is kept.
171
183
  */
172
184
  const applyInner = async ({ f, i, job, judge }: Slot): Promise<boolean> => {
173
- progress({ phase: 'extract', done: i, total: changed.length, path: f.path });
185
+ progress({ phase: 'extract', done: i, total: work.length, path: f.path });
174
186
  // A read that throws (permissions, a lock, a race with a delete) or an extraction that throws says nothing
175
187
  // about the file: skipped with its knowledge and manifest hash intact, tried again next review.
176
188
  if (job.kind === 'read-error' || job.kind === 'failed') {
@@ -192,24 +204,44 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
192
204
  // The extract cache is written HERE, in plan order, so the cache, the counts and the order match a sequential run.
193
205
  if (!job.extraction.cached) await putExtract(store, f.hash, job.extraction.extracted);
194
206
  let complete = true;
207
+ let deferred = false;
208
+ if (args.mechanical && judgesPack(args.judgement, job.extraction.pack)) {
209
+ // Pass 1: the map has this file; its judgement is pass 2's. With sections at hand (in-thread parse) a file whose sections are all
210
+ // still judged costs no model call: its facts are refreshed and it is complete. A pool returns none in a mechanical run, so those files are
211
+ // owed and pass 2 finds nothing to judge (a cache hit, no call).
212
+ const { reuse, toJudge } = splitSections(judgedPrior, job.extraction);
213
+ if (job.extraction.sections.length > 0 && toJudge.length === 0) {
214
+ for (const ref of reuse) stored.refresh(ref, f.path, f.hash, batch, entities);
215
+ } else {
216
+ complete = false;
217
+ deferred = true;
218
+ owedJudge.push(f.path);
219
+ measured.set(f.path, Math.max(1, toJudge.length));
220
+ }
221
+ }
195
222
  if (judge) {
196
- progress({ phase: 'judge', done: i, total: changed.length, path: f.path });
223
+ progress({ phase: 'judge', done: i, total: work.length, path: f.path });
197
224
  inWriter = false; // waiting for the model calls is not the writer working
198
225
  const outcome = await applyJudge(judgeCtx, f, judge);
199
226
  inWriter = true;
200
227
  if (outcome === 'aborted') return false;
201
228
  if (outcome === 'failed') {
229
+ owedJudge.push(f.path);
202
230
  // Judging failed as a whole: leave the file exactly as it was (facts, manifest hash, owed) so the next review retries it.
203
231
  measured.set(f.path, owedCalls(detail.extractor, f.path));
204
232
  return true;
205
233
  }
206
234
  complete = outcome.complete;
235
+ if (!complete) owedJudge.push(f.path);
207
236
  }
208
- progress({ phase: 'write', done: i, total: changed.length, path: f.path });
237
+ progress({ phase: 'write', done: i, total: work.length, path: f.path });
209
238
  const t0 = now();
210
239
  await write();
211
- await store.markStale(scope, srcRef(rootId, f.path), f.hash);
212
- report.staleMarked += 1;
240
+ // An owed file keeps its old judgement current until pass 2 replaces it: nothing of it is marked stale yet.
241
+ if (!deferred) {
242
+ await store.markStale(scope, srcRef(rootId, f.path), f.hash);
243
+ report.staleMarked += 1;
244
+ }
213
245
  args.onStep?.({ path: f.path, phase: 'write', ms: now() - t0, outcome: 'ok' });
214
246
  if (complete) { filesNow.set(f.path, f.hash); finished.add(f.path); }
215
247
  return true;
@@ -226,7 +258,7 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
226
258
  };
227
259
  let completed = false;
228
260
  try {
229
- for await (const { item: f, i, result } of prefetchOrdered(changed, concurrency, prefetch, runSignal)) {
261
+ for await (const { item: f, i, result } of prefetchOrdered(work, readAhead, prefetch, runSignal)) {
230
262
  if (result.status === 'rejected') throw result.reason; // a prefetch job settles to a Prefetch; this is a broken invariant
231
263
  const job = result.value;
232
264
  queue.push({ f, i, job, judge: job.kind === 'extracted' ? startJudge(dispatch, f, job.extraction) : undefined });
@@ -239,9 +271,10 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
239
271
  signal?.removeEventListener('abort', relay);
240
272
  await Promise.allSettled(queue.map((s) => s.judge?.result)); // nothing outlives the run
241
273
  }
242
- if (applied < changed.length) report.aborted = true;
274
+ if (applied < work.length) report.aborted = true;
243
275
 
244
- if (!report.aborted) {
276
+ // Pass 2 (`only`) is judging alone: the map pass already retired the removed files and ran the analyzers.
277
+ if (!report.aborted && !args.only) {
245
278
  await retire(detail.plan.removed);
246
279
  // Analyzers run in parallel and a failing one never aborts the review — its extracted
247
280
  // output is simply not stored (the file-level facts above are already durable), so a
@@ -264,7 +297,7 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
264
297
  const wantsCompare = packs.some((p) => p.judgement?.contradictions);
265
298
  const canCompare = wantsCompare && !!args.judgement && !!args.similar;
266
299
  let outcome: CompareOutcome | undefined;
267
- if (!report.aborted && canCompare) {
300
+ if (!report.aborted && canCompare && !args.mechanical) {
268
301
  outcome = await compareNew({
269
302
  args, pending: newClaims, known: stored.facts, budget, batch,
270
303
  onPairs: (total) => progress({ phase: 'compare', done: 0, total }),
@@ -281,8 +314,13 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
281
314
  await write();
282
315
  await flush();
283
316
  // No pack asks for contradictions: nothing waits, and an earlier run's awaiting set is left as it was.
284
- if (wantsCompare) await saveAwaiting(manifest, rootId, newClaims, outcome);
317
+ if (wantsCompare && !args.mechanical) await saveAwaiting(manifest, rootId, newClaims, outcome);
285
318
 
319
+ // Pass 2: what is still owed is every file of its slice it did not finish (an abort leaves the unreached ones owed too).
320
+ report.awaitingJudge = args.only ? work.filter((f) => !finished.has(f.path)).map((f) => f.path) : owedJudge;
321
+ report.awaitingJudgeCount = report.awaitingJudge.length;
322
+ report.judgedFiles = args.only ? work.length - report.awaitingJudge.length : 0;
323
+ if (breaker.stopped) report.judgeStopped = breaker.stopped;
286
324
  report.judged = batch.judged;
287
325
  report.unjudged = batch.unjudged;
288
326
  report.invalidJudgements = batch.invalid;
@@ -296,6 +334,6 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
296
334
  }));
297
335
  await write(report.aborted ? scopeRecord : { ...scopeRecord, lastDigest: report.digest, lastReviewedAt: new Date(now()).toISOString() });
298
336
  report.durationMs = now() - started;
299
- progress({ phase: 'done', done: changed.length, total: changed.length });
337
+ progress({ phase: 'done', done: work.length, total: work.length });
300
338
  return report;
301
339
  }