cursedbelt-server 4.64.1 → 4.65.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.
@@ -0,0 +1,529 @@
1
+ // Search by meaning — the shared engine (forge task 4525).
2
+ //
3
+ // The owner, 2026-11-05: *"I want to be able to put in terms and get semantic results, so I should
4
+ // even be able to put in phrases … show me the results in a way where I can tell what it is and why
5
+ // it was found."* Words and meaning together, on the pipeline photos measured (`apps/photos/docs/SEARCH.md`
6
+ // § Reranking): a lexical list and an embedding list, fused by reciprocal rank, the head read again
7
+ // by a cross-encoder that tells a match from a near-miss.
8
+ //
9
+ // Two halves live here:
10
+ //
11
+ // · The pieces any corpus uses — {@link fuse}, {@link rerankOrder}, the models and their measured
12
+ // constants, {@link rerankScores}. Photos (Vectorize + D1 FTS5, thousands of assets) imports them.
13
+ // · A whole engine for a SMALL corpus — hundreds of {@link MeaningPlace}s, the sections of an app,
14
+ // rebuilt on deploy: BM25 over the place's fields ({@link createLexicalIndex}), {@link cosineTopK}
15
+ // over an in-memory index (no Vectorize, so no index lag), {@link whyFound} derived from the words
16
+ // (never a model's sentence), and the ranking cached for {@link MEANING_CACHE_DAYS} under a key
17
+ // that holds the corpus's version, so a changed document is a fresh answer. Figures are never
18
+ // cached with it: a hit names a place, and the app reads that place's live numbers when it shows it.
19
+ //
20
+ // 🔴 A leaf: this file imports NOTHING (`leafSubpathsImportNothing.spec.ts`). The AI binding and D1
21
+ // are structural, so a Worker, a Bun server and a test all pass what they have.
22
+
23
+ /** The text embedder for both sides: a document and a query. Measured by photos, 2026-11-05. */
24
+ export const EMBED_MODEL = '@cf/baai/bge-m3';
25
+ export const EMBED_DIMS = 1024;
26
+ /** The cross-encoder that reads the query beside each candidate's document. */
27
+ export const RERANK_MODEL = '@cf/baai/bge-reranker-base';
28
+ /**
29
+ * Below this a candidate is a near-miss: irrelevant documents sat on a flat floor near 4e-5, every
30
+ * match but one at 1e-4 or above (photos, 400 production documents and ten queries, 2026-11-05).
31
+ */
32
+ export const RERANK_FLOOR = 1e-4;
33
+ /** A search waits this long for the reranker, then shows the fused order. */
34
+ export const RERANK_TIMEOUT_MS = 5_000;
35
+ /** A document's first characters the reranker reads. */
36
+ export const RERANK_DOC_CHARS = 1_500;
37
+ /** Reciprocal-rank fusion's k — the standard 60, under which rank 1 and rank 5 differ by ~6%. */
38
+ export const RRF_K = 60;
39
+ /** How long a cached ranking stands. The corpus's version is in the key, so a change never waits this out. */
40
+ export const MEANING_CACHE_DAYS = 30;
41
+
42
+ /**
43
+ * Reciprocal-rank fusion: each id scores `Σ 1 / (k + rank)` over the lists that hold it, so an id
44
+ * both lists found leads, and one only a single list found still stands where its rank puts it. A
45
+ * tie keeps first-seen order.
46
+ */
47
+ export function fuse(lists: readonly (readonly string[])[], k = RRF_K): string[] {
48
+ const score = new Map<string, number>();
49
+ const seen: string[] = [];
50
+ for (const list of lists)
51
+ list.forEach((id, rank) => {
52
+ if (!score.has(id)) seen.push(id);
53
+ score.set(id, (score.get(id) ?? 0) + 1 / (k + rank + 1));
54
+ });
55
+ const order = new Map(seen.map((id, i) => [id, i]));
56
+ return seen.sort((a, b) => (score.get(b) ?? 0) - (score.get(a) ?? 0) || (order.get(a) ?? 0) - (order.get(b) ?? 0));
57
+ }
58
+
59
+ /**
60
+ * The fused list with its head reordered by the reranker's scores (one per `head` id, in `head`'s
61
+ * order). The cross-encoder tells a match from a near-miss far better than it orders matches, so the
62
+ * head's fused rank and its reranked rank are fused again, never the score trusted alone; whatever
63
+ * scores under `floor` is a near-miss, returned apart so the caller decides — photos puts them at
64
+ * the end of its grid, a palette drops them.
65
+ */
66
+ export function rerankOrder(
67
+ fused: readonly string[],
68
+ head: readonly string[],
69
+ scores: readonly number[],
70
+ floor = RERANK_FLOOR,
71
+ ): { order: string[]; nearMisses: string[] } {
72
+ const passes = (i: number) => (scores[i] ?? 0) >= floor;
73
+ const byScore = head.map((_, i) => i).sort((a, b) => (scores[b] ?? 0) - (scores[a] ?? 0) || a - b);
74
+ const kept = fuse([head.filter((_, i) => passes(i)), byScore.filter(passes).map((i) => head[i] as string)]);
75
+ const inHead = new Set(head);
76
+ return { order: [...kept, ...fused.filter((id) => !inHead.has(id))], nearMisses: head.filter((_, i) => !passes(i)) };
77
+ }
78
+
79
+ /** The reranker's answer, `{ response: [{ id, score }] }` with `id` an index into the request, as one score per text. */
80
+ export function rerankScores(result: unknown, count: number): number[] {
81
+ const response = (result as { response?: unknown } | null)?.response;
82
+ if (!Array.isArray(response)) throw new Error(`${RERANK_MODEL} answered no scores`);
83
+ const scores = new Array<number>(count).fill(0);
84
+ for (const r of response as { id?: unknown; score?: unknown }[]) {
85
+ if (typeof r.id === 'number' && Number.isInteger(r.id) && r.id >= 0 && r.id < count && typeof r.score === 'number' && Number.isFinite(r.score))
86
+ scores[r.id] = r.score;
87
+ }
88
+ return scores;
89
+ }
90
+
91
+ /** The request body the reranker takes: an empty context is refused by its schema (`minLength: 1`), so it reads `-`. */
92
+ export const rerankInput = (query: string, texts: readonly string[]) => ({
93
+ query,
94
+ contexts: texts.map((t) => ({ text: t.slice(0, RERANK_DOC_CHARS).trim() || '-' })),
95
+ });
96
+
97
+ /** `work`, or a rejection after `ms` — a page is waiting, not a job. */
98
+ export function withinMs<T>(work: Promise<T>, ms: number, what = 'the model'): Promise<T> {
99
+ let timer: ReturnType<typeof setTimeout> | undefined;
100
+ const late = new Promise<never>((_, reject) => {
101
+ timer = setTimeout(() => reject(new Error(`${what} gave no answer in ${ms / 1000} s`)), ms);
102
+ });
103
+ return Promise.race([work, late]).finally(() => clearTimeout(timer));
104
+ }
105
+
106
+ // ── The small-corpus engine ──────────────────────────────────────────────────────────────────
107
+
108
+ /** One place a search can land: a page, a tab, a filtered view — whatever an `href` reaches. */
109
+ export interface MeaningPlace {
110
+ id: string;
111
+ /** Page + anchor + tab/filter — where choosing the hit goes. */
112
+ href: string;
113
+ title: string;
114
+ /** Its breadcrumb, outermost first, ending at the place's parent (or itself). */
115
+ crumbs: string[];
116
+ /** A sentence, in the owner's words, of what the place SHOWS. The snippet is cut from it. */
117
+ about: string;
118
+ facets: { subject: string[]; measure: string[]; breakdown: string[] };
119
+ kind: string;
120
+ }
121
+
122
+ /** How sure the engine is — from the reranker's score, or the lists' agreement when it was not asked. */
123
+ export type MeaningBand = 'strong' | 'likely' | 'loose';
124
+
125
+ /** One result, shaped for cursedbelt's palette (`MeaningRow`): what it is, and why it was found. */
126
+ export interface MeaningHit {
127
+ id: string;
128
+ href: string;
129
+ title: string;
130
+ crumbs: string[];
131
+ kind: string;
132
+ /** `about`, with the `[start, end)` ranges of the query's words marked. */
133
+ snippet: { text: string; marks: [number, number][] };
134
+ /** The query's words the place holds; none means it was found by meaning alone. */
135
+ why: { words: string[]; byMeaning: boolean };
136
+ band: MeaningBand;
137
+ }
138
+
139
+ export interface MeaningAnswer {
140
+ query: string;
141
+ /** The corpus's version — a hash of every document and the models. */
142
+ version: string;
143
+ hits: MeaningHit[];
144
+ /** Answered from the stored ranking: no model was asked. */
145
+ cached: boolean;
146
+ /** The reranker read the head (false: it was absent, slow or failed, and the fused order stands). */
147
+ reranked: boolean;
148
+ tookMs: number;
149
+ }
150
+
151
+ /**
152
+ * The bands. bge-reranker-base answers a sigmoid: a near-miss sits under {@link RERANK_FLOOR}, a
153
+ * clear match well above a tenth. Measured on Station's places at landing (forge task 4525).
154
+ */
155
+ export const BAND_STRONG = 0.1;
156
+ export const BAND_LIKELY = 0.005;
157
+
158
+ export function bandFor(score: number): MeaningBand {
159
+ return score >= BAND_STRONG ? 'strong' : score >= BAND_LIKELY ? 'likely' : 'loose';
160
+ }
161
+
162
+ /** The query as the cache and the browser key it: trimmed, lowercased, one space between words. */
163
+ export const normalizeQuery = (query: string): string => query.trim().toLowerCase().replace(/\s+/g, ' ');
164
+
165
+ const STOP = new Set(
166
+ 'a an and are as at be by for from how in is it of on or that the this to was what when where which who why with my me i'.split(' '),
167
+ );
168
+
169
+ /** A word's search form: lowercased, a plural's `s` taken off (`apps` finds `app`, `costs` finds `cost`). */
170
+ const stem = (word: string): string => (word.length > 3 && word.endsWith('s') && !word.endsWith('ss') ? word.slice(0, -1) : word);
171
+
172
+ /** The words of a text, with where each sits — for the index and for marking a snippet. */
173
+ function words(text: string): { term: string; start: number; end: number }[] {
174
+ const out: { term: string; start: number; end: number }[] = [];
175
+ for (const m of text.matchAll(/[\p{L}\p{N}]+/gu)) {
176
+ const raw = m[0].toLowerCase();
177
+ if (STOP.has(raw)) continue;
178
+ out.push({ term: stem(raw), start: m.index ?? 0, end: (m.index ?? 0) + m[0].length });
179
+ }
180
+ return out;
181
+ }
182
+
183
+ /** The search terms of a text. */
184
+ export const tokenize = (text: string): string[] => words(text).map((w) => w.term);
185
+
186
+ /** The text a place is embedded and reranked as: what it is called, where it sits, what it shows. */
187
+ export function placeDocument(p: MeaningPlace): string {
188
+ const f = p.facets;
189
+ return [
190
+ `${p.title} — ${p.crumbs.join(' › ')}`,
191
+ p.about,
192
+ [...f.subject, ...f.measure, ...f.breakdown].join(', '),
193
+ ]
194
+ .filter(Boolean)
195
+ .join('\n');
196
+ }
197
+
198
+ /** Field weights for BM25F: a word in the title says more than one in the sentence about it. */
199
+ const FIELD_WEIGHT = { title: 3, crumbs: 1.5, facets: 2, about: 1 } as const;
200
+
201
+ /**
202
+ * BM25F over a place's title, crumbs, facets and `about`, so `R2`, `D1`, `B2` and an app's name
203
+ * match exactly — the case the embedder blurs. Built once per corpus.
204
+ */
205
+ export function createLexicalIndex(places: readonly MeaningPlace[]): { search(query: string, limit?: number): { id: string; score: number }[] } {
206
+ const k1 = 1.2;
207
+ const b = 0.75;
208
+ const docs = places.map((p) => {
209
+ const tf = new Map<string, number>();
210
+ let length = 0;
211
+ const add = (text: string, weight: number) => {
212
+ for (const t of tokenize(text)) {
213
+ tf.set(t, (tf.get(t) ?? 0) + weight);
214
+ length += weight;
215
+ }
216
+ };
217
+ add(p.title, FIELD_WEIGHT.title);
218
+ add(p.crumbs.join(' '), FIELD_WEIGHT.crumbs);
219
+ add([...p.facets.subject, ...p.facets.measure, ...p.facets.breakdown].join(' '), FIELD_WEIGHT.facets);
220
+ add(p.about, FIELD_WEIGHT.about);
221
+ return { id: p.id, tf, length };
222
+ });
223
+ const avg = docs.reduce((n, d) => n + d.length, 0) / Math.max(1, docs.length);
224
+ const df = new Map<string, number>();
225
+ for (const d of docs) for (const t of d.tf.keys()) df.set(t, (df.get(t) ?? 0) + 1);
226
+ const idf = (t: string) => {
227
+ const n = df.get(t) ?? 0;
228
+ return Math.log(1 + (docs.length - n + 0.5) / (n + 0.5));
229
+ };
230
+ return {
231
+ search(query, limit = 30) {
232
+ const terms = [...new Set(tokenize(query))];
233
+ if (terms.length === 0) return [];
234
+ return docs
235
+ .map((d) => {
236
+ let score = 0;
237
+ for (const t of terms) {
238
+ const f = d.tf.get(t);
239
+ if (!f) continue;
240
+ score += idf(t) * ((f * (k1 + 1)) / (f + k1 * (1 - b + (b * d.length) / avg)));
241
+ }
242
+ return { id: d.id, score };
243
+ })
244
+ .filter((r) => r.score > 0)
245
+ .sort((x, y) => y.score - x.score)
246
+ .slice(0, limit);
247
+ },
248
+ };
249
+ }
250
+
251
+ /** A vector scaled to length 1, so a dot product is the cosine. */
252
+ export function unit(vector: ArrayLike<number>): Float32Array {
253
+ const out = Float32Array.from(vector as ArrayLike<number>);
254
+ let n = 0;
255
+ for (const x of out) n += x * x;
256
+ const len = Math.sqrt(n) || 1;
257
+ for (let i = 0; i < out.length; i++) out[i] = (out[i] as number) / len;
258
+ return out;
259
+ }
260
+
261
+ /** The `k` nearest vectors by cosine — a scan, which for hundreds of places is microseconds. */
262
+ export function cosineTopK(query: ArrayLike<number>, vectors: ReadonlyMap<string, Float32Array>, k = 30): { id: string; score: number }[] {
263
+ const q = unit(query);
264
+ const out: { id: string; score: number }[] = [];
265
+ for (const [id, v] of vectors) {
266
+ let dot = 0;
267
+ const n = Math.min(q.length, v.length);
268
+ for (let i = 0; i < n; i++) dot += (q[i] as number) * (v[i] as number);
269
+ out.push({ id, score: dot });
270
+ }
271
+ return out.sort((a, b) => b.score - a.score).slice(0, k);
272
+ }
273
+
274
+ /**
275
+ * Why a place was found — derived, never a model's sentence: the query's words it holds (marked
276
+ * where they sit in `about`), or "by meaning" when it holds none, and how sure the engine is.
277
+ */
278
+ export function whyFound(query: string, place: MeaningPlace, band: MeaningBand): MeaningHit {
279
+ const wanted = new Map<string, string>();
280
+ for (const w of words(query)) if (!wanted.has(w.term)) wanted.set(w.term, query.slice(w.start, w.end));
281
+ const fields = new Set(tokenize([place.title, place.crumbs.join(' '), place.about, ...place.facets.subject, ...place.facets.measure, ...place.facets.breakdown].join(' ')));
282
+ const matched = [...wanted].filter(([term]) => fields.has(term)).map(([, surface]) => surface.toLowerCase());
283
+ const marks: [number, number][] = words(place.about)
284
+ .filter((w) => wanted.has(w.term))
285
+ .map((w) => [w.start, w.end]);
286
+ return {
287
+ id: place.id,
288
+ href: place.href,
289
+ title: place.title,
290
+ crumbs: place.crumbs,
291
+ kind: place.kind,
292
+ snippet: { text: place.about, marks },
293
+ why: { words: matched, byMeaning: matched.length === 0 },
294
+ band,
295
+ };
296
+ }
297
+
298
+ /** A SHA-256, hex — Web Crypto, so the same in a Worker and in Bun. */
299
+ async function sha256(text: string): Promise<string> {
300
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
301
+ return [...new Uint8Array(digest)].map((x) => x.toString(16).padStart(2, '0')).join('');
302
+ }
303
+
304
+ /** What a document's vector is stored under: its text and the model that read it, so a change in either re-embeds it. */
305
+ export const documentHash = (document: string, model = EMBED_MODEL): Promise<string> => sha256(`${model}\n${document}`);
306
+
307
+ /** The cache's key: the query as normalized, under the corpus's version. */
308
+ export const meaningCacheKey = (query: string, version: string): string => `${version.slice(0, 16)}:${normalizeQuery(query)}`;
309
+
310
+ /** Where vectors and rankings rest — {@link d1MeaningStore} for D1, or anything with these four. */
311
+ export interface MeaningStore {
312
+ readVectors(hashes: readonly string[]): Promise<Map<string, Float32Array>>;
313
+ writeVectors(rows: readonly { hash: string; vector: Float32Array }[]): Promise<void>;
314
+ readAnswer(key: string, notBefore: number): Promise<MeaningHit[] | null>;
315
+ writeAnswer(key: string, hits: readonly MeaningHit[], at: number): Promise<void>;
316
+ /** The teardown: drop every ranking stored before `before`. Returns how many went. */
317
+ expireAnswers(before: number): Promise<number>;
318
+ }
319
+
320
+ /** The models, as a Workers AI binding (`env.AI`) offers them. */
321
+ export interface MeaningAi {
322
+ run(model: string, input: unknown): Promise<unknown>;
323
+ }
324
+
325
+ export interface MeaningSearchOptions {
326
+ places: readonly MeaningPlace[];
327
+ store: MeaningStore;
328
+ ai: MeaningAi;
329
+ /** Hits shown. Default 12. */
330
+ limit?: number;
331
+ now?: () => number;
332
+ rerankTimeoutMs?: number;
333
+ /** Told when the reranker fails or is slow (the fused order is shown either way). */
334
+ onRerankError?: (error: unknown) => void;
335
+ }
336
+
337
+ const DAY_MS = 86_400_000;
338
+ /** How many documents one embedding call carries. */
339
+ const EMBED_BATCH = 50;
340
+
341
+ function vectorsOf(result: unknown, count: number): number[][] {
342
+ const data = (result as { data?: unknown } | null)?.data;
343
+ if (!Array.isArray(data) || data.length !== count) throw new Error(`${EMBED_MODEL} answered ${Array.isArray(data) ? data.length : 'no'} vectors for ${count} texts`);
344
+ for (const row of data)
345
+ if (!Array.isArray(row) || row.length !== EMBED_DIMS) throw new Error(`${EMBED_MODEL} answered a vector of ${Array.isArray(row) ? row.length : 'no'} dimensions, not ${EMBED_DIMS}`);
346
+ return data as number[][];
347
+ }
348
+
349
+ /**
350
+ * The engine over a small corpus. One per isolate: the places' vectors are read (or embedded, once
351
+ * per changed document) on the first search and kept in memory after it.
352
+ */
353
+ export function createMeaningSearch(options: MeaningSearchOptions) {
354
+ const { places, store, ai } = options;
355
+ const limit = options.limit ?? 12;
356
+ const now = options.now ?? Date.now;
357
+ const byId = new Map(places.map((p) => [p.id, p]));
358
+ if (byId.size !== places.length) throw new Error('two meaning places share an id');
359
+ const lexical = createLexicalIndex(places);
360
+ const documents = places.map(placeDocument);
361
+ let ready: Promise<{ version: string; vectors: Map<string, Float32Array> }> | null = null;
362
+
363
+ const embed = async (texts: readonly string[]): Promise<number[][]> => {
364
+ const out: number[][] = [];
365
+ for (let i = 0; i < texts.length; i += EMBED_BATCH) {
366
+ const batch = texts.slice(i, i + EMBED_BATCH);
367
+ out.push(...vectorsOf(await ai.run(EMBED_MODEL, { text: batch }), batch.length));
368
+ }
369
+ return out;
370
+ };
371
+
372
+ /** The corpus's version, and every place's vector — read from the store, the missing embedded and written back. */
373
+ const index = () => {
374
+ ready ??= (async () => {
375
+ const hashes = await Promise.all(documents.map((d) => documentHash(d)));
376
+ const version = await sha256(`${EMBED_MODEL}\n${RERANK_MODEL}\n${hashes.join('\n')}`);
377
+ const stored = await store.readVectors(hashes);
378
+ const missing = hashes.map((h, i) => ({ h, i })).filter(({ h }) => !stored.has(h));
379
+ if (missing.length > 0) {
380
+ const fresh = await embed(missing.map(({ i }) => documents[i] as string));
381
+ const rows = missing.map(({ h }, j) => ({ hash: h, vector: unit(fresh[j] as number[]) }));
382
+ await store.writeVectors(rows);
383
+ for (const r of rows) stored.set(r.hash, r.vector);
384
+ }
385
+ const vectors = new Map<string, Float32Array>();
386
+ for (const [i, p] of places.entries()) vectors.set(p.id, stored.get(hashes[i] as string) as Float32Array);
387
+ return { version, vectors };
388
+ })().catch((error: unknown) => {
389
+ ready = null; // the next search tries again
390
+ throw error;
391
+ });
392
+ return ready;
393
+ };
394
+
395
+ return {
396
+ /** The corpus's version (embedding whatever changed, the first time). */
397
+ version: async () => (await index()).version,
398
+
399
+ async search(query: string): Promise<MeaningAnswer> {
400
+ const started = now();
401
+ const q = normalizeQuery(query);
402
+ const { version, vectors } = await index();
403
+ const empty = { query: q, version, hits: [], cached: false, reranked: false };
404
+ if (tokenize(q).length === 0 && q.length < 2) return { ...empty, tookMs: now() - started };
405
+ const key = meaningCacheKey(q, version);
406
+ const kept = await store.readAnswer(key, started - MEANING_CACHE_DAYS * DAY_MS);
407
+ if (kept) return { query: q, version, hits: kept, cached: true, reranked: true, tookMs: now() - started };
408
+
409
+ const words = lexical.search(q).map((r) => r.id);
410
+ const [qv] = await embed([q]);
411
+ const meaning = cosineTopK(qv as number[], vectors).map((r) => r.id);
412
+ const both = new Set(words.filter((id) => meaning.slice(0, 10).includes(id)));
413
+ const fused = fuse([words, meaning]);
414
+
415
+ let reranked = false;
416
+ let order = fused.slice(0, limit);
417
+ let bands = new Map(order.map((id, i) => [id, (both.has(id) || (i < 3 && words.includes(id)) ? 'likely' : 'loose') as MeaningBand]));
418
+ const head = fused.slice(0, 30);
419
+ try {
420
+ const result = await withinMs(ai.run(RERANK_MODEL, rerankInput(q, head.map((id) => placeDocument(byId.get(id) as MeaningPlace)))), options.rerankTimeoutMs ?? RERANK_TIMEOUT_MS, RERANK_MODEL);
421
+ const scores = rerankScores(result, head.length);
422
+ const score = new Map(head.map((id, i) => [id, scores[i] ?? 0]));
423
+ // A palette shows matches only: a near-miss is dropped, not trailed.
424
+ order = rerankOrder(head, head, scores).order.slice(0, limit);
425
+ bands = new Map(order.map((id) => [id, bandFor(score.get(id) ?? 0)]));
426
+ reranked = true;
427
+ } catch (error) {
428
+ options.onRerankError?.(error);
429
+ }
430
+ const hits = order.map((id) => whyFound(q, byId.get(id) as MeaningPlace, bands.get(id) ?? 'loose'));
431
+ // Only a reranked answer is kept: a fused one is the degraded shape, and the next search may do better.
432
+ if (reranked) await store.writeAnswer(key, hits, started);
433
+ return { query: q, version, hits, cached: false, reranked, tookMs: now() - started };
434
+ },
435
+
436
+ /** The timer's teardown: rankings older than {@link MEANING_CACHE_DAYS} go. */
437
+ expire: (): Promise<number> => store.expireAnswers(now() - MEANING_CACHE_DAYS * DAY_MS),
438
+ };
439
+ }
440
+
441
+ // ── D1 ───────────────────────────────────────────────────────────────────────────────────────
442
+
443
+ /** The two tables a D1 store needs — run it from the app's own schema/migration. */
444
+ export const MEANING_D1_DDL = `CREATE TABLE IF NOT EXISTS meaning_vectors (
445
+ hash TEXT PRIMARY KEY,
446
+ vector TEXT NOT NULL,
447
+ created_at INTEGER NOT NULL
448
+ );
449
+ CREATE TABLE IF NOT EXISTS meaning_answers (
450
+ key TEXT PRIMARY KEY,
451
+ hits TEXT NOT NULL,
452
+ created_at INTEGER NOT NULL
453
+ );
454
+ CREATE INDEX IF NOT EXISTS meaning_answers_created ON meaning_answers (created_at);`;
455
+
456
+ /** What a D1 statement resolves with — Cloudflare's `D1Result`, as loosely as the binding types it. */
457
+ interface MeaningD1Result {
458
+ results?: unknown[];
459
+ success?: boolean;
460
+ error?: string;
461
+ meta?: { changes?: number };
462
+ }
463
+
464
+ /** The slice of a D1 binding the store calls (cursedbelt-server's `D1BindingLike` satisfies it). */
465
+ export interface MeaningD1 {
466
+ prepare(sql: string): {
467
+ bind(...values: unknown[]): { all(): Promise<MeaningD1Result>; run(): Promise<MeaningD1Result> };
468
+ };
469
+ }
470
+
471
+ /** D1 can RESOLVE a failed statement with `success: false` (`../d1/remote.ts`): a silent no-op is an error. */
472
+ const settled = (r: MeaningD1Result, what: string): MeaningD1Result => {
473
+ if (r.success === false || r.error) throw new Error(`meaning: D1 refused ${what}: ${r.error ?? 'success: false'}`);
474
+ return r;
475
+ };
476
+ const rowsOf = <T>(r: MeaningD1Result, what: string): T[] => (settled(r, what).results ?? []) as T[];
477
+
478
+ const toBase64 = (v: Float32Array): string => {
479
+ const bytes = new Uint8Array(v.buffer, v.byteOffset, v.byteLength);
480
+ let s = '';
481
+ for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
482
+ return btoa(s);
483
+ };
484
+ const fromBase64 = (s: string): Float32Array => {
485
+ const bin = atob(s);
486
+ const bytes = new Uint8Array(bin.length);
487
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
488
+ return new Float32Array(bytes.buffer);
489
+ };
490
+
491
+ /** A {@link MeaningStore} over D1 ({@link MEANING_D1_DDL}): a vector is 4 KiB of float32 as base64. */
492
+ export function d1MeaningStore(db: MeaningD1): MeaningStore {
493
+ return {
494
+ async readVectors(hashes) {
495
+ const out = new Map<string, Float32Array>();
496
+ if (hashes.length === 0) return out;
497
+ const read = await db.prepare('SELECT hash, vector FROM meaning_vectors WHERE hash IN (SELECT value FROM json_each(?))').bind(JSON.stringify(hashes)).all();
498
+ for (const r of rowsOf<{ hash: string; vector: string }>(read, 'the vector read')) out.set(r.hash, fromBase64(r.vector));
499
+ return out;
500
+ },
501
+ async writeVectors(rows) {
502
+ if (rows.length === 0) return;
503
+ const at = Date.now();
504
+ const wrote = await db
505
+ .prepare(
506
+ "INSERT INTO meaning_vectors (hash, vector, created_at) SELECT json_extract(value, '$.h'), json_extract(value, '$.v'), ? FROM json_each(?) WHERE true ON CONFLICT (hash) DO NOTHING",
507
+ )
508
+ .bind(at, JSON.stringify(rows.map((r) => ({ h: r.hash, v: toBase64(r.vector) }))))
509
+ .run();
510
+ settled(wrote, 'the vector write');
511
+ },
512
+ async readAnswer(key, notBefore) {
513
+ const read = await db.prepare('SELECT hits FROM meaning_answers WHERE key = ? AND created_at >= ?').bind(key, notBefore).all();
514
+ const row = rowsOf<{ hits: string }>(read, 'the answer read')[0];
515
+ return row ? (JSON.parse(row.hits) as MeaningHit[]) : null;
516
+ },
517
+ async writeAnswer(key, hits, at) {
518
+ const wrote = await db
519
+ .prepare('INSERT INTO meaning_answers (key, hits, created_at) VALUES (?, ?, ?) ON CONFLICT (key) DO UPDATE SET hits = excluded.hits, created_at = excluded.created_at')
520
+ .bind(key, JSON.stringify(hits), at)
521
+ .run();
522
+ settled(wrote, 'the answer write');
523
+ },
524
+ async expireAnswers(before) {
525
+ const r = settled(await db.prepare('DELETE FROM meaning_answers WHERE created_at < ?').bind(before).run(), 'the expiry');
526
+ return r.meta?.changes ?? 0;
527
+ },
528
+ };
529
+ }