toon-memory 4.1.1 → 4.2.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.
package/mcp/server.js CHANGED
@@ -21994,7 +21994,7 @@ function importance(e, today = (/* @__PURE__ */ new Date()).toISOString().split(
21994
21994
  const freq = Math.min(1, e.accessed / 5);
21995
21995
  return recency * 0.6 + freq * 0.4;
21996
21996
  }
21997
- var normalize, isExpiredLocal, tokenize, escField, unescField, parseToonLine, toToonLine, isPrivate;
21997
+ var normalize, isExpiredLocal, tokenize, estimateTokens, languageFamily, escField, unescField, parseToonLine, toToonLine, isPrivate;
21998
21998
  var init_utils = __esm({
21999
21999
  "src/lib/utils.ts"() {
22000
22000
  "use strict";
@@ -22004,6 +22004,35 @@ var init_utils = __esm({
22004
22004
  return ttl <= today;
22005
22005
  };
22006
22006
  tokenize = (s2) => s2.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[-_]/g, " ").toLowerCase().split(/\s+/).filter(Boolean);
22007
+ estimateTokens = (s2) => {
22008
+ if (!s2) return 0;
22009
+ const chars = Math.ceil(s2.length / 4);
22010
+ const words = (s2.match(/\S+/g) || []).length;
22011
+ return Math.max(1, chars + words);
22012
+ };
22013
+ languageFamily = (s2) => {
22014
+ let cjk = 0, cyr = 0, arab = 0, greek = 0, hebrew = 0, deva = 0, latin = 0, total = 0;
22015
+ for (const ch2 of s2) {
22016
+ const c2 = ch2.codePointAt(0);
22017
+ if (!/[\p{L}]/u.test(ch2)) continue;
22018
+ total++;
22019
+ if (c2 >= 19968 && c2 <= 40959 || c2 >= 12352 && c2 <= 12543 || c2 >= 44032 && c2 <= 55215) cjk++;
22020
+ else if (c2 >= 1024 && c2 <= 1279) cyr++;
22021
+ else if (c2 >= 1536 && c2 <= 1791) arab++;
22022
+ else if (c2 >= 880 && c2 <= 1023) greek++;
22023
+ else if (c2 >= 1424 && c2 <= 1535) hebrew++;
22024
+ else if (c2 >= 2304 && c2 <= 2431) deva++;
22025
+ else latin++;
22026
+ }
22027
+ if (total === 0) return "none";
22028
+ if (cjk / total > 0.3) return "cjk";
22029
+ if (cyr / total > 0.3) return "cyrillic";
22030
+ if (arab / total > 0.3) return "arabic";
22031
+ if (greek / total > 0.3) return "greek";
22032
+ if (hebrew / total > 0.3) return "hebrew";
22033
+ if (deva / total > 0.3) return "devanagari";
22034
+ return "latin";
22035
+ };
22007
22036
  escField = (s2) => {
22008
22037
  let out = "";
22009
22038
  for (let i = 0; i < s2.length; i++) {
@@ -22431,6 +22460,23 @@ function centrality(adjacency) {
22431
22460
  for (const [k3, d2] of deg) out.set(k3, d2 / maxDeg);
22432
22461
  return out;
22433
22462
  }
22463
+ function buildReason(e, bm25Score, bm25Max, impScore, today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0]) {
22464
+ const parts = [];
22465
+ if (bm25Max > 0) {
22466
+ parts.push(`${Math.round(bm25Score / bm25Max * 100)}% relevance`);
22467
+ }
22468
+ if (e.accessed > 0) {
22469
+ parts.push(`used ${e.accessed}\xD7`);
22470
+ }
22471
+ if (e.lastAccessed) {
22472
+ const days = Math.floor((Date.parse(`${today}T00:00:00`) - Date.parse(e.lastAccessed)) / 864e5);
22473
+ parts.push(days <= 0 ? "used today" : days === 1 ? "used yesterday" : `used ${days}d ago`);
22474
+ } else if (e.accessed === 0) {
22475
+ parts.push("never used");
22476
+ }
22477
+ parts.push(impScore >= 0.7 ? "importance HIGH" : impScore >= 0.4 ? "importance MED" : "importance LOW");
22478
+ return parts.join(" \xB7 ");
22479
+ }
22434
22480
  function graphRecallDetailed(data, query, opts = {}) {
22435
22481
  const entries = parseEntries(data);
22436
22482
  const { adjacency, byKey } = buildGraph(entries);
@@ -22512,6 +22558,7 @@ function graphRecallDetailed(data, query, opts = {}) {
22512
22558
  s2 *= 1.15;
22513
22559
  }
22514
22560
  }
22561
+ if (e.category === "warning") s2 += 0.2;
22515
22562
  s2 *= decay;
22516
22563
  return { e, s: s2, priority: e.priority };
22517
22564
  }).sort((a, b2) => {
@@ -22537,7 +22584,16 @@ function graphRecallDetailed(data, query, opts = {}) {
22537
22584
  }
22538
22585
  const scores = /* @__PURE__ */ new Map();
22539
22586
  selected.forEach((e) => scores.set(e.key, scored.find((x) => x.e.key === e.key).s));
22540
- return { entries: selected, seeds: seedKeys, adjacency: subAdj, scores };
22587
+ let bm25Max = 0;
22588
+ for (const v3 of bm25.values()) if (v3 > bm25Max) bm25Max = v3;
22589
+ const reasons = /* @__PURE__ */ new Map();
22590
+ for (const e of selected) {
22591
+ reasons.set(
22592
+ e.key,
22593
+ buildReason(e, bm25.get(e.key) || 0, bm25Max, importance(e, opts.today), opts.today)
22594
+ );
22595
+ }
22596
+ return { entries: selected, seeds: seedKeys, adjacency: subAdj, scores, reasons };
22541
22597
  }
22542
22598
  function globMatch(pattern, target) {
22543
22599
  if (!pattern) return true;
@@ -22555,17 +22611,20 @@ function renderCompact(entries, opts = {}) {
22555
22611
  entries.forEach((e, i) => index.set(e.key, i + 1));
22556
22612
  const snippetLen = opts.snippetLen ?? 90;
22557
22613
  const budget = opts.budget ?? "normal";
22558
- return entries.map((e) => {
22614
+ const rendered = [];
22615
+ let tokens = 0;
22616
+ for (const e of entries) {
22559
22617
  const n = index.get(e.key);
22560
22618
  const isSeed = opts.seeds ? opts.seeds.has(e.key) : true;
22619
+ const reason = opts.reasons?.get(e.key);
22620
+ let block;
22561
22621
  if (budget === "tiny") {
22562
22622
  const firstLine = e.content.split("\n")[0] || "";
22563
22623
  const snippet = firstLine.length > 80 ? firstLine.slice(0, 80).trimEnd() + "\u2026" : firstLine;
22564
22624
  const pin = e.priority > 0 ? e.priority > 1 ? ` \u{1F4CC}${e.priority}` : " \u{1F4CC}" : "";
22565
- return `[${n}] ${e.category}/${e.key}${pin}
22625
+ block = `[${n}] ${e.category}/${e.key}${pin}
22566
22626
  ${snippet}`;
22567
- }
22568
- if (budget === "deep") {
22627
+ } else if (budget === "deep") {
22569
22628
  const ttlInfo = e.ttl ? ` \xB7 ttl: ${e.ttl}` : "";
22570
22629
  const accessInfo = e.accessed > 0 ? ` \xB7 accessed: ${e.accessed}x` : "";
22571
22630
  const lastAccess = e.lastAccessed ? ` \xB7 lastAccess: ${e.lastAccessed}` : "";
@@ -22576,24 +22635,36 @@ function renderCompact(entries, opts = {}) {
22576
22635
  const scopeInfo = e.path_scope ? ` \xB7 scope: ${e.path_scope}` : "";
22577
22636
  const statusInfo = e.status !== "active" ? ` \xB7 status: ${e.status}` : "";
22578
22637
  const supersededInfo = e.supersededOn ? ` \xB7 superseded: ${e.supersededOn}` : "";
22579
- return `[${n}] ${e.category}/${e.key}${pin} (${e.id})
22638
+ block = `[${n}] ${e.category}/${e.key}${pin} (${e.id})
22580
22639
  ${e.content}
22581
22640
  File: ${e.file} | Tags: ${e.tags.join(";")} | Date: ${e.date}${ttlInfo}${accessInfo}${lastAccess}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}${links}`;
22641
+ } else {
22642
+ let body = e.content;
22643
+ if (!isSeed && e.content.length > snippetLen) {
22644
+ body = e.content.slice(0, snippetLen).trimEnd() + "\u2026";
22645
+ }
22646
+ const tag = e.priority > 0 ? e.priority > 1 ? ` \u{1F4CC}${e.priority}` : " \u{1F4CC}" : "";
22647
+ const tags = e.tags.length ? ` \xB7 tags: ${e.tags.join(";")}` : "";
22648
+ let edges = "";
22649
+ if (opts.adjacency) {
22650
+ const nb2 = (opts.adjacency.get(e.key) || []).map((k3) => index.get(k3)).filter((x) => typeof x === "number");
22651
+ if (nb2.length) edges = ` \xB7 edges: ->${nb2.join(", ->")}`;
22652
+ }
22653
+ block = `[${n}] ${e.category}/${e.key}${tag}
22654
+ ${body}${tags}${edges}`;
22582
22655
  }
22583
- let body = e.content;
22584
- if (!isSeed && e.content.length > snippetLen) {
22585
- body = e.content.slice(0, snippetLen).trimEnd() + "\u2026";
22586
- }
22587
- const tag = e.priority > 0 ? e.priority > 1 ? ` \u{1F4CC}${e.priority}` : " \u{1F4CC}" : "";
22588
- const tags = e.tags.length ? ` \xB7 tags: ${e.tags.join(";")}` : "";
22589
- let edges = "";
22590
- if (opts.adjacency) {
22591
- const nb2 = (opts.adjacency.get(e.key) || []).map((k3) => index.get(k3)).filter((x) => typeof x === "number");
22592
- if (nb2.length) edges = ` \xB7 edges: ->${nb2.join(", ->")}`;
22656
+ if (reason) block += `
22657
+ \u21B3 ${reason}`;
22658
+ rendered.push(block);
22659
+ if (opts.budgetTokens && opts.budgetTokens > 0) {
22660
+ tokens += estimateTokens(block);
22661
+ if (rendered.length > 1 && tokens > opts.budgetTokens) {
22662
+ rendered.pop();
22663
+ break;
22664
+ }
22593
22665
  }
22594
- return `[${n}] ${e.category}/${e.key}${tag}
22595
- ${body}${tags}${edges}`;
22596
- }).join("\n\n");
22666
+ }
22667
+ return rendered.join("\n\n");
22597
22668
  }
22598
22669
  var DEFAULT_EDGE_TYPE, entryLines, W_CENT, W_IMP, SEED_BONUS, DECAY;
22599
22670
  var init_graph = __esm({
@@ -22756,13 +22827,22 @@ function generateSmartRecall(data, intent, opts = {}) {
22756
22827
  sessionBias = 0.15;
22757
22828
  }
22758
22829
  }
22830
+ let langBoost = 0;
22831
+ const qFamily = languageFamily(intent);
22832
+ if (qFamily !== "none") {
22833
+ const eFamily = languageFamily(`${e.content} ${e.key} ${e.tags.join(" ")}`);
22834
+ if (qFamily === eFamily) langBoost = 0.1;
22835
+ }
22836
+ let folderBoost = 0;
22837
+ if (e.path_scope && globMatch(e.path_scope, ".")) folderBoost = 0.05;
22838
+ const warningBoost = e.category === "warning" ? 0.2 : 0;
22759
22839
  let combined;
22760
22840
  if (opts.rrf) {
22761
- combined = (fused?.get(e.key) ?? 0) - drift + sessionBias;
22841
+ combined = (fused?.get(e.key) ?? 0) - drift + sessionBias + langBoost + folderBoost + warningBoost;
22762
22842
  } else {
22763
- combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias;
22843
+ combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias + langBoost + folderBoost + warningBoost;
22764
22844
  }
22765
- return { entry: e, score: combined, matchesQuery, priority: e.priority };
22845
+ return { entry: e, score: combined, matchesQuery, priority: e.priority, bm25Score };
22766
22846
  }).filter((x) => x.score > 0 || x.matchesQuery).sort((a, b2) => {
22767
22847
  if (a.priority !== b2.priority) return b2.priority - a.priority;
22768
22848
  return b2.score - a.score;
@@ -22771,7 +22851,7 @@ function generateSmartRecall(data, intent, opts = {}) {
22771
22851
  const inResult = new Set(scored.map((x) => x.entry.key));
22772
22852
  const toInject = [...pinnedKeys].filter((k3) => !inResult.has(k3)).map((k3) => eligible.find((en2) => en2.key === k3)).filter(Boolean).sort((a, b2) => b2.priority - a.priority);
22773
22853
  for (const e of toInject) {
22774
- scored.unshift({ entry: e, score: 999, matchesQuery: false, priority: e.priority });
22854
+ scored.unshift({ entry: e, score: 999, matchesQuery: false, priority: e.priority, bm25Score: 0 });
22775
22855
  }
22776
22856
  if (scored.length === 0) {
22777
22857
  const top = eligible.sort((a, b2) => {
@@ -22779,10 +22859,21 @@ function generateSmartRecall(data, intent, opts = {}) {
22779
22859
  return importance(b2, opts.today) - importance(a, opts.today);
22780
22860
  }).slice(0, limit);
22781
22861
  if (top.length === 0) return "No entries in memory.";
22782
- return renderCompact(top);
22862
+ return renderCompact(top, { budgetTokens: opts.budgetTokens });
22783
22863
  }
22784
22864
  if (opts.bumpAccess) opts.bumpAccess(scored.map((x) => x.entry.id));
22785
- return renderCompact(scored.map((x) => x.entry));
22865
+ let bm25Max = 0;
22866
+ for (const s2 of scored) if (s2.bm25Score > bm25Max) bm25Max = s2.bm25Score;
22867
+ const reasons = /* @__PURE__ */ new Map();
22868
+ if (opts.explain) {
22869
+ for (const s2 of scored) {
22870
+ reasons.set(
22871
+ s2.entry.key,
22872
+ buildReason(s2.entry, s2.bm25Score, bm25Max, importance(s2.entry, opts.today), opts.today)
22873
+ );
22874
+ }
22875
+ }
22876
+ return renderCompact(scored.map((x) => x.entry), { reasons: opts.explain ? reasons : void 0, budgetTokens: opts.budgetTokens });
22786
22877
  }
22787
22878
  function generateSystemPrimer(data) {
22788
22879
  const entries = parseEntries(data);
@@ -33242,6 +33333,73 @@ function consolidateEntries() {
33242
33333
  writeMemory(lines.join("\n"));
33243
33334
  return { removed: totalRemoved, kept: order.length, duplicates };
33244
33335
  }
33336
+ function extractVersion(text) {
33337
+ const m3 = text.match(/([A-Za-z][A-Za-z0-9._-]*?)\s*(?:v)?(\d+)\.(\d+)(?:\.(\d+))?/);
33338
+ if (!m3) return null;
33339
+ const base = m3[1].replace(/[-_.]+$/g, "").toLowerCase();
33340
+ return { base, version: [parseInt(m3[2]), parseInt(m3[3]), m3[4] ? parseInt(m3[4]) : 0] };
33341
+ }
33342
+ function compareVersions(a, b2) {
33343
+ for (let i = 0; i < 3; i++) {
33344
+ if (a[i] !== b2[i]) return a[i] - b2[i];
33345
+ }
33346
+ return 0;
33347
+ }
33348
+ function consolidateVersions(dryRun) {
33349
+ const data = readMemory();
33350
+ const lines = data.split("\n");
33351
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
33352
+ if (headerIdx === -1) return { removed: 0, proposals: [], groups: [] };
33353
+ const candidates = [];
33354
+ for (let i = headerIdx + 1; i < lines.length; i++) {
33355
+ const line = lines[i];
33356
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
33357
+ if (line.startsWith(" summaries:")) break;
33358
+ const parts = parseToonLine(line);
33359
+ if (parts.length < 7) continue;
33360
+ const [id2, category, key, content] = parts;
33361
+ const hit = extractVersion(`${key} ${content}`.toLowerCase());
33362
+ if (hit && key.toLowerCase().includes(hit.base)) {
33363
+ candidates.push({ lineIdx: i, id: id2, key, content, category, base: hit.base, version: hit.version });
33364
+ }
33365
+ }
33366
+ if (candidates.length < 2) return { removed: 0, proposals: [], groups: [] };
33367
+ const byBase = /* @__PURE__ */ new Map();
33368
+ for (const c2 of candidates) {
33369
+ const list = byBase.get(c2.base) || [];
33370
+ list.push(c2);
33371
+ byBase.set(c2.base, list);
33372
+ }
33373
+ const groups = [];
33374
+ for (const [base, list] of byBase) {
33375
+ if (list.length < 2) continue;
33376
+ const sorted = [...list].sort((a, b2) => compareVersions(b2.version, a.version));
33377
+ const winner = sorted[0];
33378
+ const losers = sorted.slice(1);
33379
+ if (losers.length === 0) continue;
33380
+ groups.push({ base, winner: winner.key, losers: losers.map((l) => l.key) });
33381
+ }
33382
+ if (groups.length === 0) return { removed: 0, proposals: [], groups };
33383
+ if (dryRun) return { removed: 0, proposals: groups.map((g) => `Replace ${g.losers.join(", ")} by ${g.winner}`), groups };
33384
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
33385
+ let changed = 0;
33386
+ for (const g of groups) {
33387
+ for (const loser of g.losers) {
33388
+ const hit = candidates.find((c2) => c2.key === loser);
33389
+ if (!hit) continue;
33390
+ const parts = parseToonLine(lines[hit.lineIdx]);
33391
+ while (parts.length < 18) parts.push("");
33392
+ parts[9] = parts[9] ? `${parts[9]} ${g.winner}` : g.winner;
33393
+ parts[16] = "obsolete";
33394
+ parts[17] = today;
33395
+ lines[hit.lineIdx] = toToonLine(parts);
33396
+ changed++;
33397
+ }
33398
+ }
33399
+ if (changed === 0) return { removed: 0, proposals: [], groups };
33400
+ writeMemory(lines.join("\n"));
33401
+ return { removed: changed, proposals: groups.map((g) => `Replace ${g.losers.join(", ")} by ${g.winner}`), groups };
33402
+ }
33245
33403
 
33246
33404
  // src/mcp/tools.ts
33247
33405
  init_graph();
@@ -33252,9 +33410,9 @@ init_graph();
33252
33410
  init_utils();
33253
33411
  init_synonyms();
33254
33412
  init_fuzzy();
33255
- init_sessions();
33256
33413
  import { existsSync as existsSync9 } from "fs";
33257
33414
  import { join as join6 } from "path";
33415
+ init_sessions();
33258
33416
 
33259
33417
  // src/lib/git.ts
33260
33418
  init_sessions();
@@ -33802,8 +33960,9 @@ function formatHealth(data) {
33802
33960
  if (expired.length > 0) {
33803
33961
  warnings.push(`${expired.length} entries with expired TTL (run memory_archive)`);
33804
33962
  }
33805
- if (entries.length > 80) {
33806
- warnings.push(`${entries.length} entries (near limit of 100, auto-archive will trigger)`);
33963
+ const maxEntries = getMaxEntries();
33964
+ if (entries.length > Math.floor(maxEntries * 0.8)) {
33965
+ warnings.push(`${entries.length} entries (near limit of ${maxEntries}, auto-archive triggers on the next memory_remember that exceeds it)`);
33807
33966
  }
33808
33967
  const orphanLinks = findOrphanLinks(entries);
33809
33968
  if (orphanLinks.length > 0) {
@@ -33994,6 +34153,24 @@ function generateContextHealth(data, root) {
33994
34153
  const warnings = [];
33995
34154
  const info = [];
33996
34155
  let score = 100;
34156
+ const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
34157
+ const TTL_RE = /^\d{4}(?:-\d{2}-\d{2})?$/;
34158
+ const malformed = [];
34159
+ for (const line of entryLines(data)) {
34160
+ const parts2 = parseToonLine(line);
34161
+ if (parts2.length < 7) {
34162
+ malformed.push(`too few fields (${parts2.length})`);
34163
+ continue;
34164
+ }
34165
+ const date5 = parts2[6] || "";
34166
+ if (date5 && !DATE_RE.test(date5)) malformed.push(`${parts2[2]} (date=${JSON.stringify(date5)})`);
34167
+ const ttl = parts2[7] || "";
34168
+ if (ttl && !DATE_RE.test(ttl) && !TTL_RE.test(ttl)) malformed.push(`${parts2[2]} (ttl=${JSON.stringify(ttl)})`);
34169
+ }
34170
+ if (malformed.length > 0) {
34171
+ critical.push(`${malformed.length} malformed entries: ${malformed.slice(0, 3).join("; ")}`);
34172
+ score -= 20;
34173
+ }
33997
34174
  const keys = new Set(entries.map((e) => e.key));
33998
34175
  const orphanLinks = [];
33999
34176
  for (const e of entries) {
@@ -34090,8 +34267,9 @@ function generateContextHealth(data, root) {
34090
34267
  warnings.push(`${staleClaims.length} potentially overlapping claims: ${staleClaims.slice(0, 3).join("; ")}`);
34091
34268
  score -= 3;
34092
34269
  }
34093
- if (entries.length > 80) {
34094
- warnings.push(`${entries.length} entries (near limit of 100)`);
34270
+ const maxEntries = getMaxEntries();
34271
+ if (entries.length > Math.floor(maxEntries * 0.8)) {
34272
+ warnings.push(`${entries.length} entries (near limit of ${maxEntries})`);
34095
34273
  score -= 3;
34096
34274
  } else if (entries.length === 0) {
34097
34275
  info.push("Empty memory");
@@ -34365,6 +34543,30 @@ Duplicates: ${result.duplicates.join(", ")}`
34365
34543
  }]
34366
34544
  };
34367
34545
  }
34546
+ function runConsolidateVersions(dryRun) {
34547
+ const result = consolidateVersions(dryRun);
34548
+ if (result.groups.length === 0) {
34549
+ return { content: [{ type: "text", text: "\u2705 No version supersession detected." }] };
34550
+ }
34551
+ if (dryRun) {
34552
+ return {
34553
+ content: [{
34554
+ type: "text",
34555
+ text: `\u{1F50D} Version supersession candidates (${result.groups.length}):
34556
+ ${result.proposals.map((p2) => ` \u2022 ${p2}`).join("\n")}
34557
+
34558
+ Run again with dryRun: false to apply.`
34559
+ }]
34560
+ };
34561
+ }
34562
+ return {
34563
+ content: [{
34564
+ type: "text",
34565
+ text: `\u{1F5C2}\uFE0F Marked ${result.removed} old-version entries obsolete:
34566
+ ${result.proposals.map((p2) => ` \u2022 ${p2}`).join("\n")}`
34567
+ }]
34568
+ };
34569
+ }
34368
34570
  function runMergeSimilar(dryRun) {
34369
34571
  const data = readMemory();
34370
34572
  const lines = data.split("\n");
@@ -34538,7 +34740,7 @@ ${mergeActions.join("\n")}`
34538
34740
  title: "Save to Memory",
34539
34741
  description: "Save a fact to the project's persistent memory (decisions, patterns, bugs, knowledge). Persists between sessions. Tags: 'private' excludes from context injection; 'superseded' marks as obsolete.",
34540
34742
  inputSchema: {
34541
- category: external_exports.enum(["decision", "pattern", "bug", "knowledge"]).describe("Category of the fact"),
34743
+ category: external_exports.enum(["decision", "pattern", "bug", "knowledge", "warning"]).describe("Category of the fact. 'warning' = negative memory ('NO hacer esto, rompe X') \u2014 recalled with a boost so past mistakes surface first."),
34542
34744
  key: external_exports.string().describe("Short title in kebab-case (e.g. risk-engine-priority)"),
34543
34745
  content: external_exports.string().describe("Detailed content of the fact"),
34544
34746
  file: external_exports.string().optional().default("").describe("Related file or line (e.g. spec.md:145)"),
@@ -34644,6 +34846,8 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34644
34846
  hops: external_exports.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
34645
34847
  compact: external_exports.boolean().optional().default(false).describe("Token-efficient output: numeric indices (1, 2), omits id/date/file (keeps tags), edges as '->2', truncates graph neighbors to a snippet. Does not mutate .toon file."),
34646
34848
  budget: external_exports.enum(["tiny", "normal", "deep"]).optional().default("deep").describe("'tiny': key+1 line (~50 tokens). 'normal': compact with tags/edges. 'deep': all fields (default). Overrides 'compact'."),
34849
+ budget_tokens: external_exports.number().optional().default(0).describe("Deterministic token budget: include entries until the estimated output reaches ~N tokens (overrides limit). 0 = no budget."),
34850
+ explain: external_exports.boolean().optional().default(false).describe("Append a 'why this entry' line to each result (relevance %, times used, last used, importance). No LLM \u2014 pure heuristics."),
34647
34851
  bias: external_exports.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
34648
34852
  path_scope: external_exports.string().optional().default("").describe("Glob pattern to filter entries by path scope (e.g. 'src/**.ts')."),
34649
34853
  rrf: external_exports.boolean().optional().default(false).describe("Use Reciprocal Rank Fusion (BM25x3 + centrality ranks, adaptive k=sqrtN) instead of weighted linear scoring. Weight-free: reaches parity with the tuned linear scorer on scripts/bench-rrf.mjs."),
@@ -34651,7 +34855,7 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34651
34855
  },
34652
34856
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
34653
34857
  },
34654
- async ({ query, category, from_date, to_date, mode, hops, compact, bias, budget: budgetParam, path_scope, rrf, as_of }) => {
34858
+ async ({ query, category, from_date, to_date, mode, hops, compact, budget: budgetParam, budget_tokens, explain, bias, path_scope, rrf, as_of }) => {
34655
34859
  const data = readMemory();
34656
34860
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
34657
34861
  const resolvedBudget = budgetParam || (compact ? "normal" : "deep");
@@ -34660,12 +34864,15 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34660
34864
  return { content: [{ type: "text", text: `No results found for "${query}"` }] };
34661
34865
  }
34662
34866
  bumpAccessed(detail.entries.map((e) => e.id));
34867
+ const reasons = explain ? detail.reasons : void 0;
34663
34868
  if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
34664
34869
  const formatted2 = renderCompact(detail.entries, {
34665
34870
  adjacency: detail.adjacency,
34666
34871
  seeds: detail.seeds,
34667
34872
  snippetLen: 90,
34668
- budget: resolvedBudget
34873
+ budget: resolvedBudget,
34874
+ reasons,
34875
+ budgetTokens: budget_tokens || void 0
34669
34876
  });
34670
34877
  return { content: [{ type: "text", text: formatted2 }] };
34671
34878
  }
@@ -34677,10 +34884,23 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34677
34884
  const scopeInfo = r2.path_scope ? ` | scope: ${r2.path_scope}` : "";
34678
34885
  const statusInfo = r2.status !== "active" ? ` | status: ${r2.status}` : "";
34679
34886
  const supersededInfo = r2.supersededOn ? ` | superseded: ${r2.supersededOn}` : "";
34887
+ const why = reasons?.get(r2.key) ? `
34888
+ \u21B3 ${reasons.get(r2.key)}` : "";
34680
34889
  return `[${r2.category}] ${r2.key}${pin} (${r2.id})
34681
34890
  ${r2.content}
34682
- File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}`;
34891
+ File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}${why}`;
34683
34892
  }).join("\n\n");
34893
+ if (budget_tokens && budget_tokens > 0) {
34894
+ const blocks = formatted.split("\n\n");
34895
+ let acc = 0;
34896
+ let out = [];
34897
+ for (let i = 0; i < blocks.length; i++) {
34898
+ acc += estimateTokens(blocks[i]);
34899
+ if (i > 0 && acc > budget_tokens) break;
34900
+ out.push(blocks[i]);
34901
+ }
34902
+ return { content: [{ type: "text", text: out.join("\n\n") }] };
34903
+ }
34684
34904
  return { content: [{ type: "text", text: formatted }] };
34685
34905
  }
34686
34906
  );
@@ -34736,10 +34956,25 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34736
34956
  const summaryLines = data.split("\n").filter((l) => l.includes(":") && !l.startsWith(" ") && !l.startsWith("version") && !l.startsWith("entries") && !/^\[\d+\|]/.test(l));
34737
34957
  const byOrigin = {};
34738
34958
  const byStatus = {};
34739
- for (const e of entries) {
34740
- byOrigin[e.origin || "agent"] = (byOrigin[e.origin || "agent"] || 0) + 1;
34741
- byStatus[e.status || "active"] = (byStatus[e.status || "active"] || 0) + 1;
34742
- }
34959
+ const accessed = /* @__PURE__ */ new Map();
34960
+ const fullParts = lines.filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")).map((l) => parseToonLine(l));
34961
+ for (const p2 of fullParts) {
34962
+ byOrigin[p2.length > 15 ? p2[15] || "agent" : "agent"] = (byOrigin[p2.length > 15 ? p2[15] || "agent" : "agent"] || 0) + 1;
34963
+ const st2 = p2.length > 16 ? p2[16] || "active" : "active";
34964
+ byStatus[st2] = (byStatus[st2] || 0) + 1;
34965
+ accessed.set(p2[0], p2.length > 8 ? parseInt(p2[8]) || 0 : 0);
34966
+ }
34967
+ const hitRate = entries.length > 0 ? (fullParts.filter((p2) => (parseInt(p2[8]) || 0) > 0).length / entries.length * 100).toFixed(0) : "0";
34968
+ const contentCounts = /* @__PURE__ */ new Map();
34969
+ for (const p2 of fullParts) {
34970
+ const norm = (p2[3] || "").toLowerCase().replace(/\s+/g, " ").trim();
34971
+ contentCounts.set(norm, (contentCounts.get(norm) || 0) + 1);
34972
+ }
34973
+ let dupCount = 0;
34974
+ for (const c2 of contentCounts.values()) if (c2 > 1) dupCount += c2 - 1;
34975
+ const dupPct = entries.length > 0 ? (dupCount / entries.length * 100).toFixed(0) : "0";
34976
+ const deadCount = byStatus["obsolete"] || 0;
34977
+ const deadPct = entries.length > 0 ? (deadCount / entries.length * 100).toFixed(0) : "0";
34743
34978
  const stats = [
34744
34979
  `Total entries: ${entries.length}`,
34745
34980
  `File summaries: ${summaryLines.length}`,
@@ -34756,6 +34991,10 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34756
34991
  `TTL: ${withTtl} with expiration, ${expired} expired`,
34757
34992
  `Average quality: ${avgQuality} (${withQuality} with score)`,
34758
34993
  "",
34994
+ `Hit rate: ${hitRate}% recalled at least once (${fullParts.filter((p2) => (parseInt(p2[8]) || 0) > 0).length}/${entries.length})`,
34995
+ `Duplicate: ${dupPct}% (${dupCount} exact-content dups)`,
34996
+ `Dead: ${deadPct}% (${deadCount} obsolete)`,
34997
+ "",
34759
34998
  `Last 5 entries:`,
34760
34999
  ...lines.slice(-5).map((l) => {
34761
35000
  const parts = parseToonLine(l);
@@ -34891,15 +35130,17 @@ ${formatted}` }] };
34891
35130
  limit: external_exports.number().optional().default(8).describe("Maximum entries to return"),
34892
35131
  category: external_exports.string().optional().default("").describe("Filter by category (empty = all)"),
34893
35132
  bias: external_exports.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
34894
- rrf: external_exports.boolean().optional().default(false).describe("Use Reciprocal Rank Fusion (BM25x3 + centrality ranks, adaptive k=sqrtN) instead of weighted linear scoring. Weight-free: reaches parity with the tuned linear scorer on scripts/bench-rrf.mjs.")
35133
+ rrf: external_exports.boolean().optional().default(false).describe("Use Reciprocal Rank Fusion (BM25x3 + centrality ranks, adaptive k=sqrtN) instead of weighted linear scoring. Weight-free: reaches parity with the tuned linear scorer on scripts/bench-rrf.mjs."),
35134
+ budget_tokens: external_exports.number().optional().default(0).describe("Deterministic token budget: include entries until the estimated output reaches ~N tokens (overrides limit). 0 = no budget."),
35135
+ explain: external_exports.boolean().optional().default(false).describe("Append a 'why this entry' line to each result (relevance %, times used, last used, importance). No LLM \u2014 pure heuristics.")
34895
35136
  },
34896
35137
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
34897
35138
  },
34898
- async ({ intent, limit, category, bias, rrf }) => {
35139
+ async ({ intent, limit, category, bias, rrf, budget_tokens, explain }) => {
34899
35140
  const data = readMemory();
34900
35141
  const mtimes = fileMtimes();
34901
35142
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
34902
- const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles, rrf });
35143
+ const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles, rrf, budgetTokens: budget_tokens || void 0, explain });
34903
35144
  return { content: [{ type: "text", text: result }] };
34904
35145
  }
34905
35146
  );
@@ -35074,9 +35315,9 @@ ${formatted}` }] };
35074
35315
  "memory_consolidate",
35075
35316
  {
35076
35317
  title: "Consolidate Memory",
35077
- description: "Cleanup operations, all deterministic (no LLM): identical removes duplicate entries (keeps the first), similar merges entries with >50% word overlap (keeps longer content, combines tags), low-quality removes entries below minQuality or without tags.",
35318
+ description: "Cleanup operations, all deterministic (no LLM): identical removes duplicate entries (keeps the first), similar merges entries with >50% word overlap (keeps longer content, combines tags), low-quality removes entries below minQuality or without tags, versions marks entries describing the same subject with older versions obsolete in favor of the newest.",
35078
35319
  inputSchema: {
35079
- mode: external_exports.enum(["identical", "similar", "low-quality"]).optional().default("identical").describe("identical: dedupe entries with identical content (default). similar: merge entries with >50% word overlap. low-quality: remove entries below minQuality or without tags."),
35320
+ mode: external_exports.enum(["identical", "similar", "low-quality", "versions"]).optional().default("identical").describe("identical: dedupe entries with identical content (default). similar: merge entries with >50% word overlap. low-quality: remove entries below minQuality or without tags. versions: detect version supersession ('Use React 18' vs 'React 19') and obsolete the older ones."),
35080
35321
  minQuality: external_exports.number().optional().default(0.3).describe("Entries below this quality score are candidates (only used with mode: low-quality)."),
35081
35322
  dryRun: external_exports.boolean().optional().default(false).describe("If true, show what would change without writing.")
35082
35323
  },
@@ -35088,6 +35329,8 @@ ${formatted}` }] };
35088
35329
  return runMergeSimilar(dryRun);
35089
35330
  case "low-quality":
35090
35331
  return runCompressAll(minQuality, dryRun);
35332
+ case "versions":
35333
+ return runConsolidateVersions(dryRun);
35091
35334
  default:
35092
35335
  return runConsolidate();
35093
35336
  }
@@ -47939,7 +48182,7 @@ function registerResources(server2) {
47939
48182
 
47940
48183
  // src/mcp/server.ts
47941
48184
  var server = new McpServer(
47942
- { name: "toon-memory", version: "4.1.1" },
48185
+ { name: "toon-memory", version: "4.2.0" },
47943
48186
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true }, experimental: { "io.modelcontextprotocol/ui": {} } } }
47944
48187
  );
