qmd.ts 89 KB

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