qmd.js 134 KB

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