-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathstore.ts
More file actions
4851 lines (4254 loc) · 168 KB
/
Copy pathstore.ts
File metadata and controls
4851 lines (4254 loc) · 168 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
/**
* QMD Store - Core data access and retrieval functions
*
* This module provides all database operations, search functions, and document
* retrieval for QMD. It returns raw data structures that can be formatted by
* CLI or MCP consumers.
*
* Usage:
* const store = createStore("/path/to/db.sqlite");
* // or use default path:
* const store = createStore();
*/
import { openDatabase, loadSqliteVec } from "./db.js";
import type { Database } from "./db.js";
import picomatch from "picomatch";
import { createHash } from "crypto";
import { readFileSync, realpathSync, statSync, mkdirSync } from "node:fs";
// Note: node:path resolve is not imported — we export our own cross-platform resolve()
import fastGlob from "fast-glob";
import {
LlamaCpp,
getDefaultLlamaCpp,
formatQueryForEmbedding,
formatDocForEmbedding,
withLLMSessionForLlm,
type RerankDocument,
type ILLMSession,
} from "./llm.js";
import type {
NamedCollection,
Collection,
CollectionConfig,
ContextMap,
} from "./collections.js";
// =============================================================================
// Configuration
// =============================================================================
const HOME = process.env.HOME || "/tmp";
export const DEFAULT_EMBED_MODEL = "embeddinggemma";
export const DEFAULT_RERANK_MODEL = "ExpedientFalcon/qwen3-reranker:0.6b-q8_0";
export const DEFAULT_QUERY_MODEL = "Qwen/Qwen3-1.7B";
export const DEFAULT_GLOB = "**/*.md";
export const DEFAULT_MULTI_GET_MAX_BYTES = 10 * 1024; // 10KB
export const DEFAULT_EMBED_MAX_DOCS_PER_BATCH = 64;
export const DEFAULT_EMBED_MAX_BATCH_BYTES = 64 * 1024 * 1024; // 64MB
// Chunking: 900 tokens per chunk with 15% overlap
// Increased from 800 to accommodate smart chunking finding natural break points
export const CHUNK_SIZE_TOKENS = 900;
export const CHUNK_OVERLAP_TOKENS = Math.floor(CHUNK_SIZE_TOKENS * 0.15); // 135 tokens (15% overlap)
// Fallback char-based approximation for sync chunking (~4 chars per token)
export const CHUNK_SIZE_CHARS = CHUNK_SIZE_TOKENS * 4; // 3600 chars
export const CHUNK_OVERLAP_CHARS = CHUNK_OVERLAP_TOKENS * 4; // 540 chars
// Search window for finding optimal break points (in tokens, ~200 tokens)
export const CHUNK_WINDOW_TOKENS = 200;
export const CHUNK_WINDOW_CHARS = CHUNK_WINDOW_TOKENS * 4; // 800 chars
/**
* Get the LlamaCpp instance for a store — prefers the store's own instance,
* falls back to the global singleton.
*/
function getLlm(store: Store): LlamaCpp {
return store.llm ?? getDefaultLlamaCpp();
}
// =============================================================================
// Smart Chunking - Break Point Detection
// =============================================================================
/**
* A potential break point in the document with a base score indicating quality.
*/
export interface BreakPoint {
pos: number; // character position
score: number; // base score (higher = better break point)
type: string; // for debugging: 'h1', 'h2', 'blank', etc.
}
/**
* A region where a code fence exists (between ``` markers).
* We should never split inside a code fence.
*/
export interface CodeFenceRegion {
start: number; // position of opening ```
end: number; // position of closing ``` (or document end if unclosed)
}
/**
* Patterns for detecting break points in markdown documents.
* Higher scores indicate better places to split.
* Scores are spread wide so headings decisively beat lower-quality breaks.
* Order matters for scoring - more specific patterns first.
*/
export const BREAK_PATTERNS: [RegExp, number, string][] = [
[/\n#{1}(?!#)/g, 100, 'h1'], // # but not ##
[/\n#{2}(?!#)/g, 90, 'h2'], // ## but not ###
[/\n#{3}(?!#)/g, 80, 'h3'], // ### but not ####
[/\n#{4}(?!#)/g, 70, 'h4'], // #### but not #####
[/\n#{5}(?!#)/g, 60, 'h5'], // ##### but not ######
[/\n#{6}(?!#)/g, 50, 'h6'], // ######
[/\n```/g, 80, 'codeblock'], // code block boundary (same as h3)
[/\n(?:---|\*\*\*|___)\s*\n/g, 60, 'hr'], // horizontal rule
[/\n\n+/g, 20, 'blank'], // paragraph boundary
[/\n[-*]\s/g, 5, 'list'], // unordered list item
[/\n\d+\.\s/g, 5, 'numlist'], // ordered list item
[/\n/g, 1, 'newline'], // minimal break
];
/**
* Scan text for all potential break points.
* Returns sorted array of break points with higher-scoring patterns taking precedence
* when multiple patterns match the same position.
*/
export function scanBreakPoints(text: string): BreakPoint[] {
const points: BreakPoint[] = [];
const seen = new Map<number, BreakPoint>(); // pos -> best break point at that pos
for (const [pattern, score, type] of BREAK_PATTERNS) {
for (const match of text.matchAll(pattern)) {
const pos = match.index!;
const existing = seen.get(pos);
// Keep higher score if position already seen
if (!existing || score > existing.score) {
const bp = { pos, score, type };
seen.set(pos, bp);
}
}
}
// Convert to array and sort by position
for (const bp of seen.values()) {
points.push(bp);
}
return points.sort((a, b) => a.pos - b.pos);
}
/**
* Find all code fence regions in the text.
* Code fences are delimited by ``` and we should never split inside them.
*/
export function findCodeFences(text: string): CodeFenceRegion[] {
const regions: CodeFenceRegion[] = [];
const fencePattern = /\n```/g;
let inFence = false;
let fenceStart = 0;
for (const match of text.matchAll(fencePattern)) {
if (!inFence) {
fenceStart = match.index!;
inFence = true;
} else {
regions.push({ start: fenceStart, end: match.index! + match[0].length });
inFence = false;
}
}
// Handle unclosed fence - extends to end of document
if (inFence) {
regions.push({ start: fenceStart, end: text.length });
}
return regions;
}
/**
* Check if a position is inside a code fence region.
*/
export function isInsideCodeFence(pos: number, fences: CodeFenceRegion[]): boolean {
return fences.some(f => pos > f.start && pos < f.end);
}
/**
* Find the best cut position using scored break points with distance decay.
*
* Uses squared distance for gentler early decay - headings far back still win
* over low-quality breaks near the target.
*
* @param breakPoints - Pre-scanned break points from scanBreakPoints()
* @param targetCharPos - The ideal cut position (e.g., maxChars boundary)
* @param windowChars - How far back to search for break points (default ~200 tokens)
* @param decayFactor - How much to penalize distance (0.7 = 30% score at window edge)
* @param codeFences - Code fence regions to avoid splitting inside
* @returns The best position to cut at
*/
export function findBestCutoff(
breakPoints: BreakPoint[],
targetCharPos: number,
windowChars: number = CHUNK_WINDOW_CHARS,
decayFactor: number = 0.7,
codeFences: CodeFenceRegion[] = []
): number {
const windowStart = targetCharPos - windowChars;
let bestScore = -1;
let bestPos = targetCharPos;
for (const bp of breakPoints) {
if (bp.pos < windowStart) continue;
if (bp.pos > targetCharPos) break; // sorted, so we can stop
// Skip break points inside code fences
if (isInsideCodeFence(bp.pos, codeFences)) continue;
const distance = targetCharPos - bp.pos;
// Squared distance decay: gentle early, steep late
// At target: multiplier = 1.0
// At 25% back: multiplier = 0.956
// At 50% back: multiplier = 0.825
// At 75% back: multiplier = 0.606
// At window edge: multiplier = 0.3
const normalizedDist = distance / windowChars;
const multiplier = 1.0 - (normalizedDist * normalizedDist) * decayFactor;
const finalScore = bp.score * multiplier;
if (finalScore > bestScore) {
bestScore = finalScore;
bestPos = bp.pos;
}
}
return bestPos;
}
// =============================================================================
// Chunk Strategy
// =============================================================================
export type ChunkStrategy = "auto" | "regex";
/**
* Merge two sets of break points (e.g. regex + AST), keeping the highest
* score at each position. Result is sorted by position.
*/
export function mergeBreakPoints(a: BreakPoint[], b: BreakPoint[]): BreakPoint[] {
const seen = new Map<number, BreakPoint>();
for (const bp of a) {
const existing = seen.get(bp.pos);
if (!existing || bp.score > existing.score) {
seen.set(bp.pos, bp);
}
}
for (const bp of b) {
const existing = seen.get(bp.pos);
if (!existing || bp.score > existing.score) {
seen.set(bp.pos, bp);
}
}
return Array.from(seen.values()).sort((a, b) => a.pos - b.pos);
}
/**
* Core chunk algorithm that operates on precomputed break points and code fences.
* This is the shared implementation used by both regex-only and AST-aware chunking.
*/
export function chunkDocumentWithBreakPoints(
content: string,
breakPoints: BreakPoint[],
codeFences: CodeFenceRegion[],
maxChars: number = CHUNK_SIZE_CHARS,
overlapChars: number = CHUNK_OVERLAP_CHARS,
windowChars: number = CHUNK_WINDOW_CHARS
): { text: string; pos: number }[] {
if (content.length <= maxChars) {
return [{ text: content, pos: 0 }];
}
const chunks: { text: string; pos: number }[] = [];
let charPos = 0;
while (charPos < content.length) {
const targetEndPos = Math.min(charPos + maxChars, content.length);
let endPos = targetEndPos;
if (endPos < content.length) {
const bestCutoff = findBestCutoff(
breakPoints,
targetEndPos,
windowChars,
0.7,
codeFences
);
if (bestCutoff > charPos && bestCutoff <= targetEndPos) {
endPos = bestCutoff;
}
}
if (endPos <= charPos) {
endPos = Math.min(charPos + maxChars, content.length);
}
chunks.push({ text: content.slice(charPos, endPos), pos: charPos });
if (endPos >= content.length) {
break;
}
charPos = endPos - overlapChars;
const lastChunkPos = chunks.at(-1)!.pos;
if (charPos <= lastChunkPos) {
charPos = endPos;
}
}
return chunks;
}
// Hybrid query: strong BM25 signal detection thresholds
// Skip expensive LLM expansion when top result is strong AND clearly separated from runner-up
export const STRONG_SIGNAL_MIN_SCORE = 0.85;
export const STRONG_SIGNAL_MIN_GAP = 0.15;
// Max candidates to pass to reranker — balances quality vs latency.
// 40 keeps rank 31-40 visible to the reranker (matters for recall on broad queries).
export const RERANK_CANDIDATE_LIMIT = 40;
/**
* A typed query expansion result. Decoupled from llm.ts internal Queryable —
* same shape, but store.ts owns its own public API type.
*
* - lex: keyword variant → routes to FTS only
* - vec: semantic variant → routes to vector only
* - hyde: hypothetical document → routes to vector only
*/
export type ExpandedQuery = {
type: 'lex' | 'vec' | 'hyde';
query: string;
/** Optional line number for error reporting (CLI parser) */
line?: number;
};
// =============================================================================
// Path utilities
// =============================================================================
export function homedir(): string {
return HOME;
}
/**
* Check if a path is absolute.
* Supports:
* - Unix paths: /path/to/file
* - Windows native: C:\path or C:/path
* - Git Bash: /c/path or /C/path (C-Z drives, excluding A/B floppy drives)
*
* Note: /c without trailing slash is treated as Unix path (directory named "c"),
* while /c/ or /c/path are treated as Git Bash paths (C: drive).
*/
export function isAbsolutePath(path: string): boolean {
if (!path) return false;
// Unix absolute path
if (path.startsWith('/')) {
// Check if it's a Git Bash style path like /c/ or /c/Users (C-Z only, not A or B)
// Requires path[2] === '/' to distinguish from Unix paths like /c or /cache
// Skipped on WSL where /c/ is a valid drvfs mount point, not a drive letter
if (!isWSL() && path.length >= 3 && path[2] === '/') {
const driveLetter = path[1];
if (driveLetter && /[c-zC-Z]/.test(driveLetter)) {
return true;
}
}
// Any other path starting with / is Unix absolute
return true;
}
// Windows native path: C:\ or C:/ (any letter A-Z)
if (path.length >= 2 && /[a-zA-Z]/.test(path[0]!) && path[1] === ':') {
return true;
}
return false;
}
/**
* Normalize path separators to forward slashes.
* Converts Windows backslashes to forward slashes.
*/
export function normalizePathSeparators(path: string): string {
return path.replace(/\\/g, '/');
}
/**
* Detect if running inside WSL (Windows Subsystem for Linux).
* On WSL, paths like /c/work/... are valid drvfs mount points, not Git Bash paths.
*/
function isWSL(): boolean {
return !!(process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP);
}
/**
* Get the relative path from a prefix.
* Returns null if path is not under prefix.
* Returns empty string if path equals prefix.
*/
export function getRelativePathFromPrefix(path: string, prefix: string): string | null {
// Empty prefix is invalid
if (!prefix) {
return null;
}
const normalizedPath = normalizePathSeparators(path);
const normalizedPrefix = normalizePathSeparators(prefix);
// Ensure prefix ends with / for proper matching
const prefixWithSlash = !normalizedPrefix.endsWith('/')
? normalizedPrefix + '/'
: normalizedPrefix;
// Exact match
if (normalizedPath === normalizedPrefix) {
return '';
}
// Check if path starts with prefix
if (normalizedPath.startsWith(prefixWithSlash)) {
return normalizedPath.slice(prefixWithSlash.length);
}
return null;
}
export function resolve(...paths: string[]): string {
if (paths.length === 0) {
throw new Error("resolve: at least one path segment is required");
}
// Normalize all paths to use forward slashes
const normalizedPaths = paths.map(normalizePathSeparators);
let result = '';
let windowsDrive = '';
// Check if first path is absolute
const firstPath = normalizedPaths[0]!;
if (isAbsolutePath(firstPath)) {
result = firstPath;
// Extract Windows drive letter if present
if (firstPath.length >= 2 && /[a-zA-Z]/.test(firstPath[0]!) && firstPath[1] === ':') {
windowsDrive = firstPath.slice(0, 2);
result = firstPath.slice(2);
} else if (!isWSL() && firstPath.startsWith('/') && firstPath.length >= 3 && firstPath[2] === '/') {
// Git Bash style: /c/ -> C: (C-Z drives only, not A or B)
// Skipped on WSL where /c/ is a valid drvfs mount point, not a drive letter
const driveLetter = firstPath[1];
if (driveLetter && /[c-zC-Z]/.test(driveLetter)) {
windowsDrive = driveLetter.toUpperCase() + ':';
result = firstPath.slice(2);
}
}
} else {
// Start with PWD or cwd, then append the first relative path
const pwd = normalizePathSeparators(process.env.PWD || process.cwd());
// Extract Windows drive from PWD if present
if (pwd.length >= 2 && /[a-zA-Z]/.test(pwd[0]!) && pwd[1] === ':') {
windowsDrive = pwd.slice(0, 2);
result = pwd.slice(2) + '/' + firstPath;
} else {
result = pwd + '/' + firstPath;
}
}
// Process remaining paths
for (let i = 1; i < normalizedPaths.length; i++) {
const p = normalizedPaths[i]!;
if (isAbsolutePath(p)) {
// Absolute path replaces everything
result = p;
// Update Windows drive if present
if (p.length >= 2 && /[a-zA-Z]/.test(p[0]!) && p[1] === ':') {
windowsDrive = p.slice(0, 2);
result = p.slice(2);
} else if (!isWSL() && p.startsWith('/') && p.length >= 3 && p[2] === '/') {
// Git Bash style (C-Z drives only, not A or B)
// Skipped on WSL where /c/ is a valid drvfs mount point, not a drive letter
const driveLetter = p[1];
if (driveLetter && /[c-zC-Z]/.test(driveLetter)) {
windowsDrive = driveLetter.toUpperCase() + ':';
result = p.slice(2);
} else {
windowsDrive = '';
}
} else {
windowsDrive = '';
}
} else {
// Relative path - append
result = result + '/' + p;
}
}
// Normalize . and .. components
const parts = result.split('/').filter(Boolean);
const normalized: string[] = [];
for (const part of parts) {
if (part === '..') {
normalized.pop();
} else if (part !== '.') {
normalized.push(part);
}
}
// Build final path
const finalPath = '/' + normalized.join('/');
// Prepend Windows drive if present
if (windowsDrive) {
return windowsDrive + finalPath;
}
return finalPath;
}
// Flag to indicate production mode (set by qmd.ts at startup)
let _productionMode = false;
export function enableProductionMode(): void {
_productionMode = true;
}
/** Reset production mode flag — only for testing. */
export function _resetProductionModeForTesting(): void {
_productionMode = false;
}
export function getDefaultDbPath(indexName: string = "index"): string {
// Always allow override via INDEX_PATH (for testing)
if (process.env.INDEX_PATH) {
return process.env.INDEX_PATH;
}
// In non-production mode (tests), require explicit path
if (!_productionMode) {
throw new Error(
"Database path not set. Tests must set INDEX_PATH env var or use createStore() with explicit path. " +
"This prevents tests from accidentally writing to the global index."
);
}
const cacheDir = process.env.XDG_CACHE_HOME || resolve(homedir(), ".cache");
const qmdCacheDir = resolve(cacheDir, "qmd");
try { mkdirSync(qmdCacheDir, { recursive: true }); } catch { }
return resolve(qmdCacheDir, `${indexName}.sqlite`);
}
export function getPwd(): string {
return process.env.PWD || process.cwd();
}
export function getRealPath(path: string): string {
try {
return realpathSync(path);
} catch {
return resolve(path);
}
}
// =============================================================================
// Virtual Path Utilities (qmd://)
// =============================================================================
export type VirtualPath = {
collectionName: string;
path: string; // relative path within collection
};
/**
* Normalize explicit virtual path formats to standard qmd:// format.
* Only handles paths that are already explicitly virtual:
* - qmd://collection/path.md (already normalized)
* - qmd:////collection/path.md (extra slashes - normalize)
* - //collection/path.md (missing qmd: prefix - add it)
*
* Does NOT handle:
* - collection/path.md (bare paths - could be filesystem relative)
* - :linenum suffix (should be parsed separately before calling this)
*/
export function normalizeVirtualPath(input: string): string {
let path = input.trim();
// Handle qmd:// with extra slashes: qmd:////collection/path -> qmd://collection/path
if (path.startsWith('qmd:')) {
// Remove qmd: prefix and normalize slashes
path = path.slice(4);
// Remove leading slashes and re-add exactly two
path = path.replace(/^\/+/, '');
return `qmd://${path}`;
}
// Handle //collection/path (missing qmd: prefix)
if (path.startsWith('//')) {
path = path.replace(/^\/+/, '');
return `qmd://${path}`;
}
// Return as-is for other cases (filesystem paths, docids, bare collection/path, etc.)
return path;
}
/**
* Parse a virtual path like "qmd://collection-name/path/to/file.md"
* into its components.
* Also supports collection root: "qmd://collection-name/" or "qmd://collection-name"
*/
export function parseVirtualPath(virtualPath: string): VirtualPath | null {
// Normalize the path first
const normalized = normalizeVirtualPath(virtualPath);
// Match: qmd://collection-name[/optional-path]
// Allows: qmd://name, qmd://name/, qmd://name/path
const match = normalized.match(/^qmd:\/\/([^\/]+)\/?(.*)$/);
if (!match?.[1]) return null;
return {
collectionName: match[1],
path: match[2] ?? '', // Empty string for collection root
};
}
/**
* Build a virtual path from collection name and relative path.
*/
export function buildVirtualPath(collectionName: string, path: string): string {
return `qmd://${collectionName}/${path}`;
}
/**
* Check if a path is explicitly a virtual path.
* Only recognizes explicit virtual path formats:
* - qmd://collection/path.md
* - //collection/path.md
*
* Does NOT consider bare collection/path.md as virtual - that should be
* handled separately by checking if the first component is a collection name.
*/
export function isVirtualPath(path: string): boolean {
const trimmed = path.trim();
// Explicit qmd:// prefix (with any number of slashes)
if (trimmed.startsWith('qmd:')) return true;
// //collection/path format (missing qmd: prefix)
if (trimmed.startsWith('//')) return true;
return false;
}
/**
* Resolve a virtual path to absolute filesystem path.
*/
export function resolveVirtualPath(db: Database, virtualPath: string): string | null {
const parsed = parseVirtualPath(virtualPath);
if (!parsed) return null;
const coll = getCollectionByName(db, parsed.collectionName);
if (!coll) return null;
return resolve(coll.pwd, parsed.path);
}
/**
* Convert an absolute filesystem path to a virtual path.
* Returns null if the file is not in any indexed collection.
*/
export function toVirtualPath(db: Database, absolutePath: string): string | null {
// Get all collections from DB
const collections = getStoreCollections(db);
// Find which collection this absolute path belongs to
for (const coll of collections) {
if (absolutePath.startsWith(coll.path + '/') || absolutePath === coll.path) {
// Extract relative path
const relativePath = absolutePath.startsWith(coll.path + '/')
? absolutePath.slice(coll.path.length + 1)
: '';
// Verify this document exists in the database
const doc = db.prepare(`
SELECT d.path
FROM documents d
WHERE d.collection = ? AND d.path = ? AND d.active = 1
LIMIT 1
`).get(coll.name, relativePath) as { path: string } | null;
if (doc) {
return buildVirtualPath(coll.name, relativePath);
}
}
}
return null;
}
// =============================================================================
// Database initialization
// =============================================================================
function createSqliteVecUnavailableError(reason: string): Error {
return new Error(
"sqlite-vec extension is unavailable. " +
`${reason}. ` +
"Install Homebrew SQLite so the sqlite-vec extension can be loaded, " +
"and set BREW_PREFIX if Homebrew is installed in a non-standard location."
);
}
function getErrorMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
export function verifySqliteVecLoaded(db: Database): void {
try {
const row = db.prepare(`SELECT vec_version() AS version`).get() as { version?: string } | null;
if (!row?.version || typeof row.version !== "string") {
throw new Error("vec_version() returned no version");
}
} catch (err) {
const message = getErrorMessage(err);
throw createSqliteVecUnavailableError(`sqlite-vec probe failed (${message})`);
}
}
let _sqliteVecAvailable: boolean | null = null;
function initializeDatabase(db: Database): void {
try {
loadSqliteVec(db);
verifySqliteVecLoaded(db);
_sqliteVecAvailable = true;
} catch (err) {
// sqlite-vec is optional — vector search won't work but FTS is fine
_sqliteVecAvailable = false;
console.warn(getErrorMessage(err));
}
db.exec("PRAGMA journal_mode = WAL");
db.exec("PRAGMA foreign_keys = ON");
// Drop legacy tables that are now managed in YAML
db.exec(`DROP TABLE IF EXISTS path_contexts`);
db.exec(`DROP TABLE IF EXISTS collections`);
// Content-addressable storage - the source of truth for document content
db.exec(`
CREATE TABLE IF NOT EXISTS content (
hash TEXT PRIMARY KEY,
doc TEXT NOT NULL,
created_at TEXT NOT NULL
)
`);
// Documents table - file system layer mapping virtual paths to content hashes
// Collections are now managed in ~/.config/qmd/index.yml
db.exec(`
CREATE TABLE IF NOT EXISTS documents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
collection TEXT NOT NULL,
path TEXT NOT NULL,
title TEXT NOT NULL,
hash TEXT NOT NULL,
created_at TEXT NOT NULL,
modified_at TEXT NOT NULL,
active INTEGER NOT NULL DEFAULT 1,
FOREIGN KEY (hash) REFERENCES content(hash) ON DELETE CASCADE,
UNIQUE(collection, path)
)
`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_documents_collection ON documents(collection, active)`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_documents_hash ON documents(hash)`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_documents_path ON documents(path, active)`);
// Cache table for LLM API calls
db.exec(`
CREATE TABLE IF NOT EXISTS llm_cache (
hash TEXT PRIMARY KEY,
result TEXT NOT NULL,
created_at TEXT NOT NULL
)
`);
// Content vectors
const cvInfo = db.prepare(`PRAGMA table_info(content_vectors)`).all() as { name: string }[];
const hasSeqColumn = cvInfo.some(col => col.name === 'seq');
if (cvInfo.length > 0 && !hasSeqColumn) {
db.exec(`DROP TABLE IF EXISTS content_vectors`);
db.exec(`DROP TABLE IF EXISTS vectors_vec`);
}
db.exec(`
CREATE TABLE IF NOT EXISTS content_vectors (
hash TEXT NOT NULL,
seq INTEGER NOT NULL DEFAULT 0,
pos INTEGER NOT NULL DEFAULT 0,
model TEXT NOT NULL,
embedded_at TEXT NOT NULL,
PRIMARY KEY (hash, seq)
)
`);
// Store collections — makes the DB self-contained (no external config needed)
db.exec(`
CREATE TABLE IF NOT EXISTS store_collections (
name TEXT PRIMARY KEY,
path TEXT NOT NULL,
pattern TEXT NOT NULL DEFAULT '**/*.md',
ignore_patterns TEXT,
include_by_default INTEGER DEFAULT 1,
update_command TEXT,
context TEXT
)
`);
// Store config — key-value metadata (e.g. config_hash for sync optimization)
db.exec(`
CREATE TABLE IF NOT EXISTS store_config (
key TEXT PRIMARY KEY,
value TEXT
)
`);
// Jina usage tracking. Append-only event log: each row is one successful
// API call to the Jina cloud. We use an event log instead of a counter so
// users can compute rolling windows (last day/week/month) without losing
// history. Indexed on (at) for fast time-window aggregation.
db.exec(`
CREATE TABLE IF NOT EXISTS jina_usage (
id INTEGER PRIMARY KEY AUTOINCREMENT,
operation TEXT NOT NULL,
model TEXT NOT NULL,
total_tokens INTEGER NOT NULL,
prompt_tokens INTEGER,
at TEXT NOT NULL
)
`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_jina_usage_at ON jina_usage(at)`);
// FTS - index filepath (collection/path), title, and content
db.exec(`
CREATE VIRTUAL TABLE IF NOT EXISTS documents_fts USING fts5(
filepath, title, body,
tokenize='porter unicode61'
)
`);
// Triggers to keep FTS in sync
db.exec(`
CREATE TRIGGER IF NOT EXISTS documents_ai AFTER INSERT ON documents
WHEN new.active = 1
BEGIN
INSERT INTO documents_fts(rowid, filepath, title, body)
SELECT
new.id,
new.collection || '/' || new.path,
new.title,
(SELECT doc FROM content WHERE hash = new.hash)
WHERE new.active = 1;
END
`);
db.exec(`
CREATE TRIGGER IF NOT EXISTS documents_ad AFTER DELETE ON documents BEGIN
DELETE FROM documents_fts WHERE rowid = old.id;
END
`);
db.exec(`
CREATE TRIGGER IF NOT EXISTS documents_au AFTER UPDATE ON documents
BEGIN
-- Delete from FTS if no longer active
DELETE FROM documents_fts WHERE rowid = old.id AND new.active = 0;
-- Update FTS if still/newly active
INSERT OR REPLACE INTO documents_fts(rowid, filepath, title, body)
SELECT
new.id,
new.collection || '/' || new.path,
new.title,
(SELECT doc FROM content WHERE hash = new.hash)
WHERE new.active = 1;
END
`);
}
// =============================================================================
// Store Collections — DB accessor functions
// =============================================================================
type StoreCollectionRow = {
name: string;
path: string;
pattern: string;
ignore_patterns: string | null;
include_by_default: number;
update_command: string | null;
context: string | null;
};
function rowToNamedCollection(row: StoreCollectionRow): NamedCollection {
return {
name: row.name,
path: row.path,
pattern: row.pattern,
...(row.ignore_patterns ? { ignore: JSON.parse(row.ignore_patterns) as string[] } : {}),
...(row.include_by_default === 0 ? { includeByDefault: false } : {}),
...(row.update_command ? { update: row.update_command } : {}),
...(row.context ? { context: JSON.parse(row.context) as ContextMap } : {}),
};
}
export function getStoreCollections(db: Database): NamedCollection[] {
const rows = db.prepare(`SELECT * FROM store_collections`).all() as StoreCollectionRow[];
return rows.map(rowToNamedCollection);
}
export function getStoreCollection(db: Database, name: string): NamedCollection | null {
const row = db.prepare(`SELECT * FROM store_collections WHERE name = ?`).get(name) as StoreCollectionRow | null | undefined;
if (row == null) return null;
return rowToNamedCollection(row);
}
export function getStoreGlobalContext(db: Database): string | undefined {
const row = db.prepare(`SELECT value FROM store_config WHERE key = 'global_context'`).get() as { value: string } | null | undefined;
if (row == null) return undefined;
return row.value || undefined;
}
export function getStoreContexts(db: Database): Array<{ collection: string; path: string; context: string }> {
const results: Array<{ collection: string; path: string; context: string }> = [];
// Global context
const globalCtx = getStoreGlobalContext(db);
if (globalCtx) {
results.push({ collection: "*", path: "/", context: globalCtx });
}
// Collection contexts
const rows = db.prepare(`SELECT name, context FROM store_collections WHERE context IS NOT NULL`).all() as { name: string; context: string }[];
for (const row of rows) {
const ctxMap = JSON.parse(row.context) as ContextMap;
for (const [path, context] of Object.entries(ctxMap)) {
results.push({ collection: row.name, path, context });
}
}
return results;
}
export function upsertStoreCollection(db: Database, name: string, collection: Omit<Collection, 'pattern'> & { pattern?: string }): void {
db.prepare(`
INSERT INTO store_collections (name, path, pattern, ignore_patterns, include_by_default, update_command, context)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(name) DO UPDATE SET
path = excluded.path,
pattern = excluded.pattern,
ignore_patterns = excluded.ignore_patterns,
include_by_default = excluded.include_by_default,
update_command = excluded.update_command,
context = excluded.context
`).run(
name,
collection.path,
collection.pattern || '**/*.md',
collection.ignore ? JSON.stringify(collection.ignore) : null,
collection.includeByDefault === false ? 0 : 1,
collection.update || null,
collection.context ? JSON.stringify(collection.context) : null,
);
}
export function deleteStoreCollection(db: Database, name: string): boolean {
const result = db.prepare(`DELETE FROM store_collections WHERE name = ?`).run(name);
return result.changes > 0;
}
export function renameStoreCollection(db: Database, oldName: string, newName: string): boolean {
// Check target doesn't exist
const existing = db.prepare(`SELECT name FROM store_collections WHERE name = ?`).get(newName) as { name: string } | null | undefined;
if (existing != null) {
throw new Error(`Collection '${newName}' already exists`);
}
const result = db.prepare(`UPDATE store_collections SET name = ? WHERE name = ?`).run(newName, oldName);
return result.changes > 0;
}
export function updateStoreContext(db: Database, collectionName: string, path: string, text: string): boolean {
const row = db.prepare(`SELECT context FROM store_collections WHERE name = ?`).get(collectionName) as { context: string | null } | null | undefined;
if (row == null) return false;
const ctxMap: ContextMap = row.context ? JSON.parse(row.context) : {};
ctxMap[path] = text;
db.prepare(`UPDATE store_collections SET context = ? WHERE name = ?`).run(JSON.stringify(ctxMap), collectionName);
return true;
}
export function removeStoreContext(db: Database, collectionName: string, path: string): boolean {
const row = db.prepare(`SELECT context FROM store_collections WHERE name = ?`).get(collectionName) as { context: string | null } | null | undefined;