@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.
@@ -0,0 +1,580 @@
1
+ /**
2
+ * The search service: it brings the index up to date from the wiki, every bot's
3
+ * memory and the chat records, then answers a search or a read. A backend only
4
+ * stores and matches; this file owns what a scope means and what a result says.
5
+ */
6
+
7
+ import { createHash } from "node:crypto";
8
+ import { readFileSync, statSync } from "node:fs";
9
+ import { dirname, join, resolve } from "node:path";
10
+ import type { JsonValue, ObjectStore } from "@operad-io/engine";
11
+ import { isRecord } from "@operad-io/engine";
12
+ import { lineCountOf, queryTerms, snippetOf } from "./chunks.ts";
13
+ import { splitMarkdown, titleFromName, titleOf } from "./frontmatter.ts";
14
+ import {
15
+ linkPlaceAt,
16
+ noteLookup,
17
+ parseNoteLinksWithPositions,
18
+ placedNoteLinks,
19
+ resolveNoteLink,
20
+ type NoteLookup,
21
+ } from "../links.ts";
22
+ import { SqliteSearchBackend } from "./backend.ts";
23
+ import {
24
+ botMemoryDirectories,
25
+ chatDocument,
26
+ chatMessages,
27
+ chatOwner,
28
+ chatTitle,
29
+ documentDirectory,
30
+ documentPath,
31
+ fileName,
32
+ markdownFiles,
33
+ } from "./sources.ts";
34
+ import { wikiDirectory } from "../memory.ts";
35
+ import {
36
+ SEARCH_SCOPES,
37
+ SearchError,
38
+ type AboutDocument,
39
+ type BackendHit,
40
+ type Backlink,
41
+ type DocumentFields,
42
+ type DocumentKey,
43
+ type IndexedNoteLink,
44
+ type LinkQuery,
45
+ type NoteLinkInfo,
46
+ type NoteLinkTarget,
47
+ type ReadRequest,
48
+ type ReadResult,
49
+ type SearchBackend,
50
+ type SearchHit,
51
+ type SearchRequest,
52
+ type SearchResult,
53
+ type SearchScope,
54
+ type StoredNoteLink,
55
+ type TokenizerName,
56
+ type UnresolvedTarget,
57
+ } from "./types.ts";
58
+
59
+ /** The index's file name under the operad home's `store/`. */
60
+ export const SEARCH_DATABASE_NAME = "search.sqlite";
61
+
62
+ /** Where the index lives: `<home>/store/search.sqlite`. Deleting it only costs a rebuild. */
63
+ export function searchDatabasePath(home: string): string {
64
+ return join(home, "store", SEARCH_DATABASE_NAME);
65
+ }
66
+
67
+ /** The options a service opens with; a test replaces the file and tokenizer. */
68
+ export interface OpenSearchOptions {
69
+ readonly file?: string | undefined;
70
+ readonly tokenizer?: TokenizerName | undefined;
71
+ readonly backend?: SearchBackend | undefined;
72
+ }
73
+
74
+ /** What one refresh changed. */
75
+ export interface RefreshStats {
76
+ readonly indexed: number;
77
+ readonly removed: number;
78
+ readonly unchanged: number;
79
+ }
80
+
81
+ interface FileRoot {
82
+ readonly scope: "wiki" | "memory";
83
+ readonly owner: string;
84
+ readonly directory: string;
85
+ }
86
+
87
+ function digestOf(text: string): string {
88
+ return createHash("sha256").update(text).digest("hex");
89
+ }
90
+
91
+ /** The links a note writes, each with where a backlink will show it. */
92
+ function indexedLinksOf(text: string): readonly IndexedNoteLink[] {
93
+ return placedNoteLinks(text).map(({ at: _at, ...link }) => link);
94
+ }
95
+
96
+ function rootsOf(home: string, settings: Readonly<Record<string, JsonValue>>): readonly FileRoot[] {
97
+ const roots: FileRoot[] = [
98
+ { scope: "wiki", owner: "", directory: wikiDirectory(home, settings) },
99
+ ];
100
+ for (const memory of botMemoryDirectories(home)) {
101
+ roots.push({ scope: "memory", owner: dirname(memory), directory: memory });
102
+ }
103
+ return roots;
104
+ }
105
+
106
+ function documentId(root: FileRoot, file: string): string {
107
+ const path = documentPath(file, root.directory);
108
+ return root.scope === "wiki" ? `wiki:${path}` : `memory:${root.owner}:${path}`;
109
+ }
110
+
111
+ /** The scopes a request may reach; the default is all three. */
112
+ export function requestedScopes(scopes: readonly SearchScope[] | undefined): readonly SearchScope[] {
113
+ if (scopes === undefined || scopes.length === 0) return [...SEARCH_SCOPES];
114
+ const found: SearchScope[] = [];
115
+ for (const scope of scopes) {
116
+ if (!SEARCH_SCOPES.includes(scope)) throw new SearchError(`unknown scope "${scope}"`);
117
+ if (!found.includes(scope)) found.push(scope);
118
+ }
119
+ return found;
120
+ }
121
+
122
+ /** A limit a caller may use: 20 by default, never more than 100. */
123
+ export function requestedLimit(limit: number | undefined): number {
124
+ if (limit === undefined) return 20;
125
+ if (!Number.isInteger(limit) || limit < 1) throw new SearchError("limit must be a whole number above zero");
126
+ return Math.min(limit, 100);
127
+ }
128
+
129
+ function normaliseFields(
130
+ fields: Readonly<Record<string, string | readonly string[]>> | undefined,
131
+ ): Readonly<Record<string, readonly string[]>> | undefined {
132
+ if (fields === undefined) return undefined;
133
+ const found: Record<string, readonly string[]> = {};
134
+ for (const [key, value] of Object.entries(fields)) {
135
+ const values = typeof value === "string" ? [value] : value;
136
+ const clean = values.filter((item) => item.length > 0);
137
+ if (clean.length > 0) found[key.toLowerCase()] = clean;
138
+ }
139
+ return Object.keys(found).length === 0 ? undefined : found;
140
+ }
141
+
142
+ /** The search service over one index file. */
143
+ export class MemorySearch {
144
+ readonly backend: SearchBackend;
145
+ private readonly home: string;
146
+ private readonly settings: Readonly<Record<string, JsonValue>>;
147
+
148
+ constructor(home: string, settings: Readonly<Record<string, JsonValue>> = {}, options: OpenSearchOptions = {}) {
149
+ this.home = home;
150
+ this.settings = settings;
151
+ this.backend =
152
+ options.backend ??
153
+ new SqliteSearchBackend({
154
+ file: options.file ?? searchDatabasePath(home),
155
+ ...(options.tokenizer === undefined ? {} : { tokenizer: options.tokenizer }),
156
+ });
157
+ }
158
+
159
+ /**
160
+ * Brings file documents and chat records up to date. A file whose size and
161
+ * modification time did not change is left alone; a chat is left alone when
162
+ * its latest fact sequence did not change, and is otherwise compared by the
163
+ * digest of its messages. A document whose file or chat is gone is removed.
164
+ */
165
+ async refresh(store?: ObjectStore | undefined): Promise<RefreshStats> {
166
+ const known = new Map<string, DocumentKey>();
167
+ for (const key of this.backend.keys()) known.set(key.id, key);
168
+ const seen = new Set<string>();
169
+ let indexed = 0;
170
+ let unchanged = 0;
171
+ let notesChanged = false;
172
+
173
+ for (const root of rootsOf(this.home, this.settings)) {
174
+ for (const file of markdownFiles(root.directory)) {
175
+ const id = documentId(root, file);
176
+ seen.add(id);
177
+ let stat;
178
+ try {
179
+ stat = statSync(file, { bigint: true });
180
+ } catch {
181
+ continue;
182
+ }
183
+ const mtimeNs = stat.mtimeNs.toString();
184
+ const size = Number(stat.size);
185
+ const before = this.backend.get(id);
186
+ if (
187
+ before !== undefined &&
188
+ before.file === file &&
189
+ before.mtimeNs === mtimeNs &&
190
+ before.size === size
191
+ ) {
192
+ unchanged += 1;
193
+ continue;
194
+ }
195
+ let raw: string;
196
+ try {
197
+ raw = readFileSync(file, "utf8");
198
+ } catch {
199
+ continue;
200
+ }
201
+ const { fields, body } = splitMarkdown(raw);
202
+ const name = fileName(file);
203
+ const title = titleOf(fields, body, titleFromName(name));
204
+ this.backend.put({
205
+ id,
206
+ scope: root.scope,
207
+ owner: root.owner,
208
+ file,
209
+ path: documentPath(file, root.directory),
210
+ directory: documentDirectory(file, root.directory),
211
+ name,
212
+ title,
213
+ text: body,
214
+ fields,
215
+ lineCount: lineCountOf(body),
216
+ digest: digestOf(body),
217
+ mtimeMs: Number(stat.mtimeMs),
218
+ mtimeNs,
219
+ size,
220
+ links: indexedLinksOf(body),
221
+ });
222
+ indexed += 1;
223
+ notesChanged = true;
224
+ }
225
+ }
226
+
227
+ let removed = 0;
228
+ for (const key of this.backend.keys()) {
229
+ if (key.file === undefined) continue;
230
+ if (seen.has(key.id)) continue;
231
+ this.backend.remove(key.id);
232
+ removed += 1;
233
+ notesChanged = true;
234
+ }
235
+
236
+ if (store !== undefined) {
237
+ const chats = await this.refreshChats(store);
238
+ indexed += chats.indexed;
239
+ unchanged += chats.unchanged;
240
+ removed += chats.removed;
241
+ }
242
+ if (notesChanged) this.resolveNoteLinks();
243
+ return { indexed, removed, unchanged };
244
+ }
245
+
246
+ /**
247
+ * Points the stored links at the notes the index holds now. Links are kept
248
+ * when nothing matches them, so a note written under a name somebody already
249
+ * linked to takes those links on this pass. Only changed rows are written,
250
+ * and a refresh that changed no note has nothing to resolve.
251
+ */
252
+ private resolveNoteLinks(): void {
253
+ const notes = this.backend.keys().filter((key) => key.file !== undefined && key.path !== undefined);
254
+ const byId = new Map<string, DocumentKey>();
255
+ const groups = new Map<string, { readonly paths: string[]; readonly ids: Map<string, string> }>();
256
+ for (const note of notes) {
257
+ byId.set(note.id, note);
258
+ const group = `${note.scope}\u0000${note.owner}`;
259
+ const entry = groups.get(group) ?? { paths: [], ids: new Map<string, string>() };
260
+ if (note.path !== undefined) {
261
+ entry.paths.push(note.path);
262
+ entry.ids.set(note.path, note.id);
263
+ }
264
+ groups.set(group, entry);
265
+ }
266
+ const lookups = new Map<string, NoteLookup>();
267
+ for (const [group, entry] of groups) lookups.set(group, noteLookup(entry.paths));
268
+ const updates: NoteLinkTarget[] = [];
269
+ for (const link of this.backend.allLinks()) {
270
+ const source = byId.get(link.docId);
271
+ if (source?.path === undefined) continue;
272
+ const group = `${source.scope}\u0000${source.owner}`;
273
+ const lookup = lookups.get(group);
274
+ const ids = groups.get(group)?.ids;
275
+ if (lookup === undefined || ids === undefined) continue;
276
+ const resolved = resolveNoteLink(source.path, link, lookup);
277
+ const targetId = resolved === undefined ? undefined : ids.get(resolved);
278
+ if (targetId === link.targetId) continue;
279
+ updates.push({
280
+ docId: link.docId,
281
+ ordinal: link.ordinal,
282
+ ...(targetId === undefined ? {} : { targetId }),
283
+ });
284
+ }
285
+ this.backend.setLinkTargets(updates);
286
+ }
287
+
288
+ private async refreshChats(store: ObjectStore): Promise<RefreshStats> {
289
+ const seen = new Set<string>();
290
+ let indexed = 0;
291
+ let unchanged = 0;
292
+ let cursor: string | undefined;
293
+ do {
294
+ const page = await store.list("chat", { ...(cursor === undefined ? {} : { cursor }), limit: 200 });
295
+ for (const object of page.objects) {
296
+ const owner = chatOwner(object.data);
297
+ if (owner === undefined) continue;
298
+ const id = `chat:${object.id}`;
299
+ seen.add(id);
300
+ const revision = store.latestFactSequence?.({ type: "chat", id: object.id });
301
+ const before = this.backend.get(id);
302
+ // The latest fact sequence changes for a message and for the object
303
+ // itself, so an unchanged chat is left alone without reading its facts.
304
+ if (revision !== undefined && before?.mtimeNs === String(revision)) {
305
+ unchanged += 1;
306
+ continue;
307
+ }
308
+ const title = chatTitle(object.id, object.data);
309
+ const text = chatDocument(object.id, title, chatMessages(store, object.id));
310
+ const digest = digestOf(text);
311
+ if (revision === undefined && before?.digest === digest) {
312
+ unchanged += 1;
313
+ continue;
314
+ }
315
+ this.backend.put({
316
+ id,
317
+ scope: "chats",
318
+ owner,
319
+ directory: "",
320
+ name: "",
321
+ title,
322
+ text,
323
+ fields: {},
324
+ lineCount: lineCountOf(text),
325
+ digest,
326
+ ...(revision === undefined ? {} : { mtimeNs: String(revision) }),
327
+ });
328
+ indexed += 1;
329
+ }
330
+ cursor = page.next;
331
+ } while (cursor !== undefined);
332
+ let removed = 0;
333
+ for (const key of this.backend.keys()) {
334
+ if (key.scope !== "chats" || seen.has(key.id)) continue;
335
+ this.backend.remove(key.id);
336
+ removed += 1;
337
+ }
338
+ return { indexed, removed, unchanged };
339
+ }
340
+
341
+ /** Answers a search over the scopes this bot may reach. */
342
+ search(request: SearchRequest): SearchResult {
343
+ const query = request.text.trim();
344
+ if (query.length === 0) throw new SearchError("search needs a query");
345
+ const scopes = requestedScopes(request.scopes);
346
+ const limit = requestedLimit(request.limit);
347
+ const fields = normaliseFields(request.fields);
348
+ const hits = this.backend.search({
349
+ text: query,
350
+ scopes,
351
+ owner: resolve(request.cwd),
352
+ ...(fields === undefined ? {} : { fields }),
353
+ limit,
354
+ });
355
+ const terms = queryTerms(query);
356
+ const found = new Map<string, BackendHit>();
357
+ for (const hit of hits) {
358
+ // A backend returns chunks; a reader wants the best chunk per document.
359
+ const before = found.get(hit.id);
360
+ if (before === undefined || hit.score > before.score) found.set(hit.id, hit);
361
+ }
362
+ const results: SearchHit[] = [];
363
+ const about = new Map<string, AboutDocument>();
364
+ for (const hit of found.values()) {
365
+ const document = this.backend.get(hit.id);
366
+ if (document === undefined) continue;
367
+ results.push({
368
+ id: document.id,
369
+ scope: document.scope,
370
+ title: document.title,
371
+ ...(document.path === undefined ? {} : { path: document.path }),
372
+ lineStart: hit.lineStart,
373
+ lineEnd: hit.lineEnd,
374
+ snippet: snippetOf(hit.text, terms),
375
+ score: hit.score,
376
+ fields: document.fields,
377
+ });
378
+ const key = `${document.scope}\u0000${document.owner}\u0000${document.directory}`;
379
+ if (about.has(key)) continue;
380
+ const description = this.backend.about(document.scope, document.owner, document.directory);
381
+ if (description === undefined) continue;
382
+ about.set(key, { id: description.id, title: description.title, text: description.text.trim() });
383
+ }
384
+ results.sort((left, right) => right.score - left.score || left.id.localeCompare(right.id));
385
+ return { query, scopes, hits: results.slice(0, limit), about: [...about.values()] };
386
+ }
387
+
388
+ /** Reads one document, or the requested line range of it. */
389
+ read(request: ReadRequest): ReadResult {
390
+ const document = this.backend.get(request.id);
391
+ if (document === undefined) {
392
+ throw new SearchError(
393
+ `no document "${request.id}" in the index; search first, or check that the wiki and memory directory still exist`,
394
+ );
395
+ }
396
+ const lines = document.text.length === 0 ? [] : document.text.split(/\r?\n/u);
397
+ const total = lines.length;
398
+ let from = request.from ?? 1;
399
+ let to = request.to ?? total;
400
+ if (!Number.isInteger(from) || from < 1) throw new SearchError("from must be a whole line number above zero");
401
+ if (!Number.isInteger(to) || to < 1) throw new SearchError("to must be a whole line number above zero");
402
+ from = Math.min(from, Math.max(1, total));
403
+ to = Math.min(to, total);
404
+ if (to < from) to = from;
405
+ return {
406
+ id: document.id,
407
+ scope: document.scope,
408
+ title: document.title,
409
+ ...(document.path === undefined ? {} : { path: document.path }),
410
+ lineStart: total === 0 ? 0 : from,
411
+ lineEnd: total === 0 ? 0 : to,
412
+ totalLines: total,
413
+ text: total === 0 ? "" : lines.slice(from - 1, to).join("\n"),
414
+ fields: document.fields,
415
+ backlinks: this.readBacklinks(document.id),
416
+ };
417
+ }
418
+
419
+ /**
420
+ * The notes that link to a note, with the line and excerpt around each link.
421
+ * A linking note marked untrusted is still listed, and says so.
422
+ */
423
+ readBacklinks(id: string): readonly Backlink[] {
424
+ const notes = this.noteKeys();
425
+ const found: Backlink[] = [];
426
+ for (const link of this.backend.linksTo(id)) {
427
+ // A note's link to itself is not something that links to it.
428
+ if (link.docId === id) continue;
429
+ const source = notes.get(link.docId);
430
+ const document = this.backend.get(link.docId);
431
+ if (source === undefined || document === undefined) continue;
432
+ const place =
433
+ link.line === undefined || link.excerpt === undefined
434
+ ? backlinkPlace(document.text, link)
435
+ : { line: link.line, excerpt: link.excerpt };
436
+ found.push({
437
+ id: source.id,
438
+ path: source.path ?? source.id,
439
+ title: document.title,
440
+ target: link.target,
441
+ ...(link.heading === undefined ? {} : { heading: link.heading }),
442
+ kind: link.kind,
443
+ line: place.line,
444
+ excerpt: place.excerpt,
445
+ untrusted: untrustedFields(document.fields),
446
+ });
447
+ }
448
+ return found;
449
+ }
450
+
451
+ /**
452
+ * The links a note writes, resolved or not. The index answers from what the
453
+ * last refresh stored; a caller refreshes first.
454
+ */
455
+ linksFrom(id: string): readonly NoteLinkInfo[] {
456
+ const notes = this.noteKeys();
457
+ return this.backend
458
+ .allLinks()
459
+ .filter((link) => link.docId === id)
460
+ .map((link) => linkInfo(link, notes));
461
+ }
462
+
463
+ /** The links that point at a note, from the notes that write them. */
464
+ backlinks(id: string): readonly NoteLinkInfo[] {
465
+ const notes = this.noteKeys();
466
+ return this.backend
467
+ .allLinks()
468
+ .filter((link) => link.targetId === id)
469
+ .map((link) => linkInfo(link, notes));
470
+ }
471
+
472
+ /** The targets nobody wrote a note for, and how many links name each. */
473
+ unresolvedTargets(query: LinkQuery = {}): readonly UnresolvedTarget[] {
474
+ const notes = this.noteKeys();
475
+ const counts = new Map<string, number>();
476
+ for (const link of this.backend.allLinks()) {
477
+ if (link.targetId !== undefined) continue;
478
+ const source = notes.get(link.docId);
479
+ if (source === undefined || !inQuery(source, query)) continue;
480
+ counts.set(link.target, (counts.get(link.target) ?? 0) + 1);
481
+ }
482
+ return [...counts.entries()]
483
+ .map(([target, count]) => ({ target, count }))
484
+ .sort((left, right) => right.count - left.count || left.target.localeCompare(right.target));
485
+ }
486
+
487
+ /** The notes no other note links to; a note that only links to itself is one. */
488
+ orphanNotes(query: LinkQuery = {}): readonly DocumentKey[] {
489
+ const notes = this.noteKeys();
490
+ const linked = new Set<string>();
491
+ for (const link of this.backend.allLinks()) {
492
+ if (link.targetId === undefined || link.targetId === link.docId) continue;
493
+ linked.add(link.targetId);
494
+ }
495
+ return [...notes.values()]
496
+ .filter((note) => inQuery(note, query) && !linked.has(note.id))
497
+ .sort((left, right) => (left.path ?? "").localeCompare(right.path ?? ""));
498
+ }
499
+
500
+ /** The note documents the index holds, by id; chats write no links. */
501
+ private noteKeys(): ReadonlyMap<string, DocumentKey> {
502
+ const found = new Map<string, DocumentKey>();
503
+ for (const key of this.backend.keys()) {
504
+ if (key.file === undefined) continue;
505
+ found.set(key.id, key);
506
+ }
507
+ return found;
508
+ }
509
+
510
+ close(): void {
511
+ this.backend.close();
512
+ }
513
+ }
514
+
515
+ /** Whether a note's frontmatter marks it as coming from untrusted content. */
516
+ export function untrustedFields(fields: DocumentFields): boolean {
517
+ return fields["untrusted"]?.some((value) => value.trim().toLowerCase() === "true") === true;
518
+ }
519
+
520
+ /** The line of a stored link and a short piece of the line around it, from a note not stored with one. */
521
+ function backlinkPlace(text: string, link: StoredNoteLink): { readonly line: number; readonly excerpt: string } {
522
+ const links = parseNoteLinksWithPositions(text);
523
+ const place =
524
+ links[link.ordinal] ??
525
+ links.find(
526
+ (entry) =>
527
+ entry.kind === link.kind &&
528
+ entry.target === link.target &&
529
+ entry.heading === link.heading,
530
+ );
531
+ if (place === undefined) return { line: 0, excerpt: "" };
532
+ return linkPlaceAt(text, place.at, link.target);
533
+ }
534
+
535
+ /** Whether a document is inside the scope a link query names. */
536
+ function inQuery(document: DocumentKey, query: LinkQuery): boolean {
537
+ if (query.scope !== undefined && document.scope !== query.scope) return false;
538
+ if (query.owner !== undefined && document.owner !== query.owner) return false;
539
+ return true;
540
+ }
541
+
542
+ /** One stored link with the paths of both ends the index knows. */
543
+ function linkInfo(link: StoredNoteLink, notes: ReadonlyMap<string, DocumentKey>): NoteLinkInfo {
544
+ const from = notes.get(link.docId);
545
+ const to = link.targetId === undefined ? undefined : notes.get(link.targetId);
546
+ return {
547
+ from: link.docId,
548
+ ...(from?.path === undefined ? {} : { fromPath: from.path }),
549
+ ...(link.targetId === undefined ? {} : { to: link.targetId }),
550
+ ...(to?.path === undefined ? {} : { toPath: to.path }),
551
+ target: link.target,
552
+ ...(link.heading === undefined ? {} : { heading: link.heading }),
553
+ kind: link.kind,
554
+ };
555
+ }
556
+
557
+ /** Opens the index a home uses, with the memory plugin's settings. */
558
+ export function openMemorySearch(
559
+ home: string,
560
+ settings: Readonly<Record<string, JsonValue>> = {},
561
+ options: OpenSearchOptions = {},
562
+ ): MemorySearch {
563
+ return new MemorySearch(home, settings, options);
564
+ }
565
+
566
+ /** Whether a parsed value can be a field filter. */
567
+ export function fieldFiltersOf(value: unknown): Record<string, string | readonly string[]> | undefined {
568
+ if (!isRecord(value)) return undefined;
569
+ const found: Record<string, string | readonly string[]> = {};
570
+ for (const [key, item] of Object.entries(value)) {
571
+ if (typeof item === "string") found[key] = item;
572
+ else if (Array.isArray(item)) {
573
+ const values = item.filter((entry): entry is string => typeof entry === "string");
574
+ if (values.length > 0) found[key] = values;
575
+ } else {
576
+ throw new SearchError(`field filter "${key}" must be text or a list of text`);
577
+ }
578
+ }
579
+ return Object.keys(found).length === 0 ? undefined : found;
580
+ }