@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.
- 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/owedFiles.d.ts +2 -1
- package/dist/knowledge/owedFiles.d.ts.map +1 -1
- package/dist/knowledge/owedFiles.js.map +1 -1
- package/dist/knowledge/review.js +3 -2
- package/dist/knowledge/review.js.map +1 -1
- package/dist/knowledge/reviewFailure.d.ts +4 -2
- package/dist/knowledge/reviewFailure.d.ts.map +1 -1
- package/dist/knowledge/reviewFailure.js +7 -4
- package/dist/knowledge/reviewFailure.js.map +1 -1
- package/dist/knowledge/reviewPrefetch.js +1 -1
- package/dist/knowledge/reviewPrefetch.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.recheck.test.ts +70 -8
- package/src/contract/regression.rows.test.ts +377 -0
- package/src/contract/types.contract.test.ts +33 -5
- package/src/knowledge/index.ts +4 -2
- package/src/knowledge/owedFiles.ts +2 -1
- package/src/knowledge/review.ordered.test.ts +7 -3
- package/src/knowledge/review.ts +2 -2
- package/src/knowledge/reviewFailure.ts +8 -5
- package/src/knowledge/reviewPrefetch.ts +1 -1
- 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
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/stores/rowDelta.ts — the dirty tracking and the port types of a ROW-persisted {@link LocalSnapshotStore}
|
|
3
|
+
* (PRD 41 B4, G03). A host that keeps rows (a SQLite file) gets only the rows that changed, not the whole snapshot.
|
|
4
|
+
*
|
|
5
|
+
* The delta records KEYS, never values: a mark says "this row was upserted" or "this row was deleted", and the value is
|
|
6
|
+
* read from memory when the change is built. The last mark per key wins (an upsert after a delete is an upsert; a delete
|
|
7
|
+
* after an upsert is a delete). `take()` swaps the marks out for one `apply`; `restore(taken)` merges them back UNDER any
|
|
8
|
+
* newer marks when the apply failed, so nothing is lost and nothing older overrides something newer. While an apply is in
|
|
9
|
+
* flight its marks stay visible to {@link RowDelta.overlay}, so a reload that races it cannot drop those rows from memory.
|
|
10
|
+
*
|
|
11
|
+
* No I/O and no store: the store only calls this.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { Extracted, ScopeRecord, StoredFact, StoredRelation } from '../model.js';
|
|
15
|
+
import type { KnowledgeSnapshot } from './snapshotFormat.js';
|
|
16
|
+
import { relKey } from './snapshotFormat.js';
|
|
17
|
+
|
|
18
|
+
/** What changed since the last `apply`. Keys of `recheck` are content hashes (the snapshot keeps ONE global set, not one per root). */
|
|
19
|
+
export interface RowChange {
|
|
20
|
+
upserts: {
|
|
21
|
+
scopes: ScopeRecord[]; facts: Array<[rootId: string, fact: StoredFact]>; relations: Array<[rootId: string, relation: StoredRelation]>;
|
|
22
|
+
extracted: Array<[hash: string, entries: Extracted[]]>; recheck: string[];
|
|
23
|
+
};
|
|
24
|
+
deletes: {
|
|
25
|
+
scopes: string[]; facts: Array<[rootId: string, key: string]>;
|
|
26
|
+
relations: Array<[rootId: string, from: string, to: string, kind: string]>;
|
|
27
|
+
extracted: string[]; recheck: string[];
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A host that keeps knowledge as rows. With it, `SnapshotPersistence` and `extractedLog` are not used. */
|
|
32
|
+
export interface RowPersistence {
|
|
33
|
+
/** Every row. `undefined` is an empty store (first open). `extracted` may be absent: bodies load lazily through `loadExtracted`. */
|
|
34
|
+
load(): Promise<KnowledgeSnapshot | undefined>;
|
|
35
|
+
/**
|
|
36
|
+
* Writes the change in ONE transaction. When another writer changed the store since this one last saw it, return the
|
|
37
|
+
* full rows as `reloaded`: the store replaces its memory with them and re-applies its own newer marks on top.
|
|
38
|
+
* - `reloaded` must be read INSIDE that same transaction, after the change was applied, so it contains the change.
|
|
39
|
+
* - `apply` may be called again with a SUPERSET of a change that already committed (the commit succeeded but returning or
|
|
40
|
+
* reading `reloaded` threw), so every upsert and delete must be idempotent.
|
|
41
|
+
* - The store never runs `load`, `apply` and the changed-elsewhere check concurrently on one connection.
|
|
42
|
+
* - `loadExtracted` and `loadAllExtracted` MAY run concurrently with an `apply` (reads never wait on persistence), so the host must allow concurrent reads.
|
|
43
|
+
*/
|
|
44
|
+
apply(change: RowChange): Promise<{ generation: number; reloaded?: KnowledgeSnapshot }>;
|
|
45
|
+
/** EVERY extract body, for a host that packs or dumps the cache. Without it, `extractedEntries()` and `canonicalDump` throw `knowledge_dump_needs_all_bodies` in row mode: they never return a partial map. Optional. */
|
|
46
|
+
loadAllExtracted?(): Promise<Record<string, Extracted[]>>;
|
|
47
|
+
/** The extract bodies of one content hash that are not in memory (reload returns rows, bodies load lazily). Optional. */
|
|
48
|
+
loadExtracted?(hash: string): Promise<Extracted[] | undefined>;
|
|
49
|
+
/** True when another writer changed the store since this store last saw it (e.g. `PRAGMA data_version`). Optional. */
|
|
50
|
+
changedElsewhere?(): Promise<boolean>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
type Kind = 'scopes' | 'facts' | 'relations' | 'extracted' | 'recheck';
|
|
54
|
+
const KINDS: readonly Kind[] = ['scopes', 'facts', 'relations', 'extracted', 'recheck'];
|
|
55
|
+
type Marks = Record<Kind, Map<string, { key: readonly string[]; del: boolean }>>;
|
|
56
|
+
const fresh = (): Marks => ({ scopes: new Map(), facts: new Map(), relations: new Map(), extracted: new Map(), recheck: new Map() });
|
|
57
|
+
|
|
58
|
+
/** The in-memory rows of a store, by reference: what {@link RowDelta.toChange} reads and {@link RowDelta.overlay} edits. */
|
|
59
|
+
export interface RowState {
|
|
60
|
+
scopes: ScopeRecord[];
|
|
61
|
+
facts: Map<string, Map<string, StoredFact>>;
|
|
62
|
+
relations: Map<string, Map<string, StoredRelation>>;
|
|
63
|
+
extracted: Map<string, Extracted[]>;
|
|
64
|
+
recheck: Set<string>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The marks swapped out by {@link RowDelta.take}. */
|
|
68
|
+
export interface TakenRows { readonly marks: Marks; readonly empty: boolean }
|
|
69
|
+
|
|
70
|
+
export class RowDelta {
|
|
71
|
+
private cur: Marks = fresh();
|
|
72
|
+
private inflight: Marks | undefined;
|
|
73
|
+
|
|
74
|
+
/** Marks a row. `key` is `[rootId]` (scope), `[rootId, key]` (fact), `[rootId, from, to, kind]` (relation), `[hash]` (extracted, recheck). */
|
|
75
|
+
mark(kind: Kind, key: readonly string[], del = false): void {
|
|
76
|
+
this.cur[kind].set(JSON.stringify(key), { key, del });
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** True when a mark is waiting for the next `apply`. */
|
|
80
|
+
get pending(): boolean { return KINDS.some((k) => this.cur[k].size > 0); }
|
|
81
|
+
|
|
82
|
+
/** Swaps the marks out for one `apply`. They stay visible to `overlay` until `settle` or `restore`. */
|
|
83
|
+
take(): TakenRows {
|
|
84
|
+
const marks = this.cur;
|
|
85
|
+
this.cur = fresh();
|
|
86
|
+
this.inflight = marks;
|
|
87
|
+
return { marks, empty: KINDS.every((k) => marks[k].size === 0) };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The apply succeeded. */
|
|
91
|
+
settle(): void { this.inflight = undefined; }
|
|
92
|
+
|
|
93
|
+
/** The apply failed: the taken marks go back UNDER any newer ones (a key marked since keeps its newer mark). */
|
|
94
|
+
restore(taken: TakenRows): void {
|
|
95
|
+
for (const k of KINDS) for (const [id, m] of taken.marks[k]) if (!this.cur[k].has(id)) this.cur[k].set(id, m);
|
|
96
|
+
if (this.inflight === taken.marks) this.inflight = undefined;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Reads the marked rows' CURRENT values from memory. A row marked as an upsert but gone from memory is skipped. */
|
|
100
|
+
toChange(taken: TakenRows, s: RowState): RowChange {
|
|
101
|
+
const out: RowChange = {
|
|
102
|
+
upserts: { scopes: [], facts: [], relations: [], extracted: [], recheck: [] },
|
|
103
|
+
deletes: { scopes: [], facts: [], relations: [], extracted: [], recheck: [] },
|
|
104
|
+
};
|
|
105
|
+
for (const { key, del } of taken.marks.scopes.values()) {
|
|
106
|
+
const v = s.scopes.find((x) => x.rootId === key[0]);
|
|
107
|
+
if (del) out.deletes.scopes.push(key[0]!); else if (v) out.upserts.scopes.push(v);
|
|
108
|
+
}
|
|
109
|
+
for (const { key, del } of taken.marks.facts.values()) {
|
|
110
|
+
const v = s.facts.get(key[0]!)?.get(key[1]!);
|
|
111
|
+
if (del) out.deletes.facts.push([key[0]!, key[1]!]); else if (v) out.upserts.facts.push([key[0]!, v]);
|
|
112
|
+
}
|
|
113
|
+
for (const { key, del } of taken.marks.relations.values()) {
|
|
114
|
+
const v = s.relations.get(key[0]!)?.get(relKey({ from: key[1]!, to: key[2]!, kind: key[3]! }));
|
|
115
|
+
if (del) out.deletes.relations.push([key[0]!, key[1]!, key[2]!, key[3]!]); else if (v) out.upserts.relations.push([key[0]!, v]);
|
|
116
|
+
}
|
|
117
|
+
for (const { key, del } of taken.marks.extracted.values()) {
|
|
118
|
+
const v = s.extracted.get(key[0]!);
|
|
119
|
+
if (del) out.deletes.extracted.push(key[0]!); else if (v) out.upserts.extracted.push([key[0]!, v]);
|
|
120
|
+
}
|
|
121
|
+
for (const { key, del } of taken.marks.recheck.values()) {
|
|
122
|
+
if (del) out.deletes.recheck.push(key[0]!); else if (s.recheck.has(key[0]!)) out.upserts.recheck.push(key[0]!);
|
|
123
|
+
}
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Lays this store's unwritten rows (the in-flight marks, then the current ones, the current winning) from `old` over `onto`,
|
|
129
|
+
* a state freshly read from the host: an upserted row keeps its in-memory value, a deleted row is removed. `onto.scopes`
|
|
130
|
+
* is edited in place. The caller rebuilds any index derived from the relations.
|
|
131
|
+
*/
|
|
132
|
+
overlay(old: RowState, onto: RowState): void {
|
|
133
|
+
for (const marks of [this.inflight, this.cur]) {
|
|
134
|
+
if (!marks) continue;
|
|
135
|
+
for (const { key, del } of marks.scopes.values()) {
|
|
136
|
+
const at = onto.scopes.findIndex((x) => x.rootId === key[0]);
|
|
137
|
+
const v = del ? undefined : old.scopes.find((x) => x.rootId === key[0]);
|
|
138
|
+
if (!del && !v) continue; // an upsert whose row is gone from memory is skipped, as in toChange
|
|
139
|
+
if (at >= 0) onto.scopes.splice(at, 1);
|
|
140
|
+
if (v) onto.scopes.push(v);
|
|
141
|
+
}
|
|
142
|
+
for (const { key, del } of marks.facts.values()) {
|
|
143
|
+
const v = old.facts.get(key[0]!)?.get(key[1]!);
|
|
144
|
+
if (del) onto.facts.get(key[0]!)?.delete(key[1]!); else if (v) rowsOf(onto.facts, key[0]!).set(key[1]!, v);
|
|
145
|
+
}
|
|
146
|
+
for (const { key, del } of marks.relations.values()) {
|
|
147
|
+
const rk = relKey({ from: key[1]!, to: key[2]!, kind: key[3]! });
|
|
148
|
+
const v = old.relations.get(key[0]!)?.get(rk);
|
|
149
|
+
if (del) onto.relations.get(key[0]!)?.delete(rk); else if (v) rowsOf(onto.relations, key[0]!).set(rk, v);
|
|
150
|
+
}
|
|
151
|
+
for (const { key, del } of marks.extracted.values()) {
|
|
152
|
+
const v = old.extracted.get(key[0]!);
|
|
153
|
+
if (del) onto.extracted.delete(key[0]!); else if (v) onto.extracted.set(key[0]!, v);
|
|
154
|
+
}
|
|
155
|
+
for (const { key, del } of marks.recheck.values()) {
|
|
156
|
+
if (del) onto.recheck.delete(key[0]!); else if (old.recheck.has(key[0]!)) onto.recheck.add(key[0]!);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function rowsOf<T>(maps: Map<string, Map<string, T>>, rootId: string): Map<string, T> {
|
|
163
|
+
let m = maps.get(rootId);
|
|
164
|
+
if (!m) maps.set(rootId, m = new Map());
|
|
165
|
+
return m;
|
|
166
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/stores/rowMemory.ts — the in-memory rows of a {@link LocalSnapshotStore}, moved out of it: per-root fact and
|
|
3
|
+
* relation maps updated incrementally (PRD 41 A10 rule 7), the relations-by-source-path index, the extract cache and the
|
|
4
|
+
* re-check set, with the snapshot read and write that go with them. No persistence and no queue: the store owns both.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { Extracted, ScopeRecord, StoredFact, StoredRelation } from '../model.js';
|
|
8
|
+
import { pathOfRef } from '../refs.js';
|
|
9
|
+
import type { RowState } from './rowDelta.js';
|
|
10
|
+
import { relKey, serializeSnapshot, type KnowledgeSnapshot } from './snapshotFormat.js';
|
|
11
|
+
|
|
12
|
+
export class RowMemory implements RowState {
|
|
13
|
+
scopes: ScopeRecord[] = [];
|
|
14
|
+
readonly facts = new Map<string, Map<string, StoredFact>>();
|
|
15
|
+
readonly relations = new Map<string, Map<string, StoredRelation>>();
|
|
16
|
+
readonly extracted = new Map<string, Extracted[]>();
|
|
17
|
+
readonly recheck = new Set<string>();
|
|
18
|
+
/** Per root: source path → keys of the relations touching it (`from` or `to`). */
|
|
19
|
+
private byPath = new Map<string, Map<string, Set<string>>>();
|
|
20
|
+
|
|
21
|
+
factsOf(rootId: string): Map<string, StoredFact> {
|
|
22
|
+
let m = this.facts.get(rootId);
|
|
23
|
+
if (!m) this.facts.set(rootId, m = new Map());
|
|
24
|
+
return m;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
relsOf(rootId: string): Map<string, StoredRelation> {
|
|
28
|
+
let m = this.relations.get(rootId);
|
|
29
|
+
if (!m) this.relations.set(rootId, m = new Map());
|
|
30
|
+
return m;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Upserts a relation and indexes it under the source paths of both ends. */
|
|
34
|
+
putRelation(rootId: string, r: StoredRelation): void {
|
|
35
|
+
this.relsOf(rootId).set(relKey(r), r);
|
|
36
|
+
this.index(rootId, r);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Keys of the root's relations touching a source path. */
|
|
40
|
+
relationKeysAt(rootId: string, path: string): Set<string> | undefined {
|
|
41
|
+
return this.byPath.get(rootId)?.get(path);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Rebuilds the path index from the relation maps (after rows were edited directly). */
|
|
45
|
+
reindex(): void {
|
|
46
|
+
this.byPath = new Map();
|
|
47
|
+
for (const [rootId, m] of this.relations) for (const r of m.values()) this.index(rootId, r);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Puts a snapshot's rows into these (empty) maps; the extract cache only when `withExtracted` (a log owns it otherwise). */
|
|
51
|
+
fill(snap: KnowledgeSnapshot, withExtracted: boolean): void {
|
|
52
|
+
this.scopes = [...snap.scopes];
|
|
53
|
+
for (const h of snap.recheck ?? []) this.recheck.add(h);
|
|
54
|
+
for (const [rootId, rows] of Object.entries(snap.facts)) {
|
|
55
|
+
const m = this.factsOf(rootId);
|
|
56
|
+
if (Array.isArray(rows)) for (const f of rows) m.set(f.key, f);
|
|
57
|
+
}
|
|
58
|
+
for (const [rootId, rows] of Object.entries(snap.relations)) {
|
|
59
|
+
this.relsOf(rootId);
|
|
60
|
+
if (Array.isArray(rows)) for (const r of rows) this.putRelation(rootId, r);
|
|
61
|
+
}
|
|
62
|
+
if (withExtracted) for (const [h, e] of Object.entries(snap.extracted ?? {})) this.extracted.set(h, e);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Canonical text of the rows with the given extract cache; `undefined` omits it (a log owns it). */
|
|
66
|
+
serialize(extracted: Map<string, Extracted[]> | undefined): string {
|
|
67
|
+
return serializeSnapshot({ scopes: this.scopes, facts: this.facts, relations: this.relations, extracted, recheck: this.recheck });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
private index(rootId: string, r: StoredRelation): void {
|
|
71
|
+
const key = relKey(r);
|
|
72
|
+
let idx = this.byPath.get(rootId);
|
|
73
|
+
if (!idx) this.byPath.set(rootId, idx = new Map());
|
|
74
|
+
for (const ref of [r.from, r.to]) {
|
|
75
|
+
const p = pathOfRef(ref);
|
|
76
|
+
if (p === undefined) continue;
|
|
77
|
+
let keys = idx.get(p);
|
|
78
|
+
if (!keys) idx.set(p, keys = new Set());
|
|
79
|
+
keys.add(key);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/stores/rowSync.ts — what a ROW-persisted {@link LocalSnapshotStore} does with its {@link RowPersistence}: write the
|
|
3
|
+
* dirty rows, reload when another writer changed the store, and read extract bodies lazily. The store owns the maps, the mutation
|
|
4
|
+
* queue and the persist chain; this reaches them only through {@link RowHost}.
|
|
5
|
+
*
|
|
6
|
+
* Every step that talks to the host's connection about the whole store (an apply, a changed-elsewhere check with its load) runs on
|
|
7
|
+
* the store's `persisting` chain, so a load never interleaves with an apply and no apply can commit between a load and the
|
|
8
|
+
* `replaceWith` that installs it.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { Extracted } from '../model.js';
|
|
12
|
+
import { RowDelta, type RowPersistence } from './rowDelta.js';
|
|
13
|
+
import { RowMemory } from './rowMemory.js';
|
|
14
|
+
import type { KnowledgeSnapshot } from './snapshotFormat.js';
|
|
15
|
+
|
|
16
|
+
export interface RowHost {
|
|
17
|
+
mem(): RowMemory;
|
|
18
|
+
setMem(next: RowMemory): void;
|
|
19
|
+
/** Runs a task inside the store's mutation queue. */
|
|
20
|
+
enqueue<T>(task: () => Promise<T>): Promise<T>;
|
|
21
|
+
/** Runs a step on the store's persist chain (one at a time, never rejects the chain). */
|
|
22
|
+
chain<T>(step: () => Promise<T>): Promise<T>;
|
|
23
|
+
inBatch(): boolean;
|
|
24
|
+
/** A step is in flight on the persist chain. */
|
|
25
|
+
busy(): boolean;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const PRELOAD_CHUNK = 64;
|
|
29
|
+
|
|
30
|
+
export class RowSync {
|
|
31
|
+
readonly delta = new RowDelta();
|
|
32
|
+
/** The one changed-elsewhere check (with its reload) in flight. */
|
|
33
|
+
private checking: Promise<void> | undefined;
|
|
34
|
+
/** Hashes the host had no body for; cleared by a `putExtracted` of that hash and by every reload. */
|
|
35
|
+
private misses = new Set<string>();
|
|
36
|
+
/** Counts reloads; a miss recorded by a read that started before a reload is dropped. */
|
|
37
|
+
private generation = 0;
|
|
38
|
+
|
|
39
|
+
constructor(readonly rows: RowPersistence, private readonly host: RowHost) {}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Swaps the dirty marks out, writes those rows and, when the host answers with `reloaded`, replaces memory inside the queue. A
|
|
43
|
+
* failed apply puts the marks back under any newer ones. Call it on the persist chain.
|
|
44
|
+
*/
|
|
45
|
+
async apply(): Promise<void> {
|
|
46
|
+
const taken = this.delta.take();
|
|
47
|
+
if (taken.empty) { this.delta.settle(); return; }
|
|
48
|
+
let reloaded: KnowledgeSnapshot | undefined;
|
|
49
|
+
try {
|
|
50
|
+
reloaded = (await this.rows.apply(this.delta.toChange(taken, this.host.mem()))).reloaded;
|
|
51
|
+
} catch (err) {
|
|
52
|
+
this.delta.restore(taken);
|
|
53
|
+
throw err;
|
|
54
|
+
}
|
|
55
|
+
this.delta.settle();
|
|
56
|
+
if (reloaded) await this.host.enqueue(async () => this.replaceWith(reloaded!));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* INSIDE the mutation queue: replaces memory with rows read from the host, keeps the extract bodies it already holds
|
|
61
|
+
* (content-addressed, so never stale), lays this store's unwritten rows back on top and rebuilds the relations-by-path index.
|
|
62
|
+
*/
|
|
63
|
+
private replaceWith(snap: KnowledgeSnapshot): void {
|
|
64
|
+
const old = this.host.mem();
|
|
65
|
+
const next = new RowMemory();
|
|
66
|
+
next.fill(snap, true);
|
|
67
|
+
for (const [h, e] of old.extracted) if (!next.extracted.has(h)) next.extracted.set(h, e);
|
|
68
|
+
this.delta.overlay(old, next);
|
|
69
|
+
next.reindex();
|
|
70
|
+
this.host.setMem(next);
|
|
71
|
+
this.misses.clear();
|
|
72
|
+
this.generation += 1;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Before a read: when another writer changed the store, load and install its rows, as ONE step on the persist chain. None inside a `batched` run; a failed check keeps memory. */
|
|
76
|
+
sync(): Promise<void> {
|
|
77
|
+
const rows = this.rows;
|
|
78
|
+
if (this.checking) return this.checking;
|
|
79
|
+
// A read never waits on persistence (PRD 41 A10): while a persist step is in flight, answer from memory (the next read checks again; an apply's `reloaded` covers other writers).
|
|
80
|
+
if (!rows.changedElsewhere || this.host.inBatch() || this.host.busy()) return Promise.resolve();
|
|
81
|
+
this.checking =this.host.chain(async () => {
|
|
82
|
+
if (!(await rows.changedElsewhere!())) return;
|
|
83
|
+
const snap = await rows.load();
|
|
84
|
+
if (snap) await this.host.enqueue(async () => this.replaceWith(snap));
|
|
85
|
+
}).catch(() => undefined).finally(() => { this.checking = undefined; });
|
|
86
|
+
return this.checking;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** A body not in memory, read through `loadExtracted` once and kept; a miss is remembered until the hash is put or the store reloads. */
|
|
90
|
+
async body(hash: string): Promise<Extracted[] | undefined> {
|
|
91
|
+
const mem = this.host.mem();
|
|
92
|
+
const have = mem.extracted.get(hash);
|
|
93
|
+
if (have || !this.rows.loadExtracted || this.misses.has(hash)) return have;
|
|
94
|
+
const startedIn = this.generation;
|
|
95
|
+
const found = await this.rows.loadExtracted(hash);
|
|
96
|
+
if (!found) { if (startedIn === this.generation) this.misses.add(hash); return undefined; }
|
|
97
|
+
const now = this.host.mem();
|
|
98
|
+
if (!now.extracted.has(hash)) now.extracted.set(hash, found);
|
|
99
|
+
return now.extracted.get(hash);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Reads the bodies of these hashes (those not in memory and not known misses), a chunk at a time. */
|
|
103
|
+
async preload(hashes: readonly string[]): Promise<void> {
|
|
104
|
+
const want = [...new Set(hashes)].filter((h) => !this.host.mem().extracted.has(h) && !this.misses.has(h));
|
|
105
|
+
for (let i = 0; i < want.length; i += PRELOAD_CHUNK) await Promise.all(want.slice(i, i + PRELOAD_CHUNK).map((h) => this.body(h)));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** A `putExtracted` of this hash makes an earlier miss stale. */
|
|
109
|
+
forget(hash: string): void { this.misses.delete(hash); }
|
|
110
|
+
|
|
111
|
+
/** EVERY body: the host's, with the ones in memory winning. Never partial: without `loadAllExtracted` it throws. */
|
|
112
|
+
async allBodies(): Promise<Map<string, Extracted[]>> {
|
|
113
|
+
if (!this.rows.loadAllExtracted) throw new Error('knowledge_dump_needs_all_bodies');
|
|
114
|
+
const all = new Map(Object.entries(await this.rows.loadAllExtracted()));
|
|
115
|
+
for (const [h, e] of this.host.mem().extracted) all.set(h, e);
|
|
116
|
+
return all;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -4,6 +4,10 @@
|
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
import type { Extracted, ScopeRecord, StoredFact, StoredRelation } from '../model.js';
|
|
7
|
+
import { canonicalJson, compareStr } from '../refs.js';
|
|
8
|
+
|
|
9
|
+
/** The unique key of a relation inside its root. */
|
|
10
|
+
export const relKey = (r: { from: string; to: string; kind: string }) => `${r.from}\u0000${r.to}\u0000${r.kind}`;
|
|
7
11
|
|
|
8
12
|
export interface KnowledgeSnapshot {
|
|
9
13
|
version: 1;
|
|
@@ -36,6 +40,32 @@ export function parse(text: string | undefined): KnowledgeSnapshot {
|
|
|
36
40
|
};
|
|
37
41
|
}
|
|
38
42
|
|
|
43
|
+
/** Canonical text of a store's rows: scopes by rootId, facts by key, relations by (from, to, kind), keys sorted. Equal content is equal bytes. */
|
|
44
|
+
export function serializeSnapshot(s: {
|
|
45
|
+
scopes: readonly ScopeRecord[];
|
|
46
|
+
facts: Map<string, Map<string, StoredFact>>;
|
|
47
|
+
relations: Map<string, Map<string, StoredRelation>>;
|
|
48
|
+
/** Omitted from the text when undefined (the extract cache lives in a log). */
|
|
49
|
+
extracted?: Map<string, Extracted[]>;
|
|
50
|
+
recheck: ReadonlySet<string>;
|
|
51
|
+
}): string {
|
|
52
|
+
const rows = <T>(maps: Map<string, Map<string, T>>, by: (a: T, b: T) => number) =>
|
|
53
|
+
Object.fromEntries([...maps.keys()].sort(compareStr).map((k) => [k, [...maps.get(k)!.values()].sort(by)]));
|
|
54
|
+
return canonicalJson({
|
|
55
|
+
version: 1,
|
|
56
|
+
scopes: [...s.scopes].sort((a, b) => compareStr(a.rootId, b.rootId)),
|
|
57
|
+
facts: rows(s.facts, (a, b) => compareStr(a.key, b.key)),
|
|
58
|
+
relations: rows(s.relations, (a, b) => compareStr(relKey(a), relKey(b))),
|
|
59
|
+
...(s.extracted ? { extracted: Object.fromEntries(s.extracted) } : {}),
|
|
60
|
+
...(s.recheck.size > 0 ? { recheck: [...s.recheck].sort(compareStr) } : {}),
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** `o` without its undefined values (a partial write must not blank a field it omits). */
|
|
65
|
+
export function stripUndefined<T extends object>(o: T): Partial<T> {
|
|
66
|
+
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)) as Partial<T>;
|
|
67
|
+
}
|
|
68
|
+
|
|
39
69
|
export interface ParsedLog {
|
|
40
70
|
entries: Map<string, Extracted[]>;
|
|
41
71
|
/** The live (last) line of each hash, newline-terminated, in log order. */
|