@seanhogg/builderforce-memory 2026.10.63 → 2026.10.67

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 (131) hide show
  1. package/dist/knowledge/index.d.ts +1 -1
  2. package/dist/knowledge/index.d.ts.map +1 -1
  3. package/dist/knowledge/index.js +1 -1
  4. package/dist/knowledge/index.js.map +1 -1
  5. package/dist/knowledge/pack/frame.d.ts +12 -3
  6. package/dist/knowledge/pack/frame.d.ts.map +1 -1
  7. package/dist/knowledge/pack/frame.js +18 -4
  8. package/dist/knowledge/pack/frame.js.map +1 -1
  9. package/dist/knowledge/pack/manifest.d.ts +11 -3
  10. package/dist/knowledge/pack/manifest.d.ts.map +1 -1
  11. package/dist/knowledge/pack/manifest.js +26 -12
  12. package/dist/knowledge/pack/manifest.js.map +1 -1
  13. package/dist/knowledge/pack/sections/extr.d.ts.map +1 -1
  14. package/dist/knowledge/pack/sections/extr.js +16 -4
  15. package/dist/knowledge/pack/sections/extr.js.map +1 -1
  16. package/dist/knowledge/pack/sections/extrLists.d.ts +0 -1
  17. package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -1
  18. package/dist/knowledge/pack/sections/extrLists.js +5 -6
  19. package/dist/knowledge/pack/sections/extrLists.js.map +1 -1
  20. package/dist/knowledge/pack/sections/facts.d.ts.map +1 -1
  21. package/dist/knowledge/pack/sections/facts.js +3 -2
  22. package/dist/knowledge/pack/sections/facts.js.map +1 -1
  23. package/dist/knowledge/pack/sections/rows.d.ts.map +1 -1
  24. package/dist/knowledge/pack/sections/rows.js +11 -2
  25. package/dist/knowledge/pack/sections/rows.js.map +1 -1
  26. package/dist/knowledge/pack/strings.d.ts.map +1 -1
  27. package/dist/knowledge/pack/strings.js +6 -1
  28. package/dist/knowledge/pack/strings.js.map +1 -1
  29. package/dist/knowledge/pack/varint.d.ts +14 -0
  30. package/dist/knowledge/pack/varint.d.ts.map +1 -1
  31. package/dist/knowledge/pack/varint.js +32 -1
  32. package/dist/knowledge/pack/varint.js.map +1 -1
  33. package/dist/knowledge/refs.d.ts +14 -2
  34. package/dist/knowledge/refs.d.ts.map +1 -1
  35. package/dist/knowledge/refs.js +30 -8
  36. package/dist/knowledge/refs.js.map +1 -1
  37. package/dist/knowledge/review.d.ts +6 -6
  38. package/dist/knowledge/review.d.ts.map +1 -1
  39. package/dist/knowledge/review.js +56 -329
  40. package/dist/knowledge/review.js.map +1 -1
  41. package/dist/knowledge/reviewAnalyse.d.ts +17 -0
  42. package/dist/knowledge/reviewAnalyse.d.ts.map +1 -0
  43. package/dist/knowledge/reviewAnalyse.js +61 -0
  44. package/dist/knowledge/reviewAnalyse.js.map +1 -0
  45. package/dist/knowledge/reviewApply.d.ts +33 -0
  46. package/dist/knowledge/reviewApply.d.ts.map +1 -0
  47. package/dist/knowledge/reviewApply.js +121 -0
  48. package/dist/knowledge/reviewApply.js.map +1 -0
  49. package/dist/knowledge/reviewContext.d.ts +77 -0
  50. package/dist/knowledge/reviewContext.d.ts.map +1 -0
  51. package/dist/knowledge/reviewContext.js +111 -0
  52. package/dist/knowledge/reviewContext.js.map +1 -0
  53. package/dist/knowledge/reviewFinish.d.ts +9 -0
  54. package/dist/knowledge/reviewFinish.d.ts.map +1 -0
  55. package/dist/knowledge/reviewFinish.js +62 -0
  56. package/dist/knowledge/reviewFinish.js.map +1 -0
  57. package/dist/knowledge/reviewRunModel.d.ts +3 -0
  58. package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
  59. package/dist/knowledge/reviewRunModel.js.map +1 -1
  60. package/dist/knowledge/stores/extractLogWriter.d.ts +16 -3
  61. package/dist/knowledge/stores/extractLogWriter.d.ts.map +1 -1
  62. package/dist/knowledge/stores/extractLogWriter.js +38 -13
  63. package/dist/knowledge/stores/extractLogWriter.js.map +1 -1
  64. package/dist/knowledge/stores/extractRefs.d.ts +68 -0
  65. package/dist/knowledge/stores/extractRefs.d.ts.map +1 -0
  66. package/dist/knowledge/stores/extractRefs.js +168 -0
  67. package/dist/knowledge/stores/extractRefs.js.map +1 -0
  68. package/dist/knowledge/stores/localSnapshotStore.d.ts +5 -0
  69. package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
  70. package/dist/knowledge/stores/localSnapshotStore.js +25 -5
  71. package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
  72. package/dist/knowledge/stores/rowDelta.d.ts +6 -0
  73. package/dist/knowledge/stores/rowDelta.d.ts.map +1 -1
  74. package/dist/knowledge/stores/rowDelta.js.map +1 -1
  75. package/dist/knowledge/stores/rowMemory.d.ts +30 -0
  76. package/dist/knowledge/stores/rowMemory.d.ts.map +1 -1
  77. package/dist/knowledge/stores/rowMemory.js +46 -1
  78. package/dist/knowledge/stores/rowMemory.js.map +1 -1
  79. package/dist/knowledge/stores/rowSync.d.ts.map +1 -1
  80. package/dist/knowledge/stores/rowSync.js +2 -1
  81. package/dist/knowledge/stores/rowSync.js.map +1 -1
  82. package/dist/knowledge/stores/snapshotFormat.d.ts +13 -2
  83. package/dist/knowledge/stores/snapshotFormat.d.ts.map +1 -1
  84. package/dist/knowledge/stores/snapshotFormat.js +22 -9
  85. package/dist/knowledge/stores/snapshotFormat.js.map +1 -1
  86. package/dist/working/fold.d.ts +14 -0
  87. package/dist/working/fold.d.ts.map +1 -1
  88. package/dist/working/fold.js +14 -4
  89. package/dist/working/fold.js.map +1 -1
  90. package/dist/working/index.d.ts +3 -1
  91. package/dist/working/index.d.ts.map +1 -1
  92. package/dist/working/index.js +2 -1
  93. package/dist/working/index.js.map +1 -1
  94. package/dist/working/textSummary.d.ts +46 -0
  95. package/dist/working/textSummary.d.ts.map +1 -0
  96. package/dist/working/textSummary.js +142 -0
  97. package/dist/working/textSummary.js.map +1 -0
  98. package/package.json +1 -1
  99. package/src/contract/exports.snapshot.json +8 -1
  100. package/src/contract/regression.extractEviction.test.ts +162 -0
  101. package/src/contract/regression.fixCommits.test.ts +112 -0
  102. package/src/contract/regression.packWire.test.ts +174 -0
  103. package/src/contract/regression.refs.test.ts +49 -0
  104. package/src/contract/types.contract.test.ts +2 -1
  105. package/src/knowledge/index.ts +1 -1
  106. package/src/knowledge/pack/frame.ts +21 -5
  107. package/src/knowledge/pack/manifest.ts +26 -11
  108. package/src/knowledge/pack/sections/extr.ts +14 -4
  109. package/src/knowledge/pack/sections/extrLists.ts +4 -6
  110. package/src/knowledge/pack/sections/facts.ts +3 -2
  111. package/src/knowledge/pack/sections/rows.ts +11 -2
  112. package/src/knowledge/pack/strings.ts +5 -1
  113. package/src/knowledge/pack/varint.ts +33 -1
  114. package/src/knowledge/refs.ts +26 -8
  115. package/src/knowledge/review.ts +58 -311
  116. package/src/knowledge/reviewAnalyse.ts +59 -0
  117. package/src/knowledge/reviewApply.ts +128 -0
  118. package/src/knowledge/reviewContext.ts +158 -0
  119. package/src/knowledge/reviewFinish.ts +63 -0
  120. package/src/knowledge/reviewRunModel.ts +3 -0
  121. package/src/knowledge/stores/extractLogWriter.ts +36 -12
  122. package/src/knowledge/stores/extractRefs.ts +161 -0
  123. package/src/knowledge/stores/localSnapshotStore.ts +22 -5
  124. package/src/knowledge/stores/rowDelta.ts +6 -0
  125. package/src/knowledge/stores/rowMemory.ts +50 -1
  126. package/src/knowledge/stores/rowSync.ts +2 -1
  127. package/src/knowledge/stores/snapshotFormat.ts +27 -10
  128. package/src/working/fold.ts +15 -4
  129. package/src/working/index.ts +13 -1
  130. package/src/working/textSummary.test.ts +113 -0
  131. package/src/working/textSummary.ts +156 -0
