qmd.js 135 KB

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