@seanhogg/builderforce-memory 2026.10.76 → 2026.10.77

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 (41) hide show
  1. package/dist/knowledge/facts/factsHash.d.ts +27 -0
  2. package/dist/knowledge/facts/factsHash.d.ts.map +1 -0
  3. package/dist/knowledge/facts/factsHash.js +67 -0
  4. package/dist/knowledge/facts/factsHash.js.map +1 -0
  5. package/dist/knowledge/facts/fileFacts.d.ts +70 -12
  6. package/dist/knowledge/facts/fileFacts.d.ts.map +1 -1
  7. package/dist/knowledge/facts/fileFacts.js +42 -33
  8. package/dist/knowledge/facts/fileFacts.js.map +1 -1
  9. package/dist/knowledge/facts/guards.d.ts +101 -0
  10. package/dist/knowledge/facts/guards.d.ts.map +1 -0
  11. package/dist/knowledge/facts/guards.js +260 -0
  12. package/dist/knowledge/facts/guards.js.map +1 -0
  13. package/dist/knowledge/index.d.ts +9 -1
  14. package/dist/knowledge/index.d.ts.map +1 -1
  15. package/dist/knowledge/index.js +7 -1
  16. package/dist/knowledge/index.js.map +1 -1
  17. package/dist/knowledge/rules/evaluateRules.d.ts.map +1 -1
  18. package/dist/knowledge/rules/evaluateRules.js +2 -1
  19. package/dist/knowledge/rules/evaluateRules.js.map +1 -1
  20. package/dist/knowledge/rules/factGraph.d.ts +2 -0
  21. package/dist/knowledge/rules/factGraph.d.ts.map +1 -1
  22. package/dist/knowledge/rules/factGraph.js +6 -2
  23. package/dist/knowledge/rules/factGraph.js.map +1 -1
  24. package/dist/knowledge/rules/factStore.d.ts +139 -0
  25. package/dist/knowledge/rules/factStore.d.ts.map +1 -0
  26. package/dist/knowledge/rules/factStore.js +252 -0
  27. package/dist/knowledge/rules/factStore.js.map +1 -0
  28. package/package.json +1 -1
  29. package/src/contract/exports.snapshot.json +14 -0
  30. package/src/contract/types.contract.test.ts +57 -2
  31. package/src/knowledge/facts/factsHash.test.ts +50 -0
  32. package/src/knowledge/facts/factsHash.ts +71 -0
  33. package/src/knowledge/facts/fileFacts.test.ts +2 -1
  34. package/src/knowledge/facts/fileFacts.ts +104 -36
  35. package/src/knowledge/facts/guards.test.ts +276 -0
  36. package/src/knowledge/facts/guards.ts +296 -0
  37. package/src/knowledge/index.ts +13 -1
  38. package/src/knowledge/rules/evaluateRules.ts +2 -1
  39. package/src/knowledge/rules/factGraph.ts +8 -2
  40. package/src/knowledge/rules/factStore.test.ts +303 -0
  41. package/src/knowledge/rules/factStore.ts +317 -0
