@ambicuity/kindx 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2787 @@
1
+ /**
2
+ * KINDX Repository - 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 "./runtime.js";
14
+ import picomatch from "picomatch";
15
+ import { createHash } from "crypto";
16
+ import { realpathSync, mkdirSync } from "node:fs";
17
+ import { getDefaultLlamaCpp, formatQueryForEmbedding, formatDocForEmbedding, } from "./inference.js";
18
+ import { addContext as collectionsAddContext, removeContext as collectionsRemoveContext, listAllContexts as collectionsListAllContexts, getCollection, listCollections as collectionsListCollections, removeCollection as collectionsRemoveCollection, renameCollection as collectionsRenameCollection, setGlobalContext, loadConfig as collectionsLoadConfig, } from "./catalogs.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 kindx.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, "kindx");
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 kindx:// format.
358
+ * Only handles paths that are already explicitly virtual:
359
+ * - kindx://collection/path.md (already normalized)
360
+ * - kindx:////collection/path.md (extra slashes - normalize)
361
+ * - //collection/path.md (missing kindx: 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 kindx:// with extra slashes: kindx:////collection/path -> kindx://collection/path
370
+ if (path.startsWith('kindx:')) {
371
+ // Remove kindx: prefix and normalize slashes
372
+ path = path.slice(6);
373
+ // Remove leading slashes and re-add exactly two
374
+ path = path.replace(/^\/+/, '');
375
+ return `kindx://${path}`;
376
+ }
377
+ // Handle //collection/path (missing kindx: prefix)
378
+ if (path.startsWith('//')) {
379
+ path = path.replace(/^\/+/, '');
380
+ return `kindx://${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 "kindx://collection-name/path/to/file.md"
387
+ * into its components.
388
+ * Also supports collection root: "kindx://collection-name/" or "kindx://collection-name"
389
+ */
390
+ export function parseVirtualPath(virtualPath) {
391
+ // Normalize the path first
392
+ const normalized = normalizeVirtualPath(virtualPath);
393
+ // Match: kindx://collection-name[/optional-path]
394
+ // Allows: kindx://name, kindx://name/, kindx://name/path
395
+ const match = normalized.match(/^kindx:\/\/([^\/]+)\/?(.*)$/);
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 `kindx://${collectionName}/${path}`;
408
+ }
409
+ /**
410
+ * Check if a path is explicitly a virtual path.
411
+ * Only recognizes explicit virtual path formats:
412
+ * - kindx://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 kindx:// prefix (with any number of slashes)
421
+ if (trimmed.startsWith('kindx:'))
422
+ return true;
423
+ // //collection/path format (missing kindx: 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/kindx/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/kindx/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
+ /** Replace emoji/symbol codepoints with their hex representation (e.g. 🐘 → 1f418) */
710
+ function emojiToHex(str) {
711
+ return str.replace(/(?:\p{So}\p{Mn}?|\p{Sk})+/gu, (run) => {
712
+ // Split the run into individual emoji and convert each to hex, dash-separated
713
+ return [...run].filter(c => /\p{So}|\p{Sk}/u.test(c))
714
+ .map(c => c.codePointAt(0).toString(16)).join('-');
715
+ });
716
+ }
717
+ export function handelize(path) {
718
+ if (!path || path.trim() === '') {
719
+ throw new Error('handelize: path cannot be empty');
720
+ }
721
+ // Allow route-style "$" filenames while still rejecting paths with no usable content.
722
+ // Emoji (\p{So}) counts as valid content — they get converted to hex codepoints below.
723
+ const segments = path.split('/').filter(Boolean);
724
+ const lastSegment = segments[segments.length - 1] || '';
725
+ const filenameWithoutExt = lastSegment.replace(/\.[^.]+$/, '');
726
+ const hasValidContent = /[\p{L}\p{N}\p{So}\p{Sk}$]/u.test(filenameWithoutExt);
727
+ if (!hasValidContent) {
728
+ throw new Error(`handelize: path "${path}" has no valid filename content`);
729
+ }
730
+ const result = path
731
+ .replace(/___/g, '/') // Triple underscore becomes folder separator
732
+ .toLowerCase()
733
+ .split('/')
734
+ .map((segment, idx, arr) => {
735
+ const isLastSegment = idx === arr.length - 1;
736
+ // Convert emoji to hex codepoints before cleaning
737
+ segment = emojiToHex(segment);
738
+ if (isLastSegment) {
739
+ // For the filename (last segment), preserve the extension
740
+ const extMatch = segment.match(/(\.[a-z0-9]+)$/i);
741
+ const ext = extMatch ? extMatch[1] : '';
742
+ const nameWithoutExt = ext ? segment.slice(0, -ext.length) : segment;
743
+ const cleanedName = nameWithoutExt
744
+ .replace(/[^\p{L}\p{N}$]+/gu, '-') // Keep route marker "$", dash-separate other chars
745
+ .replace(/^-+|-+$/g, ''); // Remove leading/trailing dashes
746
+ return cleanedName + ext;
747
+ }
748
+ else {
749
+ // For directories, just clean normally
750
+ return segment
751
+ .replace(/[^\p{L}\p{N}$]+/gu, '-')
752
+ .replace(/^-+|-+$/g, '');
753
+ }
754
+ })
755
+ .filter(Boolean)
756
+ .join('/');
757
+ if (!result) {
758
+ throw new Error(`handelize: path "${path}" resulted in empty string after processing`);
759
+ }
760
+ return result;
761
+ }
762
+ // =============================================================================
763
+ // Index health
764
+ // =============================================================================
765
+ export function getHashesNeedingEmbedding(db) {
766
+ const result = db.prepare(`
767
+ SELECT COUNT(DISTINCT d.hash) as count
768
+ FROM documents d
769
+ LEFT JOIN content_vectors v ON d.hash = v.hash AND v.seq = 0
770
+ WHERE d.active = 1 AND v.hash IS NULL
771
+ `).get();
772
+ return result.count;
773
+ }
774
+ export function getIndexHealth(db) {
775
+ const needsEmbedding = getHashesNeedingEmbedding(db);
776
+ const totalDocs = db.prepare(`SELECT COUNT(*) as count FROM documents WHERE active = 1`).get().count;
777
+ const mostRecent = db.prepare(`SELECT MAX(modified_at) as latest FROM documents WHERE active = 1`).get();
778
+ let daysStale = null;
779
+ if (mostRecent?.latest) {
780
+ const lastUpdate = new Date(mostRecent.latest);
781
+ daysStale = Math.floor((Date.now() - lastUpdate.getTime()) / (24 * 60 * 60 * 1000));
782
+ }
783
+ return { needsEmbedding, totalDocs, daysStale };
784
+ }
785
+ // =============================================================================
786
+ // Caching
787
+ // =============================================================================
788
+ export function getCacheKey(url, body) {
789
+ const hash = createHash("sha256");
790
+ hash.update(url);
791
+ hash.update(JSON.stringify(body));
792
+ return hash.digest("hex");
793
+ }
794
+ export function getCachedResult(db, cacheKey) {
795
+ const row = db.prepare(`SELECT result FROM llm_cache WHERE hash = ?`).get(cacheKey);
796
+ return row?.result || null;
797
+ }
798
+ export function setCachedResult(db, cacheKey, result) {
799
+ const now = new Date().toISOString();
800
+ db.prepare(`INSERT OR REPLACE INTO llm_cache (hash, result, created_at) VALUES (?, ?, ?)`).run(cacheKey, result, now);
801
+ if (Math.random() < 0.01) {
802
+ db.exec(`DELETE FROM llm_cache WHERE hash NOT IN (SELECT hash FROM llm_cache ORDER BY created_at DESC LIMIT 1000)`);
803
+ }
804
+ }
805
+ export function clearCache(db) {
806
+ db.exec(`DELETE FROM llm_cache`);
807
+ }
808
+ // =============================================================================
809
+ // Cleanup and maintenance operations
810
+ // =============================================================================
811
+ /**
812
+ * Delete cached LLM API responses.
813
+ * Returns the number of cached responses deleted.
814
+ */
815
+ export function deleteLLMCache(db) {
816
+ const result = db.prepare(`DELETE FROM llm_cache`).run();
817
+ return result.changes;
818
+ }
819
+ /**
820
+ * Remove inactive document records (active = 0).
821
+ * Returns the number of inactive documents deleted.
822
+ */
823
+ export function deleteInactiveDocuments(db) {
824
+ const result = db.prepare(`DELETE FROM documents WHERE active = 0`).run();
825
+ return result.changes;
826
+ }
827
+ /**
828
+ * Remove orphaned content hashes that are not referenced by any active document.
829
+ * Returns the number of orphaned content hashes deleted.
830
+ */
831
+ export function cleanupOrphanedContent(db) {
832
+ const result = db.prepare(`
833
+ DELETE FROM content
834
+ WHERE hash NOT IN (SELECT DISTINCT hash FROM documents WHERE active = 1)
835
+ `).run();
836
+ return result.changes;
837
+ }
838
+ /**
839
+ * Remove orphaned vector embeddings that are not referenced by any active document.
840
+ * Returns the number of orphaned embedding chunks deleted.
841
+ */
842
+ export function cleanupOrphanedVectors(db) {
843
+ // Check if vectors_vec table exists
844
+ const tableExists = db.prepare(`
845
+ SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'
846
+ `).get();
847
+ if (!tableExists) {
848
+ return 0;
849
+ }
850
+ // Count orphaned vectors first
851
+ const countResult = db.prepare(`
852
+ SELECT COUNT(*) as c 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
+ `).get();
857
+ if (countResult.c === 0) {
858
+ return 0;
859
+ }
860
+ // Delete from vectors_vec first
861
+ db.exec(`
862
+ DELETE FROM vectors_vec WHERE hash_seq IN (
863
+ SELECT cv.hash || '_' || cv.seq FROM content_vectors cv
864
+ WHERE NOT EXISTS (
865
+ SELECT 1 FROM documents d WHERE d.hash = cv.hash AND d.active = 1
866
+ )
867
+ )
868
+ `);
869
+ // Delete from content_vectors
870
+ db.exec(`
871
+ DELETE FROM content_vectors WHERE hash NOT IN (
872
+ SELECT hash FROM documents WHERE active = 1
873
+ )
874
+ `);
875
+ return countResult.c;
876
+ }
877
+ /**
878
+ * Run VACUUM to reclaim unused space in the database.
879
+ * This operation rebuilds the database file to eliminate fragmentation.
880
+ */
881
+ export function vacuumDatabase(db) {
882
+ db.exec(`VACUUM`);
883
+ }
884
+ // =============================================================================
885
+ // Document helpers
886
+ // =============================================================================
887
+ export async function hashContent(content) {
888
+ const hash = createHash("sha256");
889
+ hash.update(content);
890
+ return hash.digest("hex");
891
+ }
892
+ const titleExtractors = {
893
+ '.md': (content) => {
894
+ const match = content.match(/^##?\s+(.+)$/m);
895
+ if (match) {
896
+ const title = (match[1] ?? "").trim();
897
+ if (title === "📝 Notes" || title === "Notes") {
898
+ const nextMatch = content.match(/^##\s+(.+)$/m);
899
+ if (nextMatch?.[1])
900
+ return nextMatch[1].trim();
901
+ }
902
+ return title;
903
+ }
904
+ return null;
905
+ },
906
+ '.org': (content) => {
907
+ const titleProp = content.match(/^#\+TITLE:\s*(.+)$/im);
908
+ if (titleProp?.[1])
909
+ return titleProp[1].trim();
910
+ const heading = content.match(/^\*+\s+(.+)$/m);
911
+ if (heading?.[1])
912
+ return heading[1].trim();
913
+ return null;
914
+ },
915
+ };
916
+ export function extractTitle(content, filename) {
917
+ const ext = filename.slice(filename.lastIndexOf('.')).toLowerCase();
918
+ const extractor = titleExtractors[ext];
919
+ if (extractor) {
920
+ const title = extractor(content);
921
+ if (title)
922
+ return title;
923
+ }
924
+ return filename.replace(/\.[^.]+$/, "").split("/").pop() || filename;
925
+ }
926
+ // =============================================================================
927
+ // Document indexing operations
928
+ // =============================================================================
929
+ /**
930
+ * Insert content into the content table (content-addressable storage).
931
+ * Uses INSERT OR IGNORE so duplicate hashes are skipped.
932
+ */
933
+ export function insertContent(db, hash, content, createdAt) {
934
+ db.prepare(`INSERT OR IGNORE INTO content (hash, doc, created_at) VALUES (?, ?, ?)`)
935
+ .run(hash, content, createdAt);
936
+ }
937
+ /**
938
+ * Insert a new document into the documents table.
939
+ */
940
+ export function insertDocument(db, collectionName, path, title, hash, createdAt, modifiedAt) {
941
+ db.prepare(`
942
+ INSERT INTO documents (collection, path, title, hash, created_at, modified_at, active)
943
+ VALUES (?, ?, ?, ?, ?, ?, 1)
944
+ ON CONFLICT(collection, path) DO UPDATE SET
945
+ title = excluded.title,
946
+ hash = excluded.hash,
947
+ modified_at = excluded.modified_at,
948
+ active = 1
949
+ `).run(collectionName, path, title, hash, createdAt, modifiedAt);
950
+ }
951
+ /**
952
+ * Find an active document by collection name and path.
953
+ */
954
+ export function findActiveDocument(db, collectionName, path) {
955
+ const row = db.prepare(`
956
+ SELECT id, hash, title FROM documents
957
+ WHERE collection = ? AND path = ? AND active = 1
958
+ `).get(collectionName, path);
959
+ return row ?? null;
960
+ }
961
+ /**
962
+ * Update the title and modified_at timestamp for a document.
963
+ */
964
+ export function updateDocumentTitle(db, documentId, title, modifiedAt) {
965
+ db.prepare(`UPDATE documents SET title = ?, modified_at = ? WHERE id = ?`)
966
+ .run(title, modifiedAt, documentId);
967
+ }
968
+ /**
969
+ * Update an existing document's hash, title, and modified_at timestamp.
970
+ * Used when content changes but the file path stays the same.
971
+ */
972
+ export function updateDocument(db, documentId, title, hash, modifiedAt) {
973
+ db.prepare(`UPDATE documents SET title = ?, hash = ?, modified_at = ? WHERE id = ?`)
974
+ .run(title, hash, modifiedAt, documentId);
975
+ }
976
+ /**
977
+ * Deactivate a document (mark as inactive but don't delete).
978
+ */
979
+ export function deactivateDocument(db, collectionName, path) {
980
+ db.prepare(`UPDATE documents SET active = 0 WHERE collection = ? AND path = ? AND active = 1`)
981
+ .run(collectionName, path);
982
+ }
983
+ /**
984
+ * Get all active document paths for a collection.
985
+ */
986
+ export function getActiveDocumentPaths(db, collectionName) {
987
+ const rows = db.prepare(`
988
+ SELECT path FROM documents WHERE collection = ? AND active = 1
989
+ `).all(collectionName);
990
+ return rows.map(r => r.path);
991
+ }
992
+ export { formatQueryForEmbedding, formatDocForEmbedding };
993
+ export function chunkDocument(content, maxChars = CHUNK_SIZE_CHARS, overlapChars = CHUNK_OVERLAP_CHARS, windowChars = CHUNK_WINDOW_CHARS) {
994
+ if (content.length <= maxChars) {
995
+ return [{ text: content, pos: 0 }];
996
+ }
997
+ // Pre-scan all break points and code fences once
998
+ const breakPoints = scanBreakPoints(content);
999
+ const codeFences = findCodeFences(content);
1000
+ const chunks = [];
1001
+ let charPos = 0;
1002
+ while (charPos < content.length) {
1003
+ // Calculate target end position for this chunk
1004
+ const targetEndPos = Math.min(charPos + maxChars, content.length);
1005
+ let endPos = targetEndPos;
1006
+ // If not at the end, find the best break point
1007
+ if (endPos < content.length) {
1008
+ // Find best cutoff using scored algorithm
1009
+ const bestCutoff = findBestCutoff(breakPoints, targetEndPos, windowChars, 0.7, codeFences);
1010
+ // Only use the cutoff if it's within our current chunk
1011
+ if (bestCutoff > charPos && bestCutoff <= targetEndPos) {
1012
+ endPos = bestCutoff;
1013
+ }
1014
+ }
1015
+ // Ensure we make progress
1016
+ if (endPos <= charPos) {
1017
+ endPos = Math.min(charPos + maxChars, content.length);
1018
+ }
1019
+ chunks.push({ text: content.slice(charPos, endPos), pos: charPos });
1020
+ // Move forward, but overlap with previous chunk
1021
+ // For last chunk, don't overlap (just go to the end)
1022
+ if (endPos >= content.length) {
1023
+ break;
1024
+ }
1025
+ charPos = endPos - overlapChars;
1026
+ const lastChunkPos = chunks.at(-1).pos;
1027
+ if (charPos <= lastChunkPos) {
1028
+ // Prevent infinite loop - move forward at least a bit
1029
+ charPos = endPos;
1030
+ }
1031
+ }
1032
+ return chunks;
1033
+ }
1034
+ /**
1035
+ * Chunk a document by actual token count using the LLM tokenizer.
1036
+ * More accurate than character-based chunking but requires async.
1037
+ */
1038
+ export async function chunkDocumentByTokens(content, maxTokens = CHUNK_SIZE_TOKENS, overlapTokens = CHUNK_OVERLAP_TOKENS, windowTokens = CHUNK_WINDOW_TOKENS) {
1039
+ const llm = getDefaultLlamaCpp();
1040
+ // Use moderate chars/token estimate (prose ~4, code ~2, mixed ~3)
1041
+ // If chunks exceed limit, they'll be re-split with actual ratio
1042
+ const avgCharsPerToken = 3;
1043
+ const maxChars = maxTokens * avgCharsPerToken;
1044
+ const overlapChars = overlapTokens * avgCharsPerToken;
1045
+ const windowChars = windowTokens * avgCharsPerToken;
1046
+ // Chunk in character space with conservative estimate
1047
+ let charChunks = chunkDocument(content, maxChars, overlapChars, windowChars);
1048
+ // Tokenize and split any chunks that still exceed limit
1049
+ const results = [];
1050
+ for (const chunk of charChunks) {
1051
+ const tokens = await llm.tokenize(chunk.text);
1052
+ if (tokens.length <= maxTokens) {
1053
+ results.push({ text: chunk.text, pos: chunk.pos, tokens: tokens.length });
1054
+ }
1055
+ else {
1056
+ // Chunk is still too large - split it further
1057
+ // Use actual token count to estimate better char limit
1058
+ const actualCharsPerToken = chunk.text.length / tokens.length;
1059
+ const safeMaxChars = Math.floor(maxTokens * actualCharsPerToken * 0.95); // 5% safety margin
1060
+ const subChunks = chunkDocument(chunk.text, safeMaxChars, Math.floor(overlapChars * actualCharsPerToken / 2), Math.floor(windowChars * actualCharsPerToken / 2));
1061
+ for (const subChunk of subChunks) {
1062
+ const subTokens = await llm.tokenize(subChunk.text);
1063
+ results.push({
1064
+ text: subChunk.text,
1065
+ pos: chunk.pos + subChunk.pos,
1066
+ tokens: subTokens.length,
1067
+ });
1068
+ }
1069
+ }
1070
+ }
1071
+ return results;
1072
+ }
1073
+ // =============================================================================
1074
+ // Fuzzy matching
1075
+ // =============================================================================
1076
+ function levenshtein(a, b) {
1077
+ const m = a.length, n = b.length;
1078
+ if (m === 0)
1079
+ return n;
1080
+ if (n === 0)
1081
+ return m;
1082
+ const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
1083
+ for (let i = 0; i <= m; i++)
1084
+ dp[i][0] = i;
1085
+ for (let j = 0; j <= n; j++)
1086
+ dp[0][j] = j;
1087
+ for (let i = 1; i <= m; i++) {
1088
+ for (let j = 1; j <= n; j++) {
1089
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
1090
+ dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);
1091
+ }
1092
+ }
1093
+ return dp[m][n];
1094
+ }
1095
+ /**
1096
+ * Normalize a docid input by stripping surrounding quotes and leading #.
1097
+ * Handles: "#abc123", 'abc123', "abc123", #abc123, abc123
1098
+ * Returns the bare hex string.
1099
+ */
1100
+ export function normalizeDocid(docid) {
1101
+ let normalized = docid.trim();
1102
+ // Strip surrounding quotes (single or double)
1103
+ if ((normalized.startsWith('"') && normalized.endsWith('"')) ||
1104
+ (normalized.startsWith("'") && normalized.endsWith("'"))) {
1105
+ normalized = normalized.slice(1, -1);
1106
+ }
1107
+ // Strip leading # if present
1108
+ if (normalized.startsWith('#')) {
1109
+ normalized = normalized.slice(1);
1110
+ }
1111
+ return normalized;
1112
+ }
1113
+ /**
1114
+ * Check if a string looks like a docid reference.
1115
+ * Accepts: #abc123, abc123, "#abc123", "abc123", '#abc123', 'abc123'
1116
+ * Returns true if the normalized form is a valid hex string of 6+ chars.
1117
+ */
1118
+ export function isDocid(input) {
1119
+ const normalized = normalizeDocid(input);
1120
+ // Must be at least 6 hex characters
1121
+ return normalized.length >= 6 && /^[a-f0-9]+$/i.test(normalized);
1122
+ }
1123
+ /**
1124
+ * Find a document by its short docid (first 6 characters of hash).
1125
+ * Returns the document's virtual path if found, null otherwise.
1126
+ * If multiple documents match the same short hash (collision), returns the first one.
1127
+ *
1128
+ * Accepts lenient input: #abc123, abc123, "#abc123", "abc123"
1129
+ */
1130
+ export function findDocumentByDocid(db, docid) {
1131
+ const shortHash = normalizeDocid(docid);
1132
+ if (shortHash.length < 1)
1133
+ return null;
1134
+ // Look up documents where hash starts with the short hash
1135
+ const doc = db.prepare(`
1136
+ SELECT 'kindx://' || d.collection || '/' || d.path as filepath, d.hash
1137
+ FROM documents d
1138
+ WHERE d.hash LIKE ? AND d.active = 1
1139
+ LIMIT 1
1140
+ `).get(`${shortHash}%`);
1141
+ return doc;
1142
+ }
1143
+ export function findSimilarFiles(db, query, maxDistance = 3, limit = 5) {
1144
+ const allFiles = db.prepare(`
1145
+ SELECT d.path
1146
+ FROM documents d
1147
+ WHERE d.active = 1
1148
+ `).all();
1149
+ const queryLower = query.toLowerCase();
1150
+ const scored = allFiles
1151
+ .map(f => ({ path: f.path, dist: levenshtein(f.path.toLowerCase(), queryLower) }))
1152
+ .filter(f => f.dist <= maxDistance)
1153
+ .sort((a, b) => a.dist - b.dist)
1154
+ .slice(0, limit);
1155
+ return scored.map(f => f.path);
1156
+ }
1157
+ export function matchFilesByGlob(db, pattern) {
1158
+ const allFiles = db.prepare(`
1159
+ SELECT
1160
+ 'kindx://' || d.collection || '/' || d.path as virtual_path,
1161
+ LENGTH(content.doc) as body_length,
1162
+ d.path,
1163
+ d.collection
1164
+ FROM documents d
1165
+ JOIN content ON content.hash = d.hash
1166
+ WHERE d.active = 1
1167
+ `).all();
1168
+ const isMatch = picomatch(pattern);
1169
+ return allFiles
1170
+ .filter(f => isMatch(f.virtual_path) || isMatch(f.path))
1171
+ .map(f => ({
1172
+ filepath: f.virtual_path, // Virtual path for precise lookup
1173
+ displayPath: f.path, // Relative path for display
1174
+ bodyLength: f.body_length
1175
+ }));
1176
+ }
1177
+ // =============================================================================
1178
+ // Context
1179
+ // =============================================================================
1180
+ /**
1181
+ * Get context for a file path using hierarchical inheritance.
1182
+ * Contexts are collection-scoped and inherit from parent directories.
1183
+ * For example, context at "/talks" applies to "/talks/2024/keynote.md".
1184
+ *
1185
+ * @param db Database instance (unused - kept for compatibility)
1186
+ * @param collectionName Collection name
1187
+ * @param path Relative path within the collection
1188
+ * @returns Context string or null if no context is defined
1189
+ */
1190
+ export function getContextForPath(db, collectionName, path) {
1191
+ const config = collectionsLoadConfig();
1192
+ const coll = getCollection(collectionName);
1193
+ if (!coll)
1194
+ return null;
1195
+ // Collect ALL matching contexts (global + all path prefixes)
1196
+ const contexts = [];
1197
+ // Add global context if present
1198
+ if (config.global_context) {
1199
+ contexts.push(config.global_context);
1200
+ }
1201
+ // Add all matching path contexts (from most general to most specific)
1202
+ if (coll.context) {
1203
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
1204
+ // Collect all matching prefixes
1205
+ const matchingContexts = [];
1206
+ for (const [prefix, context] of Object.entries(coll.context)) {
1207
+ const normalizedPrefix = prefix.startsWith("/") ? prefix : `/${prefix}`;
1208
+ if (normalizedPath.startsWith(normalizedPrefix)) {
1209
+ matchingContexts.push({ prefix: normalizedPrefix, context });
1210
+ }
1211
+ }
1212
+ // Sort by prefix length (shortest/most general first)
1213
+ matchingContexts.sort((a, b) => a.prefix.length - b.prefix.length);
1214
+ // Add all matching contexts
1215
+ for (const match of matchingContexts) {
1216
+ contexts.push(match.context);
1217
+ }
1218
+ }
1219
+ // Join all contexts with double newline
1220
+ return contexts.length > 0 ? contexts.join('\n\n') : null;
1221
+ }
1222
+ /**
1223
+ * Get context for a file path (virtual or filesystem).
1224
+ * Resolves the collection and relative path using the YAML collections config.
1225
+ */
1226
+ export function getContextForFile(db, filepath) {
1227
+ // Handle undefined or null filepath
1228
+ if (!filepath)
1229
+ return null;
1230
+ // Get all collections from YAML config
1231
+ const collections = collectionsListCollections();
1232
+ const config = collectionsLoadConfig();
1233
+ // Parse virtual path format: kindx://collection/path
1234
+ let collectionName = null;
1235
+ let relativePath = null;
1236
+ const parsedVirtual = filepath.startsWith('kindx://') ? parseVirtualPath(filepath) : null;
1237
+ if (parsedVirtual) {
1238
+ collectionName = parsedVirtual.collectionName;
1239
+ relativePath = parsedVirtual.path;
1240
+ }
1241
+ else {
1242
+ // Filesystem path: find which collection this absolute path belongs to
1243
+ for (const coll of collections) {
1244
+ // Skip collections with missing paths
1245
+ if (!coll || !coll.path)
1246
+ continue;
1247
+ if (filepath.startsWith(coll.path + '/') || filepath === coll.path) {
1248
+ collectionName = coll.name;
1249
+ // Extract relative path
1250
+ relativePath = filepath.startsWith(coll.path + '/')
1251
+ ? filepath.slice(coll.path.length + 1)
1252
+ : '';
1253
+ break;
1254
+ }
1255
+ }
1256
+ if (!collectionName || relativePath === null)
1257
+ return null;
1258
+ }
1259
+ // Get the collection from config
1260
+ const coll = getCollection(collectionName);
1261
+ if (!coll)
1262
+ return null;
1263
+ // Verify this document exists in the database
1264
+ const doc = db.prepare(`
1265
+ SELECT d.path
1266
+ FROM documents d
1267
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
1268
+ LIMIT 1
1269
+ `).get(collectionName, relativePath);
1270
+ if (!doc)
1271
+ return null;
1272
+ // Collect ALL matching contexts (global + all path prefixes)
1273
+ const contexts = [];
1274
+ // Add global context if present
1275
+ if (config.global_context) {
1276
+ contexts.push(config.global_context);
1277
+ }
1278
+ // Add all matching path contexts (from most general to most specific)
1279
+ if (coll.context) {
1280
+ const normalizedPath = relativePath.startsWith("/") ? relativePath : `/${relativePath}`;
1281
+ // Collect all matching prefixes
1282
+ const matchingContexts = [];
1283
+ for (const [prefix, context] of Object.entries(coll.context)) {
1284
+ const normalizedPrefix = prefix.startsWith("/") ? prefix : `/${prefix}`;
1285
+ if (normalizedPath.startsWith(normalizedPrefix)) {
1286
+ matchingContexts.push({ prefix: normalizedPrefix, context });
1287
+ }
1288
+ }
1289
+ // Sort by prefix length (shortest/most general first)
1290
+ matchingContexts.sort((a, b) => a.prefix.length - b.prefix.length);
1291
+ // Add all matching contexts
1292
+ for (const match of matchingContexts) {
1293
+ contexts.push(match.context);
1294
+ }
1295
+ }
1296
+ // Join all contexts with double newline
1297
+ return contexts.length > 0 ? contexts.join('\n\n') : null;
1298
+ }
1299
+ /**
1300
+ * Get collection by name from YAML config.
1301
+ * Returns collection metadata from ~/.config/kindx/index.yml
1302
+ */
1303
+ export function getCollectionByName(db, name) {
1304
+ const collection = getCollection(name);
1305
+ if (!collection)
1306
+ return null;
1307
+ return {
1308
+ name: collection.name,
1309
+ pwd: collection.path,
1310
+ glob_pattern: collection.pattern,
1311
+ };
1312
+ }
1313
+ /**
1314
+ * List all collections with document counts from database.
1315
+ * Merges YAML config with database statistics.
1316
+ */
1317
+ export function listCollections(db) {
1318
+ const collections = collectionsListCollections();
1319
+ // Get document counts from database for each collection
1320
+ const result = collections.map(coll => {
1321
+ const stats = db.prepare(`
1322
+ SELECT
1323
+ COUNT(d.id) as doc_count,
1324
+ SUM(CASE WHEN d.active = 1 THEN 1 ELSE 0 END) as active_count,
1325
+ MAX(d.modified_at) as last_modified
1326
+ FROM documents d
1327
+ WHERE d.collection = ?
1328
+ `).get(coll.name);
1329
+ return {
1330
+ name: coll.name,
1331
+ pwd: coll.path,
1332
+ glob_pattern: coll.pattern,
1333
+ doc_count: stats?.doc_count || 0,
1334
+ active_count: stats?.active_count || 0,
1335
+ last_modified: stats?.last_modified || null,
1336
+ };
1337
+ });
1338
+ return result;
1339
+ }
1340
+ /**
1341
+ * Remove a collection and clean up its documents.
1342
+ * Uses catalogs.ts to remove from YAML config and cleans up database.
1343
+ */
1344
+ export function removeCollection(db, collectionName) {
1345
+ // Delete documents from database
1346
+ const docResult = db.prepare(`DELETE FROM documents WHERE collection = ?`).run(collectionName);
1347
+ // Clean up orphaned content hashes
1348
+ const cleanupResult = db.prepare(`
1349
+ DELETE FROM content
1350
+ WHERE hash NOT IN (SELECT DISTINCT hash FROM documents WHERE active = 1)
1351
+ `).run();
1352
+ // Remove from YAML config (returns true if found and removed)
1353
+ collectionsRemoveCollection(collectionName);
1354
+ return {
1355
+ deletedDocs: docResult.changes,
1356
+ cleanedHashes: cleanupResult.changes
1357
+ };
1358
+ }
1359
+ /**
1360
+ * Rename a collection.
1361
+ * Updates both YAML config and database documents table.
1362
+ */
1363
+ export function renameCollection(db, oldName, newName) {
1364
+ // Update all documents with the new collection name in database
1365
+ db.prepare(`UPDATE documents SET collection = ? WHERE collection = ?`)
1366
+ .run(newName, oldName);
1367
+ // Rename in YAML config
1368
+ collectionsRenameCollection(oldName, newName);
1369
+ }
1370
+ // =============================================================================
1371
+ // Context Management Operations
1372
+ // =============================================================================
1373
+ /**
1374
+ * Insert or update a context for a specific collection and path prefix.
1375
+ */
1376
+ export function insertContext(db, collectionId, pathPrefix, context) {
1377
+ // Get collection name from ID
1378
+ const coll = db.prepare(`SELECT name FROM collections WHERE id = ?`).get(collectionId);
1379
+ if (!coll) {
1380
+ throw new Error(`Collection with id ${collectionId} not found`);
1381
+ }
1382
+ // Use catalogs.ts to add context
1383
+ collectionsAddContext(coll.name, pathPrefix, context);
1384
+ }
1385
+ /**
1386
+ * Delete a context for a specific collection and path prefix.
1387
+ * Returns the number of contexts deleted.
1388
+ */
1389
+ export function deleteContext(db, collectionName, pathPrefix) {
1390
+ // Use catalogs.ts to remove context
1391
+ const success = collectionsRemoveContext(collectionName, pathPrefix);
1392
+ return success ? 1 : 0;
1393
+ }
1394
+ /**
1395
+ * Delete all global contexts (contexts with empty path_prefix).
1396
+ * Returns the number of contexts deleted.
1397
+ */
1398
+ export function deleteGlobalContexts(db) {
1399
+ let deletedCount = 0;
1400
+ // Remove global context
1401
+ setGlobalContext(undefined);
1402
+ deletedCount++;
1403
+ // Remove root context (empty string) from all collections
1404
+ const collections = collectionsListCollections();
1405
+ for (const coll of collections) {
1406
+ const success = collectionsRemoveContext(coll.name, '');
1407
+ if (success) {
1408
+ deletedCount++;
1409
+ }
1410
+ }
1411
+ return deletedCount;
1412
+ }
1413
+ /**
1414
+ * List all contexts, grouped by collection.
1415
+ * Returns contexts ordered by collection name, then by path prefix length (longest first).
1416
+ */
1417
+ export function listPathContexts(db) {
1418
+ const allContexts = collectionsListAllContexts();
1419
+ // Convert to expected format and sort
1420
+ return allContexts.map(ctx => ({
1421
+ collection_name: ctx.collection,
1422
+ path_prefix: ctx.path,
1423
+ context: ctx.context,
1424
+ })).sort((a, b) => {
1425
+ // Sort by collection name first
1426
+ if (a.collection_name !== b.collection_name) {
1427
+ return a.collection_name.localeCompare(b.collection_name);
1428
+ }
1429
+ // Then by path prefix length (longest first)
1430
+ if (a.path_prefix.length !== b.path_prefix.length) {
1431
+ return b.path_prefix.length - a.path_prefix.length;
1432
+ }
1433
+ // Then alphabetically
1434
+ return a.path_prefix.localeCompare(b.path_prefix);
1435
+ });
1436
+ }
1437
+ /**
1438
+ * Get all collections (name only - from YAML config).
1439
+ */
1440
+ export function getAllCollections(db) {
1441
+ const collections = collectionsListCollections();
1442
+ return collections.map(c => ({ name: c.name }));
1443
+ }
1444
+ /**
1445
+ * Check which collections don't have any context defined.
1446
+ * Returns collections that have no context entries at all (not even root context).
1447
+ */
1448
+ export function getCollectionsWithoutContext(db) {
1449
+ // Get all collections from YAML config
1450
+ const yamlCollections = collectionsListCollections();
1451
+ // Filter to those without context
1452
+ const collectionsWithoutContext = [];
1453
+ for (const coll of yamlCollections) {
1454
+ // Check if collection has any context
1455
+ if (!coll.context || Object.keys(coll.context).length === 0) {
1456
+ // Get doc count from database
1457
+ const stats = db.prepare(`
1458
+ SELECT COUNT(d.id) as doc_count
1459
+ FROM documents d
1460
+ WHERE d.collection = ? AND d.active = 1
1461
+ `).get(coll.name);
1462
+ collectionsWithoutContext.push({
1463
+ name: coll.name,
1464
+ pwd: coll.path,
1465
+ doc_count: stats?.doc_count || 0,
1466
+ });
1467
+ }
1468
+ }
1469
+ return collectionsWithoutContext.sort((a, b) => a.name.localeCompare(b.name));
1470
+ }
1471
+ /**
1472
+ * Get top-level directories in a collection that don't have context.
1473
+ * Useful for suggesting where context might be needed.
1474
+ */
1475
+ export function getTopLevelPathsWithoutContext(db, collectionName) {
1476
+ // Get all paths in the collection from database
1477
+ const paths = db.prepare(`
1478
+ SELECT DISTINCT path FROM documents
1479
+ WHERE collection = ? AND active = 1
1480
+ `).all(collectionName);
1481
+ // Get existing contexts for this collection from YAML
1482
+ const yamlColl = getCollection(collectionName);
1483
+ if (!yamlColl)
1484
+ return [];
1485
+ const contextPrefixes = new Set();
1486
+ if (yamlColl.context) {
1487
+ for (const prefix of Object.keys(yamlColl.context)) {
1488
+ contextPrefixes.add(prefix);
1489
+ }
1490
+ }
1491
+ // Extract top-level directories (first path component)
1492
+ const topLevelDirs = new Set();
1493
+ for (const { path } of paths) {
1494
+ const parts = path.split('/').filter(Boolean);
1495
+ if (parts.length > 1) {
1496
+ const dir = parts[0];
1497
+ if (dir)
1498
+ topLevelDirs.add(dir);
1499
+ }
1500
+ }
1501
+ // Filter out directories that already have context (exact or parent)
1502
+ const missing = [];
1503
+ for (const dir of topLevelDirs) {
1504
+ let hasContext = false;
1505
+ // Check if this dir or any parent has context
1506
+ for (const prefix of contextPrefixes) {
1507
+ if (prefix === '' || prefix === dir || dir.startsWith(prefix + '/')) {
1508
+ hasContext = true;
1509
+ break;
1510
+ }
1511
+ }
1512
+ if (!hasContext) {
1513
+ missing.push(dir);
1514
+ }
1515
+ }
1516
+ return missing.sort();
1517
+ }
1518
+ // =============================================================================
1519
+ // FTS Search
1520
+ // =============================================================================
1521
+ function sanitizeFTS5Term(term) {
1522
+ // Preserve underscores so snake_case identifiers (e.g., my_function_name)
1523
+ // are treated as single terms rather than being split into separate words.
1524
+ return term.replace(/[^\p{L}\p{N}'_]/gu, '').toLowerCase();
1525
+ }
1526
+ /**
1527
+ * Parse lex query syntax into FTS5 query.
1528
+ *
1529
+ * Supports:
1530
+ * - Quoted phrases: "exact phrase" → "exact phrase" (exact match)
1531
+ * - Negation: -term or -"phrase" → uses FTS5 NOT operator
1532
+ * - Plain terms: term → "term"* (prefix match)
1533
+ *
1534
+ * FTS5 NOT is a binary operator: `term1 NOT term2` means "match term1 but not term2".
1535
+ * So `-term` only works when there are also positive terms.
1536
+ *
1537
+ * Examples:
1538
+ * performance -sports → "performance"* NOT "sports"*
1539
+ * "machine learning" → "machine learning"
1540
+ */
1541
+ function buildFTS5Query(query) {
1542
+ const positive = [];
1543
+ const negative = [];
1544
+ let i = 0;
1545
+ const s = query.trim();
1546
+ while (i < s.length) {
1547
+ // Skip whitespace
1548
+ while (i < s.length && /\s/.test(s[i]))
1549
+ i++;
1550
+ if (i >= s.length)
1551
+ break;
1552
+ // Check for negation prefix
1553
+ const negated = s[i] === '-';
1554
+ if (negated)
1555
+ i++;
1556
+ // Check for quoted phrase
1557
+ if (s[i] === '"') {
1558
+ const start = i + 1;
1559
+ i++;
1560
+ while (i < s.length && s[i] !== '"')
1561
+ i++;
1562
+ const phrase = s.slice(start, i).trim();
1563
+ i++; // skip closing quote
1564
+ if (phrase.length > 0) {
1565
+ const sanitized = phrase.split(/\s+/).map(t => sanitizeFTS5Term(t)).filter(t => t).join(' ');
1566
+ if (sanitized) {
1567
+ const ftsPhrase = `"${sanitized}"`; // Exact phrase, no prefix match
1568
+ if (negated) {
1569
+ negative.push(ftsPhrase);
1570
+ }
1571
+ else {
1572
+ positive.push(ftsPhrase);
1573
+ }
1574
+ }
1575
+ }
1576
+ }
1577
+ else {
1578
+ // Plain term (until whitespace or quote)
1579
+ const start = i;
1580
+ while (i < s.length && !/[\s"]/.test(s[i]))
1581
+ i++;
1582
+ const term = s.slice(start, i);
1583
+ const sanitized = sanitizeFTS5Term(term);
1584
+ if (sanitized) {
1585
+ const ftsTerm = `"${sanitized}"*`; // Prefix match
1586
+ if (negated) {
1587
+ negative.push(ftsTerm);
1588
+ }
1589
+ else {
1590
+ positive.push(ftsTerm);
1591
+ }
1592
+ }
1593
+ }
1594
+ }
1595
+ if (positive.length === 0 && negative.length === 0)
1596
+ return null;
1597
+ // If only negative terms, we can't search (FTS5 NOT is binary)
1598
+ if (positive.length === 0)
1599
+ return null;
1600
+ // Join positive terms with AND
1601
+ let result = positive.join(' AND ');
1602
+ // Add NOT clause for negative terms
1603
+ for (const neg of negative) {
1604
+ result = `${result} NOT ${neg}`;
1605
+ }
1606
+ return result;
1607
+ }
1608
+ /**
1609
+ * Validate that a vec/hyde query doesn't use lex-only syntax.
1610
+ * Returns error message if invalid, null if valid.
1611
+ */
1612
+ export function validateSemanticQuery(query) {
1613
+ // Check for negation syntax
1614
+ if (/-\w/.test(query) || /-"/.test(query)) {
1615
+ return 'Negation (-term) is not supported in vec/hyde queries. Use lex for exclusions.';
1616
+ }
1617
+ return null;
1618
+ }
1619
+ export function validateLexQuery(query) {
1620
+ if (/[\r\n]/.test(query)) {
1621
+ return 'Lex queries must be a single line. Remove newline characters or split into separate lex: lines.';
1622
+ }
1623
+ const quoteCount = (query.match(/"/g) ?? []).length;
1624
+ if (quoteCount % 2 === 1) {
1625
+ return 'Lex query has an unmatched double quote ("). Add the closing quote or remove it.';
1626
+ }
1627
+ return null;
1628
+ }
1629
+ export function searchFTS(db, query, limit = 20, collectionName) {
1630
+ const ftsQuery = buildFTS5Query(query);
1631
+ if (!ftsQuery)
1632
+ return [];
1633
+ let sql = `
1634
+ SELECT
1635
+ 'kindx://' || d.collection || '/' || d.path as filepath,
1636
+ d.collection || '/' || d.path as display_path,
1637
+ d.title,
1638
+ content.doc as body,
1639
+ d.hash,
1640
+ bm25(documents_fts, 10.0, 1.0) as bm25_score
1641
+ FROM documents_fts f
1642
+ JOIN documents d ON d.id = f.rowid
1643
+ JOIN content ON content.hash = d.hash
1644
+ WHERE documents_fts MATCH ? AND d.active = 1
1645
+ `;
1646
+ const params = [ftsQuery];
1647
+ if (collectionName) {
1648
+ sql += ` AND d.collection = ?`;
1649
+ params.push(String(collectionName));
1650
+ }
1651
+ // bm25 lower is better; sort ascending.
1652
+ sql += ` ORDER BY bm25_score ASC LIMIT ?`;
1653
+ params.push(limit);
1654
+ const rows = db.prepare(sql).all(...params);
1655
+ return rows.map(row => {
1656
+ const collectionName = row.filepath.split('//')[1]?.split('/')[0] || "";
1657
+ // Convert bm25 (negative, lower is better) into a stable [0..1) score where higher is better.
1658
+ // FTS5 BM25 scores are negative (e.g., -10 is strong, -2 is weak).
1659
+ // |x| / (1 + |x|) maps: strong(-10)→0.91, medium(-2)→0.67, weak(-0.5)→0.33, none(0)→0.
1660
+ // Monotonic and query-independent — no per-query normalization needed.
1661
+ const score = Math.abs(row.bm25_score) / (1 + Math.abs(row.bm25_score));
1662
+ return {
1663
+ filepath: row.filepath,
1664
+ displayPath: row.display_path,
1665
+ title: row.title,
1666
+ hash: row.hash,
1667
+ docid: getDocid(row.hash),
1668
+ collectionName,
1669
+ modifiedAt: "", // Not available in FTS query
1670
+ bodyLength: row.body.length,
1671
+ body: row.body,
1672
+ context: getContextForFile(db, row.filepath),
1673
+ score,
1674
+ source: "fts",
1675
+ };
1676
+ });
1677
+ }
1678
+ // =============================================================================
1679
+ // Vector Search
1680
+ // =============================================================================
1681
+ export async function searchVec(db, query, model, limit = 20, collectionName, session, precomputedEmbedding) {
1682
+ const tableExists = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
1683
+ if (!tableExists)
1684
+ return [];
1685
+ const embedding = precomputedEmbedding ?? await getEmbedding(query, model, true, session);
1686
+ if (!embedding)
1687
+ return [];
1688
+ // IMPORTANT: We use a two-step query approach here because sqlite-vec virtual tables
1689
+ // hang indefinitely when combined with JOINs in the same query. Do NOT try to
1690
+ // "optimize" this by combining into a single query with JOINs - it will break.
1691
+ // See: https://github.com/ambicuity/KINDX/pull/23
1692
+ // Step 1: Get vector matches from sqlite-vec (no JOINs allowed)
1693
+ const vecResults = db.prepare(`
1694
+ SELECT hash_seq, distance
1695
+ FROM vectors_vec
1696
+ WHERE embedding MATCH ? AND k = ?
1697
+ `).all(new Float32Array(embedding), limit * 3);
1698
+ if (vecResults.length === 0)
1699
+ return [];
1700
+ // Step 2: Get chunk info and document data
1701
+ const hashSeqs = vecResults.map(r => r.hash_seq);
1702
+ const distanceMap = new Map(vecResults.map(r => [r.hash_seq, r.distance]));
1703
+ // Build query for document lookup
1704
+ const placeholders = hashSeqs.map(() => '?').join(',');
1705
+ let docSql = `
1706
+ SELECT
1707
+ cv.hash || '_' || cv.seq as hash_seq,
1708
+ cv.hash,
1709
+ cv.pos,
1710
+ 'kindx://' || d.collection || '/' || d.path as filepath,
1711
+ d.collection || '/' || d.path as display_path,
1712
+ d.title,
1713
+ content.doc as body
1714
+ FROM content_vectors cv
1715
+ JOIN documents d ON d.hash = cv.hash AND d.active = 1
1716
+ JOIN content ON content.hash = d.hash
1717
+ WHERE cv.hash || '_' || cv.seq IN (${placeholders})
1718
+ `;
1719
+ const params = [...hashSeqs];
1720
+ if (collectionName) {
1721
+ docSql += ` AND d.collection = ?`;
1722
+ params.push(collectionName);
1723
+ }
1724
+ const docRows = db.prepare(docSql).all(...params);
1725
+ // Combine with distances and dedupe by filepath
1726
+ const seen = new Map();
1727
+ for (const row of docRows) {
1728
+ const distance = distanceMap.get(row.hash_seq) ?? 1;
1729
+ const existing = seen.get(row.filepath);
1730
+ if (!existing || distance < existing.bestDist) {
1731
+ seen.set(row.filepath, { row, bestDist: distance });
1732
+ }
1733
+ }
1734
+ return Array.from(seen.values())
1735
+ .sort((a, b) => a.bestDist - b.bestDist)
1736
+ .slice(0, limit)
1737
+ .map(({ row, bestDist }) => {
1738
+ const collectionName = row.filepath.split('//')[1]?.split('/')[0] || "";
1739
+ return {
1740
+ filepath: row.filepath,
1741
+ displayPath: row.display_path,
1742
+ title: row.title,
1743
+ hash: row.hash,
1744
+ docid: getDocid(row.hash),
1745
+ collectionName,
1746
+ modifiedAt: "", // Not available in vec query
1747
+ bodyLength: row.body.length,
1748
+ body: row.body,
1749
+ context: getContextForFile(db, row.filepath),
1750
+ score: 1 - bestDist, // Cosine similarity = 1 - cosine distance
1751
+ source: "vec",
1752
+ chunkPos: row.pos,
1753
+ };
1754
+ });
1755
+ }
1756
+ // =============================================================================
1757
+ // Embeddings
1758
+ // =============================================================================
1759
+ async function getEmbedding(text, model, isQuery, session) {
1760
+ // Format text using the appropriate prompt template
1761
+ const formattedText = isQuery ? formatQueryForEmbedding(text, model) : formatDocForEmbedding(text, undefined, model);
1762
+ const result = session
1763
+ ? await session.embed(formattedText, { model, isQuery })
1764
+ : await getDefaultLlamaCpp().embed(formattedText, { model, isQuery });
1765
+ return result?.embedding || null;
1766
+ }
1767
+ /**
1768
+ * Get all unique content hashes that need embeddings (from active documents).
1769
+ * Returns hash, document body, and a sample path for display purposes.
1770
+ */
1771
+ export function getHashesForEmbedding(db) {
1772
+ return db.prepare(`
1773
+ SELECT d.hash, c.doc as body, MIN(d.path) as path
1774
+ FROM documents d
1775
+ JOIN content c ON d.hash = c.hash
1776
+ LEFT JOIN content_vectors v ON d.hash = v.hash AND v.seq = 0
1777
+ WHERE d.active = 1 AND v.hash IS NULL
1778
+ GROUP BY d.hash
1779
+ `).all();
1780
+ }
1781
+ /**
1782
+ * Clear all embeddings from the database (force re-index).
1783
+ * Deletes all rows from content_vectors and drops the vectors_vec table.
1784
+ */
1785
+ export function clearAllEmbeddings(db) {
1786
+ db.exec(`DELETE FROM content_vectors`);
1787
+ db.exec(`DROP TABLE IF EXISTS vectors_vec`);
1788
+ }
1789
+ /**
1790
+ * Insert a single embedding into both content_vectors and vectors_vec tables.
1791
+ * The hash_seq key is formatted as "hash_seq" for the vectors_vec table.
1792
+ */
1793
+ export function insertEmbedding(db, hash, seq, pos, embedding, model, embeddedAt) {
1794
+ const hashSeq = `${hash}_${seq}`;
1795
+ const insertVecStmt = db.prepare(`INSERT OR REPLACE INTO vectors_vec (hash_seq, embedding) VALUES (?, ?)`);
1796
+ const insertContentVectorStmt = db.prepare(`INSERT OR REPLACE INTO content_vectors (hash, seq, pos, model, embedded_at) VALUES (?, ?, ?, ?, ?)`);
1797
+ insertVecStmt.run(hashSeq, embedding);
1798
+ insertContentVectorStmt.run(hash, seq, pos, model, embeddedAt);
1799
+ }
1800
+ // =============================================================================
1801
+ // Query expansion
1802
+ // =============================================================================
1803
+ export async function expandQuery(query, model = DEFAULT_QUERY_MODEL, db) {
1804
+ // Check cache first — stored as JSON preserving types
1805
+ const cacheKey = getCacheKey("expandQuery", { query, model });
1806
+ const cached = getCachedResult(db, cacheKey);
1807
+ if (cached) {
1808
+ try {
1809
+ return JSON.parse(cached);
1810
+ }
1811
+ catch {
1812
+ // Old cache format (pre-typed, newline-separated text) — re-expand
1813
+ }
1814
+ }
1815
+ const llm = getDefaultLlamaCpp();
1816
+ // Note: LlamaCpp uses hardcoded model, model parameter is ignored
1817
+ const results = await llm.expandQuery(query);
1818
+ // Map Queryable[] → ExpandedQuery[] (same shape, decoupled from inference.ts internals).
1819
+ // Filter out entries that duplicate the original query text.
1820
+ const expanded = results
1821
+ .filter(r => r.text !== query)
1822
+ .map(r => ({ type: r.type, text: r.text }));
1823
+ if (expanded.length > 0) {
1824
+ setCachedResult(db, cacheKey, JSON.stringify(expanded));
1825
+ }
1826
+ return expanded;
1827
+ }
1828
+ // =============================================================================
1829
+ // Reranking
1830
+ // =============================================================================
1831
+ export async function rerank(query, documents, model = DEFAULT_RERANK_MODEL, db) {
1832
+ const cachedResults = new Map();
1833
+ const uncachedDocsByChunk = new Map();
1834
+ // Check cache for each document
1835
+ // Cache key includes chunk text — different queries can select different chunks
1836
+ // from the same file, and the reranker score depends on which chunk was sent.
1837
+ // File path is excluded from the new cache key because the reranker score
1838
+ // depends on the chunk content, not where it came from.
1839
+ for (const doc of documents) {
1840
+ const cacheKey = getCacheKey("rerank", { query, model, chunk: doc.text });
1841
+ const legacyCacheKey = getCacheKey("rerank", { query, file: doc.file, model, chunk: doc.text });
1842
+ const cached = getCachedResult(db, cacheKey) ?? getCachedResult(db, legacyCacheKey);
1843
+ if (cached !== null) {
1844
+ cachedResults.set(doc.text, parseFloat(cached));
1845
+ }
1846
+ else {
1847
+ uncachedDocsByChunk.set(doc.text, { file: doc.file, text: doc.text });
1848
+ }
1849
+ }
1850
+ // Rerank uncached documents using LlamaCpp
1851
+ if (uncachedDocsByChunk.size > 0) {
1852
+ const llm = getDefaultLlamaCpp();
1853
+ const uncachedDocs = [...uncachedDocsByChunk.values()];
1854
+ const rerankResult = await llm.rerank(query, uncachedDocs, { model });
1855
+ // Cache results by chunk text so identical chunks across files are scored once.
1856
+ const textByFile = new Map(uncachedDocs.map(d => [d.file, d.text]));
1857
+ for (const result of rerankResult.results) {
1858
+ const chunk = textByFile.get(result.file) || "";
1859
+ const cacheKey = getCacheKey("rerank", { query, model, chunk });
1860
+ setCachedResult(db, cacheKey, result.score.toString());
1861
+ cachedResults.set(chunk, result.score);
1862
+ }
1863
+ }
1864
+ // Return all results sorted by score
1865
+ return documents
1866
+ .map(doc => ({ file: doc.file, score: cachedResults.get(doc.text) || 0 }))
1867
+ .sort((a, b) => b.score - a.score);
1868
+ }
1869
+ // =============================================================================
1870
+ // Reciprocal Rank Fusion
1871
+ // =============================================================================
1872
+ export function reciprocalRankFusion(resultLists, weights = [], k = 60) {
1873
+ const scores = new Map();
1874
+ for (let listIdx = 0; listIdx < resultLists.length; listIdx++) {
1875
+ const list = resultLists[listIdx];
1876
+ if (!list)
1877
+ continue;
1878
+ const weight = weights[listIdx] ?? 1.0;
1879
+ for (let rank = 0; rank < list.length; rank++) {
1880
+ const result = list[rank];
1881
+ if (!result)
1882
+ continue;
1883
+ const rrfContribution = weight / (k + rank + 1);
1884
+ const existing = scores.get(result.file);
1885
+ if (existing) {
1886
+ existing.rrfScore += rrfContribution;
1887
+ existing.topRank = Math.min(existing.topRank, rank);
1888
+ }
1889
+ else {
1890
+ scores.set(result.file, {
1891
+ result,
1892
+ rrfScore: rrfContribution,
1893
+ topRank: rank,
1894
+ });
1895
+ }
1896
+ }
1897
+ }
1898
+ // Top-rank bonus
1899
+ for (const entry of scores.values()) {
1900
+ if (entry.topRank === 0) {
1901
+ entry.rrfScore += 0.05;
1902
+ }
1903
+ else if (entry.topRank <= 2) {
1904
+ entry.rrfScore += 0.02;
1905
+ }
1906
+ }
1907
+ return Array.from(scores.values())
1908
+ .sort((a, b) => b.rrfScore - a.rrfScore)
1909
+ .map(e => ({ ...e.result, score: e.rrfScore }));
1910
+ }
1911
+ /**
1912
+ * Build per-document RRF contribution traces for explain/debug output.
1913
+ */
1914
+ export function buildRrfTrace(resultLists, weights = [], listMeta = [], k = 60) {
1915
+ const traces = new Map();
1916
+ for (let listIdx = 0; listIdx < resultLists.length; listIdx++) {
1917
+ const list = resultLists[listIdx];
1918
+ if (!list)
1919
+ continue;
1920
+ const weight = weights[listIdx] ?? 1.0;
1921
+ const meta = listMeta[listIdx] ?? {
1922
+ source: "fts",
1923
+ queryType: "original",
1924
+ query: "",
1925
+ };
1926
+ for (let rank0 = 0; rank0 < list.length; rank0++) {
1927
+ const result = list[rank0];
1928
+ if (!result)
1929
+ continue;
1930
+ const rank = rank0 + 1; // 1-indexed rank for explain output
1931
+ const contribution = weight / (k + rank);
1932
+ const existing = traces.get(result.file);
1933
+ const detail = {
1934
+ listIndex: listIdx,
1935
+ source: meta.source,
1936
+ queryType: meta.queryType,
1937
+ query: meta.query,
1938
+ rank,
1939
+ weight,
1940
+ backendScore: result.score,
1941
+ rrfContribution: contribution,
1942
+ };
1943
+ if (existing) {
1944
+ existing.baseScore += contribution;
1945
+ existing.topRank = Math.min(existing.topRank, rank);
1946
+ existing.contributions.push(detail);
1947
+ }
1948
+ else {
1949
+ traces.set(result.file, {
1950
+ contributions: [detail],
1951
+ baseScore: contribution,
1952
+ topRank: rank,
1953
+ topRankBonus: 0,
1954
+ totalScore: 0,
1955
+ });
1956
+ }
1957
+ }
1958
+ }
1959
+ for (const trace of traces.values()) {
1960
+ let bonus = 0;
1961
+ if (trace.topRank === 1)
1962
+ bonus = 0.05;
1963
+ else if (trace.topRank <= 3)
1964
+ bonus = 0.02;
1965
+ trace.topRankBonus = bonus;
1966
+ trace.totalScore = trace.baseScore + bonus;
1967
+ }
1968
+ return traces;
1969
+ }
1970
+ /**
1971
+ * Find a document by filename/path, docid (#hash), or with fuzzy matching.
1972
+ * Returns document metadata without body by default.
1973
+ *
1974
+ * Supports:
1975
+ * - Virtual paths: kindx://collection/path/to/file.md
1976
+ * - Absolute paths: /path/to/file.md
1977
+ * - Relative paths: path/to/file.md
1978
+ * - Short docid: #abc123 (first 6 chars of hash)
1979
+ */
1980
+ export function findDocument(db, filename, options = {}) {
1981
+ let filepath = filename;
1982
+ const colonMatch = filepath.match(/:(\d+)$/);
1983
+ if (colonMatch) {
1984
+ filepath = filepath.slice(0, -colonMatch[0].length);
1985
+ }
1986
+ // Check if this is a docid lookup (#abc123, abc123, "#abc123", "abc123", etc.)
1987
+ if (isDocid(filepath)) {
1988
+ const docidMatch = findDocumentByDocid(db, filepath);
1989
+ if (docidMatch) {
1990
+ filepath = docidMatch.filepath;
1991
+ }
1992
+ else {
1993
+ return { error: "not_found", query: filename, similarFiles: [] };
1994
+ }
1995
+ }
1996
+ if (filepath.startsWith('~/')) {
1997
+ filepath = homedir() + filepath.slice(1);
1998
+ }
1999
+ const bodyCol = options.includeBody ? `, content.doc as body` : ``;
2000
+ // Build computed columns
2001
+ // Note: absoluteFilepath is computed from YAML collections after query
2002
+ const selectCols = `
2003
+ 'kindx://' || d.collection || '/' || d.path as virtual_path,
2004
+ d.collection || '/' || d.path as display_path,
2005
+ d.title,
2006
+ d.hash,
2007
+ d.collection,
2008
+ d.modified_at,
2009
+ LENGTH(content.doc) as body_length
2010
+ ${bodyCol}
2011
+ `;
2012
+ // Try to match by virtual path first
2013
+ let doc = db.prepare(`
2014
+ SELECT ${selectCols}
2015
+ FROM documents d
2016
+ JOIN content ON content.hash = d.hash
2017
+ WHERE 'kindx://' || d.collection || '/' || d.path = ? AND d.active = 1
2018
+ `).get(filepath);
2019
+ // Try fuzzy match by virtual path
2020
+ if (!doc) {
2021
+ doc = db.prepare(`
2022
+ SELECT ${selectCols}
2023
+ FROM documents d
2024
+ JOIN content ON content.hash = d.hash
2025
+ WHERE 'kindx://' || d.collection || '/' || d.path LIKE ? AND d.active = 1
2026
+ LIMIT 1
2027
+ `).get(`%${filepath}`);
2028
+ }
2029
+ // Try to match by absolute path (requires looking up collection paths from YAML)
2030
+ if (!doc && !filepath.startsWith('kindx://')) {
2031
+ const collections = collectionsListCollections();
2032
+ for (const coll of collections) {
2033
+ let relativePath = null;
2034
+ // If filepath is absolute and starts with collection path, extract relative part
2035
+ if (filepath.startsWith(coll.path + '/')) {
2036
+ relativePath = filepath.slice(coll.path.length + 1);
2037
+ }
2038
+ // Otherwise treat filepath as relative to collection
2039
+ else if (!filepath.startsWith('/')) {
2040
+ relativePath = filepath;
2041
+ }
2042
+ if (relativePath) {
2043
+ doc = db.prepare(`
2044
+ SELECT ${selectCols}
2045
+ FROM documents d
2046
+ JOIN content ON content.hash = d.hash
2047
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
2048
+ `).get(coll.name, relativePath);
2049
+ if (doc)
2050
+ break;
2051
+ }
2052
+ }
2053
+ }
2054
+ if (!doc) {
2055
+ const similar = findSimilarFiles(db, filepath, 5, 5);
2056
+ return { error: "not_found", query: filename, similarFiles: similar };
2057
+ }
2058
+ // Get context using virtual path
2059
+ const virtualPath = doc.virtual_path || `kindx://${doc.collection}/${doc.display_path}`;
2060
+ const context = getContextForFile(db, virtualPath);
2061
+ return {
2062
+ filepath: virtualPath,
2063
+ displayPath: doc.display_path,
2064
+ title: doc.title,
2065
+ context,
2066
+ hash: doc.hash,
2067
+ docid: getDocid(doc.hash),
2068
+ collectionName: doc.collection,
2069
+ modifiedAt: doc.modified_at,
2070
+ bodyLength: doc.body_length,
2071
+ ...(options.includeBody && doc.body !== undefined && { body: doc.body }),
2072
+ };
2073
+ }
2074
+ /**
2075
+ * Get the body content for a document
2076
+ * Optionally slice by line range
2077
+ */
2078
+ export function getDocumentBody(db, doc, fromLine, maxLines) {
2079
+ const filepath = doc.filepath;
2080
+ // Try to resolve document by filepath (absolute or virtual)
2081
+ let row = null;
2082
+ // Try virtual path first
2083
+ if (filepath.startsWith('kindx://')) {
2084
+ row = db.prepare(`
2085
+ SELECT content.doc as body
2086
+ FROM documents d
2087
+ JOIN content ON content.hash = d.hash
2088
+ WHERE 'kindx://' || d.collection || '/' || d.path = ? AND d.active = 1
2089
+ `).get(filepath);
2090
+ }
2091
+ // Try absolute path by looking up in YAML collections
2092
+ if (!row) {
2093
+ const collections = collectionsListCollections();
2094
+ for (const coll of collections) {
2095
+ if (filepath.startsWith(coll.path + '/')) {
2096
+ const relativePath = filepath.slice(coll.path.length + 1);
2097
+ row = db.prepare(`
2098
+ SELECT content.doc as body
2099
+ FROM documents d
2100
+ JOIN content ON content.hash = d.hash
2101
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
2102
+ `).get(coll.name, relativePath);
2103
+ if (row)
2104
+ break;
2105
+ }
2106
+ }
2107
+ }
2108
+ if (!row)
2109
+ return null;
2110
+ let body = row.body;
2111
+ if (fromLine !== undefined || maxLines !== undefined) {
2112
+ const lines = body.split('\n');
2113
+ const start = (fromLine || 1) - 1;
2114
+ const end = maxLines !== undefined ? start + maxLines : lines.length;
2115
+ body = lines.slice(start, end).join('\n');
2116
+ }
2117
+ return body;
2118
+ }
2119
+ /**
2120
+ * Find multiple documents by glob pattern or comma-separated list
2121
+ * Returns documents without body by default (use getDocumentBody to load)
2122
+ */
2123
+ export function findDocuments(db, pattern, options = {}) {
2124
+ const isCommaSeparated = pattern.includes(',') && !pattern.includes('*') && !pattern.includes('?');
2125
+ const errors = [];
2126
+ const maxBytes = options.maxBytes ?? DEFAULT_MULTI_GET_MAX_BYTES;
2127
+ const bodyCol = options.includeBody ? `, content.doc as body` : ``;
2128
+ const selectCols = `
2129
+ 'kindx://' || d.collection || '/' || d.path as virtual_path,
2130
+ d.collection || '/' || d.path as display_path,
2131
+ d.title,
2132
+ d.hash,
2133
+ d.collection,
2134
+ d.modified_at,
2135
+ LENGTH(content.doc) as body_length
2136
+ ${bodyCol}
2137
+ `;
2138
+ let fileRows;
2139
+ if (isCommaSeparated) {
2140
+ const names = pattern.split(',').map(s => s.trim()).filter(Boolean);
2141
+ fileRows = [];
2142
+ for (const name of names) {
2143
+ let doc = db.prepare(`
2144
+ SELECT ${selectCols}
2145
+ FROM documents d
2146
+ JOIN content ON content.hash = d.hash
2147
+ WHERE 'kindx://' || d.collection || '/' || d.path = ? AND d.active = 1
2148
+ `).get(name);
2149
+ if (!doc) {
2150
+ doc = db.prepare(`
2151
+ SELECT ${selectCols}
2152
+ FROM documents d
2153
+ JOIN content ON content.hash = d.hash
2154
+ WHERE 'kindx://' || d.collection || '/' || d.path LIKE ? AND d.active = 1
2155
+ LIMIT 1
2156
+ `).get(`%${name}`);
2157
+ }
2158
+ if (doc) {
2159
+ fileRows.push(doc);
2160
+ }
2161
+ else {
2162
+ const similar = findSimilarFiles(db, name, 5, 3);
2163
+ let msg = `File not found: ${name}`;
2164
+ if (similar.length > 0) {
2165
+ msg += ` (did you mean: ${similar.join(', ')}?)`;
2166
+ }
2167
+ errors.push(msg);
2168
+ }
2169
+ }
2170
+ }
2171
+ else {
2172
+ // Glob pattern match
2173
+ const matched = matchFilesByGlob(db, pattern);
2174
+ if (matched.length === 0) {
2175
+ errors.push(`No files matched pattern: ${pattern}`);
2176
+ return { docs: [], errors };
2177
+ }
2178
+ const virtualPaths = matched.map(m => m.filepath);
2179
+ const placeholders = virtualPaths.map(() => '?').join(',');
2180
+ fileRows = db.prepare(`
2181
+ SELECT ${selectCols}
2182
+ FROM documents d
2183
+ JOIN content ON content.hash = d.hash
2184
+ WHERE 'kindx://' || d.collection || '/' || d.path IN (${placeholders}) AND d.active = 1
2185
+ `).all(...virtualPaths);
2186
+ }
2187
+ const results = [];
2188
+ for (const row of fileRows) {
2189
+ // Get context using virtual path
2190
+ const virtualPath = row.virtual_path || `kindx://${row.collection}/${row.display_path}`;
2191
+ const context = getContextForFile(db, virtualPath);
2192
+ if (row.body_length > maxBytes) {
2193
+ results.push({
2194
+ doc: { filepath: virtualPath, displayPath: row.display_path },
2195
+ skipped: true,
2196
+ skipReason: `File too large (${Math.round(row.body_length / 1024)}KB > ${Math.round(maxBytes / 1024)}KB)`,
2197
+ });
2198
+ continue;
2199
+ }
2200
+ results.push({
2201
+ doc: {
2202
+ filepath: virtualPath,
2203
+ displayPath: row.display_path,
2204
+ title: row.title || row.display_path.split('/').pop() || row.display_path,
2205
+ context,
2206
+ hash: row.hash,
2207
+ docid: getDocid(row.hash),
2208
+ collectionName: row.collection,
2209
+ modifiedAt: row.modified_at,
2210
+ bodyLength: row.body_length,
2211
+ ...(options.includeBody && row.body !== undefined && { body: row.body }),
2212
+ },
2213
+ skipped: false,
2214
+ });
2215
+ }
2216
+ return { docs: results, errors };
2217
+ }
2218
+ // =============================================================================
2219
+ // Status
2220
+ // =============================================================================
2221
+ export function getStatus(db) {
2222
+ // Load collections from YAML
2223
+ const yamlCollections = collectionsListCollections();
2224
+ // Get document counts and last update times for each collection
2225
+ const collections = yamlCollections.map(col => {
2226
+ const stats = db.prepare(`
2227
+ SELECT
2228
+ COUNT(*) as active_count,
2229
+ MAX(modified_at) as last_doc_update
2230
+ FROM documents
2231
+ WHERE collection = ? AND active = 1
2232
+ `).get(col.name);
2233
+ return {
2234
+ name: col.name,
2235
+ path: col.path,
2236
+ pattern: col.pattern,
2237
+ documents: stats.active_count,
2238
+ lastUpdated: stats.last_doc_update || new Date().toISOString(),
2239
+ };
2240
+ });
2241
+ // Sort by last update time (most recent first)
2242
+ collections.sort((a, b) => {
2243
+ if (!a.lastUpdated)
2244
+ return 1;
2245
+ if (!b.lastUpdated)
2246
+ return -1;
2247
+ return new Date(b.lastUpdated).getTime() - new Date(a.lastUpdated).getTime();
2248
+ });
2249
+ const totalDocs = db.prepare(`SELECT COUNT(*) as c FROM documents WHERE active = 1`).get().c;
2250
+ const needsEmbedding = getHashesNeedingEmbedding(db);
2251
+ const hasVectors = !!db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
2252
+ return {
2253
+ totalDocuments: totalDocs,
2254
+ needsEmbedding,
2255
+ hasVectorIndex: hasVectors,
2256
+ collections,
2257
+ };
2258
+ }
2259
+ export function extractSnippet(body, query, maxLen = 500, chunkPos, chunkLen) {
2260
+ const totalLines = body.split('\n').length;
2261
+ let searchBody = body;
2262
+ let lineOffset = 0;
2263
+ if (chunkPos && chunkPos > 0) {
2264
+ // Search within the chunk region, with some padding for context
2265
+ // Use provided chunkLen or fall back to max chunk size (covers variable-length chunks)
2266
+ const searchLen = chunkLen || CHUNK_SIZE_CHARS;
2267
+ const contextStart = Math.max(0, chunkPos - 100);
2268
+ const contextEnd = Math.min(body.length, chunkPos + searchLen + 100);
2269
+ searchBody = body.slice(contextStart, contextEnd);
2270
+ if (contextStart > 0) {
2271
+ lineOffset = body.slice(0, contextStart).split('\n').length - 1;
2272
+ }
2273
+ }
2274
+ const lines = searchBody.split('\n');
2275
+ const queryTerms = query.toLowerCase().split(/\s+/).filter(t => t.length > 0);
2276
+ let bestLine = 0, bestScore = -1;
2277
+ for (let i = 0; i < lines.length; i++) {
2278
+ const lineLower = (lines[i] ?? "").toLowerCase();
2279
+ let score = 0;
2280
+ for (const term of queryTerms) {
2281
+ if (lineLower.includes(term))
2282
+ score++;
2283
+ }
2284
+ if (score > bestScore) {
2285
+ bestScore = score;
2286
+ bestLine = i;
2287
+ }
2288
+ }
2289
+ const start = Math.max(0, bestLine - 1);
2290
+ const end = Math.min(lines.length, bestLine + 3);
2291
+ const snippetLines = lines.slice(start, end);
2292
+ let snippetText = snippetLines.join('\n');
2293
+ // If we focused on a chunk window and it produced an empty/whitespace-only snippet,
2294
+ // fall back to a full-document snippet so we always show something useful.
2295
+ if (chunkPos && chunkPos > 0 && snippetText.trim().length === 0) {
2296
+ return extractSnippet(body, query, maxLen, undefined);
2297
+ }
2298
+ if (snippetText.length > maxLen)
2299
+ snippetText = snippetText.substring(0, maxLen - 3) + "...";
2300
+ const absoluteStart = lineOffset + start + 1; // 1-indexed
2301
+ const snippetLineCount = snippetLines.length;
2302
+ const linesBefore = absoluteStart - 1;
2303
+ const linesAfter = totalLines - (absoluteStart + snippetLineCount - 1);
2304
+ // Format with diff-style header: @@ -start,count @@ (linesBefore before, linesAfter after)
2305
+ const header = `@@ -${absoluteStart},${snippetLineCount} @@ (${linesBefore} before, ${linesAfter} after)`;
2306
+ const snippet = `${header}\n${snippetText}`;
2307
+ return {
2308
+ line: lineOffset + bestLine + 1,
2309
+ snippet,
2310
+ linesBefore,
2311
+ linesAfter,
2312
+ snippetLines: snippetLineCount,
2313
+ };
2314
+ }
2315
+ // =============================================================================
2316
+ // Shared helpers (used by both CLI and MCP)
2317
+ // =============================================================================
2318
+ /**
2319
+ * Add line numbers to text content.
2320
+ * Each line becomes: "{lineNum}: {content}"
2321
+ */
2322
+ export function addLineNumbers(text, startLine = 1) {
2323
+ const lines = text.split('\n');
2324
+ return lines.map((line, i) => `${startLine + i}: ${line}`).join('\n');
2325
+ }
2326
+ /**
2327
+ * Hybrid search: BM25 + vector + query expansion + RRF + chunked reranking.
2328
+ *
2329
+ * Pipeline:
2330
+ * 1. BM25 probe → skip expansion if strong signal
2331
+ * 2. expandQuery() → typed query variants (lex/vec/hyde)
2332
+ * 3. Type-routed search: original→vector, lex→FTS, vec/hyde→vector
2333
+ * 4. RRF fusion → slice to candidateLimit
2334
+ * 5. chunkDocument() + keyword-best-chunk selection
2335
+ * 6. rerank on chunks (NOT full bodies — O(tokens) trap)
2336
+ * 7. Position-aware score blending (RRF rank × reranker score)
2337
+ * 8. Dedup by file, filter by minScore, slice to limit
2338
+ */
2339
+ export async function hybridQuery(store, query, options) {
2340
+ const limit = options?.limit ?? 10;
2341
+ const minScore = options?.minScore ?? 0;
2342
+ const candidateLimit = options?.candidateLimit ?? RERANK_CANDIDATE_LIMIT;
2343
+ const collection = options?.collection;
2344
+ const explain = options?.explain ?? false;
2345
+ const hooks = options?.hooks;
2346
+ const rankedLists = [];
2347
+ const rankedListMeta = [];
2348
+ const docidMap = new Map(); // filepath -> docid
2349
+ const hasVectors = !!store.db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
2350
+ // Step 1: BM25 probe — strong signal skips expensive LLM expansion
2351
+ // Pass collection directly into FTS query (filter at SQL level, not post-hoc)
2352
+ const initialFts = store.searchFTS(query, 20, collection);
2353
+ const topScore = initialFts[0]?.score ?? 0;
2354
+ const secondScore = initialFts[1]?.score ?? 0;
2355
+ const hasStrongSignal = initialFts.length > 0
2356
+ && topScore >= STRONG_SIGNAL_MIN_SCORE
2357
+ && (topScore - secondScore) >= STRONG_SIGNAL_MIN_GAP;
2358
+ if (hasStrongSignal)
2359
+ hooks?.onStrongSignal?.(topScore);
2360
+ // Step 2: Expand query (or skip if strong signal)
2361
+ hooks?.onExpandStart?.();
2362
+ const expandStart = Date.now();
2363
+ const expanded = hasStrongSignal
2364
+ ? []
2365
+ : await store.expandQuery(query);
2366
+ hooks?.onExpand?.(query, expanded, Date.now() - expandStart);
2367
+ // Seed with initial FTS results (avoid re-running original query FTS)
2368
+ if (initialFts.length > 0) {
2369
+ for (const r of initialFts)
2370
+ docidMap.set(r.filepath, r.docid);
2371
+ rankedLists.push(initialFts.map(r => ({
2372
+ file: r.filepath, displayPath: r.displayPath,
2373
+ title: r.title, body: r.body || "", score: r.score,
2374
+ })));
2375
+ rankedListMeta.push({ source: "fts", queryType: "original", query });
2376
+ }
2377
+ // Step 3: Route searches by query type
2378
+ //
2379
+ // Strategy: run all FTS queries immediately (they're sync/instant), then
2380
+ // batch-embed all vector queries in one embedBatch() call, then run
2381
+ // sqlite-vec lookups with pre-computed embeddings.
2382
+ // 3a: Run FTS for all lex expansions right away (no LLM needed)
2383
+ for (const q of expanded) {
2384
+ if (q.type === 'lex') {
2385
+ const ftsResults = store.searchFTS(q.text, 20, collection);
2386
+ if (ftsResults.length > 0) {
2387
+ for (const r of ftsResults)
2388
+ docidMap.set(r.filepath, r.docid);
2389
+ rankedLists.push(ftsResults.map(r => ({
2390
+ file: r.filepath, displayPath: r.displayPath,
2391
+ title: r.title, body: r.body || "", score: r.score,
2392
+ })));
2393
+ rankedListMeta.push({ source: "fts", queryType: "lex", query: q.text });
2394
+ }
2395
+ }
2396
+ }
2397
+ // 3b: Collect all texts that need vector search (original query + vec/hyde expansions)
2398
+ if (hasVectors) {
2399
+ const vecQueries = [
2400
+ { text: query, queryType: "original" },
2401
+ ];
2402
+ for (const q of expanded) {
2403
+ if (q.type === 'vec' || q.type === 'hyde') {
2404
+ vecQueries.push({ text: q.text, queryType: q.type });
2405
+ }
2406
+ }
2407
+ // Batch embed all vector queries in a single call
2408
+ const llm = getDefaultLlamaCpp();
2409
+ const textsToEmbed = vecQueries.map(q => formatQueryForEmbedding(q.text));
2410
+ hooks?.onEmbedStart?.(textsToEmbed.length);
2411
+ const embedStart = Date.now();
2412
+ const embeddings = await llm.embedBatch(textsToEmbed);
2413
+ hooks?.onEmbedDone?.(Date.now() - embedStart);
2414
+ // Run sqlite-vec lookups with pre-computed embeddings
2415
+ for (let i = 0; i < vecQueries.length; i++) {
2416
+ const embedding = embeddings[i]?.embedding;
2417
+ if (!embedding)
2418
+ continue;
2419
+ const vecResults = await store.searchVec(vecQueries[i].text, DEFAULT_EMBED_MODEL, 20, collection, undefined, embedding);
2420
+ if (vecResults.length > 0) {
2421
+ for (const r of vecResults)
2422
+ docidMap.set(r.filepath, r.docid);
2423
+ rankedLists.push(vecResults.map(r => ({
2424
+ file: r.filepath, displayPath: r.displayPath,
2425
+ title: r.title, body: r.body || "", score: r.score,
2426
+ })));
2427
+ rankedListMeta.push({
2428
+ source: "vec",
2429
+ queryType: vecQueries[i].queryType,
2430
+ query: vecQueries[i].text,
2431
+ });
2432
+ }
2433
+ }
2434
+ }
2435
+ // Step 4: RRF fusion — first 2 lists (original FTS + first vec) get 2x weight
2436
+ const weights = rankedLists.map((_, i) => i < 2 ? 2.0 : 1.0);
2437
+ const fused = reciprocalRankFusion(rankedLists, weights);
2438
+ const rrfTraceByFile = explain ? buildRrfTrace(rankedLists, weights, rankedListMeta) : null;
2439
+ const candidates = fused.slice(0, candidateLimit);
2440
+ if (candidates.length === 0)
2441
+ return [];
2442
+ // Step 5: Chunk documents, pick best chunk per doc for reranking.
2443
+ // Reranking full bodies is O(tokens) — the critical perf lesson that motivated this refactor.
2444
+ const queryTerms = query.toLowerCase().split(/\s+/).filter(t => t.length > 2);
2445
+ const chunksToRerank = [];
2446
+ const docChunkMap = new Map();
2447
+ for (const cand of candidates) {
2448
+ const chunks = chunkDocument(cand.body);
2449
+ if (chunks.length === 0)
2450
+ continue;
2451
+ // Pick chunk with most keyword overlap (fallback: first chunk)
2452
+ let bestIdx = 0;
2453
+ let bestScore = -1;
2454
+ for (let i = 0; i < chunks.length; i++) {
2455
+ const chunkLower = chunks[i].text.toLowerCase();
2456
+ const score = queryTerms.reduce((acc, term) => acc + (chunkLower.includes(term) ? 1 : 0), 0);
2457
+ if (score > bestScore) {
2458
+ bestScore = score;
2459
+ bestIdx = i;
2460
+ }
2461
+ }
2462
+ chunksToRerank.push({ file: cand.file, text: chunks[bestIdx].text });
2463
+ docChunkMap.set(cand.file, { chunks, bestIdx });
2464
+ }
2465
+ // Step 6: Rerank chunks (NOT full bodies)
2466
+ hooks?.onRerankStart?.(chunksToRerank.length);
2467
+ const rerankStart = Date.now();
2468
+ const reranked = await store.rerank(query, chunksToRerank);
2469
+ hooks?.onRerankDone?.(Date.now() - rerankStart);
2470
+ // Step 7: Blend RRF position score with reranker score
2471
+ // Position-aware weights: top retrieval results get more protection from reranker disagreement
2472
+ const candidateMap = new Map(candidates.map(c => [c.file, {
2473
+ displayPath: c.displayPath, title: c.title, body: c.body,
2474
+ }]));
2475
+ const rrfRankMap = new Map(candidates.map((c, i) => [c.file, i + 1]));
2476
+ const blended = reranked.map(r => {
2477
+ const rrfRank = rrfRankMap.get(r.file) || candidateLimit;
2478
+ let rrfWeight;
2479
+ if (rrfRank <= 3)
2480
+ rrfWeight = 0.75;
2481
+ else if (rrfRank <= 10)
2482
+ rrfWeight = 0.60;
2483
+ else
2484
+ rrfWeight = 0.40;
2485
+ const rrfScore = 1 / rrfRank;
2486
+ const blendedScore = rrfWeight * rrfScore + (1 - rrfWeight) * r.score;
2487
+ const candidate = candidateMap.get(r.file);
2488
+ const chunkInfo = docChunkMap.get(r.file);
2489
+ const bestIdx = chunkInfo?.bestIdx ?? 0;
2490
+ const bestChunk = chunkInfo?.chunks[bestIdx]?.text || candidate?.body || "";
2491
+ const bestChunkPos = chunkInfo?.chunks[bestIdx]?.pos || 0;
2492
+ const trace = rrfTraceByFile?.get(r.file);
2493
+ const explainData = explain ? {
2494
+ ftsScores: trace?.contributions.filter(c => c.source === "fts").map(c => c.backendScore) ?? [],
2495
+ vectorScores: trace?.contributions.filter(c => c.source === "vec").map(c => c.backendScore) ?? [],
2496
+ rrf: {
2497
+ rank: rrfRank,
2498
+ positionScore: rrfScore,
2499
+ weight: rrfWeight,
2500
+ baseScore: trace?.baseScore ?? 0,
2501
+ topRankBonus: trace?.topRankBonus ?? 0,
2502
+ totalScore: trace?.totalScore ?? 0,
2503
+ contributions: trace?.contributions ?? [],
2504
+ },
2505
+ rerankScore: r.score,
2506
+ blendedScore,
2507
+ } : undefined;
2508
+ return {
2509
+ file: r.file,
2510
+ displayPath: candidate?.displayPath || "",
2511
+ title: candidate?.title || "",
2512
+ body: candidate?.body || "",
2513
+ bestChunk,
2514
+ bestChunkPos,
2515
+ score: blendedScore,
2516
+ context: store.getContextForFile(r.file),
2517
+ docid: docidMap.get(r.file) || "",
2518
+ ...(explainData ? { explain: explainData } : {}),
2519
+ };
2520
+ }).sort((a, b) => b.score - a.score);
2521
+ // Step 8: Dedup by file (safety net — prevents duplicate output)
2522
+ const seenFiles = new Set();
2523
+ return blended
2524
+ .filter(r => {
2525
+ if (seenFiles.has(r.file))
2526
+ return false;
2527
+ seenFiles.add(r.file);
2528
+ return true;
2529
+ })
2530
+ .filter(r => r.score >= minScore)
2531
+ .slice(0, limit);
2532
+ }
2533
+ /**
2534
+ * Vector-only semantic search with query expansion.
2535
+ *
2536
+ * Pipeline:
2537
+ * 1. expandQuery() → typed variants, filter to vec/hyde only (lex irrelevant here)
2538
+ * 2. searchVec() for original + vec/hyde variants (sequential — node-llama-cpp embed limitation)
2539
+ * 3. Dedup by filepath (keep max score)
2540
+ * 4. Sort by score descending, filter by minScore, slice to limit
2541
+ */
2542
+ export async function vectorSearchQuery(store, query, options) {
2543
+ const limit = options?.limit ?? 10;
2544
+ const minScore = options?.minScore ?? 0.3;
2545
+ const collection = options?.collection;
2546
+ const hasVectors = !!store.db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
2547
+ if (!hasVectors)
2548
+ return [];
2549
+ // Expand query — filter to vec/hyde only (lex queries target FTS, not vector)
2550
+ const expandStart = Date.now();
2551
+ const allExpanded = await store.expandQuery(query);
2552
+ const vecExpanded = allExpanded.filter(q => q.type !== 'lex');
2553
+ options?.hooks?.onExpand?.(query, vecExpanded, Date.now() - expandStart);
2554
+ // Run original + vec/hyde expanded through vector, sequentially — concurrent embed() hangs
2555
+ const queryTexts = [query, ...vecExpanded.map(q => q.text)];
2556
+ const allResults = new Map();
2557
+ for (const q of queryTexts) {
2558
+ const vecResults = await store.searchVec(q, DEFAULT_EMBED_MODEL, limit, collection);
2559
+ for (const r of vecResults) {
2560
+ const existing = allResults.get(r.filepath);
2561
+ if (!existing || r.score > existing.score) {
2562
+ allResults.set(r.filepath, {
2563
+ file: r.filepath,
2564
+ displayPath: r.displayPath,
2565
+ title: r.title,
2566
+ body: r.body || "",
2567
+ score: r.score,
2568
+ context: store.getContextForFile(r.filepath),
2569
+ docid: r.docid,
2570
+ });
2571
+ }
2572
+ }
2573
+ }
2574
+ return Array.from(allResults.values())
2575
+ .sort((a, b) => b.score - a.score)
2576
+ .filter(r => r.score >= minScore)
2577
+ .slice(0, limit);
2578
+ }
2579
+ /**
2580
+ * Structured search: execute pre-expanded queries without LLM query expansion.
2581
+ *
2582
+ * Designed for LLM callers (MCP/HTTP) that generate their own query expansions.
2583
+ * Skips the internal expandQuery() step — goes directly to:
2584
+ *
2585
+ * Pipeline:
2586
+ * 1. Route searches: lex→FTS, vec/hyde→vector (batch embed)
2587
+ * 2. RRF fusion across all result lists
2588
+ * 3. Chunk documents + keyword-best-chunk selection
2589
+ * 4. Rerank on chunks
2590
+ * 5. Position-aware score blending
2591
+ * 6. Dedup, filter, slice
2592
+ *
2593
+ * This is the recommended endpoint for capable LLMs — they can generate
2594
+ * better query variations than our small local model, especially for
2595
+ * domain-specific or nuanced queries.
2596
+ */
2597
+ export async function structuredSearch(store, searches, options) {
2598
+ const limit = options?.limit ?? 10;
2599
+ const minScore = options?.minScore ?? 0;
2600
+ const candidateLimit = options?.candidateLimit ?? RERANK_CANDIDATE_LIMIT;
2601
+ const explain = options?.explain ?? false;
2602
+ const hooks = options?.hooks;
2603
+ const collections = options?.collections;
2604
+ if (searches.length === 0)
2605
+ return [];
2606
+ // Validate queries before executing
2607
+ for (const search of searches) {
2608
+ const location = search.line ? `Line ${search.line}` : 'Structured search';
2609
+ if (/[\r\n]/.test(search.query)) {
2610
+ throw new Error(`${location} (${search.type}): queries must be single-line. Remove newline characters.`);
2611
+ }
2612
+ if (search.type === 'lex') {
2613
+ const error = validateLexQuery(search.query);
2614
+ if (error) {
2615
+ throw new Error(`${location} (lex): ${error}`);
2616
+ }
2617
+ }
2618
+ else if (search.type === 'vec' || search.type === 'hyde') {
2619
+ const error = validateSemanticQuery(search.query);
2620
+ if (error) {
2621
+ throw new Error(`${location} (${search.type}): ${error}`);
2622
+ }
2623
+ }
2624
+ }
2625
+ const rankedLists = [];
2626
+ const rankedListMeta = [];
2627
+ const docidMap = new Map(); // filepath -> docid
2628
+ const hasVectors = !!store.db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
2629
+ // Helper to run search across collections (or all if undefined)
2630
+ const collectionList = collections ?? [undefined]; // undefined = all collections
2631
+ // Step 1: Run FTS for all lex searches (sync, instant)
2632
+ for (const search of searches) {
2633
+ if (search.type === 'lex') {
2634
+ for (const coll of collectionList) {
2635
+ const ftsResults = store.searchFTS(search.query, 20, coll);
2636
+ if (ftsResults.length > 0) {
2637
+ for (const r of ftsResults)
2638
+ docidMap.set(r.filepath, r.docid);
2639
+ rankedLists.push(ftsResults.map(r => ({
2640
+ file: r.filepath, displayPath: r.displayPath,
2641
+ title: r.title, body: r.body || "", score: r.score,
2642
+ })));
2643
+ rankedListMeta.push({
2644
+ source: "fts",
2645
+ queryType: "lex",
2646
+ query: search.query,
2647
+ });
2648
+ }
2649
+ }
2650
+ }
2651
+ }
2652
+ // Step 2: Batch embed and run vector searches for vec/hyde
2653
+ if (hasVectors) {
2654
+ const vecSearches = searches.filter((s) => s.type === 'vec' || s.type === 'hyde');
2655
+ if (vecSearches.length > 0) {
2656
+ const llm = getDefaultLlamaCpp();
2657
+ const textsToEmbed = vecSearches.map(s => formatQueryForEmbedding(s.query));
2658
+ hooks?.onEmbedStart?.(textsToEmbed.length);
2659
+ const embedStart = Date.now();
2660
+ const embeddings = await llm.embedBatch(textsToEmbed);
2661
+ hooks?.onEmbedDone?.(Date.now() - embedStart);
2662
+ for (let i = 0; i < vecSearches.length; i++) {
2663
+ const embedding = embeddings[i]?.embedding;
2664
+ if (!embedding)
2665
+ continue;
2666
+ for (const coll of collectionList) {
2667
+ const vecResults = await store.searchVec(vecSearches[i].query, DEFAULT_EMBED_MODEL, 20, coll, undefined, embedding);
2668
+ if (vecResults.length > 0) {
2669
+ for (const r of vecResults)
2670
+ docidMap.set(r.filepath, r.docid);
2671
+ rankedLists.push(vecResults.map(r => ({
2672
+ file: r.filepath, displayPath: r.displayPath,
2673
+ title: r.title, body: r.body || "", score: r.score,
2674
+ })));
2675
+ rankedListMeta.push({
2676
+ source: "vec",
2677
+ queryType: vecSearches[i].type,
2678
+ query: vecSearches[i].query,
2679
+ });
2680
+ }
2681
+ }
2682
+ }
2683
+ }
2684
+ }
2685
+ if (rankedLists.length === 0)
2686
+ return [];
2687
+ // Step 3: RRF fusion — first list gets 2x weight (assume caller ordered by importance)
2688
+ const weights = rankedLists.map((_, i) => i === 0 ? 2.0 : 1.0);
2689
+ const fused = reciprocalRankFusion(rankedLists, weights);
2690
+ const rrfTraceByFile = explain ? buildRrfTrace(rankedLists, weights, rankedListMeta) : null;
2691
+ const candidates = fused.slice(0, candidateLimit);
2692
+ if (candidates.length === 0)
2693
+ return [];
2694
+ hooks?.onExpand?.("", [], 0); // Signal no expansion (pre-expanded)
2695
+ // Step 4: Chunk documents, pick best chunk per doc for reranking
2696
+ // Use first lex query as the "query" for keyword matching, or first vec if no lex
2697
+ const primaryQuery = searches.find(s => s.type === 'lex')?.query
2698
+ || searches.find(s => s.type === 'vec')?.query
2699
+ || searches[0]?.query || "";
2700
+ const queryTerms = primaryQuery.toLowerCase().split(/\s+/).filter(t => t.length > 2);
2701
+ const chunksToRerank = [];
2702
+ const docChunkMap = new Map();
2703
+ for (const cand of candidates) {
2704
+ const chunks = chunkDocument(cand.body);
2705
+ if (chunks.length === 0)
2706
+ continue;
2707
+ // Pick chunk with most keyword overlap
2708
+ let bestIdx = 0;
2709
+ let bestScore = -1;
2710
+ for (let i = 0; i < chunks.length; i++) {
2711
+ const chunkLower = chunks[i].text.toLowerCase();
2712
+ const score = queryTerms.reduce((acc, term) => acc + (chunkLower.includes(term) ? 1 : 0), 0);
2713
+ if (score > bestScore) {
2714
+ bestScore = score;
2715
+ bestIdx = i;
2716
+ }
2717
+ }
2718
+ chunksToRerank.push({ file: cand.file, text: chunks[bestIdx].text });
2719
+ docChunkMap.set(cand.file, { chunks, bestIdx });
2720
+ }
2721
+ // Step 5: Rerank chunks
2722
+ hooks?.onRerankStart?.(chunksToRerank.length);
2723
+ const rerankStart2 = Date.now();
2724
+ const reranked = await store.rerank(primaryQuery, chunksToRerank);
2725
+ hooks?.onRerankDone?.(Date.now() - rerankStart2);
2726
+ // Step 6: Blend RRF position score with reranker score
2727
+ const candidateMap = new Map(candidates.map(c => [c.file, {
2728
+ displayPath: c.displayPath, title: c.title, body: c.body,
2729
+ }]));
2730
+ const rrfRankMap = new Map(candidates.map((c, i) => [c.file, i + 1]));
2731
+ const blended = reranked.map(r => {
2732
+ const rrfRank = rrfRankMap.get(r.file) || candidateLimit;
2733
+ let rrfWeight;
2734
+ if (rrfRank <= 3)
2735
+ rrfWeight = 0.75;
2736
+ else if (rrfRank <= 10)
2737
+ rrfWeight = 0.60;
2738
+ else
2739
+ rrfWeight = 0.40;
2740
+ const rrfScore = 1 / rrfRank;
2741
+ const blendedScore = rrfWeight * rrfScore + (1 - rrfWeight) * r.score;
2742
+ const candidate = candidateMap.get(r.file);
2743
+ const chunkInfo = docChunkMap.get(r.file);
2744
+ const bestIdx = chunkInfo?.bestIdx ?? 0;
2745
+ const bestChunk = chunkInfo?.chunks[bestIdx]?.text || candidate?.body || "";
2746
+ const bestChunkPos = chunkInfo?.chunks[bestIdx]?.pos || 0;
2747
+ const trace = rrfTraceByFile?.get(r.file);
2748
+ const explainData = explain ? {
2749
+ ftsScores: trace?.contributions.filter(c => c.source === "fts").map(c => c.backendScore) ?? [],
2750
+ vectorScores: trace?.contributions.filter(c => c.source === "vec").map(c => c.backendScore) ?? [],
2751
+ rrf: {
2752
+ rank: rrfRank,
2753
+ positionScore: rrfScore,
2754
+ weight: rrfWeight,
2755
+ baseScore: trace?.baseScore ?? 0,
2756
+ topRankBonus: trace?.topRankBonus ?? 0,
2757
+ totalScore: trace?.totalScore ?? 0,
2758
+ contributions: trace?.contributions ?? [],
2759
+ },
2760
+ rerankScore: r.score,
2761
+ blendedScore,
2762
+ } : undefined;
2763
+ return {
2764
+ file: r.file,
2765
+ displayPath: candidate?.displayPath || "",
2766
+ title: candidate?.title || "",
2767
+ body: candidate?.body || "",
2768
+ bestChunk,
2769
+ bestChunkPos,
2770
+ score: blendedScore,
2771
+ context: store.getContextForFile(r.file),
2772
+ docid: docidMap.get(r.file) || "",
2773
+ ...(explainData ? { explain: explainData } : {}),
2774
+ };
2775
+ }).sort((a, b) => b.score - a.score);
2776
+ // Step 7: Dedup by file
2777
+ const seenFiles = new Set();
2778
+ return blended
2779
+ .filter(r => {
2780
+ if (seenFiles.has(r.file))
2781
+ return false;
2782
+ seenFiles.add(r.file);
2783
+ return true;
2784
+ })
2785
+ .filter(r => r.score >= minScore)
2786
+ .slice(0, limit);
2787
+ }