@seanhogg/builderforce-memory 2026.10.45 → 2026.10.47
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/README.md +21 -0
- package/dist/knowledge/build.d.ts.map +1 -1
- package/dist/knowledge/build.js +13 -7
- package/dist/knowledge/build.js.map +1 -1
- package/dist/knowledge/extractFile.d.ts +9 -1
- package/dist/knowledge/extractFile.d.ts.map +1 -1
- package/dist/knowledge/extractFile.js +25 -5
- package/dist/knowledge/extractFile.js.map +1 -1
- package/dist/knowledge/extractJob.d.ts +30 -5
- package/dist/knowledge/extractJob.d.ts.map +1 -1
- package/dist/knowledge/extractJob.js +9 -1
- package/dist/knowledge/extractJob.js.map +1 -1
- package/dist/knowledge/index.d.ts +5 -3
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +2 -1
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/jobDeadline.d.ts +17 -0
- package/dist/knowledge/jobDeadline.d.ts.map +1 -0
- package/dist/knowledge/jobDeadline.js +46 -0
- package/dist/knowledge/jobDeadline.js.map +1 -0
- package/dist/knowledge/judgeCalls.d.ts +16 -0
- package/dist/knowledge/judgeCalls.d.ts.map +1 -1
- package/dist/knowledge/judgeCalls.js +20 -1
- package/dist/knowledge/judgeCalls.js.map +1 -1
- package/dist/knowledge/judgePriority.d.ts +22 -0
- package/dist/knowledge/judgePriority.d.ts.map +1 -0
- package/dist/knowledge/judgePriority.js +28 -0
- package/dist/knowledge/judgePriority.js.map +1 -0
- package/dist/knowledge/pack/crc32.d.ts +7 -0
- package/dist/knowledge/pack/crc32.d.ts.map +1 -0
- package/dist/knowledge/pack/crc32.js +22 -0
- package/dist/knowledge/pack/crc32.js.map +1 -0
- package/dist/knowledge/pack/decode.d.ts +14 -0
- package/dist/knowledge/pack/decode.d.ts.map +1 -0
- package/dist/knowledge/pack/decode.js +66 -0
- package/dist/knowledge/pack/decode.js.map +1 -0
- package/dist/knowledge/pack/deflate.d.ts +9 -0
- package/dist/knowledge/pack/deflate.d.ts.map +1 -0
- package/dist/knowledge/pack/deflate.js +45 -0
- package/dist/knowledge/pack/deflate.js.map +1 -0
- package/dist/knowledge/pack/encode.d.ts +26 -0
- package/dist/knowledge/pack/encode.d.ts.map +1 -0
- package/dist/knowledge/pack/encode.js +86 -0
- package/dist/knowledge/pack/encode.js.map +1 -0
- package/dist/knowledge/pack/extrDiff.d.ts +26 -0
- package/dist/knowledge/pack/extrDiff.d.ts.map +1 -0
- package/dist/knowledge/pack/extrDiff.js +129 -0
- package/dist/knowledge/pack/extrDiff.js.map +1 -0
- package/dist/knowledge/pack/frame.d.ts +45 -0
- package/dist/knowledge/pack/frame.d.ts.map +1 -0
- package/dist/knowledge/pack/frame.js +101 -0
- package/dist/knowledge/pack/frame.js.map +1 -0
- package/dist/knowledge/pack/hex.d.ts +7 -0
- package/dist/knowledge/pack/hex.d.ts.map +1 -0
- package/dist/knowledge/pack/hex.js +17 -0
- package/dist/knowledge/pack/hex.js.map +1 -0
- package/dist/knowledge/pack/index.d.ts +19 -0
- package/dist/knowledge/pack/index.d.ts.map +1 -0
- package/dist/knowledge/pack/index.js +17 -0
- package/dist/knowledge/pack/index.js.map +1 -0
- package/dist/knowledge/pack/jsonSize.d.ts +5 -0
- package/dist/knowledge/pack/jsonSize.d.ts.map +1 -0
- package/dist/knowledge/pack/jsonSize.js +8 -0
- package/dist/knowledge/pack/jsonSize.js.map +1 -0
- package/dist/knowledge/pack/manifest.d.ts +66 -0
- package/dist/knowledge/pack/manifest.d.ts.map +1 -0
- package/dist/knowledge/pack/manifest.js +104 -0
- package/dist/knowledge/pack/manifest.js.map +1 -0
- package/dist/knowledge/pack/sections/columns.d.ts +32 -0
- package/dist/knowledge/pack/sections/columns.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/columns.js +53 -0
- package/dist/knowledge/pack/sections/columns.js.map +1 -0
- package/dist/knowledge/pack/sections/extr.d.ts +8 -0
- package/dist/knowledge/pack/sections/extr.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/extr.js +99 -0
- package/dist/knowledge/pack/sections/extr.js.map +1 -0
- package/dist/knowledge/pack/sections/extrLists.d.ts +23 -0
- package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/extrLists.js +200 -0
- package/dist/knowledge/pack/sections/extrLists.js.map +1 -0
- package/dist/knowledge/pack/sections/facts.d.ts +8 -0
- package/dist/knowledge/pack/sections/facts.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/facts.js +172 -0
- package/dist/knowledge/pack/sections/facts.js.map +1 -0
- package/dist/knowledge/pack/sections/index.d.ts +6 -0
- package/dist/knowledge/pack/sections/index.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/index.js +9 -0
- package/dist/knowledge/pack/sections/index.js.map +1 -0
- package/dist/knowledge/pack/sections/rows.d.ts +31 -0
- package/dist/knowledge/pack/sections/rows.d.ts.map +1 -0
- package/dist/knowledge/pack/sections/rows.js +227 -0
- package/dist/knowledge/pack/sections/rows.js.map +1 -0
- package/dist/knowledge/pack/strings.d.ts +43 -0
- package/dist/knowledge/pack/strings.d.ts.map +1 -0
- package/dist/knowledge/pack/strings.js +117 -0
- package/dist/knowledge/pack/strings.js.map +1 -0
- package/dist/knowledge/pack/types.d.ts +118 -0
- package/dist/knowledge/pack/types.d.ts.map +1 -0
- package/dist/knowledge/pack/types.js +17 -0
- package/dist/knowledge/pack/types.js.map +1 -0
- package/dist/knowledge/pack/varint.d.ts +57 -0
- package/dist/knowledge/pack/varint.d.ts.map +1 -0
- package/dist/knowledge/pack/varint.js +145 -0
- package/dist/knowledge/pack/varint.js.map +1 -0
- package/dist/knowledge/partitions.d.ts +1 -1
- package/dist/knowledge/partitions.d.ts.map +1 -1
- package/dist/knowledge/partitions.js +6 -1
- package/dist/knowledge/partitions.js.map +1 -1
- package/dist/knowledge/review.d.ts.map +1 -1
- package/dist/knowledge/review.js +58 -16
- package/dist/knowledge/review.js.map +1 -1
- package/dist/knowledge/reviewJudge.d.ts +8 -1
- package/dist/knowledge/reviewJudge.d.ts.map +1 -1
- package/dist/knowledge/reviewJudge.js +14 -8
- package/dist/knowledge/reviewJudge.js.map +1 -1
- package/dist/knowledge/reviewModel.d.ts +41 -1
- package/dist/knowledge/reviewModel.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.d.ts +10 -2
- package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.js +60 -25
- package/dist/knowledge/reviewPrefetch.js.map +1 -1
- package/dist/knowledge/reviewRun.d.ts +15 -3
- package/dist/knowledge/reviewRun.d.ts.map +1 -1
- package/dist/knowledge/reviewRun.js +19 -2
- package/dist/knowledge/reviewRun.js.map +1 -1
- package/dist/knowledge/reviewRunModel.d.ts +8 -1
- package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
- package/dist/knowledge/reviewRunModel.js.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.d.ts +72 -6
- package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.js +279 -75
- package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
- package/package.json +8 -3
- package/src/contract/dist.contract.test.ts +44 -0
- package/src/contract/exports.contract.test.ts +90 -0
- package/src/contract/exports.snapshot.json +605 -0
- package/src/contract/pack.contract.test.ts +31 -0
- package/src/contract/regression.review.test.ts +236 -0
- package/src/contract/regression.store.test.ts +84 -0
- package/src/contract/types.contract.test.ts +183 -0
- package/src/knowledge/build.ts +11 -5
- package/src/knowledge/extractFile.ts +28 -6
- package/src/knowledge/extractJob.ts +26 -7
- package/src/knowledge/index.ts +5 -3
- package/src/knowledge/jobDeadline.ts +43 -0
- package/src/knowledge/judgeCalls.ts +19 -2
- package/src/knowledge/judgePriority.ts +36 -0
- package/src/knowledge/pack/crc32.ts +21 -0
- package/src/knowledge/pack/decode.ts +60 -0
- package/src/knowledge/pack/deflate.ts +43 -0
- package/src/knowledge/pack/encode.ts +89 -0
- package/src/knowledge/pack/extrDiff.ts +116 -0
- package/src/knowledge/pack/frame.ts +94 -0
- package/src/knowledge/pack/hex.ts +17 -0
- package/src/knowledge/pack/index.ts +26 -0
- package/src/knowledge/pack/jsonSize.ts +11 -0
- package/src/knowledge/pack/manifest.ts +128 -0
- package/src/knowledge/pack/pack.guards.test.ts +109 -0
- package/src/knowledge/pack/pack.reconcile.test.ts +96 -0
- package/src/knowledge/pack/pack.roundtrip.test.ts +50 -0
- package/src/knowledge/pack/pack.size.test.ts +22 -0
- package/src/knowledge/pack/pack.testkit.test-util.ts +90 -0
- package/src/knowledge/pack/sections/columns.ts +61 -0
- package/src/knowledge/pack/sections/extr.ts +90 -0
- package/src/knowledge/pack/sections/extrLists.ts +151 -0
- package/src/knowledge/pack/sections/facts.ts +126 -0
- package/src/knowledge/pack/sections/index.ts +13 -0
- package/src/knowledge/pack/sections/rows.ts +184 -0
- package/src/knowledge/pack/strings.ts +126 -0
- package/src/knowledge/pack/types.ts +97 -0
- package/src/knowledge/pack/varint.ts +145 -0
- package/src/knowledge/partitions.test.ts +4 -0
- package/src/knowledge/partitions.ts +3 -1
- package/src/knowledge/review.throughput.test.ts +122 -0
- package/src/knowledge/review.ts +54 -16
- package/src/knowledge/review.twoPass.test.ts +224 -0
- package/src/knowledge/reviewJudge.ts +19 -8
- package/src/knowledge/reviewModel.ts +38 -1
- package/src/knowledge/reviewPrefetch.ts +60 -24
- package/src/knowledge/reviewRun.test.ts +20 -3
- package/src/knowledge/reviewRun.ts +33 -6
- package/src/knowledge/reviewRunModel.ts +4 -1
- package/src/knowledge/stores/localSnapshotStore.batched.test.ts +25 -3
- package/src/knowledge/stores/localSnapshotStore.extractedLog.test.ts +280 -0
- package/src/knowledge/stores/localSnapshotStore.ts +283 -76
- package/src/knowledge/systems.test.ts +12 -0
- package/src/knowledge/testkit.test-util.ts +13 -2
|
@@ -12,6 +12,10 @@
|
|
|
12
12
|
* Every write serializes the WHOLE snapshot, so a many-mutation run (a directory review)
|
|
13
13
|
* would cost quadratic bytes. {@link LocalSnapshotStore.batched} holds persistence back
|
|
14
14
|
* inside a run; outside one, each awaited mutation has persisted when it resolves.
|
|
15
|
+
*
|
|
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 extract cache is
|
|
18
|
+
* an append-only JSON Lines file instead of part of the snapshot.
|
|
15
19
|
*/
|
|
16
20
|
|
|
17
21
|
import type {
|
|
@@ -22,6 +26,20 @@ import { canonicalJson, compareStr, pathOfRef } from '../refs.js';
|
|
|
22
26
|
export interface SnapshotPersistence {
|
|
23
27
|
read(): Promise<string | undefined>;
|
|
24
28
|
write(snapshot: string): Promise<void>;
|
|
29
|
+
/** Keeps the bytes of a snapshot that did not parse (e.g. as `<snapshot>.corrupt`) before the store starts empty. Optional: without it they are lost. */
|
|
30
|
+
keepAside?(text: string): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Append-only, content-addressed home of the extract cache (PRD 41 A10 rule 7). JSON Lines, one
|
|
35
|
+
* `{"h":"<hash>","e":[...]}` per line; the LAST line for a hash wins, an unparseable (torn) line is ignored.
|
|
36
|
+
*/
|
|
37
|
+
export interface ExtractedLogPersistence {
|
|
38
|
+
read(): Promise<string | undefined>;
|
|
39
|
+
/** Appends `text` (whole lines, newline-terminated) to the end of the log. */
|
|
40
|
+
append(text: string): Promise<void>;
|
|
41
|
+
/** Replaces the whole log with `text` (atomically where the host can). Optional: without it the log is never compacted. */
|
|
42
|
+
replace?(text: string): Promise<void>;
|
|
25
43
|
}
|
|
26
44
|
|
|
27
45
|
export interface KnowledgeSnapshot {
|
|
@@ -29,10 +47,13 @@ export interface KnowledgeSnapshot {
|
|
|
29
47
|
scopes: ScopeRecord[];
|
|
30
48
|
facts: Record<string, StoredFact[]>;
|
|
31
49
|
relations: Record<string, StoredRelation[]>;
|
|
32
|
-
|
|
50
|
+
/** Present only when the store has no `extractedLog` (or in a snapshot written before the log existed). */
|
|
51
|
+
extracted?: Record<string, Extracted[]>;
|
|
33
52
|
}
|
|
34
53
|
|
|
35
54
|
export interface LocalSnapshotStoreOptions {
|
|
55
|
+
/** When given, the extract cache lives in this log and the snapshot omits `extracted`. */
|
|
56
|
+
extractedLog?: ExtractedLogPersistence;
|
|
36
57
|
/** ISO clock for `staleAt`. Default `new Date().toISOString()`. */
|
|
37
58
|
now?(): string;
|
|
38
59
|
/** Inside `batched`, a mutation persists when this many ms passed since the last write (a crash loses at most this much). Default 30_000. */
|
|
@@ -43,29 +64,74 @@ export interface LocalSnapshotStoreOptions {
|
|
|
43
64
|
|
|
44
65
|
const relKey = (r: Pick<StoredRelation, 'from' | 'to' | 'kind'>) => `${r.from}\u0000${r.to}\u0000${r.kind}`;
|
|
45
66
|
|
|
46
|
-
function
|
|
47
|
-
return
|
|
67
|
+
function asRecord<T>(v: unknown): Record<string, T[]> {
|
|
68
|
+
return v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, T[]> : {};
|
|
48
69
|
}
|
|
49
70
|
|
|
71
|
+
const emptySnapshot = (): KnowledgeSnapshot => ({ version: 1, scopes: [], facts: {}, relations: {} });
|
|
72
|
+
|
|
73
|
+
/** Reads a snapshot's text. THROWS when it does not parse, so the caller can keep the bytes aside before starting empty. */
|
|
50
74
|
function parse(text: string | undefined): KnowledgeSnapshot {
|
|
51
|
-
if (!text) return
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
75
|
+
if (!text) return emptySnapshot();
|
|
76
|
+
const s = JSON.parse(text) as Partial<KnowledgeSnapshot>;
|
|
77
|
+
return {
|
|
78
|
+
version: 1,
|
|
79
|
+
scopes: Array.isArray(s.scopes) ? s.scopes : [],
|
|
80
|
+
facts: asRecord(s.facts),
|
|
81
|
+
relations: asRecord(s.relations),
|
|
82
|
+
...(s.extracted && typeof s.extracted === 'object' ? { extracted: s.extracted } : {}),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
interface ParsedLog {
|
|
87
|
+
entries: Map<string, Extracted[]>;
|
|
88
|
+
/** The live (last) line of each hash, newline-terminated, in log order. */
|
|
89
|
+
liveLines: Map<string, string>;
|
|
90
|
+
liveBytes: number;
|
|
91
|
+
/** Superseded lines, torn lines and blank lines. */
|
|
92
|
+
deadBytes: number;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The log's entries, last line per hash winning. A line that does not parse (torn by a crash or a failed
|
|
97
|
+
* append) is skipped on its own: it never costs the other lines.
|
|
98
|
+
*/
|
|
99
|
+
function parseLog(text: string | undefined): ParsedLog {
|
|
100
|
+
const out: ParsedLog = { entries: new Map(), liveLines: new Map(), liveBytes: 0, deadBytes: 0 };
|
|
101
|
+
if (!text) return out;
|
|
102
|
+
for (const line of text.split('\n')) {
|
|
103
|
+
if (!line.trim()) continue;
|
|
104
|
+
try {
|
|
105
|
+
const row = JSON.parse(line) as { h?: unknown; e?: unknown };
|
|
106
|
+
if (typeof row.h === 'string' && Array.isArray(row.e)) {
|
|
107
|
+
out.entries.set(row.h, row.e as Extracted[]);
|
|
108
|
+
out.liveLines.delete(row.h); // re-set below so the map stays in log order of last occurrence
|
|
109
|
+
out.liveLines.set(row.h, `${line}\n`);
|
|
110
|
+
}
|
|
111
|
+
} catch { /* torn line */ }
|
|
64
112
|
}
|
|
113
|
+
for (const l of out.liveLines.values()) out.liveBytes += l.length;
|
|
114
|
+
out.deadBytes = Math.max(0, text.length - out.liveBytes);
|
|
115
|
+
return out;
|
|
65
116
|
}
|
|
66
117
|
|
|
118
|
+
type Index = Map<string, Set<string>>;
|
|
119
|
+
|
|
67
120
|
export class LocalSnapshotStore implements KnowledgeStore {
|
|
68
|
-
private
|
|
121
|
+
private loaded = false;
|
|
122
|
+
private loading: Promise<void> | undefined;
|
|
123
|
+
private scopeList: ScopeRecord[] = [];
|
|
124
|
+
/** Per-root rows, keyed by their unique key, updated incrementally (PRD 41 A10 rule 7). */
|
|
125
|
+
private readonly factMaps = new Map<string, Map<string, StoredFact>>();
|
|
126
|
+
private readonly relMaps = new Map<string, Map<string, StoredRelation>>();
|
|
127
|
+
/** Per root: source path → keys of the relations touching it (`from` or `to`). */
|
|
128
|
+
private readonly relByPath = new Map<string, Index>();
|
|
129
|
+
private readonly extracted = new Map<string, Extracted[]>();
|
|
130
|
+
/** Extract entries not yet appended to the log. */
|
|
131
|
+
private pending = new Map<string, Extracted[]>();
|
|
132
|
+
/** The log's last line is torn (no newline), so the next append starts on a fresh line. */
|
|
133
|
+
private logTorn = false;
|
|
134
|
+
private readonly log: ExtractedLogPersistence | undefined;
|
|
69
135
|
/** Serializes mutations so two writers never interleave a read-modify-write. */
|
|
70
136
|
private queue: Promise<unknown> = Promise.resolve();
|
|
71
137
|
private readonly now: () => string;
|
|
@@ -76,16 +142,104 @@ export class LocalSnapshotStore implements KnowledgeStore {
|
|
|
76
142
|
/** Memory is ahead of the persisted snapshot. */
|
|
77
143
|
private dirty = false;
|
|
78
144
|
private persistedAt = 0;
|
|
145
|
+
/** Serializes snapshot writes; never rejects. */
|
|
146
|
+
private persisting: Promise<void> = Promise.resolve();
|
|
147
|
+
/** A background checkpoint in flight (at most one). */
|
|
148
|
+
private checkpointing: Promise<void> | undefined;
|
|
79
149
|
|
|
80
150
|
constructor(private readonly persistence: SnapshotPersistence, opts: LocalSnapshotStoreOptions = {}) {
|
|
81
151
|
this.now = opts.now ?? (() => new Date().toISOString());
|
|
82
152
|
this.nowMs = opts.nowMs ?? Date.now;
|
|
83
153
|
this.checkpointMs = opts.checkpointMs ?? 30_000;
|
|
154
|
+
this.log = opts.extractedLog;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Loads once; every later call is a no-op, so reads never wait on the mutation queue after the first. */
|
|
158
|
+
private load(): Promise<void> {
|
|
159
|
+
if (this.loaded) return Promise.resolve();
|
|
160
|
+
this.loading ??= this.doLoad().catch((err) => { this.loading = undefined; throw err; });
|
|
161
|
+
return this.loading;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
private async doLoad(): Promise<void> {
|
|
165
|
+
const snapText = await this.persistence.read();
|
|
166
|
+
let snap: KnowledgeSnapshot;
|
|
167
|
+
try {
|
|
168
|
+
snap = parse(snapText);
|
|
169
|
+
} catch {
|
|
170
|
+
// Unreadable: never silently replaced. Its bytes are kept aside, then the store starts empty (the next review rebuilds).
|
|
171
|
+
await this.persistence.keepAside?.(snapText!).catch(() => undefined);
|
|
172
|
+
snap = emptySnapshot();
|
|
173
|
+
}
|
|
174
|
+
const logText = this.log ? await this.log.read() : undefined;
|
|
175
|
+
this.scopeList = snap.scopes;
|
|
176
|
+
for (const [rootId, rows] of Object.entries(snap.facts)) {
|
|
177
|
+
const m = this.factsOf(rootId);
|
|
178
|
+
if (Array.isArray(rows)) for (const f of rows) m.set(f.key, f);
|
|
179
|
+
}
|
|
180
|
+
for (const [rootId, rows] of Object.entries(snap.relations)) {
|
|
181
|
+
this.relsOf(rootId);
|
|
182
|
+
if (Array.isArray(rows)) for (const r of rows) this.putRelation(rootId, r);
|
|
183
|
+
}
|
|
184
|
+
if (this.log) {
|
|
185
|
+
const parsed = parseLog(logText);
|
|
186
|
+
for (const [h, e] of parsed.entries) this.extracted.set(h, e);
|
|
187
|
+
this.logTorn = !!logText && !logText.endsWith('\n');
|
|
188
|
+
await this.compactLog(parsed);
|
|
189
|
+
// An old snapshot still carrying the cache: move it into the log once; the next snapshot write omits it.
|
|
190
|
+
const legacy = Object.entries(snap.extracted ?? {});
|
|
191
|
+
if (legacy.length) {
|
|
192
|
+
for (const [h, e] of legacy) {
|
|
193
|
+
if (this.extracted.has(h)) continue;
|
|
194
|
+
this.extracted.set(h, e);
|
|
195
|
+
this.pending.set(h, e);
|
|
196
|
+
}
|
|
197
|
+
this.dirty = true;
|
|
198
|
+
}
|
|
199
|
+
} else {
|
|
200
|
+
for (const [h, e] of Object.entries(snap.extracted ?? {})) this.extracted.set(h, e);
|
|
201
|
+
}
|
|
202
|
+
this.loaded = true;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Rewrites the log to its live lines when dead bytes (superseded and torn lines) exceed live bytes. Needs the
|
|
207
|
+
* port's `replace`; a failure is ignored (the log stays correct, only larger). Another window appending between
|
|
208
|
+
* this read and the replace loses those lines from the cache — a cache miss, re-extracted next review.
|
|
209
|
+
*/
|
|
210
|
+
private async compactLog(parsed: ParsedLog): Promise<void> {
|
|
211
|
+
if (!this.log?.replace || parsed.deadBytes <= parsed.liveBytes) return;
|
|
212
|
+
try {
|
|
213
|
+
await this.log.replace([...parsed.liveLines.values()].join(''));
|
|
214
|
+
this.logTorn = false;
|
|
215
|
+
} catch { /* keep the uncompacted log */ }
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
private factsOf(rootId: string): Map<string, StoredFact> {
|
|
219
|
+
let m = this.factMaps.get(rootId);
|
|
220
|
+
if (!m) this.factMaps.set(rootId, m = new Map());
|
|
221
|
+
return m;
|
|
84
222
|
}
|
|
85
223
|
|
|
86
|
-
private
|
|
87
|
-
|
|
88
|
-
|
|
224
|
+
private relsOf(rootId: string): Map<string, StoredRelation> {
|
|
225
|
+
let m = this.relMaps.get(rootId);
|
|
226
|
+
if (!m) this.relMaps.set(rootId, m = new Map());
|
|
227
|
+
return m;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** Upserts a relation and indexes it under the source paths of both ends. */
|
|
231
|
+
private putRelation(rootId: string, r: StoredRelation): void {
|
|
232
|
+
const key = relKey(r);
|
|
233
|
+
this.relsOf(rootId).set(key, r);
|
|
234
|
+
let idx = this.relByPath.get(rootId);
|
|
235
|
+
if (!idx) this.relByPath.set(rootId, idx = new Map());
|
|
236
|
+
for (const ref of [r.from, r.to]) {
|
|
237
|
+
const p = pathOfRef(ref);
|
|
238
|
+
if (p === undefined) continue;
|
|
239
|
+
let keys = idx.get(p);
|
|
240
|
+
if (!keys) idx.set(p, keys = new Set());
|
|
241
|
+
keys.add(key);
|
|
242
|
+
}
|
|
89
243
|
}
|
|
90
244
|
|
|
91
245
|
private enqueue<T>(task: () => Promise<T>): Promise<T> {
|
|
@@ -94,28 +248,70 @@ export class LocalSnapshotStore implements KnowledgeStore {
|
|
|
94
248
|
return run;
|
|
95
249
|
}
|
|
96
250
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
251
|
+
/**
|
|
252
|
+
* Appends the not-yet-logged extract entries as ONE `append` of complete lines. A failed append keeps them
|
|
253
|
+
* pending and marks the log torn (it may hold a partial line), so the next append starts on a fresh line.
|
|
254
|
+
*/
|
|
255
|
+
private async appendPending(): Promise<void> {
|
|
256
|
+
if (!this.log || this.pending.size === 0) return;
|
|
257
|
+
const batch = this.pending;
|
|
258
|
+
this.pending = new Map();
|
|
259
|
+
let text = this.logTorn ? '\n' : '';
|
|
260
|
+
for (const [h, e] of batch) text += `${JSON.stringify({ h, e })}\n`;
|
|
261
|
+
try {
|
|
262
|
+
await this.log.append(text);
|
|
263
|
+
this.logTorn = false;
|
|
264
|
+
} catch (err) {
|
|
265
|
+
this.logTorn = true;
|
|
266
|
+
for (const [h, e] of batch) if (!this.pending.has(h)) this.pending.set(h, e);
|
|
267
|
+
throw err;
|
|
268
|
+
}
|
|
101
269
|
}
|
|
102
270
|
|
|
103
|
-
|
|
104
|
-
|
|
271
|
+
/**
|
|
272
|
+
* Appends new extract entries, then writes the snapshot if memory is ahead of it, one write at a time. It
|
|
273
|
+
* runs OUTSIDE the mutation queue: a write of a large snapshot (serialize + disk) must never hold up reads or
|
|
274
|
+
* the next mutation's in-memory apply (PRD 41 A10 — it did: every `getExtracted` waited out each checkpoint).
|
|
275
|
+
* The log goes first, so a snapshot that dropped a migrated cache never outlives its entries. A failed
|
|
276
|
+
* write leaves the snapshot dirty, so the next one retries it.
|
|
277
|
+
*/
|
|
278
|
+
private persistIfDirty(): Promise<void> {
|
|
279
|
+
const run = this.persisting.then(async () => {
|
|
280
|
+
if (!this.loaded) return;
|
|
281
|
+
await this.appendPending();
|
|
282
|
+
if (!this.dirty) return;
|
|
283
|
+
this.dirty = false;
|
|
284
|
+
try {
|
|
285
|
+
await this.persistence.write(this.serialize());
|
|
286
|
+
} catch (err) {
|
|
287
|
+
this.dirty = true;
|
|
288
|
+
throw err;
|
|
289
|
+
}
|
|
290
|
+
this.persistedAt = this.nowMs();
|
|
291
|
+
});
|
|
292
|
+
this.persisting = run.catch(() => undefined);
|
|
293
|
+
return run;
|
|
105
294
|
}
|
|
106
295
|
|
|
107
296
|
/**
|
|
108
|
-
* Applies in memory,
|
|
109
|
-
*
|
|
110
|
-
*
|
|
297
|
+
* Applies in memory (queued, so reads and writes never interleave), then persists: at once outside a
|
|
298
|
+
* batch, else a checkpoint in the BACKGROUND once `checkpointMs` passed. A plain mutation from another
|
|
299
|
+
* caller during a batch (the live file watcher shares this store) is held like the batch's own and made
|
|
300
|
+
* durable by the next checkpoint, flush or batch end. `snapshotChanged: false` is for a change that only
|
|
301
|
+
* touches the extract log.
|
|
111
302
|
*/
|
|
112
|
-
private mutate(fn: (
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
fn(
|
|
116
|
-
this.dirty = true;
|
|
117
|
-
if (this.depth === 0 || this.nowMs() - this.persistedAt >= this.checkpointMs) await this.persist(s);
|
|
303
|
+
private async mutate(fn: () => void, snapshotChanged = true): Promise<void> {
|
|
304
|
+
await this.enqueue(async () => {
|
|
305
|
+
await this.load();
|
|
306
|
+
fn();
|
|
307
|
+
if (snapshotChanged) this.dirty = true;
|
|
118
308
|
});
|
|
309
|
+
if (this.depth === 0) await this.persistIfDirty();
|
|
310
|
+
else if (!this.checkpointing && this.nowMs() - this.persistedAt >= this.checkpointMs) {
|
|
311
|
+
// A failed checkpoint is not lost: the snapshot stays dirty and the batch's end or flush writes (and reports) it.
|
|
312
|
+
// It backs off by `checkpointMs` (advances `persistedAt`) so a failing disk is not retried on every mutation.
|
|
313
|
+
this.checkpointing = this.persistIfDirty().catch(() => { this.persistedAt = this.nowMs(); }).finally(() => { this.checkpointing = undefined; });
|
|
314
|
+
}
|
|
119
315
|
}
|
|
120
316
|
|
|
121
317
|
/**
|
|
@@ -127,13 +323,13 @@ export class LocalSnapshotStore implements KnowledgeStore {
|
|
|
127
323
|
if (this.depth === 0) this.persistedAt = this.nowMs();
|
|
128
324
|
this.depth += 1;
|
|
129
325
|
// The end goes through the queue so every mutation made during the batch is held, then written once.
|
|
130
|
-
const end =
|
|
131
|
-
this.depth -= 1;
|
|
326
|
+
const end = async () => {
|
|
327
|
+
await this.enqueue(async () => { this.depth -= 1; });
|
|
132
328
|
if (this.depth === 0) await this.persistIfDirty();
|
|
133
|
-
}
|
|
329
|
+
};
|
|
134
330
|
let result: T;
|
|
135
331
|
try {
|
|
136
|
-
result = await work(() => this.
|
|
332
|
+
result = await work(async () => { await this.queue; await this.persistIfDirty(); });
|
|
137
333
|
} catch (err) {
|
|
138
334
|
await end().catch(() => undefined);
|
|
139
335
|
throw err;
|
|
@@ -143,58 +339,82 @@ export class LocalSnapshotStore implements KnowledgeStore {
|
|
|
143
339
|
}
|
|
144
340
|
|
|
145
341
|
async scopes(): Promise<ScopeRecord[]> {
|
|
146
|
-
await this.
|
|
147
|
-
return [...
|
|
342
|
+
await this.load();
|
|
343
|
+
return [...this.scopeList];
|
|
148
344
|
}
|
|
149
345
|
|
|
150
346
|
async facts(scope: Scope): Promise<StoredFact[]> {
|
|
151
|
-
await this.
|
|
152
|
-
return [...(
|
|
347
|
+
await this.load();
|
|
348
|
+
return [...(this.factMaps.get(scope.rootId)?.values() ?? [])];
|
|
153
349
|
}
|
|
154
350
|
|
|
155
351
|
async relations(scope: Scope): Promise<StoredRelation[]> {
|
|
156
|
-
await this.
|
|
157
|
-
return [...(
|
|
352
|
+
await this.load();
|
|
353
|
+
return [...(this.relMaps.get(scope.rootId)?.values() ?? [])];
|
|
158
354
|
}
|
|
159
355
|
|
|
160
356
|
write(batch: { scope: ScopeRecord; facts: StoredFact[]; relations: StoredRelation[] }): Promise<void> {
|
|
161
357
|
const bad = [...batch.facts, ...batch.relations].find((x) => (x.origin as string) === 'extracted');
|
|
162
358
|
if (bad) return Promise.reject(new Error('knowledge: extracted output is never stored'));
|
|
163
|
-
return this.mutate((
|
|
359
|
+
return this.mutate(() => {
|
|
164
360
|
const rootId = batch.scope.rootId;
|
|
165
|
-
const prior =
|
|
361
|
+
const prior = this.scopeList.find((x) => x.rootId === rootId);
|
|
166
362
|
const merged: ScopeRecord = { ...(prior ?? {}), ...stripUndefined(batch.scope) } as ScopeRecord;
|
|
167
|
-
|
|
363
|
+
this.scopeList = [...this.scopeList.filter((x) => x.rootId !== rootId), merged];
|
|
168
364
|
|
|
169
|
-
const facts =
|
|
365
|
+
const facts = this.factsOf(rootId);
|
|
170
366
|
for (const f of batch.facts) facts.set(f.key, { ...f });
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
const relations = new Map((s.relations[rootId] ?? []).map((r) => [relKey(r), r] as const));
|
|
174
|
-
for (const r of batch.relations) relations.set(relKey(r), { ...r });
|
|
175
|
-
s.relations[rootId] = [...relations.values()];
|
|
367
|
+
this.relsOf(rootId);
|
|
368
|
+
for (const r of batch.relations) this.putRelation(rootId, { ...r });
|
|
176
369
|
});
|
|
177
370
|
}
|
|
178
371
|
|
|
179
372
|
markStale(scope: Scope, sourceRef: NodeRef, currentHash: string): Promise<void> {
|
|
180
373
|
const path = pathOfRef(sourceRef);
|
|
181
|
-
return this.mutate((
|
|
374
|
+
return this.mutate(() => {
|
|
182
375
|
const at = this.now();
|
|
183
|
-
const
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
376
|
+
const rels = this.relsOf(scope.rootId);
|
|
377
|
+
const keys = path === undefined ? undefined : this.relByPath.get(scope.rootId)?.get(path);
|
|
378
|
+
for (const key of keys ?? []) {
|
|
379
|
+
const r = rels.get(key);
|
|
380
|
+
if (r && r.origin === 'model' && !r.staleAt && r.sourceHash !== currentHash) rels.set(key, { ...r, staleAt: at });
|
|
381
|
+
}
|
|
188
382
|
});
|
|
189
383
|
}
|
|
190
384
|
|
|
191
385
|
async getExtracted(hash: string): Promise<Extracted[] | undefined> {
|
|
192
|
-
await this.
|
|
193
|
-
return
|
|
386
|
+
await this.load();
|
|
387
|
+
return this.extracted.get(hash);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** Every cached entry by content hash (the log's, else the snapshot's `extracted`), for a host that packs the cache. */
|
|
391
|
+
async extractedEntries(): Promise<Record<string, Extracted[]>> {
|
|
392
|
+
await this.load();
|
|
393
|
+
return Object.fromEntries(this.extracted);
|
|
194
394
|
}
|
|
195
395
|
|
|
196
396
|
putExtracted(hash: string, extracted: Extracted[]): Promise<void> {
|
|
197
|
-
return this.mutate((
|
|
397
|
+
return this.mutate(() => {
|
|
398
|
+
// The same entry again (a second pass re-puts what the first stored) is skipped: no append, no dirty snapshot.
|
|
399
|
+
const prior = this.extracted.get(hash);
|
|
400
|
+
if (prior && canonicalJson(prior) === canonicalJson(extracted)) return;
|
|
401
|
+
this.extracted.set(hash, extracted);
|
|
402
|
+
if (this.log) this.pending.set(hash, extracted);
|
|
403
|
+
else this.dirty = true;
|
|
404
|
+
}, false);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** Canonical: scopes by rootId, facts by key, relations by (from, to, kind), keys sorted. */
|
|
408
|
+
private serialize(): string {
|
|
409
|
+
const rows = <T>(maps: Map<string, Map<string, T>>, by: (a: T, b: T) => number) =>
|
|
410
|
+
Object.fromEntries([...maps.keys()].sort(compareStr).map((k) => [k, [...maps.get(k)!.values()].sort(by)]));
|
|
411
|
+
return canonicalJson({
|
|
412
|
+
version: 1,
|
|
413
|
+
scopes: [...this.scopeList].sort((a, b) => compareStr(a.rootId, b.rootId)),
|
|
414
|
+
facts: rows(this.factMaps, (a, b) => compareStr(a.key, b.key)),
|
|
415
|
+
relations: rows(this.relMaps, (a, b) => compareStr(relKey(a), relKey(b))),
|
|
416
|
+
...(this.log ? {} : { extracted: Object.fromEntries(this.extracted) }),
|
|
417
|
+
});
|
|
198
418
|
}
|
|
199
419
|
}
|
|
200
420
|
|
|
@@ -205,16 +425,3 @@ export function localSnapshotStore(persistence: SnapshotPersistence, opts?: Loca
|
|
|
205
425
|
function stripUndefined<T extends object>(o: T): Partial<T> {
|
|
206
426
|
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)) as Partial<T>;
|
|
207
427
|
}
|
|
208
|
-
|
|
209
|
-
/** Canonical: scopes by rootId, facts by key, relations by (from, to, kind), keys sorted. */
|
|
210
|
-
function serialize(s: KnowledgeSnapshot): string {
|
|
211
|
-
const sortRecord = <T>(rec: Record<string, T[]>, by: (a: T, b: T) => number) =>
|
|
212
|
-
Object.fromEntries(Object.keys(rec).sort(compareStr).map((k) => [k, [...rec[k]!].sort(by)]));
|
|
213
|
-
return canonicalJson({
|
|
214
|
-
version: 1,
|
|
215
|
-
scopes: [...s.scopes].sort((a, b) => compareStr(a.rootId, b.rootId)),
|
|
216
|
-
facts: sortRecord(s.facts, (a, b) => compareStr(a.key, b.key)),
|
|
217
|
-
relations: sortRecord(s.relations, (a, b) => compareStr(relKey(a), relKey(b))),
|
|
218
|
-
extracted: s.extracted,
|
|
219
|
-
});
|
|
220
|
-
}
|
|
@@ -84,6 +84,18 @@ describe('buildGraph — systems', () => {
|
|
|
84
84
|
expect(g.findings.filter((f) => f.kind === 'partition-violation').every((f) => !f.nodes.some((n) => n.endsWith('b/ui/z.ts')))).toBe(true);
|
|
85
85
|
});
|
|
86
86
|
|
|
87
|
+
it('a link from a file to a path that is not there, in another system, gets no verdict', () => {
|
|
88
|
+
// b/ui/gone.ts is not a file of the graph: it becomes a `missing` node, which still lives in system b.
|
|
89
|
+
const across = buildGraph(input([sys('a'), sys('b')], [['a/data/x.ts', 'b/ui/gone.ts']]));
|
|
90
|
+
const missing = across.edges.find((e) => e.to.endsWith('b/ui/gone.ts'))!;
|
|
91
|
+
expect(across.nodes.find((n) => n.label === 'gone.ts')?.kind).toBe('missing');
|
|
92
|
+
expect(missing.verdict).toBeUndefined();
|
|
93
|
+
// Inside one system the same missing link is judged as before, and a missing node is not stamped (a file field).
|
|
94
|
+
const within = buildGraph(input([sys('a'), sys('b')], [['a/data/x.ts', 'a/ui/gone.ts']]));
|
|
95
|
+
expect(within.edges.find((e) => e.to.endsWith('a/ui/gone.ts'))?.verdict).toBe('upward');
|
|
96
|
+
expect(within.nodes.find((n) => n.label === 'gone.ts')?.system).toBeUndefined();
|
|
97
|
+
});
|
|
98
|
+
|
|
87
99
|
it('the same edge IS a violation when the root is one system', () => {
|
|
88
100
|
const g = buildGraph(input([sys('')], [['a/data/x.ts', 'b/ui/z.ts']]));
|
|
89
101
|
expect(g.edges.find((e) => e.to.endsWith('b/ui/z.ts'))?.verdict).toBe('upward');
|
|
@@ -11,7 +11,7 @@ import type {
|
|
|
11
11
|
} from './model.js';
|
|
12
12
|
import { loadExtractorState } from './owedFiles.js';
|
|
13
13
|
import { DOCS_PACK } from './packs/docs.js';
|
|
14
|
-
import { LocalSnapshotStore, type SnapshotPersistence } from './stores/localSnapshotStore.js';
|
|
14
|
+
import { LocalSnapshotStore, type ExtractedLogPersistence, type SnapshotPersistence } from './stores/localSnapshotStore.js';
|
|
15
15
|
import { srcRef } from './refs.js';
|
|
16
16
|
|
|
17
17
|
export const ROOT = 'r';
|
|
@@ -23,7 +23,7 @@ export interface SpySource extends DirectorySource {
|
|
|
23
23
|
|
|
24
24
|
export function memSource(files: Record<string, string>, rootId = ROOT): SpySource {
|
|
25
25
|
const src: SpySource = {
|
|
26
|
-
rootId, title: 'Fixture', files, reads: [],
|
|
26
|
+
rootId, title: 'Fixture', files, reads: [], hashOf: hashText,
|
|
27
27
|
async *list() {
|
|
28
28
|
for (const path of Object.keys(src.files)) {
|
|
29
29
|
const text = src.files[path]!;
|
|
@@ -46,6 +46,17 @@ export function memPersistence(): SnapshotPersistence & { value?: string } {
|
|
|
46
46
|
return p;
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
+
/** An in-memory extract log: records every `append` and `replace` so a test can prove the log is only ever appended to. */
|
|
50
|
+
export function memLog(): ExtractedLogPersistence & { text?: string; appends: string[]; replaces: number } {
|
|
51
|
+
const log: ExtractedLogPersistence & { text?: string; appends: string[]; replaces: number } = {
|
|
52
|
+
appends: [], replaces: 0,
|
|
53
|
+
async read() { return log.text; },
|
|
54
|
+
async append(t: string) { log.appends.push(t); log.text = (log.text ?? '') + t; },
|
|
55
|
+
async replace(t: string) { log.replaces += 1; log.text = t; },
|
|
56
|
+
};
|
|
57
|
+
return log;
|
|
58
|
+
}
|
|
59
|
+
|
|
49
60
|
export function memStore(): LocalSnapshotStore {
|
|
50
61
|
return new LocalSnapshotStore(memPersistence(), { now: () => '2026-10-28T00:00:00.000Z' });
|
|
51
62
|
}
|