claude-memory-layer 1.0.23 → 1.0.25

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 (58) hide show
  1. package/.claude/settings.local.json +25 -0
  2. package/README.md +2 -0
  3. package/dist/cli/index.js +229 -978
  4. package/dist/cli/index.js.map +4 -4
  5. package/dist/core/index.js +59 -71
  6. package/dist/core/index.js.map +3 -3
  7. package/dist/hooks/post-tool-use.js +287 -976
  8. package/dist/hooks/post-tool-use.js.map +4 -4
  9. package/dist/hooks/semantic-daemon.js +6520 -0
  10. package/dist/hooks/semantic-daemon.js.map +7 -0
  11. package/dist/hooks/session-end.js +209 -973
  12. package/dist/hooks/session-end.js.map +4 -4
  13. package/dist/hooks/session-start.js +293 -978
  14. package/dist/hooks/session-start.js.map +4 -4
  15. package/dist/hooks/stop.js +247 -975
  16. package/dist/hooks/stop.js.map +4 -4
  17. package/dist/hooks/user-prompt-submit.js +406 -1036
  18. package/dist/hooks/user-prompt-submit.js.map +4 -4
  19. package/dist/server/api/index.js +209 -973
  20. package/dist/server/api/index.js.map +4 -4
  21. package/dist/server/index.js +209 -973
  22. package/dist/server/index.js.map +4 -4
  23. package/dist/services/memory-service.js +209 -973
  24. package/dist/services/memory-service.js.map +4 -4
  25. package/dist/ui/app.js +48 -1
  26. package/dist/ui/index.html +11 -3
  27. package/memory/_index.md +1 -0
  28. package/memory/agent_response/uncategorized/2026-03-04.md +1314 -1
  29. package/memory/session_summary/uncategorized/2026-03-04.md +50 -0
  30. package/memory/tool_observation/uncategorized/2026-03-04.md +969 -1
  31. package/memory/user_prompt/uncategorized/2026-03-04.md +555 -1
  32. package/package.json +1 -2
  33. package/scripts/build.ts +2 -1
  34. package/specs/memory-utilization-improvements/context.md +145 -0
  35. package/specs/memory-utilization-improvements/plan.md +361 -0
  36. package/specs/memory-utilization-improvements/spec.md +308 -0
  37. package/specs/optional-duckdb/context.md +77 -0
  38. package/specs/optional-duckdb/plan.md +142 -0
  39. package/specs/optional-duckdb/spec.md +35 -0
  40. package/specs/selective-tool-observation/context.md +100 -0
  41. package/specs/selective-tool-observation/plan.md +158 -0
  42. package/specs/selective-tool-observation/spec.md +127 -0
  43. package/src/cli/index.ts +1 -0
  44. package/src/core/db-wrapper.ts +18 -73
  45. package/src/core/embedder.ts +13 -4
  46. package/src/core/sqlite-event-store.ts +40 -0
  47. package/src/core/turn-state.ts +48 -0
  48. package/src/core/types.ts +1 -0
  49. package/src/hooks/post-tool-use.ts +72 -2
  50. package/src/hooks/semantic-daemon-client.ts +208 -0
  51. package/src/hooks/semantic-daemon.ts +276 -0
  52. package/src/hooks/session-start.ts +11 -0
  53. package/src/hooks/stop.ts +33 -4
  54. package/src/hooks/user-prompt-submit.ts +48 -40
  55. package/src/services/memory-service.ts +112 -65
  56. package/src/services/session-history-importer.ts +18 -0
  57. package/src/ui/app.js +48 -1
  58. package/src/ui/index.html +11 -3
@@ -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)
@@ -1850,6 +1160,21 @@ var SQLiteEventStore = class {
1850
1160
  [id, eventId, sessionId, score, query.slice(0, 100)]
1851
1161
  );
1852
1162
  }