@@ -0,0 +1,139 @@
1
+ /**
2
+ * knowledge/rules/factStore.ts — the FACT STORE PORT (PRD 41 §B4) and the pure functions that persist, restore and sweep
3
+ * a {@link FactGraph} through it. No I/O here; {@link memoryFactStore} is the in-memory reference adapter.
4
+ *
5
+ * The graph maps onto the port 1:1:
6
+ * - OBJECTS: each `FileFacts` as its canonical JSON (`factsJson`) under its content address `factsHash`. Write-once.
7
+ * - MANIFEST: path → {@link FactManifestEntry} (`factsHash`, `contentHash`, kind hashes), stamped with a
8
+ * {@link FactStoreVersion}: an `epoch` (a random id minted when the store is created or reset) and a `generation`
9
+ * bumped by every manifest write and every sweep.
10
+ * - DERIVED: each {@link DerivedRow} under {@link derivedRowKey}, carrying its input-hash trace (`inputs`).
11
+ *
12
+ * Commit order: objects first, then the manifest delta and the derived puts/deletes in ONE transaction (`writeManifest`,
13
+ * compare-and-swap on the version). A write interrupted between the two leaves the previous manifest valid — it references
14
+ * only objects that already existed — and at worst unreferenced objects, which {@link sweepFactStore} removes.
15
+ *
16
+ * ADAPTERS:
17
+ * - Node (VSIX, on-prem): the G03 SQLite store (`localRecordTransaction`): an `extracted(hash PRIMARY KEY, json)` table
18
+ * plus manifest, derived and version rows in one `index.sqlite`. `writeManifest` and `sweepObjects` run in ONE
19
+ * `BEGIN IMMEDIATE` transaction each (the write lock is taken before the version is compared, so two processes never
20
+ * both pass the check). Adapter-private columns (stat, git blob id) never cross the port and never enter the dump (§B8.3).
21
+ * - Worker: the port needs a transactional compare-and-swap over manifest + derived. Put it behind a Durable Object
22
+ * (transactional storage), or keep manifest + derived as ONE R2 object written with an `onlyIf` etag precondition and
23
+ * the objects as R2 objects under their hash. Plain KV (eventually consistent, no CAS) cannot implement this port.
24
+ *
25
+ * HOST CONTRACT (recovery):
26
+ * - Saves to one store are SERIALIZED within a process (one writer queue per store); the version CAS guards only against
27
+ * other processes.
28
+ * - `fact_store_generation_conflict` (another writer, or a sweep, moved the store): `loadFactGraph`, re-apply the pending
29
+ * `FactChange`s with `updateFactGraph`, then `saveFactGraph` with the loaded {@link StoredFactGraph}; retry a bounded
30
+ * number of times (e.g. 3), then give up until the next change.
31
+ * - `fact_store_object_missing` / `fact_store_object_corrupt` / `fact_store_manifest_corrupt` / `fact_store_derived_corrupt`:
32
+ * the store is a disposable cache (§B1: it rebuilds to the same bytes) — call `reset()` and rebuild from the files.
33
+ */
34
+ import { type DerivedRow } from './evaluateRules.js';
35
+ import { type FactGraph, type FactManifestEntry } from './factGraph.js';
36
+ /** A value or a promise of it: the SQLite adapter is synchronous, the Durable Object / R2 one is not. */
37
+ export type Awaitable<T> = T | Promise<T>;
38
+ /** Which store (`epoch`, minted on create and on `reset()`) and which state of it (`generation`, 0 when empty). */
39
+ export interface FactStoreVersion {
40
+ epoch: string;
41
+ generation: number;
42
+ }
43
+ /** The stored manifest: path → entry, at a version. */
44
+ export interface FactStoreManifest extends FactStoreVersion {
45
+ files: ReadonlyMap<string, FactManifestEntry>;
46
+ }
47
+ /** One manifest write: the entries put and the paths deleted, committed as `generation` (stored + 1) of `epoch`. */
48
+ export interface FactManifestDelta extends FactStoreVersion {
49
+ puts: ReadonlyMap<string, FactManifestEntry>;
50
+ deletes: readonly string[];
51
+ }
52
+ export interface FactStorePort {
53
+ /** The stored JSON of each hash present (absent hashes are left out). */
54
+ getObjects(hashes: readonly string[]): Awaitable<ReadonlyMap<string, string>>;
55
+ /** Stores objects (hash → JSON). WRITE-ONCE: an existing hash is left as it is. */
56
+ putObjects(objects: ReadonlyMap<string, string>): Awaitable<void>;
57
+ /** The version alone (cheap): what a load re-reads to detect a write that landed under it. */
58
+ readVersion(): Awaitable<FactStoreVersion>;
59
+ readManifest(): Awaitable<FactStoreManifest>;
60
+ /**
61
+ * ONE transaction: compares the version (`manifest.epoch` must be the stored epoch and `manifest.generation` the stored
62
+ * generation + 1, else `fact_store_generation_conflict`), checks that every put's object exists (else
63
+ * `fact_store_object_missing`), applies the manifest delta, puts the derived rows (by {@link derivedRowKey}) and
64
+ * deletes the derived keys.
65
+ */
66
+ writeManifest(manifest: FactManifestDelta, derivedPuts: readonly DerivedRow[], derivedDeletes: readonly string[]): Awaitable<void>;
67
+ /** Every stored derived row by its key (bulk; the load path). */
68
+ derivedRows(): Awaitable<ReadonlyMap<string, DerivedRow>>;
69
+ /**
70
+ * ONE transaction: compares the version with `expected` (else `fact_store_generation_conflict`) and deletes every object
71
+ * the manifest does not reference; when it deleted any, it bumps the generation (a no-op sweep leaves the version as it
72
+ * was). Returns how many it deleted. The bump makes a writer that put objects before the sweep conflict on its
73
+ * `writeManifest`, so it re-puts them on retry.
74
+ */
75
+ sweepObjects(expected: FactStoreVersion): Awaitable<number>;
76
+ /** Drops everything and mints a new epoch at generation 0 (the recovery for a corrupt store). */
77
+ reset(): Awaitable<void>;
78
+ }
79
+ /** A graph and the store version it was loaded or saved at: what a later save diffs against. */
80
+ export interface StoredFactGraph extends FactStoreVersion {
81
+ graph: FactGraph;
82
+ }
83
+ /** What a save wrote, and the stored graph to pass as `previous` to the next save. */
84
+ export interface FactStoreSaveResult extends StoredFactGraph {
85
+ /** Objects put (hashes, sorted). */
86
+ objects: string[];
87
+ /** Manifest paths put and deleted (sorted). */
88
+ puts: string[];
89
+ deletes: string[];
90
+ /** Derived keys put and deleted (sorted). */
91
+ derivedPuts: string[];
92
+ derivedDeletes: string[];
93
+ }
94
+ /**
95
+ * Persists `graph`, writing ONLY the delta against what the store holds: the objects of new or changed manifest entries,
96
+ * the manifest entries that moved, the derived rows that moved and the keys that went away. Derived rows are diffed by
97
+ * identity against `previous.graph` (a reused row is the same object) ONLY when `previous` is at the stored epoch and
98
+ * generation; otherwise against the stored rows. Rejects `fact_store_generation_conflict` when another writer committed
99
+ * in between (see the recovery contract in the header).
100
+ */
101
+ export declare function saveFactGraph(port: FactStorePort, graph: FactGraph, previous?: StoredFactGraph): Promise<FactStoreSaveResult>;
102
+ export interface LoadFactGraphOptions {
103
+ /**
104
+ * `full` (default; tests, the oracle): every object must hash to its address, and every manifest entry must match its
105
+ * object. `manifest`: trusts the stored address and checks only each entry's content hash and kind hashes against its
106
+ * object (cheaper on a large store; a corruption that leaves those intact goes unnoticed).
107
+ */
108
+ verify?: 'full' | 'manifest';
109
+ }
110
+ /** How many times a load retries when a write lands under it before rejecting `fact_store_generation_conflict:load`. */
111
+ export declare const FACT_STORE_LOAD_ATTEMPTS = 3;
112
+ /**
113
+ * Restores the graph the store holds, with the version it was read at: the manifest, every referenced object (read through
114
+ * `readFileFacts`, so an object written before an additive field existed reads with that field empty) and every derived
115
+ * row with its trace. The result continues under `updateFactGraph` with early cutoff intact: a row whose trace still holds
116
+ * is reused, not rerun. The version is re-read after the rows: a write that landed mid-load (or a sweep that removed an
117
+ * object it was about to read) retries, up to {@link FACT_STORE_LOAD_ATTEMPTS}, so a graph never mixes generations (§B8.4).
118
+ * Throws the corruption errors of the header when the store itself is bad.
119
+ */
120
+ export declare function loadFactGraph(port: FactStorePort, opts?: LoadFactGraphOptions): Promise<StoredFactGraph>;
121
+ /**
122
+ * The store's canonical dump (§B8.6, the port's `canonicalDump()`): sorted canonical JSON of the manifest, the referenced
123
+ * objects and the derived rows — exactly `factGraphDump` of the loaded graph, so a store and the graph it was saved from
124
+ * dump to the same bytes. Versions, storage layout and unreferenced objects never take part.
125
+ */
126
+ export declare function factStoreDump(port: FactStorePort): Promise<string>;
127
+ /**
128
+ * Removes the objects the current manifest does not reference (§B4 sweep; run when idle). Rejects
129
+ * `fact_store_generation_conflict` when a write lands between reading the version and the sweep; the next idle sweep
130
+ * catches up. Returns how many objects it deleted.
131
+ */
132
+ export declare function sweepFactStore(port: FactStorePort): Promise<number>;
133
+ /** The in-memory reference adapter (tests, a Worker's per-request graph). Stores JSON, so a load is a real round trip. */
134
+ export interface MemoryFactStore extends FactStorePort {
135
+ /** Every stored object hash, referenced or not (sorted). */
136
+ objectHashes(): string[];
137
+ }
138
+ export declare function memoryFactStore(): MemoryFactStore;
139
+ //# sourceMappingURL=factStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"factStore.d.ts","sourceRoot":"","sources":["../../../src/knowledge/rules/factStore.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAKH,OAAO,EAAiB,KAAK,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAoC,KAAK,SAAS,EAAE,KAAK,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAE1G,yGAAyG;AACzG,MAAM,MAAM,SAAS,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAE1C,mHAAmH;AACnH,MAAM,WAAW,gBAAgB;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;CACtB;AAED,uDAAuD;AACvD,MAAM,WAAW,iBAAkB,SAAQ,gBAAgB;IACvD,KAAK,EAAE,WAAW,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC;CACjD;AAED,oHAAoH;AACpH,MAAM,WAAW,iBAAkB,SAAQ,gBAAgB;IACvD,IAAI,EAAE,WAAW,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC;IAC7C,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;CAC9B;AAED,MAAM,WAAW,aAAa;IAC1B,yEAAyE;IACzE,UAAU,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,CAAC,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;I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H,MAAM,CAAC,EAAE,MAAM,GAAG,UAAU,CAAC;CAChC;AAED,wHAAwH;AACxH,eAAO,MAAM,wBAAwB,IAAI,CAAC;AAoC1C;;;;;;;GAOG;AACH,wBAAsB,aAAa,CAAC,IAAI,EAAE,aAAa,EAAE,IAAI,GAAE,oBAAyB,GAAG,OAAO,CAAC,eAAe,CAAC,CAclH;AAED;;;;GAIG;AACH,wBAAsB,aAAa,CAAC,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC,CAExE;AAED;;;;GAIG;AACH,wBAAsB,cAAc,CAAC,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC,CAEzE;AAED,0HAA0H;AAC1H,MAAM,WAAW,eAAgB,SAAQ,aAAa;IAClD,4DAA4D;IAC5D,YAAY,IAAI,MAAM,EAAE,CAAC;CAC5B;AAQD,wBAAgB,eAAe,IAAI,eAAe,CAoDjD"}
@@ -0,0 +1,252 @@
1
+ /**
2
+ * knowledge/rules/factStore.ts — the FACT STORE PORT (PRD 41 §B4) and the pure functions that persist, restore and sweep
3
+ * a {@link FactGraph} through it. No I/O here; {@link memoryFactStore} is the in-memory reference adapter.
4
+ *
5
+ * The graph maps onto the port 1:1:
6
+ * - OBJECTS: each `FileFacts` as its canonical JSON (`factsJson`) under its content address `factsHash`. Write-once.
7
+ * - MANIFEST: path → {@link FactManifestEntry} (`factsHash`, `contentHash`, kind hashes), stamped with a
8
+ * {@link FactStoreVersion}: an `epoch` (a random id minted when the store is created or reset) and a `generation`
9
+ * bumped by every manifest write and every sweep.
10
+ * - DERIVED: each {@link DerivedRow} under {@link derivedRowKey}, carrying its input-hash trace (`inputs`).
11
+ *
12
+ * Commit order: objects first, then the manifest delta and the derived puts/deletes in ONE transaction (`writeManifest`,
13
+ * compare-and-swap on the version). A write interrupted between the two leaves the previous manifest valid — it references
14
+ * only objects that already existed — and at worst unreferenced objects, which {@link sweepFactStore} removes.
15
+ *
16
+ * ADAPTERS:
17
+ * - Node (VSIX, on-prem): the G03 SQLite store (`localRecordTransaction`): an `extracted(hash PRIMARY KEY, json)` table
18
+ * plus manifest, derived and version rows in one `index.sqlite`. `writeManifest` and `sweepObjects` run in ONE
19
+ * `BEGIN IMMEDIATE` transaction each (the write lock is taken before the version is compared, so two processes never
20
+ * both pass the check). Adapter-private columns (stat, git blob id) never cross the port and never enter the dump (§B8.3).
21
+ * - Worker: the port needs a transactional compare-and-swap over manifest + derived. Put it behind a Durable Object
22
+ * (transactional storage), or keep manifest + derived as ONE R2 object written with an `onlyIf` etag precondition and
23
+ * the objects as R2 objects under their hash. Plain KV (eventually consistent, no CAS) cannot implement this port.
24
+ *
25
+ * HOST CONTRACT (recovery):
26
+ * - Saves to one store are SERIALIZED within a process (one writer queue per store); the version CAS guards only against
27
+ * other processes.
28
+ * - `fact_store_generation_conflict` (another writer, or a sweep, moved the store): `loadFactGraph`, re-apply the pending
29
+ * `FactChange`s with `updateFactGraph`, then `saveFactGraph` with the loaded {@link StoredFactGraph}; retry a bounded
30
+ * number of times (e.g. 3), then give up until the next change.
31
+ * - `fact_store_object_missing` / `fact_store_object_corrupt` / `fact_store_manifest_corrupt` / `fact_store_derived_corrupt`:
32
+ * the store is a disposable cache (§B1: it rebuilds to the same bytes) — call `reset()` and rebuild from the files.
33
+ */
34
+ import { canonicalJson, compareStr } from '../refs.js';
35
+ import { readFileFacts } from '../facts/fileFacts.js';
36
+ import { factKindHashes, factsHash, factsJson } from '../facts/factsHash.js';
37
+ import { derivedRowKey } from './evaluateRules.js';
38
+ import { factGraphDump, sameManifestEntry } from './factGraph.js';
39
+ const rowJson = (row) => canonicalJson(row);
40
+ const sameVersion = (a, b) => a.epoch === b.epoch && a.generation === b.generation;
41
+ const conflict = (why) => new Error(`fact_store_generation_conflict:${why}`);
42
+ /**
43
+ * Persists `graph`, writing ONLY the delta against what the store holds: the objects of new or changed manifest entries,
44
+ * the manifest entries that moved, the derived rows that moved and the keys that went away. Derived rows are diffed by
45
+ * identity against `previous.graph` (a reused row is the same object) ONLY when `previous` is at the stored epoch and
46
+ * generation; otherwise against the stored rows. Rejects `fact_store_generation_conflict` when another writer committed
47
+ * in between (see the recovery contract in the header).
48
+ */
49
+ export async function saveFactGraph(port, graph, previous) {
50
+ const stored = await port.readManifest();
51
+ const puts = new Map();
52
+ for (const [path, e] of graph.manifest)
53
+ if (!sameManifestEntry(e, stored.files.get(path)))
54
+ puts.set(path, e);
55
+ const deletes = [...stored.files.keys()].filter((p) => !graph.manifest.has(p)).sort(compareStr);
56
+ const objects = [...new Set([...puts.values()].map((e) => e.factsHash))].sort(compareStr);
57
+ if (objects.length > 0) {
58
+ const jsons = new Map();
59
+ for (const hash of objects) {
60
+ const facts = graph.objects.get(hash);
61
+ if (!facts)
62
+ throw new Error(`fact_store_object_missing:${hash}`);
63
+ jsons.set(hash, factsJson(facts));
64
+ }
65
+ await port.putObjects(jsons);
66
+ }
67
+ const derivedPuts = [];
68
+ let derivedDeletes;
69
+ if (previous && sameVersion(previous, stored)) {
70
+ for (const [key, row] of graph.derived)
71
+ if (previous.graph.derived.get(key) !== row)
72
+ derivedPuts.push(row);
73
+ derivedDeletes = [...previous.graph.derived.keys()].filter((k) => !graph.derived.has(k));
74
+ }
75
+ else {
76
+ const rows = await port.derivedRows();
77
+ for (const [key, row] of graph.derived) {
78
+ const prior = rows.get(key);
79
+ if (!prior || rowJson(prior) !== rowJson(row))
80
+ derivedPuts.push(row);
81
+ }
82
+ derivedDeletes = [...rows.keys()].filter((k) => !graph.derived.has(k));
83
+ }
84
+ derivedPuts.sort((a, b) => compareStr(derivedRowKey(a.rule, a.focus), derivedRowKey(b.rule, b.focus)));
85
+ derivedDeletes.sort(compareStr);
86
+ const generation = stored.generation + 1;
87
+ await port.writeManifest({ epoch: stored.epoch, generation, puts, deletes }, derivedPuts, derivedDeletes);
88
+ return {
89
+ epoch: stored.epoch,
90
+ generation,
91
+ graph,
92
+ objects,
93
+ puts: [...puts.keys()].sort(compareStr),
94
+ deletes,
95
+ derivedPuts: derivedPuts.map((r) => derivedRowKey(r.rule, r.focus)),
96
+ derivedDeletes,
97
+ };
98
+ }
99
+ /** How many times a load retries when a write lands under it before rejecting `fact_store_generation_conflict:load`. */
100
+ export const FACT_STORE_LOAD_ATTEMPTS = 3;
101
+ async function loadOnce(port, stored, verify) {
102
+ const hashes = [...new Set([...stored.files.values()].map((e) => e.factsHash))].sort(compareStr);
103
+ const raw = await port.getObjects(hashes);
104
+ const objects = new Map();
105
+ for (const hash of hashes) {
106
+ const json = raw.get(hash);
107
+ if (json === undefined)
108
+ throw new Error(`fact_store_object_missing:${hash}`);
109
+ let facts;
110
+ try {
111
+ facts = readFileFacts(JSON.parse(json));
112
+ }
113
+ catch {
114
+ throw new Error(`fact_store_object_corrupt:${hash}`);
115
+ }
116
+ if (verify === 'full' && factsHash(facts) !== hash)
117
+ throw new Error(`fact_store_object_corrupt:${hash}`);
118
+ objects.set(hash, facts);
119
+ }
120
+ const manifest = new Map();
121
+ for (const path of [...stored.files.keys()].sort(compareStr)) {
122
+ const e = stored.files.get(path);
123
+ const facts = objects.get(e.factsHash);
124
+ const entry = { contentHash: facts.contentHash, factsHash: e.factsHash, kinds: factKindHashes(facts) };
125
+ if (!sameManifestEntry(e, entry))
126
+ throw new Error(`fact_store_manifest_corrupt:${path}`);
127
+ manifest.set(path, entry);
128
+ }
129
+ const derived = new Map();
130
+ const rows = await port.derivedRows();
131
+ for (const key of [...rows.keys()].sort(compareStr)) {
132
+ const row = rows.get(key);
133
+ if (derivedRowKey(row.rule, row.focus) !== key)
134
+ throw new Error(`fact_store_derived_corrupt:${key}`);
135
+ derived.set(key, row);
136
+ }
137
+ return { manifest, objects, derived };
138
+ }
139
+ /**
140
+ * Restores the graph the store holds, with the version it was read at: the manifest, every referenced object (read through
141
+ * `readFileFacts`, so an object written before an additive field existed reads with that field empty) and every derived
142
+ * row with its trace. The result continues under `updateFactGraph` with early cutoff intact: a row whose trace still holds
143
+ * is reused, not rerun. The version is re-read after the rows: a write that landed mid-load (or a sweep that removed an
144
+ * object it was about to read) retries, up to {@link FACT_STORE_LOAD_ATTEMPTS}, so a graph never mixes generations (§B8.4).
145
+ * Throws the corruption errors of the header when the store itself is bad.
146
+ */
147
+ export async function loadFactGraph(port, opts = {}) {
148
+ const verify = opts.verify ?? 'full';
149
+ for (let attempt = 0; attempt < FACT_STORE_LOAD_ATTEMPTS; attempt++) {
150
+ const stored = await port.readManifest();
151
+ let graph;
152
+ try {
153
+ graph = await loadOnce(port, stored, verify);
154
+ }
155
+ catch (err) {
156
+ if (!sameVersion(stored, await port.readVersion()))
157
+ continue;
158
+ throw err;
159
+ }
160
+ if (sameVersion(stored, await port.readVersion()))
161
+ return { epoch: stored.epoch, generation: stored.generation, graph };
162
+ }
163
+ throw conflict('load');
164
+ }
165
+ /**
166
+ * The store's canonical dump (§B8.6, the port's `canonicalDump()`): sorted canonical JSON of the manifest, the referenced
167
+ * objects and the derived rows — exactly `factGraphDump` of the loaded graph, so a store and the graph it was saved from
168
+ * dump to the same bytes. Versions, storage layout and unreferenced objects never take part.
169
+ */
170
+ export async function factStoreDump(port) {
171
+ return factGraphDump((await loadFactGraph(port)).graph);
172
+ }
173
+ /**
174
+ * Removes the objects the current manifest does not reference (§B4 sweep; run when idle). Rejects
175
+ * `fact_store_generation_conflict` when a write lands between reading the version and the sweep; the next idle sweep
176
+ * catches up. Returns how many objects it deleted.
177
+ */
178
+ export async function sweepFactStore(port) {
179
+ return port.sweepObjects(await port.readVersion());
180
+ }
181
+ let epochCounter = 0;
182
+ function newEpoch() {
183
+ const uuid = globalThis.crypto?.randomUUID?.();
184
+ return uuid ?? `epoch-${Date.now().toString(36)}-${(epochCounter++).toString(36)}-${Math.random().toString(36).slice(2)}`;
185
+ }
186
+ export function memoryFactStore() {
187
+ const objects = new Map();
188
+ let manifest = new Map();
189
+ let derived = new Map();
190
+ let epoch = newEpoch();
191
+ let generation = 0;
192
+ const check = (expected, nextGeneration) => {
193
+ if (expected.epoch !== epoch || nextGeneration !== generation + 1) {
194
+ throw conflict(`${epoch}@${generation}->${expected.epoch}@${expected.generation}`);
195
+ }
196
+ };
197
+ return {
198
+ getObjects: (hashes) => new Map(hashes.filter((h) => objects.has(h)).map((h) => [h, objects.get(h)])),
199
+ putObjects: (puts) => { for (const [h, json] of puts)
200
+ if (!objects.has(h))
201
+ objects.set(h, json); },
202
+ readVersion: () => ({ epoch, generation }),
203
+ readManifest: () => ({
204
+ epoch,
205
+ generation,
206
+ files: new Map([...manifest].map(([p, json]) => [p, JSON.parse(json)])),
207
+ }),
208
+ writeManifest: (delta, derivedPuts, derivedDeletes) => {
209
+ check(delta, delta.generation);
210
+ for (const e of delta.puts.values())
211
+ if (!objects.has(e.factsHash))
212
+ throw new Error(`fact_store_object_missing:${e.factsHash}`);
213
+ // Stage, then swap: all or nothing.
214
+ const next = new Map(manifest);
215
+ for (const [p, e] of delta.puts)
216
+ next.set(p, canonicalJson(e));
217
+ for (const p of delta.deletes)
218
+ next.delete(p);
219
+ const rows = new Map(derived);
220
+ for (const row of derivedPuts)
221
+ rows.set(derivedRowKey(row.rule, row.focus), rowJson(row));
222
+ for (const key of derivedDeletes)
223
+ rows.delete(key);
224
+ manifest = next;
225
+ derived = rows;
226
+ generation = delta.generation;
227
+ },
228
+ derivedRows: () => new Map([...derived].map(([k, json]) => [k, JSON.parse(json)])),
229
+ sweepObjects: (expected) => {
230
+ check(expected, expected.generation + 1);
231
+ const live = new Set([...manifest.values()].map((json) => JSON.parse(json).factsHash));
232
+ let removed = 0;
233
+ for (const h of [...objects.keys()])
234
+ if (!live.has(h)) {
235
+ objects.delete(h);
236
+ removed++;
237
+ }
238
+ if (removed > 0)
239
+ generation += 1;
240
+ return removed;
241
+ },
242
+ reset: () => {
243
+ objects.clear();
244
+ manifest = new Map();
245
+ derived = new Map();
246
+ epoch = newEpoch();
247
+ generation = 0;
248
+ },
249
+ objectHashes: () => [...objects.keys()].sort(compareStr),
250
+ };
251
+ }
252
+ //# sourceMappingURL=factStore.js.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K,CAAC,IAAI,CAAuB,CAAC,SAAS,CAAC,CAAC,CAAC;YAC9G,IAAI,OAAO,GAAG,CAAC,CAAC;YAChB,KAAK,MAAM,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;gBAAE,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;oBAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;oBAAC,OAAO,EAAE,CAAC;gBAAC,CAAC;YACxF,IAAI,OAAO,GAAG,CAAC;gBAAE,UAAU,IAAI,CAAC,CAAC;YACjC,OAAO,OAAO,CAAC;QACnB,CAAC;QACD,KAAK,EAAE,GAAG,EAAE;YACR,OAAO,CAAC,KAAK,EAAE,CAAC;YAChB,QAAQ,GAAG,IAAI,GAAG,EAAE,CAAC;YACrB,OAAO,GAAG,IAAI,GAAG,EAAE,CAAC;YACpB,KAAK,GAAG,QAAQ,EAAE,CAAC;YACnB,UAAU,GAAG,CAAC,CAAC;QACnB,CAAC;QACD,YAAY,EAAE,GAAG,EAAE,CAAC,CAAC,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC;KAC3D,CAAC;AACN,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seanhogg/builderforce-memory",
3
- "version": "2026.10.76",
3
+ "version": "2026.10.77",
4
4
  "description": "BuilderForce Agent Memory — runtime layer. SSM execution, Transformer orchestration, online distillation, enterprise RAG (ingestion pipelines, vector-store adapters, tenant/ACL-scoped hybrid retrieval), multi-agent graph orchestration, LLM telemetry and cost accounting, persistent agent memory, and token-saving agent-run memory (code maps, a prompt-cache-safe working memory, chunked transcript windowing) for BuilderForce.ai agents.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",
