@seanhogg/builderforce-memory 2026.10.50 → 2026.10.52

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 (54) hide show
  1. package/dist/knowledge/backfillNoExtract.d.ts +37 -0
  2. package/dist/knowledge/backfillNoExtract.d.ts.map +1 -0
  3. package/dist/knowledge/backfillNoExtract.js +97 -0
  4. package/dist/knowledge/backfillNoExtract.js.map +1 -0
  5. package/dist/knowledge/extractFile.d.ts +5 -0
  6. package/dist/knowledge/extractFile.d.ts.map +1 -1
  7. package/dist/knowledge/extractFile.js +9 -0
  8. package/dist/knowledge/extractFile.js.map +1 -1
  9. package/dist/knowledge/findingBuilder.d.ts +18 -0
  10. package/dist/knowledge/findingBuilder.d.ts.map +1 -0
  11. package/dist/knowledge/findingBuilder.js +29 -0
  12. package/dist/knowledge/findingBuilder.js.map +1 -0
  13. package/dist/knowledge/findings.d.ts +2 -11
  14. package/dist/knowledge/findings.d.ts.map +1 -1
  15. package/dist/knowledge/findings.js +4 -22
  16. package/dist/knowledge/findings.js.map +1 -1
  17. package/dist/knowledge/godModule.d.ts +21 -0
  18. package/dist/knowledge/godModule.d.ts.map +1 -0
  19. package/dist/knowledge/godModule.js +42 -0
  20. package/dist/knowledge/godModule.js.map +1 -0
  21. package/dist/knowledge/index.d.ts +3 -1
  22. package/dist/knowledge/index.d.ts.map +1 -1
  23. package/dist/knowledge/index.js +2 -1
  24. package/dist/knowledge/index.js.map +1 -1
  25. package/dist/knowledge/model.d.ts +11 -0
  26. package/dist/knowledge/model.d.ts.map +1 -1
  27. package/dist/knowledge/review.d.ts.map +1 -1
  28. package/dist/knowledge/review.js +25 -5
  29. package/dist/knowledge/review.js.map +1 -1
  30. package/dist/knowledge/stores/localSnapshotStore.d.ts +9 -8
  31. package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
  32. package/dist/knowledge/stores/localSnapshotStore.js +29 -43
  33. package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
  34. package/dist/knowledge/stores/snapshotFormat.d.ts +32 -0
  35. package/dist/knowledge/stores/snapshotFormat.d.ts.map +1 -0
  36. package/dist/knowledge/stores/snapshotFormat.js +49 -0
  37. package/dist/knowledge/stores/snapshotFormat.js.map +1 -0
  38. package/package.json +3 -3
  39. package/src/contract/exports.snapshot.json +4 -0
  40. package/src/contract/regression.review.test.ts +121 -1
  41. package/src/contract/regression.store.test.ts +13 -0
  42. package/src/contract/types.contract.test.ts +11 -6
  43. package/src/knowledge/backfillNoExtract.ts +85 -0
  44. package/src/knowledge/extractFile.ts +9 -0
  45. package/src/knowledge/findingBuilder.ts +37 -0
  46. package/src/knowledge/findings.ts +4 -27
  47. package/src/knowledge/godModule.test.ts +64 -0
  48. package/src/knowledge/godModule.ts +46 -0
  49. package/src/knowledge/index.ts +3 -1
  50. package/src/knowledge/model.ts +11 -0
  51. package/src/knowledge/pack/pack.roundtrip.test.ts +1 -1
  52. package/src/knowledge/review.ts +20 -4
  53. package/src/knowledge/stores/localSnapshotStore.ts +28 -60
  54. package/src/knowledge/stores/snapshotFormat.ts +69 -0
@@ -10,11 +10,12 @@ import type { ReviewStep } from '../knowledge/reviewRunModel.js';
10
10
  import { extractJob, type ExtractJob, type ExtractPool } from '../knowledge/extractJob.js';
11
11
  import type { JudgementRequest, KnowledgePack, KnowledgeStore } from '../knowledge/model.js';
12
12
  import { DOCS_PACK } from '../knowledge/packs/docs.js';
13
+ import { putNoExtract } from '../knowledge/extractFile.js';
13
14
  import { planReview } from '../knowledge/plan.js';
14
15
  import { srcRef } from '../knowledge/refs.js';
15
16
  import { reviewDirectory } from '../knowledge/review.js';
16
17
  import { applyRunEvent, failuresOf, failureTotal, REVIEW_RUN_FAILURE_CHUNK, startRun } from '../knowledge/reviewRun.js';
17
- import { extractorManifestKey, filesManifestKey, judgedManifestKey, manifestMap } from '../knowledge/sources.js';
18
+ import { extractorManifestKey, filesManifestKey, judgedManifestKey, manifestMap, saveManifestMap } from '../knowledge/sources.js';
18
19
  import {
19
20
  ALL, args, fakeJudge, FILES, memSource, memStore, quietPack, ROOT, stateOf, type SpySource,
20
21
  } from '../knowledge/testkit.test-util.js';
@@ -234,3 +235,122 @@ describe('regression: changed since plan', () => {
234
235
  expect(await store.getExtracted(hashText(FILES['a.md']))).toBeUndefined();
235
236
  });
236
237
  });
