@seanhogg/builderforce-memory 2026.10.42 → 2026.10.44

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 (69) hide show
  1. package/dist/knowledge/externals.d.ts +9 -0
  2. package/dist/knowledge/externals.d.ts.map +1 -0
  3. package/dist/knowledge/externals.js +8 -0
  4. package/dist/knowledge/externals.js.map +1 -0
  5. package/dist/knowledge/extractFile.d.ts +15 -0
  6. package/dist/knowledge/extractFile.d.ts.map +1 -1
  7. package/dist/knowledge/extractFile.js +40 -17
  8. package/dist/knowledge/extractFile.js.map +1 -1
  9. package/dist/knowledge/extractJob.d.ts +64 -0
  10. package/dist/knowledge/extractJob.d.ts.map +1 -0
  11. package/dist/knowledge/extractJob.js +47 -0
  12. package/dist/knowledge/extractJob.js.map +1 -0
  13. package/dist/knowledge/index.d.ts +11 -1
  14. package/dist/knowledge/index.d.ts.map +1 -1
  15. package/dist/knowledge/index.js +7 -1
  16. package/dist/knowledge/index.js.map +1 -1
  17. package/dist/knowledge/judge.d.ts +23 -5
  18. package/dist/knowledge/judge.d.ts.map +1 -1
  19. package/dist/knowledge/judge.js +14 -76
  20. package/dist/knowledge/judge.js.map +1 -1
  21. package/dist/knowledge/judgeCalls.d.ts +52 -0
  22. package/dist/knowledge/judgeCalls.d.ts.map +1 -0
  23. package/dist/knowledge/judgeCalls.js +107 -0
  24. package/dist/knowledge/judgeCalls.js.map +1 -0
  25. package/dist/knowledge/modelLimiter.d.ts +20 -0
  26. package/dist/knowledge/modelLimiter.d.ts.map +1 -0
  27. package/dist/knowledge/modelLimiter.js +63 -0
  28. package/dist/knowledge/modelLimiter.js.map +1 -0
  29. package/dist/knowledge/review.d.ts +6 -2
  30. package/dist/knowledge/review.d.ts.map +1 -1
  31. package/dist/knowledge/review.js +108 -112
  32. package/dist/knowledge/review.js.map +1 -1
  33. package/dist/knowledge/reviewJudge.d.ts +95 -0
  34. package/dist/knowledge/reviewJudge.d.ts.map +1 -0
  35. package/dist/knowledge/reviewJudge.js +119 -0
  36. package/dist/knowledge/reviewJudge.js.map +1 -0
  37. package/dist/knowledge/reviewModel.d.ts +30 -2
  38. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  39. package/dist/knowledge/reviewPrefetch.d.ts +53 -0
  40. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -0
  41. package/dist/knowledge/reviewPrefetch.js +65 -0
  42. package/dist/knowledge/reviewPrefetch.js.map +1 -0
  43. package/dist/knowledge/reviewRun.d.ts +70 -0
  44. package/dist/knowledge/reviewRun.d.ts.map +1 -0
  45. package/dist/knowledge/reviewRun.js +88 -0
  46. package/dist/knowledge/reviewRun.js.map +1 -0
  47. package/dist/knowledge/reviewRunModel.d.ts +35 -0
  48. package/dist/knowledge/reviewRunModel.d.ts.map +1 -0
  49. package/dist/knowledge/reviewRunModel.js +27 -0
  50. package/dist/knowledge/reviewRunModel.js.map +1 -0
  51. package/package.json +3 -3
  52. package/src/knowledge/externals.test.ts +21 -0
  53. package/src/knowledge/externals.ts +10 -0
  54. package/src/knowledge/extractFile.ts +49 -17
  55. package/src/knowledge/extractJob.ts +91 -0
  56. package/src/knowledge/index.ts +11 -1
  57. package/src/knowledge/judge.ts +24 -70
  58. package/src/knowledge/judgeCalls.ts +136 -0
  59. package/src/knowledge/modelLimiter.test.ts +68 -0
  60. package/src/knowledge/modelLimiter.ts +68 -0
  61. package/src/knowledge/review.failures.test.ts +277 -0
  62. package/src/knowledge/review.ordered.test.ts +114 -0
  63. package/src/knowledge/review.ts +102 -100
  64. package/src/knowledge/reviewJudge.ts +155 -0
  65. package/src/knowledge/reviewModel.ts +30 -2
  66. package/src/knowledge/reviewPrefetch.ts +86 -0
  67. package/src/knowledge/reviewRun.test.ts +96 -0
  68. package/src/knowledge/reviewRun.ts +137 -0
  69. package/src/knowledge/reviewRunModel.ts +53 -0
@@ -7,8 +7,12 @@
7
7
  * of judged kinds, within budget) · write · markStale → analyzers → compare near-duplicate
8
8
  * claims → manifest + scope digest. Claims whose compare pairs were skipped wait in the
9
9
  * compare manifest for *Continue*.
