@agency-lang/memento 0.0.0-stage → 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 (64) hide show
  1. package/README.md +64 -2
  2. package/dist/agency/embed.d.ts +22 -0
  3. package/dist/agency/embed.js +458 -0
  4. package/dist/agencyApi.d.ts +98 -0
  5. package/dist/agencyApi.js +237 -0
  6. package/dist/embed.d.ts +45 -0
  7. package/dist/embed.js +77 -0
  8. package/dist/engine/files/engine.d.ts +85 -0
  9. package/dist/engine/files/engine.js +284 -0
  10. package/dist/engine/files/lock.d.ts +18 -0
  11. package/dist/engine/files/lock.js +247 -0
  12. package/dist/engine/files/manifest.d.ts +43 -0
  13. package/dist/engine/files/manifest.js +111 -0
  14. package/dist/engine/files/safe-delete.d.ts +19 -0
  15. package/dist/engine/files/safe-delete.js +79 -0
  16. package/dist/engine/files/segments.d.ts +17 -0
  17. package/dist/engine/files/segments.js +128 -0
  18. package/dist/engine/memory/engine.d.ts +27 -0
  19. package/dist/engine/memory/engine.js +87 -0
  20. package/dist/engine/open.d.ts +7 -0
  21. package/dist/engine/open.js +28 -0
  22. package/dist/engine/shared/filter.d.ts +7 -0
  23. package/dist/engine/shared/filter.js +72 -0
  24. package/dist/engine/shared/keyword.d.ts +27 -0
  25. package/dist/engine/shared/keyword.js +92 -0
  26. package/dist/engine/shared/settings.d.ts +5 -0
  27. package/dist/engine/shared/settings.js +9 -0
  28. package/dist/engine/shared/state.d.ts +58 -0
  29. package/dist/engine/shared/state.js +275 -0
  30. package/dist/engine/shared/tokens.d.ts +15 -0
  31. package/dist/engine/shared/tokens.js +23 -0
  32. package/dist/engine/shared/vectors.d.ts +36 -0
  33. package/dist/engine/shared/vectors.js +70 -0
  34. package/dist/engine/types.d.ts +121 -0
  35. package/dist/engine/types.js +1 -0
  36. package/dist/files.d.ts +75 -0
  37. package/dist/files.js +190 -0
  38. package/dist/filter.d.ts +3 -0
  39. package/dist/filter.js +80 -0
  40. package/dist/fusion.d.ts +24 -0
  41. package/dist/fusion.js +26 -0
  42. package/dist/ids.d.ts +2 -0
  43. package/dist/ids.js +19 -0
  44. package/dist/index.d.ts +4 -0
  45. package/dist/index.js +3 -0
  46. package/dist/local.d.ts +36 -0
  47. package/dist/local.js +75 -0
  48. package/dist/memento.d.ts +151 -0
  49. package/dist/memento.js +470 -0
  50. package/dist/query.d.ts +50 -0
  51. package/dist/query.js +138 -0
  52. package/dist/rows.d.ts +17 -0
  53. package/dist/rows.js +90 -0
  54. package/dist/stem.d.ts +2 -0
  55. package/dist/stem.js +121 -0
  56. package/dist/types.d.ts +246 -0
  57. package/dist/types.js +3 -0
  58. package/dist/vectors.d.ts +2 -0
  59. package/dist/vectors.js +10 -0
  60. package/dist/windows.d.ts +44 -0
  61. package/dist/windows.js +77 -0
  62. package/index.agency +268 -0
  63. package/index.js +1803 -0
  64. package/package.json +55 -4