238
+
239
+ describe('regression: a file with nothing to extract is told apart from one not extracted yet', () => {
240
+ it('regression: a file found binary on read has an explicit stored [] (and a stale mark), never an absent body', async () => {
241
+ const text = 'bin\u0000ary';
242
+ const store = memStore();
243
+ await reviewDirectory(args(memSource({ 'blob.txt': text }), store, new InMemoryIngestManifest()));
244
+ expect(await store.getExtracted(hashText(text))).toEqual([]);
245
+ });
246
+
247
+ it('regression: a text file that is not extracted (here: its review failed) has NO stored body, so it is never mistaken for binary', async () => {
248
+ const store = memStore();
249
+ const text = '# A\nalpha\n';
250
+ expect(await store.getExtracted(hashText(text))).toBeUndefined();
251
+ await store.markStale({ rootId: ROOT }, srcRef(ROOT, 'a.md'), hashText(text)); // staled before it is extracted
252
+ expect(await store.getExtracted(hashText(text))).toBeUndefined();
253
+ });
254
+
255
+ it('regression: recording "nothing extracted" never clobbers a hash that already has entries', async () => {
256
+ const store = memStore();
257
+ const text = '# A\nalpha\n';
258
+ await reviewDirectory(args(memSource({ 'a.md': text }), store, new InMemoryIngestManifest()));
259
+ const before = await store.getExtracted(hashText(text));
260
+ expect(before!.length).toBeGreaterThan(0);
261
+ await putNoExtract(store, hashText(text));
262
+ expect(await store.getExtracted(hashText(text))).toEqual(before);
263
+ });
264
+ });
265
+
266
+ describe('regression: a root reviewed before binary files were recorded is settled by its next review, without reading a file', () => {
267
+ const text = '# A\nalpha\n';
268
+
269
+ it('regression: a binary-by-extension file the manifest names, with no stored body, gets a stored [] and no file is read', async () => {
270
+ const source = memSource({ 'a.md': text, 'img.png': 'x' });
271
+ const manifest = new InMemoryIngestManifest();
272
+ await saveManifestMap(manifest, filesManifestKey(ROOT), new Map([['img.png', 'imghash']]));
273
+ const store = memStore();
274
+ await reviewDirectory(args(source, store, manifest));
275
+ expect(await store.getExtracted('imghash')).toEqual([]);
276
+ expect(source.reads).not.toContain('img.png');
277
+ });
278
+
279
+ it('regression: the review reads ONLY the files a replica asked to re-check: a NUL-binary gets [], a text file is extracted, the set is cleared', async () => {
280
+ const binary = 'bin\u0000ary';
281
+ const files = { 'blob.txt': binary, 'a.md': text, 'b.md': '# B\nbeta\n' };
282
+ const manifest = new InMemoryIngestManifest();
283
+ await reviewDirectory(args(memSource(files), memStore(), manifest));
284
+ const legacy = memStore(); // a root reviewed before: the manifest names the files, this store holds no bodies
285
+ await legacy.markRecheck([hashText(binary), hashText(text)]);
286
+
287
+ const source = memSource(files);
288
+ await reviewDirectory(args(source, legacy, manifest));
289
+ expect(new Set(source.reads)).toEqual(new Set(['blob.txt', 'a.md'])); // b.md was never named
290
+ expect(await legacy.getExtracted(hashText(binary))).toEqual([]);
291
+ expect((await legacy.getExtracted(hashText(text)))!.length).toBeGreaterThan(0);
292
+ expect(await legacy.getExtracted(hashText(files['b.md']))).toBeUndefined();
293
+ expect(await legacy.recheckHashes()).toEqual([]);
294
+
295
+ source.reads.length = 0;
296
+ await reviewDirectory(args(source, legacy, manifest)); // the set is empty now: nothing is read
297
+ expect(source.reads).toEqual([]);
298
+ });
299
+
300
+ it('regression: a re-checked hash only a SKIPPED manifest entry carries (here: ignored) is settled with [] and cleared, never left to loop', async () => {
301
+ const manifest = new InMemoryIngestManifest();
302
+ await saveManifestMap(manifest, filesManifestKey(ROOT), new Map([['skip.md', 'skiphash']]));
303
+ const legacy = memStore();
304
+ await legacy.markRecheck(['skiphash', 'gonehash']);
305
+ await reviewDirectory(args(memSource({ '.gitignore': 'skip.md\n', 'skip.md': '# S\nskipped\n', 'a.md': text }), legacy, manifest));
306
+ expect(await legacy.getExtracted('skiphash')).toEqual([]); // no review will ever extract an ignored file
307
+ expect(await legacy.getExtracted('gonehash')).toBeUndefined(); // carried by nothing: nothing to store
308
+ expect(await legacy.recheckHashes()).toEqual([]);
309
+ });
310
+
311
+ it('regression: a file whose read fails gets a terminal [] under the hash the manifest holds, so it is never held back forever (and a later read replaces it)', async () => {
312
+ const manifest = new InMemoryIngestManifest();
313
+ await saveManifestMap(manifest, filesManifestKey(ROOT), new Map([['locked.md', 'oldhash']]));
314
+ const store = memStore();
315
+ const inner = memSource({ 'locked.md': '# L\nlocked\n' });
316
+ const locked = { ...inner, read: async () => { throw new Error('EBUSY'); } };
317
+ const report = await reviewDirectory(args(locked as never, store, manifest));
318
+ expect(report.readErrors).toBe(1);
319
+ expect(await store.getExtracted('oldhash')).toEqual([]);
320
+ // The file becomes readable at a new hash: the real body is stored under it, and the terminal answer for the old hash stays harmless.
321
+ await reviewDirectory(args(inner, store, manifest));
322
+ expect((await store.getExtracted(hashText('# L\nlocked\n')))!.length).toBeGreaterThan(0);
323
+ });
324
+
325
+ it('regression: a review that is aborted before it did the work keeps the re-check request, and one that completes it clears it', async () => {
326
+ const manifest = new InMemoryIngestManifest();
327
+ await reviewDirectory(args(memSource({ 'a.md': text }), memStore(), manifest));
328
+ const legacy = memStore();
329
+ await legacy.markRecheck([hashText(text)]);
330
+ const stop = new AbortController();
331
+ stop.abort();
332
+ await reviewDirectory(args(memSource({ 'a.md': text }), legacy, manifest, { signal: stop.signal })).catch(() => undefined);
333
+ expect(await legacy.recheckHashes()).toEqual([hashText(text)]);
334
+ await reviewDirectory(args(memSource({ 'a.md': text }), legacy, manifest));
335
+ expect(await legacy.recheckHashes()).toEqual([]);
336
+ expect((await legacy.getExtracted(hashText(text)))!.length).toBeGreaterThan(0);
337
+ });
338
+
339
+ it('regression: an unchanged text file with no stored body is NOT given [] (it is "not extracted yet")', async () => {
340
+ const manifest = new InMemoryIngestManifest();
341
+ await reviewDirectory(args(memSource({ 'a.md': text }), memStore(), manifest));
342
+ const legacy = memStore();
343
+ await reviewDirectory(args(memSource({ 'a.md': text }), legacy, manifest));
344
+ expect(await legacy.getExtracted(hashText(text))).toBeUndefined();
345
+ });
346
+
347
+ it('regression: a healthy root performs no extra reads on an incremental review', async () => {
348
+ const source = memSource({ 'a.md': text, 'blob.txt': 'bin\u0000ary' });
349
+ const manifest = new InMemoryIngestManifest();
350
+ const store = memStore();
351
+ await reviewDirectory(args(source, store, manifest));
352
+ source.reads.length = 0;
353
+ await reviewDirectory(args(source, store, manifest));
354
+ expect(source.reads).toEqual([]);
355
+ });
356
+ });
@@ -82,3 +82,16 @@ describe('regression: snapshot migration', () => {
82
82
  expect(Object.keys(JSON.parse(snap.value!).extracted).sort()).toEqual(['new', 'old']);
83
83
  });
