store.ts 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058
  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. // Allow override via INDEX_PATH for testing
  61. if (Bun.env.INDEX_PATH) {
  62. return Bun.env.INDEX_PATH;
  63. }
  64. const cacheDir = Bun.env.XDG_CACHE_HOME || resolve(homedir(), ".cache");
  65. const qmdCacheDir = resolve(cacheDir, "qmd");
  66. try { Bun.spawnSync(["mkdir", "-p", qmdCacheDir]); } catch {}
  67. return resolve(qmdCacheDir, `${indexName}.sqlite`);
  68. }
  69. export function getPwd(): string {
  70. return process.env.PWD || process.cwd();
  71. }
  72. export function getRealPath(path: string): string {
  73. try {
  74. const result = Bun.spawnSync(["realpath", path]);
  75. if (result.success) {
  76. return result.stdout.toString().trim();
  77. }
  78. } catch {}
  79. return resolve(path);
  80. }
  81. // =============================================================================
  82. // Virtual Path Utilities (qmd://)
  83. // =============================================================================
  84. export type VirtualPath = {
  85. collectionName: string;
  86. path: string; // relative path within collection
  87. };
  88. /**
  89. * Parse a virtual path like "qmd://collection-name/path/to/file.md"
  90. * into its components.
  91. */
  92. export function parseVirtualPath(virtualPath: string): VirtualPath | null {
  93. const match = virtualPath.match(/^qmd:\/\/([^\/]+)\/(.+)$/);
  94. if (!match) return null;
  95. return {
  96. collectionName: match[1],
  97. path: match[2],
  98. };
  99. }
  100. /**
  101. * Build a virtual path from collection name and relative path.
  102. */
  103. export function buildVirtualPath(collectionName: string, path: string): string {
  104. return `qmd://${collectionName}/${path}`;
  105. }
  106. /**
  107. * Check if a path is a virtual path (starts with qmd://).
  108. */
  109. export function isVirtualPath(path: string): boolean {
  110. return path.startsWith('qmd://');
  111. }
  112. /**
  113. * Resolve a virtual path to absolute filesystem path.
  114. */
  115. export function resolveVirtualPath(db: Database, virtualPath: string): string | null {
  116. const parsed = parseVirtualPath(virtualPath);
  117. if (!parsed) return null;
  118. const coll = getCollectionByName(db, parsed.collectionName);
  119. if (!coll) return null;
  120. return resolve(coll.pwd, parsed.path);
  121. }
  122. /**
  123. * Convert an absolute filesystem path to a virtual path.
  124. * Returns null if the file is not in any indexed collection.
  125. */
  126. export function toVirtualPath(db: Database, absolutePath: string): string | null {
  127. const doc = db.prepare(`
  128. SELECT c.name, d.path
  129. FROM documents d
  130. JOIN collections c ON c.id = d.collection_id
  131. WHERE c.pwd || '/' || d.path = ? AND d.active = 1
  132. LIMIT 1
  133. `).get(absolutePath) as { name: string; path: string } | null;
  134. if (!doc) return null;
  135. return buildVirtualPath(doc.name, doc.path);
  136. }
  137. // =============================================================================
  138. // Database initialization
  139. // =============================================================================
  140. // On macOS, use Homebrew's SQLite which supports extensions
  141. if (process.platform === "darwin") {
  142. const homebrewSqlitePath = "/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib";
  143. try {
  144. if (Bun.file(homebrewSqlitePath).size > 0) {
  145. Database.setCustomSQLite(homebrewSqlitePath);
  146. }
  147. } catch {}
  148. }
  149. function initializeDatabase(db: Database): void {
  150. sqliteVec.load(db);
  151. db.exec("PRAGMA journal_mode = WAL");
  152. db.exec("PRAGMA foreign_keys = ON");
  153. // Check if we need to migrate from old schema
  154. const tables = db.prepare(`SELECT name FROM sqlite_master WHERE type='table'`).all() as { name: string }[];
  155. const tableNames = tables.map(t => t.name);
  156. const needsMigration = tableNames.includes('documents') && !tableNames.includes('content');
  157. if (needsMigration) {
  158. migrateToContentAddressable(db);
  159. return; // Migration will call initializeDatabase again
  160. }
  161. // Content-addressable storage - the source of truth for document content
  162. db.exec(`
  163. CREATE TABLE IF NOT EXISTS content (
  164. hash TEXT PRIMARY KEY,
  165. doc TEXT NOT NULL,
  166. created_at TEXT NOT NULL
  167. )
  168. `);
  169. // Collections table with name field
  170. db.exec(`
  171. CREATE TABLE IF NOT EXISTS collections (
  172. id INTEGER PRIMARY KEY AUTOINCREMENT,
  173. name TEXT NOT NULL UNIQUE,
  174. pwd TEXT NOT NULL,
  175. glob_pattern TEXT NOT NULL,
  176. created_at TEXT NOT NULL,
  177. updated_at TEXT NOT NULL,
  178. UNIQUE(pwd, glob_pattern)
  179. )
  180. `);
  181. // Documents table - file system layer mapping virtual paths to content hashes
  182. db.exec(`
  183. CREATE TABLE IF NOT EXISTS documents (
  184. id INTEGER PRIMARY KEY AUTOINCREMENT,
  185. collection_id INTEGER NOT NULL,
  186. path TEXT NOT NULL,
  187. title TEXT NOT NULL,
  188. hash TEXT NOT NULL,
  189. created_at TEXT NOT NULL,
  190. modified_at TEXT NOT NULL,
  191. active INTEGER NOT NULL DEFAULT 1,
  192. FOREIGN KEY (collection_id) REFERENCES collections(id) ON DELETE CASCADE,
  193. FOREIGN KEY (hash) REFERENCES content(hash) ON DELETE CASCADE,
  194. UNIQUE(collection_id, path)
  195. )
  196. `);
  197. db.exec(`CREATE INDEX IF NOT EXISTS idx_documents_collection ON documents(collection_id, active)`);
  198. db.exec(`CREATE INDEX IF NOT EXISTS idx_documents_hash ON documents(hash)`);
  199. db.exec(`CREATE INDEX IF NOT EXISTS idx_documents_path ON documents(path, active)`);
  200. // Path-based context (collection-scoped, hierarchical)
  201. db.exec(`
  202. CREATE TABLE IF NOT EXISTS path_contexts (
  203. id INTEGER PRIMARY KEY AUTOINCREMENT,
  204. collection_id INTEGER NOT NULL,
  205. path_prefix TEXT NOT NULL,
  206. context TEXT NOT NULL,
  207. created_at TEXT NOT NULL,
  208. FOREIGN KEY (collection_id) REFERENCES collections(id) ON DELETE CASCADE,
  209. UNIQUE(collection_id, path_prefix)
  210. )
  211. `);
  212. db.exec(`CREATE INDEX IF NOT EXISTS idx_path_contexts_collection ON path_contexts(collection_id, path_prefix)`);
  213. // Cache table for Ollama API calls
  214. db.exec(`
  215. CREATE TABLE IF NOT EXISTS ollama_cache (
  216. hash TEXT PRIMARY KEY,
  217. result TEXT NOT NULL,
  218. created_at TEXT NOT NULL
  219. )
  220. `);
  221. // Content vectors
  222. const cvInfo = db.prepare(`PRAGMA table_info(content_vectors)`).all() as { name: string }[];
  223. const hasSeqColumn = cvInfo.some(col => col.name === 'seq');
  224. if (cvInfo.length > 0 && !hasSeqColumn) {
  225. db.exec(`DROP TABLE IF EXISTS content_vectors`);
  226. db.exec(`DROP TABLE IF EXISTS vectors_vec`);
  227. }
  228. db.exec(`
  229. CREATE TABLE IF NOT EXISTS content_vectors (
  230. hash TEXT NOT NULL,
  231. seq INTEGER NOT NULL DEFAULT 0,
  232. pos INTEGER NOT NULL DEFAULT 0,
  233. model TEXT NOT NULL,
  234. embedded_at TEXT NOT NULL,
  235. PRIMARY KEY (hash, seq)
  236. )
  237. `);
  238. // FTS - index path and content (joined from content table)
  239. db.exec(`
  240. CREATE VIRTUAL TABLE IF NOT EXISTS documents_fts USING fts5(
  241. path, body,
  242. tokenize='porter unicode61'
  243. )
  244. `);
  245. // Triggers to keep FTS in sync
  246. db.exec(`
  247. CREATE TRIGGER IF NOT EXISTS documents_ai AFTER INSERT ON documents BEGIN
  248. INSERT INTO documents_fts(rowid, path, body)
  249. SELECT new.id, new.path, c.doc
  250. FROM content c
  251. WHERE c.hash = new.hash;
  252. END
  253. `);
  254. db.exec(`
  255. CREATE TRIGGER IF NOT EXISTS documents_ad AFTER DELETE ON documents BEGIN
  256. DELETE FROM documents_fts WHERE rowid = old.id;
  257. END
  258. `);
  259. db.exec(`
  260. CREATE TRIGGER IF NOT EXISTS documents_au AFTER UPDATE ON documents BEGIN
  261. UPDATE documents_fts
  262. SET path = new.path,
  263. body = (SELECT doc FROM content WHERE hash = new.hash)
  264. WHERE rowid = new.id;
  265. END
  266. `);
  267. }
  268. function migrateToContentAddressable(db: Database): void {
  269. console.log("Migrating database to content-addressable schema...");
  270. // Start transaction
  271. db.exec("BEGIN TRANSACTION");
  272. try {
  273. // Rename old tables
  274. db.exec("ALTER TABLE documents RENAME TO documents_old");
  275. db.exec("ALTER TABLE collections RENAME TO collections_old");
  276. db.exec("ALTER TABLE path_contexts RENAME TO path_contexts_old");
  277. db.exec("DROP TABLE IF EXISTS documents_fts");
  278. db.exec("DROP TRIGGER IF EXISTS documents_ai");
  279. db.exec("DROP TRIGGER IF EXISTS documents_ad");
  280. db.exec("DROP TRIGGER IF EXISTS documents_au");
  281. // Create new schema
  282. db.exec(`
  283. CREATE TABLE content (
  284. hash TEXT PRIMARY KEY,
  285. doc TEXT NOT NULL,
  286. created_at TEXT NOT NULL
  287. )
  288. `);
  289. db.exec(`
  290. CREATE TABLE collections (
  291. id INTEGER PRIMARY KEY AUTOINCREMENT,
  292. name TEXT NOT NULL UNIQUE,
  293. pwd TEXT NOT NULL,
  294. glob_pattern TEXT NOT NULL,
  295. created_at TEXT NOT NULL,
  296. updated_at TEXT NOT NULL,
  297. UNIQUE(pwd, glob_pattern)
  298. )
  299. `);
  300. db.exec(`
  301. CREATE TABLE documents (
  302. id INTEGER PRIMARY KEY AUTOINCREMENT,
  303. collection_id INTEGER NOT NULL,
  304. path TEXT NOT NULL,
  305. title TEXT NOT NULL,
  306. hash TEXT NOT NULL,
  307. created_at TEXT NOT NULL,
  308. modified_at TEXT NOT NULL,
  309. active INTEGER NOT NULL DEFAULT 1,
  310. FOREIGN KEY (collection_id) REFERENCES collections(id) ON DELETE CASCADE,
  311. FOREIGN KEY (hash) REFERENCES content(hash) ON DELETE CASCADE,
  312. UNIQUE(collection_id, path)
  313. )
  314. `);
  315. db.exec(`
  316. CREATE TABLE path_contexts (
  317. id INTEGER PRIMARY KEY AUTOINCREMENT,
  318. collection_id INTEGER NOT NULL,
  319. path_prefix TEXT NOT NULL,
  320. context TEXT NOT NULL,
  321. created_at TEXT NOT NULL,
  322. FOREIGN KEY (collection_id) REFERENCES collections(id) ON DELETE CASCADE,
  323. UNIQUE(collection_id, path_prefix)
  324. )
  325. `);
  326. // Migrate data: Extract unique content hashes
  327. console.log("Migrating content...");
  328. db.exec(`
  329. INSERT INTO content (hash, doc, created_at)
  330. SELECT hash, body, MIN(created_at) as created_at
  331. FROM documents_old
  332. WHERE active = 1
  333. GROUP BY hash
  334. `);
  335. // Migrate collections: generate names from pwd basename
  336. console.log("Migrating collections...");
  337. // First insert with pwd as temporary name
  338. db.exec(`
  339. INSERT INTO collections (id, name, pwd, glob_pattern, created_at, updated_at)
  340. SELECT
  341. id,
  342. pwd as name,
  343. pwd,
  344. glob_pattern,
  345. created_at,
  346. created_at as updated_at
  347. FROM collections_old
  348. `);
  349. // Then update names to basenames using application logic
  350. const collections = db.prepare(`SELECT id, pwd FROM collections`).all() as { id: number; pwd: string }[];
  351. for (const coll of collections) {
  352. const parts = coll.pwd.split('/').filter(Boolean);
  353. const name = parts[parts.length - 1] || 'root';
  354. db.prepare(`UPDATE collections SET name = ? WHERE id = ?`).run(name, coll.id);
  355. }
  356. // Handle duplicate collection names by appending collection_id
  357. const duplicates = db.prepare(`
  358. SELECT name, COUNT(*) as cnt
  359. FROM collections
  360. GROUP BY name
  361. HAVING cnt > 1
  362. `).all() as { name: string; cnt: number }[];
  363. for (const dup of duplicates) {
  364. const rows = db.prepare(`SELECT id FROM collections WHERE name = ? ORDER BY id`).all(dup.name) as { id: number }[];
  365. for (let i = 1; i < rows.length; i++) {
  366. db.prepare(`UPDATE collections SET name = ? WHERE id = ?`).run(`${dup.name}-${rows[i].id}`, rows[i].id);
  367. }
  368. }
  369. // Migrate documents: convert filepath to relative path within collection
  370. console.log("Migrating documents...");
  371. const oldDocs = db.prepare(`
  372. SELECT d.id, d.collection_id, d.filepath, d.title, d.hash, d.created_at, d.modified_at, c.pwd
  373. FROM documents_old d
  374. JOIN collections c ON c.id = d.collection_id
  375. WHERE d.active = 1
  376. `).all() as Array<{
  377. id: number;
  378. collection_id: number;
  379. filepath: string;
  380. title: string;
  381. hash: string;
  382. created_at: string;
  383. modified_at: string;
  384. pwd: string;
  385. }>;
  386. const insertDoc = db.prepare(`
  387. INSERT INTO documents (collection_id, path, title, hash, created_at, modified_at, active)
  388. VALUES (?, ?, ?, ?, ?, ?, 1)
  389. `);
  390. for (const doc of oldDocs) {
  391. // Convert absolute filepath to relative path within collection
  392. let path = doc.filepath;
  393. if (path.startsWith(doc.pwd + '/')) {
  394. path = path.slice(doc.pwd.length + 1);
  395. } else if (path.startsWith(doc.pwd)) {
  396. path = path.slice(doc.pwd.length);
  397. }
  398. // Remove leading slash if present
  399. path = path.replace(/^\/+/, '');
  400. try {
  401. insertDoc.run(doc.collection_id, path, doc.title, doc.hash, doc.created_at, doc.modified_at);
  402. } catch (e) {
  403. console.warn(`Skipping duplicate path: ${path} in collection ${doc.collection_id}`);
  404. }
  405. }
  406. // Migrate path_contexts: associate with collections based on path prefix
  407. console.log("Migrating path contexts...");
  408. const oldContexts = db.prepare(`SELECT * FROM path_contexts_old`).all() as Array<{
  409. path_prefix: string;
  410. context: string;
  411. created_at: string;
  412. }>;
  413. const insertContext = db.prepare(`
  414. INSERT INTO path_contexts (collection_id, path_prefix, context, created_at)
  415. VALUES (?, ?, ?, ?)
  416. `);
  417. const allCollections = db.prepare(`SELECT id, pwd FROM collections`).all() as Array<{ id: number; pwd: string }>;
  418. for (const ctx of oldContexts) {
  419. // Find collection(s) that match this path prefix
  420. for (const coll of allCollections) {
  421. if (ctx.path_prefix.startsWith(coll.pwd)) {
  422. // Convert absolute path_prefix to relative within collection
  423. let relPath = ctx.path_prefix;
  424. if (relPath.startsWith(coll.pwd + '/')) {
  425. relPath = relPath.slice(coll.pwd.length + 1);
  426. } else if (relPath.startsWith(coll.pwd)) {
  427. relPath = relPath.slice(coll.pwd.length);
  428. }
  429. relPath = relPath.replace(/^\/+/, '');
  430. try {
  431. insertContext.run(coll.id, relPath, ctx.context, ctx.created_at);
  432. } catch (e) {
  433. // Ignore duplicates
  434. }
  435. }
  436. }
  437. }
  438. // Drop old tables
  439. db.exec("DROP TABLE documents_old");
  440. db.exec("DROP TABLE collections_old");
  441. db.exec("DROP TABLE path_contexts_old");
  442. // Recreate FTS and triggers
  443. db.exec(`
  444. CREATE VIRTUAL TABLE documents_fts USING fts5(
  445. path, body,
  446. tokenize='porter unicode61'
  447. )
  448. `);
  449. db.exec(`
  450. CREATE TRIGGER documents_ai AFTER INSERT ON documents BEGIN
  451. INSERT INTO documents_fts(rowid, path, body)
  452. SELECT new.id, new.path, c.doc
  453. FROM content c
  454. WHERE c.hash = new.hash;
  455. END
  456. `);
  457. db.exec(`
  458. CREATE TRIGGER documents_ad AFTER DELETE ON documents BEGIN
  459. DELETE FROM documents_fts WHERE rowid = old.id;
  460. END
  461. `);
  462. db.exec(`
  463. CREATE TRIGGER documents_au AFTER UPDATE ON documents BEGIN
  464. UPDATE documents_fts
  465. SET path = new.path,
  466. body = (SELECT doc FROM content WHERE hash = new.hash)
  467. WHERE rowid = new.id;
  468. END
  469. `);
  470. // Populate FTS from migrated data
  471. console.log("Rebuilding full-text search index...");
  472. db.exec(`
  473. INSERT INTO documents_fts(rowid, path, body)
  474. SELECT d.id, d.path, c.doc
  475. FROM documents d
  476. JOIN content c ON c.hash = d.hash
  477. WHERE d.active = 1
  478. `);
  479. // Create indexes
  480. db.exec(`CREATE INDEX idx_documents_collection ON documents(collection_id, active)`);
  481. db.exec(`CREATE INDEX idx_documents_hash ON documents(hash)`);
  482. db.exec(`CREATE INDEX idx_documents_path ON documents(path, active)`);
  483. db.exec(`CREATE INDEX idx_path_contexts_collection ON path_contexts(collection_id, path_prefix)`);
  484. db.exec("COMMIT");
  485. console.log("Migration complete!");
  486. } catch (e) {
  487. db.exec("ROLLBACK");
  488. console.error("Migration failed:", e);
  489. throw e;
  490. }
  491. }
  492. function ensureVecTableInternal(db: Database, dimensions: number): void {
  493. const tableInfo = db.prepare(`SELECT sql FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get() as { sql: string } | null;
  494. if (tableInfo) {
  495. const match = tableInfo.sql.match(/float\[(\d+)\]/);
  496. const hasHashSeq = tableInfo.sql.includes('hash_seq');
  497. if (match && parseInt(match[1]) === dimensions && hasHashSeq) return;
  498. db.exec("DROP TABLE IF EXISTS vectors_vec");
  499. }
  500. db.exec(`CREATE VIRTUAL TABLE vectors_vec USING vec0(hash_seq TEXT PRIMARY KEY, embedding float[${dimensions}])`);
  501. }
  502. // =============================================================================
  503. // Store Factory
  504. // =============================================================================
  505. export type Store = {
  506. db: Database;
  507. dbPath: string;
  508. close: () => void;
  509. ensureVecTable: (dimensions: number) => void;
  510. // Index health
  511. getHashesNeedingEmbedding: () => number;
  512. getIndexHealth: () => IndexHealthInfo;
  513. getStatus: () => IndexStatus;
  514. // Caching
  515. getCacheKey: typeof getCacheKey;
  516. getCachedResult: (cacheKey: string) => string | null;
  517. setCachedResult: (cacheKey: string, result: string) => void;
  518. clearCache: () => void;
  519. // Cleanup and maintenance
  520. deleteOllamaCache: () => number;
  521. deleteInactiveDocuments: () => number;
  522. cleanupOrphanedContent: () => number;
  523. cleanupOrphanedVectors: () => number;
  524. cleanupDuplicateCollections: () => number;
  525. vacuumDatabase: () => void;
  526. // Context
  527. getContextForFile: (filepath: string) => string | null;
  528. getContextForPath: (collectionId: number, path: string) => string | null;
  529. getCollectionIdByName: (name: string) => number | null;
  530. getCollectionByName: (name: string) => { id: number; name: string; pwd: string; glob_pattern: string } | null;
  531. // Virtual paths
  532. parseVirtualPath: typeof parseVirtualPath;
  533. buildVirtualPath: typeof buildVirtualPath;
  534. isVirtualPath: typeof isVirtualPath;
  535. resolveVirtualPath: (virtualPath: string) => string | null;
  536. toVirtualPath: (absolutePath: string) => string | null;
  537. // Search
  538. searchFTS: (query: string, limit?: number, collectionId?: number) => SearchResult[];
  539. searchVec: (query: string, model: string, limit?: number, collectionId?: number) => Promise<SearchResult[]>;
  540. // Query expansion & reranking
  541. expandQuery: (query: string, model?: string) => Promise<string[]>;
  542. rerank: (query: string, documents: { file: string; text: string }[], model?: string) => Promise<{ file: string; score: number }[]>;
  543. // Document retrieval
  544. findDocument: (filename: string, options?: { includeBody?: boolean }) => DocumentResult | DocumentNotFound;
  545. getDocumentBody: (doc: DocumentResult | { filepath: string }, fromLine?: number, maxLines?: number) => string | null;
  546. findDocuments: (pattern: string, options?: { includeBody?: boolean; maxBytes?: number }) => { docs: MultiGetResult[]; errors: string[] };
  547. // Legacy compatibility
  548. getDocument: (filename: string, fromLine?: number, maxLines?: number) => (DocumentResult & { body: string }) | DocumentNotFound;
  549. getMultipleDocuments: (pattern: string, maxLines?: number, maxBytes?: number) => { files: MultiGetFile[]; errors: string[] };
  550. // Fuzzy matching
  551. findSimilarFiles: (query: string, maxDistance?: number, limit?: number) => string[];
  552. matchFilesByGlob: (pattern: string) => { filepath: string; displayPath: string; bodyLength: number }[];
  553. // Document indexing operations
  554. insertContent: (hash: string, content: string, createdAt: string) => void;
  555. insertDocument: (collectionId: number, path: string, title: string, hash: string, createdAt: string, modifiedAt: string) => void;
  556. findActiveDocument: (collectionId: number, path: string) => { id: number; hash: string; title: string } | null;
  557. updateDocumentTitle: (documentId: number, title: string, modifiedAt: string) => void;
  558. updateDocument: (documentId: number, title: string, hash: string, modifiedAt: string) => void;
  559. deactivateDocument: (collectionId: number, path: string) => void;
  560. getActiveDocumentPaths: (collectionId: number) => string[];
  561. // Vector/embedding operations
  562. getHashesForEmbedding: () => { hash: string; body: string; path: string }[];
  563. clearAllEmbeddings: () => void;
  564. insertEmbedding: (hash: string, seq: number, pos: number, embedding: Float32Array, model: string, embeddedAt: string) => void;
  565. };
  566. /**
  567. * Create a new store instance with the given database path.
  568. * If no path is provided, uses the default path (~/.cache/qmd/index.sqlite).
  569. *
  570. * @param dbPath - Path to the SQLite database file
  571. * @returns Store instance with all methods bound to the database
  572. */
  573. export function createStore(dbPath?: string): Store {
  574. const resolvedPath = dbPath || getDefaultDbPath();
  575. const db = new Database(resolvedPath);
  576. initializeDatabase(db);
  577. return {
  578. db,
  579. dbPath: resolvedPath,
  580. close: () => db.close(),
  581. ensureVecTable: (dimensions: number) => ensureVecTableInternal(db, dimensions),
  582. // Index health
  583. getHashesNeedingEmbedding: () => getHashesNeedingEmbedding(db),
  584. getIndexHealth: () => getIndexHealth(db),
  585. getStatus: () => getStatus(db),
  586. // Caching
  587. getCacheKey,
  588. getCachedResult: (cacheKey: string) => getCachedResult(db, cacheKey),
  589. setCachedResult: (cacheKey: string, result: string) => setCachedResult(db, cacheKey, result),
  590. clearCache: () => clearCache(db),
  591. // Cleanup and maintenance
  592. deleteOllamaCache: () => deleteOllamaCache(db),
  593. deleteInactiveDocuments: () => deleteInactiveDocuments(db),
  594. cleanupOrphanedContent: () => cleanupOrphanedContent(db),
  595. cleanupOrphanedVectors: () => cleanupOrphanedVectors(db),
  596. cleanupDuplicateCollections: () => cleanupDuplicateCollections(db),
  597. vacuumDatabase: () => vacuumDatabase(db),
  598. // Context
  599. getContextForFile: (filepath: string) => getContextForFile(db, filepath),
  600. getContextForPath: (collectionId: number, path: string) => getContextForPath(db, collectionId, path),
  601. getCollectionIdByName: (name: string) => getCollectionIdByName(db, name),
  602. getCollectionByName: (name: string) => getCollectionByName(db, name),
  603. // Virtual paths
  604. parseVirtualPath,
  605. buildVirtualPath,
  606. isVirtualPath,
  607. resolveVirtualPath: (virtualPath: string) => resolveVirtualPath(db, virtualPath),
  608. toVirtualPath: (absolutePath: string) => toVirtualPath(db, absolutePath),
  609. // Search
  610. searchFTS: (query: string, limit?: number, collectionId?: number) => searchFTS(db, query, limit, collectionId),
  611. searchVec: (query: string, model: string, limit?: number, collectionId?: number) => searchVec(db, query, model, limit, collectionId),
  612. // Query expansion & reranking
  613. expandQuery: (query: string, model?: string) => expandQuery(query, model, db),
  614. rerank: (query: string, documents: { file: string; text: string }[], model?: string) => rerank(query, documents, model, db),
  615. // Document retrieval
  616. findDocument: (filename: string, options?: { includeBody?: boolean }) => findDocument(db, filename, options),
  617. getDocumentBody: (doc: DocumentResult | { filepath: string }, fromLine?: number, maxLines?: number) => getDocumentBody(db, doc, fromLine, maxLines),
  618. findDocuments: (pattern: string, options?: { includeBody?: boolean; maxBytes?: number }) => findDocuments(db, pattern, options),
  619. // Legacy compatibility
  620. getDocument: (filename: string, fromLine?: number, maxLines?: number) => getDocument(db, filename, fromLine, maxLines),
  621. getMultipleDocuments: (pattern: string, maxLines?: number, maxBytes?: number) => getMultipleDocuments(db, pattern, maxLines, maxBytes),
  622. // Fuzzy matching
  623. findSimilarFiles: (query: string, maxDistance?: number, limit?: number) => findSimilarFiles(db, query, maxDistance, limit),
  624. matchFilesByGlob: (pattern: string) => matchFilesByGlob(db, pattern),
  625. // Document indexing operations
  626. insertContent: (hash: string, content: string, createdAt: string) => insertContent(db, hash, content, createdAt),
  627. insertDocument: (collectionId: number, path: string, title: string, hash: string, createdAt: string, modifiedAt: string) => insertDocument(db, collectionId, path, title, hash, createdAt, modifiedAt),
  628. findActiveDocument: (collectionId: number, path: string) => findActiveDocument(db, collectionId, path),
  629. updateDocumentTitle: (documentId: number, title: string, modifiedAt: string) => updateDocumentTitle(db, documentId, title, modifiedAt),
  630. updateDocument: (documentId: number, title: string, hash: string, modifiedAt: string) => updateDocument(db, documentId, title, hash, modifiedAt),
  631. deactivateDocument: (collectionId: number, path: string) => deactivateDocument(db, collectionId, path),
  632. getActiveDocumentPaths: (collectionId: number) => getActiveDocumentPaths(db, collectionId),
  633. // Vector/embedding operations
  634. getHashesForEmbedding: () => getHashesForEmbedding(db),
  635. clearAllEmbeddings: () => clearAllEmbeddings(db),
  636. insertEmbedding: (hash: string, seq: number, pos: number, embedding: Float32Array, model: string, embeddedAt: string) => insertEmbedding(db, hash, seq, pos, embedding, model, embeddedAt),
  637. };
  638. }
  639. // =============================================================================
  640. // Legacy compatibility - will be removed
  641. // =============================================================================
  642. let _legacyDb: Database | null = null;
  643. let _legacyDbPath: string | null = null;
  644. /** @deprecated Use createStore() instead */
  645. export function setCustomIndexName(name: string | null): void {
  646. _legacyDbPath = name ? getDefaultDbPath(name) : null;
  647. _legacyDb = null; // Reset so next getDb() creates new connection
  648. }
  649. /** @deprecated Use createStore() instead */
  650. export function getDbPath(): string {
  651. return _legacyDbPath || getDefaultDbPath();
  652. }
  653. /** @deprecated Use createStore() instead */
  654. export function getDb(): Database {
  655. if (!_legacyDb) {
  656. _legacyDb = new Database(getDbPath());
  657. initializeDatabase(_legacyDb);
  658. }
  659. return _legacyDb;
  660. }
  661. /** @deprecated Use store.db.close() instead. Closes the legacy db and resets singleton. */
  662. export function closeDb(): void {
  663. if (_legacyDb) {
  664. _legacyDb.close();
  665. _legacyDb = null;
  666. }
  667. }
  668. /** @deprecated Use store.ensureVecTable() instead */
  669. export function ensureVecTable(db: Database, dimensions: number): void {
  670. ensureVecTableInternal(db, dimensions);
  671. }
  672. // =============================================================================
  673. // Core Document Type
  674. // =============================================================================
  675. /**
  676. * Unified document result type with all metadata.
  677. * Body is optional - use getDocumentBody() to load it separately if needed.
  678. */
  679. export type DocumentResult = {
  680. filepath: string; // Full filesystem path
  681. displayPath: string; // Short display path (e.g., "docs/readme.md")
  682. title: string; // Document title (from first heading or filename)
  683. context: string | null; // Folder context description if configured
  684. hash: string; // Content hash for caching/change detection
  685. collectionId: number; // Parent collection ID
  686. modifiedAt: string; // Last modification timestamp
  687. bodyLength: number; // Body length in bytes (useful before loading)
  688. body?: string; // Document body (optional, load with getDocumentBody)
  689. };
  690. /**
  691. * Search result extends DocumentResult with score and source info
  692. */
  693. export type SearchResult = DocumentResult & {
  694. score: number; // Relevance score (0-1)
  695. source: "fts" | "vec"; // Search source (full-text or vector)
  696. chunkPos?: number; // Character position of matching chunk (for vector search)
  697. };
  698. /**
  699. * Ranked result for RRF fusion (simplified, used internally)
  700. */
  701. export type RankedResult = {
  702. file: string;
  703. displayPath: string;
  704. title: string;
  705. body: string;
  706. score: number;
  707. };
  708. /**
  709. * Error result when document is not found
  710. */
  711. export type DocumentNotFound = {
  712. error: "not_found";
  713. query: string;
  714. similarFiles: string[];
  715. };
  716. /**
  717. * Result from multi-get operations
  718. */
  719. export type MultiGetResult = {
  720. doc: DocumentResult;
  721. skipped: false;
  722. } | {
  723. doc: Pick<DocumentResult, "filepath" | "displayPath">;
  724. skipped: true;
  725. skipReason: string;
  726. };
  727. export type CollectionInfo = {
  728. id: number;
  729. path: string;
  730. pattern: string;
  731. documents: number;
  732. lastUpdated: string;
  733. };
  734. export type IndexStatus = {
  735. totalDocuments: number;
  736. needsEmbedding: number;
  737. hasVectorIndex: boolean;
  738. collections: CollectionInfo[];
  739. };
  740. // =============================================================================
  741. // Index health
  742. // =============================================================================
  743. export function getHashesNeedingEmbedding(db: Database): number {
  744. const result = db.prepare(`
  745. SELECT COUNT(DISTINCT d.hash) as count
  746. FROM documents d
  747. LEFT JOIN content_vectors v ON d.hash = v.hash AND v.seq = 0
  748. WHERE d.active = 1 AND v.hash IS NULL
  749. `).get() as { count: number };
  750. return result.count;
  751. }
  752. export type IndexHealthInfo = {
  753. needsEmbedding: number;
  754. totalDocs: number;
  755. daysStale: number | null;
  756. };
  757. export function getIndexHealth(db: Database): IndexHealthInfo {
  758. const needsEmbedding = getHashesNeedingEmbedding(db);
  759. const totalDocs = (db.prepare(`SELECT COUNT(*) as count FROM documents WHERE active = 1`).get() as { count: number }).count;
  760. const mostRecent = db.prepare(`SELECT MAX(modified_at) as latest FROM documents WHERE active = 1`).get() as { latest: string | null };
  761. let daysStale: number | null = null;
  762. if (mostRecent?.latest) {
  763. const lastUpdate = new Date(mostRecent.latest);
  764. daysStale = Math.floor((Date.now() - lastUpdate.getTime()) / (24 * 60 * 60 * 1000));
  765. }
  766. return { needsEmbedding, totalDocs, daysStale };
  767. }
  768. // =============================================================================
  769. // Caching
  770. // =============================================================================
  771. export function getCacheKey(url: string, body: object): string {
  772. const hash = new Bun.CryptoHasher("sha256");
  773. hash.update(url);
  774. hash.update(JSON.stringify(body));
  775. return hash.digest("hex");
  776. }
  777. export function getCachedResult(db: Database, cacheKey: string): string | null {
  778. const row = db.prepare(`SELECT result FROM ollama_cache WHERE hash = ?`).get(cacheKey) as { result: string } | null;
  779. return row?.result || null;
  780. }
  781. export function setCachedResult(db: Database, cacheKey: string, result: string): void {
  782. const now = new Date().toISOString();
  783. db.prepare(`INSERT OR REPLACE INTO ollama_cache (hash, result, created_at) VALUES (?, ?, ?)`).run(cacheKey, result, now);
  784. if (Math.random() < 0.01) {
  785. db.exec(`DELETE FROM ollama_cache WHERE hash NOT IN (SELECT hash FROM ollama_cache ORDER BY created_at DESC LIMIT 1000)`);
  786. }
  787. }
  788. export function clearCache(db: Database): void {
  789. db.exec(`DELETE FROM ollama_cache`);
  790. }
  791. // =============================================================================
  792. // Cleanup and maintenance operations
  793. // =============================================================================
  794. /**
  795. * Delete cached Ollama API responses.
  796. * Returns the number of cached responses deleted.
  797. */
  798. export function deleteOllamaCache(db: Database): number {
  799. const result = db.prepare(`DELETE FROM ollama_cache`).run();
  800. return result.changes;
  801. }
  802. /**
  803. * Remove inactive document records (active = 0).
  804. * Returns the number of inactive documents deleted.
  805. */
  806. export function deleteInactiveDocuments(db: Database): number {
  807. const result = db.prepare(`DELETE FROM documents WHERE active = 0`).run();
  808. return result.changes;
  809. }
  810. /**
  811. * Remove orphaned content hashes that are not referenced by any active document.
  812. * Returns the number of orphaned content hashes deleted.
  813. */
  814. export function cleanupOrphanedContent(db: Database): number {
  815. const result = db.prepare(`
  816. DELETE FROM content
  817. WHERE hash NOT IN (SELECT DISTINCT hash FROM documents WHERE active = 1)
  818. `).run();
  819. return result.changes;
  820. }
  821. /**
  822. * Remove orphaned vector embeddings that are not referenced by any active document.
  823. * Returns the number of orphaned embedding chunks deleted.
  824. */
  825. export function cleanupOrphanedVectors(db: Database): number {
  826. // Check if vectors_vec table exists
  827. const tableExists = db.prepare(`
  828. SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'
  829. `).get();
  830. if (!tableExists) {
  831. return 0;
  832. }
  833. // Count orphaned vectors first
  834. const countResult = db.prepare(`
  835. SELECT COUNT(*) as c FROM content_vectors cv
  836. WHERE NOT EXISTS (
  837. SELECT 1 FROM documents d WHERE d.hash = cv.hash AND d.active = 1
  838. )
  839. `).get() as { c: number };
  840. if (countResult.c === 0) {
  841. return 0;
  842. }
  843. // Delete from vectors_vec first
  844. db.exec(`
  845. DELETE FROM vectors_vec WHERE hash_seq IN (
  846. SELECT cv.hash || '_' || cv.seq FROM content_vectors cv
  847. WHERE NOT EXISTS (
  848. SELECT 1 FROM documents d WHERE d.hash = cv.hash AND d.active = 1
  849. )
  850. )
  851. `);
  852. // Delete from content_vectors
  853. db.exec(`
  854. DELETE FROM content_vectors WHERE hash NOT IN (
  855. SELECT hash FROM documents WHERE active = 1
  856. )
  857. `);
  858. return countResult.c;
  859. }
  860. /**
  861. * Remove duplicate collections, keeping the oldest one per (pwd, glob_pattern).
  862. * Also removes bogus "." glob pattern entries.
  863. * Returns the number of duplicate collections removed.
  864. */
  865. export function cleanupDuplicateCollections(db: Database): number {
  866. // Count duplicates before removal
  867. const beforeCount = (db.prepare(`SELECT COUNT(*) as c FROM collections`).get() as { c: number }).c;
  868. // Remove duplicates keeping the oldest one
  869. db.exec(`
  870. DELETE FROM collections WHERE id NOT IN (
  871. SELECT MIN(id) FROM collections GROUP BY pwd, glob_pattern
  872. )
  873. `);
  874. // Remove bogus "." glob pattern entries (from earlier bug)
  875. db.exec(`DELETE FROM collections WHERE glob_pattern = '.'`);
  876. const afterCount = (db.prepare(`SELECT COUNT(*) as c FROM collections`).get() as { c: number }).c;
  877. return beforeCount - afterCount;
  878. }
  879. /**
  880. * Run VACUUM to reclaim unused space in the database.
  881. * This operation rebuilds the database file to eliminate fragmentation.
  882. */
  883. export function vacuumDatabase(db: Database): void {
  884. db.exec(`VACUUM`);
  885. }
  886. // =============================================================================
  887. // Document helpers
  888. // =============================================================================
  889. export async function hashContent(content: string): Promise<string> {
  890. const hash = new Bun.CryptoHasher("sha256");
  891. hash.update(content);
  892. return hash.digest("hex");
  893. }
  894. export function extractTitle(content: string, filename: string): string {
  895. const match = content.match(/^##?\s+(.+)$/m);
  896. if (match) {
  897. const title = match[1].trim();
  898. if (title === "📝 Notes" || title === "Notes") {
  899. const nextMatch = content.match(/^##\s+(.+)$/m);
  900. if (nextMatch) return nextMatch[1].trim();
  901. }
  902. return title;
  903. }
  904. return filename.replace(/\.md$/, "").split("/").pop() || filename;
  905. }
  906. // =============================================================================
  907. // Document indexing operations
  908. // =============================================================================
  909. /**
  910. * Insert content into the content table (content-addressable storage).
  911. * Uses INSERT OR IGNORE so duplicate hashes are skipped.
  912. */
  913. export function insertContent(db: Database, hash: string, content: string, createdAt: string): void {
  914. db.prepare(`INSERT OR IGNORE INTO content (hash, doc, created_at) VALUES (?, ?, ?)`)
  915. .run(hash, content, createdAt);
  916. }
  917. /**
  918. * Insert a new document into the documents table.
  919. */
  920. export function insertDocument(
  921. db: Database,
  922. collectionId: number,
  923. path: string,
  924. title: string,
  925. hash: string,
  926. createdAt: string,
  927. modifiedAt: string
  928. ): void {
  929. db.prepare(`
  930. INSERT INTO documents (collection_id, path, title, hash, created_at, modified_at, active)
  931. VALUES (?, ?, ?, ?, ?, ?, 1)
  932. `).run(collectionId, path, title, hash, createdAt, modifiedAt);
  933. }
  934. /**
  935. * Find an active document by collection ID and path.
  936. */
  937. export function findActiveDocument(
  938. db: Database,
  939. collectionId: number,
  940. path: string
  941. ): { id: number; hash: string; title: string } | null {
  942. return db.prepare(`
  943. SELECT id, hash, title FROM documents
  944. WHERE collection_id = ? AND path = ? AND active = 1
  945. `).get(collectionId, path) as { id: number; hash: string; title: string } | null;
  946. }
  947. /**
  948. * Update the title and modified_at timestamp for a document.
  949. */
  950. export function updateDocumentTitle(
  951. db: Database,
  952. documentId: number,
  953. title: string,
  954. modifiedAt: string
  955. ): void {
  956. db.prepare(`UPDATE documents SET title = ?, modified_at = ? WHERE id = ?`)
  957. .run(title, modifiedAt, documentId);
  958. }
  959. /**
  960. * Update an existing document's hash, title, and modified_at timestamp.
  961. * Used when content changes but the file path stays the same.
  962. */
  963. export function updateDocument(
  964. db: Database,
  965. documentId: number,
  966. title: string,
  967. hash: string,
  968. modifiedAt: string
  969. ): void {
  970. db.prepare(`UPDATE documents SET title = ?, hash = ?, modified_at = ? WHERE id = ?`)
  971. .run(title, hash, modifiedAt, documentId);
  972. }
  973. /**
  974. * Deactivate a document (mark as inactive but don't delete).
  975. */
  976. export function deactivateDocument(db: Database, collectionId: number, path: string): void {
  977. db.prepare(`UPDATE documents SET active = 0 WHERE collection_id = ? AND path = ? AND active = 1`)
  978. .run(collectionId, path);
  979. }
  980. /**
  981. * Get all active document paths for a collection.
  982. */
  983. export function getActiveDocumentPaths(db: Database, collectionId: number): string[] {
  984. const rows = db.prepare(`
  985. SELECT path FROM documents WHERE collection_id = ? AND active = 1
  986. `).all(collectionId) as { path: string }[];
  987. return rows.map(r => r.path);
  988. }
  989. // Re-export from llm.ts for backwards compatibility
  990. export { formatQueryForEmbedding, formatDocForEmbedding };
  991. export function chunkDocument(content: string, maxBytes: number = CHUNK_BYTE_SIZE): { text: string; pos: number }[] {
  992. const encoder = new TextEncoder();
  993. const totalBytes = encoder.encode(content).length;
  994. if (totalBytes <= maxBytes) {
  995. return [{ text: content, pos: 0 }];
  996. }
  997. const chunks: { text: string; pos: number }[] = [];
  998. let charPos = 0;
  999. while (charPos < content.length) {
  1000. let endPos = charPos;
  1001. let byteCount = 0;
  1002. while (endPos < content.length && byteCount < maxBytes) {
  1003. const charBytes = encoder.encode(content[endPos]).length;
  1004. if (byteCount + charBytes > maxBytes) break;
  1005. byteCount += charBytes;
  1006. endPos++;
  1007. }
  1008. if (endPos < content.length && endPos > charPos) {
  1009. const slice = content.slice(charPos, endPos);
  1010. const paragraphBreak = slice.lastIndexOf('\n\n');
  1011. const sentenceEnd = Math.max(
  1012. slice.lastIndexOf('. '),
  1013. slice.lastIndexOf('.\n'),
  1014. slice.lastIndexOf('? '),
  1015. slice.lastIndexOf('?\n'),
  1016. slice.lastIndexOf('! '),
  1017. slice.lastIndexOf('!\n')
  1018. );
  1019. const lineBreak = slice.lastIndexOf('\n');
  1020. const spaceBreak = slice.lastIndexOf(' ');
  1021. let breakPoint = -1;
  1022. if (paragraphBreak > slice.length * 0.5) {
  1023. breakPoint = paragraphBreak + 2;
  1024. } else if (sentenceEnd > slice.length * 0.5) {
  1025. breakPoint = sentenceEnd + 2;
  1026. } else if (lineBreak > slice.length * 0.3) {
  1027. breakPoint = lineBreak + 1;
  1028. } else if (spaceBreak > slice.length * 0.3) {
  1029. breakPoint = spaceBreak + 1;
  1030. }
  1031. if (breakPoint > 0) {
  1032. endPos = charPos + breakPoint;
  1033. }
  1034. }
  1035. if (endPos <= charPos) {
  1036. endPos = charPos + 1;
  1037. }
  1038. chunks.push({ text: content.slice(charPos, endPos), pos: charPos });
  1039. charPos = endPos;
  1040. }
  1041. return chunks;
  1042. }
  1043. // =============================================================================
  1044. // Fuzzy matching
  1045. // =============================================================================
  1046. function levenshtein(a: string, b: string): number {
  1047. const m = a.length, n = b.length;
  1048. if (m === 0) return n;
  1049. if (n === 0) return m;
  1050. const dp: number[][] = Array.from({ length: m + 1 }, (_, i) => [i]);
  1051. for (let j = 1; j <= n; j++) dp[0][j] = j;
  1052. for (let i = 1; i <= m; i++) {
  1053. for (let j = 1; j <= n; j++) {
  1054. const cost = a[i - 1] === b[j - 1] ? 0 : 1;
  1055. dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);
  1056. }
  1057. }
  1058. return dp[m][n];
  1059. }
  1060. export function findSimilarFiles(db: Database, query: string, maxDistance: number = 3, limit: number = 5): string[] {
  1061. const allFiles = db.prepare(`SELECT display_path FROM documents WHERE active = 1`).all() as { display_path: string }[];
  1062. const queryLower = query.toLowerCase();
  1063. const scored = allFiles
  1064. .map(f => ({ path: f.display_path, dist: levenshtein(f.display_path.toLowerCase(), queryLower) }))
  1065. .filter(f => f.dist <= maxDistance)
  1066. .sort((a, b) => a.dist - b.dist)
  1067. .slice(0, limit);
  1068. return scored.map(f => f.path);
  1069. }
  1070. export function matchFilesByGlob(db: Database, pattern: string): { filepath: string; displayPath: string; bodyLength: number }[] {
  1071. const allFiles = db.prepare(`
  1072. SELECT
  1073. 'qmd://' || c.name || '/' || d.path as virtual_path,
  1074. LENGTH(content.doc) as body_length,
  1075. d.collection_id,
  1076. d.path
  1077. FROM documents d
  1078. JOIN collections c ON c.id = d.collection_id
  1079. JOIN content ON content.hash = d.hash
  1080. WHERE d.active = 1
  1081. `).all() as { virtual_path: string; body_length: number; collection_id: number; path: string }[];
  1082. const glob = new Glob(pattern);
  1083. return allFiles
  1084. .filter(f => glob.match(f.virtual_path) || glob.match(f.path))
  1085. .map(f => ({
  1086. filepath: f.virtual_path, // Use virtual path as filepath
  1087. displayPath: f.virtual_path,
  1088. bodyLength: f.body_length
  1089. }));
  1090. }
  1091. // =============================================================================
  1092. // Context
  1093. // =============================================================================
  1094. /**
  1095. * Get context for a file path using hierarchical inheritance.
  1096. * Contexts are collection-scoped and inherit from parent directories.
  1097. * For example, context at "/talks" applies to "/talks/2024/keynote.md".
  1098. *
  1099. * @param db Database instance
  1100. * @param collectionId Collection ID
  1101. * @param path Relative path within the collection
  1102. * @returns Context string or null if no context is defined
  1103. */
  1104. export function getContextForPath(db: Database, collectionId: number, path: string): string | null {
  1105. // Find the most specific (longest) matching path prefix for this collection
  1106. const result = db.prepare(`
  1107. SELECT context FROM path_contexts
  1108. WHERE collection_id = ?
  1109. AND (? LIKE path_prefix || '/%' OR ? = path_prefix OR path_prefix = '')
  1110. ORDER BY LENGTH(path_prefix) DESC
  1111. LIMIT 1
  1112. `).get(collectionId, path, path) as { context: string } | null;
  1113. return result?.context || null;
  1114. }
  1115. /**
  1116. * Legacy function for backward compatibility - resolves filepath to collection+path first
  1117. */
  1118. export function getContextForFile(db: Database, filepath: string): string | null {
  1119. // Try to find the document to get its collection_id and path
  1120. const doc = db.prepare(`
  1121. SELECT d.collection_id, d.path
  1122. FROM documents d
  1123. JOIN collections c ON c.id = d.collection_id
  1124. WHERE c.pwd || '/' || d.path = ? AND d.active = 1
  1125. LIMIT 1
  1126. `).get(filepath) as { collection_id: number; path: string } | null;
  1127. if (!doc) return null;
  1128. return getContextForPath(db, doc.collection_id, doc.path);
  1129. }
  1130. /**
  1131. * Get collection ID by its name (exact match).
  1132. */
  1133. export function getCollectionIdByName(db: Database, name: string): number | null {
  1134. const result = db.prepare(`
  1135. SELECT id FROM collections
  1136. WHERE name = ?
  1137. LIMIT 1
  1138. `).get(name) as { id: number } | null;
  1139. return result?.id || null;
  1140. }
  1141. /**
  1142. * Get collection by name.
  1143. */
  1144. export function getCollectionByName(db: Database, name: string): { id: number; name: string; pwd: string; glob_pattern: string } | null {
  1145. const result = db.prepare(`
  1146. SELECT id, name, pwd, glob_pattern FROM collections
  1147. WHERE name = ?
  1148. LIMIT 1
  1149. `).get(name) as { id: number; name: string; pwd: string; glob_pattern: string } | null;
  1150. return result;
  1151. }
  1152. export function listCollections(db: Database): { id: number; name: string; pwd: string; glob_pattern: string; created_at: string; updated_at: string; doc_count: number; active_count: number; last_modified: string | null }[] {
  1153. const collections = db.prepare(`
  1154. SELECT c.id, c.name, c.pwd, c.glob_pattern, c.created_at, c.updated_at,
  1155. COUNT(d.id) as doc_count,
  1156. SUM(CASE WHEN d.active = 1 THEN 1 ELSE 0 END) as active_count,
  1157. MAX(d.modified_at) as last_modified
  1158. FROM collections c
  1159. LEFT JOIN documents d ON d.collection_id = c.id
  1160. GROUP BY c.id
  1161. ORDER BY c.name
  1162. `).all() as { id: number; name: string; pwd: string; glob_pattern: string; created_at: string; updated_at: string; doc_count: number; active_count: number; last_modified: string | null }[];
  1163. return collections;
  1164. }
  1165. export function removeCollection(db: Database, collectionId: number): { deletedDocs: number; cleanedHashes: number } {
  1166. // Delete documents
  1167. const docResult = db.prepare(`DELETE FROM documents WHERE collection_id = ?`).run(collectionId);
  1168. // Delete contexts
  1169. db.prepare(`DELETE FROM path_contexts WHERE collection_id = ?`).run(collectionId);
  1170. // Delete collection
  1171. db.prepare(`DELETE FROM collections WHERE id = ?`).run(collectionId);
  1172. // Clean up orphaned content hashes
  1173. const cleanupResult = db.prepare(`
  1174. DELETE FROM content
  1175. WHERE hash NOT IN (SELECT DISTINCT hash FROM documents WHERE active = 1)
  1176. `).run();
  1177. return {
  1178. deletedDocs: docResult.changes,
  1179. cleanedHashes: cleanupResult.changes
  1180. };
  1181. }
  1182. export function renameCollection(db: Database, collectionId: number, newName: string): void {
  1183. const now = new Date().toISOString();
  1184. db.prepare(`UPDATE collections SET name = ?, updated_at = ? WHERE id = ?`)
  1185. .run(newName, now, collectionId);
  1186. }
  1187. // =============================================================================
  1188. // Context Management Operations
  1189. // =============================================================================
  1190. /**
  1191. * Insert or update a context for a specific collection and path prefix.
  1192. */
  1193. export function insertContext(db: Database, collectionId: number, pathPrefix: string, context: string): void {
  1194. const now = new Date().toISOString();
  1195. db.prepare(`
  1196. INSERT INTO path_contexts (collection_id, path_prefix, context, created_at)
  1197. VALUES (?, ?, ?, ?)
  1198. ON CONFLICT(collection_id, path_prefix) DO UPDATE SET context = excluded.context
  1199. `).run(collectionId, pathPrefix, context, now);
  1200. }
  1201. /**
  1202. * Delete a context for a specific collection and path prefix.
  1203. * Returns the number of contexts deleted.
  1204. */
  1205. export function deleteContext(db: Database, collectionId: number, pathPrefix: string): number {
  1206. const result = db.prepare(`
  1207. DELETE FROM path_contexts
  1208. WHERE collection_id = ? AND path_prefix = ?
  1209. `).run(collectionId, pathPrefix);
  1210. return result.changes;
  1211. }
  1212. /**
  1213. * Delete all global contexts (contexts with empty path_prefix).
  1214. * Returns the number of contexts deleted.
  1215. */
  1216. export function deleteGlobalContexts(db: Database): number {
  1217. const result = db.prepare(`DELETE FROM path_contexts WHERE path_prefix = ''`).run();
  1218. return result.changes;
  1219. }
  1220. /**
  1221. * List all contexts, grouped by collection.
  1222. * Returns contexts ordered by collection name, then by path prefix length (longest first).
  1223. */
  1224. export function listPathContexts(db: Database): { collection_name: string; path_prefix: string; context: string }[] {
  1225. const contexts = db.prepare(`
  1226. SELECT c.name as collection_name, pc.path_prefix, pc.context
  1227. FROM path_contexts pc
  1228. JOIN collections c ON c.id = pc.collection_id
  1229. ORDER BY c.name, LENGTH(pc.path_prefix) DESC, pc.path_prefix
  1230. `).all() as { collection_name: string; path_prefix: string; context: string }[];
  1231. return contexts;
  1232. }
  1233. /**
  1234. * Get all collections (id and name).
  1235. */
  1236. export function getAllCollections(db: Database): { id: number; name: string }[] {
  1237. return db.prepare(`SELECT id, name FROM collections`).all() as { id: number; name: string }[];
  1238. }
  1239. // =============================================================================
  1240. // FTS Search
  1241. // =============================================================================
  1242. function sanitizeFTS5Term(term: string): string {
  1243. return term.replace(/[^\p{L}\p{N}']/gu, '').toLowerCase();
  1244. }
  1245. function buildFTS5Query(query: string): string | null {
  1246. const terms = query.split(/\s+/)
  1247. .map(t => sanitizeFTS5Term(t))
  1248. .filter(t => t.length > 0);
  1249. if (terms.length === 0) return null;
  1250. if (terms.length === 1) return `"${terms[0]}"*`;
  1251. return terms.map(t => `"${t}"*`).join(' AND ');
  1252. }
  1253. export function searchFTS(db: Database, query: string, limit: number = 20, collectionId?: number): SearchResult[] {
  1254. const ftsQuery = buildFTS5Query(query);
  1255. if (!ftsQuery) return [];
  1256. let sql = `
  1257. SELECT
  1258. 'qmd://' || c.name || '/' || d.path as filepath,
  1259. 'qmd://' || c.name || '/' || d.path as display_path,
  1260. d.title,
  1261. content.doc as body,
  1262. bm25(documents_fts, 10.0, 1.0) as score
  1263. FROM documents_fts f
  1264. JOIN documents d ON d.id = f.rowid
  1265. JOIN collections c ON c.id = d.collection_id
  1266. JOIN content ON content.hash = d.hash
  1267. WHERE documents_fts MATCH ? AND d.active = 1
  1268. `;
  1269. const params: (string | number)[] = [ftsQuery];
  1270. if (collectionId !== undefined) {
  1271. sql += ` AND d.collection_id = ?`;
  1272. params.push(collectionId);
  1273. }
  1274. sql += ` ORDER BY score LIMIT ?`;
  1275. params.push(limit);
  1276. const rows = db.prepare(sql).all(...params) as { filepath: string; display_path: string; title: string; body: string; score: number }[];
  1277. const maxScore = rows.length > 0 ? Math.max(...rows.map(r => Math.abs(r.score))) : 1;
  1278. return rows.map(row => ({
  1279. file: row.filepath,
  1280. displayPath: row.display_path,
  1281. title: row.title,
  1282. body: row.body,
  1283. score: Math.abs(row.score) / maxScore,
  1284. source: "fts" as const,
  1285. }));
  1286. }
  1287. // =============================================================================
  1288. // Vector Search
  1289. // =============================================================================
  1290. export async function searchVec(db: Database, query: string, model: string, limit: number = 20, collectionId?: number): Promise<SearchResult[]> {
  1291. const tableExists = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
  1292. if (!tableExists) return [];
  1293. const embedding = await getEmbedding(query, model, true);
  1294. if (!embedding) return [];
  1295. // sqlite-vec requires "k = ?" for KNN queries
  1296. let sql = `
  1297. SELECT
  1298. v.hash_seq,
  1299. v.distance,
  1300. 'qmd://' || c.name || '/' || d.path as filepath,
  1301. 'qmd://' || c.name || '/' || d.path as display_path,
  1302. d.title,
  1303. content.doc as body,
  1304. cv.pos
  1305. FROM vectors_vec v
  1306. JOIN content_vectors cv ON cv.hash || '_' || cv.seq = v.hash_seq
  1307. JOIN documents d ON d.hash = cv.hash AND d.active = 1
  1308. JOIN collections c ON c.id = d.collection_id
  1309. JOIN content ON content.hash = d.hash
  1310. WHERE v.embedding MATCH ? AND k = ?
  1311. `;
  1312. if (collectionId !== undefined) {
  1313. sql += ` AND d.collection_id = ${collectionId}`;
  1314. }
  1315. sql += ` ORDER BY v.distance`;
  1316. 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 }[];
  1317. const seen = new Map<string, { row: typeof rows[0]; bestDist: number }>();
  1318. for (const row of rows) {
  1319. const existing = seen.get(row.filepath);
  1320. if (!existing || row.distance < existing.bestDist) {
  1321. seen.set(row.filepath, { row, bestDist: row.distance });
  1322. }
  1323. }
  1324. return Array.from(seen.values())
  1325. .sort((a, b) => a.bestDist - b.bestDist)
  1326. .slice(0, limit)
  1327. .map(({ row }) => ({
  1328. file: row.filepath,
  1329. displayPath: row.display_path,
  1330. title: row.title,
  1331. body: row.body,
  1332. score: 1 / (1 + row.distance),
  1333. source: "vec" as const,
  1334. chunkPos: row.pos,
  1335. }));
  1336. }
  1337. // =============================================================================
  1338. // Embeddings
  1339. // =============================================================================
  1340. async function getEmbedding(text: string, model: string, isQuery: boolean): Promise<number[] | null> {
  1341. const ollama = getDefaultOllama();
  1342. const result = await ollama.embed(text, { model, isQuery });
  1343. return result?.embedding || null;
  1344. }
  1345. /**
  1346. * Get all unique content hashes that need embeddings (from active documents).
  1347. * Returns hash, document body, and a sample path for display purposes.
  1348. */
  1349. export function getHashesForEmbedding(db: Database): { hash: string; body: string; path: string }[] {
  1350. return db.prepare(`
  1351. SELECT d.hash, c.doc as body, MIN(d.path) as path
  1352. FROM documents d
  1353. JOIN content c ON d.hash = c.hash
  1354. LEFT JOIN content_vectors v ON d.hash = v.hash AND v.seq = 0
  1355. WHERE d.active = 1 AND v.hash IS NULL
  1356. GROUP BY d.hash
  1357. `).all() as { hash: string; body: string; path: string }[];
  1358. }
  1359. /**
  1360. * Clear all embeddings from the database (force re-index).
  1361. * Deletes all rows from content_vectors and drops the vectors_vec table.
  1362. */
  1363. export function clearAllEmbeddings(db: Database): void {
  1364. db.exec(`DELETE FROM content_vectors`);
  1365. db.exec(`DROP TABLE IF EXISTS vectors_vec`);
  1366. }
  1367. /**
  1368. * Insert a single embedding into both content_vectors and vectors_vec tables.
  1369. * The hash_seq key is formatted as "hash_seq" for the vectors_vec table.
  1370. */
  1371. export function insertEmbedding(
  1372. db: Database,
  1373. hash: string,
  1374. seq: number,
  1375. pos: number,
  1376. embedding: Float32Array,
  1377. model: string,
  1378. embeddedAt: string
  1379. ): void {
  1380. const hashSeq = `${hash}_${seq}`;
  1381. const insertVecStmt = db.prepare(`INSERT OR REPLACE INTO vectors_vec (hash_seq, embedding) VALUES (?, ?)`);
  1382. const insertContentVectorStmt = db.prepare(`INSERT OR REPLACE INTO content_vectors (hash, seq, pos, model, embedded_at) VALUES (?, ?, ?, ?, ?)`);
  1383. insertVecStmt.run(hashSeq, embedding);
  1384. insertContentVectorStmt.run(hash, seq, pos, model, embeddedAt);
  1385. }
  1386. // =============================================================================
  1387. // Query expansion
  1388. // =============================================================================
  1389. export async function expandQuery(query: string, model: string = DEFAULT_QUERY_MODEL, db: Database): Promise<string[]> {
  1390. // Check cache first
  1391. const cacheKey = getCacheKey("expandQuery", { query, model });
  1392. const cached = getCachedResult(db, cacheKey);
  1393. if (cached) {
  1394. const lines = cached.split('\n').map(l => l.trim()).filter(l => l.length > 0);
  1395. return [query, ...lines.slice(0, 2)];
  1396. }
  1397. const ollama = getDefaultOllama();
  1398. const results = await ollama.expandQuery(query, model, 2);
  1399. // Cache the expanded queries (excluding original)
  1400. if (results.length > 1) {
  1401. setCachedResult(db, cacheKey, results.slice(1).join('\n'));
  1402. }
  1403. return results;
  1404. }
  1405. // =============================================================================
  1406. // Reranking
  1407. // =============================================================================
  1408. export async function rerank(query: string, documents: { file: string; text: string }[], model: string = DEFAULT_RERANK_MODEL, db: Database): Promise<{ file: string; score: number }[]> {
  1409. const cachedResults: Map<string, number> = new Map();
  1410. const uncachedDocs: RerankDocument[] = [];
  1411. // Check cache for each document
  1412. for (const doc of documents) {
  1413. const cacheKey = getCacheKey("rerank", { query, file: doc.file, model });
  1414. const cached = getCachedResult(db, cacheKey);
  1415. if (cached !== null) {
  1416. cachedResults.set(doc.file, parseFloat(cached));
  1417. } else {
  1418. uncachedDocs.push({ file: doc.file, text: doc.text });
  1419. }
  1420. }
  1421. // Rerank uncached documents using Ollama
  1422. if (uncachedDocs.length > 0) {
  1423. const ollama = getDefaultOllama();
  1424. const rerankResult = await ollama.rerank(query, uncachedDocs, { model });
  1425. // Cache results
  1426. for (const result of rerankResult.results) {
  1427. const cacheKey = getCacheKey("rerank", { query, file: result.file, model });
  1428. setCachedResult(db, cacheKey, result.score.toString());
  1429. cachedResults.set(result.file, result.score);
  1430. }
  1431. }
  1432. // Return all results sorted by score
  1433. return documents
  1434. .map(doc => ({ file: doc.file, score: cachedResults.get(doc.file) || 0 }))
  1435. .sort((a, b) => b.score - a.score);
  1436. }
  1437. // =============================================================================
  1438. // Reciprocal Rank Fusion
  1439. // =============================================================================
  1440. export function reciprocalRankFusion(
  1441. resultLists: RankedResult[][],
  1442. weights: number[] = [],
  1443. k: number = 60
  1444. ): RankedResult[] {
  1445. const scores = new Map<string, { result: RankedResult; rrfScore: number; topRank: number }>();
  1446. for (let listIdx = 0; listIdx < resultLists.length; listIdx++) {
  1447. const list = resultLists[listIdx];
  1448. const weight = weights[listIdx] ?? 1.0;
  1449. for (let rank = 0; rank < list.length; rank++) {
  1450. const result = list[rank];
  1451. const rrfContribution = weight / (k + rank + 1);
  1452. const existing = scores.get(result.file);
  1453. if (existing) {
  1454. existing.rrfScore += rrfContribution;
  1455. existing.topRank = Math.min(existing.topRank, rank);
  1456. } else {
  1457. scores.set(result.file, {
  1458. result,
  1459. rrfScore: rrfContribution,
  1460. topRank: rank,
  1461. });
  1462. }
  1463. }
  1464. }
  1465. // Top-rank bonus
  1466. for (const entry of scores.values()) {
  1467. if (entry.topRank === 0) {
  1468. entry.rrfScore += 0.05;
  1469. } else if (entry.topRank <= 2) {
  1470. entry.rrfScore += 0.02;
  1471. }
  1472. }
  1473. return Array.from(scores.values())
  1474. .sort((a, b) => b.rrfScore - a.rrfScore)
  1475. .map(e => ({ ...e.result, score: e.rrfScore }));
  1476. }
  1477. // =============================================================================
  1478. // Document retrieval
  1479. // =============================================================================
  1480. type DbDocRow = {
  1481. filepath: string;
  1482. display_path: string;
  1483. title: string;
  1484. hash: string;
  1485. collection_id: number;
  1486. modified_at: string;
  1487. body_length: number;
  1488. body?: string;
  1489. };
  1490. /**
  1491. * Find a document by filename/path (with fuzzy matching)
  1492. * Returns document metadata without body by default
  1493. */
  1494. export function findDocument(db: Database, filename: string, options: { includeBody?: boolean } = {}): DocumentResult | DocumentNotFound {
  1495. let filepath = filename;
  1496. const colonMatch = filepath.match(/:(\d+)$/);
  1497. if (colonMatch) {
  1498. filepath = filepath.slice(0, -colonMatch[0].length);
  1499. }
  1500. if (filepath.startsWith('~/')) {
  1501. filepath = homedir() + filepath.slice(1);
  1502. }
  1503. const selectCols = options.includeBody
  1504. ? `filepath, display_path, title, hash, collection_id, modified_at, LENGTH(body) as body_length, body`
  1505. : `filepath, display_path, title, hash, collection_id, modified_at, LENGTH(body) as body_length`;
  1506. // Try various match strategies
  1507. let doc = db.prepare(`SELECT ${selectCols} FROM documents WHERE filepath = ? AND active = 1`).get(filepath) as DbDocRow | null;
  1508. if (!doc) {
  1509. doc = db.prepare(`SELECT ${selectCols} FROM documents WHERE display_path = ? AND active = 1`).get(filepath) as DbDocRow | null;
  1510. }
  1511. if (!doc) {
  1512. doc = db.prepare(`SELECT ${selectCols} FROM documents WHERE filepath LIKE ? AND active = 1 LIMIT 1`).get(`%${filepath}`) as DbDocRow | null;
  1513. }
  1514. if (!doc) {
  1515. doc = db.prepare(`SELECT ${selectCols} FROM documents WHERE display_path LIKE ? AND active = 1 LIMIT 1`).get(`%${filepath}`) as DbDocRow | null;
  1516. }
  1517. if (!doc) {
  1518. const similar = findSimilarFiles(db, filepath, 5, 5);
  1519. return { error: "not_found", query: filename, similarFiles: similar };
  1520. }
  1521. const context = getContextForFile(db, doc.filepath);
  1522. return {
  1523. filepath: doc.filepath,
  1524. displayPath: doc.display_path,
  1525. title: doc.title,
  1526. context,
  1527. hash: doc.hash,
  1528. collectionId: doc.collection_id,
  1529. modifiedAt: doc.modified_at,
  1530. bodyLength: doc.body_length,
  1531. ...(options.includeBody && doc.body !== undefined && { body: doc.body }),
  1532. };
  1533. }
  1534. /**
  1535. * Get the body content for a document
  1536. * Optionally slice by line range
  1537. */
  1538. export function getDocumentBody(db: Database, doc: DocumentResult | { filepath: string }, fromLine?: number, maxLines?: number): string | null {
  1539. const filepath = 'filepath' in doc ? doc.filepath : doc.filepath;
  1540. const row = db.prepare(`SELECT body FROM documents WHERE filepath = ? AND active = 1`).get(filepath) as { body: string } | null;
  1541. if (!row) return null;
  1542. let body = row.body;
  1543. if (fromLine !== undefined || maxLines !== undefined) {
  1544. const lines = body.split('\n');
  1545. const start = (fromLine || 1) - 1;
  1546. const end = maxLines !== undefined ? start + maxLines : lines.length;
  1547. body = lines.slice(start, end).join('\n');
  1548. }
  1549. return body;
  1550. }
  1551. /**
  1552. * Legacy function for backwards compatibility
  1553. * Combines findDocument + getDocumentBody with line slicing
  1554. */
  1555. export function getDocument(db: Database, filename: string, fromLine?: number, maxLines?: number): (DocumentResult & { body: string }) | DocumentNotFound {
  1556. // Parse :line suffix
  1557. let parsedFromLine = fromLine;
  1558. let filepath = filename;
  1559. const colonMatch = filepath.match(/:(\d+)$/);
  1560. if (colonMatch && !parsedFromLine) {
  1561. parsedFromLine = parseInt(colonMatch[1], 10);
  1562. filepath = filepath.slice(0, -colonMatch[0].length);
  1563. }
  1564. const result = findDocument(db, filepath, { includeBody: true });
  1565. if ("error" in result) return result;
  1566. let body = result.body || "";
  1567. if (parsedFromLine !== undefined || maxLines !== undefined) {
  1568. const lines = body.split('\n');
  1569. const start = (parsedFromLine || 1) - 1;
  1570. const end = maxLines !== undefined ? start + maxLines : lines.length;
  1571. body = lines.slice(start, end).join('\n');
  1572. }
  1573. return { ...result, body };
  1574. }
  1575. /**
  1576. * Find multiple documents by glob pattern or comma-separated list
  1577. * Returns documents without body by default (use getDocumentBody to load)
  1578. */
  1579. export function findDocuments(
  1580. db: Database,
  1581. pattern: string,
  1582. options: { includeBody?: boolean; maxBytes?: number } = {}
  1583. ): { docs: MultiGetResult[]; errors: string[] } {
  1584. const isCommaSeparated = pattern.includes(',') && !pattern.includes('*') && !pattern.includes('?');
  1585. const errors: string[] = [];
  1586. const maxBytes = options.maxBytes ?? DEFAULT_MULTI_GET_MAX_BYTES;
  1587. const selectCols = options.includeBody
  1588. ? `filepath, display_path, title, hash, collection_id, modified_at, LENGTH(body) as body_length, body`
  1589. : `filepath, display_path, title, hash, collection_id, modified_at, LENGTH(body) as body_length`;
  1590. let fileRows: DbDocRow[];
  1591. if (isCommaSeparated) {
  1592. const names = pattern.split(',').map(s => s.trim()).filter(Boolean);
  1593. fileRows = [];
  1594. for (const name of names) {
  1595. let doc = db.prepare(`SELECT ${selectCols} FROM documents WHERE display_path = ? AND active = 1`).get(name) as DbDocRow | null;
  1596. if (!doc) {
  1597. doc = db.prepare(`SELECT ${selectCols} FROM documents WHERE display_path LIKE ? AND active = 1 LIMIT 1`).get(`%${name}`) as DbDocRow | null;
  1598. }
  1599. if (doc) {
  1600. fileRows.push(doc);
  1601. } else {
  1602. const similar = findSimilarFiles(db, name, 5, 3);
  1603. let msg = `File not found: ${name}`;
  1604. if (similar.length > 0) {
  1605. msg += ` (did you mean: ${similar.join(', ')}?)`;
  1606. }
  1607. errors.push(msg);
  1608. }
  1609. }
  1610. } else {
  1611. // Glob pattern match
  1612. const matched = matchFilesByGlob(db, pattern);
  1613. if (matched.length === 0) {
  1614. errors.push(`No files matched pattern: ${pattern}`);
  1615. return { docs: [], errors };
  1616. }
  1617. const filepaths = matched.map(m => m.filepath);
  1618. const placeholders = filepaths.map(() => '?').join(',');
  1619. fileRows = db.prepare(`SELECT ${selectCols} FROM documents WHERE filepath IN (${placeholders}) AND active = 1`).all(...filepaths) as DbDocRow[];
  1620. }
  1621. const results: MultiGetResult[] = [];
  1622. for (const row of fileRows) {
  1623. const context = getContextForFile(db, row.filepath);
  1624. if (row.body_length > maxBytes) {
  1625. results.push({
  1626. doc: { filepath: row.filepath, displayPath: row.display_path },
  1627. skipped: true,
  1628. skipReason: `File too large (${Math.round(row.body_length / 1024)}KB > ${Math.round(maxBytes / 1024)}KB)`,
  1629. });
  1630. continue;
  1631. }
  1632. results.push({
  1633. doc: {
  1634. filepath: row.filepath,
  1635. displayPath: row.display_path,
  1636. title: row.title || row.display_path.split('/').pop() || row.display_path,
  1637. context,
  1638. hash: row.hash,
  1639. collectionId: row.collection_id,
  1640. modifiedAt: row.modified_at,
  1641. bodyLength: row.body_length,
  1642. ...(options.includeBody && row.body !== undefined && { body: row.body }),
  1643. },
  1644. skipped: false,
  1645. });
  1646. }
  1647. return { docs: results, errors };
  1648. }
  1649. /**
  1650. * Legacy function for backwards compatibility
  1651. */
  1652. export function getMultipleDocuments(db: Database, pattern: string, maxLines?: number, maxBytes: number = DEFAULT_MULTI_GET_MAX_BYTES): { files: MultiGetFile[]; errors: string[] } {
  1653. const { docs, errors } = findDocuments(db, pattern, { includeBody: true, maxBytes });
  1654. const files: MultiGetFile[] = docs.map(result => {
  1655. if (result.skipped) {
  1656. return {
  1657. filepath: result.doc.filepath,
  1658. displayPath: result.doc.displayPath,
  1659. title: "",
  1660. body: "",
  1661. context: null,
  1662. skipped: true as const,
  1663. skipReason: result.skipReason,
  1664. };
  1665. }
  1666. let body = result.doc.body || "";
  1667. if (maxLines !== undefined) {
  1668. const lines = body.split('\n');
  1669. body = lines.slice(0, maxLines).join('\n');
  1670. if (lines.length > maxLines) {
  1671. body += `\n\n[... truncated ${lines.length - maxLines} more lines]`;
  1672. }
  1673. }
  1674. return {
  1675. filepath: result.doc.filepath,
  1676. displayPath: result.doc.displayPath,
  1677. title: result.doc.title,
  1678. body,
  1679. context: result.doc.context,
  1680. skipped: false as const,
  1681. };
  1682. });
  1683. return { files, errors };
  1684. }
  1685. // Keep the old MultiGetFile type for backwards compatibility
  1686. export type MultiGetFile = {
  1687. filepath: string;
  1688. displayPath: string;
  1689. title: string;
  1690. body: string;
  1691. context: string | null;
  1692. skipped: false;
  1693. } | {
  1694. filepath: string;
  1695. displayPath: string;
  1696. title: string;
  1697. body: string;
  1698. context: string | null;
  1699. skipped: true;
  1700. skipReason: string;
  1701. };
  1702. // =============================================================================
  1703. // Status
  1704. // =============================================================================
  1705. export function getStatus(db: Database): IndexStatus {
  1706. const collections = db.prepare(`
  1707. SELECT c.id, c.pwd, c.glob_pattern, c.created_at,
  1708. COUNT(d.id) as active_count,
  1709. MAX(d.modified_at) as last_doc_update
  1710. FROM collections c
  1711. LEFT JOIN documents d ON d.collection_id = c.id AND d.active = 1
  1712. GROUP BY c.id
  1713. ORDER BY last_doc_update DESC
  1714. `).all() as { id: number; pwd: string; glob_pattern: string; created_at: string; active_count: number; last_doc_update: string | null }[];
  1715. const totalDocs = (db.prepare(`SELECT COUNT(*) as c FROM documents WHERE active = 1`).get() as { c: number }).c;
  1716. const needsEmbedding = getHashesNeedingEmbedding(db);
  1717. const hasVectors = !!db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
  1718. return {
  1719. totalDocuments: totalDocs,
  1720. needsEmbedding,
  1721. hasVectorIndex: hasVectors,
  1722. collections: collections.map(col => ({
  1723. id: col.id,
  1724. path: col.pwd,
  1725. pattern: col.glob_pattern,
  1726. documents: col.active_count,
  1727. lastUpdated: col.last_doc_update || col.created_at,
  1728. })),
  1729. };
  1730. }
  1731. // =============================================================================
  1732. // Snippet extraction
  1733. // =============================================================================
  1734. export type SnippetResult = {
  1735. line: number; // 1-indexed line number of best match
  1736. snippet: string; // The snippet text with diff-style header
  1737. linesBefore: number; // Lines in document before snippet
  1738. linesAfter: number; // Lines in document after snippet
  1739. snippetLines: number; // Number of lines in snippet
  1740. };
  1741. export function extractSnippet(body: string, query: string, maxLen = 500, chunkPos?: number): SnippetResult {
  1742. const totalLines = body.split('\n').length;
  1743. let searchBody = body;
  1744. let lineOffset = 0;
  1745. if (chunkPos && chunkPos > 0) {
  1746. const contextStart = Math.max(0, chunkPos - 100);
  1747. const contextEnd = Math.min(body.length, chunkPos + maxLen + 100);
  1748. searchBody = body.slice(contextStart, contextEnd);
  1749. if (contextStart > 0) {
  1750. lineOffset = body.slice(0, contextStart).split('\n').length - 1;
  1751. }
  1752. }
  1753. const lines = searchBody.split('\n');
  1754. const queryTerms = query.toLowerCase().split(/\s+/).filter(t => t.length > 0);
  1755. let bestLine = 0, bestScore = -1;
  1756. for (let i = 0; i < lines.length; i++) {
  1757. const lineLower = lines[i].toLowerCase();
  1758. let score = 0;
  1759. for (const term of queryTerms) {
  1760. if (lineLower.includes(term)) score++;
  1761. }
  1762. if (score > bestScore) {
  1763. bestScore = score;
  1764. bestLine = i;
  1765. }
  1766. }
  1767. const start = Math.max(0, bestLine - 1);
  1768. const end = Math.min(lines.length, bestLine + 3);
  1769. const snippetLines = lines.slice(start, end);
  1770. let snippetText = snippetLines.join('\n');
  1771. if (snippetText.length > maxLen) snippetText = snippetText.substring(0, maxLen - 3) + "...";
  1772. const absoluteStart = lineOffset + start + 1; // 1-indexed
  1773. const snippetLineCount = snippetLines.length;
  1774. const linesBefore = absoluteStart - 1;
  1775. const linesAfter = totalLines - (absoluteStart + snippetLineCount - 1);
  1776. // Format with diff-style header: @@ -start,count @@ (linesBefore before, linesAfter after)
  1777. const header = `@@ -${absoluteStart},${snippetLineCount} @@ (${linesBefore} before, ${linesAfter} after)`;
  1778. const snippet = `${header}\n${snippetText}`;
  1779. return {
  1780. line: lineOffset + bestLine + 1,
  1781. snippet,
  1782. linesBefore,
  1783. linesAfter,
  1784. snippetLines: snippetLineCount,
  1785. };
  1786. }