Repository navigation
Expand file tree
/
Copy pathdatabase.ts
More file actions
1066 lines (969 loc) · 35.4 KB
/
Copy pathdatabase.ts
File metadata and controls
1066 lines (969 loc) · 35.4 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
import path from "path";
import os from "os";
import fs from "fs";
import type {
DocumentChunk, SessionMeta, SessionSource, DatabaseConfig, QueryResult,
MessageRow, ToolCallRow, AnalyticsFilter, ToolUsageStat, MessageStat,
OverviewStats, SessionAnalytics, ModelStat,
} from "./types";
const DEFAULT_EMBEDDING_DIMENSION = 3072;
// ---------------------------------------------------------------------------
// Path resolution
// ---------------------------------------------------------------------------
/**
* Resolves the default DB path cross-platform:
* - Respects OPENCODE_MEMORY_DB_PATH env var
* - Falls back to ~/.local/share/opencode-memory/sessions.db (works on both
* macOS and Linux)
*/
export function resolveDbPath(overridePath?: string): string {
if (overridePath) {
return overridePath.replace(/^~/, os.homedir());
}
const envPath = process.env.OPENCODE_MEMORY_DB_PATH;
if (envPath) {
return envPath.replace(/^~/, os.homedir());
}
return path.join(os.homedir(), ".local", "share", "code-session-memory", "sessions.db");
}
// ---------------------------------------------------------------------------
// Database initialisation
// ---------------------------------------------------------------------------
export interface Database {
prepare: (sql: string) => Statement;
exec: (sql: string) => void;
pragma: (sql: string, opts?: { simple?: boolean }) => unknown;
close: () => void;
transaction: <T>(fn: (...args: unknown[]) => T) => (...args: unknown[]) => T;
}
export interface Statement {
run: (...args: unknown[]) => { changes: number; lastInsertRowid: number | bigint };
get: (...args: unknown[]) => unknown;
all: (...args: unknown[]) => unknown[];
}
// Lazy-loaded to avoid requiring the native module at import time (useful in tests).
let _Database: (new (path: string) => Database) | null = null;
let _sqliteVec: { load: (db: Database) => void } | null = null;
function loadDeps() {
if (!_Database) {
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
_Database = require("better-sqlite3");
// Eagerly open an in-memory DB to force the native .node file to load now,
// so a broken binary is reported here with a clear message.
new (_Database as NonNullable<typeof _Database>)(":memory:").close();
} catch (err: unknown) {
_Database = null; // reset so a restarted process starts fresh
const msg = err instanceof Error ? err.message : String(err);
// better-sqlite3 >= 12 ships Node-API prebuilt binaries inside the npm
// package, so a load failure means the install is broken (unsupported
// platform, corrupted npx cache, or Node older than the supported range).
throw new Error(
`Failed to load better-sqlite3 (Node ${process.version}, ${process.platform}-${process.arch}): ${msg}\n` +
`code-session-memory requires Node >= 22. If Node is recent, reinstall the package ` +
`(for npx: rm -rf ~/.npm/_npx, then run the command again).`,
);
}
}
if (!_sqliteVec) {
// eslint-disable-next-line @typescript-eslint/no-var-requires
_sqliteVec = require("sqlite-vec");
}
return { Database: _Database!, sqliteVec: _sqliteVec! };
}
/**
* Opens (or creates) a better-sqlite3 database with the sqlite-vec extension
* loaded. Initialises the schema if needed.
*/
export function openDatabase(config: DatabaseConfig): Database {
const { Database, sqliteVec } = loadDeps();
const { dbPath, embeddingDimension = DEFAULT_EMBEDDING_DIMENSION } = config;
// Ensure the directory exists
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
const db = new Database(dbPath);
sqliteVec.load(db);
// Performance tuning
db.pragma("journal_mode = WAL");
db.pragma("synchronous = NORMAL");
initSchema(db, embeddingDimension);
return db;
}
/**
* Columns added to `messages` after its initial release (per-model analytics).
* Kept in one place so the CREATE TABLE and the ALTER TABLE migration agree.
*/
const MESSAGES_ANALYTICS_COLUMNS: ReadonlyArray<readonly [string, string]> = [
["turn_index", "INTEGER NOT NULL DEFAULT 0"],
["model", "TEXT"],
["provider", "TEXT"],
["input_tokens", "INTEGER"],
["output_tokens", "INTEGER"],
["cache_read_tokens", "INTEGER"],
["cache_write_tokens", "INTEGER"],
["reasoning_tokens", "INTEGER"],
["cost", "REAL"],
];
/**
* Creates the schema tables if they don't already exist.
* Exported so tests can call it with an in-memory DB.
*/
export function initSchema(db: Database, embeddingDimension = DEFAULT_EMBEDDING_DIMENSION): void {
// Virtual table for vector search
db.exec(`
CREATE VIRTUAL TABLE IF NOT EXISTS vec_items USING vec0(
embedding FLOAT[${embeddingDimension}],
session_id TEXT,
session_title TEXT,
project TEXT,
heading_hierarchy TEXT,
section TEXT,
chunk_id TEXT UNIQUE,
content TEXT,
url TEXT,
hash TEXT,
chunk_index INTEGER,
total_chunks INTEGER,
message_order INTEGER,
created_at INTEGER
);
`);
// Metadata table for tracking incremental indexing progress
db.exec(`
CREATE TABLE IF NOT EXISTS sessions_meta (
session_id TEXT PRIMARY KEY,
session_title TEXT NOT NULL DEFAULT '',
project TEXT NOT NULL DEFAULT '',
source TEXT NOT NULL DEFAULT 'opencode',
last_indexed_message_id TEXT,
updated_at INTEGER NOT NULL DEFAULT 0
);
`);
// FTS5 table for keyword search (hybrid search)
db.exec(`
CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
chunk_id UNINDEXED,
content,
section UNINDEXED
);
`);
// Backfill FTS from vec_items if needed (one-time migration)
const ftsCount = db.prepare("SELECT COUNT(*) AS cnt FROM chunks_fts").get() as { cnt: number };
const vecCount = db.prepare("SELECT COUNT(*) AS cnt FROM vec_items").get() as { cnt: number };
if (ftsCount.cnt === 0 && vecCount.cnt > 0) {
db.exec(`INSERT INTO chunks_fts(chunk_id, content, section) SELECT chunk_id, content, section FROM vec_items`);
}
// Migrate existing DBs: add source column if missing
try {
db.exec(`ALTER TABLE sessions_meta ADD COLUMN source TEXT NOT NULL DEFAULT 'opencode'`);
} catch {
// Column already exists — ignore
}
// Migrate existing DBs: add transcript_path column if missing
try {
db.exec(`ALTER TABLE sessions_meta ADD COLUMN transcript_path TEXT`);
} catch {
// Column already exists — ignore
}
// Structured analytics tables
db.exec(`
CREATE TABLE IF NOT EXISTS messages (
id TEXT NOT NULL,
session_id TEXT NOT NULL,
role TEXT NOT NULL,
created_at INTEGER,
text_length INTEGER NOT NULL DEFAULT 0,
part_count INTEGER NOT NULL DEFAULT 0,
tool_call_count INTEGER NOT NULL DEFAULT 0,
message_order INTEGER NOT NULL DEFAULT 0,
indexed_at INTEGER NOT NULL,
PRIMARY KEY (session_id, id)
);
`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id)`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_messages_role ON messages(role)`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_messages_created ON messages(created_at)`);
// Migrate existing DBs: per-model analytics columns (model + token usage).
// Each ALTER is idempotent: it throws "duplicate column" when already present.
for (const [column, type] of MESSAGES_ANALYTICS_COLUMNS) {
try {
db.exec(`ALTER TABLE messages ADD COLUMN ${column} ${type}`);
} catch {
// Column already exists — ignore
}
}
db.exec(`CREATE INDEX IF NOT EXISTS idx_messages_model ON messages(model)`);
db.exec(`
CREATE TABLE IF NOT EXISTS tool_calls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
message_id TEXT NOT NULL,
session_id TEXT NOT NULL,
tool_name TEXT NOT NULL,
tool_call_id TEXT,
status TEXT,
has_error INTEGER NOT NULL DEFAULT 0,
args_length INTEGER NOT NULL DEFAULT 0,
result_length INTEGER NOT NULL DEFAULT 0,
created_at INTEGER,
indexed_at INTEGER NOT NULL
);
`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_tool_calls_session ON tool_calls(session_id)`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_tool_calls_name ON tool_calls(tool_name)`);
db.exec(`CREATE INDEX IF NOT EXISTS idx_tool_calls_message ON tool_calls(session_id, message_id)`);
}
// ---------------------------------------------------------------------------
// Session meta CRUD
// ---------------------------------------------------------------------------
export function getSessionMeta(db: Database, sessionId: string): SessionMeta | null {
const row = db
.prepare("SELECT * FROM sessions_meta WHERE session_id = ?")
.get(sessionId) as SessionMeta | undefined;
return row ?? null;
}
export function upsertSessionMeta(db: Database, meta: SessionMeta): void {
db.prepare(`
INSERT INTO sessions_meta (session_id, session_title, project, source, last_indexed_message_id, updated_at, transcript_path)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(session_id) DO UPDATE SET
session_title = excluded.session_title,
project = excluded.project,
source = excluded.source,
last_indexed_message_id = excluded.last_indexed_message_id,
updated_at = excluded.updated_at,
transcript_path = COALESCE(excluded.transcript_path, sessions_meta.transcript_path)
`).run(
meta.session_id,
meta.session_title,
meta.project,
meta.source,
meta.last_indexed_message_id,
meta.updated_at,
meta.transcript_path ?? null,
);
}
// ---------------------------------------------------------------------------
// Vector insertion
// ---------------------------------------------------------------------------
/**
* Inserts a batch of chunks + their embeddings inside a single transaction.
* Chunks with duplicate chunk_ids are silently skipped (IGNORE conflict).
*/
export function insertChunks(
db: Database,
chunks: DocumentChunk[],
embeddings: number[][],
): void {
if (chunks.length !== embeddings.length) {
throw new Error(
`Mismatch: ${chunks.length} chunks but ${embeddings.length} embeddings`,
);
}
if (chunks.length === 0) return;
const insert = db.prepare(`
INSERT INTO vec_items (
embedding, session_id, session_title, project,
heading_hierarchy, section, chunk_id, content, url, hash,
chunk_index, total_chunks, message_order, created_at
) VALUES (
?, ?, ?, ?,
?, ?, ?, ?, ?, ?,
?, ?, ?, ?
)
`);
const insertFts = db.prepare(`
INSERT INTO chunks_fts(chunk_id, content, section) VALUES (?, ?, ?)
`);
// sqlite-vec does not enforce UNIQUE constraints via INSERT OR IGNORE on
// virtual tables, so we check for existence first.
const exists = db.prepare(
"SELECT 1 FROM vec_items WHERE chunk_id = ? LIMIT 1",
);
const insertMany = db.transaction((...args: unknown[]) => {
const rows = args[0] as Array<{ chunk: DocumentChunk; embedding: number[] }>;
for (const { chunk, embedding } of rows) {
const { metadata: m } = chunk;
// Skip if chunk already exists (idempotent indexing)
if (exists.get(m.chunk_id)) continue;
insert.run(
new Float32Array(embedding),
m.session_id,
m.session_title,
m.project,
JSON.stringify(m.heading_hierarchy),
m.section,
m.chunk_id,
chunk.content,
m.url,
m.hash,
BigInt(m.chunk_index),
BigInt(m.total_chunks),
BigInt(m.message_order ?? 0),
BigInt(m.created_at ?? Date.now()),
);
insertFts.run(m.chunk_id, chunk.content, m.section);
}
});
insertMany(chunks.map((chunk, i) => ({ chunk, embedding: embeddings[i] })));
}
// ---------------------------------------------------------------------------
// Structured analytics insertion
// ---------------------------------------------------------------------------
/**
* Batch-upserts message rows. Existing (session_id, id) pairs get their
* analytics columns refreshed (idempotent for incremental indexing). The
* indexer re-extracts every message of a session on each run, so rows written
* before the per-model columns existed are backfilled the next time the
* session is indexed. `indexed_at` keeps its original value.
*/
export function insertMessages(db: Database, rows: MessageRow[]): void {
if (rows.length === 0) return;
const stmt = db.prepare(`
INSERT INTO messages
(id, session_id, role, created_at, text_length, part_count,
tool_call_count, message_order, indexed_at, turn_index, model, provider,
input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
reasoning_tokens, cost)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(session_id, id) DO UPDATE SET
role = excluded.role,
created_at = excluded.created_at,
text_length = excluded.text_length,
part_count = excluded.part_count,
tool_call_count = excluded.tool_call_count,
message_order = excluded.message_order,
turn_index = excluded.turn_index,
model = excluded.model,
provider = excluded.provider,
input_tokens = excluded.input_tokens,
output_tokens = excluded.output_tokens,
cache_read_tokens = excluded.cache_read_tokens,
cache_write_tokens = excluded.cache_write_tokens,
reasoning_tokens = excluded.reasoning_tokens,
cost = excluded.cost
`);
const insertMany = db.transaction((...args: unknown[]) => {
const items = args[0] as MessageRow[];
for (const r of items) {
stmt.run(
r.id, r.session_id, r.role, r.created_at,
r.text_length, r.part_count, r.tool_call_count,
r.message_order, r.indexed_at, r.turn_index, r.model, r.provider,
r.input_tokens, r.output_tokens, r.cache_read_tokens, r.cache_write_tokens,
r.reasoning_tokens, r.cost,
);
}
});
insertMany(rows);
}
/**
* Batch-inserts tool call rows.
*/
export function insertToolCalls(db: Database, rows: ToolCallRow[]): void {
if (rows.length === 0) return;
const stmt = db.prepare(`
INSERT INTO tool_calls
(message_id, session_id, tool_name, tool_call_id, status, has_error,
args_length, result_length, created_at, indexed_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
const insertMany = db.transaction((...args: unknown[]) => {
const items = args[0] as ToolCallRow[];
for (const r of items) {
stmt.run(
r.message_id, r.session_id, r.tool_name, r.tool_call_id,
r.status, r.has_error, r.args_length, r.result_length,
r.created_at, r.indexed_at,
);
}
});
insertMany(rows);
}
// ---------------------------------------------------------------------------
// Query helpers (used by MCP server)
// ---------------------------------------------------------------------------
export interface SectionFilterOptions {
/** Single prefix (backward compat). Matches LOWER(section) LIKE prefix%. */
sectionFilter?: string;
/** Include only chunks whose section matches one of these prefixes. */
includeSections?: string[];
/** Exclude chunks whose section matches any of these prefixes. */
excludeSections?: string[];
}
function appendSectionFilters(
sql: string,
params: unknown[],
col: string,
opts: SectionFilterOptions,
): string {
if (opts.sectionFilter) {
sql += ` AND LOWER(${col}) LIKE ?`;
params.push(opts.sectionFilter.toLowerCase() + "%");
}
if (opts.includeSections && opts.includeSections.length > 0) {
const clauses = opts.includeSections.map(() => `LOWER(${col}) LIKE ?`);
sql += ` AND (${clauses.join(" OR ")})`;
for (const prefix of opts.includeSections) {
params.push(prefix.toLowerCase() + "%");
}
}
if (opts.excludeSections && opts.excludeSections.length > 0) {
for (const prefix of opts.excludeSections) {
sql += ` AND LOWER(${col}) NOT LIKE ?`;
params.push(prefix.toLowerCase() + "%");
}
}
return sql;
}
export function queryByEmbedding(
db: Database,
queryEmbedding: number[],
topK = 10,
projectFilter?: string,
sourceFilter?: SessionSource,
fromMs?: number,
toMs?: number,
sectionFilter?: string,
sectionOpts?: SectionFilterOptions,
): QueryResult[] {
// sqlite-vec requires the LIMIT (k) constraint to be part of the KNN WHERE
// clause. We use a CTE to perform the KNN first, then join sessions_meta for
// the source column and apply optional post-filters.
// When section filters are active, over-fetch from KNN so that after post-
// filtering we still have enough results to fill the requested topK.
const hasSectionFilter = !!(sectionFilter || sectionOpts?.includeSections?.length || sectionOpts?.excludeSections?.length);
const knnK = hasSectionFilter ? topK * 5 : topK;
let sql = `
WITH knn AS (
SELECT
chunk_id, content, url, section, heading_hierarchy,
chunk_index, total_chunks, session_id, session_title, project,
distance, created_at
FROM vec_items
WHERE embedding MATCH ?
AND k = ?
)
SELECT knn.*, m.source
FROM knn
LEFT JOIN sessions_meta m ON knn.session_id = m.session_id
WHERE 1=1
`;
const params: unknown[] = [new Float32Array(queryEmbedding), knnK];
if (projectFilter) {
sql += " AND knn.project = ?";
params.push(projectFilter);
}
if (sourceFilter) {
sql += " AND m.source = ?";
params.push(sourceFilter);
}
if (typeof fromMs === "number") {
sql += " AND knn.created_at >= ?";
params.push(BigInt(fromMs));
}
if (typeof toMs === "number") {
sql += " AND knn.created_at <= ?";
params.push(BigInt(toMs));
}
// Section filtering (backward compat single prefix + new multi-prefix options)
sql = appendSectionFilters(sql, params, "knn.section", { sectionFilter, ...sectionOpts });
sql += " ORDER BY distance";
let rows = db.prepare(sql).all(...params) as QueryResult[];
// Strip raw embedding bytes from results
rows.forEach((r: unknown) => {
if (r && typeof r === "object") delete (r as Record<string, unknown>)["embedding"];
});
// Truncate to requested topK after post-filtering
if (rows.length > topK) rows = rows.slice(0, topK);
return rows;
}
/**
* Full-text keyword search using FTS5 with BM25 ranking.
* Falls back to empty results if the FTS table is empty.
*/
export function queryByKeyword(
db: Database,
queryText: string,
topK = 10,
projectFilter?: string,
sourceFilter?: SessionSource,
fromMs?: number,
toMs?: number,
sectionFilter?: string,
sectionOpts?: SectionFilterOptions,
): QueryResult[] {
// Escape FTS5 special characters and wrap terms for prefix matching
const sanitized = queryText.replace(/['"*(){}[\]:^~!\\]/g, " ").trim();
if (!sanitized) return [];
let sql = `
SELECT
v.chunk_id, v.content, v.url, v.section, v.heading_hierarchy,
v.chunk_index, v.total_chunks, v.session_id, v.session_title, v.project,
v.created_at, m.source,
bm25(chunks_fts) AS rank
FROM chunks_fts f
JOIN vec_items v ON f.chunk_id = v.chunk_id
LEFT JOIN sessions_meta m ON v.session_id = m.session_id
WHERE chunks_fts MATCH ?
`;
const params: unknown[] = [sanitized];
if (projectFilter) {
sql += " AND v.project = ?";
params.push(projectFilter);
}
if (sourceFilter) {
sql += " AND m.source = ?";
params.push(sourceFilter);
}
if (typeof fromMs === "number") {
sql += " AND v.created_at >= ?";
params.push(BigInt(fromMs));
}
if (typeof toMs === "number") {
sql += " AND v.created_at <= ?";
params.push(BigInt(toMs));
}
sql = appendSectionFilters(sql, params, "v.section", { sectionFilter, ...sectionOpts });
sql += ` ORDER BY rank LIMIT ?`;
params.push(topK);
try {
const rows = db.prepare(sql).all(...params) as QueryResult[];
rows.forEach((r: unknown) => {
if (r && typeof r === "object") {
delete (r as Record<string, unknown>)["embedding"];
delete (r as Record<string, unknown>)["rank"];
}
});
return rows;
} catch {
// FTS table might be empty or query might be invalid
return [];
}
}
/**
* Hybrid search: runs both vector and keyword search, merges results
* using Reciprocal Rank Fusion (RRF).
*/
export function queryHybrid(
db: Database,
queryEmbedding: number[],
queryText: string,
topK = 10,
projectFilter?: string,
sourceFilter?: SessionSource,
fromMs?: number,
toMs?: number,
sectionFilter?: string,
sectionOpts?: SectionFilterOptions,
): QueryResult[] {
const overFetch = topK * 3;
const vectorResults = queryByEmbedding(
db, queryEmbedding, overFetch, projectFilter, sourceFilter, fromMs, toMs, sectionFilter, sectionOpts,
);
const keywordResults = queryByKeyword(
db, queryText, overFetch, projectFilter, sourceFilter, fromMs, toMs, sectionFilter, sectionOpts,
);
// RRF constant (standard value)
const K = 60;
// Build score map by chunk_id
const scores = new Map<string, { score: number; result: QueryResult }>();
for (let i = 0; i < vectorResults.length; i++) {
const r = vectorResults[i];
const rrfScore = 1 / (K + i + 1);
scores.set(r.chunk_id, { score: rrfScore, result: r });
}
for (let i = 0; i < keywordResults.length; i++) {
const r = keywordResults[i];
const rrfScore = 1 / (K + i + 1);
const existing = scores.get(r.chunk_id);
if (existing) {
existing.score += rrfScore;
} else {
scores.set(r.chunk_id, { score: rrfScore, result: r });
}
}
// Sort by combined RRF score descending, take topK
return Array.from(scores.values())
.sort((a, b) => b.score - a.score)
.slice(0, topK)
.map((entry) => entry.result);
}
export function getChunksByUrl(
db: Database,
url: string,
startIndex?: number,
endIndex?: number,
): QueryResult[] {
let sql = `
SELECT chunk_id, content, url, section, heading_hierarchy, chunk_index, total_chunks
FROM vec_items
WHERE url = ?
`;
const params: unknown[] = [url];
if (typeof startIndex === "number") {
sql += " AND chunk_index >= ?";
params.push(startIndex);
}
if (typeof endIndex === "number") {
sql += " AND chunk_index <= ?";
params.push(endIndex);
}
sql += " ORDER BY chunk_index";
return db.prepare(sql).all(...params) as QueryResult[];
}
/**
* Fetches a window of chunks around a target chunk within the same session.
* Orders all session chunks by created_at + chunk_index, finds the target,
* and returns `window` chunks before and after it.
*/
export function getSessionContext(
db: Database,
sessionId: string,
chunkId: string,
windowSize = 1,
): QueryResult[] {
// Get all chunks for the session, ordered chronologically
const allChunks = db.prepare(`
SELECT chunk_id, content, url, section, heading_hierarchy,
chunk_index, total_chunks, created_at
FROM vec_items
WHERE session_id = ?
ORDER BY created_at, chunk_index
`).all(sessionId) as QueryResult[];
const targetIdx = allChunks.findIndex((c) => c.chunk_id === chunkId);
if (targetIdx === -1) return [];
const start = Math.max(0, targetIdx - windowSize);
const end = Math.min(allChunks.length - 1, targetIdx + windowSize);
return allChunks.slice(start, end + 1);
}
/**
* Lists all session URLs stored in the DB (for "get_session_chunks" calls that
* pass a session_id instead of a full URL).
*/
export function listSessionUrls(db: Database, sessionId: string): string[] {
const rows = db
.prepare("SELECT DISTINCT url FROM vec_items WHERE session_id = ? ORDER BY url")
.all(sessionId) as Array<{ url: string }>;
return rows.map((r) => r.url);
}
// ---------------------------------------------------------------------------
// Session browser helpers
// ---------------------------------------------------------------------------
export interface SessionRow extends SessionMeta {
chunk_count: number;
}
export interface SessionFilter {
source?: SessionSource;
fromDate?: number; // unix timestamp (seconds)
toDate?: number; // unix timestamp (seconds)
}
/**
* Returns all sessions from sessions_meta enriched with their chunk count,
* ordered by updated_at DESC.
*/
export function listSessions(db: Database, filter: SessionFilter = {}): SessionRow[] {
let sql = `
SELECT
m.session_id,
m.session_title,
m.project,
m.source,
m.last_indexed_message_id,
m.updated_at,
COUNT(v.chunk_id) AS chunk_count
FROM sessions_meta m
LEFT JOIN vec_items v ON v.session_id = m.session_id
WHERE 1=1
`;
const params: unknown[] = [];
if (filter.source) {
sql += " AND m.source = ?";
params.push(filter.source);
}
if (typeof filter.fromDate === "number") {
sql += " AND m.updated_at >= ?";
params.push(filter.fromDate);
}
if (typeof filter.toDate === "number") {
sql += " AND m.updated_at <= ?";
params.push(filter.toDate);
}
sql += " GROUP BY m.session_id ORDER BY m.updated_at DESC";
return db.prepare(sql).all(...params) as SessionRow[];
}
export interface ChunkRow {
chunk_id: string;
chunk_index: number;
total_chunks: number;
section: string;
heading_hierarchy: string; // JSON-encoded string[]
content: string;
url: string;
}
/**
* Returns all chunks for a session ordered by message_order ASC, chunk_index ASC.
* message_order is the 0-based position of the message within the session at
* index time — stable and source-agnostic (works for OpenCode, Claude Code,
* and Cursor whose message IDs are not guaranteed to sort chronologically).
*/
export function getSessionChunksOrdered(db: Database, sessionId: string): ChunkRow[] {
return db.prepare(`
SELECT chunk_id, chunk_index, total_chunks, section, heading_hierarchy, content, url
FROM vec_items
WHERE session_id = ?
ORDER BY message_order ASC, chunk_index ASC
`).all(sessionId) as ChunkRow[];
}
/**
* Deletes a session's chunks and metadata inside a single transaction.
* Returns the number of chunks deleted.
*/
export function deleteSession(db: Database, sessionId: string): number {
const selectChunkIds = db.prepare("SELECT chunk_id FROM vec_items WHERE session_id = ?");
const deleteChunks = db.prepare("DELETE FROM vec_items WHERE session_id = ?");
const deleteFts = db.prepare("DELETE FROM chunks_fts WHERE chunk_id = ?");
const deleteMeta = db.prepare("DELETE FROM sessions_meta WHERE session_id = ?");
const deleteMessages = db.prepare("DELETE FROM messages WHERE session_id = ?");
const deleteToolCalls = db.prepare("DELETE FROM tool_calls WHERE session_id = ?");
let chunkCount = 0;
db.transaction(() => {
const chunkIds = selectChunkIds.all(sessionId) as Array<{ chunk_id: string }>;
for (const { chunk_id } of chunkIds) {
deleteFts.run(chunk_id);
}
const result = deleteChunks.run(sessionId);
chunkCount = result.changes;
deleteToolCalls.run(sessionId);
deleteMessages.run(sessionId);
deleteMeta.run(sessionId);
})();
return chunkCount;
}
/**
* Deletes all sessions last updated before `olderThanMs` (unix milliseconds).
* Returns the number of sessions and chunks removed.
*/
export function deleteSessionsOlderThan(
db: Database,
olderThanMs: number,
): { sessions: number; chunks: number } {
const candidates = listSessions(db, { toDate: olderThanMs });
if (candidates.length === 0) return { sessions: 0, chunks: 0 };
const selectChunkIds = db.prepare("SELECT chunk_id FROM vec_items WHERE session_id = ?");
const deleteChunks = db.prepare("DELETE FROM vec_items WHERE session_id = ?");
const deleteFts = db.prepare("DELETE FROM chunks_fts WHERE chunk_id = ?");
const deleteMeta = db.prepare("DELETE FROM sessions_meta WHERE session_id = ?");
const deleteMessages = db.prepare("DELETE FROM messages WHERE session_id = ?");
const deleteToolCalls = db.prepare("DELETE FROM tool_calls WHERE session_id = ?");
let totalChunks = 0;
db.transaction(() => {
for (const s of candidates) {
const chunkIds = selectChunkIds.all(s.session_id) as Array<{ chunk_id: string }>;
for (const { chunk_id } of chunkIds) {
deleteFts.run(chunk_id);
}
const result = deleteChunks.run(s.session_id);
totalChunks += result.changes;
deleteToolCalls.run(s.session_id);
deleteMessages.run(s.session_id);
deleteMeta.run(s.session_id);
}
})();
return { sessions: candidates.length, chunks: totalChunks };
}
// ---------------------------------------------------------------------------
// Analytics queries
// ---------------------------------------------------------------------------
function buildAnalyticsWhere(
filter: AnalyticsFilter | undefined,
tableAlias: string,
metaAlias: string,
): { clauses: string; params: unknown[] } {
const clauses: string[] = [];
const params: unknown[] = [];
if (filter?.source) {
clauses.push(`${metaAlias}.source = ?`);
params.push(filter.source);
}
if (filter?.project) {
clauses.push(`${metaAlias}.project = ?`);
params.push(filter.project);
}
if (typeof filter?.fromMs === "number") {
clauses.push(`${tableAlias}.created_at >= ?`);
params.push(filter.fromMs);
}
if (typeof filter?.toMs === "number") {
clauses.push(`${tableAlias}.created_at <= ?`);
params.push(filter.toMs);
}
return {
clauses: clauses.length > 0 ? " AND " + clauses.join(" AND ") : "",
params,
};
}
/**
* Returns tool usage stats: call count, error count, and distinct session count per tool.
*/
export function getToolUsageStats(
db: Database,
filter?: AnalyticsFilter,
): ToolUsageStat[] {
const { clauses, params } = buildAnalyticsWhere(filter, "t", "m");
return db.prepare(`
SELECT
t.tool_name,
COUNT(*) AS call_count,
SUM(t.has_error) AS error_count,
COUNT(DISTINCT t.session_id) AS session_count
FROM tool_calls t
JOIN sessions_meta m ON t.session_id = m.session_id
WHERE 1=1${clauses}
GROUP BY t.tool_name
ORDER BY call_count DESC
`).all(...params) as ToolUsageStat[];
}
/**
* Returns message counts grouped by role.
*/
export function getMessageStats(
db: Database,
filter?: AnalyticsFilter,
): MessageStat[] {
const { clauses, params } = buildAnalyticsWhere(filter, "msg", "m");
return db.prepare(`
SELECT
msg.role,
COUNT(*) AS count
FROM messages msg
JOIN sessions_meta m ON msg.session_id = m.session_id
WHERE 1=1${clauses}
GROUP BY msg.role
ORDER BY count DESC
`).all(...params) as MessageStat[];
}
/**
* Returns per-model statistics over assistant messages that carry a model.
* A turn that involved several models is counted once for each of them.
*/
export function getModelStats(
db: Database,
filter?: AnalyticsFilter,
): ModelStat[] {
const { clauses, params } = buildAnalyticsWhere(filter, "msg", "m");
return db.prepare(`
SELECT
msg.model,
MAX(msg.provider) AS provider,
GROUP_CONCAT(DISTINCT m.source) AS sources,
COUNT(*) AS message_count,
COUNT(DISTINCT msg.session_id || ':' || msg.turn_index) AS turn_count,
COUNT(DISTINCT msg.session_id) AS session_count,
COALESCE(SUM(msg.tool_call_count), 0) AS tool_call_count,
SUM(CASE WHEN msg.input_tokens IS NOT NULL
OR msg.output_tokens IS NOT NULL THEN 1 ELSE 0 END) AS messages_with_tokens,
COALESCE(SUM(msg.input_tokens), 0) AS input_tokens,
COALESCE(SUM(msg.output_tokens), 0) AS output_tokens,
COALESCE(SUM(msg.cache_read_tokens), 0) AS cache_read_tokens,
COALESCE(SUM(msg.cache_write_tokens), 0) AS cache_write_tokens,
COALESCE(SUM(msg.reasoning_tokens), 0) AS reasoning_tokens,
SUM(msg.cost) AS cost
FROM messages msg
JOIN sessions_meta m ON msg.session_id = m.session_id
WHERE msg.role = 'assistant' AND msg.model IS NOT NULL${clauses}
GROUP BY msg.model
ORDER BY message_count DESC
`).all(...params) as ModelStat[];
}
/**
* Returns aggregate overview stats across all indexed structured data.
*/
export function getOverviewStats(
db: Database,
filter?: AnalyticsFilter,
): OverviewStats {
const { clauses: msgClauses, params: msgParams } = buildAnalyticsWhere(filter, "msg", "m");
const msgStats = db.prepare(`
SELECT
COUNT(DISTINCT msg.session_id) AS total_sessions,
COUNT(*) AS total_messages,
MIN(msg.created_at) AS earliest_message_at,
MAX(msg.created_at) AS latest_message_at
FROM messages msg
JOIN sessions_meta m ON msg.session_id = m.session_id
WHERE 1=1${msgClauses}
`).get(...msgParams) as {
total_sessions: number;
total_messages: number;
earliest_message_at: number | null;
latest_message_at: number | null;
};
const { clauses: tcClauses, params: tcParams } = buildAnalyticsWhere(filter, "t", "m");
const tcStats = db.prepare(`
SELECT COUNT(*) AS total_tool_calls
FROM tool_calls t
JOIN sessions_meta m ON t.session_id = m.session_id
WHERE 1=1${tcClauses}
`).get(...tcParams) as { total_tool_calls: number };
return {
total_sessions: msgStats.total_sessions,
total_messages: msgStats.total_messages,