kiro-memory 2.1.0 → 3.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.
Files changed (33) hide show
  1. package/README.md +5 -1
  2. package/package.json +3 -3
  3. package/plugin/dist/cli/contextkit.js +2315 -180
  4. package/plugin/dist/hooks/agentSpawn.js +548 -49
  5. package/plugin/dist/hooks/kiro-hooks.js +548 -49
  6. package/plugin/dist/hooks/postToolUse.js +556 -56
  7. package/plugin/dist/hooks/stop.js +548 -49
  8. package/plugin/dist/hooks/userPromptSubmit.js +551 -50
  9. package/plugin/dist/index.js +549 -50
  10. package/plugin/dist/plugins/github/github-client.js +152 -0
  11. package/plugin/dist/plugins/github/index.js +412 -0
  12. package/plugin/dist/plugins/github/issue-parser.js +54 -0
  13. package/plugin/dist/plugins/slack/formatter.js +90 -0
  14. package/plugin/dist/plugins/slack/index.js +215 -0
  15. package/plugin/dist/sdk/index.js +548 -49
  16. package/plugin/dist/servers/mcp-server.js +4461 -397
  17. package/plugin/dist/services/search/EmbeddingService.js +64 -20
  18. package/plugin/dist/services/search/HybridSearch.js +380 -38
  19. package/plugin/dist/services/search/VectorSearch.js +65 -21
  20. package/plugin/dist/services/search/index.js +380 -38
  21. package/plugin/dist/services/sqlite/Backup.js +416 -0
  22. package/plugin/dist/services/sqlite/Database.js +71 -0
  23. package/plugin/dist/services/sqlite/ImportExport.js +452 -0
  24. package/plugin/dist/services/sqlite/Observations.js +291 -7
  25. package/plugin/dist/services/sqlite/Prompts.js +1 -1
  26. package/plugin/dist/services/sqlite/Search.js +10 -10
  27. package/plugin/dist/services/sqlite/Summaries.js +4 -4
  28. package/plugin/dist/services/sqlite/index.js +1323 -28
  29. package/plugin/dist/viewer.css +1 -1
  30. package/plugin/dist/viewer.js +16 -8
  31. package/plugin/dist/viewer.js.map +4 -4
  32. package/plugin/dist/worker-service.js +326 -75
  33. package/plugin/dist/worker-service.js.map +4 -4
@@ -16,6 +16,290 @@ var __export = (target, all) => {
16
16
  __defProp(target, name, { get: all[name], enumerable: true });
17
17
  };
18
18
 
