@seanhogg/builderforce-memory 2026.10.45 → 2026.10.46

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 (173) hide show
  1. package/dist/knowledge/build.d.ts.map +1 -1
  2. package/dist/knowledge/build.js +13 -7
  3. package/dist/knowledge/build.js.map +1 -1
  4. package/dist/knowledge/extractFile.d.ts +9 -1
  5. package/dist/knowledge/extractFile.d.ts.map +1 -1
  6. package/dist/knowledge/extractFile.js +22 -5
  7. package/dist/knowledge/extractFile.js.map +1 -1
  8. package/dist/knowledge/extractJob.d.ts +30 -5
  9. package/dist/knowledge/extractJob.d.ts.map +1 -1
  10. package/dist/knowledge/extractJob.js +9 -1
  11. package/dist/knowledge/extractJob.js.map +1 -1
  12. package/dist/knowledge/index.d.ts +5 -3
  13. package/dist/knowledge/index.d.ts.map +1 -1
  14. package/dist/knowledge/index.js +2 -1
  15. package/dist/knowledge/index.js.map +1 -1
  16. package/dist/knowledge/jobDeadline.d.ts +17 -0
  17. package/dist/knowledge/jobDeadline.d.ts.map +1 -0
  18. package/dist/knowledge/jobDeadline.js +46 -0
  19. package/dist/knowledge/jobDeadline.js.map +1 -0
  20. package/dist/knowledge/judgeCalls.d.ts +16 -0
  21. package/dist/knowledge/judgeCalls.d.ts.map +1 -1
  22. package/dist/knowledge/judgeCalls.js +20 -1
  23. package/dist/knowledge/judgeCalls.js.map +1 -1
  24. package/dist/knowledge/judgePriority.d.ts +22 -0
  25. package/dist/knowledge/judgePriority.d.ts.map +1 -0
  26. package/dist/knowledge/judgePriority.js +28 -0
  27. package/dist/knowledge/judgePriority.js.map +1 -0
  28. package/dist/knowledge/pack/crc32.d.ts +3 -0
  29. package/dist/knowledge/pack/crc32.d.ts.map +1 -0
  30. package/dist/knowledge/pack/crc32.js +18 -0
  31. package/dist/knowledge/pack/crc32.js.map +1 -0
  32. package/dist/knowledge/pack/decode.d.ts +14 -0
  33. package/dist/knowledge/pack/decode.d.ts.map +1 -0
  34. package/dist/knowledge/pack/decode.js +64 -0
  35. package/dist/knowledge/pack/decode.js.map +1 -0
  36. package/dist/knowledge/pack/deflate.d.ts +9 -0
  37. package/dist/knowledge/pack/deflate.d.ts.map +1 -0
  38. package/dist/knowledge/pack/deflate.js +45 -0
  39. package/dist/knowledge/pack/deflate.js.map +1 -0
  40. package/dist/knowledge/pack/encode.d.ts +17 -0
  41. package/dist/knowledge/pack/encode.d.ts.map +1 -0
  42. package/dist/knowledge/pack/encode.js +79 -0
  43. package/dist/knowledge/pack/encode.js.map +1 -0
  44. package/dist/knowledge/pack/extrDiff.d.ts +23 -0
  45. package/dist/knowledge/pack/extrDiff.d.ts.map +1 -0
  46. package/dist/knowledge/pack/extrDiff.js +0 -0
  47. package/dist/knowledge/pack/extrDiff.js.map +1 -0
  48. package/dist/knowledge/pack/frame.d.ts +37 -0
  49. package/dist/knowledge/pack/frame.d.ts.map +1 -0
  50. package/dist/knowledge/pack/frame.js +94 -0
  51. package/dist/knowledge/pack/frame.js.map +1 -0
  52. package/dist/knowledge/pack/index.d.ts +19 -0
  53. package/dist/knowledge/pack/index.d.ts.map +1 -0
  54. package/dist/knowledge/pack/index.js +17 -0
  55. package/dist/knowledge/pack/index.js.map +1 -0
  56. package/dist/knowledge/pack/jsonSize.d.ts +5 -0
  57. package/dist/knowledge/pack/jsonSize.d.ts.map +1 -0
  58. package/dist/knowledge/pack/jsonSize.js +8 -0
  59. package/dist/knowledge/pack/jsonSize.js.map +1 -0
  60. package/dist/knowledge/pack/manifest.d.ts +66 -0
  61. package/dist/knowledge/pack/manifest.d.ts.map +1 -0
  62. package/dist/knowledge/pack/manifest.js +104 -0
  63. package/dist/knowledge/pack/manifest.js.map +1 -0
  64. package/dist/knowledge/pack/sections/columns.d.ts +32 -0
  65. package/dist/knowledge/pack/sections/columns.d.ts.map +1 -0
  66. package/dist/knowledge/pack/sections/columns.js +53 -0
  67. package/dist/knowledge/pack/sections/columns.js.map +1 -0
  68. package/dist/knowledge/pack/sections/extr.d.ts +8 -0
  69. package/dist/knowledge/pack/sections/extr.d.ts.map +1 -0
  70. package/dist/knowledge/pack/sections/extr.js +99 -0
  71. package/dist/knowledge/pack/sections/extr.js.map +1 -0
  72. package/dist/knowledge/pack/sections/extrLists.d.ts +23 -0
  73. package/dist/knowledge/pack/sections/extrLists.d.ts.map +1 -0
  74. package/dist/knowledge/pack/sections/extrLists.js +194 -0
  75. package/dist/knowledge/pack/sections/extrLists.js.map +1 -0
  76. package/dist/knowledge/pack/sections/facts.d.ts +8 -0
  77. package/dist/knowledge/pack/sections/facts.d.ts.map +1 -0
  78. package/dist/knowledge/pack/sections/facts.js +167 -0
  79. package/dist/knowledge/pack/sections/facts.js.map +1 -0
  80. package/dist/knowledge/pack/sections/index.d.ts +6 -0
  81. package/dist/knowledge/pack/sections/index.d.ts.map +1 -0
  82. package/dist/knowledge/pack/sections/index.js +9 -0
  83. package/dist/knowledge/pack/sections/index.js.map +1 -0
  84. package/dist/knowledge/pack/sections/rows.d.ts +31 -0
  85. package/dist/knowledge/pack/sections/rows.d.ts.map +1 -0
  86. package/dist/knowledge/pack/sections/rows.js +226 -0
  87. package/dist/knowledge/pack/sections/rows.js.map +1 -0
  88. package/dist/knowledge/pack/strings.d.ts +39 -0
  89. package/dist/knowledge/pack/strings.d.ts.map +1 -0
  90. package/dist/knowledge/pack/strings.js +115 -0
  91. package/dist/knowledge/pack/strings.js.map +1 -0
  92. package/dist/knowledge/pack/types.d.ts +109 -0
  93. package/dist/knowledge/pack/types.d.ts.map +1 -0
  94. package/dist/knowledge/pack/types.js +17 -0
  95. package/dist/knowledge/pack/types.js.map +1 -0
  96. package/dist/knowledge/pack/varint.d.ts +50 -0
  97. package/dist/knowledge/pack/varint.d.ts.map +1 -0
  98. package/dist/knowledge/pack/varint.js +141 -0
  99. package/dist/knowledge/pack/varint.js.map +1 -0
  100. package/dist/knowledge/partitions.d.ts +1 -1
  101. package/dist/knowledge/partitions.d.ts.map +1 -1
  102. package/dist/knowledge/partitions.js +6 -1
  103. package/dist/knowledge/partitions.js.map +1 -1
  104. package/dist/knowledge/review.d.ts.map +1 -1
  105. package/dist/knowledge/review.js +58 -16
  106. package/dist/knowledge/review.js.map +1 -1
  107. package/dist/knowledge/reviewJudge.d.ts +8 -1
  108. package/dist/knowledge/reviewJudge.d.ts.map +1 -1
  109. package/dist/knowledge/reviewJudge.js +14 -8
  110. package/dist/knowledge/reviewJudge.js.map +1 -1
  111. package/dist/knowledge/reviewModel.d.ts +35 -1
  112. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  113. package/dist/knowledge/reviewPrefetch.d.ts +8 -2
  114. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
  115. package/dist/knowledge/reviewPrefetch.js +50 -25
  116. package/dist/knowledge/reviewPrefetch.js.map +1 -1
  117. package/dist/knowledge/reviewRun.d.ts +15 -3
  118. package/dist/knowledge/reviewRun.d.ts.map +1 -1
  119. package/dist/knowledge/reviewRun.js +19 -2
  120. package/dist/knowledge/reviewRun.js.map +1 -1
  121. package/dist/knowledge/reviewRunModel.d.ts +8 -1
  122. package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
  123. package/dist/knowledge/reviewRunModel.js.map +1 -1
  124. package/dist/knowledge/stores/localSnapshotStore.d.ts +72 -6
  125. package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
  126. package/dist/knowledge/stores/localSnapshotStore.js +279 -75
  127. package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
  128. package/package.json +7 -3
  129. package/src/knowledge/build.ts +11 -5
  130. package/src/knowledge/extractFile.ts +26 -6
  131. package/src/knowledge/extractJob.ts +26 -7
  132. package/src/knowledge/index.ts +5 -3
  133. package/src/knowledge/jobDeadline.ts +43 -0
  134. package/src/knowledge/judgeCalls.ts +19 -2
  135. package/src/knowledge/judgePriority.ts +36 -0
  136. package/src/knowledge/pack/crc32.ts +17 -0
  137. package/src/knowledge/pack/decode.ts +58 -0
  138. package/src/knowledge/pack/deflate.ts +43 -0
  139. package/src/knowledge/pack/encode.ts +81 -0
  140. package/src/knowledge/pack/extrDiff.ts +0 -0
  141. package/src/knowledge/pack/frame.ts +86 -0
  142. package/src/knowledge/pack/index.ts +26 -0
  143. package/src/knowledge/pack/jsonSize.ts +11 -0
  144. package/src/knowledge/pack/manifest.ts +128 -0
  145. package/src/knowledge/pack/pack.guards.test.ts +77 -0
  146. package/src/knowledge/pack/pack.reconcile.test.ts +96 -0
  147. package/src/knowledge/pack/pack.roundtrip.test.ts +50 -0
  148. package/src/knowledge/pack/pack.size.test.ts +22 -0
  149. package/src/knowledge/pack/pack.testkit.test-util.ts +90 -0
  150. package/src/knowledge/pack/sections/columns.ts +61 -0
  151. package/src/knowledge/pack/sections/extr.ts +90 -0
  152. package/src/knowledge/pack/sections/extrLists.ts +147 -0
  153. package/src/knowledge/pack/sections/facts.ts +123 -0
  154. package/src/knowledge/pack/sections/index.ts +13 -0
  155. package/src/knowledge/pack/sections/rows.ts +184 -0
  156. package/src/knowledge/pack/strings.ts +123 -0
  157. package/src/knowledge/pack/types.ts +89 -0
  158. package/src/knowledge/pack/varint.ts +138 -0
  159. package/src/knowledge/partitions.test.ts +4 -0
  160. package/src/knowledge/partitions.ts +3 -1
  161. package/src/knowledge/review.throughput.test.ts +122 -0
  162. package/src/knowledge/review.ts +54 -16
  163. package/src/knowledge/review.twoPass.test.ts +224 -0
  164. package/src/knowledge/reviewJudge.ts +19 -8
  165. package/src/knowledge/reviewModel.ts +32 -1
  166. package/src/knowledge/reviewPrefetch.ts +51 -24
  167. package/src/knowledge/reviewRun.test.ts +20 -3
  168. package/src/knowledge/reviewRun.ts +33 -6
  169. package/src/knowledge/reviewRunModel.ts +4 -1
  170. package/src/knowledge/stores/localSnapshotStore.batched.test.ts +25 -3
  171. package/src/knowledge/stores/localSnapshotStore.extractedLog.test.ts +280 -0
  172. package/src/knowledge/stores/localSnapshotStore.ts +283 -76
  173. package/src/knowledge/systems.test.ts +12 -0
