@luxass/pi-session-search 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,577 @@
1
+ /**
2
+ * The /find-all index: a SQLite database with a contentless FTS5 trigram table.
3
+ *
4
+ * The index never stores message text. Each searchable item keeps the byte
5
+ * range of its session-file line, and search reads that line back to verify
6
+ * the hit and build the preview (see index-search.ts). The FTS table holds the
7
+ * trigrams of each item's case-folded text (see foldForIndex()), so any
8
+ * substring of three or more characters narrows the candidates, mid-word
9
+ * included. Shorter terms fall back to verifying the most recent items, and
10
+ * the result says it was truncated when that bound was reached.
11
+ *
12
+ * Several pi processes can share the database: every write runs in a
13
+ * BEGIN IMMEDIATE transaction that rereads the file's indexed offset first, so
14
+ * no line is indexed twice. Each search reads one consistent snapshot inside a
15
+ * read transaction.
16
+ *
17
+ * Loaded by the index worker, which strips types itself: type annotations only, and no Pi packages.
18
+ */
19
+
20
+ import { randomUUID } from "node:crypto";
21
+ import {
22
+ closeSync,
23
+ existsSync,
24
+ fstatSync,
25
+ mkdirSync,
26
+ openSync,
27
+ readdirSync,
28
+ statSync,
29
+ type BigIntStats,
30
+ } from "node:fs";
31
+ import { dirname, join } from "node:path";
32
+ import { DatabaseSync, type StatementSync } from "node:sqlite";
33
+
34
+ import {
35
+ fileIdentity,
36
+ type IndexedFileRecord,
37
+ type IndexedItemRequest,
38
+ indexedBytesIntact,
39
+ type IndexSearchRequest,
40
+ type IndexSearchResult,
41
+ integer,
42
+ modificationTime,
43
+ optionalText,
44
+ readIndexedItemText,
45
+ type SearchDatabase,
46
+ searchIndex,
47
+ text,
48
+ } from "./index-search.ts";
49
+ import { checkpointDigest, readCompleteLines } from "./jsonl-reader.ts";
50
+ import { foldForIndex } from "./query.ts";
51
+ import { extractSearchableItems } from "./searchable-text.ts";
52
+
53
+ export {
54
+ buildMatchExpression,
55
+ type IndexedItemRequest,
56
+ type IndexSearchRequest,
57
+ type IndexSearchResult,
58
+ } from "./index-search.ts";
59
+
60
+ /** Bump when the tables change. An index with another version is dropped and rebuilt. */
61
+ const SCHEMA_VERSION = "4";
62
+
63
+ /**
64
+ * The stored format: the schema version plus the Unicode version that
65
+ * foldForIndex() used. A Node.js upgrade can change case mappings, and text
66
+ * folded the old way could hide matches, so either change rebuilds the index.
67
+ */
68
+ const INDEX_FORMAT = `${SCHEMA_VERSION}+unicode-${process.versions.unicode}`;
69
+
70
+ /** Bytes of session file read per write transaction, to keep lock times short. */
71
+ const BYTES_PER_TRANSACTION = 4 * 1024 * 1024;
72
+
73
+ const SCHEMA_SQL = `
74
+ CREATE TABLE IF NOT EXISTS index_meta (
75
+ key TEXT PRIMARY KEY,
76
+ value TEXT NOT NULL
77
+ );
78
+ CREATE TABLE IF NOT EXISTS session_files (
79
+ file_id INTEGER PRIMARY KEY,
80
+ path TEXT NOT NULL UNIQUE,
81
+ identity TEXT NOT NULL DEFAULT '',
82
+ file_size INTEGER NOT NULL DEFAULT 0,
83
+ modified_ns TEXT NOT NULL DEFAULT '',
84
+ epoch TEXT NOT NULL DEFAULT '',
85
+ indexed_bytes INTEGER NOT NULL DEFAULT 0,
86
+ checkpoint TEXT NOT NULL DEFAULT '',
87
+ session_id TEXT NOT NULL DEFAULT '',
88
+ cwd TEXT NOT NULL DEFAULT '',
89
+ session_name TEXT,
90
+ last_entry_id TEXT,
91
+ last_activity INTEGER NOT NULL DEFAULT 0
92
+ );
93
+ CREATE TABLE IF NOT EXISTS entry_parents (
94
+ file_id INTEGER NOT NULL,
95
+ entry_id TEXT NOT NULL,
96
+ parent_id TEXT,
97
+ PRIMARY KEY (file_id, entry_id)
98
+ ) WITHOUT ROWID;
99
+ CREATE TABLE IF NOT EXISTS items (
100
+ item_id INTEGER PRIMARY KEY,
101
+ file_id INTEGER NOT NULL,
102
+ entry_id TEXT NOT NULL,
103
+ part INTEGER NOT NULL,
104
+ kind TEXT NOT NULL,
105
+ tool_name TEXT,
106
+ tool_name_key TEXT,
107
+ tool_name_tail TEXT,
108
+ line_offset INTEGER NOT NULL,
109
+ line_length INTEGER NOT NULL,
110
+ created_at INTEGER NOT NULL
111
+ );
112
+ CREATE INDEX IF NOT EXISTS items_by_file ON items (file_id);
113
+ CREATE INDEX IF NOT EXISTS items_by_time ON items (created_at DESC);
114
+ CREATE VIRTUAL TABLE IF NOT EXISTS items_text USING fts5 (
115
+ body,
116
+ content = '',
117
+ contentless_delete = 1,
118
+ detail = none,
119
+ tokenize = 'trigram case_sensitive 1'
120
+ );
121
+ `;
122
+
123
+ const DROP_SQL = `
124
+ DROP TABLE IF EXISTS items_text;
125
+ DROP TABLE IF EXISTS items;
126
+ DROP TABLE IF EXISTS entry_parents;
127
+ DROP TABLE IF EXISTS session_files;
128
+ DROP TABLE IF EXISTS index_meta;
129
+ `;
130
+
131
+ /**
132
+ * The keys toolNameMatches() compares: the whole name lowercased, and the
133
+ * lowercased part after the last `__`. Stored per item so SQL can filter by
134
+ * tool with the same Unicode lowercasing as JavaScript.
135
+ */
136
+ function toolNameKeys(toolName: string | undefined): { key: string | null; tail: string | null } {
137
+ if (toolName === undefined) {
138
+ return { key: null, tail: null };
139
+ }
140
+ const key = toolName.toLowerCase();
141
+ const separator = key.lastIndexOf("__");
142
+ return { key, tail: separator >= 0 ? key.slice(separator + 2) : null };
143
+ }
144
+
145
+ /**
146
+ * Lists session files below each root: `root/*.jsonl` and `root/<dir>/*.jsonl`,
147
+ * which is how pi lays out its session directory. Newest files come first so
148
+ * recent sessions become searchable early in a first build.
149
+ */
150
+ export function listSessionFiles(roots: readonly string[]): string[] {
151
+ const found = new Map<string, number>();
152
+ const visit = (directory: string, depth: number): void => {
153
+ let names;
154
+ try {
155
+ names = readdirSync(directory, { withFileTypes: true });
156
+ } catch {
157
+ return;
158
+ }
159
+ for (const dirent of names) {
160
+ const path = join(directory, dirent.name);
161
+ if (dirent.isDirectory() && depth > 0) {
162
+ visit(path, depth - 1);
163
+ } else if (dirent.isFile() && dirent.name.endsWith(".jsonl") && !found.has(path)) {
164
+ try {
165
+ found.set(path, statSync(path).mtimeMs);
166
+ } catch {
167
+ // Deleted while listing.
168
+ }
169
+ }
170
+ }
171
+ };
172
+ for (const root of roots) {
173
+ visit(root, 1);
174
+ }
175
+ return [...found.entries()].toSorted((left, right) => right[1] - left[1]).map(([path]) => path);
176
+ }
177
+
178
+ export type FileSyncResult = "unchanged" | "updated" | "stopped" | "missing";
179
+
180
+ export interface SyncProgress {
181
+ done: number;
182
+ total: number;
183
+ /** True when this step committed new data, so a running search may want to refresh. */
184
+ changed: boolean;
185
+ }
186
+
187
+ export interface SyncOptions {
188
+ onProgress?: (progress: SyncProgress) => void;
189
+ /** Checked between transactions. Return true to stop early and cleanly. */
190
+ shouldStop?: () => boolean;
191
+ }
192
+
193
+ export interface SyncSummary {
194
+ files: number;
195
+ updated: number;
196
+ removed: number;
197
+ failed: number;
198
+ stopped: boolean;
199
+ }
200
+
201
+ interface IndexedEntryState {
202
+ sessionId: string;
203
+ cwd: string;
204
+ sessionName: string | undefined;
205
+ lastEntryId: string | undefined;
206
+ lastActivity: number;
207
+ }
208
+
209
+ export class SessionIndex {
210
+ private readonly db: DatabaseSync;
211
+ private readonly statements = new Map<string, StatementSync>();
212
+ private readonly searchDatabase: SearchDatabase = {
213
+ statement: (sql) => this.statement(sql),
214
+ activeBranches: new Map(),
215
+ };
216
+
217
+ constructor(databasePath: string) {
218
+ mkdirSync(dirname(databasePath), { recursive: true });
219
+ this.db = new DatabaseSync(databasePath);
220
+ this.db.exec("PRAGMA busy_timeout = 15000");
221
+ this.db.exec("PRAGMA journal_mode = WAL");
222
+ this.db.exec("PRAGMA synchronous = NORMAL");
223
+ this.ensureSchema();
224
+ }
225
+
226
+ close(): void {
227
+ this.statements.clear();
228
+ this.db.close();
229
+ }
230
+
231
+ private ensureSchema(): void {
232
+ this.inWriteTransaction(() => {
233
+ const hasMeta = this.db
234
+ .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'index_meta'")
235
+ .get();
236
+ if (hasMeta !== undefined) {
237
+ const row = this.db
238
+ .prepare("SELECT value FROM index_meta WHERE key = 'schema_version'")
239
+ .get();
240
+ if (row !== undefined && text(row.value) === INDEX_FORMAT) {
241
+ return;
242
+ }
243
+ this.db.exec(DROP_SQL);
244
+ }
245
+ this.db.exec(SCHEMA_SQL);
246
+ this.db
247
+ .prepare("INSERT OR REPLACE INTO index_meta (key, value) VALUES ('schema_version', ?)")
248
+ .run(INDEX_FORMAT);
249
+ });
250
+ }
251
+
252
+ private statement(sql: string): StatementSync {
253
+ let prepared = this.statements.get(sql);
254
+ if (prepared === undefined) {
255
+ prepared = this.db.prepare(sql);
256
+ this.statements.set(sql, prepared);
257
+ }
258
+ return prepared;
259
+ }
260
+
261
+ /** Runs `work` holding SQLite's write lock, so no other process writes meanwhile. */
262
+ private inWriteTransaction<T>(work: () => T): T {
263
+ this.db.exec("BEGIN IMMEDIATE");
264
+ try {
265
+ const result = work();
266
+ this.db.exec("COMMIT");
267
+ return result;
268
+ } catch (error) {
269
+ if (this.db.isTransaction) {
270
+ this.db.exec("ROLLBACK");
271
+ }
272
+ throw error;
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Runs `work` in a read transaction. In WAL mode every read inside sees one
278
+ * snapshot, even while other processes commit, and does not block them.
279
+ */
280
+ private inReadTransaction<T>(work: () => T): T {
281
+ this.db.exec("BEGIN");
282
+ try {
283
+ return work();
284
+ } finally {
285
+ if (this.db.isTransaction) {
286
+ this.db.exec("COMMIT");
287
+ }
288
+ }
289
+ }
290
+
291
+ // ---------------------------------------------------------------------------
292
+ // Indexing
293
+
294
+ /** Brings the index up to date with the session files below `roots`. */
295
+ sync(roots: readonly string[], options: SyncOptions = {}): SyncSummary {
296
+ const summary: SyncSummary = {
297
+ files: 0,
298
+ updated: 0,
299
+ removed: 0,
300
+ failed: 0,
301
+ stopped: false,
302
+ };
303
+ summary.removed = this.removeDeletedFiles();
304
+
305
+ const files = listSessionFiles(roots);
306
+ summary.files = files.length;
307
+ let done = 0;
308
+ for (const path of files) {
309
+ if (options.shouldStop?.() === true) {
310
+ summary.stopped = true;
311
+ break;
312
+ }
313
+ let result: FileSyncResult;
314
+ try {
315
+ result = this.syncFile(path, options.shouldStop);
316
+ } catch {
317
+ summary.failed += 1;
318
+ result = "unchanged";
319
+ }
320
+ if (result === "updated") {
321
+ summary.updated += 1;
322
+ } else if (result === "stopped") {
323
+ summary.stopped = true;
324
+ }
325
+ done += 1;
326
+ options.onProgress?.({ done, total: files.length, changed: result === "updated" });
327
+ if (summary.stopped) {
328
+ break;
329
+ }
330
+ }
331
+ return summary;
332
+ }
333
+
334
+ /** Drops index data for files that no longer exist. Returns how many were dropped. */
335
+ removeDeletedFiles(): number {
336
+ const rows = this.statement("SELECT file_id, path FROM session_files").all();
337
+ let removed = 0;
338
+ for (const row of rows) {
339
+ if (!existsSync(text(row.path))) {
340
+ this.inWriteTransaction(() => this.deleteFile(integer(row.file_id)));
341
+ removed += 1;
342
+ }
343
+ }
344
+ return removed;
345
+ }
346
+
347
+ private deleteFile(fileId: number): void {
348
+ this.clearFileContent(fileId);
349
+ this.statement("DELETE FROM session_files WHERE file_id = ?").run(fileId);
350
+ }
351
+
352
+ private clearFileContent(fileId: number): void {
353
+ this.statement(
354
+ "DELETE FROM items_text WHERE rowid IN (SELECT item_id FROM items WHERE file_id = ?)",
355
+ ).run(fileId);
356
+ this.statement("DELETE FROM items WHERE file_id = ?").run(fileId);
357
+ this.statement("DELETE FROM entry_parents WHERE file_id = ?").run(fileId);
358
+ }
359
+
360
+ /**
361
+ * Indexes whatever was appended to one file since the last run, or the whole
362
+ * file again when it was replaced or rewritten.
363
+ *
364
+ * Every sync calls this for every session file, so an unchanged file must
365
+ * cost one stat and one row lookup, never a read. Unchanged means the same
366
+ * file, fully indexed, with the modification time the index last saw. A
367
+ * rewrite that keeps both the size and the modification time is not noticed.
368
+ */
369
+ syncFile(path: string, shouldStop?: () => boolean): FileSyncResult {
370
+ let stats: BigIntStats;
371
+ try {
372
+ stats = statSync(path, { bigint: true });
373
+ } catch {
374
+ return "missing";
375
+ }
376
+ const row = this.statement(
377
+ "SELECT identity, modified_ns, indexed_bytes FROM session_files WHERE path = ?",
378
+ ).get(path);
379
+ if (
380
+ row !== undefined &&
381
+ text(row.identity) === fileIdentity(stats) &&
382
+ text(row.modified_ns) === modificationTime(stats) &&
383
+ integer(row.indexed_bytes) === Number(stats.size)
384
+ ) {
385
+ return "unchanged";
386
+ }
387
+ let changed = false;
388
+ for (;;) {
389
+ const step = this.indexNextChunk(path);
390
+ changed = changed || step.changed;
391
+ if (!step.more) {
392
+ break;
393
+ }
394
+ if (shouldStop?.() === true) {
395
+ return "stopped";
396
+ }
397
+ }
398
+ return changed ? "updated" : "unchanged";
399
+ }
400
+
401
+ /**
402
+ * Indexes up to BYTES_PER_TRANSACTION of new lines in one write transaction.
403
+ * The stored offset is read inside the transaction, so a line can never be
404
+ * indexed twice even if another process indexed the same file meanwhile.
405
+ *
406
+ * Starts again from the first byte, with a new epoch, unless
407
+ * indexedBytesIntact() says the indexed bytes are unchanged. Only a file that
408
+ * grew and still has the checkpoint bytes is treated as an append.
409
+ */
410
+ private indexNextChunk(path: string): { changed: boolean; more: boolean } {
411
+ let fd: number;
412
+ try {
413
+ fd = openSync(path, "r");
414
+ } catch {
415
+ return { changed: false, more: false };
416
+ }
417
+ try {
418
+ return this.inWriteTransaction(() => {
419
+ // Stat before reading. A write that lands during the read then leaves a stored
420
+ // size and time older than the file's, and the next sync looks at the file again.
421
+ const stats = fstatSync(fd, { bigint: true });
422
+ const size = Number(stats.size);
423
+ // A new row has an empty epoch, so the code below indexes it from the start.
424
+ this.statement("INSERT OR IGNORE INTO session_files (path) VALUES (?)").run(path);
425
+ const row = this.statement("SELECT * FROM session_files WHERE path = ?").get(path);
426
+ if (row === undefined) {
427
+ return { changed: false, more: false };
428
+ }
429
+ const fileId = integer(row.file_id);
430
+ const record: IndexedFileRecord = {
431
+ identity: text(row.identity),
432
+ fileSize: integer(row.file_size),
433
+ modifiedNs: text(row.modified_ns),
434
+ indexedBytes: integer(row.indexed_bytes),
435
+ checkpoint: text(row.checkpoint),
436
+ };
437
+ let offset = record.indexedBytes;
438
+ let epoch = text(row.epoch);
439
+ const state: IndexedEntryState = {
440
+ sessionId: text(row.session_id),
441
+ cwd: text(row.cwd),
442
+ sessionName: optionalText(row.session_name),
443
+ lastEntryId: optionalText(row.last_entry_id),
444
+ lastActivity: integer(row.last_activity),
445
+ };
446
+
447
+ let changed = false;
448
+ if (epoch === "" || !indexedBytesIntact(record, stats, fd, false)) {
449
+ this.clearFileContent(fileId);
450
+ offset = 0;
451
+ epoch = randomUUID();
452
+ state.sessionId = "";
453
+ state.cwd = "";
454
+ state.sessionName = undefined;
455
+ state.lastEntryId = undefined;
456
+ state.lastActivity = 0;
457
+ changed = true;
458
+ }
459
+
460
+ const batch = readCompleteLines(fd, offset, BYTES_PER_TRANSACTION);
461
+ for (const line of batch.lines) {
462
+ if (this.indexLine(fileId, line.offset, line.length, line.text, state)) {
463
+ changed = true;
464
+ }
465
+ }
466
+
467
+ this.statement(
468
+ `UPDATE session_files SET identity = ?, file_size = ?, modified_ns = ?, epoch = ?, indexed_bytes = ?,
469
+ checkpoint = ?, session_id = ?, cwd = ?, session_name = ?, last_entry_id = ?, last_activity = ?
470
+ WHERE file_id = ?`,
471
+ ).run(
472
+ fileIdentity(stats),
473
+ size,
474
+ modificationTime(stats),
475
+ epoch,
476
+ batch.nextOffset,
477
+ checkpointDigest(fd, batch.nextOffset),
478
+ state.sessionId,
479
+ state.cwd,
480
+ state.sessionName ?? null,
481
+ state.lastEntryId ?? null,
482
+ state.lastActivity,
483
+ fileId,
484
+ );
485
+ const more = batch.lines.length > 0 && batch.nextOffset < size;
486
+ return { changed: changed || batch.lines.length > 0, more };
487
+ });
488
+ } finally {
489
+ closeSync(fd);
490
+ }
491
+ }
492
+
493
+ /** Records one JSONL line. Returns true when it added searchable items. */
494
+ private indexLine(
495
+ fileId: number,
496
+ offset: number,
497
+ length: number,
498
+ lineText: string,
499
+ state: IndexedEntryState,
500
+ ): boolean {
501
+ let entry: unknown;
502
+ try {
503
+ entry = JSON.parse(lineText);
504
+ } catch {
505
+ return false;
506
+ }
507
+ if (typeof entry !== "object" || entry === null) {
508
+ return false;
509
+ }
510
+ const record = entry as Record<string, unknown>;
511
+ if (record.type === "session") {
512
+ state.sessionId = typeof record.id === "string" ? record.id : state.sessionId;
513
+ state.cwd = typeof record.cwd === "string" ? record.cwd : state.cwd;
514
+ return false;
515
+ }
516
+ if (typeof record.id !== "string") {
517
+ return false;
518
+ }
519
+ state.lastEntryId = record.id;
520
+ const parentId = typeof record.parentId === "string" ? record.parentId : null;
521
+ this.statement(
522
+ "INSERT OR REPLACE INTO entry_parents (file_id, entry_id, parent_id) VALUES (?, ?, ?)",
523
+ ).run(fileId, record.id, parentId);
524
+ if (record.type === "session_info") {
525
+ state.sessionName =
526
+ typeof record.name === "string" && record.name.trim() !== "" ? record.name : undefined;
527
+ return false;
528
+ }
529
+
530
+ const items = extractSearchableItems(entry);
531
+ for (const item of items) {
532
+ const toolKeys = toolNameKeys(item.toolName);
533
+ const inserted = this.statement(
534
+ `INSERT INTO items (file_id, entry_id, part, kind, tool_name, tool_name_key, tool_name_tail,
535
+ line_offset, line_length, created_at)
536
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
537
+ ).run(
538
+ fileId,
539
+ item.entryId,
540
+ item.part,
541
+ item.kind,
542
+ item.toolName ?? null,
543
+ toolKeys.key,
544
+ toolKeys.tail,
545
+ offset,
546
+ length,
547
+ item.timestamp,
548
+ );
549
+ this.statement("INSERT INTO items_text (rowid, body) VALUES (?, ?)").run(
550
+ inserted.lastInsertRowid,
551
+ foldForIndex(item.text),
552
+ );
553
+ state.lastActivity = Math.max(state.lastActivity, item.timestamp);
554
+ }
555
+ return items.length > 0;
556
+ }
557
+
558
+ // ---------------------------------------------------------------------------
559
+ // Searching
560
+
561
+ /** Searches one consistent snapshot of the index. See searchIndex(). */
562
+ search(request: IndexSearchRequest): IndexSearchResult {
563
+ return this.inReadTransaction(() => searchIndex(this.searchDatabase, request));
564
+ }
565
+
566
+ /** The full text of one indexed item, if its file still holds it. See readIndexedItemText(). */
567
+ readItem(request: IndexedItemRequest): string | undefined {
568
+ return this.inReadTransaction(() => readIndexedItemText(this.searchDatabase, request));
569
+ }
570
+
571
+ /** Counts for diagnostics and tests. */
572
+ stats(): { files: number; items: number } {
573
+ const files = integer(this.statement("SELECT count(*) AS n FROM session_files").get()?.n);
574
+ const items = integer(this.statement("SELECT count(*) AS n FROM items").get()?.n);
575
+ return { files, items };
576
+ }
577
+ }