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
@@ -11,744 +11,31 @@ import * as os from "os";
11
11
  import * as fs4 from "fs";
12
12
  import * as crypto2 from "crypto";
13
13
 
14
- // src/core/event-store.ts
15
- import { randomUUID } from "crypto";
16
-
17
- // src/core/canonical-key.ts
18
- import { createHash } from "crypto";
19
- var MAX_KEY_LENGTH = 200;
20
- function makeCanonicalKey(title, context) {
21
- let normalized = title.normalize("NFKC");
22
- normalized = normalized.toLowerCase();
23
- normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, "");
24
- normalized = normalized.replace(/\s+/g, " ").trim();
25
- let key = normalized;
26
- if (context?.project) {
27
- key = `${context.project}::${key}`;
28
- }
29
- if (key.length > MAX_KEY_LENGTH) {
30
- const hashSuffix = createHash("md5").update(key).digest("hex").slice(0, 8);
31
- key = key.slice(0, MAX_KEY_LENGTH - 9) + "_" + hashSuffix;
32
- }
33
- return key;
34
- }
35
- function makeDedupeKey(content, sessionId) {
36
- const contentHash = createHash("sha256").update(content).digest("hex");
37
- return `${sessionId}:${contentHash}`;
38
- }
39
-
40
- // src/core/db-wrapper.ts
41
- import duckdb from "duckdb";
42
- function convertBigInts(obj) {
43
- if (obj === null || obj === void 0)
44
- return obj;
45
- if (typeof obj === "bigint")
46
- return Number(obj);
47
- if (obj instanceof Date)
48
- return obj;
49
- if (Array.isArray(obj))
50
- return obj.map(convertBigInts);
51
- if (typeof obj === "object") {
52
- const result = {};
53
- for (const [key, value] of Object.entries(obj)) {
54
- result[key] = convertBigInts(value);
55
- }
56
- return result;
57
- }
58
- return obj;
59
- }
60
- function toDate(value) {
61
- if (value instanceof Date)
62
- return value;
63
- if (typeof value === "string")
64
- return new Date(value);
65
- if (typeof value === "number")
66
- return new Date(value);
67
- return new Date(String(value));
68
- }
69
- function createDatabase(path4, options) {
70
- if (options?.readOnly) {
71
- return new duckdb.Database(path4, { access_mode: "READ_ONLY" });
72
- }
73
- return new duckdb.Database(path4);
74
- }
75
- function dbRun(db, sql, params = []) {
76
- return new Promise((resolve2, reject) => {
77
- if (params.length === 0) {
78
- db.run(sql, (err) => {
79
- if (err)
80
- reject(err);
81
- else
82
- resolve2();
83
- });
84
- } else {
85
- db.run(sql, ...params, (err) => {
86
- if (err)
87
- reject(err);
88
- else
89
- resolve2();
90
- });
91
- }
92
- });
93
- }
94
- function dbAll(db, sql, params = []) {
95
- return new Promise((resolve2, reject) => {
96
- if (params.length === 0) {
97
- db.all(sql, (err, rows) => {
98
- if (err)
99
- reject(err);
100
- else
101
- resolve2(convertBigInts(rows || []));
102
- });
103
- } else {
104
- db.all(sql, ...params, (err, rows) => {
105
- if (err)
106
- reject(err);
107
- else
108
- resolve2(convertBigInts(rows || []));
109
- });
110
- }
111
- });
112
- }
113
- function dbClose(db) {
114
- return new Promise((resolve2, reject) => {
115
- db.close((err) => {
116
- if (err)
117
- reject(err);
118
- else
119
- resolve2();
120
- });
121
- });
122
- }
123
-
124
- // src/core/event-store.ts
125
- var EventStore = class {
126
- constructor(dbPath, options) {
127
- this.dbPath = dbPath;
128
- this.readOnly = options?.readOnly ?? false;
129
- this.db = createDatabase(dbPath, { readOnly: this.readOnly });
130
- }
131
- db;
132
- initialized = false;
133
- readOnly;
134
- /**
135
- * Initialize database schema
136
- */
137
- async initialize() {
138
- if (this.initialized)
139
- return;
140
- if (this.readOnly) {
141
- this.initialized = true;
142
- return;
143
- }
144
- await dbRun(this.db, `
145
- CREATE TABLE IF NOT EXISTS events (
146
- id VARCHAR PRIMARY KEY,
147
- event_type VARCHAR NOT NULL,
148
- session_id VARCHAR NOT NULL,
149
- timestamp TIMESTAMP NOT NULL,
150
- content TEXT NOT NULL,
151
- canonical_key VARCHAR NOT NULL,
152
- dedupe_key VARCHAR UNIQUE,
153
- metadata JSON
154
- )
155
- `);
156
- await dbRun(this.db, `
157
- CREATE TABLE IF NOT EXISTS event_dedup (
158
- dedupe_key VARCHAR PRIMARY KEY,
159
- event_id VARCHAR NOT NULL,
160
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
161
- )
162
- `);
163
- await dbRun(this.db, `
164
- CREATE TABLE IF NOT EXISTS sessions (
165
- id VARCHAR PRIMARY KEY,
166
- started_at TIMESTAMP NOT NULL,
167
- ended_at TIMESTAMP,
168
- project_path VARCHAR,
169
- summary TEXT,
170
- tags JSON
171
- )
172
- `);
173
- await dbRun(this.db, `
174
- CREATE TABLE IF NOT EXISTS insights (
175
- id VARCHAR PRIMARY KEY,
176
- insight_type VARCHAR NOT NULL,
177
- content TEXT NOT NULL,
178
- canonical_key VARCHAR NOT NULL,
179
- confidence FLOAT,
180
- source_events JSON,
181
- created_at TIMESTAMP,
182
- last_updated TIMESTAMP
183
- )
184
- `);
185
- await dbRun(this.db, `
186
- CREATE TABLE IF NOT EXISTS embedding_outbox (
187
- id VARCHAR PRIMARY KEY,
188
- event_id VARCHAR NOT NULL,
189
- content TEXT NOT NULL,
190
- status VARCHAR DEFAULT 'pending',
191
- retry_count INT DEFAULT 0,
192
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
193
- processed_at TIMESTAMP,
194
- error_message TEXT
195
- )
196
- `);
197
- await dbRun(this.db, `
198
- CREATE TABLE IF NOT EXISTS projection_offsets (
199
- projection_name VARCHAR PRIMARY KEY,
200
- last_event_id VARCHAR,
201
- last_timestamp TIMESTAMP,
202
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
203
- )
204
- `);
205
- await dbRun(this.db, `
206
- CREATE TABLE IF NOT EXISTS memory_levels (
207
- event_id VARCHAR PRIMARY KEY,
208
- level VARCHAR NOT NULL DEFAULT 'L0',
209
- promoted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
210
- )
211
- `);
212
- await dbRun(this.db, `
213
- CREATE TABLE IF NOT EXISTS entries (
214
- entry_id VARCHAR PRIMARY KEY,
215
- created_ts TIMESTAMP NOT NULL,
216
- entry_type VARCHAR NOT NULL,
217
- title VARCHAR NOT NULL,
218
- content_json JSON NOT NULL,
219
- stage VARCHAR NOT NULL DEFAULT 'raw',
220
- status VARCHAR DEFAULT 'active',
221
- superseded_by VARCHAR,
222
- build_id VARCHAR,
223
- evidence_json JSON,
224
- canonical_key VARCHAR,
225
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
226
- )
227
- `);
228
- await dbRun(this.db, `
229
- CREATE TABLE IF NOT EXISTS entities (
230
- entity_id VARCHAR PRIMARY KEY,
231
- entity_type VARCHAR NOT NULL,
232
- canonical_key VARCHAR NOT NULL,
233
- title VARCHAR NOT NULL,
234
- stage VARCHAR NOT NULL DEFAULT 'raw',
235
- status VARCHAR NOT NULL DEFAULT 'active',
236
- current_json JSON NOT NULL,
237
- title_norm VARCHAR,
238
- search_text VARCHAR,
239
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
240
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
241
- )
242
- `);
243
- await dbRun(this.db, `
244
- CREATE TABLE IF NOT EXISTS entity_aliases (
245
- entity_type VARCHAR NOT NULL,
246
- canonical_key VARCHAR NOT NULL,
247
- entity_id VARCHAR NOT NULL,
248
- is_primary BOOLEAN DEFAULT FALSE,
249
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
250
- PRIMARY KEY(entity_type, canonical_key)
251
- )
252
- `);
253
- await dbRun(this.db, `
254
- CREATE TABLE IF NOT EXISTS edges (
255
- edge_id VARCHAR PRIMARY KEY,
256
- src_type VARCHAR NOT NULL,
257
- src_id VARCHAR NOT NULL,
258
- rel_type VARCHAR NOT NULL,
259
- dst_type VARCHAR NOT NULL,
260
- dst_id VARCHAR NOT NULL,
261
- meta_json JSON,
262
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
263
- )
264
- `);
265
- await dbRun(this.db, `
266
- CREATE TABLE IF NOT EXISTS vector_outbox (
267
- job_id VARCHAR PRIMARY KEY,
268
- item_kind VARCHAR NOT NULL,
269
- item_id VARCHAR NOT NULL,
270
- embedding_version VARCHAR NOT NULL,
271
- status VARCHAR NOT NULL DEFAULT 'pending',
272
- retry_count INT DEFAULT 0,
273
- error VARCHAR,
274
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
275
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
276
- UNIQUE(item_kind, item_id, embedding_version)
277
- )
278
- `);
279
- await dbRun(this.db, `
280
- CREATE TABLE IF NOT EXISTS build_runs (
281
- build_id VARCHAR PRIMARY KEY,
282
- started_at TIMESTAMP NOT NULL,
283
- finished_at TIMESTAMP,
284
- extractor_model VARCHAR NOT NULL,
285
- extractor_prompt_hash VARCHAR NOT NULL,
286
- embedder_model VARCHAR NOT NULL,
287
- embedding_version VARCHAR NOT NULL,
288
- idris_version VARCHAR NOT NULL,
289
- schema_version VARCHAR NOT NULL,
290
- status VARCHAR NOT NULL DEFAULT 'running',
291
- error VARCHAR
292
- )
293
- `);
294
- await dbRun(this.db, `
295
- CREATE TABLE IF NOT EXISTS pipeline_metrics (
296
- id VARCHAR PRIMARY KEY,
297
- ts TIMESTAMP NOT NULL,
298
- stage VARCHAR NOT NULL,
299
- latency_ms DOUBLE NOT NULL,
300
- success BOOLEAN NOT NULL,
301
- error VARCHAR,
302
- session_id VARCHAR
303
- )
304
- `);
305
- await dbRun(this.db, `
306
- CREATE TABLE IF NOT EXISTS working_set (
307
- id VARCHAR PRIMARY KEY,
308
- event_id VARCHAR NOT NULL,
309
- added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
310
- relevance_score FLOAT DEFAULT 1.0,
311
- topics JSON,
312
- expires_at TIMESTAMP
313
- )
314
- `);
315
- await dbRun(this.db, `
316
- CREATE TABLE IF NOT EXISTS consolidated_memories (
317
- memory_id VARCHAR PRIMARY KEY,
318
- summary TEXT NOT NULL,
319
- topics JSON,
320
- source_events JSON,
321
- confidence FLOAT DEFAULT 0.5,
322
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
323
- accessed_at TIMESTAMP,
324
- access_count INTEGER DEFAULT 0
325
- )
326
- `);
327
- await dbRun(this.db, `
328
- CREATE TABLE IF NOT EXISTS continuity_log (
329
- log_id VARCHAR PRIMARY KEY,
330
- from_context_id VARCHAR,
331
- to_context_id VARCHAR,
332
- continuity_score FLOAT,
333
- transition_type VARCHAR,
334
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
335
- )
336
- `);
337
- await dbRun(this.db, `
338
- CREATE TABLE IF NOT EXISTS consolidated_rules (
339
- rule_id VARCHAR PRIMARY KEY,
340
- rule TEXT NOT NULL,
341
- topics JSON,
342
- source_memory_ids JSON,
343
- source_events JSON,
344
- confidence FLOAT DEFAULT 0.5,
345
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
346
- )
347
- `);
348
- await dbRun(this.db, `
349
- CREATE TABLE IF NOT EXISTS endless_config (
350
- key VARCHAR PRIMARY KEY,
351
- value JSON,
352
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
353
- )
354
- `);
355
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_type ON entries(entry_type)`);
356
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_stage ON entries(stage)`);
357
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entries_canonical ON entries(canonical_key)`);
358
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entities_type_key ON entities(entity_type, canonical_key)`);
359
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_entities_status ON entities(status)`);
360
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src_id, rel_type)`);
361
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_dst ON edges(dst_id, rel_type)`);
362
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_edges_rel ON edges(rel_type)`);
363
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_outbox_status ON vector_outbox(status)`);
364
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_expires ON working_set(expires_at)`);
365
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_working_set_relevance ON working_set(relevance_score DESC)`);
366
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_confidence ON consolidated_memories(confidence DESC)`);
367
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_consolidated_rules_confidence ON consolidated_rules(confidence DESC)`);
368
- await dbRun(this.db, `CREATE INDEX IF NOT EXISTS idx_continuity_created ON continuity_log(created_at)`);
369
- this.initialized = true;
370
- }
371
- /**
372
- * Append event to store (AXIOMMIND Principle 2: Append-only)
373
- * Returns existing event ID if duplicate (Principle 3: Idempotency)
374
- */
375
- async append(input) {
376
- await this.initialize();
377
- const canonicalKey = makeCanonicalKey(input.content);
378
- const dedupeKey = makeDedupeKey(input.content, input.sessionId);
379
- const existing = await dbAll(
380
- this.db,
381
- `SELECT event_id FROM event_dedup WHERE dedupe_key = ?`,
382
- [dedupeKey]
383
- );
384
- if (existing.length > 0) {
385
- return {
386
- success: true,
387
- eventId: existing[0].event_id,
388
- isDuplicate: true
389
- };
390
- }
391
- const id = randomUUID();
392
- const timestamp = input.timestamp.toISOString();
393
- try {
394
- await dbRun(
395
- this.db,
396
- `INSERT INTO events (id, event_type, session_id, timestamp, content, canonical_key, dedupe_key, metadata)
397
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
398
- [
399
- id,
400
- input.eventType,
401
- input.sessionId,
402
- timestamp,
403
- input.content,
404
- canonicalKey,
405
- dedupeKey,
406
- JSON.stringify(input.metadata || {})
407
- ]
408
- );
409
- await dbRun(
410
- this.db,
411
- `INSERT INTO event_dedup (dedupe_key, event_id) VALUES (?, ?)`,
412
- [dedupeKey, id]
413
- );
414
- await dbRun(
415
- this.db,
416
- `INSERT INTO memory_levels (event_id, level) VALUES (?, 'L0')`,
417
- [id]
418
- );
419
- return { success: true, eventId: id, isDuplicate: false };
420
- } catch (error) {
421
- return {
422
- success: false,
423
- error: error instanceof Error ? error.message : String(error)
424
- };
425
- }
426
- }
427
- /**
428
- * Get events by session ID
429
- */
430
- async getSessionEvents(sessionId) {
431
- await this.initialize();
432
- const rows = await dbAll(
433
- this.db,
434
- `SELECT * FROM events WHERE session_id = ? ORDER BY timestamp ASC`,
435
- [sessionId]
436
- );
437
- return rows.map(this.rowToEvent);
438
- }
439
- /**
440
- * Get recent events
441
- */
442
- async getRecentEvents(limit = 100) {
443
- await this.initialize();
444
- const rows = await dbAll(
445
- this.db,
446
- `SELECT * FROM events ORDER BY timestamp DESC LIMIT ?`,
447
- [limit]
448
- );
449
- return rows.map(this.rowToEvent);
450
- }
451
- /**
452
- * Get event by ID
453
- */
454
- async getEvent(id) {
455
- await this.initialize();
456
- const rows = await dbAll(
457
- this.db,
458
- `SELECT * FROM events WHERE id = ?`,
459
- [id]
460
- );
461
- if (rows.length === 0)
462
- return null;
463
- return this.rowToEvent(rows[0]);
464
- }
465
- /**
466
- * Create or update session
467
- */
468
- async upsertSession(session) {
469
- await this.initialize();
470
- const existing = await dbAll(
471
- this.db,
472
- `SELECT id FROM sessions WHERE id = ?`,
473
- [session.id]
474
- );
475
- if (existing.length === 0) {
476
- await dbRun(
477
- this.db,
478
- `INSERT INTO sessions (id, started_at, project_path, tags)
479
- VALUES (?, ?, ?, ?)`,
480
- [
481
- session.id,
482
- (session.startedAt || /* @__PURE__ */ new Date()).toISOString(),
483
- session.projectPath || null,
484
- JSON.stringify(session.tags || [])
485
- ]
486
- );
487
- } else {
488
- const updates = [];
489
- const values = [];
490
- if (session.endedAt) {
491
- updates.push("ended_at = ?");
492
- values.push(session.endedAt.toISOString());
493
- }
494
- if (session.summary) {
495
- updates.push("summary = ?");
496
- values.push(session.summary);
497
- }
498
- if (session.tags) {
499
- updates.push("tags = ?");
500
- values.push(JSON.stringify(session.tags));
501
- }
502
- if (updates.length > 0) {
503
- values.push(session.id);
504
- await dbRun(
505
- this.db,
506
- `UPDATE sessions SET ${updates.join(", ")} WHERE id = ?`,
507
- values
508
- );
509
- }
510
- }
511
- }
512
- /**
513
- * Get session by ID
514
- */
515
- async getSession(id) {
516
- await this.initialize();
517
- const rows = await dbAll(
518
- this.db,
519
- `SELECT * FROM sessions WHERE id = ?`,
520
- [id]
521
- );
522
- if (rows.length === 0)
523
- return null;
524
- const row = rows[0];
525
- return {
526
- id: row.id,
527
- startedAt: toDate(row.started_at),
528
- endedAt: row.ended_at ? toDate(row.ended_at) : void 0,
529
- projectPath: row.project_path,
530
- summary: row.summary,
531
- tags: row.tags ? JSON.parse(row.tags) : void 0
532
- };
533
- }
534
- /**
535
- * Add to embedding outbox (Single-Writer Pattern)
536
- */
537
- async enqueueForEmbedding(eventId, content) {
538
- await this.initialize();
539
- const id = randomUUID();
540
- await dbRun(
541
- this.db,
542
- `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
543
- VALUES (?, ?, ?, 'pending', 0)`,
544
- [id, eventId, content]
545
- );
546
- return id;
547
- }
548
- /**
549
- * Get pending outbox items
550
- */
551
- async getPendingOutboxItems(limit = 32) {
552
- await this.initialize();
553
- const pending = await dbAll(
554
- this.db,
555
- `SELECT * FROM embedding_outbox
556
- WHERE status = 'pending'
557
- ORDER BY created_at
558
- LIMIT ?`,
559
- [limit]
560
- );
561
- if (pending.length === 0)
562
- return [];
563
- const ids = pending.map((r) => r.id);
564
- const placeholders = ids.map(() => "?").join(",");
565
- await dbRun(
566
- this.db,
567
- `UPDATE embedding_outbox SET status = 'processing' WHERE id IN (${placeholders})`,
568
- ids
569
- );
570
- return pending.map((row) => ({
571
- id: row.id,
572
- eventId: row.event_id,
573
- content: row.content,
574
- status: "processing",
575
- retryCount: row.retry_count,
576
- createdAt: toDate(row.created_at),
577
- errorMessage: row.error_message
578
- }));
579
- }
580
- /**
581
- * Mark outbox items as done
582
- */
583
- async completeOutboxItems(ids) {
584
- if (ids.length === 0)
585
- return;
586
- const placeholders = ids.map(() => "?").join(",");
587
- await dbRun(
588
- this.db,
589
- `DELETE FROM embedding_outbox WHERE id IN (${placeholders})`,
590
- ids
591
- );
592
- }
593
- /**
594
- * Mark outbox items as failed
595
- */
596
- async failOutboxItems(ids, error) {
597
- if (ids.length === 0)
598
- return;
599
- const placeholders = ids.map(() => "?").join(",");
600
- await dbRun(
601
- this.db,
602
- `UPDATE embedding_outbox
603
- SET status = CASE WHEN retry_count >= 3 THEN 'failed' ELSE 'pending' END,
604
- retry_count = retry_count + 1,
605
- error_message = ?
606
- WHERE id IN (${placeholders})`,
607
- [error, ...ids]
608
- );
609
- }
610
- /**
611
- * Update memory level
612
- */
613
- async updateMemoryLevel(eventId, level) {
614
- await this.initialize();
615
- await dbRun(
616
- this.db,
617
- `UPDATE memory_levels SET level = ?, promoted_at = CURRENT_TIMESTAMP WHERE event_id = ?`,
618
- [level, eventId]
619
- );
620
- }
621
- /**
622
- * Get memory level statistics
623
- */
624
- async getLevelStats() {
625
- await this.initialize();
626
- const rows = await dbAll(
627
- this.db,
628
- `SELECT level, COUNT(*) as count FROM memory_levels GROUP BY level`
629
- );
630
- return rows;
631
- }
632
- /**
633
- * Get events by memory level
634
- */
635
- async getEventsByLevel(level, options) {
636
- await this.initialize();
637
- const limit = options?.limit || 50;
638
- const offset = options?.offset || 0;
639
- const rows = await dbAll(
640
- this.db,
641
- `SELECT e.* FROM events e
642
- INNER JOIN memory_levels ml ON e.id = ml.event_id
643
- WHERE ml.level = ?
644
- ORDER BY e.timestamp DESC
645
- LIMIT ? OFFSET ?`,
646
- [level, limit, offset]
647
- );
648
- return rows.map((row) => this.rowToEvent(row));
649
- }
650
- /**
651
- * Get memory level for a specific event
652
- */
653
- async getEventLevel(eventId) {
654
- await this.initialize();
655
- const rows = await dbAll(
656
- this.db,
657
- `SELECT level FROM memory_levels WHERE event_id = ?`,
658
- [eventId]
659
- );
660
- return rows.length > 0 ? rows[0].level : null;
661
- }
662
- // ============================================================
663
- // Endless Mode Helper Methods
664
- // ============================================================
665
- /**
666
- * Get database instance for Endless Mode stores
667
- */
668
- getDatabase() {
669
- return this.db;
670
- }
671
- /**
672
- * Get config value for endless mode
673
- */
674
- async getEndlessConfig(key) {
675
- await this.initialize();
676
- const rows = await dbAll(
677
- this.db,
678
- `SELECT value FROM endless_config WHERE key = ?`,
679
- [key]
680
- );
681
- if (rows.length === 0)
682
- return null;
683
- return JSON.parse(rows[0].value);
684
- }
685
- /**
686
- * Set config value for endless mode
687
- */
688
- async setEndlessConfig(key, value) {
689
- await this.initialize();
690
- await dbRun(
691
- this.db,
692
- `INSERT OR REPLACE INTO endless_config (key, value, updated_at)
693
- VALUES (?, ?, CURRENT_TIMESTAMP)`,
694
- [key, JSON.stringify(value)]
695
- );
696
- }
697
- /**
698
- * Get all sessions
699
- */
700
- async getAllSessions() {
701
- await this.initialize();
702
- const rows = await dbAll(
703
- this.db,
704
- `SELECT * FROM sessions ORDER BY started_at DESC`
705
- );
706
- return rows.map((row) => ({
707
- id: row.id,
708
- startedAt: toDate(row.started_at),
709
- endedAt: row.ended_at ? toDate(row.ended_at) : void 0,
710
- projectPath: row.project_path,
711
- summary: row.summary,
712
- tags: row.tags ? JSON.parse(row.tags) : void 0
713
- }));
714
- }
715
- /**
716
- * Increment access count for events (stub for compatibility)
717
- */
718
- async incrementAccessCount(eventIds) {
719
- return Promise.resolve();
720
- }
721
- /**
722
- * Get most accessed memories (stub for compatibility)
723
- */
724
- async getMostAccessed(limit = 10) {
725
- return [];
726
- }
727
- /**
728
- * Close database connection
729
- */
730
- async close() {
731
- await dbClose(this.db);
14
+ // src/core/sqlite-event-store.ts
15
+ import { randomUUID } from "crypto";
16
+
17
+ // src/core/canonical-key.ts
18
+ import { createHash } from "crypto";
19
+ var MAX_KEY_LENGTH = 200;
20
+ function makeCanonicalKey(title, context) {
21
+ let normalized = title.normalize("NFKC");
22
+ normalized = normalized.toLowerCase();
23
+ normalized = normalized.replace(/[^\p{L}\p{N}\s]/gu, "");
24
+ normalized = normalized.replace(/\s+/g, " ").trim();
25
+ let key = normalized;
26
+ if (context?.project) {
27
+ key = `${context.project}::${key}`;
732
28
  }
733
- /**
734
- * Convert database row to MemoryEvent
735
- */
736
- rowToEvent(row) {
737
- return {
738
- id: row.id,
739
- eventType: row.event_type,
740
- sessionId: row.session_id,
741
- timestamp: toDate(row.timestamp),
742
- content: row.content,
743
- canonicalKey: row.canonical_key,
744
- dedupeKey: row.dedupe_key,
745
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0
746
- };
29
+ if (key.length > MAX_KEY_LENGTH) {
30
+ const hashSuffix = createHash("md5").update(key).digest("hex").slice(0, 8);
31
+ key = key.slice(0, MAX_KEY_LENGTH - 9) + "_" + hashSuffix;
747
32
  }
748
- };
749
-
750
- // src/core/sqlite-event-store.ts
751
- import { randomUUID as randomUUID2 } from "crypto";
33
+ return key;
34
+ }
35
+ function makeDedupeKey(content, sessionId) {
36
+ const contentHash = createHash("sha256").update(content).digest("hex");
37
+ return `${sessionId}:${contentHash}`;
38
+ }
752
39
 
753
40
  // src/core/sqlite-wrapper.ts
754
41
  import Database from "better-sqlite3";
@@ -1263,7 +550,7 @@ var SQLiteEventStore = class {
1263
550
  isDuplicate: true
1264
551
  };
1265
552
  }
