claude-memory-layer 1.0.24 → 1.0.26

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 (44) hide show
  1. package/.claude/settings.local.json +15 -1
  2. package/dist/cli/index.js +156 -972
  3. package/dist/cli/index.js.map +4 -4
  4. package/dist/core/index.js +33 -67
  5. package/dist/core/index.js.map +3 -3
  6. package/dist/hooks/post-tool-use.js +183 -968
  7. package/dist/hooks/post-tool-use.js.map +4 -4
  8. package/dist/hooks/semantic-daemon.js +150 -966
  9. package/dist/hooks/semantic-daemon.js.map +4 -4
  10. package/dist/hooks/session-end.js +150 -966
  11. package/dist/hooks/session-end.js.map +4 -4
  12. package/dist/hooks/session-start.js +152 -966
  13. package/dist/hooks/session-start.js.map +4 -4
  14. package/dist/hooks/stop.js +158 -966
  15. package/dist/hooks/stop.js.map +4 -4
  16. package/dist/hooks/user-prompt-submit.js +152 -968
  17. package/dist/hooks/user-prompt-submit.js.map +4 -4
  18. package/dist/server/api/index.js +151 -967
  19. package/dist/server/api/index.js.map +4 -4
  20. package/dist/server/index.js +151 -967
  21. package/dist/server/index.js.map +4 -4
  22. package/dist/services/memory-service.js +150 -966
  23. package/dist/services/memory-service.js.map +4 -4
  24. package/memory/_index.md +2 -0
  25. package/memory/agent_response/uncategorized/2026-03-04.md +276 -1
  26. package/memory/agent_response/uncategorized/2026-03-05.md +48 -0
  27. package/memory/session_summary/uncategorized/2026-03-04.md +20 -1
  28. package/memory/tool_observation/uncategorized/2026-03-04.md +245 -1
  29. package/memory/tool_observation/uncategorized/2026-03-05.md +29 -0
  30. package/memory/user_prompt/uncategorized/2026-03-04.md +193 -1
  31. package/package.json +1 -2
  32. package/specs/memory-utilization-improvements/context.md +145 -0
  33. package/specs/memory-utilization-improvements/plan.md +361 -0
  34. package/specs/memory-utilization-improvements/spec.md +361 -0
  35. package/specs/optional-duckdb/context.md +77 -0
  36. package/specs/optional-duckdb/plan.md +142 -0
  37. package/specs/optional-duckdb/spec.md +35 -0
  38. package/src/core/db-wrapper.ts +18 -73
  39. package/src/core/sqlite-event-store.ts +32 -4
  40. package/src/hooks/post-tool-use.ts +25 -0
  41. package/src/hooks/session-start.ts +4 -0
  42. package/src/hooks/stop.ts +14 -0
  43. package/src/server/api/utils.ts +1 -1
  44. package/src/services/memory-service.ts +62 -58
package/dist/cli/index.js CHANGED
@@ -26,744 +26,31 @@ import * as os from "os";
26
26
  import * as fs4 from "fs";
27
27
  import * as crypto2 from "crypto";
28
28
 
