claude-memory-layer 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/.claude-plugin/commands/memory-forget.md +42 -0
  2. package/.claude-plugin/commands/memory-history.md +34 -0
  3. package/.claude-plugin/commands/memory-import.md +56 -0
  4. package/.claude-plugin/commands/memory-list.md +37 -0
  5. package/.claude-plugin/commands/memory-search.md +36 -0
  6. package/.claude-plugin/commands/memory-stats.md +34 -0
  7. package/.claude-plugin/hooks.json +59 -0
  8. package/.claude-plugin/plugin.json +24 -0
  9. package/.history/package_20260201112328.json +45 -0
  10. package/.history/package_20260201113602.json +45 -0
  11. package/.history/package_20260201113713.json +45 -0
  12. package/.history/package_20260201114110.json +45 -0
  13. package/Memo.txt +558 -0
  14. package/README.md +520 -0
  15. package/context.md +636 -0
  16. package/dist/.claude-plugin/commands/memory-forget.md +42 -0
  17. package/dist/.claude-plugin/commands/memory-history.md +34 -0
  18. package/dist/.claude-plugin/commands/memory-import.md +56 -0
  19. package/dist/.claude-plugin/commands/memory-list.md +37 -0
  20. package/dist/.claude-plugin/commands/memory-search.md +36 -0
  21. package/dist/.claude-plugin/commands/memory-stats.md +34 -0
  22. package/dist/.claude-plugin/hooks.json +59 -0
  23. package/dist/.claude-plugin/plugin.json +24 -0
  24. package/dist/cli/index.js +3539 -0
  25. package/dist/cli/index.js.map +7 -0
  26. package/dist/core/index.js +4408 -0
  27. package/dist/core/index.js.map +7 -0
  28. package/dist/hooks/session-end.js +2971 -0
  29. package/dist/hooks/session-end.js.map +7 -0
  30. package/dist/hooks/session-start.js +2969 -0
  31. package/dist/hooks/session-start.js.map +7 -0
  32. package/dist/hooks/stop.js +3123 -0
  33. package/dist/hooks/stop.js.map +7 -0
  34. package/dist/hooks/user-prompt-submit.js +2960 -0
  35. package/dist/hooks/user-prompt-submit.js.map +7 -0
  36. package/dist/services/memory-service.js +2931 -0
  37. package/dist/services/memory-service.js.map +7 -0
  38. package/package.json +45 -0
  39. package/plan.md +1642 -0
  40. package/scripts/build.ts +102 -0
  41. package/spec.md +624 -0
  42. package/specs/citations-system/context.md +243 -0
  43. package/specs/citations-system/plan.md +495 -0
  44. package/specs/citations-system/spec.md +371 -0
  45. package/specs/endless-mode/context.md +305 -0
  46. package/specs/endless-mode/plan.md +620 -0
  47. package/specs/endless-mode/spec.md +455 -0
  48. package/specs/entity-edge-model/context.md +401 -0
  49. package/specs/entity-edge-model/plan.md +459 -0
  50. package/specs/entity-edge-model/spec.md +391 -0
  51. package/specs/evidence-aligner-v2/context.md +401 -0
  52. package/specs/evidence-aligner-v2/plan.md +303 -0
  53. package/specs/evidence-aligner-v2/spec.md +312 -0
  54. package/specs/mcp-desktop-integration/context.md +278 -0
  55. package/specs/mcp-desktop-integration/plan.md +550 -0
  56. package/specs/mcp-desktop-integration/spec.md +494 -0
  57. package/specs/post-tool-use-hook/context.md +319 -0
  58. package/specs/post-tool-use-hook/plan.md +469 -0
  59. package/specs/post-tool-use-hook/spec.md +364 -0
  60. package/specs/private-tags/context.md +288 -0
  61. package/specs/private-tags/plan.md +412 -0
  62. package/specs/private-tags/spec.md +345 -0
  63. package/specs/progressive-disclosure/context.md +346 -0
  64. package/specs/progressive-disclosure/plan.md +663 -0
  65. package/specs/progressive-disclosure/spec.md +415 -0
  66. package/specs/task-entity-system/context.md +297 -0
  67. package/specs/task-entity-system/plan.md +301 -0
  68. package/specs/task-entity-system/spec.md +314 -0
  69. package/specs/vector-outbox-v2/context.md +470 -0
  70. package/specs/vector-outbox-v2/plan.md +562 -0
  71. package/specs/vector-outbox-v2/spec.md +466 -0
  72. package/specs/web-viewer-ui/context.md +384 -0
  73. package/specs/web-viewer-ui/plan.md +797 -0
  74. package/specs/web-viewer-ui/spec.md +516 -0
  75. package/src/cli/index.ts +570 -0
  76. package/src/core/canonical-key.ts +186 -0
  77. package/src/core/citation-generator.ts +63 -0
  78. package/src/core/consolidated-store.ts +279 -0
  79. package/src/core/consolidation-worker.ts +384 -0
  80. package/src/core/context-formatter.ts +276 -0
  81. package/src/core/continuity-manager.ts +336 -0
  82. package/src/core/edge-repo.ts +324 -0
  83. package/src/core/embedder.ts +124 -0
  84. package/src/core/entity-repo.ts +342 -0
  85. package/src/core/event-store.ts +672 -0
  86. package/src/core/evidence-aligner.ts +635 -0
  87. package/src/core/graduation.ts +365 -0
  88. package/src/core/index.ts +32 -0
  89. package/src/core/matcher.ts +210 -0
  90. package/src/core/metadata-extractor.ts +203 -0
  91. package/src/core/privacy/filter.ts +179 -0
  92. package/src/core/privacy/index.ts +20 -0
  93. package/src/core/privacy/tag-parser.ts +145 -0
  94. package/src/core/progressive-retriever.ts +415 -0
  95. package/src/core/retriever.ts +235 -0
  96. package/src/core/task/blocker-resolver.ts +325 -0
  97. package/src/core/task/index.ts +9 -0
  98. package/src/core/task/task-matcher.ts +238 -0
  99. package/src/core/task/task-projector.ts +345 -0
  100. package/src/core/task/task-resolver.ts +414 -0
  101. package/src/core/types.ts +841 -0
  102. package/src/core/vector-outbox.ts +295 -0
  103. package/src/core/vector-store.ts +182 -0
  104. package/src/core/vector-worker.ts +488 -0
  105. package/src/core/working-set-store.ts +244 -0
  106. package/src/hooks/post-tool-use.ts +127 -0
  107. package/src/hooks/session-end.ts +78 -0
  108. package/src/hooks/session-start.ts +57 -0
  109. package/src/hooks/stop.ts +78 -0
  110. package/src/hooks/user-prompt-submit.ts +54 -0
  111. package/src/mcp/handlers.ts +212 -0
  112. package/src/mcp/index.ts +47 -0
  113. package/src/mcp/tools.ts +78 -0
  114. package/src/server/api/citations.ts +101 -0
  115. package/src/server/api/events.ts +101 -0
  116. package/src/server/api/index.ts +18 -0
  117. package/src/server/api/search.ts +98 -0
  118. package/src/server/api/sessions.ts +111 -0
  119. package/src/server/api/stats.ts +97 -0
  120. package/src/server/index.ts +91 -0
  121. package/src/services/memory-service.ts +626 -0
  122. package/src/services/session-history-importer.ts +367 -0
  123. package/tests/canonical-key.test.ts +101 -0
  124. package/tests/evidence-aligner.test.ts +152 -0
  125. package/tests/matcher.test.ts +112 -0
  126. package/tsconfig.json +24 -0
  127. package/vitest.config.ts +15 -0