10
- * Read + extract are prefetched with bounded concurrency (`args.concurrency`); judge · write ·
11
- * markStale stay in file order, so the shared model-call budget is spent deterministically.
10
+ * Read + extract are prefetched with bounded concurrency (`args.concurrency`; through `args.extractPool`
11
+ * when a host supplies one) and up to `args.judgeConcurrency` files are judged at once, but ONE writer
12
+ * applies judge · write · markStale strictly in file order, and each file's model calls are reserved from
13
+ * the shared budget in file order — so the stored bytes and the budget spend do not depend on the widths
14
+ * (PRD 41 A8). A file whose read, extraction or judging fails is recorded in `report.failures` and skipped;
15
+ * only an abort or a local store write error ends the run.
12
16
  *
13
17
  * Store judgement, compute perception: only `model` facts and relations are written —
14
18
  * `extracted` output goes to the extracted cache, never to memory ({@link assertStoredBatch}).
@@ -22,28 +26,32 @@
22
26
  * next review or *Continue* picks up exactly those files, whatever their content does.
23
27
  */
24
28
 
25
- import { hashText } from '../ingest/hash.js';
26
- import type { SourceDocument } from '../ingest/types.js';
27
29
  import { sha256Hex } from '../retrieval/knowledge-index/sha256.js';
28
- import type { NodeRef, ReviewArgs, ReviewReport, ScopeRecord, StoredFact, StoredRelation } from './model.js';
29
- import { SECTION_INDEX_BADGE } from '../ingest/docsExtract.js';
30
+ import type { ReviewArgs, ReviewReport, ScopeRecord, StoredFact, StoredRelation } from './model.js';
30
31
  import { owedAfterRun, owedCalls, saveExtractorState } from './owedFiles.js';
31
32
  import { planDetail, refreshPlan } from './plan.js';
32
- import { composePacks, filesManifestKey, isBinaryText, judgedManifestKey, manifestMap, saveManifestMap } from './sources.js';
33
- import { extractFileDetailed, knownKeysOfEntities, type FileExtraction } from './extractFile.js';
33
+ import { composePacks, filesManifestKey, judgedManifestKey, manifestMap, saveManifestMap } from './sources.js';
34
+ import { knownKeysOfEntities, putExtract } from './extractFile.js';
34
35
  import { prefetchOrdered } from './orderedPool.js';
35
- import { DEFAULT_REVIEW_CONCURRENCY, DEFAULT_REVIEW_MODEL_CALLS, JudgedBatch, judgeSections, type CompareOutcome, type JudgeBudget } from './judge.js';
36
+ import {
37
+ DEFAULT_REVIEW_CONCURRENCY, DEFAULT_REVIEW_JUDGE_CONCURRENCY, DEFAULT_REVIEW_MODEL_CALLS, JUDGE_CONCURRENCY, JudgedBatch,
38
+ type CompareOutcome, type JudgeBudget,
39
+ } from './judge.js';
40
+ import { createModelLimiter } from './modelLimiter.js';
41
+ import { applyJudge, startJudge, type JudgeJob } from './reviewJudge.js';
42
+ import { createPrefetch, type Prefetch } from './reviewPrefetch.js';
43
+ import { Lanes } from './reviewRunModel.js';
36
44
  import { compareNew, pendingClaims, saveAwaiting } from './reviewCompare.js';
37
45
  import { factsWithoutAnchor, StoredIndex } from './reviewStored.js';
38
46
  import { canonicalJson, compareStr, srcRef } from './refs.js';
39
47
 
40
- /** What the prefetch stage learned about one file; `failed` carries an extraction throw to be rethrown in file order. */
41
- type Prefetch =
42
- | { kind: 'read-error' }
43
- | { kind: 'binary' }
44
- | { kind: 'none' }
45
- | { kind: 'extracted'; doc: SourceDocument; extraction: FileExtraction }
46
- | { kind: 'failed'; error: unknown };
48
+ /** One changed file between dispatch and the ordered writer: what its prefetch found and its judging in flight. */
49
+ interface Slot {
50
+ f: { path: string; hash: string };
51
+ i: number;
52
+ job: Prefetch;
53
+ judge: JudgeJob | undefined;
54
+ }
47
55
 
48
56
  /** Throws if a batch carries `extracted` items — perception is never memory. */
