kiro-memory 1.8.1 → 2.1.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.
@@ -4,14 +4,15 @@ import { createRequire } from 'module';const require = createRequire(import.meta
4
4
  import BetterSqlite3 from "better-sqlite3";
5
5
  var Database = class {
6
6
  _db;
7
+ _stmtCache = /* @__PURE__ */ new Map();
7
8
  constructor(path, options) {
8
9
  this._db = new BetterSqlite3(path, {
9
- // better-sqlite3 crea il file di default (non serve 'create')
10
+ // better-sqlite3 creates the file by default ('create' not needed)
10
11
  readonly: options?.readwrite === false ? true : false
11
12
  });
12
13
  }
13
14
  /**
14
- * Esegui una query SQL senza risultati
15
+ * Execute a SQL query without results
15
16
  */
16
17
  run(sql, params) {
17
18
  const stmt = this._db.prepare(sql);
@@ -19,51 +20,53 @@ var Database = class {
19
20
  return result;
20
21
  }
21
22
  /**
22
- * Prepara una query con interfaccia compatibile bun:sqlite
23
+ * Prepare a query with bun:sqlite-compatible interface.
24
+ * Returns a cached prepared statement for repeated queries.
23
25
  */
24
26
  query(sql) {
25
- return new BunQueryCompat(this._db, sql);
27
+ let cached = this._stmtCache.get(sql);
28
+ if (!cached) {
29
+ cached = new BunQueryCompat(this._db, sql);
30
+ this._stmtCache.set(sql, cached);
31
+ }
32
+ return cached;
26
33
  }
27
34
  /**
28
- * Crea una transazione
35
+ * Create a transaction
29
36
  */
30
37
  transaction(fn) {
31
38
  return this._db.transaction(fn);
32
39
  }
33
40
  /**
34
- * Chiudi la connessione
41
+ * Close the connection
35
42
  */
36
43
  close() {
44
+ this._stmtCache.clear();
37
45
  this._db.close();
38
46
  }
39
47
  };
40
48
  var BunQueryCompat = class {
41
- _db;
42
- _sql;
49
+ _stmt;
43
50
  constructor(db, sql) {
44
- this._db = db;
45
- this._sql = sql;
51
+ this._stmt = db.prepare(sql);
46
52
  }
47
53
  /**
48
- * Restituisce tutte le righe
54
+ * Returns all rows
49
55
  */
50
56
  all(...params) {
51
- const stmt = this._db.prepare(this._sql);
52
- return params.length > 0 ? stmt.all(...params) : stmt.all();
57
+ return params.length > 0 ? this._stmt.all(...params) : this._stmt.all();
53
58
  }
54
59
  /**
55
- * Restituisce la prima riga o null
60
+ * Returns the first row or null
56
61
  */
57
62
  get(...params) {
58
- const stmt = this._db.prepare(this._sql);
59
- return params.length > 0 ? stmt.get(...params) : stmt.get();
63
+ return params.length > 0 ? this._stmt.get(...params) : this._stmt.get();
60
64
  }
61
65
  /**
62
- * Esegui senza risultati
66
+ * Execute without results
63
67
  */
64
68
  run(...params) {
65
- const stmt = this._db.prepare(this._sql);
66
- return params.length > 0 ? stmt.run(...params) : stmt.run();
69
+ return params.length > 0 ? this._stmt.run(...params) : this._stmt.run();
67
70
  }
68
71
  };
69
72
 
@@ -324,150 +327,63 @@ function ensureDir(dirPath) {
324
327
  // src/services/sqlite/Database.ts
325
328
  var SQLITE_MMAP_SIZE_BYTES = 256 * 1024 * 1024;
326
329
  var SQLITE_CACHE_SIZE_PAGES = 1e4;
327
- var dbInstance = null;
328
330
  var KiroMemoryDatabase = class {
329
- db;
331
+ _db;
332
+ /**
333
+ * Readonly accessor for the underlying Database instance.
334
+ * Prefer using query() and run() proxy methods directly.
335
+ */
336
+ get db() {
337
+ return this._db;
338
+ }
330
339
  /**
331
- * @param dbPath - Percorso al file SQLite (default: DB_PATH)
332
- * @param skipMigrations - Se true, salta il migration runner (per hook ad alta frequenza)
340
+ * @param dbPath - Path to the SQLite file (default: DB_PATH)
341
+ * @param skipMigrations - If true, skip the migration runner (for high-frequency hooks)
333
342
  */
334
343
  constructor(dbPath = DB_PATH, skipMigrations = false) {
335
344
  if (dbPath !== ":memory:") {
336
345
  ensureDir(DATA_DIR);
337
346
  }
338
- this.db = new Database(dbPath, { create: true, readwrite: true });
339
- this.db.run("PRAGMA journal_mode = WAL");
340
- this.db.run("PRAGMA synchronous = NORMAL");
341
- this.db.run("PRAGMA foreign_keys = ON");
342
- this.db.run("PRAGMA temp_store = memory");
343
- this.db.run(`PRAGMA mmap_size = ${SQLITE_MMAP_SIZE_BYTES}`);
344
- this.db.run(`PRAGMA cache_size = ${SQLITE_CACHE_SIZE_PAGES}`);
347
+ this._db = new Database(dbPath, { create: true, readwrite: true });
348
+ this._db.run("PRAGMA journal_mode = WAL");
349
+ this._db.run("PRAGMA busy_timeout = 5000");
350
+ this._db.run("PRAGMA synchronous = NORMAL");
351
+ this._db.run("PRAGMA foreign_keys = ON");
352
+ this._db.run("PRAGMA temp_store = memory");
353
+ this._db.run(`PRAGMA mmap_size = ${SQLITE_MMAP_SIZE_BYTES}`);
354
+ this._db.run(`PRAGMA cache_size = ${SQLITE_CACHE_SIZE_PAGES}`);
345
355
  if (!skipMigrations) {
346
- const migrationRunner = new MigrationRunner(this.db);
356
+ const migrationRunner = new MigrationRunner(this._db);
347
357
  migrationRunner.runAllMigrations();
348
358
  }
349
359
  }
350
360
  /**
351
- * Esegue una funzione all'interno di una transazione atomica.
352
- * Se fn() lancia un errore, la transazione viene annullata automaticamente.
353
- */
354
- withTransaction(fn) {
355
- const transaction = this.db.transaction(fn);
356
- return transaction(this.db);
357
- }
358
- /**
359
- * Close the database connection
360
- */
361
- close() {
362
- this.db.close();
363
- }
364
- };
365
- var DatabaseManager = class _DatabaseManager {
366
- static instance;
367
- db = null;
368
- migrations = [];
369
- static getInstance() {
370
- if (!_DatabaseManager.instance) {
371
- _DatabaseManager.instance = new _DatabaseManager();
372
- }
373
- return _DatabaseManager.instance;
374
- }
375
- /**
376
- * Register a migration to be run during initialization
377
- */
378
- registerMigration(migration) {
379
- this.migrations.push(migration);
380
- this.migrations.sort((a, b) => a.version - b.version);
381
- }
382
- /**
383
- * Initialize database connection with optimized settings
361
+ * Prepare a query (delegates to underlying Database).
362
+ * Proxy method to avoid ctx.db.db.query() double access.
384
363
  */
385
- async initialize() {
386
- if (this.db) {
387
- return this.db;
388
- }
389
- ensureDir(DATA_DIR);
390
- this.db = new Database(DB_PATH, { create: true, readwrite: true });
391
- this.db.run("PRAGMA journal_mode = WAL");
392
- this.db.run("PRAGMA synchronous = NORMAL");
393
- this.db.run("PRAGMA foreign_keys = ON");
394
- this.db.run("PRAGMA temp_store = memory");
395
- this.db.run(`PRAGMA mmap_size = ${SQLITE_MMAP_SIZE_BYTES}`);
396
- this.db.run(`PRAGMA cache_size = ${SQLITE_CACHE_SIZE_PAGES}`);
397
- this.initializeSchemaVersions();
398
- await this.runMigrations();
399
- dbInstance = this.db;
400
- return this.db;
364
+ query(sql) {
365
+ return this._db.query(sql);
401
366
  }
402
367
  /**
403
- * Get the current database connection
368
+ * Execute a SQL statement without results (delegates to underlying Database).
369
+ * Proxy method to avoid ctx.db.db.run() double access.
404
370
  */
405
- getConnection() {
406
- if (!this.db) {
407
- throw new Error("Database not initialized. Call initialize() first.");
408
- }
409
- return this.db;
371
+ run(sql, params) {
372
+ return this._db.run(sql, params);
410
373
  }
411
374
  /**
412
- * Execute a function within a transaction
375
+ * Executes a function within an atomic transaction.
376
+ * If fn() throws an error, the transaction is automatically rolled back.
413
377
  */
414
378
  withTransaction(fn) {
415
- const db = this.getConnection();
416
- const transaction = db.transaction(fn);
417
- return transaction(db);
379
+ const transaction = this._db.transaction(fn);
380
+ return transaction(this._db);
418
381
  }
419
382
  /**
420
383
  * Close the database connection
421
384
  */
422
385
  close() {
423
- if (this.db) {
424
- this.db.close();
425
- this.db = null;
426
- dbInstance = null;
427
- }
428
- }
429
- /**
430
- * Initialize the schema_versions table
431
- */
432
- initializeSchemaVersions() {
433
- if (!this.db) return;
434
- this.db.run(`
435
- CREATE TABLE IF NOT EXISTS schema_versions (
436
- id INTEGER PRIMARY KEY,
437
- version INTEGER UNIQUE NOT NULL,
438
- applied_at TEXT NOT NULL
439
- )
440
- `);
441
- }
442
- /**
443
- * Run all pending migrations
444
- */
445
- async runMigrations() {
446
- if (!this.db) return;
447
- const query = this.db.query("SELECT version FROM schema_versions ORDER BY version");
448
- const appliedVersions = query.all().map((row) => row.version);
449
- const maxApplied = appliedVersions.length > 0 ? Math.max(...appliedVersions) : 0;
450
- for (const migration of this.migrations) {
451
- if (migration.version > maxApplied) {
452
- logger.info("DB", `Applying migration ${migration.version}`);
453
- const transaction = this.db.transaction(() => {
454
- migration.up(this.db);
455
- const insertQuery = this.db.query("INSERT INTO schema_versions (version, applied_at) VALUES (?, ?)");
456
- insertQuery.run(migration.version, (/* @__PURE__ */ new Date()).toISOString());
457
- });
458
- transaction();
459
- logger.info("DB", `Migration ${migration.version} applied successfully`);
460
- }
461
- }
462
- }
463
- /**
464
- * Get current schema version
465
- */
466
- getCurrentVersion() {
467
- if (!this.db) return 0;
468
- const query = this.db.query("SELECT MAX(version) as version FROM schema_versions");
469
- const result = query.get();
470
- return result?.version || 0;
386
+ this._db.close();
471
387
  }
472
388
  };
473
389
  var MigrationRunner = class {
@@ -712,21 +628,7 @@ var MigrationRunner = class {
712
628
  ];
713
629
  }
714
630
  };
715
- function getDatabase() {
716
- if (!dbInstance) {
717
- throw new Error("Database not initialized. Call DatabaseManager.getInstance().initialize() first.");
718
- }
719
- return dbInstance;
720
- }
721
- async function initializeDatabase() {
722
- const manager = DatabaseManager.getInstance();
723
- return await manager.initialize();
724
- }
725
631
  export {
726
- KiroMemoryDatabase as ContextKitDatabase,
727
632
  Database,
728
- DatabaseManager,
729
- KiroMemoryDatabase,
730
- getDatabase,
731
- initializeDatabase
633
+ KiroMemoryDatabase
732
634
  };
@@ -72,9 +72,25 @@ function consolidateObservations(db, project, options = {}) {
72
72
  ORDER BY cnt DESC
73
73
  `).all(project, minGroupSize);
74
74
  if (groups.length === 0) return { merged: 0, removed: 0 };
75
- let totalMerged = 0;
76
- let totalRemoved = 0;
75
+ if (options.dryRun) {
76
+ let totalMerged = 0;
77
+ let totalRemoved = 0;
78
+ for (const group of groups) {
79
+ const obsIds = group.ids.split(",").map(Number);
80
+ const placeholders = obsIds.map(() => "?").join(",");
81
+ const count = db.query(
82
+ `SELECT COUNT(*) as cnt FROM observations WHERE id IN (${placeholders})`
83
+ ).get(...obsIds)?.cnt || 0;
84
+ if (count >= minGroupSize) {
85
+ totalMerged += 1;
86
+ totalRemoved += count - 1;
87
+ }
88
+ }
89
+ return { merged: totalMerged, removed: totalRemoved };
90
+ }
77
91
  const runConsolidation = db.transaction(() => {
92
+ let merged = 0;
93
+ let removed = 0;
78
94
  for (const group of groups) {
79
95
  const obsIds = group.ids.split(",").map(Number);
80
96
  const placeholders = obsIds.map(() => "?").join(",");
@@ -82,11 +98,6 @@ function consolidateObservations(db, project, options = {}) {
82
98
  `SELECT * FROM observations WHERE id IN (${placeholders}) ORDER BY created_at_epoch DESC`
83
99
  ).all(...obsIds);
84
100
  if (observations.length < minGroupSize) continue;
85
- if (options.dryRun) {
86
- totalMerged += 1;
87
- totalRemoved += observations.length - 1;
88
- continue;
89
- }
90
101
  const keeper = observations[0];
91
102
  const others = observations.slice(1);
92
103
  const uniqueTexts = /* @__PURE__ */ new Set();
@@ -99,18 +110,18 @@ function consolidateObservations(db, project, options = {}) {
99
110
  const consolidatedText = Array.from(uniqueTexts).join("\n---\n").substring(0, 1e5);
100
111
  db.run(
101
112
  "UPDATE observations SET text = ?, title = ? WHERE id = ?",
102
- [consolidatedText, `[consolidato x${observations.length}] ${keeper.title}`, keeper.id]
113
+ [consolidatedText, `[consolidated x${observations.length}] ${keeper.title}`, keeper.id]
103
114
  );
104
115
  const removeIds = others.map((o) => o.id);
105
116
  const removePlaceholders = removeIds.map(() => "?").join(",");
106
117
  db.run(`DELETE FROM observations WHERE id IN (${removePlaceholders})`, removeIds);
107
118
  db.run(`DELETE FROM observation_embeddings WHERE observation_id IN (${removePlaceholders})`, removeIds);
108
- totalMerged += 1;
109
- totalRemoved += removeIds.length;
119
+ merged += 1;
120
+ removed += removeIds.length;
110
121
  }
122
+ return { merged, removed };
111
123
  });
112
- runConsolidation();
113
- return { merged: totalMerged, removed: totalRemoved };
124
+ return runConsolidation();
114
125
  }
115
126
  export {
116
127
  consolidateObservations,
@@ -8,7 +8,7 @@ function escapeLikePattern(input) {
8
8
  }
9
9
  function sanitizeFTS5Query(query) {
10
10
  const trimmed = query.length > 1e4 ? query.substring(0, 1e4) : query;
11
- const terms = trimmed.replace(/[""]/g, "").split(/\s+/).filter((t) => t.length > 0).slice(0, 100).map((t) => `"${t}"`);
11
+ const terms = trimmed.replace(/[""\u0022]/g, "").split(/\s+/).filter((t) => t.length > 0).slice(0, 100).map((t) => `"${t}"`);
12
12
  return terms.join(" ");
13
13
  }
14
14
  function searchObservationsFTS(db, query, filters = {}) {
@@ -173,26 +173,38 @@ function getTimeline(db, anchorId, depthBefore = 5, depthAfter = 5) {
173
173
  return [...before, ...self, ...after];
174
174
  }
175
175
  function getProjectStats(db, project) {
176
- const obsStmt = db.query("SELECT COUNT(*) as count FROM observations WHERE project = ?");
177
- const sumStmt = db.query("SELECT COUNT(*) as count FROM summaries WHERE project = ?");
178
- const sesStmt = db.query("SELECT COUNT(*) as count FROM sessions WHERE project = ?");
179
- const prmStmt = db.query("SELECT COUNT(*) as count FROM prompts WHERE project = ?");
180
- const discoveryStmt = db.query(
181
- "SELECT COALESCE(SUM(discovery_tokens), 0) as total FROM observations WHERE project = ?"
182
- );
183
- const discoveryTokens = discoveryStmt.get(project)?.total || 0;
184
- const readStmt = db.query(
185
- `SELECT COALESCE(SUM(
186
- CAST((LENGTH(COALESCE(title, '')) + LENGTH(COALESCE(narrative, ''))) / 4 AS INTEGER)
187
- ), 0) as total FROM observations WHERE project = ?`
188
- );
189
- const readTokens = readStmt.get(project)?.total || 0;
176
+ const sql = `
177
+ WITH
178
+ obs_stats AS (
179
+ SELECT
180
+ COUNT(*) as count,
181
+ COALESCE(SUM(discovery_tokens), 0) as discovery_tokens,
182
+ COALESCE(SUM(
183
+ CAST((LENGTH(COALESCE(title, '')) + LENGTH(COALESCE(narrative, ''))) / 4 AS INTEGER)
184
+ ), 0) as read_tokens
185
+ FROM observations WHERE project = ?
186
+ ),
187
+ sum_count AS (SELECT COUNT(*) as count FROM summaries WHERE project = ?),
188
+ ses_count AS (SELECT COUNT(*) as count FROM sessions WHERE project = ?),
189
+ prm_count AS (SELECT COUNT(*) as count FROM prompts WHERE project = ?)
190
+ SELECT
191
+ obs_stats.count as observations,
192
+ obs_stats.discovery_tokens,
193
+ obs_stats.read_tokens,
194
+ sum_count.count as summaries,
195
+ ses_count.count as sessions,
196
+ prm_count.count as prompts
197
+ FROM obs_stats, sum_count, ses_count, prm_count
198
+ `;
199
+ const row = db.query(sql).get(project, project, project, project);
200
+ const discoveryTokens = row?.discovery_tokens || 0;
201
+ const readTokens = row?.read_tokens || 0;
190
202
  const savings = Math.max(0, discoveryTokens - readTokens);
191
203
  return {
192
- observations: obsStmt.get(project)?.count || 0,
193
- summaries: sumStmt.get(project)?.count || 0,
194
- sessions: sesStmt.get(project)?.count || 0,
195
- prompts: prmStmt.get(project)?.count || 0,
204
+ observations: row?.observations || 0,
205
+ summaries: row?.summaries || 0,
206
+ sessions: row?.sessions || 0,
207
+ prompts: row?.prompts || 0,
196
208
  tokenEconomics: { discoveryTokens, readTokens, savings }
197
209
  };
198
210
  }
@@ -46,6 +46,10 @@ function getActiveSessions(db) {
46
46
  const query = db.query("SELECT * FROM sessions WHERE status = 'active' ORDER BY started_at_epoch DESC");
47
47
  return query.all();
48
48
  }
49
+ function getAllSessions(db, limit = 100) {
50
+ const query = db.query("SELECT * FROM sessions ORDER BY started_at_epoch DESC LIMIT ?");
51
+ return query.all(limit);
52
+ }
49
53
  function getSessionsByProject(db, project, limit = 100) {
50
54
  const query = db.query("SELECT * FROM sessions WHERE project = ? ORDER BY started_at_epoch DESC LIMIT ?");
51
55
  return query.all(project, limit);
@@ -55,6 +59,7 @@ export {
55
59
  createSession,
56
60
  failSession,
57
61
  getActiveSessions,
62
+ getAllSessions,
58
63
  getSessionByContentId,
59
64
  getSessionById,
60
65
  getSessionsByProject,