claude-memory-layer 1.0.6 → 1.0.8

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