@hviana/sema 0.4.2 → 0.4.3

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 (133) hide show
  1. package/dist/example/demo.d.ts +1 -0
  2. package/dist/example/demo.js +39 -0
  3. package/dist/example/train_base.d.ts +87 -0
  4. package/dist/example/train_base.js +2252 -0
  5. package/dist/src/alphabet.d.ts +7 -0
  6. package/dist/src/alphabet.js +33 -0
  7. package/dist/src/alu/src/alu.d.ts +185 -0
  8. package/dist/src/alu/src/alu.js +440 -0
  9. package/dist/src/alu/src/expr.d.ts +61 -0
  10. package/dist/src/alu/src/expr.js +318 -0
  11. package/dist/src/alu/src/index.d.ts +11 -0
  12. package/dist/src/alu/src/index.js +19 -0
  13. package/dist/src/alu/src/kernel-arith.d.ts +16 -0
  14. package/dist/src/alu/src/kernel-arith.js +264 -0
  15. package/dist/src/alu/src/kernel-bits.d.ts +19 -0
  16. package/dist/src/alu/src/kernel-bits.js +152 -0
  17. package/dist/src/alu/src/kernel-logic.d.ts +4 -0
  18. package/dist/src/alu/src/kernel-logic.js +60 -0
  19. package/dist/src/alu/src/kernel-nd.d.ts +3 -0
  20. package/dist/src/alu/src/kernel-nd.js +208 -0
  21. package/dist/src/alu/src/kernel-numeric.d.ts +54 -0
  22. package/dist/src/alu/src/kernel-numeric.js +366 -0
  23. package/dist/src/alu/src/operation.d.ts +168 -0
  24. package/dist/src/alu/src/operation.js +189 -0
  25. package/dist/src/alu/src/parser.d.ts +221 -0
  26. package/dist/src/alu/src/parser.js +577 -0
  27. package/dist/src/alu/src/resonance.d.ts +55 -0
  28. package/dist/src/alu/src/resonance.js +126 -0
  29. package/dist/src/alu/src/text.d.ts +31 -0
  30. package/dist/src/alu/src/text.js +73 -0
  31. package/dist/src/alu/src/value.d.ts +109 -0
  32. package/dist/src/alu/src/value.js +300 -0
  33. package/dist/src/alu/test/alu.test.d.ts +1 -0
  34. package/dist/src/alu/test/alu.test.js +764 -0
  35. package/dist/src/bytes.d.ts +14 -0
  36. package/dist/src/bytes.js +59 -0
  37. package/dist/src/canon.d.ts +26 -0
  38. package/dist/src/canon.js +57 -0
  39. package/dist/src/config.d.ts +111 -0
  40. package/dist/src/config.js +91 -0
  41. package/dist/src/derive/src/deduction.d.ts +136 -0
  42. package/dist/src/derive/src/deduction.js +159 -0
  43. package/dist/src/derive/src/index.d.ts +8 -0
  44. package/dist/src/derive/src/index.js +11 -0
  45. package/dist/src/derive/src/priority-queue.d.ts +20 -0
  46. package/dist/src/derive/src/priority-queue.js +73 -0
  47. package/dist/src/derive/src/rewrite.d.ts +56 -0
  48. package/dist/src/derive/src/rewrite.js +100 -0
  49. package/dist/src/derive/src/trie.d.ts +90 -0
  50. package/dist/src/derive/src/trie.js +217 -0
  51. package/dist/src/derive/test/derive.test.d.ts +1 -0
  52. package/dist/src/derive/test/derive.test.js +122 -0
  53. package/dist/src/extension.d.ts +37 -0
  54. package/dist/src/extension.js +7 -0
  55. package/dist/src/geometry.d.ts +175 -0
  56. package/dist/src/geometry.js +823 -0
  57. package/dist/src/index.d.ts +17 -0
  58. package/dist/src/index.js +19 -0
  59. package/dist/src/ingest-cache.d.ts +41 -0
  60. package/dist/src/ingest-cache.js +165 -0
  61. package/dist/src/meter.d.ts +176 -0
  62. package/dist/src/meter.js +274 -0
  63. package/dist/src/mind/articulation.d.ts +6 -0
  64. package/dist/src/mind/articulation.js +99 -0
  65. package/dist/src/mind/attention.d.ts +414 -0
  66. package/dist/src/mind/attention.js +2082 -0
  67. package/dist/src/mind/bridge.d.ts +39 -0
  68. package/dist/src/mind/bridge.js +947 -0
  69. package/dist/src/mind/canonical.d.ts +34 -0
  70. package/dist/src/mind/canonical.js +93 -0
  71. package/dist/src/mind/graph-search.d.ts +294 -0
  72. package/dist/src/mind/graph-search.js +996 -0
  73. package/dist/src/mind/index.d.ts +9 -0
  74. package/dist/src/mind/index.js +5 -0
  75. package/dist/src/mind/junction.d.ts +137 -0
  76. package/dist/src/mind/junction.js +342 -0
  77. package/dist/src/mind/learning.d.ts +75 -0
  78. package/dist/src/mind/learning.js +270 -0
  79. package/dist/src/mind/match.d.ts +181 -0
  80. package/dist/src/mind/match.js +655 -0
  81. package/dist/src/mind/mechanisms/alu.d.ts +4 -0
  82. package/dist/src/mind/mechanisms/alu.js +36 -0
  83. package/dist/src/mind/mechanisms/cast.d.ts +89 -0
  84. package/dist/src/mind/mechanisms/cast.js +784 -0
  85. package/dist/src/mind/mechanisms/confluence.d.ts +24 -0
  86. package/dist/src/mind/mechanisms/confluence.js +255 -0
  87. package/dist/src/mind/mechanisms/cover.d.ts +6 -0
  88. package/dist/src/mind/mechanisms/cover.js +227 -0
  89. package/dist/src/mind/mechanisms/extraction.d.ts +33 -0
  90. package/dist/src/mind/mechanisms/extraction.js +300 -0
  91. package/dist/src/mind/mechanisms/recall.d.ts +16 -0
  92. package/dist/src/mind/mechanisms/recall.js +364 -0
  93. package/dist/src/mind/mind.d.ts +337 -0
  94. package/dist/src/mind/mind.js +617 -0
  95. package/dist/src/mind/pipeline-mechanism.d.ts +172 -0
  96. package/dist/src/mind/pipeline-mechanism.js +465 -0
  97. package/dist/src/mind/pipeline.d.ts +49 -0
  98. package/dist/src/mind/pipeline.js +275 -0
  99. package/dist/src/mind/primitives.d.ts +66 -0
  100. package/dist/src/mind/primitives.js +306 -0
  101. package/dist/src/mind/rationale.d.ts +139 -0
  102. package/dist/src/mind/rationale.js +163 -0
  103. package/dist/src/mind/reasoning.d.ts +40 -0
  104. package/dist/src/mind/reasoning.js +280 -0
  105. package/dist/src/mind/recognition.d.ts +20 -0
  106. package/dist/src/mind/recognition.js +504 -0
  107. package/dist/src/mind/resonance.d.ts +23 -0
  108. package/dist/src/mind/resonance.js +0 -0
  109. package/dist/src/mind/trace.d.ts +15 -0
  110. package/dist/src/mind/trace.js +73 -0
  111. package/dist/src/mind/traverse.d.ts +126 -0
  112. package/dist/src/mind/traverse.js +650 -0
  113. package/dist/src/mind/types.d.ts +333 -0
  114. package/dist/src/mind/types.js +130 -0
  115. package/dist/src/rabitq-ivf/src/database.d.ts +113 -0
  116. package/dist/src/rabitq-ivf/src/database.js +201 -0
  117. package/dist/src/rabitq-ivf/src/index.d.ts +7 -0
  118. package/dist/src/rabitq-ivf/src/index.js +4 -0
  119. package/dist/src/rabitq-ivf/src/ivf.d.ts +200 -0
  120. package/dist/src/rabitq-ivf/src/ivf.js +1165 -0
  121. package/dist/src/rabitq-ivf/src/prng.d.ts +19 -0
  122. package/dist/src/rabitq-ivf/src/prng.js +36 -0
  123. package/dist/src/rabitq-ivf/src/rabitq.d.ts +95 -0
  124. package/dist/src/rabitq-ivf/src/rabitq.js +283 -0
  125. package/dist/src/sema.d.ts +31 -0
  126. package/dist/src/sema.js +63 -0
  127. package/dist/src/store-sqlite.d.ts +184 -0
  128. package/dist/src/store-sqlite.js +942 -0
  129. package/dist/src/store.d.ts +678 -0
  130. package/dist/src/store.js +1703 -0
  131. package/dist/src/vec.d.ts +31 -0
  132. package/dist/src/vec.js +109 -0
  133. package/package.json +1 -1