@@ -304,6 +304,7 @@
304
304
  "FACT_GRAPH_DUMP_VERSION",
305
305
  "FACT_KINDS",
306
306
  "FACT_KIND_FIELDS",
307
+ "FACT_STORE_LOAD_ATTEMPTS",
307
308
  "FALLBACK_PACK_ID",
308
309
  "GENERIC_FINDING_RULES",
309
310
  "GOD_MODULE_KIND",
@@ -317,6 +318,7 @@
317
318
  "MAX_CALL_SITES_PER_EDGE",
318
319
  "MAX_CLAIM_TEXT_CHARS",
319
320
  "MAX_FINDING_NODES",
321
+ "MAX_MOUNT_DEPTH",
320
322
  "MAX_NODES_CAP",
321
323
  "MAX_QUOTE_CHARS",
322
324
  "MAX_QUOTE_LINES",
@@ -385,6 +387,7 @@
385
387
  "defineRule",
386
388
  "derivedRowKey",
387
389
  "detectCommunities",
390
+ "effectiveGuards",
388
391
  "emptyFactGraph",
389
392
  "encodeCoChange",
390
393
  "entityKey",
@@ -399,8 +402,11 @@
399
402
  "factKeyOf",
400
403
  "factKindHashes",
401
404
  "factRef",