@@ -25,30 +25,25 @@
25
25
  * sections not judged yet. A file owed under an extractor upgrade that this run left
26
26
  * unfinished (a failed read, an abort, the budget) stays owed — see owedFiles.ts — so the
27
27
  * next review or *Continue* picks up exactly those files, whatever their content does.
28
+ *
29
+ * The stages are one module each: reviewContext.ts (planning, the shared state, write and retire), reviewPrefetch.ts (read +
30
+ * extract), reviewJudge.ts (judging), reviewApply.ts (the ordered writer), reviewAnalyse.ts (analyzers), reviewFinish.ts
31
+ * (compare, durability, manifests). This file wires the read-ahead loop and the run's stop between them.
28
32
  */
29
33
 
30
- import { sha256Hex } from '../retrieval/knowledge-index/sha256.js';
31
- import type { AnalyzerProgress, ReviewArgs, ReviewReport, ScopeRecord, StoredFact, StoredRelation } from './model.js';
32
- import { owedAfterRun, owedCalls, saveExtractorState } from './owedFiles.js';
33
- import { planDetail, refreshPlan } from './plan.js';
34
- import { composePacks, filesManifestKey, judgedManifestKey, manifestMap, saveManifestMap } from './sources.js';
35
- import { knownKeysOfEntities, putExtract, putNoExtract } from './extractFile.js';
36
- import { backfillCandidates, backfillNoExtract } from './backfillNoExtract.js';
37
- import { recordFailure } from './reviewFailure.js';
34
+ import type { ReviewArgs, ReviewReport } from './model.js';
38
35
  import { prefetchOrdered } from './orderedPool.js';
39
- import {
40
- DEFAULT_REVIEW_CONCURRENCY, DEFAULT_REVIEW_JUDGE_CONCURRENCY, DEFAULT_REVIEW_MODEL_CALLS, JUDGE_CONCURRENCY, JudgedBatch,
41
- type CompareOutcome, type JudgeBudget,
42
- } from './judge.js';
36
+ import { DEFAULT_REVIEW_CONCURRENCY, DEFAULT_REVIEW_JUDGE_CONCURRENCY, JUDGE_CONCURRENCY } from './judge.js';
43
37
  import { createModelLimiter } from './modelLimiter.js';
44
- import { JudgeBreaker } from './judgeCalls.js';
45
- import { applyJudge, judgesPack, splitSections, startJudge, type JudgeJob } from './reviewJudge.js';
46
- import { createPrefetch, type Prefetch, type PrefetchFile } from './reviewPrefetch.js';
47
- import { putAsset } from './assetFile.js';
38
+ import { startJudge } from './reviewJudge.js';
39
+ import { createPrefetch } from './reviewPrefetch.js';
48
40
  import { Lanes } from './reviewRunModel.js';
