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,2931 @@
1
+ import { createRequire } from 'module';
2
+ import { fileURLToPath } from 'url';
3
+ import { dirname } from 'path';
4
+ const require = createRequire(import.meta.url);
5
+ const __filename = fileURLToPath(import.meta.url);
6
+ const __dirname = dirname(__filename);
7
+
8
+ // src/services/memory-service.ts
9
+ import * as path from "path";
10
+ import * as os from "os";
11
+ import * as fs from "fs";
12
+ import * as crypto2 from "crypto";
13
+
14
+ // src/core/event-store.ts
15
+ import { Database } from "duckdb";
16
+ import { randomUUID } from "crypto";
17
+
18
+ // src/core/canonical-key.ts
19
+ import { createHash } from "crypto";
20
+ var MAX_KEY_LENGTH = 200;
21
+ function makeCanonicalKey(title, context) {
22
+ let normalized = title.normalize("NFKC");
23
+ normalized = normalized.toLowerCase();
24
+ normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, "");
25
+ normalized = normalized.replace(/\s+/g, " ").trim();
26
+ let key = normalized;
27
+ if (context?.project) {
28
+ key = `${context.project}::${key}`;
29
+ }
30
+ if (key.length > MAX_KEY_LENGTH) {
31
+ const hashSuffix = createHash("md5").update(key).digest("hex").slice(0, 8);
32
+ key = key.slice(0, MAX_KEY_LENGTH - 9) + "_" + hashSuffix;
33
+ }
34
+ return key;
35
+ }
36
+ function makeDedupeKey(content, sessionId) {
37
+ const contentHash = createHash("sha256").update(content).digest("hex");
38
+ return `${sessionId}:${contentHash}`;
39
+ }
40
+
41
+ // src/core/event-store.ts
42
+ var EventStore = class {
43
+ constructor(dbPath) {
44
+ this.dbPath = dbPath;
45
+ this.db = new Database(dbPath);
46
+ }
47
+ db;
48
+ initialized = false;
49
+ /**
50
+ * Initialize database schema
51
+ */
52
+ async initialize() {
53
+ if (this.initialized)
54
+ return;
55
+ await this.db.run(`
56
+ CREATE TABLE IF NOT EXISTS events (
57
+ id VARCHAR PRIMARY KEY,
58
+ event_type VARCHAR NOT NULL,
59
+ session_id VARCHAR NOT NULL,
60
+ timestamp TIMESTAMP NOT NULL,
61
+ content TEXT NOT NULL,
62
+ canonical_key VARCHAR NOT NULL,
63
+ dedupe_key VARCHAR UNIQUE,
64
+ metadata JSON
65
+ )
66
+ `);
67
+ await this.db.run(`
68
+ CREATE TABLE IF NOT EXISTS event_dedup (
69
+ dedupe_key VARCHAR PRIMARY KEY,
70
+ event_id VARCHAR NOT NULL,
71
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
72
+ )
73
+ `);
74
+ await this.db.run(`
75
+ CREATE TABLE IF NOT EXISTS sessions (
76
+ id VARCHAR PRIMARY KEY,
77
+ started_at TIMESTAMP NOT NULL,
78
+ ended_at TIMESTAMP,
79
+ project_path VARCHAR,
80
+ summary TEXT,
81
+ tags JSON
82
+ )
83
+ `);
84
+ await this.db.run(`
85
+ CREATE TABLE IF NOT EXISTS insights (
86
+ id VARCHAR PRIMARY KEY,
87
+ insight_type VARCHAR NOT NULL,
88
+ content TEXT NOT NULL,
89
+ canonical_key VARCHAR NOT NULL,
90
+ confidence FLOAT,
91
+ source_events JSON,
92
+ created_at TIMESTAMP,
93
+ last_updated TIMESTAMP
94
+ )
95
+ `);
96
+ await this.db.run(`
97
+ CREATE TABLE IF NOT EXISTS embedding_outbox (
98
+ id VARCHAR PRIMARY KEY,
99
+ event_id VARCHAR NOT NULL,
100
+ content TEXT NOT NULL,
101
+ status VARCHAR DEFAULT 'pending',
102
+ retry_count INT DEFAULT 0,
103
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
104
+ processed_at TIMESTAMP,
105
+ error_message TEXT
106
+ )
107
+ `);
108
+ await this.db.run(`
109
+ CREATE TABLE IF NOT EXISTS projection_offsets (
110
+ projection_name VARCHAR PRIMARY KEY,
111
+ last_event_id VARCHAR,
112
+ last_timestamp TIMESTAMP,
113
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
114
+ )
115
+ `);
116
+ await this.db.run(`
117
+ CREATE TABLE IF NOT EXISTS memory_levels (
118
+ event_id VARCHAR PRIMARY KEY,
119
+ level VARCHAR NOT NULL DEFAULT 'L0',
120
+ promoted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
121
+ )
122
+ `);
123
+ await this.db.run(`
124
+ CREATE TABLE IF NOT EXISTS entries (
125
+ entry_id VARCHAR PRIMARY KEY,
126
+ created_ts TIMESTAMP NOT NULL,
127
+ entry_type VARCHAR NOT NULL,
128
+ title VARCHAR NOT NULL,
129
+ content_json JSON NOT NULL,
130
+ stage VARCHAR NOT NULL DEFAULT 'raw',
131
+ status VARCHAR DEFAULT 'active',
132
+ superseded_by VARCHAR,
133
+ build_id VARCHAR,
134
+ evidence_json JSON,
135
+ canonical_key VARCHAR,
136
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
137
+ )
138
+ `);
139
+ await this.db.run(`
140
+ CREATE TABLE IF NOT EXISTS entities (
141
+ entity_id VARCHAR PRIMARY KEY,
142
+ entity_type VARCHAR NOT NULL,
143
+ canonical_key VARCHAR NOT NULL,
144
+ title VARCHAR NOT NULL,
145
+ stage VARCHAR NOT NULL DEFAULT 'raw',
146
+ status VARCHAR NOT NULL DEFAULT 'active',
147
+ current_json JSON NOT NULL,
148
+ title_norm VARCHAR,
149
+ search_text VARCHAR,
150
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
151
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
152
+ )
153
+ `);
154
+ await this.db.run(`
155
+ CREATE TABLE IF NOT EXISTS entity_aliases (
156
+ entity_type VARCHAR NOT NULL,
157
+ canonical_key VARCHAR NOT NULL,
158
+ entity_id VARCHAR NOT NULL,
159
+ is_primary BOOLEAN DEFAULT FALSE,
160
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
161
+ PRIMARY KEY(entity_type, canonical_key)
162
+ )
163
+ `);
164
+ await this.db.run(`
165
+ CREATE TABLE IF NOT EXISTS edges (
166
+ edge_id VARCHAR PRIMARY KEY,
167
+ src_type VARCHAR NOT NULL,
168
+ src_id VARCHAR NOT NULL,
169
+ rel_type VARCHAR NOT NULL,
170
+ dst_type VARCHAR NOT NULL,
171
+ dst_id VARCHAR NOT NULL,
172
+ meta_json JSON,
173
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
174
+ )
175
+ `);
176
+ await this.db.run(`
177
+ CREATE TABLE IF NOT EXISTS vector_outbox (
178
+ job_id VARCHAR PRIMARY KEY,
179
+ item_kind VARCHAR NOT NULL,
180
+ item_id VARCHAR NOT NULL,
181
+ embedding_version VARCHAR NOT NULL,
182
+ status VARCHAR NOT NULL DEFAULT 'pending',
183
+ retry_count INT DEFAULT 0,
184
+ error VARCHAR,
185
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
186
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
187
+ UNIQUE(item_kind, item_id, embedding_version)
188
+ )
189
+ `);
190
+ await this.db.run(`
191
+ CREATE TABLE IF NOT EXISTS build_runs (
192
+ build_id VARCHAR PRIMARY KEY,
193
+ started_at TIMESTAMP NOT NULL,
194
+ finished_at TIMESTAMP,
195
+ extractor_model VARCHAR NOT NULL,
196
+ extractor_prompt_hash VARCHAR NOT NULL,
197
+ embedder_model VARCHAR NOT NULL,
198
+ embedding_version VARCHAR NOT NULL,
199
+ idris_version VARCHAR NOT NULL,
200
+ schema_version VARCHAR NOT NULL,
201
+ status VARCHAR NOT NULL DEFAULT 'running',
202
+ error VARCHAR
203
+ )
204
+ `);
205
+ await this.db.run(`
206
+ CREATE TABLE IF NOT EXISTS pipeline_metrics (
207
+ id VARCHAR PRIMARY KEY,
208
+ ts TIMESTAMP NOT NULL,
209
+ stage VARCHAR NOT NULL,
210
+ latency_ms DOUBLE NOT NULL,
211
+ success BOOLEAN NOT NULL,
212
+ error VARCHAR,
213
+ session_id VARCHAR
214
+ )
215
+ `);
216
+ await this.db.run(`
217
+ CREATE TABLE IF NOT EXISTS working_set (
218
+ id VARCHAR PRIMARY KEY,
219
+ event_id VARCHAR NOT NULL,
220
+ added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
221
+ relevance_score FLOAT DEFAULT 1.0,
222
+ topics JSON,
223
+ expires_at TIMESTAMP
224
+ )
225
+ `);
226
+ await this.db.run(`
227
+ CREATE TABLE IF NOT EXISTS consolidated_memories (
228
+ memory_id VARCHAR PRIMARY KEY,
229
+ summary TEXT NOT NULL,
230
+ topics JSON,
231
+ source_events JSON,
232
+ confidence FLOAT DEFAULT 0.5,
233
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
234
+ accessed_at TIMESTAMP,
235
+ access_count INTEGER DEFAULT 0
236
+ )
237
+ `);
238
+ await this.db.run(`
239
+ CREATE TABLE IF NOT EXISTS continuity_log (
240
+ log_id VARCHAR PRIMARY KEY,
241
+ from_context_id VARCHAR,
242
+ to_context_id VARCHAR,
243
+ continuity_score FLOAT,
244
+ transition_type VARCHAR,
245
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
246
+ )
247
+ `);
248
+ await this.db.run(`
249
+ CREATE TABLE IF NOT EXISTS endless_config (
250
+ key VARCHAR PRIMARY KEY,
251
+ value JSON,
252
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
253
+ )
254
+ `);
255
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_entries_type ON entries(entry_type)`);
256
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_entries_stage ON entries(stage)`);
257
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_entries_canonical ON entries(canonical_key)`);
258
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_entities_type_key ON entities(entity_type, canonical_key)`);
259
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_entities_status ON entities(status)`);
260
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src_id, rel_type)`);
261
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_edges_dst ON edges(dst_id, rel_type)`);
262
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_edges_rel ON edges(rel_type)`);
263
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_outbox_status ON vector_outbox(status)`);
264
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_working_set_expires ON working_set(expires_at)`);
265
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_working_set_relevance ON working_set(relevance_score DESC)`);
266
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence DESC)`);
267
+ await this.db.run(`CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at)`);
268
+ this.initialized = true;
269
+ }
270
+ /**
271
+ * Append event to store (AXIOMMIND Principle 2: Append-only)
272
+ * Returns existing event ID if duplicate (Principle 3: Idempotency)
273
+ */
274
+ async append(input) {
275
+ await this.initialize();
276
+ const canonicalKey = makeCanonicalKey(input.content);
277
+ const dedupeKey = makeDedupeKey(input.content, input.sessionId);
278
+ const existing = await this.db.all(
279
+ `SELECT event_id FROM event_dedup WHERE dedupe_key = ?`,
280
+ [dedupeKey]
281
+ );
282
+ if (existing.length > 0) {
283
+ return {
284
+ success: true,
285
+ eventId: existing[0].event_id,
286
+ isDuplicate: true
287
+ };
288
+ }
289
+ const id = randomUUID();
290
+ const timestamp = input.timestamp.toISOString();
291
+ try {
292
+ await this.db.run(
293
+ `INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
294
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
295
+ [
296
+ id,
297
+ input.eventType,
298
+ input.sessionId,
299
+ timestamp,
300
+ input.content,
301
+ canonicalKey,
302
+ dedupeKey,
303
+ JSON.stringify(input.metadata || {})
304
+ ]
305
+ );
306
+ await this.db.run(
307
+ `INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)`,
308
+ [dedupeKey, id]
309
+ );
310
+ await this.db.run(
311
+ `INSERT INTO memory_levels (event_id, level) VALUES (?, 'L0')`,
312
+ [id]
313
+ );
314
+ return { success: true, eventId: id, isDuplicate: false };
315
+ } catch (error) {
316
+ return {
317
+ success: false,
318
+ error: error instanceof Error ? error.message : String(error)
319
+ };
320
+ }
321
+ }
322
+ /**
323
+ * Get events by session ID
324
+ */
325
+ async getSessionEvents(sessionId) {
326
+ await this.initialize();
327
+ const rows = await this.db.all(
328
+ `SELECT * FROM events WHERE session_id = ? ORDER BY timestamp ASC`,
329
+ [sessionId]
330
+ );
331
+ return rows.map(this.rowToEvent);
332
+ }
333
+ /**
334
+ * Get recent events
335
+ */
336
+ async getRecentEvents(limit = 100) {
337
+ await this.initialize();
338
+ const rows = await this.db.all(
339
+ `SELECT * FROM events ORDER BY timestamp DESC LIMIT ?`,
340
+ [limit]
341
+ );
342
+ return rows.map(this.rowToEvent);
343
+ }
344
+ /**
345
+ * Get event by ID
346
+ */
347
+ async getEvent(id) {
348
+ await this.initialize();
349
+ const rows = await this.db.all(
350
+ `SELECT * FROM events WHERE id = ?`,
351
+ [id]
352
+ );
353
+ if (rows.length === 0)
354
+ return null;
355
+ return this.rowToEvent(rows[0]);
356
+ }
357
+ /**
358
+ * Create or update session
359
+ */
360
+ async upsertSession(session) {
361
+ await this.initialize();
362
+ const existing = await this.db.all(
363
+ `SELECT id FROM sessions WHERE id = ?`,
364
+ [session.id]
365
+ );
366
+ if (existing.length === 0) {
367
+ await this.db.run(
368
+ `INSERT INTO sessions (id, started_at, project_path, tags)
369
+ VALUES (?, ?, ?, ?)`,
370
+ [
371
+ session.id,
372
+ (session.startedAt || /* @__PURE__ */ new Date()).toISOString(),
373
+ session.projectPath || null,
374
+ JSON.stringify(session.tags || [])
375
+ ]
376
+ );
377
+ } else {
378
+ const updates = [];
379
+ const values = [];
380
+ if (session.endedAt) {
381
+ updates.push("ended_at = ?");
382
+ values.push(session.endedAt.toISOString());
383
+ }
384
+ if (session.summary) {
385
+ updates.push("summary = ?");
386
+ values.push(session.summary);
387
+ }
388
+ if (session.tags) {
389
+ updates.push("tags = ?");
390
+ values.push(JSON.stringify(session.tags));
391
+ }
392
+ if (updates.length > 0) {
393
+ values.push(session.id);
394
+ await this.db.run(
395
+ `UPDATE sessions SET ${updates.join(", ")} WHERE id = ?`,
396
+ values
397
+ );
398
+ }
399
+ }
400
+ }
401
+ /**
402
+ * Get session by ID
403
+ */
404
+ async getSession(id) {
405
+ await this.initialize();
406
+ const rows = await this.db.all(
407
+ `SELECT * FROM sessions WHERE id = ?`,
408
+ [id]
409
+ );
410
+ if (rows.length === 0)
411
+ return null;
412
+ const row = rows[0];
413
+ return {
414
+ id: row.id,
415
+ startedAt: new Date(row.started_at),
416
+ endedAt: row.ended_at ? new Date(row.ended_at) : void 0,
417
+ projectPath: row.project_path,
418
+ summary: row.summary,
419
+ tags: row.tags ? JSON.parse(row.tags) : void 0
420
+ };
421
+ }
422
+ /**
423
+ * Add to embedding outbox (Single-Writer Pattern)
424
+ */
425
+ async enqueueForEmbedding(eventId, content) {
426
+ await this.initialize();
427
+ const id = randomUUID();
428
+ await this.db.run(
429
+ `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
430
+ VALUES (?, ?, ?, 'pending', 0)`,
431
+ [id, eventId, content]
432
+ );
433
+ return id;
434
+ }
435
+ /**
436
+ * Get pending outbox items
437
+ */
438
+ async getPendingOutboxItems(limit = 32) {
439
+ await this.initialize();
440
+ const rows = await this.db.all(
441
+ `UPDATE embedding_outbox
442
+ SET status = 'processing'
443
+ WHERE id IN (
444
+ SELECT id FROM embedding_outbox
445
+ WHERE status = 'pending'
446
+ ORDER BY created_at
447
+ LIMIT ?
448
+ )
449
+ RETURNING *`,
450
+ [limit]
451
+ );
452
+ return rows.map((row) => ({
453
+ id: row.id,
454
+ eventId: row.event_id,
455
+ content: row.content,
456
+ status: row.status,
457
+ retryCount: row.retry_count,
458
+ createdAt: new Date(row.created_at),
459
+ errorMessage: row.error_message
460
+ }));
461
+ }
462
+ /**
463
+ * Mark outbox items as done
464
+ */
465
+ async completeOutboxItems(ids) {
466
+ if (ids.length === 0)
467
+ return;
468
+ const placeholders = ids.map(() => "?").join(",");
469
+ await this.db.run(
470
+ `DELETE FROM embedding_outbox WHERE id IN (${placeholders})`,
471
+ ids
472
+ );
473
+ }
474
+ /**
475
+ * Mark outbox items as failed
476
+ */
477
+ async failOutboxItems(ids, error) {
478
+ if (ids.length === 0)
479
+ return;
480
+ const placeholders = ids.map(() => "?").join(",");
481
+ await this.db.run(
482
+ `UPDATE embedding_outbox
483
+ SET status = CASE WHEN retry_count >= 3 THEN 'failed' ELSE 'pending' END,
484
+ retry_count = retry_count + 1,
485
+ error_message = ?
486
+ WHERE id IN (${placeholders})`,
487
+ [error, ...ids]
488
+ );
489
+ }
490
+ /**
491
+ * Update memory level
492
+ */
493
+ async updateMemoryLevel(eventId, level) {
494
+ await this.initialize();
495
+ await this.db.run(
496
+ `UPDATE memory_levels SET level = ?, promoted_at = CURRENT_TIMESTAMP WHERE event_id = ?`,
497
+ [level, eventId]
498
+ );
499
+ }
500
+ /**
501
+ * Get memory level statistics
502
+ */
503
+ async getLevelStats() {
504
+ await this.initialize();
505
+ const rows = await this.db.all(
506
+ `SELECT level, COUNT(*) as count FROM memory_levels GROUP BY level`
507
+ );
508
+ return rows;
509
+ }
510
+ // ============================================================
511
+ // Endless Mode Helper Methods
512
+ // ============================================================
513
+ /**
514
+ * Get database instance for Endless Mode stores
515
+ */
516
+ getDatabase() {
517
+ return this.db;
518
+ }
519
+ /**
520
+ * Get config value for endless mode
521
+ */
522
+ async getEndlessConfig(key) {
523
+ await this.initialize();
524
+ const rows = await this.db.all(
525
+ `SELECT value FROM endless_config WHERE key = ?`,
526
+ [key]
527
+ );
528
+ if (rows.length === 0)
529
+ return null;
530
+ return JSON.parse(rows[0].value);
531
+ }
532
+ /**
533
+ * Set config value for endless mode
534
+ */
535
+ async setEndlessConfig(key, value) {
536
+ await this.initialize();
537
+ await this.db.run(
538
+ `INSERT OR REPLACE INTO endless_config (key, value, updated_at)
539
+ VALUES (?, ?, CURRENT_TIMESTAMP)`,
540
+ [key, JSON.stringify(value)]
541
+ );
542
+ }
543
+ /**
544
+ * Get all sessions
545
+ */
546
+ async getAllSessions() {
547
+ await this.initialize();
548
+ const rows = await this.db.all(
549
+ `SELECT * FROM sessions ORDER BY started_at DESC`
550
+ );
551
+ return rows.map((row) => ({
552
+ id: row.id,
553
+ startedAt: new Date(row.started_at),
554
+ endedAt: row.ended_at ? new Date(row.ended_at) : void 0,
555
+ projectPath: row.project_path,
556
+ summary: row.summary,
557
+ tags: row.tags ? JSON.parse(row.tags) : void 0
558
+ }));
559
+ }
560
+ /**
561
+ * Close database connection
562
+ */
563
+ async close() {
564
+ await this.db.close();
565
+ }
566
+ /**
567
+ * Convert database row to MemoryEvent
568
+ */
569
+ rowToEvent(row) {
570
+ return {
571
+ id: row.id,
572
+ eventType: row.event_type,
573
+ sessionId: row.session_id,
574
+ timestamp: new Date(row.timestamp),
575
+ content: row.content,
576
+ canonicalKey: row.canonical_key,
577
+ dedupeKey: row.dedupe_key,
578
+ metadata: row.metadata ? JSON.parse(row.metadata) : void 0
579
+ };
580
+ }
581
+ };
582
+
583
+ // src/core/vector-store.ts
584
+ import * as lancedb from "@lancedb/lancedb";
585
+ var VectorStore = class {
586
+ constructor(dbPath) {
587
+ this.dbPath = dbPath;
588
+ }
589
+ db = null;
590
+ table = null;
591
+ tableName = "conversations";
592
+ /**
593
+ * Initialize LanceDB connection
594
+ */
595
+ async initialize() {
596
+ if (this.db)
597
+ return;
598
+ this.db = await lancedb.connect(this.dbPath);
599
+ try {
600
+ const tables = await this.db.tableNames();
601
+ if (tables.includes(this.tableName)) {
602
+ this.table = await this.db.openTable(this.tableName);
603
+ }
604
+ } catch {
605
+ this.table = null;
606
+ }
607
+ }
608
+ /**
609
+ * Add or update vector record
610
+ */
611
+ async upsert(record) {
612
+ await this.initialize();
613
+ if (!this.db) {
614
+ throw new Error("Database not initialized");
615
+ }
616
+ const data = {
617
+ id: record.id,
618
+ eventId: record.eventId,
619
+ sessionId: record.sessionId,
620
+ eventType: record.eventType,
621
+ content: record.content,
622
+ vector: record.vector,
623
+ timestamp: record.timestamp,
624
+ metadata: JSON.stringify(record.metadata || {})
625
+ };
626
+ if (!this.table) {
627
+ this.table = await this.db.createTable(this.tableName, [data]);
628
+ } else {
629
+ await this.table.add([data]);
630
+ }
631
+ }
632
+ /**
633
+ * Add multiple vector records in batch
634
+ */
635
+ async upsertBatch(records) {
636
+ if (records.length === 0)
637
+ return;
638
+ await this.initialize();
639
+ if (!this.db) {
640
+ throw new Error("Database not initialized");
641
+ }
642
+ const data = records.map((record) => ({
643
+ id: record.id,
644
+ eventId: record.eventId,
645
+ sessionId: record.sessionId,
646
+ eventType: record.eventType,
647
+ content: record.content,
648
+ vector: record.vector,
649
+ timestamp: record.timestamp,
650
+ metadata: JSON.stringify(record.metadata || {})
651
+ }));
652
+ if (!this.table) {
653
+ this.table = await this.db.createTable(this.tableName, data);
654
+ } else {
655
+ await this.table.add(data);
656
+ }
657
+ }
658
+ /**
659
+ * Search for similar vectors
660
+ */
661
+ async search(queryVector, options = {}) {
662
+ await this.initialize();
663
+ if (!this.table) {
664
+ return [];
665
+ }
666
+ const { limit = 5, minScore = 0.7, sessionId } = options;
667
+ let query = this.table.search(queryVector).limit(limit * 2);
668
+ if (sessionId) {
669
+ query = query.where(`sessionId = '${sessionId}'`);
670
+ }
671
+ const results = await query.toArray();
672
+ return results.filter((r) => {
673
+ const score = 1 - (r._distance || 0);
674
+ return score >= minScore;
675
+ }).slice(0, limit).map((r) => ({
676
+ id: r.id,
677
+ eventId: r.eventId,
678
+ content: r.content,
679
+ score: 1 - (r._distance || 0),
680
+ sessionId: r.sessionId,
681
+ eventType: r.eventType,
682
+ timestamp: r.timestamp
683
+ }));
684
+ }
685
+ /**
686
+ * Delete vector by event ID
687
+ */
688
+ async delete(eventId) {
689
+ if (!this.table)
690
+ return;
691
+ await this.table.delete(`eventId = '${eventId}'`);
692
+ }
693
+ /**
694
+ * Get total count of vectors
695
+ */
696
+ async count() {
697
+ if (!this.table)
698
+ return 0;
699
+ const result = await this.table.countRows();
700
+ return result;
701
+ }
702
+ /**
703
+ * Check if vector exists for event
704
+ */
705
+ async exists(eventId) {
706
+ if (!this.table)
707
+ return false;
708
+ const results = await this.table.search([]).where(`eventId = '${eventId}'`).limit(1).toArray();
709
+ return results.length > 0;
710
+ }
711
+ };
712
+
713
+ // src/core/embedder.ts
714
+ import { pipeline } from "@xenova/transformers";
715
+ var Embedder = class {
716
+ pipeline = null;
717
+ modelName;
718
+ initialized = false;
719
+ constructor(modelName = "Xenova/all-MiniLM-L6-v2") {
720
+ this.modelName = modelName;
721
+ }
722
+ /**
723
+ * Initialize the embedding pipeline
724
+ */
725
+ async initialize() {
726
+ if (this.initialized)
727
+ return;
728
+ this.pipeline = await pipeline("feature-extraction", this.modelName);
729
+ this.initialized = true;
730
+ }
731
+ /**
732
+ * Generate embedding for a single text
733
+ */
734
+ async embed(text) {
735
+ await this.initialize();
736
+ if (!this.pipeline) {
737
+ throw new Error("Embedding pipeline not initialized");
738
+ }
739
+ const output = await this.pipeline(text, {
740
+ pooling: "mean",
741
+ normalize: true
742
+ });
743
+ const vector = Array.from(output.data);
744
+ return {
745
+ vector,
746
+ model: this.modelName,
747
+ dimensions: vector.length
748
+ };
749
+ }
750
+ /**
751
+ * Generate embeddings for multiple texts in batch
752
+ */
753
+ async embedBatch(texts) {
754
+ await this.initialize();
755
+ if (!this.pipeline) {
756
+ throw new Error("Embedding pipeline not initialized");
757
+ }
758
+ const results = [];
759
+ const batchSize = 32;
760
+ for (let i = 0; i < texts.length; i += batchSize) {
761
+ const batch = texts.slice(i, i + batchSize);
762
+ for (const text of batch) {
763
+ const output = await this.pipeline(text, {
764
+ pooling: "mean",
765
+ normalize: true
766
+ });
767
+ const vector = Array.from(output.data);
768
+ results.push({
769
+ vector,
770
+ model: this.modelName,
771
+ dimensions: vector.length
772
+ });
773
+ }
774
+ }
775
+ return results;
776
+ }
777
+ /**
778
+ * Get embedding dimensions for the current model
779
+ */
780
+ async getDimensions() {
781
+ const result = await this.embed("test");
782
+ return result.dimensions;
783
+ }
784
+ /**
785
+ * Check if embedder is ready
786
+ */
787
+ isReady() {
788
+ return this.initialized && this.pipeline !== null;
789
+ }
790
+ /**
791
+ * Get model name
792
+ */
793
+ getModelName() {
794
+ return this.modelName;
795
+ }
796
+ };
797
+ var defaultEmbedder = null;
798
+ function getDefaultEmbedder() {
799
+ if (!defaultEmbedder) {
800
+ defaultEmbedder = new Embedder();
801
+ }
802
+ return defaultEmbedder;
803
+ }
804
+
805
+ // src/core/vector-outbox.ts
806
+ var DEFAULT_CONFIG = {
807
+ embeddingVersion: "v1",
808
+ maxRetries: 3,
809
+ stuckThresholdMs: 5 * 60 * 1e3,
810
+ // 5 minutes
811
+ cleanupDays: 7
812
+ };
813
+
814
+ // src/core/vector-worker.ts
815
+ var DEFAULT_CONFIG2 = {
816
+ batchSize: 32,
817
+ pollIntervalMs: 1e3,
818
+ maxRetries: 3
819
+ };
820
+ var VectorWorker = class {
821
+ eventStore;
822
+ vectorStore;
823
+ embedder;
824
+ config;
825
+ running = false;
826
+ pollTimeout = null;
827
+ constructor(eventStore, vectorStore, embedder, config = {}) {
828
+ this.eventStore = eventStore;
829
+ this.vectorStore = vectorStore;
830
+ this.embedder = embedder;
831
+ this.config = { ...DEFAULT_CONFIG2, ...config };
832
+ }
833
+ /**
834
+ * Start the worker polling loop
835
+ */
836
+ start() {
837
+ if (this.running)
838
+ return;
839
+ this.running = true;
840
+ this.poll();
841
+ }
842
+ /**
843
+ * Stop the worker
844
+ */
845
+ stop() {
846
+ this.running = false;
847
+ if (this.pollTimeout) {
848
+ clearTimeout(this.pollTimeout);
849
+ this.pollTimeout = null;
850
+ }
851
+ }
852
+ /**
853
+ * Process a single batch of outbox items
854
+ */
855
+ async processBatch() {
856
+ const items = await this.eventStore.getPendingOutboxItems(this.config.batchSize);
857
+ if (items.length === 0) {
858
+ return 0;
859
+ }
860
+ const successful = [];
861
+ const failed = [];
862
+ try {
863
+ const embeddings = await this.embedder.embedBatch(items.map((i) => i.content));
864
+ const records = [];
865
+ for (let i = 0; i < items.length; i++) {
866
+ const item = items[i];
867
+ const embedding = embeddings[i];
868
+ const event = await this.eventStore.getEvent(item.eventId);
869
+ if (!event) {
870
+ failed.push(item.id);
871
+ continue;
872
+ }
873
+ records.push({
874
+ id: `vec_${item.id}`,
875
+ eventId: item.eventId,
876
+ sessionId: event.sessionId,
877
+ eventType: event.eventType,
878
+ content: item.content,
879
+ vector: embedding.vector,
880
+ timestamp: event.timestamp.toISOString(),
881
+ metadata: event.metadata
882
+ });
883
+ successful.push(item.id);
884
+ }
885
+ if (records.length > 0) {
886
+ await this.vectorStore.upsertBatch(records);
887
+ }
888
+ if (successful.length > 0) {
889
+ await this.eventStore.completeOutboxItems(successful);
890
+ }
891
+ if (failed.length > 0) {
892
+ await this.eventStore.failOutboxItems(failed, "Event not found");
893
+ }
894
+ return successful.length;
895
+ } catch (error) {
896
+ const allIds = items.map((i) => i.id);
897
+ const errorMessage = error instanceof Error ? error.message : String(error);
898
+ await this.eventStore.failOutboxItems(allIds, errorMessage);
899
+ throw error;
900
+ }
901
+ }
902
+ /**
903
+ * Poll for new items
904
+ */
905
+ async poll() {
906
+ if (!this.running)
907
+ return;
908
+ try {
909
+ await this.processBatch();
910
+ } catch (error) {
911
+ console.error("Vector worker error:", error);
912
+ }
913
+ this.pollTimeout = setTimeout(() => this.poll(), this.config.pollIntervalMs);
914
+ }
915
+ /**
916
+ * Process all pending items (blocking)
917
+ */
918
+ async processAll() {
919
+ let totalProcessed = 0;
920
+ let processed;
921
+ do {
922
+ processed = await this.processBatch();
923
+ totalProcessed += processed;
924
+ } while (processed > 0);
925
+ return totalProcessed;
926
+ }
927
+ /**
928
+ * Check if worker is running
929
+ */
930
+ isRunning() {
931
+ return this.running;
932
+ }
933
+ };
934
+ function createVectorWorker(eventStore, vectorStore, embedder, config) {
935
+ const worker = new VectorWorker(eventStore, vectorStore, embedder, config);
936
+ return worker;
937
+ }
938
+
939
+ // src/core/matcher.ts
940
+ var DEFAULT_CONFIG3 = {
941
+ weights: {
942
+ semanticSimilarity: 0.4,
943
+ ftsScore: 0.25,
944
+ recencyBonus: 0.2,
945
+ statusWeight: 0.15
946
+ },
947
+ minCombinedScore: 0.92,
948
+ minGap: 0.03,
949
+ suggestionThreshold: 0.75
950
+ };
951
+ var Matcher = class {
952
+ config;
953
+ constructor(config = {}) {
954
+ this.config = {
955
+ ...DEFAULT_CONFIG3,
956
+ ...config,
957
+ weights: { ...DEFAULT_CONFIG3.weights, ...config.weights }
958
+ };
959
+ }
960
+ /**
961
+ * Calculate combined score using AXIOMMIND weighted formula
962
+ */
963
+ calculateCombinedScore(semanticScore, ftsScore = 0, recencyDays = 0, isActive = true) {
964
+ const { weights } = this.config;
965
+ const recencyBonus = Math.max(0, 1 - recencyDays / 30);
966
+ const statusMultiplier = isActive ? 1 : 0.7;
967
+ const combinedScore = weights.semanticSimilarity * semanticScore + weights.ftsScore * ftsScore + weights.recencyBonus * recencyBonus + weights.statusWeight * statusMultiplier;
968
+ return Math.min(1, combinedScore);
969
+ }
970
+ /**
971
+ * Classify match confidence based on AXIOMMIND thresholds
972
+ */
973
+ classifyConfidence(topScore, secondScore) {
974
+ const { minCombinedScore, minGap, suggestionThreshold } = this.config;
975
+ const gap = secondScore !== null ? topScore - secondScore : Infinity;
976
+ if (topScore >= minCombinedScore && gap >= minGap) {
977
+ return "high";
978
+ }
979
+ if (topScore >= suggestionThreshold) {
980
+ return "suggested";
981
+ }
982
+ return "none";
983
+ }
984
+ /**
985
+ * Match search results to find best memory
986
+ */
987
+ matchSearchResults(results, getEventAge) {
988
+ if (results.length === 0) {
989
+ return {
990
+ match: null,
991
+ confidence: "none"
992
+ };
993
+ }
994
+ const scoredResults = results.map((result) => {
995
+ const ageDays = getEventAge(result.eventId);
996
+ const combinedScore = this.calculateCombinedScore(
997
+ result.score,
998
+ 0,
999
+ // FTS score - would need to be passed in
1000
+ ageDays,
1001
+ true
1002
+ // Assume active
1003
+ );
1004
+ return {
1005
+ result,
1006
+ combinedScore
1007
+ };
1008
+ });
1009
+ scoredResults.sort((a, b) => b.combinedScore - a.combinedScore);
1010
+ const topResult = scoredResults[0];
1011
+ const secondScore = scoredResults.length > 1 ? scoredResults[1].combinedScore : null;
1012
+ const confidence = this.classifyConfidence(topResult.combinedScore, secondScore);
1013
+ const match = {
1014
+ event: {
1015
+ id: topResult.result.eventId,
1016
+ eventType: topResult.result.eventType,
1017
+ sessionId: topResult.result.sessionId,
1018
+ timestamp: new Date(topResult.result.timestamp),
1019
+ content: topResult.result.content,
1020
+ canonicalKey: "",
1021
+ // Would need to be fetched
1022
+ dedupeKey: ""
1023
+ // Would need to be fetched
1024
+ },
1025
+ score: topResult.combinedScore
1026
+ };
1027
+ const gap = secondScore !== null ? topResult.combinedScore - secondScore : void 0;
1028
+ const alternatives = confidence === "suggested" ? scoredResults.slice(1, 4).map((sr) => ({
1029
+ event: {
1030
+ id: sr.result.eventId,
1031
+ eventType: sr.result.eventType,
1032
+ sessionId: sr.result.sessionId,
1033
+ timestamp: new Date(sr.result.timestamp),
1034
+ content: sr.result.content,
1035
+ canonicalKey: "",
1036
+ dedupeKey: ""
1037
+ },
1038
+ score: sr.combinedScore
1039
+ })) : void 0;
1040
+ return {
1041
+ match: confidence !== "none" ? match : null,
1042
+ confidence,
1043
+ gap,
1044
+ alternatives
1045
+ };
1046
+ }
1047
+ /**
1048
+ * Calculate days between two dates
1049
+ */
1050
+ static calculateAgeDays(timestamp) {
1051
+ const now = /* @__PURE__ */ new Date();
1052
+ const diffMs = now.getTime() - timestamp.getTime();
1053
+ return diffMs / (1e3 * 60 * 60 * 24);
1054
+ }
1055
+ /**
1056
+ * Get current configuration
1057
+ */
1058
+ getConfig() {
1059
+ return { ...this.config };
1060
+ }
1061
+ };
1062
+ var defaultMatcher = null;
1063
+ function getDefaultMatcher() {
1064
+ if (!defaultMatcher) {
1065
+ defaultMatcher = new Matcher();
1066
+ }
1067
+ return defaultMatcher;
1068
+ }
1069
+
1070
+ // src/core/retriever.ts
1071
+ var DEFAULT_OPTIONS = {
1072
+ topK: 5,
1073
+ minScore: 0.7,
1074
+ maxTokens: 2e3,
1075
+ includeSessionContext: true
1076
+ };
1077
+ var Retriever = class {
1078
+ eventStore;
1079
+ vectorStore;
1080
+ embedder;
1081
+ matcher;
1082
+ constructor(eventStore, vectorStore, embedder, matcher) {
1083
+ this.eventStore = eventStore;
1084
+ this.vectorStore = vectorStore;
1085
+ this.embedder = embedder;
1086
+ this.matcher = matcher;
1087
+ }
1088
+ /**
1089
+ * Retrieve relevant memories for a query
1090
+ */
1091
+ async retrieve(query, options = {}) {
1092
+ const opts = { ...DEFAULT_OPTIONS, ...options };
1093
+ const queryEmbedding = await this.embedder.embed(query);
1094
+ const searchResults = await this.vectorStore.search(queryEmbedding.vector, {
1095
+ limit: opts.topK * 2,
1096
+ // Get extra for filtering
1097
+ minScore: opts.minScore,
1098
+ sessionId: opts.sessionId
1099
+ });
1100
+ const matchResult = this.matcher.matchSearchResults(
1101
+ searchResults,
1102
+ (eventId) => this.getEventAgeDays(eventId)
1103
+ );
1104
+ const memories = await this.enrichResults(searchResults.slice(0, opts.topK), opts);
1105
+ const context = this.buildContext(memories, opts.maxTokens);
1106
+ return {
1107
+ memories,
1108
+ matchResult,
1109
+ totalTokens: this.estimateTokens(context),
1110
+ context
1111
+ };
1112
+ }
1113
+ /**
1114
+ * Retrieve memories from a specific session
1115
+ */
1116
+ async retrieveFromSession(sessionId) {
1117
+ return this.eventStore.getSessionEvents(sessionId);
1118
+ }
1119
+ /**
1120
+ * Get recent memories across all sessions
1121
+ */
1122
+ async retrieveRecent(limit = 100) {
1123
+ return this.eventStore.getRecentEvents(limit);
1124
+ }
1125
+ /**
1126
+ * Enrich search results with full event data
1127
+ */
1128
+ async enrichResults(results, options) {
1129
+ const memories = [];
1130
+ for (const result of results) {
1131
+ const event = await this.eventStore.getEvent(result.eventId);
1132
+ if (!event)
1133
+ continue;
1134
+ let sessionContext;
1135
+ if (options.includeSessionContext) {
1136
+ sessionContext = await this.getSessionContext(event.sessionId, event.id);
1137
+ }
1138
+ memories.push({
1139
+ event,
1140
+ score: result.score,
1141
+ sessionContext
1142
+ });
1143
+ }
1144
+ return memories;
1145
+ }
1146
+ /**
1147
+ * Get surrounding context from the same session
1148
+ */
1149
+ async getSessionContext(sessionId, eventId) {
1150
+ const sessionEvents = await this.eventStore.getSessionEvents(sessionId);
1151
+ const eventIndex = sessionEvents.findIndex((e) => e.id === eventId);
1152
+ if (eventIndex === -1)
1153
+ return void 0;
1154
+ const start = Math.max(0, eventIndex - 1);
1155
+ const end = Math.min(sessionEvents.length, eventIndex + 2);
1156
+ const contextEvents = sessionEvents.slice(start, end);
1157
+ if (contextEvents.length <= 1)
1158
+ return void 0;
1159
+ return contextEvents.filter((e) => e.id !== eventId).map((e) => `[${e.eventType}]: ${e.content.slice(0, 200)}...`).join("\n");
1160
+ }
1161
+ /**
1162
+ * Build context string from memories (respecting token limit)
1163
+ */
1164
+ buildContext(memories, maxTokens) {
1165
+ const parts = [];
1166
+ let currentTokens = 0;
1167
+ for (const memory of memories) {
1168
+ const memoryText = this.formatMemory(memory);
1169
+ const memoryTokens = this.estimateTokens(memoryText);
1170
+ if (currentTokens + memoryTokens > maxTokens) {
1171
+ break;
1172
+ }
1173
+ parts.push(memoryText);
1174
+ currentTokens += memoryTokens;
1175
+ }
1176
+ if (parts.length === 0) {
1177
+ return "";
1178
+ }
1179
+ return `## Relevant Memories
1180
+
1181
+ ${parts.join("\n\n---\n\n")}`;
1182
+ }
1183
+ /**
1184
+ * Format a single memory for context
1185
+ */
1186
+ formatMemory(memory) {
1187
+ const { event, score, sessionContext } = memory;
1188
+ const date = event.timestamp.toISOString().split("T")[0];
1189
+ let text = `**${event.eventType}** (${date}, score: ${score.toFixed(2)})
1190
+ ${event.content}`;
1191
+ if (sessionContext) {
1192
+ text += `
1193
+
1194
+ _Context:_ ${sessionContext}`;
1195
+ }
1196
+ return text;
1197
+ }
1198
+ /**
1199
+ * Estimate token count (rough approximation)
1200
+ */
1201
+ estimateTokens(text) {
1202
+ return Math.ceil(text.length / 4);
1203
+ }
1204
+ /**
1205
+ * Get event age in days (for recency scoring)
1206
+ */
1207
+ getEventAgeDays(eventId) {
1208
+ return 0;
1209
+ }
1210
+ };
1211
+ function createRetriever(eventStore, vectorStore, embedder, matcher) {
1212
+ return new Retriever(eventStore, vectorStore, embedder, matcher);
1213
+ }
1214
+
1215
+ // src/core/graduation.ts
1216
+ var DEFAULT_CRITERIA = {
1217
+ L0toL1: {
1218
+ minAccessCount: 1,
1219
+ minConfidence: 0.5,
1220
+ minCrossSessionRefs: 0,
1221
+ maxAgeDays: 30
1222
+ },
1223
+ L1toL2: {
1224
+ minAccessCount: 3,
1225
+ minConfidence: 0.7,
1226
+ minCrossSessionRefs: 1,
1227
+ maxAgeDays: 60
1228
+ },
1229
+ L2toL3: {
1230
+ minAccessCount: 5,
1231
+ minConfidence: 0.85,
1232
+ minCrossSessionRefs: 2,
1233
+ maxAgeDays: 90
1234
+ },
1235
+ L3toL4: {
1236
+ minAccessCount: 10,
1237
+ minConfidence: 0.92,
1238
+ minCrossSessionRefs: 3,
1239
+ maxAgeDays: 180
1240
+ }
1241
+ };
1242
+ var GraduationPipeline = class {
1243
+ eventStore;
1244
+ criteria;
1245
+ metrics = /* @__PURE__ */ new Map();
1246
+ constructor(eventStore, criteria = {}) {
1247
+ this.eventStore = eventStore;
1248
+ this.criteria = {
1249
+ L0toL1: { ...DEFAULT_CRITERIA.L0toL1, ...criteria.L0toL1 },
1250
+ L1toL2: { ...DEFAULT_CRITERIA.L1toL2, ...criteria.L1toL2 },
1251
+ L2toL3: { ...DEFAULT_CRITERIA.L2toL3, ...criteria.L2toL3 },
1252
+ L3toL4: { ...DEFAULT_CRITERIA.L3toL4, ...criteria.L3toL4 }
1253
+ };
1254
+ }
1255
+ /**
1256
+ * Record an access to an event (used for graduation scoring)
1257
+ */
1258
+ recordAccess(eventId, fromSessionId, confidence = 1) {
1259
+ const existing = this.metrics.get(eventId);
1260
+ if (existing) {
1261
+ existing.accessCount++;
1262
+ existing.lastAccessed = /* @__PURE__ */ new Date();
1263
+ existing.confidence = Math.max(existing.confidence, confidence);
1264
+ } else {
1265
+ this.metrics.set(eventId, {
1266
+ eventId,
1267
+ accessCount: 1,
1268
+ lastAccessed: /* @__PURE__ */ new Date(),
1269
+ crossSessionRefs: 0,
1270
+ confidence
1271
+ });
1272
+ }
1273
+ }
1274
+ /**
1275
+ * Evaluate if an event should graduate to the next level
1276
+ */
1277
+ async evaluateGraduation(eventId, currentLevel) {
1278
+ const metrics = this.metrics.get(eventId);
1279
+ if (!metrics) {
1280
+ return {
1281
+ eventId,
1282
+ fromLevel: currentLevel,
1283
+ toLevel: currentLevel,
1284
+ success: false,
1285
+ reason: "No metrics available for event"
1286
+ };
1287
+ }
1288
+ const nextLevel = this.getNextLevel(currentLevel);
1289
+ if (!nextLevel) {
1290
+ return {
1291
+ eventId,
1292
+ fromLevel: currentLevel,
1293
+ toLevel: currentLevel,
1294
+ success: false,
1295
+ reason: "Already at maximum level"
1296
+ };
1297
+ }
1298
+ const criteria = this.getCriteria(currentLevel, nextLevel);
1299
+ const evaluation = this.checkCriteria(metrics, criteria);
1300
+ if (evaluation.passed) {
1301
+ await this.eventStore.updateMemoryLevel(eventId, nextLevel);
1302
+ return {
1303
+ eventId,
1304
+ fromLevel: currentLevel,
1305
+ toLevel: nextLevel,
1306
+ success: true
1307
+ };
1308
+ }
1309
+ return {
1310
+ eventId,
1311
+ fromLevel: currentLevel,
1312
+ toLevel: currentLevel,
1313
+ success: false,
1314
+ reason: evaluation.reason
1315
+ };
1316
+ }
1317
+ /**
1318
+ * Run graduation evaluation for all events at a given level
1319
+ */
1320
+ async graduateBatch(level) {
1321
+ const results = [];
1322
+ for (const [eventId, metrics] of this.metrics) {
1323
+ const result = await this.evaluateGraduation(eventId, level);
1324
+ results.push(result);
1325
+ }
1326
+ return results;
1327
+ }
1328
+ /**
1329
+ * Extract insights from graduated events (L1+)
1330
+ */
1331
+ extractInsights(events) {
1332
+ const insights = [];
1333
+ const patterns = this.detectPatterns(events);
1334
+ for (const pattern of patterns) {
1335
+ insights.push({
1336
+ id: crypto.randomUUID(),
1337
+ insightType: "pattern",
1338
+ content: pattern.description,
1339
+ canonicalKey: pattern.key,
1340
+ confidence: pattern.confidence,
1341
+ sourceEvents: pattern.eventIds,
1342
+ createdAt: /* @__PURE__ */ new Date(),
1343
+ lastUpdated: /* @__PURE__ */ new Date()
1344
+ });
1345
+ }
1346
+ const preferences = this.detectPreferences(events);
1347
+ for (const pref of preferences) {
1348
+ insights.push({
1349
+ id: crypto.randomUUID(),
1350
+ insightType: "preference",
1351
+ content: pref.description,
1352
+ canonicalKey: pref.key,
1353
+ confidence: pref.confidence,
1354
+ sourceEvents: pref.eventIds,
1355
+ createdAt: /* @__PURE__ */ new Date(),
1356
+ lastUpdated: /* @__PURE__ */ new Date()
1357
+ });
1358
+ }
1359
+ return insights;
1360
+ }
1361
+ /**
1362
+ * Get the next level in the graduation pipeline
1363
+ */
1364
+ getNextLevel(current) {
1365
+ const levels = ["L0", "L1", "L2", "L3", "L4"];
1366
+ const currentIndex = levels.indexOf(current);
1367
+ if (currentIndex === -1 || currentIndex >= levels.length - 1) {
1368
+ return null;
1369
+ }
1370
+ return levels[currentIndex + 1];
1371
+ }
1372
+ /**
1373
+ * Get criteria for level transition
1374
+ */
1375
+ getCriteria(from, to) {
1376
+ const key = `${from}to${to}`;
1377
+ return this.criteria[key] || DEFAULT_CRITERIA.L0toL1;
1378
+ }
1379
+ /**
1380
+ * Check if metrics meet criteria
1381
+ */
1382
+ checkCriteria(metrics, criteria) {
1383
+ if (metrics.accessCount < criteria.minAccessCount) {
1384
+ return {
1385
+ passed: false,
1386
+ reason: `Access count ${metrics.accessCount} < ${criteria.minAccessCount}`
1387
+ };
1388
+ }
1389
+ if (metrics.confidence < criteria.minConfidence) {
1390
+ return {
1391
+ passed: false,
1392
+ reason: `Confidence ${metrics.confidence} < ${criteria.minConfidence}`
1393
+ };
1394
+ }
1395
+ if (metrics.crossSessionRefs < criteria.minCrossSessionRefs) {
1396
+ return {
1397
+ passed: false,
1398
+ reason: `Cross-session refs ${metrics.crossSessionRefs} < ${criteria.minCrossSessionRefs}`
1399
+ };
1400
+ }
1401
+ const ageDays = (Date.now() - metrics.lastAccessed.getTime()) / (1e3 * 60 * 60 * 24);
1402
+ if (ageDays > criteria.maxAgeDays) {
1403
+ return {
1404
+ passed: false,
1405
+ reason: `Event too old: ${ageDays.toFixed(1)} days > ${criteria.maxAgeDays}`
1406
+ };
1407
+ }
1408
+ return { passed: true };
1409
+ }
1410
+ /**
1411
+ * Detect patterns in events
1412
+ */
1413
+ detectPatterns(events) {
1414
+ const keyGroups = /* @__PURE__ */ new Map();
1415
+ for (const event of events) {
1416
+ const existing = keyGroups.get(event.canonicalKey) || [];
1417
+ existing.push(event);
1418
+ keyGroups.set(event.canonicalKey, existing);
1419
+ }
1420
+ const patterns = [];
1421
+ for (const [key, groupEvents] of keyGroups) {
1422
+ if (groupEvents.length >= 2) {
1423
+ patterns.push({
1424
+ key,
1425
+ description: `Repeated topic: ${key.slice(0, 50)}`,
1426
+ confidence: Math.min(1, groupEvents.length / 5),
1427
+ eventIds: groupEvents.map((e) => e.id)
1428
+ });
1429
+ }
1430
+ }
1431
+ return patterns;
1432
+ }
1433
+ /**
1434
+ * Detect user preferences from events
1435
+ */
1436
+ detectPreferences(events) {
1437
+ const preferenceKeywords = ["prefer", "like", "want", "always", "never", "favorite"];
1438
+ const preferences = [];
1439
+ for (const event of events) {
1440
+ if (event.eventType !== "user_prompt")
1441
+ continue;
1442
+ const lowerContent = event.content.toLowerCase();
1443
+ for (const keyword of preferenceKeywords) {
1444
+ if (lowerContent.includes(keyword)) {
1445
+ preferences.push({
1446
+ key: `preference_${keyword}_${event.id.slice(0, 8)}`,
1447
+ description: `User preference: ${event.content.slice(0, 100)}`,
1448
+ confidence: 0.7,
1449
+ eventIds: [event.id]
1450
+ });
1451
+ break;
1452
+ }
1453
+ }
1454
+ }
1455
+ return preferences;
1456
+ }
1457
+ /**
1458
+ * Get graduation statistics
1459
+ */
1460
+ async getStats() {
1461
+ return this.eventStore.getLevelStats();
1462
+ }
1463
+ };
1464
+ function createGraduationPipeline(eventStore) {
1465
+ return new GraduationPipeline(eventStore);
1466
+ }
1467
+
1468
+ // src/core/metadata-extractor.ts
1469
+ function createToolObservationEmbedding(toolName, metadata, success) {
1470
+ const parts = [];
1471
+ parts.push(`Tool: ${toolName}`);
1472
+ if (metadata.filePath) {
1473
+ parts.push(`File: ${metadata.filePath}`);
1474
+ }
1475
+ if (metadata.command) {
1476
+ parts.push(`Command: ${metadata.command}`);
1477
+ }
1478
+ if (metadata.pattern) {
1479
+ parts.push(`Pattern: ${metadata.pattern}`);
1480
+ }
1481
+ if (metadata.url) {
1482
+ try {
1483
+ const url = new URL(metadata.url);
1484
+ parts.push(`URL: ${url.hostname}`);
1485
+ } catch {
1486
+ }
1487
+ }
1488
+ parts.push(`Result: ${success ? "Success" : "Failed"}`);
1489
+ return parts.join("\n");
1490
+ }
1491
+
1492
+ // src/core/working-set-store.ts
1493
+ import { randomUUID as randomUUID2 } from "crypto";
1494
+ var WorkingSetStore = class {
1495
+ constructor(eventStore, config) {
1496
+ this.eventStore = eventStore;
1497
+ this.config = config;
1498
+ }
1499
+ get db() {
1500
+ return this.eventStore.getDatabase();
1501
+ }
1502
+ /**
1503
+ * Add an event to the working set
1504
+ */
1505
+ async add(eventId, relevanceScore = 1, topics) {
1506
+ const expiresAt = new Date(
1507
+ Date.now() + this.config.workingSet.timeWindowHours * 60 * 60 * 1e3
1508
+ );
1509
+ await this.db.run(
1510
+ `INSERT OR REPLACE INTO working_set (id, event_id, added_at, relevance_score, topics, expires_at)
1511
+ VALUES (?, ?, CURRENT_TIMESTAMP, ?, ?, ?)`,
1512
+ [
1513
+ randomUUID2(),
1514
+ eventId,
1515
+ relevanceScore,
1516
+ JSON.stringify(topics || []),
1517
+ expiresAt.toISOString()
1518
+ ]
1519
+ );
1520
+ await this.enforceLimit();
1521
+ }
1522
+ /**
1523
+ * Get the current working set
1524
+ */
1525
+ async get() {
1526
+ await this.cleanup();
1527
+ const rows = await this.db.all(
1528
+ `SELECT ws.*, e.*
1529
+ FROM working_set ws
1530
+ JOIN events e ON ws.event_id = e.id
1531
+ ORDER BY ws.relevance_score DESC, ws.added_at DESC
1532
+ LIMIT ?`,
1533
+ [this.config.workingSet.maxEvents]
1534
+ );
1535
+ const events = rows.map((row) => ({
1536
+ id: row.id,
1537
+ eventType: row.event_type,
1538
+ sessionId: row.session_id,
1539
+ timestamp: new Date(row.timestamp),
1540
+ content: row.content,
1541
+ canonicalKey: row.canonical_key,
1542
+ dedupeKey: row.dedupe_key,
1543
+ metadata: row.metadata ? JSON.parse(row.metadata) : void 0
1544
+ }));
1545
+ return {
1546
+ recentEvents: events,
1547
+ lastActivity: events.length > 0 ? events[0].timestamp : /* @__PURE__ */ new Date(),
1548
+ continuityScore: await this.calculateContinuityScore()
1549
+ };
1550
+ }
1551
+ /**
1552
+ * Get working set items (metadata only)
1553
+ */
1554
+ async getItems() {
1555
+ const rows = await this.db.all(
1556
+ `SELECT * FROM working_set ORDER BY relevance_score DESC, added_at DESC`
1557
+ );
1558
+ return rows.map((row) => ({
1559
+ id: row.id,
1560
+ eventId: row.event_id,
1561
+ addedAt: new Date(row.added_at),
1562
+ relevanceScore: row.relevance_score,
1563
+ topics: row.topics ? JSON.parse(row.topics) : void 0,
1564
+ expiresAt: new Date(row.expires_at)
1565
+ }));
1566
+ }
1567
+ /**
1568
+ * Update relevance score for an event
1569
+ */
1570
+ async updateRelevance(eventId, score) {
1571
+ await this.db.run(
1572
+ `UPDATE working_set SET relevance_score = ? WHERE event_id = ?`,
1573
+ [score, eventId]
1574
+ );
1575
+ }
1576
+ /**
1577
+ * Prune specific events from working set (after consolidation)
1578
+ */
1579
+ async prune(eventIds) {
1580
+ if (eventIds.length === 0)
1581
+ return;
1582
+ const placeholders = eventIds.map(() => "?").join(",");
1583
+ await this.db.run(
1584
+ `DELETE FROM working_set WHERE event_id IN (${placeholders})`,
1585
+ eventIds
1586
+ );
1587
+ }
1588
+ /**
1589
+ * Get the count of items in working set
1590
+ */
1591
+ async count() {
1592
+ const result = await this.db.all(
1593
+ `SELECT COUNT(*) as count FROM working_set`
1594
+ );
1595
+ return result[0]?.count || 0;
1596
+ }
1597
+ /**
1598
+ * Clear the entire working set
1599
+ */
1600
+ async clear() {
1601
+ await this.db.run(`DELETE FROM working_set`);
1602
+ }
1603
+ /**
1604
+ * Check if an event is in the working set
1605
+ */
1606
+ async contains(eventId) {
1607
+ const result = await this.db.all(
1608
+ `SELECT COUNT(*) as count FROM working_set WHERE event_id = ?`,
1609
+ [eventId]
1610
+ );
1611
+ return (result[0]?.count || 0) > 0;
1612
+ }
1613
+ /**
1614
+ * Refresh expiration for an event (rehears al - keep relevant items longer)
1615
+ */
1616
+ async refresh(eventId) {
1617
+ const newExpiresAt = new Date(
1618
+ Date.now() + this.config.workingSet.timeWindowHours * 60 * 60 * 1e3
1619
+ );
1620
+ await this.db.run(
1621
+ `UPDATE working_set SET expires_at = ? WHERE event_id = ?`,
1622
+ [newExpiresAt.toISOString(), eventId]
1623
+ );
1624
+ }
1625
+ /**
1626
+ * Clean up expired items
1627
+ */
1628
+ async cleanup() {
1629
+ await this.db.run(
1630
+ `DELETE FROM working_set WHERE expires_at < datetime('now')`
1631
+ );
1632
+ }
1633
+ /**
1634
+ * Enforce the maximum size limit
1635
+ * Removes lowest relevance items when over limit
1636
+ */
1637
+ async enforceLimit() {
1638
+ const maxEvents = this.config.workingSet.maxEvents;
1639
+ const keepIds = await this.db.all(
1640
+ `SELECT id FROM working_set
1641
+ ORDER BY relevance_score DESC, added_at DESC
1642
+ LIMIT ?`,
1643
+ [maxEvents]
1644
+ );
1645
+ if (keepIds.length === 0)
1646
+ return;
1647
+ const keepIdList = keepIds.map((r) => r.id);
1648
+ const placeholders = keepIdList.map(() => "?").join(",");
1649
+ await this.db.run(
1650
+ `DELETE FROM working_set WHERE id NOT IN (${placeholders})`,
1651
+ keepIdList
1652
+ );
1653
+ }
1654
+ /**
1655
+ * Calculate continuity score based on recent context transitions
1656
+ */
1657
+ async calculateContinuityScore() {
1658
+ const result = await this.db.all(
1659
+ `SELECT AVG(continuity_score) as avg_score
1660
+ FROM continuity_log
1661
+ WHERE created_at > datetime('now', '-1 hour')`
1662
+ );
1663
+ return result[0]?.avg_score ?? 0.5;
1664
+ }
1665
+ /**
1666
+ * Get topics from current working set for context matching
1667
+ */
1668
+ async getActiveTopics() {
1669
+ const rows = await this.db.all(
1670
+ `SELECT topics FROM working_set WHERE topics IS NOT NULL`
1671
+ );
1672
+ const allTopics = /* @__PURE__ */ new Set();
1673
+ for (const row of rows) {
1674
+ const topics = JSON.parse(row.topics);
1675
+ topics.forEach((t) => allTopics.add(t));
1676
+ }
1677
+ return Array.from(allTopics);
1678
+ }
1679
+ };
1680
+ function createWorkingSetStore(eventStore, config) {
1681
+ return new WorkingSetStore(eventStore, config);
1682
+ }
1683
+
1684
+ // src/core/consolidated-store.ts
1685
+ import { randomUUID as randomUUID3 } from "crypto";
1686
+ var ConsolidatedStore = class {
1687
+ constructor(eventStore) {
1688
+ this.eventStore = eventStore;
1689
+ }
1690
+ get db() {
1691
+ return this.eventStore.getDatabase();
1692
+ }
1693
+ /**
1694
+ * Create a new consolidated memory
1695
+ */
1696
+ async create(input) {
1697
+ const memoryId = randomUUID3();
1698
+ await this.db.run(
1699
+ `INSERT INTO consolidated_memories
1700
+ (memory_id, summary, topics, source_events, confidence, created_at)
1701
+ VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
1702
+ [
1703
+ memoryId,
1704
+ input.summary,
1705
+ JSON.stringify(input.topics),
1706
+ JSON.stringify(input.sourceEvents),
1707
+ input.confidence
1708
+ ]
1709
+ );
1710
+ return memoryId;
1711
+ }
1712
+ /**
1713
+ * Get a consolidated memory by ID
1714
+ */
1715
+ async get(memoryId) {
1716
+ const rows = await this.db.all(
1717
+ `SELECT * FROM consolidated_memories WHERE memory_id = ?`,
1718
+ [memoryId]
1719
+ );
1720
+ if (rows.length === 0)
1721
+ return null;
1722
+ return this.rowToMemory(rows[0]);
1723
+ }
1724
+ /**
1725
+ * Search consolidated memories by query (simple text search)
1726
+ */
1727
+ async search(query, options) {
1728
+ const topK = options?.topK || 5;
1729
+ const rows = await this.db.all(
1730
+ `SELECT * FROM consolidated_memories
1731
+ WHERE summary LIKE ?
1732
+ ORDER BY confidence DESC
1733
+ LIMIT ?`,
1734
+ [`%${query}%`, topK]
1735
+ );
1736
+ return rows.map(this.rowToMemory);
1737
+ }
1738
+ /**
1739
+ * Search by topics
1740
+ */
1741
+ async searchByTopics(topics, options) {
1742
+ const topK = options?.topK || 5;
1743
+ const topicConditions = topics.map(() => `topics LIKE ?`).join(" OR ");
1744
+ const topicParams = topics.map((t) => `%"${t}"%`);
1745
+ const rows = await this.db.all(
1746
+ `SELECT * FROM consolidated_memories
1747
+ WHERE ${topicConditions}
1748
+ ORDER BY confidence DESC
1749
+ LIMIT ?`,
1750
+ [...topicParams, topK]
1751
+ );
1752
+ return rows.map(this.rowToMemory);
1753
+ }
1754
+ /**
1755
+ * Get all consolidated memories ordered by confidence
1756
+ */
1757
+ async getAll(options) {
1758
+ const limit = options?.limit || 100;
1759
+ const rows = await this.db.all(
1760
+ `SELECT * FROM consolidated_memories
1761
+ ORDER BY confidence DESC, created_at DESC
1762
+ LIMIT ?`,
1763
+ [limit]
1764
+ );
1765
+ return rows.map(this.rowToMemory);
1766
+ }
1767
+ /**
1768
+ * Get recently created memories
1769
+ */
1770
+ async getRecent(options) {
1771
+ const limit = options?.limit || 10;
1772
+ const hours = options?.hours || 24;
1773
+ const rows = await this.db.all(
1774
+ `SELECT * FROM consolidated_memories
1775
+ WHERE created_at > datetime('now', '-${hours} hours')
1776
+ ORDER BY created_at DESC
1777
+ LIMIT ?`,
1778
+ [limit]
1779
+ );
1780
+ return rows.map(this.rowToMemory);
1781
+ }
1782
+ /**
1783
+ * Mark a memory as accessed (tracks usage for importance scoring)
1784
+ */
1785
+ async markAccessed(memoryId) {
1786
+ await this.db.run(
1787
+ `UPDATE consolidated_memories
1788
+ SET accessed_at = CURRENT_TIMESTAMP,
1789
+ access_count = access_count + 1
1790
+ WHERE memory_id = ?`,
1791
+ [memoryId]
1792
+ );
1793
+ }
1794
+ /**
1795
+ * Update confidence score for a memory
1796
+ */
1797
+ async updateConfidence(memoryId, confidence) {
1798
+ await this.db.run(
1799
+ `UPDATE consolidated_memories
1800
+ SET confidence = ?
1801
+ WHERE memory_id = ?`,
1802
+ [confidence, memoryId]
1803
+ );
1804
+ }
1805
+ /**
1806
+ * Delete a consolidated memory
1807
+ */
1808
+ async delete(memoryId) {
1809
+ await this.db.run(
1810
+ `DELETE FROM consolidated_memories WHERE memory_id = ?`,
1811
+ [memoryId]
1812
+ );
1813
+ }
1814
+ /**
1815
+ * Get count of consolidated memories
1816
+ */
1817
+ async count() {
1818
+ const result = await this.db.all(
1819
+ `SELECT COUNT(*) as count FROM consolidated_memories`
1820
+ );
1821
+ return result[0]?.count || 0;
1822
+ }
1823
+ /**
1824
+ * Get most accessed memories (for importance scoring)
1825
+ */
1826
+ async getMostAccessed(limit = 10) {
1827
+ const rows = await this.db.all(
1828
+ `SELECT * FROM consolidated_memories
1829
+ WHERE access_count > 0
1830
+ ORDER BY access_count DESC
1831
+ LIMIT ?`,
1832
+ [limit]
1833
+ );
1834
+ return rows.map(this.rowToMemory);
1835
+ }
1836
+ /**
1837
+ * Get statistics about consolidated memories
1838
+ */
1839
+ async getStats() {
1840
+ const total = await this.count();
1841
+ const avgResult = await this.db.all(
1842
+ `SELECT AVG(confidence) as avg FROM consolidated_memories`
1843
+ );
1844
+ const averageConfidence = avgResult[0]?.avg || 0;
1845
+ const recentResult = await this.db.all(
1846
+ `SELECT COUNT(*) as count FROM consolidated_memories
1847
+ WHERE created_at > datetime('now', '-24 hours')`
1848
+ );
1849
+ const recentCount = recentResult[0]?.count || 0;
1850
+ const allMemories = await this.getAll({ limit: 1e3 });
1851
+ const topicCounts = {};
1852
+ for (const memory of allMemories) {
1853
+ for (const topic of memory.topics) {
1854
+ topicCounts[topic] = (topicCounts[topic] || 0) + 1;
1855
+ }
1856
+ }
1857
+ return {
1858
+ total,
1859
+ averageConfidence,
1860
+ topicCounts,
1861
+ recentCount
1862
+ };
1863
+ }
1864
+ /**
1865
+ * Check if source events are already consolidated
1866
+ */
1867
+ async isAlreadyConsolidated(eventIds) {
1868
+ for (const eventId of eventIds) {
1869
+ const result = await this.db.all(
1870
+ `SELECT COUNT(*) as count FROM consolidated_memories
1871
+ WHERE source_events LIKE ?`,
1872
+ [`%"${eventId}"%`]
1873
+ );
1874
+ if ((result[0]?.count || 0) > 0)
1875
+ return true;
1876
+ }
1877
+ return false;
1878
+ }
1879
+ /**
1880
+ * Get the last consolidation time
1881
+ */
1882
+ async getLastConsolidationTime() {
1883
+ const result = await this.db.all(
1884
+ `SELECT created_at FROM consolidated_memories
1885
+ ORDER BY created_at DESC
1886
+ LIMIT 1`
1887
+ );
1888
+ if (result.length === 0)
1889
+ return null;
1890
+ return new Date(result[0].created_at);
1891
+ }
1892
+ /**
1893
+ * Convert database row to ConsolidatedMemory
1894
+ */
1895
+ rowToMemory(row) {
1896
+ return {
1897
+ memoryId: row.memory_id,
1898
+ summary: row.summary,
1899
+ topics: JSON.parse(row.topics || "[]"),
1900
+ sourceEvents: JSON.parse(row.source_events || "[]"),
1901
+ confidence: row.confidence,
1902
+ createdAt: new Date(row.created_at),
1903
+ accessedAt: row.accessed_at ? new Date(row.accessed_at) : void 0,
1904
+ accessCount: row.access_count || 0
1905
+ };
1906
+ }
1907
+ };
1908
+ function createConsolidatedStore(eventStore) {
1909
+ return new ConsolidatedStore(eventStore);
1910
+ }
1911
+
1912
+ // src/core/consolidation-worker.ts
1913
+ var ConsolidationWorker = class {
1914
+ constructor(workingSetStore, consolidatedStore, config) {
1915
+ this.workingSetStore = workingSetStore;
1916
+ this.consolidatedStore = consolidatedStore;
1917
+ this.config = config;
1918
+ }
1919
+ running = false;
1920
+ timeout = null;
1921
+ lastActivity = /* @__PURE__ */ new Date();
1922
+ /**
1923
+ * Start the consolidation worker
1924
+ */
1925
+ start() {
1926
+ if (this.running)
1927
+ return;
1928
+ this.running = true;
1929
+ this.scheduleNext();
1930
+ }
1931
+ /**
1932
+ * Stop the consolidation worker
1933
+ */
1934
+ stop() {
1935
+ this.running = false;
1936
+ if (this.timeout) {
1937
+ clearTimeout(this.timeout);
1938
+ this.timeout = null;
1939
+ }
1940
+ }
1941
+ /**
1942
+ * Record activity (resets idle timer)
1943
+ */
1944
+ recordActivity() {
1945
+ this.lastActivity = /* @__PURE__ */ new Date();
1946
+ }
1947
+ /**
1948
+ * Check if currently running
1949
+ */
1950
+ isRunning() {
1951
+ return this.running;
1952
+ }
1953
+ /**
1954
+ * Force a consolidation run (manual trigger)
1955
+ */
1956
+ async forceRun() {
1957
+ return await this.consolidate();
1958
+ }
1959
+ /**
1960
+ * Schedule the next consolidation check
1961
+ */
1962
+ scheduleNext() {
1963
+ if (!this.running)
1964
+ return;
1965
+ this.timeout = setTimeout(
1966
+ () => this.run(),
1967
+ this.config.consolidation.triggerIntervalMs
1968
+ );
1969
+ }
1970
+ /**
1971
+ * Run consolidation check
1972
+ */
1973
+ async run() {
1974
+ if (!this.running)
1975
+ return;
1976
+ try {
1977
+ await this.checkAndConsolidate();
1978
+ } catch (error) {
1979
+ console.error("Consolidation error:", error);
1980
+ }
1981
+ this.scheduleNext();
1982
+ }
1983
+ /**
1984
+ * Check conditions and consolidate if needed
1985
+ */
1986
+ async checkAndConsolidate() {
1987
+ const workingSet = await this.workingSetStore.get();
1988
+ if (!this.shouldConsolidate(workingSet)) {
1989
+ return;
1990
+ }
1991
+ await this.consolidate();
1992
+ }
1993
+ /**
1994
+ * Perform consolidation
1995
+ */
1996
+ async consolidate() {
1997
+ const workingSet = await this.workingSetStore.get();
1998
+ if (workingSet.recentEvents.length < 3) {
1999
+ return 0;
2000
+ }
2001
+ const groups = this.groupByTopic(workingSet.recentEvents);
2002
+ let consolidatedCount = 0;
2003
+ for (const group of groups) {
2004
+ if (group.events.length < 3)
2005
+ continue;
2006
+ const eventIds = group.events.map((e) => e.id);
2007
+ const alreadyConsolidated = await this.consolidatedStore.isAlreadyConsolidated(eventIds);
2008
+ if (alreadyConsolidated)
2009
+ continue;
2010
+ const summary = await this.summarize(group);
2011
+ await this.consolidatedStore.create({
2012
+ summary,
2013
+ topics: group.topics,
2014
+ sourceEvents: eventIds,
2015
+ confidence: this.calculateConfidence(group)
2016
+ });
2017
+ consolidatedCount++;
2018
+ }
2019
+ if (consolidatedCount > 0) {
2020
+ const consolidatedEventIds = groups.filter((g) => g.events.length >= 3).flatMap((g) => g.events.map((e) => e.id));
2021
+ const oldEventIds = consolidatedEventIds.filter((id) => {
2022
+ const event = workingSet.recentEvents.find((e) => e.id === id);
2023
+ if (!event)
2024
+ return false;
2025
+ const ageHours = (Date.now() - event.timestamp.getTime()) / (1e3 * 60 * 60);
2026
+ return ageHours > this.config.workingSet.timeWindowHours / 2;
2027
+ });
2028
+ if (oldEventIds.length > 0) {
2029
+ await this.workingSetStore.prune(oldEventIds);
2030
+ }
2031
+ }
2032
+ return consolidatedCount;
2033
+ }
2034
+ /**
2035
+ * Check if consolidation should run
2036
+ */
2037
+ shouldConsolidate(workingSet) {
2038
+ if (workingSet.recentEvents.length >= this.config.consolidation.triggerEventCount) {
2039
+ return true;
2040
+ }
2041
+ const idleTime = Date.now() - this.lastActivity.getTime();
2042
+ if (idleTime >= this.config.consolidation.triggerIdleMs) {
2043
+ return true;
2044
+ }
2045
+ return false;
2046
+ }
2047
+ /**
2048
+ * Group events by topic using simple keyword extraction
2049
+ */
2050
+ groupByTopic(events) {
2051
+ const groups = /* @__PURE__ */ new Map();
2052
+ for (const event of events) {
2053
+ const topics = this.extractTopics(event.content);
2054
+ for (const topic of topics) {
2055
+ if (!groups.has(topic)) {
2056
+ groups.set(topic, { topics: [topic], events: [] });
2057
+ }
2058
+ const group = groups.get(topic);
2059
+ if (!group.events.find((e) => e.id === event.id)) {
2060
+ group.events.push(event);
2061
+ }
2062
+ }
2063
+ }
2064
+ const mergedGroups = this.mergeOverlappingGroups(Array.from(groups.values()));
2065
+ return mergedGroups;
2066
+ }
2067
+ /**
2068
+ * Extract topics from content using simple keyword extraction
2069
+ */
2070
+ extractTopics(content) {
2071
+ const topics = [];
2072
+ const codePatterns = [
2073
+ /\b(function|class|interface|type|const|let|var)\s+(\w+)/gi,
2074
+ /\b(import|export)\s+.*?from\s+['"]([^'"]+)['"]/gi,
2075
+ /\bfile[:\s]+([^\s,]+)/gi
2076
+ ];
2077
+ for (const pattern of codePatterns) {
2078
+ let match;
2079
+ while ((match = pattern.exec(content)) !== null) {
2080
+ const keyword = match[2] || match[1];
2081
+ if (keyword && keyword.length > 2) {
2082
+ topics.push(keyword.toLowerCase());
2083
+ }
2084
+ }
2085
+ }
2086
+ const commonTerms = [
2087
+ "bug",
2088
+ "fix",
2089
+ "error",
2090
+ "issue",
2091
+ "feature",
2092
+ "test",
2093
+ "refactor",
2094
+ "implement",
2095
+ "add",
2096
+ "remove",
2097
+ "update",
2098
+ "change",
2099
+ "modify",
2100
+ "create",
2101
+ "delete"
2102
+ ];
2103
+ const contentLower = content.toLowerCase();
2104
+ for (const term of commonTerms) {
2105
+ if (contentLower.includes(term)) {
2106
+ topics.push(term);
2107
+ }
2108
+ }
2109
+ return [...new Set(topics)].slice(0, 5);
2110
+ }
2111
+ /**
2112
+ * Merge groups that have significant event overlap
2113
+ */
2114
+ mergeOverlappingGroups(groups) {
2115
+ const merged = [];
2116
+ for (const group of groups) {
2117
+ let foundMerge = false;
2118
+ for (const existing of merged) {
2119
+ const overlap = group.events.filter(
2120
+ (e) => existing.events.some((ex) => ex.id === e.id)
2121
+ );
2122
+ if (overlap.length > group.events.length / 2) {
2123
+ existing.topics = [.../* @__PURE__ */ new Set([...existing.topics, ...group.topics])];
2124
+ for (const event of group.events) {
2125
+ if (!existing.events.find((e) => e.id === event.id)) {
2126
+ existing.events.push(event);
2127
+ }
2128
+ }
2129
+ foundMerge = true;
2130
+ break;
2131
+ }
2132
+ }
2133
+ if (!foundMerge) {
2134
+ merged.push(group);
2135
+ }
2136
+ }
2137
+ return merged;
2138
+ }
2139
+ /**
2140
+ * Generate summary for a group of events
2141
+ * Rule-based extraction (no LLM by default)
2142
+ */
2143
+ async summarize(group) {
2144
+ if (this.config.consolidation.useLLMSummarization) {
2145
+ return this.ruleBasedSummary(group);
2146
+ }
2147
+ return this.ruleBasedSummary(group);
2148
+ }
2149
+ /**
2150
+ * Rule-based summary generation
2151
+ */
2152
+ ruleBasedSummary(group) {
2153
+ const keyPoints = [];
2154
+ for (const event of group.events.slice(0, 10)) {
2155
+ const keyPoint = this.extractKeyPoint(event.content);
2156
+ if (keyPoint) {
2157
+ keyPoints.push(keyPoint);
2158
+ }
2159
+ }
2160
+ const topicsStr = group.topics.slice(0, 3).join(", ");
2161
+ const summary = [
2162
+ `Topics: ${topicsStr}`,
2163
+ "",
2164
+ "Key points:",
2165
+ ...keyPoints.map((kp) => `- ${kp}`)
2166
+ ].join("\n");
2167
+ return summary;
2168
+ }
2169
+ /**
2170
+ * Extract key point from content
2171
+ */
2172
+ extractKeyPoint(content) {
2173
+ const sentences = content.split(/[.!?\n]+/).filter((s) => s.trim().length > 10);
2174
+ if (sentences.length === 0)
2175
+ return null;
2176
+ const firstSentence = sentences[0].trim();
2177
+ if (firstSentence.length > 100) {
2178
+ return firstSentence.slice(0, 100) + "...";
2179
+ }
2180
+ return firstSentence;
2181
+ }
2182
+ /**
2183
+ * Calculate confidence score for a group
2184
+ */
2185
+ calculateConfidence(group) {
2186
+ const eventScore = Math.min(group.events.length / 10, 1);
2187
+ const timeScore = this.calculateTimeProximity(group.events);
2188
+ const topicScore = Math.min(3 / group.topics.length, 1);
2189
+ return eventScore * 0.4 + timeScore * 0.4 + topicScore * 0.2;
2190
+ }
2191
+ /**
2192
+ * Calculate time proximity score
2193
+ */
2194
+ calculateTimeProximity(events) {
2195
+ if (events.length < 2)
2196
+ return 1;
2197
+ const timestamps = events.map((e) => e.timestamp.getTime()).sort((a, b) => a - b);
2198
+ const timeSpan = timestamps[timestamps.length - 1] - timestamps[0];
2199
+ const avgGap = timeSpan / (events.length - 1);
2200
+ const hourInMs = 60 * 60 * 1e3;
2201
+ return Math.max(0, 1 - avgGap / (24 * hourInMs));
2202
+ }
2203
+ };
2204
+ function createConsolidationWorker(workingSetStore, consolidatedStore, config) {
2205
+ return new ConsolidationWorker(workingSetStore, consolidatedStore, config);
2206
+ }
2207
+
2208
+ // src/core/continuity-manager.ts
2209
+ import { randomUUID as randomUUID4 } from "crypto";
2210
+ var ContinuityManager = class {
2211
+ constructor(eventStore, config) {
2212
+ this.eventStore = eventStore;
2213
+ this.config = config;
2214
+ }
2215
+ lastContext = null;
2216
+ get db() {
2217
+ return this.eventStore.getDatabase();
2218
+ }
2219
+ /**
2220
+ * Calculate continuity score between current and previous context
2221
+ */
2222
+ async calculateScore(currentContext, previousContext) {
2223
+ const prev = previousContext || this.lastContext;
2224
+ if (!prev) {
2225
+ this.lastContext = currentContext;
2226
+ return { score: 0.5, transitionType: "break" };
2227
+ }
2228
+ let score = 0;
2229
+ const topicOverlap = this.calculateOverlap(
2230
+ currentContext.topics,
2231
+ prev.topics
2232
+ );
2233
+ score += topicOverlap * 0.3;
2234
+ const fileOverlap = this.calculateOverlap(
2235
+ currentContext.files,
2236
+ prev.files
2237
+ );
2238
+ score += fileOverlap * 0.2;
2239
+ const timeDiff = currentContext.timestamp - prev.timestamp;
2240
+ const decayHours = this.config.continuity.topicDecayHours;
2241
+ const timeScore = Math.exp(-timeDiff / (decayHours * 36e5));
2242
+ score += timeScore * 0.3;
2243
+ const entityOverlap = this.calculateOverlap(
2244
+ currentContext.entities,
2245
+ prev.entities
2246
+ );
2247
+ score += entityOverlap * 0.2;
2248
+ const transitionType = this.determineTransitionType(score);
2249
+ await this.logTransition(currentContext, prev, score, transitionType);
2250
+ this.lastContext = currentContext;
2251
+ return { score, transitionType };
2252
+ }
2253
+ /**
2254
+ * Create a context snapshot from current state
2255
+ */
2256
+ createSnapshot(id, content, metadata) {
2257
+ return {
2258
+ id,
2259
+ timestamp: Date.now(),
2260
+ topics: this.extractTopics(content),
2261
+ files: metadata?.files || this.extractFiles(content),
2262
+ entities: metadata?.entities || this.extractEntities(content)
2263
+ };
2264
+ }
2265
+ /**
2266
+ * Get recent continuity logs
2267
+ */
2268
+ async getRecentLogs(limit = 10) {
2269
+ const rows = await this.db.all(
2270
+ `SELECT * FROM continuity_log
2271
+ ORDER BY created_at DESC
2272
+ LIMIT ?`,
2273
+ [limit]
2274
+ );
2275
+ return rows.map((row) => ({
2276
+ logId: row.log_id,
2277
+ fromContextId: row.from_context_id,
2278
+ toContextId: row.to_context_id,
2279
+ continuityScore: row.continuity_score,
2280
+ transitionType: row.transition_type,
2281
+ createdAt: new Date(row.created_at)
2282
+ }));
2283
+ }
2284
+ /**
2285
+ * Get average continuity score over time period
2286
+ */
2287
+ async getAverageScore(hours = 1) {
2288
+ const result = await this.db.all(
2289
+ `SELECT AVG(continuity_score) as avg_score
2290
+ FROM continuity_log
2291
+ WHERE created_at > datetime('now', '-${hours} hours')`
2292
+ );
2293
+ return result[0]?.avg_score ?? 0.5;
2294
+ }
2295
+ /**
2296
+ * Get transition type distribution
2297
+ */
2298
+ async getTransitionStats(hours = 24) {
2299
+ const rows = await this.db.all(
2300
+ `SELECT transition_type, COUNT(*) as count
2301
+ FROM continuity_log
2302
+ WHERE created_at > datetime('now', '-${hours} hours')
2303
+ GROUP BY transition_type`
2304
+ );
2305
+ const stats = {
2306
+ seamless: 0,
2307
+ topic_shift: 0,
2308
+ break: 0
2309
+ };
2310
+ for (const row of rows) {
2311
+ stats[row.transition_type] = row.count;
2312
+ }
2313
+ return stats;
2314
+ }
2315
+ /**
2316
+ * Clear old continuity logs
2317
+ */
2318
+ async cleanup(olderThanDays = 7) {
2319
+ const result = await this.db.all(
2320
+ `DELETE FROM continuity_log
2321
+ WHERE created_at < datetime('now', '-${olderThanDays} days')
2322
+ RETURNING COUNT(*) as changes`
2323
+ );
2324
+ return result[0]?.changes || 0;
2325
+ }
2326
+ /**
2327
+ * Calculate overlap between two arrays
2328
+ */
2329
+ calculateOverlap(a, b) {
2330
+ if (a.length === 0 || b.length === 0)
2331
+ return 0;
2332
+ const setA = new Set(a.map((s) => s.toLowerCase()));
2333
+ const setB = new Set(b.map((s) => s.toLowerCase()));
2334
+ const intersection = [...setA].filter((x) => setB.has(x));
2335
+ const union = /* @__PURE__ */ new Set([...setA, ...setB]);
2336
+ return intersection.length / union.size;
2337
+ }
2338
+ /**
2339
+ * Determine transition type based on score
2340
+ */
2341
+ determineTransitionType(score) {
2342
+ if (score >= this.config.continuity.minScoreForSeamless) {
2343
+ return "seamless";
2344
+ } else if (score >= 0.4) {
2345
+ return "topic_shift";
2346
+ } else {
2347
+ return "break";
2348
+ }
2349
+ }
2350
+ /**
2351
+ * Log a context transition
2352
+ */
2353
+ async logTransition(current, previous, score, type) {
2354
+ await this.db.run(
2355
+ `INSERT INTO continuity_log
2356
+ (log_id, from_context_id, to_context_id, continuity_score, transition_type, created_at)
2357
+ VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
2358
+ [randomUUID4(), previous.id, current.id, score, type]
2359
+ );
2360
+ }
2361
+ /**
2362
+ * Extract topics from content
2363
+ */
2364
+ extractTopics(content) {
2365
+ const topics = [];
2366
+ const contentLower = content.toLowerCase();
2367
+ const langPatterns = [
2368
+ { pattern: /typescript|\.ts\b/i, topic: "typescript" },
2369
+ { pattern: /javascript|\.js\b/i, topic: "javascript" },
2370
+ { pattern: /python|\.py\b/i, topic: "python" },
2371
+ { pattern: /rust|\.rs\b/i, topic: "rust" },
2372
+ { pattern: /go\b|golang/i, topic: "go" }
2373
+ ];
2374
+ for (const { pattern, topic } of langPatterns) {
2375
+ if (pattern.test(content)) {
2376
+ topics.push(topic);
2377
+ }
2378
+ }
2379
+ const devTopics = [
2380
+ "api",
2381
+ "database",
2382
+ "test",
2383
+ "bug",
2384
+ "feature",
2385
+ "refactor",
2386
+ "component",
2387
+ "function",
2388
+ "class",
2389
+ "module",
2390
+ "hook",
2391
+ "deploy",
2392
+ "build",
2393
+ "config",
2394
+ "docker",
2395
+ "git"
2396
+ ];
2397
+ for (const topic of devTopics) {
2398
+ if (contentLower.includes(topic)) {
2399
+ topics.push(topic);
2400
+ }
2401
+ }
2402
+ return [...new Set(topics)].slice(0, 10);
2403
+ }
2404
+ /**
2405
+ * Extract file paths from content
2406
+ */
2407
+ extractFiles(content) {
2408
+ const filePatterns = [
2409
+ /(?:^|\s)([a-zA-Z0-9_\-./]+\.[a-zA-Z0-9]+)(?:\s|$|:)/gm,
2410
+ /['"](\.?\/[^'"]+\.[a-zA-Z0-9]+)['"]/g,
2411
+ /file[:\s]+([^\s,]+)/gi
2412
+ ];
2413
+ const files = /* @__PURE__ */ new Set();
2414
+ for (const pattern of filePatterns) {
2415
+ let match;
2416
+ while ((match = pattern.exec(content)) !== null) {
2417
+ const file = match[1];
2418
+ if (file && file.length > 3 && file.length < 100) {
2419
+ if (!file.match(/^(https?:|mailto:|ftp:)/i)) {
2420
+ files.add(file);
2421
+ }
2422
+ }
2423
+ }
2424
+ }
2425
+ return Array.from(files).slice(0, 10);
2426
+ }
2427
+ /**
2428
+ * Extract entity names from content (functions, classes, variables)
2429
+ */
2430
+ extractEntities(content) {
2431
+ const entities = /* @__PURE__ */ new Set();
2432
+ const entityPatterns = [
2433
+ /\b(function|const|let|var|class|interface|type)\s+([a-zA-Z_][a-zA-Z0-9_]*)/g,
2434
+ /\b([A-Z][a-zA-Z0-9_]*(?:Component|Service|Store|Manager|Handler|Factory|Provider))\b/g,
2435
+ /\b(use[A-Z][a-zA-Z0-9_]*)\b/g
2436
+ // React hooks
2437
+ ];
2438
+ for (const pattern of entityPatterns) {
2439
+ let match;
2440
+ while ((match = pattern.exec(content)) !== null) {
2441
+ const entity = match[2] || match[1];
2442
+ if (entity && entity.length > 2) {
2443
+ entities.add(entity);
2444
+ }
2445
+ }
2446
+ }
2447
+ return Array.from(entities).slice(0, 20);
2448
+ }
2449
+ /**
2450
+ * Reset the last context (for testing or manual reset)
2451
+ */
2452
+ resetLastContext() {
2453
+ this.lastContext = null;
2454
+ }
2455
+ /**
2456
+ * Get the last context snapshot
2457
+ */
2458
+ getLastContext() {
2459
+ return this.lastContext;
2460
+ }
2461
+ };
2462
+ function createContinuityManager(eventStore, config) {
2463
+ return new ContinuityManager(eventStore, config);
2464
+ }
2465
+
2466
+ // src/services/memory-service.ts
2467
+ var MemoryService = class {
2468
+ eventStore;
2469
+ vectorStore;
2470
+ embedder;
2471
+ matcher;
2472
+ retriever;
2473
+ graduation;
2474
+ vectorWorker = null;
2475
+ initialized = false;
2476
+ // Endless Mode components
2477
+ workingSetStore = null;
2478
+ consolidatedStore = null;
2479
+ consolidationWorker = null;
2480
+ continuityManager = null;
2481
+ endlessMode = "session";
2482
+ constructor(config) {
2483
+ const storagePath = this.expandPath(config.storagePath);
2484
+ if (!fs.existsSync(storagePath)) {
2485
+ fs.mkdirSync(storagePath, { recursive: true });
2486
+ }
2487
+ this.eventStore = new EventStore(path.join(storagePath, "events.duckdb"));
2488
+ this.vectorStore = new VectorStore(path.join(storagePath, "vectors"));
2489
+ this.embedder = config.embeddingModel ? new Embedder(config.embeddingModel) : getDefaultEmbedder();
2490
+ this.matcher = getDefaultMatcher();
2491
+ this.retriever = createRetriever(
2492
+ this.eventStore,
2493
+ this.vectorStore,
2494
+ this.embedder,
2495
+ this.matcher
2496
+ );
2497
+ this.graduation = createGraduationPipeline(this.eventStore);
2498
+ }
2499
+ /**
2500
+ * Initialize all components
2501
+ */
2502
+ async initialize() {
2503
+ if (this.initialized)
2504
+ return;
2505
+ await this.eventStore.initialize();
2506
+ await this.vectorStore.initialize();
2507
+ await this.embedder.initialize();
2508
+ this.vectorWorker = createVectorWorker(
2509
+ this.eventStore,
2510
+ this.vectorStore,
2511
+ this.embedder
2512
+ );
2513
+ this.vectorWorker.start();
2514
+ const savedMode = await this.eventStore.getEndlessConfig("mode");
2515
+ if (savedMode === "endless") {
2516
+ this.endlessMode = "endless";
2517
+ await this.initializeEndlessMode();
2518
+ }
2519
+ this.initialized = true;
2520
+ }
2521
+ /**
2522
+ * Start a new session
2523
+ */
2524
+ async startSession(sessionId, projectPath) {
2525
+ await this.initialize();
2526
+ await this.eventStore.upsertSession({
2527
+ id: sessionId,
2528
+ startedAt: /* @__PURE__ */ new Date(),
2529
+ projectPath
2530
+ });
2531
+ }
2532
+ /**
2533
+ * End a session
2534
+ */
2535
+ async endSession(sessionId, summary) {
2536
+ await this.initialize();
2537
+ await this.eventStore.upsertSession({
2538
+ id: sessionId,
2539
+ endedAt: /* @__PURE__ */ new Date(),
2540
+ summary
2541
+ });
2542
+ }
2543
+ /**
2544
+ * Store a user prompt
2545
+ */
2546
+ async storeUserPrompt(sessionId, content, metadata) {
2547
+ await this.initialize();
2548
+ const result = await this.eventStore.append({
2549
+ eventType: "user_prompt",
2550
+ sessionId,
2551
+ timestamp: /* @__PURE__ */ new Date(),
2552
+ content,
2553
+ metadata
2554
+ });
2555
+ if (result.success && !result.isDuplicate) {
2556
+ await this.eventStore.enqueueForEmbedding(result.eventId, content);
2557
+ }
2558
+ return result;
2559
+ }
2560
+ /**
2561
+ * Store an agent response
2562
+ */
2563
+ async storeAgentResponse(sessionId, content, metadata) {
2564
+ await this.initialize();
2565
+ const result = await this.eventStore.append({
2566
+ eventType: "agent_response",
2567
+ sessionId,
2568
+ timestamp: /* @__PURE__ */ new Date(),
2569
+ content,
2570
+ metadata
2571
+ });
2572
+ if (result.success && !result.isDuplicate) {
2573
+ await this.eventStore.enqueueForEmbedding(result.eventId, content);
2574
+ }
2575
+ return result;
2576
+ }
2577
+ /**
2578
+ * Store a session summary
2579
+ */
2580
+ async storeSessionSummary(sessionId, summary) {
2581
+ await this.initialize();
2582
+ const result = await this.eventStore.append({
2583
+ eventType: "session_summary",
2584
+ sessionId,
2585
+ timestamp: /* @__PURE__ */ new Date(),
2586
+ content: summary
2587
+ });
2588
+ if (result.success && !result.isDuplicate) {
2589
+ await this.eventStore.enqueueForEmbedding(result.eventId, summary);
2590
+ }
2591
+ return result;
2592
+ }
2593
+ /**
2594
+ * Store a tool observation
2595
+ */
2596
+ async storeToolObservation(sessionId, payload) {
2597
+ await this.initialize();
2598
+ const content = JSON.stringify(payload);
2599
+ const result = await this.eventStore.append({
2600
+ eventType: "tool_observation",
2601
+ sessionId,
2602
+ timestamp: /* @__PURE__ */ new Date(),
2603
+ content,
2604
+ metadata: {
2605
+ toolName: payload.toolName,
2606
+ success: payload.success
2607
+ }
2608
+ });
2609
+ if (result.success && !result.isDuplicate) {
2610
+ const embeddingContent = createToolObservationEmbedding(
2611
+ payload.toolName,
2612
+ payload.metadata || {},
2613
+ payload.success
2614
+ );
2615
+ await this.eventStore.enqueueForEmbedding(result.eventId, embeddingContent);
2616
+ }
2617
+ return result;
2618
+ }
2619
+ /**
2620
+ * Retrieve relevant memories for a query
2621
+ */
2622
+ async retrieveMemories(query, options) {
2623
+ await this.initialize();
2624
+ if (this.vectorWorker) {
2625
+ await this.vectorWorker.processAll();
2626
+ }
2627
+ return this.retriever.retrieve(query, options);
2628
+ }
2629
+ /**
2630
+ * Get session history
2631
+ */
2632
+ async getSessionHistory(sessionId) {
2633
+ await this.initialize();
2634
+ return this.eventStore.getSessionEvents(sessionId);
2635
+ }
2636
+ /**
2637
+ * Get recent events
2638
+ */
2639
+ async getRecentEvents(limit = 100) {
2640
+ await this.initialize();
2641
+ return this.eventStore.getRecentEvents(limit);
2642
+ }
2643
+ /**
2644
+ * Get memory statistics
2645
+ */
2646
+ async getStats() {
2647
+ await this.initialize();
2648
+ const recentEvents = await this.eventStore.getRecentEvents(1e4);
2649
+ const vectorCount = await this.vectorStore.count();
2650
+ const levelStats = await this.graduation.getStats();
2651
+ return {
2652
+ totalEvents: recentEvents.length,
2653
+ vectorCount,
2654
+ levelStats
2655
+ };
2656
+ }
2657
+ /**
2658
+ * Process pending embeddings
2659
+ */
2660
+ async processPendingEmbeddings() {
2661
+ if (this.vectorWorker) {
2662
+ return this.vectorWorker.processAll();
2663
+ }
2664
+ return 0;
2665
+ }
2666
+ /**
2667
+ * Format retrieval results as context for Claude
2668
+ */
2669
+ formatAsContext(result) {
2670
+ if (!result.context) {
2671
+ return "";
2672
+ }
2673
+ const confidence = result.matchResult.confidence;
2674
+ let header = "";
2675
+ if (confidence === "high") {
2676
+ header = "\u{1F3AF} **High-confidence memory match found:**\n\n";
2677
+ } else if (confidence === "suggested") {
2678
+ header = "\u{1F4A1} **Suggested memories (may be relevant):**\n\n";
2679
+ }
2680
+ return header + result.context;
2681
+ }
2682
+ // ============================================================
2683
+ // Endless Mode Methods
2684
+ // ============================================================
2685
+ /**
2686
+ * Get the default endless mode config
2687
+ */
2688
+ getDefaultEndlessConfig() {
2689
+ return {
2690
+ enabled: true,
2691
+ workingSet: {
2692
+ maxEvents: 100,
2693
+ timeWindowHours: 24,
2694
+ minRelevanceScore: 0.5
2695
+ },
2696
+ consolidation: {
2697
+ triggerIntervalMs: 36e5,
2698
+ // 1 hour
2699
+ triggerEventCount: 100,
2700
+ triggerIdleMs: 18e5,
2701
+ // 30 minutes
2702
+ useLLMSummarization: false
2703
+ },
2704
+ continuity: {
2705
+ minScoreForSeamless: 0.7,
2706
+ topicDecayHours: 48
2707
+ }
2708
+ };
2709
+ }
2710
+ /**
2711
+ * Initialize Endless Mode components
2712
+ */
2713
+ async initializeEndlessMode() {
2714
+ const config = await this.getEndlessConfig();
2715
+ this.workingSetStore = createWorkingSetStore(this.eventStore, config);
2716
+ this.consolidatedStore = createConsolidatedStore(this.eventStore);
2717
+ this.consolidationWorker = createConsolidationWorker(
2718
+ this.workingSetStore,
2719
+ this.consolidatedStore,
2720
+ config
2721
+ );
2722
+ this.continuityManager = createContinuityManager(this.eventStore, config);
2723
+ this.consolidationWorker.start();
2724
+ }
2725
+ /**
2726
+ * Get Endless Mode configuration
2727
+ */
2728
+ async getEndlessConfig() {
2729
+ const savedConfig = await this.eventStore.getEndlessConfig("config");
2730
+ return savedConfig || this.getDefaultEndlessConfig();
2731
+ }
2732
+ /**
2733
+ * Set Endless Mode configuration
2734
+ */
2735
+ async setEndlessConfig(config) {
2736
+ const current = await this.getEndlessConfig();
2737
+ const merged = { ...current, ...config };
2738
+ await this.eventStore.setEndlessConfig("config", merged);
2739
+ }
2740
+ /**
2741
+ * Set memory mode (session or endless)
2742
+ */
2743
+ async setMode(mode) {
2744
+ await this.initialize();
2745
+ if (mode === this.endlessMode)
2746
+ return;
2747
+ this.endlessMode = mode;
2748
+ await this.eventStore.setEndlessConfig("mode", mode);
2749
+ if (mode === "endless") {
2750
+ await this.initializeEndlessMode();
2751
+ } else {
2752
+ if (this.consolidationWorker) {
2753
+ this.consolidationWorker.stop();
2754
+ this.consolidationWorker = null;
2755
+ }
2756
+ this.workingSetStore = null;
2757
+ this.consolidatedStore = null;
2758
+ this.continuityManager = null;
2759
+ }
2760
+ }
2761
+ /**
2762
+ * Get current memory mode
2763
+ */
2764
+ getMode() {
2765
+ return this.endlessMode;
2766
+ }
2767
+ /**
2768
+ * Check if endless mode is active
2769
+ */
2770
+ isEndlessModeActive() {
2771
+ return this.endlessMode === "endless";
2772
+ }
2773
+ /**
2774
+ * Add event to Working Set (Endless Mode)
2775
+ */
2776
+ async addToWorkingSet(eventId, relevanceScore) {
2777
+ if (!this.workingSetStore)
2778
+ return;
2779
+ await this.workingSetStore.add(eventId, relevanceScore);
2780
+ }
2781
+ /**
2782
+ * Get the current Working Set
2783
+ */
2784
+ async getWorkingSet() {
2785
+ if (!this.workingSetStore)
2786
+ return null;
2787
+ return this.workingSetStore.get();
2788
+ }
2789
+ /**
2790
+ * Search consolidated memories
2791
+ */
2792
+ async searchConsolidated(query, options) {
2793
+ if (!this.consolidatedStore)
2794
+ return [];
2795
+ return this.consolidatedStore.search(query, options);
2796
+ }
2797
+ /**
2798
+ * Get all consolidated memories
2799
+ */
2800
+ async getConsolidatedMemories(limit) {
2801
+ if (!this.consolidatedStore)
2802
+ return [];
2803
+ return this.consolidatedStore.getAll({ limit });
2804
+ }
2805
+ /**
2806
+ * Calculate continuity score for current context
2807
+ */
2808
+ async calculateContinuity(content, metadata) {
2809
+ if (!this.continuityManager)
2810
+ return null;
2811
+ const snapshot = this.continuityManager.createSnapshot(
2812
+ crypto2.randomUUID(),
2813
+ content,
2814
+ metadata
2815
+ );
2816
+ return this.continuityManager.calculateScore(snapshot);
2817
+ }
2818
+ /**
2819
+ * Record activity (for consolidation idle trigger)
2820
+ */
2821
+ recordActivity() {
2822
+ if (this.consolidationWorker) {
2823
+ this.consolidationWorker.recordActivity();
2824
+ }
2825
+ }
2826
+ /**
2827
+ * Force a consolidation run
2828
+ */
2829
+ async forceConsolidation() {
2830
+ if (!this.consolidationWorker)
2831
+ return 0;
2832
+ return this.consolidationWorker.forceRun();
2833
+ }
2834
+ /**
2835
+ * Get Endless Mode status
2836
+ */
2837
+ async getEndlessModeStatus() {
2838
+ await this.initialize();
2839
+ let workingSetSize = 0;
2840
+ let continuityScore = 0.5;
2841
+ let consolidatedCount = 0;
2842
+ let lastConsolidation = null;
2843
+ if (this.workingSetStore) {
2844
+ workingSetSize = await this.workingSetStore.count();
2845
+ const workingSet = await this.workingSetStore.get();
2846
+ continuityScore = workingSet.continuityScore;
2847
+ }
2848
+ if (this.consolidatedStore) {
2849
+ consolidatedCount = await this.consolidatedStore.count();
2850
+ lastConsolidation = await this.consolidatedStore.getLastConsolidationTime();
2851
+ }
2852
+ return {
2853
+ mode: this.endlessMode,
2854
+ workingSetSize,
2855
+ continuityScore,
2856
+ consolidatedCount,
2857
+ lastConsolidation
2858
+ };
2859
+ }
2860
+ /**
2861
+ * Format Endless Mode context for Claude
2862
+ */
2863
+ async formatEndlessContext(query) {
2864
+ if (!this.isEndlessModeActive()) {
2865
+ return "";
2866
+ }
2867
+ const workingSet = await this.getWorkingSet();
2868
+ const consolidated = await this.searchConsolidated(query, { topK: 3 });
2869
+ const continuity = await this.calculateContinuity(query);
2870
+ const parts = [];
2871
+ if (continuity) {
2872
+ const statusEmoji = continuity.transitionType === "seamless" ? "\u{1F517}" : continuity.transitionType === "topic_shift" ? "\u21AA\uFE0F" : "\u{1F195}";
2873
+ parts.push(`${statusEmoji} Context: ${continuity.transitionType} (score: ${continuity.score.toFixed(2)})`);
2874
+ }
2875
+ if (workingSet && workingSet.recentEvents.length > 0) {
2876
+ parts.push("\n## Recent Context (Working Set)");
2877
+ const recent = workingSet.recentEvents.slice(0, 5);
2878
+ for (const event of recent) {
2879
+ const preview = event.content.slice(0, 80) + (event.content.length > 80 ? "..." : "");
2880
+ const time = event.timestamp.toLocaleTimeString();
2881
+ parts.push(`- ${time} [${event.eventType}] ${preview}`);
2882
+ }
2883
+ }
2884
+ if (consolidated.length > 0) {
2885
+ parts.push("\n## Related Knowledge (Consolidated)");
2886
+ for (const memory of consolidated) {
2887
+ parts.push(`- ${memory.topics.slice(0, 3).join(", ")}: ${memory.summary.slice(0, 100)}...`);
2888
+ }
2889
+ }
2890
+ return parts.join("\n");
2891
+ }
2892
+ /**
2893
+ * Shutdown service
2894
+ */
2895
+ async shutdown() {
2896
+ if (this.consolidationWorker) {
2897
+ this.consolidationWorker.stop();
2898
+ }
2899
+ if (this.vectorWorker) {
2900
+ this.vectorWorker.stop();
2901
+ }
2902
+ await this.eventStore.close();
2903
+ }
2904
+ /**
2905
+ * Expand ~ to home directory
2906
+ */
2907
+ expandPath(p) {
2908
+ if (p.startsWith("~")) {
2909
+ return path.join(os.homedir(), p.slice(1));
2910
+ }
2911
+ return p;
2912
+ }
2913
+ };
2914
+ var defaultService = null;
2915
+ function getDefaultMemoryService() {
2916
+ if (!defaultService) {
2917
+ defaultService = new MemoryService({
2918
+ storagePath: "~/.claude-code/memory"
2919
+ });
2920
+ }
2921
+ return defaultService;
2922
+ }
2923
+ function createMemoryService(config) {
2924
+ return new MemoryService(config);
2925
+ }
2926
+ export {
2927
+ MemoryService,
2928
+ createMemoryService,
2929
+ getDefaultMemoryService
2930
+ };
2931
+ //# sourceMappingURL=memory-service.js.map