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