49
- import { compareNew, pendingClaims, saveAwaiting } from './reviewCompare.js';
50
- import { factsWithoutAnchor, StoredIndex } from './reviewStored.js';
51
- import { canonicalJson, compareStr, srcRef } from './refs.js';
41
+ import { openReview, retire, type ReviewContext } from './reviewContext.js';
42
+ import { applyFile, type ApplyContext, type Slot, type WriterGate } from './reviewApply.js';
43
+ import { runAnalyzers } from './reviewAnalyse.js';
44
+ import { finishReview } from './reviewFinish.js';
45
+
46
+ export { assertStoredBatch } from './reviewContext.js';
52
47
 
53
48
  /** Read-ahead window for a MECHANICAL review with a pool that reads files itself: wide enough to buffer finished results behind one slow head file. Real extraction width is bounded separately (the extract-slot limiter in reviewPrefetch). */
54
49
  const POOL_READ_AHEAD_DEFAULT = 256;
@@ -66,20 +61,6 @@ function readAheadOf(args: ReviewArgs, concurrency: number): number {
66
61
  return Math.min(64, Math.max(concurrency, Math.floor(args.readAhead ?? Math.max(32, concurrency * 4)) || concurrency));
67
62
  }
68
63
 
69
- /** One changed file between dispatch and the ordered writer: what its prefetch found and its judging in flight. */
70
- interface Slot {
71
- f: PrefetchFile;
72
- i: number;
73
- job: Prefetch;
74
- judge: JudgeJob | undefined;
75
- }
76
-
77
- /** Throws if a batch carries `extracted` items — perception is never memory. */
78
- export function assertStoredBatch(batch: { facts: readonly StoredFact[]; relations: readonly StoredRelation[] }): void {
79
- const bad = [...batch.facts, ...batch.relations].find((x) => (x.origin as string) === 'extracted');
80
- if (bad) throw new Error('knowledge: extracted output is never written to a KnowledgeStore');
81
- }
82
-
83
64
  /**
84
65
  * A store that can hold persistence (`batched`) gets the whole review as one batch, so a snapshot
85
66
  * store writes a bounded number of times instead of once per file; any other store is unaffected.
@@ -89,99 +70,34 @@ export async function reviewDirectory(args: ReviewArgs): Promise<ReviewReport> {
89
70
  }
90
71
 
91
72
  async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<ReviewReport> {
92
- const now = () => Date.now();
93
- const started = now();
94
- const { source, store, packs, manifest, signal } = args;
95
- const rootId = source.rootId;
96
- const scope = { rootId };
97
- const progress = (p: Parameters<NonNullable<ReviewArgs['onProgress']>>[0]) => args.onProgress?.(p);
98
- const report: ReviewReport = {
99
- rootId, digest: '', extracted: 0, judged: 0, unjudged: 0, invalidJudgements: 0,
100
- factsWritten: 0, relationsWritten: 0, staleMarked: 0, readErrors: 0, extractErrors: 0, failures: [], awaitingJudge: [], aborted: false, durationMs: 0,
101
- };
102
-
103
- const detail = args.plan
104
- ? await refreshPlan(args.plan, manifest)
105
- : await planDetail(source, manifest, packs, { ...(args.force ? { force: true } : {}), compare: !!args.similar && !!args.judgement });
106
- progress({ phase: 'plan', done: detail.files.length, total: detail.files.length });
107
- const composed = composePacks(packs);
108
- const packIds = packs.map((p) => p.id).sort(compareStr);
109
- const scopeRecord: ScopeRecord = { rootId, title: source.title, packs: packIds };
110
- const [storedFacts, storedRelations] = await Promise.all([store.facts(scope), store.relations(scope)]);
111
- const stored = new StoredIndex(storedFacts, storedRelations);
112
- const entities = new Map(storedFacts.filter((f) => f.key.startsWith('ent:')).map((f) => [f.key, f] as const));
113
- const knownKeys = knownKeysOfEntities(entities.keys());
114
- const budget: JudgeBudget = {
115
- modelCalls: args.budget?.modelCalls ?? DEFAULT_REVIEW_MODEL_CALLS,
116
- deadline: started + (Number.isFinite(args.budget?.ms) ? args.budget.ms : Number.POSITIVE_INFINITY),
117
- used: 0, now,
118
- };
119
- const batch = new JudgedBatch();
120
- const breaker = new JudgeBreaker();
121
- const owedJudge: string[] = [];
122
- const judgedPrior = await manifestMap(manifest, judgedManifestKey(rootId));
123
- const judgedNow = new Map(judgedPrior);
124
- const filesNow = new Map(detail.prior);
125
- // Files with no stored body: assets the manifest names (queued so their node is written, no read) and the ones a replica asked to re-check (queued; this review stores their body or asset node).
126
- const asked = (await store.recheckHashes?.()) ?? [];
127
- // ONE bulk fetch of the extract cache for the whole run instead of a round trip per file: the files this run extracts and the ones the backfill looks up.
128
- const preChanged = detail.files.filter((f) => f.changed && (!args.only || args.only.includes(f.path)));
129
- const preload = [...new Set([...preChanged.map((f) => f.hash), ...backfillCandidates(detail, asked)])];
130
- if (preload.length > 0) await store.preloadExtracted?.(preload);
131
- await backfillNoExtract({ store, detail, asked, only: args.only, signal });
132
- // A re-check request is answered only when the work it asked for is done: the body stored, the binary recorded, or the failure recorded.
133
- const askedSet = new Set(asked);
134
- const settledRecheck = async (hash: string): Promise<void> => { if (askedSet.has(hash)) await store.clearRecheck?.([hash]); };
135
- // Claims awaiting comparison: those a previous run could not compare, then this run's.
136
- const newClaims = await pendingClaims(manifest, rootId, stored.facts);
137
-
138
- const write = async (withScope: ScopeRecord = scopeRecord) => {
139
- const out = batch.take();
140
- assertStoredBatch(out);
141
- if (out.facts.length === 0 && out.relations.length === 0 && withScope === scopeRecord) return;
142
- await store.write({ scope: withScope, ...out });
143
- report.factsWritten += out.facts.length;
144
- report.relationsWritten += out.relations.length;
145
- };
73
+ const c = await openReview(args);
74
+ const { report } = c;
75
+ const runSignal = await applyChangedFiles(c);
76
+ // A Stop ends the run: the file in hand was finished and applied, but nothing after it (retire, analyzers, the digest stamp) runs.
77
+ report.aborted ||= runSignal.aborted;
146
78
 
147
- // A source that is gone: its knowledge goes stale at no hash, its judged sections are forgotten, and
148
- // facts other sources still back drop its anchor. `rewritten` is the run's one record of such facts,
149
- // so a later retire() never restores an anchor an earlier one dropped.
150
- const rewritten = new Map<string, StoredFact>();
151
- const retire = async (paths: readonly string[]) => {
152
- const live = new Map([...stored.facts, ...entities, ...rewritten]);
153
- for (const path of paths) {
154
- await store.markStale(scope, srcRef(rootId, path), '');
155
- report.staleMarked += 1;
156
- filesNow.delete(path);
157
- const sectionPrefix = `${srcRef(rootId, path)}#`;
158
- for (const section of [...judgedNow.keys()]) if (section.startsWith(sectionPrefix)) judgedNow.delete(section);
159
- for (const fact of factsWithoutAnchor(live.values(), path)) {
160
- batch.fact(fact);
161
- live.set(fact.key, fact);
162
- rewritten.set(fact.key, fact);
163
- if (entities.has(fact.key)) entities.set(fact.key, fact);
164
- }
165
- }
166
- await write();
167
- };
79
+ // Pass 2 (`only`) is judging alone: the map pass already retired the removed files and ran the analyzers.
80
+ if (!report.aborted && !args.only) {
81
+ // The last file is written: leave "write" now, the analyzers below can take minutes.
82
+ // Opened as 0/1 (not 0/0, which would close the row at once) so the row stays active until the analyzers close it.
83
+ c.progress({ phase: 'analyse', done: 0, total: 1 });
84
+ await retire(c, c.detail.plan.removed);
85
+ await runAnalyzers(c);
86
+ // A Stop during the analyzers ends the run like one during the write loop (`runSignal` no longer follows `signal` here).
87
+ report.aborted ||= runSignal.aborted || !!args.signal?.aborted;
88
+ if (!report.aborted) c.progress({ phase: 'resolve', done: 0, total: c.newClaims.size });
89
+ }
90
+ return finishReview(c, flush);
91
+ }
168
92
 
169
- const changed = detail.files.filter((f) => f.changed);
170
- // `only` (pass 2) narrows what this run works on; the other changed files are untouched and stay owed (owedAfterRun sees them all).
171
- // Pass 2 works in the order it was given (priority), so a model-call ceiling is spent on the most important files first.
172
- const byPath = new Map(changed.map((f) => [f.path, f] as const));
173
- const work = args.only ? args.only.flatMap((p) => byPath.get(p) ?? []) : changed;
174
- // Changed files this run finished (or had nothing to do for); an owed file not in it stays owed,
175
- // at the model calls it still costs where this run could measure that (see owedFiles.ts).
176
- const finished = new Set<string>();
177
- /** Files that failed for a reason that says nothing final about them, at the manifest's own bytes: owed, so the next review retries them. */
178
- const unreadable = new Set<string>();
179
- /** Consecutive transient failures by path at one hash (saved beside the owed record). */
180
- const failures = new Map(detail.extractor.failures ?? []);
181
- const measured = new Map<string, number>();
182
- // Read + binary check + extract run ahead with bounded concurrency (extraction only reads `knownKeys`,
183
- // fixed above, and the content-hash extract cache); with `args.extractPool` the width is the pool's.
184
- // Judging runs `judgeWidth` files at once; ONE writer (`applyFile`) consumes them strictly in plan order.
93
+ /**
94
+ * Read + binary check + extract run ahead with bounded concurrency (extraction only reads `knownKeys`, fixed at open, and the
95
+ * content-hash extract cache); with `args.extractPool` the width is the pool's. Judging runs `judgeWidth` files at once; ONE
96
+ * writer ({@link applyFile}) consumes them strictly in plan order. Returns the run's own stop signal.
97
+ */
98
+ async function applyChangedFiles(c: ReviewContext): Promise<AbortSignal> {
99
+ const { args, report } = c;
100
+ const { signal } = args;
185
101
  const concurrency = Math.min(32, Math.max(1, Math.floor(args.concurrency ?? DEFAULT_REVIEW_CONCURRENCY) || 1));
186
102
  // Read-ahead is wider than the pool (PRD 41 A10 rule 8) so workers never wait for the ordered writer.
187
103
  const readAhead = readAheadOf(args, concurrency);
@@ -191,118 +107,35 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
191
107
  const stopper = new AbortController();
192
108
  // An abort that lands while the writer is mid-file ends the run at that file's boundary, as a sequential run
193
109
  // does (`cut`); one that lands anywhere else (a read, a model call) keeps every file whose work completed.
194
- let inWriter = false;
110
+ const gate: WriterGate = { inWriter: false };
195
111
  let cut = false;
196
- const relay = () => { if (inWriter) cut = true; stopper.abort(signal?.reason); };
112
+ const relay = () => { if (gate.inWriter) cut = true; stopper.abort(signal?.reason); };
197
113
  if (signal?.aborted) relay(); else signal?.addEventListener('abort', relay, { once: true });
198
114
  const runSignal = stopper.signal;
199
- const prefetch = createPrefetch({ args, signal: runSignal, rootId, packs, store, composed, knownKeys, width: readAhead, extractWidth: concurrency });
115
+ const prefetch = createPrefetch({
116
+ args, signal: runSignal, rootId: c.rootId, packs: args.packs, store: args.store, composed: c.composed, knownKeys: c.knownKeys,
117
+ width: readAhead, extractWidth: concurrency,
118
+ });
200
119
  const dispatch = {
201
120
  // A mechanical run (pass 1) makes no model call: judged files stay owed.
202
- port: args.mechanical ? undefined : args.judgement, signal: runSignal, breaker, budget, judgedPrior, lanes: new Lanes(judgeWidth),
203
- limiter: createModelLimiter(args.maxModelCalls ?? JUDGE_CONCURRENCY),
121
+ port: args.mechanical ? undefined : args.judgement, signal: runSignal, breaker: c.breaker, budget: c.budget, judgedPrior: c.judgedPrior,
122
+ lanes: new Lanes(judgeWidth), limiter: createModelLimiter(args.maxModelCalls ?? JUDGE_CONCURRENCY),
204
123
  };
205
- const judgeCtx = { batch, entities, stored, judgedNow, newClaims, measured, detail, report, ...(args.onStep ? { onStep: args.onStep } : {}) };
206
- const fail = (path: string, phase: 'extract' | 'judge', reason: string) => report.failures.push({ path, phase, reason });
207
-
208
- /**
209
- * Applies one file, in plan order. False when its work was cut short by an abort (extracted, judging
210
- * unfinished): nothing of it is applied and it stays as it was, owed. A file whose work is complete is
211
- * applied even after an abort — the work is done, so it is kept.
212
- */
213
- const applyInner = async ({ f, i, job, judge }: Slot): Promise<boolean> => {
214
- progress({ phase: 'extract', done: i, total: work.length, path: f.path });
215
- // A read that throws (permissions, a lock, a race with a delete) or an extraction that throws says nothing
216
- // about the file: skipped with its knowledge and manifest hash intact, tried again next review.
217
- if (job.kind === 'read-error' || job.kind === 'failed') {
218
- if (job.kind === 'read-error') report.readErrors += 1; else report.extractErrors += 1;
219
- fail(f.path, 'extract', job.kind === 'read-error' ? `read: ${job.reason}` : job.reason);
220
- measured.set(f.path, owedCalls(detail.extractor, f.path)); // learns nothing: keep what it was owed
221
- // The ONE failure path (reviewFailure.ts): a transient failure keeps the re-check request and makes the file owed; only a proven-final
222
- // one (or the third in a row at the same bytes) is answered with a terminal `[]`.
223
- if (await recordFailure({ store, detail, stopped: () => runSignal.aborted, unreadable, failures, settledRecheck }, f, job)) finished.add(f.path); // final: settled, not re-read while its bytes stand
224
- return true;
225
- }
226
- failures.delete(f.path); // it read and extracted (or was decided): the run of failures at this hash ends
227
- // An asset (planned binary, or a text-extension file found binary on read): never extracted, but it IS a file of the root, so
228
- // its file node is stored (assetFile.ts) — a replica tells it from "not extracted yet", and references to its path resolve.
229
- // Recorded, so a file found binary on read is not re-read by every later review.
230
- if (job.kind === 'binary' || job.kind === 'asset') {
231
- filesNow.set(f.path, f.hash);
232
- finished.add(f.path);
233
- await putAsset(store, rootId, f);
234
- await settledRecheck(f.hash);
235
- await store.markStale(scope, srcRef(rootId, f.path), f.hash);
236
- report.staleMarked += 1;
237
- return true;
238
- }
239
- if (job.kind === 'none') {
240
- // No pack accepts the file: nothing will ever be extracted for it, so say so (and answer any re-check of it).
241
- finished.add(f.path);
242
- await putNoExtract(store, f.hash);
243
- await settledRecheck(f.hash);
244
- return true;
245
- }
246
- report.extracted += 1;
247
- // The extract cache is written HERE, in plan order, so the cache, the counts and the order match a sequential run.
248
- if (!job.extraction.cached) await putExtract(store, f.hash, job.extraction.extracted);
249
- await settledRecheck(f.hash);
250
- let complete = true;
251
- let deferred = false;
252
- if (args.mechanical && judgesPack(args.judgement, job.extraction.pack)) {
253
- // 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
254
- // 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
255
- // owed and pass 2 finds nothing to judge (a cache hit, no call).
256
- const { reuse, toJudge } = splitSections(judgedPrior, job.extraction);
257
- if (job.extraction.sections.length > 0 && toJudge.length === 0) {
258
- for (const ref of reuse) stored.refresh(ref, f.path, f.hash, batch, entities);
259
- } else {
260
- complete = false;
261
- deferred = true;
262
- owedJudge.push(f.path);
263
- measured.set(f.path, Math.max(1, toJudge.length));
264
- }
265
- }
266
- if (judge) {
267
- progress({ phase: 'judge', done: i, total: work.length, path: f.path });
268
- inWriter = false; // waiting for the model calls is not the writer working
269
- const outcome = await applyJudge(judgeCtx, f, judge);
270
- inWriter = true;
271
- if (outcome === 'aborted') return false;
272
- if (outcome === 'failed') {
273
- owedJudge.push(f.path);
274
- // Judging failed as a whole: leave the file exactly as it was (facts, manifest hash, owed) so the next review retries it.
275
- measured.set(f.path, owedCalls(detail.extractor, f.path));
276
- return true;
277
- }
278
- complete = outcome.complete;
279
- if (!complete) owedJudge.push(f.path);
280
- }
281
- progress({ phase: 'write', done: i, total: work.length, path: f.path });
282
- const t0 = now();
283
- await write();
284
- // An owed file keeps its old judgement current until pass 2 replaces it: nothing of it is marked stale yet.
285
- if (!deferred) {
286
- await store.markStale(scope, srcRef(rootId, f.path), f.hash);
287
- report.staleMarked += 1;
288
- }
289
- args.onStep?.({ path: f.path, phase: 'write', ms: now() - t0, outcome: 'ok' });
290
- if (complete) { filesNow.set(f.path, f.hash); finished.add(f.path); }
291
- return true;
292
- };
293
-
294
- const applyFile = async (slot: Slot): Promise<boolean> => {
295
- inWriter = true;
296
- try { return await applyInner(slot); } finally { inWriter = false; }
124
+ const apply: ApplyContext = {
125
+ c, gate, runSignal,
126
+ judgeCtx: {
127
+ batch: c.batch, entities: c.entities, stored: c.stored, judgedNow: c.judgedNow, newClaims: c.newClaims, measured: c.measured,
128
+ detail: c.detail, report, ...(args.onStep ? { onStep: args.onStep } : {}),
129
+ },
297
130
  };
298
131
  const queue: Slot[] = [];
299
132
  let applied = 0;
300
133
  const drain = async (keep: number) => {
301
- while (!cut && queue.length > keep) if (await applyFile(queue.shift()!)) applied += 1;
134
+ while (!cut && queue.length > keep) if (await applyFile(apply, queue.shift()!)) applied += 1;
302
135
  };
303
136
  let completed = false;
304
137
  try {
305
- for await (const { item: f, i, result } of prefetchOrdered(work, readAhead, prefetch, runSignal)) {
138
+ for await (const { item: f, i, result } of prefetchOrdered(c.work, readAhead, prefetch, runSignal)) {
306
139
  if (result.status === 'rejected') throw result.reason; // a prefetch job settles to a Prefetch; this is a broken invariant
307
140
  const job = result.value;
308
141
  queue.push({ f, i, job, judge: job.kind === 'extracted' ? startJudge(dispatch, f, job.extraction) : undefined });
@@ -315,92 +148,6 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
315
148
  signal?.removeEventListener('abort', relay);
316
149
  await Promise.allSettled(queue.map((s) => s.judge?.result)); // nothing outlives the run
317
150
  }
318
- if (applied < work.length) report.aborted = true;
319
- // A Stop ends the run: the file in hand was finished and applied above, but nothing after it (retire, analyzers, the digest stamp) runs.
320
- report.aborted ||= runSignal.aborted;
321
-
322
- // Pass 2 (`only`) is judging alone: the map pass already retired the removed files and ran the analyzers.
323
- if (!report.aborted && !args.only) {
324
- // The last file is written: leave "write" now, the analyzers below can take minutes.
325
- // Opened as 0/1 (not 0/0, which would close the row at once) so the row stays active until the final event below.
326
- progress({ phase: 'analyse', done: 0, total: 1 });
327
- await retire(detail.plan.removed);
328
- // Analyzers run in parallel and a failing one never aborts the review — its extracted
329
- // output is simply not stored (the file-level facts above are already durable), so a
330
- // single bad pack cannot sink the whole run. Each pack's latest count is kept and summed; only `done` is
331
- // monotonic (a total may grow as a pack discovers more work). A callback after its pack settled is dropped.
332
- const latest = new Map<number, AnalyzerProgress>();
333
- const sum = () => {
334
- let done = 0; let total = 0;
335
- for (const v of latest.values()) { done += v.done; total += v.total; }
336
- return { done, total: Math.max(1, total) };
337
- };
338
- const analysed = await Promise.all(
339
- packs.filter((p) => p.analyzers).map(async (p, k) => {
340
- let settled = false;
341
- const onProgress = (a: AnalyzerProgress) => {
342
- if (settled) return;
343
- latest.set(k, { done: a.done, total: a.total });
344
- progress({ phase: 'analyse', ...sum(), ...(a.path !== undefined ? { path: a.path } : {}) });
345
- };
346
- try { return await p.analyzers!.analyse(rootId, signal, onProgress); } catch { return []; } finally { settled = true; }
347
- }),
348
- );
349
- // Close the row whatever the analyzers reported (none, short, or a throw).
350
- const closing = Math.max(1, sum().total);
351
- progress({ phase: 'analyse', done: closing, total: closing });
352
- // A Stop during the analyzers ends the run like one during the write loop (`runSignal` no longer follows `signal` here).
353
- report.aborted ||= runSignal.aborted || !!signal?.aborted;
354
- for (const packResults of analysed) {
355
- for (const ex of packResults) {
356
- await store.putExtracted?.(ex.sourceHash, [ex]);
357
- report.extracted += 1;
358
- }
359
- }
360
- if (!report.aborted) progress({ phase: 'resolve', done: 0, total: newClaims.size });
361
- }
362
-
363
- // The compare phase needs a pack asking for it AND both ports.
364
- const wantsCompare = packs.some((p) => p.judgement?.contradictions);
365
- const canCompare = wantsCompare && !!args.judgement && !!args.similar;
366
- let outcome: CompareOutcome | undefined;
367
- if (!report.aborted && canCompare && !args.mechanical) {
368
- outcome = await compareNew({
369
- args, pending: newClaims, known: stored.facts, budget, batch,
370
- onPairs: (total) => progress({ phase: 'compare', done: 0, total }),
371
- });
372
- // Aborted only if the abort landed before the last pair was compared.
373
- if (outcome?.aborted) report.aborted = true;
374
- }
375
- // DURABILITY ORDER: everything the run produced is stored and durable BEFORE a manifest says its files are
376
- // done. A manifest ahead of the store loses knowledge for good (the next review sees those files unchanged
377
- // and skips them); a store ahead of the manifest only re-reviews files. `write()` first stores what the compare
378
- // phase left in the batch, then one flush covers the awaiting set (it names stored claims) and the files
379
- // manifest: nothing mutates the store between them. The trailing write only stamps lastDigest; the end of
380
- // the batch persists it.
381
- await write();
382
- await flush();
383
- // No pack asks for contradictions: nothing waits, and an earlier run's awaiting set is left as it was.
384
- if (wantsCompare && !args.mechanical) await saveAwaiting(manifest, rootId, newClaims, outcome);
385
-
386
- // Pass 2: what is still owed is every file of its slice it did not finish (an abort leaves the unreached ones owed too).
387
- report.awaitingJudge = args.only ? work.filter((f) => !finished.has(f.path)).map((f) => f.path) : owedJudge;
388
- report.awaitingJudgeCount = report.awaitingJudge.length;
389
- report.judgedFiles = args.only ? work.length - report.awaitingJudge.length : 0;
390
- if (breaker.stopped) report.judgeStopped = breaker.stopped;
391
- report.judged = batch.judged;
392
- report.unjudged = batch.unjudged;
393
- report.invalidJudgements = batch.invalid;
394
- report.digest = sha256Hex(canonicalJson({ rootId, packs: packIds, files: [...filesNow].sort((a, b) => compareStr(a[0], b[0])) }));
395
- await saveManifestMap(manifest, filesManifestKey(rootId), filesNow);
396
- await saveManifestMap(manifest, judgedManifestKey(rootId), judgedNow);
397
- // After every run: today's version and every file still owed a re-extraction — the unfinished ones,
398
- // content-changed or not, and the owed paths the plan did not list that the manifest still holds.
399
- await saveExtractorState(manifest, rootId, owedAfterRun({
400
- state: detail.extractor, changed, prior: detail.prior, finished, carried: detail.carried, live: filesNow, measured, unreadable,
401
- }), failures, detail.extractor.documentsNow);
402
- await write(report.aborted ? scopeRecord : { ...scopeRecord, lastDigest: report.digest, lastReviewedAt: new Date(now()).toISOString() });
403
- report.durationMs = now() - started;
404
- progress({ phase: 'done', done: work.length, total: work.length });
405
- return report;
151
+ if (applied < c.work.length) report.aborted = true;
152
+ return runSignal;
406
153
  }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * knowledge/reviewAnalyse.ts — the `analyse` stage of a review: every pack's analyzers run in parallel, under their own progress
3
+ * row, and their output goes to the extract cache (perception, never memory). Moved out of review.ts.
4
+ *
5
+ * A failing analyzer never aborts the review — its output is simply not stored (the file-level facts are already durable), so
6
+ * one bad pack cannot sink the run — but it is never silent either: it is recorded in `report.failures` (`kind: 'analyzer'`, phase `analyse`, path
7
+ * `analyzer:<pack id>`) and the other analyzers keep running.
8
+ */
9
+
10
+ import type { AnalyzerProgress, Extracted } from './model.js';
11
+ import type { ReviewContext } from './reviewContext.js';
12
+ import { reasonOf } from './reviewRunModel.js';
13
+
14
+ /** The `path` an analyzer failure is recorded under. */
15
+ export const analyzerFailurePath = (packId: string): string => `analyzer:${packId}`;
16
+
17
+ /**
18
+ * Runs the analyzers and stores what they extracted. Each pack's latest count is summed; only `done` is monotonic. The caller
19
+ * opened the `analyse` row (as 0/1); this closes it.
20
+ */
21
+ export async function runAnalyzers(c: ReviewContext): Promise<void> {
22
+ const { packs, signal } = c.args;
23
+ const latest = new Map<number, AnalyzerProgress>();
24
+ const sum = () => {
25
+ let done = 0; let total = 0;
26
+ for (const v of latest.values()) { done += v.done; total += v.total; }
27
+ return { done, total: Math.max(1, total) };
28
+ };
29
+ const analysed = await Promise.all(
30
+ packs.filter((p) => p.analyzers).map(async (p, k): Promise<Extracted[]> => {
31
+ let settled = false;
32
+ // A total may grow as a pack discovers more work. A callback after its pack settled is dropped.
33
+ const onProgress = (a: AnalyzerProgress) => {
34
+ if (settled) return;
35
+ latest.set(k, { done: a.done, total: a.total });
36
+ c.progress({ phase: 'analyse', ...sum(), ...(a.path !== undefined ? { path: a.path } : {}) });
37
+ };
38
+ try {
39
+ return await p.analyzers!.analyse(c.rootId, signal, onProgress);
40
+ } catch (error) {
41
+ c.report.failures.push({ kind: 'analyzer', path: analyzerFailurePath(p.id), phase: 'analyse', reason: reasonOf(error) });
42
+ return [];
43
+ } finally { settled = true; }
44
+ }),
45
+ );
46
+ // Close the row whatever the analyzers reported (none, short, or a throw).
47
+ const closing = Math.max(1, sum().total);
48
+ c.progress({ phase: 'analyse', done: closing, total: closing });
49
+ return storeAnalysed(c, analysed);
50
+ }
51
+
52
+ async function storeAnalysed(c: ReviewContext, analysed: readonly Extracted[][]): Promise<void> {
53
+ for (const packResults of analysed) {
54
+ for (const ex of packResults) {
55
+ await c.args.store.putExtracted?.(ex.sourceHash, [ex]);
56
+ c.report.extracted += 1;
57
+ }
58
+ }
59
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * knowledge/reviewApply.ts — the ordered writer of a review (PRD 41 A8): applies ONE settled file, in plan order — its failure,
3
+ * its asset node, its "nothing to extract", or its extract cache entry, judgement, write and markStale. Moved out of review.ts.
4
+ */
5
+
6
+ import type { ReviewContext } from './reviewContext.js';
7
+ import { writeBatch } from './reviewContext.js';
8
+ import { owedCalls } from './owedFiles.js';
9
+ import { putExtract, putNoExtract } from './extractFile.js';
10
+ import { recordFailure } from './reviewFailure.js';
11
+ import { applyJudge, judgesPack, splitSections, type JudgeJob } from './reviewJudge.js';
12
+ import type { Prefetch, PrefetchFile } from './reviewPrefetch.js';
13
+ import { putAsset } from './assetFile.js';
14
+ import { srcRef } from './refs.js';
15
+
16
+ /** One changed file between dispatch and the ordered writer: what its prefetch found and its judging in flight. */
17
+ export interface Slot {
18
+ f: PrefetchFile;
19
+ i: number;
20
+ job: Prefetch;
21
+ judge: JudgeJob | undefined;
22
+ }
23
+
24
+ /** Whether the writer is mid-file (an abort then cuts the run at this file's boundary), shared with the run's abort relay. */
25
+ export interface WriterGate { inWriter: boolean }
26
+
27
+ export interface ApplyContext {
28
+ c: ReviewContext;
29
+ gate: WriterGate;
30
+ /** The run's own stop signal. */
31
+ runSignal: AbortSignal;
32
+ /** What `applyJudge` merges into. */
33
+ judgeCtx: Parameters<typeof applyJudge>[0];
34
+ }
35
+
36
+ /**
37
+ * Applies one file, in plan order. False when its work was cut short by an abort (extracted, judging
38
+ * unfinished): nothing of it is applied and it stays as it was, owed. A file whose work is complete is
39
+ * applied even after an abort — the work is done, so it is kept.
40
+ */
41
+ export async function applyFile(a: ApplyContext, slot: Slot): Promise<boolean> {
42
+ a.gate.inWriter = true;
43
+ try { return await applyInner(a, slot); } finally { a.gate.inWriter = false; }
44
+ }
45
+
46
+ async function applyInner(a: ApplyContext, { f, i, job, judge }: Slot): Promise<boolean> {
47
+ const { c } = a;
48
+ const { store } = c.args;
49
+ c.progress({ phase: 'extract', done: i, total: c.work.length, path: f.path });
50
+ // A read that throws (permissions, a lock, a race with a delete) or an extraction that throws says nothing
51
+ // about the file: skipped with its knowledge and manifest hash intact, tried again next review.
52
+ if (job.kind === 'read-error' || job.kind === 'failed') {
53
+ if (job.kind === 'read-error') c.report.readErrors += 1; else c.report.extractErrors += 1;
54
+ c.report.failures.push({ path: f.path, phase: 'extract', reason: job.kind === 'read-error' ? `read: ${job.reason}` : job.reason });
55
+ c.measured.set(f.path, owedCalls(c.detail.extractor, f.path)); // learns nothing: keep what it was owed
56
+ // The ONE failure path (reviewFailure.ts): a transient failure keeps the re-check request and makes the file owed; only a proven-final
57
+ // one (or the third in a row at the same bytes) is answered with a terminal `[]`.
58
+ const ctx = { store, detail: c.detail, stopped: () => a.runSignal.aborted, unreadable: c.unreadable, failures: c.failures, settledRecheck: c.settledRecheck };
59
+ if (await recordFailure(ctx, f, job)) c.finished.add(f.path); // final: settled, not re-read while its bytes stand
60
+ return true;
61
+ }
62
+ c.failures.delete(f.path); // it read and extracted (or was decided): the run of failures at this hash ends
63
+ // An asset (planned binary, or a text-extension file found binary on read): never extracted, but it IS a file of the root, so
64
+ // its file node is stored (assetFile.ts) — a replica tells it from "not extracted yet", and references to its path resolve.
65
+ // Recorded, so a file found binary on read is not re-read by every later review.
66
+ if (job.kind === 'binary' || job.kind === 'asset') {
67
+ c.filesNow.set(f.path, f.hash);
68
+ c.finished.add(f.path);
69
+ await putAsset(store, c.rootId, f);
70
+ await c.settledRecheck(f.hash);
71
+ await store.markStale(c.scope, srcRef(c.rootId, f.path), f.hash);
72
+ c.report.staleMarked += 1;
73
+ return true;
74
+ }
75
+ if (job.kind === 'none') {
76
+ // No pack accepts the file: nothing will ever be extracted for it, so say so (and answer any re-check of it).
77
+ c.finished.add(f.path);
78
+ await putNoExtract(store, f.hash);
79
+ await c.settledRecheck(f.hash);
80
+ return true;
81
+ }
82
+ c.report.extracted += 1;
83
+ // The extract cache is written HERE, in plan order, so the cache, the counts and the order match a sequential run.
84
+ if (!job.extraction.cached) await putExtract(store, f.hash, job.extraction.extracted);
85
+ await c.settledRecheck(f.hash);
86
+ let complete = true;
87
+ let deferred = false;
88
+ if (c.args.mechanical && judgesPack(c.args.judgement, job.extraction.pack)) {
89
+ // 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
90
+ // 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
91
+ // owed and pass 2 finds nothing to judge (a cache hit, no call).
92
+ const { reuse, toJudge } = splitSections(c.judgedPrior, job.extraction);
93
+ if (job.extraction.sections.length > 0 && toJudge.length === 0) {
94
+ for (const ref of reuse) c.stored.refresh(ref, f.path, f.hash, c.batch, c.entities);
95
+ } else {
96
+ complete = false;
97
+ deferred = true;
98
+ c.owedJudge.push(f.path);
99
+ c.measured.set(f.path, Math.max(1, toJudge.length));
100
+ }
101
+ }
102
+ if (judge) {
103
+ c.progress({ phase: 'judge', done: i, total: c.work.length, path: f.path });
104
+ a.gate.inWriter = false; // waiting for the model calls is not the writer working
105
+ const outcome = await applyJudge(a.judgeCtx, f, judge);
106
+ a.gate.inWriter = true;
107
+ if (outcome === 'aborted') return false;
108
+ if (outcome === 'failed') {
109
+ c.owedJudge.push(f.path);
110
+ // Judging failed as a whole: leave the file exactly as it was (facts, manifest hash, owed) so the next review retries it.
111
+ c.measured.set(f.path, owedCalls(c.detail.extractor, f.path));
112
+ return true;
113
+ }
114
+ complete = outcome.complete;
115
+ if (!complete) c.owedJudge.push(f.path);
116
+ }
117
+ c.progress({ phase: 'write', done: i, total: c.work.length, path: f.path });
118
+ const t0 = c.now();
119
+ await writeBatch(c);
120
+ // An owed file keeps its old judgement current until pass 2 replaces it: nothing of it is marked stale yet.
121
+ if (!deferred) {
122
+ await store.markStale(c.scope, srcRef(c.rootId, f.path), f.hash);
123
+ c.report.staleMarked += 1;
124
+ }
125
+ c.args.onStep?.({ path: f.path, phase: 'write', ms: c.now() - t0, outcome: 'ok' });
126
+ if (complete) { c.filesNow.set(f.path, f.hash); c.finished.add(f.path); }
127
+ return true;
128
+ }