toon-memory 4.1.2 → 4.3.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, IMPORTANCE_BOOST, importanceBoost, importanceRank, tokenize, estimateTokens, languageFamily, escField, unescField, parseToonLine, toToonLine, isPrivate;
21998
21998
  var init_utils = __esm({
21999
21999
  "src/lib/utils.ts"() {
22000
22000
  "use strict";
@@ -22003,7 +22003,49 @@ var init_utils = __esm({
22003
22003
  if (!ttl) return false;
22004
22004
  return ttl <= today;
22005
22005
  };
22006
+ IMPORTANCE_BOOST = {
22007
+ critical: 0.3,
22008
+ high: 0.15,
22009
+ medium: 0,
22010
+ low: -0.1
22011
+ };
22012
+ importanceBoost = (level) => IMPORTANCE_BOOST[level] ?? 0;
22013
+ importanceRank = (level) => {
22014
+ if (level === "critical") return 4;
22015
+ if (level === "high") return 3;
22016
+ if (level === "low") return 1;
22017
+ return 2;
22018
+ };
22006
22019
  tokenize = (s2) => s2.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[-_]/g, " ").toLowerCase().split(/\s+/).filter(Boolean);
22020
+ estimateTokens = (s2) => {
22021
+ if (!s2) return 0;
22022
+ const chars = Math.ceil(s2.length / 4);
22023
+ const words = (s2.match(/\S+/g) || []).length;
22024
+ return Math.max(1, chars + words);
22025
+ };
22026
+ languageFamily = (s2) => {
22027
+ let cjk = 0, cyr = 0, arab = 0, greek = 0, hebrew = 0, deva = 0, latin = 0, total = 0;
22028
+ for (const ch2 of s2) {
22029
+ const c2 = ch2.codePointAt(0);
22030
+ if (!/[\p{L}]/u.test(ch2)) continue;
22031
+ total++;
22032
+ if (c2 >= 19968 && c2 <= 40959 || c2 >= 12352 && c2 <= 12543 || c2 >= 44032 && c2 <= 55215) cjk++;
22033
+ else if (c2 >= 1024 && c2 <= 1279) cyr++;
22034
+ else if (c2 >= 1536 && c2 <= 1791) arab++;
22035
+ else if (c2 >= 880 && c2 <= 1023) greek++;
22036
+ else if (c2 >= 1424 && c2 <= 1535) hebrew++;
22037
+ else if (c2 >= 2304 && c2 <= 2431) deva++;
22038
+ else latin++;
22039
+ }
22040
+ if (total === 0) return "none";
22041
+ if (cjk / total > 0.3) return "cjk";
22042
+ if (cyr / total > 0.3) return "cyrillic";
22043
+ if (arab / total > 0.3) return "arabic";
22044
+ if (greek / total > 0.3) return "greek";
22045
+ if (hebrew / total > 0.3) return "hebrew";
22046
+ if (deva / total > 0.3) return "devanagari";
22047
+ return "latin";
22048
+ };
22007
22049
  escField = (s2) => {
22008
22050
  let out = "";
22009
22051
  for (let i = 0; i < s2.length; i++) {
@@ -22255,7 +22297,8 @@ function parseEntries(data) {
22255
22297
  path_scope: parts.length > 14 ? parts[14] || "" : "",
22256
22298
  origin: parts.length > 15 && parts[15] ? parts[15] : "agent",
22257
22299
  status: parts.length > 16 && parts[16] ? parts[16] : "active",
22258
- supersededOn: parts.length > 17 ? parts[17] || "" : ""
22300
+ supersededOn: parts.length > 17 ? parts[17] || "" : "",
22301
+ importance: parts.length > 18 ? parts[18] || "" : ""
22259
22302
  });
22260
22303
  }
22261
22304
  return out;
@@ -22431,6 +22474,24 @@ function centrality(adjacency) {
22431
22474
  for (const [k3, d2] of deg) out.set(k3, d2 / maxDeg);
22432
22475
  return out;
22433
22476
  }
22477
+ function buildReason(e, bm25Score, bm25Max, impScore, today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0]) {
22478
+ const parts = [];
22479
+ if (bm25Max > 0) {
22480
+ parts.push(`${Math.round(bm25Score / bm25Max * 100)}% relevance`);
22481
+ }
22482
+ if (e.accessed > 0) {
22483
+ parts.push(`used ${e.accessed}\xD7`);
22484
+ }
22485
+ if (e.lastAccessed) {
22486
+ const days = Math.floor((Date.parse(`${today}T00:00:00`) - Date.parse(e.lastAccessed)) / 864e5);
22487
+ parts.push(days <= 0 ? "used today" : days === 1 ? "used yesterday" : `used ${days}d ago`);
22488
+ } else if (e.accessed === 0) {
22489
+ parts.push("never used");
22490
+ }
22491
+ parts.push(impScore >= 0.7 ? "importance HIGH" : impScore >= 0.4 ? "importance MED" : "importance LOW");
22492
+ if (e.importance) parts.push(`explicit ${e.importance}`);
22493
+ return parts.join(" \xB7 ");
22494
+ }
22434
22495
  function graphRecallDetailed(data, query, opts = {}) {
22435
22496
  const entries = parseEntries(data);
22436
22497
  const { adjacency, byKey } = buildGraph(entries);
@@ -22478,8 +22539,11 @@ function graphRecallDetailed(data, query, opts = {}) {
22478
22539
  scored.push(
22479
22540
  ...visibleEntries.sort((a, b2) => {
22480
22541
  if (a.priority !== b2.priority) return b2.priority - a.priority;
22542
+ const ia2 = importanceRank(a.importance);
22543
+ const ib2 = importanceRank(b2.importance);
22544
+ if (ia2 !== ib2) return ib2 - ia2;
22481
22545
  return importance(b2, opts.today) - importance(a, opts.today);
22482
- }).slice(0, opts.limit ?? 6).map((e) => ({ e, s: importance(e, opts.today) }))
22546
+ }).slice(0, opts.limit ?? 6).map((e) => ({ e, s: importance(e, opts.today) + importanceBoost(e.importance) }))
22483
22547
  );
22484
22548
  } else {
22485
22549
  const best = /* @__PURE__ */ new Map();
@@ -22512,6 +22576,8 @@ function graphRecallDetailed(data, query, opts = {}) {
22512
22576
  s2 *= 1.15;
22513
22577
  }
22514
22578
  }
22579
+ if (e.category === "warning") s2 += 0.2;
22580
+ s2 += importanceBoost(e.importance);
22515
22581
  s2 *= decay;
22516
22582
  return { e, s: s2, priority: e.priority };
22517
22583
  }).sort((a, b2) => {
@@ -22537,7 +22603,16 @@ function graphRecallDetailed(data, query, opts = {}) {
22537
22603
  }
22538
22604
  const scores = /* @__PURE__ */ new Map();
22539
22605
  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 };
22606
+ let bm25Max = 0;
22607
+ for (const v3 of bm25.values()) if (v3 > bm25Max) bm25Max = v3;
22608
+ const reasons = /* @__PURE__ */ new Map();
22609
+ for (const e of selected) {
22610
+ reasons.set(
22611
+ e.key,
22612
+ buildReason(e, bm25.get(e.key) || 0, bm25Max, importance(e, opts.today), opts.today)
22613
+ );
22614
+ }
22615
+ return { entries: selected, seeds: seedKeys, adjacency: subAdj, scores, reasons };
22541
22616
  }
