qmd.ts 89 KB

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