@joycodetech/qmd-ja 2.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +819 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1143 -0
  4. package/bin/qmd +162 -0
  5. package/dist/ast.d.ts +65 -0
  6. package/dist/ast.js +334 -0
  7. package/dist/bench/bench.d.ts +23 -0
  8. package/dist/bench/bench.js +280 -0
  9. package/dist/bench/score.d.ts +33 -0
  10. package/dist/bench/score.js +88 -0
  11. package/dist/bench/types.d.ts +80 -0
  12. package/dist/bench/types.js +8 -0
  13. package/dist/cli/formatter.d.ts +120 -0
  14. package/dist/cli/formatter.js +355 -0
  15. package/dist/cli/qmd.d.ts +43 -0
  16. package/dist/cli/qmd.js +4159 -0
  17. package/dist/collections.d.ts +166 -0
  18. package/dist/collections.js +410 -0
  19. package/dist/db.d.ts +44 -0
  20. package/dist/db.js +75 -0
  21. package/dist/index.d.ts +230 -0
  22. package/dist/index.js +242 -0
  23. package/dist/llm.d.ts +500 -0
  24. package/dist/llm.js +1615 -0
  25. package/dist/maintenance.d.ts +23 -0
  26. package/dist/maintenance.js +37 -0
  27. package/dist/mcp/server.d.ts +24 -0
  28. package/dist/mcp/server.js +702 -0
  29. package/dist/paths.d.ts +1 -0
  30. package/dist/paths.js +4 -0
  31. package/dist/store.d.ts +996 -0
  32. package/dist/store.js +4208 -0
  33. package/models/vaporetto-bccwj.model +0 -0
  34. package/package.json +130 -0
  35. package/scripts/build.mjs +30 -0
  36. package/scripts/check-package-grammars.mjs +29 -0
  37. package/scripts/package-smoke.mjs +65 -0
  38. package/scripts/test-all.mjs +38 -0
  39. package/skills/qmd/SKILL.md +295 -0
  40. package/skills/qmd/references/mcp-setup.md +102 -0
  41. package/skills/release/SKILL.md +139 -0
  42. package/skills/release/scripts/install-hooks.sh +38 -0
  43. package/vendor/vaporetto-node-wasm/package.json +11 -0
  44. package/vendor/vaporetto-node-wasm/vaporetto_node_wasm.d.ts +19 -0
  45. package/vendor/vaporetto-node-wasm/vaporetto_node_wasm.js +202 -0
  46. package/vendor/vaporetto-node-wasm/vaporetto_node_wasm_bg.wasm +0 -0
  47. package/vendor/vaporetto-node-wasm/vaporetto_node_wasm_bg.wasm.d.ts +13 -0
