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
@@ -11,744 +11,31 @@ import * as os from "os";
11
11
  import * as fs4 from "fs";
12
12
  import * as crypto2 from "crypto";
13
13
 
14
- // src/core/event-store.ts
15
- import { randomUUID } from "crypto";
16
-
17
- // src/core/canonical-key.ts
18
- import { createHash } from "crypto";
19
- var MAX_KEY_LENGTH = 200;
20
- function makeCanonicalKey(title, context) {
21
- let normalized = title.normalize("NFKC");
22
- normalized = normalized.toLowerCase();
23
- normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, "");
24
- normalized = normalized.replace(/\s+/g, " ").trim();
25
- let key = normalized;
26
- if (context?.project) {
27
- key = `${context.project}::${key}`;
28
- }
29
- if (key.length > MAX_KEY_LENGTH) {
30
- const hashSuffix = createHash("md5").update(key).digest("hex").slice(0, 8);
31
- key = key.slice(0, MAX_KEY_LENGTH - 9) + "_" + hashSuffix;
32
- }
33
- return key;
34
- }
35
- function makeDedupeKey(content, sessionId) {
36
- const contentHash = createHash("sha256").update(content).digest("hex");
37
- return `${sessionId}:${contentHash}`;
38
- }
39
-
40
- // src/core/db-wrapper.ts
41
- import duckdb from "duckdb";
42
- function convertBigInts(obj) {
43
- if (obj === null || obj === void 0)
44
- return obj;
45
- if (typeof obj === "bigint")
46
- return Number(obj);
47
- if (obj instanceof Date)
48
- return obj;
49
- if (Array.isArray(obj))
50
- return obj.map(convertBigInts);
51
- if (typeof obj === "object") {
52
- const result = {};
53
- for (const [key, value] of Object.entries(obj)) {
54
- result[key] = convertBigInts(value);
55
- }
56
- return result;
57
- }
58
- return obj;
59
- }
60
- function toDate(value) {
61
- if (value instanceof Date)
62
- return value;
63
- if (typeof value === "string")
64
- return new Date(value);
65
- if (typeof value === "number")
66
- return new Date(value);
67
- return new Date(String(value));
68
- }
69
- function createDatabase(path4, options) {
70
- if (options?.readOnly) {
71
- return new duckdb.Database(path4, { access_mode: "READ_ONLY" });
72
- }
73
- return new duckdb.Database(path4);
74
- }
75
- function dbRun(db, sql, params = []) {
76
- return new Promise((resolve2, reject) => {
77
- if (params.length === 0) {
78
- db.run(sql, (err) => {
79
- if (err)
80
- reject(err);
81
- else
82
- resolve2();
83
- });
84
- } else {
85
- db.run(sql, ...params, (err) => {
86
- if (err)
87
- reject(err);
88
- else
89
- resolve2();
90
- });
91
- }
92
- });
93
- }
94
- function dbAll(db, sql, params = []) {
95
- return new Promise((resolve2, reject) => {
96
- if (params.length === 0) {
97
- db.all(sql, (err, rows) => {
98
- if (err)
99
- reject(err);
100
- else
101
- resolve2(convertBigInts(rows || []));
102
- });
103
- } else {
104
- db.all(sql, ...params, (err, rows) => {
105
- if (err)
106
- reject(err);
107
- else
108
- resolve2(convertBigInts(rows || []));
109
- });
110
- }
111
- });
112
- }
113
- function dbClose(db) {
114
- return new Promise((resolve2, reject) => {
115
- db.close((err) => {
116
- if (err)
117
- reject(err);
118
- else
119
- resolve2();
120
- });
121
- });
122
- }
123
-
124
- // src/core/event-store.ts
125
- var EventStore = class {
126
- constructor(dbPath, options) {
127
- this.dbPath = dbPath;
128
- this.readOnly = options?.readOnly ?? false;
129
- this.db = createDatabase(dbPath, { readOnly: this.readOnly });
130
- }
131
- db;
132
- initialized = false;
133
- readOnly;
134
- /**
135
- * Initialize database schema
136
- */
137
- async initialize() {
138
- if (this.initialized)
139
- return;
140
- if (this.readOnly) {
141
- this.initialized = true;
142
- return;
143
- }
144
- await dbRun(this.db, `
145
- CREATE TABLE IF NOT EXISTS events (
146
- id VARCHAR PRIMARY KEY,
147
- event_type VARCHAR NOT NULL,
148
- session_id VARCHAR NOT NULL,
149
- timestamp TIMESTAMP NOT NULL,
150
- content TEXT NOT NULL,
151
- canonical_key VARCHAR NOT NULL,
152
- dedupe_key VARCHAR UNIQUE,
153
- metadata JSON
154
- )
155
- `);
156
- await dbRun(this.db, `
157
- CREATE TABLE IF NOT EXISTS event_dedup (
158
- dedupe_key VARCHAR PRIMARY KEY,
159
- event_id VARCHAR NOT NULL,
160
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
161
- )
162
- `);
163
- await dbRun(this.db, `
164
- CREATE TABLE IF NOT EXISTS sessions (
165
- id VARCHAR PRIMARY KEY,
166
- started_at TIMESTAMP NOT NULL,
167
- ended_at TIMESTAMP,
168
- project_path VARCHAR,
169
- summary TEXT,
170
- tags JSON
171
- )
172
- `);
173
- await dbRun(this.db, `
174
- CREATE TABLE IF NOT EXISTS insights (
175
- id VARCHAR PRIMARY KEY,
176
- insight_type VARCHAR NOT NULL,
177
- content TEXT NOT NULL,
178
- canonical_key VARCHAR NOT NULL,
179
- confidence FLOAT,
180
- source_events JSON,
181
- created_at TIMESTAMP,
182
- last_updated TIMESTAMP
183
- )
184
- `);
185
- await dbRun(this.db, `
186
- CREATE TABLE IF NOT EXISTS embedding_outbox (
187
- id VARCHAR PRIMARY KEY,
188
- event_id VARCHAR NOT NULL,
189
- content TEXT NOT NULL,
190
- status VARCHAR DEFAULT 'pending',
191
- retry_count INT DEFAULT 0,
192
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
193
- processed_at TIMESTAMP,
194
- error_message TEXT
195
- )
196
- `);
197
- await dbRun(this.db, `
198
- CREATE TABLE IF NOT EXISTS projection_offsets (
199
- projection_name VARCHAR PRIMARY KEY,
200
- last_event_id VARCHAR,
201
- last_timestamp TIMESTAMP,
202
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
203
- )
204
- `);
205
- await dbRun(this.db, `
206
- CREATE TABLE IF NOT EXISTS memory_levels (
207
- event_id VARCHAR PRIMARY KEY,
208
- level VARCHAR NOT NULL DEFAULT 'L0',
209
- promoted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
210
- )
211
- `);
212
- await dbRun(this.db, `
213
- CREATE TABLE IF NOT EXISTS entries (
214
- entry_id VARCHAR PRIMARY KEY,
215
- created_ts TIMESTAMP NOT NULL,
216
- entry_type VARCHAR NOT NULL,
217
- title VARCHAR NOT NULL,
218
- content_json JSON NOT NULL,
219
- stage VARCHAR NOT NULL DEFAULT 'raw',
220
- status VARCHAR DEFAULT 'active',
221
- superseded_by VARCHAR,
222
- build_id VARCHAR,
223
- evidence_json JSON,
224
- canonical_key VARCHAR,
225
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
226
- )
227
- `);
228
- await dbRun(this.db, `
229
- CREATE TABLE IF NOT EXISTS entities (
230
- entity_id VARCHAR PRIMARY KEY,
231
- entity_type VARCHAR NOT NULL,
232
- canonical_key VARCHAR NOT NULL,
233
- title VARCHAR NOT NULL,
234
- stage VARCHAR NOT NULL DEFAULT 'raw',
235
- status VARCHAR NOT NULL DEFAULT 'active',
236
- current_json JSON NOT NULL,
237
- title_norm VARCHAR,
238
- search_text VARCHAR,
239
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
240
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
241
- )
242
- `);
243
- await dbRun(this.db, `
244
- CREATE TABLE IF NOT EXISTS entity_aliases (
245
- entity_type VARCHAR NOT NULL,
246
- canonical_key VARCHAR NOT NULL,
247
- entity_id VARCHAR NOT NULL,
248
- is_primary BOOLEAN DEFAULT FALSE,
249
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
250
- PRIMARY KEY(entity_type, canonical_key)
251
- )
252
- `);
253
- await dbRun(this.db, `
254
- CREATE TABLE IF NOT EXISTS edges (
255
- edge_id VARCHAR PRIMARY KEY,
256
- src_type VARCHAR NOT NULL,
257
- src_id VARCHAR NOT NULL,
258
- rel_type VARCHAR NOT NULL,
259
- dst_type VARCHAR NOT NULL,
260
- dst_id VARCHAR NOT NULL,
261
- meta_json JSON,
262
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
263
- )
264
- `);
265
- await dbRun(this.db, `
266
- CREATE TABLE IF NOT EXISTS vector_outbox (
267
- job_id VARCHAR PRIMARY KEY,
268
- item_kind VARCHAR NOT NULL,
269
- item_id VARCHAR NOT NULL,
270
- embedding_version VARCHAR NOT NULL,
271
- status VARCHAR NOT NULL DEFAULT 'pending',
272
- retry_count INT DEFAULT 0,
273
- error VARCHAR,
274
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
275
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
276
- UNIQUE(item_kind, item_id, embedding_version)
277
- )
278
- `);
279
- await dbRun(this.db, `
280
- CREATE TABLE IF NOT EXISTS build_runs (
281
- build_id VARCHAR PRIMARY KEY,
282
- started_at TIMESTAMP NOT NULL,
283
- finished_at TIMESTAMP,
284
- extractor_model VARCHAR NOT NULL,
285
- extractor_prompt_hash VARCHAR NOT NULL,
286
- embedder_model VARCHAR NOT NULL,
287
- embedding_version VARCHAR NOT NULL,
288
- idris_version VARCHAR NOT NULL,
289
- schema_version VARCHAR NOT NULL,
290
- status VARCHAR NOT NULL DEFAULT 'running',
291
- error VARCHAR
292
- )
293
- `);
294
- await dbRun(this.db, `
295
- CREATE TABLE IF NOT EXISTS pipeline_metrics (
296
- id VARCHAR PRIMARY KEY,
297
- ts TIMESTAMP NOT NULL,
298
- stage VARCHAR NOT NULL,
299
- latency_ms DOUBLE NOT NULL,
300
- success BOOLEAN NOT NULL,
301
- error VARCHAR,
302
- session_id VARCHAR
303
- )
304
- `);
305
- await dbRun(this.db, `
306
- CREATE TABLE IF NOT EXISTS working_set (
307
- id VARCHAR PRIMARY KEY,
308
- event_id VARCHAR NOT NULL,
309
- added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
310
- relevance_score FLOAT DEFAULT 1.0,
311
- topics JSON,
312
- expires_at TIMESTAMP
313
- )
314
- `);
315
- await dbRun(this.db, `
316
- CREATE TABLE IF NOT EXISTS consolidated_memories (
317
- memory_id VARCHAR PRIMARY KEY,
318
- summary TEXT NOT NULL,
319
- topics JSON,
320
- source_events JSON,
321
- confidence FLOAT DEFAULT 0.5,
322
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
323
- accessed_at TIMESTAMP,
324
- access_count INTEGER DEFAULT 0
325
- )
326
- `);
327
- await dbRun(this.db, `
328
- CREATE TABLE IF NOT EXISTS continuity_log (
329
- log_id VARCHAR PRIMARY KEY,
330
- from_context_id VARCHAR,
331
- to_context_id VARCHAR,
332
- continuity_score FLOAT,
333
- transition_type VARCHAR,
334
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
335
- )
336
- `);
337
- await dbRun(this.db, `
338
- CREATE TABLE IF NOT EXISTS consolidated_rules (
339
- rule_id VARCHAR PRIMARY KEY,
340
- rule TEXT NOT NULL,
341
- topics JSON,
342
- source_memory_ids JSON,
343
- source_events JSON,
344
- confidence FLOAT DEFAULT 0.5,
345
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
346
- )
347
- `);
348
- await dbRun(this.db, `
349
- CREATE TABLE IF NOT EXISTS endless_config (
350
- key VARCHAR PRIMARY KEY,
351
- value JSON,
352
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
353
- )
354
- `);
355
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_type ON entries(entry_type)`);
356
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_stage ON entries(stage)`);
357
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_canonical ON entries(canonical_key)`);
358
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entities_type_key ON entities(entity_type, canonical_key)`);
359
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entities_status ON entities(status)`);
360
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src_id, rel_type)`);
361
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_dst ON edges(dst_id, rel_type)`);
362
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_rel ON edges(rel_type)`);
363
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_outbox_status ON vector_outbox(status)`);
364
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_expires ON working_set(expires_at)`);
365
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_relevance ON working_set(relevance_score DESC)`);
366
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence DESC)`);
367
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_rules_confidence ON consolidated_rules(confidence DESC)`);
368
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at)`);
369
- this.initialized = true;
370
- }
371
- /**
372
- * Append event to store (AXIOMMIND Principle 2: Append-only)
373
- * Returns existing event ID if duplicate (Principle 3: Idempotency)
374
- */
375
- async append(input) {
376
- await this.initialize();
377
- const canonicalKey = makeCanonicalKey(input.content);
378
- const dedupeKey = makeDedupeKey(input.content, input.sessionId);
379
- const existing = await dbAll(
380
- this.db,
381
- `SELECT event_id FROM event_dedup WHERE dedupe_key = ?`,
382
- [dedupeKey]
383
- );
384
- if (existing.length > 0) {
385
- return {
386
- success: true,
387
- eventId: existing[0].event_id,
388
- isDuplicate: true
389
- };
390
- }
391
- const id = randomUUID();
392
- const timestamp = input.timestamp.toISOString();
393
- try {
394
- await dbRun(
395
- this.db,
396
- `INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
397
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
398
- [
399
- id,
400
- input.eventType,
401
- input.sessionId,
402
- timestamp,
403
- input.content,
404
- canonicalKey,
405
- dedupeKey,
406
- JSON.stringify(input.metadata || {})
407
- ]
408
- );
409
- await dbRun(
410
- this.db,
411
- `INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)`,
412
- [dedupeKey, id]
413
- );
414
- await dbRun(
415
- this.db,
416
- `INSERT INTO memory_levels (event_id, level) VALUES (?, 'L0')`,
417
- [id]
418
- );
419
- return { success: true, eventId: id, isDuplicate: false };
420
- } catch (error) {
421
- return {
422
- success: false,
423
- error: error instanceof Error ? error.message : String(error)
424
- };
425
- }
426
- }
427
- /**
428
- * Get events by session ID
429
- */
430
- async getSessionEvents(sessionId) {
431
- await this.initialize();
432
- const rows = await dbAll(
433
- this.db,
434
- `SELECT * FROM events WHERE session_id = ? ORDER BY timestamp ASC`,
435
- [sessionId]
436
- );
437
- return rows.map(this.rowToEvent);
438
- }
439
- /**
440
- * Get recent events
441
- */
442
- async getRecentEvents(limit = 100) {
443
- await this.initialize();
444
- const rows = await dbAll(
445
- this.db,
446
- `SELECT * FROM events ORDER BY timestamp DESC LIMIT ?`,
447
- [limit]
448
- );
449
- return rows.map(this.rowToEvent);
450
- }
451
- /**
452
- * Get event by ID
453
- */
454
- async getEvent(id) {
455
- await this.initialize();
456
- const rows = await dbAll(
457
- this.db,
458
- `SELECT * FROM events WHERE id = ?`,
459
- [id]
460
- );
461
- if (rows.length === 0)
462
- return null;
463
- return this.rowToEvent(rows[0]);
464
- }
465
- /**
466
- * Create or update session
467
- */
468
- async upsertSession(session) {
469
- await this.initialize();
470
- const existing = await dbAll(
471
- this.db,
472
- `SELECT id FROM sessions WHERE id = ?`,
473
- [session.id]
474
- );
475
- if (existing.length === 0) {
476
- await dbRun(
477
- this.db,
478
- `INSERT INTO sessions (id, started_at, project_path, tags)
479
- VALUES (?, ?, ?, ?)`,
480
- [
481
- session.id,
482
- (session.startedAt || /* @__PURE__ */ new Date()).toISOString(),
483
- session.projectPath || null,
484
- JSON.stringify(session.tags || [])
485
- ]
486
- );
487
- } else {
488
- const updates = [];
489
- const values = [];
490
- if (session.endedAt) {
491
- updates.push("ended_at = ?");
492
- values.push(session.endedAt.toISOString());
493
- }
494
- if (session.summary) {
495
- updates.push("summary = ?");
496
- values.push(session.summary);
497
- }
498
- if (session.tags) {
499
- updates.push("tags = ?");
500
- values.push(JSON.stringify(session.tags));
501
- }
502
- if (updates.length > 0) {
503
- values.push(session.id);
504
- await dbRun(
505
- this.db,
506
- `UPDATE sessions SET ${updates.join(", ")} WHERE id = ?`,
507
- values
508
- );
509
- }
510
- }
511
- }
512
- /**
513
- * Get session by ID
514
- */
515
- async getSession(id) {
516
- await this.initialize();
517
- const rows = await dbAll(
518
- this.db,
519
- `SELECT * FROM sessions WHERE id = ?`,
520
- [id]
521
- );
522
- if (rows.length === 0)
523
- return null;
524
- const row = rows[0];
525
- return {
526
- id: row.id,
527
- startedAt: toDate(row.started_at),
528
- endedAt: row.ended_at ? toDate(row.ended_at) : void 0,
529
- projectPath: row.project_path,
530
- summary: row.summary,
531
- tags: row.tags ? JSON.parse(row.tags) : void 0
532
- };
533
- }
534
- /**
535
- * Add to embedding outbox (Single-Writer Pattern)
536
- */
537
- async enqueueForEmbedding(eventId, content) {
538
- await this.initialize();
539
- const id = randomUUID();
540
- await dbRun(
541
- this.db,
542
- `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
543
- VALUES (?, ?, ?, 'pending', 0)`,
544
- [id, eventId, content]
545
- );
546
- return id;
547
- }
548
- /**
549
- * Get pending outbox items
550
- */
551
- async getPendingOutboxItems(limit = 32) {
552
- await this.initialize();
553
- const pending = await dbAll(
554
- this.db,
555
- `SELECT * FROM embedding_outbox
556
- WHERE status = 'pending'
557
- ORDER BY created_at
558
- LIMIT ?`,
559
- [limit]
560
- );
561
- if (pending.length === 0)
562
- return [];
563
- const ids = pending.map((r) => r.id);
564
- const placeholders = ids.map(() => "?").join(",");
565
- await dbRun(
566
- this.db,
567
- `UPDATE embedding_outbox SET status = 'processing' WHERE id IN (${placeholders})`,
568
- ids
569
- );
570
- return pending.map((row) => ({
571
- id: row.id,
572
- eventId: row.event_id,
573
- content: row.content,
574
- status: "processing",
575
- retryCount: row.retry_count,
576
- createdAt: toDate(row.created_at),
577
- errorMessage: row.error_message
578
- }));
579
- }
580
- /**
581
- * Mark outbox items as done
582
- */
583
- async completeOutboxItems(ids) {
584
- if (ids.length === 0)
585
- return;
586
- const placeholders = ids.map(() => "?").join(",");
587
- await dbRun(
588
- this.db,
589
- `DELETE FROM embedding_outbox WHERE id IN (${placeholders})`,
590
- ids
591
- );
592
- }
593
- /**
594
- * Mark outbox items as failed
595
- */
596
- async failOutboxItems(ids, error) {
597
- if (ids.length === 0)
598
- return;
599
- const placeholders = ids.map(() => "?").join(",");
600
- await dbRun(
601
- this.db,
602
- `UPDATE embedding_outbox
603
- SET status = CASE WHEN retry_count >= 3 THEN 'failed' ELSE 'pending' END,
604
- retry_count = retry_count + 1,
605
- error_message = ?
606
- WHERE id IN (${placeholders})`,
607
- [error, ...ids]
608
- );
609
- }
610
- /**
611
- * Update memory level
612
- */
613
- async updateMemoryLevel(eventId, level) {
614
- await this.initialize();
615
- await dbRun(
616
- this.db,
617
- `UPDATE memory_levels SET level = ?, promoted_at = CURRENT_TIMESTAMP WHERE event_id = ?`,
618
- [level, eventId]
619
- );
620
- }
621
- /**
622
- * Get memory level statistics
623
- */
624
- async getLevelStats() {
625
- await this.initialize();
626
- const rows = await dbAll(
627
- this.db,
628
- `SELECT level, COUNT(*) as count FROM memory_levels GROUP BY level`
629
- );
630
- return rows;
631
- }
632
- /**
633
- * Get events by memory level
634
- */
635
- async getEventsByLevel(level, options) {
636
- await this.initialize();
637
- const limit = options?.limit || 50;
638
- const offset = options?.offset || 0;
639
- const rows = await dbAll(
640
- this.db,
641
- `SELECT e.* FROM events e
642
- INNER JOIN memory_levels ml ON e.id = ml.event_id
643
- WHERE ml.level = ?
644
- ORDER BY e.timestamp DESC
645
- LIMIT ? OFFSET ?`,
646
- [level, limit, offset]
647
- );
648
- return rows.map((row) => this.rowToEvent(row));
649
- }
650
- /**
651
- * Get memory level for a specific event
652
- */
653
- async getEventLevel(eventId) {
654
- await this.initialize();
655
- const rows = await dbAll(
656
- this.db,
657
- `SELECT level FROM memory_levels WHERE event_id = ?`,
658
- [eventId]
659
- );
660
- return rows.length > 0 ? rows[0].level : null;
661
- }
662
- // ============================================================
663
- // Endless Mode Helper Methods
664
- // ============================================================
665
- /**
666
- * Get database instance for Endless Mode stores
667
- */
668
- getDatabase() {
669
- return this.db;
670
- }
671
- /**
672
- * Get config value for endless mode
673
- */
674
- async getEndlessConfig(key) {
675
- await this.initialize();
676
- const rows = await dbAll(
677
- this.db,
678
- `SELECT value FROM endless_config WHERE key = ?`,
679
- [key]
680
- );
681
- if (rows.length === 0)
682
- return null;
683
- return JSON.parse(rows[0].value);
684
- }
685
- /**
686
- * Set config value for endless mode
687
- */
688
- async setEndlessConfig(key, value) {
689
- await this.initialize();
690
- await dbRun(
691
- this.db,
692
- `INSERT OR REPLACE INTO endless_config (key, value, updated_at)
693
- VALUES (?, ?, CURRENT_TIMESTAMP)`,
694
- [key, JSON.stringify(value)]
695
- );
696
- }
697
- /**
698
- * Get all sessions
699
- */
700
- async getAllSessions() {
701
- await this.initialize();
702
- const rows = await dbAll(
703
- this.db,
704
- `SELECT * FROM sessions ORDER BY started_at DESC`
705
- );
706
- return rows.map((row) => ({
707
- id: row.id,
708
- startedAt: toDate(row.started_at),
709
- endedAt: row.ended_at ? toDate(row.ended_at) : void 0,
710
- projectPath: row.project_path,
711
- summary: row.summary,
712
- tags: row.tags ? JSON.parse(row.tags) : void 0
713
- }));
714
- }
715
- /**
716
- * Increment access count for events (stub for compatibility)
717
- */
718
- async incrementAccessCount(eventIds) {
719
- return Promise.resolve();
720
- }
721
- /**
722
- * Get most accessed memories (stub for compatibility)
723
- */
724
- async getMostAccessed(limit = 10) {
725
- return [];
726
- }
727
- /**
728
- * Close database connection
729
- */
730
- async close() {
731
- await dbClose(this.db);
14
+ // src/core/sqlite-event-store.ts
15
+ import { randomUUID } from "crypto";
16
+
17
+ // src/core/canonical-key.ts
18
+ import { createHash } from "crypto";
19
+ var MAX_KEY_LENGTH = 200;
20
+ function makeCanonicalKey(title, context) {
21
+ let normalized = title.normalize("NFKC");
22
+ normalized = normalized.toLowerCase();
23
+ normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, "");
24
+ normalized = normalized.replace(/\s+/g, " ").trim();
25
+ let key = normalized;
26
+ if (context?.project) {
27
+ key = `${context.project}::${key}`;
732
28
  }
733
- /**
734
- * Convert database row to MemoryEvent
735
- */
736
- rowToEvent(row) {
737
- return {
738
- id: row.id,
739
- eventType: row.event_type,
740
- sessionId: row.session_id,
741
- timestamp: toDate(row.timestamp),
742
- content: row.content,
743
- canonicalKey: row.canonical_key,
744
- dedupeKey: row.dedupe_key,
745
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0
746
- };
29
+ if (key.length > MAX_KEY_LENGTH) {
30
+ const hashSuffix = createHash("md5").update(key).digest("hex").slice(0, 8);
31
+ key = key.slice(0, MAX_KEY_LENGTH - 9) + "_" + hashSuffix;
747
32
  }
748
- };
749
-
750
- // src/core/sqlite-event-store.ts
751
- import { randomUUID as randomUUID2 } from "crypto";
33
+ return key;
34
+ }
35
+ function makeDedupeKey(content, sessionId) {
36
+ const contentHash = createHash("sha256").update(content).digest("hex");
37
+ return `${sessionId}:${contentHash}`;
38
+ }
752
39
 
753
40
  // src/core/sqlite-wrapper.ts
754
41
  import Database from "better-sqlite3";
@@ -1263,7 +550,7 @@ var SQLiteEventStore = class {
1263
550
  isDuplicate: true
1264
551
  };
1265
552
  }
1266
- const id = randomUUID2();
553
+ const id = randomUUID();
1267
554
  const timestamp = toSQLiteTimestamp(input.timestamp);
1268
555
  try {
1269
556
  const metadata = input.metadata || {};
@@ -1317,6 +604,29 @@ var SQLiteEventStore = class {
1317
604
  };
1318
605
  }
1319
606
  }
607
+ /**
608
+ * Get session IDs that have events but no session_summary event.
609
+ * Used to backfill summaries for sessions that ended without Stop hook.
610
+ */
611
+ async getSessionsWithoutSummary(currentSessionId, limit = 5) {
612
+ await this.initialize();
613
+ const rows = sqliteAll(
614
+ this.db,
615
+ `SELECT DISTINCT e.session_id
616
+ FROM events e
617
+ WHERE e.session_id != ?
618
+ AND e.event_type != 'session_summary'
619
+ AND e.session_id NOT IN (
620
+ SELECT DISTINCT session_id FROM events WHERE event_type = 'session_summary'
621
+ )
622
+ GROUP BY e.session_id
623
+ HAVING COUNT(*) >= 3
624
+ ORDER BY MAX(e.timestamp) DESC
625
+ LIMIT ?`,
626
+ [currentSessionId, limit]
627
+ );
628
+ return rows.map((r) => r.session_id);
629
+ }
1320
630
  /**
1321
631
  * Get events by session ID
1322
632
  */
@@ -1544,7 +854,7 @@ var SQLiteEventStore = class {
1544
854
  */
1545
855
  async enqueueForEmbedding(eventId, content) {
1546
856
  await this.initialize();
1547
- const id = randomUUID2();
857
+ const id = randomUUID();
1548
858
  sqliteRun(
1549
859
  this.db,
1550
860
  `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
@@ -1825,7 +1135,7 @@ var SQLiteEventStore = class {
1825
1135
  if (this.readOnly)
1826
1136
  return;
1827
1137
  await this.initialize();
1828
- const id = randomUUID2();
1138
+ const id = randomUUID();
1829
1139
  sqliteRun(
1830
1140
  this.db,
1831
1141
  `INSERT INTO memory_helpfulness (id, event_id, session_id, retrieval_score, query_preview, created_at)
@@ -1903,7 +1213,8 @@ var SQLiteEventStore = class {
1903
1213
  }
1904
1214
  }
1905
1215
  const retrievalScore = retrieval.retrieval_score || 0;
1906
- const helpfulnessScore = 0.3 * Math.min(retrievalScore, 1) + 0.25 * (sessionContinued ? 1 : 0) + 0.25 * toolSuccessRatio + 0.2 * (wasReasked ? 0 : 1);
1216
+ const promptNorm = Math.min(promptCountAfter / 2, 1);
1217
+ const helpfulnessScore = 0.4 * Math.min(retrievalScore, 1) + 0.3 * promptNorm + 0.2 * toolSuccessRatio + 0.1 * (sessionContinued ? 1 : 0);
1907
1218
  sqliteRun(
1908
1219
  this.db,
1909
1220
  `UPDATE memory_helpfulness
@@ -2046,7 +1357,7 @@ var SQLiteEventStore = class {
2046
1357
  }
2047
1358
  async recordRetrievalTrace(input) {
2048
1359
  await this.initialize();
2049
- const traceId = randomUUID2();
1360
+ const traceId = randomUUID();
2050
1361
  sqliteRun(
2051
1362
  this.db,
2052
1363
  `INSERT INTO retrieval_traces (
@@ -2300,169 +1611,6 @@ var SQLiteEventStore = class {
2300
1611
  }
2301
1612
  };
2302
1613
 
2303
- // src/core/sync-worker.ts
2304
- var DEFAULT_CONFIG = {
2305
- intervalMs: 3e4,
2306
- batchSize: 500,
2307
- maxRetries: 3,
2308
- retryDelayMs: 5e3
2309
- };
2310
- var SyncWorker = class {
2311
- constructor(sqliteStore, duckdbStore, config) {
2312
- this.sqliteStore = sqliteStore;
2313
- this.duckdbStore = duckdbStore;
2314
- this.config = { ...DEFAULT_CONFIG, ...config };
2315
- }
2316
- config;
2317
- intervalHandle = null;
2318
- running = false;
2319
- stats = {
2320
- lastSyncAt: null,
2321
- eventsSynced: 0,
2322
- sessionsSynced: 0,
2323
- errors: 0,
2324
- status: "idle"
2325
- };
2326
- /**
2327
- * Start the sync worker
2328
- */
2329
- start() {
2330
- if (this.running)
2331
- return;
2332
- this.running = true;
2333
- this.stats.status = "idle";
2334
- this.syncNow().catch((err) => {
2335
- console.error("[SyncWorker] Initial sync failed:", err);
2336
- });
2337
- this.intervalHandle = setInterval(() => {
2338
- this.syncNow().catch((err) => {
2339
- console.error("[SyncWorker] Periodic sync failed:", err);
2340
- });
2341
- }, this.config.intervalMs);
2342
- }
2343
- /**
2344
- * Stop the sync worker
2345
- */
2346
- stop() {
2347
- this.running = false;
2348
- this.stats.status = "stopped";
2349
- if (this.intervalHandle) {
2350
- clearInterval(this.intervalHandle);
2351
- this.intervalHandle = null;
2352
- }
2353
- }
2354
- /**
2355
- * Trigger immediate sync
2356
- */
2357
- async syncNow() {
2358
- if (this.stats.status === "syncing") {
2359
- return;
2360
- }
2361
- this.stats.status = "syncing";
2362
- try {
2363
- await this.syncEvents();
2364
- await this.syncSessions();
2365
- this.stats.lastSyncAt = /* @__PURE__ */ new Date();
2366
- this.stats.status = "idle";
2367
- } catch (error) {
2368
- this.stats.errors++;
2369
- this.stats.status = "error";
2370
- throw error;
2371
- }
2372
- }
2373
- /**
2374
- * Sync events from SQLite to DuckDB
2375
- */
2376
- async syncEvents() {
2377
- const targetName = "duckdb_analytics";
2378
- const position = await this.sqliteStore.getSyncPosition(targetName);
2379
- const lastTimestamp = position.lastTimestamp || "1970-01-01T00:00:00.000Z";
2380
- let hasMore = true;
2381
- let totalSynced = 0;
2382
- while (hasMore) {
2383
- const events = await this.sqliteStore.getEventsSince(lastTimestamp, this.config.batchSize);
2384
- if (events.length === 0) {
2385
- hasMore = false;
2386
- break;
2387
- }
2388
- await this.retryWithBackoff(async () => {
2389
- for (const event of events) {
2390
- await this.insertEventToDuckDB(event);
2391
- }
2392
- });
2393
- totalSynced += events.length;
2394
- const lastEvent = events[events.length - 1];
2395
- await this.sqliteStore.updateSyncPosition(
2396
- targetName,
2397
- lastEvent.id,
2398
- lastEvent.timestamp.toISOString()
2399
- );
2400
- hasMore = events.length === this.config.batchSize;
2401
- }
2402
- this.stats.eventsSynced += totalSynced;
2403
- }
2404
- /**
2405
- * Sync sessions from SQLite to DuckDB
2406
- */
2407
- async syncSessions() {
2408
- const sessions = await this.sqliteStore.getAllSessions();
2409
- for (const session of sessions) {
2410
- await this.retryWithBackoff(async () => {
2411
- await this.duckdbStore.upsertSession(session);
2412
- });
2413
- }
2414
- this.stats.sessionsSynced = sessions.length;
2415
- }
2416
- /**
2417
- * Insert a single event into DuckDB
2418
- */
2419
- async insertEventToDuckDB(event) {
2420
- await this.duckdbStore.append({
2421
- eventType: event.eventType,
2422
- sessionId: event.sessionId,
2423
- timestamp: event.timestamp,
2424
- content: event.content,
2425
- metadata: event.metadata
2426
- });
2427
- }
2428
- /**
2429
- * Retry operation with exponential backoff
2430
- */
2431
- async retryWithBackoff(fn) {
2432
- let lastError = null;
2433
- for (let attempt = 0; attempt < this.config.maxRetries; attempt++) {
2434
- try {
2435
- return await fn();
2436
- } catch (error) {
2437
- lastError = error instanceof Error ? error : new Error(String(error));
2438
- if (attempt < this.config.maxRetries - 1) {
2439
- const delay = this.config.retryDelayMs * Math.pow(2, attempt);
2440
- await this.sleep(delay);
2441
- }
2442
- }
2443
- }
2444
- throw lastError;
2445
- }
2446
- /**
2447
- * Sleep utility
2448
- */
2449
- sleep(ms) {
2450
- return new Promise((resolve2) => setTimeout(resolve2, ms));
2451
- }
2452
- /**
2453
- * Get sync statistics
2454
- */
2455
- getStats() {
2456
- return { ...this.stats };
2457
- }
2458
- /**
2459
- * Check if worker is running
2460
- */
2461
- isRunning() {
2462
- return this.running;
2463
- }
2464
- };
2465
-
2466
1614
  // src/core/vector-store.ts
2467
1615
  import * as lancedb from "@lancedb/lancedb";
2468
1616
  var VectorStore = class {
@@ -2750,8 +1898,34 @@ function getDefaultEmbedder() {
2750
1898
  return defaultEmbedder;
2751
1899
  }
2752
1900
 
1901
+ // src/core/db-wrapper.ts
1902
+ import BetterSqlite3 from "better-sqlite3";
1903
+ function toDate(value) {
1904
+ if (value instanceof Date)
1905
+ return value;
1906
+ if (typeof value === "string")
1907
+ return new Date(value);
1908
+ if (typeof value === "number")
1909
+ return new Date(value);
1910
+ return new Date(String(value));
1911
+ }
1912
+ function createDatabase(dbPath, options) {
1913
+ return new BetterSqlite3(dbPath, { readonly: options?.readOnly });
1914
+ }
1915
+ function dbRun(db, sql, params = []) {
1916
+ db.prepare(sql).run(...params);
1917
+ return Promise.resolve();
1918
+ }
1919
+ function dbAll(db, sql, params = []) {
1920
+ return Promise.resolve(db.prepare(sql).all(...params));
1921
+ }
1922
+ function dbClose(db) {
1923
+ db.close();
1924
+ return Promise.resolve();
1925
+ }
1926
+
2753
1927
  // src/core/vector-outbox.ts
2754
- var DEFAULT_CONFIG2 = {
1928
+ var DEFAULT_CONFIG = {
2755
1929
  embeddingVersion: "v1",
2756
1930
  maxRetries: 3,
2757
1931
  stuckThresholdMs: 5 * 60 * 1e3,
@@ -2760,7 +1934,7 @@ var DEFAULT_CONFIG2 = {
2760
1934
  };
2761
1935
 
2762
1936
  // src/core/vector-worker.ts
2763
- var DEFAULT_CONFIG3 = {
1937
+ var DEFAULT_CONFIG2 = {
2764
1938
  batchSize: 32,
2765
1939
  pollIntervalMs: 1e3,
2766
1940
  maxRetries: 3
@@ -2777,7 +1951,7 @@ var VectorWorker = class {
2777
1951
  this.eventStore = eventStore;
2778
1952
  this.vectorStore = vectorStore;
2779
1953
  this.embedder = embedder;
2780
- this.config = { ...DEFAULT_CONFIG3, ...config };
1954
+ this.config = { ...DEFAULT_CONFIG2, ...config };
2781
1955
  }
2782
1956
  /**
2783
1957
  * Start the worker polling loop
@@ -2898,7 +2072,7 @@ function createVectorWorker(eventStore, vectorStore, embedder, config) {
2898
2072
  }
2899
2073
 
2900
2074
  // src/core/matcher.ts
2901
- var DEFAULT_CONFIG4 = {
2075
+ var DEFAULT_CONFIG3 = {
2902
2076
  weights: {
2903
2077
  semanticSimilarity: 0.4,
2904
2078
  ftsScore: 0.25,
@@ -2913,9 +2087,9 @@ var Matcher = class {
2913
2087
  config;
2914
2088
  constructor(config = {}) {
2915
2089
  this.config = {
2916
- ...DEFAULT_CONFIG4,
2090
+ ...DEFAULT_CONFIG3,
2917
2091
  ...config,
2918
- weights: { ...DEFAULT_CONFIG4.weights, ...config.weights }
2092
+ weights: { ...DEFAULT_CONFIG3.weights, ...config.weights }
2919
2093
  };
2920
2094
  }
2921
2095
  /**
@@ -3905,7 +3079,7 @@ function createSharedEventStore(dbPath) {
3905
3079
  }
3906
3080
 
3907
3081
  // src/core/shared-store.ts
3908
- import { randomUUID as randomUUID3 } from "crypto";
3082
+ import { randomUUID as randomUUID2 } from "crypto";
3909
3083
  var SharedStore = class {
3910
3084
  constructor(sharedEventStore) {
3911
3085
  this.sharedEventStore = sharedEventStore;
@@ -3917,7 +3091,7 @@ var SharedStore = class {
3917
3091
  * Promote a verified troubleshooting entry to shared storage
3918
3092
  */
3919
3093
  async promoteEntry(input) {
3920
- const entryId = randomUUID3();
3094
+ const entryId = randomUUID2();
3921
3095
  await dbRun(
3922
3096
  this.db,
3923
3097
  `INSERT INTO shared_troubleshooting (
@@ -4282,7 +3456,7 @@ function createSharedVectorStore(dbPath) {
4282
3456
  }
4283
3457
 
4284
3458
  // src/core/shared-promoter.ts
4285
- import { randomUUID as randomUUID4 } from "crypto";
3459
+ import { randomUUID as randomUUID3 } from "crypto";
4286
3460
  var SharedPromoter = class {
4287
3461
  constructor(sharedStore, sharedVectorStore, embedder, config) {
4288
3462
  this.sharedStore = sharedStore;
@@ -4350,7 +3524,7 @@ var SharedPromoter = class {
4350
3524
  const embeddingContent = this.createEmbeddingContent(input);
4351
3525
  const embedding = await this.embedder.embed(embeddingContent);
4352
3526
  await this.sharedVectorStore.upsert({
4353
- id: randomUUID4(),
3527
+ id: randomUUID3(),
4354
3528
  entryId,
4355
3529
  entryType: "troubleshooting",
4356
3530
  content: embeddingContent,
@@ -4490,7 +3664,7 @@ function createToolObservationEmbedding(toolName, metadata, success) {
4490
3664
  }
4491
3665
 
4492
3666
  // src/core/working-set-store.ts
4493
- import { randomUUID as randomUUID5 } from "crypto";
3667
+ import { randomUUID as randomUUID4 } from "crypto";
4494
3668
  var WorkingSetStore = class {
4495
3669
  constructor(eventStore, config) {
4496
3670
  this.eventStore = eventStore;
@@ -4511,7 +3685,7 @@ var WorkingSetStore = class {
4511
3685
  `INSERT OR REPLACE INTO working_set (id, event_id, added_at, relevance_score, topics, expires_at)
4512
3686
  VALUES (?, ?, CURRENT_TIMESTAMP, ?, ?, ?)`,
4513
3687
  [
4514
- randomUUID5(),
3688
+ randomUUID4(),
4515
3689
  eventId,
4516
3690
  relevanceScore,
4517
3691
  JSON.stringify(topics || []),
@@ -4695,7 +3869,7 @@ function createWorkingSetStore(eventStore, config) {
4695
3869
  }
4696
3870
 
4697
3871
  // src/core/consolidated-store.ts
4698
- import { randomUUID as randomUUID6 } from "crypto";
3872
+ import { randomUUID as randomUUID5 } from "crypto";
4699
3873
  var ConsolidatedStore = class {
4700
3874
  constructor(eventStore) {
4701
3875
  this.eventStore = eventStore;
@@ -4707,7 +3881,7 @@ var ConsolidatedStore = class {
4707
3881
  * Create a new consolidated memory
4708
3882
  */
4709
3883
  async create(input) {
4710
- const memoryId = randomUUID6();
3884
+ const memoryId = randomUUID5();
4711
3885
  await dbRun(
4712
3886
  this.db,
4713
3887
  `INSERT INTO consolidated_memories
@@ -4837,7 +4011,7 @@ var ConsolidatedStore = class {
4837
4011
  * Create a long-term rule promoted from stable summaries
4838
4012
  */
4839
4013
  async createRule(input) {
4840
- const ruleId = randomUUID6();
4014
+ const ruleId = randomUUID5();
4841
4015
  await dbRun(
4842
4016
  this.db,
4843
4017
  `INSERT INTO consolidated_rules
@@ -5359,7 +4533,7 @@ function createConsolidationWorker(workingSetStore, consolidatedStore, config) {
5359
4533
  }
5360
4534
 
5361
4535
  // src/core/continuity-manager.ts
5362
- import { randomUUID as randomUUID7 } from "crypto";
4536
+ import { randomUUID as randomUUID6 } from "crypto";
5363
4537
  var ContinuityManager = class {
5364
4538
  constructor(eventStore, config) {
5365
4539
  this.eventStore = eventStore;
@@ -5513,7 +4687,7 @@ var ContinuityManager = class {
5513
4687
  `INSERT INTO continuity_log
5514
4688
  (log_id, from_context_id, to_context_id, continuity_score, transition_type, created_at)
5515
4689
  VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
5516
- [randomUUID7(), previous.id, current.id, score, type]
4690
+ [randomUUID6(), previous.id, current.id, score, type]
5517
4691
  );
5518
4692
  }
5519
4693
  /**
@@ -5622,7 +4796,7 @@ function createContinuityManager(eventStore, config) {
5622
4796
  }
5623
4797
 
5624
4798
  // src/core/graduation-worker.ts
5625
- var DEFAULT_CONFIG5 = {
4799
+ var DEFAULT_CONFIG4 = {
5626
4800
  evaluationIntervalMs: 3e5,
5627
4801
  // 5 minutes
5628
4802
  batchSize: 50,
@@ -5630,7 +4804,7 @@ var DEFAULT_CONFIG5 = {
5630
4804
  // 1 hour cooldown between evaluations
5631
4805
  };
5632
4806
  var GraduationWorker = class {
5633
- constructor(eventStore, graduation, config = DEFAULT_CONFIG5) {
4807
+ constructor(eventStore, graduation, config = DEFAULT_CONFIG4) {
5634
4808
  this.eventStore = eventStore;
5635
4809
  this.graduation = graduation;
5636
4810
  this.config = config;
@@ -5738,7 +4912,7 @@ function createGraduationWorker(eventStore, graduation, config) {
5738
4912
  return new GraduationWorker(
5739
4913
  eventStore,
5740
4914
  graduation,
5741
- { ...DEFAULT_CONFIG5, ...config }
4915
+ { ...DEFAULT_CONFIG4, ...config }
5742
4916
  );
5743
4917
  }
5744
4918
 
@@ -5976,9 +5150,6 @@ function getSessionProject(sessionId) {
5976
5150
  var MemoryService = class {
5977
5151
  // Primary store: SQLite (WAL mode) - for hooks, always available
5978
5152
  sqliteStore;
5979
- // Analytics store: DuckDB - for server reads (optional, synced from SQLite)
5980
- analyticsStore;
5981
- syncWorker = null;
5982
5153
  vectorStore;
5983
5154
  embedder;
5984
5155
  matcher;
@@ -6027,24 +5198,6 @@ var MemoryService = class {
6027
5198
  markdownMirrorRoot: storagePath
6028
5199
  }
6029
5200
  );
6030
- const analyticsEnabled = config.analyticsEnabled ?? this.readOnly;
6031
- if (!analyticsEnabled) {
6032
- this.analyticsStore = null;
6033
- } else if (this.readOnly) {
6034
- try {
6035
- this.analyticsStore = new EventStore(
6036
- path3.join(storagePath, "analytics.duckdb"),
6037
- { readOnly: true }
6038
- );
6039
- } catch {
6040
- this.analyticsStore = null;
6041
- }
6042
- } else {
6043
- this.analyticsStore = new EventStore(
6044
- path3.join(storagePath, "analytics.duckdb"),
6045
- { readOnly: false }
6046
- );
6047
- }
6048
5201
  this.vectorStore = new VectorStore(path3.join(storagePath, "vectors"));
6049
5202
  const embeddingModel = config.embeddingModel || process.env.CLAUDE_MEMORY_EMBEDDING_MODEL;
6050
5203
  this.embedder = embeddingModel ? new Embedder(embeddingModel) : getDefaultEmbedder();
@@ -6070,13 +5223,6 @@ var MemoryService = class {
6070
5223
  this.initialized = true;
6071
5224
  return;
6072
5225
  }
6073
- if (this.analyticsStore) {
6074
- try {
6075
- await this.analyticsStore.initialize();
6076
- } catch (error) {
6077
- console.warn("[MemoryService] Analytics store (DuckDB) initialization failed, using SQLite for reads:", error);
6078
- }
6079
- }
6080
5226
  await this.vectorStore.initialize();
6081
5227
  await this.embedder.initialize();
6082
5228
  if (!this.readOnly) {
@@ -6093,14 +5239,6 @@ var MemoryService = class {
6093
5239
  this.graduation
6094
5240
  );
6095
5241
  this.graduationWorker.start();
6096
- if (this.analyticsStore) {
6097
- this.syncWorker = new SyncWorker(
6098
- this.sqliteStore,
6099
- this.analyticsStore,
6100
- { intervalMs: 3e4, batchSize: 500 }
6101
- );
6102
- this.syncWorker.start();
6103
- }
6104
5242
  }
6105
5243
  const savedMode = await this.sqliteStore.getEndlessConfig("mode");
6106
5244
  if (savedMode === "endless") {
@@ -6297,6 +5435,57 @@ var MemoryService = class {
6297
5435
  }
6298
5436
  );
6299
5437
  }
5438
+ /**
5439
+ * Backfill session summaries for recent sessions that are missing them.
5440
+ * Called from session-start hook to catch sessions that ended without Stop hook.
5441
+ */
5442
+ async backfillMissingSummaries(currentSessionId, limit = 5) {
5443
+ await this.initialize();
5444
+ const recentSessionIds = await this.sqliteStore.getSessionsWithoutSummary(currentSessionId, limit);
5445
+ for (const sid of recentSessionIds) {
5446
+ try {
5447
+ await this.generateSessionSummary(sid);
5448
+ } catch {
5449
+ }
5450
+ }
5451
+ }
5452
+ /**
5453
+ * Generate a rule-based session summary from stored events.
5454
+ * Called at session end (Stop hook) when no LLM-generated summary exists.
5455
+ * Skips if a summary already exists for this session.
5456
+ */
5457
+ async generateSessionSummary(sessionId) {
5458
+ await this.initialize();
5459
+ const events = await this.sqliteStore.getSessionEvents(sessionId);
5460
+ if (events.length < 3)
5461
+ return;
5462
+ const hasSummary = events.some((e) => e.eventType === "session_summary");
5463
+ if (hasSummary)
5464
+ return;
5465
+ const prompts = events.filter((e) => e.eventType === "user_prompt");
5466
+ const toolObs = events.filter((e) => e.eventType === "tool_observation");
5467
+ const toolNames = [...new Set(
5468
+ toolObs.map((e) => e.metadata?.toolName).filter(Boolean)
5469
+ )];
5470
+ const errorObs = toolObs.filter((e) => {
5471
+ const meta = e.metadata;
5472
+ return meta?.exitCode !== void 0 && meta.exitCode !== 0;
5473
+ });
5474
+ const datePart = events[0].timestamp.toISOString().split("T")[0];
5475
+ const parts = [`[${datePart}] ${prompts.length}\uD134 \uC138\uC158.`];
5476
+ if (prompts.length > 0) {
5477
+ const firstPrompt = prompts[0].content.slice(0, 120).replace(/\n/g, " ");
5478
+ parts.push(`\uC8FC\uC694 \uC791\uC5C5: ${firstPrompt}`);
5479
+ }
5480
+ if (toolNames.length > 0) {
5481
+ parts.push(`\uC0AC\uC6A9 \uD234: ${toolNames.slice(0, 6).join(", ")}`);
5482
+ }
5483
+ if (errorObs.length > 0) {
5484
+ parts.push(`\uC624\uB958 ${errorObs.length}\uAC74 \uBC1C\uC0DD`);
5485
+ }
5486
+ const summary = parts.join(". ");
5487
+ await this.storeSessionSummary(sessionId, summary, { generated: "rule-based", eventCount: events.length });
5488
+ }
6300
5489
  /**
6301
5490
  * Store a tool observation
6302
5491
  */
@@ -6832,6 +6021,7 @@ var MemoryService = class {
6832
6021
  await this.initialize();
6833
6022
  await this.sqliteStore.recordRetrievalTrace({
6834
6023
  ...input,
6024
+ projectHash: this.projectHash || void 0,
6835
6025
  candidateDetails: [],
6836
6026
  selectedDetails: [],
6837
6027
  fallbackTrace: []
@@ -7122,16 +6312,10 @@ var MemoryService = class {
7122
6312
  if (this.vectorWorker) {
7123
6313
  this.vectorWorker.stop();
7124
6314
  }
7125
- if (this.syncWorker) {
7126
- this.syncWorker.stop();
7127
- }
7128
6315
  if (this.sharedEventStore) {
7129
6316
  await this.sharedEventStore.close();
7130
6317
  }
7131
6318
  await this.sqliteStore.close();
7132
- if (this.analyticsStore) {
7133
- await this.analyticsStore.close();
7134
- }
7135
6319
  }
7136
6320
  /**
7137
6321
  * Expand ~ to home directory