49
57
  export function assertStoredBatch(batch: { facts: readonly StoredFact[]; relations: readonly StoredRelation[] }): void {
@@ -68,7 +76,7 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
68
76
  const progress = (p: Parameters<NonNullable<ReviewArgs['onProgress']>>[0]) => args.onProgress?.(p);
69
77
  const report: ReviewReport = {
70
78
  rootId, digest: '', extracted: 0, judged: 0, unjudged: 0, invalidJudgements: 0,
71
- factsWritten: 0, relationsWritten: 0, staleMarked: 0, readErrors: 0, aborted: false, durationMs: 0,
79
+ factsWritten: 0, relationsWritten: 0, staleMarked: 0, readErrors: 0, extractErrors: 0, failures: [], aborted: false, durationMs: 0,
72
80
  };
73
81
 
74
82
  const detail = args.plan
@@ -134,46 +142,42 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
134
142
  const hashes = [...new Set(changed.map((f) => f.hash))];
135
143
  if (hashes.length > 0) await store.preloadExtracted?.(hashes);
136
144
  // Read + binary check + extract run ahead with bounded concurrency (extraction only reads `knownKeys`,
137
- // fixed above, and the content-hash extract cache); everything after stays sequential, in file order.
145
+ // fixed above, and the content-hash extract cache); with `args.extractPool` the width is the pool's.
146
+ // Judging runs `judgeWidth` files at once; ONE writer (`applyFile`) consumes them strictly in plan order.
138
147
  const concurrency = Math.min(32, Math.max(1, Math.floor(args.concurrency ?? DEFAULT_REVIEW_CONCURRENCY) || 1));
139
- // extractFileDetailed read-modify-writes the extract cache entry of a content hash, so files sharing a hash
140
- // extract one after another, in file order (jobs start in file order). Reads still overlap. A job always
141
- // releases its turn, so a failed predecessor never blocks or poisons the next one.
142
- const hashTail = new Map<string, Promise<void>>();
143
- const prefetch = async (f: (typeof changed)[number]): Promise<Prefetch> => {
144
- const before = hashTail.get(f.hash) ?? Promise.resolve();
145
- let release!: () => void;
146
- const mine = new Promise<void>((r) => { release = r; });
147
- const tail = before.then(() => mine);
148
- hashTail.set(f.hash, tail);
149
- try {
150
- let doc: SourceDocument;
151
- try { doc = await source.read(f.path); } catch { return { kind: 'read-error' }; }
152
- try {
153
- if (doc.content.kind === 'text' && isBinaryText(doc.content.text)) return { kind: 'binary' };
154
- await before;
155
- const extraction = await extractFileDetailed({
156
- rootId, path: f.path, hash: f.hash, doc, packs, store, composed, knownKeys,
157
- });
158
- return extraction ? { kind: 'extracted', doc, extraction } : { kind: 'none' };
159
- } catch (error) { return { kind: 'failed', error }; }
160
- } finally {
161
- release();
162
- void tail.then(() => { if (hashTail.get(f.hash) === tail) hashTail.delete(f.hash); });
163
- }
148
+ const judgeWidth = Math.min(concurrency, Math.min(16, Math.max(1, Math.floor(args.judgeConcurrency ?? DEFAULT_REVIEW_JUDGE_CONCURRENCY) || 1)));
149
+ // The run's own stop: the caller's abort relays into it, and a thrown error (a local store failure) aborts it,
150
+ // so queued and in-flight judge calls and pool jobs stop and nothing outlives the run.
151
+ const stopper = new AbortController();
152
+ // An abort that lands while the writer is mid-file ends the run at that file's boundary, as a sequential run
153
+ // does (`cut`); one that lands anywhere else (a read, a model call) keeps every file whose work completed.
154
+ let inWriter = false;
155
+ let cut = false;
156
+ const relay = () => { if (inWriter) cut = true; stopper.abort(signal?.reason); };
157
+ if (signal?.aborted) relay(); else signal?.addEventListener('abort', relay, { once: true });
158
+ const runSignal = stopper.signal;
159
+ const prefetch = createPrefetch({ args, signal: runSignal, rootId, packs, store, composed, knownKeys, width: concurrency });
160
+ const dispatch = {
161
+ port: args.judgement, signal: runSignal, budget, judgedPrior, lanes: new Lanes(judgeWidth),
162
+ limiter: createModelLimiter(args.maxModelCalls ?? JUDGE_CONCURRENCY),
164
163
  };
165
- let consumed = 0;
166
- for await (const { item: f, i, result } of prefetchOrdered(changed, concurrency, prefetch, signal)) {
167
- consumed += 1; // the pool ends the stream at a file boundary once aborted, discarding read-ahead
164
+ const judgeCtx = { batch, entities, stored, judgedNow, newClaims, measured, detail, report, ...(args.onStep ? { onStep: args.onStep } : {}) };
165
+ const fail = (path: string, phase: 'extract' | 'judge', reason: string) => report.failures.push({ path, phase, reason });
166
+
167
+ /**
168
+ * Applies one file, in plan order. False when its work was cut short by an abort (extracted, judging
169
+ * unfinished): nothing of it is applied and it stays as it was, owed. A file whose work is complete is
170
+ * applied even after an abort — the work is done, so it is kept.
171
+ */
172
+ const applyInner = async ({ f, i, job, judge }: Slot): Promise<boolean> => {
168
173
  progress({ phase: 'extract', done: i, total: changed.length, path: f.path });
169
- // A read that throws (permissions, a lock, a race with a delete) says nothing about the file:
170
- // skipped with its knowledge and manifest hash intact, tried again next review.
171
- if (result.status === 'rejected') throw result.reason; // unreachable: a prefetch job settles to a Prefetch
172
- const job = result.value;
173
- if (job.kind === 'read-error') {
174
- report.readErrors += 1;
175
- measured.set(f.path, owedCalls(detail.extractor, f.path)); // a read error learns nothing: keep what it was owed
176
- continue;
174
+ // A read that throws (permissions, a lock, a race with a delete) or an extraction that throws says nothing
175
+ // about the file: skipped with its knowledge and manifest hash intact, tried again next review.
176
+ if (job.kind === 'read-error' || job.kind === 'failed') {
177
+ if (job.kind === 'read-error') report.readErrors += 1; else report.extractErrors += 1;
178
+ fail(f.path, 'extract', job.kind === 'read-error' ? `read: ${job.reason}` : job.reason);
179
+ measured.set(f.path, owedCalls(detail.extractor, f.path)); // learns nothing: keep what it was owed
180
+ return true;
177
181
  }
178
182
  // Recorded, so a file found binary on read is not re-read by every later review.
179
183
  if (job.kind === 'binary') {
@@ -181,63 +185,61 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
181
185
  finished.add(f.path);
182
186
  await store.markStale(scope, srcRef(rootId, f.path), f.hash);
183
187
  report.staleMarked += 1;
184
- continue;
188
+ return true;
185
189
  }
186
- if (job.kind === 'failed') throw job.error;
187
- if (job.kind === 'none') { finished.add(f.path); continue; }
188
- const { extracted: ex, sections, pack } = job.extraction;
190
+ if (job.kind === 'none') { finished.add(f.path); return true; }
189
191
  report.extracted += 1;
190
-
191
- const spec = pack.judgement;
192
+ // The extract cache is written HERE, in plan order, so the cache, the counts and the order match a sequential run.
193
+ if (!job.extraction.cached) await putExtract(store, f.hash, job.extraction.extracted);
192
194
  let complete = true;
193
- if (spec && args.judgement && (spec.claims || spec.entities)) {
194
- const kinds = new Set(spec.nodeKinds);
195
- const toJudge: Array<{ ref: NodeRef; text: string }> = [];
196
- for (const node of ex.nodes) {
197
- const index = node.badges?.[SECTION_INDEX_BADGE];
198
- const text = typeof index === 'number' ? sections[index]?.text : undefined;
199
- if (!kinds.has(node.kind) || !text) continue;
200
- if (judgedPrior.get(node.ref) === hashText(text)) stored.refresh(node.ref, f.path, f.hash, batch, entities);
201
- else toJudge.push({ ref: node.ref, text });
202
- }
203
- const unjudgedBefore = batch.unjudged;
204
- // Staged per file: a section counts as judged only once its facts are written,
205
- // so an abort mid-file leaves it to be judged again (written whole or not at all).
206
- const judgedHere = new Map<NodeRef, string>();
195
+ if (judge) {
207
196
  progress({ phase: 'judge', done: i, total: changed.length, path: f.path });
208
- try {
209
- const claims = await judgeSections({
210
- port: args.judgement, pack: pack.id, path: f.path, fileHash: f.hash, sections: toJudge,
211
- budget, batch, entities, ...(signal ? { signal } : {}),
212
- onJudged: (ref) => judgedHere.set(ref, hashText(toJudge.find((s) => s.ref === ref)!.text)),
213
- });
214
- // Only a pack that asks for contradictions has claims to compare (the estimate counts the same).
215
- // Deleted first so a re-judged claim moves to the newest position (the awaiting cap drops the oldest).
216
- if (spec.contradictions) {
217
- for (const c of claims) { newClaims.delete(c.ref); newClaims.set(c.ref, { text: c.text, hash: f.hash }); }
218
- }
219
- } catch (err) {
220
- if (!signal?.aborted) throw err;
221
- batch.take();
222
- report.aborted = true;
223
- break;
224
- }
225
- for (const [ref, h] of judgedHere) judgedNow.set(ref, h);
226
- complete = batch.unjudged === unjudgedBefore;
227
- // A content-changed file may revert to the manifest bytes: then all it had to judge — and what it was
228
- // already owed from earlier cuts — is still owed.
229
- if (!complete) {
230
- const contentChanged = detail.prior.get(f.path) !== f.hash;
231
- measured.set(f.path, contentChanged ? toJudge.length + (detail.extractor.owed.get(f.path) ?? 0) : batch.unjudged - unjudgedBefore);
197
+ inWriter = false; // waiting for the model calls is not the writer working
198
+ const outcome = await applyJudge(judgeCtx, f, judge);
199
+ inWriter = true;
200
+ if (outcome === 'aborted') return false;
201
+ if (outcome === 'failed') {
202
+ // Judging failed as a whole: leave the file exactly as it was (facts, manifest hash, owed) so the next review retries it.
203
+ measured.set(f.path, owedCalls(detail.extractor, f.path));
204
+ return true;
232
205
  }
206
+ complete = outcome.complete;
233
207
  }
234
208
  progress({ phase: 'write', done: i, total: changed.length, path: f.path });
209
+ const t0 = now();
235
210
  await write();
236
211
  await store.markStale(scope, srcRef(rootId, f.path), f.hash);
237
212
  report.staleMarked += 1;
213
+ args.onStep?.({ path: f.path, phase: 'write', ms: now() - t0, outcome: 'ok' });
238
214
  if (complete) { filesNow.set(f.path, f.hash); finished.add(f.path); }
215
+ return true;
216
+ };
217
+
218
+ const applyFile = async (slot: Slot): Promise<boolean> => {
219
+ inWriter = true;
220
+ try { return await applyInner(slot); } finally { inWriter = false; }
221
+ };
222
+ const queue: Slot[] = [];
223
+ let applied = 0;
224
+ const drain = async (keep: number) => {
225
+ while (!cut && queue.length > keep) if (await applyFile(queue.shift()!)) applied += 1;
226
+ };
227
+ let completed = false;
228
+ try {
229
+ for await (const { item: f, i, result } of prefetchOrdered(changed, concurrency, prefetch, runSignal)) {
230
+ if (result.status === 'rejected') throw result.reason; // a prefetch job settles to a Prefetch; this is a broken invariant
231
+ const job = result.value;
232
+ queue.push({ f, i, job, judge: job.kind === 'extracted' ? startJudge(dispatch, f, job.extraction) : undefined });
233
+ await drain(judgeWidth - 1);
234
+ }
235
+ await drain(0);
236
+ completed = true;
237
+ } finally {
238
+ if (!completed) stopper.abort(); // a thrown error stops every queued and in-flight call
239
+ signal?.removeEventListener('abort', relay);
240
+ await Promise.allSettled(queue.map((s) => s.judge?.result)); // nothing outlives the run
239
241
  }
240
- if (consumed < changed.length) report.aborted = true;
242
+ if (applied < changed.length) report.aborted = true;
241
243
 
242
244
  if (!report.aborted) {
243
245
  await retire(detail.plan.removed);
@@ -265,7 +267,7 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
265
267
  if (!report.aborted && canCompare) {
266
268
  outcome = await compareNew({
267
269
  args, pending: newClaims, known: stored.facts, budget, batch,
268
- onPairs: (total) => progress({ phase: 'judge', done: 0, total }),
270
+ onPairs: (total) => progress({ phase: 'compare', done: 0, total }),
269
271
  });
270
272
  // Aborted only if the abort landed before the last pair was compared.
271
273
  if (outcome?.aborted) report.aborted = true;
@@ -0,0 +1,155 @@
1
+ /**
2
+ * knowledge/reviewJudge.ts — the judge stage of a review, split in two so files can be judged N at
3
+ * once while ONE writer keeps the result deterministic (PRD 41 A8).
4
+ *
5
+ * • {@link startJudge} runs at DISPATCH, in plan order: it picks the sections to judge, reserves
6
+ * their model calls from the shared budget up front (so the budget is spent in file order whatever
7
+ * the concurrency) and starts the calls under the review's ONE {@link ModelLimiter}. It touches no
8
+ * shared state but the budget counter.
9
+ * • {@link applyJudge} runs at WRITE, in plan order: it merges the answers into the batch, the entity
10
+ * map, the judged-section manifest and the awaiting claims. One writer, so the bytes equal a
11
+ * one-file-at-a-time review's.
12
+ *
13
+ * A file whose EVERY call failed (a provider error: 401, 429, network) or whose judging threw is a
14
+ * judge failure: nothing of it is applied, so the writer leaves its prior knowledge and manifest hash as
15
+ * they were and the next review retries it. A budget cut, or some calls failing, is the older "Continue"
16
+ * behaviour and is left as it was.
17
+ */
18
+
19
+ import { hashText } from '../ingest/hash.js';
20
+ import { SECTION_INDEX_BADGE } from '../ingest/docsExtract.js';
21
+ import { budgetLeft, type JudgeBudget, type JudgedBatch, type SectionToJudge } from './judge.js';
22
+ import { applyAnswers, callSections, type SectionAnswer } from './judgeCalls.js';
23
+ import type { FileExtraction } from './extractFile.js';
24
+ import type { KnowledgePack, NodeRef, ReviewArgs, ReviewReport, StoredFact } from './model.js';
25
+ import type { ModelLimiter } from './modelLimiter.js';
26
+ import type { PlanDetail } from './plan.js';
27
+ import type { StoredIndex } from './reviewStored.js';
28
+ import { Lanes, reasonOf, type ReviewStep } from './reviewRunModel.js';
29
+
30
+ /** Whether the file's pack asks for judgement and a port is there to do it. */
31
+ export const judgesPack = (port: unknown, pack: KnowledgePack): boolean =>
32
+ !!port && !!pack.judgement && !!(pack.judgement.claims || pack.judgement.entities);
33
+
34
+ type CallResult =
35
+ | { status: 'ok'; answers: SectionAnswer[]; unjudged: number; errors: number; ms: number; lane?: number }
36
+ | { status: 'aborted' }
37
+ | { status: 'error'; reason: string; ms: number; lane?: number };
38
+
39
+ /** A file's judging in flight: what to merge once it settles. */
40
+ export interface JudgeJob {
41
+ pack: string;
42
+ contradictions: boolean;
43
+ /** Sections whose judgement is current: their facts are refreshed, not judged. */
44
+ reuse: NodeRef[];
45
+ toJudge: SectionToJudge[];
46
+ /** Never rejects (bar a broken lane invariant). */
47
+ result: Promise<CallResult>;
48
+ }
49
+
50
+ export interface JudgeDispatch {
51
+ port: NonNullable<ReviewArgs['judgement']> | undefined;
52
+ /** The run's signal. */
53
+ signal: AbortSignal;
54
+ budget: JudgeBudget;
55
+ judgedPrior: ReadonlyMap<string, string>;
56
+ lanes: Lanes;
57
+ limiter: ModelLimiter;
58
+ }
59
+
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
+ 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);
66
+ const reuse: NodeRef[] = [];
67
+ const toJudge: SectionToJudge[] = [];
68
+ for (const node of ex.nodes) {
69
+ const index = node.badges?.[SECTION_INDEX_BADGE];
70
+ const text = typeof index === 'number' ? sections[index]?.text : undefined;
71
+ if (!kinds.has(node.kind) || !text) continue;
72
+ if (d.judgedPrior.get(node.ref) === hashText(text)) reuse.push(node.ref);
73
+ else toJudge.push({ ref: node.ref, text });
74
+ }
75
+ // Reserved now, in plan order: this file's calls come out of the shared budget before any later file's.
76
+ const allot = budgetLeft(d.budget) ? Math.min(toJudge.length, Math.max(0, d.budget.modelCalls - d.budget.used)) : 0;
77
+ d.budget.used += allot;
78
+ const slice: JudgeBudget = { modelCalls: allot, deadline: d.budget.deadline, used: 0, now: d.budget.now };
79
+ const result = (async (): Promise<CallResult> => {
80
+ if (toJudge.length === 0) return { status: 'ok', answers: [], unjudged: 0, errors: 0, ms: 0 };
81
+ const lane = d.lanes.take();
82
+ const t0 = Date.now();
83
+ try {
84
+ const r = await callSections({ port, fileHash: f.hash, sections: toJudge, budget: slice, limiter: d.limiter, signal: d.signal });
85
+ // Every call that was made failed: the provider is refusing us (key, quota, network), not the file.
86
+ if (r.answers.length === 0 && r.errors > 0) {
87
+ return { status: 'error', reason: `judge: ${r.firstError ?? 'model call failed'}`, ms: Date.now() - t0, lane };
88
+ }
89
+ return { status: 'ok', answers: r.answers, unjudged: r.unjudged, errors: r.errors, ms: Date.now() - t0, lane };
90
+ } catch (error) {
91
+ if (d.signal.aborted) return { status: 'aborted' };
92
+ return { status: 'error', reason: `judge: ${reasonOf(error)}`, ms: Date.now() - t0, lane };
93
+ } finally {
94
+ d.lanes.free(lane);
95
+ }
96
+ })();
97
+ return { pack: pack.id, contradictions: !!pack.judgement!.contradictions, reuse, toJudge, result };
98
+ }
99
+
100
+ export interface JudgeApply {
101
+ batch: JudgedBatch;
102
+ entities: Map<string, StoredFact>;
103
+ stored: StoredIndex;
104
+ judgedNow: Map<string, string>;
105
+ /** Claims awaiting comparison. */
106
+ newClaims: Map<string, { text: string; hash: string }>;
107
+ /** Model calls each unfinished file is still owed. */
108
+ measured: Map<string, number>;
109
+ detail: PlanDetail;
110
+ report: ReviewReport;
111
+ onStep?(step: ReviewStep): void;
112
+ }
113
+
114
+ /**
115
+ * Merges a settled judge job. `aborted`: the file's judging was cut short, nothing was applied. `failed`:
116
+ * judging failed as a whole, nothing was applied (the caller leaves the file as it was). Otherwise whether
117
+ * the file is complete.
118
+ */
119
+ export async function applyJudge(
120
+ c: JudgeApply, f: { path: string; hash: string }, job: JudgeJob,
121
+ ): Promise<'aborted' | 'failed' | { complete: boolean }> {
122
+ const r = await job.result;
123
+ if (r.status === 'aborted') return 'aborted';
124
+ const step = { path: f.path, phase: 'judge' as const, ms: r.ms, ...(r.lane !== undefined ? { lane: r.lane } : {}) };
125
+ if (r.status === 'error') {
126
+ c.batch.unjudged += job.toJudge.length;
127
+ c.report.failures.push({ path: f.path, phase: 'judge', reason: r.reason });
128
+ c.onStep?.({ ...step, outcome: 'failed', reason: r.reason });
129
+ return 'failed';
130
+ }
131
+ const unjudgedBefore = c.batch.unjudged;
132
+ for (const ref of job.reuse) c.stored.refresh(ref, f.path, f.hash, c.batch, c.entities);
133
+ c.batch.unjudged += r.unjudged;
134
+ // Staged per file: a section counts as judged only once its facts are written, so an abort mid-file
135
+ // leaves it to be judged again (written whole or not at all).
136
+ const judgedHere = new Map<NodeRef, string>();
137
+ const claims = applyAnswers({
138
+ pack: job.pack, path: f.path, fileHash: f.hash, batch: c.batch, entities: c.entities,
139
+ onJudged: (ref) => judgedHere.set(ref, hashText(job.toJudge.find((s) => s.ref === ref)!.text)),
140
+ }, r.answers);
141
+ // Only a pack that asks for contradictions has claims to compare (the estimate counts the same).
142
+ // Deleted first so a re-judged claim moves to the newest position (the awaiting cap drops the oldest).
143
+ if (job.contradictions) for (const x of claims) { c.newClaims.delete(x.ref); c.newClaims.set(x.ref, { text: x.text, hash: f.hash }); }
144
+ for (const [ref, h] of judgedHere) c.judgedNow.set(ref, h);
145
+ const reason = r.errors > 0 ? `${r.unjudged} unjudged (${r.errors} errors)` : r.unjudged > 0 ? `${r.unjudged} unjudged` : undefined;
146
+ c.onStep?.({ ...step, outcome: job.toJudge.length === 0 ? 'cached' : 'ok', ...(reason ? { reason } : {}) });
147
+ const complete = c.batch.unjudged === unjudgedBefore;
148
+ // A content-changed file may revert to the manifest bytes: then all it had to judge — and what it was
149
+ // already owed from earlier cuts — is still owed.
150
+ if (!complete) {
151
+ const contentChanged = c.detail.prior.get(f.path) !== f.hash;
152
+ c.measured.set(f.path, contentChanged ? job.toJudge.length + (c.detail.extractor.owed.get(f.path) ?? 0) : c.batch.unjudged - unjudgedBefore);
153
+ }
154
+ return { complete };
155
+ }
@@ -7,6 +7,8 @@ import type { IngestManifest, SourceDocument } from '../ingest/types.js';
7
7
  import type { SimilarPair } from '../retrieval/knowledge-index/types.js';
8
8
  import type { JudgementPort, KnowledgePack, KnowledgeStore } from './model.js';
9
9
  import type { PlanDetail } from './plan.js';
10
+ import type { ExtractPool } from './extractJob.js';
11
+ import type { ReviewFailure, ReviewPhase, ReviewStep } from './reviewRunModel.js';
10
12
 
11
13
  /** Where files come from: one adapter per host. */
12
14
  export interface DirectorySource {
@@ -30,7 +32,7 @@ export interface ReviewPlan {
30
32
  }
31
33
 
32
34
  export interface ReviewProgress {
33
- phase: 'plan' | 'extract' | 'resolve' | 'judge' | 'write' | 'index' | 'done';
35
+ phase: ReviewPhase;
34
36
  done: number;
35
37
  total: number;
36
38
  path?: string;
@@ -53,6 +55,10 @@ export interface ReviewReport {
53
55
  * the next fresh plan's `removed`.
54
56
  */
55
57
  readErrors: number;
58
+ /** Files whose extraction threw: handled like a read error (knowledge and manifest hash kept, retried next review). */
59
+ extractErrors: number;
60
+ /** Every file this run could not finish (read, extract, judge), with why. */
61
+ failures: ReviewFailure[];
56
62
  aborted: boolean;
57
63
  durationMs: number;
58
64
  }
@@ -77,7 +83,29 @@ export interface ReviewArgs {
77
83
  /** *Re-review all*: every file is reviewed whatever its hash (see `PlanOptions.force`). Ignored with `plan`. */
78
84
  force?: boolean;
79
85
  signal?: AbortSignal;
80
- /** Files read + extracted ahead of judging (1..32, default 8). Judge/write stay in file order. */
86
+ /**
87
+ * Files read + extracted ahead of judging (1..32, default 8). With an `extractPool` this is the pool's width.
88
+ * Writes always stay in file order.
89
+ */
81
90
  concurrency?: number;
91
+ /**
92
+ * Files judged at once (1..16, default 4, never wider than the read-ahead). One ordered writer applies the
93
+ * results in plan order, so the stored bytes equal those of `concurrency: 1, judgeConcurrency: 1`.
94
+ */
95
+ judgeConcurrency?: number;
96
+ /**
97
+ * The most model calls in flight across ALL files of the review (default 6): `judgeConcurrency` parallelizes
98
+ * files without multiplying the provider's load. A rate-limit answer halves it (minimum 1); it grows back by 1
99
+ * per 20 successful calls.
100
+ */
101
+ maxModelCalls?: number;
102
+ /**
103
+ * Extracts a changed file whose extract is not cached — e.g. a `worker_threads` pool. Default: in-thread.
104
+ * With a pool the main thread never parses; the pool returns a file's sections when it will be judged.
105
+ * A result without the file's exact `sourceRef` fails that file's extraction (prior knowledge kept).
106
+ */
107
+ extractPool?: ExtractPool;
108
+ /** One event per file per phase, as it happens (PRD 41 A8). */
109
+ onStep?(step: ReviewStep): void;
82
110
  onProgress?(p: ReviewProgress): void;
83
111
  }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * knowledge/reviewPrefetch.ts — the read + extract stage of a review (PRD 38 §4.3, PRD 41 A8).
3
+ *
4
+ * `createPrefetch` returns the per-file job `prefetchOrdered` runs ahead of the consumer: read,
5
+ * binary check, extract (the content-hash cache is READ here; through `args.extractPool` on a miss when
6
+ * the host supplies one). A job never throws — it settles to a {@link Prefetch}, and a failure carries
7
+ * its reason so the review can keep the file's prior knowledge and retry it next time. It never WRITES
8
+ * the extract cache: the review's ordered writer does, so the cache matches a sequential run. Each job
9
+ * holds one lane (0..width-1) and emits its `extract` step the moment it settles.
10
+ */
11
+
12
+ import type { SourceDocument } from '../ingest/types.js';
13
+ import type { KnowledgePack, KnowledgeStore, NodeRef, ReviewArgs } from './model.js';
14
+ import { extractFileDetailed, type FileExtraction } from './extractFile.js';
15
+ import { judgesPack } from './reviewJudge.js';
16
+ import { Lanes, reasonOf, type ReviewStep } from './reviewRunModel.js';
17
+ import { isBinaryText, type ComposedPacks } from './sources.js';
18
+
19
+ /** What the prefetch stage learned about one file. `failed` and `read-error` carry why. */
20
+ export type Prefetch = (
21
+ | { kind: 'read-error'; reason: string }
22
+ | { kind: 'binary' }
23
+ | { kind: 'none' }
24
+ | { kind: 'extracted'; doc: SourceDocument; extraction: FileExtraction }
25
+ | { kind: 'failed'; reason: string }
26
+ ) & { ms: number; lane: number };
27
+
28
+ export interface PrefetchContext {
29
+ args: ReviewArgs;
30
+ /** The run's signal (the caller's, plus the run's own stop on a thrown error). */
31
+ signal: AbortSignal;
32
+ rootId: string;
33
+ packs: readonly KnowledgePack[];
34
+ store: KnowledgeStore;
35
+ composed: ComposedPacks;
36
+ knownKeys: ReadonlyMap<string, NodeRef>;
37
+ /** Lanes = the read-ahead width. */
38
+ width: number;
39
+ }
40
+
41
+ /** A {@link Prefetch} before its timing is stamped. */
42
+ type Outcome = Prefetch extends infer P ? (P extends unknown ? Omit<P, 'ms' | 'lane'> : never) : never;
43
+
44
+ /** The extract step event of a settled job. */
45
+ export function extractStepOf(path: string, job: Prefetch): ReviewStep {
46
+ const base = { path, phase: 'extract' as const, ms: job.ms, lane: job.lane };
47
+ switch (job.kind) {
48
+ case 'read-error': return { ...base, outcome: 'failed', reason: `read: ${job.reason}` };
49
+ case 'failed': return { ...base, outcome: 'failed', reason: job.reason };
50
+ case 'binary': return { ...base, outcome: 'skipped', reason: 'binary' };
51
+ case 'none': return { ...base, outcome: 'skipped', reason: 'no-pack' };
52
+ case 'extracted': return { ...base, outcome: job.extraction.cached ? 'cached' : 'ok' };
53
+ }
54
+ }
55
+
56
+ export function createPrefetch(c: PrefetchContext): (f: { path: string; hash: string }) => Promise<Prefetch> {
57
+ const lanes = new Lanes(c.width);
58
+ const wantsSections = (pack: KnowledgePack) => judgesPack(c.args.judgement, pack);
59
+
60
+ const run = async (f: { path: string; hash: string }): Promise<Outcome> => {
61
+ let doc: SourceDocument;
62
+ try { doc = await c.args.source.read(f.path); } catch (error) { return { kind: 'read-error', reason: reasonOf(error) }; }
63
+ try {
64
+ if (doc.content.kind === 'text' && isBinaryText(doc.content.text)) return { kind: 'binary' };
65
+ const extraction = await extractFileDetailed({
66
+ rootId: c.rootId, path: f.path, hash: f.hash, doc, packs: c.packs, store: c.store, composed: c.composed,
67
+ knownKeys: c.knownKeys, writeCache: false,
68
+ ...(c.args.extractPool ? { pool: c.args.extractPool, signal: c.signal, wantsSections } : {}),
69
+ });
70
+ return extraction ? { kind: 'extracted', doc, extraction } : { kind: 'none' };
71
+ } catch (error) { return { kind: 'failed', reason: reasonOf(error) }; }
72
+ };
73
+
74
+ return async (f) => {
75
+ const lane = lanes.take();
76
+ const t0 = Date.now();
77
+ try {
78
+ const out = await run(f);
79
+ const job = { ...out, ms: Date.now() - t0, lane } as Prefetch;
80
+ c.args.onStep?.(extractStepOf(f.path, job));
81
+ return job;
82
+ } finally {
83
+ lanes.free(lane);
84
+ }
85
+ };
86
+ }