@tobilu/qmd 1.0.0 → 1.0.6

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