47945
48188
  var s = server.server;
@@ -47951,7 +48194,7 @@ s.setRequestHandler(InitializeRequestSchema, async (request) => {
47951
48194
  return {
47952
48195
  protocolVersion,
47953
48196
  capabilities: s.getCapabilities(),
47954
- serverInfo: { name: "toon-memory", version: "4.1.1" },
48197
+ serverInfo: { name: "toon-memory", version: "4.2.0" },
47955
48198
  ...s._instructions && { instructions: s._instructions }
47956
48199
  };
47957
48200
  });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "toon-memory",
3
3
  "mcpName": "io.github.LuiggiVal08/toon-memory",
4
- "version": "4.1.1",
4
+ "version": "4.2.0",
5
5
  "description": "MCP server giving AI coding agents offline, token-efficient persistent memory — 35 tools, 80% fewer tool calls, recall decisions, patterns, and bugs across sessions. No LLM, no server; works with 15+ agents.",
6
6
  "type": "module",
7
7
  "bin": {
@@ -15,11 +15,12 @@
15
15
 
16
16
  import { existsSync, readFileSync } from "fs"
17
17
  import { join } from "path"
18
- import { parseEntries, buildGraph, bm25Scores, centrality, renderCompact, type GraphEntry } from "./graph"
18
+ import { parseEntries, buildGraph, bm25Scores, centrality, renderCompact, entryLines, type GraphEntry } from "./graph"
19
19
  import { qualityScore } from "./quality"
20
- import { normalize, isExpiredLocal, tokenize, importance, isPrivate } from "./utils"
20
+ import { normalize, isExpiredLocal, tokenize, importance, isPrivate, parseToonLine } from "./utils"
21
21
  import { expandSynonyms } from "./synonyms"
22
22
  import { fuzzyMatch } from "./fuzzy"
23
+ import { getMaxEntries } from "../mcp/config"
23
24
  import { coordinationView, currentBranch, pruneSessions, listSessions } from "./sessions"
24
25
  import { readRecentCommits, gitStatusSummary, readGitIndex, fileMtimes } from "./git"
25
26
  import { scanProjectStructure, readManifest, readEnvExample } from "./project-scan"
@@ -176,8 +177,9 @@ function formatHealth(data: string): string {
176
177
  warnings.push(`${expired.length} entries with expired TTL (run memory_archive)`)
177
178
  }
178
179
 
179
- if (entries.length > 80) {
180
- warnings.push(`${entries.length} entries (near limit of 100, auto-archive will trigger)`)
180
+ const maxEntries = getMaxEntries()
181
+ if (entries.length > Math.floor(maxEntries * 0.8)) {
182
+ warnings.push(`${entries.length} entries (near limit of ${maxEntries}, auto-archive triggers on the next memory_remember that exceeds it)`)
181
183
  }
182
184
 
183
185
  const orphanLinks = findOrphanLinks(entries)
@@ -495,6 +497,27 @@ export function generateContextHealth(data: string, root: string): { report: Hea
495
497
  const info: string[] = []
496
498
  let score = 100
497
499
 
500
+ // 0. Malformed lines (unescaped-pipe corruption shifts fields; a non-date
501
+ // date field is the reliable signature — seen as "3"/"2"/a file path).
502
+ const DATE_RE = /^\d{4}-\d{2}-\d{2}$/
503
+ const TTL_RE = /^\d{4}(?:-\d{2}-\d{2})?$/
504
+ const malformed: string[] = []
505
+ for (const line of entryLines(data)) {
506
+ const parts = parseToonLine(line)
507
+ if (parts.length < 7) {
508
+ malformed.push(`too few fields (${parts.length})`)
509
+ continue
510
+ }
511
+ const date = parts[6] || ""
512
+ if (date && !DATE_RE.test(date)) malformed.push(`${parts[2]} (date=${JSON.stringify(date)})`)
513
+ const ttl = parts[7] || ""
514
+ if (ttl && !DATE_RE.test(ttl) && !TTL_RE.test(ttl)) malformed.push(`${parts[2]} (ttl=${JSON.stringify(ttl)})`)
515
+ }
516
+ if (malformed.length > 0) {
517
+ critical.push(`${malformed.length} malformed entries: ${malformed.slice(0, 3).join("; ")}`)
518
+ score -= 20
519
+ }
520
+
498
521
  // 1. Orphan links
499
522
  const keys = new Set(entries.map((e) => e.key))
500
523
  const orphanLinks: string[] = []
@@ -611,8 +634,9 @@ export function generateContextHealth(data: string, root: string): { report: Hea
611
634
  }
612
635
 
613
636
  // 10. Entry count
614
- if (entries.length > 80) {
615
- warnings.push(`${entries.length} entries (near limit of 100)`)
637
+ const maxEntries = getMaxEntries()
638
+ if (entries.length > Math.floor(maxEntries * 0.8)) {
639
+ warnings.push(`${entries.length} entries (near limit of ${maxEntries})`)
616
640
  score -= 3
617
641
  } else if (entries.length === 0) {
618
642
  info.push("Empty memory")
package/src/lib/graph.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  * without mutating the stored `.toon` file.
15
15
  */
16
16
 
17
- import { normalize, isExpiredLocal, tokenize, importance, parseToonLine } from "./utils"
17
+ import { normalize, isExpiredLocal, tokenize, importance, estimateTokens, parseToonLine } from "./utils"
18
18
  import { expandSynonyms } from "./synonyms"
19
19
  import { fuzzyMatch } from "./fuzzy"
20
20
 
@@ -86,7 +86,7 @@ export interface MemoryGraph {
86
86
  byKey: Map<string, GraphEntry>
87
87
  }
88
88
 
89
- const entryLines = (data: string): string[] =>
89
+ export const entryLines = (data: string): string[] =>
90
90
  data
91
91
  .split("\n")
92
92
  .filter(
@@ -389,6 +389,37 @@ export interface GraphRecallResult {
389
389
  adjacency: Map<string, string[]>
390
390
  /** Final combined score per key (bm25 + centrality + importance + seed bonus). */
391
391
  scores: Map<string, number>
392
+ /** Optional per-key "why selected" reason strings (Explaining WHY). */
393
+ reasons?: Map<string, string>
394
+ }
395
+
396
+ /**
397
+ * Build a short, deterministic "why was this selected" string per entry.
398
+ * Pure heuristics — no LLM. Used to explain recall results so the agent can
399
+ * trust the ranking instead of trusting a black box.
400
+ */
401
+ export function buildReason(
402
+ e: GraphEntry,
403
+ bm25Score: number,
404
+ bm25Max: number,
405
+ impScore: number,
406
+ today = new Date().toISOString().split("T")[0]
407
+ ): string {
408
+ const parts: string[] = []
409
+ if (bm25Max > 0) {
410
+ parts.push(`${Math.round((bm25Score / bm25Max) * 100)}% relevance`)
411
+ }
412
+ if (e.accessed > 0) {
413
+ parts.push(`used ${e.accessed}×`)
414
+ }
415
+ if (e.lastAccessed) {
416
+ const days = Math.floor((Date.parse(`${today}T00:00:00`) - Date.parse(e.lastAccessed)) / 86400000)
417
+ parts.push(days <= 0 ? "used today" : days === 1 ? "used yesterday" : `used ${days}d ago`)
418
+ } else if (e.accessed === 0) {
419
+ parts.push("never used")
420
+ }
421
+ parts.push(impScore >= 0.7 ? "importance HIGH" : impScore >= 0.4 ? "importance MED" : "importance LOW")
422
+ return parts.join(" · ")
392
423
  }
393
424
 
394
425
  const W_CENT = 0.4
@@ -508,6 +539,8 @@ export function graphRecallDetailed(
508
539
  s *= 1.15
509
540
  }
510
541
  }
542
+ // Negative-memory boost: warnings surface first.
543
+ if (e.category === "warning") s += 0.2
511
544
  s *= decay
512
545
  return { e, s, priority: e.priority }
513
546
  })
@@ -545,7 +578,18 @@ export function graphRecallDetailed(
545
578
  const scores = new Map<string, number>()
546
579
  selected.forEach((e) => scores.set(e.key, scored.find((x) => x.e.key === e.key)!.s))
547
580
 
548
- return { entries: selected, seeds: seedKeys, adjacency: subAdj, scores }
581
+ // Explain WHY: normalize bm25 by its max over the visible candidates.
582
+ let bm25Max = 0
583
+ for (const v of bm25.values()) if (v > bm25Max) bm25Max = v
584
+ const reasons = new Map<string, string>()
585
+ for (const e of selected) {
586
+ reasons.set(
587
+ e.key,
588
+ buildReason(e, bm25.get(e.key) || 0, bm25Max, importance(e, opts.today), opts.today)
589
+ )
590
+ }
591
+
592
+ return { entries: selected, seeds: seedKeys, adjacency: subAdj, scores, reasons }
549
593
  }
550
594
 
551
595
  /**
@@ -568,6 +612,10 @@ export interface RenderCompactOpts {
568
612
  snippetLen?: number
569
613
  /** Budget level: "tiny" (key+1 line), "normal" (compact, default), "deep" (all fields). */
570
614
  budget?: "tiny" | "normal" | "deep"
615
+ /** Optional per-key reason strings appended after each entry ("why it was selected"). */
616
+ reasons?: Map<string, string>
617
+ /** Deterministic token budget: stop after entries consume ~N estimated tokens. */
618
+ budgetTokens?: number
571
619
  }
572
620
 
573
621
  /**
@@ -614,31 +662,31 @@ export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {
614
662
 
615
663
  const budget = opts.budget ?? "normal"
616
664
 
617
- return entries
618
- .map((e) => {
619
- const n = index.get(e.key)!
620
- const isSeed = opts.seeds ? opts.seeds.has(e.key) : true
621
-
622
- if (budget === "tiny") {
623
- const firstLine = e.content.split("\n")[0] || ""
624
- const snippet = firstLine.length > 80 ? firstLine.slice(0, 80).trimEnd() + "…" : firstLine
625
- const pin = e.priority > 0 ? (e.priority > 1 ? ` 📌${e.priority}` : " 📌") : ""
626
- return `[${n}] ${e.category}/${e.key}${pin}\n ${snippet}`
627
- }
628
-
629
- if (budget === "deep") {
630
- const ttlInfo = e.ttl ? ` · ttl: ${e.ttl}` : ""
631
- const accessInfo = e.accessed > 0 ? ` · accessed: ${e.accessed}x` : ""
632
- const lastAccess = e.lastAccessed ? ` · lastAccess: ${e.lastAccessed}` : ""
633
- const pin = e.priority > 0 ? (e.priority > 1 ? ` 📌${e.priority}` : " 📌") : ""
634
- const links = e.links.length ? `\n links: ${e.links.join(", ")}` : ""
635
- const originInfo = e.origin !== "agent" ? ` · origin: ${e.origin}` : ""
636
- const scopeInfo = e.path_scope ? ` · scope: ${e.path_scope}` : ""
637
- const statusInfo = e.status !== "active" ? ` · status: ${e.status}` : ""
638
- const supersededInfo = e.supersededOn ? ` · superseded: ${e.supersededOn}` : ""
639
- return `[${n}] ${e.category}/${e.key}${pin} (${e.id})\n ${e.content}\n File: ${e.file} | Tags: ${e.tags.join(";")} | Date: ${e.date}${ttlInfo}${accessInfo}${lastAccess}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}${links}`
640
- }
641
-
665
+ const rendered: string[] = []
666
+ let tokens = 0
667
+ for (const e of entries) {
668
+ const n = index.get(e.key)!
669
+ const isSeed = opts.seeds ? opts.seeds.has(e.key) : true
670
+ const reason = opts.reasons?.get(e.key)
671
+ let block: string
672
+
673
+ if (budget === "tiny") {
674
+ const firstLine = e.content.split("\n")[0] || ""
675
+ const snippet = firstLine.length > 80 ? firstLine.slice(0, 80).trimEnd() + "…" : firstLine
676
+ const pin = e.priority > 0 ? (e.priority > 1 ? ` 📌${e.priority}` : " 📌") : ""
677
+ block = `[${n}] ${e.category}/${e.key}${pin}\n ${snippet}`
678
+ } else if (budget === "deep") {
679
+ const ttlInfo = e.ttl ? ` · ttl: ${e.ttl}` : ""
680
+ const accessInfo = e.accessed > 0 ? ` · accessed: ${e.accessed}x` : ""
681
+ const lastAccess = e.lastAccessed ? ` · lastAccess: ${e.lastAccessed}` : ""
682
+ const pin = e.priority > 0 ? (e.priority > 1 ? ` 📌${e.priority}` : " 📌") : ""
683
+ const links = e.links.length ? `\n links: ${e.links.join(", ")}` : ""
684
+ const originInfo = e.origin !== "agent" ? ` · origin: ${e.origin}` : ""
685
+ const scopeInfo = e.path_scope ? ` · scope: ${e.path_scope}` : ""
686
+ const statusInfo = e.status !== "active" ? ` · status: ${e.status}` : ""
687
+ const supersededInfo = e.supersededOn ? ` · superseded: ${e.supersededOn}` : ""
688
+ block = `[${n}] ${e.category}/${e.key}${pin} (${e.id})\n ${e.content}\n File: ${e.file} | Tags: ${e.tags.join(";")} | Date: ${e.date}${ttlInfo}${accessInfo}${lastAccess}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}${links}`
689
+ } else {
642
690
  // "normal" budget (default)
643
691
  let body = e.content
644
692
  if (!isSeed && e.content.length > snippetLen) {
@@ -653,7 +701,21 @@ export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {
653
701
  .filter((x): x is number => typeof x === "number")
654
702
  if (nb.length) edges = ` · edges: ->${nb.join(", ->")}`
655
703
  }
656
- return `[${n}] ${e.category}/${e.key}${tag}\n ${body}${tags}${edges}`
657
- })
658
- .join("\n\n")
704
+ block = `[${n}] ${e.category}/${e.key}${tag}\n ${body}${tags}${edges}`
705
+ }
706
+
707
+ if (reason) block += `\n ↳ ${reason}`
708
+ rendered.push(block)
709
+
710
+ // Deterministic token budget: stop before the accumulated estimate exceeds it.
711
+ if (opts.budgetTokens && opts.budgetTokens > 0) {
712
+ tokens += estimateTokens(block)
713
+ if (rendered.length > 1 && tokens > opts.budgetTokens) {
714
+ rendered.pop()
715
+ break
716
+ }
717
+ }
718
+ }
719
+
720
+ return rendered.join("\n\n")
659
721
  }
@@ -16,9 +16,11 @@ import {
16
16
  rankBy,
17
17
  rrfFuse,
18
18
  rrfK,
19
+ globMatch,
20
+ buildReason,
19
21
  type GraphEntry,
20
22
  } from "./graph"
21
- import { normalize, isExpiredLocal, tokenize, importance, isPrivate, parseToonLine, toToonLine } from "./utils"
23
+ import { normalize, isExpiredLocal, tokenize, importance, isPrivate, estimateTokens, languageFamily, parseToonLine, toToonLine } from "./utils"
22
24
  import { expandSynonyms } from "./synonyms"
23
25
  import { fuzzyMatch } from "./fuzzy"
24
26
 
@@ -188,7 +190,17 @@ export function mergeEntries(existingLine: string, newLine: string): string {
188
190
  export function generateSmartRecall(
189
191
  data: string,
190
192
  intent: string,
191
- opts: { limit?: number; category?: string; bumpAccess?: (ids: string[]) => void; fileMtimes?: Map<string, string>; sessionFiles?: string[]; rrf?: boolean; today?: string } = {}
193
+ opts: {
194
+ limit?: number
195
+ category?: string
196
+ bumpAccess?: (ids: string[]) => void
197
+ fileMtimes?: Map<string, string>
198
+ sessionFiles?: string[]
199
+ rrf?: boolean
200
+ today?: string
201
+ explain?: boolean
202
+ budgetTokens?: number
203
+ } = {}
192
204
  ): string {
193
205
  const entries = parseEntries(data)
194
206
  if (entries.length === 0) return "Empty memory."
@@ -247,14 +259,27 @@ export function generateSmartRecall(
247
259
  sessionBias = 0.15
248
260
  }
249
261
  }
262
+ // Language match: same script family as the query gets a small boost
263
+ // (a Spanish query should prefer Spanish entries over English ones).
264
+ let langBoost = 0
265
+ const qFamily = languageFamily(intent)
266
+ if (qFamily !== "none") {
267
+ const eFamily = languageFamily(`${e.content} ${e.key} ${e.tags.join(" ")}`)
268
+ if (qFamily === eFamily) langBoost = 0.1
269
+ }
270
+ // Folder match: entries scoped to the current working directory get a boost.
271
+ let folderBoost = 0
272
+ if (e.path_scope && globMatch(e.path_scope, ".")) folderBoost = 0.05
273
+ // Negative-memory boost: warnings are cheap to ignore and expensive to repeat.
274
+ const warningBoost = e.category === "warning" ? 0.2 : 0
250
275
  let combined: number
251
276
  if (opts.rrf) {
252
- combined = (fused?.get(e.key) ?? 0) - drift + sessionBias
277
+ combined = (fused?.get(e.key) ?? 0) - drift + sessionBias + langBoost + folderBoost + warningBoost
253
278
  } else {
254
279
  combined =
255
- bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias
280
+ bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias + langBoost + folderBoost + warningBoost
256
281
  }
257
- return { entry: e, score: combined, matchesQuery, priority: e.priority }
282
+ return { entry: e, score: combined, matchesQuery, priority: e.priority, bm25Score }
258
283
  })
259
284
  .filter((x) => x.score > 0 || x.matchesQuery)
260
285
  .sort((a, b) => {
@@ -272,7 +297,7 @@ export function generateSmartRecall(
272
297
  .filter(Boolean)
273
298
  .sort((a, b) => b.priority - a.priority)
274
299
  for (const e of toInject) {
275
- scored.unshift({ entry: e, score: 999, matchesQuery: false, priority: e.priority })
300
+ scored.unshift({ entry: e, score: 999, matchesQuery: false, priority: e.priority, bm25Score: 0 })
276
301
  }
277
302
 
278
303
  if (scored.length === 0) {
@@ -283,11 +308,24 @@ export function generateSmartRecall(
283
308
  })
284
309
  .slice(0, limit)
285
310
  if (top.length === 0) return "No entries in memory."
286
- return renderCompact(top)
311
+ return renderCompact(top, { budgetTokens: opts.budgetTokens })
287
312
  }
288
313
 
289
314
  if (opts.bumpAccess) opts.bumpAccess(scored.map((x) => x.entry.id))
290
- return renderCompact(scored.map((x) => x.entry))
315
+
316
+ // Explain WHY: build per-key reasons with the same determinism as graph recall.
317
+ let bm25Max = 0
318
+ for (const s of scored) if (s.bm25Score > bm25Max) bm25Max = s.bm25Score
319
+ const reasons = new Map<string, string>()
320
+ if (opts.explain) {
321
+ for (const s of scored) {
322
+ reasons.set(
323
+ s.entry.key,
324
+ buildReason(s.entry, s.bm25Score, bm25Max, importance(s.entry, opts.today), opts.today)
325
+ )
326
+ }
327
+ }
328
+ return renderCompact(scored.map((x) => x.entry), { reasons: opts.explain ? reasons : undefined, budgetTokens: opts.budgetTokens })
291
329
  }
292
330
 
293
331
  /**
package/src/lib/utils.ts CHANGED
@@ -31,6 +31,46 @@ export const tokenize = (s: string): string[] =>
31
31
  .split(/\s+/)
32
32
  .filter(Boolean)
33
33
 
34
+ /**
35
+ * Deterministic token estimate for a text: roughly one token per 4 chars,
36
+ * plus one per whitespace run. No LLM — good enough to budget recall output.
37
+ */
38
+ export const estimateTokens = (s: string): number => {
39
+ if (!s) return 0
40
+ const chars = Math.ceil(s.length / 4)
41
+ const words = (s.match(/\S+/g) || []).length
42
+ return Math.max(1, chars + words)
43
+ }
44
+
45
+ /**
46
+ * Language-family detection via character ranges. Deterministic, no libraries.
47
+ * Returns "latin" for ASCII/EU languages, "cjk" for CJK, "cyrillic", "arabic",
48
+ * "greek", "hebrew", "devanagari", or "other".
49
+ */
50
+ export const languageFamily = (s: string): string => {
51
+ let cjk = 0, cyr = 0, arab = 0, greek = 0, hebrew = 0, deva = 0, latin = 0, total = 0
52
+ for (const ch of s) {
53
+ const c = ch.codePointAt(0)!
54
+ if (!/[\p{L}]/u.test(ch)) continue
55
+ total++
56
+ if (c >= 0x4e00 && c <= 0x9fff || c >= 0x3040 && c <= 0x30ff || c >= 0xac00 && c <= 0xd7af) cjk++
57
+ else if (c >= 0x0400 && c <= 0x04ff) cyr++
58
+ else if (c >= 0x0600 && c <= 0x06ff) arab++
59
+ else if (c >= 0x0370 && c <= 0x03ff) greek++
60
+ else if (c >= 0x0590 && c <= 0x05ff) hebrew++
61
+ else if (c >= 0x0900 && c <= 0x097f) deva++
62
+ else latin++
63
+ }
64
+ if (total === 0) return "none"
65
+ if (cjk / total > 0.3) return "cjk"
66
+ if (cyr / total > 0.3) return "cyrillic"
67
+ if (arab / total > 0.3) return "arabic"
68
+ if (greek / total > 0.3) return "greek"
69
+ if (hebrew / total > 0.3) return "hebrew"
70
+ if (deva / total > 0.3) return "devanagari"
71
+ return "latin"
72
+ }
73
+
34
74
  /**
35
75
  * Escape a field for the pipe-delimited TOON format. Literal newlines, pipes and
36
76
  * backslashes would otherwise break line-based parsing (a multi-line content turns
@@ -1,6 +1,6 @@
1
1
  import { readMemory, writeMemory } from "./memory-io"
2
2
  import { mergeEntries } from "../lib/quality"
3
- import { parseToonLine } from "../lib/utils"
3
+ import { parseToonLine, toToonLine } from "../lib/utils"
4
4
 
5
5
  /**
6
6
  * Jaccard similarity between two content strings (0..1).
@@ -114,3 +114,96 @@ export function consolidateEntries(): { removed: number; kept: number; duplicate
114
114
 
115
115
  return { removed: totalRemoved, kept: order.length, duplicates }
116
116
  }
117
+
118
+ /**
119
+ * Extract a (base, version) pair from a versioned key or content line.
120
+ * Matches "Use React 18", "React 18.2", "next 13.5.1", "vite ^5.0.0", etc.
121
+ * Returns null when no version number is present.
122
+ */
123
+ export function extractVersion(text: string): { base: string; version: [number, number, number] } | null {
124
+ const m = text.match(/([A-Za-z][A-Za-z0-9._-]*?)\s*(?:v)?(\d+)\.(\d+)(?:\.(\d+))?/)
125
+ if (!m) return null
126
+ const base = m[1].replace(/[-_.]+$/g, "").toLowerCase()
127
+ return { base, version: [parseInt(m[2]), parseInt(m[3]), m[4] ? parseInt(m[4]) : 0] }
128
+ }
129
+
130
+ /** Compare two [major, minor, patch] version tuples: >0, <0, or 0. */
131
+ function compareVersions(a: [number, number, number], b: [number, number, number]): number {
132
+ for (let i = 0; i < 3; i++) {
133
+ if (a[i] !== b[i]) return a[i] - b[i]
134
+ }
135
+ return 0
136
+ }
137
+
138
+ /**
139
+ * Version-supersession compaction: detect entries that describe the same
140
+ * subject with different versions (e.g. "Use React 18" vs "Use React 19")
141
+ * and mark the older ones obsolete in favor of the newest. Deterministic,
142
+ * no LLM — uses a version regex + base-name grouping.
143
+ *
144
+ * Returns the actions taken (or proposed when `dryRun`).
145
+ */
146
+ export function consolidateVersions(dryRun: boolean): { removed: number; proposals: string[]; groups: Array<{ base: string; winner: string; losers: string[] }> } {
147
+ const data = readMemory()
148
+ const lines = data.split("\n")
149
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
150
+ if (headerIdx === -1) return { removed: 0, proposals: [], groups: [] }
151
+
152
+ interface Candidate { lineIdx: number; id: string; key: string; content: string; category: string; base: string; version: [number, number, number] }
153
+ const candidates: Candidate[] = []
154
+ for (let i = headerIdx + 1; i < lines.length; i++) {
155
+ const line = lines[i]
156
+ if (!line.startsWith(" ") || !line.includes("|")) continue
157
+ if (line.startsWith(" summaries:")) break
158
+ const parts = parseToonLine(line)
159
+ if (parts.length < 7) continue
160
+ const [id, category, key, content] = parts
161
+ const hit = extractVersion(`${key} ${content}`.toLowerCase())
162
+ if (hit && key.toLowerCase().includes(hit.base)) {
163
+ candidates.push({ lineIdx: i, id, key, content, category, base: hit.base, version: hit.version })
164
+ }
165
+ }
166
+ if (candidates.length < 2) return { removed: 0, proposals: [], groups: [] }
167
+
168
+ // Group by base name.
169
+ const byBase = new Map<string, Candidate[]>()
170
+ for (const c of candidates) {
171
+ const list = byBase.get(c.base) || []
172
+ list.push(c)
173
+ byBase.set(c.base, list)
174
+ }
175
+
176
+ const groups: Array<{ base: string; winner: string; losers: string[] }> = []
177
+ for (const [base, list] of byBase) {
178
+ if (list.length < 2) continue
179
+ const sorted = [...list].sort((a, b) => compareVersions(b.version, a.version))
180
+ const winner = sorted[0]
181
+ const losers = sorted.slice(1)
182
+ if (losers.length === 0) continue
183
+ groups.push({ base, winner: winner.key, losers: losers.map((l) => l.key) })
184
+ }
185
+
186
+ if (groups.length === 0) return { removed: 0, proposals: [], groups }
187
+ if (dryRun) return { removed: 0, proposals: groups.map((g) => `Replace ${g.losers.join(", ")} by ${g.winner}`), groups }
188
+
189
+ // Apply: mark losers obsolete with a superseded note.
190
+ const today = new Date().toISOString().split("T")[0]
191
+ let changed = 0
192
+ for (const g of groups) {
193
+ for (const loser of g.losers) {
194
+ const hit = candidates.find((c) => c.key === loser)
195
+ if (!hit) continue
196
+ const parts = parseToonLine(lines[hit.lineIdx])
197
+ while (parts.length < 18) parts.push("")
198
+ parts[9] = parts[9] ? `${parts[9]} ${g.winner}` : g.winner
199
+ parts[16] = "obsolete"
200
+ parts[17] = today
201
+ lines[hit.lineIdx] = toToonLine(parts)
202
+ changed++
203
+ }
204
+ }
205
+ if (changed === 0) return { removed: 0, proposals: [], groups }
206
+
207
+ writeMemory(lines.join("\n"))
208
+ return { removed: changed, proposals: groups.map((g) => `Replace ${g.losers.join(", ")} by ${g.winner}`), groups }
209
+ }
@@ -94,7 +94,7 @@ export function writeSessionEntry(entry: Omit<SessionEntry, "accessed" | "lastAc
94
94
  */
95
95
  export function promoteSessionEntries(
96
96
  entriesToPromote: SessionEntry[],
97
- category: "decision" | "pattern" | "bug" | "knowledge" | "architecture" = "knowledge"
97
+ category: "decision" | "pattern" | "bug" | "knowledge" | "architecture" | "warning" = "knowledge"
98
98
  ): number {
99
99
  if (entriesToPromote.length === 0) return 0
100
100
 
package/src/mcp/tools.ts CHANGED
@@ -9,7 +9,7 @@ import { generateId, parseTTL, isExpired, inferTags, parseRelativeDate } from ".
9
9
  import { findRelatedEntries, bumpAccessed } from "./scoring"
10
10
  import { readObservations } from "./observations"
11
11
  import { archiveOldEntries } from "./archive"
12
- import { consolidateEntries } from "./consolidation"
12
+ import { consolidateEntries, consolidateVersions } from "./consolidation"
13
13
  import { readUnderLock } from "../lib/lock"
14
14
  import { encrypt, decrypt } from "./crypto"
15
15
  import { graphRecallDetailed, renderCompact, parseEntries, buildGraph, parseLinkToken, formatLink, typedLinks } from "../lib/graph"
@@ -17,7 +17,7 @@ import { qualityScore, mergeEntries, generateSmartRecall } from "../lib/quality"
17
17
  import { generateContextBrief, generateContextGenerate, generateContextDiff, generateContextFocus, generateContextHealth, generateContextExport } from "../lib/context"
18
18
  import { coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS, getCurrentSessionFiles } from "../lib/sessions"
19
19
  import { fileMtimes } from "../lib/git"
20
- import { normalize, isExpiredLocal, tokenize, importance, parseToonLine, toToonLine, escField, unescField } from "../lib/utils"
20
+ import { normalize, isExpiredLocal, tokenize, importance, estimateTokens, parseToonLine, toToonLine, escField, unescField } from "../lib/utils"
21
21
  import { expandSynonyms } from "../lib/synonyms"
22
22
 
23
23
  /**
@@ -236,6 +236,27 @@ function runConsolidate(): { content: ToolText[] } {
236
236
  }
237
237
  }
238
238
 
239
+ function runConsolidateVersions(dryRun: boolean): { content: ToolText[] } {
240
+ const result = consolidateVersions(dryRun)
241
+ if (result.groups.length === 0) {
242
+ return { content: [{ type: "text", text: "✅ No version supersession detected." }] }
243
+ }
244
+ if (dryRun) {
245
+ return {
246
+ content: [{
247
+ type: "text",
248
+ text: `🔍 Version supersession candidates (${result.groups.length}):\n${result.proposals.map((p) => ` • ${p}`).join("\n")}\n\nRun again with dryRun: false to apply.`,
249
+ }],
250
+ }
251
+ }
252
+ return {
253
+ content: [{
254
+ type: "text",
255
+ text: `🗂️ Marked ${result.removed} old-version entries obsolete:\n${result.proposals.map((p) => ` • ${p}`).join("\n")}`,
256
+ }],
257
+ }
258
+ }
259
+
239
260
  function runMergeSimilar(dryRun: boolean): { content: ToolText[] } {
240
261
  const data = readMemory()
241
262
  const lines = data.split("\n")
@@ -436,7 +457,7 @@ server.registerTool(
436
457
  title: "Save to Memory",
437
458
  description: "Save a fact to the project's persistent memory (decisions, patterns, bugs, knowledge). Persists between sessions. Tags: 'private' excludes from context injection; 'superseded' marks as obsolete.",
438
459
  inputSchema: {
439
- category: z.enum(["decision", "pattern", "bug", "knowledge"]).describe("Category of the fact"),
460
+ category: z.enum(["decision", "pattern", "bug", "knowledge", "warning"]).describe("Category of the fact. 'warning' = negative memory ('NO hacer esto, rompe X') — recalled with a boost so past mistakes surface first."),
440
461
  key: z.string().describe("Short title in kebab-case (e.g. risk-engine-priority)"),
441
462
  content: z.string().describe("Detailed content of the fact"),
442
463
  file: z.string().optional().default("").describe("Related file or line (e.g. spec.md:145)"),
@@ -549,6 +570,8 @@ server.registerTool(
549
570
  hops: z.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
550
571
  compact: z.boolean().optional().default(false).describe("Token-efficient output: numeric indices (1, 2), omits id/date/file (keeps tags), edges as '->2', truncates graph neighbors to a snippet. Does not mutate .toon file."),
551
572
  budget: z.enum(["tiny", "normal", "deep"]).optional().default("deep").describe("'tiny': key+1 line (~50 tokens). 'normal': compact with tags/edges. 'deep': all fields (default). Overrides 'compact'."),
573
+ budget_tokens: z.number().optional().default(0).describe("Deterministic token budget: include entries until the estimated output reaches ~N tokens (overrides limit). 0 = no budget."),
574
+ explain: z.boolean().optional().default(false).describe("Append a 'why this entry' line to each result (relevance %, times used, last used, importance). No LLM — pure heuristics."),
552
575
  bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
553
576
  path_scope: z.string().optional().default("").describe("Glob pattern to filter entries by path scope (e.g. 'src/**.ts')."),
554
577
  rrf: z.boolean().optional().default(false).describe("Use Reciprocal Rank Fusion (BM25x3 + centrality ranks, adaptive k=sqrtN) instead of weighted linear scoring. Weight-free: reaches parity with the tuned linear scorer on scripts/bench-rrf.mjs."),
@@ -556,7 +579,7 @@ server.registerTool(
556
579
  },
557
580
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
558
581
  },
559
- async ({ query, category, from_date, to_date, mode, hops, compact, bias, budget: budgetParam, path_scope, rrf, as_of }) => {
582
+ async ({ query, category, from_date, to_date, mode, hops, compact, budget: budgetParam, budget_tokens, explain, bias, path_scope, rrf, as_of }) => {
560
583
  const data = readMemory()
561
584
 
562
585
  // Delegate to graphRecallDetailed for both flat and graph modes
@@ -568,12 +591,15 @@ server.registerTool(
568
591
  return { content: [{ type: "text" as const, text: `No results found for "${query}"` }] }
569
592
  }
570
593
  bumpAccessed(detail.entries.map((e) => e.id))
594
+ const reasons = explain ? detail.reasons : undefined
571
595
  if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
572
596
  const formatted = renderCompact(detail.entries, {
573
597
  adjacency: detail.adjacency,
574
598
  seeds: detail.seeds,
575
599
  snippetLen: 90,
576
600
  budget: resolvedBudget,
601
+ reasons,
602
+ budgetTokens: budget_tokens || undefined,
577
603
  })
578
604
  return { content: [{ type: "text" as const, text: formatted }] }
579
605
  }
@@ -585,9 +611,22 @@ server.registerTool(
585
611
  const scopeInfo = r.path_scope ? ` | scope: ${r.path_scope}` : ""
586
612
  const statusInfo = r.status !== "active" ? ` | status: ${r.status}` : ""
587
613
  const supersededInfo = r.supersededOn ? ` | superseded: ${r.supersededOn}` : ""
588
- return `[${r.category}] ${r.key}${pin} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}`
614
+ const why = reasons?.get(r.key) ? `\n ↳ ${reasons.get(r.key)}` : ""
615
+ return `[${r.category}] ${r.key}${pin} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}${why}`
589
616
  })
590
617
  .join("\n\n")
618
+ // Deterministic token budget for the deep render.
619
+ if (budget_tokens && budget_tokens > 0) {
620
+ const blocks = formatted.split("\n\n")
621
+ let acc = 0
622
+ let out: string[] = []
623
+ for (let i = 0; i < blocks.length; i++) {
624
+ acc += estimateTokens(blocks[i])
625
+ if (i > 0 && acc > budget_tokens) break
626
+ out.push(blocks[i])
627
+ }
628
+ return { content: [{ type: "text" as const, text: out.join("\n\n") }] }
629
+ }
591
630
  return { content: [{ type: "text" as const, text: formatted }] }
592
631
  }
593
632
  )
@@ -654,10 +693,31 @@ server.registerTool(
654
693
  const summaryLines = data.split("\n").filter((l) => l.includes(":") && !l.startsWith(" ") && !l.startsWith("version") && !l.startsWith("entries") && !/^\[\d+\|]/.test(l))
655
694
  const byOrigin: Record<string, number> = {}
656
695
  const byStatus: Record<string, number> = {}
657
- for (const e of entries) {
658
- byOrigin[e.origin || "agent"] = (byOrigin[e.origin || "agent"] || 0) + 1
659
- byStatus[e.status || "active"] = (byStatus[e.status || "active"] || 0) + 1
660
- }
696
+ const accessed = new Map<string, number>()
697
+ const fullParts = lines
698
+ .filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
699
+ .map((l) => parseToonLine(l))
700
+ for (const p of fullParts) {
701
+ byOrigin[p.length > 15 ? p[15] || "agent" : "agent"] = (byOrigin[p.length > 15 ? p[15] || "agent" : "agent"] || 0) + 1
702
+ const st = p.length > 16 ? p[16] || "active" : "active"
703
+ byStatus[st] = (byStatus[st] || 0) + 1
704
+ accessed.set(p[0], p.length > 8 ? parseInt(p[8]) || 0 : 0)
705
+ }
706
+
707
+ // Extended stats: hit rate, duplicate %, dead %
708
+ const hitRate = entries.length > 0
709
+ ? ((fullParts.filter((p) => (parseInt(p[8]) || 0) > 0).length / entries.length) * 100).toFixed(0)
710
+ : "0"
711
+ const contentCounts = new Map<string, number>()
712
+ for (const p of fullParts) {
713
+ const norm = (p[3] || "").toLowerCase().replace(/\s+/g, " ").trim()
714
+ contentCounts.set(norm, (contentCounts.get(norm) || 0) + 1)
715
+ }
716
+ let dupCount = 0
717
+ for (const c of contentCounts.values()) if (c > 1) dupCount += c - 1
718
+ const dupPct = entries.length > 0 ? ((dupCount / entries.length) * 100).toFixed(0) : "0"
719
+ const deadCount = byStatus["obsolete"] || 0
720
+ const deadPct = entries.length > 0 ? ((deadCount / entries.length) * 100).toFixed(0) : "0"
661
721
 
662
722
  const stats = [
663
723
  `Total entries: ${entries.length}`,
@@ -675,6 +735,10 @@ server.registerTool(
675
735
  `TTL: ${withTtl} with expiration, ${expired} expired`,
676
736
  `Average quality: ${avgQuality} (${withQuality} with score)`,
677
737
  "",
738
+ `Hit rate: ${hitRate}% recalled at least once (${fullParts.filter((p) => (parseInt(p[8]) || 0) > 0).length}/${entries.length})`,
739
+ `Duplicate: ${dupPct}% (${dupCount} exact-content dups)`,
740
+ `Dead: ${deadPct}% (${deadCount} obsolete)`,
741
+ "",
678
742
  `Last 5 entries:`,
679
743
  ...lines.slice(-5).map((l) => {
680
744
  const parts = parseToonLine(l)
@@ -843,14 +907,16 @@ server.registerTool(
843
907
  category: z.string().optional().default("").describe("Filter by category (empty = all)"),
844
908
  bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
845
909
  rrf: z.boolean().optional().default(false).describe("Use Reciprocal Rank Fusion (BM25x3 + centrality ranks, adaptive k=sqrtN) instead of weighted linear scoring. Weight-free: reaches parity with the tuned linear scorer on scripts/bench-rrf.mjs."),
910
+ budget_tokens: z.number().optional().default(0).describe("Deterministic token budget: include entries until the estimated output reaches ~N tokens (overrides limit). 0 = no budget."),
911
+ explain: z.boolean().optional().default(false).describe("Append a 'why this entry' line to each result (relevance %, times used, last used, importance). No LLM — pure heuristics."),
846
912
  },
847
913
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
848
914
  },
849
- async ({ intent, limit, category, bias, rrf }) => {
915
+ async ({ intent, limit, category, bias, rrf, budget_tokens, explain }) => {
850
916
  const data = readMemory()
851
917
  const mtimes = fileMtimes()
852
918
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
853
- const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles, rrf })
919
+ const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles, rrf, budgetTokens: budget_tokens || undefined, explain })
854
920
  return { content: [{ type: "text" as const, text: result }] }
855
921
  }
856
922
  )
@@ -1065,9 +1131,9 @@ server.registerTool(
1065
1131
  "memory_consolidate",
1066
1132
  {
1067
1133
  title: "Consolidate Memory",
1068
- description: "Cleanup operations, all deterministic (no LLM): identical removes duplicate entries (keeps the first), similar merges entries with >50% word overlap (keeps longer content, combines tags), low-quality removes entries below minQuality or without tags.",
1134
+ description: "Cleanup operations, all deterministic (no LLM): identical removes duplicate entries (keeps the first), similar merges entries with >50% word overlap (keeps longer content, combines tags), low-quality removes entries below minQuality or without tags, versions marks entries describing the same subject with older versions obsolete in favor of the newest.",
1069
1135
  inputSchema: {
1070
- mode: z.enum(["identical", "similar", "low-quality"]).optional().default("identical").describe("identical: dedupe entries with identical content (default). similar: merge entries with >50% word overlap. low-quality: remove entries below minQuality or without tags."),
1136
+ mode: z.enum(["identical", "similar", "low-quality", "versions"]).optional().default("identical").describe("identical: dedupe entries with identical content (default). similar: merge entries with >50% word overlap. low-quality: remove entries below minQuality or without tags. versions: detect version supersession ('Use React 18' vs 'React 19') and obsolete the older ones."),
1071
1137
  minQuality: z.number().optional().default(0.3).describe("Entries below this quality score are candidates (only used with mode: low-quality)."),
1072
1138
  dryRun: z.boolean().optional().default(false).describe("If true, show what would change without writing."),
1073
1139
  },
@@ -1079,6 +1145,8 @@ server.registerTool(
1079
1145
  return runMergeSimilar(dryRun)
1080
1146
  case "low-quality":
1081
1147
  return runCompressAll(minQuality, dryRun)
1148
+ case "versions":
1149
+ return runConsolidateVersions(dryRun)
1082
1150
  default:
1083
1151
  return runConsolidate()
1084
1152
  }