@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.
- package/README.md +64 -2
- package/dist/agency/embed.d.ts +22 -0
- package/dist/agency/embed.js +458 -0
- package/dist/agencyApi.d.ts +98 -0
- package/dist/agencyApi.js +237 -0
- package/dist/embed.d.ts +45 -0
- package/dist/embed.js +77 -0
- package/dist/engine/files/engine.d.ts +85 -0
- package/dist/engine/files/engine.js +284 -0
- package/dist/engine/files/lock.d.ts +18 -0
- package/dist/engine/files/lock.js +247 -0
- package/dist/engine/files/manifest.d.ts +43 -0
- package/dist/engine/files/manifest.js +111 -0
- package/dist/engine/files/safe-delete.d.ts +19 -0
- package/dist/engine/files/safe-delete.js +79 -0
- package/dist/engine/files/segments.d.ts +17 -0
- package/dist/engine/files/segments.js +128 -0
- package/dist/engine/memory/engine.d.ts +27 -0
- package/dist/engine/memory/engine.js +87 -0
- package/dist/engine/open.d.ts +7 -0
- package/dist/engine/open.js +28 -0
- package/dist/engine/shared/filter.d.ts +7 -0
- package/dist/engine/shared/filter.js +72 -0
- package/dist/engine/shared/keyword.d.ts +27 -0
- package/dist/engine/shared/keyword.js +92 -0
- package/dist/engine/shared/settings.d.ts +5 -0
- package/dist/engine/shared/settings.js +9 -0
- package/dist/engine/shared/state.d.ts +58 -0
- package/dist/engine/shared/state.js +275 -0
- package/dist/engine/shared/tokens.d.ts +15 -0
- package/dist/engine/shared/tokens.js +23 -0
- package/dist/engine/shared/vectors.d.ts +36 -0
- package/dist/engine/shared/vectors.js +70 -0
- package/dist/engine/types.d.ts +121 -0
- package/dist/engine/types.js +1 -0
- package/dist/files.d.ts +75 -0
- package/dist/files.js +190 -0
- package/dist/filter.d.ts +3 -0
- package/dist/filter.js +80 -0
- package/dist/fusion.d.ts +24 -0
- package/dist/fusion.js +26 -0
- package/dist/ids.d.ts +2 -0
- package/dist/ids.js +19 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/local.d.ts +36 -0
- package/dist/local.js +75 -0
- package/dist/memento.d.ts +151 -0
- package/dist/memento.js +470 -0
- package/dist/query.d.ts +50 -0
- package/dist/query.js +138 -0
- package/dist/rows.d.ts +17 -0
- package/dist/rows.js +90 -0
- package/dist/stem.d.ts +2 -0
- package/dist/stem.js +121 -0
- package/dist/types.d.ts +246 -0
- package/dist/types.js +3 -0
- package/dist/vectors.d.ts +2 -0
- package/dist/vectors.js +10 -0
- package/dist/windows.d.ts +44 -0
- package/dist/windows.js +77 -0
- package/index.agency +268 -0
- package/index.js +1803 -0
- package/package.json +55 -4
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// The manifest of a files store: what the store is, in one small file. Writing
|
|
2
|
+
// it through a temporary name and a rename is the store's commit, so a reader
|
|
3
|
+
// sees the old manifest or the new one and never a mix.
|
|
4
|
+
import { open, readdir, readFile, rename, stat } from "node:fs/promises";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
export const MANIFEST_FILE = "manifest.json";
|
|
7
|
+
export const SEGMENTS_DIR = "segments";
|
|
8
|
+
export const LOCK_FILE = "lock";
|
|
9
|
+
/** The files engine's layout version, checked before anything else is read. */
|
|
10
|
+
export const SCHEMA_VERSION = 1;
|
|
11
|
+
export function manifestPath(dir) {
|
|
12
|
+
return path.join(dir, MANIFEST_FILE);
|
|
13
|
+
}
|
|
14
|
+
/** The manifest, or undefined when the directory has none. Rejects another layout version, and a directory holding other files. */
|
|
15
|
+
export async function readManifest(dir) {
|
|
16
|
+
let contents;
|
|
17
|
+
try {
|
|
18
|
+
contents = await readFile(manifestPath(dir), "utf8");
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
if (error.code !== "ENOENT") {
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
await rejectForeignFiles(dir);
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
const manifest = JSON.parse(contents);
|
|
28
|
+
checkSchemaVersion(dir, manifest.schemaVersion);
|
|
29
|
+
return manifest;
|
|
30
|
+
}
|
|
31
|
+
/** The names a files store directory may hold besides the manifest. */
|
|
32
|
+
function isOwnEntry(name) {
|
|
33
|
+
return name === SEGMENTS_DIR || name === LOCK_FILE || name.startsWith(`${LOCK_FILE}.`) || name.startsWith(`${MANIFEST_FILE}.`);
|
|
34
|
+
}
|
|
35
|
+
/** True when the directory holds files that are not a files store's: a store built by an earlier Memento, or someone's own directory. */
|
|
36
|
+
export async function hasForeignFiles(dir) {
|
|
37
|
+
const names = await readdir(dir).catch(() => []);
|
|
38
|
+
return names.some((name) => name !== MANIFEST_FILE && !isOwnEntry(name));
|
|
39
|
+
}
|
|
40
|
+
/** A directory without a manifest that holds other files is not a new store; writing one there would mix the two. */
|
|
41
|
+
async function rejectForeignFiles(dir) {
|
|
42
|
+
if (await hasForeignFiles(dir)) {
|
|
43
|
+
throw new Error(`store at ${dir} holds files that are not a files store's; a store built by an earlier Memento must be rebuilt`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export function checkSchemaVersion(dir, found) {
|
|
47
|
+
if (found === SCHEMA_VERSION) {
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (found > SCHEMA_VERSION) {
|
|
51
|
+
throw new Error(`store at ${dir} uses schema ${found}, written by a newer Memento; this version reads ${SCHEMA_VERSION}`);
|
|
52
|
+
}
|
|
53
|
+
throw new Error(`store at ${dir} uses schema ${found}; this version needs ${SCHEMA_VERSION} and cannot migrate it yet`);
|
|
54
|
+
}
|
|
55
|
+
/** The manifest file's stamp, or undefined when there is none. */
|
|
56
|
+
export async function manifestStamp(dir) {
|
|
57
|
+
try {
|
|
58
|
+
const info = await stat(manifestPath(dir));
|
|
59
|
+
return { ino: info.ino, mtimeMs: info.mtimeMs };
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
if (error.code === "ENOENT") {
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* The commit: writes the manifest to a temporary name, syncs it, renames it
|
|
70
|
+
* over the live one, and syncs the directory so the rename is durable. The
|
|
71
|
+
* caller has synced the segment files first.
|
|
72
|
+
*/
|
|
73
|
+
export async function commitManifest(dir, manifest) {
|
|
74
|
+
const temporary = path.join(dir, `${MANIFEST_FILE}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);
|
|
75
|
+
await writeSynced(temporary, JSON.stringify(manifest));
|
|
76
|
+
await rename(temporary, manifestPath(dir));
|
|
77
|
+
await syncDirectory(dir);
|
|
78
|
+
const stamp = await manifestStamp(dir);
|
|
79
|
+
return stamp;
|
|
80
|
+
}
|
|
81
|
+
/** Writes a file and waits for its bytes to reach the disk. */
|
|
82
|
+
export async function writeSynced(file, contents) {
|
|
83
|
+
const handle = await open(file, "w");
|
|
84
|
+
try {
|
|
85
|
+
await handle.writeFile(contents);
|
|
86
|
+
await handle.sync();
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
await handle.close();
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Syncs a directory, so renames and new names in it are durable. Some file
|
|
94
|
+
* systems refuse to sync a directory handle; the rename itself is still
|
|
95
|
+
* atomic there, so that refusal is not an error for the store.
|
|
96
|
+
*/
|
|
97
|
+
export async function syncDirectory(dir) {
|
|
98
|
+
const handle = await open(dir, "r");
|
|
99
|
+
try {
|
|
100
|
+
await handle.sync();
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
const code = error.code;
|
|
104
|
+
if (code !== "EISDIR" && code !== "EPERM" && code !== "EINVAL") {
|
|
105
|
+
throw error;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
finally {
|
|
109
|
+
await handle.close();
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export type SafeDeleteResult = {
|
|
2
|
+
success: boolean;
|
|
3
|
+
message?: string;
|
|
4
|
+
};
|
|
5
|
+
/**
|
|
6
|
+
* True when `target` is inside `root` and is not `root` itself. Both must be
|
|
7
|
+
* resolved paths. A first segment of exactly `..` is the escape; a name that
|
|
8
|
+
* only begins with two dots, such as `..cache`, is an ordinary child.
|
|
9
|
+
*/
|
|
10
|
+
export declare function isStrictDescendant(root: string, target: string): boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Deletes a directory only if it is a strict descendant of `root`. Both paths
|
|
13
|
+
* are resolved through symlinks, so `target` must lie strictly inside `root`:
|
|
14
|
+
* never the root itself, never a sibling, never `..`, never a symlink that
|
|
15
|
+
* escapes. Returns a result instead of throwing.
|
|
16
|
+
*/
|
|
17
|
+
export declare function safeDeleteDirectoryWithin(root: string, target: string): SafeDeleteResult;
|
|
18
|
+
/** Deletes one file only if it is a strict descendant of `root`, with the same checks as safeDeleteDirectoryWithin. */
|
|
19
|
+
export declare function safeDeleteFileWithin(root: string, target: string): SafeDeleteResult;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Safe deletes, copied from Agency's lib/utils.ts (safeDeleteDirectoryWithin
|
|
2
|
+
// and isStrictDescendant), with a file variant. This copy ships with the
|
|
3
|
+
// package; test/safe-delete.ts is the same code for the tests and scripts.
|
|
4
|
+
// Every delete in the files engine goes through these. Never call fs.rm,
|
|
5
|
+
// rmSync or unlink directly, and never run `rm -rf`.
|
|
6
|
+
import * as fs from "node:fs";
|
|
7
|
+
import * as path from "node:path";
|
|
8
|
+
/**
|
|
9
|
+
* True when `target` is inside `root` and is not `root` itself. Both must be
|
|
10
|
+
* resolved paths. A first segment of exactly `..` is the escape; a name that
|
|
11
|
+
* only begins with two dots, such as `..cache`, is an ordinary child.
|
|
12
|
+
*/
|
|
13
|
+
export function isStrictDescendant(root, target) {
|
|
14
|
+
const relative = path.relative(root, target);
|
|
15
|
+
if (relative === "" || path.isAbsolute(relative)) {
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
const first = relative.split(path.sep)[0];
|
|
19
|
+
return first !== "..";
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Deletes a directory only if it is a strict descendant of `root`. Both paths
|
|
23
|
+
* are resolved through symlinks, so `target` must lie strictly inside `root`:
|
|
24
|
+
* never the root itself, never a sibling, never `..`, never a symlink that
|
|
25
|
+
* escapes. Returns a result instead of throwing.
|
|
26
|
+
*/
|
|
27
|
+
export function safeDeleteDirectoryWithin(root, target) {
|
|
28
|
+
return safeDeleteWithin(root, target, "directory");
|
|
29
|
+
}
|
|
30
|
+
/** Deletes one file only if it is a strict descendant of `root`, with the same checks as safeDeleteDirectoryWithin. */
|
|
31
|
+
export function safeDeleteFileWithin(root, target) {
|
|
32
|
+
return safeDeleteWithin(root, target, "file");
|
|
33
|
+
}
|
|
34
|
+
function safeDeleteWithin(root, target, kind) {
|
|
35
|
+
if (!fs.existsSync(target)) {
|
|
36
|
+
return { success: false, message: `Path does not exist: '${target}'.` };
|
|
37
|
+
}
|
|
38
|
+
let resolvedRoot;
|
|
39
|
+
let resolvedTarget;
|
|
40
|
+
try {
|
|
41
|
+
resolvedRoot = fs.realpathSync(path.resolve(root));
|
|
42
|
+
resolvedTarget = fs.realpathSync(path.resolve(target));
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
return { success: false, message: `Refusing to delete '${target}': ${errorMessage(err)}` };
|
|
46
|
+
}
|
|
47
|
+
let stat;
|
|
48
|
+
try {
|
|
49
|
+
stat = fs.statSync(resolvedTarget);
|
|
50
|
+
}
|
|
51
|
+
catch (err) {
|
|
52
|
+
return { success: false, message: `Refusing to delete '${target}': ${errorMessage(err)}` };
|
|
53
|
+
}
|
|
54
|
+
const isRightKind = kind === "file" ? stat.isFile() : stat.isDirectory();
|
|
55
|
+
if (!isRightKind) {
|
|
56
|
+
return { success: false, message: `Not a ${kind}: '${resolvedTarget}'.` };
|
|
57
|
+
}
|
|
58
|
+
if (!isStrictDescendant(resolvedRoot, resolvedTarget)) {
|
|
59
|
+
return {
|
|
60
|
+
success: false,
|
|
61
|
+
message: `Refusing to delete '${resolvedTarget}': not strictly inside '${resolvedRoot}'.`,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
if (kind === "file") {
|
|
66
|
+
fs.unlinkSync(resolvedTarget);
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
fs.rmSync(resolvedTarget, { recursive: true, force: true });
|
|
70
|
+
}
|
|
71
|
+
return { success: true };
|
|
72
|
+
}
|
|
73
|
+
catch (err) {
|
|
74
|
+
return { success: false, message: `Failed to delete '${resolvedTarget}': ${errorMessage(err)}` };
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function errorMessage(err) {
|
|
78
|
+
return err instanceof Error ? err.message : String(err);
|
|
79
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { StoreRecord } from "../shared/state.ts";
|
|
2
|
+
export declare function segmentName(write: number): string;
|
|
3
|
+
/**
|
|
4
|
+
* Writes a segment's two files, syncs them, and syncs the segments directory
|
|
5
|
+
* so their names are durable before the manifest that names them is
|
|
6
|
+
* committed. The files are opened with `w`, so an orphan from a crash is
|
|
7
|
+
* overwritten.
|
|
8
|
+
*/
|
|
9
|
+
export declare function writeSegment(dir: string, name: string, records: StoreRecord[]): Promise<void>;
|
|
10
|
+
/** Every segment name with a file on disk, including orphans a crash left. Files that are not a segment's are left out. */
|
|
11
|
+
export declare function segmentNamesOnDisk(dir: string): Promise<string[]>;
|
|
12
|
+
/** Reads a segment back into records. Rejects with the read error, such as ENOENT after a compaction. */
|
|
13
|
+
export declare function readSegment(dir: string, name: string): Promise<StoreRecord[]>;
|
|
14
|
+
/** The size of a segment's files, in bytes. */
|
|
15
|
+
export declare function segmentBytes(dir: string, name: string): Promise<number>;
|
|
16
|
+
/** Deletes a segment's files, through the safe delete, inside the store's segments directory only. A file already gone is not an error. */
|
|
17
|
+
export declare function deleteSegment(dir: string, name: string): void;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// A segment is one write of a files store, as a list of records: a JSONL file
|
|
2
|
+
// of records and a float32 file of the vectors the window records name, in
|
|
3
|
+
// order. Segments are written once and never changed.
|
|
4
|
+
import { readdir, readFile, stat } from "node:fs/promises";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { decodeVector, encodeVector } from "../shared/vectors.js";
|
|
7
|
+
import { SEGMENTS_DIR, syncDirectory, writeSynced } from "./manifest.js";
|
|
8
|
+
import { safeDeleteFileWithin } from "./safe-delete.js";
|
|
9
|
+
/** Segment names are the write counter, zero-padded to this many digits, so they list in order. */
|
|
10
|
+
const NAME_DIGITS = 6;
|
|
11
|
+
const RECORDS_SUFFIX = ".records.jsonl";
|
|
12
|
+
const VECTORS_SUFFIX = ".vectors.f32";
|
|
13
|
+
/** A segment file's name: six digits and one of the two suffixes. Anything else in the directory is not ours. */
|
|
14
|
+
const SEGMENT_FILE = /^(\d{6})\.(records\.jsonl|vectors\.f32)$/;
|
|
15
|
+
export function segmentName(write) {
|
|
16
|
+
return String(write).padStart(NAME_DIGITS, "0");
|
|
17
|
+
}
|
|
18
|
+
function recordsFile(dir, name) {
|
|
19
|
+
return path.join(dir, SEGMENTS_DIR, `${name}${RECORDS_SUFFIX}`);
|
|
20
|
+
}
|
|
21
|
+
function vectorsFile(dir, name) {
|
|
22
|
+
return path.join(dir, SEGMENTS_DIR, `${name}${VECTORS_SUFFIX}`);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Writes a segment's two files, syncs them, and syncs the segments directory
|
|
26
|
+
* so their names are durable before the manifest that names them is
|
|
27
|
+
* committed. The files are opened with `w`, so an orphan from a crash is
|
|
28
|
+
* overwritten.
|
|
29
|
+
*/
|
|
30
|
+
export async function writeSegment(dir, name, records) {
|
|
31
|
+
const lines = [];
|
|
32
|
+
const vectors = [];
|
|
33
|
+
for (const record of records) {
|
|
34
|
+
lines.push(JSON.stringify(toLine(record)));
|
|
35
|
+
if (record.kind === "windows") {
|
|
36
|
+
for (const window of record.windows) {
|
|
37
|
+
vectors.push(encodeVector(window.vector));
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
await writeSynced(recordsFile(dir, name), lines.map((line) => `${line}\n`).join(""));
|
|
42
|
+
await writeSynced(vectorsFile(dir, name), Buffer.concat(vectors));
|
|
43
|
+
await syncDirectory(path.join(dir, SEGMENTS_DIR));
|
|
44
|
+
}
|
|
45
|
+
/** Every segment name with a file on disk, including orphans a crash left. Files that are not a segment's are left out. */
|
|
46
|
+
export async function segmentNamesOnDisk(dir) {
|
|
47
|
+
const names = await readdir(path.join(dir, SEGMENTS_DIR));
|
|
48
|
+
const segments = names.map((file) => SEGMENT_FILE.exec(file)?.[1]).filter((name) => name !== undefined);
|
|
49
|
+
return [...new Set(segments)];
|
|
50
|
+
}
|
|
51
|
+
/** Reads a segment back into records. Rejects with the read error, such as ENOENT after a compaction. */
|
|
52
|
+
export async function readSegment(dir, name) {
|
|
53
|
+
const [text, bytes] = await Promise.all([readFile(recordsFile(dir, name), "utf8"), readFile(vectorsFile(dir, name))]);
|
|
54
|
+
const floats = decodeVector(bytes);
|
|
55
|
+
let offset = 0;
|
|
56
|
+
const records = [];
|
|
57
|
+
for (const line of text.split("\n")) {
|
|
58
|
+
if (line === "") {
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const parsed = JSON.parse(line);
|
|
62
|
+
if (parsed.kind === "windows") {
|
|
63
|
+
const windows = parsed.windows.map((window) => {
|
|
64
|
+
const vector = floats.slice(offset, offset + parsed.dimension);
|
|
65
|
+
offset += parsed.dimension;
|
|
66
|
+
return { ...window, vector };
|
|
67
|
+
});
|
|
68
|
+
records.push({ kind: "windows", id: parsed.id, windows });
|
|
69
|
+
}
|
|
70
|
+
else if (parsed.kind === "document") {
|
|
71
|
+
records.push({ kind: "document", document: fromDocumentLine(parsed.document) });
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
records.push(parsed);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return records;
|
|
78
|
+
}
|
|
79
|
+
/** The size of a segment's files, in bytes. */
|
|
80
|
+
export async function segmentBytes(dir, name) {
|
|
81
|
+
const sizes = await Promise.all([stat(recordsFile(dir, name)), stat(vectorsFile(dir, name))]);
|
|
82
|
+
return sizes.reduce((sum, info) => sum + info.size, 0);
|
|
83
|
+
}
|
|
84
|
+
/** Deletes a segment's files, through the safe delete, inside the store's segments directory only. A file already gone is not an error. */
|
|
85
|
+
export function deleteSegment(dir, name) {
|
|
86
|
+
const root = path.join(dir, SEGMENTS_DIR);
|
|
87
|
+
for (const file of [recordsFile(dir, name), vectorsFile(dir, name)]) {
|
|
88
|
+
const result = safeDeleteFileWithin(root, file);
|
|
89
|
+
if (!result.success && !result.message?.includes("does not exist")) {
|
|
90
|
+
throw new Error(result.message);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
function toLine(record) {
|
|
95
|
+
switch (record.kind) {
|
|
96
|
+
case "document":
|
|
97
|
+
return { kind: "document", document: toDocumentLine(record.document) };
|
|
98
|
+
case "windows":
|
|
99
|
+
return {
|
|
100
|
+
kind: "windows",
|
|
101
|
+
id: record.id,
|
|
102
|
+
dimension: record.windows[0]?.vector.length ?? 0,
|
|
103
|
+
windows: record.windows.map(({ n, start, end }) => ({ n, start, end })),
|
|
104
|
+
};
|
|
105
|
+
default:
|
|
106
|
+
return record;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
function toDocumentLine(doc) {
|
|
110
|
+
const line = { id: doc.id, title: doc.title, text: doc.text, meta: doc.meta ?? {} };
|
|
111
|
+
if (doc.createdAt !== undefined) {
|
|
112
|
+
line.createdAt = doc.createdAt.getTime();
|
|
113
|
+
}
|
|
114
|
+
if (doc.sourcePath !== undefined) {
|
|
115
|
+
line.sourcePath = doc.sourcePath;
|
|
116
|
+
}
|
|
117
|
+
return line;
|
|
118
|
+
}
|
|
119
|
+
function fromDocumentLine(line) {
|
|
120
|
+
const doc = { id: line.id, title: line.title, text: line.text, meta: line.meta };
|
|
121
|
+
if (line.createdAt !== undefined) {
|
|
122
|
+
doc.createdAt = new Date(line.createdAt);
|
|
123
|
+
}
|
|
124
|
+
if (line.sourcePath !== undefined) {
|
|
125
|
+
doc.sourcePath = line.sourcePath;
|
|
126
|
+
}
|
|
127
|
+
return doc;
|
|
128
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { FileStat } from "../../files.ts";
|
|
2
|
+
import type { Filter } from "../../types.ts";
|
|
3
|
+
import type { DocumentWindows, Engine, ScoredDocument, StoredDocument, StoreSettings, WindowHit, WriteBatch } from "../types.ts";
|
|
4
|
+
export declare function openMemoryEngine(): Promise<MemoryEngine>;
|
|
5
|
+
export declare class MemoryEngine implements Engine {
|
|
6
|
+
readonly kind = "memory";
|
|
7
|
+
private state;
|
|
8
|
+
private store;
|
|
9
|
+
/** A memory store is always new, so the defaults are its settings. Called again, it returns what is there. */
|
|
10
|
+
initialize(defaults: StoreSettings): Promise<StoreSettings>;
|
|
11
|
+
getSettings(): Promise<StoreSettings>;
|
|
12
|
+
setSettings(patch: Partial<StoreSettings>): Promise<void>;
|
|
13
|
+
getDocsById(ids: string[]): Promise<StoredDocument[]>;
|
|
14
|
+
getWindows(ids: string[]): Promise<DocumentWindows[]>;
|
|
15
|
+
getDocumentCount(): Promise<number>;
|
|
16
|
+
getFileCount(): Promise<number>;
|
|
17
|
+
statFiles(paths: string[]): Promise<FileStat[]>;
|
|
18
|
+
/** An estimate: the characters of every document at two bytes each, plus the vectors' bytes. */
|
|
19
|
+
getSizeBytes(): Promise<number>;
|
|
20
|
+
write(batch: WriteBatch): Promise<void>;
|
|
21
|
+
keywordSearch(terms: string[], filter: Filter | undefined, limit: number): Promise<ScoredDocument[]>;
|
|
22
|
+
getNewest(filter: Filter | undefined, limit: number): Promise<StoredDocument[]>;
|
|
23
|
+
embeddingsSearch(query: Float32Array, filter: Filter | undefined, limit: number): Promise<WindowHit[]>;
|
|
24
|
+
check(): Promise<void>;
|
|
25
|
+
/** Lets the store go. A second call does nothing. */
|
|
26
|
+
close(): Promise<void>;
|
|
27
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { copySettings, mergeSettings } from "../shared/settings.js";
|
|
2
|
+
import { StoreState } from "../shared/state.js";
|
|
3
|
+
/** Each character of title, text and meta is counted as this many bytes in getSizeBytes. */
|
|
4
|
+
const BYTES_PER_CHAR = 2;
|
|
5
|
+
export async function openMemoryEngine() {
|
|
6
|
+
return new MemoryEngine();
|
|
7
|
+
}
|
|
8
|
+
export class MemoryEngine {
|
|
9
|
+
kind = "memory";
|
|
10
|
+
state = new StoreState();
|
|
11
|
+
store() {
|
|
12
|
+
if (this.state === undefined) {
|
|
13
|
+
throw new Error("store is closed");
|
|
14
|
+
}
|
|
15
|
+
return this.state;
|
|
16
|
+
}
|
|
17
|
+
// Settings
|
|
18
|
+
/** A memory store is always new, so the defaults are its settings. Called again, it returns what is there. */
|
|
19
|
+
async initialize(defaults) {
|
|
20
|
+
const state = this.store();
|
|
21
|
+
state.settings ??= copySettings(defaults);
|
|
22
|
+
return this.getSettings();
|
|
23
|
+
}
|
|
24
|
+
async getSettings() {
|
|
25
|
+
const settings = this.store().settings;
|
|
26
|
+
if (settings === undefined) {
|
|
27
|
+
throw new Error("store is not initialized");
|
|
28
|
+
}
|
|
29
|
+
return copySettings(settings);
|
|
30
|
+
}
|
|
31
|
+
async setSettings(patch) {
|
|
32
|
+
this.store().settings = mergeSettings(await this.getSettings(), patch);
|
|
33
|
+
}
|
|
34
|
+
// Reading
|
|
35
|
+
async getDocsById(ids) {
|
|
36
|
+
return this.store().getDocsById(ids);
|
|
37
|
+
}
|
|
38
|
+
async getWindows(ids) {
|
|
39
|
+
return this.store().getWindows(ids);
|
|
40
|
+
}
|
|
41
|
+
async getDocumentCount() {
|
|
42
|
+
return this.store().documentCount();
|
|
43
|
+
}
|
|
44
|
+
async getFileCount() {
|
|
45
|
+
return this.store().fileCount();
|
|
46
|
+
}
|
|
47
|
+
async statFiles(paths) {
|
|
48
|
+
return this.store().statFiles(paths);
|
|
49
|
+
}
|
|
50
|
+
/** An estimate: the characters of every document at two bytes each, plus the vectors' bytes. */
|
|
51
|
+
async getSizeBytes() {
|
|
52
|
+
const state = this.store();
|
|
53
|
+
let bytes = 0;
|
|
54
|
+
for (const doc of Object.values(state.documents)) {
|
|
55
|
+
bytes += BYTES_PER_CHAR * (doc.title.length + doc.text.length + JSON.stringify(doc.meta ?? {}).length);
|
|
56
|
+
}
|
|
57
|
+
for (const windows of Object.values(state.windows)) {
|
|
58
|
+
for (const window of windows) {
|
|
59
|
+
bytes += window.vector.byteLength;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return bytes;
|
|
63
|
+
}
|
|
64
|
+
// Writing
|
|
65
|
+
async write(batch) {
|
|
66
|
+
const state = this.store();
|
|
67
|
+
state.commit(state.prepare(batch));
|
|
68
|
+
}
|
|
69
|
+
// Searching
|
|
70
|
+
async keywordSearch(terms, filter, limit) {
|
|
71
|
+
return this.store().keywordSearch(terms, filter, limit);
|
|
72
|
+
}
|
|
73
|
+
async getNewest(filter, limit) {
|
|
74
|
+
return this.store().getNewest(filter, limit);
|
|
75
|
+
}
|
|
76
|
+
async embeddingsSearch(query, filter, limit) {
|
|
77
|
+
return this.store().embeddingsSearch(query, filter, limit);
|
|
78
|
+
}
|
|
79
|
+
// Lifecycle
|
|
80
|
+
async check() {
|
|
81
|
+
this.store().check();
|
|
82
|
+
}
|
|
83
|
+
/** Lets the store go. A second call does nothing. */
|
|
84
|
+
async close() {
|
|
85
|
+
this.state = undefined;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Storage } from "../types.ts";
|
|
2
|
+
import type { Engine, StoreSettings } from "./types.ts";
|
|
3
|
+
export declare function openEngine(storage: Storage): Promise<Engine>;
|
|
4
|
+
/** Whether a store has been created at `storage`. A memory store never exists before it is opened. Creates nothing. */
|
|
5
|
+
export declare function engineExists(storage: Storage): Promise<boolean>;
|
|
6
|
+
/** The settings a store records, or undefined when there is no store. Loads no documents and creates nothing. */
|
|
7
|
+
export declare function engineSettings(storage: Storage): Promise<StoreSettings | undefined>;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { filesStoreExists, filesStoreSettings, openFilesEngine } from "./files/engine.js";
|
|
2
|
+
import { openMemoryEngine } from "./memory/engine.js";
|
|
3
|
+
export async function openEngine(storage) {
|
|
4
|
+
switch (storage.type) {
|
|
5
|
+
case "memory":
|
|
6
|
+
return openMemoryEngine();
|
|
7
|
+
case "files":
|
|
8
|
+
return openFilesEngine(storage);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/** Whether a store has been created at `storage`. A memory store never exists before it is opened. Creates nothing. */
|
|
12
|
+
export async function engineExists(storage) {
|
|
13
|
+
switch (storage.type) {
|
|
14
|
+
case "memory":
|
|
15
|
+
return false;
|
|
16
|
+
case "files":
|
|
17
|
+
return filesStoreExists(storage);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** The settings a store records, or undefined when there is no store. Loads no documents and creates nothing. */
|
|
21
|
+
export async function engineSettings(storage) {
|
|
22
|
+
switch (storage.type) {
|
|
23
|
+
case "memory":
|
|
24
|
+
return undefined;
|
|
25
|
+
case "files":
|
|
26
|
+
return filesStoreSettings(storage);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { StoredDocument } from "../types.ts";
|
|
2
|
+
import type { Filter } from "../../types.ts";
|
|
3
|
+
export type Matcher = (doc: StoredDocument) => boolean;
|
|
4
|
+
/** True when the document passes the filter. No filter passes everything. For many documents, compile the filter once. */
|
|
5
|
+
export declare function matchesFilter(doc: StoredDocument, filter: Filter | undefined): boolean;
|
|
6
|
+
/** The filter as a function of one document, built once: an `ids` list becomes a Set, so a long list costs the same per document as a short one. */
|
|
7
|
+
export declare function compileMatcher(filter: Filter | undefined): Matcher;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/** True when the document passes the filter. No filter passes everything. For many documents, compile the filter once. */
|
|
2
|
+
export function matchesFilter(doc, filter) {
|
|
3
|
+
return compileMatcher(filter)(doc);
|
|
4
|
+
}
|
|
5
|
+
/** The filter as a function of one document, built once: an `ids` list becomes a Set, so a long list costs the same per document as a short one. */
|
|
6
|
+
export function compileMatcher(filter) {
|
|
7
|
+
if (filter === undefined) {
|
|
8
|
+
return () => true;
|
|
9
|
+
}
|
|
10
|
+
if ("and" in filter) {
|
|
11
|
+
const children = filter.and.map(compileMatcher);
|
|
12
|
+
return (doc) => children.every((child) => child(doc));
|
|
13
|
+
}
|
|
14
|
+
if ("or" in filter) {
|
|
15
|
+
const children = filter.or.map(compileMatcher);
|
|
16
|
+
return (doc) => children.some((child) => child(doc));
|
|
17
|
+
}
|
|
18
|
+
if ("not" in filter) {
|
|
19
|
+
const inner = compileMatcher(filter.not);
|
|
20
|
+
return (doc) => !inner(doc);
|
|
21
|
+
}
|
|
22
|
+
const ids = filter.ids === undefined ? undefined : new Set(filter.ids);
|
|
23
|
+
return (doc) => matchesCondition(doc, filter, ids);
|
|
24
|
+
}
|
|
25
|
+
function matchesCondition(doc, condition, ids) {
|
|
26
|
+
const { date, meta, lengthChars } = condition;
|
|
27
|
+
// A document without a date never matches a date condition, and its `not` matches it.
|
|
28
|
+
if (date?.after !== undefined && !(doc.createdAt !== undefined && doc.createdAt.getTime() >= date.after.getTime())) {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
if (date?.before !== undefined && !(doc.createdAt !== undefined && doc.createdAt.getTime() <= date.before.getTime())) {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
for (const [key, wanted] of definedEntries(meta ?? {})) {
|
|
35
|
+
if (!metaMatches(doc.meta ?? {}, key, wanted)) {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (ids !== undefined && !ids.has(doc.id)) {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
if (lengthChars?.min !== undefined && doc.text.length < lengthChars.min) {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
if (lengthChars?.max !== undefined && doc.text.length > lengthChars.max) {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* A meta value equals the filter's after booleans become 1 and 0 on both
|
|
52
|
+
* sides. A missing key is null, so a null filter matches a missing key and a
|
|
53
|
+
* stored null alike. A stored array or object never matches.
|
|
54
|
+
*/
|
|
55
|
+
function metaMatches(meta, key, wanted) {
|
|
56
|
+
// hasOwn, so a key such as "constructor" that the document lacks reads as missing, not as Object.prototype's.
|
|
57
|
+
const stored = Object.hasOwn(meta, key) ? meta[key] : null;
|
|
58
|
+
if (typeof stored === "object" && stored !== null) {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
return comparable(stored) === comparable(wanted);
|
|
62
|
+
}
|
|
63
|
+
function comparable(value) {
|
|
64
|
+
if (typeof value === "boolean") {
|
|
65
|
+
return value ? 1 : 0;
|
|
66
|
+
}
|
|
67
|
+
return value;
|
|
68
|
+
}
|
|
69
|
+
/** The entries whose value is not undefined; `{ year: undefined }` means the same as leaving `year` out. */
|
|
70
|
+
function definedEntries(object) {
|
|
71
|
+
return Object.entries(object).filter(([, value]) => value !== undefined);
|
|
72
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type DocumentTokens } from "./tokens.ts";
|
|
2
|
+
/** BM25 weight of a match in the title, relative to TEXT_WEIGHT. */
|
|
3
|
+
export declare const TITLE_WEIGHT = 2;
|
|
4
|
+
export declare const TEXT_WEIGHT = 1;
|
|
5
|
+
export type ScoredId = {
|
|
6
|
+
id: string;
|
|
7
|
+
score: number;
|
|
8
|
+
};
|
|
9
|
+
/** A test of which documents the filter allows, or undefined for every document. */
|
|
10
|
+
export type Allowed = ((id: string) => boolean) | undefined;
|
|
11
|
+
export declare class KeywordIndex {
|
|
12
|
+
private readonly postings;
|
|
13
|
+
private readonly tokens;
|
|
14
|
+
private documents;
|
|
15
|
+
private totalLength;
|
|
16
|
+
/** Indexes a document that is not in the index. A replaced document is removed first. */
|
|
17
|
+
add(id: string, tokens: DocumentTokens): void;
|
|
18
|
+
/** Removes a document from the index. A document that is not indexed is left alone. */
|
|
19
|
+
remove(id: string): void;
|
|
20
|
+
has(id: string): boolean;
|
|
21
|
+
/**
|
|
22
|
+
* The documents matching any term, best first, after `allowed`, at most
|
|
23
|
+
* `limit`. Equal scores order by id in code point order before the limit.
|
|
24
|
+
*/
|
|
25
|
+
search(terms: string[], allowed: Allowed, limit: number): ScoredId[];
|
|
26
|
+
private idf;
|
|
27
|
+
}
|