@seanhogg/builderforce-memory 2026.10.55 → 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.
- package/dist/knowledge/index.d.ts +2 -2
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +1 -1
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/stores/extractLogWriter.d.ts +26 -0
- package/dist/knowledge/stores/extractLogWriter.d.ts.map +1 -0
- package/dist/knowledge/stores/extractLogWriter.js +60 -0
- package/dist/knowledge/stores/extractLogWriter.js.map +1 -0
- package/dist/knowledge/stores/localSnapshotStore.d.ts +48 -39
- package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.js +137 -179
- package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
- package/dist/knowledge/stores/rowDelta.d.ts +97 -0
- package/dist/knowledge/stores/rowDelta.d.ts.map +1 -0
- package/dist/knowledge/stores/rowDelta.js +141 -0
- package/dist/knowledge/stores/rowDelta.js.map +1 -0
- package/dist/knowledge/stores/rowMemory.d.ts +31 -0
- package/dist/knowledge/stores/rowMemory.d.ts.map +1 -0
- package/dist/knowledge/stores/rowMemory.js +85 -0
- package/dist/knowledge/stores/rowMemory.js.map +1 -0
- package/dist/knowledge/stores/rowSync.d.ts +56 -0
- package/dist/knowledge/stores/rowSync.d.ts.map +1 -0
- package/dist/knowledge/stores/rowSync.js +119 -0
- package/dist/knowledge/stores/rowSync.js.map +1 -0
- package/dist/knowledge/stores/snapshotFormat.d.ts +17 -0
- package/dist/knowledge/stores/snapshotFormat.d.ts.map +1 -1
- package/dist/knowledge/stores/snapshotFormat.js +19 -0
- package/dist/knowledge/stores/snapshotFormat.js.map +1 -1
- package/package.json +3 -3
- package/src/contract/exports.snapshot.json +1 -0
- package/src/contract/regression.rows.test.ts +377 -0
- package/src/contract/types.contract.test.ts +28 -4
- package/src/knowledge/index.ts +4 -2
- package/src/knowledge/stores/extractLogWriter.ts +57 -0
- package/src/knowledge/stores/localSnapshotStore.ts +138 -168
- package/src/knowledge/stores/rowDelta.test.ts +91 -0
- package/src/knowledge/stores/rowDelta.ts +166 -0
- package/src/knowledge/stores/rowMemory.ts +82 -0
- package/src/knowledge/stores/rowSync.ts +118 -0
- package/src/knowledge/stores/snapshotFormat.ts +30 -0
|
@@ -14,17 +14,24 @@
|
|
|
14
14
|
* inside a run; outside one, each awaited mutation has persisted when it resolves.
|
|
15
15
|
*
|
|
16
16
|
* PRD 41 A10: reads come from memory once loaded (never behind the mutation queue); rows live in
|
|
17
|
-
* per-root maps updated incrementally; with the optional `extractedLog` port the
|
|
18
|
-
* an append-only JSON Lines file instead of part of the snapshot.
|
|
17
|
+
* per-root maps (rowMemory.ts) updated incrementally; with the optional `extractedLog` port the
|
|
18
|
+
* extract cache is an append-only JSON Lines file (extractLogWriter.ts) instead of part of the snapshot.
|
|
19
|
+
*
|
|
20
|
+
* PRD 41 B4 (G03): with `opts.rows` ({@link RowPersistence}) the store persists only the rows that changed
|
|
21
|
+
* (dirty keys in rowDelta.ts) and `persistence` / `extractedLog` are not used. Construct it as
|
|
22
|
+
* `new LocalSnapshotStore(undefined, { rows })`; a `persistence` given beside `rows` is ignored.
|
|
19
23
|
*/
|
|
20
24
|
|
|
21
|
-
import type {
|
|
22
|
-
Extracted, KnowledgeStore, NodeRef, Scope, ScopeRecord, StoredFact, StoredRelation,
|
|
23
|
-
} from '../model.js';
|
|
25
|
+
import type { Extracted, KnowledgeStore, NodeRef, Scope, ScopeRecord, StoredFact, StoredRelation } from '../model.js';
|
|
24
26
|
import { canonicalJson, compareStr, pathOfRef } from '../refs.js';
|
|
25
|
-
import {
|
|
27
|
+
import { ExtractLogWriter } from './extractLogWriter.js';
|
|
28
|
+
import type { RowDelta, RowPersistence } from './rowDelta.js';
|
|
29
|
+
import { RowMemory } from './rowMemory.js';
|
|
30
|
+
import { RowSync } from './rowSync.js';
|
|
31
|
+
import { emptySnapshot, parse, stripUndefined, type KnowledgeSnapshot } from './snapshotFormat.js';
|
|
26
32
|
|
|
27
33
|
export type { KnowledgeSnapshot } from './snapshotFormat.js';
|
|
34
|
+
export type { RowChange, RowPersistence } from './rowDelta.js';
|
|
28
35
|
|
|
29
36
|
export interface SnapshotPersistence {
|
|
30
37
|
read(): Promise<string | undefined>;
|
|
@@ -46,8 +53,10 @@ export interface ExtractedLogPersistence {
|
|
|
46
53
|
}
|
|
47
54
|
|
|
48
55
|
export interface LocalSnapshotStoreOptions {
|
|
49
|
-
/** When given, the extract cache lives in this log and the snapshot omits `extracted`. */
|
|
56
|
+
/** When given, the extract cache lives in this log and the snapshot omits `extracted`. Ignored with `rows`. */
|
|
50
57
|
extractedLog?: ExtractedLogPersistence;
|
|
58
|
+
/** Row-level persistence (a SQLite file): only changed rows are written; `SnapshotPersistence` and `extractedLog` are not used. */
|
|
59
|
+
rows?: RowPersistence;
|
|
51
60
|
/** ISO clock for `staleAt`. Default `new Date().toISOString()`. */
|
|
52
61
|
now?(): string;
|
|
53
62
|
/** Inside `batched`, a mutation persists when this many ms passed since the last write (a crash loses at most this much). Default 30_000. */
|
|
@@ -56,27 +65,17 @@ export interface LocalSnapshotStoreOptions {
|
|
|
56
65
|
nowMs?(): number;
|
|
57
66
|
}
|
|
58
67
|
|
|
59
|
-
const relKey = (r: Pick<StoredRelation, 'from' | 'to' | 'kind'>) => `${r.from}\u0000${r.to}\u0000${r.kind}`;
|
|
60
|
-
|
|
61
|
-
type Index = Map<string, Set<string>>;
|
|
62
|
-
|
|
63
68
|
export class LocalSnapshotStore implements KnowledgeStore {
|
|
64
69
|
private loaded = false;
|
|
65
70
|
private loading: Promise<void> | undefined;
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
private readonly
|
|
69
|
-
private readonly
|
|
70
|
-
/**
|
|
71
|
-
private readonly
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
private readonly recheck = new Set<string>();
|
|
75
|
-
/** Extract entries not yet appended to the log. */
|
|
76
|
-
private pending = new Map<string, Extracted[]>();
|
|
77
|
-
/** The log's last line is torn (no newline), so the next append starts on a fresh line. */
|
|
78
|
-
private logTorn = false;
|
|
79
|
-
private readonly log: ExtractedLogPersistence | undefined;
|
|
71
|
+
/** Per-root rows and the extract cache (PRD 41 A10 rule 7). */
|
|
72
|
+
private mem = new RowMemory();
|
|
73
|
+
private readonly log: ExtractLogWriter | undefined;
|
|
74
|
+
private readonly rows: RowPersistence | undefined;
|
|
75
|
+
/** Row mode only: writes the changed rows, reloads, reads bodies lazily (rowSync.ts). */
|
|
76
|
+
private readonly sync: RowSync | undefined;
|
|
77
|
+
/** Row mode only: the keys changed since the last `apply`. */
|
|
78
|
+
private readonly delta: RowDelta | undefined;
|
|
80
79
|
/** Serializes mutations so two writers never interleave a read-modify-write. */
|
|
81
80
|
private queue: Promise<unknown> = Promise.resolve();
|
|
82
81
|
private readonly now: () => string;
|
|
@@ -89,14 +88,26 @@ export class LocalSnapshotStore implements KnowledgeStore {
|
|
|
89
88
|
private persistedAt = 0;
|
|
90
89
|
/** Serializes snapshot writes; never rejects. */
|
|
91
90
|
private persisting: Promise<void> = Promise.resolve();
|
|
91
|
+
/** Steps queued or running on the persist chain. */
|
|
92
|
+
private steps = 0;
|
|
92
93
|
/** A background checkpoint in flight (at most one). */
|
|
93
94
|
private checkpointing: Promise<void> | undefined;
|
|
94
95
|
|
|
95
|
-
|
|
96
|
+
/** Row-persisted: no whole-snapshot port; only changed rows are written through `opts.rows`. */
|
|
97
|
+
constructor(persistence: undefined, opts: LocalSnapshotStoreOptions & { rows: RowPersistence });
|
|
98
|
+
/** Snapshot-persisted (the default): the whole canonical snapshot is written through `persistence`. */
|
|
99
|
+
constructor(persistence: SnapshotPersistence, opts?: LocalSnapshotStoreOptions);
|
|
100
|
+
constructor(private readonly persistence: SnapshotPersistence | undefined, opts: LocalSnapshotStoreOptions = {}) {
|
|
101
|
+
this.rows = opts.rows;
|
|
102
|
+
if (!this.rows && !persistence) throw new Error('LocalSnapshotStore: give a SnapshotPersistence or opts.rows');
|
|
103
|
+
this.sync = this.rows && new RowSync(this.rows, {
|
|
104
|
+
mem: () => this.mem, setMem: (m) => { this.mem = m; }, enqueue: (t) => this.enqueue(t), chain: (s) => this.onChain(s), inBatch: () => this.depth > 0, busy: () => this.steps > 0,
|
|
105
|
+
});
|
|
106
|
+
this.delta = this.sync?.delta;
|
|
96
107
|
this.now = opts.now ?? (() => new Date().toISOString());
|
|
97
108
|
this.nowMs = opts.nowMs ?? Date.now;
|
|
98
109
|
this.checkpointMs = opts.checkpointMs ?? 30_000;
|
|
99
|
-
this.log = opts.extractedLog;
|
|
110
|
+
this.log = !this.rows && opts.extractedLog ? new ExtractLogWriter(opts.extractedLog) : undefined;
|
|
100
111
|
}
|
|
101
112
|
|
|
102
113
|
/** Loads once; every later call is a no-op, so reads never wait on the mutation queue after the first. */
|
|
@@ -106,86 +117,51 @@ export class LocalSnapshotStore implements KnowledgeStore {
|
|
|
106
117
|
return this.loading;
|
|
107
118
|
}
|
|
108
119
|
|
|
120
|
+
/** What a read waits for: the first load, then (row mode) a reload when another writer changed the store. */
|
|
121
|
+
private async fresh(): Promise<void> {
|
|
122
|
+
await this.load();
|
|
123
|
+
await this.sync?.sync();
|
|
124
|
+
}
|
|
125
|
+
|
|
109
126
|
private async doLoad(): Promise<void> {
|
|
110
|
-
const snapText = await this.persistence.read();
|
|
111
127
|
let snap: KnowledgeSnapshot;
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
await this.persistence
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
}
|
|
126
|
-
for (const [rootId, rows] of Object.entries(snap.relations)) {
|
|
127
|
-
this.relsOf(rootId);
|
|
128
|
-
if (Array.isArray(rows)) for (const r of rows) this.putRelation(rootId, r);
|
|
128
|
+
let logText: string | undefined;
|
|
129
|
+
if (this.rows) {
|
|
130
|
+
snap = (await this.rows.load()) ?? emptySnapshot();
|
|
131
|
+
} else {
|
|
132
|
+
const snapText = await this.persistence!.read();
|
|
133
|
+
try {
|
|
134
|
+
snap = parse(snapText);
|
|
135
|
+
} catch {
|
|
136
|
+
// Unreadable: never silently replaced. Its bytes are kept aside, then the store starts empty (the next review rebuilds).
|
|
137
|
+
await this.persistence!.keepAside?.(snapText!).catch(() => undefined);
|
|
138
|
+
snap = emptySnapshot();
|
|
139
|
+
}
|
|
140
|
+
logText = this.log ? await this.log.read() : undefined;
|
|
129
141
|
}
|
|
142
|
+
this.mem.fill(snap, !this.log);
|
|
130
143
|
if (this.log) {
|
|
131
|
-
|
|
132
|
-
for (const [h, e] of parsed.entries) this.extracted.set(h, e);
|
|
133
|
-
this.logTorn = !!logText && !logText.endsWith('\n');
|
|
134
|
-
await this.compactLog(parsed);
|
|
144
|
+
await this.log.load(logText, this.mem.extracted);
|
|
135
145
|
// An old snapshot still carrying the cache: move it into the log once; the next snapshot write omits it.
|
|
136
146
|
const legacy = Object.entries(snap.extracted ?? {});
|
|
137
147
|
if (legacy.length) {
|
|
138
148
|
for (const [h, e] of legacy) {
|
|
139
|
-
if (this.extracted.has(h)) continue;
|
|
140
|
-
this.extracted.set(h, e);
|
|
141
|
-
this.
|
|
149
|
+
if (this.mem.extracted.has(h)) continue;
|
|
150
|
+
this.mem.extracted.set(h, e);
|
|
151
|
+
this.log.queue(h, e);
|
|
142
152
|
}
|
|
143
153
|
this.dirty = true;
|
|
144
154
|
}
|
|
145
|
-
} else {
|
|
146
|
-
for (const [h, e] of Object.entries(snap.extracted ?? {})) this.extracted.set(h, e);
|
|
147
155
|
}
|
|
148
156
|
this.loaded = true;
|
|
149
157
|
}
|
|
150
158
|
|
|
151
|
-
/**
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
if (!this.log?.replace || parsed.deadBytes <= parsed.liveBytes) return;
|
|
158
|
-
try {
|
|
159
|
-
await this.log.replace([...parsed.liveLines.values()].join(''));
|
|
160
|
-
this.logTorn = false;
|
|
161
|
-
} catch { /* keep the uncompacted log */ }
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
private factsOf(rootId: string): Map<string, StoredFact> {
|
|
165
|
-
let m = this.factMaps.get(rootId);
|
|
166
|
-
if (!m) this.factMaps.set(rootId, m = new Map());
|
|
167
|
-
return m;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
private relsOf(rootId: string): Map<string, StoredRelation> {
|
|
171
|
-
let m = this.relMaps.get(rootId);
|
|
172
|
-
if (!m) this.relMaps.set(rootId, m = new Map());
|
|
173
|
-
return m;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
/** Upserts a relation and indexes it under the source paths of both ends. */
|
|
177
|
-
private putRelation(rootId: string, r: StoredRelation): void {
|
|
178
|
-
const key = relKey(r);
|
|
179
|
-
this.relsOf(rootId).set(key, r);
|
|
180
|
-
let idx = this.relByPath.get(rootId);
|
|
181
|
-
if (!idx) this.relByPath.set(rootId, idx = new Map());
|
|
182
|
-
for (const ref of [r.from, r.to]) {
|
|
183
|
-
const p = pathOfRef(ref);
|
|
184
|
-
if (p === undefined) continue;
|
|
185
|
-
let keys = idx.get(p);
|
|
186
|
-
if (!keys) idx.set(p, keys = new Set());
|
|
187
|
-
keys.add(key);
|
|
188
|
-
}
|
|
159
|
+
/** Runs a step after the previous persist step (one at a time); the chain itself never rejects. */
|
|
160
|
+
private onChain<T>(step: () => Promise<T>): Promise<T> {
|
|
161
|
+
const run = this.persisting.then(step);
|
|
162
|
+
this.steps += 1;
|
|
163
|
+
this.persisting = run.then(() => undefined, () => undefined).then(() => { this.steps -= 1; });
|
|
164
|
+
return run;
|
|
189
165
|
}
|
|
190
166
|
|
|
191
167
|
private enqueue<T>(task: () => Promise<T>): Promise<T> {
|
|
@@ -195,48 +171,26 @@ export class LocalSnapshotStore implements KnowledgeStore {
|
|
|
195
171
|
}
|
|
196
172
|
|
|
197
173
|
/**
|
|
198
|
-
* Appends
|
|
199
|
-
*
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
const batch = this.pending;
|
|
204
|
-
this.pending = new Map();
|
|
205
|
-
let text = this.logTorn ? '\n' : '';
|
|
206
|
-
for (const [h, e] of batch) text += `${JSON.stringify({ h, e })}\n`;
|
|
207
|
-
try {
|
|
208
|
-
await this.log.append(text);
|
|
209
|
-
this.logTorn = false;
|
|
210
|
-
} catch (err) {
|
|
211
|
-
this.logTorn = true;
|
|
212
|
-
for (const [h, e] of batch) if (!this.pending.has(h)) this.pending.set(h, e);
|
|
213
|
-
throw err;
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
/**
|
|
218
|
-
* Appends new extract entries, then writes the snapshot if memory is ahead of it, one write at a time. It
|
|
219
|
-
* runs OUTSIDE the mutation queue: a write of a large snapshot (serialize + disk) must never hold up reads or
|
|
220
|
-
* the next mutation's in-memory apply (PRD 41 A10 — it did: every `getExtracted` waited out each checkpoint).
|
|
221
|
-
* The log goes first, so a snapshot that dropped a migrated cache never outlives its entries. A failed
|
|
222
|
-
* write leaves the snapshot dirty, so the next one retries it.
|
|
174
|
+
* Appends new extract entries, then writes the snapshot (or, in row mode, the changed rows) if memory is ahead of it,
|
|
175
|
+
* one write at a time. It runs OUTSIDE the mutation queue: a write of a large snapshot (serialize + disk) must never
|
|
176
|
+
* hold up reads or the next mutation's in-memory apply (PRD 41 A10 — it did: every `getExtracted` waited out each
|
|
177
|
+
* checkpoint). The log goes first, so a snapshot that dropped a migrated cache never outlives its entries. A failed
|
|
178
|
+
* write leaves the store dirty, so the next one retries it.
|
|
223
179
|
*/
|
|
224
180
|
private persistIfDirty(): Promise<void> {
|
|
225
|
-
|
|
181
|
+
return this.onChain(async () => {
|
|
226
182
|
if (!this.loaded) return;
|
|
227
|
-
await this.
|
|
183
|
+
await this.log?.flush();
|
|
228
184
|
if (!this.dirty) return;
|
|
229
185
|
this.dirty = false;
|
|
230
186
|
try {
|
|
231
|
-
await this.persistence
|
|
187
|
+
await (this.sync ? this.sync.apply() : this.persistence!.write(this.mem.serialize(this.log ? undefined : this.mem.extracted)));
|
|
232
188
|
} catch (err) {
|
|
233
189
|
this.dirty = true;
|
|
234
190
|
throw err;
|
|
235
191
|
}
|
|
236
192
|
this.persistedAt = this.nowMs();
|
|
237
193
|
});
|
|
238
|
-
this.persisting = run.catch(() => undefined);
|
|
239
|
-
return run;
|
|
240
194
|
}
|
|
241
195
|
|
|
242
196
|
/**
|
|
@@ -285,18 +239,18 @@ export class LocalSnapshotStore implements KnowledgeStore {
|
|
|
285
239
|
}
|
|
286
240
|
|
|
287
241
|
async scopes(): Promise<ScopeRecord[]> {
|
|
288
|
-
await this.
|
|
289
|
-
return [...this.
|
|
242
|
+
await this.fresh();
|
|
243
|
+
return [...this.mem.scopes];
|
|
290
244
|
}
|
|
291
245
|
|
|
292
246
|
async facts(scope: Scope): Promise<StoredFact[]> {
|
|
293
|
-
await this.
|
|
294
|
-
return [...(this.
|
|
247
|
+
await this.fresh();
|
|
248
|
+
return [...(this.mem.facts.get(scope.rootId)?.values() ?? [])];
|
|
295
249
|
}
|
|
296
250
|
|
|
297
251
|
async relations(scope: Scope): Promise<StoredRelation[]> {
|
|
298
|
-
await this.
|
|
299
|
-
return [...(this.
|
|
252
|
+
await this.fresh();
|
|
253
|
+
return [...(this.mem.relations.get(scope.rootId)?.values() ?? [])];
|
|
300
254
|
}
|
|
301
255
|
|
|
302
256
|
write(batch: { scope: ScopeRecord; facts: StoredFact[]; relations: StoredRelation[] }): Promise<void> {
|
|
@@ -304,14 +258,15 @@ export class LocalSnapshotStore implements KnowledgeStore {
|
|
|
304
258
|
if (bad) return Promise.reject(new Error('knowledge: extracted output is never stored'));
|
|
305
259
|
return this.mutate(() => {
|
|
306
260
|
const rootId = batch.scope.rootId;
|
|
307
|
-
const prior = this.
|
|
261
|
+
const prior = this.mem.scopes.find((x) => x.rootId === rootId);
|
|
308
262
|
const merged: ScopeRecord = { ...(prior ?? {}), ...stripUndefined(batch.scope) } as ScopeRecord;
|
|
309
|
-
this.
|
|
263
|
+
this.mem.scopes = [...this.mem.scopes.filter((x) => x.rootId !== rootId), merged];
|
|
264
|
+
this.delta?.mark('scopes', [rootId]);
|
|
310
265
|
|
|
311
|
-
const facts = this.factsOf(rootId);
|
|
312
|
-
for (const f of batch.facts) facts.set(f.key, { ...f });
|
|
313
|
-
this.relsOf(rootId);
|
|
314
|
-
for (const r of batch.relations) this.putRelation(rootId, { ...r });
|
|
266
|
+
const facts = this.mem.factsOf(rootId);
|
|
267
|
+
for (const f of batch.facts) { facts.set(f.key, { ...f }); this.delta?.mark('facts', [rootId, f.key]); }
|
|
268
|
+
this.mem.relsOf(rootId);
|
|
269
|
+
for (const r of batch.relations) { this.mem.putRelation(rootId, { ...r }); this.delta?.mark('relations', [rootId, r.from, r.to, r.kind]); }
|
|
315
270
|
});
|
|
316
271
|
}
|
|
317
272
|
|
|
@@ -319,77 +274,92 @@ export class LocalSnapshotStore implements KnowledgeStore {
|
|
|
319
274
|
const path = pathOfRef(sourceRef);
|
|
320
275
|
return this.mutate(() => {
|
|
321
276
|
const at = this.now();
|
|
322
|
-
const rels = this.relsOf(scope.rootId);
|
|
323
|
-
const keys = path === undefined ? undefined : this.
|
|
277
|
+
const rels = this.mem.relsOf(scope.rootId);
|
|
278
|
+
const keys = path === undefined ? undefined : this.mem.relationKeysAt(scope.rootId, path);
|
|
324
279
|
for (const key of keys ?? []) {
|
|
325
280
|
const r = rels.get(key);
|
|
326
|
-
if (r && r.origin === 'model' && !r.staleAt && r.sourceHash !== currentHash)
|
|
281
|
+
if (r && r.origin === 'model' && !r.staleAt && r.sourceHash !== currentHash) {
|
|
282
|
+
rels.set(key, { ...r, staleAt: at });
|
|
283
|
+
this.delta?.mark('relations', [scope.rootId, r.from, r.to, r.kind]);
|
|
284
|
+
}
|
|
327
285
|
}
|
|
328
286
|
});
|
|
329
287
|
}
|
|
330
288
|
|
|
289
|
+
/** The cached entries of a content hash. In row mode a hash not in memory is read through `rows.loadExtracted` and kept. */
|
|
331
290
|
async getExtracted(hash: string): Promise<Extracted[] | undefined> {
|
|
332
|
-
await this.
|
|
333
|
-
return this.extracted.get(hash);
|
|
291
|
+
await this.fresh();
|
|
292
|
+
return this.sync ? this.sync.body(hash) : this.mem.extracted.get(hash);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Row mode: reads the bodies of these hashes through `rows.loadExtracted`, a chunk at a time. Otherwise a no-op (everything is in memory). */
|
|
296
|
+
async preloadExtracted(hashes: readonly string[]): Promise<void> {
|
|
297
|
+
if (!this.sync) return;
|
|
298
|
+
await this.fresh();
|
|
299
|
+
await this.sync.preload(hashes);
|
|
334
300
|
}
|
|
335
301
|
|
|
336
302
|
/** Asks the next review to re-check the files with these content hashes (persisted until {@link clearRecheck}). */
|
|
337
303
|
markRecheck(hashes: readonly string[]): Promise<void> {
|
|
338
304
|
// The snapshot is dirty only when the set really changed (a repeated mark costs no write).
|
|
339
|
-
return this.mutate(() => {
|
|
305
|
+
return this.mutate(() => {
|
|
306
|
+
for (const h of hashes) if (!this.mem.recheck.has(h)) { this.mem.recheck.add(h); this.dirty = true; this.delta?.mark('recheck', [h]); }
|
|
307
|
+
}, false);
|
|
340
308
|
}
|
|
341
309
|
|
|
342
310
|
async hasRecheck(hash: string): Promise<boolean> {
|
|
343
|
-
await this.
|
|
344
|
-
return this.recheck.has(hash);
|
|
311
|
+
await this.fresh();
|
|
312
|
+
return this.mem.recheck.has(hash);
|
|
345
313
|
}
|
|
346
314
|
|
|
347
315
|
async recheckHashes(): Promise<string[]> {
|
|
348
|
-
await this.
|
|
349
|
-
return [...this.recheck].sort(compareStr);
|
|
316
|
+
await this.fresh();
|
|
317
|
+
return [...this.mem.recheck].sort(compareStr);
|
|
350
318
|
}
|
|
351
319
|
|
|
352
320
|
/** Forgets hashes a review has handled. */
|
|
353
321
|
clearRecheck(hashes: readonly string[]): Promise<void> {
|
|
354
|
-
return this.mutate(() => {
|
|
322
|
+
return this.mutate(() => {
|
|
323
|
+
for (const h of hashes) if (this.mem.recheck.delete(h)) { this.dirty = true; this.delta?.mark('recheck', [h], true); }
|
|
324
|
+
}, false);
|
|
355
325
|
}
|
|
356
326
|
|
|
357
|
-
/** Every cached entry by content hash (the log's, else the snapshot's `extracted`), for a host that packs the cache. */
|
|
327
|
+
/** Every cached entry by content hash (the log's, else the snapshot's `extracted`), for a host that packs the cache. Row mode reads ALL bodies through `loadAllExtracted` (memory wins) and throws without it: never a partial map. */
|
|
358
328
|
async extractedEntries(): Promise<Record<string, Extracted[]>> {
|
|
359
|
-
await this.
|
|
360
|
-
return Object.fromEntries(this.extracted);
|
|
329
|
+
await this.fresh();
|
|
330
|
+
return Object.fromEntries(this.sync ? await this.sync.allBodies() : this.mem.extracted);
|
|
361
331
|
}
|
|
362
332
|
|
|
363
333
|
putExtracted(hash: string, extracted: Extracted[]): Promise<void> {
|
|
364
334
|
return this.mutate(() => {
|
|
365
335
|
// The same entry again (a second pass re-puts what the first stored) is skipped: no append, no dirty snapshot.
|
|
366
|
-
const prior = this.extracted.get(hash);
|
|
336
|
+
const prior = this.mem.extracted.get(hash);
|
|
367
337
|
if (prior && canonicalJson(prior) === canonicalJson(extracted)) return;
|
|
368
|
-
this.extracted.set(hash, extracted);
|
|
369
|
-
|
|
338
|
+
this.mem.extracted.set(hash, extracted);
|
|
339
|
+
this.sync?.forget(hash);
|
|
340
|
+
this.delta?.mark('extracted', [hash]);
|
|
341
|
+
if (this.log) this.log.queue(hash, extracted);
|
|
370
342
|
else this.dirty = true;
|
|
371
343
|
}, false);
|
|
372
344
|
}
|
|
373
345
|
|
|
374
|
-
/**
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
scopes: [...this.scopeList].sort((a, b) => compareStr(a.rootId, b.rootId)),
|
|
381
|
-
facts: rows(this.factMaps, (a, b) => compareStr(a.key, b.key)),
|
|
382
|
-
relations: rows(this.relMaps, (a, b) => compareStr(relKey(a), relKey(b))),
|
|
383
|
-
...(this.log ? {} : { extracted: Object.fromEntries(this.extracted) }),
|
|
384
|
-
...(this.recheck.size > 0 ? { recheck: [...this.recheck].sort(compareStr) } : {}),
|
|
385
|
-
});
|
|
346
|
+
/** See {@link canonicalDump}. Static so it can reach private state without widening the instance's public surface. */
|
|
347
|
+
static async dumpOf(store: LocalSnapshotStore): Promise<string> {
|
|
348
|
+
await store.fresh();
|
|
349
|
+
if (!store.sync) return store.mem.serialize(store.log ? undefined : store.mem.extracted);
|
|
350
|
+
const bodies = await store.sync.allBodies();
|
|
351
|
+
return store.mem.serialize(bodies);
|
|
386
352
|
}
|
|
387
353
|
}
|
|
388
354
|
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
355
|
+
/**
|
|
356
|
+
* The canonical text of a store's rows: byte-equal to what a snapshot-persisted store writes (without `extractedLog`, the
|
|
357
|
+
* extract cache included). The projection `packPush` / `portablePack` read. Row mode reads every body through `loadAllExtracted` and throws `knowledge_dump_needs_all_bodies` without it.
|
|
358
|
+
*/
|
|
359
|
+
export const canonicalDump = (store: LocalSnapshotStore): Promise<string> => LocalSnapshotStore.dumpOf(store);
|
|
392
360
|
|
|
393
|
-
function
|
|
394
|
-
|
|
361
|
+
export function localSnapshotStore(persistence: undefined, opts: LocalSnapshotStoreOptions & { rows: RowPersistence }): LocalSnapshotStore;
|
|
362
|
+
export function localSnapshotStore(persistence: SnapshotPersistence, opts?: LocalSnapshotStoreOptions): LocalSnapshotStore;
|
|
363
|
+
export function localSnapshotStore(persistence: SnapshotPersistence | undefined, opts?: LocalSnapshotStoreOptions): LocalSnapshotStore {
|
|
364
|
+
return new LocalSnapshotStore(persistence as SnapshotPersistence, opts);
|
|
395
365
|
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/knowledge/stores/rowDelta.test.ts — the dirty tracking of a row-persisted store: last mark wins per key, `take` swaps
|
|
3
|
+
* the marks out, `restore` merges them back UNDER newer marks, `overlay` lays unwritten rows over rows read from the host.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { Extracted, ScopeRecord, StoredFact } from '../model.js';
|
|
7
|
+
import { RowDelta } from './rowDelta.js';
|
|
8
|
+
import { RowMemory } from './rowMemory.js';
|
|
9
|
+
|
|
10
|
+
const fact = (key: string, content: string): StoredFact => ({ key, content, source: 's', importance: 0.5, origin: 'model', fileAnchors: [] });
|
|
11
|
+
|
|
12
|
+
function memory(): RowMemory {
|
|
13
|
+
const m = new RowMemory();
|
|
14
|
+
m.factsOf('r').set('k', fact('k', 'v1'));
|
|
15
|
+
m.scopes = [{ rootId: 'r', title: 'R', packs: ['docs'] } as ScopeRecord];
|
|
16
|
+
m.extracted.set('h', [{ name: 'e' }] as unknown as Extracted[]);
|
|
17
|
+
m.recheck.add('c');
|
|
18
|
+
return m;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
describe('RowDelta', () => {
|
|
22
|
+
it('an upsert after a delete is an upsert, a delete after an upsert is a delete (last mark wins)', () => {
|
|
23
|
+
const d = new RowDelta();
|
|
24
|
+
const m = memory();
|
|
25
|
+
d.mark('facts', ['r', 'k'], true);
|
|
26
|
+
d.mark('facts', ['r', 'k']);
|
|
27
|
+
expect(d.toChange(d.take(), m).upserts.facts.map(([, f]) => f.content)).toEqual(['v1']);
|
|
28
|
+
d.mark('facts', ['r', 'k']);
|
|
29
|
+
d.mark('facts', ['r', 'k'], true);
|
|
30
|
+
const c = d.toChange(d.take(), m);
|
|
31
|
+
expect(c.upserts.facts).toEqual([]);
|
|
32
|
+
expect(c.deletes.facts).toEqual([['r', 'k']]);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('take swaps the marks out; restore merges them back under newer marks; nothing is lost or reordered', () => {
|
|
36
|
+
const d = new RowDelta();
|
|
37
|
+
const m = memory();
|
|
38
|
+
d.mark('facts', ['r', 'k']);
|
|
39
|
+
d.mark('recheck', ['c']);
|
|
40
|
+
const taken = d.take();
|
|
41
|
+
expect(d.pending).toBe(false);
|
|
42
|
+
d.mark('facts', ['r', 'k'], true); // newer: a delete
|
|
43
|
+
d.mark('extracted', ['h']);
|
|
44
|
+
d.restore(taken);
|
|
45
|
+
const c = d.toChange(d.take(), m);
|
|
46
|
+
expect(c.deletes.facts).toEqual([['r', 'k']]); // the newer delete beats the restored upsert
|
|
47
|
+
expect(c.upserts.recheck).toEqual(['c']); // the restored mark survives
|
|
48
|
+
expect(c.upserts.extracted.map(([h]) => h)).toEqual(['h']); // the newer mark survives
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('overlay skips an upsert mark whose row is gone from memory: it does not delete the host\'s row', () => {
|
|
52
|
+
const d = new RowDelta();
|
|
53
|
+
d.mark('facts', ['r', 'k']);
|
|
54
|
+
d.mark('scopes', ['r']);
|
|
55
|
+
d.mark('extracted', ['h']);
|
|
56
|
+
const fresh = new RowMemory();
|
|
57
|
+
fresh.factsOf('r').set('k', fact('k', 'theirs'));
|
|
58
|
+
fresh.scopes = [{ rootId: 'r', title: 'T', packs: [] } as ScopeRecord];
|
|
59
|
+
fresh.extracted.set('h', [{ name: 'x' }] as unknown as Extracted[]);
|
|
60
|
+
d.overlay(new RowMemory(), fresh);
|
|
61
|
+
expect(fresh.facts.get('r')!.get('k')!.content).toBe('theirs');
|
|
62
|
+
expect(fresh.scopes).toHaveLength(1);
|
|
63
|
+
expect(fresh.extracted.has('h')).toBe(true);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('an empty take is empty; an upsert whose row is gone from memory is skipped', () => {
|
|
67
|
+
const d = new RowDelta();
|
|
68
|
+
expect(d.take().empty).toBe(true);
|
|
69
|
+
d.mark('facts', ['r', 'missing']);
|
|
70
|
+
const t = d.take();
|
|
71
|
+
expect(t.empty).toBe(false);
|
|
72
|
+
expect(d.toChange(t, memory()).upserts.facts).toEqual([]);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('overlay keeps unwritten upserts and deletes (in-flight and current) over rows read from the host', () => {
|
|
76
|
+
const d = new RowDelta();
|
|
77
|
+
const old = memory();
|
|
78
|
+
old.factsOf('r').set('k2', fact('k2', 'mine'));
|
|
79
|
+
old.factsOf('r').set('k3', fact('k3', 'mine'));
|
|
80
|
+
d.mark('facts', ['r', 'k2']); // will be in flight
|
|
81
|
+
d.take();
|
|
82
|
+
d.mark('facts', ['r', 'k3'], true); // newer: delete
|
|
83
|
+
d.mark('facts', ['r', 'k'], true);
|
|
84
|
+
const fresh = new RowMemory();
|
|
85
|
+
fresh.factsOf('r').set('k', fact('k', 'theirs'));
|
|
86
|
+
fresh.factsOf('r').set('k3', fact('k3', 'theirs'));
|
|
87
|
+
fresh.factsOf('r').set('k4', fact('k4', 'theirs'));
|
|
88
|
+
d.overlay(old, fresh);
|
|
89
|
+
expect([...fresh.facts.get('r')!.entries()].map(([k, v]) => [k, v.content]).sort()).toEqual([['k2', 'mine'], ['k4', 'theirs']]);
|
|
90
|
+
});
|
|
91
|
+
});
|