qmd.ts 87 KB

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