405
+ "factStoreDump",
402
406
  "factsExtractorTag",
403
407
  "factsHash",
408
+ "factsJson",
409
+ "factsWireForm",
404
410
  "failureTotal",
405
411
  "failuresOf",
406
412
  "fileRefOf",
@@ -429,23 +435,27 @@
429
435
  "isRootFilePath",
430
436
  "isSymbolEdgeKind",
431
437
  "jobOf",
438
+ "joinRoutePath",
432
439
  "judgedManifestKey",
433
440
  "kindOfAnchor",
434
441
  "knowledgeFacts",
435
442
  "knowledgeInputHash",
436
443
  "knownKeysOf",
437
444
  "knownKeysOfEntities",
445
+ "loadFactGraph",
438
446
  "loadKnowledgeIndex",
439
447
  "loadPartitions",
440
448
  "localSnapshotStore",
441
449
  "matchGlob",
442
450
  "matchLineage",
443
451
  "mediaTypeOfPath",
452
+ "memoryFactStore",
444
453
  "merkleTree",
445
454
  "mostLikelyWalk",
446
455
  "nameResolver",
447
456
  "normalizeAnalysis",
448
457
  "normalizeKey",
458
+ "normalizeMountPrefix",
449
459
  "normalizePath",
450
460
  "normalizeSnippet",
