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