19
+ // src/utils/secrets.ts
20
+ function redactSecrets(text) {
21
+ if (!text) return text;
22
+ let redacted = text;
23
+ for (const { pattern } of SECRET_PATTERNS) {
24
+ pattern.lastIndex = 0;
25
+ redacted = redacted.replace(pattern, (match) => {
26
+ const prefix = match.substring(0, Math.min(4, match.length));
27
+ return `${prefix}***REDACTED***`;
28
+ });
29
+ }
30
+ return redacted;
31
+ }
32
+ var SECRET_PATTERNS;
33
+ var init_secrets = __esm({
34
+ "src/utils/secrets.ts"() {
35
+ "use strict";
36
+ SECRET_PATTERNS = [
37
+ // AWS Access Keys (AKIA, ABIA, ACCA, ASIA prefixes + 16 alphanumeric chars)
38
+ { name: "aws-key", pattern: /(?:AKIA|ABIA|ACCA|ASIA)[A-Z0-9]{16}/g },
39
+ // JWT tokens (three base64url segments separated by dots)
40
+ { name: "jwt", pattern: /eyJ[a-zA-Z0-9_-]{10,}\.eyJ[a-zA-Z0-9_-]{10,}\.[a-zA-Z0-9_-]{10,}/g },
41
+ // Generic API keys in key=value or key: value assignments
42
+ { name: "api-key", pattern: /(?:api[_-]?key|apikey|api[_-]?secret)\s*[:=]\s*['"]?([a-zA-Z0-9_\-]{20,})['"]?/gi },
43
+ // Password/secret/token in variable assignments
44
+ { name: "credential", pattern: /(?:password|passwd|pwd|secret|token|auth[_-]?token|access[_-]?token|bearer)\s*[:=]\s*['"]?([^\s'"]{8,})['"]?/gi },
45
+ // Credentials embedded in URLs (user:pass@host)
46
+ { name: "url-credential", pattern: /(?:https?:\/\/)([^:]+):([^@]+)@/g },
47
+ // PEM-encoded private keys (RSA, EC, DSA, OpenSSH)
48
+ { name: "private-key", pattern: /-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----/g },
49
+ // GitHub personal access tokens (ghp_, gho_, ghu_, ghs_, ghr_ prefixes)
50
+ { name: "github-token", pattern: /gh[pousr]_[a-zA-Z0-9]{36,}/g },
51
+ // Slack bot/user/app tokens
52
+ { name: "slack-token", pattern: /xox[bpoas]-[a-zA-Z0-9-]{10,}/g },
53
+ // HTTP Authorization Bearer header values
54
+ { name: "bearer-header", pattern: /\bBearer\s+([a-zA-Z0-9_\-\.]{20,})/g },
55
+ // Generic hex secrets (32+ hex chars after a key/secret/token/password label)
56
+ { name: "hex-secret", pattern: /(?:key|secret|token|password)\s*[:=]\s*['"]?([0-9a-f]{32,})['"]?/gi }
57
+ ];
58
+ }
59
+ });
60
+
61
+ // src/utils/categorizer.ts
62
+ function categorize(input) {
63
+ const scores = /* @__PURE__ */ new Map();
64
+ const searchText = [
65
+ input.title,
66
+ input.text || "",
67
+ input.narrative || "",
68
+ input.concepts || ""
69
+ ].join(" ").toLowerCase();
70
+ const allFiles = [input.filesModified || "", input.filesRead || ""].join(",");
71
+ for (const rule of CATEGORY_RULES) {
72
+ let score = 0;
73
+ for (const kw of rule.keywords) {
74
+ if (searchText.includes(kw.toLowerCase())) {
75
+ score += rule.weight;
76
+ }
77
+ }
78
+ if (rule.types && rule.types.includes(input.type)) {
79
+ score += rule.weight * 2;
80
+ }
81
+ if (rule.filePatterns && allFiles) {
82
+ for (const pattern of rule.filePatterns) {
83
+ if (pattern.test(allFiles)) {
84
+ score += rule.weight;
85
+ }
86
+ }
87
+ }
88
+ if (score > 0) {
89
+ scores.set(rule.category, (scores.get(rule.category) || 0) + score);
90
+ }
91
+ }
92
+ let bestCategory = "general";
93
+ let bestScore = 0;
94
+ for (const [category, score] of scores) {
95
+ if (score > bestScore) {
96
+ bestScore = score;
97
+ bestCategory = category;
98
+ }
99
+ }
100
+ return bestCategory;
101
+ }
102
+ var CATEGORY_RULES;
103
+ var init_categorizer = __esm({
104
+ "src/utils/categorizer.ts"() {
105
+ "use strict";
106
+ CATEGORY_RULES = [
107
+ {
108
+ category: "security",
109
+ keywords: [
110
+ "security",
111
+ "vulnerability",
112
+ "cve",
113
+ "xss",
114
+ "csrf",
115
+ "injection",
116
+ "sanitize",
117
+ "escape",
118
+ "auth",
119
+ "authentication",
120
+ "authorization",
121
+ "permission",
122
+ "helmet",
123
+ "cors",
124
+ "rate-limit",
125
+ "token",
126
+ "encrypt",
127
+ "decrypt",
128
+ "secret",
129
+ "redact",
130
+ "owasp"
131
+ ],
132
+ filePatterns: [/security/i, /auth/i, /secrets?\.ts/i],
133
+ weight: 10
134
+ },
135
+ {
136
+ category: "testing",
137
+ keywords: [
138
+ "test",
139
+ "spec",
140
+ "expect",
141
+ "assert",
142
+ "mock",
143
+ "stub",
144
+ "fixture",
145
+ "coverage",
146
+ "jest",
147
+ "vitest",
148
+ "bun test",
149
+ "unit test",
150
+ "integration test",
151
+ "e2e"
152
+ ],
153
+ types: ["test"],
154
+ filePatterns: [/\.test\./i, /\.spec\./i, /tests?\//i, /__tests__/i],
155
+ weight: 8
156
+ },
157
+ {
158
+ category: "debugging",
159
+ keywords: [
160
+ "debug",
161
+ "fix",
162
+ "bug",
163
+ "error",
164
+ "crash",
165
+ "stacktrace",
166
+ "stack trace",
167
+ "exception",
168
+ "breakpoint",
169
+ "investigate",
170
+ "root cause",
171
+ "troubleshoot",
172
+ "diagnose",
173
+ "bisect",
174
+ "regression"
175
+ ],
176
+ types: ["bugfix"],
177
+ weight: 8
178
+ },
179
+ {
180
+ category: "architecture",
181
+ keywords: [
182
+ "architect",
183
+ "design",
184
+ "pattern",
185
+ "modular",
186
+ "migration",
187
+ "schema",
188
+ "database",
189
+ "api design",
190
+ "abstract",
191
+ "dependency injection",
192
+ "singleton",
193
+ "factory",
194
+ "observer",
195
+ "middleware",
196
+ "pipeline",
197
+ "microservice",
198
+ "monolith"
199
+ ],
200
+ types: ["decision", "constraint"],
201
+ weight: 7
202
+ },
203
+ {
204
+ category: "refactoring",
205
+ keywords: [
206
+ "refactor",
207
+ "rename",
208
+ "extract",
209
+ "inline",
210
+ "move",
211
+ "split",
212
+ "merge",
213
+ "simplify",
214
+ "cleanup",
215
+ "clean up",
216
+ "dead code",
217
+ "consolidate",
218
+ "reorganize",
219
+ "restructure",
220
+ "decouple"
221
+ ],
222
+ weight: 6
223
+ },
224
+ {
225
+ category: "config",
226
+ keywords: [
227
+ "config",
228
+ "configuration",
229
+ "env",
230
+ "environment",
231
+ "dotenv",
232
+ ".env",
233
+ "settings",
234
+ "tsconfig",
235
+ "eslint",
236
+ "prettier",
237
+ "webpack",
238
+ "vite",
239
+ "esbuild",
240
+ "docker",
241
+ "ci/cd",
242
+ "github actions",
243
+ "deploy",
244
+ "build",
245
+ "bundle",
246
+ "package.json"
247
+ ],
248
+ filePatterns: [
249
+ /\.config\./i,
250
+ /\.env/i,
251
+ /tsconfig/i,
252
+ /\.ya?ml/i,
253
+ /Dockerfile/i,
254
+ /docker-compose/i
255
+ ],
256
+ weight: 5
257
+ },
258
+ {
259
+ category: "docs",
260
+ keywords: [
261
+ "document",
262
+ "readme",
263
+ "changelog",
264
+ "jsdoc",
265
+ "comment",
266
+ "explain",
267
+ "guide",
268
+ "tutorial",
269
+ "api doc",
270
+ "openapi",
271
+ "swagger"
272
+ ],
273
+ types: ["docs"],
274
+ filePatterns: [/\.md$/i, /docs?\//i, /readme/i, /changelog/i],
275
+ weight: 5
276
+ },
277
+ {
278
+ category: "feature-dev",
279
+ keywords: [
280
+ "feature",
281
+ "implement",
282
+ "add",
283
+ "create",
284
+ "new",
285
+ "endpoint",
286
+ "component",
287
+ "module",
288
+ "service",
289
+ "handler",
290
+ "route",
291
+ "hook",
292
+ "plugin",
293
+ "integration"
294
+ ],
295
+ types: ["feature", "file-write"],
296
+ weight: 3
297
+ // lowest — generic catch-all for development
298
+ }
299
+ ];
300
+ }
301
+ });
302
+
19
303
  // src/services/sqlite/Observations.ts
20
304
  var Observations_exports = {};
21
305
  __export(Observations_exports, {
@@ -41,11 +325,23 @@ function isDuplicateObservation(db, contentHash, windowMs = 3e4) {
41
325
  }
42
326
  function createObservation(db, memorySessionId, project, type, title, subtitle, text, narrative, facts, concepts, filesRead, filesModified, promptNumber, contentHash = null, discoveryTokens = 0) {
43
327
  const now = /* @__PURE__ */ new Date();
328
+ const safeTitle = redactSecrets(title);
329
+ const safeText = text ? redactSecrets(text) : text;
330
+ const safeNarrative = narrative ? redactSecrets(narrative) : narrative;
331
+ const autoCategory = categorize({
332
+ type,
333
+ title: safeTitle,
334
+ text: safeText,
335
+ narrative: safeNarrative,
336
+ concepts,
337
+ filesModified,
338
+ filesRead
339
+ });
44
340
  const result = db.run(
45
341
  `INSERT INTO observations
46
- (memory_session_id, project, type, title, subtitle, text, narrative, facts, concepts, files_read, files_modified, prompt_number, created_at, created_at_epoch, content_hash, discovery_tokens)
47
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
48
- [memorySessionId, project, type, title, subtitle, text, narrative, facts, concepts, filesRead, filesModified, promptNumber, now.toISOString(), now.getTime(), contentHash, discoveryTokens]
342
+ (memory_session_id, project, type, title, subtitle, text, narrative, facts, concepts, files_read, files_modified, prompt_number, created_at, created_at_epoch, content_hash, discovery_tokens, auto_category)
343
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
344
+ [memorySessionId, project, type, safeTitle, subtitle, safeText, safeNarrative, facts, concepts, filesRead, filesModified, promptNumber, now.toISOString(), now.getTime(), contentHash, discoveryTokens, autoCategory]
49
345
  );
50
346
  return Number(result.lastInsertRowid);
51
347
  }
@@ -57,16 +353,16 @@ function getObservationsBySession(db, memorySessionId) {
57
353
  }
58
354
  function getObservationsByProject(db, project, limit = 100) {
59
355
  const query = db.query(
60
- "SELECT * FROM observations WHERE project = ? ORDER BY created_at_epoch DESC LIMIT ?"
356
+ "SELECT * FROM observations WHERE project = ? ORDER BY created_at_epoch DESC, id DESC LIMIT ?"
61
357
  );
62
358
  return query.all(project, limit);
63
359
  }
64
360
  function searchObservations(db, searchTerm, project) {
65
361
  const sql = project ? `SELECT * FROM observations
66
362
  WHERE project = ? AND (title LIKE ? ESCAPE '\\' OR text LIKE ? ESCAPE '\\' OR narrative LIKE ? ESCAPE '\\')
67
- ORDER BY created_at_epoch DESC` : `SELECT * FROM observations
363
+ ORDER BY created_at_epoch DESC, id DESC` : `SELECT * FROM observations
68
364
  WHERE title LIKE ? ESCAPE '\\' OR text LIKE ? ESCAPE '\\' OR narrative LIKE ? ESCAPE '\\'
69
- ORDER BY created_at_epoch DESC`;
365
+ ORDER BY created_at_epoch DESC, id DESC`;
70
366
  const pattern = `%${escapeLikePattern(searchTerm)}%`;
71
367
  const query = db.query(sql);
72
368
  if (project) {
@@ -122,7 +418,7 @@ function consolidateObservations(db, project, options = {}) {
122
418
  const obsIds = group.ids.split(",").map(Number);
123
419
  const placeholders = obsIds.map(() => "?").join(",");
124
420
  const observations = db.query(
125
- `SELECT * FROM observations WHERE id IN (${placeholders}) ORDER BY created_at_epoch DESC`
421
+ `SELECT * FROM observations WHERE id IN (${placeholders}) ORDER BY created_at_epoch DESC, id DESC`
126
422
  ).all(...obsIds);
127
423
  if (observations.length < minGroupSize) continue;
128
424
  const keeper = observations[0];
@@ -153,6 +449,8 @@ function consolidateObservations(db, project, options = {}) {
153
449
  var init_Observations = __esm({
154
450
  "src/services/sqlite/Observations.ts"() {
155
451
  "use strict";
452
+ init_secrets();
453
+ init_categorizer();
156
454
  }
157
455
  });
158
456
 
@@ -272,7 +570,7 @@ function searchObservationsLIKE(db, query, filters = {}) {
272
570
  sql += " AND created_at_epoch <= ?";
273
571
  params.push(filters.dateEnd);
274
572
  }
275
- sql += " ORDER BY created_at_epoch DESC LIMIT ?";
573
+ sql += " ORDER BY created_at_epoch DESC, id DESC LIMIT ?";
276
574
  params.push(limit);
277
575
  const stmt = db.query(sql);
278
576
  return stmt.all(...params);
@@ -297,7 +595,7 @@ function searchSummariesFiltered(db, query, filters = {}) {
297
595
  sql += " AND created_at_epoch <= ?";
298
596
  params.push(filters.dateEnd);
299
597
  }
300
- sql += " ORDER BY created_at_epoch DESC LIMIT ?";
598
+ sql += " ORDER BY created_at_epoch DESC, id DESC LIMIT ?";
301
599
  params.push(limit);
302
600
  const stmt = db.query(sql);
303
601
  return stmt.all(...params);
@@ -307,7 +605,7 @@ function getObservationsByIds(db, ids) {
307
605
  const validIds = ids.filter((id) => typeof id === "number" && Number.isInteger(id) && id > 0).slice(0, 500);
308
606
  if (validIds.length === 0) return [];
309
607
  const placeholders = validIds.map(() => "?").join(",");
310
- const sql = `SELECT * FROM observations WHERE id IN (${placeholders}) ORDER BY created_at_epoch DESC`;
608
+ const sql = `SELECT * FROM observations WHERE id IN (${placeholders}) ORDER BY created_at_epoch DESC, id DESC`;
311
609
  const stmt = db.query(sql);
312
610
  return stmt.all(...validIds);
313
611
  }
@@ -319,11 +617,11 @@ function getTimeline(db, anchorId, depthBefore = 5, depthAfter = 5) {
319
617
  const beforeStmt = db.query(`
320
618
  SELECT id, 'observation' as type, title, text as content, project, created_at, created_at_epoch
321
619
  FROM observations
322
- WHERE created_at_epoch < ?
323
- ORDER BY created_at_epoch DESC
620
+ WHERE (created_at_epoch < ? OR (created_at_epoch = ? AND id < ?))
621
+ ORDER BY created_at_epoch DESC, id DESC
324
622
  LIMIT ?
325
623
  `);
326
- const before = beforeStmt.all(anchorEpoch, depthBefore).reverse();
624
+ const before = beforeStmt.all(anchorEpoch, anchorEpoch, anchorId, depthBefore).reverse();
327
625
  const selfStmt = db.query(`
328
626
  SELECT id, 'observation' as type, title, text as content, project, created_at, created_at_epoch
329
627
  FROM observations WHERE id = ?
@@ -332,11 +630,11 @@ function getTimeline(db, anchorId, depthBefore = 5, depthAfter = 5) {
332
630
  const afterStmt = db.query(`
333
631
  SELECT id, 'observation' as type, title, text as content, project, created_at, created_at_epoch
334
632
  FROM observations
335
- WHERE created_at_epoch > ?
336
- ORDER BY created_at_epoch ASC
633
+ WHERE (created_at_epoch > ? OR (created_at_epoch = ? AND id > ?))
634
+ ORDER BY created_at_epoch ASC, id ASC
337
635
  LIMIT ?
338
636
  `);
339
- const after = afterStmt.all(anchorEpoch, depthAfter);
637
+ const after = afterStmt.all(anchorEpoch, anchorEpoch, anchorId, depthAfter);
340
638
  return [...before, ...self, ...after];
341
639
  }
342
640
  function getProjectStats(db, project) {
@@ -379,7 +677,7 @@ function getStaleObservations(db, project) {
379
677
  const rows = db.query(`
380
678
  SELECT * FROM observations
381
679
  WHERE project = ? AND files_modified IS NOT NULL AND files_modified != ''
382
- ORDER BY created_at_epoch DESC
680
+ ORDER BY created_at_epoch DESC, id DESC
383
681
  LIMIT 500
384
682
  `).all(project);
385
683
  const staleObs = [];
@@ -1208,11 +1506,104 @@ var MigrationRunner = class {
1208
1506
  db.run("CREATE INDEX IF NOT EXISTS idx_summaries_project_epoch ON summaries(project, created_at_epoch DESC)");
1209
1507
  db.run("CREATE INDEX IF NOT EXISTS idx_prompts_project_epoch ON prompts(project, created_at_epoch DESC)");
1210
1508
  }
1509
+ },
1510
+ {
1511
+ version: 10,
1512
+ up: (db) => {
1513
+ db.run(`
1514
+ CREATE TABLE IF NOT EXISTS job_queue (
1515
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1516
+ type TEXT NOT NULL,
1517
+ status TEXT NOT NULL DEFAULT 'pending',
1518
+ payload TEXT,
1519
+ result TEXT,
1520
+ error TEXT,
1521
+ retry_count INTEGER DEFAULT 0,
1522
+ max_retries INTEGER DEFAULT 3,
1523
+ priority INTEGER DEFAULT 0,
1524
+ created_at TEXT NOT NULL,
1525
+ created_at_epoch INTEGER NOT NULL,
1526
+ started_at_epoch INTEGER,
1527
+ completed_at_epoch INTEGER
1528
+ )
1529
+ `);
1530
+ db.run("CREATE INDEX IF NOT EXISTS idx_jobs_status ON job_queue(status)");
1531
+ db.run("CREATE INDEX IF NOT EXISTS idx_jobs_type ON job_queue(type)");
1532
+ db.run("CREATE INDEX IF NOT EXISTS idx_jobs_priority ON job_queue(status, priority DESC, created_at_epoch ASC)");
1533
+ }
1534
+ },
1535
+ {
1536
+ version: 11,
1537
+ up: (db) => {
1538
+ db.run("ALTER TABLE observations ADD COLUMN auto_category TEXT");
1539
+ db.run("CREATE INDEX IF NOT EXISTS idx_observations_category ON observations(auto_category)");
1540
+ }
1541
+ },
1542
+ {
1543
+ version: 12,
1544
+ up: (db) => {
1545
+ db.run(`
1546
+ CREATE TABLE IF NOT EXISTS github_links (
1547
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1548
+ observation_id INTEGER,
1549
+ session_id TEXT,
1550
+ repo TEXT NOT NULL,
1551
+ issue_number INTEGER,
1552
+ pr_number INTEGER,
1553
+ event_type TEXT NOT NULL,
1554
+ action TEXT,
1555
+ title TEXT,
1556
+ url TEXT,
1557
+ author TEXT,
1558
+ created_at TEXT NOT NULL,
1559
+ created_at_epoch INTEGER NOT NULL,
1560
+ FOREIGN KEY (observation_id) REFERENCES observations(id)
1561
+ )
1562
+ `);
1563
+ db.run("CREATE INDEX IF NOT EXISTS idx_github_links_repo ON github_links(repo)");
1564
+ db.run("CREATE INDEX IF NOT EXISTS idx_github_links_obs ON github_links(observation_id)");
1565
+ db.run("CREATE INDEX IF NOT EXISTS idx_github_links_event ON github_links(event_type)");
1566
+ db.run("CREATE INDEX IF NOT EXISTS idx_github_links_repo_issue ON github_links(repo, issue_number)");
1567
+ db.run("CREATE INDEX IF NOT EXISTS idx_github_links_repo_pr ON github_links(repo, pr_number)");
1568
+ }
1569
+ },
1570
+ {
1571
+ version: 13,
1572
+ up: (db) => {
1573
+ db.run("CREATE INDEX IF NOT EXISTS idx_observations_keyset ON observations(created_at_epoch DESC, id DESC)");
1574
+ db.run("CREATE INDEX IF NOT EXISTS idx_observations_project_keyset ON observations(project, created_at_epoch DESC, id DESC)");
1575
+ db.run("CREATE INDEX IF NOT EXISTS idx_summaries_keyset ON summaries(created_at_epoch DESC, id DESC)");
1576
+ db.run("CREATE INDEX IF NOT EXISTS idx_summaries_project_keyset ON summaries(project, created_at_epoch DESC, id DESC)");
1577
+ db.run("CREATE INDEX IF NOT EXISTS idx_prompts_keyset ON prompts(created_at_epoch DESC, id DESC)");
1578
+ db.run("CREATE INDEX IF NOT EXISTS idx_prompts_project_keyset ON prompts(project, created_at_epoch DESC, id DESC)");
1579
+ }
1211
1580
  }
1212
1581
  ];
1213
1582
  }
1214
1583
  };
1215
1584
 
1585
+ // src/services/sqlite/cursor.ts
1586
+ function encodeCursor(id, epoch) {
1587
+ const raw = `${epoch}:${id}`;
1588
+ return Buffer.from(raw, "utf8").toString("base64url");
1589
+ }
1590
+ function decodeCursor(cursor) {
1591
+ try {
1592
+ const raw = Buffer.from(cursor, "base64url").toString("utf8");
1593
+ const colonIdx = raw.indexOf(":");
1594
+ if (colonIdx === -1) return null;
1595
+ const epochStr = raw.substring(0, colonIdx);
1596
+ const idStr = raw.substring(colonIdx + 1);
1597
+ const epoch = parseInt(epochStr, 10);
1598
+ const id = parseInt(idStr, 10);
1599
+ if (!Number.isInteger(epoch) || epoch <= 0) return null;
1600
+ if (!Number.isInteger(id) || id <= 0) return null;
1601
+ return { epoch, id };
1602
+ } catch {
1603
+ return null;
1604
+ }
1605
+ }
1606
+
1216
1607
  // src/services/sqlite/Sessions.ts
1217
1608
  function createSession(db, contentSessionId, project, userPrompt) {
1218
1609
  const now = /* @__PURE__ */ new Date();
@@ -1256,16 +1647,16 @@ function createSummary(db, sessionId, project, request, investigated, learned, c
1256
1647
  }
1257
1648
  function getSummariesByProject(db, project, limit = 50) {
1258
1649
  const query = db.query(
1259
- "SELECT * FROM summaries WHERE project = ? ORDER BY created_at_epoch DESC LIMIT ?"
1650
+ "SELECT * FROM summaries WHERE project = ? ORDER BY created_at_epoch DESC, id DESC LIMIT ?"
1260
1651
  );
1261
1652
  return query.all(project, limit);
1262
1653
  }
1263
1654
  function searchSummaries(db, searchTerm, project) {
1264
1655
  const sql = project ? `SELECT * FROM summaries
1265
1656
  WHERE project = ? AND (request LIKE ? ESCAPE '\\' OR learned LIKE ? ESCAPE '\\' OR completed LIKE ? ESCAPE '\\' OR notes LIKE ? ESCAPE '\\')
1266
- ORDER BY created_at_epoch DESC` : `SELECT * FROM summaries
1657
+ ORDER BY created_at_epoch DESC, id DESC` : `SELECT * FROM summaries
1267
1658
  WHERE request LIKE ? ESCAPE '\\' OR learned LIKE ? ESCAPE '\\' OR completed LIKE ? ESCAPE '\\' OR notes LIKE ? ESCAPE '\\'
1268
- ORDER BY created_at_epoch DESC`;
1659
+ ORDER BY created_at_epoch DESC, id DESC`;
1269
1660
  const pattern = `%${escapeLikePattern2(searchTerm)}%`;
1270
1661
  const query = db.query(sql);
1271
1662
  if (project) {
@@ -1287,7 +1678,7 @@ function createPrompt(db, contentSessionId, project, promptNumber, promptText) {
1287
1678
  }
1288
1679
  function getPromptsByProject(db, project, limit = 100) {
1289
1680
  const query = db.query(
1290
- "SELECT * FROM prompts WHERE project = ? ORDER BY created_at_epoch DESC LIMIT ?"
1681
+ "SELECT * FROM prompts WHERE project = ? ORDER BY created_at_epoch DESC, id DESC LIMIT ?"
1291
1682
  );
1292
1683
  return query.all(project, limit);
1293
1684
  }
@@ -1315,13 +1706,13 @@ function createCheckpoint(db, sessionId, project, data) {
1315
1706
  }
1316
1707
  function getLatestCheckpoint(db, sessionId) {
1317
1708
  const query = db.query(
1318
- "SELECT * FROM checkpoints WHERE session_id = ? ORDER BY created_at_epoch DESC LIMIT 1"
1709
+ "SELECT * FROM checkpoints WHERE session_id = ? ORDER BY created_at_epoch DESC, id DESC LIMIT 1"
1319
1710
  );
1320
1711
  return query.get(sessionId);
1321
1712
  }
1322
1713
  function getLatestCheckpointByProject(db, project) {
1323
1714
  const query = db.query(
1324
- "SELECT * FROM checkpoints WHERE project = ? ORDER BY created_at_epoch DESC LIMIT 1"
1715
+ "SELECT * FROM checkpoints WHERE project = ? ORDER BY created_at_epoch DESC, id DESC LIMIT 1"
1325
1716
  );
1326
1717
  return query.get(project);
1327
1718
  }
@@ -1383,9 +1774,9 @@ function getReportData(db, project, startEpoch, endEpoch) {
1383
1774
  const staleCount = (project ? db.query(staleSql).get(project, startEpoch, endEpoch)?.count : db.query(staleSql).get(startEpoch, endEpoch)?.count) || 0;
1384
1775
  const summarySql = project ? `SELECT learned, completed, next_steps FROM summaries
1385
1776
  WHERE project = ? AND created_at_epoch >= ? AND created_at_epoch <= ?
1386
- ORDER BY created_at_epoch DESC` : `SELECT learned, completed, next_steps FROM summaries
1777
+ ORDER BY created_at_epoch DESC, id DESC` : `SELECT learned, completed, next_steps FROM summaries
1387
1778
  WHERE created_at_epoch >= ? AND created_at_epoch <= ?
1388
- ORDER BY created_at_epoch DESC`;
1779
+ ORDER BY created_at_epoch DESC, id DESC`;
1389
1780
  const summaryRows = project ? db.query(summarySql).all(project, startEpoch, endEpoch) : db.query(summarySql).all(startEpoch, endEpoch);
1390
1781
  const topLearnings = [];
1391
1782
  const completedTasks = [];
@@ -1450,20 +1841,61 @@ function getReportData(db, project, startEpoch, endEpoch) {
1450
1841
  // src/services/sqlite/index.ts
1451
1842
  init_Search();
1452
1843
 
1844
+ // src/types/worker-types.ts
1845
+ var KNOWLEDGE_TYPES = ["constraint", "decision", "heuristic", "rejected"];
1846
+
1847
+ // src/services/sqlite/Retention.ts
1848
+ var KNOWLEDGE_TYPE_LIST = KNOWLEDGE_TYPES;
1849
+ var KNOWLEDGE_PLACEHOLDERS = KNOWLEDGE_TYPE_LIST.map(() => "?").join(", ");
1850
+
1453
1851
  // src/sdk/index.ts
1454
1852
  init_Observations();
1455
1853
  import { createHash } from "crypto";
1456
1854
  init_Search();
1457
1855
 
1458
1856
  // src/services/search/EmbeddingService.ts
1857
+ var MODEL_CONFIGS = {
1858
+ "all-MiniLM-L6-v2": {
1859
+ modelId: "Xenova/all-MiniLM-L6-v2",
1860
+ dimensions: 384
1861
+ },
1862
+ "jina-code-v2": {
1863
+ modelId: "jinaai/jina-embeddings-v2-base-code",
1864
+ dimensions: 768
1865
+ },
1866
+ "bge-small-en": {
1867
+ modelId: "BAAI/bge-small-en-v1.5",
1868
+ dimensions: 384
1869
+ }
1870
+ };
1871
+ var FASTEMBED_COMPATIBLE_MODELS = /* @__PURE__ */ new Set(["all-MiniLM-L6-v2", "bge-small-en"]);
1459
1872
  var EmbeddingService = class {
1460
1873
  provider = null;
1461
1874
  model = null;
1462
1875
  initialized = false;
1463
1876
  initializing = null;
1877
+ config;
1878
+ configName;
1879
+ constructor() {
1880
+ const envModel = process.env.KIRO_MEMORY_EMBEDDING_MODEL || "all-MiniLM-L6-v2";
1881
+ this.configName = envModel;
1882
+ if (MODEL_CONFIGS[envModel]) {
1883
+ this.config = MODEL_CONFIGS[envModel];
1884
+ } else if (envModel.includes("/")) {
1885
+ const dimensions = parseInt(process.env.KIRO_MEMORY_EMBEDDING_DIMENSIONS || "384", 10);
1886
+ this.config = {
1887
+ modelId: envModel,
1888
+ dimensions: isNaN(dimensions) ? 384 : dimensions
1889
+ };
1890
+ } else {
1891
+ logger.warn("EMBEDDING", `Unknown model name '${envModel}', falling back to 'all-MiniLM-L6-v2'`);
1892
+ this.configName = "all-MiniLM-L6-v2";
1893
+ this.config = MODEL_CONFIGS["all-MiniLM-L6-v2"];
1894
+ }
1895
+ }
1464
1896
  /**
1465
1897
  * Initialize the embedding service.
1466
- * Tries fastembed, then @huggingface/transformers, then fallback to null.
1898
+ * Tries fastembed (when compatible), then @huggingface/transformers, then falls back to null.
1467
1899
  */
1468
1900
  async initialize() {
1469
1901
  if (this.initialized) return this.provider !== null;
@@ -1474,32 +1906,35 @@ var EmbeddingService = class {
1474
1906
  return result;
1475
1907
  }
1476
1908
  async _doInitialize() {
1477
- try {
1478
- const fastembed = await import("fastembed");
1479
- const EmbeddingModel = fastembed.EmbeddingModel || fastembed.default?.EmbeddingModel;
1480
- const FlagEmbedding = fastembed.FlagEmbedding || fastembed.default?.FlagEmbedding;
1481
- if (FlagEmbedding && EmbeddingModel) {
1482
- this.model = await FlagEmbedding.init({
1483
- model: EmbeddingModel.BGESmallENV15
1484
- });
1485
- this.provider = "fastembed";
1486
- this.initialized = true;
1487
- logger.info("EMBEDDING", "Initialized with fastembed (BGE-small-en-v1.5)");
1488
- return true;
1909
+ const fastembedCompatible = FASTEMBED_COMPATIBLE_MODELS.has(this.configName);
1910
+ if (fastembedCompatible) {
1911
+ try {
1912
+ const fastembed = await import("fastembed");
1913
+ const EmbeddingModel = fastembed.EmbeddingModel || fastembed.default?.EmbeddingModel;
1914
+ const FlagEmbedding = fastembed.FlagEmbedding || fastembed.default?.FlagEmbedding;
1915
+ if (FlagEmbedding && EmbeddingModel) {
1916
+ this.model = await FlagEmbedding.init({
1917
+ model: EmbeddingModel.BGESmallENV15
1918
+ });
1919
+ this.provider = "fastembed";
1920
+ this.initialized = true;
1921
+ logger.info("EMBEDDING", `Initialized with fastembed (BGE-small-en-v1.5) for model '${this.configName}'`);
1922
+ return true;
1923
+ }
1924
+ } catch (error) {
1925
+ logger.debug("EMBEDDING", `fastembed not available: ${error}`);
1489
1926
  }
1490
- } catch (error) {
1491
- logger.debug("EMBEDDING", `fastembed not available: ${error}`);
1492
1927
  }
1493
1928
  try {
1494
1929
  const transformers = await import("@huggingface/transformers");
1495
1930
  const pipeline = transformers.pipeline || transformers.default?.pipeline;
1496
1931
  if (pipeline) {
1497
- this.model = await pipeline("feature-extraction", "Xenova/all-MiniLM-L6-v2", {
1932
+ this.model = await pipeline("feature-extraction", this.config.modelId, {
1498
1933
  quantized: true
1499
1934
  });
1500
1935
  this.provider = "transformers";
1501
1936
  this.initialized = true;
1502
- logger.info("EMBEDDING", "Initialized with @huggingface/transformers (all-MiniLM-L6-v2)");
1937
+ logger.info("EMBEDDING", `Initialized with @huggingface/transformers (${this.config.modelId})`);
1503
1938
  return true;
1504
1939
  }
1505
1940
  } catch (error) {
@@ -1512,7 +1947,7 @@ var EmbeddingService = class {
1512
1947
  }
1513
1948
  /**
1514
1949
  * Generate embedding for a single text.
1515
- * Returns Float32Array with 384 dimensions, or null if not available.
1950
+ * Returns Float32Array with configured dimensions, or null if not available.
1516
1951
  */
1517
1952
  async embed(text) {
1518
1953
  if (!this.initialized) await this.initialize();
@@ -1563,10 +1998,17 @@ var EmbeddingService = class {
1563
1998
  return this.provider;
1564
1999
  }
1565
2000
  /**
1566
- * Embedding vector dimensions.
2001
+ * Embedding vector dimensions for the active model configuration.
1567
2002
  */
1568
2003
  getDimensions() {
1569
- return 384;
2004
+ return this.config.dimensions;
2005
+ }
2006
+ /**
2007
+ * Human-readable model name used as identifier in the observation_embeddings table.
2008
+ * Returns the short name (e.g., 'all-MiniLM-L6-v2') or the full HF model ID for custom models.
2009
+ */
2010
+ getModelName() {
2011
+ return this.configName;
1570
2012
  }
1571
2013
  // --- Batch implementations ---
1572
2014
  /**
@@ -1785,7 +2227,7 @@ var VectorSearch = class {
1785
2227
  `).all(batchSize);
1786
2228
  if (rows.length === 0) return 0;
1787
2229
  let count = 0;
1788
- const model = embeddingService2.getProvider() || "unknown";
2230
+ const model = embeddingService2.getModelName();
1789
2231
  for (const row of rows) {
1790
2232
  const parts = [row.title];
1791
2233
  if (row.text) parts.push(row.text);
@@ -1963,9 +2405,6 @@ function getHybridSearch() {
1963
2405
  return hybridSearch;
1964
2406
  }
1965
2407
 
1966
- // src/types/worker-types.ts
1967
- var KNOWLEDGE_TYPES = ["constraint", "decision", "heuristic", "rejected"];
1968
-
1969
2408
  // src/sdk/index.ts
1970
2409
  var KiroMemorySDK = class {
1971
2410
  db;
@@ -2522,6 +2961,66 @@ var KiroMemorySDK = class {
2522
2961
  }
2523
2962
  return getReportData(this.db.db, this.project, startEpoch, endEpoch);
2524
2963
  }
2964
+ /**
2965
+ * Lista osservazioni con keyset pagination.
2966
+ * Restituisce un oggetto { data, next_cursor, has_more }.
2967
+ *
2968
+ * Esempio:
2969
+ * const page1 = await sdk.listObservations({ limit: 50 });
2970
+ * const page2 = await sdk.listObservations({ cursor: page1.next_cursor });
2971
+ */
2972
+ async listObservations(options = {}) {
2973
+ const limit = Math.min(Math.max(options.limit ?? 50, 1), 200);
2974
+ const project = options.project ?? this.project;
2975
+ let rows;
2976
+ if (options.cursor) {
2977
+ const decoded = decodeCursor(options.cursor);
2978
+ if (!decoded) throw new Error("Cursor non valido");
2979
+ const sql = project ? `SELECT * FROM observations
2980
+ WHERE project = ? AND (created_at_epoch < ? OR (created_at_epoch = ? AND id < ?))
2981
+ ORDER BY created_at_epoch DESC, id DESC
2982
+ LIMIT ?` : `SELECT * FROM observations
2983
+ WHERE (created_at_epoch < ? OR (created_at_epoch = ? AND id < ?))
2984
+ ORDER BY created_at_epoch DESC, id DESC
2985
+ LIMIT ?`;
2986
+ rows = project ? this.db.db.query(sql).all(project, decoded.epoch, decoded.epoch, decoded.id, limit) : this.db.db.query(sql).all(decoded.epoch, decoded.epoch, decoded.id, limit);
2987
+ } else {
2988
+ const sql = project ? "SELECT * FROM observations WHERE project = ? ORDER BY created_at_epoch DESC, id DESC LIMIT ?" : "SELECT * FROM observations ORDER BY created_at_epoch DESC, id DESC LIMIT ?";
2989
+ rows = project ? this.db.db.query(sql).all(project, limit) : this.db.db.query(sql).all(limit);
2990
+ }
2991
+ const next_cursor = rows.length >= limit ? encodeCursor(rows[rows.length - 1].id, rows[rows.length - 1].created_at_epoch) : null;
2992
+ return { data: rows, next_cursor, has_more: next_cursor !== null };
2993
+ }
2994
+ /**
2995
+ * Lista sommari con keyset pagination.
2996
+ * Restituisce un oggetto { data, next_cursor, has_more }.
2997
+ *
2998
+ * Esempio:
2999
+ * const page1 = await sdk.listSummaries({ limit: 20 });
3000
+ * const page2 = await sdk.listSummaries({ cursor: page1.next_cursor });
3001
+ */
3002
+ async listSummaries(options = {}) {
3003
+ const limit = Math.min(Math.max(options.limit ?? 20, 1), 200);
3004
+ const project = options.project ?? this.project;
3005
+ let rows;
3006
+ if (options.cursor) {
3007
+ const decoded = decodeCursor(options.cursor);
3008
+ if (!decoded) throw new Error("Cursor non valido");
3009
+ const sql = project ? `SELECT * FROM summaries
3010
+ WHERE project = ? AND (created_at_epoch < ? OR (created_at_epoch = ? AND id < ?))
3011
+ ORDER BY created_at_epoch DESC, id DESC
3012
+ LIMIT ?` : `SELECT * FROM summaries
3013
+ WHERE (created_at_epoch < ? OR (created_at_epoch = ? AND id < ?))
3014
+ ORDER BY created_at_epoch DESC, id DESC
3015
+ LIMIT ?`;
3016
+ rows = project ? this.db.db.query(sql).all(project, decoded.epoch, decoded.epoch, decoded.id, limit) : this.db.db.query(sql).all(decoded.epoch, decoded.epoch, decoded.id, limit);
3017
+ } else {
3018
+ const sql = project ? "SELECT * FROM summaries WHERE project = ? ORDER BY created_at_epoch DESC, id DESC LIMIT ?" : "SELECT * FROM summaries ORDER BY created_at_epoch DESC, id DESC LIMIT ?";
3019
+ rows = project ? this.db.db.query(sql).all(project, limit) : this.db.db.query(sql).all(limit);
3020
+ }
3021
+ const next_cursor = rows.length >= limit ? encodeCursor(rows[rows.length - 1].id, rows[rows.length - 1].created_at_epoch) : null;
3022
+ return { data: rows, next_cursor, has_more: next_cursor !== null };
3023
+ }
2525
3024
  /**
2526
3025
  * Getter for direct database access (for API routes)
2527
3026
  */
@@ -2540,6 +3039,7 @@ function createKiroMemory(config) {
2540
3039
  }
2541
3040
 
2542
3041
  // src/hooks/postToolUse.ts
3042
+ init_secrets();
2543
3043
  runHook("postToolUse", async (input) => {
2544
3044
  if (input.hook_event_name === "afterFileEdit" && !input.tool_name) {
2545
3045
  input.tool_name = "Write";
@@ -2564,10 +3064,10 @@ runHook("postToolUse", async (input) => {
2564
3064
  const concepts = extractConcepts(input.tool_name, input.tool_input, files);
2565
3065
  await sdk2.storeObservation({
2566
3066
  type: "file-read",
2567
- title,
3067
+ title: redactSecrets(title),
2568
3068
  subtitle,
2569
- content: files.length > 0 ? `Files: ${files.join(", ")}` : `Tool ${input.tool_name} executed`,
2570
- narrative,
3069
+ content: redactSecrets(files.length > 0 ? `Files: ${files.join(", ")}` : `Tool ${input.tool_name} executed`),
3070
+ narrative: redactSecrets(narrative),
2571
3071
  concepts: concepts.length > 0 ? concepts : void 0,
2572
3072
  filesRead: files
2573
3073
  });
@@ -2589,11 +3089,11 @@ runHook("postToolUse", async (input) => {
2589
3089
  const isWrite = type === "file-write";
2590
3090
  await sdk.storeObservation({
2591
3091
  type,
2592
- title,
3092
+ title: redactSecrets(title),
2593
3093
  subtitle,
2594
- content,
2595
- narrative,
2596
- facts: facts || void 0,
3094
+ content: redactSecrets(content),
3095
+ narrative: redactSecrets(narrative),
3096
+ facts: facts ? redactSecrets(facts) : void 0,
2597
3097
  concepts: concepts.length > 0 ? concepts : void 0,
2598
3098
  filesRead: isWrite ? void 0 : files,
2599
3099
  filesModified: isWrite ? files : void 0