@oyasmi/pipiclaw 0.9.6-beta.2 → 0.9.6-beta.3

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.
Files changed (78) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +2 -2
  3. package/dist/agent/channel-runner.js +2 -0
  4. package/dist/agent/maintenance-context.js +21 -2
  5. package/dist/agent/turn/turn-context.js +10 -6
  6. package/dist/config/settings.d.ts +0 -2
  7. package/dist/config/settings.js +0 -2
  8. package/dist/config/tools.d.ts +8 -2
  9. package/dist/config/tools.js +35 -19
  10. package/dist/memory/anchors.d.ts +5 -0
  11. package/dist/memory/anchors.js +49 -0
  12. package/dist/memory/boundary-work.d.ts +1 -0
  13. package/dist/memory/boundary-work.js +1 -0
  14. package/dist/memory/commands.js +23 -6
  15. package/dist/memory/index-budget.d.ts +16 -0
  16. package/dist/memory/index-budget.js +24 -2
  17. package/dist/memory/journal.d.ts +7 -12
  18. package/dist/memory/journal.js +9 -41
  19. package/dist/memory/lifecycle.d.ts +1 -0
  20. package/dist/memory/lifecycle.js +2 -0
  21. package/dist/memory/reflect-job.d.ts +1 -0
  22. package/dist/memory/reflect-job.js +1 -0
  23. package/dist/memory/reflect.d.ts +10 -0
  24. package/dist/memory/reflect.js +103 -20
  25. package/dist/memory/render.d.ts +4 -1
  26. package/dist/memory/render.js +6 -4
  27. package/dist/memory/review-log.d.ts +2 -2
  28. package/dist/memory/scheduler.d.ts +7 -0
  29. package/dist/memory/scheduler.js +70 -3
  30. package/dist/memory/search-index-db.d.ts +15 -0
  31. package/dist/memory/search-index-db.js +247 -0
  32. package/dist/memory/search-index-files.d.ts +11 -0
  33. package/dist/memory/search-index-files.js +26 -0
  34. package/dist/memory/search-index-notes.d.ts +11 -0
  35. package/dist/memory/search-index-notes.js +155 -0
  36. package/dist/memory/search-index-sync.d.ts +19 -0
  37. package/dist/memory/search-index-sync.js +267 -0
  38. package/dist/memory/search-terms.d.ts +12 -0
  39. package/dist/memory/search-terms.js +185 -0
  40. package/dist/memory/search.d.ts +8 -28
  41. package/dist/memory/search.js +18 -278
  42. package/dist/memory/session-corpus.d.ts +15 -26
  43. package/dist/memory/session-corpus.js +120 -327
  44. package/dist/memory/session-search.d.ts +5 -3
  45. package/dist/memory/session-search.js +119 -171
  46. package/dist/memory/sidecar-worker.d.ts +2 -0
  47. package/dist/memory/sidecar-worker.js +25 -1
  48. package/dist/memory/store.d.ts +4 -0
  49. package/dist/memory/store.js +22 -1
  50. package/dist/memory/task-archive-digest.d.ts +61 -0
  51. package/dist/memory/task-archive-digest.js +366 -0
  52. package/dist/models/provider-login.d.ts +1 -1
  53. package/dist/models/provider-login.js +1 -1
  54. package/dist/playbooks/memory-operations.md +2 -2
  55. package/dist/shared/text-utils.d.ts +0 -1
  56. package/dist/shared/text-utils.js +0 -1
  57. package/dist/subagents/runs.d.ts +1 -1
  58. package/dist/subagents/task-envelope.js +6 -8
  59. package/dist/tools/memory-manage.d.ts +1 -0
  60. package/dist/tools/memory-manage.js +9 -23
  61. package/dist/tools/registry.js +2 -0
  62. package/dist/tools/session-search.d.ts +1 -0
  63. package/dist/tools/session-search.js +12 -6
  64. package/dist/tools/web-search.d.ts +13 -7
  65. package/dist/tools/web-search.js +62 -19
  66. package/dist/web/client.d.ts +2 -0
  67. package/dist/web/client.js +7 -3
  68. package/dist/web/config.d.ts +17 -4
  69. package/dist/web/config.js +42 -4
  70. package/dist/web/format.d.ts +2 -1
  71. package/dist/web/format.js +7 -3
  72. package/dist/web/search-providers.d.ts +15 -8
  73. package/dist/web/search-providers.js +208 -139
  74. package/dist/web/search.d.ts +13 -3
  75. package/dist/web/search.js +86 -40
  76. package/package.json +1 -1
  77. package/dist/memory/chinese-words.d.ts +0 -1
  78. package/dist/memory/chinese-words.js +0 -273
