@seanhogg/builderforce-memory 2026.10.45 → 2026.10.47

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 (187) hide show
  1. package/README.md +21 -0
  2. package/dist/knowledge/build.d.ts.map +1 -1
  3. package/dist/knowledge/build.js +13 -7
  4. package/dist/knowledge/build.js.map +1 -1
  5. package/dist/knowledge/extractFile.d.ts +9 -1
  6. package/dist/knowledge/extractFile.d.ts.map +1 -1
  7. package/dist/knowledge/extractFile.js +25 -5
  8. package/dist/knowledge/extractFile.js.map +1 -1
  9. package/dist/knowledge/extractJob.d.ts +30 -5
  10. package/dist/knowledge/extractJob.d.ts.map +1 -1
  11. package/dist/knowledge/extractJob.js +9 -1
  12. package/dist/knowledge/extractJob.js.map +1 -1
  13. package/dist/knowledge/index.d.ts +5 -3
  14. package/dist/knowledge/index.d.ts.map +1 -1
  15. package/dist/knowledge/index.js +2 -1
  16. package/dist/knowledge/index.js.map +1 -1
  17. package/dist/knowledge/jobDeadline.d.ts +17 -0
  18. package/dist/knowledge/jobDeadline.d.ts.map +1 -0
  19. package/dist/knowledge/jobDeadline.js +46 -0
  20. package/dist/knowledge/jobDeadline.js.map +1 -0
  21. package/dist/knowledge/judgeCalls.d.ts +16 -0
  22. package/dist/knowledge/judgeCalls.d.ts.map +1 -1
  23. package/dist/knowledge/judgeCalls.js +20 -1
  24. package/dist/knowledge/judgeCalls.js.map +1 -1
  25. package/dist/knowledge/judgePriority.d.ts +22 -0
  26. package/dist/knowledge/judgePriority.d.ts.map +1 -0
  27. package/dist/knowledge/judgePriority.js +28 -0
  28. package/dist/knowledge/judgePriority.js.map +1 -0
  29. package/dist/knowledge/pack/crc32.d.ts +7 -0
  30. package/dist/knowledge/pack/crc32.d.ts.map +1 -0
  31. package/dist/knowledge/pack/crc32.js +22 -0
  32. package/dist/knowledge/pack/crc32.js.map +1 -0
  33. package/dist/knowledge/pack/decode.d.ts +14 -0
  34. package/dist/knowledge/pack/decode.d.ts.map +1 -0
  35. package/dist/knowledge/pack/decode.js +66 -0
  36. package/dist/knowledge/pack/decode.js.map +1 -0
  37. package/dist/knowledge/pack/deflate.d.ts +9 -0
  38. package/dist/knowledge/pack/deflate.d.ts.map +1 -0
  39. package/dist/knowledge/pack/deflate.js +45 -0
  40. package/dist/knowledge/pack/deflate.js.map +1 -0
  41. package/dist/knowledge/pack/encode.d.ts +26 -0
  42. package/dist/knowledge/pack/encode.d.ts.map +1 -0
  43. package/dist/knowledge/pack/encode.js +86 -0
  44. package/dist/knowledge/pack/encode.js.map +1 -0
  45. package/dist/knowledge/pack/extrDiff.d.ts +26 -0
  46. package/dist/knowledge/pack/extrDiff.d.ts.map +1 -0
  47. package/dist/knowledge/pack/extrDiff.js +129 -0
  48. package/dist/knowledge/pack/extrDiff.js.map +1 -0
  49. package/dist/knowledge/pack/frame.d.ts +45 -0
  50. package/dist/knowledge/pack/frame.d.ts.map +1 -0
  51. package/dist/knowledge/pack/frame.js +101 -0
  52. package/dist/knowledge/pack/frame.js.map +1 -0
  53. package/dist/knowledge/pack/hex.d.ts +7 -0
  54. package/dist/knowledge/pack/hex.d.ts.map +1 -0
  55. package/dist/knowledge/pack/hex.js +17 -0
  56. package/dist/knowledge/pack/hex.js.map +1 -0
  57. package/dist/knowledge/pack/index.d.ts +19 -0
  58. package/dist/knowledge/pack/index.d.ts.map +1 -0
  59. package/dist/knowledge/pack/index.js +17 -0
  60. package/dist/knowledge/pack/index.js.map +1 -0
  61. package/dist/knowledge/pack/jsonSize.d.ts +5 -0
  62. package/dist/knowledge/pack/jsonSize.d.ts.map +1 -0
  63. package/dist/knowledge/pack/jsonSize.js +8 -0
  64. package/dist/knowledge/pack/jsonSize.js.map +1 -0
  65. package/dist/knowledge/pack/manifest.d.ts +66 -0
  66. package/dist/knowledge/pack/manifest.d.ts.map +1 -0
  67. package/dist/knowledge/pack/manifest.js +104 -0
  68. package/dist/knowledge/pack/manifest.js.map +1 -0
  69. package/dist/knowledge/pack/sections/columns.d.ts +32 -0
  70. package/dist/knowledge/pack/sections/columns.d.ts.map +1 -0
  71. package/dist/knowledge/pack/sections/columns.js +53 -0
  72. package/dist/knowledge/pack/sections/columns.js.map +1 -0
  73. package/dist/knowledge/pack/sections/extr.d.ts +8 -0
  74. package/dist/knowledge/pack/sections/extr.d.ts.map +1 -0
  75. package/dist/knowledge/pack/sections/extr.js +99 -0
  76. package/dist/knowledge/pack/sections/extr.js.map +1 -0
  77. package/dist/knowledge/pack/sections/extrLists.d.ts +23 -0
  78. package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -0
  79. package/dist/knowledge/pack/sections/extrLists.js +200 -0
  80. package/dist/knowledge/pack/sections/extrLists.js.map +1 -0
  81. package/dist/knowledge/pack/sections/facts.d.ts +8 -0
  82. package/dist/knowledge/pack/sections/facts.d.ts.map +1 -0
  83. package/dist/knowledge/pack/sections/facts.js +172 -0
  84. package/dist/knowledge/pack/sections/facts.js.map +1 -0
  85. package/dist/knowledge/pack/sections/index.d.ts +6 -0
  86. package/dist/knowledge/pack/sections/index.d.ts.map +1 -0
  87. package/dist/knowledge/pack/sections/index.js +9 -0
  88. package/dist/knowledge/pack/sections/index.js.map +1 -0
  89. package/dist/knowledge/pack/sections/rows.d.ts +31 -0
  90. package/dist/knowledge/pack/sections/rows.d.ts.map +1 -0
  91. package/dist/knowledge/pack/sections/rows.js +227 -0
  92. package/dist/knowledge/pack/sections/rows.js.map +1 -0
  93. package/dist/knowledge/pack/strings.d.ts +43 -0
  94. package/dist/knowledge/pack/strings.d.ts.map +1 -0
  95. package/dist/knowledge/pack/strings.js +117 -0
  96. package/dist/knowledge/pack/strings.js.map +1 -0
  97. package/dist/knowledge/pack/types.d.ts +118 -0
  98. package/dist/knowledge/pack/types.d.ts.map +1 -0
  99. package/dist/knowledge/pack/types.js +17 -0
  100. package/dist/knowledge/pack/types.js.map +1 -0
  101. package/dist/knowledge/pack/varint.d.ts +57 -0
  102. package/dist/knowledge/pack/varint.d.ts.map +1 -0
  103. package/dist/knowledge/pack/varint.js +145 -0
  104. package/dist/knowledge/pack/varint.js.map +1 -0
  105. package/dist/knowledge/partitions.d.ts +1 -1
  106. package/dist/knowledge/partitions.d.ts.map +1 -1
  107. package/dist/knowledge/partitions.js +6 -1
  108. package/dist/knowledge/partitions.js.map +1 -1
  109. package/dist/knowledge/review.d.ts.map +1 -1
  110. package/dist/knowledge/review.js +58 -16
  111. package/dist/knowledge/review.js.map +1 -1
  112. package/dist/knowledge/reviewJudge.d.ts +8 -1
  113. package/dist/knowledge/reviewJudge.d.ts.map +1 -1
  114. package/dist/knowledge/reviewJudge.js +14 -8
  115. package/dist/knowledge/reviewJudge.js.map +1 -1
  116. package/dist/knowledge/reviewModel.d.ts +41 -1
  117. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  118. package/dist/knowledge/reviewPrefetch.d.ts +10 -2
  119. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
  120. package/dist/knowledge/reviewPrefetch.js +60 -25
  121. package/dist/knowledge/reviewPrefetch.js.map +1 -1
  122. package/dist/knowledge/reviewRun.d.ts +15 -3
  123. package/dist/knowledge/reviewRun.d.ts.map +1 -1
  124. package/dist/knowledge/reviewRun.js +19 -2
  125. package/dist/knowledge/reviewRun.js.map +1 -1
  126. package/dist/knowledge/reviewRunModel.d.ts +8 -1
  127. package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
  128. package/dist/knowledge/reviewRunModel.js.map +1 -1
  129. package/dist/knowledge/stores/localSnapshotStore.d.ts +72 -6
  130. package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
  131. package/dist/knowledge/stores/localSnapshotStore.js +279 -75
  132. package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
  133. package/package.json +8 -3
  134. package/src/contract/dist.contract.test.ts +44 -0
  135. package/src/contract/exports.contract.test.ts +90 -0
  136. package/src/contract/exports.snapshot.json +605 -0
  137. package/src/contract/pack.contract.test.ts +31 -0
  138. package/src/contract/regression.review.test.ts +236 -0
  139. package/src/contract/regression.store.test.ts +84 -0
  140. package/src/contract/types.contract.test.ts +183 -0
  141. package/src/knowledge/build.ts +11 -5
  142. package/src/knowledge/extractFile.ts +28 -6
  143. package/src/knowledge/extractJob.ts +26 -7
  144. package/src/knowledge/index.ts +5 -3
  145. package/src/knowledge/jobDeadline.ts +43 -0
  146. package/src/knowledge/judgeCalls.ts +19 -2
  147. package/src/knowledge/judgePriority.ts +36 -0
  148. package/src/knowledge/pack/crc32.ts +21 -0
  149. package/src/knowledge/pack/decode.ts +60 -0
  150. package/src/knowledge/pack/deflate.ts +43 -0
  151. package/src/knowledge/pack/encode.ts +89 -0
  152. package/src/knowledge/pack/extrDiff.ts +116 -0
  153. package/src/knowledge/pack/frame.ts +94 -0
  154. package/src/knowledge/pack/hex.ts +17 -0
  155. package/src/knowledge/pack/index.ts +26 -0
  156. package/src/knowledge/pack/jsonSize.ts +11 -0
  157. package/src/knowledge/pack/manifest.ts +128 -0
  158. package/src/knowledge/pack/pack.guards.test.ts +109 -0
  159. package/src/knowledge/pack/pack.reconcile.test.ts +96 -0
  160. package/src/knowledge/pack/pack.roundtrip.test.ts +50 -0
  161. package/src/knowledge/pack/pack.size.test.ts +22 -0
  162. package/src/knowledge/pack/pack.testkit.test-util.ts +90 -0
  163. package/src/knowledge/pack/sections/columns.ts +61 -0
  164. package/src/knowledge/pack/sections/extr.ts +90 -0
  165. package/src/knowledge/pack/sections/extrLists.ts +151 -0
  166. package/src/knowledge/pack/sections/facts.ts +126 -0
  167. package/src/knowledge/pack/sections/index.ts +13 -0
  168. package/src/knowledge/pack/sections/rows.ts +184 -0
  169. package/src/knowledge/pack/strings.ts +126 -0
  170. package/src/knowledge/pack/types.ts +97 -0
  171. package/src/knowledge/pack/varint.ts +145 -0
  172. package/src/knowledge/partitions.test.ts +4 -0
  173. package/src/knowledge/partitions.ts +3 -1
  174. package/src/knowledge/review.throughput.test.ts +122 -0
  175. package/src/knowledge/review.ts +54 -16
  176. package/src/knowledge/review.twoPass.test.ts +224 -0
  177. package/src/knowledge/reviewJudge.ts +19 -8
  178. package/src/knowledge/reviewModel.ts +38 -1
  179. package/src/knowledge/reviewPrefetch.ts +60 -24
  180. package/src/knowledge/reviewRun.test.ts +20 -3
  181. package/src/knowledge/reviewRun.ts +33 -6
  182. package/src/knowledge/reviewRunModel.ts +4 -1
  183. package/src/knowledge/stores/localSnapshotStore.batched.test.ts +25 -3
  184. package/src/knowledge/stores/localSnapshotStore.extractedLog.test.ts +280 -0
  185. package/src/knowledge/stores/localSnapshotStore.ts +283 -76
  186. package/src/knowledge/systems.test.ts +12 -0
  187. package/src/knowledge/testkit.test-util.ts +13 -2