22542
22617
  function globMatch(pattern, target) {
22543
22618
  if (!pattern) return true;
@@ -22555,17 +22630,20 @@ function renderCompact(entries, opts = {}) {
22555
22630
  entries.forEach((e, i) => index.set(e.key, i + 1));
22556
22631
  const snippetLen = opts.snippetLen ?? 90;
22557
22632
  const budget = opts.budget ?? "normal";
22558
- return entries.map((e) => {
22633
+ const rendered = [];
22634
+ let tokens = 0;
22635
+ for (const e of entries) {
22559
22636
  const n = index.get(e.key);
22560
22637
  const isSeed = opts.seeds ? opts.seeds.has(e.key) : true;
22638
+ const reason = opts.reasons?.get(e.key);
22639
+ let block;
22561
22640
  if (budget === "tiny") {
22562
22641
  const firstLine = e.content.split("\n")[0] || "";
22563
22642
  const snippet = firstLine.length > 80 ? firstLine.slice(0, 80).trimEnd() + "\u2026" : firstLine;
22564
22643
  const pin = e.priority > 0 ? e.priority > 1 ? ` \u{1F4CC}${e.priority}` : " \u{1F4CC}" : "";
22565
- return `[${n}] ${e.category}/${e.key}${pin}
22644
+ block = `[${n}] ${e.category}/${e.key}${pin}
22566
22645
  ${snippet}`;
22567
- }
22568
- if (budget === "deep") {
22646
+ } else if (budget === "deep") {
22569
22647
  const ttlInfo = e.ttl ? ` \xB7 ttl: ${e.ttl}` : "";
22570
22648
  const accessInfo = e.accessed > 0 ? ` \xB7 accessed: ${e.accessed}x` : "";
22571
22649
  const lastAccess = e.lastAccessed ? ` \xB7 lastAccess: ${e.lastAccessed}` : "";
@@ -22576,24 +22654,37 @@ function renderCompact(entries, opts = {}) {
22576
22654
  const scopeInfo = e.path_scope ? ` \xB7 scope: ${e.path_scope}` : "";
22577
22655
  const statusInfo = e.status !== "active" ? ` \xB7 status: ${e.status}` : "";
22578
22656
  const supersededInfo = e.supersededOn ? ` \xB7 superseded: ${e.supersededOn}` : "";
22579
- return `[${n}] ${e.category}/${e.key}${pin} (${e.id})
22657
+ const impInfo = e.importance ? ` \xB7 importance: ${e.importance}` : "";
22658
+ block = `[${n}] ${e.category}/${e.key}${pin} (${e.id})
22580
22659
  ${e.content}
22581
- File: ${e.file} | Tags: ${e.tags.join(";")} | Date: ${e.date}${ttlInfo}${accessInfo}${lastAccess}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}${links}`;
22582
- }
22583
- let body = e.content;
22584
- if (!isSeed && e.content.length > snippetLen) {
22585
- body = e.content.slice(0, snippetLen).trimEnd() + "\u2026";
22660
+ File: ${e.file} | Tags: ${e.tags.join(";")} | Date: ${e.date}${ttlInfo}${accessInfo}${lastAccess}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}${impInfo}${links}`;
22661
+ } else {
22662
+ let body = e.content;
22663
+ if (!isSeed && e.content.length > snippetLen) {
22664
+ body = e.content.slice(0, snippetLen).trimEnd() + "\u2026";
22665
+ }
22666
+ const tag = e.priority > 0 ? e.priority > 1 ? ` \u{1F4CC}${e.priority}` : " \u{1F4CC}" : "";
22667
+ const tags = e.tags.length ? ` \xB7 tags: ${e.tags.join(";")}` : "";
22668
+ let edges = "";
22669
+ if (opts.adjacency) {
22670
+ const nb2 = (opts.adjacency.get(e.key) || []).map((k3) => index.get(k3)).filter((x) => typeof x === "number");
22671
+ if (nb2.length) edges = ` \xB7 edges: ->${nb2.join(", ->")}`;
22672
+ }
22673
+ block = `[${n}] ${e.category}/${e.key}${tag}
22674
+ ${body}${tags}${edges}`;
22586
22675
  }
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(", ->")}`;
22676
+ if (reason) block += `
22677
+ \u21B3 ${reason}`;
22678
+ rendered.push(block);
22679
+ if (opts.budgetTokens && opts.budgetTokens > 0) {
22680
+ tokens += estimateTokens(block);
22681
+ if (rendered.length > 1 && tokens > opts.budgetTokens) {
22682
+ rendered.pop();
22683
+ break;
22684
+ }
22593
22685
  }
22594
- return `[${n}] ${e.category}/${e.key}${tag}
22595
- ${body}${tags}${edges}`;
22596
- }).join("\n\n");
22686
+ }
22687
+ return rendered.join("\n\n");
22597
22688
  }
22598
22689
  var DEFAULT_EDGE_TYPE, entryLines, W_CENT, W_IMP, SEED_BONUS, DECAY;
22599
22690
  var init_graph = __esm({
@@ -22710,7 +22801,10 @@ function mergeEntries(existingLine, newLine) {
22710
22801
  const newStatus = np2.length > 16 ? np2[16] || "" : "";
22711
22802
  const status = newStatus === "active" || existingStatus === "active" ? "active" : newStatus || existingStatus || "active";
22712
22803
  const existingSupersededOn = ep2.length > 17 ? ep2[17] || "" : "";
22713
- return toToonLine([id2, category, key, content, file2, mergedTags, date5, ttl, String(accessed), mergedLinks, quality.toFixed(2), String(confidence), lastAccessed, String(priority), path_scope, origin, status, existingSupersededOn]);
22804
+ const existingImportance = ep2.length > 18 ? ep2[18] || "" : "";
22805
+ const newImportance = np2.length > 18 ? np2[18] || "" : "";
22806
+ const importance2 = importanceRank(newImportance) >= importanceRank(existingImportance) ? newImportance : existingImportance;
22807
+ return toToonLine([id2, category, key, content, file2, mergedTags, date5, ttl, String(accessed), mergedLinks, quality.toFixed(2), String(confidence), lastAccessed, String(priority), path_scope, origin, status, existingSupersededOn, importance2]);
22714
22808
  }
22715
22809
  function generateSmartRecall(data, intent, opts = {}) {
22716
22810
  const entries = parseEntries(data);
@@ -22756,13 +22850,23 @@ function generateSmartRecall(data, intent, opts = {}) {
22756
22850
  sessionBias = 0.15;
22757
22851
  }
22758
22852
  }
22853
+ let langBoost = 0;
22854
+ const qFamily = languageFamily(intent);
22855
+ if (qFamily !== "none") {
22856
+ const eFamily = languageFamily(`${e.content} ${e.key} ${e.tags.join(" ")}`);
22857
+ if (qFamily === eFamily) langBoost = 0.1;
22858
+ }
22859
+ let folderBoost = 0;
22860
+ if (e.path_scope && globMatch(e.path_scope, ".")) folderBoost = 0.05;
22861
+ const warningBoost = e.category === "warning" ? 0.2 : 0;
22862
+ const impBoost = importanceBoost(e.importance);
22759
22863
  let combined;
22760
22864
  if (opts.rrf) {
22761
- combined = (fused?.get(e.key) ?? 0) - drift + sessionBias;
22865
+ combined = (fused?.get(e.key) ?? 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost;
22762
22866
  } else {
22763
- combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias;
22867
+ combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost;
22764
22868
  }
22765
- return { entry: e, score: combined, matchesQuery, priority: e.priority };
22869
+ return { entry: e, score: combined, matchesQuery, priority: e.priority, bm25Score };
22766
22870
  }).filter((x) => x.score > 0 || x.matchesQuery).sort((a, b2) => {
22767
22871
  if (a.priority !== b2.priority) return b2.priority - a.priority;
22768
22872
  return b2.score - a.score;
@@ -22771,18 +22875,32 @@ function generateSmartRecall(data, intent, opts = {}) {
22771
22875
  const inResult = new Set(scored.map((x) => x.entry.key));
22772
22876
  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
22877
  for (const e of toInject) {
22774
- scored.unshift({ entry: e, score: 999, matchesQuery: false, priority: e.priority });
22878
+ scored.unshift({ entry: e, score: 999, matchesQuery: false, priority: e.priority, bm25Score: 0 });
22775
22879
  }
22776
22880
  if (scored.length === 0) {
22777
22881
  const top = eligible.sort((a, b2) => {
22778
22882
  if (a.priority !== b2.priority) return b2.priority - a.priority;
22883
+ const ia2 = importanceRank(a.importance);
22884
+ const ib2 = importanceRank(b2.importance);
22885
+ if (ia2 !== ib2) return ib2 - ia2;
22779
22886
  return importance(b2, opts.today) - importance(a, opts.today);
22780
22887
  }).slice(0, limit);
22781
22888
  if (top.length === 0) return "No entries in memory.";
22782
- return renderCompact(top);
22889
+ return renderCompact(top, { budgetTokens: opts.budgetTokens });
22783
22890
  }
22784
22891
  if (opts.bumpAccess) opts.bumpAccess(scored.map((x) => x.entry.id));
22785
- return renderCompact(scored.map((x) => x.entry));
22892
+ let bm25Max = 0;
22893
+ for (const s2 of scored) if (s2.bm25Score > bm25Max) bm25Max = s2.bm25Score;
22894
+ const reasons = /* @__PURE__ */ new Map();
22895
+ if (opts.explain) {
22896
+ for (const s2 of scored) {
22897
+ reasons.set(
22898
+ s2.entry.key,
22899
+ buildReason(s2.entry, s2.bm25Score, bm25Max, importance(s2.entry, opts.today), opts.today)
22900
+ );
22901
+ }
22902
+ }
22903
+ return renderCompact(scored.map((x) => x.entry), { reasons: opts.explain ? reasons : void 0, budgetTokens: opts.budgetTokens });
22786
22904
  }
22787
22905
  function generateSystemPrimer(data) {
22788
22906
  const entries = parseEntries(data);
@@ -33242,6 +33360,73 @@ function consolidateEntries() {
33242
33360
  writeMemory(lines.join("\n"));
33243
33361
  return { removed: totalRemoved, kept: order.length, duplicates };
33244
33362
  }
33363
+ function extractVersion(text) {
33364
+ const m3 = text.match(/([A-Za-z][A-Za-z0-9._-]*?)\s*(?:v)?(\d+)\.(\d+)(?:\.(\d+))?/);
33365
+ if (!m3) return null;
33366
+ const base = m3[1].replace(/[-_.]+$/g, "").toLowerCase();
33367
+ return { base, version: [parseInt(m3[2]), parseInt(m3[3]), m3[4] ? parseInt(m3[4]) : 0] };
33368
+ }
33369
+ function compareVersions(a, b2) {
33370
+ for (let i = 0; i < 3; i++) {
33371
+ if (a[i] !== b2[i]) return a[i] - b2[i];
33372
+ }
33373
+ return 0;
33374
+ }
33375
+ function consolidateVersions(dryRun) {
33376
+ const data = readMemory();
33377
+ const lines = data.split("\n");
33378
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
33379
+ if (headerIdx === -1) return { removed: 0, proposals: [], groups: [] };
33380
+ const candidates = [];
33381
+ for (let i = headerIdx + 1; i < lines.length; i++) {
33382
+ const line = lines[i];
33383
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
33384
+ if (line.startsWith(" summaries:")) break;
33385
+ const parts = parseToonLine(line);
33386
+ if (parts.length < 7) continue;
33387
+ const [id2, category, key, content] = parts;
33388
+ const hit = extractVersion(`${key} ${content}`.toLowerCase());
33389
+ if (hit && key.toLowerCase().includes(hit.base)) {
33390
+ candidates.push({ lineIdx: i, id: id2, key, content, category, base: hit.base, version: hit.version });
33391
+ }
33392
+ }
33393
+ if (candidates.length < 2) return { removed: 0, proposals: [], groups: [] };
33394
+ const byBase = /* @__PURE__ */ new Map();
33395
+ for (const c2 of candidates) {
33396
+ const list = byBase.get(c2.base) || [];
33397
+ list.push(c2);
33398
+ byBase.set(c2.base, list);
33399
+ }
33400
+ const groups = [];
33401
+ for (const [base, list] of byBase) {
33402
+ if (list.length < 2) continue;
33403
+ const sorted = [...list].sort((a, b2) => compareVersions(b2.version, a.version));
33404
+ const winner = sorted[0];
33405
+ const losers = sorted.slice(1);
33406
+ if (losers.length === 0) continue;
33407
+ groups.push({ base, winner: winner.key, losers: losers.map((l) => l.key) });
33408
+ }
33409
+ if (groups.length === 0) return { removed: 0, proposals: [], groups };
33410
+ if (dryRun) return { removed: 0, proposals: groups.map((g) => `Replace ${g.losers.join(", ")} by ${g.winner}`), groups };
33411
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
33412
+ let changed = 0;
33413
+ for (const g of groups) {
33414
+ for (const loser of g.losers) {
33415
+ const hit = candidates.find((c2) => c2.key === loser);
33416
+ if (!hit) continue;
33417
+ const parts = parseToonLine(lines[hit.lineIdx]);
33418
+ while (parts.length < 18) parts.push("");
33419
+ parts[9] = parts[9] ? `${parts[9]} ${g.winner}` : g.winner;
33420
+ parts[16] = "obsolete";
33421
+ parts[17] = today;
33422
+ lines[hit.lineIdx] = toToonLine(parts);
33423
+ changed++;
33424
+ }
33425
+ }
33426
+ if (changed === 0) return { removed: 0, proposals: [], groups };
33427
+ writeMemory(lines.join("\n"));
33428
+ return { removed: changed, proposals: groups.map((g) => `Replace ${g.losers.join(", ")} by ${g.winner}`), groups };
33429
+ }
33245
33430
 
33246
33431
  // src/mcp/tools.ts
33247
33432
  init_graph();
@@ -34385,6 +34570,30 @@ Duplicates: ${result.duplicates.join(", ")}`
34385
34570
  }]
34386
34571
  };
34387
34572
  }
34573
+ function runConsolidateVersions(dryRun) {
34574
+ const result = consolidateVersions(dryRun);
34575
+ if (result.groups.length === 0) {
34576
+ return { content: [{ type: "text", text: "\u2705 No version supersession detected." }] };
34577
+ }
34578
+ if (dryRun) {
34579
+ return {
34580
+ content: [{
34581
+ type: "text",
34582
+ text: `\u{1F50D} Version supersession candidates (${result.groups.length}):
34583
+ ${result.proposals.map((p2) => ` \u2022 ${p2}`).join("\n")}
34584
+
34585
+ Run again with dryRun: false to apply.`
34586
+ }]
34587
+ };
34588
+ }
34589
+ return {
34590
+ content: [{
34591
+ type: "text",
34592
+ text: `\u{1F5C2}\uFE0F Marked ${result.removed} old-version entries obsolete:
34593
+ ${result.proposals.map((p2) => ` \u2022 ${p2}`).join("\n")}`
34594
+ }]
34595
+ };
34596
+ }
34388
34597
  function runMergeSimilar(dryRun) {
34389
34598
  const data = readMemory();
34390
34599
  const lines = data.split("\n");
@@ -34558,7 +34767,7 @@ ${mergeActions.join("\n")}`
34558
34767
  title: "Save to Memory",
34559
34768
  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.",
34560
34769
  inputSchema: {
34561
- category: external_exports.enum(["decision", "pattern", "bug", "knowledge"]).describe("Category of the fact"),
34770
+ 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."),
34562
34771
  key: external_exports.string().describe("Short title in kebab-case (e.g. risk-engine-priority)"),
34563
34772
  content: external_exports.string().describe("Detailed content of the fact"),
34564
34773
  file: external_exports.string().optional().default("").describe("Related file or line (e.g. spec.md:145)"),
@@ -34566,11 +34775,12 @@ ${mergeActions.join("\n")}`
34566
34775
  ttl: external_exports.string().optional().default("").describe("Time to live (e.g. 7d, 2026-07-17). Empty = no expiration"),
34567
34776
  links: external_exports.string().optional().default("").describe("Related entry keys, separated by space or ';' (e.g. risk-spec engine-arch). Builds graph edges."),
34568
34777
  path_scope: external_exports.string().optional().default("").describe("Glob pattern to scope this entry (e.g. src/**.ts). Empty = global."),
34569
- origin: external_exports.enum(["human", "agent", "inferred"]).optional().default("agent").describe("Who created this entry.")
34778
+ origin: external_exports.enum(["human", "agent", "inferred"]).optional().default("agent").describe("Who created this entry."),
34779
+ importance: external_exports.enum(["critical", "high", "medium", "low"]).optional().describe("Explicit importance level \u2014 critical/high entries surface first in recall, low last. Omit for auto (recency + frequency).")
34570
34780
  },
34571
34781
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
34572
34782
  },
34573
- async ({ category, key, content, file: file2, tags, ttl, links, path_scope, origin }) => {
34783
+ async ({ category, key, content, file: file2, tags, ttl, links, path_scope, origin, importance: importance2 = "" }) => {
34574
34784
  const data = readMemory();
34575
34785
  const newId = generateId();
34576
34786
  const date5 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
@@ -34600,7 +34810,7 @@ ${mergeActions.join("\n")}`
34600
34810
  const resolvedTags = tags ? tags : verbatim ? "" : inferTags(content, key, config2.vocab);
34601
34811
  const existingParts = existingIdx !== -1 ? parseToonLine(lines[existingIdx]) : [];
34602
34812
  const resolvedLinks = links ? links.split(/[\s;]+/).filter(Boolean).join(" ") : existingParts[9] || "";
34603
- let newEntry = toToonLine([entryId, category, key, content, file2 || "", resolvedTags, date5, resolvedTtl, "0", resolvedLinks, "", "", "", path_scope || "", origin]);
34813
+ let newEntry = toToonLine([entryId, category, key, content, file2 || "", resolvedTags, date5, resolvedTtl, "0", resolvedLinks, "", "", "", "0", path_scope || "", origin, "", "", importance2]);
34604
34814
  let action = "Saved";
34605
34815
  let mergeInfo = "";
34606
34816
  const tagsInferred = !tags && resolvedTags ? true : false;
@@ -34614,7 +34824,7 @@ ${mergeActions.join("\n")}`
34614
34824
  const lastAccessed = "";
34615
34825
  const quality = verbatim ? 0.5 : qualityScore(resolvedTags, resolvedLinks, content, date5, accessed, lastAccessed, origin);
34616
34826
  const confidence = 1;
34617
- newEntry = toToonLine([entryId, category, key, content, file2 || "", resolvedTags, date5, resolvedTtl, String(accessed), resolvedLinks, quality.toFixed(2), String(confidence), lastAccessed, "0", path_scope || "", origin, "active"]);
34827
+ newEntry = toToonLine([entryId, category, key, content, file2 || "", resolvedTags, date5, resolvedTtl, String(accessed), resolvedLinks, quality.toFixed(2), String(confidence), lastAccessed, "0", path_scope || "", origin, "active", "", importance2]);
34618
34828
  const match = lines[headerIdx].match(/\[(\d+)\|/);
34619
34829
  const count = match ? parseInt(match[1]) : 0;
34620
34830
  lines.splice(headerIdx + 1, 0, newEntry);
@@ -34664,6 +34874,8 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34664
34874
  hops: external_exports.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
34665
34875
  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."),
34666
34876
  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'."),
34877
+ 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."),
34878
+ 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."),
34667
34879
  bias: external_exports.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
34668
34880
  path_scope: external_exports.string().optional().default("").describe("Glob pattern to filter entries by path scope (e.g. 'src/**.ts')."),
34669
34881
  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."),
@@ -34671,7 +34883,7 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34671
34883
  },
34672
34884
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
34673
34885
  },
34674
- async ({ query, category, from_date, to_date, mode, hops, compact, bias, budget: budgetParam, path_scope, rrf, as_of }) => {
34886
+ async ({ query, category, from_date, to_date, mode, hops, compact, budget: budgetParam, budget_tokens, explain, bias, path_scope, rrf, as_of }) => {
34675
34887
  const data = readMemory();
34676
34888
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
34677
34889
  const resolvedBudget = budgetParam || (compact ? "normal" : "deep");
@@ -34680,12 +34892,15 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34680
34892
  return { content: [{ type: "text", text: `No results found for "${query}"` }] };
34681
34893
  }
34682
34894
  bumpAccessed(detail.entries.map((e) => e.id));
34895
+ const reasons = explain ? detail.reasons : void 0;
34683
34896
  if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
34684
34897
  const formatted2 = renderCompact(detail.entries, {
34685
34898
  adjacency: detail.adjacency,
34686
34899
  seeds: detail.seeds,
34687
34900
  snippetLen: 90,
34688
- budget: resolvedBudget
34901
+ budget: resolvedBudget,
34902
+ reasons,
34903
+ budgetTokens: budget_tokens || void 0
34689
34904
  });
34690
34905
  return { content: [{ type: "text", text: formatted2 }] };
34691
34906
  }
@@ -34697,10 +34912,23 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34697
34912
  const scopeInfo = r2.path_scope ? ` | scope: ${r2.path_scope}` : "";
34698
34913
  const statusInfo = r2.status !== "active" ? ` | status: ${r2.status}` : "";
34699
34914
  const supersededInfo = r2.supersededOn ? ` | superseded: ${r2.supersededOn}` : "";
34915
+ const why = reasons?.get(r2.key) ? `
34916
+ \u21B3 ${reasons.get(r2.key)}` : "";
34700
34917
  return `[${r2.category}] ${r2.key}${pin} (${r2.id})
34701
34918
  ${r2.content}
34702
- File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}`;
34919
+ File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}${why}`;
34703
34920
  }).join("\n\n");
34921
+ if (budget_tokens && budget_tokens > 0) {
34922
+ const blocks = formatted.split("\n\n");
34923
+ let acc = 0;
34924
+ let out = [];
34925
+ for (let i = 0; i < blocks.length; i++) {
34926
+ acc += estimateTokens(blocks[i]);
34927
+ if (i > 0 && acc > budget_tokens) break;
34928
+ out.push(blocks[i]);
34929
+ }
34930
+ return { content: [{ type: "text", text: out.join("\n\n") }] };
34931
+ }
34704
34932
  return { content: [{ type: "text", text: formatted }] };
34705
34933
  }
34706
34934
  );
@@ -34756,10 +34984,25 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34756
34984
  const summaryLines = data.split("\n").filter((l) => l.includes(":") && !l.startsWith(" ") && !l.startsWith("version") && !l.startsWith("entries") && !/^\[\d+\|]/.test(l));
34757
34985
  const byOrigin = {};
34758
34986
  const byStatus = {};
34759
- for (const e of entries) {
34760
- byOrigin[e.origin || "agent"] = (byOrigin[e.origin || "agent"] || 0) + 1;
34761
- byStatus[e.status || "active"] = (byStatus[e.status || "active"] || 0) + 1;
34762
- }
34987
+ const accessed = /* @__PURE__ */ new Map();
34988
+ const fullParts = lines.filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")).map((l) => parseToonLine(l));
34989
+ for (const p2 of fullParts) {
34990
+ byOrigin[p2.length > 15 ? p2[15] || "agent" : "agent"] = (byOrigin[p2.length > 15 ? p2[15] || "agent" : "agent"] || 0) + 1;
34991
+ const st2 = p2.length > 16 ? p2[16] || "active" : "active";
34992
+ byStatus[st2] = (byStatus[st2] || 0) + 1;
34993
+ accessed.set(p2[0], p2.length > 8 ? parseInt(p2[8]) || 0 : 0);
34994
+ }
34995
+ const hitRate = entries.length > 0 ? (fullParts.filter((p2) => (parseInt(p2[8]) || 0) > 0).length / entries.length * 100).toFixed(0) : "0";
34996
+ const contentCounts = /* @__PURE__ */ new Map();
34997
+ for (const p2 of fullParts) {
34998
+ const norm = (p2[3] || "").toLowerCase().replace(/\s+/g, " ").trim();
34999
+ contentCounts.set(norm, (contentCounts.get(norm) || 0) + 1);
35000
+ }
35001
+ let dupCount = 0;
35002
+ for (const c2 of contentCounts.values()) if (c2 > 1) dupCount += c2 - 1;
35003
+ const dupPct = entries.length > 0 ? (dupCount / entries.length * 100).toFixed(0) : "0";
35004
+ const deadCount = byStatus["obsolete"] || 0;
35005
+ const deadPct = entries.length > 0 ? (deadCount / entries.length * 100).toFixed(0) : "0";
34763
35006
  const stats = [
34764
35007
  `Total entries: ${entries.length}`,
34765
35008
  `File summaries: ${summaryLines.length}`,
@@ -34776,6 +35019,10 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34776
35019
  `TTL: ${withTtl} with expiration, ${expired} expired`,
34777
35020
  `Average quality: ${avgQuality} (${withQuality} with score)`,
34778
35021
  "",
35022
+ `Hit rate: ${hitRate}% recalled at least once (${fullParts.filter((p2) => (parseInt(p2[8]) || 0) > 0).length}/${entries.length})`,
35023
+ `Duplicate: ${dupPct}% (${dupCount} exact-content dups)`,
35024
+ `Dead: ${deadPct}% (${deadCount} obsolete)`,
35025
+ "",
34779
35026
  `Last 5 entries:`,
34780
35027
  ...lines.slice(-5).map((l) => {
34781
35028
  const parts = parseToonLine(l);
@@ -34911,15 +35158,17 @@ ${formatted}` }] };
34911
35158
  limit: external_exports.number().optional().default(8).describe("Maximum entries to return"),
34912
35159
  category: external_exports.string().optional().default("").describe("Filter by category (empty = all)"),
34913
35160
  bias: external_exports.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
34914
- 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.")
35161
+ 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."),
35162
+ 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."),
35163
+ 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.")
34915
35164
  },
34916
35165
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
34917
35166
  },
34918
- async ({ intent, limit, category, bias, rrf }) => {
35167
+ async ({ intent, limit, category, bias, rrf, budget_tokens, explain }) => {
34919
35168
  const data = readMemory();
34920
35169
  const mtimes = fileMtimes();
34921
35170
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
34922
- const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles, rrf });
35171
+ const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles, rrf, budgetTokens: budget_tokens || void 0, explain });
34923
35172
  return { content: [{ type: "text", text: result }] };
34924
35173
  }
34925
35174
  );
@@ -35094,9 +35343,9 @@ ${formatted}` }] };
35094
35343
  "memory_consolidate",
35095
35344
  {
35096
35345
  title: "Consolidate Memory",
35097
- 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.",
35346
+ 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.",
35098
35347
  inputSchema: {
35099
- 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."),
35348
+ 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."),
35100
35349
  minQuality: external_exports.number().optional().default(0.3).describe("Entries below this quality score are candidates (only used with mode: low-quality)."),
35101
35350
  dryRun: external_exports.boolean().optional().default(false).describe("If true, show what would change without writing.")
35102
35351
  },
@@ -35108,6 +35357,8 @@ ${formatted}` }] };
35108
35357
  return runMergeSimilar(dryRun);
35109
35358
  case "low-quality":
35110
35359
  return runCompressAll(minQuality, dryRun);
35360
+ case "versions":
35361
+ return runConsolidateVersions(dryRun);
35111
35362
  default:
35112
35363
  return runConsolidate();
35113
35364
  }
@@ -47959,7 +48210,7 @@ function registerResources(server2) {
47959
48210
 
47960
48211
  // src/mcp/server.ts
47961
48212
  var server = new McpServer(
47962
- { name: "toon-memory", version: "4.1.2" },
48213
+ { name: "toon-memory", version: "4.3.0" },
47963
48214
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true }, experimental: { "io.modelcontextprotocol/ui": {} } } }
47964
48215
  );
47965
48216
  var s = server.server;
@@ -47971,7 +48222,7 @@ s.setRequestHandler(InitializeRequestSchema, async (request) => {
47971
48222
  return {
47972
48223
  protocolVersion,
47973
48224
  capabilities: s.getCapabilities(),
47974
- serverInfo: { name: "toon-memory", version: "4.1.2" },
48225
+ serverInfo: { name: "toon-memory", version: "4.3.0" },
47975
48226
  ...s._instructions && { instructions: s._instructions }
47976
48227
  };
47977
48228
  });
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.2",
4
+ "version": "4.3.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": {