counterparts 0.1.0

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 (195) hide show
  1. package/CONSTITUTION.md +68 -0
  2. package/LICENSE +21 -0
  3. package/README.md +348 -0
  4. package/docs/ELI5.md +84 -0
  5. package/docs/QUICKSTART.md +1258 -0
  6. package/docs/module-map.md +81 -0
  7. package/package.json +63 -0
  8. package/src/adapters/claude-code/CONTRACT.md +606 -0
  9. package/src/adapters/claude-code/INTERFACE-GAPS.md +655 -0
  10. package/src/adapters/claude-code/NOTES.md +1055 -0
  11. package/src/adapters/claude-code/bin/hook.ts +820 -0
  12. package/src/adapters/claude-code/bin/runner.ts +522 -0
  13. package/src/adapters/claude-code/config.ts +778 -0
  14. package/src/adapters/claude-code/credentials.ts +199 -0
  15. package/src/adapters/claude-code/doctor.ts +2557 -0
  16. package/src/adapters/claude-code/embed-client.ts +617 -0
  17. package/src/adapters/claude-code/hooks.ts +2240 -0
  18. package/src/adapters/claude-code/index.ts +224 -0
  19. package/src/adapters/claude-code/interpret-client.ts +395 -0
  20. package/src/adapters/claude-code/page-writer.ts +462 -0
  21. package/src/adapters/claude-code/primacy.ts +162 -0
  22. package/src/adapters/claude-code/spawn.ts +241 -0
  23. package/src/adapters/claude-code/standdown.ts +536 -0
  24. package/src/adapters/claude-code/transcript.ts +661 -0
  25. package/src/adapters/claude-code/vectors.ts +415 -0
  26. package/src/adapters/cli/CONTRACT.md +255 -0
  27. package/src/adapters/cli/INTERFACE-GAPS.md +350 -0
  28. package/src/adapters/cli/NOTES.md +936 -0
  29. package/src/adapters/cli/bin/counterparts.ts +74 -0
  30. package/src/adapters/cli/commands.ts +6095 -0
  31. package/src/adapters/cli/export.ts +766 -0
  32. package/src/adapters/cli/index.ts +103 -0
  33. package/src/adapters/cli/install.ts +670 -0
  34. package/src/adapters/cli/removal.ts +1186 -0
  35. package/src/adapters/cli/repair-dates.ts +659 -0
  36. package/src/adapters/cli/self-page.ts +229 -0
  37. package/src/adapters/cli/snapshot.ts +279 -0
  38. package/src/adapters/cli/start-fresh.ts +1228 -0
  39. package/src/adapters/config-path.ts +342 -0
  40. package/src/adapters/dashboard/CONTRACT.md +67 -0
  41. package/src/adapters/dashboard/INTERFACE-GAPS.md +139 -0
  42. package/src/adapters/dashboard/NOTES.md +474 -0
  43. package/src/adapters/dashboard/activity.ts +121 -0
  44. package/src/adapters/dashboard/ansi.ts +82 -0
  45. package/src/adapters/dashboard/bin/dashboard.ts +479 -0
  46. package/src/adapters/dashboard/browse.ts +298 -0
  47. package/src/adapters/dashboard/identity.ts +182 -0
  48. package/src/adapters/dashboard/index.ts +183 -0
  49. package/src/adapters/dashboard/layout.ts +149 -0
  50. package/src/adapters/dashboard/registries.ts +291 -0
  51. package/src/adapters/dashboard/resolve.ts +206 -0
  52. package/src/adapters/dashboard/source.ts +48 -0
  53. package/src/adapters/dashboard/status.ts +327 -0
  54. package/src/adapters/dashboard/stories.ts +194 -0
  55. package/src/adapters/dashboard/web/app.html +1731 -0
  56. package/src/adapters/dashboard/web/brain.html +463 -0
  57. package/src/adapters/dashboard/web/fired.ts +31 -0
  58. package/src/adapters/dashboard/web/flow.ts +457 -0
  59. package/src/adapters/dashboard/web/narrate.ts +1042 -0
  60. package/src/adapters/dashboard/web/reveal.ts +135 -0
  61. package/src/adapters/dashboard/web/server.ts +287 -0
  62. package/src/adapters/dashboard/web/views.ts +1744 -0
  63. package/src/adapters/expansions.ts +569 -0
  64. package/src/adapters/fired.ts +1580 -0
  65. package/src/adapters/mcp/CONTRACT.md +240 -0
  66. package/src/adapters/mcp/INTERFACE-GAPS.md +271 -0
  67. package/src/adapters/mcp/NOTES.md +205 -0
  68. package/src/adapters/mcp/bin/serve.ts +349 -0
  69. package/src/adapters/mcp/deliberate.ts +619 -0
  70. package/src/adapters/mcp/index.ts +101 -0
  71. package/src/adapters/mcp/protocol.ts +170 -0
  72. package/src/adapters/mcp/server.ts +1740 -0
  73. package/src/adapters/mcp/stdio.ts +56 -0
  74. package/src/adapters/mcp/tools.ts +779 -0
  75. package/src/adapters/scopes.ts +657 -0
  76. package/src/adapters/sessions.ts +402 -0
  77. package/src/adapters/snapshots.ts +1069 -0
  78. package/src/adapters/stance-env.ts +137 -0
  79. package/src/core/associate/CONTRACT.md +118 -0
  80. package/src/core/associate/INTERFACE-GAPS.md +173 -0
  81. package/src/core/associate/NOTES.md +194 -0
  82. package/src/core/associate/buffer.ts +66 -0
  83. package/src/core/associate/edges.ts +188 -0
  84. package/src/core/associate/index.ts +570 -0
  85. package/src/core/associate/pending.ts +383 -0
  86. package/src/core/associate/spread.ts +149 -0
  87. package/src/core/associate/tunables.ts +123 -0
  88. package/src/core/bridge.ts +272 -0
  89. package/src/core/briefing.ts +67 -0
  90. package/src/core/counterpart.ts +3855 -0
  91. package/src/core/encode/CONTRACT.md +151 -0
  92. package/src/core/encode/INTERFACE-GAPS.md +135 -0
  93. package/src/core/encode/NOTES.md +146 -0
  94. package/src/core/encode/aliases.ts +71 -0
  95. package/src/core/encode/battery.ts +284 -0
  96. package/src/core/encode/chunk.ts +265 -0
  97. package/src/core/encode/emotion.ts +119 -0
  98. package/src/core/encode/floor.ts +76 -0
  99. package/src/core/encode/index.ts +100 -0
  100. package/src/core/encode/precision.ts +162 -0
  101. package/src/core/encode/preselect.ts +269 -0
  102. package/src/core/encode/salience.ts +108 -0
  103. package/src/core/encode/secrets.ts +265 -0
  104. package/src/core/encode/tunables.ts +99 -0
  105. package/src/core/encode/types.ts +286 -0
  106. package/src/core/encode/words.ts +75 -0
  107. package/src/core/handoff/CONTRACT.md +199 -0
  108. package/src/core/handoff/INTERFACE-GAPS.md +166 -0
  109. package/src/core/handoff/NOTES.md +206 -0
  110. package/src/core/handoff/index.ts +957 -0
  111. package/src/core/mint.ts +279 -0
  112. package/src/core/observer.ts +28 -0
  113. package/src/core/physics/CONTRACT.md +341 -0
  114. package/src/core/physics/NOTES.md +155 -0
  115. package/src/core/physics/clock.ts +51 -0
  116. package/src/core/physics/index.ts +1054 -0
  117. package/src/core/prospective/CONTRACT.md +137 -0
  118. package/src/core/prospective/INTERFACE-GAPS.md +112 -0
  119. package/src/core/prospective/NOTES.md +160 -0
  120. package/src/core/prospective/derive.ts +188 -0
  121. package/src/core/prospective/index.ts +1030 -0
  122. package/src/core/prospective/tunables.ts +72 -0
  123. package/src/core/prospective/windows.ts +187 -0
  124. package/src/core/recall/CONTRACT.md +326 -0
  125. package/src/core/recall/INTERFACE-GAPS.md +163 -0
  126. package/src/core/recall/NOTES.md +472 -0
  127. package/src/core/recall/activate.ts +521 -0
  128. package/src/core/recall/cues.ts +275 -0
  129. package/src/core/recall/gate.ts +441 -0
  130. package/src/core/recall/index.ts +692 -0
  131. package/src/core/recall/probe.ts +239 -0
  132. package/src/core/recall/reference.ts +201 -0
  133. package/src/core/recall/render.ts +285 -0
  134. package/src/core/recall/session.ts +403 -0
  135. package/src/core/recall/tunables.ts +329 -0
  136. package/src/core/remember/CONTRACT.md +293 -0
  137. package/src/core/remember/INTERFACE-GAPS.md +189 -0
  138. package/src/core/remember/NOTES.md +373 -0
  139. package/src/core/remember/fallback.ts +452 -0
  140. package/src/core/remember/index.ts +103 -0
  141. package/src/core/remember/owner-strike-seam.ts +479 -0
  142. package/src/core/remember/proposals.ts +609 -0
  143. package/src/core/remember/spans.ts +1310 -0
  144. package/src/core/remember/tunables.ts +111 -0
  145. package/src/core/remember/updates.ts +198 -0
  146. package/src/core/retrieval.ts +96 -0
  147. package/src/core/revision.ts +441 -0
  148. package/src/core/schemas/CONTRACT.md +190 -0
  149. package/src/core/schemas/INTERFACE-GAPS.md +172 -0
  150. package/src/core/schemas/NOTES.md +260 -0
  151. package/src/core/schemas/aliases.ts +160 -0
  152. package/src/core/schemas/index.ts +1459 -0
  153. package/src/core/schemas/tunables.ts +44 -0
  154. package/src/core/schemas/types.ts +387 -0
  155. package/src/core/self/CONTRACT.md +459 -0
  156. package/src/core/self/INTERFACE-GAPS.md +284 -0
  157. package/src/core/self/NOTES.md +1057 -0
  158. package/src/core/self/briefing.ts +980 -0
  159. package/src/core/self/episodes.ts +483 -0
  160. package/src/core/self/freeze.ts +103 -0
  161. package/src/core/self/identity.ts +604 -0
  162. package/src/core/self/index.ts +2130 -0
  163. package/src/core/self/journal-file.ts +760 -0
  164. package/src/core/self/page.ts +404 -0
  165. package/src/core/self/tunables.ts +244 -0
  166. package/src/core/self/writer.ts +714 -0
  167. package/src/core/sleep/CONTRACT.md +298 -0
  168. package/src/core/sleep/INTERFACE-GAPS.md +262 -0
  169. package/src/core/sleep/NOTES.md +770 -0
  170. package/src/core/sleep/briefing.ts +86 -0
  171. package/src/core/sleep/consolidate.ts +241 -0
  172. package/src/core/sleep/cycle.ts +598 -0
  173. package/src/core/sleep/decay.ts +237 -0
  174. package/src/core/sleep/dedup.ts +373 -0
  175. package/src/core/sleep/index.ts +112 -0
  176. package/src/core/sleep/log.ts +116 -0
  177. package/src/core/sleep/markers.ts +164 -0
  178. package/src/core/sleep/prune.ts +170 -0
  179. package/src/core/sleep/strength-cache.ts +176 -0
  180. package/src/core/sleep/tunables.ts +135 -0
  181. package/src/core/sleep/types.ts +542 -0
  182. package/src/core/store/CONTRACT.md +446 -0
  183. package/src/core/store/NOTES.md +1068 -0
  184. package/src/core/store/cache.ts +709 -0
  185. package/src/core/store/db.ts +275 -0
  186. package/src/core/store/errors.ts +134 -0
  187. package/src/core/store/index.ts +2450 -0
  188. package/src/core/store/operational.ts +610 -0
  189. package/src/core/store/owner-op-seam.ts +428 -0
  190. package/src/core/store/paths.ts +494 -0
  191. package/src/core/store/prose.ts +165 -0
  192. package/src/core/store/render.ts +87 -0
  193. package/src/core/store/walk-seam.ts +78 -0
  194. package/src/core/types.ts +68 -0
  195. package/tools/install-loop/run.sh +1063 -0
