Repository navigation
Expand file tree
/
Copy pathstore.ts
More file actions
6130 lines (5414 loc) · 222 KB
/
Copy pathstore.ts
File metadata and controls
6130 lines (5414 loc) · 222 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 { qmdHomedir } from "./paths.js";
import {
LlamaCpp,
getDefaultLlamaCpp,
formatQueryForEmbedding,
formatDocForEmbedding,
withLLMSessionForLlm,
DEFAULT_EMBED_MODEL_URI,
DEFAULT_RERANK_MODEL_URI,
DEFAULT_GENERATE_MODEL_URI,
type RerankDocument,
type ILLMSession,
} from "./llm.js";
import type {
NamedCollection,
Collection,
CollectionConfig,
ContextMap,
} from "./collections.js";
// =============================================================================
// Configuration
// =============================================================================
export const DEFAULT_EMBED_MODEL = DEFAULT_EMBED_MODEL_URI;
export const DEFAULT_RERANK_MODEL = DEFAULT_RERANK_MODEL_URI;
export const DEFAULT_QUERY_MODEL = DEFAULT_GENERATE_MODEL_URI;
export const DEFAULT_GLOB = "**/*.md";
/**
* Split a collection glob mask into fast-glob patterns.
*
* `--mask "a.md,*.txt"` is a comma-separated union (issue #557), but
* fast-glob treats a comma outside `{...}` as a literal character, so
* the joined string matches nothing. Brace form `{a.md,*.txt}` is
* already valid glob syntax and is left intact.
*
* Commas inside `{...}` or `[...]` are not separators. Empty segments
* after the split are dropped.
*/
export function splitGlobMask(mask: string): string[] {
const parts: string[] = [];
let current = "";
let braceDepth = 0;
let bracketDepth = 0;
for (const ch of mask) {
if (ch === "{") {
braceDepth++;
current += ch;
} else if (ch === "}" && braceDepth > 0) {
braceDepth--;
current += ch;
} else if (ch === "[") {
bracketDepth++;
current += ch;
} else if (ch === "]" && bracketDepth > 0) {
bracketDepth--;
current += ch;
} else if (ch === "," && braceDepth === 0 && bracketDepth === 0) {
const trimmed = current.trim();
if (trimmed) parts.push(trimmed);
current = "";
} else {
current += ch;
}
}
const trimmed = current.trim();
if (trimmed) parts.push(trimmed);
return parts.length > 0 ? parts : [mask];
}
export const DEFAULT_MULTI_GET_MAX_BYTES = 64 * 1024; // 64KB
export const DEFAULT_EMBED_MAX_DOCS_PER_BATCH = 64;
export const DEFAULT_EMBED_MAX_BATCH_BYTES = 64 * 1024 * 1024; // 64MB
export const DEFAULT_EMBED_MAX_DURATION_MS = 30 * 60 * 1000; // 30 minutes; see EmbedOptions.maxDurationMs
const EMBED_FINGERPRINT_PROBE_QUERY = "__qmd_embedding_query_probe__";
const EMBED_FINGERPRINT_PROBE_TITLE = "__qmd_embedding_title_probe__";
const EMBED_FINGERPRINT_PROBE_DOC = "__qmd_embedding_document_probe__";
// 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
export function getEmbeddingFingerprint(model: string = DEFAULT_EMBED_MODEL): string {
const significant = [
`model:${model}`,
`query:${formatQueryForEmbedding(EMBED_FINGERPRINT_PROBE_QUERY, model)}`,
`doc:${formatDocForEmbedding(EMBED_FINGERPRINT_PROBE_DOC, EMBED_FINGERPRINT_PROBE_TITLE, model)}`,
`chunk_tokens:${CHUNK_SIZE_TOKENS}`,
`chunk_overlap_tokens:${CHUNK_OVERLAP_TOKENS}`,
].join("\n");
return createHash("sha256").update(significant).digest("hex").slice(0, 6);
}
/**
* 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);
}
/**
* True if `pos` sits between a UTF-16 high surrogate (at pos-1) and a low
* surrogate (at pos) — i.e. slicing at `pos` would split an astral-plane
* character (emoji, etc.) into two unpaired surrogates.
*/
function isSurrogatePairBoundary(content: string, pos: number): boolean {
if (pos <= 0 || pos >= content.length) return false;
const high = content.charCodeAt(pos - 1);
const low = content.charCodeAt(pos);
return high >= 0xd800 && high <= 0xdbff && low >= 0xdc00 && low <= 0xdfff;
}
/**
* Nudges `pos` off a surrogate-pair boundary so a slice ending or starting
* at `pos` never contains an unpaired surrogate. Prefers retreating by one
* code unit (excludes the pair from this slice, deferring it to the next
* chunk); when that would violate forward progress (`pos - 1 <= floor`,
* the caller-supplied lower bound, e.g. the previous chunk's start),
* advances by one code unit instead (includes the whole pair in this
* slice, slightly exceeding the caller's target width).
*
* Advancing is always safe: `isSurrogatePairBoundary` only returns true
* for `pos < content.length`, so `pos + 1 <= content.length`; and every
* call site already guarantees `pos > floor` before calling this function,
* so `pos + 1 > floor` too. This means a surrogate pair is never split —
* unlike a plain "give up and leave pos unchanged" fallback, which would
* let recursive re-chunking (e.g. chunkDocumentByTokens shrinking maxChars
* toward 1 for astral-dense content) reproduce the exact bug this exists
* to prevent.
*/
function adjustSurrogateBoundary(content: string, pos: number, floor: number): number {
if (!isSurrogatePairBoundary(content, pos)) return pos;
const retreat = pos - 1;
return retreat > floor ? retreat : pos + 1;
}
/**
* 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);
}
// Never slice through the middle of a surrogate pair (e.g. an emoji) —
// an unpaired surrogate in the chunk text breaks JSON serialization for
// remote embedding APIs.
endPos = adjustSurrogateBoundary(content, endPos, charPos);
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;
}
charPos = adjustSurrogateBoundary(content, charPos, lastChunkPos);
}
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 qmdHomedir();
}
/**
* 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);
}
}
/**
* True if `target` is `dir` or a descendant, after resolving symlinks.
* Used to keep indexing and qmd:// filesystem resolution inside a collection.
*/
export function isPathInsideDir(dir: string, target: string): boolean {
const realDir = getRealPath(dir);
try {
return getRelativePathFromPrefix(realpathSync(target), realDir) !== null;
} catch {
// Unreadable or dangling: realpath fails. Compare lexically so a mode-0
// file inside the collection is not treated as an escape (macOS /var vs
// /private/var). Readable out-of-tree symlinks still hit the try path.
return getRelativePathFromPrefix(resolve(target), resolve(dir)) !== null;
}
}
// =============================================================================
// Virtual Path Utilities (qmd://)
// =============================================================================
export type VirtualPath = {
collectionName: string;
path: string; // relative path within collection
indexName?: string;
};
/**
* 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);
const [pathPart = normalized, queryString = ""] = normalized.split("?");
// Match: qmd://collection-name[/optional-path]
// Allows: qmd://name, qmd://name/, qmd://name/path
const match = pathPart.match(/^qmd:\/\/([^\/]+)\/?(.*)$/);
if (!match?.[1]) return null;
const indexName = new URLSearchParams(queryString).get("index")?.trim() || undefined;
return {
collectionName: match[1],
path: match[2] ?? '', // Empty string for collection root
...(indexName ? { indexName } : {}),
};
}
/**
* Build a virtual path from collection name and relative path.
*/
export function buildVirtualPath(collectionName: string, path: string, indexName?: string): string {
const base = `qmd://${collectionName}/${path}`;
return indexName ? `${base}?index=${encodeURIComponent(indexName)}` : base;
}
/**
* 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;
const resolved = resolve(coll.pwd, parsed.path);
if (!isPathInsideDir(coll.pwd, resolved)) return null;
return resolved;
}
/**
* 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."
);
}
let _sqliteVecUnavailableReason: string | null = null;
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;
const CJK_CHAR_PATTERN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
const CJK_RUN_PATTERN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+/gu;
const FTS_CJK_NORMALIZED_VERSION = "1";
// Bump when any FTS sync trigger body in applyFtsSyncTriggers changes, so the
// new definition is reapplied to existing databases on next open.
const STORE_SCHEMA_VERSION = 1;
/**
* FTS5's unicode61 tokenizer does not segment CJK text into searchable words.
* Normalize CJK runs by spacing every character so exact CJK queries can be
* translated into phrase queries while Latin text keeps the default tokenizer.
*/
export function normalizeCjkForFTS(text: string): string {
return text.replace(CJK_RUN_PATTERN, run => ` ${Array.from(run).join(' ')} `);
}
function containsCjk(text: string): boolean {
return CJK_CHAR_PATTERN.test(text);
}
function sanitizeFTS5Phrase(phrase: string): string {
// Dotted tokens (1.0.21, 2026.4.10) are indexed as adjacent parts by the
// porter unicode61 tokenizer. Stripping the dots would produce "1021",
// which never matches — split them into phrase terms instead (#757).
return normalizeCjkForFTS(phrase)
.split(/\s+/)
.flatMap(t => {
if (isDottedToken(t)) {
return t.split('.').map(p => sanitizeFTS5Term(p)).filter(p => p);
}
const sanitized = sanitizeFTS5Term(t);
return sanitized ? [sanitized] : [];
})
.join(' ');
}
function getUserVersion(db: Database): number {
const row = db.prepare(`PRAGMA user_version`).get() as Record<string, number> | undefined;
const value = row ? Object.values(row)[0] : 0;
return typeof value === "number" ? value : Number(value) || 0;
}
// FTS sync triggers keep documents_fts current for callers that write directly
// to documents (production indexing rebuilds FTS in TypeScript to normalize CJK
// first). The bodies use DROP+CREATE rather than CREATE IF NOT EXISTS so a
// changed body propagates to existing databases. DROP and CREATE are separate
// autocommit statements, so concurrent opens of one database interleave across
// connections (A drops, B drops, A creates, B creates -> "trigger already
// exists"); busy_timeout serializes individual statements but not the pair.
// Gate the work behind PRAGMA user_version and apply it inside one IMMEDIATE
// transaction: the DROP+CREATE pair is atomic across connections, and a
// double-checked read skips it once any process has stamped the version.
function installFtsSyncTriggers(db: Database): void {
db.exec(`DROP TRIGGER IF EXISTS documents_ai`);
db.exec(`
CREATE TRIGGER 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(`DROP TRIGGER IF EXISTS documents_ad`);
db.exec(`
CREATE TRIGGER documents_ad AFTER DELETE ON documents BEGIN
DELETE FROM documents_fts WHERE rowid = old.id;
END
`);
db.exec(`DROP TRIGGER IF EXISTS documents_au`);
db.exec(`
CREATE TRIGGER 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
`);
}
function applyFtsSyncTriggers(db: Database): void {
if (getUserVersion(db) >= STORE_SCHEMA_VERSION) return;
db.exec(`BEGIN IMMEDIATE`);
try {
if (getUserVersion(db) < STORE_SCHEMA_VERSION) {
installFtsSyncTriggers(db);
db.exec(`PRAGMA user_version = ${STORE_SCHEMA_VERSION}`);
}
db.exec(`COMMIT`);
} catch (err) {
db.exec(`ROLLBACK`);
throw err;
}
}
/**
* True when documents_fts is the current standalone (filepath, title, body)
* table. Older schemas used fts5(name, body, content='documents'), and
* CREATE VIRTUAL TABLE IF NOT EXISTS will not replace them. A CJK rebuild
* then runs `DELETE FROM documents_fts`, which FTS5 compiles against the
* external content table as `SELECT T.name FROM documents AS T` — documents
* has no `name` column, so open throws `no such column: T.name` (#792).
*
* sqlite_master.sql is the usual signal, but PRAGMA table_info is the live
* virtual-table schema: a leftover `name` column with no `filepath` is never
* current, even if CREATE IF NOT EXISTS rewrote the sql text.
*/
function documentsFtsColumnNames(db: Database): string[] {
try {
const cols = db.prepare(`PRAGMA table_info(documents_fts)`).all() as { name?: string }[];
return cols.map(c => (c.name ?? "").toLowerCase()).filter(Boolean);
} catch {
return [];
}
}
function documentsFtsSchemaIsCurrent(db: Database): boolean {
const row = db.prepare(
`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'documents_fts'`
).get() as { sql?: string } | undefined | null;
const sql = (row?.sql ?? "").toLowerCase().replace(/\s+/g, "");
if (!sql.includes("filepath") || !sql.includes("title") || sql.includes("content=")) {
return false;
}
const names = new Set(documentsFtsColumnNames(db));