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
@@ -16,744 +16,31 @@ import * as os from "os";
16
16
  import * as fs4 from "fs";
17
17
  import * as crypto2 from "crypto";
18
18
 
19
- // src/core/event-store.ts
20
- import { randomUUID } from "crypto";
21
-
22
- // src/core/canonical-key.ts
23
- import { createHash } from "crypto";
24
- var MAX_KEY_LENGTH = 200;
25
- function makeCanonicalKey(title, context) {
26
- let normalized = title.normalize("NFKC");
27
- normalized = normalized.toLowerCase();
28
- normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, "");
29
- normalized = normalized.replace(/\s+/g, " ").trim();
30
- let key = normalized;
31
- if (context?.project) {
32
- key = `${context.project}::${key}`;
33
- }
34
- if (key.length > MAX_KEY_LENGTH) {
35
- const hashSuffix = createHash("md5").update(key).digest("hex").slice(0, 8);
36
- key = key.slice(0, MAX_KEY_LENGTH - 9) + "_" + hashSuffix;
37
- }
38
- return key;
39
- }
40
- function makeDedupeKey(content, sessionId) {
41
- const contentHash = createHash("sha256").update(content).digest("hex");
42
- return `${sessionId}:${contentHash}`;
43
- }
44
-
45
- // src/core/db-wrapper.ts
46
- import duckdb from "duckdb";
47
- function convertBigInts(obj) {
48
- if (obj === null || obj === void 0)
49
- return obj;
50
- if (typeof obj === "bigint")
51
- return Number(obj);
52
- if (obj instanceof Date)
53
- return obj;
54
- if (Array.isArray(obj))
55
- return obj.map(convertBigInts);
56
- if (typeof obj === "object") {
57
- const result = {};
58
- for (const [key, value] of Object.entries(obj)) {
59
- result[key] = convertBigInts(value);
60
- }
61
- return result;
62
- }
63
- return obj;
64
- }
65
- function toDate(value) {
66
- if (value instanceof Date)
67
- return value;
68
- if (typeof value === "string")
69
- return new Date(value);
70
- if (typeof value === "number")
71
- return new Date(value);
72
- return new Date(String(value));
73
- }
74
- function createDatabase(path5, options) {
75
- if (options?.readOnly) {
76
- return new duckdb.Database(path5, { access_mode: "READ_ONLY" });
77
- }
78
- return new duckdb.Database(path5);
79
- }
80
- function dbRun(db, sql, params = []) {
81
- return new Promise((resolve2, reject) => {
82
- if (params.length === 0) {
83
- db.run(sql, (err) => {
84
- if (err)
85
- reject(err);
86
- else
87
- resolve2();
88
- });
89
- } else {
90
- db.run(sql, ...params, (err) => {
91
- if (err)
92
- reject(err);
93
- else
94
- resolve2();
95
- });
96
- }
97
- });
98
- }
99
- function dbAll(db, sql, params = []) {
100
- return new Promise((resolve2, reject) => {
101
- if (params.length === 0) {
102
- db.all(sql, (err, rows) => {
103
- if (err)
104
- reject(err);
105
- else
106
- resolve2(convertBigInts(rows || []));
107
- });
108
- } else {
109
- db.all(sql, ...params, (err, rows) => {
110
- if (err)
111
- reject(err);
112
- else
113
- resolve2(convertBigInts(rows || []));
114
- });
115
- }
116
- });
117
- }
118
- function dbClose(db) {
119
- return new Promise((resolve2, reject) => {
120
- db.close((err) => {
121
- if (err)
122
- reject(err);
123
- else
124
- resolve2();
125
- });
126
- });
127
- }
128
-
129
- // src/core/event-store.ts
130
- var EventStore = class {
131
- constructor(dbPath, options) {
132
- this.dbPath = dbPath;
133
- this.readOnly = options?.readOnly ?? false;
134
- this.db = createDatabase(dbPath, { readOnly: this.readOnly });
135
- }
136
- db;
137
- initialized = false;
138
- readOnly;
139
- /**
140
- * Initialize database schema
141
- */
142
- async initialize() {
143
- if (this.initialized)
144
- return;
145
- if (this.readOnly) {
146
- this.initialized = true;
147
- return;
148
- }
149
- await dbRun(this.db, `
150
- CREATE TABLE IF NOT EXISTS events (
151
- id VARCHAR PRIMARY KEY,
152
- event_type VARCHAR NOT NULL,
153
- session_id VARCHAR NOT NULL,
154
- timestamp TIMESTAMP NOT NULL,
155
- content TEXT NOT NULL,
156
- canonical_key VARCHAR NOT NULL,
157
- dedupe_key VARCHAR UNIQUE,
158
- metadata JSON
159
- )
160
- `);
161
- await dbRun(this.db, `
162
- CREATE TABLE IF NOT EXISTS event_dedup (
163
- dedupe_key VARCHAR PRIMARY KEY,
164
- event_id VARCHAR NOT NULL,
165
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
166
- )
167
- `);
168
- await dbRun(this.db, `
169
- CREATE TABLE IF NOT EXISTS sessions (
170
- id VARCHAR PRIMARY KEY,
171
- started_at TIMESTAMP NOT NULL,
172
- ended_at TIMESTAMP,
173
- project_path VARCHAR,
174
- summary TEXT,
175
- tags JSON
176
- )
177
- `);
178
- await dbRun(this.db, `
179
- CREATE TABLE IF NOT EXISTS insights (
180
- id VARCHAR PRIMARY KEY,
181
- insight_type VARCHAR NOT NULL,
182
- content TEXT NOT NULL,
183
- canonical_key VARCHAR NOT NULL,
184
- confidence FLOAT,
185
- source_events JSON,
186
- created_at TIMESTAMP,
187
- last_updated TIMESTAMP
188
- )
189
- `);
190
- await dbRun(this.db, `
191
- CREATE TABLE IF NOT EXISTS embedding_outbox (
192
- id VARCHAR PRIMARY KEY,
193
- event_id VARCHAR NOT NULL,
194
- content TEXT NOT NULL,
195
- status VARCHAR DEFAULT 'pending',
196
- retry_count INT DEFAULT 0,
197
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
198
- processed_at TIMESTAMP,
199
- error_message TEXT
200
- )
201
- `);
202
- await dbRun(this.db, `
203
- CREATE TABLE IF NOT EXISTS projection_offsets (
204
- projection_name VARCHAR PRIMARY KEY,
205
- last_event_id VARCHAR,
206
- last_timestamp TIMESTAMP,
207
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
208
- )
209
- `);
210
- await dbRun(this.db, `
211
- CREATE TABLE IF NOT EXISTS memory_levels (
212
- event_id VARCHAR PRIMARY KEY,
213
- level VARCHAR NOT NULL DEFAULT 'L0',
214
- promoted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
215
- )
216
- `);
217
- await dbRun(this.db, `
218
- CREATE TABLE IF NOT EXISTS entries (
219
- entry_id VARCHAR PRIMARY KEY,
220
- created_ts TIMESTAMP NOT NULL,
221
- entry_type VARCHAR NOT NULL,
222
- title VARCHAR NOT NULL,
223
- content_json JSON NOT NULL,
224
- stage VARCHAR NOT NULL DEFAULT 'raw',
225
- status VARCHAR DEFAULT 'active',
226
- superseded_by VARCHAR,
227
- build_id VARCHAR,
228
- evidence_json JSON,
229
- canonical_key VARCHAR,
230
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
231
- )
232
- `);
233
- await dbRun(this.db, `
234
- CREATE TABLE IF NOT EXISTS entities (
235
- entity_id VARCHAR PRIMARY KEY,
236
- entity_type VARCHAR NOT NULL,
237
- canonical_key VARCHAR NOT NULL,
238
- title VARCHAR NOT NULL,
239
- stage VARCHAR NOT NULL DEFAULT 'raw',
240
- status VARCHAR NOT NULL DEFAULT 'active',
241
- current_json JSON NOT NULL,
242
- title_norm VARCHAR,
243
- search_text VARCHAR,
244
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
245
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
246
- )
247
- `);
248
- await dbRun(this.db, `
249
- CREATE TABLE IF NOT EXISTS entity_aliases (
250
- entity_type VARCHAR NOT NULL,
251
- canonical_key VARCHAR NOT NULL,
252
- entity_id VARCHAR NOT NULL,
253
- is_primary BOOLEAN DEFAULT FALSE,
254
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
255
- PRIMARY KEY(entity_type, canonical_key)
256
- )
257
- `);
258
- await dbRun(this.db, `
259
- CREATE TABLE IF NOT EXISTS edges (
260
- edge_id VARCHAR PRIMARY KEY,
261
- src_type VARCHAR NOT NULL,
262
- src_id VARCHAR NOT NULL,
263
- rel_type VARCHAR NOT NULL,
264
- dst_type VARCHAR NOT NULL,
265
- dst_id VARCHAR NOT NULL,
266
- meta_json JSON,
267
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
268
- )
269
- `);
270
- await dbRun(this.db, `
271
- CREATE TABLE IF NOT EXISTS vector_outbox (
272
- job_id VARCHAR PRIMARY KEY,
273
- item_kind VARCHAR NOT NULL,
274
- item_id VARCHAR NOT NULL,
275
- embedding_version VARCHAR NOT NULL,
276
- status VARCHAR NOT NULL DEFAULT 'pending',
277
- retry_count INT DEFAULT 0,
278
- error VARCHAR,
279
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
280
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
281
- UNIQUE(item_kind, item_id, embedding_version)
282
- )
283
- `);
284
- await dbRun(this.db, `
285
- CREATE TABLE IF NOT EXISTS build_runs (
286
- build_id VARCHAR PRIMARY KEY,
287
- started_at TIMESTAMP NOT NULL,
288
- finished_at TIMESTAMP,
289
- extractor_model VARCHAR NOT NULL,
290
- extractor_prompt_hash VARCHAR NOT NULL,
291
- embedder_model VARCHAR NOT NULL,
292
- embedding_version VARCHAR NOT NULL,
293
- idris_version VARCHAR NOT NULL,
294
- schema_version VARCHAR NOT NULL,
295
- status VARCHAR NOT NULL DEFAULT 'running',
296
- error VARCHAR
297
- )
298
- `);
299
- await dbRun(this.db, `
300
- CREATE TABLE IF NOT EXISTS pipeline_metrics (
301
- id VARCHAR PRIMARY KEY,
302
- ts TIMESTAMP NOT NULL,
303
- stage VARCHAR NOT NULL,
304
- latency_ms DOUBLE NOT NULL,
305
- success BOOLEAN NOT NULL,
306
- error VARCHAR,
307
- session_id VARCHAR
308
- )
309
- `);
310
- await dbRun(this.db, `
311
- CREATE TABLE IF NOT EXISTS working_set (
312
- id VARCHAR PRIMARY KEY,
313
- event_id VARCHAR NOT NULL,
314
- added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
315
- relevance_score FLOAT DEFAULT 1.0,
316
- topics JSON,
317
- expires_at TIMESTAMP
318
- )
319
- `);
320
- await dbRun(this.db, `
321
- CREATE TABLE IF NOT EXISTS consolidated_memories (
322
- memory_id VARCHAR PRIMARY KEY,
323
- summary TEXT NOT NULL,
324
- topics JSON,
325
- source_events JSON,
326
- confidence FLOAT DEFAULT 0.5,
327
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
328
- accessed_at TIMESTAMP,
329
- access_count INTEGER DEFAULT 0
330
- )
331
- `);
332
- await dbRun(this.db, `
333
- CREATE TABLE IF NOT EXISTS continuity_log (
334
- log_id VARCHAR PRIMARY KEY,
335
- from_context_id VARCHAR,
336
- to_context_id VARCHAR,
337
- continuity_score FLOAT,
338
- transition_type VARCHAR,
339
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
340
- )
341
- `);
342
- await dbRun(this.db, `
343
- CREATE TABLE IF NOT EXISTS consolidated_rules (
344
- rule_id VARCHAR PRIMARY KEY,
345
- rule TEXT NOT NULL,
346
- topics JSON,
347
- source_memory_ids JSON,
348
- source_events JSON,
349
- confidence FLOAT DEFAULT 0.5,
350
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
351
- )
352
- `);
353
- await dbRun(this.db, `
354
- CREATE TABLE IF NOT EXISTS endless_config (
355
- key VARCHAR PRIMARY KEY,
356
- value JSON,
357
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
358
- )
359
- `);
360
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_type ON entries(entry_type)`);
361
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_stage ON entries(stage)`);
362
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_canonical ON entries(canonical_key)`);
363
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entities_type_key ON entities(entity_type, canonical_key)`);
364
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entities_status ON entities(status)`);
365
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src_id, rel_type)`);
366
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_dst ON edges(dst_id, rel_type)`);
367
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_rel ON edges(rel_type)`);
368
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_outbox_status ON vector_outbox(status)`);
369
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_expires ON working_set(expires_at)`);
370
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_relevance ON working_set(relevance_score DESC)`);
371
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence DESC)`);
372
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_rules_confidence ON consolidated_rules(confidence DESC)`);
373
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at)`);
374
- this.initialized = true;
375
- }
376
- /**
377
- * Append event to store (AXIOMMIND Principle 2: Append-only)
378
- * Returns existing event ID if duplicate (Principle 3: Idempotency)
379
- */
380
- async append(input) {
381
- await this.initialize();
382
- const canonicalKey = makeCanonicalKey(input.content);
383
- const dedupeKey = makeDedupeKey(input.content, input.sessionId);
384
- const existing = await dbAll(
385
- this.db,
386
- `SELECT event_id FROM event_dedup WHERE dedupe_key = ?`,
387
- [dedupeKey]
388
- );
389
- if (existing.length > 0) {
390
- return {
391
- success: true,
392
- eventId: existing[0].event_id,
393
- isDuplicate: true
394
- };
395
- }
396
- const id = randomUUID();
397
- const timestamp = input.timestamp.toISOString();
398
- try {
399
- await dbRun(
400
- this.db,
401
- `INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
402
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
403
- [
404
- id,
405
- input.eventType,
406
- input.sessionId,
407
- timestamp,
408
- input.content,
409
- canonicalKey,
410
- dedupeKey,
411
- JSON.stringify(input.metadata || {})
412
- ]
413
- );
414
- await dbRun(
415
- this.db,
416
- `INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)`,
417
- [dedupeKey, id]
418
- );
419
- await dbRun(
420
- this.db,
421
- `INSERT INTO memory_levels (event_id, level) VALUES (?, 'L0')`,
422
- [id]
423
- );
424
- return { success: true, eventId: id, isDuplicate: false };
425
- } catch (error) {
426
- return {
427
- success: false,
428
- error: error instanceof Error ? error.message : String(error)
429
- };
430
- }
431
- }
432
- /**
433
- * Get events by session ID
434
- */
435
- async getSessionEvents(sessionId) {
436
- await this.initialize();
437
- const rows = await dbAll(
438
- this.db,
439
- `SELECT * FROM events WHERE session_id = ? ORDER BY timestamp ASC`,
440
- [sessionId]
441
- );
442
- return rows.map(this.rowToEvent);
443
- }
444
- /**
445
- * Get recent events
446
- */
447
- async getRecentEvents(limit = 100) {
448
- await this.initialize();
449
- const rows = await dbAll(
450
- this.db,
451
- `SELECT * FROM events ORDER BY timestamp DESC LIMIT ?`,
452
- [limit]
453
- );
454
- return rows.map(this.rowToEvent);
455
- }
456
- /**
457
- * Get event by ID
458
- */
459
- async getEvent(id) {
460
- await this.initialize();
461
- const rows = await dbAll(
462
- this.db,
463
- `SELECT * FROM events WHERE id = ?`,
464
- [id]
465
- );
466
- if (rows.length === 0)
467
- return null;
468
- return this.rowToEvent(rows[0]);
469
- }
470
- /**
471
- * Create or update session
472
- */
473
- async upsertSession(session) {
474
- await this.initialize();
475
- const existing = await dbAll(
476
- this.db,
477
- `SELECT id FROM sessions WHERE id = ?`,
478
- [session.id]
479
- );
480
- if (existing.length === 0) {
481
- await dbRun(
482
- this.db,
483
- `INSERT INTO sessions (id, started_at, project_path, tags)
484
- VALUES (?, ?, ?, ?)`,
485
- [
486
- session.id,
487
- (session.startedAt || /* @__PURE__ */ new Date()).toISOString(),
488
- session.projectPath || null,
489
- JSON.stringify(session.tags || [])
490
- ]
491
- );
492
- } else {
493
- const updates = [];
494
- const values = [];
495
- if (session.endedAt) {
496
- updates.push("ended_at = ?");
497
- values.push(session.endedAt.toISOString());
498
- }
499
- if (session.summary) {
500
- updates.push("summary = ?");
501
- values.push(session.summary);
502
- }
503
- if (session.tags) {
504
- updates.push("tags = ?");
505
- values.push(JSON.stringify(session.tags));
506
- }
507
- if (updates.length > 0) {
508
- values.push(session.id);
509
- await dbRun(
510
- this.db,
511
- `UPDATE sessions SET ${updates.join(", ")} WHERE id = ?`,
512
- values
513
- );
514
- }
515
- }
516
- }
517
- /**
518
- * Get session by ID
519
- */
520
- async getSession(id) {
521
- await this.initialize();
522
- const rows = await dbAll(
523
- this.db,
524
- `SELECT * FROM sessions WHERE id = ?`,
525
- [id]
526
- );
527
- if (rows.length === 0)
528
- return null;
529
- const row = rows[0];
530
- return {
531
- id: row.id,
532
- startedAt: toDate(row.started_at),
533
- endedAt: row.ended_at ? toDate(row.ended_at) : void 0,
534
- projectPath: row.project_path,
535
- summary: row.summary,
536
- tags: row.tags ? JSON.parse(row.tags) : void 0
537
- };
538
- }
539
- /**
540
- * Add to embedding outbox (Single-Writer Pattern)
541
- */
542
- async enqueueForEmbedding(eventId, content) {
543
- await this.initialize();
544
- const id = randomUUID();
545
- await dbRun(
546
- this.db,
547
- `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
548
- VALUES (?, ?, ?, 'pending', 0)`,
549
- [id, eventId, content]
550
- );
551
- return id;
552
- }
553
- /**
554
- * Get pending outbox items
555
- */
556
- async getPendingOutboxItems(limit = 32) {
557
- await this.initialize();
558
- const pending = await dbAll(
559
- this.db,
560
- `SELECT * FROM embedding_outbox
561
- WHERE status = 'pending'
562
- ORDER BY created_at
563
- LIMIT ?`,
564
- [limit]
565
- );
566
- if (pending.length === 0)
567
- return [];
568
- const ids = pending.map((r) => r.id);
569
- const placeholders = ids.map(() => "?").join(",");
570
- await dbRun(
571
- this.db,
572
- `UPDATE embedding_outbox SET status = 'processing' WHERE id IN (${placeholders})`,
573
- ids
574
- );
575
- return pending.map((row) => ({
576
- id: row.id,
577
- eventId: row.event_id,
578
- content: row.content,
579
- status: "processing",
580
- retryCount: row.retry_count,
581
- createdAt: toDate(row.created_at),
582
- errorMessage: row.error_message
583
- }));
584
- }
585
- /**
586
- * Mark outbox items as done
587
- */
588
- async completeOutboxItems(ids) {
589
- if (ids.length === 0)
590
- return;
591
- const placeholders = ids.map(() => "?").join(",");
592
- await dbRun(
593
- this.db,
594
- `DELETE FROM embedding_outbox WHERE id IN (${placeholders})`,
595
- ids
596
- );
597
- }
598
- /**
599
- * Mark outbox items as failed
600
- */
601
- async failOutboxItems(ids, error) {
602
- if (ids.length === 0)
603
- return;
604
- const placeholders = ids.map(() => "?").join(",");
605
- await dbRun(
606
- this.db,
607
- `UPDATE embedding_outbox
608
- SET status = CASE WHEN retry_count >= 3 THEN 'failed' ELSE 'pending' END,
609
- retry_count = retry_count + 1,
610
- error_message = ?
611
- WHERE id IN (${placeholders})`,
612
- [error, ...ids]
613
- );
614
- }
615
- /**
616
- * Update memory level
617
- */
618
- async updateMemoryLevel(eventId, level) {
619
- await this.initialize();
620
- await dbRun(
621
- this.db,
622
- `UPDATE memory_levels SET level = ?, promoted_at = CURRENT_TIMESTAMP WHERE event_id = ?`,
623
- [level, eventId]
624
- );
625
- }
626
- /**
627
- * Get memory level statistics
628
- */
629
- async getLevelStats() {
630
- await this.initialize();
631
- const rows = await dbAll(
632
- this.db,
633
- `SELECT level, COUNT(*) as count FROM memory_levels GROUP BY level`
634
- );
635
- return rows;
636
- }
637
- /**
638
- * Get events by memory level
639
- */
640
- async getEventsByLevel(level, options) {
641
- await this.initialize();
642
- const limit = options?.limit || 50;
643
- const offset = options?.offset || 0;
644
- const rows = await dbAll(
645
- this.db,
646
- `SELECT e.* FROM events e
647
- INNER JOIN memory_levels ml ON e.id = ml.event_id
648
- WHERE ml.level = ?
649
- ORDER BY e.timestamp DESC
650
- LIMIT ? OFFSET ?`,
651
- [level, limit, offset]
652
- );
653
- return rows.map((row) => this.rowToEvent(row));
654
- }
655
- /**
656
- * Get memory level for a specific event
657
- */
658
- async getEventLevel(eventId) {
659
- await this.initialize();
660
- const rows = await dbAll(
661
- this.db,
662
- `SELECT level FROM memory_levels WHERE event_id = ?`,
663
- [eventId]
664
- );
665
- return rows.length > 0 ? rows[0].level : null;
666
- }
667
- // ============================================================
668
- // Endless Mode Helper Methods
669
- // ============================================================
670
- /**
671
- * Get database instance for Endless Mode stores
672
- */
673
- getDatabase() {
674
- return this.db;
675
- }
676
- /**
677
- * Get config value for endless mode
678
- */
679
- async getEndlessConfig(key) {
680
- await this.initialize();
681
- const rows = await dbAll(
682
- this.db,
683
- `SELECT value FROM endless_config WHERE key = ?`,
684
- [key]
685
- );
686
- if (rows.length === 0)
687
- return null;
688
- return JSON.parse(rows[0].value);
689
- }
690
- /**
691
- * Set config value for endless mode
692
- */
693
- async setEndlessConfig(key, value) {
694
- await this.initialize();
695
- await dbRun(
696
- this.db,
697
- `INSERT OR REPLACE INTO endless_config (key, value, updated_at)
698
- VALUES (?, ?, CURRENT_TIMESTAMP)`,
699
- [key, JSON.stringify(value)]
700
- );
701
- }
702
- /**
703
- * Get all sessions
704
- */
705
- async getAllSessions() {
706
- await this.initialize();
707
- const rows = await dbAll(
708
- this.db,
709
- `SELECT * FROM sessions ORDER BY started_at DESC`
710
- );
711
- return rows.map((row) => ({
712
- id: row.id,
713
- startedAt: toDate(row.started_at),
714
- endedAt: row.ended_at ? toDate(row.ended_at) : void 0,
715
- projectPath: row.project_path,
716
- summary: row.summary,
717
- tags: row.tags ? JSON.parse(row.tags) : void 0
718
- }));
719
- }
720
- /**
721
- * Increment access count for events (stub for compatibility)
722
- */
723
- async incrementAccessCount(eventIds) {
724
- return Promise.resolve();
725
- }
726
- /**
727
- * Get most accessed memories (stub for compatibility)
728
- */
729
- async getMostAccessed(limit = 10) {
730
- return [];
731
- }
732
- /**
733
- * Close database connection
734
- */
735
- async close() {
736
- await dbClose(this.db);
19
+ // src/core/sqlite-event-store.ts
20
+ import { randomUUID } from "crypto";
21
+
22
+ // src/core/canonical-key.ts
23
+ import { createHash } from "crypto";
24
+ var MAX_KEY_LENGTH = 200;
25
+ function makeCanonicalKey(title, context) {
26
+ let normalized = title.normalize("NFKC");
27
+ normalized = normalized.toLowerCase();
28
+ normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, "");
29
+ normalized = normalized.replace(/\s+/g, " ").trim();
30
+ let key = normalized;
31
+ if (context?.project) {
32
+ key = `${context.project}::${key}`;
737
33
  }
738
- /**
739
- * Convert database row to MemoryEvent
740
- */
741
- rowToEvent(row) {
742
- return {
743
- id: row.id,
744
- eventType: row.event_type,
745
- sessionId: row.session_id,
746
- timestamp: toDate(row.timestamp),
747
- content: row.content,
748
- canonicalKey: row.canonical_key,
749
- dedupeKey: row.dedupe_key,
750
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0
751
- };
34
+ if (key.length > MAX_KEY_LENGTH) {
35
+ const hashSuffix = createHash("md5").update(key).digest("hex").slice(0, 8);
36
+ key = key.slice(0, MAX_KEY_LENGTH - 9) + "_" + hashSuffix;
752
37
  }
753
- };
754
-
755
- // src/core/sqlite-event-store.ts
756
- import { randomUUID as randomUUID2 } from "crypto";
38
+ return key;
39
+ }
40
+ function makeDedupeKey(content, sessionId) {
41
+ const contentHash = createHash("sha256").update(content).digest("hex");
42
+ return `${sessionId}:${contentHash}`;
43
+ }
757
44
 
758
45
  // src/core/sqlite-wrapper.ts
759
46
  import Database from "better-sqlite3";
@@ -1268,7 +555,7 @@ var SQLiteEventStore = class {
1268
555
  isDuplicate: true
1269
556
  };
1270
557
  }
1271
- const id = randomUUID2();
558
+ const id = randomUUID();
1272
559
  const timestamp = toSQLiteTimestamp(input.timestamp);
1273
560
  try {
1274
561
  const metadata = input.metadata || {};
@@ -1322,6 +609,29 @@ var SQLiteEventStore = class {
1322
609
  };
1323
610
  }
1324
611
  }
612
+ /**
613
+ * Get session IDs that have events but no session_summary event.
614
+ * Used to backfill summaries for sessions that ended without Stop hook.
615
+ */
616
+ async getSessionsWithoutSummary(currentSessionId, limit = 5) {
617
+ await this.initialize();
618
+ const rows = sqliteAll(
619
+ this.db,
620
+ `SELECT DISTINCT e.session_id
621
+ FROM events e
622
+ WHERE e.session_id != ?
623
+ AND e.event_type != 'session_summary'
624
+ AND e.session_id NOT IN (
625
+ SELECT DISTINCT session_id FROM events WHERE event_type = 'session_summary'
626
+ )
627
+ GROUP BY e.session_id
628
+ HAVING COUNT(*) >= 3
629
+ ORDER BY MAX(e.timestamp) DESC
630
+ LIMIT ?`,
631
+ [currentSessionId, limit]
632
+ );
633
+ return rows.map((r) => r.session_id);
634
+ }
1325
635
  /**
1326
636
  * Get events by session ID
1327
637
  */
@@ -1549,7 +859,7 @@ var SQLiteEventStore = class {
1549
859
  */
1550
860
  async enqueueForEmbedding(eventId, content) {
1551
861
  await this.initialize();
1552
- const id = randomUUID2();
862
+ const id = randomUUID();
1553
863
  sqliteRun(
1554
864
  this.db,
1555
865
  `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
@@ -1830,7 +1140,7 @@ var SQLiteEventStore = class {
1830
1140
  if (this.readOnly)
1831
1141
  return;
1832
1142
  await this.initialize();
1833
- const id = randomUUID2();
1143
+ const id = randomUUID();
1834
1144
  sqliteRun(
1835
1145
  this.db,
1836
1146
  `INSERT INTO memory_helpfulness (id, event_id, session_id, retrieval_score, query_preview, created_at)
@@ -2051,7 +1361,7 @@ var SQLiteEventStore = class {
2051
1361
  }
2052
1362
  async recordRetrievalTrace(input) {
2053
1363
  await this.initialize();
2054
- const traceId = randomUUID2();
1364
+ const traceId = randomUUID();
2055
1365
  sqliteRun(
2056
1366
  this.db,
2057
1367
  `INSERT INTO retrieval_traces (
@@ -2305,169 +1615,6 @@ var SQLiteEventStore = class {
2305
1615
  }
2306
1616
  };
2307
1617
 
2308
- // src/core/sync-worker.ts
2309
- var DEFAULT_CONFIG = {
2310
- intervalMs: 3e4,
2311
- batchSize: 500,
2312
- maxRetries: 3,
2313
- retryDelayMs: 5e3
2314
- };
2315
- var SyncWorker = class {
2316
- constructor(sqliteStore, duckdbStore, config) {
2317
- this.sqliteStore = sqliteStore;
2318
- this.duckdbStore = duckdbStore;
2319
- this.config = { ...DEFAULT_CONFIG, ...config };
2320
- }
2321
- config;
2322
- intervalHandle = null;
2323
- running = false;
2324
- stats = {
2325
- lastSyncAt: null,
2326
- eventsSynced: 0,
2327
- sessionsSynced: 0,
2328
- errors: 0,
2329
- status: "idle"
2330
- };
2331
- /**
2332
- * Start the sync worker
2333
- */
2334
- start() {
2335
- if (this.running)
2336
- return;
2337
- this.running = true;
2338
- this.stats.status = "idle";
2339
- this.syncNow().catch((err) => {
2340
- console.error("[SyncWorker] Initial sync failed:", err);
2341
- });
2342
- this.intervalHandle = setInterval(() => {
2343
- this.syncNow().catch((err) => {
2344
- console.error("[SyncWorker] Periodic sync failed:", err);
2345
- });
2346
- }, this.config.intervalMs);
2347
- }
2348
- /**
2349
- * Stop the sync worker
2350
- */
2351
- stop() {
2352
- this.running = false;
2353
- this.stats.status = "stopped";
2354
- if (this.intervalHandle) {
2355
- clearInterval(this.intervalHandle);
2356
- this.intervalHandle = null;
2357
- }
2358
- }
2359
- /**
2360
- * Trigger immediate sync
2361
- */
2362
- async syncNow() {
2363
- if (this.stats.status === "syncing") {
2364
- return;
2365
- }
2366
- this.stats.status = "syncing";
2367
- try {
2368
- await this.syncEvents();
2369
- await this.syncSessions();
2370
- this.stats.lastSyncAt = /* @__PURE__ */ new Date();
2371
- this.stats.status = "idle";
2372
- } catch (error) {
2373
- this.stats.errors++;
2374
- this.stats.status = "error";
2375
- throw error;
2376
- }
2377
- }
2378
- /**
2379
- * Sync events from SQLite to DuckDB
2380
- */
2381
- async syncEvents() {
2382
- const targetName = "duckdb_analytics";
2383
- const position = await this.sqliteStore.getSyncPosition(targetName);
2384
- const lastTimestamp = position.lastTimestamp || "1970-01-01T00:00:00.000Z";
2385
- let hasMore = true;
2386
- let totalSynced = 0;
2387
- while (hasMore) {
2388
- const events = await this.sqliteStore.getEventsSince(lastTimestamp, this.config.batchSize);
2389
- if (events.length === 0) {
2390
- hasMore = false;
2391
- break;
2392
- }
2393
- await this.retryWithBackoff(async () => {
2394
- for (const event of events) {
2395
- await this.insertEventToDuckDB(event);
2396
- }
2397
- });
2398
- totalSynced += events.length;
2399
- const lastEvent = events[events.length - 1];
2400
- await this.sqliteStore.updateSyncPosition(
2401
- targetName,
2402
- lastEvent.id,
2403
- lastEvent.timestamp.toISOString()
2404
- );
2405
- hasMore = events.length === this.config.batchSize;
2406
- }
2407
- this.stats.eventsSynced += totalSynced;
2408
- }
2409
- /**
2410
- * Sync sessions from SQLite to DuckDB
2411
- */
2412
- async syncSessions() {
2413
- const sessions = await this.sqliteStore.getAllSessions();
2414
- for (const session of sessions) {
2415
- await this.retryWithBackoff(async () => {
2416
- await this.duckdbStore.upsertSession(session);
2417
- });
2418
- }
2419
- this.stats.sessionsSynced = sessions.length;
2420
- }
2421
- /**
2422
- * Insert a single event into DuckDB
2423
- */
2424
- async insertEventToDuckDB(event) {
2425
- await this.duckdbStore.append({
2426
- eventType: event.eventType,
2427
- sessionId: event.sessionId,
2428
- timestamp: event.timestamp,
2429
- content: event.content,
2430
- metadata: event.metadata
2431
- });
2432
- }
2433
- /**
2434
- * Retry operation with exponential backoff
2435
- */
2436
- async retryWithBackoff(fn) {
2437
- let lastError = null;
2438
- for (let attempt = 0; attempt < this.config.maxRetries; attempt++) {
2439
- try {
2440
- return await fn();
2441
- } catch (error) {
2442
- lastError = error instanceof Error ? error : new Error(String(error));
2443
- if (attempt < this.config.maxRetries - 1) {
2444
- const delay = this.config.retryDelayMs * Math.pow(2, attempt);
2445
- await this.sleep(delay);
2446
- }
2447
- }
2448
- }
2449
- throw lastError;
2450
- }
2451
- /**
2452
- * Sleep utility
2453
- */
2454
- sleep(ms) {
2455
- return new Promise((resolve2) => setTimeout(resolve2, ms));
2456
- }
2457
- /**
2458
- * Get sync statistics
2459
- */
2460
- getStats() {
2461
- return { ...this.stats };
2462
- }
2463
- /**
2464
- * Check if worker is running
2465
- */
2466
- isRunning() {
2467
- return this.running;
2468
- }
2469
- };
2470
-
2471
1618
  // src/core/vector-store.ts
2472
1619
  import * as lancedb from "@lancedb/lancedb";
2473
1620
  var VectorStore = class {
@@ -2755,8 +1902,34 @@ function getDefaultEmbedder() {
2755
1902
  return defaultEmbedder;
2756
1903
  }
2757
1904
 
1905
+ // src/core/db-wrapper.ts
1906
+ import BetterSqlite3 from "better-sqlite3";
1907
+ function toDate(value) {
1908
+ if (value instanceof Date)
1909
+ return value;
1910
+ if (typeof value === "string")
1911
+ return new Date(value);
1912
+ if (typeof value === "number")
1913
+ return new Date(value);
1914
+ return new Date(String(value));
1915
+ }
1916
+ function createDatabase(dbPath, options) {
1917
+ return new BetterSqlite3(dbPath, { readonly: options?.readOnly });
1918
+ }
1919
+ function dbRun(db, sql, params = []) {
1920
+ db.prepare(sql).run(...params);
1921
+ return Promise.resolve();
1922
+ }
1923
+ function dbAll(db, sql, params = []) {
1924
+ return Promise.resolve(db.prepare(sql).all(...params));
1925
+ }
1926
+ function dbClose(db) {
1927
+ db.close();
1928
+ return Promise.resolve();
1929
+ }
1930
+
2758
1931
  // src/core/vector-outbox.ts
2759
- var DEFAULT_CONFIG2 = {
1932
+ var DEFAULT_CONFIG = {
2760
1933
  embeddingVersion: "v1",
2761
1934
  maxRetries: 3,
2762
1935
  stuckThresholdMs: 5 * 60 * 1e3,
@@ -2765,7 +1938,7 @@ var DEFAULT_CONFIG2 = {
2765
1938
  };
2766
1939
 
2767
1940
  // src/core/vector-worker.ts
2768
- var DEFAULT_CONFIG3 = {
1941
+ var DEFAULT_CONFIG2 = {
2769
1942
  batchSize: 32,
2770
1943
  pollIntervalMs: 1e3,
2771
1944
  maxRetries: 3
@@ -2782,7 +1955,7 @@ var VectorWorker = class {
2782
1955
  this.eventStore = eventStore;
2783
1956
  this.vectorStore = vectorStore;
2784
1957
  this.embedder = embedder;
2785
- this.config = { ...DEFAULT_CONFIG3, ...config };
1958
+ this.config = { ...DEFAULT_CONFIG2, ...config };
2786
1959
  }
2787
1960
  /**
2788
1961
  * Start the worker polling loop
@@ -2903,7 +2076,7 @@ function createVectorWorker(eventStore, vectorStore, embedder, config) {
2903
2076
  }
2904
2077
 
2905
2078
  // src/core/matcher.ts
2906
- var DEFAULT_CONFIG4 = {
2079
+ var DEFAULT_CONFIG3 = {
2907
2080
  weights: {
2908
2081
  semanticSimilarity: 0.4,
2909
2082
  ftsScore: 0.25,
@@ -2918,9 +2091,9 @@ var Matcher = class {
2918
2091
  config;
2919
2092
  constructor(config = {}) {
2920
2093
  this.config = {
2921
- ...DEFAULT_CONFIG4,
2094
+ ...DEFAULT_CONFIG3,
2922
2095
  ...config,
2923
- weights: { ...DEFAULT_CONFIG4.weights, ...config.weights }
2096
+ weights: { ...DEFAULT_CONFIG3.weights, ...config.weights }
2924
2097
  };
2925
2098
  }
2926
2099
  /**
@@ -3910,7 +3083,7 @@ function createSharedEventStore(dbPath) {
3910
3083
  }
3911
3084
 
3912
3085
  // src/core/shared-store.ts
3913
- import { randomUUID as randomUUID3 } from "crypto";
3086
+ import { randomUUID as randomUUID2 } from "crypto";
3914
3087
  var SharedStore = class {
3915
3088
  constructor(sharedEventStore) {
3916
3089
  this.sharedEventStore = sharedEventStore;
@@ -3922,7 +3095,7 @@ var SharedStore = class {
3922
3095
  * Promote a verified troubleshooting entry to shared storage
3923
3096
  */
3924
3097
  async promoteEntry(input) {
3925
- const entryId = randomUUID3();
3098
+ const entryId = randomUUID2();
3926
3099
  await dbRun(
3927
3100
  this.db,
3928
3101
  `INSERT INTO shared_troubleshooting (
@@ -4287,7 +3460,7 @@ function createSharedVectorStore(dbPath) {
4287
3460
  }
4288
3461
 
4289
3462
  // src/core/shared-promoter.ts
4290
- import { randomUUID as randomUUID4 } from "crypto";
3463
+ import { randomUUID as randomUUID3 } from "crypto";
4291
3464
  var SharedPromoter = class {
4292
3465
  constructor(sharedStore, sharedVectorStore, embedder, config) {
4293
3466
  this.sharedStore = sharedStore;
@@ -4355,7 +3528,7 @@ var SharedPromoter = class {
4355
3528
  const embeddingContent = this.createEmbeddingContent(input);
4356
3529
  const embedding = await this.embedder.embed(embeddingContent);
4357
3530
  await this.sharedVectorStore.upsert({
4358
- id: randomUUID4(),
3531
+ id: randomUUID3(),
4359
3532
  entryId,
4360
3533
  entryType: "troubleshooting",
4361
3534
  content: embeddingContent,
@@ -4495,7 +3668,7 @@ function createToolObservationEmbedding(toolName, metadata, success) {
4495
3668
  }
4496
3669
 
4497
3670
  // src/core/working-set-store.ts
4498
- import { randomUUID as randomUUID5 } from "crypto";
3671
+ import { randomUUID as randomUUID4 } from "crypto";
4499
3672
  var WorkingSetStore = class {
4500
3673
  constructor(eventStore, config) {
4501
3674
  this.eventStore = eventStore;
@@ -4516,7 +3689,7 @@ var WorkingSetStore = class {
4516
3689
  `INSERT OR REPLACE INTO working_set (id, event_id, added_at, relevance_score, topics, expires_at)
4517
3690
  VALUES (?, ?, CURRENT_TIMESTAMP, ?, ?, ?)`,
4518
3691
  [
4519
- randomUUID5(),
3692
+ randomUUID4(),
4520
3693
  eventId,
4521
3694
  relevanceScore,
4522
3695
  JSON.stringify(topics || []),
@@ -4700,7 +3873,7 @@ function createWorkingSetStore(eventStore, config) {
4700
3873
  }
4701
3874
 
4702
3875
  // src/core/consolidated-store.ts
4703
- import { randomUUID as randomUUID6 } from "crypto";
3876
+ import { randomUUID as randomUUID5 } from "crypto";
4704
3877
  var ConsolidatedStore = class {
4705
3878
  constructor(eventStore) {
4706
3879
  this.eventStore = eventStore;
@@ -4712,7 +3885,7 @@ var ConsolidatedStore = class {
4712
3885
  * Create a new consolidated memory
4713
3886
  */
4714
3887
  async create(input) {
4715
- const memoryId = randomUUID6();
3888
+ const memoryId = randomUUID5();
4716
3889
  await dbRun(
4717
3890
  this.db,
4718
3891
  `INSERT INTO consolidated_memories
@@ -4842,7 +4015,7 @@ var ConsolidatedStore = class {
4842
4015
  * Create a long-term rule promoted from stable summaries
4843
4016
  */
4844
4017
  async createRule(input) {
4845
- const ruleId = randomUUID6();
4018
+ const ruleId = randomUUID5();
4846
4019
  await dbRun(
4847
4020
  this.db,
4848
4021
  `INSERT INTO consolidated_rules
@@ -5364,7 +4537,7 @@ function createConsolidationWorker(workingSetStore, consolidatedStore, config) {
5364
4537
  }
5365
4538
 
5366
4539
  // src/core/continuity-manager.ts
5367
- import { randomUUID as randomUUID7 } from "crypto";
4540
+ import { randomUUID as randomUUID6 } from "crypto";
5368
4541
  var ContinuityManager = class {
5369
4542
  constructor(eventStore, config) {
5370
4543
  this.eventStore = eventStore;
@@ -5518,7 +4691,7 @@ var ContinuityManager = class {
5518
4691
  `INSERT INTO continuity_log
5519
4692
  (log_id, from_context_id, to_context_id, continuity_score, transition_type, created_at)
5520
4693
  VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
5521
- [randomUUID7(), previous.id, current.id, score, type]
4694
+ [randomUUID6(), previous.id, current.id, score, type]
5522
4695
  );
5523
4696
  }
5524
4697
  /**
@@ -5627,7 +4800,7 @@ function createContinuityManager(eventStore, config) {
5627
4800
  }
5628
4801
 
5629
4802
  // src/core/graduation-worker.ts
5630
- var DEFAULT_CONFIG5 = {
4803
+ var DEFAULT_CONFIG4 = {
5631
4804
  evaluationIntervalMs: 3e5,
5632
4805
  // 5 minutes
5633
4806
  batchSize: 50,
@@ -5635,7 +4808,7 @@ var DEFAULT_CONFIG5 = {
5635
4808
  // 1 hour cooldown between evaluations
5636
4809
  };
5637
4810
  var GraduationWorker = class {
5638
- constructor(eventStore, graduation, config = DEFAULT_CONFIG5) {
4811
+ constructor(eventStore, graduation, config = DEFAULT_CONFIG4) {
5639
4812
  this.eventStore = eventStore;
5640
4813
  this.graduation = graduation;
5641
4814
  this.config = config;
@@ -5743,7 +4916,7 @@ function createGraduationWorker(eventStore, graduation, config) {
5743
4916
  return new GraduationWorker(
5744
4917
  eventStore,
5745
4918
  graduation,
5746
- { ...DEFAULT_CONFIG5, ...config }
4919
+ { ...DEFAULT_CONFIG4, ...config }
5747
4920
  );
5748
4921
  }
5749
4922
 
@@ -5956,9 +5129,6 @@ function getSessionProject(sessionId) {
5956
5129
  var MemoryService = class {
5957
5130
  // Primary store: SQLite (WAL mode) - for hooks, always available
5958
5131
  sqliteStore;
5959
- // Analytics store: DuckDB - for server reads (optional, synced from SQLite)
5960
- analyticsStore;
5961
- syncWorker = null;
5962
5132
  vectorStore;
5963
5133
  embedder;
5964
5134
  matcher;
@@ -6007,24 +5177,6 @@ var MemoryService = class {
6007
5177
  markdownMirrorRoot: storagePath
6008
5178
  }
6009
5179
  );
6010
- const analyticsEnabled = config.analyticsEnabled ?? this.readOnly;
6011
- if (!analyticsEnabled) {
6012
- this.analyticsStore = null;
6013
- } else if (this.readOnly) {
6014
- try {
6015
- this.analyticsStore = new EventStore(
6016
- path3.join(storagePath, "analytics.duckdb"),
6017
- { readOnly: true }
6018
- );
6019
- } catch {
6020
- this.analyticsStore = null;
6021
- }
6022
- } else {
6023
- this.analyticsStore = new EventStore(
6024
- path3.join(storagePath, "analytics.duckdb"),
6025
- { readOnly: false }
6026
- );
6027
- }
6028
5180
  this.vectorStore = new VectorStore(path3.join(storagePath, "vectors"));
6029
5181
  const embeddingModel = config.embeddingModel || process.env.CLAUDE_MEMORY_EMBEDDING_MODEL;
6030
5182
  this.embedder = embeddingModel ? new Embedder(embeddingModel) : getDefaultEmbedder();
@@ -6050,13 +5202,6 @@ var MemoryService = class {
6050
5202
  this.initialized = true;
6051
5203
  return;
6052
5204
  }
6053
- if (this.analyticsStore) {
6054
- try {
6055
- await this.analyticsStore.initialize();
6056
- } catch (error) {
6057
- console.warn("[MemoryService] Analytics store (DuckDB) initialization failed, using SQLite for reads:", error);
6058
- }
6059
- }
6060
5205
  await this.vectorStore.initialize();
6061
5206
  await this.embedder.initialize();
6062
5207
  if (!this.readOnly) {
@@ -6073,14 +5218,6 @@ var MemoryService = class {
6073
5218
  this.graduation
6074
5219
  );
6075
5220
  this.graduationWorker.start();
6076
- if (this.analyticsStore) {
6077
- this.syncWorker = new SyncWorker(
6078
- this.sqliteStore,
6079
- this.analyticsStore,
6080
- { intervalMs: 3e4, batchSize: 500 }
6081
- );
6082
- this.syncWorker.start();
6083
- }
6084
5221
  }
6085
5222
  const savedMode = await this.sqliteStore.getEndlessConfig("mode");
6086
5223
  if (savedMode === "endless") {
@@ -6277,6 +5414,57 @@ var MemoryService = class {
6277
5414
  }
6278
5415
  );
6279
5416
  }
5417
+ /**
5418
+ * Backfill session summaries for recent sessions that are missing them.
5419
+ * Called from session-start hook to catch sessions that ended without Stop hook.
5420
+ */
5421
+ async backfillMissingSummaries(currentSessionId, limit = 5) {
5422
+ await this.initialize();
5423
+ const recentSessionIds = await this.sqliteStore.getSessionsWithoutSummary(currentSessionId, limit);
5424
+ for (const sid of recentSessionIds) {
5425
+ try {
5426
+ await this.generateSessionSummary(sid);
5427
+ } catch {
5428
+ }
5429
+ }
5430
+ }
5431
+ /**
5432
+ * Generate a rule-based session summary from stored events.
5433
+ * Called at session end (Stop hook) when no LLM-generated summary exists.
5434
+ * Skips if a summary already exists for this session.
5435
+ */
5436
+ async generateSessionSummary(sessionId) {
5437
+ await this.initialize();
5438
+ const events = await this.sqliteStore.getSessionEvents(sessionId);
5439
+ if (events.length < 3)
5440
+ return;
5441
+ const hasSummary = events.some((e) => e.eventType === "session_summary");
5442
+ if (hasSummary)
5443
+ return;
5444
+ const prompts = events.filter((e) => e.eventType === "user_prompt");
5445
+ const toolObs = events.filter((e) => e.eventType === "tool_observation");
5446
+ const toolNames = [...new Set(
5447
+ toolObs.map((e) => e.metadata?.toolName).filter(Boolean)
5448
+ )];
5449
+ const errorObs = toolObs.filter((e) => {
5450
+ const meta = e.metadata;
5451
+ return meta?.exitCode !== void 0 && meta.exitCode !== 0;
5452
+ });
5453
+ const datePart = events[0].timestamp.toISOString().split("T")[0];
5454
+ const parts = [`[${datePart}] ${prompts.length}\uD134 \uC138\uC158.`];
5455
+ if (prompts.length > 0) {
5456
+ const firstPrompt = prompts[0].content.slice(0, 120).replace(/\n/g, " ");
5457
+ parts.push(`\uC8FC\uC694 \uC791\uC5C5: ${firstPrompt}`);
5458
+ }
5459
+ if (toolNames.length > 0) {
5460
+ parts.push(`\uC0AC\uC6A9 \uD234: ${toolNames.slice(0, 6).join(", ")}`);
5461
+ }
5462
+ if (errorObs.length > 0) {
5463
+ parts.push(`\uC624\uB958 ${errorObs.length}\uAC74 \uBC1C\uC0DD`);
5464
+ }
5465
+ const summary = parts.join(". ");
5466
+ await this.storeSessionSummary(sessionId, summary, { generated: "rule-based", eventCount: events.length });
5467
+ }
6280
5468
  /**
6281
5469
  * Store a tool observation
6282
5470
  */
@@ -6812,6 +6000,7 @@ var MemoryService = class {
6812
6000
  await this.initialize();
6813
6001
  await this.sqliteStore.recordRetrievalTrace({
6814
6002
  ...input,
6003
+ projectHash: this.projectHash || void 0,
6815
6004
  candidateDetails: [],
6816
6005
  selectedDetails: [],
6817
6006
  fallbackTrace: []
@@ -7102,16 +6291,10 @@ var MemoryService = class {
7102
6291
  if (this.vectorWorker) {
7103
6292
  this.vectorWorker.stop();
7104
6293
  }
7105
- if (this.syncWorker) {
7106
- this.syncWorker.stop();
7107
- }
7108
6294
  if (this.sharedEventStore) {
7109
6295
  await this.sharedEventStore.close();
7110
6296
  }
7111
6297
  await this.sqliteStore.close();
7112
- if (this.analyticsStore) {
7113
- await this.analyticsStore.close();
7114
- }
7115
6298
  }
7116
6299
  /**
7117
6300
  * Expand ~ to home directory
@@ -7425,6 +6608,14 @@ async function main() {
7425
6608
  writeLastAssistantSnippet(input.session_id, lastMessage);
7426
6609
  }
7427
6610
  clearTurnState(input.session_id);
6611
+ try {
6612
+ await memoryService.evaluateSessionHelpfulness(input.session_id);
6613
+ } catch {
6614
+ }
6615
+ try {
6616
+ await memoryService.generateSessionSummary(input.session_id);
6617
+ } catch {
6618
+ }
7428
6619
  await memoryService.processPendingEmbeddings();
7429
6620
  console.log(JSON.stringify({}));
7430
6621
  } catch (error) {