@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,151 @@
1
+ import type { Engine } from "./engine/types.ts";
2
+ import { type FileStat } from "./files.ts";
3
+ import type { AddFilesOptions, AddFilesResult, AddOptions, Answer, AskOptions, Document, Hit, OpenOptions, SearchOptions, Stats, Storage, StoreSettings } from "./types.ts";
4
+ /** Documents written per transaction by add, and per onProgress call. */
5
+ export declare const DOCUMENTS_PER_BATCH = 500;
6
+ /** Files read before each write transaction in addFiles. */
7
+ export declare const FILES_PER_BATCH = 100;
8
+ /** How many hits search returns when no limit is given. */
9
+ export declare const DEFAULT_LIMIT = 20;
10
+ /** How many documents each of the keyword list and the embedding list holds before fusion, at least. */
11
+ export declare const CANDIDATES = 100;
12
+ /**
13
+ * What an open does about the embedding model, from the table in
14
+ * docs/dev/package.md: record the given model, embed with the recorded one,
15
+ * run keyword-only, or reject.
16
+ */
17
+ export type OpenPlan = {
18
+ kind: "record";
19
+ } | {
20
+ kind: "embed";
21
+ } | {
22
+ kind: "keyword";
23
+ } | {
24
+ kind: "reject";
25
+ message: string;
26
+ };
27
+ export declare class Memento {
28
+ private readonly engine;
29
+ /** Set when this connection can embed: the store's model was given at open. */
30
+ private readonly embedder;
31
+ /** The chat model this open named. The store does not record it. */
32
+ private readonly chat;
33
+ private constructor();
34
+ /**
35
+ * Opens a store, creating it if it does not exist. One store per
36
+ * collection: the city code, the email, the medical reference.
37
+ */
38
+ static open(store: Storage, options?: OpenOptions): Promise<Memento>;
39
+ /**
40
+ * Whether a store has already been created at `store`. `open` creates a
41
+ * missing files store, so a program that must not start from an empty
42
+ * store checks this first. A memory store never exists before it is opened.
43
+ */
44
+ static exists(store: Storage): Promise<boolean>;
45
+ /**
46
+ * The settings a store records, with the embedding model it was made
47
+ * with, or undefined when there is no store. Loads no documents and
48
+ * creates nothing. A store is written only through a connection opened
49
+ * with its embedding model, so a caller that did not make the store
50
+ * reads the model here before it opens one.
51
+ */
52
+ static settings(store: Storage): Promise<StoreSettings | undefined>;
53
+ /**
54
+ * Indexes documents: keyword index, embeddings, and model-written questions
55
+ * when `enrich` is on. Replaces any document with the same id. May be called
56
+ * any number of times.
57
+ */
58
+ add(documents: Document[], options?: AddOptions): Promise<void>;
59
+ /**
60
+ * A store with a recorded embedding model is written only through a
61
+ * connection that has the model; new documents would otherwise have no
62
+ * vectors. The recorded model is read now and not at open, because
63
+ * another connection can record one after this one opened without it.
64
+ */
65
+ private checkCanWrite;
66
+ private recordedEmbeddingModel;
67
+ /**
68
+ * Each document with what happens to its windows. A document whose title
69
+ * and text are stored unchanged keeps its windows. Any other gets new
70
+ * ones, embedded here, or none when the store has no embedding model or
71
+ * the document is blank. The model calls happen before the write. A
72
+ * document removed between the read of `existing` and the write makes
73
+ * the write reject, because "keep" names a document the engine no longer
74
+ * holds; docs/dev/engine.md has the race.
75
+ */
76
+ private documentWrites;
77
+ /**
78
+ * Reads files matching the globs and indexes them. A file's id is its path,
79
+ * so re-adding a changed file replaces it; unchanged files are skipped.
80
+ * Globs skip dotfiles and dot directories, such as `.git`.
81
+ */
82
+ addFiles(globs: string[], options?: AddFilesOptions): Promise<AddFilesResult>;
83
+ /** Checks that no document's id belongs elsewhere, then writes the batch's files in one write. */
84
+ private writeFiles;
85
+ remove(ids: string[]): Promise<void>;
86
+ /**
87
+ * Finds documents, no answer written. For "every tax document for 2024" and "all my notes on retirement".
88
+ *
89
+ * A query is blank when it is empty after trimming. A blank query returns
90
+ * `[]`, or with a filter the filtered documents newest first, each with
91
+ * score 0. A query of stop words alone, such as "what is it", has no
92
+ * keyword terms: keyword search alone treats it like a blank query, and
93
+ * a search by meaning still runs it.
94
+ */
95
+ search(query: string, options?: SearchOptions): Promise<Hit[]>;
96
+ /** What a query with nothing to search for returns: the filtered documents newest first with score 0, or nothing without a filter. */
97
+ private listNewest;
98
+ /**
99
+ * Both lists, fused by rank. The keyword list is empty for a query of stop
100
+ * words alone. The excerpt comes from the query's words when one is in
101
+ * the text, and from the document's best window otherwise.
102
+ */
103
+ private fusedSearch;
104
+ /**
105
+ * Whether this search uses the embedding model. Unset means "when the
106
+ * store has it and was opened with it"; `true` without it rejects.
107
+ * `useLLM` is checked the same way and is not implemented yet.
108
+ */
109
+ private resolveUseEmbeddings;
110
+ /** Finds documents and writes an answer from them. For "what permits do we need?". Rejects if the open named no chat model. */
111
+ ask(query: string, options?: AskOptions): Promise<Answer>;
112
+ /** Fetch documents by id, in the order asked, one per asked id. Unknown ids are skipped. */
113
+ get(ids: string[]): Promise<Document[]>;
114
+ stats(): Promise<Stats>;
115
+ /** Flush and release the store and any model processes. A second call does nothing. */
116
+ close(): Promise<void>;
117
+ }
118
+ /**
119
+ * One return per row of the open-rules table. `recorded` is the store's
120
+ * embedding model, `given` the one this open names.
121
+ */
122
+ export declare function planOpen(recorded: string | undefined, given: string | undefined, hasDocuments: boolean): OpenPlan;
123
+ /**
124
+ * What `planFiles` found: how many files the globs matched, the ones that
125
+ * changed, and the ones the file system refused. `replaces` counts the
126
+ * changed files the store has loaded before, whose documents a load replaces.
127
+ */
128
+ export type FilesPlan = {
129
+ files: number;
130
+ changed: FileStat[];
131
+ replaces: number;
132
+ skipped: number;
133
+ unreadable: string[];
134
+ };
135
+ /** The counts `addPaths` reports for the files it was given. */
136
+ export type AddPathsResult = Pick<AddFilesResult, "nonText" | "unreadable" | "documents">;
137
+ /**
138
+ * The first half of `addFiles`: expands the globs, stats the files, and
139
+ * compares them with what the store knows. Reads no file's contents and
140
+ * writes nothing. Not exported from the package.
141
+ */
142
+ export declare function planFiles(memento: Memento, globs: string[]): Promise<FilesPlan>;
143
+ /**
144
+ * The second half of `addFiles`, for a caller that holds paths: stats them,
145
+ * reads every one, and writes their documents. `onProgress` counts the files
146
+ * of `paths`. A path the file system now refuses counts as unreadable. Not
147
+ * exported from the package.
148
+ */
149
+ export declare function addPaths(memento: Memento, paths: string[], options?: AddFilesOptions): Promise<AddPathsResult>;
150
+ /** The store's engine, for tests. Not exported from the package. */
151
+ export declare function engineOf(memento: Memento): Engine;
@@ -0,0 +1,470 @@
1
+ import { Embedder, hasSameText, nothingSpent, splitModelName } from "./embed.js";
2
+ import { engineExists, engineSettings, openEngine } from "./engine/open.js";
3
+ import { expandGlobs, planFileChanges, readAndParse, statFiles } from "./files.js";
4
+ import { validateFilter } from "./filter.js";
5
+ import { FUSION_WEIGHTS, fuse } from "./fusion.js";
6
+ import { checkLocalModels, checkModelCall } from "./local.js";
7
+ import { excerpt, excerptAt, queryWords } from "./query.js";
8
+ import { documentToStored, storedToDocument, toHit, validateDocuments } from "./rows.js";
9
+ import { windowExcerpt, windowsOf, wholeText } from "./windows.js";
10
+ /** Documents written per transaction by add, and per onProgress call. */
11
+ export const DOCUMENTS_PER_BATCH = 500;
12
+ /** Files read before each write transaction in addFiles. */
13
+ export const FILES_PER_BATCH = 100;
14
+ /** How many hits search returns when no limit is given. */
15
+ export const DEFAULT_LIMIT = 20;
16
+ /** How many documents each of the keyword list and the embedding list holds before fusion, at least. */
17
+ export const CANDIDATES = 100;
18
+ export class Memento {
19
+ engine;
20
+ /** Set when this connection can embed: the store's model was given at open. */
21
+ embedder;
22
+ /** The chat model this open named. The store does not record it. */
23
+ chat;
24
+ constructor(engine, embedder, chat) {
25
+ this.engine = engine;
26
+ this.embedder = embedder;
27
+ this.chat = chat;
28
+ }
29
+ /**
30
+ * Opens a store, creating it if it does not exist. One store per
31
+ * collection: the city code, the email, the medical reference.
32
+ */
33
+ static async open(store, options = {}) {
34
+ const models = options.models ?? {};
35
+ // Before the engine opens, so a bad name is never recorded in a new store,
36
+ // and a new store the guard rejects is never created.
37
+ if (models.embedding !== undefined) {
38
+ splitModelName(models.embedding);
39
+ }
40
+ if (options.local === true) {
41
+ checkLocalModels(models, undefined);
42
+ }
43
+ const engine = await openEngine(store);
44
+ try {
45
+ const settings = await engine.initialize({
46
+ models: models.embedding === undefined ? {} : { embedding: models.embedding },
47
+ local: options.local === true,
48
+ });
49
+ // Before anything is recorded, so an open the guard rejects leaves the store as it was.
50
+ if (options.local === true || settings.local) {
51
+ checkLocalModels(models, settings.models.embedding);
52
+ }
53
+ // `local` is sticky: once recorded, it stays, whatever a later open passes.
54
+ if (options.local === true && !settings.local) {
55
+ await engine.setSettings({ local: true });
56
+ }
57
+ const embedder = await applyOpenPlan(engine, settings.models, models.embedding);
58
+ return new Memento(engine, embedder, models.chat);
59
+ }
60
+ catch (error) {
61
+ await engine.close();
62
+ throw error;
63
+ }
64
+ }
65
+ /**
66
+ * Whether a store has already been created at `store`. `open` creates a
67
+ * missing files store, so a program that must not start from an empty
68
+ * store checks this first. A memory store never exists before it is opened.
69
+ */
70
+ static async exists(store) {
71
+ return engineExists(store);
72
+ }
73
+ /**
74
+ * The settings a store records, with the embedding model it was made
75
+ * with, or undefined when there is no store. Loads no documents and
76
+ * creates nothing. A store is written only through a connection opened
77
+ * with its embedding model, so a caller that did not make the store
78
+ * reads the model here before it opens one.
79
+ */
80
+ static async settings(store) {
81
+ return engineSettings(store);
82
+ }
83
+ /**
84
+ * Indexes documents: keyword index, embeddings, and model-written questions
85
+ * when `enrich` is on. Replaces any document with the same id. May be called
86
+ * any number of times.
87
+ */
88
+ async add(documents, options = {}) {
89
+ await this.checkCanWrite();
90
+ validateDocuments(documents, options.meta);
91
+ const stored = documents.map((doc) => documentToStored(doc, options.meta));
92
+ for (let done = 0; done < stored.length; done += DOCUMENTS_PER_BATCH) {
93
+ const batch = stored.slice(done, done + DOCUMENTS_PER_BATCH);
94
+ const existing = await this.engine.getDocsById(batch.map((doc) => doc.id));
95
+ const writes = await this.documentWrites(batch, existing);
96
+ await this.engine.write({ kind: "upsert", documents: writes });
97
+ options.onProgress?.(done + batch.length, stored.length);
98
+ }
99
+ }
100
+ /**
101
+ * A store with a recorded embedding model is written only through a
102
+ * connection that has the model; new documents would otherwise have no
103
+ * vectors. The recorded model is read now and not at open, because
104
+ * another connection can record one after this one opened without it.
105
+ */
106
+ async checkCanWrite() {
107
+ if (this.embedder === undefined && (await this.recordedEmbeddingModel()) !== undefined) {
108
+ throw new Error("store was opened without its embedding model");
109
+ }
110
+ }
111
+ async recordedEmbeddingModel() {
112
+ return (await this.engine.getSettings()).models.embedding;
113
+ }
114
+ /**
115
+ * Each document with what happens to its windows. A document whose title
116
+ * and text are stored unchanged keeps its windows. Any other gets new
117
+ * ones, embedded here, or none when the store has no embedding model or
118
+ * the document is blank. The model calls happen before the write. A
119
+ * document removed between the read of `existing` and the write makes
120
+ * the write reject, because "keep" names a document the engine no longer
121
+ * holds; docs/dev/engine.md has the race.
122
+ */
123
+ async documentWrites(batch, existing) {
124
+ // One write per id. The engine's upsert keeps the last copy of a repeated id, so only the last copy's windows fit its text.
125
+ const documents = lastCopies(batch);
126
+ const storedById = Object.fromEntries(existing.map((doc) => [doc.id, doc]));
127
+ const stored = (doc) => (Object.hasOwn(storedById, doc.id) ? storedById[doc.id] : undefined);
128
+ if (this.embedder === undefined) {
129
+ return documents.map((document) => ({ document, windows: stored(document) === undefined ? [] : "keep" }));
130
+ }
131
+ const changed = documents.filter((doc) => !hasSameText(doc, stored(doc)));
132
+ const windows = changed.map((doc) => windowsOf(doc));
133
+ const vectors = await this.embedder.embedWindows(windows.flat());
134
+ const writesById = {};
135
+ let next = 0;
136
+ changed.forEach((doc, i) => {
137
+ writesById[doc.id] = windows[i].map(({ n, start, end }) => ({ n, start, end, vector: vectors[next++] }));
138
+ });
139
+ return documents.map((document) => ({ document, windows: Object.hasOwn(writesById, document.id) ? writesById[document.id] : "keep" }));
140
+ }
141
+ /**
142
+ * Reads files matching the globs and indexes them. A file's id is its path,
143
+ * so re-adding a changed file replaces it; unchanged files are skipped.
144
+ * Globs skip dotfiles and dot directories, such as `.git`.
145
+ */
146
+ async addFiles(globs, options = {}) {
147
+ await this.checkCanWrite();
148
+ validateDocuments([], options.meta); // checks the batch meta before any file is read
149
+ // Listed and stat'ed once: the prune, the forced re-read and the plan all use this result.
150
+ const paths = await expandGlobs(globs);
151
+ const stats = await statFiles(paths);
152
+ if (options.prune === true) {
153
+ if (stats.files.length + stats.unreadable.length === 0) {
154
+ throw new Error("prune: the globs matched no files; nothing was removed");
155
+ }
156
+ // Before the writes, so an id from a removed file can move to a matched one.
157
+ await this.engine.write({ kind: "keepOnlyFiles", paths });
158
+ }
159
+ if (options.force === true) {
160
+ // The plan then finds every file changed. If this run rejects partway, the
161
+ // next run without force reads again every file this one did not finish,
162
+ // and reports the same error.
163
+ await this.engine.write({ kind: "forgetFileStamps", paths: stats.files.map((f) => f.path) });
164
+ }
165
+ const plan = await planStats(this, stats);
166
+ const total = plan.files;
167
+ const alreadyDone = plan.skipped + plan.unreadable.length;
168
+ const loaded = await addFileStats(this, plan.changed, {
169
+ ...options,
170
+ onProgress: (done) => options.onProgress?.(alreadyDone + done, total),
171
+ });
172
+ if (plan.changed.length === 0 && total > 0) {
173
+ options.onProgress?.(total, total);
174
+ }
175
+ return {
176
+ files: total,
177
+ skipped: plan.skipped,
178
+ nonText: loaded.nonText,
179
+ unreadable: plan.unreadable.length + loaded.unreadable,
180
+ documents: loaded.documents,
181
+ };
182
+ }
183
+ /** Checks that no document's id belongs elsewhere, then writes the batch's files in one write. */
184
+ async writeFiles(files, later) {
185
+ const all = files.flatMap((one) => one.documents);
186
+ const stored = await this.engine.getDocsById(all.map((doc) => doc.id));
187
+ checkOwnership(files, stored, later);
188
+ await this.engine.write({
189
+ kind: "replaceFiles",
190
+ files: files.map((one) => one.file),
191
+ documents: await this.documentWrites(all, stored),
192
+ });
193
+ }
194
+ async remove(ids) {
195
+ await this.engine.write({ kind: "remove", ids });
196
+ }
197
+ /**
198
+ * Finds documents, no answer written. For "every tax document for 2024" and "all my notes on retirement".
199
+ *
200
+ * A query is blank when it is empty after trimming. A blank query returns
201
+ * `[]`, or with a filter the filtered documents newest first, each with
202
+ * score 0. A query of stop words alone, such as "what is it", has no
203
+ * keyword terms: keyword search alone treats it like a blank query, and
204
+ * a search by meaning still runs it.
205
+ */
206
+ async search(query, options = {}) {
207
+ const limit = validateLimit(options.limit ?? DEFAULT_LIMIT);
208
+ const useEmbeddings = await this.resolveUseEmbeddings(options);
209
+ if (options.filter !== undefined) {
210
+ validateFilter(options.filter);
211
+ }
212
+ const terms = queryWords(query);
213
+ if (query.trim() === "" || (!useEmbeddings && terms.length === 0)) {
214
+ return this.listNewest(options.filter, limit);
215
+ }
216
+ if (!useEmbeddings) {
217
+ const scored = await this.engine.keywordSearch(terms, options.filter, limit);
218
+ return scored.map((one) => toHit(one.document, one.score, excerpt(one.document.text, terms) ?? excerptAt(one.document.text, 0)));
219
+ }
220
+ return this.fusedSearch(query, terms, options, limit);
221
+ }
222
+ /** What a query with nothing to search for returns: the filtered documents newest first with score 0, or nothing without a filter. */
223
+ async listNewest(filter, limit) {
224
+ if (filter === undefined) {
225
+ return [];
226
+ }
227
+ const newest = await this.engine.getNewest(filter, limit);
228
+ return newest.map((doc) => toHit(doc, 0, excerptAt(doc.text, 0)));
229
+ }
230
+ /**
231
+ * Both lists, fused by rank. The keyword list is empty for a query of stop
232
+ * words alone. The excerpt comes from the query's words when one is in
233
+ * the text, and from the document's best window otherwise.
234
+ */
235
+ async fusedSearch(query, terms, options, limit) {
236
+ const candidates = Math.max(CANDIDATES, limit);
237
+ const byKeyword = terms.length === 0 ? [] : await this.engine.keywordSearch(terms, options.filter, candidates);
238
+ const vector = await this.embedder.embedQuery(query);
239
+ const byMeaning = await this.engine.embeddingsSearch(vector, options.filter, candidates);
240
+ const fused = fuse([
241
+ { ids: byKeyword.map((one) => one.document.id), weight: FUSION_WEIGHTS.keyword },
242
+ { ids: byMeaning.map((one) => one.document.id), weight: FUSION_WEIGHTS.embedding },
243
+ ]).slice(0, limit);
244
+ const docs = Object.fromEntries([...byKeyword, ...byMeaning].map((one) => [one.document.id, one.document]));
245
+ const bestWindow = Object.fromEntries(byMeaning.map((one) => [one.document.id, one.window]));
246
+ return fused.map(({ id, score }) => {
247
+ const doc = docs[id];
248
+ const window = Object.hasOwn(bestWindow, id) ? bestWindow[id] : wholeText(doc.text);
249
+ return toHit(doc, score, excerpt(doc.text, terms) ?? windowExcerpt(doc.text, window));
250
+ });
251
+ }
252
+ /**
253
+ * Whether this search uses the embedding model. Unset means "when the
254
+ * store has it and was opened with it"; `true` without it rejects.
255
+ * `useLLM` is checked the same way and is not implemented yet.
256
+ */
257
+ async resolveUseEmbeddings(options) {
258
+ if (options.useEmbeddings === true && this.embedder === undefined) {
259
+ const recorded = await this.recordedEmbeddingModel();
260
+ throw new Error(recorded === undefined ? "store has no embedding model" : "store was opened without its embedding model");
261
+ }
262
+ if (options.useLLM === true && this.chat === undefined) {
263
+ throw new Error("store was opened without a chat model");
264
+ }
265
+ if (options.useLLM === true) {
266
+ throw new Error("model search is not implemented yet");
267
+ }
268
+ return options.useEmbeddings ?? this.embedder !== undefined;
269
+ }
270
+ /** Finds documents and writes an answer from them. For "what permits do we need?". Rejects if the open named no chat model. */
271
+ async ask(query, options = {}) {
272
+ throw new Error("store was opened without a chat model");
273
+ }
274
+ /** Fetch documents by id, in the order asked, one per asked id. Unknown ids are skipped. */
275
+ async get(ids) {
276
+ const byId = Object.fromEntries((await this.engine.getDocsById(ids)).map((doc) => [doc.id, storedToDocument(doc)]));
277
+ // hasOwn, so an id such as "constructor" does not find Object.prototype's.
278
+ return ids.flatMap((id) => (Object.hasOwn(byId, id) ? [byId[id]] : []));
279
+ }
280
+ async stats() {
281
+ return {
282
+ documents: await this.engine.getDocumentCount(),
283
+ files: await this.engine.getFileCount(),
284
+ bytes: await this.engine.getSizeBytes(),
285
+ models: (await this.engine.getSettings()).models,
286
+ // Milestone 3 counts the documents in the enrichment table.
287
+ enriched: 0,
288
+ // A copy, like every other field: the embedder's own count moves on with the next call.
289
+ spent: this.embedder === undefined ? nothingSpent() : { ...this.embedder.spent },
290
+ };
291
+ }
292
+ /** Flush and release the store and any model processes. A second call does nothing. */
293
+ async close() {
294
+ await this.engine.close();
295
+ }
296
+ }
297
+ /**
298
+ * One return per row of the open-rules table. `recorded` is the store's
299
+ * embedding model, `given` the one this open names.
300
+ */
301
+ export function planOpen(recorded, given, hasDocuments) {
302
+ if (recorded === undefined && given === undefined) {
303
+ return { kind: "keyword" };
304
+ }
305
+ if (recorded === undefined) {
306
+ return hasDocuments
307
+ ? { kind: "reject", message: `store holds documents without vectors; rebuild it to use embedding model ${given}` }
308
+ : { kind: "record" };
309
+ }
310
+ if (given === undefined) {
311
+ return { kind: "keyword" };
312
+ }
313
+ if (given !== recorded) {
314
+ return { kind: "reject", message: `store was built with embedding model ${recorded}; cannot open with ${given}` };
315
+ }
316
+ return { kind: "embed" };
317
+ }
318
+ /** Acts on the plan: records the model when the plan says so, and builds the embedder when the store will embed. */
319
+ async function applyOpenPlan(engine, stored, given) {
320
+ const plan = planOpen(stored.embedding, given, (await engine.getDocumentCount()) > 0);
321
+ switch (plan.kind) {
322
+ case "reject":
323
+ throw new Error(plan.message);
324
+ case "keyword":
325
+ return undefined;
326
+ case "record":
327
+ await engine.setSettings({ models: { embedding: given } });
328
+ return guardedEmbedder(engine, given);
329
+ case "embed":
330
+ return guardedEmbedder(engine, given);
331
+ }
332
+ }
333
+ /** An embedder that runs the local guard before every call. */
334
+ function guardedEmbedder(engine, model) {
335
+ return new Embedder(model, () => checkModelCall(engine, "embedding", model));
336
+ }
337
+ /** The batch with each repeated id reduced to its last copy, in the order of those copies. */
338
+ function lastCopies(batch) {
339
+ const seen = new Set();
340
+ const kept = [];
341
+ for (const doc of batch.toReversed()) {
342
+ if (!seen.has(doc.id)) {
343
+ seen.add(doc.id);
344
+ kept.push(doc);
345
+ }
346
+ }
347
+ return kept.reverse();
348
+ }
349
+ function toFileDocuments(parsed, batchMeta) {
350
+ try {
351
+ validateDocuments(parsed.documents);
352
+ }
353
+ catch (error) {
354
+ throw new Error(`${parsed.file.path}: ${error.message}`, { cause: error });
355
+ }
356
+ return { file: parsed.file, documents: parsed.documents.map((doc) => documentToStored(doc, batchMeta, parsed.file.path)) };
357
+ }
358
+ /**
359
+ * Rejects a document whose id already belongs elsewhere, naming both places.
360
+ * Without the check, one file would silently replace another's document, and
361
+ * re-indexing the first file would then delete it. Three rules:
362
+ *
363
+ * 1. Two files in this batch giving one id reject, the second naming the
364
+ * first. The same id twice from one file is allowed; the last wins.
365
+ * 2. A stored owner in `later` or in this batch is allowed: the id has moved
366
+ * out of a file this load rewrites.
367
+ * 3. Any other stored owner rejects, as does a stored document from add.
368
+ */
369
+ function checkOwnership(files, stored, later) {
370
+ const inBatch = new Set(files.map((one) => one.file.path));
371
+ const storedOwner = Object.fromEntries(stored.map((doc) => [doc.id, doc.sourcePath]));
372
+ const seenIn = {};
373
+ for (const { file, documents } of files) {
374
+ for (const { id } of documents) {
375
+ const earlier = Object.hasOwn(seenIn, id) ? seenIn[id] : undefined;
376
+ if (earlier !== undefined && earlier !== file.path) {
377
+ throw alreadyExists(id, file.path, earlier);
378
+ }
379
+ seenIn[id] = file.path;
380
+ if (!Object.hasOwn(storedOwner, id)) {
381
+ continue;
382
+ }
383
+ const owner = storedOwner[id];
384
+ const rewritten = owner !== undefined && (owner === file.path || later.has(owner) || inBatch.has(owner));
385
+ if (!rewritten) {
386
+ throw alreadyExists(id, file.path, owner ?? "add()");
387
+ }
388
+ }
389
+ }
390
+ }
391
+ function alreadyExists(id, file, owner) {
392
+ return new Error(`document "${id}" from ${file} already exists from ${owner}`);
393
+ }
394
+ function validateLimit(limit) {
395
+ if (!Number.isInteger(limit) || limit < 0) {
396
+ throw new Error(`limit must be a whole number, 0 or more; got ${limit}`);
397
+ }
398
+ return limit;
399
+ }
400
+ /**
401
+ * The first half of `addFiles`: expands the globs, stats the files, and
402
+ * compares them with what the store knows. Reads no file's contents and
403
+ * writes nothing. Not exported from the package.
404
+ */
405
+ export async function planFiles(memento, globs) {
406
+ return planStats(memento, await statFiles(await expandGlobs(globs)));
407
+ }
408
+ /** `planFiles` for files already stat'ed, so `addFiles` stats each file once. */
409
+ async function planStats(memento, stats) {
410
+ const known = await engineOf(memento).statFiles(stats.files.map((f) => f.path));
411
+ const knownPaths = new Set(known.map((file) => file.path));
412
+ const plan = planFileChanges(stats.files, known, false);
413
+ return {
414
+ files: plan.total + stats.unreadable.length,
415
+ changed: plan.changed,
416
+ replaces: plan.changed.filter((file) => knownPaths.has(file.path)).length,
417
+ skipped: plan.skipped,
418
+ unreadable: stats.unreadable,
419
+ };
420
+ }
421
+ /**
422
+ * The second half of `addFiles`, for a caller that holds paths: stats them,
423
+ * reads every one, and writes their documents. `onProgress` counts the files
424
+ * of `paths`. A path the file system now refuses counts as unreadable. Not
425
+ * exported from the package.
426
+ */
427
+ export async function addPaths(memento, paths, options = {}) {
428
+ await memento["checkCanWrite"]();
429
+ validateDocuments([], options.meta);
430
+ const stats = await statFiles(paths);
431
+ const refused = stats.unreadable.length;
432
+ const loaded = await addFileStats(memento, stats.files, {
433
+ ...options,
434
+ onProgress: (done) => options.onProgress?.(refused + done, paths.length),
435
+ });
436
+ return { ...loaded, unreadable: refused + loaded.unreadable };
437
+ }
438
+ /**
439
+ * Reads every file in `files` and writes their documents, FILES_PER_BATCH
440
+ * files per write. `onProgress` counts the files of `files`. The caller has
441
+ * checked that the store can be written.
442
+ */
443
+ async function addFileStats(memento, files, options) {
444
+ // Files not yet written; an id they own may move to a file written earlier.
445
+ const later = new Set(files.map((file) => file.path));
446
+ let done = 0;
447
+ let nonText = 0;
448
+ let unreadable = 0;
449
+ let documents = 0;
450
+ for (let start = 0; start < files.length; start += FILES_PER_BATCH) {
451
+ // Read with await first; the write is one batch the engine applies atomically.
452
+ const group = files.slice(start, start + FILES_PER_BATCH);
453
+ const batch = await Promise.all(group.map((file) => readAndParse(file, options.parse)));
454
+ for (const file of group) {
455
+ later.delete(file.path);
456
+ }
457
+ const readable = batch.filter((one) => one.kind !== "unreadable").map((one) => toFileDocuments(one, options.meta));
458
+ await memento["writeFiles"](readable, later);
459
+ done += batch.length;
460
+ nonText += batch.filter((one) => one.kind === "nonText").length;
461
+ unreadable += batch.length - readable.length;
462
+ documents += readable.reduce((sum, one) => sum + one.documents.length, 0);
463
+ options.onProgress?.(done, files.length);
464
+ }
465
+ return { nonText, unreadable, documents };
466
+ }
467
+ /** The store's engine, for tests. Not exported from the package. */
468
+ export function engineOf(memento) {
469
+ return memento["engine"];
470
+ }
@@ -0,0 +1,50 @@
1
+ import type { Position } from "./types.ts";
2
+ /** How long an excerpt is, before widening to whitespace. */
3
+ export declare const EXCERPT_CHARS = 300;
4
+ /** How far an excerpt may widen at each end to reach whitespace. */
5
+ export declare const WIDEN_CHARS = 40;
6
+ /**
7
+ * Lowercases a word and removes every combining mark, then recomposes what is
8
+ * left, so Hangul stays in syllables. It folds more than unicode61 does, which
9
+ * keeps accents on non-Latin letters and on letters with two accents. Folds
10
+ * one word at a time, so offsets in the original text stay valid.
11
+ */
12
+ export declare function foldWord(word: string): string;
13
+ /**
14
+ * The distinct content words of a question, in order, each in two forms: the
15
+ * word lowercased, and the word folded by foldWord. An engine's tokenizer
16
+ * folds the first form the way it indexed the documents, which finds "Сергей"
17
+ * and "Nguyễn" as written. The folded form finds the same word written without its marks,
18
+ * such as "שלום" for "שָׁלוֹם". The stop list and MIN_TERM_LENGTH check the
19
+ * folded form, so "thé" is dropped like "the".
20
+ */
21
+ export declare function queryWords(text: string, maxTerms?: number): string[];
22
+ export type Excerpt = {
23
+ excerpt: string;
24
+ position: Position;
25
+ };
26
+ export type Match = {
27
+ stem: string;
28
+ start: number;
29
+ };
30
+ /**
31
+ * Every word of a text as its stem, with where it starts: the word by WORD,
32
+ * folded by foldWord, stemmed by stem. The keyword index and the excerpt both
33
+ * use this, so what the index matched is what the excerpt highlights.
34
+ */
35
+ export declare function stemsOf(text: string): Match[];
36
+ /**
37
+ * The window of `text` holding the most distinct query terms, matched by
38
+ * Porter stem, the way the keyword index matched them. Ties go to the earliest window.
39
+ * Undefined when no word in the text matches, so the caller can show
40
+ * another part of the document.
41
+ */
42
+ export declare function excerpt(text: string, terms: string[]): Excerpt | undefined;
43
+ /** The excerpt of EXCERPT_CHARS starting at `from`, widened to whitespace at each end. */
44
+ export declare function excerptAt(text: string, from: number): Excerpt;
45
+ /**
46
+ * Slides a window of EXCERPT_CHARS over the matches in one pass. Starting at
47
+ * 0 or at a match covers every best window, since a window can move right to
48
+ * its first match without losing one. Ties go to the earliest window.
49
+ */
50
+ export declare function bestWindowStart(matches: Match[]): number;