@@ -0,0 +1,92 @@
1
+ // The keyword index the memory and files engines search: postings per stem
2
+ // and BM25 scoring, computed the way the package's earlier engine ranked, so
3
+ // the recorded eval numbers stay comparable. The weighted counts are added
4
+ // across the columns first and the saturation is applied once, with the
5
+ // length of the whole row. Each query term scores as given: two terms that
6
+ // stem alike both count, as they did before.
7
+ import { compareCodePoints } from "../../ids.js";
8
+ import { foldWord } from "../../query.js";
9
+ import { stem } from "../../stem.js";
10
+ import { stemsIn } from "./tokens.js";
11
+ /** BM25 weight of a match in the title, relative to TEXT_WEIGHT. */
12
+ export const TITLE_WEIGHT = 2.0;
13
+ export const TEXT_WEIGHT = 1.0;
14
+ /** BM25's saturation constant. */
15
+ const K1 = 1.2;
16
+ /** BM25's length normalisation constant. */
17
+ const B = 0.75;
18
+ /** An idf of zero or less, for a term in half the documents or more, is replaced by this, as the earlier engine did. */
19
+ const IDF_FLOOR = 1e-6;
20
+ export class KeywordIndex {
21
+ postings = Object.create(null);
22
+ tokens = Object.create(null);
23
+ documents = 0;
24
+ totalLength = 0;
25
+ /** Indexes a document that is not in the index. A replaced document is removed first. */
26
+ add(id, tokens) {
27
+ if (Object.hasOwn(this.tokens, id)) {
28
+ throw new Error(`document "${id}" is already indexed`);
29
+ }
30
+ this.tokens[id] = tokens;
31
+ this.documents += 1;
32
+ this.totalLength += tokens.titleLength + tokens.textLength;
33
+ for (const one of stemsIn(tokens)) {
34
+ const posting = (this.postings[one] ??= { documents: 0, byId: Object.create(null) });
35
+ posting.byId[id] = { title: tokens.title[one] ?? 0, text: tokens.text[one] ?? 0 };
36
+ posting.documents += 1;
37
+ }
38
+ }
39
+ /** Removes a document from the index. A document that is not indexed is left alone. */
40
+ remove(id) {
41
+ if (!Object.hasOwn(this.tokens, id)) {
42
+ return;
43
+ }
44
+ const tokens = this.tokens[id];
45
+ delete this.tokens[id];
46
+ this.documents -= 1;
47
+ this.totalLength -= tokens.titleLength + tokens.textLength;
48
+ for (const one of stemsIn(tokens)) {
49
+ const posting = this.postings[one];
50
+ delete posting.byId[id];
51
+ posting.documents -= 1;
52
+ // The count, not Object.keys, so a remove costs the document's own stems and not every document that shares them.
53
+ if (posting.documents === 0) {
54
+ delete this.postings[one];
55
+ }
56
+ }
57
+ }
58
+ has(id) {
59
+ return Object.hasOwn(this.tokens, id);
60
+ }
61
+ /**
62
+ * The documents matching any term, best first, after `allowed`, at most
63
+ * `limit`. Equal scores order by id in code point order before the limit.
64
+ */
65
+ search(terms, allowed, limit) {
66
+ const scores = Object.create(null);
67
+ const averageLength = this.documents === 0 ? 0 : this.totalLength / this.documents;
68
+ for (const term of terms) {
69
+ const posting = this.postings[stem(foldWord(term))];
70
+ if (posting === undefined) {
71
+ continue;
72
+ }
73
+ const idf = this.idf(posting.documents);
74
+ for (const [id, counts] of Object.entries(posting.byId)) {
75
+ const weighted = TITLE_WEIGHT * counts.title + TEXT_WEIGHT * counts.text;
76
+ const tokens = this.tokens[id];
77
+ const rowLength = tokens.titleLength + tokens.textLength;
78
+ const saturation = weighted / (weighted + K1 * (1 - B + (B * rowLength) / averageLength));
79
+ scores[id] = (scores[id] ?? 0) + idf * saturation * (K1 + 1);
80
+ }
81
+ }
82
+ return Object.entries(scores)
83
+ .filter(([id]) => allowed === undefined || allowed(id))
84
+ .map(([id, score]) => ({ id, score }))
85
+ .sort((a, b) => b.score - a.score || compareCodePoints(a.id, b.id))
86
+ .slice(0, limit);
87
+ }
88
+ idf(matching) {
89
+ const raw = Math.log((this.documents - matching + 0.5) / (matching + 0.5));
90
+ return Math.max(raw, IDF_FLOOR);
91
+ }
92
+ }
@@ -0,0 +1,5 @@
1
+ import type { StoreSettings } from "../types.ts";
2
+ /** A copy holding only the fields StoreSettings names. */
3
+ export declare function copySettings(settings: StoreSettings): StoreSettings;
4
+ /** The settings with `patch` merged in. A patch with `models` replaces all of them. */
5
+ export declare function mergeSettings(settings: StoreSettings, patch: Partial<StoreSettings>): StoreSettings;
@@ -0,0 +1,9 @@
1
+ /** A copy holding only the fields StoreSettings names. */
2
+ export function copySettings(settings) {
3
+ const { embedding } = settings.models;
4
+ return { models: embedding === undefined ? {} : { embedding }, local: settings.local };
5
+ }
6
+ /** The settings with `patch` merged in. A patch with `models` replaces all of them. */
7
+ export function mergeSettings(settings, patch) {
8
+ return copySettings({ ...settings, ...patch });
9
+ }
@@ -0,0 +1,58 @@
1
+ import type { FileStat } from "../../files.ts";
2
+ import type { Filter } from "../../types.ts";
3
+ import type { DocumentWindows, ScoredDocument, StoredDocument, StoreSettings, WindowHit, WindowWrite, WriteBatch } from "../types.ts";
4
+ import { KeywordIndex } from "./keyword.ts";
5
+ /**
6
+ * One change to the store. A segment of the files store is a list of these,
7
+ * and replay applies them in order: the newest record about an id or a path
8
+ * wins, and a removal drops what came before it.
9
+ */
10
+ export type StoreRecord = {
11
+ kind: "document";
12
+ document: StoredDocument;
13
+ } | {
14
+ kind: "windows";
15
+ id: string;
16
+ windows: WindowWrite[];
17
+ } | {
18
+ kind: "file";
19
+ file: FileStat;
20
+ } | {
21
+ kind: "removeDocuments";
22
+ ids: string[];
23
+ } | {
24
+ kind: "removeFiles";
25
+ paths: string[];
26
+ };
27
+ export declare class StoreState {
28
+ settings: StoreSettings | undefined;
29
+ readonly documents: Record<string, StoredDocument>;
30
+ readonly files: Record<string, FileStat>;
31
+ readonly windows: Record<string, WindowWrite[]>;
32
+ readonly index: KeywordIndex;
33
+ getDocsById(ids: string[]): StoredDocument[];
34
+ getWindows(ids: string[]): DocumentWindows[];
35
+ private windowsOf;
36
+ documentCount(): number;
37
+ fileCount(): number;
38
+ statFiles(paths: string[]): FileStat[];
39
+ /** The length of the vectors the store holds, or undefined when it holds none. */
40
+ dimension(): number | undefined;
41
+ keywordSearch(terms: string[], filter: Filter | undefined, limit: number): ScoredDocument[];
42
+ getNewest(filter: Filter | undefined, limit: number): StoredDocument[];
43
+ embeddingsSearch(query: Float32Array, filter: Filter | undefined, limit: number): WindowHit[];
44
+ /** The filter compiled once, as a test of an id, or undefined when there is no filter. */
45
+ private allowedBy;
46
+ /**
47
+ * The records a batch produces, or a throw, with nothing changed. Later
48
+ * entries see earlier ones, so a repeated id may keep the windows this
49
+ * batch gave it, the first vector sets the reference length for the
50
+ * rest, and a file recorded earlier in the batch is tracked.
51
+ */
52
+ prepare(batch: WriteBatch): StoreRecord[];
53
+ private prepareDocuments;
54
+ /** Applies records that prepare returned, or that a segment holds. Nothing in here can fail. */
55
+ commit(records: StoreRecord[]): void;
56
+ /** Throws when the structures disagree: a window without a document, two vector lengths, a window past its text. */
57
+ check(): void;
58
+ }
@@ -0,0 +1,275 @@
1
+ import { compareCodePoints } from "../../ids.js";
2
+ import { compileMatcher } from "./filter.js";
3
+ import { KeywordIndex } from "./keyword.js";
4
+ import { tokenize } from "./tokens.js";
5
+ import { bestWindows, validateVector } from "./vectors.js";
6
+ /** The stamp a forgotten file gets, so the next load reads it again. */
7
+ const FORGOTTEN_MTIME = -1;
8
+ export class StoreState {
9
+ settings;
10
+ documents = Object.create(null);
11
+ files = Object.create(null);
12
+ windows = Object.create(null);
13
+ index = new KeywordIndex();
14
+ // Reading. Every method returns copies: a caller that changes a Date, a
15
+ // meta object or a vector it was handed must not change the store.
16
+ getDocsById(ids) {
17
+ return [...new Set(ids)].flatMap((id) => (Object.hasOwn(this.documents, id) ? [cloneDocument(this.documents[id])] : []));
18
+ }
19
+ getWindows(ids) {
20
+ return [...new Set(ids)].flatMap((id) => (Object.hasOwn(this.documents, id) ? [{ id, windows: this.windowsOf(id).map(cloneWindow) }] : []));
21
+ }
22
+ windowsOf(id) {
23
+ return Object.hasOwn(this.windows, id) ? this.windows[id] : [];
24
+ }
25
+ documentCount() {
26
+ return Object.keys(this.documents).length;
27
+ }
28
+ fileCount() {
29
+ return Object.keys(this.files).length;
30
+ }
31
+ statFiles(paths) {
32
+ return [...new Set(paths)].flatMap((path) => (Object.hasOwn(this.files, path) ? [{ ...this.files[path] }] : []));
33
+ }
34
+ /** The length of the vectors the store holds, or undefined when it holds none. */
35
+ dimension() {
36
+ for (const windows of Object.values(this.windows)) {
37
+ if (windows.length > 0) {
38
+ return windows[0].vector.length;
39
+ }
40
+ }
41
+ return undefined;
42
+ }
43
+ keywordSearch(terms, filter, limit) {
44
+ const allowed = this.allowedBy(filter);
45
+ return this.index.search(terms, allowed, limit).map(({ id, score }) => ({ document: cloneDocument(this.documents[id]), score }));
46
+ }
47
+ getNewest(filter, limit) {
48
+ const matches = compileMatcher(filter);
49
+ return Object.values(this.documents)
50
+ .filter(matches)
51
+ .sort(compareNewest)
52
+ .slice(0, limit)
53
+ .map(cloneDocument);
54
+ }
55
+ embeddingsSearch(query, filter, limit) {
56
+ const entries = Object.entries(this.windows).map(([id, windows]) => ({ id, windows }));
57
+ return bestWindows(entries, query, this.dimension(), this.allowedBy(filter), limit).map((hit) => ({
58
+ document: cloneDocument(this.documents[hit.id]),
59
+ score: hit.score,
60
+ window: hit.window,
61
+ }));
62
+ }
63
+ /** The filter compiled once, as a test of an id, or undefined when there is no filter. */
64
+ allowedBy(filter) {
65
+ if (filter === undefined) {
66
+ return undefined;
67
+ }
68
+ const matches = compileMatcher(filter);
69
+ return (id) => matches(this.documents[id]);
70
+ }
71
+ // Writing
72
+ /**
73
+ * The records a batch produces, or a throw, with nothing changed. Later
74
+ * entries see earlier ones, so a repeated id may keep the windows this
75
+ * batch gave it, the first vector sets the reference length for the
76
+ * rest, and a file recorded earlier in the batch is tracked.
77
+ */
78
+ prepare(batch) {
79
+ const view = new BatchView(this);
80
+ switch (batch.kind) {
81
+ case "upsert":
82
+ this.prepareDocuments(view, batch.documents);
83
+ return view.records;
84
+ case "replaceFiles": {
85
+ for (const file of batch.files) {
86
+ view.recordFile(file);
87
+ }
88
+ this.prepareDocuments(view, batch.documents);
89
+ const kept = new Set(batch.documents.map((write) => write.document.id));
90
+ const paths = new Set(batch.files.map((file) => file.path));
91
+ const gone = Object.values(this.documents)
92
+ .filter((doc) => doc.sourcePath !== undefined && paths.has(doc.sourcePath) && !kept.has(doc.id))
93
+ .map((doc) => doc.id);
94
+ view.removeDocuments(gone);
95
+ return view.records;
96
+ }
97
+ case "remove":
98
+ view.removeDocuments(batch.ids.filter((id) => Object.hasOwn(this.documents, id)));
99
+ return view.records;
100
+ case "keepOnlyFiles": {
101
+ const keep = new Set(batch.paths);
102
+ const gone = Object.values(this.documents)
103
+ .filter((doc) => doc.sourcePath !== undefined && !keep.has(doc.sourcePath))
104
+ .map((doc) => doc.id);
105
+ view.removeDocuments(gone);
106
+ view.removeFiles(Object.keys(this.files).filter((path) => !keep.has(path)));
107
+ return view.records;
108
+ }
109
+ case "forgetFileStamps":
110
+ for (const path of batch.paths) {
111
+ if (Object.hasOwn(this.files, path)) {
112
+ view.recordFile({ ...this.files[path], mtime: FORGOTTEN_MTIME });
113
+ }
114
+ }
115
+ return view.records;
116
+ }
117
+ }
118
+ prepareDocuments(view, writes) {
119
+ for (const write of writes) {
120
+ const { document, windows } = write;
121
+ if (windows === "keep" && !view.hasDocument(document.id)) {
122
+ throw new Error(`document "${document.id}" is new and has no windows to keep`);
123
+ }
124
+ if (document.sourcePath !== undefined && !view.hasFile(document.sourcePath)) {
125
+ throw new Error(`document "${document.id}" comes from ${document.sourcePath}, which the store does not track`);
126
+ }
127
+ view.recordDocument(cloneDocument(document));
128
+ if (windows !== "keep") {
129
+ const seen = new Set();
130
+ for (const window of windows) {
131
+ if (seen.has(window.n)) {
132
+ throw new Error(`document "${document.id}": window ${window.n} is given twice`);
133
+ }
134
+ seen.add(window.n);
135
+ validateVector(window, view.dimension);
136
+ view.dimension = window.vector.length;
137
+ }
138
+ view.recordWindows(document.id, windows.map(cloneWindow));
139
+ }
140
+ }
141
+ }
142
+ /** Applies records that prepare returned, or that a segment holds. Nothing in here can fail. */
143
+ commit(records) {
144
+ for (const record of records) {
145
+ switch (record.kind) {
146
+ case "document":
147
+ this.index.remove(record.document.id);
148
+ this.documents[record.document.id] = record.document;
149
+ this.index.add(record.document.id, tokenize(record.document));
150
+ break;
151
+ case "windows":
152
+ this.windows[record.id] = record.windows;
153
+ break;
154
+ case "file":
155
+ this.files[record.file.path] = { ...record.file };
156
+ break;
157
+ case "removeDocuments":
158
+ for (const id of record.ids) {
159
+ this.index.remove(id);
160
+ delete this.documents[id];
161
+ delete this.windows[id];
162
+ }
163
+ break;
164
+ case "removeFiles":
165
+ for (const path of record.paths) {
166
+ delete this.files[path];
167
+ }
168
+ break;
169
+ }
170
+ }
171
+ }
172
+ /** Throws when the structures disagree: a window without a document, two vector lengths, a window past its text. */
173
+ check() {
174
+ let dimension;
175
+ for (const [id, windows] of Object.entries(this.windows)) {
176
+ if (!Object.hasOwn(this.documents, id)) {
177
+ throw new Error(`windows of "${id}" belong to no document`);
178
+ }
179
+ const length = this.documents[id].text.length;
180
+ for (const window of windows) {
181
+ if (window.end > length) {
182
+ throw new Error(`window ${window.n} of "${id}" ends past its document's text`);
183
+ }
184
+ if (dimension !== undefined && window.vector.length !== dimension) {
185
+ throw new Error("the store holds vectors of different lengths");
186
+ }
187
+ dimension = window.vector.length;
188
+ }
189
+ }
190
+ for (const id of Object.keys(this.documents)) {
191
+ if (!this.index.has(id)) {
192
+ throw new Error(`document "${id}" is not in the keyword index`);
193
+ }
194
+ }
195
+ }
196
+ }
197
+ /** A copy the caller may change: the Date, the meta and the strings are new; a document comes in and goes out through this. */
198
+ function cloneDocument(doc) {
199
+ const copy = { id: doc.id, title: doc.title, text: doc.text, meta: structuredClone(doc.meta ?? {}) };
200
+ if (doc.createdAt !== undefined) {
201
+ copy.createdAt = new Date(doc.createdAt.getTime());
202
+ }
203
+ if (doc.sourcePath !== undefined) {
204
+ copy.sourcePath = doc.sourcePath;
205
+ }
206
+ return copy;
207
+ }
208
+ function cloneWindow(window) {
209
+ return { n: window.n, start: window.start, end: window.end, vector: Float32Array.from(window.vector) };
210
+ }
211
+ /** Newest first, documents without a date last, then by id. */
212
+ function compareNewest(a, b) {
213
+ const aTime = a.createdAt?.getTime();
214
+ const bTime = b.createdAt?.getTime();
215
+ if (aTime !== bTime) {
216
+ if (aTime === undefined) {
217
+ return 1;
218
+ }
219
+ if (bTime === undefined) {
220
+ return -1;
221
+ }
222
+ return bTime - aTime;
223
+ }
224
+ return compareCodePoints(a.id, b.id);
225
+ }
226
+ /**
227
+ * The state as the batch has changed it so far, for prepare: the records
228
+ * produced, and what they say about which documents and files exist.
229
+ */
230
+ class BatchView {
231
+ records = [];
232
+ dimension;
233
+ state;
234
+ documentsSeen = Object.create(null);
235
+ filesSeen = Object.create(null);
236
+ constructor(state) {
237
+ this.state = state;
238
+ this.dimension = state.dimension();
239
+ }
240
+ hasDocument(id) {
241
+ return Object.hasOwn(this.documentsSeen, id) ? this.documentsSeen[id] : Object.hasOwn(this.state.documents, id);
242
+ }
243
+ hasFile(path) {
244
+ return Object.hasOwn(this.filesSeen, path) ? this.filesSeen[path] : Object.hasOwn(this.state.files, path);
245
+ }
246
+ recordDocument(document) {
247
+ this.records.push({ kind: "document", document });
248
+ this.documentsSeen[document.id] = true;
249
+ }
250
+ recordWindows(id, windows) {
251
+ this.records.push({ kind: "windows", id, windows });
252
+ }
253
+ recordFile(file) {
254
+ this.records.push({ kind: "file", file });
255
+ this.filesSeen[file.path] = true;
256
+ }
257
+ removeDocuments(ids) {
258
+ if (ids.length === 0) {
259
+ return;
260
+ }
261
+ this.records.push({ kind: "removeDocuments", ids });
262
+ for (const id of ids) {
263
+ this.documentsSeen[id] = false;
264
+ }
265
+ }
266
+ removeFiles(paths) {
267
+ if (paths.length === 0) {
268
+ return;
269
+ }
270
+ this.records.push({ kind: "removeFiles", paths });
271
+ for (const path of paths) {
272
+ this.filesSeen[path] = false;
273
+ }
274
+ }
275
+ }
@@ -0,0 +1,15 @@
1
+ /** How often each stem occurs in one column. A null prototype, so a stem such as "constructor" is an ordinary key. */
2
+ export type StemCounts = Record<string, number>;
3
+ /** One document's tokens: the counts per column, and each column's length in tokens. */
4
+ export type DocumentTokens = {
5
+ title: StemCounts;
6
+ text: StemCounts;
7
+ titleLength: number;
8
+ textLength: number;
9
+ };
10
+ export declare function tokenize(doc: {
11
+ title: string;
12
+ text: string;
13
+ }): DocumentTokens;
14
+ /** The stems a document holds in either column, once each. */
15
+ export declare function stemsIn(tokens: DocumentTokens): string[];
@@ -0,0 +1,23 @@
1
+ // The tokenizer the memory and files engines index with: every word of a
2
+ // text as its stem, counted per column. The rule is the package's own,
3
+ // stemsOf in src/query.ts, so what the index matched is what the excerpt
4
+ // highlights. Every token counts, stop words and one-letter words included;
5
+ // the stop list in src/query.ts is for questions only.
6
+ import { stemsOf } from "../../query.js";
7
+ export function tokenize(doc) {
8
+ const title = countStems(doc.title);
9
+ const text = countStems(doc.text);
10
+ return { title: title.counts, text: text.counts, titleLength: title.length, textLength: text.length };
11
+ }
12
+ function countStems(text) {
13
+ const counts = Object.create(null);
14
+ const stems = stemsOf(text);
15
+ for (const { stem } of stems) {
16
+ counts[stem] = (counts[stem] ?? 0) + 1;
17
+ }
18
+ return { counts, length: stems.length };
19
+ }
20
+ /** The stems a document holds in either column, once each. */
21
+ export function stemsIn(tokens) {
22
+ return [...new Set([...Object.keys(tokens.title), ...Object.keys(tokens.text)])];
23
+ }
@@ -0,0 +1,36 @@
1
+ import type { Window, WindowWrite } from "../types.ts";
2
+ /** How far a vector's length may be from 1. Float32 rounding keeps a 1,536-number unit vector within about 1e-6. */
3
+ export declare const UNIT_LENGTH_TOLERANCE = 0.001;
4
+ /** A window as stored, as the scan reports it. */
5
+ export type ScoredWindow = {
6
+ id: string;
7
+ window: Window;
8
+ score: number;
9
+ };
10
+ /** The vector's bytes, in the platform's byte order, which is little-endian on every machine Memento runs on. */
11
+ export declare function encodeVector(vector: Float32Array): Uint8Array;
12
+ /** A copy, so the floats are aligned whatever offset the bytes came back at. */
13
+ export declare function decodeVector(bytes: Uint8Array): Float32Array;
14
+ export declare function dimensionOfBlob(byteLength: number): number;
15
+ /**
16
+ * Throws when the vector is the wrong length or not unit length. `dimension`
17
+ * is undefined when the store holds no vectors yet. A vector holding NaN or
18
+ * Infinity has a length that is not finite, and the comparison is written
19
+ * so that such a length fails it: `Math.abs(NaN - 1) > tolerance` is false.
20
+ */
21
+ export declare function validateVector(write: WindowWrite, dimension: number | undefined): void;
22
+ export declare function dotProduct(a: Float32Array, b: Float32Array): number;
23
+ /** A document's windows as the scan reads them. */
24
+ export type WindowsOfDocument = {
25
+ id: string;
26
+ windows: WindowWrite[];
27
+ };
28
+ /**
29
+ * Each document's best window by dot product with `query`, best first, at
30
+ * most `limit` documents. Equal scores order by id in code point order
31
+ * before the limit cuts the list, so a tie at the limit goes the same way as
32
+ * in keywordSearch. `allowed` is the filter, or undefined for every document.
33
+ * `dimension` is the store's, so a query of another length is rejected even
34
+ * when the filter lets nothing through.
35
+ */
36
+ export declare function bestWindows(documents: Iterable<WindowsOfDocument>, query: Float32Array, dimension: number | undefined, allowed: ((id: string) => boolean) | undefined, limit: number): ScoredWindow[];
@@ -0,0 +1,70 @@
1
+ // Vectors as the engines keep and scan them: float32 bytes on disk, one
2
+ // Float32Array per window in memory, and an exact scan by dot product.
3
+ import { compareCodePoints } from "../../ids.js";
4
+ const BYTES_PER_FLOAT = 4;
5
+ /** How far a vector's length may be from 1. Float32 rounding keeps a 1,536-number unit vector within about 1e-6. */
6
+ export const UNIT_LENGTH_TOLERANCE = 1e-3;
7
+ /** The vector's bytes, in the platform's byte order, which is little-endian on every machine Memento runs on. */
8
+ export function encodeVector(vector) {
9
+ return new Uint8Array(vector.buffer, vector.byteOffset, vector.byteLength);
10
+ }
11
+ /** A copy, so the floats are aligned whatever offset the bytes came back at. */
12
+ export function decodeVector(bytes) {
13
+ const copy = new Uint8Array(bytes);
14
+ return new Float32Array(copy.buffer, 0, copy.byteLength / BYTES_PER_FLOAT);
15
+ }
16
+ export function dimensionOfBlob(byteLength) {
17
+ return byteLength / BYTES_PER_FLOAT;
18
+ }
19
+ /**
20
+ * Throws when the vector is the wrong length or not unit length. `dimension`
21
+ * is undefined when the store holds no vectors yet. A vector holding NaN or
22
+ * Infinity has a length that is not finite, and the comparison is written
23
+ * so that such a length fails it: `Math.abs(NaN - 1) > tolerance` is false.
24
+ */
25
+ export function validateVector(write, dimension) {
26
+ const { vector } = write;
27
+ if (dimension !== undefined && vector.length !== dimension) {
28
+ throw new Error(`window ${write.n}: vector has ${vector.length} numbers; the store's vectors have ${dimension}`);
29
+ }
30
+ const length = Math.sqrt(vector.reduce((sum, value) => sum + value * value, 0));
31
+ if (!(Math.abs(length - 1) <= UNIT_LENGTH_TOLERANCE)) {
32
+ throw new Error(`window ${write.n}: vector is not unit length (${length})`);
33
+ }
34
+ }
35
+ export function dotProduct(a, b) {
36
+ let sum = 0;
37
+ for (let i = 0; i < a.length; i++) {
38
+ sum += a[i] * b[i];
39
+ }
40
+ return sum;
41
+ }
42
+ /**
43
+ * Each document's best window by dot product with `query`, best first, at
44
+ * most `limit` documents. Equal scores order by id in code point order
45
+ * before the limit cuts the list, so a tie at the limit goes the same way as
46
+ * in keywordSearch. `allowed` is the filter, or undefined for every document.
47
+ * `dimension` is the store's, so a query of another length is rejected even
48
+ * when the filter lets nothing through.
49
+ */
50
+ export function bestWindows(documents, query, dimension, allowed, limit) {
51
+ if (dimension !== undefined && query.length !== dimension) {
52
+ throw new Error(`query vector has ${query.length} numbers; the store's vectors have ${dimension}`);
53
+ }
54
+ const best = [];
55
+ for (const { id, windows } of documents) {
56
+ if (windows.length === 0 || (allowed !== undefined && !allowed(id))) {
57
+ continue;
58
+ }
59
+ let top;
60
+ for (const window of windows) {
61
+ const score = dotProduct(window.vector, query);
62
+ // Equal scores go to the lowest n, whatever order the windows were written in.
63
+ if (top === undefined || score > top.score || (score === top.score && window.n < top.window.n)) {
64
+ top = { id, window: { n: window.n, start: window.start, end: window.end }, score };
65
+ }
66
+ }
67
+ best.push(top);
68
+ }
69
+ return best.sort((a, b) => b.score - a.score || compareCodePoints(a.id, b.id)).slice(0, limit);
70
+ }