kirograph 0.22.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -5
- package/dist/bin/commands/configure-mcp.js +104 -0
- package/dist/bin/commands/configure-mcp.js.map +7 -0
- package/dist/bin/commands/memory.js +334 -2
- package/dist/bin/commands/memory.js.map +2 -2
- package/dist/bin/commands/wiki.js +307 -0
- package/dist/bin/commands/wiki.js.map +7 -0
- package/dist/bin/installer/common.js +9 -0
- package/dist/bin/installer/common.js.map +2 -2
- package/dist/bin/installer/config-prompt.js +96 -5
- package/dist/bin/installer/config-prompt.js.map +2 -2
- package/dist/bin/installer/hooks.js +40 -0
- package/dist/bin/installer/hooks.js.map +2 -2
- package/dist/bin/installer/index.js +22 -11
- package/dist/bin/installer/index.js.map +2 -2
- package/dist/bin/installer/instructions.js +27 -1
- package/dist/bin/installer/instructions.js.map +2 -2
- package/dist/bin/installer/mcp.js +37 -4
- package/dist/bin/installer/mcp.js.map +2 -2
- package/dist/bin/installer/prompts.js +3 -3
- package/dist/bin/installer/prompts.js.map +2 -2
- package/dist/bin/installer/steering.js +633 -291
- package/dist/bin/installer/steering.js.map +2 -2
- package/dist/bin/installer/targets/index.js.map +1 -1
- package/dist/bin/installer/targets/kiro.js +5 -4
- package/dist/bin/installer/targets/kiro.js.map +2 -2
- package/dist/bin/kirograph.js +3 -1
- package/dist/bin/kirograph.js.map +3 -3
- package/dist/config.js +52 -5
- package/dist/config.js.map +2 -2
- package/dist/db/database.js +11 -0
- package/dist/db/database.js.map +2 -2
- package/dist/db/memory-schema.sql +34 -1
- package/dist/db/wiki-schema.sql +40 -0
- package/dist/mcp/server.js +35 -11
- package/dist/mcp/server.js.map +2 -2
- package/dist/mcp/tool-names.js +112 -1
- package/dist/mcp/tool-names.js.map +2 -2
- package/dist/mcp/tools.js +458 -3
- package/dist/mcp/tools.js.map +2 -2
- package/dist/memory/database.js +131 -7
- package/dist/memory/database.js.map +2 -2
- package/dist/memory/index.js +130 -4
- package/dist/memory/index.js.map +3 -3
- package/dist/memory/types.js.map +1 -1
- package/dist/watchmen/synthesize.js +2 -0
- package/dist/watchmen/synthesize.js.map +2 -2
- package/dist/wiki/database.js +143 -0
- package/dist/wiki/database.js.map +7 -0
- package/dist/wiki/index.js +149 -0
- package/dist/wiki/index.js.map +7 -0
- package/dist/wiki/ingest.js +259 -0
- package/dist/wiki/ingest.js.map +7 -0
- package/dist/wiki/lint.js +93 -0
- package/dist/wiki/lint.js.map +7 -0
- package/dist/wiki/schema.js +148 -0
- package/dist/wiki/schema.js.map +7 -0
- package/dist/wiki/synthesize.js +104 -0
- package/dist/wiki/synthesize.js.map +7 -0
- package/dist/wiki/types.js +17 -0
- package/dist/wiki/types.js.map +7 -0
- package/package.json +5 -3
package/dist/memory/database.js
CHANGED
|
@@ -54,6 +54,7 @@ class MemoryDatabase {
|
|
|
54
54
|
const sql = fs.readFileSync(schemaPath, "utf8");
|
|
55
55
|
this.db.exec(sql);
|
|
56
56
|
this.migrateTemporalColumns();
|
|
57
|
+
this.migrateRelationsAndPrompts();
|
|
57
58
|
this.initialized = true;
|
|
58
59
|
}
|
|
59
60
|
/**
|
|
@@ -65,7 +66,9 @@ class MemoryDatabase {
|
|
|
65
66
|
{ name: "valid_from", type: "INTEGER" },
|
|
66
67
|
{ name: "valid_until", type: "INTEGER" },
|
|
67
68
|
{ name: "superseded_by", type: "TEXT" },
|
|
68
|
-
{ name: "fact_type", type: "TEXT DEFAULT 'observation'" }
|
|
69
|
+
{ name: "fact_type", type: "TEXT DEFAULT 'observation'" },
|
|
70
|
+
{ name: "topic_key", type: "TEXT" },
|
|
71
|
+
{ name: "review_after", type: "INTEGER" }
|
|
69
72
|
];
|
|
70
73
|
for (const col of columnsToAdd) {
|
|
71
74
|
try {
|
|
@@ -74,6 +77,33 @@ class MemoryDatabase {
|
|
|
74
77
|
}
|
|
75
78
|
}
|
|
76
79
|
}
|
|
80
|
+
migrateRelationsAndPrompts() {
|
|
81
|
+
this.db.exec(`
|
|
82
|
+
CREATE TABLE IF NOT EXISTS mem_relations (
|
|
83
|
+
id TEXT PRIMARY KEY,
|
|
84
|
+
observation_a TEXT NOT NULL REFERENCES mem_observations(id) ON DELETE CASCADE,
|
|
85
|
+
observation_b TEXT NOT NULL REFERENCES mem_observations(id) ON DELETE CASCADE,
|
|
86
|
+
relation TEXT NOT NULL,
|
|
87
|
+
confidence REAL NOT NULL DEFAULT 1.0,
|
|
88
|
+
reason TEXT,
|
|
89
|
+
evidence TEXT,
|
|
90
|
+
judgment_status TEXT NOT NULL DEFAULT 'pending',
|
|
91
|
+
judged_at INTEGER,
|
|
92
|
+
created_at INTEGER NOT NULL,
|
|
93
|
+
UNIQUE(observation_a, observation_b)
|
|
94
|
+
);
|
|
95
|
+
CREATE INDEX IF NOT EXISTS idx_mem_rel_a ON mem_relations(observation_a);
|
|
96
|
+
CREATE INDEX IF NOT EXISTS idx_mem_rel_b ON mem_relations(observation_b);
|
|
97
|
+
CREATE INDEX IF NOT EXISTS idx_mem_rel_status ON mem_relations(judgment_status);
|
|
98
|
+
CREATE TABLE IF NOT EXISTS mem_prompts (
|
|
99
|
+
id TEXT PRIMARY KEY,
|
|
100
|
+
session_id TEXT REFERENCES mem_sessions(id) ON DELETE CASCADE,
|
|
101
|
+
content TEXT NOT NULL,
|
|
102
|
+
created_at INTEGER NOT NULL
|
|
103
|
+
);
|
|
104
|
+
CREATE INDEX IF NOT EXISTS idx_mem_prompts_session ON mem_prompts(session_id);
|
|
105
|
+
`);
|
|
106
|
+
}
|
|
77
107
|
// ── Watchmen ─────────────────────────────────────────────────────────────
|
|
78
108
|
/**
|
|
79
109
|
* Count non-summary observations created after the most recent summary.
|
|
@@ -166,9 +196,9 @@ class MemoryDatabase {
|
|
|
166
196
|
const now = Date.now();
|
|
167
197
|
try {
|
|
168
198
|
this.db.run(
|
|
169
|
-
`INSERT INTO mem_observations (id, session_id, content, content_raw, content_hash, kind, source, tags, created_at)
|
|
170
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
171
|
-
[id, opts.sessionId ?? null, content, opts.contentRaw ?? null, contentHash, kind, source, tags, now]
|
|
199
|
+
`INSERT INTO mem_observations (id, session_id, content, content_raw, content_hash, kind, source, tags, created_at, topic_key, review_after)
|
|
200
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
201
|
+
[id, opts.sessionId ?? null, content, opts.contentRaw ?? null, contentHash, kind, source, tags, now, opts.topicKey ?? null, opts.reviewAfter ?? null]
|
|
172
202
|
);
|
|
173
203
|
} catch (err) {
|
|
174
204
|
if (err.message?.includes("UNIQUE constraint failed") || err.message?.includes("unique")) {
|
|
@@ -201,7 +231,7 @@ class MemoryDatabase {
|
|
|
201
231
|
// ── FTS Search ───────────────────────────────────────────────────────────
|
|
202
232
|
searchFTS(query, opts = {}) {
|
|
203
233
|
const { limit = 10, kind, sessionId, asOf } = opts;
|
|
204
|
-
const safe = query.replace(/\b(AND|OR|NOT)\b/g, " ").replace(/['"*()?\-+^~:{}
|
|
234
|
+
const safe = query.replace(/\b(AND|OR|NOT)\b/g, " ").replace(/['"*()?\-+^~:{}\\\.\/,\[\]]/g, " ").replace(/\s+/g, " ").trim();
|
|
205
235
|
if (!safe) return [];
|
|
206
236
|
const ftsQuery = safe + "*";
|
|
207
237
|
const safeLimit = Math.max(1, Math.floor(Number(limit)));
|
|
@@ -328,6 +358,94 @@ class MemoryDatabase {
|
|
|
328
358
|
deleteVectors() {
|
|
329
359
|
this.db.run("DELETE FROM mem_vectors");
|
|
330
360
|
}
|
|
361
|
+
// ── Relations ────────────────────────────────────────────────────────────
|
|
362
|
+
insertRelation(input) {
|
|
363
|
+
const id = generateId();
|
|
364
|
+
this.db.run(
|
|
365
|
+
`INSERT OR REPLACE INTO mem_relations (id, observation_a, observation_b, relation, confidence, reason, evidence, judgment_status, created_at)
|
|
366
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?)`,
|
|
367
|
+
[id, input.observationA, input.observationB, input.relation, input.confidence ?? 1, input.reason ?? null, input.evidence ?? null, Date.now()]
|
|
368
|
+
);
|
|
369
|
+
return id;
|
|
370
|
+
}
|
|
371
|
+
judgeRelation(id, relation, confidence, reason, evidence) {
|
|
372
|
+
this.db.run(
|
|
373
|
+
`UPDATE mem_relations SET relation = ?, confidence = ?, reason = ?, evidence = ?, judgment_status = 'judged', judged_at = ? WHERE id = ?`,
|
|
374
|
+
[relation, confidence, reason ?? null, evidence ?? null, Date.now(), id]
|
|
375
|
+
);
|
|
376
|
+
}
|
|
377
|
+
ignoreRelation(id) {
|
|
378
|
+
this.db.run(`UPDATE mem_relations SET judgment_status = 'ignored' WHERE id = ?`, [id]);
|
|
379
|
+
}
|
|
380
|
+
getPendingRelations(limit = 20) {
|
|
381
|
+
return this.db.all(
|
|
382
|
+
`SELECT * FROM mem_relations WHERE judgment_status = 'pending' ORDER BY created_at DESC LIMIT ?`,
|
|
383
|
+
[limit]
|
|
384
|
+
).map((row) => this.rowToRelation(row));
|
|
385
|
+
}
|
|
386
|
+
getRelationsForObservations(ids) {
|
|
387
|
+
if (ids.length === 0) return /* @__PURE__ */ new Map();
|
|
388
|
+
const placeholders = ids.map(() => "?").join(",");
|
|
389
|
+
const rows = this.db.all(
|
|
390
|
+
`SELECT * FROM mem_relations WHERE observation_a IN (${placeholders}) OR observation_b IN (${placeholders})`,
|
|
391
|
+
[...ids, ...ids]
|
|
392
|
+
);
|
|
393
|
+
const map = /* @__PURE__ */ new Map();
|
|
394
|
+
for (const row of rows) {
|
|
395
|
+
const rel = this.rowToRelation(row);
|
|
396
|
+
for (const obsId of [row.observation_a, row.observation_b]) {
|
|
397
|
+
if (ids.includes(obsId)) {
|
|
398
|
+
if (!map.has(obsId)) map.set(obsId, []);
|
|
399
|
+
map.get(obsId).push(rel);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
return map;
|
|
404
|
+
}
|
|
405
|
+
resolveObservationByTopicKey(topicKey) {
|
|
406
|
+
const row = this.db.get("SELECT * FROM mem_observations WHERE topic_key = ? LIMIT 1", [topicKey]);
|
|
407
|
+
return row ? this.rowToObservation(row) : null;
|
|
408
|
+
}
|
|
409
|
+
rowToRelation(row) {
|
|
410
|
+
return {
|
|
411
|
+
id: row.id,
|
|
412
|
+
observationA: row.observation_a,
|
|
413
|
+
observationB: row.observation_b,
|
|
414
|
+
relation: row.relation,
|
|
415
|
+
confidence: row.confidence,
|
|
416
|
+
reason: row.reason ?? void 0,
|
|
417
|
+
evidence: row.evidence ?? void 0,
|
|
418
|
+
judgmentStatus: row.judgment_status,
|
|
419
|
+
judgedAt: row.judged_at ?? void 0,
|
|
420
|
+
createdAt: row.created_at
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
// ── Review ────────────────────────────────────────────────────────────────
|
|
424
|
+
getObservationsForReview(limit = 20) {
|
|
425
|
+
const now = Date.now();
|
|
426
|
+
return this.db.all(
|
|
427
|
+
`SELECT * FROM mem_observations WHERE review_after IS NOT NULL AND review_after < ? AND superseded_by IS NULL ORDER BY review_after ASC LIMIT ?`,
|
|
428
|
+
[now, limit]
|
|
429
|
+
).map((row) => this.rowToObservation(row));
|
|
430
|
+
}
|
|
431
|
+
markReviewed(id) {
|
|
432
|
+
this.db.run(`UPDATE mem_observations SET review_after = NULL WHERE id = ?`, [id]);
|
|
433
|
+
}
|
|
434
|
+
// ── Prompts ───────────────────────────────────────────────────────────────
|
|
435
|
+
insertPrompt(sessionId, content) {
|
|
436
|
+
const id = generateId();
|
|
437
|
+
this.db.run(
|
|
438
|
+
`INSERT INTO mem_prompts (id, session_id, content, created_at) VALUES (?, ?, ?, ?)`,
|
|
439
|
+
[id, sessionId ?? null, content, Date.now()]
|
|
440
|
+
);
|
|
441
|
+
return id;
|
|
442
|
+
}
|
|
443
|
+
getPromptsBySession(sessionId, limit = 20) {
|
|
444
|
+
return this.db.all(
|
|
445
|
+
`SELECT * FROM mem_prompts WHERE session_id = ? ORDER BY created_at DESC LIMIT ?`,
|
|
446
|
+
[sessionId, limit]
|
|
447
|
+
).map((row) => ({ id: row.id, sessionId: row.session_id ?? void 0, content: row.content, createdAt: row.created_at }));
|
|
448
|
+
}
|
|
331
449
|
// ── Stats ────────────────────────────────────────────────────────────────
|
|
332
450
|
getStats(currentModel) {
|
|
333
451
|
const sessions = this.db.get("SELECT COUNT(*) as c FROM mem_sessions")?.c ?? 0;
|
|
@@ -336,6 +454,8 @@ class MemoryDatabase {
|
|
|
336
454
|
const links = this.db.get("SELECT COUNT(*) as c FROM mem_links")?.c ?? 0;
|
|
337
455
|
const vectors = this.db.get("SELECT COUNT(*) as c FROM mem_vectors")?.c ?? 0;
|
|
338
456
|
const mismatch = currentModel ? this.getVectorModelMismatch(currentModel) : 0;
|
|
457
|
+
const relations = this.db.get("SELECT COUNT(*) as c FROM mem_relations")?.c ?? 0;
|
|
458
|
+
const pendingConflicts = this.db.get("SELECT COUNT(*) as c FROM mem_relations WHERE judgment_status = 'pending'")?.c ?? 0;
|
|
339
459
|
return {
|
|
340
460
|
sessions,
|
|
341
461
|
activeSessions,
|
|
@@ -344,7 +464,9 @@ class MemoryDatabase {
|
|
|
344
464
|
vectors,
|
|
345
465
|
embeddableCount: observations,
|
|
346
466
|
modelMismatch: mismatch > 0,
|
|
347
|
-
currentModel
|
|
467
|
+
currentModel,
|
|
468
|
+
relations,
|
|
469
|
+
pendingConflicts
|
|
348
470
|
};
|
|
349
471
|
}
|
|
350
472
|
// ── Maintenance ──────────────────────────────────────────────────────────
|
|
@@ -432,7 +554,9 @@ class MemoryDatabase {
|
|
|
432
554
|
validFrom: row.valid_from ?? void 0,
|
|
433
555
|
validUntil: row.valid_until ?? void 0,
|
|
434
556
|
supersededBy: row.superseded_by ?? void 0,
|
|
435
|
-
factType: row.fact_type ?? void 0
|
|
557
|
+
factType: row.fact_type ?? void 0,
|
|
558
|
+
topicKey: row.topic_key ?? void 0,
|
|
559
|
+
reviewAfter: row.review_after ?? void 0
|
|
436
560
|
};
|
|
437
561
|
}
|
|
438
562
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/memory/database.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * KiroGraph Memory \u2014 Database layer\n *\n * Operates on mem_* tables within the same SQLite database as the code graph.\n * Completely isolated: no FK to core nodes/edges tables.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as crypto from 'crypto';\nimport type {\n MemSession,\n MemObservation,\n MemObservationInput,\n MemLink,\n ScoredObservation,\n MemSearchOptions,\n MemTimelineOptions,\n MemStats,\n} from './types';\n\n// \u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction generateId(): string {\n return crypto.randomUUID();\n}\n\nfunction hashContent(content: string): string {\n return crypto.createHash('sha256').update(content).digest('hex');\n}\n\n// \u2500\u2500 MemoryDatabase \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport class MemoryDatabase {\n private db: any;\n private initialized = false;\n\n constructor(db: any) {\n this.db = db;\n }\n\n /**\n * Apply memory schema. Called once when enableMemory is true.\n */\n initialize(): void {\n if (this.initialized) return;\n const schemaPath = path.join(__dirname, '../db/memory-schema.sql');\n const sql = fs.readFileSync(schemaPath, 'utf8');\n this.db.exec(sql);\n\n // Migration: add temporal columns if they don't exist (for existing databases)\n this.migrateTemporalColumns();\n\n this.initialized = true;\n }\n\n /**\n * Add temporal fact columns to mem_observations if missing.\n * Safe to run multiple times (uses IF NOT EXISTS pattern via try/catch).\n */\n private migrateTemporalColumns(): void {\n const columnsToAdd = [\n { name: 'valid_from', type: 'INTEGER' },\n { name: 'valid_until', type: 'INTEGER' },\n { name: 'superseded_by', type: 'TEXT' },\n { name: 'fact_type', type: \"TEXT DEFAULT 'observation'\" },\n ];\n\n for (const col of columnsToAdd) {\n try {\n this.db.exec(`ALTER TABLE mem_observations ADD COLUMN ${col.name} ${col.type}`);\n } catch {\n // Column already exists \u2014 ignore\n }\n }\n }\n\n // \u2500\u2500 Watchmen \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Count non-summary observations created after the most recent summary.\n * Used by WatchmenChecker to decide if synthesis should trigger.\n */\n countSinceLastSummary(): number {\n const lastSummary = this.db.get(\n `SELECT created_at FROM mem_observations WHERE kind = 'summary' ORDER BY created_at DESC LIMIT 1`\n ) as { created_at: number } | undefined;\n\n const since = lastSummary?.created_at ?? 0;\n const row = this.db.get(\n `SELECT COUNT(*) as count FROM mem_observations WHERE kind != 'summary' AND created_at > ?`,\n [since]\n ) as { count: number };\n\n return row?.count ?? 0;\n }\n\n getObservationsSinceLastSummary(limit = 50): MemObservation[] {\n const lastSummary = this.db.get(\n `SELECT created_at FROM mem_observations WHERE kind = 'summary' ORDER BY created_at DESC LIMIT 1`\n ) as { created_at: number } | undefined;\n\n const since = lastSummary?.created_at ?? 0;\n const rows = this.db.all(\n `SELECT * FROM mem_observations WHERE kind != 'summary' AND created_at > ?\n ORDER BY created_at DESC LIMIT ?`,\n [since, limit]\n ) as any[];\n\n return rows.map(row => ({\n id: row.id,\n sessionId: row.session_id ?? undefined,\n content: row.content,\n contentRaw: row.content_raw ?? undefined,\n contentHash: row.content_hash,\n kind: row.kind,\n source: row.source,\n tags: row.tags ? JSON.parse(row.tags) : undefined,\n createdAt: row.created_at,\n }));\n }\n\n // \u2500\u2500 Sessions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Get or create an active session. Auto-creates if no active session exists\n * within the timeout window.\n */\n getOrCreateSession(ide: string, cwd: string, timeoutSeconds = 7200): string {\n const cutoff = Date.now() - (timeoutSeconds * 1000);\n\n // Look for an active session (no ended_at, same ide, started within timeout)\n const existing = this.db.get(\n `SELECT id FROM mem_sessions\n WHERE ended_at IS NULL AND ide = ? AND started_at > ?\n ORDER BY started_at DESC LIMIT 1`,\n [ide, cutoff]\n );\n\n if (existing) return existing.id;\n\n // Auto-close any stale sessions for this IDE\n this.db.run(\n `UPDATE mem_sessions SET ended_at = ? WHERE ended_at IS NULL AND ide = ?`,\n [Date.now(), ide]\n );\n\n // Create new session\n const id = generateId();\n this.db.run(\n `INSERT INTO mem_sessions (id, ide, cwd, started_at) VALUES (?, ?, ?, ?)`,\n [id, ide, cwd, Date.now()]\n );\n return id;\n }\n\n endSession(sessionId: string): void {\n this.db.run(\n `UPDATE mem_sessions SET ended_at = ? WHERE id = ? AND ended_at IS NULL`,\n [Date.now(), sessionId]\n );\n }\n\n getSession(sessionId: string): MemSession | null {\n const row = this.db.get('SELECT * FROM mem_sessions WHERE id = ?', [sessionId]);\n return row ? this.rowToSession(row) : null;\n }\n\n listSessions(limit = 10): MemSession[] {\n return this.db.all(\n 'SELECT * FROM mem_sessions ORDER BY started_at DESC LIMIT ?',\n [limit]\n ).map(this.rowToSession);\n }\n\n // \u2500\u2500 Observations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Insert an observation. Returns the ID, or null if a duplicate (same content_hash).\n */\n insertObservation(\n content: string,\n opts: {\n contentRaw?: string;\n kind?: string;\n source?: string;\n tags?: string[];\n sessionId?: string;\n } = {}\n ): string | null {\n const id = generateId();\n const contentHash = hashContent(content);\n const kind = opts.kind ?? 'note';\n const source = opts.source ?? 'manual';\n const tags = opts.tags ? JSON.stringify(opts.tags) : null;\n const now = Date.now();\n\n try {\n this.db.run(\n `INSERT INTO mem_observations (id, session_id, content, content_raw, content_hash, kind, source, tags, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n [id, opts.sessionId ?? null, content, opts.contentRaw ?? null, contentHash, kind, source, tags, now]\n );\n } catch (err: any) {\n // Unique constraint on content_hash \u2014 duplicate, skip silently\n if (err.message?.includes('UNIQUE constraint failed') || err.message?.includes('unique')) {\n return null;\n }\n throw err;\n }\n\n // Keep FTS in sync\n this.db.run(\n `INSERT INTO mem_fts (id, content, kind) VALUES (?, ?, ?)`,\n [id, content, kind]\n );\n\n return id;\n }\n\n getObservation(id: string): MemObservation | null {\n const row = this.db.get('SELECT * FROM mem_observations WHERE id = ?', [id]);\n return row ? this.rowToObservation(row) : null;\n }\n\n getObservationsBySession(sessionId: string, limit = 50): MemObservation[] {\n return this.db.all(\n 'SELECT * FROM mem_observations WHERE session_id = ? ORDER BY created_at DESC LIMIT ?',\n [sessionId, limit]\n ).map(this.rowToObservation);\n }\n\n getObservationsByTimeRange(from: number, to: number, limit = 50): MemObservation[] {\n return this.db.all(\n 'SELECT * FROM mem_observations WHERE created_at >= ? AND created_at <= ? ORDER BY created_at DESC LIMIT ?',\n [from, to, limit]\n ).map(this.rowToObservation);\n }\n\n // \u2500\u2500 FTS Search \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n searchFTS(query: string, opts: MemSearchOptions = {}): ScoredObservation[] {\n const { limit = 10, kind, sessionId, asOf } = opts;\n\n // Sanitize for FTS5\n const safe = query\n .replace(/\\b(AND|OR|NOT)\\b/g, ' ')\n .replace(/['\"*()?\\-+^~:{}\\\\\\.\\/,]/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n if (!safe) return [];\n\n const ftsQuery = safe + '*';\n const safeLimit = Math.max(1, Math.floor(Number(limit)));\n\n const conditions: string[] = [];\n const params: any[] = [];\n\n if (kind) {\n conditions.push('o.kind = ?');\n params.push(kind);\n }\n if (sessionId) {\n conditions.push('o.session_id = ?');\n params.push(sessionId);\n }\n\n // Temporal filtering: exclude expired and superseded facts\n if (asOf) {\n conditions.push('(o.valid_from IS NULL OR o.valid_from <= ?)');\n params.push(asOf);\n conditions.push('(o.valid_until IS NULL OR o.valid_until > ?)');\n params.push(asOf);\n conditions.push('o.superseded_by IS NULL');\n }\n\n const where = conditions.length > 0 ? `AND ${conditions.join(' AND ')}` : '';\n\n const rows = this.db.all(\n `SELECT o.*, rank FROM mem_fts f\n JOIN mem_observations o ON o.id = f.id\n WHERE mem_fts MATCH '${ftsQuery}' ${where}\n ORDER BY rank\n LIMIT ${safeLimit}`,\n params\n );\n\n return rows.map((row: any) => ({\n observation: this.rowToObservation(row),\n score: Math.abs(row.rank ?? 0),\n scoreSource: 'fts' as const,\n }));\n }\n\n // \u2500\u2500 Links \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n linkToSymbol(observationId: string, qualifiedName: string, relevance = 1.0): void {\n this.db.run(\n `INSERT OR IGNORE INTO mem_links (observation_id, qualified_name, relevance)\n VALUES (?, ?, ?)`,\n [observationId, qualifiedName, relevance]\n );\n }\n\n linkToSymbols(observationId: string, qualifiedNames: string[]): void {\n for (const qn of qualifiedNames) {\n this.linkToSymbol(observationId, qn);\n }\n }\n\n /**\n * Get observations linked to a symbol by qualified_name.\n * Resolves through mem_links \u2014 no dependency on node IDs.\n */\n getLinkedObservations(qualifiedName: string, limit = 10): ScoredObservation[] {\n const rows = this.db.all(\n `SELECT o.*, l.relevance FROM mem_observations o\n JOIN mem_links l ON l.observation_id = o.id\n WHERE l.qualified_name = ?\n ORDER BY l.relevance DESC, o.created_at DESC\n LIMIT ?`,\n [qualifiedName, limit]\n );\n\n return rows.map((row: any) => ({\n observation: this.rowToObservation(row),\n score: row.relevance ?? 1.0,\n scoreSource: 'fts' as const,\n }));\n }\n\n /**\n * Get observations linked to any of the given qualified names.\n * Used by kirograph_context and kirograph_impact to surface memory.\n */\n getLinkedObservationsForSymbols(qualifiedNames: string[], limit = 5): ScoredObservation[] {\n if (qualifiedNames.length === 0) return [];\n const placeholders = qualifiedNames.map(() => '?').join(',');\n const rows = this.db.all(\n `SELECT DISTINCT o.*, MAX(l.relevance) as relevance FROM mem_observations o\n JOIN mem_links l ON l.observation_id = o.id\n WHERE l.qualified_name IN (${placeholders})\n GROUP BY o.id\n ORDER BY relevance DESC, o.created_at DESC\n LIMIT ?`,\n [...qualifiedNames, limit]\n );\n\n return rows.map((row: any) => ({\n observation: this.rowToObservation(row),\n score: row.relevance ?? 1.0,\n scoreSource: 'fts' as const,\n }));\n }\n\n // \u2500\u2500 Vectors \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n insertVector(observationId: string, embedding: Buffer, model: string): void {\n this.db.run(\n `INSERT OR REPLACE INTO mem_vectors (observation_id, embedding, model, created_at)\n VALUES (?, ?, ?, ?)`,\n [observationId, embedding, model, Date.now()]\n );\n }\n\n getVector(observationId: string): { embedding: Buffer; model: string } | null {\n const row = this.db.get(\n 'SELECT embedding, model FROM mem_vectors WHERE observation_id = ?',\n [observationId]\n );\n return row ? { embedding: row.embedding, model: row.model } : null;\n }\n\n getVectorCount(): number {\n const row = this.db.get('SELECT COUNT(*) as count FROM mem_vectors');\n return row?.count ?? 0;\n }\n\n getVectorModelMismatch(currentModel: string): number {\n const row = this.db.get(\n 'SELECT COUNT(*) as count FROM mem_vectors WHERE model != ?',\n [currentModel]\n );\n return row?.count ?? 0;\n }\n\n getAllVectors(model?: string): Array<{ observationId: string; embedding: Buffer }> {\n const sql = model\n ? 'SELECT observation_id, embedding FROM mem_vectors WHERE model = ?'\n : 'SELECT observation_id, embedding FROM mem_vectors';\n const params = model ? [model] : [];\n return this.db.all(sql, params).map((row: any) => ({\n observationId: row.observation_id,\n embedding: row.embedding,\n }));\n }\n\n deleteVectors(): void {\n this.db.run('DELETE FROM mem_vectors');\n }\n\n // \u2500\u2500 Stats \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n getStats(currentModel?: string): MemStats {\n const sessions = this.db.get('SELECT COUNT(*) as c FROM mem_sessions')?.c ?? 0;\n const activeSessions = this.db.get('SELECT COUNT(*) as c FROM mem_sessions WHERE ended_at IS NULL')?.c ?? 0;\n const observations = this.db.get('SELECT COUNT(*) as c FROM mem_observations')?.c ?? 0;\n const links = this.db.get('SELECT COUNT(*) as c FROM mem_links')?.c ?? 0;\n const vectors = this.db.get('SELECT COUNT(*) as c FROM mem_vectors')?.c ?? 0;\n const mismatch = currentModel ? this.getVectorModelMismatch(currentModel) : 0;\n\n return {\n sessions,\n activeSessions,\n observations,\n links,\n vectors,\n embeddableCount: observations,\n modelMismatch: mismatch > 0,\n currentModel,\n };\n }\n\n // \u2500\u2500 Maintenance \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Delete observations older than the given timestamp.\n * Cascades to mem_links and mem_vectors via FK.\n */\n prune(olderThan: number): number {\n // Get IDs to delete (for FTS cleanup)\n const ids = this.db.all(\n 'SELECT id FROM mem_observations WHERE created_at < ?',\n [olderThan]\n ).map((r: any) => r.id);\n\n if (ids.length === 0) return 0;\n\n const placeholders = ids.map(() => '?').join(',');\n this.db.run(`DELETE FROM mem_fts WHERE id IN (${placeholders})`, ids);\n this.db.run(`DELETE FROM mem_observations WHERE created_at < ?`, [olderThan]);\n\n // Clean up empty sessions\n this.db.run(\n `DELETE FROM mem_sessions WHERE id NOT IN (SELECT DISTINCT session_id FROM mem_observations WHERE session_id IS NOT NULL)`\n );\n\n return ids.length;\n }\n\n /**\n * Find stale links where qualified_name no longer exists in the nodes table.\n */\n findStaleLinks(): MemLink[] {\n const rows = this.db.all(\n `SELECT l.* FROM mem_links l\n LEFT JOIN nodes n ON n.qualified_name = l.qualified_name\n WHERE n.id IS NULL`\n );\n return rows.map((row: any) => ({\n observationId: row.observation_id,\n qualifiedName: row.qualified_name,\n relevance: row.relevance,\n }));\n }\n\n /**\n * Remove stale links (where qualified_name no longer resolves).\n */\n removeStaleLinks(): number {\n const result = this.db.run(\n `DELETE FROM mem_links WHERE qualified_name NOT IN (SELECT DISTINCT qualified_name FROM nodes)`\n );\n return result?.changes ?? 0;\n }\n\n /**\n * Close stale sessions (started but never ended, older than timeout).\n */\n closeStaleSessionsOlderThan(timeoutMs: number): number {\n const cutoff = Date.now() - timeoutMs;\n const result = this.db.run(\n `UPDATE mem_sessions SET ended_at = ? WHERE ended_at IS NULL AND started_at < ?`,\n [Date.now(), cutoff]\n );\n return result?.changes ?? 0;\n }\n\n // \u2500\u2500 Privacy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Strip <private>...</private> blocks from text.\n */\n static stripPrivate(text: string): string {\n return text.replace(/<private>[\\s\\S]*?<\\/private>/gi, '').trim();\n }\n\n // \u2500\u2500 Row mappers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private rowToSession(row: any): MemSession {\n return {\n id: row.id,\n ide: row.ide ?? undefined,\n cwd: row.cwd ?? undefined,\n startedAt: row.started_at,\n endedAt: row.ended_at ?? undefined,\n };\n }\n\n private rowToObservation(row: any): MemObservation {\n return {\n id: row.id,\n sessionId: row.session_id ?? undefined,\n content: row.content,\n contentRaw: row.content_raw ?? undefined,\n contentHash: row.content_hash,\n kind: row.kind,\n source: row.source,\n tags: row.tags ? JSON.parse(row.tags) : undefined,\n createdAt: row.created_at,\n validFrom: row.valid_from ?? undefined,\n validUntil: row.valid_until ?? undefined,\n supersededBy: row.superseded_by ?? undefined,\n factType: row.fact_type ?? undefined,\n };\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;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AAAA,MAChB,WAAW,IAAI;AAAA,MACf,SAAS,IAAI,YAAY;AAAA,IAC3B;AAAA,EACF;AAAA,EAEQ,iBAAiB,KAA0B;AACjD,WAAO;AAAA,MACL,IAAI,IAAI;AAAA,MACR,WAAW,IAAI,cAAc;AAAA,MAC7B,SAAS,IAAI;AAAA,MACb,YAAY,IAAI,eAAe;AAAA,MAC/B,aAAa,IAAI;AAAA,MACjB,MAAM,IAAI;AAAA,MACV,QAAQ,IAAI;AAAA,MACZ,MAAM,IAAI,OAAO,KAAK,MAAM,IAAI,IAAI,IAAI;AAAA,MACxC,WAAW,IAAI;AAAA,MACf,WAAW,IAAI,cAAc;AAAA,MAC7B,YAAY,IAAI,eAAe;AAAA,MAC/B,cAAc,IAAI,iBAAiB;AAAA,MACnC,UAAU,IAAI,aAAa;AAAA,IAC7B;AAAA,EACF;AACF;",
|
|
4
|
+
"sourcesContent": ["/**\n * KiroGraph Memory \u2014 Database layer\n *\n * Operates on mem_* tables within the same SQLite database as the code graph.\n * Completely isolated: no FK to core nodes/edges tables.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as crypto from 'crypto';\nimport type {\n MemSession,\n MemObservation,\n MemObservationInput,\n MemLink,\n ScoredObservation,\n MemSearchOptions,\n MemTimelineOptions,\n MemStats,\n MemRelation,\n MemRelationInput,\n MemPrompt,\n RelationType,\n} from './types';\n\n// \u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction generateId(): string {\n return crypto.randomUUID();\n}\n\nfunction hashContent(content: string): string {\n return crypto.createHash('sha256').update(content).digest('hex');\n}\n\n// \u2500\u2500 MemoryDatabase \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport class MemoryDatabase {\n private db: any;\n private initialized = false;\n\n constructor(db: any) {\n this.db = db;\n }\n\n /**\n * Apply memory schema. Called once when enableMemory is true.\n */\n initialize(): void {\n if (this.initialized) return;\n const schemaPath = path.join(__dirname, '../db/memory-schema.sql');\n const sql = fs.readFileSync(schemaPath, 'utf8');\n this.db.exec(sql);\n\n // Migration: add temporal columns if they don't exist (for existing databases)\n this.migrateTemporalColumns();\n this.migrateRelationsAndPrompts();\n\n this.initialized = true;\n }\n\n /**\n * Add temporal fact columns to mem_observations if missing.\n * Safe to run multiple times (uses IF NOT EXISTS pattern via try/catch).\n */\n private migrateTemporalColumns(): void {\n const columnsToAdd = [\n { name: 'valid_from', type: 'INTEGER' },\n { name: 'valid_until', type: 'INTEGER' },\n { name: 'superseded_by', type: 'TEXT' },\n { name: 'fact_type', type: \"TEXT DEFAULT 'observation'\" },\n { name: 'topic_key', type: 'TEXT' },\n { name: 'review_after', type: 'INTEGER' },\n ];\n\n for (const col of columnsToAdd) {\n try {\n this.db.exec(`ALTER TABLE mem_observations ADD COLUMN ${col.name} ${col.type}`);\n } catch {\n // Column already exists \u2014 ignore\n }\n }\n }\n\n private migrateRelationsAndPrompts(): void {\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS mem_relations (\n id TEXT PRIMARY KEY,\n observation_a TEXT NOT NULL REFERENCES mem_observations(id) ON DELETE CASCADE,\n observation_b TEXT NOT NULL REFERENCES mem_observations(id) ON DELETE CASCADE,\n relation TEXT NOT NULL,\n confidence REAL NOT NULL DEFAULT 1.0,\n reason TEXT,\n evidence TEXT,\n judgment_status TEXT NOT NULL DEFAULT 'pending',\n judged_at INTEGER,\n created_at INTEGER NOT NULL,\n UNIQUE(observation_a, observation_b)\n );\n CREATE INDEX IF NOT EXISTS idx_mem_rel_a ON mem_relations(observation_a);\n CREATE INDEX IF NOT EXISTS idx_mem_rel_b ON mem_relations(observation_b);\n CREATE INDEX IF NOT EXISTS idx_mem_rel_status ON mem_relations(judgment_status);\n CREATE TABLE IF NOT EXISTS mem_prompts (\n id TEXT PRIMARY KEY,\n session_id TEXT REFERENCES mem_sessions(id) ON DELETE CASCADE,\n content TEXT NOT NULL,\n created_at INTEGER NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_mem_prompts_session ON mem_prompts(session_id);\n `);\n }\n\n // \u2500\u2500 Watchmen \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Count non-summary observations created after the most recent summary.\n * Used by WatchmenChecker to decide if synthesis should trigger.\n */\n countSinceLastSummary(): number {\n const lastSummary = this.db.get(\n `SELECT created_at FROM mem_observations WHERE kind = 'summary' ORDER BY created_at DESC LIMIT 1`\n ) as { created_at: number } | undefined;\n\n const since = lastSummary?.created_at ?? 0;\n const row = this.db.get(\n `SELECT COUNT(*) as count FROM mem_observations WHERE kind != 'summary' AND created_at > ?`,\n [since]\n ) as { count: number };\n\n return row?.count ?? 0;\n }\n\n getObservationsSinceLastSummary(limit = 50): MemObservation[] {\n const lastSummary = this.db.get(\n `SELECT created_at FROM mem_observations WHERE kind = 'summary' ORDER BY created_at DESC LIMIT 1`\n ) as { created_at: number } | undefined;\n\n const since = lastSummary?.created_at ?? 0;\n const rows = this.db.all(\n `SELECT * FROM mem_observations WHERE kind != 'summary' AND created_at > ?\n ORDER BY created_at DESC LIMIT ?`,\n [since, limit]\n ) as any[];\n\n return rows.map(row => ({\n id: row.id,\n sessionId: row.session_id ?? undefined,\n content: row.content,\n contentRaw: row.content_raw ?? undefined,\n contentHash: row.content_hash,\n kind: row.kind,\n source: row.source,\n tags: row.tags ? JSON.parse(row.tags) : undefined,\n createdAt: row.created_at,\n }));\n }\n\n // \u2500\u2500 Sessions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Get or create an active session. Auto-creates if no active session exists\n * within the timeout window.\n */\n getOrCreateSession(ide: string, cwd: string, timeoutSeconds = 7200): string {\n const cutoff = Date.now() - (timeoutSeconds * 1000);\n\n // Look for an active session (no ended_at, same ide, started within timeout)\n const existing = this.db.get(\n `SELECT id FROM mem_sessions\n WHERE ended_at IS NULL AND ide = ? AND started_at > ?\n ORDER BY started_at DESC LIMIT 1`,\n [ide, cutoff]\n );\n\n if (existing) return existing.id;\n\n // Auto-close any stale sessions for this IDE\n this.db.run(\n `UPDATE mem_sessions SET ended_at = ? WHERE ended_at IS NULL AND ide = ?`,\n [Date.now(), ide]\n );\n\n // Create new session\n const id = generateId();\n this.db.run(\n `INSERT INTO mem_sessions (id, ide, cwd, started_at) VALUES (?, ?, ?, ?)`,\n [id, ide, cwd, Date.now()]\n );\n return id;\n }\n\n endSession(sessionId: string): void {\n this.db.run(\n `UPDATE mem_sessions SET ended_at = ? WHERE id = ? AND ended_at IS NULL`,\n [Date.now(), sessionId]\n );\n }\n\n getSession(sessionId: string): MemSession | null {\n const row = this.db.get('SELECT * FROM mem_sessions WHERE id = ?', [sessionId]);\n return row ? this.rowToSession(row) : null;\n }\n\n listSessions(limit = 10): MemSession[] {\n return this.db.all(\n 'SELECT * FROM mem_sessions ORDER BY started_at DESC LIMIT ?',\n [limit]\n ).map(this.rowToSession);\n }\n\n // \u2500\u2500 Observations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Insert an observation. Returns the ID, or null if a duplicate (same content_hash).\n */\n insertObservation(\n content: string,\n opts: {\n contentRaw?: string;\n kind?: string;\n source?: string;\n tags?: string[];\n sessionId?: string;\n topicKey?: string;\n reviewAfter?: number;\n } = {}\n ): string | null {\n const id = generateId();\n const contentHash = hashContent(content);\n const kind = opts.kind ?? 'note';\n const source = opts.source ?? 'manual';\n const tags = opts.tags ? JSON.stringify(opts.tags) : null;\n const now = Date.now();\n\n try {\n this.db.run(\n `INSERT INTO mem_observations (id, session_id, content, content_raw, content_hash, kind, source, tags, created_at, topic_key, review_after)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n [id, opts.sessionId ?? null, content, opts.contentRaw ?? null, contentHash, kind, source, tags, now, opts.topicKey ?? null, opts.reviewAfter ?? null]\n );\n } catch (err: any) {\n // Unique constraint on content_hash \u2014 duplicate, skip silently\n if (err.message?.includes('UNIQUE constraint failed') || err.message?.includes('unique')) {\n return null;\n }\n throw err;\n }\n\n // Keep FTS in sync\n this.db.run(\n `INSERT INTO mem_fts (id, content, kind) VALUES (?, ?, ?)`,\n [id, content, kind]\n );\n\n return id;\n }\n\n getObservation(id: string): MemObservation | null {\n const row = this.db.get('SELECT * FROM mem_observations WHERE id = ?', [id]);\n return row ? this.rowToObservation(row) : null;\n }\n\n getObservationsBySession(sessionId: string, limit = 50): MemObservation[] {\n return this.db.all(\n 'SELECT * FROM mem_observations WHERE session_id = ? ORDER BY created_at DESC LIMIT ?',\n [sessionId, limit]\n ).map(this.rowToObservation);\n }\n\n getObservationsByTimeRange(from: number, to: number, limit = 50): MemObservation[] {\n return this.db.all(\n 'SELECT * FROM mem_observations WHERE created_at >= ? AND created_at <= ? ORDER BY created_at DESC LIMIT ?',\n [from, to, limit]\n ).map(this.rowToObservation);\n }\n\n // \u2500\u2500 FTS Search \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n searchFTS(query: string, opts: MemSearchOptions = {}): ScoredObservation[] {\n const { limit = 10, kind, sessionId, asOf } = opts;\n\n // Sanitize for FTS5\n const safe = query\n .replace(/\\b(AND|OR|NOT)\\b/g, ' ')\n .replace(/['\"*()?\\-+^~:{}\\\\\\.\\/,\\[\\]]/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n if (!safe) return [];\n\n const ftsQuery = safe + '*';\n const safeLimit = Math.max(1, Math.floor(Number(limit)));\n\n const conditions: string[] = [];\n const params: any[] = [];\n\n if (kind) {\n conditions.push('o.kind = ?');\n params.push(kind);\n }\n if (sessionId) {\n conditions.push('o.session_id = ?');\n params.push(sessionId);\n }\n\n // Temporal filtering: exclude expired and superseded facts\n if (asOf) {\n conditions.push('(o.valid_from IS NULL OR o.valid_from <= ?)');\n params.push(asOf);\n conditions.push('(o.valid_until IS NULL OR o.valid_until > ?)');\n params.push(asOf);\n conditions.push('o.superseded_by IS NULL');\n }\n\n const where = conditions.length > 0 ? `AND ${conditions.join(' AND ')}` : '';\n\n const rows = this.db.all(\n `SELECT o.*, rank FROM mem_fts f\n JOIN mem_observations o ON o.id = f.id\n WHERE mem_fts MATCH '${ftsQuery}' ${where}\n ORDER BY rank\n LIMIT ${safeLimit}`,\n params\n );\n\n return rows.map((row: any) => ({\n observation: this.rowToObservation(row),\n score: Math.abs(row.rank ?? 0),\n scoreSource: 'fts' as const,\n }));\n }\n\n // \u2500\u2500 Links \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n linkToSymbol(observationId: string, qualifiedName: string, relevance = 1.0): void {\n this.db.run(\n `INSERT OR IGNORE INTO mem_links (observation_id, qualified_name, relevance)\n VALUES (?, ?, ?)`,\n [observationId, qualifiedName, relevance]\n );\n }\n\n linkToSymbols(observationId: string, qualifiedNames: string[]): void {\n for (const qn of qualifiedNames) {\n this.linkToSymbol(observationId, qn);\n }\n }\n\n /**\n * Get observations linked to a symbol by qualified_name.\n * Resolves through mem_links \u2014 no dependency on node IDs.\n */\n getLinkedObservations(qualifiedName: string, limit = 10): ScoredObservation[] {\n const rows = this.db.all(\n `SELECT o.*, l.relevance FROM mem_observations o\n JOIN mem_links l ON l.observation_id = o.id\n WHERE l.qualified_name = ?\n ORDER BY l.relevance DESC, o.created_at DESC\n LIMIT ?`,\n [qualifiedName, limit]\n );\n\n return rows.map((row: any) => ({\n observation: this.rowToObservation(row),\n score: row.relevance ?? 1.0,\n scoreSource: 'fts' as const,\n }));\n }\n\n /**\n * Get observations linked to any of the given qualified names.\n * Used by kirograph_context and kirograph_impact to surface memory.\n */\n getLinkedObservationsForSymbols(qualifiedNames: string[], limit = 5): ScoredObservation[] {\n if (qualifiedNames.length === 0) return [];\n const placeholders = qualifiedNames.map(() => '?').join(',');\n const rows = this.db.all(\n `SELECT DISTINCT o.*, MAX(l.relevance) as relevance FROM mem_observations o\n JOIN mem_links l ON l.observation_id = o.id\n WHERE l.qualified_name IN (${placeholders})\n GROUP BY o.id\n ORDER BY relevance DESC, o.created_at DESC\n LIMIT ?`,\n [...qualifiedNames, limit]\n );\n\n return rows.map((row: any) => ({\n observation: this.rowToObservation(row),\n score: row.relevance ?? 1.0,\n scoreSource: 'fts' as const,\n }));\n }\n\n // \u2500\u2500 Vectors \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n insertVector(observationId: string, embedding: Buffer, model: string): void {\n this.db.run(\n `INSERT OR REPLACE INTO mem_vectors (observation_id, embedding, model, created_at)\n VALUES (?, ?, ?, ?)`,\n [observationId, embedding, model, Date.now()]\n );\n }\n\n getVector(observationId: string): { embedding: Buffer; model: string } | null {\n const row = this.db.get(\n 'SELECT embedding, model FROM mem_vectors WHERE observation_id = ?',\n [observationId]\n );\n return row ? { embedding: row.embedding, model: row.model } : null;\n }\n\n getVectorCount(): number {\n const row = this.db.get('SELECT COUNT(*) as count FROM mem_vectors');\n return row?.count ?? 0;\n }\n\n getVectorModelMismatch(currentModel: string): number {\n const row = this.db.get(\n 'SELECT COUNT(*) as count FROM mem_vectors WHERE model != ?',\n [currentModel]\n );\n return row?.count ?? 0;\n }\n\n getAllVectors(model?: string): Array<{ observationId: string; embedding: Buffer }> {\n const sql = model\n ? 'SELECT observation_id, embedding FROM mem_vectors WHERE model = ?'\n : 'SELECT observation_id, embedding FROM mem_vectors';\n const params = model ? [model] : [];\n return this.db.all(sql, params).map((row: any) => ({\n observationId: row.observation_id,\n embedding: row.embedding,\n }));\n }\n\n deleteVectors(): void {\n this.db.run('DELETE FROM mem_vectors');\n }\n\n // \u2500\u2500 Relations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n insertRelation(input: MemRelationInput): string {\n const id = generateId();\n this.db.run(\n `INSERT OR REPLACE INTO mem_relations (id, observation_a, observation_b, relation, confidence, reason, evidence, judgment_status, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?)`,\n [id, input.observationA, input.observationB, input.relation, input.confidence ?? 1.0, input.reason ?? null, input.evidence ?? null, Date.now()]\n );\n return id;\n }\n\n judgeRelation(id: string, relation: RelationType, confidence: number, reason?: string, evidence?: string): void {\n this.db.run(\n `UPDATE mem_relations SET relation = ?, confidence = ?, reason = ?, evidence = ?, judgment_status = 'judged', judged_at = ? WHERE id = ?`,\n [relation, confidence, reason ?? null, evidence ?? null, Date.now(), id]\n );\n }\n\n ignoreRelation(id: string): void {\n this.db.run(`UPDATE mem_relations SET judgment_status = 'ignored' WHERE id = ?`, [id]);\n }\n\n getPendingRelations(limit = 20): MemRelation[] {\n return this.db.all(\n `SELECT * FROM mem_relations WHERE judgment_status = 'pending' ORDER BY created_at DESC LIMIT ?`,\n [limit]\n ).map((row: any) => this.rowToRelation(row));\n }\n\n getRelationsForObservations(ids: string[]): Map<string, MemRelation[]> {\n if (ids.length === 0) return new Map();\n const placeholders = ids.map(() => '?').join(',');\n const rows = this.db.all(\n `SELECT * FROM mem_relations WHERE observation_a IN (${placeholders}) OR observation_b IN (${placeholders})`,\n [...ids, ...ids]\n ) as any[];\n const map = new Map<string, MemRelation[]>();\n for (const row of rows) {\n const rel = this.rowToRelation(row);\n for (const obsId of [row.observation_a, row.observation_b]) {\n if (ids.includes(obsId)) {\n if (!map.has(obsId)) map.set(obsId, []);\n map.get(obsId)!.push(rel);\n }\n }\n }\n return map;\n }\n\n resolveObservationByTopicKey(topicKey: string): MemObservation | null {\n const row = this.db.get('SELECT * FROM mem_observations WHERE topic_key = ? LIMIT 1', [topicKey]);\n return row ? this.rowToObservation(row) : null;\n }\n\n private rowToRelation(row: any): MemRelation {\n return {\n id: row.id,\n observationA: row.observation_a,\n observationB: row.observation_b,\n relation: row.relation,\n confidence: row.confidence,\n reason: row.reason ?? undefined,\n evidence: row.evidence ?? undefined,\n judgmentStatus: row.judgment_status,\n judgedAt: row.judged_at ?? undefined,\n createdAt: row.created_at,\n };\n }\n\n // \u2500\u2500 Review \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n getObservationsForReview(limit = 20): MemObservation[] {\n const now = Date.now();\n return this.db.all(\n `SELECT * FROM mem_observations WHERE review_after IS NOT NULL AND review_after < ? AND superseded_by IS NULL ORDER BY review_after ASC LIMIT ?`,\n [now, limit]\n ).map((row: any) => this.rowToObservation(row));\n }\n\n markReviewed(id: string): void {\n this.db.run(`UPDATE mem_observations SET review_after = NULL WHERE id = ?`, [id]);\n }\n\n // \u2500\u2500 Prompts \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n insertPrompt(sessionId: string | undefined, content: string): string {\n const id = generateId();\n this.db.run(\n `INSERT INTO mem_prompts (id, session_id, content, created_at) VALUES (?, ?, ?, ?)`,\n [id, sessionId ?? null, content, Date.now()]\n );\n return id;\n }\n\n getPromptsBySession(sessionId: string, limit = 20): MemPrompt[] {\n return this.db.all(\n `SELECT * FROM mem_prompts WHERE session_id = ? ORDER BY created_at DESC LIMIT ?`,\n [sessionId, limit]\n ).map((row: any) => ({ id: row.id, sessionId: row.session_id ?? undefined, content: row.content, createdAt: row.created_at }));\n }\n\n // \u2500\u2500 Stats \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n getStats(currentModel?: string): MemStats {\n const sessions = this.db.get('SELECT COUNT(*) as c FROM mem_sessions')?.c ?? 0;\n const activeSessions = this.db.get('SELECT COUNT(*) as c FROM mem_sessions WHERE ended_at IS NULL')?.c ?? 0;\n const observations = this.db.get('SELECT COUNT(*) as c FROM mem_observations')?.c ?? 0;\n const links = this.db.get('SELECT COUNT(*) as c FROM mem_links')?.c ?? 0;\n const vectors = this.db.get('SELECT COUNT(*) as c FROM mem_vectors')?.c ?? 0;\n const mismatch = currentModel ? this.getVectorModelMismatch(currentModel) : 0;\n const relations = this.db.get('SELECT COUNT(*) as c FROM mem_relations')?.c ?? 0;\n const pendingConflicts = this.db.get(\"SELECT COUNT(*) as c FROM mem_relations WHERE judgment_status = 'pending'\")?.c ?? 0;\n\n return {\n sessions,\n activeSessions,\n observations,\n links,\n vectors,\n embeddableCount: observations,\n modelMismatch: mismatch > 0,\n currentModel,\n relations,\n pendingConflicts,\n };\n }\n\n // \u2500\u2500 Maintenance \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Delete observations older than the given timestamp.\n * Cascades to mem_links and mem_vectors via FK.\n */\n prune(olderThan: number): number {\n // Get IDs to delete (for FTS cleanup)\n const ids = this.db.all(\n 'SELECT id FROM mem_observations WHERE created_at < ?',\n [olderThan]\n ).map((r: any) => r.id);\n\n if (ids.length === 0) return 0;\n\n const placeholders = ids.map(() => '?').join(',');\n this.db.run(`DELETE FROM mem_fts WHERE id IN (${placeholders})`, ids);\n this.db.run(`DELETE FROM mem_observations WHERE created_at < ?`, [olderThan]);\n\n // Clean up empty sessions\n this.db.run(\n `DELETE FROM mem_sessions WHERE id NOT IN (SELECT DISTINCT session_id FROM mem_observations WHERE session_id IS NOT NULL)`\n );\n\n return ids.length;\n }\n\n /**\n * Find stale links where qualified_name no longer exists in the nodes table.\n */\n findStaleLinks(): MemLink[] {\n const rows = this.db.all(\n `SELECT l.* FROM mem_links l\n LEFT JOIN nodes n ON n.qualified_name = l.qualified_name\n WHERE n.id IS NULL`\n );\n return rows.map((row: any) => ({\n observationId: row.observation_id,\n qualifiedName: row.qualified_name,\n relevance: row.relevance,\n }));\n }\n\n /**\n * Remove stale links (where qualified_name no longer resolves).\n */\n removeStaleLinks(): number {\n const result = this.db.run(\n `DELETE FROM mem_links WHERE qualified_name NOT IN (SELECT DISTINCT qualified_name FROM nodes)`\n );\n return result?.changes ?? 0;\n }\n\n /**\n * Close stale sessions (started but never ended, older than timeout).\n */\n closeStaleSessionsOlderThan(timeoutMs: number): number {\n const cutoff = Date.now() - timeoutMs;\n const result = this.db.run(\n `UPDATE mem_sessions SET ended_at = ? WHERE ended_at IS NULL AND started_at < ?`,\n [Date.now(), cutoff]\n );\n return result?.changes ?? 0;\n }\n\n // \u2500\u2500 Privacy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Strip <private>...</private> blocks from text.\n */\n static stripPrivate(text: string): string {\n return text.replace(/<private>[\\s\\S]*?<\\/private>/gi, '').trim();\n }\n\n // \u2500\u2500 Row mappers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private rowToSession(row: any): MemSession {\n return {\n id: row.id,\n ide: row.ide ?? undefined,\n cwd: row.cwd ?? undefined,\n startedAt: row.started_at,\n endedAt: row.ended_at ?? undefined,\n };\n }\n\n private rowToObservation(row: any): MemObservation {\n return {\n id: row.id,\n sessionId: row.session_id ?? undefined,\n content: row.content,\n contentRaw: row.content_raw ?? undefined,\n contentHash: row.content_hash,\n kind: row.kind,\n source: row.source,\n tags: row.tags ? JSON.parse(row.tags) : undefined,\n createdAt: row.created_at,\n validFrom: row.valid_from ?? undefined,\n validUntil: row.valid_until ?? undefined,\n supersededBy: row.superseded_by ?? undefined,\n factType: row.fact_type ?? undefined,\n topicKey: row.topic_key ?? undefined,\n reviewAfter: row.review_after ?? undefined,\n };\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,SAAoB;AACpB,WAAsB;AACtB,aAAwB;AAkBxB,SAAS,aAAqB;AAC5B,SAAO,OAAO,WAAW;AAC3B;AAEA,SAAS,YAAY,SAAyB;AAC5C,SAAO,OAAO,WAAW,QAAQ,EAAE,OAAO,OAAO,EAAE,OAAO,KAAK;AACjE;AAIO,MAAM,eAAe;AAAA,EAI1B,YAAY,IAAS;AAFrB,SAAQ,cAAc;AAGpB,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA,EAKA,aAAmB;AACjB,QAAI,KAAK,YAAa;AACtB,UAAM,aAAa,KAAK,KAAK,WAAW,yBAAyB;AACjE,UAAM,MAAM,GAAG,aAAa,YAAY,MAAM;AAC9C,SAAK,GAAG,KAA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AAAA,MAChB,KAAK,IAAI,OAAO;AAAA,MAChB,WAAW,IAAI;AAAA,MACf,SAAS,IAAI,YAAY;AAAA,IAC3B;AAAA,EACF;AAAA,EAEQ,iBAAiB,KAA0B;AACjD,WAAO;AAAA,MACL,IAAI,IAAI;AAAA,MACR,WAAW,IAAI,cAAc;AAAA,MAC7B,SAAS,IAAI;AAAA,MACb,YAAY,IAAI,eAAe;AAAA,MAC/B,aAAa,IAAI;AAAA,MACjB,MAAM,IAAI;AAAA,MACV,QAAQ,IAAI;AAAA,MACZ,MAAM,IAAI,OAAO,KAAK,MAAM,IAAI,IAAI,IAAI;AAAA,MACxC,WAAW,IAAI;AAAA,MACf,WAAW,IAAI,cAAc;AAAA,MAC7B,YAAY,IAAI,eAAe;AAAA,MAC/B,cAAc,IAAI,iBAAiB;AAAA,MACnC,UAAU,IAAI,aAAa;AAAA,MAC3B,UAAU,IAAI,aAAa;AAAA,MAC3B,aAAa,IAAI,gBAAgB;AAAA,IACnC;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/memory/index.js
CHANGED
|
@@ -94,7 +94,9 @@ class MemoryManager {
|
|
|
94
94
|
kind: input.kind ?? "note",
|
|
95
95
|
source: input.source ?? "manual",
|
|
96
96
|
tags: input.tags,
|
|
97
|
-
sessionId
|
|
97
|
+
sessionId,
|
|
98
|
+
topicKey: input.topicKey,
|
|
99
|
+
reviewAfter: input.reviewAfter
|
|
98
100
|
});
|
|
99
101
|
if (!id) {
|
|
100
102
|
(0, import_errors.logDebug)("Memory: duplicate observation skipped");
|
|
@@ -137,10 +139,35 @@ class MemoryManager {
|
|
|
137
139
|
if (this.vectorMgr.isEnabled() && !this.vectorMgr.hasModelMismatch()) {
|
|
138
140
|
vectorResults = await this.vectorMgr.search(query, limit * 2);
|
|
139
141
|
}
|
|
140
|
-
if (vectorResults.length === 0)
|
|
141
|
-
|
|
142
|
+
if (vectorResults.length === 0) {
|
|
143
|
+
const sliced2 = ftsResults.slice(0, limit);
|
|
144
|
+
const ids2 = sliced2.map((r) => r.observation.id);
|
|
145
|
+
const relMap2 = this.memDb.getRelationsForObservations(ids2);
|
|
146
|
+
for (const r of sliced2) {
|
|
147
|
+
const rels = relMap2.get(r.observation.id);
|
|
148
|
+
if (rels && rels.length > 0) r.relations = rels;
|
|
149
|
+
}
|
|
150
|
+
return sliced2;
|
|
151
|
+
}
|
|
152
|
+
if (ftsResults.length === 0) {
|
|
153
|
+
const sliced2 = vectorResults.slice(0, limit);
|
|
154
|
+
const ids2 = sliced2.map((r) => r.observation.id);
|
|
155
|
+
const relMap2 = this.memDb.getRelationsForObservations(ids2);
|
|
156
|
+
for (const r of sliced2) {
|
|
157
|
+
const rels = relMap2.get(r.observation.id);
|
|
158
|
+
if (rels && rels.length > 0) r.relations = rels;
|
|
159
|
+
}
|
|
160
|
+
return sliced2;
|
|
161
|
+
}
|
|
142
162
|
const merged = this.mergeResults(ftsResults, vectorResults, alpha);
|
|
143
|
-
|
|
163
|
+
const sliced = merged.slice(0, limit);
|
|
164
|
+
const ids = sliced.map((r) => r.observation.id);
|
|
165
|
+
const relMap = this.memDb.getRelationsForObservations(ids);
|
|
166
|
+
for (const r of sliced) {
|
|
167
|
+
const rels = relMap.get(r.observation.id);
|
|
168
|
+
if (rels && rels.length > 0) r.relations = rels;
|
|
169
|
+
}
|
|
170
|
+
return sliced;
|
|
144
171
|
}
|
|
145
172
|
/**
|
|
146
173
|
* Get observations linked to specific symbols.
|
|
@@ -202,6 +229,105 @@ class MemoryManager {
|
|
|
202
229
|
removeStaleLinks() {
|
|
203
230
|
return this.memDb.removeStaleLinks();
|
|
204
231
|
}
|
|
232
|
+
// ── Relations ─────────────────────────────────────────────────────────────
|
|
233
|
+
compareObservations(input) {
|
|
234
|
+
let obsA = input.observationA;
|
|
235
|
+
let obsB = input.observationB;
|
|
236
|
+
if (!this.memDb.getObservation(obsA)) {
|
|
237
|
+
const byKey = this.memDb.resolveObservationByTopicKey(obsA);
|
|
238
|
+
if (byKey) obsA = byKey.id;
|
|
239
|
+
}
|
|
240
|
+
if (!this.memDb.getObservation(obsB)) {
|
|
241
|
+
const byKey = this.memDb.resolveObservationByTopicKey(obsB);
|
|
242
|
+
if (byKey) obsB = byKey.id;
|
|
243
|
+
}
|
|
244
|
+
return this.memDb.insertRelation({ ...input, observationA: obsA, observationB: obsB });
|
|
245
|
+
}
|
|
246
|
+
judgeRelation(relationId, relation, confidence, reason, evidence) {
|
|
247
|
+
this.memDb.judgeRelation(relationId, relation, confidence, reason, evidence);
|
|
248
|
+
}
|
|
249
|
+
ignoreRelation(relationId) {
|
|
250
|
+
this.memDb.ignoreRelation(relationId);
|
|
251
|
+
}
|
|
252
|
+
getPendingRelations(limit = 20) {
|
|
253
|
+
return this.memDb.getPendingRelations(limit);
|
|
254
|
+
}
|
|
255
|
+
// ── Review ─────────────────────────────────────────────────────────────────
|
|
256
|
+
getObservationsForReview(limit = 20) {
|
|
257
|
+
return this.memDb.getObservationsForReview(limit);
|
|
258
|
+
}
|
|
259
|
+
markReviewed(id) {
|
|
260
|
+
this.memDb.markReviewed(id);
|
|
261
|
+
}
|
|
262
|
+
// ── Prompts ────────────────────────────────────────────────────────────────
|
|
263
|
+
async savePrompt(content, ide = "kiro") {
|
|
264
|
+
const cwd = process.cwd();
|
|
265
|
+
const sessionTimeout = this.config.memorySessionTimeout ?? 7200;
|
|
266
|
+
const sessionId = this.memDb.getOrCreateSession(ide, cwd, sessionTimeout);
|
|
267
|
+
return this.memDb.insertPrompt(sessionId, content);
|
|
268
|
+
}
|
|
269
|
+
// ── Passive capture ────────────────────────────────────────────────────────
|
|
270
|
+
capturePassive(content, sessionId) {
|
|
271
|
+
const kindMap = {
|
|
272
|
+
"key learnings": "pattern",
|
|
273
|
+
"learnings": "pattern",
|
|
274
|
+
"observations": "note",
|
|
275
|
+
"decisions": "decision",
|
|
276
|
+
"key changes": "pattern",
|
|
277
|
+
"errors": "error",
|
|
278
|
+
"patterns": "pattern"
|
|
279
|
+
};
|
|
280
|
+
const results = [];
|
|
281
|
+
const lines = content.split("\n");
|
|
282
|
+
let currentKind = null;
|
|
283
|
+
for (const line of lines) {
|
|
284
|
+
const headingMatch = line.match(/^#{1,3}\s+(.+)/);
|
|
285
|
+
if (headingMatch) {
|
|
286
|
+
const heading = headingMatch[1].toLowerCase().trim();
|
|
287
|
+
currentKind = kindMap[heading] ?? null;
|
|
288
|
+
continue;
|
|
289
|
+
}
|
|
290
|
+
if (!currentKind) continue;
|
|
291
|
+
const bulletMatch = line.match(/^[\s]*[-*•]\s+(.+)|^[\s]*\d+[.)]\s+(.+)/);
|
|
292
|
+
if (bulletMatch) {
|
|
293
|
+
const text = (bulletMatch[1] || bulletMatch[2]).trim();
|
|
294
|
+
if (text.length < 5) continue;
|
|
295
|
+
const id = this.memDb.insertObservation(text, { kind: currentKind, source: "passive", sessionId });
|
|
296
|
+
const symbols = (0, import_symbols.detectSymbols)(text, this.db);
|
|
297
|
+
if (id && symbols.length > 0) this.memDb.linkToSymbols(id, symbols.map((s) => s.qualifiedName));
|
|
298
|
+
results.push({ id, kind: currentKind, content: text });
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
return results;
|
|
302
|
+
}
|
|
303
|
+
// ── Topic key ──────────────────────────────────────────────────────────────
|
|
304
|
+
suggestTopicKey(kind, title) {
|
|
305
|
+
const slug = title.toLowerCase().replace(/[^a-z0-9\s-]/g, "").trim().split(/\s+/).slice(0, 6).join("-");
|
|
306
|
+
return `${kind}/${slug}`;
|
|
307
|
+
}
|
|
308
|
+
// ── Conflict scan ──────────────────────────────────────────────────────────
|
|
309
|
+
scanConflicts(limit = 50) {
|
|
310
|
+
const recent = this.memDb.getObservationsByTimeRange(0, Date.now(), limit);
|
|
311
|
+
const candidates = [];
|
|
312
|
+
const seen = /* @__PURE__ */ new Set();
|
|
313
|
+
for (const obs of recent) {
|
|
314
|
+
if (!obs.content || obs.content.length < 20) continue;
|
|
315
|
+
const words = obs.content.split(/\s+/).slice(0, 8).join(" ");
|
|
316
|
+
const similar = this.memDb.searchFTS(words, { limit: 5 });
|
|
317
|
+
for (const match of similar) {
|
|
318
|
+
if (match.observation.id === obs.id) continue;
|
|
319
|
+
const pairKey = [obs.id, match.observation.id].sort().join("|");
|
|
320
|
+
if (seen.has(pairKey)) continue;
|
|
321
|
+
seen.add(pairKey);
|
|
322
|
+
const existing = this.memDb.getRelationsForObservations([obs.id]);
|
|
323
|
+
const alreadyLinked = existing.get(obs.id)?.some((r) => r.observationA === match.observation.id || r.observationB === match.observation.id);
|
|
324
|
+
if (!alreadyLinked && match.score > 0.3) {
|
|
325
|
+
candidates.push({ observationA: obs, observationB: match.observation, similarity: match.score });
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return candidates.slice(0, 20);
|
|
330
|
+
}
|
|
205
331
|
// ── Private ────────────────────────────────────────────────────────────────
|
|
206
332
|
shouldExclude(text) {
|
|
207
333
|
if (this.excludePatterns.length === 0) return false;
|