1266
- const id = randomUUID2();
553
+ const id = randomUUID();
1267
554
  const timestamp = toSQLiteTimestamp(input.timestamp);
1268
555
  try {
1269
556
  const metadata = input.metadata || {};
@@ -1317,6 +604,29 @@ var SQLiteEventStore = class {
1317
604
  };
1318
605
  }
1319
606
  }
607
+ /**
608
+ * Get session IDs that have events but no session_summary event.
609
+ * Used to backfill summaries for sessions that ended without Stop hook.
610
+ */
611
+ async getSessionsWithoutSummary(currentSessionId, limit = 5) {
612
+ await this.initialize();
613
+ const rows = sqliteAll(
614
+ this.db,
615
+ `SELECT DISTINCT e.session_id
616
+ FROM events e
617
+ WHERE e.session_id != ?
618
+ AND e.event_type != 'session_summary'
619
+ AND e.session_id NOT IN (
620
+ SELECT DISTINCT session_id FROM events WHERE event_type = 'session_summary'
621
+ )
622
+ GROUP BY e.session_id
623
+ HAVING COUNT(*) >= 3
624
+ ORDER BY MAX(e.timestamp) DESC
625
+ LIMIT ?`,
626
+ [currentSessionId, limit]
627
+ );
628
+ return rows.map((r) => r.session_id);
629
+ }
1320
630
  /**
1321
631
  * Get events by session ID
1322
632
  */