84
84
  });
85
+
86
+ describe('regression: re-check channel', () => {
87
+ it('regression: hashes marked for re-check survive a reload, and clearing them removes them from the snapshot', async () => {
88
+ const snap = memPersistence();
89
+ await new LocalSnapshotStore(snap).markRecheck(['b', 'a']);
90
+ const again = new LocalSnapshotStore(snap);
91
+ expect(await again.recheckHashes()).toEqual(['a', 'b']);
92
+ await again.clearRecheck(['a']);
93
+ expect(await new LocalSnapshotStore(snap).recheckHashes()).toEqual(['b']);
94
+ await again.clearRecheck(['b']);
95
+ expect(JSON.parse(snap.value!).recheck).toBeUndefined();
96
+ });
97
+ });
@@ -26,7 +26,7 @@ type IsOptional<T, K extends keyof T> = Record<never, never> extends Pick<T, K>
26
26
 
27
27
  /* ── KnowledgeSnapshot ─────────────────────────────────────────────────────────────────────────────────────── */
28
28
  // `extracted` became optional (the extract cache moved to the log); consumers read it ONLY through `extractedEntries()`.
29
- export type KnowledgeSnapshot_keys = Expect<Equal<keyof KnowledgeSnapshot, 'version' | 'scopes' | 'facts' | 'relations' | 'extracted'>>;
29
+ export type KnowledgeSnapshot_keys = Expect<Equal<keyof KnowledgeSnapshot, 'version' | 'scopes' | 'facts' | 'relations' | 'extracted' | 'recheck'>>;
30
30
  export type KnowledgeSnapshot_extracted_is_optional = Expect<Equal<IsOptional<KnowledgeSnapshot, 'extracted'>, true>>;
31
31
  export type KnowledgeSnapshot_extracted_shape = Expect<Equal<KnowledgeSnapshot['extracted'], Record<string, Extracted[]> | undefined>>;
32
32
  export type KnowledgeSnapshot_rows_are_required = Expect<Equal<