@@ -0,0 +1,709 @@
1
+ /**
2
+ * Box 3 — the rebuildable cache: a SEPARATE sqlite file for the inverted text index
3
+ * and embeddings. Never backed up. Its loss is a re-index, never a memory.
4
+ *
5
+ * The index is a plain inverted table rather than FTS5 on purpose: FTS5 is a
6
+ * compile-time option and the two runtimes we support do not guarantee it the same
7
+ * way. The simplest thing that answers a cue identically on both is 40 lines of
8
+ * tokenizer (constitution line 15 — machinery is earned, not anticipated).
9
+ */
10
+ import type { Db, SqlValue } from "./db.js";
11
+ import { openDb } from "./db.js";
12
+
13
+ /**
14
+ * Bumped to 2 (2026-08-25, SEAMS item J): the `ranking` table joins box 3.
15
+ * Bumped to 3 (2026-09-04): `doc_lens` — the document length the cue channel
16
+ * needs to stop rewarding a memory for being long (see `LengthNorm` below).
17
+ * Bumped to 4 (2026-09-05): embeddings are written as a float32 BLOB rather
18
+ * than JSON text (see `encodeVector`). The bump changes what a WRITE produces;
19
+ * reads stay tolerant of both shapes, and `counterparts migrate-cache`
20
+ * converts the rows already on disk.
21
+ */
22
+ export const CACHE_SCHEMA_VERSION = 4;
23
+
24
+ const DDL: readonly string[] = [
25
+ `CREATE TABLE IF NOT EXISTS doc_tokens (
26
+ memory_id TEXT NOT NULL,
27
+ token TEXT NOT NULL,
28
+ tf INTEGER NOT NULL,
29
+ PRIMARY KEY (memory_id, token)
30
+ )`,
31
+ `CREATE INDEX IF NOT EXISTS doc_tokens_token ON doc_tokens (token)`,
32
+ // Document length, in indexed tokens — SUM(tf) over the row's `doc_tokens`.
33
+ //
34
+ // It is DERIVED FROM `doc_tokens` AND NOTHING ELSE, which is the whole reason
35
+ // it is its own table rather than a column somewhere upstream: a cache that
36
+ // predates this version rebuilds its lengths with one `GROUP BY` over the
37
+ // index it already has (`backfillLengths` below) — no prose read, no embedder,
38
+ // and above all no `resetCache`, which would drop 13,868 vectors that cost a
39
+ // network call each to recompute.
40
+ `CREATE TABLE IF NOT EXISTS doc_lens (
41
+ memory_id TEXT PRIMARY KEY,
42
+ len INTEGER NOT NULL
43
+ )`,
44
+ // `vec` is a float32 BLOB: `dim` little-endian IEEE-754 singles, `dim * 4`
45
+ // bytes (v4, 2026-09-05). It was JSON text through v3, and the declared type
46
+ // here is AFFINITY, not a constraint — a v3 cache whose table says `TEXT`
47
+ // stores a bound BLOB as a BLOB (SQLite's TEXT affinity keeps NULL/TEXT/BLOB
48
+ // storage classes unchanged), so the write side needs no table rewrite and
49
+ // the read side decodes whichever shape a row actually holds.
50
+ `CREATE TABLE IF NOT EXISTS embeddings (
51
+ memory_id TEXT PRIMARY KEY,
52
+ dim INTEGER NOT NULL,
53
+ vec BLOB NOT NULL
54
+ )`,
55
+ `CREATE TABLE IF NOT EXISTS cache_meta (
56
+ key TEXT PRIMARY KEY,
57
+ value TEXT NOT NULL
58
+ )`,
59
+ // SEAMS item J — the materialized ranking cache.
60
+ //
61
+ // Strength is a PURE FUNCTION of stored state and the lived day (physics §5.4),
62
+ // so nothing here is truth: it is `strength(m, d)` and `band(m, d)` written down
63
+ // so a ranker need not recompute the whole store per query. Delete the file and
64
+ // the next decay tick re-materializes every row.
65
+ //
66
+ // It lives in box 3's own file (and in `TABLES`, so `resetCache` drops it with
67
+ // the rest) rather than in the side file `sleep/strength-cache.ts` opened: the
68
+ // store holds the write lock on this database, and two connections contending
69
+ // for it left box 3 with two owners and one rebuild story
70
+ // (sleep/INTERFACE-GAPS.md §1).
71
+ `CREATE TABLE IF NOT EXISTS ranking (
72
+ memory_id TEXT PRIMARY KEY,
73
+ strength REAL NOT NULL,
74
+ band TEXT NOT NULL,
75
+ day INTEGER NOT NULL
76
+ )`,
77
+ ];
78
+
79
+ const TABLES = ["doc_tokens", "doc_lens", "embeddings", "cache_meta", "ranking"] as const;
80
+
81
+ /**
82
+ * Length normalization for the token channel — the document side of §9 G4.
83
+ *
84
+ * Cue matching is already rarity-weighted on the CUE side: a token spanning the
85
+ * whole store is evidence of nothing, and that zero is what replaces the stop
86
+ * list. This is the same rule read from the other end of the edge: **a memory
87
+ * spanning every topic is specific evidence for none of them.** Before this,
88
+ * `searchIndex` scored a document by raw `SUM(tf)` and took the top `limit` by
89
+ * it, so the longest documents in the store won every cue — measured
90
+ * 2026-09-04 on the live store, where nine memories of 9–20 KB (against a
91
+ * ~1.1 KB median, ~106 indexed tokens) came back as footnotes for every topic
92
+ * across two unrelated sessions and were judged 0-of-9 relevant.
93
+ *
94
+ * The formula is BM25's, and it is chosen because it is the SMALLEST change
95
+ * that could work (constitution 15): the old score's saturating half,
96
+ * `2·tf/(tf+1)`, is exactly this expression at `b = 0, k1 = 1`. Turning `b` up
97
+ * adds length normalization and moves nothing else.
98
+ *
99
+ * score(tok, doc) = tf·(k1+1) / ( tf + k1·( 1 − b + b·len/avgLen ) )
100
+ *
101
+ * The CAL home for these numbers — the calibration record, with how they were
102
+ * chosen — is `src/core/recall/tunables.ts` (`CUE_TF_SATURATION`,
103
+ * `CUE_LENGTH_NORM`). This default exists because `search()` has two callers
104
+ * that are not recall (`counterpart.ts`'s update-candidate lookup and the CLI's
105
+ * contamination scan), and a test asserts the two agree.
106
+ */
107
+ export interface LengthNorm {
108
+ /** tf saturation (BM25 k1). 1.0 reproduces the previous `2·tf/(tf+1)`. */
109
+ readonly k1: number;
110
+ /** length normalization (BM25 b). 0 = none; 1 = fully proportional. */
111
+ readonly b: number;
112
+ /**
113
+ * ONE-SIDED: clamp the length factor at 1, so a long document is penalized
114
+ * and a short one is never REWARDED.
115
+ *
116
+ * BM25's factor is centered on the mean, so at `b = 0.75` a very short
117
+ * document scores up to ~1.6× what it scored with no normalization at all.
118
+ * That is fine for ranking — ranking is relative — and it is not fine for the
119
+ * gate's ABSOLUTE floors (`FLOOR_GLOBAL_UNITS`, `FLOOR_STRONG_DEFAULT_UNITS`),
120
+ * which a candidate clears in a fixed number of cue units. Clamping keeps
121
+ * every score at or below its previous value, so a floor means what it meant.
122
+ *
123
+ * Measured before shipping (`tools/recall-bench`, 13 real prompts, 2026-09-04),
124
+ * and the measurement REFUSED the hypothesis it was built to confirm: clamping
125
+ * does NOT bring the loud tier down (24 one-sided vs 23 two-sided at b=0.75,
126
+ * against 4 before). So the loud-tier inflation is the RELATIVE BAR meeting a
127
+ * distribution that no longer has nine outliers setting its variance — not the
128
+ * scale meeting old floors. That question is now answered, and it is answered
129
+ * against the clamp. Recorded because a flag kept for a reason that turned out
130
+ * to be false is how a codebase accumulates folklore.
131
+ *
132
+ * The clamp ships anyway, for the two reasons that survived: at `b = 0.5` it
133
+ * is the only configuration in the grid that recovers an AMBIENT labeled
134
+ * positive (a correction the owner once gave, as a turn-4 footnote — see
135
+ * `recall/tunables.ts`), and it is the conservative
136
+ * arithmetic — no score exceeds what it was before normalization, so an
137
+ * inherited absolute floor still means what it meant.
138
+ */
139
+ readonly oneSided?: boolean;
140
+ }
141
+
142
+ export const DEFAULT_LENGTH_NORM: LengthNorm = { k1: 1, b: 0.5, oneSided: true };
143
+
144
+ /**
145
+ * Mean document length, memoized per open database.
146
+ *
147
+ * A recall pass issues up to `MAX_CUES` index probes, and re-deriving
148
+ * `AVG(len)` over 15k rows inside each of them is real time against a 1200 ms
149
+ * budget. Staleness is harmless by construction: this is a SMOOTHING CONSTANT,
150
+ * not truth — it moves by a fraction of a token when a memory is written, and
151
+ * every writer here invalidates it anyway. A second process's writes are not
152
+ * seen until this one reopens, which is the same tolerance box 3 already has.
153
+ */
154
+ const avgLenMemo = new WeakMap<Db, number>();
155
+
156
+ export function avgDocLen(db: Db): number {
157
+ const memo = avgLenMemo.get(db);
158
+ if (memo !== undefined) return memo;
159
+ const row = db.get<{ a: number | null }>("SELECT AVG(len) AS a FROM doc_lens");
160
+ const avg = row?.a !== null && row?.a !== undefined && row.a > 0 ? row.a : 1;
161
+ avgLenMemo.set(db, avg);
162
+ return avg;
163
+ }
164
+
165
+ function forgetAvgDocLen(db: Db): void {
166
+ avgLenMemo.delete(db);
167
+ }
168
+
169
+ /**
170
+ * The v2 → v3 migration, and the reason the length column is not a rebuild.
171
+ *
172
+ * Lengths are a pure function of `doc_tokens`, so an existing cache re-derives
173
+ * them with one aggregate — no prose read, no embedder, and no `resetCache`.
174
+ * That distinction is the whole point: `rebuildCache()` drops `embeddings`, and
175
+ * on a store whose embedder is not configured in the migrating process, those
176
+ * vectors do not come back. Returns the number of rows written.
177
+ */
178
+ export function backfillLengths(db: Db): number {
179
+ const have = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM doc_lens")?.n ?? 0;
180
+ if (have > 0) return 0;
181
+ db.run(
182
+ `INSERT OR REPLACE INTO doc_lens (memory_id, len)
183
+ SELECT memory_id, SUM(tf) FROM doc_tokens GROUP BY memory_id`,
184
+ );
185
+ forgetAvgDocLen(db);
186
+ return db.get<{ n: number }>("SELECT COUNT(*) AS n FROM doc_lens")?.n ?? 0;
187
+ }
188
+
189
+ export function openCache(path: string): Db {
190
+ // WAL here whatever the stance, unlike box 2: the dashboard and the worker read
191
+ // and write this file at the same time, its sidecars live inside `cache/` where
192
+ // nothing classifies them, and box 3 is DECLARED rebuildable — the same reason
193
+ // the constructor lets an instrument materialize this directory at all.
194
+ const db = openDb(path, { wal: true });
195
+ // Idempotent open: write the version row only when it differs. An observer
196
+ // constructing a Store over an up-to-date cache must not churn a byte — the
197
+ // dashboard build measured exactly that churn and filed it (its gap §1).
198
+ // A fresh or outdated cache still initializes (box 3 is rebuildable, and an
199
+ // absent cache is not canonical state), but the steady state is read-only.
200
+ const existing = (() => {
201
+ try {
202
+ const row = db.get<{ value: string }>("SELECT value FROM cache_meta WHERE key = 'schemaVersion'");
203
+ return row?.value ?? null;
204
+ } catch {
205
+ return null; // table absent: fresh cache
206
+ }
207
+ })();
208
+ if (existing !== String(CACHE_SCHEMA_VERSION)) {
209
+ db.transaction(() => {
210
+ for (const sql of DDL) db.exec(sql);
211
+ // The version bump and the lengths it promises land in ONE transaction:
212
+ // a cache stamped v3 with no lengths would score every document as if it
213
+ // were average, silently, which is the failure this version exists to end.
214
+ backfillLengths(db);
215
+ db.run("INSERT OR REPLACE INTO cache_meta (key, value) VALUES ('schemaVersion', ?)", String(CACHE_SCHEMA_VERSION));
216
+ });
217
+ }
218
+ return db;
219
+ }
220
+
221
+ /**
222
+ * Scoped to box 3 alone: drops only this file's tables, touches no canonical state.
223
+ *
224
+ * `keepEmbeddings` spares exactly one table, and it exists because "rebuildable"
225
+ * is not the same claim for all four. `doc_tokens`, `doc_lens` and `ranking` are
226
+ * recomputed from state this process already holds; `embeddings` are recomputed
227
+ * from a PAID NETWORK CALL, one per row, and a console with no embedder wired
228
+ * cannot put them back at all (`adapters/cli/NOTES.md`, 2026-09-04 — a bare
229
+ * `verify` would have dropped ~13,700 of them). The table is left in place
230
+ * rather than read out and rewritten, so nothing has to fit in memory.
231
+ */
232
+ export function resetCache(db: Db, opts: { keepEmbeddings?: boolean } = {}): void {
233
+ const drop = opts.keepEmbeddings === true ? TABLES.filter((t) => t !== "embeddings") : TABLES;
234
+ forgetAvgDocLen(db);
235
+ db.transaction(() => {
236
+ for (const t of drop) db.exec(`DROP TABLE IF EXISTS ${t}`);
237
+ for (const sql of DDL) db.exec(sql);
238
+ db.run("INSERT OR REPLACE INTO cache_meta (key, value) VALUES ('schemaVersion', ?)", String(CACHE_SCHEMA_VERSION));
239
+ });
240
+ }
241
+
242
+ // ── vectors: the wire shape of box 3's embeddings ────────────────────────────
243
+
244
+ /**
245
+ * A vector as box 3 stores it since v4: **`dim` little-endian float32s**, not
246
+ * JSON text.
247
+ *
248
+ * The measurement that motivated it (`docs/LAUNCH-STATUS.md` §E-W1(4), and the
249
+ * synthetic re-measurement in this module's NOTES): at 1,024 dimensions a JSON
250
+ * row is ~12.7 KB against 4 KB of float32, and `nearest()` — a full scan that
251
+ * `JSON.parse`d every row — cost 590–1,040 ms on the live store's ~13.9K
252
+ * vectors. Nothing about that is the parser being slow; it is the SCAN reading
253
+ * three times the bytes and then allocating a 1,024-element `number[]` per row
254
+ * to throw away.
255
+ *
256
+ * **float32 is not a lossy choice for an embedding, it is the embedder's own
257
+ * precision.** Every provider this adapter speaks to computes and serves single
258
+ * precision; JSON text was storing float64 room that never held float64
259
+ * information. What float32 IS lossy about is a value that arrived as a
260
+ * float64 which is not exactly representable as a float32 — a re-serialized
261
+ * vector, a hand-written test fixture — and there the round trip moves the
262
+ * value by at most one float32 ulp (~1e-7 relative). `nearest` accumulates in
263
+ * float64 either way, so for a vector whose values are already float32-exact
264
+ * (`Math.fround(x) === x`) the scores are BIT-IDENTICAL before and after; that
265
+ * is the property `test/store.test.ts` pins, and the general case is pinned as
266
+ * same-order, ≤1e-6 score movement.
267
+ */
268
+ export function encodeVector(vec: readonly number[]): Uint8Array {
269
+ const f = new Float32Array(vec.length);
270
+ // `Number.isFinite`, not `?? 0`: a `NaN` or an infinity is not a coordinate,
271
+ // and it must not reach the scan. v3 coerced it by accident —
272
+ // `JSON.stringify(NaN)` is `"null"` and `JSON.parse` gave back `null ?? 0` —
273
+ // so writing it through would have been a REGRESSION dressed as a format
274
+ // change. A NaN row scores `NaN`, and `nearest`'s comparator
275
+ // (`b.score - a.score || id`) reads `NaN - x` as falsy and falls through to
276
+ // the id tiebreak, so one such row sorts anywhere at all, first included.
277
+ // `countNonFinite` is how a caller reports what it coerced.
278
+ for (let i = 0; i < vec.length; i++) {
279
+ const x = vec[i];
280
+ f[i] = typeof x === "number" && Number.isFinite(x) ? x : 0;
281
+ }
282
+ return new Uint8Array(f.buffer, f.byteOffset, f.byteLength);
283
+ }
284
+
285
+ /** How many of `vec`'s entries `encodeVector` would coerce to zero. */
286
+ export function countNonFinite(vec: readonly number[]): number {
287
+ let n = 0;
288
+ for (const x of vec) if (!(typeof x === "number" && Number.isFinite(x))) n += 1;
289
+ return n;
290
+ }
291
+
292
+ /**
293
+ * Read a stored vector back in whatever shape the row holds — float32 BLOB
294
+ * (v4) or JSON text (v3 and earlier).
295
+ *
296
+ * Tolerating both is deliberate and is what makes the migration safe rather
297
+ * than a flag day: a cache mid-`migrate-cache` (or one written by a v4 process
298
+ * and last converted by nothing) is MIXED, and a reader that assumed one shape
299
+ * would turn an unconverted row into either a crash or a silent zero-similarity
300
+ * lie. The cost is one `typeof` per row.
301
+ *
302
+ * The BLOB arm returns a `Float32Array` VIEW where it can — no per-row copy of
303
+ * 1,024 numbers, which is most of what the old scan spent. A driver that hands
304
+ * back a pooled buffer at an unaligned `byteOffset` (node:sqlite's `Buffer`s do
305
+ * this; bun:sqlite's always start at 0) forces one copy, which is what the
306
+ * second arm is.
307
+ *
308
+ * A byte length that is not a multiple of four is **not** a short vector, it is
309
+ * a CORRUPT ROW, and it comes back empty rather than truncated: truncating
310
+ * would hand the scan a silently shortened vector and a cosine computed over a
311
+ * prefix, which is a wrong number with no signal on it. Empty scores 0 through
312
+ * `cosine`'s zero-norm arm, `nearestVectors` skips it, and `vectorFormats`
313
+ * counts the row in `other` so a census names it instead of a scan hiding it.
314
+ */
315
+ export function decodeVector(raw: SqlValue): Float32Array | number[] {
316
+ if (typeof raw === "string") return JSON.parse(raw) as number[];
317
+ if (raw instanceof Uint8Array) {
318
+ if (raw.byteLength % 4 !== 0) return [];
319
+ const n = raw.byteLength >>> 2;
320
+ if (n === 0) return [];
321
+ if (raw.byteOffset % 4 === 0) return new Float32Array(raw.buffer, raw.byteOffset, n);
322
+ const copy = new Uint8Array(raw); // fresh buffer, byteOffset 0
323
+ return new Float32Array(copy.buffer, 0, n);
324
+ }
325
+ return [];
326
+ }
327
+
328
+ /** How many vectors box 3 holds, in each of the two shapes. Cheap: a grouped count. */
329
+ export interface VectorFormatCensus {
330
+ readonly total: number;
331
+ /** v4 rows: `dim` little-endian float32s. */
332
+ readonly float32: number;
333
+ /** v3 rows: `JSON.stringify(vec)`. What `migrate-cache` converts. */
334
+ readonly jsonText: number;
335
+ /**
336
+ * Unreadable: neither shape, or a BLOB whose byte length is not a multiple
337
+ * of four (`decodeVector` returns empty for those rather than a truncated
338
+ * vector). Named rather than folded into a total.
339
+ */
340
+ readonly other: number;
341
+ /** `SUM(LENGTH(vec))` over each shape, in bytes. */
342
+ readonly float32Bytes: number;
343
+ readonly jsonTextBytes: number;
344
+ }
345
+
346
+ export function vectorFormats(db: Db): VectorFormatCensus {
347
+ // The GROUP BY key is the shape as a READER sees it, not `typeof` alone: a
348
+ // blob of 4,097 bytes has `typeof = 'blob'` and is still not a vector, and a
349
+ // census that counted it as one would report a store as fully converted while
350
+ // `decodeVector` was returning empty for it.
351
+ const rows = db.all<{ t: string; n: number; b: number | null }>(
352
+ `SELECT CASE
353
+ WHEN typeof(vec) = 'blob' AND LENGTH(vec) % 4 = 0 THEN 'blob'
354
+ WHEN typeof(vec) = 'text' THEN 'text'
355
+ ELSE 'other'
356
+ END AS t,
357
+ COUNT(*) AS n, SUM(LENGTH(vec)) AS b
358
+ FROM embeddings GROUP BY t`,
359
+ );
360
+ let float32 = 0;
361
+ let jsonText = 0;
362
+ let other = 0;
363
+ let float32Bytes = 0;
364
+ let jsonTextBytes = 0;
365
+ for (const r of rows) {
366
+ const bytes = r.b ?? 0;
367
+ if (r.t === "blob") {
368
+ float32 += r.n;
369
+ float32Bytes += bytes;
370
+ } else if (r.t === "text") {
371
+ jsonText += r.n;
372
+ jsonTextBytes += bytes;
373
+ } else other += r.n;
374
+ }
375
+ return { total: float32 + jsonText + other, float32, jsonText, other, float32Bytes, jsonTextBytes };
376
+ }
377
+
378
+ export interface ConvertBatchReport {
379
+ /** Rows examined this batch. Zero means the walk is finished. */
380
+ readonly examined: number;
381
+ /** Rows rewritten as float32 BLOBs. */
382
+ readonly converted: number;
383
+ /** Rows whose `vec` would not parse — left exactly as they are, and named. */
384
+ readonly skipped: readonly string[];
385
+ /** Coordinates coerced to zero because they were NaN or infinite. */
386
+ readonly coerced: number;
387
+ /** The last `memory_id` examined, to continue the walk past a skipped row. */
388
+ readonly lastId: string | null;
389
+ }
390
+
391
+ /**
392
+ * Convert up to `batch` JSON-text vectors to float32 BLOBs, in ONE transaction,
393
+ * and report what happened. `examined === 0` means the walk is finished.
394
+ *
395
+ * **Batched, not one statement**, because this runs on a 177 MB file the
396
+ * Stop-hook worker also writes to: a single transaction over 13.9K rows holds
397
+ * box 3's write lock for the whole rewrite, and `BUSY_TIMEOUT_MS` is five
398
+ * seconds. Idempotent by its WHERE clause — a converted row is not selected —
399
+ * so an interrupted run resumes by being run again, and a finished one is a
400
+ * no-op.
401
+ *
402
+ * **`after` is what makes one bad row survivable.** The first version parsed
403
+ * inside the transaction and let a throw roll the batch back; because the
404
+ * selection is `ORDER BY memory_id LIMIT ?`, the very next attempt selected the
405
+ * same unparseable row and threw again, and every row after it stayed in the
406
+ * old shape forever — one corrupt byte holding 13,000 vectors hostage. Now a
407
+ * row that will not parse is SKIPPED, NAMED, and left untouched (nothing here
408
+ * repairs data it cannot read), and the caller walks past it with
409
+ * `after = lastId`.
410
+ */
411
+ export function convertVectorBatch(db: Db, batch = 500, after?: string): ConvertBatchReport {
412
+ const rows =
413
+ after === undefined
414
+ ? db.all<{ memory_id: string; vec: SqlValue }>(
415
+ "SELECT memory_id, vec FROM embeddings WHERE typeof(vec) = 'text' ORDER BY memory_id LIMIT ?",
416
+ batch,
417
+ )
418
+ : db.all<{ memory_id: string; vec: SqlValue }>(
419
+ "SELECT memory_id, vec FROM embeddings WHERE typeof(vec) = 'text' AND memory_id > ? ORDER BY memory_id LIMIT ?",
420
+ after,
421
+ batch,
422
+ );
423
+ const lastId = rows.length === 0 ? null : (rows[rows.length - 1]?.memory_id ?? null);
424
+ if (rows.length === 0) return { examined: 0, converted: 0, skipped: [], coerced: 0, lastId };
425
+ // Parse OUTSIDE the transaction: a throw here must cost one row, not a batch.
426
+ const decoded: { id: string; arr: number[] }[] = [];
427
+ const skipped: string[] = [];
428
+ let coerced = 0;
429
+ for (const row of rows) {
430
+ try {
431
+ const arr = Array.from(decodeVector(row.vec));
432
+ coerced += countNonFinite(arr);
433
+ decoded.push({ id: row.memory_id, arr });
434
+ } catch {
435
+ skipped.push(row.memory_id);
436
+ }
437
+ }
438
+ const converted = db.transaction(() => {
439
+ const upd = db.prepare("UPDATE embeddings SET dim = ?, vec = ? WHERE memory_id = ?");
440
+ let n = 0;
441
+ for (const d of decoded) {
442
+ upd.run(d.arr.length, encodeVector(d.arr), d.id);
443
+ n += 1;
444
+ }
445
+ return n;
446
+ });
447
+ return { examined: rows.length, converted, skipped, coerced, lastId };
448
+ }
449
+
450
+ export function tokenize(text: string): string[] {
451
+ return text
452
+ .toLowerCase()
453
+ .split(/[^a-z0-9]+/)
454
+ .filter((t) => t.length >= 2);
455
+ }
456
+
457
+ /** (Re)index one document. Idempotent: the doc's prior rows are replaced wholesale. */
458
+ export function indexDoc(db: Db, id: string, text: string, vec?: readonly number[]): void {
459
+ const counts = new Map<string, number>();
460
+ let len = 0;
461
+ for (const tok of tokenize(text)) {
462
+ counts.set(tok, (counts.get(tok) ?? 0) + 1);
463
+ len += 1;
464
+ }
465
+ forgetAvgDocLen(db);
466
+ db.transaction(() => {
467
+ db.run("DELETE FROM doc_tokens WHERE memory_id = ?", id);
468
+ const ins = db.prepare("INSERT INTO doc_tokens (memory_id, token, tf) VALUES (?, ?, ?)");
469
+ for (const [token, tf] of counts) ins.run(id, token, tf);
470
+ // A document with no indexable tokens has no length either: it leaves the
471
+ // table rather than dragging a zero through `AVG(len)`.
472
+ if (len > 0) db.run("INSERT OR REPLACE INTO doc_lens (memory_id, len) VALUES (?, ?)", id, len);
473
+ else db.run("DELETE FROM doc_lens WHERE memory_id = ?", id);
474
+ if (vec !== undefined) {
475
+ db.run(
476
+ "INSERT OR REPLACE INTO embeddings (memory_id, dim, vec) VALUES (?, ?, ?)",
477
+ id,
478
+ vec.length,
479
+ encodeVector(vec),
480
+ );
481
+ }
482
+ });
483
+ }
484
+
485
+ /**
486
+ * Write ONE document's vector, and touch nothing else.
487
+ *
488
+ * Split out of `indexDoc` because the backfill needs exactly this and `indexDoc`
489
+ * does far more: it `DELETE`s and re-inserts every token row for the document.
490
+ * For a memory whose text has not changed, that is pure churn on `doc_tokens` —
491
+ * and `doc_tokens` is the 263 MB index whose page-cache warming measured 794-819
492
+ * ms on the first recall of every fresh hook process, which is the whole reason
493
+ * `BUDGET_MS` went from 250 to 1200. Sixty-four token-index rewrites per Stop
494
+ * would have fought the constraint that motivated the lag in the first place.
495
+ */
496
+ export function setEmbedding(db: Db, id: string, vec: readonly number[]): void {
497
+ db.run(
498
+ "INSERT OR REPLACE INTO embeddings (memory_id, dim, vec) VALUES (?, ?, ?)",
499
+ id,
500
+ vec.length,
501
+ encodeVector(vec),
502
+ );
503
+ }
504
+
505
+ /**
506
+ * Take one document OUT of the text index — the other half of `indexDoc`.
507
+ *
508
+ * **The rule this makes structural: the index is the index OF THE LIVE STORE.**
509
+ * `doc_tokens` is what `docFrequency` counts and what `searchIndex` selects
510
+ * from, and both of those numbers are read against a LIVE denominator:
511
+ * `recall/`'s `storeSize` is `store.list({ archived: false }).length`, and
512
+ * `activate.ts` throws away any hit whose row is archived or superseded. While
513
+ * a dead row kept its token rows, the two counts came from two different
514
+ * populations — so `df > storeSize` was reachable, and
515
+ * `informativeness(df, storeSize)` returns exactly zero at `df >= storeSize`.
516
+ * MEASURED 2026-09-04: a fresh store, one note, one revision — `revision.ts`
517
+ * calls `Store.supersede`, the head is archived and stays indexed,
518
+ * `df(sourdough) = 2` against `storeSize = 1`, every cue is dropped, and the
519
+ * MCP `recall` door answers `nothing-came` on a store whose only memory plainly
520
+ * matches the question. That is NOTES §12's N=1 re-zeroing, restored by an
521
+ * ordinary revision (LAUNCH-STATUS I13).
522
+ *
523
+ * It also stops a dead row from spending a slot ON THE LEXICAL CHANNEL:
524
+ * `searchIndex` takes the top `limit` per cue, and a row `activate` will
525
+ * discard was still winning one of them. Narrowing the candidate SET is the
526
+ * same failure length normalization was moved into the SQL to avoid.
527
+ *
528
+ * **`embeddings` is left alone, and the semantic half of that same slot problem
529
+ * is therefore still OPEN.** A vector cost a paid network call, so deleting it
530
+ * here would spend money — but the first draft of this docblock justified that
531
+ * with "nothing reads a dead row's vector", and an adversarial review measured
532
+ * the opposite: `nearest` (below) scans `embeddings` with no filter, and
533
+ * `activate.ts`'s semantic channel takes that ranking as `SEMANTIC_TOP_M`
534
+ * candidates before discarding the dead one. After a `supersede`, `nearestTo`
535
+ * returned the dead row FIRST of three. So what is true is narrower: nothing
536
+ * can be DELIVERED from a dead row, and its vector can still displace a live
537
+ * neighbour from the semantic slate. Named as a follow-up in
538
+ * `recall/NOTES.md` §13 (filter inside `Store.nearestTo` — over-fetch and drop
539
+ * the non-live against box 2, the shape the lexical half just got) rather than
540
+ * widened into this change. `rebuildCache` does not carry a dead row's vector
541
+ * forward — a rebuild reproduces the LIVE index — and that asymmetry is named
542
+ * there too.
543
+ *
544
+ * **Two things this does NOT reach, deliberately.** The `ranking` table keeps
545
+ * the row: it is keyed by id and read per-id by callers that already iterate
546
+ * live rows, so it is inert rather than wrong. And the rule is kept by the two
547
+ * WRITERS of `archived = 1` that live in this module — `Store.archive` and
548
+ * `Store.supersede`; the third, `owner-op-seam.ts`'s removal scrub, is reached
549
+ * only by its caller's convention (the console's destruction path always
550
+ * follows it with `rebuildCache`, which drops the row as `skippedDenied`). If
551
+ * that rebuild ever failed, `counterparts verify`'s "indexed but not live" line
552
+ * now names the leftover instead of hiding it.
553
+ */
554
+ export function deindexDoc(db: Db, id: string): void {
555
+ forgetAvgDocLen(db);
556
+ db.transaction(() => {
557
+ db.run("DELETE FROM doc_tokens WHERE memory_id = ?", id);
558
+ db.run("DELETE FROM doc_lens WHERE memory_id = ?", id);
559
+ });
560
+ }
561
+
562
+ /** How many vectors box 3 holds. The count `unembeddedCount()` is NOT. */
563
+ export function embeddingCount(db: Db): number {
564
+ return db.get<{ n: number }>("SELECT COUNT(*) AS n FROM embeddings")?.n ?? 0;
565
+ }
566
+
567
+ export interface Hit {
568
+ id: string;
569
+ score: number;
570
+ }
571
+
572
+ /**
573
+ * Deterministic: score desc, then id asc — so "same cue, same order" is testable.
574
+ *
575
+ * The normalization is applied **inside the SQL, before `ORDER BY … LIMIT`**,
576
+ * and that placement is the fix rather than a detail of it. Normalizing the
577
+ * score afterwards in the caller would have left the CANDIDATE SET chosen by
578
+ * raw `SUM(tf)`: the longest documents would still occupy all `limit` slots for
579
+ * every cue, and the caller would only have re-ranked a set that was already
580
+ * wrong.
581
+ *
582
+ * `LEFT JOIN` + `COALESCE`: a row whose length is not (yet) known is treated as
583
+ * average rather than dropped. Box 3 is rebuildable and partially-built states
584
+ * are ordinary; a missing length must cost precision, never a hit.
585
+ *
586
+ * `CAST(… AS REAL)` on every operand: SQLite divides integers as integers, and
587
+ * both drivers bind an integer-valued JS number as INTEGER. At `b = 1` with an
588
+ * integer mean length, `1 * len / avg` would truncate — silently, and only for
589
+ * some values of the tunables, which is the worst way for arithmetic to be wrong.
590
+ */
591
+ export function searchIndex(db: Db, cue: string, limit = 10, norm: LengthNorm = DEFAULT_LENGTH_NORM): Hit[] {
592
+ const tokens = [...new Set(tokenize(cue))];
593
+ if (tokens.length === 0) return [];
594
+ const placeholders = tokens.map(() => "?").join(",");
595
+ const avg = avgDocLen(db);
596
+ const lengthFactor =
597
+ `CAST(? AS REAL) + CAST(? AS REAL) * COALESCE(dl.len, CAST(? AS REAL)) / CAST(? AS REAL)`;
598
+ const clamped = norm.oneSided === true ? `MAX(1.0, ${lengthFactor})` : lengthFactor;
599
+ const rows = db.all<{ memory_id: string; score: number }>(
600
+ `SELECT dt.memory_id AS memory_id,
601
+ SUM(CAST(dt.tf AS REAL) * CAST(? AS REAL)
602
+ / (dt.tf + CAST(? AS REAL) * (${clamped}))) AS score
603
+ FROM doc_tokens dt
604
+ LEFT JOIN doc_lens dl ON dl.memory_id = dt.memory_id
605
+ WHERE dt.token IN (${placeholders})
606
+ GROUP BY dt.memory_id
607
+ ORDER BY score DESC, dt.memory_id ASC
608
+ LIMIT ?`,
609
+ norm.k1 + 1,
610
+ norm.k1,
611
+ 1 - norm.b,
612
+ norm.b,
613
+ avg,
614
+ avg,
615
+ ...tokens,
616
+ limit,
617
+ );
618
+ return rows.map((r) => ({ id: r.memory_id, score: r.score }));
619
+ }
620
+
621
+ /**
622
+ * Document frequency — in how many indexed documents does each token appear?
623
+ *
624
+ * This exists because the caller that needs df was counting the wrong thing.
625
+ * `recall/activate.ts` took `df = searchIndex(tok, PER_CUE_FETCH).length`, which
626
+ * is `min(trueDf, PER_CUE_FETCH)` — so on a store with more than
627
+ * `PER_CUE_FETCH` documents holding a token, EVERY common word measured as
628
+ * "appears in 24 documents" and drew a rarity weight near the maximum.
629
+ * MEASURED 2026-09-04 on a 15,421-document index: `the` and `conversation`
630
+ * scored `informativeness = 5.7` against a ceiling of 8.95, where their true
631
+ * frequencies (df 350–10k) put them at 0–3. On a seventeen-memory fixture the
632
+ * truncation cannot happen at all, so the bug was invisible to every hermetic
633
+ * test and grew with the store.
634
+ *
635
+ * `doc_tokens` is keyed `(memory_id, token)`, so `COUNT(*)` per token IS the
636
+ * document count — no `DISTINCT` needed, and the `doc_tokens_token` index
637
+ * covers it. One grouped query for the whole turn: measured 8–36 ms cold and
638
+ * 2–4 ms warm for 72 tokens on that same index.
639
+ */
640
+ export function docFrequency(db: Db, tokens: readonly string[]): Map<string, number> {
641
+ const out = new Map<string, number>();
642
+ const unique = [...new Set(tokens)];
643
+ if (unique.length === 0) return out;
644
+ // Bound the statement's variable count; SQLite's default limit is 999.
645
+ const CHUNK = 400;
646
+ for (let i = 0; i < unique.length; i += CHUNK) {
647
+ const slice = unique.slice(i, i + CHUNK);
648
+ const placeholders = slice.map(() => "?").join(",");
649
+ const rows = db.all<{ token: string; n: number }>(
650
+ `SELECT token, COUNT(*) AS n FROM doc_tokens WHERE token IN (${placeholders}) GROUP BY token`,
651
+ ...slice,
652
+ );
653
+ for (const r of rows) out.set(r.token, r.n);
654
+ }
655
+ return out;
656
+ }
657
+
658
+ export function nearest(db: Db, vec: readonly number[], limit = 10): Hit[] {
659
+ const rows = db.all<{ memory_id: string; vec: SqlValue }>("SELECT memory_id, vec FROM embeddings");
660
+ const hits: Hit[] = [];
661
+ for (const row of rows) {
662
+ const other = decodeVector(row.vec);
663
+ hits.push({ id: row.memory_id, score: cosine(vec, other) });
664
+ }
665
+ hits.sort((a, b) => b.score - a.score || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
666
+ return hits.slice(0, limit);
667
+ }
668
+
669
+ /**
670
+ * The same ranking as `nearest`, returning the VECTORS rather than the ids —
671
+ * the context slice a novelty measurement is error against. One scan, one
672
+ * ordering, no second definition of "nearest" to drift from the first.
673
+ */
674
+ export function nearestVectors(db: Db, vec: readonly number[], limit = 10): number[][] {
675
+ const rows = db.all<{ memory_id: string; vec: SqlValue }>("SELECT memory_id, vec FROM embeddings");
676
+ const scored: { id: string; score: number; vec: Float32Array | number[] }[] = [];
677
+ for (const row of rows) {
678
+ const other = decodeVector(row.vec);
679
+ if (other.length === 0) continue;
680
+ scored.push({ id: row.memory_id, score: cosine(vec, other), vec: other });
681
+ }
682
+ scored.sort((a, b) => b.score - a.score || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
683
+ // `Array.from` only on the `limit` survivors: the caller's contract is
684
+ // `number[][]`, and materializing the whole scan to satisfy it would give
685
+ // back exactly the per-row allocation the BLOB read exists to avoid.
686
+ return scored.slice(0, limit).map((s) => (Array.isArray(s.vec) ? s.vec : Array.from(s.vec)));
687
+ }
688
+
689
+ /**
690
+ * `ArrayLike<number>` rather than `readonly number[]`: since v4 the stored side
691
+ * arrives as a `Float32Array` view over the row's bytes, and widening the
692
+ * parameter is what lets the scan score it WITHOUT copying it into an array
693
+ * first. The arithmetic is unchanged and still accumulates in float64.
694
+ */
695
+ export function cosine(a: ArrayLike<number>, b: ArrayLike<number>): number {
696
+ const n = Math.min(a.length, b.length);
697
+ let dot = 0;
698
+ let na = 0;
699
+ let nb = 0;
700
+ for (let i = 0; i < n; i++) {
701
+ const x = a[i] ?? 0;
702
+ const y = b[i] ?? 0;
703
+ dot += x * y;
704
+ na += x * x;
705
+ nb += y * y;
706
+ }
707
+ if (na === 0 || nb === 0) return 0;
708
+ return dot / (Math.sqrt(na) * Math.sqrt(nb));
709
+ }