@operad-io/memory 0.0.0-stage → 0.3.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/LICENSE +21 -0
- package/README.md +16 -2
- package/memory.schema.json +17 -0
- package/package.json +23 -4
- package/skills/memory/SKILL.md +90 -0
- package/src/commit.ts +280 -0
- package/src/index.ts +138 -0
- package/src/link-report.ts +224 -0
- package/src/links.ts +378 -0
- package/src/memory.ts +230 -0
- package/src/search/backend.ts +489 -0
- package/src/search/chunks.ts +86 -0
- package/src/search/command.ts +216 -0
- package/src/search/frontmatter.ts +114 -0
- package/src/search/service.ts +580 -0
- package/src/search/sources.ts +212 -0
- package/src/search/types.ts +245 -0
- package/src/tidy.ts +342 -0
- package/src/wiki.ts +619 -0
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The SQLite FTS5 backend. One file holds every document and its chunks; the
|
|
3
|
+
* document table says which scope and owner a hit belongs to, which is how a
|
|
4
|
+
* bot sees only its own memory and chats beside the shared wiki.
|
|
5
|
+
*
|
|
6
|
+
* The default tokenizer is `trigram`. It is the one measured on Chinese and
|
|
7
|
+
* mixed text: `unicode61` takes a whole run of Chinese characters as one token,
|
|
8
|
+
* so a word inside a sentence does not match. Trigram cannot match a query
|
|
9
|
+
* shorter than three characters, so the backend falls back to a substring scan
|
|
10
|
+
* for those terms.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { Database } from "bun:sqlite";
|
|
14
|
+
import { mkdirSync } from "node:fs";
|
|
15
|
+
import { dirname } from "node:path";
|
|
16
|
+
import { enableWal, setBusyTimeout, writeImmediate } from "@operad-io/engine/platform";
|
|
17
|
+
import { chunksOf, characterLength, queryTerms } from "./chunks.ts";
|
|
18
|
+
import {
|
|
19
|
+
type BackendHit,
|
|
20
|
+
type BackendQuery,
|
|
21
|
+
type DocumentFields,
|
|
22
|
+
type DocumentKey,
|
|
23
|
+
type IndexedDocument,
|
|
24
|
+
type NoteLinkTarget,
|
|
25
|
+
type SearchBackend,
|
|
26
|
+
type StoredNoteLink,
|
|
27
|
+
type SearchScope,
|
|
28
|
+
type TokenizerName,
|
|
29
|
+
} from "./types.ts";
|
|
30
|
+
|
|
31
|
+
interface DocumentRow {
|
|
32
|
+
readonly id: string;
|
|
33
|
+
readonly scope: string;
|
|
34
|
+
readonly owner: string;
|
|
35
|
+
readonly file: string | null;
|
|
36
|
+
readonly path: string | null;
|
|
37
|
+
readonly directory: string;
|
|
38
|
+
readonly name: string;
|
|
39
|
+
readonly title: string;
|
|
40
|
+
readonly text: string;
|
|
41
|
+
readonly fields: string;
|
|
42
|
+
readonly line_count: number;
|
|
43
|
+
readonly digest: string;
|
|
44
|
+
readonly mtime_ms: number | null;
|
|
45
|
+
readonly mtime_ns: string | null;
|
|
46
|
+
readonly size: number | null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
interface KeyRow {
|
|
50
|
+
readonly id: string;
|
|
51
|
+
readonly scope: string;
|
|
52
|
+
readonly owner: string;
|
|
53
|
+
readonly file: string | null;
|
|
54
|
+
readonly path: string | null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
interface MatchRow {
|
|
58
|
+
readonly id: string;
|
|
59
|
+
readonly line_start: number;
|
|
60
|
+
readonly line_end: number;
|
|
61
|
+
readonly text: string;
|
|
62
|
+
readonly rank: number;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface VersionRow {
|
|
66
|
+
readonly value: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
interface LinkRow {
|
|
70
|
+
readonly doc_id: string;
|
|
71
|
+
readonly ordinal: number;
|
|
72
|
+
readonly target: string;
|
|
73
|
+
readonly heading: string | null;
|
|
74
|
+
readonly kind: string;
|
|
75
|
+
readonly target_id: string | null;
|
|
76
|
+
readonly line: number | null;
|
|
77
|
+
readonly excerpt: string | null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The options a backend opens with. */
|
|
81
|
+
export interface SqliteSearchBackendOptions {
|
|
82
|
+
readonly file: string;
|
|
83
|
+
readonly tokenizer?: TokenizerName | undefined;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The version of the link table. A table from another version, and an index
|
|
88
|
+
* built before there was one, is filled from the notes again.
|
|
89
|
+
*/
|
|
90
|
+
const LINK_TABLE_VERSION = "2";
|
|
91
|
+
|
|
92
|
+
function scopeOf(value: string): SearchScope {
|
|
93
|
+
if (value === "wiki" || value === "chats") return value;
|
|
94
|
+
return "memory";
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function fieldsOf(text: string): DocumentFields {
|
|
98
|
+
try {
|
|
99
|
+
const parsed: unknown = JSON.parse(text);
|
|
100
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
|
|
101
|
+
const fields: Record<string, readonly string[]> = {};
|
|
102
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
103
|
+
if (!Array.isArray(value)) continue;
|
|
104
|
+
const values = value.filter((item): item is string => typeof item === "string");
|
|
105
|
+
if (values.length > 0) fields[key] = values;
|
|
106
|
+
}
|
|
107
|
+
return fields;
|
|
108
|
+
} catch {
|
|
109
|
+
return {};
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function documentOf(row: DocumentRow): IndexedDocument {
|
|
114
|
+
return {
|
|
115
|
+
id: row.id,
|
|
116
|
+
scope: scopeOf(row.scope),
|
|
117
|
+
owner: row.owner,
|
|
118
|
+
...(row.file === null ? {} : { file: row.file }),
|
|
119
|
+
...(row.path === null ? {} : { path: row.path }),
|
|
120
|
+
directory: row.directory,
|
|
121
|
+
name: row.name,
|
|
122
|
+
title: row.title,
|
|
123
|
+
text: row.text,
|
|
124
|
+
fields: fieldsOf(row.fields),
|
|
125
|
+
lineCount: row.line_count,
|
|
126
|
+
digest: row.digest,
|
|
127
|
+
...(row.mtime_ms === null ? {} : { mtimeMs: row.mtime_ms }),
|
|
128
|
+
...(row.mtime_ns === null ? {} : { mtimeNs: row.mtime_ns }),
|
|
129
|
+
...(row.size === null ? {} : { size: row.size }),
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function linkOf(row: LinkRow): StoredNoteLink {
|
|
134
|
+
return {
|
|
135
|
+
docId: row.doc_id,
|
|
136
|
+
ordinal: row.ordinal,
|
|
137
|
+
target: row.target,
|
|
138
|
+
...(row.heading === null ? {} : { heading: row.heading }),
|
|
139
|
+
kind: row.kind === "wikilink" ? "wikilink" : "markdown",
|
|
140
|
+
...(row.target_id === null ? {} : { targetId: row.target_id }),
|
|
141
|
+
...(row.line === null ? {} : { line: row.line }),
|
|
142
|
+
...(row.excerpt === null ? {} : { excerpt: row.excerpt }),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function quoteTerm(term: string): string {
|
|
147
|
+
return `"${term.replace(/"/g, "\"\"")}"`;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function ftsQuery(terms: readonly string[]): string {
|
|
151
|
+
return terms.map(quoteTerm).join(" OR ");
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** The default SQLite FTS5 backend. */
|
|
155
|
+
export class SqliteSearchBackend implements SearchBackend {
|
|
156
|
+
readonly tokenizer: TokenizerName;
|
|
157
|
+
private readonly db: Database;
|
|
158
|
+
|
|
159
|
+
constructor(options: SqliteSearchBackendOptions) {
|
|
160
|
+
this.tokenizer = options.tokenizer ?? "trigram";
|
|
161
|
+
if (options.file !== ":memory:") mkdirSync(dirname(options.file), { recursive: true });
|
|
162
|
+
this.db = new Database(options.file);
|
|
163
|
+
setBusyTimeout(this.db);
|
|
164
|
+
if (options.file !== ":memory:") enableWal(this.db);
|
|
165
|
+
this.ensureSchema();
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
private ensureSchema(): void {
|
|
169
|
+
this.db.run("CREATE TABLE IF NOT EXISTS search_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)");
|
|
170
|
+
this.db.run(
|
|
171
|
+
"CREATE TABLE IF NOT EXISTS search_documents (" +
|
|
172
|
+
"id TEXT PRIMARY KEY, scope TEXT NOT NULL, owner TEXT NOT NULL, file TEXT, path TEXT, " +
|
|
173
|
+
"directory TEXT NOT NULL, name TEXT NOT NULL, title TEXT NOT NULL, text TEXT NOT NULL, " +
|
|
174
|
+
"fields TEXT NOT NULL, line_count INTEGER NOT NULL, digest TEXT NOT NULL, " +
|
|
175
|
+
"mtime_ms REAL, mtime_ns TEXT, size INTEGER)",
|
|
176
|
+
);
|
|
177
|
+
// A store made before the nanosecond column existed gains it without a
|
|
178
|
+
// version: the column is an optimisation, not the identity of a document.
|
|
179
|
+
const columns = this.db.query<{ name: string }, []>("PRAGMA table_info(search_documents)").all();
|
|
180
|
+
if (!columns.some((column) => column.name === "mtime_ns")) {
|
|
181
|
+
this.db.run("ALTER TABLE search_documents ADD COLUMN mtime_ns TEXT");
|
|
182
|
+
}
|
|
183
|
+
this.db.run("CREATE INDEX IF NOT EXISTS search_documents_scope ON search_documents (scope, owner)");
|
|
184
|
+
this.db.run("CREATE INDEX IF NOT EXISTS search_documents_file ON search_documents (file)");
|
|
185
|
+
this.db.run(
|
|
186
|
+
"CREATE TABLE IF NOT EXISTS search_fields (" +
|
|
187
|
+
"doc_id TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, " +
|
|
188
|
+
"PRIMARY KEY (doc_id, key, value))",
|
|
189
|
+
);
|
|
190
|
+
this.db.run("CREATE INDEX IF NOT EXISTS search_fields_lookup ON search_fields (key, value)");
|
|
191
|
+
const current = this.db
|
|
192
|
+
.query<VersionRow, []>("SELECT value FROM search_meta WHERE key = 'tokenizer'")
|
|
193
|
+
.get();
|
|
194
|
+
if (current !== null && current.value !== this.tokenizer) {
|
|
195
|
+
// The index is a cache: a different tokenizer means a fresh one, links too.
|
|
196
|
+
this.db.run("DROP TABLE IF EXISTS search_chunks");
|
|
197
|
+
this.db.run("DROP TABLE IF EXISTS search_links");
|
|
198
|
+
this.db.run("DELETE FROM search_fields");
|
|
199
|
+
this.db.run("DELETE FROM search_documents");
|
|
200
|
+
}
|
|
201
|
+
// The link table is part of the same cache as the chunks. An index built
|
|
202
|
+
// before it, or with another version of it, holds notes whose links were
|
|
203
|
+
// never parsed, and a refresh skips a note whose modification time and
|
|
204
|
+
// size did not change. Clearing that stored time makes the next refresh
|
|
205
|
+
// read every note again and fill the table.
|
|
206
|
+
const links = this.db
|
|
207
|
+
.query<VersionRow, []>("SELECT value FROM search_meta WHERE key = 'links'")
|
|
208
|
+
.get();
|
|
209
|
+
if (links === null || links.value !== LINK_TABLE_VERSION) {
|
|
210
|
+
this.db.run("DROP TABLE IF EXISTS search_links");
|
|
211
|
+
this.db.run("UPDATE search_documents SET mtime_ns = NULL WHERE scope != 'chats'");
|
|
212
|
+
}
|
|
213
|
+
this.db.run(
|
|
214
|
+
"CREATE TABLE IF NOT EXISTS search_links (" +
|
|
215
|
+
"doc_id TEXT NOT NULL, ordinal INTEGER NOT NULL, target TEXT NOT NULL, heading TEXT, " +
|
|
216
|
+
"kind TEXT NOT NULL, target_id TEXT, line INTEGER, excerpt TEXT, " +
|
|
217
|
+
"PRIMARY KEY (doc_id, ordinal))",
|
|
218
|
+
);
|
|
219
|
+
this.db.run("CREATE INDEX IF NOT EXISTS search_links_target ON search_links (target_id)");
|
|
220
|
+
this.db.run(
|
|
221
|
+
"INSERT INTO search_meta (key, value) VALUES ('links', ?) " +
|
|
222
|
+
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
|
223
|
+
[LINK_TABLE_VERSION],
|
|
224
|
+
);
|
|
225
|
+
this.db.run(
|
|
226
|
+
`CREATE VIRTUAL TABLE IF NOT EXISTS search_chunks USING fts5(` +
|
|
227
|
+
`text, doc_id UNINDEXED, line_start UNINDEXED, line_end UNINDEXED, ` +
|
|
228
|
+
`tokenize = '${this.tokenizer}')`,
|
|
229
|
+
);
|
|
230
|
+
this.db.run(
|
|
231
|
+
"INSERT INTO search_meta (key, value) VALUES ('tokenizer', ?) " +
|
|
232
|
+
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
|
233
|
+
[this.tokenizer],
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
put(document: IndexedDocument): void {
|
|
238
|
+
writeImmediate(this.db, () => {
|
|
239
|
+
this.db.run("DELETE FROM search_chunks WHERE doc_id = ?", [document.id]);
|
|
240
|
+
this.db.run("DELETE FROM search_fields WHERE doc_id = ?", [document.id]);
|
|
241
|
+
this.db.run("DELETE FROM search_links WHERE doc_id = ?", [document.id]);
|
|
242
|
+
this.db.run(
|
|
243
|
+
"INSERT INTO search_documents " +
|
|
244
|
+
"(id, scope, owner, file, path, directory, name, title, text, fields, line_count, digest, mtime_ms, mtime_ns, size) " +
|
|
245
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " +
|
|
246
|
+
"ON CONFLICT(id) DO UPDATE SET scope = excluded.scope, owner = excluded.owner, " +
|
|
247
|
+
"file = excluded.file, path = excluded.path, directory = excluded.directory, " +
|
|
248
|
+
"name = excluded.name, title = excluded.title, text = excluded.text, " +
|
|
249
|
+
"fields = excluded.fields, line_count = excluded.line_count, digest = excluded.digest, " +
|
|
250
|
+
"mtime_ms = excluded.mtime_ms, mtime_ns = excluded.mtime_ns, size = excluded.size",
|
|
251
|
+
[
|
|
252
|
+
document.id,
|
|
253
|
+
document.scope,
|
|
254
|
+
document.owner,
|
|
255
|
+
document.file ?? null,
|
|
256
|
+
document.path ?? null,
|
|
257
|
+
document.directory,
|
|
258
|
+
document.name,
|
|
259
|
+
document.title,
|
|
260
|
+
document.text,
|
|
261
|
+
JSON.stringify(document.fields),
|
|
262
|
+
document.lineCount,
|
|
263
|
+
document.digest,
|
|
264
|
+
document.mtimeMs ?? null,
|
|
265
|
+
document.mtimeNs ?? null,
|
|
266
|
+
document.size ?? null,
|
|
267
|
+
],
|
|
268
|
+
);
|
|
269
|
+
const field = this.db.query(
|
|
270
|
+
"INSERT OR IGNORE INTO search_fields (doc_id, key, value) VALUES (?, ?, ?)",
|
|
271
|
+
);
|
|
272
|
+
for (const [key, values] of Object.entries(document.fields)) {
|
|
273
|
+
for (const value of values) field.run(document.id, key, value);
|
|
274
|
+
}
|
|
275
|
+
const chunk = this.db.query(
|
|
276
|
+
"INSERT INTO search_chunks (text, doc_id, line_start, line_end) VALUES (?, ?, ?, ?)",
|
|
277
|
+
);
|
|
278
|
+
for (const piece of chunksOf(document.text)) {
|
|
279
|
+
chunk.run(piece.text, document.id, piece.lineStart, piece.lineEnd);
|
|
280
|
+
}
|
|
281
|
+
const link = this.db.query(
|
|
282
|
+
"INSERT INTO search_links (doc_id, ordinal, target, heading, kind, target_id, line, excerpt) " +
|
|
283
|
+
"VALUES (?, ?, ?, ?, ?, NULL, ?, ?)",
|
|
284
|
+
);
|
|
285
|
+
(document.links ?? []).forEach((entry, ordinal) => {
|
|
286
|
+
link.run(
|
|
287
|
+
document.id,
|
|
288
|
+
ordinal,
|
|
289
|
+
entry.target,
|
|
290
|
+
entry.heading ?? null,
|
|
291
|
+
entry.kind,
|
|
292
|
+
entry.line ?? null,
|
|
293
|
+
entry.excerpt ?? null,
|
|
294
|
+
);
|
|
295
|
+
});
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
remove(id: string): void {
|
|
300
|
+
writeImmediate(this.db, () => {
|
|
301
|
+
this.db.run("DELETE FROM search_chunks WHERE doc_id = ?", [id]);
|
|
302
|
+
this.db.run("DELETE FROM search_fields WHERE doc_id = ?", [id]);
|
|
303
|
+
this.db.run("DELETE FROM search_links WHERE doc_id = ?", [id]);
|
|
304
|
+
// A link to a note that is gone is kept, with no target, so the note
|
|
305
|
+
// that appears at that name takes it on the next resolution.
|
|
306
|
+
this.db.run("UPDATE search_links SET target_id = NULL WHERE target_id = ?", [id]);
|
|
307
|
+
this.db.run("DELETE FROM search_documents WHERE id = ?", [id]);
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
get(id: string): IndexedDocument | undefined {
|
|
312
|
+
const row = this.db
|
|
313
|
+
.query<DocumentRow, [string]>(
|
|
314
|
+
"SELECT id, scope, owner, file, path, directory, name, title, text, fields, " +
|
|
315
|
+
"line_count, digest, mtime_ms, mtime_ns, size FROM search_documents WHERE id = ?",
|
|
316
|
+
)
|
|
317
|
+
.get(id);
|
|
318
|
+
return row === null ? undefined : documentOf(row);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
keys(): readonly DocumentKey[] {
|
|
322
|
+
return this.db
|
|
323
|
+
.query<KeyRow, []>("SELECT id, scope, owner, file, path FROM search_documents ORDER BY id")
|
|
324
|
+
.all()
|
|
325
|
+
.map((row) => ({
|
|
326
|
+
id: row.id,
|
|
327
|
+
scope: scopeOf(row.scope),
|
|
328
|
+
owner: row.owner,
|
|
329
|
+
...(row.file === null ? {} : { file: row.file }),
|
|
330
|
+
...(row.path === null ? {} : { path: row.path }),
|
|
331
|
+
}));
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
about(scope: SearchScope, owner: string, directory: string): IndexedDocument | undefined {
|
|
335
|
+
const row = this.db
|
|
336
|
+
.query<DocumentRow, [string, string, string]>(
|
|
337
|
+
"SELECT id, scope, owner, file, path, directory, name, title, text, fields, " +
|
|
338
|
+
"line_count, digest, mtime_ms, mtime_ns, size FROM search_documents " +
|
|
339
|
+
"WHERE scope = ? AND owner = ? AND directory = ? AND name = '_about.md' LIMIT 1",
|
|
340
|
+
)
|
|
341
|
+
.get(scope, owner, directory);
|
|
342
|
+
return row === null ? undefined : documentOf(row);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
allLinks(): readonly StoredNoteLink[] {
|
|
346
|
+
return this.db
|
|
347
|
+
.query<LinkRow, []>(
|
|
348
|
+
"SELECT doc_id, ordinal, target, heading, kind, target_id, line, excerpt FROM search_links " +
|
|
349
|
+
"ORDER BY doc_id, ordinal",
|
|
350
|
+
)
|
|
351
|
+
.all()
|
|
352
|
+
.map(linkOf);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
linksTo(targetId: string): readonly StoredNoteLink[] {
|
|
356
|
+
return this.db
|
|
357
|
+
.query<LinkRow, [string]>(
|
|
358
|
+
"SELECT doc_id, ordinal, target, heading, kind, target_id, line, excerpt FROM search_links " +
|
|
359
|
+
"WHERE target_id = ? ORDER BY doc_id, ordinal",
|
|
360
|
+
)
|
|
361
|
+
.all(targetId)
|
|
362
|
+
.map(linkOf);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
setLinkTargets(updates: readonly NoteLinkTarget[]): void {
|
|
366
|
+
if (updates.length === 0) return;
|
|
367
|
+
writeImmediate(this.db, () => {
|
|
368
|
+
const update = this.db.query(
|
|
369
|
+
"UPDATE search_links SET target_id = ? WHERE doc_id = ? AND ordinal = ?",
|
|
370
|
+
);
|
|
371
|
+
for (const entry of updates) {
|
|
372
|
+
update.run(entry.targetId ?? null, entry.docId, entry.ordinal);
|
|
373
|
+
}
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
search(query: BackendQuery): readonly BackendHit[] {
|
|
378
|
+
const terms = queryTerms(query.text);
|
|
379
|
+
if (terms.length === 0) return [];
|
|
380
|
+
const long = terms.filter((term) => characterLength(term) >= 3);
|
|
381
|
+
const short = terms.filter((term) => characterLength(term) < 3);
|
|
382
|
+
const found = new Map<string, BackendHit>();
|
|
383
|
+
// A tokenizer other than trigram is only used to measure it; the substring
|
|
384
|
+
// fallback is what makes trigram's short-query gap harmless.
|
|
385
|
+
const fallback = this.tokenizer === "trigram" && short.length > 0;
|
|
386
|
+
if (long.length > 0) {
|
|
387
|
+
for (const hit of this.matchFts(query, long)) found.set(hit.id, hit);
|
|
388
|
+
}
|
|
389
|
+
if (fallback) {
|
|
390
|
+
for (const hit of this.matchSubstring(query, short)) {
|
|
391
|
+
const before = found.get(hit.id);
|
|
392
|
+
if (before === undefined || hit.score > before.score) found.set(hit.id, hit);
|
|
393
|
+
}
|
|
394
|
+
} else if (long.length === 0) {
|
|
395
|
+
// A non-trigram backend still asks FTS for its short terms.
|
|
396
|
+
for (const hit of this.matchFts(query, short)) found.set(hit.id, hit);
|
|
397
|
+
}
|
|
398
|
+
return [...found.values()]
|
|
399
|
+
.sort((left, right) => right.score - left.score || left.id.localeCompare(right.id))
|
|
400
|
+
.slice(0, query.limit);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
close(): void {
|
|
404
|
+
this.db.close();
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** The scope, owner and frontmatter conditions every query shares. */
|
|
408
|
+
private filters(query: BackendQuery): { readonly sql: readonly string[]; readonly params: readonly string[] } {
|
|
409
|
+
const sql: string[] = [];
|
|
410
|
+
const params: string[] = [];
|
|
411
|
+
const places = query.scopes.map(() => "?").join(", ");
|
|
412
|
+
sql.push(`d.scope IN (${places})`);
|
|
413
|
+
params.push(...query.scopes);
|
|
414
|
+
if (query.scopes.some((scope) => scope !== "wiki")) {
|
|
415
|
+
// The wiki is shared; a bot's memory and chats are only the ones whose
|
|
416
|
+
// owner is the bot's working directory.
|
|
417
|
+
sql.push("(d.scope = 'wiki' OR d.owner = ?)");
|
|
418
|
+
params.push(query.owner);
|
|
419
|
+
}
|
|
420
|
+
for (const [key, value] of Object.entries(query.fields ?? {})) {
|
|
421
|
+
const values = typeof value === "string" ? [value] : value;
|
|
422
|
+
if (values.length === 0) continue;
|
|
423
|
+
const list = values.map(() => "?").join(", ");
|
|
424
|
+
sql.push(
|
|
425
|
+
"EXISTS (SELECT 1 FROM search_fields f WHERE f.doc_id = d.id " +
|
|
426
|
+
`AND f.key = ? AND f.value IN (${list}))`,
|
|
427
|
+
);
|
|
428
|
+
params.push(key.toLowerCase(), ...values);
|
|
429
|
+
}
|
|
430
|
+
return { sql, params };
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
private matchFts(query: BackendQuery, terms: readonly string[]): readonly BackendHit[] {
|
|
434
|
+
const filter = this.filters(query);
|
|
435
|
+
const sql =
|
|
436
|
+
"SELECT d.id AS id, search_chunks.line_start AS line_start, " +
|
|
437
|
+
"search_chunks.line_end AS line_end, search_chunks.text AS text, " +
|
|
438
|
+
"bm25(search_chunks) AS rank FROM search_chunks " +
|
|
439
|
+
"JOIN search_documents d ON d.id = search_chunks.doc_id " +
|
|
440
|
+
`WHERE search_chunks MATCH ? AND ${filter.sql.join(" AND ")} ` +
|
|
441
|
+
"ORDER BY rank LIMIT ?";
|
|
442
|
+
const rows = this.db
|
|
443
|
+
.query<MatchRow, (string | number)[]>(sql)
|
|
444
|
+
.all(ftsQuery(terms), ...filter.params, query.limit * 4);
|
|
445
|
+
return rows.map((row) => ({
|
|
446
|
+
id: row.id,
|
|
447
|
+
lineStart: row.line_start,
|
|
448
|
+
lineEnd: row.line_end,
|
|
449
|
+
text: row.text,
|
|
450
|
+
score: -row.rank,
|
|
451
|
+
}));
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* Trigram cannot match fewer than three characters. These terms are found by
|
|
456
|
+
* scanning the chunks the caller may see with `instr`, the documented
|
|
457
|
+
* fallback; it is slower and bounded by the same scope and field filters.
|
|
458
|
+
*/
|
|
459
|
+
private matchSubstring(query: BackendQuery, terms: readonly string[]): readonly BackendHit[] {
|
|
460
|
+
const filter = this.filters(query);
|
|
461
|
+
const any = terms.map(() => "instr(lower(search_chunks.text), lower(?)) > 0").join(" OR ");
|
|
462
|
+
const sql =
|
|
463
|
+
"SELECT d.id AS id, search_chunks.line_start AS line_start, " +
|
|
464
|
+
"search_chunks.line_end AS line_end, search_chunks.text AS text, 0 AS rank " +
|
|
465
|
+
"FROM search_chunks JOIN search_documents d ON d.id = search_chunks.doc_id " +
|
|
466
|
+
`WHERE (${any}) AND ${filter.sql.join(" AND ")} ` +
|
|
467
|
+
"ORDER BY d.id LIMIT ?";
|
|
468
|
+
const rows = this.db
|
|
469
|
+
.query<MatchRow, (string | number)[]>(sql)
|
|
470
|
+
.all(...terms, ...filter.params, query.limit * 4);
|
|
471
|
+
return rows.map((row) => {
|
|
472
|
+
const text = row.text.toLocaleLowerCase();
|
|
473
|
+
let at = -1;
|
|
474
|
+
for (const term of terms) {
|
|
475
|
+
const found = text.indexOf(term.toLocaleLowerCase());
|
|
476
|
+
if (found >= 0 && (at < 0 || found < at)) at = found;
|
|
477
|
+
}
|
|
478
|
+
// Earlier is better, and a shorter chunk is a tighter answer.
|
|
479
|
+
const score = 1 / (1 + Math.max(0, at)) + (terms.length === 1 ? 0.5 : 0);
|
|
480
|
+
return {
|
|
481
|
+
id: row.id,
|
|
482
|
+
lineStart: row.line_start,
|
|
483
|
+
lineEnd: row.line_end,
|
|
484
|
+
text: row.text,
|
|
485
|
+
score,
|
|
486
|
+
};
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/** How a document becomes searchable chunks and a snippet a reader can scan. */
|
|
2
|
+
|
|
3
|
+
/** One slice of a document, with the lines it covers (1-based). */
|
|
4
|
+
export interface TextChunk {
|
|
5
|
+
readonly text: string;
|
|
6
|
+
readonly lineStart: number;
|
|
7
|
+
readonly lineEnd: number;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** How many lines one chunk holds, and how many it repeats from the last. */
|
|
11
|
+
export const CHUNK_LINES = 20;
|
|
12
|
+
export const CHUNK_OVERLAP = 2;
|
|
13
|
+
|
|
14
|
+
/** The number of lines a text has, with 0 for empty text. */
|
|
15
|
+
export function lineCountOf(text: string): number {
|
|
16
|
+
if (text.length === 0) return 0;
|
|
17
|
+
return text.split(/\r?\n/u).length;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Splits text into overlapping line windows. The overlap keeps a phrase that
|
|
22
|
+
* straddles a chunk boundary reachable; line numbers are the document's own.
|
|
23
|
+
*/
|
|
24
|
+
export function chunksOf(
|
|
25
|
+
text: string,
|
|
26
|
+
maxLines: number = CHUNK_LINES,
|
|
27
|
+
overlap: number = CHUNK_OVERLAP,
|
|
28
|
+
): readonly TextChunk[] {
|
|
29
|
+
if (text.length === 0) return [];
|
|
30
|
+
const lines = text.split(/\r?\n/u);
|
|
31
|
+
const limit = Math.max(1, maxLines);
|
|
32
|
+
const step = Math.max(1, limit - Math.max(0, overlap));
|
|
33
|
+
const chunks: TextChunk[] = [];
|
|
34
|
+
for (let start = 0; start < lines.length; start += step) {
|
|
35
|
+
const end = Math.min(lines.length, start + limit);
|
|
36
|
+
const textOfChunk = lines.slice(start, end).join("\n");
|
|
37
|
+
if (textOfChunk.trim().length > 0) {
|
|
38
|
+
chunks.push({ text: textOfChunk, lineStart: start + 1, lineEnd: end });
|
|
39
|
+
}
|
|
40
|
+
if (end >= lines.length) break;
|
|
41
|
+
}
|
|
42
|
+
return chunks;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* A short piece of text around the first term it contains. The markers say
|
|
47
|
+
* where the snippet was cut, not where the match is: a reader sees the lines a
|
|
48
|
+
* result points at.
|
|
49
|
+
*/
|
|
50
|
+
export function snippetOf(text: string, terms: readonly string[], width: number = 180): string {
|
|
51
|
+
const flat = text.replace(/\s+/gu, " ").trim();
|
|
52
|
+
if (flat.length <= width) return flat;
|
|
53
|
+
let at = -1;
|
|
54
|
+
for (const term of terms) {
|
|
55
|
+
if (term.length === 0) continue;
|
|
56
|
+
const found = flat.toLocaleLowerCase().indexOf(term.toLocaleLowerCase());
|
|
57
|
+
if (found >= 0 && (at < 0 || found < at)) at = found;
|
|
58
|
+
}
|
|
59
|
+
if (at < 0) at = 0;
|
|
60
|
+
const half = Math.floor(width / 2);
|
|
61
|
+
const start = Math.max(0, at - half);
|
|
62
|
+
const end = Math.min(flat.length, start + width);
|
|
63
|
+
return `${start > 0 ? "…" : ""}${flat.slice(start, end)}${end < flat.length ? "…" : ""}`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Splits a query into terms. Whitespace and common punctuation separate them;
|
|
68
|
+
* a run of Chinese characters with no separator stays one term, which is what a
|
|
69
|
+
* phrase search needs. The caller decides which terms the tokenizer can use.
|
|
70
|
+
*/
|
|
71
|
+
export function queryTerms(text: string): readonly string[] {
|
|
72
|
+
const trimmed = text.trim();
|
|
73
|
+
if (trimmed.length === 0) return [];
|
|
74
|
+
const parts = trimmed.split(/[\s,,.。;;::!!??()()[\]【】{}"'“”‘’、/\\|]+/u);
|
|
75
|
+
const terms: string[] = [];
|
|
76
|
+
for (const part of parts) {
|
|
77
|
+
const term = part.trim();
|
|
78
|
+
if (term.length > 0 && !terms.includes(term)) terms.push(term);
|
|
79
|
+
}
|
|
80
|
+
return terms;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The number of Unicode characters in a term, which trigram counts. */
|
|
84
|
+
export function characterLength(term: string): number {
|
|
85
|
+
return [...term].length;
|
|
86
|
+
}
|