@seanhogg/builderforce-memory 2026.10.54 → 2026.10.56

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 (57) hide show
  1. package/dist/knowledge/index.d.ts +2 -2
  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/owedFiles.d.ts +2 -1
  6. package/dist/knowledge/owedFiles.d.ts.map +1 -1
  7. package/dist/knowledge/owedFiles.js.map +1 -1
  8. package/dist/knowledge/review.js +3 -2
  9. package/dist/knowledge/review.js.map +1 -1
  10. package/dist/knowledge/reviewFailure.d.ts +4 -2
  11. package/dist/knowledge/reviewFailure.d.ts.map +1 -1
  12. package/dist/knowledge/reviewFailure.js +7 -4
  13. package/dist/knowledge/reviewFailure.js.map +1 -1
  14. package/dist/knowledge/reviewPrefetch.js +1 -1
  15. package/dist/knowledge/reviewPrefetch.js.map +1 -1
  16. package/dist/knowledge/stores/extractLogWriter.d.ts +26 -0
  17. package/dist/knowledge/stores/extractLogWriter.d.ts.map +1 -0
  18. package/dist/knowledge/stores/extractLogWriter.js +60 -0
  19. package/dist/knowledge/stores/extractLogWriter.js.map +1 -0
  20. package/dist/knowledge/stores/localSnapshotStore.d.ts +48 -39
  21. package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
  22. package/dist/knowledge/stores/localSnapshotStore.js +137 -179
  23. package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
  24. package/dist/knowledge/stores/rowDelta.d.ts +97 -0
  25. package/dist/knowledge/stores/rowDelta.d.ts.map +1 -0
  26. package/dist/knowledge/stores/rowDelta.js +141 -0
  27. package/dist/knowledge/stores/rowDelta.js.map +1 -0
  28. package/dist/knowledge/stores/rowMemory.d.ts +31 -0
  29. package/dist/knowledge/stores/rowMemory.d.ts.map +1 -0
  30. package/dist/knowledge/stores/rowMemory.js +85 -0
  31. package/dist/knowledge/stores/rowMemory.js.map +1 -0
  32. package/dist/knowledge/stores/rowSync.d.ts +56 -0
  33. package/dist/knowledge/stores/rowSync.d.ts.map +1 -0
  34. package/dist/knowledge/stores/rowSync.js +119 -0
  35. package/dist/knowledge/stores/rowSync.js.map +1 -0
  36. package/dist/knowledge/stores/snapshotFormat.d.ts +17 -0
  37. package/dist/knowledge/stores/snapshotFormat.d.ts.map +1 -1
  38. package/dist/knowledge/stores/snapshotFormat.js +19 -0
  39. package/dist/knowledge/stores/snapshotFormat.js.map +1 -1
  40. package/package.json +3 -3
  41. package/src/contract/exports.snapshot.json +1 -0
  42. package/src/contract/regression.recheck.test.ts +70 -8
  43. package/src/contract/regression.rows.test.ts +377 -0
  44. package/src/contract/types.contract.test.ts +33 -5
  45. package/src/knowledge/index.ts +4 -2
  46. package/src/knowledge/owedFiles.ts +2 -1
  47. package/src/knowledge/review.ordered.test.ts +7 -3
  48. package/src/knowledge/review.ts +2 -2
  49. package/src/knowledge/reviewFailure.ts +8 -5
  50. package/src/knowledge/reviewPrefetch.ts +1 -1
  51. package/src/knowledge/stores/extractLogWriter.ts +57 -0
  52. package/src/knowledge/stores/localSnapshotStore.ts +138 -168
  53. package/src/knowledge/stores/rowDelta.test.ts +91 -0
  54. package/src/knowledge/stores/rowDelta.ts +166 -0
  55. package/src/knowledge/stores/rowMemory.ts +82 -0
  56. package/src/knowledge/stores/rowSync.ts +118 -0
  57. package/src/knowledge/stores/snapshotFormat.ts +30 -0
@@ -5,11 +5,12 @@
5
5
 
6
6
  import { hashText } from '../ingest/hash.js';
7
7
  import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
8
- import { ExtractFailed, type ExtractPool } from '../knowledge/extractJob.js';
8
+ import { ExtractFailed, extractJob, type ExtractJob, type ExtractPool } from '../knowledge/extractJob.js';
9
+ import { CHANGED_SINCE_PLAN } from '../knowledge/reviewPrefetch.js';
9
10
  import { DOCS_PACK } from '../knowledge/packs/docs.js';
10
11
  import type { KnowledgePack } from '../knowledge/model.js';
11
12
  import { reviewDirectory } from '../knowledge/review.js';
12
- import { filesManifestKey, saveManifestMap } from '../knowledge/sources.js';
13
+ import { extractorManifestKey, filesManifestKey, manifestMap, saveManifestMap } from '../knowledge/sources.js';
13
14
  import { args, memSource, memStore, ROOT, stateOf, type SpySource } from '../knowledge/testkit.test-util.js';
14
15
 
