qmd.js 131 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994
  1. #!/usr/bin/env node
  2. import { openDatabase } from "../db.js";
  3. import fastGlob from "fast-glob";
  4. import { execSync, spawn as nodeSpawn } from "child_process";
  5. import { fileURLToPath } from "url";
  6. import { dirname, join as pathJoin, relative as relativePath } from "path";
  7. import { parseArgs } from "util";
  8. import { readFileSync, realpathSync, statSync, existsSync, unlinkSync, writeFileSync, openSync, closeSync, mkdirSync, lstatSync, rmSync, symlinkSync, readlinkSync } from "fs";
  9. import { createInterface } from "readline/promises";
  10. import { getPwd, getRealPath, homedir, resolve, enableProductionMode, searchFTS, extractSnippet, getContextForFile, getContextForPath, listCollections, removeCollection, renameCollection, findSimilarFiles, findDocumentByDocid, isDocid, matchFilesByGlob, getHashesNeedingEmbedding, clearAllEmbeddings, insertEmbedding, getStatus, hashContent, extractTitle, formatDocForEmbedding, chunkDocumentByTokens, clearCache, getCacheKey, getCachedResult, setCachedResult, getIndexHealth, parseVirtualPath, buildVirtualPath, isVirtualPath, resolveVirtualPath, toVirtualPath, insertContent, insertDocument, findActiveDocument, updateDocumentTitle, updateDocument, deactivateDocument, getActiveDocumentPaths, cleanupOrphanedContent, deleteLLMCache, deleteInactiveDocuments, cleanupOrphanedVectors, vacuumDatabase, getCollectionsWithoutContext, getTopLevelPathsWithoutContext, handelize, hybridQuery, vectorSearchQuery, structuredSearch, addLineNumbers, DEFAULT_EMBED_MODEL, DEFAULT_EMBED_MAX_BATCH_BYTES, DEFAULT_EMBED_MAX_DOCS_PER_BATCH, DEFAULT_RERANK_MODEL, DEFAULT_GLOB, DEFAULT_MULTI_GET_MAX_BYTES, createStore, getDefaultDbPath, reindexCollection, generateEmbeddings, syncConfigToDb, } from "../store.js";
  11. import { disposeDefaultLlamaCpp, getDefaultLlamaCpp, setDefaultLlamaCpp, LlamaCpp, withLLMSession, pullModels, DEFAULT_EMBED_MODEL_URI, DEFAULT_GENERATE_MODEL_URI, DEFAULT_RERANK_MODEL_URI, DEFAULT_MODEL_CACHE_DIR } from "../llm.js";
  12. import { formatSearchResults, formatDocuments, escapeXml, escapeCSV, } from "./formatter.js";
  13. import { getCollection as getCollectionFromYaml, listCollections as yamlListCollections, getDefaultCollectionNames, addContext as yamlAddContext, removeContext as yamlRemoveContext, removeCollection as yamlRemoveCollectionFn, renameCollection as yamlRenameCollectionFn, setGlobalContext, listAllContexts, setConfigIndexName, loadConfig, } from "../collections.js";
  14. import { getEmbeddedQmdSkillContent, getEmbeddedQmdSkillFiles } from "../embedded-skills.js";
  15. import { createEmbeddingProvider, resolveProviderKind, ModelMismatchError, } from "../embedding/index.js";
  16. // Enable production mode - allows using default database path
  17. // Tests must set INDEX_PATH or use createStore() with explicit path
  18. enableProductionMode();
  19. // =============================================================================
  20. // Store/DB lifecycle (no legacy singletons in store.ts)
  21. // =============================================================================
  22. let store = null;
  23. let storeDbPathOverride;
  24. function getStore() {
  25. if (!store) {
  26. store = createStore(storeDbPathOverride);
  27. // Sync YAML config into SQLite store_collections so store.ts reads from DB
  28. try {
  29. const config = loadConfig();
  30. syncConfigToDb(store.db, config);
  31. if (config.models) {
  32. setDefaultLlamaCpp(new LlamaCpp({
  33. embedModel: config.models.embed,
  34. generateModel: config.models.generate,
  35. rerankModel: config.models.rerank,
  36. }));
  37. }
  38. }
  39. catch {
  40. // Config may not exist yet — that's fine, DB works without it
  41. }
  42. }
  43. return store;
  44. }
  45. function getDb() {
  46. return getStore().db;
  47. }
  48. /** Re-sync YAML config into SQLite after CLI mutations (add/remove/rename collection, context changes) */
  49. function resyncConfig() {
  50. const s = getStore();
  51. try {
  52. const config = loadConfig();
  53. // Clear config hash to force re-sync
  54. s.db.prepare(`DELETE FROM store_config WHERE key = 'config_hash'`).run();
  55. syncConfigToDb(s.db, config);
  56. }
  57. catch {
  58. // Config may not exist — that's fine
  59. }
  60. }
  61. function closeDb() {
  62. if (store) {
  63. store.close();
  64. store = null;
  65. }
  66. }
  67. function getDbPath() {
  68. return store?.dbPath ?? storeDbPathOverride ?? getDefaultDbPath();
  69. }
  70. function setIndexName(name) {
  71. let normalizedName = name;
  72. // Normalize relative paths to prevent malformed database paths
  73. if (name && name.includes('/')) {
  74. const { resolve } = require('path');
  75. const { cwd } = require('process');
  76. const absolutePath = resolve(cwd(), name);
  77. // Replace path separators with underscores to create a valid filename
  78. normalizedName = absolutePath.replace(/\//g, '_').replace(/^_/, '');
  79. }
  80. storeDbPathOverride = normalizedName ? getDefaultDbPath(normalizedName) : undefined;
  81. // Reset open handle so next use opens the new index
  82. closeDb();
  83. }
  84. function ensureVecTable(_db, dimensions) {
  85. // Store owns the DB; ignore `_db` and ensure vec table on the active store
  86. getStore().ensureVecTable(dimensions);
  87. }
  88. // Terminal colors (respects NO_COLOR env)
  89. const useColor = !process.env.NO_COLOR && process.stdout.isTTY;
  90. const c = {
  91. reset: useColor ? "\x1b[0m" : "",
  92. dim: useColor ? "\x1b[2m" : "",
  93. bold: useColor ? "\x1b[1m" : "",
  94. cyan: useColor ? "\x1b[36m" : "",
  95. yellow: useColor ? "\x1b[33m" : "",
  96. green: useColor ? "\x1b[32m" : "",
  97. magenta: useColor ? "\x1b[35m" : "",
  98. blue: useColor ? "\x1b[34m" : "",
  99. red: useColor ? "\x1b[31m" : "",
  100. };
  101. // Terminal cursor control
  102. const cursor = {
  103. hide() { process.stderr.write('\x1b[?25l'); },
  104. show() { process.stderr.write('\x1b[?25h'); },
  105. };
  106. // Ensure cursor is restored on exit
  107. process.on('SIGINT', () => { cursor.show(); process.exit(130); });
  108. process.on('SIGTERM', () => { cursor.show(); process.exit(143); });
  109. // Terminal progress bar using OSC 9;4 escape sequence (TTY only)
  110. const isTTY = process.stderr.isTTY;
  111. const progress = {
  112. set(percent) {
  113. if (isTTY)
  114. process.stderr.write(`\x1b]9;4;1;${Math.round(percent)}\x07`);
  115. },
  116. clear() {
  117. if (isTTY)
  118. process.stderr.write(`\x1b]9;4;0\x07`);
  119. },
  120. indeterminate() {
  121. if (isTTY)
  122. process.stderr.write(`\x1b]9;4;3\x07`);
  123. },
  124. error() {
  125. if (isTTY)
  126. process.stderr.write(`\x1b]9;4;2\x07`);
  127. },
  128. };
  129. // Format seconds into human-readable ETA
  130. function formatETA(seconds) {
  131. if (seconds < 60)
  132. return `${Math.round(seconds)}s`;
  133. if (seconds < 3600)
  134. return `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`;
  135. return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;
  136. }
  137. // Check index health and print warnings/tips
  138. function checkIndexHealth(db) {
  139. const { needsEmbedding, totalDocs, daysStale } = getIndexHealth(db);
  140. // Warn if many docs need embedding
  141. if (needsEmbedding > 0) {
  142. const pct = Math.round((needsEmbedding / totalDocs) * 100);
  143. if (pct >= 10) {
  144. process.stderr.write(`${c.yellow}Warning: ${needsEmbedding} documents (${pct}%) need embeddings. Run 'qmd embed' for better results.${c.reset}\n`);
  145. }
  146. else {
  147. process.stderr.write(`${c.dim}Tip: ${needsEmbedding} documents need embeddings. Run 'qmd embed' to index them.${c.reset}\n`);
  148. }
  149. }
  150. // Check if most recent document update is older than 2 weeks
  151. if (daysStale !== null && daysStale >= 14) {
  152. process.stderr.write(`${c.dim}Tip: Index last updated ${daysStale} days ago. Run 'qmd update' to refresh.${c.reset}\n`);
  153. }
  154. }
  155. // Compute unique display path for a document
  156. // Always include at least parent folder + filename, add more parent dirs until unique
  157. function computeDisplayPath(filepath, collectionPath, existingPaths) {
  158. // Get path relative to collection (include collection dir name)
  159. const collectionDir = collectionPath.replace(/\/$/, '');
  160. const collectionName = collectionDir.split('/').pop() || '';
  161. let relativePath;
  162. if (filepath.startsWith(collectionDir + '/')) {
  163. // filepath is under collection: use collection name + relative path
  164. relativePath = collectionName + filepath.slice(collectionDir.length);
  165. }
  166. else {
  167. // Fallback: just use the filepath
  168. relativePath = filepath;
  169. }
  170. const parts = relativePath.split('/').filter(p => p.length > 0);
  171. // Always include at least parent folder + filename (minimum 2 parts if available)
  172. // Then add more parent dirs until unique
  173. const minParts = Math.min(2, parts.length);
  174. for (let i = parts.length - minParts; i >= 0; i--) {
  175. const candidate = parts.slice(i).join('/');
  176. if (!existingPaths.has(candidate)) {
  177. return candidate;
  178. }
  179. }
  180. // Absolute fallback: use full path (should be unique)
  181. return filepath;
  182. }
  183. function formatTimeAgo(date) {
  184. const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
  185. if (seconds < 60)
  186. return `${seconds}s ago`;
  187. const minutes = Math.floor(seconds / 60);
  188. if (minutes < 60)
  189. return `${minutes}m ago`;
  190. const hours = Math.floor(minutes / 60);
  191. if (hours < 24)
  192. return `${hours}h ago`;
  193. const days = Math.floor(hours / 24);
  194. return `${days}d ago`;
  195. }
  196. function formatMs(ms) {
  197. if (ms < 1000)
  198. return `${ms}ms`;
  199. return `${(ms / 1000).toFixed(1)}s`;
  200. }
  201. function formatBytes(bytes) {
  202. if (bytes < 1024)
  203. return `${bytes} B`;
  204. if (bytes < 1024 * 1024)
  205. return `${(bytes / 1024).toFixed(1)} KB`;
  206. if (bytes < 1024 * 1024 * 1024)
  207. return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  208. return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
  209. }
  210. async function showStatus() {
  211. const dbPath = getDbPath();
  212. const db = getDb();
  213. // Collections are defined in YAML; no duplicate cleanup needed.
  214. // Collections are defined in YAML; no duplicate cleanup needed.
  215. // Index size
  216. let indexSize = 0;
  217. try {
  218. const stat = statSync(dbPath).size;
  219. indexSize = stat;
  220. }
  221. catch { }
  222. // Collections info (from YAML + database stats)
  223. const collections = listCollections(db);
  224. // Overall stats
  225. const totalDocs = db.prepare(`SELECT COUNT(*) as count FROM documents WHERE active = 1`).get();
  226. const vectorCount = db.prepare(`SELECT COUNT(*) as count FROM content_vectors`).get();
  227. const needsEmbedding = getHashesNeedingEmbedding(db);
  228. // Most recent update across all collections
  229. const mostRecent = db.prepare(`SELECT MAX(modified_at) as latest FROM documents WHERE active = 1`).get();
  230. console.log(`${c.bold}QMD Status${c.reset}\n`);
  231. console.log(`Index: ${dbPath}`);
  232. console.log(`Size: ${formatBytes(indexSize)}`);
  233. // MCP daemon status (check PID file liveness)
  234. const mcpCacheDir = process.env.XDG_CACHE_HOME
  235. ? resolve(process.env.XDG_CACHE_HOME, "qmd")
  236. : resolve(homedir(), ".cache", "qmd");
  237. const mcpPidPath = resolve(mcpCacheDir, "mcp.pid");
  238. if (existsSync(mcpPidPath)) {
  239. const mcpPid = parseInt(readFileSync(mcpPidPath, "utf-8").trim());
  240. try {
  241. process.kill(mcpPid, 0);
  242. console.log(`MCP: ${c.green}running${c.reset} (PID ${mcpPid})`);
  243. }
  244. catch {
  245. unlinkSync(mcpPidPath);
  246. // Stale PID file cleaned up silently
  247. }
  248. }
  249. console.log("");
  250. console.log(`${c.bold}Documents${c.reset}`);
  251. console.log(` Total: ${totalDocs.count} files indexed`);
  252. console.log(` Vectors: ${vectorCount.count} embedded`);
  253. if (needsEmbedding > 0) {
  254. console.log(` ${c.yellow}Pending: ${needsEmbedding} need embedding${c.reset} (run 'qmd embed')`);
  255. }
  256. if (mostRecent.latest) {
  257. const lastUpdate = new Date(mostRecent.latest);
  258. console.log(` Updated: ${formatTimeAgo(lastUpdate)}`);
  259. }
  260. // Get all contexts grouped by collection (from YAML)
  261. const allContexts = listAllContexts();
  262. const contextsByCollection = new Map();
  263. for (const ctx of allContexts) {
  264. // Group contexts by collection name
  265. if (!contextsByCollection.has(ctx.collection)) {
  266. contextsByCollection.set(ctx.collection, []);
  267. }
  268. contextsByCollection.get(ctx.collection).push({
  269. path_prefix: ctx.path,
  270. context: ctx.context
  271. });
  272. }
  273. // AST chunking status
  274. try {
  275. const { getASTStatus } = await import("../ast.js");
  276. const ast = await getASTStatus();
  277. console.log(`\n${c.bold}AST Chunking${c.reset}`);
  278. if (ast.available) {
  279. const ok = ast.languages.filter(l => l.available).map(l => l.language);
  280. const fail = ast.languages.filter(l => !l.available);
  281. console.log(` Status: ${c.green}active${c.reset}`);
  282. console.log(` Languages: ${ok.join(", ")}`);
  283. if (fail.length > 0) {
  284. for (const f of fail) {
  285. console.log(` ${c.yellow}Unavailable: ${f.language} (${f.error})${c.reset}`);
  286. }
  287. }
  288. }
  289. else {
  290. console.log(` Status: ${c.yellow}unavailable${c.reset} (falling back to regex chunking)`);
  291. for (const l of ast.languages) {
  292. if (l.error)
  293. console.log(` ${c.dim}${l.language}: ${l.error}${c.reset}`);
  294. }
  295. }
  296. }
  297. catch {
  298. console.log(`\n${c.bold}AST Chunking${c.reset}`);
  299. console.log(` Status: ${c.dim}not available${c.reset}`);
  300. }
  301. if (collections.length > 0) {
  302. console.log(`\n${c.bold}Collections${c.reset}`);
  303. for (const col of collections) {
  304. const lastMod = col.last_modified ? formatTimeAgo(new Date(col.last_modified)) : "never";
  305. const contexts = contextsByCollection.get(col.name) || [];
  306. console.log(` ${c.cyan}${col.name}${c.reset} ${c.dim}(qmd://${col.name}/)${c.reset}`);
  307. console.log(` ${c.dim}Pattern:${c.reset} ${col.glob_pattern}`);
  308. console.log(` ${c.dim}Files:${c.reset} ${col.active_count} (updated ${lastMod})`);
  309. if (contexts.length > 0) {
  310. console.log(` ${c.dim}Contexts:${c.reset} ${contexts.length}`);
  311. for (const ctx of contexts) {
  312. // Handle both empty string and '/' as root context
  313. const pathDisplay = (ctx.path_prefix === '' || ctx.path_prefix === '/') ? '/' : `/${ctx.path_prefix}`;
  314. const contextPreview = ctx.context.length > 60
  315. ? ctx.context.substring(0, 57) + '...'
  316. : ctx.context;
  317. console.log(` ${c.dim}${pathDisplay}:${c.reset} ${contextPreview}`);
  318. }
  319. }
  320. }
  321. // Show examples of virtual paths
  322. console.log(`\n${c.bold}Examples${c.reset}`);
  323. console.log(` ${c.dim}# List files in a collection${c.reset}`);
  324. if (collections.length > 0 && collections[0]) {
  325. console.log(` qmd ls ${collections[0].name}`);
  326. }
  327. console.log(` ${c.dim}# Get a document${c.reset}`);
  328. if (collections.length > 0 && collections[0]) {
  329. console.log(` qmd get qmd://${collections[0].name}/path/to/file.md`);
  330. }
  331. console.log(` ${c.dim}# Search within a collection${c.reset}`);
  332. if (collections.length > 0 && collections[0]) {
  333. console.log(` qmd search "query" -c ${collections[0].name}`);
  334. }
  335. }
  336. else {
  337. console.log(`\n${c.dim}No collections. Run 'qmd collection add .' to index markdown files.${c.reset}`);
  338. }
  339. // Models
  340. {
  341. // hf:org/repo/file.gguf → https://huggingface.co/org/repo
  342. const hfLink = (uri) => {
  343. const match = uri.match(/^hf:([^/]+\/[^/]+)\//);
  344. return match ? `https://huggingface.co/${match[1]}` : uri;
  345. };
  346. console.log(`\n${c.bold}Models${c.reset}`);
  347. console.log(` Embedding: ${hfLink(DEFAULT_EMBED_MODEL_URI)}`);
  348. console.log(` Reranking: ${hfLink(DEFAULT_RERANK_MODEL_URI)}`);
  349. console.log(` Generation: ${hfLink(DEFAULT_GENERATE_MODEL_URI)}`);
  350. }
  351. // Device / GPU info
  352. try {
  353. const llm = getDefaultLlamaCpp();
  354. const device = await llm.getDeviceInfo();
  355. console.log(`\n${c.bold}Device${c.reset}`);
  356. if (device.gpu) {
  357. console.log(` GPU: ${c.green}${device.gpu}${c.reset} (offloading: ${device.gpuOffloading ? 'yes' : 'no'})`);
  358. if (device.gpuDevices.length > 0) {
  359. // Deduplicate and count GPUs
  360. const counts = new Map();
  361. for (const name of device.gpuDevices) {
  362. counts.set(name, (counts.get(name) || 0) + 1);
  363. }
  364. const deviceStr = Array.from(counts.entries())
  365. .map(([name, count]) => count > 1 ? `${count}× ${name}` : name)
  366. .join(', ');
  367. console.log(` Devices: ${deviceStr}`);
  368. }
  369. if (device.vram) {
  370. console.log(` VRAM: ${formatBytes(device.vram.free)} free / ${formatBytes(device.vram.total)} total`);
  371. }
  372. }
  373. else {
  374. console.log(` GPU: ${c.yellow}none${c.reset} (running on CPU — models will be slow)`);
  375. console.log(` ${c.dim}Tip: Install CUDA, Vulkan, or Metal support for GPU acceleration.${c.reset}`);
  376. }
  377. console.log(` CPU: ${device.cpuCores} math cores`);
  378. }
  379. catch {
  380. // Don't fail status if LLM init fails
  381. }
  382. // Tips section
  383. const tips = [];
  384. // Check for collections without context
  385. const collectionsWithoutContext = collections.filter(col => {
  386. const contexts = contextsByCollection.get(col.name) || [];
  387. return contexts.length === 0;
  388. });
  389. if (collectionsWithoutContext.length > 0) {
  390. const names = collectionsWithoutContext.map(c => c.name).slice(0, 3).join(', ');
  391. const more = collectionsWithoutContext.length > 3 ? ` +${collectionsWithoutContext.length - 3} more` : '';
  392. tips.push(`Add context to collections for better search results: ${names}${more}`);
  393. tips.push(` ${c.dim}qmd context add qmd://<name>/ "What this collection contains"${c.reset}`);
  394. tips.push(` ${c.dim}qmd context add qmd://<name>/meeting-notes "Weekly team meeting notes"${c.reset}`);
  395. }
  396. // Check for collections without update commands
  397. const collectionsWithoutUpdate = collections.filter(col => {
  398. const yamlCol = getCollectionFromYaml(col.name);
  399. return !yamlCol?.update;
  400. });
  401. if (collectionsWithoutUpdate.length > 0 && collections.length > 1) {
  402. const names = collectionsWithoutUpdate.map(c => c.name).slice(0, 3).join(', ');
  403. const more = collectionsWithoutUpdate.length > 3 ? ` +${collectionsWithoutUpdate.length - 3} more` : '';
  404. tips.push(`Add update commands to keep collections fresh: ${names}${more}`);
  405. tips.push(` ${c.dim}qmd collection update-cmd <name> 'git stash && git pull --rebase --ff-only && git stash pop'${c.reset}`);
  406. }
  407. if (tips.length > 0) {
  408. console.log(`\n${c.bold}Tips${c.reset}`);
  409. for (const tip of tips) {
  410. console.log(` ${tip}`);
  411. }
  412. }
  413. closeDb();
  414. }
  415. async function updateCollections() {
  416. const db = getDb();
  417. const storeInstance = getStore();
  418. // Collections are defined in YAML; no duplicate cleanup needed.
  419. // Clear Ollama cache on update
  420. clearCache(db);
  421. const collections = listCollections(db);
  422. if (collections.length === 0) {
  423. console.log(`${c.dim}No collections found. Run 'qmd collection add .' to index markdown files.${c.reset}`);
  424. closeDb();
  425. return;
  426. }
  427. console.log(`${c.bold}Updating ${collections.length} collection(s)...${c.reset}\n`);
  428. for (let i = 0; i < collections.length; i++) {
  429. const col = collections[i];
  430. if (!col)
  431. continue;
  432. console.log(`${c.cyan}[${i + 1}/${collections.length}]${c.reset} ${c.bold}${col.name}${c.reset} ${c.dim}(${col.glob_pattern})${c.reset}`);
  433. // Execute custom update command if specified in YAML
  434. const yamlCol = getCollectionFromYaml(col.name);
  435. if (yamlCol?.update) {
  436. console.log(`${c.dim} Running update command: ${yamlCol.update}${c.reset}`);
  437. try {
  438. const proc = nodeSpawn("bash", ["-c", yamlCol.update], {
  439. cwd: col.pwd,
  440. stdio: ["ignore", "pipe", "pipe"],
  441. });
  442. const [output, errorOutput, exitCode] = await new Promise((resolve, reject) => {
  443. let out = "";
  444. let err = "";
  445. proc.stdout?.on("data", (d) => { out += d.toString(); });
  446. proc.stderr?.on("data", (d) => { err += d.toString(); });
  447. proc.on("error", reject);
  448. proc.on("close", (code) => resolve([out, err, code ?? 1]));
  449. });
  450. if (output.trim()) {
  451. console.log(output.trim().split('\n').map(l => ` ${l}`).join('\n'));
  452. }
  453. if (errorOutput.trim()) {
  454. console.log(errorOutput.trim().split('\n').map(l => ` ${l}`).join('\n'));
  455. }
  456. if (exitCode !== 0) {
  457. console.log(`${c.yellow}✗ Update command failed with exit code ${exitCode}${c.reset}`);
  458. process.exit(exitCode);
  459. }
  460. }
  461. catch (err) {
  462. console.log(`${c.yellow}✗ Update command failed: ${err}${c.reset}`);
  463. process.exit(1);
  464. }
  465. }
  466. const startTime = Date.now();
  467. console.log(`Collection: ${col.pwd} (${col.glob_pattern})`);
  468. progress.indeterminate();
  469. const result = await reindexCollection(storeInstance, col.pwd, col.glob_pattern, col.name, {
  470. ignorePatterns: yamlCol?.ignore,
  471. onProgress: (info) => {
  472. progress.set((info.current / info.total) * 100);
  473. const elapsed = (Date.now() - startTime) / 1000;
  474. const rate = info.current / elapsed;
  475. const remaining = (info.total - info.current) / rate;
  476. const eta = info.current > 2 ? ` ETA: ${formatETA(remaining)}` : "";
  477. if (isTTY)
  478. process.stderr.write(`\rIndexing: ${info.current}/${info.total}${eta} `);
  479. },
  480. });
  481. progress.clear();
  482. console.log(`\nIndexed: ${result.indexed} new, ${result.updated} updated, ${result.unchanged} unchanged, ${result.removed} removed`);
  483. if (result.orphanedCleaned > 0) {
  484. console.log(`Cleaned up ${result.orphanedCleaned} orphaned content hash(es)`);
  485. }
  486. console.log("");
  487. }
  488. // Check if any documents need embedding (show once at end)
  489. const needsEmbedding = getHashesNeedingEmbedding(db);
  490. closeDb();
  491. console.log(`${c.green}✓ All collections updated.${c.reset}`);
  492. if (needsEmbedding > 0) {
  493. console.log(`\nRun 'qmd embed' to update embeddings (${needsEmbedding} unique hashes need vectors)`);
  494. }
  495. }
  496. /**
  497. * Detect which collection (if any) contains the given filesystem path.
  498. * Returns { collectionId, collectionName, relativePath } or null if not in any collection.
  499. */
  500. function detectCollectionFromPath(db, fsPath) {
  501. const realPath = getRealPath(fsPath);
  502. // Find collections that this path is under from YAML
  503. const allCollections = yamlListCollections();
  504. // Find longest matching path
  505. let bestMatch = null;
  506. for (const coll of allCollections) {
  507. if (realPath.startsWith(coll.path + '/') || realPath === coll.path) {
  508. if (!bestMatch || coll.path.length > bestMatch.path.length) {
  509. bestMatch = { name: coll.name, path: coll.path };
  510. }
  511. }
  512. }
  513. if (!bestMatch)
  514. return null;
  515. // Calculate relative path
  516. let relativePath = realPath;
  517. if (relativePath.startsWith(bestMatch.path + '/')) {
  518. relativePath = relativePath.slice(bestMatch.path.length + 1);
  519. }
  520. else if (relativePath === bestMatch.path) {
  521. relativePath = '';
  522. }
  523. return {
  524. collectionName: bestMatch.name,
  525. relativePath
  526. };
  527. }
  528. async function contextAdd(pathArg, contextText) {
  529. const db = getDb();
  530. // Handle "/" as global context (applies to all collections)
  531. if (pathArg === '/') {
  532. setGlobalContext(contextText);
  533. resyncConfig();
  534. console.log(`${c.green}✓${c.reset} Set global context`);
  535. console.log(`${c.dim}Context: ${contextText}${c.reset}`);
  536. closeDb();
  537. return;
  538. }
  539. // Resolve path - defaults to current directory if not provided
  540. let fsPath = pathArg || '.';
  541. if (fsPath === '.' || fsPath === './') {
  542. fsPath = getPwd();
  543. }
  544. else if (fsPath.startsWith('~/')) {
  545. fsPath = homedir() + fsPath.slice(1);
  546. }
  547. else if (!fsPath.startsWith('/') && !fsPath.startsWith('qmd://')) {
  548. fsPath = resolve(getPwd(), fsPath);
  549. }
  550. // Handle virtual paths (qmd://collection/path)
  551. if (isVirtualPath(fsPath)) {
  552. const parsed = parseVirtualPath(fsPath);
  553. if (!parsed) {
  554. console.error(`${c.yellow}Invalid virtual path: ${fsPath}${c.reset}`);
  555. process.exit(1);
  556. }
  557. const coll = getCollectionFromYaml(parsed.collectionName);
  558. if (!coll) {
  559. console.error(`${c.yellow}Collection not found: ${parsed.collectionName}${c.reset}`);
  560. process.exit(1);
  561. }
  562. yamlAddContext(parsed.collectionName, parsed.path, contextText);
  563. resyncConfig();
  564. const displayPath = parsed.path
  565. ? `qmd://${parsed.collectionName}/${parsed.path}`
  566. : `qmd://${parsed.collectionName}/ (collection root)`;
  567. console.log(`${c.green}✓${c.reset} Added context for: ${displayPath}`);
  568. console.log(`${c.dim}Context: ${contextText}${c.reset}`);
  569. closeDb();
  570. return;
  571. }
  572. // Detect collection from filesystem path
  573. const detected = detectCollectionFromPath(db, fsPath);
  574. if (!detected) {
  575. console.error(`${c.yellow}Path is not in any indexed collection: ${fsPath}${c.reset}`);
  576. console.error(`${c.dim}Run 'qmd status' to see indexed collections${c.reset}`);
  577. process.exit(1);
  578. }
  579. yamlAddContext(detected.collectionName, detected.relativePath, contextText);
  580. resyncConfig();
  581. const displayPath = detected.relativePath ? `qmd://${detected.collectionName}/${detected.relativePath}` : `qmd://${detected.collectionName}/`;
  582. console.log(`${c.green}✓${c.reset} Added context for: ${displayPath}`);
  583. console.log(`${c.dim}Context: ${contextText}${c.reset}`);
  584. closeDb();
  585. }
  586. function contextList() {
  587. const db = getDb();
  588. const allContexts = listAllContexts();
  589. if (allContexts.length === 0) {
  590. console.log(`${c.dim}No contexts configured. Use 'qmd context add' to add one.${c.reset}`);
  591. closeDb();
  592. return;
  593. }
  594. console.log(`\n${c.bold}Configured Contexts${c.reset}\n`);
  595. let lastCollection = '';
  596. for (const ctx of allContexts) {
  597. if (ctx.collection !== lastCollection) {
  598. console.log(`${c.cyan}${ctx.collection}${c.reset}`);
  599. lastCollection = ctx.collection;
  600. }
  601. const displayPath = ctx.path ? ` ${ctx.path}` : ' / (root)';
  602. console.log(`${displayPath}`);
  603. console.log(` ${c.dim}${ctx.context}${c.reset}`);
  604. }
  605. closeDb();
  606. }
  607. function contextRemove(pathArg) {
  608. if (pathArg === '/') {
  609. // Remove global context
  610. setGlobalContext(undefined);
  611. // Resync so SQLite store_config is updated
  612. const s = getStore();
  613. resyncConfig();
  614. closeDb();
  615. console.log(`${c.green}✓${c.reset} Removed global context`);
  616. return;
  617. }
  618. // Handle virtual paths
  619. if (isVirtualPath(pathArg)) {
  620. const parsed = parseVirtualPath(pathArg);
  621. if (!parsed) {
  622. console.error(`${c.yellow}Invalid virtual path: ${pathArg}${c.reset}`);
  623. process.exit(1);
  624. }
  625. const coll = getCollectionFromYaml(parsed.collectionName);
  626. if (!coll) {
  627. console.error(`${c.yellow}Collection not found: ${parsed.collectionName}${c.reset}`);
  628. process.exit(1);
  629. }
  630. const success = yamlRemoveContext(coll.name, parsed.path);
  631. if (!success) {
  632. console.error(`${c.yellow}No context found for: ${pathArg}${c.reset}`);
  633. process.exit(1);
  634. }
  635. console.log(`${c.green}✓${c.reset} Removed context for: ${pathArg}`);
  636. return;
  637. }
  638. // Handle filesystem paths
  639. let fsPath = pathArg;
  640. if (fsPath === '.' || fsPath === './') {
  641. fsPath = getPwd();
  642. }
  643. else if (fsPath.startsWith('~/')) {
  644. fsPath = homedir() + fsPath.slice(1);
  645. }
  646. else if (!fsPath.startsWith('/')) {
  647. fsPath = resolve(getPwd(), fsPath);
  648. }
  649. const db = getDb();
  650. const detected = detectCollectionFromPath(db, fsPath);
  651. closeDb();
  652. if (!detected) {
  653. console.error(`${c.yellow}Path is not in any indexed collection: ${fsPath}${c.reset}`);
  654. process.exit(1);
  655. }
  656. const success = yamlRemoveContext(detected.collectionName, detected.relativePath);
  657. if (!success) {
  658. console.error(`${c.yellow}No context found for: qmd://${detected.collectionName}/${detected.relativePath}${c.reset}`);
  659. process.exit(1);
  660. }
  661. console.log(`${c.green}✓${c.reset} Removed context for: qmd://${detected.collectionName}/${detected.relativePath}`);
  662. }
  663. function getDocument(filename, fromLine, maxLines, lineNumbers) {
  664. const db = getDb();
  665. // Parse :linenum suffix from filename (e.g., "file.md:100")
  666. let inputPath = filename;
  667. const colonMatch = inputPath.match(/:(\d+)$/);
  668. if (colonMatch && !fromLine) {
  669. const matched = colonMatch[1];
  670. if (matched) {
  671. fromLine = parseInt(matched, 10);
  672. inputPath = inputPath.slice(0, -colonMatch[0].length);
  673. }
  674. }
  675. // Handle docid lookup (#abc123, abc123, "#abc123", "abc123", etc.)
  676. if (isDocid(inputPath)) {
  677. const docidMatch = findDocumentByDocid(db, inputPath);
  678. if (docidMatch) {
  679. inputPath = docidMatch.filepath;
  680. }
  681. else {
  682. console.error(`Document not found: ${filename}`);
  683. closeDb();
  684. process.exit(1);
  685. }
  686. }
  687. let doc = null;
  688. let virtualPath;
  689. // Handle virtual paths (qmd://collection/path)
  690. if (isVirtualPath(inputPath)) {
  691. const parsed = parseVirtualPath(inputPath);
  692. if (!parsed) {
  693. console.error(`Invalid virtual path: ${inputPath}`);
  694. closeDb();
  695. process.exit(1);
  696. }
  697. // Try exact match on collection + path
  698. doc = db.prepare(`
  699. SELECT d.collection as collectionName, d.path, content.doc as body
  700. FROM documents d
  701. JOIN content ON content.hash = d.hash
  702. WHERE d.collection = ? AND d.path = ? AND d.active = 1
  703. `).get(parsed.collectionName, parsed.path);
  704. if (!doc) {
  705. // Try fuzzy match by path ending
  706. doc = db.prepare(`
  707. SELECT d.collection as collectionName, d.path, content.doc as body
  708. FROM documents d
  709. JOIN content ON content.hash = d.hash
  710. WHERE d.collection = ? AND d.path LIKE ? AND d.active = 1
  711. LIMIT 1
  712. `).get(parsed.collectionName, `%${parsed.path}`);
  713. }
  714. virtualPath = inputPath;
  715. }
  716. else {
  717. // Try to interpret as collection/path format first (before filesystem path)
  718. // If path is relative (no / or ~ prefix), check if first component is a collection name
  719. if (!inputPath.startsWith('/') && !inputPath.startsWith('~')) {
  720. const parts = inputPath.split('/');
  721. if (parts.length >= 2) {
  722. const possibleCollection = parts[0];
  723. const possiblePath = parts.slice(1).join('/');
  724. // Check if this collection exists
  725. const collExists = possibleCollection ? db.prepare(`
  726. SELECT 1 FROM documents WHERE collection = ? AND active = 1 LIMIT 1
  727. `).get(possibleCollection) : null;
  728. if (collExists) {
  729. // Try exact match on collection + path
  730. doc = db.prepare(`
  731. SELECT d.collection as collectionName, d.path, content.doc as body
  732. FROM documents d
  733. JOIN content ON content.hash = d.hash
  734. WHERE d.collection = ? AND d.path = ? AND d.active = 1
  735. `).get(possibleCollection || "", possiblePath || "");
  736. if (!doc) {
  737. // Try fuzzy match by path ending
  738. doc = db.prepare(`
  739. SELECT d.collection as collectionName, d.path, content.doc as body
  740. FROM documents d
  741. JOIN content ON content.hash = d.hash
  742. WHERE d.collection = ? AND d.path LIKE ? AND d.active = 1
  743. LIMIT 1
  744. `).get(possibleCollection || "", `%${possiblePath}`);
  745. }
  746. if (doc) {
  747. virtualPath = buildVirtualPath(doc.collectionName, doc.path);
  748. // Skip the filesystem path handling below
  749. }
  750. }
  751. }
  752. }
  753. // If not found as collection/path, handle as filesystem paths
  754. if (!doc) {
  755. let fsPath = inputPath;
  756. // Expand ~ to home directory
  757. if (fsPath.startsWith('~/')) {
  758. fsPath = homedir() + fsPath.slice(1);
  759. }
  760. else if (!fsPath.startsWith('/')) {
  761. // Relative path - resolve from current directory
  762. fsPath = resolve(getPwd(), fsPath);
  763. }
  764. fsPath = getRealPath(fsPath);
  765. // Try to detect which collection contains this path
  766. const detected = detectCollectionFromPath(db, fsPath);
  767. if (detected) {
  768. // Found collection - query by collection name + relative path
  769. doc = db.prepare(`
  770. SELECT d.collection as collectionName, d.path, content.doc as body
  771. FROM documents d
  772. JOIN content ON content.hash = d.hash
  773. WHERE d.collection = ? AND d.path = ? AND d.active = 1
  774. `).get(detected.collectionName, detected.relativePath);
  775. }
  776. // Fuzzy match by filename (last component of path)
  777. if (!doc) {
  778. const filename = inputPath.split('/').pop() || inputPath;
  779. doc = db.prepare(`
  780. SELECT d.collection as collectionName, d.path, content.doc as body
  781. FROM documents d
  782. JOIN content ON content.hash = d.hash
  783. WHERE d.path LIKE ? AND d.active = 1
  784. LIMIT 1
  785. `).get(`%${filename}`);
  786. }
  787. if (doc) {
  788. virtualPath = buildVirtualPath(doc.collectionName, doc.path);
  789. }
  790. else {
  791. virtualPath = inputPath;
  792. }
  793. }
  794. }
  795. // Ensure doc is not null before proceeding
  796. if (!doc) {
  797. console.error(`Document not found: ${filename}`);
  798. closeDb();
  799. process.exit(1);
  800. }
  801. // Get context for this file
  802. const context = getContextForPath(db, doc.collectionName, doc.path);
  803. let output = doc.body;
  804. const startLine = fromLine || 1;
  805. // Apply line filtering if specified
  806. if (fromLine !== undefined || maxLines !== undefined) {
  807. const lines = output.split('\n');
  808. const start = startLine - 1; // Convert to 0-indexed
  809. const end = maxLines !== undefined ? start + maxLines : lines.length;
  810. output = lines.slice(start, end).join('\n');
  811. }
  812. // Add line numbers if requested
  813. if (lineNumbers) {
  814. output = addLineNumbers(output, startLine);
  815. }
  816. // Output context header if exists
  817. if (context) {
  818. console.log(`Folder Context: ${context}\n---\n`);
  819. }
  820. console.log(output);
  821. closeDb();
  822. }
  823. // Multi-get: fetch multiple documents by glob pattern or comma-separated list
  824. function multiGet(pattern, maxLines, maxBytes = DEFAULT_MULTI_GET_MAX_BYTES, format = "cli") {
  825. const db = getDb();
  826. // Check if it's a comma-separated list or a glob pattern
  827. const isCommaSeparated = pattern.includes(',') && !pattern.includes('*') && !pattern.includes('?') && !pattern.includes('{');
  828. let files;
  829. if (isCommaSeparated) {
  830. // Comma-separated list of files (can be virtual paths or relative paths)
  831. const names = pattern.split(',').map(s => s.trim()).filter(Boolean);
  832. files = [];
  833. for (const name of names) {
  834. let doc = null;
  835. // Handle virtual paths
  836. if (isVirtualPath(name)) {
  837. const parsed = parseVirtualPath(name);
  838. if (parsed) {
  839. // Try exact match on collection + path
  840. doc = db.prepare(`
  841. SELECT
  842. 'qmd://' || d.collection || '/' || d.path as virtual_path,
  843. LENGTH(content.doc) as body_length,
  844. d.collection,
  845. d.path
  846. FROM documents d
  847. JOIN content ON content.hash = d.hash
  848. WHERE d.collection = ? AND d.path = ? AND d.active = 1
  849. `).get(parsed.collectionName, parsed.path);
  850. }
  851. }
  852. else {
  853. // Try exact match on path
  854. doc = db.prepare(`
  855. SELECT
  856. 'qmd://' || d.collection || '/' || d.path as virtual_path,
  857. LENGTH(content.doc) as body_length,
  858. d.collection,
  859. d.path
  860. FROM documents d
  861. JOIN content ON content.hash = d.hash
  862. WHERE d.path = ? AND d.active = 1
  863. LIMIT 1
  864. `).get(name);
  865. // Try suffix match
  866. if (!doc) {
  867. doc = db.prepare(`
  868. SELECT
  869. 'qmd://' || d.collection || '/' || d.path as virtual_path,
  870. LENGTH(content.doc) as body_length,
  871. d.collection,
  872. d.path
  873. FROM documents d
  874. JOIN content ON content.hash = d.hash
  875. WHERE d.path LIKE ? AND d.active = 1
  876. LIMIT 1
  877. `).get(`%${name}`);
  878. }
  879. }
  880. if (doc) {
  881. files.push({
  882. filepath: doc.virtual_path,
  883. displayPath: doc.virtual_path,
  884. bodyLength: doc.body_length,
  885. collection: doc.collection,
  886. path: doc.path
  887. });
  888. }
  889. else {
  890. console.error(`File not found: ${name}`);
  891. }
  892. }
  893. }
  894. else {
  895. // Glob pattern - matchFilesByGlob now returns virtual paths
  896. files = matchFilesByGlob(db, pattern).map(f => ({
  897. ...f,
  898. collection: undefined, // Will be fetched later if needed
  899. path: undefined
  900. }));
  901. if (files.length === 0) {
  902. console.error(`No files matched pattern: ${pattern}`);
  903. closeDb();
  904. process.exit(1);
  905. }
  906. }
  907. // Collect results for structured output
  908. const results = [];
  909. for (const file of files) {
  910. // Parse virtual path to get collection info if not already available
  911. let collection = file.collection;
  912. let path = file.path;
  913. if (!collection || !path) {
  914. const parsed = parseVirtualPath(file.filepath);
  915. if (parsed) {
  916. collection = parsed.collectionName;
  917. path = parsed.path;
  918. }
  919. }
  920. // Get context using collection-scoped function
  921. const context = collection && path ? getContextForPath(db, collection, path) : null;
  922. // Check size limit
  923. if (file.bodyLength > maxBytes) {
  924. results.push({
  925. file: file.filepath,
  926. displayPath: file.displayPath,
  927. title: file.displayPath.split('/').pop() || file.displayPath,
  928. body: "",
  929. context,
  930. skipped: true,
  931. skipReason: `File too large (${Math.round(file.bodyLength / 1024)}KB > ${Math.round(maxBytes / 1024)}KB). Use 'qmd get ${file.displayPath}' to retrieve.`,
  932. });
  933. continue;
  934. }
  935. // Fetch document content using collection and path
  936. if (!collection || !path)
  937. continue;
  938. const doc = db.prepare(`
  939. SELECT content.doc as body, d.title
  940. FROM documents d
  941. JOIN content ON content.hash = d.hash
  942. WHERE d.collection = ? AND d.path = ? AND d.active = 1
  943. `).get(collection, path);
  944. if (!doc)
  945. continue;
  946. let body = doc.body;
  947. // Apply line limit if specified
  948. if (maxLines !== undefined) {
  949. const lines = body.split('\n');
  950. body = lines.slice(0, maxLines).join('\n');
  951. if (lines.length > maxLines) {
  952. body += `\n\n[... truncated ${lines.length - maxLines} more lines]`;
  953. }
  954. }
  955. results.push({
  956. file: file.filepath,
  957. displayPath: file.displayPath,
  958. title: doc.title || file.displayPath.split('/').pop() || file.displayPath,
  959. body,
  960. context,
  961. skipped: false,
  962. });
  963. }
  964. closeDb();
  965. // Output based on format
  966. if (format === "json") {
  967. const output = results.map(r => ({
  968. file: r.displayPath,
  969. title: r.title,
  970. ...(r.context && { context: r.context }),
  971. ...(r.skipped ? { skipped: true, reason: r.skipReason } : { body: r.body }),
  972. }));
  973. console.log(JSON.stringify(output, null, 2));
  974. }
  975. else if (format === "csv") {
  976. const escapeField = (val) => {
  977. if (val === null || val === undefined)
  978. return "";
  979. const str = String(val);
  980. if (str.includes(",") || str.includes('"') || str.includes("\n")) {
  981. return `"${str.replace(/"/g, '""')}"`;
  982. }
  983. return str;
  984. };
  985. console.log("file,title,context,skipped,body");
  986. for (const r of results) {
  987. console.log([r.displayPath, r.title, r.context, r.skipped ? "true" : "false", r.skipped ? r.skipReason : r.body].map(escapeField).join(","));
  988. }
  989. }
  990. else if (format === "files") {
  991. for (const r of results) {
  992. const ctx = r.context ? `,"${r.context.replace(/"/g, '""')}"` : "";
  993. const status = r.skipped ? "[SKIPPED]" : "";
  994. console.log(`${r.displayPath}${ctx}${status ? `,${status}` : ""}`);
  995. }
  996. }
  997. else if (format === "md") {
  998. for (const r of results) {
  999. console.log(`## ${r.displayPath}\n`);
  1000. if (r.title && r.title !== r.displayPath)
  1001. console.log(`**Title:** ${r.title}\n`);
  1002. if (r.context)
  1003. console.log(`**Context:** ${r.context}\n`);
  1004. if (r.skipped) {
  1005. console.log(`> ${r.skipReason}\n`);
  1006. }
  1007. else {
  1008. console.log("```");
  1009. console.log(r.body);
  1010. console.log("```\n");
  1011. }
  1012. }
  1013. }
  1014. else if (format === "xml") {
  1015. console.log('<?xml version="1.0" encoding="UTF-8"?>');
  1016. console.log("<documents>");
  1017. for (const r of results) {
  1018. console.log(" <document>");
  1019. console.log(` <file>${escapeXml(r.displayPath)}</file>`);
  1020. console.log(` <title>${escapeXml(r.title)}</title>`);
  1021. if (r.context)
  1022. console.log(` <context>${escapeXml(r.context)}</context>`);
  1023. if (r.skipped) {
  1024. console.log(` <skipped>true</skipped>`);
  1025. console.log(` <reason>${escapeXml(r.skipReason || "")}</reason>`);
  1026. }
  1027. else {
  1028. console.log(` <body>${escapeXml(r.body)}</body>`);
  1029. }
  1030. console.log(" </document>");
  1031. }
  1032. console.log("</documents>");
  1033. }
  1034. else {
  1035. // CLI format (default)
  1036. for (const r of results) {
  1037. console.log(`\n${'='.repeat(60)}`);
  1038. console.log(`File: ${r.displayPath}`);
  1039. console.log(`${'='.repeat(60)}\n`);
  1040. if (r.skipped) {
  1041. console.log(`[SKIPPED: ${r.skipReason}]`);
  1042. continue;
  1043. }
  1044. if (r.context) {
  1045. console.log(`Folder Context: ${r.context}\n---\n`);
  1046. }
  1047. console.log(r.body);
  1048. }
  1049. }
  1050. }
  1051. // List files in virtual file tree
  1052. function listFiles(pathArg) {
  1053. const db = getDb();
  1054. if (!pathArg) {
  1055. // No argument - list all collections
  1056. const yamlCollections = yamlListCollections();
  1057. if (yamlCollections.length === 0) {
  1058. console.log("No collections found. Run 'qmd collection add .' to index files.");
  1059. closeDb();
  1060. return;
  1061. }
  1062. // Get file counts from database for each collection
  1063. const collections = yamlCollections.map(coll => {
  1064. const stats = db.prepare(`
  1065. SELECT COUNT(*) as file_count
  1066. FROM documents d
  1067. WHERE d.collection = ? AND d.active = 1
  1068. `).get(coll.name);
  1069. return {
  1070. name: coll.name,
  1071. file_count: stats?.file_count || 0
  1072. };
  1073. });
  1074. console.log(`${c.bold}Collections:${c.reset}\n`);
  1075. for (const coll of collections) {
  1076. console.log(` ${c.dim}qmd://${c.reset}${c.cyan}${coll.name}/${c.reset} ${c.dim}(${coll.file_count} files)${c.reset}`);
  1077. }
  1078. closeDb();
  1079. return;
  1080. }
  1081. // Parse the path argument
  1082. let collectionName;
  1083. let pathPrefix = null;
  1084. if (pathArg.startsWith('qmd://')) {
  1085. // Virtual path format: qmd://collection/path
  1086. const parsed = parseVirtualPath(pathArg);
  1087. if (!parsed) {
  1088. console.error(`Invalid virtual path: ${pathArg}`);
  1089. closeDb();
  1090. process.exit(1);
  1091. }
  1092. collectionName = parsed.collectionName;
  1093. pathPrefix = parsed.path;
  1094. }
  1095. else {
  1096. // Just collection name or collection/path
  1097. const parts = pathArg.split('/');
  1098. collectionName = parts[0] || '';
  1099. if (parts.length > 1) {
  1100. pathPrefix = parts.slice(1).join('/');
  1101. }
  1102. }
  1103. // Get the collection
  1104. const coll = getCollectionFromYaml(collectionName);
  1105. if (!coll) {
  1106. console.error(`Collection not found: ${collectionName}`);
  1107. console.error(`Run 'qmd ls' to see available collections.`);
  1108. closeDb();
  1109. process.exit(1);
  1110. }
  1111. // List files in the collection with size and modification time
  1112. let query;
  1113. let params;
  1114. if (pathPrefix) {
  1115. // List files under a specific path
  1116. query = `
  1117. SELECT d.path, d.title, d.modified_at, LENGTH(ct.doc) as size
  1118. FROM documents d
  1119. JOIN content ct ON d.hash = ct.hash
  1120. WHERE d.collection = ? AND d.path LIKE ? AND d.active = 1
  1121. ORDER BY d.path
  1122. `;
  1123. params = [coll.name, `${pathPrefix}%`];
  1124. }
  1125. else {
  1126. // List all files in the collection
  1127. query = `
  1128. SELECT d.path, d.title, d.modified_at, LENGTH(ct.doc) as size
  1129. FROM documents d
  1130. JOIN content ct ON d.hash = ct.hash
  1131. WHERE d.collection = ? AND d.active = 1
  1132. ORDER BY d.path
  1133. `;
  1134. params = [coll.name];
  1135. }
  1136. const files = db.prepare(query).all(...params);
  1137. if (files.length === 0) {
  1138. if (pathPrefix) {
  1139. console.log(`No files found under qmd://${collectionName}/${pathPrefix}`);
  1140. }
  1141. else {
  1142. console.log(`No files found in collection: ${collectionName}`);
  1143. }
  1144. closeDb();
  1145. return;
  1146. }
  1147. // Calculate max widths for alignment
  1148. const maxSize = Math.max(...files.map(f => formatBytes(f.size).length));
  1149. // Output in ls -l style
  1150. for (const file of files) {
  1151. const sizeStr = formatBytes(file.size).padStart(maxSize);
  1152. const date = new Date(file.modified_at);
  1153. const timeStr = formatLsTime(date);
  1154. // Dim the qmd:// prefix, highlight the filename
  1155. console.log(`${sizeStr} ${timeStr} ${c.dim}qmd://${collectionName}/${c.reset}${c.cyan}${file.path}${c.reset}`);
  1156. }
  1157. closeDb();
  1158. }
  1159. // Format date/time like ls -l
  1160. function formatLsTime(date) {
  1161. const now = new Date();
  1162. const sixMonthsAgo = new Date(now.getTime() - 6 * 30 * 24 * 60 * 60 * 1000);
  1163. const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  1164. const month = months[date.getMonth()];
  1165. const day = date.getDate().toString().padStart(2, ' ');
  1166. // If file is older than 6 months, show year instead of time
  1167. if (date < sixMonthsAgo) {
  1168. const year = date.getFullYear();
  1169. return `${month} ${day} ${year}`;
  1170. }
  1171. else {
  1172. const hours = date.getHours().toString().padStart(2, '0');
  1173. const minutes = date.getMinutes().toString().padStart(2, '0');
  1174. return `${month} ${day} ${hours}:${minutes}`;
  1175. }
  1176. }
  1177. // Collection management commands
  1178. function collectionList() {
  1179. const db = getDb();
  1180. const collections = listCollections(db);
  1181. if (collections.length === 0) {
  1182. console.log("No collections found. Run 'qmd collection add .' to create one.");
  1183. closeDb();
  1184. return;
  1185. }
  1186. console.log(`${c.bold}Collections (${collections.length}):${c.reset}\n`);
  1187. for (const coll of collections) {
  1188. const updatedAt = coll.last_modified ? new Date(coll.last_modified) : new Date();
  1189. const timeAgo = formatTimeAgo(updatedAt);
  1190. // Get YAML config to check includeByDefault
  1191. const yamlColl = getCollectionFromYaml(coll.name);
  1192. const excluded = yamlColl?.includeByDefault === false;
  1193. const excludeTag = excluded ? ` ${c.yellow}[excluded]${c.reset}` : '';
  1194. console.log(`${c.cyan}${coll.name}${c.reset} ${c.dim}(qmd://${coll.name}/)${c.reset}${excludeTag}`);
  1195. console.log(` ${c.dim}Pattern:${c.reset} ${coll.glob_pattern}`);
  1196. if (yamlColl?.ignore?.length) {
  1197. console.log(` ${c.dim}Ignore:${c.reset} ${yamlColl.ignore.join(', ')}`);
  1198. }
  1199. console.log(` ${c.dim}Files:${c.reset} ${coll.active_count}`);
  1200. console.log(` ${c.dim}Updated:${c.reset} ${timeAgo}`);
  1201. console.log();
  1202. }
  1203. closeDb();
  1204. }
  1205. async function collectionAdd(pwd, globPattern, name) {
  1206. // If name not provided, generate from pwd basename
  1207. let collName = name;
  1208. if (!collName) {
  1209. const parts = pwd.split('/').filter(Boolean);
  1210. collName = parts[parts.length - 1] || 'root';
  1211. }
  1212. // Check if collection with this name already exists in YAML
  1213. const existing = getCollectionFromYaml(collName);
  1214. if (existing) {
  1215. console.error(`${c.yellow}Collection '${collName}' already exists.${c.reset}`);
  1216. console.error(`Use a different name with --name <name>`);
  1217. process.exit(1);
  1218. }
  1219. // Check if a collection with this pwd+glob already exists in YAML
  1220. const allCollections = yamlListCollections();
  1221. const existingPwdGlob = allCollections.find(c => c.path === pwd && c.pattern === globPattern);
  1222. if (existingPwdGlob) {
  1223. console.error(`${c.yellow}A collection already exists for this path and pattern:${c.reset}`);
  1224. console.error(` Name: ${existingPwdGlob.name} (qmd://${existingPwdGlob.name}/)`);
  1225. console.error(` Pattern: ${globPattern}`);
  1226. console.error(`\nUse 'qmd update' to re-index it, or remove it first with 'qmd collection remove ${existingPwdGlob.name}'`);
  1227. process.exit(1);
  1228. }
  1229. // Add to YAML config + sync to SQLite
  1230. const { addCollection } = await import("../collections.js");
  1231. addCollection(collName, pwd, globPattern);
  1232. resyncConfig();
  1233. // Create the collection and index files
  1234. console.log(`Creating collection '${collName}'...`);
  1235. const newColl = getCollectionFromYaml(collName);
  1236. await indexFiles(pwd, globPattern, collName, false, newColl?.ignore);
  1237. console.log(`${c.green}✓${c.reset} Collection '${collName}' created successfully`);
  1238. }
  1239. function collectionRemove(name) {
  1240. // Check if collection exists in YAML
  1241. const coll = getCollectionFromYaml(name);
  1242. if (!coll) {
  1243. console.error(`${c.yellow}Collection not found: ${name}${c.reset}`);
  1244. console.error(`Run 'qmd collection list' to see available collections.`);
  1245. process.exit(1);
  1246. }
  1247. const db = getDb();
  1248. const result = removeCollection(db, name);
  1249. // Also remove from YAML config
  1250. yamlRemoveCollectionFn(name);
  1251. closeDb();
  1252. console.log(`${c.green}✓${c.reset} Removed collection '${name}'`);
  1253. console.log(` Deleted ${result.deletedDocs} documents`);
  1254. if (result.cleanedHashes > 0) {
  1255. console.log(` Cleaned up ${result.cleanedHashes} orphaned content hashes`);
  1256. }
  1257. }
  1258. function collectionRename(oldName, newName) {
  1259. // Check if old collection exists in YAML
  1260. const coll = getCollectionFromYaml(oldName);
  1261. if (!coll) {
  1262. console.error(`${c.yellow}Collection not found: ${oldName}${c.reset}`);
  1263. console.error(`Run 'qmd collection list' to see available collections.`);
  1264. process.exit(1);
  1265. }
  1266. // Check if new name already exists in YAML
  1267. const existing = getCollectionFromYaml(newName);
  1268. if (existing) {
  1269. console.error(`${c.yellow}Collection name already exists: ${newName}${c.reset}`);
  1270. console.error(`Choose a different name or remove the existing collection first.`);
  1271. process.exit(1);
  1272. }
  1273. const db = getDb();
  1274. renameCollection(db, oldName, newName);
  1275. // Also rename in YAML config
  1276. yamlRenameCollectionFn(oldName, newName);
  1277. closeDb();
  1278. console.log(`${c.green}✓${c.reset} Renamed collection '${oldName}' to '${newName}'`);
  1279. console.log(` Virtual paths updated: ${c.cyan}qmd://${oldName}/${c.reset} → ${c.cyan}qmd://${newName}/${c.reset}`);
  1280. }
  1281. async function indexFiles(pwd, globPattern = DEFAULT_GLOB, collectionName, suppressEmbedNotice = false, ignorePatterns) {
  1282. const db = getDb();
  1283. const resolvedPwd = pwd || getPwd();
  1284. const now = new Date().toISOString();
  1285. const excludeDirs = ["node_modules", ".git", ".cache", "vendor", "dist", "build"];
  1286. // Clear Ollama cache on index
  1287. clearCache(db);
  1288. // Collection name must be provided (from YAML)
  1289. if (!collectionName) {
  1290. throw new Error("Collection name is required. Collections must be defined in ~/.config/qmd/index.yml");
  1291. }
  1292. console.log(`Collection: ${resolvedPwd} (${globPattern})`);
  1293. progress.indeterminate();
  1294. const allIgnore = [
  1295. ...excludeDirs.map(d => `**/${d}/**`),
  1296. ...(ignorePatterns || []),
  1297. ];
  1298. const allFiles = await fastGlob(globPattern, {
  1299. cwd: resolvedPwd,
  1300. onlyFiles: true,
  1301. followSymbolicLinks: false,
  1302. dot: false,
  1303. ignore: allIgnore,
  1304. });
  1305. // Filter hidden files/folders (dot: false handles top-level but not nested)
  1306. const files = allFiles.filter(file => {
  1307. const parts = file.split("/");
  1308. return !parts.some(part => part.startsWith("."));
  1309. });
  1310. const total = files.length;
  1311. const hasNoFiles = total === 0;
  1312. if (hasNoFiles) {
  1313. progress.clear();
  1314. console.log("No files found matching pattern.");
  1315. // Continue so the deactivation pass can mark previously indexed docs as inactive.
  1316. }
  1317. let indexed = 0, updated = 0, unchanged = 0, processed = 0;
  1318. const seenPaths = new Set();
  1319. const startTime = Date.now();
  1320. for (const relativeFile of files) {
  1321. const filepath = getRealPath(resolve(resolvedPwd, relativeFile));
  1322. const path = handelize(relativeFile); // Normalize path for token-friendliness
  1323. seenPaths.add(path);
  1324. let content;
  1325. try {
  1326. content = readFileSync(filepath, "utf-8");
  1327. }
  1328. catch (err) {
  1329. // Skip files that can't be read (e.g. iCloud evicted files returning EAGAIN)
  1330. processed++;
  1331. progress.set((processed / total) * 100);
  1332. continue;
  1333. }
  1334. // Skip empty files - nothing useful to index
  1335. if (!content.trim()) {
  1336. processed++;
  1337. continue;
  1338. }
  1339. const hash = await hashContent(content);
  1340. const title = extractTitle(content, relativeFile);
  1341. // Check if document exists in this collection with this path
  1342. const existing = findActiveDocument(db, collectionName, path);
  1343. if (existing) {
  1344. if (existing.hash === hash) {
  1345. // Hash unchanged, but check if title needs updating
  1346. if (existing.title !== title) {
  1347. updateDocumentTitle(db, existing.id, title, now);
  1348. updated++;
  1349. }
  1350. else {
  1351. unchanged++;
  1352. }
  1353. }
  1354. else {
  1355. // Content changed - insert new content hash and update document
  1356. insertContent(db, hash, content, now);
  1357. const stat = statSync(filepath);
  1358. updateDocument(db, existing.id, title, hash, stat ? new Date(stat.mtime).toISOString() : now);
  1359. updated++;
  1360. }
  1361. }
  1362. else {
  1363. // New document - insert content and document
  1364. indexed++;
  1365. insertContent(db, hash, content, now);
  1366. const stat = statSync(filepath);
  1367. insertDocument(db, collectionName, path, title, hash, stat ? new Date(stat.birthtime).toISOString() : now, stat ? new Date(stat.mtime).toISOString() : now);
  1368. }
  1369. processed++;
  1370. progress.set((processed / total) * 100);
  1371. const elapsed = (Date.now() - startTime) / 1000;
  1372. const rate = processed / elapsed;
  1373. const remaining = (total - processed) / rate;
  1374. const eta = processed > 2 ? ` ETA: ${formatETA(remaining)}` : "";
  1375. if (isTTY)
  1376. process.stderr.write(`\rIndexing: ${processed}/${total}${eta} `);
  1377. }
  1378. // Deactivate documents in this collection that no longer exist
  1379. const allActive = getActiveDocumentPaths(db, collectionName);
  1380. let removed = 0;
  1381. for (const path of allActive) {
  1382. if (!seenPaths.has(path)) {
  1383. deactivateDocument(db, collectionName, path);
  1384. removed++;
  1385. }
  1386. }
  1387. // Clean up orphaned content hashes (content not referenced by any document)
  1388. const orphanedContent = cleanupOrphanedContent(db);
  1389. // Check if vector index needs updating
  1390. const needsEmbedding = getHashesNeedingEmbedding(db);
  1391. progress.clear();
  1392. console.log(`\nIndexed: ${indexed} new, ${updated} updated, ${unchanged} unchanged, ${removed} removed`);
  1393. if (orphanedContent > 0) {
  1394. console.log(`Cleaned up ${orphanedContent} orphaned content hash(es)`);
  1395. }
  1396. if (needsEmbedding > 0 && !suppressEmbedNotice) {
  1397. console.log(`\nRun 'qmd embed' to update embeddings (${needsEmbedding} unique hashes need vectors)`);
  1398. }
  1399. closeDb();
  1400. }
  1401. function renderProgressBar(percent, width = 30) {
  1402. const filled = Math.round((percent / 100) * width);
  1403. const empty = width - filled;
  1404. const bar = "█".repeat(filled) + "░".repeat(empty);
  1405. return bar;
  1406. }
  1407. function parseEmbedBatchOption(name, value) {
  1408. if (value === undefined)
  1409. return undefined;
  1410. const parsed = Number(value);
  1411. if (!Number.isInteger(parsed) || parsed < 1) {
  1412. throw new Error(`${name} must be a positive integer`);
  1413. }
  1414. return parsed;
  1415. }
  1416. function parseChunkStrategy(value) {
  1417. if (value === undefined)
  1418. return undefined;
  1419. const s = String(value);
  1420. if (s === "auto" || s === "regex" || s === "function")
  1421. return s;
  1422. throw new Error(`--chunk-strategy must be "auto", "regex", or "function" (got "${s}")`);
  1423. }
  1424. function parseProviderKind(value) {
  1425. if (value === undefined)
  1426. return undefined;
  1427. const s = String(value).toLowerCase();
  1428. if (s === "local" || s === "openai")
  1429. return s;
  1430. throw new Error(`--provider must be "local" or "openai" (got "${s}")`);
  1431. }
  1432. function parseOptionalPositiveInt(name, value) {
  1433. if (value === undefined)
  1434. return undefined;
  1435. const parsed = Number(value);
  1436. if (!Number.isInteger(parsed) || parsed < 1) {
  1437. throw new Error(`${name} must be a positive integer`);
  1438. }
  1439. return parsed;
  1440. }
  1441. /**
  1442. * Translate `cli.values` into `CreateEmbeddingProviderOptions`. CLI flags
  1443. * win over env vars (the factory itself reads env when these are unset).
  1444. */
  1445. function buildProviderOpts(values, providerCliKind) {
  1446. const endpoint = optionalString(values["embed-endpoint"]);
  1447. const apiKey = optionalString(values["embed-api-key"]);
  1448. const modelId = optionalString(values["embed-model-id"]);
  1449. const upstreamModel = optionalString(values["embed-upstream-model"]);
  1450. const batchSize = parseOptionalPositiveInt("--embed-batch-size", values["embed-batch-size"]);
  1451. const timeoutMs = parseOptionalPositiveInt("--embed-timeout-ms", values["embed-timeout-ms"]);
  1452. // Only build the openai overrides object if the user supplied flags
  1453. const openai = endpoint || apiKey || modelId || upstreamModel || batchSize !== undefined || timeoutMs !== undefined
  1454. ? {
  1455. ...(endpoint !== undefined ? { endpoint } : {}),
  1456. ...(apiKey !== undefined ? { apiKey } : {}),
  1457. ...(modelId !== undefined ? { modelId } : {}),
  1458. ...(upstreamModel !== undefined ? { upstreamModel } : {}),
  1459. ...(batchSize !== undefined ? { batchSize } : {}),
  1460. ...(timeoutMs !== undefined ? { timeoutMs } : {}),
  1461. }
  1462. : undefined;
  1463. // CLI flag for auto-fallback wrapping (only meaningful when kind === openai)
  1464. const autoFallback = values["embed-auto-fallback"] === true ? true : undefined;
  1465. return {
  1466. ...(providerCliKind ? { kind: providerCliKind } : {}),
  1467. ...(openai ? { openai } : {}),
  1468. ...(autoFallback !== undefined ? { autoFallback } : {}),
  1469. };
  1470. }
  1471. function optionalString(v) {
  1472. if (v === undefined || v === null)
  1473. return undefined;
  1474. const s = String(v);
  1475. return s === "" ? undefined : s;
  1476. }
  1477. async function vectorIndex(model = DEFAULT_EMBED_MODEL_URI, force = false, batchOptions) {
  1478. const storeInstance = getStore();
  1479. const db = storeInstance.db;
  1480. if (force) {
  1481. console.log(`${c.yellow}Force re-indexing: clearing all vectors...${c.reset}`);
  1482. }
  1483. // Check if there's work to do before starting
  1484. const hashesToEmbed = getHashesNeedingEmbedding(db);
  1485. if (hashesToEmbed === 0 && !force) {
  1486. console.log(`${c.green}✓ All content hashes already have embeddings.${c.reset}`);
  1487. closeDb();
  1488. return;
  1489. }
  1490. console.log(`${c.dim}Model: ${model}${c.reset}\n`);
  1491. if (batchOptions?.embedProvider) {
  1492. const kind = batchOptions.embedProvider.kind;
  1493. const providerModel = batchOptions.embedProvider.getModelId();
  1494. console.log(`${c.dim}Provider: ${kind} (model id "${providerModel}")${c.reset}\n`);
  1495. }
  1496. else if (batchOptions?.providerKind) {
  1497. console.log(`${c.dim}Provider: ${batchOptions.providerKind}${c.reset}\n`);
  1498. }
  1499. if (batchOptions?.maxDocsPerBatch !== undefined || batchOptions?.maxBatchBytes !== undefined) {
  1500. const maxDocsPerBatch = batchOptions.maxDocsPerBatch ?? DEFAULT_EMBED_MAX_DOCS_PER_BATCH;
  1501. const maxBatchBytes = batchOptions.maxBatchBytes ?? DEFAULT_EMBED_MAX_BATCH_BYTES;
  1502. console.log(`${c.dim}Batch: ${maxDocsPerBatch} docs / ${formatBytes(maxBatchBytes)}${c.reset}\n`);
  1503. }
  1504. cursor.hide();
  1505. progress.indeterminate();
  1506. const startTime = Date.now();
  1507. const result = await generateEmbeddings(storeInstance, {
  1508. force,
  1509. model,
  1510. maxDocsPerBatch: batchOptions?.maxDocsPerBatch,
  1511. maxBatchBytes: batchOptions?.maxBatchBytes,
  1512. chunkStrategy: batchOptions?.chunkStrategy,
  1513. embedProvider: batchOptions?.embedProvider,
  1514. onProgress: (info) => {
  1515. if (info.totalBytes === 0)
  1516. return;
  1517. const percent = (info.bytesProcessed / info.totalBytes) * 100;
  1518. progress.set(percent);
  1519. const elapsed = (Date.now() - startTime) / 1000;
  1520. const bytesPerSec = info.bytesProcessed / elapsed;
  1521. const remainingBytes = info.totalBytes - info.bytesProcessed;
  1522. const etaSec = remainingBytes / bytesPerSec;
  1523. const bar = renderProgressBar(percent);
  1524. const percentStr = percent.toFixed(0).padStart(3);
  1525. const throughput = `${formatBytes(bytesPerSec)}/s`;
  1526. const eta = elapsed > 2 ? formatETA(etaSec) : "...";
  1527. const errStr = info.errors > 0 ? ` ${c.yellow}${info.errors} err${c.reset}` : "";
  1528. if (isTTY)
  1529. process.stderr.write(`\r${c.cyan}${bar}${c.reset} ${c.bold}${percentStr}%${c.reset} ${c.dim}${info.chunksEmbedded}/${info.totalChunks}${c.reset}${errStr} ${c.dim}${throughput} ETA ${eta}${c.reset} `);
  1530. },
  1531. });
  1532. progress.clear();
  1533. cursor.show();
  1534. const totalTimeSec = result.durationMs / 1000;
  1535. if (result.chunksEmbedded === 0 && result.docsProcessed === 0) {
  1536. console.log(`${c.green}✓ No non-empty documents to embed.${c.reset}`);
  1537. }
  1538. else {
  1539. console.log(`\r${c.green}${renderProgressBar(100)}${c.reset} ${c.bold}100%${c.reset} `);
  1540. console.log(`\n${c.green}✓ Done!${c.reset} Embedded ${c.bold}${result.chunksEmbedded}${c.reset} chunks from ${c.bold}${result.docsProcessed}${c.reset} documents in ${c.bold}${formatETA(totalTimeSec)}${c.reset}`);
  1541. if (result.errors > 0) {
  1542. console.log(`${c.yellow}⚠ ${result.errors} chunks failed${c.reset}`);
  1543. }
  1544. }
  1545. closeDb();
  1546. }
  1547. // Sanitize a term for FTS5: remove punctuation except apostrophes
  1548. function sanitizeFTS5Term(term) {
  1549. // Remove all non-alphanumeric except apostrophes (for contractions like "don't")
  1550. return term.replace(/[^\w']/g, '').trim();
  1551. }
  1552. // Build FTS5 query: phrase-aware with fallback to individual terms
  1553. function buildFTS5Query(query) {
  1554. // Sanitize the full query for phrase matching
  1555. const sanitizedQuery = query.replace(/[^\w\s']/g, '').trim();
  1556. const terms = query
  1557. .split(/\s+/)
  1558. .map(sanitizeFTS5Term)
  1559. .filter(term => term.length >= 2); // Skip single chars and empty
  1560. if (terms.length === 0)
  1561. return "";
  1562. if (terms.length === 1)
  1563. return `"${terms[0].replace(/"/g, '""')}"`;
  1564. // Strategy: exact phrase OR proximity match OR individual terms
  1565. // Exact phrase matches rank highest, then close proximity, then any term
  1566. const phrase = `"${sanitizedQuery.replace(/"/g, '""')}"`;
  1567. const quotedTerms = terms.map(t => `"${t.replace(/"/g, '""')}"`);
  1568. // FTS5 NEAR syntax: NEAR(term1 term2, distance)
  1569. const nearPhrase = `NEAR(${quotedTerms.join(' ')}, 10)`;
  1570. const orTerms = quotedTerms.join(' OR ');
  1571. // Exact phrase > proximity > any term
  1572. return `(${phrase}) OR (${nearPhrase}) OR (${orTerms})`;
  1573. }
  1574. // Normalize BM25 score to 0-1 range using sigmoid
  1575. function normalizeBM25(score) {
  1576. // BM25 scores are negative in SQLite (lower = better)
  1577. // Typical range: -15 (excellent) to -2 (weak match)
  1578. // Map to 0-1 where higher is better
  1579. const absScore = Math.abs(score);
  1580. // Sigmoid-ish normalization: maps ~2-15 range to ~0.1-0.95
  1581. return 1 / (1 + Math.exp(-(absScore - 5) / 3));
  1582. }
  1583. // Highlight query terms in text (skip short words < 3 chars)
  1584. function highlightTerms(text, query) {
  1585. if (!useColor)
  1586. return text;
  1587. const terms = query.toLowerCase().split(/\s+/).filter(t => t.length >= 3);
  1588. let result = text;
  1589. for (const term of terms) {
  1590. const regex = new RegExp(`(${term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
  1591. result = result.replace(regex, `${c.yellow}${c.bold}$1${c.reset}`);
  1592. }
  1593. return result;
  1594. }
  1595. // Format score with color based on value
  1596. function formatScore(score) {
  1597. const pct = (score * 100).toFixed(0).padStart(3);
  1598. if (!useColor)
  1599. return `${pct}%`;
  1600. if (score >= 0.7)
  1601. return `${c.green}${pct}%${c.reset}`;
  1602. if (score >= 0.4)
  1603. return `${c.yellow}${pct}%${c.reset}`;
  1604. return `${c.dim}${pct}%${c.reset}`;
  1605. }
  1606. function formatExplainNumber(value) {
  1607. return value.toFixed(4);
  1608. }
  1609. // Shorten directory path for display - relative to $HOME (used for context paths, not documents)
  1610. function shortPath(dirpath) {
  1611. const home = homedir();
  1612. if (dirpath.startsWith(home)) {
  1613. return '~' + dirpath.slice(home.length);
  1614. }
  1615. return dirpath;
  1616. }
  1617. // Emit format-safe empty output for search commands.
  1618. function printEmptySearchResults(format, reason = "no_results") {
  1619. if (format === "json") {
  1620. console.log("[]");
  1621. return;
  1622. }
  1623. if (format === "csv") {
  1624. console.log("docid,score,file,title,context,line,snippet");
  1625. return;
  1626. }
  1627. if (format === "xml") {
  1628. console.log("<results></results>");
  1629. return;
  1630. }
  1631. if (format === "md" || format === "files") {
  1632. return;
  1633. }
  1634. if (reason === "min_score") {
  1635. console.log("No results found above minimum score threshold.");
  1636. return;
  1637. }
  1638. console.log("No results found.");
  1639. }
  1640. const DEFAULT_EDITOR_URI_TEMPLATE = "vscode://file/{path}:{line}:{col}";
  1641. function encodePathForEditorUri(absolutePath) {
  1642. return encodeURI(absolutePath)
  1643. .replace(/\?/g, "%3F")
  1644. .replace(/#/g, "%23");
  1645. }
  1646. function getEditorUriTemplate() {
  1647. const envTemplate = process.env.QMD_EDITOR_URI?.trim();
  1648. if (envTemplate)
  1649. return envTemplate;
  1650. try {
  1651. const config = loadConfig();
  1652. const configTemplate = (config.editor_uri
  1653. || config.editor_uri_template
  1654. || config.editorUri
  1655. || (typeof config["editor-uri"] === "string" ? config["editor-uri"] : undefined))?.trim();
  1656. if (configTemplate)
  1657. return configTemplate;
  1658. }
  1659. catch {
  1660. // Ignore config parsing issues and use default template.
  1661. }
  1662. return DEFAULT_EDITOR_URI_TEMPLATE;
  1663. }
  1664. export function buildEditorUri(template, absolutePath, line, col) {
  1665. const safeLine = Number.isFinite(line) && line > 0 ? Math.floor(line) : 1;
  1666. const safeCol = Number.isFinite(col) && col > 0 ? Math.floor(col) : 1;
  1667. const encodedPath = encodePathForEditorUri(absolutePath);
  1668. return template
  1669. .replace(/\{path\}/g, encodedPath)
  1670. .replace(/\{line\}/g, String(safeLine))
  1671. .replace(/\{col\}/g, String(safeCol))
  1672. .replace(/\{column\}/g, String(safeCol));
  1673. }
  1674. export function termLink(text, url, isTTY = !!process.stdout.isTTY) {
  1675. if (!isTTY)
  1676. return text;
  1677. return `\x1b]8;;${url}\x07${text}\x1b]8;;\x07`;
  1678. }
  1679. function outputResults(results, query, opts) {
  1680. const filtered = results.filter(r => r.score >= opts.minScore).slice(0, opts.limit);
  1681. if (filtered.length === 0) {
  1682. printEmptySearchResults(opts.format, "min_score");
  1683. return;
  1684. }
  1685. // Helper to create qmd:// URI from displayPath
  1686. const toQmdPath = (displayPath) => `qmd://${displayPath}`;
  1687. if (opts.format === "json") {
  1688. // JSON output for LLM consumption
  1689. const output = filtered.map(row => {
  1690. const docid = row.docid || (row.hash ? row.hash.slice(0, 6) : undefined);
  1691. let body = opts.full ? row.body : undefined;
  1692. let snippet = !opts.full ? extractSnippet(row.body, query, 300, row.chunkPos, undefined, opts.intent).snippet : undefined;
  1693. if (opts.lineNumbers) {
  1694. if (body)
  1695. body = addLineNumbers(body);
  1696. if (snippet)
  1697. snippet = addLineNumbers(snippet);
  1698. }
  1699. return {
  1700. ...(docid && { docid: `#${docid}` }),
  1701. score: Math.round(row.score * 100) / 100,
  1702. file: toQmdPath(row.displayPath),
  1703. title: row.title,
  1704. ...(row.context && { context: row.context }),
  1705. ...(body && { body }),
  1706. ...(snippet && { snippet }),
  1707. ...(opts.explain && row.explain && { explain: row.explain }),
  1708. };
  1709. });
  1710. console.log(JSON.stringify(output, null, 2));
  1711. }
  1712. else if (opts.format === "files") {
  1713. // Simple docid,score,filepath,context output
  1714. for (const row of filtered) {
  1715. const docid = row.docid || (row.hash ? row.hash.slice(0, 6) : "");
  1716. const ctx = row.context ? `,"${row.context.replace(/"/g, '""')}"` : "";
  1717. console.log(`#${docid},${row.score.toFixed(2)},${toQmdPath(row.displayPath)}${ctx}`);
  1718. }
  1719. }
  1720. else if (opts.format === "cli") {
  1721. const editorUriTemplate = getEditorUriTemplate();
  1722. const linkDb = getDb();
  1723. for (let i = 0; i < filtered.length; i++) {
  1724. const row = filtered[i];
  1725. if (!row)
  1726. continue;
  1727. const { line, snippet } = extractSnippet(row.body, query, 500, row.chunkPos, undefined, opts.intent);
  1728. const docid = row.docid || (row.hash ? row.hash.slice(0, 6) : undefined);
  1729. // Line 1: filepath with docid
  1730. const virtualPath = row.file.startsWith("qmd://") ? row.file : toQmdPath(row.displayPath);
  1731. const parsed = parseVirtualPath(virtualPath);
  1732. const absolutePath = resolveVirtualPath(linkDb, virtualPath);
  1733. const legacyPath = toQmdPath(row.displayPath);
  1734. const displayPath = parsed?.path || row.displayPath;
  1735. // Only show :line if we actually found a term match in the snippet body (exclude header line).
  1736. const snippetBody = snippet.split("\n").slice(1).join("\n").toLowerCase();
  1737. const hasMatch = query.toLowerCase().split(/\s+/).some(t => t.length > 0 && snippetBody.includes(t));
  1738. const lineInfo = hasMatch ? `:${line}` : "";
  1739. const docidStr = docid ? ` ${c.dim}#${docid}${c.reset}` : "";
  1740. if (process.stdout.isTTY && absolutePath && parsed?.path) {
  1741. const linkLine = hasMatch ? line : 1;
  1742. const linkTarget = buildEditorUri(editorUriTemplate, absolutePath, linkLine, 1);
  1743. const clickable = termLink(`${displayPath}${lineInfo}`, linkTarget);
  1744. console.log(`${c.cyan}${clickable}${c.reset}${docidStr}`);
  1745. }
  1746. else {
  1747. console.log(`${c.cyan}${legacyPath}${c.dim}${lineInfo}${c.reset}${docidStr}`);
  1748. }
  1749. // Line 2: Title (if available)
  1750. if (row.title) {
  1751. console.log(`${c.bold}Title: ${row.title}${c.reset}`);
  1752. }
  1753. // Line 3: Context (if available)
  1754. if (row.context) {
  1755. console.log(`${c.dim}Context: ${row.context}${c.reset}`);
  1756. }
  1757. // Line 4: Score
  1758. const score = formatScore(row.score);
  1759. console.log(`Score: ${c.bold}${score}${c.reset}`);
  1760. if (opts.explain && row.explain) {
  1761. const explain = row.explain;
  1762. const ftsScores = explain.ftsScores.length > 0
  1763. ? explain.ftsScores.map(formatExplainNumber).join(", ")
  1764. : "none";
  1765. const vecScores = explain.vectorScores.length > 0
  1766. ? explain.vectorScores.map(formatExplainNumber).join(", ")
  1767. : "none";
  1768. const contribSummary = explain.rrf.contributions
  1769. .slice()
  1770. .sort((a, b) => b.rrfContribution - a.rrfContribution)
  1771. .slice(0, 3)
  1772. .map(c => `${c.source}/${c.queryType}#${c.rank}:${formatExplainNumber(c.rrfContribution)}`)
  1773. .join(" | ");
  1774. console.log(`${c.dim}Explain: fts=[${ftsScores}] vec=[${vecScores}]${c.reset}`);
  1775. console.log(`${c.dim} RRF: total=${formatExplainNumber(explain.rrf.totalScore)} base=${formatExplainNumber(explain.rrf.baseScore)} bonus=${formatExplainNumber(explain.rrf.topRankBonus)} rank=${explain.rrf.rank}${c.reset}`);
  1776. console.log(`${c.dim} Blend: ${Math.round(explain.rrf.weight * 100)}%*${formatExplainNumber(explain.rrf.positionScore)} + ${Math.round((1 - explain.rrf.weight) * 100)}%*${formatExplainNumber(explain.rerankScore)} = ${formatExplainNumber(explain.blendedScore)}${c.reset}`);
  1777. if (contribSummary.length > 0) {
  1778. console.log(`${c.dim} Top RRF contributions: ${contribSummary}${c.reset}`);
  1779. }
  1780. }
  1781. console.log();
  1782. // Snippet with highlighting (diff-style header included)
  1783. let displaySnippet = opts.lineNumbers ? addLineNumbers(snippet, line) : snippet;
  1784. const highlighted = highlightTerms(displaySnippet, query);
  1785. console.log(highlighted);
  1786. // Double empty line between results
  1787. if (i < filtered.length - 1)
  1788. console.log('\n');
  1789. }
  1790. }
  1791. else if (opts.format === "md") {
  1792. for (let i = 0; i < filtered.length; i++) {
  1793. const row = filtered[i];
  1794. if (!row)
  1795. continue;
  1796. const heading = row.title || row.displayPath;
  1797. const docid = row.docid || (row.hash ? row.hash.slice(0, 6) : undefined);
  1798. let content = opts.full ? row.body : extractSnippet(row.body, query, 500, row.chunkPos, undefined, opts.intent).snippet;
  1799. if (opts.lineNumbers) {
  1800. content = addLineNumbers(content);
  1801. }
  1802. const docidLine = docid ? `**docid:** \`#${docid}\`\n` : "";
  1803. const contextLine = row.context ? `**context:** ${row.context}\n` : "";
  1804. console.log(`---\n# ${heading}\n${docidLine}${contextLine}\n${content}\n`);
  1805. }
  1806. }
  1807. else if (opts.format === "xml") {
  1808. for (const row of filtered) {
  1809. const titleAttr = row.title ? ` title="${row.title.replace(/"/g, '&quot;')}"` : "";
  1810. const contextAttr = row.context ? ` context="${row.context.replace(/"/g, '&quot;')}"` : "";
  1811. const docid = row.docid || (row.hash ? row.hash.slice(0, 6) : "");
  1812. let content = opts.full ? row.body : extractSnippet(row.body, query, 500, row.chunkPos, undefined, opts.intent).snippet;
  1813. if (opts.lineNumbers) {
  1814. content = addLineNumbers(content);
  1815. }
  1816. console.log(`<file docid="#${docid}" name="${toQmdPath(row.displayPath)}"${titleAttr}${contextAttr}>\n${content}\n</file>\n`);
  1817. }
  1818. }
  1819. else {
  1820. // CSV format
  1821. console.log("docid,score,file,title,context,line,snippet");
  1822. for (const row of filtered) {
  1823. const { line, snippet } = extractSnippet(row.body, query, 500, row.chunkPos, undefined, opts.intent);
  1824. let content = opts.full ? row.body : snippet;
  1825. if (opts.lineNumbers) {
  1826. content = addLineNumbers(content, line);
  1827. }
  1828. const docid = row.docid || (row.hash ? row.hash.slice(0, 6) : "");
  1829. const snippetText = content || "";
  1830. console.log(`#${docid},${row.score.toFixed(4)},${escapeCSV(toQmdPath(row.displayPath))},${escapeCSV(row.title || "")},${escapeCSV(row.context || "")},${line},${escapeCSV(snippetText)}`);
  1831. }
  1832. }
  1833. }
  1834. // Resolve -c collection filter: supports single string, array, or undefined.
  1835. // Returns validated collection names (exits on unknown collection).
  1836. function resolveCollectionFilter(raw, useDefaults = false) {
  1837. // If no filter specified and useDefaults is true, use default collections
  1838. if (!raw && useDefaults) {
  1839. return getDefaultCollectionNames();
  1840. }
  1841. if (!raw)
  1842. return [];
  1843. const names = Array.isArray(raw) ? raw : [raw];
  1844. const validated = [];
  1845. for (const name of names) {
  1846. const coll = getCollectionFromYaml(name);
  1847. if (!coll) {
  1848. console.error(`Collection not found: ${name}`);
  1849. closeDb();
  1850. process.exit(1);
  1851. }
  1852. validated.push(name);
  1853. }
  1854. return validated;
  1855. }
  1856. // Post-filter results to only include files from specified collections.
  1857. function filterByCollections(results, collectionNames) {
  1858. if (collectionNames.length <= 1)
  1859. return results;
  1860. const prefixes = collectionNames.map(n => `qmd://${n}/`);
  1861. return results.filter(r => {
  1862. const path = r.filepath || r.file || '';
  1863. return prefixes.some(p => path.startsWith(p));
  1864. });
  1865. }
  1866. function parseStructuredQuery(query) {
  1867. const rawLines = query.split('\n').map((line, idx) => ({
  1868. raw: line,
  1869. trimmed: line.trim(),
  1870. number: idx + 1,
  1871. })).filter(line => line.trimmed.length > 0);
  1872. if (rawLines.length === 0)
  1873. return null;
  1874. const prefixRe = /^(lex|vec|hyde):\s*/i;
  1875. const expandRe = /^expand:\s*/i;
  1876. const intentRe = /^intent:\s*/i;
  1877. const typed = [];
  1878. let intent;
  1879. for (const line of rawLines) {
  1880. if (expandRe.test(line.trimmed)) {
  1881. if (rawLines.length > 1) {
  1882. throw new Error(`Line ${line.number} starts with expand:, but query documents cannot mix expand with typed lines. Submit a single expand query instead.`);
  1883. }
  1884. const text = line.trimmed.replace(expandRe, '').trim();
  1885. if (!text) {
  1886. throw new Error('expand: query must include text.');
  1887. }
  1888. return null; // treat as standalone expand query
  1889. }
  1890. // Parse intent: lines
  1891. if (intentRe.test(line.trimmed)) {
  1892. if (intent !== undefined) {
  1893. throw new Error(`Line ${line.number}: only one intent: line is allowed per query document.`);
  1894. }
  1895. const text = line.trimmed.replace(intentRe, '').trim();
  1896. if (!text) {
  1897. throw new Error(`Line ${line.number}: intent: must include text.`);
  1898. }
  1899. intent = text;
  1900. continue;
  1901. }
  1902. const match = line.trimmed.match(prefixRe);
  1903. if (match) {
  1904. const type = match[1].toLowerCase();
  1905. const text = line.trimmed.slice(match[0].length).trim();
  1906. if (!text) {
  1907. throw new Error(`Line ${line.number} (${type}:) must include text.`);
  1908. }
  1909. if (/\r|\n/.test(text)) {
  1910. throw new Error(`Line ${line.number} (${type}:) contains a newline. Keep each query on a single line.`);
  1911. }
  1912. typed.push({ type, query: text, line: line.number });
  1913. continue;
  1914. }
  1915. if (rawLines.length === 1) {
  1916. // Single plain line -> implicit expand
  1917. return null;
  1918. }
  1919. throw new Error(`Line ${line.number} is missing a lex:/vec:/hyde:/intent: prefix. Each line in a query document must start with one.`);
  1920. }
  1921. // intent: alone is not a valid query — must have at least one search
  1922. if (intent && typed.length === 0) {
  1923. throw new Error('intent: cannot appear alone. Add at least one lex:, vec:, or hyde: line.');
  1924. }
  1925. return typed.length > 0 ? { searches: typed, intent } : null;
  1926. }
  1927. function search(query, opts) {
  1928. const db = getDb();
  1929. // Validate collection filter (supports multiple -c flags)
  1930. // Use default collections if none specified
  1931. const collectionNames = resolveCollectionFilter(opts.collection, true);
  1932. const singleCollection = collectionNames.length === 1 ? collectionNames[0] : undefined;
  1933. // Use large limit for --all, otherwise fetch more than needed and let outputResults filter
  1934. const fetchLimit = opts.all ? 100000 : Math.max(50, opts.limit * 2);
  1935. const results = filterByCollections(searchFTS(db, query, fetchLimit, singleCollection), collectionNames);
  1936. // Add context to results
  1937. const resultsWithContext = results.map(r => ({
  1938. file: r.filepath,
  1939. displayPath: r.displayPath,
  1940. title: r.title,
  1941. body: r.body || "",
  1942. score: r.score,
  1943. context: getContextForFile(db, r.filepath),
  1944. hash: r.hash,
  1945. docid: r.docid,
  1946. }));
  1947. closeDb();
  1948. if (resultsWithContext.length === 0) {
  1949. printEmptySearchResults(opts.format);
  1950. return;
  1951. }
  1952. outputResults(resultsWithContext, query, opts);
  1953. }
  1954. // Log query expansion as a tree to stderr (CLI progress feedback)
  1955. function logExpansionTree(originalQuery, expanded) {
  1956. const lines = [];
  1957. lines.push(`${c.dim}├─ ${originalQuery}${c.reset}`);
  1958. for (const q of expanded) {
  1959. let preview = q.query.replace(/\n/g, ' ');
  1960. if (preview.length > 72)
  1961. preview = preview.substring(0, 69) + '...';
  1962. lines.push(`${c.dim}├─ ${q.type}: ${preview}${c.reset}`);
  1963. }
  1964. if (lines.length > 0) {
  1965. lines[lines.length - 1] = lines[lines.length - 1].replace('├─', '└─');
  1966. }
  1967. for (const line of lines)
  1968. process.stderr.write(line + '\n');
  1969. }
  1970. async function vectorSearch(query, opts, _model = DEFAULT_EMBED_MODEL) {
  1971. const store = getStore();
  1972. // Validate collection filter (supports multiple -c flags)
  1973. // Use default collections if none specified
  1974. const collectionNames = resolveCollectionFilter(opts.collection, true);
  1975. const singleCollection = collectionNames.length === 1 ? collectionNames[0] : undefined;
  1976. checkIndexHealth(store.db);
  1977. await withLLMSession(async () => {
  1978. let results = await vectorSearchQuery(store, query, {
  1979. collection: singleCollection,
  1980. limit: opts.all ? 500 : (opts.limit || 10),
  1981. minScore: opts.minScore || 0.3,
  1982. intent: opts.intent,
  1983. hooks: {
  1984. onExpand: (original, expanded) => {
  1985. logExpansionTree(original, expanded);
  1986. process.stderr.write(`${c.dim}Searching ${expanded.length + 1} vector queries...${c.reset}\n`);
  1987. },
  1988. },
  1989. });
  1990. // Post-filter for multi-collection
  1991. if (collectionNames.length > 1) {
  1992. results = results.filter(r => {
  1993. const prefixes = collectionNames.map(n => `qmd://${n}/`);
  1994. return prefixes.some(p => r.file.startsWith(p));
  1995. });
  1996. }
  1997. closeDb();
  1998. if (results.length === 0) {
  1999. printEmptySearchResults(opts.format);
  2000. return;
  2001. }
  2002. outputResults(results.map(r => ({
  2003. file: r.file,
  2004. displayPath: r.displayPath,
  2005. title: r.title,
  2006. body: r.body,
  2007. score: r.score,
  2008. context: r.context,
  2009. docid: r.docid,
  2010. })), query, { ...opts, limit: results.length });
  2011. }, { maxDuration: 10 * 60 * 1000, name: 'vectorSearch' });
  2012. }
  2013. async function querySearch(query, opts, _embedModel = DEFAULT_EMBED_MODEL, _rerankModel = DEFAULT_RERANK_MODEL) {
  2014. const store = getStore();
  2015. // Validate collection filter (supports multiple -c flags)
  2016. // Use default collections if none specified
  2017. const collectionNames = resolveCollectionFilter(opts.collection, true);
  2018. const singleCollection = collectionNames.length === 1 ? collectionNames[0] : undefined;
  2019. checkIndexHealth(store.db);
  2020. // Check for structured query syntax (lex:/vec:/hyde:/intent: prefixes)
  2021. const parsed = parseStructuredQuery(query);
  2022. // Intent can come from --intent flag or from intent: line in query document
  2023. const intent = opts.intent || parsed?.intent;
  2024. await withLLMSession(async () => {
  2025. let results;
  2026. if (parsed) {
  2027. const structuredQueries = parsed.searches;
  2028. // Structured search — user provided their own query expansions
  2029. const typeLabels = structuredQueries.map(s => s.type).join('+');
  2030. process.stderr.write(`${c.dim}Structured search: ${structuredQueries.length} queries (${typeLabels})${c.reset}\n`);
  2031. if (intent) {
  2032. process.stderr.write(`${c.dim}├─ intent: ${intent}${c.reset}\n`);
  2033. }
  2034. // Log each sub-query
  2035. for (const s of structuredQueries) {
  2036. let preview = s.query.replace(/\n/g, ' ');
  2037. if (preview.length > 72)
  2038. preview = preview.substring(0, 69) + '...';
  2039. process.stderr.write(`${c.dim}├─ ${s.type}: ${preview}${c.reset}\n`);
  2040. }
  2041. process.stderr.write(`${c.dim}└─ Searching...${c.reset}\n`);
  2042. results = await structuredSearch(store, structuredQueries, {
  2043. collections: singleCollection ? [singleCollection] : undefined,
  2044. limit: opts.all ? 500 : (opts.limit || 10),
  2045. minScore: opts.minScore || 0,
  2046. candidateLimit: opts.candidateLimit,
  2047. skipRerank: opts.skipRerank,
  2048. explain: !!opts.explain,
  2049. intent,
  2050. chunkStrategy: opts.chunkStrategy,
  2051. hooks: {
  2052. onEmbedStart: (count) => {
  2053. process.stderr.write(`${c.dim}Embedding ${count} ${count === 1 ? 'query' : 'queries'}...${c.reset}`);
  2054. },
  2055. onEmbedDone: (ms) => {
  2056. process.stderr.write(`${c.dim} (${formatMs(ms)})${c.reset}\n`);
  2057. },
  2058. onRerankStart: (chunkCount) => {
  2059. process.stderr.write(`${c.dim}Reranking ${chunkCount} chunks...${c.reset}`);
  2060. progress.indeterminate();
  2061. },
  2062. onRerankDone: (ms) => {
  2063. progress.clear();
  2064. process.stderr.write(`${c.dim} (${formatMs(ms)})${c.reset}\n`);
  2065. },
  2066. },
  2067. });
  2068. }
  2069. else {
  2070. // Standard hybrid query with automatic expansion
  2071. results = await hybridQuery(store, query, {
  2072. collection: singleCollection,
  2073. limit: opts.all ? 500 : (opts.limit || 10),
  2074. minScore: opts.minScore || 0,
  2075. candidateLimit: opts.candidateLimit,
  2076. skipRerank: opts.skipRerank,
  2077. explain: !!opts.explain,
  2078. intent,
  2079. chunkStrategy: opts.chunkStrategy,
  2080. hooks: {
  2081. onStrongSignal: (score) => {
  2082. process.stderr.write(`${c.dim}Strong BM25 signal (${score.toFixed(2)}) — skipping expansion${c.reset}\n`);
  2083. },
  2084. onExpandStart: () => {
  2085. process.stderr.write(`${c.dim}Expanding query...${c.reset}`);
  2086. },
  2087. onExpand: (original, expanded, ms) => {
  2088. process.stderr.write(`${c.dim} (${formatMs(ms)})${c.reset}\n`);
  2089. logExpansionTree(original, expanded);
  2090. process.stderr.write(`${c.dim}Searching ${expanded.length + 1} queries...${c.reset}\n`);
  2091. },
  2092. onEmbedStart: (count) => {
  2093. process.stderr.write(`${c.dim}Embedding ${count} ${count === 1 ? 'query' : 'queries'}...${c.reset}`);
  2094. },
  2095. onEmbedDone: (ms) => {
  2096. process.stderr.write(`${c.dim} (${formatMs(ms)})${c.reset}\n`);
  2097. },
  2098. onRerankStart: (chunkCount) => {
  2099. process.stderr.write(`${c.dim}Reranking ${chunkCount} chunks...${c.reset}`);
  2100. progress.indeterminate();
  2101. },
  2102. onRerankDone: (ms) => {
  2103. progress.clear();
  2104. process.stderr.write(`${c.dim} (${formatMs(ms)})${c.reset}\n`);
  2105. },
  2106. },
  2107. });
  2108. }
  2109. // Post-filter for multi-collection
  2110. if (collectionNames.length > 1) {
  2111. results = results.filter(r => {
  2112. const prefixes = collectionNames.map(n => `qmd://${n}/`);
  2113. return prefixes.some(p => r.file.startsWith(p));
  2114. });
  2115. }
  2116. closeDb();
  2117. if (results.length === 0) {
  2118. printEmptySearchResults(opts.format);
  2119. return;
  2120. }
  2121. // Use first lex/vec query for output context, or original query
  2122. const structuredQueries = parsed?.searches;
  2123. const displayQuery = structuredQueries
  2124. ? (structuredQueries.find(s => s.type === 'lex')?.query || structuredQueries.find(s => s.type === 'vec')?.query || query)
  2125. : query;
  2126. // Map to CLI output format — use bestChunk for snippet display
  2127. outputResults(results.map(r => ({
  2128. file: r.file,
  2129. displayPath: r.displayPath,
  2130. title: r.title,
  2131. body: r.bestChunk,
  2132. chunkPos: r.bestChunkPos,
  2133. score: r.score,
  2134. context: r.context,
  2135. docid: r.docid,
  2136. explain: r.explain,
  2137. })), displayQuery, { ...opts, limit: results.length });
  2138. }, { maxDuration: 10 * 60 * 1000, name: 'querySearch' });
  2139. }
  2140. // Parse CLI arguments using util.parseArgs
  2141. function parseCLI() {
  2142. const { values, positionals } = parseArgs({
  2143. args: process.argv.slice(2), // Skip node and script path
  2144. options: {
  2145. // Global options
  2146. index: {
  2147. type: "string",
  2148. },
  2149. context: {
  2150. type: "string",
  2151. },
  2152. help: { type: "boolean", short: "h" },
  2153. version: { type: "boolean", short: "v" },
  2154. skill: { type: "boolean" },
  2155. global: { type: "boolean" },
  2156. yes: { type: "boolean" },
  2157. // Search options
  2158. n: { type: "string" },
  2159. "min-score": { type: "string" },
  2160. all: { type: "boolean" },
  2161. full: { type: "boolean" },
  2162. csv: { type: "boolean" },
  2163. md: { type: "boolean" },
  2164. xml: { type: "boolean" },
  2165. files: { type: "boolean" },
  2166. json: { type: "boolean" },
  2167. explain: { type: "boolean" },
  2168. collection: { type: "string", short: "c", multiple: true }, // Filter by collection(s)
  2169. // Collection options
  2170. name: { type: "string" }, // collection name
  2171. mask: { type: "string" }, // glob pattern
  2172. // Embed options
  2173. force: { type: "boolean", short: "f" },
  2174. "max-docs-per-batch": { type: "string" },
  2175. "max-batch-mb": { type: "string" },
  2176. provider: { type: "string" }, // "local" | "openai"
  2177. "embed-endpoint": { type: "string" }, // OpenAI-compatible endpoint URL
  2178. "embed-api-key": { type: "string" }, // Bearer token
  2179. "embed-model-id": { type: "string" }, // Stable model id (default: embeddinggemma)
  2180. "embed-upstream-model": { type: "string" }, // Upstream model name in HTTP body
  2181. "embed-batch-size": { type: "string" }, // Batch size for HTTP provider
  2182. "embed-timeout-ms": { type: "string" }, // Per-request timeout
  2183. "embed-auto-fallback": { type: "boolean" }, // Wrap openai in AutoFallback (local fallback)
  2184. // Update options
  2185. pull: { type: "boolean" }, // git pull before update
  2186. refresh: { type: "boolean" },
  2187. // Get options
  2188. l: { type: "string" }, // max lines
  2189. from: { type: "string" }, // start line
  2190. "max-bytes": { type: "string" }, // max bytes for multi-get
  2191. "line-numbers": { type: "boolean" }, // add line numbers to output
  2192. // Query options
  2193. "candidate-limit": { type: "string", short: "C" },
  2194. "no-rerank": { type: "boolean", default: false },
  2195. intent: { type: "string" },
  2196. // Chunking options
  2197. "chunk-strategy": { type: "string" }, // "regex" (default) or "auto" (AST for code files)
  2198. // MCP HTTP transport options
  2199. http: { type: "boolean" },
  2200. daemon: { type: "boolean" },
  2201. port: { type: "string" },
  2202. },
  2203. allowPositionals: true,
  2204. strict: false, // Allow unknown options to pass through
  2205. });
  2206. // Select index name (default: "index")
  2207. const indexName = values.index;
  2208. if (indexName) {
  2209. setIndexName(indexName);
  2210. setConfigIndexName(indexName);
  2211. }
  2212. // Determine output format
  2213. let format = "cli";
  2214. if (values.csv)
  2215. format = "csv";
  2216. else if (values.md)
  2217. format = "md";
  2218. else if (values.xml)
  2219. format = "xml";
  2220. else if (values.files)
  2221. format = "files";
  2222. else if (values.json)
  2223. format = "json";
  2224. // Default limit: 20 for --files/--json, 5 otherwise
  2225. // --all means return all results (use very large limit)
  2226. const defaultLimit = (format === "files" || format === "json") ? 20 : 5;
  2227. const isAll = !!values.all;
  2228. const opts = {
  2229. format,
  2230. full: !!values.full,
  2231. limit: isAll ? 100000 : (values.n ? parseInt(String(values.n), 10) || defaultLimit : defaultLimit),
  2232. minScore: values["min-score"] ? parseFloat(String(values["min-score"])) || 0 : 0,
  2233. all: isAll,
  2234. collection: values.collection,
  2235. lineNumbers: !!values["line-numbers"],
  2236. candidateLimit: values["candidate-limit"] ? parseInt(String(values["candidate-limit"]), 10) : undefined,
  2237. skipRerank: !!values["no-rerank"],
  2238. explain: !!values.explain,
  2239. intent: values.intent,
  2240. chunkStrategy: parseChunkStrategy(values["chunk-strategy"]),
  2241. };
  2242. return {
  2243. command: positionals[0] || "",
  2244. args: positionals.slice(1),
  2245. query: positionals.slice(1).join(" "),
  2246. opts,
  2247. values,
  2248. };
  2249. }
  2250. function getSkillInstallDir(globalInstall) {
  2251. return globalInstall
  2252. ? resolve(homedir(), ".agents", "skills", "qmd")
  2253. : resolve(getPwd(), ".agents", "skills", "qmd");
  2254. }
  2255. function getClaudeSkillLinkPath(globalInstall) {
  2256. return globalInstall
  2257. ? resolve(homedir(), ".claude", "skills", "qmd")
  2258. : resolve(getPwd(), ".claude", "skills", "qmd");
  2259. }
  2260. function pathExists(path) {
  2261. try {
  2262. lstatSync(path);
  2263. return true;
  2264. }
  2265. catch {
  2266. return false;
  2267. }
  2268. }
  2269. function removePath(path) {
  2270. const stat = lstatSync(path);
  2271. if (stat.isDirectory() && !stat.isSymbolicLink()) {
  2272. rmSync(path, { recursive: true, force: true });
  2273. }
  2274. else {
  2275. unlinkSync(path);
  2276. }
  2277. }
  2278. function showSkill() {
  2279. console.log("QMD Skill (embedded)");
  2280. console.log("");
  2281. const content = getEmbeddedQmdSkillContent();
  2282. process.stdout.write(content.endsWith("\n") ? content : content + "\n");
  2283. }
  2284. function writeEmbeddedSkill(targetDir, force) {
  2285. if (pathExists(targetDir)) {
  2286. if (!force) {
  2287. throw new Error(`Skill already exists: ${targetDir} (use --force to replace it)`);
  2288. }
  2289. removePath(targetDir);
  2290. }
  2291. mkdirSync(targetDir, { recursive: true });
  2292. for (const file of getEmbeddedQmdSkillFiles()) {
  2293. const destination = resolve(targetDir, file.relativePath);
  2294. mkdirSync(dirname(destination), { recursive: true });
  2295. writeFileSync(destination, file.content, "utf-8");
  2296. }
  2297. }
  2298. function ensureClaudeSymlink(linkPath, targetDir, force) {
  2299. const parentDir = dirname(linkPath);
  2300. if (pathExists(parentDir)) {
  2301. const resolvedTargetDir = realpathSync(dirname(targetDir));
  2302. const resolvedLinkParent = realpathSync(parentDir);
  2303. // If .claude/skills already resolves to the same directory as .agents/skills,
  2304. // the skill is already visible to Claude and creating qmd -> qmd would loop.
  2305. if (resolvedTargetDir === resolvedLinkParent) {
  2306. return false;
  2307. }
  2308. }
  2309. const linkTarget = relativePath(parentDir, targetDir) || ".";
  2310. mkdirSync(parentDir, { recursive: true });
  2311. if (pathExists(linkPath)) {
  2312. const stat = lstatSync(linkPath);
  2313. if (stat.isSymbolicLink() && readlinkSync(linkPath) === linkTarget) {
  2314. return true;
  2315. }
  2316. if (!force) {
  2317. throw new Error(`Claude skill path already exists: ${linkPath} (use --force to replace it)`);
  2318. }
  2319. removePath(linkPath);
  2320. }
  2321. symlinkSync(linkTarget, linkPath, "dir");
  2322. return true;
  2323. }
  2324. async function shouldCreateClaudeSymlink(linkPath, autoYes) {
  2325. if (autoYes) {
  2326. return true;
  2327. }
  2328. if (!process.stdin.isTTY || !process.stdout.isTTY) {
  2329. console.log(`Tip: create a Claude symlink manually at ${linkPath}`);
  2330. return false;
  2331. }
  2332. const rl = createInterface({
  2333. input: process.stdin,
  2334. output: process.stdout,
  2335. });
  2336. try {
  2337. const answer = await rl.question(`Create a symlink in ${linkPath}? [y/N] `);
  2338. const normalized = answer.trim().toLowerCase();
  2339. return normalized === "y" || normalized === "yes";
  2340. }
  2341. finally {
  2342. rl.close();
  2343. }
  2344. }
  2345. async function installSkill(globalInstall, force, autoYes) {
  2346. const installDir = getSkillInstallDir(globalInstall);
  2347. writeEmbeddedSkill(installDir, force);
  2348. console.log(`✓ Installed QMD skill to ${installDir}`);
  2349. const claudeLinkPath = getClaudeSkillLinkPath(globalInstall);
  2350. if (!(await shouldCreateClaudeSymlink(claudeLinkPath, autoYes))) {
  2351. return;
  2352. }
  2353. const linked = ensureClaudeSymlink(claudeLinkPath, installDir, force);
  2354. if (linked) {
  2355. console.log(`✓ Linked Claude skill at ${claudeLinkPath}`);
  2356. }
  2357. else {
  2358. console.log(`✓ Claude already sees the skill via ${dirname(claudeLinkPath)}`);
  2359. }
  2360. }
  2361. function showHelp() {
  2362. console.log("qmd — Quick Markdown Search");
  2363. console.log("");
  2364. console.log("Usage:");
  2365. console.log(" qmd <command> [options]");
  2366. console.log("");
  2367. console.log("Primary commands:");
  2368. console.log(" qmd query <query> - Hybrid search with auto expansion + reranking (recommended)");
  2369. console.log(" qmd query 'lex:..\\nvec:...' - Structured query document (you provide lex/vec/hyde lines)");
  2370. console.log(" qmd search <query> - Full-text BM25 keywords (no LLM)");
  2371. console.log(" qmd vsearch <query> - Vector similarity only");
  2372. console.log(" qmd get <file>[:line] [-l N] - Show a single document, optional line slice");
  2373. console.log(" qmd multi-get <pattern> - Batch fetch via glob or comma-separated list");
  2374. console.log(" qmd skill show/install - Show or install the packaged QMD skill");
  2375. console.log(" qmd mcp - Start the MCP server (stdio transport for AI agents)");
  2376. console.log(" qmd bench <fixture.json> - Run search quality benchmarks against a fixture file");
  2377. console.log("");
  2378. console.log("Collections & context:");
  2379. console.log(" qmd collection add/list/remove/rename/show - Manage indexed folders");
  2380. console.log(" qmd context add/list/rm - Attach human-written summaries");
  2381. console.log(" qmd ls [collection[/path]] - Inspect indexed files");
  2382. console.log("");
  2383. console.log("Maintenance:");
  2384. console.log(" qmd status - View index + collection health");
  2385. console.log(" qmd update [--pull] - Re-index collections (optionally git pull first)");
  2386. console.log(" qmd embed [-f] - Generate/refresh vector embeddings");
  2387. console.log(" --max-docs-per-batch <n> - Cap docs loaded into memory per embedding batch");
  2388. console.log(" --max-batch-mb <n> - Cap UTF-8 MB loaded into memory per embedding batch");
  2389. console.log(" --provider {local,openai} - Embedding backend (default: local llama.cpp)");
  2390. console.log(" --embed-endpoint <url> - OpenAI-compatible endpoint (or QMD_EMBED_ENDPOINT)");
  2391. console.log(" --embed-api-key <key> - Bearer token (or QMD_EMBED_API_KEY)");
  2392. console.log(" --embed-model-id <id> - Stable model id stored in DB (default: embeddinggemma)");
  2393. console.log(" --embed-upstream-model <m> - Model name sent in HTTP body (default: same as model-id)");
  2394. console.log(" --embed-batch-size <n> - Batch size for HTTP provider (default: 64)");
  2395. console.log(" --embed-timeout-ms <n> - Per-request timeout in ms (default: 30000)");
  2396. console.log(" --embed-auto-fallback - Wrap openai provider in local fallback (or QMD_EMBED_AUTO_FALLBACK)");
  2397. console.log(" qmd cleanup - Clear caches, vacuum DB");
  2398. console.log("");
  2399. console.log("Query syntax (qmd query):");
  2400. console.log(" QMD queries are either a single expand query (no prefix) or a multi-line");
  2401. console.log(" document where every line is typed with lex:, vec:, or hyde:. This grammar");
  2402. console.log(" matches the docs in docs/SYNTAX.md and is enforced in the CLI.");
  2403. console.log("");
  2404. const grammar = [
  2405. `query = expand_query | query_document ;`,
  2406. `expand_query = text | explicit_expand ;`,
  2407. `explicit_expand= "expand:" text ;`,
  2408. `query_document = [ intent_line ] { typed_line } ;`,
  2409. `intent_line = "intent:" text newline ;`,
  2410. `typed_line = type ":" text newline ;`,
  2411. `type = "lex" | "vec" | "hyde" ;`,
  2412. `text = quoted_phrase | plain_text ;`,
  2413. `quoted_phrase = '"' { character } '"' ;`,
  2414. `plain_text = { character } ;`,
  2415. `newline = "\\n" ;`,
  2416. ];
  2417. console.log(" Grammar:");
  2418. for (const line of grammar) {
  2419. console.log(` ${line}`);
  2420. }
  2421. console.log("");
  2422. console.log(" Examples:");
  2423. console.log(" qmd query \"how does auth work\" # single-line → implicit expand");
  2424. console.log(" qmd query $'lex: CAP theorem\\nvec: consistency' # typed query document");
  2425. console.log(" qmd query $'lex: \"exact matches\" sports -baseball' # phrase + negation lex search");
  2426. console.log(" qmd query $'hyde: Hypothetical answer text' # hyde-only document");
  2427. console.log("");
  2428. console.log(" Constraints:");
  2429. console.log(" - Standalone expand queries cannot mix with typed lines.");
  2430. console.log(" - Query documents allow only lex:, vec:, or hyde: prefixes.");
  2431. console.log(" - Each typed line must be single-line text with balanced quotes.");
  2432. console.log("");
  2433. console.log("AI agents & integrations:");
  2434. console.log(" - Run `qmd mcp` to expose the MCP server (stdio) to agents/IDEs.");
  2435. console.log(" - `qmd skill install` installs the QMD skill into ./.agents/skills/qmd.");
  2436. console.log(" - Use `qmd skill install --global` for ~/.agents/skills/qmd.");
  2437. console.log(" - `qmd --skill` is kept as an alias for `qmd skill show`.");
  2438. console.log(" - Advanced: `qmd mcp --http ...` and `qmd mcp --http --daemon` are optional for custom transports.");
  2439. console.log("");
  2440. console.log("Global options:");
  2441. console.log(" --index <name> - Use a named index (default: index)");
  2442. console.log(" QMD_EDITOR_URI - Editor link template for clickable TTY search output");
  2443. console.log("");
  2444. console.log("Search options:");
  2445. console.log(" -n <num> - Max results (default 5, or 20 for --files/--json)");
  2446. console.log(" --all - Return all matches (pair with --min-score)");
  2447. console.log(" --min-score <num> - Minimum similarity score");
  2448. console.log(" --full - Output full document instead of snippet");
  2449. console.log(" -C, --candidate-limit <n> - Max candidates to rerank (default 40, lower = faster)");
  2450. console.log(" --no-rerank - Skip LLM reranking (use RRF scores only, much faster on CPU)");
  2451. console.log(" --line-numbers - Include line numbers in output");
  2452. console.log(" --explain - Include retrieval score traces (query --json/CLI)");
  2453. console.log(" --files | --json | --csv | --md | --xml - Output format");
  2454. console.log(" -c, --collection <name> - Filter by one or more collections");
  2455. console.log("");
  2456. console.log("Embed/query options:");
  2457. console.log(" --chunk-strategy <auto|regex> - Chunking mode (default: regex; auto uses AST for code files)");
  2458. console.log("");
  2459. console.log("Multi-get options:");
  2460. console.log(" -l <num> - Maximum lines per file");
  2461. console.log(" --max-bytes <num> - Skip files larger than N bytes (default 10240)");
  2462. console.log(" --json/--csv/--md/--xml/--files - Same formats as search");
  2463. console.log("");
  2464. console.log(`Index: ${getDbPath()}`);
  2465. }
  2466. async function showVersion() {
  2467. const scriptDir = dirname(fileURLToPath(import.meta.url));
  2468. const pkgPath = resolve(scriptDir, "..", "..", "package.json");
  2469. const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
  2470. let commit = "";
  2471. try {
  2472. commit = execSync(`git -C ${scriptDir} rev-parse --short HEAD`, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim();
  2473. }
  2474. catch {
  2475. // Not a git repo or git not available
  2476. }
  2477. const versionStr = commit ? `${pkg.version} (${commit})` : pkg.version;
  2478. console.log(`qmd ${versionStr}`);
  2479. }
  2480. // Main CLI - only run if this is the main module
  2481. const __filename = fileURLToPath(import.meta.url);
  2482. const argv1 = process.argv[1];
  2483. const isMain = argv1 === __filename
  2484. || argv1?.endsWith("/qmd.ts")
  2485. || argv1?.endsWith("/qmd.js")
  2486. || (argv1 != null && realpathSync(argv1) === __filename);
  2487. if (isMain) {
  2488. const cli = parseCLI();
  2489. if (cli.values.version) {
  2490. await showVersion();
  2491. process.exit(0);
  2492. }
  2493. if (cli.values.skill) {
  2494. showSkill();
  2495. process.exit(0);
  2496. }
  2497. if (cli.values.help && cli.command === "skill") {
  2498. console.log("Usage: qmd skill <show|install> [options]");
  2499. console.log("");
  2500. console.log("Commands:");
  2501. console.log(" show Print the packaged QMD skill");
  2502. console.log(" install Install into ./.agents/skills/qmd");
  2503. console.log("");
  2504. console.log("Options:");
  2505. console.log(" --global Install into ~/.agents/skills/qmd");
  2506. console.log(" --yes Also create the .claude/skills/qmd symlink");
  2507. console.log(" -f, --force Replace existing install or symlink");
  2508. process.exit(0);
  2509. }
  2510. if (!cli.command || cli.values.help) {
  2511. showHelp();
  2512. process.exit(cli.values.help ? 0 : 1);
  2513. }
  2514. switch (cli.command) {
  2515. case "context": {
  2516. const subcommand = cli.args[0];
  2517. if (!subcommand) {
  2518. console.error("Usage: qmd context <add|list|rm>");
  2519. console.error("");
  2520. console.error("Commands:");
  2521. console.error(" qmd context add [path] \"text\" - Add context (defaults to current dir)");
  2522. console.error(" qmd context add / \"text\" - Add global context to all collections");
  2523. console.error(" qmd context list - List all contexts");
  2524. console.error(" qmd context rm <path> - Remove context");
  2525. process.exit(1);
  2526. }
  2527. switch (subcommand) {
  2528. case "add": {
  2529. if (cli.args.length < 2) {
  2530. console.error("Usage: qmd context add [path] \"text\"");
  2531. console.error("");
  2532. console.error("Examples:");
  2533. console.error(" qmd context add \"Context for current directory\"");
  2534. console.error(" qmd context add . \"Context for current directory\"");
  2535. console.error(" qmd context add /subfolder \"Context for subfolder\"");
  2536. console.error(" qmd context add / \"Global context for all collections\"");
  2537. console.error("");
  2538. console.error(" Using virtual paths:");
  2539. console.error(" qmd context add qmd://journals/ \"Context for entire journals collection\"");
  2540. console.error(" qmd context add qmd://journals/2024 \"Context for 2024 journals\"");
  2541. process.exit(1);
  2542. }
  2543. let pathArg;
  2544. let contextText;
  2545. // Check if first arg looks like a path or if it's the context text
  2546. const firstArg = cli.args[1] || '';
  2547. const secondArg = cli.args[2];
  2548. if (secondArg) {
  2549. // Two args: path + context
  2550. pathArg = firstArg;
  2551. contextText = cli.args.slice(2).join(" ");
  2552. }
  2553. else {
  2554. // One arg: context only (use current directory)
  2555. pathArg = undefined;
  2556. contextText = firstArg;
  2557. }
  2558. await contextAdd(pathArg, contextText);
  2559. break;
  2560. }
  2561. case "list": {
  2562. contextList();
  2563. break;
  2564. }
  2565. case "rm":
  2566. case "remove": {
  2567. if (cli.args.length < 2 || !cli.args[1]) {
  2568. console.error("Usage: qmd context rm <path>");
  2569. console.error("Examples:");
  2570. console.error(" qmd context rm /");
  2571. console.error(" qmd context rm qmd://journals/2024");
  2572. process.exit(1);
  2573. }
  2574. contextRemove(cli.args[1]);
  2575. break;
  2576. }
  2577. default:
  2578. console.error(`Unknown subcommand: ${subcommand}`);
  2579. console.error("Available: add, list, rm");
  2580. process.exit(1);
  2581. }
  2582. break;
  2583. }
  2584. case "get": {
  2585. if (!cli.args[0]) {
  2586. console.error("Usage: qmd get <filepath>[:line] [--from <line>] [-l <lines>] [--line-numbers]");
  2587. process.exit(1);
  2588. }
  2589. const fromLine = cli.values.from ? parseInt(cli.values.from, 10) : undefined;
  2590. const maxLines = cli.values.l ? parseInt(cli.values.l, 10) : undefined;
  2591. getDocument(cli.args[0], fromLine, maxLines, cli.opts.lineNumbers);
  2592. break;
  2593. }
  2594. case "multi-get": {
  2595. if (!cli.args[0]) {
  2596. console.error("Usage: qmd multi-get <pattern> [-l <lines>] [--max-bytes <bytes>] [--json|--csv|--md|--xml|--files]");
  2597. console.error(" pattern: glob (e.g., 'journals/2025-05*.md') or comma-separated list");
  2598. process.exit(1);
  2599. }
  2600. const maxLinesMulti = cli.values.l ? parseInt(cli.values.l, 10) : undefined;
  2601. const maxBytes = cli.values["max-bytes"] ? parseInt(cli.values["max-bytes"], 10) : DEFAULT_MULTI_GET_MAX_BYTES;
  2602. multiGet(cli.args[0], maxLinesMulti, maxBytes, cli.opts.format);
  2603. break;
  2604. }
  2605. case "ls": {
  2606. listFiles(cli.args[0]);
  2607. break;
  2608. }
  2609. case "collection": {
  2610. const subcommand = cli.args[0];
  2611. switch (subcommand) {
  2612. case "list": {
  2613. collectionList();
  2614. break;
  2615. }
  2616. case "add": {
  2617. const pwd = cli.args[1] || getPwd();
  2618. const resolvedPwd = pwd === '.' ? getPwd() : getRealPath(resolve(pwd));
  2619. const globPattern = cli.values.mask || DEFAULT_GLOB;
  2620. const name = cli.values.name;
  2621. await collectionAdd(resolvedPwd, globPattern, name);
  2622. break;
  2623. }
  2624. case "remove":
  2625. case "rm": {
  2626. if (!cli.args[1]) {
  2627. console.error("Usage: qmd collection remove <name>");
  2628. console.error(" Use 'qmd collection list' to see available collections");
  2629. process.exit(1);
  2630. }
  2631. collectionRemove(cli.args[1]);
  2632. break;
  2633. }
  2634. case "rename":
  2635. case "mv": {
  2636. if (!cli.args[1] || !cli.args[2]) {
  2637. console.error("Usage: qmd collection rename <old-name> <new-name>");
  2638. console.error(" Use 'qmd collection list' to see available collections");
  2639. process.exit(1);
  2640. }
  2641. collectionRename(cli.args[1], cli.args[2]);
  2642. break;
  2643. }
  2644. case "set-update":
  2645. case "update-cmd": {
  2646. const name = cli.args[1];
  2647. const cmd = cli.args.slice(2).join(' ') || null;
  2648. if (!name) {
  2649. console.error("Usage: qmd collection update-cmd <name> [command]");
  2650. console.error(" Set the command to run before indexing (e.g., 'git pull')");
  2651. console.error(" Omit command to clear it");
  2652. process.exit(1);
  2653. }
  2654. const { updateCollectionSettings, getCollection } = await import("../collections.js");
  2655. const col = getCollection(name);
  2656. if (!col) {
  2657. console.error(`Collection not found: ${name}`);
  2658. process.exit(1);
  2659. }
  2660. updateCollectionSettings(name, { update: cmd });
  2661. if (cmd) {
  2662. console.log(`✓ Set update command for '${name}': ${cmd}`);
  2663. }
  2664. else {
  2665. console.log(`✓ Cleared update command for '${name}'`);
  2666. }
  2667. break;
  2668. }
  2669. case "include":
  2670. case "exclude": {
  2671. const name = cli.args[1];
  2672. if (!name) {
  2673. console.error(`Usage: qmd collection ${subcommand} <name>`);
  2674. console.error(` ${subcommand === 'include' ? 'Include' : 'Exclude'} collection in default queries`);
  2675. process.exit(1);
  2676. }
  2677. const { updateCollectionSettings, getCollection } = await import("../collections.js");
  2678. const col = getCollection(name);
  2679. if (!col) {
  2680. console.error(`Collection not found: ${name}`);
  2681. process.exit(1);
  2682. }
  2683. const include = subcommand === 'include';
  2684. updateCollectionSettings(name, { includeByDefault: include });
  2685. console.log(`✓ Collection '${name}' ${include ? 'included in' : 'excluded from'} default queries`);
  2686. break;
  2687. }
  2688. case "show":
  2689. case "info": {
  2690. const name = cli.args[1];
  2691. if (!name) {
  2692. console.error("Usage: qmd collection show <name>");
  2693. process.exit(1);
  2694. }
  2695. const { getCollection } = await import("../collections.js");
  2696. const col = getCollection(name);
  2697. if (!col) {
  2698. console.error(`Collection not found: ${name}`);
  2699. process.exit(1);
  2700. }
  2701. console.log(`Collection: ${name}`);
  2702. console.log(` Path: ${col.path}`);
  2703. console.log(` Pattern: ${col.pattern}`);
  2704. console.log(` Include: ${col.includeByDefault !== false ? 'yes (default)' : 'no'}`);
  2705. if (col.update) {
  2706. console.log(` Update: ${col.update}`);
  2707. }
  2708. if (col.context) {
  2709. const ctxCount = Object.keys(col.context).length;
  2710. console.log(` Contexts: ${ctxCount}`);
  2711. }
  2712. break;
  2713. }
  2714. case "help":
  2715. case undefined: {
  2716. console.log("Usage: qmd collection <command> [options]");
  2717. console.log("");
  2718. console.log("Commands:");
  2719. console.log(" list List all collections");
  2720. console.log(" add <path> [--name NAME] Add a collection");
  2721. console.log(" remove <name> Remove a collection");
  2722. console.log(" rename <old> <new> Rename a collection");
  2723. console.log(" show <name> Show collection details");
  2724. console.log(" update-cmd <name> [cmd] Set pre-update command (e.g., 'git pull')");
  2725. console.log(" include <name> Include in default queries");
  2726. console.log(" exclude <name> Exclude from default queries");
  2727. console.log("");
  2728. console.log("Examples:");
  2729. console.log(" qmd collection add ~/notes --name notes");
  2730. console.log(" qmd collection update-cmd brain 'git pull'");
  2731. console.log(" qmd collection exclude archive");
  2732. process.exit(0);
  2733. }
  2734. default:
  2735. console.error(`Unknown subcommand: ${subcommand}`);
  2736. console.error("Run 'qmd collection help' for usage");
  2737. process.exit(1);
  2738. }
  2739. break;
  2740. }
  2741. case "status":
  2742. await showStatus();
  2743. break;
  2744. case "update":
  2745. await updateCollections();
  2746. break;
  2747. case "embed":
  2748. try {
  2749. const maxDocsPerBatch = parseEmbedBatchOption("maxDocsPerBatch", cli.values["max-docs-per-batch"]);
  2750. const maxBatchMb = parseEmbedBatchOption("maxBatchBytes", cli.values["max-batch-mb"]);
  2751. const embedChunkStrategy = parseChunkStrategy(cli.values["chunk-strategy"]);
  2752. // Build embedding provider from CLI flags + env + config file.
  2753. // Backward compat: with no flags / env vars, the factory returns
  2754. // a LocalLlamaCppProvider that delegates to the default LlamaCpp
  2755. // singleton — identical to pre-patch behavior.
  2756. const providerCliKind = parseProviderKind(cli.values["provider"]);
  2757. const providerOpts = buildProviderOpts(cli.values, providerCliKind);
  2758. const embedProvider = createEmbeddingProvider(providerOpts);
  2759. await vectorIndex(DEFAULT_EMBED_MODEL_URI, !!cli.values.force, {
  2760. maxDocsPerBatch,
  2761. maxBatchBytes: maxBatchMb === undefined ? undefined : maxBatchMb * 1024 * 1024,
  2762. chunkStrategy: embedChunkStrategy,
  2763. embedProvider,
  2764. providerKind: embedProvider.kind,
  2765. });
  2766. }
  2767. catch (error) {
  2768. if (error instanceof ModelMismatchError) {
  2769. // Friendlier output for the migration-safety guard
  2770. console.error(`${c.red}Model mismatch:${c.reset} ${error.message}`);
  2771. }
  2772. else {
  2773. console.error(error instanceof Error ? error.message : String(error));
  2774. }
  2775. process.exit(1);
  2776. }
  2777. break;
  2778. case "pull": {
  2779. const refresh = cli.values.refresh === undefined ? false : Boolean(cli.values.refresh);
  2780. const models = [
  2781. DEFAULT_EMBED_MODEL_URI,
  2782. DEFAULT_GENERATE_MODEL_URI,
  2783. DEFAULT_RERANK_MODEL_URI,
  2784. ];
  2785. console.log(`${c.bold}Pulling models${c.reset}`);
  2786. const results = await pullModels(models, {
  2787. refresh,
  2788. cacheDir: DEFAULT_MODEL_CACHE_DIR,
  2789. });
  2790. for (const result of results) {
  2791. const size = formatBytes(result.sizeBytes);
  2792. const note = result.refreshed ? "refreshed" : "cached/checked";
  2793. console.log(`- ${result.model} -> ${result.path} (${size}, ${note})`);
  2794. }
  2795. break;
  2796. }
  2797. case "search":
  2798. if (!cli.query) {
  2799. console.error("Usage: qmd search [options] <query>");
  2800. process.exit(1);
  2801. }
  2802. search(cli.query, cli.opts);
  2803. break;
  2804. case "vsearch":
  2805. case "vector-search": // undocumented alias
  2806. if (!cli.query) {
  2807. console.error("Usage: qmd vsearch [options] <query>");
  2808. process.exit(1);
  2809. }
  2810. // Default min-score for vector search is 0.3
  2811. if (!cli.values["min-score"]) {
  2812. cli.opts.minScore = 0.3;
  2813. }
  2814. await vectorSearch(cli.query, cli.opts);
  2815. break;
  2816. case "query":
  2817. case "deep-search": // undocumented alias
  2818. if (!cli.query) {
  2819. console.error("Usage: qmd query [options] <query>");
  2820. process.exit(1);
  2821. }
  2822. await querySearch(cli.query, cli.opts);
  2823. break;
  2824. case "bench": {
  2825. const fixturePath = cli.args[0];
  2826. if (!fixturePath) {
  2827. console.error("Usage: qmd bench <fixture.json> [--json] [-c collection]");
  2828. console.error("");
  2829. console.error("Run search quality benchmarks against a fixture file.");
  2830. console.error("See src/bench/fixtures/example.json for the fixture format.");
  2831. process.exit(1);
  2832. }
  2833. const { runBenchmark } = await import("../bench/bench.js");
  2834. const benchCollection = cli.opts.collection;
  2835. await runBenchmark(fixturePath, {
  2836. json: !!cli.opts.json,
  2837. collection: Array.isArray(benchCollection) ? benchCollection[0] : benchCollection,
  2838. });
  2839. break;
  2840. }
  2841. case "mcp": {
  2842. const sub = cli.args[0]; // stop | status | undefined
  2843. // Cache dir for PID/log files — same dir as the index
  2844. const cacheDir = process.env.XDG_CACHE_HOME
  2845. ? resolve(process.env.XDG_CACHE_HOME, "qmd")
  2846. : resolve(homedir(), ".cache", "qmd");
  2847. const pidPath = resolve(cacheDir, "mcp.pid");
  2848. // Subcommands take priority over flags
  2849. if (sub === "stop") {
  2850. if (!existsSync(pidPath)) {
  2851. console.log("Not running (no PID file).");
  2852. process.exit(0);
  2853. }
  2854. const pid = parseInt(readFileSync(pidPath, "utf-8").trim());
  2855. try {
  2856. process.kill(pid, 0); // alive?
  2857. process.kill(pid, "SIGTERM");
  2858. unlinkSync(pidPath);
  2859. console.log(`Stopped QMD MCP server (PID ${pid}).`);
  2860. }
  2861. catch {
  2862. unlinkSync(pidPath);
  2863. console.log("Cleaned up stale PID file (server was not running).");
  2864. }
  2865. process.exit(0);
  2866. }
  2867. if (cli.values.http) {
  2868. const port = Number(cli.values.port) || 8181;
  2869. if (cli.values.daemon) {
  2870. // Guard: check if already running
  2871. if (existsSync(pidPath)) {
  2872. const existingPid = parseInt(readFileSync(pidPath, "utf-8").trim());
  2873. try {
  2874. process.kill(existingPid, 0); // alive?
  2875. console.error(`Already running (PID ${existingPid}). Run 'qmd mcp stop' first.`);
  2876. process.exit(1);
  2877. }
  2878. catch {
  2879. // Stale PID file — continue
  2880. }
  2881. }
  2882. mkdirSync(cacheDir, { recursive: true });
  2883. const logPath = resolve(cacheDir, "mcp.log");
  2884. const logFd = openSync(logPath, "w"); // truncate — fresh log per daemon run
  2885. const selfPath = fileURLToPath(import.meta.url);
  2886. const spawnArgs = selfPath.endsWith(".ts")
  2887. ? ["--import", pathJoin(dirname(selfPath), "..", "..", "node_modules", "tsx", "dist", "esm", "index.mjs"), selfPath, "mcp", "--http", "--port", String(port)]
  2888. : [selfPath, "mcp", "--http", "--port", String(port)];
  2889. const child = nodeSpawn(process.execPath, spawnArgs, {
  2890. stdio: ["ignore", logFd, logFd],
  2891. detached: true,
  2892. });
  2893. child.unref();
  2894. closeSync(logFd); // parent's copy; child inherited the fd
  2895. writeFileSync(pidPath, String(child.pid));
  2896. console.log(`Started on http://localhost:${port}/mcp (PID ${child.pid})`);
  2897. console.log(`Logs: ${logPath}`);
  2898. process.exit(0);
  2899. }
  2900. // Foreground HTTP mode — remove top-level cursor handlers so the
  2901. // async cleanup handlers in startMcpHttpServer actually run.
  2902. process.removeAllListeners("SIGTERM");
  2903. process.removeAllListeners("SIGINT");
  2904. const { startMcpHttpServer } = await import("../mcp/server.js");
  2905. try {
  2906. await startMcpHttpServer(port);
  2907. }
  2908. catch (e) {
  2909. if (e?.code === "EADDRINUSE") {
  2910. console.error(`Port ${port} already in use. Try a different port with --port.`);
  2911. process.exit(1);
  2912. }
  2913. throw e;
  2914. }
  2915. }
  2916. else {
  2917. // Default: stdio transport
  2918. const { startMcpServer } = await import("../mcp/server.js");
  2919. await startMcpServer();
  2920. }
  2921. break;
  2922. }
  2923. case "skill": {
  2924. const subcommand = cli.args[0];
  2925. switch (subcommand) {
  2926. case "show": {
  2927. showSkill();
  2928. break;
  2929. }
  2930. case "install": {
  2931. try {
  2932. await installSkill(Boolean(cli.values.global), Boolean(cli.values.force), Boolean(cli.values.yes));
  2933. }
  2934. catch (error) {
  2935. console.error(error instanceof Error ? error.message : String(error));
  2936. process.exit(1);
  2937. }
  2938. break;
  2939. }
  2940. case "help":
  2941. case undefined: {
  2942. console.log("Usage: qmd skill <show|install> [options]");
  2943. console.log("");
  2944. console.log("Commands:");
  2945. console.log(" show Print the packaged QMD skill");
  2946. console.log(" install Install into ./.agents/skills/qmd");
  2947. console.log("");
  2948. console.log("Options:");
  2949. console.log(" --global Install into ~/.agents/skills/qmd");
  2950. console.log(" --yes Also create the .claude/skills/qmd symlink");
  2951. console.log(" -f, --force Replace existing install or symlink");
  2952. process.exit(0);
  2953. }
  2954. default:
  2955. console.error(`Unknown subcommand: ${subcommand}`);
  2956. console.error("Run 'qmd skill help' for usage");
  2957. process.exit(1);
  2958. }
  2959. break;
  2960. }
  2961. case "cleanup": {
  2962. const db = getDb();
  2963. // 1. Clear llm_cache
  2964. const cacheCount = deleteLLMCache(db);
  2965. console.log(`${c.green}✓${c.reset} Cleared ${cacheCount} cached API responses`);
  2966. // 2. Remove orphaned vectors
  2967. const orphanedVecs = cleanupOrphanedVectors(db);
  2968. if (orphanedVecs > 0) {
  2969. console.log(`${c.green}✓${c.reset} Removed ${orphanedVecs} orphaned embedding chunks`);
  2970. }
  2971. else {
  2972. console.log(`${c.dim}No orphaned embeddings to remove${c.reset}`);
  2973. }
  2974. // 3. Remove inactive documents
  2975. const inactiveDocs = deleteInactiveDocuments(db);
  2976. if (inactiveDocs > 0) {
  2977. console.log(`${c.green}✓${c.reset} Removed ${inactiveDocs} inactive document records`);
  2978. }
  2979. // 4. Vacuum to reclaim space
  2980. vacuumDatabase(db);
  2981. console.log(`${c.green}✓${c.reset} Database vacuumed`);
  2982. closeDb();
  2983. break;
  2984. }
  2985. default:
  2986. console.error(`Unknown command: ${cli.command}`);
  2987. console.error("Run 'qmd --help' for usage.");
  2988. process.exit(1);
  2989. }
  2990. if (cli.command !== "mcp") {
  2991. await disposeDefaultLlamaCpp();
  2992. process.exit(0);
  2993. }
  2994. } // end if (main module)