antigravity-plugin-context-mode 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/LICENSE +21 -0
- package/README.md +184 -2
- package/assets/icon.svg +20 -0
- package/hooks/pre-tool-use.js +141 -0
- package/hooks/session-start.js +35 -0
- package/hooks.json +23 -0
- package/lib/executor.js +221 -0
- package/lib/store.js +565 -0
- package/lib/tools.js +339 -0
- package/mcp_config.json +8 -0
- package/package.json +55 -4
- package/plugin.json +18 -0
- package/rules/AGENTS.md +8 -0
- package/server.js +262 -0
- package/skills/context-mode/SKILL.md +84 -0
package/lib/store.js
ADDED
|
@@ -0,0 +1,565 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import { DatabaseSync } from "node:sqlite";
|
|
5
|
+
|
|
6
|
+
export const MAX_CHUNK_BYTES = 4096;
|
|
7
|
+
export const SNIPPET_MAX_BYTES = 800;
|
|
8
|
+
export const RRF_K = 60;
|
|
9
|
+
export const STATE_BUDGET = 2048;
|
|
10
|
+
|
|
11
|
+
/** Default path to context database (~/.context-mode/context.db) */
|
|
12
|
+
export function getDefaultDbPath() {
|
|
13
|
+
const dir = path.join(os.homedir(), ".context-mode");
|
|
14
|
+
return path.join(dir, "context.db");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Sanitize an input query string for safe FTS5 queries */
|
|
18
|
+
export function sanitizeFtsQuery(query) {
|
|
19
|
+
if (!query || typeof query !== "string") return "";
|
|
20
|
+
const cleaned = query.trim().replace(/[\x00-\x1f]/g, " ");
|
|
21
|
+
const tokens = cleaned.match(/[a-zA-Z0-9_\u0080-\uffff]+/g);
|
|
22
|
+
if (!tokens || tokens.length === 0) return "";
|
|
23
|
+
return tokens.map((t) => `"${t.replace(/"/g, '""')}"`).join(" ");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Sanitize query specifically for trigram index (must have at least 3 characters) */
|
|
27
|
+
export function sanitizeTrigramQuery(query) {
|
|
28
|
+
if (!query || typeof query !== "string") return "";
|
|
29
|
+
const tokens = query.match(/[a-zA-Z0-9_\u0080-\uffff]{3,}/g);
|
|
30
|
+
if (!tokens || tokens.length === 0) return "";
|
|
31
|
+
return tokens.map((t) => `"${t.replace(/"/g, '""')}"`).join(" ");
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export class ContextModeStore {
|
|
35
|
+
constructor(optionsOrDbPath) {
|
|
36
|
+
if (typeof optionsOrDbPath === "string" && optionsOrDbPath.trim()) {
|
|
37
|
+
this.dbPath = optionsOrDbPath.trim();
|
|
38
|
+
} else if (optionsOrDbPath && typeof optionsOrDbPath.dbPath === "string" && optionsOrDbPath.dbPath.trim()) {
|
|
39
|
+
this.dbPath = optionsOrDbPath.dbPath.trim();
|
|
40
|
+
} else {
|
|
41
|
+
this.dbPath = getDefaultDbPath();
|
|
42
|
+
}
|
|
43
|
+
this.db = null;
|
|
44
|
+
this.sourceCounter = 0;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Open or initialize SQLite database */
|
|
48
|
+
open() {
|
|
49
|
+
if (this.db) return this.db;
|
|
50
|
+
const dbDir = path.dirname(this.dbPath);
|
|
51
|
+
if (!fs.existsSync(dbDir)) {
|
|
52
|
+
fs.mkdirSync(dbDir, { recursive: true });
|
|
53
|
+
}
|
|
54
|
+
this.db = new DatabaseSync(this.dbPath);
|
|
55
|
+
this.initSchema();
|
|
56
|
+
return this.db;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
close() {
|
|
60
|
+
if (this.db) {
|
|
61
|
+
try {
|
|
62
|
+
this.db.close();
|
|
63
|
+
} catch {
|
|
64
|
+
// ignore close error
|
|
65
|
+
}
|
|
66
|
+
this.db = null;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Initialize tables, FTS5 virtual tables, and indexes */
|
|
71
|
+
initSchema() {
|
|
72
|
+
if (!this.db) return;
|
|
73
|
+
this.db.exec("PRAGMA journal_mode = WAL;");
|
|
74
|
+
this.db.exec("PRAGMA synchronous = NORMAL;");
|
|
75
|
+
|
|
76
|
+
// Standard tables
|
|
77
|
+
this.db.exec(`
|
|
78
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
79
|
+
key TEXT PRIMARY KEY,
|
|
80
|
+
value TEXT NOT NULL
|
|
81
|
+
);
|
|
82
|
+
|
|
83
|
+
CREATE TABLE IF NOT EXISTS sources (
|
|
84
|
+
id TEXT PRIMARY KEY,
|
|
85
|
+
session_id TEXT NOT NULL,
|
|
86
|
+
worktree TEXT NOT NULL,
|
|
87
|
+
agent TEXT NOT NULL,
|
|
88
|
+
kind TEXT NOT NULL,
|
|
89
|
+
label TEXT NOT NULL,
|
|
90
|
+
bytes_total INTEGER NOT NULL DEFAULT 0,
|
|
91
|
+
chunk_count INTEGER NOT NULL DEFAULT 0,
|
|
92
|
+
created_ts INTEGER NOT NULL,
|
|
93
|
+
created_at TEXT NOT NULL,
|
|
94
|
+
accessed_ts INTEGER NOT NULL
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
CREATE INDEX IF NOT EXISTS idx_sources_session ON sources(session_id);
|
|
98
|
+
CREATE INDEX IF NOT EXISTS idx_sources_worktree ON sources(worktree);
|
|
99
|
+
|
|
100
|
+
CREATE TABLE IF NOT EXISTS events (
|
|
101
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
102
|
+
session_id TEXT NOT NULL,
|
|
103
|
+
worktree TEXT NOT NULL,
|
|
104
|
+
agent TEXT NOT NULL,
|
|
105
|
+
kind TEXT NOT NULL,
|
|
106
|
+
tool TEXT,
|
|
107
|
+
key TEXT,
|
|
108
|
+
path TEXT,
|
|
109
|
+
ok INTEGER NOT NULL DEFAULT 1,
|
|
110
|
+
exit_code INTEGER,
|
|
111
|
+
bytes INTEGER NOT NULL DEFAULT 0,
|
|
112
|
+
body TEXT,
|
|
113
|
+
turn INTEGER NOT NULL DEFAULT 0,
|
|
114
|
+
sandbox_bytes INTEGER NOT NULL DEFAULT 0,
|
|
115
|
+
returned_bytes INTEGER NOT NULL DEFAULT 0,
|
|
116
|
+
created_at TEXT NOT NULL,
|
|
117
|
+
accessed_at TEXT
|
|
118
|
+
);
|
|
119
|
+
|
|
120
|
+
CREATE INDEX IF NOT EXISTS idx_events_session ON events(session_id);
|
|
121
|
+
CREATE INDEX IF NOT EXISTS idx_events_turn ON events(session_id, turn);
|
|
122
|
+
`);
|
|
123
|
+
|
|
124
|
+
// Virtual FTS5 tables
|
|
125
|
+
this.db.exec(`
|
|
126
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS chunks USING fts5(
|
|
127
|
+
source_id UNINDEXED,
|
|
128
|
+
session_id UNINDEXED,
|
|
129
|
+
worktree UNINDEXED,
|
|
130
|
+
agent UNINDEXED,
|
|
131
|
+
ord UNINDEXED,
|
|
132
|
+
body,
|
|
133
|
+
title,
|
|
134
|
+
tokenize = 'porter unicode61 remove_diacritics 2'
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS chunks_tri USING fts5(
|
|
138
|
+
source_id UNINDEXED,
|
|
139
|
+
session_id UNINDEXED,
|
|
140
|
+
ord UNINDEXED,
|
|
141
|
+
body,
|
|
142
|
+
tokenize = 'trigram'
|
|
143
|
+
);
|
|
144
|
+
`);
|
|
145
|
+
|
|
146
|
+
const versionRow = this.db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get();
|
|
147
|
+
if (!versionRow) {
|
|
148
|
+
this.db.prepare("INSERT INTO meta(key, value) VALUES ('schema_version', '2')").run();
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Split content into chunks by byte budget on newline boundaries */
|
|
153
|
+
chunkContent(text, maxBytes = MAX_CHUNK_BYTES) {
|
|
154
|
+
if (!text) return [];
|
|
155
|
+
const chunks = [];
|
|
156
|
+
const lines = text.split("\n");
|
|
157
|
+
let currentChunk = [];
|
|
158
|
+
let currentBytes = 0;
|
|
159
|
+
|
|
160
|
+
for (let i = 0; i < lines.length; i++) {
|
|
161
|
+
const line = lines[i];
|
|
162
|
+
const lineBytes = Buffer.byteLength(line, "utf8") + 1;
|
|
163
|
+
|
|
164
|
+
if (currentBytes + lineBytes > maxBytes && currentChunk.length > 0) {
|
|
165
|
+
chunks.push(currentChunk.join("\n"));
|
|
166
|
+
currentChunk = [line];
|
|
167
|
+
currentBytes = lineBytes;
|
|
168
|
+
} else {
|
|
169
|
+
currentChunk.push(line);
|
|
170
|
+
currentBytes += lineBytes;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (currentChunk.length > 0) {
|
|
175
|
+
chunks.push(currentChunk.join("\n"));
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
return chunks;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Index a text, file output, or tool response into SQLite FTS5 */
|
|
182
|
+
indexContent({ sessionId, worktree, agent, kind, label, content, sourceId }) {
|
|
183
|
+
this.open();
|
|
184
|
+
const sid = sessionId || "default";
|
|
185
|
+
const wt = worktree || process.cwd();
|
|
186
|
+
const ag = agent || "antigravity";
|
|
187
|
+
const k = kind || "content";
|
|
188
|
+
const lbl = label || "untitled";
|
|
189
|
+
const rawText = typeof content === "string" ? content : String(content || "");
|
|
190
|
+
const totalBytes = Buffer.byteLength(rawText, "utf8");
|
|
191
|
+
|
|
192
|
+
const id = sourceId || `s_${Date.now()}_${(++this.sourceCounter).toString(36)}`;
|
|
193
|
+
const now = Date.now();
|
|
194
|
+
const isoDate = new Date(now).toISOString();
|
|
195
|
+
|
|
196
|
+
const chunks = this.chunkContent(rawText);
|
|
197
|
+
const chunkCount = chunks.length;
|
|
198
|
+
|
|
199
|
+
const insertSource = this.db.prepare(`
|
|
200
|
+
INSERT OR REPLACE INTO sources (
|
|
201
|
+
id, session_id, worktree, agent, kind, label, bytes_total, chunk_count, created_ts, created_at, accessed_ts
|
|
202
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
203
|
+
`);
|
|
204
|
+
|
|
205
|
+
const insertChunk = this.db.prepare(`
|
|
206
|
+
INSERT INTO chunks (source_id, session_id, worktree, agent, ord, body, title)
|
|
207
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
208
|
+
`);
|
|
209
|
+
|
|
210
|
+
const insertChunkTri = this.db.prepare(`
|
|
211
|
+
INSERT INTO chunks_tri (source_id, session_id, ord, body)
|
|
212
|
+
VALUES (?, ?, ?, ?)
|
|
213
|
+
`);
|
|
214
|
+
|
|
215
|
+
insertSource.run(id, sid, wt, ag, k, lbl, totalBytes, chunkCount, now, isoDate, now);
|
|
216
|
+
|
|
217
|
+
for (let ord = 0; ord < chunkCount; ord++) {
|
|
218
|
+
const chunkText = chunks[ord];
|
|
219
|
+
insertChunk.run(id, sid, wt, ag, ord, chunkText, lbl);
|
|
220
|
+
insertChunkTri.run(id, sid, ord, chunkText);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
return {
|
|
224
|
+
sourceId: id,
|
|
225
|
+
bytesTotal: totalBytes,
|
|
226
|
+
chunkCount,
|
|
227
|
+
label: lbl,
|
|
228
|
+
chunks
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Search indexed chunks using BM25 + Trigram Reciprocal Rank Fusion */
|
|
233
|
+
search({ queries, sourceId, sessionId, worktree, scope = "session", limit = 5, offset = 0 }) {
|
|
234
|
+
this.open();
|
|
235
|
+
const queryList = Array.isArray(queries) ? queries : [queries];
|
|
236
|
+
const maxHits = Math.min(Math.max(1, limit || 5), 20);
|
|
237
|
+
const skipHits = Math.max(0, offset || 0);
|
|
238
|
+
|
|
239
|
+
const scores = new Map();
|
|
240
|
+
|
|
241
|
+
for (const q of queryList) {
|
|
242
|
+
if (!q || typeof q !== "string") continue;
|
|
243
|
+
const porterQ = sanitizeFtsQuery(q);
|
|
244
|
+
const trigramQ = sanitizeTrigramQuery(q);
|
|
245
|
+
|
|
246
|
+
// 1. Porter FTS5 with BM25 ranking
|
|
247
|
+
if (porterQ) {
|
|
248
|
+
let sql = `
|
|
249
|
+
SELECT rowid, source_id, ord, body, title, session_id, worktree, bm25(chunks) AS rank
|
|
250
|
+
FROM chunks
|
|
251
|
+
WHERE chunks MATCH ?
|
|
252
|
+
`;
|
|
253
|
+
const params = [porterQ];
|
|
254
|
+
|
|
255
|
+
if (sourceId) {
|
|
256
|
+
sql += " AND source_id = ?";
|
|
257
|
+
params.push(sourceId);
|
|
258
|
+
} else if (scope === "session" && sessionId) {
|
|
259
|
+
sql += " AND session_id = ?";
|
|
260
|
+
params.push(sessionId);
|
|
261
|
+
} else if (scope === "worktree" && worktree) {
|
|
262
|
+
sql += " AND worktree = ?";
|
|
263
|
+
params.push(worktree);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
sql += " ORDER BY rank LIMIT 30";
|
|
267
|
+
|
|
268
|
+
try {
|
|
269
|
+
const rows = this.db.prepare(sql).all(...params);
|
|
270
|
+
rows.forEach((row, rankIdx) => {
|
|
271
|
+
const key = `${row.source_id}:${row.ord}`;
|
|
272
|
+
const rrf = 1.0 / (RRF_K + rankIdx + 1);
|
|
273
|
+
const existing = scores.get(key);
|
|
274
|
+
if (existing) {
|
|
275
|
+
existing.rrfScore += rrf;
|
|
276
|
+
existing.matches.push({ query: q, type: "porter", rank: rankIdx + 1 });
|
|
277
|
+
} else {
|
|
278
|
+
scores.set(key, {
|
|
279
|
+
rowid: row.rowid,
|
|
280
|
+
sourceId: row.source_id,
|
|
281
|
+
ord: row.ord,
|
|
282
|
+
body: row.body,
|
|
283
|
+
title: row.title,
|
|
284
|
+
sessionId: row.session_id,
|
|
285
|
+
worktree: row.worktree,
|
|
286
|
+
rrfScore: rrf,
|
|
287
|
+
matches: [{ query: q, type: "porter", rank: rankIdx + 1 }]
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
} catch {
|
|
292
|
+
// Porter match error ignored
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// 2. Trigram FTS5
|
|
297
|
+
if (trigramQ) {
|
|
298
|
+
let sqlTri = `
|
|
299
|
+
SELECT rowid, source_id, ord, body, session_id
|
|
300
|
+
FROM chunks_tri
|
|
301
|
+
WHERE chunks_tri MATCH ?
|
|
302
|
+
`;
|
|
303
|
+
const paramsTri = [trigramQ];
|
|
304
|
+
|
|
305
|
+
if (sourceId) {
|
|
306
|
+
sqlTri += " AND source_id = ?";
|
|
307
|
+
paramsTri.push(sourceId);
|
|
308
|
+
} else if (scope === "session" && sessionId) {
|
|
309
|
+
sqlTri += " AND session_id = ?";
|
|
310
|
+
paramsTri.push(sessionId);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
sqlTri += " LIMIT 30";
|
|
314
|
+
|
|
315
|
+
try {
|
|
316
|
+
const rowsTri = this.db.prepare(sqlTri).all(...paramsTri);
|
|
317
|
+
rowsTri.forEach((row, rankIdx) => {
|
|
318
|
+
const key = `${row.source_id}:${row.ord}`;
|
|
319
|
+
const rrf = 1.0 / (RRF_K + rankIdx + 1);
|
|
320
|
+
const existing = scores.get(key);
|
|
321
|
+
if (existing) {
|
|
322
|
+
existing.rrfScore += rrf;
|
|
323
|
+
existing.matches.push({ query: q, type: "trigram", rank: rankIdx + 1 });
|
|
324
|
+
} else {
|
|
325
|
+
scores.set(key, {
|
|
326
|
+
rowid: row.rowid,
|
|
327
|
+
sourceId: row.source_id,
|
|
328
|
+
ord: row.ord,
|
|
329
|
+
body: row.body,
|
|
330
|
+
title: "",
|
|
331
|
+
sessionId: row.session_id,
|
|
332
|
+
worktree: "",
|
|
333
|
+
rrfScore: rrf,
|
|
334
|
+
matches: [{ query: q, type: "trigram", rank: rankIdx + 1 }]
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
});
|
|
338
|
+
} catch {
|
|
339
|
+
// Trigram match error ignored
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const allHits = Array.from(scores.values()).sort((a, b) => b.rrfScore - a.rrfScore);
|
|
345
|
+
const paginated = allHits.slice(skipHits, skipHits + maxHits);
|
|
346
|
+
|
|
347
|
+
const formatted = paginated.map((hit) => {
|
|
348
|
+
let snippet = hit.body;
|
|
349
|
+
if (Buffer.byteLength(snippet, "utf8") > SNIPPET_MAX_BYTES) {
|
|
350
|
+
snippet = snippet.slice(0, SNIPPET_MAX_BYTES) + "\n... [truncated, use ctx_search or ctx_index to inspect full]";
|
|
351
|
+
}
|
|
352
|
+
return {
|
|
353
|
+
sourceId: hit.sourceId,
|
|
354
|
+
ord: hit.ord,
|
|
355
|
+
title: hit.title || hit.sourceId,
|
|
356
|
+
rrfScore: parseFloat(hit.rrfScore.toFixed(5)),
|
|
357
|
+
matches: hit.matches.length,
|
|
358
|
+
snippet
|
|
359
|
+
};
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
return {
|
|
363
|
+
hits: formatted,
|
|
364
|
+
totalMatches: allHits.length,
|
|
365
|
+
returned: formatted.length,
|
|
366
|
+
offset: skipHits,
|
|
367
|
+
limit: maxHits
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/** Record an event in the session journal */
|
|
372
|
+
recordEvent({
|
|
373
|
+
sessionId,
|
|
374
|
+
worktree,
|
|
375
|
+
agent,
|
|
376
|
+
kind,
|
|
377
|
+
tool,
|
|
378
|
+
key,
|
|
379
|
+
path: filePath,
|
|
380
|
+
ok = 1,
|
|
381
|
+
exitCode,
|
|
382
|
+
bytes = 0,
|
|
383
|
+
body = "",
|
|
384
|
+
turn = 0,
|
|
385
|
+
sandboxBytes = 0,
|
|
386
|
+
returnedBytes = 0
|
|
387
|
+
}) {
|
|
388
|
+
this.open();
|
|
389
|
+
const now = new Date().toISOString();
|
|
390
|
+
const insert = this.db.prepare(`
|
|
391
|
+
INSERT INTO events (
|
|
392
|
+
session_id, worktree, agent, kind, tool, key, path, ok, exit_code, bytes, body, turn, sandbox_bytes, returned_bytes, created_at, accessed_at
|
|
393
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
394
|
+
`);
|
|
395
|
+
|
|
396
|
+
const result = insert.run(
|
|
397
|
+
sessionId || "default",
|
|
398
|
+
worktree || process.cwd(),
|
|
399
|
+
agent || "antigravity",
|
|
400
|
+
kind || "tool",
|
|
401
|
+
tool || null,
|
|
402
|
+
key || null,
|
|
403
|
+
filePath || null,
|
|
404
|
+
ok ? 1 : 0,
|
|
405
|
+
exitCode ?? (ok ? 0 : 1),
|
|
406
|
+
bytes,
|
|
407
|
+
body || null,
|
|
408
|
+
turn,
|
|
409
|
+
sandboxBytes,
|
|
410
|
+
returnedBytes,
|
|
411
|
+
now,
|
|
412
|
+
now
|
|
413
|
+
);
|
|
414
|
+
|
|
415
|
+
return { seq: result.lastInsertRowid };
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** Retrieve compaction / state resume block */
|
|
419
|
+
getResumeState(sessionId, limit = 5) {
|
|
420
|
+
this.open();
|
|
421
|
+
const sid = sessionId || "default";
|
|
422
|
+
|
|
423
|
+
const sources = this.db
|
|
424
|
+
.prepare(
|
|
425
|
+
`
|
|
426
|
+
SELECT id, label, kind, bytes_total, chunk_count, created_at
|
|
427
|
+
FROM sources
|
|
428
|
+
WHERE session_id = ?
|
|
429
|
+
ORDER BY created_ts DESC
|
|
430
|
+
LIMIT ?
|
|
431
|
+
`
|
|
432
|
+
)
|
|
433
|
+
.all(sid, limit);
|
|
434
|
+
|
|
435
|
+
const events = this.db
|
|
436
|
+
.prepare(
|
|
437
|
+
`
|
|
438
|
+
SELECT seq, tool, kind, ok, sandbox_bytes, returned_bytes, created_at
|
|
439
|
+
FROM events
|
|
440
|
+
WHERE session_id = ?
|
|
441
|
+
ORDER BY seq DESC
|
|
442
|
+
LIMIT ?
|
|
443
|
+
`
|
|
444
|
+
)
|
|
445
|
+
.all(sid, limit);
|
|
446
|
+
|
|
447
|
+
return {
|
|
448
|
+
sessionId: sid,
|
|
449
|
+
recentSources: sources,
|
|
450
|
+
recentEvents: events
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** Retrieve full event body by sequence number */
|
|
455
|
+
getEventBySeq(seq) {
|
|
456
|
+
this.open();
|
|
457
|
+
const row = this.db.prepare("SELECT * FROM events WHERE seq = ?").get(seq);
|
|
458
|
+
return row || null;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** Calculate token savings & statistics */
|
|
462
|
+
getStats(sessionId) {
|
|
463
|
+
this.open();
|
|
464
|
+
const sid = sessionId || "default";
|
|
465
|
+
|
|
466
|
+
const eventStats = this.db
|
|
467
|
+
.prepare(
|
|
468
|
+
`
|
|
469
|
+
SELECT
|
|
470
|
+
COUNT(*) AS total_calls,
|
|
471
|
+
SUM(sandbox_bytes) AS total_sandbox_bytes,
|
|
472
|
+
SUM(returned_bytes) AS total_returned_bytes
|
|
473
|
+
FROM events
|
|
474
|
+
WHERE session_id = ?
|
|
475
|
+
`
|
|
476
|
+
)
|
|
477
|
+
.get(sid);
|
|
478
|
+
|
|
479
|
+
const sourceStats = this.db
|
|
480
|
+
.prepare(
|
|
481
|
+
`
|
|
482
|
+
SELECT
|
|
483
|
+
COUNT(*) AS total_sources,
|
|
484
|
+
SUM(bytes_total) AS total_source_bytes,
|
|
485
|
+
SUM(chunk_count) AS total_chunks
|
|
486
|
+
FROM sources
|
|
487
|
+
WHERE session_id = ?
|
|
488
|
+
`
|
|
489
|
+
)
|
|
490
|
+
.get(sid);
|
|
491
|
+
|
|
492
|
+
const totalRawBytes = (eventStats?.total_sandbox_bytes || 0) + (sourceStats?.total_source_bytes || 0);
|
|
493
|
+
const totalReturnedBytes = eventStats?.total_returned_bytes || 0;
|
|
494
|
+
const keptOutBytes = Math.max(0, totalRawBytes - totalReturnedBytes);
|
|
495
|
+
const savingsPercent = totalRawBytes > 0 ? ((keptOutBytes / totalRawBytes) * 100).toFixed(1) : "0.0";
|
|
496
|
+
const tokensKeptOut = Math.round(keptOutBytes / 4);
|
|
497
|
+
|
|
498
|
+
return {
|
|
499
|
+
sessionId: sid,
|
|
500
|
+
calls: eventStats?.total_calls || 0,
|
|
501
|
+
totalRawBytes,
|
|
502
|
+
totalReturnedBytes,
|
|
503
|
+
keptOutBytes,
|
|
504
|
+
savingsPercent: parseFloat(savingsPercent),
|
|
505
|
+
tokensKeptOut,
|
|
506
|
+
sourcesCount: sourceStats?.total_sources || 0,
|
|
507
|
+
chunksCount: sourceStats?.total_chunks || 0
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** Purge stored data */
|
|
512
|
+
purge({ scope = "session", sessionId, worktree }) {
|
|
513
|
+
this.open();
|
|
514
|
+
if (scope === "all") {
|
|
515
|
+
this.db.exec(`
|
|
516
|
+
DELETE FROM chunks;
|
|
517
|
+
DELETE FROM chunks_tri;
|
|
518
|
+
DELETE FROM sources;
|
|
519
|
+
DELETE FROM events;
|
|
520
|
+
VACUUM;
|
|
521
|
+
`);
|
|
522
|
+
return { ok: true, purged: "all" };
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
if (scope === "worktree" && worktree) {
|
|
526
|
+
this.db.prepare("DELETE FROM chunks WHERE worktree = ?").run(worktree);
|
|
527
|
+
this.db.prepare("DELETE FROM sources WHERE worktree = ?").run(worktree);
|
|
528
|
+
this.db.prepare("DELETE FROM events WHERE worktree = ?").run(worktree);
|
|
529
|
+
return { ok: true, purged: "worktree", worktree };
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
const sid = sessionId || "default";
|
|
533
|
+
this.db.prepare("DELETE FROM chunks WHERE session_id = ?").run(sid);
|
|
534
|
+
this.db.prepare("DELETE FROM chunks_tri WHERE session_id = ?").run(sid);
|
|
535
|
+
this.db.prepare("DELETE FROM sources WHERE session_id = ?").run(sid);
|
|
536
|
+
this.db.prepare("DELETE FROM events WHERE session_id = ?").run(sid);
|
|
537
|
+
return { ok: true, purged: "session", sessionId: sid };
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/** Run diagnostic checks */
|
|
541
|
+
doctor() {
|
|
542
|
+
try {
|
|
543
|
+
this.open();
|
|
544
|
+
const versionRow = this.db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get();
|
|
545
|
+
const ftsCheck = this.db.prepare("SELECT count(*) as cnt FROM chunks").get();
|
|
546
|
+
const stat = fs.existsSync(this.dbPath) ? fs.statSync(this.dbPath) : null;
|
|
547
|
+
|
|
548
|
+
return {
|
|
549
|
+
status: "HEALTHY",
|
|
550
|
+
allOk: true,
|
|
551
|
+
dbPath: this.dbPath,
|
|
552
|
+
dbSizeBytes: stat ? stat.size : 0,
|
|
553
|
+
schemaVersion: versionRow ? versionRow.value : "unknown",
|
|
554
|
+
totalChunksIndexed: ftsCheck ? ftsCheck.cnt : 0,
|
|
555
|
+
sqliteVersion: process.versions.node
|
|
556
|
+
};
|
|
557
|
+
} catch (err) {
|
|
558
|
+
return {
|
|
559
|
+
status: "ERROR",
|
|
560
|
+
allOk: false,
|
|
561
|
+
error: String(err && err.message ? err.message : err)
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
}
|