@@ -0,0 +1,1703 @@
1
+ // store.ts — the memory as a content-addressed node graph (a Merkle DAG).
2
+ //
3
+ // There is no "whole", no "leaf vs interior" privilege. There is one kind of
4
+ // thing — a NODE — named by its content. A node is either a leaf (a single
5
+ // byte, with an implicit negative id) or a branch (an ordered list of child
6
+ // node ids). Identical nodes are stored once (hash-consing); a node that was the
7
+ // root of one deposit becomes, by reference, an interior child of a larger
8
+ // deposit that contains it. Storage is therefore O(distinct subtrees), and every
9
+ // span the encoder ever produced is individually addressable.
10
+ //
11
+ // Node ids are signed integers. Single-byte leaves occupy the negative range
12
+ // −256…−1 (derived from the byte value, never stored in a DB row). Branches
13
+ // are dense, monotonically-increasing positive integers (0,1,2,…), never
14
+ // deleted, so the count of minted branch ids is the next id. Integer ids are the
15
+ // most compact key possible: SQLite stores them inline in the rowid B-tree (no
16
+ // secondary index), child lists pack to 4-byte signed integers, and the vector
17
+ // index keys on them as a 4-byte int32.
18
+ //
19
+ // On top of the DAG sit two relations:
20
+ // • the gist index — each node's fold vector, for SOFT (resonant) lookup;
21
+ // • continuation edges — learned "what follows what", the associations recall
22
+ // traverses. Both are keyed by node id, so both deduplicate for free.
23
+ //
24
+ // AbstractStore is the template-method base class that contains ALL domain
25
+ // logic — caching, dedup/merge decisions, geometric
26
+ // halo scheduling, buffer management — and calls down to a handful of
27
+ // protected abstract methods that a concrete persistence adapter implements.
28
+ // SQliteStore (in store-sqlite.ts) extends it and provides only the bare
29
+ // essentials required for SQLite + VectorDatabase communication.
30
+ import { addInto, copy, dot, normalize } from "./vec.js";
31
+ import { identityBar } from "./geometry.js";
32
+ /** Entry cap for the two ANN read caches ({@link AbstractStore._resonateCache}
33
+ * / `_resonateHaloCache`). They are only dropped on index writes, so a long
34
+ * query-only session otherwise grows them without bound — a slow memory/GC
35
+ * degradation that takes hours to manifest. At the cap the cache is cleared
36
+ * wholesale (repeat-query hits re-warm it; a miss only re-runs the ANN). */
37
+ const RESONATE_CACHE_MAX = 4096;
38
+ /** Longest dedup-cache KEY worth retaining, in string length. Branch keys
39
+ * are `kids.join(",")`; structural branches stay tiny (≤ maxGroup kids), but
40
+ * the whole-stream flat branches deposit interns (one leaf id PER INPUT
41
+ * BYTE) produce keys of ~4–5 chars per content byte — one per deposit. The
42
+ * dedup caches are bounded by ENTRY count, so retaining those keys grows
43
+ * memory with total ingested content. Past this bound the cache is
44
+ * bypassed: the durable content-addressed probe still answers (dedup never
45
+ * depends on the cache), at one indexed SQLite lookup per re-encounter —
46
+ * and true input-level repeats are already absorbed by the ingest cache. */
47
+ const DEDUP_KEY_MAX = 4096;
48
+ /** Safety depth bound for one {@link Store.chainRun} read. Semantics never
49
+ * depend on it (a truncated run ends on a still-transparent node and the
50
+ * climber continues from there); it only bounds a single read's size. */
51
+ const CHAIN_DEPTH_CAP = 65_536;
52
+ /** The content key of a Float32Array — one latin1 char per byte, an exact
53
+ * encoding of the 32-bit floats. Content-addressed, not object-identity,
54
+ * so a fresh Float32Array carrying the same values still hits. Vectors are
55
+ * D·4 bytes (max ~4096), well under the argument limit; the key is far
56
+ * cheaper than the ANN query it deduplicates. */
57
+ function vecKey(v) {
58
+ const bytes = new Uint8Array(v.buffer, v.byteOffset, v.byteLength);
59
+ // Chunked fromCharCode: one spread of D·4 args (16K at D=4096) flirts with
60
+ // engine argument limits and is slower than a few bounded calls.
61
+ let s = "";
62
+ for (let i = 0; i < bytes.length; i += 8192) {
63
+ s += String.fromCharCode(...bytes.subarray(i, i + 8192));
64
+ }
65
+ return s;
66
+ }
67
+ /** Bounded map with LRU eviction and byte accounting. On get the entry
68
+ * moves to the most-recent end; on set the least-recently-used entries are
69
+ * evicted until total bytes ≤ `maxBytes`. The optional `sizeOf` callback
70
+ * measures each value in bytes (defaults to 1, so `maxBytes` = max entries
71
+ * for uniform caches). A miss only costs a little extra work later, never
72
+ * correctness. */
73
+ export class BoundedMap {
74
+ maxBytes;
75
+ sizeOf;
76
+ evict;
77
+ m = new Map();
78
+ _bytes = 0;
79
+ // Persistent eviction cursor over the Map's insertion order. A fresh
80
+ // `keys()` iterator per eviction re-skips the growing prefix of holes that
81
+ // deletions leave in V8's ordered backing store (compacted only on rehash),
82
+ // making each eviction O(size) once the map first fills — the training-rate
83
+ // cliff at scale. A persistent iterator passes each hole exactly once
84
+ // (V8 map iterators stay valid under mutation): amortized O(1).
85
+ _cursor = null;
86
+ // "smallest" mode: oldest-entry candidates carried between evictions, fed
87
+ // from the cursor, so the LRU window never rescans from the front.
88
+ _candidates = [];
89
+ constructor(maxBytes, sizeOf = () => 1, evict = "lru") {
90
+ this.maxBytes = maxBytes;
91
+ this.sizeOf = sizeOf;
92
+ this.evict = evict;
93
+ }
94
+ /** Next key in insertion (≈ LRU) order, resuming where the last call left
95
+ * off; wraps to the front when exhausted. Undefined only when empty. */
96
+ nextOldest() {
97
+ for (let wrapped = false;;) {
98
+ if (this._cursor === null)
99
+ this._cursor = this.m.keys();
100
+ const n = this._cursor.next();
101
+ if (!n.done)
102
+ return n.value;
103
+ this._cursor = null;
104
+ if (this.m.size === 0 || wrapped)
105
+ return undefined;
106
+ wrapped = true;
107
+ }
108
+ }
109
+ get(k) {
110
+ const v = this.m.get(k);
111
+ if (v !== undefined) {
112
+ this.m.delete(k);
113
+ this.m.set(k, v);
114
+ }
115
+ return v;
116
+ }
117
+ /** Membership without touching LRU order — a pure peek, for callers that only
118
+ * need "is this key present?" and must not promote it to most-recent. */
119
+ has(k) {
120
+ return this.m.has(k);
121
+ }
122
+ set(k, v) {
123
+ const old = this.m.get(k);
124
+ if (old !== undefined) {
125
+ this._bytes -= this.sizeOf(old);
126
+ this.m.delete(k);
127
+ }
128
+ this.m.set(k, v);
129
+ this._bytes += this.sizeOf(v);
130
+ while (this._bytes > this.maxBytes && this.m.size > 0) {
131
+ if (this.evict === "smallest") {
132
+ // Among the oldest LRU candidates, evict the cheapest to rebuild.
133
+ // Window grows logarithmically with cache size — wide enough to
134
+ // find a cheap victim without scanning the whole map. Candidates
135
+ // are pulled from the persistent cursor and carried between
136
+ // evictions, so the window never rescans the map from the front.
137
+ const WINDOW = Math.ceil(Math.log2(this.m.size + 1));
138
+ this._candidates = this._candidates.filter((k) => this.m.has(k));
139
+ while (this._candidates.length < WINDOW) {
140
+ const k = this.nextOldest();
141
+ if (k === undefined)
142
+ break;
143
+ if (!this._candidates.includes(k))
144
+ this._candidates.push(k);
145
+ }
146
+ let bestI = -1;
147
+ let bestSz = Infinity;
148
+ for (let i = 0; i < this._candidates.length; i++) {
149
+ const sz = this.sizeOf(this.m.get(this._candidates[i]));
150
+ if (sz < bestSz) {
151
+ bestSz = sz;
152
+ bestI = i;
153
+ }
154
+ }
155
+ if (bestI < 0)
156
+ break;
157
+ const bestK = this._candidates[bestI];
158
+ this._candidates.splice(bestI, 1);
159
+ this._bytes -= bestSz;
160
+ this.m.delete(bestK);
161
+ }
162
+ else {
163
+ const lru = this.nextOldest();
164
+ if (lru === undefined)
165
+ break;
166
+ const lruv = this.m.get(lru);
167
+ if (lruv === undefined)
168
+ continue;
169
+ this._bytes -= this.sizeOf(lruv);
170
+ this.m.delete(lru);
171
+ }
172
+ }
173
+ }
174
+ get size() {
175
+ return this.m.size;
176
+ }
177
+ get bytes() {
178
+ return this._bytes;
179
+ }
180
+ /** Remove one entry (point invalidation), with byte accounting. */
181
+ delete(k) {
182
+ const v = this.m.get(k);
183
+ if (v === undefined)
184
+ return;
185
+ this._bytes -= this.sizeOf(v);
186
+ this.m.delete(k);
187
+ }
188
+ /** Drop every entry (bulk invalidation) — O(1) amortised via fresh maps. */
189
+ clear() {
190
+ if (this.m.size === 0)
191
+ return;
192
+ this.m = new Map();
193
+ this._bytes = 0;
194
+ this._cursor = null;
195
+ this._candidates = [];
196
+ }
197
+ }
198
+ // ── Serialisation utilities (pure functions, no DB dependency) ───────────
199
+ const _ZERO = new Uint8Array(0);
200
+ /** Hand control back to the event loop for exactly one turn.
201
+ *
202
+ * `await` on an already-resolved promise only queues a MICROTASK, and the engine
203
+ * drains the entire microtask queue before it runs a single MACROTASK — so
204
+ * micro-awaiting alone never lets a timer, an I/O completion, or any other queued
205
+ * macrotask run. A macrotask primitive (`setImmediate`, else `setTimeout`) does:
206
+ * it parks the continuation behind the loop's next iteration, after pending I/O.
207
+ *
208
+ * Deliberately NOT unref'd: a caller is awaiting this promise, so the one
209
+ * scheduling turn is real pending work. An unref'd wake-up let the process
210
+ * exit mid-`ingest` whenever the event loop had nothing else alive (a bare
211
+ * top-level deposit loop) — the await simply never resolved. */
212
+ function yieldToEventLoop() {
213
+ return new Promise((resolve) => {
214
+ const g = globalThis;
215
+ if (g.setImmediate)
216
+ g.setImmediate(resolve);
217
+ else
218
+ g.setTimeout(resolve, 0);
219
+ });
220
+ }
221
+ /** Concatenate an array of byte arrays. */
222
+ function concat(parts) {
223
+ let n = 0;
224
+ for (const p of parts)
225
+ n += p.length;
226
+ const out = new Uint8Array(n);
227
+ let o = 0;
228
+ for (const p of parts) {
229
+ out.set(p, o);
230
+ o += p.length;
231
+ }
232
+ return out;
233
+ }
234
+ /** The byte string a FLAT branch spans — a branch whose kids are ALL implicit
235
+ * single-byte leaves (ids −256…−1) is fully determined by its bytes, one per
236
+ * kid. Returns null when any kid is a real node. Such branches (the sliding
237
+ * sub-span windows, the leaf-parent chunks, the per-deposit flat root spans —
238
+ * the bulk of what perception explodes text into) are stored as their BYTES
239
+ * (1 byte per kid) in the leaf column, with a zero-length kids blob marking
240
+ * "derive the kid list from the bytes" — 4× smaller than int32-packed ids,
241
+ * and content-addressed through the same leaf index instead of a second
242
+ * blob-duplicating kids index. */
243
+ function flatKidsBytes(kids) {
244
+ const out = new Uint8Array(kids.length);
245
+ for (let i = 0; i < kids.length; i++) {
246
+ const k = kids[i];
247
+ if (k < -256 || k >= 0)
248
+ return null;
249
+ out[i] = -(k + 1);
250
+ }
251
+ return out;
252
+ }
253
+ /** The implicit kid list of a flat branch — the inverse of
254
+ * {@link flatKidsBytes}. */
255
+ export function flatBytesKids(bytes) {
256
+ const out = new Array(bytes.length);
257
+ for (let i = 0; i < bytes.length; i++)
258
+ out[i] = -(bytes[i] + 1);
259
+ return out;
260
+ }
261
+ /** Pack a child-id list as little-endian int32s — 4 bytes per child, far more
262
+ * compact than a space-joined decimal string and trivial to read back. */
263
+ export function packKids(kids) {
264
+ const out = new Int32Array(kids.length);
265
+ for (let i = 0; i < kids.length; i++)
266
+ out[i] = kids[i];
267
+ return new Uint8Array(out.buffer);
268
+ }
269
+ export function unpackKids(blob) {
270
+ // The BLOB may be a view at a non-multiple-of-4 byteOffset, so copy before
271
+ // reinterpreting as int32.
272
+ const i32 = new Int32Array(blob.slice().buffer);
273
+ return Array.from(i32);
274
+ }
275
+ /** 32-bit FNV-1a of a byte blob — the integer content hash `idx_node_h` keys
276
+ * on. Collisions are resolved by verifying the stored blob, never trusted. */
277
+ function hashOf(bytes) {
278
+ let h = 0x811c9dc5 >>> 0;
279
+ for (let i = 0; i < bytes.length; i++) {
280
+ h ^= bytes[i];
281
+ h = Math.imul(h, 0x01000193) >>> 0;
282
+ }
283
+ return h >>> 0;
284
+ }
285
+ /** Fast content key (FNV-1a + length). No array spread onto the call stack. */
286
+ function keyOf(bytes) {
287
+ return hashOf(bytes).toString(16) + ":" + bytes.length;
288
+ }
289
+ /** Re-index a halo only when its mass is small or a power of two — O(log mass)
290
+ * writes per node instead of O(mass). */
291
+ function geometricMass(mass) {
292
+ return mass <= 4 || (mass & (mass - 1)) === 0;
293
+ }
294
+ // Halo accumulators are stored 2-bit quantized: the exact float32 L2 norm
295
+ // followed by D two-bit codes (sign + magnitude class) — 4 + D/4 bytes, 16×
296
+ // smaller than float32 and 4× smaller than int8, which made halo rows the
297
+ // single largest table in an episodically-trained store.
298
+ //
299
+ // Two bits is the COARSEST grain that preserves what halos are read for. A
300
+ // halo is a superposition of high-dimensional random signatures, so its
301
+ // elements are Gaussian; the four levels below are the Lloyd-Max optimal
302
+ // quantizer for a unit Gaussian (decision threshold ±0.9816σ, reconstruction
303
+ // ±0.4528σ / ±1.5104σ), whose output keeps ≥0.88 correlation with the exact
304
+ // accumulator. Every consumer is a thresholded resonance — direct cosines
305
+ // against the concept midpoint, or queries into the halo VectorDatabase whose
306
+ // stored codes are 1-bit RaBitQ anyway — and a 0.88-correlated direction moves
307
+ // none of those comparisons across the midpoint. One bit is NOT enough: a pure
308
+ // sign grid compresses cosine c to (2/π)·asin(c), which drags mid-band concept
309
+ // resonance below the midpoint and severs legitimate cross-name transfer.
310
+ // σ is derived from the stored norm (σ = norm/√D), so the codec carries no
311
+ // per-corpus state; the decoded vector is rescaled to the exact norm, keeping
312
+ // incremental pours magnitude-true.
313
+ const HALO_Q_THRESHOLD = 0.9816; // Lloyd-Max decision point, unit Gaussian
314
+ const HALO_Q_LO = 0.4528; // reconstruction level, inner cell
315
+ const HALO_Q_HI = 1.5104; // reconstruction level, outer cell
316
+ function haloEncode(v) {
317
+ const D = v.length;
318
+ const out = new Uint8Array(4 + ((D + 3) >> 2));
319
+ let n2 = 0;
320
+ for (let i = 0; i < D; i++)
321
+ n2 += v[i] * v[i];
322
+ const norm = Math.sqrt(n2);
323
+ new DataView(out.buffer).setFloat32(0, norm, true);
324
+ const bar = HALO_Q_THRESHOLD * (norm / Math.sqrt(D));
325
+ for (let i = 0; i < D; i++) {
326
+ const x = v[i];
327
+ // bit0: sign, bit1: |x| beyond the Gaussian decision threshold.
328
+ const code = (x > 0 ? 1 : 0) | ((x > bar || -x > bar) ? 2 : 0);
329
+ out[4 + (i >> 2)] |= code << ((i & 3) << 1);
330
+ }
331
+ return out;
332
+ }
333
+ function haloDecode(blob, D) {
334
+ const norm = new DataView(blob.buffer, blob.byteOffset, 4).getFloat32(0, true);
335
+ const out = new Float32Array(D);
336
+ if (norm === 0)
337
+ return out;
338
+ const sigma = norm / Math.sqrt(D);
339
+ let n2 = 0;
340
+ for (let i = 0; i < D; i++) {
341
+ const code = (blob[4 + (i >> 2)] >> ((i & 3) << 1)) & 3;
342
+ const mag = (code & 2 ? HALO_Q_HI : HALO_Q_LO) * sigma;
343
+ const x = code & 1 ? mag : -mag;
344
+ out[i] = x;
345
+ n2 += x * x;
346
+ }
347
+ // Rescale to the exact stored norm so accumulation stays magnitude-true.
348
+ const s = norm / Math.sqrt(n2);
349
+ for (let i = 0; i < D; i++)
350
+ out[i] *= s;
351
+ return out;
352
+ }
353
+ // ── AbstractStore: template-method base with all domain logic ────────────
354
+ /**
355
+ * Template-method base class that contains ALL domain logic for the content-
356
+ * addressed DAG store — caching, dedup/merge decisions, structural-compaction
357
+ * geometric halo scheduling, buffer management. A concrete persistence adapter
358
+ * (e.g. {@link SQliteStore}) extends it and implements only the ~35 one-liner
359
+ * protected abstract methods that talk to the actual storage backend.
360
+ */
361
+ export class AbstractStore {
362
+ /** Derived query breadth for a partitioned index of C clusters: probe √C
363
+ * of them (the same √-of-the-population convention as the hub bound √N).
364
+ * The IVF maps ef → nprobe as ceil(ef/4), so ef = 4·⌈√C⌉ probes exactly
365
+ * ⌈√C⌉ clusters. A FIXED efSearch stops scaling the moment the
366
+ * collection outgrows it: at 4,270 clusters the default 64 probed 16
367
+ * clusters (0.4%), and an exact stored match of a query routinely sat in
368
+ * an unprobed cluster — recall silently degraded as the store grew. The
369
+ * configured efSearch remains the floor for small collections. */
370
+ efFor(clusterCount) {
371
+ return Math.max(this.efSearch, 4 * Math.ceil(Math.sqrt(Math.max(1, clusterCount))));
372
+ }
373
+ // ── Config ─────────────────────────────────────────────────────────────
374
+ _D;
375
+ _maxGroup;
376
+ minHaloMass;
377
+ efSearch;
378
+ overfetch;
379
+ batchSize;
380
+ compactEveryNWrites;
381
+ // ── State ──────────────────────────────────────────────────────────────
382
+ /** Branch node ids are a dense, monotonically-increasing integer sequence
383
+ * (0,1,2,…). Single-byte leaves occupy the implicit negative range −256…−1.
384
+ * They are NEVER deleted, so the count of minted branch ids IS the next id —
385
+ * which doubles as the branch-node count and lets has() be an O(1) check.
386
+ * Set by `_dbOpen()` from the stored node count; incremented by `mintId()`. */
387
+ _nextId = 0;
388
+ _writtenSinceCompact = 0;
389
+ closed = false;
390
+ /** Lifecycle guard — resolved once `_dbOpen()` completes. */
391
+ _ready = null;
392
+ // ── Caches ─────────────────────────────────────────────────────────────
393
+ /** Exact-content dedup: content-key → node id. Intrinsic compression. */
394
+ _leafKey;
395
+ _branchKey;
396
+ /** Reconstructed-bytes read cache (regenerable), keyed by node id. */
397
+ _bytesCache;
398
+ /** contentLen memo — content is immutable, so entries never invalidate. */
399
+ _lenCache;
400
+ /** Node-record cache — avoids repeated persistence queries for shared DAG
401
+ * nodes. Each record is small (a few ints + short leaf buffer). */
402
+ _recCache;
403
+ /** Captured-but-not-yet-indexed gists. Sized in bytes (each is D·4); a deposit
404
+ * links/pours a node right after interning it, so the working set is one
405
+ * deposit's nodes — a small budget captures ~all of it, and an eviction only
406
+ * means that node is reached by the DAG climb instead of by direct
407
+ * resonance. */
408
+ _pendingGist;
409
+ /** EXACT halo accumulators for the session's live pours: full-precision in
410
+ * memory, 2-bit on disk, so within-session accumulate-then-compare never
411
+ * round-trips through the quantizer. Regenerable — a miss reads the durable
412
+ * 2-bit row. */
413
+ _haloExact;
414
+ /** NORMALIZED halo read cache — the decoded, normalized vector {@link halo}
415
+ * returns, cached by id so repeat reads skip the per-call 2-bit decode and
416
+ * normalize of a full D-element row (measured on a trained store: ~15K
417
+ * halo() calls per deep query over ~50 distinct ids — all but the first
418
+ * per id pure re-decode). Point-invalidated by {@link pourHalo}, the one
419
+ * halo mutation site. Callers receive a COPY, so the cached vector is
420
+ * never aliased. Regenerable — a miss re-decodes the durable row. */
421
+ _haloNorm;
422
+ /** Interiors deliberately SKIPPED by indexSubtree (unique nodes with 1 parent
423
+ * that bridge nothing). Remembered so subsequent visits prune the subtree
424
+ * without re-checking parent count. LRU-bounded: an evicted entry is
425
+ * re-checked on next visit — if it gained parents in the meantime, it will
426
+ * be promoted to the index. */
427
+ _coveredIds;
428
+ /** Live content-index id set, LRU-bounded so a massive ingest never leaks
429
+ * memory; an evicted entry is still indexed (the row is durable), so the
430
+ * only cost of an eviction is a duplicate index probe on next visit. */
431
+ _indexedIds;
432
+ // ── ANN read cache ─────────────────────────────────────────────────────
433
+ // The index is read-only between writes, so the same (v,k) always returns
434
+ // the same neighbours. Any index mutation (flush, delete, compact) drops
435
+ // the cache; the next miss recreates it. Content-addressed (vecKey), not
436
+ // identity-addressed — same principle as perceiveMemo.
437
+ /** ANN read cache for {@link resonate} — keyed by vecKey(v) + ":" + k;
438
+ * lazily initialised, dropped on any index mutation. */
439
+ _resonateCache = null;
440
+ /** ANN read cache for {@link resonateHalo} — same scheme. */
441
+ _resonateHaloCache = null;
442
+ // ── Write buffers ──────────────────────────────────────────────────────
443
+ /** Content (gist) index write buffer. */
444
+ _contentBuffer = [];
445
+ /** Halo index write buffer — keyed by id so repeats within a batch coalesce. */
446
+ _haloBuffer = new Map();
447
+ /** Containment write buffer: child → new parents, merged on flush cadence. */
448
+ _containBuf = new Map();
449
+ /** Dedup-target candidates still in the write buffer (keyed by id). Only
450
+ * roots that have gained an edge/halo are targets; a fresh intermediate
451
+ * branch is never folded onto. */
452
+ _nearDedupBuf = new Map();
453
+ /** Ids currently in `_contentBuffer` (not yet flushed) — O(1) membership. */
454
+ _bufferedIds = new Set();
455
+ // ── Transparent-chain cache ────────────────────────────────────────────
456
+ /** {@link Store.chainRun} results, valid for the store's lifetime BETWEEN
457
+ * writes: a chain is a pure function of the kid and edge tables, so any
458
+ * write that could break a node's transparency (a fresh mint inserting kid
459
+ * rows, a link inserting an edge) drops the whole cache — see the two
460
+ * invalidation sites. Regenerable; a miss re-walks. */
461
+ _chainMemo;
462
+ // ── Edge-source-count cache ────────────────────────────────────────────
463
+ /** Distinct edge-source count — the store's DOCUMENT COUNT (how many
464
+ * learnt contexts predict a continuation), the N of every
465
+ * inverse-document-frequency read. −1 until first asked for; from then
466
+ * on maintained INCREMENTALLY by {@link link} (edges are never deleted),
467
+ * so a read is O(1) — never a table scan on the recall path. */
468
+ _edgeSrcCount = -1;
469
+ // ── Constructor ────────────────────────────────────────────────────────
470
+ constructor(config, D, maxGroup) {
471
+ this._D = D;
472
+ this._maxGroup = maxGroup;
473
+ this.minHaloMass = config.minHaloMass;
474
+ this.efSearch = config.efSearch;
475
+ this.overfetch = config.overfetch;
476
+ this.batchSize = config.batchSize;
477
+ this.compactEveryNWrites = config.compactEveryNWrites;
478
+ this._leafKey = new BoundedMap(config.dedupCacheMax);
479
+ this._branchKey = new BoundedMap(config.dedupCacheMax);
480
+ this._bytesCache = new BoundedMap(config.bytesCacheMax, (v) => v.byteLength, "smallest");
481
+ this._lenCache = new BoundedMap(config.bytesCacheMax, () => 16);
482
+ this._recCache = new BoundedMap(config.recCacheBytes, (r) => (r.leaf?.byteLength ?? 0) + (r.kids?.length ?? 0) * 4 + 12);
483
+ this._pendingGist = new BoundedMap(config.pendingGistBytes, (v) => v.byteLength);
484
+ this._haloExact = new BoundedMap(config.haloCacheBytes, (v) => v.byteLength);
485
+ this._haloNorm = new BoundedMap(config.haloCacheBytes, (v) => v.byteLength);
486
+ this._coveredIds = new BoundedMap(config.coveredIdsMax);
487
+ this._indexedIds = new BoundedMap(config.coveredIdsMax);
488
+ this._chainMemo = new BoundedMap(config.chainCacheBytes, (v) => v.length * 4 + 32);
489
+ }
490
+ // ── Public accessors ───────────────────────────────────────────────────
491
+ get D() {
492
+ return this._D;
493
+ }
494
+ /** Await the async initialisation performed by the concrete constructor. */
495
+ async _ensureReady() {
496
+ if (!this._ready)
497
+ throw new Error("Store: not open");
498
+ await this._ready;
499
+ }
500
+ // ── Id management ──────────────────────────────────────────────────────
501
+ has(id) {
502
+ // Byte leaves (negative ids) always exist.
503
+ if (id < 0)
504
+ return id >= -256;
505
+ return Number.isInteger(id) && id >= 0 && id < this._nextId;
506
+ }
507
+ mintId() {
508
+ return this._nextId++;
509
+ }
510
+ nodeCount() {
511
+ return this._nextId;
512
+ }
513
+ async size() {
514
+ await this._ensureReady();
515
+ return this._nextId;
516
+ }
517
+ // ── DAG traversal ──────────────────────────────────────────────────────
518
+ get(id) {
519
+ if (this.meter)
520
+ this.meter.nodeRecords++;
521
+ // Byte leaves are implicit — fabricate from the id.
522
+ if (id < 0) {
523
+ return { id, leaf: new Uint8Array([-(id + 1)]), kids: null };
524
+ }
525
+ const hit = this._recCache.get(id);
526
+ if (hit !== undefined)
527
+ return hit;
528
+ const rec = this._dbGetNode(id);
529
+ if (rec)
530
+ this._recCache.set(id, rec);
531
+ return rec;
532
+ }
533
+ /** Reconstruct the bytes a node spans by traversing the DAG bottom-up.
534
+ * Iterative post-order on an explicit stack — the call stack never sees the
535
+ * tree depth, so even an adversarial chain of nodes stays safe. */
536
+ /** How many reads hit a MISSING node record this session (a dangling edge
537
+ * or kid id). Zero in a healthy store; a growing count means references
538
+ * outlive their records — the read degrades safely to empty bytes, this
539
+ * counter is what keeps that degradation observable. */
540
+ danglingReads = 0;
541
+ /** {@link Store.meter} — the per-response work accumulator, or null when
542
+ * nothing is profiling. Every read below bumps it through `?.`, so an
543
+ * unprofiled store pays one null check per read and allocates nothing. */
544
+ meter = null;
545
+ bytes(id) {
546
+ if (this.meter) {
547
+ this.meter.byteReads++;
548
+ // Charged BEFORE the fast path returns, and from the cache entry when
549
+ // there is one: the volume a caller pulled through is the cost signal
550
+ // (an unbounded read is unbounded whether or not it was cached).
551
+ const c = this._bytesCache.get(id);
552
+ if (c)
553
+ this.meter.bytesRead += c.length;
554
+ }
555
+ // Fast path.
556
+ const hit = this._bytesCache.get(id);
557
+ if (hit)
558
+ return hit;
559
+ const stack = [id];
560
+ const cache = this._bytesCache;
561
+ while (stack.length > 0) {
562
+ const nid = stack[stack.length - 1]; // peek
563
+ // Already resolved by an earlier traversal.
564
+ if (cache.get(nid)) {
565
+ stack.pop();
566
+ continue;
567
+ }
568
+ const rec = this.get(nid);
569
+ if (!rec) {
570
+ // A DANGLING id (an edge or kid pointing at no record) reads as
571
+ // empty — safe (empty-bytes guards drop it from grounding) but a
572
+ // symptom of store corruption, so count it rather than stay silent.
573
+ // The cache makes the empty read permanent for the session; the
574
+ // counter survives as the visible trace.
575
+ this.danglingReads++;
576
+ cache.set(nid, _ZERO);
577
+ stack.pop();
578
+ continue;
579
+ }
580
+ if (rec.leaf) {
581
+ cache.set(nid, new Uint8Array(rec.leaf));
582
+ stack.pop();
583
+ continue;
584
+ }
585
+ // Branch — push any uncached children (reverse order so they resolve
586
+ // left-to-right). If every child is already cached, concatenate now.
587
+ const kids = rec.kids ?? [];
588
+ let ready = true;
589
+ for (let i = kids.length - 1; i >= 0; i--) {
590
+ if (!cache.get(kids[i])) {
591
+ stack.push(kids[i]);
592
+ ready = false;
593
+ }
594
+ }
595
+ if (!ready)
596
+ continue;
597
+ stack.pop();
598
+ const out = concat(kids.map((k) => cache.get(k)));
599
+ cache.set(nid, out);
600
+ }
601
+ const out = cache.get(id) ?? _ZERO;
602
+ if (this.meter)
603
+ this.meter.bytesRead += out.length;
604
+ return out;
605
+ }
606
+ /** First `maxLen` bytes of a node. Walks only the leftmost branch,
607
+ * stopping at `maxLen` — so a 1 MB document root costs the same as a
608
+ * 4-byte leaf. Recursive, but tree depth is logarithmic.
609
+ *
610
+ * IMMUTABILITY CONTRACT (applies to {@link bytes} too): returned arrays
611
+ * may be shared with the byte cache and with other callers — treat them
612
+ * as read-only. Mutating one would corrupt every subsequent read. */
613
+ bytesPrefix(id, maxLen) {
614
+ // A FULL read (the ALL sentinel) routes through bytes(), whose
615
+ // reconstruction enters the byte-budget cache. Without this, the mind's
616
+ // read() — which always passes ALL — re-walked the DAG and re-concatenated
617
+ // on EVERY repeated read of an uncached branch, bypassing the cache that
618
+ // exists precisely for those reconstructions.
619
+ if (maxLen >= 0x7fffffff)
620
+ return this.bytes(id);
621
+ // METERING BOUNDARY: this public entry point is charged ONCE per logical
622
+ // read; the walk below recurses through `_prefix`, which is not charged.
623
+ // Counting the recursion instead made a single read of an N-byte branch
624
+ // report as N reads (one per node descended), so `byteReads` measured
625
+ // tree size rather than read requests — it read as ~1 byte per read.
626
+ if (this.meter)
627
+ this.meter.byteReads++;
628
+ const out = this._prefix(id, maxLen);
629
+ if (this.meter)
630
+ this.meter.bytesRead += out.length;
631
+ return out;
632
+ }
633
+ /** {@link bytesPrefix}'s recursive body — uncharged; see the metering
634
+ * boundary note there. */
635
+ _prefix(id, maxLen) {
636
+ if (maxLen <= 0)
637
+ return _ZERO;
638
+ // Full-cache hit: bytes() already reconstructed the whole node.
639
+ const full = this._bytesCache.get(id);
640
+ if (full)
641
+ return full.length <= maxLen ? full : full.subarray(0, maxLen);
642
+ const rec = this.get(id);
643
+ if (!rec)
644
+ return _ZERO;
645
+ if (rec.leaf) {
646
+ // Cache the (small) leaf bytes — cheap and reusable. COPY before
647
+ // caching: rec.leaf is the node record's own buffer, and handing it
648
+ // out would let one mutating caller corrupt the record AND the cache
649
+ // (bytes() makes the same copy for the same reason).
650
+ const leaf = new Uint8Array(rec.leaf);
651
+ this._bytesCache.set(id, leaf);
652
+ return leaf.length <= maxLen ? leaf : leaf.subarray(0, maxLen);
653
+ }
654
+ // Branch — walk children left-to-right, stopping at maxLen.
655
+ const kids = rec.kids ?? [];
656
+ const parts = [];
657
+ let got = 0;
658
+ for (const k of kids) {
659
+ if (got >= maxLen)
660
+ break;
661
+ const child = this._prefix(k, maxLen - got);
662
+ parts.push(child);
663
+ got += child.length;
664
+ }
665
+ return concat(parts);
666
+ }
667
+ contentLen(id, cap = Infinity) {
668
+ if (this.meter)
669
+ this.meter.lenReads++;
670
+ if (id < 0)
671
+ return 1; // implicit single-byte leaf
672
+ const hit = this._lenCache.get(id);
673
+ if (hit !== undefined)
674
+ return hit; // exact — valid under any cap
675
+ if (cap <= 0)
676
+ return 0;
677
+ const rec = this.get(id);
678
+ let n = 0;
679
+ let clamped = false;
680
+ if (rec) {
681
+ if (rec.leaf)
682
+ n = rec.leaf.length;
683
+ else if (rec.kids) {
684
+ for (const k of rec.kids) {
685
+ n += this.contentLen(k, cap - n);
686
+ if (n >= cap) {
687
+ clamped = true; // partial sum — a lower bound, not the length
688
+ break;
689
+ }
690
+ }
691
+ }
692
+ }
693
+ if (!clamped)
694
+ this._lenCache.set(id, n);
695
+ return n;
696
+ }
697
+ // ── Content-addressed lookup ───────────────────────────────────────────
698
+ findLeaf(bytes) {
699
+ if (this.meter)
700
+ this.meter.leafLookups++;
701
+ if (bytes.length === 1)
702
+ return -(bytes[0] + 1);
703
+ const key = keyOf(bytes);
704
+ const cached = this._leafKey.get(key);
705
+ if (cached !== undefined)
706
+ return cached;
707
+ const id = this._dbFindLeaf(hashOf(bytes), bytes);
708
+ if (id !== null)
709
+ this._leafKey.set(key, id);
710
+ return id;
711
+ }
712
+ findBranch(kids) {
713
+ if (this.meter)
714
+ this.meter.branchLookups++;
715
+ const key = kids.join(",");
716
+ const cached = this._branchKey.get(key);
717
+ if (cached !== undefined)
718
+ return cached;
719
+ const flat = flatKidsBytes(kids);
720
+ let id;
721
+ if (flat) {
722
+ id = this._dbFindBranchByLeaf(hashOf(flat), flat);
723
+ }
724
+ else {
725
+ const packed = packKids(kids);
726
+ id = this._dbFindBranchByKids(hashOf(packed), packed);
727
+ }
728
+ if (id !== null && key.length <= DEDUP_KEY_MAX) {
729
+ this._branchKey.set(key, id);
730
+ }
731
+ return id;
732
+ }
733
+ // ── Structural parents ─────────────────────────────────────────────────
734
+ parents(id) {
735
+ if (this.meter)
736
+ this.meter.parentReads++;
737
+ return this._dbGetParents(id);
738
+ }
739
+ parentsFirst(id, limit) {
740
+ if (this.meter)
741
+ this.meter.parentReads++;
742
+ return this._dbGetParentsFirst(id, limit);
743
+ }
744
+ hasParents(id) {
745
+ if (this.meter)
746
+ this.meter.parentProbes++;
747
+ return this._dbGetParentsFirst(id, 1).length > 0;
748
+ }
749
+ chainRun(id) {
750
+ if (this.meter)
751
+ this.meter.chainRuns++;
752
+ const hit = this._chainMemo.get(id);
753
+ if (hit !== undefined)
754
+ return hit;
755
+ const run = this._chainWalk(id, CHAIN_DEPTH_CAP);
756
+ this._chainMemo.set(id, run);
757
+ return run;
758
+ }
759
+ /** {@link Store.chainRun}'s walk, node at a time through the existing
760
+ * probes. Adapters with a set-based query engine should override with a
761
+ * single server-side descent (the SQLite adapter uses a recursive CTE). */
762
+ _chainWalk(id, cap) {
763
+ const run = [id];
764
+ let n = id;
765
+ while (run.length < cap) {
766
+ if (this.hasNext(n) || this.prevCount(n) > 0)
767
+ break;
768
+ const ps = this._dbGetParentsFirst(n, 2);
769
+ if (ps.length !== 1)
770
+ break;
771
+ n = ps[0];
772
+ run.push(n);
773
+ }
774
+ return run;
775
+ }
776
+ // ── Containment ────────────────────────────────────────────────────────
777
+ addContainer(child, parent) {
778
+ let set = this._containBuf.get(child);
779
+ if (set === undefined) {
780
+ set = new Set();
781
+ this._containBuf.set(child, set);
782
+ }
783
+ set.add(parent);
784
+ }
785
+ hasContainers(child) {
786
+ if (this.meter)
787
+ this.meter.containerProbes++;
788
+ if (this._dbContainExists(child))
789
+ return true;
790
+ const buf = this._containBuf.get(child);
791
+ return buf !== undefined && buf.size > 0;
792
+ }
793
+ containersSlice(child, offset, limit) {
794
+ if (this.meter)
795
+ this.meter.containerReads++;
796
+ const out = this._dbGetContainParentsSlice(child, offset, limit);
797
+ if (out.length >= limit)
798
+ return out;
799
+ // Buffered adds page in AFTER the stored ones. A buffered parent that is
800
+ // also stored may repeat across the seam; page consumers dedup by id
801
+ // (they all carry seen-sets), so a repeat costs a skip, never an error.
802
+ const buf = this._containBuf.get(child);
803
+ if (!buf || buf.size === 0)
804
+ return out;
805
+ const storedCount = this._dbGetContainCount(child);
806
+ const bufStart = Math.max(0, offset - storedCount) +
807
+ Math.max(0, out.length - Math.max(0, storedCount - offset));
808
+ let i = 0;
809
+ for (const p of buf) {
810
+ if (out.length >= limit)
811
+ break;
812
+ if (i++ < bufStart)
813
+ continue;
814
+ out.push(p);
815
+ }
816
+ return out;
817
+ }
818
+ containers(child) {
819
+ if (this.meter)
820
+ this.meter.containerReads++;
821
+ const stored = this._dbGetContainParents(child);
822
+ const buf = this._containBuf.get(child);
823
+ if (stored.length === 0)
824
+ return buf ? [...buf] : [];
825
+ if (!buf)
826
+ return stored;
827
+ const merged = new Set(stored);
828
+ for (const p of buf)
829
+ merged.add(p);
830
+ return [...merged];
831
+ }
832
+ // ── Walk kids to collect implicit per-byte leaf ids ────────────────────
833
+ flatLeafIds(kids) {
834
+ const out = [];
835
+ const stack = [...kids].reverse();
836
+ while (stack.length > 0) {
837
+ const id = stack.pop();
838
+ if (id < 0) {
839
+ out.push(id);
840
+ continue;
841
+ }
842
+ const rec = this.get(id);
843
+ if (!rec)
844
+ return null;
845
+ if (rec.leaf !== null) {
846
+ for (let i = 0; i < rec.leaf.length; i++)
847
+ out.push(-(rec.leaf[i] + 1));
848
+ }
849
+ else if (rec.kids !== null) {
850
+ for (let i = rec.kids.length - 1; i >= 0; i--)
851
+ stack.push(rec.kids[i]);
852
+ }
853
+ }
854
+ return out;
855
+ }
856
+ /** On a dedup HIT, keep the node's gist available for lazy indexing —
857
+ * EXACTLY when it is not already indexed. Replaces the old id-range
858
+ * "recency" heuristic (id ≥ nextId − cacheWindow), which conflated an LRU
859
+ * entry COUNT with an id RANGE and permanently refused to index any node
860
+ * that first became a resonance target long after it was minted (an early
861
+ * interior later reused as an edge/halo-bearing deposit root was silently
862
+ * unreachable by resonance). The durable index itself is the arbiter:
863
+ * one point query, cached in `_indexedIds` on a hit so repeats are O(1). */
864
+ captureIfUnindexed(id, gist) {
865
+ if (this._indexedIds.has(id) || this._pendingGist.has(id))
866
+ return;
867
+ if (this._vecContentHas(id)) {
868
+ this._indexedIds.set(id, true);
869
+ return;
870
+ }
871
+ this._pendingGist.set(id, normalize(copy(gist)));
872
+ // A node that ALREADY bridges experiences but was never indexed (its 1→2
873
+ // transition fired while its gist was evicted, or in a pre-transition
874
+ // store) is promoted on this re-encounter — the recapture above is
875
+ // exactly what makes its gist available again. Byte leaves (negative
876
+ // ids) never have kid rows, so skip their parent probe.
877
+ if (id >= 0)
878
+ this.promoteBridge(id);
879
+ }
880
+ /** If `id` structurally bridges ≥2 experiences (the post-hoc compaction
881
+ * criterion), promote its gist into the content index NOW — the exact
882
+ * moment it becomes useful for multi-experience recall. The 1→2 parent
883
+ * transition fires on {@link _dbInsertKid} during mint, and nodes that
884
+ * were already bridges but missed indexing (gist evicted, pre-transition
885
+ * store) are recaptured in {@link captureIfUnindexed}.
886
+ *
887
+ * A no-op when the node is already indexed or its gist is evicted from
888
+ * the pending cache — a future re-encounter will retry. */
889
+ promoteBridge(id) {
890
+ // A LIMITed probe: this runs once per kid insert on the MINT hot path,
891
+ // and a shared child's full parent set grows with the corpus.
892
+ if (this._dbGetParentsFirst(id, 2).length < 2)
893
+ return;
894
+ this.indexGist(id, false);
895
+ }
896
+ // ── Core interning: dedup → near-dedup → mint ──────────────────────────
897
+ async intern(leaf, kids, gist) {
898
+ await this._ensureReady();
899
+ // 1. Exact dedup — equal content → one id, no vector work. Primary
900
+ // compression mechanism, intrinsic to the store.
901
+ //
902
+ // findLeaf/findBranch are the content-addressed lookups: in-memory cache
903
+ // first, then a durable probe that repopulates the cache on a hit.
904
+ // Using them here (rather than only the cache) makes dedup survive a cold
905
+ // cache — a resumed/checkpointed training run, or one whose dedup cache
906
+ // has evicted old keys, still recognises content already on disk and
907
+ // reuses its id instead of minting a duplicate.
908
+ const hit = leaf !== null ? this.findLeaf(leaf) : this.findBranch(kids);
909
+ if (hit !== null) {
910
+ this.captureIfUnindexed(hit, gist);
911
+ return hit;
912
+ }
913
+ // 1b. Content-addressed lookup by leaf-id signature. When the same byte
914
+ // sequence was stored as a flat branch (via putBranch during deposit),
915
+ // a branch node spanning those bytes reuses that id even when its tree
916
+ // structure differs — pure content addressing, same bytes → same node.
917
+ if (kids !== null && kids.length >= 2) {
918
+ const leafIds = this.flatLeafIds(kids);
919
+ if (leafIds !== null) {
920
+ const flatHit = this.findBranch(leafIds);
921
+ if (flatHit !== null) {
922
+ this.captureIfUnindexed(flatHit, gist);
923
+ return flatHit;
924
+ }
925
+ }
926
+ }
927
+ const cache = leaf !== null ? this._leafKey : this._branchKey;
928
+ const key = leaf !== null ? keyOf(leaf) : kids.join(",");
929
+ // 2. Near dedup — BRANCHES ONLY, against RESONANCE TARGETS only.
930
+ // Leaves are single bytes: exact dedup already collapses every identical
931
+ // leaf, and near-merging distinct leaves only corrupts bytes for no real
932
+ // saving. Real near-dedup compression lives in subtree (branch) fusion.
933
+ //
934
+ // There is deliberately NO ANN probe of the FLUSHED index here. It used
935
+ // to fire for EVERY new branch that the buffer scan didn't settle — i.e.
936
+ // ~every interior branch, since interiors are never dedup targets —
937
+ // making one ANN query per branch the dominant training cost (it dwarfed
938
+ // perception and the index write). And it was not merely expensive but
939
+ // WRONG: the 1-bit RaBitQ code can rank a byte-DISTINCT branch as the
940
+ // nearest "target" of a fresh branch, so the fold collapsed two
941
+ // byte-different subtrees onto one id and corrupted exact reconstruction
942
+ // (02-roundtrip's random-byte streams). Real near-duplicate EXPERIENCES
943
+ // are caught two cheaper, exact ways instead: identical content by the
944
+ // exact-dedup hash-cons above, and a near-gist target still in the write
945
+ // buffer by the scan below.
946
+ if (leaf === null) {
947
+ // Near-dedup PREFILTER — the scale-aware identity bar
948
+ // ({@link identityBar}) for THIS branch's own length, not the fixed
949
+ // estimator floor: under the linear fold a long branch crosses
950
+ // 1 − 1/√D while whole windows differ, and every such crossing paid a
951
+ // full differsByOneWindow byte reconstruction. Same final semantics
952
+ // (the byte check below still decides identity); strictly fewer byte
953
+ // reads. The scan runs FIRST: the branch length (Σ kids' contentLen —
954
+ // memoized bottom-up by the interning order itself, O(kids)) is only
955
+ // computed once a nearest candidate actually exists, so the hot
956
+ // no-candidate mint pays nothing.
957
+ let best = -1;
958
+ let bestId = null;
959
+ if (this._nearDedupBuf.size > 0) {
960
+ const g = normalize(copy(gist));
961
+ // Candidates are the buffered DEDUP TARGETS only — genuine whole
962
+ // experiences (edge/halo-bearing roots) not yet flushed.
963
+ for (const [id, vector] of this._nearDedupBuf) {
964
+ const s = dot(g, vector);
965
+ if (s > best) {
966
+ best = s;
967
+ bestId = id;
968
+ }
969
+ }
970
+ }
971
+ let blen = 0;
972
+ if (bestId !== null) {
973
+ for (const k of kids)
974
+ blen += this.contentLen(k);
975
+ }
976
+ if (bestId !== null &&
977
+ best >= identityBar(this.D, this._maxGroup, blen)) {
978
+ // Scale-aware acceptance. The cosine bar alone is scale-BLIND
979
+ // against a scale-DEPENDENT quantity: the hierarchical fold dilutes
980
+ // a localized difference faster than linearly in form size, so for
981
+ // deep forms ANY fixed bar below 1 is crossed by exactly the one
982
+ // span that distinguishes two experiences. No inversion of the
983
+ // deficit is trustworthy, so the bytes themselves decide: the two
984
+ // forms must be identical except for ONE local span of at most W
985
+ // bytes — the river window, the perception's own resolution quantum.
986
+ const W = this._maxGroup;
987
+ if (this.differsByOneWindow(kids, bestId, W)) {
988
+ if (key.length <= DEDUP_KEY_MAX)
989
+ cache.set(key, bestId);
990
+ return bestId;
991
+ }
992
+ }
993
+ }
994
+ // 3. Mint a fresh node. A FLAT branch (every kid an implicit single-byte
995
+ // leaf) stores its BYTES in the leaf column with a zero-length kids blob
996
+ // as the marker — the kid list is derived on read.
997
+ const id = this.mintId();
998
+ this._dbBeginTx();
999
+ const flat = kids ? flatKidsBytes(kids) : null;
1000
+ const packed = kids && !flat ? packKids(kids) : null;
1001
+ this._dbInsertNode(id, leaf ?? flat, packed ?? (flat ? _ZERO : null), hashOf(leaf ?? flat ?? packed));
1002
+ // Reverse structural edge: each distinct child → this parent. Lets the graph
1003
+ // be climbed upward in index time, with no scan of the kids blobs.
1004
+ //
1005
+ // Populated NATURALLY here and only here — one write per child, in the SAME
1006
+ // mint that creates the node, inside the SAME deferred transaction as the
1007
+ // node row, so node and kid rows are always durable together.
1008
+ //
1009
+ // Implicit single-byte leaves get NO parent edge: a byte belongs to nearly
1010
+ // every branch, so its parent set is the corpus-sized hub the climb's
1011
+ // saturation guard discards unread.
1012
+ if (kids) {
1013
+ // Kid rows change parent counts — a child whose parent set grows from
1014
+ // one is no longer transparent, so every cached chain that hopped
1015
+ // through it is stale. Which chains those are is unknowable without a
1016
+ // reverse index, so the WHOLE cache drops (writes come in training
1017
+ // bursts where the cache is cold anyway; queries rebuild it lazily).
1018
+ this._chainMemo.clear();
1019
+ for (const c of kids) {
1020
+ if (c < 0 && c >= -256)
1021
+ continue;
1022
+ this._dbInsertKid(c, id);
1023
+ // The 1→2 parent TRANSITION happens here and only here (hash-cons
1024
+ // means an existing branch never re-inserts kid rows, so parent sets
1025
+ // grow exclusively through fresh mints): the child just became a
1026
+ // structural bridge between experiences — the exact set post-hoc
1027
+ // compaction keeps — so its gist enters the reach index NOW.
1028
+ this.promoteBridge(c);
1029
+ }
1030
+ }
1031
+ if (key.length <= DEDUP_KEY_MAX)
1032
+ cache.set(key, id);
1033
+ if (leaf)
1034
+ this._bytesCache.set(id, new Uint8Array(leaf));
1035
+ else if (flat)
1036
+ this._bytesCache.set(id, flat);
1037
+ // Capture the gist; it is pushed into the content index lazily, the first
1038
+ // time this node becomes a resonance target (link / pourHalo). A node that
1039
+ // never does (a pure intermediate DAG node — ~99.5% of them) is never
1040
+ // indexed: it costs one persistence row, no vector-index slot and no merge probe.
1041
+ this._pendingGist.set(id, normalize(copy(gist)));
1042
+ await this.maybeFlush();
1043
+ return id;
1044
+ }
1045
+ /** Whether the byte content under `kids` and the byte content of `targetId`
1046
+ * are identical except for ONE local span of at most `W` bytes on each side
1047
+ * — the near dedup's byte-grain definition of a near-duplicate. A
1048
+ * common-prefix / common-suffix trim: whatever remains after both trims is
1049
+ * the single differing span (substitution, insertion or deletion), and both
1050
+ * remainders must fit the budget. Scattered differences leave a wide
1051
+ * middle and are rejected. */
1052
+ differsByOneWindow(kids, targetId, W) {
1053
+ const a = concat(kids.map((k) => this.bytesPrefix(k, Number.MAX_SAFE_INTEGER)));
1054
+ const b = this.bytesPrefix(targetId, a.length + W + 1);
1055
+ if (Math.abs(a.length - b.length) > W)
1056
+ return false;
1057
+ const n = Math.min(a.length, b.length);
1058
+ let i = 0;
1059
+ while (i < n && a[i] === b[i])
1060
+ i++;
1061
+ let j = 0;
1062
+ while (j < n - i && a[a.length - 1 - j] === b[b.length - 1 - j])
1063
+ j++;
1064
+ return a.length - i - j <= W && b.length - i - j <= W;
1065
+ }
1066
+ async putLeaf(bytes, gist) {
1067
+ // Single bytes are implicit — no DB row and no eager index slot. The gist
1068
+ // is captured like any other node's and promoted into the content index
1069
+ // LAZILY, the first time the byte becomes a resonance target.
1070
+ if (bytes.length === 1) {
1071
+ const id = -(bytes[0] + 1);
1072
+ this.captureIfUnindexed(id, gist);
1073
+ return id;
1074
+ }
1075
+ return this.intern(new Uint8Array(bytes), null, gist);
1076
+ }
1077
+ async putBranch(kids, gist) {
1078
+ return this.intern(null, kids, gist);
1079
+ }
1080
+ // ── Lazy content indexing ──────────────────────────────────────────────
1081
+ /** Promote a node's captured gist into the content (resonance) index, once.
1082
+ * Called the first time a node becomes a target — i.e. from `link` (it bears
1083
+ * or receives a continuation edge) or `pourHalo` (it gains distributional
1084
+ * company). Idempotent: a node already indexed, or whose gist has been evicted
1085
+ * from the bounded pending map, is a no-op.
1086
+ *
1087
+ * `dedupTarget` marks the node a candidate the near dedup may fold a fresh
1088
+ * near-gist branch ONTO. Only a genuine target — an edge/halo-bearing ROOT —
1089
+ * is one; a climb-only interior is reach-indexed but never a dedup sink. */
1090
+ indexGist(id, dedupTarget) {
1091
+ if (dedupTarget && this._bufferedIds.has(id)) {
1092
+ // Still buffered (indexed this batch, not yet flushed) — a live dedup
1093
+ // candidate, recorded in O(1) with no scan of the content buffer.
1094
+ const v = this._pendingGist.get(id);
1095
+ if (v !== undefined)
1096
+ this._nearDedupBuf.set(id, v);
1097
+ }
1098
+ if (this._indexedIds.has(id))
1099
+ return;
1100
+ const v = this._pendingGist.get(id);
1101
+ if (v === undefined)
1102
+ return;
1103
+ // Already durably indexed by a previous session? A node id names its
1104
+ // content, and the gist is a pure function of the content, so the stored
1105
+ // vector can only be identical — re-buffering it would spend an encode
1106
+ // and an upsert on a guaranteed no-op. One point query recognises this;
1107
+ // it costs ~nothing for genuinely new nodes (a miss on a covering index).
1108
+ // This is what makes a RESUMED training run replay already-deposited
1109
+ // content at read speed instead of re-upserting the recent-id window.
1110
+ if (this._vecContentHas(id)) {
1111
+ this._indexedIds.set(id, true);
1112
+ return;
1113
+ }
1114
+ this._indexedIds.set(id, true);
1115
+ this._contentBuffer.push({ id, vector: v });
1116
+ this._bufferedIds.add(id);
1117
+ // A node indexed AS a dedup target enters the candidate set immediately.
1118
+ if (dedupTarget)
1119
+ this._nearDedupBuf.set(id, v);
1120
+ }
1121
+ /** {@link Store.indexTarget} — the public hook for marking a deposit root a
1122
+ * resonance target, the one target `link`/`pourHalo` do not cover. A deposit
1123
+ * root is a genuine target (a whole experience), so it is a dedup target
1124
+ * too. */
1125
+ indexTarget(id) {
1126
+ this.indexGist(id, true);
1127
+ }
1128
+ /** Index a node and its interior forms as resonance targets. A node that
1129
+ * gains an edge is a learnt EXPERIENCE, and the consensus climb
1130
+ * ({@link Mind.climbAttention}) answers a query naming only a PORTION of it by
1131
+ * resonating its SUB-REGIONS — branch nodes within the experience — and
1132
+ * climbing their parents back to it.
1133
+ *
1134
+ * EVERY interior branch is indexed unconditionally, and this is
1135
+ * LOAD-BEARING: indexing only structural bridges (nodes with ≥2 parents,
1136
+ * the post-hoc compaction criterion) was tried and REJECTED by the test
1137
+ * suite — partial recall of an experience's interior slices, multi-topic
1138
+ * attention, and counterfactual anchoring all resonate to SINGLE-parent
1139
+ * interiors (13 tests fail without them). Post-hoc structural compaction
1140
+ * ({@link compactContentIndex}) may still remove them, but that is a
1141
+ * storage/recall trade-off for archived stores, not a free optimisation.
1142
+ * The store's hash-cons bounds the index by the number of DISTINCT byte
1143
+ * patterns in the corpus — not by the number of deposits.
1144
+ *
1145
+ * Only the ROOT is a DEDUP TARGET — the whole experience a fresh near-gist
1146
+ * branch may legitimately fold onto. Interior nodes are REACH-ONLY: they
1147
+ * let a partial query resonate and climb, but a fresh branch must never
1148
+ * merge onto an interior node of another experience.
1149
+ *
1150
+ * Iterative explicit-queue walk: the call stack never sees tree depth. */
1151
+ indexSubtree(root) {
1152
+ // The root is the whole experience — always index as a merge target.
1153
+ this.indexGist(root, true);
1154
+ const seen = new Set([root]);
1155
+ const stack = [root];
1156
+ while (stack.length > 0) {
1157
+ const id = stack.pop();
1158
+ const kids = this.get(id)?.kids;
1159
+ if (!kids)
1160
+ continue; // leaf — never a resonance anchor
1161
+ const isRoot = id === root;
1162
+ // Already-indexed or already-skipped nodes PRUNE the walk — their
1163
+ // subtrees were classified in a prior call.
1164
+ if (!isRoot && (this._indexedIds.has(id) || this._coveredIds.has(id))) {
1165
+ continue;
1166
+ }
1167
+ for (const k of kids) {
1168
+ if (!seen.has(k)) {
1169
+ seen.add(k);
1170
+ stack.push(k);
1171
+ }
1172
+ }
1173
+ if (isRoot)
1174
+ continue;
1175
+ const g = this._pendingGist.get(id);
1176
+ if (g === undefined) {
1177
+ // Gist evicted from the bounded pending cache — the node can't be
1178
+ // indexed now. Mark as covered so subsequent visits prune here
1179
+ // instead of re-walking the subtree (the gist won't return).
1180
+ this._coveredIds.set(id, true);
1181
+ continue;
1182
+ }
1183
+ // Index unconditionally — every interior node is a valid resonance
1184
+ // anchor for partial-query recall. The _indexedIds cache and the
1185
+ // durable-index check in indexGist prevent duplicate indexing across
1186
+ // multiple encounters of the same shared subtree.
1187
+ this.indexGist(id, false);
1188
+ }
1189
+ }
1190
+ // ── Soft resonance ─────────────────────────────────────────────────────
1191
+ async resonate(v, k, exhaustive = false) {
1192
+ await this._ensureReady();
1193
+ // Synchronous flush of any buffered index writes: the FIRST resonance
1194
+ // after a large ingest pays that flush here, so it shows up in respond
1195
+ // latency, not ingest latency — correct behaviour, skewed attribution;
1196
+ // profile accordingly.
1197
+ this.flushContent();
1198
+ if (k <= 0)
1199
+ return [];
1200
+ // ANN read cache — content-addressed so a fresh Float32Array with the
1201
+ // same values still hits. Lazy-init: null after any index write; the
1202
+ // first miss after a flush recreates it. When voteRegions resonates
1203
+ // identical perceived sub-regions, only the first call descends the ANN.
1204
+ const rk = vecKey(v) + ":" + k + (exhaustive ? ":x" : "");
1205
+ const cache = this._resonateCache;
1206
+ if (cache) {
1207
+ const hit = cache.get(rk);
1208
+ if (hit !== undefined) {
1209
+ if (this.meter)
1210
+ this.meter.annCacheHits++;
1211
+ return hit;
1212
+ }
1213
+ }
1214
+ if (this.meter)
1215
+ this.meter.annQueries++;
1216
+ const clusters = this._vecContentClusterCount();
1217
+ const results = this._vecContentQuery(normalize(copy(v)), k * this.overfetch,
1218
+ // Exhaustive: probe every cluster (ef ≥ 4·clusters guarantees the
1219
+ // IVF's own ef→nprobe=ceil(ef/4) mapping reaches all of them) — the
1220
+ // natural ceiling for a search that is ALREADY refusal-path-only and
1221
+ // must not miss a candidate hiding in an unprobed cluster.
1222
+ exhaustive ? 4 * clusters : this.efFor(clusters));
1223
+ const out = [];
1224
+ for (const r of results) {
1225
+ const id = r.id;
1226
+ out.push({ id, score: 1 - r.distance });
1227
+ if (out.length >= k)
1228
+ break;
1229
+ }
1230
+ // Vectors the index actually scored for THIS descent — the counter that
1231
+ // exposes a query whose ANN cost is growing with the corpus.
1232
+ if (this.meter)
1233
+ this.meter.annVectorReads += this._vecContentLastReads();
1234
+ const rc = this._resonateCache ??= new Map();
1235
+ if (rc.size >= RESONATE_CACHE_MAX)
1236
+ rc.clear();
1237
+ rc.set(rk, out);
1238
+ return out;
1239
+ }
1240
+ indexedVectorCount() {
1241
+ this.flushContent();
1242
+ return this._vecContentSize();
1243
+ }
1244
+ lastResonateReads() {
1245
+ return this._vecContentLastReads();
1246
+ }
1247
+ // ── Content index compaction ────────────────────────────────────────────
1248
+ /** How many physical compaction attempts have failed this session. Zero in
1249
+ * a healthy store; a growing count means tombstones are accumulating and
1250
+ * index query cost is drifting up (the first failure also warns once). */
1251
+ compactFailures = 0;
1252
+ /** Meta key holding the incremental scan watermark of
1253
+ * {@link compactContentIndex}: "minParents:maxInternalIdScanned". KEEP
1254
+ * decisions are MONOTONE — parents, edges and halos only ever grow, so an
1255
+ * entry once kept can never become removable — and removed entries are
1256
+ * gone, so a pass only ever needs to examine entries indexed AFTER the
1257
+ * previous pass. Internal ids are monotone and survive the index's
1258
+ * splice compaction; the watermark is reset whenever a PHYSICAL index
1259
+ * compaction runs (id reuse after a dropped top row would otherwise hide
1260
+ * new entries behind it). */
1261
+ static COMPACT_WATERMARK_KEY = "contentCompact.watermark";
1262
+ /** {@link Store.compactContentIndex} */
1263
+ async compactContentIndex(minParents = 2) {
1264
+ await this._ensureReady();
1265
+ this.flush(); // commit any pending writes first
1266
+ // Incremental scan: resume from the last pass's watermark when its
1267
+ // minParents matches; a changed criterion forces a full rescan.
1268
+ let after = 0;
1269
+ {
1270
+ const raw = this._dbGetMeta(AbstractStore.COMPACT_WATERMARK_KEY);
1271
+ if (raw !== null) {
1272
+ const sep = raw.indexOf(":");
1273
+ const mp = Number(raw.slice(0, sep));
1274
+ const wm = Number(raw.slice(sep + 1));
1275
+ if (mp === minParents && Number.isFinite(wm) && wm > 0)
1276
+ after = wm;
1277
+ }
1278
+ }
1279
+ // The keep criterion "has edges or a halo" as ONE sorted id set (edge
1280
+ // sources ∪ edge targets ∪ halo rows), materialised by a single C-side
1281
+ // scan. A binary-search membership probe replaces the three per-entry
1282
+ // point queries that made this stage minutes long on a trained store.
1283
+ const targets = this._dbEdgeOrHaloIds();
1284
+ const isTarget = (id) => {
1285
+ let lo = 0, hi = targets.length - 1;
1286
+ while (lo <= hi) {
1287
+ const mid = (lo + hi) >> 1;
1288
+ const v = targets[mid];
1289
+ if (v === id)
1290
+ return true;
1291
+ if (v < id)
1292
+ lo = mid + 1;
1293
+ else
1294
+ hi = mid - 1;
1295
+ }
1296
+ return false;
1297
+ };
1298
+ // Collect ids to remove: nodes that are structurally isolated (few
1299
+ // parents), not edge-bearing, and not halo-bearing. These nodes are
1300
+ // unique to one experience tree — they bridge nothing and their index
1301
+ // slots are wasted. Multi-parent nodes are the structural bridges
1302
+ // that let a partial query climb from one experience to another.
1303
+ const toRemove = [];
1304
+ let scanned = 0;
1305
+ let watermark = after;
1306
+ for (const { ext: id, internal } of this._vecContentEntriesSince(after)) {
1307
+ // Yield a real event-loop turn on a fixed cadence: this scan runs over
1308
+ // every unexamined indexed entry, and point probes alone pin the
1309
+ // thread otherwise (the "frozen" symptom).
1310
+ if (++scanned % 8192 === 0)
1311
+ await yieldToEventLoop();
1312
+ watermark = internal;
1313
+ if (isTarget(id))
1314
+ continue;
1315
+ if (this._dbGetParentsFirst(id, minParents).length >= minParents) {
1316
+ continue;
1317
+ }
1318
+ toRemove.push(id);
1319
+ }
1320
+ // Delete in batches — each batch is ONE vector-store transaction (one WAL
1321
+ // commit), with an event-loop turn between batches.
1322
+ const BATCH = 1000;
1323
+ for (let i = 0; i < toRemove.length; i += BATCH) {
1324
+ const batch = toRemove.slice(i, i + BATCH);
1325
+ this._vecContentDeleteMany(batch);
1326
+ // Purge the "already indexed" cache for removed ids: without this, a
1327
+ // node that LATER becomes a resonance target again (gains an edge or
1328
+ // halo) hits the stale cache entry in indexGist and is silently never
1329
+ // re-indexed for the rest of the session.
1330
+ for (const id of batch)
1331
+ this._indexedIds.delete(id);
1332
+ await yieldToEventLoop();
1333
+ }
1334
+ // Persist the scan watermark so the next pass starts where this one
1335
+ // ended (kept beside the criterion that produced it).
1336
+ this._dbBeginTx();
1337
+ this._dbSetMeta(AbstractStore.COMPACT_WATERMARK_KEY, minParents + ":" + watermark);
1338
+ this._dbCommitTx();
1339
+ if (toRemove.length > 0) {
1340
+ // Compact to physically reclaim space from tombstones.
1341
+ try {
1342
+ if (this._vecContentPhysicalSize() > this._vecContentSize() * 1.5) {
1343
+ this._vecContentCompact();
1344
+ // Physical compaction may free the top internal id for reuse —
1345
+ // drop the watermark so the next pass rescans from the start.
1346
+ this._dbBeginTx();
1347
+ this._dbDeleteMeta(AbstractStore.COMPACT_WATERMARK_KEY);
1348
+ this._dbCommitTx();
1349
+ }
1350
+ }
1351
+ catch (e) {
1352
+ // Best-effort, but never SILENT: a persistently failing compaction
1353
+ // lets tombstones accumulate and query cost grow with no signal.
1354
+ this.compactFailures++;
1355
+ if (this.compactFailures === 1) {
1356
+ console.warn("sema: content-index compaction failed (will keep " +
1357
+ "counting in store.compactFailures):", e);
1358
+ }
1359
+ }
1360
+ // Index mutations (delete, compact) invalidate the ANN read cache.
1361
+ this._resonateCache = null;
1362
+ }
1363
+ return toRemove.length;
1364
+ }
1365
+ /** {@link Store.repairContentIndex} */
1366
+ async repairContentIndex(regenerateGist, minParents = 2) {
1367
+ await this._ensureReady();
1368
+ this.flush(); // commit any pending writes first
1369
+ if (this._nextId === 0)
1370
+ return 0;
1371
+ let added = 0;
1372
+ // A repairable node MUST carry edges or a halo, so the candidate set IS
1373
+ // the edge/halo id set — corpus-of-experiences-sized (hundreds of
1374
+ // thousands), not node-count-sized (tens of millions). The old walk
1375
+ // visited EVERY branch id ever minted with a parent probe each; driving
1376
+ // from the target set visits only real candidates, in the same ascending
1377
+ // id order (the set is sorted), so the result and its ordering are
1378
+ // identical. Byte leaves (negative ids) were never visited by the old
1379
+ // walk and are skipped here too.
1380
+ const targets = this._dbEdgeOrHaloIds();
1381
+ let scanned = 0;
1382
+ for (const id of targets) {
1383
+ // Yield a real event-loop turn on a fixed cadence so the scan never
1384
+ // pins the thread for its whole duration.
1385
+ if (++scanned % 8192 === 0)
1386
+ await yieldToEventLoop();
1387
+ if (id < 0)
1388
+ continue; // byte leaves: implicit, never repaired
1389
+ // Already indexed in memory — skip.
1390
+ if (this._indexedIds.has(id))
1391
+ continue;
1392
+ // Must be a structural bridge: ≥ minParents parents in the DAG.
1393
+ // One LIMITed probe per candidate.
1394
+ if (this._dbGetParentsFirst(id, minParents).length < minParents) {
1395
+ continue;
1396
+ }
1397
+ // Already durably indexed by a previous session — record and skip.
1398
+ // Probed AFTER the structural filters: candidates are few, so this
1399
+ // point query runs rarely instead of once per node in the store.
1400
+ if (this._vecContentHas(id)) {
1401
+ this._indexedIds.set(id, true);
1402
+ continue;
1403
+ }
1404
+ // Regenerate the gist from bytes. The callback is async (the Mind's
1405
+ // perception is synchronous, but the interface allows a disk-backed
1406
+ // regenerator that yields).
1407
+ const gist = await regenerateGist(id);
1408
+ if (!gist)
1409
+ continue;
1410
+ // Index it — same code path as indexGist, but the vector is injected
1411
+ // directly rather than read from the (empty) pending-gist cache.
1412
+ this._indexedIds.set(id, true);
1413
+ this._contentBuffer.push({ id, vector: gist });
1414
+ this._bufferedIds.add(id);
1415
+ // Repaired nodes are reach-indexed, never dedup targets: their gist is
1416
+ // regenerated (may differ numerically from the original) and they are
1417
+ // interiors, not deposit roots.
1418
+ added++;
1419
+ // Flush periodically to bound the write-transaction size and yield to
1420
+ // the event loop, same cadence compactContentIndex uses.
1421
+ if (added % 1000 === 0)
1422
+ await this.maybeFlush();
1423
+ }
1424
+ // Final flush for the last partial batch.
1425
+ if (added > 0)
1426
+ await this.maybeFlush();
1427
+ return added;
1428
+ }
1429
+ // ── Continuation edges ─────────────────────────────────────────────────
1430
+ async link(from, to) {
1431
+ await this._ensureReady();
1432
+ // Both endpoints become learnt EXPERIENCES whose whole subtree is REACH-
1433
+ // indexed, because the seat is symmetric — a query may name only a PORTION of
1434
+ // either side and must still resonate to its interior and climb to the whole.
1435
+ // Only each ROOT is a MERGE target; the interiors are reach-only.
1436
+ this.indexSubtree(from);
1437
+ this.indexSubtree(to);
1438
+ // Flush the vectors indexSubtree just added to the buffer.
1439
+ // This keeps the buffer bounded and yields to the event loop.
1440
+ await this.maybeFlush();
1441
+ this._dbBeginTx();
1442
+ // Keep the document count exact as it grows: a source gaining its FIRST
1443
+ // edge is one new learnt context. One indexed point probe, and only once
1444
+ // the count has been materialised — before that, the lazy full count in
1445
+ // {@link edgeSourceCount} will see this edge anyway.
1446
+ if (this._edgeSrcCount >= 0 && !this._dbEdgeSrcExists(from)) {
1447
+ this._edgeSrcCount++;
1448
+ }
1449
+ // An edge breaks the transparency of both endpoints — drop cached chains
1450
+ // (same reasoning as the kid-row invalidation in put).
1451
+ this._chainMemo.clear();
1452
+ this._dbInsertEdge(from, to);
1453
+ }
1454
+ next(id) {
1455
+ if (this.meter)
1456
+ this.meter.edgeReads++;
1457
+ return this._dbGetNextEdges(id);
1458
+ }
1459
+ /** {@link Store.hasNext} — one indexed point probe, never a range read. */
1460
+ hasNext(id) {
1461
+ if (this.meter)
1462
+ this.meter.edgeProbes++;
1463
+ return this._dbEdgeSrcExists(id);
1464
+ }
1465
+ prev(id) {
1466
+ if (this.meter)
1467
+ this.meter.prevReads++;
1468
+ return this._dbGetPrevEdges(id);
1469
+ }
1470
+ nextFirst(id, limit) {
1471
+ if (this.meter)
1472
+ this.meter.edgeReads++;
1473
+ return this._dbGetNextEdgesFirst(id, limit);
1474
+ }
1475
+ prevFirst(id, limit) {
1476
+ if (this.meter)
1477
+ this.meter.prevReads++;
1478
+ return this._dbGetPrevEdgesFirst(id, limit);
1479
+ }
1480
+ /** {@link Store.prevCount}. Subclasses with an indexed reverse-edge count
1481
+ * should override; this default materialises (correct, not optimal). */
1482
+ prevCount(id) {
1483
+ if (this.meter)
1484
+ this.meter.prevProbes++;
1485
+ return this._dbGetPrevEdges(id).length;
1486
+ }
1487
+ edgeSourceCount() {
1488
+ // Materialised once per session (edges written before this moment are
1489
+ // covered by the full count), then kept exact incrementally by link().
1490
+ // The old form re-ran a full COUNT(*) table scan on EVERY call just to
1491
+ // detect staleness — O(edges) on the recall hot path, at every IDF read.
1492
+ if (this._edgeSrcCount < 0) {
1493
+ this._edgeSrcCount = this._dbEdgeDistinctSrcCount();
1494
+ }
1495
+ return this._edgeSrcCount;
1496
+ }
1497
+ // ── Halos ──────────────────────────────────────────────────────────────
1498
+ haloMass(id) {
1499
+ if (this.meter)
1500
+ this.meter.haloProbes++;
1501
+ const r = this._dbGetHalo(id);
1502
+ return r ? r.mass : 0;
1503
+ }
1504
+ halo(id) {
1505
+ if (this.meter)
1506
+ this.meter.haloReads++;
1507
+ const cached = this._haloNorm.get(id);
1508
+ if (cached !== undefined)
1509
+ return copy(cached);
1510
+ const r = this._dbGetHalo(id);
1511
+ if (!r || r.mass < this.minHaloMass)
1512
+ return null;
1513
+ const exact = this._haloExact.get(id);
1514
+ const v = normalize(exact ? copy(exact) : haloDecode(r.vec, this.D));
1515
+ this._haloNorm.set(id, v);
1516
+ return copy(v);
1517
+ }
1518
+ /** {@link Store.hasHalo} — MUST mirror {@link halo}'s null condition
1519
+ * exactly (row present AND mass ≥ minHaloMass), minus the decode. */
1520
+ hasHalo(id) {
1521
+ if (this.meter)
1522
+ this.meter.haloProbes++;
1523
+ const r = this._dbGetHalo(id);
1524
+ return r !== null && r.mass >= this.minHaloMass;
1525
+ }
1526
+ async pourHalo(id, add) {
1527
+ await this._ensureReady();
1528
+ // A node with a halo is a genuine resonance target — the consensus climb
1529
+ // resonates a query region to it, and articulation reads its halo.
1530
+ this.indexGist(id, true);
1531
+ const r = this._dbGetHalo(id);
1532
+ const acc = this._haloExact.get(id) ??
1533
+ (r ? haloDecode(r.vec, this.D) : new Float32Array(this.D));
1534
+ addInto(acc, add);
1535
+ this._haloExact.set(id, acc);
1536
+ this._haloNorm.delete(id); // the normalized read cache is now stale
1537
+ const mass = (r?.mass ?? 0) + 1;
1538
+ this._dbBeginTx();
1539
+ this._dbUpsertHalo(id, haloEncode(acc), mass);
1540
+ // Re-index on a geometric schedule only (the exact halo is persisted).
1541
+ if (mass >= this.minHaloMass && geometricMass(mass)) {
1542
+ this._haloBuffer.set(id, normalize(copy(acc)));
1543
+ await this.maybeFlush();
1544
+ }
1545
+ }
1546
+ async resonateHalo(v, k) {
1547
+ await this._ensureReady();
1548
+ this.flushHalos();
1549
+ if (k <= 0)
1550
+ return [];
1551
+ // ANN read cache — same scheme as resonate's, but for the halo index.
1552
+ const rk = vecKey(v) + ":" + k;
1553
+ const cache = this._resonateHaloCache;
1554
+ if (cache) {
1555
+ const hit = cache.get(rk);
1556
+ if (hit !== undefined) {
1557
+ if (this.meter)
1558
+ this.meter.annCacheHits++;
1559
+ return hit;
1560
+ }
1561
+ }
1562
+ if (this.meter)
1563
+ this.meter.haloQueries++;
1564
+ const results = this._vecHaloQuery(normalize(copy(v)), k * this.overfetch, this.efFor(this._vecHaloClusterCount()));
1565
+ const out = [];
1566
+ for (const r of results) {
1567
+ const id = r.id;
1568
+ out.push({ id, score: 1 - r.distance });
1569
+ if (out.length >= k)
1570
+ break;
1571
+ }
1572
+ const rhc = this._resonateHaloCache ??= new Map();
1573
+ if (rhc.size >= RESONATE_CACHE_MAX)
1574
+ rhc.clear();
1575
+ rhc.set(rk, out);
1576
+ return out;
1577
+ }
1578
+ // ── Buffering, flushing, compaction ────────────────────────────────────
1579
+ pending() {
1580
+ return this._contentBuffer.length + this._haloBuffer.size;
1581
+ }
1582
+ flushContent() {
1583
+ if (this._contentBuffer.length === 0)
1584
+ return 0;
1585
+ const batch = this._contentBuffer.splice(0);
1586
+ // The merge scan only consults UNFLUSHED candidates, so clear them in
1587
+ // lockstep with the content buffer they mirror.
1588
+ this._nearDedupBuf.clear();
1589
+ this._bufferedIds.clear();
1590
+ this._vecContentUpsert(batch);
1591
+ this._resonateCache = null;
1592
+ return batch.length;
1593
+ }
1594
+ flushHalos() {
1595
+ if (this._haloBuffer.size === 0)
1596
+ return 0;
1597
+ const batch = [...this._haloBuffer.entries()];
1598
+ this._haloBuffer.clear();
1599
+ this._vecHaloUpsert(batch.map(([id, vector]) => ({ id, vector })));
1600
+ this._resonateHaloCache = null;
1601
+ return batch.length;
1602
+ }
1603
+ /** Append the buffered containment pairs, inside the deferred transaction.
1604
+ * Pure appends: durable dedup lives in the adapter (the pair PK), so a
1605
+ * flush never reads a child's stored list back — the old packed-blob
1606
+ * read-merge-rewrite was O(fan-in) per touched child per flush, quadratic
1607
+ * over a long training run on a hot window. */
1608
+ flushContain() {
1609
+ if (this._containBuf.size === 0)
1610
+ return;
1611
+ this._dbBeginTx();
1612
+ for (const [child, set] of this._containBuf) {
1613
+ this._dbAppendContain(child, [...set]);
1614
+ }
1615
+ this._containBuf.clear();
1616
+ }
1617
+ /** Flush all three buffers; compact vector indices on a write-volume cadence. */
1618
+ flush() {
1619
+ this.flushContain();
1620
+ const written = this.flushContent() + this.flushHalos();
1621
+ // Commit the deferred write transaction on the same cadence as the vector
1622
+ // buffers, so node rows / edges / halos become durable in coalesced batches.
1623
+ this._dbCommitTx();
1624
+ if (written === 0)
1625
+ return;
1626
+ this._writtenSinceCompact += written;
1627
+ if (this._writtenSinceCompact >= this.compactEveryNWrites) {
1628
+ this._writtenSinceCompact = 0;
1629
+ try {
1630
+ if (this._vecContentPhysicalSize() > this._vecContentSize() * 2) {
1631
+ this._vecContentCompact();
1632
+ // Physical compaction may free the top internal id for reuse —
1633
+ // invalidate the incremental maintenance watermark.
1634
+ this._dbBeginTx();
1635
+ this._dbDeleteMeta(AbstractStore.COMPACT_WATERMARK_KEY);
1636
+ this._dbCommitTx();
1637
+ }
1638
+ if (this._vecHaloPhysicalSize() > this._vecHaloSize() * 2) {
1639
+ this._vecHaloCompact();
1640
+ }
1641
+ }
1642
+ catch (e) {
1643
+ // Best-effort, but never SILENT (same contract as the prune-path
1644
+ // compaction above): a persistently failing compaction lets
1645
+ // tombstones accumulate and query cost grow with no signal.
1646
+ this.compactFailures++;
1647
+ if (this.compactFailures === 1) {
1648
+ console.warn("sema: vector-index compaction failed (will keep " +
1649
+ "counting in store.compactFailures):", e);
1650
+ }
1651
+ }
1652
+ }
1653
+ }
1654
+ async maybeFlush() {
1655
+ if (this.pending() >= this.batchSize) {
1656
+ this.flush();
1657
+ // A flush is the one HEAVY, fully-synchronous unit of the ingest path.
1658
+ // Every `await` elsewhere in ingestion resolves as a MICROTASK, which the
1659
+ // engine drains to empty before it ever services a MACROTASK — so a deposit
1660
+ // burst that only micro-awaits pins the single thread for its whole
1661
+ // duration, starving timers, pending I/O and any overlapped work. Here —
1662
+ // buffers empty, transaction committed, nothing mid-write — is the one
1663
+ // safe point to hand the event loop a real turn.
1664
+ await yieldToEventLoop();
1665
+ }
1666
+ }
1667
+ // ── Meta ───────────────────────────────────────────────────────────────
1668
+ async setMeta(key, val) {
1669
+ await this._ensureReady();
1670
+ this._dbBeginTx();
1671
+ this._dbSetMeta(key, val);
1672
+ }
1673
+ async getMeta(key) {
1674
+ await this._ensureReady();
1675
+ return this._dbGetMeta(key);
1676
+ }
1677
+ async deleteMeta(key) {
1678
+ await this._ensureReady();
1679
+ this._dbBeginTx();
1680
+ this._dbDeleteMeta(key);
1681
+ }
1682
+ // ── Snapshot ───────────────────────────────────────────────────────────
1683
+ async saveSnapshot(bytes) {
1684
+ await this._ensureReady();
1685
+ this.flush(); // commits any open write transaction + vector buffers
1686
+ this._dbSaveSnapshot(bytes);
1687
+ }
1688
+ async loadSnapshot() {
1689
+ await this._ensureReady();
1690
+ return this._dbLoadSnapshot();
1691
+ }
1692
+ // ── Lifecycle ──────────────────────────────────────────────────────────
1693
+ commit() {
1694
+ this.flush();
1695
+ }
1696
+ async close() {
1697
+ if (this.closed)
1698
+ return;
1699
+ this.closed = true;
1700
+ this.flush(); // commits any open write transaction + vector buffers
1701
+ this._dbClose();
1702
+ }
1703
+ }