claude-memory-layer 1.0.24 → 1.0.25

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 (40) hide show
  1. package/.claude/settings.local.json +15 -1
  2. package/dist/cli/index.js +152 -969
  3. package/dist/cli/index.js.map +4 -4
  4. package/dist/core/index.js +31 -66
  5. package/dist/core/index.js.map +3 -3
  6. package/dist/hooks/post-tool-use.js +181 -967
  7. package/dist/hooks/post-tool-use.js.map +4 -4
  8. package/dist/hooks/semantic-daemon.js +148 -965
  9. package/dist/hooks/semantic-daemon.js.map +4 -4
  10. package/dist/hooks/session-end.js +148 -965
  11. package/dist/hooks/session-end.js.map +4 -4
  12. package/dist/hooks/session-start.js +150 -965
  13. package/dist/hooks/session-start.js.map +4 -4
  14. package/dist/hooks/stop.js +156 -965
  15. package/dist/hooks/stop.js.map +4 -4
  16. package/dist/hooks/user-prompt-submit.js +150 -967
  17. package/dist/hooks/user-prompt-submit.js.map +4 -4
  18. package/dist/server/api/index.js +148 -965
  19. package/dist/server/api/index.js.map +4 -4
  20. package/dist/server/index.js +148 -965
  21. package/dist/server/index.js.map +4 -4
  22. package/dist/services/memory-service.js +148 -965
  23. package/dist/services/memory-service.js.map +4 -4
  24. package/memory/agent_response/uncategorized/2026-03-04.md +217 -1
  25. package/memory/session_summary/uncategorized/2026-03-04.md +20 -1
  26. package/memory/tool_observation/uncategorized/2026-03-04.md +237 -1
  27. package/memory/user_prompt/uncategorized/2026-03-04.md +185 -1
  28. package/package.json +1 -2
  29. package/specs/memory-utilization-improvements/context.md +145 -0
  30. package/specs/memory-utilization-improvements/plan.md +361 -0
  31. package/specs/memory-utilization-improvements/spec.md +308 -0
  32. package/specs/optional-duckdb/context.md +77 -0
  33. package/specs/optional-duckdb/plan.md +142 -0
  34. package/specs/optional-duckdb/spec.md +35 -0
  35. package/src/core/db-wrapper.ts +18 -73
  36. package/src/core/sqlite-event-store.ts +24 -0
  37. package/src/hooks/post-tool-use.ts +25 -0
  38. package/src/hooks/session-start.ts +4 -0
  39. package/src/hooks/stop.ts +14 -0
  40. package/src/services/memory-service.ts +62 -58
@@ -28,744 +28,31 @@ import * as os from "os";
28
28
  import * as fs4 from "fs";
29
29
  import * as crypto2 from "crypto";
30
30
 