@@ -1544,7 +854,7 @@ var SQLiteEventStore = class {
1544
854
  */
1545
855
  async enqueueForEmbedding(eventId, content) {
1546
856
  await this.initialize();
1547
- const id = randomUUID2();
857
+ const id = randomUUID();
1548
858
  sqliteRun(
1549
859
  this.db,
1550
860
  `INSERT INTO embedding_outbox (id, event_id, content, status, retry_count)
@@ -1825,7 +1135,7 @@ var SQLiteEventStore = class {
1825
1135
  if (this.readOnly)
1826
1136
  return;
1827
1137
  await this.initialize();
1828
- const id = randomUUID2();
1138
+ const id = randomUUID();
1829
1139
  sqliteRun(
1830
1140
  this.db,
1831
1141
  `INSERT INTO memory_helpfulness (id, event_id, session_id, retrieval_score, query_preview, created_at)
@@ -1833,6 +1143,21 @@ var SQLiteEventStore = class {
1833
1143
  [id, eventId, sessionId, score, query.slice(0, 100)]
1834
1144
  );
1835
1145
  }
1146
+ /**
1147
+ * Get session IDs that have unevaluated retrievals (measured_at IS NULL).
1148
+ * Excludes the current session. Used to backfill sessions that ended without Stop hook.
1149
+ */
1150
+ async getUnevaluatedSessions(currentSessionId, limit = 5) {
1151
+ await this.initialize();
1152
+ const rows = sqliteAll(
1153
+ this.db,
1154
+ `SELECT DISTINCT session_id FROM memory_helpfulness
1155
+ WHERE measured_at IS NULL AND session_id != ?
1156
+ ORDER BY created_at DESC LIMIT ?`,
1157
+ [currentSessionId, limit]
1158
+ );
1159
+ return rows.map((r) => r.session_id);
1160
+ }
1836
1161
  /**
1837
1162
  * Evaluate helpfulness for all retrievals in a session
1838
1163
  * Called at session end - uses behavioral signals to compute score
@@ -2031,7 +1356,7 @@ var SQLiteEventStore = class {
2031
1356
  }
2032
1357
  async recordRetrievalTrace(input) {
2033
1358
  await this.initialize();
2034
- const traceId = randomUUID2();
1359
+ const traceId = randomUUID();
2035
1360
  sqliteRun(
2036
1361
  this.db,
2037
1362
  `INSERT INTO retrieval_traces (
@@ -2285,169 +1610,6 @@ var SQLiteEventStore = class {
2285
1610
  }
2286
1611
  };
2287
1612
 
2288
- // src/core/sync-worker.ts
2289
- var DEFAULT_CONFIG = {
2290
- intervalMs: 3e4,
2291
- batchSize: 500,
2292
- maxRetries: 3,
2293
- retryDelayMs: 5e3
2294
- };
2295
- var SyncWorker = class {
2296
- constructor(sqliteStore, duckdbStore, config) {
2297
- this.sqliteStore = sqliteStore;
2298
- this.duckdbStore = duckdbStore;
2299
- this.config = { ...DEFAULT_CONFIG, ...config };
2300
- }
2301
- config;
2302
- intervalHandle = null;
2303
- running = false;
2304
- stats = {
2305
- lastSyncAt: null,
2306
- eventsSynced: 0,
2307
- sessionsSynced: 0,
2308
- errors: 0,
2309
- status: "idle"
2310
- };
2311
- /**
2312
- * Start the sync worker
2313
- */
2314
- start() {
2315
- if (this.running)
2316
- return;
2317
- this.running = true;
2318
- this.stats.status = "idle";
2319
- this.syncNow().catch((err) => {
2320
- console.error("[SyncWorker] Initial sync failed:", err);
2321
- });
2322
- this.intervalHandle = setInterval(() => {
2323
- this.syncNow().catch((err) => {
2324
- console.error("[SyncWorker] Periodic sync failed:", err);
2325
- });
2326
- }, this.config.intervalMs);
2327
- }
2328
- /**
2329
- * Stop the sync worker
2330
- */
2331
- stop() {
2332
- this.running = false;
2333
- this.stats.status = "stopped";
2334
- if (this.intervalHandle) {
2335
- clearInterval(this.intervalHandle);
2336
- this.intervalHandle = null;
2337
- }
2338
- }
2339
- /**
2340
- * Trigger immediate sync
2341
- */
2342
- async syncNow() {
2343
- if (this.stats.status === "syncing") {
2344
- return;
2345
- }
2346
- this.stats.status = "syncing";
2347
- try {
2348
- await this.syncEvents();
2349
- await this.syncSessions();
2350
- this.stats.lastSyncAt = /* @__PURE__ */ new Date();
2351
- this.stats.status = "idle";
2352
- } catch (error) {
2353
- this.stats.errors++;
2354
- this.stats.status = "error";
2355
- throw error;
2356
- }
2357
- }
2358
- /**
2359
- * Sync events from SQLite to DuckDB
2360
- */
2361
- async syncEvents() {
2362
- const targetName = "duckdb_analytics";
2363
- const position = await this.sqliteStore.getSyncPosition(targetName);
2364
- const lastTimestamp = position.lastTimestamp || "1970-01-01T00:00:00.000Z";
2365
- let hasMore = true;
2366
- let totalSynced = 0;
2367
- while (hasMore) {
2368
- const events = await this.sqliteStore.getEventsSince(lastTimestamp, this.config.batchSize);
2369
- if (events.length === 0) {
2370
- hasMore = false;
2371
- break;
2372
- }
2373
- await this.retryWithBackoff(async () => {
2374
- for (const event of events) {
2375
- await this.insertEventToDuckDB(event);
2376
- }
2377
- });
2378
- totalSynced += events.length;
2379
- const lastEvent = events[events.length - 1];
2380
- await this.sqliteStore.updateSyncPosition(
2381
- targetName,
2382
- lastEvent.id,
2383
- lastEvent.timestamp.toISOString()
2384
- );
2385
- hasMore = events.length === this.config.batchSize;
2386
- }
2387
- this.stats.eventsSynced += totalSynced;
2388
- }
2389
- /**
2390
- * Sync sessions from SQLite to DuckDB
2391
- */
2392
- async syncSessions() {
2393
- const sessions = await this.sqliteStore.getAllSessions();
2394
- for (const session of sessions) {
2395
- await this.retryWithBackoff(async () => {
2396
- await this.duckdbStore.upsertSession(session);
2397
- });
2398
- }
2399
- this.stats.sessionsSynced = sessions.length;
2400
- }
2401
- /**
2402
- * Insert a single event into DuckDB
2403
- */
2404
- async insertEventToDuckDB(event) {
2405
- await this.duckdbStore.append({
2406
- eventType: event.eventType,
2407
- sessionId: event.sessionId,
2408
- timestamp: event.timestamp,
2409
- content: event.content,
2410
- metadata: event.metadata
2411
- });
2412
- }
2413
- /**
2414
- * Retry operation with exponential backoff
2415
- */
2416
- async retryWithBackoff(fn) {
2417
- let lastError = null;
2418
- for (let attempt = 0; attempt < this.config.maxRetries; attempt++) {
2419
- try {
2420
- return await fn();
2421
- } catch (error) {
2422
- lastError = error instanceof Error ? error : new Error(String(error));
2423
- if (attempt < this.config.maxRetries - 1) {
2424
- const delay = this.config.retryDelayMs * Math.pow(2, attempt);
2425
- await this.sleep(delay);
2426
- }
2427
- }
2428
- }
2429
- throw lastError;
2430
- }
2431
- /**
2432
- * Sleep utility
2433
- */
2434
- sleep(ms) {
2435
- return new Promise((resolve2) => setTimeout(resolve2, ms));
2436
- }
2437
- /**
2438
- * Get sync statistics
2439
- */
2440
- getStats() {
2441
- return { ...this.stats };
2442
- }
2443
- /**
2444
- * Check if worker is running
2445
- */
2446
- isRunning() {
2447
- return this.running;
2448
- }
2449
- };
2450
-
2451
1613
  // src/core/vector-store.ts
2452
1614
  import * as lancedb from "@lancedb/lancedb";
2453
1615
  var VectorStore = class {
@@ -2620,7 +1782,7 @@ var VectorStore = class {
2620
1782
 
2621
1783
  // src/core/embedder.ts
2622
1784
  import { pipeline } from "@huggingface/transformers";
2623
- var Embedder = class {
1785
+ var Embedder = class _Embedder {
2624
1786
  pipeline = null;
2625
1787
  modelName;
2626
1788
  activeModelName;
@@ -2651,6 +1813,11 @@ var Embedder = class {
2651
1813
  this.initialized = true;
2652
1814
  }
2653
1815
  }
1816
+ // ~4 chars per token; 512 tokens * 4 = 2048, use 2000 to be safe
1817
+ static MAX_CHARS = 2e3;
1818
+ truncate(text) {
1819
+ return text.length > _Embedder.MAX_CHARS ? text.slice(0, _Embedder.MAX_CHARS) : text;
1820
+ }
2654
1821
  /**
2655
1822
  * Generate embedding for a single text
2656
1823
  */
@@ -2659,10 +1826,11 @@ var Embedder = class {
2659
1826
  if (!this.pipeline) {
2660
1827
  throw new Error("Embedding pipeline not initialized");
2661
1828
  }
2662
- const output = await this.pipeline(text, {
1829
+ const output = await this.pipeline(this.truncate(text), {
2663
1830
  pooling: "mean",
2664
1831
  normalize: true,
2665
- truncation: true
1832
+ truncation: true,
1833
+ max_length: 512
2666
1834
  });
2667
1835
  const vector = Array.from(output.data);
2668
1836
  return {
@@ -2684,10 +1852,11 @@ var Embedder = class {
2684
1852
  for (let i = 0; i < texts.length; i += batchSize) {
2685
1853
  const batch = texts.slice(i, i + batchSize);
2686
1854
  for (const text of batch) {
2687
- const output = await this.pipeline(text, {
1855
+ const output = await this.pipeline(this.truncate(text), {
2688
1856
  pooling: "mean",
2689
1857
  normalize: true,
2690
- truncation: true
1858
+ truncation: true,
1859
+ max_length: 512
2691
1860
  });
2692
1861
  const vector = Array.from(output.data);
2693
1862
  results.push({
@@ -2728,8 +1897,34 @@ function getDefaultEmbedder() {
2728
1897
  return defaultEmbedder;
2729
1898
  }
2730
1899
 
1900
+ // src/core/db-wrapper.ts
1901
+ import BetterSqlite3 from "better-sqlite3";
1902
+ function toDate(value) {
1903
+ if (value instanceof Date)
1904
+ return value;
1905
+ if (typeof value === "string")
1906
+ return new Date(value);
1907
+ if (typeof value === "number")
1908
+ return new Date(value);
1909
+ return new Date(String(value));
1910
+ }
1911
+ function createDatabase(dbPath, options) {
1912
+ return new BetterSqlite3(dbPath, { readonly: options?.readOnly });
1913
+ }
1914
+ function dbRun(db, sql, params = []) {
1915
+ db.prepare(sql).run(...params);
1916
+ return Promise.resolve();
1917
+ }
1918
+ function dbAll(db, sql, params = []) {
1919
+ return Promise.resolve(db.prepare(sql).all(...params));
1920
+ }
1921
+ function dbClose(db) {
1922
+ db.close();
1923
+ return Promise.resolve();
1924
+ }
1925
+
2731
1926
  // src/core/vector-outbox.ts
2732
- var DEFAULT_CONFIG2 = {
1927
+ var DEFAULT_CONFIG = {
2733
1928
  embeddingVersion: "v1",
2734
1929
  maxRetries: 3,
2735
1930
  stuckThresholdMs: 5 * 60 * 1e3,
@@ -2738,7 +1933,7 @@ var DEFAULT_CONFIG2 = {
2738
1933
  };
2739
1934
 
2740
1935
  // src/core/vector-worker.ts
2741
- var DEFAULT_CONFIG3 = {
1936
+ var DEFAULT_CONFIG2 = {
2742
1937
  batchSize: 32,
2743
1938
  pollIntervalMs: 1e3,
2744
1939
  maxRetries: 3
@@ -2755,7 +1950,7 @@ var VectorWorker = class {
2755
1950
  this.eventStore = eventStore;
2756
1951
  this.vectorStore = vectorStore;
2757
1952
  this.embedder = embedder;
2758
- this.config = { ...DEFAULT_CONFIG3, ...config };
1953
+ this.config = { ...DEFAULT_CONFIG2, ...config };
2759
1954
  }
2760
1955
  /**
2761
1956
  * Start the worker polling loop
@@ -2876,7 +2071,7 @@ function createVectorWorker(eventStore, vectorStore, embedder, config) {
2876
2071
  }
2877
2072
 
2878
2073
  // src/core/matcher.ts
2879
- var DEFAULT_CONFIG4 = {
2074
+ var DEFAULT_CONFIG3 = {
2880
2075
  weights: {
2881
2076
  semanticSimilarity: 0.4,
2882
2077
  ftsScore: 0.25,
@@ -2891,9 +2086,9 @@ var Matcher = class {
2891
2086
  config;
2892
2087
  constructor(config = {}) {
2893
2088
  this.config = {
2894
- ...DEFAULT_CONFIG4,
2089
+ ...DEFAULT_CONFIG3,
2895
2090
  ...config,
2896
- weights: { ...DEFAULT_CONFIG4.weights, ...config.weights }
2091
+ weights: { ...DEFAULT_CONFIG3.weights, ...config.weights }
2897
2092
  };
2898
2093
  }
2899
2094
  /**
@@ -3883,7 +3078,7 @@ function createSharedEventStore(dbPath) {
3883
3078
  }
3884
3079
 
3885
3080
  // src/core/shared-store.ts
3886
- import { randomUUID as randomUUID3 } from "crypto";
3081
+ import { randomUUID as randomUUID2 } from "crypto";
3887
3082
  var SharedStore = class {
3888
3083
  constructor(sharedEventStore) {
3889
3084
  this.sharedEventStore = sharedEventStore;
@@ -3895,7 +3090,7 @@ var SharedStore = class {
3895
3090
  * Promote a verified troubleshooting entry to shared storage
3896
3091
  */
3897
3092
  async promoteEntry(input) {
3898
- const entryId = randomUUID3();
3093
+ const entryId = randomUUID2();
3899
3094
  await dbRun(
3900
3095
  this.db,
3901
3096
  `INSERT INTO shared_troubleshooting (
@@ -4260,7 +3455,7 @@ function createSharedVectorStore(dbPath) {
4260
3455
  }
4261
3456
 
4262
3457
  // src/core/shared-promoter.ts
4263
- import { randomUUID as randomUUID4 } from "crypto";
3458
+ import { randomUUID as randomUUID3 } from "crypto";
4264
3459
  var SharedPromoter = class {
4265
3460
  constructor(sharedStore, sharedVectorStore, embedder, config) {
4266
3461
  this.sharedStore = sharedStore;
@@ -4328,7 +3523,7 @@ var SharedPromoter = class {
4328
3523
  const embeddingContent = this.createEmbeddingContent(input);
4329
3524
  const embedding = await this.embedder.embed(embeddingContent);
4330
3525
  await this.sharedVectorStore.upsert({
4331
- id: randomUUID4(),
3526
+ id: randomUUID3(),
4332
3527
  entryId,
4333
3528
  entryType: "troubleshooting",
4334
3529
  content: embeddingContent,
@@ -4468,7 +3663,7 @@ function createToolObservationEmbedding(toolName, metadata, success) {
4468
3663
  }
4469
3664
 
4470
3665
  // src/core/working-set-store.ts
4471
- import { randomUUID as randomUUID5 } from "crypto";
3666
+ import { randomUUID as randomUUID4 } from "crypto";
4472
3667
  var WorkingSetStore = class {
4473
3668
  constructor(eventStore, config) {
4474
3669
  this.eventStore = eventStore;
@@ -4489,7 +3684,7 @@ var WorkingSetStore = class {
4489
3684
  `INSERT OR REPLACE INTO working_set (id, event_id, added_at, relevance_score, topics, expires_at)
4490
3685
  VALUES (?, ?, CURRENT_TIMESTAMP, ?, ?, ?)`,
4491
3686
  [
4492
- randomUUID5(),
3687
+ randomUUID4(),
4493
3688
  eventId,
4494
3689
  relevanceScore,
4495
3690
  JSON.stringify(topics || []),
@@ -4673,7 +3868,7 @@ function createWorkingSetStore(eventStore, config) {
4673
3868
  }
4674
3869
 
4675
3870
  // src/core/consolidated-store.ts
4676
- import { randomUUID as randomUUID6 } from "crypto";
3871
+ import { randomUUID as randomUUID5 } from "crypto";
4677
3872
  var ConsolidatedStore = class {
4678
3873
  constructor(eventStore) {
4679
3874
  this.eventStore = eventStore;
@@ -4685,7 +3880,7 @@ var ConsolidatedStore = class {
4685
3880
  * Create a new consolidated memory
4686
3881
  */
4687
3882
  async create(input) {
4688
- const memoryId = randomUUID6();
3883
+ const memoryId = randomUUID5();
4689
3884
  await dbRun(
4690
3885
  this.db,
4691
3886
  `INSERT INTO consolidated_memories
@@ -4815,7 +4010,7 @@ var ConsolidatedStore = class {
4815
4010
  * Create a long-term rule promoted from stable summaries
4816
4011
  */
4817
4012
  async createRule(input) {
4818
- const ruleId = randomUUID6();
4013
+ const ruleId = randomUUID5();
4819
4014
  await dbRun(
4820
4015
  this.db,
4821
4016
  `INSERT INTO consolidated_rules
@@ -5337,7 +4532,7 @@ function createConsolidationWorker(workingSetStore, consolidatedStore, config) {
5337
4532
  }
5338
4533
 
5339
4534
  // src/core/continuity-manager.ts
5340
- import { randomUUID as randomUUID7 } from "crypto";
4535
+ import { randomUUID as randomUUID6 } from "crypto";
5341
4536
  var ContinuityManager = class {
5342
4537
  constructor(eventStore, config) {
5343
4538
  this.eventStore = eventStore;
@@ -5491,7 +4686,7 @@ var ContinuityManager = class {
5491
4686
  `INSERT INTO continuity_log
5492
4687
  (log_id, from_context_id, to_context_id, continuity_score, transition_type, created_at)
5493
4688
  VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`,
5494
- [randomUUID7(), previous.id, current.id, score, type]
4689
+ [randomUUID6(), previous.id, current.id, score, type]
5495
4690
  );
5496
4691
  }
5497
4692
  /**
@@ -5600,7 +4795,7 @@ function createContinuityManager(eventStore, config) {
5600
4795
  }
5601
4796
 
5602
4797
  // src/core/graduation-worker.ts
5603
- var DEFAULT_CONFIG5 = {
4798
+ var DEFAULT_CONFIG4 = {
5604
4799
  evaluationIntervalMs: 3e5,
5605
4800
  // 5 minutes
5606
4801
  batchSize: 50,
@@ -5608,7 +4803,7 @@ var DEFAULT_CONFIG5 = {
5608
4803
  // 1 hour cooldown between evaluations
5609
4804
  };
5610
4805
  var GraduationWorker = class {
5611
- constructor(eventStore, graduation, config = DEFAULT_CONFIG5) {
4806
+ constructor(eventStore, graduation, config = DEFAULT_CONFIG4) {
5612
4807
  this.eventStore = eventStore;
5613
4808
  this.graduation = graduation;
5614
4809
  this.config = config;
@@ -5716,7 +4911,7 @@ function createGraduationWorker(eventStore, graduation, config) {
5716
4911
  return new GraduationWorker(
5717
4912
  eventStore,
5718
4913
  graduation,
5719
- { ...DEFAULT_CONFIG5, ...config }
4914
+ { ...DEFAULT_CONFIG4, ...config }
5720
4915
  );
5721
4916
  }
5722
4917
 
@@ -5954,9 +5149,6 @@ function getSessionProject(sessionId) {
5954
5149
  var MemoryService = class {
5955
5150
  // Primary store: SQLite (WAL mode) - for hooks, always available
5956
5151
  sqliteStore;
5957
- // Analytics store: DuckDB - for server reads (optional, synced from SQLite)
5958
- analyticsStore;
5959
- syncWorker = null;
5960
5152
  vectorStore;
5961
5153
  embedder;
5962
5154
  matcher;
@@ -5982,6 +5174,7 @@ var MemoryService = class {
5982
5174
  projectPath = null;
5983
5175
  readOnly;
5984
5176
  lightweightMode;
5177
+ embeddingOnly;
5985
5178
  mdMirror;
5986
5179
  storagePath;
5987
5180
  constructor(config) {
@@ -5989,6 +5182,7 @@ var MemoryService = class {
5989
5182
  this.storagePath = storagePath;
5990
5183
  this.readOnly = config.readOnly ?? false;
5991
5184
  this.lightweightMode = config.lightweightMode ?? false;
5185
+ this.embeddingOnly = config.embeddingOnly ?? false;
5992
5186
  this.mdMirror = new MarkdownMirror2(process.cwd());
5993
5187
  if (!this.readOnly && !fs4.existsSync(storagePath)) {
5994
5188
  fs4.mkdirSync(storagePath, { recursive: true });
@@ -6003,24 +5197,6 @@ var MemoryService = class {
6003
5197
  markdownMirrorRoot: storagePath
6004
5198
  }
6005
5199
  );
6006
- const analyticsEnabled = config.analyticsEnabled ?? this.readOnly;
6007
- if (!analyticsEnabled) {
6008
- this.analyticsStore = null;
6009
- } else if (this.readOnly) {
6010
- try {
6011
- this.analyticsStore = new EventStore(
6012
- path3.join(storagePath, "analytics.duckdb"),
6013
- { readOnly: true }
6014
- );
6015
- } catch {
6016
- this.analyticsStore = null;
6017
- }
6018
- } else {
6019
- this.analyticsStore = new EventStore(
6020
- path3.join(storagePath, "analytics.duckdb"),
6021
- { readOnly: false }
6022
- );
6023
- }
6024
5200
  this.vectorStore = new VectorStore(path3.join(storagePath, "vectors"));
6025
5201
  const embeddingModel = config.embeddingModel || process.env.CLAUDE_MEMORY_EMBEDDING_MODEL;
6026
5202
  this.embedder = embeddingModel ? new Embedder(embeddingModel) : getDefaultEmbedder();
@@ -6046,13 +5222,6 @@ var MemoryService = class {
6046
5222
  this.initialized = true;
6047
5223
  return;
6048
5224
  }
6049
- if (this.analyticsStore) {
6050
- try {
6051
- await this.analyticsStore.initialize();
6052
- } catch (error) {
6053
- console.warn("[MemoryService] Analytics store (DuckDB) initialization failed, using SQLite for reads:", error);
6054
- }
6055
- }
6056
5225
  await this.vectorStore.initialize();
6057
5226
  await this.embedder.initialize();
6058
5227
  if (!this.readOnly) {
@@ -6062,19 +5231,13 @@ var MemoryService = class {
6062
5231
  this.embedder
6063
5232
  );
6064
5233
  this.vectorWorker.start();
6065
- this.retriever.setGraduationPipeline(this.graduation);
6066
- this.graduationWorker = createGraduationWorker(
6067
- this.sqliteStore,
6068
- this.graduation
6069
- );
6070
- this.graduationWorker.start();
6071
- if (this.analyticsStore) {
6072
- this.syncWorker = new SyncWorker(
5234
+ if (!this.embeddingOnly) {
5235
+ this.retriever.setGraduationPipeline(this.graduation);
5236
+ this.graduationWorker = createGraduationWorker(
6073
5237
  this.sqliteStore,
6074
- this.analyticsStore,
6075
- { intervalMs: 3e4, batchSize: 500 }
5238
+ this.graduation
6076
5239
  );
6077
- this.syncWorker.start();
5240
+ this.graduationWorker.start();
6078
5241
  }
6079
5242
  const savedMode = await this.sqliteStore.getEndlessConfig("mode");
6080
5243
  if (savedMode === "endless") {
@@ -6271,6 +5434,57 @@ var MemoryService = class {
6271
5434
  }
6272
5435
  );
6273
5436
  }
5437
+ /**
5438
+ * Backfill session summaries for recent sessions that are missing them.
5439
+ * Called from session-start hook to catch sessions that ended without Stop hook.
5440
+ */
5441
+ async backfillMissingSummaries(currentSessionId, limit = 5) {
5442
+ await this.initialize();
5443
+ const recentSessionIds = await this.sqliteStore.getSessionsWithoutSummary(currentSessionId, limit);
5444
+ for (const sid of recentSessionIds) {
5445
+ try {
5446
+ await this.generateSessionSummary(sid);
5447
+ } catch {
5448
+ }
5449
+ }
5450
+ }
5451
+ /**
5452
+ * Generate a rule-based session summary from stored events.
5453
+ * Called at session end (Stop hook) when no LLM-generated summary exists.
5454
+ * Skips if a summary already exists for this session.
5455
+ */
5456
+ async generateSessionSummary(sessionId) {
5457
+ await this.initialize();
5458
+ const events = await this.sqliteStore.getSessionEvents(sessionId);
5459
+ if (events.length < 3)
5460
+ return;
5461
+ const hasSummary = events.some((e) => e.eventType === "session_summary");
5462
+ if (hasSummary)
5463
+ return;
5464
+ const prompts = events.filter((e) => e.eventType === "user_prompt");
5465
+ const toolObs = events.filter((e) => e.eventType === "tool_observation");
5466
+ const toolNames = [...new Set(
5467
+ toolObs.map((e) => e.metadata?.toolName).filter(Boolean)
5468
+ )];
5469
+ const errorObs = toolObs.filter((e) => {
5470
+ const meta = e.metadata;
5471
+ return meta?.exitCode !== void 0 && meta.exitCode !== 0;
5472
+ });
5473
+ const datePart = events[0].timestamp.toISOString().split("T")[0];
5474
+ const parts = [`[${datePart}] ${prompts.length}\uD134 \uC138\uC158.`];
5475
+ if (prompts.length > 0) {
5476
+ const firstPrompt = prompts[0].content.slice(0, 120).replace(/\n/g, " ");
5477
+ parts.push(`\uC8FC\uC694 \uC791\uC5C5: ${firstPrompt}`);
5478
+ }
5479
+ if (toolNames.length > 0) {
5480
+ parts.push(`\uC0AC\uC6A9 \uD234: ${toolNames.slice(0, 6).join(", ")}`);
5481
+ }
5482
+ if (errorObs.length > 0) {
5483
+ parts.push(`\uC624\uB958 ${errorObs.length}\uAC74 \uBC1C\uC0DD`);
5484
+ }
5485
+ const summary = parts.join(". ");
5486
+ await this.storeSessionSummary(sessionId, summary, { generated: "rule-based", eventCount: events.length });
5487
+ }
6274
5488
  /**
6275
5489
  * Store a tool observation
6276
5490
  */
@@ -6798,6 +6012,20 @@ var MemoryService = class {
6798
6012
  await this.initialize();
6799
6013
  await this.sqliteStore.recordRetrieval(eventId, sessionId, score, query);
6800
6014
  }
6015
+ /**
6016
+ * Record a query-level retrieval trace (used by user-prompt-submit hook).
6017
+ * Feeds the retrieval_traces table that powers dashboard stats.
6018
+ */
6019
+ async recordQueryTrace(input) {
6020
+ await this.initialize();
6021
+ await this.sqliteStore.recordRetrievalTrace({
6022
+ ...input,
6023
+ projectHash: this.projectHash || void 0,
6024
+ candidateDetails: [],
6025
+ selectedDetails: [],
6026
+ fallbackTrace: []
6027
+ });
6028
+ }
6801
6029
  /**
6802
6030
  * Evaluate helpfulness of retrievals in a session (called at session end)
6803
6031
  */
@@ -6805,6 +6033,20 @@ var MemoryService = class {
6805
6033
  await this.initialize();
6806
6034
  await this.sqliteStore.evaluateSessionHelpfulness(sessionId);
6807
6035
  }
6036
+ /**
6037
+ * Backfill helpfulness evaluation for sessions that ended without Stop hook.
6038
+ * Call on first turn of a new session to catch missed evaluations.
6039
+ */
6040
+ async evaluatePendingSessions(currentSessionId) {
6041
+ await this.initialize();
6042
+ const sessions = await this.sqliteStore.getUnevaluatedSessions(currentSessionId, 5);
6043
+ for (const sid of sessions) {
6044
+ try {
6045
+ await this.sqliteStore.evaluateSessionHelpfulness(sid);
6046
+ } catch {
6047
+ }
6048
+ }
6049
+ }
6808
6050
  /**
6809
6051
  * Get most helpful memories ranked by helpfulness score
6810
6052
  */
@@ -7069,16 +6311,10 @@ var MemoryService = class {
7069
6311
  if (this.vectorWorker) {
7070
6312
  this.vectorWorker.stop();
7071
6313
  }
7072
- if (this.syncWorker) {
7073
- this.syncWorker.stop();
7074
- }
7075
6314
  if (this.sharedEventStore) {
7076
6315
  await this.sharedEventStore.close();
7077
6316
  }
7078
6317
  await this.sqliteStore.close();
7079
- if (this.analyticsStore) {
7080
- await this.analyticsStore.close();
7081
- }
7082
6318
  }
7083
6319
  /**
7084
6320
  * Expand ~ to home directory