qmd.ts 87 KB

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