@@ -0,0 +1,4159 @@
1
+ #!/usr/bin/env node
2
+ import { isBun, openDatabase } 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 { basename, dirname, join as pathJoin, relative as relativePath, resolve as pathResolve } from "path";
7
+ import { parseArgs } from "util";
8
+ import { readFileSync, readdirSync, realpathSync, statSync, existsSync, unlinkSync, writeFileSync, openSync, closeSync, mkdirSync, lstatSync, rmSync, symlinkSync, readlinkSync, copyFileSync } from "fs";
9
+ import { createInterface } from "readline/promises";
10
+ import { getPwd, getRealPath, homedir, resolve, enableProductionMode, searchFTS, extractSnippet, getContextForFile, getContextForPath, listCollections, removeCollection, renameCollection, findSimilarFiles, findDocumentByDocid, isDocid, matchFilesByGlob, getHashesNeedingEmbedding, clearAllEmbeddings, insertEmbedding, getStatus, hashContent, extractTitle, formatDocForEmbedding, getEmbeddingFingerprint, chunkDocumentByTokens, clearCache, getCacheKey, getCachedResult, setCachedResult, getIndexHealth, parseVirtualPath, buildVirtualPath, isVirtualPath, resolveVirtualPath, toVirtualPath, insertContent, insertDocument, findActiveDocument, findOrMigrateLegacyDocument, updateDocumentTitle, updateDocument, deactivateDocument, getActiveDocumentPaths, cleanupOrphanedContent, deleteLLMCache, deleteInactiveDocuments, cleanupOrphanedVectors, vacuumDatabase, getCollectionsWithoutContext, getTopLevelPathsWithoutContext, handelize, hybridQuery, vectorSearchQuery, structuredSearch, addLineNumbers, DEFAULT_EMBED_MODEL, DEFAULT_EMBED_MAX_BATCH_BYTES, DEFAULT_EMBED_MAX_DOCS_PER_BATCH, DEFAULT_RERANK_MODEL, DEFAULT_QUERY_MODEL, DEFAULT_GLOB, DEFAULT_MULTI_GET_MAX_BYTES, createStore, getDefaultDbPath, reindexCollection, initializeKuromojiTokenizer, generateEmbeddings, maybeAdoptLegacyEmbeddingFingerprint, syncConfigToDb, } from "../store.js";
11
+ import { disposeDefaultLlamaCpp, getDefaultLlamaCpp, setDefaultLlamaCpp, LlamaCpp, withLLMSession, pullModels, DEFAULT_MODEL_CACHE_DIR, resolveEmbedModel, resolveGenerateModel, resolveRerankModel, resolveModels, inspectGgufFile, isDarwinMetalMitigationActive } from "../llm.js";
12
+ import { formatSearchResults, formatDocuments, escapeXml, escapeCSV, } from "./formatter.js";
13
+ import { getCollection as getCollectionFromYaml, listCollections as yamlListCollections, getDefaultCollectionNames, addContext as yamlAddContext, removeContext as yamlRemoveContext, removeCollection as yamlRemoveCollectionFn, renameCollection as yamlRenameCollectionFn, setGlobalContext, listAllContexts, setConfigIndexName, loadConfig, saveConfig, setConfigSource, findLocalConfigPath, getLocalDbPath, getConfigPath, configExists, } from "../collections.js";
14
+ // NOTE: enableProductionMode() is intentionally NOT called at module scope here.
15
+ // Importing this module for its exports (e.g. buildEditorUri, termLink from
16
+ // test/cli.test.ts) must not flip the global production flag, as that leaks
17
+ // into unrelated tests that rely on the default (development) database path
18
+ // resolution. The flag is flipped inside the CLI's main-module guard below so
19
+ // it only fires when qmd is actually invoked as a script.
20
+ // =============================================================================
21
+ // Store/DB lifecycle (no legacy singletons in store.ts)
22
+ // =============================================================================
23
+ let store = null;
24
+ let storeDbPathOverride;
25
+ let currentIndexName = "index";
26
+ function getStore() {
27
+ if (!store) {
28
+ store = createStore(storeDbPathOverride);
29
+ // Sync YAML config into SQLite store_collections so store.ts reads from DB
30
+ try {
31
+ const activeModels = ensureModelsConfiguredForCli();
32
+ const config = loadConfig();
33
+ syncConfigToDb(store.db, config);
34
+ setDefaultLlamaCpp(new LlamaCpp({
35
+ embedModel: activeModels.embed,
36
+ generateModel: activeModels.generate,
37
+ rerankModel: activeModels.rerank,
38
+ }));
39
+ }
40
+ catch {
41
+ // Config may not exist yet — that's fine, DB works without it
42
+ }
43
+ }
44
+ return store;
45
+ }
46
+ function getDb() {
47
+ return getStore().db;
48
+ }
49
+ /** Re-sync YAML config into SQLite after CLI mutations (add/remove/rename collection, context changes) */
50
+ function resyncConfig() {
51
+ const s = getStore();
52
+ try {
53
+ const config = loadConfig();
54
+ // Clear config hash to force re-sync
55
+ s.db.prepare(`DELETE FROM store_config WHERE key = 'config_hash'`).run();
56
+ syncConfigToDb(s.db, config);
57
+ }
58
+ catch {
59
+ // Config may not exist — that's fine
60
+ }
61
+ }
62
+ function closeDb() {
63
+ if (store) {
64
+ store.close();
65
+ store = null;
66
+ }
67
+ }
68
+ function getDbPath() {
69
+ return store?.dbPath ?? storeDbPathOverride ?? getDefaultDbPath();
70
+ }
71
+ function getActiveIndexName() {
72
+ return currentIndexName;
73
+ }
74
+ function setIndexName(name) {
75
+ let normalizedName = name;
76
+ // Normalize relative paths to prevent malformed database paths
77
+ if (name && name.includes('/')) {
78
+ const absolutePath = pathResolve(process.cwd(), name);
79
+ // Replace path separators with underscores to create a valid filename
80
+ normalizedName = absolutePath.replace(/\//g, '_').replace(/^_/, '');
81
+ }
82
+ currentIndexName = normalizedName || "index";
83
+ storeDbPathOverride = normalizedName ? getDefaultDbPath(normalizedName) : undefined;
84
+ // Reset open handle so next use opens the new index
85
+ closeDb();
86
+ }
87
+ function ensureVecTable(_db, dimensions) {
88
+ // Store owns the DB; ignore `_db` and ensure vec table on the active store
89
+ getStore().ensureVecTable(dimensions);
90
+ }
91
+ // Terminal colors (respects NO_COLOR env)
92
+ const useColor = !process.env.NO_COLOR && process.stdout.isTTY;
93
+ const c = {
94
+ reset: useColor ? "\x1b[0m" : "",
95
+ dim: useColor ? "\x1b[2m" : "",
96
+ bold: useColor ? "\x1b[1m" : "",
97
+ cyan: useColor ? "\x1b[36m" : "",
98
+ yellow: useColor ? "\x1b[33m" : "",
99
+ green: useColor ? "\x1b[32m" : "",
100
+ magenta: useColor ? "\x1b[35m" : "",
101
+ blue: useColor ? "\x1b[34m" : "",
102
+ };
103
+ // Terminal cursor control
104
+ const cursor = {
105
+ hide() { process.stderr.write('\x1b[?25l'); },
106
+ show() { process.stderr.write('\x1b[?25h'); },
107
+ };
108
+ async function flushWritable(stream) {
109
+ await new Promise((resolve) => {
110
+ stream.write("", () => resolve());
111
+ });
112
+ }
113
+ /**
114
+ * Finish a successful CLI command after output has been flushed.
115
+ *
116
+ * We deliberately do NOT call `process.exit(0)`. `process.exit()` skips
117
+ * Node's `beforeExit` event, and node-llama-cpp registers a `beforeExit` hook
118
+ * that auto-disposes its native handles. On darwin, without that hook firing,
119
+ * libggml-metal's static `ggml_metal_device` destructor asserts on a
120
+ * non-empty residency-set collection during `__cxa_finalize_ranges` and
121
+ * dumps a multi-kB backtrace (upstream ggml-org/llama.cpp#22593, fix open as
122
+ * PR #22595). Empirically, even with explicit `disposeDefaultLlamaCpp()` the
123
+ * direct `process.exit(0)` path still trips the assertion — letting the
124
+ * event loop drain naturally is what actually clears the rsets.
125
+ *
126
+ * So: set `process.exitCode = 0` and return. The main module finishes, the
127
+ * event loop drains, `beforeExit` fires, native resources tear down in
128
+ * order, and the process exits cleanly. The `GGML_METAL_NO_RESIDENCY=1` env
129
+ * var that `bin/qmd` exports is a defense-in-depth safety net for paths
130
+ * that still call `process.exit()` after loading the native binding
131
+ * (signal handlers, error paths, `bun test`).
132
+ *
133
+ * If the caller passes an explicit `exit` for testability, we honor it —
134
+ * the lifecycle tests verify the legacy flush → cleanup → exit ordering.
135
+ * Production callers must not pass `exit`.
136
+ */
137
+ export async function finishSuccessfulCliCommand(options) {
138
+ const stderr = options.stderr ?? process.stderr;
139
+ await flushWritable(options.stdout ?? process.stdout);
140
+ try {
141
+ await (options.cleanup ?? disposeDefaultLlamaCpp)();
142
+ }
143
+ catch (error) {
144
+ stderr.write(`QMD Warning: cleanup after successful output failed (${error instanceof Error ? error.message : String(error)}); exiting 0 because command output completed.\n`);
145
+ }
146
+ await flushWritable(stderr);
147
+ if (options.exit) {
148
+ options.exit(0);
149
+ return;
150
+ }
151
+ process.exitCode = 0;
152
+ }
153
+ // Ensure cursor is restored on exit
154
+ process.on('SIGINT', () => { cursor.show(); process.exit(130); });
155
+ process.on('SIGTERM', () => { cursor.show(); process.exit(143); });
156
+ // Terminal progress bar using OSC 9;4 escape sequence (TTY only)
157
+ const isTTY = process.stderr.isTTY;
158
+ const progress = {
159
+ set(percent) {
160
+ if (isTTY)
161
+ process.stderr.write(`\x1b]9;4;1;${Math.round(percent)}\x07`);
162
+ },
163
+ clear() {
164
+ if (isTTY)
165
+ process.stderr.write(`\x1b]9;4;0\x07`);
166
+ },
167
+ indeterminate() {
168
+ if (isTTY)
169
+ process.stderr.write(`\x1b]9;4;3\x07`);
170
+ },
171
+ error() {
172
+ if (isTTY)
173
+ process.stderr.write(`\x1b]9;4;2\x07`);
174
+ },
175
+ };
176
+ // Format seconds into human-readable ETA
177
+ function formatETA(seconds) {
178
+ if (seconds < 60)
179
+ return `${Math.round(seconds)}s`;
180
+ if (seconds < 3600)
181
+ return `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`;
182
+ return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;
183
+ }
184
+ // Check index health and print warnings/tips
185
+ function checkIndexHealth(db, model = resolveEmbedModelForCli()) {
186
+ const { needsEmbedding, totalDocs, daysStale } = getIndexHealth(db, model);
187
+ // Warn if many docs need embedding
188
+ if (needsEmbedding > 0) {
189
+ const pct = Math.round((needsEmbedding / totalDocs) * 100);
190
+ if (pct >= 10) {
191
+ process.stderr.write(`${c.yellow}Warning: ${needsEmbedding} documents (${pct}%) need embeddings. Run 'qmd embed' for better results.${c.reset}\n`);
192
+ }
193
+ else {
194
+ process.stderr.write(`${c.dim}Tip: ${needsEmbedding} documents need embeddings. Run 'qmd embed' to index them.${c.reset}\n`);
195
+ }
196
+ }
197
+ // Check if most recent document update is older than 2 weeks
198
+ if (daysStale !== null && daysStale >= 14) {
199
+ process.stderr.write(`${c.dim}Tip: Index last updated ${daysStale} days ago. Run 'qmd update' to refresh.${c.reset}\n`);
200
+ }
201
+ }
202
+ // Compute unique display path for a document
203
+ // Always include at least parent folder + filename, add more parent dirs until unique
204
+ function computeDisplayPath(filepath, collectionPath, existingPaths) {
205
+ // Get path relative to collection (include collection dir name)
206
+ const collectionDir = collectionPath.replace(/\/$/, '');
207
+ const collectionName = collectionDir.split('/').pop() || '';
208
+ let relativePath;
209
+ if (filepath.startsWith(collectionDir + '/')) {
210
+ // filepath is under collection: use collection name + relative path
211
+ relativePath = collectionName + filepath.slice(collectionDir.length);
212
+ }
213
+ else {
214
+ // Fallback: just use the filepath
215
+ relativePath = filepath;
216
+ }
217
+ const parts = relativePath.split('/').filter(p => p.length > 0);
218
+ // Always include at least parent folder + filename (minimum 2 parts if available)
219
+ // Then add more parent dirs until unique
220
+ const minParts = Math.min(2, parts.length);
221
+ for (let i = parts.length - minParts; i >= 0; i--) {
222
+ const candidate = parts.slice(i).join('/');
223
+ if (!existingPaths.has(candidate)) {
224
+ return candidate;
225
+ }
226
+ }
227
+ // Absolute fallback: use full path (should be unique)
228
+ return filepath;
229
+ }
230
+ function formatTimeAgo(date) {
231
+ const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
232
+ if (seconds < 60)
233
+ return `${seconds}s ago`;
234
+ const minutes = Math.floor(seconds / 60);
235
+ if (minutes < 60)
236
+ return `${minutes}m ago`;
237
+ const hours = Math.floor(minutes / 60);
238
+ if (hours < 24)
239
+ return `${hours}h ago`;
240
+ const days = Math.floor(hours / 24);
241
+ return `${days}d ago`;
242
+ }
243
+ function formatMs(ms) {
244
+ if (ms < 1000)
245
+ return `${ms}ms`;
246
+ return `${(ms / 1000).toFixed(1)}s`;
247
+ }
248
+ function formatBytes(bytes) {
249
+ if (bytes < 1024)
250
+ return `${bytes} B`;
251
+ if (bytes < 1024 * 1024)
252
+ return `${(bytes / 1024).toFixed(1)} KB`;
253
+ if (bytes < 1024 * 1024 * 1024)
254
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
255
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
256
+ }
257
+ function sameDirectory(a, b) {
258
+ try {
259
+ return realpathSync(a) === realpathSync(b);
260
+ }
261
+ catch {
262
+ return pathResolve(a) === pathResolve(b);
263
+ }
264
+ }
265
+ function initLocalIndex() {
266
+ const cwd = getPwd();
267
+ if (sameDirectory(cwd, homedir())) {
268
+ throw new Error("Refusing to initialize a local index in $HOME. The global index is automatically created; run `qmd collection add <path>` for the global index, or run `qmd init` inside a project folder.");
269
+ }
270
+ const qmdDir = pathJoin(cwd, ".qmd");
271
+ const ymlPath = pathJoin(qmdDir, "index.yml");
272
+ const yamlPath = pathJoin(qmdDir, "index.yaml");
273
+ const configPath = existsSync(yamlPath) ? yamlPath : ymlPath;
274
+ const dbPath = pathJoin(qmdDir, "index.sqlite");
275
+ mkdirSync(qmdDir, { recursive: true });
276
+ setConfigSource({ configPath });
277
+ storeDbPathOverride = dbPath;
278
+ closeDb();
279
+ if (!existsSync(configPath)) {
280
+ saveConfig({
281
+ collections: {},
282
+ models: resolveModels(),
283
+ });
284
+ }
285
+ else {
286
+ ensureModelsConfiguredForCli();
287
+ }
288
+ const localStore = createStore(dbPath);
289
+ syncConfigToDb(localStore.db, loadConfig());
290
+ localStore.close();
291
+ console.log("ready to go with new local index");
292
+ }
293
+ function isForceCpuEnabled() {
294
+ const value = process.env.QMD_FORCE_CPU;
295
+ return !!value && !["false", "off", "none", "disable", "disabled", "0"].includes(value.trim().toLowerCase());
296
+ }
297
+ function configuredGpuModeLabel() {
298
+ return isForceCpuEnabled()
299
+ ? "CPU forced (QMD_FORCE_CPU)"
300
+ : (process.env.QMD_LLAMA_GPU?.trim() || "auto");
301
+ }
302
+ function summarizeDeviceNames(names) {
303
+ const counts = new Map();
304
+ for (const name of names) {
305
+ counts.set(name, (counts.get(name) || 0) + 1);
306
+ }
307
+ return Array.from(counts.entries())
308
+ .map(([name, count]) => count > 1 ? `${count}× ${name}` : name)
309
+ .join(", ");
310
+ }
311
+ function sanitizeDiagnosticMessage(message) {
312
+ const home = homedir();
313
+ return message
314
+ .replaceAll(home, "~")
315
+ .replaceAll(process.cwd(), ".")
316
+ .split("\n")
317
+ .map(line => line.trim())
318
+ .filter(Boolean)
319
+ .slice(0, 3)
320
+ .join("; ");
321
+ }
322
+ async function showStatus() {
323
+ const dbPath = getDbPath();
324
+ const db = getDb();
325
+ // Collections are defined in YAML; no duplicate cleanup needed.
326
+ // Collections are defined in YAML; no duplicate cleanup needed.
327
+ // Index size
328
+ let indexSize = 0;
329
+ try {
330
+ const stat = statSync(dbPath).size;
331
+ indexSize = stat;
332
+ }
333
+ catch { }
334
+ // Collections info (from YAML + database stats)
335
+ const collections = listCollections(db);
336
+ // Overall stats
337
+ const totalDocs = db.prepare(`SELECT COUNT(*) as count FROM documents WHERE active = 1`).get();
338
+ const vectorCount = db.prepare(`SELECT COUNT(*) as count FROM content_vectors`).get();
339
+ const statusEmbedModel = resolveEmbedModelForCli();
340
+ const needsEmbedding = getHashesNeedingEmbedding(db, undefined, statusEmbedModel);
341
+ // Most recent update across all collections
342
+ const mostRecent = db.prepare(`SELECT MAX(modified_at) as latest FROM documents WHERE active = 1`).get();
343
+ console.log(`${c.bold}QMD Status${c.reset}\n`);
344
+ console.log(`Index: ${dbPath}`);
345
+ console.log(`Size: ${formatBytes(indexSize)}`);
346
+ // MCP daemon status (check PID file liveness)
347
+ const mcpCacheDir = process.env.XDG_CACHE_HOME
348
+ ? resolve(process.env.XDG_CACHE_HOME, "qmd")
349
+ : resolve(homedir(), ".cache", "qmd");
350
+ const mcpPidPath = resolve(mcpCacheDir, "mcp.pid");
351
+ if (existsSync(mcpPidPath)) {
352
+ const mcpPid = parseInt(readFileSync(mcpPidPath, "utf-8").trim());
353
+ try {
354
+ process.kill(mcpPid, 0);
355
+ console.log(`MCP: ${c.green}running${c.reset} (PID ${mcpPid})`);
356
+ }
357
+ catch {
358
+ unlinkSync(mcpPidPath);
359
+ // Stale PID file cleaned up silently
360
+ }
361
+ }
362
+ console.log("");
363
+ console.log(`${c.bold}Documents${c.reset}`);
364
+ console.log(` Total: ${totalDocs.count} files indexed`);
365
+ console.log(` Vectors: ${vectorCount.count} embedded`);
366
+ if (needsEmbedding > 0) {
367
+ console.log(` ${c.yellow}Pending: ${needsEmbedding} need embedding${c.reset} (run 'qmd embed')`);
368
+ }
369
+ if (mostRecent.latest) {
370
+ const lastUpdate = new Date(mostRecent.latest);
371
+ console.log(` Updated: ${formatTimeAgo(lastUpdate)}`);
372
+ }
373
+ // Get all contexts grouped by collection (from YAML)
374
+ const allContexts = listAllContexts();
375
+ const contextsByCollection = new Map();
376
+ for (const ctx of allContexts) {
377
+ // Group contexts by collection name
378
+ if (!contextsByCollection.has(ctx.collection)) {
379
+ contextsByCollection.set(ctx.collection, []);
380
+ }
381
+ contextsByCollection.get(ctx.collection).push({
382
+ path_prefix: ctx.path,
383
+ context: ctx.context
384
+ });
385
+ }
386
+ // AST chunking status
387
+ try {
388
+ const { getASTStatus } = await import("../ast.js");
389
+ const ast = await getASTStatus();
390
+ console.log(`\n${c.bold}AST Chunking${c.reset}`);
391
+ if (ast.available) {
392
+ const ok = ast.languages.filter(l => l.available).map(l => l.language);
393
+ const fail = ast.languages.filter(l => !l.available);
394
+ console.log(` Status: ${c.green}active${c.reset}`);
395
+ console.log(` Languages: ${ok.join(", ")}`);
396
+ if (fail.length > 0) {
397
+ for (const f of fail) {
398
+ console.log(` ${c.yellow}Unavailable: ${f.language} (${f.error})${c.reset}`);
399
+ }
400
+ }
401
+ }
402
+ else {
403
+ console.log(` Status: ${c.yellow}unavailable${c.reset} (falling back to regex chunking)`);
404
+ for (const l of ast.languages) {
405
+ if (l.error)
406
+ console.log(` ${c.dim}${l.language}: ${l.error}${c.reset}`);
407
+ }
408
+ }
409
+ }
410
+ catch {
411
+ console.log(`\n${c.bold}AST Chunking${c.reset}`);
412
+ console.log(` Status: ${c.dim}not available${c.reset}`);
413
+ }
414
+ if (collections.length > 0) {
415
+ console.log(`\n${c.bold}Collections${c.reset}`);
416
+ for (const col of collections) {
417
+ const lastMod = col.last_modified ? formatTimeAgo(new Date(col.last_modified)) : "never";
418
+ const contexts = contextsByCollection.get(col.name) || [];
419
+ console.log(` ${c.cyan}${col.name}${c.reset} ${c.dim}(qmd://${col.name}/)${c.reset}`);
420
+ console.log(` ${c.dim}Pattern:${c.reset} ${col.glob_pattern}`);
421
+ console.log(` ${c.dim}Files:${c.reset} ${col.active_count} (updated ${lastMod})`);
422
+ if (contexts.length > 0) {
423
+ console.log(` ${c.dim}Contexts:${c.reset} ${contexts.length}`);
424
+ for (const ctx of contexts) {
425
+ // Handle both empty string and '/' as root context
426
+ const pathDisplay = (ctx.path_prefix === '' || ctx.path_prefix === '/') ? '/' : `/${ctx.path_prefix}`;
427
+ const contextPreview = ctx.context.length > 60
428
+ ? ctx.context.substring(0, 57) + '...'
429
+ : ctx.context;
430
+ console.log(` ${c.dim}${pathDisplay}:${c.reset} ${contextPreview}`);
431
+ }
432
+ }
433
+ }
434
+ // Show examples of virtual paths
435
+ console.log(`\n${c.bold}Examples${c.reset}`);
436
+ console.log(` ${c.dim}# List files in a collection${c.reset}`);
437
+ if (collections.length > 0 && collections[0]) {
438
+ console.log(` qmd ls ${collections[0].name}`);
439
+ }
440
+ console.log(` ${c.dim}# Get a document${c.reset}`);
441
+ if (collections.length > 0 && collections[0]) {
442
+ console.log(` qmd get qmd://${collections[0].name}/path/to/file.md`);
443
+ }
444
+ console.log(` ${c.dim}# Search within a collection${c.reset}`);
445
+ if (collections.length > 0 && collections[0]) {
446
+ console.log(` qmd search "query" -c ${collections[0].name}`);
447
+ }
448
+ }
449
+ else {
450
+ console.log(`\n${c.dim}No collections. Run 'qmd collection add .' to index markdown files.${c.reset}`);
451
+ }
452
+ // Models
453
+ {
454
+ // hf:org/repo/file.gguf → https://huggingface.co/org/repo
455
+ const hfLink = (uri) => {
456
+ const match = uri.match(/^hf:([^/]+\/[^/]+)\//);
457
+ return match ? `https://huggingface.co/${match[1]}` : uri;
458
+ };
459
+ const activeModels = resolveModelsForCli();
460
+ console.log(`\n${c.bold}Models${c.reset}`);
461
+ console.log(` Embedding: ${hfLink(activeModels.embed)}`);
462
+ console.log(` Reranking: ${hfLink(activeModels.rerank)}`);
463
+ console.log(` Generation: ${hfLink(activeModels.generate)}`);
464
+ }
465
+ // Tips section
466
+ const tips = [];
467
+ // Check for collections without context
468
+ const collectionsWithoutContext = collections.filter(col => {
469
+ const contexts = contextsByCollection.get(col.name) || [];
470
+ return contexts.length === 0;
471
+ });
472
+ if (collectionsWithoutContext.length > 0) {
473
+ const names = collectionsWithoutContext.map(c => c.name).slice(0, 3).join(', ');
474
+ const more = collectionsWithoutContext.length > 3 ? ` +${collectionsWithoutContext.length - 3} more` : '';
475
+ tips.push(`Add context to collections for better search results: ${names}${more}`);
476
+ tips.push(` ${c.dim}qmd context add qmd://<name>/ "What this collection contains"${c.reset}`);
477
+ tips.push(` ${c.dim}qmd context add qmd://<name>/meeting-notes "Weekly team meeting notes"${c.reset}`);
478
+ }
479
+ // Check for collections without update commands
480
+ const collectionsWithoutUpdate = collections.filter(col => {
481
+ const yamlCol = getCollectionFromYaml(col.name);
482
+ return !yamlCol?.update;
483
+ });
484
+ if (collectionsWithoutUpdate.length > 0 && collections.length > 1) {
485
+ const names = collectionsWithoutUpdate.map(c => c.name).slice(0, 3).join(', ');
486
+ const more = collectionsWithoutUpdate.length > 3 ? ` +${collectionsWithoutUpdate.length - 3} more` : '';
487
+ tips.push(`Add update commands to keep collections fresh: ${names}${more}`);
488
+ tips.push(` ${c.dim}qmd collection update-cmd <name> 'git stash && git pull --rebase --ff-only && git stash pop'${c.reset}`);
489
+ }
490
+ if (tips.length > 0) {
491
+ console.log(`\n${c.bold}Tips${c.reset}`);
492
+ for (const tip of tips) {
493
+ console.log(` ${tip}`);
494
+ }
495
+ }
496
+ closeDb();
497
+ }
498
+ async function updateCollections() {
499
+ await initializeKuromojiTokenizer(); // kuromoji: morphological analysis for CJK FTS
500
+ const db = getDb();
501
+ const storeInstance = getStore();
502
+ // Collections are defined in YAML; no duplicate cleanup needed.
503
+ // Clear Ollama cache on update
504
+ clearCache(db);
505
+ const collections = listCollections(db);
506
+ if (collections.length === 0) {
507
+ console.log(`${c.dim}No collections found. Run 'qmd collection add .' to index markdown files.${c.reset}`);
508
+ closeDb();
509
+ return;
510
+ }
511
+ console.log(`${c.bold}Updating ${collections.length} collection(s)...${c.reset}\n`);
512
+ for (let i = 0; i < collections.length; i++) {
513
+ const col = collections[i];
514
+ if (!col)
515
+ continue;
516
+ console.log(`${c.cyan}[${i + 1}/${collections.length}]${c.reset} ${c.bold}${col.name}${c.reset} ${c.dim}(${col.glob_pattern})${c.reset}`);
517
+ // Execute custom update command if specified in YAML
518
+ const yamlCol = getCollectionFromYaml(col.name);
519
+ if (yamlCol?.update) {
520
+ console.log(`${c.dim} Running update command: ${yamlCol.update}${c.reset}`);
521
+ try {
522
+ const proc = nodeSpawn("bash", ["-c", yamlCol.update], {
523
+ cwd: col.pwd,
524
+ stdio: ["ignore", "pipe", "pipe"],
525
+ });
526
+ const [output, errorOutput, exitCode] = await new Promise((resolve, reject) => {
527
+ let out = "";
528
+ let err = "";
529
+ proc.stdout?.on("data", (d) => { out += d.toString(); });
530
+ proc.stderr?.on("data", (d) => { err += d.toString(); });
531
+ proc.on("error", reject);
532
+ proc.on("close", (code) => resolve([out, err, code ?? 1]));
533
+ });
534
+ if (output.trim()) {
535
+ console.log(output.trim().split('\n').map(l => ` ${l}`).join('\n'));
536
+ }
537
+ if (errorOutput.trim()) {
538
+ console.log(errorOutput.trim().split('\n').map(l => ` ${l}`).join('\n'));
539
+ }
540
+ if (exitCode !== 0) {
541
+ console.log(`${c.yellow}✗ Update command failed with exit code ${exitCode}${c.reset}`);
542
+ process.exit(exitCode);
543
+ }
544
+ }
545
+ catch (err) {
546
+ console.log(`${c.yellow}✗ Update command failed: ${err}${c.reset}`);
547
+ process.exit(1);
548
+ }
549
+ }
550
+ const startTime = Date.now();
551
+ console.log(`Collection: ${col.pwd} (${col.glob_pattern})`);
552
+ progress.indeterminate();
553
+ const result = await reindexCollection(storeInstance, col.pwd, col.glob_pattern, col.name, {
554
+ ignorePatterns: yamlCol?.ignore,
555
+ onProgress: (info) => {
556
+ progress.set((info.current / info.total) * 100);
557
+ const elapsed = (Date.now() - startTime) / 1000;
558
+ const rate = info.current / elapsed;
559
+ const remaining = (info.total - info.current) / rate;
560
+ const eta = info.current > 2 ? ` ETA: ${formatETA(remaining)}` : "";
561
+ if (isTTY)
562
+ process.stderr.write(`\rIndexing: ${info.current}/${info.total}${eta} `);
563
+ },
564
+ });
565
+ progress.clear();
566
+ console.log(`\nIndexed: ${result.indexed} new, ${result.updated} updated, ${result.unchanged} unchanged, ${result.removed} removed`);
567
+ if (result.orphanedCleaned > 0) {
568
+ console.log(`Cleaned up ${result.orphanedCleaned} orphaned content hash(es)`);
569
+ }
570
+ console.log("");
571
+ }
572
+ // Check if any documents need embedding (show once at end)
573
+ const needsEmbedding = getHashesNeedingEmbedding(db);
574
+ closeDb();
575
+ console.log(`${c.green}✓ All collections updated.${c.reset}`);
576
+ if (needsEmbedding > 0) {
577
+ console.log(`\nRun 'qmd embed' to update embeddings (${needsEmbedding} unique hashes need vectors)`);
578
+ }
579
+ }
580
+ /**
581
+ * Detect which collection (if any) contains the given filesystem path.
582
+ * Returns { collectionId, collectionName, relativePath } or null if not in any collection.
583
+ */
584
+ function detectCollectionFromPath(db, fsPath) {
585
+ const realPath = getRealPath(fsPath);
586
+ // Find collections that this path is under from YAML
587
+ const allCollections = yamlListCollections();
588
+ // Find longest matching path
589
+ let bestMatch = null;
590
+ for (const coll of allCollections) {
591
+ if (realPath.startsWith(coll.path + '/') || realPath === coll.path) {
592
+ if (!bestMatch || coll.path.length > bestMatch.path.length) {
593
+ bestMatch = { name: coll.name, path: coll.path };
594
+ }
595
+ }
596
+ }
597
+ if (!bestMatch)
598
+ return null;
599
+ // Calculate relative path
600
+ let relativePath = realPath;
601
+ if (relativePath.startsWith(bestMatch.path + '/')) {
602
+ relativePath = relativePath.slice(bestMatch.path.length + 1);
603
+ }
604
+ else if (relativePath === bestMatch.path) {
605
+ relativePath = '';
606
+ }
607
+ return {
608
+ collectionName: bestMatch.name,
609
+ relativePath
610
+ };
611
+ }
612
+ async function contextAdd(pathArg, contextText) {
613
+ const db = getDb();
614
+ // Handle "/" as global context (applies to all collections)
615
+ if (pathArg === '/') {
616
+ setGlobalContext(contextText);
617
+ resyncConfig();
618
+ console.log(`${c.green}✓${c.reset} Set global context`);
619
+ console.log(`${c.dim}Context: ${contextText}${c.reset}`);
620
+ closeDb();
621
+ return;
622
+ }
623
+ // Resolve path - defaults to current directory if not provided
624
+ let fsPath = pathArg || '.';
625
+ if (fsPath === '.' || fsPath === './') {
626
+ fsPath = getPwd();
627
+ }
628
+ else if (fsPath.startsWith('~/')) {
629
+ fsPath = homedir() + fsPath.slice(1);
630
+ }
631
+ else if (!fsPath.startsWith('/') && !fsPath.startsWith('qmd://')) {
632
+ fsPath = resolve(getPwd(), fsPath);
633
+ }
634
+ // Handle virtual paths (qmd://collection/path)
635
+ if (isVirtualPath(fsPath)) {
636
+ const parsed = parseVirtualPath(fsPath);
637
+ if (!parsed) {
638
+ console.error(`${c.yellow}Invalid virtual path: ${fsPath}${c.reset}`);
639
+ process.exit(1);
640
+ }
641
+ const coll = getCollectionFromYaml(parsed.collectionName);
642
+ if (!coll) {
643
+ console.error(`${c.yellow}Collection not found: ${parsed.collectionName}${c.reset}`);
644
+ process.exit(1);
645
+ }
646
+ yamlAddContext(parsed.collectionName, parsed.path, contextText);
647
+ resyncConfig();
648
+ const displayPath = parsed.path
649
+ ? `qmd://${parsed.collectionName}/${parsed.path}`
650
+ : `qmd://${parsed.collectionName}/ (collection root)`;
651
+ console.log(`${c.green}✓${c.reset} Added context for: ${displayPath}`);
652
+ console.log(`${c.dim}Context: ${contextText}${c.reset}`);
653
+ closeDb();
654
+ return;
655
+ }
656
+ // Detect collection from filesystem path
657
+ const detected = detectCollectionFromPath(db, fsPath);
658
+ if (!detected) {
659
+ console.error(`${c.yellow}Path is not in any indexed collection: ${fsPath}${c.reset}`);
660
+ console.error(`${c.dim}Run 'qmd status' to see indexed collections${c.reset}`);
661
+ process.exit(1);
662
+ }
663
+ yamlAddContext(detected.collectionName, detected.relativePath, contextText);
664
+ resyncConfig();
665
+ const displayPath = detected.relativePath ? `qmd://${detected.collectionName}/${detected.relativePath}` : `qmd://${detected.collectionName}/`;
666
+ console.log(`${c.green}✓${c.reset} Added context for: ${displayPath}`);
667
+ console.log(`${c.dim}Context: ${contextText}${c.reset}`);
668
+ closeDb();
669
+ }
670
+ function contextList() {
671
+ const db = getDb();
672
+ const allContexts = listAllContexts();
673
+ if (allContexts.length === 0) {
674
+ console.log(`${c.dim}No contexts configured. Use 'qmd context add' to add one.${c.reset}`);
675
+ closeDb();
676
+ return;
677
+ }
678
+ console.log(`\n${c.bold}Configured Contexts${c.reset}\n`);
679
+ let lastCollection = '';
680
+ for (const ctx of allContexts) {
681
+ if (ctx.collection !== lastCollection) {
682
+ console.log(`${c.cyan}${ctx.collection}${c.reset}`);
683
+ lastCollection = ctx.collection;
684
+ }
685
+ const displayPath = ctx.path ? ` ${ctx.path}` : ' / (root)';
686
+ console.log(`${displayPath}`);
687
+ console.log(` ${c.dim}${ctx.context}${c.reset}`);
688
+ }
689
+ closeDb();
690
+ }
691
+ function contextRemove(pathArg) {
692
+ if (pathArg === '/') {
693
+ // Remove global context
694
+ setGlobalContext(undefined);
695
+ // Resync so SQLite store_config is updated
696
+ const s = getStore();
697
+ resyncConfig();
698
+ closeDb();
699
+ console.log(`${c.green}✓${c.reset} Removed global context`);
700
+ return;
701
+ }
702
+ // Handle virtual paths
703
+ if (isVirtualPath(pathArg)) {
704
+ const parsed = parseVirtualPath(pathArg);
705
+ if (!parsed) {
706
+ console.error(`${c.yellow}Invalid virtual path: ${pathArg}${c.reset}`);
707
+ process.exit(1);
708
+ }
709
+ const coll = getCollectionFromYaml(parsed.collectionName);
710
+ if (!coll) {
711
+ console.error(`${c.yellow}Collection not found: ${parsed.collectionName}${c.reset}`);
712
+ process.exit(1);
713
+ }
714
+ const success = yamlRemoveContext(coll.name, parsed.path);
715
+ if (!success) {
716
+ console.error(`${c.yellow}No context found for: ${pathArg}${c.reset}`);
717
+ process.exit(1);
718
+ }
719
+ console.log(`${c.green}✓${c.reset} Removed context for: ${pathArg}`);
720
+ return;
721
+ }
722
+ // Handle filesystem paths
723
+ let fsPath = pathArg;
724
+ if (fsPath === '.' || fsPath === './') {
725
+ fsPath = getPwd();
726
+ }
727
+ else if (fsPath.startsWith('~/')) {
728
+ fsPath = homedir() + fsPath.slice(1);
729
+ }
730
+ else if (!fsPath.startsWith('/')) {
731
+ fsPath = resolve(getPwd(), fsPath);
732
+ }
733
+ const db = getDb();
734
+ const detected = detectCollectionFromPath(db, fsPath);
735
+ closeDb();
736
+ if (!detected) {
737
+ console.error(`${c.yellow}Path is not in any indexed collection: ${fsPath}${c.reset}`);
738
+ process.exit(1);
739
+ }
740
+ const success = yamlRemoveContext(detected.collectionName, detected.relativePath);
741
+ if (!success) {
742
+ console.error(`${c.yellow}No context found for: qmd://${detected.collectionName}/${detected.relativePath}${c.reset}`);
743
+ process.exit(1);
744
+ }
745
+ console.log(`${c.green}✓${c.reset} Removed context for: qmd://${detected.collectionName}/${detected.relativePath}`);
746
+ }
747
+ /**
748
+ * Render an absolute filesystem path for human display under --full-path.
749
+ *
750
+ * If the path is the current working directory or a subpath of it, return a
751
+ * "./"-prefixed relative path so it is unambiguously a filesystem path (not a
752
+ * bare collection-relative string that could be confused for a `qmd://`
753
+ * fragment). Otherwise return the absolute realpath so symlinks resolve
754
+ * consistently. Returns `null` if the path could not be normalized — callers
755
+ * fall back to whatever they had before.
756
+ */
757
+ function renderFullPath(absolutePath, cwd = process.cwd()) {
758
+ let real;
759
+ try {
760
+ real = realpathSync(absolutePath);
761
+ }
762
+ catch {
763
+ real = absolutePath;
764
+ }
765
+ const cwdReal = (() => { try {
766
+ return realpathSync(cwd);
767
+ }
768
+ catch {
769
+ return cwd;
770
+ } })();
771
+ if (real === cwdReal)
772
+ return "./";
773
+ if (real.startsWith(cwdReal + "/")) {
774
+ const rel = relativePath(cwdReal, real);
775
+ if (rel && !rel.startsWith(".."))
776
+ return `./${rel}`;
777
+ }
778
+ return real;
779
+ }
780
+ function getDocument(filename, fromLine, maxLines, lineNumbers, fullPath = false) {
781
+ // Parse :line suffix from filename. Two forms:
782
+ // "file.md:100" -> start at line 100
783
+ // "file.md:100:40" -> start at line 100, read 40 lines
784
+ // The :// in virtual paths is never matched because we anchor digits to $.
785
+ // Explicit --from/-l flags always win over values parsed from the path.
786
+ let inputPath = filename;
787
+ const rangeMatch = inputPath.match(/:(\d+):(\d+)$/);
788
+ if (rangeMatch) {
789
+ if (fromLine === undefined)
790
+ fromLine = parseInt(rangeMatch[1], 10);
791
+ if (maxLines === undefined)
792
+ maxLines = parseInt(rangeMatch[2], 10);
793
+ inputPath = inputPath.slice(0, -rangeMatch[0].length);
794
+ }
795
+ else {
796
+ const colonMatch = inputPath.match(/:(\d+)$/);
797
+ if (colonMatch) {
798
+ const matched = colonMatch[1];
799
+ if (matched) {
800
+ if (fromLine === undefined)
801
+ fromLine = parseInt(matched, 10);
802
+ inputPath = inputPath.slice(0, -colonMatch[0].length);
803
+ }
804
+ }
805
+ }
806
+ if (fromLine !== undefined)
807
+ fromLine = Math.max(1, fromLine);
808
+ const parsedIndexPath = isVirtualPath(inputPath) ? parseVirtualPath(inputPath) : null;
809
+ if (parsedIndexPath?.indexName) {
810
+ setIndexName(parsedIndexPath.indexName);
811
+ setConfigIndexName(parsedIndexPath.indexName);
812
+ }
813
+ const db = getDb();
814
+ // Handle docid lookup (#abc123, abc123, "#abc123", "abc123", etc.)
815
+ if (isDocid(inputPath)) {
816
+ const docidMatch = findDocumentByDocid(db, inputPath);
817
+ if (docidMatch) {
818
+ inputPath = docidMatch.filepath;
819
+ }
820
+ else {
821
+ console.error(`Document not found: ${filename}`);
822
+ closeDb();
823
+ process.exit(1);
824
+ }
825
+ }
826
+ let doc = null;
827
+ let virtualPath;
828
+ // Handle virtual paths (qmd://collection/path)
829
+ if (isVirtualPath(inputPath)) {
830
+ const parsed = parseVirtualPath(inputPath);
831
+ if (!parsed) {
832
+ console.error(`Invalid virtual path: ${inputPath}`);
833
+ closeDb();
834
+ process.exit(1);
835
+ }
836
+ // Try exact match on collection + path
837
+ doc = db.prepare(`
838
+ SELECT d.collection as collectionName, d.path, content.doc as body
839
+ FROM documents d
840
+ JOIN content ON content.hash = d.hash
841
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
842
+ `).get(parsed.collectionName, parsed.path);
843
+ if (!doc) {
844
+ // Try fuzzy match by path ending
845
+ doc = db.prepare(`
846
+ SELECT d.collection as collectionName, d.path, content.doc as body
847
+ FROM documents d
848
+ JOIN content ON content.hash = d.hash
849
+ WHERE d.collection = ? AND d.path LIKE ? AND d.active = 1
850
+ LIMIT 1
851
+ `).get(parsed.collectionName, `%${parsed.path}`);
852
+ }
853
+ virtualPath = inputPath;
854
+ }
855
+ else {
856
+ // Try to interpret as collection/path format first (before filesystem path)
857
+ // If path is relative (no / or ~ prefix), check if first component is a collection name
858
+ if (!inputPath.startsWith('/') && !inputPath.startsWith('~')) {
859
+ const parts = inputPath.split('/');
860
+ if (parts.length >= 2) {
861
+ const possibleCollection = parts[0];
862
+ const possiblePath = parts.slice(1).join('/');
863
+ // Check if this collection exists
864
+ const collExists = possibleCollection ? db.prepare(`
865
+ SELECT 1 FROM documents WHERE collection = ? AND active = 1 LIMIT 1
866
+ `).get(possibleCollection) : null;
867
+ if (collExists) {
868
+ // Try exact match on collection + path
869
+ doc = db.prepare(`
870
+ SELECT d.collection as collectionName, d.path, content.doc as body
871
+ FROM documents d
872
+ JOIN content ON content.hash = d.hash
873
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
874
+ `).get(possibleCollection || "", possiblePath || "");
875
+ if (!doc) {
876
+ // Try fuzzy match by path ending
877
+ doc = db.prepare(`
878
+ SELECT d.collection as collectionName, d.path, content.doc as body
879
+ FROM documents d
880
+ JOIN content ON content.hash = d.hash
881
+ WHERE d.collection = ? AND d.path LIKE ? AND d.active = 1
882
+ LIMIT 1
883
+ `).get(possibleCollection || "", `%${possiblePath}`);
884
+ }
885
+ if (doc) {
886
+ virtualPath = buildVirtualPath(doc.collectionName, doc.path);
887
+ // Skip the filesystem path handling below
888
+ }
889
+ }
890
+ }
891
+ }
892
+ // If not found as collection/path, handle as filesystem paths
893
+ if (!doc) {
894
+ let fsPath = inputPath;
895
+ // Expand ~ to home directory
896
+ if (fsPath.startsWith('~/')) {
897
+ fsPath = homedir() + fsPath.slice(1);
898
+ }
899
+ else if (!fsPath.startsWith('/')) {
900
+ // Relative path - resolve from current directory
901
+ fsPath = resolve(getPwd(), fsPath);
902
+ }
903
+ fsPath = getRealPath(fsPath);
904
+ // Try to detect which collection contains this path
905
+ const detected = detectCollectionFromPath(db, fsPath);
906
+ if (detected) {
907
+ // Found collection - query by collection name + relative path
908
+ doc = db.prepare(`
909
+ SELECT d.collection as collectionName, d.path, content.doc as body
910
+ FROM documents d
911
+ JOIN content ON content.hash = d.hash
912
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
913
+ `).get(detected.collectionName, detected.relativePath);
914
+ }
915
+ // Fuzzy match by filename (last component of path)
916
+ if (!doc) {
917
+ const filename = inputPath.split('/').pop() || inputPath;
918
+ doc = db.prepare(`
919
+ SELECT d.collection as collectionName, d.path, content.doc as body
920
+ FROM documents d
921
+ JOIN content ON content.hash = d.hash
922
+ WHERE d.path LIKE ? AND d.active = 1
923
+ LIMIT 1
924
+ `).get(`%${filename}`);
925
+ }
926
+ if (doc) {
927
+ virtualPath = buildVirtualPath(doc.collectionName, doc.path);
928
+ }
929
+ else {
930
+ virtualPath = inputPath;
931
+ }
932
+ }
933
+ }
934
+ // Ensure doc is not null before proceeding
935
+ if (!doc) {
936
+ console.error(`Document not found: ${filename}`);
937
+ closeDb();
938
+ process.exit(1);
939
+ }
940
+ // Get context for this file
941
+ const context = getContextForPath(db, doc.collectionName, doc.path);
942
+ // Resolve the docid (first 6 chars of the content hash) so callers always
943
+ // know what they retrieved and can cite it back to `get`/`multi-get`.
944
+ const hashRow = db.prepare(`
945
+ SELECT d.hash as hash
946
+ FROM documents d
947
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
948
+ `).get(doc.collectionName, doc.path);
949
+ const docid = hashRow?.hash ? hashRow.hash.slice(0, 6) : undefined;
950
+ const canonicalPath = buildVirtualPath(doc.collectionName, doc.path);
951
+ // --full-path: show the on-disk path instead of the qmd:// URL + docid, when
952
+ // the file actually exists. Fall back to the canonical header otherwise.
953
+ let header;
954
+ if (fullPath) {
955
+ const fsPath = resolveVirtualPath(db, canonicalPath);
956
+ if (fsPath && existsSync(fsPath)) {
957
+ header = renderFullPath(fsPath);
958
+ }
959
+ else {
960
+ header = docid ? `${canonicalPath} #${docid}` : canonicalPath;
961
+ }
962
+ }
963
+ else {
964
+ header = docid ? `${canonicalPath} #${docid}` : canonicalPath;
965
+ }
966
+ let output = doc.body;
967
+ const startLine = fromLine || 1;
968
+ // Apply line filtering if specified
969
+ if (fromLine !== undefined || maxLines !== undefined) {
970
+ const lines = output.split('\n');
971
+ const start = startLine - 1; // Convert to 0-indexed
972
+ const end = maxLines !== undefined ? start + maxLines : lines.length;
973
+ output = lines.slice(start, end).join('\n');
974
+ }
975
+ // Line numbers are on by default (disable with --no-line-numbers) so the
976
+ // model can cite exact lines and request follow-up ranges via path:from:count.
977
+ if (lineNumbers) {
978
+ output = addLineNumbers(output, startLine);
979
+ }
980
+ // Header: identify the document (path + docid, or the on-disk path with
981
+ // --full-path), then optional context.
982
+ console.log(header);
983
+ if (context) {
984
+ console.log(`Folder Context: ${context}`);
985
+ }
986
+ console.log("---\n");
987
+ console.log(output);
988
+ closeDb();
989
+ }
990
+ // Multi-get: fetch multiple documents by glob pattern or comma-separated list
991
+ function multiGet(pattern, maxLines, maxBytes = DEFAULT_MULTI_GET_MAX_BYTES, format = "cli", lineNumbers = true, fullPath = false) {
992
+ const db = getDb();
993
+ // Check if it's a comma-separated list or a glob pattern
994
+ const isCommaSeparated = pattern.includes(',') && !pattern.includes('*') && !pattern.includes('?') && !pattern.includes('{');
995
+ let files;
996
+ if (isCommaSeparated) {
997
+ // Comma-separated list of files (can be virtual paths or relative paths)
998
+ const names = pattern.split(',').map(s => s.trim()).filter(Boolean);
999
+ files = [];
1000
+ for (const name of names) {
1001
+ let doc = null;
1002
+ // Handle virtual paths
1003
+ if (isVirtualPath(name)) {
1004
+ const parsed = parseVirtualPath(name);
1005
+ if (parsed) {
1006
+ // Try exact match on collection + path
1007
+ doc = db.prepare(`
1008
+ SELECT
1009
+ 'qmd://' || d.collection || '/' || d.path as virtual_path,
1010
+ LENGTH(content.doc) as body_length,
1011
+ d.collection,
1012
+ d.path
1013
+ FROM documents d
1014
+ JOIN content ON content.hash = d.hash
1015
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
1016
+ `).get(parsed.collectionName, parsed.path);
1017
+ }
1018
+ }
1019
+ else {
1020
+ // Try exact match on path
1021
+ doc = db.prepare(`
1022
+ SELECT
1023
+ 'qmd://' || d.collection || '/' || d.path as virtual_path,
1024
+ LENGTH(content.doc) as body_length,
1025
+ d.collection,
1026
+ d.path
1027
+ FROM documents d
1028
+ JOIN content ON content.hash = d.hash
1029
+ WHERE d.path = ? AND d.active = 1
1030
+ LIMIT 1
1031
+ `).get(name);
1032
+ // Try suffix match
1033
+ if (!doc) {
1034
+ doc = db.prepare(`
1035
+ SELECT
1036
+ 'qmd://' || d.collection || '/' || d.path as virtual_path,
1037
+ LENGTH(content.doc) as body_length,
1038
+ d.collection,
1039
+ d.path
1040
+ FROM documents d
1041
+ JOIN content ON content.hash = d.hash
1042
+ WHERE d.path LIKE ? AND d.active = 1
1043
+ LIMIT 1
1044
+ `).get(`%${name}`);
1045
+ }
1046
+ }
1047
+ if (doc) {
1048
+ files.push({
1049
+ filepath: doc.virtual_path,
1050
+ displayPath: doc.virtual_path,
1051
+ bodyLength: doc.body_length,
1052
+ collection: doc.collection,
1053
+ path: doc.path
1054
+ });
1055
+ }
1056
+ else {
1057
+ console.error(`File not found: ${name}`);
1058
+ }
1059
+ }
1060
+ }
1061
+ else {
1062
+ // Glob pattern - matchFilesByGlob now returns virtual paths
1063
+ files = matchFilesByGlob(db, pattern).map(f => ({
1064
+ ...f,
1065
+ collection: undefined, // Will be fetched later if needed
1066
+ path: undefined
1067
+ }));
1068
+ if (files.length === 0) {
1069
+ console.error(`No files matched pattern: ${pattern}`);
1070
+ closeDb();
1071
+ process.exit(1);
1072
+ }
1073
+ }
1074
+ // Collect results for structured output
1075
+ const results = [];
1076
+ for (const file of files) {
1077
+ // Parse virtual path to get collection info if not already available
1078
+ let collection = file.collection;
1079
+ let path = file.path;
1080
+ if (!collection || !path) {
1081
+ const parsed = parseVirtualPath(file.filepath);
1082
+ if (parsed) {
1083
+ collection = parsed.collectionName;
1084
+ path = parsed.path;
1085
+ }
1086
+ }
1087
+ // Get context using collection-scoped function
1088
+ const context = collection && path ? getContextForPath(db, collection, path) : null;
1089
+ // Resolve docid (first 6 chars of content hash) so every entry can be cited.
1090
+ const docidRow = collection && path ? db.prepare(`
1091
+ SELECT d.hash as hash
1092
+ FROM documents d
1093
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
1094
+ `).get(collection, path) : null;
1095
+ const docid = docidRow?.hash ? docidRow.hash.slice(0, 6) : undefined;
1096
+ // --full-path: resolve the on-disk path when it exists (else fall back).
1097
+ // Display as ./-prefixed relative path when under $PWD; absolute realpath
1098
+ // otherwise. See renderFullPath() for the policy.
1099
+ let fsPath;
1100
+ if (fullPath) {
1101
+ const resolved = resolveVirtualPath(db, file.filepath);
1102
+ if (resolved && existsSync(resolved))
1103
+ fsPath = renderFullPath(resolved);
1104
+ }
1105
+ // Check size limit
1106
+ if (file.bodyLength > maxBytes) {
1107
+ results.push({
1108
+ file: file.filepath,
1109
+ displayPath: file.displayPath,
1110
+ fsPath,
1111
+ docid,
1112
+ title: file.displayPath.split('/').pop() || file.displayPath,
1113
+ body: "",
1114
+ context,
1115
+ skipped: true,
1116
+ skipReason: `File too large (${Math.round(file.bodyLength / 1024)}KB > ${Math.round(maxBytes / 1024)}KB). Use 'qmd get ${file.displayPath}' to retrieve.`,
1117
+ });
1118
+ continue;
1119
+ }
1120
+ // Fetch document content using collection and path
1121
+ if (!collection || !path)
1122
+ continue;
1123
+ const doc = db.prepare(`
1124
+ SELECT content.doc as body, d.title
1125
+ FROM documents d
1126
+ JOIN content ON content.hash = d.hash
1127
+ WHERE d.collection = ? AND d.path = ? AND d.active = 1
1128
+ `).get(collection, path);
1129
+ if (!doc)
1130
+ continue;
1131
+ let body = doc.body;
1132
+ // Apply line limit if specified
1133
+ if (maxLines !== undefined) {
1134
+ const lines = body.split('\n');
1135
+ body = lines.slice(0, maxLines).join('\n');
1136
+ if (lines.length > maxLines) {
1137
+ body += `\n\n[... truncated ${lines.length - maxLines} more lines]`;
1138
+ }
1139
+ }
1140
+ // Line numbers on by default (disable with --no-line-numbers).
1141
+ if (lineNumbers) {
1142
+ body = addLineNumbers(body);
1143
+ }
1144
+ results.push({
1145
+ file: file.filepath,
1146
+ displayPath: file.displayPath,
1147
+ fsPath,
1148
+ docid,
1149
+ title: doc.title || file.displayPath.split('/').pop() || file.displayPath,
1150
+ body,
1151
+ context,
1152
+ skipped: false,
1153
+ });
1154
+ }
1155
+ closeDb();
1156
+ // --full-path replaces the qmd:// path + docid with the on-disk path (when it
1157
+ // resolved). Per result: pick the identifier and whether to show the docid.
1158
+ const identOf = (r) => (fullPath && r.fsPath) ? r.fsPath : r.displayPath;
1159
+ const docidOf = (r) => (fullPath && r.fsPath) ? undefined : r.docid;
1160
+ // Output based on format
1161
+ if (format === "json") {
1162
+ const output = results.map(r => {
1163
+ const docidVal = docidOf(r);
1164
+ return {
1165
+ file: identOf(r),
1166
+ ...(docidVal && { docid: `#${docidVal}` }),
1167
+ title: r.title,
1168
+ ...(r.context && { context: r.context }),
1169
+ ...(r.skipped ? { skipped: true, reason: r.skipReason } : { body: r.body }),
1170
+ };
1171
+ });
1172
+ console.log(JSON.stringify(output, null, 2));
1173
+ }
1174
+ else if (format === "csv") {
1175
+ const escapeField = (val) => {
1176
+ if (val === null || val === undefined)
1177
+ return "";
1178
+ const str = String(val);
1179
+ if (str.includes(",") || str.includes('"') || str.includes("\n")) {
1180
+ return `"${str.replace(/"/g, '""')}"`;
1181
+ }
1182
+ return str;
1183
+ };
1184
+ console.log("docid,file,title,context,skipped,body");
1185
+ for (const r of results) {
1186
+ const docidVal = docidOf(r);
1187
+ console.log([docidVal ? `#${docidVal}` : "", identOf(r), r.title, r.context, r.skipped ? "true" : "false", r.skipped ? r.skipReason : r.body].map(escapeField).join(","));
1188
+ }
1189
+ }
1190
+ else if (format === "files") {
1191
+ for (const r of results) {
1192
+ const docidVal = docidOf(r);
1193
+ const id = docidVal ? `#${docidVal} ` : "";
1194
+ const ctx = r.context ? `,"${r.context.replace(/"/g, '""')}"` : "";
1195
+ const status = r.skipped ? "[SKIPPED]" : "";
1196
+ console.log(`${id}${identOf(r)}${ctx}${status ? `,${status}` : ""}`);
1197
+ }
1198
+ }
1199
+ else if (format === "md") {
1200
+ for (const r of results) {
1201
+ const docidVal = docidOf(r);
1202
+ console.log(`## ${identOf(r)}\n`);
1203
+ if (docidVal)
1204
+ console.log(`**docid:** \`#${docidVal}\`\n`);
1205
+ if (r.title && r.title !== r.displayPath)
1206
+ console.log(`**Title:** ${r.title}\n`);
1207
+ if (r.context)
1208
+ console.log(`**Context:** ${r.context}\n`);
1209
+ if (r.skipped) {
1210
+ console.log(`> ${r.skipReason}\n`);
1211
+ }
1212
+ else {
1213
+ console.log("```");
1214
+ console.log(r.body);
1215
+ console.log("```\n");
1216
+ }
1217
+ }
1218
+ }
1219
+ else if (format === "xml") {
1220
+ console.log('<?xml version="1.0" encoding="UTF-8"?>');
1221
+ console.log("<documents>");
1222
+ for (const r of results) {
1223
+ const docidVal = docidOf(r);
1224
+ const docidAttr = docidVal ? ` docid="#${docidVal}"` : "";
1225
+ console.log(` <document${docidAttr}>`);
1226
+ console.log(` <file>${escapeXml(identOf(r))}</file>`);
1227
+ console.log(` <title>${escapeXml(r.title)}</title>`);
1228
+ if (r.context)
1229
+ console.log(` <context>${escapeXml(r.context)}</context>`);
1230
+ if (r.skipped) {
1231
+ console.log(` <skipped>true</skipped>`);
1232
+ console.log(` <reason>${escapeXml(r.skipReason || "")}</reason>`);
1233
+ }
1234
+ else {
1235
+ console.log(` <body>${escapeXml(r.body)}</body>`);
1236
+ }
1237
+ console.log(" </document>");
1238
+ }
1239
+ console.log("</documents>");
1240
+ }
1241
+ else {
1242
+ // CLI format (default)
1243
+ for (const r of results) {
1244
+ const docidVal = docidOf(r);
1245
+ const id = docidVal ? ` #${docidVal}` : "";
1246
+ console.log(`\n${'='.repeat(60)}`);
1247
+ console.log(`File: ${identOf(r)}${id}`);
1248
+ console.log(`${'='.repeat(60)}\n`);
1249
+ if (r.skipped) {
1250
+ console.log(`[SKIPPED: ${r.skipReason}]`);
1251
+ continue;
1252
+ }
1253
+ if (r.context) {
1254
+ console.log(`Folder Context: ${r.context}\n---\n`);
1255
+ }
1256
+ console.log(r.body);
1257
+ }
1258
+ }
1259
+ }
1260
+ // List files in virtual file tree
1261
+ function listFiles(pathArg) {
1262
+ const db = getDb();
1263
+ if (!pathArg) {
1264
+ // No argument - list all collections
1265
+ const yamlCollections = yamlListCollections();
1266
+ if (yamlCollections.length === 0) {
1267
+ console.log("No collections found. Run 'qmd collection add .' to index files.");
1268
+ closeDb();
1269
+ return;
1270
+ }
1271
+ // Get file counts from database for each collection
1272
+ const collections = yamlCollections.map(coll => {
1273
+ const stats = db.prepare(`
1274
+ SELECT COUNT(*) as file_count
1275
+ FROM documents d
1276
+ WHERE d.collection = ? AND d.active = 1
1277
+ `).get(coll.name);
1278
+ return {
1279
+ name: coll.name,
1280
+ file_count: stats?.file_count || 0
1281
+ };
1282
+ });
1283
+ console.log(`${c.bold}Collections:${c.reset}\n`);
1284
+ for (const coll of collections) {
1285
+ console.log(` ${c.dim}qmd://${c.reset}${c.cyan}${coll.name}/${c.reset} ${c.dim}(${coll.file_count} files)${c.reset}`);
1286
+ }
1287
+ closeDb();
1288
+ return;
1289
+ }
1290
+ // Parse the path argument
1291
+ let collectionName;
1292
+ let pathPrefix = null;
1293
+ const afterScheme = pathArg.startsWith('qmd://') ? pathArg.slice('qmd://'.length) : null;
1294
+ if (afterScheme !== null && afterScheme.startsWith('/')) {
1295
+ // Absolute-path collection: qmd:///Users/foo/bar — normalizeVirtualPath would corrupt
1296
+ // this by stripping all leading slashes, so bypass parseVirtualPath entirely.
1297
+ const normalized = afterScheme.replace(/\/$/, '');
1298
+ const allColls = yamlListCollections();
1299
+ const match = allColls
1300
+ .filter(c => normalized === c.name || normalized.startsWith(c.name + '/'))
1301
+ .sort((a, b) => b.name.length - a.name.length)[0];
1302
+ if (match) {
1303
+ collectionName = match.name;
1304
+ const rest = normalized.slice(match.name.length).replace(/^\//, '');
1305
+ pathPrefix = rest || null;
1306
+ }
1307
+ else {
1308
+ // Preserve the historical qmd:////collection/path alias behavior for normal
1309
+ // collections when no absolute-path collection matches.
1310
+ const parsed = parseVirtualPath(pathArg);
1311
+ if (!parsed) {
1312
+ console.error(`Invalid virtual path: ${pathArg}`);
1313
+ closeDb();
1314
+ process.exit(1);
1315
+ }
1316
+ collectionName = parsed.collectionName;
1317
+ pathPrefix = parsed.path;
1318
+ }
1319
+ }
1320
+ else if (afterScheme !== null) {
1321
+ // Normal virtual path: qmd://collection-name/path
1322
+ const parsed = parseVirtualPath(pathArg);
1323
+ if (!parsed) {
1324
+ console.error(`Invalid virtual path: ${pathArg}`);
1325
+ closeDb();
1326
+ process.exit(1);
1327
+ }
1328
+ collectionName = parsed.collectionName;
1329
+ pathPrefix = parsed.path;
1330
+ }
1331
+ else if (pathArg.startsWith('/')) {
1332
+ // Raw absolute filesystem path — longest-prefix match against collection names
1333
+ const normalized = pathArg.replace(/\/$/, '');
1334
+ const allColls = yamlListCollections();
1335
+ const match = allColls
1336
+ .filter(c => normalized === c.name || normalized.startsWith(c.name + '/'))
1337
+ .sort((a, b) => b.name.length - a.name.length)[0];
1338
+ if (match) {
1339
+ collectionName = match.name;
1340
+ const rest = normalized.slice(match.name.length).replace(/^\//, '');
1341
+ pathPrefix = rest || null;
1342
+ }
1343
+ else {
1344
+ collectionName = normalized;
1345
+ }
1346
+ }
1347
+ else {
1348
+ // Short collection name or name/path
1349
+ const parts = pathArg.split('/');
1350
+ collectionName = parts[0] || '';
1351
+ if (parts.length > 1) {
1352
+ pathPrefix = parts.slice(1).join('/');
1353
+ }
1354
+ }
1355
+ // Get the collection
1356
+ const coll = getCollectionFromYaml(collectionName);
1357
+ if (!coll) {
1358
+ console.error(`Collection not found: ${collectionName}`);
1359
+ console.error(`Run 'qmd ls' to see available collections.`);
1360
+ closeDb();
1361
+ process.exit(1);
1362
+ }
1363
+ // List files in the collection with size and modification time
1364
+ let query;
1365
+ let params;
1366
+ if (pathPrefix) {
1367
+ // List files under a specific path
1368
+ query = `
1369
+ SELECT d.path, d.title, d.modified_at, LENGTH(ct.doc) as size
1370
+ FROM documents d
1371
+ JOIN content ct ON d.hash = ct.hash
1372
+ WHERE d.collection = ? AND d.path LIKE ? AND d.active = 1
1373
+ ORDER BY d.path
1374
+ `;
1375
+ params = [coll.name, `${pathPrefix}%`];
1376
+ }
1377
+ else {
1378
+ // List all files in the collection
1379
+ query = `
1380
+ SELECT d.path, d.title, d.modified_at, LENGTH(ct.doc) as size
1381
+ FROM documents d
1382
+ JOIN content ct ON d.hash = ct.hash
1383
+ WHERE d.collection = ? AND d.active = 1
1384
+ ORDER BY d.path
1385
+ `;
1386
+ params = [coll.name];
1387
+ }
1388
+ const files = db.prepare(query).all(...params);
1389
+ if (files.length === 0) {
1390
+ if (pathPrefix) {
1391
+ console.log(`No files found under qmd://${collectionName}/${pathPrefix}`);
1392
+ }
1393
+ else {
1394
+ console.log(`No files found in collection: ${collectionName}`);
1395
+ }
1396
+ closeDb();
1397
+ return;
1398
+ }
1399
+ // Calculate max widths for alignment
1400
+ const maxSize = Math.max(...files.map(f => formatBytes(f.size).length));
1401
+ // Output in ls -l style
1402
+ for (const file of files) {
1403
+ const sizeStr = formatBytes(file.size).padStart(maxSize);
1404
+ const date = new Date(file.modified_at);
1405
+ const timeStr = formatLsTime(date);
1406
+ // Dim the qmd:// prefix, highlight the filename
1407
+ console.log(`${sizeStr} ${timeStr} ${c.dim}qmd://${collectionName}/${c.reset}${c.cyan}${file.path}${c.reset}`);
1408
+ }
1409
+ closeDb();
1410
+ }
1411
+ // Format date/time like ls -l
1412
+ function formatLsTime(date) {
1413
+ const now = new Date();
1414
+ const sixMonthsAgo = new Date(now.getTime() - 6 * 30 * 24 * 60 * 60 * 1000);
1415
+ const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
1416
+ const month = months[date.getMonth()];
1417
+ const day = date.getDate().toString().padStart(2, ' ');
1418
+ // If file is older than 6 months, show year instead of time
1419
+ if (date < sixMonthsAgo) {
1420
+ const year = date.getFullYear();
1421
+ return `${month} ${day} ${year}`;
1422
+ }
1423
+ else {
1424
+ const hours = date.getHours().toString().padStart(2, '0');
1425
+ const minutes = date.getMinutes().toString().padStart(2, '0');
1426
+ return `${month} ${day} ${hours}:${minutes}`;
1427
+ }
1428
+ }
1429
+ // Collection management commands
1430
+ function collectionList() {
1431
+ const db = getDb();
1432
+ const collections = listCollections(db);
1433
+ if (collections.length === 0) {
1434
+ console.log("No collections found. Run 'qmd collection add .' to create one.");
1435
+ closeDb();
1436
+ return;
1437
+ }
1438
+ console.log(`${c.bold}Collections (${collections.length}):${c.reset}\n`);
1439
+ for (const coll of collections) {
1440
+ const updatedAt = coll.last_modified ? new Date(coll.last_modified) : new Date();
1441
+ const timeAgo = formatTimeAgo(updatedAt);
1442
+ // Get YAML config to check includeByDefault
1443
+ const yamlColl = getCollectionFromYaml(coll.name);
1444
+ const excluded = yamlColl?.includeByDefault === false;
1445
+ const excludeTag = excluded ? ` ${c.yellow}[excluded]${c.reset}` : '';
1446
+ console.log(`${c.cyan}${coll.name}${c.reset} ${c.dim}(qmd://${coll.name}/)${c.reset}${excludeTag}`);
1447
+ console.log(` ${c.dim}Pattern:${c.reset} ${coll.glob_pattern}`);
1448
+ if (yamlColl?.ignore?.length) {
1449
+ console.log(` ${c.dim}Ignore:${c.reset} ${yamlColl.ignore.join(', ')}`);
1450
+ }
1451
+ console.log(` ${c.dim}Files:${c.reset} ${coll.active_count}`);
1452
+ console.log(` ${c.dim}Updated:${c.reset} ${timeAgo}`);
1453
+ console.log();
1454
+ }
1455
+ closeDb();
1456
+ }
1457
+ async function collectionAdd(pwd, globPattern, name) {
1458
+ // If name not provided, generate from pwd basename
1459
+ let collName = name;
1460
+ if (!collName) {
1461
+ const parts = pwd.split('/').filter(Boolean);
1462
+ collName = parts[parts.length - 1] || 'root';
1463
+ }
1464
+ // Check if collection with this name already exists in YAML
1465
+ const existing = getCollectionFromYaml(collName);
1466
+ if (existing) {
1467
+ console.error(`${c.yellow}Collection '${collName}' already exists.${c.reset}`);
1468
+ console.error(`Use a different name with --name <name>`);
1469
+ process.exit(1);
1470
+ }
1471
+ // Check if a collection with this pwd+glob already exists in YAML
1472
+ const allCollections = yamlListCollections();
1473
+ const existingPwdGlob = allCollections.find(c => c.path === pwd && c.pattern === globPattern);
1474
+ if (existingPwdGlob) {
1475
+ console.error(`${c.yellow}A collection already exists for this path and pattern:${c.reset}`);
1476
+ console.error(` Name: ${existingPwdGlob.name} (qmd://${existingPwdGlob.name}/)`);
1477
+ console.error(` Pattern: ${globPattern}`);
1478
+ console.error(`\nUse 'qmd update' to re-index it, or remove it first with 'qmd collection remove ${existingPwdGlob.name}'`);
1479
+ process.exit(1);
1480
+ }
1481
+ // Add to YAML config + sync to SQLite
1482
+ const { addCollection } = await import("../collections.js");
1483
+ addCollection(collName, pwd, globPattern);
1484
+ resyncConfig();
1485
+ // Create the collection and index files
1486
+ console.log(`Creating collection '${collName}'...`);
1487
+ const newColl = getCollectionFromYaml(collName);
1488
+ await indexFiles(pwd, globPattern, collName, false, newColl?.ignore);
1489
+ console.log(`${c.green}✓${c.reset} Collection '${collName}' created successfully`);
1490
+ }
1491
+ function collectionRemove(name) {
1492
+ // Check if collection exists in YAML
1493
+ const coll = getCollectionFromYaml(name);
1494
+ if (!coll) {
1495
+ console.error(`${c.yellow}Collection not found: ${name}${c.reset}`);
1496
+ console.error(`Run 'qmd collection list' to see available collections.`);
1497
+ process.exit(1);
1498
+ }
1499
+ const db = getDb();
1500
+ const result = removeCollection(db, name);
1501
+ // Also remove from YAML config
1502
+ yamlRemoveCollectionFn(name);
1503
+ closeDb();
1504
+ console.log(`${c.green}✓${c.reset} Removed collection '${name}'`);
1505
+ console.log(` Deleted ${result.deletedDocs} documents`);
1506
+ if (result.cleanedHashes > 0) {
1507
+ console.log(` Cleaned up ${result.cleanedHashes} orphaned content hashes`);
1508
+ }
1509
+ }
1510
+ function collectionRename(oldName, newName) {
1511
+ // Check if old collection exists in YAML
1512
+ const coll = getCollectionFromYaml(oldName);
1513
+ if (!coll) {
1514
+ console.error(`${c.yellow}Collection not found: ${oldName}${c.reset}`);
1515
+ console.error(`Run 'qmd collection list' to see available collections.`);
1516
+ process.exit(1);
1517
+ }
1518
+ // Check if new name already exists in YAML
1519
+ const existing = getCollectionFromYaml(newName);
1520
+ if (existing) {
1521
+ console.error(`${c.yellow}Collection name already exists: ${newName}${c.reset}`);
1522
+ console.error(`Choose a different name or remove the existing collection first.`);
1523
+ process.exit(1);
1524
+ }
1525
+ const db = getDb();
1526
+ renameCollection(db, oldName, newName);
1527
+ // Also rename in YAML config
1528
+ yamlRenameCollectionFn(oldName, newName);
1529
+ closeDb();
1530
+ console.log(`${c.green}✓${c.reset} Renamed collection '${oldName}' to '${newName}'`);
1531
+ console.log(` Virtual paths updated: ${c.cyan}qmd://${oldName}/${c.reset} → ${c.cyan}qmd://${newName}/${c.reset}`);
1532
+ }
1533
+ async function indexFiles(pwd, globPattern = DEFAULT_GLOB, collectionName, suppressEmbedNotice = false, ignorePatterns) {
1534
+ const db = getDb();
1535
+ const resolvedPwd = pwd || getPwd();
1536
+ const now = new Date().toISOString();
1537
+ const excludeDirs = ["node_modules", ".git", ".cache", "vendor", "dist", "build"];
1538
+ // Clear Ollama cache on index
1539
+ clearCache(db);
1540
+ // Collection name must be provided (from YAML)
1541
+ if (!collectionName) {
1542
+ throw new Error("Collection name is required. Collections must be defined in ~/.config/qmd/index.yml");
1543
+ }
1544
+ console.log(`Collection: ${resolvedPwd} (${globPattern})`);
1545
+ progress.indeterminate();
1546
+ const allIgnore = [
1547
+ ...excludeDirs.map(d => `**/${d}/**`),
1548
+ ...(ignorePatterns || []),
1549
+ ];
1550
+ const allFiles = await fastGlob(globPattern, {
1551
+ cwd: resolvedPwd,
1552
+ onlyFiles: true,
1553
+ followSymbolicLinks: false,
1554
+ dot: false,
1555
+ ignore: allIgnore,
1556
+ });
1557
+ // Filter hidden files/folders (dot: false handles top-level but not nested)
1558
+ const files = allFiles.filter(file => {
1559
+ const parts = file.split("/");
1560
+ return !parts.some(part => part.startsWith("."));
1561
+ });
1562
+ const total = files.length;
1563
+ const hasNoFiles = total === 0;
1564
+ if (hasNoFiles) {
1565
+ progress.clear();
1566
+ console.log("No files found matching pattern.");
1567
+ // Continue so the deactivation pass can mark previously indexed docs as inactive.
1568
+ }
1569
+ let indexed = 0, updated = 0, unchanged = 0, processed = 0;
1570
+ const seenPaths = new Set();
1571
+ const startTime = Date.now();
1572
+ for (const relativeFile of files) {
1573
+ const filepath = getRealPath(resolve(resolvedPwd, relativeFile));
1574
+ // Store the literal relative path — handelize() is NOT applied at index time.
1575
+ const path = relativeFile.replace(/\\/g, '/');
1576
+ seenPaths.add(path);
1577
+ let content;
1578
+ try {
1579
+ content = readFileSync(filepath, "utf-8");
1580
+ }
1581
+ catch {
1582
+ // Skip files that can't be read (e.g. iCloud evicted files returning EAGAIN)
1583
+ processed++;
1584
+ progress.set((processed / total) * 100);
1585
+ continue;
1586
+ }
1587
+ // Skip empty files - nothing useful to index
1588
+ if (!content.trim()) {
1589
+ processed++;
1590
+ continue;
1591
+ }
1592
+ const hash = await hashContent(content);
1593
+ const title = extractTitle(content, relativeFile);
1594
+ // Check if document exists (also migrates legacy lowercase paths)
1595
+ const existing = findOrMigrateLegacyDocument(db, collectionName, path);
1596
+ if (existing) {
1597
+ if (existing.hash === hash) {
1598
+ // Hash unchanged, but check if title needs updating
1599
+ if (existing.title !== title) {
1600
+ updateDocumentTitle(db, existing.id, title, now);
1601
+ updated++;
1602
+ }
1603
+ else {
1604
+ unchanged++;
1605
+ }
1606
+ }
1607
+ else {
1608
+ // Content changed - insert new content hash and update document
1609
+ insertContent(db, hash, content, now);
1610
+ const stat = statSync(filepath);
1611
+ updateDocument(db, existing.id, title, hash, stat ? new Date(stat.mtime).toISOString() : now);
1612
+ updated++;
1613
+ }
1614
+ }
1615
+ else {
1616
+ // New document - insert content and document
1617
+ indexed++;
1618
+ insertContent(db, hash, content, now);
1619
+ const stat = statSync(filepath);
1620
+ insertDocument(db, collectionName, path, title, hash, stat ? new Date(stat.birthtime).toISOString() : now, stat ? new Date(stat.mtime).toISOString() : now);
1621
+ }
1622
+ processed++;
1623
+ progress.set((processed / total) * 100);
1624
+ const elapsed = (Date.now() - startTime) / 1000;
1625
+ const rate = processed / elapsed;
1626
+ const remaining = (total - processed) / rate;
1627
+ const eta = processed > 2 ? ` ETA: ${formatETA(remaining)}` : "";
1628
+ if (isTTY)
1629
+ process.stderr.write(`\rIndexing: ${processed}/${total}${eta} `);
1630
+ }
1631
+ // Deactivate documents in this collection that no longer exist
1632
+ const allActive = getActiveDocumentPaths(db, collectionName);
1633
+ let removed = 0;
1634
+ for (const path of allActive) {
1635
+ if (!seenPaths.has(path)) {
1636
+ deactivateDocument(db, collectionName, path);
1637
+ removed++;
1638
+ }
1639
+ }
1640
+ // Clean up orphaned content hashes (content not referenced by any document)
1641
+ const orphanedContent = cleanupOrphanedContent(db);
1642
+ // Check if vector index needs updating
1643
+ const needsEmbedding = getHashesNeedingEmbedding(db);
1644
+ progress.clear();
1645
+ console.log(`\nIndexed: ${indexed} new, ${updated} updated, ${unchanged} unchanged, ${removed} removed`);
1646
+ if (orphanedContent > 0) {
1647
+ console.log(`Cleaned up ${orphanedContent} orphaned content hash(es)`);
1648
+ }
1649
+ if (needsEmbedding > 0 && !suppressEmbedNotice) {
1650
+ console.log(`\nRun 'qmd embed' to update embeddings (${needsEmbedding} unique hashes need vectors)`);
1651
+ }
1652
+ closeDb();
1653
+ }
1654
+ function renderProgressBar(percent, width = 30) {
1655
+ const filled = Math.round((percent / 100) * width);
1656
+ const empty = width - filled;
1657
+ const bar = "█".repeat(filled) + "░".repeat(empty);
1658
+ return bar;
1659
+ }
1660
+ function parseEmbedBatchOption(name, value) {
1661
+ if (value === undefined)
1662
+ return undefined;
1663
+ const parsed = Number(value);
1664
+ if (!Number.isInteger(parsed) || parsed < 1) {
1665
+ throw new Error(`${name} must be a positive integer`);
1666
+ }
1667
+ return parsed;
1668
+ }
1669
+ function parseChunkStrategy(value) {
1670
+ if (value === undefined)
1671
+ return undefined;
1672
+ const s = String(value);
1673
+ if (s === "auto" || s === "regex")
1674
+ return s;
1675
+ throw new Error(`--chunk-strategy must be "auto" or "regex" (got "${s}")`);
1676
+ }
1677
+ function ensureModelsConfiguredForCli() {
1678
+ try {
1679
+ const config = loadConfig();
1680
+ const models = resolveModels(config.models);
1681
+ const current = config.models ?? {};
1682
+ if (current.embed !== models.embed || current.generate !== models.generate || current.rerank !== models.rerank) {
1683
+ saveConfig({
1684
+ ...config,
1685
+ models: {
1686
+ ...current,
1687
+ embed: models.embed,
1688
+ generate: models.generate,
1689
+ rerank: models.rerank,
1690
+ },
1691
+ });
1692
+ }
1693
+ return models;
1694
+ }
1695
+ catch {
1696
+ return resolveModels();
1697
+ }
1698
+ }
1699
+ export function resolveEmbedModelForCli() {
1700
+ return ensureModelsConfiguredForCli().embed;
1701
+ }
1702
+ export function resolveGenerateModelForCli() {
1703
+ return ensureModelsConfiguredForCli().generate;
1704
+ }
1705
+ export function resolveRerankModelForCli() {
1706
+ return ensureModelsConfiguredForCli().rerank;
1707
+ }
1708
+ function resolveModelsForCli() {
1709
+ return ensureModelsConfiguredForCli();
1710
+ }
1711
+ async function vectorIndex(model = resolveEmbedModelForCli(), force = false, batchOptions) {
1712
+ const storeInstance = getStore();
1713
+ const db = storeInstance.db;
1714
+ if (force) {
1715
+ console.log(`${c.yellow}Force re-indexing: clearing all vectors...${c.reset}`);
1716
+ }
1717
+ // Check if there's work to do before starting
1718
+ const hashesToEmbed = getHashesNeedingEmbedding(db, batchOptions?.collection, model);
1719
+ if (hashesToEmbed === 0 && !force) {
1720
+ console.log(`${c.green}✓ All content hashes already have embeddings.${c.reset}`);
1721
+ closeDb();
1722
+ return;
1723
+ }
1724
+ console.log(`${c.dim}Model: ${shortModelName(model)}${c.reset}\n`);
1725
+ if (batchOptions?.maxDocsPerBatch !== undefined || batchOptions?.maxBatchBytes !== undefined) {
1726
+ const maxDocsPerBatch = batchOptions.maxDocsPerBatch ?? DEFAULT_EMBED_MAX_DOCS_PER_BATCH;
1727
+ const maxBatchBytes = batchOptions.maxBatchBytes ?? DEFAULT_EMBED_MAX_BATCH_BYTES;
1728
+ console.log(`${c.dim}Batch: ${maxDocsPerBatch} docs / ${formatBytes(maxBatchBytes)}${c.reset}\n`);
1729
+ }
1730
+ cursor.hide();
1731
+ progress.indeterminate();
1732
+ const startTime = Date.now();
1733
+ const result = await generateEmbeddings(storeInstance, {
1734
+ force,
1735
+ model,
1736
+ collection: batchOptions?.collection,
1737
+ maxDocsPerBatch: batchOptions?.maxDocsPerBatch,
1738
+ maxBatchBytes: batchOptions?.maxBatchBytes,
1739
+ chunkStrategy: batchOptions?.chunkStrategy,
1740
+ onProgress: (info) => {
1741
+ if (info.totalBytes === 0)
1742
+ return;
1743
+ // Progress is measured by input bytes, not by chunks. The final chunk
1744
+ // count is discovered lazily batch-by-batch, so displaying
1745
+ // chunksEmbedded/totalChunks makes the percent look wrong when a few
1746
+ // large documents remain. Show chunks as a count and label the byte
1747
+ // percentage explicitly as input progress.
1748
+ const percent = Math.min(100, (info.bytesProcessed / info.totalBytes) * 100);
1749
+ progress.set(percent);
1750
+ const elapsed = (Date.now() - startTime) / 1000;
1751
+ const bytesPerSec = elapsed > 0 ? info.bytesProcessed / elapsed : 0;
1752
+ const remainingBytes = Math.max(0, info.totalBytes - info.bytesProcessed);
1753
+ const etaSec = bytesPerSec > 0 ? remainingBytes / bytesPerSec : Number.POSITIVE_INFINITY;
1754
+ const bar = renderProgressBar(percent);
1755
+ const percentStr = percent.toFixed(0).padStart(3);
1756
+ const throughput = bytesPerSec > 0 ? `${formatBytes(bytesPerSec)}/s` : ".../s";
1757
+ const eta = elapsed > 2 && Number.isFinite(etaSec) ? formatETA(etaSec) : "...";
1758
+ const inputStr = `${formatBytes(info.bytesProcessed)}/${formatBytes(info.totalBytes)} input`;
1759
+ const chunkStr = `${formatCount(info.chunksEmbedded)} chunks`;
1760
+ const errStr = info.errors > 0 ? ` ${c.yellow}${formatCount(info.errors)} err${c.reset}` : "";
1761
+ if (isTTY)
1762
+ process.stderr.write(`\r${c.cyan}${bar}${c.reset} ${c.bold}${percentStr}% input${c.reset} ${c.dim}${chunkStr}${errStr} · ${inputStr} · ${throughput} · ETA ${eta}${c.reset} `);
1763
+ },
1764
+ });
1765
+ progress.clear();
1766
+ cursor.show();
1767
+ const totalTimeSec = result.durationMs / 1000;
1768
+ if (result.chunksEmbedded === 0 && result.docsProcessed === 0) {
1769
+ console.log(`${c.green}✓ No non-empty documents to embed.${c.reset}`);
1770
+ }
1771
+ else {
1772
+ console.log(`\r${c.green}${renderProgressBar(100)}${c.reset} ${c.bold}100%${c.reset} `);
1773
+ 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}`);
1774
+ if (result.errors > 0) {
1775
+ console.log(`${c.yellow}⚠ ${formatCount(result.errors)} chunks still failed after retries${c.reset}`);
1776
+ for (const failure of (result.failures ?? []).slice(0, 8)) {
1777
+ console.log(` ${c.dim}${failure.path}#${failure.seq} (${failure.attempts} attempts): ${failure.reason}${c.reset}`);
1778
+ }
1779
+ if ((result.failures?.length ?? 0) > 8) {
1780
+ console.log(` ${c.dim}...and ${formatCount((result.failures?.length ?? 0) - 8)} more${c.reset}`);
1781
+ }
1782
+ }
1783
+ }
1784
+ closeDb();
1785
+ }
1786
+ // Sanitize a term for FTS5: remove punctuation except apostrophes
1787
+ function sanitizeFTS5Term(term) {
1788
+ // Remove all non-alphanumeric except apostrophes (for contractions like "don't")
1789
+ return term.replace(/[^\w']/g, '').trim();
1790
+ }
1791
+ // Build FTS5 query: phrase-aware with fallback to individual terms
1792
+ function buildFTS5Query(query) {
1793
+ // Sanitize the full query for phrase matching
1794
+ const sanitizedQuery = query.replace(/[^\w\s']/g, '').trim();
1795
+ const terms = query
1796
+ .split(/\s+/)
1797
+ .map(sanitizeFTS5Term)
1798
+ .filter(term => term.length >= 2); // Skip single chars and empty
1799
+ if (terms.length === 0)
1800
+ return "";
1801
+ if (terms.length === 1)
1802
+ return `"${terms[0].replace(/"/g, '""')}"`;
1803
+ // Strategy: exact phrase OR proximity match OR individual terms
1804
+ // Exact phrase matches rank highest, then close proximity, then any term
1805
+ const phrase = `"${sanitizedQuery.replace(/"/g, '""')}"`;
1806
+ const quotedTerms = terms.map(t => `"${t.replace(/"/g, '""')}"`);
1807
+ // FTS5 NEAR syntax: NEAR(term1 term2, distance)
1808
+ const nearPhrase = `NEAR(${quotedTerms.join(' ')}, 10)`;
1809
+ const orTerms = quotedTerms.join(' OR ');
1810
+ // Exact phrase > proximity > any term
1811
+ return `(${phrase}) OR (${nearPhrase}) OR (${orTerms})`;
1812
+ }
1813
+ // Normalize BM25 score to 0-1 range using sigmoid
1814
+ function normalizeBM25(score) {
1815
+ // BM25 scores are negative in SQLite (lower = better)
1816
+ // Typical range: -15 (excellent) to -2 (weak match)
1817
+ // Map to 0-1 where higher is better
1818
+ const absScore = Math.abs(score);
1819
+ // Sigmoid-ish normalization: maps ~2-15 range to ~0.1-0.95
1820
+ return 1 / (1 + Math.exp(-(absScore - 5) / 3));
1821
+ }
1822
+ // Highlight query terms in text (skip short words < 3 chars)
1823
+ function highlightTerms(text, query) {
1824
+ if (!useColor)
1825
+ return text;
1826
+ const terms = query.toLowerCase().split(/\s+/).filter(t => t.length >= 3);
1827
+ let result = text;
1828
+ for (const term of terms) {
1829
+ const regex = new RegExp(`(${term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
1830
+ result = result.replace(regex, `${c.yellow}${c.bold}$1${c.reset}`);
1831
+ }
1832
+ return result;
1833
+ }
1834
+ // Format score with color based on value
1835
+ function formatScore(score) {
1836
+ const pct = (score * 100).toFixed(0).padStart(3);
1837
+ if (!useColor)
1838
+ return `${pct}%`;
1839
+ if (score >= 0.7)
1840
+ return `${c.green}${pct}%${c.reset}`;
1841
+ if (score >= 0.4)
1842
+ return `${c.yellow}${pct}%${c.reset}`;
1843
+ return `${c.dim}${pct}%${c.reset}`;
1844
+ }
1845
+ function formatExplainNumber(value) {
1846
+ return value.toFixed(4);
1847
+ }
1848
+ // Shorten directory path for display - relative to $HOME (used for context paths, not documents)
1849
+ function shortPath(dirpath) {
1850
+ const home = homedir();
1851
+ if (dirpath.startsWith(home)) {
1852
+ return '~' + dirpath.slice(home.length);
1853
+ }
1854
+ return dirpath;
1855
+ }
1856
+ // Emit format-safe empty output for search commands.
1857
+ function printEmptySearchResults(format, reason = "no_results") {
1858
+ if (format === "json") {
1859
+ console.log("[]");
1860
+ return;
1861
+ }
1862
+ if (format === "csv") {
1863
+ console.log("docid,score,file,title,context,line,snippet");
1864
+ return;
1865
+ }
1866
+ if (format === "xml") {
1867
+ console.log("<results></results>");
1868
+ return;
1869
+ }
1870
+ if (format === "md" || format === "files") {
1871
+ return;
1872
+ }
1873
+ if (reason === "min_score") {
1874
+ console.log("No results found above minimum score threshold.");
1875
+ return;
1876
+ }
1877
+ console.log("No results found.");
1878
+ }
1879
+ const DEFAULT_EDITOR_URI_TEMPLATE = "vscode://file/{path}:{line}:{col}";
1880
+ function encodePathForEditorUri(absolutePath) {
1881
+ return encodeURI(absolutePath)
1882
+ .replace(/\?/g, "%3F")
1883
+ .replace(/#/g, "%23");
1884
+ }
1885
+ function getEditorUriTemplate() {
1886
+ const envTemplate = process.env.QMD_EDITOR_URI?.trim();
1887
+ if (envTemplate)
1888
+ return envTemplate;
1889
+ try {
1890
+ const config = loadConfig();
1891
+ const configTemplate = (config.editor_uri
1892
+ || config.editor_uri_template
1893
+ || config.editorUri
1894
+ || (typeof config["editor-uri"] === "string" ? config["editor-uri"] : undefined))?.trim();
1895
+ if (configTemplate)
1896
+ return configTemplate;
1897
+ }
1898
+ catch {
1899
+ // Ignore config parsing issues and use default template.
1900
+ }
1901
+ return DEFAULT_EDITOR_URI_TEMPLATE;
1902
+ }
1903
+ export function buildEditorUri(template, absolutePath, line, col) {
1904
+ const safeLine = Number.isFinite(line) && line > 0 ? Math.floor(line) : 1;
1905
+ const safeCol = Number.isFinite(col) && col > 0 ? Math.floor(col) : 1;
1906
+ const encodedPath = encodePathForEditorUri(absolutePath);
1907
+ return template
1908
+ .replace(/\{path\}/g, encodedPath)
1909
+ .replace(/\{line\}/g, String(safeLine))
1910
+ .replace(/\{col\}/g, String(safeCol))
1911
+ .replace(/\{column\}/g, String(safeCol));
1912
+ }
1913
+ export function termLink(text, url, isTTY = !!process.stdout.isTTY) {
1914
+ if (!isTTY)
1915
+ return text;
1916
+ return `\x1b]8;;${url}\x07${text}\x1b]8;;\x07`;
1917
+ }
1918
+ function outputResults(results, query, opts) {
1919
+ const filtered = results.filter(r => r.score >= opts.minScore).slice(0, opts.limit);
1920
+ if (filtered.length === 0) {
1921
+ printEmptySearchResults(opts.format, "min_score");
1922
+ return;
1923
+ }
1924
+ // Helper to create qmd:// URI from displayPath
1925
+ const toQmdPath = (displayPath) => {
1926
+ const [collectionName, ...segments] = displayPath.split("/");
1927
+ if (!collectionName || segments.length === 0) {
1928
+ return `qmd://${displayPath}`;
1929
+ }
1930
+ const indexName = getActiveIndexName();
1931
+ return buildVirtualPath(collectionName, segments.join("/"), indexName === "index" ? undefined : indexName);
1932
+ };
1933
+ // Helper to pick the visible path for a result. With --full-path we swap
1934
+ // the qmd:// URI for the file's on-disk path via renderFullPath() (./-
1935
+ // prefixed relative when under $PWD, absolute realpath otherwise). Falls
1936
+ // back to qmd:// if the file is no longer resolvable on disk.
1937
+ const linkDbForPaths = opts.fullPath ? getDb() : null;
1938
+ const displayPathFor = (row) => {
1939
+ // Always rebuild from displayPath so the active index name is included
1940
+ // as ?index=… for non-default indexes. row.file may not carry it.
1941
+ const qmdUri = toQmdPath(row.displayPath);
1942
+ if (!opts.fullPath || !linkDbForPaths)
1943
+ return qmdUri;
1944
+ const absolute = resolveVirtualPath(linkDbForPaths, qmdUri);
1945
+ if (!absolute || !existsSync(absolute))
1946
+ return qmdUri;
1947
+ return renderFullPath(absolute);
1948
+ };
1949
+ if (opts.format === "json") {
1950
+ // JSON output for LLM consumption
1951
+ const output = filtered.map(row => {
1952
+ const docid = row.docid || (row.hash ? row.hash.slice(0, 6) : undefined);
1953
+ const snippetInfo = extractSnippet(row.body, query, 300, row.chunkPos, row.chunkLen, opts.intent);
1954
+ let body = opts.full ? row.body : undefined;
1955
+ let snippet = !opts.full ? snippetInfo.snippet : undefined;
1956
+ if (opts.lineNumbers) {
1957
+ if (body)
1958
+ body = addLineNumbers(body);
1959
+ if (snippet)
1960
+ snippet = addLineNumbers(snippet);
1961
+ }
1962
+ // With --full-path, omit docid (the on-disk path is the identifier).
1963
+ return {
1964
+ ...(docid && !opts.fullPath && { docid: `#${docid}` }),
1965
+ score: Math.round(row.score * 100) / 100,
1966
+ file: displayPathFor(row),
1967
+ line: snippetInfo.line,
1968
+ title: row.title,
1969
+ ...(row.context && { context: row.context }),
1970
+ ...(body && { body }),
1971
+ ...(snippet && { snippet }),
1972
+ ...(opts.explain && row.explain && { explain: row.explain }),
1973
+ };
1974
+ });
1975
+ console.log(JSON.stringify(output, null, 2));
1976
+ }
1977
+ else if (opts.format === "files") {
1978
+ // Simple docid,score,filepath,context output
1979
+ for (const row of filtered) {
1980
+ const docid = row.docid || (row.hash ? row.hash.slice(0, 6) : "");
1981
+ const ctx = row.context ? `,"${row.context.replace(/"/g, '""')}"` : "";
1982
+ if (opts.fullPath) {
1983
+ // --full-path: drop the docid, the on-disk path is the identifier.
1984
+ console.log(`${row.score.toFixed(2)},${displayPathFor(row)}${ctx}`);
1985
+ }
1986
+ else {
1987
+ console.log(`#${docid},${row.score.toFixed(2)},${displayPathFor(row)}${ctx}`);
1988
+ }
1989
+ }
1990
+ }
1991
+ else if (opts.format === "cli") {
1992
+ const editorUriTemplate = getEditorUriTemplate();
1993
+ const linkDb = getDb();
1994
+ for (let i = 0; i < filtered.length; i++) {
1995
+ const row = filtered[i];
1996
+ if (!row)
1997
+ continue;
1998
+ const { line, snippet } = extractSnippet(row.body, query, 500, row.chunkPos, row.chunkLen, opts.intent);
1999
+ const docid = row.docid || (row.hash ? row.hash.slice(0, 6) : undefined);
2000
+ // Line 1: filepath with docid
2001
+ // Default: show the full qmd:// URI so the user can see which collection
2002
+ // a hit lives in and can pipe the same string straight back into
2003
+ // `qmd get`. A bare collection-relative path like `sources/foo.md` is
2004
+ // ambiguous: it's not a real filesystem path, not a URI, and not a
2005
+ // shell-friendly identifier on its own.
2006
+ // With --full-path the visible label is the file's on-disk path
2007
+ // ($PWD-relative when in a subfolder; absolute realpath otherwise),
2008
+ // and the docid is omitted because the path is the identifier.
2009
+ const virtualPath = toQmdPath(row.displayPath);
2010
+ const parsed = parseVirtualPath(virtualPath);
2011
+ const absolutePath = resolveVirtualPath(linkDb, virtualPath);
2012
+ const visiblePath = displayPathFor(row);
2013
+ // Only show :line if we actually found a term match in the snippet body (exclude header line).
2014
+ const snippetBody = snippet.split("\n").slice(1).join("\n").toLowerCase();
2015
+ const hasMatch = query.toLowerCase().split(/\s+/).some(t => t.length > 0 && snippetBody.includes(t));
2016
+ const lineInfo = hasMatch ? `:${line}` : "";
2017
+ const docidStr = (docid && !opts.fullPath) ? ` ${c.dim}#${docid}${c.reset}` : "";
2018
+ if (process.stdout.isTTY && absolutePath && parsed?.path) {
2019
+ const linkLine = hasMatch ? line : 1;
2020
+ const linkTarget = buildEditorUri(editorUriTemplate, absolutePath, linkLine, 1);
2021
+ const clickable = termLink(`${visiblePath}${lineInfo}`, linkTarget);
2022
+ console.log(`${c.cyan}${clickable}${c.reset}${docidStr}`);
2023
+ }
2024
+ else {
2025
+ console.log(`${c.cyan}${visiblePath}${c.dim}${lineInfo}${c.reset}${docidStr}`);
2026
+ }
2027
+ // Line 2: Title (if available)
2028
+ if (row.title) {
2029
+ console.log(`${c.bold}Title: ${row.title}${c.reset}`);
2030
+ }
2031
+ // Line 3: Context (if available)
2032
+ if (row.context) {
2033
+ console.log(`${c.dim}Context: ${row.context}${c.reset}`);
2034
+ }
2035
+ // Line 4: Score
2036
+ const score = formatScore(row.score);
2037
+ console.log(`Score: ${c.bold}${score}${c.reset}`);
2038
+ if (opts.explain && row.explain) {
2039
+ const explain = row.explain;
2040
+ const ftsScores = explain.ftsScores.length > 0
2041
+ ? explain.ftsScores.map(formatExplainNumber).join(", ")
2042
+ : "none";
2043
+ const vecScores = explain.vectorScores.length > 0
2044
+ ? explain.vectorScores.map(formatExplainNumber).join(", ")
2045
+ : "none";
2046
+ const contribSummary = explain.rrf.contributions
2047
+ .slice()
2048
+ .sort((a, b) => b.rrfContribution - a.rrfContribution)
2049
+ .slice(0, 3)
2050
+ .map(c => `${c.source}/${c.queryType}#${c.rank}:${formatExplainNumber(c.rrfContribution)}`)
2051
+ .join(" | ");
2052
+ console.log(`${c.dim}Explain: fts=[${ftsScores}] vec=[${vecScores}]${c.reset}`);
2053
+ 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}`);
2054
+ 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}`);
2055
+ if (contribSummary.length > 0) {
2056
+ console.log(`${c.dim} Top RRF contributions: ${contribSummary}${c.reset}`);
2057
+ }
2058
+ }
2059
+ console.log();
2060
+ // Snippet with highlighting (diff-style header included)
2061
+ const content = opts.full ? row.body : snippet;
2062
+ const displayContent = opts.lineNumbers ? addLineNumbers(content, opts.full ? 1 : line) : content;
2063
+ const highlighted = highlightTerms(displayContent, query);
2064
+ console.log(highlighted);
2065
+ // Double empty line between results
2066
+ if (i < filtered.length - 1)
2067
+ console.log('\n');
2068
+ }
2069
+ }
2070
+ else if (opts.format === "md") {
2071
+ for (let i = 0; i < filtered.length; i++) {
2072
+ const row = filtered[i];
2073
+ if (!row)
2074
+ continue;
2075
+ const visiblePath = displayPathFor(row);
2076
+ const heading = row.title || visiblePath;
2077
+ const docid = row.docid || (row.hash ? row.hash.slice(0, 6) : undefined);
2078
+ let content = opts.full ? row.body : extractSnippet(row.body, query, 500, row.chunkPos, row.chunkLen, opts.intent).snippet;
2079
+ if (opts.lineNumbers) {
2080
+ content = addLineNumbers(content);
2081
+ }
2082
+ const fileLine = `**file:** \`${visiblePath}\`\n`;
2083
+ // With --full-path the on-disk path is the identifier; drop the docid line.
2084
+ const docidLine = (docid && !opts.fullPath) ? `**docid:** \`#${docid}\`\n` : "";
2085
+ const contextLine = row.context ? `**context:** ${row.context}\n` : "";
2086
+ console.log(`---\n# ${heading}\n${fileLine}${docidLine}${contextLine}\n${content}\n`);
2087
+ }
2088
+ }
2089
+ else if (opts.format === "xml") {
2090
+ for (const row of filtered) {
2091
+ const titleAttr = row.title ? ` title="${row.title.replace(/"/g, '&quot;')}"` : "";
2092
+ const contextAttr = row.context ? ` context="${row.context.replace(/"/g, '&quot;')}"` : "";
2093
+ const docid = row.docid || (row.hash ? row.hash.slice(0, 6) : "");
2094
+ let content = opts.full ? row.body : extractSnippet(row.body, query, 500, row.chunkPos, row.chunkLen, opts.intent).snippet;
2095
+ if (opts.lineNumbers) {
2096
+ content = addLineNumbers(content);
2097
+ }
2098
+ const docidAttr = opts.fullPath ? "" : ` docid="#${docid}"`;
2099
+ console.log(`<file${docidAttr} name="${displayPathFor(row)}"${titleAttr}${contextAttr}>\n${content}\n</file>\n`);
2100
+ }
2101
+ }
2102
+ else {
2103
+ // CSV format
2104
+ const csvHeader = opts.fullPath
2105
+ ? "score,file,title,context,line,snippet"
2106
+ : "docid,score,file,title,context,line,snippet";
2107
+ console.log(csvHeader);
2108
+ for (const row of filtered) {
2109
+ const { line, snippet } = extractSnippet(row.body, query, 500, row.chunkPos, row.chunkLen, opts.intent);
2110
+ let content = opts.full ? row.body : snippet;
2111
+ if (opts.lineNumbers) {
2112
+ content = addLineNumbers(content, opts.full ? 1 : line);
2113
+ }
2114
+ const docid = row.docid || (row.hash ? row.hash.slice(0, 6) : "");
2115
+ const snippetText = content || "";
2116
+ const path = escapeCSV(displayPathFor(row));
2117
+ const tail = `${path},${escapeCSV(row.title || "")},${escapeCSV(row.context || "")},${line},${escapeCSV(snippetText)}`;
2118
+ if (opts.fullPath) {
2119
+ console.log(`${row.score.toFixed(4)},${tail}`);
2120
+ }
2121
+ else {
2122
+ console.log(`#${docid},${row.score.toFixed(4)},${tail}`);
2123
+ }
2124
+ }
2125
+ }
2126
+ }
2127
+ // Resolve -c collection filter: supports single string, array, or undefined.
2128
+ // Returns validated collection names (exits on unknown collection).
2129
+ function resolveCollectionFilter(raw, useDefaults = false) {
2130
+ // If no filter specified and useDefaults is true, use default collections
2131
+ if (!raw && useDefaults) {
2132
+ return getDefaultCollectionNames();
2133
+ }
2134
+ if (!raw)
2135
+ return [];
2136
+ const names = Array.isArray(raw) ? raw : [raw];
2137
+ const validated = [];
2138
+ for (const name of names) {
2139
+ const coll = getCollectionFromYaml(name);
2140
+ if (!coll) {
2141
+ console.error(`Collection not found: ${name}`);
2142
+ closeDb();
2143
+ process.exit(1);
2144
+ }
2145
+ validated.push(name);
2146
+ }
2147
+ return validated;
2148
+ }
2149
+ // Post-filter results to only include files from specified collections.
2150
+ function filterByCollections(results, collectionNames) {
2151
+ if (collectionNames.length <= 1)
2152
+ return results;
2153
+ const prefixes = collectionNames.map(n => `qmd://${n}/`);
2154
+ return results.filter(r => {
2155
+ const path = r.filepath || r.file || '';
2156
+ return prefixes.some(p => path.startsWith(p));
2157
+ });
2158
+ }
2159
+ function parseStructuredQuery(query) {
2160
+ const rawLines = query.split('\n').map((line, idx) => ({
2161
+ raw: line,
2162
+ trimmed: line.trim(),
2163
+ number: idx + 1,
2164
+ })).filter(line => line.trimmed.length > 0);
2165
+ if (rawLines.length === 0)
2166
+ return null;
2167
+ const prefixRe = /^(lex|vec|hyde):\s*/i;
2168
+ const expandRe = /^expand:\s*/i;
2169
+ const intentRe = /^intent:\s*/i;
2170
+ const typed = [];
2171
+ let intent;
2172
+ for (const line of rawLines) {
2173
+ if (expandRe.test(line.trimmed)) {
2174
+ if (rawLines.length > 1) {
2175
+ throw new Error(`Line ${line.number} starts with expand:, but query documents cannot mix expand with typed lines. Submit a single expand query instead.`);
2176
+ }
2177
+ const text = line.trimmed.replace(expandRe, '').trim();
2178
+ if (!text) {
2179
+ throw new Error('expand: query must include text.');
2180
+ }
2181
+ return null; // treat as standalone expand query
2182
+ }
2183
+ // Parse intent: lines
2184
+ if (intentRe.test(line.trimmed)) {
2185
+ if (intent !== undefined) {
2186
+ throw new Error(`Line ${line.number}: only one intent: line is allowed per query document.`);
2187
+ }
2188
+ const text = line.trimmed.replace(intentRe, '').trim();
2189
+ if (!text) {
2190
+ throw new Error(`Line ${line.number}: intent: must include text.`);
2191
+ }
2192
+ intent = text;
2193
+ continue;
2194
+ }
2195
+ const match = line.trimmed.match(prefixRe);
2196
+ if (match) {
2197
+ const type = match[1].toLowerCase();
2198
+ const text = line.trimmed.slice(match[0].length).trim();
2199
+ if (!text) {
2200
+ throw new Error(`Line ${line.number} (${type}:) must include text.`);
2201
+ }
2202
+ if (/\r|\n/.test(text)) {
2203
+ throw new Error(`Line ${line.number} (${type}:) contains a newline. Keep each query on a single line.`);
2204
+ }
2205
+ typed.push({ type, query: text, line: line.number });
2206
+ continue;
2207
+ }
2208
+ if (rawLines.length === 1) {
2209
+ // Single plain line -> implicit expand
2210
+ return null;
2211
+ }
2212
+ throw new Error(`Line ${line.number} is missing a lex:/vec:/hyde:/intent: prefix. Each line in a query document must start with one.`);
2213
+ }
2214
+ // intent: alone is not a valid query — must have at least one search
2215
+ if (intent && typed.length === 0) {
2216
+ throw new Error('intent: cannot appear alone. Add at least one lex:, vec:, or hyde: line.');
2217
+ }
2218
+ return typed.length > 0 ? { searches: typed, intent } : null;
2219
+ }
2220
+ function search(query, opts) {
2221
+ const db = getDb();
2222
+ // Validate collection filter (supports multiple -c flags)
2223
+ // Use default collections if none specified
2224
+ const collectionNames = resolveCollectionFilter(opts.collection, true);
2225
+ const singleCollection = collectionNames.length === 1 ? collectionNames[0] : undefined;
2226
+ // Use large limit for --all, otherwise fetch more than needed and let outputResults filter
2227
+ const fetchLimit = opts.all ? 100000 : Math.max(50, opts.limit * 2);
2228
+ const results = filterByCollections(searchFTS(db, query, fetchLimit, singleCollection), collectionNames);
2229
+ // Add context to results
2230
+ const resultsWithContext = results.map(r => ({
2231
+ file: r.filepath,
2232
+ displayPath: r.displayPath,
2233
+ title: r.title,
2234
+ body: r.body || "",
2235
+ score: r.score,
2236
+ context: getContextForFile(db, r.filepath),
2237
+ hash: r.hash,
2238
+ docid: r.docid,
2239
+ }));
2240
+ closeDb();
2241
+ if (resultsWithContext.length === 0) {
2242
+ printEmptySearchResults(opts.format);
2243
+ return;
2244
+ }
2245
+ outputResults(resultsWithContext, query, opts);
2246
+ }
2247
+ // Log query expansion as a tree to stderr (CLI progress feedback)
2248
+ function logExpansionTree(originalQuery, expanded) {
2249
+ const lines = [];
2250
+ lines.push(`${c.dim}├─ ${originalQuery}${c.reset}`);
2251
+ for (const q of expanded) {
2252
+ let preview = q.query.replace(/\n/g, ' ');
2253
+ if (preview.length > 72)
2254
+ preview = preview.substring(0, 69) + '...';
2255
+ lines.push(`${c.dim}├─ ${q.type}: ${preview}${c.reset}`);
2256
+ }
2257
+ if (lines.length > 0) {
2258
+ lines[lines.length - 1] = lines[lines.length - 1].replace('├─', '└─');
2259
+ }
2260
+ for (const line of lines)
2261
+ process.stderr.write(line + '\n');
2262
+ }
2263
+ async function vectorSearch(query, opts, _model = DEFAULT_EMBED_MODEL) {
2264
+ const store = getStore();
2265
+ // Validate collection filter (supports multiple -c flags)
2266
+ // Use default collections if none specified
2267
+ const collectionNames = resolveCollectionFilter(opts.collection, true);
2268
+ const singleCollection = collectionNames.length === 1 ? collectionNames[0] : undefined;
2269
+ checkIndexHealth(store.db);
2270
+ await withLLMSession(async () => {
2271
+ let results = await vectorSearchQuery(store, query, {
2272
+ collection: singleCollection,
2273
+ limit: opts.all ? 500 : (opts.limit || 10),
2274
+ minScore: opts.minScore || 0.3,
2275
+ intent: opts.intent,
2276
+ hooks: {
2277
+ onExpand: (original, expanded) => {
2278
+ logExpansionTree(original, expanded);
2279
+ process.stderr.write(`${c.dim}Searching ${expanded.length + 1} vector queries...${c.reset}\n`);
2280
+ },
2281
+ },
2282
+ });
2283
+ // Post-filter for multi-collection
2284
+ if (collectionNames.length > 1) {
2285
+ results = results.filter(r => {
2286
+ const prefixes = collectionNames.map(n => `qmd://${n}/`);
2287
+ return prefixes.some(p => r.file.startsWith(p));
2288
+ });
2289
+ }
2290
+ closeDb();
2291
+ if (results.length === 0) {
2292
+ printEmptySearchResults(opts.format);
2293
+ return;
2294
+ }
2295
+ outputResults(results.map(r => ({
2296
+ file: r.file,
2297
+ displayPath: r.displayPath,
2298
+ title: r.title,
2299
+ body: r.body,
2300
+ score: r.score,
2301
+ context: r.context,
2302
+ docid: r.docid,
2303
+ })), query, { ...opts, limit: results.length });
2304
+ }, { maxDuration: 10 * 60 * 1000, name: 'vectorSearch' });
2305
+ }
2306
+ async function querySearch(query, opts, _embedModel = DEFAULT_EMBED_MODEL, _rerankModel = DEFAULT_RERANK_MODEL) {
2307
+ const store = getStore();
2308
+ // Validate collection filter (supports multiple -c flags)
2309
+ // Use default collections if none specified
2310
+ const collectionNames = resolveCollectionFilter(opts.collection, true);
2311
+ const singleCollection = collectionNames.length === 1 ? collectionNames[0] : undefined;
2312
+ checkIndexHealth(store.db);
2313
+ // Check for structured query syntax (lex:/vec:/hyde:/intent: prefixes)
2314
+ const parsed = parseStructuredQuery(query);
2315
+ // Intent can come from --intent flag or from intent: line in query document
2316
+ const intent = opts.intent || parsed?.intent;
2317
+ await withLLMSession(async () => {
2318
+ let results;
2319
+ if (parsed) {
2320
+ const structuredQueries = parsed.searches;
2321
+ // Structured search — user provided their own query expansions
2322
+ const typeLabels = structuredQueries.map(s => s.type).join('+');
2323
+ process.stderr.write(`${c.dim}Structured search: ${structuredQueries.length} queries (${typeLabels})${c.reset}\n`);
2324
+ if (intent) {
2325
+ process.stderr.write(`${c.dim}├─ intent: ${intent}${c.reset}\n`);
2326
+ }
2327
+ // Log each sub-query
2328
+ for (const s of structuredQueries) {
2329
+ let preview = s.query.replace(/\n/g, ' ');
2330
+ if (preview.length > 72)
2331
+ preview = preview.substring(0, 69) + '...';
2332
+ process.stderr.write(`${c.dim}├─ ${s.type}: ${preview}${c.reset}\n`);
2333
+ }
2334
+ process.stderr.write(`${c.dim}└─ Searching...${c.reset}\n`);
2335
+ results = await structuredSearch(store, structuredQueries, {
2336
+ collections: singleCollection ? [singleCollection] : undefined,
2337
+ limit: opts.all ? 500 : (opts.limit || 10),
2338
+ minScore: opts.minScore || 0,
2339
+ candidateLimit: opts.candidateLimit,
2340
+ skipRerank: opts.skipRerank,
2341
+ explain: !!opts.explain,
2342
+ intent,
2343
+ chunkStrategy: opts.chunkStrategy,
2344
+ hooks: {
2345
+ onEmbedStart: (count) => {
2346
+ process.stderr.write(`${c.dim}Embedding ${count} ${count === 1 ? 'query' : 'queries'}...${c.reset}`);
2347
+ },
2348
+ onEmbedDone: (ms) => {
2349
+ process.stderr.write(`${c.dim} (${formatMs(ms)})${c.reset}\n`);
2350
+ },
2351
+ onRerankStart: (chunkCount) => {
2352
+ process.stderr.write(`${c.dim}Reranking ${chunkCount} chunks...${c.reset}`);
2353
+ progress.indeterminate();
2354
+ },
2355
+ onRerankDone: (ms) => {
2356
+ progress.clear();
2357
+ process.stderr.write(`${c.dim} (${formatMs(ms)})${c.reset}\n`);
2358
+ },
2359
+ },
2360
+ });
2361
+ }
2362
+ else {
2363
+ // Standard hybrid query with automatic expansion
2364
+ results = await hybridQuery(store, query, {
2365
+ collection: singleCollection,
2366
+ limit: opts.all ? 500 : (opts.limit || 10),
2367
+ minScore: opts.minScore || 0,
2368
+ candidateLimit: opts.candidateLimit,
2369
+ skipRerank: opts.skipRerank,
2370
+ explain: !!opts.explain,
2371
+ intent,
2372
+ chunkStrategy: opts.chunkStrategy,
2373
+ hooks: {
2374
+ onStrongSignal: (score) => {
2375
+ process.stderr.write(`${c.dim}Strong BM25 signal (${score.toFixed(2)}) — skipping expansion${c.reset}\n`);
2376
+ },
2377
+ onExpandStart: () => {
2378
+ process.stderr.write(`${c.dim}Expanding query...${c.reset}`);
2379
+ },
2380
+ onExpand: (original, expanded, ms) => {
2381
+ process.stderr.write(`${c.dim} (${formatMs(ms)})${c.reset}\n`);
2382
+ logExpansionTree(original, expanded);
2383
+ process.stderr.write(`${c.dim}Searching ${expanded.length + 1} queries...${c.reset}\n`);
2384
+ },
2385
+ onEmbedStart: (count) => {
2386
+ process.stderr.write(`${c.dim}Embedding ${count} ${count === 1 ? 'query' : 'queries'}...${c.reset}`);
2387
+ },
2388
+ onEmbedDone: (ms) => {
2389
+ process.stderr.write(`${c.dim} (${formatMs(ms)})${c.reset}\n`);
2390
+ },
2391
+ onRerankStart: (chunkCount) => {
2392
+ process.stderr.write(`${c.dim}Reranking ${chunkCount} chunks...${c.reset}`);
2393
+ progress.indeterminate();
2394
+ },
2395
+ onRerankDone: (ms) => {
2396
+ progress.clear();
2397
+ process.stderr.write(`${c.dim} (${formatMs(ms)})${c.reset}\n`);
2398
+ },
2399
+ },
2400
+ });
2401
+ }
2402
+ // Post-filter for multi-collection
2403
+ if (collectionNames.length > 1) {
2404
+ results = results.filter(r => {
2405
+ const prefixes = collectionNames.map(n => `qmd://${n}/`);
2406
+ return prefixes.some(p => r.file.startsWith(p));
2407
+ });
2408
+ }
2409
+ closeDb();
2410
+ if (results.length === 0) {
2411
+ printEmptySearchResults(opts.format);
2412
+ return;
2413
+ }
2414
+ // Use first lex/vec query for output context, or original query
2415
+ const structuredQueries = parsed?.searches;
2416
+ const displayQuery = structuredQueries
2417
+ ? (structuredQueries.find(s => s.type === 'lex')?.query || structuredQueries.find(s => s.type === 'vec')?.query || query)
2418
+ : query;
2419
+ outputResults(results.map(r => ({
2420
+ file: r.file,
2421
+ displayPath: r.displayPath,
2422
+ title: r.title,
2423
+ body: r.body,
2424
+ chunkPos: r.bestChunkPos,
2425
+ chunkLen: r.bestChunk.length,
2426
+ score: r.score,
2427
+ context: r.context,
2428
+ docid: r.docid,
2429
+ explain: r.explain,
2430
+ })), displayQuery, { ...opts, limit: results.length });
2431
+ }, { maxDuration: 10 * 60 * 1000, name: 'querySearch' });
2432
+ }
2433
+ // Parse CLI arguments using util.parseArgs
2434
+ function parseCLI() {
2435
+ const { values, positionals } = parseArgs({
2436
+ args: process.argv.slice(2), // Skip node and script path
2437
+ options: {
2438
+ // Global options
2439
+ index: {
2440
+ type: "string",
2441
+ },
2442
+ context: {
2443
+ type: "string",
2444
+ },
2445
+ help: { type: "boolean", short: "h" },
2446
+ version: { type: "boolean", short: "v" },
2447
+ skill: { type: "boolean" },
2448
+ global: { type: "boolean" },
2449
+ yes: { type: "boolean" },
2450
+ // Search options
2451
+ n: { type: "string" },
2452
+ "min-score": { type: "string" },
2453
+ all: { type: "boolean" },
2454
+ full: { type: "boolean" },
2455
+ format: { type: "string" }, // preferred: --format cli|json|csv|md|xml|files
2456
+ // Legacy boolean format aliases. Kept working for back-compat but
2457
+ // omitted from the documented help; prefer `--format <kind>`.
2458
+ csv: { type: "boolean" },
2459
+ md: { type: "boolean" },
2460
+ xml: { type: "boolean" },
2461
+ files: { type: "boolean" },
2462
+ json: { type: "boolean" },
2463
+ explain: { type: "boolean" },
2464
+ collection: { type: "string", short: "c", multiple: true }, // Filter by collection(s)
2465
+ // Collection options
2466
+ name: { type: "string" }, // collection name
2467
+ mask: { type: "string" }, // glob pattern
2468
+ // Embed options
2469
+ force: { type: "boolean", short: "f" },
2470
+ "max-docs-per-batch": { type: "string" },
2471
+ "max-batch-mb": { type: "string" },
2472
+ // Update options
2473
+ pull: { type: "boolean" }, // git pull before update
2474
+ refresh: { type: "boolean" },
2475
+ // Get options
2476
+ l: { type: "string" }, // max lines
2477
+ from: { type: "string" }, // start line
2478
+ "max-bytes": { type: "string" }, // max bytes for multi-get
2479
+ "line-numbers": { type: "boolean" }, // add line numbers to output (search; default on for get/multi-get)
2480
+ "no-line-numbers": { type: "boolean" }, // disable line numbers for get/multi-get
2481
+ "full-path": { type: "boolean" }, // show on-disk paths instead of qmd:// (get/multi-get/search/query)
2482
+ // Query options
2483
+ "candidate-limit": { type: "string", short: "C" },
2484
+ "no-rerank": { type: "boolean", default: false },
2485
+ "no-gpu": { type: "boolean", default: false },
2486
+ intent: { type: "string" },
2487
+ // Chunking options
2488
+ "chunk-strategy": { type: "string" }, // "regex" (default) or "auto" (AST for code files)
2489
+ // MCP HTTP transport options
2490
+ http: { type: "boolean" },
2491
+ daemon: { type: "boolean" },
2492
+ port: { type: "string" },
2493
+ },
2494
+ allowPositionals: true,
2495
+ strict: false, // Allow unknown options to pass through
2496
+ });
2497
+ if (values["no-gpu"]) {
2498
+ process.env.QMD_FORCE_CPU = "1";
2499
+ }
2500
+ // Select index name (default: "index"). If no explicit --index is supplied,
2501
+ // a project-local .qmd/index.yaml overrides the global config/cache paths.
2502
+ const indexName = values.index;
2503
+ if (indexName) {
2504
+ setIndexName(indexName);
2505
+ setConfigIndexName(indexName);
2506
+ setConfigSource();
2507
+ }
2508
+ else {
2509
+ const localConfigPath = findLocalConfigPath();
2510
+ if (localConfigPath) {
2511
+ setConfigSource({ configPath: localConfigPath });
2512
+ storeDbPathOverride = getLocalDbPath(localConfigPath);
2513
+ closeDb();
2514
+ }
2515
+ else {
2516
+ setConfigSource();
2517
+ }
2518
+ }
2519
+ // Determine output format. Prefer --format <kind>; fall back to the
2520
+ // legacy boolean aliases (--csv/--md/--xml/--files/--json) which remain
2521
+ // wired up for back-compat but are no longer documented.
2522
+ let format = "cli";
2523
+ const rawFormat = typeof values.format === "string" ? values.format.toLowerCase().trim() : "";
2524
+ const VALID_FORMATS = ["cli", "json", "csv", "md", "xml", "files"];
2525
+ if (rawFormat) {
2526
+ if (VALID_FORMATS.includes(rawFormat)) {
2527
+ format = rawFormat;
2528
+ }
2529
+ else {
2530
+ console.error(`Unknown --format value: ${values.format}`);
2531
+ console.error(`Valid: ${VALID_FORMATS.join(", ")}`);
2532
+ process.exit(1);
2533
+ }
2534
+ }
2535
+ else if (values.csv)
2536
+ format = "csv";
2537
+ else if (values.md)
2538
+ format = "md";
2539
+ else if (values.xml)
2540
+ format = "xml";
2541
+ else if (values.files)
2542
+ format = "files";
2543
+ else if (values.json)
2544
+ format = "json";
2545
+ // Default limit: 20 for --files/--json, 5 otherwise
2546
+ // --all means return all results (use very large limit)
2547
+ const defaultLimit = (format === "files" || format === "json") ? 20 : 5;
2548
+ const isAll = !!values.all;
2549
+ const opts = {
2550
+ format,
2551
+ full: !!values.full,
2552
+ limit: isAll ? 100000 : (values.n ? parseInt(String(values.n), 10) || defaultLimit : defaultLimit),
2553
+ minScore: values["min-score"] ? parseFloat(String(values["min-score"])) || 0 : 0,
2554
+ all: isAll,
2555
+ collection: values.collection,
2556
+ lineNumbers: !!values["line-numbers"],
2557
+ candidateLimit: values["candidate-limit"] ? parseInt(String(values["candidate-limit"]), 10) : undefined,
2558
+ skipRerank: !!values["no-rerank"],
2559
+ explain: !!values.explain,
2560
+ intent: values.intent,
2561
+ chunkStrategy: parseChunkStrategy(values["chunk-strategy"]),
2562
+ fullPath: !!values["full-path"],
2563
+ };
2564
+ return {
2565
+ command: positionals[0] || "",
2566
+ args: positionals.slice(1),
2567
+ query: positionals.slice(1).join(" "),
2568
+ opts,
2569
+ values,
2570
+ };
2571
+ }
2572
+ function getSkillInstallDir(globalInstall) {
2573
+ return globalInstall
2574
+ ? resolve(homedir(), ".agents", "skills", "qmd")
2575
+ : resolve(getPwd(), ".agents", "skills", "qmd");
2576
+ }
2577
+ function getClaudeSkillLinkPath(globalInstall) {
2578
+ return globalInstall
2579
+ ? resolve(homedir(), ".claude", "skills", "qmd")
2580
+ : resolve(getPwd(), ".claude", "skills", "qmd");
2581
+ }
2582
+ function pathExists(path) {
2583
+ try {
2584
+ lstatSync(path);
2585
+ return true;
2586
+ }
2587
+ catch {
2588
+ return false;
2589
+ }
2590
+ }
2591
+ function removePath(path) {
2592
+ const stat = lstatSync(path);
2593
+ if (stat.isDirectory() && !stat.isSymbolicLink()) {
2594
+ rmSync(path, { recursive: true, force: true });
2595
+ }
2596
+ else {
2597
+ unlinkSync(path);
2598
+ }
2599
+ }
2600
+ const SKILL_DIR = "skills";
2601
+ function findPackageRoot() {
2602
+ if (process.env.QMD_SKILLS_DIR) {
2603
+ return null;
2604
+ }
2605
+ const start = dirname(fileURLToPath(import.meta.url));
2606
+ let current = start;
2607
+ while (true) {
2608
+ if (existsSync(resolve(current, SKILL_DIR))) {
2609
+ return current;
2610
+ }
2611
+ const parent = dirname(current);
2612
+ if (parent === current)
2613
+ break;
2614
+ current = parent;
2615
+ }
2616
+ return null;
2617
+ }
2618
+ function getSkillSearchDirs(_runtimeOnly = false) {
2619
+ if (process.env.QMD_SKILLS_DIR) {
2620
+ return [process.env.QMD_SKILLS_DIR];
2621
+ }
2622
+ const root = findPackageRoot();
2623
+ if (!root)
2624
+ return [];
2625
+ const dir = resolve(root, SKILL_DIR);
2626
+ return existsSync(dir) ? [dir] : [];
2627
+ }
2628
+ function parseSkillFrontmatter(content) {
2629
+ const trimmed = content.trimStart();
2630
+ if (!trimmed.startsWith("---"))
2631
+ return null;
2632
+ const end = trimmed.slice(3).indexOf("\n---");
2633
+ if (end < 0)
2634
+ return null;
2635
+ const frontmatter = trimmed.slice(3, 3 + end);
2636
+ let name = "";
2637
+ let description = "";
2638
+ let hidden = false;
2639
+ const lines = frontmatter.split(/\r?\n/);
2640
+ for (let i = 0; i < lines.length; i++) {
2641
+ const line = lines[i];
2642
+ if (line.startsWith("name:")) {
2643
+ name = line.slice("name:".length).trim();
2644
+ }
2645
+ else if (line.startsWith("description:")) {
2646
+ const parts = [line.slice("description:".length).trim()];
2647
+ while (i + 1 < lines.length && /^\s+\S/.test(lines[i + 1])) {
2648
+ i++;
2649
+ parts.push(lines[i].trim());
2650
+ }
2651
+ description = parts.join(" ");
2652
+ }
2653
+ else if (line.startsWith("hidden:")) {
2654
+ const value = line.slice("hidden:".length).trim().toLowerCase();
2655
+ hidden = value === "true" || value === "yes";
2656
+ }
2657
+ }
2658
+ if (!name)
2659
+ return null;
2660
+ return { name, description, hidden };
2661
+ }
2662
+ function discoverSkills(runtimeOnly = false) {
2663
+ const skills = [];
2664
+ for (const dir of getSkillSearchDirs(runtimeOnly)) {
2665
+ let entries = [];
2666
+ try {
2667
+ entries = readdirSync(dir);
2668
+ }
2669
+ catch {
2670
+ continue;
2671
+ }
2672
+ for (const entry of entries) {
2673
+ const skillDir = resolve(dir, entry);
2674
+ const skillPath = resolve(skillDir, "SKILL.md");
2675
+ if (!existsSync(skillPath))
2676
+ continue;
2677
+ let content = "";
2678
+ try {
2679
+ content = readFileSync(skillPath, "utf-8");
2680
+ }
2681
+ catch {
2682
+ continue;
2683
+ }
2684
+ const parsed = parseSkillFrontmatter(content);
2685
+ if (!parsed)
2686
+ continue;
2687
+ skills.push({ ...parsed, dir: skillDir });
2688
+ }
2689
+ }
2690
+ return skills.sort((a, b) => a.name.localeCompare(b.name));
2691
+ }
2692
+ function findSkill(name, runtimeOnly = false) {
2693
+ return discoverSkills(runtimeOnly).find((skill) => skill.name === name) ?? null;
2694
+ }
2695
+ function readSkillContent(skill) {
2696
+ return readFileSync(resolve(skill.dir, "SKILL.md"), "utf-8");
2697
+ }
2698
+ function collectSkillFiles(skill) {
2699
+ const files = [];
2700
+ for (const subdirName of ["references", "templates", "scripts"]) {
2701
+ const subdir = resolve(skill.dir, subdirName);
2702
+ if (!existsSync(subdir))
2703
+ continue;
2704
+ for (const entry of readdirSync(subdir).sort()) {
2705
+ const filePath = resolve(subdir, entry);
2706
+ try {
2707
+ if (!statSync(filePath).isFile())
2708
+ continue;
2709
+ files.push({ relativePath: `${subdirName}/${basename(filePath)}`, content: readFileSync(filePath, "utf-8") });
2710
+ }
2711
+ catch {
2712
+ // Ignore unreadable supplementary files.
2713
+ }
2714
+ }
2715
+ }
2716
+ return files;
2717
+ }
2718
+ function showSkill() {
2719
+ const skill = findSkill("qmd");
2720
+ if (!skill) {
2721
+ throw new Error("QMD skill not found. Reinstall qmd or set QMD_SKILLS_DIR.");
2722
+ }
2723
+ console.log("QMD Skill");
2724
+ console.log("");
2725
+ const content = readSkillContent(skill);
2726
+ process.stdout.write(content.endsWith("\n") ? content : content + "\n");
2727
+ }
2728
+ function copyDirectoryContents(sourceDir, targetDir) {
2729
+ mkdirSync(targetDir, { recursive: true });
2730
+ for (const entry of readdirSync(sourceDir)) {
2731
+ const sourcePath = resolve(sourceDir, entry);
2732
+ const targetPath = resolve(targetDir, entry);
2733
+ const stat = statSync(sourcePath);
2734
+ if (stat.isDirectory()) {
2735
+ copyDirectoryContents(sourcePath, targetPath);
2736
+ }
2737
+ else if (stat.isFile()) {
2738
+ copyFileSync(sourcePath, targetPath);
2739
+ }
2740
+ }
2741
+ }
2742
+ function installedSkillStubContent() {
2743
+ return `---
2744
+ name: qmd
2745
+ description: Bootstrap QMD search instructions from the installed qmd CLI. Use when users ask to find notes, retrieve documents, inspect a wiki, or answer from indexed local markdown.
2746
+ license: MIT
2747
+ compatibility: Requires qmd CLI. Run \`qmd skill show\` for version-matched instructions.
2748
+ allowed-tools: Bash(qmd:*), mcp__qmd__*
2749
+ ---
2750
+
2751
+ # QMD - Query Markdown Documents
2752
+
2753
+ This installed skill is intentionally a small bootstrap so it does not go stale
2754
+ when the qmd package updates.
2755
+
2756
+ Load the full, version-matched QMD instructions from the CLI:
2757
+
2758
+ !\`qmd skill show\`
2759
+
2760
+ If your agent does not support bang-command expansion, run:
2761
+
2762
+ \`\`\`bash
2763
+ qmd skill show
2764
+ \`\`\`
2765
+
2766
+ Then follow those instructions. In short: search first, fetch full sources with
2767
+ \`qmd get\` or \`qmd multi-get\`, and answer from retrieved text rather than snippets.
2768
+ `;
2769
+ }
2770
+ function writeSkillInstall(targetDir, force) {
2771
+ if (pathExists(targetDir)) {
2772
+ if (!force) {
2773
+ throw new Error(`Skill already exists: ${targetDir} (use --force to replace it)`);
2774
+ }
2775
+ removePath(targetDir);
2776
+ }
2777
+ const skill = findSkill("qmd");
2778
+ if (!skill) {
2779
+ throw new Error("QMD skill not found. Reinstall qmd or set QMD_SKILLS_DIR.");
2780
+ }
2781
+ copyDirectoryContents(skill.dir, targetDir);
2782
+ writeFileSync(resolve(targetDir, "SKILL.md"), installedSkillStubContent(), "utf-8");
2783
+ }
2784
+ function outputSkillsJson(payload) {
2785
+ console.log(JSON.stringify(payload));
2786
+ }
2787
+ function runSkillsCommand(args, jsonMode, fullOption = false, allOption = false) {
2788
+ const subcommand = args[0] ?? "list";
2789
+ const runtimeSkills = () => discoverSkills(true).filter((skill) => !skill.hidden);
2790
+ switch (subcommand) {
2791
+ case "list": {
2792
+ const skills = runtimeSkills();
2793
+ if (jsonMode) {
2794
+ outputSkillsJson({ success: true, data: skills.map(({ name, description }) => ({ name, description })) });
2795
+ return;
2796
+ }
2797
+ if (skills.length === 0) {
2798
+ console.log("No skills found");
2799
+ return;
2800
+ }
2801
+ const maxName = Math.max(...skills.map((skill) => skill.name.length));
2802
+ for (const skill of skills) {
2803
+ console.log(` ${skill.name.padEnd(maxName)} ${skill.description}`);
2804
+ }
2805
+ return;
2806
+ }
2807
+ case "get": {
2808
+ const full = fullOption || args.includes("--full");
2809
+ const getAll = allOption || args.includes("--all");
2810
+ const names = args.slice(1).filter((arg) => arg !== "--full" && arg !== "--all");
2811
+ const targets = getAll ? runtimeSkills() : names.map((name) => {
2812
+ const skill = findSkill(name, true);
2813
+ if (!skill) {
2814
+ throw new Error(`Skill not found: ${name}`);
2815
+ }
2816
+ return skill;
2817
+ });
2818
+ if (targets.length === 0) {
2819
+ throw new Error("No skill name provided. Usage: qmd skills get <name>");
2820
+ }
2821
+ if (jsonMode) {
2822
+ outputSkillsJson({
2823
+ success: true,
2824
+ data: targets.map((skill) => ({
2825
+ name: skill.name,
2826
+ content: readSkillContent(skill),
2827
+ ...(full ? { files: collectSkillFiles(skill).map((file) => ({ path: file.relativePath, content: file.content })) } : {}),
2828
+ })),
2829
+ });
2830
+ return;
2831
+ }
2832
+ targets.forEach((skill, index) => {
2833
+ if (index > 0)
2834
+ console.log("\n---\n");
2835
+ const content = readSkillContent(skill);
2836
+ process.stdout.write(content.endsWith("\n") ? content : content + "\n");
2837
+ if (full) {
2838
+ for (const file of collectSkillFiles(skill)) {
2839
+ console.log(`\n--- ${file.relativePath} ---\n`);
2840
+ process.stdout.write(file.content.endsWith("\n") ? file.content : file.content + "\n");
2841
+ }
2842
+ }
2843
+ });
2844
+ return;
2845
+ }
2846
+ case "path": {
2847
+ const name = args[1];
2848
+ if (!name) {
2849
+ const paths = getSkillSearchDirs(true);
2850
+ if (jsonMode)
2851
+ outputSkillsJson({ success: true, data: { paths } });
2852
+ else
2853
+ paths.forEach((path) => console.log(path));
2854
+ return;
2855
+ }
2856
+ const skill = findSkill(name, true);
2857
+ if (!skill) {
2858
+ throw new Error(`Skill not found: ${name}`);
2859
+ }
2860
+ if (jsonMode)
2861
+ outputSkillsJson({ success: true, data: { name: skill.name, path: skill.dir } });
2862
+ else
2863
+ console.log(skill.dir);
2864
+ return;
2865
+ }
2866
+ case "help": {
2867
+ showSkillsHelp();
2868
+ return;
2869
+ }
2870
+ default:
2871
+ throw new Error(`Unknown skills subcommand: ${subcommand}`);
2872
+ }
2873
+ }
2874
+ function showSkillsHelp() {
2875
+ console.log("Usage: qmd skills <list|get|path> [options]");
2876
+ console.log("");
2877
+ console.log("Commands:");
2878
+ console.log(" list List bundled runtime skills");
2879
+ console.log(" get <name> Print a bundled runtime skill");
2880
+ console.log(" get <name> --full Include references/templates/scripts");
2881
+ console.log(" get --all Print all bundled runtime skills");
2882
+ console.log(" path [name] Print runtime skill directory path(s)");
2883
+ console.log("");
2884
+ console.log("Options:");
2885
+ console.log(" --json Print structured JSON");
2886
+ }
2887
+ function ensureClaudeSymlink(linkPath, targetDir, force) {
2888
+ const parentDir = dirname(linkPath);
2889
+ if (pathExists(parentDir)) {
2890
+ const resolvedTargetDir = realpathSync(dirname(targetDir));
2891
+ const resolvedLinkParent = realpathSync(parentDir);
2892
+ // If .claude/skills already resolves to the same directory as .agents/skills,
2893
+ // the skill is already visible to Claude and creating qmd -> qmd would loop.
2894
+ if (resolvedTargetDir === resolvedLinkParent) {
2895
+ return false;
2896
+ }
2897
+ }
2898
+ const linkTarget = relativePath(parentDir, targetDir) || ".";
2899
+ mkdirSync(parentDir, { recursive: true });
2900
+ if (pathExists(linkPath)) {
2901
+ const stat = lstatSync(linkPath);
2902
+ if (stat.isSymbolicLink() && readlinkSync(linkPath) === linkTarget) {
2903
+ return true;
2904
+ }
2905
+ if (!force) {
2906
+ throw new Error(`Claude skill path already exists: ${linkPath} (use --force to replace it)`);
2907
+ }
2908
+ removePath(linkPath);
2909
+ }
2910
+ symlinkSync(linkTarget, linkPath, "dir");
2911
+ return true;
2912
+ }
2913
+ async function shouldCreateClaudeSymlink(linkPath, autoYes) {
2914
+ if (autoYes) {
2915
+ return true;
2916
+ }
2917
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
2918
+ console.log(`Tip: create a Claude symlink manually at ${linkPath}`);
2919
+ return false;
2920
+ }
2921
+ const rl = createInterface({
2922
+ input: process.stdin,
2923
+ output: process.stdout,
2924
+ });
2925
+ try {
2926
+ const answer = await rl.question(`Create a symlink in ${linkPath}? [y/N] `);
2927
+ const normalized = answer.trim().toLowerCase();
2928
+ return normalized === "y" || normalized === "yes";
2929
+ }
2930
+ finally {
2931
+ rl.close();
2932
+ }
2933
+ }
2934
+ async function installSkill(globalInstall, force, autoYes) {
2935
+ const installDir = getSkillInstallDir(globalInstall);
2936
+ writeSkillInstall(installDir, force);
2937
+ console.log(`✓ Installed QMD skill to ${installDir}`);
2938
+ const claudeLinkPath = getClaudeSkillLinkPath(globalInstall);
2939
+ if (!(await shouldCreateClaudeSymlink(claudeLinkPath, autoYes))) {
2940
+ return;
2941
+ }
2942
+ const linked = ensureClaudeSymlink(claudeLinkPath, installDir, force);
2943
+ if (linked) {
2944
+ console.log(`✓ Linked Claude skill at ${claudeLinkPath}`);
2945
+ }
2946
+ else {
2947
+ console.log(`✓ Claude already sees the skill via ${dirname(claudeLinkPath)}`);
2948
+ }
2949
+ }
2950
+ function showHelp() {
2951
+ console.log("qmd — Quick Markdown Search");
2952
+ console.log("");
2953
+ console.log("Usage:");
2954
+ console.log(" qmd <command> [options]");
2955
+ console.log("");
2956
+ console.log("Primary commands:");
2957
+ console.log(" qmd query <query> - Hybrid search with auto expansion + reranking (recommended)");
2958
+ console.log(" qmd query 'lex:..\\nvec:...' - Structured query document (you provide lex/vec/hyde lines)");
2959
+ console.log(" qmd search <query> - Full-text BM25 keywords (no LLM)");
2960
+ console.log(" qmd vsearch <query> - Vector similarity only");
2961
+ console.log(" qmd get <file>[:from[:count]] - Show a document (line-numbered; #docid in header)");
2962
+ console.log(" qmd multi-get <pattern> - Batch fetch via glob or comma-separated list");
2963
+ console.log(" qmd skills list/get/path - List and retrieve bundled runtime skills");
2964
+ console.log(" qmd skill show/install - Show or install the QMD skill");
2965
+ console.log(" qmd mcp - Start the MCP server (stdio transport for AI agents)");
2966
+ console.log(" qmd bench <fixture.json> - Run search quality benchmarks against a fixture file");
2967
+ console.log("");
2968
+ console.log("Collections & context:");
2969
+ console.log(" qmd collection add/list/remove/rename/show - Manage indexed folders");
2970
+ console.log(" qmd context add/list/rm - Attach human-written summaries");
2971
+ console.log(" qmd ls [collection[/path]] - Inspect indexed files");
2972
+ console.log("");
2973
+ console.log("Maintenance:");
2974
+ console.log(" qmd init - Create a project-local .qmd index");
2975
+ console.log(" qmd status - View index + collection health");
2976
+ console.log(" qmd update [--pull] - Re-index collections (optionally git pull first)");
2977
+ console.log(" qmd embed [-f] [-c <name>] - Generate/refresh vector embeddings");
2978
+ console.log(" --max-docs-per-batch <n> - Cap docs loaded into memory per embedding batch");
2979
+ console.log(" --max-batch-mb <n> - Cap UTF-8 MB loaded into memory per embedding batch");
2980
+ console.log(" qmd cleanup - Clear caches, vacuum DB");
2981
+ console.log("");
2982
+ console.log("Query syntax (qmd query):");
2983
+ console.log(" QMD queries are either a single expand query (no prefix) or a multi-line");
2984
+ console.log(" document where every line is typed with lex:, vec:, or hyde:. This grammar");
2985
+ console.log(" matches the docs in docs/SYNTAX.md and is enforced in the CLI.");
2986
+ console.log("");
2987
+ const grammar = [
2988
+ `query = expand_query | query_document ;`,
2989
+ `expand_query = text | explicit_expand ;`,
2990
+ `explicit_expand= "expand:" text ;`,
2991
+ `query_document = [ intent_line ] { typed_line } ;`,
2992
+ `intent_line = "intent:" text newline ;`,
2993
+ `typed_line = type ":" text newline ;`,
2994
+ `type = "lex" | "vec" | "hyde" ;`,
2995
+ `text = quoted_phrase | plain_text ;`,
2996
+ `quoted_phrase = '"' { character } '"' ;`,
2997
+ `plain_text = { character } ;`,
2998
+ `newline = "\\n" ;`,
2999
+ ];
3000
+ console.log(" Grammar:");
3001
+ for (const line of grammar) {
3002
+ console.log(` ${line}`);
3003
+ }
3004
+ console.log("");
3005
+ console.log(" Examples:");
3006
+ console.log(" qmd query \"how does auth work\" # single-line → implicit expand");
3007
+ console.log(" qmd query $'lex: CAP theorem\\nvec: consistency' # typed query document");
3008
+ console.log(" qmd query $'lex: \"exact matches\" sports -baseball' # phrase + negation lex search");
3009
+ console.log(" qmd query $'hyde: Hypothetical answer text' # hyde-only document");
3010
+ console.log("");
3011
+ console.log(" Constraints:");
3012
+ console.log(" - Standalone expand queries cannot mix with typed lines.");
3013
+ console.log(" - Query documents allow only lex:, vec:, or hyde: prefixes.");
3014
+ console.log(" - Each typed line must be single-line text with balanced quotes.");
3015
+ console.log("");
3016
+ console.log("AI agents & integrations:");
3017
+ console.log(" - Run `qmd mcp` to expose the MCP server (stdio) to agents/IDEs.");
3018
+ console.log(" - Run `qmd skills get qmd --full` for version-matched agent instructions.");
3019
+ console.log(" - `qmd skill install` installs the QMD skill into ./.agents/skills/qmd.");
3020
+ console.log(" - Use `qmd skill install --global` for ~/.agents/skills/qmd.");
3021
+ console.log(" - `qmd --skill` is kept as an alias for `qmd skill show`.");
3022
+ console.log(" - Advanced: `qmd mcp --http ...` and `qmd mcp --http --daemon` are optional for custom transports.");
3023
+ console.log("");
3024
+ console.log("Global options:");
3025
+ console.log(" --index <name> - Use a named index (default: index)");
3026
+ console.log(" QMD_EDITOR_URI - Editor link template for clickable TTY search output");
3027
+ console.log("");
3028
+ console.log("Search options:");
3029
+ console.log(" -n <num> - Max results (default 5, or 20 for --format files|json)");
3030
+ console.log(" --all - Return all matches (pair with --min-score)");
3031
+ console.log(" --min-score <num> - Minimum similarity score");
3032
+ console.log(" --full - Output full document instead of snippet");
3033
+ console.log(" -C, --candidate-limit <n> - Max candidates to rerank (default 40, lower = faster)");
3034
+ console.log(" --no-rerank - Skip LLM reranking (use RRF scores only, much faster on CPU)");
3035
+ console.log(" --no-gpu - Force CPU mode for llama.cpp operations (same as QMD_FORCE_CPU=1)");
3036
+ console.log(" --line-numbers - Include line numbers (search; get/multi-get are on by default)");
3037
+ console.log(" --no-line-numbers - Disable line numbers for get/multi-get");
3038
+ console.log(" --full-path - Show on-disk paths instead of qmd:// + docid (get/multi-get/search/query)");
3039
+ console.log(" Paths are ./-prefixed when under $PWD, absolute otherwise");
3040
+ console.log(" --explain - Include retrieval score traces (query, CLI/--format json)");
3041
+ console.log(" --format <kind> - Output format: cli (default) | json | csv | md | xml | files");
3042
+ console.log(" -c, --collection <name> - Filter by one or more collections");
3043
+ console.log("");
3044
+ console.log("Embed/query options:");
3045
+ console.log(" --chunk-strategy <auto|regex> - Chunking mode (default: regex; auto uses AST for code files)");
3046
+ console.log("");
3047
+ console.log("Multi-get options:");
3048
+ console.log(" -l <num> - Maximum lines per file");
3049
+ console.log(" --max-bytes <num> - Skip files larger than N bytes (default 10240)");
3050
+ console.log(" --format <kind> - Same formats as search");
3051
+ console.log("");
3052
+ console.log(`Index: ${getDbPath()}`);
3053
+ }
3054
+ function doctorCheck(label, ok, details) {
3055
+ const mark = ok ? `${c.green}✓${c.reset}` : `${c.yellow}⚠${c.reset}`;
3056
+ console.log(`${mark} ${label}: ${details}`);
3057
+ }
3058
+ function formatCount(n) {
3059
+ return n.toLocaleString("en-US");
3060
+ }
3061
+ function shortModelName(model) {
3062
+ if (model.startsWith("hf:")) {
3063
+ return model.split("/").pop() || model;
3064
+ }
3065
+ return model.length > 56 ? `${model.slice(0, 53)}...` : model;
3066
+ }
3067
+ function normalizedDoctorNextSteps(steps) {
3068
+ const unique = Array.from(new Set(steps));
3069
+ const hasForceEmbed = unique.some(step => step.includes("qmd embed --force"));
3070
+ if (!hasForceEmbed)
3071
+ return unique;
3072
+ return unique.filter(step => !step.includes("qmd embed") || step.startsWith("Run `qmd embed --force`"));
3073
+ }
3074
+ function shortHashSeq(hashSeq) {
3075
+ const idx = hashSeq.lastIndexOf("_");
3076
+ if (idx < 0)
3077
+ return hashSeq.length > 18 ? `${hashSeq.slice(0, 18)}...` : hashSeq;
3078
+ return `${hashSeq.slice(0, 12)}_${hashSeq.slice(idx + 1)}`;
3079
+ }
3080
+ function decodeStoredEmbedding(bytes) {
3081
+ return new Float32Array(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
3082
+ }
3083
+ function cosineDistance(a, b) {
3084
+ if (a.length !== b.length || a.length === 0)
3085
+ return Number.POSITIVE_INFINITY;
3086
+ let dot = 0;
3087
+ let normA = 0;
3088
+ let normB = 0;
3089
+ for (let i = 0; i < a.length; i++) {
3090
+ const av = a[i] ?? 0;
3091
+ const bv = b[i] ?? 0;
3092
+ dot += av * bv;
3093
+ normA += av * av;
3094
+ normB += bv * bv;
3095
+ }
3096
+ if (normA === 0 || normB === 0)
3097
+ return Number.POSITIVE_INFINITY;
3098
+ return 1 - (dot / (Math.sqrt(normA) * Math.sqrt(normB)));
3099
+ }
3100
+ function formatModelDiagnosticPath(path) {
3101
+ return sanitizeDiagnosticMessage(path);
3102
+ }
3103
+ function findCachedModelInspection(model) {
3104
+ const invalid = [];
3105
+ if (model.startsWith("hf:")) {
3106
+ const filename = model.split("/").pop();
3107
+ if (!filename || !existsSync(DEFAULT_MODEL_CACHE_DIR))
3108
+ return { path: null, invalid };
3109
+ const entries = readdirSync(DEFAULT_MODEL_CACHE_DIR, { withFileTypes: true });
3110
+ for (const entry of entries) {
3111
+ if (!entry.isFile() || !entry.name.includes(filename))
3112
+ continue;
3113
+ const candidate = pathJoin(DEFAULT_MODEL_CACHE_DIR, entry.name);
3114
+ const inspection = inspectGgufFile(candidate);
3115
+ if (inspection.valid)
3116
+ return { path: candidate, invalid };
3117
+ invalid.push(`${formatModelDiagnosticPath(candidate)}: ${inspection.details}`);
3118
+ }
3119
+ return { path: null, invalid };
3120
+ }
3121
+ const inspection = inspectGgufFile(model);
3122
+ if (inspection.valid)
3123
+ return { path: model, invalid };
3124
+ if (inspection.exists)
3125
+ invalid.push(`${formatModelDiagnosticPath(model)}: ${inspection.details}`);
3126
+ return { path: null, invalid };
3127
+ }
3128
+ function envValueForDisplay(value) {
3129
+ const sanitized = sanitizeDiagnosticMessage(value);
3130
+ return sanitized.length > 96 ? `${sanitized.slice(0, 93)}...` : sanitized;
3131
+ }
3132
+ function collectEnvironmentOverrides(activeModels, configModels = {}) {
3133
+ const overrides = [];
3134
+ const add = (name, consequence) => {
3135
+ const raw = process.env[name]?.trim();
3136
+ if (!raw)
3137
+ return;
3138
+ overrides.push({ name, value: envValueForDisplay(raw), consequence });
3139
+ };
3140
+ const addModel = (name, key, active) => {
3141
+ const raw = process.env[name]?.trim();
3142
+ if (!raw)
3143
+ return;
3144
+ const configured = configModels[key];
3145
+ const consequence = configured && configured !== raw
3146
+ ? `set but ignored because index models.${key} is configured as ${configured}`
3147
+ : `sets the active ${key} model to ${active}; changes embedding/search semantics and may require \`qmd pull\` plus \`qmd embed\``;
3148
+ overrides.push({ name, value: envValueForDisplay(raw), consequence });
3149
+ };
3150
+ add("INDEX_PATH", "overrides the SQLite index path; QMD reads/writes a different database");
3151
+ add("QMD_CONFIG_DIR", "overrides the QMD config directory and takes precedence over XDG_CONFIG_HOME");
3152
+ add("XDG_CONFIG_HOME", "moves QMD config to $XDG_CONFIG_HOME/qmd when QMD_CONFIG_DIR is not set");
3153
+ add("XDG_CACHE_HOME", "moves the default index cache, model cache, and MCP daemon PID files");
3154
+ addModel("QMD_EMBED_MODEL", "embed", activeModels.embed);
3155
+ addModel("QMD_GENERATE_MODEL", "generate", activeModels.generate);
3156
+ addModel("QMD_RERANK_MODEL", "rerank", activeModels.rerank);
3157
+ add("QMD_FORCE_CPU", "forces llama.cpp to bypass GPU backends; embeddings/query will be slower but GPU crashes are avoided");
3158
+ add("QMD_LLAMA_GPU", "selects llama.cpp GPU backend (metal/cuda/vulkan) or disables GPU when set to false/off/0");
3159
+ add("QMD_DOCTOR_DEVICE_PROBE", "controls qmd doctor native device probing; 0/off skips GPU probing");
3160
+ add("QMD_EMBED_PARALLELISM", "overrides embedding parallel context count; too high can exhaust RAM/VRAM");
3161
+ add("QMD_EXPAND_CONTEXT_SIZE", "overrides query expansion context size; larger values use more memory");
3162
+ add("QMD_RERANK_CONTEXT_SIZE", "overrides reranker context size; larger values use more memory");
3163
+ add("QMD_EMBED_CONTEXT_SIZE", "overrides embed context size; larger values use more memory");
3164
+ add("QMD_EDITOR_URI", "overrides clickable editor link template in terminal output");
3165
+ add("QMD_SKILLS_DIR", "overrides where qmd skills are discovered from");
3166
+ add("QMD_METAL_KEEP_RESIDENCY", "opts back into libggml-metal residency sets on darwin; restores ~0ms perf wins for long-lived processes but re-exposes the static-destructor backtrace dump at process exit (ggml-org/llama.cpp#22593)");
3167
+ add("GGML_METAL_NO_RESIDENCY", "set automatically by the launcher on darwin to disable Metal residency sets (avoids ggml-org/llama.cpp#22593); override via QMD_METAL_KEEP_RESIDENCY=1");
3168
+ add("NO_COLOR", "disables colored terminal output");
3169
+ add("CI", "disables real LLM operations inside QMD's LlamaCpp wrapper");
3170
+ add("HF_ENDPOINT", "changes Hugging Face download endpoint used when pulling models");
3171
+ add("QMD_WRAPPER_CAPTURE", "test/debug hook for the qmd shell wrapper; should not be set in normal use");
3172
+ add("WSL_DISTRO_NAME", "enables WSL path handling heuristics");
3173
+ add("WSL_INTEROP", "enables WSL path handling heuristics");
3174
+ return overrides;
3175
+ }
3176
+ function checkDoctorIndexConfig(nextSteps) {
3177
+ try {
3178
+ const config = loadConfig();
3179
+ const collectionCount = Object.keys(config.collections ?? {}).length;
3180
+ if (collectionCount === 0) {
3181
+ doctorCheck("index config", false, "no collections configured. Next: `qmd collection add .`");
3182
+ nextSteps.push("Run `qmd collection add . --name <name>` from the folder you want to index, or edit .qmd/index.yml manually.");
3183
+ }
3184
+ else {
3185
+ doctorCheck("index config", true, `${formatCount(collectionCount)} ${collectionCount === 1 ? "collection" : "collections"} configured`);
3186
+ }
3187
+ return { config, valid: true };
3188
+ }
3189
+ catch (error) {
3190
+ const message = error instanceof Error ? sanitizeDiagnosticMessage(error.message) : sanitizeDiagnosticMessage(String(error));
3191
+ const configPath = getConfigPath();
3192
+ doctorCheck("index config", false, `invalid index.yml at ${configPath}: ${message}. Next: fix the YAML and rerun \`qmd doctor\``);
3193
+ nextSteps.push(`Fix invalid YAML in ${configPath}, then rerun \`qmd doctor\`.`);
3194
+ return { config: null, valid: false };
3195
+ }
3196
+ }
3197
+ function checkEnvironmentOverrides(activeModels, configModels = {}) {
3198
+ const overrides = collectEnvironmentOverrides(activeModels, configModels);
3199
+ if (overrides.length === 0) {
3200
+ doctorCheck("environment overrides", true, "none");
3201
+ return;
3202
+ }
3203
+ doctorCheck("environment overrides", false, `${overrides.length} set`);
3204
+ for (const override of overrides) {
3205
+ console.log(` - ${override.name}=${override.value}: ${override.consequence}`);
3206
+ }
3207
+ }
3208
+ function checkModelDefaults(activeModels, configModels = {}) {
3209
+ const checks = [
3210
+ { role: "embedding", key: "embed", active: activeModels.embed, configured: configModels.embed, defaultModel: DEFAULT_EMBED_MODEL, envName: "QMD_EMBED_MODEL", envValue: process.env.QMD_EMBED_MODEL },
3211
+ { role: "generation", key: "generate", active: activeModels.generate, configured: configModels.generate, defaultModel: DEFAULT_QUERY_MODEL, envName: "QMD_GENERATE_MODEL", envValue: process.env.QMD_GENERATE_MODEL },
3212
+ { role: "reranking", key: "rerank", active: activeModels.rerank, configured: configModels.rerank, defaultModel: DEFAULT_RERANK_MODEL, envName: "QMD_RERANK_MODEL", envValue: process.env.QMD_RERANK_MODEL },
3213
+ ];
3214
+ const notes = [];
3215
+ for (const check of checks) {
3216
+ const envValue = check.envValue?.trim();
3217
+ if (envValue && check.active === envValue) {
3218
+ notes.push(`${check.role}: env ${check.envName}=${check.active} (default ${check.defaultModel}; might be ok)`);
3219
+ }
3220
+ else if (check.configured && check.configured !== check.defaultModel) {
3221
+ notes.push(`${check.role}: index ${check.configured} (default ${check.defaultModel}; might be ok)`);
3222
+ }
3223
+ else if (envValue && check.active !== envValue) {
3224
+ notes.push(`${check.role}: ${check.envName} is set to ${envValue} but index config uses ${check.active}`);
3225
+ }
3226
+ }
3227
+ if (notes.length === 0) {
3228
+ doctorCheck("model defaults", true, "using QMD codebase defaults");
3229
+ return;
3230
+ }
3231
+ doctorCheck("model defaults", false, `non-default model configuration: ${notes.join("; ")}`);
3232
+ }
3233
+ function checkModelCache(activeModels, nextSteps) {
3234
+ const models = [
3235
+ ["embedding", activeModels.embed],
3236
+ ["generation", activeModels.generate],
3237
+ ["reranking", activeModels.rerank],
3238
+ ];
3239
+ const unique = new Map();
3240
+ for (const [role, model] of models) {
3241
+ unique.set(model, [...(unique.get(model) ?? []), role]);
3242
+ }
3243
+ const missing = [];
3244
+ const cached = [];
3245
+ const invalid = [];
3246
+ for (const [model, roles] of unique) {
3247
+ const label = `${roles.join("+")}: ${model}`;
3248
+ const inspection = findCachedModelInspection(model);
3249
+ invalid.push(...inspection.invalid.map(detail => `${label} (${detail})`));
3250
+ if (inspection.path) {
3251
+ cached.push(label);
3252
+ }
3253
+ else {
3254
+ missing.push(label);
3255
+ }
3256
+ }
3257
+ if (missing.length === 0 && invalid.length === 0) {
3258
+ doctorCheck("model cache", true, `${cached.length} active ${cached.length === 1 ? "model is" : "models are"} downloaded and valid GGUF`);
3259
+ return;
3260
+ }
3261
+ const parts = [];
3262
+ if (invalid.length > 0)
3263
+ parts.push(`invalid ${invalid.length}: ${invalid.join("; ")}`);
3264
+ if (missing.length > 0)
3265
+ parts.push(`missing ${missing.length}/${unique.size}: ${missing.join("; ")}`);
3266
+ const next = invalid.length > 0
3267
+ ? "Next: run `qmd pull --refresh` (or remove the bad cached file)"
3268
+ : "Next: run `qmd pull`";
3269
+ doctorCheck("model cache", false, `${parts.join("; ")}. ${next}`);
3270
+ if (invalid.length > 0) {
3271
+ nextSteps.push("Run `qmd pull --refresh` to replace invalid cached model files, or delete the listed file and rerun `qmd pull`.");
3272
+ }
3273
+ else {
3274
+ nextSteps.push("Run `qmd pull` to download missing embedding/generation/reranking models before `qmd embed` or `qmd query`.");
3275
+ }
3276
+ }
3277
+ async function checkEmbeddingVectorSamples(db, model, fingerprint, sampleSize = 3) {
3278
+ const activeDocs = db.prepare(`SELECT COUNT(*) AS count FROM documents WHERE active = 1`).get().count;
3279
+ if (activeDocs === 0) {
3280
+ return { ok: true, details: "no active documents indexed" };
3281
+ }
3282
+ const vecTableExists = db.prepare(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='vectors_vec'`).get();
3283
+ if (!vecTableExists) {
3284
+ return { ok: false, details: "no vector table to test; please run qmd embed again" };
3285
+ }
3286
+ const samples = db.prepare(`
3287
+ SELECT cv.hash, cv.seq, c.doc AS body, MIN(d.path) AS path
3288
+ FROM content_vectors cv
3289
+ JOIN documents d ON d.hash = cv.hash AND d.active = 1
3290
+ JOIN content c ON c.hash = cv.hash
3291
+ WHERE cv.model = ? AND cv.embed_fingerprint = ?
3292
+ GROUP BY cv.hash, cv.seq, c.doc
3293
+ ORDER BY random()
3294
+ LIMIT ?
3295
+ `).all(model, fingerprint, sampleSize);
3296
+ if (samples.length === 0) {
3297
+ return { ok: false, details: "no current embedded chunks to test; please run qmd embed again" };
3298
+ }
3299
+ const threshold = 0.0001;
3300
+ const mismatches = [];
3301
+ await withLLMSession(async (session) => {
3302
+ for (const sample of samples) {
3303
+ const hashSeq = `${sample.hash}_${sample.seq}`;
3304
+ const chunks = await chunkDocumentByTokens(sample.body, undefined, undefined, undefined, sample.path, undefined, session.signal);
3305
+ const chunk = chunks[sample.seq];
3306
+ if (!chunk) {
3307
+ mismatches.push(`${shortHashSeq(hashSeq)}: chunk no longer exists`);
3308
+ continue;
3309
+ }
3310
+ const title = extractTitle(sample.body, sample.path);
3311
+ const result = await session.embed(formatDocForEmbedding(chunk.text, title, model), { model });
3312
+ if (!result) {
3313
+ mismatches.push(`${shortHashSeq(hashSeq)}: embedding failed`);
3314
+ continue;
3315
+ }
3316
+ const stored = db.prepare(`SELECT embedding FROM vectors_vec WHERE hash_seq = ?`).get(hashSeq);
3317
+ if (!stored) {
3318
+ mismatches.push(`${shortHashSeq(hashSeq)}: stored vector missing`);
3319
+ continue;
3320
+ }
3321
+ const distance = cosineDistance(result.embedding, decodeStoredEmbedding(stored.embedding));
3322
+ if (distance > threshold) {
3323
+ mismatches.push(`${shortHashSeq(hashSeq)}: stored vector distance ${distance.toFixed(6)}`);
3324
+ }
3325
+ }
3326
+ }, { maxDuration: 10 * 60 * 1000, name: "doctorEmbeddingVectorSample" });
3327
+ if (mismatches.length > 0) {
3328
+ return {
3329
+ ok: false,
3330
+ details: `${mismatches.length}/${samples.length} sampled chunks differ from stored vectors (${mismatches[0]}). Rebuild with \`qmd embed --force\``,
3331
+ };
3332
+ }
3333
+ return {
3334
+ ok: true,
3335
+ details: `${samples.length} sampled ${samples.length === 1 ? "chunk" : "chunks"} reproduce stored vectors`,
3336
+ };
3337
+ }
3338
+ function hasLibraryInDirs(libraryBaseName, dirs) {
3339
+ for (const dir of dirs) {
3340
+ if (!dir || !existsSync(dir))
3341
+ continue;
3342
+ try {
3343
+ for (const entry of readdirSync(dir)) {
3344
+ if (entry === libraryBaseName || entry.startsWith(`${libraryBaseName}.`))
3345
+ return true;
3346
+ }
3347
+ }
3348
+ catch { /* ignore unreadable system library dirs */ }
3349
+ }
3350
+ return false;
3351
+ }
3352
+ function linuxCudaRuntimeDiagnostic() {
3353
+ if (process.platform !== "linux")
3354
+ return null;
3355
+ const dirs = new Set();
3356
+ for (const value of [process.env.LD_LIBRARY_PATH, process.env.CUDA_PATH]) {
3357
+ for (const part of (value ?? "").split(":")) {
3358
+ if (part)
3359
+ dirs.add(part);
3360
+ }
3361
+ }
3362
+ if (process.env.CUDA_PATH) {
3363
+ dirs.add(pathJoin(process.env.CUDA_PATH, "lib64"));
3364
+ dirs.add(pathJoin(process.env.CUDA_PATH, "targets", "x86_64-linux", "lib"));
3365
+ }
3366
+ for (const dir of ["/usr/lib", "/usr/lib64", "/usr/lib/x86_64-linux-gnu", "/usr/local/cuda/lib64", "/usr/local/cuda/targets/x86_64-linux/lib"]) {
3367
+ dirs.add(dir);
3368
+ }
3369
+ try {
3370
+ for (const entry of readdirSync("/usr/local")) {
3371
+ if (!entry.toLowerCase().startsWith("cuda-"))
3372
+ continue;
3373
+ const cudaRoot = pathJoin("/usr/local", entry);
3374
+ dirs.add(pathJoin(cudaRoot, "lib64"));
3375
+ dirs.add(pathJoin(cudaRoot, "targets", "x86_64-linux", "lib"));
3376
+ }
3377
+ }
3378
+ catch { /* /usr/local may not be readable in restricted environments */ }
3379
+ const searchDirs = [...dirs];
3380
+ const hasDriver = hasLibraryInDirs("libcuda.so", searchDirs) || hasLibraryInDirs("libnvidia-ml.so", searchDirs);
3381
+ if (!hasDriver)
3382
+ return null;
3383
+ const cudaLibraries = [
3384
+ ["libcudart.so", "CUDA runtime"],
3385
+ ["libcublas.so", "cuBLAS"],
3386
+ ["libcublasLt.so", "cuBLASLt"],
3387
+ ];
3388
+ const missing = cudaLibraries
3389
+ .filter(([library]) => !hasLibraryInDirs(library, searchDirs))
3390
+ .map(([, label]) => label);
3391
+ if (missing.length === 0)
3392
+ return null;
3393
+ return `NVIDIA driver libraries are visible, but CUDA user-space libraries are missing from loader paths (${missing.join(", ")})`;
3394
+ }
3395
+ async function runDoctorDeviceChecks(nextSteps) {
3396
+ const mode = configuredGpuModeLabel();
3397
+ doctorCheck("device mode", true, mode);
3398
+ const skipProbe = ["0", "false", "off", "no", "skip"].includes((process.env.QMD_DOCTOR_DEVICE_PROBE ?? "").trim().toLowerCase());
3399
+ if (skipProbe) {
3400
+ doctorCheck("device probe", false, "skipped by QMD_DOCTOR_DEVICE_PROBE=0. Next: unset it and rerun `qmd doctor` to verify GPU/CPU acceleration");
3401
+ nextSteps.push("Unset `QMD_DOCTOR_DEVICE_PROBE` and rerun `qmd doctor` when you want to verify llama.cpp device acceleration.");
3402
+ return;
3403
+ }
3404
+ const crashHint = "Probing native llama backend now. If qmd crashes here, rerun with `QMD_FORCE_CPU=1 qmd doctor` (or `QMD_DOCTOR_DEVICE_PROBE=0 qmd doctor` to skip this probe).";
3405
+ if (process.stdout.isTTY) {
3406
+ process.stdout.write(`${c.dim}${crashHint}${c.reset}`);
3407
+ }
3408
+ try {
3409
+ const device = await getDefaultLlamaCpp().getDeviceInfo({ allowBuild: false });
3410
+ if (process.stdout.isTTY) {
3411
+ process.stdout.write(`\r${" ".repeat(crashHint.length)}\r`);
3412
+ }
3413
+ if (device.gpu) {
3414
+ const gpuLabel = device.gpu === "metal" && process.platform === "darwin"
3415
+ ? "metal (macOS Metal backend)"
3416
+ : String(device.gpu);
3417
+ const parts = [`GPU ${gpuLabel}`, `offloading ${device.gpuOffloading ? "enabled" : "disabled"}`];
3418
+ if (device.gpuDevices.length > 0)
3419
+ parts.push(`devices: ${summarizeDeviceNames(device.gpuDevices)}`);
3420
+ if (device.vram)
3421
+ parts.push(`VRAM ${formatBytes(device.vram.free)} free / ${formatBytes(device.vram.total)} total`);
3422
+ parts.push(`${device.cpuCores} CPU math cores`);
3423
+ doctorCheck("device probe", device.gpuOffloading, device.gpuOffloading
3424
+ ? parts.join("; ")
3425
+ : `${parts.join("; ")}. Next: check QMD_LLAMA_GPU and llama.cpp backend support`);
3426
+ if (!device.gpuOffloading) {
3427
+ nextSteps.push("GPU was detected but offloading is disabled; check `QMD_LLAMA_GPU=metal|cuda|vulkan` and rerun `qmd doctor`.");
3428
+ }
3429
+ // Surface the darwin residency-set mitigation. libggml-metal's
3430
+ // process-static device dtor asserts on un-expired residency sets
3431
+ // during libc exit() (ggml-org/llama.cpp#22593), producing a giant
3432
+ // stderr backtrace after correct output. The bin/qmd launcher exports
3433
+ // GGML_METAL_NO_RESIDENCY=1 on darwin to skip the assertion entirely.
3434
+ // No measurable perf cost on short-lived CLI calls.
3435
+ if (device.gpu === "metal" && process.platform === "darwin") {
3436
+ if (isDarwinMetalMitigationActive()) {
3437
+ doctorCheck("darwin metal residency", true, "GGML_METAL_NO_RESIDENCY=1 set by launcher; clean process exit (avoids ggml-org/llama.cpp#22593). Opt back in with QMD_METAL_KEEP_RESIDENCY=1 if you run long-lived qmd processes.");
3438
+ }
3439
+ else {
3440
+ doctorCheck("darwin metal residency", false, "residency sets active (QMD_METAL_KEEP_RESIDENCY=1 or launcher bypassed); llama-using commands may dump a libggml-metal backtrace at exit (ggml-org/llama.cpp#22593) even when output succeeded.");
3441
+ nextSteps.push("Unset `QMD_METAL_KEEP_RESIDENCY` so the launcher can disable Metal residency sets; without this, query/vsearch/embed dump a stack trace at exit even on success.");
3442
+ }
3443
+ }
3444
+ }
3445
+ else {
3446
+ const cudaDiagnostic = linuxCudaRuntimeDiagnostic();
3447
+ const diagnosticSuffix = cudaDiagnostic ? ` ${cudaDiagnostic}.` : "";
3448
+ doctorCheck("device probe", false, `running on CPU (${device.cpuCores} math cores).${diagnosticSuffix} Next: install/configure Metal, CUDA, or Vulkan for faster embeddings, or set QMD_FORCE_CPU=1 to make CPU mode explicit`);
3449
+ if (cudaDiagnostic) {
3450
+ nextSteps.push(`${cudaDiagnostic}; install CUDA runtime/cuBLAS libraries or add their directory to LD_LIBRARY_PATH, then rerun \`qmd doctor\`.`);
3451
+ }
3452
+ else {
3453
+ nextSteps.push("Vector operations are running on CPU; install/configure Metal, CUDA, or Vulkan if embedding/query performance is too slow.");
3454
+ }
3455
+ }
3456
+ }
3457
+ catch (error) {
3458
+ if (process.stdout.isTTY) {
3459
+ process.stdout.write(`\r${" ".repeat(crashHint.length)}\r`);
3460
+ }
3461
+ const message = error instanceof Error ? sanitizeDiagnosticMessage(error.message) : sanitizeDiagnosticMessage(String(error));
3462
+ doctorCheck("device probe", false, `probe failed: ${message}. Next: run with QMD_FORCE_CPU=1 to bypass GPU probing, or set QMD_LLAMA_GPU=metal|cuda|vulkan and retry`);
3463
+ nextSteps.push("GPU probe failed; try `QMD_FORCE_CPU=1 qmd doctor` to confirm CPU fallback, then fix GPU drivers/backend if acceleration is expected.");
3464
+ }
3465
+ }
3466
+ async function showDoctor() {
3467
+ const storeInstance = getStore();
3468
+ const db = storeInstance.db;
3469
+ const pkg = readPackageJson();
3470
+ const activeModels = resolveModelsForCli();
3471
+ const embedModel = activeModels.embed;
3472
+ const fingerprint = getEmbeddingFingerprint(embedModel);
3473
+ const nextSteps = [];
3474
+ console.log(`${c.bold}QMD Doctor${c.reset}\n`);
3475
+ console.log(`Index: ${getDbPath()}`);
3476
+ console.log(`Runtime: ${isBun ? "bun:sqlite" : "better-sqlite3"}`);
3477
+ try {
3478
+ const row = db.prepare(`SELECT sqlite_version() AS version`).get();
3479
+ doctorCheck("SQLite runtime", true, row.version);
3480
+ }
3481
+ catch (error) {
3482
+ doctorCheck("SQLite runtime", false, error instanceof Error ? error.message : String(error));
3483
+ }
3484
+ const betterSqliteVersion = pkg.dependencies?.["better-sqlite3"] ?? pkg.devDependencies?.["better-sqlite3"] ?? "not declared";
3485
+ doctorCheck("better-sqlite3 package", true, String(betterSqliteVersion));
3486
+ try {
3487
+ const row = db.prepare(`SELECT vec_version() AS version`).get();
3488
+ doctorCheck("sqlite-vec", true, row.version);
3489
+ }
3490
+ catch (error) {
3491
+ doctorCheck("sqlite-vec", false, error instanceof Error ? error.message : String(error));
3492
+ }
3493
+ const configCheck = checkDoctorIndexConfig(nextSteps);
3494
+ const configModels = configCheck.config?.models ?? {};
3495
+ checkEnvironmentOverrides(activeModels, configModels);
3496
+ checkModelDefaults(activeModels, configModels);
3497
+ checkModelCache(activeModels, nextSteps);
3498
+ await runDoctorDeviceChecks(nextSteps);
3499
+ try {
3500
+ const adoption = await maybeAdoptLegacyEmbeddingFingerprint(storeInstance, embedModel);
3501
+ if (adoption.checked || adoption.adopted > 0) {
3502
+ doctorCheck("legacy fingerprint adoption", adoption.adopted > 0, adoption.adopted > 0 ? `adopted ${adoption.adopted} legacy chunks; ${adoption.reason}` : adoption.reason);
3503
+ }
3504
+ }
3505
+ catch (error) {
3506
+ doctorCheck("legacy fingerprint adoption", false, error instanceof Error ? error.message : String(error));
3507
+ }
3508
+ try {
3509
+ const pending = getHashesNeedingEmbedding(db, undefined, embedModel);
3510
+ doctorCheck("embedding freshness", pending === 0, pending === 0 ? "all active documents match current fingerprint" : `${formatCount(pending)} active documents need embeddings. Next: \`qmd embed\``);
3511
+ if (pending > 0) {
3512
+ nextSteps.push(`Run \`qmd embed\` to generate ${formatCount(pending)} missing/stale document embeddings.`);
3513
+ }
3514
+ }
3515
+ catch (error) {
3516
+ doctorCheck("embedding freshness", false, error instanceof Error ? error.message : String(error));
3517
+ }
3518
+ try {
3519
+ const rows = db.prepare(`
3520
+ SELECT model, embed_fingerprint AS fingerprint, COUNT(DISTINCT hash) AS docs, COUNT(*) AS chunks
3521
+ FROM content_vectors
3522
+ GROUP BY model, embed_fingerprint
3523
+ ORDER BY chunks DESC, model, embed_fingerprint
3524
+ `).all();
3525
+ const uniqueFingerprints = new Set(rows.map(row => row.fingerprint));
3526
+ const offCurrent = rows.filter(row => row.model === embedModel && row.fingerprint !== fingerprint);
3527
+ const ok = rows.length === 0 || (uniqueFingerprints.size === 1 && rows[0]?.fingerprint === fingerprint && offCurrent.length === 0);
3528
+ const currentDocs = rows
3529
+ .filter(row => row.model === embedModel && row.fingerprint === fingerprint)
3530
+ .reduce((sum, row) => sum + row.docs, 0);
3531
+ const otherDocs = rows.reduce((sum, row) => sum + row.docs, 0) - currentDocs;
3532
+ const groups = rows.map(row => {
3533
+ const label = row.fingerprint === fingerprint ? "current" : (row.fingerprint || "legacy");
3534
+ return `${shortModelName(row.model)}:${label} ${formatCount(row.docs)} docs/${formatCount(row.chunks)} chunks`;
3535
+ }).join("; ");
3536
+ const namedFingerprintRows = rows.filter(row => row.fingerprint);
3537
+ const namedFingerprints = [...new Set(namedFingerprintRows.map(row => row.fingerprint))];
3538
+ if (namedFingerprints.length > 1) {
3539
+ const namedGroups = namedFingerprintRows
3540
+ .map(row => `${row.fingerprint}${row.fingerprint === fingerprint ? " (current)" : ""}: ${shortModelName(row.model)} ${formatCount(row.docs)} docs/${formatCount(row.chunks)} chunks`)
3541
+ .join("; ");
3542
+ doctorCheck("mixed named embedding fingerprints", false, `content_vectors contains ${namedFingerprints.length} named fingerprints: ${namedGroups}. Next: \`qmd embed\` or \`qmd embed --force\``);
3543
+ nextSteps.push("Run `qmd embed` to converge mixed named embedding fingerprints; use `qmd embed --force` if old named fingerprints or vector sample mismatches remain.");
3544
+ }
3545
+ const details = rows.length === 0
3546
+ ? `no vectors yet; current fingerprint ${fingerprint}`
3547
+ : ok
3548
+ ? `${formatCount(currentDocs)} docs on current fingerprint (${fingerprint})`
3549
+ : `${formatCount(currentDocs)} docs current, ${formatCount(otherDocs)} docs legacy/stale. ${groups}. Next: \`qmd embed\``;
3550
+ doctorCheck("embedding fingerprints", ok, details);
3551
+ if (!ok) {
3552
+ nextSteps.push("Run `qmd embed` to migrate active documents to the current embedding fingerprint; use `qmd embed --force` if vector samples still fail afterward.");
3553
+ }
3554
+ }
3555
+ catch (error) {
3556
+ doctorCheck("embedding fingerprints", false, error instanceof Error ? error.message : String(error));
3557
+ }
3558
+ try {
3559
+ const vectorSample = await checkEmbeddingVectorSamples(db, embedModel, fingerprint);
3560
+ doctorCheck("embedding vector sample", vectorSample.ok, vectorSample.details);
3561
+ if (!vectorSample.ok) {
3562
+ nextSteps.push("Run `qmd embed --force` to rebuild existing vectors that no longer reproduce under the current embedding pipeline.");
3563
+ }
3564
+ }
3565
+ catch (error) {
3566
+ const message = error instanceof Error ? sanitizeDiagnosticMessage(error.message) : sanitizeDiagnosticMessage(String(error));
3567
+ doctorCheck("embedding vector sample", false, `${message}; rebuild with \`qmd embed --force\``);
3568
+ nextSteps.push("Run `qmd embed --force` to rebuild existing vectors, then rerun `qmd doctor`.");
3569
+ }
3570
+ const steps = normalizedDoctorNextSteps(nextSteps);
3571
+ if (steps.length > 0) {
3572
+ console.log(`\n${c.bold}Recommended next step${steps.length === 1 ? "" : "s"}${c.reset}`);
3573
+ for (const step of steps) {
3574
+ console.log(` - ${step}`);
3575
+ }
3576
+ }
3577
+ closeDb();
3578
+ }
3579
+ function printDoctorHint() {
3580
+ console.error("If qmd still behaves unexpectedly, run 'qmd doctor' for diagnostics.");
3581
+ }
3582
+ function exitWithError(error, code = 1) {
3583
+ console.error(error instanceof Error ? error.message : String(error));
3584
+ printDoctorHint();
3585
+ process.exit(code);
3586
+ }
3587
+ function readPackageJson() {
3588
+ const scriptDir = dirname(fileURLToPath(import.meta.url));
3589
+ const pkgPath = resolve(scriptDir, "..", "..", "package.json");
3590
+ return JSON.parse(readFileSync(pkgPath, "utf-8"));
3591
+ }
3592
+ async function showVersion() {
3593
+ const scriptDir = dirname(fileURLToPath(import.meta.url));
3594
+ const pkg = readPackageJson();
3595
+ let commit = "";
3596
+ try {
3597
+ commit = execSync(`git -C ${scriptDir} rev-parse --short HEAD`, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim();
3598
+ }
3599
+ catch {
3600
+ // Not a git repo or git not available
3601
+ }
3602
+ const versionStr = commit ? `${pkg.version} (${commit})` : pkg.version;
3603
+ console.log(`qmd ${versionStr}`);
3604
+ }
3605
+ // Main CLI - only run if this is the main module
3606
+ const __filename = fileURLToPath(import.meta.url);
3607
+ const argv1 = process.argv[1];
3608
+ const isMain = argv1 === __filename
3609
+ || argv1?.endsWith("/qmd.ts")
3610
+ || argv1?.endsWith("/qmd.js")
3611
+ || (argv1 != null && realpathSync(argv1) === __filename);
3612
+ if (isMain) {
3613
+ // Flip to production mode only when this module is executed as the CLI
3614
+ // entrypoint, not when imported for its exports. Tests must set INDEX_PATH
3615
+ // or use createStore() with an explicit path.
3616
+ enableProductionMode();
3617
+ const cli = parseCLI();
3618
+ if (cli.values.version) {
3619
+ await showVersion();
3620
+ process.exit(0);
3621
+ }
3622
+ if (cli.values.skill) {
3623
+ showSkill();
3624
+ process.exit(0);
3625
+ }
3626
+ if (cli.values.help && cli.command === "skill") {
3627
+ console.log("Usage: qmd skill <show|install> [options]");
3628
+ console.log("");
3629
+ console.log("Commands:");
3630
+ console.log(" show Print the QMD skill");
3631
+ console.log(" install Install QMD skill into ./.agents/skills/qmd");
3632
+ console.log("");
3633
+ console.log("Options:");
3634
+ console.log(" --global Install into ~/.agents/skills/qmd");
3635
+ console.log(" --yes Also create the .claude/skills/qmd symlink");
3636
+ console.log(" -f, --force Replace existing install or symlink");
3637
+ process.exit(0);
3638
+ }
3639
+ if (!cli.command || cli.values.help) {
3640
+ showHelp();
3641
+ process.exit(cli.values.help ? 0 : 1);
3642
+ }
3643
+ switch (cli.command) {
3644
+ case "context": {
3645
+ const subcommand = cli.args[0];
3646
+ if (!subcommand) {
3647
+ console.error("Usage: qmd context <add|list|rm>");
3648
+ console.error("");
3649
+ console.error("Commands:");
3650
+ console.error(" qmd context add [path] \"text\" - Add context (defaults to current dir)");
3651
+ console.error(" qmd context add / \"text\" - Add global context to all collections");
3652
+ console.error(" qmd context list - List all contexts");
3653
+ console.error(" qmd context rm <path> - Remove context");
3654
+ process.exit(1);
3655
+ }
3656
+ switch (subcommand) {
3657
+ case "add": {
3658
+ if (cli.args.length < 2) {
3659
+ console.error("Usage: qmd context add [path] \"text\"");
3660
+ console.error("");
3661
+ console.error("Examples:");
3662
+ console.error(" qmd context add \"Context for current directory\"");
3663
+ console.error(" qmd context add . \"Context for current directory\"");
3664
+ console.error(" qmd context add /subfolder \"Context for subfolder\"");
3665
+ console.error(" qmd context add / \"Global context for all collections\"");
3666
+ console.error("");
3667
+ console.error(" Using virtual paths:");
3668
+ console.error(" qmd context add qmd://journals/ \"Context for entire journals collection\"");
3669
+ console.error(" qmd context add qmd://journals/2024 \"Context for 2024 journals\"");
3670
+ process.exit(1);
3671
+ }
3672
+ let pathArg;
3673
+ let contextText;
3674
+ // Check if first arg looks like a path or if it's the context text
3675
+ const firstArg = cli.args[1] || '';
3676
+ const secondArg = cli.args[2];
3677
+ if (secondArg) {
3678
+ // Two args: path + context
3679
+ pathArg = firstArg;
3680
+ contextText = cli.args.slice(2).join(" ");
3681
+ }
3682
+ else {
3683
+ // One arg: context only (use current directory)
3684
+ pathArg = undefined;
3685
+ contextText = firstArg;
3686
+ }
3687
+ await contextAdd(pathArg, contextText);
3688
+ break;
3689
+ }
3690
+ case "list": {
3691
+ contextList();
3692
+ break;
3693
+ }
3694
+ case "rm":
3695
+ case "remove": {
3696
+ if (cli.args.length < 2 || !cli.args[1]) {
3697
+ console.error("Usage: qmd context rm <path>");
3698
+ console.error("Examples:");
3699
+ console.error(" qmd context rm /");
3700
+ console.error(" qmd context rm qmd://journals/2024");
3701
+ process.exit(1);
3702
+ }
3703
+ contextRemove(cli.args[1]);
3704
+ break;
3705
+ }
3706
+ default:
3707
+ console.error(`Unknown subcommand: ${subcommand}`);
3708
+ console.error("Available: add, list, rm");
3709
+ process.exit(1);
3710
+ }
3711
+ break;
3712
+ }
3713
+ case "get": {
3714
+ if (!cli.args[0]) {
3715
+ console.error("Usage: qmd get <filepath>[:from[:count]] [--from <line>] [-l <lines>] [--no-line-numbers] [--full-path]");
3716
+ process.exit(1);
3717
+ }
3718
+ const fromLine = cli.values.from ? parseInt(cli.values.from, 10) : undefined;
3719
+ const maxLines = cli.values.l ? parseInt(cli.values.l, 10) : undefined;
3720
+ // Line numbers default ON for get; opt out with --no-line-numbers.
3721
+ const getLineNumbers = !cli.values["no-line-numbers"];
3722
+ getDocument(cli.args[0], fromLine, maxLines, getLineNumbers, !!cli.values["full-path"]);
3723
+ break;
3724
+ }
3725
+ case "multi-get": {
3726
+ if (!cli.args[0]) {
3727
+ console.error("Usage: qmd multi-get <pattern> [-l <lines>] [--max-bytes <bytes>] [--no-line-numbers] [--full-path] [--format json|csv|md|xml|files]");
3728
+ console.error(" pattern: glob (e.g., 'journals/2025-05*.md') or comma-separated list");
3729
+ process.exit(1);
3730
+ }
3731
+ const maxLinesMulti = cli.values.l ? parseInt(cli.values.l, 10) : undefined;
3732
+ const maxBytes = cli.values["max-bytes"] ? parseInt(cli.values["max-bytes"], 10) : DEFAULT_MULTI_GET_MAX_BYTES;
3733
+ // Line numbers default ON for multi-get; opt out with --no-line-numbers.
3734
+ const mgLineNumbers = !cli.values["no-line-numbers"];
3735
+ multiGet(cli.args[0], maxLinesMulti, maxBytes, cli.opts.format, mgLineNumbers, !!cli.values["full-path"]);
3736
+ break;
3737
+ }
3738
+ case "ls": {
3739
+ listFiles(cli.args[0]);
3740
+ break;
3741
+ }
3742
+ case "collection": {
3743
+ const subcommand = cli.args[0];
3744
+ switch (subcommand) {
3745
+ case "list": {
3746
+ collectionList();
3747
+ break;
3748
+ }
3749
+ case "add": {
3750
+ const pwd = cli.args[1] || getPwd();
3751
+ const resolvedPwd = pwd === '.' ? getPwd() : getRealPath(resolve(pwd));
3752
+ const globPattern = cli.values.mask || DEFAULT_GLOB;
3753
+ const name = cli.values.name;
3754
+ await collectionAdd(resolvedPwd, globPattern, name);
3755
+ break;
3756
+ }
3757
+ case "remove":
3758
+ case "rm": {
3759
+ if (!cli.args[1]) {
3760
+ console.error("Usage: qmd collection remove <name>");
3761
+ console.error(" Use 'qmd collection list' to see available collections");
3762
+ process.exit(1);
3763
+ }
3764
+ collectionRemove(cli.args[1]);
3765
+ break;
3766
+ }
3767
+ case "rename":
3768
+ case "mv": {
3769
+ if (!cli.args[1] || !cli.args[2]) {
3770
+ console.error("Usage: qmd collection rename <old-name> <new-name>");
3771
+ console.error(" Use 'qmd collection list' to see available collections");
3772
+ process.exit(1);
3773
+ }
3774
+ collectionRename(cli.args[1], cli.args[2]);
3775
+ break;
3776
+ }
3777
+ case "set-update":
3778
+ case "update-cmd": {
3779
+ const name = cli.args[1];
3780
+ const cmd = cli.args.slice(2).join(' ') || null;
3781
+ if (!name) {
3782
+ console.error("Usage: qmd collection update-cmd <name> [command]");
3783
+ console.error(" Set the command to run before indexing (e.g., 'git pull')");
3784
+ console.error(" Omit command to clear it");
3785
+ process.exit(1);
3786
+ }
3787
+ const { updateCollectionSettings, getCollection } = await import("../collections.js");
3788
+ const col = getCollection(name);
3789
+ if (!col) {
3790
+ console.error(`Collection not found: ${name}`);
3791
+ process.exit(1);
3792
+ }
3793
+ updateCollectionSettings(name, { update: cmd });
3794
+ if (cmd) {
3795
+ console.log(`✓ Set update command for '${name}': ${cmd}`);
3796
+ }
3797
+ else {
3798
+ console.log(`✓ Cleared update command for '${name}'`);
3799
+ }
3800
+ break;
3801
+ }
3802
+ case "include":
3803
+ case "exclude": {
3804
+ const name = cli.args[1];
3805
+ if (!name) {
3806
+ console.error(`Usage: qmd collection ${subcommand} <name>`);
3807
+ console.error(` ${subcommand === 'include' ? 'Include' : 'Exclude'} collection in default queries`);
3808
+ process.exit(1);
3809
+ }
3810
+ const { updateCollectionSettings, getCollection } = await import("../collections.js");
3811
+ const col = getCollection(name);
3812
+ if (!col) {
3813
+ console.error(`Collection not found: ${name}`);
3814
+ process.exit(1);
3815
+ }
3816
+ const include = subcommand === 'include';
3817
+ updateCollectionSettings(name, { includeByDefault: include });
3818
+ console.log(`✓ Collection '${name}' ${include ? 'included in' : 'excluded from'} default queries`);
3819
+ break;
3820
+ }
3821
+ case "show":
3822
+ case "info": {
3823
+ const name = cli.args[1];
3824
+ if (!name) {
3825
+ console.error("Usage: qmd collection show <name>");
3826
+ process.exit(1);
3827
+ }
3828
+ const { getCollection } = await import("../collections.js");
3829
+ const col = getCollection(name);
3830
+ if (!col) {
3831
+ console.error(`Collection not found: ${name}`);
3832
+ process.exit(1);
3833
+ }
3834
+ console.log(`Collection: ${name}`);
3835
+ console.log(` Path: ${col.path}`);
3836
+ console.log(` Pattern: ${col.pattern}`);
3837
+ console.log(` Include: ${col.includeByDefault !== false ? 'yes (default)' : 'no'}`);
3838
+ if (col.update) {
3839
+ console.log(` Update: ${col.update}`);
3840
+ }
3841
+ if (col.context) {
3842
+ const ctxCount = Object.keys(col.context).length;
3843
+ console.log(` Contexts: ${ctxCount}`);
3844
+ }
3845
+ break;
3846
+ }
3847
+ case "help":
3848
+ case undefined: {
3849
+ console.log("Usage: qmd collection <command> [options]");
3850
+ console.log("");
3851
+ console.log("Commands:");
3852
+ console.log(" list List all collections");
3853
+ console.log(" add <path> [--name NAME] Add a collection");
3854
+ console.log(" remove <name> Remove a collection");
3855
+ console.log(" rename <old> <new> Rename a collection");
3856
+ console.log(" show <name> Show collection details");
3857
+ console.log(" update-cmd <name> [cmd] Set pre-update command (e.g., 'git pull')");
3858
+ console.log(" include <name> Include in default queries");
3859
+ console.log(" exclude <name> Exclude from default queries");
3860
+ console.log("");
3861
+ console.log("Examples:");
3862
+ console.log(" qmd collection add ~/notes --name notes");
3863
+ console.log(" qmd collection update-cmd brain 'git pull'");
3864
+ console.log(" qmd collection exclude archive");
3865
+ process.exit(0);
3866
+ }
3867
+ default:
3868
+ console.error(`Unknown subcommand: ${subcommand}`);
3869
+ console.error("Run 'qmd collection help' for usage");
3870
+ printDoctorHint();
3871
+ process.exit(1);
3872
+ }
3873
+ break;
3874
+ }
3875
+ case "init":
3876
+ try {
3877
+ initLocalIndex();
3878
+ }
3879
+ catch (error) {
3880
+ exitWithError(error);
3881
+ }
3882
+ break;
3883
+ case "status":
3884
+ await showStatus();
3885
+ break;
3886
+ case "doctor":
3887
+ await showDoctor();
3888
+ break;
3889
+ case "update":
3890
+ await updateCollections();
3891
+ break;
3892
+ case "embed":
3893
+ try {
3894
+ const maxDocsPerBatch = parseEmbedBatchOption("maxDocsPerBatch", cli.values["max-docs-per-batch"]);
3895
+ const maxBatchMb = parseEmbedBatchOption("maxBatchBytes", cli.values["max-batch-mb"]);
3896
+ const embedChunkStrategy = parseChunkStrategy(cli.values["chunk-strategy"]);
3897
+ // Validate -c against configured collections before dispatching, so a
3898
+ // typo errors with "Collection not found: X" instead of silently
3899
+ // reporting success because no pending docs match a nonexistent name.
3900
+ // embed operates on a single collection; only the first value is used.
3901
+ const embedValidatedCollections = resolveCollectionFilter(cli.opts.collection, false);
3902
+ const embedCollection = embedValidatedCollections[0];
3903
+ await vectorIndex(resolveEmbedModelForCli(), !!cli.values.force, {
3904
+ maxDocsPerBatch,
3905
+ maxBatchBytes: maxBatchMb === undefined ? undefined : maxBatchMb * 1024 * 1024,
3906
+ chunkStrategy: embedChunkStrategy,
3907
+ collection: embedCollection,
3908
+ });
3909
+ }
3910
+ catch (error) {
3911
+ exitWithError(error);
3912
+ }
3913
+ break;
3914
+ case "pull": {
3915
+ const refresh = cli.values.refresh === undefined ? false : Boolean(cli.values.refresh);
3916
+ const activeModels = resolveModelsForCli();
3917
+ const models = [
3918
+ activeModels.embed,
3919
+ activeModels.generate,
3920
+ activeModels.rerank,
3921
+ ];
3922
+ console.log(`${c.bold}Pulling models${c.reset}`);
3923
+ const results = await pullModels(models, {
3924
+ refresh,
3925
+ cacheDir: DEFAULT_MODEL_CACHE_DIR,
3926
+ });
3927
+ for (const result of results) {
3928
+ const size = formatBytes(result.sizeBytes);
3929
+ const note = result.refreshed ? "refreshed" : "cached/checked";
3930
+ console.log(`- ${result.model} -> ${result.path} (${size}, ${note})`);
3931
+ }
3932
+ break;
3933
+ }
3934
+ case "search":
3935
+ if (!cli.query) {
3936
+ console.error("Usage: qmd search [options] <query>");
3937
+ process.exit(1);
3938
+ }
3939
+ await initializeKuromojiTokenizer(); // kuromoji: normalize CJK query
3940
+ search(cli.query, cli.opts);
3941
+ break;
3942
+ case "vsearch":
3943
+ case "vector-search": // undocumented alias
3944
+ if (!cli.query) {
3945
+ console.error("Usage: qmd vsearch [options] <query>");
3946
+ process.exit(1);
3947
+ }
3948
+ // Default min-score for vector search is 0.3
3949
+ if (!cli.values["min-score"]) {
3950
+ cli.opts.minScore = 0.3;
3951
+ }
3952
+ await vectorSearch(cli.query, cli.opts);
3953
+ break;
3954
+ case "query":
3955
+ case "deep-search": // undocumented alias
3956
+ if (!cli.query) {
3957
+ console.error("Usage: qmd query [options] <query>");
3958
+ process.exit(1);
3959
+ }
3960
+ await initializeKuromojiTokenizer(); // kuromoji: normalize CJK query
3961
+ await querySearch(cli.query, cli.opts);
3962
+ break;
3963
+ case "bench": {
3964
+ const fixturePath = cli.args[0];
3965
+ if (!fixturePath) {
3966
+ console.error("Usage: qmd bench <fixture.json> [--json] [-c collection]");
3967
+ console.error("");
3968
+ console.error("Run search quality benchmarks against a fixture file.");
3969
+ console.error("See src/bench/fixtures/example.json for the fixture format.");
3970
+ process.exit(1);
3971
+ }
3972
+ const { runBenchmark } = await import("../bench/bench.js");
3973
+ const benchCollection = cli.opts.collection;
3974
+ await runBenchmark(fixturePath, {
3975
+ json: !!cli.values.json,
3976
+ collection: Array.isArray(benchCollection) ? benchCollection[0] : benchCollection,
3977
+ dbPath: getDbPath(),
3978
+ configPath: configExists() ? getConfigPath() : undefined,
3979
+ });
3980
+ break;
3981
+ }
3982
+ case "mcp": {
3983
+ const sub = cli.args[0]; // stop | status | undefined
3984
+ // Cache dir for PID/log files — same dir as the index
3985
+ const cacheDir = process.env.XDG_CACHE_HOME
3986
+ ? resolve(process.env.XDG_CACHE_HOME, "qmd")
3987
+ : resolve(homedir(), ".cache", "qmd");
3988
+ const pidPath = resolve(cacheDir, "mcp.pid");
3989
+ // Subcommands take priority over flags
3990
+ if (sub === "stop") {
3991
+ if (!existsSync(pidPath)) {
3992
+ console.log("Not running (no PID file).");
3993
+ process.exit(0);
3994
+ }
3995
+ const pid = parseInt(readFileSync(pidPath, "utf-8").trim());
3996
+ try {
3997
+ process.kill(pid, 0); // alive?
3998
+ process.kill(pid, "SIGTERM");
3999
+ unlinkSync(pidPath);
4000
+ console.log(`Stopped QMD MCP server (PID ${pid}).`);
4001
+ }
4002
+ catch {
4003
+ unlinkSync(pidPath);
4004
+ console.log("Cleaned up stale PID file (server was not running).");
4005
+ }
4006
+ process.exit(0);
4007
+ }
4008
+ if (cli.values.http) {
4009
+ const port = Number(cli.values.port) || 8181;
4010
+ if (cli.values.daemon) {
4011
+ // Guard: check if already running
4012
+ if (existsSync(pidPath)) {
4013
+ const existingPid = parseInt(readFileSync(pidPath, "utf-8").trim());
4014
+ try {
4015
+ process.kill(existingPid, 0); // alive?
4016
+ console.error(`Already running (PID ${existingPid}). Run 'qmd mcp stop' first.`);
4017
+ process.exit(1);
4018
+ }
4019
+ catch {
4020
+ // Stale PID file — continue
4021
+ }
4022
+ }
4023
+ mkdirSync(cacheDir, { recursive: true });
4024
+ const logPath = resolve(cacheDir, "mcp.log");
4025
+ const logFd = openSync(logPath, "w"); // truncate — fresh log per daemon run
4026
+ const selfPath = fileURLToPath(import.meta.url);
4027
+ const indexArgs = cli.values.index ? ["--index", String(cli.values.index)] : [];
4028
+ const spawnArgs = selfPath.endsWith(".ts")
4029
+ ? ["--import", pathJoin(dirname(selfPath), "..", "..", "node_modules", "tsx", "dist", "esm", "index.mjs"), selfPath, ...indexArgs, "mcp", "--http", "--port", String(port)]
4030
+ : [selfPath, ...indexArgs, "mcp", "--http", "--port", String(port)];
4031
+ const child = nodeSpawn(process.execPath, spawnArgs, {
4032
+ stdio: ["ignore", logFd, logFd],
4033
+ detached: true,
4034
+ });
4035
+ child.unref();
4036
+ closeSync(logFd); // parent's copy; child inherited the fd
4037
+ writeFileSync(pidPath, String(child.pid));
4038
+ console.log(`Started on http://localhost:${port}/mcp (PID ${child.pid})`);
4039
+ console.log(`Logs: ${logPath}`);
4040
+ process.exit(0);
4041
+ }
4042
+ // Foreground HTTP mode — remove top-level cursor handlers so the
4043
+ // async cleanup handlers in startMcpHttpServer actually run.
4044
+ process.removeAllListeners("SIGTERM");
4045
+ process.removeAllListeners("SIGINT");
4046
+ const { startMcpHttpServer } = await import("../mcp/server.js");
4047
+ try {
4048
+ await startMcpHttpServer(port, { dbPath: getDbPath() });
4049
+ }
4050
+ catch (e) {
4051
+ if (typeof e === "object" && e !== null && "code" in e && e.code === "EADDRINUSE") {
4052
+ console.error(`Port ${port} already in use. Try a different port with --port.`);
4053
+ process.exit(1);
4054
+ }
4055
+ throw e;
4056
+ }
4057
+ }
4058
+ else {
4059
+ // Default: stdio transport
4060
+ const { startMcpServer } = await import("../mcp/server.js");
4061
+ await startMcpServer({ dbPath: getDbPath() });
4062
+ }
4063
+ break;
4064
+ }
4065
+ case "skills": {
4066
+ try {
4067
+ if (cli.values.help || cli.args[0] === "help") {
4068
+ showSkillsHelp();
4069
+ }
4070
+ else {
4071
+ runSkillsCommand(cli.args, Boolean(cli.values.json), Boolean(cli.values.full), Boolean(cli.values.all));
4072
+ }
4073
+ }
4074
+ catch (error) {
4075
+ if (cli.values.json) {
4076
+ outputSkillsJson({ success: false, error: error instanceof Error ? error.message : String(error) });
4077
+ }
4078
+ else {
4079
+ console.error(error instanceof Error ? error.message : String(error));
4080
+ }
4081
+ process.exit(1);
4082
+ }
4083
+ break;
4084
+ }
4085
+ case "skill": {
4086
+ const subcommand = cli.args[0];
4087
+ switch (subcommand) {
4088
+ case "show": {
4089
+ showSkill();
4090
+ break;
4091
+ }
4092
+ case "install": {
4093
+ try {
4094
+ await installSkill(Boolean(cli.values.global), Boolean(cli.values.force), Boolean(cli.values.yes));
4095
+ }
4096
+ catch (error) {
4097
+ exitWithError(error);
4098
+ }
4099
+ break;
4100
+ }
4101
+ case "help":
4102
+ case undefined: {
4103
+ console.log("Usage: qmd skill <show|install> [options]");
4104
+ console.log("");
4105
+ console.log("Commands:");
4106
+ console.log(" show Print the QMD skill");
4107
+ console.log(" install Install QMD skill into ./.agents/skills/qmd");
4108
+ console.log("");
4109
+ console.log("Options:");
4110
+ console.log(" --global Install into ~/.agents/skills/qmd");
4111
+ console.log(" --yes Also create the .claude/skills/qmd symlink");
4112
+ console.log(" -f, --force Replace existing install or symlink");
4113
+ process.exit(0);
4114
+ }
4115
+ default:
4116
+ console.error(`Unknown subcommand: ${subcommand}`);
4117
+ console.error("Run 'qmd skill help' for usage");
4118
+ printDoctorHint();
4119
+ process.exit(1);
4120
+ }
4121
+ break;
4122
+ }
4123
+ case "cleanup": {
4124
+ const db = getDb();
4125
+ // 1. Clear llm_cache
4126
+ const cacheCount = deleteLLMCache(db);
4127
+ console.log(`${c.green}✓${c.reset} Cleared ${cacheCount} cached API responses`);
4128
+ // 2. Remove orphaned vectors
4129
+ const orphanedVecs = cleanupOrphanedVectors(db);
4130
+ if (orphanedVecs > 0) {
4131
+ console.log(`${c.green}✓${c.reset} Removed ${orphanedVecs} orphaned embedding chunks`);
4132
+ }
4133
+ else {
4134
+ console.log(`${c.dim}No orphaned embeddings to remove${c.reset}`);
4135
+ }
4136
+ // 3. Remove inactive documents
4137
+ const inactiveDocs = deleteInactiveDocuments(db);
4138
+ if (inactiveDocs > 0) {
4139
+ console.log(`${c.green}✓${c.reset} Removed ${inactiveDocs} inactive document records`);
4140
+ }
4141
+ // 4. Vacuum to reclaim space
4142
+ vacuumDatabase(db);
4143
+ console.log(`${c.green}✓${c.reset} Database vacuumed`);
4144
+ closeDb();
4145
+ break;
4146
+ }
4147
+ default:
4148
+ console.error(`Unknown command: ${cli.command}`);
4149
+ console.error("Run 'qmd --help' for usage.");
4150
+ printDoctorHint();
4151
+ process.exit(1);
4152
+ }
4153
+ if (cli.command !== "mcp") {
4154
+ await finishSuccessfulCliCommand({
4155
+ command: cli.command,
4156
+ format: cli.opts.format,
4157
+ });
4158
+ }
4159
+ } // end if (main module)