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
@@ -37,744 +37,31 @@ import * as os from "os";
37
37
  import * as fs4 from "fs";
38
38
  import * as crypto2 from "crypto";
39
39
 
40
- // src/core/event-store.ts
41
- import { randomUUID } from "crypto";
42
-
43
- // src/core/canonical-key.ts
44
- import { createHash } from "crypto";
45
- var MAX_KEY_LENGTH = 200;
46
- function makeCanonicalKey(title, context) {
47
- let normalized = title.normalize("NFKC");
48
- normalized = normalized.toLowerCase();
49
- normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, "");
50
- normalized = normalized.replace(/\s+/g, " ").trim();
51
- let key = normalized;
52
- if (context?.project) {
53
- key = `${context.project}::${key}`;
54
- }
55
- if (key.length > MAX_KEY_LENGTH) {
56
- const hashSuffix = createHash("md5").update(key).digest("hex").slice(0, 8);
57
- key = key.slice(0, MAX_KEY_LENGTH - 9) + "_" + hashSuffix;
58
- }
59
- return key;
60
- }
61
- function makeDedupeKey(content, sessionId) {
62
- const contentHash = createHash("sha256").update(content).digest("hex");
63
- return `${sessionId}:${contentHash}`;
64
- }
65
-
66
- // src/core/db-wrapper.ts
67
- import duckdb from "duckdb";
68
- function convertBigInts(obj) {
69
- if (obj === null || obj === void 0)
70
- return obj;
71
- if (typeof obj === "bigint")
72
- return Number(obj);
73
- if (obj instanceof Date)
74
- return obj;
75
- if (Array.isArray(obj))
76
- return obj.map(convertBigInts);
77
- if (typeof obj === "object") {
78
- const result = {};
79
- for (const [key, value] of Object.entries(obj)) {
80
- result[key] = convertBigInts(value);
81
- }
82
- return result;
83
- }
84
- return obj;
85
- }
86
- function toDate(value) {
87
- if (value instanceof Date)
88
- return value;
89
- if (typeof value === "string")
90
- return new Date(value);
91
- if (typeof value === "number")
92
- return new Date(value);
93
- return new Date(String(value));
94
- }
95
- function createDatabase(path8, options) {
96
- if (options?.readOnly) {
97
- return new duckdb.Database(path8, { access_mode: "READ_ONLY" });
98
- }
99
- return new duckdb.Database(path8);
100
- }
101
- function dbRun(db, sql, params = []) {
102
- return new Promise((resolve3, reject) => {
103
- if (params.length === 0) {
104
- db.run(sql, (err) => {
105
- if (err)
106
- reject(err);
107
- else
108
- resolve3();
109
- });
110
- } else {
111
- db.run(sql, ...params, (err) => {
112
- if (err)
113
- reject(err);
114
- else
115
- resolve3();
116
- });
117
- }
118
- });
119
- }
120
- function dbAll(db, sql, params = []) {
121
- return new Promise((resolve3, reject) => {
122
- if (params.length === 0) {
123
- db.all(sql, (err, rows) => {
124
- if (err)
125
- reject(err);
126
- else
127
- resolve3(convertBigInts(rows || []));
128
- });
129
- } else {
130
- db.all(sql, ...params, (err, rows) => {
131
- if (err)
132
- reject(err);
133
- else
134
- resolve3(convertBigInts(rows || []));
135
- });
136
- }
137
- });
138
- }
139
- function dbClose(db) {
140
- return new Promise((resolve3, reject) => {
141
- db.close((err) => {
142
- if (err)
143
- reject(err);
144
- else
145
- resolve3();
146
- });
147
- });
148
- }
149
-
150
- // src/core/event-store.ts
151
- var EventStore = class {
152
- constructor(dbPath, options) {
153
- this.dbPath = dbPath;
154
- this.readOnly = options?.readOnly ?? false;
155
- this.db = createDatabase(dbPath, { readOnly: this.readOnly });
156
- }
157
- db;
158
- initialized = false;
159
- readOnly;
160
- /**
161
- * Initialize database schema
162
- */
163
- async initialize() {
164
- if (this.initialized)
165
- return;
166
- if (this.readOnly) {
167
- this.initialized = true;
168
- return;
169
- }
170
- await dbRun(this.db, `
171
- CREATE TABLE IF NOT EXISTS events (
172
- id VARCHAR PRIMARY KEY,
173
- event_type VARCHAR NOT NULL,
174
- session_id VARCHAR NOT NULL,
175
- timestamp TIMESTAMP NOT NULL,
176
- content TEXT NOT NULL,
177
- canonical_key VARCHAR NOT NULL,
178
- dedupe_key VARCHAR UNIQUE,
179
- metadata JSON
180
- )
181
- `);
182
- await dbRun(this.db, `
183
- CREATE TABLE IF NOT EXISTS event_dedup (
184
- dedupe_key VARCHAR PRIMARY KEY,
185
- event_id VARCHAR NOT NULL,
186
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
187
- )
188
- `);
189
- await dbRun(this.db, `
190
- CREATE TABLE IF NOT EXISTS sessions (
191
- id VARCHAR PRIMARY KEY,
192
- started_at TIMESTAMP NOT NULL,
193
- ended_at TIMESTAMP,
194
- project_path VARCHAR,
195
- summary TEXT,
196
- tags JSON
197
- )
198
- `);
199
- await dbRun(this.db, `
200
- CREATE TABLE IF NOT EXISTS insights (
201
- id VARCHAR PRIMARY KEY,
202
- insight_type VARCHAR NOT NULL,
203
- content TEXT NOT NULL,
204
- canonical_key VARCHAR NOT NULL,
205
- confidence FLOAT,
206
- source_events JSON,
207
- created_at TIMESTAMP,
208
- last_updated TIMESTAMP
209
- )
210
- `);
211
- await dbRun(this.db, `
212
- CREATE TABLE IF NOT EXISTS embedding_outbox (
213
- id VARCHAR PRIMARY KEY,
214
- event_id VARCHAR NOT NULL,
215
- content TEXT NOT NULL,
216
- status VARCHAR DEFAULT 'pending',
217
- retry_count INT DEFAULT 0,
218
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
219
- processed_at TIMESTAMP,
220
- error_message TEXT
221
- )
222
- `);
223
- await dbRun(this.db, `
224
- CREATE TABLE IF NOT EXISTS projection_offsets (
225
- projection_name VARCHAR PRIMARY KEY,
226
- last_event_id VARCHAR,
227
- last_timestamp TIMESTAMP,
228
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
229
- )
230
- `);
231
- await dbRun(this.db, `
232
- CREATE TABLE IF NOT EXISTS memory_levels (
233
- event_id VARCHAR PRIMARY KEY,
234
- level VARCHAR NOT NULL DEFAULT 'L0',
235
- promoted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
236
- )
237
- `);
238
- await dbRun(this.db, `
239
- CREATE TABLE IF NOT EXISTS entries (
240
- entry_id VARCHAR PRIMARY KEY,
241
- created_ts TIMESTAMP NOT NULL,
242
- entry_type VARCHAR NOT NULL,
243
- title VARCHAR NOT NULL,
244
- content_json JSON NOT NULL,
245
- stage VARCHAR NOT NULL DEFAULT 'raw',
246
- status VARCHAR DEFAULT 'active',
247
- superseded_by VARCHAR,
248
- build_id VARCHAR,
249
- evidence_json JSON,
250
- canonical_key VARCHAR,
251
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
252
- )
253
- `);
254
- await dbRun(this.db, `
255
- CREATE TABLE IF NOT EXISTS entities (
256
- entity_id VARCHAR PRIMARY KEY,
257
- entity_type VARCHAR NOT NULL,
258
- canonical_key VARCHAR NOT NULL,
259
- title VARCHAR NOT NULL,
260
- stage VARCHAR NOT NULL DEFAULT 'raw',
261
- status VARCHAR NOT NULL DEFAULT 'active',
262
- current_json JSON NOT NULL,
263
- title_norm VARCHAR,
264
- search_text VARCHAR,
265
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
266
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
267
- )
268
- `);
269
- await dbRun(this.db, `
270
- CREATE TABLE IF NOT EXISTS entity_aliases (
271
- entity_type VARCHAR NOT NULL,
272
- canonical_key VARCHAR NOT NULL,
273
- entity_id VARCHAR NOT NULL,
274
- is_primary BOOLEAN DEFAULT FALSE,
275
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
276
- PRIMARY KEY(entity_type, canonical_key)
277
- )
278
- `);
279
- await dbRun(this.db, `
280
- CREATE TABLE IF NOT EXISTS edges (
281
- edge_id VARCHAR PRIMARY KEY,
282
- src_type VARCHAR NOT NULL,
283
- src_id VARCHAR NOT NULL,
284
- rel_type VARCHAR NOT NULL,
285
- dst_type VARCHAR NOT NULL,
286
- dst_id VARCHAR NOT NULL,
287
- meta_json JSON,
288
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
289
- )
290
- `);
291
- await dbRun(this.db, `
292
- CREATE TABLE IF NOT EXISTS vector_outbox (
293
- job_id VARCHAR PRIMARY KEY,
294
- item_kind VARCHAR NOT NULL,
295
- item_id VARCHAR NOT NULL,
296
- embedding_version VARCHAR NOT NULL,
297
- status VARCHAR NOT NULL DEFAULT 'pending',
298
- retry_count INT DEFAULT 0,
299
- error VARCHAR,
300
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
301
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
302
- UNIQUE(item_kind, item_id, embedding_version)
303
- )
304
- `);
305
- await dbRun(this.db, `
306
- CREATE TABLE IF NOT EXISTS build_runs (
307
- build_id VARCHAR PRIMARY KEY,
308
- started_at TIMESTAMP NOT NULL,
309
- finished_at TIMESTAMP,
310
- extractor_model VARCHAR NOT NULL,
311
- extractor_prompt_hash VARCHAR NOT NULL,
312
- embedder_model VARCHAR NOT NULL,
313
- embedding_version VARCHAR NOT NULL,
314
- idris_version VARCHAR NOT NULL,
315
- schema_version VARCHAR NOT NULL,
316
- status VARCHAR NOT NULL DEFAULT 'running',
317
- error VARCHAR
318
- )
319
- `);
320
- await dbRun(this.db, `
321
- CREATE TABLE IF NOT EXISTS pipeline_metrics (
322
- id VARCHAR PRIMARY KEY,
323
- ts TIMESTAMP NOT NULL,
324
- stage VARCHAR NOT NULL,
325
- latency_ms DOUBLE NOT NULL,
326
- success BOOLEAN NOT NULL,
327
- error VARCHAR,
328
- session_id VARCHAR
329
- )
330
- `);
331
- await dbRun(this.db, `
332
- CREATE TABLE IF NOT EXISTS working_set (
333
- id VARCHAR PRIMARY KEY,
334
- event_id VARCHAR NOT NULL,
335
- added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
336
- relevance_score FLOAT DEFAULT 1.0,
337
- topics JSON,
338
- expires_at TIMESTAMP
339
- )
340
- `);
341
- await dbRun(this.db, `
342
- CREATE TABLE IF NOT EXISTS consolidated_memories (
343
- memory_id VARCHAR PRIMARY KEY,
344
- summary TEXT NOT NULL,
345
- topics JSON,
346
- source_events JSON,
347
- confidence FLOAT DEFAULT 0.5,
348
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
349
- accessed_at TIMESTAMP,
350
- access_count INTEGER DEFAULT 0
351
- )
352
- `);
353
- await dbRun(this.db, `
354
- CREATE TABLE IF NOT EXISTS continuity_log (
355
- log_id VARCHAR PRIMARY KEY,
356
- from_context_id VARCHAR,
357
- to_context_id VARCHAR,
358
- continuity_score FLOAT,
359
- transition_type VARCHAR,
360
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
361
- )
362
- `);
363
- await dbRun(this.db, `
364
- CREATE TABLE IF NOT EXISTS consolidated_rules (
365
- rule_id VARCHAR PRIMARY KEY,
366
- rule TEXT NOT NULL,
367
- topics JSON,
368
- source_memory_ids JSON,
369
- source_events JSON,
370
- confidence FLOAT DEFAULT 0.5,
371
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
372
- )
373
- `);
374
- await dbRun(this.db, `
375
- CREATE TABLE IF NOT EXISTS endless_config (
376
- key VARCHAR PRIMARY KEY,
377
- value JSON,
378
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
379
- )
380
- `);
381
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_type ON entries(entry_type)`);
382
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_stage ON entries(stage)`);
383
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_canonical ON entries(canonical_key)`);
384
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entities_type_key ON entities(entity_type, canonical_key)`);
385
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entities_status ON entities(status)`);
386
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src_id, rel_type)`);
387
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_dst ON edges(dst_id, rel_type)`);
388
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_rel ON edges(rel_type)`);
389
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_outbox_status ON vector_outbox(status)`);
390
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_expires ON working_set(expires_at)`);
391
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_relevance ON working_set(relevance_score DESC)`);
392
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence DESC)`);
393
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_rules_confidence ON consolidated_rules(confidence DESC)`);
394
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at)`);
395
- this.initialized = true;
396
- }
397
- /**
398
- * Append event to store (AXIOMMIND Principle 2: Append-only)
399
- * Returns existing event ID if duplicate (Principle 3: Idempotency)
400
- */
401
- async append(input) {
402
- await this.initialize();
403
- const canonicalKey = makeCanonicalKey(input.content);
404
- const dedupeKey = makeDedupeKey(input.content, input.sessionId);
405
- const existing = await dbAll(
406
- this.db,
407
- `SELECT event_id FROM event_dedup WHERE dedupe_key = ?`,
408
- [dedupeKey]
409
- );
410
- if (existing.length > 0) {
411
- return {
412
- success: true,
413
- eventId: existing[0].event_id,
414
- isDuplicate: true
415
- };
416
- }
417
- const id = randomUUID();
418
- const timestamp = input.timestamp.toISOString();
419
- try {
420
- await dbRun(
421
- this.db,
422
- `INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
423
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
424
- [
425
- id,
426
- input.eventType,
427
- input.sessionId,
428
- timestamp,
429
- input.content,
430
- canonicalKey,
431
- dedupeKey,
432
- JSON.stringify(input.metadata || {})
433
- ]
434
- );
435
- await dbRun(
436
- this.db,
437
- `INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)`,
438
- [dedupeKey, id]
439
- );
440
- await dbRun(
441
- this.db,
442
- `INSERT INTO memory_levels (event_id, level) VALUES (?, 'L0')`,
443
- [id]
444
- );
445
- return { success: true, eventId: id, isDuplicate: false };
446
- } catch (error) {
447
- return {
448
- success: false,
449
- error: error instanceof Error ? error.message : String(error)
450
- };
451
- }
452
- }
453
- /**
454
- * Get events by session ID
455
- */
456
- async getSessionEvents(sessionId) {
457
- await this.initialize();
458
- const rows = await dbAll(
459
- this.db,
460
- `SELECT * FROM events WHERE session_id = ? ORDER BY timestamp ASC`,
461
- [sessionId]
462
- );
463
- return rows.map(this.rowToEvent);
464
- }
465
- /**
466
- * Get recent events
467
- */
468
- async getRecentEvents(limit = 100) {
469
- await this.initialize();
470
- const rows = await dbAll(
471
- this.db,
472
- `SELECT * FROM events ORDER BY timestamp DESC LIMIT ?`,
473
- [limit]
474
- );
475
- return rows.map(this.rowToEvent);
476
- }
477
- /**
478
- * Get event by ID
479
- */
480
- async getEvent(id) {
481
- await this.initialize();
482
- const rows = await dbAll(
483
- this.db,
484
- `SELECT * FROM events WHERE id = ?`,
485
- [id]
486
- );
487
- if (rows.length === 0)
488
- return null;
489
- return this.rowToEvent(rows[0]);
490
- }
491
- /**
492
- * Create or update session
493
- */
494
- async upsertSession(session) {
495
- await this.initialize();
496
- const existing = await dbAll(
497
- this.db,
498
- `SELECT id FROM sessions WHERE id = ?`,
499
- [session.id]
500
- );
501
- if (existing.length === 0) {
502
- await dbRun(
503
- this.db,
504
- `INSERT INTO sessions (id, started_at, project_path, tags)
505
- VALUES (?, ?, ?, ?)`,
506
- [
507
- session.id,
508
- (session.startedAt || /* @__PURE__ */ new Date()).toISOString(),
509
- session.projectPath || null,
510
- JSON.stringify(session.tags || [])
511
- ]
512
- );
513
- } else {
514
- const updates = [];
515
- const values = [];
516
- if (session.endedAt) {
517
- updates.push("ended_at = ?");
518
- values.push(session.endedAt.toISOString());
519
- }
520
- if (session.summary) {
521
- updates.push("summary = ?");
522
- values.push(session.summary);
523
- }
524
- if (session.tags) {
525
- updates.push("tags = ?");
526
- values.push(JSON.stringify(session.tags));
527
- }
528
- if (updates.length > 0) {
529
- values.push(session.id);
530
- await dbRun(
531
- this.db,
532
- `UPDATE sessions SET ${updates.join(", ")} WHERE id = ?`,
533
- values
534
- );
535
- }
536
- }
537
- }
538
- /**
539
- * Get session by ID
540
- */
541
- async getSession(id) {
542
- await this.initialize();
543
- const rows = await dbAll(
544
- this.db,
545
- `SELECT * FROM sessions WHERE id = ?`,
546
- [id]
547
- );
548
- if (rows.length === 0)
549
- return null;
550
- const row = rows[0];
551
- return {
552
- id: row.id,
553
- startedAt: toDate(row.started_at),
554
- endedAt: row.ended_at ? toDate(row.ended_at) : void 0,
555
- projectPath: row.project_path,
556
- summary: row.summary,
557
- tags: row.tags ? JSON.parse(row.tags) : void 0
558
- };
559
- }
560
- /**
561
- * Add to embedding outbox (Single-Writer Pattern)
562
- */
563
- async enqueueForEmbedding(eventId, content) {
564
- await this.initialize();
565
- const id = randomUUID();
566
- await dbRun(
567
- this.db,
568
- `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
569
- VALUES (?, ?, ?, 'pending', 0)`,
570
- [id, eventId, content]
571
- );
572
- return id;
573
- }
574
- /**
575
- * Get pending outbox items
576
- */
577
- async getPendingOutboxItems(limit = 32) {
578
- await this.initialize();
579
- const pending = await dbAll(
580
- this.db,
581
- `SELECT * FROM embedding_outbox
582
- WHERE status = 'pending'
583
- ORDER BY created_at
584
- LIMIT ?`,
585
- [limit]
586
- );
587
- if (pending.length === 0)
588
- return [];
589
- const ids = pending.map((r) => r.id);
590
- const placeholders = ids.map(() => "?").join(",");
591
- await dbRun(
592
- this.db,
593
- `UPDATE embedding_outbox SET status = 'processing' WHERE id IN (${placeholders})`,
594
- ids
595
- );
596
- return pending.map((row) => ({
597
- id: row.id,
598
- eventId: row.event_id,
599
- content: row.content,
600
- status: "processing",
601
- retryCount: row.retry_count,
602
- createdAt: toDate(row.created_at),
603
- errorMessage: row.error_message
604
- }));
605
- }
606
- /**
607
- * Mark outbox items as done
608
- */
609
- async completeOutboxItems(ids) {
610
- if (ids.length === 0)
611
- return;
612
- const placeholders = ids.map(() => "?").join(",");
613
- await dbRun(
614
- this.db,
615
- `DELETE FROM embedding_outbox WHERE id IN (${placeholders})`,
616
- ids
617
- );
618
- }
619
- /**
620
- * Mark outbox items as failed
621
- */
622
- async failOutboxItems(ids, error) {
623
- if (ids.length === 0)
624
- return;
625
- const placeholders = ids.map(() => "?").join(",");
626
- await dbRun(
627
- this.db,
628
- `UPDATE embedding_outbox
629
- SET status = CASE WHEN retry_count >= 3 THEN 'failed' ELSE 'pending' END,
630
- retry_count = retry_count + 1,
631
- error_message = ?
632
- WHERE id IN (${placeholders})`,
633
- [error, ...ids]
634
- );
635
- }
636
- /**
637
- * Update memory level
638
- */
639
- async updateMemoryLevel(eventId, level) {
640
- await this.initialize();
641
- await dbRun(
642
- this.db,
643
- `UPDATE memory_levels SET level = ?, promoted_at = CURRENT_TIMESTAMP WHERE event_id = ?`,
644
- [level, eventId]
645
- );
646
- }
647
- /**
648
- * Get memory level statistics
649
- */
650
- async getLevelStats() {
651
- await this.initialize();
652
- const rows = await dbAll(
653
- this.db,
654
- `SELECT level, COUNT(*) as count FROM memory_levels GROUP BY level`
655
- );
656
- return rows;
657
- }
658
- /**
659
- * Get events by memory level
660
- */
661
- async getEventsByLevel(level, options) {
662
- await this.initialize();
663
- const limit = options?.limit || 50;
664
- const offset = options?.offset || 0;
665
- const rows = await dbAll(
666
- this.db,
667
- `SELECT e.* FROM events e
668
- INNER JOIN memory_levels ml ON e.id = ml.event_id
669
- WHERE ml.level = ?
670
- ORDER BY e.timestamp DESC
671
- LIMIT ? OFFSET ?`,
672
- [level, limit, offset]
673
- );
674
- return rows.map((row) => this.rowToEvent(row));
675
- }
676
- /**
677
- * Get memory level for a specific event
678
- */
679
- async getEventLevel(eventId) {
680
- await this.initialize();
681
- const rows = await dbAll(
682
- this.db,
683
- `SELECT level FROM memory_levels WHERE event_id = ?`,
684
- [eventId]
685
- );
686
- return rows.length > 0 ? rows[0].level : null;
687
- }
688
- // ============================================================
689
- // Endless Mode Helper Methods
690
- // ============================================================
691
- /**
692
- * Get database instance for Endless Mode stores
693
- */
694
- getDatabase() {
695
- return this.db;
696
- }
697
- /**
698
- * Get config value for endless mode
699
- */
700
- async getEndlessConfig(key) {
701
- await this.initialize();
702
- const rows = await dbAll(
703
- this.db,
704
- `SELECT value FROM endless_config WHERE key = ?`,
705
- [key]
706
- );
707
- if (rows.length === 0)
708
- return null;
709
- return JSON.parse(rows[0].value);
710
- }
711
- /**
712
- * Set config value for endless mode
713
- */
714
- async setEndlessConfig(key, value) {
715
- await this.initialize();
716
- await dbRun(
717
- this.db,
718
- `INSERT OR REPLACE INTO endless_config (key, value, updated_at)
719
- VALUES (?, ?, CURRENT_TIMESTAMP)`,
720
- [key, JSON.stringify(value)]
721
- );
722
- }
723
- /**
724
- * Get all sessions
725
- */
726
- async getAllSessions() {
727
- await this.initialize();
728
- const rows = await dbAll(
729
- this.db,
730
- `SELECT * FROM sessions ORDER BY started_at DESC`
731
- );
732
- return rows.map((row) => ({
733
- id: row.id,
734
- startedAt: toDate(row.started_at),
735
- endedAt: row.ended_at ? toDate(row.ended_at) : void 0,
736
- projectPath: row.project_path,
737
- summary: row.summary,
738
- tags: row.tags ? JSON.parse(row.tags) : void 0
739
- }));
740
- }
741
- /**
742
- * Increment access count for events (stub for compatibility)
743
- */
744
- async incrementAccessCount(eventIds) {
745
- return Promise.resolve();
746
- }
747
- /**
748
- * Get most accessed memories (stub for compatibility)
749
- */
750
- async getMostAccessed(limit = 10) {
751
- return [];
752
- }
753
- /**
754
- * Close database connection
755
- */
756
- async close() {
757
- await dbClose(this.db);
40
+ // src/core/sqlite-event-store.ts
41
+ import { randomUUID } from "crypto";
42
+
43
+ // src/core/canonical-key.ts
44
+ import { createHash } from "crypto";
45
+ var MAX_KEY_LENGTH = 200;
46
+ function makeCanonicalKey(title, context) {
47
+ let normalized = title.normalize("NFKC");
48
+ normalized = normalized.toLowerCase();
49
+ normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, "");
50
+ normalized = normalized.replace(/\s+/g, " ").trim();
51
+ let key = normalized;
52
+ if (context?.project) {
53
+ key = `${context.project}::${key}`;
758
54
  }
759
- /**
760
- * Convert database row to MemoryEvent
761
- */
762
- rowToEvent(row) {
763
- return {
764
- id: row.id,
765
- eventType: row.event_type,
766
- sessionId: row.session_id,
767
- timestamp: toDate(row.timestamp),
768
- content: row.content,
769
- canonicalKey: row.canonical_key,
770
- dedupeKey: row.dedupe_key,
771
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0
772
- };
55
+ if (key.length > MAX_KEY_LENGTH) {
56
+ const hashSuffix = createHash("md5").update(key).digest("hex").slice(0, 8);
57
+ key = key.slice(0, MAX_KEY_LENGTH - 9) + "_" + hashSuffix;
773
58
  }
774
- };
775
-
776
- // src/core/sqlite-event-store.ts
777
- import { randomUUID as randomUUID2 } from "crypto";
59
+ return key;
60
+ }
61
+ function makeDedupeKey(content, sessionId) {
62
+ const contentHash = createHash("sha256").update(content).digest("hex");
63
+ return `${sessionId}:${contentHash}`;
64
+ }
778
65
 
779
66
  // src/core/sqlite-wrapper.ts
780
67
  import Database from "better-sqlite3";
@@ -1289,7 +576,7 @@ var SQLiteEventStore = class {
1289
576
  isDuplicate: true
1290
577
  };
1291
578
  }
1292
- const id = randomUUID2();
579
+ const id = randomUUID();
1293
580
  const timestamp = toSQLiteTimestamp(input.timestamp);
1294
581
  try {
1295
582
  const metadata = input.metadata || {};
@@ -1343,6 +630,29 @@ var SQLiteEventStore = class {
1343
630
  };
1344
631
  }
1345
632
  }
633
+ /**
634
+ * Get session IDs that have events but no session_summary event.
635
+ * Used to backfill summaries for sessions that ended without Stop hook.
636
+ */
637
+ async getSessionsWithoutSummary(currentSessionId, limit = 5) {
638
+ await this.initialize();
639
+ const rows = sqliteAll(
640
+ this.db,
641
+ `SELECT DISTINCT e.session_id
642
+ FROM events e
643
+ WHERE e.session_id != ?
644
+ AND e.event_type != 'session_summary'
645
+ AND e.session_id NOT IN (
646
+ SELECT DISTINCT session_id FROM events WHERE event_type = 'session_summary'
647
+ )
648
+ GROUP BY e.session_id
649
+ HAVING COUNT(*) >= 3
650
+ ORDER BY MAX(e.timestamp) DESC
651
+ LIMIT ?`,
652
+ [currentSessionId, limit]
653
+ );
654
+ return rows.map((r) => r.session_id);
655
+ }
1346
656
  /**
1347
657
  * Get events by session ID
1348
658
  */
@@ -1570,7 +880,7 @@ var SQLiteEventStore = class {
1570
880
  */
1571
881
  async enqueueForEmbedding(eventId, content) {
1572
882
  await this.initialize();
1573
- const id = randomUUID2();
883
+ const id = randomUUID();
1574
884
  sqliteRun(
1575
885
  this.db,
1576
886
  `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
@@ -1851,7 +1161,7 @@ var SQLiteEventStore = class {
1851
1161
  if (this.readOnly)
1852
1162
  return;
1853
1163
  await this.initialize();
1854
- const id = randomUUID2();
1164
+ const id = randomUUID();
1855
1165
  sqliteRun(
1856
1166
  this.db,
1857
1167
  `INSERT INTO memory_helpfulness (id, event_id, session_id, retrieval_score, query_preview, created_at)
@@ -2072,7 +1382,7 @@ var SQLiteEventStore = class {
2072
1382
  }
2073
1383
  async recordRetrievalTrace(input) {
2074
1384
  await this.initialize();
2075
- const traceId = randomUUID2();
1385
+ const traceId = randomUUID();
2076
1386
  sqliteRun(
2077
1387
  this.db,
2078
1388
  `INSERT INTO retrieval_traces (
@@ -2326,169 +1636,6 @@ var SQLiteEventStore = class {
2326
1636
  }
2327
1637
  };
2328
1638
 
2329
- // src/core/sync-worker.ts
2330
- var DEFAULT_CONFIG = {
2331
- intervalMs: 3e4,
2332
- batchSize: 500,
2333
- maxRetries: 3,
2334
- retryDelayMs: 5e3
2335
- };
2336
- var SyncWorker = class {
2337
- constructor(sqliteStore, duckdbStore, config) {
2338
- this.sqliteStore = sqliteStore;
2339
- this.duckdbStore = duckdbStore;
2340
- this.config = { ...DEFAULT_CONFIG, ...config };
2341
- }
2342
- config;
2343
- intervalHandle = null;
2344
- running = false;
2345
- stats = {
2346
- lastSyncAt: null,
2347
- eventsSynced: 0,
2348
- sessionsSynced: 0,
2349
- errors: 0,
2350
- status: "idle"
2351
- };
2352
- /**
2353
- * Start the sync worker
2354
- */
2355
- start() {
2356
- if (this.running)
2357
- return;
2358
- this.running = true;
2359
- this.stats.status = "idle";
2360
- this.syncNow().catch((err) => {
2361
- console.error("[SyncWorker] Initial sync failed:", err);
2362
- });
2363
- this.intervalHandle = setInterval(() => {
2364
- this.syncNow().catch((err) => {
2365
- console.error("[SyncWorker] Periodic sync failed:", err);
2366
- });
2367
- }, this.config.intervalMs);
2368
- }
2369
- /**
2370
- * Stop the sync worker
2371
- */
2372
- stop() {
2373
- this.running = false;
2374
- this.stats.status = "stopped";
2375
- if (this.intervalHandle) {
2376
- clearInterval(this.intervalHandle);
2377
- this.intervalHandle = null;
2378
- }
2379
- }
2380
- /**
2381
- * Trigger immediate sync
2382
- */
2383
- async syncNow() {
2384
- if (this.stats.status === "syncing") {
2385
- return;
2386
- }
2387
- this.stats.status = "syncing";
2388
- try {
2389
- await this.syncEvents();
2390
- await this.syncSessions();
2391
- this.stats.lastSyncAt = /* @__PURE__ */ new Date();
2392
- this.stats.status = "idle";
2393
- } catch (error) {
2394
- this.stats.errors++;
2395
- this.stats.status = "error";
2396
- throw error;
2397
- }
2398
- }
2399
- /**
2400
- * Sync events from SQLite to DuckDB
2401
- */
2402
- async syncEvents() {
2403
- const targetName = "duckdb_analytics";
2404
- const position = await this.sqliteStore.getSyncPosition(targetName);
2405
- const lastTimestamp = position.lastTimestamp || "1970-01-01T00:00:00.000Z";
2406
- let hasMore = true;
2407
- let totalSynced = 0;
2408
- while (hasMore) {
2409
- const events = await this.sqliteStore.getEventsSince(lastTimestamp, this.config.batchSize);
2410
- if (events.length === 0) {
2411
- hasMore = false;
2412
- break;
2413
- }
2414
- await this.retryWithBackoff(async () => {
2415
- for (const event of events) {
2416
- await this.insertEventToDuckDB(event);
2417
- }
2418
- });
2419
- totalSynced += events.length;
2420
- const lastEvent = events[events.length - 1];
2421
- await this.sqliteStore.updateSyncPosition(
2422
- targetName,
2423
- lastEvent.id,
2424
- lastEvent.timestamp.toISOString()
2425
- );
2426
- hasMore = events.length === this.config.batchSize;
2427
- }
2428
- this.stats.eventsSynced += totalSynced;
2429
- }
2430
- /**
2431
- * Sync sessions from SQLite to DuckDB
2432
- */
2433
- async syncSessions() {
2434
- const sessions = await this.sqliteStore.getAllSessions();
2435
- for (const session of sessions) {
2436
- await this.retryWithBackoff(async () => {
2437
- await this.duckdbStore.upsertSession(session);
2438
- });
2439
- }
2440
- this.stats.sessionsSynced = sessions.length;
2441
- }
2442
- /**
2443
- * Insert a single event into DuckDB
2444
- */
2445
- async insertEventToDuckDB(event) {
2446
- await this.duckdbStore.append({
2447
- eventType: event.eventType,
2448
- sessionId: event.sessionId,
2449
- timestamp: event.timestamp,
2450
- content: event.content,
2451
- metadata: event.metadata
2452
- });
2453
- }
2454
- /**
2455
- * Retry operation with exponential backoff
2456
- */
2457
- async retryWithBackoff(fn) {
2458
- let lastError = null;
2459
- for (let attempt = 0; attempt < this.config.maxRetries; attempt++) {
2460
- try {
2461
- return await fn();
2462
- } catch (error) {
2463
- lastError = error instanceof Error ? error : new Error(String(error));
2464
- if (attempt < this.config.maxRetries - 1) {
2465
- const delay = this.config.retryDelayMs * Math.pow(2, attempt);
2466
- await this.sleep(delay);
2467
- }
2468
- }
2469
- }
2470
- throw lastError;
2471
- }
2472
- /**
2473
- * Sleep utility
2474
- */
2475
- sleep(ms) {
2476
- return new Promise((resolve3) => setTimeout(resolve3, ms));
2477
- }
2478
- /**
2479
- * Get sync statistics
2480
- */
2481
- getStats() {
2482
- return { ...this.stats };
2483
- }
2484
- /**
2485
- * Check if worker is running
2486
- */
2487
- isRunning() {
2488
- return this.running;
2489
- }
2490
- };
2491
-
2492
1639
  // src/core/vector-store.ts
2493
1640
  import * as lancedb from "@lancedb/lancedb";
2494
1641
  var VectorStore = class {
@@ -2776,8 +1923,34 @@ function getDefaultEmbedder() {
2776
1923
  return defaultEmbedder;
2777
1924
  }
2778
1925
 
1926
+ // src/core/db-wrapper.ts
1927
+ import BetterSqlite3 from "better-sqlite3";
1928
+ function toDate(value) {
1929
+ if (value instanceof Date)
1930
+ return value;
1931
+ if (typeof value === "string")
1932
+ return new Date(value);
1933
+ if (typeof value === "number")
1934
+ return new Date(value);
1935
+ return new Date(String(value));
1936
+ }
1937
+ function createDatabase(dbPath, options) {
1938
+ return new BetterSqlite3(dbPath, { readonly: options?.readOnly });
1939
+ }
1940
+ function dbRun(db, sql, params = []) {
1941
+ db.prepare(sql).run(...params);
1942
+ return Promise.resolve();
1943
+ }
1944
+ function dbAll(db, sql, params = []) {
1945
+ return Promise.resolve(db.prepare(sql).all(...params));
1946
+ }
1947
+ function dbClose(db) {
1948
+ db.close();
1949
+ return Promise.resolve();
1950
+ }
1951
+
2779
1952
  // src/core/vector-outbox.ts
2780
- var DEFAULT_CONFIG2 = {
1953
+ var DEFAULT_CONFIG = {
2781
1954
  embeddingVersion: "v1",
2782
1955
  maxRetries: 3,
2783
1956
  stuckThresholdMs: 5 * 60 * 1e3,
@@ -2786,7 +1959,7 @@ var DEFAULT_CONFIG2 = {
2786
1959
  };
2787
1960
 
2788
1961
  // src/core/vector-worker.ts
2789
- var DEFAULT_CONFIG3 = {
1962
+ var DEFAULT_CONFIG2 = {
2790
1963
  batchSize: 32,
2791
1964
  pollIntervalMs: 1e3,
2792
1965
  maxRetries: 3
@@ -2803,7 +1976,7 @@ var VectorWorker = class {
2803
1976
  this.eventStore = eventStore;
2804
1977
  this.vectorStore = vectorStore;
2805
1978
  this.embedder = embedder;
2806
- this.config = { ...DEFAULT_CONFIG3, ...config };
1979
+ this.config = { ...DEFAULT_CONFIG2, ...config };
2807
1980
  }
2808
1981
  /**
2809
1982
  * Start the worker polling loop
@@ -2924,7 +2097,7 @@ function createVectorWorker(eventStore, vectorStore, embedder, config) {
2924
2097
  }
2925
2098
 
2926
2099
  // src/core/matcher.ts
2927
- var DEFAULT_CONFIG4 = {
2100
+ var DEFAULT_CONFIG3 = {
2928
2101
  weights: {
2929
2102
  semanticSimilarity: 0.4,
2930
2103
  ftsScore: 0.25,
@@ -2939,9 +2112,9 @@ var Matcher = class {
2939
2112
  config;
2940
2113
  constructor(config = {}) {
2941
2114
  this.config = {
2942
- ...DEFAULT_CONFIG4,
2115
+ ...DEFAULT_CONFIG3,
2943
2116
  ...config,
2944
- weights: { ...DEFAULT_CONFIG4.weights, ...config.weights }
2117
+ weights: { ...DEFAULT_CONFIG3.weights, ...config.weights }
2945
2118
  };
2946
2119
  }
2947
2120
  /**
@@ -3931,7 +3104,7 @@ function createSharedEventStore(dbPath) {
3931
3104
  }
3932
3105
 
3933
3106
  // src/core/shared-store.ts
3934
- import { randomUUID as randomUUID3 } from "crypto";
3107
+ import { randomUUID as randomUUID2 } from "crypto";
3935
3108
  var SharedStore = class {
3936
3109
  constructor(sharedEventStore) {
3937
3110
  this.sharedEventStore = sharedEventStore;
@@ -3943,7 +3116,7 @@ var SharedStore = class {
3943
3116
  * Promote a verified troubleshooting entry to shared storage
3944
3117
  */
3945
3118
  async promoteEntry(input) {
3946
- const entryId = randomUUID3();
3119
+ const entryId = randomUUID2();
3947
3120
  await dbRun(
3948
3121
  this.db,
3949
3122
  `INSERT INTO shared_troubleshooting (
@@ -4308,7 +3481,7 @@ function createSharedVectorStore(dbPath) {
4308
3481
  }
4309
3482
 
4310
3483
  // src/core/shared-promoter.ts
4311
- import { randomUUID as randomUUID4 } from "crypto";
3484
+ import { randomUUID as randomUUID3 } from "crypto";
4312
3485
  var SharedPromoter = class {
4313
3486
  constructor(sharedStore, sharedVectorStore, embedder, config) {
4314
3487
  this.sharedStore = sharedStore;
@@ -4376,7 +3549,7 @@ var SharedPromoter = class {
4376
3549
  const embeddingContent = this.createEmbeddingContent(input);
4377
3550
  const embedding = await this.embedder.embed(embeddingContent);
4378
3551
  await this.sharedVectorStore.upsert({
4379
- id: randomUUID4(),
3552
+ id: randomUUID3(),
4380
3553
  entryId,
4381
3554
  entryType: "troubleshooting",
4382
3555
  content: embeddingContent,
@@ -4516,7 +3689,7 @@ function createToolObservationEmbedding(toolName, metadata, success) {
4516
3689
  }
4517
3690
 
4518
3691
  // src/core/working-set-store.ts
4519
- import { randomUUID as randomUUID5 } from "crypto";
3692
+ import { randomUUID as randomUUID4 } from "crypto";
4520
3693
  var WorkingSetStore = class {
4521
3694
  constructor(eventStore, config) {
4522
3695
  this.eventStore = eventStore;
@@ -4537,7 +3710,7 @@ var WorkingSetStore = class {
4537
3710
  `INSERT OR REPLACE INTO working_set (id, event_id, added_at, relevance_score, topics, expires_at)
4538
3711
  VALUES (?, ?, CURRENT_TIMESTAMP, ?, ?, ?)`,
4539
3712
  [
4540
- randomUUID5(),
3713
+ randomUUID4(),
4541
3714
  eventId,
4542
3715
  relevanceScore,
4543
3716
  JSON.stringify(topics || []),
@@ -4721,7 +3894,7 @@ function createWorkingSetStore(eventStore, config) {
4721
3894
  }
4722
3895
 
4723
3896
  // src/core/consolidated-store.ts
4724
- import { randomUUID as randomUUID6 } from "crypto";
3897
+ import { randomUUID as randomUUID5 } from "crypto";
4725
3898
  var ConsolidatedStore = class {
4726
3899
  constructor(eventStore) {
4727
3900
  this.eventStore = eventStore;
@@ -4733,7 +3906,7 @@ var ConsolidatedStore = class {
4733
3906
  * Create a new consolidated memory
4734
3907
  */
4735
3908
  async create(input) {
4736
- const memoryId = randomUUID6();
3909
+ const memoryId = randomUUID5();
4737
3910
  await dbRun(
4738
3911
  this.db,
4739
3912
  `INSERT INTO consolidated_memories
@@ -4863,7 +4036,7 @@ var ConsolidatedStore = class {
4863
4036
  * Create a long-term rule promoted from stable summaries
4864
4037
  */
4865
4038
  async createRule(input) {
4866
- const ruleId = randomUUID6();
4039
+ const ruleId = randomUUID5();
4867
4040
  await dbRun(
4868
4041
  this.db,
4869
4042
  `INSERT INTO consolidated_rules
@@ -5385,7 +4558,7 @@ function createConsolidationWorker(workingSetStore, consolidatedStore, config) {
5385
4558
  }
5386
4559
 
5387
4560
  // src/core/continuity-manager.ts
5388
- import { randomUUID as randomUUID7 } from "crypto";
4561
+ import { randomUUID as randomUUID6 } from "crypto";
5389
4562
  var ContinuityManager = class {
5390
4563
  constructor(eventStore, config) {
5391
4564
  this.eventStore = eventStore;
@@ -5539,7 +4712,7 @@ var ContinuityManager = class {
5539
4712
  `INSERT INTO continuity_log
5540
4713
  (log_id, from_context_id, to_context_id, continuity_score, transition_type, created_at)
5541
4714
  VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
5542
- [randomUUID7(), previous.id, current.id, score, type]
4715
+ [randomUUID6(), previous.id, current.id, score, type]
5543
4716
  );
5544
4717
  }
5545
4718
  /**
@@ -5648,7 +4821,7 @@ function createContinuityManager(eventStore, config) {
5648
4821
  }
5649
4822
 
5650
4823
  // src/core/graduation-worker.ts
5651
- var DEFAULT_CONFIG5 = {
4824
+ var DEFAULT_CONFIG4 = {
5652
4825
  evaluationIntervalMs: 3e5,
5653
4826
  // 5 minutes
5654
4827
  batchSize: 50,
@@ -5656,7 +4829,7 @@ var DEFAULT_CONFIG5 = {
5656
4829
  // 1 hour cooldown between evaluations
5657
4830
  };
5658
4831
  var GraduationWorker = class {
5659
- constructor(eventStore, graduation, config = DEFAULT_CONFIG5) {
4832
+ constructor(eventStore, graduation, config = DEFAULT_CONFIG4) {
5660
4833
  this.eventStore = eventStore;
5661
4834
  this.graduation = graduation;
5662
4835
  this.config = config;
@@ -5764,7 +4937,7 @@ function createGraduationWorker(eventStore, graduation, config) {
5764
4937
  return new GraduationWorker(
5765
4938
  eventStore,
5766
4939
  graduation,
5767
- { ...DEFAULT_CONFIG5, ...config }
4940
+ { ...DEFAULT_CONFIG4, ...config }
5768
4941
  );
5769
4942
  }
5770
4943
 
@@ -5973,9 +5146,6 @@ function loadSessionRegistry() {
5973
5146
  var MemoryService = class {
5974
5147
  // Primary store: SQLite (WAL mode) - for hooks, always available
5975
5148
  sqliteStore;
5976
- // Analytics store: DuckDB - for server reads (optional, synced from SQLite)
5977
- analyticsStore;
5978
- syncWorker = null;
5979
5149
  vectorStore;
5980
5150
  embedder;
5981
5151
  matcher;
@@ -6024,24 +5194,6 @@ var MemoryService = class {
6024
5194
  markdownMirrorRoot: storagePath
6025
5195
  }
6026
5196
  );
6027
- const analyticsEnabled = config.analyticsEnabled ?? this.readOnly;
6028
- if (!analyticsEnabled) {
6029
- this.analyticsStore = null;
6030
- } else if (this.readOnly) {
6031
- try {
6032
- this.analyticsStore = new EventStore(
6033
- path3.join(storagePath, "analytics.duckdb"),
6034
- { readOnly: true }
6035
- );
6036
- } catch {
6037
- this.analyticsStore = null;
6038
- }
6039
- } else {
6040
- this.analyticsStore = new EventStore(
6041
- path3.join(storagePath, "analytics.duckdb"),
6042
- { readOnly: false }
6043
- );
6044
- }
6045
5197
  this.vectorStore = new VectorStore(path3.join(storagePath, "vectors"));
6046
5198
  const embeddingModel = config.embeddingModel || process.env.CLAUDE_MEMORY_EMBEDDING_MODEL;
6047
5199
  this.embedder = embeddingModel ? new Embedder(embeddingModel) : getDefaultEmbedder();
@@ -6067,13 +5219,6 @@ var MemoryService = class {
6067
5219
  this.initialized = true;
6068
5220
  return;
6069
5221
  }
6070
- if (this.analyticsStore) {
6071
- try {
6072
- await this.analyticsStore.initialize();
6073
- } catch (error) {
6074
- console.warn("[MemoryService] Analytics store (DuckDB) initialization failed, using SQLite for reads:", error);
6075
- }
6076
- }
6077
5222
  await this.vectorStore.initialize();
6078
5223
  await this.embedder.initialize();
6079
5224
  if (!this.readOnly) {
@@ -6090,14 +5235,6 @@ var MemoryService = class {
6090
5235
  this.graduation
6091
5236
  );
6092
5237
  this.graduationWorker.start();
6093
- if (this.analyticsStore) {
6094
- this.syncWorker = new SyncWorker(
6095
- this.sqliteStore,
6096
- this.analyticsStore,
6097
- { intervalMs: 3e4, batchSize: 500 }
6098
- );
6099
- this.syncWorker.start();
6100
- }
6101
5238
  }
6102
5239
  const savedMode = await this.sqliteStore.getEndlessConfig("mode");
6103
5240
  if (savedMode === "endless") {
@@ -6294,6 +5431,57 @@ var MemoryService = class {
6294
5431
  }
6295
5432
  );
6296
5433
  }
5434
+ /**
5435
+ * Backfill session summaries for recent sessions that are missing them.
5436
+ * Called from session-start hook to catch sessions that ended without Stop hook.
5437
+ */
5438
+ async backfillMissingSummaries(currentSessionId, limit = 5) {
5439
+ await this.initialize();
5440
+ const recentSessionIds = await this.sqliteStore.getSessionsWithoutSummary(currentSessionId, limit);
5441
+ for (const sid of recentSessionIds) {
5442
+ try {
5443
+ await this.generateSessionSummary(sid);
5444
+ } catch {
5445
+ }
5446
+ }
5447
+ }
5448
+ /**
5449
+ * Generate a rule-based session summary from stored events.
5450
+ * Called at session end (Stop hook) when no LLM-generated summary exists.
5451
+ * Skips if a summary already exists for this session.
5452
+ */
5453
+ async generateSessionSummary(sessionId) {
5454
+ await this.initialize();
5455
+ const events = await this.sqliteStore.getSessionEvents(sessionId);
5456
+ if (events.length < 3)
5457
+ return;
5458
+ const hasSummary = events.some((e) => e.eventType === "session_summary");
5459
+ if (hasSummary)
5460
+ return;
5461
+ const prompts = events.filter((e) => e.eventType === "user_prompt");
5462
+ const toolObs = events.filter((e) => e.eventType === "tool_observation");
5463
+ const toolNames = [...new Set(
5464
+ toolObs.map((e) => e.metadata?.toolName).filter(Boolean)
5465
+ )];
5466
+ const errorObs = toolObs.filter((e) => {
5467
+ const meta = e.metadata;
5468
+ return meta?.exitCode !== void 0 && meta.exitCode !== 0;
5469
+ });
5470
+ const datePart = events[0].timestamp.toISOString().split("T")[0];
5471
+ const parts = [`[${datePart}] ${prompts.length}\uD134 \uC138\uC158.`];
5472
+ if (prompts.length > 0) {
5473
+ const firstPrompt = prompts[0].content.slice(0, 120).replace(/\n/g, " ");
5474
+ parts.push(`\uC8FC\uC694 \uC791\uC5C5: ${firstPrompt}`);
5475
+ }
5476
+ if (toolNames.length > 0) {
5477
+ parts.push(`\uC0AC\uC6A9 \uD234: ${toolNames.slice(0, 6).join(", ")}`);
5478
+ }
5479
+ if (errorObs.length > 0) {
5480
+ parts.push(`\uC624\uB958 ${errorObs.length}\uAC74 \uBC1C\uC0DD`);
5481
+ }
5482
+ const summary = parts.join(". ");
5483
+ await this.storeSessionSummary(sessionId, summary, { generated: "rule-based", eventCount: events.length });
5484
+ }
6297
5485
  /**
6298
5486
  * Store a tool observation
6299
5487
  */
@@ -6829,6 +6017,7 @@ var MemoryService = class {
6829
6017
  await this.initialize();
6830
6018
  await this.sqliteStore.recordRetrievalTrace({
6831
6019
  ...input,
6020
+ projectHash: this.projectHash || void 0,
6832
6021
  candidateDetails: [],
6833
6022
  selectedDetails: [],
6834
6023
  fallbackTrace: []
@@ -7119,16 +6308,10 @@ var MemoryService = class {
7119
6308
  if (this.vectorWorker) {
7120
6309
  this.vectorWorker.stop();
7121
6310
  }
7122
- if (this.syncWorker) {
7123
- this.syncWorker.stop();
7124
- }
7125
6311
  if (this.sharedEventStore) {
7126
6312
  await this.sharedEventStore.close();
7127
6313
  }
7128
6314
  await this.sqliteStore.close();
7129
- if (this.analyticsStore) {
7130
- await this.analyticsStore.close();
7131
- }
7132
6315
  }
7133
6316
  /**
7134
6317
  * Expand ~ to home directory