@@ -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
- extracted: Record<string, Extracted[]>;
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 empty(): KnowledgeSnapshot {
47
- return { version: 1, scopes: [], facts: {}, relations: {}, extracted: {} };
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 empty();
52
- try {
53
- const s = JSON.parse(text) as Partial<KnowledgeSnapshot>;
54
- return {
55
- version: 1,
56
- scopes: Array.isArray(s.scopes) ? s.scopes : [],
57
- facts: s.facts && typeof s.facts === 'object' ? s.facts : {},
58
- relations: s.relations && typeof s.relations === 'object' ? s.relations : {},
59
- extracted: s.extracted && typeof s.extracted === 'object' ? s.extracted : {},
60
- };
61
- } catch {
62
- // A corrupt snapshot is rebuilt by the next review rather than failing every read.
63
- return empty();
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 snapshot: KnowledgeSnapshot | undefined;
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 async load(): Promise<KnowledgeSnapshot> {
87
- if (!this.snapshot) this.snapshot = parse(await this.persistence.read());
88
- return this.snapshot;
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
- private async persist(s: KnowledgeSnapshot): Promise<void> {
98
- await this.persistence.write(serialize(s));
99
- this.dirty = false;
100
- this.persistedAt = this.nowMs();
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
- private async persistIfDirty(): Promise<void> {
104
- if (this.dirty && this.snapshot) await this.persist(this.snapshot);
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, then persists: at once outside a batch, else only at a checkpoint. A plain
109
- * mutation from another caller during a batch (the live file watcher shares this store) is held
110
- * like the batch's own and made durable by the next checkpoint, flush or batch end.
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: (s: KnowledgeSnapshot) => void): Promise<void> {
113
- return this.enqueue(async () => {
114
- const s = await this.load();
115
- fn(s);
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 = () => this.enqueue(async () => {
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.enqueue(() => this.persistIfDirty()));
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.queue;
147
- return [...(await this.load()).scopes];
342
+ await this.load();
343
+ return [...this.scopeList];
148
344
  }
149
345
 
150
346
  async facts(scope: Scope): Promise<StoredFact[]> {
151
- await this.queue;
152
- return [...((await this.load()).facts[scope.rootId] ?? [])];
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.queue;
157
- return [...((await this.load()).relations[scope.rootId] ?? [])];
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((s) => {
359
+ return this.mutate(() => {
164
360
  const rootId = batch.scope.rootId;
165
- const prior = s.scopes.find((x) => x.rootId === rootId);
361
+ const prior = this.scopeList.find((x) => x.rootId === rootId);
166
362
  const merged: ScopeRecord = { ...(prior ?? {}), ...stripUndefined(batch.scope) } as ScopeRecord;
167
- s.scopes = [...s.scopes.filter((x) => x.rootId !== rootId), merged];
363
+ this.scopeList = [...this.scopeList.filter((x) => x.rootId !== rootId), merged];
168
364
 
169
- const facts = new Map((s.facts[rootId] ?? []).map((f) => [f.key, f] as const));
365
+ const facts = this.factsOf(rootId);
170
366
  for (const f of batch.facts) facts.set(f.key, { ...f });
171
- s.facts[rootId] = [...facts.values()];
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((s) => {
374
+ return this.mutate(() => {
182
375
  const at = this.now();
183
- const onSource = (ref: NodeRef) => path !== undefined && pathOfRef(ref) === path;
184
- s.relations[scope.rootId] = (s.relations[scope.rootId] ?? []).map((r) =>
185
- r.origin === 'model' && !r.staleAt && r.sourceHash !== currentHash && (onSource(r.from) || onSource(r.to))
186
- ? { ...r, staleAt: at }
187
- : r);
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.queue;
193
- return (await this.load()).extracted[hash];
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((s) => { s.extracted[hash] = extracted; });
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');