@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
package/dist/find.d.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The search index of one work tree (design sections 7.3 to 7.5): fresh before every query
|
|
3
|
+
* unless another process holds the write lock, in which case the query answers at once from the
|
|
4
|
+
* current table with `fresh: false` and writes nothing.
|
|
5
|
+
*/
|
|
6
|
+
import type { Embedder } from "./embedder.ts";
|
|
7
|
+
import { type RefreshStats } from "./indexer.ts";
|
|
8
|
+
import { type LanceStoreOptions } from "./lance-store.ts";
|
|
9
|
+
import { type Library } from "./library.ts";
|
|
10
|
+
import type { BuiltFrom, FilterTerm, Hit, Row, Store, StoreQuery } from "./store.ts";
|
|
11
|
+
/** Reciprocal Rank Fusion's constant (design section 7.5). */
|
|
12
|
+
export declare const RRF_K = 60;
|
|
13
|
+
export interface FindOptions {
|
|
14
|
+
/** A words query: fused image-vector, card-text-vector and full-text rankings. */
|
|
15
|
+
words?: string;
|
|
16
|
+
/** `field=value`, `!=`, `<`, `>` and `tag=value` terms, all of which must match. */
|
|
17
|
+
where?: string | string[];
|
|
18
|
+
/** Search every tree in the store, not only this one (`--game all`). */
|
|
19
|
+
allTrees?: boolean;
|
|
20
|
+
limit?: number;
|
|
21
|
+
}
|
|
22
|
+
export interface FindHit {
|
|
23
|
+
address: string;
|
|
24
|
+
rank: number;
|
|
25
|
+
score: number;
|
|
26
|
+
source: Row["source"];
|
|
27
|
+
path: string;
|
|
28
|
+
view: string;
|
|
29
|
+
fields: Pick<Row, "game" | "kind" | "subject" | "tags" | "state" | "bible" | "license" | "origin" | "declaredOrigin" | "originEvidence" | "originSource" | "originLicense" | "digitalSourceType" | "width" | "height" | "durationS" | "form" | "tempo" | "mediaType" | "mediaSha256" | "mediaStatus" | "mediaReason">;
|
|
30
|
+
/** Card text: core passes it on only under `sharedText`. */
|
|
31
|
+
sharedText: Pick<Row, "title" | "description" | "text">;
|
|
32
|
+
}
|
|
33
|
+
export interface FindResult {
|
|
34
|
+
hits: FindHit[];
|
|
35
|
+
fresh: boolean;
|
|
36
|
+
builtFrom: BuiltFrom | undefined;
|
|
37
|
+
}
|
|
38
|
+
/** Keeps each asset's first row, in the order given: its best view in that ranking. */
|
|
39
|
+
export declare function bestViewPerAsset(hits: Hit[]): Hit[];
|
|
40
|
+
/**
|
|
41
|
+
* Reciprocal Rank Fusion over assets: each list is first cut to one row per asset, its best
|
|
42
|
+
* view there, and an asset scores Σ 1 / (k + rank), rank from 1. An asset keeps the view of its
|
|
43
|
+
* best rank, earlier lists winning ties, so with the image-vector list first a turntable answers
|
|
44
|
+
* at the view that looks most like the words.
|
|
45
|
+
*/
|
|
46
|
+
export declare function rrf(lists: Hit[][], k?: number): Hit[];
|
|
47
|
+
export interface QueryVectors {
|
|
48
|
+
words?: Float32Array;
|
|
49
|
+
like?: Float32Array;
|
|
50
|
+
}
|
|
51
|
+
/** One store searched, with the filter its rows must match (its tree, the query's where terms). */
|
|
52
|
+
export interface Searched {
|
|
53
|
+
store: Store;
|
|
54
|
+
filter: FilterTerm[];
|
|
55
|
+
}
|
|
56
|
+
/** Each ranking's pool: four times the limit, at least 100. */
|
|
57
|
+
export declare const poolFor: (limit: number) => number;
|
|
58
|
+
/**
|
|
59
|
+
* The store queries a query ranks by, in fusion order: for words the image vector, the card-text
|
|
60
|
+
* vector and the full text; for an image, its image vector. No filter set.
|
|
61
|
+
*/
|
|
62
|
+
export declare function rankingQueries(words: string, vectors: QueryVectors, limit: number): StoreQuery[];
|
|
63
|
+
/**
|
|
64
|
+
* One ranking's answers from several stores, merged by the ranking's own score, best first; ties
|
|
65
|
+
* keep the earlier store first. A single list is returned unchanged.
|
|
66
|
+
*/
|
|
67
|
+
export declare function mergeByScore(lists: Hit[][]): Hit[];
|
|
68
|
+
/**
|
|
69
|
+
* The shipped ranking: each ranking asked of every store, merged across stores by its own score,
|
|
70
|
+
* then fused once. With no ranking, every store's filtered rows, local first.
|
|
71
|
+
*/
|
|
72
|
+
export declare function rankAcross(asked: Searched[], q: {
|
|
73
|
+
words?: string;
|
|
74
|
+
limit: number;
|
|
75
|
+
}, vectors: QueryVectors): Promise<Hit[]>;
|
|
76
|
+
export interface SearchIndexOptions {
|
|
77
|
+
/** The store folder, `<stateDir>/search`; it holds `write.lock`. */
|
|
78
|
+
dir: string;
|
|
79
|
+
embedder: Embedder;
|
|
80
|
+
library: Library;
|
|
81
|
+
/** The work tree whose rows this index keeps; its real path's sha256 is the `tree` key. */
|
|
82
|
+
worktree: string;
|
|
83
|
+
/** An already open store; otherwise LanceDB is opened at `dir`. */
|
|
84
|
+
store?: Store;
|
|
85
|
+
platform?: LanceStoreOptions["platform"];
|
|
86
|
+
importLance?: LanceStoreOptions["importLance"];
|
|
87
|
+
/** How long `index()` waits for another writer; queries never wait. */
|
|
88
|
+
lockTimeoutMs?: number;
|
|
89
|
+
onProgress?: (done: number, total: number) => void;
|
|
90
|
+
}
|
|
91
|
+
export declare class SearchIndex {
|
|
92
|
+
readonly dir: string;
|
|
93
|
+
readonly tree: string;
|
|
94
|
+
readonly store: Store;
|
|
95
|
+
private readonly o;
|
|
96
|
+
private constructor();
|
|
97
|
+
/** Opens without writing. Refuses on darwin-x64 before LanceDB is imported. */
|
|
98
|
+
static open(o: SearchIndexOptions): Promise<SearchIndex>;
|
|
99
|
+
private refreshUnder;
|
|
100
|
+
/** Brings the tree up to date unless another process holds the lock; never waits. */
|
|
101
|
+
refresh(): Promise<{
|
|
102
|
+
fresh: boolean;
|
|
103
|
+
stats?: RefreshStats;
|
|
104
|
+
}>;
|
|
105
|
+
/**
|
|
106
|
+
* The writer's path (`search index`): waits its turn for the lock, then refreshes. `before`
|
|
107
|
+
* runs under the same lock first (a rebuild records its embedder there, so no concurrent
|
|
108
|
+
* refresh sees the record missing).
|
|
109
|
+
*/
|
|
110
|
+
index(options?: {
|
|
111
|
+
before?: (store: Store) => Promise<void>;
|
|
112
|
+
}): Promise<RefreshStats>;
|
|
113
|
+
find(q: FindOptions): Promise<FindResult>;
|
|
114
|
+
close(): void;
|
|
115
|
+
}
|
package/dist/find.js
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { refreshTree } from "./indexer.js";
|
|
2
|
+
import { LanceStore } from "./lance-store.js";
|
|
3
|
+
import { treeKey } from "./library.js";
|
|
4
|
+
import { acquireWriteLock, tryAcquireWriteLock } from "./lock.js";
|
|
5
|
+
import { parseWhere, resolveOrdered } from "./where.js";
|
|
6
|
+
/** Reciprocal Rank Fusion's constant (design section 7.5). */
|
|
7
|
+
export const RRF_K = 60;
|
|
8
|
+
const assetOf = (h) => `${h.row.tree}\0${h.row.id}`;
|
|
9
|
+
/** Keeps each asset's first row, in the order given: its best view in that ranking. */
|
|
10
|
+
export function bestViewPerAsset(hits) {
|
|
11
|
+
const seen = new Set();
|
|
12
|
+
return hits.filter((h) => {
|
|
13
|
+
const asset = assetOf(h);
|
|
14
|
+
if (seen.has(asset))
|
|
15
|
+
return false;
|
|
16
|
+
seen.add(asset);
|
|
17
|
+
return true;
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Reciprocal Rank Fusion over assets: each list is first cut to one row per asset, its best
|
|
22
|
+
* view there, and an asset scores Σ 1 / (k + rank), rank from 1. An asset keeps the view of its
|
|
23
|
+
* best rank, earlier lists winning ties, so with the image-vector list first a turntable answers
|
|
24
|
+
* at the view that looks most like the words.
|
|
25
|
+
*/
|
|
26
|
+
export function rrf(lists, k = RRF_K) {
|
|
27
|
+
const fused = new Map();
|
|
28
|
+
for (const list of lists) {
|
|
29
|
+
bestViewPerAsset(list).forEach((h, i) => {
|
|
30
|
+
const asset = assetOf(h);
|
|
31
|
+
const had = fused.get(asset);
|
|
32
|
+
const add = 1 / (k + i + 1);
|
|
33
|
+
if (!had)
|
|
34
|
+
fused.set(asset, { row: h.row, score: add, best: i });
|
|
35
|
+
else {
|
|
36
|
+
had.score += add;
|
|
37
|
+
if (i < had.best)
|
|
38
|
+
Object.assign(had, { row: h.row, best: i });
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
return [...fused.values()]
|
|
43
|
+
.map(({ row, score }) => ({ row, score }))
|
|
44
|
+
.sort((a, b) => b.score - a.score || (a.row.key < b.row.key ? -1 : a.row.key > b.row.key ? 1 : 0));
|
|
45
|
+
}
|
|
46
|
+
/** Each ranking's pool: four times the limit, at least 100. */
|
|
47
|
+
export const poolFor = (limit) => Math.max(4 * limit, 100);
|
|
48
|
+
/**
|
|
49
|
+
* The store queries a query ranks by, in fusion order: for words the image vector, the card-text
|
|
50
|
+
* vector and the full text; for an image, its image vector. No filter set.
|
|
51
|
+
*/
|
|
52
|
+
export function rankingQueries(words, vectors, limit) {
|
|
53
|
+
const queries = [];
|
|
54
|
+
if (vectors.words) {
|
|
55
|
+
const value = vectors.words;
|
|
56
|
+
queries.push({ vector: { column: "imageVec", value }, limit }, { vector: { column: "textVec", value }, limit }, { text: words, limit });
|
|
57
|
+
}
|
|
58
|
+
if (vectors.like) {
|
|
59
|
+
queries.push({ vector: { column: "imageVec", value: vectors.like }, limit });
|
|
60
|
+
}
|
|
61
|
+
return queries;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* One ranking's answers from several stores, merged by the ranking's own score, best first; ties
|
|
65
|
+
* keep the earlier store first. A single list is returned unchanged.
|
|
66
|
+
*/
|
|
67
|
+
export function mergeByScore(lists) {
|
|
68
|
+
if (lists.length === 1)
|
|
69
|
+
return lists[0];
|
|
70
|
+
return lists.flat().sort((a, b) => b.score - a.score);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* A store's filter with each `bible<` and `bible>` term resolved to the `bible` values its rows
|
|
74
|
+
* (under the other terms) hold on the asked side, in version order ("2" before "10").
|
|
75
|
+
*/
|
|
76
|
+
async function ordered(s) {
|
|
77
|
+
return resolveOrdered(s.filter, async (field, others) => {
|
|
78
|
+
const rows = await s.store.query({ filter: others, limit: Number.MAX_SAFE_INTEGER });
|
|
79
|
+
const values = rows.map(({ row }) => row[field]);
|
|
80
|
+
return values.filter((v) => ["string", "number", "boolean"].includes(typeof v));
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* The shipped ranking: each ranking asked of every store, merged across stores by its own score,
|
|
85
|
+
* then fused once. With no ranking, every store's filtered rows, local first.
|
|
86
|
+
*/
|
|
87
|
+
export async function rankAcross(asked, q, vectors) {
|
|
88
|
+
const searched = await Promise.all(asked.map(async (s) => ({ ...s, filter: await ordered(s) })));
|
|
89
|
+
const rankings = rankingQueries(q.words?.trim() ?? "", vectors, poolFor(q.limit));
|
|
90
|
+
if (rankings.length === 0) {
|
|
91
|
+
const rows = await Promise.all(searched.map((s) => s.store.query({ filter: s.filter, limit: Number.MAX_SAFE_INTEGER })));
|
|
92
|
+
return rows.flat();
|
|
93
|
+
}
|
|
94
|
+
const merged = await Promise.all(rankings.map(async (r) => mergeByScore(await Promise.all(searched.map((s) => s.store.query({ ...r, filter: s.filter }))))));
|
|
95
|
+
return merged.length === 1 ? bestViewPerAsset(merged[0]) : rrf(merged);
|
|
96
|
+
}
|
|
97
|
+
export class SearchIndex {
|
|
98
|
+
dir;
|
|
99
|
+
tree;
|
|
100
|
+
store;
|
|
101
|
+
o;
|
|
102
|
+
constructor(o, store) {
|
|
103
|
+
this.o = o;
|
|
104
|
+
this.dir = o.dir;
|
|
105
|
+
this.tree = treeKey(o.worktree);
|
|
106
|
+
this.store = store;
|
|
107
|
+
}
|
|
108
|
+
/** Opens without writing. Refuses on darwin-x64 before LanceDB is imported. */
|
|
109
|
+
static async open(o) {
|
|
110
|
+
const store = o.store ??
|
|
111
|
+
(await LanceStore.open(o.dir, {
|
|
112
|
+
embedder: o.embedder,
|
|
113
|
+
platform: o.platform,
|
|
114
|
+
importLance: o.importLance,
|
|
115
|
+
}));
|
|
116
|
+
return new SearchIndex(o, store);
|
|
117
|
+
}
|
|
118
|
+
async refreshUnder(lock, before) {
|
|
119
|
+
try {
|
|
120
|
+
if (before)
|
|
121
|
+
await before(this.store);
|
|
122
|
+
const stats = await refreshTree({
|
|
123
|
+
store: this.store,
|
|
124
|
+
embedder: this.o.embedder,
|
|
125
|
+
library: this.o.library,
|
|
126
|
+
tree: this.tree,
|
|
127
|
+
onProgress: this.o.onProgress,
|
|
128
|
+
});
|
|
129
|
+
// One optimize per batch, under the lock.
|
|
130
|
+
if (stats.written + stats.removed > 0)
|
|
131
|
+
await this.store.optimize();
|
|
132
|
+
return stats;
|
|
133
|
+
}
|
|
134
|
+
finally {
|
|
135
|
+
await lock.release();
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/** Brings the tree up to date unless another process holds the lock; never waits. */
|
|
139
|
+
async refresh() {
|
|
140
|
+
const lock = await tryAcquireWriteLock(this.dir);
|
|
141
|
+
if (!lock)
|
|
142
|
+
return { fresh: false };
|
|
143
|
+
return { fresh: true, stats: await this.refreshUnder(lock) };
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* The writer's path (`search index`): waits its turn for the lock, then refreshes. `before`
|
|
147
|
+
* runs under the same lock first (a rebuild records its embedder there, so no concurrent
|
|
148
|
+
* refresh sees the record missing).
|
|
149
|
+
*/
|
|
150
|
+
async index(options = {}) {
|
|
151
|
+
const lock = await acquireWriteLock(this.dir, { timeoutMs: this.o.lockTimeoutMs });
|
|
152
|
+
return this.refreshUnder(lock, options.before);
|
|
153
|
+
}
|
|
154
|
+
async find(q) {
|
|
155
|
+
const filter = q.where === undefined ? [] : parseWhere(q.where);
|
|
156
|
+
const limit = q.limit ?? 20;
|
|
157
|
+
const { fresh } = await this.refresh();
|
|
158
|
+
if (!q.allTrees)
|
|
159
|
+
filter.push({ field: "tree", op: "=", value: this.tree });
|
|
160
|
+
const words = q.words?.trim() ?? "";
|
|
161
|
+
const vec = words !== "" ? (await this.o.embedder.embedTexts([words]))[0] : undefined;
|
|
162
|
+
const ranked = await rankAcross([{ store: this.store, filter }], { words, limit }, vec ? { words: vec } : {});
|
|
163
|
+
const hits = bestViewPerAsset(ranked) // one row per asset already after fusion
|
|
164
|
+
.slice(0, limit)
|
|
165
|
+
.map(({ row, score }, i) => ({
|
|
166
|
+
address: row.address,
|
|
167
|
+
rank: i + 1,
|
|
168
|
+
score,
|
|
169
|
+
source: row.source,
|
|
170
|
+
path: row.path,
|
|
171
|
+
view: row.view ?? "",
|
|
172
|
+
fields: {
|
|
173
|
+
game: row.game,
|
|
174
|
+
kind: row.kind,
|
|
175
|
+
subject: row.subject,
|
|
176
|
+
tags: row.tags,
|
|
177
|
+
state: row.state,
|
|
178
|
+
bible: row.bible,
|
|
179
|
+
license: row.license,
|
|
180
|
+
origin: row.origin,
|
|
181
|
+
declaredOrigin: row.declaredOrigin,
|
|
182
|
+
originEvidence: row.originEvidence,
|
|
183
|
+
originSource: row.originSource,
|
|
184
|
+
originLicense: row.originLicense,
|
|
185
|
+
digitalSourceType: row.digitalSourceType,
|
|
186
|
+
width: row.width,
|
|
187
|
+
height: row.height,
|
|
188
|
+
durationS: row.durationS,
|
|
189
|
+
form: row.form,
|
|
190
|
+
tempo: row.tempo,
|
|
191
|
+
mediaType: row.mediaType,
|
|
192
|
+
mediaSha256: row.mediaSha256,
|
|
193
|
+
mediaStatus: row.mediaStatus,
|
|
194
|
+
mediaReason: row.mediaReason,
|
|
195
|
+
},
|
|
196
|
+
sharedText: { title: row.title, description: row.description, text: row.text },
|
|
197
|
+
}));
|
|
198
|
+
return { hits, fresh, builtFrom: await this.store.builtFrom(this.tree) };
|
|
199
|
+
}
|
|
200
|
+
close() {
|
|
201
|
+
this.store.close?.();
|
|
202
|
+
}
|
|
203
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** The fixed background transparent pixels are flattened onto before embedding. */
|
|
2
|
+
export declare const FLATTEN_BACKGROUND: {
|
|
3
|
+
readonly r: 255;
|
|
4
|
+
readonly g: 255;
|
|
5
|
+
readonly b: 255;
|
|
6
|
+
};
|
|
7
|
+
export interface RgbImage {
|
|
8
|
+
width: number;
|
|
9
|
+
height: number;
|
|
10
|
+
/** width × height × 3 bytes. */
|
|
11
|
+
data: Uint8Array;
|
|
12
|
+
}
|
|
13
|
+
/** Composite straight-alpha RGBA onto the fixed background. */
|
|
14
|
+
export declare function flattenRgba(width: number, height: number, rgba: Uint8Array): RgbImage;
|
|
15
|
+
export declare function flattenPng(bytes: Uint8Array): RgbImage;
|
package/dist/flatten.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { PNG } from "pngjs";
|
|
2
|
+
/** The fixed background transparent pixels are flattened onto before embedding. */
|
|
3
|
+
export const FLATTEN_BACKGROUND = { r: 255, g: 255, b: 255 };
|
|
4
|
+
/** Composite straight-alpha RGBA onto the fixed background. */
|
|
5
|
+
export function flattenRgba(width, height, rgba) {
|
|
6
|
+
const out = new Uint8Array(width * height * 3);
|
|
7
|
+
const bg = [FLATTEN_BACKGROUND.r, FLATTEN_BACKGROUND.g, FLATTEN_BACKGROUND.b];
|
|
8
|
+
for (let p = 0; p < width * height; p++) {
|
|
9
|
+
const a = rgba[p * 4 + 3] / 255;
|
|
10
|
+
for (let c = 0; c < 3; c++) {
|
|
11
|
+
out[p * 3 + c] = Math.round(rgba[p * 4 + c] * a + bg[c] * (1 - a));
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
return { width, height, data: out };
|
|
15
|
+
}
|
|
16
|
+
export function flattenPng(bytes) {
|
|
17
|
+
const png = PNG.sync.read(Buffer.from(bytes));
|
|
18
|
+
return flattenRgba(png.width, png.height, png.data);
|
|
19
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export * from "./embedder.ts";
|
|
2
|
+
export * from "./errors.ts";
|
|
3
|
+
export * from "./flatten.ts";
|
|
4
|
+
export * from "./memory-store.ts";
|
|
5
|
+
export * from "./model-manifest.ts";
|
|
6
|
+
export * from "./route-embedder.ts";
|
|
7
|
+
export * from "./scripted.ts";
|
|
8
|
+
export * from "./setup.ts";
|
|
9
|
+
export * from "./siglip2.ts";
|
|
10
|
+
export * from "./store.ts";
|
|
11
|
+
export * from "./find.ts";
|
|
12
|
+
export * from "./indexer.ts";
|
|
13
|
+
export * from "./lance-store.ts";
|
|
14
|
+
export * from "./library.ts";
|
|
15
|
+
export * from "./lock.ts";
|
|
16
|
+
export * from "./platform.ts";
|
|
17
|
+
export * from "./where.ts";
|
|
18
|
+
export * from "./extension.ts";
|
|
19
|
+
export type { Extension, NearMatchQuery, SearchContext, SearchFindResult, SearchForecast, SearchHit, SearchLibrary, SearchLibraryItem, SearchLoadedItem, SearchOutliersResult, SearchQuery, SearchRankedMember, SearchRouteEmbedder, SearchSettings, SearchSlot, SearchSource, SearchStoreSettings, } from "@clockgrove/assetgrove/extension";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export * from "./embedder.js";
|
|
2
|
+
export * from "./errors.js";
|
|
3
|
+
export * from "./flatten.js";
|
|
4
|
+
export * from "./memory-store.js";
|
|
5
|
+
export * from "./model-manifest.js";
|
|
6
|
+
export * from "./route-embedder.js";
|
|
7
|
+
export * from "./scripted.js";
|
|
8
|
+
export * from "./setup.js";
|
|
9
|
+
export * from "./siglip2.js";
|
|
10
|
+
export * from "./store.js";
|
|
11
|
+
export * from "./find.js";
|
|
12
|
+
export * from "./indexer.js";
|
|
13
|
+
export * from "./lance-store.js";
|
|
14
|
+
export * from "./library.js";
|
|
15
|
+
export * from "./lock.js";
|
|
16
|
+
export * from "./platform.js";
|
|
17
|
+
export * from "./where.js";
|
|
18
|
+
export * from "./extension.js";
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Freshness (design section 7.4): stat the tree's indexable files, compare them with `sources`,
|
|
3
|
+
* hash only changed files, take vectors from the cache, embed only unseen content, and drop
|
|
4
|
+
* rows for files that are gone. The caller holds the write lock.
|
|
5
|
+
*/
|
|
6
|
+
import type { Embedder } from "./embedder.ts";
|
|
7
|
+
import { type Library } from "./library.ts";
|
|
8
|
+
import type { EmbedderRecord, Store } from "./store.ts";
|
|
9
|
+
/** The `view` under which a text's vector is cached. */
|
|
10
|
+
export declare const TEXT_VIEW = "#text";
|
|
11
|
+
export interface RefreshStats {
|
|
12
|
+
/** Files whose rows were written: added, changed, or with changed card fields. */
|
|
13
|
+
written: number;
|
|
14
|
+
removed: number;
|
|
15
|
+
/** Content the embedder was asked for. */
|
|
16
|
+
embeddedImages: number;
|
|
17
|
+
embeddedTexts: number;
|
|
18
|
+
}
|
|
19
|
+
export interface RefreshOptions {
|
|
20
|
+
store: Store;
|
|
21
|
+
embedder: Embedder;
|
|
22
|
+
library: Library;
|
|
23
|
+
tree: string;
|
|
24
|
+
onProgress?: (done: number, total: number) => void;
|
|
25
|
+
}
|
|
26
|
+
export declare const embedderRecord: (e: Embedder) => EmbedderRecord;
|
|
27
|
+
export declare const embedderKey: (e: Embedder) => string;
|
|
28
|
+
/** Brings one tree's rows up to date. Returns what it did; writes nothing when nothing changed. */
|
|
29
|
+
export declare function refreshTree(o: RefreshOptions): Promise<RefreshStats>;
|
|
30
|
+
export interface PendingWork {
|
|
31
|
+
images: number;
|
|
32
|
+
texts: number;
|
|
33
|
+
/** sha256 hex over the stale items, the removed paths and the embedder key. */
|
|
34
|
+
fingerprint: string;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* What `refreshTree` would embed, decided the same way and without embedding or writing: stale
|
|
38
|
+
* items are loaded and hashed, touched-but-identical ones skipped, and content already in the
|
|
39
|
+
* vector cache or shared within the pending work counted once or not at all. With `rebuild`
|
|
40
|
+
* the tree's rows are taken as gone, so every item is stale; the vector cache still answers.
|
|
41
|
+
*/
|
|
42
|
+
export declare function pendingWork(o: {
|
|
43
|
+
store: Store;
|
|
44
|
+
embedder: Embedder;
|
|
45
|
+
library: Library;
|
|
46
|
+
tree: string;
|
|
47
|
+
rebuild?: boolean;
|
|
48
|
+
}): Promise<PendingWork>;
|
package/dist/indexer.js
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { itemMeta, itemText, sha256Hex } from "./library.js";
|
|
2
|
+
/** The `view` under which a text's vector is cached. */
|
|
3
|
+
export const TEXT_VIEW = "#text";
|
|
4
|
+
const BATCH = 64;
|
|
5
|
+
export const embedderRecord = (e) => ({
|
|
6
|
+
id: e.id,
|
|
7
|
+
revision: e.revision,
|
|
8
|
+
...(e.route !== undefined && { route: e.route }),
|
|
9
|
+
...(e.model !== undefined && { model: e.model }),
|
|
10
|
+
dimension: e.dimension,
|
|
11
|
+
});
|
|
12
|
+
export const embedderKey = (e) => `${e.id}@${e.revision}`;
|
|
13
|
+
const vecKey = (sha256, view) => `${sha256}\0${view}`;
|
|
14
|
+
/** Brings one tree's rows up to date. Returns what it did; writes nothing when nothing changed. */
|
|
15
|
+
export async function refreshTree(o) {
|
|
16
|
+
const { store, library, tree } = o;
|
|
17
|
+
const stats = { written: 0, removed: 0, embeddedImages: 0, embeddedTexts: 0 };
|
|
18
|
+
const items = await library.list();
|
|
19
|
+
const known = new Map((await store.sources(tree)).map((s) => [s.path, s]));
|
|
20
|
+
const listed = new Set(items.map((i) => i.path));
|
|
21
|
+
const gone = [...known.keys()].filter((p) => !listed.has(p));
|
|
22
|
+
if (gone.length > 0) {
|
|
23
|
+
await store.removePaths(tree, gone);
|
|
24
|
+
await store.removeSources(tree, gone);
|
|
25
|
+
stats.removed = gone.length;
|
|
26
|
+
}
|
|
27
|
+
const stale = items.filter((item) => {
|
|
28
|
+
const s = known.get(item.path);
|
|
29
|
+
return !s || s.size !== item.size || s.mtimeMs !== item.mtimeMs || s.meta !== itemMeta(item);
|
|
30
|
+
});
|
|
31
|
+
for (let i = 0; i < stale.length; i += BATCH) {
|
|
32
|
+
await refreshBatch(o, stale.slice(i, i + BATCH), known, stats);
|
|
33
|
+
o.onProgress?.(Math.min(i + BATCH, stale.length), stale.length);
|
|
34
|
+
}
|
|
35
|
+
if (stats.written + stats.removed > 0 || !(await store.builtFrom(tree))) {
|
|
36
|
+
const head = (await library.head?.()) ?? "";
|
|
37
|
+
await store.recordBuiltFrom(tree, { head, at: new Date().toISOString() });
|
|
38
|
+
}
|
|
39
|
+
if (!(await store.embedder()))
|
|
40
|
+
await store.recordEmbedder(embedderRecord(o.embedder));
|
|
41
|
+
return stats;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* What `refreshTree` would embed, decided the same way and without embedding or writing: stale
|
|
45
|
+
* items are loaded and hashed, touched-but-identical ones skipped, and content already in the
|
|
46
|
+
* vector cache or shared within the pending work counted once or not at all. With `rebuild`
|
|
47
|
+
* the tree's rows are taken as gone, so every item is stale; the vector cache still answers.
|
|
48
|
+
*/
|
|
49
|
+
export async function pendingWork(o) {
|
|
50
|
+
const { store, library, tree } = o;
|
|
51
|
+
const ek = embedderKey(o.embedder);
|
|
52
|
+
const items = await library.list();
|
|
53
|
+
const known = new Map((o.rebuild ? [] : await store.sources(tree)).map((s) => [s.path, s]));
|
|
54
|
+
const listed = new Set(items.map((i) => i.path));
|
|
55
|
+
const gone = [...known.keys()].filter((p) => !listed.has(p)).sort();
|
|
56
|
+
const stale = items.filter((item) => {
|
|
57
|
+
const s = known.get(item.path);
|
|
58
|
+
return !s || s.size !== item.size || s.mtimeMs !== item.mtimeMs || s.meta !== itemMeta(item);
|
|
59
|
+
});
|
|
60
|
+
const wanted = new Map();
|
|
61
|
+
const changed = [];
|
|
62
|
+
for (const item of stale) {
|
|
63
|
+
const loaded = await library.load(item);
|
|
64
|
+
const sha256 = sha256Hex(loaded.bytes);
|
|
65
|
+
const meta = itemMeta(item);
|
|
66
|
+
const was = known.get(item.path);
|
|
67
|
+
changed.push([item.path, String(item.size), String(item.mtimeMs), meta]);
|
|
68
|
+
if (was && was.sha256 === sha256 && was.meta === meta)
|
|
69
|
+
continue;
|
|
70
|
+
for (const v of loaded.views) {
|
|
71
|
+
wanted.set(vecKey(sha256, v.view), { sha256, view: v.view, image: true });
|
|
72
|
+
}
|
|
73
|
+
const text = itemText(item);
|
|
74
|
+
wanted.set(vecKey(sha256Hex(text), TEXT_VIEW), {
|
|
75
|
+
sha256: sha256Hex(text),
|
|
76
|
+
view: TEXT_VIEW,
|
|
77
|
+
image: false,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
const cached = new Set((await store.cachedVectors(ek, [...wanted.values()])).map((c) => vecKey(c.sha256, c.view)));
|
|
81
|
+
const missing = [...wanted.entries()].filter(([k]) => !cached.has(k)).map(([, v]) => v);
|
|
82
|
+
const fingerprint = sha256Hex(JSON.stringify({ changed: changed.sort(), gone, embedder: ek, rebuild: o.rebuild ?? false }));
|
|
83
|
+
return {
|
|
84
|
+
images: missing.filter((m) => m.image).length,
|
|
85
|
+
texts: missing.filter((m) => !m.image).length,
|
|
86
|
+
fingerprint,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
async function refreshBatch(o, batch, known, stats) {
|
|
90
|
+
const { store, embedder, library, tree } = o;
|
|
91
|
+
const ek = embedderKey(embedder);
|
|
92
|
+
const sources = [];
|
|
93
|
+
const toWrite = [];
|
|
94
|
+
for (const item of batch) {
|
|
95
|
+
const loaded = await library.load(item);
|
|
96
|
+
const sha256 = sha256Hex(loaded.bytes);
|
|
97
|
+
const meta = itemMeta(item);
|
|
98
|
+
const source = { tree, path: item.path, size: item.size, mtimeMs: item.mtimeMs, sha256, meta };
|
|
99
|
+
sources.push(source);
|
|
100
|
+
const was = known.get(item.path);
|
|
101
|
+
// Touched but identical: only the stat changes.
|
|
102
|
+
if (was && was.sha256 === sha256 && was.meta === meta)
|
|
103
|
+
continue;
|
|
104
|
+
const text = itemText(item);
|
|
105
|
+
toWrite.push({ item, sha256, text, textSha: sha256Hex(text), views: loaded.views });
|
|
106
|
+
}
|
|
107
|
+
// Vectors by content: the cache first, the embedder only for what it has never seen.
|
|
108
|
+
const wanted = new Map();
|
|
109
|
+
for (const w of toWrite) {
|
|
110
|
+
for (const v of w.views)
|
|
111
|
+
wanted.set(vecKey(w.sha256, v.view), { sha256: w.sha256, view: v.view, image: v.image });
|
|
112
|
+
wanted.set(vecKey(w.textSha, TEXT_VIEW), { sha256: w.textSha, view: TEXT_VIEW, text: w.text });
|
|
113
|
+
}
|
|
114
|
+
const vectors = new Map();
|
|
115
|
+
for (const c of await store.cachedVectors(ek, [...wanted.values()])) {
|
|
116
|
+
vectors.set(vecKey(c.sha256, c.view), c.vec);
|
|
117
|
+
}
|
|
118
|
+
const missing = [...wanted.entries()].filter(([k]) => !vectors.has(k)).map(([, v]) => v);
|
|
119
|
+
const images = missing.filter((m) => m.image !== undefined);
|
|
120
|
+
const texts = missing.filter((m) => m.text !== undefined);
|
|
121
|
+
const fresh = [];
|
|
122
|
+
if (images.length > 0) {
|
|
123
|
+
const vecs = await embedder.embedImages(images.map((m) => m.image));
|
|
124
|
+
images.forEach((m, i) => fresh.push({ sha256: m.sha256, view: m.view, vec: vecs[i] }));
|
|
125
|
+
stats.embeddedImages += images.length;
|
|
126
|
+
}
|
|
127
|
+
if (texts.length > 0) {
|
|
128
|
+
const vecs = await embedder.embedTexts(texts.map((m) => m.text));
|
|
129
|
+
texts.forEach((m, i) => fresh.push({ sha256: m.sha256, view: m.view, vec: vecs[i] }));
|
|
130
|
+
stats.embeddedTexts += texts.length;
|
|
131
|
+
}
|
|
132
|
+
if (fresh.length > 0) {
|
|
133
|
+
await store.cacheVectors(ek, fresh);
|
|
134
|
+
for (const f of fresh)
|
|
135
|
+
vectors.set(vecKey(f.sha256, f.view), f.vec);
|
|
136
|
+
}
|
|
137
|
+
const rows = toWrite.flatMap(({ item, sha256, text, textSha, views }) => (views.length ? views : [{ view: "" }]).map((v) => {
|
|
138
|
+
const row = {
|
|
139
|
+
key: `${tree}:${item.path}#${v.view}`,
|
|
140
|
+
tree,
|
|
141
|
+
id: item.id,
|
|
142
|
+
address: item.address,
|
|
143
|
+
source: item.source,
|
|
144
|
+
path: item.path,
|
|
145
|
+
sha256,
|
|
146
|
+
view: v.view,
|
|
147
|
+
text,
|
|
148
|
+
imageVec: vectors.get(vecKey(sha256, v.view)),
|
|
149
|
+
textVec: vectors.get(vecKey(textSha, TEXT_VIEW)),
|
|
150
|
+
};
|
|
151
|
+
for (const f of [
|
|
152
|
+
"game",
|
|
153
|
+
"kind",
|
|
154
|
+
"subject",
|
|
155
|
+
"tags",
|
|
156
|
+
"state",
|
|
157
|
+
"bible",
|
|
158
|
+
"license",
|
|
159
|
+
"origin",
|
|
160
|
+
"declaredOrigin",
|
|
161
|
+
"originEvidence",
|
|
162
|
+
"originSource",
|
|
163
|
+
"originLicense",
|
|
164
|
+
"digitalSourceType",
|
|
165
|
+
"title",
|
|
166
|
+
"description",
|
|
167
|
+
"width",
|
|
168
|
+
"height",
|
|
169
|
+
"durationS",
|
|
170
|
+
"form",
|
|
171
|
+
"tempo",
|
|
172
|
+
"mediaType",
|
|
173
|
+
"mediaSha256",
|
|
174
|
+
"mediaStatus",
|
|
175
|
+
"mediaReason",
|
|
176
|
+
]) {
|
|
177
|
+
if (item[f] !== undefined)
|
|
178
|
+
row[f] = item[f];
|
|
179
|
+
}
|
|
180
|
+
return row;
|
|
181
|
+
}));
|
|
182
|
+
// Views can change with the content, so a rewritten file's old rows go first.
|
|
183
|
+
await store.removePaths(tree, toWrite.map((w) => w.item.path));
|
|
184
|
+
await store.upsert(rows);
|
|
185
|
+
await store.putSources(sources);
|
|
186
|
+
stats.written += toWrite.length;
|
|
187
|
+
}
|