@tobilu/qmd 1.0.0 → 1.0.5

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