claude-memory-layer 1.0.6 → 1.0.8

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 (45) hide show
  1. package/.claude/settings.local.json +4 -1
  2. package/.claude-plugin/plugin.json +3 -3
  3. package/.history/package_20260201142928.json +46 -0
  4. package/.history/package_20260201192048.json +47 -0
  5. package/README.md +26 -26
  6. package/dist/.claude-plugin/plugin.json +3 -3
  7. package/dist/cli/index.js +1109 -25
  8. package/dist/cli/index.js.map +4 -4
  9. package/dist/core/index.js +192 -5
  10. package/dist/core/index.js.map +4 -4
  11. package/dist/hooks/session-end.js +262 -18
  12. package/dist/hooks/session-end.js.map +4 -4
  13. package/dist/hooks/session-start.js +262 -18
  14. package/dist/hooks/session-start.js.map +4 -4
  15. package/dist/hooks/stop.js +262 -18
  16. package/dist/hooks/stop.js.map +4 -4
  17. package/dist/hooks/user-prompt-submit.js +262 -18
  18. package/dist/hooks/user-prompt-submit.js.map +4 -4
  19. package/dist/server/api/index.js +4728 -0
  20. package/dist/server/api/index.js.map +7 -0
  21. package/dist/server/index.js +4790 -0
  22. package/dist/server/index.js.map +7 -0
  23. package/dist/services/memory-service.js +269 -18
  24. package/dist/services/memory-service.js.map +4 -4
  25. package/dist/ui/index.html +1225 -0
  26. package/package.json +4 -2
  27. package/scripts/build.ts +33 -3
  28. package/src/cli/index.ts +311 -6
  29. package/src/core/db-wrapper.ts +8 -1
  30. package/src/core/event-store.ts +52 -3
  31. package/src/core/graduation-worker.ts +171 -0
  32. package/src/core/graduation.ts +15 -2
  33. package/src/core/index.ts +1 -0
  34. package/src/core/retriever.ts +18 -0
  35. package/src/core/types.ts +1 -1
  36. package/src/mcp/index.ts +2 -2
  37. package/src/mcp/tools.ts +1 -1
  38. package/src/server/api/citations.ts +7 -3
  39. package/src/server/api/events.ts +7 -3
  40. package/src/server/api/search.ts +7 -3
  41. package/src/server/api/sessions.ts +7 -3
  42. package/src/server/api/stats.ts +175 -5
  43. package/src/server/index.ts +18 -9
  44. package/src/services/memory-service.ts +107 -19
  45. package/src/ui/index.html +1225 -0