@@ -93,18 +93,19 @@ export type ExtractJobResult_fields = Expect<Equal<ExtractJobResult, { binary?:
93
93
  /* ── KnowledgeStore: the port hosts implement ──────────────────────────────────────────────────────────────── */
94
94
  export type KnowledgeStore_methods = Expect<Equal<
95
95
  keyof KnowledgeStore,
96
- 'scopes' | 'facts' | 'relations' | 'write' | 'markStale' | 'getExtracted' | 'putExtracted' | 'preloadExtracted' | 'batched'
96
+ 'scopes' | 'facts' | 'relations' | 'write' | 'markStale' | 'getExtracted' | 'putExtracted' | 'preloadExtracted' | 'markRecheck' | 'recheckHashes' | 'clearRecheck' | 'hasRecheck' | 'batched'
97
97
  >>;
98
98
  export type KnowledgeStore_optional_methods = Expect<Equal<
99
- [IsOptional<KnowledgeStore, 'getExtracted'>, IsOptional<KnowledgeStore, 'putExtracted'>, IsOptional<KnowledgeStore, 'preloadExtracted'>, IsOptional<KnowledgeStore, 'batched'>],
100
- [true, true, true, true]
99
+ [IsOptional<KnowledgeStore, 'getExtracted'>, IsOptional<KnowledgeStore, 'putExtracted'>, IsOptional<KnowledgeStore, 'preloadExtracted'>, IsOptional<KnowledgeStore, 'batched'>,
100
+ IsOptional<KnowledgeStore, 'markRecheck'>, IsOptional<KnowledgeStore, 'recheckHashes'>, IsOptional<KnowledgeStore, 'clearRecheck'>, IsOptional<KnowledgeStore, 'hasRecheck'>],
101
+ [true, true, true, true, true, true, true, true]
101
102
  >>;
102
103
  export type KnowledgeStore_required_methods = Expect<Equal<
103
104
  [IsOptional<KnowledgeStore, 'scopes'>, IsOptional<KnowledgeStore, 'facts'>, IsOptional<KnowledgeStore, 'relations'>, IsOptional<KnowledgeStore, 'write'>, IsOptional<KnowledgeStore, 'markStale'>],
104
105
  [false, false, false, false, false]
105
106
  >>;
106
107
  export type KnowledgeStore_signatures = Expect<Equal<
107
- Pick<KnowledgeStore, 'scopes' | 'facts' | 'relations' | 'write' | 'markStale' | 'getExtracted' | 'putExtracted' | 'preloadExtracted'>,
108
+ Pick<KnowledgeStore, 'scopes' | 'facts' | 'relations' | 'write' | 'markStale' | 'getExtracted' | 'putExtracted' | 'preloadExtracted' | 'markRecheck' | 'recheckHashes' | 'clearRecheck' | 'hasRecheck'>,
108
109
  {
109
110
  scopes(): Promise<ScopeRecord[]>;
110
111
  facts(scope: { rootId: string }): Promise<StoredFact[]>;
@@ -114,6 +115,10 @@ export type KnowledgeStore_signatures = Expect<Equal<
114
115
  getExtracted?(hash: string): Promise<Extracted[] | undefined>;
115
116
  putExtracted?(hash: string, extracted: Extracted[]): Promise<void>;
116
117
  preloadExtracted?(hashes: readonly string[]): Promise<void>;
118
+ markRecheck?(hashes: readonly string[]): Promise<void>;
119
+ recheckHashes?(): Promise<string[]>;
120
+ clearRecheck?(hashes: readonly string[]): Promise<void>;
121
+ hasRecheck?(hash: string): Promise<boolean>;
117
122
  }
118
123
  >>;
119
124
  // A host store with only the required methods is still a KnowledgeStore (the optional ones stay optional).
@@ -133,7 +138,7 @@ export const batchedHostStore = {
133
138
  export type LocalSnapshotStore_is_a_KnowledgeStore = Expect<Equal<LocalSnapshotStore extends KnowledgeStore ? true : false, true>>;
134
139
  export type LocalSnapshotStore_public_methods = Expect<Equal<
135
140
  keyof LocalSnapshotStore,
136
- 'batched' | 'scopes' | 'facts' | 'relations' | 'write' | 'markStale' | 'getExtracted' | 'extractedEntries' | 'putExtracted'
141
+ 'batched' | 'scopes' | 'facts' | 'relations' | 'write' | 'markStale' | 'getExtracted' | 'extractedEntries' | 'putExtracted' | 'markRecheck' | 'recheckHashes' | 'clearRecheck' | 'hasRecheck'
137
142
  >>;
138
143
  export type LocalSnapshotStore_extractedEntries = Expect<Equal<LocalSnapshotStore['extractedEntries'], () => Promise<Record<string, Extracted[]>>>>;
139
144
  export type LocalSnapshotStore_constructor = Expect<Equal<
@@ -0,0 +1,85 @@
1
+ /**
2
+ * knowledge/backfillNoExtract.ts — settles the files a root holds with no stored body, so a replica can tell
3
+ * "nothing is extracted for this file" (binary: an explicit `[]`) from "not extracted yet".
4
+ *
5
+ * A review stores `[]` for a file it finds binary (`putNoExtract`), but a root reviewed before that existed names such
6
+ * files in its manifest with no body, and no later review visits them again. Two cases, neither a sweep:
7
+ *
8
+ * - binary by EXTENSION: the plan SKIPS the file (reason `binary`) yet the manifest may still name it. The extension is the
9
+ * whole test, so no file is read; only a hash with no stored body is touched. (A planned file with a binary-looking
10
+ * extension is a pdf/office document a host extractor handles: never `[]` by extension.)
11
+ * - binary by CONTENT (a NUL): unknowable without reading. A replica that holds a file back, or is told by the server that a
12
+ * body is missing, calls `store.markRecheck(hashes)`; the review reads ONLY the unchanged planned files with those hashes.
13
+ * Binary → `[]`. Anything else (text, a document) → queued for extraction this run (`changed`). A hash only a SKIPPED
14
+ * prior entry carries is never extracted by any review: `[]`. Hashes settled HERE are cleared here; a queued one is cleared by the review
15
+ * once its body (or the failure) is stored, so an aborted run keeps the request.
16
+ *
17
+ * A healthy root has no body missing and an empty recheck set: it reads nothing and costs only in-memory lookups.
18
+ */
19
+
20
+ import type { DirectorySource, KnowledgeStore } from './model.js';
21
+ import { putNoExtract } from './extractFile.js';
22
+ import type { PlanDetail } from './plan.js';
23
+ import { isBinaryText } from './sources.js';
24
+
25
+ export interface BackfillResult {
26
+ /** Hashes stored as an explicit `[]`. */
27
+ recorded: number;
28
+ /** Files queued for extraction (marked `changed` in the plan). */
29
+ queued: string[];
30
+ }
31
+
32
+ /** The hashes the backfill will look up (for the review's ONE bulk preload): binary-by-extension manifest entries, and the re-check set. */
33
+ export function backfillCandidates(detail: PlanDetail, asked: readonly string[]): string[] {
34
+ const skippedBinary = detail.plan.skipped.filter((s) => s.reason === 'binary').map((s) => detail.prior.get(s.path)).filter((h): h is string => !!h);
35
+ return [...new Set([...skippedBinary, ...asked])];
36
+ }
37
+
38
+ export async function backfillNoExtract(args: { store: KnowledgeStore; source: DirectorySource; detail: PlanDetail; asked: readonly string[]; only?: readonly string[] | undefined; signal?: AbortSignal | undefined }): Promise<BackfillResult> {
39
+ const { store, source, detail, signal } = args;
40
+ const asked = new Set(args.asked);
41
+ const out: BackfillResult = { recorded: 0, queued: [] };
42
+ if (!store.getExtracted || !store.putExtracted) return out;
43
+
44
+ const skippedBinary = detail.plan.skipped.filter((s) => s.reason === 'binary').map((s) => detail.prior.get(s.path)).filter((h): h is string => !!h);
45
+
46
+ for (const hash of skippedBinary) {
47
+ if (signal?.aborted) return out;
48
+ if ((await store.getExtracted(hash)) !== undefined) continue;
49
+ await putNoExtract(store, hash);
50
+ out.recorded += 1;
51
+ }
52
+ if (asked.size === 0) return out;
53
+
54
+ const skippedHashes = new Set(detail.plan.skipped.map((s) => detail.prior.get(s.path)).filter((h): h is string => !!h));
55
+ const planned = new Map<string, typeof detail.files>();
56
+ for (const f of detail.files) planned.set(f.hash, [...(planned.get(f.hash) ?? []), f]);
57
+ const done = new Set<string>();
58
+ for (const hash of asked) {
59
+ if (signal?.aborted) break;
60
+ if ((await store.getExtracted(hash)) !== undefined) { done.add(hash); continue; }
61
+ const files = planned.get(hash);
62
+ if (!files) {
63
+ // Only a skipped prior entry (ignored, too large, no pack) carries it: no review will ever extract it. Otherwise it is gone.
64
+ if (skippedHashes.has(hash)) { await putNoExtract(store, hash); out.recorded += 1; }
65
+ done.add(hash);
66
+ continue;
67
+ }
68
+ const todo = files.filter((f) => !f.changed && detail.prior.get(f.path) === f.hash);
69
+ if (todo.length === 0) { done.add(hash); continue; } // a changed file is handled by this review
70
+ // Pass 2 works only on `only`: a file it will not process is not queued here, and its hash stays asked for the run that will.
71
+ if (args.only && !todo.some((t) => args.only!.includes(t.path))) continue;
72
+ const f = todo[0]!;
73
+ let binary = false;
74
+ try {
75
+ const doc = await source.read(f.path);
76
+ binary = doc.content.kind === 'text' && isBinaryText(doc.content.text);
77
+ } catch {
78
+ continue; // unreadable says nothing about the file: asked again next time
79
+ }
80
+ if (binary) { await putNoExtract(store, hash); out.recorded += 1; done.add(hash); }
81
+ else for (const t of todo) { t.changed = true; out.queued.push(t.path); } // asked for until the review has stored its body (see `settledRecheck`)
82
+ }
83
+ if (done.size > 0 && !signal?.aborted) await store.clearRecheck?.([...done]);
84
+ return out;
85
+ }
@@ -69,6 +69,15 @@ export async function putExtract(store: KnowledgeStore, hash: string, extracted:
69
69
  await store.putExtracted?.(hash, [...cached.filter((e) => e.sourceRef !== extracted.sourceRef), extracted]);
70
70
  }
71
71
 
72
+ /**
73
+ * Records, once, that nothing is extracted for `hash` (a binary file): the cache holds an explicit `[]`, which a store keeps
74
+ * distinct from "absent" (a text file not extracted yet). A hash that already has entries is left alone.
75
+ */
76
+ export async function putNoExtract(store: KnowledgeStore, hash: string): Promise<void> {
77
+ if (!store.putExtracted || !store.getExtracted || (await store.getExtracted(hash)) !== undefined) return;
78
+ await store.putExtracted(hash, []);
79
+ }
80
+
72
81
  /** Extraction plus what produced it; undefined when no pack's parser accepts the file. */
73
82
  export async function extractFileDetailed(a: ExtractFileArgs): Promise<FileExtraction | undefined> {
74
83
  // Pack resolution needs only the path and media type, so a file the pool reads is resolved from a content-free key.
@@ -0,0 +1,37 @@
1
+ /**
2
+ * knowledge/findingBuilder.ts — the ONE finding builder and its id scheme, split out of
3
+ * findings.ts so a rule module (e.g. godModule.ts) and findings.ts can both import it
4
+ * without importing each other.
5
+ */
6
+
7
+ import { hashText } from '../ingest/hash.js';
8
+ import type { Finding, NodeRef } from './model.js';
9
+ import { compareStr } from './refs.js';
10
+
11
+ /** Refs listed on one grouped finding, at most (the count rides in params). */
12
+ export const MAX_FINDING_NODES = 50;
13
+
14
+ export function findingId(kind: string, refs: readonly string[]): string {
15
+ return `${kind}:${hashText([...refs].sort(compareStr).join('\u0000'))}`;
16
+ }
17
+
18
+ /** `clone-group` → `knowledgeGraph.fix.cloneGroup`. */
19
+ export function requestKeyFor(kind: string): string {
20
+ return `knowledgeGraph.fix.${kind.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase())}`;
21
+ }
22
+
23
+ /**
24
+ * The ONE finding builder: nodes deduped, sorted and capped at {@link MAX_FINDING_NODES}.
25
+ * The id hashes `idRefs` (default: all the nodes) — pass a narrower set to keep it stable
26
+ * while the listed nodes change.
27
+ */
28
+ export function finding(
29
+ kind: string, pack: string, nodes: readonly NodeRef[], severity: Finding['severity'], params: Finding['params'],
30
+ idRefs?: readonly string[],
31
+ ): Finding {
32
+ const sorted = [...new Set(nodes)].sort(compareStr);
33
+ return {
34
+ id: findingId(kind, idRefs ?? sorted), kind, pack, nodes: sorted.slice(0, MAX_FINDING_NODES), severity, params,
35
+ requestKey: requestKeyFor(kind),
36
+ };
37
+ }
@@ -8,16 +8,15 @@
8
8
  * Fix-with-agent request, never a model call.
9
9
  */
10
10
 
11
- import { hashText } from '../ingest/hash.js';
11
+ import { finding, findingId, MAX_FINDING_NODES, requestKeyFor } from './findingBuilder.js';
12
12
  import type { EdgeVerdict, Finding, KEdge, KNode, KnowledgeGraph, KnowledgePack, NodeRef, PartitionRegistry } from './model.js';
13
13
  import type { SimilarPair } from '../retrieval/knowledge-index/types.js';
14
+ import { godModuleFindings } from './godModule.js';
14
15
  import { possibleSameFindings } from './resolve.js';
15
16
  import { aboutTargets, compareStr, round6, srcRef } from './refs.js';
16
17
 
17
18
  /** Node badge naming the clone group (e.g. a jscpd issue id) its `duplicate` edges belong to. */
18
19
  export const CLONE_GROUP_BADGE = 'cloneGroup';
19
- /** Refs listed on one grouped finding, at most (the count rides in params). */
20
- export const MAX_FINDING_NODES = 50;
21
20
 
22
21
  const SEVERITY_RANK = { error: 0, warn: 1, info: 2 } as const;
23
22
 
@@ -26,30 +25,7 @@ export function partitionSeverity(verdict: EdgeVerdict): Finding['severity'] {
26
25
  return verdict === 'upward' ? 'error' : 'warn';
27
26
  }
28
27
 
29
- export function findingId(kind: string, refs: readonly string[]): string {
30
- return `${kind}:${hashText([...refs].sort(compareStr).join('\u0000'))}`;
31
- }
32
-
33
- /** `clone-group` → `knowledgeGraph.fix.cloneGroup`. */
34
- export function requestKeyFor(kind: string): string {
35
- return `knowledgeGraph.fix.${kind.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase())}`;
36
- }
37
-
38
- /**
39
- * The ONE finding builder: nodes deduped, sorted and capped at {@link MAX_FINDING_NODES}.
40
- * The id hashes `idRefs` (default: all the nodes) — pass a narrower set to keep it stable
41
- * while the listed nodes change.
42
- */
43
- export function finding(
44
- kind: string, pack: string, nodes: readonly NodeRef[], severity: Finding['severity'], params: Finding['params'],
45
- idRefs?: readonly string[],
46
- ): Finding {
47
- const sorted = [...new Set(nodes)].sort(compareStr);
48
- return {
49
- id: findingId(kind, idRefs ?? sorted), kind, pack, nodes: sorted.slice(0, MAX_FINDING_NODES), severity, params,
50
- requestKey: requestKeyFor(kind),
51
- };
52
- }
28
+ export { finding, findingId, requestKeyFor, MAX_FINDING_NODES };
53
29
 
54
30
  /** Connected components over edges, each sorted; components sorted by first ref. */
55
31
  export function components(edges: readonly KEdge[]): NodeRef[][] {
@@ -135,6 +111,7 @@ export function genericFindings(g: KnowledgeGraph, registries: ReadonlyMap<strin
135
111
  }
136
112
 
137
113
  out.push(...staleFindings(g, byRef));
114
+ out.push(...godModuleFindings(g));
138
115
  return out;
139
116
  }
140
117
 
@@ -0,0 +1,64 @@
1
+ /**
2
+ * src/knowledge/godModule.test.ts — the `god-module` finding: measures beside limits, omitted when
3
+ * the badge is absent, stable id, deterministic order.
4
+ */
5
+
6
+ import { computeFindings, findingId } from './findings.js';
7
+ import { GOD_MODULE_LIMITS, godModuleFindings } from './godModule.js';
8
+ import type { KNode, KnowledgeGraph } from './model.js';
9
+
10
+ function fileNode(ref: string, badges: Record<string, number | string>, kind = 'file'): KNode {
11
+ return { ref, kind, label: ref, pack: 'code', importance: 0, origin: 'extracted' as KNode['origin'], badges };
12
+ }
13
+
14
+ function graph(nodes: KNode[]): KnowledgeGraph {
15
+ return {
16
+ scope: { rootId: 'r', packs: ['code'], digest: 'd' }, nodes, edges: [], findings: [],
17
+ stats: { sources: nodes.length, nodes: nodes.length, edges: 0, stale: 0, truncated: false },
18
+ };
19
+ }
20
+
21
+ describe('GOD_MODULE_LIMITS', () => {
22
+ it('is frozen at the documented limits', () => {
23
+ expect(GOD_MODULE_LIMITS).toEqual({ lines: 1000, exports: 40, complexity: 60 });
24
+ expect(Object.isFrozen(GOD_MODULE_LIMITS)).toBe(true);
25
+ });
26
+ });
27
+
28
+ describe('godModuleFindings', () => {
29
+ it('regression: a file with the god-module badge yields a heuristic-sized warn finding with measures and limits', () => {
30
+ const g = graph([fileNode('src:r::big.ts', { patterns: 'adapter,god-module', lines: 1500, exports: 12, maxComplexity: 70 })]);
31
+ const found = godModuleFindings(g);
32
+ expect(found).toHaveLength(1);
33
+ expect(found[0]).toMatchObject({
34
+ kind: 'god-module', pack: 'code', severity: 'warn', nodes: ['src:r::big.ts'], requestKey: 'knowledgeGraph.fix.godModule',
35
+ params: { lines: 1500, exports: 12, complexity: 70, linesLimit: 1000, exportsLimit: 40, complexityLimit: 60 },
36
+ });
37
+ expect(found[0]!.id).toBe(findingId('god-module', ['src:r::big.ts']));
38
+ });
39
+
40
+ it('omits a measure whose badge is absent, never the limits', () => {
41
+ const [f] = godModuleFindings(graph([fileNode('src:r::old.ts', { patterns: 'god-module', exports: 55 })]));
42
+ expect(f!.params).toEqual({ exports: 55, linesLimit: 1000, exportsLimit: 40, complexityLimit: 60 });
43
+ });
44
+
45
+ it('ignores files without the badge, a lookalike pattern id and non-file nodes', () => {
46
+ const g = graph([
47
+ fileNode('src:r::a.ts', { patterns: 'adapter' }),
48
+ fileNode('src:r::b.ts', { patterns: 'not-god-module-ish' }),
49
+ fileNode('src:r::c.ts', { patterns: 'god-module' }, 'symbol'),
50
+ ]);
51
+ expect(godModuleFindings(g)).toEqual([]);
52
+ });
53
+
54
+ it('is part of computeFindings, in a deterministic order', () => {
55
+ const g = graph([
56
+ fileNode('src:r::z.ts', { patterns: 'god-module' }),
57
+ fileNode('src:r::a.ts', { patterns: 'god-module' }),
58
+ ]);
59
+ const a = computeFindings(g, [], new Map(), []).filter((f) => f.kind === 'god-module');
60
+ const b = computeFindings({ ...g, nodes: [...g.nodes].reverse() }, [], new Map(), []).filter((f) => f.kind === 'god-module');
61
+ expect(a).toHaveLength(2);
62
+ expect(a.map((f) => f.id)).toEqual(b.map((f) => f.id));
63
+ });
64
+ });
@@ -0,0 +1,46 @@
1
+ /**
2
+ * knowledge/godModule.ts — the `god-module` finding: one per file node whose `patterns` badge
3
+ * names `god-module`, carrying the measures that tripped it next to the limits they are held to.
4
+ *
5
+ * Memory owns the limits ({@link GOD_MODULE_LIMITS}); the code pack's detector imports them, so the
6
+ * badge and the finding can never disagree. The measures are read from the file's badges
7
+ * (`lines`, `exports`, `maxComplexity`); a measure is omitted when its badge is absent (a graph
8
+ * reviewed before that badge existed). Heuristic by nature: it is a size/shape guess, never a model.
9
+ */
10
+
11
+ import type { Finding, KnowledgeGraph } from './model.js';
12
+ import { finding } from './findingBuilder.js';
13
+ import { compareStr } from './refs.js';
14
+
15
+ /** What a file may grow to before it is a god module: more lines, exports or worst-function complexity than this. */
16
+ export const GOD_MODULE_LIMITS = Object.freeze({ lines: 1_000, exports: 40, complexity: 60 } as const);
17
+ export type GodModuleLimits = typeof GOD_MODULE_LIMITS;
18
+
19
+ /** The finding kind (also the pattern id in the `patterns` badge). */
20
+ export const GOD_MODULE_KIND = 'god-module';
21
+
22
+ const PATTERNS_BADGE = 'patterns';
23
+ const MEASURE_BADGES = { lines: 'lines', exports: 'exports', complexity: 'maxComplexity' } as const;
24
+
25
+ const numberOf = (v: unknown): number | undefined => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);
26
+
27
+ export function godModuleFindings(g: KnowledgeGraph): Finding[] {
28
+ const out: Finding[] = [];
29
+ for (const n of [...g.nodes].sort((a, b) => compareStr(a.ref, b.ref))) {
30
+ if (n.kind !== 'file') continue;
31
+ const patterns = n.badges?.[PATTERNS_BADGE];
32
+ if (typeof patterns !== 'string' || !patterns.split(',').includes(GOD_MODULE_KIND)) continue;
33
+ const params: Record<string, number> = {};
34
+ for (const [key, badge] of Object.entries(MEASURE_BADGES)) {
35
+ const value = numberOf(n.badges?.[badge]);
36
+ if (value !== undefined) params[key] = value;
37
+ }
38
+ out.push(finding(GOD_MODULE_KIND, n.pack, [n.ref], 'warn', {
39
+ ...params,
40
+ linesLimit: GOD_MODULE_LIMITS.lines,
41
+ exportsLimit: GOD_MODULE_LIMITS.exports,
42
+ complexityLimit: GOD_MODULE_LIMITS.complexity,
43
+ }));
44
+ }
45
+ return out;
46
+ }
@@ -34,6 +34,8 @@ export type { LanedTrace, TraceOptions } from './trace.js';
34
34
  export {
35
35
  computeFindings, genericFindings, finding, findingId, partitionSeverity, requestKeyFor, components, CLONE_GROUP_BADGE, MAX_FINDING_NODES,
36
36
  } from './findings.js';
37
+ export { GOD_MODULE_LIMITS, GOD_MODULE_KIND, godModuleFindings } from './godModule.js';
38
+ export type { GodModuleLimits } from './godModule.js';
37
39
  export {
38
40
  resolveEntities, knownKeysOf, possibleSameFindings, normalizeKey, entityName, entityKey,
39
41
  } from './resolve.js';
@@ -49,7 +51,7 @@ export { extractFile, extractFileDetailed, knownKeysOfEntities } from './extract
49
51
  export type { ExtractFileArgs, FileExtraction } from './extractFile.js';
50
52
  export { extractJob, jobOf } from './extractJob.js';
51
53
  export type { ExtractJob, ExtractJobResult, ExtractPool } from './extractJob.js';
52
- export { putExtract } from './extractFile.js';
54
+ export { putExtract, putNoExtract } from './extractFile.js';
53
55
  export { createModelLimiter, isRateLimit } from './modelLimiter.js';
54
56
  export type { ModelLimiter } from './modelLimiter.js';
55
57
  export { reasonOf } from './reviewRunModel.js';
@@ -224,6 +224,17 @@ export interface KnowledgeStore {
224
224
  * Only a hint: `getExtracted` stays correct without it, and a failure propagates like any store failure.
225
225
  */
226
226
  preloadExtracted?(hashes: readonly string[]): Promise<void>;
227
+ /**
228
+ * The re-check channel between a replica and the review, through the one store both already share: a replica that
229
+ * is asked for the body of a hash it holds none of calls `markRecheck(hashes)`; the next review reads ONLY the
230
+ * manifest files with those hashes (binary → an explicit `[]`, text → extracted), then `clearRecheck`s them. A store
231
+ * that cannot persist the set keeps it in memory. Optional like the cache methods; a store without them has no channel.
232
+ */
233
+ markRecheck?(hashes: readonly string[]): Promise<void>;
234
+ recheckHashes?(): Promise<string[]>;
235
+ clearRecheck?(hashes: readonly string[]): Promise<void>;
236
+ /** Whether a hash is on the re-check set (a cheap membership test for a store that observes every put). */
237
+ hasRecheck?(hash: string): Promise<boolean>;
227
238
  /**
228
239
  * Runs `work` as one unit of many mutations. Inside it the store may hold persistence back
229
240
  * (a whole-snapshot store would otherwise rewrite everything per mutation); `flush` makes
@@ -41,7 +41,7 @@ describe('BFKP round trip', () => {
41
41
 
42
42
  it('round-trips awkward numbers exactly', async () => {
43
43
  const g = genPack(1, { files: 1 });
44
- g.facts = [0, 1, 0.5, 1e-9, 0.1234567, 2 ** 40, 1e15 + 0.5, 123456789.123456789].map((importance, i) => ({
44
+ g.facts = [0, 1, 0.5, 1e-9, 0.1234567, 2 ** 40, 1e15 + 0.5, 123456789.12345679].map((importance, i) => ({
45
45
  key: `k${i}`, content: 'c', source: 's', importance, origin: 'model' as const, fileAnchors: [],
46
46
  }));
47
47
  const back = await decodePack(await encodePack(g));
@@ -31,7 +31,8 @@ import type { ReviewArgs, ReviewReport, ScopeRecord, StoredFact, StoredRelation
31
31
  import { owedAfterRun, owedCalls, saveExtractorState } from './owedFiles.js';
32
32
  import { planDetail, refreshPlan } from './plan.js';
33
33
  import { composePacks, filesManifestKey, judgedManifestKey, manifestMap, saveManifestMap } from './sources.js';
34
- import { knownKeysOfEntities, putExtract } from './extractFile.js';
34
+ import { knownKeysOfEntities, putExtract, putNoExtract } from './extractFile.js';
35
+ import { backfillCandidates, backfillNoExtract } from './backfillNoExtract.js';
35
36
  import { prefetchOrdered } from './orderedPool.js';
36
37
  import {
37
38
  DEFAULT_REVIEW_CONCURRENCY, DEFAULT_REVIEW_JUDGE_CONCURRENCY, DEFAULT_REVIEW_MODEL_CALLS, JUDGE_CONCURRENCY, JudgedBatch,
@@ -118,6 +119,16 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
118
119
  const judgedPrior = await manifestMap(manifest, judgedManifestKey(rootId));
119
120
  const judgedNow = new Map(judgedPrior);
120
121
  const filesNow = new Map(detail.prior);
122
+ // A root reviewed before binary files were recorded: settle files with no body: binary-by-extension ones (no read), and the ones a replica asked to re-check.
123
+ const asked = (await store.recheckHashes?.()) ?? [];
124
+ // 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.
125
+ const preChanged = detail.files.filter((f) => f.changed && (!args.only || args.only.includes(f.path)));
126
+ const preload = [...new Set([...preChanged.map((f) => f.hash), ...backfillCandidates(detail, asked)])];
127
+ if (preload.length > 0) await store.preloadExtracted?.(preload);
128
+ await backfillNoExtract({ store, source, detail, asked, only: args.only, signal });
129
+ // 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.
130
+ const askedSet = new Set(asked);
131
+ const settledRecheck = async (hash: string): Promise<void> => { if (askedSet.has(hash)) await store.clearRecheck?.([hash]); };
121
132
  // Claims awaiting comparison: those a previous run could not compare, then this run's.
122
133
  const newClaims = await pendingClaims(manifest, rootId, stored.facts);
123
134
 
@@ -161,9 +172,6 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
161
172
  // at the model calls it still costs where this run could measure that (see owedFiles.ts).
162
173
  const finished = new Set<string>();
163
174
  const measured = new Map<string, number>();
164
- // One bulk fetch of the extract cache for the whole run instead of a round trip per file.
165
- const hashes = [...new Set(work.map((f) => f.hash))];
166
- if (hashes.length > 0) await store.preloadExtracted?.(hashes);
167
175
  // Read + binary check + extract run ahead with bounded concurrency (extraction only reads `knownKeys`,
168
176
  // fixed above, and the content-hash extract cache); with `args.extractPool` the width is the pool's.
169
177
  // Judging runs `judgeWidth` files at once; ONE writer (`applyFile`) consumes them strictly in plan order.
@@ -203,12 +211,19 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
203
211
  if (job.kind === 'read-error') report.readErrors += 1; else report.extractErrors += 1;
204
212
  fail(f.path, 'extract', job.kind === 'read-error' ? `read: ${job.reason}` : job.reason);
205
213
  measured.set(f.path, owedCalls(detail.extractor, f.path)); // learns nothing: keep what it was owed
214
+ // The manifest keeps the file at its old hash, which is what a replica syncs: if no body is stored for it, say so once (a terminal
215
+ // answer, `[]` = nothing extracted), so the file is not held back and re-asked for forever. A later successful read replaces it.
216
+ // (`[]` rather than a sibling "failed" member: the reason is already in `report.failures`, and a new store member would have no reader.)
217
+ const known = detail.prior.get(f.path);
218
+ if (known) { await putNoExtract(store, known); await settledRecheck(known); }
206
219
  return true;
207
220
  }
208
221
  // Recorded, so a file found binary on read is not re-read by every later review.
209
222
  if (job.kind === 'binary') {
210
223
  filesNow.set(f.path, f.hash);
211
224
  finished.add(f.path);
225
+ await putNoExtract(store, f.hash); // the explicit "nothing extracted", so a replica can tell it from "not extracted yet"
226
+ await settledRecheck(f.hash);
212
227
  await store.markStale(scope, srcRef(rootId, f.path), f.hash);
213
228
  report.staleMarked += 1;
214
229
  return true;
@@ -217,6 +232,7 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
217
232
  report.extracted += 1;
218
233
  // The extract cache is written HERE, in plan order, so the cache, the counts and the order match a sequential run.
219
234
  if (!job.extraction.cached) await putExtract(store, f.hash, job.extraction.extracted);
235
+ await settledRecheck(f.hash);
220
236
  let complete = true;
221
237
  let deferred = false;
222
238
  if (args.mechanical && judgesPack(args.judgement, job.extraction.pack)) {