qmd.ts 93 KB

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