451
461
  "oneLineLabel",
@@ -476,9 +486,12 @@
476
486
  "resolveEntities",
477
487
  "resolveRelativePath",
478
488
  "reviewDirectory",
489
+ "rootRouters",
490
+ "routePathCovers",
479
491
  "runEta",
480
492
  "runKnowledgeRules",
481
493
  "runRate",
494
+ "saveFactGraph",
482
495
  "sha256",
483
496
  "sha256Hex",
484
497
  "slowestSteps",
@@ -487,6 +500,7 @@
487
500
  "srcRef",
488
501
  "startRun",
489
502
  "stationTransitions",
503
+ "sweepFactStore",
490
504
  "toCards",
491
505
  "toMermaid",
492
506
  "traceGraph",
@@ -42,6 +42,12 @@ import type {
42
42
  FactGraphUpdate, FactKind, FactRule, FileFacts, RuleEvaluation, RuleScope, RuleWorld, TestCaseFact, TestFacts,
43
43
  evaluateRules, factGraphDump, factsExtractorTag, updateFactGraph,
44
44
  } from '../knowledge/index.js';
45
+ import type {
46
+ Awaitable, DerivedRow, EffectiveEntryPoint, EffectiveGuardsOptions, EffectiveGuardsResult, FactManifestDelta, FactManifestEntry,
47
+ FactStoreManifest, FactStorePort, FactStoreSaveResult, FactStoreVersion, LoadFactGraphOptions, MemoryFactStore, MountFact, ResolvedMount,
48
+ StoredFactGraph, UseFact, RootRouter, MountTarget,
49
+ effectiveGuards, factStoreDump, loadFactGraph, memoryFactStore, rootRouters, saveFactGraph, sweepFactStore,
50
+ } from '../knowledge/index.js';
45
51
  import { canonicalDump, ExtractFailed, failuresOf, failureTotal, LocalSnapshotStore, localSnapshotStore, type ExtractorState } from '../knowledge/index.js';
