@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,237 @@
1
+ // The functions index.agency calls. Each opens the store inside the call and
2
+ // returns plain JSON, because a value that crosses into Agency can end up in
3
+ // a checkpoint. docs/dev/agency-module.md has the design. Not part of the
4
+ // TypeScript interface: index.agency imports this file by relative path, and
5
+ // package.json's "exports" has no entry for it.
6
+ //
7
+ // The describe and plan functions take the path as the caller wrote it, with
8
+ // `base`, the run's working folder, and return the absolute folder. Every
9
+ // other function takes that absolute folder.
10
+ import { realpath } from "node:fs/promises";
11
+ import path from "node:path";
12
+ import { splitModelName } from "./embed.js";
13
+ import { engineExists, engineSettings } from "./engine/open.js";
14
+ import { expandHome } from "./files.js";
15
+ import { isLocalModel } from "./local.js";
16
+ import { addPaths, Memento, planFiles } from "./memento.js";
17
+ export async function describeStore(store, base) {
18
+ const dir = resolveFrom(base, store);
19
+ return storeInfo(dir, (await existingSettings(dir)).models.embedding ?? "");
20
+ }
21
+ /** Checks that `createStoreAt` can create a store here with this model, and creates nothing. */
22
+ export async function describeNewStore(store, embeddingModel, base) {
23
+ const dir = resolveFrom(base, store);
24
+ if (embeddingModel !== "") {
25
+ splitModelName(embeddingModel);
26
+ }
27
+ await checkNoStore(dir);
28
+ return storeInfo(dir, embeddingModel);
29
+ }
30
+ /** `describeStore`, with how many of the documents would replace one the store holds. Loads the store to find out. */
31
+ export async function describeAdd(store, documents, base) {
32
+ const info = await describeStore(store, base);
33
+ if (documents.length === 0) {
34
+ return { ...info, replaces: 0 };
35
+ }
36
+ const ids = [...new Set(documents.map((document) => document.id))];
37
+ const held = await withStore(info.store, (memento) => memento.get(ids));
38
+ return { ...info, replaces: held.length };
39
+ }
40
+ export async function createStoreAt(store, embeddingModel) {
41
+ await checkNoStore(store);
42
+ const models = embeddingModel === "" ? {} : { embedding: embeddingModel };
43
+ const memento = await Memento.open({ type: "files", path: store }, { models });
44
+ await memento.close();
45
+ return { store };
46
+ }
47
+ /** `approved` is what the caller approved: the store, its embedding model and where the model runs. A store that no longer matches fails. */
48
+ export async function searchStore(approved, query, limit, filter) {
49
+ const options = filter === null ? { limit } : { limit, filter: toCondition(filter) };
50
+ const hits = await withApprovedStore(approved, (memento) => memento.search(query, options));
51
+ return hits.map(toJsonHit);
52
+ }
53
+ export async function getStoredDocuments(store, ids) {
54
+ const documents = await withStore(store, (memento) => memento.get(ids));
55
+ return documents.map(toJsonDocument);
56
+ }
57
+ export async function storeStats(store) {
58
+ const stats = await withStore(store, (memento) => memento.stats());
59
+ return { documents: stats.documents, files: stats.files, bytes: stats.bytes, embeddingModel: stats.models.embedding ?? "" };
60
+ }
61
+ /** `approved` is what the caller approved: the store, its embedding model and where the model runs. A store that no longer matches fails. */
62
+ export async function addDocuments(approved, documents) {
63
+ // Converted before the store opens, so a bad date fails before anything is written.
64
+ const converted = documents.map(toDocument);
65
+ await withApprovedStore(approved, (memento) => memento.add(converted));
66
+ return { documents: converted.length };
67
+ }
68
+ export async function removeDocuments(store, ids) {
69
+ await withStore(store, (memento) => memento.remove(ids));
70
+ return { removed: ids.length };
71
+ }
72
+ /** Lists and compares the files the globs match. Reads no file's contents and writes nothing. A relative glob starts at `base`. */
73
+ export async function planStoreFiles(store, globs, base) {
74
+ const info = await describeStore(store, base);
75
+ const absolute = globs.map((pattern) => resolveFrom(base, pattern));
76
+ const plan = await withStore(info.store, (memento) => planFiles(memento, absolute));
77
+ const changed = await Promise.all(plan.changed.map((file) => changedFile(file.path)));
78
+ return { ...info, files: plan.files, changed, replaces: plan.replaces, skipped: plan.skipped, unreadable: plan.unreadable };
79
+ }
80
+ /**
81
+ * Reads the plan's changed files and no others. A file that changed after the
82
+ * plan waits for the next plan. Fails when a file now points somewhere other
83
+ * than the real path approved, or when the store's embedding model is no
84
+ * longer what the plan says. A plan with nothing changed opens no store.
85
+ */
86
+ export async function loadStoreFiles(plan) {
87
+ const counts = { files: plan.files, skipped: plan.skipped, nonText: 0, unreadable: plan.unreadable.length, documents: 0 };
88
+ if (plan.changed.length === 0) {
89
+ await existingSettings(plan.store);
90
+ return counts;
91
+ }
92
+ const paths = plan.changed.map((file) => file.path);
93
+ const loaded = await withApprovedStore(plan, async (memento) => {
94
+ // Just before the read, so the window for a swapped link is as short as it can be.
95
+ await Promise.all(plan.changed.map(checkStillApproved));
96
+ return addPaths(memento, paths);
97
+ });
98
+ return { ...counts, nonText: loaded.nonText, unreadable: counts.unreadable + loaded.unreadable, documents: loaded.documents };
99
+ }
100
+ /** Opens an existing store with its recorded embedding model, runs `fn`, and closes the store. Never creates a store. */
101
+ async function withStore(store, fn) {
102
+ return openAndRun(store, (await existingSettings(store)).models.embedding, fn);
103
+ }
104
+ /**
105
+ * `withStore` for a call that may send text to the embedding model. The
106
+ * caller approved a model and where it runs. Both can change while a program
107
+ * is paused at the approval: the store can be rebuilt with another model, and
108
+ * the run can resume where `MLX_BASE_URL` names another machine. A store that
109
+ * no longer matches fails before anything is sent.
110
+ */
111
+ async function withApprovedStore(approved, fn) {
112
+ const embedding = (await existingSettings(approved.store)).models.embedding;
113
+ const now = storeInfo(approved.store, embedding ?? "");
114
+ if (now.embeddingModel !== approved.embeddingModel) {
115
+ const was = approved.embeddingModel === "" ? "none" : approved.embeddingModel;
116
+ throw new Error(`the store's embedding model is now ${embedding ?? "none"}; it was approved as ${was}. Call again to be asked about the new model`);
117
+ }
118
+ if (now.runsOn !== approved.runsOn) {
119
+ throw new Error(`the store's embedding model ${now.embeddingModel} now runs ${now.runsOn}; it was approved as ${approved.runsOn}. Call again to be asked`);
120
+ }
121
+ return openAndRun(approved.store, embedding, fn);
122
+ }
123
+ async function openAndRun(dir, embedding, fn) {
124
+ const models = embedding === undefined ? {} : { embedding };
125
+ const memento = await Memento.open({ type: "files", path: dir }, { models });
126
+ try {
127
+ return await fn(memento);
128
+ }
129
+ finally {
130
+ await memento.close();
131
+ }
132
+ }
133
+ /**
134
+ * A path or glob as the caller wrote it, made absolute: `~` expanded, then
135
+ * resolved against `base`. `base` is the run's working folder, which Agency's
136
+ * own file functions resolve against, and which a host can set apart from the
137
+ * process's.
138
+ */
139
+ function resolveFrom(base, written) {
140
+ return path.resolve(base, expandHome(written));
141
+ }
142
+ async function existingSettings(dir) {
143
+ const settings = await engineSettings({ type: "files", path: dir });
144
+ if (settings === undefined) {
145
+ throw new Error(`no store at ${dir}; create one with createStore`);
146
+ }
147
+ return settings;
148
+ }
149
+ async function checkNoStore(dir) {
150
+ if (await engineExists({ type: "files", path: dir })) {
151
+ throw new Error(`${dir} already holds a store, or other files; createStore needs a missing or empty folder`);
152
+ }
153
+ }
154
+ function storeInfo(dir, embeddingModel) {
155
+ return { store: dir, embeddingModel, runsOn: runsOn(embeddingModel) };
156
+ }
157
+ function runsOn(embeddingModel) {
158
+ if (embeddingModel === "") {
159
+ return "";
160
+ }
161
+ return isLocalModel(embeddingModel) ? "local" : "hosted";
162
+ }
163
+ /**
164
+ * Fails when the file at `file.path` is no longer the real file that was
165
+ * approved, such as a plain file replaced by a link. A file gone since the
166
+ * plan is left to `addPaths`, which counts it as unreadable.
167
+ */
168
+ async function checkStillApproved(file) {
169
+ const approved = path.join(file.dir, file.filename);
170
+ const real = await realpath(file.path).catch((error) => {
171
+ if (typeof error?.code !== "string") {
172
+ throw error;
173
+ }
174
+ return undefined;
175
+ });
176
+ if (real !== undefined && real !== approved) {
177
+ throw new Error(`${file.path} now points to ${real}, which was not approved; run addFiles again`);
178
+ }
179
+ }
180
+ /** The real folder and name of a file, so a link is asked about as the file it points to. */
181
+ async function changedFile(matched) {
182
+ const real = await realpath(matched);
183
+ return { path: matched, dir: path.dirname(real), filename: path.basename(real) };
184
+ }
185
+ /** The object without its null fields. Only the top level: a null inside a nested value stays. */
186
+ function withoutNulls(object) {
187
+ return Object.fromEntries(Object.entries(object).filter(([, value]) => value !== null));
188
+ }
189
+ /** A filter from Agency as a Condition. A null field means the field was not given, except inside `meta`, where null is a value. */
190
+ export function toCondition(filter) {
191
+ const { date, lengthChars, ...rest } = withoutNulls(filter);
192
+ const condition = rest;
193
+ if (date !== undefined) {
194
+ condition.date = toDateRange(withoutNulls(date));
195
+ }
196
+ if (lengthChars !== undefined) {
197
+ condition.lengthChars = withoutNulls(lengthChars);
198
+ }
199
+ return condition;
200
+ }
201
+ function toDateRange(range) {
202
+ const dates = {};
203
+ if (range.after !== undefined) {
204
+ dates.after = parseDate(range.after, "date.after");
205
+ }
206
+ if (range.before !== undefined) {
207
+ dates.before = parseDate(range.before, "date.before");
208
+ }
209
+ return dates;
210
+ }
211
+ /** A document from Agency as a Document. A null field means the field was not given. */
212
+ export function toDocument(document) {
213
+ const { createdAt, ...rest } = withoutNulls(document);
214
+ const converted = rest;
215
+ if (createdAt !== undefined) {
216
+ converted.createdAt = parseDate(createdAt, `document "${document.id}": createdAt`);
217
+ }
218
+ return converted;
219
+ }
220
+ function parseDate(value, field) {
221
+ const date = typeof value === "string" ? new Date(value) : new Date(Number.NaN);
222
+ if (Number.isNaN(date.getTime())) {
223
+ throw new Error(`${field} must be an ISO date such as "2024-01-01"; got ${JSON.stringify(value)}`);
224
+ }
225
+ return date;
226
+ }
227
+ export function toJsonDocument(document) {
228
+ const { createdAt, ...rest } = document;
229
+ if (createdAt === undefined) {
230
+ return rest;
231
+ }
232
+ return { ...rest, createdAt: createdAt.toISOString() };
233
+ }
234
+ export function toJsonHit(hit) {
235
+ const { text: _text, ...document } = toJsonDocument(hit.document);
236
+ return { ...hit, document };
237
+ }
@@ -0,0 +1,45 @@
1
+ import { type EmbedNodeRun } from "./agency/embed.js";
2
+ import type { StoredDocument } from "./engine/types.ts";
3
+ import type { Spent } from "./types.ts";
4
+ import type { TextWindow } from "./windows.ts";
5
+ /** Texts per embedMany call. */
6
+ export declare const EMBED_BATCH = 128;
7
+ /** embedMany calls in flight at once. */
8
+ export declare const EMBED_CONCURRENCY = 4;
9
+ export type EmbedKind = "document" | "query";
10
+ /** What the node takes: the texts already cut into batches and groups of batches. */
11
+ export type EmbedNodeInput = {
12
+ groups: string[][][];
13
+ model: string;
14
+ provider: string;
15
+ kind: EmbedKind;
16
+ };
17
+ /** What the node returns to TypeScript: its return value in `data`, and what the run spent. */
18
+ export type EmbedNodeResult = Pick<EmbedNodeRun, "data" | "usage">;
19
+ export type EmbedNode = (input: EmbedNodeInput) => Promise<EmbedNodeResult>;
20
+ /** Replaces the node, for tests that must not call a provider. `undefined` restores the real one. */
21
+ export declare function useEmbedNode(node: EmbedNode | undefined): void;
22
+ export type ModelName = {
23
+ provider: string;
24
+ model: string;
25
+ };
26
+ /** "provider:model", split at the first colon, so a model name may hold one: "ollama:qwen3:8b". */
27
+ export declare function splitModelName(name: string): ModelName;
28
+ export declare function nothingSpent(): Spent;
29
+ /** One embedding model, and what this connection has spent on it. */
30
+ export declare class Embedder {
31
+ readonly name: string;
32
+ readonly spent: Spent;
33
+ private readonly model;
34
+ /** Runs before every call to the node, and rejects to stop it. Memento passes the local guard. */
35
+ private readonly beforeCall;
36
+ constructor(name: string, beforeCall: () => Promise<void>);
37
+ /** One unit-length vector per text, in order. Rejects when the node fails, returns the wrong count, or returns a vector of zeros. */
38
+ embed(texts: string[], kind: EmbedKind): Promise<Float32Array[]>;
39
+ embedWindows(windows: TextWindow[]): Promise<Float32Array[]>;
40
+ embedQuery(query: string): Promise<Float32Array>;
41
+ }
42
+ /** Batches of EMBED_BATCH texts, in groups of EMBED_CONCURRENCY batches. */
43
+ export declare function groupsOf(texts: string[]): string[][][];
44
+ /** True when the stored document has the same title and text, so its windows still describe it. */
45
+ export declare function hasSameText(doc: StoredDocument, stored: StoredDocument | undefined): boolean;
package/dist/embed.js ADDED
@@ -0,0 +1,77 @@
1
+ // The model call: from texts to unit-length vectors through the compiled
2
+ // Agency node in src/agency/embed.agency, and what it cost. agency compile
3
+ // writes the node to src/agency/embed.js; embed.d.ts beside it has its types.
4
+ import { embedTexts } from "./agency/embed.js";
5
+ import { toUnitVector } from "./vectors.js";
6
+ /** Texts per embedMany call. */
7
+ export const EMBED_BATCH = 128;
8
+ /** embedMany calls in flight at once. */
9
+ export const EMBED_CONCURRENCY = 4;
10
+ const realNode = (input) => embedTexts(input);
11
+ let embedNode = realNode;
12
+ /** Replaces the node, for tests that must not call a provider. `undefined` restores the real one. */
13
+ export function useEmbedNode(node) {
14
+ embedNode = node ?? realNode;
15
+ }
16
+ /** "provider:model", split at the first colon, so a model name may hold one: "ollama:qwen3:8b". */
17
+ export function splitModelName(name) {
18
+ const colon = name.indexOf(":");
19
+ if (colon <= 0 || colon === name.length - 1) {
20
+ throw new Error(`model "${name}" must be named "provider:model", such as "openai:text-embedding-3-small"`);
21
+ }
22
+ return { provider: name.slice(0, colon), model: name.slice(colon + 1) };
23
+ }
24
+ export function nothingSpent() {
25
+ return { embeddingCalls: 0, embeddingTokens: 0, cost: 0 };
26
+ }
27
+ /** One embedding model, and what this connection has spent on it. */
28
+ export class Embedder {
29
+ name;
30
+ spent = nothingSpent();
31
+ model;
32
+ /** Runs before every call to the node, and rejects to stop it. Memento passes the local guard. */
33
+ beforeCall;
34
+ constructor(name, beforeCall) {
35
+ this.name = name;
36
+ this.model = splitModelName(name);
37
+ this.beforeCall = beforeCall;
38
+ }
39
+ /** One unit-length vector per text, in order. Rejects when the node fails, returns the wrong count, or returns a vector of zeros. */
40
+ async embed(texts, kind) {
41
+ if (texts.length === 0) {
42
+ return [];
43
+ }
44
+ await this.beforeCall();
45
+ const result = await embedNode({ groups: groupsOf(texts), model: this.model.model, provider: this.model.provider, kind });
46
+ this.spent.embeddingCalls += 1;
47
+ this.spent.embeddingTokens += result.usage.tokens.inputTokens;
48
+ this.spent.cost += result.usage.cost.totalCost;
49
+ if (!result.data.success) {
50
+ throw new Error(`embedding with ${this.name} failed: ${result.data.error}`);
51
+ }
52
+ const { vectors } = result.data.value;
53
+ if (vectors.length !== texts.length) {
54
+ throw new Error(`embedding with ${this.name} returned ${vectors.length} vectors for ${texts.length} texts`);
55
+ }
56
+ return vectors.map(toUnitVector);
57
+ }
58
+ embedWindows(windows) {
59
+ return this.embed(windows.map((window) => window.text), "document");
60
+ }
61
+ async embedQuery(query) {
62
+ const [vector] = await this.embed([query], "query");
63
+ return vector;
64
+ }
65
+ }
66
+ /** Batches of EMBED_BATCH texts, in groups of EMBED_CONCURRENCY batches. */
67
+ export function groupsOf(texts) {
68
+ const batches = chunk(texts, EMBED_BATCH);
69
+ return chunk(batches, EMBED_CONCURRENCY);
70
+ }
71
+ function chunk(items, size) {
72
+ return Array.from({ length: Math.ceil(items.length / size) }, (_, i) => items.slice(i * size, (i + 1) * size));
73
+ }
74
+ /** True when the stored document has the same title and text, so its windows still describe it. */
75
+ export function hasSameText(doc, stored) {
76
+ return stored !== undefined && stored.title === doc.title && stored.text === doc.text;
77
+ }
@@ -0,0 +1,85 @@
1
+ import { type FileStat } from "../../files.ts";
2
+ import type { Filter, Storage } from "../../types.ts";
3
+ import type { DocumentWindows, Engine, ScoredDocument, StoredDocument, StoreSettings, WindowHit, WriteBatch } from "../types.ts";
4
+ /**
5
+ * Runs `hook` in every load, between reading the manifest and reading its
6
+ * segments, for the test of a compaction that lands in that gap.
7
+ * `undefined` removes it.
8
+ */
9
+ export declare function useAfterManifestRead(hook: (() => Promise<void>) | undefined): void;
10
+ /** Opens the directory, creating a missing one. Writes nothing inside it; `initialize` does, once the directory is known to be a store or empty. */
11
+ export declare function openFilesEngine(storage: Storage & {
12
+ type: "files";
13
+ }): Promise<FilesEngine>;
14
+ /** True when the directory holds a manifest, or other files, such as an earlier Memento's store, which open then rejects with a message. Creates nothing. */
15
+ export declare function filesStoreExists(storage: Storage & {
16
+ type: "files";
17
+ }): Promise<boolean>;
18
+ /** The settings in the manifest, or undefined when the directory holds no store. Reads the manifest alone, and creates nothing. */
19
+ export declare function filesStoreSettings(storage: Storage & {
20
+ type: "files";
21
+ }): Promise<StoreSettings | undefined>;
22
+ export declare class FilesEngine implements Engine {
23
+ readonly kind = "files";
24
+ private readonly dir;
25
+ private state;
26
+ private loaded;
27
+ constructor(dir: string);
28
+ private store;
29
+ /**
30
+ * A new directory gets a manifest with the defaults, written under the
31
+ * lock through the rename, so two processes creating the same store get
32
+ * one manifest and the loser reads what the winner wrote. An existing
33
+ * store is read without the lock.
34
+ */
35
+ initialize(defaults: StoreSettings): Promise<StoreSettings>;
36
+ getSettings(): Promise<StoreSettings>;
37
+ setSettings(patch: Partial<StoreSettings>): Promise<void>;
38
+ getDocsById(ids: string[]): Promise<StoredDocument[]>;
39
+ getWindows(ids: string[]): Promise<DocumentWindows[]>;
40
+ getDocumentCount(): Promise<number>;
41
+ getFileCount(): Promise<number>;
42
+ statFiles(paths: string[]): Promise<FileStat[]>;
43
+ /** The bytes of the live segments' files. A compaction under the stat makes it read the manifest again. */
44
+ getSizeBytes(): Promise<number>;
45
+ /**
46
+ * Under the lock: catch up with other writers, validate the batch against
47
+ * the current state, write its segment, commit the manifest, and only
48
+ * then change memory. A failure before the commit leaves both as they
49
+ * were. A batch that changes nothing, such as a remove of ids the store
50
+ * does not hold, writes nothing.
51
+ */
52
+ write(batch: WriteBatch): Promise<void>;
53
+ /** Commits a manifest already backed by its segment files, then applies the records to memory. */
54
+ private commit;
55
+ private needsCompaction;
56
+ /** One record per document, per document with windows, and per file: what a compacted segment holds. */
57
+ private liveRecords;
58
+ /**
59
+ * Rewrites the whole store as one segment and deletes the others. Runs
60
+ * under the write lock. Deletes only segment files the new manifest no
61
+ * longer names, inside the segments directory, and only files with a
62
+ * segment's name; a stray file such as .DS_Store is left alone. A
63
+ * segment file that is already gone is not an error.
64
+ */
65
+ private compact;
66
+ keywordSearch(terms: string[], filter: Filter | undefined, limit: number): Promise<ScoredDocument[]>;
67
+ getNewest(filter: Filter | undefined, limit: number): Promise<StoredDocument[]>;
68
+ embeddingsSearch(query: Float32Array, filter: Filter | undefined, limit: number): Promise<WindowHit[]>;
69
+ private current;
70
+ /**
71
+ * Catches up with the manifest on disk when another process changed it.
72
+ * The check is a stat: a commit renames a new file over the manifest, so
73
+ * its inode changes. When the segment list only grew, the new segments
74
+ * are replayed onto the state; otherwise the state is rebuilt. A segment
75
+ * a compaction removed under the load makes the load start again.
76
+ */
77
+ private sync;
78
+ /** Runs `fn` after a load, and again after a fresh load when a segment it read was compacted away under it. */
79
+ private withReload;
80
+ private isCurrent;
81
+ private load;
82
+ check(): Promise<void>;
83
+ /** Lets the state go. Nothing is held open between calls, so there is nothing to flush. A second call does nothing. */
84
+ close(): Promise<void>;
85
+ }