@@ -0,0 +1,4728 @@
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/server/api/index.ts
9
+ import { Hono as Hono6 } from "hono";
10
+
11
+ // src/server/api/sessions.ts
12
+ import { Hono } from "hono";
13
+
14
+ // src/services/memory-service.ts
15
+ import * as path from "path";
16
+ import * as os from "os";
17
+ import * as fs from "fs";
18
+ import * as crypto2 from "crypto";
19
+
20
+ // src/core/event-store.ts
21
+ import { randomUUID } from "crypto";
22
+
23
+ // src/core/canonical-key.ts
24
+ import { createHash } from "crypto";
25
+ var MAX_KEY_LENGTH = 200;
26
+ function makeCanonicalKey(title, context) {
27
+ let normalized = title.normalize("NFKC");
28
+ normalized = normalized.toLowerCase();
29
+ normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, "");
30
+ normalized = normalized.replace(/\s+/g, " ").trim();
31
+ let key = normalized;
32
+ if (context?.project) {
33
+ key = `${context.project}::${key}`;
34
+ }
35
+ if (key.length > MAX_KEY_LENGTH) {
36
+ const hashSuffix = createHash("md5").update(key).digest("hex").slice(0, 8);
37
+ key = key.slice(0, MAX_KEY_LENGTH - 9) + "_" + hashSuffix;
38
+ }
39
+ return key;
40
+ }
41
+ function makeDedupeKey(content, sessionId) {
42
+ const contentHash = createHash("sha256").update(content).digest("hex");
43
+ return `${sessionId}:${contentHash}`;
44
+ }
45
+
46
+ // src/core/db-wrapper.ts
47
+ import duckdb from "duckdb";
48
+ function convertBigInts(obj) {
49
+ if (obj === null || obj === void 0)
50
+ return obj;
51
+ if (typeof obj === "bigint")
52
+ return Number(obj);
53
+ if (obj instanceof Date)
54
+ return obj;
55
+ if (Array.isArray(obj))
56
+ return obj.map(convertBigInts);
57
+ if (typeof obj === "object") {
58
+ const result = {};
59
+ for (const [key, value] of Object.entries(obj)) {
60
+ result[key] = convertBigInts(value);
61
+ }
62
+ return result;
63
+ }
64
+ return obj;
65
+ }
66
+ function toDate(value) {
67
+ if (value instanceof Date)
68
+ return value;
69
+ if (typeof value === "string")
70
+ return new Date(value);
71
+ if (typeof value === "number")
72
+ return new Date(value);
73
+ return new Date(String(value));
74
+ }
75
+ function createDatabase(path2, options) {
76
+ if (options?.readOnly) {
77
+ return new duckdb.Database(path2, { access_mode: "READ_ONLY" });
78
+ }
79
+ return new duckdb.Database(path2);
80
+ }
81
+ function dbRun(db, sql, params = []) {
82
+ return new Promise((resolve2, reject) => {
83
+ if (params.length === 0) {
84
+ db.run(sql, (err) => {
85
+ if (err)
86
+ reject(err);
87
+ else
88
+ resolve2();
89
+ });
90
+ } else {
91
+ db.run(sql, ...params, (err) => {
92
+ if (err)
93
+ reject(err);
94
+ else
95
+ resolve2();
96
+ });
97
+ }
98
+ });
99
+ }
100
+ function dbAll(db, sql, params = []) {
101
+ return new Promise((resolve2, reject) => {
102
+ if (params.length === 0) {
103
+ db.all(sql, (err, rows) => {
104
+ if (err)
105
+ reject(err);
106
+ else
107
+ resolve2(convertBigInts(rows || []));
108
+ });
109
+ } else {
110
+ db.all(sql, ...params, (err, rows) => {
111
+ if (err)
112
+ reject(err);
113
+ else
114
+ resolve2(convertBigInts(rows || []));
115
+ });
116
+ }
117
+ });
118
+ }
119
+ function dbClose(db) {
120
+ return new Promise((resolve2, reject) => {
121
+ db.close((err) => {
122
+ if (err)
123
+ reject(err);
124
+ else
125
+ resolve2();
126
+ });
127
+ });
128
+ }
129
+
130
+ // src/core/event-store.ts
131
+ var EventStore = class {
132
+ constructor(dbPath, options) {
133
+ this.dbPath = dbPath;
134
+ this.readOnly = options?.readOnly ?? false;
135
+ this.db = createDatabase(dbPath, { readOnly: this.readOnly });
136
+ }
137
+ db;
138
+ initialized = false;
139
+ readOnly;
140
+ /**
141
+ * Initialize database schema
142
+ */
143
+ async initialize() {
144
+ if (this.initialized)
145
+ return;
146
+ if (this.readOnly) {
147
+ this.initialized = true;
148
+ return;
149
+ }
150
+ await dbRun(this.db, `
151
+ CREATE TABLE IF NOT EXISTS events (
152
+ id VARCHAR PRIMARY KEY,
153
+ event_type VARCHAR NOT NULL,
154
+ session_id VARCHAR NOT NULL,
155
+ timestamp TIMESTAMP NOT NULL,
156
+ content TEXT NOT NULL,
157
+ canonical_key VARCHAR NOT NULL,
158
+ dedupe_key VARCHAR UNIQUE,
159
+ metadata JSON
160
+ )
161
+ `);
162
+ await dbRun(this.db, `
163
+ CREATE TABLE IF NOT EXISTS event_dedup (
164
+ dedupe_key VARCHAR PRIMARY KEY,
165
+ event_id VARCHAR NOT NULL,
166
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
167
+ )
168
+ `);
169
+ await dbRun(this.db, `
170
+ CREATE TABLE IF NOT EXISTS sessions (
171
+ id VARCHAR PRIMARY KEY,
172
+ started_at TIMESTAMP NOT NULL,
173
+ ended_at TIMESTAMP,
174
+ project_path VARCHAR,
175
+ summary TEXT,
176
+ tags JSON
177
+ )
178
+ `);
179
+ await dbRun(this.db, `
180
+ CREATE TABLE IF NOT EXISTS insights (
181
+ id VARCHAR PRIMARY KEY,
182
+ insight_type VARCHAR NOT NULL,
183
+ content TEXT NOT NULL,
184
+ canonical_key VARCHAR NOT NULL,
185
+ confidence FLOAT,
186
+ source_events JSON,
187
+ created_at TIMESTAMP,
188
+ last_updated TIMESTAMP
189
+ )
190
+ `);
191
+ await dbRun(this.db, `
192
+ CREATE TABLE IF NOT EXISTS embedding_outbox (
193
+ id VARCHAR PRIMARY KEY,
194
+ event_id VARCHAR NOT NULL,
195
+ content TEXT NOT NULL,
196
+ status VARCHAR DEFAULT 'pending',
197
+ retry_count INT DEFAULT 0,
198
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
199
+ processed_at TIMESTAMP,
200
+ error_message TEXT
201
+ )
202
+ `);
203
+ await dbRun(this.db, `
204
+ CREATE TABLE IF NOT EXISTS projection_offsets (
205
+ projection_name VARCHAR PRIMARY KEY,
206
+ last_event_id VARCHAR,
207
+ last_timestamp TIMESTAMP,
208
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
209
+ )
210
+ `);
211
+ await dbRun(this.db, `
212
+ CREATE TABLE IF NOT EXISTS memory_levels (
213
+ event_id VARCHAR PRIMARY KEY,
214
+ level VARCHAR NOT NULL DEFAULT 'L0',
215
+ promoted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
216
+ )
217
+ `);
218
+ await dbRun(this.db, `
219
+ CREATE TABLE IF NOT EXISTS entries (
220
+ entry_id VARCHAR PRIMARY KEY,
221
+ created_ts TIMESTAMP NOT NULL,
222
+ entry_type VARCHAR NOT NULL,
223
+ title VARCHAR NOT NULL,
224
+ content_json JSON NOT NULL,
225
+ stage VARCHAR NOT NULL DEFAULT 'raw',
226
+ status VARCHAR DEFAULT 'active',
227
+ superseded_by VARCHAR,
228
+ build_id VARCHAR,
229
+ evidence_json JSON,
230
+ canonical_key VARCHAR,
231
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
232
+ )
233
+ `);
234
+ await dbRun(this.db, `
235
+ CREATE TABLE IF NOT EXISTS entities (
236
+ entity_id VARCHAR PRIMARY KEY,
237
+ entity_type VARCHAR NOT NULL,
238
+ canonical_key VARCHAR NOT NULL,
239
+ title VARCHAR NOT NULL,
240
+ stage VARCHAR NOT NULL DEFAULT 'raw',
241
+ status VARCHAR NOT NULL DEFAULT 'active',
242
+ current_json JSON NOT NULL,
243
+ title_norm VARCHAR,
244
+ search_text VARCHAR,
245
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
246
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
247
+ )
248
+ `);
249
+ await dbRun(this.db, `
250
+ CREATE TABLE IF NOT EXISTS entity_aliases (
251
+ entity_type VARCHAR NOT NULL,
252
+ canonical_key VARCHAR NOT NULL,
253
+ entity_id VARCHAR NOT NULL,
254
+ is_primary BOOLEAN DEFAULT FALSE,
255
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
256
+ PRIMARY KEY(entity_type, canonical_key)
257
+ )
258
+ `);
259
+ await dbRun(this.db, `
260
+ CREATE TABLE IF NOT EXISTS edges (
261
+ edge_id VARCHAR PRIMARY KEY,
262
+ src_type VARCHAR NOT NULL,
263
+ src_id VARCHAR NOT NULL,
264
+ rel_type VARCHAR NOT NULL,
265
+ dst_type VARCHAR NOT NULL,
266
+ dst_id VARCHAR NOT NULL,
267
+ meta_json JSON,
268
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
269
+ )
270
+ `);
271
+ await dbRun(this.db, `
272
+ CREATE TABLE IF NOT EXISTS vector_outbox (
273
+ job_id VARCHAR PRIMARY KEY,
274
+ item_kind VARCHAR NOT NULL,
275
+ item_id VARCHAR NOT NULL,
276
+ embedding_version VARCHAR NOT NULL,
277
+ status VARCHAR NOT NULL DEFAULT 'pending',
278
+ retry_count INT DEFAULT 0,
279
+ error VARCHAR,
280
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
281
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
282
+ UNIQUE(item_kind, item_id, embedding_version)
283
+ )
284
+ `);
285
+ await dbRun(this.db, `
286
+ CREATE TABLE IF NOT EXISTS build_runs (
287
+ build_id VARCHAR PRIMARY KEY,
288
+ started_at TIMESTAMP NOT NULL,
289
+ finished_at TIMESTAMP,
290
+ extractor_model VARCHAR NOT NULL,
291
+ extractor_prompt_hash VARCHAR NOT NULL,
292
+ embedder_model VARCHAR NOT NULL,
293
+ embedding_version VARCHAR NOT NULL,
294
+ idris_version VARCHAR NOT NULL,
295
+ schema_version VARCHAR NOT NULL,
296
+ status VARCHAR NOT NULL DEFAULT 'running',
297
+ error VARCHAR
298
+ )
299
+ `);
300
+ await dbRun(this.db, `
301
+ CREATE TABLE IF NOT EXISTS pipeline_metrics (
302
+ id VARCHAR PRIMARY KEY,
303
+ ts TIMESTAMP NOT NULL,
304
+ stage VARCHAR NOT NULL,
305
+ latency_ms DOUBLE NOT NULL,
306
+ success BOOLEAN NOT NULL,
307
+ error VARCHAR,
308
+ session_id VARCHAR
309
+ )
310
+ `);
311
+ await dbRun(this.db, `
312
+ CREATE TABLE IF NOT EXISTS working_set (
313
+ id VARCHAR PRIMARY KEY,
314
+ event_id VARCHAR NOT NULL,
315
+ added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
316
+ relevance_score FLOAT DEFAULT 1.0,
317
+ topics JSON,
318
+ expires_at TIMESTAMP
319
+ )
320
+ `);
321
+ await dbRun(this.db, `
322
+ CREATE TABLE IF NOT EXISTS consolidated_memories (
323
+ memory_id VARCHAR PRIMARY KEY,
324
+ summary TEXT NOT NULL,
325
+ topics JSON,
326
+ source_events JSON,
327
+ confidence FLOAT DEFAULT 0.5,
328
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
329
+ accessed_at TIMESTAMP,
330
+ access_count INTEGER DEFAULT 0
331
+ )
332
+ `);
333
+ await dbRun(this.db, `
334
+ CREATE TABLE IF NOT EXISTS continuity_log (
335
+ log_id VARCHAR PRIMARY KEY,
336
+ from_context_id VARCHAR,
337
+ to_context_id VARCHAR,
338
+ continuity_score FLOAT,
339
+ transition_type VARCHAR,
340
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
341
+ )
342
+ `);
343
+ await dbRun(this.db, `
344
+ CREATE TABLE IF NOT EXISTS endless_config (
345
+ key VARCHAR PRIMARY KEY,
346
+ value JSON,
347
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
348
+ )
349
+ `);
350
+ await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_type ON entries(entry_type)`);
351
+ await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_stage ON entries(stage)`);
352
+ await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_canonical ON entries(canonical_key)`);
353
+ await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entities_type_key ON entities(entity_type, canonical_key)`);
354
+ await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entities_status ON entities(status)`);
355
+ await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src_id, rel_type)`);
356
+ await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_dst ON edges(dst_id, rel_type)`);
357
+ await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_rel ON edges(rel_type)`);
358
+ await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_outbox_status ON vector_outbox(status)`);
359
+ await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_expires ON working_set(expires_at)`);
360
+ await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_relevance ON working_set(relevance_score DESC)`);
361
+ await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence DESC)`);
362
+ await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at)`);
363
+ this.initialized = true;
364
+ }
365
+ /**
366
+ * Append event to store (AXIOMMIND Principle 2: Append-only)
367
+ * Returns existing event ID if duplicate (Principle 3: Idempotency)
368
+ */
369
+ async append(input) {
370
+ await this.initialize();
371
+ const canonicalKey = makeCanonicalKey(input.content);
372
+ const dedupeKey = makeDedupeKey(input.content, input.sessionId);
373
+ const existing = await dbAll(
374
+ this.db,
375
+ `SELECT event_id FROM event_dedup WHERE dedupe_key = ?`,
376
+ [dedupeKey]
377
+ );
378
+ if (existing.length > 0) {
379
+ return {
380
+ success: true,
381
+ eventId: existing[0].event_id,
382
+ isDuplicate: true
383
+ };
384
+ }
385
+ const id = randomUUID();
386
+ const timestamp = input.timestamp.toISOString();
387
+ try {
388
+ await dbRun(
389
+ this.db,
390
+ `INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
391
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
392
+ [
393
+ id,
394
+ input.eventType,
395
+ input.sessionId,
396
+ timestamp,
397
+ input.content,
398
+ canonicalKey,
399
+ dedupeKey,
400
+ JSON.stringify(input.metadata || {})
401
+ ]
402
+ );
403
+ await dbRun(
404
+ this.db,
405
+ `INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)`,
406
+ [dedupeKey, id]
407
+ );
408
+ await dbRun(
409
+ this.db,
410
+ `INSERT INTO memory_levels (event_id, level) VALUES (?, 'L0')`,
411
+ [id]
412
+ );
413
+ return { success: true, eventId: id, isDuplicate: false };
414
+ } catch (error) {
415
+ return {
416
+ success: false,
417
+ error: error instanceof Error ? error.message : String(error)
418
+ };
419
+ }
420
+ }
421
+ /**
422
+ * Get events by session ID
423
+ */
424
+ async getSessionEvents(sessionId) {
425
+ await this.initialize();
426
+ const rows = await dbAll(
427
+ this.db,
428
+ `SELECT * FROM events WHERE session_id = ? ORDER BY timestamp ASC`,
429
+ [sessionId]
430
+ );
431
+ return rows.map(this.rowToEvent);
432
+ }
433
+ /**
434
+ * Get recent events
435
+ */
436
+ async getRecentEvents(limit = 100) {
437
+ await this.initialize();
438
+ const rows = await dbAll(
439
+ this.db,
440
+ `SELECT * FROM events ORDER BY timestamp DESC LIMIT ?`,
441
+ [limit]
442
+ );
443
+ return rows.map(this.rowToEvent);
444
+ }
445
+ /**
446
+ * Get event by ID
447
+ */
448
+ async getEvent(id) {
449
+ await this.initialize();
450
+ const rows = await dbAll(
451
+ this.db,
452
+ `SELECT * FROM events WHERE id = ?`,
453
+ [id]
454
+ );
455
+ if (rows.length === 0)
456
+ return null;
457
+ return this.rowToEvent(rows[0]);
458
+ }
459
+ /**
460
+ * Create or update session
461
+ */
462
+ async upsertSession(session) {
463
+ await this.initialize();
464
+ const existing = await dbAll(
465
+ this.db,
466
+ `SELECT id FROM sessions WHERE id = ?`,
467
+ [session.id]
468
+ );
469
+ if (existing.length === 0) {
470
+ await dbRun(
471
+ this.db,
472
+ `INSERT INTO sessions (id, started_at, project_path, tags)
473
+ VALUES (?, ?, ?, ?)`,
474
+ [
475
+ session.id,
476
+ (session.startedAt || /* @__PURE__ */ new Date()).toISOString(),
477
+ session.projectPath || null,
478
+ JSON.stringify(session.tags || [])
479
+ ]
480
+ );
481
+ } else {
482
+ const updates = [];
483
+ const values = [];
484
+ if (session.endedAt) {
485
+ updates.push("ended_at = ?");
486
+ values.push(session.endedAt.toISOString());
487
+ }
488
+ if (session.summary) {
489
+ updates.push("summary = ?");
490
+ values.push(session.summary);
491
+ }
492
+ if (session.tags) {
493
+ updates.push("tags = ?");
494
+ values.push(JSON.stringify(session.tags));
495
+ }
496
+ if (updates.length > 0) {
497
+ values.push(session.id);
498
+ await dbRun(
499
+ this.db,
500
+ `UPDATE sessions SET ${updates.join(", ")} WHERE id = ?`,
501
+ values
502
+ );
503
+ }
504
+ }
505
+ }
506
+ /**
507
+ * Get session by ID
508
+ */
509
+ async getSession(id) {
510
+ await this.initialize();
511
+ const rows = await dbAll(
512
+ this.db,
513
+ `SELECT * FROM sessions WHERE id = ?`,
514
+ [id]
515
+ );
516
+ if (rows.length === 0)
517
+ return null;
518
+ const row = rows[0];
519
+ return {
520
+ id: row.id,
521
+ startedAt: toDate(row.started_at),
522
+ endedAt: row.ended_at ? toDate(row.ended_at) : void 0,
523
+ projectPath: row.project_path,
524
+ summary: row.summary,
525
+ tags: row.tags ? JSON.parse(row.tags) : void 0
526
+ };
527
+ }
528
+ /**
529
+ * Add to embedding outbox (Single-Writer Pattern)
530
+ */
531
+ async enqueueForEmbedding(eventId, content) {
532
+ await this.initialize();
533
+ const id = randomUUID();
534
+ await dbRun(
535
+ this.db,
536
+ `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
537
+ VALUES (?, ?, ?, 'pending', 0)`,
538
+ [id, eventId, content]
539
+ );
540
+ return id;
541
+ }
542
+ /**
543
+ * Get pending outbox items
544
+ */
545
+ async getPendingOutboxItems(limit = 32) {
546
+ await this.initialize();
547
+ const pending = await dbAll(
548
+ this.db,
549
+ `SELECT * FROM embedding_outbox
550
+ WHERE status = 'pending'
551
+ ORDER BY created_at
552
+ LIMIT ?`,
553
+ [limit]
554
+ );
555
+ if (pending.length === 0)
556
+ return [];
557
+ const ids = pending.map((r) => r.id);
558
+ const placeholders = ids.map(() => "?").join(",");
559
+ await dbRun(
560
+ this.db,
561
+ `UPDATE embedding_outbox SET status = 'processing' WHERE id IN (${placeholders})`,
562
+ ids
563
+ );
564
+ return pending.map((row) => ({
565
+ id: row.id,
566
+ eventId: row.event_id,
567
+ content: row.content,
568
+ status: "processing",
569
+ retryCount: row.retry_count,
570
+ createdAt: toDate(row.created_at),
571
+ errorMessage: row.error_message
572
+ }));
573
+ }
574
+ /**
575
+ * Mark outbox items as done
576
+ */
577
+ async completeOutboxItems(ids) {
578
+ if (ids.length === 0)
579
+ return;
580
+ const placeholders = ids.map(() => "?").join(",");
581
+ await dbRun(
582
+ this.db,
583
+ `DELETE FROM embedding_outbox WHERE id IN (${placeholders})`,
584
+ ids
585
+ );
586
+ }
587
+ /**
588
+ * Mark outbox items as failed
589
+ */
590
+ async failOutboxItems(ids, error) {
591
+ if (ids.length === 0)
592
+ return;
593
+ const placeholders = ids.map(() => "?").join(",");
594
+ await dbRun(
595
+ this.db,
596
+ `UPDATE embedding_outbox
597
+ SET status = CASE WHEN retry_count >= 3 THEN 'failed' ELSE 'pending' END,
598
+ retry_count = retry_count + 1,
599
+ error_message = ?
600
+ WHERE id IN (${placeholders})`,
601
+ [error, ...ids]
602
+ );
603
+ }
604
+ /**
605
+ * Update memory level
606
+ */
607
+ async updateMemoryLevel(eventId, level) {
608
+ await this.initialize();
609
+ await dbRun(
610
+ this.db,
611
+ `UPDATE memory_levels SET level = ?, promoted_at = CURRENT_TIMESTAMP WHERE event_id = ?`,
612
+ [level, eventId]
613
+ );
614
+ }
615
+ /**
616
+ * Get memory level statistics
617
+ */
618
+ async getLevelStats() {
619
+ await this.initialize();
620
+ const rows = await dbAll(
621
+ this.db,
622
+ `SELECT level, COUNT(*) as count FROM memory_levels GROUP BY level`
623
+ );
624
+ return rows;
625
+ }
626
+ /**
627
+ * Get events by memory level
628
+ */
629
+ async getEventsByLevel(level, options) {
630
+ await this.initialize();
631
+ const limit = options?.limit || 50;
632
+ const offset = options?.offset || 0;
633
+ const rows = await dbAll(
634
+ this.db,
635
+ `SELECT e.* FROM events e
636
+ INNER JOIN memory_levels ml ON e.id = ml.event_id
637
+ WHERE ml.level = ?
638
+ ORDER BY e.timestamp DESC
639
+ LIMIT ? OFFSET ?`,
640
+ [level, limit, offset]
641
+ );
642
+ return rows.map((row) => this.rowToEvent(row));
643
+ }
644
+ /**
645
+ * Get memory level for a specific event
646
+ */
647
+ async getEventLevel(eventId) {
648
+ await this.initialize();
649
+ const rows = await dbAll(
650
+ this.db,
651
+ `SELECT level FROM memory_levels WHERE event_id = ?`,
652
+ [eventId]
653
+ );
654
+ return rows.length > 0 ? rows[0].level : null;
655
+ }
656
+ // ============================================================
657
+ // Endless Mode Helper Methods
658
+ // ============================================================
659
+ /**
660
+ * Get database instance for Endless Mode stores
661
+ */
662
+ getDatabase() {
663
+ return this.db;
664
+ }
665
+ /**
666
+ * Get config value for endless mode
667
+ */
668
+ async getEndlessConfig(key) {
669
+ await this.initialize();
670
+ const rows = await dbAll(
671
+ this.db,
672
+ `SELECT value FROM endless_config WHERE key = ?`,
673
+ [key]
674
+ );
675
+ if (rows.length === 0)
676
+ return null;
677
+ return JSON.parse(rows[0].value);
678
+ }
679
+ /**
680
+ * Set config value for endless mode
681
+ */
682
+ async setEndlessConfig(key, value) {
683
+ await this.initialize();
684
+ await dbRun(
685
+ this.db,
686
+ `INSERT OR REPLACE INTO endless_config (key, value, updated_at)
687
+ VALUES (?, ?, CURRENT_TIMESTAMP)`,
688
+ [key, JSON.stringify(value)]
689
+ );
690
+ }
691
+ /**
692
+ * Get all sessions
693
+ */
694
+ async getAllSessions() {
695
+ await this.initialize();
696
+ const rows = await dbAll(
697
+ this.db,
698
+ `SELECT * FROM sessions ORDER BY started_at DESC`
699
+ );
700
+ return rows.map((row) => ({
701
+ id: row.id,
702
+ startedAt: toDate(row.started_at),
703
+ endedAt: row.ended_at ? toDate(row.ended_at) : void 0,
704
+ projectPath: row.project_path,
705
+ summary: row.summary,
706
+ tags: row.tags ? JSON.parse(row.tags) : void 0
707
+ }));
708
+ }
709
+ /**
710
+ * Close database connection
711
+ */
712
+ async close() {
713
+ await dbClose(this.db);
714
+ }
715
+ /**
716
+ * Convert database row to MemoryEvent
717
+ */
718
+ rowToEvent(row) {
719
+ return {
720
+ id: row.id,
721
+ eventType: row.event_type,
722
+ sessionId: row.session_id,
723
+ timestamp: toDate(row.timestamp),
724
+ content: row.content,
725
+ canonicalKey: row.canonical_key,
726
+ dedupeKey: row.dedupe_key,
727
+ metadata: row.metadata ? JSON.parse(row.metadata) : void 0
728
+ };
729
+ }
730
+ };
731
+
732
+ // src/core/vector-store.ts
733
+ import * as lancedb from "@lancedb/lancedb";
734
+ var VectorStore = class {
735
+ constructor(dbPath) {
736
+ this.dbPath = dbPath;
737
+ }
738
+ db = null;
739
+ table = null;
740
+ tableName = "conversations";
741
+ /**
742
+ * Initialize LanceDB connection
743
+ */
744
+ async initialize() {
745
+ if (this.db)
746
+ return;
747
+ this.db = await lancedb.connect(this.dbPath);
748
+ try {
749
+ const tables = await this.db.tableNames();
750
+ if (tables.includes(this.tableName)) {
751
+ this.table = await this.db.openTable(this.tableName);
752
+ }
753
+ } catch {
754
+ this.table = null;
755
+ }
756
+ }
757
+ /**
758
+ * Add or update vector record
759
+ */
760
+ async upsert(record) {
761
+ await this.initialize();
762
+ if (!this.db) {
763
+ throw new Error("Database not initialized");
764
+ }
765
+ const data = {
766
+ id: record.id,
767
+ eventId: record.eventId,
768
+ sessionId: record.sessionId,
769
+ eventType: record.eventType,
770
+ content: record.content,
771
+ vector: record.vector,
772
+ timestamp: record.timestamp,
773
+ metadata: JSON.stringify(record.metadata || {})
774
+ };
775
+ if (!this.table) {
776
+ this.table = await this.db.createTable(this.tableName, [data]);
777
+ } else {
778
+ await this.table.add([data]);
779
+ }
780
+ }
781
+ /**
782
+ * Add multiple vector records in batch
783
+ */
784
+ async upsertBatch(records) {
785
+ if (records.length === 0)
786
+ return;
787
+ await this.initialize();
788
+ if (!this.db) {
789
+ throw new Error("Database not initialized");
790
+ }
791
+ const data = records.map((record) => ({
792
+ id: record.id,
793
+ eventId: record.eventId,
794
+ sessionId: record.sessionId,
795
+ eventType: record.eventType,
796
+ content: record.content,
797
+ vector: record.vector,
798
+ timestamp: record.timestamp,
799
+ metadata: JSON.stringify(record.metadata || {})
800
+ }));
801
+ if (!this.table) {
802
+ this.table = await this.db.createTable(this.tableName, data);
803
+ } else {
804
+ await this.table.add(data);
805
+ }
806
+ }
807
+ /**
808
+ * Search for similar vectors
809
+ */
810
+ async search(queryVector, options = {}) {
811
+ await this.initialize();
812
+ if (!this.table) {
813
+ return [];
814
+ }
815
+ const { limit = 5, minScore = 0.7, sessionId } = options;
816
+ let query = this.table.search(queryVector).distanceType("cosine").limit(limit * 2);
817
+ if (sessionId) {
818
+ query = query.where(`sessionId = '${sessionId}'`);
819
+ }
820
+ const results = await query.toArray();
821
+ return results.filter((r) => {
822
+ const distance = r._distance || 0;
823
+ const score = 1 - distance / 2;
824
+ return score >= minScore;
825
+ }).slice(0, limit).map((r) => {
826
+ const distance = r._distance || 0;
827
+ const score = 1 - distance / 2;
828
+ return {
829
+ id: r.id,
830
+ eventId: r.eventId,
831
+ content: r.content,
832
+ score,
833
+ sessionId: r.sessionId,
834
+ eventType: r.eventType,
835
+ timestamp: r.timestamp
836
+ };
837
+ });
838
+ }
839
+ /**
840
+ * Delete vector by event ID
841
+ */
842
+ async delete(eventId) {
843
+ if (!this.table)
844
+ return;
845
+ await this.table.delete(`eventId = '${eventId}'`);
846
+ }
847
+ /**
848
+ * Get total count of vectors
849
+ */
850
+ async count() {
851
+ if (!this.table)
852
+ return 0;
853
+ const result = await this.table.countRows();
854
+ return result;
855
+ }
856
+ /**
857
+ * Check if vector exists for event
858
+ */
859
+ async exists(eventId) {
860
+ if (!this.table)
861
+ return false;
862
+ const results = await this.table.search([]).where(`eventId = '${eventId}'`).limit(1).toArray();
863
+ return results.length > 0;
864
+ }
865
+ };
866
+
867
+ // src/core/embedder.ts
868
+ import { pipeline } from "@xenova/transformers";
869
+ var Embedder = class {
870
+ pipeline = null;
871
+ modelName;
872
+ initialized = false;
873
+ constructor(modelName = "Xenova/all-MiniLM-L6-v2") {
874
+ this.modelName = modelName;
875
+ }
876
+ /**
877
+ * Initialize the embedding pipeline
878
+ */
879
+ async initialize() {
880
+ if (this.initialized)
881
+ return;
882
+ this.pipeline = await pipeline("feature-extraction", this.modelName);
883
+ this.initialized = true;
884
+ }
885
+ /**
886
+ * Generate embedding for a single text
887
+ */
888
+ async embed(text) {
889
+ await this.initialize();
890
+ if (!this.pipeline) {
891
+ throw new Error("Embedding pipeline not initialized");
892
+ }
893
+ const output = await this.pipeline(text, {
894
+ pooling: "mean",
895
+ normalize: true
896
+ });
897
+ const vector = Array.from(output.data);
898
+ return {
899
+ vector,
900
+ model: this.modelName,
901
+ dimensions: vector.length
902
+ };
903
+ }
904
+ /**
905
+ * Generate embeddings for multiple texts in batch
906
+ */
907
+ async embedBatch(texts) {
908
+ await this.initialize();
909
+ if (!this.pipeline) {
910
+ throw new Error("Embedding pipeline not initialized");
911
+ }
912
+ const results = [];
913
+ const batchSize = 32;
914
+ for (let i = 0; i < texts.length; i += batchSize) {
915
+ const batch = texts.slice(i, i + batchSize);
916
+ for (const text of batch) {
917
+ const output = await this.pipeline(text, {
918
+ pooling: "mean",
919
+ normalize: true
920
+ });
921
+ const vector = Array.from(output.data);
922
+ results.push({
923
+ vector,
924
+ model: this.modelName,
925
+ dimensions: vector.length
926
+ });
927
+ }
928
+ }
929
+ return results;
930
+ }
931
+ /**
932
+ * Get embedding dimensions for the current model
933
+ */
934
+ async getDimensions() {
935
+ const result = await this.embed("test");
936
+ return result.dimensions;
937
+ }
938
+ /**
939
+ * Check if embedder is ready
940
+ */
941
+ isReady() {
942
+ return this.initialized && this.pipeline !== null;
943
+ }
944
+ /**
945
+ * Get model name
946
+ */
947
+ getModelName() {
948
+ return this.modelName;
949
+ }
950
+ };
951
+ var defaultEmbedder = null;
952
+ function getDefaultEmbedder() {
953
+ if (!defaultEmbedder) {
954
+ defaultEmbedder = new Embedder();
955
+ }
956
+ return defaultEmbedder;
957
+ }
958
+
959
+ // src/core/vector-outbox.ts
960
+ var DEFAULT_CONFIG = {
961
+ embeddingVersion: "v1",
962
+ maxRetries: 3,
963
+ stuckThresholdMs: 5 * 60 * 1e3,
964
+ // 5 minutes
965
+ cleanupDays: 7
966
+ };
967
+
968
+ // src/core/vector-worker.ts
969
+ var DEFAULT_CONFIG2 = {
970
+ batchSize: 32,
971
+ pollIntervalMs: 1e3,
972
+ maxRetries: 3
973
+ };
974
+ var VectorWorker = class {
975
+ eventStore;
976
+ vectorStore;
977
+ embedder;
978
+ config;
979
+ running = false;
980
+ pollTimeout = null;
981
+ constructor(eventStore, vectorStore, embedder, config = {}) {
982
+ this.eventStore = eventStore;
983
+ this.vectorStore = vectorStore;
984
+ this.embedder = embedder;
985
+ this.config = { ...DEFAULT_CONFIG2, ...config };
986
+ }
987
+ /**
988
+ * Start the worker polling loop
989
+ */
990
+ start() {
991
+ if (this.running)
992
+ return;
993
+ this.running = true;
994
+ this.poll();
995
+ }
996
+ /**
997
+ * Stop the worker
998
+ */
999
+ stop() {
1000
+ this.running = false;
1001
+ if (this.pollTimeout) {
1002
+ clearTimeout(this.pollTimeout);
1003
+ this.pollTimeout = null;
1004
+ }
1005
+ }
1006
+ /**
1007
+ * Process a single batch of outbox items
1008
+ */
1009
+ async processBatch() {
1010
+ const items = await this.eventStore.getPendingOutboxItems(this.config.batchSize);
1011
+ if (items.length === 0) {
1012
+ return 0;
1013
+ }
1014
+ const successful = [];
1015
+ const failed = [];
1016
+ try {
1017
+ const embeddings = await this.embedder.embedBatch(items.map((i) => i.content));
1018
+ const records = [];
1019
+ for (let i = 0; i < items.length; i++) {
1020
+ const item = items[i];
1021
+ const embedding = embeddings[i];
1022
+ const event = await this.eventStore.getEvent(item.eventId);
1023
+ if (!event) {
1024
+ failed.push(item.id);
1025
+ continue;
1026
+ }
1027
+ records.push({
1028
+ id: `vec_${item.id}`,
1029
+ eventId: item.eventId,
1030
+ sessionId: event.sessionId,
1031
+ eventType: event.eventType,
1032
+ content: item.content,
1033
+ vector: embedding.vector,
1034
+ timestamp: event.timestamp.toISOString(),
1035
+ metadata: event.metadata
1036
+ });
1037
+ successful.push(item.id);
1038
+ }
1039
+ if (records.length > 0) {
1040
+ await this.vectorStore.upsertBatch(records);
1041
+ }
1042
+ if (successful.length > 0) {
1043
+ await this.eventStore.completeOutboxItems(successful);
1044
+ }
1045
+ if (failed.length > 0) {
1046
+ await this.eventStore.failOutboxItems(failed, "Event not found");
1047
+ }
1048
+ return successful.length;
1049
+ } catch (error) {
1050
+ const allIds = items.map((i) => i.id);
1051
+ const errorMessage = error instanceof Error ? error.message : String(error);
1052
+ await this.eventStore.failOutboxItems(allIds, errorMessage);
1053
+ throw error;
1054
+ }
1055
+ }
1056
+ /**
1057
+ * Poll for new items
1058
+ */
1059
+ async poll() {
1060
+ if (!this.running)
1061
+ return;
1062
+ try {
1063
+ await this.processBatch();
1064
+ } catch (error) {
1065
+ console.error("Vector worker error:", error);
1066
+ }
1067
+ this.pollTimeout = setTimeout(() => this.poll(), this.config.pollIntervalMs);
1068
+ }
1069
+ /**
1070
+ * Process all pending items (blocking)
1071
+ */
1072
+ async processAll() {
1073
+ let totalProcessed = 0;
1074
+ let processed;
1075
+ do {
1076
+ processed = await this.processBatch();
1077
+ totalProcessed += processed;
1078
+ } while (processed > 0);
1079
+ return totalProcessed;
1080
+ }
1081
+ /**
1082
+ * Check if worker is running
1083
+ */
1084
+ isRunning() {
1085
+ return this.running;
1086
+ }
1087
+ };
1088
+ function createVectorWorker(eventStore, vectorStore, embedder, config) {
1089
+ const worker = new VectorWorker(eventStore, vectorStore, embedder, config);
1090
+ return worker;
1091
+ }
1092
+
1093
+ // src/core/matcher.ts
1094
+ var DEFAULT_CONFIG3 = {
1095
+ weights: {
1096
+ semanticSimilarity: 0.4,
1097
+ ftsScore: 0.25,
1098
+ recencyBonus: 0.2,
1099
+ statusWeight: 0.15
1100
+ },
1101
+ minCombinedScore: 0.92,
1102
+ minGap: 0.03,
1103
+ suggestionThreshold: 0.75
1104
+ };
1105
+ var Matcher = class {
1106
+ config;
1107
+ constructor(config = {}) {
1108
+ this.config = {
1109
+ ...DEFAULT_CONFIG3,
1110
+ ...config,
1111
+ weights: { ...DEFAULT_CONFIG3.weights, ...config.weights }
1112
+ };
1113
+ }
1114
+ /**
1115
+ * Calculate combined score using AXIOMMIND weighted formula
1116
+ */
1117
+ calculateCombinedScore(semanticScore, ftsScore = 0, recencyDays = 0, isActive = true) {
1118
+ const { weights } = this.config;
1119
+ const recencyBonus = Math.max(0, 1 - recencyDays / 30);
1120
+ const statusMultiplier = isActive ? 1 : 0.7;
1121
+ const combinedScore = weights.semanticSimilarity * semanticScore + weights.ftsScore * ftsScore + weights.recencyBonus * recencyBonus + weights.statusWeight * statusMultiplier;
1122
+ return Math.min(1, combinedScore);
1123
+ }
1124
+ /**
1125
+ * Classify match confidence based on AXIOMMIND thresholds
1126
+ */
1127
+ classifyConfidence(topScore, secondScore) {
1128
+ const { minCombinedScore, minGap, suggestionThreshold } = this.config;
1129
+ const gap = secondScore !== null ? topScore - secondScore : Infinity;
1130
+ if (topScore >= minCombinedScore && gap >= minGap) {
1131
+ return "high";
1132
+ }
1133
+ if (topScore >= suggestionThreshold) {
1134
+ return "suggested";
1135
+ }
1136
+ return "none";
1137
+ }
1138
+ /**
1139
+ * Match search results to find best memory
1140
+ */
1141
+ matchSearchResults(results, getEventAge) {
1142
+ if (results.length === 0) {
1143
+ return {
1144
+ match: null,
1145
+ confidence: "none"
1146
+ };
1147
+ }
1148
+ const scoredResults = results.map((result) => {
1149
+ const ageDays = getEventAge(result.eventId);
1150
+ const combinedScore = this.calculateCombinedScore(
1151
+ result.score,
1152
+ 0,
1153
+ // FTS score - would need to be passed in
1154
+ ageDays,
1155
+ true
1156
+ // Assume active
1157
+ );
1158
+ return {
1159
+ result,
1160
+ combinedScore
1161
+ };
1162
+ });
1163
+ scoredResults.sort((a, b) => b.combinedScore - a.combinedScore);
1164
+ const topResult = scoredResults[0];
1165
+ const secondScore = scoredResults.length > 1 ? scoredResults[1].combinedScore : null;
1166
+ const confidence = this.classifyConfidence(topResult.combinedScore, secondScore);
1167
+ const match = {
1168
+ event: {
1169
+ id: topResult.result.eventId,
1170
+ eventType: topResult.result.eventType,
1171
+ sessionId: topResult.result.sessionId,
1172
+ timestamp: new Date(topResult.result.timestamp),
1173
+ content: topResult.result.content,
1174
+ canonicalKey: "",
1175
+ // Would need to be fetched
1176
+ dedupeKey: ""
1177
+ // Would need to be fetched
1178
+ },
1179
+ score: topResult.combinedScore
1180
+ };
1181
+ const gap = secondScore !== null ? topResult.combinedScore - secondScore : void 0;
1182
+ const alternatives = confidence === "suggested" ? scoredResults.slice(1, 4).map((sr) => ({
1183
+ event: {
1184
+ id: sr.result.eventId,
1185
+ eventType: sr.result.eventType,
1186
+ sessionId: sr.result.sessionId,
1187
+ timestamp: new Date(sr.result.timestamp),
1188
+ content: sr.result.content,
1189
+ canonicalKey: "",
1190
+ dedupeKey: ""
1191
+ },
1192
+ score: sr.combinedScore
1193
+ })) : void 0;
1194
+ return {
1195
+ match: confidence !== "none" ? match : null,
1196
+ confidence,
1197
+ gap,
1198
+ alternatives
1199
+ };
1200
+ }
1201
+ /**
1202
+ * Calculate days between two dates
1203
+ */
1204
+ static calculateAgeDays(timestamp) {
1205
+ const now = /* @__PURE__ */ new Date();
1206
+ const diffMs = now.getTime() - timestamp.getTime();
1207
+ return diffMs / (1e3 * 60 * 60 * 24);
1208
+ }
1209
+ /**
1210
+ * Get current configuration
1211
+ */
1212
+ getConfig() {
1213
+ return { ...this.config };
1214
+ }
1215
+ };
1216
+ var defaultMatcher = null;
1217
+ function getDefaultMatcher() {
1218
+ if (!defaultMatcher) {
1219
+ defaultMatcher = new Matcher();
1220
+ }
1221
+ return defaultMatcher;
1222
+ }
1223
+
1224
+ // src/core/retriever.ts
1225
+ var DEFAULT_OPTIONS = {
1226
+ topK: 5,
1227
+ minScore: 0.7,
1228
+ maxTokens: 2e3,
1229
+ includeSessionContext: true
1230
+ };
1231
+ var Retriever = class {
1232
+ eventStore;
1233
+ vectorStore;
1234
+ embedder;
1235
+ matcher;
1236
+ sharedStore;
1237
+ sharedVectorStore;
1238
+ graduation;
1239
+ constructor(eventStore, vectorStore, embedder, matcher, sharedOptions) {
1240
+ this.eventStore = eventStore;
1241
+ this.vectorStore = vectorStore;
1242
+ this.embedder = embedder;
1243
+ this.matcher = matcher;
1244
+ this.sharedStore = sharedOptions?.sharedStore;
1245
+ this.sharedVectorStore = sharedOptions?.sharedVectorStore;
1246
+ }
1247
+ /**
1248
+ * Set graduation pipeline for access tracking
1249
+ */
1250
+ setGraduationPipeline(graduation) {
1251
+ this.graduation = graduation;
1252
+ }
1253
+ /**
1254
+ * Set shared stores after construction
1255
+ */
1256
+ setSharedStores(sharedStore, sharedVectorStore) {
1257
+ this.sharedStore = sharedStore;
1258
+ this.sharedVectorStore = sharedVectorStore;
1259
+ }
1260
+ /**
1261
+ * Retrieve relevant memories for a query
1262
+ */
1263
+ async retrieve(query, options = {}) {
1264
+ const opts = { ...DEFAULT_OPTIONS, ...options };
1265
+ const queryEmbedding = await this.embedder.embed(query);
1266
+ const searchResults = await this.vectorStore.search(queryEmbedding.vector, {
1267
+ limit: opts.topK * 2,
1268
+ // Get extra for filtering
1269
+ minScore: opts.minScore,
1270
+ sessionId: opts.sessionId
1271
+ });
1272
+ const matchResult = this.matcher.matchSearchResults(
1273
+ searchResults,
1274
+ (eventId) => this.getEventAgeDays(eventId)
1275
+ );
1276
+ const memories = await this.enrichResults(searchResults.slice(0, opts.topK), opts);
1277
+ const context = this.buildContext(memories, opts.maxTokens);
1278
+ return {
1279
+ memories,
1280
+ matchResult,
1281
+ totalTokens: this.estimateTokens(context),
1282
+ context
1283
+ };
1284
+ }
1285
+ /**
1286
+ * Retrieve with unified search (project + shared)
1287
+ */
1288
+ async retrieveUnified(query, options = {}) {
1289
+ const projectResult = await this.retrieve(query, options);
1290
+ if (!options.includeShared || !this.sharedStore || !this.sharedVectorStore) {
1291
+ return projectResult;
1292
+ }
1293
+ try {
1294
+ const queryEmbedding = await this.embedder.embed(query);
1295
+ const sharedVectorResults = await this.sharedVectorStore.search(
1296
+ queryEmbedding.vector,
1297
+ {
1298
+ limit: options.topK || 5,
1299
+ minScore: options.minScore || 0.7,
1300
+ excludeProjectHash: options.projectHash
1301
+ }
1302
+ );
1303
+ const sharedMemories = [];
1304
+ for (const result of sharedVectorResults) {
1305
+ const entry = await this.sharedStore.get(result.entryId);
1306
+ if (entry) {
1307
+ if (!options.projectHash || entry.sourceProjectHash !== options.projectHash) {
1308
+ sharedMemories.push(entry);
1309
+ await this.sharedStore.recordUsage(entry.entryId);
1310
+ }
1311
+ }
1312
+ }
1313
+ const unifiedContext = this.buildUnifiedContext(projectResult, sharedMemories);
1314
+ return {
1315
+ ...projectResult,
1316
+ context: unifiedContext,
1317
+ totalTokens: this.estimateTokens(unifiedContext),
1318
+ sharedMemories
1319
+ };
1320
+ } catch (error) {
1321
+ console.error("Shared search failed:", error);
1322
+ return projectResult;
1323
+ }
1324
+ }
1325
+ /**
1326
+ * Build unified context combining project and shared memories
1327
+ */
1328
+ buildUnifiedContext(projectResult, sharedMemories) {
1329
+ let context = projectResult.context;
1330
+ if (sharedMemories.length > 0) {
1331
+ context += "\n\n## Cross-Project Knowledge\n\n";
1332
+ for (const memory of sharedMemories.slice(0, 3)) {
1333
+ context += `### ${memory.title}
1334
+ `;
1335
+ if (memory.symptoms.length > 0) {
1336
+ context += `**Symptoms:** ${memory.symptoms.join(", ")}
1337
+ `;
1338
+ }
1339
+ context += `**Root Cause:** ${memory.rootCause}
1340
+ `;
1341
+ context += `**Solution:** ${memory.solution}
1342
+ `;
1343
+ if (memory.technologies && memory.technologies.length > 0) {
1344
+ context += `**Technologies:** ${memory.technologies.join(", ")}
1345
+ `;
1346
+ }
1347
+ context += `_Confidence: ${(memory.confidence * 100).toFixed(0)}%_
1348
+
1349
+ `;
1350
+ }
1351
+ }
1352
+ return context;
1353
+ }
1354
+ /**
1355
+ * Retrieve memories from a specific session
1356
+ */
1357
+ async retrieveFromSession(sessionId) {
1358
+ return this.eventStore.getSessionEvents(sessionId);
1359
+ }
1360
+ /**
1361
+ * Get recent memories across all sessions
1362
+ */
1363
+ async retrieveRecent(limit = 100) {
1364
+ return this.eventStore.getRecentEvents(limit);
1365
+ }
1366
+ /**
1367
+ * Enrich search results with full event data
1368
+ */
1369
+ async enrichResults(results, options) {
1370
+ const memories = [];
1371
+ for (const result of results) {
1372
+ const event = await this.eventStore.getEvent(result.eventId);
1373
+ if (!event)
1374
+ continue;
1375
+ if (this.graduation) {
1376
+ this.graduation.recordAccess(
1377
+ event.id,
1378
+ options.sessionId || "unknown",
1379
+ result.score
1380
+ );
1381
+ }
1382
+ let sessionContext;
1383
+ if (options.includeSessionContext) {
1384
+ sessionContext = await this.getSessionContext(event.sessionId, event.id);
1385
+ }
1386
+ memories.push({
1387
+ event,
1388
+ score: result.score,
1389
+ sessionContext
1390
+ });
1391
+ }
1392
+ return memories;
1393
+ }
1394
+ /**
1395
+ * Get surrounding context from the same session
1396
+ */
1397
+ async getSessionContext(sessionId, eventId) {
1398
+ const sessionEvents = await this.eventStore.getSessionEvents(sessionId);
1399
+ const eventIndex = sessionEvents.findIndex((e) => e.id === eventId);
1400
+ if (eventIndex === -1)
1401
+ return void 0;
1402
+ const start = Math.max(0, eventIndex - 1);
1403
+ const end = Math.min(sessionEvents.length, eventIndex + 2);
1404
+ const contextEvents = sessionEvents.slice(start, end);
1405
+ if (contextEvents.length <= 1)
1406
+ return void 0;
1407
+ return contextEvents.filter((e) => e.id !== eventId).map((e) => `[${e.eventType}]: ${e.content.slice(0, 200)}...`).join("\n");
1408
+ }
1409
+ /**
1410
+ * Build context string from memories (respecting token limit)
1411
+ */
1412
+ buildContext(memories, maxTokens) {
1413
+ const parts = [];
1414
+ let currentTokens = 0;
1415
+ for (const memory of memories) {
1416
+ const memoryText = this.formatMemory(memory);
1417
+ const memoryTokens = this.estimateTokens(memoryText);
1418
+ if (currentTokens + memoryTokens > maxTokens) {
1419
+ break;
1420
+ }
1421
+ parts.push(memoryText);
1422
+ currentTokens += memoryTokens;
1423
+ }
1424
+ if (parts.length === 0) {
1425
+ return "";
1426
+ }
1427
+ return `## Relevant Memories
1428
+
1429
+ ${parts.join("\n\n---\n\n")}`;
1430
+ }
1431
+ /**
1432
+ * Format a single memory for context
1433
+ */
1434
+ formatMemory(memory) {
1435
+ const { event, score, sessionContext } = memory;
1436
+ const date = event.timestamp.toISOString().split("T")[0];
1437
+ let text = `**${event.eventType}** (${date}, score: ${score.toFixed(2)})
1438
+ ${event.content}`;
1439
+ if (sessionContext) {
1440
+ text += `
1441
+
1442
+ _Context:_ ${sessionContext}`;
1443
+ }
1444
+ return text;
1445
+ }
1446
+ /**
1447
+ * Estimate token count (rough approximation)
1448
+ */
1449
+ estimateTokens(text) {
1450
+ return Math.ceil(text.length / 4);
1451
+ }
1452
+ /**
1453
+ * Get event age in days (for recency scoring)
1454
+ */
1455
+ getEventAgeDays(eventId) {
1456
+ return 0;
1457
+ }
1458
+ };
1459
+ function createRetriever(eventStore, vectorStore, embedder, matcher) {
1460
+ return new Retriever(eventStore, vectorStore, embedder, matcher);
1461
+ }
1462
+
1463
+ // src/core/graduation.ts
1464
+ var DEFAULT_CRITERIA = {
1465
+ L0toL1: {
1466
+ minAccessCount: 1,
1467
+ minConfidence: 0.5,
1468
+ minCrossSessionRefs: 0,
1469
+ maxAgeDays: 30
1470
+ },
1471
+ L1toL2: {
1472
+ minAccessCount: 3,
1473
+ minConfidence: 0.7,
1474
+ minCrossSessionRefs: 1,
1475
+ maxAgeDays: 60
1476
+ },
1477
+ L2toL3: {
1478
+ minAccessCount: 5,
1479
+ minConfidence: 0.85,
1480
+ minCrossSessionRefs: 2,
1481
+ maxAgeDays: 90
1482
+ },
1483
+ L3toL4: {
1484
+ minAccessCount: 10,
1485
+ minConfidence: 0.92,
1486
+ minCrossSessionRefs: 3,
1487
+ maxAgeDays: 180
1488
+ }
1489
+ };
1490
+ var GraduationPipeline = class {
1491
+ eventStore;
1492
+ criteria;
1493
+ metrics = /* @__PURE__ */ new Map();
1494
+ constructor(eventStore, criteria = {}) {
1495
+ this.eventStore = eventStore;
1496
+ this.criteria = {
1497
+ L0toL1: { ...DEFAULT_CRITERIA.L0toL1, ...criteria.L0toL1 },
1498
+ L1toL2: { ...DEFAULT_CRITERIA.L1toL2, ...criteria.L1toL2 },
1499
+ L2toL3: { ...DEFAULT_CRITERIA.L2toL3, ...criteria.L2toL3 },
1500
+ L3toL4: { ...DEFAULT_CRITERIA.L3toL4, ...criteria.L3toL4 }
1501
+ };
1502
+ }
1503
+ // Track which sessions have accessed each event
1504
+ sessionAccesses = /* @__PURE__ */ new Map();
1505
+ /**
1506
+ * Record an access to an event (used for graduation scoring)
1507
+ */
1508
+ recordAccess(eventId, fromSessionId, confidence = 1) {
1509
+ const existing = this.metrics.get(eventId);
1510
+ if (!this.sessionAccesses.has(eventId)) {
1511
+ this.sessionAccesses.set(eventId, /* @__PURE__ */ new Set());
1512
+ }
1513
+ const sessions = this.sessionAccesses.get(eventId);
1514
+ const isNewSession = !sessions.has(fromSessionId);
1515
+ sessions.add(fromSessionId);
1516
+ if (existing) {
1517
+ existing.accessCount++;
1518
+ existing.lastAccessed = /* @__PURE__ */ new Date();
1519
+ existing.confidence = Math.max(existing.confidence, confidence);
1520
+ if (isNewSession && sessions.size > 1) {
1521
+ existing.crossSessionRefs = sessions.size - 1;
1522
+ }
1523
+ } else {
1524
+ this.metrics.set(eventId, {
1525
+ eventId,
1526
+ accessCount: 1,
1527
+ lastAccessed: /* @__PURE__ */ new Date(),
1528
+ crossSessionRefs: 0,
1529
+ confidence
1530
+ });
1531
+ }
1532
+ }
1533
+ /**
1534
+ * Evaluate if an event should graduate to the next level
1535
+ */
1536
+ async evaluateGraduation(eventId, currentLevel) {
1537
+ const metrics = this.metrics.get(eventId);
1538
+ if (!metrics) {
1539
+ return {
1540
+ eventId,
1541
+ fromLevel: currentLevel,
1542
+ toLevel: currentLevel,
1543
+ success: false,
1544
+ reason: "No metrics available for event"
1545
+ };
1546
+ }
1547
+ const nextLevel = this.getNextLevel(currentLevel);
1548
+ if (!nextLevel) {
1549
+ return {
1550
+ eventId,
1551
+ fromLevel: currentLevel,
1552
+ toLevel: currentLevel,
1553
+ success: false,
1554
+ reason: "Already at maximum level"
1555
+ };
1556
+ }
1557
+ const criteria = this.getCriteria(currentLevel, nextLevel);
1558
+ const evaluation = this.checkCriteria(metrics, criteria);
1559
+ if (evaluation.passed) {
1560
+ await this.eventStore.updateMemoryLevel(eventId, nextLevel);
1561
+ return {
1562
+ eventId,
1563
+ fromLevel: currentLevel,
1564
+ toLevel: nextLevel,
1565
+ success: true
1566
+ };
1567
+ }
1568
+ return {
1569
+ eventId,
1570
+ fromLevel: currentLevel,
1571
+ toLevel: currentLevel,
1572
+ success: false,
1573
+ reason: evaluation.reason
1574
+ };
1575
+ }
1576
+ /**
1577
+ * Run graduation evaluation for all events at a given level
1578
+ */
1579
+ async graduateBatch(level) {
1580
+ const results = [];
1581
+ for (const [eventId, metrics] of this.metrics) {
1582
+ const result = await this.evaluateGraduation(eventId, level);
1583
+ results.push(result);
1584
+ }
1585
+ return results;
1586
+ }
1587
+ /**
1588
+ * Extract insights from graduated events (L1+)
1589
+ */
1590
+ extractInsights(events) {
1591
+ const insights = [];
1592
+ const patterns = this.detectPatterns(events);
1593
+ for (const pattern of patterns) {
1594
+ insights.push({
1595
+ id: crypto.randomUUID(),
1596
+ insightType: "pattern",
1597
+ content: pattern.description,
1598
+ canonicalKey: pattern.key,
1599
+ confidence: pattern.confidence,
1600
+ sourceEvents: pattern.eventIds,
1601
+ createdAt: /* @__PURE__ */ new Date(),
1602
+ lastUpdated: /* @__PURE__ */ new Date()
1603
+ });
1604
+ }
1605
+ const preferences = this.detectPreferences(events);
1606
+ for (const pref of preferences) {
1607
+ insights.push({
1608
+ id: crypto.randomUUID(),
1609
+ insightType: "preference",
1610
+ content: pref.description,
1611
+ canonicalKey: pref.key,
1612
+ confidence: pref.confidence,
1613
+ sourceEvents: pref.eventIds,
1614
+ createdAt: /* @__PURE__ */ new Date(),
1615
+ lastUpdated: /* @__PURE__ */ new Date()
1616
+ });
1617
+ }
1618
+ return insights;
1619
+ }
1620
+ /**
1621
+ * Get the next level in the graduation pipeline
1622
+ */
1623
+ getNextLevel(current) {
1624
+ const levels = ["L0", "L1", "L2", "L3", "L4"];
1625
+ const currentIndex = levels.indexOf(current);
1626
+ if (currentIndex === -1 || currentIndex >= levels.length - 1) {
1627
+ return null;
1628
+ }
1629
+ return levels[currentIndex + 1];
1630
+ }
1631
+ /**
1632
+ * Get criteria for level transition
1633
+ */
1634
+ getCriteria(from, to) {
1635
+ const key = `${from}to${to}`;
1636
+ return this.criteria[key] || DEFAULT_CRITERIA.L0toL1;
1637
+ }
1638
+ /**
1639
+ * Check if metrics meet criteria
1640
+ */
1641
+ checkCriteria(metrics, criteria) {
1642
+ if (metrics.accessCount < criteria.minAccessCount) {
1643
+ return {
1644
+ passed: false,
1645
+ reason: `Access count ${metrics.accessCount} < ${criteria.minAccessCount}`
1646
+ };
1647
+ }
1648
+ if (metrics.confidence < criteria.minConfidence) {
1649
+ return {
1650
+ passed: false,
1651
+ reason: `Confidence ${metrics.confidence} < ${criteria.minConfidence}`
1652
+ };
1653
+ }
1654
+ if (metrics.crossSessionRefs < criteria.minCrossSessionRefs) {
1655
+ return {
1656
+ passed: false,
1657
+ reason: `Cross-session refs ${metrics.crossSessionRefs} < ${criteria.minCrossSessionRefs}`
1658
+ };
1659
+ }
1660
+ const ageDays = (Date.now() - metrics.lastAccessed.getTime()) / (1e3 * 60 * 60 * 24);
1661
+ if (ageDays > criteria.maxAgeDays) {
1662
+ return {
1663
+ passed: false,
1664
+ reason: `Event too old: ${ageDays.toFixed(1)} days > ${criteria.maxAgeDays}`
1665
+ };
1666
+ }
1667
+ return { passed: true };
1668
+ }
1669
+ /**
1670
+ * Detect patterns in events
1671
+ */
1672
+ detectPatterns(events) {
1673
+ const keyGroups = /* @__PURE__ */ new Map();
1674
+ for (const event of events) {
1675
+ const existing = keyGroups.get(event.canonicalKey) || [];
1676
+ existing.push(event);
1677
+ keyGroups.set(event.canonicalKey, existing);
1678
+ }
1679
+ const patterns = [];
1680
+ for (const [key, groupEvents] of keyGroups) {
1681
+ if (groupEvents.length >= 2) {
1682
+ patterns.push({
1683
+ key,
1684
+ description: `Repeated topic: ${key.slice(0, 50)}`,
1685
+ confidence: Math.min(1, groupEvents.length / 5),
1686
+ eventIds: groupEvents.map((e) => e.id)
1687
+ });
1688
+ }
1689
+ }
1690
+ return patterns;
1691
+ }
1692
+ /**
1693
+ * Detect user preferences from events
1694
+ */
1695
+ detectPreferences(events) {
1696
+ const preferenceKeywords = ["prefer", "like", "want", "always", "never", "favorite"];
1697
+ const preferences = [];
1698
+ for (const event of events) {
1699
+ if (event.eventType !== "user_prompt")
1700
+ continue;
1701
+ const lowerContent = event.content.toLowerCase();
1702
+ for (const keyword of preferenceKeywords) {
1703
+ if (lowerContent.includes(keyword)) {
1704
+ preferences.push({
1705
+ key: `preference_${keyword}_${event.id.slice(0, 8)}`,
1706
+ description: `User preference: ${event.content.slice(0, 100)}`,
1707
+ confidence: 0.7,
1708
+ eventIds: [event.id]
1709
+ });
1710
+ break;
1711
+ }
1712
+ }
1713
+ }
1714
+ return preferences;
1715
+ }
1716
+ /**
1717
+ * Get graduation statistics
1718
+ */
1719
+ async getStats() {
1720
+ return this.eventStore.getLevelStats();
1721
+ }
1722
+ };
1723
+ function createGraduationPipeline(eventStore) {
1724
+ return new GraduationPipeline(eventStore);
1725
+ }
1726
+
1727
+ // src/core/shared-event-store.ts
1728
+ var SharedEventStore = class {
1729
+ constructor(dbPath) {
1730
+ this.dbPath = dbPath;
1731
+ this.db = createDatabase(dbPath);
1732
+ }
1733
+ db;
1734
+ initialized = false;
1735
+ async initialize() {
1736
+ if (this.initialized)
1737
+ return;
1738
+ await dbRun(this.db, `
1739
+ CREATE TABLE IF NOT EXISTS shared_troubleshooting (
1740
+ entry_id VARCHAR PRIMARY KEY,
1741
+ source_project_hash VARCHAR NOT NULL,
1742
+ source_entry_id VARCHAR NOT NULL,
1743
+ title VARCHAR NOT NULL,
1744
+ symptoms JSON NOT NULL,
1745
+ root_cause TEXT NOT NULL,
1746
+ solution TEXT NOT NULL,
1747
+ topics JSON NOT NULL,
1748
+ technologies JSON,
1749
+ confidence REAL NOT NULL DEFAULT 0.8,
1750
+ usage_count INTEGER DEFAULT 0,
1751
+ last_used_at TIMESTAMP,
1752
+ promoted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
1753
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
1754
+ UNIQUE(source_project_hash, source_entry_id)
1755
+ )
1756
+ `);
1757
+ await dbRun(this.db, `
1758
+ CREATE TABLE IF NOT EXISTS shared_best_practices (
1759
+ entry_id VARCHAR PRIMARY KEY,
1760
+ source_project_hash VARCHAR NOT NULL,
1761
+ source_entry_id VARCHAR NOT NULL,
1762
+ title VARCHAR NOT NULL,
1763
+ content_json JSON NOT NULL,
1764
+ topics JSON NOT NULL,
1765
+ confidence REAL NOT NULL DEFAULT 0.8,
1766
+ usage_count INTEGER DEFAULT 0,
1767
+ promoted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
1768
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
1769
+ UNIQUE(source_project_hash, source_entry_id)
1770
+ )
1771
+ `);
1772
+ await dbRun(this.db, `
1773
+ CREATE TABLE IF NOT EXISTS shared_common_errors (
1774
+ entry_id VARCHAR PRIMARY KEY,
1775
+ source_project_hash VARCHAR NOT NULL,
1776
+ source_entry_id VARCHAR NOT NULL,
1777
+ title VARCHAR NOT NULL,
1778
+ error_pattern TEXT NOT NULL,
1779
+ solution TEXT NOT NULL,
1780
+ topics JSON NOT NULL,
1781
+ technologies JSON,
1782
+ confidence REAL NOT NULL DEFAULT 0.8,
1783
+ usage_count INTEGER DEFAULT 0,
1784
+ promoted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
1785
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
1786
+ UNIQUE(source_project_hash, source_entry_id)
1787
+ )
1788
+ `);
1789
+ await dbRun(this.db, `
1790
+ CREATE INDEX IF NOT EXISTS idx_shared_ts_confidence
1791
+ ON shared_troubleshooting(confidence DESC)
1792
+ `);
1793
+ await dbRun(this.db, `
1794
+ CREATE INDEX IF NOT EXISTS idx_shared_ts_usage
1795
+ ON shared_troubleshooting(usage_count DESC)
1796
+ `);
1797
+ await dbRun(this.db, `
1798
+ CREATE INDEX IF NOT EXISTS idx_shared_ts_source
1799
+ ON shared_troubleshooting(source_project_hash)
1800
+ `);
1801
+ this.initialized = true;
1802
+ }
1803
+ getDatabase() {
1804
+ return this.db;
1805
+ }
1806
+ isInitialized() {
1807
+ return this.initialized;
1808
+ }
1809
+ async close() {
1810
+ await dbClose(this.db);
1811
+ this.initialized = false;
1812
+ }
1813
+ };
1814
+ function createSharedEventStore(dbPath) {
1815
+ return new SharedEventStore(dbPath);
1816
+ }
1817
+
1818
+ // src/core/shared-store.ts
1819
+ import { randomUUID as randomUUID2 } from "crypto";
1820
+ var SharedStore = class {
1821
+ constructor(sharedEventStore) {
1822
+ this.sharedEventStore = sharedEventStore;
1823
+ }
1824
+ get db() {
1825
+ return this.sharedEventStore.getDatabase();
1826
+ }
1827
+ /**
1828
+ * Promote a verified troubleshooting entry to shared storage
1829
+ */
1830
+ async promoteEntry(input) {
1831
+ const entryId = randomUUID2();
1832
+ await dbRun(
1833
+ this.db,
1834
+ `INSERT INTO shared_troubleshooting (
1835
+ entry_id, source_project_hash, source_entry_id,
1836
+ title, symptoms, root_cause, solution, topics,
1837
+ technologies, confidence, promoted_at
1838
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
1839
+ ON CONFLICT (source_project_hash, source_entry_id)
1840
+ DO UPDATE SET
1841
+ title = excluded.title,
1842
+ symptoms = excluded.symptoms,
1843
+ root_cause = excluded.root_cause,
1844
+ solution = excluded.solution,
1845
+ topics = excluded.topics,
1846
+ technologies = excluded.technologies,
1847
+ confidence = CASE
1848
+ WHEN excluded.confidence > shared_troubleshooting.confidence
1849
+ THEN excluded.confidence
1850
+ ELSE shared_troubleshooting.confidence
1851
+ END`,
1852
+ [
1853
+ entryId,
1854
+ input.sourceProjectHash,
1855
+ input.sourceEntryId,
1856
+ input.title,
1857
+ JSON.stringify(input.symptoms),
1858
+ input.rootCause,
1859
+ input.solution,
1860
+ JSON.stringify(input.topics),
1861
+ JSON.stringify(input.technologies || []),
1862
+ input.confidence
1863
+ ]
1864
+ );
1865
+ return entryId;
1866
+ }
1867
+ /**
1868
+ * Search troubleshooting entries by text query
1869
+ */
1870
+ async search(query, options) {
1871
+ const topK = options?.topK || 5;
1872
+ const minConfidence = options?.minConfidence || 0.5;
1873
+ const searchPattern = `%${query}%`;
1874
+ const rows = await dbAll(
1875
+ this.db,
1876
+ `SELECT * FROM shared_troubleshooting
1877
+ WHERE (title LIKE ? OR root_cause LIKE ? OR solution LIKE ?)
1878
+ AND confidence >= ?
1879
+ ORDER BY confidence DESC, usage_count DESC
1880
+ LIMIT ?`,
1881
+ [searchPattern, searchPattern, searchPattern, minConfidence, topK]
1882
+ );
1883
+ return rows.map(this.rowToEntry);
1884
+ }
1885
+ /**
1886
+ * Search by topics
1887
+ */
1888
+ async searchByTopics(topics, options) {
1889
+ const topK = options?.topK || 5;
1890
+ if (topics.length === 0) {
1891
+ return [];
1892
+ }
1893
+ const topicConditions = topics.map(() => `topics LIKE ?`).join(" OR ");
1894
+ const topicParams = topics.map((t) => `%"${t}"%`);
1895
+ let query = `SELECT * FROM shared_troubleshooting WHERE (${topicConditions})`;
1896
+ const params = [...topicParams];
1897
+ if (options?.excludeProjectHash) {
1898
+ query += ` AND source_project_hash != ?`;
1899
+ params.push(options.excludeProjectHash);
1900
+ }
1901
+ query += ` ORDER BY confidence DESC, usage_count DESC LIMIT ?`;
1902
+ params.push(topK);
1903
+ const rows = await dbAll(this.db, query, params);
1904
+ return rows.map(this.rowToEntry);
1905
+ }
1906
+ /**
1907
+ * Record usage of a shared entry (for ranking)
1908
+ */
1909
+ async recordUsage(entryId) {
1910
+ await dbRun(
1911
+ this.db,
1912
+ `UPDATE shared_troubleshooting
1913
+ SET usage_count = usage_count + 1,
1914
+ last_used_at = CURRENT_TIMESTAMP
1915
+ WHERE entry_id = ?`,
1916
+ [entryId]
1917
+ );
1918
+ }
1919
+ /**
1920
+ * Get entry by ID
1921
+ */
1922
+ async get(entryId) {
1923
+ const rows = await dbAll(
1924
+ this.db,
1925
+ `SELECT * FROM shared_troubleshooting WHERE entry_id = ?`,
1926
+ [entryId]
1927
+ );
1928
+ if (rows.length === 0)
1929
+ return null;
1930
+ return this.rowToEntry(rows[0]);
1931
+ }
1932
+ /**
1933
+ * Get entry by source (project hash + entry ID)
1934
+ */
1935
+ async getBySource(projectHash, sourceEntryId) {
1936
+ const rows = await dbAll(
1937
+ this.db,
1938
+ `SELECT * FROM shared_troubleshooting
1939
+ WHERE source_project_hash = ? AND source_entry_id = ?`,
1940
+ [projectHash, sourceEntryId]
1941
+ );
1942
+ if (rows.length === 0)
1943
+ return null;
1944
+ return this.rowToEntry(rows[0]);
1945
+ }
1946
+ /**
1947
+ * Check if an entry already exists in shared store
1948
+ */
1949
+ async exists(projectHash, sourceEntryId) {
1950
+ const result = await dbAll(
1951
+ this.db,
1952
+ `SELECT COUNT(*) as count FROM shared_troubleshooting
1953
+ WHERE source_project_hash = ? AND source_entry_id = ?`,
1954
+ [projectHash, sourceEntryId]
1955
+ );
1956
+ return (result[0]?.count || 0) > 0;
1957
+ }
1958
+ /**
1959
+ * Get all entries (with limit for safety)
1960
+ */
1961
+ async getAll(options) {
1962
+ const limit = options?.limit || 100;
1963
+ const rows = await dbAll(
1964
+ this.db,
1965
+ `SELECT * FROM shared_troubleshooting
1966
+ ORDER BY confidence DESC, usage_count DESC
1967
+ LIMIT ?`,
1968
+ [limit]
1969
+ );
1970
+ return rows.map(this.rowToEntry);
1971
+ }
1972
+ /**
1973
+ * Get total count
1974
+ */
1975
+ async count() {
1976
+ const result = await dbAll(
1977
+ this.db,
1978
+ `SELECT COUNT(*) as count FROM shared_troubleshooting`
1979
+ );
1980
+ return result[0]?.count || 0;
1981
+ }
1982
+ /**
1983
+ * Get statistics
1984
+ */
1985
+ async getStats() {
1986
+ const countResult = await dbAll(
1987
+ this.db,
1988
+ `SELECT COUNT(*) as count FROM shared_troubleshooting`
1989
+ );
1990
+ const total = countResult[0]?.count || 0;
1991
+ const avgResult = await dbAll(
1992
+ this.db,
1993
+ `SELECT AVG(confidence) as avg FROM shared_troubleshooting`
1994
+ );
1995
+ const averageConfidence = avgResult[0]?.avg || 0;
1996
+ const usageResult = await dbAll(
1997
+ this.db,
1998
+ `SELECT SUM(usage_count) as total FROM shared_troubleshooting`
1999
+ );
2000
+ const totalUsageCount = usageResult[0]?.total || 0;
2001
+ const entries = await this.getAll({ limit: 1e3 });
2002
+ const topicCounts = {};
2003
+ for (const entry of entries) {
2004
+ for (const topic of entry.topics) {
2005
+ topicCounts[topic] = (topicCounts[topic] || 0) + 1;
2006
+ }
2007
+ }
2008
+ const topTopics = Object.entries(topicCounts).map(([topic, count]) => ({ topic, count })).sort((a, b) => b.count - a.count).slice(0, 10);
2009
+ return { total, averageConfidence, topTopics, totalUsageCount };
2010
+ }
2011
+ /**
2012
+ * Delete an entry
2013
+ */
2014
+ async delete(entryId) {
2015
+ const before = await this.count();
2016
+ await dbRun(
2017
+ this.db,
2018
+ `DELETE FROM shared_troubleshooting WHERE entry_id = ?`,
2019
+ [entryId]
2020
+ );
2021
+ const after = await this.count();
2022
+ return before > after;
2023
+ }
2024
+ rowToEntry(row) {
2025
+ return {
2026
+ entryId: row.entry_id,
2027
+ sourceProjectHash: row.source_project_hash,
2028
+ sourceEntryId: row.source_entry_id,
2029
+ title: row.title,
2030
+ symptoms: JSON.parse(row.symptoms || "[]"),
2031
+ rootCause: row.root_cause,
2032
+ solution: row.solution,
2033
+ topics: JSON.parse(row.topics || "[]"),
2034
+ technologies: JSON.parse(row.technologies || "[]"),
2035
+ confidence: row.confidence,
2036
+ usageCount: row.usage_count || 0,
2037
+ lastUsedAt: row.last_used_at ? toDate(row.last_used_at) : void 0,
2038
+ promotedAt: toDate(row.promoted_at),
2039
+ createdAt: toDate(row.created_at)
2040
+ };
2041
+ }
2042
+ };
2043
+ function createSharedStore(sharedEventStore) {
2044
+ return new SharedStore(sharedEventStore);
2045
+ }
2046
+
2047
+ // src/core/shared-vector-store.ts
2048
+ import * as lancedb2 from "@lancedb/lancedb";
2049
+ var SharedVectorStore = class {
2050
+ constructor(dbPath) {
2051
+ this.dbPath = dbPath;
2052
+ }
2053
+ db = null;
2054
+ table = null;
2055
+ tableName = "shared_knowledge";
2056
+ /**
2057
+ * Initialize LanceDB connection
2058
+ */
2059
+ async initialize() {
2060
+ if (this.db)
2061
+ return;
2062
+ this.db = await lancedb2.connect(this.dbPath);
2063
+ try {
2064
+ const tables = await this.db.tableNames();
2065
+ if (tables.includes(this.tableName)) {
2066
+ this.table = await this.db.openTable(this.tableName);
2067
+ }
2068
+ } catch {
2069
+ this.table = null;
2070
+ }
2071
+ }
2072
+ /**
2073
+ * Add or update a shared vector record
2074
+ */
2075
+ async upsert(record) {
2076
+ await this.initialize();
2077
+ if (!this.db) {
2078
+ throw new Error("Database not initialized");
2079
+ }
2080
+ const data = {
2081
+ id: record.id,
2082
+ entryId: record.entryId,
2083
+ entryType: record.entryType,
2084
+ content: record.content,
2085
+ vector: record.vector,
2086
+ topics: JSON.stringify(record.topics),
2087
+ sourceProjectHash: record.sourceProjectHash || ""
2088
+ };
2089
+ if (!this.table) {
2090
+ this.table = await this.db.createTable(this.tableName, [data]);
2091
+ } else {
2092
+ try {
2093
+ await this.table.delete(`entryId = '${record.entryId}'`);
2094
+ } catch {
2095
+ }
2096
+ await this.table.add([data]);
2097
+ }
2098
+ }
2099
+ /**
2100
+ * Add multiple records in batch
2101
+ */
2102
+ async upsertBatch(records) {
2103
+ if (records.length === 0)
2104
+ return;
2105
+ await this.initialize();
2106
+ if (!this.db) {
2107
+ throw new Error("Database not initialized");
2108
+ }
2109
+ const data = records.map((record) => ({
2110
+ id: record.id,
2111
+ entryId: record.entryId,
2112
+ entryType: record.entryType,
2113
+ content: record.content,
2114
+ vector: record.vector,
2115
+ topics: JSON.stringify(record.topics),
2116
+ sourceProjectHash: record.sourceProjectHash || ""
2117
+ }));
2118
+ if (!this.table) {
2119
+ this.table = await this.db.createTable(this.tableName, data);
2120
+ } else {
2121
+ await this.table.add(data);
2122
+ }
2123
+ }
2124
+ /**
2125
+ * Search for similar vectors
2126
+ */
2127
+ async search(queryVector, options = {}) {
2128
+ await this.initialize();
2129
+ if (!this.table) {
2130
+ return [];
2131
+ }
2132
+ const { limit = 5, minScore = 0.7, excludeProjectHash, entryType } = options;
2133
+ let query = this.table.search(queryVector).distanceType("cosine").limit(limit * 2);
2134
+ const filters = [];
2135
+ if (excludeProjectHash) {
2136
+ filters.push(`sourceProjectHash != '${excludeProjectHash}'`);
2137
+ }
2138
+ if (entryType) {
2139
+ filters.push(`entryType = '${entryType}'`);
2140
+ }
2141
+ if (filters.length > 0) {
2142
+ query = query.where(filters.join(" AND "));
2143
+ }
2144
+ const results = await query.toArray();
2145
+ return results.filter((r) => {
2146
+ const distance = r._distance || 0;
2147
+ const score = 1 - distance / 2;
2148
+ return score >= minScore;
2149
+ }).slice(0, limit).map((r) => {
2150
+ const distance = r._distance || 0;
2151
+ const score = 1 - distance / 2;
2152
+ return {
2153
+ id: r.id,
2154
+ entryId: r.entryId,
2155
+ content: r.content,
2156
+ score,
2157
+ entryType: r.entryType
2158
+ };
2159
+ });
2160
+ }
2161
+ /**
2162
+ * Delete vector by entry ID
2163
+ */
2164
+ async delete(entryId) {
2165
+ if (!this.table)
2166
+ return;
2167
+ await this.table.delete(`entryId = '${entryId}'`);
2168
+ }
2169
+ /**
2170
+ * Get total count
2171
+ */
2172
+ async count() {
2173
+ if (!this.table)
2174
+ return 0;
2175
+ return this.table.countRows();
2176
+ }
2177
+ /**
2178
+ * Check if vector exists for entry
2179
+ */
2180
+ async exists(entryId) {
2181
+ if (!this.table)
2182
+ return false;
2183
+ try {
2184
+ const results = await this.table.search([]).where(`entryId = '${entryId}'`).limit(1).toArray();
2185
+ return results.length > 0;
2186
+ } catch {
2187
+ return false;
2188
+ }
2189
+ }
2190
+ };
2191
+ function createSharedVectorStore(dbPath) {
2192
+ return new SharedVectorStore(dbPath);
2193
+ }
2194
+
2195
+ // src/core/shared-promoter.ts
2196
+ import { randomUUID as randomUUID3 } from "crypto";
2197
+ var SharedPromoter = class {
2198
+ constructor(sharedStore, sharedVectorStore, embedder, config) {
2199
+ this.sharedStore = sharedStore;
2200
+ this.sharedVectorStore = sharedVectorStore;
2201
+ this.embedder = embedder;
2202
+ this.config = config;
2203
+ }
2204
+ /**
2205
+ * Check if an entry is eligible for promotion
2206
+ */
2207
+ isEligibleForPromotion(entry) {
2208
+ if (entry.entryType !== "troubleshooting") {
2209
+ return false;
2210
+ }
2211
+ if (entry.stage !== "verified" && entry.stage !== "certified") {
2212
+ return false;
2213
+ }
2214
+ if (entry.status !== "active") {
2215
+ return false;
2216
+ }
2217
+ return true;
2218
+ }
2219
+ /**
2220
+ * Promote a verified troubleshooting entry to shared storage
2221
+ */
2222
+ async promoteEntry(entry, projectHash) {
2223
+ if (!this.isEligibleForPromotion(entry)) {
2224
+ return {
2225
+ success: false,
2226
+ skipped: true,
2227
+ skipReason: `Entry not eligible: type=${entry.entryType}, stage=${entry.stage}, status=${entry.status}`
2228
+ };
2229
+ }
2230
+ const exists = await this.sharedStore.exists(projectHash, entry.entryId);
2231
+ if (exists) {
2232
+ return {
2233
+ success: true,
2234
+ skipped: true,
2235
+ skipReason: "Entry already exists in shared store"
2236
+ };
2237
+ }
2238
+ try {
2239
+ const content = entry.contentJson;
2240
+ const confidence = this.calculateConfidence(entry);
2241
+ const minConfidence = this.config?.minConfidenceForPromotion ?? 0.8;
2242
+ if (confidence < minConfidence) {
2243
+ return {
2244
+ success: false,
2245
+ skipped: true,
2246
+ skipReason: `Confidence ${confidence} below threshold ${minConfidence}`
2247
+ };
2248
+ }
2249
+ const input = {
2250
+ sourceProjectHash: projectHash,
2251
+ sourceEntryId: entry.entryId,
2252
+ title: entry.title,
2253
+ symptoms: content.symptoms || [],
2254
+ rootCause: content.rootCause || "",
2255
+ solution: content.solution || "",
2256
+ topics: this.extractTopics(entry),
2257
+ technologies: content.technologies || [],
2258
+ confidence
2259
+ };
2260
+ const entryId = await this.sharedStore.promoteEntry(input);
2261
+ const embeddingContent = this.createEmbeddingContent(input);
2262
+ const embedding = await this.embedder.embed(embeddingContent);
2263
+ await this.sharedVectorStore.upsert({
2264
+ id: randomUUID3(),
2265
+ entryId,
2266
+ entryType: "troubleshooting",
2267
+ content: embeddingContent,
2268
+ vector: embedding.vector,
2269
+ topics: input.topics,
2270
+ sourceProjectHash: projectHash
2271
+ });
2272
+ return {
2273
+ success: true,
2274
+ entryId
2275
+ };
2276
+ } catch (error) {
2277
+ return {
2278
+ success: false,
2279
+ error: error instanceof Error ? error.message : String(error)
2280
+ };
2281
+ }
2282
+ }
2283
+ /**
2284
+ * Batch promote multiple entries
2285
+ */
2286
+ async promoteEntries(entries, projectHash) {
2287
+ const results = /* @__PURE__ */ new Map();
2288
+ for (const entry of entries) {
2289
+ const result = await this.promoteEntry(entry, projectHash);
2290
+ results.set(entry.entryId, result);
2291
+ }
2292
+ return results;
2293
+ }
2294
+ /**
2295
+ * Extract topics from entry
2296
+ */
2297
+ extractTopics(entry) {
2298
+ const topics = [];
2299
+ const titleWords = entry.title.toLowerCase().split(/[\s\-_]+/).filter((w) => w.length > 3 && !this.isStopWord(w));
2300
+ topics.push(...titleWords);
2301
+ const content = entry.contentJson;
2302
+ if (content.topics && Array.isArray(content.topics)) {
2303
+ topics.push(...content.topics.map((t) => String(t).toLowerCase()));
2304
+ }
2305
+ if (content.technologies && Array.isArray(content.technologies)) {
2306
+ topics.push(...content.technologies.map((t) => String(t).toLowerCase()));
2307
+ }
2308
+ return [...new Set(topics)];
2309
+ }
2310
+ /**
2311
+ * Check if word is a stop word
2312
+ */
2313
+ isStopWord(word) {
2314
+ const stopWords = /* @__PURE__ */ new Set([
2315
+ "the",
2316
+ "and",
2317
+ "for",
2318
+ "with",
2319
+ "this",
2320
+ "that",
2321
+ "from",
2322
+ "have",
2323
+ "been",
2324
+ "were",
2325
+ "are",
2326
+ "was",
2327
+ "had",
2328
+ "has",
2329
+ "will",
2330
+ "would",
2331
+ "could",
2332
+ "should",
2333
+ "when",
2334
+ "where",
2335
+ "what",
2336
+ "which",
2337
+ "while",
2338
+ "error",
2339
+ "problem",
2340
+ "issue"
2341
+ ]);
2342
+ return stopWords.has(word);
2343
+ }
2344
+ /**
2345
+ * Calculate confidence score for entry
2346
+ */
2347
+ calculateConfidence(entry) {
2348
+ let confidence = 0.8;
2349
+ if (entry.stage === "certified") {
2350
+ confidence = 0.95;
2351
+ }
2352
+ return Math.min(confidence, 1);
2353
+ }
2354
+ /**
2355
+ * Create embedding content from input
2356
+ */
2357
+ createEmbeddingContent(input) {
2358
+ const parts = [];
2359
+ parts.push(`Problem: ${input.title}`);
2360
+ if (input.symptoms.length > 0) {
2361
+ parts.push(`Symptoms: ${input.symptoms.join(", ")}`);
2362
+ }
2363
+ if (input.rootCause) {
2364
+ parts.push(`Root Cause: ${input.rootCause}`);
2365
+ }
2366
+ if (input.solution) {
2367
+ parts.push(`Solution: ${input.solution}`);
2368
+ }
2369
+ if (input.technologies && input.technologies.length > 0) {
2370
+ parts.push(`Technologies: ${input.technologies.join(", ")}`);
2371
+ }
2372
+ return parts.join("\n");
2373
+ }
2374
+ };
2375
+ function createSharedPromoter(sharedStore, sharedVectorStore, embedder, config) {
2376
+ return new SharedPromoter(sharedStore, sharedVectorStore, embedder, config);
2377
+ }
2378
+
2379
+ // src/core/metadata-extractor.ts
2380
+ function createToolObservationEmbedding(toolName, metadata, success) {
2381
+ const parts = [];
2382
+ parts.push(`Tool: ${toolName}`);
2383
+ if (metadata.filePath) {
2384
+ parts.push(`File: ${metadata.filePath}`);
2385
+ }
2386
+ if (metadata.command) {
2387
+ parts.push(`Command: ${metadata.command}`);
2388
+ }
2389
+ if (metadata.pattern) {
2390
+ parts.push(`Pattern: ${metadata.pattern}`);
2391
+ }
2392
+ if (metadata.url) {
2393
+ try {
2394
+ const url = new URL(metadata.url);
2395
+ parts.push(`URL: ${url.hostname}`);
2396
+ } catch {
2397
+ }
2398
+ }
2399
+ parts.push(`Result: ${success ? "Success" : "Failed"}`);
2400
+ return parts.join("\n");
2401
+ }
2402
+
2403
+ // src/core/working-set-store.ts
2404
+ import { randomUUID as randomUUID4 } from "crypto";
2405
+ var WorkingSetStore = class {
2406
+ constructor(eventStore, config) {
2407
+ this.eventStore = eventStore;
2408
+ this.config = config;
2409
+ }
2410
+ get db() {
2411
+ return this.eventStore.getDatabase();
2412
+ }
2413
+ /**
2414
+ * Add an event to the working set
2415
+ */
2416
+ async add(eventId, relevanceScore = 1, topics) {
2417
+ const expiresAt = new Date(
2418
+ Date.now() + this.config.workingSet.timeWindowHours * 60 * 60 * 1e3
2419
+ );
2420
+ await dbRun(
2421
+ this.db,
2422
+ `INSERT OR REPLACE INTO working_set (id, event_id, added_at, relevance_score, topics, expires_at)
2423
+ VALUES (?, ?, CURRENT_TIMESTAMP, ?, ?, ?)`,
2424
+ [
2425
+ randomUUID4(),
2426
+ eventId,
2427
+ relevanceScore,
2428
+ JSON.stringify(topics || []),
2429
+ expiresAt.toISOString()
2430
+ ]
2431
+ );
2432
+ await this.enforceLimit();
2433
+ }
2434
+ /**
2435
+ * Get the current working set
2436
+ */
2437
+ async get() {
2438
+ await this.cleanup();
2439
+ const rows = await dbAll(
2440
+ this.db,
2441
+ `SELECT ws.*, e.*
2442
+ FROM working_set ws
2443
+ JOIN events e ON ws.event_id = e.id
2444
+ ORDER BY ws.relevance_score DESC, ws.added_at DESC
2445
+ LIMIT ?`,
2446
+ [this.config.workingSet.maxEvents]
2447
+ );
2448
+ const events = rows.map((row) => ({
2449
+ id: row.id,
2450
+ eventType: row.event_type,
2451
+ sessionId: row.session_id,
2452
+ timestamp: toDate(row.timestamp),
2453
+ content: row.content,
2454
+ canonicalKey: row.canonical_key,
2455
+ dedupeKey: row.dedupe_key,
2456
+ metadata: row.metadata ? JSON.parse(row.metadata) : void 0
2457
+ }));
2458
+ return {
2459
+ recentEvents: events,
2460
+ lastActivity: events.length > 0 ? events[0].timestamp : /* @__PURE__ */ new Date(),
2461
+ continuityScore: await this.calculateContinuityScore()
2462
+ };
2463
+ }
2464
+ /**
2465
+ * Get working set items (metadata only)
2466
+ */
2467
+ async getItems() {
2468
+ const rows = await dbAll(
2469
+ this.db,
2470
+ `SELECT * FROM working_set ORDER BY relevance_score DESC, added_at DESC`
2471
+ );
2472
+ return rows.map((row) => ({
2473
+ id: row.id,
2474
+ eventId: row.event_id,
2475
+ addedAt: toDate(row.added_at),
2476
+ relevanceScore: row.relevance_score,
2477
+ topics: row.topics ? JSON.parse(row.topics) : void 0,
2478
+ expiresAt: toDate(row.expires_at)
2479
+ }));
2480
+ }
2481
+ /**
2482
+ * Update relevance score for an event
2483
+ */
2484
+ async updateRelevance(eventId, score) {
2485
+ await dbRun(
2486
+ this.db,
2487
+ `UPDATE working_set SET relevance_score = ? WHERE event_id = ?`,
2488
+ [score, eventId]
2489
+ );
2490
+ }
2491
+ /**
2492
+ * Prune specific events from working set (after consolidation)
2493
+ */
2494
+ async prune(eventIds) {
2495
+ if (eventIds.length === 0)
2496
+ return;
2497
+ const placeholders = eventIds.map(() => "?").join(",");
2498
+ await dbRun(
2499
+ this.db,
2500
+ `DELETE FROM working_set WHERE event_id IN (${placeholders})`,
2501
+ eventIds
2502
+ );
2503
+ }
2504
+ /**
2505
+ * Get the count of items in working set
2506
+ */
2507
+ async count() {
2508
+ const result = await dbAll(
2509
+ this.db,
2510
+ `SELECT COUNT(*) as count FROM working_set`
2511
+ );
2512
+ return result[0]?.count || 0;
2513
+ }
2514
+ /**
2515
+ * Clear the entire working set
2516
+ */
2517
+ async clear() {
2518
+ await dbRun(this.db, `DELETE FROM working_set`);
2519
+ }
2520
+ /**
2521
+ * Check if an event is in the working set
2522
+ */
2523
+ async contains(eventId) {
2524
+ const result = await dbAll(
2525
+ this.db,
2526
+ `SELECT COUNT(*) as count FROM working_set WHERE event_id = ?`,
2527
+ [eventId]
2528
+ );
2529
+ return (result[0]?.count || 0) > 0;
2530
+ }
2531
+ /**
2532
+ * Refresh expiration for an event (rehears al - keep relevant items longer)
2533
+ */
2534
+ async refresh(eventId) {
2535
+ const newExpiresAt = new Date(
2536
+ Date.now() + this.config.workingSet.timeWindowHours * 60 * 60 * 1e3
2537
+ );
2538
+ await dbRun(
2539
+ this.db,
2540
+ `UPDATE working_set SET expires_at = ? WHERE event_id = ?`,
2541
+ [newExpiresAt.toISOString(), eventId]
2542
+ );
2543
+ }
2544
+ /**
2545
+ * Clean up expired items
2546
+ */
2547
+ async cleanup() {
2548
+ await dbRun(
2549
+ this.db,
2550
+ `DELETE FROM working_set WHERE expires_at < datetime('now')`
2551
+ );
2552
+ }
2553
+ /**
2554
+ * Enforce the maximum size limit
2555
+ * Removes lowest relevance items when over limit
2556
+ */
2557
+ async enforceLimit() {
2558
+ const maxEvents = this.config.workingSet.maxEvents;
2559
+ const keepIds = await dbAll(
2560
+ this.db,
2561
+ `SELECT id FROM working_set
2562
+ ORDER BY relevance_score DESC, added_at DESC
2563
+ LIMIT ?`,
2564
+ [maxEvents]
2565
+ );
2566
+ if (keepIds.length === 0)
2567
+ return;
2568
+ const keepIdList = keepIds.map((r) => r.id);
2569
+ const placeholders = keepIdList.map(() => "?").join(",");
2570
+ await dbRun(
2571
+ this.db,
2572
+ `DELETE FROM working_set WHERE id NOT IN (${placeholders})`,
2573
+ keepIdList
2574
+ );
2575
+ }
2576
+ /**
2577
+ * Calculate continuity score based on recent context transitions
2578
+ */
2579
+ async calculateContinuityScore() {
2580
+ const result = await dbAll(
2581
+ this.db,
2582
+ `SELECT AVG(continuity_score) as avg_score
2583
+ FROM continuity_log
2584
+ WHERE created_at > datetime('now', '-1 hour')`
2585
+ );
2586
+ return result[0]?.avg_score ?? 0.5;
2587
+ }
2588
+ /**
2589
+ * Get topics from current working set for context matching
2590
+ */
2591
+ async getActiveTopics() {
2592
+ const rows = await dbAll(
2593
+ this.db,
2594
+ `SELECT topics FROM working_set WHERE topics IS NOT NULL`
2595
+ );
2596
+ const allTopics = /* @__PURE__ */ new Set();
2597
+ for (const row of rows) {
2598
+ const topics = JSON.parse(row.topics);
2599
+ topics.forEach((t) => allTopics.add(t));
2600
+ }
2601
+ return Array.from(allTopics);
2602
+ }
2603
+ };
2604
+ function createWorkingSetStore(eventStore, config) {
2605
+ return new WorkingSetStore(eventStore, config);
2606
+ }
2607
+
2608
+ // src/core/consolidated-store.ts
2609
+ import { randomUUID as randomUUID5 } from "crypto";
2610
+ var ConsolidatedStore = class {
2611
+ constructor(eventStore) {
2612
+ this.eventStore = eventStore;
2613
+ }
2614
+ get db() {
2615
+ return this.eventStore.getDatabase();
2616
+ }
2617
+ /**
2618
+ * Create a new consolidated memory
2619
+ */
2620
+ async create(input) {
2621
+ const memoryId = randomUUID5();
2622
+ await dbRun(
2623
+ this.db,
2624
+ `INSERT INTO consolidated_memories
2625
+ (memory_id, summary, topics, source_events, confidence, created_at)
2626
+ VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
2627
+ [
2628
+ memoryId,
2629
+ input.summary,
2630
+ JSON.stringify(input.topics),
2631
+ JSON.stringify(input.sourceEvents),
2632
+ input.confidence
2633
+ ]
2634
+ );
2635
+ return memoryId;
2636
+ }
2637
+ /**
2638
+ * Get a consolidated memory by ID
2639
+ */
2640
+ async get(memoryId) {
2641
+ const rows = await dbAll(
2642
+ this.db,
2643
+ `SELECT * FROM consolidated_memories WHERE memory_id = ?`,
2644
+ [memoryId]
2645
+ );
2646
+ if (rows.length === 0)
2647
+ return null;
2648
+ return this.rowToMemory(rows[0]);
2649
+ }
2650
+ /**
2651
+ * Search consolidated memories by query (simple text search)
2652
+ */
2653
+ async search(query, options) {
2654
+ const topK = options?.topK || 5;
2655
+ const rows = await dbAll(
2656
+ this.db,
2657
+ `SELECT * FROM consolidated_memories
2658
+ WHERE summary LIKE ?
2659
+ ORDER BY confidence DESC
2660
+ LIMIT ?`,
2661
+ [`%${query}%`, topK]
2662
+ );
2663
+ return rows.map(this.rowToMemory);
2664
+ }
2665
+ /**
2666
+ * Search by topics
2667
+ */
2668
+ async searchByTopics(topics, options) {
2669
+ const topK = options?.topK || 5;
2670
+ const topicConditions = topics.map(() => `topics LIKE ?`).join(" OR ");
2671
+ const topicParams = topics.map((t) => `%"${t}"%`);
2672
+ const rows = await dbAll(
2673
+ this.db,
2674
+ `SELECT * FROM consolidated_memories
2675
+ WHERE ${topicConditions}
2676
+ ORDER BY confidence DESC
2677
+ LIMIT ?`,
2678
+ [...topicParams, topK]
2679
+ );
2680
+ return rows.map(this.rowToMemory);
2681
+ }
2682
+ /**
2683
+ * Get all consolidated memories ordered by confidence
2684
+ */
2685
+ async getAll(options) {
2686
+ const limit = options?.limit || 100;
2687
+ const rows = await dbAll(
2688
+ this.db,
2689
+ `SELECT * FROM consolidated_memories
2690
+ ORDER BY confidence DESC, created_at DESC
2691
+ LIMIT ?`,
2692
+ [limit]
2693
+ );
2694
+ return rows.map(this.rowToMemory);
2695
+ }
2696
+ /**
2697
+ * Get recently created memories
2698
+ */
2699
+ async getRecent(options) {
2700
+ const limit = options?.limit || 10;
2701
+ const hours = options?.hours || 24;
2702
+ const rows = await dbAll(
2703
+ this.db,
2704
+ `SELECT * FROM consolidated_memories
2705
+ WHERE created_at > datetime('now', '-${hours} hours')
2706
+ ORDER BY created_at DESC
2707
+ LIMIT ?`,
2708
+ [limit]
2709
+ );
2710
+ return rows.map(this.rowToMemory);
2711
+ }
2712
+ /**
2713
+ * Mark a memory as accessed (tracks usage for importance scoring)
2714
+ */
2715
+ async markAccessed(memoryId) {
2716
+ await dbRun(
2717
+ this.db,
2718
+ `UPDATE consolidated_memories
2719
+ SET accessed_at = CURRENT_TIMESTAMP,
2720
+ access_count = access_count + 1
2721
+ WHERE memory_id = ?`,
2722
+ [memoryId]
2723
+ );
2724
+ }
2725
+ /**
2726
+ * Update confidence score for a memory
2727
+ */
2728
+ async updateConfidence(memoryId, confidence) {
2729
+ await dbRun(
2730
+ this.db,
2731
+ `UPDATE consolidated_memories
2732
+ SET confidence = ?
2733
+ WHERE memory_id = ?`,
2734
+ [confidence, memoryId]
2735
+ );
2736
+ }
2737
+ /**
2738
+ * Delete a consolidated memory
2739
+ */
2740
+ async delete(memoryId) {
2741
+ await dbRun(
2742
+ this.db,
2743
+ `DELETE FROM consolidated_memories WHERE memory_id = ?`,
2744
+ [memoryId]
2745
+ );
2746
+ }
2747
+ /**
2748
+ * Get count of consolidated memories
2749
+ */
2750
+ async count() {
2751
+ const result = await dbAll(
2752
+ this.db,
2753
+ `SELECT COUNT(*) as count FROM consolidated_memories`
2754
+ );
2755
+ return result[0]?.count || 0;
2756
+ }
2757
+ /**
2758
+ * Get most accessed memories (for importance scoring)
2759
+ */
2760
+ async getMostAccessed(limit = 10) {
2761
+ const rows = await dbAll(
2762
+ this.db,
2763
+ `SELECT * FROM consolidated_memories
2764
+ WHERE access_count > 0
2765
+ ORDER BY access_count DESC
2766
+ LIMIT ?`,
2767
+ [limit]
2768
+ );
2769
+ return rows.map(this.rowToMemory);
2770
+ }
2771
+ /**
2772
+ * Get statistics about consolidated memories
2773
+ */
2774
+ async getStats() {
2775
+ const total = await this.count();
2776
+ const avgResult = await dbAll(
2777
+ this.db,
2778
+ `SELECT AVG(confidence) as avg FROM consolidated_memories`
2779
+ );
2780
+ const averageConfidence = avgResult[0]?.avg || 0;
2781
+ const recentResult = await dbAll(
2782
+ this.db,
2783
+ `SELECT COUNT(*) as count FROM consolidated_memories
2784
+ WHERE created_at > datetime('now', '-24 hours')`
2785
+ );
2786
+ const recentCount = recentResult[0]?.count || 0;
2787
+ const allMemories = await this.getAll({ limit: 1e3 });
2788
+ const topicCounts = {};
2789
+ for (const memory of allMemories) {
2790
+ for (const topic of memory.topics) {
2791
+ topicCounts[topic] = (topicCounts[topic] || 0) + 1;
2792
+ }
2793
+ }
2794
+ return {
2795
+ total,
2796
+ averageConfidence,
2797
+ topicCounts,
2798
+ recentCount
2799
+ };
2800
+ }
2801
+ /**
2802
+ * Check if source events are already consolidated
2803
+ */
2804
+ async isAlreadyConsolidated(eventIds) {
2805
+ for (const eventId of eventIds) {
2806
+ const result = await dbAll(
2807
+ this.db,
2808
+ `SELECT COUNT(*) as count FROM consolidated_memories
2809
+ WHERE source_events LIKE ?`,
2810
+ [`%"${eventId}"%`]
2811
+ );
2812
+ if ((result[0]?.count || 0) > 0)
2813
+ return true;
2814
+ }
2815
+ return false;
2816
+ }
2817
+ /**
2818
+ * Get the last consolidation time
2819
+ */
2820
+ async getLastConsolidationTime() {
2821
+ const result = await dbAll(
2822
+ this.db,
2823
+ `SELECT created_at FROM consolidated_memories
2824
+ ORDER BY created_at DESC
2825
+ LIMIT 1`
2826
+ );
2827
+ if (result.length === 0)
2828
+ return null;
2829
+ return new Date(result[0].created_at);
2830
+ }
2831
+ /**
2832
+ * Convert database row to ConsolidatedMemory
2833
+ */
2834
+ rowToMemory(row) {
2835
+ return {
2836
+ memoryId: row.memory_id,
2837
+ summary: row.summary,
2838
+ topics: JSON.parse(row.topics || "[]"),
2839
+ sourceEvents: JSON.parse(row.source_events || "[]"),
2840
+ confidence: row.confidence,
2841
+ createdAt: toDate(row.created_at),
2842
+ accessedAt: row.accessed_at ? toDate(row.accessed_at) : void 0,
2843
+ accessCount: row.access_count || 0
2844
+ };
2845
+ }
2846
+ };
2847
+ function createConsolidatedStore(eventStore) {
2848
+ return new ConsolidatedStore(eventStore);
2849
+ }
2850
+
2851
+ // src/core/consolidation-worker.ts
2852
+ var ConsolidationWorker = class {
2853
+ constructor(workingSetStore, consolidatedStore, config) {
2854
+ this.workingSetStore = workingSetStore;
2855
+ this.consolidatedStore = consolidatedStore;
2856
+ this.config = config;
2857
+ }
2858
+ running = false;
2859
+ timeout = null;
2860
+ lastActivity = /* @__PURE__ */ new Date();
2861
+ /**
2862
+ * Start the consolidation worker
2863
+ */
2864
+ start() {
2865
+ if (this.running)
2866
+ return;
2867
+ this.running = true;
2868
+ this.scheduleNext();
2869
+ }
2870
+ /**
2871
+ * Stop the consolidation worker
2872
+ */
2873
+ stop() {
2874
+ this.running = false;
2875
+ if (this.timeout) {
2876
+ clearTimeout(this.timeout);
2877
+ this.timeout = null;
2878
+ }
2879
+ }
2880
+ /**
2881
+ * Record activity (resets idle timer)
2882
+ */
2883
+ recordActivity() {
2884
+ this.lastActivity = /* @__PURE__ */ new Date();
2885
+ }
2886
+ /**
2887
+ * Check if currently running
2888
+ */
2889
+ isRunning() {
2890
+ return this.running;
2891
+ }
2892
+ /**
2893
+ * Force a consolidation run (manual trigger)
2894
+ */
2895
+ async forceRun() {
2896
+ return await this.consolidate();
2897
+ }
2898
+ /**
2899
+ * Schedule the next consolidation check
2900
+ */
2901
+ scheduleNext() {
2902
+ if (!this.running)
2903
+ return;
2904
+ this.timeout = setTimeout(
2905
+ () => this.run(),
2906
+ this.config.consolidation.triggerIntervalMs
2907
+ );
2908
+ }
2909
+ /**
2910
+ * Run consolidation check
2911
+ */
2912
+ async run() {
2913
+ if (!this.running)
2914
+ return;
2915
+ try {
2916
+ await this.checkAndConsolidate();
2917
+ } catch (error) {
2918
+ console.error("Consolidation error:", error);
2919
+ }
2920
+ this.scheduleNext();
2921
+ }
2922
+ /**
2923
+ * Check conditions and consolidate if needed
2924
+ */
2925
+ async checkAndConsolidate() {
2926
+ const workingSet = await this.workingSetStore.get();
2927
+ if (!this.shouldConsolidate(workingSet)) {
2928
+ return;
2929
+ }
2930
+ await this.consolidate();
2931
+ }
2932
+ /**
2933
+ * Perform consolidation
2934
+ */
2935
+ async consolidate() {
2936
+ const workingSet = await this.workingSetStore.get();
2937
+ if (workingSet.recentEvents.length < 3) {
2938
+ return 0;
2939
+ }
2940
+ const groups = this.groupByTopic(workingSet.recentEvents);
2941
+ let consolidatedCount = 0;
2942
+ for (const group of groups) {
2943
+ if (group.events.length < 3)
2944
+ continue;
2945
+ const eventIds = group.events.map((e) => e.id);
2946
+ const alreadyConsolidated = await this.consolidatedStore.isAlreadyConsolidated(eventIds);
2947
+ if (alreadyConsolidated)
2948
+ continue;
2949
+ const summary = await this.summarize(group);
2950
+ await this.consolidatedStore.create({
2951
+ summary,
2952
+ topics: group.topics,
2953
+ sourceEvents: eventIds,
2954
+ confidence: this.calculateConfidence(group)
2955
+ });
2956
+ consolidatedCount++;
2957
+ }
2958
+ if (consolidatedCount > 0) {
2959
+ const consolidatedEventIds = groups.filter((g) => g.events.length >= 3).flatMap((g) => g.events.map((e) => e.id));
2960
+ const oldEventIds = consolidatedEventIds.filter((id) => {
2961
+ const event = workingSet.recentEvents.find((e) => e.id === id);
2962
+ if (!event)
2963
+ return false;
2964
+ const ageHours = (Date.now() - event.timestamp.getTime()) / (1e3 * 60 * 60);
2965
+ return ageHours > this.config.workingSet.timeWindowHours / 2;
2966
+ });
2967
+ if (oldEventIds.length > 0) {
2968
+ await this.workingSetStore.prune(oldEventIds);
2969
+ }
2970
+ }
2971
+ return consolidatedCount;
2972
+ }
2973
+ /**
2974
+ * Check if consolidation should run
2975
+ */
2976
+ shouldConsolidate(workingSet) {
2977
+ if (workingSet.recentEvents.length >= this.config.consolidation.triggerEventCount) {
2978
+ return true;
2979
+ }
2980
+ const idleTime = Date.now() - this.lastActivity.getTime();
2981
+ if (idleTime >= this.config.consolidation.triggerIdleMs) {
2982
+ return true;
2983
+ }
2984
+ return false;
2985
+ }
2986
+ /**
2987
+ * Group events by topic using simple keyword extraction
2988
+ */
2989
+ groupByTopic(events) {
2990
+ const groups = /* @__PURE__ */ new Map();
2991
+ for (const event of events) {
2992
+ const topics = this.extractTopics(event.content);
2993
+ for (const topic of topics) {
2994
+ if (!groups.has(topic)) {
2995
+ groups.set(topic, { topics: [topic], events: [] });
2996
+ }
2997
+ const group = groups.get(topic);
2998
+ if (!group.events.find((e) => e.id === event.id)) {
2999
+ group.events.push(event);
3000
+ }
3001
+ }
3002
+ }
3003
+ const mergedGroups = this.mergeOverlappingGroups(Array.from(groups.values()));
3004
+ return mergedGroups;
3005
+ }
3006
+ /**
3007
+ * Extract topics from content using simple keyword extraction
3008
+ */
3009
+ extractTopics(content) {
3010
+ const topics = [];
3011
+ const codePatterns = [
3012
+ /\b(function|class|interface|type|const|let|var)\s+(\w+)/gi,
3013
+ /\b(import|export)\s+.*?from\s+['"]([^'"]+)['"]/gi,
3014
+ /\bfile[:\s]+([^\s,]+)/gi
3015
+ ];
3016
+ for (const pattern of codePatterns) {
3017
+ let match;
3018
+ while ((match = pattern.exec(content)) !== null) {
3019
+ const keyword = match[2] || match[1];
3020
+ if (keyword && keyword.length > 2) {
3021
+ topics.push(keyword.toLowerCase());
3022
+ }
3023
+ }
3024
+ }
3025
+ const commonTerms = [
3026
+ "bug",
3027
+ "fix",
3028
+ "error",
3029
+ "issue",
3030
+ "feature",
3031
+ "test",
3032
+ "refactor",
3033
+ "implement",
3034
+ "add",
3035
+ "remove",
3036
+ "update",
3037
+ "change",
3038
+ "modify",
3039
+ "create",
3040
+ "delete"
3041
+ ];
3042
+ const contentLower = content.toLowerCase();
3043
+ for (const term of commonTerms) {
3044
+ if (contentLower.includes(term)) {
3045
+ topics.push(term);
3046
+ }
3047
+ }
3048
+ return [...new Set(topics)].slice(0, 5);
3049
+ }
3050
+ /**
3051
+ * Merge groups that have significant event overlap
3052
+ */
3053
+ mergeOverlappingGroups(groups) {
3054
+ const merged = [];
3055
+ for (const group of groups) {
3056
+ let foundMerge = false;
3057
+ for (const existing of merged) {
3058
+ const overlap = group.events.filter(
3059
+ (e) => existing.events.some((ex) => ex.id === e.id)
3060
+ );
3061
+ if (overlap.length > group.events.length / 2) {
3062
+ existing.topics = [.../* @__PURE__ */ new Set([...existing.topics, ...group.topics])];
3063
+ for (const event of group.events) {
3064
+ if (!existing.events.find((e) => e.id === event.id)) {
3065
+ existing.events.push(event);
3066
+ }
3067
+ }
3068
+ foundMerge = true;
3069
+ break;
3070
+ }
3071
+ }
3072
+ if (!foundMerge) {
3073
+ merged.push(group);
3074
+ }
3075
+ }
3076
+ return merged;
3077
+ }
3078
+ /**
3079
+ * Generate summary for a group of events
3080
+ * Rule-based extraction (no LLM by default)
3081
+ */
3082
+ async summarize(group) {
3083
+ if (this.config.consolidation.useLLMSummarization) {
3084
+ return this.ruleBasedSummary(group);
3085
+ }
3086
+ return this.ruleBasedSummary(group);
3087
+ }
3088
+ /**
3089
+ * Rule-based summary generation
3090
+ */
3091
+ ruleBasedSummary(group) {
3092
+ const keyPoints = [];
3093
+ for (const event of group.events.slice(0, 10)) {
3094
+ const keyPoint = this.extractKeyPoint(event.content);
3095
+ if (keyPoint) {
3096
+ keyPoints.push(keyPoint);
3097
+ }
3098
+ }
3099
+ const topicsStr = group.topics.slice(0, 3).join(", ");
3100
+ const summary = [
3101
+ `Topics: ${topicsStr}`,
3102
+ "",
3103
+ "Key points:",
3104
+ ...keyPoints.map((kp) => `- ${kp}`)
3105
+ ].join("\n");
3106
+ return summary;
3107
+ }
3108
+ /**
3109
+ * Extract key point from content
3110
+ */
3111
+ extractKeyPoint(content) {
3112
+ const sentences = content.split(/[.!?\n]+/).filter((s) => s.trim().length > 10);
3113
+ if (sentences.length === 0)
3114
+ return null;
3115
+ const firstSentence = sentences[0].trim();
3116
+ if (firstSentence.length > 100) {
3117
+ return firstSentence.slice(0, 100) + "...";
3118
+ }
3119
+ return firstSentence;
3120
+ }
3121
+ /**
3122
+ * Calculate confidence score for a group
3123
+ */
3124
+ calculateConfidence(group) {
3125
+ const eventScore = Math.min(group.events.length / 10, 1);
3126
+ const timeScore = this.calculateTimeProximity(group.events);
3127
+ const topicScore = Math.min(3 / group.topics.length, 1);
3128
+ return eventScore * 0.4 + timeScore * 0.4 + topicScore * 0.2;
3129
+ }
3130
+ /**
3131
+ * Calculate time proximity score
3132
+ */
3133
+ calculateTimeProximity(events) {
3134
+ if (events.length < 2)
3135
+ return 1;
3136
+ const timestamps = events.map((e) => e.timestamp.getTime()).sort((a, b) => a - b);
3137
+ const timeSpan = timestamps[timestamps.length - 1] - timestamps[0];
3138
+ const avgGap = timeSpan / (events.length - 1);
3139
+ const hourInMs = 60 * 60 * 1e3;
3140
+ return Math.max(0, 1 - avgGap / (24 * hourInMs));
3141
+ }
3142
+ };
3143
+ function createConsolidationWorker(workingSetStore, consolidatedStore, config) {
3144
+ return new ConsolidationWorker(workingSetStore, consolidatedStore, config);
3145
+ }
3146
+
3147
+ // src/core/continuity-manager.ts
3148
+ import { randomUUID as randomUUID6 } from "crypto";
3149
+ var ContinuityManager = class {
3150
+ constructor(eventStore, config) {
3151
+ this.eventStore = eventStore;
3152
+ this.config = config;
3153
+ }
3154
+ lastContext = null;
3155
+ get db() {
3156
+ return this.eventStore.getDatabase();
3157
+ }
3158
+ /**
3159
+ * Calculate continuity score between current and previous context
3160
+ */
3161
+ async calculateScore(currentContext, previousContext) {
3162
+ const prev = previousContext || this.lastContext;
3163
+ if (!prev) {
3164
+ this.lastContext = currentContext;
3165
+ return { score: 0.5, transitionType: "break" };
3166
+ }
3167
+ let score = 0;
3168
+ const topicOverlap = this.calculateOverlap(
3169
+ currentContext.topics,
3170
+ prev.topics
3171
+ );
3172
+ score += topicOverlap * 0.3;
3173
+ const fileOverlap = this.calculateOverlap(
3174
+ currentContext.files,
3175
+ prev.files
3176
+ );
3177
+ score += fileOverlap * 0.2;
3178
+ const timeDiff = currentContext.timestamp - prev.timestamp;
3179
+ const decayHours = this.config.continuity.topicDecayHours;
3180
+ const timeScore = Math.exp(-timeDiff / (decayHours * 36e5));
3181
+ score += timeScore * 0.3;
3182
+ const entityOverlap = this.calculateOverlap(
3183
+ currentContext.entities,
3184
+ prev.entities
3185
+ );
3186
+ score += entityOverlap * 0.2;
3187
+ const transitionType = this.determineTransitionType(score);
3188
+ await this.logTransition(currentContext, prev, score, transitionType);
3189
+ this.lastContext = currentContext;
3190
+ return { score, transitionType };
3191
+ }
3192
+ /**
3193
+ * Create a context snapshot from current state
3194
+ */
3195
+ createSnapshot(id, content, metadata) {
3196
+ return {
3197
+ id,
3198
+ timestamp: Date.now(),
3199
+ topics: this.extractTopics(content),
3200
+ files: metadata?.files || this.extractFiles(content),
3201
+ entities: metadata?.entities || this.extractEntities(content)
3202
+ };
3203
+ }
3204
+ /**
3205
+ * Get recent continuity logs
3206
+ */
3207
+ async getRecentLogs(limit = 10) {
3208
+ const rows = await dbAll(
3209
+ this.db,
3210
+ `SELECT * FROM continuity_log
3211
+ ORDER BY created_at DESC
3212
+ LIMIT ?`,
3213
+ [limit]
3214
+ );
3215
+ return rows.map((row) => ({
3216
+ logId: row.log_id,
3217
+ fromContextId: row.from_context_id,
3218
+ toContextId: row.to_context_id,
3219
+ continuityScore: row.continuity_score,
3220
+ transitionType: row.transition_type,
3221
+ createdAt: toDate(row.created_at)
3222
+ }));
3223
+ }
3224
+ /**
3225
+ * Get average continuity score over time period
3226
+ */
3227
+ async getAverageScore(hours = 1) {
3228
+ const result = await dbAll(
3229
+ this.db,
3230
+ `SELECT AVG(continuity_score) as avg_score
3231
+ FROM continuity_log
3232
+ WHERE created_at > datetime('now', '-${hours} hours')`
3233
+ );
3234
+ return result[0]?.avg_score ?? 0.5;
3235
+ }
3236
+ /**
3237
+ * Get transition type distribution
3238
+ */
3239
+ async getTransitionStats(hours = 24) {
3240
+ const rows = await dbAll(
3241
+ this.db,
3242
+ `SELECT transition_type, COUNT(*) as count
3243
+ FROM continuity_log
3244
+ WHERE created_at > datetime('now', '-${hours} hours')
3245
+ GROUP BY transition_type`
3246
+ );
3247
+ const stats = {
3248
+ seamless: 0,
3249
+ topic_shift: 0,
3250
+ break: 0
3251
+ };
3252
+ for (const row of rows) {
3253
+ stats[row.transition_type] = row.count;
3254
+ }
3255
+ return stats;
3256
+ }
3257
+ /**
3258
+ * Clear old continuity logs
3259
+ */
3260
+ async cleanup(olderThanDays = 7) {
3261
+ const result = await dbAll(
3262
+ this.db,
3263
+ `DELETE FROM continuity_log
3264
+ WHERE created_at < datetime('now', '-${olderThanDays} days')
3265
+ RETURNING COUNT(*) as changes`
3266
+ );
3267
+ return result[0]?.changes || 0;
3268
+ }
3269
+ /**
3270
+ * Calculate overlap between two arrays
3271
+ */
3272
+ calculateOverlap(a, b) {
3273
+ if (a.length === 0 || b.length === 0)
3274
+ return 0;
3275
+ const setA = new Set(a.map((s) => s.toLowerCase()));
3276
+ const setB = new Set(b.map((s) => s.toLowerCase()));
3277
+ const intersection = [...setA].filter((x) => setB.has(x));
3278
+ const union = /* @__PURE__ */ new Set([...setA, ...setB]);
3279
+ return intersection.length / union.size;
3280
+ }
3281
+ /**
3282
+ * Determine transition type based on score
3283
+ */
3284
+ determineTransitionType(score) {
3285
+ if (score >= this.config.continuity.minScoreForSeamless) {
3286
+ return "seamless";
3287
+ } else if (score >= 0.4) {
3288
+ return "topic_shift";
3289
+ } else {
3290
+ return "break";
3291
+ }
3292
+ }
3293
+ /**
3294
+ * Log a context transition
3295
+ */
3296
+ async logTransition(current, previous, score, type) {
3297
+ await dbRun(
3298
+ this.db,
3299
+ `INSERT INTO continuity_log
3300
+ (log_id, from_context_id, to_context_id, continuity_score, transition_type, created_at)
3301
+ VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
3302
+ [randomUUID6(), previous.id, current.id, score, type]
3303
+ );
3304
+ }
3305
+ /**
3306
+ * Extract topics from content
3307
+ */
3308
+ extractTopics(content) {
3309
+ const topics = [];
3310
+ const contentLower = content.toLowerCase();
3311
+ const langPatterns = [
3312
+ { pattern: /typescript|\.ts\b/i, topic: "typescript" },
3313
+ { pattern: /javascript|\.js\b/i, topic: "javascript" },
3314
+ { pattern: /python|\.py\b/i, topic: "python" },
3315
+ { pattern: /rust|\.rs\b/i, topic: "rust" },
3316
+ { pattern: /go\b|golang/i, topic: "go" }
3317
+ ];
3318
+ for (const { pattern, topic } of langPatterns) {
3319
+ if (pattern.test(content)) {
3320
+ topics.push(topic);
3321
+ }
3322
+ }
3323
+ const devTopics = [
3324
+ "api",
3325
+ "database",
3326
+ "test",
3327
+ "bug",
3328
+ "feature",
3329
+ "refactor",
3330
+ "component",
3331
+ "function",
3332
+ "class",
3333
+ "module",
3334
+ "hook",
3335
+ "deploy",
3336
+ "build",
3337
+ "config",
3338
+ "docker",
3339
+ "git"
3340
+ ];
3341
+ for (const topic of devTopics) {
3342
+ if (contentLower.includes(topic)) {
3343
+ topics.push(topic);
3344
+ }
3345
+ }
3346
+ return [...new Set(topics)].slice(0, 10);
3347
+ }
3348
+ /**
3349
+ * Extract file paths from content
3350
+ */
3351
+ extractFiles(content) {
3352
+ const filePatterns = [
3353
+ /(?:^|\s)([a-zA-Z0-9_\-./]+\.[a-zA-Z0-9]+)(?:\s|$|:)/gm,
3354
+ /['"](\.?\/[^'"]+\.[a-zA-Z0-9]+)['"]/g,
3355
+ /file[:\s]+([^\s,]+)/gi
3356
+ ];
3357
+ const files = /* @__PURE__ */ new Set();
3358
+ for (const pattern of filePatterns) {
3359
+ let match;
3360
+ while ((match = pattern.exec(content)) !== null) {
3361
+ const file = match[1];
3362
+ if (file && file.length > 3 && file.length < 100) {
3363
+ if (!file.match(/^(https?:|mailto:|ftp:)/i)) {
3364
+ files.add(file);
3365
+ }
3366
+ }
3367
+ }
3368
+ }
3369
+ return Array.from(files).slice(0, 10);
3370
+ }
3371
+ /**
3372
+ * Extract entity names from content (functions, classes, variables)
3373
+ */
3374
+ extractEntities(content) {
3375
+ const entities = /* @__PURE__ */ new Set();
3376
+ const entityPatterns = [
3377
+ /\b(function|const|let|var|class|interface|type)\s+([a-zA-Z_][a-zA-Z0-9_]*)/g,
3378
+ /\b([A-Z][a-zA-Z0-9_]*(?:Component|Service|Store|Manager|Handler|Factory|Provider))\b/g,
3379
+ /\b(use[A-Z][a-zA-Z0-9_]*)\b/g
3380
+ // React hooks
3381
+ ];
3382
+ for (const pattern of entityPatterns) {
3383
+ let match;
3384
+ while ((match = pattern.exec(content)) !== null) {
3385
+ const entity = match[2] || match[1];
3386
+ if (entity && entity.length > 2) {
3387
+ entities.add(entity);
3388
+ }
3389
+ }
3390
+ }
3391
+ return Array.from(entities).slice(0, 20);
3392
+ }
3393
+ /**
3394
+ * Reset the last context (for testing or manual reset)
3395
+ */
3396
+ resetLastContext() {
3397
+ this.lastContext = null;
3398
+ }
3399
+ /**
3400
+ * Get the last context snapshot
3401
+ */
3402
+ getLastContext() {
3403
+ return this.lastContext;
3404
+ }
3405
+ };
3406
+ function createContinuityManager(eventStore, config) {
3407
+ return new ContinuityManager(eventStore, config);
3408
+ }
3409
+
3410
+ // src/core/graduation-worker.ts
3411
+ var DEFAULT_CONFIG4 = {
3412
+ evaluationIntervalMs: 3e5,
3413
+ // 5 minutes
3414
+ batchSize: 50,
3415
+ cooldownMs: 36e5
3416
+ // 1 hour cooldown between evaluations
3417
+ };
3418
+ var GraduationWorker = class {
3419
+ constructor(eventStore, graduation, config = DEFAULT_CONFIG4) {
3420
+ this.eventStore = eventStore;
3421
+ this.graduation = graduation;
3422
+ this.config = config;
3423
+ }
3424
+ running = false;
3425
+ timeout = null;
3426
+ lastEvaluated = /* @__PURE__ */ new Map();
3427
+ /**
3428
+ * Start the graduation worker
3429
+ */
3430
+ start() {
3431
+ if (this.running)
3432
+ return;
3433
+ this.running = true;
3434
+ this.scheduleNext();
3435
+ }
3436
+ /**
3437
+ * Stop the graduation worker
3438
+ */
3439
+ stop() {
3440
+ this.running = false;
3441
+ if (this.timeout) {
3442
+ clearTimeout(this.timeout);
3443
+ this.timeout = null;
3444
+ }
3445
+ }
3446
+ /**
3447
+ * Check if currently running
3448
+ */
3449
+ isRunning() {
3450
+ return this.running;
3451
+ }
3452
+ /**
3453
+ * Force a graduation evaluation run
3454
+ */
3455
+ async forceRun() {
3456
+ return await this.runGraduation();
3457
+ }
3458
+ /**
3459
+ * Schedule the next graduation check
3460
+ */
3461
+ scheduleNext() {
3462
+ if (!this.running)
3463
+ return;
3464
+ this.timeout = setTimeout(
3465
+ () => this.run(),
3466
+ this.config.evaluationIntervalMs
3467
+ );
3468
+ }
3469
+ /**
3470
+ * Run graduation evaluation
3471
+ */
3472
+ async run() {
3473
+ if (!this.running)
3474
+ return;
3475
+ try {
3476
+ await this.runGraduation();
3477
+ } catch (error) {
3478
+ console.error("Graduation error:", error);
3479
+ }
3480
+ this.scheduleNext();
3481
+ }
3482
+ /**
3483
+ * Perform graduation evaluation across all levels
3484
+ */
3485
+ async runGraduation() {
3486
+ const result = {
3487
+ evaluated: 0,
3488
+ graduated: 0,
3489
+ byLevel: {}
3490
+ };
3491
+ const levels = ["L0", "L1", "L2", "L3"];
3492
+ const now = Date.now();
3493
+ for (const level of levels) {
3494
+ const events = await this.eventStore.getEventsByLevel(level, {
3495
+ limit: this.config.batchSize
3496
+ });
3497
+ let levelGraduated = 0;
3498
+ for (const event of events) {
3499
+ const lastEval = this.lastEvaluated.get(event.id);
3500
+ if (lastEval && now - lastEval < this.config.cooldownMs) {
3501
+ continue;
3502
+ }
3503
+ result.evaluated++;
3504
+ this.lastEvaluated.set(event.id, now);
3505
+ const gradResult = await this.graduation.evaluateGraduation(event.id, level);
3506
+ if (gradResult.success) {
3507
+ result.graduated++;
3508
+ levelGraduated++;
3509
+ }
3510
+ }
3511
+ if (levelGraduated > 0) {
3512
+ result.byLevel[level] = levelGraduated;
3513
+ }
3514
+ }
3515
+ if (this.lastEvaluated.size > 1e3) {
3516
+ const entries = Array.from(this.lastEvaluated.entries());
3517
+ entries.sort((a, b) => b[1] - a[1]);
3518
+ this.lastEvaluated = new Map(entries.slice(0, 1e3));
3519
+ }
3520
+ return result;
3521
+ }
3522
+ };
3523
+ function createGraduationWorker(eventStore, graduation, config) {
3524
+ return new GraduationWorker(
3525
+ eventStore,
3526
+ graduation,
3527
+ { ...DEFAULT_CONFIG4, ...config }
3528
+ );
3529
+ }
3530
+
3531
+ // src/services/memory-service.ts
3532
+ function normalizePath(projectPath) {
3533
+ const expanded = projectPath.startsWith("~") ? path.join(os.homedir(), projectPath.slice(1)) : projectPath;
3534
+ try {
3535
+ return fs.realpathSync(expanded);
3536
+ } catch {
3537
+ return path.resolve(expanded);
3538
+ }
3539
+ }
3540
+ function hashProjectPath(projectPath) {
3541
+ const normalizedPath = normalizePath(projectPath);
3542
+ return crypto2.createHash("sha256").update(normalizedPath).digest("hex").slice(0, 8);
3543
+ }
3544
+ function getProjectStoragePath(projectPath) {
3545
+ const hash = hashProjectPath(projectPath);
3546
+ return path.join(os.homedir(), ".claude-code", "memory", "projects", hash);
3547
+ }
3548
+ var REGISTRY_PATH = path.join(os.homedir(), ".claude-code", "memory", "session-registry.json");
3549
+ var SHARED_STORAGE_PATH = path.join(os.homedir(), ".claude-code", "memory", "shared");
3550
+ var MemoryService = class {
3551
+ eventStore;
3552
+ vectorStore;
3553
+ embedder;
3554
+ matcher;
3555
+ retriever;
3556
+ graduation;
3557
+ vectorWorker = null;
3558
+ graduationWorker = null;
3559
+ initialized = false;
3560
+ // Endless Mode components
3561
+ workingSetStore = null;
3562
+ consolidatedStore = null;
3563
+ consolidationWorker = null;
3564
+ continuityManager = null;
3565
+ endlessMode = "session";
3566
+ // Shared Store components (cross-project knowledge)
3567
+ sharedEventStore = null;
3568
+ sharedStore = null;
3569
+ sharedVectorStore = null;
3570
+ sharedPromoter = null;
3571
+ sharedStoreConfig = null;
3572
+ projectHash = null;
3573
+ readOnly;
3574
+ constructor(config) {
3575
+ const storagePath = this.expandPath(config.storagePath);
3576
+ this.readOnly = config.readOnly ?? false;
3577
+ if (!this.readOnly && !fs.existsSync(storagePath)) {
3578
+ fs.mkdirSync(storagePath, { recursive: true });
3579
+ }
3580
+ this.projectHash = config.projectHash || null;
3581
+ this.sharedStoreConfig = config.sharedStoreConfig ?? { enabled: true };
3582
+ this.eventStore = new EventStore(path.join(storagePath, "events.duckdb"), { readOnly: this.readOnly });
3583
+ this.vectorStore = new VectorStore(path.join(storagePath, "vectors"));
3584
+ this.embedder = config.embeddingModel ? new Embedder(config.embeddingModel) : getDefaultEmbedder();
3585
+ this.matcher = getDefaultMatcher();
3586
+ this.retriever = createRetriever(
3587
+ this.eventStore,
3588
+ this.vectorStore,
3589
+ this.embedder,
3590
+ this.matcher
3591
+ );
3592
+ this.graduation = createGraduationPipeline(this.eventStore);
3593
+ }
3594
+ /**
3595
+ * Initialize all components
3596
+ */
3597
+ async initialize() {
3598
+ if (this.initialized)
3599
+ return;
3600
+ await this.eventStore.initialize();
3601
+ await this.vectorStore.initialize();
3602
+ await this.embedder.initialize();
3603
+ if (!this.readOnly) {
3604
+ this.vectorWorker = createVectorWorker(
3605
+ this.eventStore,
3606
+ this.vectorStore,
3607
+ this.embedder
3608
+ );
3609
+ this.vectorWorker.start();
3610
+ this.retriever.setGraduationPipeline(this.graduation);
3611
+ this.graduationWorker = createGraduationWorker(
3612
+ this.eventStore,
3613
+ this.graduation
3614
+ );
3615
+ this.graduationWorker.start();
3616
+ const savedMode = await this.eventStore.getEndlessConfig("mode");
3617
+ if (savedMode === "endless") {
3618
+ this.endlessMode = "endless";
3619
+ await this.initializeEndlessMode();
3620
+ }
3621
+ if (this.sharedStoreConfig?.enabled !== false) {
3622
+ await this.initializeSharedStore();
3623
+ }
3624
+ }
3625
+ this.initialized = true;
3626
+ }
3627
+ /**
3628
+ * Initialize Shared Store components
3629
+ */
3630
+ async initializeSharedStore() {
3631
+ const sharedPath = this.sharedStoreConfig?.sharedStoragePath ? this.expandPath(this.sharedStoreConfig.sharedStoragePath) : SHARED_STORAGE_PATH;
3632
+ if (!fs.existsSync(sharedPath)) {
3633
+ fs.mkdirSync(sharedPath, { recursive: true });
3634
+ }
3635
+ this.sharedEventStore = createSharedEventStore(
3636
+ path.join(sharedPath, "shared.duckdb")
3637
+ );
3638
+ await this.sharedEventStore.initialize();
3639
+ this.sharedStore = createSharedStore(this.sharedEventStore);
3640
+ this.sharedVectorStore = createSharedVectorStore(
3641
+ path.join(sharedPath, "vectors")
3642
+ );
3643
+ await this.sharedVectorStore.initialize();
3644
+ this.sharedPromoter = createSharedPromoter(
3645
+ this.sharedStore,
3646
+ this.sharedVectorStore,
3647
+ this.embedder,
3648
+ this.sharedStoreConfig || void 0
3649
+ );
3650
+ this.retriever.setSharedStores(this.sharedStore, this.sharedVectorStore);
3651
+ }
3652
+ /**
3653
+ * Start a new session
3654
+ */
3655
+ async startSession(sessionId, projectPath) {
3656
+ await this.initialize();
3657
+ await this.eventStore.upsertSession({
3658
+ id: sessionId,
3659
+ startedAt: /* @__PURE__ */ new Date(),
3660
+ projectPath
3661
+ });
3662
+ }
3663
+ /**
3664
+ * End a session
3665
+ */
3666
+ async endSession(sessionId, summary) {
3667
+ await this.initialize();
3668
+ await this.eventStore.upsertSession({
3669
+ id: sessionId,
3670
+ endedAt: /* @__PURE__ */ new Date(),
3671
+ summary
3672
+ });
3673
+ }
3674
+ /**
3675
+ * Store a user prompt
3676
+ */
3677
+ async storeUserPrompt(sessionId, content, metadata) {
3678
+ await this.initialize();
3679
+ const result = await this.eventStore.append({
3680
+ eventType: "user_prompt",
3681
+ sessionId,
3682
+ timestamp: /* @__PURE__ */ new Date(),
3683
+ content,
3684
+ metadata
3685
+ });
3686
+ if (result.success && !result.isDuplicate) {
3687
+ await this.eventStore.enqueueForEmbedding(result.eventId, content);
3688
+ }
3689
+ return result;
3690
+ }
3691
+ /**
3692
+ * Store an agent response
3693
+ */
3694
+ async storeAgentResponse(sessionId, content, metadata) {
3695
+ await this.initialize();
3696
+ const result = await this.eventStore.append({
3697
+ eventType: "agent_response",
3698
+ sessionId,
3699
+ timestamp: /* @__PURE__ */ new Date(),
3700
+ content,
3701
+ metadata
3702
+ });
3703
+ if (result.success && !result.isDuplicate) {
3704
+ await this.eventStore.enqueueForEmbedding(result.eventId, content);
3705
+ }
3706
+ return result;
3707
+ }
3708
+ /**
3709
+ * Store a session summary
3710
+ */
3711
+ async storeSessionSummary(sessionId, summary) {
3712
+ await this.initialize();
3713
+ const result = await this.eventStore.append({
3714
+ eventType: "session_summary",
3715
+ sessionId,
3716
+ timestamp: /* @__PURE__ */ new Date(),
3717
+ content: summary
3718
+ });
3719
+ if (result.success && !result.isDuplicate) {
3720
+ await this.eventStore.enqueueForEmbedding(result.eventId, summary);
3721
+ }
3722
+ return result;
3723
+ }
3724
+ /**
3725
+ * Store a tool observation
3726
+ */
3727
+ async storeToolObservation(sessionId, payload) {
3728
+ await this.initialize();
3729
+ const content = JSON.stringify(payload);
3730
+ const result = await this.eventStore.append({
3731
+ eventType: "tool_observation",
3732
+ sessionId,
3733
+ timestamp: /* @__PURE__ */ new Date(),
3734
+ content,
3735
+ metadata: {
3736
+ toolName: payload.toolName,
3737
+ success: payload.success
3738
+ }
3739
+ });
3740
+ if (result.success && !result.isDuplicate) {
3741
+ const embeddingContent = createToolObservationEmbedding(
3742
+ payload.toolName,
3743
+ payload.metadata || {},
3744
+ payload.success
3745
+ );
3746
+ await this.eventStore.enqueueForEmbedding(result.eventId, embeddingContent);
3747
+ }
3748
+ return result;
3749
+ }
3750
+ /**
3751
+ * Retrieve relevant memories for a query
3752
+ */
3753
+ async retrieveMemories(query, options) {
3754
+ await this.initialize();
3755
+ if (this.vectorWorker) {
3756
+ await this.vectorWorker.processAll();
3757
+ }
3758
+ if (options?.includeShared && this.sharedStore) {
3759
+ return this.retriever.retrieveUnified(query, {
3760
+ ...options,
3761
+ includeShared: true,
3762
+ projectHash: this.projectHash || void 0
3763
+ });
3764
+ }
3765
+ return this.retriever.retrieve(query, options);
3766
+ }
3767
+ /**
3768
+ * Get session history
3769
+ */
3770
+ async getSessionHistory(sessionId) {
3771
+ await this.initialize();
3772
+ return this.eventStore.getSessionEvents(sessionId);
3773
+ }
3774
+ /**
3775
+ * Get recent events
3776
+ */
3777
+ async getRecentEvents(limit = 100) {
3778
+ await this.initialize();
3779
+ return this.eventStore.getRecentEvents(limit);
3780
+ }
3781
+ /**
3782
+ * Get memory statistics
3783
+ */
3784
+ async getStats() {
3785
+ await this.initialize();
3786
+ const recentEvents = await this.eventStore.getRecentEvents(1e4);
3787
+ const vectorCount = await this.vectorStore.count();
3788
+ const levelStats = await this.graduation.getStats();
3789
+ return {
3790
+ totalEvents: recentEvents.length,
3791
+ vectorCount,
3792
+ levelStats
3793
+ };
3794
+ }
3795
+ /**
3796
+ * Process pending embeddings
3797
+ */
3798
+ async processPendingEmbeddings() {
3799
+ if (this.vectorWorker) {
3800
+ return this.vectorWorker.processAll();
3801
+ }
3802
+ return 0;
3803
+ }
3804
+ /**
3805
+ * Get events by memory level
3806
+ */
3807
+ async getEventsByLevel(level, options) {
3808
+ await this.initialize();
3809
+ return this.eventStore.getEventsByLevel(level, options);
3810
+ }
3811
+ /**
3812
+ * Get memory level for a specific event
3813
+ */
3814
+ async getEventLevel(eventId) {
3815
+ await this.initialize();
3816
+ return this.eventStore.getEventLevel(eventId);
3817
+ }
3818
+ /**
3819
+ * Format retrieval results as context for Claude
3820
+ */
3821
+ formatAsContext(result) {
3822
+ if (!result.context) {
3823
+ return "";
3824
+ }
3825
+ const confidence = result.matchResult.confidence;
3826
+ let header = "";
3827
+ if (confidence === "high") {
3828
+ header = "\u{1F3AF} **High-confidence memory match found:**\n\n";
3829
+ } else if (confidence === "suggested") {
3830
+ header = "\u{1F4A1} **Suggested memories (may be relevant):**\n\n";
3831
+ }
3832
+ return header + result.context;
3833
+ }
3834
+ // ============================================================
3835
+ // Shared Store Methods (Cross-Project Knowledge)
3836
+ // ============================================================
3837
+ /**
3838
+ * Check if shared store is enabled and initialized
3839
+ */
3840
+ isSharedStoreEnabled() {
3841
+ return this.sharedStore !== null;
3842
+ }
3843
+ /**
3844
+ * Promote an entry to shared storage
3845
+ */
3846
+ async promoteToShared(entry) {
3847
+ if (!this.sharedPromoter || !this.projectHash) {
3848
+ return {
3849
+ success: false,
3850
+ error: "Shared store not initialized or project hash not set"
3851
+ };
3852
+ }
3853
+ return this.sharedPromoter.promoteEntry(entry, this.projectHash);
3854
+ }
3855
+ /**
3856
+ * Get shared store statistics
3857
+ */
3858
+ async getSharedStoreStats() {
3859
+ if (!this.sharedStore)
3860
+ return null;
3861
+ return this.sharedStore.getStats();
3862
+ }
3863
+ /**
3864
+ * Search shared troubleshooting entries
3865
+ */
3866
+ async searchShared(query, options) {
3867
+ if (!this.sharedStore)
3868
+ return [];
3869
+ return this.sharedStore.search(query, options);
3870
+ }
3871
+ /**
3872
+ * Get project hash for this service
3873
+ */
3874
+ getProjectHash() {
3875
+ return this.projectHash;
3876
+ }
3877
+ // ============================================================
3878
+ // Endless Mode Methods
3879
+ // ============================================================
3880
+ /**
3881
+ * Get the default endless mode config
3882
+ */
3883
+ getDefaultEndlessConfig() {
3884
+ return {
3885
+ enabled: true,
3886
+ workingSet: {
3887
+ maxEvents: 100,
3888
+ timeWindowHours: 24,
3889
+ minRelevanceScore: 0.5
3890
+ },
3891
+ consolidation: {
3892
+ triggerIntervalMs: 36e5,
3893
+ // 1 hour
3894
+ triggerEventCount: 100,
3895
+ triggerIdleMs: 18e5,
3896
+ // 30 minutes
3897
+ useLLMSummarization: false
3898
+ },
3899
+ continuity: {
3900
+ minScoreForSeamless: 0.7,
3901
+ topicDecayHours: 48
3902
+ }
3903
+ };
3904
+ }
3905
+ /**
3906
+ * Initialize Endless Mode components
3907
+ */
3908
+ async initializeEndlessMode() {
3909
+ const config = await this.getEndlessConfig();
3910
+ this.workingSetStore = createWorkingSetStore(this.eventStore, config);
3911
+ this.consolidatedStore = createConsolidatedStore(this.eventStore);
3912
+ this.consolidationWorker = createConsolidationWorker(
3913
+ this.workingSetStore,
3914
+ this.consolidatedStore,
3915
+ config
3916
+ );
3917
+ this.continuityManager = createContinuityManager(this.eventStore, config);
3918
+ this.consolidationWorker.start();
3919
+ }
3920
+ /**
3921
+ * Get Endless Mode configuration
3922
+ */
3923
+ async getEndlessConfig() {
3924
+ const savedConfig = await this.eventStore.getEndlessConfig("config");
3925
+ return savedConfig || this.getDefaultEndlessConfig();
3926
+ }
3927
+ /**
3928
+ * Set Endless Mode configuration
3929
+ */
3930
+ async setEndlessConfig(config) {
3931
+ const current = await this.getEndlessConfig();
3932
+ const merged = { ...current, ...config };
3933
+ await this.eventStore.setEndlessConfig("config", merged);
3934
+ }
3935
+ /**
3936
+ * Set memory mode (session or endless)
3937
+ */
3938
+ async setMode(mode) {
3939
+ await this.initialize();
3940
+ if (mode === this.endlessMode)
3941
+ return;
3942
+ this.endlessMode = mode;
3943
+ await this.eventStore.setEndlessConfig("mode", mode);
3944
+ if (mode === "endless") {
3945
+ await this.initializeEndlessMode();
3946
+ } else {
3947
+ if (this.consolidationWorker) {
3948
+ this.consolidationWorker.stop();
3949
+ this.consolidationWorker = null;
3950
+ }
3951
+ this.workingSetStore = null;
3952
+ this.consolidatedStore = null;
3953
+ this.continuityManager = null;
3954
+ }
3955
+ }
3956
+ /**
3957
+ * Get current memory mode
3958
+ */
3959
+ getMode() {
3960
+ return this.endlessMode;
3961
+ }
3962
+ /**
3963
+ * Check if endless mode is active
3964
+ */
3965
+ isEndlessModeActive() {
3966
+ return this.endlessMode === "endless";
3967
+ }
3968
+ /**
3969
+ * Add event to Working Set (Endless Mode)
3970
+ */
3971
+ async addToWorkingSet(eventId, relevanceScore) {
3972
+ if (!this.workingSetStore)
3973
+ return;
3974
+ await this.workingSetStore.add(eventId, relevanceScore);
3975
+ }
3976
+ /**
3977
+ * Get the current Working Set
3978
+ */
3979
+ async getWorkingSet() {
3980
+ if (!this.workingSetStore)
3981
+ return null;
3982
+ return this.workingSetStore.get();
3983
+ }
3984
+ /**
3985
+ * Search consolidated memories
3986
+ */
3987
+ async searchConsolidated(query, options) {
3988
+ if (!this.consolidatedStore)
3989
+ return [];
3990
+ return this.consolidatedStore.search(query, options);
3991
+ }
3992
+ /**
3993
+ * Get all consolidated memories
3994
+ */
3995
+ async getConsolidatedMemories(limit) {
3996
+ if (!this.consolidatedStore)
3997
+ return [];
3998
+ return this.consolidatedStore.getAll({ limit });
3999
+ }
4000
+ /**
4001
+ * Get most accessed consolidated memories
4002
+ */
4003
+ async getMostAccessedMemories(limit = 10) {
4004
+ if (!this.consolidatedStore)
4005
+ return [];
4006
+ return this.consolidatedStore.getMostAccessed(limit);
4007
+ }
4008
+ /**
4009
+ * Mark a consolidated memory as accessed
4010
+ */
4011
+ async markMemoryAccessed(memoryId) {
4012
+ if (!this.consolidatedStore)
4013
+ return;
4014
+ await this.consolidatedStore.markAccessed(memoryId);
4015
+ }
4016
+ /**
4017
+ * Calculate continuity score for current context
4018
+ */
4019
+ async calculateContinuity(content, metadata) {
4020
+ if (!this.continuityManager)
4021
+ return null;
4022
+ const snapshot = this.continuityManager.createSnapshot(
4023
+ crypto2.randomUUID(),
4024
+ content,
4025
+ metadata
4026
+ );
4027
+ return this.continuityManager.calculateScore(snapshot);
4028
+ }
4029
+ /**
4030
+ * Record activity (for consolidation idle trigger)
4031
+ */
4032
+ recordActivity() {
4033
+ if (this.consolidationWorker) {
4034
+ this.consolidationWorker.recordActivity();
4035
+ }
4036
+ }
4037
+ /**
4038
+ * Force a consolidation run
4039
+ */
4040
+ async forceConsolidation() {
4041
+ if (!this.consolidationWorker)
4042
+ return 0;
4043
+ return this.consolidationWorker.forceRun();
4044
+ }
4045
+ /**
4046
+ * Get Endless Mode status
4047
+ */
4048
+ async getEndlessModeStatus() {
4049
+ await this.initialize();
4050
+ let workingSetSize = 0;
4051
+ let continuityScore = 0.5;
4052
+ let consolidatedCount = 0;
4053
+ let lastConsolidation = null;
4054
+ if (this.workingSetStore) {
4055
+ workingSetSize = await this.workingSetStore.count();
4056
+ const workingSet = await this.workingSetStore.get();
4057
+ continuityScore = workingSet.continuityScore;
4058
+ }
4059
+ if (this.consolidatedStore) {
4060
+ consolidatedCount = await this.consolidatedStore.count();
4061
+ lastConsolidation = await this.consolidatedStore.getLastConsolidationTime();
4062
+ }
4063
+ return {
4064
+ mode: this.endlessMode,
4065
+ workingSetSize,
4066
+ continuityScore,
4067
+ consolidatedCount,
4068
+ lastConsolidation
4069
+ };
4070
+ }
4071
+ /**
4072
+ * Format Endless Mode context for Claude
4073
+ */
4074
+ async formatEndlessContext(query) {
4075
+ if (!this.isEndlessModeActive()) {
4076
+ return "";
4077
+ }
4078
+ const workingSet = await this.getWorkingSet();
4079
+ const consolidated = await this.searchConsolidated(query, { topK: 3 });
4080
+ const continuity = await this.calculateContinuity(query);
4081
+ const parts = [];
4082
+ if (continuity) {
4083
+ const statusEmoji = continuity.transitionType === "seamless" ? "\u{1F517}" : continuity.transitionType === "topic_shift" ? "\u21AA\uFE0F" : "\u{1F195}";
4084
+ parts.push(`${statusEmoji} Context: ${continuity.transitionType} (score: ${continuity.score.toFixed(2)})`);
4085
+ }
4086
+ if (workingSet && workingSet.recentEvents.length > 0) {
4087
+ parts.push("\n## Recent Context (Working Set)");
4088
+ const recent = workingSet.recentEvents.slice(0, 5);
4089
+ for (const event of recent) {
4090
+ const preview = event.content.slice(0, 80) + (event.content.length > 80 ? "..." : "");
4091
+ const time = event.timestamp.toLocaleTimeString();
4092
+ parts.push(`- ${time} [${event.eventType}] ${preview}`);
4093
+ }
4094
+ }
4095
+ if (consolidated.length > 0) {
4096
+ parts.push("\n## Related Knowledge (Consolidated)");
4097
+ for (const memory of consolidated) {
4098
+ parts.push(`- ${memory.topics.slice(0, 3).join(", ")}: ${memory.summary.slice(0, 100)}...`);
4099
+ }
4100
+ }
4101
+ return parts.join("\n");
4102
+ }
4103
+ /**
4104
+ * Force a graduation evaluation run
4105
+ */
4106
+ async forceGraduation() {
4107
+ if (!this.graduationWorker) {
4108
+ return { evaluated: 0, graduated: 0, byLevel: {} };
4109
+ }
4110
+ return this.graduationWorker.forceRun();
4111
+ }
4112
+ /**
4113
+ * Record access to a memory event (for graduation scoring)
4114
+ */
4115
+ recordMemoryAccess(eventId, sessionId, confidence = 1) {
4116
+ this.graduation.recordAccess(eventId, sessionId, confidence);
4117
+ }
4118
+ /**
4119
+ * Shutdown service
4120
+ */
4121
+ async shutdown() {
4122
+ if (this.graduationWorker) {
4123
+ this.graduationWorker.stop();
4124
+ }
4125
+ if (this.consolidationWorker) {
4126
+ this.consolidationWorker.stop();
4127
+ }
4128
+ if (this.vectorWorker) {
4129
+ this.vectorWorker.stop();
4130
+ }
4131
+ if (this.sharedEventStore) {
4132
+ await this.sharedEventStore.close();
4133
+ }
4134
+ await this.eventStore.close();
4135
+ }
4136
+ /**
4137
+ * Expand ~ to home directory
4138
+ */
4139
+ expandPath(p) {
4140
+ if (p.startsWith("~")) {
4141
+ return path.join(os.homedir(), p.slice(1));
4142
+ }
4143
+ return p;
4144
+ }
4145
+ };
4146
+ var serviceCache = /* @__PURE__ */ new Map();
4147
+ function getReadOnlyMemoryService() {
4148
+ return new MemoryService({
4149
+ storagePath: "~/.claude-code/memory",
4150
+ readOnly: true
4151
+ });
4152
+ }
4153
+ function getMemoryServiceForProject(projectPath, sharedStoreConfig) {
4154
+ const hash = hashProjectPath(projectPath);
4155
+ if (!serviceCache.has(hash)) {
4156
+ const storagePath = getProjectStoragePath(projectPath);
4157
+ serviceCache.set(hash, new MemoryService({
4158
+ storagePath,
4159
+ projectHash: hash,
4160
+ sharedStoreConfig
4161
+ }));
4162
+ }
4163
+ return serviceCache.get(hash);
4164
+ }
4165
+
4166
+ // src/server/api/sessions.ts
4167
+ var sessionsRouter = new Hono();
4168
+ sessionsRouter.get("/", async (c) => {
4169
+ const page = parseInt(c.req.query("page") || "1", 10);
4170
+ const pageSize = parseInt(c.req.query("pageSize") || "20", 10);
4171
+ const memoryService = getReadOnlyMemoryService();
4172
+ try {
4173
+ await memoryService.initialize();
4174
+ const recentEvents = await memoryService.getRecentEvents(1e3);
4175
+ const sessionMap = /* @__PURE__ */ new Map();
4176
+ for (const event of recentEvents) {
4177
+ const existing = sessionMap.get(event.sessionId);
4178
+ if (!existing) {
4179
+ sessionMap.set(event.sessionId, {
4180
+ id: event.sessionId,
4181
+ startedAt: event.timestamp,
4182
+ eventCount: 1,
4183
+ lastEventAt: event.timestamp
4184
+ });
4185
+ } else {
4186
+ existing.eventCount++;
4187
+ if (event.timestamp < existing.startedAt) {
4188
+ existing.startedAt = event.timestamp;
4189
+ }
4190
+ if (event.timestamp > existing.lastEventAt) {
4191
+ existing.lastEventAt = event.timestamp;
4192
+ }
4193
+ }
4194
+ }
4195
+ const sessions = Array.from(sessionMap.values()).sort((a, b) => b.lastEventAt.getTime() - a.lastEventAt.getTime());
4196
+ const total = sessions.length;
4197
+ const start = (page - 1) * pageSize;
4198
+ const end = start + pageSize;
4199
+ const paginatedSessions = sessions.slice(start, end);
4200
+ return c.json({
4201
+ sessions: paginatedSessions,
4202
+ total,
4203
+ page,
4204
+ pageSize,
4205
+ hasMore: end < total
4206
+ });
4207
+ } catch (error) {
4208
+ return c.json({ error: error.message }, 500);
4209
+ } finally {
4210
+ await memoryService.shutdown();
4211
+ }
4212
+ });
4213
+ sessionsRouter.get("/:id", async (c) => {
4214
+ const { id } = c.req.param();
4215
+ const memoryService = getReadOnlyMemoryService();
4216
+ try {
4217
+ await memoryService.initialize();
4218
+ const events = await memoryService.getSessionHistory(id);
4219
+ if (events.length === 0) {
4220
+ return c.json({ error: "Session not found" }, 404);
4221
+ }
4222
+ const session = {
4223
+ id,
4224
+ startedAt: events[0].timestamp,
4225
+ endedAt: events[events.length - 1].timestamp,
4226
+ eventCount: events.length
4227
+ };
4228
+ const eventsByType = {
4229
+ user_prompt: events.filter((e) => e.eventType === "user_prompt").length,
4230
+ agent_response: events.filter((e) => e.eventType === "agent_response").length,
4231
+ tool_observation: events.filter((e) => e.eventType === "tool_observation").length
4232
+ };
4233
+ return c.json({
4234
+ session,
4235
+ events: events.slice(0, 100).map((e) => ({
4236
+ id: e.id,
4237
+ eventType: e.eventType,
4238
+ timestamp: e.timestamp,
4239
+ preview: e.content.slice(0, 200) + (e.content.length > 200 ? "..." : "")
4240
+ })),
4241
+ stats: eventsByType
4242
+ });
4243
+ } catch (error) {
4244
+ return c.json({ error: error.message }, 500);
4245
+ } finally {
4246
+ await memoryService.shutdown();
4247
+ }
4248
+ });
4249
+
4250
+ // src/server/api/events.ts
4251
+ import { Hono as Hono2 } from "hono";
4252
+ var eventsRouter = new Hono2();
4253
+ eventsRouter.get("/", async (c) => {
4254
+ const sessionId = c.req.query("sessionId");
4255
+ const eventType = c.req.query("type");
4256
+ const limit = parseInt(c.req.query("limit") || "100", 10);
4257
+ const offset = parseInt(c.req.query("offset") || "0", 10);
4258
+ const memoryService = getReadOnlyMemoryService();
4259
+ try {
4260
+ await memoryService.initialize();
4261
+ let events = await memoryService.getRecentEvents(limit + offset + 1e3);
4262
+ if (sessionId) {
4263
+ events = events.filter((e) => e.sessionId === sessionId);
4264
+ }
4265
+ if (eventType) {
4266
+ events = events.filter((e) => e.eventType === eventType);
4267
+ }
4268
+ const total = events.length;
4269
+ events = events.slice(offset, offset + limit);
4270
+ return c.json({
4271
+ events: events.map((e) => ({
4272
+ id: e.id,
4273
+ eventType: e.eventType,
4274
+ timestamp: e.timestamp,
4275
+ sessionId: e.sessionId,
4276
+ preview: e.content.slice(0, 200) + (e.content.length > 200 ? "..." : ""),
4277
+ contentLength: e.content.length
4278
+ })),
4279
+ total,
4280
+ limit,
4281
+ offset,
4282
+ hasMore: offset + limit < total
4283
+ });
4284
+ } catch (error) {
4285
+ return c.json({ error: error.message }, 500);
4286
+ } finally {
4287
+ await memoryService.shutdown();
4288
+ }
4289
+ });
4290
+ eventsRouter.get("/:id", async (c) => {
4291
+ const { id } = c.req.param();
4292
+ const memoryService = getReadOnlyMemoryService();
4293
+ try {
4294
+ await memoryService.initialize();
4295
+ const recentEvents = await memoryService.getRecentEvents(1e4);
4296
+ const event = recentEvents.find((e) => e.id === id);
4297
+ if (!event) {
4298
+ return c.json({ error: "Event not found" }, 404);
4299
+ }
4300
+ const sessionEvents = recentEvents.filter((e) => e.sessionId === event.sessionId).sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
4301
+ const eventIndex = sessionEvents.findIndex((e) => e.id === id);
4302
+ const start = Math.max(0, eventIndex - 2);
4303
+ const end = Math.min(sessionEvents.length, eventIndex + 3);
4304
+ const context = sessionEvents.slice(start, end).filter((e) => e.id !== id);
4305
+ return c.json({
4306
+ event: {
4307
+ id: event.id,
4308
+ eventType: event.eventType,
4309
+ timestamp: event.timestamp,
4310
+ sessionId: event.sessionId,
4311
+ content: event.content,
4312
+ metadata: event.metadata
4313
+ },
4314
+ context: context.map((e) => ({
4315
+ id: e.id,
4316
+ eventType: e.eventType,
4317
+ timestamp: e.timestamp,
4318
+ preview: e.content.slice(0, 100) + (e.content.length > 100 ? "..." : "")
4319
+ }))
4320
+ });
4321
+ } catch (error) {
4322
+ return c.json({ error: error.message }, 500);
4323
+ } finally {
4324
+ await memoryService.shutdown();
4325
+ }
4326
+ });
4327
+
4328
+ // src/server/api/search.ts
4329
+ import { Hono as Hono3 } from "hono";
4330
+ var searchRouter = new Hono3();
4331
+ searchRouter.post("/", async (c) => {
4332
+ const memoryService = getReadOnlyMemoryService();
4333
+ try {
4334
+ const body = await c.req.json();
4335
+ if (!body.query) {
4336
+ return c.json({ error: "Query is required" }, 400);
4337
+ }
4338
+ await memoryService.initialize();
4339
+ const startTime = Date.now();
4340
+ const result = await memoryService.retrieveMemories(body.query, {
4341
+ topK: body.options?.topK ?? 10,
4342
+ minScore: body.options?.minScore ?? 0.7,
4343
+ sessionId: body.options?.sessionId
4344
+ });
4345
+ const searchTime = Date.now() - startTime;
4346
+ return c.json({
4347
+ results: result.memories.map((m) => ({
4348
+ id: m.event.id,
4349
+ eventType: m.event.eventType,
4350
+ timestamp: m.event.timestamp,
4351
+ sessionId: m.event.sessionId,
4352
+ score: m.score,
4353
+ content: m.event.content,
4354
+ preview: m.event.content.slice(0, 200) + (m.event.content.length > 200 ? "..." : ""),
4355
+ context: m.sessionContext
4356
+ })),
4357
+ meta: {
4358
+ totalMatches: result.memories.length,
4359
+ searchTime,
4360
+ confidence: result.matchResult.confidence,
4361
+ totalTokens: result.totalTokens
4362
+ }
4363
+ });
4364
+ } catch (error) {
4365
+ return c.json({ error: error.message }, 500);
4366
+ } finally {
4367
+ await memoryService.shutdown();
4368
+ }
4369
+ });
4370
+ searchRouter.get("/", async (c) => {
4371
+ const query = c.req.query("q");
4372
+ if (!query) {
4373
+ return c.json({ error: 'Query parameter "q" is required' }, 400);
4374
+ }
4375
+ const topK = parseInt(c.req.query("topK") || "5", 10);
4376
+ const memoryService = getReadOnlyMemoryService();
4377
+ try {
4378
+ await memoryService.initialize();
4379
+ const result = await memoryService.retrieveMemories(query, { topK });
4380
+ return c.json({
4381
+ results: result.memories.map((m) => ({
4382
+ id: m.event.id,
4383
+ eventType: m.event.eventType,
4384
+ timestamp: m.event.timestamp,
4385
+ score: m.score,
4386
+ preview: m.event.content.slice(0, 200) + (m.event.content.length > 200 ? "..." : "")
4387
+ })),
4388
+ meta: {
4389
+ totalMatches: result.memories.length,
4390
+ confidence: result.matchResult.confidence
4391
+ }
4392
+ });
4393
+ } catch (error) {
4394
+ return c.json({ error: error.message }, 500);
4395
+ } finally {
4396
+ await memoryService.shutdown();
4397
+ }
4398
+ });
4399
+
4400
+ // src/server/api/stats.ts
4401
+ import { Hono as Hono4 } from "hono";
4402
+ var statsRouter = new Hono4();
4403
+ statsRouter.get("/shared", async (c) => {
4404
+ const memoryService = getReadOnlyMemoryService();
4405
+ try {
4406
+ await memoryService.initialize();
4407
+ const sharedStats = await memoryService.getSharedStoreStats();
4408
+ return c.json({
4409
+ troubleshooting: sharedStats?.troubleshooting || 0,
4410
+ bestPractices: sharedStats?.bestPractices || 0,
4411
+ commonErrors: sharedStats?.commonErrors || 0,
4412
+ totalUsageCount: sharedStats?.totalUsageCount || 0,
4413
+ lastUpdated: sharedStats?.lastUpdated || null
4414
+ });
4415
+ } catch (error) {
4416
+ return c.json({
4417
+ troubleshooting: 0,
4418
+ bestPractices: 0,
4419
+ commonErrors: 0,
4420
+ totalUsageCount: 0,
4421
+ lastUpdated: null
4422
+ });
4423
+ } finally {
4424
+ await memoryService.shutdown();
4425
+ }
4426
+ });
4427
+ statsRouter.get("/endless", async (c) => {
4428
+ const projectPath = c.req.query("project") || process.cwd();
4429
+ const memoryService = getMemoryServiceForProject(projectPath);
4430
+ try {
4431
+ await memoryService.initialize();
4432
+ const status = await memoryService.getEndlessModeStatus();
4433
+ return c.json({
4434
+ mode: status.mode,
4435
+ continuityScore: status.continuityScore,
4436
+ workingSetSize: status.workingSetSize,
4437
+ consolidatedCount: status.consolidatedCount,
4438
+ lastConsolidation: status.lastConsolidation?.toISOString() || null
4439
+ });
4440
+ } catch (error) {
4441
+ return c.json({
4442
+ mode: "session",
4443
+ continuityScore: 0,
4444
+ workingSetSize: 0,
4445
+ consolidatedCount: 0,
4446
+ lastConsolidation: null
4447
+ });
4448
+ } finally {
4449
+ await memoryService.shutdown();
4450
+ }
4451
+ });
4452
+ statsRouter.get("/levels/:level", async (c) => {
4453
+ const { level } = c.req.param();
4454
+ const limit = parseInt(c.req.query("limit") || "20", 10);
4455
+ const offset = parseInt(c.req.query("offset") || "0", 10);
4456
+ const validLevels = ["L0", "L1", "L2", "L3", "L4"];
4457
+ if (!validLevels.includes(level)) {
4458
+ return c.json({ error: `Invalid level. Must be one of: ${validLevels.join(", ")}` }, 400);
4459
+ }
4460
+ const memoryService = getReadOnlyMemoryService();
4461
+ try {
4462
+ await memoryService.initialize();
4463
+ const events = await memoryService.getEventsByLevel(level, { limit, offset });
4464
+ const stats = await memoryService.getStats();
4465
+ const levelStat = stats.levelStats.find((s) => s.level === level);
4466
+ return c.json({
4467
+ level,
4468
+ events: events.map((e) => ({
4469
+ id: e.id,
4470
+ eventType: e.eventType,
4471
+ sessionId: e.sessionId,
4472
+ timestamp: e.timestamp.toISOString(),
4473
+ content: e.content.slice(0, 500) + (e.content.length > 500 ? "..." : ""),
4474
+ metadata: e.metadata
4475
+ })),
4476
+ total: levelStat?.count || 0,
4477
+ limit,
4478
+ offset,
4479
+ hasMore: events.length === limit
4480
+ });
4481
+ } catch (error) {
4482
+ return c.json({ error: error.message }, 500);
4483
+ } finally {
4484
+ await memoryService.shutdown();
4485
+ }
4486
+ });
4487
+ statsRouter.get("/", async (c) => {
4488
+ const memoryService = getReadOnlyMemoryService();
4489
+ try {
4490
+ await memoryService.initialize();
4491
+ const stats = await memoryService.getStats();
4492
+ const recentEvents = await memoryService.getRecentEvents(1e4);
4493
+ const eventsByType = recentEvents.reduce((acc, e) => {
4494
+ acc[e.eventType] = (acc[e.eventType] || 0) + 1;
4495
+ return acc;
4496
+ }, {});
4497
+ const uniqueSessions = new Set(recentEvents.map((e) => e.sessionId));
4498
+ const now = /* @__PURE__ */ new Date();
4499
+ const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1e3);
4500
+ const eventsByDay = recentEvents.filter((e) => e.timestamp >= sevenDaysAgo).reduce((acc, e) => {
4501
+ const day = e.timestamp.toISOString().split("T")[0];
4502
+ acc[day] = (acc[day] || 0) + 1;
4503
+ return acc;
4504
+ }, {});
4505
+ return c.json({
4506
+ storage: {
4507
+ eventCount: stats.totalEvents,
4508
+ vectorCount: stats.vectorCount
4509
+ },
4510
+ sessions: {
4511
+ total: uniqueSessions.size
4512
+ },
4513
+ eventsByType,
4514
+ activity: {
4515
+ daily: eventsByDay,
4516
+ total7Days: recentEvents.filter((e) => e.timestamp >= sevenDaysAgo).length
4517
+ },
4518
+ memory: {
4519
+ heapUsed: Math.round(process.memoryUsage().heapUsed / 1024 / 1024),
4520
+ heapTotal: Math.round(process.memoryUsage().heapTotal / 1024 / 1024)
4521
+ },
4522
+ levelStats: stats.levelStats
4523
+ });
4524
+ } catch (error) {
4525
+ return c.json({ error: error.message }, 500);
4526
+ } finally {
4527
+ await memoryService.shutdown();
4528
+ }
4529
+ });
4530
+ statsRouter.get("/most-accessed", async (c) => {
4531
+ const limit = parseInt(c.req.query("limit") || "10", 10);
4532
+ const projectPath = c.req.query("project") || process.cwd();
4533
+ const memoryService = getMemoryServiceForProject(projectPath);
4534
+ try {
4535
+ await memoryService.initialize();
4536
+ const memories = await memoryService.getMostAccessedMemories(limit);
4537
+ return c.json({
4538
+ memories: memories.map((m) => ({
4539
+ memoryId: m.memoryId,
4540
+ summary: m.summary,
4541
+ topics: m.topics,
4542
+ accessCount: m.accessCount,
4543
+ lastAccessed: m.accessedAt?.toISOString() || null,
4544
+ confidence: m.confidence,
4545
+ createdAt: m.createdAt.toISOString()
4546
+ })),
4547
+ total: memories.length
4548
+ });
4549
+ } catch (error) {
4550
+ return c.json({
4551
+ memories: [],
4552
+ total: 0,
4553
+ error: error.message
4554
+ });
4555
+ } finally {
4556
+ await memoryService.shutdown();
4557
+ }
4558
+ });
4559
+ statsRouter.get("/timeline", async (c) => {
4560
+ const days = parseInt(c.req.query("days") || "7", 10);
4561
+ const memoryService = getReadOnlyMemoryService();
4562
+ try {
4563
+ await memoryService.initialize();
4564
+ const recentEvents = await memoryService.getRecentEvents(1e4);
4565
+ const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1e3);
4566
+ const filteredEvents = recentEvents.filter((e) => e.timestamp >= cutoff);
4567
+ const daily = filteredEvents.reduce((acc, e) => {
4568
+ const day = e.timestamp.toISOString().split("T")[0];
4569
+ if (!acc[day]) {
4570
+ acc[day] = { date: day, total: 0, prompts: 0, responses: 0, tools: 0 };
4571
+ }
4572
+ acc[day].total++;
4573
+ if (e.eventType === "user_prompt")
4574
+ acc[day].prompts++;
4575
+ if (e.eventType === "agent_response")
4576
+ acc[day].responses++;
4577
+ if (e.eventType === "tool_observation")
4578
+ acc[day].tools++;
4579
+ return acc;
4580
+ }, {});
4581
+ return c.json({
4582
+ days,
4583
+ daily: Object.values(daily).sort((a, b) => a.date.localeCompare(b.date))
4584
+ });
4585
+ } catch (error) {
4586
+ return c.json({ error: error.message }, 500);
4587
+ } finally {
4588
+ await memoryService.shutdown();
4589
+ }
4590
+ });
4591
+ statsRouter.post("/graduation/run", async (c) => {
4592
+ const memoryService = getReadOnlyMemoryService();
4593
+ try {
4594
+ await memoryService.initialize();
4595
+ const result = await memoryService.forceGraduation();
4596
+ return c.json({
4597
+ success: true,
4598
+ evaluated: result.evaluated,
4599
+ graduated: result.graduated,
4600
+ byLevel: result.byLevel
4601
+ });
4602
+ } catch (error) {
4603
+ return c.json({
4604
+ success: false,
4605
+ error: error.message
4606
+ }, 500);
4607
+ } finally {
4608
+ await memoryService.shutdown();
4609
+ }
4610
+ });
4611
+ statsRouter.get("/graduation", async (c) => {
4612
+ return c.json({
4613
+ criteria: {
4614
+ L0toL1: { minAccessCount: 1, minConfidence: 0.5, minCrossSessionRefs: 0, maxAgeDays: 30 },
4615
+ L1toL2: { minAccessCount: 3, minConfidence: 0.7, minCrossSessionRefs: 1, maxAgeDays: 60 },
4616
+ L2toL3: { minAccessCount: 5, minConfidence: 0.85, minCrossSessionRefs: 2, maxAgeDays: 90 },
4617
+ L3toL4: { minAccessCount: 10, minConfidence: 0.92, minCrossSessionRefs: 3, maxAgeDays: 180 }
4618
+ },
4619
+ description: {
4620
+ accessCount: "Number of times the memory was retrieved/referenced",
4621
+ confidence: "Match confidence score when retrieved (0.0-1.0)",
4622
+ crossSessionRefs: "Number of different sessions that referenced this memory",
4623
+ maxAgeDays: "Maximum days since last access (prevents stale promotion)"
4624
+ }
4625
+ });
4626
+ });
4627
+
4628
+ // src/server/api/citations.ts
4629
+ import { Hono as Hono5 } from "hono";
4630
+
4631
+ // src/core/citation-generator.ts
4632
+ import { createHash as createHash3 } from "crypto";
4633
+ var ID_LENGTH = 6;
4634
+ var CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
4635
+ function generateCitationId(eventId) {
4636
+ const hash = createHash3("sha256").update(eventId).digest();
4637
+ let id = "";
4638
+ for (let i = 0; i < ID_LENGTH; i++) {
4639
+ id += CHARSET[hash[i] % CHARSET.length];
4640
+ }
4641
+ return id;
4642
+ }
4643
+ function parseCitationId(formatted) {
4644
+ const match = formatted.match(/\[?mem:([A-Za-z0-9]{6})\]?/);
4645
+ return match ? match[1] : null;
4646
+ }
4647
+
4648
+ // src/server/api/citations.ts
4649
+ var citationsRouter = new Hono5();
4650
+ citationsRouter.get("/:id", async (c) => {
4651
+ const { id } = c.req.param();
4652
+ const citationId = parseCitationId(id) || id;
4653
+ const memoryService = getReadOnlyMemoryService();
4654
+ try {
4655
+ await memoryService.initialize();
4656
+ const recentEvents = await memoryService.getRecentEvents(1e4);
4657
+ const event = recentEvents.find((e) => {
4658
+ const eventCitationId = generateCitationId(e.id);
4659
+ return eventCitationId === citationId;
4660
+ });
4661
+ if (!event) {
4662
+ return c.json({ error: "Citation not found" }, 404);
4663
+ }
4664
+ return c.json({
4665
+ citation: {
4666
+ id: citationId,
4667
+ eventId: event.id
4668
+ },
4669
+ event: {
4670
+ id: event.id,
4671
+ eventType: event.eventType,
4672
+ timestamp: event.timestamp,
4673
+ sessionId: event.sessionId,
4674
+ content: event.content,
4675
+ metadata: event.metadata
4676
+ }
4677
+ });
4678
+ } catch (error) {
4679
+ return c.json({ error: error.message }, 500);
4680
+ } finally {
4681
+ await memoryService.shutdown();
4682
+ }
4683
+ });
4684
+ citationsRouter.get("/:id/related", async (c) => {
4685
+ const { id } = c.req.param();
4686
+ const citationId = parseCitationId(id) || id;
4687
+ const memoryService = getReadOnlyMemoryService();
4688
+ try {
4689
+ await memoryService.initialize();
4690
+ const recentEvents = await memoryService.getRecentEvents(1e4);
4691
+ const event = recentEvents.find((e) => {
4692
+ const eventCitationId = generateCitationId(e.id);
4693
+ return eventCitationId === citationId;
4694
+ });
4695
+ if (!event) {
4696
+ return c.json({ error: "Citation not found" }, 404);
4697
+ }
4698
+ const sessionEvents = recentEvents.filter((e) => e.sessionId === event.sessionId).sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
4699
+ const eventIndex = sessionEvents.findIndex((e) => e.id === event.id);
4700
+ const prev = eventIndex > 0 ? sessionEvents[eventIndex - 1] : null;
4701
+ const next = eventIndex < sessionEvents.length - 1 ? sessionEvents[eventIndex + 1] : null;
4702
+ return c.json({
4703
+ previous: prev ? {
4704
+ citationId: generateCitationId(prev.id),
4705
+ eventType: prev.eventType,
4706
+ timestamp: prev.timestamp,
4707
+ preview: prev.content.slice(0, 100) + (prev.content.length > 100 ? "..." : "")
4708
+ } : null,
4709
+ next: next ? {
4710
+ citationId: generateCitationId(next.id),
4711
+ eventType: next.eventType,
4712
+ timestamp: next.timestamp,
4713
+ preview: next.content.slice(0, 100) + (next.content.length > 100 ? "..." : "")
4714
+ } : null
4715
+ });
4716
+ } catch (error) {
4717
+ return c.json({ error: error.message }, 500);
4718
+ } finally {
4719
+ await memoryService.shutdown();
4720
+ }
4721
+ });
4722
+
4723
+ // src/server/api/index.ts
4724
+ var apiRouter = new Hono6().route("/sessions", sessionsRouter).route("/events", eventsRouter).route("/search", searchRouter).route("/stats", statsRouter).route("/citations", citationsRouter);
4725
+ export {
4726
+ apiRouter
4727
+ };
4728
+ //# sourceMappingURL=index.js.map