@@ -0,0 +1,672 @@
1
+ /**
2
+ * AXIOMMIND EventStore implementation
3
+ * Principles: Append-only, Single Source of Truth, Idempotency
4
+ */
5
+
6
+ import { Database } from 'duckdb';
7
+ import { randomUUID } from 'crypto';
8
+ import {
9
+ MemoryEvent,
10
+ MemoryEventInput,
11
+ Session,
12
+ AppendResult,
13
+ OutboxItem
14
+ } from './types.js';
15
+ import { makeCanonicalKey, makeDedupeKey } from './canonical-key.js';
16
+
17
+ export class EventStore {
18
+ private db: Database;
19
+ private initialized = false;
20
+
21
+ constructor(private dbPath: string) {
22
+ this.db = new Database(dbPath);
23
+ }
24
+
25
+ /**
26
+ * Initialize database schema
27
+ */
28
+ async initialize(): Promise<void> {
29
+ if (this.initialized) return;
30
+
31
+ // L0 EventStore: Single Source of Truth (immutable, append-only)
32
+ await this.db.run(`
33
+ CREATE TABLE IF NOT EXISTS events (
34
+ id VARCHAR PRIMARY KEY,
35
+ event_type VARCHAR NOT NULL,
36
+ session_id VARCHAR NOT NULL,
37
+ timestamp TIMESTAMP NOT NULL,
38
+ content TEXT NOT NULL,
39
+ canonical_key VARCHAR NOT NULL,
40
+ dedupe_key VARCHAR UNIQUE,
41
+ metadata JSON
42
+ )
43
+ `);
44
+
45
+ // Dedup table for idempotency
46
+ await this.db.run(`
47
+ CREATE TABLE IF NOT EXISTS event_dedup (
48
+ dedupe_key VARCHAR PRIMARY KEY,
49
+ event_id VARCHAR NOT NULL,
50
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
51
+ )
52
+ `);
53
+
54
+ // Session metadata
55
+ await this.db.run(`
56
+ CREATE TABLE IF NOT EXISTS sessions (
57
+ id VARCHAR PRIMARY KEY,
58
+ started_at TIMESTAMP NOT NULL,
59
+ ended_at TIMESTAMP,
60
+ project_path VARCHAR,
61
+ summary TEXT,
62
+ tags JSON
63
+ )
64
+ `);
65
+
66
+ // Insights (derived data, rebuildable)
67
+ await this.db.run(`
68
+ CREATE TABLE IF NOT EXISTS insights (
69
+ id VARCHAR PRIMARY KEY,
70
+ insight_type VARCHAR NOT NULL,
71
+ content TEXT NOT NULL,
72
+ canonical_key VARCHAR NOT NULL,
73
+ confidence FLOAT,
74
+ source_events JSON,
75
+ created_at TIMESTAMP,
76
+ last_updated TIMESTAMP
77
+ )
78
+ `);
79
+
80
+ // Embedding Outbox (Single-Writer Pattern)
81
+ await this.db.run(`
82
+ CREATE TABLE IF NOT EXISTS embedding_outbox (
83
+ id VARCHAR PRIMARY KEY,
84
+ event_id VARCHAR NOT NULL,
85
+ content TEXT NOT NULL,
86
+ status VARCHAR DEFAULT 'pending',
87
+ retry_count INT DEFAULT 0,
88
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
89
+ processed_at TIMESTAMP,
90
+ error_message TEXT
91
+ )
92
+ `);
93
+
94
+ // Projection offset tracking
95
+ await this.db.run(`
96
+ CREATE TABLE IF NOT EXISTS projection_offsets (
97
+ projection_name VARCHAR PRIMARY KEY,
98
+ last_event_id VARCHAR,
99
+ last_timestamp TIMESTAMP,
100
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
101
+ )
102
+ `);
103
+
104
+ // Memory level tracking
105
+ await this.db.run(`
106
+ CREATE TABLE IF NOT EXISTS memory_levels (
107
+ event_id VARCHAR PRIMARY KEY,
108
+ level VARCHAR NOT NULL DEFAULT 'L0',
109
+ promoted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
110
+ )
111
+ `);
112
+
113
+ // ============================================================
114
+ // Entity-Edge Model Tables
115
+ // ============================================================
116
+
117
+ // Entries (immutable memory units)
118
+ await this.db.run(`
119
+ CREATE TABLE IF NOT EXISTS entries (
120
+ entry_id VARCHAR PRIMARY KEY,
121
+ created_ts TIMESTAMP NOT NULL,
122
+ entry_type VARCHAR NOT NULL,
123
+ title VARCHAR NOT NULL,
124
+ content_json JSON NOT NULL,
125
+ stage VARCHAR NOT NULL DEFAULT 'raw',
126
+ status VARCHAR DEFAULT 'active',
127
+ superseded_by VARCHAR,
128
+ build_id VARCHAR,
129
+ evidence_json JSON,
130
+ canonical_key VARCHAR,
131
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
132
+ )
133
+ `);
134
+
135
+ // Entities (task/condition/artifact)
136
+ await this.db.run(`
137
+ CREATE TABLE IF NOT EXISTS entities (
138
+ entity_id VARCHAR PRIMARY KEY,
139
+ entity_type VARCHAR NOT NULL,
140
+ canonical_key VARCHAR NOT NULL,
141
+ title VARCHAR NOT NULL,
142
+ stage VARCHAR NOT NULL DEFAULT 'raw',
143
+ status VARCHAR NOT NULL DEFAULT 'active',
144
+ current_json JSON NOT NULL,
145
+ title_norm VARCHAR,
146
+ search_text VARCHAR,
147
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
148
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
149
+ )
150
+ `);
151
+
152
+ // Entity aliases for canonical key lookup
153
+ await this.db.run(`
154
+ CREATE TABLE IF NOT EXISTS entity_aliases (
155
+ entity_type VARCHAR NOT NULL,
156
+ canonical_key VARCHAR NOT NULL,
157
+ entity_id VARCHAR NOT NULL,
158
+ is_primary BOOLEAN DEFAULT FALSE,
159
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
160
+ PRIMARY KEY(entity_type, canonical_key)
161
+ )
162
+ `);
163
+
164
+ // Edges (relationships between entries/entities)
165
+ await this.db.run(`
166
+ CREATE TABLE IF NOT EXISTS edges (
167
+ edge_id VARCHAR PRIMARY KEY,
168
+ src_type VARCHAR NOT NULL,
169
+ src_id VARCHAR NOT NULL,
170
+ rel_type VARCHAR NOT NULL,
171
+ dst_type VARCHAR NOT NULL,
172
+ dst_id VARCHAR NOT NULL,
173
+ meta_json JSON,
174
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
175
+ )
176
+ `);
177
+
178
+ // ============================================================
179
+ // Vector Outbox V2 Table
180
+ // ============================================================
181
+
182
+ await this.db.run(`
183
+ CREATE TABLE IF NOT EXISTS vector_outbox (
184
+ job_id VARCHAR PRIMARY KEY,
185
+ item_kind VARCHAR NOT NULL,
186
+ item_id VARCHAR NOT NULL,
187
+ embedding_version VARCHAR NOT NULL,
188
+ status VARCHAR NOT NULL DEFAULT 'pending',
189
+ retry_count INT DEFAULT 0,
190
+ error VARCHAR,
191
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
192
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
193
+ UNIQUE(item_kind, item_id, embedding_version)
194
+ )
195
+ `);
196
+
197
+ // ============================================================
198
+ // Build Runs & Metrics Tables
199
+ // ============================================================
200
+
201
+ await this.db.run(`
202
+ CREATE TABLE IF NOT EXISTS build_runs (
203
+ build_id VARCHAR PRIMARY KEY,
204
+ started_at TIMESTAMP NOT NULL,
205
+ finished_at TIMESTAMP,
206
+ extractor_model VARCHAR NOT NULL,
207
+ extractor_prompt_hash VARCHAR NOT NULL,
208
+ embedder_model VARCHAR NOT NULL,
209
+ embedding_version VARCHAR NOT NULL,
210
+ idris_version VARCHAR NOT NULL,
211
+ schema_version VARCHAR NOT NULL,
212
+ status VARCHAR NOT NULL DEFAULT 'running',
213
+ error VARCHAR
214
+ )
215
+ `);
216
+
217
+ await this.db.run(`
218
+ CREATE TABLE IF NOT EXISTS pipeline_metrics (
219
+ id VARCHAR PRIMARY KEY,
220
+ ts TIMESTAMP NOT NULL,
221
+ stage VARCHAR NOT NULL,
222
+ latency_ms DOUBLE NOT NULL,
223
+ success BOOLEAN NOT NULL,
224
+ error VARCHAR,
225
+ session_id VARCHAR
226
+ )
227
+ `);
228
+
229
+ // ============================================================
230
+ // Endless Mode Tables
231
+ // ============================================================
232
+
233
+ // Working Set table (active memory window)
234
+ await this.db.run(`
235
+ CREATE TABLE IF NOT EXISTS working_set (
236
+ id VARCHAR PRIMARY KEY,
237
+ event_id VARCHAR NOT NULL,
238
+ added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
239
+ relevance_score FLOAT DEFAULT 1.0,
240
+ topics JSON,
241
+ expires_at TIMESTAMP
242
+ )
243
+ `);
244
+
245
+ // Consolidated Memories table (long-term integrated memories)
246
+ await this.db.run(`
247
+ CREATE TABLE IF NOT EXISTS consolidated_memories (
248
+ memory_id VARCHAR PRIMARY KEY,
249
+ summary TEXT NOT NULL,
250
+ topics JSON,
251
+ source_events JSON,
252
+ confidence FLOAT DEFAULT 0.5,
253
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
254
+ accessed_at TIMESTAMP,
255
+ access_count INTEGER DEFAULT 0
256
+ )
257
+ `);
258
+
259
+ // Continuity Log table (tracks context transitions)
260
+ await this.db.run(`
261
+ CREATE TABLE IF NOT EXISTS continuity_log (
262
+ log_id VARCHAR PRIMARY KEY,
263
+ from_context_id VARCHAR,
264
+ to_context_id VARCHAR,
265
+ continuity_score FLOAT,
266
+ transition_type VARCHAR,
267
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
268
+ )
269
+ `);
270
+
271
+ // Endless Mode Config table
272
+ await this.db.run(`
273
+ CREATE TABLE IF NOT EXISTS endless_config (
274
+ key VARCHAR PRIMARY KEY,
275
+ value JSON,
276
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
277
+ )
278
+ `);
279
+
280
+ // ============================================================
281
+ // Create Indexes
282
+ // ============================================================
283
+
284
+ // Entry indexes
285
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_entries_type ON entries(entry_type)`);
286
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_entries_stage ON entries(stage)`);
287
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_entries_canonical ON entries(canonical_key)`);
288
+
289
+ // Entity indexes
290
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_entities_type_key ON entities(entity_type, canonical_key)`);
291
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_entities_status ON entities(status)`);
292
+
293
+ // Edge indexes
294
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src_id, rel_type)`);
295
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_edges_dst ON edges(dst_id, rel_type)`);
296
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_edges_rel ON edges(rel_type)`);
297
+
298
+ // Outbox indexes
299
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_outbox_status ON vector_outbox(status)`);
300
+
301
+ // Endless Mode indexes
302
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_working_set_expires ON working_set(expires_at)`);
303
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_working_set_relevance ON working_set(relevance_score DESC)`);
304
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence DESC)`);
305
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at)`);
306
+
307
+ this.initialized = true;
308
+ }
309
+
310
+ /**
311
+ * Append event to store (AXIOMMIND Principle 2: Append-only)
312
+ * Returns existing event ID if duplicate (Principle 3: Idempotency)
313
+ */
314
+ async append(input: MemoryEventInput): Promise<AppendResult> {
315
+ await this.initialize();
316
+
317
+ const canonicalKey = makeCanonicalKey(input.content);
318
+ const dedupeKey = makeDedupeKey(input.content, input.sessionId);
319
+
320
+ // Check for duplicate
321
+ const existing = await this.db.all<{ event_id: string }[]>(
322
+ `SELECT event_id FROM event_dedup WHERE dedupe_key = ?`,
323
+ [dedupeKey]
324
+ );
325
+
326
+ if (existing.length > 0) {
327
+ return {
328
+ success: true,
329
+ eventId: existing[0].event_id,
330
+ isDuplicate: true
331
+ };
332
+ }
333
+
334
+ const id = randomUUID();
335
+ const timestamp = input.timestamp.toISOString();
336
+
337
+ try {
338
+ await this.db.run(
339
+ `INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
340
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
341
+ [
342
+ id,
343
+ input.eventType,
344
+ input.sessionId,
345
+ timestamp,
346
+ input.content,
347
+ canonicalKey,
348
+ dedupeKey,
349
+ JSON.stringify(input.metadata || {})
350
+ ]
351
+ );
352
+
353
+ await this.db.run(
354
+ `INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)`,
355
+ [dedupeKey, id]
356
+ );
357
+
358
+ // Initialize at L0
359
+ await this.db.run(
360
+ `INSERT INTO memory_levels (event_id, level) VALUES (?, 'L0')`,
361
+ [id]
362
+ );
363
+
364
+ return { success: true, eventId: id, isDuplicate: false };
365
+ } catch (error) {
366
+ return {
367
+ success: false,
368
+ error: error instanceof Error ? error.message : String(error)
369
+ };
370
+ }
371
+ }
372
+
373
+ /**
374
+ * Get events by session ID
375
+ */
376
+ async getSessionEvents(sessionId: string): Promise<MemoryEvent[]> {
377
+ await this.initialize();
378
+
379
+ const rows = await this.db.all<Array<Record<string, unknown>>>(
380
+ `SELECT * FROM events WHERE session_id = ? ORDER BY timestamp ASC`,
381
+ [sessionId]
382
+ );
383
+
384
+ return rows.map(this.rowToEvent);
385
+ }
386
+
387
+ /**
388
+ * Get recent events
389
+ */
390
+ async getRecentEvents(limit: number = 100): Promise<MemoryEvent[]> {
391
+ await this.initialize();
392
+
393
+ const rows = await this.db.all<Array<Record<string, unknown>>>(
394
+ `SELECT * FROM events ORDER BY timestamp DESC LIMIT ?`,
395
+ [limit]
396
+ );
397
+
398
+ return rows.map(this.rowToEvent);
399
+ }
400
+
401
+ /**
402
+ * Get event by ID
403
+ */
404
+ async getEvent(id: string): Promise<MemoryEvent | null> {
405
+ await this.initialize();
406
+
407
+ const rows = await this.db.all<Array<Record<string, unknown>>>(
408
+ `SELECT * FROM events WHERE id = ?`,
409
+ [id]
410
+ );
411
+
412
+ if (rows.length === 0) return null;
413
+ return this.rowToEvent(rows[0]);
414
+ }
415
+
416
+ /**
417
+ * Create or update session
418
+ */
419
+ async upsertSession(session: Partial<Session> & { id: string }): Promise<void> {
420
+ await this.initialize();
421
+
422
+ const existing = await this.db.all<Array<{ id: string }>>(
423
+ `SELECT id FROM sessions WHERE id = ?`,
424
+ [session.id]
425
+ );
426
+
427
+ if (existing.length === 0) {
428
+ await this.db.run(
429
+ `INSERT INTO sessions (id, started_at, project_path, tags)
430
+ VALUES (?, ?, ?, ?)`,
431
+ [
432
+ session.id,
433
+ (session.startedAt || new Date()).toISOString(),
434
+ session.projectPath || null,
435
+ JSON.stringify(session.tags || [])
436
+ ]
437
+ );
438
+ } else {
439
+ const updates: string[] = [];
440
+ const values: unknown[] = [];
441
+
442
+ if (session.endedAt) {
443
+ updates.push('ended_at = ?');
444
+ values.push(session.endedAt.toISOString());
445
+ }
446
+ if (session.summary) {
447
+ updates.push('summary = ?');
448
+ values.push(session.summary);
449
+ }
450
+ if (session.tags) {
451
+ updates.push('tags = ?');
452
+ values.push(JSON.stringify(session.tags));
453
+ }
454
+
455
+ if (updates.length > 0) {
456
+ values.push(session.id);
457
+ await this.db.run(
458
+ `UPDATE sessions SET ${updates.join(', ')} WHERE id = ?`,
459
+ values
460
+ );
461
+ }
462
+ }
463
+ }
464
+
465
+ /**
466
+ * Get session by ID
467
+ */
468
+ async getSession(id: string): Promise<Session | null> {
469
+ await this.initialize();
470
+
471
+ const rows = await this.db.all<Array<Record<string, unknown>>>(
472
+ `SELECT * FROM sessions WHERE id = ?`,
473
+ [id]
474
+ );
475
+
476
+ if (rows.length === 0) return null;
477
+
478
+ const row = rows[0];
479
+ return {
480
+ id: row.id as string,
481
+ startedAt: new Date(row.started_at as string),
482
+ endedAt: row.ended_at ? new Date(row.ended_at as string) : undefined,
483
+ projectPath: row.project_path as string | undefined,
484
+ summary: row.summary as string | undefined,
485
+ tags: row.tags ? JSON.parse(row.tags as string) : undefined
486
+ };
487
+ }
488
+
489
+ /**
490
+ * Add to embedding outbox (Single-Writer Pattern)
491
+ */
492
+ async enqueueForEmbedding(eventId: string, content: string): Promise<string> {
493
+ await this.initialize();
494
+
495
+ const id = randomUUID();
496
+ await this.db.run(
497
+ `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
498
+ VALUES (?, ?, ?, 'pending', 0)`,
499
+ [id, eventId, content]
500
+ );
501
+
502
+ return id;
503
+ }
504
+
505
+ /**
506
+ * Get pending outbox items
507
+ */
508
+ async getPendingOutboxItems(limit: number = 32): Promise<OutboxItem[]> {
509
+ await this.initialize();
510
+
511
+ // Atomic update to claim items
512
+ const rows = await this.db.all<Array<Record<string, unknown>>>(
513
+ `UPDATE embedding_outbox
514
+ SET status = 'processing'
515
+ WHERE id IN (
516
+ SELECT id FROM embedding_outbox
517
+ WHERE status = 'pending'
518
+ ORDER BY created_at
519
+ LIMIT ?
520
+ )
521
+ RETURNING *`,
522
+ [limit]
523
+ );
524
+
525
+ return rows.map(row => ({
526
+ id: row.id as string,
527
+ eventId: row.event_id as string,
528
+ content: row.content as string,
529
+ status: row.status as 'pending' | 'processing' | 'done' | 'failed',
530
+ retryCount: row.retry_count as number,
531
+ createdAt: new Date(row.created_at as string),
532
+ errorMessage: row.error_message as string | undefined
533
+ }));
534
+ }
535
+
536
+ /**
537
+ * Mark outbox items as done
538
+ */
539
+ async completeOutboxItems(ids: string[]): Promise<void> {
540
+ if (ids.length === 0) return;
541
+
542
+ const placeholders = ids.map(() => '?').join(',');
543
+ await this.db.run(
544
+ `DELETE FROM embedding_outbox WHERE id IN (${placeholders})`,
545
+ ids
546
+ );
547
+ }
548
+
549
+ /**
550
+ * Mark outbox items as failed
551
+ */
552
+ async failOutboxItems(ids: string[], error: string): Promise<void> {
553
+ if (ids.length === 0) return;
554
+
555
+ const placeholders = ids.map(() => '?').join(',');
556
+ await this.db.run(
557
+ `UPDATE embedding_outbox
558
+ SET status = CASE WHEN retry_count >= 3 THEN 'failed' ELSE 'pending' END,
559
+ retry_count = retry_count + 1,
560
+ error_message = ?
561
+ WHERE id IN (${placeholders})`,
562
+ [error, ...ids]
563
+ );
564
+ }
565
+
566
+ /**
567
+ * Update memory level
568
+ */
569
+ async updateMemoryLevel(eventId: string, level: string): Promise<void> {
570
+ await this.initialize();
571
+
572
+ await this.db.run(
573
+ `UPDATE memory_levels SET level = ?, promoted_at = CURRENT_TIMESTAMP WHERE event_id = ?`,
574
+ [level, eventId]
575
+ );
576
+ }
577
+
578
+ /**
579
+ * Get memory level statistics
580
+ */
581
+ async getLevelStats(): Promise<Array<{ level: string; count: number }>> {
582
+ await this.initialize();
583
+
584
+ const rows = await this.db.all<Array<{ level: string; count: number }>>(
585
+ `SELECT level, COUNT(*) as count FROM memory_levels GROUP BY level`
586
+ );
587
+
588
+ return rows;
589
+ }
590
+
591
+ // ============================================================
592
+ // Endless Mode Helper Methods
593
+ // ============================================================
594
+
595
+ /**
596
+ * Get database instance for Endless Mode stores
597
+ */
598
+ getDatabase(): Database {
599
+ return this.db;
600
+ }
601
+
602
+ /**
603
+ * Get config value for endless mode
604
+ */
605
+ async getEndlessConfig(key: string): Promise<unknown | null> {
606
+ await this.initialize();
607
+
608
+ const rows = await this.db.all<Array<{ value: string }>>(
609
+ `SELECT value FROM endless_config WHERE key = ?`,
610
+ [key]
611
+ );
612
+
613
+ if (rows.length === 0) return null;
614
+ return JSON.parse(rows[0].value);
615
+ }
616
+
617
+ /**
618
+ * Set config value for endless mode
619
+ */
620
+ async setEndlessConfig(key: string, value: unknown): Promise<void> {
621
+ await this.initialize();
622
+
623
+ await this.db.run(
624
+ `INSERT OR REPLACE INTO endless_config (key, value, updated_at)
625
+ VALUES (?, ?, CURRENT_TIMESTAMP)`,
626
+ [key, JSON.stringify(value)]
627
+ );
628
+ }
629
+
630
+ /**
631
+ * Get all sessions
632
+ */
633
+ async getAllSessions(): Promise<Session[]> {
634
+ await this.initialize();
635
+
636
+ const rows = await this.db.all<Array<Record<string, unknown>>>(
637
+ `SELECT * FROM sessions ORDER BY started_at DESC`
638
+ );
639
+
640
+ return rows.map(row => ({
641
+ id: row.id as string,
642
+ startedAt: new Date(row.started_at as string),
643
+ endedAt: row.ended_at ? new Date(row.ended_at as string) : undefined,
644
+ projectPath: row.project_path as string | undefined,
645
+ summary: row.summary as string | undefined,
646
+ tags: row.tags ? JSON.parse(row.tags as string) : undefined
647
+ }));
648
+ }
649
+
650
+ /**
651
+ * Close database connection
652
+ */
653
+ async close(): Promise<void> {
654
+ await this.db.close();
655
+ }
656
+
657
+ /**
658
+ * Convert database row to MemoryEvent
659
+ */
660
+ private rowToEvent(row: Record<string, unknown>): MemoryEvent {
661
+ return {
662
+ id: row.id as string,
663
+ eventType: row.event_type as 'user_prompt' | 'agent_response' | 'session_summary',
664
+ sessionId: row.session_id as string,
665
+ timestamp: new Date(row.timestamp as string),
666
+ content: row.content as string,
667
+ canonicalKey: row.canonical_key as string,
668
+ dedupeKey: row.dedupe_key as string,
669
+ metadata: row.metadata ? JSON.parse(row.metadata as string) : undefined
670
+ };
671
+ }
672
+ }