store.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  1. /**
  2. * QMD Store - Core data access and retrieval functions
  3. *
  4. * This module provides all database operations, search functions, and document
  5. * retrieval for QMD. It returns raw data structures that can be formatted by
  6. * CLI or MCP consumers.
  7. *
  8. * Usage:
  9. * const store = createStore("/path/to/db.sqlite");
  10. * // or use default path:
  11. * const store = createStore();
  12. */
  13. import { Database } from "bun:sqlite";
  14. import { Glob } from "bun";
  15. import * as sqliteVec from "sqlite-vec";
  16. import {
  17. Ollama,
  18. getDefaultOllama,
  19. formatQueryForEmbedding,
  20. formatDocForEmbedding,
  21. type RerankDocument,
  22. } from "./llm";
  23. // =============================================================================
  24. // Configuration
  25. // =============================================================================
  26. const HOME = Bun.env.HOME || "/tmp";
  27. export const DEFAULT_EMBED_MODEL = "embeddinggemma";
  28. export const DEFAULT_RERANK_MODEL = "ExpedientFalcon/qwen3-reranker:0.6b-q8_0";
  29. export const DEFAULT_QUERY_MODEL = "qwen3:0.6b";
  30. export const DEFAULT_GLOB = "**/*.md";
  31. export const DEFAULT_MULTI_GET_MAX_BYTES = 10 * 1024; // 10KB
  32. // Re-export OLLAMA_URL for backwards compatibility
  33. export const OLLAMA_URL = getDefaultOllama().getBaseUrl();
  34. // Chunking: ~2000 tokens per chunk, ~3 bytes/token = 6KB
  35. const CHUNK_BYTE_SIZE = 6 * 1024;
  36. // =============================================================================
  37. // Path utilities
  38. // =============================================================================
  39. export function homedir(): string {
  40. return HOME;
  41. }
  42. export function resolve(...paths: string[]): string {
  43. let result = paths[0].startsWith('/') ? '' : Bun.env.PWD || process.cwd();
  44. for (const p of paths) {
  45. if (p.startsWith('/')) {
  46. result = p;
  47. } else {
  48. result = result + '/' + p;
  49. }
  50. }
  51. const parts = result.split('/').filter(Boolean);
  52. const normalized: string[] = [];
  53. for (const part of parts) {
  54. if (part === '..') normalized.pop();
  55. else if (part !== '.') normalized.push(part);
  56. }
  57. return '/' + normalized.join('/');
  58. }
  59. export function getDefaultDbPath(indexName: string = "index"): string {
  60. const cacheDir = Bun.env.XDG_CACHE_HOME || resolve(homedir(), ".cache");
  61. const qmdCacheDir = resolve(cacheDir, "qmd");
  62. try { Bun.spawnSync(["mkdir", "-p", qmdCacheDir]); } catch {}
  63. return resolve(qmdCacheDir, `${indexName}.sqlite`);
  64. }
  65. export function getPwd(): string {
  66. return process.env.PWD || process.cwd();
  67. }
  68. export function getRealPath(path: string): string {
  69. try {
  70. const result = Bun.spawnSync(["realpath", path]);
  71. if (result.success) {
  72. return result.stdout.toString().trim();
  73. }
  74. } catch {}
  75. return resolve(path);
  76. }
  77. // =============================================================================
  78. // Database initialization
  79. // =============================================================================
  80. // On macOS, use Homebrew's SQLite which supports extensions
  81. if (process.platform === "darwin") {
  82. const homebrewSqlitePath = "/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib";
  83. try {
  84. if (Bun.file(homebrewSqlitePath).size > 0) {
  85. Database.setCustomSQLite(homebrewSqlitePath);
  86. }
  87. } catch {}
  88. }
  89. function initializeDatabase(db: Database): void {
  90. sqliteVec.load(db);
  91. db.exec("PRAGMA journal_mode = WAL");
  92. // Collections table
  93. db.exec(`
  94. CREATE TABLE IF NOT EXISTS collections (
  95. id INTEGER PRIMARY KEY AUTOINCREMENT,
  96. pwd TEXT NOT NULL,
  97. glob_pattern TEXT NOT NULL,
  98. created_at TEXT NOT NULL,
  99. context TEXT,
  100. UNIQUE(pwd, glob_pattern)
  101. )
  102. `);
  103. // Path-based context
  104. db.exec(`
  105. CREATE TABLE IF NOT EXISTS path_contexts (
  106. id INTEGER PRIMARY KEY AUTOINCREMENT,
  107. path_prefix TEXT NOT NULL UNIQUE,
  108. context TEXT NOT NULL,
  109. created_at TEXT NOT NULL
  110. )
  111. `);
  112. db.exec(`CREATE INDEX IF NOT EXISTS idx_path_contexts_prefix ON path_contexts(path_prefix)`);
  113. // Cache table for Ollama API calls
  114. db.exec(`
  115. CREATE TABLE IF NOT EXISTS ollama_cache (
  116. hash TEXT PRIMARY KEY,
  117. result TEXT NOT NULL,
  118. created_at TEXT NOT NULL
  119. )
  120. `);
  121. // Documents table
  122. db.exec(`
  123. CREATE TABLE IF NOT EXISTS documents (
  124. id INTEGER PRIMARY KEY AUTOINCREMENT,
  125. collection_id INTEGER NOT NULL,
  126. name TEXT NOT NULL,
  127. title TEXT NOT NULL,
  128. hash TEXT NOT NULL,
  129. filepath TEXT NOT NULL,
  130. display_path TEXT NOT NULL DEFAULT '',
  131. body TEXT NOT NULL,
  132. created_at TEXT NOT NULL,
  133. modified_at TEXT NOT NULL,
  134. active INTEGER NOT NULL DEFAULT 1,
  135. FOREIGN KEY (collection_id) REFERENCES collections(id)
  136. )
  137. `);
  138. // Migration: add display_path column if missing
  139. const docInfo = db.prepare(`PRAGMA table_info(documents)`).all() as { name: string }[];
  140. const hasDisplayPath = docInfo.some(col => col.name === 'display_path');
  141. if (!hasDisplayPath) {
  142. db.exec(`ALTER TABLE documents ADD COLUMN display_path TEXT NOT NULL DEFAULT ''`);
  143. }
  144. db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_documents_display_path ON documents(display_path) WHERE display_path != '' AND active = 1`);
  145. // Content vectors
  146. const cvInfo = db.prepare(`PRAGMA table_info(content_vectors)`).all() as { name: string }[];
  147. const hasSeqColumn = cvInfo.some(col => col.name === 'seq');
  148. if (cvInfo.length > 0 && !hasSeqColumn) {
  149. db.exec(`DROP TABLE IF EXISTS content_vectors`);
  150. db.exec(`DROP TABLE IF EXISTS vectors_vec`);
  151. }
  152. db.exec(`
  153. CREATE TABLE IF NOT EXISTS content_vectors (
  154. hash TEXT NOT NULL,
  155. seq INTEGER NOT NULL DEFAULT 0,
  156. pos INTEGER NOT NULL DEFAULT 0,
  157. model TEXT NOT NULL,
  158. embedded_at TEXT NOT NULL,
  159. PRIMARY KEY (hash, seq)
  160. )
  161. `);
  162. // FTS
  163. db.exec(`
  164. CREATE VIRTUAL TABLE IF NOT EXISTS documents_fts USING fts5(
  165. name, body,
  166. content='documents',
  167. content_rowid='id',
  168. tokenize='porter unicode61'
  169. )
  170. `);
  171. db.exec(`
  172. CREATE TRIGGER IF NOT EXISTS documents_ai AFTER INSERT ON documents BEGIN
  173. INSERT INTO documents_fts(rowid, name, body) VALUES (new.id, new.name, new.body);
  174. END
  175. `);
  176. db.exec(`
  177. CREATE TRIGGER IF NOT EXISTS documents_ad AFTER DELETE ON documents BEGIN
  178. INSERT INTO documents_fts(documents_fts, rowid, name, body) VALUES('delete', old.id, old.name, old.body);
  179. END
  180. `);
  181. db.exec(`
  182. CREATE TRIGGER IF NOT EXISTS documents_au AFTER UPDATE ON documents BEGIN
  183. INSERT INTO documents_fts(documents_fts, rowid, name, body) VALUES('delete', old.id, old.name, old.body);
  184. INSERT INTO documents_fts(rowid, name, body) VALUES (new.id, new.name, new.body);
  185. END
  186. `);
  187. db.exec(`CREATE INDEX IF NOT EXISTS idx_documents_collection ON documents(collection_id, active)`);
  188. db.exec(`CREATE INDEX IF NOT EXISTS idx_documents_hash ON documents(hash)`);
  189. db.exec(`CREATE INDEX IF NOT EXISTS idx_documents_filepath ON documents(filepath, active)`);
  190. db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_documents_filepath_active ON documents(filepath) WHERE active = 1`);
  191. }
  192. function ensureVecTableInternal(db: Database, dimensions: number): void {
  193. const tableInfo = db.prepare(`SELECT sql FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get() as { sql: string } | null;
  194. if (tableInfo) {
  195. const match = tableInfo.sql.match(/float\[(\d+)\]/);
  196. const hasHashSeq = tableInfo.sql.includes('hash_seq');
  197. if (match && parseInt(match[1]) === dimensions && hasHashSeq) return;
  198. db.exec("DROP TABLE IF EXISTS vectors_vec");
  199. }
  200. db.exec(`CREATE VIRTUAL TABLE vectors_vec USING vec0(hash_seq TEXT PRIMARY KEY, embedding float[${dimensions}])`);
  201. }
  202. // =============================================================================
  203. // Store Factory
  204. // =============================================================================
  205. export type Store = {
  206. db: Database;
  207. dbPath: string;
  208. close: () => void;
  209. ensureVecTable: (dimensions: number) => void;
  210. // Index health
  211. getHashesNeedingEmbedding: () => number;
  212. getIndexHealth: () => IndexHealthInfo;
  213. getStatus: () => IndexStatus;
  214. // Caching
  215. getCacheKey: typeof getCacheKey;
  216. getCachedResult: (cacheKey: string) => string | null;
  217. setCachedResult: (cacheKey: string, result: string) => void;
  218. clearCache: () => void;
  219. // Context
  220. getContextForFile: (filepath: string) => string | null;
  221. getCollectionIdByName: (name: string) => number | null;
  222. // Search
  223. searchFTS: (query: string, limit?: number, collectionId?: number) => SearchResult[];
  224. searchVec: (query: string, model: string, limit?: number, collectionId?: number) => Promise<SearchResult[]>;
  225. // Query expansion & reranking
  226. expandQuery: (query: string, model?: string) => Promise<string[]>;
  227. rerank: (query: string, documents: { file: string; text: string }[], model?: string) => Promise<{ file: string; score: number }[]>;
  228. // Document retrieval
  229. findDocument: (filename: string, options?: { includeBody?: boolean }) => DocumentResult | DocumentNotFound;
  230. getDocumentBody: (doc: DocumentResult | { filepath: string }, fromLine?: number, maxLines?: number) => string | null;
  231. findDocuments: (pattern: string, options?: { includeBody?: boolean; maxBytes?: number }) => { docs: MultiGetResult[]; errors: string[] };
  232. // Legacy compatibility
  233. getDocument: (filename: string, fromLine?: number, maxLines?: number) => (DocumentResult & { body: string }) | DocumentNotFound;
  234. getMultipleDocuments: (pattern: string, maxLines?: number, maxBytes?: number) => { files: MultiGetFile[]; errors: string[] };
  235. // Fuzzy matching
  236. findSimilarFiles: (query: string, maxDistance?: number, limit?: number) => string[];
  237. matchFilesByGlob: (pattern: string) => { filepath: string; displayPath: string; bodyLength: number }[];
  238. };
  239. /**
  240. * Create a new store instance with the given database path.
  241. * If no path is provided, uses the default path (~/.cache/qmd/index.sqlite).
  242. *
  243. * @param dbPath - Path to the SQLite database file
  244. * @returns Store instance with all methods bound to the database
  245. */
  246. export function createStore(dbPath?: string): Store {
  247. const resolvedPath = dbPath || getDefaultDbPath();
  248. const db = new Database(resolvedPath);
  249. initializeDatabase(db);
  250. return {
  251. db,
  252. dbPath: resolvedPath,
  253. close: () => db.close(),
  254. ensureVecTable: (dimensions: number) => ensureVecTableInternal(db, dimensions),
  255. // Index health
  256. getHashesNeedingEmbedding: () => getHashesNeedingEmbedding(db),
  257. getIndexHealth: () => getIndexHealth(db),
  258. getStatus: () => getStatus(db),
  259. // Caching
  260. getCacheKey,
  261. getCachedResult: (cacheKey: string) => getCachedResult(db, cacheKey),
  262. setCachedResult: (cacheKey: string, result: string) => setCachedResult(db, cacheKey, result),
  263. clearCache: () => clearCache(db),
  264. // Context
  265. getContextForFile: (filepath: string) => getContextForFile(db, filepath),
  266. getCollectionIdByName: (name: string) => getCollectionIdByName(db, name),
  267. // Search
  268. searchFTS: (query: string, limit?: number, collectionId?: number) => searchFTS(db, query, limit, collectionId),
  269. searchVec: (query: string, model: string, limit?: number, collectionId?: number) => searchVec(db, query, model, limit, collectionId),
  270. // Query expansion & reranking
  271. expandQuery: (query: string, model?: string) => expandQuery(query, model, db),
  272. rerank: (query: string, documents: { file: string; text: string }[], model?: string) => rerank(query, documents, model, db),
  273. // Document retrieval
  274. findDocument: (filename: string, options?: { includeBody?: boolean }) => findDocument(db, filename, options),
  275. getDocumentBody: (doc: DocumentResult | { filepath: string }, fromLine?: number, maxLines?: number) => getDocumentBody(db, doc, fromLine, maxLines),
  276. findDocuments: (pattern: string, options?: { includeBody?: boolean; maxBytes?: number }) => findDocuments(db, pattern, options),
  277. // Legacy compatibility
  278. getDocument: (filename: string, fromLine?: number, maxLines?: number) => getDocument(db, filename, fromLine, maxLines),
  279. getMultipleDocuments: (pattern: string, maxLines?: number, maxBytes?: number) => getMultipleDocuments(db, pattern, maxLines, maxBytes),
  280. // Fuzzy matching
  281. findSimilarFiles: (query: string, maxDistance?: number, limit?: number) => findSimilarFiles(db, query, maxDistance, limit),
  282. matchFilesByGlob: (pattern: string) => matchFilesByGlob(db, pattern),
  283. };
  284. }
  285. // =============================================================================
  286. // Legacy compatibility - will be removed
  287. // =============================================================================
  288. let _legacyDb: Database | null = null;
  289. let _legacyDbPath: string | null = null;
  290. /** @deprecated Use createStore() instead */
  291. export function setCustomIndexName(name: string | null): void {
  292. _legacyDbPath = name ? getDefaultDbPath(name) : null;
  293. _legacyDb = null; // Reset so next getDb() creates new connection
  294. }
  295. /** @deprecated Use createStore() instead */
  296. export function getDbPath(): string {
  297. return _legacyDbPath || getDefaultDbPath();
  298. }
  299. /** @deprecated Use createStore() instead */
  300. export function getDb(): Database {
  301. if (!_legacyDb) {
  302. _legacyDb = new Database(getDbPath());
  303. initializeDatabase(_legacyDb);
  304. }
  305. return _legacyDb;
  306. }
  307. /** @deprecated Use store.ensureVecTable() instead */
  308. export function ensureVecTable(db: Database, dimensions: number): void {
  309. ensureVecTableInternal(db, dimensions);
  310. }
  311. // =============================================================================
  312. // Core Document Type
  313. // =============================================================================
  314. /**
  315. * Unified document result type with all metadata.
  316. * Body is optional - use getDocumentBody() to load it separately if needed.
  317. */
  318. export type DocumentResult = {
  319. filepath: string; // Full filesystem path
  320. displayPath: string; // Short display path (e.g., "docs/readme.md")
  321. title: string; // Document title (from first heading or filename)
  322. context: string | null; // Folder context description if configured
  323. hash: string; // Content hash for caching/change detection
  324. collectionId: number; // Parent collection ID
  325. modifiedAt: string; // Last modification timestamp
  326. bodyLength: number; // Body length in bytes (useful before loading)
  327. body?: string; // Document body (optional, load with getDocumentBody)
  328. };
  329. /**
  330. * Search result extends DocumentResult with score and source info
  331. */
  332. export type SearchResult = DocumentResult & {
  333. score: number; // Relevance score (0-1)
  334. source: "fts" | "vec"; // Search source (full-text or vector)
  335. chunkPos?: number; // Character position of matching chunk (for vector search)
  336. };
  337. /**
  338. * Ranked result for RRF fusion (simplified, used internally)
  339. */
  340. export type RankedResult = {
  341. file: string;
  342. displayPath: string;
  343. title: string;
  344. body: string;
  345. score: number;
  346. };
  347. /**
  348. * Error result when document is not found
  349. */
  350. export type DocumentNotFound = {
  351. error: "not_found";
  352. query: string;
  353. similarFiles: string[];
  354. };
  355. /**
  356. * Result from multi-get operations
  357. */
  358. export type MultiGetResult = {
  359. doc: DocumentResult;
  360. skipped: false;
  361. } | {
  362. doc: Pick<DocumentResult, "filepath" | "displayPath">;
  363. skipped: true;
  364. skipReason: string;
  365. };
  366. export type CollectionInfo = {
  367. id: number;
  368. path: string;
  369. pattern: string;
  370. documents: number;
  371. lastUpdated: string;
  372. };
  373. export type IndexStatus = {
  374. totalDocuments: number;
  375. needsEmbedding: number;
  376. hasVectorIndex: boolean;
  377. collections: CollectionInfo[];
  378. };
  379. // =============================================================================
  380. // Index health
  381. // =============================================================================
  382. export function getHashesNeedingEmbedding(db: Database): number {
  383. const result = db.prepare(`
  384. SELECT COUNT(DISTINCT d.hash) as count
  385. FROM documents d
  386. LEFT JOIN content_vectors v ON d.hash = v.hash AND v.seq = 0
  387. WHERE d.active = 1 AND v.hash IS NULL
  388. `).get() as { count: number };
  389. return result.count;
  390. }
  391. export type IndexHealthInfo = {
  392. needsEmbedding: number;
  393. totalDocs: number;
  394. daysStale: number | null;
  395. };
  396. export function getIndexHealth(db: Database): IndexHealthInfo {
  397. const needsEmbedding = getHashesNeedingEmbedding(db);
  398. const totalDocs = (db.prepare(`SELECT COUNT(*) as count FROM documents WHERE active = 1`).get() as { count: number }).count;
  399. const mostRecent = db.prepare(`SELECT MAX(modified_at) as latest FROM documents WHERE active = 1`).get() as { latest: string | null };
  400. let daysStale: number | null = null;
  401. if (mostRecent?.latest) {
  402. const lastUpdate = new Date(mostRecent.latest);
  403. daysStale = Math.floor((Date.now() - lastUpdate.getTime()) / (24 * 60 * 60 * 1000));
  404. }
  405. return { needsEmbedding, totalDocs, daysStale };
  406. }
  407. // =============================================================================
  408. // Caching
  409. // =============================================================================
  410. export function getCacheKey(url: string, body: object): string {
  411. const hash = new Bun.CryptoHasher("sha256");
  412. hash.update(url);
  413. hash.update(JSON.stringify(body));
  414. return hash.digest("hex");
  415. }
  416. export function getCachedResult(db: Database, cacheKey: string): string | null {
  417. const row = db.prepare(`SELECT result FROM ollama_cache WHERE hash = ?`).get(cacheKey) as { result: string } | null;
  418. return row?.result || null;
  419. }
  420. export function setCachedResult(db: Database, cacheKey: string, result: string): void {
  421. const now = new Date().toISOString();
  422. db.prepare(`INSERT OR REPLACE INTO ollama_cache (hash, result, created_at) VALUES (?, ?, ?)`).run(cacheKey, result, now);
  423. if (Math.random() < 0.01) {
  424. db.exec(`DELETE FROM ollama_cache WHERE hash NOT IN (SELECT hash FROM ollama_cache ORDER BY created_at DESC LIMIT 1000)`);
  425. }
  426. }
  427. export function clearCache(db: Database): void {
  428. db.exec(`DELETE FROM ollama_cache`);
  429. }
  430. // =============================================================================
  431. // Document helpers
  432. // =============================================================================
  433. export async function hashContent(content: string): Promise<string> {
  434. const hash = new Bun.CryptoHasher("sha256");
  435. hash.update(content);
  436. return hash.digest("hex");
  437. }
  438. export function extractTitle(content: string, filename: string): string {
  439. const match = content.match(/^##?\s+(.+)$/m);
  440. if (match) {
  441. const title = match[1].trim();
  442. if (title === "📝 Notes" || title === "Notes") {
  443. const nextMatch = content.match(/^##\s+(.+)$/m);
  444. if (nextMatch) return nextMatch[1].trim();
  445. }
  446. return title;
  447. }
  448. return filename.replace(/\.md$/, "").split("/").pop() || filename;
  449. }
  450. // Re-export from llm.ts for backwards compatibility
  451. export { formatQueryForEmbedding, formatDocForEmbedding };
  452. export function chunkDocument(content: string, maxBytes: number = CHUNK_BYTE_SIZE): { text: string; pos: number }[] {
  453. const encoder = new TextEncoder();
  454. const totalBytes = encoder.encode(content).length;
  455. if (totalBytes <= maxBytes) {
  456. return [{ text: content, pos: 0 }];
  457. }
  458. const chunks: { text: string; pos: number }[] = [];
  459. let charPos = 0;
  460. while (charPos < content.length) {
  461. let endPos = charPos;
  462. let byteCount = 0;
  463. while (endPos < content.length && byteCount < maxBytes) {
  464. const charBytes = encoder.encode(content[endPos]).length;
  465. if (byteCount + charBytes > maxBytes) break;
  466. byteCount += charBytes;
  467. endPos++;
  468. }
  469. if (endPos < content.length && endPos > charPos) {
  470. const slice = content.slice(charPos, endPos);
  471. const paragraphBreak = slice.lastIndexOf('\n\n');
  472. const sentenceEnd = Math.max(
  473. slice.lastIndexOf('. '),
  474. slice.lastIndexOf('.\n'),
  475. slice.lastIndexOf('? '),
  476. slice.lastIndexOf('?\n'),
  477. slice.lastIndexOf('! '),
  478. slice.lastIndexOf('!\n')
  479. );
  480. const lineBreak = slice.lastIndexOf('\n');
  481. const spaceBreak = slice.lastIndexOf(' ');
  482. let breakPoint = -1;
  483. if (paragraphBreak > slice.length * 0.5) {
  484. breakPoint = paragraphBreak + 2;
  485. } else if (sentenceEnd > slice.length * 0.5) {
  486. breakPoint = sentenceEnd + 2;
  487. } else if (lineBreak > slice.length * 0.3) {
  488. breakPoint = lineBreak + 1;
  489. } else if (spaceBreak > slice.length * 0.3) {
  490. breakPoint = spaceBreak + 1;
  491. }
  492. if (breakPoint > 0) {
  493. endPos = charPos + breakPoint;
  494. }
  495. }
  496. if (endPos <= charPos) {
  497. endPos = charPos + 1;
  498. }
  499. chunks.push({ text: content.slice(charPos, endPos), pos: charPos });
  500. charPos = endPos;
  501. }
  502. return chunks;
  503. }
  504. // =============================================================================
  505. // Fuzzy matching
  506. // =============================================================================
  507. function levenshtein(a: string, b: string): number {
  508. const m = a.length, n = b.length;
  509. if (m === 0) return n;
  510. if (n === 0) return m;
  511. const dp: number[][] = Array.from({ length: m + 1 }, (_, i) => [i]);
  512. for (let j = 1; j <= n; j++) dp[0][j] = j;
  513. for (let i = 1; i <= m; i++) {
  514. for (let j = 1; j <= n; j++) {
  515. const cost = a[i - 1] === b[j - 1] ? 0 : 1;
  516. dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);
  517. }
  518. }
  519. return dp[m][n];
  520. }
  521. export function findSimilarFiles(db: Database, query: string, maxDistance: number = 3, limit: number = 5): string[] {
  522. const allFiles = db.prepare(`SELECT display_path FROM documents WHERE active = 1`).all() as { display_path: string }[];
  523. const queryLower = query.toLowerCase();
  524. const scored = allFiles
  525. .map(f => ({ path: f.display_path, dist: levenshtein(f.display_path.toLowerCase(), queryLower) }))
  526. .filter(f => f.dist <= maxDistance)
  527. .sort((a, b) => a.dist - b.dist)
  528. .slice(0, limit);
  529. return scored.map(f => f.path);
  530. }
  531. export function matchFilesByGlob(db: Database, pattern: string): { filepath: string; displayPath: string; bodyLength: number }[] {
  532. const allFiles = db.prepare(`SELECT filepath, display_path, LENGTH(body) as body_length FROM documents WHERE active = 1`).all() as { filepath: string; display_path: string; body_length: number }[];
  533. const glob = new Glob(pattern);
  534. return allFiles
  535. .filter(f => glob.match(f.display_path))
  536. .map(f => ({ filepath: f.filepath, displayPath: f.display_path, bodyLength: f.body_length }));
  537. }
  538. // =============================================================================
  539. // Context
  540. // =============================================================================
  541. export function getContextForFile(db: Database, filepath: string): string | null {
  542. const result = db.prepare(`
  543. SELECT context FROM path_contexts
  544. WHERE ? LIKE path_prefix || '%'
  545. ORDER BY LENGTH(path_prefix) DESC
  546. LIMIT 1
  547. `).get(filepath) as { context: string } | null;
  548. return result?.context || null;
  549. }
  550. export function getCollectionIdByName(db: Database, name: string): number | null {
  551. const result = db.prepare(`SELECT id FROM collections WHERE pwd LIKE ? ORDER BY LENGTH(pwd) DESC LIMIT 1`).get(`%${name}`) as { id: number } | null;
  552. return result?.id || null;
  553. }
  554. // =============================================================================
  555. // FTS Search
  556. // =============================================================================
  557. function sanitizeFTS5Term(term: string): string {
  558. return term.replace(/[^\p{L}\p{N}']/gu, '').toLowerCase();
  559. }
  560. function buildFTS5Query(query: string): string | null {
  561. const terms = query.split(/\s+/)
  562. .map(t => sanitizeFTS5Term(t))
  563. .filter(t => t.length > 0);
  564. if (terms.length === 0) return null;
  565. if (terms.length === 1) return `"${terms[0]}"*`;
  566. return terms.map(t => `"${t}"*`).join(' AND ');
  567. }
  568. export function searchFTS(db: Database, query: string, limit: number = 20, collectionId?: number): SearchResult[] {
  569. const ftsQuery = buildFTS5Query(query);
  570. if (!ftsQuery) return [];
  571. let sql = `
  572. SELECT d.filepath, d.display_path, d.title, d.body, bm25(documents_fts, 10.0, 1.0) as score
  573. FROM documents_fts f
  574. JOIN documents d ON d.id = f.rowid
  575. WHERE documents_fts MATCH ? AND d.active = 1
  576. `;
  577. const params: (string | number)[] = [ftsQuery];
  578. if (collectionId !== undefined) {
  579. sql += ` AND d.collection_id = ?`;
  580. params.push(collectionId);
  581. }
  582. sql += ` ORDER BY score LIMIT ?`;
  583. params.push(limit);
  584. const rows = db.prepare(sql).all(...params) as { filepath: string; display_path: string; title: string; body: string; score: number }[];
  585. const maxScore = rows.length > 0 ? Math.max(...rows.map(r => Math.abs(r.score))) : 1;
  586. return rows.map(row => ({
  587. file: row.filepath,
  588. displayPath: row.display_path,
  589. title: row.title,
  590. body: row.body,
  591. score: Math.abs(row.score) / maxScore,
  592. source: "fts" as const,
  593. }));
  594. }
  595. // =============================================================================
  596. // Vector Search
  597. // =============================================================================
  598. export async function searchVec(db: Database, query: string, model: string, limit: number = 20, collectionId?: number): Promise<SearchResult[]> {
  599. const tableExists = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
  600. if (!tableExists) return [];
  601. const embedding = await getEmbedding(query, model, true);
  602. if (!embedding) return [];
  603. // sqlite-vec requires "k = ?" for KNN queries
  604. let sql = `
  605. SELECT v.hash_seq, v.distance, d.filepath, d.display_path, d.title, d.body, cv.pos
  606. FROM vectors_vec v
  607. JOIN content_vectors cv ON cv.hash || '_' || cv.seq = v.hash_seq
  608. JOIN documents d ON d.hash = cv.hash AND d.active = 1
  609. WHERE v.embedding MATCH ? AND k = ?
  610. `;
  611. if (collectionId !== undefined) {
  612. sql += ` AND d.collection_id = ${collectionId}`;
  613. }
  614. sql += ` ORDER BY v.distance`;
  615. const rows = db.prepare(sql).all(new Float32Array(embedding), limit * 3) as { hash_seq: string; distance: number; filepath: string; display_path: string; title: string; body: string; pos: number }[];
  616. const seen = new Map<string, { row: typeof rows[0]; bestDist: number }>();
  617. for (const row of rows) {
  618. const existing = seen.get(row.filepath);
  619. if (!existing || row.distance < existing.bestDist) {
  620. seen.set(row.filepath, { row, bestDist: row.distance });
  621. }
  622. }
  623. return Array.from(seen.values())
  624. .sort((a, b) => a.bestDist - b.bestDist)
  625. .slice(0, limit)
  626. .map(({ row }) => ({
  627. file: row.filepath,
  628. displayPath: row.display_path,
  629. title: row.title,
  630. body: row.body,
  631. score: 1 / (1 + row.distance),
  632. source: "vec" as const,
  633. chunkPos: row.pos,
  634. }));
  635. }
  636. // =============================================================================
  637. // Embeddings
  638. // =============================================================================
  639. async function getEmbedding(text: string, model: string, isQuery: boolean): Promise<number[] | null> {
  640. const ollama = getDefaultOllama();
  641. const result = await ollama.embed(text, { model, isQuery });
  642. return result?.embedding || null;
  643. }
  644. // =============================================================================
  645. // Query expansion
  646. // =============================================================================
  647. export async function expandQuery(query: string, model: string = DEFAULT_QUERY_MODEL, db: Database): Promise<string[]> {
  648. // Check cache first
  649. const cacheKey = getCacheKey("expandQuery", { query, model });
  650. const cached = getCachedResult(db, cacheKey);
  651. if (cached) {
  652. const lines = cached.split('\n').map(l => l.trim()).filter(l => l.length > 0);
  653. return [query, ...lines.slice(0, 2)];
  654. }
  655. const ollama = getDefaultOllama();
  656. const results = await ollama.expandQuery(query, model, 2);
  657. // Cache the expanded queries (excluding original)
  658. if (results.length > 1) {
  659. setCachedResult(db, cacheKey, results.slice(1).join('\n'));
  660. }
  661. return results;
  662. }
  663. // =============================================================================
  664. // Reranking
  665. // =============================================================================
  666. export async function rerank(query: string, documents: { file: string; text: string }[], model: string = DEFAULT_RERANK_MODEL, db: Database): Promise<{ file: string; score: number }[]> {
  667. const cachedResults: Map<string, number> = new Map();
  668. const uncachedDocs: RerankDocument[] = [];
  669. // Check cache for each document
  670. for (const doc of documents) {
  671. const cacheKey = getCacheKey("rerank", { query, file: doc.file, model });
  672. const cached = getCachedResult(db, cacheKey);
  673. if (cached !== null) {
  674. cachedResults.set(doc.file, parseFloat(cached));
  675. } else {
  676. uncachedDocs.push({ file: doc.file, text: doc.text });
  677. }
  678. }
  679. // Rerank uncached documents using Ollama
  680. if (uncachedDocs.length > 0) {
  681. const ollama = getDefaultOllama();
  682. const rerankResult = await ollama.rerank(query, uncachedDocs, { model });
  683. // Cache results
  684. for (const result of rerankResult.results) {
  685. const cacheKey = getCacheKey("rerank", { query, file: result.file, model });
  686. setCachedResult(db, cacheKey, result.score.toString());
  687. cachedResults.set(result.file, result.score);
  688. }
  689. }
  690. // Return all results sorted by score
  691. return documents
  692. .map(doc => ({ file: doc.file, score: cachedResults.get(doc.file) || 0 }))
  693. .sort((a, b) => b.score - a.score);
  694. }
  695. // =============================================================================
  696. // Reciprocal Rank Fusion
  697. // =============================================================================
  698. export function reciprocalRankFusion(
  699. resultLists: RankedResult[][],
  700. weights: number[] = [],
  701. k: number = 60
  702. ): RankedResult[] {
  703. const scores = new Map<string, { result: RankedResult; rrfScore: number; topRank: number }>();
  704. for (let listIdx = 0; listIdx < resultLists.length; listIdx++) {
  705. const list = resultLists[listIdx];
  706. const weight = weights[listIdx] ?? 1.0;
  707. for (let rank = 0; rank < list.length; rank++) {
  708. const result = list[rank];
  709. const rrfContribution = weight / (k + rank + 1);
  710. const existing = scores.get(result.file);
  711. if (existing) {
  712. existing.rrfScore += rrfContribution;
  713. existing.topRank = Math.min(existing.topRank, rank);
  714. } else {
  715. scores.set(result.file, {
  716. result,
  717. rrfScore: rrfContribution,
  718. topRank: rank,
  719. });
  720. }
  721. }
  722. }
  723. // Top-rank bonus
  724. for (const entry of scores.values()) {
  725. if (entry.topRank === 0) {
  726. entry.rrfScore += 0.05;
  727. } else if (entry.topRank <= 2) {
  728. entry.rrfScore += 0.02;
  729. }
  730. }
  731. return Array.from(scores.values())
  732. .sort((a, b) => b.rrfScore - a.rrfScore)
  733. .map(e => ({ ...e.result, score: e.rrfScore }));
  734. }
  735. // =============================================================================
  736. // Document retrieval
  737. // =============================================================================
  738. type DbDocRow = {
  739. filepath: string;
  740. display_path: string;
  741. title: string;
  742. hash: string;
  743. collection_id: number;
  744. modified_at: string;
  745. body_length: number;
  746. body?: string;
  747. };
  748. /**
  749. * Find a document by filename/path (with fuzzy matching)
  750. * Returns document metadata without body by default
  751. */
  752. export function findDocument(db: Database, filename: string, options: { includeBody?: boolean } = {}): DocumentResult | DocumentNotFound {
  753. let filepath = filename;
  754. const colonMatch = filepath.match(/:(\d+)$/);
  755. if (colonMatch) {
  756. filepath = filepath.slice(0, -colonMatch[0].length);
  757. }
  758. if (filepath.startsWith('~/')) {
  759. filepath = homedir() + filepath.slice(1);
  760. }
  761. const selectCols = options.includeBody
  762. ? `filepath, display_path, title, hash, collection_id, modified_at, LENGTH(body) as body_length, body`
  763. : `filepath, display_path, title, hash, collection_id, modified_at, LENGTH(body) as body_length`;
  764. // Try various match strategies
  765. let doc = db.prepare(`SELECT ${selectCols} FROM documents WHERE filepath = ? AND active = 1`).get(filepath) as DbDocRow | null;
  766. if (!doc) {
  767. doc = db.prepare(`SELECT ${selectCols} FROM documents WHERE display_path = ? AND active = 1`).get(filepath) as DbDocRow | null;
  768. }
  769. if (!doc) {
  770. doc = db.prepare(`SELECT ${selectCols} FROM documents WHERE filepath LIKE ? AND active = 1 LIMIT 1`).get(`%${filepath}`) as DbDocRow | null;
  771. }
  772. if (!doc) {
  773. doc = db.prepare(`SELECT ${selectCols} FROM documents WHERE display_path LIKE ? AND active = 1 LIMIT 1`).get(`%${filepath}`) as DbDocRow | null;
  774. }
  775. if (!doc) {
  776. const similar = findSimilarFiles(db, filepath, 5, 5);
  777. return { error: "not_found", query: filename, similarFiles: similar };
  778. }
  779. const context = getContextForFile(db, doc.filepath);
  780. return {
  781. filepath: doc.filepath,
  782. displayPath: doc.display_path,
  783. title: doc.title,
  784. context,
  785. hash: doc.hash,
  786. collectionId: doc.collection_id,
  787. modifiedAt: doc.modified_at,
  788. bodyLength: doc.body_length,
  789. ...(options.includeBody && doc.body !== undefined && { body: doc.body }),
  790. };
  791. }
  792. /**
  793. * Get the body content for a document
  794. * Optionally slice by line range
  795. */
  796. export function getDocumentBody(db: Database, doc: DocumentResult | { filepath: string }, fromLine?: number, maxLines?: number): string | null {
  797. const filepath = 'filepath' in doc ? doc.filepath : doc.filepath;
  798. const row = db.prepare(`SELECT body FROM documents WHERE filepath = ? AND active = 1`).get(filepath) as { body: string } | null;
  799. if (!row) return null;
  800. let body = row.body;
  801. if (fromLine !== undefined || maxLines !== undefined) {
  802. const lines = body.split('\n');
  803. const start = (fromLine || 1) - 1;
  804. const end = maxLines !== undefined ? start + maxLines : lines.length;
  805. body = lines.slice(start, end).join('\n');
  806. }
  807. return body;
  808. }
  809. /**
  810. * Legacy function for backwards compatibility
  811. * Combines findDocument + getDocumentBody with line slicing
  812. */
  813. export function getDocument(db: Database, filename: string, fromLine?: number, maxLines?: number): (DocumentResult & { body: string }) | DocumentNotFound {
  814. // Parse :line suffix
  815. let parsedFromLine = fromLine;
  816. let filepath = filename;
  817. const colonMatch = filepath.match(/:(\d+)$/);
  818. if (colonMatch && !parsedFromLine) {
  819. parsedFromLine = parseInt(colonMatch[1], 10);
  820. filepath = filepath.slice(0, -colonMatch[0].length);
  821. }
  822. const result = findDocument(db, filepath, { includeBody: true });
  823. if ("error" in result) return result;
  824. let body = result.body || "";
  825. if (parsedFromLine !== undefined || maxLines !== undefined) {
  826. const lines = body.split('\n');
  827. const start = (parsedFromLine || 1) - 1;
  828. const end = maxLines !== undefined ? start + maxLines : lines.length;
  829. body = lines.slice(start, end).join('\n');
  830. }
  831. return { ...result, body };
  832. }
  833. /**
  834. * Find multiple documents by glob pattern or comma-separated list
  835. * Returns documents without body by default (use getDocumentBody to load)
  836. */
  837. export function findDocuments(
  838. db: Database,
  839. pattern: string,
  840. options: { includeBody?: boolean; maxBytes?: number } = {}
  841. ): { docs: MultiGetResult[]; errors: string[] } {
  842. const isCommaSeparated = pattern.includes(',') && !pattern.includes('*') && !pattern.includes('?');
  843. const errors: string[] = [];
  844. const maxBytes = options.maxBytes ?? DEFAULT_MULTI_GET_MAX_BYTES;
  845. const selectCols = options.includeBody
  846. ? `filepath, display_path, title, hash, collection_id, modified_at, LENGTH(body) as body_length, body`
  847. : `filepath, display_path, title, hash, collection_id, modified_at, LENGTH(body) as body_length`;
  848. let fileRows: DbDocRow[];
  849. if (isCommaSeparated) {
  850. const names = pattern.split(',').map(s => s.trim()).filter(Boolean);
  851. fileRows = [];
  852. for (const name of names) {
  853. let doc = db.prepare(`SELECT ${selectCols} FROM documents WHERE display_path = ? AND active = 1`).get(name) as DbDocRow | null;
  854. if (!doc) {
  855. doc = db.prepare(`SELECT ${selectCols} FROM documents WHERE display_path LIKE ? AND active = 1 LIMIT 1`).get(`%${name}`) as DbDocRow | null;
  856. }
  857. if (doc) {
  858. fileRows.push(doc);
  859. } else {
  860. const similar = findSimilarFiles(db, name, 5, 3);
  861. let msg = `File not found: ${name}`;
  862. if (similar.length > 0) {
  863. msg += ` (did you mean: ${similar.join(', ')}?)`;
  864. }
  865. errors.push(msg);
  866. }
  867. }
  868. } else {
  869. // Glob pattern match
  870. const matched = matchFilesByGlob(db, pattern);
  871. if (matched.length === 0) {
  872. errors.push(`No files matched pattern: ${pattern}`);
  873. return { docs: [], errors };
  874. }
  875. const filepaths = matched.map(m => m.filepath);
  876. const placeholders = filepaths.map(() => '?').join(',');
  877. fileRows = db.prepare(`SELECT ${selectCols} FROM documents WHERE filepath IN (${placeholders}) AND active = 1`).all(...filepaths) as DbDocRow[];
  878. }
  879. const results: MultiGetResult[] = [];
  880. for (const row of fileRows) {
  881. const context = getContextForFile(db, row.filepath);
  882. if (row.body_length > maxBytes) {
  883. results.push({
  884. doc: { filepath: row.filepath, displayPath: row.display_path },
  885. skipped: true,
  886. skipReason: `File too large (${Math.round(row.body_length / 1024)}KB > ${Math.round(maxBytes / 1024)}KB)`,
  887. });
  888. continue;
  889. }
  890. results.push({
  891. doc: {
  892. filepath: row.filepath,
  893. displayPath: row.display_path,
  894. title: row.title || row.display_path.split('/').pop() || row.display_path,
  895. context,
  896. hash: row.hash,
  897. collectionId: row.collection_id,
  898. modifiedAt: row.modified_at,
  899. bodyLength: row.body_length,
  900. ...(options.includeBody && row.body !== undefined && { body: row.body }),
  901. },
  902. skipped: false,
  903. });
  904. }
  905. return { docs: results, errors };
  906. }
  907. /**
  908. * Legacy function for backwards compatibility
  909. */
  910. export function getMultipleDocuments(db: Database, pattern: string, maxLines?: number, maxBytes: number = DEFAULT_MULTI_GET_MAX_BYTES): { files: MultiGetFile[]; errors: string[] } {
  911. const { docs, errors } = findDocuments(db, pattern, { includeBody: true, maxBytes });
  912. const files: MultiGetFile[] = docs.map(result => {
  913. if (result.skipped) {
  914. return {
  915. filepath: result.doc.filepath,
  916. displayPath: result.doc.displayPath,
  917. title: "",
  918. body: "",
  919. context: null,
  920. skipped: true as const,
  921. skipReason: result.skipReason,
  922. };
  923. }
  924. let body = result.doc.body || "";
  925. if (maxLines !== undefined) {
  926. const lines = body.split('\n');
  927. body = lines.slice(0, maxLines).join('\n');
  928. if (lines.length > maxLines) {
  929. body += `\n\n[... truncated ${lines.length - maxLines} more lines]`;
  930. }
  931. }
  932. return {
  933. filepath: result.doc.filepath,
  934. displayPath: result.doc.displayPath,
  935. title: result.doc.title,
  936. body,
  937. context: result.doc.context,
  938. skipped: false as const,
  939. };
  940. });
  941. return { files, errors };
  942. }
  943. // Keep the old MultiGetFile type for backwards compatibility
  944. export type MultiGetFile = {
  945. filepath: string;
  946. displayPath: string;
  947. title: string;
  948. body: string;
  949. context: string | null;
  950. skipped: false;
  951. } | {
  952. filepath: string;
  953. displayPath: string;
  954. title: string;
  955. body: string;
  956. context: string | null;
  957. skipped: true;
  958. skipReason: string;
  959. };
  960. // =============================================================================
  961. // Status
  962. // =============================================================================
  963. export function getStatus(db: Database): IndexStatus {
  964. const collections = db.prepare(`
  965. SELECT c.id, c.pwd, c.glob_pattern, c.created_at,
  966. COUNT(d.id) as active_count,
  967. MAX(d.modified_at) as last_doc_update
  968. FROM collections c
  969. LEFT JOIN documents d ON d.collection_id = c.id AND d.active = 1
  970. GROUP BY c.id
  971. ORDER BY last_doc_update DESC
  972. `).all() as { id: number; pwd: string; glob_pattern: string; created_at: string; active_count: number; last_doc_update: string | null }[];
  973. const totalDocs = (db.prepare(`SELECT COUNT(*) as c FROM documents WHERE active = 1`).get() as { c: number }).c;
  974. const needsEmbedding = getHashesNeedingEmbedding(db);
  975. const hasVectors = !!db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
  976. return {
  977. totalDocuments: totalDocs,
  978. needsEmbedding,
  979. hasVectorIndex: hasVectors,
  980. collections: collections.map(col => ({
  981. id: col.id,
  982. path: col.pwd,
  983. pattern: col.glob_pattern,
  984. documents: col.active_count,
  985. lastUpdated: col.last_doc_update || col.created_at,
  986. })),
  987. };
  988. }
  989. // =============================================================================
  990. // Snippet extraction
  991. // =============================================================================
  992. export type SnippetResult = {
  993. line: number; // 1-indexed line number of best match
  994. snippet: string; // The snippet text with diff-style header
  995. linesBefore: number; // Lines in document before snippet
  996. linesAfter: number; // Lines in document after snippet
  997. snippetLines: number; // Number of lines in snippet
  998. };
  999. export function extractSnippet(body: string, query: string, maxLen = 500, chunkPos?: number): SnippetResult {
  1000. const totalLines = body.split('\n').length;
  1001. let searchBody = body;
  1002. let lineOffset = 0;
  1003. if (chunkPos && chunkPos > 0) {
  1004. const contextStart = Math.max(0, chunkPos - 100);
  1005. const contextEnd = Math.min(body.length, chunkPos + maxLen + 100);
  1006. searchBody = body.slice(contextStart, contextEnd);
  1007. if (contextStart > 0) {
  1008. lineOffset = body.slice(0, contextStart).split('\n').length - 1;
  1009. }
  1010. }
  1011. const lines = searchBody.split('\n');
  1012. const queryTerms = query.toLowerCase().split(/\s+/).filter(t => t.length > 0);
  1013. let bestLine = 0, bestScore = -1;
  1014. for (let i = 0; i < lines.length; i++) {
  1015. const lineLower = lines[i].toLowerCase();
  1016. let score = 0;
  1017. for (const term of queryTerms) {
  1018. if (lineLower.includes(term)) score++;
  1019. }
  1020. if (score > bestScore) {
  1021. bestScore = score;
  1022. bestLine = i;
  1023. }
  1024. }
  1025. const start = Math.max(0, bestLine - 1);
  1026. const end = Math.min(lines.length, bestLine + 3);
  1027. const snippetLines = lines.slice(start, end);
  1028. let snippetText = snippetLines.join('\n');
  1029. if (snippetText.length > maxLen) snippetText = snippetText.substring(0, maxLen - 3) + "...";
  1030. const absoluteStart = lineOffset + start + 1; // 1-indexed
  1031. const snippetLineCount = snippetLines.length;
  1032. const linesBefore = absoluteStart - 1;
  1033. const linesAfter = totalLines - (absoluteStart + snippetLineCount - 1);
  1034. // Format with diff-style header: @@ -start,count @@ (linesBefore before, linesAfter after)
  1035. const header = `@@ -${absoluteStart},${snippetLineCount} @@ (${linesBefore} before, ${linesAfter} after)`;
  1036. const snippet = `${header}\n${snippetText}`;
  1037. return {
  1038. line: lineOffset + bestLine + 1,
  1039. snippet,
  1040. linesBefore,
  1041. linesAfter,
  1042. snippetLines: snippetLineCount,
  1043. };
  1044. }