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
@@ -37,744 +37,31 @@ import * as os from "os";
37
37
  import * as fs4 from "fs";
38
38
  import * as crypto2 from "crypto";
39
39
 
40
- // src/core/event-store.ts
41
- import { randomUUID } from "crypto";
42
-
43
- // src/core/canonical-key.ts
44
- import { createHash } from "crypto";
45
- var MAX_KEY_LENGTH = 200;
46
- function makeCanonicalKey(title, context) {
47
- let normalized = title.normalize("NFKC");
48
- normalized = normalized.toLowerCase();
49
- normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, "");
50
- normalized = normalized.replace(/\s+/g, " ").trim();
51
- let key = normalized;
52
- if (context?.project) {
53
- key = `${context.project}::${key}`;
54
- }
55
- if (key.length > MAX_KEY_LENGTH) {
56
- const hashSuffix = createHash("md5").update(key).digest("hex").slice(0, 8);
57
- key = key.slice(0, MAX_KEY_LENGTH - 9) + "_" + hashSuffix;
58
- }
59
- return key;
60
- }
61
- function makeDedupeKey(content, sessionId) {
62
- const contentHash = createHash("sha256").update(content).digest("hex");
63
- return `${sessionId}:${contentHash}`;
64
- }
65
-
66
- // src/core/db-wrapper.ts
67
- import duckdb from "duckdb";
68
- function convertBigInts(obj) {
69
- if (obj === null || obj === void 0)
70
- return obj;
71
- if (typeof obj === "bigint")
72
- return Number(obj);
73
- if (obj instanceof Date)
74
- return obj;
75
- if (Array.isArray(obj))
76
- return obj.map(convertBigInts);
77
- if (typeof obj === "object") {
78
- const result = {};
79
- for (const [key, value] of Object.entries(obj)) {
80
- result[key] = convertBigInts(value);
81
- }
82
- return result;
83
- }
84
- return obj;
85
- }
86
- function toDate(value) {
87
- if (value instanceof Date)
88
- return value;
89
- if (typeof value === "string")
90
- return new Date(value);
91
- if (typeof value === "number")
92
- return new Date(value);
93
- return new Date(String(value));
94
- }
95
- function createDatabase(path8, options) {
96
- if (options?.readOnly) {
97
- return new duckdb.Database(path8, { access_mode: "READ_ONLY" });
98
- }
99
- return new duckdb.Database(path8);
100
- }
101
- function dbRun(db, sql, params = []) {
102
- return new Promise((resolve3, reject) => {
103
- if (params.length === 0) {
104
- db.run(sql, (err) => {
105
- if (err)
106
- reject(err);
107
- else
108
- resolve3();
109
- });
110
- } else {
111
- db.run(sql, ...params, (err) => {
112
- if (err)
113
- reject(err);
114
- else
115
- resolve3();
116
- });
117
- }
118
- });
119
- }
120
- function dbAll(db, sql, params = []) {
121
- return new Promise((resolve3, reject) => {
122
- if (params.length === 0) {
123
- db.all(sql, (err, rows) => {
124
- if (err)
125
- reject(err);
126
- else
127
- resolve3(convertBigInts(rows || []));
128
- });
129
- } else {
130
- db.all(sql, ...params, (err, rows) => {
131
- if (err)
132
- reject(err);
133
- else
134
- resolve3(convertBigInts(rows || []));
135
- });
136
- }
137
- });
138
- }
139
- function dbClose(db) {
140
- return new Promise((resolve3, reject) => {
141
- db.close((err) => {
142
- if (err)
143
- reject(err);
144
- else
145
- resolve3();
146
- });
147
- });
148
- }
149
-
150
- // src/core/event-store.ts
151
- var EventStore = class {
152
- constructor(dbPath, options) {
153
- this.dbPath = dbPath;
154
- this.readOnly = options?.readOnly ?? false;
155
- this.db = createDatabase(dbPath, { readOnly: this.readOnly });
156
- }
157
- db;
158
- initialized = false;
159
- readOnly;
160
- /**
161
- * Initialize database schema
162
- */
163
- async initialize() {
164
- if (this.initialized)
165
- return;
166
- if (this.readOnly) {
167
- this.initialized = true;
168
- return;
169
- }
170
- await dbRun(this.db, `
171
- CREATE TABLE IF NOT EXISTS events (
172
- id VARCHAR PRIMARY KEY,
173
- event_type VARCHAR NOT NULL,
174
- session_id VARCHAR NOT NULL,
175
- timestamp TIMESTAMP NOT NULL,
176
- content TEXT NOT NULL,
177
- canonical_key VARCHAR NOT NULL,
178
- dedupe_key VARCHAR UNIQUE,
179
- metadata JSON
180
- )
181
- `);
182
- await dbRun(this.db, `
183
- CREATE TABLE IF NOT EXISTS event_dedup (
184
- dedupe_key VARCHAR PRIMARY KEY,
185
- event_id VARCHAR NOT NULL,
186
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
187
- )
188
- `);
189
- await dbRun(this.db, `
190
- CREATE TABLE IF NOT EXISTS sessions (
191
- id VARCHAR PRIMARY KEY,
192
- started_at TIMESTAMP NOT NULL,
193
- ended_at TIMESTAMP,
194
- project_path VARCHAR,
195
- summary TEXT,
196
- tags JSON
197
- )
198
- `);
199
- await dbRun(this.db, `
200
- CREATE TABLE IF NOT EXISTS insights (
201
- id VARCHAR PRIMARY KEY,
202
- insight_type VARCHAR NOT NULL,
203
- content TEXT NOT NULL,
204
- canonical_key VARCHAR NOT NULL,
205
- confidence FLOAT,
206
- source_events JSON,
207
- created_at TIMESTAMP,
208
- last_updated TIMESTAMP
209
- )
210
- `);
211
- await dbRun(this.db, `
212
- CREATE TABLE IF NOT EXISTS embedding_outbox (
213
- id VARCHAR PRIMARY KEY,
214
- event_id VARCHAR NOT NULL,
215
- content TEXT NOT NULL,
216
- status VARCHAR DEFAULT 'pending',
217
- retry_count INT DEFAULT 0,
218
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
219
- processed_at TIMESTAMP,
220
- error_message TEXT
221
- )
222
- `);
223
- await dbRun(this.db, `
224
- CREATE TABLE IF NOT EXISTS projection_offsets (
225
- projection_name VARCHAR PRIMARY KEY,
226
- last_event_id VARCHAR,
227
- last_timestamp TIMESTAMP,
228
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
229
- )
230
- `);
231
- await dbRun(this.db, `
232
- CREATE TABLE IF NOT EXISTS memory_levels (
233
- event_id VARCHAR PRIMARY KEY,
234
- level VARCHAR NOT NULL DEFAULT 'L0',
235
- promoted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
236
- )
237
- `);
238
- await dbRun(this.db, `
239
- CREATE TABLE IF NOT EXISTS entries (
240
- entry_id VARCHAR PRIMARY KEY,
241
- created_ts TIMESTAMP NOT NULL,
242
- entry_type VARCHAR NOT NULL,
243
- title VARCHAR NOT NULL,
244
- content_json JSON NOT NULL,
245
- stage VARCHAR NOT NULL DEFAULT 'raw',
246
- status VARCHAR DEFAULT 'active',
247
- superseded_by VARCHAR,
248
- build_id VARCHAR,
249
- evidence_json JSON,
250
- canonical_key VARCHAR,
251
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
252
- )
253
- `);
254
- await dbRun(this.db, `
255
- CREATE TABLE IF NOT EXISTS entities (
256
- entity_id VARCHAR PRIMARY KEY,
257
- entity_type VARCHAR NOT NULL,
258
- canonical_key VARCHAR NOT NULL,
259
- title VARCHAR NOT NULL,
260
- stage VARCHAR NOT NULL DEFAULT 'raw',
261
- status VARCHAR NOT NULL DEFAULT 'active',
262
- current_json JSON NOT NULL,
263
- title_norm VARCHAR,
264
- search_text VARCHAR,
265
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
266
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
267
- )
268
- `);
269
- await dbRun(this.db, `
270
- CREATE TABLE IF NOT EXISTS entity_aliases (
271
- entity_type VARCHAR NOT NULL,
272
- canonical_key VARCHAR NOT NULL,
273
- entity_id VARCHAR NOT NULL,
274
- is_primary BOOLEAN DEFAULT FALSE,
275
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
276
- PRIMARY KEY(entity_type, canonical_key)
277
- )
278
- `);
279
- await dbRun(this.db, `
280
- CREATE TABLE IF NOT EXISTS edges (
281
- edge_id VARCHAR PRIMARY KEY,
282
- src_type VARCHAR NOT NULL,
283
- src_id VARCHAR NOT NULL,
284
- rel_type VARCHAR NOT NULL,
285
- dst_type VARCHAR NOT NULL,
286
- dst_id VARCHAR NOT NULL,
287
- meta_json JSON,
288
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
289
- )
290
- `);
291
- await dbRun(this.db, `
292
- CREATE TABLE IF NOT EXISTS vector_outbox (
293
- job_id VARCHAR PRIMARY KEY,
294
- item_kind VARCHAR NOT NULL,
295
- item_id VARCHAR NOT NULL,
296
- embedding_version VARCHAR NOT NULL,
297
- status VARCHAR NOT NULL DEFAULT 'pending',
298
- retry_count INT DEFAULT 0,
299
- error VARCHAR,
300
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
301
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
302
- UNIQUE(item_kind, item_id, embedding_version)
303
- )
304
- `);
305
- await dbRun(this.db, `
306
- CREATE TABLE IF NOT EXISTS build_runs (
307
- build_id VARCHAR PRIMARY KEY,
308
- started_at TIMESTAMP NOT NULL,
309
- finished_at TIMESTAMP,
310
- extractor_model VARCHAR NOT NULL,
311
- extractor_prompt_hash VARCHAR NOT NULL,
312
- embedder_model VARCHAR NOT NULL,
313
- embedding_version VARCHAR NOT NULL,
314
- idris_version VARCHAR NOT NULL,
315
- schema_version VARCHAR NOT NULL,
316
- status VARCHAR NOT NULL DEFAULT 'running',
317
- error VARCHAR
318
- )
319
- `);
320
- await dbRun(this.db, `
321
- CREATE TABLE IF NOT EXISTS pipeline_metrics (
322
- id VARCHAR PRIMARY KEY,
323
- ts TIMESTAMP NOT NULL,
324
- stage VARCHAR NOT NULL,
325
- latency_ms DOUBLE NOT NULL,
326
- success BOOLEAN NOT NULL,
327
- error VARCHAR,
328
- session_id VARCHAR
329
- )
330
- `);
331
- await dbRun(this.db, `
332
- CREATE TABLE IF NOT EXISTS working_set (
333
- id VARCHAR PRIMARY KEY,
334
- event_id VARCHAR NOT NULL,
335
- added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
336
- relevance_score FLOAT DEFAULT 1.0,
337
- topics JSON,
338
- expires_at TIMESTAMP
339
- )
340
- `);
341
- await dbRun(this.db, `
342
- CREATE TABLE IF NOT EXISTS consolidated_memories (
343
- memory_id VARCHAR PRIMARY KEY,
344
- summary TEXT NOT NULL,
345
- topics JSON,
346
- source_events JSON,
347
- confidence FLOAT DEFAULT 0.5,
348
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
349
- accessed_at TIMESTAMP,
350
- access_count INTEGER DEFAULT 0
351
- )
352
- `);
353
- await dbRun(this.db, `
354
- CREATE TABLE IF NOT EXISTS continuity_log (
355
- log_id VARCHAR PRIMARY KEY,
356
- from_context_id VARCHAR,
357
- to_context_id VARCHAR,
358
- continuity_score FLOAT,
359
- transition_type VARCHAR,
360
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
361
- )
362
- `);
363
- await dbRun(this.db, `
364
- CREATE TABLE IF NOT EXISTS consolidated_rules (
365
- rule_id VARCHAR PRIMARY KEY,
366
- rule TEXT NOT NULL,
367
- topics JSON,
368
- source_memory_ids JSON,
369
- source_events JSON,
370
- confidence FLOAT DEFAULT 0.5,
371
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
372
- )
373
- `);
374
- await dbRun(this.db, `
375
- CREATE TABLE IF NOT EXISTS endless_config (
376
- key VARCHAR PRIMARY KEY,
377
- value JSON,
378
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
379
- )
380
- `);
381
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_type ON entries(entry_type)`);
382
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_stage ON entries(stage)`);
383
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_canonical ON entries(canonical_key)`);
384
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entities_type_key ON entities(entity_type, canonical_key)`);
385
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entities_status ON entities(status)`);
386
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src_id, rel_type)`);
387
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_dst ON edges(dst_id, rel_type)`);
388
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_rel ON edges(rel_type)`);
389
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_outbox_status ON vector_outbox(status)`);
390
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_expires ON working_set(expires_at)`);
391
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_relevance ON working_set(relevance_score DESC)`);
392
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence DESC)`);
393
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_rules_confidence ON consolidated_rules(confidence DESC)`);
394
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at)`);
395
- this.initialized = true;
396
- }
397
- /**
398
- * Append event to store (AXIOMMIND Principle 2: Append-only)
399
- * Returns existing event ID if duplicate (Principle 3: Idempotency)
400
- */
401
- async append(input) {
402
- await this.initialize();
403
- const canonicalKey = makeCanonicalKey(input.content);
404
- const dedupeKey = makeDedupeKey(input.content, input.sessionId);
405
- const existing = await dbAll(
406
- this.db,
407
- `SELECT event_id FROM event_dedup WHERE dedupe_key = ?`,
408
- [dedupeKey]
409
- );
410
- if (existing.length > 0) {
411
- return {
412
- success: true,
413
- eventId: existing[0].event_id,
414
- isDuplicate: true
415
- };
416
- }
417
- const id = randomUUID();
418
- const timestamp = input.timestamp.toISOString();
419
- try {
420
- await dbRun(
421
- this.db,
422
- `INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
423
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
424
- [
425
- id,
426
- input.eventType,
427
- input.sessionId,
428
- timestamp,
429
- input.content,
430
- canonicalKey,
431
- dedupeKey,
432
- JSON.stringify(input.metadata || {})
433
- ]
434
- );
435
- await dbRun(
436
- this.db,
437
- `INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)`,
438
- [dedupeKey, id]
439
- );
440
- await dbRun(
441
- this.db,
442
- `INSERT INTO memory_levels (event_id, level) VALUES (?, 'L0')`,
443
- [id]
444
- );
445
- return { success: true, eventId: id, isDuplicate: false };
446
- } catch (error) {
447
- return {
448
- success: false,
449
- error: error instanceof Error ? error.message : String(error)
450
- };
451
- }
452
- }
453
- /**
454
- * Get events by session ID
455
- */
456
- async getSessionEvents(sessionId) {
457
- await this.initialize();
458
- const rows = await dbAll(
459
- this.db,
460
- `SELECT * FROM events WHERE session_id = ? ORDER BY timestamp ASC`,
461
- [sessionId]
462
- );
463
- return rows.map(this.rowToEvent);
464
- }
465
- /**
466
- * Get recent events
467
- */
468
- async getRecentEvents(limit = 100) {
469
- await this.initialize();
470
- const rows = await dbAll(
471
- this.db,
472
- `SELECT * FROM events ORDER BY timestamp DESC LIMIT ?`,
473
- [limit]
474
- );
475
- return rows.map(this.rowToEvent);
476
- }
477
- /**
478
- * Get event by ID
479
- */
480
- async getEvent(id) {
481
- await this.initialize();
482
- const rows = await dbAll(
483
- this.db,
484
- `SELECT * FROM events WHERE id = ?`,
485
- [id]
486
- );
487
- if (rows.length === 0)
488
- return null;
489
- return this.rowToEvent(rows[0]);
490
- }
491
- /**
492
- * Create or update session
493
- */
494
- async upsertSession(session) {
495
- await this.initialize();
496
- const existing = await dbAll(
497
- this.db,
498
- `SELECT id FROM sessions WHERE id = ?`,
499
- [session.id]
500
- );
501
- if (existing.length === 0) {
502
- await dbRun(
503
- this.db,
504
- `INSERT INTO sessions (id, started_at, project_path, tags)
505
- VALUES (?, ?, ?, ?)`,
506
- [
507
- session.id,
508
- (session.startedAt || /* @__PURE__ */ new Date()).toISOString(),
509
- session.projectPath || null,
510
- JSON.stringify(session.tags || [])
511
- ]
512
- );
513
- } else {
514
- const updates = [];
515
- const values = [];
516
- if (session.endedAt) {
517
- updates.push("ended_at = ?");
518
- values.push(session.endedAt.toISOString());
519
- }
520
- if (session.summary) {
521
- updates.push("summary = ?");
522
- values.push(session.summary);
523
- }
524
- if (session.tags) {
525
- updates.push("tags = ?");
526
- values.push(JSON.stringify(session.tags));
527
- }
528
- if (updates.length > 0) {
529
- values.push(session.id);
530
- await dbRun(
531
- this.db,
532
- `UPDATE sessions SET ${updates.join(", ")} WHERE id = ?`,
533
- values
534
- );
535
- }
536
- }
537
- }
538
- /**
539
- * Get session by ID
540
- */
541
- async getSession(id) {
542
- await this.initialize();
543
- const rows = await dbAll(
544
- this.db,
545
- `SELECT * FROM sessions WHERE id = ?`,
546
- [id]
547
- );
548
- if (rows.length === 0)
549
- return null;
550
- const row = rows[0];
551
- return {
552
- id: row.id,
553
- startedAt: toDate(row.started_at),
554
- endedAt: row.ended_at ? toDate(row.ended_at) : void 0,
555
- projectPath: row.project_path,
556
- summary: row.summary,
557
- tags: row.tags ? JSON.parse(row.tags) : void 0
558
- };
559
- }
560
- /**
561
- * Add to embedding outbox (Single-Writer Pattern)
562
- */
563
- async enqueueForEmbedding(eventId, content) {
564
- await this.initialize();
565
- const id = randomUUID();
566
- await dbRun(
567
- this.db,
568
- `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
569
- VALUES (?, ?, ?, 'pending', 0)`,
570
- [id, eventId, content]
571
- );
572
- return id;
573
- }
574
- /**
575
- * Get pending outbox items
576
- */
577
- async getPendingOutboxItems(limit = 32) {
578
- await this.initialize();
579
- const pending = await dbAll(
580
- this.db,
581
- `SELECT * FROM embedding_outbox
582
- WHERE status = 'pending'
583
- ORDER BY created_at
584
- LIMIT ?`,
585
- [limit]
586
- );
587
- if (pending.length === 0)
588
- return [];
589
- const ids = pending.map((r) => r.id);
590
- const placeholders = ids.map(() => "?").join(",");
591
- await dbRun(
592
- this.db,
593
- `UPDATE embedding_outbox SET status = 'processing' WHERE id IN (${placeholders})`,
594
- ids
595
- );
596
- return pending.map((row) => ({
597
- id: row.id,
598
- eventId: row.event_id,
599
- content: row.content,
600
- status: "processing",
601
- retryCount: row.retry_count,
602
- createdAt: toDate(row.created_at),
603
- errorMessage: row.error_message
604
- }));
605
- }
606
- /**
607
- * Mark outbox items as done
608
- */
609
- async completeOutboxItems(ids) {
610
- if (ids.length === 0)
611
- return;
612
- const placeholders = ids.map(() => "?").join(",");
613
- await dbRun(
614
- this.db,
615
- `DELETE FROM embedding_outbox WHERE id IN (${placeholders})`,
616
- ids
617
- );
618
- }
619
- /**
620
- * Mark outbox items as failed
621
- */
622
- async failOutboxItems(ids, error) {
623
- if (ids.length === 0)
624
- return;
625
- const placeholders = ids.map(() => "?").join(",");
626
- await dbRun(
627
- this.db,
628
- `UPDATE embedding_outbox
629
- SET status = CASE WHEN retry_count >= 3 THEN 'failed' ELSE 'pending' END,
630
- retry_count = retry_count + 1,
631
- error_message = ?
632
- WHERE id IN (${placeholders})`,
633
- [error, ...ids]
634
- );
635
- }
636
- /**
637
- * Update memory level
638
- */
639
- async updateMemoryLevel(eventId, level) {
640
- await this.initialize();
641
- await dbRun(
642
- this.db,
643
- `UPDATE memory_levels SET level = ?, promoted_at = CURRENT_TIMESTAMP WHERE event_id = ?`,
644
- [level, eventId]
645
- );
646
- }
647
- /**
648
- * Get memory level statistics
649
- */
650
- async getLevelStats() {
651
- await this.initialize();
652
- const rows = await dbAll(
653
- this.db,
654
- `SELECT level, COUNT(*) as count FROM memory_levels GROUP BY level`
655
- );
656
- return rows;
657
- }
658
- /**
659
- * Get events by memory level
660
- */
661
- async getEventsByLevel(level, options) {
662
- await this.initialize();
663
- const limit = options?.limit || 50;
664
- const offset = options?.offset || 0;
665
- const rows = await dbAll(
666
- this.db,
667
- `SELECT e.* FROM events e
668
- INNER JOIN memory_levels ml ON e.id = ml.event_id
669
- WHERE ml.level = ?
670
- ORDER BY e.timestamp DESC
671
- LIMIT ? OFFSET ?`,
672
- [level, limit, offset]
673
- );
674
- return rows.map((row) => this.rowToEvent(row));
675
- }
676
- /**
677
- * Get memory level for a specific event
678
- */
679
- async getEventLevel(eventId) {
680
- await this.initialize();
681
- const rows = await dbAll(
682
- this.db,
683
- `SELECT level FROM memory_levels WHERE event_id = ?`,
684
- [eventId]
685
- );
686
- return rows.length > 0 ? rows[0].level : null;
687
- }
688
- // ============================================================
689
- // Endless Mode Helper Methods
690
- // ============================================================
691
- /**
692
- * Get database instance for Endless Mode stores
693
- */
694
- getDatabase() {
695
- return this.db;
696
- }
697
- /**
698
- * Get config value for endless mode
699
- */
700
- async getEndlessConfig(key) {
701
- await this.initialize();
702
- const rows = await dbAll(
703
- this.db,
704
- `SELECT value FROM endless_config WHERE key = ?`,
705
- [key]
706
- );
707
- if (rows.length === 0)
708
- return null;
709
- return JSON.parse(rows[0].value);
710
- }
711
- /**
712
- * Set config value for endless mode
713
- */
714
- async setEndlessConfig(key, value) {
715
- await this.initialize();
716
- await dbRun(
717
- this.db,
718
- `INSERT OR REPLACE INTO endless_config (key, value, updated_at)
719
- VALUES (?, ?, CURRENT_TIMESTAMP)`,
720
- [key, JSON.stringify(value)]
721
- );
722
- }
723
- /**
724
- * Get all sessions
725
- */
726
- async getAllSessions() {
727
- await this.initialize();
728
- const rows = await dbAll(
729
- this.db,
730
- `SELECT * FROM sessions ORDER BY started_at DESC`
731
- );
732
- return rows.map((row) => ({
733
- id: row.id,
734
- startedAt: toDate(row.started_at),
735
- endedAt: row.ended_at ? toDate(row.ended_at) : void 0,
736
- projectPath: row.project_path,
737
- summary: row.summary,
738
- tags: row.tags ? JSON.parse(row.tags) : void 0
739
- }));
740
- }
741
- /**
742
- * Increment access count for events (stub for compatibility)
743
- */
744
- async incrementAccessCount(eventIds) {
745
- return Promise.resolve();
746
- }
747
- /**
748
- * Get most accessed memories (stub for compatibility)
749
- */
750
- async getMostAccessed(limit = 10) {
751
- return [];
752
- }
753
- /**
754
- * Close database connection
755
- */
756
- async close() {
757
- await dbClose(this.db);
40
+ // src/core/sqlite-event-store.ts
41
+ import { randomUUID } from "crypto";
42
+
43
+ // src/core/canonical-key.ts
44
+ import { createHash } from "crypto";
45
+ var MAX_KEY_LENGTH = 200;
46
+ function makeCanonicalKey(title, context) {
47
+ let normalized = title.normalize("NFKC");
48
+ normalized = normalized.toLowerCase();
49
+ normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, "");
50
+ normalized = normalized.replace(/\s+/g, " ").trim();
51
+ let key = normalized;
52
+ if (context?.project) {
53
+ key = `${context.project}::${key}`;
758
54
  }
759
- /**
760
- * Convert database row to MemoryEvent
761
- */
762
- rowToEvent(row) {
763
- return {
764
- id: row.id,
765
- eventType: row.event_type,
766
- sessionId: row.session_id,
767
- timestamp: toDate(row.timestamp),
768
- content: row.content,
769
- canonicalKey: row.canonical_key,
770
- dedupeKey: row.dedupe_key,
771
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0
772
- };
55
+ if (key.length > MAX_KEY_LENGTH) {
56
+ const hashSuffix = createHash("md5").update(key).digest("hex").slice(0, 8);
57
+ key = key.slice(0, MAX_KEY_LENGTH - 9) + "_" + hashSuffix;
773
58
  }
774
- };
775
-
776
- // src/core/sqlite-event-store.ts
777
- import { randomUUID as randomUUID2 } from "crypto";
59
+ return key;
60
+ }
61
+ function makeDedupeKey(content, sessionId) {
62
+ const contentHash = createHash("sha256").update(content).digest("hex");
63
+ return `${sessionId}:${contentHash}`;
64
+ }
778
65
 
779
66
  // src/core/sqlite-wrapper.ts
780
67
  import Database from "better-sqlite3";
@@ -1289,7 +576,7 @@ var SQLiteEventStore = class {
1289
576
  isDuplicate: true
1290
577
  };
1291
578
  }
1292
- const id = randomUUID2();
579
+ const id = randomUUID();
1293
580
  const timestamp = toSQLiteTimestamp(input.timestamp);
1294
581
  try {
1295
582
  const metadata = input.metadata || {};
@@ -1343,6 +630,29 @@ var SQLiteEventStore = class {
1343
630
  };
1344
631
  }
1345
632
  }
633
+ /**
634
+ * Get session IDs that have events but no session_summary event.
635
+ * Used to backfill summaries for sessions that ended without Stop hook.
636
+ */
637
+ async getSessionsWithoutSummary(currentSessionId, limit = 5) {
638
+ await this.initialize();
639
+ const rows = sqliteAll(
640
+ this.db,
641
+ `SELECT DISTINCT e.session_id
642
+ FROM events e
643
+ WHERE e.session_id != ?
644
+ AND e.event_type != 'session_summary'
645
+ AND e.session_id NOT IN (
646
+ SELECT DISTINCT session_id FROM events WHERE event_type = 'session_summary'
647
+ )
648
+ GROUP BY e.session_id
649
+ HAVING COUNT(*) >= 3
650
+ ORDER BY MAX(e.timestamp) DESC
651
+ LIMIT ?`,
652
+ [currentSessionId, limit]
653
+ );
654
+ return rows.map((r) => r.session_id);
655
+ }
1346
656
  /**
1347
657
  * Get events by session ID
1348
658
  */
@@ -1570,7 +880,7 @@ var SQLiteEventStore = class {
1570
880
  */
1571
881
  async enqueueForEmbedding(eventId, content) {
1572
882
  await this.initialize();
1573
- const id = randomUUID2();
883
+ const id = randomUUID();
1574
884
  sqliteRun(
1575
885
  this.db,
1576
886
  `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
@@ -1851,7 +1161,7 @@ var SQLiteEventStore = class {
1851
1161
  if (this.readOnly)
1852
1162
  return;
1853
1163
  await this.initialize();
1854
- const id = randomUUID2();
1164
+ const id = randomUUID();
1855
1165
  sqliteRun(
1856
1166
  this.db,
1857
1167
  `INSERT INTO memory_helpfulness (id, event_id, session_id, retrieval_score, query_preview, created_at)
@@ -1929,7 +1239,8 @@ var SQLiteEventStore = class {
1929
1239
  }
1930
1240
  }
1931
1241
  const retrievalScore = retrieval.retrieval_score || 0;
1932
- const helpfulnessScore = 0.3 * Math.min(retrievalScore, 1) + 0.25 * (sessionContinued ? 1 : 0) + 0.25 * toolSuccessRatio + 0.2 * (wasReasked ? 0 : 1);
1242
+ const promptNorm = Math.min(promptCountAfter / 2, 1);
1243
+ const helpfulnessScore = 0.4 * Math.min(retrievalScore, 1) + 0.3 * promptNorm + 0.2 * toolSuccessRatio + 0.1 * (sessionContinued ? 1 : 0);
1933
1244
  sqliteRun(
1934
1245
  this.db,
1935
1246
  `UPDATE memory_helpfulness
@@ -2072,7 +1383,7 @@ var SQLiteEventStore = class {
2072
1383
  }
2073
1384
  async recordRetrievalTrace(input) {
2074
1385
  await this.initialize();
2075
- const traceId = randomUUID2();
1386
+ const traceId = randomUUID();
2076
1387
  sqliteRun(
2077
1388
  this.db,
2078
1389
  `INSERT INTO retrieval_traces (
@@ -2326,169 +1637,6 @@ var SQLiteEventStore = class {
2326
1637
  }
2327
1638
  };
2328
1639
 
2329
- // src/core/sync-worker.ts
2330
- var DEFAULT_CONFIG = {
2331
- intervalMs: 3e4,
2332
- batchSize: 500,
2333
- maxRetries: 3,
2334
- retryDelayMs: 5e3
2335
- };
2336
- var SyncWorker = class {
2337
- constructor(sqliteStore, duckdbStore, config) {
2338
- this.sqliteStore = sqliteStore;
2339
- this.duckdbStore = duckdbStore;
2340
- this.config = { ...DEFAULT_CONFIG, ...config };
2341
- }
2342
- config;
2343
- intervalHandle = null;
2344
- running = false;
2345
- stats = {
2346
- lastSyncAt: null,
2347
- eventsSynced: 0,
2348
- sessionsSynced: 0,
2349
- errors: 0,
2350
- status: "idle"
2351
- };
2352
- /**
2353
- * Start the sync worker
2354
- */
2355
- start() {
2356
- if (this.running)
2357
- return;
2358
- this.running = true;
2359
- this.stats.status = "idle";
2360
- this.syncNow().catch((err) => {
2361
- console.error("[SyncWorker] Initial sync failed:", err);
2362
- });
2363
- this.intervalHandle = setInterval(() => {
2364
- this.syncNow().catch((err) => {
2365
- console.error("[SyncWorker] Periodic sync failed:", err);
2366
- });
2367
- }, this.config.intervalMs);
2368
- }
2369
- /**
2370
- * Stop the sync worker
2371
- */
2372
- stop() {
2373
- this.running = false;
2374
- this.stats.status = "stopped";
2375
- if (this.intervalHandle) {
2376
- clearInterval(this.intervalHandle);
2377
- this.intervalHandle = null;
2378
- }
2379
- }
2380
- /**
2381
- * Trigger immediate sync
2382
- */
2383
- async syncNow() {
2384
- if (this.stats.status === "syncing") {
2385
- return;
2386
- }
2387
- this.stats.status = "syncing";
2388
- try {
2389
- await this.syncEvents();
2390
- await this.syncSessions();
2391
- this.stats.lastSyncAt = /* @__PURE__ */ new Date();
2392
- this.stats.status = "idle";
2393
- } catch (error) {
2394
- this.stats.errors++;
2395
- this.stats.status = "error";
2396
- throw error;
2397
- }
2398
- }
2399
- /**
2400
- * Sync events from SQLite to DuckDB
2401
- */
2402
- async syncEvents() {
2403
- const targetName = "duckdb_analytics";
2404
- const position = await this.sqliteStore.getSyncPosition(targetName);
2405
- const lastTimestamp = position.lastTimestamp || "1970-01-01T00:00:00.000Z";
2406
- let hasMore = true;
2407
- let totalSynced = 0;
2408
- while (hasMore) {
2409
- const events = await this.sqliteStore.getEventsSince(lastTimestamp, this.config.batchSize);
2410
- if (events.length === 0) {
2411
- hasMore = false;
2412
- break;
2413
- }
2414
- await this.retryWithBackoff(async () => {
2415
- for (const event of events) {
2416
- await this.insertEventToDuckDB(event);
2417
- }
2418
- });
2419
- totalSynced += events.length;
2420
- const lastEvent = events[events.length - 1];
2421
- await this.sqliteStore.updateSyncPosition(
2422
- targetName,
2423
- lastEvent.id,
2424
- lastEvent.timestamp.toISOString()
2425
- );
2426
- hasMore = events.length === this.config.batchSize;
2427
- }
2428
- this.stats.eventsSynced += totalSynced;
2429
- }
2430
- /**
2431
- * Sync sessions from SQLite to DuckDB
2432
- */
2433
- async syncSessions() {
2434
- const sessions = await this.sqliteStore.getAllSessions();
2435
- for (const session of sessions) {
2436
- await this.retryWithBackoff(async () => {
2437
- await this.duckdbStore.upsertSession(session);
2438
- });
2439
- }
2440
- this.stats.sessionsSynced = sessions.length;
2441
- }
2442
- /**
2443
- * Insert a single event into DuckDB
2444
- */
2445
- async insertEventToDuckDB(event) {
2446
- await this.duckdbStore.append({
2447
- eventType: event.eventType,
2448
- sessionId: event.sessionId,
2449
- timestamp: event.timestamp,
2450
- content: event.content,
2451
- metadata: event.metadata
2452
- });
2453
- }
2454
- /**
2455
- * Retry operation with exponential backoff
2456
- */
2457
- async retryWithBackoff(fn) {
2458
- let lastError = null;
2459
- for (let attempt = 0; attempt < this.config.maxRetries; attempt++) {
2460
- try {
2461
- return await fn();
2462
- } catch (error) {
2463
- lastError = error instanceof Error ? error : new Error(String(error));
2464
- if (attempt < this.config.maxRetries - 1) {
2465
- const delay = this.config.retryDelayMs * Math.pow(2, attempt);
2466
- await this.sleep(delay);
2467
- }
2468
- }
2469
- }
2470
- throw lastError;
2471
- }
2472
- /**
2473
- * Sleep utility
2474
- */
2475
- sleep(ms) {
2476
- return new Promise((resolve3) => setTimeout(resolve3, ms));
2477
- }
2478
- /**
2479
- * Get sync statistics
2480
- */
2481
- getStats() {
2482
- return { ...this.stats };
2483
- }
2484
- /**
2485
- * Check if worker is running
2486
- */
2487
- isRunning() {
2488
- return this.running;
2489
- }
2490
- };
2491
-
2492
1640
  // src/core/vector-store.ts
2493
1641
  import * as lancedb from "@lancedb/lancedb";
2494
1642
  var VectorStore = class {
@@ -2776,8 +1924,34 @@ function getDefaultEmbedder() {
2776
1924
  return defaultEmbedder;
2777
1925
  }
2778
1926
 
1927
+ // src/core/db-wrapper.ts
1928
+ import BetterSqlite3 from "better-sqlite3";
1929
+ function toDate(value) {
1930
+ if (value instanceof Date)
1931
+ return value;
1932
+ if (typeof value === "string")
1933
+ return new Date(value);
1934
+ if (typeof value === "number")
1935
+ return new Date(value);
1936
+ return new Date(String(value));
1937
+ }
1938
+ function createDatabase(dbPath, options) {
1939
+ return new BetterSqlite3(dbPath, { readonly: options?.readOnly });
1940
+ }
1941
+ function dbRun(db, sql, params = []) {
1942
+ db.prepare(sql).run(...params);
1943
+ return Promise.resolve();
1944
+ }
1945
+ function dbAll(db, sql, params = []) {
1946
+ return Promise.resolve(db.prepare(sql).all(...params));
1947
+ }
1948
+ function dbClose(db) {
1949
+ db.close();
1950
+ return Promise.resolve();
1951
+ }
1952
+
2779
1953
  // src/core/vector-outbox.ts
2780
- var DEFAULT_CONFIG2 = {
1954
+ var DEFAULT_CONFIG = {
2781
1955
  embeddingVersion: "v1",
2782
1956
  maxRetries: 3,
2783
1957
  stuckThresholdMs: 5 * 60 * 1e3,
@@ -2786,7 +1960,7 @@ var DEFAULT_CONFIG2 = {
2786
1960
  };
2787
1961
 
2788
1962
  // src/core/vector-worker.ts
2789
- var DEFAULT_CONFIG3 = {
1963
+ var DEFAULT_CONFIG2 = {
2790
1964
  batchSize: 32,
2791
1965
  pollIntervalMs: 1e3,
2792
1966
  maxRetries: 3
@@ -2803,7 +1977,7 @@ var VectorWorker = class {
2803
1977
  this.eventStore = eventStore;
2804
1978
  this.vectorStore = vectorStore;
2805
1979
  this.embedder = embedder;
2806
- this.config = { ...DEFAULT_CONFIG3, ...config };
1980
+ this.config = { ...DEFAULT_CONFIG2, ...config };
2807
1981
  }
2808
1982
  /**
2809
1983
  * Start the worker polling loop
@@ -2924,7 +2098,7 @@ function createVectorWorker(eventStore, vectorStore, embedder, config) {
2924
2098
  }
2925
2099
 
2926
2100
  // src/core/matcher.ts
2927
- var DEFAULT_CONFIG4 = {
2101
+ var DEFAULT_CONFIG3 = {
2928
2102
  weights: {
2929
2103
  semanticSimilarity: 0.4,
2930
2104
  ftsScore: 0.25,
@@ -2939,9 +2113,9 @@ var Matcher = class {
2939
2113
  config;
2940
2114
  constructor(config = {}) {
2941
2115
  this.config = {
2942
- ...DEFAULT_CONFIG4,
2116
+ ...DEFAULT_CONFIG3,
2943
2117
  ...config,
2944
- weights: { ...DEFAULT_CONFIG4.weights, ...config.weights }
2118
+ weights: { ...DEFAULT_CONFIG3.weights, ...config.weights }
2945
2119
  };
2946
2120
  }
2947
2121
  /**
@@ -3931,7 +3105,7 @@ function createSharedEventStore(dbPath) {
3931
3105
  }
3932
3106
 
3933
3107
  // src/core/shared-store.ts
3934
- import { randomUUID as randomUUID3 } from "crypto";
3108
+ import { randomUUID as randomUUID2 } from "crypto";
3935
3109
  var SharedStore = class {
3936
3110
  constructor(sharedEventStore) {
3937
3111
  this.sharedEventStore = sharedEventStore;
@@ -3943,7 +3117,7 @@ var SharedStore = class {
3943
3117
  * Promote a verified troubleshooting entry to shared storage
3944
3118
  */
3945
3119
  async promoteEntry(input) {
3946
- const entryId = randomUUID3();
3120
+ const entryId = randomUUID2();
3947
3121
  await dbRun(
3948
3122
  this.db,
3949
3123
  `INSERT INTO shared_troubleshooting (
@@ -4308,7 +3482,7 @@ function createSharedVectorStore(dbPath) {
4308
3482
  }
4309
3483
 
4310
3484
  // src/core/shared-promoter.ts
4311
- import { randomUUID as randomUUID4 } from "crypto";
3485
+ import { randomUUID as randomUUID3 } from "crypto";
4312
3486
  var SharedPromoter = class {
4313
3487
  constructor(sharedStore, sharedVectorStore, embedder, config) {
4314
3488
  this.sharedStore = sharedStore;
@@ -4376,7 +3550,7 @@ var SharedPromoter = class {
4376
3550
  const embeddingContent = this.createEmbeddingContent(input);
4377
3551
  const embedding = await this.embedder.embed(embeddingContent);
4378
3552
  await this.sharedVectorStore.upsert({
4379
- id: randomUUID4(),
3553
+ id: randomUUID3(),
4380
3554
  entryId,
4381
3555
  entryType: "troubleshooting",
4382
3556
  content: embeddingContent,
@@ -4516,7 +3690,7 @@ function createToolObservationEmbedding(toolName, metadata, success) {
4516
3690
  }
4517
3691
 
4518
3692
  // src/core/working-set-store.ts
4519
- import { randomUUID as randomUUID5 } from "crypto";
3693
+ import { randomUUID as randomUUID4 } from "crypto";
4520
3694
  var WorkingSetStore = class {
4521
3695
  constructor(eventStore, config) {
4522
3696
  this.eventStore = eventStore;
@@ -4537,7 +3711,7 @@ var WorkingSetStore = class {
4537
3711
  `INSERT OR REPLACE INTO working_set (id, event_id, added_at, relevance_score, topics, expires_at)
4538
3712
  VALUES (?, ?, CURRENT_TIMESTAMP, ?, ?, ?)`,
4539
3713
  [
4540
- randomUUID5(),
3714
+ randomUUID4(),
4541
3715
  eventId,
4542
3716
  relevanceScore,
4543
3717
  JSON.stringify(topics || []),
@@ -4721,7 +3895,7 @@ function createWorkingSetStore(eventStore, config) {
4721
3895
  }
4722
3896
 
4723
3897
  // src/core/consolidated-store.ts
4724
- import { randomUUID as randomUUID6 } from "crypto";
3898
+ import { randomUUID as randomUUID5 } from "crypto";
4725
3899
  var ConsolidatedStore = class {
4726
3900
  constructor(eventStore) {
4727
3901
  this.eventStore = eventStore;
@@ -4733,7 +3907,7 @@ var ConsolidatedStore = class {
4733
3907
  * Create a new consolidated memory
4734
3908
  */
4735
3909
  async create(input) {
4736
- const memoryId = randomUUID6();
3910
+ const memoryId = randomUUID5();
4737
3911
  await dbRun(
4738
3912
  this.db,
4739
3913
  `INSERT INTO consolidated_memories
@@ -4863,7 +4037,7 @@ var ConsolidatedStore = class {
4863
4037
  * Create a long-term rule promoted from stable summaries
4864
4038
  */
4865
4039
  async createRule(input) {
4866
- const ruleId = randomUUID6();
4040
+ const ruleId = randomUUID5();
4867
4041
  await dbRun(
4868
4042
  this.db,
4869
4043
  `INSERT INTO consolidated_rules
@@ -5385,7 +4559,7 @@ function createConsolidationWorker(workingSetStore, consolidatedStore, config) {
5385
4559
  }
5386
4560
 
5387
4561
  // src/core/continuity-manager.ts
5388
- import { randomUUID as randomUUID7 } from "crypto";
4562
+ import { randomUUID as randomUUID6 } from "crypto";
5389
4563
  var ContinuityManager = class {
5390
4564
  constructor(eventStore, config) {
5391
4565
  this.eventStore = eventStore;
@@ -5539,7 +4713,7 @@ var ContinuityManager = class {
5539
4713
  `INSERT INTO continuity_log
5540
4714
  (log_id, from_context_id, to_context_id, continuity_score, transition_type, created_at)
5541
4715
  VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
5542
- [randomUUID7(), previous.id, current.id, score, type]
4716
+ [randomUUID6(), previous.id, current.id, score, type]
5543
4717
  );
5544
4718
  }
5545
4719
  /**
@@ -5648,7 +4822,7 @@ function createContinuityManager(eventStore, config) {
5648
4822
  }
5649
4823
 
5650
4824
  // src/core/graduation-worker.ts
5651
- var DEFAULT_CONFIG5 = {
4825
+ var DEFAULT_CONFIG4 = {
5652
4826
  evaluationIntervalMs: 3e5,
5653
4827
  // 5 minutes
5654
4828
  batchSize: 50,
@@ -5656,7 +4830,7 @@ var DEFAULT_CONFIG5 = {
5656
4830
  // 1 hour cooldown between evaluations
5657
4831
  };
5658
4832
  var GraduationWorker = class {
5659
- constructor(eventStore, graduation, config = DEFAULT_CONFIG5) {
4833
+ constructor(eventStore, graduation, config = DEFAULT_CONFIG4) {
5660
4834
  this.eventStore = eventStore;
5661
4835
  this.graduation = graduation;
5662
4836
  this.config = config;
@@ -5764,7 +4938,7 @@ function createGraduationWorker(eventStore, graduation, config) {
5764
4938
  return new GraduationWorker(
5765
4939
  eventStore,
5766
4940
  graduation,
5767
- { ...DEFAULT_CONFIG5, ...config }
4941
+ { ...DEFAULT_CONFIG4, ...config }
5768
4942
  );
5769
4943
  }
5770
4944
 
@@ -5973,9 +5147,6 @@ function loadSessionRegistry() {
5973
5147
  var MemoryService = class {
5974
5148
  // Primary store: SQLite (WAL mode) - for hooks, always available
5975
5149
  sqliteStore;
5976
- // Analytics store: DuckDB - for server reads (optional, synced from SQLite)
5977
- analyticsStore;
5978
- syncWorker = null;
5979
5150
  vectorStore;
5980
5151
  embedder;
5981
5152
  matcher;
@@ -6024,24 +5195,6 @@ var MemoryService = class {
6024
5195
  markdownMirrorRoot: storagePath
6025
5196
  }
6026
5197
  );
6027
- const analyticsEnabled = config.analyticsEnabled ?? this.readOnly;
6028
- if (!analyticsEnabled) {
6029
- this.analyticsStore = null;
6030
- } else if (this.readOnly) {
6031
- try {
6032
- this.analyticsStore = new EventStore(
6033
- path3.join(storagePath, "analytics.duckdb"),
6034
- { readOnly: true }
6035
- );
6036
- } catch {
6037
- this.analyticsStore = null;
6038
- }
6039
- } else {
6040
- this.analyticsStore = new EventStore(
6041
- path3.join(storagePath, "analytics.duckdb"),
6042
- { readOnly: false }
6043
- );
6044
- }
6045
5198
  this.vectorStore = new VectorStore(path3.join(storagePath, "vectors"));
6046
5199
  const embeddingModel = config.embeddingModel || process.env.CLAUDE_MEMORY_EMBEDDING_MODEL;
6047
5200
  this.embedder = embeddingModel ? new Embedder(embeddingModel) : getDefaultEmbedder();
@@ -6067,13 +5220,6 @@ var MemoryService = class {
6067
5220
  this.initialized = true;
6068
5221
  return;
6069
5222
  }
6070
- if (this.analyticsStore) {
6071
- try {
6072
- await this.analyticsStore.initialize();
6073
- } catch (error) {
6074
- console.warn("[MemoryService] Analytics store (DuckDB) initialization failed, using SQLite for reads:", error);
6075
- }
6076
- }
6077
5223
  await this.vectorStore.initialize();
6078
5224
  await this.embedder.initialize();
6079
5225
  if (!this.readOnly) {
@@ -6090,14 +5236,6 @@ var MemoryService = class {
6090
5236
  this.graduation
6091
5237
  );
6092
5238
  this.graduationWorker.start();
6093
- if (this.analyticsStore) {
6094
- this.syncWorker = new SyncWorker(
6095
- this.sqliteStore,
6096
- this.analyticsStore,
6097
- { intervalMs: 3e4, batchSize: 500 }
6098
- );
6099
- this.syncWorker.start();
6100
- }
6101
5239
  }
6102
5240
  const savedMode = await this.sqliteStore.getEndlessConfig("mode");
6103
5241
  if (savedMode === "endless") {
@@ -6294,6 +5432,57 @@ var MemoryService = class {
6294
5432
  }
6295
5433
  );
6296
5434
  }
5435
+ /**
5436
+ * Backfill session summaries for recent sessions that are missing them.
5437
+ * Called from session-start hook to catch sessions that ended without Stop hook.
5438
+ */
5439
+ async backfillMissingSummaries(currentSessionId, limit = 5) {
5440
+ await this.initialize();
5441
+ const recentSessionIds = await this.sqliteStore.getSessionsWithoutSummary(currentSessionId, limit);
5442
+ for (const sid of recentSessionIds) {
5443
+ try {
5444
+ await this.generateSessionSummary(sid);
5445
+ } catch {
5446
+ }
5447
+ }
5448
+ }
5449
+ /**
5450
+ * Generate a rule-based session summary from stored events.
5451
+ * Called at session end (Stop hook) when no LLM-generated summary exists.
5452
+ * Skips if a summary already exists for this session.
5453
+ */
5454
+ async generateSessionSummary(sessionId) {
5455
+ await this.initialize();
5456
+ const events = await this.sqliteStore.getSessionEvents(sessionId);
5457
+ if (events.length < 3)
5458
+ return;
5459
+ const hasSummary = events.some((e) => e.eventType === "session_summary");
5460
+ if (hasSummary)
5461
+ return;
5462
+ const prompts = events.filter((e) => e.eventType === "user_prompt");
5463
+ const toolObs = events.filter((e) => e.eventType === "tool_observation");
5464
+ const toolNames = [...new Set(
5465
+ toolObs.map((e) => e.metadata?.toolName).filter(Boolean)
5466
+ )];
5467
+ const errorObs = toolObs.filter((e) => {
5468
+ const meta = e.metadata;
5469
+ return meta?.exitCode !== void 0 && meta.exitCode !== 0;
5470
+ });
5471
+ const datePart = events[0].timestamp.toISOString().split("T")[0];
5472
+ const parts = [`[${datePart}] ${prompts.length}\uD134 \uC138\uC158.`];
5473
+ if (prompts.length > 0) {
5474
+ const firstPrompt = prompts[0].content.slice(0, 120).replace(/\n/g, " ");
5475
+ parts.push(`\uC8FC\uC694 \uC791\uC5C5: ${firstPrompt}`);
5476
+ }
5477
+ if (toolNames.length > 0) {
5478
+ parts.push(`\uC0AC\uC6A9 \uD234: ${toolNames.slice(0, 6).join(", ")}`);
5479
+ }
5480
+ if (errorObs.length > 0) {
5481
+ parts.push(`\uC624\uB958 ${errorObs.length}\uAC74 \uBC1C\uC0DD`);
5482
+ }
5483
+ const summary = parts.join(". ");
5484
+ await this.storeSessionSummary(sessionId, summary, { generated: "rule-based", eventCount: events.length });
5485
+ }
6297
5486
  /**
6298
5487
  * Store a tool observation
6299
5488
  */
@@ -6829,6 +6018,7 @@ var MemoryService = class {
6829
6018
  await this.initialize();
6830
6019
  await this.sqliteStore.recordRetrievalTrace({
6831
6020
  ...input,
6021
+ projectHash: this.projectHash || void 0,
6832
6022
  candidateDetails: [],
6833
6023
  selectedDetails: [],
6834
6024
  fallbackTrace: []
@@ -7119,16 +6309,10 @@ var MemoryService = class {
7119
6309
  if (this.vectorWorker) {
7120
6310
  this.vectorWorker.stop();
7121
6311
  }
7122
- if (this.syncWorker) {
7123
- this.syncWorker.stop();
7124
- }
7125
6312
  if (this.sharedEventStore) {
7126
6313
  await this.sharedEventStore.close();
7127
6314
  }
7128
6315
  await this.sqliteStore.close();
7129
- if (this.analyticsStore) {
7130
- await this.analyticsStore.close();
7131
- }
7132
6316
  }
7133
6317
  /**
7134
6318
  * Expand ~ to home directory
@@ -7170,7 +6354,7 @@ function getMemoryServiceForProject(projectPath, sharedStoreConfig) {
7170
6354
 
7171
6355
  // src/server/api/utils.ts
7172
6356
  function getServiceFromQuery(c) {
7173
- const project = c.req.query("project");
6357
+ const project = c.req.query("project") || c.req.query("projectId");
7174
6358
  if (project) {
7175
6359
  const isHash = /^[a-f0-9]{8}$/.test(project);
7176
6360
  let storagePath;