counterparts 0.2.0 → 0.3.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.
- package/README.md +87 -367
- package/docs/QUICKSTART.md +83 -1584
- package/docs/README.md +86 -0
- package/docs/module-map.md +1 -0
- package/package.json +5 -2
- package/src/adapters/claude-code/CONTRACT.md +151 -18
- package/src/adapters/claude-code/INTERFACE-GAPS.md +138 -2
- package/src/adapters/claude-code/NOTES.md +452 -0
- package/src/adapters/claude-code/bin/hook.ts +221 -49
- package/src/adapters/claude-code/bin/runner.ts +220 -101
- package/src/adapters/claude-code/config.ts +202 -279
- package/src/adapters/claude-code/doctor.ts +713 -421
- package/src/adapters/claude-code/embed-client.ts +165 -557
- package/src/adapters/claude-code/hooks.ts +409 -116
- package/src/adapters/claude-code/index.ts +7 -59
- package/src/adapters/claude-code/page-writer.ts +24 -4
- package/src/adapters/claude-code/spawn.ts +6 -7
- package/src/adapters/claude-code/transcript.ts +204 -10
- package/src/adapters/claude-code/vectors.ts +108 -24
- package/src/adapters/cli/CONTRACT.md +123 -3
- package/src/adapters/cli/INTERFACE-GAPS.md +45 -2
- package/src/adapters/cli/NOTES.md +265 -1
- package/src/adapters/cli/bin/counterparts.ts +9 -9
- package/src/adapters/cli/commands.ts +494 -436
- package/src/adapters/cli/help.ts +22 -27
- package/src/adapters/cli/index.ts +0 -2
- package/src/adapters/cli/install.ts +102 -89
- package/src/adapters/cli/removal.ts +1 -1
- package/src/adapters/cli/report.ts +25 -2
- package/src/adapters/cli/uninstall.ts +182 -34
- package/src/adapters/cli/wire.ts +232 -35
- package/src/adapters/dashboard/INTERFACE-GAPS.md +14 -2
- package/src/adapters/dashboard/activity.ts +4 -1
- package/src/adapters/dashboard/bin/dashboard.ts +1 -1
- package/src/adapters/dashboard/registries.ts +16 -1
- package/src/adapters/dashboard/resolve.ts +4 -4
- package/src/adapters/dashboard/source.ts +8 -2
- package/src/adapters/dashboard/web/flow.ts +6 -0
- package/src/adapters/dashboard/web/narrate.ts +66 -14
- package/src/adapters/dashboard/web/reveal.ts +6 -6
- package/src/adapters/dashboard/web/views.ts +12 -4
- package/src/adapters/fired.ts +20 -5
- package/src/adapters/mcp/CONTRACT.md +73 -1
- package/src/adapters/mcp/INTERFACE-GAPS.md +51 -1
- package/src/adapters/mcp/NOTES.md +389 -0
- package/src/adapters/mcp/bin/serve.ts +24 -35
- package/src/adapters/mcp/deliberate.ts +22 -0
- package/src/adapters/mcp/index.ts +26 -2
- package/src/adapters/mcp/server.ts +425 -49
- package/src/adapters/mcp/tools.ts +32 -7
- package/src/adapters/mcp/write-up.ts +454 -0
- package/src/adapters/sessions.ts +1353 -0
- package/src/core/counterpart.ts +32 -8
- package/src/core/embed/CONTRACT.md +85 -0
- package/src/core/embed/NOTES.md +93 -0
- package/src/core/embed/static.ts +622 -0
- package/src/core/encode/INTERFACE-GAPS.md +17 -0
- package/src/core/encode/NOTES.md +78 -0
- package/src/core/encode/secrets.ts +309 -9
- package/src/core/handoff/INTERFACE-GAPS.md +13 -1
- package/src/core/recall/CONTRACT.md +15 -3
- package/src/core/recall/INTERFACE-GAPS.md +94 -0
- package/src/core/recall/NOTES.md +49 -0
- package/src/core/recall/activate.ts +37 -3
- package/src/core/recall/index.ts +22 -1
- package/src/core/recall/session.ts +32 -0
- package/src/core/recall/tunables.ts +99 -2
- package/src/core/remember/CONTRACT.md +51 -7
- package/src/core/remember/INTERFACE-GAPS.md +111 -1
- package/src/core/remember/NOTES.md +221 -1
- package/src/core/remember/index.ts +28 -0
- package/src/core/remember/owes.ts +532 -0
- package/src/core/remember/owner-strike-seam.ts +34 -2
- package/src/core/remember/proposals.ts +25 -6
- package/src/core/remember/retention.ts +154 -0
- package/src/core/remember/spans.ts +53 -12
- package/src/core/remember/tunables.ts +8 -0
- package/src/core/remember/write-up-seam.ts +104 -0
- package/src/core/self/CONTRACT.md +16 -13
- package/src/core/self/INTERFACE-GAPS.md +8 -1
- package/src/core/self/NOTES.md +123 -1
- package/src/core/self/calendar.ts +81 -0
- package/src/core/self/episodes.ts +158 -36
- package/src/core/self/identity.ts +2 -2
- package/src/core/self/index.ts +88 -20
- package/src/core/self/tunables.ts +18 -46
- package/src/core/self/writer.ts +58 -9
- package/src/core/store/CONTRACT.md +16 -1
- package/src/core/store/NOTES.md +293 -0
- package/src/core/store/cache.ts +585 -27
- package/src/core/store/db.ts +97 -0
- package/src/core/store/index.ts +570 -13
- package/tools/install-loop/run.sh +52 -71
- package/src/adapters/claude-code/credentials.ts +0 -199
- package/src/adapters/claude-code/interpret-client.ts +0 -395
- package/src/adapters/cli/keys.ts +0 -503
package/src/core/store/cache.ts
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import type { Db, SqlValue } from "./db.js";
|
|
11
11
|
import { openDb } from "./db.js";
|
|
12
|
+
import { StoreError } from "./errors.js";
|
|
12
13
|
|
|
13
14
|
/**
|
|
14
15
|
* Bumped to 2 (2026-08-25, SEAMS item J): the `ranking` table joins box 3.
|
|
@@ -18,8 +19,16 @@ import { openDb } from "./db.js";
|
|
|
18
19
|
* than JSON text (see `encodeVector`). The bump changes what a WRITE produces;
|
|
19
20
|
* reads stay tolerant of both shapes, and `counterparts migrate-cache`
|
|
20
21
|
* converts the rows already on disk.
|
|
22
|
+
* Bumped to 5 (2026-09-23, roadmap C1): `cache_meta.embedder` — the IDENTITY of
|
|
23
|
+
* the vectors in `embeddings` (`<model>@<dim>`, see `reconcileEmbedder`). The
|
|
24
|
+
* table's shape does not change; what changes is that a v5 cache's vectors
|
|
25
|
+
* carry a claim about which model wrote them, and a v4 cache's do not. The
|
|
26
|
+
* migration therefore ERASES any tag it finds (a v5 tag that has since passed
|
|
27
|
+
* through a v4 build's writes is not evidence of anything) and leaves the rows
|
|
28
|
+
* where they are; the first open with an embedder configured decides what they
|
|
29
|
+
* are (`reconcileEmbedder`'s legacy arm).
|
|
21
30
|
*/
|
|
22
|
-
export const CACHE_SCHEMA_VERSION =
|
|
31
|
+
export const CACHE_SCHEMA_VERSION = 5;
|
|
23
32
|
|
|
24
33
|
const DDL: readonly string[] = [
|
|
25
34
|
`CREATE TABLE IF NOT EXISTS doc_tokens (
|
|
@@ -186,25 +195,64 @@ export function backfillLengths(db: Db): number {
|
|
|
186
195
|
return db.get<{ n: number }>("SELECT COUNT(*) AS n FROM doc_lens")?.n ?? 0;
|
|
187
196
|
}
|
|
188
197
|
|
|
198
|
+
/**
|
|
199
|
+
* The schema version box 3 says it is, or null for a fresh file (no table, no
|
|
200
|
+
* row). A read; nothing is created. E's every-call check reads the same key.
|
|
201
|
+
*/
|
|
202
|
+
export function cacheSchemaVersion(db: Db): string | null {
|
|
203
|
+
try {
|
|
204
|
+
return db.get<{ value: string }>("SELECT value FROM cache_meta WHERE key = 'schemaVersion'")?.value ?? null;
|
|
205
|
+
} catch {
|
|
206
|
+
return null; // table absent: fresh cache
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* THE ONE DEFINITION OF "AHEAD", for both boxes and every reader (roadmap E's
|
|
212
|
+
* server gate included): a stamp is ahead of the code only when it is a plain
|
|
213
|
+
* base-10 integer greater than the code's version. Absent, behind, or anything
|
|
214
|
+
* that is not digits (`"6-beta"`, `"7a"`, `""`) reads as NOT ahead — today's
|
|
215
|
+
* behaviour, in which an older or odd stamp is the migrating open's to fix.
|
|
216
|
+
* `parseInt` would have read `"6-beta"` as 6; this does not.
|
|
217
|
+
*/
|
|
218
|
+
export function schemaAhead(found: string | null, code: number): boolean {
|
|
219
|
+
if (found === null || !/^[0-9]+$/.test(found)) return false;
|
|
220
|
+
return Number.parseInt(found, 10) > code;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Is this cache from a NEWER build? Then this build must not stamp it, migrate
|
|
225
|
+
* it, drop from it or write vectors into it — only read what it can.
|
|
226
|
+
*/
|
|
227
|
+
export function cacheAhead(db: Db): { found: string; expected: number } | null {
|
|
228
|
+
const found = cacheSchemaVersion(db);
|
|
229
|
+
return found !== null && schemaAhead(found, CACHE_SCHEMA_VERSION)
|
|
230
|
+
? { found, expected: CACHE_SCHEMA_VERSION }
|
|
231
|
+
: null;
|
|
232
|
+
}
|
|
233
|
+
|
|
189
234
|
export function openCache(path: string): Db {
|
|
190
235
|
// WAL here whatever the stance, unlike box 2: the dashboard and the worker read
|
|
191
236
|
// and write this file at the same time, its sidecars live inside `cache/` where
|
|
192
237
|
// nothing classifies them, and box 3 is DECLARED rebuildable — the same reason
|
|
193
238
|
// the constructor lets an instrument materialize this directory at all.
|
|
194
239
|
const db = openDb(path, { wal: true });
|
|
240
|
+
// A CACHE FROM A NEWER BUILD IS LEFT EXACTLY AS IT IS (2026-09-23, found by
|
|
241
|
+
// roadmap E). Before v5 this function stamped whatever version it found back
|
|
242
|
+
// DOWN to its own — so an old MCP server opened after an upgrade rewrote the
|
|
243
|
+
// new build's `schemaVersion`, and the every-call "schema ahead" refusal that
|
|
244
|
+
// exists to stop that server could never see what it was looking for. The
|
|
245
|
+
// handle is returned unmigrated; the `Store` built on it turns the vector
|
|
246
|
+
// channel off by name (`EmbedderVerdict` "cache-ahead") and refuses a
|
|
247
|
+
// rebuild. (The MCP server refuses every tool in this state — #187 — and
|
|
248
|
+
// that policy wins for the server; see store NOTES, 2026-09-23.)
|
|
249
|
+
if (cacheAhead(db) !== null) return db;
|
|
195
250
|
// Idempotent open: write the version row only when it differs. An observer
|
|
196
251
|
// constructing a Store over an up-to-date cache must not churn a byte — the
|
|
197
252
|
// dashboard build measured exactly that churn and filed it (its gap §1).
|
|
198
253
|
// A fresh or outdated cache still initializes (box 3 is rebuildable, and an
|
|
199
254
|
// 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
|
-
})();
|
|
255
|
+
const existing = cacheSchemaVersion(db);
|
|
208
256
|
if (existing !== String(CACHE_SCHEMA_VERSION)) {
|
|
209
257
|
db.transaction(() => {
|
|
210
258
|
for (const sql of DDL) db.exec(sql);
|
|
@@ -212,12 +260,470 @@ export function openCache(path: string): Db {
|
|
|
212
260
|
// a cache stamped v3 with no lengths would score every document as if it
|
|
213
261
|
// were average, silently, which is the failure this version exists to end.
|
|
214
262
|
backfillLengths(db);
|
|
263
|
+
// v5: a tag found on a cache stamped BELOW 5 means a v5 build tagged it
|
|
264
|
+
// and an OLDER build then stamped the version down (any 0.2.0 process,
|
|
265
|
+
// an unrestarted MCP server, a dev checkout) and may have written vectors
|
|
266
|
+
// of its own beside the tagged ones. Before v5 the only thing that ever
|
|
267
|
+
// wrote a vector was the paid seat, so what an older build can add is
|
|
268
|
+
// paid-width rows. The tag is KEPT when every row still has the width it
|
|
269
|
+
// names — nothing foreign was written — and erased otherwise, leaving the
|
|
270
|
+
// rows untagged for the first identified open to judge
|
|
271
|
+
// (`reconcileEmbedder`'s legacy arm: a static table refills rows of its
|
|
272
|
+
// own width and holds anything else; a paid seat adopts only its own
|
|
273
|
+
// known width). The held marker survives either way: a hold is the
|
|
274
|
+
// owner's to release, never a migration's.
|
|
275
|
+
if (existing !== null && Number(existing) < 5) {
|
|
276
|
+
const tag = db.get<{ value: string }>("SELECT value FROM cache_meta WHERE key = ?", EMBEDDER_META_KEY)?.value;
|
|
277
|
+
const dim = tag === undefined ? null : parseIdentityTag(tag).dim;
|
|
278
|
+
const foreign =
|
|
279
|
+
dim === null
|
|
280
|
+
? 1
|
|
281
|
+
: (db.get<{ n: number }>("SELECT COUNT(*) AS n FROM embeddings WHERE dim != ?", dim)?.n ?? 0);
|
|
282
|
+
if (tag !== undefined && foreign > 0) {
|
|
283
|
+
db.run("DELETE FROM cache_meta WHERE key IN (?, ?)", EMBEDDER_META_KEY, EMBEDDER_REBUILD_META_KEY);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
215
286
|
db.run("INSERT OR REPLACE INTO cache_meta (key, value) VALUES ('schemaVersion', ?)", String(CACHE_SCHEMA_VERSION));
|
|
216
287
|
});
|
|
217
288
|
}
|
|
218
289
|
return db;
|
|
219
290
|
}
|
|
220
291
|
|
|
292
|
+
// ── the embedder identity tag (v5) ──────────────────────────────────────────
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* `cache_meta` key holding the identity of every vector in `embeddings`:
|
|
296
|
+
* `<model>@<dim>`, e.g. `potion-base-8M@256` (or `voyage-3-large@1024`, from
|
|
297
|
+
* the paid seat the adapter had until 2026-09-24).
|
|
298
|
+
*
|
|
299
|
+
* WHY IT EXISTS: `embed-client.ts` §2.15 — "a vector's generation is part of
|
|
300
|
+
* its identity; vectors from two models are not comparable." Through v4 that
|
|
301
|
+
* was enforced by nothing: the seat id was pinned in config, and a changed
|
|
302
|
+
* config would have ranked a new model's query against an old model's rows
|
|
303
|
+
* with no sign anything was wrong. Two embedders exist now (a paid remote seat
|
|
304
|
+
* and a free local table), and switching between them is an ordinary act — so
|
|
305
|
+
* the rows have to say what they are.
|
|
306
|
+
*/
|
|
307
|
+
export const EMBEDDER_META_KEY = "embedder";
|
|
308
|
+
/**
|
|
309
|
+
* Companion key: how the tagged vectors come BACK after a drop — `inline` (the
|
|
310
|
+
* embedder computes them in-process, for nothing) or `external` (only a paid or
|
|
311
|
+
* asynchronous path can). It is what lets a mismatch drop free rows at open and
|
|
312
|
+
* refuse to drop paid ones.
|
|
313
|
+
*/
|
|
314
|
+
export const EMBEDDER_REBUILD_META_KEY = "embedderRebuild";
|
|
315
|
+
/**
|
|
316
|
+
* THE DURABLE HOLD (review of #190, MAJOR 1). Present ⇔ box 3 holds PAID
|
|
317
|
+
* vectors that the configured embedder cannot use, and nobody has confirmed
|
|
318
|
+
* dropping them. Its value is the identity that was refused (the configured
|
|
319
|
+
* one). It lives in the FILE, not in a handle, because the handles that rank
|
|
320
|
+
* are not all the handles that reconcile: the MCP server's store, the
|
|
321
|
+
* dashboard, the console all open without an identity, and a per-handle hold
|
|
322
|
+
* let every one of them take a cosine across two models.
|
|
323
|
+
*
|
|
324
|
+
* Written by `reconcileEmbedder`; read by every `Store.open`; cleared by the
|
|
325
|
+
* two exits and nothing else — an open whose configured identity matches the
|
|
326
|
+
* recorded one again (the owner put the config back), or a rebuild that drops
|
|
327
|
+
* the vectors (`counterparts verify --rebuild --drop-vectors --dir <store>`,
|
|
328
|
+
* which drops `cache_meta` with them). `migrate-cache` gains a typed confirm
|
|
329
|
+
* for it in C3.
|
|
330
|
+
*/
|
|
331
|
+
export const EMBEDDER_HELD_META_KEY = "embedderHeld";
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* The way out of a hold, in the words doctor and the durable row use.
|
|
335
|
+
*
|
|
336
|
+
* There were two until 2026-09-24: put the configuration back to the model
|
|
337
|
+
* that wrote the rows (free), or drop them. The Claude Code adapter no longer
|
|
338
|
+
* offers any embedder but its local table, so the model that wrote held rows —
|
|
339
|
+
* the removed Voyage seat, in practice — cannot be configured again, and the
|
|
340
|
+
* one exit left is the drop: `verify --rebuild --drop-vectors`, after which the
|
|
341
|
+
* configured embedder re-embeds every memory. `recorded` is kept so the
|
|
342
|
+
* signature (and the durable row's `exits` field) stays one shape. `<store>` is
|
|
343
|
+
* the caller's to fill.
|
|
344
|
+
*/
|
|
345
|
+
export function heldExits(recorded: string | null): string {
|
|
346
|
+
void recorded;
|
|
347
|
+
return (
|
|
348
|
+
"drop the old vectors: counterparts verify --rebuild --drop-vectors --dir <store> " +
|
|
349
|
+
"(the configured embedder then re-embeds every memory)"
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** What a configured embedder says about the vectors it produces. */
|
|
354
|
+
export interface EmbedderIdentity {
|
|
355
|
+
/** The pinned model id: `potion-base-8M`, `voyage-3-large`. */
|
|
356
|
+
readonly model: string;
|
|
357
|
+
/**
|
|
358
|
+
* The output width when it is KNOWN before the first vector: a static table
|
|
359
|
+
* always knows; a paid seat knows for the models this package names
|
|
360
|
+
* (`claude-code/config.ts#EMBED_MODEL_DIMS`). Null only for a paid id this
|
|
361
|
+
* package has never heard of — then the width is learned from the first
|
|
362
|
+
* vector written, and untagged rows are never adopted under it.
|
|
363
|
+
*/
|
|
364
|
+
readonly dim: number | null;
|
|
365
|
+
/**
|
|
366
|
+
* `inline`: the SYNC embedder computes every vector itself, here, now, at no
|
|
367
|
+
* cost — so rows IT wrote can be dropped and refilled at open.
|
|
368
|
+
* `external`: the sync face is a cache over a paid call — nothing is rebuilt
|
|
369
|
+
* inline, and rows it wrote are never dropped at open (see `reconcileEmbedder`).
|
|
370
|
+
*/
|
|
371
|
+
readonly rebuild: "inline" | "external";
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** A tag, as recorded. `dim` null only for a hand-written tag with no `@`. */
|
|
375
|
+
export interface RecordedEmbedder {
|
|
376
|
+
readonly tag: string;
|
|
377
|
+
readonly model: string;
|
|
378
|
+
readonly dim: number | null;
|
|
379
|
+
/** Null when the companion key is absent — read as `external` (the cautious reading). */
|
|
380
|
+
readonly rebuild: "inline" | "external" | null;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export function identityTag(model: string, dim: number | null): string {
|
|
384
|
+
return dim === null ? model : `${model}@${dim}`;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Split on the LAST `@`, so a model id that contains one survives. */
|
|
388
|
+
export function parseIdentityTag(tag: string): { model: string; dim: number | null } {
|
|
389
|
+
const at = tag.lastIndexOf("@");
|
|
390
|
+
if (at <= 0) return { model: tag, dim: null };
|
|
391
|
+
const dim = Number(tag.slice(at + 1));
|
|
392
|
+
return Number.isInteger(dim) && dim > 0 ? { model: tag.slice(0, at), dim } : { model: tag, dim: null };
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function metaOf(db: Db): Map<string, string> {
|
|
396
|
+
return new Map(
|
|
397
|
+
db
|
|
398
|
+
.all<{ key: string; value: string }>(
|
|
399
|
+
"SELECT key, value FROM cache_meta WHERE key IN (?, ?, ?)",
|
|
400
|
+
EMBEDDER_META_KEY,
|
|
401
|
+
EMBEDDER_REBUILD_META_KEY,
|
|
402
|
+
EMBEDDER_HELD_META_KEY,
|
|
403
|
+
)
|
|
404
|
+
.map((r) => [r.key, r.value] as const),
|
|
405
|
+
);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
export function recordedEmbedder(db: Db): RecordedEmbedder | null {
|
|
409
|
+
const m = metaOf(db);
|
|
410
|
+
const tag = m.get(EMBEDDER_META_KEY);
|
|
411
|
+
if (tag === undefined || tag.length === 0) return null;
|
|
412
|
+
const rebuild = m.get(EMBEDDER_REBUILD_META_KEY);
|
|
413
|
+
return {
|
|
414
|
+
tag,
|
|
415
|
+
...parseIdentityTag(tag),
|
|
416
|
+
rebuild: rebuild === "inline" || rebuild === "external" ? rebuild : null,
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** The durable hold, if box 3 is under one: the refused identity, or null. */
|
|
421
|
+
export function heldEmbedder(db: Db): string | null {
|
|
422
|
+
try {
|
|
423
|
+
const v = metaOf(db).get(EMBEDDER_HELD_META_KEY);
|
|
424
|
+
return v === undefined || v.length === 0 ? null : v;
|
|
425
|
+
} catch {
|
|
426
|
+
return null; // a cache with no meta table holds nothing
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* The outcome of `reconcileEmbedder`, by name. Every arm is a different
|
|
432
|
+
* sentence to somebody reading why their semantic channel looks the way it
|
|
433
|
+
* does, so none of them is folded into another.
|
|
434
|
+
*/
|
|
435
|
+
export type EmbedderVerdict =
|
|
436
|
+
/** No embedder configured in this process and no hold on the file: the rows were not looked at. */
|
|
437
|
+
| { readonly kind: "none" }
|
|
438
|
+
/**
|
|
439
|
+
* The recorded identity is the configured one. Nothing was written — unless
|
|
440
|
+
* this open RELEASED a hold (`released`), because the owner put the
|
|
441
|
+
* configuration back to the model that wrote the rows.
|
|
442
|
+
*/
|
|
443
|
+
| { readonly kind: "match"; readonly tag: string; readonly released?: boolean }
|
|
444
|
+
/**
|
|
445
|
+
* There was no tag, and now there is: a fresh table taken by this identity
|
|
446
|
+
* (a static table's `<model>@<dim>`, a paid seat's model alone until its
|
|
447
|
+
* first vector), or legacy untagged rows ADOPTED by a paid seat whose known
|
|
448
|
+
* width they all have. (`tag` is null only in a verdict from before the
|
|
449
|
+
* re-review, kept in the type for readers of old telemetry.)
|
|
450
|
+
*/
|
|
451
|
+
| { readonly kind: "tagged"; readonly tag: string | null; readonly adopted: number }
|
|
452
|
+
/**
|
|
453
|
+
* The rows were FREE to recompute (a static table's, or none at all) and
|
|
454
|
+
* were from another model: gone, and the tag names the configured one. An
|
|
455
|
+
* inline embedder refills them at open; a paid one through its backfill.
|
|
456
|
+
*/
|
|
457
|
+
| { readonly kind: "reset"; readonly from: string | null; readonly to: string | null; readonly dropped: number }
|
|
458
|
+
/**
|
|
459
|
+
* PAID rows the configured embedder cannot use (or untagged rows it cannot
|
|
460
|
+
* vouch for): NOTHING dropped, nothing tagged, and a durable marker says so.
|
|
461
|
+
* No handle on this file writes vectors or ranks against them until one of
|
|
462
|
+
* `heldExits(recorded)` is taken. `fresh` is true on the open that WROTE the marker.
|
|
463
|
+
*/
|
|
464
|
+
| {
|
|
465
|
+
readonly kind: "held";
|
|
466
|
+
readonly recorded: string | null;
|
|
467
|
+
readonly configured: string | null;
|
|
468
|
+
readonly rows: number;
|
|
469
|
+
readonly fresh: boolean;
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Box 3 was written by a NEWER build (`cacheAhead`). The identity check did
|
|
473
|
+
* not run, nothing was written, and — exactly as under `held` — this handle
|
|
474
|
+
* neither writes vectors nor ranks against them. The lexical index is still
|
|
475
|
+
* read and written by a non-server handle (the MCP server refuses every tool
|
|
476
|
+
* instead, #187).
|
|
477
|
+
*/
|
|
478
|
+
| { readonly kind: "cache-ahead"; readonly found: string; readonly expected: number }
|
|
479
|
+
/**
|
|
480
|
+
* The check had a DECISION to write (a first tag, a reset, a hold, an
|
|
481
|
+
* adoption) and another process held box 3's write lock past the busy
|
|
482
|
+
* timeout. Nothing was written; this handle's embedder is withdrawn for this
|
|
483
|
+
* open (no vector written under an unsettled identity), and the next open
|
|
484
|
+
* decides again. A lost lock costs the tag, never the open (re-review NIT 1).
|
|
485
|
+
*/
|
|
486
|
+
| { readonly kind: "deferred"; readonly reason: "locked" };
|
|
487
|
+
|
|
488
|
+
/** Per open database: the identity this process writes vectors under. */
|
|
489
|
+
const writerIdentity = new WeakMap<Db, EmbedderIdentity>();
|
|
490
|
+
|
|
491
|
+
function writeTag(db: Db, tag: string | null, rebuild: "inline" | "external"): void {
|
|
492
|
+
if (tag === null) {
|
|
493
|
+
db.run("DELETE FROM cache_meta WHERE key IN (?, ?)", EMBEDDER_META_KEY, EMBEDDER_REBUILD_META_KEY);
|
|
494
|
+
} else {
|
|
495
|
+
db.run("INSERT OR REPLACE INTO cache_meta (key, value) VALUES (?, ?)", EMBEDDER_META_KEY, tag);
|
|
496
|
+
db.run("INSERT OR REPLACE INTO cache_meta (key, value) VALUES (?, ?)", EMBEDDER_REBUILD_META_KEY, rebuild);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* Is the recorded identity the configured one? The model always; the width
|
|
502
|
+
* only for an INLINE table, where it is part of what the table is (a 256-wide
|
|
503
|
+
* slice of a 1,024-wide table is another space). A paid seat's width is its
|
|
504
|
+
* provider's, pinned by the model id — so its declared width (`EMBED_MODEL_DIMS`)
|
|
505
|
+
* decides only whether untagged rows may be adopted, and the tag records what
|
|
506
|
+
* its vectors actually measured.
|
|
507
|
+
*/
|
|
508
|
+
function sameIdentity(recorded: { model: string; dim: number | null }, configured: EmbedderIdentity): boolean {
|
|
509
|
+
if (recorded.model !== configured.model) return false;
|
|
510
|
+
if (configured.rebuild === "external") return true;
|
|
511
|
+
return configured.dim === null || recorded.dim === null || recorded.dim === configured.dim;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* The tag an open writes when it TAKES a file (a fresh table, a reset): an
|
|
516
|
+
* inline table's full `<model>@<dim>`; a paid seat's model alone — its first
|
|
517
|
+
* vector completes it with the width the provider actually returned.
|
|
518
|
+
*/
|
|
519
|
+
function takenTag(configured: EmbedderIdentity): string {
|
|
520
|
+
return identityTag(configured.model, configured.rebuild === "inline" ? configured.dim : null);
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* THE AT-OPEN IDENTITY CHECK. Called once per open by a process that has an
|
|
525
|
+
* embedder configured (never by an instrument — an observer has none), and
|
|
526
|
+
* never again for the life of the handle: "at open only" is the rule, and the
|
|
527
|
+
* per-call schema check is another module's (roadmap E).
|
|
528
|
+
*
|
|
529
|
+
* **The steady state takes no lock.** A match, or a paid seat of unknown width
|
|
530
|
+
* meeting a table with no rows and no tag (nothing to decide), returns from a
|
|
531
|
+
* plain read. Only a real decision opens a transaction.
|
|
532
|
+
*
|
|
533
|
+
* **Paid rows are never dropped at open**, whatever is configured (review of
|
|
534
|
+
* #190, MAJOR 2). The rules, by what the table holds:
|
|
535
|
+
*
|
|
536
|
+
* - **held already** — stays held until the configured identity matches the
|
|
537
|
+
* recorded one again (then released) or the rows are dropped by a rebuild.
|
|
538
|
+
* - **tagged, same identity** — match.
|
|
539
|
+
* - **tagged, other identity:**
|
|
540
|
+
* - no rows → retag (nothing to lose);
|
|
541
|
+
* - the recorded rows are INLINE (a static table's) → drop, retag, and
|
|
542
|
+
* the configured embedder refills (free);
|
|
543
|
+
* - the recorded rows are EXTERNAL (paid) → HELD, even under a static
|
|
544
|
+
* configuration. Dropping paid vectors is the owner's decision.
|
|
545
|
+
* - **untagged, no rows** — tag now if the width is known.
|
|
546
|
+
* - **untagged rows** (a v4 cache, or a tag erased by a mixed-build stamp-down):
|
|
547
|
+
* - static configured, and EVERY row has the table's own width → drop and
|
|
548
|
+
* refill (they are a static table's rows whose name was lost; free);
|
|
549
|
+
* - paid configured with a KNOWN width, and every row has it → adopt;
|
|
550
|
+
* - anything else → HELD.
|
|
551
|
+
*
|
|
552
|
+
* Race-safe by construction: anything that writes re-reads and re-decides
|
|
553
|
+
* inside one IMMEDIATE transaction, so two processes opening at once agree on
|
|
554
|
+
* one outcome and the second sees the first's tag as a match.
|
|
555
|
+
*/
|
|
556
|
+
export function reconcileEmbedder(db: Db, configured: EmbedderIdentity): EmbedderVerdict {
|
|
557
|
+
const m0 = metaOf(db);
|
|
558
|
+
const fastTag = m0.get(EMBEDDER_META_KEY);
|
|
559
|
+
const fastHeld = m0.get(EMBEDDER_HELD_META_KEY);
|
|
560
|
+
if (fastHeld === undefined && fastTag !== undefined && sameIdentity(parseIdentityTag(fastTag), configured)) {
|
|
561
|
+
writerIdentity.set(db, configured);
|
|
562
|
+
return { kind: "match", tag: fastTag };
|
|
563
|
+
}
|
|
564
|
+
// A STANDING hold, asked again by the identity it already refused: nothing to
|
|
565
|
+
// decide, so no lock — every hook on a held store opens with a read.
|
|
566
|
+
const fastConfigured = identityTag(configured.model, configured.dim);
|
|
567
|
+
if (
|
|
568
|
+
fastHeld !== undefined &&
|
|
569
|
+
fastHeld === fastConfigured &&
|
|
570
|
+
!(fastTag !== undefined && sameIdentity(parseIdentityTag(fastTag), configured))
|
|
571
|
+
) {
|
|
572
|
+
return { kind: "held", recorded: fastTag ?? null, configured: fastConfigured, rows: embeddingCount(db), fresh: false };
|
|
573
|
+
}
|
|
574
|
+
// (BLOCKER 1 of the #190 review: every arm below is a TRANSITION, taken once
|
|
575
|
+
// per store — a fresh table is tagged on its first identified open, even a
|
|
576
|
+
// paid seat's with its model alone, so every later open is one of the two
|
|
577
|
+
// lock-free reads above. The once-only write may still lose the lock: the
|
|
578
|
+
// Store turns that into `deferred`, never a throw.)
|
|
579
|
+
const verdict = db.transaction((): EmbedderVerdict => {
|
|
580
|
+
const recorded = recordedEmbedder(db);
|
|
581
|
+
const held = heldEmbedder(db);
|
|
582
|
+
const rows = embeddingCount(db);
|
|
583
|
+
const configuredTag = identityTag(configured.model, configured.dim);
|
|
584
|
+
const dropAndTag = (from: string | null): EmbedderVerdict => {
|
|
585
|
+
db.run("DELETE FROM embeddings");
|
|
586
|
+
db.run("DELETE FROM cache_meta WHERE key = ?", EMBEDDER_HELD_META_KEY);
|
|
587
|
+
// A tag even when the width is unknown (`model` alone): the per-write and
|
|
588
|
+
// per-search checks need to know WHOSE the file is now, or a process
|
|
589
|
+
// still running under the old identity would re-tag it with the first
|
|
590
|
+
// vector it wrote (re-review of #190, MAJOR A).
|
|
591
|
+
const to = takenTag(configured);
|
|
592
|
+
writeTag(db, to, configured.rebuild);
|
|
593
|
+
return { kind: "reset", from, to, dropped: rows };
|
|
594
|
+
};
|
|
595
|
+
const hold = (): EmbedderVerdict => {
|
|
596
|
+
const fresh = held !== configuredTag;
|
|
597
|
+
if (fresh) db.run("INSERT OR REPLACE INTO cache_meta (key, value) VALUES (?, ?)", EMBEDDER_HELD_META_KEY, configuredTag);
|
|
598
|
+
return { kind: "held", recorded: recorded?.tag ?? null, configured: configuredTag, rows, fresh };
|
|
599
|
+
};
|
|
600
|
+
if (recorded !== null) {
|
|
601
|
+
if (sameIdentity(recorded, configured)) {
|
|
602
|
+
if (held !== null) {
|
|
603
|
+
db.run("DELETE FROM cache_meta WHERE key = ?", EMBEDDER_HELD_META_KEY);
|
|
604
|
+
return { kind: "match", tag: recorded.tag, released: true };
|
|
605
|
+
}
|
|
606
|
+
return { kind: "match", tag: recorded.tag };
|
|
607
|
+
}
|
|
608
|
+
if (rows === 0) return dropAndTag(recorded.tag);
|
|
609
|
+
if (recorded.rebuild === "inline") return dropAndTag(recorded.tag);
|
|
610
|
+
return hold();
|
|
611
|
+
}
|
|
612
|
+
if (rows === 0) {
|
|
613
|
+
db.run("DELETE FROM cache_meta WHERE key = ?", EMBEDDER_HELD_META_KEY);
|
|
614
|
+
const tag = takenTag(configured);
|
|
615
|
+
writeTag(db, tag, configured.rebuild);
|
|
616
|
+
return { kind: "tagged", tag, adopted: 0 };
|
|
617
|
+
}
|
|
618
|
+
// Untagged rows.
|
|
619
|
+
const dims = db.all<{ dim: number }>("SELECT DISTINCT dim FROM embeddings").map((r) => r.dim);
|
|
620
|
+
const only = dims.length === 1 ? dims[0] : undefined;
|
|
621
|
+
if (configured.rebuild === "inline") {
|
|
622
|
+
return only !== undefined && only === configured.dim ? dropAndTag(null) : hold();
|
|
623
|
+
}
|
|
624
|
+
if (only !== undefined && configured.dim !== null && only === configured.dim) {
|
|
625
|
+
db.run("DELETE FROM cache_meta WHERE key = ?", EMBEDDER_HELD_META_KEY);
|
|
626
|
+
const tag = identityTag(configured.model, only);
|
|
627
|
+
writeTag(db, tag, configured.rebuild);
|
|
628
|
+
return { kind: "tagged", tag, adopted: rows };
|
|
629
|
+
}
|
|
630
|
+
return hold();
|
|
631
|
+
});
|
|
632
|
+
if (verdict.kind !== "held") writerIdentity.set(db, configured);
|
|
633
|
+
return verdict;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/** Why a vector was not written, or a ranking not taken — by name. */
|
|
637
|
+
export type VectorRefusal =
|
|
638
|
+
/** Box 3 is under a durable hold (`EMBEDDER_HELD_META_KEY`). */
|
|
639
|
+
| "held"
|
|
640
|
+
/** Box 3 was written by a newer build. */
|
|
641
|
+
| "cache-ahead"
|
|
642
|
+
/**
|
|
643
|
+
* The file now names ANOTHER identity than this handle's: a process with a
|
|
644
|
+
* newer configuration reset or re-tagged it after this handle opened (a
|
|
645
|
+
* session-long MCP server, the re-review's MAJOR A). A vector written now
|
|
646
|
+
* would be filed under a tag it does not match; a cosine taken now would
|
|
647
|
+
* cross two models.
|
|
648
|
+
*/
|
|
649
|
+
| "identity-changed";
|
|
650
|
+
|
|
651
|
+
/** The file's claim, read FRESH: one primary-key read of three `cache_meta` rows. */
|
|
652
|
+
function fileClaim(db: Db): { tag: string | null; held: string | null; ahead: boolean } {
|
|
653
|
+
let rows: { key: string; value: string }[];
|
|
654
|
+
try {
|
|
655
|
+
rows = db.all<{ key: string; value: string }>(
|
|
656
|
+
"SELECT key, value FROM cache_meta WHERE key IN ('schemaVersion', ?, ?)",
|
|
657
|
+
EMBEDDER_META_KEY,
|
|
658
|
+
EMBEDDER_HELD_META_KEY,
|
|
659
|
+
);
|
|
660
|
+
} catch {
|
|
661
|
+
return { tag: null, held: null, ahead: false };
|
|
662
|
+
}
|
|
663
|
+
const get = (k: string): string | null => {
|
|
664
|
+
const v = rows.find((r) => r.key === k)?.value;
|
|
665
|
+
return v === undefined || v.length === 0 ? null : v;
|
|
666
|
+
};
|
|
667
|
+
return {
|
|
668
|
+
tag: get(EMBEDDER_META_KEY),
|
|
669
|
+
held: get(EMBEDDER_HELD_META_KEY),
|
|
670
|
+
ahead: schemaAhead(get("schemaVersion"), CACHE_SCHEMA_VERSION),
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
function refusalFor(
|
|
675
|
+
claim: { tag: string | null; held: string | null; ahead: boolean },
|
|
676
|
+
identity: EmbedderIdentity | undefined,
|
|
677
|
+
dim: number,
|
|
678
|
+
): VectorRefusal | null {
|
|
679
|
+
if (claim.ahead) return "cache-ahead";
|
|
680
|
+
if (claim.held !== null) return "held";
|
|
681
|
+
if (identity === undefined || claim.tag === null) return null;
|
|
682
|
+
const recorded = parseIdentityTag(claim.tag);
|
|
683
|
+
if (recorded.model !== identity.model) return "identity-changed";
|
|
684
|
+
// An inline table's width is part of its identity; a paid seat's is its
|
|
685
|
+
// provider's (see `sameIdentity`), and the scan's width filter covers it.
|
|
686
|
+
if (identity.rebuild === "inline" && recorded.dim !== null && recorded.dim !== dim) return "identity-changed";
|
|
687
|
+
return null;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/**
|
|
691
|
+
* THE PER-CALL CHECK FOR A RANKING (re-review of #190, MAJOR A). The at-open
|
|
692
|
+
* check is not enough for a handle that lives all session: another process
|
|
693
|
+
* may reset or re-tag box 3 under it. So every ranking reads the file's claim
|
|
694
|
+
* first — the same cheap read #187 makes of the schema stamp on every tool
|
|
695
|
+
* call — and answers nothing, by name, when the file is held, ahead, or now
|
|
696
|
+
* another identity's. A handle with no identity (the console, the dashboard)
|
|
697
|
+
* is checked for the hold and the stamp only; the width filter in `nearest`
|
|
698
|
+
* is its last line.
|
|
699
|
+
*/
|
|
700
|
+
export function searchRefusal(db: Db, identity: EmbedderIdentity | undefined, dim: number): VectorRefusal | null {
|
|
701
|
+
return refusalFor(fileClaim(db), identity, dim);
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
/**
|
|
705
|
+
* THE PER-WRITE CHECK, and "written whenever vectors are written" (the tag
|
|
706
|
+
* follows the vectors). Called INSIDE the vector write's own transaction, so
|
|
707
|
+
* the check, the vector and the tag it implies are one unit:
|
|
708
|
+
*
|
|
709
|
+
* - the file held, ahead, or now another identity's → REFUSED: no vector is
|
|
710
|
+
* written, and the memory is left unembedded for whichever process owns the
|
|
711
|
+
* file now (its backfill fills it);
|
|
712
|
+
* - otherwise, a handle with a reconciled identity re-tags the file when its
|
|
713
|
+
* `<model>@<dim>` differs from the file's (a first vector; a paid seat's
|
|
714
|
+
* width learned; a model-only tag completed). A handle with no identity
|
|
715
|
+
* (the console converting rows, a test's bare cache) writes no tag.
|
|
716
|
+
*/
|
|
717
|
+
function admitVector(db: Db, dim: number): VectorRefusal | null {
|
|
718
|
+
const identity = writerIdentity.get(db);
|
|
719
|
+
const claim = fileClaim(db);
|
|
720
|
+
const refusal = refusalFor(claim, identity, dim);
|
|
721
|
+
if (refusal !== null || identity === undefined) return refusal;
|
|
722
|
+
const tag = identityTag(identity.model, dim);
|
|
723
|
+
if (claim.tag !== tag) writeTag(db, tag, identity.rebuild);
|
|
724
|
+
return null;
|
|
725
|
+
}
|
|
726
|
+
|
|
221
727
|
/**
|
|
222
728
|
* Scoped to box 3 alone: drops only this file's tables, touches no canonical state.
|
|
223
729
|
*
|
|
@@ -230,13 +736,33 @@ export function openCache(path: string): Db {
|
|
|
230
736
|
* rather than read out and rewritten, so nothing has to fit in memory.
|
|
231
737
|
*/
|
|
232
738
|
export function resetCache(db: Db, opts: { keepEmbeddings?: boolean } = {}): void {
|
|
233
|
-
|
|
739
|
+
// A rebuild re-stamps the version, so on a newer build's cache it would be a
|
|
740
|
+
// downgrade by another name. Refused by the same code box 2 uses.
|
|
741
|
+
const ahead = cacheAhead(db);
|
|
742
|
+
if (ahead !== null) throw new StoreError("SCHEMA_AHEAD", { box: "cache", expected: ahead.expected, found: ahead.found });
|
|
743
|
+
const keep = opts.keepEmbeddings === true;
|
|
744
|
+
const drop = keep ? TABLES.filter((t) => t !== "embeddings") : TABLES;
|
|
234
745
|
forgetAvgDocLen(db);
|
|
235
746
|
db.transaction(() => {
|
|
747
|
+
// KEEP MEANS KEEP THE TAG TOO — and the hold. `cache_meta` is one of the
|
|
748
|
+
// dropped tables, and a rebuild that spared the vectors but dropped the
|
|
749
|
+
// line saying which model wrote them would leave untagged rows behind. A
|
|
750
|
+
// rebuild that DROPS the vectors drops both, and that is one of the two
|
|
751
|
+
// ways out of a hold (`heldExits`).
|
|
752
|
+
const tag = keep
|
|
753
|
+
? db.all<{ key: string; value: string }>(
|
|
754
|
+
"SELECT key, value FROM cache_meta WHERE key IN (?, ?, ?)",
|
|
755
|
+
EMBEDDER_META_KEY,
|
|
756
|
+
EMBEDDER_REBUILD_META_KEY,
|
|
757
|
+
EMBEDDER_HELD_META_KEY,
|
|
758
|
+
)
|
|
759
|
+
: [];
|
|
236
760
|
for (const t of drop) db.exec(`DROP TABLE IF EXISTS ${t}`);
|
|
237
761
|
for (const sql of DDL) db.exec(sql);
|
|
238
762
|
db.run("INSERT OR REPLACE INTO cache_meta (key, value) VALUES ('schemaVersion', ?)", String(CACHE_SCHEMA_VERSION));
|
|
763
|
+
for (const r of tag) db.run("INSERT OR REPLACE INTO cache_meta (key, value) VALUES (?, ?)", r.key, r.value);
|
|
239
764
|
});
|
|
765
|
+
// No vectors, no tag: the next vector written re-tags (`admitVector`).
|
|
240
766
|
}
|
|
241
767
|
|
|
242
768
|
// ── vectors: the wire shape of box 3's embeddings ────────────────────────────
|
|
@@ -455,7 +981,7 @@ export function tokenize(text: string): string[] {
|
|
|
455
981
|
}
|
|
456
982
|
|
|
457
983
|
/** (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[]):
|
|
984
|
+
export function indexDoc(db: Db, id: string, text: string, vec?: readonly number[]): VectorRefusal | null {
|
|
459
985
|
const counts = new Map<string, number>();
|
|
460
986
|
let len = 0;
|
|
461
987
|
for (const tok of tokenize(text)) {
|
|
@@ -463,7 +989,7 @@ export function indexDoc(db: Db, id: string, text: string, vec?: readonly number
|
|
|
463
989
|
len += 1;
|
|
464
990
|
}
|
|
465
991
|
forgetAvgDocLen(db);
|
|
466
|
-
db.transaction(() => {
|
|
992
|
+
return db.transaction((): VectorRefusal | null => {
|
|
467
993
|
db.run("DELETE FROM doc_tokens WHERE memory_id = ?", id);
|
|
468
994
|
const ins = db.prepare("INSERT INTO doc_tokens (memory_id, token, tf) VALUES (?, ?, ?)");
|
|
469
995
|
for (const [token, tf] of counts) ins.run(id, token, tf);
|
|
@@ -471,14 +997,22 @@ export function indexDoc(db: Db, id: string, text: string, vec?: readonly number
|
|
|
471
997
|
// table rather than dragging a zero through `AVG(len)`.
|
|
472
998
|
if (len > 0) db.run("INSERT OR REPLACE INTO doc_lens (memory_id, len) VALUES (?, ?)", id, len);
|
|
473
999
|
else db.run("DELETE FROM doc_lens WHERE memory_id = ?", id);
|
|
474
|
-
if (vec
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
);
|
|
1000
|
+
if (vec === undefined) return null;
|
|
1001
|
+
const refusal = admitVector(db, vec.length);
|
|
1002
|
+
if (refusal !== null) {
|
|
1003
|
+
// The text changed and this vector may not be filed: the row's OLD
|
|
1004
|
+
// vector (if any) describes words the memory no longer says, so it goes,
|
|
1005
|
+
// and the memory waits for the owning identity's backfill.
|
|
1006
|
+
db.run("DELETE FROM embeddings WHERE memory_id = ?", id);
|
|
1007
|
+
return refusal;
|
|
481
1008
|
}
|
|
1009
|
+
db.run(
|
|
1010
|
+
"INSERT OR REPLACE INTO embeddings (memory_id, dim, vec) VALUES (?, ?, ?)",
|
|
1011
|
+
id,
|
|
1012
|
+
vec.length,
|
|
1013
|
+
encodeVector(vec),
|
|
1014
|
+
);
|
|
1015
|
+
return null;
|
|
482
1016
|
});
|
|
483
1017
|
}
|
|
484
1018
|
|
|
@@ -493,13 +1027,22 @@ export function indexDoc(db: Db, id: string, text: string, vec?: readonly number
|
|
|
493
1027
|
* `BUDGET_MS` went from 250 to 1200. Sixty-four token-index rewrites per Stop
|
|
494
1028
|
* would have fought the constraint that motivated the lag in the first place.
|
|
495
1029
|
*/
|
|
496
|
-
export function setEmbedding(db: Db, id: string, vec: readonly number[]):
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
1030
|
+
export function setEmbedding(db: Db, id: string, vec: readonly number[]): VectorRefusal | null {
|
|
1031
|
+
// ONE transaction for the check, the vector and the tag it may imply (a
|
|
1032
|
+
// SAVEPOINT when the caller already holds one — the at-open refill does): a
|
|
1033
|
+
// crash between them must not leave a vector under no tag, or a tag with no
|
|
1034
|
+
// rebuild key. Returns the refusal, by name, or null when the vector landed.
|
|
1035
|
+
return db.transaction((): VectorRefusal | null => {
|
|
1036
|
+
const refusal = admitVector(db, vec.length);
|
|
1037
|
+
if (refusal !== null) return refusal;
|
|
1038
|
+
db.run(
|
|
1039
|
+
"INSERT OR REPLACE INTO embeddings (memory_id, dim, vec) VALUES (?, ?, ?)",
|
|
1040
|
+
id,
|
|
1041
|
+
vec.length,
|
|
1042
|
+
encodeVector(vec),
|
|
1043
|
+
);
|
|
1044
|
+
return null;
|
|
1045
|
+
});
|
|
503
1046
|
}
|
|
504
1047
|
|
|
505
1048
|
/**
|
|
@@ -655,11 +1198,25 @@ export function docFrequency(db: Db, tokens: readonly string[]): Map<string, num
|
|
|
655
1198
|
return out;
|
|
656
1199
|
}
|
|
657
1200
|
|
|
1201
|
+
/**
|
|
1202
|
+
* Rank every stored vector against `vec`.
|
|
1203
|
+
*
|
|
1204
|
+
* **Only rows of the query's own width are scored (v5).** `cosine` reads the
|
|
1205
|
+
* common prefix of two vectors of different lengths, so a 1,024-d query against
|
|
1206
|
+
* a 256-d row used to produce a NUMBER — the cosine of a truncated query against
|
|
1207
|
+
* a whole row, which means nothing and ranks anyway. Since two embedders can
|
|
1208
|
+
* now have written this table (the identity check keeps them apart, and a held
|
|
1209
|
+
* mismatch is exactly the state where they are not), a row of another width is
|
|
1210
|
+
* skipped rather than scored. A CORRUPT row (`decodeVector` → empty) keeps its
|
|
1211
|
+
* old treatment — it scores 0 through `cosine`'s zero-norm arm, and the census
|
|
1212
|
+
* names it — because that is a different fault with its own reporting.
|
|
1213
|
+
*/
|
|
658
1214
|
export function nearest(db: Db, vec: readonly number[], limit = 10): Hit[] {
|
|
659
1215
|
const rows = db.all<{ memory_id: string; vec: SqlValue }>("SELECT memory_id, vec FROM embeddings");
|
|
660
1216
|
const hits: Hit[] = [];
|
|
661
1217
|
for (const row of rows) {
|
|
662
1218
|
const other = decodeVector(row.vec);
|
|
1219
|
+
if (other.length > 0 && other.length !== vec.length) continue;
|
|
663
1220
|
hits.push({ id: row.memory_id, score: cosine(vec, other) });
|
|
664
1221
|
}
|
|
665
1222
|
hits.sort((a, b) => b.score - a.score || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
@@ -676,7 +1233,8 @@ export function nearestVectors(db: Db, vec: readonly number[], limit = 10): numb
|
|
|
676
1233
|
const scored: { id: string; score: number; vec: Float32Array | number[] }[] = [];
|
|
677
1234
|
for (const row of rows) {
|
|
678
1235
|
const other = decodeVector(row.vec);
|
|
679
|
-
|
|
1236
|
+
// Same width as the query or not at all — see `nearest`.
|
|
1237
|
+
if (other.length === 0 || other.length !== vec.length) continue;
|
|
680
1238
|
scored.push({ id: row.memory_id, score: cosine(vec, other), vec: other });
|
|
681
1239
|
}
|
|
682
1240
|
scored.sort((a, b) => b.score - a.score || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|