46
52
 
47
53
  type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
@@ -389,12 +395,14 @@ export type isBinaryBytes_signature = Expect<Equal<typeof isBinaryBytes, (bytes:
389
395
  /* ── FileFacts v3, FactRule, the fact graph (PRD 41 §B1/§B3/§B5) ──────────────────────────────────────────── */
390
396
  // The Phase 2 extractors (agent-tools, tree-sitter) emit exactly this shape; run-delta rules read it.
391
397
  export type FactKind_values = Expect<Equal<FactKind, 'body' | 'content' | 'structure'>>;
398
+ // 2026-11-10 (additive, §C5.1): + optional `mounts` and `uses`.
392
399
  export type FileFacts_keys = Expect<Equal<keyof FileFacts,
393
400
  'factsVersion' | 'extractor' | 'language' | 'contentHash' | 'symbols' | 'imports' | 'exports' | 'entryPoints'
394
- | 'calls' | 'complexity' | 'capabilityImports' | 'testFacts'>>;
401
+ | 'calls' | 'complexity' | 'capabilityImports' | 'testFacts' | 'mounts' | 'uses'>>;
395
402
  export type FileFacts_testFacts_is_optional = Expect<Equal<IsOptional<FileFacts, 'testFacts'>, true>>;
403
+ // 2026-11-10 (additive, §C5.1): + optional registration `order` and `router`.
396
404
  export type EntryPointFact_shape = Expect<Equal<EntryPointFact, {
397
- kind: EntryPointKind; key: string; symbol: string; guards: string[]; inputs: string[]; chain: string[];
405
+ kind: EntryPointKind; key: string; symbol: string; guards: string[]; inputs: string[]; chain: string[]; order?: number; router?: string;
398
406
  }>>;
399
407
  export type ExportFact_keys = Expect<Equal<keyof ExportFact, 'name' | 'kind' | 'signatureHash' | 'from'>>;
400
408
  export type CallFact_keys = Expect<Equal<keyof CallFact, 'callee' | 'enclosing' | 'awaited' | 'inLoop' | 'count'>>;
@@ -412,6 +420,53 @@ export type updateFactGraph_signature = Expect<Equal<
412
420
  >>;
413
421
  export type factGraphDump_signature = Expect<Equal<typeof factGraphDump, (graph: FactGraph) => string>>;
414
422
 
423
+ /* ── FactStorePort (PRD 41 §B4) and router mounts (§C5.1) ──────────────────────────────────────────────────── */
424
+ // Node hosts implement the port on the G03 SQLite store, the Worker behind a Durable Object (or one R2 object with an
425
+ // `onlyIf` etag); memory owns the shape and the save / load / sweep.
426
+ export type FileFacts_mounts_is_optional = Expect<Equal<IsOptional<FileFacts, 'mounts'>, true>>;
427
+ export type FileFacts_uses_is_optional = Expect<Equal<IsOptional<FileFacts, 'uses'>, true>>;
428
+ export type MountFact_keys = Expect<Equal<keyof MountFact, 'prefix' | 'target' | 'order' | 'router' | 'guards'>>;
429
+ export type MountFact_required = Expect<Equal<Pick<MountFact, 'prefix' | 'target' | 'order'>, { prefix: string; target: string; order: number }>>;
430
+ export type UseFact_keys = Expect<Equal<keyof UseFact, 'path' | 'match' | 'guards' | 'order' | 'router'>>;
431
+ export type UseFact_match = Expect<Equal<UseFact['match'], 'prefix' | 'exact' | undefined>>;
432
+ export type FactStoreVersion_shape = Expect<Equal<FactStoreVersion, { epoch: string; generation: number }>>;
433
+ export type FactStorePort_keys = Expect<Equal<keyof FactStorePort,
434
+ 'getObjects' | 'putObjects' | 'readVersion' | 'readManifest' | 'writeManifest' | 'derivedRows' | 'sweepObjects' | 'reset'>>;
435
+ export type FactStorePort_writeManifest = Expect<Equal<FactStorePort['writeManifest'],
436
+ (manifest: FactManifestDelta, derivedPuts: readonly DerivedRow[], derivedDeletes: readonly string[]) => Awaitable<void>>>;
437
+ export type FactStorePort_getObjects = Expect<Equal<FactStorePort['getObjects'], (hashes: readonly string[]) => Awaitable<ReadonlyMap<string, string>>>>;
438
+ export type FactStorePort_putObjects = Expect<Equal<FactStorePort['putObjects'], (objects: ReadonlyMap<string, string>) => Awaitable<void>>>;
439
+ export type FactStorePort_derivedRows = Expect<Equal<FactStorePort['derivedRows'], () => Awaitable<ReadonlyMap<string, DerivedRow>>>>;
440
+ export type FactStorePort_sweepObjects = Expect<Equal<FactStorePort['sweepObjects'], (expected: FactStoreVersion) => Awaitable<number>>>;
441
+ export type FactStoreManifest_keys = Expect<Equal<keyof FactStoreManifest, 'epoch' | 'generation' | 'files'>>;
442
+ export type FactStoreManifest_files = Expect<Equal<FactStoreManifest['files'], ReadonlyMap<string, FactManifestEntry>>>;
443
+ export type FactManifestDelta_keys = Expect<Equal<keyof FactManifestDelta, 'epoch' | 'generation' | 'puts' | 'deletes'>>;
444
+ export type StoredFactGraph_keys = Expect<Equal<keyof StoredFactGraph, 'epoch' | 'generation' | 'graph'>>;
445
+ export type FactStoreSaveResult_keys = Expect<Equal<keyof FactStoreSaveResult,
446
+ 'epoch' | 'generation' | 'graph' | 'objects' | 'puts' | 'deletes' | 'derivedPuts' | 'derivedDeletes'>>;
447
+ export type LoadFactGraphOptions_shape = Expect<Equal<LoadFactGraphOptions, { verify?: 'full' | 'manifest' }>>;
448
+ export type saveFactGraph_signature = Expect<Equal<
449
+ typeof saveFactGraph, (port: FactStorePort, graph: FactGraph, previous?: StoredFactGraph) => Promise<FactStoreSaveResult>
450
+ >>;
451
+ export type loadFactGraph_signature = Expect<Equal<typeof loadFactGraph, (port: FactStorePort, opts?: LoadFactGraphOptions) => Promise<StoredFactGraph>>>;
452
+ export type factStoreDump_signature = Expect<Equal<typeof factStoreDump, (port: FactStorePort) => Promise<string>>>;
453
+ export type sweepFactStore_signature = Expect<Equal<typeof sweepFactStore, (port: FactStorePort) => Promise<number>>>;
454
+ export type memoryFactStore_signature = Expect<Equal<typeof memoryFactStore, () => MemoryFactStore>>;
455
+ export type effectiveGuards_signature = Expect<Equal<
456
+ typeof effectiveGuards, (fileFacts: FileFacts, resolvedMounts: readonly ResolvedMount[], opts?: EffectiveGuardsOptions) => EffectiveGuardsResult
457
+ >>;
458
+ export type EffectiveGuardsResult_shape = Expect<Equal<EffectiveGuardsResult, { entryPoints: EffectiveEntryPoint[]; truncated: number; unresolved: number }>>;
459
+ export type EffectiveGuardsOptions_shape = Expect<Equal<EffectiveGuardsOptions, { path?: string; router?: string; maxDepth?: number }>>;
460
+ export type rootRouters_signature = Expect<Equal<
461
+ typeof rootRouters, (files: ReadonlyMap<string, FileFacts>, resolveMount: (from: string, mount: MountFact) => MountTarget | undefined) => RootRouter[]
462
+ >>;
463
+ export type RootRouter_shape = Expect<Equal<RootRouter, { path: string; router: string }>>;
464
+ export type MountTarget_shape = Expect<Equal<MountTarget, { path: string; router?: string }>>;
465
+ export type ResolvedMount_shape = Expect<Equal<ResolvedMount, {
466
+ target: string; path: string; facts: FileFacts; router?: string; mounts?: readonly ResolvedMount[];
467
+ }>>;
468
+ export type EffectiveEntryPoint_extra_keys = Expect<Equal<Exclude<keyof EffectiveEntryPoint, keyof EntryPointFact>, 'file' | 'via' | 'guardsInferred'>>;
469
+
415
470
  describe('type contract', () => {
416
471
  it('is enforced by `npm run check:contract-types` (tsc over tsconfig.contract.json), not at run time', () => {
417
472
  // The values above only exist so the `satisfies` / `@ts-expect-error` lines are real code; this proves the file loads.