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