grov 0.2.3 → 0.5.3

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.
Files changed (64) hide show
  1. package/README.md +44 -5
  2. package/dist/cli.js +40 -2
  3. package/dist/commands/login.d.ts +1 -0
  4. package/dist/commands/login.js +115 -0
  5. package/dist/commands/logout.d.ts +1 -0
  6. package/dist/commands/logout.js +13 -0
  7. package/dist/commands/sync.d.ts +8 -0
  8. package/dist/commands/sync.js +127 -0
  9. package/dist/lib/api-client.d.ts +57 -0
  10. package/dist/lib/api-client.js +174 -0
  11. package/dist/lib/cloud-sync.d.ts +33 -0
  12. package/dist/lib/cloud-sync.js +176 -0
  13. package/dist/lib/credentials.d.ts +53 -0
  14. package/dist/lib/credentials.js +201 -0
  15. package/dist/lib/llm-extractor.d.ts +15 -39
  16. package/dist/lib/llm-extractor.js +400 -418
  17. package/dist/lib/store/convenience.d.ts +40 -0
  18. package/dist/lib/store/convenience.js +104 -0
  19. package/dist/lib/store/database.d.ts +22 -0
  20. package/dist/lib/store/database.js +375 -0
  21. package/dist/lib/store/drift.d.ts +9 -0
  22. package/dist/lib/store/drift.js +89 -0
  23. package/dist/lib/store/index.d.ts +7 -0
  24. package/dist/lib/store/index.js +13 -0
  25. package/dist/lib/store/sessions.d.ts +32 -0
  26. package/dist/lib/store/sessions.js +240 -0
  27. package/dist/lib/store/steps.d.ts +40 -0
  28. package/dist/lib/store/steps.js +161 -0
  29. package/dist/lib/store/tasks.d.ts +33 -0
  30. package/dist/lib/store/tasks.js +133 -0
  31. package/dist/lib/store/types.d.ts +167 -0
  32. package/dist/lib/store/types.js +2 -0
  33. package/dist/lib/store.d.ts +1 -406
  34. package/dist/lib/store.js +2 -1356
  35. package/dist/lib/utils.d.ts +5 -0
  36. package/dist/lib/utils.js +45 -0
  37. package/dist/proxy/action-parser.d.ts +10 -2
  38. package/dist/proxy/action-parser.js +4 -2
  39. package/dist/proxy/cache.d.ts +36 -0
  40. package/dist/proxy/cache.js +51 -0
  41. package/dist/proxy/config.d.ts +1 -0
  42. package/dist/proxy/config.js +2 -0
  43. package/dist/proxy/extended-cache.d.ts +10 -0
  44. package/dist/proxy/extended-cache.js +155 -0
  45. package/dist/proxy/forwarder.d.ts +7 -1
  46. package/dist/proxy/forwarder.js +157 -7
  47. package/dist/proxy/handlers/preprocess.d.ts +20 -0
  48. package/dist/proxy/handlers/preprocess.js +169 -0
  49. package/dist/proxy/injection/delta-tracking.d.ts +11 -0
  50. package/dist/proxy/injection/delta-tracking.js +93 -0
  51. package/dist/proxy/injection/injectors.d.ts +7 -0
  52. package/dist/proxy/injection/injectors.js +139 -0
  53. package/dist/proxy/request-processor.d.ts +18 -3
  54. package/dist/proxy/request-processor.js +151 -28
  55. package/dist/proxy/response-processor.js +116 -47
  56. package/dist/proxy/server.d.ts +4 -1
  57. package/dist/proxy/server.js +592 -253
  58. package/dist/proxy/types.d.ts +13 -0
  59. package/dist/proxy/types.js +2 -0
  60. package/dist/proxy/utils/extractors.d.ts +18 -0
  61. package/dist/proxy/utils/extractors.js +109 -0
  62. package/dist/proxy/utils/logging.d.ts +18 -0
  63. package/dist/proxy/utils/logging.js +42 -0
  64. package/package.json +22 -4
