ko-qmd 2.8.3-ko.2

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