@tobilu/qmd 1.0.0 → 1.0.6

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/dist/store.js ADDED
@@ -0,0 +1,2374 @@
1
+ /**
2
+ * QMD Store - Core data access and retrieval functions
3
+ *
4
+ * This module provides all database operations, search functions, and document
5
+ * retrieval for QMD. It returns raw data structures that can be formatted by
6
+ * CLI or MCP consumers.
7
+ *
8
+ * Usage:
9
+ * const store = createStore("/path/to/db.sqlite");
10
+ * // or use default path:
11
+ * const store = createStore();
12
+ */
13
+ import { openDatabase, loadSqliteVec } from "./db.js";
14
+ import picomatch from "picomatch";
15
+ import { createHash } from "crypto";
16
+ import { realpathSync, statSync, mkdirSync } from "node:fs";
17
+ import { LlamaCpp, getDefaultLlamaCpp, formatQueryForEmbedding, formatDocForEmbedding, } from "./llm.js";
18
+ import { findContextForPath as collectionsFindContextForPath, addContext as collectionsAddContext, removeContext as collectionsRemoveContext, listAllContexts as collectionsListAllContexts, getCollection, listCollections as collectionsListCollections, addCollection as collectionsAddCollection, removeCollection as collectionsRemoveCollection, renameCollection as collectionsRenameCollection, setGlobalContext, loadConfig as collectionsLoadConfig, } from "./collections.js";
19
+ // =============================================================================
20
+ // Configuration
21
+ // =============================================================================
22
+ const HOME = process.env.HOME || "/tmp";
23
+ export const DEFAULT_EMBED_MODEL = "embeddinggemma";
24
+ export const DEFAULT_RERANK_MODEL = "ExpedientFalcon/qwen3-reranker:0.6b-q8_0";
25
+ export const DEFAULT_QUERY_MODEL = "Qwen/Qwen3-1.7B";
26
+ export const DEFAULT_GLOB = "**/*.md";
27
+ export const DEFAULT_MULTI_GET_MAX_BYTES = 10 * 1024; // 10KB
28
+ // Chunking: 900 tokens per chunk with 15% overlap
29
+ // Increased from 800 to accommodate smart chunking finding natural break points
30
+ export const CHUNK_SIZE_TOKENS = 900;
31
+ export const CHUNK_OVERLAP_TOKENS = Math.floor(CHUNK_SIZE_TOKENS * 0.15); // 135 tokens (15% overlap)
32
+ // Fallback char-based approximation for sync chunking (~4 chars per token)
33
+ export const CHUNK_SIZE_CHARS = CHUNK_SIZE_TOKENS * 4; // 3600 chars
34
+ export const CHUNK_OVERLAP_CHARS = CHUNK_OVERLAP_TOKENS * 4; // 540 chars
35
+ // Search window for finding optimal break points (in tokens, ~200 tokens)
36
+ export const CHUNK_WINDOW_TOKENS = 200;
37
+ export const CHUNK_WINDOW_CHARS = CHUNK_WINDOW_TOKENS * 4; // 800 chars
38
+ /**
39
+ * Patterns for detecting break points in markdown documents.
40
+ * Higher scores indicate better places to split.
41
+ * Scores are spread wide so headings decisively beat lower-quality breaks.
42
+ * Order matters for scoring - more specific patterns first.
43
+ */
44
+ export const BREAK_PATTERNS = [
45
+ [/\n#{1}(?!#)/g, 100, 'h1'], // # but not ##
46
+ [/\n#{2}(?!#)/g, 90, 'h2'], // ## but not ###
47
+ [/\n#{3}(?!#)/g, 80, 'h3'], // ### but not ####
48
+ [/\n#{4}(?!#)/g, 70, 'h4'], // #### but not #####
49
+ [/\n#{5}(?!#)/g, 60, 'h5'], // ##### but not ######
50
+ [/\n#{6}(?!#)/g, 50, 'h6'], // ######
51
+ [/\n```/g, 80, 'codeblock'], // code block boundary (same as h3)
52
+ [/\n(?:---|\*\*\*|___)\s*\n/g, 60, 'hr'], // horizontal rule
53
+ [/\n\n+/g, 20, 'blank'], // paragraph boundary
54
+ [/\n[-*]\s/g, 5, 'list'], // unordered list item
55
+ [/\n\d+\.\s/g, 5, 'numlist'], // ordered list item
56
+ [/\n/g, 1, 'newline'], // minimal break
57
+ ];
58
+ /**
59
+ * Scan text for all potential break points.
60
+ * Returns sorted array of break points with higher-scoring patterns taking precedence
61
+ * when multiple patterns match the same position.
62
+ */
63
+ export function scanBreakPoints(text) {
64
+ const points = [];
65
+ const seen = new Map(); // pos -> best break point at that pos
66
+ for (const [pattern, score, type] of BREAK_PATTERNS) {
67
+ for (const match of text.matchAll(pattern)) {
68
+ const pos = match.index;
69
+ const existing = seen.get(pos);
70
+ // Keep higher score if position already seen
71
+ if (!existing || score > existing.score) {
72
+ const bp = { pos, score, type };
73
+ seen.set(pos, bp);
74
+ }
75
+ }
76
+ }
77
+ // Convert to array and sort by position
78
+ for (const bp of seen.values()) {
79
+ points.push(bp);
80
+ }
81
+ return points.sort((a, b) => a.pos - b.pos);
82
+ }
83
+ /**
84
+ * Find all code fence regions in the text.
85
+ * Code fences are delimited by ``` and we should never split inside them.
86
+ */
87
+ export function findCodeFences(text) {
88
+ const regions = [];
89
+ const fencePattern = /\n```/g;
90
+ let inFence = false;
91
+ let fenceStart = 0;
92
+ for (const match of text.matchAll(fencePattern)) {
93
+ if (!inFence) {
94
+ fenceStart = match.index;
95
+ inFence = true;
96
+ }
97
+ else {
98
+ regions.push({ start: fenceStart, end: match.index + match[0].length });
99
+ inFence = false;
100
+ }
101
+ }
102
+ // Handle unclosed fence - extends to end of document
103
+ if (inFence) {
104
+ regions.push({ start: fenceStart, end: text.length });
105
+ }
106
+ return regions;
107
+ }
108
+ /**
109
+ * Check if a position is inside a code fence region.
110
+ */
111
+ export function isInsideCodeFence(pos, fences) {
112
+ return fences.some(f => pos > f.start && pos < f.end);
113
+ }
114
+ /**
115
+ * Find the best cut position using scored break points with distance decay.
116
+ *
117
+ * Uses squared distance for gentler early decay - headings far back still win
118
+ * over low-quality breaks near the target.
119
+ *
120
+ * @param breakPoints - Pre-scanned break points from scanBreakPoints()
121
+ * @param targetCharPos - The ideal cut position (e.g., maxChars boundary)
122
+ * @param windowChars - How far back to search for break points (default ~200 tokens)
123
+ * @param decayFactor - How much to penalize distance (0.7 = 30% score at window edge)
124
+ * @param codeFences - Code fence regions to avoid splitting inside
125
+ * @returns The best position to cut at
126
+ */
127
+ export function findBestCutoff(breakPoints, targetCharPos, windowChars = CHUNK_WINDOW_CHARS, decayFactor = 0.7, codeFences = []) {
128
+ const windowStart = targetCharPos - windowChars;
129
+ let bestScore = -1;
130
+ let bestPos = targetCharPos;
131
+ for (const bp of breakPoints) {
132
+ if (bp.pos < windowStart)
133
+ continue;
134
+ if (bp.pos > targetCharPos)
135
+ break; // sorted, so we can stop
136
+ // Skip break points inside code fences
137
+ if (isInsideCodeFence(bp.pos, codeFences))
138
+ continue;
139
+ const distance = targetCharPos - bp.pos;
140
+ // Squared distance decay: gentle early, steep late
141
+ // At target: multiplier = 1.0
142
+ // At 25% back: multiplier = 0.956
143
+ // At 50% back: multiplier = 0.825
144
+ // At 75% back: multiplier = 0.606
145
+ // At window edge: multiplier = 0.3
146
+ const normalizedDist = distance / windowChars;
147
+ const multiplier = 1.0 - (normalizedDist * normalizedDist) * decayFactor;
148
+ const finalScore = bp.score * multiplier;
149
+ if (finalScore > bestScore) {
150
+ bestScore = finalScore;
151
+ bestPos = bp.pos;
152
+ }
153
+ }
154
+ return bestPos;
155
+ }
156
+ // Hybrid query: strong BM25 signal detection thresholds
157
+ // Skip expensive LLM expansion when top result is strong AND clearly separated from runner-up
158
+ export const STRONG_SIGNAL_MIN_SCORE = 0.85;
159
+ export const STRONG_SIGNAL_MIN_GAP = 0.15;
160
+ // Max candidates to pass to reranker — balances quality vs latency.
161
+ // 40 keeps rank 31-40 visible to the reranker (matters for recall on broad queries).
162
+ export const RERANK_CANDIDATE_LIMIT = 40;
163
+ // =============================================================================
164
+ // Path utilities
165
+ // =============================================================================
166
+ export function homedir() {
167
+ return HOME;
168
+ }
169
+ /**
170
+ * Check if a path is absolute.
171
+ * Supports:
172
+ * - Unix paths: /path/to/file
173
+ * - Windows native: C:\path or C:/path
174
+ * - Git Bash: /c/path or /C/path (C-Z drives, excluding A/B floppy drives)
175
+ *
176
+ * Note: /c without trailing slash is treated as Unix path (directory named "c"),
177
+ * while /c/ or /c/path are treated as Git Bash paths (C: drive).
178
+ */
179
+ export function isAbsolutePath(path) {
180
+ if (!path)
181
+ return false;
182
+ // Unix absolute path
183
+ if (path.startsWith('/')) {
184
+ // Check if it's a Git Bash style path like /c/ or /c/Users (C-Z only, not A or B)
185
+ // Requires path[2] === '/' to distinguish from Unix paths like /c or /cache
186
+ if (path.length >= 3 && path[2] === '/') {
187
+ const driveLetter = path[1];
188
+ if (driveLetter && /[c-zC-Z]/.test(driveLetter)) {
189
+ return true;
190
+ }
191
+ }
192
+ // Any other path starting with / is Unix absolute
193
+ return true;
194
+ }
195
+ // Windows native path: C:\ or C:/ (any letter A-Z)
196
+ if (path.length >= 2 && /[a-zA-Z]/.test(path[0]) && path[1] === ':') {
197
+ return true;
198
+ }
199
+ return false;
200
+ }
201
+ /**
202
+ * Normalize path separators to forward slashes.
203
+ * Converts Windows backslashes to forward slashes.
204
+ */
205
+ export function normalizePathSeparators(path) {
206
+ return path.replace(/\\/g, '/');
207
+ }
208
+ /**
209
+ * Get the relative path from a prefix.
210
+ * Returns null if path is not under prefix.
211
+ * Returns empty string if path equals prefix.
212
+ */
213
+ export function getRelativePathFromPrefix(path, prefix) {
214
+ // Empty prefix is invalid
215
+ if (!prefix) {
216
+ return null;
217
+ }
218
+ const normalizedPath = normalizePathSeparators(path);
219
+ const normalizedPrefix = normalizePathSeparators(prefix);
220
+ // Ensure prefix ends with / for proper matching
221
+ const prefixWithSlash = !normalizedPrefix.endsWith('/')
222
+ ? normalizedPrefix + '/'
223
+ : normalizedPrefix;
224
+ // Exact match
225
+ if (normalizedPath === normalizedPrefix) {
226
+ return '';
227
+ }
228
+ // Check if path starts with prefix
229
+ if (normalizedPath.startsWith(prefixWithSlash)) {
230
+ return normalizedPath.slice(prefixWithSlash.length);
231
+ }
232
+ return null;
233
+ }
234
+ export function resolve(...paths) {
235
+ if (paths.length === 0) {
236
+ throw new Error("resolve: at least one path segment is required");
237
+ }
238
+ // Normalize all paths to use forward slashes
239
+ const normalizedPaths = paths.map(normalizePathSeparators);
240
+ let result = '';
241
+ let windowsDrive = '';
242
+ // Check if first path is absolute
243
+ const firstPath = normalizedPaths[0];
244
+ if (isAbsolutePath(firstPath)) {
245
+ result = firstPath;
246
+ // Extract Windows drive letter if present
247
+ if (firstPath.length >= 2 && /[a-zA-Z]/.test(firstPath[0]) && firstPath[1] === ':') {
248
+ windowsDrive = firstPath.slice(0, 2);
249
+ result = firstPath.slice(2);
250
+ }
251
+ else if (firstPath.startsWith('/') && firstPath.length >= 3 && firstPath[2] === '/') {
252
+ // Git Bash style: /c/ -> C: (C-Z drives only, not A or B)
253
+ const driveLetter = firstPath[1];
254
+ if (driveLetter && /[c-zC-Z]/.test(driveLetter)) {
255
+ windowsDrive = driveLetter.toUpperCase() + ':';
256
+ result = firstPath.slice(2);
257
+ }
258
+ }
259
+ }
260
+ else {
261
+ // Start with PWD or cwd, then append the first relative path
262
+ const pwd = normalizePathSeparators(process.env.PWD || process.cwd());
263
+ // Extract Windows drive from PWD if present
264
+ if (pwd.length >= 2 && /[a-zA-Z]/.test(pwd[0]) && pwd[1] === ':') {
265
+ windowsDrive = pwd.slice(0, 2);
266
+ result = pwd.slice(2) + '/' + firstPath;
267
+ }
268
+ else {
269
+ result = pwd + '/' + firstPath;
270
+ }
271
+ }
272
+ // Process remaining paths
273
+ for (let i = 1; i < normalizedPaths.length; i++) {
274
+ const p = normalizedPaths[i];
275
+ if (isAbsolutePath(p)) {
276
+ // Absolute path replaces everything
277
+ result = p;
278
+ // Update Windows drive if present
279
+ if (p.length >= 2 && /[a-zA-Z]/.test(p[0]) && p[1] === ':') {
280
+ windowsDrive = p.slice(0, 2);
281
+ result = p.slice(2);
282
+ }
283
+ else if (p.startsWith('/') && p.length >= 3 && p[2] === '/') {
284
+ // Git Bash style (C-Z drives only, not A or B)
285
+ const driveLetter = p[1];
286
+ if (driveLetter && /[c-zC-Z]/.test(driveLetter)) {
287
+ windowsDrive = driveLetter.toUpperCase() + ':';
288
+ result = p.slice(2);
289
+ }
290
+ else {
291
+ windowsDrive = '';
292
+ }
293
+ }
294
+ else {
295
+ windowsDrive = '';
296
+ }
297
+ }
298
+ else {
299
+ // Relative path - append
300
+ result = result + '/' + p;
301
+ }
302
+ }
303
+ // Normalize . and .. components
304
+ const parts = result.split('/').filter(Boolean);
305
+ const normalized = [];
306
+ for (const part of parts) {
307
+ if (part === '..') {
308
+ normalized.pop();
309
+ }
310
+ else if (part !== '.') {
311
+ normalized.push(part);
312
+ }
313
+ }
314
+ // Build final path
315
+ const finalPath = '/' + normalized.join('/');
316
+ // Prepend Windows drive if present
317
+ if (windowsDrive) {
318
+ return windowsDrive + finalPath;
319
+ }
320
+ return finalPath;
321
+ }
322
+ // Flag to indicate production mode (set by qmd.ts at startup)
323
+ let _productionMode = false;
324
+ export function enableProductionMode() {
325
+ _productionMode = true;
326
+ }
327
+ export function getDefaultDbPath(indexName = "index") {
328
+ // Always allow override via INDEX_PATH (for testing)
329
+ if (process.env.INDEX_PATH) {
330
+ return process.env.INDEX_PATH;
331
+ }
332
+ // In non-production mode (tests), require explicit path
333
+ if (!_productionMode) {
334
+ throw new Error("Database path not set. Tests must set INDEX_PATH env var or use createStore() with explicit path. " +
335
+ "This prevents tests from accidentally writing to the global index.");
336
+ }
337
+ const cacheDir = process.env.XDG_CACHE_HOME || resolve(homedir(), ".cache");
338
+ const qmdCacheDir = resolve(cacheDir, "qmd");
339
+ try {
340
+ mkdirSync(qmdCacheDir, { recursive: true });
341
+ }
342
+ catch { }
343
+ return resolve(qmdCacheDir, `${indexName}.sqlite`);
344
+ }
345
+ export function getPwd() {
346
+ return process.env.PWD || process.cwd();
347
+ }
348
+ export function getRealPath(path) {
349
+ try {
350
+ return realpathSync(path);
351
+ }
352
+ catch {
353
+ return resolve(path);
354
+ }
355
+ }
356
+ /**
357
+ * Normalize explicit virtual path formats to standard qmd:// format.
358
+ * Only handles paths that are already explicitly virtual:
359
+ * - qmd://collection/path.md (already normalized)
360
+ * - qmd:////collection/path.md (extra slashes - normalize)
361
+ * - //collection/path.md (missing qmd: prefix - add it)
362
+ *
363
+ * Does NOT handle:
364
+ * - collection/path.md (bare paths - could be filesystem relative)
365
+ * - :linenum suffix (should be parsed separately before calling this)
366
+ */
367
+ export function normalizeVirtualPath(input) {
368
+ let path = input.trim();
369
+ // Handle qmd:// with extra slashes: qmd:////collection/path -> qmd://collection/path
370
+ if (path.startsWith('qmd:')) {
371
+ // Remove qmd: prefix and normalize slashes
372
+ path = path.slice(4);
373
+ // Remove leading slashes and re-add exactly two
374
+ path = path.replace(/^\/+/, '');
375
+ return `qmd://${path}`;
376
+ }
377
+ // Handle //collection/path (missing qmd: prefix)
378
+ if (path.startsWith('//')) {
379
+ path = path.replace(/^\/+/, '');
380
+ return `qmd://${path}`;
381
+ }
382
+ // Return as-is for other cases (filesystem paths, docids, bare collection/path, etc.)
383
+ return path;
384
+ }
385
+ /**
386
+ * Parse a virtual path like "qmd://collection-name/path/to/file.md"
387
+ * into its components.
388
+ * Also supports collection root: "qmd://collection-name/" or "qmd://collection-name"
389
+ */
390
+ export function parseVirtualPath(virtualPath) {
391
+ // Normalize the path first
392
+ const normalized = normalizeVirtualPath(virtualPath);
393
+ // Match: qmd://collection-name[/optional-path]
394
+ // Allows: qmd://name, qmd://name/, qmd://name/path
395
+ const match = normalized.match(/^qmd:\/\/([^\/]+)\/?(.*)$/);
396
+ if (!match?.[1])
397
+ return null;
398
+ return {
399
+ collectionName: match[1],
400
+ path: match[2] ?? '', // Empty string for collection root
401
+ };
402
+ }
403
+ /**
404
+ * Build a virtual path from collection name and relative path.
405
+ */
406
+ export function buildVirtualPath(collectionName, path) {
407
+ return `qmd://${collectionName}/${path}`;
408
+ }
409
+ /**
410
+ * Check if a path is explicitly a virtual path.
411
+ * Only recognizes explicit virtual path formats:
412
+ * - qmd://collection/path.md
413
+ * - //collection/path.md
414
+ *
415
+ * Does NOT consider bare collection/path.md as virtual - that should be
416
+ * handled separately by checking if the first component is a collection name.
417
+ */
418
+ export function isVirtualPath(path) {
419
+ const trimmed = path.trim();
420
+ // Explicit qmd:// prefix (with any number of slashes)
421
+ if (trimmed.startsWith('qmd:'))
422
+ return true;
423
+ // //collection/path format (missing qmd: prefix)
424
+ if (trimmed.startsWith('//'))
425
+ return true;
426
+ return false;
427
+ }
428
+ /**
429
+ * Resolve a virtual path to absolute filesystem path.
430
+ */
431
+ export function resolveVirtualPath(db, virtualPath) {
432
+ const parsed = parseVirtualPath(virtualPath);
433
+ if (!parsed)
434
+ return null;
435
+ const coll = getCollectionByName(db, parsed.collectionName);
436
+ if (!coll)
437
+ return null;
438
+ return resolve(coll.pwd, parsed.path);
439
+ }
440
+ /**
441
+ * Convert an absolute filesystem path to a virtual path.
442
+ * Returns null if the file is not in any indexed collection.
443
+ */
444
+ export function toVirtualPath(db, absolutePath) {
445
+ // Get all collections from YAML config
446
+ const collections = collectionsListCollections();
447
+ // Find which collection this absolute path belongs to
448
+ for (const coll of collections) {
449
+ if (absolutePath.startsWith(coll.path + '/') || absolutePath === coll.path) {
450
+ // Extract relative path
451
+ const relativePath = absolutePath.startsWith(coll.path + '/')
452
+ ? absolutePath.slice(coll.path.length + 1)
453
+ : '';
454
+ // Verify this document exists in the database
455
+ const doc = db.prepare(`
456
+ SELECT d.path
457
+ FROM documents d
458
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
459
+ LIMIT 1
460
+ `).get(coll.name, relativePath);
461
+ if (doc) {
462
+ return buildVirtualPath(coll.name, relativePath);
463
+ }
464
+ }
465
+ }
466
+ return null;
467
+ }
468
+ // =============================================================================
469
+ // Database initialization
470
+ // =============================================================================
471
+ function createSqliteVecUnavailableError(reason) {
472
+ return new Error("sqlite-vec extension is unavailable. " +
473
+ `${reason}. ` +
474
+ "Install Homebrew SQLite so the sqlite-vec extension can be loaded, " +
475
+ "and set BREW_PREFIX if Homebrew is installed in a non-standard location.");
476
+ }
477
+ function getErrorMessage(err) {
478
+ return err instanceof Error ? err.message : String(err);
479
+ }
480
+ export function verifySqliteVecLoaded(db) {
481
+ try {
482
+ const row = db.prepare(`SELECT vec_version() AS version`).get();
483
+ if (!row?.version || typeof row.version !== "string") {
484
+ throw new Error("vec_version() returned no version");
485
+ }
486
+ }
487
+ catch (err) {
488
+ const message = getErrorMessage(err);
489
+ throw createSqliteVecUnavailableError(`sqlite-vec probe failed (${message})`);
490
+ }
491
+ }
492
+ let _sqliteVecAvailable = null;
493
+ function initializeDatabase(db) {
494
+ try {
495
+ loadSqliteVec(db);
496
+ verifySqliteVecLoaded(db);
497
+ _sqliteVecAvailable = true;
498
+ }
499
+ catch {
500
+ // sqlite-vec is optional — vector search won't work but FTS is fine
501
+ _sqliteVecAvailable = false;
502
+ }
503
+ db.exec("PRAGMA journal_mode = WAL");
504
+ db.exec("PRAGMA foreign_keys = ON");
505
+ // Drop legacy tables that are now managed in YAML
506
+ db.exec(`DROP TABLE IF EXISTS path_contexts`);
507
+ db.exec(`DROP TABLE IF EXISTS collections`);
508
+ // Content-addressable storage - the source of truth for document content
509
+ db.exec(`
510
+ CREATE TABLE IF NOT EXISTS content (
511
+ hash TEXT PRIMARY KEY,
512
+ doc TEXT NOT NULL,
513
+ created_at TEXT NOT NULL
514
+ )
515
+ `);
516
+ // Documents table - file system layer mapping virtual paths to content hashes
517
+ // Collections are now managed in ~/.config/qmd/index.yml
518
+ db.exec(`
519
+ CREATE TABLE IF NOT EXISTS documents (
520
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
521
+ collection TEXT NOT NULL,
522
+ path TEXT NOT NULL,
523
+ title TEXT NOT NULL,
524
+ hash TEXT NOT NULL,
525
+ created_at TEXT NOT NULL,
526
+ modified_at TEXT NOT NULL,
527
+ active INTEGER NOT NULL DEFAULT 1,
528
+ FOREIGN KEY (hash) REFERENCES content(hash) ON DELETE CASCADE,
529
+ UNIQUE(collection, path)
530
+ )
531
+ `);
532
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_documents_collection ON documents(collection, active)`);
533
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_documents_hash ON documents(hash)`);
534
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_documents_path ON documents(path, active)`);
535
+ // Cache table for LLM API calls
536
+ db.exec(`
537
+ CREATE TABLE IF NOT EXISTS llm_cache (
538
+ hash TEXT PRIMARY KEY,
539
+ result TEXT NOT NULL,
540
+ created_at TEXT NOT NULL
541
+ )
542
+ `);
543
+ // Content vectors
544
+ const cvInfo = db.prepare(`PRAGMA table_info(content_vectors)`).all();
545
+ const hasSeqColumn = cvInfo.some(col => col.name === 'seq');
546
+ if (cvInfo.length > 0 && !hasSeqColumn) {
547
+ db.exec(`DROP TABLE IF EXISTS content_vectors`);
548
+ db.exec(`DROP TABLE IF EXISTS vectors_vec`);
549
+ }
550
+ db.exec(`
551
+ CREATE TABLE IF NOT EXISTS content_vectors (
552
+ hash TEXT NOT NULL,
553
+ seq INTEGER NOT NULL DEFAULT 0,
554
+ pos INTEGER NOT NULL DEFAULT 0,
555
+ model TEXT NOT NULL,
556
+ embedded_at TEXT NOT NULL,
557
+ PRIMARY KEY (hash, seq)
558
+ )
559
+ `);
560
+ // FTS - index filepath (collection/path), title, and content
561
+ db.exec(`
562
+ CREATE VIRTUAL TABLE IF NOT EXISTS documents_fts USING fts5(
563
+ filepath, title, body,
564
+ tokenize='porter unicode61'
565
+ )
566
+ `);
567
+ // Triggers to keep FTS in sync
568
+ db.exec(`
569
+ CREATE TRIGGER IF NOT EXISTS documents_ai AFTER INSERT ON documents
570
+ WHEN new.active = 1
571
+ BEGIN
572
+ INSERT INTO documents_fts(rowid, filepath, title, body)
573
+ SELECT
574
+ new.id,
575
+ new.collection || '/' || new.path,
576
+ new.title,
577
+ (SELECT doc FROM content WHERE hash = new.hash)
578
+ WHERE new.active = 1;
579
+ END
580
+ `);
581
+ db.exec(`
582
+ CREATE TRIGGER IF NOT EXISTS documents_ad AFTER DELETE ON documents BEGIN
583
+ DELETE FROM documents_fts WHERE rowid = old.id;
584
+ END
585
+ `);
586
+ db.exec(`
587
+ CREATE TRIGGER IF NOT EXISTS documents_au AFTER UPDATE ON documents
588
+ BEGIN
589
+ -- Delete from FTS if no longer active
590
+ DELETE FROM documents_fts WHERE rowid = old.id AND new.active = 0;
591
+
592
+ -- Update FTS if still/newly active
593
+ INSERT OR REPLACE INTO documents_fts(rowid, filepath, title, body)
594
+ SELECT
595
+ new.id,
596
+ new.collection || '/' || new.path,
597
+ new.title,
598
+ (SELECT doc FROM content WHERE hash = new.hash)
599
+ WHERE new.active = 1;
600
+ END
601
+ `);
602
+ }
603
+ export function isSqliteVecAvailable() {
604
+ return _sqliteVecAvailable === true;
605
+ }
606
+ function ensureVecTableInternal(db, dimensions) {
607
+ if (!_sqliteVecAvailable) {
608
+ throw new Error("sqlite-vec is not available. Vector operations require a SQLite build with extension loading support.");
609
+ }
610
+ const tableInfo = db.prepare(`SELECT sql FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
611
+ if (tableInfo) {
612
+ const match = tableInfo.sql.match(/float\[(\d+)\]/);
613
+ const hasHashSeq = tableInfo.sql.includes('hash_seq');
614
+ const hasCosine = tableInfo.sql.includes('distance_metric=cosine');
615
+ const existingDims = match?.[1] ? parseInt(match[1], 10) : null;
616
+ if (existingDims === dimensions && hasHashSeq && hasCosine)
617
+ return;
618
+ // Table exists but wrong schema - need to rebuild
619
+ db.exec("DROP TABLE IF EXISTS vectors_vec");
620
+ }
621
+ db.exec(`CREATE VIRTUAL TABLE vectors_vec USING vec0(hash_seq TEXT PRIMARY KEY, embedding float[${dimensions}] distance_metric=cosine)`);
622
+ }
623
+ /**
624
+ * Create a new store instance with the given database path.
625
+ * If no path is provided, uses the default path (~/.cache/qmd/index.sqlite).
626
+ *
627
+ * @param dbPath - Path to the SQLite database file
628
+ * @returns Store instance with all methods bound to the database
629
+ */
630
+ export function createStore(dbPath) {
631
+ const resolvedPath = dbPath || getDefaultDbPath();
632
+ const db = openDatabase(resolvedPath);
633
+ initializeDatabase(db);
634
+ return {
635
+ db,
636
+ dbPath: resolvedPath,
637
+ close: () => db.close(),
638
+ ensureVecTable: (dimensions) => ensureVecTableInternal(db, dimensions),
639
+ // Index health
640
+ getHashesNeedingEmbedding: () => getHashesNeedingEmbedding(db),
641
+ getIndexHealth: () => getIndexHealth(db),
642
+ getStatus: () => getStatus(db),
643
+ // Caching
644
+ getCacheKey,
645
+ getCachedResult: (cacheKey) => getCachedResult(db, cacheKey),
646
+ setCachedResult: (cacheKey, result) => setCachedResult(db, cacheKey, result),
647
+ clearCache: () => clearCache(db),
648
+ // Cleanup and maintenance
649
+ deleteLLMCache: () => deleteLLMCache(db),
650
+ deleteInactiveDocuments: () => deleteInactiveDocuments(db),
651
+ cleanupOrphanedContent: () => cleanupOrphanedContent(db),
652
+ cleanupOrphanedVectors: () => cleanupOrphanedVectors(db),
653
+ vacuumDatabase: () => vacuumDatabase(db),
654
+ // Context
655
+ getContextForFile: (filepath) => getContextForFile(db, filepath),
656
+ getContextForPath: (collectionName, path) => getContextForPath(db, collectionName, path),
657
+ getCollectionByName: (name) => getCollectionByName(db, name),
658
+ getCollectionsWithoutContext: () => getCollectionsWithoutContext(db),
659
+ getTopLevelPathsWithoutContext: (collectionName) => getTopLevelPathsWithoutContext(db, collectionName),
660
+ // Virtual paths
661
+ parseVirtualPath,
662
+ buildVirtualPath,
663
+ isVirtualPath,
664
+ resolveVirtualPath: (virtualPath) => resolveVirtualPath(db, virtualPath),
665
+ toVirtualPath: (absolutePath) => toVirtualPath(db, absolutePath),
666
+ // Search
667
+ searchFTS: (query, limit, collectionName) => searchFTS(db, query, limit, collectionName),
668
+ searchVec: (query, model, limit, collectionName, session, precomputedEmbedding) => searchVec(db, query, model, limit, collectionName, session, precomputedEmbedding),
669
+ // Query expansion & reranking
670
+ expandQuery: (query, model) => expandQuery(query, model, db),
671
+ rerank: (query, documents, model) => rerank(query, documents, model, db),
672
+ // Document retrieval
673
+ findDocument: (filename, options) => findDocument(db, filename, options),
674
+ getDocumentBody: (doc, fromLine, maxLines) => getDocumentBody(db, doc, fromLine, maxLines),
675
+ findDocuments: (pattern, options) => findDocuments(db, pattern, options),
676
+ // Fuzzy matching and docid lookup
677
+ findSimilarFiles: (query, maxDistance, limit) => findSimilarFiles(db, query, maxDistance, limit),
678
+ matchFilesByGlob: (pattern) => matchFilesByGlob(db, pattern),
679
+ findDocumentByDocid: (docid) => findDocumentByDocid(db, docid),
680
+ // Document indexing operations
681
+ insertContent: (hash, content, createdAt) => insertContent(db, hash, content, createdAt),
682
+ insertDocument: (collectionName, path, title, hash, createdAt, modifiedAt) => insertDocument(db, collectionName, path, title, hash, createdAt, modifiedAt),
683
+ findActiveDocument: (collectionName, path) => findActiveDocument(db, collectionName, path),
684
+ updateDocumentTitle: (documentId, title, modifiedAt) => updateDocumentTitle(db, documentId, title, modifiedAt),
685
+ updateDocument: (documentId, title, hash, modifiedAt) => updateDocument(db, documentId, title, hash, modifiedAt),
686
+ deactivateDocument: (collectionName, path) => deactivateDocument(db, collectionName, path),
687
+ getActiveDocumentPaths: (collectionName) => getActiveDocumentPaths(db, collectionName),
688
+ // Vector/embedding operations
689
+ getHashesForEmbedding: () => getHashesForEmbedding(db),
690
+ clearAllEmbeddings: () => clearAllEmbeddings(db),
691
+ insertEmbedding: (hash, seq, pos, embedding, model, embeddedAt) => insertEmbedding(db, hash, seq, pos, embedding, model, embeddedAt),
692
+ };
693
+ }
694
+ /**
695
+ * Extract short docid from a full hash (first 6 characters).
696
+ */
697
+ export function getDocid(hash) {
698
+ return hash.slice(0, 6);
699
+ }
700
+ /**
701
+ * Handelize a filename to be more token-friendly.
702
+ * - Convert triple underscore `___` to `/` (folder separator)
703
+ * - Convert to lowercase
704
+ * - Replace sequences of non-word chars (except /) with single dash
705
+ * - Remove leading/trailing dashes from path segments
706
+ * - Preserve folder structure (a/b/c/d.md stays structured)
707
+ * - Preserve file extension
708
+ */
709
+ export function handelize(path) {
710
+ if (!path || path.trim() === '') {
711
+ throw new Error('handelize: path cannot be empty');
712
+ }
713
+ // Allow route-style "$" filenames while still rejecting paths with no usable content.
714
+ const segments = path.split('/').filter(Boolean);
715
+ const lastSegment = segments[segments.length - 1] || '';
716
+ const filenameWithoutExt = lastSegment.replace(/\.[^.]+$/, '');
717
+ const hasValidContent = /[\p{L}\p{N}$]/u.test(filenameWithoutExt);
718
+ if (!hasValidContent) {
719
+ throw new Error(`handelize: path "${path}" has no valid filename content`);
720
+ }
721
+ const result = path
722
+ .replace(/___/g, '/') // Triple underscore becomes folder separator
723
+ .toLowerCase()
724
+ .split('/')
725
+ .map((segment, idx, arr) => {
726
+ const isLastSegment = idx === arr.length - 1;
727
+ if (isLastSegment) {
728
+ // For the filename (last segment), preserve the extension
729
+ const extMatch = segment.match(/(\.[a-z0-9]+)$/i);
730
+ const ext = extMatch ? extMatch[1] : '';
731
+ const nameWithoutExt = ext ? segment.slice(0, -ext.length) : segment;
732
+ const cleanedName = nameWithoutExt
733
+ .replace(/[^\p{L}\p{N}$]+/gu, '-') // Keep route marker "$", dash-separate other chars
734
+ .replace(/^-+|-+$/g, ''); // Remove leading/trailing dashes
735
+ return cleanedName + ext;
736
+ }
737
+ else {
738
+ // For directories, just clean normally
739
+ return segment
740
+ .replace(/[^\p{L}\p{N}$]+/gu, '-')
741
+ .replace(/^-+|-+$/g, '');
742
+ }
743
+ })
744
+ .filter(Boolean)
745
+ .join('/');
746
+ if (!result) {
747
+ throw new Error(`handelize: path "${path}" resulted in empty string after processing`);
748
+ }
749
+ return result;
750
+ }
751
+ // =============================================================================
752
+ // Index health
753
+ // =============================================================================
754
+ export function getHashesNeedingEmbedding(db) {
755
+ const result = db.prepare(`
756
+ SELECT COUNT(DISTINCT d.hash) as count
757
+ FROM documents d
758
+ LEFT JOIN content_vectors v ON d.hash = v.hash AND v.seq = 0
759
+ WHERE d.active = 1 AND v.hash IS NULL
760
+ `).get();
761
+ return result.count;
762
+ }
763
+ export function getIndexHealth(db) {
764
+ const needsEmbedding = getHashesNeedingEmbedding(db);
765
+ const totalDocs = db.prepare(`SELECT COUNT(*) as count FROM documents WHERE active = 1`).get().count;
766
+ const mostRecent = db.prepare(`SELECT MAX(modified_at) as latest FROM documents WHERE active = 1`).get();
767
+ let daysStale = null;
768
+ if (mostRecent?.latest) {
769
+ const lastUpdate = new Date(mostRecent.latest);
770
+ daysStale = Math.floor((Date.now() - lastUpdate.getTime()) / (24 * 60 * 60 * 1000));
771
+ }
772
+ return { needsEmbedding, totalDocs, daysStale };
773
+ }
774
+ // =============================================================================
775
+ // Caching
776
+ // =============================================================================
777
+ export function getCacheKey(url, body) {
778
+ const hash = createHash("sha256");
779
+ hash.update(url);
780
+ hash.update(JSON.stringify(body));
781
+ return hash.digest("hex");
782
+ }
783
+ export function getCachedResult(db, cacheKey) {
784
+ const row = db.prepare(`SELECT result FROM llm_cache WHERE hash = ?`).get(cacheKey);
785
+ return row?.result || null;
786
+ }
787
+ export function setCachedResult(db, cacheKey, result) {
788
+ const now = new Date().toISOString();
789
+ db.prepare(`INSERT OR REPLACE INTO llm_cache (hash, result, created_at) VALUES (?, ?, ?)`).run(cacheKey, result, now);
790
+ if (Math.random() < 0.01) {
791
+ db.exec(`DELETE FROM llm_cache WHERE hash NOT IN (SELECT hash FROM llm_cache ORDER BY created_at DESC LIMIT 1000)`);
792
+ }
793
+ }
794
+ export function clearCache(db) {
795
+ db.exec(`DELETE FROM llm_cache`);
796
+ }
797
+ // =============================================================================
798
+ // Cleanup and maintenance operations
799
+ // =============================================================================
800
+ /**
801
+ * Delete cached LLM API responses.
802
+ * Returns the number of cached responses deleted.
803
+ */
804
+ export function deleteLLMCache(db) {
805
+ const result = db.prepare(`DELETE FROM llm_cache`).run();
806
+ return result.changes;
807
+ }
808
+ /**
809
+ * Remove inactive document records (active = 0).
810
+ * Returns the number of inactive documents deleted.
811
+ */
812
+ export function deleteInactiveDocuments(db) {
813
+ const result = db.prepare(`DELETE FROM documents WHERE active = 0`).run();
814
+ return result.changes;
815
+ }
816
+ /**
817
+ * Remove orphaned content hashes that are not referenced by any active document.
818
+ * Returns the number of orphaned content hashes deleted.
819
+ */
820
+ export function cleanupOrphanedContent(db) {
821
+ const result = db.prepare(`
822
+ DELETE FROM content
823
+ WHERE hash NOT IN (SELECT DISTINCT hash FROM documents WHERE active = 1)
824
+ `).run();
825
+ return result.changes;
826
+ }
827
+ /**
828
+ * Remove orphaned vector embeddings that are not referenced by any active document.
829
+ * Returns the number of orphaned embedding chunks deleted.
830
+ */
831
+ export function cleanupOrphanedVectors(db) {
832
+ // Check if vectors_vec table exists
833
+ const tableExists = db.prepare(`
834
+ SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'
835
+ `).get();
836
+ if (!tableExists) {
837
+ return 0;
838
+ }
839
+ // Count orphaned vectors first
840
+ const countResult = db.prepare(`
841
+ SELECT COUNT(*) as c FROM content_vectors cv
842
+ WHERE NOT EXISTS (
843
+ SELECT 1 FROM documents d WHERE d.hash = cv.hash AND d.active = 1
844
+ )
845
+ `).get();
846
+ if (countResult.c === 0) {
847
+ return 0;
848
+ }
849
+ // Delete from vectors_vec first
850
+ db.exec(`
851
+ DELETE FROM vectors_vec WHERE hash_seq IN (
852
+ SELECT cv.hash || '_' || cv.seq FROM content_vectors cv
853
+ WHERE NOT EXISTS (
854
+ SELECT 1 FROM documents d WHERE d.hash = cv.hash AND d.active = 1
855
+ )
856
+ )
857
+ `);
858
+ // Delete from content_vectors
859
+ db.exec(`
860
+ DELETE FROM content_vectors WHERE hash NOT IN (
861
+ SELECT hash FROM documents WHERE active = 1
862
+ )
863
+ `);
864
+ return countResult.c;
865
+ }
866
+ /**
867
+ * Run VACUUM to reclaim unused space in the database.
868
+ * This operation rebuilds the database file to eliminate fragmentation.
869
+ */
870
+ export function vacuumDatabase(db) {
871
+ db.exec(`VACUUM`);
872
+ }
873
+ // =============================================================================
874
+ // Document helpers
875
+ // =============================================================================
876
+ export async function hashContent(content) {
877
+ const hash = createHash("sha256");
878
+ hash.update(content);
879
+ return hash.digest("hex");
880
+ }
881
+ const titleExtractors = {
882
+ '.md': (content) => {
883
+ const match = content.match(/^##?\s+(.+)$/m);
884
+ if (match) {
885
+ const title = (match[1] ?? "").trim();
886
+ if (title === "📝 Notes" || title === "Notes") {
887
+ const nextMatch = content.match(/^##\s+(.+)$/m);
888
+ if (nextMatch?.[1])
889
+ return nextMatch[1].trim();
890
+ }
891
+ return title;
892
+ }
893
+ return null;
894
+ },
895
+ '.org': (content) => {
896
+ const titleProp = content.match(/^#\+TITLE:\s*(.+)$/im);
897
+ if (titleProp?.[1])
898
+ return titleProp[1].trim();
899
+ const heading = content.match(/^\*+\s+(.+)$/m);
900
+ if (heading?.[1])
901
+ return heading[1].trim();
902
+ return null;
903
+ },
904
+ };
905
+ export function extractTitle(content, filename) {
906
+ const ext = filename.slice(filename.lastIndexOf('.')).toLowerCase();
907
+ const extractor = titleExtractors[ext];
908
+ if (extractor) {
909
+ const title = extractor(content);
910
+ if (title)
911
+ return title;
912
+ }
913
+ return filename.replace(/\.[^.]+$/, "").split("/").pop() || filename;
914
+ }
915
+ // =============================================================================
916
+ // Document indexing operations
917
+ // =============================================================================
918
+ /**
919
+ * Insert content into the content table (content-addressable storage).
920
+ * Uses INSERT OR IGNORE so duplicate hashes are skipped.
921
+ */
922
+ export function insertContent(db, hash, content, createdAt) {
923
+ db.prepare(`INSERT OR IGNORE INTO content (hash, doc, created_at) VALUES (?, ?, ?)`)
924
+ .run(hash, content, createdAt);
925
+ }
926
+ /**
927
+ * Insert a new document into the documents table.
928
+ */
929
+ export function insertDocument(db, collectionName, path, title, hash, createdAt, modifiedAt) {
930
+ db.prepare(`
931
+ INSERT INTO documents (collection, path, title, hash, created_at, modified_at, active)
932
+ VALUES (?, ?, ?, ?, ?, ?, 1)
933
+ ON CONFLICT(collection, path) DO UPDATE SET
934
+ title = excluded.title,
935
+ hash = excluded.hash,
936
+ modified_at = excluded.modified_at,
937
+ active = 1
938
+ `).run(collectionName, path, title, hash, createdAt, modifiedAt);
939
+ }
940
+ /**
941
+ * Find an active document by collection name and path.
942
+ */
943
+ export function findActiveDocument(db, collectionName, path) {
944
+ const row = db.prepare(`
945
+ SELECT id, hash, title FROM documents
946
+ WHERE collection = ? AND path = ? AND active = 1
947
+ `).get(collectionName, path);
948
+ return row ?? null;
949
+ }
950
+ /**
951
+ * Update the title and modified_at timestamp for a document.
952
+ */
953
+ export function updateDocumentTitle(db, documentId, title, modifiedAt) {
954
+ db.prepare(`UPDATE documents SET title = ?, modified_at = ? WHERE id = ?`)
955
+ .run(title, modifiedAt, documentId);
956
+ }
957
+ /**
958
+ * Update an existing document's hash, title, and modified_at timestamp.
959
+ * Used when content changes but the file path stays the same.
960
+ */
961
+ export function updateDocument(db, documentId, title, hash, modifiedAt) {
962
+ db.prepare(`UPDATE documents SET title = ?, hash = ?, modified_at = ? WHERE id = ?`)
963
+ .run(title, hash, modifiedAt, documentId);
964
+ }
965
+ /**
966
+ * Deactivate a document (mark as inactive but don't delete).
967
+ */
968
+ export function deactivateDocument(db, collectionName, path) {
969
+ db.prepare(`UPDATE documents SET active = 0 WHERE collection = ? AND path = ? AND active = 1`)
970
+ .run(collectionName, path);
971
+ }
972
+ /**
973
+ * Get all active document paths for a collection.
974
+ */
975
+ export function getActiveDocumentPaths(db, collectionName) {
976
+ const rows = db.prepare(`
977
+ SELECT path FROM documents WHERE collection = ? AND active = 1
978
+ `).all(collectionName);
979
+ return rows.map(r => r.path);
980
+ }
981
+ export { formatQueryForEmbedding, formatDocForEmbedding };
982
+ export function chunkDocument(content, maxChars = CHUNK_SIZE_CHARS, overlapChars = CHUNK_OVERLAP_CHARS, windowChars = CHUNK_WINDOW_CHARS) {
983
+ if (content.length <= maxChars) {
984
+ return [{ text: content, pos: 0 }];
985
+ }
986
+ // Pre-scan all break points and code fences once
987
+ const breakPoints = scanBreakPoints(content);
988
+ const codeFences = findCodeFences(content);
989
+ const chunks = [];
990
+ let charPos = 0;
991
+ while (charPos < content.length) {
992
+ // Calculate target end position for this chunk
993
+ const targetEndPos = Math.min(charPos + maxChars, content.length);
994
+ let endPos = targetEndPos;
995
+ // If not at the end, find the best break point
996
+ if (endPos < content.length) {
997
+ // Find best cutoff using scored algorithm
998
+ const bestCutoff = findBestCutoff(breakPoints, targetEndPos, windowChars, 0.7, codeFences);
999
+ // Only use the cutoff if it's within our current chunk
1000
+ if (bestCutoff > charPos && bestCutoff <= targetEndPos) {
1001
+ endPos = bestCutoff;
1002
+ }
1003
+ }
1004
+ // Ensure we make progress
1005
+ if (endPos <= charPos) {
1006
+ endPos = Math.min(charPos + maxChars, content.length);
1007
+ }
1008
+ chunks.push({ text: content.slice(charPos, endPos), pos: charPos });
1009
+ // Move forward, but overlap with previous chunk
1010
+ // For last chunk, don't overlap (just go to the end)
1011
+ if (endPos >= content.length) {
1012
+ break;
1013
+ }
1014
+ charPos = endPos - overlapChars;
1015
+ const lastChunkPos = chunks.at(-1).pos;
1016
+ if (charPos <= lastChunkPos) {
1017
+ // Prevent infinite loop - move forward at least a bit
1018
+ charPos = endPos;
1019
+ }
1020
+ }
1021
+ return chunks;
1022
+ }
1023
+ /**
1024
+ * Chunk a document by actual token count using the LLM tokenizer.
1025
+ * More accurate than character-based chunking but requires async.
1026
+ */
1027
+ export async function chunkDocumentByTokens(content, maxTokens = CHUNK_SIZE_TOKENS, overlapTokens = CHUNK_OVERLAP_TOKENS, windowTokens = CHUNK_WINDOW_TOKENS) {
1028
+ const llm = getDefaultLlamaCpp();
1029
+ // Use moderate chars/token estimate (prose ~4, code ~2, mixed ~3)
1030
+ // If chunks exceed limit, they'll be re-split with actual ratio
1031
+ const avgCharsPerToken = 3;
1032
+ const maxChars = maxTokens * avgCharsPerToken;
1033
+ const overlapChars = overlapTokens * avgCharsPerToken;
1034
+ const windowChars = windowTokens * avgCharsPerToken;
1035
+ // Chunk in character space with conservative estimate
1036
+ let charChunks = chunkDocument(content, maxChars, overlapChars, windowChars);
1037
+ // Tokenize and split any chunks that still exceed limit
1038
+ const results = [];
1039
+ for (const chunk of charChunks) {
1040
+ const tokens = await llm.tokenize(chunk.text);
1041
+ if (tokens.length <= maxTokens) {
1042
+ results.push({ text: chunk.text, pos: chunk.pos, tokens: tokens.length });
1043
+ }
1044
+ else {
1045
+ // Chunk is still too large - split it further
1046
+ // Use actual token count to estimate better char limit
1047
+ const actualCharsPerToken = chunk.text.length / tokens.length;
1048
+ const safeMaxChars = Math.floor(maxTokens * actualCharsPerToken * 0.95); // 5% safety margin
1049
+ const subChunks = chunkDocument(chunk.text, safeMaxChars, Math.floor(overlapChars * actualCharsPerToken / 2), Math.floor(windowChars * actualCharsPerToken / 2));
1050
+ for (const subChunk of subChunks) {
1051
+ const subTokens = await llm.tokenize(subChunk.text);
1052
+ results.push({
1053
+ text: subChunk.text,
1054
+ pos: chunk.pos + subChunk.pos,
1055
+ tokens: subTokens.length,
1056
+ });
1057
+ }
1058
+ }
1059
+ }
1060
+ return results;
1061
+ }
1062
+ // =============================================================================
1063
+ // Fuzzy matching
1064
+ // =============================================================================
1065
+ function levenshtein(a, b) {
1066
+ const m = a.length, n = b.length;
1067
+ if (m === 0)
1068
+ return n;
1069
+ if (n === 0)
1070
+ return m;
1071
+ const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
1072
+ for (let i = 0; i <= m; i++)
1073
+ dp[i][0] = i;
1074
+ for (let j = 0; j <= n; j++)
1075
+ dp[0][j] = j;
1076
+ for (let i = 1; i <= m; i++) {
1077
+ for (let j = 1; j <= n; j++) {
1078
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
1079
+ dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);
1080
+ }
1081
+ }
1082
+ return dp[m][n];
1083
+ }
1084
+ /**
1085
+ * Normalize a docid input by stripping surrounding quotes and leading #.
1086
+ * Handles: "#abc123", 'abc123', "abc123", #abc123, abc123
1087
+ * Returns the bare hex string.
1088
+ */
1089
+ export function normalizeDocid(docid) {
1090
+ let normalized = docid.trim();
1091
+ // Strip surrounding quotes (single or double)
1092
+ if ((normalized.startsWith('"') && normalized.endsWith('"')) ||
1093
+ (normalized.startsWith("'") && normalized.endsWith("'"))) {
1094
+ normalized = normalized.slice(1, -1);
1095
+ }
1096
+ // Strip leading # if present
1097
+ if (normalized.startsWith('#')) {
1098
+ normalized = normalized.slice(1);
1099
+ }
1100
+ return normalized;
1101
+ }
1102
+ /**
1103
+ * Check if a string looks like a docid reference.
1104
+ * Accepts: #abc123, abc123, "#abc123", "abc123", '#abc123', 'abc123'
1105
+ * Returns true if the normalized form is a valid hex string of 6+ chars.
1106
+ */
1107
+ export function isDocid(input) {
1108
+ const normalized = normalizeDocid(input);
1109
+ // Must be at least 6 hex characters
1110
+ return normalized.length >= 6 && /^[a-f0-9]+$/i.test(normalized);
1111
+ }
1112
+ /**
1113
+ * Find a document by its short docid (first 6 characters of hash).
1114
+ * Returns the document's virtual path if found, null otherwise.
1115
+ * If multiple documents match the same short hash (collision), returns the first one.
1116
+ *
1117
+ * Accepts lenient input: #abc123, abc123, "#abc123", "abc123"
1118
+ */
1119
+ export function findDocumentByDocid(db, docid) {
1120
+ const shortHash = normalizeDocid(docid);
1121
+ if (shortHash.length < 1)
1122
+ return null;
1123
+ // Look up documents where hash starts with the short hash
1124
+ const doc = db.prepare(`
1125
+ SELECT 'qmd://' || d.collection || '/' || d.path as filepath, d.hash
1126
+ FROM documents d
1127
+ WHERE d.hash LIKE ? AND d.active = 1
1128
+ LIMIT 1
1129
+ `).get(`${shortHash}%`);
1130
+ return doc;
1131
+ }
1132
+ export function findSimilarFiles(db, query, maxDistance = 3, limit = 5) {
1133
+ const allFiles = db.prepare(`
1134
+ SELECT d.path
1135
+ FROM documents d
1136
+ WHERE d.active = 1
1137
+ `).all();
1138
+ const queryLower = query.toLowerCase();
1139
+ const scored = allFiles
1140
+ .map(f => ({ path: f.path, dist: levenshtein(f.path.toLowerCase(), queryLower) }))
1141
+ .filter(f => f.dist <= maxDistance)
1142
+ .sort((a, b) => a.dist - b.dist)
1143
+ .slice(0, limit);
1144
+ return scored.map(f => f.path);
1145
+ }
1146
+ export function matchFilesByGlob(db, pattern) {
1147
+ const allFiles = db.prepare(`
1148
+ SELECT
1149
+ 'qmd://' || d.collection || '/' || d.path as virtual_path,
1150
+ LENGTH(content.doc) as body_length,
1151
+ d.path,
1152
+ d.collection
1153
+ FROM documents d
1154
+ JOIN content ON content.hash = d.hash
1155
+ WHERE d.active = 1
1156
+ `).all();
1157
+ const isMatch = picomatch(pattern);
1158
+ return allFiles
1159
+ .filter(f => isMatch(f.virtual_path) || isMatch(f.path))
1160
+ .map(f => ({
1161
+ filepath: f.virtual_path, // Virtual path for precise lookup
1162
+ displayPath: f.path, // Relative path for display
1163
+ bodyLength: f.body_length
1164
+ }));
1165
+ }
1166
+ // =============================================================================
1167
+ // Context
1168
+ // =============================================================================
1169
+ /**
1170
+ * Get context for a file path using hierarchical inheritance.
1171
+ * Contexts are collection-scoped and inherit from parent directories.
1172
+ * For example, context at "/talks" applies to "/talks/2024/keynote.md".
1173
+ *
1174
+ * @param db Database instance (unused - kept for compatibility)
1175
+ * @param collectionName Collection name
1176
+ * @param path Relative path within the collection
1177
+ * @returns Context string or null if no context is defined
1178
+ */
1179
+ export function getContextForPath(db, collectionName, path) {
1180
+ const config = collectionsLoadConfig();
1181
+ const coll = getCollection(collectionName);
1182
+ if (!coll)
1183
+ return null;
1184
+ // Collect ALL matching contexts (global + all path prefixes)
1185
+ const contexts = [];
1186
+ // Add global context if present
1187
+ if (config.global_context) {
1188
+ contexts.push(config.global_context);
1189
+ }
1190
+ // Add all matching path contexts (from most general to most specific)
1191
+ if (coll.context) {
1192
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
1193
+ // Collect all matching prefixes
1194
+ const matchingContexts = [];
1195
+ for (const [prefix, context] of Object.entries(coll.context)) {
1196
+ const normalizedPrefix = prefix.startsWith("/") ? prefix : `/${prefix}`;
1197
+ if (normalizedPath.startsWith(normalizedPrefix)) {
1198
+ matchingContexts.push({ prefix: normalizedPrefix, context });
1199
+ }
1200
+ }
1201
+ // Sort by prefix length (shortest/most general first)
1202
+ matchingContexts.sort((a, b) => a.prefix.length - b.prefix.length);
1203
+ // Add all matching contexts
1204
+ for (const match of matchingContexts) {
1205
+ contexts.push(match.context);
1206
+ }
1207
+ }
1208
+ // Join all contexts with double newline
1209
+ return contexts.length > 0 ? contexts.join('\n\n') : null;
1210
+ }
1211
+ /**
1212
+ * Get context for a file path (virtual or filesystem).
1213
+ * Resolves the collection and relative path using the YAML collections config.
1214
+ */
1215
+ export function getContextForFile(db, filepath) {
1216
+ // Handle undefined or null filepath
1217
+ if (!filepath)
1218
+ return null;
1219
+ // Get all collections from YAML config
1220
+ const collections = collectionsListCollections();
1221
+ const config = collectionsLoadConfig();
1222
+ // Parse virtual path format: qmd://collection/path
1223
+ let collectionName = null;
1224
+ let relativePath = null;
1225
+ const parsedVirtual = filepath.startsWith('qmd://') ? parseVirtualPath(filepath) : null;
1226
+ if (parsedVirtual) {
1227
+ collectionName = parsedVirtual.collectionName;
1228
+ relativePath = parsedVirtual.path;
1229
+ }
1230
+ else {
1231
+ // Filesystem path: find which collection this absolute path belongs to
1232
+ for (const coll of collections) {
1233
+ // Skip collections with missing paths
1234
+ if (!coll || !coll.path)
1235
+ continue;
1236
+ if (filepath.startsWith(coll.path + '/') || filepath === coll.path) {
1237
+ collectionName = coll.name;
1238
+ // Extract relative path
1239
+ relativePath = filepath.startsWith(coll.path + '/')
1240
+ ? filepath.slice(coll.path.length + 1)
1241
+ : '';
1242
+ break;
1243
+ }
1244
+ }
1245
+ if (!collectionName || relativePath === null)
1246
+ return null;
1247
+ }
1248
+ // Get the collection from config
1249
+ const coll = getCollection(collectionName);
1250
+ if (!coll)
1251
+ return null;
1252
+ // Verify this document exists in the database
1253
+ const doc = db.prepare(`
1254
+ SELECT d.path
1255
+ FROM documents d
1256
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
1257
+ LIMIT 1
1258
+ `).get(collectionName, relativePath);
1259
+ if (!doc)
1260
+ return null;
1261
+ // Collect ALL matching contexts (global + all path prefixes)
1262
+ const contexts = [];
1263
+ // Add global context if present
1264
+ if (config.global_context) {
1265
+ contexts.push(config.global_context);
1266
+ }
1267
+ // Add all matching path contexts (from most general to most specific)
1268
+ if (coll.context) {
1269
+ const normalizedPath = relativePath.startsWith("/") ? relativePath : `/${relativePath}`;
1270
+ // Collect all matching prefixes
1271
+ const matchingContexts = [];
1272
+ for (const [prefix, context] of Object.entries(coll.context)) {
1273
+ const normalizedPrefix = prefix.startsWith("/") ? prefix : `/${prefix}`;
1274
+ if (normalizedPath.startsWith(normalizedPrefix)) {
1275
+ matchingContexts.push({ prefix: normalizedPrefix, context });
1276
+ }
1277
+ }
1278
+ // Sort by prefix length (shortest/most general first)
1279
+ matchingContexts.sort((a, b) => a.prefix.length - b.prefix.length);
1280
+ // Add all matching contexts
1281
+ for (const match of matchingContexts) {
1282
+ contexts.push(match.context);
1283
+ }
1284
+ }
1285
+ // Join all contexts with double newline
1286
+ return contexts.length > 0 ? contexts.join('\n\n') : null;
1287
+ }
1288
+ /**
1289
+ * Get collection by name from YAML config.
1290
+ * Returns collection metadata from ~/.config/qmd/index.yml
1291
+ */
1292
+ export function getCollectionByName(db, name) {
1293
+ const collection = getCollection(name);
1294
+ if (!collection)
1295
+ return null;
1296
+ return {
1297
+ name: collection.name,
1298
+ pwd: collection.path,
1299
+ glob_pattern: collection.pattern,
1300
+ };
1301
+ }
1302
+ /**
1303
+ * List all collections with document counts from database.
1304
+ * Merges YAML config with database statistics.
1305
+ */
1306
+ export function listCollections(db) {
1307
+ const collections = collectionsListCollections();
1308
+ // Get document counts from database for each collection
1309
+ const result = collections.map(coll => {
1310
+ const stats = db.prepare(`
1311
+ SELECT
1312
+ COUNT(d.id) as doc_count,
1313
+ SUM(CASE WHEN d.active = 1 THEN 1 ELSE 0 END) as active_count,
1314
+ MAX(d.modified_at) as last_modified
1315
+ FROM documents d
1316
+ WHERE d.collection = ?
1317
+ `).get(coll.name);
1318
+ return {
1319
+ name: coll.name,
1320
+ pwd: coll.path,
1321
+ glob_pattern: coll.pattern,
1322
+ doc_count: stats?.doc_count || 0,
1323
+ active_count: stats?.active_count || 0,
1324
+ last_modified: stats?.last_modified || null,
1325
+ };
1326
+ });
1327
+ return result;
1328
+ }
1329
+ /**
1330
+ * Remove a collection and clean up its documents.
1331
+ * Uses collections.ts to remove from YAML config and cleans up database.
1332
+ */
1333
+ export function removeCollection(db, collectionName) {
1334
+ // Delete documents from database
1335
+ const docResult = db.prepare(`DELETE FROM documents WHERE collection = ?`).run(collectionName);
1336
+ // Clean up orphaned content hashes
1337
+ const cleanupResult = db.prepare(`
1338
+ DELETE FROM content
1339
+ WHERE hash NOT IN (SELECT DISTINCT hash FROM documents WHERE active = 1)
1340
+ `).run();
1341
+ // Remove from YAML config (returns true if found and removed)
1342
+ collectionsRemoveCollection(collectionName);
1343
+ return {
1344
+ deletedDocs: docResult.changes,
1345
+ cleanedHashes: cleanupResult.changes
1346
+ };
1347
+ }
1348
+ /**
1349
+ * Rename a collection.
1350
+ * Updates both YAML config and database documents table.
1351
+ */
1352
+ export function renameCollection(db, oldName, newName) {
1353
+ // Update all documents with the new collection name in database
1354
+ db.prepare(`UPDATE documents SET collection = ? WHERE collection = ?`)
1355
+ .run(newName, oldName);
1356
+ // Rename in YAML config
1357
+ collectionsRenameCollection(oldName, newName);
1358
+ }
1359
+ // =============================================================================
1360
+ // Context Management Operations
1361
+ // =============================================================================
1362
+ /**
1363
+ * Insert or update a context for a specific collection and path prefix.
1364
+ */
1365
+ export function insertContext(db, collectionId, pathPrefix, context) {
1366
+ // Get collection name from ID
1367
+ const coll = db.prepare(`SELECT name FROM collections WHERE id = ?`).get(collectionId);
1368
+ if (!coll) {
1369
+ throw new Error(`Collection with id ${collectionId} not found`);
1370
+ }
1371
+ // Use collections.ts to add context
1372
+ collectionsAddContext(coll.name, pathPrefix, context);
1373
+ }
1374
+ /**
1375
+ * Delete a context for a specific collection and path prefix.
1376
+ * Returns the number of contexts deleted.
1377
+ */
1378
+ export function deleteContext(db, collectionName, pathPrefix) {
1379
+ // Use collections.ts to remove context
1380
+ const success = collectionsRemoveContext(collectionName, pathPrefix);
1381
+ return success ? 1 : 0;
1382
+ }
1383
+ /**
1384
+ * Delete all global contexts (contexts with empty path_prefix).
1385
+ * Returns the number of contexts deleted.
1386
+ */
1387
+ export function deleteGlobalContexts(db) {
1388
+ let deletedCount = 0;
1389
+ // Remove global context
1390
+ setGlobalContext(undefined);
1391
+ deletedCount++;
1392
+ // Remove root context (empty string) from all collections
1393
+ const collections = collectionsListCollections();
1394
+ for (const coll of collections) {
1395
+ const success = collectionsRemoveContext(coll.name, '');
1396
+ if (success) {
1397
+ deletedCount++;
1398
+ }
1399
+ }
1400
+ return deletedCount;
1401
+ }
1402
+ /**
1403
+ * List all contexts, grouped by collection.
1404
+ * Returns contexts ordered by collection name, then by path prefix length (longest first).
1405
+ */
1406
+ export function listPathContexts(db) {
1407
+ const allContexts = collectionsListAllContexts();
1408
+ // Convert to expected format and sort
1409
+ return allContexts.map(ctx => ({
1410
+ collection_name: ctx.collection,
1411
+ path_prefix: ctx.path,
1412
+ context: ctx.context,
1413
+ })).sort((a, b) => {
1414
+ // Sort by collection name first
1415
+ if (a.collection_name !== b.collection_name) {
1416
+ return a.collection_name.localeCompare(b.collection_name);
1417
+ }
1418
+ // Then by path prefix length (longest first)
1419
+ if (a.path_prefix.length !== b.path_prefix.length) {
1420
+ return b.path_prefix.length - a.path_prefix.length;
1421
+ }
1422
+ // Then alphabetically
1423
+ return a.path_prefix.localeCompare(b.path_prefix);
1424
+ });
1425
+ }
1426
+ /**
1427
+ * Get all collections (name only - from YAML config).
1428
+ */
1429
+ export function getAllCollections(db) {
1430
+ const collections = collectionsListCollections();
1431
+ return collections.map(c => ({ name: c.name }));
1432
+ }
1433
+ /**
1434
+ * Check which collections don't have any context defined.
1435
+ * Returns collections that have no context entries at all (not even root context).
1436
+ */
1437
+ export function getCollectionsWithoutContext(db) {
1438
+ // Get all collections from YAML config
1439
+ const yamlCollections = collectionsListCollections();
1440
+ // Filter to those without context
1441
+ const collectionsWithoutContext = [];
1442
+ for (const coll of yamlCollections) {
1443
+ // Check if collection has any context
1444
+ if (!coll.context || Object.keys(coll.context).length === 0) {
1445
+ // Get doc count from database
1446
+ const stats = db.prepare(`
1447
+ SELECT COUNT(d.id) as doc_count
1448
+ FROM documents d
1449
+ WHERE d.collection = ? AND d.active = 1
1450
+ `).get(coll.name);
1451
+ collectionsWithoutContext.push({
1452
+ name: coll.name,
1453
+ pwd: coll.path,
1454
+ doc_count: stats?.doc_count || 0,
1455
+ });
1456
+ }
1457
+ }
1458
+ return collectionsWithoutContext.sort((a, b) => a.name.localeCompare(b.name));
1459
+ }
1460
+ /**
1461
+ * Get top-level directories in a collection that don't have context.
1462
+ * Useful for suggesting where context might be needed.
1463
+ */
1464
+ export function getTopLevelPathsWithoutContext(db, collectionName) {
1465
+ // Get all paths in the collection from database
1466
+ const paths = db.prepare(`
1467
+ SELECT DISTINCT path FROM documents
1468
+ WHERE collection = ? AND active = 1
1469
+ `).all(collectionName);
1470
+ // Get existing contexts for this collection from YAML
1471
+ const yamlColl = getCollection(collectionName);
1472
+ if (!yamlColl)
1473
+ return [];
1474
+ const contextPrefixes = new Set();
1475
+ if (yamlColl.context) {
1476
+ for (const prefix of Object.keys(yamlColl.context)) {
1477
+ contextPrefixes.add(prefix);
1478
+ }
1479
+ }
1480
+ // Extract top-level directories (first path component)
1481
+ const topLevelDirs = new Set();
1482
+ for (const { path } of paths) {
1483
+ const parts = path.split('/').filter(Boolean);
1484
+ if (parts.length > 1) {
1485
+ const dir = parts[0];
1486
+ if (dir)
1487
+ topLevelDirs.add(dir);
1488
+ }
1489
+ }
1490
+ // Filter out directories that already have context (exact or parent)
1491
+ const missing = [];
1492
+ for (const dir of topLevelDirs) {
1493
+ let hasContext = false;
1494
+ // Check if this dir or any parent has context
1495
+ for (const prefix of contextPrefixes) {
1496
+ if (prefix === '' || prefix === dir || dir.startsWith(prefix + '/')) {
1497
+ hasContext = true;
1498
+ break;
1499
+ }
1500
+ }
1501
+ if (!hasContext) {
1502
+ missing.push(dir);
1503
+ }
1504
+ }
1505
+ return missing.sort();
1506
+ }
1507
+ // =============================================================================
1508
+ // FTS Search
1509
+ // =============================================================================
1510
+ function sanitizeFTS5Term(term) {
1511
+ return term.replace(/[^\p{L}\p{N}']/gu, '').toLowerCase();
1512
+ }
1513
+ function buildFTS5Query(query) {
1514
+ const terms = query.split(/\s+/)
1515
+ .map(t => sanitizeFTS5Term(t))
1516
+ .filter(t => t.length > 0);
1517
+ if (terms.length === 0)
1518
+ return null;
1519
+ if (terms.length === 1)
1520
+ return `"${terms[0]}"*`;
1521
+ return terms.map(t => `"${t}"*`).join(' AND ');
1522
+ }
1523
+ export function searchFTS(db, query, limit = 20, collectionName) {
1524
+ const ftsQuery = buildFTS5Query(query);
1525
+ if (!ftsQuery)
1526
+ return [];
1527
+ let sql = `
1528
+ SELECT
1529
+ 'qmd://' || d.collection || '/' || d.path as filepath,
1530
+ d.collection || '/' || d.path as display_path,
1531
+ d.title,
1532
+ content.doc as body,
1533
+ d.hash,
1534
+ bm25(documents_fts, 10.0, 1.0) as bm25_score
1535
+ FROM documents_fts f
1536
+ JOIN documents d ON d.id = f.rowid
1537
+ JOIN content ON content.hash = d.hash
1538
+ WHERE documents_fts MATCH ? AND d.active = 1
1539
+ `;
1540
+ const params = [ftsQuery];
1541
+ if (collectionName) {
1542
+ sql += ` AND d.collection = ?`;
1543
+ params.push(String(collectionName));
1544
+ }
1545
+ // bm25 lower is better; sort ascending.
1546
+ sql += ` ORDER BY bm25_score ASC LIMIT ?`;
1547
+ params.push(limit);
1548
+ const rows = db.prepare(sql).all(...params);
1549
+ return rows.map(row => {
1550
+ const collectionName = row.filepath.split('//')[1]?.split('/')[0] || "";
1551
+ // Convert bm25 (negative, lower is better) into a stable [0..1) score where higher is better.
1552
+ // FTS5 BM25 scores are negative (e.g., -10 is strong, -2 is weak).
1553
+ // |x| / (1 + |x|) maps: strong(-10)→0.91, medium(-2)→0.67, weak(-0.5)→0.33, none(0)→0.
1554
+ // Monotonic and query-independent — no per-query normalization needed.
1555
+ const score = Math.abs(row.bm25_score) / (1 + Math.abs(row.bm25_score));
1556
+ return {
1557
+ filepath: row.filepath,
1558
+ displayPath: row.display_path,
1559
+ title: row.title,
1560
+ hash: row.hash,
1561
+ docid: getDocid(row.hash),
1562
+ collectionName,
1563
+ modifiedAt: "", // Not available in FTS query
1564
+ bodyLength: row.body.length,
1565
+ body: row.body,
1566
+ context: getContextForFile(db, row.filepath),
1567
+ score,
1568
+ source: "fts",
1569
+ };
1570
+ });
1571
+ }
1572
+ // =============================================================================
1573
+ // Vector Search
1574
+ // =============================================================================
1575
+ export async function searchVec(db, query, model, limit = 20, collectionName, session, precomputedEmbedding) {
1576
+ const tableExists = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
1577
+ if (!tableExists)
1578
+ return [];
1579
+ const embedding = precomputedEmbedding ?? await getEmbedding(query, model, true, session);
1580
+ if (!embedding)
1581
+ return [];
1582
+ // IMPORTANT: We use a two-step query approach here because sqlite-vec virtual tables
1583
+ // hang indefinitely when combined with JOINs in the same query. Do NOT try to
1584
+ // "optimize" this by combining into a single query with JOINs - it will break.
1585
+ // See: https://github.com/tobi/qmd/pull/23
1586
+ // Step 1: Get vector matches from sqlite-vec (no JOINs allowed)
1587
+ const vecResults = db.prepare(`
1588
+ SELECT hash_seq, distance
1589
+ FROM vectors_vec
1590
+ WHERE embedding MATCH ? AND k = ?
1591
+ `).all(new Float32Array(embedding), limit * 3);
1592
+ if (vecResults.length === 0)
1593
+ return [];
1594
+ // Step 2: Get chunk info and document data
1595
+ const hashSeqs = vecResults.map(r => r.hash_seq);
1596
+ const distanceMap = new Map(vecResults.map(r => [r.hash_seq, r.distance]));
1597
+ // Build query for document lookup
1598
+ const placeholders = hashSeqs.map(() => '?').join(',');
1599
+ let docSql = `
1600
+ SELECT
1601
+ cv.hash || '_' || cv.seq as hash_seq,
1602
+ cv.hash,
1603
+ cv.pos,
1604
+ 'qmd://' || d.collection || '/' || d.path as filepath,
1605
+ d.collection || '/' || d.path as display_path,
1606
+ d.title,
1607
+ content.doc as body
1608
+ FROM content_vectors cv
1609
+ JOIN documents d ON d.hash = cv.hash AND d.active = 1
1610
+ JOIN content ON content.hash = d.hash
1611
+ WHERE cv.hash || '_' || cv.seq IN (${placeholders})
1612
+ `;
1613
+ const params = [...hashSeqs];
1614
+ if (collectionName) {
1615
+ docSql += ` AND d.collection = ?`;
1616
+ params.push(collectionName);
1617
+ }
1618
+ const docRows = db.prepare(docSql).all(...params);
1619
+ // Combine with distances and dedupe by filepath
1620
+ const seen = new Map();
1621
+ for (const row of docRows) {
1622
+ const distance = distanceMap.get(row.hash_seq) ?? 1;
1623
+ const existing = seen.get(row.filepath);
1624
+ if (!existing || distance < existing.bestDist) {
1625
+ seen.set(row.filepath, { row, bestDist: distance });
1626
+ }
1627
+ }
1628
+ return Array.from(seen.values())
1629
+ .sort((a, b) => a.bestDist - b.bestDist)
1630
+ .slice(0, limit)
1631
+ .map(({ row, bestDist }) => {
1632
+ const collectionName = row.filepath.split('//')[1]?.split('/')[0] || "";
1633
+ return {
1634
+ filepath: row.filepath,
1635
+ displayPath: row.display_path,
1636
+ title: row.title,
1637
+ hash: row.hash,
1638
+ docid: getDocid(row.hash),
1639
+ collectionName,
1640
+ modifiedAt: "", // Not available in vec query
1641
+ bodyLength: row.body.length,
1642
+ body: row.body,
1643
+ context: getContextForFile(db, row.filepath),
1644
+ score: 1 - bestDist, // Cosine similarity = 1 - cosine distance
1645
+ source: "vec",
1646
+ chunkPos: row.pos,
1647
+ };
1648
+ });
1649
+ }
1650
+ // =============================================================================
1651
+ // Embeddings
1652
+ // =============================================================================
1653
+ async function getEmbedding(text, model, isQuery, session) {
1654
+ // Format text using the appropriate prompt template
1655
+ const formattedText = isQuery ? formatQueryForEmbedding(text) : formatDocForEmbedding(text);
1656
+ const result = session
1657
+ ? await session.embed(formattedText, { model, isQuery })
1658
+ : await getDefaultLlamaCpp().embed(formattedText, { model, isQuery });
1659
+ return result?.embedding || null;
1660
+ }
1661
+ /**
1662
+ * Get all unique content hashes that need embeddings (from active documents).
1663
+ * Returns hash, document body, and a sample path for display purposes.
1664
+ */
1665
+ export function getHashesForEmbedding(db) {
1666
+ return db.prepare(`
1667
+ SELECT d.hash, c.doc as body, MIN(d.path) as path
1668
+ FROM documents d
1669
+ JOIN content c ON d.hash = c.hash
1670
+ LEFT JOIN content_vectors v ON d.hash = v.hash AND v.seq = 0
1671
+ WHERE d.active = 1 AND v.hash IS NULL
1672
+ GROUP BY d.hash
1673
+ `).all();
1674
+ }
1675
+ /**
1676
+ * Clear all embeddings from the database (force re-index).
1677
+ * Deletes all rows from content_vectors and drops the vectors_vec table.
1678
+ */
1679
+ export function clearAllEmbeddings(db) {
1680
+ db.exec(`DELETE FROM content_vectors`);
1681
+ db.exec(`DROP TABLE IF EXISTS vectors_vec`);
1682
+ }
1683
+ /**
1684
+ * Insert a single embedding into both content_vectors and vectors_vec tables.
1685
+ * The hash_seq key is formatted as "hash_seq" for the vectors_vec table.
1686
+ */
1687
+ export function insertEmbedding(db, hash, seq, pos, embedding, model, embeddedAt) {
1688
+ const hashSeq = `${hash}_${seq}`;
1689
+ const insertVecStmt = db.prepare(`INSERT OR REPLACE INTO vectors_vec (hash_seq, embedding) VALUES (?, ?)`);
1690
+ const insertContentVectorStmt = db.prepare(`INSERT OR REPLACE INTO content_vectors (hash, seq, pos, model, embedded_at) VALUES (?, ?, ?, ?, ?)`);
1691
+ insertVecStmt.run(hashSeq, embedding);
1692
+ insertContentVectorStmt.run(hash, seq, pos, model, embeddedAt);
1693
+ }
1694
+ // =============================================================================
1695
+ // Query expansion
1696
+ // =============================================================================
1697
+ export async function expandQuery(query, model = DEFAULT_QUERY_MODEL, db) {
1698
+ // Check cache first — stored as JSON preserving types
1699
+ const cacheKey = getCacheKey("expandQuery", { query, model });
1700
+ const cached = getCachedResult(db, cacheKey);
1701
+ if (cached) {
1702
+ try {
1703
+ return JSON.parse(cached);
1704
+ }
1705
+ catch {
1706
+ // Old cache format (pre-typed, newline-separated text) — re-expand
1707
+ }
1708
+ }
1709
+ const llm = getDefaultLlamaCpp();
1710
+ // Note: LlamaCpp uses hardcoded model, model parameter is ignored
1711
+ const results = await llm.expandQuery(query);
1712
+ // Map Queryable[] → ExpandedQuery[] (same shape, decoupled from llm.ts internals).
1713
+ // Filter out entries that duplicate the original query text.
1714
+ const expanded = results
1715
+ .filter(r => r.text !== query)
1716
+ .map(r => ({ type: r.type, text: r.text }));
1717
+ if (expanded.length > 0) {
1718
+ setCachedResult(db, cacheKey, JSON.stringify(expanded));
1719
+ }
1720
+ return expanded;
1721
+ }
1722
+ // =============================================================================
1723
+ // Reranking
1724
+ // =============================================================================
1725
+ export async function rerank(query, documents, model = DEFAULT_RERANK_MODEL, db) {
1726
+ const cachedResults = new Map();
1727
+ const uncachedDocs = [];
1728
+ // Check cache for each document
1729
+ // Cache key includes chunk text — different queries can select different chunks
1730
+ // from the same file, and the reranker score depends on which chunk was sent.
1731
+ for (const doc of documents) {
1732
+ const cacheKey = getCacheKey("rerank", { query, file: doc.file, model, chunk: doc.text });
1733
+ const cached = getCachedResult(db, cacheKey);
1734
+ if (cached !== null) {
1735
+ cachedResults.set(doc.file, parseFloat(cached));
1736
+ }
1737
+ else {
1738
+ uncachedDocs.push({ file: doc.file, text: doc.text });
1739
+ }
1740
+ }
1741
+ // Rerank uncached documents using LlamaCpp
1742
+ if (uncachedDocs.length > 0) {
1743
+ const llm = getDefaultLlamaCpp();
1744
+ const rerankResult = await llm.rerank(query, uncachedDocs, { model });
1745
+ // Cache results — use original doc.text for cache key (result.file lacks chunk text)
1746
+ const textByFile = new Map(documents.map(d => [d.file, d.text]));
1747
+ for (const result of rerankResult.results) {
1748
+ const cacheKey = getCacheKey("rerank", { query, file: result.file, model, chunk: textByFile.get(result.file) || "" });
1749
+ setCachedResult(db, cacheKey, result.score.toString());
1750
+ cachedResults.set(result.file, result.score);
1751
+ }
1752
+ }
1753
+ // Return all results sorted by score
1754
+ return documents
1755
+ .map(doc => ({ file: doc.file, score: cachedResults.get(doc.file) || 0 }))
1756
+ .sort((a, b) => b.score - a.score);
1757
+ }
1758
+ // =============================================================================
1759
+ // Reciprocal Rank Fusion
1760
+ // =============================================================================
1761
+ export function reciprocalRankFusion(resultLists, weights = [], k = 60) {
1762
+ const scores = new Map();
1763
+ for (let listIdx = 0; listIdx < resultLists.length; listIdx++) {
1764
+ const list = resultLists[listIdx];
1765
+ if (!list)
1766
+ continue;
1767
+ const weight = weights[listIdx] ?? 1.0;
1768
+ for (let rank = 0; rank < list.length; rank++) {
1769
+ const result = list[rank];
1770
+ if (!result)
1771
+ continue;
1772
+ const rrfContribution = weight / (k + rank + 1);
1773
+ const existing = scores.get(result.file);
1774
+ if (existing) {
1775
+ existing.rrfScore += rrfContribution;
1776
+ existing.topRank = Math.min(existing.topRank, rank);
1777
+ }
1778
+ else {
1779
+ scores.set(result.file, {
1780
+ result,
1781
+ rrfScore: rrfContribution,
1782
+ topRank: rank,
1783
+ });
1784
+ }
1785
+ }
1786
+ }
1787
+ // Top-rank bonus
1788
+ for (const entry of scores.values()) {
1789
+ if (entry.topRank === 0) {
1790
+ entry.rrfScore += 0.05;
1791
+ }
1792
+ else if (entry.topRank <= 2) {
1793
+ entry.rrfScore += 0.02;
1794
+ }
1795
+ }
1796
+ return Array.from(scores.values())
1797
+ .sort((a, b) => b.rrfScore - a.rrfScore)
1798
+ .map(e => ({ ...e.result, score: e.rrfScore }));
1799
+ }
1800
+ /**
1801
+ * Find a document by filename/path, docid (#hash), or with fuzzy matching.
1802
+ * Returns document metadata without body by default.
1803
+ *
1804
+ * Supports:
1805
+ * - Virtual paths: qmd://collection/path/to/file.md
1806
+ * - Absolute paths: /path/to/file.md
1807
+ * - Relative paths: path/to/file.md
1808
+ * - Short docid: #abc123 (first 6 chars of hash)
1809
+ */
1810
+ export function findDocument(db, filename, options = {}) {
1811
+ let filepath = filename;
1812
+ const colonMatch = filepath.match(/:(\d+)$/);
1813
+ if (colonMatch) {
1814
+ filepath = filepath.slice(0, -colonMatch[0].length);
1815
+ }
1816
+ // Check if this is a docid lookup (#abc123, abc123, "#abc123", "abc123", etc.)
1817
+ if (isDocid(filepath)) {
1818
+ const docidMatch = findDocumentByDocid(db, filepath);
1819
+ if (docidMatch) {
1820
+ filepath = docidMatch.filepath;
1821
+ }
1822
+ else {
1823
+ return { error: "not_found", query: filename, similarFiles: [] };
1824
+ }
1825
+ }
1826
+ if (filepath.startsWith('~/')) {
1827
+ filepath = homedir() + filepath.slice(1);
1828
+ }
1829
+ const bodyCol = options.includeBody ? `, content.doc as body` : ``;
1830
+ // Build computed columns
1831
+ // Note: absoluteFilepath is computed from YAML collections after query
1832
+ const selectCols = `
1833
+ 'qmd://' || d.collection || '/' || d.path as virtual_path,
1834
+ d.collection || '/' || d.path as display_path,
1835
+ d.title,
1836
+ d.hash,
1837
+ d.collection,
1838
+ d.modified_at,
1839
+ LENGTH(content.doc) as body_length
1840
+ ${bodyCol}
1841
+ `;
1842
+ // Try to match by virtual path first
1843
+ let doc = db.prepare(`
1844
+ SELECT ${selectCols}
1845
+ FROM documents d
1846
+ JOIN content ON content.hash = d.hash
1847
+ WHERE 'qmd://' || d.collection || '/' || d.path = ? AND d.active = 1
1848
+ `).get(filepath);
1849
+ // Try fuzzy match by virtual path
1850
+ if (!doc) {
1851
+ doc = db.prepare(`
1852
+ SELECT ${selectCols}
1853
+ FROM documents d
1854
+ JOIN content ON content.hash = d.hash
1855
+ WHERE 'qmd://' || d.collection || '/' || d.path LIKE ? AND d.active = 1
1856
+ LIMIT 1
1857
+ `).get(`%${filepath}`);
1858
+ }
1859
+ // Try to match by absolute path (requires looking up collection paths from YAML)
1860
+ if (!doc && !filepath.startsWith('qmd://')) {
1861
+ const collections = collectionsListCollections();
1862
+ for (const coll of collections) {
1863
+ let relativePath = null;
1864
+ // If filepath is absolute and starts with collection path, extract relative part
1865
+ if (filepath.startsWith(coll.path + '/')) {
1866
+ relativePath = filepath.slice(coll.path.length + 1);
1867
+ }
1868
+ // Otherwise treat filepath as relative to collection
1869
+ else if (!filepath.startsWith('/')) {
1870
+ relativePath = filepath;
1871
+ }
1872
+ if (relativePath) {
1873
+ doc = db.prepare(`
1874
+ SELECT ${selectCols}
1875
+ FROM documents d
1876
+ JOIN content ON content.hash = d.hash
1877
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
1878
+ `).get(coll.name, relativePath);
1879
+ if (doc)
1880
+ break;
1881
+ }
1882
+ }
1883
+ }
1884
+ if (!doc) {
1885
+ const similar = findSimilarFiles(db, filepath, 5, 5);
1886
+ return { error: "not_found", query: filename, similarFiles: similar };
1887
+ }
1888
+ // Get context using virtual path
1889
+ const virtualPath = doc.virtual_path || `qmd://${doc.collection}/${doc.display_path}`;
1890
+ const context = getContextForFile(db, virtualPath);
1891
+ return {
1892
+ filepath: virtualPath,
1893
+ displayPath: doc.display_path,
1894
+ title: doc.title,
1895
+ context,
1896
+ hash: doc.hash,
1897
+ docid: getDocid(doc.hash),
1898
+ collectionName: doc.collection,
1899
+ modifiedAt: doc.modified_at,
1900
+ bodyLength: doc.body_length,
1901
+ ...(options.includeBody && doc.body !== undefined && { body: doc.body }),
1902
+ };
1903
+ }
1904
+ /**
1905
+ * Get the body content for a document
1906
+ * Optionally slice by line range
1907
+ */
1908
+ export function getDocumentBody(db, doc, fromLine, maxLines) {
1909
+ const filepath = doc.filepath;
1910
+ // Try to resolve document by filepath (absolute or virtual)
1911
+ let row = null;
1912
+ // Try virtual path first
1913
+ if (filepath.startsWith('qmd://')) {
1914
+ row = db.prepare(`
1915
+ SELECT content.doc as body
1916
+ FROM documents d
1917
+ JOIN content ON content.hash = d.hash
1918
+ WHERE 'qmd://' || d.collection || '/' || d.path = ? AND d.active = 1
1919
+ `).get(filepath);
1920
+ }
1921
+ // Try absolute path by looking up in YAML collections
1922
+ if (!row) {
1923
+ const collections = collectionsListCollections();
1924
+ for (const coll of collections) {
1925
+ if (filepath.startsWith(coll.path + '/')) {
1926
+ const relativePath = filepath.slice(coll.path.length + 1);
1927
+ row = db.prepare(`
1928
+ SELECT content.doc as body
1929
+ FROM documents d
1930
+ JOIN content ON content.hash = d.hash
1931
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
1932
+ `).get(coll.name, relativePath);
1933
+ if (row)
1934
+ break;
1935
+ }
1936
+ }
1937
+ }
1938
+ if (!row)
1939
+ return null;
1940
+ let body = row.body;
1941
+ if (fromLine !== undefined || maxLines !== undefined) {
1942
+ const lines = body.split('\n');
1943
+ const start = (fromLine || 1) - 1;
1944
+ const end = maxLines !== undefined ? start + maxLines : lines.length;
1945
+ body = lines.slice(start, end).join('\n');
1946
+ }
1947
+ return body;
1948
+ }
1949
+ /**
1950
+ * Find multiple documents by glob pattern or comma-separated list
1951
+ * Returns documents without body by default (use getDocumentBody to load)
1952
+ */
1953
+ export function findDocuments(db, pattern, options = {}) {
1954
+ const isCommaSeparated = pattern.includes(',') && !pattern.includes('*') && !pattern.includes('?');
1955
+ const errors = [];
1956
+ const maxBytes = options.maxBytes ?? DEFAULT_MULTI_GET_MAX_BYTES;
1957
+ const bodyCol = options.includeBody ? `, content.doc as body` : ``;
1958
+ const selectCols = `
1959
+ 'qmd://' || d.collection || '/' || d.path as virtual_path,
1960
+ d.collection || '/' || d.path as display_path,
1961
+ d.title,
1962
+ d.hash,
1963
+ d.collection,
1964
+ d.modified_at,
1965
+ LENGTH(content.doc) as body_length
1966
+ ${bodyCol}
1967
+ `;
1968
+ let fileRows;
1969
+ if (isCommaSeparated) {
1970
+ const names = pattern.split(',').map(s => s.trim()).filter(Boolean);
1971
+ fileRows = [];
1972
+ for (const name of names) {
1973
+ let doc = db.prepare(`
1974
+ SELECT ${selectCols}
1975
+ FROM documents d
1976
+ JOIN content ON content.hash = d.hash
1977
+ WHERE 'qmd://' || d.collection || '/' || d.path = ? AND d.active = 1
1978
+ `).get(name);
1979
+ if (!doc) {
1980
+ doc = db.prepare(`
1981
+ SELECT ${selectCols}
1982
+ FROM documents d
1983
+ JOIN content ON content.hash = d.hash
1984
+ WHERE 'qmd://' || d.collection || '/' || d.path LIKE ? AND d.active = 1
1985
+ LIMIT 1
1986
+ `).get(`%${name}`);
1987
+ }
1988
+ if (doc) {
1989
+ fileRows.push(doc);
1990
+ }
1991
+ else {
1992
+ const similar = findSimilarFiles(db, name, 5, 3);
1993
+ let msg = `File not found: ${name}`;
1994
+ if (similar.length > 0) {
1995
+ msg += ` (did you mean: ${similar.join(', ')}?)`;
1996
+ }
1997
+ errors.push(msg);
1998
+ }
1999
+ }
2000
+ }
2001
+ else {
2002
+ // Glob pattern match
2003
+ const matched = matchFilesByGlob(db, pattern);
2004
+ if (matched.length === 0) {
2005
+ errors.push(`No files matched pattern: ${pattern}`);
2006
+ return { docs: [], errors };
2007
+ }
2008
+ const virtualPaths = matched.map(m => m.filepath);
2009
+ const placeholders = virtualPaths.map(() => '?').join(',');
2010
+ fileRows = db.prepare(`
2011
+ SELECT ${selectCols}
2012
+ FROM documents d
2013
+ JOIN content ON content.hash = d.hash
2014
+ WHERE 'qmd://' || d.collection || '/' || d.path IN (${placeholders}) AND d.active = 1
2015
+ `).all(...virtualPaths);
2016
+ }
2017
+ const results = [];
2018
+ for (const row of fileRows) {
2019
+ // Get context using virtual path
2020
+ const virtualPath = row.virtual_path || `qmd://${row.collection}/${row.display_path}`;
2021
+ const context = getContextForFile(db, virtualPath);
2022
+ if (row.body_length > maxBytes) {
2023
+ results.push({
2024
+ doc: { filepath: virtualPath, displayPath: row.display_path },
2025
+ skipped: true,
2026
+ skipReason: `File too large (${Math.round(row.body_length / 1024)}KB > ${Math.round(maxBytes / 1024)}KB)`,
2027
+ });
2028
+ continue;
2029
+ }
2030
+ results.push({
2031
+ doc: {
2032
+ filepath: virtualPath,
2033
+ displayPath: row.display_path,
2034
+ title: row.title || row.display_path.split('/').pop() || row.display_path,
2035
+ context,
2036
+ hash: row.hash,
2037
+ docid: getDocid(row.hash),
2038
+ collectionName: row.collection,
2039
+ modifiedAt: row.modified_at,
2040
+ bodyLength: row.body_length,
2041
+ ...(options.includeBody && row.body !== undefined && { body: row.body }),
2042
+ },
2043
+ skipped: false,
2044
+ });
2045
+ }
2046
+ return { docs: results, errors };
2047
+ }
2048
+ // =============================================================================
2049
+ // Status
2050
+ // =============================================================================
2051
+ export function getStatus(db) {
2052
+ // Load collections from YAML
2053
+ const yamlCollections = collectionsListCollections();
2054
+ // Get document counts and last update times for each collection
2055
+ const collections = yamlCollections.map(col => {
2056
+ const stats = db.prepare(`
2057
+ SELECT
2058
+ COUNT(*) as active_count,
2059
+ MAX(modified_at) as last_doc_update
2060
+ FROM documents
2061
+ WHERE collection = ? AND active = 1
2062
+ `).get(col.name);
2063
+ return {
2064
+ name: col.name,
2065
+ path: col.path,
2066
+ pattern: col.pattern,
2067
+ documents: stats.active_count,
2068
+ lastUpdated: stats.last_doc_update || new Date().toISOString(),
2069
+ };
2070
+ });
2071
+ // Sort by last update time (most recent first)
2072
+ collections.sort((a, b) => {
2073
+ if (!a.lastUpdated)
2074
+ return 1;
2075
+ if (!b.lastUpdated)
2076
+ return -1;
2077
+ return new Date(b.lastUpdated).getTime() - new Date(a.lastUpdated).getTime();
2078
+ });
2079
+ const totalDocs = db.prepare(`SELECT COUNT(*) as c FROM documents WHERE active = 1`).get().c;
2080
+ const needsEmbedding = getHashesNeedingEmbedding(db);
2081
+ const hasVectors = !!db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
2082
+ return {
2083
+ totalDocuments: totalDocs,
2084
+ needsEmbedding,
2085
+ hasVectorIndex: hasVectors,
2086
+ collections,
2087
+ };
2088
+ }
2089
+ export function extractSnippet(body, query, maxLen = 500, chunkPos, chunkLen) {
2090
+ const totalLines = body.split('\n').length;
2091
+ let searchBody = body;
2092
+ let lineOffset = 0;
2093
+ if (chunkPos && chunkPos > 0) {
2094
+ // Search within the chunk region, with some padding for context
2095
+ // Use provided chunkLen or fall back to max chunk size (covers variable-length chunks)
2096
+ const searchLen = chunkLen || CHUNK_SIZE_CHARS;
2097
+ const contextStart = Math.max(0, chunkPos - 100);
2098
+ const contextEnd = Math.min(body.length, chunkPos + searchLen + 100);
2099
+ searchBody = body.slice(contextStart, contextEnd);
2100
+ if (contextStart > 0) {
2101
+ lineOffset = body.slice(0, contextStart).split('\n').length - 1;
2102
+ }
2103
+ }
2104
+ const lines = searchBody.split('\n');
2105
+ const queryTerms = query.toLowerCase().split(/\s+/).filter(t => t.length > 0);
2106
+ let bestLine = 0, bestScore = -1;
2107
+ for (let i = 0; i < lines.length; i++) {
2108
+ const lineLower = (lines[i] ?? "").toLowerCase();
2109
+ let score = 0;
2110
+ for (const term of queryTerms) {
2111
+ if (lineLower.includes(term))
2112
+ score++;
2113
+ }
2114
+ if (score > bestScore) {
2115
+ bestScore = score;
2116
+ bestLine = i;
2117
+ }
2118
+ }
2119
+ const start = Math.max(0, bestLine - 1);
2120
+ const end = Math.min(lines.length, bestLine + 3);
2121
+ const snippetLines = lines.slice(start, end);
2122
+ let snippetText = snippetLines.join('\n');
2123
+ // If we focused on a chunk window and it produced an empty/whitespace-only snippet,
2124
+ // fall back to a full-document snippet so we always show something useful.
2125
+ if (chunkPos && chunkPos > 0 && snippetText.trim().length === 0) {
2126
+ return extractSnippet(body, query, maxLen, undefined);
2127
+ }
2128
+ if (snippetText.length > maxLen)
2129
+ snippetText = snippetText.substring(0, maxLen - 3) + "...";
2130
+ const absoluteStart = lineOffset + start + 1; // 1-indexed
2131
+ const snippetLineCount = snippetLines.length;
2132
+ const linesBefore = absoluteStart - 1;
2133
+ const linesAfter = totalLines - (absoluteStart + snippetLineCount - 1);
2134
+ // Format with diff-style header: @@ -start,count @@ (linesBefore before, linesAfter after)
2135
+ const header = `@@ -${absoluteStart},${snippetLineCount} @@ (${linesBefore} before, ${linesAfter} after)`;
2136
+ const snippet = `${header}\n${snippetText}`;
2137
+ return {
2138
+ line: lineOffset + bestLine + 1,
2139
+ snippet,
2140
+ linesBefore,
2141
+ linesAfter,
2142
+ snippetLines: snippetLineCount,
2143
+ };
2144
+ }
2145
+ // =============================================================================
2146
+ // Shared helpers (used by both CLI and MCP)
2147
+ // =============================================================================
2148
+ /**
2149
+ * Add line numbers to text content.
2150
+ * Each line becomes: "{lineNum}: {content}"
2151
+ */
2152
+ export function addLineNumbers(text, startLine = 1) {
2153
+ const lines = text.split('\n');
2154
+ return lines.map((line, i) => `${startLine + i}: ${line}`).join('\n');
2155
+ }
2156
+ /**
2157
+ * Hybrid search: BM25 + vector + query expansion + RRF + chunked reranking.
2158
+ *
2159
+ * Pipeline:
2160
+ * 1. BM25 probe → skip expansion if strong signal
2161
+ * 2. expandQuery() → typed query variants (lex/vec/hyde)
2162
+ * 3. Type-routed search: original→vector, lex→FTS, vec/hyde→vector
2163
+ * 4. RRF fusion → slice to candidateLimit
2164
+ * 5. chunkDocument() + keyword-best-chunk selection
2165
+ * 6. rerank on chunks (NOT full bodies — O(tokens) trap)
2166
+ * 7. Position-aware score blending (RRF rank × reranker score)
2167
+ * 8. Dedup by file, filter by minScore, slice to limit
2168
+ */
2169
+ export async function hybridQuery(store, query, options) {
2170
+ const limit = options?.limit ?? 10;
2171
+ const minScore = options?.minScore ?? 0;
2172
+ const candidateLimit = options?.candidateLimit ?? RERANK_CANDIDATE_LIMIT;
2173
+ const collection = options?.collection;
2174
+ const hooks = options?.hooks;
2175
+ const rankedLists = [];
2176
+ const docidMap = new Map(); // filepath -> docid
2177
+ const hasVectors = !!store.db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
2178
+ // Step 1: BM25 probe — strong signal skips expensive LLM expansion
2179
+ // Pass collection directly into FTS query (filter at SQL level, not post-hoc)
2180
+ const initialFts = store.searchFTS(query, 20, collection);
2181
+ const topScore = initialFts[0]?.score ?? 0;
2182
+ const secondScore = initialFts[1]?.score ?? 0;
2183
+ const hasStrongSignal = initialFts.length > 0
2184
+ && topScore >= STRONG_SIGNAL_MIN_SCORE
2185
+ && (topScore - secondScore) >= STRONG_SIGNAL_MIN_GAP;
2186
+ if (hasStrongSignal)
2187
+ hooks?.onStrongSignal?.(topScore);
2188
+ // Step 2: Expand query (or skip if strong signal)
2189
+ const expanded = hasStrongSignal
2190
+ ? []
2191
+ : await store.expandQuery(query);
2192
+ hooks?.onExpand?.(query, expanded);
2193
+ // Seed with initial FTS results (avoid re-running original query FTS)
2194
+ if (initialFts.length > 0) {
2195
+ for (const r of initialFts)
2196
+ docidMap.set(r.filepath, r.docid);
2197
+ rankedLists.push(initialFts.map(r => ({
2198
+ file: r.filepath, displayPath: r.displayPath,
2199
+ title: r.title, body: r.body || "", score: r.score,
2200
+ })));
2201
+ }
2202
+ // Step 3: Route searches by query type
2203
+ //
2204
+ // Strategy: run all FTS queries immediately (they're sync/instant), then
2205
+ // batch-embed all vector queries in one embedBatch() call, then run
2206
+ // sqlite-vec lookups with pre-computed embeddings.
2207
+ // 3a: Run FTS for all lex expansions right away (no LLM needed)
2208
+ for (const q of expanded) {
2209
+ if (q.type === 'lex') {
2210
+ const ftsResults = store.searchFTS(q.text, 20, collection);
2211
+ if (ftsResults.length > 0) {
2212
+ for (const r of ftsResults)
2213
+ docidMap.set(r.filepath, r.docid);
2214
+ rankedLists.push(ftsResults.map(r => ({
2215
+ file: r.filepath, displayPath: r.displayPath,
2216
+ title: r.title, body: r.body || "", score: r.score,
2217
+ })));
2218
+ }
2219
+ }
2220
+ }
2221
+ // 3b: Collect all texts that need vector search (original query + vec/hyde expansions)
2222
+ if (hasVectors) {
2223
+ const vecQueries = [
2224
+ { text: query, isOriginal: true },
2225
+ ];
2226
+ for (const q of expanded) {
2227
+ if (q.type === 'vec' || q.type === 'hyde') {
2228
+ vecQueries.push({ text: q.text, isOriginal: false });
2229
+ }
2230
+ }
2231
+ // Batch embed all vector queries in a single call
2232
+ const llm = getDefaultLlamaCpp();
2233
+ const textsToEmbed = vecQueries.map(q => formatQueryForEmbedding(q.text));
2234
+ const embeddings = await llm.embedBatch(textsToEmbed);
2235
+ // Run sqlite-vec lookups with pre-computed embeddings
2236
+ for (let i = 0; i < vecQueries.length; i++) {
2237
+ const embedding = embeddings[i]?.embedding;
2238
+ if (!embedding)
2239
+ continue;
2240
+ const vecResults = await store.searchVec(vecQueries[i].text, DEFAULT_EMBED_MODEL, 20, collection, undefined, embedding);
2241
+ if (vecResults.length > 0) {
2242
+ for (const r of vecResults)
2243
+ docidMap.set(r.filepath, r.docid);
2244
+ rankedLists.push(vecResults.map(r => ({
2245
+ file: r.filepath, displayPath: r.displayPath,
2246
+ title: r.title, body: r.body || "", score: r.score,
2247
+ })));
2248
+ }
2249
+ }
2250
+ }
2251
+ // Step 4: RRF fusion — first 2 lists (original FTS + first vec) get 2x weight
2252
+ const weights = rankedLists.map((_, i) => i < 2 ? 2.0 : 1.0);
2253
+ const fused = reciprocalRankFusion(rankedLists, weights);
2254
+ const candidates = fused.slice(0, candidateLimit);
2255
+ if (candidates.length === 0)
2256
+ return [];
2257
+ // Step 5: Chunk documents, pick best chunk per doc for reranking.
2258
+ // Reranking full bodies is O(tokens) — the critical perf lesson that motivated this refactor.
2259
+ const queryTerms = query.toLowerCase().split(/\s+/).filter(t => t.length > 2);
2260
+ const chunksToRerank = [];
2261
+ const docChunkMap = new Map();
2262
+ for (const cand of candidates) {
2263
+ const chunks = chunkDocument(cand.body);
2264
+ if (chunks.length === 0)
2265
+ continue;
2266
+ // Pick chunk with most keyword overlap (fallback: first chunk)
2267
+ let bestIdx = 0;
2268
+ let bestScore = -1;
2269
+ for (let i = 0; i < chunks.length; i++) {
2270
+ const chunkLower = chunks[i].text.toLowerCase();
2271
+ const score = queryTerms.reduce((acc, term) => acc + (chunkLower.includes(term) ? 1 : 0), 0);
2272
+ if (score > bestScore) {
2273
+ bestScore = score;
2274
+ bestIdx = i;
2275
+ }
2276
+ }
2277
+ chunksToRerank.push({ file: cand.file, text: chunks[bestIdx].text });
2278
+ docChunkMap.set(cand.file, { chunks, bestIdx });
2279
+ }
2280
+ // Step 6: Rerank chunks (NOT full bodies)
2281
+ hooks?.onRerankStart?.(chunksToRerank.length);
2282
+ const reranked = await store.rerank(query, chunksToRerank);
2283
+ hooks?.onRerankDone?.();
2284
+ // Step 7: Blend RRF position score with reranker score
2285
+ // Position-aware weights: top retrieval results get more protection from reranker disagreement
2286
+ const candidateMap = new Map(candidates.map(c => [c.file, {
2287
+ displayPath: c.displayPath, title: c.title, body: c.body,
2288
+ }]));
2289
+ const rrfRankMap = new Map(candidates.map((c, i) => [c.file, i + 1]));
2290
+ const blended = reranked.map(r => {
2291
+ const rrfRank = rrfRankMap.get(r.file) || candidateLimit;
2292
+ let rrfWeight;
2293
+ if (rrfRank <= 3)
2294
+ rrfWeight = 0.75;
2295
+ else if (rrfRank <= 10)
2296
+ rrfWeight = 0.60;
2297
+ else
2298
+ rrfWeight = 0.40;
2299
+ const rrfScore = 1 / rrfRank;
2300
+ const blendedScore = rrfWeight * rrfScore + (1 - rrfWeight) * r.score;
2301
+ const candidate = candidateMap.get(r.file);
2302
+ const chunkInfo = docChunkMap.get(r.file);
2303
+ const bestIdx = chunkInfo?.bestIdx ?? 0;
2304
+ const bestChunk = chunkInfo?.chunks[bestIdx]?.text || candidate?.body || "";
2305
+ const bestChunkPos = chunkInfo?.chunks[bestIdx]?.pos || 0;
2306
+ return {
2307
+ file: r.file,
2308
+ displayPath: candidate?.displayPath || "",
2309
+ title: candidate?.title || "",
2310
+ body: candidate?.body || "",
2311
+ bestChunk,
2312
+ bestChunkPos,
2313
+ score: blendedScore,
2314
+ context: store.getContextForFile(r.file),
2315
+ docid: docidMap.get(r.file) || "",
2316
+ };
2317
+ }).sort((a, b) => b.score - a.score);
2318
+ // Step 8: Dedup by file (safety net — prevents duplicate output)
2319
+ const seenFiles = new Set();
2320
+ return blended
2321
+ .filter(r => {
2322
+ if (seenFiles.has(r.file))
2323
+ return false;
2324
+ seenFiles.add(r.file);
2325
+ return true;
2326
+ })
2327
+ .filter(r => r.score >= minScore)
2328
+ .slice(0, limit);
2329
+ }
2330
+ /**
2331
+ * Vector-only semantic search with query expansion.
2332
+ *
2333
+ * Pipeline:
2334
+ * 1. expandQuery() → typed variants, filter to vec/hyde only (lex irrelevant here)
2335
+ * 2. searchVec() for original + vec/hyde variants (sequential — node-llama-cpp embed limitation)
2336
+ * 3. Dedup by filepath (keep max score)
2337
+ * 4. Sort by score descending, filter by minScore, slice to limit
2338
+ */
2339
+ export async function vectorSearchQuery(store, query, options) {
2340
+ const limit = options?.limit ?? 10;
2341
+ const minScore = options?.minScore ?? 0.3;
2342
+ const collection = options?.collection;
2343
+ const hasVectors = !!store.db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
2344
+ if (!hasVectors)
2345
+ return [];
2346
+ // Expand query — filter to vec/hyde only (lex queries target FTS, not vector)
2347
+ const allExpanded = await store.expandQuery(query);
2348
+ const vecExpanded = allExpanded.filter(q => q.type !== 'lex');
2349
+ options?.hooks?.onExpand?.(query, vecExpanded);
2350
+ // Run original + vec/hyde expanded through vector, sequentially — concurrent embed() hangs
2351
+ const queryTexts = [query, ...vecExpanded.map(q => q.text)];
2352
+ const allResults = new Map();
2353
+ for (const q of queryTexts) {
2354
+ const vecResults = await store.searchVec(q, DEFAULT_EMBED_MODEL, limit, collection);
2355
+ for (const r of vecResults) {
2356
+ const existing = allResults.get(r.filepath);
2357
+ if (!existing || r.score > existing.score) {
2358
+ allResults.set(r.filepath, {
2359
+ file: r.filepath,
2360
+ displayPath: r.displayPath,
2361
+ title: r.title,
2362
+ body: r.body || "",
2363
+ score: r.score,
2364
+ context: store.getContextForFile(r.filepath),
2365
+ docid: r.docid,
2366
+ });
2367
+ }
2368
+ }
2369
+ }
2370
+ return Array.from(allResults.values())
2371
+ .sort((a, b) => b.score - a.score)
2372
+ .filter(r => r.score >= minScore)
2373
+ .slice(0, limit);
2374
+ }