qmd.ts 111 KB

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