qmd.ts 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661
  1. #!/usr/bin/env bun
  2. import { Database } from "bun:sqlite";
  3. import { Glob, $ } from "bun";
  4. import { parseArgs } from "util";
  5. import * as sqliteVec from "sqlite-vec";
  6. import {
  7. getDb,
  8. closeDb,
  9. getDbPath,
  10. getPwd,
  11. getRealPath,
  12. homedir,
  13. resolve,
  14. setCustomIndexName,
  15. searchFTS,
  16. searchVec,
  17. reciprocalRankFusion,
  18. extractSnippet,
  19. getContextForFile,
  20. getContextForPath,
  21. getCollectionIdByName,
  22. getCollectionByName,
  23. listCollections,
  24. removeCollection,
  25. renameCollection,
  26. findSimilarFiles,
  27. matchFilesByGlob,
  28. getHashesNeedingEmbedding,
  29. getDocument as storeGetDocument,
  30. getMultipleDocuments as storeMultiGetDocuments,
  31. getStatus,
  32. hashContent,
  33. extractTitle,
  34. formatDocForEmbedding,
  35. formatQueryForEmbedding,
  36. chunkDocument,
  37. ensureVecTable,
  38. clearCache,
  39. getCacheKey,
  40. getCachedResult,
  41. setCachedResult,
  42. getIndexHealth,
  43. parseVirtualPath,
  44. buildVirtualPath,
  45. isVirtualPath,
  46. resolveVirtualPath,
  47. toVirtualPath,
  48. OLLAMA_URL,
  49. DEFAULT_EMBED_MODEL,
  50. DEFAULT_QUERY_MODEL,
  51. DEFAULT_RERANK_MODEL,
  52. DEFAULT_GLOB,
  53. DEFAULT_MULTI_GET_MAX_BYTES,
  54. } from "./store.js";
  55. import type { SearchResult, RankedResult } from "./store.js";
  56. import {
  57. formatSearchResults,
  58. formatDocuments,
  59. escapeXml,
  60. escapeCSV,
  61. type OutputFormat,
  62. } from "./formatter.js";
  63. // Chunking: ~2000 tokens per chunk, ~3 bytes/token = 6KB
  64. const CHUNK_BYTE_SIZE = 6 * 1024;
  65. // Terminal colors (respects NO_COLOR env)
  66. const useColor = !process.env.NO_COLOR && process.stdout.isTTY;
  67. const c = {
  68. reset: useColor ? "\x1b[0m" : "",
  69. dim: useColor ? "\x1b[2m" : "",
  70. bold: useColor ? "\x1b[1m" : "",
  71. cyan: useColor ? "\x1b[36m" : "",
  72. yellow: useColor ? "\x1b[33m" : "",
  73. green: useColor ? "\x1b[32m" : "",
  74. magenta: useColor ? "\x1b[35m" : "",
  75. blue: useColor ? "\x1b[34m" : "",
  76. };
  77. // Terminal cursor control
  78. const cursor = {
  79. hide() { process.stderr.write('\x1b[?25l'); },
  80. show() { process.stderr.write('\x1b[?25h'); },
  81. };
  82. // Ensure cursor is restored on exit
  83. process.on('SIGINT', () => { cursor.show(); process.exit(130); });
  84. process.on('SIGTERM', () => { cursor.show(); process.exit(143); });
  85. // Terminal progress bar using OSC 9;4 escape sequence
  86. const progress = {
  87. set(percent: number) {
  88. process.stderr.write(`\x1b]9;4;1;${Math.round(percent)}\x07`);
  89. },
  90. clear() {
  91. process.stderr.write(`\x1b]9;4;0\x07`);
  92. },
  93. indeterminate() {
  94. process.stderr.write(`\x1b]9;4;3\x07`);
  95. },
  96. error() {
  97. process.stderr.write(`\x1b]9;4;2\x07`);
  98. },
  99. };
  100. // Format seconds into human-readable ETA
  101. function formatETA(seconds: number): string {
  102. if (seconds < 60) return `${Math.round(seconds)}s`;
  103. if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`;
  104. return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;
  105. }
  106. // Check index health and print warnings/tips
  107. function checkIndexHealth(db: Database): void {
  108. const { needsEmbedding, totalDocs, daysStale } = getIndexHealth(db);
  109. // Warn if many docs need embedding
  110. if (needsEmbedding > 0) {
  111. const pct = Math.round((needsEmbedding / totalDocs) * 100);
  112. if (pct >= 10) {
  113. process.stderr.write(`${c.yellow}Warning: ${needsEmbedding} documents (${pct}%) need embeddings. Run 'qmd embed' for better results.${c.reset}\n`);
  114. } else {
  115. process.stderr.write(`${c.dim}Tip: ${needsEmbedding} documents need embeddings. Run 'qmd embed' to index them.${c.reset}\n`);
  116. }
  117. }
  118. // Check if most recent document update is older than 2 weeks
  119. if (daysStale !== null && daysStale >= 14) {
  120. process.stderr.write(`${c.dim}Tip: Index last updated ${daysStale} days ago. Run 'qmd update' to refresh.${c.reset}\n`);
  121. }
  122. }
  123. // Compute unique display path for a document
  124. // Always include at least parent folder + filename, add more parent dirs until unique
  125. function computeDisplayPath(
  126. filepath: string,
  127. collectionPath: string,
  128. existingPaths: Set<string>
  129. ): string {
  130. // Get path relative to collection (include collection dir name)
  131. const collectionDir = collectionPath.replace(/\/$/, '');
  132. const collectionName = collectionDir.split('/').pop() || '';
  133. let relativePath: string;
  134. if (filepath.startsWith(collectionDir + '/')) {
  135. // filepath is under collection: use collection name + relative path
  136. relativePath = collectionName + filepath.slice(collectionDir.length);
  137. } else {
  138. // Fallback: just use the filepath
  139. relativePath = filepath;
  140. }
  141. const parts = relativePath.split('/').filter(p => p.length > 0);
  142. // Always include at least parent folder + filename (minimum 2 parts if available)
  143. // Then add more parent dirs until unique
  144. const minParts = Math.min(2, parts.length);
  145. for (let i = parts.length - minParts; i >= 0; i--) {
  146. const candidate = parts.slice(i).join('/');
  147. if (!existingPaths.has(candidate)) {
  148. return candidate;
  149. }
  150. }
  151. // Absolute fallback: use full path (should be unique)
  152. return filepath;
  153. }
  154. // Auto-pull model if not found
  155. async function ensureModelAvailable(model: string): Promise<void> {
  156. try {
  157. const response = await fetch(`${OLLAMA_URL}/api/show`, {
  158. method: "POST",
  159. headers: { "Content-Type": "application/json" },
  160. body: JSON.stringify({ name: model }),
  161. });
  162. if (response.ok) return;
  163. } catch {
  164. // Continue to pull attempt
  165. }
  166. console.log(`Model ${model} not found. Pulling...`);
  167. progress.indeterminate();
  168. const pullResponse = await fetch(`${OLLAMA_URL}/api/pull`, {
  169. method: "POST",
  170. headers: { "Content-Type": "application/json" },
  171. body: JSON.stringify({ name: model, stream: false }),
  172. });
  173. if (!pullResponse.ok) {
  174. progress.error();
  175. throw new Error(`Failed to pull model ${model}: ${pullResponse.status} - ${await pullResponse.text()}`);
  176. }
  177. progress.clear();
  178. console.log(`Model ${model} pulled successfully.`);
  179. }
  180. async function getEmbedding(text: string, model: string, isQuery: boolean = false, title?: string, retried: boolean = false): Promise<number[]> {
  181. const input = isQuery ? formatQueryForEmbedding(text) : formatDocForEmbedding(text, title);
  182. const response = await fetch(`${OLLAMA_URL}/api/embed`, {
  183. method: "POST",
  184. headers: { "Content-Type": "application/json" },
  185. body: JSON.stringify({ model, input }),
  186. });
  187. if (!response.ok) {
  188. const errorText = await response.text();
  189. if (!retried && (errorText.includes("not found") || errorText.includes("does not exist"))) {
  190. await ensureModelAvailable(model);
  191. return getEmbedding(text, model, isQuery, title, true);
  192. }
  193. throw new Error(`Ollama API error: ${response.status} - ${errorText}`);
  194. }
  195. const data = await response.json() as { embeddings: number[][] };
  196. return data.embeddings[0];
  197. }
  198. // Qwen3-Reranker prompt format (trained for yes/no relevance classification)
  199. const RERANK_SYSTEM = `Judge whether the Document meets the requirements based on the Query and the Instruct provided. Note that the answer can only be "yes" or "no".`;
  200. function formatRerankPrompt(query: string, title: string, doc: string): string {
  201. return `<Instruct>: Determine if this document from a Shopify knowledge base is relevant to the search query. The query may reference specific Shopify programs, competitions, features, or named concepts (e.g., "Build a Business" competition, "Shop Pay", "Polaris"). Match documents that discuss the queried topic, even if phrasing differs.
  202. <Query>: ${query}
  203. <Document Title>: ${title}
  204. <Document>: ${doc}`;
  205. }
  206. type LogProb = { token: string; logprob: number };
  207. type RerankResponse = {
  208. response: string;
  209. logprobs?: LogProb[];
  210. };
  211. function parseRerankResponse(data: RerankResponse): number {
  212. if (!data.logprobs || data.logprobs.length === 0) {
  213. throw new Error("Reranker response missing logprobs");
  214. }
  215. const firstToken = data.logprobs[0];
  216. const token = firstToken.token.toLowerCase().trim();
  217. const confidence = Math.exp(firstToken.logprob);
  218. if (token === "yes") {
  219. return confidence;
  220. }
  221. if (token === "no") {
  222. return (1 - confidence) * 0.3;
  223. }
  224. throw new Error(`Unexpected reranker token: "${token}"`);
  225. }
  226. async function rerankSingle(prompt: string, model: string, db?: Database, retried: boolean = false): Promise<number> {
  227. // Use generate with raw template for qwen3-reranker format
  228. // Include empty <think> tags as per HuggingFace reference implementation
  229. const fullPrompt = `<|im_start|>system
  230. ${RERANK_SYSTEM}<|im_end|>
  231. <|im_start|>user
  232. ${prompt}<|im_end|>
  233. <|im_start|>assistant
  234. <think>
  235. </think>
  236. `;
  237. const requestBody = {
  238. model,
  239. prompt: fullPrompt,
  240. raw: true,
  241. stream: false,
  242. logprobs: true,
  243. options: { num_predict: 1 },
  244. };
  245. // Check cache
  246. const cacheKey = db ? getCacheKey(`${OLLAMA_URL}/api/generate`, requestBody) : "";
  247. if (db) {
  248. const cached = getCachedResult(db, cacheKey);
  249. if (cached) {
  250. const data = JSON.parse(cached) as RerankResponse;
  251. return parseRerankResponse(data);
  252. }
  253. }
  254. const response = await fetch(`${OLLAMA_URL}/api/generate`, {
  255. method: "POST",
  256. headers: { "Content-Type": "application/json" },
  257. body: JSON.stringify(requestBody),
  258. });
  259. if (!response.ok) {
  260. const errorText = await response.text();
  261. if (!retried && (errorText.includes("not found") || errorText.includes("does not exist"))) {
  262. await ensureModelAvailable(model);
  263. return rerankSingle(prompt, model, db, true);
  264. }
  265. throw new Error(`Ollama API error: ${response.status} - ${errorText}`);
  266. }
  267. const data = await response.json() as RerankResponse;
  268. // Cache the result
  269. if (db) {
  270. setCachedResult(db, cacheKey, JSON.stringify(data));
  271. }
  272. return parseRerankResponse(data);
  273. }
  274. async function rerank(query: string, documents: { file: string; text: string }[], model: string = DEFAULT_RERANK_MODEL, db?: Database): Promise<{ file: string; score: number }[]> {
  275. const results: { file: string; score: number }[] = [];
  276. const total = documents.length;
  277. const PARALLEL = 5;
  278. process.stderr.write(`Reranking ${total} documents with ${model} (parallel: ${PARALLEL})...\n`);
  279. progress.indeterminate();
  280. // Process in parallel batches
  281. for (let i = 0; i < documents.length; i += PARALLEL) {
  282. const batch = documents.slice(i, i + PARALLEL);
  283. const batchResults = await Promise.all(
  284. batch.map(async (doc) => {
  285. try {
  286. // Extract title from filename for reranker context
  287. const title = doc.file.split('/').pop()?.replace(/\.md$/, '') || doc.file;
  288. const prompt = formatRerankPrompt(query, title, doc.text.slice(0, 4000));
  289. const score = await rerankSingle(prompt, model, db);
  290. return { file: doc.file, score };
  291. } catch (err) {
  292. return { file: doc.file, score: 0 };
  293. }
  294. })
  295. );
  296. results.push(...batchResults);
  297. const processed = Math.min(i + PARALLEL, total);
  298. progress.set((processed / total) * 100);
  299. process.stderr.write(`\rReranking: ${processed}/${total}`);
  300. }
  301. progress.clear();
  302. process.stderr.write("\n");
  303. return results.sort((a, b) => b.score - a.score);
  304. }
  305. function getOrCreateCollection(db: Database, pwd: string, globPattern: string, name?: string): number {
  306. const now = new Date().toISOString();
  307. // Generate collection name from pwd basename if not provided
  308. if (!name) {
  309. const parts = pwd.split('/').filter(Boolean);
  310. name = parts[parts.length - 1] || 'root';
  311. }
  312. // Check if collection with this pwd+glob already exists
  313. const existing = db.prepare(`SELECT id FROM collections WHERE pwd = ? AND glob_pattern = ?`).get(pwd, globPattern) as { id: number } | null;
  314. if (existing) return existing.id;
  315. // Try to insert with generated name
  316. try {
  317. const result = db.prepare(`INSERT INTO collections (name, pwd, glob_pattern, created_at, updated_at) VALUES (?, ?, ?, ?, ?)`).run(name, pwd, globPattern, now, now);
  318. return result.lastInsertRowid as number;
  319. } catch (e) {
  320. // Name collision - append a unique suffix
  321. const allCollections = db.prepare(`SELECT name FROM collections WHERE name LIKE ?`).all(`${name}%`) as { name: string }[];
  322. let suffix = 2;
  323. let uniqueName = `${name}-${suffix}`;
  324. while (allCollections.some(c => c.name === uniqueName)) {
  325. suffix++;
  326. uniqueName = `${name}-${suffix}`;
  327. }
  328. const result = db.prepare(`INSERT INTO collections (name, pwd, glob_pattern, created_at, updated_at) VALUES (?, ?, ?, ?, ?)`).run(uniqueName, pwd, globPattern, now, now);
  329. return result.lastInsertRowid as number;
  330. }
  331. }
  332. function cleanupDuplicateCollections(db: Database): void {
  333. // Remove duplicate collections keeping the oldest one
  334. db.exec(`
  335. DELETE FROM collections WHERE id NOT IN (
  336. SELECT MIN(id) FROM collections GROUP BY pwd, glob_pattern
  337. )
  338. `);
  339. // Remove bogus "." glob pattern entries (from earlier bug)
  340. db.exec(`DELETE FROM collections WHERE glob_pattern = '.'`);
  341. }
  342. function formatTimeAgo(date: Date): string {
  343. const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
  344. if (seconds < 60) return `${seconds}s ago`;
  345. const minutes = Math.floor(seconds / 60);
  346. if (minutes < 60) return `${minutes}m ago`;
  347. const hours = Math.floor(minutes / 60);
  348. if (hours < 24) return `${hours}h ago`;
  349. const days = Math.floor(hours / 24);
  350. return `${days}d ago`;
  351. }
  352. function formatBytes(bytes: number): string {
  353. if (bytes < 1024) return `${bytes} B`;
  354. if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  355. if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  356. return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
  357. }
  358. function showStatus(): void {
  359. const dbPath = getDbPath();
  360. const db = getDb();
  361. // Cleanup any duplicate collections
  362. cleanupDuplicateCollections(db);
  363. // Index size
  364. let indexSize = 0;
  365. try {
  366. const stat = Bun.file(dbPath).size;
  367. indexSize = stat;
  368. } catch {}
  369. // Collections info
  370. const collections = db.prepare(`
  371. SELECT c.id, c.name, c.pwd, c.glob_pattern, c.created_at,
  372. COUNT(d.id) as doc_count,
  373. SUM(CASE WHEN d.active = 1 THEN 1 ELSE 0 END) as active_count,
  374. MAX(d.modified_at) as last_modified
  375. FROM collections c
  376. LEFT JOIN documents d ON d.collection_id = c.id
  377. GROUP BY c.id
  378. ORDER BY c.name
  379. `).all() as { id: number; name: string; pwd: string; glob_pattern: string; created_at: string; doc_count: number; active_count: number; last_modified: string | null }[];
  380. // Overall stats
  381. const totalDocs = db.prepare(`SELECT COUNT(*) as count FROM documents WHERE active = 1`).get() as { count: number };
  382. const vectorCount = db.prepare(`SELECT COUNT(*) as count FROM content_vectors`).get() as { count: number };
  383. const needsEmbedding = getHashesNeedingEmbedding(db);
  384. // Most recent update across all collections
  385. const mostRecent = db.prepare(`SELECT MAX(modified_at) as latest FROM documents WHERE active = 1`).get() as { latest: string | null };
  386. console.log(`${c.bold}QMD Status${c.reset}\n`);
  387. console.log(`Index: ${dbPath}`);
  388. console.log(`Size: ${formatBytes(indexSize)}\n`);
  389. console.log(`${c.bold}Documents${c.reset}`);
  390. console.log(` Total: ${totalDocs.count} files indexed`);
  391. console.log(` Vectors: ${vectorCount.count} embedded`);
  392. if (needsEmbedding > 0) {
  393. console.log(` ${c.yellow}Pending: ${needsEmbedding} need embedding${c.reset} (run 'qmd embed')`);
  394. }
  395. if (mostRecent.latest) {
  396. const lastUpdate = new Date(mostRecent.latest);
  397. console.log(` Updated: ${formatTimeAgo(lastUpdate)}`);
  398. }
  399. // Get context counts per collection
  400. const contextCounts = db.prepare(`
  401. SELECT collection_id, COUNT(*) as count
  402. FROM path_contexts
  403. GROUP BY collection_id
  404. `).all() as { collection_id: number; count: number }[];
  405. const contextCountMap = new Map(contextCounts.map(c => [c.collection_id, c.count]));
  406. if (collections.length > 0) {
  407. console.log(`\n${c.bold}Collections${c.reset}`);
  408. for (const col of collections) {
  409. const lastMod = col.last_modified ? formatTimeAgo(new Date(col.last_modified)) : "never";
  410. const contextCount = contextCountMap.get(col.id) || 0;
  411. console.log(` ${c.cyan}${col.name}${c.reset} ${c.dim}(qmd://${col.name}/)${c.reset}`);
  412. console.log(` ${c.dim}Path:${c.reset} ${col.pwd}`);
  413. console.log(` ${c.dim}Pattern:${c.reset} ${col.glob_pattern}`);
  414. console.log(` ${c.dim}Files:${c.reset} ${col.active_count} (updated ${lastMod})`);
  415. if (contextCount > 0) {
  416. console.log(` ${c.dim}Contexts:${c.reset} ${contextCount}`);
  417. }
  418. }
  419. // Show examples of virtual paths
  420. console.log(`\n${c.bold}Examples${c.reset}`);
  421. console.log(` ${c.dim}# List files in a collection${c.reset}`);
  422. if (collections.length > 0) {
  423. console.log(` qmd ls ${collections[0].name}`);
  424. }
  425. console.log(` ${c.dim}# Get a document${c.reset}`);
  426. if (collections.length > 0) {
  427. console.log(` qmd get qmd://${collections[0].name}/path/to/file.md`);
  428. }
  429. console.log(` ${c.dim}# Search within a collection${c.reset}`);
  430. if (collections.length > 0) {
  431. console.log(` qmd search "query" -c ${collections[0].name}`);
  432. }
  433. } else {
  434. console.log(`\n${c.dim}No collections. Run 'qmd collection add .' to index markdown files.${c.reset}`);
  435. }
  436. closeDb();
  437. }
  438. // Update display_paths for all documents that have empty display_path
  439. function updateDisplayPaths(db: Database): number {
  440. // Get all docs with empty display_path, grouped by collection
  441. const emptyDocs = db.prepare(`
  442. SELECT d.id, d.filepath, c.pwd
  443. FROM documents d
  444. JOIN collections c ON d.collection_id = c.id
  445. WHERE d.active = 1 AND (d.display_path IS NULL OR d.display_path = '')
  446. `).all() as { id: number; filepath: string; pwd: string }[];
  447. if (emptyDocs.length === 0) return 0;
  448. // Collect existing display_paths
  449. const existingPaths = new Set<string>(
  450. (db.prepare(`SELECT display_path FROM documents WHERE active = 1 AND display_path != ''`).all() as { display_path: string }[])
  451. .map(r => r.display_path)
  452. );
  453. const updateStmt = db.prepare(`UPDATE documents SET display_path = ? WHERE id = ?`);
  454. let updated = 0;
  455. for (const doc of emptyDocs) {
  456. const displayPath = computeDisplayPath(doc.filepath, doc.pwd, existingPaths);
  457. updateStmt.run(displayPath, doc.id);
  458. existingPaths.add(displayPath);
  459. updated++;
  460. }
  461. return updated;
  462. }
  463. async function updateCollections(): Promise<void> {
  464. const db = getDb();
  465. cleanupDuplicateCollections(db);
  466. // Clear Ollama cache on update
  467. clearCache(db);
  468. const collections = db.prepare(`SELECT id, pwd, glob_pattern FROM collections`).all() as { id: number; pwd: string; glob_pattern: string }[];
  469. if (collections.length === 0) {
  470. console.log(`${c.dim}No collections found. Run 'qmd add .' to index markdown files.${c.reset}`);
  471. closeDb();
  472. return;
  473. }
  474. // Update display_paths for any documents missing them (migration)
  475. const pathsUpdated = updateDisplayPaths(db);
  476. if (pathsUpdated > 0) {
  477. console.log(`${c.green}✓${c.reset} Updated ${pathsUpdated} display paths`);
  478. }
  479. // Don't close db here - indexFiles will reuse it and close at the end
  480. console.log(`${c.bold}Updating ${collections.length} collection(s)...${c.reset}\n`);
  481. for (let i = 0; i < collections.length; i++) {
  482. const col = collections[i];
  483. console.log(`${c.cyan}[${i + 1}/${collections.length}]${c.reset} ${c.bold}${col.pwd}${c.reset}`);
  484. console.log(`${c.dim} Pattern: ${col.glob_pattern}${c.reset}`);
  485. // Temporarily set PWD for indexing
  486. const originalPwd = process.env.PWD;
  487. process.env.PWD = col.pwd;
  488. await indexFiles(col.glob_pattern);
  489. process.env.PWD = originalPwd;
  490. console.log("");
  491. }
  492. console.log(`${c.green}✓ All collections updated.${c.reset}`);
  493. }
  494. /**
  495. * Detect which collection (if any) contains the given filesystem path.
  496. * Returns { collectionId, collectionName, relativePath } or null if not in any collection.
  497. */
  498. function detectCollectionFromPath(db: Database, fsPath: string): { collectionId: number; collectionName: string; relativePath: string } | null {
  499. const realPath = getRealPath(fsPath);
  500. // Find collections that this path is under
  501. const collections = db.prepare(`
  502. SELECT id, name, pwd
  503. FROM collections
  504. WHERE ? LIKE pwd || '/%' OR ? = pwd
  505. ORDER BY LENGTH(pwd) DESC
  506. LIMIT 1
  507. `).get(realPath, realPath) as { id: number; name: string; pwd: string } | null;
  508. if (!collections) return null;
  509. // Calculate relative path
  510. let relativePath = realPath;
  511. if (relativePath.startsWith(collections.pwd + '/')) {
  512. relativePath = relativePath.slice(collections.pwd.length + 1);
  513. } else if (relativePath === collections.pwd) {
  514. relativePath = '';
  515. }
  516. return {
  517. collectionId: collections.id,
  518. collectionName: collections.name,
  519. relativePath
  520. };
  521. }
  522. async function contextAdd(pathArg: string | undefined, contextText: string): Promise<void> {
  523. const db = getDb();
  524. const now = new Date().toISOString();
  525. // Handle "/" as global/root context (applies to all collections)
  526. if (pathArg === '/') {
  527. // Find all collections and add context to each
  528. const collections = db.prepare(`SELECT id, name FROM collections`).all() as { id: number; name: string }[];
  529. for (const coll of collections) {
  530. db.prepare(`
  531. INSERT INTO path_contexts (collection_id, path_prefix, context, created_at)
  532. VALUES (?, '', ?, ?)
  533. ON CONFLICT(collection_id, path_prefix) DO UPDATE SET context = excluded.context
  534. `).run(coll.id, contextText, now);
  535. }
  536. console.log(`${c.green}✓${c.reset} Added global context to ${collections.length} collection(s)`);
  537. console.log(`${c.dim}Context: ${contextText}${c.reset}`);
  538. closeDb();
  539. return;
  540. }
  541. // Resolve path - defaults to current directory if not provided
  542. let fsPath = pathArg || '.';
  543. if (fsPath === '.' || fsPath === './') {
  544. fsPath = getPwd();
  545. } else if (fsPath.startsWith('~/')) {
  546. fsPath = homedir() + fsPath.slice(1);
  547. } else if (!fsPath.startsWith('/') && !fsPath.startsWith('qmd://')) {
  548. fsPath = resolve(getPwd(), fsPath);
  549. }
  550. // Handle virtual paths (qmd://collection/path)
  551. if (isVirtualPath(fsPath)) {
  552. const parsed = parseVirtualPath(fsPath);
  553. if (!parsed) {
  554. console.error(`${c.yellow}Invalid virtual path: ${fsPath}${c.reset}`);
  555. process.exit(1);
  556. }
  557. const coll = getCollectionByName(db, parsed.collectionName);
  558. if (!coll) {
  559. console.error(`${c.yellow}Collection not found: ${parsed.collectionName}${c.reset}`);
  560. process.exit(1);
  561. }
  562. db.prepare(`
  563. INSERT INTO path_contexts (collection_id, path_prefix, context, created_at)
  564. VALUES (?, ?, ?, ?)
  565. ON CONFLICT(collection_id, path_prefix) DO UPDATE SET context = excluded.context
  566. `).run(coll.id, parsed.path, contextText, now);
  567. console.log(`${c.green}✓${c.reset} Added context for: qmd://${parsed.collectionName}/${parsed.path || ''}`);
  568. console.log(`${c.dim}Context: ${contextText}${c.reset}`);
  569. closeDb();
  570. return;
  571. }
  572. // Detect collection from filesystem path
  573. const detected = detectCollectionFromPath(db, fsPath);
  574. if (!detected) {
  575. console.error(`${c.yellow}Path is not in any indexed collection: ${fsPath}${c.reset}`);
  576. console.error(`${c.dim}Run 'qmd status' to see indexed collections${c.reset}`);
  577. process.exit(1);
  578. }
  579. db.prepare(`
  580. INSERT INTO path_contexts (collection_id, path_prefix, context, created_at)
  581. VALUES (?, ?, ?, ?)
  582. ON CONFLICT(collection_id, path_prefix) DO UPDATE SET context = excluded.context
  583. `).run(detected.collectionId, detected.relativePath, contextText, now);
  584. const displayPath = detected.relativePath ? `qmd://${detected.collectionName}/${detected.relativePath}` : `qmd://${detected.collectionName}/`;
  585. console.log(`${c.green}✓${c.reset} Added context for: ${displayPath}`);
  586. console.log(`${c.dim}Context: ${contextText}${c.reset}`);
  587. closeDb();
  588. }
  589. function contextList(): void {
  590. const db = getDb();
  591. const contexts = db.prepare(`
  592. SELECT c.name as collection_name, pc.path_prefix, pc.context
  593. FROM path_contexts pc
  594. JOIN collections c ON c.id = pc.collection_id
  595. ORDER BY c.name, LENGTH(pc.path_prefix) DESC, pc.path_prefix
  596. `).all() as { collection_name: string; path_prefix: string; context: string }[];
  597. if (contexts.length === 0) {
  598. console.log(`${c.dim}No contexts configured. Use 'qmd context add' to add one.${c.reset}`);
  599. closeDb();
  600. return;
  601. }
  602. console.log(`\n${c.bold}Configured Contexts${c.reset}\n`);
  603. let lastCollection = '';
  604. for (const ctx of contexts) {
  605. if (ctx.collection_name !== lastCollection) {
  606. console.log(`${c.cyan}${ctx.collection_name}${c.reset}`);
  607. lastCollection = ctx.collection_name;
  608. }
  609. const path = ctx.path_prefix || '/';
  610. const displayPath = ctx.path_prefix ? ` ${path}` : ' / (root)';
  611. console.log(`${displayPath}`);
  612. console.log(` ${c.dim}${ctx.context}${c.reset}`);
  613. }
  614. closeDb();
  615. }
  616. function contextRemove(pathArg: string): void {
  617. const db = getDb();
  618. if (pathArg === '/') {
  619. // Remove all root contexts
  620. const result = db.prepare(`DELETE FROM path_contexts WHERE path_prefix = ''`).run();
  621. console.log(`${c.green}✓${c.reset} Removed ${result.changes} global context(s)`);
  622. closeDb();
  623. return;
  624. }
  625. // Handle virtual paths
  626. if (isVirtualPath(pathArg)) {
  627. const parsed = parseVirtualPath(pathArg);
  628. if (!parsed) {
  629. console.error(`${c.yellow}Invalid virtual path: ${pathArg}${c.reset}`);
  630. process.exit(1);
  631. }
  632. const coll = getCollectionByName(db, parsed.collectionName);
  633. if (!coll) {
  634. console.error(`${c.yellow}Collection not found: ${parsed.collectionName}${c.reset}`);
  635. process.exit(1);
  636. }
  637. const result = db.prepare(`
  638. DELETE FROM path_contexts
  639. WHERE collection_id = ? AND path_prefix = ?
  640. `).run(coll.id, parsed.path);
  641. if (result.changes === 0) {
  642. console.error(`${c.yellow}No context found for: ${pathArg}${c.reset}`);
  643. process.exit(1);
  644. }
  645. console.log(`${c.green}✓${c.reset} Removed context for: ${pathArg}`);
  646. closeDb();
  647. return;
  648. }
  649. // Handle filesystem paths
  650. let fsPath = pathArg;
  651. if (fsPath === '.' || fsPath === './') {
  652. fsPath = getPwd();
  653. } else if (fsPath.startsWith('~/')) {
  654. fsPath = homedir() + fsPath.slice(1);
  655. } else if (!fsPath.startsWith('/')) {
  656. fsPath = resolve(getPwd(), fsPath);
  657. }
  658. const detected = detectCollectionFromPath(db, fsPath);
  659. if (!detected) {
  660. console.error(`${c.yellow}Path is not in any indexed collection: ${fsPath}${c.reset}`);
  661. process.exit(1);
  662. }
  663. const result = db.prepare(`
  664. DELETE FROM path_contexts
  665. WHERE collection_id = ? AND path_prefix = ?
  666. `).run(detected.collectionId, detected.relativePath);
  667. if (result.changes === 0) {
  668. console.error(`${c.yellow}No context found for: qmd://${detected.collectionName}/${detected.relativePath}${c.reset}`);
  669. process.exit(1);
  670. }
  671. console.log(`${c.green}✓${c.reset} Removed context for: qmd://${detected.collectionName}/${detected.relativePath}`);
  672. closeDb();
  673. }
  674. function getDocument(filename: string, fromLine?: number, maxLines?: number): void {
  675. const db = getDb();
  676. // Parse :linenum suffix from filename (e.g., "file.md:100")
  677. let inputPath = filename;
  678. const colonMatch = inputPath.match(/:(\d+)$/);
  679. if (colonMatch && !fromLine) {
  680. fromLine = parseInt(colonMatch[1], 10);
  681. inputPath = inputPath.slice(0, -colonMatch[0].length);
  682. }
  683. let doc: { collectionId: number; collectionName: string; path: string; body: string } | null = null;
  684. let virtualPath: string;
  685. // Handle virtual paths (qmd://collection/path)
  686. if (isVirtualPath(inputPath)) {
  687. const parsed = parseVirtualPath(inputPath);
  688. if (!parsed) {
  689. console.error(`Invalid virtual path: ${inputPath}`);
  690. closeDb();
  691. process.exit(1);
  692. }
  693. // Try exact match on collection + path
  694. doc = db.prepare(`
  695. SELECT c.id as collectionId, c.name as collectionName, d.path, content.doc as body
  696. FROM documents d
  697. JOIN collections c ON c.id = d.collection_id
  698. JOIN content ON content.hash = d.hash
  699. WHERE c.name = ? AND d.path = ? AND d.active = 1
  700. `).get(parsed.collectionName, parsed.path) as typeof doc;
  701. if (!doc) {
  702. // Try fuzzy match by path ending
  703. doc = db.prepare(`
  704. SELECT c.id as collectionId, c.name as collectionName, d.path, content.doc as body
  705. FROM documents d
  706. JOIN collections c ON c.id = d.collection_id
  707. JOIN content ON content.hash = d.hash
  708. WHERE c.name = ? AND d.path LIKE ? AND d.active = 1
  709. LIMIT 1
  710. `).get(parsed.collectionName, `%${parsed.path}`) as typeof doc;
  711. }
  712. virtualPath = inputPath;
  713. } else {
  714. // Handle filesystem paths
  715. let fsPath = inputPath;
  716. // Expand ~ to home directory
  717. if (fsPath.startsWith('~/')) {
  718. fsPath = homedir() + fsPath.slice(1);
  719. } else if (!fsPath.startsWith('/')) {
  720. // Relative path - resolve from current directory
  721. fsPath = resolve(getPwd(), fsPath);
  722. }
  723. fsPath = getRealPath(fsPath);
  724. // Try to detect which collection contains this path
  725. const detected = detectCollectionFromPath(db, fsPath);
  726. if (detected) {
  727. // Found collection - query by collection_id + relative path
  728. doc = db.prepare(`
  729. SELECT c.id as collectionId, c.name as collectionName, d.path, content.doc as body
  730. FROM documents d
  731. JOIN collections c ON c.id = d.collection_id
  732. JOIN content ON content.hash = d.hash
  733. WHERE c.id = ? AND d.path = ? AND d.active = 1
  734. `).get(detected.collectionId, detected.relativePath) as typeof doc;
  735. }
  736. // Fuzzy match by filename (last component of path)
  737. if (!doc) {
  738. const filename = inputPath.split('/').pop() || inputPath;
  739. doc = db.prepare(`
  740. SELECT c.id as collectionId, c.name as collectionName, d.path, content.doc as body
  741. FROM documents d
  742. JOIN collections c ON c.id = d.collection_id
  743. JOIN content ON content.hash = d.hash
  744. WHERE d.path LIKE ? AND d.active = 1
  745. LIMIT 1
  746. `).get(`%${filename}`) as typeof doc;
  747. }
  748. if (doc) {
  749. virtualPath = buildVirtualPath(doc.collectionName, doc.path);
  750. } else {
  751. virtualPath = inputPath;
  752. }
  753. }
  754. if (!doc) {
  755. console.error(`Document not found: ${filename}`);
  756. closeDb();
  757. process.exit(1);
  758. }
  759. // Get context for this file
  760. const context = getContextForPath(db, doc.collectionId, doc.path);
  761. let output = doc.body;
  762. // Apply line filtering if specified
  763. if (fromLine !== undefined || maxLines !== undefined) {
  764. const lines = output.split('\n');
  765. const start = (fromLine || 1) - 1; // Convert to 0-indexed
  766. const end = maxLines !== undefined ? start + maxLines : lines.length;
  767. output = lines.slice(start, end).join('\n');
  768. }
  769. // Output context header if exists
  770. if (context) {
  771. console.log(`Folder Context: ${context}\n---\n`);
  772. }
  773. console.log(output);
  774. closeDb();
  775. }
  776. // Multi-get: fetch multiple documents by glob pattern or comma-separated list
  777. function multiGet(pattern: string, maxLines?: number, maxBytes: number = DEFAULT_MULTI_GET_MAX_BYTES, format: OutputFormat = "cli"): void {
  778. const db = getDb();
  779. // Check if it's a comma-separated list or a glob pattern
  780. const isCommaSeparated = pattern.includes(',') && !pattern.includes('*') && !pattern.includes('?');
  781. let files: { filepath: string; displayPath: string; bodyLength: number; collectionId?: number; path?: string }[];
  782. if (isCommaSeparated) {
  783. // Comma-separated list of files (can be virtual paths or relative paths)
  784. const names = pattern.split(',').map(s => s.trim()).filter(Boolean);
  785. files = [];
  786. for (const name of names) {
  787. let doc: { virtual_path: string; body_length: number; collection_id: number; path: string } | null = null;
  788. // Handle virtual paths
  789. if (isVirtualPath(name)) {
  790. const parsed = parseVirtualPath(name);
  791. if (parsed) {
  792. // Try exact match on collection + path
  793. doc = db.prepare(`
  794. SELECT
  795. 'qmd://' || c.name || '/' || d.path as virtual_path,
  796. LENGTH(content.doc) as body_length,
  797. d.collection_id,
  798. d.path
  799. FROM documents d
  800. JOIN collections c ON c.id = d.collection_id
  801. JOIN content ON content.hash = d.hash
  802. WHERE c.name = ? AND d.path = ? AND d.active = 1
  803. `).get(parsed.collectionName, parsed.path) as typeof doc;
  804. }
  805. } else {
  806. // Try exact match on path
  807. doc = db.prepare(`
  808. SELECT
  809. 'qmd://' || c.name || '/' || d.path as virtual_path,
  810. LENGTH(content.doc) as body_length,
  811. d.collection_id,
  812. d.path
  813. FROM documents d
  814. JOIN collections c ON c.id = d.collection_id
  815. JOIN content ON content.hash = d.hash
  816. WHERE d.path = ? AND d.active = 1
  817. LIMIT 1
  818. `).get(name) as typeof doc;
  819. // Try suffix match
  820. if (!doc) {
  821. doc = db.prepare(`
  822. SELECT
  823. 'qmd://' || c.name || '/' || d.path as virtual_path,
  824. LENGTH(content.doc) as body_length,
  825. d.collection_id,
  826. d.path
  827. FROM documents d
  828. JOIN collections c ON c.id = d.collection_id
  829. JOIN content ON content.hash = d.hash
  830. WHERE d.path LIKE ? AND d.active = 1
  831. LIMIT 1
  832. `).get(`%${name}`) as typeof doc;
  833. }
  834. }
  835. if (doc) {
  836. files.push({
  837. filepath: doc.virtual_path,
  838. displayPath: doc.virtual_path,
  839. bodyLength: doc.body_length,
  840. collectionId: doc.collection_id,
  841. path: doc.path
  842. });
  843. } else {
  844. console.error(`File not found: ${name}`);
  845. }
  846. }
  847. } else {
  848. // Glob pattern - matchFilesByGlob now returns virtual paths
  849. files = matchFilesByGlob(db, pattern).map(f => ({
  850. ...f,
  851. collectionId: undefined, // Will be fetched later if needed
  852. path: undefined
  853. }));
  854. if (files.length === 0) {
  855. console.error(`No files matched pattern: ${pattern}`);
  856. closeDb();
  857. process.exit(1);
  858. }
  859. }
  860. // Collect results for structured output
  861. const results: { file: string; displayPath: string; title: string; body: string; context: string | null; skipped: boolean; skipReason?: string }[] = [];
  862. for (const file of files) {
  863. // Parse virtual path to get collection info if not already available
  864. let collectionId = file.collectionId;
  865. let path = file.path;
  866. if (!collectionId || !path) {
  867. const parsed = parseVirtualPath(file.displayPath);
  868. if (parsed) {
  869. const coll = getCollectionByName(db, parsed.collectionName);
  870. if (coll) {
  871. collectionId = coll.id;
  872. path = parsed.path;
  873. }
  874. }
  875. }
  876. // Get context using collection-scoped function
  877. const context = collectionId && path ? getContextForPath(db, collectionId, path) : null;
  878. // Check size limit
  879. if (file.bodyLength > maxBytes) {
  880. results.push({
  881. file: file.filepath,
  882. displayPath: file.displayPath,
  883. title: file.displayPath.split('/').pop() || file.displayPath,
  884. body: "",
  885. context,
  886. skipped: true,
  887. skipReason: `File too large (${Math.round(file.bodyLength / 1024)}KB > ${Math.round(maxBytes / 1024)}KB). Use 'qmd get ${file.displayPath}' to retrieve.`,
  888. });
  889. continue;
  890. }
  891. // Fetch document content - use virtual path to query
  892. const parsed = parseVirtualPath(file.displayPath);
  893. if (!parsed) continue;
  894. const doc = db.prepare(`
  895. SELECT content.doc as body, d.title
  896. FROM documents d
  897. JOIN collections c ON c.id = d.collection_id
  898. JOIN content ON content.hash = d.hash
  899. WHERE c.name = ? AND d.path = ? AND d.active = 1
  900. `).get(parsed.collectionName, parsed.path) as { body: string; title: string } | null;
  901. if (!doc) continue;
  902. let body = doc.body;
  903. // Apply line limit if specified
  904. if (maxLines !== undefined) {
  905. const lines = body.split('\n');
  906. body = lines.slice(0, maxLines).join('\n');
  907. if (lines.length > maxLines) {
  908. body += `\n\n[... truncated ${lines.length - maxLines} more lines]`;
  909. }
  910. }
  911. results.push({
  912. file: file.filepath,
  913. displayPath: file.displayPath,
  914. title: doc.title || file.displayPath.split('/').pop() || file.displayPath,
  915. body,
  916. context,
  917. skipped: false,
  918. });
  919. }
  920. closeDb();
  921. // Output based on format
  922. if (format === "json") {
  923. const output = results.map(r => ({
  924. file: r.displayPath,
  925. title: r.title,
  926. ...(r.context && { context: r.context }),
  927. ...(r.skipped ? { skipped: true, reason: r.skipReason } : { body: r.body }),
  928. }));
  929. console.log(JSON.stringify(output, null, 2));
  930. } else if (format === "csv") {
  931. const escapeField = (val: string | null): string => {
  932. if (val === null || val === undefined) return "";
  933. const str = String(val);
  934. if (str.includes(",") || str.includes('"') || str.includes("\n")) {
  935. return `"${str.replace(/"/g, '""')}"`;
  936. }
  937. return str;
  938. };
  939. console.log("file,title,context,skipped,body");
  940. for (const r of results) {
  941. console.log([r.displayPath, r.title, r.context || "", r.skipped ? "true" : "false", r.skipped ? r.skipReason : r.body].map(escapeField).join(","));
  942. }
  943. } else if (format === "files") {
  944. for (const r of results) {
  945. const ctx = r.context ? `,"${r.context.replace(/"/g, '""')}"` : "";
  946. const status = r.skipped ? "[SKIPPED]" : "";
  947. console.log(`${r.displayPath}${ctx}${status ? `,${status}` : ""}`);
  948. }
  949. } else if (format === "md") {
  950. for (const r of results) {
  951. console.log(`## ${r.displayPath}\n`);
  952. if (r.title && r.title !== r.displayPath) console.log(`**Title:** ${r.title}\n`);
  953. if (r.context) console.log(`**Context:** ${r.context}\n`);
  954. if (r.skipped) {
  955. console.log(`> ${r.skipReason}\n`);
  956. } else {
  957. console.log("```");
  958. console.log(r.body);
  959. console.log("```\n");
  960. }
  961. }
  962. } else if (format === "xml") {
  963. console.log('<?xml version="1.0" encoding="UTF-8"?>');
  964. console.log("<documents>");
  965. for (const r of results) {
  966. console.log(" <document>");
  967. console.log(` <file>${escapeXml(r.displayPath)}</file>`);
  968. console.log(` <title>${escapeXml(r.title)}</title>`);
  969. if (r.context) console.log(` <context>${escapeXml(r.context)}</context>`);
  970. if (r.skipped) {
  971. console.log(` <skipped>true</skipped>`);
  972. console.log(` <reason>${escapeXml(r.skipReason || "")}</reason>`);
  973. } else {
  974. console.log(` <body>${escapeXml(r.body)}</body>`);
  975. }
  976. console.log(" </document>");
  977. }
  978. console.log("</documents>");
  979. } else {
  980. // CLI format (default)
  981. for (const r of results) {
  982. console.log(`\n${'='.repeat(60)}`);
  983. console.log(`File: ${r.displayPath}`);
  984. console.log(`${'='.repeat(60)}\n`);
  985. if (r.skipped) {
  986. console.log(`[SKIPPED: ${r.skipReason}]`);
  987. continue;
  988. }
  989. if (r.context) {
  990. console.log(`Folder Context: ${r.context}\n---\n`);
  991. }
  992. console.log(r.body);
  993. }
  994. }
  995. }
  996. // List files in virtual file tree
  997. function listFiles(pathArg?: string): void {
  998. const db = getDb();
  999. if (!pathArg) {
  1000. // No argument - list all collections
  1001. const collections = db.prepare(`
  1002. SELECT name, COUNT(d.id) as file_count
  1003. FROM collections c
  1004. LEFT JOIN documents d ON d.collection_id = c.id AND d.active = 1
  1005. GROUP BY c.id, c.name
  1006. ORDER BY c.name
  1007. `).all() as { name: string; file_count: number }[];
  1008. if (collections.length === 0) {
  1009. console.log("No collections found. Run 'qmd add .' to index files.");
  1010. closeDb();
  1011. return;
  1012. }
  1013. console.log(`${c.bold}Collections:${c.reset}\n`);
  1014. for (const coll of collections) {
  1015. console.log(`${c.cyan}qmd://${coll.name}/${c.reset} (${coll.file_count} files)`);
  1016. }
  1017. closeDb();
  1018. return;
  1019. }
  1020. // Parse the path argument
  1021. let collectionName: string;
  1022. let pathPrefix: string | null = null;
  1023. if (pathArg.startsWith('qmd://')) {
  1024. // Virtual path format: qmd://collection/path
  1025. const parsed = parseVirtualPath(pathArg);
  1026. if (!parsed) {
  1027. console.error(`Invalid virtual path: ${pathArg}`);
  1028. closeDb();
  1029. process.exit(1);
  1030. }
  1031. collectionName = parsed.collectionName;
  1032. pathPrefix = parsed.path;
  1033. } else {
  1034. // Just collection name or collection/path
  1035. const parts = pathArg.split('/');
  1036. collectionName = parts[0];
  1037. if (parts.length > 1) {
  1038. pathPrefix = parts.slice(1).join('/');
  1039. }
  1040. }
  1041. // Get the collection
  1042. const coll = getCollectionByName(db, collectionName);
  1043. if (!coll) {
  1044. console.error(`Collection not found: ${collectionName}`);
  1045. console.error(`Run 'qmd ls' to see available collections.`);
  1046. closeDb();
  1047. process.exit(1);
  1048. }
  1049. // List files in the collection (optionally filtered by path prefix)
  1050. let query: string;
  1051. let params: any[];
  1052. if (pathPrefix) {
  1053. // List files under a specific path
  1054. query = `
  1055. SELECT d.path
  1056. FROM documents d
  1057. WHERE d.collection_id = ? AND d.path LIKE ? AND d.active = 1
  1058. ORDER BY d.path
  1059. `;
  1060. params = [coll.id, `${pathPrefix}%`];
  1061. } else {
  1062. // List all files in the collection
  1063. query = `
  1064. SELECT d.path
  1065. FROM documents d
  1066. WHERE d.collection_id = ? AND d.active = 1
  1067. ORDER BY d.path
  1068. `;
  1069. params = [coll.id];
  1070. }
  1071. const files = db.prepare(query).all(...params) as { path: string }[];
  1072. if (files.length === 0) {
  1073. if (pathPrefix) {
  1074. console.log(`No files found under qmd://${collectionName}/${pathPrefix}`);
  1075. } else {
  1076. console.log(`No files found in collection: ${collectionName}`);
  1077. }
  1078. closeDb();
  1079. return;
  1080. }
  1081. // Output virtual paths
  1082. for (const file of files) {
  1083. console.log(buildVirtualPath(collectionName, file.path));
  1084. }
  1085. closeDb();
  1086. }
  1087. // Collection management commands
  1088. function collectionList(): void {
  1089. const db = getDb();
  1090. const collections = listCollections(db);
  1091. if (collections.length === 0) {
  1092. console.log("No collections found. Run 'qmd add .' to create one.");
  1093. closeDb();
  1094. return;
  1095. }
  1096. console.log(`${c.bold}Collections (${collections.length}):${c.reset}\n`);
  1097. for (const coll of collections) {
  1098. const updatedAt = new Date(coll.updated_at);
  1099. const timeAgo = formatTimeAgo(updatedAt);
  1100. console.log(`${c.cyan}${coll.name}${c.reset}`);
  1101. console.log(` ${c.dim}Path:${c.reset} ${coll.pwd}`);
  1102. console.log(` ${c.dim}Pattern:${c.reset} ${coll.glob_pattern}`);
  1103. console.log(` ${c.dim}Files:${c.reset} ${coll.active_count}`);
  1104. console.log(` ${c.dim}Updated:${c.reset} ${timeAgo}`);
  1105. console.log();
  1106. }
  1107. closeDb();
  1108. }
  1109. async function collectionAdd(pwd: string, globPattern: string, name?: string): Promise<void> {
  1110. const db = getDb();
  1111. // If name not provided, generate from pwd basename
  1112. if (!name) {
  1113. const parts = pwd.split('/').filter(Boolean);
  1114. name = parts[parts.length - 1] || 'root';
  1115. }
  1116. // Check if collection with this name already exists
  1117. const existing = getCollectionByName(db, name);
  1118. if (existing) {
  1119. console.error(`${c.yellow}Collection '${name}' already exists.${c.reset}`);
  1120. console.error(`Use a different name with --name <name>`);
  1121. closeDb();
  1122. process.exit(1);
  1123. }
  1124. // Check if a collection with this pwd+glob already exists
  1125. const existingPwdGlob = db.prepare(`
  1126. SELECT id, name FROM collections WHERE pwd = ? AND glob_pattern = ?
  1127. `).get(pwd, globPattern) as { id: number; name: string } | null;
  1128. if (existingPwdGlob) {
  1129. console.error(`${c.yellow}A collection already exists for this path and pattern:${c.reset}`);
  1130. console.error(` Name: ${existingPwdGlob.name}`);
  1131. console.error(` Path: ${pwd}`);
  1132. console.error(` Pattern: ${globPattern}`);
  1133. console.error(`\nUse 'qmd add ${globPattern}' to update it, or remove it first with 'qmd collection remove ${existingPwdGlob.name}'`);
  1134. closeDb();
  1135. process.exit(1);
  1136. }
  1137. closeDb();
  1138. // Create the collection and index files
  1139. console.log(`Creating collection '${name}'...`);
  1140. await indexFiles(pwd, globPattern, name);
  1141. console.log(`${c.green}✓${c.reset} Collection '${name}' created successfully`);
  1142. }
  1143. function collectionRemove(name: string): void {
  1144. const db = getDb();
  1145. const coll = getCollectionByName(db, name);
  1146. if (!coll) {
  1147. console.error(`${c.yellow}Collection not found: ${name}${c.reset}`);
  1148. console.error(`Run 'qmd collection list' to see available collections.`);
  1149. closeDb();
  1150. process.exit(1);
  1151. }
  1152. const result = removeCollection(db, coll.id);
  1153. console.log(`${c.green}✓${c.reset} Removed collection '${name}'`);
  1154. console.log(` Deleted ${result.deletedDocs} documents`);
  1155. if (result.cleanedHashes > 0) {
  1156. console.log(` Cleaned up ${result.cleanedHashes} orphaned content hashes`);
  1157. }
  1158. closeDb();
  1159. }
  1160. function collectionRename(oldName: string, newName: string): void {
  1161. const db = getDb();
  1162. // Check if old collection exists
  1163. const coll = getCollectionByName(db, oldName);
  1164. if (!coll) {
  1165. console.error(`${c.yellow}Collection not found: ${oldName}${c.reset}`);
  1166. console.error(`Run 'qmd collection list' to see available collections.`);
  1167. closeDb();
  1168. process.exit(1);
  1169. }
  1170. // Check if new name already exists
  1171. const existing = getCollectionByName(db, newName);
  1172. if (existing) {
  1173. console.error(`${c.yellow}Collection name already exists: ${newName}${c.reset}`);
  1174. console.error(`Choose a different name or remove the existing collection first.`);
  1175. closeDb();
  1176. process.exit(1);
  1177. }
  1178. renameCollection(db, coll.id, newName);
  1179. console.log(`${c.green}✓${c.reset} Renamed collection '${oldName}' to '${newName}'`);
  1180. console.log(` Virtual paths updated: ${c.cyan}qmd://${oldName}/${c.reset} → ${c.cyan}qmd://${newName}/${c.reset}`);
  1181. closeDb();
  1182. }
  1183. async function dropCollection(globPattern: string): Promise<void> {
  1184. const db = getDb();
  1185. const pwd = getPwd();
  1186. const collection = db.prepare(`SELECT id FROM collections WHERE pwd = ? AND glob_pattern = ?`).get(pwd, globPattern) as { id: number } | null;
  1187. if (!collection) {
  1188. // No collection to drop - this is fine, we'll create one during indexing
  1189. return;
  1190. }
  1191. // Delete documents in this collection
  1192. const deleted = db.prepare(`DELETE FROM documents WHERE collection_id = ?`).run(collection.id);
  1193. // Delete the collection
  1194. db.prepare(`DELETE FROM collections WHERE id = ?`).run(collection.id);
  1195. console.log(`Dropped collection: ${pwd} (${globPattern})`);
  1196. console.log(`Removed ${deleted.changes} documents`);
  1197. console.log(`(Vectors kept for potential reuse)`);
  1198. // Don't close db - indexFiles will use it and close at the end
  1199. }
  1200. async function indexFiles(pwd?: string, globPattern: string = DEFAULT_GLOB, name?: string): Promise<void> {
  1201. const db = getDb();
  1202. const resolvedPwd = pwd || getPwd();
  1203. const now = new Date().toISOString();
  1204. const excludeDirs = ["node_modules", ".git", ".cache", "vendor", "dist", "build"];
  1205. // Clear Ollama cache on index
  1206. clearCache(db);
  1207. // Get or create collection for this (pwd, glob)
  1208. const collectionId = getOrCreateCollection(db, resolvedPwd, globPattern, name);
  1209. console.log(`Collection: ${resolvedPwd} (${globPattern})`);
  1210. progress.indeterminate();
  1211. const glob = new Glob(globPattern);
  1212. const files: string[] = [];
  1213. for await (const file of glob.scan({ cwd: resolvedPwd, onlyFiles: true, followSymlinks: true })) {
  1214. // Skip node_modules, hidden folders (.*), and other common excludes
  1215. const parts = file.split("/");
  1216. const shouldSkip = parts.some(part =>
  1217. part === "node_modules" ||
  1218. part.startsWith(".") ||
  1219. excludeDirs.includes(part)
  1220. );
  1221. if (!shouldSkip) {
  1222. files.push(file);
  1223. }
  1224. }
  1225. const total = files.length;
  1226. if (total === 0) {
  1227. progress.clear();
  1228. console.log("No files found matching pattern.");
  1229. closeDb();
  1230. return;
  1231. }
  1232. // Prepared statements for new schema
  1233. const insertContentStmt = db.prepare(`INSERT OR IGNORE INTO content (hash, doc, created_at) VALUES (?, ?, ?)`);
  1234. const insertDocStmt = db.prepare(`INSERT INTO documents (collection_id, path, title, hash, created_at, modified_at, active) VALUES (?, ?, ?, ?, ?, ?, 1)`);
  1235. const deactivateStmt = db.prepare(`UPDATE documents SET active = 0 WHERE collection_id = ? AND path = ? AND active = 1`);
  1236. const findActiveStmt = db.prepare(`SELECT id, hash, title FROM documents WHERE collection_id = ? AND path = ? AND active = 1`);
  1237. const updateTitleStmt = db.prepare(`UPDATE documents SET title = ?, modified_at = ? WHERE id = ?`);
  1238. let indexed = 0, updated = 0, unchanged = 0, processed = 0;
  1239. const seenPaths = new Set<string>();
  1240. const startTime = Date.now();
  1241. for (const relativeFile of files) {
  1242. const filepath = getRealPath(resolve(resolvedPwd, relativeFile));
  1243. const path = relativeFile; // Use relative path as-is
  1244. seenPaths.add(path);
  1245. const content = await Bun.file(filepath).text();
  1246. const hash = await hashContent(content);
  1247. const title = extractTitle(content, relativeFile);
  1248. // Check if document exists in this collection with this path
  1249. const existing = findActiveStmt.get(collectionId, path) as { id: number; hash: string; title: string } | null;
  1250. if (existing) {
  1251. if (existing.hash === hash) {
  1252. // Hash unchanged, but check if title needs updating
  1253. if (existing.title !== title) {
  1254. updateTitleStmt.run(title, now, existing.id);
  1255. updated++;
  1256. } else {
  1257. unchanged++;
  1258. }
  1259. } else {
  1260. // Content changed - insert new content hash and update document
  1261. insertContentStmt.run(hash, content, now);
  1262. deactivateStmt.run(collectionId, path);
  1263. updated++;
  1264. const stat = await Bun.file(filepath).stat();
  1265. insertDocStmt.run(collectionId, path, title, hash,
  1266. stat ? new Date(stat.birthtime).toISOString() : now,
  1267. stat ? new Date(stat.mtime).toISOString() : now);
  1268. }
  1269. } else {
  1270. // New document - insert content and document
  1271. indexed++;
  1272. insertContentStmt.run(hash, content, now);
  1273. const stat = await Bun.file(filepath).stat();
  1274. insertDocStmt.run(collectionId, path, title, hash,
  1275. stat ? new Date(stat.birthtime).toISOString() : now,
  1276. stat ? new Date(stat.mtime).toISOString() : now);
  1277. }
  1278. processed++;
  1279. progress.set((processed / total) * 100);
  1280. const elapsed = (Date.now() - startTime) / 1000;
  1281. const rate = processed / elapsed;
  1282. const remaining = (total - processed) / rate;
  1283. const eta = processed > 2 ? ` ETA: ${formatETA(remaining)}` : "";
  1284. process.stderr.write(`\rIndexing: ${processed}/${total}${eta} `);
  1285. }
  1286. // Deactivate documents in this collection that no longer exist
  1287. const allActive = db.prepare(`SELECT path FROM documents WHERE collection_id = ? AND active = 1`).all(collectionId) as { path: string }[];
  1288. let removed = 0;
  1289. for (const row of allActive) {
  1290. if (!seenPaths.has(row.path)) {
  1291. deactivateStmt.run(collectionId, row.path);
  1292. removed++;
  1293. }
  1294. }
  1295. // Clean up orphaned content hashes (content not referenced by any document)
  1296. const cleanupResult = db.prepare(`
  1297. DELETE FROM content
  1298. WHERE hash NOT IN (SELECT DISTINCT hash FROM documents WHERE active = 1)
  1299. `).run();
  1300. const orphanedContent = cleanupResult.changes;
  1301. // Check if vector index needs updating
  1302. const needsEmbedding = getHashesNeedingEmbedding(db);
  1303. progress.clear();
  1304. console.log(`\nIndexed: ${indexed} new, ${updated} updated, ${unchanged} unchanged, ${removed} removed`);
  1305. if (orphanedContent > 0) {
  1306. console.log(`Cleaned up ${orphanedContent} orphaned content hash(es)`);
  1307. }
  1308. if (needsEmbedding > 0) {
  1309. console.log(`\nRun 'qmd embed' to update embeddings (${needsEmbedding} unique hashes need vectors)`);
  1310. }
  1311. closeDb();
  1312. }
  1313. function renderProgressBar(percent: number, width: number = 30): string {
  1314. const filled = Math.round((percent / 100) * width);
  1315. const empty = width - filled;
  1316. const bar = "█".repeat(filled) + "░".repeat(empty);
  1317. return bar;
  1318. }
  1319. async function vectorIndex(model: string = DEFAULT_EMBED_MODEL, force: boolean = false): Promise<void> {
  1320. const db = getDb();
  1321. const now = new Date().toISOString();
  1322. // If force, clear all vectors
  1323. if (force) {
  1324. console.log(`${c.yellow}Force re-indexing: clearing all vectors...${c.reset}`);
  1325. db.exec(`DELETE FROM content_vectors`);
  1326. db.exec(`DROP TABLE IF EXISTS vectors_vec`);
  1327. }
  1328. // Find unique hashes that need embedding (from active documents)
  1329. // Join with content table to get document body
  1330. const hashesToEmbed = db.prepare(`
  1331. SELECT d.hash, c.doc as body, MIN(d.path) as path
  1332. FROM documents d
  1333. JOIN content c ON d.hash = c.hash
  1334. LEFT JOIN content_vectors v ON d.hash = v.hash AND v.seq = 0
  1335. WHERE d.active = 1 AND v.hash IS NULL
  1336. GROUP BY d.hash
  1337. `).all() as { hash: string; body: string; path: string }[];
  1338. if (hashesToEmbed.length === 0) {
  1339. console.log(`${c.green}✓ All content hashes already have embeddings.${c.reset}`);
  1340. closeDb();
  1341. return;
  1342. }
  1343. // Prepare documents with chunks
  1344. type ChunkItem = { hash: string; title: string; text: string; seq: number; pos: number; bytes: number; displayName: string };
  1345. const allChunks: ChunkItem[] = [];
  1346. let multiChunkDocs = 0;
  1347. for (const item of hashesToEmbed) {
  1348. const encoder = new TextEncoder();
  1349. const bodyBytes = encoder.encode(item.body).length;
  1350. if (bodyBytes === 0) continue; // Skip empty
  1351. const title = extractTitle(item.body, item.path);
  1352. const displayName = item.path;
  1353. const chunks = chunkDocument(item.body, CHUNK_BYTE_SIZE);
  1354. if (chunks.length > 1) multiChunkDocs++;
  1355. for (let seq = 0; seq < chunks.length; seq++) {
  1356. allChunks.push({
  1357. hash: item.hash,
  1358. title,
  1359. text: chunks[seq].text,
  1360. seq,
  1361. pos: chunks[seq].pos,
  1362. bytes: encoder.encode(chunks[seq].text).length,
  1363. displayName,
  1364. });
  1365. }
  1366. }
  1367. if (allChunks.length === 0) {
  1368. console.log(`${c.green}✓ No non-empty documents to embed.${c.reset}`);
  1369. closeDb();
  1370. return;
  1371. }
  1372. const totalBytes = allChunks.reduce((sum, c) => sum + c.bytes, 0);
  1373. const totalChunks = allChunks.length;
  1374. const totalDocs = hashesToEmbed.length;
  1375. console.log(`${c.bold}Embedding ${totalDocs} documents${c.reset} ${c.dim}(${totalChunks} chunks, ${formatBytes(totalBytes)})${c.reset}`);
  1376. if (multiChunkDocs > 0) {
  1377. console.log(`${c.dim}${multiChunkDocs} documents split into multiple chunks${c.reset}`);
  1378. }
  1379. console.log(`${c.dim}Model: ${model}${c.reset}\n`);
  1380. // Hide cursor during embedding
  1381. cursor.hide();
  1382. // Get embedding dimensions from first chunk
  1383. progress.indeterminate();
  1384. const firstEmbedding = await getEmbedding(allChunks[0].text, model, false, allChunks[0].title);
  1385. ensureVecTable(db, firstEmbedding.length);
  1386. const insertVecStmt = db.prepare(`INSERT OR REPLACE INTO vectors_vec (hash_seq, embedding) VALUES (?, ?)`);
  1387. const insertContentVectorStmt = db.prepare(`INSERT OR REPLACE INTO content_vectors (hash, seq, pos, model, embedded_at) VALUES (?, ?, ?, ?, ?)`);
  1388. let chunksEmbedded = 0, errors = 0, bytesProcessed = 0;
  1389. const startTime = Date.now();
  1390. // Insert first chunk
  1391. const firstHashSeq = `${allChunks[0].hash}_${allChunks[0].seq}`;
  1392. insertVecStmt.run(firstHashSeq, new Float32Array(firstEmbedding));
  1393. insertContentVectorStmt.run(allChunks[0].hash, allChunks[0].seq, allChunks[0].pos, model, now);
  1394. chunksEmbedded++;
  1395. bytesProcessed += allChunks[0].bytes;
  1396. for (let i = 1; i < allChunks.length; i++) {
  1397. const chunk = allChunks[i];
  1398. try {
  1399. const embedding = await getEmbedding(chunk.text, model, false, chunk.title);
  1400. const hashSeq = `${chunk.hash}_${chunk.seq}`;
  1401. insertVecStmt.run(hashSeq, new Float32Array(embedding));
  1402. insertContentVectorStmt.run(chunk.hash, chunk.seq, chunk.pos, model, now);
  1403. chunksEmbedded++;
  1404. bytesProcessed += chunk.bytes;
  1405. } catch (err) {
  1406. errors++;
  1407. bytesProcessed += chunk.bytes;
  1408. progress.error();
  1409. console.error(`\n${c.yellow}⚠ Error embedding "${chunk.displayName}" chunk ${chunk.seq}: ${err}${c.reset}`);
  1410. }
  1411. const percent = (bytesProcessed / totalBytes) * 100;
  1412. progress.set(percent);
  1413. const elapsed = (Date.now() - startTime) / 1000;
  1414. const bytesPerSec = bytesProcessed / elapsed;
  1415. const remainingBytes = totalBytes - bytesProcessed;
  1416. const etaSec = remainingBytes / bytesPerSec;
  1417. const bar = renderProgressBar(percent);
  1418. const percentStr = percent.toFixed(0).padStart(3);
  1419. const throughput = `${formatBytes(bytesPerSec)}/s`;
  1420. const eta = elapsed > 2 ? formatETA(etaSec) : "...";
  1421. const errStr = errors > 0 ? ` ${c.yellow}${errors} err${c.reset}` : "";
  1422. process.stderr.write(`\r${c.cyan}${bar}${c.reset} ${c.bold}${percentStr}%${c.reset} ${c.dim}${chunksEmbedded}/${totalChunks}${c.reset}${errStr} ${c.dim}${throughput} ETA ${eta}${c.reset} `);
  1423. }
  1424. progress.clear();
  1425. cursor.show();
  1426. const totalTimeSec = (Date.now() - startTime) / 1000;
  1427. const avgThroughput = formatBytes(totalBytes / totalTimeSec);
  1428. console.log(`\r${c.green}${renderProgressBar(100)}${c.reset} ${c.bold}100%${c.reset} `);
  1429. console.log(`\n${c.green}✓ Done!${c.reset} Embedded ${c.bold}${chunksEmbedded}${c.reset} chunks from ${c.bold}${totalDocs}${c.reset} documents in ${c.bold}${formatETA(totalTimeSec)}${c.reset} ${c.dim}(${avgThroughput}/s)${c.reset}`);
  1430. if (errors > 0) {
  1431. console.log(`${c.yellow}⚠ ${errors} chunks failed${c.reset}`);
  1432. }
  1433. closeDb();
  1434. }
  1435. // Sanitize a term for FTS5: remove punctuation except apostrophes
  1436. function sanitizeFTS5Term(term: string): string {
  1437. // Remove all non-alphanumeric except apostrophes (for contractions like "don't")
  1438. return term.replace(/[^\w']/g, '').trim();
  1439. }
  1440. // Build FTS5 query: phrase-aware with fallback to individual terms
  1441. function buildFTS5Query(query: string): string {
  1442. // Sanitize the full query for phrase matching
  1443. const sanitizedQuery = query.replace(/[^\w\s']/g, '').trim();
  1444. const terms = query
  1445. .split(/\s+/)
  1446. .map(sanitizeFTS5Term)
  1447. .filter(term => term.length >= 2); // Skip single chars and empty
  1448. if (terms.length === 0) return "";
  1449. if (terms.length === 1) return `"${terms[0].replace(/"/g, '""')}"`;
  1450. // Strategy: exact phrase OR proximity match OR individual terms
  1451. // Exact phrase matches rank highest, then close proximity, then any term
  1452. const phrase = `"${sanitizedQuery.replace(/"/g, '""')}"`;
  1453. const quotedTerms = terms.map(t => `"${t.replace(/"/g, '""')}"`);
  1454. // FTS5 NEAR syntax: NEAR(term1 term2, distance)
  1455. const nearPhrase = `NEAR(${quotedTerms.join(' ')}, 10)`;
  1456. const orTerms = quotedTerms.join(' OR ');
  1457. // Exact phrase > proximity > any term
  1458. return `(${phrase}) OR (${nearPhrase}) OR (${orTerms})`;
  1459. }
  1460. // Normalize BM25 score to 0-1 range using sigmoid
  1461. function normalizeBM25(score: number): number {
  1462. // BM25 scores are negative in SQLite (lower = better)
  1463. // Typical range: -15 (excellent) to -2 (weak match)
  1464. // Map to 0-1 where higher is better
  1465. const absScore = Math.abs(score);
  1466. // Sigmoid-ish normalization: maps ~2-15 range to ~0.1-0.95
  1467. return 1 / (1 + Math.exp(-(absScore - 5) / 3));
  1468. }
  1469. // Get collection ID by name (matches pwd or glob_pattern suffix)
  1470. function getCollectionIdByName(db: Database, name: string): number | null {
  1471. // Search both pwd and glob_pattern columns for the name
  1472. const result = db.prepare(`
  1473. SELECT id FROM collections
  1474. WHERE pwd LIKE ? OR glob_pattern LIKE ?
  1475. ORDER BY LENGTH(pwd) DESC
  1476. LIMIT 1
  1477. `).get(`%${name}%`, `%${name}%`) as { id: number } | null;
  1478. return result?.id || null;
  1479. }
  1480. // searchFTS and searchVec are now imported from store.ts with updated schema
  1481. // Removed duplicate searchFTS and searchVec functions - using store.ts versions instead
  1482. async function REMOVED_searchVec(db: Database, query: string, model: string, limit: number = 20, collectionId?: number): Promise<SearchResult[]> {
  1483. const tableExists = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
  1484. if (!tableExists) return [];
  1485. const queryEmbedding = await getEmbedding(query, model, true);
  1486. const queryVec = new Float32Array(queryEmbedding);
  1487. // Join: vectors_vec -> content_vectors -> documents
  1488. // Over-retrieve to handle multiple chunks per document, then dedupe
  1489. let sql = `
  1490. SELECT d.filepath, d.display_path, d.title, d.body, vec.distance, cv.pos
  1491. FROM vectors_vec vec
  1492. JOIN content_vectors cv ON vec.hash_seq = cv.hash || '_' || cv.seq
  1493. JOIN documents d ON d.hash = cv.hash AND d.active = 1
  1494. WHERE vec.embedding MATCH ? AND k = ?
  1495. `;
  1496. if (collectionId !== undefined) {
  1497. sql += ` AND d.collection_id = ${collectionId}`;
  1498. }
  1499. sql += ` ORDER BY vec.distance`;
  1500. const stmt = db.prepare(sql);
  1501. const rawResults = stmt.all(queryVec, limit * 3) as { filepath: string; display_path: string; title: string; body: string; distance: number; pos: number }[];
  1502. // Aggregate chunks per document: max score + small bonus for additional matches
  1503. const byFile = new Map<string, { filepath: string; displayPath: string; title: string; body: string; chunkCount: number; bestPos: number; bestDist: number }>();
  1504. for (const r of rawResults) {
  1505. const existing = byFile.get(r.filepath);
  1506. if (!existing) {
  1507. byFile.set(r.filepath, { filepath: r.filepath, displayPath: r.display_path, title: r.title, body: r.body, chunkCount: 1, bestPos: r.pos, bestDist: r.distance });
  1508. } else {
  1509. existing.chunkCount++;
  1510. if (r.distance < existing.bestDist) {
  1511. existing.bestDist = r.distance;
  1512. existing.bestPos = r.pos;
  1513. }
  1514. }
  1515. }
  1516. // Score = max chunk score + 0.02 bonus per additional chunk (capped at +0.1)
  1517. return Array.from(byFile.values())
  1518. .map(r => {
  1519. const maxScore = 1 / (1 + r.bestDist);
  1520. const bonusChunks = Math.min(r.chunkCount - 1, 5);
  1521. const bonus = bonusChunks * 0.02;
  1522. return {
  1523. file: r.filepath,
  1524. displayPath: r.displayPath,
  1525. title: r.title,
  1526. body: r.body,
  1527. score: maxScore + bonus,
  1528. source: "vec" as const,
  1529. chunkPos: r.bestPos,
  1530. };
  1531. })
  1532. .sort((a, b) => b.score - a.score)
  1533. .slice(0, limit);
  1534. }
  1535. function normalizeScores(results: SearchResult[]): SearchResult[] {
  1536. if (results.length === 0) return results;
  1537. const maxScore = Math.max(...results.map(r => r.score));
  1538. const minScore = Math.min(...results.map(r => r.score));
  1539. const range = maxScore - minScore || 1;
  1540. return results.map(r => ({ ...r, score: (r.score - minScore) / range }));
  1541. }
  1542. // Reciprocal Rank Fusion: combines multiple ranked lists
  1543. // RRF score = sum(1 / (k + rank)) across all lists where doc appears
  1544. // k=60 is standard, provides good balance between top and lower ranks
  1545. export type RankedResult = { file: string; displayPath: string; title: string; body: string; score: number };
  1546. function reciprocalRankFusion(
  1547. resultLists: RankedResult[][],
  1548. weights: number[] = [], // Weight per result list (default 1.0)
  1549. k: number = 60
  1550. ): RankedResult[] {
  1551. const scores = new Map<string, { score: number; displayPath: string; title: string; body: string; bestRank: number }>();
  1552. for (let listIdx = 0; listIdx < resultLists.length; listIdx++) {
  1553. const results = resultLists[listIdx];
  1554. const weight = weights[listIdx] ?? 1.0;
  1555. for (let rank = 0; rank < results.length; rank++) {
  1556. const doc = results[rank];
  1557. const rrfScore = weight / (k + rank + 1);
  1558. const existing = scores.get(doc.file);
  1559. if (existing) {
  1560. existing.score += rrfScore;
  1561. existing.bestRank = Math.min(existing.bestRank, rank);
  1562. } else {
  1563. scores.set(doc.file, { score: rrfScore, displayPath: doc.displayPath, title: doc.title, body: doc.body, bestRank: rank });
  1564. }
  1565. }
  1566. }
  1567. // Add bonus for best rank: documents that ranked #1-3 in any list get a boost
  1568. // This prevents dilution of exact matches by expansion queries
  1569. return Array.from(scores.entries())
  1570. .map(([file, { score, displayPath, title, body, bestRank }]) => {
  1571. let bonus = 0;
  1572. if (bestRank === 0) bonus = 0.05; // Ranked #1 somewhere
  1573. else if (bestRank <= 2) bonus = 0.02; // Ranked top-3 somewhere
  1574. return { file, displayPath, title, body, score: score + bonus };
  1575. })
  1576. .sort((a, b) => b.score - a.score);
  1577. }
  1578. type OutputOptions = {
  1579. format: OutputFormat;
  1580. full: boolean;
  1581. limit: number;
  1582. minScore: number;
  1583. all?: boolean;
  1584. collection?: string; // Filter by collection name (pwd suffix match)
  1585. };
  1586. // Extract snippet with more context lines for CLI display
  1587. function extractSnippetWithContext(body: string, query: string, contextLines = 3, chunkPos?: number): { line: number; snippet: string; hasMatch: boolean } {
  1588. // If chunkPos provided, focus search on that area
  1589. let lineOffset = 0;
  1590. let searchBody = body;
  1591. if (chunkPos && chunkPos > 0) {
  1592. const contextStart = Math.max(0, chunkPos - 200);
  1593. searchBody = body.slice(contextStart);
  1594. if (contextStart > 0) {
  1595. lineOffset = body.slice(0, contextStart).split('\n').length - 1;
  1596. }
  1597. }
  1598. const lines = searchBody.split('\n');
  1599. const queryTerms = query.toLowerCase().split(/\s+/).filter(t => t.length > 0);
  1600. let bestLine = 0, bestScore = -1;
  1601. for (let i = 0; i < lines.length; i++) {
  1602. const lineLower = lines[i].toLowerCase();
  1603. let score = 0;
  1604. for (const term of queryTerms) {
  1605. if (lineLower.includes(term)) score++;
  1606. }
  1607. if (score > bestScore) {
  1608. bestScore = score;
  1609. bestLine = i;
  1610. }
  1611. }
  1612. // No query match found - return beginning of chunk area or file
  1613. if (bestScore <= 0) {
  1614. const preview = lines.slice(0, contextLines * 2).join('\n').trim();
  1615. return { line: lineOffset + 1, snippet: preview, hasMatch: false };
  1616. }
  1617. const startLine = Math.max(0, bestLine - contextLines);
  1618. const endLine = Math.min(lines.length, bestLine + contextLines + 1);
  1619. const snippet = lines.slice(startLine, endLine).join('\n').trim();
  1620. return { line: lineOffset + bestLine + 1, snippet, hasMatch: true };
  1621. }
  1622. // Highlight query terms in text (skip short words < 3 chars)
  1623. function highlightTerms(text: string, query: string): string {
  1624. if (!useColor) return text;
  1625. const terms = query.toLowerCase().split(/\s+/).filter(t => t.length >= 3);
  1626. let result = text;
  1627. for (const term of terms) {
  1628. const regex = new RegExp(`(${term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
  1629. result = result.replace(regex, `${c.yellow}${c.bold}$1${c.reset}`);
  1630. }
  1631. return result;
  1632. }
  1633. // Format score with color based on value
  1634. function formatScore(score: number): string {
  1635. const pct = (score * 100).toFixed(0).padStart(3);
  1636. if (!useColor) return `${pct}%`;
  1637. if (score >= 0.7) return `${c.green}${pct}%${c.reset}`;
  1638. if (score >= 0.4) return `${c.yellow}${pct}%${c.reset}`;
  1639. return `${c.dim}${pct}%${c.reset}`;
  1640. }
  1641. // Shorten directory path for display - relative to $HOME (used for context paths, not documents)
  1642. function shortPath(dirpath: string): string {
  1643. const home = homedir();
  1644. if (dirpath.startsWith(home)) {
  1645. return '~' + dirpath.slice(home.length);
  1646. }
  1647. return dirpath;
  1648. }
  1649. function outputResults(results: { file: string; displayPath: string; title: string; body: string; score: number; context?: string | null; chunkPos?: number }[], query: string, opts: OutputOptions): void {
  1650. const filtered = results.filter(r => r.score >= opts.minScore).slice(0, opts.limit);
  1651. if (filtered.length === 0) {
  1652. console.log("No results found above minimum score threshold.");
  1653. return;
  1654. }
  1655. if (opts.format === "json") {
  1656. // JSON output for LLM consumption
  1657. const output = filtered.map(row => ({
  1658. score: Math.round(row.score * 100) / 100,
  1659. file: row.displayPath,
  1660. title: row.title,
  1661. ...(row.context && { context: row.context }),
  1662. ...(opts.full && { body: row.body }),
  1663. ...(!opts.full && { snippet: extractSnippet(row.body, query, 300, row.chunkPos).snippet }),
  1664. }));
  1665. console.log(JSON.stringify(output, null, 2));
  1666. } else if (opts.format === "files") {
  1667. // Simple score,filepath,context output
  1668. for (const row of filtered) {
  1669. const ctx = row.context ? `,"${row.context.replace(/"/g, '""')}"` : "";
  1670. console.log(`${row.score.toFixed(2)},${row.displayPath}${ctx}`);
  1671. }
  1672. } else if (opts.format === "cli") {
  1673. for (let i = 0; i < filtered.length; i++) {
  1674. const row = filtered[i];
  1675. const { line, snippet, hasMatch } = extractSnippetWithContext(row.body, query, 2, row.chunkPos);
  1676. // Line 1: filepath
  1677. const path = row.displayPath;
  1678. const lineInfo = hasMatch ? `:${line}` : "";
  1679. console.log(`${c.cyan}${path}${c.dim}${lineInfo}${c.reset}`);
  1680. // Line 2: Title (if available)
  1681. if (row.title) {
  1682. console.log(`${c.bold}Title: ${row.title}${c.reset}`);
  1683. }
  1684. // Line 3: Context (if available)
  1685. if (row.context) {
  1686. console.log(`${c.dim}Context: ${row.context}${c.reset}`);
  1687. }
  1688. // Line 4: Score
  1689. const score = formatScore(row.score);
  1690. console.log(`Score: ${c.bold}${score}${c.reset}`);
  1691. console.log();
  1692. // Snippet with highlighting (no leading | chars for better word wrap)
  1693. const highlighted = highlightTerms(snippet, query);
  1694. console.log(highlighted);
  1695. // Double empty line between results
  1696. if (i < filtered.length - 1) console.log('\n');
  1697. }
  1698. } else if (opts.format === "md") {
  1699. for (const row of filtered) {
  1700. const heading = row.title || row.displayPath;
  1701. if (opts.full) {
  1702. console.log(`---\n# ${heading}\n\n${row.body}\n`);
  1703. } else {
  1704. const { snippet } = extractSnippet(row.body, query, 500, row.chunkPos);
  1705. console.log(`---\n# ${heading}\n\n${snippet}\n`);
  1706. }
  1707. }
  1708. } else if (opts.format === "xml") {
  1709. for (const row of filtered) {
  1710. const titleAttr = row.title ? ` title="${row.title.replace(/"/g, '&quot;')}"` : "";
  1711. if (opts.full) {
  1712. console.log(`<file name="${row.displayPath}"${titleAttr}>\n${row.body}\n</file>\n`);
  1713. } else {
  1714. const { snippet } = extractSnippet(row.body, query, 500, row.chunkPos);
  1715. console.log(`<file name="${row.displayPath}"${titleAttr}>\n${snippet}\n</file>\n`);
  1716. }
  1717. }
  1718. } else {
  1719. // CSV format
  1720. console.log("score,file,title,line,snippet");
  1721. for (const row of filtered) {
  1722. const { line, snippet } = extractSnippet(row.body, query, 500, row.chunkPos);
  1723. const content = opts.full ? row.body : snippet;
  1724. console.log(`${row.score.toFixed(4)},${escapeCSV(row.displayPath)},${escapeCSV(row.title)},${line},${escapeCSV(content)}`);
  1725. }
  1726. }
  1727. }
  1728. function search(query: string, opts: OutputOptions): void {
  1729. const db = getDb();
  1730. // Resolve collection filter if specified
  1731. let collectionId: number | undefined;
  1732. if (opts.collection) {
  1733. collectionId = getCollectionIdByName(db, opts.collection) ?? undefined;
  1734. if (collectionId === undefined) {
  1735. console.error(`Collection not found: ${opts.collection}`);
  1736. closeDb();
  1737. process.exit(1);
  1738. }
  1739. }
  1740. // Use large limit for --all, otherwise fetch more than needed and let outputResults filter
  1741. const fetchLimit = opts.all ? 100000 : Math.max(50, opts.limit * 2);
  1742. const results = searchFTS(db, query, fetchLimit, collectionId);
  1743. // Add context to results
  1744. const resultsWithContext = results.map(r => ({
  1745. ...r,
  1746. context: getContextForFile(db, r.file),
  1747. }));
  1748. closeDb();
  1749. if (resultsWithContext.length === 0) {
  1750. console.log("No results found.");
  1751. return;
  1752. }
  1753. outputResults(resultsWithContext, query, opts);
  1754. }
  1755. async function vectorSearch(query: string, opts: OutputOptions, model: string = DEFAULT_EMBED_MODEL): Promise<void> {
  1756. const db = getDb();
  1757. // Resolve collection filter if specified
  1758. let collectionId: number | undefined;
  1759. if (opts.collection) {
  1760. collectionId = getCollectionIdByName(db, opts.collection) ?? undefined;
  1761. if (collectionId === undefined) {
  1762. console.error(`Collection not found: ${opts.collection}`);
  1763. closeDb();
  1764. process.exit(1);
  1765. }
  1766. }
  1767. const tableExists = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
  1768. if (!tableExists) {
  1769. console.error("Vector index not found. Run 'qmd embed' first to create embeddings.");
  1770. closeDb();
  1771. return;
  1772. }
  1773. // Check index health and warn about issues
  1774. checkIndexHealth(db);
  1775. // Expand query to multiple variations (with caching)
  1776. const queries = await expandQuery(query, DEFAULT_QUERY_MODEL, db);
  1777. process.stderr.write(`Searching with ${queries.length} query variations...\n`);
  1778. // Collect results from all query variations
  1779. // For --all, fetch more results per query
  1780. const perQueryLimit = opts.all ? 500 : 20;
  1781. const allResults = new Map<string, { file: string; displayPath: string; title: string; body: string; score: number }>();
  1782. for (const q of queries) {
  1783. const vecResults = await searchVec(db, q, model, perQueryLimit, collectionId);
  1784. for (const r of vecResults) {
  1785. const existing = allResults.get(r.file);
  1786. if (!existing || r.score > existing.score) {
  1787. allResults.set(r.file, { file: r.file, displayPath: r.displayPath, title: r.title, body: r.body, score: r.score });
  1788. }
  1789. }
  1790. }
  1791. // Sort by max score and limit to requested count
  1792. const results = Array.from(allResults.values())
  1793. .sort((a, b) => b.score - a.score)
  1794. .slice(0, opts.limit)
  1795. .map(r => ({ ...r, context: getContextForFile(db, r.file) }));
  1796. closeDb();
  1797. if (results.length === 0) {
  1798. console.log("No results found.");
  1799. return;
  1800. }
  1801. outputResults(results, query, { ...opts, limit: results.length }); // Already limited
  1802. }
  1803. async function expandQuery(query: string, model: string = DEFAULT_QUERY_MODEL, db?: Database): Promise<string[]> {
  1804. process.stderr.write("Generating query variations...\n");
  1805. const prompt = `You are a search query expander. Given a search query, generate 2 alternative queries that would help find relevant documents.
  1806. Rules:
  1807. - Use synonyms and related terminology (e.g., "craft" → "craftsmanship", "quality", "excellence")
  1808. - Rephrase to capture different angles (e.g., "engineering culture" → "technical excellence", "developer practices")
  1809. - Keep proper nouns and named concepts exactly as written (e.g., "Build a Business", "Stripe", "Shopify")
  1810. - Each variation should be 3-8 words, natural search terms
  1811. - Do NOT just append words like "search" or "find" or "documents"
  1812. Query: "${query}"
  1813. Output exactly 2 variations, one per line, no numbering or bullets:`;
  1814. const requestBody = {
  1815. model,
  1816. prompt,
  1817. stream: false,
  1818. think: false,
  1819. options: { num_predict: 150 },
  1820. };
  1821. // Check cache
  1822. const cacheDb = db || getDb();
  1823. const cacheKey = getCacheKey(`${OLLAMA_URL}/api/generate`, requestBody);
  1824. const cached = getCachedResult(cacheDb, cacheKey);
  1825. let responseText: string;
  1826. if (cached) {
  1827. responseText = cached;
  1828. } else {
  1829. const response = await fetch(`${OLLAMA_URL}/api/generate`, {
  1830. method: "POST",
  1831. headers: { "Content-Type": "application/json" },
  1832. body: JSON.stringify(requestBody),
  1833. });
  1834. if (!response.ok) {
  1835. const errorText = await response.text();
  1836. if (errorText.includes("not found") || errorText.includes("does not exist")) {
  1837. await ensureModelAvailable(model);
  1838. if (!db) cacheDb.close();
  1839. return expandQuery(query, model, db);
  1840. }
  1841. if (!db) cacheDb.close();
  1842. return [query];
  1843. }
  1844. const data = await response.json() as { response: string };
  1845. responseText = data.response;
  1846. setCachedResult(cacheDb, cacheKey, responseText);
  1847. }
  1848. if (!db) cacheDb.close();
  1849. const lines = responseText.trim().split('\n')
  1850. .map(l => l.replace(/^[\d\.\-\*\"\s]+/, '').replace(/["\s]+$/, '').trim())
  1851. .filter(l => l.length > 2 && l.length < 100 && !l.startsWith('<') && !l.toLowerCase().includes('variation'))
  1852. .slice(0, 2);
  1853. const allQueries = [query, ...lines];
  1854. process.stderr.write(`${c.dim}Queries: ${allQueries.join(' | ')}${c.reset}\n`);
  1855. return allQueries;
  1856. }
  1857. async function querySearch(query: string, opts: OutputOptions, embedModel: string = DEFAULT_EMBED_MODEL, rerankModel: string = DEFAULT_RERANK_MODEL): Promise<void> {
  1858. const db = getDb();
  1859. // Resolve collection filter if specified
  1860. let collectionId: number | undefined;
  1861. if (opts.collection) {
  1862. collectionId = getCollectionIdByName(db, opts.collection) ?? undefined;
  1863. if (collectionId === undefined) {
  1864. console.error(`Collection not found: ${opts.collection}`);
  1865. closeDb();
  1866. process.exit(1);
  1867. }
  1868. }
  1869. // Check index health and warn about issues
  1870. checkIndexHealth(db);
  1871. // Expand query to multiple variations (with caching)
  1872. const queries = await expandQuery(query, DEFAULT_QUERY_MODEL, db);
  1873. process.stderr.write(`Searching with ${queries.length} query variations...\n`);
  1874. // Collect ranked result lists for RRF fusion
  1875. const rankedLists: RankedResult[][] = [];
  1876. const hasVectors = !!db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
  1877. for (const q of queries) {
  1878. // FTS search - get ranked results
  1879. const ftsResults = searchFTS(db, q, 20, collectionId);
  1880. if (ftsResults.length > 0) {
  1881. rankedLists.push(ftsResults.map(r => ({ file: r.file, displayPath: r.displayPath, title: r.title, body: r.body, score: r.score })));
  1882. }
  1883. // Vector search - get ranked results
  1884. if (hasVectors) {
  1885. const vecResults = await searchVec(db, q, embedModel, 20, collectionId);
  1886. if (vecResults.length > 0) {
  1887. rankedLists.push(vecResults.map(r => ({ file: r.file, displayPath: r.displayPath, title: r.title, body: r.body, score: r.score })));
  1888. }
  1889. }
  1890. }
  1891. // Apply Reciprocal Rank Fusion to combine all ranked lists
  1892. // Give 2x weight to original query results (first 2 lists: FTS + vector)
  1893. const weights = rankedLists.map((_, i) => i < 2 ? 2.0 : 1.0);
  1894. const fused = reciprocalRankFusion(rankedLists, weights);
  1895. const candidates = fused.slice(0, 30); // Over-retrieve for reranking
  1896. if (candidates.length === 0) {
  1897. console.log("No results found.");
  1898. closeDb();
  1899. return;
  1900. }
  1901. // Rerank with the original query (with caching)
  1902. const reranked = await rerank(
  1903. query,
  1904. candidates.map(c => ({ file: c.file, text: c.body })),
  1905. rerankModel,
  1906. db
  1907. );
  1908. // Blend RRF position score with reranker score using position-aware weights
  1909. // Top retrieval results get more protection from reranker disagreement
  1910. const candidateMap = new Map(candidates.map(c => [c.file, { displayPath: c.displayPath, title: c.title, body: c.body }]));
  1911. const rrfRankMap = new Map(candidates.map((c, i) => [c.file, i + 1])); // 1-indexed rank
  1912. const finalResults = reranked.map(r => {
  1913. const rrfRank = rrfRankMap.get(r.file) || 30;
  1914. // Position-aware blending: top retrieval results preserved more
  1915. // Rank 1-3: 75% RRF, 25% reranker (trust retrieval for exact matches)
  1916. // Rank 4-10: 60% RRF, 40% reranker
  1917. // Rank 11+: 40% RRF, 60% reranker (trust reranker for lower-ranked)
  1918. let rrfWeight: number;
  1919. if (rrfRank <= 3) {
  1920. rrfWeight = 0.75;
  1921. } else if (rrfRank <= 10) {
  1922. rrfWeight = 0.60;
  1923. } else {
  1924. rrfWeight = 0.40;
  1925. }
  1926. const rrfScore = 1 / rrfRank; // Position-based: 1, 0.5, 0.33...
  1927. const blendedScore = rrfWeight * rrfScore + (1 - rrfWeight) * r.score;
  1928. const candidate = candidateMap.get(r.file);
  1929. return {
  1930. file: r.file,
  1931. displayPath: candidate?.displayPath || "",
  1932. title: candidate?.title || "",
  1933. body: candidate?.body || "",
  1934. score: blendedScore,
  1935. context: getContextForFile(db, r.file),
  1936. };
  1937. }).sort((a, b) => b.score - a.score);
  1938. closeDb();
  1939. outputResults(finalResults, query, opts);
  1940. }
  1941. // Parse CLI arguments using util.parseArgs
  1942. function parseCLI() {
  1943. const { values, positionals } = parseArgs({
  1944. args: Bun.argv.slice(2), // Skip bun and script path
  1945. options: {
  1946. // Global options
  1947. index: { type: "string" },
  1948. help: { type: "boolean", short: "h" },
  1949. // Search options
  1950. n: { type: "string" },
  1951. "min-score": { type: "string" },
  1952. all: { type: "boolean" },
  1953. full: { type: "boolean" },
  1954. csv: { type: "boolean" },
  1955. md: { type: "boolean" },
  1956. xml: { type: "boolean" },
  1957. files: { type: "boolean" },
  1958. json: { type: "boolean" },
  1959. collection: { type: "string", short: "c" }, // Filter by collection
  1960. // Collection options
  1961. name: { type: "string" }, // collection name
  1962. mask: { type: "string" }, // glob pattern
  1963. // Embed options
  1964. force: { type: "boolean", short: "f" },
  1965. // Get options
  1966. l: { type: "string" }, // max lines
  1967. from: { type: "string" }, // start line
  1968. "max-bytes": { type: "string" }, // max bytes for multi-get
  1969. },
  1970. allowPositionals: true,
  1971. strict: false, // Allow unknown options to pass through
  1972. });
  1973. // Set global index name in store
  1974. if (values.index) {
  1975. setCustomIndexName(values.index);
  1976. }
  1977. // Determine output format
  1978. let format: OutputFormat = "cli";
  1979. if (values.csv) format = "csv";
  1980. else if (values.md) format = "md";
  1981. else if (values.xml) format = "xml";
  1982. else if (values.files) format = "files";
  1983. else if (values.json) format = "json";
  1984. // Default limit: 20 for --files/--json, 5 otherwise
  1985. // --all means return all results (use very large limit)
  1986. const defaultLimit = (format === "files" || format === "json") ? 20 : 5;
  1987. const isAll = values.all || false;
  1988. const opts: OutputOptions = {
  1989. format,
  1990. full: values.full || false,
  1991. limit: isAll ? 100000 : (values.n ? parseInt(values.n, 10) || defaultLimit : defaultLimit),
  1992. minScore: values["min-score"] ? parseFloat(values["min-score"]) || 0 : 0,
  1993. all: isAll,
  1994. collection: values.collection as string | undefined,
  1995. };
  1996. return {
  1997. command: positionals[0] || "",
  1998. args: positionals.slice(1),
  1999. query: positionals.slice(1).join(" "),
  2000. opts,
  2001. values,
  2002. };
  2003. }
  2004. function showHelp(): void {
  2005. console.log("Usage:");
  2006. console.log(" qmd collection add [path] --name <name> --mask <pattern> - Create/index collection");
  2007. console.log(" qmd collection list - List all collections with details");
  2008. console.log(" qmd collection remove <name> - Remove a collection by name");
  2009. console.log(" qmd collection rename <old> <new> - Rename a collection");
  2010. console.log(" qmd ls [collection[/path]] - List collections or files in a collection");
  2011. console.log(" qmd context add [path] \"text\" - Add context for path (defaults to current dir)");
  2012. console.log(" qmd context list - List all contexts");
  2013. console.log(" qmd context rm <path> - Remove context");
  2014. console.log(" qmd get <file>[:line] [-l N] [--from N] - Get document (optionally from line, max N lines)");
  2015. console.log(" qmd multi-get <pattern> [-l N] [--max-bytes N] - Get multiple docs by glob or comma-separated list");
  2016. console.log(" qmd status - Show index status and collections");
  2017. console.log(" qmd update - Re-index all collections");
  2018. console.log(" qmd embed [-f] - Create vector embeddings (chunks ~6KB each)");
  2019. console.log(" qmd cleanup - Remove cache and orphaned data, vacuum DB");
  2020. console.log(" qmd search <query> - Full-text search (BM25)");
  2021. console.log(" qmd vsearch <query> - Vector similarity search");
  2022. console.log(" qmd query <query> - Combined search with query expansion + reranking");
  2023. console.log(" qmd mcp - Start MCP server (for AI agent integration)");
  2024. console.log("");
  2025. console.log("Global options:");
  2026. console.log(" --index <name> - Use custom index name (default: index)");
  2027. console.log("");
  2028. console.log("Search options:");
  2029. console.log(" -n <num> - Number of results (default: 5, or 20 for --files)");
  2030. console.log(" --all - Return all matches (use with --min-score to filter)");
  2031. console.log(" --min-score <num> - Minimum similarity score");
  2032. console.log(" --full - Output full document instead of snippet");
  2033. console.log(" --files - Output score,filepath,context (default: 20 results)");
  2034. console.log(" --json - JSON output with snippets (default: 20 results)");
  2035. console.log(" --csv - CSV output with snippets");
  2036. console.log(" --md - Markdown output");
  2037. console.log(" --xml - XML output");
  2038. console.log(" -c, --collection <name> - Filter results to a specific collection");
  2039. console.log("");
  2040. console.log("Multi-get options:");
  2041. console.log(" -l <num> - Maximum lines per file");
  2042. console.log(" --max-bytes <num> - Skip files larger than N bytes (default: 10240)");
  2043. console.log(" --json/--csv/--md/--xml/--files - Output format (same as search)");
  2044. console.log("");
  2045. console.log("Environment:");
  2046. console.log(" OLLAMA_URL - Ollama server URL (default: http://localhost:11434)");
  2047. console.log("");
  2048. console.log("Models:");
  2049. console.log(` Embedding: ${DEFAULT_EMBED_MODEL}`);
  2050. console.log(` Reranking: ${DEFAULT_RERANK_MODEL}`);
  2051. console.log("");
  2052. console.log(`Index: ${getDbPath()}`);
  2053. }
  2054. // Main CLI - only run if this is the main module
  2055. if (import.meta.main) {
  2056. const cli = parseCLI();
  2057. if (!cli.command || cli.values.help) {
  2058. showHelp();
  2059. process.exit(cli.values.help ? 0 : 1);
  2060. }
  2061. switch (cli.command) {
  2062. case "context": {
  2063. const subcommand = cli.args[0];
  2064. if (!subcommand) {
  2065. console.error("Usage: qmd context <add|list|rm>");
  2066. console.error("");
  2067. console.error("Commands:");
  2068. console.error(" qmd context add [path] \"text\" - Add context (defaults to current dir)");
  2069. console.error(" qmd context add / \"text\" - Add global context to all collections");
  2070. console.error(" qmd context list - List all contexts");
  2071. console.error(" qmd context rm <path> - Remove context");
  2072. process.exit(1);
  2073. }
  2074. switch (subcommand) {
  2075. case "add": {
  2076. if (cli.args.length < 2) {
  2077. console.error("Usage: qmd context add [path] \"text\"");
  2078. console.error("Examples:");
  2079. console.error(" qmd context add \"Context for current directory\"");
  2080. console.error(" qmd context add . \"Context for current directory\"");
  2081. console.error(" qmd context add /subfolder \"Context for subfolder\"");
  2082. console.error(" qmd context add / \"Global context for all collections\"");
  2083. console.error(" qmd context add qmd://journals/2024 \"Context for 2024 journals\"");
  2084. process.exit(1);
  2085. }
  2086. let pathArg: string | undefined;
  2087. let contextText: string;
  2088. // Check if first arg looks like a path or if it's the context text
  2089. const firstArg = cli.args[1];
  2090. const secondArg = cli.args[2];
  2091. if (secondArg) {
  2092. // Two args: path + context
  2093. pathArg = firstArg;
  2094. contextText = cli.args.slice(2).join(" ");
  2095. } else {
  2096. // One arg: context only (use current directory)
  2097. pathArg = undefined;
  2098. contextText = firstArg;
  2099. }
  2100. await contextAdd(pathArg, contextText);
  2101. break;
  2102. }
  2103. case "list": {
  2104. contextList();
  2105. break;
  2106. }
  2107. case "rm":
  2108. case "remove": {
  2109. if (cli.args.length < 2) {
  2110. console.error("Usage: qmd context rm <path>");
  2111. console.error("Examples:");
  2112. console.error(" qmd context rm /");
  2113. console.error(" qmd context rm qmd://journals/2024");
  2114. process.exit(1);
  2115. }
  2116. contextRemove(cli.args[1]);
  2117. break;
  2118. }
  2119. default:
  2120. console.error(`Unknown subcommand: ${subcommand}`);
  2121. console.error("Available: add, list, rm");
  2122. process.exit(1);
  2123. }
  2124. break;
  2125. }
  2126. // Legacy alias for backwards compatibility
  2127. case "add-context": {
  2128. console.error(`${c.yellow}Note: 'qmd add-context' is deprecated. Use 'qmd context add' instead.${c.reset}`);
  2129. if (cli.args.length === 0) {
  2130. console.error("Usage: qmd context add [path] \"text\"");
  2131. process.exit(1);
  2132. }
  2133. let pathArg: string | undefined;
  2134. let contextText: string;
  2135. if (cli.args.length === 1) {
  2136. pathArg = undefined;
  2137. contextText = cli.args[0];
  2138. } else {
  2139. pathArg = cli.args[0];
  2140. contextText = cli.args.slice(1).join(" ");
  2141. }
  2142. await contextAdd(pathArg, contextText);
  2143. break;
  2144. }
  2145. case "get": {
  2146. if (!cli.args[0]) {
  2147. console.error("Usage: qmd get <filepath>[:line] [--from <line>] [-l <lines>]");
  2148. process.exit(1);
  2149. }
  2150. const fromLine = cli.values.from ? parseInt(cli.values.from as string, 10) : undefined;
  2151. const maxLines = cli.values.l ? parseInt(cli.values.l as string, 10) : undefined;
  2152. getDocument(cli.args[0], fromLine, maxLines);
  2153. break;
  2154. }
  2155. case "multi-get": {
  2156. if (!cli.args[0]) {
  2157. console.error("Usage: qmd multi-get <pattern> [-l <lines>] [--max-bytes <bytes>] [--json|--csv|--md|--xml|--files]");
  2158. console.error(" pattern: glob (e.g., 'journals/2025-05*.md') or comma-separated list");
  2159. process.exit(1);
  2160. }
  2161. const maxLinesMulti = cli.values.l ? parseInt(cli.values.l as string, 10) : undefined;
  2162. const maxBytes = cli.values["max-bytes"] ? parseInt(cli.values["max-bytes"] as string, 10) : DEFAULT_MULTI_GET_MAX_BYTES;
  2163. multiGet(cli.args[0], maxLinesMulti, maxBytes, cli.opts.format);
  2164. break;
  2165. }
  2166. case "ls": {
  2167. listFiles(cli.args[0]);
  2168. break;
  2169. }
  2170. case "collection": {
  2171. const subcommand = cli.args[0];
  2172. switch (subcommand) {
  2173. case "list": {
  2174. collectionList();
  2175. break;
  2176. }
  2177. case "add": {
  2178. const pwd = cli.args[1] || getPwd();
  2179. const resolvedPwd = pwd === '.' ? getPwd() : getRealPath(resolve(pwd));
  2180. const globPattern = cli.values.mask as string || DEFAULT_GLOB;
  2181. const name = cli.values.name as string | undefined;
  2182. await collectionAdd(resolvedPwd, globPattern, name);
  2183. break;
  2184. }
  2185. case "remove":
  2186. case "rm": {
  2187. if (!cli.args[1]) {
  2188. console.error("Usage: qmd collection remove <name>");
  2189. console.error(" Use 'qmd collection list' to see available collections");
  2190. process.exit(1);
  2191. }
  2192. collectionRemove(cli.args[1]);
  2193. break;
  2194. }
  2195. case "rename":
  2196. case "mv": {
  2197. if (!cli.args[1] || !cli.args[2]) {
  2198. console.error("Usage: qmd collection rename <old-name> <new-name>");
  2199. console.error(" Use 'qmd collection list' to see available collections");
  2200. process.exit(1);
  2201. }
  2202. collectionRename(cli.args[1], cli.args[2]);
  2203. break;
  2204. }
  2205. default:
  2206. console.error(`Unknown subcommand: ${subcommand}`);
  2207. console.error("Available: list, add, remove, rename");
  2208. process.exit(1);
  2209. }
  2210. break;
  2211. }
  2212. case "status":
  2213. showStatus();
  2214. break;
  2215. case "update":
  2216. await updateCollections();
  2217. break;
  2218. case "embed":
  2219. await vectorIndex(DEFAULT_EMBED_MODEL, cli.values.force || false);
  2220. break;
  2221. case "search":
  2222. if (!cli.query) {
  2223. console.error("Usage: qmd search [options] <query>");
  2224. process.exit(1);
  2225. }
  2226. search(cli.query, cli.opts);
  2227. break;
  2228. case "vsearch":
  2229. if (!cli.query) {
  2230. console.error("Usage: qmd vsearch [options] <query>");
  2231. process.exit(1);
  2232. }
  2233. // Default min-score for vector search is 0.3
  2234. if (!cli.values["min-score"]) {
  2235. cli.opts.minScore = 0.3;
  2236. }
  2237. await vectorSearch(cli.query, cli.opts);
  2238. break;
  2239. case "query":
  2240. if (!cli.query) {
  2241. console.error("Usage: qmd query [options] <query>");
  2242. process.exit(1);
  2243. }
  2244. await querySearch(cli.query, cli.opts);
  2245. break;
  2246. case "mcp": {
  2247. const { startMcpServer } = await import("./mcp.js");
  2248. await startMcpServer();
  2249. break;
  2250. }
  2251. case "cleanup": {
  2252. const db = getDb();
  2253. // 1. Clear ollama_cache
  2254. const cacheCount = db.prepare(`SELECT COUNT(*) as c FROM ollama_cache`).get() as { c: number };
  2255. db.exec(`DELETE FROM ollama_cache`);
  2256. console.log(`${c.green}✓${c.reset} Cleared ${cacheCount.c} cached API responses`);
  2257. // 2. Remove orphaned vectors (no active document with that hash)
  2258. const orphanedVecs = db.prepare(`
  2259. SELECT COUNT(*) as c FROM content_vectors cv
  2260. WHERE NOT EXISTS (
  2261. SELECT 1 FROM documents d WHERE d.hash = cv.hash AND d.active = 1
  2262. )
  2263. `).get() as { c: number };
  2264. if (orphanedVecs.c > 0) {
  2265. db.exec(`
  2266. DELETE FROM vectors_vec WHERE hash_seq IN (
  2267. SELECT cv.hash || '_' || cv.seq FROM content_vectors cv
  2268. WHERE NOT EXISTS (
  2269. SELECT 1 FROM documents d WHERE d.hash = cv.hash AND d.active = 1
  2270. )
  2271. )
  2272. `);
  2273. db.exec(`
  2274. DELETE FROM content_vectors WHERE hash NOT IN (
  2275. SELECT hash FROM documents WHERE active = 1
  2276. )
  2277. `);
  2278. console.log(`${c.green}✓${c.reset} Removed ${orphanedVecs.c} orphaned embedding chunks`);
  2279. } else {
  2280. console.log(`${c.dim}No orphaned embeddings to remove${c.reset}`);
  2281. }
  2282. // 3. Count inactive documents
  2283. const inactiveDocs = db.prepare(`SELECT COUNT(*) as c FROM documents WHERE active = 0`).get() as { c: number };
  2284. if (inactiveDocs.c > 0) {
  2285. db.exec(`DELETE FROM documents WHERE active = 0`);
  2286. console.log(`${c.green}✓${c.reset} Removed ${inactiveDocs.c} inactive document records`);
  2287. }
  2288. // 4. Vacuum to reclaim space
  2289. db.exec(`VACUUM`);
  2290. console.log(`${c.green}✓${c.reset} Database vacuumed`);
  2291. closeDb();
  2292. break;
  2293. }
  2294. default:
  2295. console.error(`Unknown command: ${cli.command}`);
  2296. console.error("Run 'qmd --help' for usage.");
  2297. process.exit(1);
  2298. }
  2299. } // end if (import.meta.main)