-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathqmd.ts
More file actions
executable file
·4059 lines (3615 loc) · 146 KB
/
Copy pathqmd.ts
File metadata and controls
executable file
·4059 lines (3615 loc) · 146 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Load .env before any other import so env-driven singletons (LlamaCpp,
// JinaEmbedder, etc.) see the values on their first read. Safe no-op when
// no .env file is present. Shell env vars still win over .env values.
import { loadDotenv } from "../dotenv.js";
loadDotenv();
import { openDatabase } from "../db.js";
import type { Database } from "../db.js";
import fastGlob from "fast-glob";
import { execSync, spawn as nodeSpawn } from "child_process";
import { fileURLToPath } from "url";
import { dirname, join as pathJoin, relative as relativePath } from "path";
import { parseArgs } from "util";
import { readFileSync, realpathSync, statSync, existsSync, unlinkSync, writeFileSync, openSync, closeSync, mkdirSync, lstatSync, rmSync, symlinkSync, readlinkSync } from "fs";
import { createInterface } from "readline/promises";
import {
getPwd,
getRealPath,
homedir,
resolve,
enableProductionMode,
searchFTS,
extractSnippet,
getContextForFile,
getContextForPath,
listCollections,
removeCollection,
renameCollection,
findSimilarFiles,
findDocumentByDocid,
isDocid,
matchFilesByGlob,
getHashesNeedingEmbedding,
clearAllEmbeddings,
insertEmbedding,
getStatus,
hashContent,
extractTitle,
formatDocForEmbedding,
chunkDocumentByTokens,
clearCache,
getCacheKey,
getCachedResult,
setCachedResult,
getIndexHealth,
parseVirtualPath,
buildVirtualPath,
isVirtualPath,
resolveVirtualPath,
toVirtualPath,
insertContent,
insertDocument,
findActiveDocument,
updateDocumentTitle,
updateDocument,
deactivateDocument,
getActiveDocumentPaths,
cleanupOrphanedContent,
deleteLLMCache,
deleteInactiveDocuments,
cleanupOrphanedVectors,
vacuumDatabase,
getCollectionsWithoutContext,
getTopLevelPathsWithoutContext,
handelize,
hybridQuery,
vectorSearchQuery,
structuredSearch,
addLineNumbers,
type ExpandedQuery,
type HybridQueryExplain,
DEFAULT_EMBED_MODEL,
DEFAULT_EMBED_MAX_BATCH_BYTES,
DEFAULT_EMBED_MAX_DOCS_PER_BATCH,
DEFAULT_RERANK_MODEL,
DEFAULT_GLOB,
DEFAULT_MULTI_GET_MAX_BYTES,
createStore,
getDefaultDbPath,
reindexCollection,
generateEmbeddings,
syncConfigToDb,
type ReindexResult,
type ChunkStrategy,
recordJinaUsage,
getJinaUsageSummary,
getJinaUsageTotal,
clearJinaUsage,
getUsageSnapshot,
getDailyUsage,
type JinaUsageSummary,
type UsageSnapshot,
type QuotaWindow,
type QuotaSeverity,
type DailyUsageBucket,
} from "../store.js";
import { disposeDefaultLlamaCpp, getDefaultLlamaCpp, setDefaultLlamaCpp, LlamaCpp, withLLMSession, pullModels, DEFAULT_EMBED_MODEL_URI, DEFAULT_GENERATE_MODEL_URI, DEFAULT_RERANK_MODEL_URI, DEFAULT_MODEL_CACHE_DIR } from "../llm.js";
import {
formatSearchResults,
formatDocuments,
escapeXml,
escapeCSV,
type OutputFormat,
} from "./formatter.js";
import {
getCollection as getCollectionFromYaml,
listCollections as yamlListCollections,
getDefaultCollectionNames,
addContext as yamlAddContext,
removeContext as yamlRemoveContext,
removeCollection as yamlRemoveCollectionFn,
renameCollection as yamlRenameCollectionFn,
setGlobalContext,
listAllContexts,
setConfigIndexName,
loadConfig,
} from "../collections.js";
import { getEmbeddedQmdSkillContent, getEmbeddedQmdSkillFiles } from "../embedded-skills.js";
// Enable production mode - allows using default database path
// Tests must set INDEX_PATH or use createStore() with explicit path
enableProductionMode();
// =============================================================================
// Store/DB lifecycle (no legacy singletons in store.ts)
// =============================================================================
let store: ReturnType<typeof createStore> | null = null;
let storeDbPathOverride: string | undefined;
function getStore(): ReturnType<typeof createStore> {
if (!store) {
store = createStore(storeDbPathOverride);
// Sync YAML config into SQLite store_collections so store.ts reads from DB
let loadedConfig: ReturnType<typeof loadConfig> | undefined;
try {
loadedConfig = loadConfig();
syncConfigToDb(store.db, loadedConfig);
} catch {
// Config may not exist yet — that's fine, DB works without it
}
// If config explicitly specifies models, honour them. Bubble up
// construction errors when a remote provider URI (jina:*) is requested
// so the user gets a clear error instead of a silent fall-back to local.
if (loadedConfig?.models) {
try {
setDefaultLlamaCpp(new LlamaCpp({
embedModel: loadedConfig.models.embed,
generateModel: loadedConfig.models.generate,
rerankModel: loadedConfig.models.rerank,
}));
} catch (err) {
const wantsRemote =
loadedConfig.models.embed?.startsWith("jina:") ||
loadedConfig.models.rerank?.startsWith("jina:");
if (wantsRemote) {
process.stderr.write(
`${c.red}QMD Error: ${err instanceof Error ? err.message : String(err)}${c.reset}\n`,
);
process.exit(1);
}
// Non-remote errors: keep the legacy silent behaviour.
}
}
// Attach the Jina usage reporter to the active LlamaCpp instance so any
// remote API calls record their token usage to the local SQLite store.
// Safe to call even when no remote provider is active — it's a no-op.
try {
const dbForReporter = store.db;
getDefaultLlamaCpp().setRemoteUsageReporter((event) => {
recordJinaUsage(dbForReporter, {
operation: event.operation,
model: event.model,
totalTokens: event.totalTokens,
promptTokens: event.promptTokens,
at: event.at,
});
});
} catch {
// Reporter wiring is best-effort.
}
}
return store;
}
function getDb(): Database {
return getStore().db;
}
/** Re-sync YAML config into SQLite after CLI mutations (add/remove/rename collection, context changes) */
function resyncConfig(): void {
const s = getStore();
try {
const config = loadConfig();
// Clear config hash to force re-sync
s.db.prepare(`DELETE FROM store_config WHERE key = 'config_hash'`).run();
syncConfigToDb(s.db, config);
} catch {
// Config may not exist — that's fine
}
}
function closeDb(): void {
if (store) {
store.close();
store = null;
}
}
function getDbPath(): string {
return store?.dbPath ?? storeDbPathOverride ?? getDefaultDbPath();
}
function setIndexName(name: string | null): void {
let normalizedName = name;
// Normalize relative paths to prevent malformed database paths
if (name && name.includes('/')) {
const { resolve } = require('path');
const { cwd } = require('process');
const absolutePath = resolve(cwd(), name);
// Replace path separators with underscores to create a valid filename
normalizedName = absolutePath.replace(/\//g, '_').replace(/^_/, '');
}
storeDbPathOverride = normalizedName ? getDefaultDbPath(normalizedName) : undefined;
// Reset open handle so next use opens the new index
closeDb();
}
function ensureVecTable(_db: Database, dimensions: number): void {
// Store owns the DB; ignore `_db` and ensure vec table on the active store
getStore().ensureVecTable(dimensions);
}
// Terminal colors (respects NO_COLOR env)
const useColor = !process.env.NO_COLOR && process.stdout.isTTY;
const c = {
reset: useColor ? "\x1b[0m" : "",
dim: useColor ? "\x1b[2m" : "",
bold: useColor ? "\x1b[1m" : "",
cyan: useColor ? "\x1b[36m" : "",
yellow: useColor ? "\x1b[33m" : "",
green: useColor ? "\x1b[32m" : "",
magenta: useColor ? "\x1b[35m" : "",
blue: useColor ? "\x1b[34m" : "",
red: useColor ? "\x1b[31m" : "",
};
// Terminal cursor control
const cursor = {
hide() { process.stderr.write('\x1b[?25l'); },
show() { process.stderr.write('\x1b[?25h'); },
};
// Ensure cursor is restored on exit
process.on('SIGINT', () => { cursor.show(); process.exit(130); });
process.on('SIGTERM', () => { cursor.show(); process.exit(143); });
// Terminal progress bar using OSC 9;4 escape sequence (TTY only)
const isTTY = process.stderr.isTTY;
const progress = {
set(percent: number) {
if (isTTY) process.stderr.write(`\x1b]9;4;1;${Math.round(percent)}\x07`);
},
clear() {
if (isTTY) process.stderr.write(`\x1b]9;4;0\x07`);
},
indeterminate() {
if (isTTY) process.stderr.write(`\x1b]9;4;3\x07`);
},
error() {
if (isTTY) process.stderr.write(`\x1b]9;4;2\x07`);
},
};
// Format seconds into human-readable ETA
function formatETA(seconds: number): string {
if (seconds < 60) return `${Math.round(seconds)}s`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`;
return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;
}
// Check index health and print warnings/tips
function checkIndexHealth(db: Database): void {
const { needsEmbedding, totalDocs, daysStale } = getIndexHealth(db);
// Warn if many docs need embedding
if (needsEmbedding > 0) {
const pct = Math.round((needsEmbedding / totalDocs) * 100);
if (pct >= 10) {
process.stderr.write(`${c.yellow}Warning: ${needsEmbedding} documents (${pct}%) need embeddings. Run 'qmd embed' for better results.${c.reset}\n`);
} else {
process.stderr.write(`${c.dim}Tip: ${needsEmbedding} documents need embeddings. Run 'qmd embed' to index them.${c.reset}\n`);
}
}
// Check if most recent document update is older than 2 weeks
if (daysStale !== null && daysStale >= 14) {
process.stderr.write(`${c.dim}Tip: Index last updated ${daysStale} days ago. Run 'qmd update' to refresh.${c.reset}\n`);
}
}
// Compute unique display path for a document
// Always include at least parent folder + filename, add more parent dirs until unique
function computeDisplayPath(
filepath: string,
collectionPath: string,
existingPaths: Set<string>
): string {
// Get path relative to collection (include collection dir name)
const collectionDir = collectionPath.replace(/\/$/, '');
const collectionName = collectionDir.split('/').pop() || '';
let relativePath: string;
if (filepath.startsWith(collectionDir + '/')) {
// filepath is under collection: use collection name + relative path
relativePath = collectionName + filepath.slice(collectionDir.length);
} else {
// Fallback: just use the filepath
relativePath = filepath;
}
const parts = relativePath.split('/').filter(p => p.length > 0);
// Always include at least parent folder + filename (minimum 2 parts if available)
// Then add more parent dirs until unique
const minParts = Math.min(2, parts.length);
for (let i = parts.length - minParts; i >= 0; i--) {
const candidate = parts.slice(i).join('/');
if (!existingPaths.has(candidate)) {
return candidate;
}
}
// Absolute fallback: use full path (should be unique)
return filepath;
}
function formatTimeAgo(date: Date): string {
const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
if (seconds < 60) return `${seconds}s ago`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ago`;
const days = Math.floor(hours / 24);
return `${days}d ago`;
}
function formatMs(ms: number): string {
if (ms < 1000) return `${ms}ms`;
return `${(ms / 1000).toFixed(1)}s`;
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
}
/** Format token counts with K/M/B suffixes for human readability. */
function formatTokens(n: number): string {
const abs = Math.abs(n);
const sign = n < 0 ? "-" : "";
if (abs < 1_000) return `${sign}${abs}`;
if (abs < 1_000_000) return `${sign}${(abs / 1_000).toFixed(1)}K`;
if (abs < 1_000_000_000) return `${sign}${(abs / 1_000_000).toFixed(2)}M`;
return `${sign}${(abs / 1_000_000_000).toFixed(2)}B`;
}
/**
* Parse a token count from an env var. Accepts plain digits and suffixes:
* "1000000000" → 1_000_000_000
* "1b" / "1B" → 1_000_000_000
* "500m" → 500_000_000
* "10k" → 10_000
* Returns 0 for invalid / missing values (disables quota tracking).
*/
function parseTokenEnv(raw: string | undefined): number {
if (!raw) return 0;
const trimmed = raw.trim().toLowerCase();
if (!trimmed) return 0;
const match = trimmed.match(/^([\d.]+)\s*([kmb]?)$/);
if (!match) return 0;
const num = Number.parseFloat(match[1]!);
if (!Number.isFinite(num) || num <= 0) return 0;
const mul =
match[2] === "k" ? 1_000 :
match[2] === "m" ? 1_000_000 :
match[2] === "b" ? 1_000_000_000 :
1;
return Math.floor(num * mul);
}
/** Parse QMD_JINA_QUOTA_WINDOW → QuotaWindow, with default and validation. */
function parseQuotaWindow(raw: string | undefined): QuotaWindow {
const v = (raw ?? "").trim().toLowerCase();
if (v === "24h" || v === "7d" || v === "30d" || v === "all") return v;
return "30d";
}
/**
* Read quota configuration from environment. Centralised so `qmd usage`,
* `qmd status`, and any future entrypoints compute the same numbers.
*/
function readQuotaOptionsFromEnv(): {
quotaLimit: number;
quotaWindow: QuotaWindow;
warnFraction: number;
} {
const quotaLimit = parseTokenEnv(process.env.QMD_JINA_QUOTA);
const quotaWindow = parseQuotaWindow(process.env.QMD_JINA_QUOTA_WINDOW);
let warnFraction = 0.8;
const warnPctRaw = process.env.QMD_JINA_WARN_PCT?.trim();
if (warnPctRaw) {
const n = Number.parseFloat(warnPctRaw);
if (Number.isFinite(n) && n > 0 && n <= 100) {
warnFraction = n / 100;
}
}
return { quotaLimit, quotaWindow, warnFraction };
}
/** Colour for a quota severity level. */
function severityColor(severity: QuotaSeverity): string {
if (severity === "over") return c.red;
if (severity === "critical") return c.red;
if (severity === "warn") return c.yellow;
return c.green;
}
/** Human label for a quota severity level. */
function severityLabel(severity: QuotaSeverity): string {
if (severity === "over") return "OVER QUOTA";
if (severity === "critical") return "CRITICAL";
if (severity === "warn") return "WARN";
return "OK";
}
/**
* Build the snapshot shape rendered by both `qmd usage` and `qmd status`.
* The `llmInstance` is captured separately so JSON output can include the
* active provider names without calling the getter twice.
*/
function collectUsageReport(): {
snapshot: UsageSnapshot;
embedProvider: string | null;
rerankProvider: string | null;
} {
const db = getDb();
const llmInstance = getDefaultLlamaCpp();
const quotaOpts = readQuotaOptionsFromEnv();
const snapshot = getUsageSnapshot(db, {
quotaLimit: quotaOpts.quotaLimit,
quotaWindow: quotaOpts.quotaWindow,
warnFraction: quotaOpts.warnFraction,
});
return {
snapshot,
embedProvider: llmInstance.usingRemoteEmbedder ? llmInstance.embedProviderName : null,
rerankProvider: llmInstance.usingRemoteReranker ? llmInstance.rerankProviderName : null,
};
}
/**
* Render a JSON payload describing current Jina usage. Stable shape intended
* for scripting — wraps `UsageSnapshot` with provider info and a schema tag.
*/
function renderUsageJson(report: ReturnType<typeof collectUsageReport>): string {
const { snapshot, embedProvider, rerankProvider } = report;
return JSON.stringify(
{
schema: "qmd.usage.v1",
generated_at: new Date().toISOString(),
provider: { embed: embedProvider, rerank: rerankProvider },
totals: {
last_24h: snapshot.totals.last24h,
last_7d: snapshot.totals.last7d,
last_30d: snapshot.totals.last30d,
all_time: snapshot.totals.allTime,
},
by_operation: snapshot.byOperation.map((row) => ({
operation: row.operation,
model: row.model,
calls: row.calls,
total_tokens: row.totalTokens,
})),
quota: snapshot.quota
? {
limit: snapshot.quota.limit,
window: snapshot.quota.window,
used: snapshot.quota.used,
used_fraction: snapshot.quota.usedFraction,
remaining: snapshot.quota.remaining,
warn_fraction: snapshot.quota.warnFraction,
severity: snapshot.quota.severity,
}
: null,
},
null,
2,
);
}
/**
* Show Jina API token usage broken down by operation + model, plus rolling
* windows (24h, 7d, 30d, all) and optional quota threshold. Designed to fit
* in a small terminal.
*
* When `json` is true, emit a machine-readable payload instead.
*/
async function showUsage(options: { json?: boolean } = {}): Promise<void> {
const report = collectUsageReport();
if (options.json) {
process.stdout.write(renderUsageJson(report) + "\n");
return;
}
const { snapshot, embedProvider, rerankProvider } = report;
console.log(`${c.bold}QMD Jina Usage${c.reset}\n`);
if (!embedProvider && !rerankProvider) {
console.log(`${c.dim}No remote provider active. Set QMD_EMBED_PROVIDER=jina${c.reset}`);
console.log(`${c.dim}or QMD_RERANK_PROVIDER=jina to enable Jina API usage tracking.${c.reset}`);
} else {
if (embedProvider) {
console.log(`${c.dim}Embed provider: ${embedProvider}${c.reset}`);
}
if (rerankProvider) {
console.log(`${c.dim}Rerank provider: ${rerankProvider}${c.reset}`);
}
console.log();
}
if (snapshot.totals.allTime === 0) {
console.log(`${c.dim}No usage recorded yet.${c.reset}`);
return;
}
// Quota block (if configured)
if (snapshot.quota) {
const q = snapshot.quota;
const color = severityColor(q.severity);
const pct = (q.usedFraction * 100).toFixed(1);
const label = severityLabel(q.severity);
const warnPct = (q.warnFraction * 100).toFixed(0);
console.log(`${c.bold}Quota (${q.window} window)${c.reset}`);
console.log(
` Used: ${color}${formatTokens(q.used)}${c.reset} / ${formatTokens(q.limit)} ` +
`(${color}${pct}%${c.reset}) ${color}${label}${c.reset}`,
);
if (q.remaining >= 0) {
console.log(` Remaining: ${formatTokens(q.remaining)}`);
} else {
console.log(` Over by: ${color}${formatTokens(-q.remaining)}${c.reset}`);
}
console.log(` ${c.dim}Warn threshold: ${warnPct}%${c.reset}\n`);
}
console.log(`${c.bold}Tokens consumed${c.reset}`);
console.log(` Last 24h: ${formatTokens(snapshot.totals.last24h)}`);
console.log(` Last 7d: ${formatTokens(snapshot.totals.last7d)}`);
console.log(` Last 30d: ${formatTokens(snapshot.totals.last30d)}`);
console.log(` All time: ${formatTokens(snapshot.totals.allTime)}`);
if (snapshot.byOperation.length > 0) {
console.log(`\n${c.bold}By operation${c.reset}`);
// Compute column widths
const opWidth = Math.max(9, ...snapshot.byOperation.map((s) => s.operation.length));
const modelWidth = Math.max(5, ...snapshot.byOperation.map((s) => s.model.length));
for (const row of snapshot.byOperation) {
const op = row.operation.padEnd(opWidth);
const model = row.model.padEnd(modelWidth);
const calls = String(row.calls).padStart(6);
const tokens = formatTokens(row.totalTokens).padStart(8);
console.log(` ${op} ${c.dim}${model}${c.reset} ${calls} calls ${tokens} tok`);
}
}
if (!snapshot.quota) {
console.log(
`\n${c.dim}Tip: set QMD_JINA_QUOTA=1B (or 500m, 10k) to enable quota warnings.${c.reset}`,
);
}
console.log(
`${c.dim}Tip: 'qmd usage reset' to clear history, 'qmd usage --json' for scripting, 'qmd usage chart' for daily histogram.${c.reset}`,
);
}
/**
* Render a usage report as CSV for spreadsheet import. Emits one row per
* (operation, model) pair — the most common shape for tracking consumption
* in Google Sheets / Excel. Totals and quota live in `--json` output; users
* who need those can combine `jq` + spreadsheet tools.
*/
function renderUsageCsv(report: ReturnType<typeof collectUsageReport>): string {
const rows: string[] = [];
rows.push("operation,model,calls,total_tokens");
for (const row of report.snapshot.byOperation) {
// CSV escape: wrap in quotes if contains comma / quote / newline, double-up embedded quotes.
const esc = (s: string) => {
if (/[,"\n]/.test(s)) return `"${s.replace(/"/g, '""')}"`;
return s;
};
rows.push(`${esc(row.operation)},${esc(row.model)},${row.calls},${row.totalTokens}`);
}
return rows.join("\n") + "\n";
}
/**
* Render an ASCII histogram of daily token usage. Computes a bar width
* proportional to the max daily value so the shape scales to any magnitude.
*
* Layout:
* MM-DD <bar> <label>
*
* Empty days render as a blank bar so gaps are visible. Uses unicode block
* characters for partial cells to get finer-grained bars.
*/
function renderUsageChart(
buckets: DailyUsageBucket[],
options: { barWidth?: number; useColor?: boolean } = {},
): string {
if (buckets.length === 0) return `${c.dim}No usage data.${c.reset}\n`;
const barWidth = options.barWidth ?? 40;
const max = Math.max(...buckets.map((b) => b.totalTokens));
if (max === 0) {
// All zero — show the outline so users know the range was checked.
const lines: string[] = [];
lines.push(`${c.dim}No tokens consumed in the last ${buckets.length} days.${c.reset}`);
for (const b of buckets) {
const mmdd = b.date.slice(5); // MM-DD
lines.push(` ${c.dim}${mmdd}${c.reset} ${c.dim}${"·".repeat(Math.max(0, barWidth))}${c.reset} ${c.dim}0${c.reset}`);
}
return lines.join("\n") + "\n";
}
// Unicode block characters for sub-cell bar width.
// Each cell = 1 full block; partial cells use 1/8 increments.
const partials = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"];
const full = "█";
const lines: string[] = [];
for (const b of buckets) {
const mmdd = b.date.slice(5); // MM-DD portion of YYYY-MM-DD
const fraction = b.totalTokens / max;
const cells = fraction * barWidth;
const fullCells = Math.floor(cells);
const partialIdx = Math.floor((cells - fullCells) * 8);
const partial = partials[partialIdx] ?? "";
const bar = full.repeat(fullCells) + partial;
const padding = " ".repeat(Math.max(0, barWidth - bar.length));
// Color: dim for empty, green for below 50% of max, yellow above.
const color =
b.totalTokens === 0 ? c.dim :
fraction >= 0.8 ? c.yellow :
c.green;
const label = formatTokens(b.totalTokens).padStart(8);
lines.push(` ${c.dim}${mmdd}${c.reset} ${color}${bar}${c.reset}${padding} ${label}`);
}
return lines.join("\n") + "\n";
}
/**
* Show a daily usage histogram for the last N days. Defaults to 30 days.
* Can emit JSON with `--json`.
*/
async function showUsageChart(options: { days?: number; json?: boolean } = {}): Promise<void> {
const db = getDb();
const days = Math.max(1, Math.min(365, options.days ?? 30));
const buckets = getDailyUsage(db, { days });
if (options.json) {
process.stdout.write(
JSON.stringify(
{
schema: "qmd.usage.chart.v1",
generated_at: new Date().toISOString(),
days,
buckets: buckets.map((b) => ({ date: b.date, total_tokens: b.totalTokens })),
},
null,
2,
) + "\n",
);
return;
}
console.log(`${c.bold}Jina daily usage (last ${days} days, UTC)${c.reset}\n`);
process.stdout.write(renderUsageChart(buckets));
const total = buckets.reduce((sum, b) => sum + b.totalTokens, 0);
const nonZero = buckets.filter((b) => b.totalTokens > 0).length;
const avg = nonZero > 0 ? total / nonZero : 0;
const max = Math.max(...buckets.map((b) => b.totalTokens));
console.log();
console.log(`${c.dim}Total: ${formatTokens(total)} | Active days: ${nonZero}/${days} | Peak: ${formatTokens(max)} | Avg/active: ${formatTokens(Math.round(avg))}${c.reset}`);
}
/**
* Render the qmd bench jina report as a human-readable table. Mirrors the
* JSON shape exactly so scripts and humans see the same numbers. Shows
* stddev when stage has >1 sample (i.e. --runs > 1 or single-embed).
*/
function renderBenchJinaTable(report: {
config: { size: number; docLen: number; runs: number; skipRerank: boolean; skipSingle: boolean };
providers: Array<{
provider: "local" | "jina";
label: string;
modelUri: string;
stages: Array<{
stage: "embed_single" | "embed_batch" | "rerank";
medianMs: number;
meanMs: number;
stddevMs: number;
p95Ms: number;
minMs: number;
maxMs: number;
throughputPerSec: number;
items: number;
runs: number;
latenciesMs: number[];
ok: boolean;
error?: string;
}>;
totalMs: number;
}>;
comparison?: Array<{
stage: "embed_single" | "embed_batch" | "rerank";
localMs: number;
jinaMs: number;
speedup: number;
winner: "local" | "jina" | "tie";
}>;
}): void {
const stageLabel = (s: string) =>
s === "embed_single" ? "embed (single)" :
s === "embed_batch" ? "embed (batch) " :
s === "rerank" ? "rerank " :
s;
const multiSample = report.config.runs > 1;
for (const prov of report.providers) {
const provColor = prov.provider === "jina" ? c.green : c.cyan;
console.log(`${c.bold}${provColor}${prov.label}${c.reset} ${c.dim}(${prov.modelUri})${c.reset}`);
if (multiSample) {
console.log(` ${c.dim}stage median p95 stddev throughput items${c.reset}`);
} else {
console.log(` ${c.dim}stage median p95 throughput items${c.reset}`);
}
for (const stage of prov.stages) {
if (!stage.ok) {
console.log(` ${stageLabel(stage.stage)} ${c.red}FAILED: ${stage.error ?? "unknown"}${c.reset}`);
continue;
}
const median = `${stage.medianMs.toFixed(1)}ms`.padStart(10);
const p95 = `${stage.p95Ms.toFixed(1)}ms`.padStart(9);
const thru = `${stage.throughputPerSec.toFixed(1)}/s`.padStart(12);
const items = String(stage.items).padStart(6);
if (multiSample) {
const stddev = `±${stage.stddevMs.toFixed(1)}ms`.padStart(10);
// Highlight noisy stages (stddev > 20% of median) in yellow.
const noiseColor =
stage.medianMs > 0 && stage.stddevMs / stage.medianMs > 0.2 ? c.yellow : c.dim;
console.log(
` ${stageLabel(stage.stage)} ${median} ${p95} ${noiseColor}${stddev}${c.reset} ${thru} ${items}`,
);
} else {
console.log(` ${stageLabel(stage.stage)} ${median} ${p95} ${thru} ${items}`);
}
}
console.log(` ${c.dim}Total wall time: ${prov.totalMs}ms${c.reset}\n`);
}
if (report.comparison && report.comparison.length > 0) {
console.log(`${c.bold}Comparison (local / jina)${c.reset}`);
console.log(` ${c.dim}stage local jina speedup winner${c.reset}`);
for (const row of report.comparison) {
const stage = stageLabel(row.stage);
const local = `${row.localMs.toFixed(1)}ms`.padStart(10);
const jina = `${row.jinaMs.toFixed(1)}ms`.padStart(10);
const speedupRaw = row.speedup.toFixed(2) + "×";
const speedup = speedupRaw.padStart(9);
const winnerColor =
row.winner === "jina" ? c.green :
row.winner === "local" ? c.cyan :
c.dim;
const winner = row.winner.padEnd(5);
console.log(` ${stage} ${local} ${jina} ${speedup} ${winnerColor}${winner}${c.reset}`);
}
console.log(
`\n${c.dim}Speedup = local_median / jina_median. >1 means jina is faster on this stage.${c.reset}`,
);
}
if (multiSample) {
console.log(
`${c.dim}Stats computed over ${report.config.runs} runs. Stddev in yellow = high variance (>20% of median).${c.reset}`,
);
}
console.log(`${c.dim}Tip: 'qmd bench jina --runs 5 --json' reduces noise and enables scripting.${c.reset}`);
}
async function showStatus(): Promise<void> {
const dbPath = getDbPath();
const db = getDb();
// Collections are defined in YAML; no duplicate cleanup needed.
// Collections are defined in YAML; no duplicate cleanup needed.
// Index size
let indexSize = 0;
try {
const stat = statSync(dbPath).size;
indexSize = stat;
} catch { }
// Collections info (from YAML + database stats)
const collections = listCollections(db);
// Overall stats
const totalDocs = db.prepare(`SELECT COUNT(*) as count FROM documents WHERE active = 1`).get() as { count: number };
const vectorCount = db.prepare(`SELECT COUNT(*) as count FROM content_vectors`).get() as { count: number };
const needsEmbedding = getHashesNeedingEmbedding(db);
// Most recent update across all collections
const mostRecent = db.prepare(`SELECT MAX(modified_at) as latest FROM documents WHERE active = 1`).get() as { latest: string | null };
console.log(`${c.bold}QMD Status${c.reset}\n`);
console.log(`Index: ${dbPath}`);
console.log(`Size: ${formatBytes(indexSize)}`);
// MCP daemon status (check PID file liveness)
const mcpCacheDir = process.env.XDG_CACHE_HOME
? resolve(process.env.XDG_CACHE_HOME, "qmd")
: resolve(homedir(), ".cache", "qmd");
const mcpPidPath = resolve(mcpCacheDir, "mcp.pid");
if (existsSync(mcpPidPath)) {
const mcpPid = parseInt(readFileSync(mcpPidPath, "utf-8").trim());
try {
process.kill(mcpPid, 0);
console.log(`MCP: ${c.green}running${c.reset} (PID ${mcpPid})`);
} catch {
unlinkSync(mcpPidPath);
// Stale PID file cleaned up silently
}
}
console.log("");
console.log(`${c.bold}Documents${c.reset}`);
console.log(` Total: ${totalDocs.count} files indexed`);
console.log(` Vectors: ${vectorCount.count} embedded`);
if (needsEmbedding > 0) {
console.log(` ${c.yellow}Pending: ${needsEmbedding} need embedding${c.reset} (run 'qmd embed')`);
}
if (mostRecent.latest) {
const lastUpdate = new Date(mostRecent.latest);
console.log(` Updated: ${formatTimeAgo(lastUpdate)}`);
}
// Get all contexts grouped by collection (from YAML)
const allContexts = listAllContexts();
const contextsByCollection = new Map<string, { path_prefix: string; context: string }[]>();
for (const ctx of allContexts) {
// Group contexts by collection name
if (!contextsByCollection.has(ctx.collection)) {
contextsByCollection.set(ctx.collection, []);
}
contextsByCollection.get(ctx.collection)!.push({
path_prefix: ctx.path,
context: ctx.context
});
}
// AST chunking status
try {
const { getASTStatus } = await import("../ast.js");
const ast = await getASTStatus();
console.log(`\n${c.bold}AST Chunking${c.reset}`);
if (ast.available) {
const ok = ast.languages.filter(l => l.available).map(l => l.language);
const fail = ast.languages.filter(l => !l.available);
console.log(` Status: ${c.green}active${c.reset}`);
console.log(` Languages: ${ok.join(", ")}`);
if (fail.length > 0) {
for (const f of fail) {
console.log(` ${c.yellow}Unavailable: ${f.language} (${f.error})${c.reset}`);
}
}
} else {
console.log(` Status: ${c.yellow}unavailable${c.reset} (falling back to regex chunking)`);
for (const l of ast.languages) {
if (l.error) console.log(` ${c.dim}${l.language}: ${l.error}${c.reset}`);
}
}
} catch {
console.log(`\n${c.bold}AST Chunking${c.reset}`);
console.log(` Status: ${c.dim}not available${c.reset}`);
}
if (collections.length > 0) {
console.log(`\n${c.bold}Collections${c.reset}`);
for (const col of collections) {
const lastMod = col.last_modified ? formatTimeAgo(new Date(col.last_modified)) : "never";
const contexts = contextsByCollection.get(col.name) || [];
console.log(` ${c.cyan}${col.name}${c.reset} ${c.dim}(qmd://${col.name}/)${c.reset}`);
console.log(` ${c.dim}Pattern:${c.reset} ${col.glob_pattern}`);
console.log(` ${c.dim}Files:${c.reset} ${col.active_count} (updated ${lastMod})`);
if (contexts.length > 0) {
console.log(` ${c.dim}Contexts:${c.reset} ${contexts.length}`);
for (const ctx of contexts) {
// Handle both empty string and '/' as root context
const pathDisplay = (ctx.path_prefix === '' || ctx.path_prefix === '/') ? '/' : `/${ctx.path_prefix}`;
const contextPreview = ctx.context.length > 60
? ctx.context.substring(0, 57) + '...'
: ctx.context;
console.log(` ${c.dim}${pathDisplay}:${c.reset} ${contextPreview}`);
}
}
}
// Show examples of virtual paths
console.log(`\n${c.bold}Examples${c.reset}`);
console.log(` ${c.dim}# List files in a collection${c.reset}`);
if (collections.length > 0 && collections[0]) {
console.log(` qmd ls ${collections[0].name}`);
}
console.log(` ${c.dim}# Get a document${c.reset}`);
if (collections.length > 0 && collections[0]) {
console.log(` qmd get qmd://${collections[0].name}/path/to/file.md`);
}
console.log(` ${c.dim}# Search within a collection${c.reset}`);
if (collections.length > 0 && collections[0]) {
console.log(` qmd search "query" -c ${collections[0].name}`);
}
} else {
console.log(`\n${c.dim}No collections. Run 'qmd collection add .' to index markdown files.${c.reset}`);
}
// Models
{
// hf:org/repo/file.gguf → https://huggingface.co/org/repo
const hfLink = (uri: string) => {
const match = uri.match(/^hf:([^/]+\/[^/]+)\//);
return match ? `https://huggingface.co/${match[1]}` : uri;
};
console.log(`\n${c.bold}Models${c.reset}`);
// Show active embedding backend. For remote providers (jina:*) we print
// the provider name + model instead of a HF link. If the user requested
// a remote provider but init failed (e.g. missing API key), surface the
// error so they can fix their env instead of silently falling back.
const requestedRemote = (process.env.QMD_EMBED_PROVIDER ?? "").trim().toLowerCase();
let activeEmbed: string;
let embedInitError: string | null = null;
try {
activeEmbed = getDefaultLlamaCpp().embedModelName;
} catch (err) {
activeEmbed = DEFAULT_EMBED_MODEL_URI;
embedInitError = err instanceof Error ? err.message : String(err);
}
if (embedInitError && requestedRemote) {
console.log(` Embedding: ${c.red}error${c.reset} (${requestedRemote})`);
console.log(` ${c.red}${embedInitError}${c.reset}`);
} else if (activeEmbed.startsWith("jina:")) {
const model = activeEmbed.slice("jina:".length);
console.log(` Embedding: ${c.green}jina${c.reset} (${model}) ${c.dim}[remote]${c.reset}`);
} else {
console.log(` Embedding: ${hfLink(activeEmbed)} ${c.dim}[local]${c.reset}`);
}
// Active rerank backend (mirrors the embed display).
const requestedRemoteRerank = (process.env.QMD_RERANK_PROVIDER ?? "").trim().toLowerCase();
let activeRerank: string;
let rerankInitError: string | null = null;
try {
activeRerank = getDefaultLlamaCpp().rerankModelName;
} catch (err) {
activeRerank = DEFAULT_RERANK_MODEL_URI;
rerankInitError = err instanceof Error ? err.message : String(err);
}
if (rerankInitError && requestedRemoteRerank) {
console.log(` Reranking: ${c.red}error${c.reset} (${requestedRemoteRerank})`);
console.log(` ${c.red}${rerankInitError}${c.reset}`);
} else if (activeRerank.startsWith("jina:")) {
const model = activeRerank.slice("jina:".length);