15
16
  describe('regression: a root reviewed before binary files were recorded is settled by its next review, without reading a file', () => {
@@ -159,7 +160,7 @@ describe('regression: a root reviewed before binary files were recorded is settl
159
160
  await expectTransient(legacy, manifest);
160
161
  });
161
162
 
162
- it('regression: an in-thread read that does not match the planned hash (changed since plan) at the same hash is transient', async () => {
163
+ it('guard: an in-thread read that does not match the planned hash (changed since plan) at the same hash is transient', async () => {
163
164
  const manifest = new InMemoryIngestManifest();
164
165
  const legacy = await legacyStore(manifest);
165
166
  const drifting = { ...memSource({ 'a.md': text }), hashOf: () => 'some-other-hash' } as SpySource;
@@ -168,7 +169,7 @@ describe('regression: a root reviewed before binary files were recorded is settl
168
169
  await expectTransient(legacy, manifest);
169
170
  });
170
171
 
171
- it('regression: an extraction past its ceiling (a slow pool under a tiny extractMs) is transient', async () => {
172
+ it('guard: an extraction past its ceiling (a slow pool under a tiny extractMs) is transient', async () => {
172
173
  const manifest = new InMemoryIngestManifest();
173
174
  const legacy = await legacyStore(manifest);
174
175
  const slow: ExtractPool = () => new Promise(() => undefined);
@@ -176,10 +177,11 @@ describe('regression: a root reviewed before binary files were recorded is settl
176
177
  await expectTransient(legacy, manifest);
177
178
  });
178
179
 
179
- it('regression: the third transient failure in a row at the same hash is recorded as final', async () => {
180
+ it('regression: the third transient failure in a row at the same hash is recorded as final, and STICKY: the file is not re-read while its bytes stand', async () => {
180
181
  const manifest = new InMemoryIngestManifest();
181
182
  const legacy = await legacyStore(manifest);
182
- const busy: ExtractPool = async () => { throw new Error('EBUSY'); };
183
+ let calls = 0;
184
+ const busy: ExtractPool = async () => { calls += 1; throw new Error('EBUSY'); };
183
185
  const run = () => reviewDirectory(args(memSource({ 'a.md': text }), legacy, manifest, { extractPool: busy, deferRead: true }));
184
186
  await run();
185
187
  await run();
@@ -187,9 +189,69 @@ describe('regression: a root reviewed before binary files were recorded is settl
187
189
  await run();
188
190
  expect(await legacy.getExtracted(hashText(text))).toEqual([]); // the third: final
189
191
  expect(await legacy.recheckHashes()).toEqual([]);
192
+ const settledAt = calls;
193
+ const report = await run();
194
+ expect(calls).toBe(settledAt); // sticky: not re-read ...
195
+ expect(report.failures).toEqual([]); // ... and not reported failed again
196
+ expect((await stateOf(manifest)).owed).toEqual([]);
197
+ });
198
+
199
+ it('regression: a pool that rejects with "changed since plan" is transient (it was terminal before)', async () => {
200
+ const manifest = new InMemoryIngestManifest();
201
+ const legacy = await legacyStore(manifest);
202
+ const drifting: ExtractPool = async () => { throw new Error(CHANGED_SINCE_PLAN); };
203
+ await reviewDirectory(args(memSource({ 'a.md': text }), legacy, manifest, { extractPool: drifting, deferRead: true }));
204
+ await expectTransient(legacy, manifest);
205
+ });
206
+
207
+ it('regression: the failure count resets on a success: fail, fail, succeed, then fail, fail is still transient and `fail:a.md` is gone after the success', async () => {
208
+ const manifest = new InMemoryIngestManifest();
209
+ const source = memSource({ 'a.md': text });
210
+ await reviewDirectory(args(source, memStore(), manifest));
211
+ const busy: ExtractPool = async () => { throw new Error('EBUSY'); };
212
+ const reading: ExtractPool = async (job) => extractJob({ ...job, doc: await source.read(job.path) } as ExtractJob, [DOCS_PACK]);
213
+ const failIds = async () => ((await manifest.get(extractorManifestKey(ROOT))) ?? []).map((f) => f.id).filter((id) => id.startsWith('fail:'));
214
+ const withPool = (store: ReturnType<typeof memStore>, pool: ExtractPool, extra = {}) =>
215
+ reviewDirectory(args(source, store, manifest, { extractPool: pool, deferRead: true, ...extra }));
216
+ await withPool(memStore(), busy, { force: true });
217
+ await withPool(memStore(), busy, { force: true });
218
+ expect(await failIds()).toEqual(['fail:a.md']);
219
+ await withPool(memStore(), reading, { force: true }); // a success
220
+ expect(await failIds()).toEqual([]);
221
+ const last = memStore();
222
+ await withPool(last, busy, { force: true });
223
+ await withPool(last, busy, { force: true });
224
+ expect(await last.getExtracted(hashText(text))).toBeUndefined(); // two since the success: not final (it would be the fourth without the reset)
225
+ expect((await stateOf(manifest)).owed).toContain('a.md');
226
+ });
227
+
228
+ it('regression: two paths share a hash; the unchanged one stays readable content, so a final failure of the other stores no [] under it and the request stays asked', async () => {
229
+ const manifest = new InMemoryIngestManifest();
230
+ await reviewDirectory(args(memSource({ 'x.md': text, 'y.md': text }), memStore(), manifest)); // both at hash H
231
+ const legacy = memStore();
232
+ await legacy.markRecheck([hashText(text)]);
233
+ const inner = memSource({ 'x.md': text, 'y.md': '# Y\nchanged\n' });
234
+ const source = { ...inner, read: async (p: string) => { if (p === 'y.md') throw new Error('EBUSY'); return inner.read(p); } } as SpySource;
235
+ await reviewDirectory(args(source, legacy, manifest, { only: ['y.md'] })); // y.md moved off H and cannot be read
236
+ expect(await legacy.getExtracted(hashText(text))).toBeUndefined();
237
+ expect(await legacy.recheckHashes()).toEqual([hashText(text)]);
238
+ });
239
+
240
+ it('regression: a Stop that lands during the LAST file still applies it, but retires nothing, runs no analyzers and stamps no digest', async () => {
241
+ const manifest = new InMemoryIngestManifest();
242
+ const store = memStore();
243
+ await reviewDirectory(args(memSource({ 'a.md': text, 'gone.md': '# G\nbye\n' }), store, manifest));
244
+ const stamped = (await store.scopes()).find((s) => s.rootId === ROOT)!.lastDigest;
245
+ const stop = new AbortController();
246
+ const report = await reviewDirectory(args(memSource({ 'a.md': '# A\nedited\n' }), store, manifest, {
247
+ signal: stop.signal, onProgress: (p) => { if (p.phase === 'write') stop.abort(); },
248
+ }));
249
+ expect(report.aborted).toBe(true);
250
+ expect([...(await manifestMap(manifest, filesManifestKey(ROOT))).keys()]).toContain('gone.md'); // not retired
251
+ expect((await store.scopes()).find((s) => s.rootId === ROOT)!.lastDigest).toBe(stamped);
190
252
  });
191
253
 
192
- it('regression: a forced review whose read fails keeps the request (the backfill does not clear a changed file\'s hash)', async () => {
254
+ it('guard: a forced review whose read fails keeps the request (the backfill does not clear a changed file\'s hash)', async () => {
193
255
  const manifest = new InMemoryIngestManifest();
194
256
  const legacy = await legacyStore(manifest);
195
257
  const failing = { ...memSource({ 'a.md': text }), read: async () => { throw new Error('EBUSY'); } } as SpySource;
@@ -197,7 +259,7 @@ describe('regression: a root reviewed before binary files were recorded is settl
197
259
  expect(await legacy.recheckHashes()).toEqual([hashText(text)]);
198
260
  });
199
261
 
200
- it('regression: a file the packs accept at plan time but not once read (job "none") is recorded as nothing-to-extract and its request is answered', async () => {
262
+ it('guard: a file the packs accept at plan time but not once read (job "none") is recorded as nothing-to-extract and its request is answered', async () => {
201
263
  const picky: KnowledgePack = { ...DOCS_PACK, parsers: [{ ...DOCS_PACK.parsers[0]!, accepts: (s) => s.content.kind === 'text' && s.content.text === '' }] };
202
264
  const manifest = new InMemoryIngestManifest();
203
265
  await reviewDirectory(args(memSource({ 'a.md': text }), memStore(), manifest, { packs: [picky] }));
@@ -0,0 +1,377 @@
1
+ /**
2
+ * src/contract/regression.rows.test.ts — the row-persisted LocalSnapshotStore (PRD 41 B4, G03), each invariant pinned by one
3
+ * test named `regression: <what broke>`. The host here is a fake `RowPersistence`: a map-backed "database" that records every
4
+ * change it is given and can be held, failed, told another writer changed it, or made to return `reloaded`.
5
+ */
6
+
7
+ import type { Extracted, NodeRef, ScopeRecord, StoredFact, StoredRelation } from '../knowledge/model.js';
8
+ import { canonicalDump, LocalSnapshotStore, type KnowledgeSnapshot, type RowChange, type RowPersistence } from '../knowledge/stores/localSnapshotStore.js';
9
+ import { memPersistence } from '../knowledge/testkit.test-util.js';
10
+
11
+ const SCOPE: ScopeRecord = { rootId: 'a', title: 'A', packs: ['docs'] };
12
+ const fact = (key: string, content = 'c'): StoredFact => ({ key, content, source: 's', importance: 0.5, origin: 'model', fileAnchors: [] });
13
+ const rel = (from: string, to: string, kind: string): StoredRelation => ({ from: from as NodeRef, to: to as NodeRef, kind, weight: 1, origin: 'model', sourceHash: 'h1' });
14
+ const ex = (name: string) => [{ name }] as unknown as Extracted[];
15
+ const deferred = () => { let resolve!: () => void; const promise = new Promise<void>((r) => { resolve = r; }); return { promise, resolve }; };
16
+ const settle = async () => { for (let i = 0; i < 5; i++) await new Promise((r) => setImmediate(r)); };
17
+
18
+ interface Db {
19
+ scopes: Map<string, ScopeRecord>;
20
+ facts: Map<string, StoredFact>;
21
+ relations: Map<string, StoredRelation>;
22
+ extracted: Map<string, Extracted[]>;
23
+ recheck: Set<string>;
24
+ }
25
+
26
+ interface FakeRows extends RowPersistence {
27
+ db: Db;
28
+ applies: RowChange[];
29
+ generation: number;
30
+ loads: number;
31
+ checks: number;
32
+ bodyReads: string[];
33
+ /** Holds every `apply` (after recording it) until resolved. */
34
+ hold?: ReturnType<typeof deferred>;
35
+ failNext: number;
36
+ /** Another writer's change: run after an apply merged, its result is returned as `reloaded`. */
37
+ reload?: () => KnowledgeSnapshot;
38
+ /** `changedElsewhere` answers true once. */
39
+ changed: boolean;
40
+ /** `load` leaves extract bodies out (they load lazily). */
41
+ lazyBodies: boolean;
42
+ }
43
+
44
+ const fkey = (root: string, key: string) => `${root}\u0000${key}`;
45
+ const rkey = (root: string, from: string, to: string, kind: string) => `${root}\u0000${from}\u0000${to}\u0000${kind}`;
46
+
47
+ function snapshotOf(db: Db, withExtracted = true): KnowledgeSnapshot {
48
+ const facts: Record<string, StoredFact[]> = {};
49
+ const relations: Record<string, StoredRelation[]> = {};
50
+ for (const [k, f] of db.facts) (facts[k.split('\u0000')[0]!] ??= []).push(f);
51
+ for (const [k, r] of db.relations) (relations[k.split('\u0000')[0]!] ??= []).push(r);
52
+ return {
53
+ version: 1, scopes: [...db.scopes.values()], facts, relations,
54
+ ...(withExtracted ? { extracted: Object.fromEntries(db.extracted) } : {}),
55
+ ...(db.recheck.size ? { recheck: [...db.recheck] } : {}),
56
+ };
57
+ }
58
+
59
+ function fakeRows(): FakeRows {
60
+ const db: Db = { scopes: new Map(), facts: new Map(), relations: new Map(), extracted: new Map(), recheck: new Set() };
61
+ const f: FakeRows = {
62
+ db, applies: [], generation: 0, loads: 0, checks: 0, bodyReads: [], failNext: 0, changed: false, lazyBodies: false,
63
+ async load() { f.loads += 1; return snapshotOf(db, !f.lazyBodies); },
64
+ async apply(change) {
65
+ f.applies.push(change);
66
+ if (f.hold) await f.hold.promise;
67
+ if (f.failNext > 0) { f.failNext -= 1; throw new Error('disk full'); }
68
+ const { upserts: u, deletes: d } = change;
69
+ for (const s of u.scopes) db.scopes.set(s.rootId, s);
70
+ for (const [root, x] of u.facts) db.facts.set(fkey(root, x.key), x);
71
+ for (const [root, r] of u.relations) db.relations.set(rkey(root, r.from, r.to, r.kind), r);
72
+ for (const [h, e] of u.extracted) db.extracted.set(h, e);
73
+ for (const h of u.recheck) db.recheck.add(h);
74
+ for (const id of d.scopes) db.scopes.delete(id);
75
+ for (const [root, key] of d.facts) db.facts.delete(fkey(root, key));
76
+ for (const [root, from, to, kind] of d.relations) db.relations.delete(rkey(root, from, to, kind));
77
+ for (const h of d.extracted) db.extracted.delete(h);
78
+ for (const h of d.recheck) db.recheck.delete(h);
79
+ f.generation += 1;
80
+ const reload = f.reload;
81
+ f.reload = undefined;
82
+ return { generation: f.generation, ...(reload ? { reloaded: reload() } : {}) };
83
+ },
84
+ async loadAllExtracted() { return Object.fromEntries(db.extracted); },
85
+ async loadExtracted(hash) { f.bodyReads.push(hash); return db.extracted.get(hash); },
86
+ async changedElsewhere() { f.checks += 1; const c = f.changed; f.changed = false; return c; },
87
+ };
88
+ return f;
89
+ }
90
+
91
+
92
+ const rowStore = (rows: RowPersistence) => new LocalSnapshotStore(undefined, { rows, now: () => 'T' });
93
+ const loadedFrom = (snap: KnowledgeSnapshot) => {
94
+ const p = memPersistence();
95
+ p.value = JSON.stringify(snap);
96
+ return new LocalSnapshotStore(p, { now: () => 'T' });
97
+ };
98
+
99
+ function prng(seed: number): () => number {
100
+ return () => {
101
+ seed = (seed + 0x6d2b79f5) | 0;
102
+ let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
103
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
104
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
105
+ };
106
+ }
107
+
108
+ /** The seeded op sequence both kinds of store run: facts, relations, scopes, extracted, recheck (with clears), stale marks, reads, some inside `batched`. */
109
+ async function driveOps(store: LocalSnapshotStore, seed: number, steps: number, between?: (rand: () => number, pick: (n: number) => number) => void): Promise<void> {
110
+ const rand = prng(seed);
111
+ const pick = (n: number) => Math.floor(rand() * n);
112
+ const op = async () => {
113
+ const kind = pick(8);
114
+ if (kind <= 2) {
115
+ await store.write({
116
+ scope: { ...SCOPE, ...(rand() < 0.5 ? { lastDigest: `d${pick(9)}` } : {}) },
117
+ facts: Array.from({ length: pick(4) }, () => fact(`claim:k${pick(6)}`, `v${pick(99)}`)),
118
+ relations: Array.from({ length: pick(3) }, () => rel(`fact:claim:k${pick(6)}`, `src:a::f${pick(4)}.md#s`, ['about', 'mentions'][pick(2)]!)),
119
+ });
120
+ } else if (kind === 3) await store.markStale({ rootId: 'a' }, `src:a::f${pick(4)}.md#s` as NodeRef, `h${pick(3)}`);
121
+ else if (kind === 4) await store.putExtracted(`x${pick(8)}`, ex(`e${pick(5)}`));
122
+ else if (kind === 5) await store.markRecheck([`h${pick(5)}`, `h${pick(5)}`]);
123
+ else if (kind === 6) await store.clearRecheck([`h${pick(5)}`]);
124
+ else await store.facts({ rootId: 'a' });
125
+ };
126
+ for (let i = 0; i < steps; i++) {
127
+ between?.(rand, pick);
128
+ try {
129
+ if (rand() < 0.3) await store.batched(async () => { for (let j = 0; j < 5; j++) await op(); });
130
+ else await op();
131
+ } catch (err) {
132
+ if (!between) throw err; // only the fuzz injects failures
133
+ }
134
+ }
135
+ }
136
+
137
+ const sameAsHost = async (store: LocalSnapshotStore, rows: FakeRows) => expect(await canonicalDump(store)).toBe(await canonicalDump(loadedFrom(snapshotOf(rows.db))));
138
+
139
+ describe('regression: row persistence', () => {
140
+ it('regression: after N random mutations the rows the host accumulated equal the canonical dump', async () => {
141
+ const rows = fakeRows();
142
+ const store = rowStore(rows);
143
+ await driveOps(store, 20261108, 90);
144
+ const dump = await canonicalDump(store);
145
+ expect(dump).toContain('"facts"');
146
+ expect(dump).toContain('"recheck"');
147
+ await sameAsHost(store, rows); // the accumulated rows
148
+ expect(await canonicalDump(rowStore(rows))).toBe(dump); // and a second store loading them
149
+ });
150
+
151
+ it('regression: parity oracle: the same op sequence on a snapshot-persisted store and a row store gives byte-equal dumps', async () => {
152
+ for (const seed of [1, 2, 3]) {
153
+ const classic = new LocalSnapshotStore(memPersistence(), { now: () => 'T' });
154
+ const rowed = rowStore(fakeRows());
155
+ await driveOps(classic, seed, 60);
156
+ await driveOps(rowed, seed, 60);
157
+ expect(await canonicalDump(rowed)).toBe(await canonicalDump(classic));
158
+ }
159
+ });
160
+
161
+ it('regression: fuzz: failed applies, `reloaded` and another writer changing the store, interleaved with the ops, never lose or reorder this window\'s rows', async () => {
162
+ for (const seed of [11, 12, 13, 14]) {
163
+ const rows = fakeRows();
164
+ const store = rowStore(rows);
165
+ let other = 0;
166
+ const theirs = () => { const key = `claim:o${other++}`; rows.db.facts.set(fkey('b', key), fact(key)); };
167
+ await driveOps(store, seed, 80, (rand) => {
168
+ const r = rand();
169
+ if (r < 0.15) rows.failNext = 1;
170
+ else if (r < 0.3) rows.reload = () => { theirs(); return snapshotOf(rows.db); };
171
+ else if (r < 0.45) { theirs(); rows.changed = true; }
172
+ });
173
+ rows.failNext = 0;
174
+ rows.reload = undefined;
175
+ await store.write({ scope: SCOPE, facts: [], relations: [] }); // flush whatever a failure left marked
176
+ rows.changed = true;
177
+ await store.scopes(); // pick up the other writer's last change
178
+ await sameAsHost(store, rows);
179
+ }
180
+ });
181
+
182
+ it('regression: a changed-elsewhere read that races an apply cannot drop the rows that apply commits', async () => {
183
+ const rows = fakeRows();
184
+ const store = rowStore(rows);
185
+ await store.facts({ rootId: 'a' });
186
+ rows.hold = deferred();
187
+ const write = store.write({ scope: SCOPE, facts: [fact('claim:mine')], relations: [] });
188
+ await settle();
189
+ rows.db.facts.set(fkey('b', 'claim:theirs'), fact('claim:theirs'));
190
+ rows.changed = true;
191
+ const read = store.facts({ rootId: 'b' });
192
+ await settle();
193
+ rows.hold.resolve();
194
+ await Promise.all([write, read]);
195
+ await store.scopes();
196
+ expect((await store.facts({ rootId: 'a' })).map((x) => x.key)).toEqual(['claim:mine']);
197
+ expect((await store.facts({ rootId: 'b' })).map((x) => x.key)).toEqual(['claim:theirs']);
198
+ await sameAsHost(store, rows);
199
+ });
200
+
201
+ it('regression: a read during a held apply resolves without waiting for it', async () => {
202
+ const rows = fakeRows();
203
+ const store = rowStore(rows);
204
+ await store.facts({ rootId: 'a' });
205
+ rows.checks = 0;
206
+ rows.hold = deferred();
207
+ const write = store.write({ scope: SCOPE, facts: [fact('claim:1')], relations: [] });
208
+ await settle();
209
+ rows.changed = true;
210
+ expect((await store.facts({ rootId: 'a' })).map((x) => x.key)).toEqual(['claim:1']); // resolves while the apply is held
211
+ expect(rows.checks).toBe(0); // no check was made behind the apply
212
+ rows.hold.resolve();
213
+ await write;
214
+ });
215
+
216
+ it('regression: a reload arriving while a failed apply is restored keeps the restored rows, and the next apply persists them', async () => {
217
+ const rows = fakeRows();
218
+ const store = rowStore(rows);
219
+ await store.facts({ rootId: 'a' });
220
+ rows.hold = deferred();
221
+ rows.failNext = 1;
222
+ const write = store.write({ scope: SCOPE, facts: [fact('claim:mine')], relations: [] });
223
+ await settle();
224
+ rows.db.facts.set(fkey('b', 'claim:theirs'), fact('claim:theirs'));
225
+ rows.changed = true;
226
+ const read = store.facts({ rootId: 'b' });
227
+ expect(await read).toEqual([]); // answered from memory while the apply was in flight
228
+ rows.hold.resolve();
229
+ await expect(write).rejects.toThrow('disk full');
230
+ expect((await store.facts({ rootId: 'b' })).map((x) => x.key)).toEqual(['claim:theirs']); // the next read reloads
231
+ expect((await store.facts({ rootId: 'a' })).map((x) => x.key)).toEqual(['claim:mine']); // restored marks survived the reload
232
+ await store.markRecheck(['x']);
233
+ expect(rows.db.facts.has(fkey('a', 'claim:mine'))).toBe(true);
234
+ await sameAsHost(store, rows);
235
+ });
236
+
237
+ it('regression: a dump or extractedEntries with lazy bodies reads them all through loadAllExtracted, and throws without it', async () => {
238
+ const rows = fakeRows();
239
+ rows.lazyBodies = true;
240
+ rows.db.extracted.set('h9', ex('nine'));
241
+ const store = rowStore(rows);
242
+ await store.putExtracted('mem', ex('m'));
243
+ expect(Object.keys(await store.extractedEntries()).sort()).toEqual(['h9', 'mem']);
244
+ expect(await canonicalDump(store)).toContain('"h9"');
245
+
246
+ const bare = fakeRows();
247
+ delete bare.loadAllExtracted;
248
+ const partial = rowStore(bare);
249
+ await expect(partial.extractedEntries()).rejects.toThrow('knowledge_dump_needs_all_bodies');
250
+ await expect(canonicalDump(partial)).rejects.toThrow('knowledge_dump_needs_all_bodies');
251
+ });
252
+
253
+ it('regression: preloadExtracted reads the missing bodies once; a miss is remembered until the hash is put', async () => {
254
+ const rows = fakeRows();
255
+ rows.lazyBodies = true;
256
+ for (const h of ['h1', 'h2']) rows.db.extracted.set(h, ex(h));
257
+ const store = rowStore(rows);
258
+ await store.preloadExtracted(['h1', 'h2', 'h1', 'zz']);
259
+ expect([...rows.bodyReads].sort()).toEqual(['h1', 'h2', 'zz']);
260
+ expect(await store.getExtracted('h2')).toEqual(ex('h2'));
261
+ expect(await store.getExtracted('zz')).toBeUndefined();
262
+ expect(rows.bodyReads).toHaveLength(3); // nothing read again
263
+ await store.putExtracted('zz', ex('z'));
264
+ expect(await store.getExtracted('zz')).toEqual(ex('z'));
265
+ });
266
+
267
+ it('regression: a mutation made while apply is pending is persisted by the next apply', async () => {
268
+ const rows = fakeRows();
269
+ const store = rowStore(rows);
270
+ rows.hold = deferred();
271
+ const first = store.write({ scope: SCOPE, facts: [fact('claim:1')], relations: [] });
272
+ await settle();
273
+ expect(rows.applies).toHaveLength(1);
274
+ const second = store.write({ scope: SCOPE, facts: [fact('claim:2')], relations: [] });
275
+ await settle();
276
+ rows.hold.resolve();
277
+ await Promise.all([first, second]);
278
+ expect(rows.applies).toHaveLength(2);
279
+ expect(rows.applies[0]!.upserts.facts.map(([, x]) => x.key)).toEqual(['claim:1']);
280
+ expect(rows.applies[1]!.upserts.facts.map(([, x]) => x.key)).toEqual(['claim:2']);
281
+ expect([...rows.db.facts.values()].map((x) => x.key).sort()).toEqual(['claim:1', 'claim:2']);
282
+ });
283
+
284
+ it('regression: a rejected apply loses nothing: the retry persists the failed rows with the newer value of a row marked since', async () => {
285
+ const rows = fakeRows();
286
+ const store = rowStore(rows);
287
+ rows.failNext = 1;
288
+ await expect(store.write({ scope: SCOPE, facts: [fact('claim:1', 'old'), fact('claim:2')], relations: [rel('fact:claim:1', 'src:a::f.md#s', 'about')] })).rejects.toThrow('disk full');
289
+ expect(rows.db.facts.size).toBe(0);
290
+ await store.markRecheck(['h1']); // a later mutation: persists, and carries the failed rows with it
291
+ await store.write({ scope: SCOPE, facts: [fact('claim:1', 'new')], relations: [] });
292
+ expect([...rows.db.facts.values()].map((x) => [x.key, x.content]).sort()).toEqual([['claim:1', 'new'], ['claim:2', 'c']]);
293
+ expect(rows.db.relations.size).toBe(1);
294
+ expect(rows.db.scopes.has('a')).toBe(true);
295
+ expect([...rows.db.recheck]).toEqual(['h1']);
296
+ expect(await canonicalDump(loadedFrom(snapshotOf(rows.db)))).toBe(await canonicalDump(store));
297
+ });
298
+
299
+ it('regression: recheck survives a reload', async () => {
300
+ const rows = fakeRows();
301
+ const store = rowStore(rows);
302
+ await store.markRecheck(['h2', 'h1', 'h3']);
303
+ await store.clearRecheck(['h2']);
304
+ expect(rows.applies.at(-1)!.deletes.recheck).toEqual(['h2']);
305
+ expect(await rowStore(rows).recheckHashes()).toEqual(['h1', 'h3']);
306
+ });
307
+
308
+ it('regression: `reloaded` replaces memory, and a mark made while apply was pending survives in memory and is persisted next', async () => {
309
+ const rows = fakeRows();
310
+ const store = rowStore(rows);
311
+ await store.write({ scope: SCOPE, facts: [fact('claim:gone')], relations: [] });
312
+ rows.hold = deferred();
313
+ // Another window: deletes `claim:gone`, adds `claim:other`. Its rows come back with this window's apply.
314
+ rows.reload = () => { rows.db.facts.delete(fkey('a', 'claim:gone')); rows.db.facts.set(fkey('a', 'claim:other'), fact('claim:other')); return snapshotOf(rows.db); };
315
+ const first = store.write({ scope: SCOPE, facts: [fact('claim:1')], relations: [] });
316
+ await settle();
317
+ const second = store.write({ scope: SCOPE, facts: [fact('claim:2')], relations: [] }); // marked during the apply
318
+ await settle();
319
+ rows.hold.resolve();
320
+ await Promise.all([first, second]);
321
+ const keys = (await store.facts({ rootId: 'a' })).map((x) => x.key).sort();
322
+ expect(keys).toEqual(['claim:1', 'claim:2', 'claim:other']); // replaced (gone is gone, other is here), claim:2 not lost
323
+ expect(rows.applies.at(-1)!.upserts.facts.map(([, x]) => x.key)).toEqual(['claim:2']);
324
+ expect([...rows.db.facts.values()].map((x) => x.key).sort()).toEqual(keys);
325
+ });
326
+
327
+ it('regression: `reloaded` rebuilds the relations-by-path index, so markStale finds a relation another window wrote', async () => {
328
+ const rows = fakeRows();
329
+ const store = rowStore(rows);
330
+ rows.reload = () => { rows.db.relations.set(rkey('a', 'fact:claim:9', 'src:a::z.md#s', 'about'), rel('fact:claim:9', 'src:a::z.md#s', 'about')); return snapshotOf(rows.db); };
331
+ await store.write({ scope: SCOPE, facts: [], relations: [] });
332
+ await store.markStale({ rootId: 'a' }, 'src:a::z.md#s', 'other-hash');
333
+ expect((await store.relations({ rootId: 'a' }))[0]!.staleAt).toBe('T');
334
+ });
335
+
336
+ it('regression: when another writer changed the store, a read reloads first (one check in flight, none inside a batch)', async () => {
337
+ const rows = fakeRows();
338
+ const store = rowStore(rows);
339
+ await store.facts({ rootId: 'a' });
340
+ rows.checks = 0;
341
+ rows.db.facts.set(fkey('a', 'claim:theirs'), fact('claim:theirs'));
342
+ rows.changed = true;
343
+ const reads = await Promise.all([1, 2, 3, 4, 5].map(() => store.facts({ rootId: 'a' })));
344
+ expect(rows.checks).toBe(1);
345
+ expect(reads.every((r) => r.map((x) => x.key).join() === 'claim:theirs')).toBe(true);
346
+
347
+ rows.db.facts.set(fkey('a', 'claim:later'), fact('claim:later'));
348
+ rows.changed = true;
349
+ rows.checks = 0;
350
+ await store.batched(async () => { expect((await store.facts({ rootId: 'a' })).map((x) => x.key)).toEqual(['claim:theirs']); });
351
+ expect(rows.checks).toBe(0);
352
+ expect((await store.facts({ rootId: 'a' })).map((x) => x.key).sort()).toEqual(['claim:later', 'claim:theirs']); // the next read outside the batch sees it
353
+ });
354
+
355
+ it('regression: an extract body missing from memory is read through loadExtracted once, and kept', async () => {
356
+ const rows = fakeRows();
357
+ rows.lazyBodies = true;
358
+ rows.db.extracted.set('h9', ex('nine'));
359
+ const store = rowStore(rows);
360
+ expect(await store.getExtracted('h9')).toEqual(ex('nine'));
361
+ expect(await store.getExtracted('h9')).toEqual(ex('nine'));
362
+ expect(await store.getExtracted('nope')).toBeUndefined();
363
+ expect(rows.bodyReads).toEqual(['h9', 'nope']);
364
+ await store.putExtracted('h9', ex('nine')); // the same body: no row written
365
+ expect(rows.applies).toHaveLength(0);
366
+ });
367
+
368
+ it('regression: without rows the store writes the same bytes as the dump, and needs one of the two ports', async () => {
369
+ const p = memPersistence();
370
+ const store = new LocalSnapshotStore(p, { now: () => 'T' });
371
+ await store.write({ scope: SCOPE, facts: [fact('claim:1')], relations: [rel('fact:claim:1', 'src:a::f.md#s', 'about')] });
372
+ await store.putExtracted('h1', ex('one'));
373
+ await store.markRecheck(['h1']);
374
+ expect(await canonicalDump(store)).toBe(p.value);
375
+ expect(() => new (LocalSnapshotStore as unknown as new (p: undefined, o: object) => unknown)(undefined, {})).toThrow();
376
+ });
377
+ });
@@ -16,8 +16,9 @@ import type {
16
16
  Extracted, ExtractJob, ExtractJobResult, GraphApp, GraphOutline, GraphReadSkip, GraphSystem, KEdge, KNode, KnowledgeGraph, KnowledgeStore,
17
17
  OutlineFile, ReviewFailure, ReviewFailureChunks, ReviewPhase, ReviewReport, ReviewRun, ReviewRunPhase, ReviewStep, ScopeRecord,
18
18
  StoredFact, StoredRelation, ExtractedLogPersistence, KnowledgeSnapshot, LocalSnapshotStoreOptions, SnapshotPersistence,
19
+ RowChange, RowPersistence,
19
20
  } from '../knowledge/index.js';
20
- import { ExtractFailed, failuresOf, failureTotal, LocalSnapshotStore, localSnapshotStore } from '../knowledge/index.js';
21
+ import { canonicalDump, ExtractFailed, failuresOf, failureTotal, LocalSnapshotStore, localSnapshotStore, type ExtractorState } from '../knowledge/index.js';
21
22
 
22
23
  type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
23
24
  type Expect<T extends true> = T;
@@ -89,7 +90,11 @@ export const jobWithNeither: ExtractJob = { ...base };
89
90
  export type ExtractJob_readByPool_shape = Expect<Equal<NonNullable<Extract<ExtractJob, { readByPool: unknown }>['readByPool']>, { path: string; hash: string }>>;
90
91
  export const resultShape = { binary: true, extracted: [anExtract], sections: someSections } satisfies ExtractJobResult;
91
92
  export type ExtractJobResult_fields = Expect<Equal<ExtractJobResult, { binary?: true; extracted: Extracted[]; sections?: ParsedSection[] }>>;
92
- // ExtractFailed: the marker of a PROVEN-final extraction failure (the parser or extractor threw); every other failure is transient.export type ExtractFailed_is_an_Error = Expect<Equal<InstanceType<typeof ExtractFailed> extends Error ? true : false, true>>;export type ExtractFailed_constructor = Expect<Equal<ConstructorParameters<typeof ExtractFailed>, [message: string, options?: { cause?: unknown }]>>;
93
+ // ExtractFailed: the marker of a PROVEN-final extraction failure (the parser or extractor threw); every other failure is transient.
94
+ export type ExtractFailed_is_an_Error = Expect<Equal<InstanceType<typeof ExtractFailed> extends Error ? true : false, true>>;
95
+ export type ExtractFailed_constructor = Expect<Equal<ConstructorParameters<typeof ExtractFailed>, [message: string, options?: { cause?: unknown }]>>;
96
+ // ExtractorState.failures: consecutive transient failures by path at one hash; optional so a hand-built state stays valid.
97
+ export type ExtractorState_failures = Expect<Equal<ExtractorState['failures'], ReadonlyMap<string, { hash: string; count: number }> | undefined>>;
93
98
 
94
99
  /* ── KnowledgeStore: the port hosts implement ──────────────────────────────────────────────────────────────── */
95
100
  export type KnowledgeStore_methods = Expect<Equal<
@@ -139,14 +144,37 @@ export const batchedHostStore = {
139
144
  export type LocalSnapshotStore_is_a_KnowledgeStore = Expect<Equal<LocalSnapshotStore extends KnowledgeStore ? true : false, true>>;
140
145
  export type LocalSnapshotStore_public_methods = Expect<Equal<
141
146
  keyof LocalSnapshotStore,
142
- 'batched' | 'scopes' | 'facts' | 'relations' | 'write' | 'markStale' | 'getExtracted' | 'extractedEntries' | 'putExtracted' | 'markRecheck' | 'recheckHashes' | 'clearRecheck' | 'hasRecheck'
147
+ 'batched' | 'scopes' | 'facts' | 'relations' | 'write' | 'markStale' | 'getExtracted' | 'extractedEntries' | 'preloadExtracted' | 'putExtracted' | 'markRecheck' | 'recheckHashes' | 'clearRecheck' | 'hasRecheck'
143
148
  >>;
144
149
  export type LocalSnapshotStore_extractedEntries = Expect<Equal<LocalSnapshotStore['extractedEntries'], () => Promise<Record<string, Extracted[]>>>>;
145
150
  export type LocalSnapshotStore_constructor = Expect<Equal<
146
151
  ConstructorParameters<typeof LocalSnapshotStore>, [persistence: SnapshotPersistence, opts?: LocalSnapshotStoreOptions]
147
152
  >>;
148
- export type localSnapshotStore_factory = Expect<Equal<typeof localSnapshotStore, (persistence: SnapshotPersistence, opts?: LocalSnapshotStoreOptions) => LocalSnapshotStore>>;
149
- export type LocalSnapshotStoreOptions_keys = Expect<Equal<keyof LocalSnapshotStoreOptions, 'extractedLog' | 'now' | 'checkpointMs' | 'nowMs'>>;
153
+ // Two overloads: the snapshot-persisted one (the last, so `Parameters` reads it) and the row-persisted one (`undefined` + `opts.rows`).
154
+ export type localSnapshotStore_factory = Expect<Equal<Parameters<typeof localSnapshotStore>, [persistence: SnapshotPersistence, opts?: LocalSnapshotStoreOptions]>>;
155
+ export type localSnapshotStore_factory_returns = Expect<Equal<ReturnType<typeof localSnapshotStore>, LocalSnapshotStore>>;
156
+ export const rowPersistedStore = (rows: RowPersistence): LocalSnapshotStore => localSnapshotStore(undefined, { rows });
157
+ export const rowPersistedStoreByConstructor = (rows: RowPersistence): LocalSnapshotStore => new LocalSnapshotStore(undefined, { rows });
158
+ export const dumpsAStore = (store: LocalSnapshotStore): Promise<string> => canonicalDump(store);
159
+ export type LocalSnapshotStoreOptions_keys = Expect<Equal<keyof LocalSnapshotStoreOptions, 'extractedLog' | 'rows' | 'now' | 'checkpointMs' | 'nowMs'>>;
160
+ export type RowChange_shape = Expect<Equal<RowChange, {
161
+ upserts: {
162
+ scopes: ScopeRecord[]; facts: Array<[rootId: string, fact: StoredFact]>; relations: Array<[rootId: string, relation: StoredRelation]>;
163
+ extracted: Array<[hash: string, entries: Extracted[]]>; recheck: string[];
164
+ };
165
+ deletes: {
166
+ scopes: string[]; facts: Array<[rootId: string, key: string]>;
167
+ relations: Array<[rootId: string, from: string, to: string, kind: string]>;
168
+ extracted: string[]; recheck: string[];
169
+ };
170
+ }>>;
171
+ export type RowPersistence_ports = Expect<Equal<RowPersistence, {
172
+ load(): Promise<KnowledgeSnapshot | undefined>;
173
+ apply(change: RowChange): Promise<{ generation: number; reloaded?: KnowledgeSnapshot }>;
174
+ loadAllExtracted?(): Promise<Record<string, Extracted[]>>;
175
+ loadExtracted?(hash: string): Promise<Extracted[] | undefined>;
176
+ changedElsewhere?(): Promise<boolean>;
177
+ }>>;
150
178
  export type SnapshotPersistence_ports = Expect<Equal<
151
179
  SnapshotPersistence,
152
180
  { read(): Promise<string | undefined>; write(snapshot: string): Promise<void>; keepAside?(text: string): Promise<void> }
@@ -72,8 +72,10 @@ export {
72
72
  } from './refs.js';
73
73
  export { DOCS_PACK, DOCS_PACK_ID, brokenLinkRule, orphanDocumentRule, contradictionRule } from './packs/docs.js';
74
74
  export { frontMatterOf, SECTION_INDEX_BADGE } from '../ingest/docsExtract.js';
75
- export { LocalSnapshotStore, localSnapshotStore } from './stores/localSnapshotStore.js';
76
- export type { SnapshotPersistence, KnowledgeSnapshot, LocalSnapshotStoreOptions, ExtractedLogPersistence } from './stores/localSnapshotStore.js';
75
+ export { LocalSnapshotStore, localSnapshotStore, canonicalDump } from './stores/localSnapshotStore.js';
76
+ export type {
77
+ SnapshotPersistence, KnowledgeSnapshot, LocalSnapshotStoreOptions, ExtractedLogPersistence, RowPersistence, RowChange,
78
+ } from './stores/localSnapshotStore.js';
77
79
 
78
80
  // The knowledge index (search, expand, near-duplicate pairs) ships on the same subpath.
79
81
  export * from '../retrieval/knowledge-index/index.js';
@@ -40,7 +40,8 @@ export interface ExtractorState {
40
40
  version: number | undefined;
41
41
  /** Paths a previous run left unfinished under that version → model calls each still costs. */
42
42
  owed: ReadonlyMap<string, number>;
43
- /** Consecutive transient failures of a path at one content hash (stored beside its owed entry); a success or a new hash resets it. */ failures: ReadonlyMap<string, { hash: string; count: number }>;
43
+ /** Consecutive transient failures of a path at one content hash (stored beside its owed entry); a success or a new hash resets it. Optional: a caller that builds a state by hand need not know it. */
44
+ failures?: ReadonlyMap<string, { hash: string; count: number }>;
44
45
  }
45
46
 
46
47
  export async function loadExtractorState(manifest: IngestManifest, rootId: string): Promise<ExtractorState> {
@@ -78,6 +78,10 @@ async function runTwice(shape: Shape) {
78
78
  return { first, second, inFlight: max };
79
79
  }
80
80
 
81
+ // Each case runs four full reviews of the fixture (two widths, first + incremental); under a
82
+ // parallel jest run that exceeds the 5 s default, so the budget is explicit.
83
+ const ORDERED_REVIEW_TIMEOUT_MS = 30_000;
84
+
81
85
  describe('parallel review, ordered writer', () => {
82
86
  it('stores the same bytes and manifests at 8/4 as at 1/1, on a first and an incremental review', async () => {
83
87
  const wide = await runTwice({ concurrency: 8, judgeConcurrency: 4, modelCalls: 500 });
@@ -90,7 +94,7 @@ describe('parallel review, ordered writer', () => {
90
94
  expect(wide.second.bytes).not.toBe(wide.first.bytes);
91
95
  expect(wide.second.bytes).toBe(narrow.second.bytes);
92
96
  expect(wide.second.manifests).toBe(narrow.second.manifests);
93
- });
97
+ }, ORDERED_REVIEW_TIMEOUT_MS);
94
98
 
95
99
  it('stores the same bytes through an extraction pool at width as in-thread at 1/1', async () => {
96
100
  const pooled = await runTwice({ concurrency: 8, judgeConcurrency: 4, modelCalls: 500, pool: true });
@@ -98,7 +102,7 @@ describe('parallel review, ordered writer', () => {
98
102
  expect(pooled.first.bytes).toBe(narrow.first.bytes);
99
103
  expect(pooled.second.bytes).toBe(narrow.second.bytes);
100
104
  expect(pooled.second.manifests).toBe(narrow.second.manifests);
101
- });
105
+ }, ORDERED_REVIEW_TIMEOUT_MS);
102
106
 
103
107
  it('spends a short model-call budget in plan order whatever the widths', async () => {
104
108
  const wide = await runTwice({ concurrency: 8, judgeConcurrency: 4, modelCalls: 17 });
@@ -110,5 +114,5 @@ describe('parallel review, ordered writer', () => {
110
114
  expect(wide.first.bytes).toBe(narrow.first.bytes);
111
115
  expect(wide.second.bytes).toBe(narrow.second.bytes);
112
116
  expect(wide.second.manifests).toBe(narrow.second.manifests);
113
- });
117
+ }, ORDERED_REVIEW_TIMEOUT_MS);
114
118
  });