31
- // src/core/event-store.ts
32
- import { randomUUID } from "crypto";
33
-
34
- // src/core/canonical-key.ts
35
- import { createHash } from "crypto";
36
- var MAX_KEY_LENGTH = 200;
37
- function makeCanonicalKey(title, context) {
38
- let normalized = title.normalize("NFKC");
39
- normalized = normalized.toLowerCase();
40
- normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, "");
41
- normalized = normalized.replace(/\s+/g, " ").trim();
42
- let key = normalized;
43
- if (context?.project) {
44
- key = `${context.project}::${key}`;
45
- }
46
- if (key.length > MAX_KEY_LENGTH) {
47
- const hashSuffix = createHash("md5").update(key).digest("hex").slice(0, 8);
48
- key = key.slice(0, MAX_KEY_LENGTH - 9) + "_" + hashSuffix;
49
- }
50
- return key;
51
- }
52
- function makeDedupeKey(content, sessionId) {
53
- const contentHash = createHash("sha256").update(content).digest("hex");
54
- return `${sessionId}:${contentHash}`;
55
- }
56
-
57
- // src/core/db-wrapper.ts
58
- import duckdb from "duckdb";
59
- function convertBigInts(obj) {
60
- if (obj === null || obj === void 0)
61
- return obj;
62
- if (typeof obj === "bigint")
63
- return Number(obj);
64
- if (obj instanceof Date)
65
- return obj;
66
- if (Array.isArray(obj))
67
- return obj.map(convertBigInts);
68
- if (typeof obj === "object") {
69
- const result = {};
70
- for (const [key, value] of Object.entries(obj)) {
71
- result[key] = convertBigInts(value);
72
- }
73
- return result;
74
- }
75
- return obj;
76
- }
77
- function toDate(value) {
78
- if (value instanceof Date)
79
- return value;
80
- if (typeof value === "string")
81
- return new Date(value);
82
- if (typeof value === "number")
83
- return new Date(value);
84
- return new Date(String(value));
85
- }
86
- function createDatabase(path7, options) {
87
- if (options?.readOnly) {
88
- return new duckdb.Database(path7, { access_mode: "READ_ONLY" });
89
- }
90
- return new duckdb.Database(path7);
91
- }
92
- function dbRun(db, sql, params = []) {
93
- return new Promise((resolve3, reject) => {
94
- if (params.length === 0) {
95
- db.run(sql, (err) => {
96
- if (err)
97
- reject(err);
98
- else
99
- resolve3();
100
- });
101
- } else {
102
- db.run(sql, ...params, (err) => {
103
- if (err)
104
- reject(err);
105
- else
106
- resolve3();
107
- });
108
- }
109
- });
110
- }
111
- function dbAll(db, sql, params = []) {
112
- return new Promise((resolve3, reject) => {
113
- if (params.length === 0) {
114
- db.all(sql, (err, rows) => {
115
- if (err)
116
- reject(err);
117
- else
118
- resolve3(convertBigInts(rows || []));
119
- });
120
- } else {
121
- db.all(sql, ...params, (err, rows) => {
122
- if (err)
123
- reject(err);
124
- else
125
- resolve3(convertBigInts(rows || []));
126
- });
127
- }
128
- });
129
- }
130
- function dbClose(db) {
131
- return new Promise((resolve3, reject) => {
132
- db.close((err) => {
133
- if (err)
134
- reject(err);
135
- else
136
- resolve3();
137
- });
138
- });
139
- }
140
-
141
- // src/core/event-store.ts
142
- var EventStore = class {
143
- constructor(dbPath, options) {
144
- this.dbPath = dbPath;
145
- this.readOnly = options?.readOnly ?? false;
146
- this.db = createDatabase(dbPath, { readOnly: this.readOnly });
147
- }
148
- db;
149
- initialized = false;
150
- readOnly;
151
- /**
152
- * Initialize database schema
153
- */
154
- async initialize() {
155
- if (this.initialized)
156
- return;
157
- if (this.readOnly) {
158
- this.initialized = true;
159
- return;
160
- }
161
- await dbRun(this.db, `
162
- CREATE TABLE IF NOT EXISTS events (
163
- id VARCHAR PRIMARY KEY,
164
- event_type VARCHAR NOT NULL,
165
- session_id VARCHAR NOT NULL,
166
- timestamp TIMESTAMP NOT NULL,
167
- content TEXT NOT NULL,
168
- canonical_key VARCHAR NOT NULL,
169
- dedupe_key VARCHAR UNIQUE,
170
- metadata JSON
171
- )
172
- `);
173
- await dbRun(this.db, `
174
- CREATE TABLE IF NOT EXISTS event_dedup (
175
- dedupe_key VARCHAR PRIMARY KEY,
176
- event_id VARCHAR NOT NULL,
177
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
178
- )
179
- `);
180
- await dbRun(this.db, `
181
- CREATE TABLE IF NOT EXISTS sessions (
182
- id VARCHAR PRIMARY KEY,
183
- started_at TIMESTAMP NOT NULL,
184
- ended_at TIMESTAMP,
185
- project_path VARCHAR,
186
- summary TEXT,
187
- tags JSON
188
- )
189
- `);
190
- await dbRun(this.db, `
191
- CREATE TABLE IF NOT EXISTS insights (
192
- id VARCHAR PRIMARY KEY,
193
- insight_type VARCHAR NOT NULL,
194
- content TEXT NOT NULL,
195
- canonical_key VARCHAR NOT NULL,
196
- confidence FLOAT,
197
- source_events JSON,
198
- created_at TIMESTAMP,
199
- last_updated TIMESTAMP
200
- )
201
- `);
202
- await dbRun(this.db, `
203
- CREATE TABLE IF NOT EXISTS embedding_outbox (
204
- id VARCHAR PRIMARY KEY,
205
- event_id VARCHAR NOT NULL,
206
- content TEXT NOT NULL,
207
- status VARCHAR DEFAULT 'pending',
208
- retry_count INT DEFAULT 0,
209
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
210
- processed_at TIMESTAMP,
211
- error_message TEXT
212
- )
213
- `);
214
- await dbRun(this.db, `
215
- CREATE TABLE IF NOT EXISTS projection_offsets (
216
- projection_name VARCHAR PRIMARY KEY,
217
- last_event_id VARCHAR,
218
- last_timestamp TIMESTAMP,
219
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
220
- )
221
- `);
222
- await dbRun(this.db, `
223
- CREATE TABLE IF NOT EXISTS memory_levels (
224
- event_id VARCHAR PRIMARY KEY,
225
- level VARCHAR NOT NULL DEFAULT 'L0',
226
- promoted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
227
- )
228
- `);
229
- await dbRun(this.db, `
230
- CREATE TABLE IF NOT EXISTS entries (
231
- entry_id VARCHAR PRIMARY KEY,
232
- created_ts TIMESTAMP NOT NULL,
233
- entry_type VARCHAR NOT NULL,
234
- title VARCHAR NOT NULL,
235
- content_json JSON NOT NULL,
236
- stage VARCHAR NOT NULL DEFAULT 'raw',
237
- status VARCHAR DEFAULT 'active',
238
- superseded_by VARCHAR,
239
- build_id VARCHAR,
240
- evidence_json JSON,
241
- canonical_key VARCHAR,
242
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
243
- )
244
- `);
245
- await dbRun(this.db, `
246
- CREATE TABLE IF NOT EXISTS entities (
247
- entity_id VARCHAR PRIMARY KEY,
248
- entity_type VARCHAR NOT NULL,
249
- canonical_key VARCHAR NOT NULL,
250
- title VARCHAR NOT NULL,
251
- stage VARCHAR NOT NULL DEFAULT 'raw',
252
- status VARCHAR NOT NULL DEFAULT 'active',
253
- current_json JSON NOT NULL,
254
- title_norm VARCHAR,
255
- search_text VARCHAR,
256
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
257
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
258
- )
259
- `);
260
- await dbRun(this.db, `
261
- CREATE TABLE IF NOT EXISTS entity_aliases (
262
- entity_type VARCHAR NOT NULL,
263
- canonical_key VARCHAR NOT NULL,
264
- entity_id VARCHAR NOT NULL,
265
- is_primary BOOLEAN DEFAULT FALSE,
266
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
267
- PRIMARY KEY(entity_type, canonical_key)
268
- )
269
- `);
270
- await dbRun(this.db, `
271
- CREATE TABLE IF NOT EXISTS edges (
272
- edge_id VARCHAR PRIMARY KEY,
273
- src_type VARCHAR NOT NULL,
274
- src_id VARCHAR NOT NULL,
275
- rel_type VARCHAR NOT NULL,
276
- dst_type VARCHAR NOT NULL,
277
- dst_id VARCHAR NOT NULL,
278
- meta_json JSON,
279
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
280
- )
281
- `);
282
- await dbRun(this.db, `
283
- CREATE TABLE IF NOT EXISTS vector_outbox (
284
- job_id VARCHAR PRIMARY KEY,
285
- item_kind VARCHAR NOT NULL,
286
- item_id VARCHAR NOT NULL,
287
- embedding_version VARCHAR NOT NULL,
288
- status VARCHAR NOT NULL DEFAULT 'pending',
289
- retry_count INT DEFAULT 0,
290
- error VARCHAR,
291
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
292
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
293
- UNIQUE(item_kind, item_id, embedding_version)
294
- )
295
- `);
296
- await dbRun(this.db, `
297
- CREATE TABLE IF NOT EXISTS build_runs (
298
- build_id VARCHAR PRIMARY KEY,
299
- started_at TIMESTAMP NOT NULL,
300
- finished_at TIMESTAMP,
301
- extractor_model VARCHAR NOT NULL,
302
- extractor_prompt_hash VARCHAR NOT NULL,
303
- embedder_model VARCHAR NOT NULL,
304
- embedding_version VARCHAR NOT NULL,
305
- idris_version VARCHAR NOT NULL,
306
- schema_version VARCHAR NOT NULL,
307
- status VARCHAR NOT NULL DEFAULT 'running',
308
- error VARCHAR
309
- )
310
- `);
311
- await dbRun(this.db, `
312
- CREATE TABLE IF NOT EXISTS pipeline_metrics (
313
- id VARCHAR PRIMARY KEY,
314
- ts TIMESTAMP NOT NULL,
315
- stage VARCHAR NOT NULL,
316
- latency_ms DOUBLE NOT NULL,
317
- success BOOLEAN NOT NULL,
318
- error VARCHAR,
319
- session_id VARCHAR
320
- )
321
- `);
322
- await dbRun(this.db, `
323
- CREATE TABLE IF NOT EXISTS working_set (
324
- id VARCHAR PRIMARY KEY,
325
- event_id VARCHAR NOT NULL,
326
- added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
327
- relevance_score FLOAT DEFAULT 1.0,
328
- topics JSON,
329
- expires_at TIMESTAMP
330
- )
331
- `);
332
- await dbRun(this.db, `
333
- CREATE TABLE IF NOT EXISTS consolidated_memories (
334
- memory_id VARCHAR PRIMARY KEY,
335
- summary TEXT NOT NULL,
336
- topics JSON,
337
- source_events JSON,
338
- confidence FLOAT DEFAULT 0.5,
339
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
340
- accessed_at TIMESTAMP,
341
- access_count INTEGER DEFAULT 0
342
- )
343
- `);
344
- await dbRun(this.db, `
345
- CREATE TABLE IF NOT EXISTS continuity_log (
346
- log_id VARCHAR PRIMARY KEY,
347
- from_context_id VARCHAR,
348
- to_context_id VARCHAR,
349
- continuity_score FLOAT,
350
- transition_type VARCHAR,
351
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
352
- )
353
- `);
354
- await dbRun(this.db, `
355
- CREATE TABLE IF NOT EXISTS consolidated_rules (
356
- rule_id VARCHAR PRIMARY KEY,
357
- rule TEXT NOT NULL,
358
- topics JSON,
359
- source_memory_ids JSON,
360
- source_events JSON,
361
- confidence FLOAT DEFAULT 0.5,
362
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
363
- )
364
- `);
365
- await dbRun(this.db, `
366
- CREATE TABLE IF NOT EXISTS endless_config (
367
- key VARCHAR PRIMARY KEY,
368
- value JSON,
369
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
370
- )
371
- `);
372
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_type ON entries(entry_type)`);
373
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_stage ON entries(stage)`);
374
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_canonical ON entries(canonical_key)`);
375
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entities_type_key ON entities(entity_type, canonical_key)`);
376
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entities_status ON entities(status)`);
377
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src_id, rel_type)`);
378
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_dst ON edges(dst_id, rel_type)`);
379
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_rel ON edges(rel_type)`);
380
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_outbox_status ON vector_outbox(status)`);
381
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_expires ON working_set(expires_at)`);
382
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_relevance ON working_set(relevance_score DESC)`);
383
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence DESC)`);
384
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_rules_confidence ON consolidated_rules(confidence DESC)`);
385
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at)`);
386
- this.initialized = true;
387
- }
388
- /**
389
- * Append event to store (AXIOMMIND Principle 2: Append-only)
390
- * Returns existing event ID if duplicate (Principle 3: Idempotency)
391
- */
392
- async append(input) {
393
- await this.initialize();
394
- const canonicalKey = makeCanonicalKey(input.content);
395
- const dedupeKey = makeDedupeKey(input.content, input.sessionId);
396
- const existing = await dbAll(
397
- this.db,
398
- `SELECT event_id FROM event_dedup WHERE dedupe_key = ?`,
399
- [dedupeKey]
400
- );
401
- if (existing.length > 0) {
402
- return {
403
- success: true,
404
- eventId: existing[0].event_id,
405
- isDuplicate: true
406
- };
407
- }
408
- const id = randomUUID();
409
- const timestamp = input.timestamp.toISOString();
410
- try {
411
- await dbRun(
412
- this.db,
413
- `INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
414
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
415
- [
416
- id,
417
- input.eventType,
418
- input.sessionId,
419
- timestamp,
420
- input.content,
421
- canonicalKey,
422
- dedupeKey,
423
- JSON.stringify(input.metadata || {})
424
- ]
425
- );
426
- await dbRun(
427
- this.db,
428
- `INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)`,
429
- [dedupeKey, id]
430
- );
431
- await dbRun(
432
- this.db,
433
- `INSERT INTO memory_levels (event_id, level) VALUES (?, 'L0')`,
434
- [id]
435
- );
436
- return { success: true, eventId: id, isDuplicate: false };
437
- } catch (error) {
438
- return {
439
- success: false,
440
- error: error instanceof Error ? error.message : String(error)
441
- };
442
- }
443
- }
444
- /**
445
- * Get events by session ID
446
- */
447
- async getSessionEvents(sessionId) {
448
- await this.initialize();
449
- const rows = await dbAll(
450
- this.db,
451
- `SELECT * FROM events WHERE session_id = ? ORDER BY timestamp ASC`,
452
- [sessionId]
453
- );
454
- return rows.map(this.rowToEvent);
455
- }
456
- /**
457
- * Get recent events
458
- */
459
- async getRecentEvents(limit = 100) {
460
- await this.initialize();
461
- const rows = await dbAll(
462
- this.db,
463
- `SELECT * FROM events ORDER BY timestamp DESC LIMIT ?`,
464
- [limit]
465
- );
466
- return rows.map(this.rowToEvent);
467
- }
468
- /**
469
- * Get event by ID
470
- */
471
- async getEvent(id) {
472
- await this.initialize();
473
- const rows = await dbAll(
474
- this.db,
475
- `SELECT * FROM events WHERE id = ?`,
476
- [id]
477
- );
478
- if (rows.length === 0)
479
- return null;
480
- return this.rowToEvent(rows[0]);
481
- }
482
- /**
483
- * Create or update session
484
- */
485
- async upsertSession(session) {
486
- await this.initialize();
487
- const existing = await dbAll(
488
- this.db,
489
- `SELECT id FROM sessions WHERE id = ?`,
490
- [session.id]
491
- );
492
- if (existing.length === 0) {
493
- await dbRun(
494
- this.db,
495
- `INSERT INTO sessions (id, started_at, project_path, tags)
496
- VALUES (?, ?, ?, ?)`,
497
- [
498
- session.id,
499
- (session.startedAt || /* @__PURE__ */ new Date()).toISOString(),
500
- session.projectPath || null,
501
- JSON.stringify(session.tags || [])
502
- ]
503
- );
504
- } else {
505
- const updates = [];
506
- const values = [];
507
- if (session.endedAt) {
508
- updates.push("ended_at = ?");
509
- values.push(session.endedAt.toISOString());
510
- }
511
- if (session.summary) {
512
- updates.push("summary = ?");
513
- values.push(session.summary);
514
- }
515
- if (session.tags) {
516
- updates.push("tags = ?");
517
- values.push(JSON.stringify(session.tags));
518
- }
519
- if (updates.length > 0) {
520
- values.push(session.id);
521
- await dbRun(
522
- this.db,
523
- `UPDATE sessions SET ${updates.join(", ")} WHERE id = ?`,
524
- values
525
- );
526
- }
527
- }
528
- }
529
- /**
530
- * Get session by ID
531
- */
532
- async getSession(id) {
533
- await this.initialize();
534
- const rows = await dbAll(
535
- this.db,
536
- `SELECT * FROM sessions WHERE id = ?`,
537
- [id]
538
- );
539
- if (rows.length === 0)
540
- return null;
541
- const row = rows[0];
542
- return {
543
- id: row.id,
544
- startedAt: toDate(row.started_at),
545
- endedAt: row.ended_at ? toDate(row.ended_at) : void 0,
546
- projectPath: row.project_path,
547
- summary: row.summary,
548
- tags: row.tags ? JSON.parse(row.tags) : void 0
549
- };
550
- }
551
- /**
552
- * Add to embedding outbox (Single-Writer Pattern)
553
- */
554
- async enqueueForEmbedding(eventId, content) {
555
- await this.initialize();
556
- const id = randomUUID();
557
- await dbRun(
558
- this.db,
559
- `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
560
- VALUES (?, ?, ?, 'pending', 0)`,
561
- [id, eventId, content]
562
- );
563
- return id;
564
- }
565
- /**
566
- * Get pending outbox items
567
- */
568
- async getPendingOutboxItems(limit = 32) {
569
- await this.initialize();
570
- const pending = await dbAll(
571
- this.db,
572
- `SELECT * FROM embedding_outbox
573
- WHERE status = 'pending'
574
- ORDER BY created_at
575
- LIMIT ?`,
576
- [limit]
577
- );
578
- if (pending.length === 0)
579
- return [];
580
- const ids = pending.map((r) => r.id);
581
- const placeholders = ids.map(() => "?").join(",");
582
- await dbRun(
583
- this.db,
584
- `UPDATE embedding_outbox SET status = 'processing' WHERE id IN (${placeholders})`,
585
- ids
586
- );
587
- return pending.map((row) => ({
588
- id: row.id,
589
- eventId: row.event_id,
590
- content: row.content,
591
- status: "processing",
592
- retryCount: row.retry_count,
593
- createdAt: toDate(row.created_at),
594
- errorMessage: row.error_message
595
- }));
596
- }
597
- /**
598
- * Mark outbox items as done
599
- */
600
- async completeOutboxItems(ids) {
601
- if (ids.length === 0)
602
- return;
603
- const placeholders = ids.map(() => "?").join(",");
604
- await dbRun(
605
- this.db,
606
- `DELETE FROM embedding_outbox WHERE id IN (${placeholders})`,
607
- ids
608
- );
609
- }
610
- /**
611
- * Mark outbox items as failed
612
- */
613
- async failOutboxItems(ids, error) {
614
- if (ids.length === 0)
615
- return;
616
- const placeholders = ids.map(() => "?").join(",");
617
- await dbRun(
618
- this.db,
619
- `UPDATE embedding_outbox
620
- SET status = CASE WHEN retry_count >= 3 THEN 'failed' ELSE 'pending' END,
621
- retry_count = retry_count + 1,
622
- error_message = ?
623
- WHERE id IN (${placeholders})`,
624
- [error, ...ids]
625
- );
626
- }
627
- /**
628
- * Update memory level
629
- */
630
- async updateMemoryLevel(eventId, level) {
631
- await this.initialize();
632
- await dbRun(
633
- this.db,
634
- `UPDATE memory_levels SET level = ?, promoted_at = CURRENT_TIMESTAMP WHERE event_id = ?`,
635
- [level, eventId]
636
- );
637
- }
638
- /**
639
- * Get memory level statistics
640
- */
641
- async getLevelStats() {
642
- await this.initialize();
643
- const rows = await dbAll(
644
- this.db,
645
- `SELECT level, COUNT(*) as count FROM memory_levels GROUP BY level`
646
- );
647
- return rows;
648
- }
649
- /**
650
- * Get events by memory level
651
- */
652
- async getEventsByLevel(level, options) {
653
- await this.initialize();
654
- const limit = options?.limit || 50;
655
- const offset = options?.offset || 0;
656
- const rows = await dbAll(
657
- this.db,
658
- `SELECT e.* FROM events e
659
- INNER JOIN memory_levels ml ON e.id = ml.event_id
660
- WHERE ml.level = ?
661
- ORDER BY e.timestamp DESC
662
- LIMIT ? OFFSET ?`,
663
- [level, limit, offset]
664
- );
665
- return rows.map((row) => this.rowToEvent(row));
666
- }
667
- /**
668
- * Get memory level for a specific event
669
- */
670
- async getEventLevel(eventId) {
671
- await this.initialize();
672
- const rows = await dbAll(
673
- this.db,
674
- `SELECT level FROM memory_levels WHERE event_id = ?`,
675
- [eventId]
676
- );
677
- return rows.length > 0 ? rows[0].level : null;
678
- }
679
- // ============================================================
680
- // Endless Mode Helper Methods
681
- // ============================================================
682
- /**
683
- * Get database instance for Endless Mode stores
684
- */
685
- getDatabase() {
686
- return this.db;
687
- }
688
- /**
689
- * Get config value for endless mode
690
- */
691
- async getEndlessConfig(key) {
692
- await this.initialize();
693
- const rows = await dbAll(
694
- this.db,
695
- `SELECT value FROM endless_config WHERE key = ?`,
696
- [key]
697
- );
698
- if (rows.length === 0)
699
- return null;
700
- return JSON.parse(rows[0].value);
701
- }
702
- /**
703
- * Set config value for endless mode
704
- */
705
- async setEndlessConfig(key, value) {
706
- await this.initialize();
707
- await dbRun(
708
- this.db,
709
- `INSERT OR REPLACE INTO endless_config (key, value, updated_at)
710
- VALUES (?, ?, CURRENT_TIMESTAMP)`,
711
- [key, JSON.stringify(value)]
712
- );
713
- }
714
- /**
715
- * Get all sessions
716
- */
717
- async getAllSessions() {
718
- await this.initialize();
719
- const rows = await dbAll(
720
- this.db,
721
- `SELECT * FROM sessions ORDER BY started_at DESC`
722
- );
723
- return rows.map((row) => ({
724
- id: row.id,
725
- startedAt: toDate(row.started_at),
726
- endedAt: row.ended_at ? toDate(row.ended_at) : void 0,
727
- projectPath: row.project_path,
728
- summary: row.summary,
729
- tags: row.tags ? JSON.parse(row.tags) : void 0
730
- }));
731
- }
732
- /**
733
- * Increment access count for events (stub for compatibility)
734
- */
735
- async incrementAccessCount(eventIds) {
736
- return Promise.resolve();
737
- }
738
- /**
739
- * Get most accessed memories (stub for compatibility)
740
- */
741
- async getMostAccessed(limit = 10) {
742
- return [];
743
- }
744
- /**
745
- * Close database connection
746
- */
747
- async close() {
748
- await dbClose(this.db);
31
+ // src/core/sqlite-event-store.ts
32
+ import { randomUUID } from "crypto";
33
+
34
+ // src/core/canonical-key.ts
35
+ import { createHash } from "crypto";
36
+ var MAX_KEY_LENGTH = 200;
37
+ function makeCanonicalKey(title, context) {
38
+ let normalized = title.normalize("NFKC");
39
+ normalized = normalized.toLowerCase();
40
+ normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, "");
41
+ normalized = normalized.replace(/\s+/g, " ").trim();
42
+ let key = normalized;
43
+ if (context?.project) {
44
+ key = `${context.project}::${key}`;
749
45
  }
750
- /**
751
- * Convert database row to MemoryEvent
752
- */
753
- rowToEvent(row) {
754
- return {
755
- id: row.id,
756
- eventType: row.event_type,
757
- sessionId: row.session_id,
758
- timestamp: toDate(row.timestamp),
759
- content: row.content,
760
- canonicalKey: row.canonical_key,
761
- dedupeKey: row.dedupe_key,
762
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0
763
- };
46
+ if (key.length > MAX_KEY_LENGTH) {
47
+ const hashSuffix = createHash("md5").update(key).digest("hex").slice(0, 8);
48
+ key = key.slice(0, MAX_KEY_LENGTH - 9) + "_" + hashSuffix;
764
49
  }
765
- };
766
-
767
- // src/core/sqlite-event-store.ts
768
- import { randomUUID as randomUUID2 } from "crypto";
50
+ return key;
51
+ }
52
+ function makeDedupeKey(content, sessionId) {
53
+ const contentHash = createHash("sha256").update(content).digest("hex");
54
+ return `${sessionId}:${contentHash}`;
55
+ }
769
56
 
770
57
  // src/core/sqlite-wrapper.ts
771
58
  import Database from "better-sqlite3";
@@ -1280,7 +567,7 @@ var SQLiteEventStore = class {
1280
567
  isDuplicate: true
1281
568
  };
1282
569
  }
1283
- const id = randomUUID2();
570
+ const id = randomUUID();
1284
571
  const timestamp = toSQLiteTimestamp(input.timestamp);
1285
572
  try {
1286
573
  const metadata = input.metadata || {};
@@ -1334,6 +621,29 @@ var SQLiteEventStore = class {
1334
621
  };
1335
622
  }
1336
623
  }
624
+ /**
625
+ * Get session IDs that have events but no session_summary event.
626
+ * Used to backfill summaries for sessions that ended without Stop hook.
627
+ */
628
+ async getSessionsWithoutSummary(currentSessionId, limit = 5) {
629
+ await this.initialize();
630
+ const rows = sqliteAll(
631
+ this.db,
632
+ `SELECT DISTINCT e.session_id
633
+ FROM events e
634
+ WHERE e.session_id != ?
635
+ AND e.event_type != 'session_summary'
636
+ AND e.session_id NOT IN (
637
+ SELECT DISTINCT session_id FROM events WHERE event_type = 'session_summary'
638
+ )
639
+ GROUP BY e.session_id
640
+ HAVING COUNT(*) >= 3
641
+ ORDER BY MAX(e.timestamp) DESC
642
+ LIMIT ?`,
643
+ [currentSessionId, limit]
644
+ );
645
+ return rows.map((r) => r.session_id);
646
+ }
1337
647
  /**
1338
648
  * Get events by session ID
1339
649
  */
@@ -1561,7 +871,7 @@ var SQLiteEventStore = class {
1561
871
  */
1562
872
  async enqueueForEmbedding(eventId, content) {
1563
873
  await this.initialize();
1564
- const id = randomUUID2();
874
+ const id = randomUUID();
1565
875
  sqliteRun(
1566
876
  this.db,
1567
877
  `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
@@ -1842,7 +1152,7 @@ var SQLiteEventStore = class {
1842
1152
  if (this.readOnly)
1843
1153
  return;
1844
1154
  await this.initialize();
1845
- const id = randomUUID2();
1155
+ const id = randomUUID();
1846
1156
  sqliteRun(
1847
1157
  this.db,
1848
1158
  `INSERT INTO memory_helpfulness (id, event_id, session_id, retrieval_score, query_preview, created_at)
@@ -2063,7 +1373,7 @@ var SQLiteEventStore = class {
2063
1373
  }
2064
1374
  async recordRetrievalTrace(input) {
2065
1375
  await this.initialize();
2066
- const traceId = randomUUID2();
1376
+ const traceId = randomUUID();
2067
1377
  sqliteRun(
2068
1378
  this.db,
2069
1379
  `INSERT INTO retrieval_traces (
@@ -2317,169 +1627,6 @@ var SQLiteEventStore = class {
2317
1627
  }
2318
1628
  };
2319
1629
 
2320
- // src/core/sync-worker.ts
2321
- var DEFAULT_CONFIG = {
2322
- intervalMs: 3e4,
2323
- batchSize: 500,
2324
- maxRetries: 3,
2325
- retryDelayMs: 5e3
2326
- };
2327
- var SyncWorker = class {
2328
- constructor(sqliteStore, duckdbStore, config) {
2329
- this.sqliteStore = sqliteStore;
2330
- this.duckdbStore = duckdbStore;
2331
- this.config = { ...DEFAULT_CONFIG, ...config };
2332
- }
2333
- config;
2334
- intervalHandle = null;
2335
- running = false;
2336
- stats = {
2337
- lastSyncAt: null,
2338
- eventsSynced: 0,
2339
- sessionsSynced: 0,
2340
- errors: 0,
2341
- status: "idle"
2342
- };
2343
- /**
2344
- * Start the sync worker
2345
- */
2346
- start() {
2347
- if (this.running)
2348
- return;
2349
- this.running = true;
2350
- this.stats.status = "idle";
2351
- this.syncNow().catch((err) => {
2352
- console.error("[SyncWorker] Initial sync failed:", err);
2353
- });
2354
- this.intervalHandle = setInterval(() => {
2355
- this.syncNow().catch((err) => {
2356
- console.error("[SyncWorker] Periodic sync failed:", err);
2357
- });
2358
- }, this.config.intervalMs);
2359
- }
2360
- /**
2361
- * Stop the sync worker
2362
- */
2363
- stop() {
2364
- this.running = false;
2365
- this.stats.status = "stopped";
2366
- if (this.intervalHandle) {
2367
- clearInterval(this.intervalHandle);
2368
- this.intervalHandle = null;
2369
- }
2370
- }
2371
- /**
2372
- * Trigger immediate sync
2373
- */
2374
- async syncNow() {
2375
- if (this.stats.status === "syncing") {
2376
- return;
2377
- }
2378
- this.stats.status = "syncing";
2379
- try {
2380
- await this.syncEvents();
2381
- await this.syncSessions();
2382
- this.stats.lastSyncAt = /* @__PURE__ */ new Date();
2383
- this.stats.status = "idle";
2384
- } catch (error) {
2385
- this.stats.errors++;
2386
- this.stats.status = "error";
2387
- throw error;
2388
- }
2389
- }
2390
- /**
2391
- * Sync events from SQLite to DuckDB
2392
- */
2393
- async syncEvents() {
2394
- const targetName = "duckdb_analytics";
2395
- const position = await this.sqliteStore.getSyncPosition(targetName);
2396
- const lastTimestamp = position.lastTimestamp || "1970-01-01T00:00:00.000Z";
2397
- let hasMore = true;
2398
- let totalSynced = 0;
2399
- while (hasMore) {
2400
- const events = await this.sqliteStore.getEventsSince(lastTimestamp, this.config.batchSize);
2401
- if (events.length === 0) {
2402
- hasMore = false;
2403
- break;
2404
- }
2405
- await this.retryWithBackoff(async () => {
2406
- for (const event of events) {
2407
- await this.insertEventToDuckDB(event);
2408
- }
2409
- });
2410
- totalSynced += events.length;
2411
- const lastEvent = events[events.length - 1];
2412
- await this.sqliteStore.updateSyncPosition(
2413
- targetName,
2414
- lastEvent.id,
2415
- lastEvent.timestamp.toISOString()
2416
- );
2417
- hasMore = events.length === this.config.batchSize;
2418
- }
2419
- this.stats.eventsSynced += totalSynced;
2420
- }
2421
- /**
2422
- * Sync sessions from SQLite to DuckDB
2423
- */
2424
- async syncSessions() {
2425
- const sessions = await this.sqliteStore.getAllSessions();
2426
- for (const session of sessions) {
2427
- await this.retryWithBackoff(async () => {
2428
- await this.duckdbStore.upsertSession(session);
2429
- });
2430
- }
2431
- this.stats.sessionsSynced = sessions.length;
2432
- }
2433
- /**
2434
- * Insert a single event into DuckDB
2435
- */
2436
- async insertEventToDuckDB(event) {
2437
- await this.duckdbStore.append({
2438
- eventType: event.eventType,
2439
- sessionId: event.sessionId,
2440
- timestamp: event.timestamp,
2441
- content: event.content,
2442
- metadata: event.metadata
2443
- });
2444
- }
2445
- /**
2446
- * Retry operation with exponential backoff
2447
- */
2448
- async retryWithBackoff(fn) {
2449
- let lastError = null;
2450
- for (let attempt = 0; attempt < this.config.maxRetries; attempt++) {
2451
- try {
2452
- return await fn();
2453
- } catch (error) {
2454
- lastError = error instanceof Error ? error : new Error(String(error));
2455
- if (attempt < this.config.maxRetries - 1) {
2456
- const delay = this.config.retryDelayMs * Math.pow(2, attempt);
2457
- await this.sleep(delay);
2458
- }
2459
- }
2460
- }
2461
- throw lastError;
2462
- }
2463
- /**
2464
- * Sleep utility
2465
- */
2466
- sleep(ms) {
2467
- return new Promise((resolve3) => setTimeout(resolve3, ms));
2468
- }
2469
- /**
2470
- * Get sync statistics
2471
- */
2472
- getStats() {
2473
- return { ...this.stats };
2474
- }
2475
- /**
2476
- * Check if worker is running
2477
- */
2478
- isRunning() {
2479
- return this.running;
2480
- }
2481
- };
2482
-
2483
1630
  // src/core/vector-store.ts
2484
1631
  import * as lancedb from "@lancedb/lancedb";
2485
1632
  var VectorStore = class {
@@ -2767,8 +1914,34 @@ function getDefaultEmbedder() {
2767
1914
  return defaultEmbedder;
2768
1915
  }
2769
1916
 
1917
+ // src/core/db-wrapper.ts
1918
+ import BetterSqlite3 from "better-sqlite3";
1919
+ function toDate(value) {
1920
+ if (value instanceof Date)
1921
+ return value;
1922
+ if (typeof value === "string")
1923
+ return new Date(value);
1924
+ if (typeof value === "number")
1925
+ return new Date(value);
1926
+ return new Date(String(value));
1927
+ }
1928
+ function createDatabase(dbPath, options) {
1929
+ return new BetterSqlite3(dbPath, { readonly: options?.readOnly });
1930
+ }
1931
+ function dbRun(db, sql, params = []) {
1932
+ db.prepare(sql).run(...params);
1933
+ return Promise.resolve();
1934
+ }
1935
+ function dbAll(db, sql, params = []) {
1936
+ return Promise.resolve(db.prepare(sql).all(...params));
1937
+ }
1938
+ function dbClose(db) {
1939
+ db.close();
1940
+ return Promise.resolve();
1941
+ }
1942
+
2770
1943
  // src/core/vector-outbox.ts
2771
- var DEFAULT_CONFIG2 = {
1944
+ var DEFAULT_CONFIG = {
2772
1945
  embeddingVersion: "v1",
2773
1946
  maxRetries: 3,
2774
1947
  stuckThresholdMs: 5 * 60 * 1e3,
@@ -2777,7 +1950,7 @@ var DEFAULT_CONFIG2 = {
2777
1950
  };
2778
1951
 
2779
1952
  // src/core/vector-worker.ts
2780
- var DEFAULT_CONFIG3 = {
1953
+ var DEFAULT_CONFIG2 = {
2781
1954
  batchSize: 32,
2782
1955
  pollIntervalMs: 1e3,
2783
1956
  maxRetries: 3
@@ -2794,7 +1967,7 @@ var VectorWorker = class {
2794
1967
  this.eventStore = eventStore;
2795
1968
  this.vectorStore = vectorStore;
2796
1969
  this.embedder = embedder;
2797
- this.config = { ...DEFAULT_CONFIG3, ...config };
1970
+ this.config = { ...DEFAULT_CONFIG2, ...config };
2798
1971
  }
2799
1972
  /**
2800
1973
  * Start the worker polling loop
@@ -2915,7 +2088,7 @@ function createVectorWorker(eventStore, vectorStore, embedder, config) {
2915
2088
  }
2916
2089
 
2917
2090
  // src/core/matcher.ts
2918
- var DEFAULT_CONFIG4 = {
2091
+ var DEFAULT_CONFIG3 = {
2919
2092
  weights: {
2920
2093
  semanticSimilarity: 0.4,
2921
2094
  ftsScore: 0.25,
@@ -2930,9 +2103,9 @@ var Matcher = class {
2930
2103
  config;
2931
2104
  constructor(config = {}) {
2932
2105
  this.config = {
2933
- ...DEFAULT_CONFIG4,
2106
+ ...DEFAULT_CONFIG3,
2934
2107
  ...config,
2935
- weights: { ...DEFAULT_CONFIG4.weights, ...config.weights }
2108
+ weights: { ...DEFAULT_CONFIG3.weights, ...config.weights }
2936
2109
  };
2937
2110
  }
2938
2111
  /**
@@ -3922,7 +3095,7 @@ function createSharedEventStore(dbPath) {
3922
3095
  }
3923
3096
 
3924
3097
  // src/core/shared-store.ts
3925
- import { randomUUID as randomUUID3 } from "crypto";
3098
+ import { randomUUID as randomUUID2 } from "crypto";
3926
3099
  var SharedStore = class {
3927
3100
  constructor(sharedEventStore) {
3928
3101
  this.sharedEventStore = sharedEventStore;
@@ -3934,7 +3107,7 @@ var SharedStore = class {
3934
3107
  * Promote a verified troubleshooting entry to shared storage
3935
3108
  */
3936
3109
  async promoteEntry(input) {
3937
- const entryId = randomUUID3();
3110
+ const entryId = randomUUID2();
3938
3111
  await dbRun(
3939
3112
  this.db,
3940
3113
  `INSERT INTO shared_troubleshooting (
@@ -4299,7 +3472,7 @@ function createSharedVectorStore(dbPath) {
4299
3472
  }
4300
3473
 
4301
3474
  // src/core/shared-promoter.ts
4302
- import { randomUUID as randomUUID4 } from "crypto";
3475
+ import { randomUUID as randomUUID3 } from "crypto";
4303
3476
  var SharedPromoter = class {
4304
3477
  constructor(sharedStore, sharedVectorStore, embedder, config) {
4305
3478
  this.sharedStore = sharedStore;
@@ -4367,7 +3540,7 @@ var SharedPromoter = class {
4367
3540
  const embeddingContent = this.createEmbeddingContent(input);
4368
3541
  const embedding = await this.embedder.embed(embeddingContent);
4369
3542
  await this.sharedVectorStore.upsert({
4370
- id: randomUUID4(),
3543
+ id: randomUUID3(),
4371
3544
  entryId,
4372
3545
  entryType: "troubleshooting",
4373
3546
  content: embeddingContent,
@@ -4507,7 +3680,7 @@ function createToolObservationEmbedding(toolName, metadata, success) {
4507
3680
  }
4508
3681
 
4509
3682
  // src/core/working-set-store.ts
4510
- import { randomUUID as randomUUID5 } from "crypto";
3683
+ import { randomUUID as randomUUID4 } from "crypto";
4511
3684
  var WorkingSetStore = class {
4512
3685
  constructor(eventStore, config) {
4513
3686
  this.eventStore = eventStore;
@@ -4528,7 +3701,7 @@ var WorkingSetStore = class {
4528
3701
  `INSERT OR REPLACE INTO working_set (id, event_id, added_at, relevance_score, topics, expires_at)
4529
3702
  VALUES (?, ?, CURRENT_TIMESTAMP, ?, ?, ?)`,
4530
3703
  [
4531
- randomUUID5(),
3704
+ randomUUID4(),
4532
3705
  eventId,
4533
3706
  relevanceScore,
4534
3707
  JSON.stringify(topics || []),
@@ -4712,7 +3885,7 @@ function createWorkingSetStore(eventStore, config) {
4712
3885
  }
4713
3886
 
4714
3887
  // src/core/consolidated-store.ts
4715
- import { randomUUID as randomUUID6 } from "crypto";
3888
+ import { randomUUID as randomUUID5 } from "crypto";
4716
3889
  var ConsolidatedStore = class {
4717
3890
  constructor(eventStore) {
4718
3891
  this.eventStore = eventStore;
@@ -4724,7 +3897,7 @@ var ConsolidatedStore = class {
4724
3897
  * Create a new consolidated memory
4725
3898
  */
4726
3899
  async create(input) {
4727
- const memoryId = randomUUID6();
3900
+ const memoryId = randomUUID5();
4728
3901
  await dbRun(
4729
3902
  this.db,
4730
3903
  `INSERT INTO consolidated_memories
@@ -4854,7 +4027,7 @@ var ConsolidatedStore = class {
4854
4027
  * Create a long-term rule promoted from stable summaries
4855
4028
  */
4856
4029
  async createRule(input) {
4857
- const ruleId = randomUUID6();
4030
+ const ruleId = randomUUID5();
4858
4031
  await dbRun(
4859
4032
  this.db,
4860
4033
  `INSERT INTO consolidated_rules
@@ -5376,7 +4549,7 @@ function createConsolidationWorker(workingSetStore, consolidatedStore, config) {
5376
4549
  }
5377
4550
 
5378
4551
  // src/core/continuity-manager.ts
5379
- import { randomUUID as randomUUID7 } from "crypto";
4552
+ import { randomUUID as randomUUID6 } from "crypto";
5380
4553
  var ContinuityManager = class {
5381
4554
  constructor(eventStore, config) {
5382
4555
  this.eventStore = eventStore;
@@ -5530,7 +4703,7 @@ var ContinuityManager = class {
5530
4703
  `INSERT INTO continuity_log
5531
4704
  (log_id, from_context_id, to_context_id, continuity_score, transition_type, created_at)
5532
4705
  VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
5533
- [randomUUID7(), previous.id, current.id, score, type]
4706
+ [randomUUID6(), previous.id, current.id, score, type]
5534
4707
  );
5535
4708
  }
5536
4709
  /**
@@ -5639,7 +4812,7 @@ function createContinuityManager(eventStore, config) {
5639
4812
  }
5640
4813
 
5641
4814
  // src/core/graduation-worker.ts
5642
- var DEFAULT_CONFIG5 = {
4815
+ var DEFAULT_CONFIG4 = {
5643
4816
  evaluationIntervalMs: 3e5,
5644
4817
  // 5 minutes
5645
4818
  batchSize: 50,
@@ -5647,7 +4820,7 @@ var DEFAULT_CONFIG5 = {
5647
4820
  // 1 hour cooldown between evaluations
5648
4821
  };
5649
4822
  var GraduationWorker = class {
5650
- constructor(eventStore, graduation, config = DEFAULT_CONFIG5) {
4823
+ constructor(eventStore, graduation, config = DEFAULT_CONFIG4) {
5651
4824
  this.eventStore = eventStore;
5652
4825
  this.graduation = graduation;
5653
4826
  this.config = config;
@@ -5755,7 +4928,7 @@ function createGraduationWorker(eventStore, graduation, config) {
5755
4928
  return new GraduationWorker(
5756
4929
  eventStore,
5757
4930
  graduation,
5758
- { ...DEFAULT_CONFIG5, ...config }
4931
+ { ...DEFAULT_CONFIG4, ...config }
5759
4932
  );
5760
4933
  }
5761
4934
 
@@ -5964,9 +5137,6 @@ function loadSessionRegistry() {
5964
5137
  var MemoryService = class {
5965
5138
  // Primary store: SQLite (WAL mode) - for hooks, always available
5966
5139
  sqliteStore;
5967
- // Analytics store: DuckDB - for server reads (optional, synced from SQLite)
5968
- analyticsStore;
5969
- syncWorker = null;
5970
5140
  vectorStore;
5971
5141
  embedder;
5972
5142
  matcher;
@@ -6015,24 +5185,6 @@ var MemoryService = class {
6015
5185
  markdownMirrorRoot: storagePath
6016
5186
  }
6017
5187
  );
6018
- const analyticsEnabled = config.analyticsEnabled ?? this.readOnly;
6019
- if (!analyticsEnabled) {
6020
- this.analyticsStore = null;
6021
- } else if (this.readOnly) {
6022
- try {
6023
- this.analyticsStore = new EventStore(
6024
- path3.join(storagePath, "analytics.duckdb"),
6025
- { readOnly: true }
6026
- );
6027
- } catch {
6028
- this.analyticsStore = null;
6029
- }
6030
- } else {
6031
- this.analyticsStore = new EventStore(
6032
- path3.join(storagePath, "analytics.duckdb"),
6033
- { readOnly: false }
6034
- );
6035
- }
6036
5188
  this.vectorStore = new VectorStore(path3.join(storagePath, "vectors"));
6037
5189
  const embeddingModel = config.embeddingModel || process.env.CLAUDE_MEMORY_EMBEDDING_MODEL;
6038
5190
  this.embedder = embeddingModel ? new Embedder(embeddingModel) : getDefaultEmbedder();
@@ -6058,13 +5210,6 @@ var MemoryService = class {
6058
5210
  this.initialized = true;
6059
5211
  return;
6060
5212
  }
6061
- if (this.analyticsStore) {
6062
- try {
6063
- await this.analyticsStore.initialize();
6064
- } catch (error) {
6065
- console.warn("[MemoryService] Analytics store (DuckDB) initialization failed, using SQLite for reads:", error);
6066
- }
6067
- }
6068
5213
  await this.vectorStore.initialize();
6069
5214
  await this.embedder.initialize();
6070
5215
  if (!this.readOnly) {
@@ -6081,14 +5226,6 @@ var MemoryService = class {
6081
5226
  this.graduation
6082
5227
  );
6083
5228
  this.graduationWorker.start();
6084
- if (this.analyticsStore) {
6085
- this.syncWorker = new SyncWorker(
6086
- this.sqliteStore,
6087
- this.analyticsStore,
6088
- { intervalMs: 3e4, batchSize: 500 }
6089
- );
6090
- this.syncWorker.start();
6091
- }
6092
5229
  }
6093
5230
  const savedMode = await this.sqliteStore.getEndlessConfig("mode");
6094
5231
  if (savedMode === "endless") {
@@ -6285,6 +5422,57 @@ var MemoryService = class {
6285
5422
  }
6286
5423
  );
6287
5424
  }
5425
+ /**
5426
+ * Backfill session summaries for recent sessions that are missing them.
5427
+ * Called from session-start hook to catch sessions that ended without Stop hook.
5428
+ */
5429
+ async backfillMissingSummaries(currentSessionId, limit = 5) {
5430
+ await this.initialize();
5431
+ const recentSessionIds = await this.sqliteStore.getSessionsWithoutSummary(currentSessionId, limit);
5432
+ for (const sid of recentSessionIds) {
5433
+ try {
5434
+ await this.generateSessionSummary(sid);
5435
+ } catch {
5436
+ }
5437
+ }
5438
+ }
5439
+ /**
5440
+ * Generate a rule-based session summary from stored events.
5441
+ * Called at session end (Stop hook) when no LLM-generated summary exists.
5442
+ * Skips if a summary already exists for this session.
5443
+ */
5444
+ async generateSessionSummary(sessionId) {
5445
+ await this.initialize();
5446
+ const events = await this.sqliteStore.getSessionEvents(sessionId);
5447
+ if (events.length < 3)
5448
+ return;
5449
+ const hasSummary = events.some((e) => e.eventType === "session_summary");
5450
+ if (hasSummary)
5451
+ return;
5452
+ const prompts = events.filter((e) => e.eventType === "user_prompt");
5453
+ const toolObs = events.filter((e) => e.eventType === "tool_observation");
5454
+ const toolNames = [...new Set(
5455
+ toolObs.map((e) => e.metadata?.toolName).filter(Boolean)
5456
+ )];
5457
+ const errorObs = toolObs.filter((e) => {
5458
+ const meta = e.metadata;
5459
+ return meta?.exitCode !== void 0 && meta.exitCode !== 0;
5460
+ });
5461
+ const datePart = events[0].timestamp.toISOString().split("T")[0];
5462
+ const parts = [`[${datePart}] ${prompts.length}\uD134 \uC138\uC158.`];
5463
+ if (prompts.length > 0) {
5464
+ const firstPrompt = prompts[0].content.slice(0, 120).replace(/\n/g, " ");
5465
+ parts.push(`\uC8FC\uC694 \uC791\uC5C5: ${firstPrompt}`);
5466
+ }
5467
+ if (toolNames.length > 0) {
5468
+ parts.push(`\uC0AC\uC6A9 \uD234: ${toolNames.slice(0, 6).join(", ")}`);
5469
+ }
5470
+ if (errorObs.length > 0) {
5471
+ parts.push(`\uC624\uB958 ${errorObs.length}\uAC74 \uBC1C\uC0DD`);
5472
+ }
5473
+ const summary = parts.join(". ");
5474
+ await this.storeSessionSummary(sessionId, summary, { generated: "rule-based", eventCount: events.length });
5475
+ }
6288
5476
  /**
6289
5477
  * Store a tool observation
6290
5478
  */
@@ -6820,6 +6008,7 @@ var MemoryService = class {
6820
6008
  await this.initialize();
6821
6009
  await this.sqliteStore.recordRetrievalTrace({
6822
6010
  ...input,
6011
+ projectHash: this.projectHash || void 0,
6823
6012
  candidateDetails: [],
6824
6013
  selectedDetails: [],
6825
6014
  fallbackTrace: []
@@ -7110,16 +6299,10 @@ var MemoryService = class {
7110
6299
  if (this.vectorWorker) {
7111
6300
  this.vectorWorker.stop();
7112
6301
  }
7113
- if (this.syncWorker) {
7114
- this.syncWorker.stop();
7115
- }
7116
6302
  if (this.sharedEventStore) {
7117
6303
  await this.sharedEventStore.close();
7118
6304
  }
7119
6305
  await this.sqliteStore.close();
7120
- if (this.analyticsStore) {
7121
- await this.analyticsStore.close();
7122
- }
7123
6306
  }
7124
6307
  /**
7125
6308
  * Expand ~ to home directory