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