@@ -0,0 +1,247 @@
1
+ import { chmodSync, mkdirSync, rmSync, statSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { isDeskName } from "../desk/paths.js";
4
+ import * as log from "../log.js";
5
+ import { isNodeError } from "../shared/os.js";
6
+ import { createSerialQueue } from "../shared/serial-queue.js";
7
+ import { errorMessage } from "../shared/text-utils.js";
8
+ import { isRecord } from "../shared/type-guards.js";
9
+ const SCHEMA_VERSION = 2;
10
+ const SCHEMA = `
11
+ CREATE TABLE files (
12
+ path TEXT PRIMARY KEY,
13
+ kind TEXT NOT NULL,
14
+ conversation TEXT,
15
+ ino INTEGER NOT NULL,
16
+ size INTEGER NOT NULL,
17
+ mtime_ms INTEGER NOT NULL,
18
+ indexed_bytes INTEGER NOT NULL,
19
+ indexed_lines INTEGER NOT NULL,
20
+ head_len INTEGER NOT NULL,
21
+ head_hash TEXT NOT NULL
22
+ );
23
+ CREATE TABLE docs (
24
+ id INTEGER PRIMARY KEY,
25
+ hash TEXT NOT NULL UNIQUE,
26
+ role TEXT NOT NULL,
27
+ text TEXT NOT NULL,
28
+ search_text TEXT,
29
+ truncated INTEGER NOT NULL DEFAULT 0
30
+ );
31
+ CREATE TABLE refs (
32
+ path TEXT NOT NULL,
33
+ line INTEGER NOT NULL,
34
+ doc_id INTEGER NOT NULL,
35
+ source TEXT NOT NULL,
36
+ conversation TEXT,
37
+ speaker TEXT,
38
+ ts TEXT,
39
+ ts_ms INTEGER,
40
+ PRIMARY KEY (path, line)
41
+ ) WITHOUT ROWID;
42
+ CREATE INDEX refs_doc ON refs(doc_id);
43
+ CREATE INDEX refs_ts ON refs(ts_ms);
44
+ CREATE VIEW docs_search AS SELECT id AS rid, coalesce(search_text, text) AS text FROM docs;
45
+ CREATE VIRTUAL TABLE docs_fts USING fts5(
46
+ text, content='docs_search', content_rowid='rid', tokenize='unicode61'
47
+ );
48
+ CREATE TRIGGER docs_ai AFTER INSERT ON docs BEGIN
49
+ INSERT INTO docs_fts(rowid, text) VALUES (new.id, coalesce(new.search_text, new.text));
50
+ END;
51
+ CREATE TRIGGER docs_ad AFTER DELETE ON docs BEGIN
52
+ INSERT INTO docs_fts(docs_fts, rowid, text) VALUES ('delete', old.id, coalesce(old.search_text, old.text));
53
+ END;
54
+ CREATE TRIGGER docs_au AFTER UPDATE ON docs BEGIN
55
+ INSERT INTO docs_fts(docs_fts, rowid, text) VALUES ('delete', old.id, coalesce(old.search_text, old.text));
56
+ INSERT INTO docs_fts(rowid, text) VALUES (new.id, coalesce(new.search_text, new.text));
57
+ END;
58
+ CREATE TABLE notes (
59
+ id INTEGER PRIMARY KEY,
60
+ path TEXT NOT NULL,
61
+ kind TEXT NOT NULL,
62
+ label TEXT NOT NULL,
63
+ date TEXT,
64
+ expires TEXT,
65
+ text TEXT NOT NULL,
66
+ search_text TEXT
67
+ );
68
+ CREATE INDEX notes_path ON notes(path);
69
+ CREATE VIEW notes_search AS SELECT id AS rid, coalesce(search_text, text) AS text FROM notes;
70
+ CREATE VIRTUAL TABLE notes_fts USING fts5(
71
+ text, content='notes_search', content_rowid='rid', tokenize='unicode61'
72
+ );
73
+ CREATE TRIGGER notes_ai AFTER INSERT ON notes BEGIN
74
+ INSERT INTO notes_fts(rowid, text) VALUES (new.id, coalesce(new.search_text, new.text));
75
+ END;
76
+ CREATE TRIGGER notes_ad AFTER DELETE ON notes BEGIN
77
+ INSERT INTO notes_fts(notes_fts, rowid, text) VALUES ('delete', old.id, coalesce(old.search_text, old.text));
78
+ END;
79
+ CREATE TRIGGER notes_au AFTER UPDATE ON notes BEGIN
80
+ INSERT INTO notes_fts(notes_fts, rowid, text) VALUES ('delete', old.id, coalesce(old.search_text, old.text));
81
+ INSERT INTO notes_fts(rowid, text) VALUES (new.id, coalesce(new.search_text, new.text));
82
+ END;
83
+ `;
84
+ let sqlitePromise;
85
+ function loadSqlite() {
86
+ sqlitePromise ??= (async () => {
87
+ const original = process.emitWarning;
88
+ process.emitWarning = ((...args) => {
89
+ const [warning, options] = args;
90
+ const type = typeof options === "object" ? options?.type : options;
91
+ if (type === "ExperimentalWarning" && typeof warning === "string" && warning.includes("SQLite"))
92
+ return;
93
+ Reflect.apply(original, process, args);
94
+ });
95
+ try {
96
+ return await import("node:sqlite");
97
+ }
98
+ finally {
99
+ process.emitWarning = original;
100
+ }
101
+ })();
102
+ return sqlitePromise;
103
+ }
104
+ const queue = createSerialQueue();
105
+ const handles = new Map();
106
+ const rebuiltOnce = new Set();
107
+ export function getSearchIndexDir(appHomeDir) {
108
+ return resolve(appHomeDir, "state", "search-index");
109
+ }
110
+ export function getSearchIndexPath(appHomeDir, desk) {
111
+ if (!isDeskName(desk))
112
+ throw new Error(`Invalid desk name: ${desk}`);
113
+ return join(getSearchIndexDir(appHomeDir), `${desk}.sqlite`);
114
+ }
115
+ export class SearchIndexUnavailableError extends Error {
116
+ }
117
+ class IndexVersionMismatch extends Error {
118
+ }
119
+ export function transaction(db, work) {
120
+ db.exec("BEGIN IMMEDIATE");
121
+ try {
122
+ const result = work();
123
+ db.exec("COMMIT");
124
+ return result;
125
+ }
126
+ catch (error) {
127
+ try {
128
+ db.exec("ROLLBACK");
129
+ }
130
+ catch {
131
+ // SQLite can already have rolled back the transaction. Preserve the original error.
132
+ }
133
+ throw error;
134
+ }
135
+ }
136
+ function closeIndex(path) {
137
+ const handle = handles.get(path);
138
+ if (!handle)
139
+ return;
140
+ handles.delete(path);
141
+ handle.db.close();
142
+ }
143
+ export async function closeSearchIndexes() {
144
+ await Promise.all([...handles.keys()].map((path) => queue.run(path, async () => closeIndex(path))));
145
+ }
146
+ function removeIndexFiles(path) {
147
+ closeIndex(path);
148
+ for (const suffix of ["", "-wal", "-shm"])
149
+ rmSync(path + suffix, { force: true });
150
+ }
151
+ export async function removeSearchIndex(path) {
152
+ await queue.run(resolve(path), async () => removeIndexFiles(resolve(path)));
153
+ }
154
+ function statIndex(path) {
155
+ try {
156
+ return statSync(path);
157
+ }
158
+ catch (error) {
159
+ if (!isNodeError(error) || error.code !== "ENOENT")
160
+ throw error;
161
+ return undefined;
162
+ }
163
+ }
164
+ async function ensureOpen(path) {
165
+ const stats = statIndex(path);
166
+ const cached = handles.get(path);
167
+ if (cached && stats?.ino === cached.ino)
168
+ return cached;
169
+ if (cached || !stats)
170
+ removeIndexSidecars(path);
171
+ const { DatabaseSync } = await loadSqlite();
172
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
173
+ const db = new DatabaseSync(path);
174
+ try {
175
+ // Set the mode before SQLite creates the WAL and SHM, which inherit the database mode.
176
+ chmodSync(path, 0o600);
177
+ db.exec("PRAGMA busy_timeout = 5000");
178
+ const version = db.prepare("PRAGMA user_version").get()?.user_version;
179
+ if (version !== SCHEMA_VERSION && (version !== 0 || (stats && stats.size > 0))) {
180
+ throw new IndexVersionMismatch(`schema version ${version}, expected ${SCHEMA_VERSION}`);
181
+ }
182
+ db.exec("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL");
183
+ if (version === 0)
184
+ transaction(db, () => db.exec(`${SCHEMA} PRAGMA user_version = ${SCHEMA_VERSION}`));
185
+ const handle = { db, ino: statSync(path).ino };
186
+ handles.set(path, handle);
187
+ return handle;
188
+ }
189
+ catch (error) {
190
+ db.close();
191
+ throw error;
192
+ }
193
+ }
194
+ function removeIndexSidecars(path) {
195
+ closeIndex(path);
196
+ rmSync(`${path}-wal`, { force: true });
197
+ rmSync(`${path}-shm`, { force: true });
198
+ }
199
+ function rebuildable(error) {
200
+ if (error instanceof IndexVersionMismatch)
201
+ return true;
202
+ if (!isRecord(error) || error.code !== "ERR_SQLITE_ERROR" || typeof error.errcode !== "number")
203
+ return false;
204
+ const primaryCode = error.errcode & 0xff;
205
+ return primaryCode === 11 || primaryCode === 26;
206
+ }
207
+ function unavailable(path, error) {
208
+ const reason = errorMessage(error);
209
+ log.logWarn("memory.search_index.open_failed", "Search index open failed", { reason, fields: { path } });
210
+ return new SearchIndexUnavailableError(reason, { cause: error });
211
+ }
212
+ export function withSearchIndex(path, job) {
213
+ const key = resolve(path);
214
+ return queue.run(key, async () => {
215
+ for (;;) {
216
+ let opened = false;
217
+ try {
218
+ const handle = await ensureOpen(key);
219
+ opened = true;
220
+ return await job(handle);
221
+ }
222
+ catch (error) {
223
+ if (rebuildable(error) && !rebuiltOnce.has(key)) {
224
+ rebuiltOnce.add(key);
225
+ log.logWarn("memory.search_index.rebuilt", "Search index rebuild started", {
226
+ reason: errorMessage(error),
227
+ fields: { path: key },
228
+ });
229
+ try {
230
+ removeIndexFiles(key);
231
+ }
232
+ catch (cleanupError) {
233
+ throw unavailable(key, cleanupError);
234
+ }
235
+ continue;
236
+ }
237
+ // Generic SQL errors (including MATCH syntax errors) are programming errors.
238
+ if (!opened ||
239
+ rebuildable(error) ||
240
+ (isRecord(error) && error.code === "ERR_SQLITE_ERROR" && error.errcode !== 1)) {
241
+ throw unavailable(key, error);
242
+ }
243
+ throw error;
244
+ }
245
+ }
246
+ });
247
+ }
@@ -0,0 +1,11 @@
1
+ export declare function listIndexSourceEntries(dir: string): Promise<import("fs").Dirent<string>[]>;
2
+ export declare function statIndexSource(path: string): Promise<import("fs").Stats | undefined>;
3
+ export declare function sameIndexSourceStat(previous: {
4
+ ino: number;
5
+ size: number;
6
+ mtime_ms: number;
7
+ }, current: {
8
+ ino: number;
9
+ size: number;
10
+ mtimeMs: number;
11
+ }): boolean;
@@ -0,0 +1,26 @@
1
+ import { lstat, readdir } from "node:fs/promises";
2
+ import { isNodeError } from "../shared/os.js";
3
+ export async function listIndexSourceEntries(dir) {
4
+ try {
5
+ return await readdir(dir, { withFileTypes: true });
6
+ }
7
+ catch (error) {
8
+ if (isNodeError(error) && error.code === "ENOENT")
9
+ return [];
10
+ throw error;
11
+ }
12
+ }
13
+ export async function statIndexSource(path) {
14
+ try {
15
+ const stats = await lstat(path);
16
+ return stats.isFile() ? stats : undefined;
17
+ }
18
+ catch (error) {
19
+ if (isNodeError(error) && error.code === "ENOENT")
20
+ return undefined;
21
+ throw error;
22
+ }
23
+ }
24
+ export function sameIndexSourceStat(previous, current) {
25
+ return previous.ino === current.ino && previous.size === current.size && previous.mtime_ms === current.mtimeMs;
26
+ }
@@ -0,0 +1,11 @@
1
+ import { type SearchIndexHandle } from "./search-index-db.js";
2
+ import { type QueryTerms } from "./search-terms.js";
3
+ export interface MemorySearchHit {
4
+ kind: "memory" | "journal" | "workspace";
5
+ /** Entry name, journal date, or workspace heading. */
6
+ label: string;
7
+ date?: string;
8
+ line: string;
9
+ }
10
+ export declare function syncNoteSources(handle: SearchIndexHandle, deskDir: string, workspaceDir: string): Promise<void>;
11
+ export declare function queryNotes(handle: SearchIndexHandle, terms: QueryTerms, today: string, limit: number): MemorySearchHit[];
@@ -0,0 +1,155 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { basename, join } from "node:path";
3
+ import * as log from "../log.js";
4
+ import { localDayKey } from "../shared/local-time.js";
5
+ import { isNodeError } from "../shared/os.js";
6
+ import { errorMessage } from "../shared/text-utils.js";
7
+ import { getJournalDir } from "./journal.js";
8
+ import { transaction } from "./search-index-db.js";
9
+ import { listIndexSourceEntries, sameIndexSourceStat, statIndexSource } from "./search-index-files.js";
10
+ import { buildMatchExpression, effectiveTermCount, matchedTerms, searchTextFor, windowAroundDensestMatch, } from "./search-terms.js";
11
+ import { redactSecrets } from "./secret-redaction.js";
12
+ import { getMemoryDir, isValidMemoryName, parseMemoryFile } from "./store.js";
13
+ const WORKSPACE_MEMORY_PATH = "../MEMORY.md";
14
+ const MAX_LINE_CHARS = 200;
15
+ async function listNoteSources(deskDir, workspaceDir) {
16
+ const memoryDir = getMemoryDir(deskDir);
17
+ const journalDir = getJournalDir(deskDir);
18
+ const [memory, journal] = await Promise.all([listIndexSourceEntries(memoryDir), listIndexSourceEntries(journalDir)]);
19
+ return [
20
+ ...memory
21
+ .filter((entry) => entry.isFile() && entry.name.endsWith(".md") && isValidMemoryName(basename(entry.name, ".md")))
22
+ .map(({ name }) => ({ kind: "memory", path: join(memoryDir, name), relPath: `memory/${name}` })),
23
+ ...journal
24
+ .filter((entry) => entry.isFile() && /^\d{4}-\d{2}-\d{2}\.md$/.test(entry.name))
25
+ .map(({ name }) => ({ kind: "journal", path: join(journalDir, name), relPath: `journal/${name}` })),
26
+ { kind: "workspace", path: join(workspaceDir, "MEMORY.md"), relPath: WORKSPACE_MEMORY_PATH },
27
+ ];
28
+ }
29
+ function notesFromFile(source, raw, fallbackDate) {
30
+ switch (source.kind) {
31
+ case "memory": {
32
+ const { description, body, name, updated, expires } = parseMemoryFile(basename(source.path, ".md"), raw, fallbackDate);
33
+ return [{ kind: "memory", label: name, date: updated, expires, text: `${description}\n${body}`.trim() }];
34
+ }
35
+ case "journal": {
36
+ const date = basename(source.path, ".md");
37
+ return raw
38
+ .split("\n")
39
+ .map((line) => line.replace(/^[-*]\s*/, "").trim())
40
+ .filter((line) => line && !line.startsWith("#"))
41
+ .map((text) => ({ kind: "journal", label: date, date, text }));
42
+ }
43
+ case "workspace":
44
+ return raw
45
+ .split(/(?=^## )/m)
46
+ .map((text) => text.trim())
47
+ .filter(Boolean)
48
+ .map((text) => ({
49
+ kind: "workspace",
50
+ label: /^## ([^\n]+)/.exec(text)?.[1]?.trim() ?? "Background",
51
+ text,
52
+ }));
53
+ }
54
+ }
55
+ export async function syncNoteSources(handle, deskDir, workspaceDir) {
56
+ const db = handle.db;
57
+ const files = db
58
+ .prepare("SELECT path, ino, size, mtime_ms FROM files WHERE kind IN ('memory', 'journal', 'workspace')")
59
+ .all();
60
+ const previous = new Map(files.map((file) => [file.path, file]));
61
+ const deleteNotes = db.prepare("DELETE FROM notes WHERE path = ?");
62
+ const deleteFile = db.prepare("DELETE FROM files WHERE path = ?");
63
+ const insertNote = db.prepare("INSERT INTO notes(path, kind, label, date, expires, text, search_text) VALUES (?, ?, ?, ?, ?, ?, ?)");
64
+ const upsertFile = db.prepare(`
65
+ INSERT INTO files VALUES (?, ?, NULL, ?, ?, ?, ?, 0, 0, '')
66
+ ON CONFLICT(path) DO UPDATE SET ino=excluded.ino, size=excluded.size,
67
+ mtime_ms=excluded.mtime_ms, indexed_bytes=excluded.indexed_bytes
68
+ `);
69
+ const sources = await listNoteSources(deskDir, workspaceDir);
70
+ for (let offset = 0; offset < sources.length; offset += 64) {
71
+ const batch = sources.slice(offset, offset + 64);
72
+ const metadata = await Promise.allSettled(batch.map((source) => statIndexSource(source.path)));
73
+ for (const [index, source] of batch.entries()) {
74
+ const file = previous.get(source.relPath);
75
+ const result = metadata[index];
76
+ let notes;
77
+ try {
78
+ if (result.status === "rejected")
79
+ throw result.reason;
80
+ if (!result.value)
81
+ continue;
82
+ if (file && sameIndexSourceStat(file, result.value)) {
83
+ previous.delete(source.relPath);
84
+ continue;
85
+ }
86
+ notes = notesFromFile(source, await readFile(source.path, "utf8"), localDayKey(result.value.mtime));
87
+ }
88
+ catch (error) {
89
+ if (!isNodeError(error))
90
+ throw error;
91
+ if (error.code !== "ENOENT") {
92
+ previous.delete(source.relPath);
93
+ log.logWarn("memory.search_index.sync_failed", "Search index sync failed", {
94
+ reason: errorMessage(error),
95
+ fields: { path: source.path },
96
+ });
97
+ }
98
+ continue;
99
+ }
100
+ const { ino, size, mtimeMs } = result.value;
101
+ transaction(db, () => {
102
+ deleteNotes.run(source.relPath);
103
+ for (const note of notes) {
104
+ const text = redactSecrets(note.text);
105
+ if (!text)
106
+ continue;
107
+ insertNote.run(source.relPath, note.kind, redactSecrets(note.label), note.date ?? null, note.expires ?? null, text, searchTextFor(text));
108
+ }
109
+ upsertFile.run(source.relPath, source.kind, ino, size, mtimeMs, size);
110
+ });
111
+ previous.delete(source.relPath);
112
+ }
113
+ }
114
+ for (const path of previous.keys()) {
115
+ transaction(db, () => {
116
+ deleteNotes.run(path);
117
+ deleteFile.run(path);
118
+ });
119
+ }
120
+ }
121
+ function densestLine(text, terms) {
122
+ const lines = text
123
+ .split("\n")
124
+ .map((line) => line.trim())
125
+ .filter(Boolean);
126
+ let best = { text: lines[0] ?? text.trim(), matches: [], units: 0 };
127
+ for (const line of lines) {
128
+ const matched = matchedTerms(line, terms);
129
+ const units = effectiveTermCount(matched);
130
+ const matches = [...matched.latin, ...matched.cjk];
131
+ if (units > best.units || (units === best.units && matches.length > best.matches.length)) {
132
+ best = { text: line, units, matches };
133
+ }
134
+ }
135
+ return windowAroundDensestMatch(best.text, best.matches, MAX_LINE_CHARS, "…");
136
+ }
137
+ export function queryNotes(handle, terms, today, limit) {
138
+ const expression = buildMatchExpression(terms);
139
+ if (!expression)
140
+ return [];
141
+ const rows = handle.db
142
+ .prepare(`
143
+ SELECT n.kind, n.label, n.date, n.text, bm25(notes_fts) AS rank
144
+ FROM notes_fts JOIN notes n ON n.id = notes_fts.rowid
145
+ WHERE notes_fts MATCH ? AND (n.expires IS NULL OR n.expires >= ?)
146
+ ORDER BY rank, n.date DESC, n.path, n.id LIMIT ?
147
+ `)
148
+ .all(expression, today, limit);
149
+ return rows.map(({ kind, label, date, text }) => ({
150
+ kind,
151
+ label,
152
+ date: date ?? undefined,
153
+ line: densestLine(text, terms),
154
+ }));
155
+ }
@@ -0,0 +1,19 @@
1
+ import { type SearchIndexHandle } from "./search-index-db.js";
2
+ export interface DeskIndexTarget {
3
+ appHomeDir: string;
4
+ desk: string;
5
+ deskDir: string;
6
+ }
7
+ export interface SyncStats {
8
+ filesScanned: number;
9
+ filesIndexed: number;
10
+ filesAppended: number;
11
+ filesRebuilt: number;
12
+ filesRemoved: number;
13
+ docsAdded: number;
14
+ durationMs: number;
15
+ maxSliceMs: number;
16
+ }
17
+ export declare function syncTranscriptSources(handle: SearchIndexHandle, deskDir: string): Promise<SyncStats>;
18
+ export declare function syncDeskSearchIndex(target: DeskIndexTarget): Promise<SyncStats>;
19
+ export declare function pruneOrphanSearchIndexes(appHomeDir: string, workspaceDir: string): Promise<string[]>;