qmd.ts 103 KB

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