@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,578 @@
1
+ /**
2
+ * Searching the /find-all index: candidate retrieval through the FTS5 trigram
3
+ * table, verification against the session files, and hit building.
4
+ *
5
+ * The index never stores message text, so each candidate's line is read back
6
+ * from disk at its stored byte range. A file is read only while it still holds
7
+ * the bytes the index covers (see indexedBytesIntact()), and each line must
8
+ * still hold the indexed item, so a search never shows text that is no longer
9
+ * in the file.
10
+ *
11
+ * Loaded by the index worker, which strips types itself: type annotations only, and no Pi packages.
12
+ */
13
+
14
+ import { closeSync, fstatSync, openSync, type BigIntStats } from "node:fs";
15
+ import type { SQLOutputValue, StatementSync } from "node:sqlite";
16
+
17
+ import { type SearchHit, windowAroundMatch } from "./hits.ts";
18
+ import { checkpointDigest, readLineAt } from "./jsonl-reader.ts";
19
+ import {
20
+ cwdMatches,
21
+ foldForIndex,
22
+ kindAllowed,
23
+ matchesItem,
24
+ parseQuery,
25
+ resolveTimeRange,
26
+ type RoleFilter,
27
+ sessionNameMatches,
28
+ termPatterns,
29
+ type TimeRange,
30
+ } from "./query.ts";
31
+ import { extractSearchableItems, type ItemKind, type SearchableItem } from "./searchable-text.ts";
32
+
33
+ /** Upper bound of candidate rows one search looks at. */
34
+ const MAX_CANDIDATES = 20_000;
35
+
36
+ /** Upper bound of candidate lines read back from disk for one search. */
37
+ const MAX_VERIFIED_LINES = 4_000;
38
+
39
+ /**
40
+ * Upper bound of trigrams looked up for one term. A longer term uses evenly
41
+ * spread trigrams. Fewer trigrams only loosen the candidates, never lose one.
42
+ */
43
+ const MAX_TRIGRAMS_PER_TERM = 24;
44
+
45
+ /** Active branches kept between searches before the cache is cleared. */
46
+ const ACTIVE_BRANCH_CACHE_ENTRIES = 500;
47
+
48
+ const ALL_KINDS: readonly ItemKind[] = ["user", "assistant", "toolCall", "toolResult", "shell"];
49
+
50
+ export function text(value: SQLOutputValue | undefined): string {
51
+ return typeof value === "string" ? value : "";
52
+ }
53
+
54
+ export function optionalText(value: SQLOutputValue | undefined): string | undefined {
55
+ return typeof value === "string" ? value : undefined;
56
+ }
57
+
58
+ export function integer(value: SQLOutputValue | undefined): number {
59
+ if (typeof value === "number") {
60
+ return value;
61
+ }
62
+ if (typeof value === "bigint") {
63
+ return Number(value);
64
+ }
65
+ return 0;
66
+ }
67
+
68
+ export function fileIdentity(stats: BigIntStats): string {
69
+ return `${stats.dev}:${stats.ino}`;
70
+ }
71
+
72
+ /**
73
+ * The modification time as `session_files.modified_ns` keeps it: whole
74
+ * nanoseconds, as text because they do not fit a JavaScript number. It is only
75
+ * compared for equality, to tell whether the file was written to since.
76
+ */
77
+ export function modificationTime(stats: BigIntStats): string {
78
+ return stats.mtimeNs.toString();
79
+ }
80
+
81
+ /** What the index recorded about a file's bytes when it last indexed it. */
82
+ export interface IndexedFileRecord {
83
+ identity: string;
84
+ fileSize: number;
85
+ modifiedNs: string;
86
+ indexedBytes: number;
87
+ checkpoint: string;
88
+ }
89
+
90
+ /**
91
+ * True when the bytes the index covers are still the same in the open file,
92
+ * so indexed offsets are valid and only appended bytes may be new.
93
+ *
94
+ * False when the file was replaced, shrank below the indexed offset, was
95
+ * written to without growing, or no longer has the checkpoint bytes before the
96
+ * indexed offset. With `trustUnchangedStat`, a file whose size and
97
+ * modification time are both unchanged counts as intact without reading it.
98
+ */
99
+ export function indexedBytesIntact(
100
+ record: IndexedFileRecord,
101
+ stats: BigIntStats,
102
+ fd: number,
103
+ trustUnchangedStat: boolean,
104
+ ): boolean {
105
+ if (record.identity !== fileIdentity(stats)) {
106
+ return false;
107
+ }
108
+ const size = Number(stats.size);
109
+ if (size < record.indexedBytes) {
110
+ return false;
111
+ }
112
+ if (record.indexedBytes === 0) {
113
+ return true;
114
+ }
115
+ const modified = modificationTime(stats);
116
+ if (trustUnchangedStat && size === record.fileSize && modified === record.modifiedNs) {
117
+ return true;
118
+ }
119
+ // An append makes a file longer. A file that was written to but did not grow had
120
+ // existing bytes changed. They can be anywhere, so the checkpoint cannot clear it.
121
+ if (size <= record.fileSize && modified !== record.modifiedNs) {
122
+ return false;
123
+ }
124
+ return checkpointDigest(fd, record.indexedBytes) === record.checkpoint;
125
+ }
126
+
127
+ /** Picks `count` indexes spread evenly over 0..total-1, always including both ends. */
128
+ function spreadIndexes(total: number, count: number): number[] {
129
+ if (total <= count) {
130
+ return Array.from({ length: total }, (_, index) => index);
131
+ }
132
+ const picked = new Set<number>();
133
+ for (let step = 0; step < count; step += 1) {
134
+ picked.add(Math.round((step * (total - 1)) / (count - 1)));
135
+ }
136
+ return [...picked];
137
+ }
138
+
139
+ /**
140
+ * Turns query terms into an FTS5 expression that finds candidates: every
141
+ * trigram of every folded term, joined with AND. A term that matches an item
142
+ * has all its trigrams in the item, so no match is lost. Phrases, punctuation,
143
+ * and mid-word terms need no special case because trigrams cover every
144
+ * character. Terms shorter than three characters after folding are left to
145
+ * the exact check. Returns undefined when no term has a trigram.
146
+ */
147
+ export function buildMatchExpression(terms: readonly string[]): string | undefined {
148
+ const trigrams = new Set<string>();
149
+ for (const term of terms) {
150
+ const characters = Array.from(foldForIndex(term));
151
+ const windows = characters.length - 2;
152
+ if (windows <= 0) {
153
+ continue;
154
+ }
155
+ for (const start of spreadIndexes(windows, MAX_TRIGRAMS_PER_TERM)) {
156
+ trigrams.add(characters.slice(start, start + 3).join(""));
157
+ }
158
+ }
159
+ if (trigrams.size === 0) {
160
+ return undefined;
161
+ }
162
+ return [...trigrams].map((trigram) => `"${trigram.replaceAll('"', '""')}"`).join(" AND ");
163
+ }
164
+
165
+ export interface IndexSearchRequest {
166
+ queryText: string;
167
+ roleFilter: RoleFilter;
168
+ limit: number;
169
+ /**
170
+ * Milliseconds since the epoch that relative since: and until: values count
171
+ * back from. The main thread sends it, so the worker never reads the clock.
172
+ */
173
+ now: number;
174
+ /**
175
+ * Most hits kept per session file. Once a file has this many, its later
176
+ * candidates are skipped without reading their lines. Undefined for no cap.
177
+ */
178
+ perSessionLimit?: number;
179
+ /** Checked before each candidate. Return true to abandon the search. */
180
+ shouldStop?: () => boolean;
181
+ }
182
+
183
+ export interface IndexSearchResult {
184
+ hits: SearchHit[];
185
+ /**
186
+ * True when more matches may exist than were returned or verified: the
187
+ * limit was reached, or the search stopped at its bound of candidates or
188
+ * lines read, which short terms without trigrams reach most often.
189
+ */
190
+ truncated: boolean;
191
+ /**
192
+ * Session files that reached perSessionLimit and still had candidates left,
193
+ * which the search skipped. Their matches may go past the hits returned.
194
+ * Independent of `truncated`, which only means the search stopped early.
195
+ */
196
+ sessionsWithMore: string[];
197
+ /** True when shouldStop ended the search early. */
198
+ stopped: boolean;
199
+ }
200
+
201
+ /** What a search needs from the open index. */
202
+ export interface SearchDatabase {
203
+ /** A prepared statement for `sql`, reused between calls. */
204
+ statement(sql: string): StatementSync;
205
+ /** Active branches by file, epoch, and indexed length. Kept between searches. */
206
+ activeBranches: Map<string, Set<string>>;
207
+ }
208
+
209
+ interface FileInfo extends IndexedFileRecord {
210
+ path: string;
211
+ /** Random id given each time the file is indexed from the start. Never reused. */
212
+ epoch: string;
213
+ sessionId: string;
214
+ cwd: string;
215
+ sessionName: string | undefined;
216
+ lastEntryId: string | undefined;
217
+ }
218
+
219
+ interface Candidate {
220
+ fileId: number;
221
+ entryId: string;
222
+ part: number;
223
+ lineOffset: number;
224
+ lineLength: number;
225
+ }
226
+
227
+ /**
228
+ * Finds candidates with the trigram index, newest first, then verifies each
229
+ * against the real session text with the same rules as /find. Call it inside
230
+ * a read transaction so the whole search sees one snapshot.
231
+ *
232
+ * With perSessionLimit, a long session cannot fill the whole limit: once a
233
+ * file has that many hits, its later candidates are skipped before their
234
+ * lines are read. Skipped candidates still count toward the bound of
235
+ * candidates, but not toward the bound of lines read.
236
+ */
237
+ export function searchIndex(
238
+ database: SearchDatabase,
239
+ request: IndexSearchRequest,
240
+ ): IndexSearchResult {
241
+ const query = parseQuery(request.queryText);
242
+ const kinds = ALL_KINDS.filter((kind) => kindAllowed(kind, query, request.roleFilter));
243
+ if (kinds.length === 0) {
244
+ return { hits: [], truncated: false, sessionsWithMore: [], stopped: false };
245
+ }
246
+ const patterns = termPatterns(query);
247
+ const files = loadFiles(database);
248
+ let fileIds: number[] | undefined;
249
+ // cwd: and name: are checked against session metadata, before any line is read.
250
+ if (query.cwd !== undefined || query.name !== undefined) {
251
+ const wantedCwd = query.cwd;
252
+ const wantedName = query.name;
253
+ fileIds = [...files.entries()]
254
+ .filter(
255
+ ([, file]) =>
256
+ (wantedCwd === undefined || cwdMatches(file.cwd, wantedCwd)) &&
257
+ (wantedName === undefined || sessionNameMatches(file.sessionName, wantedName)),
258
+ )
259
+ .map(([fileId]) => fileId);
260
+ if (fileIds.length === 0) {
261
+ return { hits: [], truncated: false, sessionsWithMore: [], stopped: false };
262
+ }
263
+ }
264
+
265
+ const candidates = candidateRows(database, {
266
+ matchExpression: buildMatchExpression(query.terms),
267
+ kinds,
268
+ toolName: query.toolName,
269
+ fileIds,
270
+ timeRange: resolveTimeRange(query, request.now),
271
+ });
272
+ // Each file is opened once per search. Undefined marks a file that cannot be
273
+ // opened or no longer holds the indexed bytes; its candidates are skipped.
274
+ const openFiles = new Map<number, number | undefined>();
275
+ const hits: SearchHit[] = [];
276
+ const perSessionLimit = request.perSessionLimit ?? Number.POSITIVE_INFINITY;
277
+ const hitsPerFile = new Map<number, number>();
278
+ const filesWithMore = new Set<number>();
279
+ let examined = 0;
280
+ let verifiedLines = 0;
281
+ let truncated = false;
282
+ let stopped = false;
283
+
284
+ try {
285
+ for (;;) {
286
+ if (request.shouldStop?.() === true) {
287
+ stopped = true;
288
+ break;
289
+ }
290
+ const next = candidates.next();
291
+ if (next.done === true) {
292
+ break;
293
+ }
294
+ if (
295
+ hits.length >= request.limit ||
296
+ verifiedLines >= MAX_VERIFIED_LINES ||
297
+ examined >= MAX_CANDIDATES
298
+ ) {
299
+ truncated = true;
300
+ break;
301
+ }
302
+ examined += 1;
303
+ const candidate = toCandidate(next.value);
304
+ const file = files.get(candidate.fileId);
305
+ if (file === undefined) {
306
+ continue;
307
+ }
308
+ // A file at its cap is not read again; its later candidates only mark that it had more.
309
+ if ((hitsPerFile.get(candidate.fileId) ?? 0) >= perSessionLimit) {
310
+ filesWithMore.add(candidate.fileId);
311
+ continue;
312
+ }
313
+ if (!openFiles.has(candidate.fileId)) {
314
+ openFiles.set(candidate.fileId, openIntactFile(file));
315
+ }
316
+ const fd = openFiles.get(candidate.fileId);
317
+ if (fd === undefined) {
318
+ continue;
319
+ }
320
+ verifiedLines += 1;
321
+ const item = readItemsAt(fd, candidate)?.find(
322
+ (each) => each.part === candidate.part && each.entryId === candidate.entryId,
323
+ );
324
+ if (item === undefined || !matchesItem(item, query, request.roleFilter, patterns)) {
325
+ continue;
326
+ }
327
+ hits.push(toHit(database, candidate.fileId, file, item, patterns));
328
+ hitsPerFile.set(candidate.fileId, (hitsPerFile.get(candidate.fileId) ?? 0) + 1);
329
+ }
330
+ } finally {
331
+ candidates.return?.();
332
+ for (const fd of openFiles.values()) {
333
+ if (fd !== undefined) {
334
+ closeSync(fd);
335
+ }
336
+ }
337
+ }
338
+ const sessionsWithMore = [...filesWithMore].flatMap((fileId) => {
339
+ const file = files.get(fileId);
340
+ return file === undefined ? [] : [file.path];
341
+ });
342
+ return { hits, truncated, sessionsWithMore, stopped };
343
+ }
344
+
345
+ /** Opens a session file if it still holds the bytes the snapshot indexed. */
346
+ function openIntactFile(file: FileInfo): number | undefined {
347
+ let fd: number;
348
+ try {
349
+ fd = openSync(file.path, "r");
350
+ } catch {
351
+ return undefined;
352
+ }
353
+ let intact = false;
354
+ try {
355
+ intact = indexedBytesIntact(file, fstatSync(fd, { bigint: true }), fd, true);
356
+ } catch {
357
+ intact = false;
358
+ }
359
+ if (!intact) {
360
+ closeSync(fd);
361
+ return undefined;
362
+ }
363
+ return fd;
364
+ }
365
+
366
+ const FILE_COLUMNS = `file_id, path, identity, file_size, modified_ns, epoch, indexed_bytes,
367
+ checkpoint, session_id, cwd, session_name, last_entry_id`;
368
+
369
+ function toFileInfo(row: Record<string, SQLOutputValue>): FileInfo {
370
+ return {
371
+ path: text(row.path),
372
+ identity: text(row.identity),
373
+ fileSize: integer(row.file_size),
374
+ modifiedNs: text(row.modified_ns),
375
+ epoch: text(row.epoch),
376
+ indexedBytes: integer(row.indexed_bytes),
377
+ checkpoint: text(row.checkpoint),
378
+ sessionId: text(row.session_id),
379
+ cwd: text(row.cwd),
380
+ sessionName: optionalText(row.session_name),
381
+ lastEntryId: optionalText(row.last_entry_id),
382
+ };
383
+ }
384
+
385
+ function loadFiles(database: SearchDatabase): Map<number, FileInfo> {
386
+ const files = new Map<number, FileInfo>();
387
+ const rows = database.statement(`SELECT ${FILE_COLUMNS} FROM session_files`).all();
388
+ for (const row of rows) {
389
+ files.set(integer(row.file_id), toFileInfo(row));
390
+ }
391
+ return files;
392
+ }
393
+
394
+ /** Which indexed item to read back in full. */
395
+ export interface IndexedItemRequest {
396
+ sessionFile: string;
397
+ entryId: string;
398
+ part: number;
399
+ }
400
+
401
+ /**
402
+ * The full text of one indexed item, read back from its session file at the
403
+ * stored offset. Undefined when the index does not know the item, or the file
404
+ * no longer holds the indexed bytes or the item, so the text is never stale.
405
+ * Call it inside a read transaction.
406
+ */
407
+ export function readIndexedItemText(
408
+ database: SearchDatabase,
409
+ request: IndexedItemRequest,
410
+ ): string | undefined {
411
+ const fileRow = database
412
+ .statement(`SELECT ${FILE_COLUMNS} FROM session_files WHERE path = ?`)
413
+ .get(request.sessionFile);
414
+ if (fileRow === undefined) {
415
+ return undefined;
416
+ }
417
+ const fileId = integer(fileRow.file_id);
418
+ const itemRow = database
419
+ .statement(
420
+ `SELECT file_id, entry_id, part, line_offset, line_length FROM items
421
+ WHERE file_id = ? AND entry_id = ? AND part = ?`,
422
+ )
423
+ .get(fileId, request.entryId, request.part);
424
+ if (itemRow === undefined) {
425
+ return undefined;
426
+ }
427
+ const fd = openIntactFile(toFileInfo(fileRow));
428
+ if (fd === undefined) {
429
+ return undefined;
430
+ }
431
+ try {
432
+ const candidate = toCandidate(itemRow);
433
+ return readItemsAt(fd, candidate)?.find(
434
+ (each) => each.part === candidate.part && each.entryId === candidate.entryId,
435
+ )?.text;
436
+ } finally {
437
+ closeSync(fd);
438
+ }
439
+ }
440
+
441
+ /** The conditions candidateRows() turns into SQL. */
442
+ interface CandidateFilter {
443
+ /** FTS5 expression from buildMatchExpression(). Undefined matches every item. */
444
+ matchExpression: string | undefined;
445
+ kinds: readonly ItemKind[];
446
+ toolName: string | undefined;
447
+ /** Files allowed by cwd: and name:. Undefined allows every file. */
448
+ fileIds: number[] | undefined;
449
+ timeRange: TimeRange;
450
+ }
451
+
452
+ /**
453
+ * Streams candidate rows, newest first, so a search that fills its limit
454
+ * early never reads the rest. Kind, tool, file, and time filters run in SQL.
455
+ */
456
+ function candidateRows(
457
+ database: SearchDatabase,
458
+ filter: CandidateFilter,
459
+ ): Iterator<Record<string, SQLOutputValue>> {
460
+ const { matchExpression, kinds, toolName, fileIds, timeRange } = filter;
461
+ const conditions = [`kind IN (${kinds.map(() => "?").join(", ")})`];
462
+ const parameters: Array<string | number> = [...kinds];
463
+ if (toolName !== undefined) {
464
+ // Same rule as toolNameMatches(): the whole name, or the part after the last "__".
465
+ const wanted = toolName.toLowerCase();
466
+ conditions.push("(tool_name_key = ? OR tool_name_tail = ?)");
467
+ parameters.push(wanted, wanted);
468
+ }
469
+ if (matchExpression !== undefined) {
470
+ conditions.push("item_id IN (SELECT rowid FROM items_text WHERE items_text MATCH ?)");
471
+ parameters.push(matchExpression);
472
+ }
473
+ if (fileIds !== undefined) {
474
+ // json_each() keeps the statement within SQLite's limit on bound parameters.
475
+ conditions.push("file_id IN (SELECT value FROM json_each(?))");
476
+ parameters.push(JSON.stringify(fileIds));
477
+ }
478
+ // created_at holds the same timestamp as SearchableItem, so this matches inTimeRange().
479
+ if (timeRange.since !== undefined) {
480
+ conditions.push("created_at >= ?");
481
+ parameters.push(timeRange.since);
482
+ }
483
+ if (timeRange.until !== undefined) {
484
+ conditions.push("created_at < ?");
485
+ parameters.push(timeRange.until);
486
+ }
487
+ const sql = `SELECT file_id, entry_id, part, line_offset, line_length FROM items
488
+ WHERE ${conditions.join(" AND ")}
489
+ ORDER BY created_at DESC, item_id DESC`;
490
+ return database.statement(sql).iterate(...parameters);
491
+ }
492
+
493
+ function toCandidate(row: Record<string, SQLOutputValue>): Candidate {
494
+ return {
495
+ fileId: integer(row.file_id),
496
+ entryId: text(row.entry_id),
497
+ part: integer(row.part),
498
+ lineOffset: integer(row.line_offset),
499
+ lineLength: integer(row.line_length),
500
+ };
501
+ }
502
+
503
+ /**
504
+ * Reads a candidate's line back and extracts its items. Undefined when the
505
+ * line cannot be read or parsed, as when the file is mid-write.
506
+ */
507
+ function readItemsAt(fd: number, candidate: Candidate): SearchableItem[] | undefined {
508
+ try {
509
+ return extractSearchableItems(
510
+ JSON.parse(readLineAt(fd, candidate.lineOffset, candidate.lineLength)),
511
+ );
512
+ } catch {
513
+ return undefined;
514
+ }
515
+ }
516
+
517
+ /**
518
+ * Entry ids on the branch pi opens for a file: the path from the last entry
519
+ * in the file up to the root, because pi sets the leaf to the last entry.
520
+ */
521
+ function activeBranch(database: SearchDatabase, fileId: number, file: FileInfo): Set<string> {
522
+ // Within one epoch a file only grows, so the indexed length identifies its entries.
523
+ const key = `${fileId}:${file.epoch}:${file.indexedBytes}`;
524
+ const cached = database.activeBranches.get(key);
525
+ if (cached !== undefined) {
526
+ return cached;
527
+ }
528
+ const parents = new Map<string, string | null>();
529
+ const rows = database
530
+ .statement("SELECT entry_id, parent_id FROM entry_parents WHERE file_id = ?")
531
+ .all(fileId);
532
+ for (const row of rows) {
533
+ parents.set(text(row.entry_id), optionalText(row.parent_id) ?? null);
534
+ }
535
+ const branch = new Set<string>();
536
+ let cursor = file.lastEntryId;
537
+ while (cursor !== undefined && !branch.has(cursor)) {
538
+ branch.add(cursor);
539
+ const parent = parents.get(cursor);
540
+ cursor = parent ?? undefined;
541
+ }
542
+ if (database.activeBranches.size > ACTIVE_BRANCH_CACHE_ENTRIES) {
543
+ database.activeBranches.clear();
544
+ }
545
+ database.activeBranches.set(key, branch);
546
+ return branch;
547
+ }
548
+
549
+ function toHit(
550
+ database: SearchDatabase,
551
+ fileId: number,
552
+ file: FileInfo,
553
+ item: SearchableItem,
554
+ patterns: RegExp[],
555
+ ): SearchHit {
556
+ const window = windowAroundMatch(item.text, patterns);
557
+ const hit: SearchHit = {
558
+ sessionFile: file.path,
559
+ sessionId: file.sessionId,
560
+ cwd: file.cwd,
561
+ entryId: item.entryId,
562
+ part: item.part,
563
+ kind: item.kind,
564
+ timestamp: item.timestamp,
565
+ onActiveBranch: activeBranch(database, fileId, file).has(item.entryId),
566
+ text: window.text,
567
+ clippedStart: window.clippedStart,
568
+ clippedEnd: window.clippedEnd,
569
+ fuzzy: false,
570
+ };
571
+ if (file.sessionName !== undefined) {
572
+ hit.sessionName = file.sessionName;
573
+ }
574
+ if (item.toolName !== undefined) {
575
+ hit.toolName = item.toolName;
576
+ }
577
+ return hit;
578
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Worker thread for /find-all. Opens the index, indexes session files,
3
+ * answers searches, and reads matches back in full, so SQLite and file reads
4
+ * never run on pi's main thread.
5
+ *
6
+ * The loader in index-client.ts strips the types of this file and its
7
+ * imports, so they hold type annotations only and import no Pi packages.
8
+ */
9
+
10
+ import { parentPort, workerData } from "node:worker_threads";
11
+
12
+ import { SessionIndex } from "./session-index.ts";
13
+ import type { WorkerReply, WorkerRequest, WorkerSetup } from "./worker-protocol.ts";
14
+ import { SEARCH_SLOT, STOP_SLOT } from "./worker-protocol.ts";
15
+
16
+ const port = parentPort;
17
+ const setup = workerData as WorkerSetup;
18
+ const signals = new Int32Array(setup.signals);
19
+ let index: SessionIndex | undefined;
20
+
21
+ function reply(message: WorkerReply): void {
22
+ port?.postMessage(message);
23
+ }
24
+
25
+ function describe(error: unknown): string {
26
+ return error instanceof Error ? error.message : String(error);
27
+ }
28
+
29
+ function openIndex(): SessionIndex {
30
+ if (index === undefined) {
31
+ index = new SessionIndex(setup.databasePath);
32
+ }
33
+ return index;
34
+ }
35
+
36
+ function handle(request: WorkerRequest): void {
37
+ switch (request.type) {
38
+ case "sync": {
39
+ try {
40
+ const summary = openIndex().sync(request.roots, {
41
+ shouldStop: () => Atomics.load(signals, STOP_SLOT) !== 0,
42
+ onProgress: (progress) => reply({ type: "progress", ...progress }),
43
+ });
44
+ reply({ type: "synced", summary });
45
+ } catch (error) {
46
+ reply({ type: "failed", message: describe(error) });
47
+ }
48
+ return;
49
+ }
50
+ case "search": {
51
+ // A newer search was requested while this one waited in the queue.
52
+ if (Atomics.load(signals, SEARCH_SLOT) !== request.requestId) {
53
+ return;
54
+ }
55
+ try {
56
+ const result = openIndex().search({
57
+ queryText: request.queryText,
58
+ roleFilter: request.roleFilter,
59
+ limit: request.limit,
60
+ now: request.now,
61
+ perSessionLimit: request.perSessionLimit,
62
+ shouldStop: () => Atomics.load(signals, SEARCH_SLOT) !== request.requestId,
63
+ });
64
+ if (!result.stopped) {
65
+ reply({
66
+ type: "results",
67
+ requestId: request.requestId,
68
+ hits: result.hits,
69
+ truncated: result.truncated,
70
+ sessionsWithMore: result.sessionsWithMore,
71
+ });
72
+ }
73
+ } catch (error) {
74
+ reply({ type: "failed", requestId: request.requestId, message: describe(error) });
75
+ }
76
+ return;
77
+ }
78
+ case "readItem": {
79
+ try {
80
+ const itemText = openIndex().readItem({
81
+ sessionFile: request.sessionFile,
82
+ entryId: request.entryId,
83
+ part: request.part,
84
+ });
85
+ reply({ type: "item", requestId: request.requestId, text: itemText });
86
+ } catch (error) {
87
+ reply({ type: "failed", requestId: request.requestId, message: describe(error) });
88
+ }
89
+ return;
90
+ }
91
+ case "close": {
92
+ index?.close();
93
+ index = undefined;
94
+ port?.close();
95
+ return;
96
+ }
97
+ }
98
+ }
99
+
100
+ port?.on("message", (request: WorkerRequest) => {
101
+ handle(request);
102
+ });