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
@@ -28,744 +28,31 @@ import * as os from "os";
28
28
  import * as fs4 from "fs";
29
29
  import * as crypto2 from "crypto";
30
30
 
31
- // src/core/event-store.ts
32
- import { randomUUID } from "crypto";
33
-
34
- // src/core/canonical-key.ts
35
- import { createHash } from "crypto";
36
- var MAX_KEY_LENGTH = 200;
37
- function makeCanonicalKey(title, context) {
38
- let normalized = title.normalize("NFKC");
39
- normalized = normalized.toLowerCase();
40
- normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, "");
41
- normalized = normalized.replace(/\s+/g, " ").trim();
42
- let key = normalized;
43
- if (context?.project) {
44
- key = `${context.project}::${key}`;
45
- }
46
- if (key.length > MAX_KEY_LENGTH) {
47
- const hashSuffix = createHash("md5").update(key).digest("hex").slice(0, 8);
48
- key = key.slice(0, MAX_KEY_LENGTH - 9) + "_" + hashSuffix;
49
- }
50
- return key;
51
- }
52
- function makeDedupeKey(content, sessionId) {
53
- const contentHash = createHash("sha256").update(content).digest("hex");
54
- return `${sessionId}:${contentHash}`;
55
- }
56
-
57
- // src/core/db-wrapper.ts
58
- import duckdb from "duckdb";
59
- function convertBigInts(obj) {
60
- if (obj === null || obj === void 0)
61
- return obj;
62
- if (typeof obj === "bigint")
63
- return Number(obj);
64
- if (obj instanceof Date)
65
- return obj;
66
- if (Array.isArray(obj))
67
- return obj.map(convertBigInts);
68
- if (typeof obj === "object") {
69
- const result = {};
70
- for (const [key, value] of Object.entries(obj)) {
71
- result[key] = convertBigInts(value);
72
- }
73
- return result;
74
- }
75
- return obj;
76
- }
77
- function toDate(value) {
78
- if (value instanceof Date)
79
- return value;
80
- if (typeof value === "string")
81
- return new Date(value);
82
- if (typeof value === "number")
83
- return new Date(value);
84
- return new Date(String(value));
85
- }
86
- function createDatabase(path7, options) {
87
- if (options?.readOnly) {
88
- return new duckdb.Database(path7, { access_mode: "READ_ONLY" });
89
- }
90
- return new duckdb.Database(path7);
91
- }
92
- function dbRun(db, sql, params = []) {
93
- return new Promise((resolve3, reject) => {
94
- if (params.length === 0) {
95
- db.run(sql, (err) => {
96
- if (err)
97
- reject(err);
98
- else
99
- resolve3();
100
- });
101
- } else {
102
- db.run(sql, ...params, (err) => {
103
- if (err)
104
- reject(err);
105
- else
106
- resolve3();
107
- });
108
- }
109
- });
110
- }
111
- function dbAll(db, sql, params = []) {
112
- return new Promise((resolve3, reject) => {
113
- if (params.length === 0) {
114
- db.all(sql, (err, rows) => {
115
- if (err)
116
- reject(err);
117
- else
118
- resolve3(convertBigInts(rows || []));
119
- });
120
- } else {
121
- db.all(sql, ...params, (err, rows) => {
122
- if (err)
123
- reject(err);
124
- else
125
- resolve3(convertBigInts(rows || []));
126
- });
127
- }
128
- });
129
- }
130
- function dbClose(db) {
131
- return new Promise((resolve3, reject) => {
132
- db.close((err) => {
133
- if (err)
134
- reject(err);
135
- else
136
- resolve3();
137
- });
138
- });
139
- }
140
-
141
- // src/core/event-store.ts
142
- var EventStore = class {
143
- constructor(dbPath, options) {
144
- this.dbPath = dbPath;
145
- this.readOnly = options?.readOnly ?? false;
146
- this.db = createDatabase(dbPath, { readOnly: this.readOnly });
147
- }
148
- db;
149
- initialized = false;
150
- readOnly;
151
- /**
152
- * Initialize database schema
153
- */
154
- async initialize() {
155
- if (this.initialized)
156
- return;
157
- if (this.readOnly) {
158
- this.initialized = true;
159
- return;
160
- }
161
- await dbRun(this.db, `
162
- CREATE TABLE IF NOT EXISTS events (
163
- id VARCHAR PRIMARY KEY,
164
- event_type VARCHAR NOT NULL,
165
- session_id VARCHAR NOT NULL,
166
- timestamp TIMESTAMP NOT NULL,
167
- content TEXT NOT NULL,
168
- canonical_key VARCHAR NOT NULL,
169
- dedupe_key VARCHAR UNIQUE,
170
- metadata JSON
171
- )
172
- `);
173
- await dbRun(this.db, `
174
- CREATE TABLE IF NOT EXISTS event_dedup (
175
- dedupe_key VARCHAR PRIMARY KEY,
176
- event_id VARCHAR NOT NULL,
177
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
178
- )
179
- `);
180
- await dbRun(this.db, `
181
- CREATE TABLE IF NOT EXISTS sessions (
182
- id VARCHAR PRIMARY KEY,
183
- started_at TIMESTAMP NOT NULL,
184
- ended_at TIMESTAMP,
185
- project_path VARCHAR,
186
- summary TEXT,
187
- tags JSON
188
- )
189
- `);
190
- await dbRun(this.db, `
191
- CREATE TABLE IF NOT EXISTS insights (
192
- id VARCHAR PRIMARY KEY,
193
- insight_type VARCHAR NOT NULL,
194
- content TEXT NOT NULL,
195
- canonical_key VARCHAR NOT NULL,
196
- confidence FLOAT,
197
- source_events JSON,
198
- created_at TIMESTAMP,
199
- last_updated TIMESTAMP
200
- )
201
- `);
202
- await dbRun(this.db, `
203
- CREATE TABLE IF NOT EXISTS embedding_outbox (
204
- id VARCHAR PRIMARY KEY,
205
- event_id VARCHAR NOT NULL,
206
- content TEXT NOT NULL,
207
- status VARCHAR DEFAULT 'pending',
208
- retry_count INT DEFAULT 0,
209
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
210
- processed_at TIMESTAMP,
211
- error_message TEXT
212
- )
213
- `);
214
- await dbRun(this.db, `
215
- CREATE TABLE IF NOT EXISTS projection_offsets (
216
- projection_name VARCHAR PRIMARY KEY,
217
- last_event_id VARCHAR,
218
- last_timestamp TIMESTAMP,
219
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
220
- )
221
- `);
222
- await dbRun(this.db, `
223
- CREATE TABLE IF NOT EXISTS memory_levels (
224
- event_id VARCHAR PRIMARY KEY,
225
- level VARCHAR NOT NULL DEFAULT 'L0',
226
- promoted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
227
- )
228
- `);
229
- await dbRun(this.db, `
230
- CREATE TABLE IF NOT EXISTS entries (
231
- entry_id VARCHAR PRIMARY KEY,
232
- created_ts TIMESTAMP NOT NULL,
233
- entry_type VARCHAR NOT NULL,
234
- title VARCHAR NOT NULL,
235
- content_json JSON NOT NULL,
236
- stage VARCHAR NOT NULL DEFAULT 'raw',
237
- status VARCHAR DEFAULT 'active',
238
- superseded_by VARCHAR,
239
- build_id VARCHAR,
240
- evidence_json JSON,
241
- canonical_key VARCHAR,
242
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
243
- )
244
- `);
245
- await dbRun(this.db, `
246
- CREATE TABLE IF NOT EXISTS entities (
247
- entity_id VARCHAR PRIMARY KEY,
248
- entity_type VARCHAR NOT NULL,
249
- canonical_key VARCHAR NOT NULL,
250
- title VARCHAR NOT NULL,
251
- stage VARCHAR NOT NULL DEFAULT 'raw',
252
- status VARCHAR NOT NULL DEFAULT 'active',
253
- current_json JSON NOT NULL,
254
- title_norm VARCHAR,
255
- search_text VARCHAR,
256
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
257
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
258
- )
259
- `);
260
- await dbRun(this.db, `
261
- CREATE TABLE IF NOT EXISTS entity_aliases (
262
- entity_type VARCHAR NOT NULL,
263
- canonical_key VARCHAR NOT NULL,
264
- entity_id VARCHAR NOT NULL,
265
- is_primary BOOLEAN DEFAULT FALSE,
266
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
267
- PRIMARY KEY(entity_type, canonical_key)
268
- )
269
- `);
270
- await dbRun(this.db, `
271
- CREATE TABLE IF NOT EXISTS edges (
272
- edge_id VARCHAR PRIMARY KEY,
273
- src_type VARCHAR NOT NULL,
274
- src_id VARCHAR NOT NULL,
275
- rel_type VARCHAR NOT NULL,
276
- dst_type VARCHAR NOT NULL,
277
- dst_id VARCHAR NOT NULL,
278
- meta_json JSON,
279
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
280
- )
281
- `);
282
- await dbRun(this.db, `
283
- CREATE TABLE IF NOT EXISTS vector_outbox (
284
- job_id VARCHAR PRIMARY KEY,
285
- item_kind VARCHAR NOT NULL,
286
- item_id VARCHAR NOT NULL,
287
- embedding_version VARCHAR NOT NULL,
288
- status VARCHAR NOT NULL DEFAULT 'pending',
289
- retry_count INT DEFAULT 0,
290
- error VARCHAR,
291
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
292
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
293
- UNIQUE(item_kind, item_id, embedding_version)
294
- )
295
- `);
296
- await dbRun(this.db, `
297
- CREATE TABLE IF NOT EXISTS build_runs (
298
- build_id VARCHAR PRIMARY KEY,
299
- started_at TIMESTAMP NOT NULL,
300
- finished_at TIMESTAMP,
301
- extractor_model VARCHAR NOT NULL,
302
- extractor_prompt_hash VARCHAR NOT NULL,
303
- embedder_model VARCHAR NOT NULL,
304
- embedding_version VARCHAR NOT NULL,
305
- idris_version VARCHAR NOT NULL,
306
- schema_version VARCHAR NOT NULL,
307
- status VARCHAR NOT NULL DEFAULT 'running',
308
- error VARCHAR
309
- )
310
- `);
311
- await dbRun(this.db, `
312
- CREATE TABLE IF NOT EXISTS pipeline_metrics (
313
- id VARCHAR PRIMARY KEY,
314
- ts TIMESTAMP NOT NULL,
315
- stage VARCHAR NOT NULL,
316
- latency_ms DOUBLE NOT NULL,
317
- success BOOLEAN NOT NULL,
318
- error VARCHAR,
319
- session_id VARCHAR
320
- )
321
- `);
322
- await dbRun(this.db, `
323
- CREATE TABLE IF NOT EXISTS working_set (
324
- id VARCHAR PRIMARY KEY,
325
- event_id VARCHAR NOT NULL,
326
- added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
327
- relevance_score FLOAT DEFAULT 1.0,
328
- topics JSON,
329
- expires_at TIMESTAMP
330
- )
331
- `);
332
- await dbRun(this.db, `
333
- CREATE TABLE IF NOT EXISTS consolidated_memories (
334
- memory_id VARCHAR PRIMARY KEY,
335
- summary TEXT NOT NULL,
336
- topics JSON,
337
- source_events JSON,
338
- confidence FLOAT DEFAULT 0.5,
339
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
340
- accessed_at TIMESTAMP,
341
- access_count INTEGER DEFAULT 0
342
- )
343
- `);
344
- await dbRun(this.db, `
345
- CREATE TABLE IF NOT EXISTS continuity_log (
346
- log_id VARCHAR PRIMARY KEY,
347
- from_context_id VARCHAR,
348
- to_context_id VARCHAR,
349
- continuity_score FLOAT,
350
- transition_type VARCHAR,
351
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
352
- )
353
- `);
354
- await dbRun(this.db, `
355
- CREATE TABLE IF NOT EXISTS consolidated_rules (
356
- rule_id VARCHAR PRIMARY KEY,
357
- rule TEXT NOT NULL,
358
- topics JSON,
359
- source_memory_ids JSON,
360
- source_events JSON,
361
- confidence FLOAT DEFAULT 0.5,
362
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
363
- )
364
- `);
365
- await dbRun(this.db, `
366
- CREATE TABLE IF NOT EXISTS endless_config (
367
- key VARCHAR PRIMARY KEY,
368
- value JSON,
369
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
370
- )
371
- `);
372
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_type ON entries(entry_type)`);
373
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_stage ON entries(stage)`);
374
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_canonical ON entries(canonical_key)`);
375
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entities_type_key ON entities(entity_type, canonical_key)`);
376
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entities_status ON entities(status)`);
377
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src_id, rel_type)`);
378
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_dst ON edges(dst_id, rel_type)`);
379
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_rel ON edges(rel_type)`);
380
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_outbox_status ON vector_outbox(status)`);
381
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_expires ON working_set(expires_at)`);
382
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_relevance ON working_set(relevance_score DESC)`);
383
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence DESC)`);
384
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_rules_confidence ON consolidated_rules(confidence DESC)`);
385
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at)`);
386
- this.initialized = true;
387
- }
388
- /**
389
- * Append event to store (AXIOMMIND Principle 2: Append-only)
390
- * Returns existing event ID if duplicate (Principle 3: Idempotency)
391
- */
392
- async append(input) {
393
- await this.initialize();
394
- const canonicalKey = makeCanonicalKey(input.content);
395
- const dedupeKey = makeDedupeKey(input.content, input.sessionId);
396
- const existing = await dbAll(
397
- this.db,
398
- `SELECT event_id FROM event_dedup WHERE dedupe_key = ?`,
399
- [dedupeKey]
400
- );
401
- if (existing.length > 0) {
402
- return {
403
- success: true,
404
- eventId: existing[0].event_id,
405
- isDuplicate: true
406
- };
407
- }
408
- const id = randomUUID();
409
- const timestamp = input.timestamp.toISOString();
410
- try {
411
- await dbRun(
412
- this.db,
413
- `INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
414
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
415
- [
416
- id,
417
- input.eventType,
418
- input.sessionId,
419
- timestamp,
420
- input.content,
421
- canonicalKey,
422
- dedupeKey,
423
- JSON.stringify(input.metadata || {})
424
- ]
425
- );
426
- await dbRun(
427
- this.db,
428
- `INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)`,
429
- [dedupeKey, id]
430
- );
431
- await dbRun(
432
- this.db,
433
- `INSERT INTO memory_levels (event_id, level) VALUES (?, 'L0')`,
434
- [id]
435
- );
436
- return { success: true, eventId: id, isDuplicate: false };
437
- } catch (error) {
438
- return {
439
- success: false,
440
- error: error instanceof Error ? error.message : String(error)
441
- };
442
- }
443
- }
444
- /**
445
- * Get events by session ID
446
- */
447
- async getSessionEvents(sessionId) {
448
- await this.initialize();
449
- const rows = await dbAll(
450
- this.db,
451
- `SELECT * FROM events WHERE session_id = ? ORDER BY timestamp ASC`,
452
- [sessionId]
453
- );
454
- return rows.map(this.rowToEvent);
455
- }
456
- /**
457
- * Get recent events
458
- */
459
- async getRecentEvents(limit = 100) {
460
- await this.initialize();
461
- const rows = await dbAll(
462
- this.db,
463
- `SELECT * FROM events ORDER BY timestamp DESC LIMIT ?`,
464
- [limit]
465
- );
466
- return rows.map(this.rowToEvent);
467
- }
468
- /**
469
- * Get event by ID
470
- */
471
- async getEvent(id) {
472
- await this.initialize();
473
- const rows = await dbAll(
474
- this.db,
475
- `SELECT * FROM events WHERE id = ?`,
476
- [id]
477
- );
478
- if (rows.length === 0)
479
- return null;
480
- return this.rowToEvent(rows[0]);
481
- }
482
- /**
483
- * Create or update session
484
- */
485
- async upsertSession(session) {
486
- await this.initialize();
487
- const existing = await dbAll(
488
- this.db,
489
- `SELECT id FROM sessions WHERE id = ?`,
490
- [session.id]
491
- );
492
- if (existing.length === 0) {
493
- await dbRun(
494
- this.db,
495
- `INSERT INTO sessions (id, started_at, project_path, tags)
496
- VALUES (?, ?, ?, ?)`,
497
- [
498
- session.id,
499
- (session.startedAt || /* @__PURE__ */ new Date()).toISOString(),
500
- session.projectPath || null,
501
- JSON.stringify(session.tags || [])
502
- ]
503
- );
504
- } else {
505
- const updates = [];
506
- const values = [];
507
- if (session.endedAt) {
508
- updates.push("ended_at = ?");
509
- values.push(session.endedAt.toISOString());
510
- }
511
- if (session.summary) {
512
- updates.push("summary = ?");
513
- values.push(session.summary);
514
- }
515
- if (session.tags) {
516
- updates.push("tags = ?");
517
- values.push(JSON.stringify(session.tags));
518
- }
519
- if (updates.length > 0) {
520
- values.push(session.id);
521
- await dbRun(
522
- this.db,
523
- `UPDATE sessions SET ${updates.join(", ")} WHERE id = ?`,
524
- values
525
- );
526
- }
527
- }
528
- }
529
- /**
530
- * Get session by ID
531
- */
532
- async getSession(id) {
533
- await this.initialize();
534
- const rows = await dbAll(
535
- this.db,
536
- `SELECT * FROM sessions WHERE id = ?`,
537
- [id]
538
- );
539
- if (rows.length === 0)
540
- return null;
541
- const row = rows[0];
542
- return {
543
- id: row.id,
544
- startedAt: toDate(row.started_at),
545
- endedAt: row.ended_at ? toDate(row.ended_at) : void 0,
546
- projectPath: row.project_path,
547
- summary: row.summary,
548
- tags: row.tags ? JSON.parse(row.tags) : void 0
549
- };
550
- }
551
- /**
552
- * Add to embedding outbox (Single-Writer Pattern)
553
- */
554
- async enqueueForEmbedding(eventId, content) {
555
- await this.initialize();
556
- const id = randomUUID();
557
- await dbRun(
558
- this.db,
559
- `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
560
- VALUES (?, ?, ?, 'pending', 0)`,
561
- [id, eventId, content]
562
- );
563
- return id;
564
- }
565
- /**
566
- * Get pending outbox items
567
- */
568
- async getPendingOutboxItems(limit = 32) {
569
- await this.initialize();
570
- const pending = await dbAll(
571
- this.db,
572
- `SELECT * FROM embedding_outbox
573
- WHERE status = 'pending'
574
- ORDER BY created_at
575
- LIMIT ?`,
576
- [limit]
577
- );
578
- if (pending.length === 0)
579
- return [];
580
- const ids = pending.map((r) => r.id);
581
- const placeholders = ids.map(() => "?").join(",");
582
- await dbRun(
583
- this.db,
584
- `UPDATE embedding_outbox SET status = 'processing' WHERE id IN (${placeholders})`,
585
- ids
586
- );
587
- return pending.map((row) => ({
588
- id: row.id,
589
- eventId: row.event_id,
590
- content: row.content,
591
- status: "processing",
592
- retryCount: row.retry_count,
593
- createdAt: toDate(row.created_at),
594
- errorMessage: row.error_message
595
- }));
596
- }
597
- /**
598
- * Mark outbox items as done
599
- */
600
- async completeOutboxItems(ids) {
601
- if (ids.length === 0)
602
- return;
603
- const placeholders = ids.map(() => "?").join(",");
604
- await dbRun(
605
- this.db,
606
- `DELETE FROM embedding_outbox WHERE id IN (${placeholders})`,
607
- ids
608
- );
609
- }
610
- /**
611
- * Mark outbox items as failed
612
- */
613
- async failOutboxItems(ids, error) {
614
- if (ids.length === 0)
615
- return;
616
- const placeholders = ids.map(() => "?").join(",");
617
- await dbRun(
618
- this.db,
619
- `UPDATE embedding_outbox
620
- SET status = CASE WHEN retry_count >= 3 THEN 'failed' ELSE 'pending' END,
621
- retry_count = retry_count + 1,
622
- error_message = ?
623
- WHERE id IN (${placeholders})`,
624
- [error, ...ids]
625
- );
626
- }
627
- /**
628
- * Update memory level
629
- */
630
- async updateMemoryLevel(eventId, level) {
631
- await this.initialize();
632
- await dbRun(
633
- this.db,
634
- `UPDATE memory_levels SET level = ?, promoted_at = CURRENT_TIMESTAMP WHERE event_id = ?`,
635
- [level, eventId]
636
- );
637
- }
638
- /**
639
- * Get memory level statistics
640
- */
641
- async getLevelStats() {
642
- await this.initialize();
643
- const rows = await dbAll(
644
- this.db,
645
- `SELECT level, COUNT(*) as count FROM memory_levels GROUP BY level`
646
- );
647
- return rows;
648
- }
649
- /**
650
- * Get events by memory level
651
- */
652
- async getEventsByLevel(level, options) {
653
- await this.initialize();
654
- const limit = options?.limit || 50;
655
- const offset = options?.offset || 0;
656
- const rows = await dbAll(
657
- this.db,
658
- `SELECT e.* FROM events e
659
- INNER JOIN memory_levels ml ON e.id = ml.event_id
660
- WHERE ml.level = ?
661
- ORDER BY e.timestamp DESC
662
- LIMIT ? OFFSET ?`,
663
- [level, limit, offset]
664
- );
665
- return rows.map((row) => this.rowToEvent(row));
666
- }
667
- /**
668
- * Get memory level for a specific event
669
- */
670
- async getEventLevel(eventId) {
671
- await this.initialize();
672
- const rows = await dbAll(
673
- this.db,
674
- `SELECT level FROM memory_levels WHERE event_id = ?`,
675
- [eventId]
676
- );
677
- return rows.length > 0 ? rows[0].level : null;
678
- }
679
- // ============================================================
680
- // Endless Mode Helper Methods
681
- // ============================================================
682
- /**
683
- * Get database instance for Endless Mode stores
684
- */
685
- getDatabase() {
686
- return this.db;
687
- }
688
- /**
689
- * Get config value for endless mode
690
- */
691
- async getEndlessConfig(key) {
692
- await this.initialize();
693
- const rows = await dbAll(
694
- this.db,
695
- `SELECT value FROM endless_config WHERE key = ?`,
696
- [key]
697
- );
698
- if (rows.length === 0)
699
- return null;
700
- return JSON.parse(rows[0].value);
701
- }
702
- /**
703
- * Set config value for endless mode
704
- */
705
- async setEndlessConfig(key, value) {
706
- await this.initialize();
707
- await dbRun(
708
- this.db,
709
- `INSERT OR REPLACE INTO endless_config (key, value, updated_at)
710
- VALUES (?, ?, CURRENT_TIMESTAMP)`,
711
- [key, JSON.stringify(value)]
712
- );
713
- }
714
- /**
715
- * Get all sessions
716
- */
717
- async getAllSessions() {
718
- await this.initialize();
719
- const rows = await dbAll(
720
- this.db,
721
- `SELECT * FROM sessions ORDER BY started_at DESC`
722
- );
723
- return rows.map((row) => ({
724
- id: row.id,
725
- startedAt: toDate(row.started_at),
726
- endedAt: row.ended_at ? toDate(row.ended_at) : void 0,
727
- projectPath: row.project_path,
728
- summary: row.summary,
729
- tags: row.tags ? JSON.parse(row.tags) : void 0
730
- }));
731
- }
732
- /**
733
- * Increment access count for events (stub for compatibility)
734
- */
735
- async incrementAccessCount(eventIds) {
736
- return Promise.resolve();
737
- }
738
- /**
739
- * Get most accessed memories (stub for compatibility)
740
- */
741
- async getMostAccessed(limit = 10) {
742
- return [];
743
- }
744
- /**
745
- * Close database connection
746
- */
747
- async close() {
748
- await dbClose(this.db);
31
+ // src/core/sqlite-event-store.ts
32
+ import { randomUUID } from "crypto";
33
+
34
+ // src/core/canonical-key.ts
35
+ import { createHash } from "crypto";
36
+ var MAX_KEY_LENGTH = 200;
37
+ function makeCanonicalKey(title, context) {
38
+ let normalized = title.normalize("NFKC");
39
+ normalized = normalized.toLowerCase();
40
+ normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, "");
41
+ normalized = normalized.replace(/\s+/g, " ").trim();
42
+ let key = normalized;
43
+ if (context?.project) {
44
+ key = `${context.project}::${key}`;
749
45
  }
750
- /**
751
- * Convert database row to MemoryEvent
752
- */
753
- rowToEvent(row) {
754
- return {
755
- id: row.id,
756
- eventType: row.event_type,
757
- sessionId: row.session_id,
758
- timestamp: toDate(row.timestamp),
759
- content: row.content,
760
- canonicalKey: row.canonical_key,
761
- dedupeKey: row.dedupe_key,
762
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0
763
- };
46
+ if (key.length > MAX_KEY_LENGTH) {
47
+ const hashSuffix = createHash("md5").update(key).digest("hex").slice(0, 8);
48
+ key = key.slice(0, MAX_KEY_LENGTH - 9) + "_" + hashSuffix;
764
49
  }
765
- };
766
-
767
- // src/core/sqlite-event-store.ts
768
- import { randomUUID as randomUUID2 } from "crypto";
50
+ return key;
51
+ }
52
+ function makeDedupeKey(content, sessionId) {
53
+ const contentHash = createHash("sha256").update(content).digest("hex");
54
+ return `${sessionId}:${contentHash}`;
55
+ }
769
56
 
770
57
  // src/core/sqlite-wrapper.ts
771
58
  import Database from "better-sqlite3";
@@ -1280,7 +567,7 @@ var SQLiteEventStore = class {
1280
567
  isDuplicate: true
1281
568
  };
1282
569
  }
1283
- const id = randomUUID2();
570
+ const id = randomUUID();
1284
571
  const timestamp = toSQLiteTimestamp(input.timestamp);
1285
572
  try {
1286
573
  const metadata = input.metadata || {};
@@ -1334,6 +621,29 @@ var SQLiteEventStore = class {
1334
621
  };
1335
622
  }
1336
623
  }
624
+ /**
625
+ * Get session IDs that have events but no session_summary event.
626
+ * Used to backfill summaries for sessions that ended without Stop hook.
627
+ */
628
+ async getSessionsWithoutSummary(currentSessionId, limit = 5) {
629
+ await this.initialize();
630
+ const rows = sqliteAll(
631
+ this.db,
632
+ `SELECT DISTINCT e.session_id
633
+ FROM events e
634
+ WHERE e.session_id != ?
635
+ AND e.event_type != 'session_summary'
636
+ AND e.session_id NOT IN (
637
+ SELECT DISTINCT session_id FROM events WHERE event_type = 'session_summary'
638
+ )
639
+ GROUP BY e.session_id
640
+ HAVING COUNT(*) >= 3
641
+ ORDER BY MAX(e.timestamp) DESC
642
+ LIMIT ?`,
643
+ [currentSessionId, limit]
644
+ );
645
+ return rows.map((r) => r.session_id);
646
+ }
1337
647
  /**
1338
648
  * Get events by session ID
1339
649
  */
@@ -1561,7 +871,7 @@ var SQLiteEventStore = class {
1561
871
  */
1562
872
  async enqueueForEmbedding(eventId, content) {
1563
873
  await this.initialize();
1564
- const id = randomUUID2();
874
+ const id = randomUUID();
1565
875
  sqliteRun(
1566
876
  this.db,
1567
877
  `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
@@ -1842,7 +1152,7 @@ var SQLiteEventStore = class {
1842
1152
  if (this.readOnly)
1843
1153
  return;
1844
1154
  await this.initialize();
1845
- const id = randomUUID2();
1155
+ const id = randomUUID();
1846
1156
  sqliteRun(
1847
1157
  this.db,
1848
1158
  `INSERT INTO memory_helpfulness (id, event_id, session_id, retrieval_score, query_preview, created_at)
@@ -1920,7 +1230,8 @@ var SQLiteEventStore = class {
1920
1230
  }
1921
1231
  }
1922
1232
  const retrievalScore = retrieval.retrieval_score || 0;
1923
- const helpfulnessScore = 0.3 * Math.min(retrievalScore, 1) + 0.25 * (sessionContinued ? 1 : 0) + 0.25 * toolSuccessRatio + 0.2 * (wasReasked ? 0 : 1);
1233
+ const promptNorm = Math.min(promptCountAfter / 2, 1);
1234
+ const helpfulnessScore = 0.4 * Math.min(retrievalScore, 1) + 0.3 * promptNorm + 0.2 * toolSuccessRatio + 0.1 * (sessionContinued ? 1 : 0);
1924
1235
  sqliteRun(
1925
1236
  this.db,
1926
1237
  `UPDATE memory_helpfulness
@@ -2063,7 +1374,7 @@ var SQLiteEventStore = class {
2063
1374
  }
2064
1375
  async recordRetrievalTrace(input) {
2065
1376
  await this.initialize();
2066
- const traceId = randomUUID2();
1377
+ const traceId = randomUUID();
2067
1378
  sqliteRun(
2068
1379
  this.db,
2069
1380
  `INSERT INTO retrieval_traces (
@@ -2317,169 +1628,6 @@ var SQLiteEventStore = class {
2317
1628
  }
2318
1629
  };
2319
1630
 
2320
- // src/core/sync-worker.ts
2321
- var DEFAULT_CONFIG = {
2322
- intervalMs: 3e4,
2323
- batchSize: 500,
2324
- maxRetries: 3,
2325
- retryDelayMs: 5e3
2326
- };
2327
- var SyncWorker = class {
2328
- constructor(sqliteStore, duckdbStore, config) {
2329
- this.sqliteStore = sqliteStore;
2330
- this.duckdbStore = duckdbStore;
2331
- this.config = { ...DEFAULT_CONFIG, ...config };
2332
- }
2333
- config;
2334
- intervalHandle = null;
2335
- running = false;
2336
- stats = {
2337
- lastSyncAt: null,
2338
- eventsSynced: 0,
2339
- sessionsSynced: 0,
2340
- errors: 0,
2341
- status: "idle"
2342
- };
2343
- /**
2344
- * Start the sync worker
2345
- */
2346
- start() {
2347
- if (this.running)
2348
- return;
2349
- this.running = true;
2350
- this.stats.status = "idle";
2351
- this.syncNow().catch((err) => {
2352
- console.error("[SyncWorker] Initial sync failed:", err);
2353
- });
2354
- this.intervalHandle = setInterval(() => {
2355
- this.syncNow().catch((err) => {
2356
- console.error("[SyncWorker] Periodic sync failed:", err);
2357
- });
2358
- }, this.config.intervalMs);
2359
- }
2360
- /**
2361
- * Stop the sync worker
2362
- */
2363
- stop() {
2364
- this.running = false;
2365
- this.stats.status = "stopped";
2366
- if (this.intervalHandle) {
2367
- clearInterval(this.intervalHandle);
2368
- this.intervalHandle = null;
2369
- }
2370
- }
2371
- /**
2372
- * Trigger immediate sync
2373
- */
2374
- async syncNow() {
2375
- if (this.stats.status === "syncing") {
2376
- return;
2377
- }
2378
- this.stats.status = "syncing";
2379
- try {
2380
- await this.syncEvents();
2381
- await this.syncSessions();
2382
- this.stats.lastSyncAt = /* @__PURE__ */ new Date();
2383
- this.stats.status = "idle";
2384
- } catch (error) {
2385
- this.stats.errors++;
2386
- this.stats.status = "error";
2387
- throw error;
2388
- }
2389
- }
2390
- /**
2391
- * Sync events from SQLite to DuckDB
2392
- */
2393
- async syncEvents() {
2394
- const targetName = "duckdb_analytics";
2395
- const position = await this.sqliteStore.getSyncPosition(targetName);
2396
- const lastTimestamp = position.lastTimestamp || "1970-01-01T00:00:00.000Z";
2397
- let hasMore = true;
2398
- let totalSynced = 0;
2399
- while (hasMore) {
2400
- const events = await this.sqliteStore.getEventsSince(lastTimestamp, this.config.batchSize);
2401
- if (events.length === 0) {
2402
- hasMore = false;
2403
- break;
2404
- }
2405
- await this.retryWithBackoff(async () => {
2406
- for (const event of events) {
2407
- await this.insertEventToDuckDB(event);
2408
- }
2409
- });
2410
- totalSynced += events.length;
2411
- const lastEvent = events[events.length - 1];
2412
- await this.sqliteStore.updateSyncPosition(
2413
- targetName,
2414
- lastEvent.id,
2415
- lastEvent.timestamp.toISOString()
2416
- );
2417
- hasMore = events.length === this.config.batchSize;
2418
- }
2419
- this.stats.eventsSynced += totalSynced;
2420
- }
2421
- /**
2422
- * Sync sessions from SQLite to DuckDB
2423
- */
2424
- async syncSessions() {
2425
- const sessions = await this.sqliteStore.getAllSessions();
2426
- for (const session of sessions) {
2427
- await this.retryWithBackoff(async () => {
2428
- await this.duckdbStore.upsertSession(session);
2429
- });
2430
- }
2431
- this.stats.sessionsSynced = sessions.length;
2432
- }
2433
- /**
2434
- * Insert a single event into DuckDB
2435
- */
2436
- async insertEventToDuckDB(event) {
2437
- await this.duckdbStore.append({
2438
- eventType: event.eventType,
2439
- sessionId: event.sessionId,
2440
- timestamp: event.timestamp,
2441
- content: event.content,
2442
- metadata: event.metadata
2443
- });
2444
- }
2445
- /**
2446
- * Retry operation with exponential backoff
2447
- */
2448
- async retryWithBackoff(fn) {
2449
- let lastError = null;
2450
- for (let attempt = 0; attempt < this.config.maxRetries; attempt++) {
2451
- try {
2452
- return await fn();
2453
- } catch (error) {
2454
- lastError = error instanceof Error ? error : new Error(String(error));
2455
- if (attempt < this.config.maxRetries - 1) {
2456
- const delay = this.config.retryDelayMs * Math.pow(2, attempt);
2457
- await this.sleep(delay);
2458
- }
2459
- }
2460
- }
2461
- throw lastError;
2462
- }
2463
- /**
2464
- * Sleep utility
2465
- */
2466
- sleep(ms) {
2467
- return new Promise((resolve3) => setTimeout(resolve3, ms));
2468
- }
2469
- /**
2470
- * Get sync statistics
2471
- */
2472
- getStats() {
2473
- return { ...this.stats };
2474
- }
2475
- /**
2476
- * Check if worker is running
2477
- */
2478
- isRunning() {
2479
- return this.running;
2480
- }
2481
- };
2482
-
2483
1631
  // src/core/vector-store.ts
2484
1632
  import * as lancedb from "@lancedb/lancedb";
2485
1633
  var VectorStore = class {
@@ -2767,8 +1915,34 @@ function getDefaultEmbedder() {
2767
1915
  return defaultEmbedder;
2768
1916
  }
2769
1917
 
1918
+ // src/core/db-wrapper.ts
1919
+ import BetterSqlite3 from "better-sqlite3";
1920
+ function toDate(value) {
1921
+ if (value instanceof Date)
1922
+ return value;
1923
+ if (typeof value === "string")
1924
+ return new Date(value);
1925
+ if (typeof value === "number")
1926
+ return new Date(value);
1927
+ return new Date(String(value));
1928
+ }
1929
+ function createDatabase(dbPath, options) {
1930
+ return new BetterSqlite3(dbPath, { readonly: options?.readOnly });
1931
+ }
1932
+ function dbRun(db, sql, params = []) {
1933
+ db.prepare(sql).run(...params);
1934
+ return Promise.resolve();
1935
+ }
1936
+ function dbAll(db, sql, params = []) {
1937
+ return Promise.resolve(db.prepare(sql).all(...params));
1938
+ }
1939
+ function dbClose(db) {
1940
+ db.close();
1941
+ return Promise.resolve();
1942
+ }
1943
+
2770
1944
  // src/core/vector-outbox.ts
2771
- var DEFAULT_CONFIG2 = {
1945
+ var DEFAULT_CONFIG = {
2772
1946
  embeddingVersion: "v1",
2773
1947
  maxRetries: 3,
2774
1948
  stuckThresholdMs: 5 * 60 * 1e3,
@@ -2777,7 +1951,7 @@ var DEFAULT_CONFIG2 = {
2777
1951
  };
2778
1952
 
2779
1953
  // src/core/vector-worker.ts
2780
- var DEFAULT_CONFIG3 = {
1954
+ var DEFAULT_CONFIG2 = {
2781
1955
  batchSize: 32,
2782
1956
  pollIntervalMs: 1e3,
2783
1957
  maxRetries: 3
@@ -2794,7 +1968,7 @@ var VectorWorker = class {
2794
1968
  this.eventStore = eventStore;
2795
1969
  this.vectorStore = vectorStore;
2796
1970
  this.embedder = embedder;
2797
- this.config = { ...DEFAULT_CONFIG3, ...config };
1971
+ this.config = { ...DEFAULT_CONFIG2, ...config };
2798
1972
  }
2799
1973
  /**
2800
1974
  * Start the worker polling loop
@@ -2915,7 +2089,7 @@ function createVectorWorker(eventStore, vectorStore, embedder, config) {
2915
2089
  }
2916
2090
 
2917
2091
  // src/core/matcher.ts
2918
- var DEFAULT_CONFIG4 = {
2092
+ var DEFAULT_CONFIG3 = {
2919
2093
  weights: {
2920
2094
  semanticSimilarity: 0.4,
2921
2095
  ftsScore: 0.25,
@@ -2930,9 +2104,9 @@ var Matcher = class {
2930
2104
  config;
2931
2105
  constructor(config = {}) {
2932
2106
  this.config = {
2933
- ...DEFAULT_CONFIG4,
2107
+ ...DEFAULT_CONFIG3,
2934
2108
  ...config,
2935
- weights: { ...DEFAULT_CONFIG4.weights, ...config.weights }
2109
+ weights: { ...DEFAULT_CONFIG3.weights, ...config.weights }
2936
2110
  };
2937
2111
  }
2938
2112
  /**
@@ -3922,7 +3096,7 @@ function createSharedEventStore(dbPath) {
3922
3096
  }
3923
3097
 
3924
3098
  // src/core/shared-store.ts
3925
- import { randomUUID as randomUUID3 } from "crypto";
3099
+ import { randomUUID as randomUUID2 } from "crypto";
3926
3100
  var SharedStore = class {
3927
3101
  constructor(sharedEventStore) {
3928
3102
  this.sharedEventStore = sharedEventStore;
@@ -3934,7 +3108,7 @@ var SharedStore = class {
3934
3108
  * Promote a verified troubleshooting entry to shared storage
3935
3109
  */
3936
3110
  async promoteEntry(input) {
3937
- const entryId = randomUUID3();
3111
+ const entryId = randomUUID2();
3938
3112
  await dbRun(
3939
3113
  this.db,
3940
3114
  `INSERT INTO shared_troubleshooting (
@@ -4299,7 +3473,7 @@ function createSharedVectorStore(dbPath) {
4299
3473
  }
4300
3474
 
4301
3475
  // src/core/shared-promoter.ts
4302
- import { randomUUID as randomUUID4 } from "crypto";
3476
+ import { randomUUID as randomUUID3 } from "crypto";
4303
3477
  var SharedPromoter = class {
4304
3478
  constructor(sharedStore, sharedVectorStore, embedder, config) {
4305
3479
  this.sharedStore = sharedStore;
@@ -4367,7 +3541,7 @@ var SharedPromoter = class {
4367
3541
  const embeddingContent = this.createEmbeddingContent(input);
4368
3542
  const embedding = await this.embedder.embed(embeddingContent);
4369
3543
  await this.sharedVectorStore.upsert({
4370
- id: randomUUID4(),
3544
+ id: randomUUID3(),
4371
3545
  entryId,
4372
3546
  entryType: "troubleshooting",
4373
3547
  content: embeddingContent,
@@ -4507,7 +3681,7 @@ function createToolObservationEmbedding(toolName, metadata, success) {
4507
3681
  }
4508
3682
 
4509
3683
  // src/core/working-set-store.ts
4510
- import { randomUUID as randomUUID5 } from "crypto";
3684
+ import { randomUUID as randomUUID4 } from "crypto";
4511
3685
  var WorkingSetStore = class {
4512
3686
  constructor(eventStore, config) {
4513
3687
  this.eventStore = eventStore;
@@ -4528,7 +3702,7 @@ var WorkingSetStore = class {
4528
3702
  `INSERT OR REPLACE INTO working_set (id, event_id, added_at, relevance_score, topics, expires_at)
4529
3703
  VALUES (?, ?, CURRENT_TIMESTAMP, ?, ?, ?)`,
4530
3704
  [
4531
- randomUUID5(),
3705
+ randomUUID4(),
4532
3706
  eventId,
4533
3707
  relevanceScore,
4534
3708
  JSON.stringify(topics || []),
@@ -4712,7 +3886,7 @@ function createWorkingSetStore(eventStore, config) {
4712
3886
  }
4713
3887
 
4714
3888
  // src/core/consolidated-store.ts
4715
- import { randomUUID as randomUUID6 } from "crypto";
3889
+ import { randomUUID as randomUUID5 } from "crypto";
4716
3890
  var ConsolidatedStore = class {
4717
3891
  constructor(eventStore) {
4718
3892
  this.eventStore = eventStore;
@@ -4724,7 +3898,7 @@ var ConsolidatedStore = class {
4724
3898
  * Create a new consolidated memory
4725
3899
  */
4726
3900
  async create(input) {
4727
- const memoryId = randomUUID6();
3901
+ const memoryId = randomUUID5();
4728
3902
  await dbRun(
4729
3903
  this.db,
4730
3904
  `INSERT INTO consolidated_memories
@@ -4854,7 +4028,7 @@ var ConsolidatedStore = class {
4854
4028
  * Create a long-term rule promoted from stable summaries
4855
4029
  */
4856
4030
  async createRule(input) {
4857
- const ruleId = randomUUID6();
4031
+ const ruleId = randomUUID5();
4858
4032
  await dbRun(
4859
4033
  this.db,
4860
4034
  `INSERT INTO consolidated_rules
@@ -5376,7 +4550,7 @@ function createConsolidationWorker(workingSetStore, consolidatedStore, config) {
5376
4550
  }
5377
4551
 
5378
4552
  // src/core/continuity-manager.ts
5379
- import { randomUUID as randomUUID7 } from "crypto";
4553
+ import { randomUUID as randomUUID6 } from "crypto";
5380
4554
  var ContinuityManager = class {
5381
4555
  constructor(eventStore, config) {
5382
4556
  this.eventStore = eventStore;
@@ -5530,7 +4704,7 @@ var ContinuityManager = class {
5530
4704
  `INSERT INTO continuity_log
5531
4705
  (log_id, from_context_id, to_context_id, continuity_score, transition_type, created_at)
5532
4706
  VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
5533
- [randomUUID7(), previous.id, current.id, score, type]
4707
+ [randomUUID6(), previous.id, current.id, score, type]
5534
4708
  );
5535
4709
  }
5536
4710
  /**
@@ -5639,7 +4813,7 @@ function createContinuityManager(eventStore, config) {
5639
4813
  }
5640
4814
 
5641
4815
  // src/core/graduation-worker.ts
5642
- var DEFAULT_CONFIG5 = {
4816
+ var DEFAULT_CONFIG4 = {
5643
4817
  evaluationIntervalMs: 3e5,
5644
4818
  // 5 minutes
5645
4819
  batchSize: 50,
@@ -5647,7 +4821,7 @@ var DEFAULT_CONFIG5 = {
5647
4821
  // 1 hour cooldown between evaluations
5648
4822
  };
5649
4823
  var GraduationWorker = class {
5650
- constructor(eventStore, graduation, config = DEFAULT_CONFIG5) {
4824
+ constructor(eventStore, graduation, config = DEFAULT_CONFIG4) {
5651
4825
  this.eventStore = eventStore;
5652
4826
  this.graduation = graduation;
5653
4827
  this.config = config;
@@ -5755,7 +4929,7 @@ function createGraduationWorker(eventStore, graduation, config) {
5755
4929
  return new GraduationWorker(
5756
4930
  eventStore,
5757
4931
  graduation,
5758
- { ...DEFAULT_CONFIG5, ...config }
4932
+ { ...DEFAULT_CONFIG4, ...config }
5759
4933
  );
5760
4934
  }
5761
4935
 
@@ -5964,9 +5138,6 @@ function loadSessionRegistry() {
5964
5138
  var MemoryService = class {
5965
5139
  // Primary store: SQLite (WAL mode) - for hooks, always available
5966
5140
  sqliteStore;
5967
- // Analytics store: DuckDB - for server reads (optional, synced from SQLite)
5968
- analyticsStore;
5969
- syncWorker = null;
5970
5141
  vectorStore;
5971
5142
  embedder;
5972
5143
  matcher;
@@ -6015,24 +5186,6 @@ var MemoryService = class {
6015
5186
  markdownMirrorRoot: storagePath
6016
5187
  }
6017
5188
  );
6018
- const analyticsEnabled = config.analyticsEnabled ?? this.readOnly;
6019
- if (!analyticsEnabled) {
6020
- this.analyticsStore = null;
6021
- } else if (this.readOnly) {
6022
- try {
6023
- this.analyticsStore = new EventStore(
6024
- path3.join(storagePath, "analytics.duckdb"),
6025
- { readOnly: true }
6026
- );
6027
- } catch {
6028
- this.analyticsStore = null;
6029
- }
6030
- } else {
6031
- this.analyticsStore = new EventStore(
6032
- path3.join(storagePath, "analytics.duckdb"),
6033
- { readOnly: false }
6034
- );
6035
- }
6036
5189
  this.vectorStore = new VectorStore(path3.join(storagePath, "vectors"));
6037
5190
  const embeddingModel = config.embeddingModel || process.env.CLAUDE_MEMORY_EMBEDDING_MODEL;
6038
5191
  this.embedder = embeddingModel ? new Embedder(embeddingModel) : getDefaultEmbedder();
@@ -6058,13 +5211,6 @@ var MemoryService = class {
6058
5211
  this.initialized = true;
6059
5212
  return;
6060
5213
  }
6061
- if (this.analyticsStore) {
6062
- try {
6063
- await this.analyticsStore.initialize();
6064
- } catch (error) {
6065
- console.warn("[MemoryService] Analytics store (DuckDB) initialization failed, using SQLite for reads:", error);
6066
- }
6067
- }
6068
5214
  await this.vectorStore.initialize();
6069
5215
  await this.embedder.initialize();
6070
5216
  if (!this.readOnly) {
@@ -6081,14 +5227,6 @@ var MemoryService = class {
6081
5227
  this.graduation
6082
5228
  );
6083
5229
  this.graduationWorker.start();
6084
- if (this.analyticsStore) {
6085
- this.syncWorker = new SyncWorker(
6086
- this.sqliteStore,
6087
- this.analyticsStore,
6088
- { intervalMs: 3e4, batchSize: 500 }
6089
- );
6090
- this.syncWorker.start();
6091
- }
6092
5230
  }
6093
5231
  const savedMode = await this.sqliteStore.getEndlessConfig("mode");
6094
5232
  if (savedMode === "endless") {
@@ -6285,6 +5423,57 @@ var MemoryService = class {
6285
5423
  }
6286
5424
  );
6287
5425
  }
5426
+ /**
5427
+ * Backfill session summaries for recent sessions that are missing them.
5428
+ * Called from session-start hook to catch sessions that ended without Stop hook.
5429
+ */
5430
+ async backfillMissingSummaries(currentSessionId, limit = 5) {
5431
+ await this.initialize();
5432
+ const recentSessionIds = await this.sqliteStore.getSessionsWithoutSummary(currentSessionId, limit);
5433
+ for (const sid of recentSessionIds) {
5434
+ try {
5435
+ await this.generateSessionSummary(sid);
5436
+ } catch {
5437
+ }
5438
+ }
5439
+ }
5440
+ /**
5441
+ * Generate a rule-based session summary from stored events.
5442
+ * Called at session end (Stop hook) when no LLM-generated summary exists.
5443
+ * Skips if a summary already exists for this session.
5444
+ */
5445
+ async generateSessionSummary(sessionId) {
5446
+ await this.initialize();
5447
+ const events = await this.sqliteStore.getSessionEvents(sessionId);
5448
+ if (events.length < 3)
5449
+ return;
5450
+ const hasSummary = events.some((e) => e.eventType === "session_summary");
5451
+ if (hasSummary)
5452
+ return;
5453
+ const prompts = events.filter((e) => e.eventType === "user_prompt");
5454
+ const toolObs = events.filter((e) => e.eventType === "tool_observation");
5455
+ const toolNames = [...new Set(
5456
+ toolObs.map((e) => e.metadata?.toolName).filter(Boolean)
5457
+ )];
5458
+ const errorObs = toolObs.filter((e) => {
5459
+ const meta = e.metadata;
5460
+ return meta?.exitCode !== void 0 && meta.exitCode !== 0;
5461
+ });
5462
+ const datePart = events[0].timestamp.toISOString().split("T")[0];
5463
+ const parts = [`[${datePart}] ${prompts.length}\uD134 \uC138\uC158.`];
5464
+ if (prompts.length > 0) {
5465
+ const firstPrompt = prompts[0].content.slice(0, 120).replace(/\n/g, " ");
5466
+ parts.push(`\uC8FC\uC694 \uC791\uC5C5: ${firstPrompt}`);
5467
+ }
5468
+ if (toolNames.length > 0) {
5469
+ parts.push(`\uC0AC\uC6A9 \uD234: ${toolNames.slice(0, 6).join(", ")}`);
5470
+ }
5471
+ if (errorObs.length > 0) {
5472
+ parts.push(`\uC624\uB958 ${errorObs.length}\uAC74 \uBC1C\uC0DD`);
5473
+ }
5474
+ const summary = parts.join(". ");
5475
+ await this.storeSessionSummary(sessionId, summary, { generated: "rule-based", eventCount: events.length });
5476
+ }
6288
5477
  /**
6289
5478
  * Store a tool observation
6290
5479
  */
@@ -6820,6 +6009,7 @@ var MemoryService = class {
6820
6009
  await this.initialize();
6821
6010
  await this.sqliteStore.recordRetrievalTrace({
6822
6011
  ...input,
6012
+ projectHash: this.projectHash || void 0,
6823
6013
  candidateDetails: [],
6824
6014
  selectedDetails: [],
6825
6015
  fallbackTrace: []
@@ -7110,16 +6300,10 @@ var MemoryService = class {
7110
6300
  if (this.vectorWorker) {
7111
6301
  this.vectorWorker.stop();
7112
6302
  }
7113
- if (this.syncWorker) {
7114
- this.syncWorker.stop();
7115
- }
7116
6303
  if (this.sharedEventStore) {
7117
6304
  await this.sharedEventStore.close();
7118
6305
  }
7119
6306
  await this.sqliteStore.close();
7120
- if (this.analyticsStore) {
7121
- await this.analyticsStore.close();
7122
- }
7123
6307
  }
7124
6308
  /**
7125
6309
  * Expand ~ to home directory
@@ -7161,7 +6345,7 @@ function getMemoryServiceForProject(projectPath, sharedStoreConfig) {
7161
6345
 
7162
6346
  // src/server/api/utils.ts
7163
6347
  function getServiceFromQuery(c) {
7164
- const project = c.req.query("project");
6348
+ const project = c.req.query("project") || c.req.query("projectId");
7165
6349
  if (project) {
7166
6350
  const isHash = /^[a-f0-9]{8}$/.test(project);
7167
6351
  let storagePath;