claude-mem-lite 3.40.0 → 3.41.0

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.
@@ -10,7 +10,7 @@
10
10
  "plugins": [
11
11
  {
12
12
  "name": "claude-mem-lite",
13
- "version": "3.40.0",
13
+ "version": "3.41.0",
14
14
  "source": "./",
15
15
  "description": "Persistent long-term memory for Claude Code via MCP — captures coding decisions, bugfixes, and context across sessions. Hybrid FTS5 + TF-IDF search with episode batching. Single SQLite DB, no external services. A lighter, lower-cost alternative to claude-mem (episode batching + a smaller model; cost savings are an internal estimate, not a measured benchmark)."
16
16
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem-lite",
3
- "version": "3.40.0",
3
+ "version": "3.41.0",
4
4
  "description": "Persistent long-term memory for Claude Code via MCP — captures coding decisions, bugfixes, and context across sessions. Hybrid FTS5 + TF-IDF search with episode batching. Single SQLite DB, no external services. A lighter, lower-cost alternative to claude-mem (episode batching + a smaller model; cost savings are an internal estimate, not a measured benchmark).",
5
5
  "author": {
6
6
  "name": "sdsrss"
package/hook-context.mjs CHANGED
@@ -305,6 +305,7 @@ export function buildSessionContextLines(db, project, now = new Date(), currentC
305
305
  FROM observations
306
306
  WHERE COALESCE(compressed_into, 0) = 0
307
307
  AND superseded_at IS NULL
308
+ AND ${notLowSignalTitleClause('')}
308
309
  AND (
309
310
  (created_at_epoch > ? AND importance >= 1)
310
311
  OR (created_at_epoch > ? AND importance >= 2)
package/hook-handoff.mjs CHANGED
@@ -271,13 +271,28 @@ export function detectContinuationIntent(db, promptText, project, currentCcSessi
271
271
  try {
272
272
  const currentSha = gitStateModule.readGitState({ cwd: process.cwd() }).headSha;
273
273
  if (currentSha) {
274
- const anchor = db.prepare(`
275
- SELECT created_at_epoch FROM session_handoffs
276
- WHERE project = ? AND git_sha_at_handoff = ?
277
- ORDER BY created_at_epoch DESC LIMIT 1
278
- `).get(project, currentSha);
274
+ // Scope like Stage 2: an 'exit' anchor is cross-session (resume after /exit), but a 'clear'
275
+ // anchor is same-session only — else a parallel same-project session at the same commit
276
+ // would hijack (and then delete) another session's clear handoff.
277
+ const anchor = currentCcSessionId
278
+ ? db.prepare(`
279
+ SELECT created_at_epoch, match_keywords FROM session_handoffs
280
+ WHERE project = ? AND git_sha_at_handoff = ? AND (type = 'exit' OR session_id = ?)
281
+ ORDER BY created_at_epoch DESC LIMIT 1
282
+ `).get(project, currentSha, currentCcSessionId)
283
+ : db.prepare(`
284
+ SELECT created_at_epoch, match_keywords FROM session_handoffs
285
+ WHERE project = ? AND git_sha_at_handoff = ?
286
+ ORDER BY created_at_epoch DESC LIMIT 1
287
+ `).get(project, currentSha);
279
288
  if (anchor && (Date.now() - anchor.created_at_epoch <= HANDOFF_ANCHOR_MAX_AGE)) {
280
- return true;
289
+ // Unmoved HEAD is a strong resume signal, but must not hijack a NEW task typed at the
290
+ // same commit: gate long prompts on keyword overlap (mirror Stage 0). Short prompts
291
+ // (resume nudges) auto-continue.
292
+ if (promptText.length < 40) return true;
293
+ const hTokens = anchor.match_keywords ? new Set(tokenizeHandoff(anchor.match_keywords)) : null;
294
+ if (!hTokens || tokenizeHandoff(promptText).some(t => hTokens.has(t))) return true;
295
+ // long prompt with zero keyword overlap → fall through to Stage 0/1/2
281
296
  }
282
297
  }
283
298
  } catch { /* git/DB failure must not break the rest of the pipeline */ }
package/hook-llm.mjs CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  } from './utils.mjs';
12
12
  import { acquireLLMSlot, releaseLLMSlot } from './hook-semaphore.mjs';
13
13
  import { scrubRecord } from './lib/scrub-record.mjs';
14
- import { getVocabulary, computeVector } from './tfidf.mjs';
14
+ import { getVocabulary, computeVector, vecTextForRow } from './tfidf.mjs';
15
15
  import { insertObservationRow, insertObservationFiles, insertObservationVector } from './lib/observation-write.mjs';
16
16
  import { DEDUP_JACCARD_THRESHOLD, AUTO_MERGE_THRESHOLD } from './lib/dedup-constants.mjs';
17
17
  import {
@@ -124,10 +124,12 @@ function buildFtsTextField(obs) {
124
124
  // weight) and search_aliases (finding #8: previously omitted, so even with vectors
125
125
  // enabled the paraphrase-bridge alias terms were invisible to cosine similarity).
126
126
  export function buildVecText(obs) {
127
- const conceptsText = Array.isArray(obs.concepts) ? obs.concepts.join(' ') : (obs.concepts || '');
128
- const aliasesText = obs.searchAliases || '';
129
- return [obs.title || '', obs.narrative || '', conceptsText, obs.lessonLearned || '', aliasesText]
130
- .filter(Boolean).join(' ');
127
+ // Single source (V-F1): map the camelCase obs onto vecTextForRow's row shape so save and
128
+ // every rebuild path encode the identical field set (title/narrative/concepts/lesson/aliases).
129
+ return vecTextForRow({
130
+ title: obs.title, narrative: obs.narrative, concepts: obs.concepts,
131
+ lesson_learned: obs.lessonLearned, search_aliases: obs.searchAliases,
132
+ });
131
133
  }
132
134
 
133
135
  /**
@@ -996,7 +998,8 @@ ${actionList}`;
996
998
  search_aliases: obs.searchAliases || null,
997
999
  });
998
1000
  db.prepare(`
999
- UPDATE observations SET type=?, title=?, subtitle=?, narrative=?, concepts=?, facts=?,
1001
+ UPDATE observations SET type=?, title=?, subtitle=?,
1002
+ narrative=COALESCE(NULLIF(?, ''), narrative), concepts=?, facts=?,
1000
1003
  text=?, importance=?, files_read=?, minhash_sig=?, lesson_learned=?, search_aliases=?
1001
1004
  WHERE id = ?
1002
1005
  `).run(
@@ -1018,7 +1021,7 @@ ${actionList}`;
1018
1021
  try {
1019
1022
  const vocab = getVocabulary(db);
1020
1023
  if (vocab) {
1021
- const vecText = [obs.title || '', obs.narrative || '', conceptsText].filter(Boolean).join(' ');
1024
+ const vecText = vecTextForRow({ title: obs.title, narrative: obs.narrative, concepts: conceptsText, lesson_learned: safe.lesson_learned, search_aliases: safe.search_aliases });
1022
1025
  const vec = computeVector(vecText, vocab);
1023
1026
  if (vec) {
1024
1027
  db.prepare('INSERT OR REPLACE INTO observation_vectors (observation_id, vector, vocab_version, created_at_epoch) VALUES (?, ?, ?, ?)')
package/hook-optimize.mjs CHANGED
@@ -12,7 +12,7 @@ import {
12
12
  import { callModelJSON } from './haiku-client.mjs';
13
13
  import { acquireLLMSlot, releaseLLMSlot } from './hook-semaphore.mjs';
14
14
  import { scrubRecord } from './lib/scrub-record.mjs';
15
- import { getVocabulary, computeVector, cosineSimilarity } from './tfidf.mjs';
15
+ import { getVocabulary, computeVector, cosineSimilarity, vecTextForRow } from './tfidf.mjs';
16
16
  import { MERGE_JACCARD_LOW, AUTO_MERGE_THRESHOLD } from './lib/dedup-constants.mjs';
17
17
  import { DB_DIR } from './schema.mjs';
18
18
 
@@ -25,9 +25,14 @@ export function distributeBudget(total = 15) {
25
25
  const reenrich = Math.max(1, Math.floor(total * 0.4));
26
26
  const clusterMerge = Math.max(1, Math.floor(total * 0.3));
27
27
  const smartCompress = Math.max(1, total - reenrich - normalize - clusterMerge);
28
- // Clamp: if total is too small for 4 tasks, cap each so sum total
28
+ // Clamp: if total is too small for all 4 tasks, allocate 1 each by priority until `total`
29
+ // is exhausted so the returned sum is ≤ total (the old fallback returned {1,1,1,1}=4 for
30
+ // total≤3, over-running `optimize --max N`).
29
31
  if (reenrich + normalize + clusterMerge + smartCompress > total) {
30
- return { reenrich: Math.max(1, total - 3), normalize: 1, clusterMerge: 1, smartCompress: 1 };
32
+ const alloc = { reenrich: 0, clusterMerge: 0, smartCompress: 0, normalize: 0 };
33
+ const order = ['reenrich', 'clusterMerge', 'smartCompress', 'normalize'];
34
+ for (let i = 0; i < total && i < order.length; i++) alloc[order[i]] = 1;
35
+ return alloc;
31
36
  }
32
37
  return { reenrich, normalize, clusterMerge, smartCompress };
33
38
  }
@@ -39,11 +44,16 @@ export function distributeBudget(total = 15) {
39
44
  * Exported for testing; also kept as the single source of vector-rebuild logic
40
45
  * for the optimize / re-enrich path to avoid drift with the hook-llm write path.
41
46
  */
42
- export function rebuildVector(db, obsId, textParts) {
47
+ export function rebuildVector(db, obsId, textPartsOrRow) {
43
48
  try {
44
49
  const vocab = getVocabulary(db);
45
50
  if (!vocab) return;
46
- const vec = computeVector(textParts.filter(Boolean).join(' '), vocab);
51
+ // Accept a legacy [parts] array OR an observation row (preferred single-source field set
52
+ // incl. lesson_learned/search_aliases via vecTextForRow, so rebuilds match the save path).
53
+ const text = Array.isArray(textPartsOrRow)
54
+ ? textPartsOrRow.filter(Boolean).join(' ')
55
+ : vecTextForRow(textPartsOrRow);
56
+ const vec = computeVector(text, vocab);
47
57
  if (vec) {
48
58
  // Bug #1 fix: column is `created_at_epoch`, not `computed_at`. Every other
49
59
  // INSERT callsite (server.mjs, hook-llm.mjs, mem-cli.mjs) uses the correct
@@ -87,7 +97,7 @@ export function findReenrichCandidates(db, limit = 10, { scope = 'narrow', proje
87
97
  // deliberately NOT gated on optimized_at, so a lesson-less row can still be
88
98
  // picked up by wide scope for lesson enrichment afterward.
89
99
  const stmt = db.prepare(`
90
- SELECT id, title, narrative, type, subtitle, concepts, facts, text, search_aliases, project
100
+ SELECT id, title, narrative, type, subtitle, concepts, facts, text, search_aliases, importance, project
91
101
  FROM observations
92
102
  WHERE COALESCE(compressed_into, 0) = 0
93
103
  AND superseded_at IS NULL
@@ -102,7 +112,7 @@ export function findReenrichCandidates(db, limit = 10, { scope = 'narrow', proje
102
112
  }
103
113
  if (scope === 'wide') {
104
114
  const stmt = db.prepare(`
105
- SELECT id, title, narrative, type, subtitle, concepts, facts, search_aliases, project
115
+ SELECT id, title, narrative, type, subtitle, concepts, facts, search_aliases, importance, project
106
116
  FROM observations
107
117
  WHERE COALESCE(compressed_into, 0) = 0
108
118
  AND superseded_at IS NULL
@@ -120,7 +130,7 @@ export function findReenrichCandidates(db, limit = 10, { scope = 'narrow', proje
120
130
  return project ? stmt.all(project, limit) : stmt.all(limit);
121
131
  }
122
132
  const stmt = db.prepare(`
123
- SELECT id, title, narrative, type, subtitle, project
133
+ SELECT id, title, narrative, type, subtitle, importance, project
124
134
  FROM observations
125
135
  WHERE COALESCE(compressed_into, 0) = 0
126
136
  AND (concepts IS NULL OR concepts = '')
@@ -205,7 +215,10 @@ search_aliases: 2-6 alternative search terms (include CJK if applicable).`;
205
215
  continue;
206
216
  }
207
217
 
208
- const type = validTypes.has(parsed.type) ? parsed.type : cand.type || 'change';
218
+ // Enrichment ("add a lesson") must not reclassify a specific type down to the generic
219
+ // 'change' (lower TYPE_QUALITY + faster decay); keep the stored type on that downgrade.
220
+ let type = validTypes.has(parsed.type) ? parsed.type : (cand.type || 'change');
221
+ if (type === 'change' && cand.type && cand.type !== 'change') type = cand.type;
209
222
  const concepts = Array.isArray(parsed.concepts) ? parsed.concepts.slice(0, 10) : [];
210
223
  const facts = Array.isArray(parsed.facts) ? parsed.facts.slice(0, 10) : [];
211
224
  // Preserve-on-empty: wide-scope candidates can already carry concepts/facts/aliases
@@ -227,7 +240,10 @@ search_aliases: 2-6 alternative search terms (include CJK if applicable).`;
227
240
  ? parsed.search_aliases.slice(0, 6).join(' ') : (cand.search_aliases || null);
228
241
  const title = truncate(scrubSecrets(parsed.title || ''), 120);
229
242
  const narrative = truncate(scrubSecrets(parsed.narrative || cand.narrative || ''), 500);
230
- const importance = clampImportance(parsed.importance);
243
+ // Floor at the stored importance: re-enrich adds a lesson, it must never silently downgrade
244
+ // a user-set/promoted importance (the UPDATE also sets optimized_at → the loss is permanent).
245
+ // Upgrades are still honored.
246
+ const importance = Math.max(clampImportance(parsed.importance), cand.importance || 1);
231
247
 
232
248
  const bigramText = cjkBigrams((title || '') + ' ' + (narrative || ''));
233
249
  const textField = [conceptsText, factsText, searchAliases || '', bigramText].filter(Boolean).join(' ');
@@ -250,7 +266,7 @@ search_aliases: 2-6 alternative search terms (include CJK if applicable).`;
250
266
  `).run(type, safe.title, safe.narrative, safe.concepts, safe.facts, safe.text,
251
267
  importance, safe.lesson_learned, safe.search_aliases, minhashSig, Date.now(), cand.id);
252
268
 
253
- rebuildVector(db, cand.id, [title, narrative, conceptsText]);
269
+ rebuildVector(db, cand.id, { title, narrative, concepts: conceptsText, lesson_learned: safe.lesson_learned, search_aliases: safe.search_aliases });
254
270
 
255
271
  processed++;
256
272
  } catch (e) {
@@ -362,7 +378,7 @@ export function applyNormalization(db, groups, { project = null } = {}) {
362
378
  // contamination the --project flag was added to prevent. NULL → all projects (legacy
363
379
  // unscoped run), matching the search-engine `(? IS NULL OR project = ?)` idiom.
364
380
  const rows = db.prepare(`
365
- SELECT id, concepts, search_aliases FROM observations
381
+ SELECT id, title, narrative, concepts, search_aliases, lesson_learned FROM observations
366
382
  WHERE COALESCE(compressed_into, 0) = 0
367
383
  AND concepts IS NOT NULL AND concepts != ''
368
384
  AND (? IS NULL OR project = ?)
@@ -395,6 +411,9 @@ export function applyNormalization(db, groups, { project = null } = {}) {
395
411
  search_aliases: newAliases,
396
412
  });
397
413
  updateStmt.run(safe.concepts, safe.search_aliases, Date.now(), row.id);
414
+ // V-F3: normalize mutated concepts + search_aliases (both vector fields) — rebuild the
415
+ // vector so it reflects the canonicalized terms (no-op when the vector arm is disabled).
416
+ rebuildVector(db, row.id, { title: row.title, narrative: row.narrative, concepts: safe.concepts, search_aliases: safe.search_aliases, lesson_learned: row.lesson_learned });
398
417
  updated++;
399
418
  }
400
419
  }
@@ -433,7 +452,7 @@ export function findMergeCandidates(db, maxClusters = 5, { project } = {}) {
433
452
  const cutoff = Date.now() - MERGE_TIME_WINDOW_MS;
434
453
  const projectClause = project ? 'AND project = ?' : '';
435
454
  const stmt = db.prepare(`
436
- SELECT id, title, narrative, project, type, access_count, importance, created_at_epoch, minhash_sig, lesson_learned
455
+ SELECT id, title, narrative, project, type, access_count, importance, created_at_epoch, minhash_sig, lesson_learned, concepts, facts
437
456
  FROM observations
438
457
  WHERE COALESCE(compressed_into, 0) = 0
439
458
  AND superseded_at IS NULL
@@ -520,12 +539,15 @@ Return ONLY valid JSON:
520
539
 
521
540
  const concepts = Array.isArray(parsed.merged_concepts) ? parsed.merged_concepts.slice(0, 10) : [];
522
541
  const facts = Array.isArray(parsed.merged_facts) ? parsed.merged_facts.slice(0, 10) : [];
523
- const conceptsText = concepts.join(' ');
524
- const factsText = facts.join(' ');
542
+ // Preserve-on-empty (mirror the merged_lesson guard below + the re-enrich path): the merge
543
+ // overwrites the keeper in place, so a partial LLM response that omits these must fall back to
544
+ // the keeper's own values, not blank its live concepts/facts (findMergeCandidates now selects them).
545
+ const conceptsText = concepts.length ? concepts.join(' ') : (keeper.concepts || '');
546
+ const factsText = facts.length ? facts.join(' ') : (keeper.facts || '');
525
547
  // Scrub BEFORE truncate (see re-enrich note): keep the boundary cut on
526
548
  // already-scrubbed text so a straddling secret can't leak a sub-floor head.
527
549
  const title = truncate(scrubSecrets(parsed.merged_title || ''), 120);
528
- const narrative = truncate(scrubSecrets(parsed.merged_narrative || ''), 800);
550
+ const narrative = truncate(scrubSecrets(parsed.merged_narrative || keeper.narrative || ''), 800);
529
551
  // Preserve-on-empty. The merge overwrites the keeper in place and hides every non-keeper
530
552
  // member (compressed_into=keeper.id), so if the LLM returns merged_lesson:null (the prompt
531
553
  // at :429 explicitly permits it) every cluster lesson would leave all live surfaces at once
@@ -589,7 +611,7 @@ Return ONLY valid JSON:
589
611
  .run(keeper.id, ...otherIds);
590
612
  })();
591
613
 
592
- rebuildVector(db, keeper.id, [title, narrative, conceptsText]);
614
+ rebuildVector(db, keeper.id, { title, narrative, concepts: conceptsText, lesson_learned: lessonLearned, search_aliases: keeper.search_aliases });
593
615
 
594
616
  debugLog('DEBUG', 'llm-optimize', `merged ${cluster.length} observations into #${keeper.id}`);
595
617
  return { merged: true, keeperId: keeper.id, mergedCount: others.length };
@@ -793,7 +815,7 @@ JSON: {"title":"descriptive summary ≤120 chars","narrative":"comprehensive sum
793
815
  return sId;
794
816
  })();
795
817
 
796
- rebuildVector(db, summaryId, [title, narrative, conceptsText]);
818
+ rebuildVector(db, summaryId, { title, narrative, concepts: conceptsText });
797
819
 
798
820
  debugLog('DEBUG', 'llm-optimize', `smart-compressed ${observations.length} observations into #${summaryId}`);
799
821
  return { compressed: true, summaryId, count: observations.length };
package/hook-shared.mjs CHANGED
@@ -98,7 +98,9 @@ export function sweepOrphanEpisodeFiles(runtimeDir, { ageMs = ORPHAN_EPISODE_AGE
98
98
  const readsCutoff = now - readsAgeMs;
99
99
  let count = 0;
100
100
  for (const f of entries) {
101
- const isEpisode = f.startsWith('ep-flush-') || f.startsWith('pending-');
101
+ // `.claim-` = handleStop's lock-contended fallback claim file (ep-<project>.json.claim-<pid>-<ts>),
102
+ // which leaks if the process dies between rename and unlink; sweep it on the same 1h cutoff.
103
+ const isEpisode = f.startsWith('ep-flush-') || f.startsWith('pending-') || f.includes('.claim-');
102
104
  const isReads = f.startsWith('reads-') && f.endsWith('.txt');
103
105
  if (!isEpisode && !isReads) continue;
104
106
  const full = join(runtimeDir, f);
package/hook.mjs CHANGED
@@ -484,6 +484,10 @@ async function handleStop() {
484
484
  for (const sub of planEpisodeFlush(episode)) {
485
485
  if (!sub.sessionId) sub.sessionId = sessionId;
486
486
  if (!sub.project) sub.project = project;
487
+ // Per-sub significance gate — parity with flushEpisodeGroup. The whole-episode check
488
+ // above can pass while an interleaved concurrent-session sub is pure noise (e.g. a lone
489
+ // Read); without this the fallback persists that noise sub AND spawns an LLM worker for it.
490
+ if (!episodeHasSignificantContent(sub)) continue;
487
491
  try {
488
492
  const obs = buildImmediateObservation(sub);
489
493
  const id = saveObservation(obs, sub.project, sub.sessionId);
@@ -1412,7 +1416,14 @@ async function handleUserPrompt() {
1412
1416
  );
1413
1417
 
1414
1418
  // Cross-session handoff injection (first 3 prompts window, before semantic memory).
1415
- if (promptNumber <= 3) {
1419
+ // prompt_counter is project-scoped (shared across concurrent same-project CC sessions), so a
1420
+ // parallel session would start past the window and never get its handoff injected. Count THIS
1421
+ // cc_session's own prompts instead (the current one is already inserted above); legacy null cc
1422
+ // id falls back to the shared counter.
1423
+ const windowPos = ccSessionId
1424
+ ? (db.prepare('SELECT COUNT(*) c FROM user_prompts WHERE cc_session_id = ?').get(ccSessionId)?.c || promptNumber)
1425
+ : promptNumber;
1426
+ if (windowPos <= 3) {
1416
1427
  try {
1417
1428
  if (detectContinuationIntent(db, promptText, project, ccSessionId)) {
1418
1429
  const picked = pickHandoffToInject(db, project, ccSessionId);
package/install.mjs CHANGED
@@ -1688,12 +1688,18 @@ async function doctor() {
1688
1688
 
1689
1689
  // ─── Settings helpers ───────────────────────────────────────────────────────
1690
1690
 
1691
- function isMemHook(cfg) {
1691
+ // Identify a settings hook as one of OURS (to replace on install / strip on uninstall).
1692
+ // Must be tight: the old `hook.mjs` + event-word test matched a user's OWN generic hook
1693
+ // (`node ~/.config/hook.mjs session-start`) and install/uninstall silently deleted it.
1694
+ // The launcher marker (`hook-launcher.mjs`, which every Node hook routes through since v2.84)
1695
+ // replaces that clause; the product-name substring (our install-dir / legacy-direct hooks)
1696
+ // and the bash prefilter round out the real markers.
1697
+ export function isMemHook(cfg) {
1692
1698
  if (!cfg.hooks) return false;
1693
1699
  return cfg.hooks.some(h => {
1694
1700
  const cmd = h.command || '';
1695
1701
  return cmd.includes('claude-mem-lite') ||
1696
- (cmd.includes('hook.mjs') && /\b(session-start|stop|user-prompt|pre-tool-use)\b/.test(cmd)) ||
1702
+ cmd.includes('hook-launcher.mjs') ||
1697
1703
  cmd.includes('scripts/post-tool-use.sh');
1698
1704
  });
1699
1705
  }
@@ -13,7 +13,7 @@
13
13
  // { projectFilter: 'AND project = ?' | '', baseParams: [project?] , staleAge, opCap }
14
14
 
15
15
  import { COMPRESSED_PENDING_PURGE, computeMinHash, estimateJaccardFromMinHash, jaccardSimilarity } from '../utils.mjs';
16
- import { rebuildVocabulary, computeVector, _resetVocabCache, vectorsEnabled } from '../tfidf.mjs';
16
+ import { rebuildVocabulary, computeVector, _resetVocabCache, vectorsEnabled, vecTextForRow } from '../tfidf.mjs';
17
17
  import { DEDUP_JACCARD_THRESHOLD, MINHASH_PRE_THRESHOLD as MINHASH_PRE_THRESHOLD_SRC, FUZZY_DEDUP_THRESHOLD, FUZZY_BODY_THRESHOLD, MINHASH_PREFILTER } from './dedup-constants.mjs';
18
18
 
19
19
  export const STALE_AGE_MS = 30 * 86400000;
@@ -428,7 +428,7 @@ export function rebuildVectors(db) {
428
428
  const vocab = rebuildVocabulary(db);
429
429
  if (!vocab) return { ok: false, reason: 'no observations to build vocabulary from' };
430
430
  const allObs = db.prepare(`
431
- SELECT id, title, narrative, concepts FROM observations
431
+ SELECT id, title, narrative, concepts, lesson_learned, search_aliases FROM observations
432
432
  WHERE COALESCE(compressed_into, 0) = 0 AND superseded_at IS NULL
433
433
  `).all();
434
434
  let updated = 0;
@@ -437,8 +437,7 @@ export function rebuildVectors(db) {
437
437
  db.transaction(() => {
438
438
  db.prepare('DELETE FROM observation_vectors').run();
439
439
  for (const obs of allObs) {
440
- const text = [obs.title || '', obs.narrative || '', obs.concepts || ''].filter(Boolean).join(' ');
441
- const vec = computeVector(text, vocab);
440
+ const vec = computeVector(vecTextForRow(obs), vocab);
442
441
  if (vec) {
443
442
  insertStmt.run(obs.id, Buffer.from(vec.buffer), vocab.version, now);
444
443
  updated++;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem-lite",
3
- "version": "3.40.0",
3
+ "version": "3.41.0",
4
4
  "description": "Persistent long-term memory for Claude Code via MCP — captures coding decisions, bugfixes, and context across sessions. Hybrid FTS5 + TF-IDF search with episode batching. Single SQLite DB, no external services. A lighter, lower-cost alternative to claude-mem (episode batching + a smaller model; cost savings are an internal estimate, not a measured benchmark).",
5
5
  "type": "module",
6
6
  "packageManager": "npm@10.9.2",
package/scripts/setup.sh CHANGED
@@ -39,20 +39,18 @@ fi
39
39
  mkdir -p "$DATA_DIR"
40
40
  log_ok "Data directory: $DATA_DIR"
41
41
 
42
- # 3. Migrate from old ~/.claude-mem/ if needed
42
+ # 3. Legacy ~/.claude-mem/ DB is schema-v16 (no memory_session_id) with no migration bridge to
43
+ # the current schema — activating it FATALs on first launch ("no such column: memory_session_id")
44
+ # and the "! -f claude-mem-lite.db" guard would re-copy it every time the user deletes the broken
45
+ # DB (recovery loop). Mirror install.mjs migrateLegacyClaudeMemData: back it up (don't activate)
46
+ # and let a fresh DB be created. Source ~/.claude-mem/ is left intact.
43
47
  OLD_DIR="$HOME/.claude-mem"
44
48
  if [[ -f "$OLD_DIR/claude-mem.db" && ! -f "$DATA_DIR/claude-mem-lite.db" && ! -f "$DATA_DIR/claude-mem.db" ]]; then
45
- log_info "Migrating data from ~/.claude-mem/ → ~/.claude-mem-lite/..."
46
- if cp "$OLD_DIR/claude-mem.db" "$DATA_DIR/claude-mem-lite.db" 2>/dev/null; then
47
- # Main DB copied successfully, WAL/SHM are optional
48
- cp "$OLD_DIR/claude-mem.db-wal" "$DATA_DIR/claude-mem-lite.db-wal" 2>/dev/null || true
49
- cp "$OLD_DIR/claude-mem.db-shm" "$DATA_DIR/claude-mem-lite.db-shm" 2>/dev/null || true
50
- if [[ -d "$OLD_DIR/runtime" && ! -d "$DATA_DIR/runtime" ]]; then
51
- cp -r "$OLD_DIR/runtime" "$DATA_DIR/runtime" 2>/dev/null || true
52
- fi
53
- log_ok "Data migrated (old ~/.claude-mem/ preserved)"
49
+ BACKUP="$DATA_DIR/claude-mem-lite.db.legacy-backup-$(date +%s)"
50
+ if cp "$OLD_DIR/claude-mem.db" "$BACKUP" 2>/dev/null; then
51
+ log_info "Legacy ~/.claude-mem/ DB is schema-incompatible; backed up to $(basename "$BACKUP") (a fresh DB will be created). Old ~/.claude-mem/ preserved."
54
52
  else
55
- log_warn "Migration failed — using fresh database"
53
+ log_warn "Legacy DB backup failed — a fresh database will be created"
56
54
  fi
57
55
  fi
58
56
 
package/tfidf.mjs CHANGED
@@ -207,6 +207,19 @@ let _vocabCache = null;
207
207
  /** Reset vocabulary cache (for testing). */
208
208
  export function _resetVocabCache() { _vocabCache = null; }
209
209
 
210
+ /**
211
+ * Canonical TF-IDF vector text for an observation ROW (snake_case DB fields). Single source for
212
+ * EVERY (re)build path — save, enrich, rebuild_vectors, cluster-merge, compress, normalize — so
213
+ * they encode the identical field set and can't drift (V-F1). Mirrors the FTS-searchable columns
214
+ * incl. lesson_learned + search_aliases (finding #8). `concepts` may be an array or a string.
215
+ */
216
+ export function vecTextForRow(row) {
217
+ if (!row) return '';
218
+ const concepts = Array.isArray(row.concepts) ? row.concepts.join(' ') : (row.concepts || '');
219
+ return [row.title || '', row.narrative || '', concepts, row.lesson_learned || '', row.search_aliases || '']
220
+ .filter(Boolean).join(' ');
221
+ }
222
+
210
223
  /**
211
224
  * Build global vocabulary (IDF table) from all active observations.
212
225
  * @param {object} db - better-sqlite3 database
@@ -214,7 +227,7 @@ export function _resetVocabCache() { _vocabCache = null; }
214
227
  */
215
228
  export function buildVocabulary(db, { dim = VOCAB_DIM } = {}) {
216
229
  const rows = db.prepare(`
217
- SELECT title, narrative, concepts FROM observations
230
+ SELECT title, narrative, concepts, lesson_learned, search_aliases FROM observations
218
231
  WHERE COALESCE(compressed_into, 0) = 0 AND superseded_at IS NULL
219
232
  `).all();
220
233
 
@@ -224,7 +237,10 @@ export function buildVocabulary(db, { dim = VOCAB_DIM } = {}) {
224
237
  // Count document frequency for each term
225
238
  const df = new Map();
226
239
  for (const row of rows) {
227
- const text = [row.title || '', row.narrative || '', row.concepts || ''].join(' ');
240
+ // V-F2: include lesson_learned + search_aliases so terms living only there get a vocab
241
+ // dimension (else computeVector silently drops them — the exact paraphrase-bridge terms
242
+ // search_aliases exists to carry). Mirrors vecTextForRow's field set.
243
+ const text = [row.title || '', row.narrative || '', row.concepts || '', row.lesson_learned || '', row.search_aliases || ''].join(' ');
228
244
  const docTerms = new Set(tokenize(text));
229
245
  for (const term of docTerms) {
230
246
  df.set(term, (df.get(term) || 0) + 1);
package/utils.mjs CHANGED
@@ -404,7 +404,13 @@ export function isMetaTriggerPrompt(text) {
404
404
  .replace(/上次(到哪了|说到哪了)?/g, '')
405
405
  .replace(/总结一下|复盘一下/g, '')
406
406
  .replace(/前面(的)?(工作|话题|讨论|内容)/g, '')
407
+ // R3 H-M2: control phrases named in lesson #8287 / common continuations. Phrase-anchored
408
+ // (or bare suffix/prefix) so a real subject that merely contains one keeps its other tokens.
409
+ .replace(/停了|停不下来/g, '')
410
+ .replace(/怎么(回事|了|样了|停的)?/g, '')
411
+ .replace(/再来(一次|一遍|一下)?/g, '')
407
412
  .replace(/\/?(clear|exit)\b/gi, '')
413
+ .replace(/\b(go on|go ahead|keep going|carry on|proceed|why(?:'?d| did) you stop)\b/gi, '')
408
414
  .replace(/\b(commit|continue|resume|push|save|restart|exit|next)\b/gi, '')
409
415
  .replace(/[,,。.!!??::;;()()【】[\]\s/\\-]+/g, '')
410
416
  .trim();