package/dist/lib/store.js CHANGED
@@ -1,1356 +1,2 @@
1
- // SQLite store for task reasoning at ~/.grov/memory.db
2
- import Database from 'better-sqlite3';
3
- import { existsSync, mkdirSync, chmodSync } from 'fs';
4
- import { homedir } from 'os';
5
- import { join } from 'path';
6
- import { randomUUID } from 'crypto';
7
- /**
8
- * Escape LIKE pattern special characters to prevent SQL injection.
9
- * SECURITY: Prevents wildcard injection in LIKE queries.
10
- */
11
- function escapeLikePattern(str) {
12
- return str.replace(/[%_\\]/g, '\\$&');
13
- }
14
- const GROV_DIR = join(homedir(), '.grov');
15
- const DB_PATH = join(GROV_DIR, 'memory.db');
16
- let db = null;
17
- // PERFORMANCE: Statement cache to avoid re-preparing frequently used queries
18
- const statementCache = new Map();
19
- /**
20
- * Get a cached prepared statement or create a new one.
21
- * PERFORMANCE: Avoids overhead of re-preparing the same SQL.
22
- */
23
- function getCachedStatement(database, sql) {
24
- let stmt = statementCache.get(sql);
25
- if (!stmt) {
26
- stmt = database.prepare(sql);
27
- statementCache.set(sql, stmt);
28
- }
29
- return stmt;
30
- }
31
- /**
32
- * Initialize the database connection and create tables
33
- */
34
- export function initDatabase() {
35
- if (db)
36
- return db;
37
- // Ensure .grov directory exists with secure permissions
38
- if (!existsSync(GROV_DIR)) {
39
- mkdirSync(GROV_DIR, { recursive: true, mode: 0o700 });
40
- }
41
- db = new Database(DB_PATH);
42
- // Set secure file permissions on the database
43
- try {
44
- chmodSync(DB_PATH, 0o600);
45
- }
46
- catch {
47
- // SECURITY: Warn user if permissions can't be set (e.g., on Windows)
48
- // The database may be world-readable on some systems
49
- console.warn('Warning: Could not set restrictive permissions on ~/.grov/memory.db');
50
- console.warn('Please ensure the file has appropriate permissions for your system.');
51
- }
52
- // OPTIMIZATION: Enable WAL mode for better concurrent performance
53
- db.pragma('journal_mode = WAL');
54
- // Create all tables in a single transaction for efficiency
55
- db.exec(`
56
- CREATE TABLE IF NOT EXISTS tasks (
57
- id TEXT PRIMARY KEY,
58
- project_path TEXT NOT NULL,
59
- user TEXT,
60
- original_query TEXT NOT NULL,
61
- goal TEXT,
62
- reasoning_trace JSON DEFAULT '[]',
63
- files_touched JSON DEFAULT '[]',
64
- decisions JSON DEFAULT '[]',
65
- constraints JSON DEFAULT '[]',
66
- status TEXT NOT NULL CHECK(status IN ('complete', 'question', 'partial', 'abandoned')),
67
- trigger_reason TEXT CHECK(trigger_reason IN ('complete', 'threshold', 'abandoned')),
68
- linked_commit TEXT,
69
- parent_task_id TEXT,
70
- turn_number INTEGER,
71
- tags JSON DEFAULT '[]',
72
- created_at TEXT NOT NULL,
73
- FOREIGN KEY (parent_task_id) REFERENCES tasks(id)
74
- );
75
-
76
- CREATE INDEX IF NOT EXISTS idx_project ON tasks(project_path);
77
- CREATE INDEX IF NOT EXISTS idx_status ON tasks(status);
78
- CREATE INDEX IF NOT EXISTS idx_created ON tasks(created_at);
79
- `);
80
- // Migration: add new columns to existing tasks table
81
- try {
82
- db.exec(`ALTER TABLE tasks ADD COLUMN decisions JSON DEFAULT '[]'`);
83
- }
84
- catch { /* column exists */ }
85
- try {
86
- db.exec(`ALTER TABLE tasks ADD COLUMN constraints JSON DEFAULT '[]'`);
87
- }
88
- catch { /* column exists */ }
89
- try {
90
- db.exec(`ALTER TABLE tasks ADD COLUMN trigger_reason TEXT`);
91
- }
92
- catch { /* column exists */ }
93
- // Create session_states table (temporary per-session tracking)
94
- db.exec(`
95
- CREATE TABLE IF NOT EXISTS session_states (
96
- session_id TEXT PRIMARY KEY,
97
- user_id TEXT,
98
- project_path TEXT NOT NULL,
99
- original_goal TEXT,
100
- expected_scope JSON DEFAULT '[]',
101
- constraints JSON DEFAULT '[]',
102
- keywords JSON DEFAULT '[]',
103
- token_count INTEGER DEFAULT 0,
104
- escalation_count INTEGER DEFAULT 0,
105
- session_mode TEXT DEFAULT 'normal' CHECK(session_mode IN ('normal', 'drifted', 'forced')),
106
- waiting_for_recovery INTEGER DEFAULT 0,
107
- last_checked_at INTEGER DEFAULT 0,
108
- last_clear_at INTEGER,
109
- start_time TEXT NOT NULL,
110
- last_update TEXT NOT NULL,
111
- status TEXT DEFAULT 'active' CHECK(status IN ('active', 'completed', 'abandoned')),
112
- completed_at TEXT,
113
- parent_session_id TEXT,
114
- task_type TEXT DEFAULT 'main' CHECK(task_type IN ('main', 'subtask', 'parallel')),
115
- FOREIGN KEY (parent_session_id) REFERENCES session_states(session_id)
116
- );
117
-
118
- CREATE INDEX IF NOT EXISTS idx_session_project ON session_states(project_path);
119
- CREATE INDEX IF NOT EXISTS idx_session_status ON session_states(status);
120
- CREATE INDEX IF NOT EXISTS idx_session_parent ON session_states(parent_session_id);
121
- `);
122
- // Migration: add new columns to existing session_states table
123
- try {
124
- db.exec(`ALTER TABLE session_states ADD COLUMN expected_scope JSON DEFAULT '[]'`);
125
- }
126
- catch { /* column exists */ }
127
- try {
128
- db.exec(`ALTER TABLE session_states ADD COLUMN constraints JSON DEFAULT '[]'`);
129
- }
130
- catch { /* column exists */ }
131
- try {
132
- db.exec(`ALTER TABLE session_states ADD COLUMN keywords JSON DEFAULT '[]'`);
133
- }
134
- catch { /* column exists */ }
135
- try {
136
- db.exec(`ALTER TABLE session_states ADD COLUMN token_count INTEGER DEFAULT 0`);
137
- }
138
- catch { /* column exists */ }
139
- try {
140
- db.exec(`ALTER TABLE session_states ADD COLUMN escalation_count INTEGER DEFAULT 0`);
141
- }
142
- catch { /* column exists */ }
143
- try {
144
- db.exec(`ALTER TABLE session_states ADD COLUMN session_mode TEXT DEFAULT 'normal'`);
145
- }
146
- catch { /* column exists */ }
147
- try {
148
- db.exec(`ALTER TABLE session_states ADD COLUMN waiting_for_recovery INTEGER DEFAULT 0`);
149
- }
150
- catch { /* column exists */ }
151
- try {
152
- db.exec(`ALTER TABLE session_states ADD COLUMN last_checked_at INTEGER DEFAULT 0`);
153
- }
154
- catch { /* column exists */ }
155
- try {
156
- db.exec(`ALTER TABLE session_states ADD COLUMN last_clear_at INTEGER`);
157
- }
158
- catch { /* column exists */ }
159
- try {
160
- db.exec(`ALTER TABLE session_states ADD COLUMN parent_session_id TEXT`);
161
- }
162
- catch { /* column exists */ }
163
- try {
164
- db.exec(`ALTER TABLE session_states ADD COLUMN task_type TEXT DEFAULT 'main'`);
165
- }
166
- catch { /* column exists */ }
167
- try {
168
- db.exec(`ALTER TABLE session_states ADD COLUMN completed_at TEXT`);
169
- }
170
- catch { /* column exists */ }
171
- try {
172
- db.exec(`CREATE INDEX IF NOT EXISTS idx_session_parent ON session_states(parent_session_id)`);
173
- }
174
- catch { /* index exists */ }
175
- try {
176
- db.exec(`CREATE INDEX IF NOT EXISTS idx_session_completed ON session_states(completed_at)`);
177
- }
178
- catch { /* index exists */ }
179
- // Create file_reasoning table (file-level reasoning with anchoring)
180
- db.exec(`
181
- CREATE TABLE IF NOT EXISTS file_reasoning (
182
- id TEXT PRIMARY KEY,
183
- task_id TEXT,
184
- file_path TEXT NOT NULL,
185
- anchor TEXT,
186
- line_start INTEGER,
187
- line_end INTEGER,
188
- code_hash TEXT,
189
- change_type TEXT CHECK(change_type IN ('read', 'write', 'edit', 'create', 'delete')),
190
- reasoning TEXT NOT NULL,
191
- created_at TEXT NOT NULL,
192
- FOREIGN KEY (task_id) REFERENCES tasks(id)
193
- );
194
-
195
- CREATE INDEX IF NOT EXISTS idx_file_task ON file_reasoning(task_id);
196
- CREATE INDEX IF NOT EXISTS idx_file_path ON file_reasoning(file_path);
197
- -- PERFORMANCE: Composite index for common query pattern (file_path + ORDER BY created_at)
198
- CREATE INDEX IF NOT EXISTS idx_file_path_created ON file_reasoning(file_path, created_at DESC);
199
- `);
200
- // Migration: Add drift detection columns to session_states (safe to run multiple times)
201
- const columns = db.pragma('table_info(session_states)');
202
- const existingColumns = new Set(columns.map(c => c.name));
203
- // Shared columns
204
- if (!existingColumns.has('expected_scope')) {
205
- db.exec(`ALTER TABLE session_states ADD COLUMN expected_scope JSON DEFAULT '[]'`);
206
- }
207
- if (!existingColumns.has('constraints')) {
208
- db.exec(`ALTER TABLE session_states ADD COLUMN constraints JSON DEFAULT '[]'`);
209
- }
210
- if (!existingColumns.has('keywords')) {
211
- db.exec(`ALTER TABLE session_states ADD COLUMN keywords JSON DEFAULT '[]'`);
212
- }
213
- if (!existingColumns.has('escalation_count')) {
214
- db.exec(`ALTER TABLE session_states ADD COLUMN escalation_count INTEGER DEFAULT 0`);
215
- }
216
- if (!existingColumns.has('last_checked_at')) {
217
- db.exec(`ALTER TABLE session_states ADD COLUMN last_checked_at INTEGER DEFAULT 0`);
218
- }
219
- // Hook-specific columns
220
- if (!existingColumns.has('success_criteria')) {
221
- db.exec(`ALTER TABLE session_states ADD COLUMN success_criteria JSON DEFAULT '[]'`);
222
- }
223
- if (!existingColumns.has('last_drift_score')) {
224
- db.exec(`ALTER TABLE session_states ADD COLUMN last_drift_score INTEGER`);
225
- }
226
- if (!existingColumns.has('pending_recovery_plan')) {
227
- db.exec(`ALTER TABLE session_states ADD COLUMN pending_recovery_plan JSON`);
228
- }
229
- if (!existingColumns.has('drift_history')) {
230
- db.exec(`ALTER TABLE session_states ADD COLUMN drift_history JSON DEFAULT '[]'`);
231
- }
232
- // Proxy-specific columns
233
- if (!existingColumns.has('token_count')) {
234
- db.exec(`ALTER TABLE session_states ADD COLUMN token_count INTEGER DEFAULT 0`);
235
- }
236
- if (!existingColumns.has('session_mode')) {
237
- db.exec(`ALTER TABLE session_states ADD COLUMN session_mode TEXT DEFAULT 'normal'`);
238
- }
239
- if (!existingColumns.has('waiting_for_recovery')) {
240
- db.exec(`ALTER TABLE session_states ADD COLUMN waiting_for_recovery INTEGER DEFAULT 0`);
241
- }
242
- if (!existingColumns.has('last_clear_at')) {
243
- db.exec(`ALTER TABLE session_states ADD COLUMN last_clear_at INTEGER`);
244
- }
245
- if (!existingColumns.has('completed_at')) {
246
- db.exec(`ALTER TABLE session_states ADD COLUMN completed_at TEXT`);
247
- }
248
- if (!existingColumns.has('parent_session_id')) {
249
- db.exec(`ALTER TABLE session_states ADD COLUMN parent_session_id TEXT`);
250
- }
251
- if (!existingColumns.has('task_type')) {
252
- db.exec(`ALTER TABLE session_states ADD COLUMN task_type TEXT DEFAULT 'main'`);
253
- }
254
- // Additional hook fields
255
- if (!existingColumns.has('actions_taken')) {
256
- db.exec(`ALTER TABLE session_states ADD COLUMN actions_taken JSON DEFAULT '[]'`);
257
- }
258
- if (!existingColumns.has('files_explored')) {
259
- db.exec(`ALTER TABLE session_states ADD COLUMN files_explored JSON DEFAULT '[]'`);
260
- }
261
- if (!existingColumns.has('current_intent')) {
262
- db.exec(`ALTER TABLE session_states ADD COLUMN current_intent TEXT`);
263
- }
264
- if (!existingColumns.has('drift_warnings')) {
265
- db.exec(`ALTER TABLE session_states ADD COLUMN drift_warnings JSON DEFAULT '[]'`);
266
- }
267
- // Create steps table (action log for current session)
268
- db.exec(`
269
- CREATE TABLE IF NOT EXISTS steps (
270
- id TEXT PRIMARY KEY,
271
- session_id TEXT NOT NULL,
272
- action_type TEXT NOT NULL CHECK(action_type IN ('edit', 'write', 'bash', 'read', 'glob', 'grep', 'task', 'other')),
273
- files JSON DEFAULT '[]',
274
- folders JSON DEFAULT '[]',
275
- command TEXT,
276
- reasoning TEXT,
277
- drift_score INTEGER,
278
- drift_type TEXT CHECK(drift_type IN ('none', 'minor', 'major', 'critical')),
279
- is_key_decision INTEGER DEFAULT 0,
280
- is_validated INTEGER DEFAULT 1,
281
- correction_given TEXT,
282
- correction_level TEXT CHECK(correction_level IN ('nudge', 'correct', 'intervene', 'halt')),
283
- keywords JSON DEFAULT '[]',
284
- timestamp INTEGER NOT NULL,
285
- FOREIGN KEY (session_id) REFERENCES session_states(session_id)
286
- );
287
- CREATE INDEX IF NOT EXISTS idx_steps_session ON steps(session_id);
288
- CREATE INDEX IF NOT EXISTS idx_steps_timestamp ON steps(timestamp);
289
- `);
290
- // Migration: add new columns to existing steps table
291
- try {
292
- db.exec(`ALTER TABLE steps ADD COLUMN drift_type TEXT`);
293
- }
294
- catch { /* column exists */ }
295
- try {
296
- db.exec(`ALTER TABLE steps ADD COLUMN is_key_decision INTEGER DEFAULT 0`);
297
- }
298
- catch { /* column exists */ }
299
- try {
300
- db.exec(`ALTER TABLE steps ADD COLUMN is_validated INTEGER DEFAULT 1`);
301
- }
302
- catch { /* column exists */ }
303
- try {
304
- db.exec(`ALTER TABLE steps ADD COLUMN correction_given TEXT`);
305
- }
306
- catch { /* column exists */ }
307
- try {
308
- db.exec(`ALTER TABLE steps ADD COLUMN correction_level TEXT`);
309
- }
310
- catch { /* column exists */ }
311
- try {
312
- db.exec(`ALTER TABLE steps ADD COLUMN keywords JSON DEFAULT '[]'`);
313
- }
314
- catch { /* column exists */ }
315
- try {
316
- db.exec(`ALTER TABLE steps ADD COLUMN reasoning TEXT`);
317
- }
318
- catch { /* column exists */ }
319
- // Create drift_log table (rejected actions for audit)
320
- db.exec(`
321
- CREATE TABLE IF NOT EXISTS drift_log (
322
- id TEXT PRIMARY KEY,
323
- session_id TEXT NOT NULL,
324
- timestamp INTEGER NOT NULL,
325
- action_type TEXT,
326
- files JSON DEFAULT '[]',
327
- drift_score INTEGER NOT NULL,
328
- drift_reason TEXT,
329
- correction_given TEXT,
330
- recovery_plan JSON,
331
- FOREIGN KEY (session_id) REFERENCES session_states(session_id)
332
- );
333
-
334
- CREATE INDEX IF NOT EXISTS idx_drift_log_session ON drift_log(session_id);
335
- CREATE INDEX IF NOT EXISTS idx_drift_log_timestamp ON drift_log(timestamp);
336
- `);
337
- return db;
338
- }
339
- /**
340
- * Close the database connection
341
- */
342
- export function closeDatabase() {
343
- if (db) {
344
- db.close();
345
- db = null;
346
- // PERFORMANCE: Clear statement cache when database is closed
347
- statementCache.clear();
348
- }
349
- }
350
- /**
351
- * Create a new task
352
- */
353
- export function createTask(input) {
354
- const database = initDatabase();
355
- const task = {
356
- id: randomUUID(),
357
- project_path: input.project_path,
358
- user: input.user,
359
- original_query: input.original_query,
360
- goal: input.goal,
361
- reasoning_trace: input.reasoning_trace || [],
362
- files_touched: input.files_touched || [],
363
- decisions: input.decisions || [],
364
- constraints: input.constraints || [],
365
- status: input.status,
366
- trigger_reason: input.trigger_reason,
367
- linked_commit: input.linked_commit,
368
- parent_task_id: input.parent_task_id,
369
- turn_number: input.turn_number,
370
- tags: input.tags || [],
371
- created_at: new Date().toISOString()
372
- };
373
- const stmt = database.prepare(`
374
- INSERT INTO tasks (
375
- id, project_path, user, original_query, goal,
376
- reasoning_trace, files_touched, decisions, constraints,
377
- status, trigger_reason, linked_commit,
378
- parent_task_id, turn_number, tags, created_at
379
- ) VALUES (
380
- ?, ?, ?, ?, ?,
381
- ?, ?, ?, ?,
382
- ?, ?, ?,
383
- ?, ?, ?, ?
384
- )
385
- `);
386
- stmt.run(task.id, task.project_path, task.user || null, task.original_query, task.goal || null, JSON.stringify(task.reasoning_trace), JSON.stringify(task.files_touched), JSON.stringify(task.decisions), JSON.stringify(task.constraints), task.status, task.trigger_reason || null, task.linked_commit || null, task.parent_task_id || null, task.turn_number || null, JSON.stringify(task.tags), task.created_at);
387
- return task;
388
- }
389
- /**
390
- * Get tasks for a project
391
- */
392
- export function getTasksForProject(projectPath, options = {}) {
393
- const database = initDatabase();
394
- let sql = 'SELECT * FROM tasks WHERE project_path = ?';
395
- const params = [projectPath];
396
- if (options.status) {
397
- sql += ' AND status = ?';
398
- params.push(options.status);
399
- }
400
- sql += ' ORDER BY created_at DESC';
401
- if (options.limit) {
402
- sql += ' LIMIT ?';
403
- params.push(options.limit);
404
- }
405
- const stmt = database.prepare(sql);
406
- const rows = stmt.all(...params);
407
- return rows.map(rowToTask);
408
- }
409
- /**
410
- * Get tasks that touched specific files.
411
- * SECURITY: Uses json_each for proper array handling and escaped LIKE patterns.
412
- */
413
- // SECURITY: Maximum files per query to prevent SQL DoS
414
- const MAX_FILES_PER_QUERY = 100;
415
- export function getTasksByFiles(projectPath, files, options = {}) {
416
- const database = initDatabase();
417
- if (files.length === 0) {
418
- return [];
419
- }
420
- // SECURITY: Limit file count to prevent SQL DoS via massive query generation
421
- const limitedFiles = files.length > MAX_FILES_PER_QUERY
422
- ? files.slice(0, MAX_FILES_PER_QUERY)
423
- : files;
424
- // Use json_each for proper array iteration with escaped LIKE patterns
425
- const fileConditions = limitedFiles.map(() => "EXISTS (SELECT 1 FROM json_each(files_touched) WHERE value LIKE ? ESCAPE '\\')").join(' OR ');
426
- let sql = `SELECT * FROM tasks WHERE project_path = ? AND (${fileConditions})`;
427
- // Escape LIKE special characters to prevent injection
428
- const params = [
429
- projectPath,
430
- ...limitedFiles.map(f => `%${escapeLikePattern(f)}%`)
431
- ];
432
- if (options.status) {
433
- sql += ' AND status = ?';
434
- params.push(options.status);
435
- }
436
- sql += ' ORDER BY created_at DESC';
437
- if (options.limit) {
438
- sql += ' LIMIT ?';
439
- params.push(options.limit);
440
- }
441
- const stmt = database.prepare(sql);
442
- const rows = stmt.all(...params);
443
- return rows.map(rowToTask);
444
- }
445
- /**
446
- * Get a task by ID
447
- */
448
- export function getTaskById(id) {
449
- const database = initDatabase();
450
- const stmt = database.prepare('SELECT * FROM tasks WHERE id = ?');
451
- const row = stmt.get(id);
452
- return row ? rowToTask(row) : null;
453
- }
454
- /**
455
- * Update a task's status
456
- */
457
- export function updateTaskStatus(id, status) {
458
- const database = initDatabase();
459
- const stmt = database.prepare('UPDATE tasks SET status = ? WHERE id = ?');
460
- stmt.run(status, id);
461
- }
462
- /**
463
- * Get task count for a project
464
- */
465
- export function getTaskCount(projectPath) {
466
- const database = initDatabase();
467
- const stmt = database.prepare('SELECT COUNT(*) as count FROM tasks WHERE project_path = ?');
468
- const row = stmt.get(projectPath);
469
- return row?.count ?? 0;
470
- }
471
- /**
472
- * Safely parse JSON with fallback to empty array.
473
- */
474
- function safeJsonParse(value, fallback) {
475
- if (typeof value !== 'string' || !value) {
476
- return fallback;
477
- }
478
- try {
479
- return JSON.parse(value);
480
- }
481
- catch {
482
- return fallback;
483
- }
484
- }
485
- /**
486
- * Convert database row to Task object
487
- */
488
- function rowToTask(row) {
489
- return {
490
- id: row.id,
491
- project_path: row.project_path,
492
- user: row.user,
493
- original_query: row.original_query,
494
- goal: row.goal,
495
- reasoning_trace: safeJsonParse(row.reasoning_trace, []),
496
- files_touched: safeJsonParse(row.files_touched, []),
497
- decisions: safeJsonParse(row.decisions, []),
498
- constraints: safeJsonParse(row.constraints, []),
499
- status: row.status,
500
- trigger_reason: row.trigger_reason,
501
- linked_commit: row.linked_commit,
502
- parent_task_id: row.parent_task_id,
503
- turn_number: row.turn_number,
504
- tags: safeJsonParse(row.tags, []),
505
- created_at: row.created_at
506
- };
507
- }
508
- // ============================================
509
- // SESSION STATE CRUD OPERATIONS
510
- // ============================================
511
- /**
512
- * Create a new session state.
513
- * FIXED: Uses INSERT OR IGNORE to handle race conditions safely.
514
- */
515
- export function createSessionState(input) {
516
- const database = initDatabase();
517
- const now = new Date().toISOString();
518
- const sessionState = {
519
- // Base fields
520
- session_id: input.session_id,
521
- user_id: input.user_id,
522
- project_path: input.project_path,
523
- original_goal: input.original_goal,
524
- expected_scope: input.expected_scope || [],
525
- constraints: input.constraints || [],
526
- keywords: input.keywords || [],
527
- escalation_count: 0,
528
- last_checked_at: 0,
529
- start_time: now,
530
- last_update: now,
531
- status: 'active',
532
- // Hook-specific fields
533
- success_criteria: input.success_criteria || [],
534
- last_drift_score: undefined,
535
- pending_recovery_plan: undefined,
536
- drift_history: [],
537
- actions_taken: [],
538
- files_explored: [],
539
- current_intent: undefined,
540
- drift_warnings: [],
541
- // Proxy-specific fields
542
- token_count: 0,
543
- session_mode: 'normal',
544
- waiting_for_recovery: false,
545
- last_clear_at: undefined,
546
- completed_at: undefined,
547
- parent_session_id: input.parent_session_id,
548
- task_type: input.task_type || 'main',
549
- };
550
- const stmt = database.prepare(`
551
- INSERT OR IGNORE INTO session_states (
552
- session_id, user_id, project_path, original_goal,
553
- expected_scope, constraints, keywords,
554
- token_count, escalation_count, session_mode,
555
- waiting_for_recovery, last_checked_at, last_clear_at,
556
- start_time, last_update, status,
557
- parent_session_id, task_type,
558
- success_criteria, last_drift_score, pending_recovery_plan, drift_history,
559
- completed_at
560
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
561
- `);
562
- stmt.run(sessionState.session_id, sessionState.user_id || null, sessionState.project_path, sessionState.original_goal || null, JSON.stringify(sessionState.expected_scope), JSON.stringify(sessionState.constraints), JSON.stringify(sessionState.keywords), sessionState.token_count, sessionState.escalation_count, sessionState.session_mode, sessionState.waiting_for_recovery ? 1 : 0, sessionState.last_checked_at, sessionState.last_clear_at || null, sessionState.start_time, sessionState.last_update, sessionState.status, sessionState.parent_session_id || null, sessionState.task_type, JSON.stringify(sessionState.success_criteria || []), sessionState.last_drift_score || null, sessionState.pending_recovery_plan ? JSON.stringify(sessionState.pending_recovery_plan) : null, JSON.stringify(sessionState.drift_history || []), sessionState.completed_at || null);
563
- return sessionState;
564
- }
565
- /**
566
- * Get a session state by ID
567
- */
568
- export function getSessionState(sessionId) {
569
- const database = initDatabase();
570
- const stmt = database.prepare('SELECT * FROM session_states WHERE session_id = ?');
571
- const row = stmt.get(sessionId);
572
- return row ? rowToSessionState(row) : null;
573
- }
574
- /**
575
- * Update a session state.
576
- * SECURITY: Uses transaction for atomic updates to prevent race conditions.
577
- */
578
- export function updateSessionState(sessionId, updates) {
579
- const database = initDatabase();
580
- const setClauses = [];
581
- const params = [];
582
- if (updates.user_id !== undefined) {
583
- setClauses.push('user_id = ?');
584
- params.push(updates.user_id || null);
585
- }
586
- if (updates.project_path !== undefined) {
587
- setClauses.push('project_path = ?');
588
- params.push(updates.project_path);
589
- }
590
- if (updates.original_goal !== undefined) {
591
- setClauses.push('original_goal = ?');
592
- params.push(updates.original_goal || null);
593
- }
594
- if (updates.expected_scope !== undefined) {
595
- setClauses.push('expected_scope = ?');
596
- params.push(JSON.stringify(updates.expected_scope));
597
- }
598
- if (updates.constraints !== undefined) {
599
- setClauses.push('constraints = ?');
600
- params.push(JSON.stringify(updates.constraints));
601
- }
602
- if (updates.keywords !== undefined) {
603
- setClauses.push('keywords = ?');
604
- params.push(JSON.stringify(updates.keywords));
605
- }
606
- if (updates.token_count !== undefined) {
607
- setClauses.push('token_count = ?');
608
- params.push(updates.token_count);
609
- }
610
- if (updates.escalation_count !== undefined) {
611
- setClauses.push('escalation_count = ?');
612
- params.push(updates.escalation_count);
613
- }
614
- if (updates.session_mode !== undefined) {
615
- setClauses.push('session_mode = ?');
616
- params.push(updates.session_mode);
617
- }
618
- if (updates.waiting_for_recovery !== undefined) {
619
- setClauses.push('waiting_for_recovery = ?');
620
- params.push(updates.waiting_for_recovery ? 1 : 0);
621
- }
622
- if (updates.last_checked_at !== undefined) {
623
- setClauses.push('last_checked_at = ?');
624
- params.push(updates.last_checked_at);
625
- }
626
- if (updates.last_clear_at !== undefined) {
627
- setClauses.push('last_clear_at = ?');
628
- params.push(updates.last_clear_at);
629
- }
630
- if (updates.status !== undefined) {
631
- setClauses.push('status = ?');
632
- params.push(updates.status);
633
- }
634
- // Always update last_update
635
- setClauses.push('last_update = ?');
636
- params.push(new Date().toISOString());
637
- if (setClauses.length === 0)
638
- return;
639
- params.push(sessionId);
640
- const sql = `UPDATE session_states SET ${setClauses.join(', ')} WHERE session_id = ?`;
641
- // SECURITY: Use transaction for atomic updates to prevent race conditions
642
- const transaction = database.transaction(() => {
643
- database.prepare(sql).run(...params);
644
- });
645
- transaction();
646
- }
647
- /**
648
- * Delete a session state
649
- */
650
- export function deleteSessionState(sessionId) {
651
- const database = initDatabase();
652
- database.prepare('DELETE FROM session_states WHERE session_id = ?').run(sessionId);
653
- }
654
- /**
655
- * Get active sessions for a project
656
- */
657
- export function getActiveSessionsForProject(projectPath) {
658
- const database = initDatabase();
659
- const stmt = database.prepare("SELECT * FROM session_states WHERE project_path = ? AND status = 'active' ORDER BY start_time DESC");
660
- const rows = stmt.all(projectPath);
661
- return rows.map(rowToSessionState);
662
- }
663
- /**
664
- * Get child sessions (subtasks and parallel tasks) for a parent session
665
- */
666
- export function getChildSessions(parentSessionId) {
667
- const database = initDatabase();
668
- const stmt = database.prepare('SELECT * FROM session_states WHERE parent_session_id = ? ORDER BY start_time DESC');
669
- const rows = stmt.all(parentSessionId);
670
- return rows.map(rowToSessionState);
671
- }
672
- /**
673
- * Get active session for a specific user in a project
674
- */
675
- export function getActiveSessionForUser(projectPath, userId) {
676
- const database = initDatabase();
677
- if (userId) {
678
- const stmt = database.prepare("SELECT * FROM session_states WHERE project_path = ? AND user_id = ? AND status = 'active' ORDER BY last_update DESC LIMIT 1");
679
- const row = stmt.get(projectPath, userId);
680
- return row ? rowToSessionState(row) : null;
681
- }
682
- else {
683
- const stmt = database.prepare("SELECT * FROM session_states WHERE project_path = ? AND status = 'active' ORDER BY last_update DESC LIMIT 1");
684
- const row = stmt.get(projectPath);
685
- return row ? rowToSessionState(row) : null;
686
- }
687
- }
688
- /**
689
- * Get all active sessions (for proxy-status command)
690
- */
691
- export function getActiveSessionsForStatus() {
692
- const database = initDatabase();
693
- const stmt = database.prepare("SELECT * FROM session_states WHERE status = 'active' ORDER BY last_update DESC LIMIT 20");
694
- const rows = stmt.all();
695
- return rows.map(rowToSessionState);
696
- }
697
- /**
698
- * Convert database row to SessionState object
699
- */
700
- function rowToSessionState(row) {
701
- return {
702
- // Base fields
703
- session_id: row.session_id,
704
- user_id: row.user_id,
705
- project_path: row.project_path,
706
- original_goal: row.original_goal,
707
- expected_scope: safeJsonParse(row.expected_scope, []),
708
- constraints: safeJsonParse(row.constraints, []),
709
- keywords: safeJsonParse(row.keywords, []),
710
- escalation_count: row.escalation_count || 0,
711
- last_checked_at: row.last_checked_at || 0,
712
- start_time: row.start_time,
713
- last_update: row.last_update,
714
- status: row.status,
715
- // Hook-specific fields
716
- success_criteria: safeJsonParse(row.success_criteria, []),
717
- last_drift_score: row.last_drift_score,
718
- pending_recovery_plan: safeJsonParse(row.pending_recovery_plan, undefined),
719
- drift_history: safeJsonParse(row.drift_history, []),
720
- actions_taken: safeJsonParse(row.actions_taken, []),
721
- files_explored: safeJsonParse(row.files_explored, []),
722
- current_intent: row.current_intent,
723
- drift_warnings: safeJsonParse(row.drift_warnings, []),
724
- // Proxy-specific fields
725
- token_count: row.token_count || 0,
726
- session_mode: row.session_mode || 'normal',
727
- waiting_for_recovery: Boolean(row.waiting_for_recovery),
728
- last_clear_at: row.last_clear_at,
729
- completed_at: row.completed_at,
730
- parent_session_id: row.parent_session_id,
731
- task_type: row.task_type || 'main',
732
- };
733
- }
734
- // ============================================
735
- // DRIFT DETECTION OPERATIONS (hook uses these)
736
- // ============================================
737
- /**
738
- * Update session drift metrics after a prompt check
739
- */
740
- export function updateSessionDrift(sessionId, driftScore, correctionLevel, promptSummary, recoveryPlan) {
741
- const database = initDatabase();
742
- const session = getSessionState(sessionId);
743
- if (!session)
744
- return;
745
- const now = new Date().toISOString();
746
- // Calculate new escalation count
747
- let newEscalation = session.escalation_count;
748
- if (driftScore >= 8) {
749
- // Recovery - decrease escalation
750
- newEscalation = Math.max(0, newEscalation - 1);
751
- }
752
- else if (correctionLevel && correctionLevel !== 'nudge') {
753
- // Significant drift - increase escalation
754
- newEscalation = Math.min(3, newEscalation + 1);
755
- }
756
- // Add to drift history
757
- const driftEvent = {
758
- timestamp: now,
759
- score: driftScore,
760
- level: correctionLevel || 'none',
761
- prompt_summary: promptSummary.substring(0, 100)
762
- };
763
- const newHistory = [...(session.drift_history || []), driftEvent];
764
- // Add to drift_warnings if correction was given
765
- const currentWarnings = session.drift_warnings || [];
766
- const newWarnings = correctionLevel
767
- ? [...currentWarnings, `[${now}] ${correctionLevel}: score ${driftScore}`]
768
- : currentWarnings;
769
- const stmt = database.prepare(`
770
- UPDATE session_states SET
771
- last_drift_score = ?,
772
- escalation_count = ?,
773
- pending_recovery_plan = ?,
774
- drift_history = ?,
775
- drift_warnings = ?,
776
- last_update = ?
777
- WHERE session_id = ?
778
- `);
779
- stmt.run(driftScore, newEscalation, recoveryPlan ? JSON.stringify(recoveryPlan) : null, JSON.stringify(newHistory), JSON.stringify(newWarnings), now, sessionId);
780
- }
781
- /**
782
- * Check if a session should be flagged for review
783
- * Returns true if: status=drifted OR warnings>=3 OR avg_score<6
784
- */
785
- export function shouldFlagForReview(sessionId) {
786
- const session = getSessionState(sessionId);
787
- if (!session)
788
- return false;
789
- // Check number of warnings
790
- const warnings = session.drift_warnings || [];
791
- if (warnings.length >= 3) {
792
- return true;
793
- }
794
- // Check drift history for average score
795
- const history = session.drift_history || [];
796
- if (history.length >= 2) {
797
- const totalScore = history.reduce((sum, e) => sum + e.score, 0);
798
- const avgScore = totalScore / history.length;
799
- if (avgScore < 6) {
800
- return true;
801
- }
802
- }
803
- // Check if any HALT level drift occurred
804
- if (history.some(e => e.level === 'halt')) {
805
- return true;
806
- }
807
- // Check current escalation level
808
- if (session.escalation_count >= 2) {
809
- return true;
810
- }
811
- return false;
812
- }
813
- /**
814
- * Get drift summary for a session (used by capture)
815
- */
816
- export function getDriftSummary(sessionId) {
817
- const session = getSessionState(sessionId);
818
- const history = session?.drift_history || [];
819
- if (!session || history.length === 0) {
820
- return { totalEvents: 0, resolved: true, finalScore: null, hadHalt: false };
821
- }
822
- const lastEvent = history[history.length - 1];
823
- return {
824
- totalEvents: history.length,
825
- resolved: lastEvent.score >= 8,
826
- finalScore: lastEvent.score,
827
- hadHalt: history.some(e => e.level === 'halt')
828
- };
829
- }
830
- // ============================================
831
- // FILE REASONING CRUD OPERATIONS
832
- // ============================================
833
- /**
834
- * Create a new file reasoning entry
835
- */
836
- export function createFileReasoning(input) {
837
- const database = initDatabase();
838
- const fileReasoning = {
839
- id: randomUUID(),
840
- task_id: input.task_id,
841
- file_path: input.file_path,
842
- anchor: input.anchor,
843
- line_start: input.line_start,
844
- line_end: input.line_end,
845
- code_hash: input.code_hash,
846
- change_type: input.change_type,
847
- reasoning: input.reasoning,
848
- created_at: new Date().toISOString()
849
- };
850
- const stmt = database.prepare(`
851
- INSERT INTO file_reasoning (
852
- id, task_id, file_path, anchor, line_start, line_end,
853
- code_hash, change_type, reasoning, created_at
854
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
855
- `);
856
- stmt.run(fileReasoning.id, fileReasoning.task_id || null, fileReasoning.file_path, fileReasoning.anchor || null, fileReasoning.line_start || null, fileReasoning.line_end || null, fileReasoning.code_hash || null, fileReasoning.change_type || null, fileReasoning.reasoning, fileReasoning.created_at);
857
- return fileReasoning;
858
- }
859
- /**
860
- * Get file reasoning entries for a task
861
- */
862
- export function getFileReasoningForTask(taskId) {
863
- const database = initDatabase();
864
- const stmt = database.prepare('SELECT * FROM file_reasoning WHERE task_id = ? ORDER BY created_at DESC');
865
- const rows = stmt.all(taskId);
866
- return rows.map(rowToFileReasoning);
867
- }
868
- /**
869
- * Get file reasoning entries by file path
870
- */
871
- export function getFileReasoningByPath(filePath, limit = 10) {
872
- const database = initDatabase();
873
- const stmt = database.prepare('SELECT * FROM file_reasoning WHERE file_path = ? ORDER BY created_at DESC LIMIT ?');
874
- const rows = stmt.all(filePath, limit);
875
- return rows.map(rowToFileReasoning);
876
- }
877
- /**
878
- * Get file reasoning entries matching a pattern (for files in a project).
879
- * SECURITY: Uses escaped LIKE patterns to prevent injection.
880
- */
881
- export function getFileReasoningByPathPattern(pathPattern, limit = 20) {
882
- const database = initDatabase();
883
- // Escape LIKE special characters to prevent injection
884
- const escapedPattern = escapeLikePattern(pathPattern);
885
- const stmt = database.prepare("SELECT * FROM file_reasoning WHERE file_path LIKE ? ESCAPE '\\' ORDER BY created_at DESC LIMIT ?");
886
- const rows = stmt.all(`%${escapedPattern}%`, limit);
887
- return rows.map(rowToFileReasoning);
888
- }
889
- /**
890
- * Convert database row to FileReasoning object
891
- */
892
- function rowToFileReasoning(row) {
893
- return {
894
- id: row.id,
895
- task_id: row.task_id,
896
- file_path: row.file_path,
897
- anchor: row.anchor,
898
- line_start: row.line_start,
899
- line_end: row.line_end,
900
- code_hash: row.code_hash,
901
- change_type: row.change_type,
902
- reasoning: row.reasoning,
903
- created_at: row.created_at
904
- };
905
- }
906
- /**
907
- * Get the database path
908
- */
909
- export function getDatabasePath() {
910
- return DB_PATH;
911
- }
912
- // ============================================
913
- // STEPS CRUD OPERATIONS (Proxy uses these)
914
- // ============================================
915
- /**
916
- * Create a new step record (proxy version)
917
- */
918
- export function createStep(input) {
919
- const database = initDatabase();
920
- const step = {
921
- id: randomUUID(),
922
- session_id: input.session_id,
923
- action_type: input.action_type,
924
- files: input.files || [],
925
- folders: input.folders || [],
926
- command: input.command,
927
- reasoning: input.reasoning,
928
- drift_score: input.drift_score,
929
- drift_type: input.drift_type,
930
- is_key_decision: input.is_key_decision || false,
931
- is_validated: input.is_validated !== false,
932
- correction_given: input.correction_given,
933
- correction_level: input.correction_level,
934
- keywords: input.keywords || [],
935
- timestamp: Date.now()
936
- };
937
- const stmt = database.prepare(`
938
- INSERT INTO steps (
939
- id, session_id, action_type, files, folders, command, reasoning,
940
- drift_score, drift_type, is_key_decision, is_validated,
941
- correction_given, correction_level, keywords, timestamp
942
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
943
- `);
944
- stmt.run(step.id, step.session_id, step.action_type, JSON.stringify(step.files), JSON.stringify(step.folders), step.command || null, step.reasoning || null, step.drift_score || null, step.drift_type || null, step.is_key_decision ? 1 : 0, step.is_validated ? 1 : 0, step.correction_given || null, step.correction_level || null, JSON.stringify(step.keywords), step.timestamp);
945
- return step;
946
- }
947
- /**
948
- * Get steps for a session
949
- */
950
- export function getStepsForSession(sessionId, limit) {
951
- const database = initDatabase();
952
- let sql = 'SELECT * FROM steps WHERE session_id = ? ORDER BY timestamp DESC';
953
- const params = [sessionId];
954
- if (limit) {
955
- sql += ' LIMIT ?';
956
- params.push(limit);
957
- }
958
- const stmt = database.prepare(sql);
959
- const rows = stmt.all(...params);
960
- return rows.map(rowToStep);
961
- }
962
- /**
963
- * Get recent steps for a session (most recent N)
964
- */
965
- export function getRecentSteps(sessionId, count = 10) {
966
- return getStepsForSession(sessionId, count);
967
- }
968
- /**
969
- * Get validated steps only (for summary generation)
970
- */
971
- export function getValidatedSteps(sessionId) {
972
- const database = initDatabase();
973
- const stmt = database.prepare('SELECT * FROM steps WHERE session_id = ? AND is_validated = 1 ORDER BY timestamp ASC');
974
- const rows = stmt.all(sessionId);
975
- return rows.map(rowToStep);
976
- }
977
- /**
978
- * Delete steps for a session
979
- */
980
- export function deleteStepsForSession(sessionId) {
981
- const database = initDatabase();
982
- database.prepare('DELETE FROM steps WHERE session_id = ?').run(sessionId);
983
- }
984
- /**
985
- * Update reasoning for recent steps that don't have reasoning yet
986
- * Called at end_turn to backfill reasoning from Claude's text response
987
- */
988
- export function updateRecentStepsReasoning(sessionId, reasoning, limit = 10) {
989
- const database = initDatabase();
990
- const stmt = database.prepare(`
991
- UPDATE steps
992
- SET reasoning = ?
993
- WHERE session_id = ?
994
- AND (reasoning IS NULL OR reasoning = '')
995
- AND id IN (
996
- SELECT id FROM steps
997
- WHERE session_id = ?
998
- ORDER BY timestamp DESC
999
- LIMIT ?
1000
- )
1001
- `);
1002
- const result = stmt.run(reasoning, sessionId, sessionId, limit);
1003
- return result.changes;
1004
- }
1005
- /**
1006
- * Get relevant steps (key decisions and write/edit actions) - proxy version
1007
- * Reference: plan_proxy_local.md Section 2.2
1008
- */
1009
- export function getRelevantStepsSimple(sessionId, limit = 20) {
1010
- const database = initDatabase();
1011
- const stmt = database.prepare(`
1012
- SELECT * FROM steps
1013
- WHERE session_id = ?
1014
- AND (is_key_decision = 1 OR action_type IN ('edit', 'write', 'bash'))
1015
- AND is_validated = 1
1016
- ORDER BY timestamp DESC
1017
- LIMIT ?
1018
- `);
1019
- const rows = stmt.all(sessionId, limit);
1020
- return rows.map(rowToStep);
1021
- }
1022
- /**
1023
- * Convert database row to StepRecord object (proxy version - all fields)
1024
- */
1025
- function rowToStep(row) {
1026
- return {
1027
- id: row.id,
1028
- session_id: row.session_id,
1029
- action_type: row.action_type,
1030
- files: safeJsonParse(row.files, []),
1031
- folders: safeJsonParse(row.folders, []),
1032
- command: row.command,
1033
- reasoning: row.reasoning,
1034
- drift_score: row.drift_score,
1035
- drift_type: row.drift_type,
1036
- is_key_decision: Boolean(row.is_key_decision),
1037
- is_validated: Boolean(row.is_validated),
1038
- correction_given: row.correction_given,
1039
- correction_level: row.correction_level,
1040
- keywords: safeJsonParse(row.keywords, []),
1041
- timestamp: row.timestamp
1042
- };
1043
- }
1044
- // ============================================
1045
- // STEPS CRUD (Hook uses these)
1046
- // ============================================
1047
- /**
1048
- * Save a Claude action as a step (hook version - uses ClaudeAction)
1049
- */
1050
- export function saveStep(sessionId, action, driftScore, isKeyDecision = false, keywords = []) {
1051
- const database = initDatabase();
1052
- // Extract folders from files
1053
- const folders = [...new Set(action.files
1054
- .map(f => f.split('/').slice(0, -1).join('/'))
1055
- .filter(f => f.length > 0))];
1056
- database.prepare(`
1057
- INSERT INTO steps (id, session_id, action_type, files, folders, command, drift_score, is_key_decision, keywords, timestamp)
1058
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1059
- `).run(randomUUID(), sessionId, action.type, JSON.stringify(action.files), JSON.stringify(folders), action.command || null, driftScore, isKeyDecision ? 1 : 0, JSON.stringify(keywords), action.timestamp);
1060
- }
1061
- /**
1062
- * Update last_checked_at timestamp for a session
1063
- */
1064
- export function updateLastChecked(sessionId, timestamp) {
1065
- const database = initDatabase();
1066
- database.prepare(`
1067
- UPDATE session_states SET last_checked_at = ? WHERE session_id = ?
1068
- `).run(timestamp, sessionId);
1069
- }
1070
- // ============================================
1071
- // 4-QUERY RETRIEVAL (Hook uses these - from deep_dive.md)
1072
- // ============================================
1073
- /**
1074
- * Get steps that touched specific files
1075
- */
1076
- export function getStepsByFiles(sessionId, files, limit = 5) {
1077
- if (files.length === 0)
1078
- return [];
1079
- const database = initDatabase();
1080
- const placeholders = files.map(() => `files LIKE ?`).join(' OR ');
1081
- const patterns = files.map(f => `%"${escapeLikePattern(f)}"%`);
1082
- const rows = database.prepare(`
1083
- SELECT * FROM steps
1084
- WHERE session_id = ? AND drift_score >= 5 AND (${placeholders})
1085
- ORDER BY timestamp DESC LIMIT ?
1086
- `).all(sessionId, ...patterns, limit);
1087
- return rows.map(rowToStepRecord);
1088
- }
1089
- /**
1090
- * Get steps that touched specific folders
1091
- */
1092
- export function getStepsByFolders(sessionId, folders, limit = 5) {
1093
- if (folders.length === 0)
1094
- return [];
1095
- const database = initDatabase();
1096
- const placeholders = folders.map(() => `folders LIKE ?`).join(' OR ');
1097
- const patterns = folders.map(f => `%"${escapeLikePattern(f)}"%`);
1098
- const rows = database.prepare(`
1099
- SELECT * FROM steps
1100
- WHERE session_id = ? AND drift_score >= 5 AND (${placeholders})
1101
- ORDER BY timestamp DESC LIMIT ?
1102
- `).all(sessionId, ...patterns, limit);
1103
- return rows.map(rowToStepRecord);
1104
- }
1105
- /**
1106
- * Get steps matching keywords
1107
- */
1108
- export function getStepsByKeywords(sessionId, keywords, limit = 5) {
1109
- if (keywords.length === 0)
1110
- return [];
1111
- const database = initDatabase();
1112
- const conditions = keywords.map(() => `keywords LIKE ?`).join(' OR ');
1113
- const patterns = keywords.map(k => `%"${escapeLikePattern(k)}"%`);
1114
- const rows = database.prepare(`
1115
- SELECT * FROM steps
1116
- WHERE session_id = ? AND drift_score >= 5 AND (${conditions})
1117
- ORDER BY timestamp DESC LIMIT ?
1118
- `).all(sessionId, ...patterns, limit);
1119
- return rows.map(rowToStepRecord);
1120
- }
1121
- /**
1122
- * Get key decision steps
1123
- */
1124
- export function getKeyDecisionSteps(sessionId, limit = 5) {
1125
- const database = initDatabase();
1126
- const rows = database.prepare(`
1127
- SELECT * FROM steps
1128
- WHERE session_id = ? AND is_key_decision = 1
1129
- ORDER BY timestamp DESC LIMIT ?
1130
- `).all(sessionId, limit);
1131
- return rows.map(rowToStepRecord);
1132
- }
1133
- /**
1134
- * Get steps reasoning by file path (for proxy team memory injection)
1135
- * Searches across ALL sessions, returns file-level reasoning from steps table
1136
- */
1137
- export function getStepsReasoningByPath(filePath, limit = 5) {
1138
- const database = initDatabase();
1139
- // Search steps where files JSON contains this path and reasoning exists
1140
- const pattern = `%"${escapeLikePattern(filePath)}"%`;
1141
- const rows = database.prepare(`
1142
- SELECT files, reasoning
1143
- FROM steps
1144
- WHERE files LIKE ? AND reasoning IS NOT NULL AND reasoning != ''
1145
- ORDER BY timestamp DESC
1146
- LIMIT ?
1147
- `).all(pattern, limit);
1148
- return rows.map(row => {
1149
- const files = safeJsonParse(row.files, []);
1150
- // Find the matching file path from the files array
1151
- const matchedFile = files.find(f => f.includes(filePath)) || filePath;
1152
- return {
1153
- file_path: matchedFile,
1154
- reasoning: row.reasoning,
1155
- };
1156
- });
1157
- }
1158
- /**
1159
- * Combined retrieval: runs all 4 queries and deduplicates (hook version)
1160
- * Priority: key decisions > files > folders > keywords
1161
- */
1162
- export function getRelevantSteps(sessionId, currentFiles, currentFolders, keywords, limit = 10) {
1163
- const byFiles = getStepsByFiles(sessionId, currentFiles, 5);
1164
- const byFolders = getStepsByFolders(sessionId, currentFolders, 5);
1165
- const byKeywords = getStepsByKeywords(sessionId, keywords, 5);
1166
- const keyDecisions = getKeyDecisionSteps(sessionId, 5);
1167
- const seen = new Set();
1168
- const results = [];
1169
- // Priority order: key decisions > files > folders > keywords
1170
- for (const step of [...keyDecisions, ...byFiles, ...byFolders, ...byKeywords]) {
1171
- if (!seen.has(step.id)) {
1172
- seen.add(step.id);
1173
- results.push(step);
1174
- if (results.length >= limit)
1175
- break;
1176
- }
1177
- }
1178
- return results;
1179
- }
1180
- /**
1181
- * Convert database row to StepRecord (hook version - basic fields)
1182
- */
1183
- function rowToStepRecord(row) {
1184
- return {
1185
- id: row.id,
1186
- session_id: row.session_id,
1187
- action_type: row.action_type,
1188
- files: safeJsonParse(row.files, []),
1189
- folders: safeJsonParse(row.folders, []),
1190
- command: row.command,
1191
- reasoning: row.reasoning,
1192
- drift_score: row.drift_score || 0,
1193
- drift_type: row.drift_type,
1194
- is_key_decision: Boolean(row.is_key_decision),
1195
- is_validated: Boolean(row.is_validated),
1196
- correction_given: row.correction_given,
1197
- correction_level: row.correction_level,
1198
- keywords: safeJsonParse(row.keywords, []),
1199
- timestamp: row.timestamp
1200
- };
1201
- }
1202
- // ============================================
1203
- // DRIFT LOG CRUD OPERATIONS (Proxy uses these)
1204
- // ============================================
1205
- /**
1206
- * Log a drift event (for rejected actions)
1207
- */
1208
- export function logDriftEvent(input) {
1209
- const database = initDatabase();
1210
- const entry = {
1211
- id: randomUUID(),
1212
- session_id: input.session_id,
1213
- timestamp: Date.now(),
1214
- action_type: input.action_type,
1215
- files: input.files || [],
1216
- drift_score: input.drift_score,
1217
- drift_reason: input.drift_reason,
1218
- correction_given: input.correction_given,
1219
- recovery_plan: input.recovery_plan
1220
- };
1221
- const stmt = database.prepare(`
1222
- INSERT INTO drift_log (
1223
- id, session_id, timestamp, action_type, files,
1224
- drift_score, drift_reason, correction_given, recovery_plan
1225
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1226
- `);
1227
- stmt.run(entry.id, entry.session_id, entry.timestamp, entry.action_type || null, JSON.stringify(entry.files), entry.drift_score, entry.drift_reason || null, entry.correction_given || null, entry.recovery_plan ? JSON.stringify(entry.recovery_plan) : null);
1228
- return entry;
1229
- }
1230
- /**
1231
- * Get drift log for a session
1232
- */
1233
- export function getDriftLog(sessionId, limit = 50) {
1234
- const database = initDatabase();
1235
- const stmt = database.prepare('SELECT * FROM drift_log WHERE session_id = ? ORDER BY timestamp DESC LIMIT ?');
1236
- const rows = stmt.all(sessionId, limit);
1237
- return rows.map(rowToDriftLogEntry);
1238
- }
1239
- /**
1240
- * Convert database row to DriftLogEntry object
1241
- */
1242
- function rowToDriftLogEntry(row) {
1243
- return {
1244
- id: row.id,
1245
- session_id: row.session_id,
1246
- timestamp: row.timestamp,
1247
- action_type: row.action_type,
1248
- files: safeJsonParse(row.files, []),
1249
- drift_score: row.drift_score,
1250
- drift_reason: row.drift_reason,
1251
- correction_given: row.correction_given,
1252
- recovery_plan: row.recovery_plan ? safeJsonParse(row.recovery_plan, {}) : undefined
1253
- };
1254
- }
1255
- // ============================================
1256
- // CONVENIENCE FUNCTIONS FOR PROXY
1257
- // ============================================
1258
- /**
1259
- * Update token count for a session
1260
- */
1261
- export function updateTokenCount(sessionId, tokenCount) {
1262
- updateSessionState(sessionId, { token_count: tokenCount });
1263
- }
1264
- /**
1265
- * Update session mode
1266
- */
1267
- export function updateSessionMode(sessionId, mode) {
1268
- updateSessionState(sessionId, { session_mode: mode });
1269
- }
1270
- /**
1271
- * Mark session as waiting for recovery
1272
- */
1273
- export function markWaitingForRecovery(sessionId, waiting) {
1274
- updateSessionState(sessionId, { waiting_for_recovery: waiting });
1275
- }
1276
- /**
1277
- * Increment escalation count
1278
- */
1279
- export function incrementEscalation(sessionId) {
1280
- const session = getSessionState(sessionId);
1281
- if (session) {
1282
- updateSessionState(sessionId, { escalation_count: session.escalation_count + 1 });
1283
- }
1284
- }
1285
- /**
1286
- * Update last clear timestamp and reset token count
1287
- */
1288
- export function markCleared(sessionId) {
1289
- updateSessionState(sessionId, {
1290
- last_clear_at: Date.now(),
1291
- token_count: 0
1292
- });
1293
- }
1294
- /**
1295
- * Mark session as completed (instead of deleting)
1296
- * Session will be cleaned up after 1 hour
1297
- */
1298
- export function markSessionCompleted(sessionId) {
1299
- const database = initDatabase();
1300
- const now = new Date().toISOString();
1301
- database.prepare(`
1302
- UPDATE session_states
1303
- SET status = 'completed', completed_at = ?, last_update = ?
1304
- WHERE session_id = ?
1305
- `).run(now, now, sessionId);
1306
- }
1307
- /**
1308
- * Cleanup sessions completed more than 24 hours ago
1309
- * Also deletes associated steps and drift_log entries
1310
- * Skips sessions that have active children (RESTRICT approach)
1311
- * Returns number of sessions cleaned up
1312
- */
1313
- export function cleanupOldCompletedSessions(maxAgeMs = 86400000) {
1314
- const database = initDatabase();
1315
- const cutoff = new Date(Date.now() - maxAgeMs).toISOString();
1316
- // Get sessions to cleanup, excluding those with active children
1317
- // RESTRICT approach: don't delete parent if children still active
1318
- const oldSessions = database.prepare(`
1319
- SELECT session_id FROM session_states
1320
- WHERE status = 'completed'
1321
- AND completed_at < ?
1322
- AND session_id NOT IN (
1323
- SELECT DISTINCT parent_session_id
1324
- FROM session_states
1325
- WHERE parent_session_id IS NOT NULL
1326
- AND status != 'completed'
1327
- )
1328
- `).all(cutoff);
1329
- if (oldSessions.length === 0) {
1330
- return 0;
1331
- }
1332
- // Delete in correct order to respect FK constraints
1333
- for (const session of oldSessions) {
1334
- // 1. Delete from drift_log (FK to session_states)
1335
- database.prepare('DELETE FROM drift_log WHERE session_id = ?').run(session.session_id);
1336
- // 2. Delete from steps (FK to session_states)
1337
- database.prepare('DELETE FROM steps WHERE session_id = ?').run(session.session_id);
1338
- // 3. Now safe to delete session_states
1339
- database.prepare('DELETE FROM session_states WHERE session_id = ?').run(session.session_id);
1340
- }
1341
- return oldSessions.length;
1342
- }
1343
- /**
1344
- * Get completed session for project (for new_task detection)
1345
- * Returns most recent completed session if exists
1346
- */
1347
- export function getCompletedSessionForProject(projectPath) {
1348
- const database = initDatabase();
1349
- const row = database.prepare(`
1350
- SELECT * FROM session_states
1351
- WHERE project_path = ? AND status = 'completed'
1352
- ORDER BY completed_at DESC
1353
- LIMIT 1
1354
- `).get(projectPath);
1355
- return row ? rowToSessionState(row) : null;
1356
- }
1
+ // Re-export from modular store for backward compatibility
2
+ export * from './store/index.js';