claude-memory-layer 1.0.5 → 1.0.7

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