@clockgrove/assetgrove-search 0.0.0-stage → 0.3.2
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/LICENSE +21 -0
- package/README.md +12 -2
- package/dist/embedder.d.ts +20 -0
- package/dist/embedder.js +21 -0
- package/dist/errors.d.ts +12 -0
- package/dist/errors.js +12 -0
- package/dist/extension.d.ts +38 -0
- package/dist/extension.js +589 -0
- package/dist/find.d.ts +115 -0
- package/dist/find.js +203 -0
- package/dist/flatten.d.ts +15 -0
- package/dist/flatten.js +19 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +18 -0
- package/dist/indexer.d.ts +48 -0
- package/dist/indexer.js +187 -0
- package/dist/lance-store.d.ts +98 -0
- package/dist/lance-store.js +456 -0
- package/dist/library.d.ts +63 -0
- package/dist/library.js +32 -0
- package/dist/lock.d.ts +11 -0
- package/dist/lock.js +176 -0
- package/dist/memory-store.d.ts +26 -0
- package/dist/memory-store.js +111 -0
- package/dist/model-manifest.d.ts +20 -0
- package/dist/model-manifest.js +14 -0
- package/dist/model-manifest.json +38 -0
- package/dist/outliers.d.ts +14 -0
- package/dist/outliers.js +41 -0
- package/dist/platform.d.ts +4 -0
- package/dist/platform.js +6 -0
- package/dist/route-embedder.d.ts +20 -0
- package/dist/route-embedder.js +47 -0
- package/dist/scripted.d.ts +15 -0
- package/dist/scripted.js +35 -0
- package/dist/setup.d.ts +26 -0
- package/dist/setup.js +60 -0
- package/dist/siglip2.d.ts +6 -0
- package/dist/siglip2.js +84 -0
- package/dist/store.d.ts +129 -0
- package/dist/store.js +2 -0
- package/dist/tokens.d.ts +6 -0
- package/dist/tokens.js +22 -0
- package/dist/where.d.ts +20 -0
- package/dist/where.js +164 -0
- package/package.json +55 -3
- package/skills/assetgrove-search/SKILL.md +41 -0
- package/skills/assetgrove-search/references/commands.md +65 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type * as Arrow from "apache-arrow";
|
|
2
|
+
import type * as Lance from "@lancedb/lancedb";
|
|
3
|
+
import type { BuiltFrom, CachedVector, EmbedderRecord, Hit, Row, SourceRow, Store, StoreQuery } from "./store.ts";
|
|
4
|
+
export interface LanceModules {
|
|
5
|
+
lancedb: typeof Lance;
|
|
6
|
+
arrow: typeof Arrow;
|
|
7
|
+
}
|
|
8
|
+
export interface LanceStoreOptions {
|
|
9
|
+
/** The embedder whose vectors the rows table holds. */
|
|
10
|
+
embedder: {
|
|
11
|
+
id: string;
|
|
12
|
+
revision: string;
|
|
13
|
+
dimension: number;
|
|
14
|
+
};
|
|
15
|
+
/** For tests: the platform to check instead of this process's. */
|
|
16
|
+
platform?: {
|
|
17
|
+
platform: string;
|
|
18
|
+
arch: string;
|
|
19
|
+
};
|
|
20
|
+
/** For tests: how LanceDB is imported. */
|
|
21
|
+
importLance?: () => Promise<LanceModules>;
|
|
22
|
+
/** Object-store options handed to LanceDB, and nothing else. */
|
|
23
|
+
storageOptions?: Record<string, string>;
|
|
24
|
+
/** The location is an object-store URI, not a local folder: table presence comes from the connection. */
|
|
25
|
+
remote?: boolean;
|
|
26
|
+
}
|
|
27
|
+
/** `rows_<id>_<revision>` made safe for a table name. */
|
|
28
|
+
export declare function rowsTableName(embedder: {
|
|
29
|
+
id: string;
|
|
30
|
+
revision: string;
|
|
31
|
+
}): string;
|
|
32
|
+
/**
|
|
33
|
+
* `sources_<id>_<revision>` and `built_<id>_<revision>`: freshness and built-from belong to one
|
|
34
|
+
* rows table, so one embedder's index is never judged by what another indexed.
|
|
35
|
+
*/
|
|
36
|
+
export declare function sourcesTableName(embedder: {
|
|
37
|
+
id: string;
|
|
38
|
+
revision: string;
|
|
39
|
+
}): string;
|
|
40
|
+
export declare function builtTableName(embedder: {
|
|
41
|
+
id: string;
|
|
42
|
+
revision: string;
|
|
43
|
+
}): string;
|
|
44
|
+
export declare class LanceStore implements Store {
|
|
45
|
+
readonly dir: string;
|
|
46
|
+
private readonly m;
|
|
47
|
+
private readonly dimension;
|
|
48
|
+
private readonly storageOptions;
|
|
49
|
+
private readonly remote;
|
|
50
|
+
private readonly rowsName;
|
|
51
|
+
private readonly sourcesName;
|
|
52
|
+
private readonly builtName;
|
|
53
|
+
private db;
|
|
54
|
+
private readonly tables;
|
|
55
|
+
private constructor();
|
|
56
|
+
/**
|
|
57
|
+
* Opens the store at `dir` without writing. On darwin-x64 it refuses with
|
|
58
|
+
* `extension_unavailable` (reason `platform`) before LanceDB is imported.
|
|
59
|
+
*/
|
|
60
|
+
static open(dir: string, options: LanceStoreOptions): Promise<LanceStore>;
|
|
61
|
+
private schemas;
|
|
62
|
+
private connection;
|
|
63
|
+
/**
|
|
64
|
+
* The table, or undefined when it is missing in read mode. A table folder without
|
|
65
|
+
* `_versions` (found by stat), or a store folder deleted under an open handle, means rebuild:
|
|
66
|
+
* a writer recreates the table, and recreating the rows table also forgets `sources`, so the
|
|
67
|
+
* next freshness pass re-adds every file.
|
|
68
|
+
*/
|
|
69
|
+
private table;
|
|
70
|
+
private mergeInto;
|
|
71
|
+
private deleteFrom;
|
|
72
|
+
private select;
|
|
73
|
+
upsert(rows: Row[]): Promise<void>;
|
|
74
|
+
remove(keys: string[]): Promise<void>;
|
|
75
|
+
removePaths(tree: string, paths: string[]): Promise<void>;
|
|
76
|
+
private toRow;
|
|
77
|
+
query(q: StoreQuery): Promise<Hit[]>;
|
|
78
|
+
private hasIndex;
|
|
79
|
+
embedder(): Promise<EmbedderRecord | undefined>;
|
|
80
|
+
recordEmbedder(record: EmbedderRecord): Promise<void>;
|
|
81
|
+
recordBuiltFrom(tree: string, built: BuiltFrom): Promise<void>;
|
|
82
|
+
builtFrom(tree: string): Promise<BuiltFrom | undefined>;
|
|
83
|
+
sources(tree: string): Promise<SourceRow[]>;
|
|
84
|
+
putSources(rows: SourceRow[]): Promise<void>;
|
|
85
|
+
removeSources(tree: string, paths: string[]): Promise<void>;
|
|
86
|
+
cachedVectors(embedder: string, keys: {
|
|
87
|
+
sha256: string;
|
|
88
|
+
view: string;
|
|
89
|
+
}[]): Promise<CachedVector[]>;
|
|
90
|
+
cacheVectors(embedder: string, vectors: CachedVector[]): Promise<void>;
|
|
91
|
+
/**
|
|
92
|
+
* Builds the missing scalar and full-text indexes, then compacts every table and brings its
|
|
93
|
+
* indexes up to date. Run by a writer under the write lock after a batch, never per upsert.
|
|
94
|
+
*/
|
|
95
|
+
optimize(): Promise<void>;
|
|
96
|
+
/** Closes the open tables and the connection. */
|
|
97
|
+
close(): void;
|
|
98
|
+
}
|
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The LanceDB store (design section 7.3): one rows table per embedder and revision, with its own
|
|
3
|
+
* `sources` table for freshness and `built` table recording what each tree's rows were built
|
|
4
|
+
* from, and one `vectors` table caching vectors by content and embedder. LanceDB is pinned
|
|
5
|
+
* exactly and imported only after the platform check.
|
|
6
|
+
*
|
|
7
|
+
* The store takes no lock itself: a writer holds the package's write lock (`lock.ts`) around
|
|
8
|
+
* every write and `optimize()`. Reads never create, repair or write anything.
|
|
9
|
+
*/
|
|
10
|
+
import { rm, stat } from "node:fs/promises";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import { assertSupportedPlatform } from "./platform.js";
|
|
13
|
+
import { compileFilter } from "./where.js";
|
|
14
|
+
const importLanceDefault = async () => ({
|
|
15
|
+
lancedb: await import("@lancedb/lancedb"),
|
|
16
|
+
arrow: await import("apache-arrow"),
|
|
17
|
+
});
|
|
18
|
+
const ROW_STRINGS = [
|
|
19
|
+
"key",
|
|
20
|
+
"tree",
|
|
21
|
+
"game",
|
|
22
|
+
"id",
|
|
23
|
+
"address",
|
|
24
|
+
"source",
|
|
25
|
+
"kind",
|
|
26
|
+
"subject",
|
|
27
|
+
"form",
|
|
28
|
+
"state",
|
|
29
|
+
"bible",
|
|
30
|
+
"license",
|
|
31
|
+
"origin",
|
|
32
|
+
"declaredOrigin",
|
|
33
|
+
"originEvidence",
|
|
34
|
+
"originSource",
|
|
35
|
+
"originLicense",
|
|
36
|
+
"digitalSourceType",
|
|
37
|
+
"title",
|
|
38
|
+
"description",
|
|
39
|
+
"text",
|
|
40
|
+
"path",
|
|
41
|
+
"sha256",
|
|
42
|
+
"view",
|
|
43
|
+
"mediaType",
|
|
44
|
+
"mediaSha256",
|
|
45
|
+
"mediaStatus",
|
|
46
|
+
"mediaReason",
|
|
47
|
+
];
|
|
48
|
+
const ORIGIN_COLUMNS = [
|
|
49
|
+
"origin",
|
|
50
|
+
"declaredOrigin",
|
|
51
|
+
"originEvidence",
|
|
52
|
+
"originSource",
|
|
53
|
+
"originLicense",
|
|
54
|
+
"digitalSourceType",
|
|
55
|
+
];
|
|
56
|
+
const REQUIRED = new Set(["key", "tree", "id", "address", "source", "path", "sha256"]);
|
|
57
|
+
/** Scalar indexes of design section 7.3; `tree` has many values, the others few. */
|
|
58
|
+
const SCALAR_INDEXES = [
|
|
59
|
+
["tree", "btree"],
|
|
60
|
+
["source", "bitmap"],
|
|
61
|
+
["kind", "bitmap"],
|
|
62
|
+
["state", "bitmap"],
|
|
63
|
+
];
|
|
64
|
+
const sqlString = (s) => `'${s.replaceAll("'", "''")}'`;
|
|
65
|
+
const sqlList = (xs) => xs.map(sqlString).join(", ");
|
|
66
|
+
const byKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
|
|
67
|
+
const tableSuffix = (embedder) => {
|
|
68
|
+
const safe = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "_");
|
|
69
|
+
return `${safe(embedder.id)}_${safe(embedder.revision)}`;
|
|
70
|
+
};
|
|
71
|
+
/** `rows_<id>_<revision>` made safe for a table name. */
|
|
72
|
+
export function rowsTableName(embedder) {
|
|
73
|
+
return `rows_v3_${tableSuffix(embedder)}`;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* `sources_<id>_<revision>` and `built_<id>_<revision>`: freshness and built-from belong to one
|
|
77
|
+
* rows table, so one embedder's index is never judged by what another indexed.
|
|
78
|
+
*/
|
|
79
|
+
export function sourcesTableName(embedder) {
|
|
80
|
+
return `sources_v3_${tableSuffix(embedder)}`;
|
|
81
|
+
}
|
|
82
|
+
export function builtTableName(embedder) {
|
|
83
|
+
return `built_v3_${tableSuffix(embedder)}`;
|
|
84
|
+
}
|
|
85
|
+
/** The one-row table recording which embedder made the store's vectors. */
|
|
86
|
+
const EMBEDDER_TABLE = "embedder";
|
|
87
|
+
export class LanceStore {
|
|
88
|
+
dir;
|
|
89
|
+
m;
|
|
90
|
+
dimension;
|
|
91
|
+
storageOptions;
|
|
92
|
+
remote;
|
|
93
|
+
rowsName;
|
|
94
|
+
sourcesName;
|
|
95
|
+
builtName;
|
|
96
|
+
db;
|
|
97
|
+
tables = new Map();
|
|
98
|
+
constructor(dir, m, options) {
|
|
99
|
+
this.dir = dir;
|
|
100
|
+
this.m = m;
|
|
101
|
+
this.dimension = options.embedder.dimension;
|
|
102
|
+
this.storageOptions = options.storageOptions;
|
|
103
|
+
this.remote = options.remote ?? false;
|
|
104
|
+
this.rowsName = rowsTableName(options.embedder);
|
|
105
|
+
this.sourcesName = sourcesTableName(options.embedder);
|
|
106
|
+
this.builtName = builtTableName(options.embedder);
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Opens the store at `dir` without writing. On darwin-x64 it refuses with
|
|
110
|
+
* `extension_unavailable` (reason `platform`) before LanceDB is imported.
|
|
111
|
+
*/
|
|
112
|
+
static async open(dir, options) {
|
|
113
|
+
assertSupportedPlatform(options.platform);
|
|
114
|
+
const m = await (options.importLance ?? importLanceDefault)();
|
|
115
|
+
return new LanceStore(dir, m, options);
|
|
116
|
+
}
|
|
117
|
+
schemas(name) {
|
|
118
|
+
const { Schema, Field, Utf8, Float32, Float64, FixedSizeList, List } = this.m.arrow;
|
|
119
|
+
const str = (n, nullable = true) => new Field(n, new Utf8(), nullable);
|
|
120
|
+
const num = (n) => new Field(n, new Float64(), false);
|
|
121
|
+
const vec = (n) => new Field(n, new FixedSizeList(this.dimension, new Field("item", new Float32(), true)), true);
|
|
122
|
+
if (name === this.rowsName) {
|
|
123
|
+
return new Schema([
|
|
124
|
+
...ROW_STRINGS.map((n) => str(n, !REQUIRED.has(n))),
|
|
125
|
+
new Field("width", new Float64(), true),
|
|
126
|
+
new Field("height", new Float64(), true),
|
|
127
|
+
new Field("durationS", new Float64(), true),
|
|
128
|
+
new Field("tempo", new Float64(), true),
|
|
129
|
+
new Field("tags", new List(new Field("item", new Utf8(), true)), true),
|
|
130
|
+
vec("imageVec"),
|
|
131
|
+
vec("textVec"),
|
|
132
|
+
]);
|
|
133
|
+
}
|
|
134
|
+
if (name === this.sourcesName) {
|
|
135
|
+
return new Schema([
|
|
136
|
+
str("tree", false),
|
|
137
|
+
str("path", false),
|
|
138
|
+
num("size"),
|
|
139
|
+
num("mtimeMs"),
|
|
140
|
+
str("sha256", false),
|
|
141
|
+
str("meta", false),
|
|
142
|
+
]);
|
|
143
|
+
}
|
|
144
|
+
if (name === "vectors") {
|
|
145
|
+
return new Schema([
|
|
146
|
+
str("sha256", false),
|
|
147
|
+
str("view", false),
|
|
148
|
+
str("embedder", false),
|
|
149
|
+
new Field("vec", new List(new Field("item", new Float32(), true)), false),
|
|
150
|
+
]);
|
|
151
|
+
}
|
|
152
|
+
if (name === EMBEDDER_TABLE) {
|
|
153
|
+
return new Schema([
|
|
154
|
+
str("id", false),
|
|
155
|
+
str("revision", false),
|
|
156
|
+
str("route"),
|
|
157
|
+
str("model"),
|
|
158
|
+
num("dimension"),
|
|
159
|
+
]);
|
|
160
|
+
}
|
|
161
|
+
return new Schema([str("tree", false), str("head", false), str("at", false)]);
|
|
162
|
+
}
|
|
163
|
+
async connection() {
|
|
164
|
+
// Strong consistency: every read sees what another process committed.
|
|
165
|
+
this.db ??= await this.m.lancedb.connect(this.dir, {
|
|
166
|
+
readConsistencyInterval: 0,
|
|
167
|
+
...(this.storageOptions && { storageOptions: this.storageOptions }),
|
|
168
|
+
});
|
|
169
|
+
return this.db;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* The table, or undefined when it is missing in read mode. A table folder without
|
|
173
|
+
* `_versions` (found by stat), or a store folder deleted under an open handle, means rebuild:
|
|
174
|
+
* a writer recreates the table, and recreating the rows table also forgets `sources`, so the
|
|
175
|
+
* next freshness pass re-adds every file.
|
|
176
|
+
*/
|
|
177
|
+
async table(name, mode) {
|
|
178
|
+
const folder = join(this.dir, `${name}.lance`);
|
|
179
|
+
const present = this.remote
|
|
180
|
+
? (await (await this.connection()).tableNames()).includes(name)
|
|
181
|
+
: await stat(join(folder, "_versions")).then(() => true, () => false);
|
|
182
|
+
if (present) {
|
|
183
|
+
const open = this.tables.get(name);
|
|
184
|
+
if (open)
|
|
185
|
+
return open;
|
|
186
|
+
const t = await (await this.connection()).openTable(name);
|
|
187
|
+
this.tables.set(name, t);
|
|
188
|
+
return t;
|
|
189
|
+
}
|
|
190
|
+
this.tables.delete(name);
|
|
191
|
+
if (mode === "read")
|
|
192
|
+
return undefined;
|
|
193
|
+
if (!this.remote) {
|
|
194
|
+
await rm(folder, { recursive: true, force: true });
|
|
195
|
+
if (name === this.rowsName) {
|
|
196
|
+
this.tables.delete(this.sourcesName);
|
|
197
|
+
await rm(join(this.dir, `${this.sourcesName}.lance`), { recursive: true, force: true });
|
|
198
|
+
}
|
|
199
|
+
// A deleted store folder leaves the connection pointing at nothing; connect afresh.
|
|
200
|
+
this.db = undefined;
|
|
201
|
+
}
|
|
202
|
+
const t = await (await this.connection()).createEmptyTable(name, this.schemas(name), {
|
|
203
|
+
mode: "overwrite",
|
|
204
|
+
});
|
|
205
|
+
this.tables.set(name, t);
|
|
206
|
+
return t;
|
|
207
|
+
}
|
|
208
|
+
async mergeInto(name, on, records) {
|
|
209
|
+
if (records.length === 0)
|
|
210
|
+
return;
|
|
211
|
+
const t = (await this.table(name, "write"));
|
|
212
|
+
if (name === this.rowsName) {
|
|
213
|
+
const existing = new Set((await t.schema()).fields.map((field) => field.name));
|
|
214
|
+
const missing = this.schemas(name).fields.filter((field) => ORIGIN_COLUMNS.includes(field.name) && !existing.has(field.name));
|
|
215
|
+
if (missing.length)
|
|
216
|
+
await t.addColumns(missing.map((field) => ({
|
|
217
|
+
name: field.name,
|
|
218
|
+
valueSql: field.name === "origin" ? "CAST('unknown' AS STRING)" : "CAST(NULL AS STRING)",
|
|
219
|
+
})));
|
|
220
|
+
}
|
|
221
|
+
const data = this.m.lancedb.makeArrowTable(records, { schema: this.schemas(name) });
|
|
222
|
+
await t.mergeInsert(on).whenMatchedUpdateAll().whenNotMatchedInsertAll().execute(data);
|
|
223
|
+
}
|
|
224
|
+
async deleteFrom(name, where) {
|
|
225
|
+
const t = await this.table(name, "read");
|
|
226
|
+
if (t)
|
|
227
|
+
await t.delete(where);
|
|
228
|
+
}
|
|
229
|
+
async select(name, where) {
|
|
230
|
+
const t = await this.table(name, "read");
|
|
231
|
+
if (!t)
|
|
232
|
+
return [];
|
|
233
|
+
return (await t.query().where(where).toArray());
|
|
234
|
+
}
|
|
235
|
+
async upsert(rows) {
|
|
236
|
+
const records = rows.map((r) => {
|
|
237
|
+
const o = {};
|
|
238
|
+
for (const n of ROW_STRINGS)
|
|
239
|
+
o[n] = r[n] ?? null;
|
|
240
|
+
o.origin = r.origin ?? "unknown";
|
|
241
|
+
o.width = r.width ?? null;
|
|
242
|
+
o.height = r.height ?? null;
|
|
243
|
+
o.durationS = r.durationS ?? null;
|
|
244
|
+
o.tempo = r.tempo ?? null;
|
|
245
|
+
o.tags = r.tags ?? null;
|
|
246
|
+
o.imageVec = r.imageVec ? Array.from(r.imageVec) : null;
|
|
247
|
+
o.textVec = r.textVec ? Array.from(r.textVec) : null;
|
|
248
|
+
return o;
|
|
249
|
+
});
|
|
250
|
+
await this.mergeInto(this.rowsName, "key", records);
|
|
251
|
+
}
|
|
252
|
+
async remove(keys) {
|
|
253
|
+
if (keys.length > 0)
|
|
254
|
+
await this.deleteFrom(this.rowsName, `key IN (${sqlList(keys)})`);
|
|
255
|
+
}
|
|
256
|
+
async removePaths(tree, paths) {
|
|
257
|
+
if (paths.length === 0)
|
|
258
|
+
return;
|
|
259
|
+
await this.deleteFrom(this.rowsName, `tree = ${sqlString(tree)} AND path IN (${sqlList(paths)})`);
|
|
260
|
+
}
|
|
261
|
+
toRow(o) {
|
|
262
|
+
const r = {};
|
|
263
|
+
for (const n of ROW_STRINGS)
|
|
264
|
+
if (o[n] !== null && o[n] !== undefined)
|
|
265
|
+
r[n] = o[n];
|
|
266
|
+
for (const n of ["width", "height", "durationS", "tempo"])
|
|
267
|
+
if (typeof o[n] === "number")
|
|
268
|
+
r[n] = o[n];
|
|
269
|
+
const list = (v) => v.toArray();
|
|
270
|
+
if (o.tags !== null && o.tags !== undefined)
|
|
271
|
+
r.tags = Array.from(list(o.tags));
|
|
272
|
+
for (const n of ["imageVec", "textVec"]) {
|
|
273
|
+
if (o[n] !== null && o[n] !== undefined)
|
|
274
|
+
r[n] = Float32Array.from(list(o[n]));
|
|
275
|
+
}
|
|
276
|
+
r.origin ??= "unknown";
|
|
277
|
+
return r;
|
|
278
|
+
}
|
|
279
|
+
async query(q) {
|
|
280
|
+
const t = await this.table(this.rowsName, "read");
|
|
281
|
+
if (!t)
|
|
282
|
+
return [];
|
|
283
|
+
const fields = new Set((await t.schema()).fields.map((field) => field.name));
|
|
284
|
+
const filters = [];
|
|
285
|
+
for (const term of q.filter ?? []) {
|
|
286
|
+
if (fields.has(term.field)) {
|
|
287
|
+
filters.push(term);
|
|
288
|
+
continue;
|
|
289
|
+
}
|
|
290
|
+
if (!ORIGIN_COLUMNS.includes(term.field)) {
|
|
291
|
+
filters.push(term);
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
const value = term.field === "origin" ? "unknown" : undefined;
|
|
295
|
+
const matches = term.op === "in"
|
|
296
|
+
? value !== undefined && term.value.includes(value)
|
|
297
|
+
: term.op === "!="
|
|
298
|
+
? value === undefined || value !== term.value
|
|
299
|
+
: value !== undefined &&
|
|
300
|
+
(term.op === "="
|
|
301
|
+
? value === term.value
|
|
302
|
+
: term.op === "<"
|
|
303
|
+
? value < String(term.value)
|
|
304
|
+
: term.op === ">"
|
|
305
|
+
? value > String(term.value)
|
|
306
|
+
: false);
|
|
307
|
+
if (!matches)
|
|
308
|
+
return [];
|
|
309
|
+
}
|
|
310
|
+
const where = compileFilter(filters);
|
|
311
|
+
let hits;
|
|
312
|
+
if (q.vector) {
|
|
313
|
+
// Exact, flat search: no vector index is ever built (design section 7.3).
|
|
314
|
+
let vq = t
|
|
315
|
+
.vectorSearch(Array.from(q.vector.value))
|
|
316
|
+
.column(q.vector.column)
|
|
317
|
+
.distanceType("cosine")
|
|
318
|
+
.bypassVectorIndex()
|
|
319
|
+
.limit(q.limit);
|
|
320
|
+
if (where)
|
|
321
|
+
vq = vq.where(where);
|
|
322
|
+
const found = (await vq.toArray());
|
|
323
|
+
hits = found.map((o) => ({ row: this.toRow(o), score: 1 - o._distance }));
|
|
324
|
+
}
|
|
325
|
+
else if (q.text !== undefined) {
|
|
326
|
+
if (q.text.trim() === "" || !(await this.hasIndex(t, "text")))
|
|
327
|
+
return [];
|
|
328
|
+
let fq = t
|
|
329
|
+
.query()
|
|
330
|
+
.fullTextSearch(q.text, { columns: ["text"] })
|
|
331
|
+
.limit(q.limit);
|
|
332
|
+
if (where)
|
|
333
|
+
fq = fq.where(where);
|
|
334
|
+
const found = (await fq.toArray());
|
|
335
|
+
hits = found.map((o) => ({ row: this.toRow(o), score: o._score }));
|
|
336
|
+
}
|
|
337
|
+
else {
|
|
338
|
+
const query = where ? t.query().where(where) : t.query();
|
|
339
|
+
const found = (await query.toArray());
|
|
340
|
+
return found
|
|
341
|
+
.map((o) => ({ row: this.toRow(o), score: 0 }))
|
|
342
|
+
.sort((a, b) => byKey(a.row, b.row))
|
|
343
|
+
.slice(0, q.limit);
|
|
344
|
+
}
|
|
345
|
+
// Ties break by key, so equal stores answer in equal order.
|
|
346
|
+
return hits.sort((a, b) => b.score - a.score || byKey(a.row, b.row));
|
|
347
|
+
}
|
|
348
|
+
async hasIndex(t, column) {
|
|
349
|
+
return (await t.listIndices()).some((i) => i.columns.includes(column));
|
|
350
|
+
}
|
|
351
|
+
async embedder() {
|
|
352
|
+
const [o] = await this.select(EMBEDDER_TABLE, "id IS NOT NULL");
|
|
353
|
+
if (!o)
|
|
354
|
+
return undefined;
|
|
355
|
+
const record = {
|
|
356
|
+
id: o.id,
|
|
357
|
+
revision: o.revision,
|
|
358
|
+
dimension: o.dimension,
|
|
359
|
+
};
|
|
360
|
+
if (typeof o.route === "string")
|
|
361
|
+
record.route = o.route;
|
|
362
|
+
if (typeof o.model === "string")
|
|
363
|
+
record.model = o.model;
|
|
364
|
+
return record;
|
|
365
|
+
}
|
|
366
|
+
async recordEmbedder(record) {
|
|
367
|
+
const t = (await this.table(EMBEDDER_TABLE, "write"));
|
|
368
|
+
await t.delete("id IS NOT NULL");
|
|
369
|
+
const row = {
|
|
370
|
+
id: record.id,
|
|
371
|
+
revision: record.revision,
|
|
372
|
+
route: record.route ?? null,
|
|
373
|
+
model: record.model ?? null,
|
|
374
|
+
dimension: record.dimension,
|
|
375
|
+
};
|
|
376
|
+
await t.add(this.m.lancedb.makeArrowTable([row], { schema: this.schemas(EMBEDDER_TABLE) }));
|
|
377
|
+
}
|
|
378
|
+
async recordBuiltFrom(tree, built) {
|
|
379
|
+
await this.mergeInto(this.builtName, "tree", [{ tree, head: built.head, at: built.at }]);
|
|
380
|
+
}
|
|
381
|
+
async builtFrom(tree) {
|
|
382
|
+
const [o] = await this.select(this.builtName, `tree = ${sqlString(tree)}`);
|
|
383
|
+
return o ? { head: o.head, at: o.at } : undefined;
|
|
384
|
+
}
|
|
385
|
+
async sources(tree) {
|
|
386
|
+
// Without a rows table its sources describe nothing that exists.
|
|
387
|
+
if (!(await this.table(this.rowsName, "read")))
|
|
388
|
+
return [];
|
|
389
|
+
return (await this.select(this.sourcesName, `tree = ${sqlString(tree)}`)).map((o) => ({
|
|
390
|
+
tree: o.tree,
|
|
391
|
+
path: o.path,
|
|
392
|
+
size: o.size,
|
|
393
|
+
mtimeMs: o.mtimeMs,
|
|
394
|
+
sha256: o.sha256,
|
|
395
|
+
meta: o.meta,
|
|
396
|
+
}));
|
|
397
|
+
}
|
|
398
|
+
async putSources(rows) {
|
|
399
|
+
await this.mergeInto(this.sourcesName, ["tree", "path"], rows);
|
|
400
|
+
}
|
|
401
|
+
async removeSources(tree, paths) {
|
|
402
|
+
if (paths.length === 0)
|
|
403
|
+
return;
|
|
404
|
+
await this.deleteFrom(this.sourcesName, `tree = ${sqlString(tree)} AND path IN (${sqlList(paths)})`);
|
|
405
|
+
}
|
|
406
|
+
async cachedVectors(embedder, keys) {
|
|
407
|
+
if (keys.length === 0)
|
|
408
|
+
return [];
|
|
409
|
+
const wanted = new Set(keys.map((k) => `${k.sha256}\0${k.view}`));
|
|
410
|
+
const shas = [...new Set(keys.map((k) => k.sha256))];
|
|
411
|
+
const found = await this.select("vectors", `embedder = ${sqlString(embedder)} AND sha256 IN (${sqlList(shas)})`);
|
|
412
|
+
return found
|
|
413
|
+
.filter((o) => wanted.has(`${o.sha256}\0${o.view}`))
|
|
414
|
+
.map((o) => ({
|
|
415
|
+
sha256: o.sha256,
|
|
416
|
+
view: o.view,
|
|
417
|
+
vec: Float32Array.from(o.vec.toArray()),
|
|
418
|
+
}));
|
|
419
|
+
}
|
|
420
|
+
async cacheVectors(embedder, vectors) {
|
|
421
|
+
await this.mergeInto("vectors", ["sha256", "view", "embedder"], vectors.map((v) => ({ sha256: v.sha256, view: v.view, embedder, vec: Array.from(v.vec) })));
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Builds the missing scalar and full-text indexes, then compacts every table and brings its
|
|
425
|
+
* indexes up to date. Run by a writer under the write lock after a batch, never per upsert.
|
|
426
|
+
*/
|
|
427
|
+
async optimize() {
|
|
428
|
+
const rows = await this.table(this.rowsName, "read");
|
|
429
|
+
if (rows && (await rows.countRows()) > 0) {
|
|
430
|
+
const have = new Set((await rows.listIndices()).flatMap((i) => i.columns));
|
|
431
|
+
const { Index } = this.m.lancedb;
|
|
432
|
+
for (const [column, kind] of SCALAR_INDEXES) {
|
|
433
|
+
if (!have.has(column)) {
|
|
434
|
+
await rows.createIndex(column, {
|
|
435
|
+
config: kind === "btree" ? Index.btree() : Index.bitmap(),
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
if (!have.has("text"))
|
|
440
|
+
await rows.createIndex("text", { config: Index.fts() });
|
|
441
|
+
}
|
|
442
|
+
for (const name of [this.rowsName, this.sourcesName, "vectors", this.builtName]) {
|
|
443
|
+
const t = await this.table(name, "read");
|
|
444
|
+
if (t)
|
|
445
|
+
await t.optimize();
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
/** Closes the open tables and the connection. */
|
|
449
|
+
close() {
|
|
450
|
+
for (const t of this.tables.values())
|
|
451
|
+
t.close();
|
|
452
|
+
this.tables.clear();
|
|
453
|
+
this.db?.close();
|
|
454
|
+
this.db = undefined;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { Row } from "./store.ts";
|
|
2
|
+
/** One indexable file, as listed: cheap to produce, no file contents read. */
|
|
3
|
+
export interface LibraryItem {
|
|
4
|
+
/** The file's path inside the work tree, `/`-separated. */
|
|
5
|
+
path: string;
|
|
6
|
+
size: number;
|
|
7
|
+
mtimeMs: number;
|
|
8
|
+
source: Row["source"];
|
|
9
|
+
id: string;
|
|
10
|
+
address: string;
|
|
11
|
+
game?: string;
|
|
12
|
+
kind?: string;
|
|
13
|
+
subject?: string;
|
|
14
|
+
tags?: string[];
|
|
15
|
+
state?: string;
|
|
16
|
+
bible?: string;
|
|
17
|
+
license?: string;
|
|
18
|
+
origin?: string;
|
|
19
|
+
declaredOrigin?: string;
|
|
20
|
+
originEvidence?: string;
|
|
21
|
+
originSource?: string;
|
|
22
|
+
originLicense?: string;
|
|
23
|
+
digitalSourceType?: string;
|
|
24
|
+
title?: string;
|
|
25
|
+
description?: string;
|
|
26
|
+
width?: number;
|
|
27
|
+
height?: number;
|
|
28
|
+
durationS?: number;
|
|
29
|
+
form?: string;
|
|
30
|
+
tempo?: number;
|
|
31
|
+
mediaType?: string;
|
|
32
|
+
mediaSha256?: string;
|
|
33
|
+
mediaStatus?: "available" | "unavailable";
|
|
34
|
+
mediaReason?: string;
|
|
35
|
+
/** The card fields and body joined; full-text indexed and embedded as the card-text vector. */
|
|
36
|
+
text?: string;
|
|
37
|
+
}
|
|
38
|
+
/** An item loaded on demand: the file's bytes and each image view to embed. */
|
|
39
|
+
export interface LoadedItem {
|
|
40
|
+
bytes: Uint8Array;
|
|
41
|
+
/** One per view; a still image has one view named `""`. */
|
|
42
|
+
views: {
|
|
43
|
+
view: string;
|
|
44
|
+
image: Uint8Array;
|
|
45
|
+
}[];
|
|
46
|
+
}
|
|
47
|
+
export interface Library {
|
|
48
|
+
list(): Promise<LibraryItem[]>;
|
|
49
|
+
load(item: LibraryItem): Promise<LoadedItem>;
|
|
50
|
+
/** The commit the work tree is on, recorded as `builtFrom.head`. */
|
|
51
|
+
head?(): Promise<string>;
|
|
52
|
+
}
|
|
53
|
+
export declare const sha256Hex: (data: Uint8Array | string) => string;
|
|
54
|
+
/**
|
|
55
|
+
* The key of a work tree's rows: the sha256 of its real path. The native realpath, so every
|
|
56
|
+
* spelling of one tree gives one key: on Windows it expands 8.3 short names (a `RUNNER~1` temp
|
|
57
|
+
* folder) and Git's forward-slash top level alike, which the JavaScript one leaves as they are.
|
|
58
|
+
*/
|
|
59
|
+
export declare function treeKey(worktree: string): string;
|
|
60
|
+
/** The text an item is full-text indexed and embedded by. */
|
|
61
|
+
export declare function itemText(item: LibraryItem): string;
|
|
62
|
+
/** The sha256 of an item's card fields and text: what decides whether its rows need rewriting. */
|
|
63
|
+
export declare function itemMeta(item: LibraryItem): string;
|
package/dist/library.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the indexer reads. Core supplies the real library reader (design section 7.1: picks with
|
|
3
|
+
* card fields and text, bible references, run candidates, folders from settings); the package
|
|
4
|
+
* defines the shape it needs, so the indexer and its tests do not depend on core.
|
|
5
|
+
*/
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { realpathSync } from "node:fs";
|
|
8
|
+
export const sha256Hex = (data) => createHash("sha256").update(data).digest("hex");
|
|
9
|
+
/**
|
|
10
|
+
* The key of a work tree's rows: the sha256 of its real path. The native realpath, so every
|
|
11
|
+
* spelling of one tree gives one key: on Windows it expands 8.3 short names (a `RUNNER~1` temp
|
|
12
|
+
* folder) and Git's forward-slash top level alike, which the JavaScript one leaves as they are.
|
|
13
|
+
*/
|
|
14
|
+
export function treeKey(worktree) {
|
|
15
|
+
return sha256Hex(realpathSync.native(worktree));
|
|
16
|
+
}
|
|
17
|
+
/** The text an item is full-text indexed and embedded by. */
|
|
18
|
+
export function itemText(item) {
|
|
19
|
+
if (item.text !== undefined)
|
|
20
|
+
return item.text;
|
|
21
|
+
return [item.title, item.subject, item.kind, ...(item.tags ?? []), item.description]
|
|
22
|
+
.filter((s) => typeof s === "string" && s !== "")
|
|
23
|
+
.join("\n");
|
|
24
|
+
}
|
|
25
|
+
/** The sha256 of an item's card fields and text: what decides whether its rows need rewriting. */
|
|
26
|
+
export function itemMeta(item) {
|
|
27
|
+
const stat = new Set(["path", "size", "mtimeMs"]);
|
|
28
|
+
const sorted = Object.fromEntries(Object.entries({ ...item, text: itemText(item) })
|
|
29
|
+
.filter(([k]) => !stat.has(k))
|
|
30
|
+
.sort(([a], [b]) => (a < b ? -1 : 1)));
|
|
31
|
+
return sha256Hex(JSON.stringify(sorted));
|
|
32
|
+
}
|
package/dist/lock.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare class WriteLock {
|
|
2
|
+
readonly path: string;
|
|
3
|
+
constructor(path: string);
|
|
4
|
+
release(): Promise<void>;
|
|
5
|
+
}
|
|
6
|
+
export declare function tryAcquireWriteLock(storeDir: string): Promise<WriteLock | undefined>;
|
|
7
|
+
export declare function acquireWriteLock(storeDir: string, opts?: {
|
|
8
|
+
timeoutMs?: number;
|
|
9
|
+
pollMs?: number;
|
|
10
|
+
}): Promise<WriteLock>;
|
|
11
|
+
export declare function lockHeldByOther(storeDir: string): Promise<boolean>;
|