1163
+ /**
1164
+ * Get session IDs that have unevaluated retrievals (measured_at IS NULL).
1165
+ * Excludes the current session. Used to backfill sessions that ended without Stop hook.
1166
+ */
1167
+ async getUnevaluatedSessions(currentSessionId, limit = 5) {
1168
+ await this.initialize();
1169
+ const rows = sqliteAll(
1170
+ this.db,
1171
+ `SELECT DISTINCT session_id FROM memory_helpfulness
1172
+ WHERE measured_at IS NULL AND session_id != ?
1173
+ ORDER BY created_at DESC LIMIT ?`,
1174
+ [currentSessionId, limit]
1175
+ );
1176
+ return rows.map((r) => r.session_id);
1177
+ }
1853
1178
  /**
1854
1179
  * Evaluate helpfulness for all retrievals in a session
1855
1180
  * Called at session end - uses behavioral signals to compute score
@@ -2048,7 +1373,7 @@ var SQLiteEventStore = class {
2048
1373
  }
2049
1374
  async recordRetrievalTrace(input) {
2050
1375
  await this.initialize();
2051
- const traceId = randomUUID2();
1376
+ const traceId = randomUUID();
2052
1377
  sqliteRun(
2053
1378
  this.db,
2054
1379
  `INSERT INTO retrieval_traces (
@@ -2302,169 +1627,6 @@ var SQLiteEventStore = class {
2302
1627
  }
2303
1628
  };
2304
1629
 
2305
- // src/core/sync-worker.ts
2306
- var DEFAULT_CONFIG = {
2307
- intervalMs: 3e4,
2308
- batchSize: 500,
2309
- maxRetries: 3,
2310
- retryDelayMs: 5e3
2311
- };
2312
- var SyncWorker = class {
2313
- constructor(sqliteStore, duckdbStore, config) {
2314
- this.sqliteStore = sqliteStore;
2315
- this.duckdbStore = duckdbStore;
2316
- this.config = { ...DEFAULT_CONFIG, ...config };
2317
- }
2318
- config;
2319
- intervalHandle = null;
2320
- running = false;
2321
- stats = {
2322
- lastSyncAt: null,
2323
- eventsSynced: 0,
2324
- sessionsSynced: 0,
2325
- errors: 0,
2326
- status: "idle"
2327
- };
2328
- /**
2329
- * Start the sync worker
2330
- */
2331
- start() {
2332
- if (this.running)
2333
- return;
2334
- this.running = true;
2335
- this.stats.status = "idle";
2336
- this.syncNow().catch((err) => {
2337
- console.error("[SyncWorker] Initial sync failed:", err);
2338
- });
2339
- this.intervalHandle = setInterval(() => {
2340
- this.syncNow().catch((err) => {
2341
- console.error("[SyncWorker] Periodic sync failed:", err);
2342
- });
2343
- }, this.config.intervalMs);
2344
- }
2345
- /**
2346
- * Stop the sync worker
2347
- */
2348
- stop() {
2349
- this.running = false;
2350
- this.stats.status = "stopped";
2351
- if (this.intervalHandle) {
2352
- clearInterval(this.intervalHandle);
2353
- this.intervalHandle = null;
2354
- }
2355
- }
2356
- /**
2357
- * Trigger immediate sync
2358
- */
2359
- async syncNow() {
2360
- if (this.stats.status === "syncing") {
2361
- return;
2362
- }
2363
- this.stats.status = "syncing";
2364
- try {
2365
- await this.syncEvents();
2366
- await this.syncSessions();
2367
- this.stats.lastSyncAt = /* @__PURE__ */ new Date();
2368
- this.stats.status = "idle";
2369
- } catch (error) {
2370
- this.stats.errors++;
2371
- this.stats.status = "error";
2372
- throw error;
2373
- }
2374
- }
2375
- /**
2376
- * Sync events from SQLite to DuckDB
2377
- */
2378
- async syncEvents() {
2379
- const targetName = "duckdb_analytics";
2380
- const position = await this.sqliteStore.getSyncPosition(targetName);
2381
- const lastTimestamp = position.lastTimestamp || "1970-01-01T00:00:00.000Z";
2382
- let hasMore = true;
2383
- let totalSynced = 0;
2384
- while (hasMore) {
2385
- const events = await this.sqliteStore.getEventsSince(lastTimestamp, this.config.batchSize);
2386
- if (events.length === 0) {
2387
- hasMore = false;
2388
- break;
2389
- }
2390
- await this.retryWithBackoff(async () => {
2391
- for (const event of events) {
2392
- await this.insertEventToDuckDB(event);
2393
- }
2394
- });
2395
- totalSynced += events.length;
2396
- const lastEvent = events[events.length - 1];
2397
- await this.sqliteStore.updateSyncPosition(
2398
- targetName,
2399
- lastEvent.id,
2400
- lastEvent.timestamp.toISOString()
2401
- );
2402
- hasMore = events.length === this.config.batchSize;
2403
- }
2404
- this.stats.eventsSynced += totalSynced;
2405
- }
2406
- /**
2407
- * Sync sessions from SQLite to DuckDB
2408
- */
2409
- async syncSessions() {
2410
- const sessions = await this.sqliteStore.getAllSessions();
2411
- for (const session of sessions) {
2412
- await this.retryWithBackoff(async () => {
2413
- await this.duckdbStore.upsertSession(session);
2414
- });
2415
- }
2416
- this.stats.sessionsSynced = sessions.length;
2417
- }
2418
- /**
2419
- * Insert a single event into DuckDB
2420
- */
2421
- async insertEventToDuckDB(event) {
2422
- await this.duckdbStore.append({
2423
- eventType: event.eventType,
2424
- sessionId: event.sessionId,
2425
- timestamp: event.timestamp,
2426
- content: event.content,
2427
- metadata: event.metadata
2428
- });
2429
- }
2430
- /**
2431
- * Retry operation with exponential backoff
2432
- */
2433
- async retryWithBackoff(fn) {
2434
- let lastError = null;
2435
- for (let attempt = 0; attempt < this.config.maxRetries; attempt++) {
2436
- try {
2437
- return await fn();
2438
- } catch (error) {
2439
- lastError = error instanceof Error ? error : new Error(String(error));
2440
- if (attempt < this.config.maxRetries - 1) {
2441
- const delay = this.config.retryDelayMs * Math.pow(2, attempt);
2442
- await this.sleep(delay);
2443
- }
2444
- }
2445
- }
2446
- throw lastError;
2447
- }
2448
- /**
2449
- * Sleep utility
2450
- */
2451
- sleep(ms) {
2452
- return new Promise((resolve3) => setTimeout(resolve3, ms));
2453
- }
2454
- /**
2455
- * Get sync statistics
2456
- */
2457
- getStats() {
2458
- return { ...this.stats };
2459
- }
2460
- /**
2461
- * Check if worker is running
2462
- */
2463
- isRunning() {
2464
- return this.running;
2465
- }
2466
- };
2467
-
2468
1630
  // src/core/vector-store.ts