@@ -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
  }
@@ -0,0 +1,224 @@
1
+ /**
2
+ * src/knowledge/review.twoPass.test.ts — PRD 41 A10: the map is complete without the model (pass 1,
3
+ * `mechanical`), judging follows in priority order within a budget (pass 2, `only`), the next run judges only what
4
+ * is still owed, a hanging job is a `timeout` failure that never stalls the run, and consecutive provider failures
5
+ * stop judging with the sections left owed.
6
+ */
7
+
8
+ import { hashText } from '../ingest/hash.js';
9
+ import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
10
+ import { DOCS_PACK } from './packs/docs.js';
11
+ import { extractJob } from './extractJob.js';
12
+ import type { ExtractPool } from './extractJob.js';
13
+ import { orderForJudging } from './judgePriority.js';
14
+ import { reviewDirectory } from './review.js';
15
+ import { applyRunEvent, slowestSteps, startRun } from './reviewRun.js';
16
+ import { LocalSnapshotStore } from './stores/localSnapshotStore.js';
17
+ import { args, fakeJudge, memPersistence, memSource, memStore, quietPack, ROOT, stateOf } from './testkit.test-util.js';
18
+ import type { ReviewStep } from './reviewRunModel.js';
19
+
20
+ const N = 6;
21
+ const files = () => Object.fromEntries(Array.from({ length: N }, (_, i) => [`d${i}.md`, `# T${i}\nbody ${i}\n`]));
22
+ const byKey = (a: { key: string }, b: { key: string }) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
23
+ const factsOf = async (store: ReturnType<typeof memStore>) => [...(await store.facts({ rootId: ROOT }))].sort(byKey);
24
+
25
+ describe('two-pass review', () => {
26
+ it('pass 1 makes no model call, completes the extract cache and lists every judged file as awaiting judgement', async () => {
27
+ const judge = fakeJudge();
28
+ const store = memStore();
29
+ const manifest = new InMemoryIngestManifest();
30
+ const report = await reviewDirectory(args(memSource(files()), store, manifest, { judgement: judge, mechanical: true, packs: [quietPack] }));
31
+ expect(judge.requests).toHaveLength(0);
32
+ expect(report.awaitingJudge).toEqual(Object.keys(files()));
33
+ expect(report.extracted).toBe(N);
34
+ expect(await factsOf(store)).toEqual([]);
35
+ expect(await store.getExtracted(hashText(files()['d0.md']!))).toBeDefined(); // the map has the file
36
+ expect((await stateOf(manifest)).owed).toEqual(Object.keys(files()));
37
+ });
38
+
39
+ it('pass 2 judges only the files named, and the next run judges only what is still owed', async () => {
40
+ const judge = fakeJudge();
41
+ const store = memStore();
42
+ const manifest = new InMemoryIngestManifest();
43
+ const source = memSource(files());
44
+ const base = { judgement: judge, packs: [quietPack] };
45
+ await reviewDirectory(args(source, store, manifest, { ...base, mechanical: true }));
46
+ const first = await reviewDirectory(args(source, store, manifest, { ...base, only: ['d3.md', 'd1.md'] }));
47
+ const judgedFirst = new Set(judge.requests.flatMap((r) => r.items.map((it) => it.ref as string)));
48
+ expect(judgedFirst.size).toBe(2);
49
+ expect([...judgedFirst].every((r) => r.includes('d1.md') || r.includes('d3.md'))).toBe(true);
50
+ expect((await stateOf(manifest)).owed).toEqual(['d0.md', 'd2.md', 'd4.md', 'd5.md']);
51
+ expect(first.judged).toBe(2);
52
+
53
+ judge.requests.length = 0;
54
+ const next = await reviewDirectory(args(source, store, manifest, base));
55
+ const judgedNext = judge.requests.flatMap((r) => r.items.map((it) => it.ref as string));
56
+ expect(judgedNext).toHaveLength(4);
57
+ expect(judgedNext.some((r) => r.includes('d1.md') || r.includes('d3.md'))).toBe(false);
58
+ expect(next.judged).toBe(4);
59
+ expect((await stateOf(manifest)).owed).toEqual([]);
60
+ });
61
+
62
+ it('mechanical pass then pass 2 over every file stores the same facts as one sequential pass', async () => {
63
+ const single = memStore();
64
+ await reviewDirectory(args(memSource(files()), single, new InMemoryIngestManifest(), { judgement: fakeJudge(), packs: [quietPack], concurrency: 1, judgeConcurrency: 1 }));
65
+
66
+ const two = memStore();
67
+ const manifest = new InMemoryIngestManifest();
68
+ const source = memSource(files());
69
+ await reviewDirectory(args(source, two, manifest, { judgement: fakeJudge(), packs: [quietPack], mechanical: true, concurrency: 4 }));
70
+ await reviewDirectory(args(source, two, manifest, { judgement: fakeJudge(), packs: [quietPack], only: Object.keys(files()), concurrency: 4 }));
71
+ expect(await factsOf(two)).toEqual(await factsOf(single));
72
+ const relKey = (r: { from: string; to: string; kind: string }) => `${r.from}|${r.to}|${r.kind}`;
73
+ const sorted = async (st: ReturnType<typeof memStore>) => [...(await st.relations({ rootId: ROOT }))].sort((a, b) => (relKey(a) < relKey(b) ? -1 : 1));
74
+ expect(await sorted(two)).toEqual(await sorted(single));
75
+ });
76
+ });
77
+
78
+ describe('pass 1 owes only what costs a model call, and a partial budget stores what a sequential run stores', () => {
79
+ const K = 3;
80
+ const bytesOf = (p: { value?: string }) => {
81
+ const snap = JSON.parse(p.value!) as { scopes: Array<Record<string, unknown>> };
82
+ for (const sc of snap.scopes) delete sc.lastReviewedAt; // the wall clock of the run
83
+ return JSON.stringify(snap);
84
+ };
85
+
86
+ it('mechanical + pass 2 over the first K files equals one sequential run with a budget of K calls, byte for byte', async () => {
87
+ const seq = memPersistence();
88
+ await reviewDirectory(args(memSource(files()), new LocalSnapshotStore(seq, { now: () => 'T' }), new InMemoryIngestManifest(), {
89
+ judgement: fakeJudge(), packs: [quietPack], concurrency: 1, judgeConcurrency: 1, budget: { modelCalls: K, ms: 60_000 },
90
+ }));
91
+
92
+ const two = memPersistence();
93
+ const store = new LocalSnapshotStore(two, { now: () => 'T' });
94
+ const manifest = new InMemoryIngestManifest();
95
+ const source = memSource(files());
96
+ await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge(), packs: [quietPack], mechanical: true }));
97
+ await reviewDirectory(args(source, store, manifest, {
98
+ judgement: fakeJudge(), packs: [quietPack], only: Object.keys(files()).slice(0, K), budget: { modelCalls: K, ms: 60_000 },
99
+ }));
100
+ expect(bytesOf(two)).toEqual(bytesOf(seq));
101
+ });
102
+
103
+ it('a re-review of files whose sections are all still judged owes nothing and calls no model', async () => {
104
+ const store = memStore();
105
+ const manifest = new InMemoryIngestManifest();
106
+ const source = memSource(files());
107
+ await reviewDirectory(args(source, store, manifest, { judgement: fakeJudge(), packs: [quietPack] }));
108
+ const judge = fakeJudge();
109
+ const report = await reviewDirectory(args(source, store, manifest, { judgement: judge, packs: [quietPack], mechanical: true, force: true }));
110
+ expect(judge.requests).toHaveLength(0);
111
+ expect(report.awaitingJudge).toEqual([]);
112
+ expect((await stateOf(manifest)).owed).toEqual([]);
113
+ });
114
+
115
+ it('pass 2 follows the order it is given and reports what it left owed, unreached files included', async () => {
116
+ const judge = fakeJudge();
117
+ const store = memStore();
118
+ const manifest = new InMemoryIngestManifest();
119
+ const source = memSource(files());
120
+ const base = { judgement: judge, packs: [quietPack] };
121
+ await reviewDirectory(args(source, store, manifest, { ...base, mechanical: true }));
122
+ const order = ['d4.md', 'd0.md', 'd2.md'];
123
+ const report = await reviewDirectory(args(source, store, manifest, { ...base, only: order, concurrency: 1, judgeConcurrency: 1, budget: { modelCalls: 1, ms: 60_000 } }));
124
+ expect(judge.requests.map((r) => r.items[0]!.ref)).toEqual(['src:r::d4.md#'].map((p) => expect.stringContaining(p)));
125
+ expect(report.judgedFiles).toBe(1);
126
+ expect(report.awaitingJudge).toEqual(['d0.md', 'd2.md']);
127
+ });
128
+ });
129
+
130
+ describe('per-job timeouts', () => {
131
+ const hang = (path: string): ExtractPool => (job, signal) =>
132
+ job.path === path
133
+ ? new Promise((_, reject) => signal?.addEventListener('abort', () => reject(new Error('aborted')), { once: true }))
134
+ : Promise.resolve(extractJob(job, [DOCS_PACK]));
135
+
136
+ it('a hanging extractor is one timeout failure (its worker told to stop) and the run continues', async () => {
137
+ const steps: ReviewStep[] = [];
138
+ const started = Date.now();
139
+ const report = await reviewDirectory(args(memSource(files()), memStore(), new InMemoryIngestManifest(), {
140
+ extractPool: hang('d2.md'), concurrency: 2, timeouts: { extractMs: 60 }, onStep: (s) => steps.push(s),
141
+ }));
142
+ expect(Date.now() - started).toBeLessThan(5_000);
143
+ expect(report.aborted).toBe(false);
144
+ expect(report.extractErrors).toBe(1);
145
+ expect(report.failures).toEqual([{ path: 'd2.md', phase: 'extract', reason: 'timeout' }]);
146
+ expect(report.extracted).toBe(N - 1);
147
+ expect(steps.filter((s) => s.phase === 'extract' && s.outcome === 'failed').map((s) => s.reason)).toEqual(['timeout']);
148
+ });
149
+
150
+ it('a read that never returns is a failed read with a timeout and the file keeps its prior state', async () => {
151
+ const source = memSource(files());
152
+ const read = source.read.bind(source);
153
+ source.read = (path) => (path === 'd1.md' ? new Promise(() => undefined) : read(path));
154
+ const report = await reviewDirectory(args(source, memStore(), new InMemoryIngestManifest(), { timeouts: { readMs: 40 } }));
155
+ expect(report.readErrors).toBe(1);
156
+ expect(report.failures).toEqual([{ path: 'd1.md', phase: 'extract', reason: 'read: timeout' }]);
157
+ expect(report.extracted).toBe(N - 1);
158
+ });
159
+
160
+ it('queued jobs are not timed out while they wait for a pool slot', async () => {
161
+ let busy = 0, peak = 0;
162
+ const slow: ExtractPool = async (job) => {
163
+ busy += 1; peak = Math.max(peak, busy);
164
+ await new Promise((r) => setTimeout(r, 30));
165
+ busy -= 1;
166
+ return extractJob(job, [DOCS_PACK]);
167
+ };
168
+ const report = await reviewDirectory(args(memSource(files()), memStore(), new InMemoryIngestManifest(), {
169
+ extractPool: slow, concurrency: 1, readAhead: 6, timeouts: { extractMs: 200 },
170
+ }));
171
+ expect(peak).toBe(1);
172
+ expect(report.failures).toEqual([]);
173
+ expect(report.extracted).toBe(N);
174
+ });
175
+ });
176
+
177
+ describe('judge breaker', () => {
178
+ it('stops judging after consecutive failures; the unjudged sections stay owed and the next run judges them', async () => {
179
+ let fail = true;
180
+ const calls: string[] = [];
181
+ const judge = {
182
+ async judge(req: Parameters<ReturnType<typeof fakeJudge>['judge']>[0]) {
183
+ calls.push(req.items[0]!.ref as string);
184
+ if (fail) throw new Error('judge: timeout after 60s');
185
+ return fakeJudge().judge(req);
186
+ },
187
+ };
188
+ const store = memStore();
189
+ const manifest = new InMemoryIngestManifest();
190
+ const source = memSource(files());
191
+ const report = await reviewDirectory(args(source, store, manifest, { judgement: judge, packs: [quietPack], concurrency: 1, judgeConcurrency: 1 }));
192
+ expect(calls.length).toBe(5);
193
+ expect(report.judgeStopped).toMatch(/5 model calls failed in a row/);
194
+ expect(report.judged).toBe(0);
195
+ expect((await stateOf(manifest)).owed).toEqual(Object.keys(files()));
196
+
197
+ fail = false;
198
+ calls.length = 0;
199
+ const next = await reviewDirectory(args(source, store, manifest, { judgement: judge, packs: [quietPack] }));
200
+ expect(next.judged).toBe(N);
201
+ expect((await stateOf(manifest)).owed).toEqual([]);
202
+ });
203
+ });
204
+
205
+ describe('judge priority and the slowest steps', () => {
206
+ it('orders entry points, then inbound references (most first), then recent, then the rest, ties by path', () => {
207
+ const paths = ['z.md', 'b.md', 'a.md', 'recent.md', 'hub.md', 'README.md', 'few.md'];
208
+ const order = orderForJudging(paths, {
209
+ entry: (p) => p === 'README.md',
210
+ inbound: new Map([['hub.md', 9], ['few.md', 2]]),
211
+ recent: new Set(['recent.md']),
212
+ });
213
+ expect(order).toEqual(['README.md', 'hub.md', 'few.md', 'recent.md', 'a.md', 'b.md', 'z.md']);
214
+ expect(paths[0]).toBe('z.md');
215
+ });
216
+
217
+ it('slowestSteps lists the longest steps first with their reasons', () => {
218
+ let run = startRun({ id: 'r', root: ROOT, kind: 'review', at: 0 });
219
+ for (const [path, ms, reason] of [['a', 5, undefined], ['b', 9000, 'timeout'], ['c', 300, undefined]] as const) {
220
+ run = applyRunEvent(run, { type: 'step', step: { path, phase: 'extract', ms, outcome: reason ? 'failed' : 'ok', ...(reason ? { reason } : {}) } }, 1);
221
+ }
222
+ expect(slowestSteps(run, 2).map((s) => [s.path, s.reason])).toEqual([['b', 'timeout'], ['c', undefined]]);
223
+ });
224
+ });
@@ -19,7 +19,7 @@
19
19
  import { hashText } from '../ingest/hash.js';
