qmd.ts 89 KB

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