2469
1631
  import * as lancedb from "@lancedb/lancedb";
2470
1632
  var VectorStore = class {
@@ -2637,7 +1799,7 @@ var VectorStore = class {
2637
1799
 
2638
1800
  // src/core/embedder.ts
2639
1801
  import { pipeline } from "@huggingface/transformers";
2640
- var Embedder = class {
1802
+ var Embedder = class _Embedder {
2641
1803
  pipeline = null;
2642
1804
  modelName;
2643
1805
  activeModelName;
@@ -2668,6 +1830,11 @@ var Embedder = class {
2668
1830
  this.initialized = true;
2669
1831
  }
2670
1832
  }
1833
+ // ~4 chars per token; 512 tokens * 4 = 2048, use 2000 to be safe
1834
+ static MAX_CHARS = 2e3;
1835
+ truncate(text) {
1836
+ return text.length > _Embedder.MAX_CHARS ? text.slice(0, _Embedder.MAX_CHARS) : text;
1837
+ }
2671
1838
  /**
2672
1839
  * Generate embedding for a single text
2673
1840
  */
@@ -2676,10 +1843,11 @@ var Embedder = class {
2676
1843
  if (!this.pipeline) {
2677
1844
  throw new Error("Embedding pipeline not initialized");
2678
1845
  }
2679
- const output = await this.pipeline(text, {
1846
+ const output = await this.pipeline(this.truncate(text), {
2680
1847
  pooling: "mean",
2681
1848
  normalize: true,
2682
- truncation: true
1849
+ truncation: true,
1850
+ max_length: 512
2683
1851
  });
2684
1852
  const vector = Array.from(output.data);
2685
1853
  return {
@@ -2701,10 +1869,11 @@ var Embedder = class {
2701
1869
  for (let i = 0; i < texts.length; i += batchSize) {
2702
1870
  const batch = texts.slice(i, i + batchSize);
2703
1871
  for (const text of batch) {
2704
- const output = await this.pipeline(text, {
1872
+ const output = await this.pipeline(this.truncate(text), {
2705
1873
  pooling: "mean",
2706
1874
  normalize: true,
2707
- truncation: true
1875
+ truncation: true,
1876
+ max_length: 512
2708
1877
  });
2709
1878
  const vector = Array.from(output.data);
2710
1879
  results.push({
@@ -2745,8 +1914,34 @@ function getDefaultEmbedder() {
2745
1914
  return defaultEmbedder;
2746
1915
  }
2747
1916
 
1917
+ // src/core/db-wrapper.ts
1918
+ import BetterSqlite3 from "better-sqlite3";
1919
+ function toDate(value) {
1920
+ if (value instanceof Date)
1921
+ return value;
1922
+ if (typeof value === "string")
1923
+ return new Date(value);
1924
+ if (typeof value === "number")
1925
+ return new Date(value);
1926
+ return new Date(String(value));
1927
+ }
1928
+ function createDatabase(dbPath, options) {
1929
+ return new BetterSqlite3(dbPath, { readonly: options?.readOnly });
1930
+ }
1931
+ function dbRun(db, sql, params = []) {
1932
+ db.prepare(sql).run(...params);
1933
+ return Promise.resolve();
1934
+ }
1935
+ function dbAll(db, sql, params = []) {
1936
+ return Promise.resolve(db.prepare(sql).all(...params));
1937
+ }
1938
+ function dbClose(db) {
1939
+ db.close();
1940
+ return Promise.resolve();
1941
+ }
1942
+
2748
1943
  // src/core/vector-outbox.ts
2749
- var DEFAULT_CONFIG2 = {
1944
+ var DEFAULT_CONFIG = {
2750
1945
  embeddingVersion: "v1",
2751
1946
  maxRetries: 3,
2752
1947
  stuckThresholdMs: 5 * 60 * 1e3,
@@ -2755,7 +1950,7 @@ var DEFAULT_CONFIG2 = {
2755
1950
  };
2756
1951
 
2757
1952
  // src/core/vector-worker.ts
2758
- var DEFAULT_CONFIG3 = {
1953
+ var DEFAULT_CONFIG2 = {
2759
1954
  batchSize: 32,
2760
1955
  pollIntervalMs: 1e3,
2761
1956
  maxRetries: 3
@@ -2772,7 +1967,7 @@ var VectorWorker = class {
2772
1967
  this.eventStore = eventStore;
2773
1968
  this.vectorStore = vectorStore;
2774
1969
  this.embedder = embedder;
2775
- this.config = { ...DEFAULT_CONFIG3, ...config };
1970
+ this.config = { ...DEFAULT_CONFIG2, ...config };
2776
1971
  }
2777
1972
  /**
2778
1973
  * Start the worker polling loop
@@ -2893,7 +2088,7 @@ function createVectorWorker(eventStore, vectorStore, embedder, config) {
2893
2088
  }
2894
2089
 
2895
2090
  // src/core/matcher.ts
2896
- var DEFAULT_CONFIG4 = {
2091
+ var DEFAULT_CONFIG3 = {
2897
2092
  weights: {
2898
2093
  semanticSimilarity: 0.4,
2899
2094
  ftsScore: 0.25,
@@ -2908,9 +2103,9 @@ var Matcher = class {
2908
2103
  config;
2909
2104
  constructor(config = {}) {
2910
2105
  this.config = {
2911
- ...DEFAULT_CONFIG4,
2106
+ ...DEFAULT_CONFIG3,
2912
2107
  ...config,
2913
- weights: { ...DEFAULT_CONFIG4.weights, ...config.weights }
2108
+ weights: { ...DEFAULT_CONFIG3.weights, ...config.weights }
2914
2109
  };
2915
2110
  }
2916
2111
  /**
@@ -3900,7 +3095,7 @@ function createSharedEventStore(dbPath) {
3900
3095
  }
3901
3096
 
3902
3097
  // src/core/shared-store.ts
3903
- import { randomUUID as randomUUID3 } from "crypto";
3098
+ import { randomUUID as randomUUID2 } from "crypto";
3904
3099
  var SharedStore = class {
3905
3100
  constructor(sharedEventStore) {
3906
3101
  this.sharedEventStore = sharedEventStore;
@@ -3912,7 +3107,7 @@ var SharedStore = class {
3912
3107
  * Promote a verified troubleshooting entry to shared storage
3913
3108
  */
3914
3109
  async promoteEntry(input) {
3915
- const entryId = randomUUID3();
3110
+ const entryId = randomUUID2();
3916
3111
  await dbRun(
3917
3112
  this.db,
3918
3113
  `INSERT INTO shared_troubleshooting (
@@ -4277,7 +3472,7 @@ function createSharedVectorStore(dbPath) {
4277
3472
  }
4278
3473
 
4279
3474
  // src/core/shared-promoter.ts
4280
- import { randomUUID as randomUUID4 } from "crypto";
3475
+ import { randomUUID as randomUUID3 } from "crypto";
4281
3476
  var SharedPromoter = class {
4282
3477
  constructor(sharedStore, sharedVectorStore, embedder, config) {
4283
3478
  this.sharedStore = sharedStore;
@@ -4345,7 +3540,7 @@ var SharedPromoter = class {
4345
3540
  const embeddingContent = this.createEmbeddingContent(input);
4346
3541
  const embedding = await this.embedder.embed(embeddingContent);
4347
3542
  await this.sharedVectorStore.upsert({
4348
- id: randomUUID4(),
3543
+ id: randomUUID3(),
4349
3544
  entryId,
4350
3545
  entryType: "troubleshooting",
4351
3546
  content: embeddingContent,
@@ -4485,7 +3680,7 @@ function createToolObservationEmbedding(toolName, metadata, success) {
4485
3680
  }
4486
3681
 
4487
3682
  // src/core/working-set-store.ts
4488
- import { randomUUID as randomUUID5 } from "crypto";
3683
+ import { randomUUID as randomUUID4 } from "crypto";
4489
3684
  var WorkingSetStore = class {
4490
3685
  constructor(eventStore, config) {
4491
3686
  this.eventStore = eventStore;
@@ -4506,7 +3701,7 @@ var WorkingSetStore = class {
4506
3701
  `INSERT OR REPLACE INTO working_set (id, event_id, added_at, relevance_score, topics, expires_at)
4507
3702
  VALUES (?, ?, CURRENT_TIMESTAMP, ?, ?, ?)`,
4508
3703
  [
4509
- randomUUID5(),
3704
+ randomUUID4(),
4510
3705
  eventId,
4511
3706
  relevanceScore,
4512
3707
  JSON.stringify(topics || []),
@@ -4690,7 +3885,7 @@ function createWorkingSetStore(eventStore, config) {
4690
3885
  }
4691
3886
 
4692
3887
  // src/core/consolidated-store.ts
4693
- import { randomUUID as randomUUID6 } from "crypto";
3888
+ import { randomUUID as randomUUID5 } from "crypto";
4694
3889
  var ConsolidatedStore = class {
4695
3890
  constructor(eventStore) {
4696
3891
  this.eventStore = eventStore;
@@ -4702,7 +3897,7 @@ var ConsolidatedStore = class {
4702
3897
  * Create a new consolidated memory
4703
3898
  */
4704
3899
  async create(input) {
4705
- const memoryId = randomUUID6();
3900
+ const memoryId = randomUUID5();
4706
3901
  await dbRun(
4707
3902
  this.db,
4708
3903
  `INSERT INTO consolidated_memories
@@ -4832,7 +4027,7 @@ var ConsolidatedStore = class {
4832
4027
  * Create a long-term rule promoted from stable summaries
4833
4028
  */
4834
4029
  async createRule(input) {
4835
- const ruleId = randomUUID6();
4030
+ const ruleId = randomUUID5();
4836
4031
  await dbRun(
4837
4032
  this.db,
4838
4033
  `INSERT INTO consolidated_rules
@@ -5354,7 +4549,7 @@ function createConsolidationWorker(workingSetStore, consolidatedStore, config) {
5354
4549
  }
5355
4550
 
5356
4551
  // src/core/continuity-manager.ts
5357
- import { randomUUID as randomUUID7 } from "crypto";
4552
+ import { randomUUID as randomUUID6 } from "crypto";
5358
4553
  var ContinuityManager = class {
5359
4554
  constructor(eventStore, config) {
5360
4555
  this.eventStore = eventStore;
@@ -5508,7 +4703,7 @@ var ContinuityManager = class {
5508
4703
  `INSERT INTO continuity_log
5509
4704
  (log_id, from_context_id, to_context_id, continuity_score, transition_type, created_at)
5510
4705
  VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
5511
- [randomUUID7(), previous.id, current.id, score, type]
4706
+ [randomUUID6(), previous.id, current.id, score, type]
5512
4707
  );
5513
4708
  }
5514
4709
  /**
@@ -5617,7 +4812,7 @@ function createContinuityManager(eventStore, config) {
5617
4812
  }
5618
4813
 
5619
4814
  // src/core/graduation-worker.ts
5620
- var DEFAULT_CONFIG5 = {
4815
+ var DEFAULT_CONFIG4 = {
5621
4816
  evaluationIntervalMs: 3e5,
5622
4817
  // 5 minutes
5623
4818
  batchSize: 50,
@@ -5625,7 +4820,7 @@ var DEFAULT_CONFIG5 = {
5625
4820
  // 1 hour cooldown between evaluations
5626
4821
  };
5627
4822
  var GraduationWorker = class {
5628
- constructor(eventStore, graduation, config = DEFAULT_CONFIG5) {
4823
+ constructor(eventStore, graduation, config = DEFAULT_CONFIG4) {
5629
4824
  this.eventStore = eventStore;
5630
4825
  this.graduation = graduation;
5631
4826
  this.config = config;
@@ -5733,7 +4928,7 @@ function createGraduationWorker(eventStore, graduation, config) {
5733
4928
  return new GraduationWorker(
5734
4929
  eventStore,
5735
4930
  graduation,
5736
- { ...DEFAULT_CONFIG5, ...config }
4931
+ { ...DEFAULT_CONFIG4, ...config }
5737
4932
  );
5738
4933
  }
5739
4934
 
@@ -5942,9 +5137,6 @@ function loadSessionRegistry() {
5942
5137
  var MemoryService = class {
5943
5138
  // Primary store: SQLite (WAL mode) - for hooks, always available
5944
5139
  sqliteStore;
5945
- // Analytics store: DuckDB - for server reads (optional, synced from SQLite)
5946
- analyticsStore;
5947
- syncWorker = null;
5948
5140
  vectorStore;
5949
5141
  embedder;
5950
5142
  matcher;
@@ -5970,6 +5162,7 @@ var MemoryService = class {
5970
5162
  projectPath = null;
5971
5163
  readOnly;
5972
5164
  lightweightMode;
5165
+ embeddingOnly;
5973
5166
  mdMirror;
5974
5167
  storagePath;
5975
5168
  constructor(config) {
@@ -5977,6 +5170,7 @@ var MemoryService = class {
5977
5170
  this.storagePath = storagePath;
5978
5171
  this.readOnly = config.readOnly ?? false;
5979
5172
  this.lightweightMode = config.lightweightMode ?? false;
5173
+ this.embeddingOnly = config.embeddingOnly ?? false;
5980
5174
  this.mdMirror = new MarkdownMirror2(process.cwd());
5981
5175
  if (!this.readOnly && !fs4.existsSync(storagePath)) {
5982
5176
  fs4.mkdirSync(storagePath, { recursive: true });
@@ -5991,24 +5185,6 @@ var MemoryService = class {
5991
5185
  markdownMirrorRoot: storagePath
5992
5186
  }
5993
5187
  );
5994
- const analyticsEnabled = config.analyticsEnabled ?? this.readOnly;
5995
- if (!analyticsEnabled) {
5996
- this.analyticsStore = null;
5997
- } else if (this.readOnly) {
5998
- try {
5999
- this.analyticsStore = new EventStore(
6000
- path3.join(storagePath, "analytics.duckdb"),
6001
- { readOnly: true }
6002
- );
6003
- } catch {
6004
- this.analyticsStore = null;
6005
- }
6006
- } else {
6007
- this.analyticsStore = new EventStore(
6008
- path3.join(storagePath, "analytics.duckdb"),
6009
- { readOnly: false }
6010
- );
6011
- }
6012
5188
  this.vectorStore = new VectorStore(path3.join(storagePath, "vectors"));
6013
5189
  const embeddingModel = config.embeddingModel || process.env.CLAUDE_MEMORY_EMBEDDING_MODEL;
6014
5190
  this.embedder = embeddingModel ? new Embedder(embeddingModel) : getDefaultEmbedder();
@@ -6034,13 +5210,6 @@ var MemoryService = class {
6034
5210
  this.initialized = true;
6035
5211
  return;
6036
5212
  }
6037
- if (this.analyticsStore) {
6038
- try {
6039
- await this.analyticsStore.initialize();
6040
- } catch (error) {
6041
- console.warn("[MemoryService] Analytics store (DuckDB) initialization failed, using SQLite for reads:", error);
6042
- }
6043
- }
6044
5213
  await this.vectorStore.initialize();
6045
5214
  await this.embedder.initialize();
6046
5215
  if (!this.readOnly) {
@@ -6050,19 +5219,13 @@ var MemoryService = class {
6050
5219
  this.embedder
6051
5220
  );
6052
5221
  this.vectorWorker.start();
6053
- this.retriever.setGraduationPipeline(this.graduation);
6054
- this.graduationWorker = createGraduationWorker(
6055
- this.sqliteStore,
6056
- this.graduation
6057
- );
6058
- this.graduationWorker.start();
6059
- if (this.analyticsStore) {
6060
- this.syncWorker = new SyncWorker(
5222
+ if (!this.embeddingOnly) {
5223
+ this.retriever.setGraduationPipeline(this.graduation);
5224
+ this.graduationWorker = createGraduationWorker(
6061
5225
  this.sqliteStore,
6062
- this.analyticsStore,
6063
- { intervalMs: 3e4, batchSize: 500 }
5226
+ this.graduation
6064
5227
  );
6065
- this.syncWorker.start();
5228
+ this.graduationWorker.start();
6066
5229
  }
6067
5230
  const savedMode = await this.sqliteStore.getEndlessConfig("mode");
6068
5231
  if (savedMode === "endless") {
@@ -6259,6 +5422,57 @@ var MemoryService = class {
6259
5422
  }
6260
5423
  );
6261
5424
  }
5425
+ /**
5426
+ * Backfill session summaries for recent sessions that are missing them.
5427
+ * Called from session-start hook to catch sessions that ended without Stop hook.
5428
+ */
5429
+ async backfillMissingSummaries(currentSessionId, limit = 5) {
5430
+ await this.initialize();
5431
+ const recentSessionIds = await this.sqliteStore.getSessionsWithoutSummary(currentSessionId, limit);
5432
+ for (const sid of recentSessionIds) {
5433
+ try {
5434
+ await this.generateSessionSummary(sid);
5435
+ } catch {
5436
+ }
5437
+ }
5438
+ }
5439
+ /**
5440
+ * Generate a rule-based session summary from stored events.
5441
+ * Called at session end (Stop hook) when no LLM-generated summary exists.
5442
+ * Skips if a summary already exists for this session.
5443
+ */
5444
+ async generateSessionSummary(sessionId) {
5445
+ await this.initialize();
5446
+ const events = await this.sqliteStore.getSessionEvents(sessionId);
5447
+ if (events.length < 3)
5448
+ return;
5449
+ const hasSummary = events.some((e) => e.eventType === "session_summary");
5450
+ if (hasSummary)
5451
+ return;
5452
+ const prompts = events.filter((e) => e.eventType === "user_prompt");
5453
+ const toolObs = events.filter((e) => e.eventType === "tool_observation");
5454
+ const toolNames = [...new Set(
5455
+ toolObs.map((e) => e.metadata?.toolName).filter(Boolean)
5456
+ )];
5457
+ const errorObs = toolObs.filter((e) => {
5458
+ const meta = e.metadata;
5459
+ return meta?.exitCode !== void 0 && meta.exitCode !== 0;
5460
+ });
5461
+ const datePart = events[0].timestamp.toISOString().split("T")[0];
5462
+ const parts = [`[${datePart}] ${prompts.length}\uD134 \uC138\uC158.`];
5463
+ if (prompts.length > 0) {
5464
+ const firstPrompt = prompts[0].content.slice(0, 120).replace(/\n/g, " ");
5465
+ parts.push(`\uC8FC\uC694 \uC791\uC5C5: ${firstPrompt}`);
5466
+ }
5467
+ if (toolNames.length > 0) {
5468
+ parts.push(`\uC0AC\uC6A9 \uD234: ${toolNames.slice(0, 6).join(", ")}`);
5469
+ }
5470
+ if (errorObs.length > 0) {
5471
+ parts.push(`\uC624\uB958 ${errorObs.length}\uAC74 \uBC1C\uC0DD`);
5472
+ }
5473
+ const summary = parts.join(". ");
5474
+ await this.storeSessionSummary(sessionId, summary, { generated: "rule-based", eventCount: events.length });
5475
+ }
6262
5476
  /**
6263
5477
  * Store a tool observation
6264
5478
  */
@@ -6786,6 +6000,20 @@ var MemoryService = class {
6786
6000
  await this.initialize();
6787
6001
  await this.sqliteStore.recordRetrieval(eventId, sessionId, score, query);
6788
6002
  }
6003
+ /**
6004
+ * Record a query-level retrieval trace (used by user-prompt-submit hook).
6005
+ * Feeds the retrieval_traces table that powers dashboard stats.
6006
+ */
6007
+ async recordQueryTrace(input) {
6008
+ await this.initialize();
6009
+ await this.sqliteStore.recordRetrievalTrace({
6010
+ ...input,
6011
+ projectHash: this.projectHash || void 0,
6012
+ candidateDetails: [],
6013
+ selectedDetails: [],
6014
+ fallbackTrace: []
6015
+ });
6016
+ }
6789
6017
  /**
6790
6018
  * Evaluate helpfulness of retrievals in a session (called at session end)
6791
6019
  */
@@ -6793,6 +6021,20 @@ var MemoryService = class {
6793
6021
  await this.initialize();
6794
6022
  await this.sqliteStore.evaluateSessionHelpfulness(sessionId);
6795
6023
  }
6024
+ /**
6025
+ * Backfill helpfulness evaluation for sessions that ended without Stop hook.
6026
+ * Call on first turn of a new session to catch missed evaluations.
6027
+ */
6028
+ async evaluatePendingSessions(currentSessionId) {
6029
+ await this.initialize();
6030
+ const sessions = await this.sqliteStore.getUnevaluatedSessions(currentSessionId, 5);
6031
+ for (const sid of sessions) {
6032
+ try {
6033
+ await this.sqliteStore.evaluateSessionHelpfulness(sid);
6034
+ } catch {
6035
+ }
6036
+ }
6037
+ }
6796
6038
  /**
6797
6039
  * Get most helpful memories ranked by helpfulness score
6798
6040
  */
@@ -7057,16 +6299,10 @@ var MemoryService = class {
7057
6299
  if (this.vectorWorker) {
7058
6300
  this.vectorWorker.stop();
7059
6301
  }
7060
- if (this.syncWorker) {
7061
- this.syncWorker.stop();
7062
- }
7063
6302
  if (this.sharedEventStore) {
7064
6303
  await this.sharedEventStore.close();
7065
6304
  }
7066
6305
  await this.sqliteStore.close();
7067
- if (this.analyticsStore) {
7068
- await this.analyticsStore.close();
7069
- }
7070
6306
  }
7071
6307
  /**
7072
6308
  * Expand ~ to home directory