29
- // src/core/event-store.ts
30
- import { randomUUID } from "crypto";
31
-
32
- // src/core/canonical-key.ts
33
- import { createHash } from "crypto";
34
- var MAX_KEY_LENGTH = 200;
35
- function makeCanonicalKey(title, context) {
36
- let normalized = title.normalize("NFKC");
37
- normalized = normalized.toLowerCase();
38
- normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, "");
39
- normalized = normalized.replace(/\s+/g, " ").trim();
40
- let key = normalized;
41
- if (context?.project) {
42
- key = `${context.project}::${key}`;
43
- }
44
- if (key.length > MAX_KEY_LENGTH) {
45
- const hashSuffix = createHash("md5").update(key).digest("hex").slice(0, 8);
46
- key = key.slice(0, MAX_KEY_LENGTH - 9) + "_" + hashSuffix;
47
- }
48
- return key;
49
- }
50
- function makeDedupeKey(content, sessionId) {
51
- const contentHash = createHash("sha256").update(content).digest("hex");
52
- return `${sessionId}:${contentHash}`;
53
- }
54
-
55
- // src/core/db-wrapper.ts
56
- import duckdb from "duckdb";
57
- function convertBigInts(obj) {
58
- if (obj === null || obj === void 0)
59
- return obj;
60
- if (typeof obj === "bigint")
61
- return Number(obj);
62
- if (obj instanceof Date)
63
- return obj;
64
- if (Array.isArray(obj))
65
- return obj.map(convertBigInts);
66
- if (typeof obj === "object") {
67
- const result = {};
68
- for (const [key, value] of Object.entries(obj)) {
69
- result[key] = convertBigInts(value);
70
- }
71
- return result;
72
- }
73
- return obj;
74
- }
75
- function toDate(value) {
76
- if (value instanceof Date)
77
- return value;
78
- if (typeof value === "string")
79
- return new Date(value);
80
- if (typeof value === "number")
81
- return new Date(value);
82
- return new Date(String(value));
83
- }
84
- function createDatabase(path11, options) {
85
- if (options?.readOnly) {
86
- return new duckdb.Database(path11, { access_mode: "READ_ONLY" });
87
- }
88
- return new duckdb.Database(path11);
89
- }
90
- function dbRun(db, sql, params = []) {
91
- return new Promise((resolve5, reject) => {
92
- if (params.length === 0) {
93
- db.run(sql, (err) => {
94
- if (err)
95
- reject(err);
96
- else
97
- resolve5();
98
- });
99
- } else {
100
- db.run(sql, ...params, (err) => {
101
- if (err)
102
- reject(err);
103
- else
104
- resolve5();
105
- });
106
- }
107
- });
108
- }
109
- function dbAll(db, sql, params = []) {
110
- return new Promise((resolve5, reject) => {
111
- if (params.length === 0) {
112
- db.all(sql, (err, rows) => {
113
- if (err)
114
- reject(err);
115
- else
116
- resolve5(convertBigInts(rows || []));
117
- });
118
- } else {
119
- db.all(sql, ...params, (err, rows) => {
120
- if (err)
121
- reject(err);
122
- else
123
- resolve5(convertBigInts(rows || []));
124
- });
125
- }
126
- });
127
- }
128
- function dbClose(db) {
129
- return new Promise((resolve5, reject) => {
130
- db.close((err) => {
131
- if (err)
132
- reject(err);
133
- else
134
- resolve5();
135
- });
136
- });
137
- }
138
-
139
- // src/core/event-store.ts
140
- var EventStore = class {
141
- constructor(dbPath, options) {
142
- this.dbPath = dbPath;
143
- this.readOnly = options?.readOnly ?? false;
144
- this.db = createDatabase(dbPath, { readOnly: this.readOnly });
145
- }
146
- db;
147
- initialized = false;
148
- readOnly;
149
- /**
150
- * Initialize database schema
151
- */
152
- async initialize() {
153
- if (this.initialized)
154
- return;
155
- if (this.readOnly) {
156
- this.initialized = true;
157
- return;
158
- }
159
- await dbRun(this.db, `
160
- CREATE TABLE IF NOT EXISTS events (
161
- id VARCHAR PRIMARY KEY,
162
- event_type VARCHAR NOT NULL,
163
- session_id VARCHAR NOT NULL,
164
- timestamp TIMESTAMP NOT NULL,
165
- content TEXT NOT NULL,
166
- canonical_key VARCHAR NOT NULL,
167
- dedupe_key VARCHAR UNIQUE,
168
- metadata JSON
169
- )
170
- `);
171
- await dbRun(this.db, `
172
- CREATE TABLE IF NOT EXISTS event_dedup (
173
- dedupe_key VARCHAR PRIMARY KEY,
174
- event_id VARCHAR NOT NULL,
175
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
176
- )
177
- `);
178
- await dbRun(this.db, `
179
- CREATE TABLE IF NOT EXISTS sessions (
180
- id VARCHAR PRIMARY KEY,
181
- started_at TIMESTAMP NOT NULL,
182
- ended_at TIMESTAMP,
183
- project_path VARCHAR,
184
- summary TEXT,
185
- tags JSON
186
- )
187
- `);
188
- await dbRun(this.db, `
189
- CREATE TABLE IF NOT EXISTS insights (
190
- id VARCHAR PRIMARY KEY,
191
- insight_type VARCHAR NOT NULL,
192
- content TEXT NOT NULL,
193
- canonical_key VARCHAR NOT NULL,
194
- confidence FLOAT,
195
- source_events JSON,
196
- created_at TIMESTAMP,
197
- last_updated TIMESTAMP
198
- )
199
- `);
200
- await dbRun(this.db, `
201
- CREATE TABLE IF NOT EXISTS embedding_outbox (
202
- id VARCHAR PRIMARY KEY,
203
- event_id VARCHAR NOT NULL,
204
- content TEXT NOT NULL,
205
- status VARCHAR DEFAULT 'pending',
206
- retry_count INT DEFAULT 0,
207
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
208
- processed_at TIMESTAMP,
209
- error_message TEXT
210
- )
211
- `);
212
- await dbRun(this.db, `
213
- CREATE TABLE IF NOT EXISTS projection_offsets (
214
- projection_name VARCHAR PRIMARY KEY,
215
- last_event_id VARCHAR,
216
- last_timestamp TIMESTAMP,
217
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
218
- )
219
- `);
220
- await dbRun(this.db, `
221
- CREATE TABLE IF NOT EXISTS memory_levels (
222
- event_id VARCHAR PRIMARY KEY,
223
- level VARCHAR NOT NULL DEFAULT 'L0',
224
- promoted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
225
- )
226
- `);
227
- await dbRun(this.db, `
228
- CREATE TABLE IF NOT EXISTS entries (
229
- entry_id VARCHAR PRIMARY KEY,
230
- created_ts TIMESTAMP NOT NULL,
231
- entry_type VARCHAR NOT NULL,
232
- title VARCHAR NOT NULL,
233
- content_json JSON NOT NULL,
234
- stage VARCHAR NOT NULL DEFAULT 'raw',
235
- status VARCHAR DEFAULT 'active',
236
- superseded_by VARCHAR,
237
- build_id VARCHAR,
238
- evidence_json JSON,
239
- canonical_key VARCHAR,
240
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
241
- )
242
- `);
243
- await dbRun(this.db, `
244
- CREATE TABLE IF NOT EXISTS entities (
245
- entity_id VARCHAR PRIMARY KEY,
246
- entity_type VARCHAR NOT NULL,
247
- canonical_key VARCHAR NOT NULL,
248
- title VARCHAR NOT NULL,
249
- stage VARCHAR NOT NULL DEFAULT 'raw',
250
- status VARCHAR NOT NULL DEFAULT 'active',
251
- current_json JSON NOT NULL,
252
- title_norm VARCHAR,
253
- search_text VARCHAR,
254
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
255
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
256
- )
257
- `);
258
- await dbRun(this.db, `
259
- CREATE TABLE IF NOT EXISTS entity_aliases (
260
- entity_type VARCHAR NOT NULL,
261
- canonical_key VARCHAR NOT NULL,
262
- entity_id VARCHAR NOT NULL,
263
- is_primary BOOLEAN DEFAULT FALSE,
264
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
265
- PRIMARY KEY(entity_type, canonical_key)
266
- )
267
- `);
268
- await dbRun(this.db, `
269
- CREATE TABLE IF NOT EXISTS edges (
270
- edge_id VARCHAR PRIMARY KEY,
271
- src_type VARCHAR NOT NULL,
272
- src_id VARCHAR NOT NULL,
273
- rel_type VARCHAR NOT NULL,
274
- dst_type VARCHAR NOT NULL,
275
- dst_id VARCHAR NOT NULL,
276
- meta_json JSON,
277
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
278
- )
279
- `);
280
- await dbRun(this.db, `
281
- CREATE TABLE IF NOT EXISTS vector_outbox (
282
- job_id VARCHAR PRIMARY KEY,
283
- item_kind VARCHAR NOT NULL,
284
- item_id VARCHAR NOT NULL,
285
- embedding_version VARCHAR NOT NULL,
286
- status VARCHAR NOT NULL DEFAULT 'pending',
287
- retry_count INT DEFAULT 0,
288
- error VARCHAR,
289
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
290
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
291
- UNIQUE(item_kind, item_id, embedding_version)
292
- )
293
- `);
294
- await dbRun(this.db, `
295
- CREATE TABLE IF NOT EXISTS build_runs (
296
- build_id VARCHAR PRIMARY KEY,
297
- started_at TIMESTAMP NOT NULL,
298
- finished_at TIMESTAMP,
299
- extractor_model VARCHAR NOT NULL,
300
- extractor_prompt_hash VARCHAR NOT NULL,
301
- embedder_model VARCHAR NOT NULL,
302
- embedding_version VARCHAR NOT NULL,
303
- idris_version VARCHAR NOT NULL,
304
- schema_version VARCHAR NOT NULL,
305
- status VARCHAR NOT NULL DEFAULT 'running',
306
- error VARCHAR
307
- )
308
- `);
309
- await dbRun(this.db, `
310
- CREATE TABLE IF NOT EXISTS pipeline_metrics (
311
- id VARCHAR PRIMARY KEY,
312
- ts TIMESTAMP NOT NULL,
313
- stage VARCHAR NOT NULL,
314
- latency_ms DOUBLE NOT NULL,
315
- success BOOLEAN NOT NULL,
316
- error VARCHAR,
317
- session_id VARCHAR
318
- )
319
- `);
320
- await dbRun(this.db, `
321
- CREATE TABLE IF NOT EXISTS working_set (
322
- id VARCHAR PRIMARY KEY,
323
- event_id VARCHAR NOT NULL,
324
- added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
325
- relevance_score FLOAT DEFAULT 1.0,
326
- topics JSON,
327
- expires_at TIMESTAMP
328
- )
329
- `);
330
- await dbRun(this.db, `
331
- CREATE TABLE IF NOT EXISTS consolidated_memories (
332
- memory_id VARCHAR PRIMARY KEY,
333
- summary TEXT NOT NULL,
334
- topics JSON,
335
- source_events JSON,
336
- confidence FLOAT DEFAULT 0.5,
337
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
338
- accessed_at TIMESTAMP,
339
- access_count INTEGER DEFAULT 0
340
- )
341
- `);
342
- await dbRun(this.db, `
343
- CREATE TABLE IF NOT EXISTS continuity_log (
344
- log_id VARCHAR PRIMARY KEY,
345
- from_context_id VARCHAR,
346
- to_context_id VARCHAR,
347
- continuity_score FLOAT,
348
- transition_type VARCHAR,
349
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
350
- )
351
- `);
352
- await dbRun(this.db, `
353
- CREATE TABLE IF NOT EXISTS consolidated_rules (
354
- rule_id VARCHAR PRIMARY KEY,
355
- rule TEXT NOT NULL,
356
- topics JSON,
357
- source_memory_ids JSON,
358
- source_events JSON,
359
- confidence FLOAT DEFAULT 0.5,
360
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
361
- )
362
- `);
363
- await dbRun(this.db, `
364
- CREATE TABLE IF NOT EXISTS endless_config (
365
- key VARCHAR PRIMARY KEY,
366
- value JSON,
367
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
368
- )
369
- `);
370
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_type ON entries(entry_type)`);
371
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_stage ON entries(stage)`);
372
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_canonical ON entries(canonical_key)`);
373
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entities_type_key ON entities(entity_type, canonical_key)`);
374
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entities_status ON entities(status)`);
375
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src_id, rel_type)`);
376
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_dst ON edges(dst_id, rel_type)`);
377
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_rel ON edges(rel_type)`);
378
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_outbox_status ON vector_outbox(status)`);
379
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_expires ON working_set(expires_at)`);
380
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_relevance ON working_set(relevance_score DESC)`);
381
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence DESC)`);
382
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_rules_confidence ON consolidated_rules(confidence DESC)`);
383
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at)`);
384
- this.initialized = true;
385
- }
386
- /**
387
- * Append event to store (AXIOMMIND Principle 2: Append-only)
388
- * Returns existing event ID if duplicate (Principle 3: Idempotency)
389
- */
390
- async append(input) {
391
- await this.initialize();
392
- const canonicalKey = makeCanonicalKey(input.content);
393
- const dedupeKey = makeDedupeKey(input.content, input.sessionId);
394
- const existing = await dbAll(
395
- this.db,
396
- `SELECT event_id FROM event_dedup WHERE dedupe_key = ?`,
397
- [dedupeKey]
398
- );
399
- if (existing.length > 0) {
400
- return {
401
- success: true,
402
- eventId: existing[0].event_id,
403
- isDuplicate: true
404
- };
405
- }
406
- const id = randomUUID();
407
- const timestamp = input.timestamp.toISOString();
408
- try {
409
- await dbRun(
410
- this.db,
411
- `INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
412
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
413
- [
414
- id,
415
- input.eventType,
416
- input.sessionId,
417
- timestamp,
418
- input.content,
419
- canonicalKey,
420
- dedupeKey,
421
- JSON.stringify(input.metadata || {})
422
- ]
423
- );
424
- await dbRun(
425
- this.db,
426
- `INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)`,
427
- [dedupeKey, id]
428
- );
429
- await dbRun(
430
- this.db,
431
- `INSERT INTO memory_levels (event_id, level) VALUES (?, 'L0')`,
432
- [id]
433
- );
434
- return { success: true, eventId: id, isDuplicate: false };
435
- } catch (error) {
436
- return {
437
- success: false,
438
- error: error instanceof Error ? error.message : String(error)
439
- };
440
- }
441
- }
442
- /**
443
- * Get events by session ID
444
- */
445
- async getSessionEvents(sessionId) {
446
- await this.initialize();
447
- const rows = await dbAll(
448
- this.db,
449
- `SELECT * FROM events WHERE session_id = ? ORDER BY timestamp ASC`,
450
- [sessionId]
451
- );
452
- return rows.map(this.rowToEvent);
453
- }
454
- /**
455
- * Get recent events
456
- */
457
- async getRecentEvents(limit = 100) {
458
- await this.initialize();
459
- const rows = await dbAll(
460
- this.db,
461
- `SELECT * FROM events ORDER BY timestamp DESC LIMIT ?`,
462
- [limit]
463
- );
464
- return rows.map(this.rowToEvent);
465
- }
466
- /**
467
- * Get event by ID
468
- */
469
- async getEvent(id) {
470
- await this.initialize();
471
- const rows = await dbAll(
472
- this.db,
473
- `SELECT * FROM events WHERE id = ?`,
474
- [id]
475
- );
476
- if (rows.length === 0)
477
- return null;
478
- return this.rowToEvent(rows[0]);
479
- }
480
- /**
481
- * Create or update session
482
- */
483
- async upsertSession(session) {
484
- await this.initialize();
485
- const existing = await dbAll(
486
- this.db,
487
- `SELECT id FROM sessions WHERE id = ?`,
488
- [session.id]
489
- );
490
- if (existing.length === 0) {
491
- await dbRun(
492
- this.db,
493
- `INSERT INTO sessions (id, started_at, project_path, tags)
494
- VALUES (?, ?, ?, ?)`,
495
- [
496
- session.id,
497
- (session.startedAt || /* @__PURE__ */ new Date()).toISOString(),
498
- session.projectPath || null,
499
- JSON.stringify(session.tags || [])
500
- ]
501
- );
502
- } else {
503
- const updates = [];
504
- const values = [];
505
- if (session.endedAt) {
506
- updates.push("ended_at = ?");
507
- values.push(session.endedAt.toISOString());
508
- }
509
- if (session.summary) {
510
- updates.push("summary = ?");
511
- values.push(session.summary);
512
- }
513
- if (session.tags) {
514
- updates.push("tags = ?");
515
- values.push(JSON.stringify(session.tags));
516
- }
517
- if (updates.length > 0) {
518
- values.push(session.id);
519
- await dbRun(
520
- this.db,
521
- `UPDATE sessions SET ${updates.join(", ")} WHERE id = ?`,
522
- values
523
- );
524
- }
525
- }
526
- }
527
- /**
528
- * Get session by ID
529
- */
530
- async getSession(id) {
531
- await this.initialize();
532
- const rows = await dbAll(
533
- this.db,
534
- `SELECT * FROM sessions WHERE id = ?`,
535
- [id]
536
- );
537
- if (rows.length === 0)
538
- return null;
539
- const row = rows[0];
540
- return {
541
- id: row.id,
542
- startedAt: toDate(row.started_at),
543
- endedAt: row.ended_at ? toDate(row.ended_at) : void 0,
544
- projectPath: row.project_path,
545
- summary: row.summary,
546
- tags: row.tags ? JSON.parse(row.tags) : void 0
547
- };
548
- }
549
- /**
550
- * Add to embedding outbox (Single-Writer Pattern)
551
- */
552
- async enqueueForEmbedding(eventId, content) {
553
- await this.initialize();
554
- const id = randomUUID();
555
- await dbRun(
556
- this.db,
557
- `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
558
- VALUES (?, ?, ?, 'pending', 0)`,
559
- [id, eventId, content]
560
- );
561
- return id;
562
- }
563
- /**
564
- * Get pending outbox items
565
- */
566
- async getPendingOutboxItems(limit = 32) {
567
- await this.initialize();
568
- const pending = await dbAll(
569
- this.db,
570
- `SELECT * FROM embedding_outbox
571
- WHERE status = 'pending'
572
- ORDER BY created_at
573
- LIMIT ?`,
574
- [limit]
575
- );
576
- if (pending.length === 0)
577
- return [];
578
- const ids = pending.map((r) => r.id);
579
- const placeholders = ids.map(() => "?").join(",");
580
- await dbRun(
581
- this.db,
582
- `UPDATE embedding_outbox SET status = 'processing' WHERE id IN (${placeholders})`,
583
- ids
584
- );
585
- return pending.map((row) => ({
586
- id: row.id,
587
- eventId: row.event_id,
588
- content: row.content,
589
- status: "processing",
590
- retryCount: row.retry_count,
591
- createdAt: toDate(row.created_at),
592
- errorMessage: row.error_message
593
- }));
594
- }
595
- /**
596
- * Mark outbox items as done
597
- */
598
- async completeOutboxItems(ids) {
599
- if (ids.length === 0)
600
- return;
601
- const placeholders = ids.map(() => "?").join(",");
602
- await dbRun(
603
- this.db,
604
- `DELETE FROM embedding_outbox WHERE id IN (${placeholders})`,
605
- ids
606
- );
607
- }
608
- /**
609
- * Mark outbox items as failed
610
- */
611
- async failOutboxItems(ids, error) {
612
- if (ids.length === 0)
613
- return;
614
- const placeholders = ids.map(() => "?").join(",");
615
- await dbRun(
616
- this.db,
617
- `UPDATE embedding_outbox
618
- SET status = CASE WHEN retry_count >= 3 THEN 'failed' ELSE 'pending' END,
619
- retry_count = retry_count + 1,
620
- error_message = ?
621
- WHERE id IN (${placeholders})`,
622
- [error, ...ids]
623
- );
624
- }
625
- /**
626
- * Update memory level
627
- */
628
- async updateMemoryLevel(eventId, level) {
629
- await this.initialize();
630
- await dbRun(
631
- this.db,
632
- `UPDATE memory_levels SET level = ?, promoted_at = CURRENT_TIMESTAMP WHERE event_id = ?`,
633
- [level, eventId]
634
- );
635
- }
636
- /**
637
- * Get memory level statistics
638
- */
639
- async getLevelStats() {
640
- await this.initialize();
641
- const rows = await dbAll(
642
- this.db,
643
- `SELECT level, COUNT(*) as count FROM memory_levels GROUP BY level`
644
- );
645
- return rows;
646
- }
647
- /**
648
- * Get events by memory level
649
- */
650
- async getEventsByLevel(level, options) {
651
- await this.initialize();
652
- const limit = options?.limit || 50;
653
- const offset = options?.offset || 0;
654
- const rows = await dbAll(
655
- this.db,
656
- `SELECT e.* FROM events e
657
- INNER JOIN memory_levels ml ON e.id = ml.event_id
658
- WHERE ml.level = ?
659
- ORDER BY e.timestamp DESC
660
- LIMIT ? OFFSET ?`,
661
- [level, limit, offset]
662
- );
663
- return rows.map((row) => this.rowToEvent(row));
664
- }
665
- /**
666
- * Get memory level for a specific event
667
- */
668
- async getEventLevel(eventId) {
669
- await this.initialize();
670
- const rows = await dbAll(
671
- this.db,
672
- `SELECT level FROM memory_levels WHERE event_id = ?`,
673
- [eventId]
674
- );
675
- return rows.length > 0 ? rows[0].level : null;
676
- }
677
- // ============================================================
678
- // Endless Mode Helper Methods
679
- // ============================================================
680
- /**
681
- * Get database instance for Endless Mode stores
682
- */
683
- getDatabase() {
684
- return this.db;
685
- }
686
- /**
687
- * Get config value for endless mode
688
- */
689
- async getEndlessConfig(key) {
690
- await this.initialize();
691
- const rows = await dbAll(
692
- this.db,
693
- `SELECT value FROM endless_config WHERE key = ?`,
694
- [key]
695
- );
696
- if (rows.length === 0)
697
- return null;
698
- return JSON.parse(rows[0].value);
699
- }
700
- /**
701
- * Set config value for endless mode
702
- */
703
- async setEndlessConfig(key, value) {
704
- await this.initialize();
705
- await dbRun(
706
- this.db,
707
- `INSERT OR REPLACE INTO endless_config (key, value, updated_at)
708
- VALUES (?, ?, CURRENT_TIMESTAMP)`,
709
- [key, JSON.stringify(value)]
710
- );
711
- }
712
- /**
713
- * Get all sessions
714
- */
715
- async getAllSessions() {
716
- await this.initialize();
717
- const rows = await dbAll(
718
- this.db,
719
- `SELECT * FROM sessions ORDER BY started_at DESC`
720
- );
721
- return rows.map((row) => ({
722
- id: row.id,
723
- startedAt: toDate(row.started_at),
724
- endedAt: row.ended_at ? toDate(row.ended_at) : void 0,
725
- projectPath: row.project_path,
726
- summary: row.summary,
727
- tags: row.tags ? JSON.parse(row.tags) : void 0
728
- }));
729
- }
730
- /**
731
- * Increment access count for events (stub for compatibility)
732
- */
733
- async incrementAccessCount(eventIds) {
734
- return Promise.resolve();
735
- }
736
- /**
737
- * Get most accessed memories (stub for compatibility)
738
- */
739
- async getMostAccessed(limit = 10) {
740
- return [];
741
- }
742
- /**
743
- * Close database connection
744
- */
745
- async close() {
746
- await dbClose(this.db);
29
+ // src/core/sqlite-event-store.ts
30
+ import { randomUUID } from "crypto";
31
+
32
+ // src/core/canonical-key.ts
33
+ import { createHash } from "crypto";
34
+ var MAX_KEY_LENGTH = 200;
35
+ function makeCanonicalKey(title, context) {
36
+ let normalized = title.normalize("NFKC");
37
+ normalized = normalized.toLowerCase();
38
+ normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, "");
39
+ normalized = normalized.replace(/\s+/g, " ").trim();
40
+ let key = normalized;
41
+ if (context?.project) {
42
+ key = `${context.project}::${key}`;
747
43
  }
748
- /**
749
- * Convert database row to MemoryEvent
750
- */
751
- rowToEvent(row) {
752
- return {
753
- id: row.id,
754
- eventType: row.event_type,
755
- sessionId: row.session_id,
756
- timestamp: toDate(row.timestamp),
757
- content: row.content,
758
- canonicalKey: row.canonical_key,
759
- dedupeKey: row.dedupe_key,
760
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0
761
- };
44
+ if (key.length > MAX_KEY_LENGTH) {
45
+ const hashSuffix = createHash("md5").update(key).digest("hex").slice(0, 8);
46
+ key = key.slice(0, MAX_KEY_LENGTH - 9) + "_" + hashSuffix;
762
47
  }
763
- };
764
-
765
- // src/core/sqlite-event-store.ts
766
- import { randomUUID as randomUUID2 } from "crypto";
48
+ return key;
49
+ }
50
+ function makeDedupeKey(content, sessionId) {
51
+ const contentHash = createHash("sha256").update(content).digest("hex");
52
+ return `${sessionId}:${contentHash}`;
53
+ }
767
54
 
768
55
  // src/core/sqlite-wrapper.ts
769
56
  import Database from "better-sqlite3";
@@ -1278,7 +565,7 @@ var SQLiteEventStore = class {
1278
565
  isDuplicate: true
1279
566
  };
1280
567
  }
1281
- const id = randomUUID2();
568
+ const id = randomUUID();
1282
569
  const timestamp = toSQLiteTimestamp(input.timestamp);
1283
570
  try {
1284
571
  const metadata = input.metadata || {};
@@ -1332,6 +619,29 @@ var SQLiteEventStore = class {
1332
619
  };
1333
620
  }
1334
621
  }
622
+ /**
623
+ * Get session IDs that have events but no session_summary event.
624
+ * Used to backfill summaries for sessions that ended without Stop hook.
625
+ */
626
+ async getSessionsWithoutSummary(currentSessionId, limit = 5) {
627
+ await this.initialize();
628
+ const rows = sqliteAll(
629
+ this.db,
630
+ `SELECT DISTINCT e.session_id
631
+ FROM events e
632
+ WHERE e.session_id != ?
633
+ AND e.event_type != 'session_summary'
634
+ AND e.session_id NOT IN (
635
+ SELECT DISTINCT session_id FROM events WHERE event_type = 'session_summary'
636
+ )
637
+ GROUP BY e.session_id
638
+ HAVING COUNT(*) >= 3
639
+ ORDER BY MAX(e.timestamp) DESC
640
+ LIMIT ?`,
641
+ [currentSessionId, limit]
642
+ );
643
+ return rows.map((r) => r.session_id);
644
+ }
1335
645
  /**
1336
646
  * Get events by session ID
1337
647
  */
@@ -1559,7 +869,7 @@ var SQLiteEventStore = class {
1559
869
  */
1560
870
  async enqueueForEmbedding(eventId, content) {
1561
871
  await this.initialize();
1562
- const id = randomUUID2();
872
+ const id = randomUUID();
1563
873
  sqliteRun(
1564
874
  this.db,
1565
875
  `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
@@ -1840,7 +1150,7 @@ var SQLiteEventStore = class {
1840
1150
  if (this.readOnly)
1841
1151
  return;
1842
1152
  await this.initialize();
1843
- const id = randomUUID2();
1153
+ const id = randomUUID();
1844
1154
  sqliteRun(
1845
1155
  this.db,
1846
1156
  `INSERT INTO memory_helpfulness (id, event_id, session_id, retrieval_score, query_preview, created_at)
@@ -1918,7 +1228,8 @@ var SQLiteEventStore = class {
1918
1228
  }
1919
1229
  }
1920
1230
  const retrievalScore = retrieval.retrieval_score || 0;
1921
- const helpfulnessScore = 0.3 * Math.min(retrievalScore, 1) + 0.25 * (sessionContinued ? 1 : 0) + 0.25 * toolSuccessRatio + 0.2 * (wasReasked ? 0 : 1);
1231
+ const promptNorm = Math.min(promptCountAfter / 2, 1);
1232
+ const helpfulnessScore = 0.4 * Math.min(retrievalScore, 1) + 0.3 * promptNorm + 0.2 * toolSuccessRatio + 0.1 * (sessionContinued ? 1 : 0);
1922
1233
  sqliteRun(
1923
1234
  this.db,
1924
1235
  `UPDATE memory_helpfulness
@@ -2061,7 +1372,7 @@ var SQLiteEventStore = class {
2061
1372
  }
2062
1373
  async recordRetrievalTrace(input) {
2063
1374
  await this.initialize();
2064
- const traceId = randomUUID2();
1375
+ const traceId = randomUUID();
2065
1376
  sqliteRun(
2066
1377
  this.db,
2067
1378
  `INSERT INTO retrieval_traces (
@@ -2315,169 +1626,6 @@ var SQLiteEventStore = class {
2315
1626
  }
2316
1627
  };
2317
1628
 
2318
- // src/core/sync-worker.ts
2319
- var DEFAULT_CONFIG = {
2320
- intervalMs: 3e4,
2321
- batchSize: 500,
2322
- maxRetries: 3,
2323
- retryDelayMs: 5e3
2324
- };
2325
- var SyncWorker = class {
2326
- constructor(sqliteStore, duckdbStore, config) {
2327
- this.sqliteStore = sqliteStore;
2328
- this.duckdbStore = duckdbStore;
2329
- this.config = { ...DEFAULT_CONFIG, ...config };
2330
- }
2331
- config;
2332
- intervalHandle = null;
2333
- running = false;
2334
- stats = {
2335
- lastSyncAt: null,
2336
- eventsSynced: 0,
2337
- sessionsSynced: 0,
2338
- errors: 0,
2339
- status: "idle"
2340
- };
2341
- /**
2342
- * Start the sync worker
2343
- */
2344
- start() {
2345
- if (this.running)
2346
- return;
2347
- this.running = true;
2348
- this.stats.status = "idle";
2349
- this.syncNow().catch((err) => {
2350
- console.error("[SyncWorker] Initial sync failed:", err);
2351
- });
2352
- this.intervalHandle = setInterval(() => {
2353
- this.syncNow().catch((err) => {
2354
- console.error("[SyncWorker] Periodic sync failed:", err);
2355
- });
2356
- }, this.config.intervalMs);
2357
- }
2358
- /**
2359
- * Stop the sync worker
2360
- */
2361
- stop() {
2362
- this.running = false;
2363
- this.stats.status = "stopped";
2364
- if (this.intervalHandle) {
2365
- clearInterval(this.intervalHandle);
2366
- this.intervalHandle = null;
2367
- }
2368
- }
2369
- /**
2370
- * Trigger immediate sync
2371
- */
2372
- async syncNow() {
2373
- if (this.stats.status === "syncing") {
2374
- return;
2375
- }
2376
- this.stats.status = "syncing";
2377
- try {
2378
- await this.syncEvents();
2379
- await this.syncSessions();
2380
- this.stats.lastSyncAt = /* @__PURE__ */ new Date();
2381
- this.stats.status = "idle";
2382
- } catch (error) {
2383
- this.stats.errors++;
2384
- this.stats.status = "error";
2385
- throw error;
2386
- }
2387
- }
2388
- /**
2389
- * Sync events from SQLite to DuckDB
2390
- */
2391
- async syncEvents() {
2392
- const targetName = "duckdb_analytics";
2393
- const position = await this.sqliteStore.getSyncPosition(targetName);
2394
- const lastTimestamp = position.lastTimestamp || "1970-01-01T00:00:00.000Z";
2395
- let hasMore = true;
2396
- let totalSynced = 0;
2397
- while (hasMore) {
2398
- const events = await this.sqliteStore.getEventsSince(lastTimestamp, this.config.batchSize);
2399
- if (events.length === 0) {
2400
- hasMore = false;
2401
- break;
2402
- }
2403
- await this.retryWithBackoff(async () => {
2404
- for (const event of events) {
2405
- await this.insertEventToDuckDB(event);
2406
- }
2407
- });
2408
- totalSynced += events.length;
2409
- const lastEvent = events[events.length - 1];
2410
- await this.sqliteStore.updateSyncPosition(
2411
- targetName,
2412
- lastEvent.id,
2413
- lastEvent.timestamp.toISOString()
2414
- );
2415
- hasMore = events.length === this.config.batchSize;
2416
- }
2417
- this.stats.eventsSynced += totalSynced;
2418
- }
2419
- /**
2420
- * Sync sessions from SQLite to DuckDB
2421
- */
2422
- async syncSessions() {
2423
- const sessions = await this.sqliteStore.getAllSessions();
2424
- for (const session of sessions) {
2425
- await this.retryWithBackoff(async () => {
2426
- await this.duckdbStore.upsertSession(session);
2427
- });
2428
- }
2429
- this.stats.sessionsSynced = sessions.length;
2430
- }
2431
- /**
2432
- * Insert a single event into DuckDB
2433
- */
2434
- async insertEventToDuckDB(event) {
2435
- await this.duckdbStore.append({
2436
- eventType: event.eventType,
2437
- sessionId: event.sessionId,
2438
- timestamp: event.timestamp,
2439
- content: event.content,
2440
- metadata: event.metadata
2441
- });
2442
- }
2443
- /**
2444
- * Retry operation with exponential backoff
2445
- */
2446
- async retryWithBackoff(fn) {
2447
- let lastError = null;
2448
- for (let attempt = 0; attempt < this.config.maxRetries; attempt++) {
2449
- try {
2450
- return await fn();
2451
- } catch (error) {
2452
- lastError = error instanceof Error ? error : new Error(String(error));
2453
- if (attempt < this.config.maxRetries - 1) {
2454
- const delay = this.config.retryDelayMs * Math.pow(2, attempt);
2455
- await this.sleep(delay);
2456
- }
2457
- }
2458
- }
2459
- throw lastError;
2460
- }
2461
- /**
2462
- * Sleep utility
2463
- */
2464
- sleep(ms) {
2465
- return new Promise((resolve5) => setTimeout(resolve5, ms));
2466
- }
2467
- /**
2468
- * Get sync statistics
2469
- */
2470
- getStats() {
2471
- return { ...this.stats };
2472
- }
2473
- /**
2474
- * Check if worker is running
2475
- */
2476
- isRunning() {
2477
- return this.running;
2478
- }
2479
- };
2480
-
2481
1629
  // src/core/vector-store.ts
2482
1630
  import * as lancedb from "@lancedb/lancedb";
2483
1631
  var VectorStore = class {
@@ -2765,8 +1913,34 @@ function getDefaultEmbedder() {
2765
1913
  return defaultEmbedder;
2766
1914
  }
2767
1915
 
1916
+ // src/core/db-wrapper.ts
1917
+ import BetterSqlite3 from "better-sqlite3";
1918
+ function toDate(value) {
1919
+ if (value instanceof Date)
1920
+ return value;
1921
+ if (typeof value === "string")
1922
+ return new Date(value);
1923
+ if (typeof value === "number")
1924
+ return new Date(value);
1925
+ return new Date(String(value));
1926
+ }
1927
+ function createDatabase(dbPath, options) {
1928
+ return new BetterSqlite3(dbPath, { readonly: options?.readOnly });
1929
+ }
1930
+ function dbRun(db, sql, params = []) {
1931
+ db.prepare(sql).run(...params);
1932
+ return Promise.resolve();
1933
+ }
1934
+ function dbAll(db, sql, params = []) {
1935
+ return Promise.resolve(db.prepare(sql).all(...params));
1936
+ }
1937
+ function dbClose(db) {
1938
+ db.close();
1939
+ return Promise.resolve();
1940
+ }
1941
+
2768
1942
  // src/core/vector-outbox.ts
2769
- var DEFAULT_CONFIG2 = {
1943
+ var DEFAULT_CONFIG = {
2770
1944
  embeddingVersion: "v1",
2771
1945
  maxRetries: 3,
2772
1946
  stuckThresholdMs: 5 * 60 * 1e3,
@@ -2775,7 +1949,7 @@ var DEFAULT_CONFIG2 = {
2775
1949
  };
2776
1950
 
2777
1951
  // src/core/vector-worker.ts
2778
- var DEFAULT_CONFIG3 = {
1952
+ var DEFAULT_CONFIG2 = {
2779
1953
  batchSize: 32,
2780
1954
  pollIntervalMs: 1e3,
2781
1955
  maxRetries: 3
@@ -2792,7 +1966,7 @@ var VectorWorker = class {
2792
1966
  this.eventStore = eventStore;
2793
1967
  this.vectorStore = vectorStore;
2794
1968
  this.embedder = embedder;
2795
- this.config = { ...DEFAULT_CONFIG3, ...config };
1969
+ this.config = { ...DEFAULT_CONFIG2, ...config };
2796
1970
  }
2797
1971
  /**
2798
1972
  * Start the worker polling loop
@@ -2913,7 +2087,7 @@ function createVectorWorker(eventStore, vectorStore, embedder, config) {
2913
2087
  }
2914
2088
 
2915
2089
  // src/core/matcher.ts
2916
- var DEFAULT_CONFIG4 = {
2090
+ var DEFAULT_CONFIG3 = {
2917
2091
  weights: {
2918
2092
  semanticSimilarity: 0.4,
2919
2093
  ftsScore: 0.25,
@@ -2928,9 +2102,9 @@ var Matcher = class {
2928
2102
  config;
2929
2103
  constructor(config = {}) {
2930
2104
  this.config = {
2931
- ...DEFAULT_CONFIG4,
2105
+ ...DEFAULT_CONFIG3,
2932
2106
  ...config,
2933
- weights: { ...DEFAULT_CONFIG4.weights, ...config.weights }
2107
+ weights: { ...DEFAULT_CONFIG3.weights, ...config.weights }
2934
2108
  };
2935
2109
  }
2936
2110
  /**
@@ -3920,7 +3094,7 @@ function createSharedEventStore(dbPath) {
3920
3094
  }
3921
3095
 
3922
3096
  // src/core/shared-store.ts
3923
- import { randomUUID as randomUUID3 } from "crypto";
3097
+ import { randomUUID as randomUUID2 } from "crypto";
3924
3098
  var SharedStore = class {
3925
3099
  constructor(sharedEventStore) {
3926
3100
  this.sharedEventStore = sharedEventStore;
@@ -3932,7 +3106,7 @@ var SharedStore = class {
3932
3106
  * Promote a verified troubleshooting entry to shared storage
3933
3107
  */
3934
3108
  async promoteEntry(input) {
3935
- const entryId = randomUUID3();
3109
+ const entryId = randomUUID2();
3936
3110
  await dbRun(
3937
3111
  this.db,
3938
3112
  `INSERT INTO shared_troubleshooting (
@@ -4297,7 +3471,7 @@ function createSharedVectorStore(dbPath) {
4297
3471
  }
4298
3472
 
4299
3473
  // src/core/shared-promoter.ts
4300
- import { randomUUID as randomUUID4 } from "crypto";
3474
+ import { randomUUID as randomUUID3 } from "crypto";
4301
3475
  var SharedPromoter = class {
4302
3476
  constructor(sharedStore, sharedVectorStore, embedder, config) {
4303
3477
  this.sharedStore = sharedStore;
@@ -4365,7 +3539,7 @@ var SharedPromoter = class {
4365
3539
  const embeddingContent = this.createEmbeddingContent(input);
4366
3540
  const embedding = await this.embedder.embed(embeddingContent);
4367
3541
  await this.sharedVectorStore.upsert({
4368
- id: randomUUID4(),
3542
+ id: randomUUID3(),
4369
3543
  entryId,
4370
3544
  entryType: "troubleshooting",
4371
3545
  content: embeddingContent,
@@ -4505,7 +3679,7 @@ function createToolObservationEmbedding(toolName, metadata, success) {
4505
3679
  }
4506
3680
 
4507
3681
  // src/core/working-set-store.ts
4508
- import { randomUUID as randomUUID5 } from "crypto";
3682
+ import { randomUUID as randomUUID4 } from "crypto";
4509
3683
  var WorkingSetStore = class {
4510
3684
  constructor(eventStore, config) {
4511
3685
  this.eventStore = eventStore;
@@ -4526,7 +3700,7 @@ var WorkingSetStore = class {
4526
3700
  `INSERT OR REPLACE INTO working_set (id, event_id, added_at, relevance_score, topics, expires_at)
4527
3701
  VALUES (?, ?, CURRENT_TIMESTAMP, ?, ?, ?)`,
4528
3702
  [
4529
- randomUUID5(),
3703
+ randomUUID4(),
4530
3704
  eventId,
4531
3705
  relevanceScore,
4532
3706
  JSON.stringify(topics || []),
@@ -4710,7 +3884,7 @@ function createWorkingSetStore(eventStore, config) {
4710
3884
  }
4711
3885
 
4712
3886
  // src/core/consolidated-store.ts
4713
- import { randomUUID as randomUUID6 } from "crypto";
3887
+ import { randomUUID as randomUUID5 } from "crypto";
4714
3888
  var ConsolidatedStore = class {
4715
3889
  constructor(eventStore) {
4716
3890
  this.eventStore = eventStore;
@@ -4722,7 +3896,7 @@ var ConsolidatedStore = class {
4722
3896
  * Create a new consolidated memory
4723
3897
  */
4724
3898
  async create(input) {
4725
- const memoryId = randomUUID6();
3899
+ const memoryId = randomUUID5();
4726
3900
  await dbRun(
4727
3901
  this.db,
4728
3902
  `INSERT INTO consolidated_memories
@@ -4852,7 +4026,7 @@ var ConsolidatedStore = class {
4852
4026
  * Create a long-term rule promoted from stable summaries
4853
4027
  */
4854
4028
  async createRule(input) {
4855
- const ruleId = randomUUID6();
4029
+ const ruleId = randomUUID5();
4856
4030
  await dbRun(
4857
4031
  this.db,
4858
4032
  `INSERT INTO consolidated_rules
@@ -5374,7 +4548,7 @@ function createConsolidationWorker(workingSetStore, consolidatedStore, config) {
5374
4548
  }
5375
4549
 
5376
4550
  // src/core/continuity-manager.ts
5377
- import { randomUUID as randomUUID7 } from "crypto";
4551
+ import { randomUUID as randomUUID6 } from "crypto";
5378
4552
  var ContinuityManager = class {
5379
4553
  constructor(eventStore, config) {
5380
4554
  this.eventStore = eventStore;
@@ -5528,7 +4702,7 @@ var ContinuityManager = class {
5528
4702
  `INSERT INTO continuity_log
5529
4703
  (log_id, from_context_id, to_context_id, continuity_score, transition_type, created_at)
5530
4704
  VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
5531
- [randomUUID7(), previous.id, current.id, score, type]
4705
+ [randomUUID6(), previous.id, current.id, score, type]
5532
4706
  );
5533
4707
  }
5534
4708
  /**
@@ -5637,7 +4811,7 @@ function createContinuityManager(eventStore, config) {
5637
4811
  }
5638
4812
 
5639
4813
  // src/core/graduation-worker.ts
5640
- var DEFAULT_CONFIG5 = {
4814
+ var DEFAULT_CONFIG4 = {
5641
4815
  evaluationIntervalMs: 3e5,
5642
4816
  // 5 minutes
5643
4817
  batchSize: 50,
@@ -5645,7 +4819,7 @@ var DEFAULT_CONFIG5 = {
5645
4819
  // 1 hour cooldown between evaluations
5646
4820
  };
5647
4821
  var GraduationWorker = class {
5648
- constructor(eventStore, graduation, config = DEFAULT_CONFIG5) {
4822
+ constructor(eventStore, graduation, config = DEFAULT_CONFIG4) {
5649
4823
  this.eventStore = eventStore;
5650
4824
  this.graduation = graduation;
5651
4825
  this.config = config;
@@ -5753,7 +4927,7 @@ function createGraduationWorker(eventStore, graduation, config) {
5753
4927
  return new GraduationWorker(
5754
4928
  eventStore,
5755
4929
  graduation,
5756
- { ...DEFAULT_CONFIG5, ...config }
4930
+ { ...DEFAULT_CONFIG4, ...config }
5757
4931
  );
5758
4932
  }
5759
4933
 
@@ -5987,9 +5161,6 @@ function registerSession(sessionId, projectPath) {
5987
5161
  var MemoryService = class {
5988
5162
  // Primary store: SQLite (WAL mode) - for hooks, always available
5989
5163
  sqliteStore;
5990
- // Analytics store: DuckDB - for server reads (optional, synced from SQLite)
5991
- analyticsStore;
5992
- syncWorker = null;
5993
5164
  vectorStore;
5994
5165
  embedder;
5995
5166
  matcher;
@@ -6038,24 +5209,6 @@ var MemoryService = class {
6038
5209
  markdownMirrorRoot: storagePath
6039
5210
  }
6040
5211
  );
6041
- const analyticsEnabled = config.analyticsEnabled ?? this.readOnly;
6042
- if (!analyticsEnabled) {
6043
- this.analyticsStore = null;
6044
- } else if (this.readOnly) {
6045
- try {
6046
- this.analyticsStore = new EventStore(
6047
- path3.join(storagePath, "analytics.duckdb"),
6048
- { readOnly: true }
6049
- );
6050
- } catch {
6051
- this.analyticsStore = null;
6052
- }
6053
- } else {
6054
- this.analyticsStore = new EventStore(
6055
- path3.join(storagePath, "analytics.duckdb"),
6056
- { readOnly: false }
6057
- );
6058
- }
6059
5212
  this.vectorStore = new VectorStore(path3.join(storagePath, "vectors"));
6060
5213
  const embeddingModel = config.embeddingModel || process.env.CLAUDE_MEMORY_EMBEDDING_MODEL;
6061
5214
  this.embedder = embeddingModel ? new Embedder(embeddingModel) : getDefaultEmbedder();
@@ -6081,13 +5234,6 @@ var MemoryService = class {
6081
5234
  this.initialized = true;
6082
5235
  return;
6083
5236
  }
6084
- if (this.analyticsStore) {
6085
- try {
6086
- await this.analyticsStore.initialize();
6087
- } catch (error) {
6088
- console.warn("[MemoryService] Analytics store (DuckDB) initialization failed, using SQLite for reads:", error);
6089
- }
6090
- }
6091
5237
  await this.vectorStore.initialize();
6092
5238
  await this.embedder.initialize();
6093
5239
  if (!this.readOnly) {
@@ -6104,14 +5250,6 @@ var MemoryService = class {
6104
5250
  this.graduation
6105
5251
  );
6106
5252
  this.graduationWorker.start();
6107
- if (this.analyticsStore) {
6108
- this.syncWorker = new SyncWorker(
6109
- this.sqliteStore,
6110
- this.analyticsStore,
6111
- { intervalMs: 3e4, batchSize: 500 }
6112
- );
6113
- this.syncWorker.start();
6114
- }
6115
5253
  }
6116
5254
  const savedMode = await this.sqliteStore.getEndlessConfig("mode");
6117
5255
  if (savedMode === "endless") {
@@ -6308,6 +5446,57 @@ var MemoryService = class {
6308
5446
  }
6309
5447
  );
6310
5448
  }
5449
+ /**
5450
+ * Backfill session summaries for recent sessions that are missing them.
5451
+ * Called from session-start hook to catch sessions that ended without Stop hook.
5452
+ */
5453
+ async backfillMissingSummaries(currentSessionId, limit = 5) {
5454
+ await this.initialize();
5455
+ const recentSessionIds = await this.sqliteStore.getSessionsWithoutSummary(currentSessionId, limit);
5456
+ for (const sid of recentSessionIds) {
5457
+ try {
5458
+ await this.generateSessionSummary(sid);
5459
+ } catch {
5460
+ }
5461
+ }
5462
+ }
5463
+ /**
5464
+ * Generate a rule-based session summary from stored events.
5465
+ * Called at session end (Stop hook) when no LLM-generated summary exists.
5466
+ * Skips if a summary already exists for this session.
5467
+ */
5468
+ async generateSessionSummary(sessionId) {
5469
+ await this.initialize();
5470
+ const events = await this.sqliteStore.getSessionEvents(sessionId);
5471
+ if (events.length < 3)
5472
+ return;
5473
+ const hasSummary = events.some((e) => e.eventType === "session_summary");
5474
+ if (hasSummary)
5475
+ return;
5476
+ const prompts = events.filter((e) => e.eventType === "user_prompt");
5477
+ const toolObs = events.filter((e) => e.eventType === "tool_observation");
5478
+ const toolNames = [...new Set(
5479
+ toolObs.map((e) => e.metadata?.toolName).filter(Boolean)
5480
+ )];
5481
+ const errorObs = toolObs.filter((e) => {
5482
+ const meta = e.metadata;
5483
+ return meta?.exitCode !== void 0 && meta.exitCode !== 0;
5484
+ });
5485
+ const datePart = events[0].timestamp.toISOString().split("T")[0];
5486
+ const parts = [`[${datePart}] ${prompts.length}\uD134 \uC138\uC158.`];
5487
+ if (prompts.length > 0) {
5488
+ const firstPrompt = prompts[0].content.slice(0, 120).replace(/\n/g, " ");
5489
+ parts.push(`\uC8FC\uC694 \uC791\uC5C5: ${firstPrompt}`);
5490
+ }
5491
+ if (toolNames.length > 0) {
5492
+ parts.push(`\uC0AC\uC6A9 \uD234: ${toolNames.slice(0, 6).join(", ")}`);
5493
+ }
5494
+ if (errorObs.length > 0) {
5495
+ parts.push(`\uC624\uB958 ${errorObs.length}\uAC74 \uBC1C\uC0DD`);
5496
+ }
5497
+ const summary = parts.join(". ");
5498
+ await this.storeSessionSummary(sessionId, summary, { generated: "rule-based", eventCount: events.length });
5499
+ }
6311
5500
  /**
6312
5501
  * Store a tool observation
6313
5502
  */
@@ -6843,6 +6032,7 @@ var MemoryService = class {
6843
6032
  await this.initialize();
6844
6033
  await this.sqliteStore.recordRetrievalTrace({
6845
6034
  ...input,
6035
+ projectHash: this.projectHash || void 0,
6846
6036
  candidateDetails: [],
6847
6037
  selectedDetails: [],
6848
6038
  fallbackTrace: []
@@ -7133,16 +6323,10 @@ var MemoryService = class {
7133
6323
  if (this.vectorWorker) {
7134
6324
  this.vectorWorker.stop();
7135
6325
  }
7136
- if (this.syncWorker) {
7137
- this.syncWorker.stop();
7138
- }
7139
6326
  if (this.sharedEventStore) {
7140
6327
  await this.sharedEventStore.close();
7141
6328
  }
7142
6329
  await this.sqliteStore.close();
7143
- if (this.analyticsStore) {
7144
- await this.analyticsStore.close();
7145
- }
7146
6330
  }
7147
6331
  /**
7148
6332
  * Expand ~ to home directory
@@ -7200,7 +6384,7 @@ import * as fs5 from "fs";
7200
6384
  import * as path4 from "path";
7201
6385
  import * as os2 from "os";
7202
6386
  import * as readline from "readline";
7203
- import { randomUUID as randomUUID9 } from "crypto";
6387
+ import { randomUUID as randomUUID8 } from "crypto";
7204
6388
  function isWorthStoringPrompt(content) {
7205
6389
  const trimmed = content.trim();
7206
6390
  if (trimmed.startsWith("/"))
@@ -7391,7 +6575,7 @@ var SessionHistoryImporter = class {
7391
6575
  result.skippedDuplicates++;
7392
6576
  continue;
7393
6577
  }
7394
- currentTurnId = randomUUID9();
6578
+ currentTurnId = randomUUID8();
7395
6579
  const appendResult = await this.memoryService.storeUserPrompt(
7396
6580
  sessionId,
7397
6581
  content,
@@ -8000,7 +7184,7 @@ import { Hono } from "hono";
8000
7184
  import * as path6 from "path";
8001
7185
  import * as os3 from "os";
8002
7186
  function getServiceFromQuery(c) {
8003
- const project = c.req.query("project");
7187
+ const project = c.req.query("project") || c.req.query("projectId");
8004
7188
  if (project) {
8005
7189
  const isHash = /^[a-f0-9]{8}$/.test(project);
8006
7190
  let storagePath;
@@ -9432,7 +8616,7 @@ if (isMainModule) {
9432
8616
  }
9433
8617
 
9434
8618
  // src/core/mongo-sync-worker.ts
9435
- import { randomUUID as randomUUID10 } from "crypto";
8619
+ import { randomUUID as randomUUID9 } from "crypto";
9436
8620
  import * as os5 from "os";
9437
8621
  import { MongoClient } from "mongodb";
9438
8622
  function redactMongoUri(uri) {
@@ -9466,7 +8650,7 @@ var MongoSyncWorker = class {
9466
8650
  direction: config.direction ?? "both",
9467
8651
  intervalMs: config.intervalMs ?? 3e4,
9468
8652
  batchSize: config.batchSize ?? 500,
9469
- instanceId: config.instanceId ?? randomUUID10()
8653
+ instanceId: config.instanceId ?? randomUUID9()
9470
8654
  };
9471
8655
  }
9472
8656
  config;
@@ -9778,7 +8962,7 @@ function getHooksConfig(pluginPath) {
9778
8962
  };
9779
8963
  }
9780
8964
  var program = new Command();
9781
- program.name("claude-memory-layer").description("Claude Code Memory Plugin CLI").version("1.0.24");
8965
+ program.name("claude-memory-layer").description("Claude Code Memory Plugin CLI").version("1.0.26");
9782
8966
  program.command("install").description("Install hooks into Claude Code settings").option("--path <path>", "Custom plugin path (defaults to auto-detect)").action(async (options) => {
9783
8967
  try {
9784
8968
  const pluginPath = options.path || getPluginPath();