20
20
  import { SECTION_INDEX_BADGE } from '../ingest/docsExtract.js';
21
21
  import { budgetLeft, type JudgeBudget, type JudgedBatch, type SectionToJudge } from './judge.js';
22
- import { applyAnswers, callSections, type SectionAnswer } from './judgeCalls.js';
22
+ import { applyAnswers, callSections, type JudgeBreaker, type SectionAnswer } from './judgeCalls.js';
23
23
  import type { FileExtraction } from './extractFile.js';
24
24
  import type { KnowledgePack, NodeRef, ReviewArgs, ReviewReport, StoredFact } from './model.js';
25
25
  import type { ModelLimiter } from './modelLimiter.js';
@@ -55,23 +55,34 @@ export interface JudgeDispatch {
55
55
  judgedPrior: ReadonlyMap<string, string>;
56
56
  lanes: Lanes;
57
57
  limiter: ModelLimiter;
58
+ /** Stops judging for the run after consecutive provider failures. */
59
+ breaker?: JudgeBreaker;
58
60
  }
59
61
 
60
- /** Starts judging a file's changed sections; undefined when its pack asks for no judgement (or there is no port). */
61
- export function startJudge(d: JudgeDispatch, f: { path: string; hash: string }, extraction: FileExtraction): JudgeJob | undefined {
62
+ /** The sections of a file the model has to judge (changed text) and those whose judgement is still current. */
63
+ export function splitSections(
64
+ judgedPrior: ReadonlyMap<string, string>, extraction: FileExtraction,
65
+ ): { reuse: NodeRef[]; toJudge: SectionToJudge[] } {
62
66
  const { extracted: ex, sections, pack } = extraction;
63
- const port = d.port;
64
- if (!port || !judgesPack(port, pack)) return undefined;
65
- const kinds = new Set(pack.judgement!.nodeKinds);
67
+ const kinds = new Set(pack.judgement?.nodeKinds ?? []);
66
68
  const reuse: NodeRef[] = [];
67
69
  const toJudge: SectionToJudge[] = [];
68
70
  for (const node of ex.nodes) {
69
71
  const index = node.badges?.[SECTION_INDEX_BADGE];
70
72
  const text = typeof index === 'number' ? sections[index]?.text : undefined;
71
73
  if (!kinds.has(node.kind) || !text) continue;
72
- if (d.judgedPrior.get(node.ref) === hashText(text)) reuse.push(node.ref);
74
+ if (judgedPrior.get(node.ref) === hashText(text)) reuse.push(node.ref);
73
75
  else toJudge.push({ ref: node.ref, text });
74
76
  }
77
+ return { reuse, toJudge };
78
+ }
79
+
80
+ /** Starts judging a file's changed sections; undefined when its pack asks for no judgement (or there is no port). */
81
+ export function startJudge(d: JudgeDispatch, f: { path: string; hash: string }, extraction: FileExtraction): JudgeJob | undefined {
82
+ const { pack } = extraction;
83
+ const port = d.port;
84
+ if (!port || !judgesPack(port, pack)) return undefined;
85
+ const { reuse, toJudge } = splitSections(d.judgedPrior, extraction);
75
86
  // Reserved now, in plan order: this file's calls come out of the shared budget before any later file's.
76
87
  const allot = budgetLeft(d.budget) ? Math.min(toJudge.length, Math.max(0, d.budget.modelCalls - d.budget.used)) : 0;
77
88
  d.budget.used += allot;
@@ -81,7 +92,7 @@ export function startJudge(d: JudgeDispatch, f: { path: string; hash: string },
81
92
  const lane = d.lanes.take();
82
93
  const t0 = Date.now();
83
94
  try {
84
- const r = await callSections({ port, fileHash: f.hash, sections: toJudge, budget: slice, limiter: d.limiter, signal: d.signal });
95
+ const r = await callSections({ port, fileHash: f.hash, sections: toJudge, budget: slice, limiter: d.limiter, signal: d.signal, ...(d.breaker ? { breaker: d.breaker } : {}) });
85
96
  // Every call that was made failed: the provider is refusing us (key, quota, network), not the file.
86
97
  if (r.answers.length === 0 && r.errors > 0) {
87
98
  return { status: 'error', reason: `judge: ${r.firstError ?? 'model call failed'}`, ms: Date.now() - t0, lane };
@@ -15,8 +15,15 @@ export interface DirectorySource {
15
15
  rootId: string;
16
16
  title: string;
17
17
  list(): AsyncIterable<{ path: string; hash: string; size: number }>;
18
- read(path: string): Promise<SourceDocument>;
18
+ /** `signal` aborts the read when the review gives up on it (a per-job timeout, a stop); a source that cannot cancel may ignore it. */
19
+ read(path: string, signal?: AbortSignal): Promise<SourceDocument>;
19
20
  watch?(cb: (paths: string[]) => void): () => void;
21
+ /**
22
+ * The function that produced the `hash` of `list()` entries, over a text file's content. When given, the review hashes the
23
+ * text it read (once) and a file whose bytes no longer match the planned hash fails with "changed since plan" and stays owed.
24
+ * Optional: a source whose hash is not a pure function of the text (or that cannot say) is not checked in-thread.
25
+ */
26
+ hashOf?(text: string): string;
20
27
  }
21
28
 
22
29
  export interface ReviewPlan {
@@ -29,6 +36,8 @@ export interface ReviewPlan {
29
36
  skipped: Array<{ path: string; reason: 'ignored' | 'binary' | 'too-large' | 'no-pack' }>;
30
37
  /** ≈ judgement calls for changed files (sections of judged kinds). */
31
38
  estimatedModelCalls: number;
39
+ /** The file budget of the judge pass this run will run after the map is complete (PRD 41 A10); set by the host, so the confirm chip states it. */
40
+ judgeFiles?: number;
32
41
  }
33
42
 
34
43
  export interface ReviewProgress {
@@ -59,6 +68,17 @@ export interface ReviewReport {
59
68
  extractErrors: number;
60
69
  /** Every file this run could not finish (read, extract, judge), with why. */
61
70
  failures: ReviewFailure[];
71
+ /**
72
+ * Files still owed model judgement after this run (PRD 41 A10): in a `mechanical` run every file of a judged pack
73
+ * with a section to judge; otherwise the files a budget cut or a failed call left. Plan order.
74
+ */
75
+ awaitingJudge: string[];
76
+ /** How many files are awaiting judgement: the ONLY form that leaves memory — hosts persist and send this, never the path list. */
77
+ awaitingJudgeCount?: number;
78
+ /** Pass 2 (`only`): files of the slice judged to completion. */
79
+ judgedFiles?: number;
80
+ /** Judging was stopped for this run after consecutive provider failures (A10 rule 9); the files stay owed. */
81
+ judgeStopped?: string;
62
82
  aborted: boolean;
63
83
  durationMs: number;
64
84
  }
@@ -105,6 +125,23 @@ export interface ReviewArgs {
105
125
  * A result without the file's exact `sourceRef` fails that file's extraction (prior knowledge kept).
106
126
  */
107
127
  extractPool?: ExtractPool;
128
+ /**
129
+ * Pass 1 of a two-pass review (PRD 41 A10): read, extract, write — no model call. A file whose pack asks for
130
+ * judgement and has sections to judge stays OWED (manifest hash unchanged) and is listed in `report.awaitingJudge`;
131
+ * the map is complete without it. A later run without `mechanical` (pass 2) judges it.
132
+ */
133
+ mechanical?: boolean;
134
+ /** Restrict the run to these changed paths (pass 2: the prioritized, budgeted slice). Other changed files are untouched and stay owed. */
135
+ only?: readonly string[];
136
+ /**
137
+ * With an `extractPool`: the pool reads each file itself (PRD 41 A10 rule 8) — the job carries the path and the planned hash,
138
+ * the main thread neither reads nor copies the text, and a binary file comes back as `binary`. The pool must support `readByPool` jobs.
139
+ */
140
+ deferRead?: boolean;
141
+ /** Files read and extracted ahead of the writer (default: the pool's width times 4, 32..64, with a pool; else `concurrency`). Wider than the pool, so workers never wait for the writer. */
142
+ readAhead?: number;
143
+ /** Per-job ceilings in ms for the extract path (PRD 41 A10): reads 5000, extract (pool dispatch included) 10000. A job over its ceiling is a failed step with reason `timeout`. */
144
+ timeouts?: { readMs?: number; extractMs?: number };
108
145
  /** One event per file per phase, as it happens (PRD 41 A8). */
109
146
  onStep?(step: ReviewStep): void;
110
147
  onProgress?(p: ReviewProgress): void;