toon-memory 3.5.0 → 3.6.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
@@ -22176,7 +22176,10 @@ function parseEntries(data) {
22176
22176
  accessed: accessedRaw ? parseInt(accessedRaw) || 0 : 0,
22177
22177
  links: (linksRaw || "").split(/[\s;]+/).map((t) => t.trim()).filter(Boolean),
22178
22178
  lastAccessed: parts.length > 12 ? parts[12] || "" : "",
22179
- priority: parts.length > 13 ? parseInt(parts[13]) || 0 : 0
22179
+ priority: parts.length > 13 ? parseInt(parts[13]) || 0 : 0,
22180
+ path_scope: parts.length > 14 ? parts[14] || "" : "",
22181
+ origin: parts.length > 15 && parts[15] ? parts[15] : "agent",
22182
+ status: parts.length > 16 && parts[16] ? parts[16] : "active"
22180
22183
  });
22181
22184
  }
22182
22185
  return out;
@@ -22223,7 +22226,7 @@ function bm25Scores(entries, query) {
22223
22226
  const scores = /* @__PURE__ */ new Map();
22224
22227
  if (N === 0) return scores;
22225
22228
  const docs = entries.map(
22226
- (e) => tokenize(`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`)
22229
+ (e) => tokenize(`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")} ${e.path_scope}`)
22227
22230
  );
22228
22231
  const df2 = /* @__PURE__ */ new Map();
22229
22232
  for (const d2 of docs) {
@@ -22273,11 +22276,13 @@ function graphRecallDetailed(data, query, opts = {}) {
22273
22276
  const cent = centrality(adjacency);
22274
22277
  const seedKeys = /* @__PURE__ */ new Set();
22275
22278
  for (const e of entries) {
22279
+ if (e.status === "obsolete") continue;
22276
22280
  if (category && e.category !== category) continue;
22277
22281
  if (tagsFilter.length > 0 && !tagsFilter.every((t) => e.tags.includes(t))) continue;
22278
22282
  if (from_date && e.date < from_date) continue;
22279
22283
  if (to_date && e.date > to_date) continue;
22280
22284
  if (e.ttl && isExpiredLocal(e.ttl)) continue;
22285
+ if (opts.path_scope && e.path_scope && !globMatch(opts.path_scope, e.path_scope)) continue;
22281
22286
  const text = normalize(
22282
22287
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
22283
22288
  );
@@ -22291,7 +22296,7 @@ function graphRecallDetailed(data, query, opts = {}) {
22291
22296
  const scored = [];
22292
22297
  if (seedKeys.size === 0) {
22293
22298
  scored.push(
22294
- ...[...entries].sort((a, b2) => {
22299
+ ...[...entries].filter((e) => e.status !== "obsolete").sort((a, b2) => {
22295
22300
  if (a.priority !== b2.priority) return b2.priority - a.priority;
22296
22301
  return importance(b2) - importance(a);
22297
22302
  }).slice(0, opts.limit ?? 6).map((e) => ({ e, s: importance(e) }))
@@ -22331,7 +22336,7 @@ function graphRecallDetailed(data, query, opts = {}) {
22331
22336
  );
22332
22337
  }
22333
22338
  selected = scored.map((x) => x.e);
22334
- const pinnedKeys = new Set(entries.filter((e) => e.priority > 0).map((e) => e.key));
22339
+ const pinnedKeys = new Set(entries.filter((e) => e.priority > 0 && e.status !== "obsolete").map((e) => e.key));
22335
22340
  const inResult = new Set(selected.map((e) => e.key));
22336
22341
  const toInject = [...pinnedKeys].filter((k3) => !inResult.has(k3) && byKey.has(k3)).map((k3) => byKey.get(k3)).sort((a, b2) => b2.priority - a.priority);
22337
22342
  for (const e of toInject) {
@@ -22349,13 +22354,46 @@ function graphRecallDetailed(data, query, opts = {}) {
22349
22354
  selected.forEach((e) => scores.set(e.key, scored.find((x) => x.e.key === e.key).s));
22350
22355
  return { entries: selected, seeds: seedKeys, adjacency: subAdj, scores };
22351
22356
  }
22357
+ function globMatch(pattern, target) {
22358
+ if (!pattern) return true;
22359
+ if (pattern.startsWith("/")) pattern = pattern.slice(1);
22360
+ if (target.startsWith("/")) target = target.slice(1);
22361
+ const reStr = "^" + pattern.replace(/\*\*/g, "___DOUBLESTAR___").replace(/\*/g, "[^/]*").replace(/___DOUBLESTAR___/g, ".*").replace(/\?/g, ".").replace(/\./g, "\\.").replace(/\\\.\*/g, ".*") + "$";
22362
+ try {
22363
+ return new RegExp(reStr).test(target);
22364
+ } catch {
22365
+ return false;
22366
+ }
22367
+ }
22352
22368
  function renderCompact(entries, opts = {}) {
22353
22369
  const index = /* @__PURE__ */ new Map();
22354
22370
  entries.forEach((e, i) => index.set(e.key, i + 1));
22355
22371
  const snippetLen = opts.snippetLen ?? 90;
22372
+ const budget = opts.budget ?? "normal";
22356
22373
  return entries.map((e) => {
22357
22374
  const n = index.get(e.key);
22358
22375
  const isSeed = opts.seeds ? opts.seeds.has(e.key) : true;
22376
+ if (budget === "tiny") {
22377
+ const firstLine = e.content.split("\n")[0] || "";
22378
+ const snippet = firstLine.length > 80 ? firstLine.slice(0, 80).trimEnd() + "\u2026" : firstLine;
22379
+ const pin = e.priority > 0 ? e.priority > 1 ? ` \u{1F4CC}${e.priority}` : " \u{1F4CC}" : "";
22380
+ return `[${n}] ${e.category}/${e.key}${pin}
22381
+ ${snippet}`;
22382
+ }
22383
+ if (budget === "deep") {
22384
+ const ttlInfo = e.ttl ? ` \xB7 ttl: ${e.ttl}` : "";
22385
+ const accessInfo = e.accessed > 0 ? ` \xB7 accessed: ${e.accessed}x` : "";
22386
+ const lastAccess = e.lastAccessed ? ` \xB7 lastAccess: ${e.lastAccessed}` : "";
22387
+ const pin = e.priority > 0 ? e.priority > 1 ? ` \u{1F4CC}${e.priority}` : " \u{1F4CC}" : "";
22388
+ const links = e.links.length ? `
22389
+ links: ${e.links.join(", ")}` : "";
22390
+ const originInfo = e.origin !== "agent" ? ` \xB7 origin: ${e.origin}` : "";
22391
+ const scopeInfo = e.path_scope ? ` \xB7 scope: ${e.path_scope}` : "";
22392
+ const statusInfo = e.status !== "active" ? ` \xB7 status: ${e.status}` : "";
22393
+ return `[${n}] ${e.category}/${e.key}${pin} (${e.id})
22394
+ ${e.content}
22395
+ File: ${e.file} | Tags: ${e.tags.join(";")} | Date: ${e.date}${ttlInfo}${accessInfo}${lastAccess}${originInfo}${scopeInfo}${statusInfo}${links}`;
22396
+ }
22359
22397
  let body = e.content;
22360
22398
  if (!isSeed && e.content.length > snippetLen) {
22361
22399
  body = e.content.slice(0, snippetLen).trimEnd() + "\u2026";
@@ -22396,7 +22434,7 @@ __export(quality_exports, {
22396
22434
  mergeEntries: () => mergeEntries,
22397
22435
  qualityScore: () => qualityScore
22398
22436
  });
22399
- function qualityScore(tags, links, content, date5, accessed = 0, lastAccessed = "") {
22437
+ function qualityScore(tags, links, content, date5, accessed = 0, lastAccessed = "", origin = "") {
22400
22438
  let score = 0;
22401
22439
  if (tags) {
22402
22440
  const count = tags.split(";").filter(Boolean).length;
@@ -22428,6 +22466,8 @@ function qualityScore(tags, links, content, date5, accessed = 0, lastAccessed =
22428
22466
  else if (daysSinceAccess < 7) score += 0.07;
22429
22467
  else if (daysSinceAccess < 30) score += 0.03;
22430
22468
  }
22469
+ if (origin === "human") score += 0.1;
22470
+ else if (origin === "inferred") score -= 0.05;
22431
22471
  if (date5) {
22432
22472
  const daysSinceCreation = (Date.now() - (/* @__PURE__ */ new Date(`${date5}T00:00:00`)).getTime()) / 864e5;
22433
22473
  const daysSinceLastAccess = lastAccessed ? (Date.now() - new Date(lastAccessed).getTime()) / 864e5 : daysSinceCreation;
@@ -22472,7 +22512,17 @@ function mergeEntries(existingLine, newLine) {
22472
22512
  const newPriority = np2.length > 13 ? parseInt(np2[13]) || 0 : 0;
22473
22513
  const priority = Math.max(existingPriority, newPriority);
22474
22514
  const quality = qualityScore(mergedTags, mergedLinks, content, date5, accessed, lastAccessed);
22475
- return `${id2}|${category}|${key}|${content}|${file2}|${mergedTags}|${date5}|${ttl}|${accessed}|${mergedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}|${priority}`;
22515
+ const existingScope = ep2.length > 14 ? ep2[14] || "" : "";
22516
+ const newScope = np2.length > 14 ? np2[14] || "" : "";
22517
+ const path_scope = newScope || existingScope;
22518
+ const existingOrigin = ep2.length > 15 ? ep2[15] || "" : "";
22519
+ const newOrigin = np2.length > 15 ? np2[15] || "" : "";
22520
+ const originRank = { human: 3, agent: 2, inferred: 1 };
22521
+ const origin = (originRank[newOrigin] || 0) >= (originRank[existingOrigin] || 0) ? newOrigin : existingOrigin;
22522
+ const existingStatus = ep2.length > 16 ? ep2[16] || "" : "";
22523
+ const newStatus = np2.length > 16 ? np2[16] || "" : "";
22524
+ const status = newStatus === "active" || existingStatus === "active" ? "active" : newStatus || existingStatus || "active";
22525
+ return `${id2}|${category}|${key}|${content}|${file2}|${mergedTags}|${date5}|${ttl}|${accessed}|${mergedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}|${priority}|${path_scope}|${origin}|${status}`;
22476
22526
  }
22477
22527
  function generateSmartRecall(data, intent, opts = {}) {
22478
22528
  const entries = parseEntries(data);
@@ -33460,9 +33510,19 @@ function formatOverview(data) {
33460
33510
  if (e.ttl && isExpiredLocal(e.ttl)) expired++;
33461
33511
  }
33462
33512
  const cats = Object.entries(byCategory).map(([k3, v3]) => `${k3}:${v3}`).join(" ");
33513
+ const originBreak = () => {
33514
+ const o = {};
33515
+ for (const e of entries) {
33516
+ o[e.origin] = (o[e.origin] || 0) + 1;
33517
+ }
33518
+ return Object.entries(o).map(([k3, v3]) => `${k3}:${v3}`).join(" ");
33519
+ };
33520
+ const obsoleteCount = entries.filter((e) => e.status === "obsolete").length;
33463
33521
  const ttlNote = expired > 0 ? ` | ${expired} expired` : "";
33464
- return `## Memory (${entries.length} entries)${ttlNote}
33465
- ${cats}`;
33522
+ const obsoleteNote = obsoleteCount > 0 ? ` | ${obsoleteCount} obsolete` : "";
33523
+ return `## Memory (${entries.length} entries)${ttlNote}${obsoleteNote}
33524
+ ${cats}
33525
+ Origin: ${originBreak()}`;
33466
33526
  }
33467
33527
  function formatRelevantEntries(data, task, limit = 6) {
33468
33528
  const entries = parseEntries(data);
@@ -33802,6 +33862,33 @@ function generateContextHealth(data, root) {
33802
33862
  if (stale.length > 0) {
33803
33863
  info.push(`${stale.length} stale sessions (will be pruned automatically)`);
33804
33864
  }
33865
+ const missingEvidence = entries.filter((e) => e.path_scope && !e.file);
33866
+ if (missingEvidence.length > 0) {
33867
+ warnings.push(`${missingEvidence.length} entries with path_scope but no file (missing evidence): ${missingEvidence.slice(0, 3).map((e) => e.key).join(", ")}`);
33868
+ score -= 3;
33869
+ }
33870
+ const staleClaims = [];
33871
+ for (let i = 0; i < entries.length; i++) {
33872
+ for (let j3 = i + 1; j3 < entries.length; j3++) {
33873
+ const a = entries[i], b2 = entries[j3];
33874
+ if (a.category !== b2.category) continue;
33875
+ if (a.key === b2.key) continue;
33876
+ const aWords = new Set(normalize(a.content).split(/\s+/).filter((w3) => w3.length > 3));
33877
+ const bWords = new Set(normalize(b2.content).split(/\s+/).filter((w3) => w3.length > 3));
33878
+ const intersection2 = new Set([...aWords].filter((w3) => bWords.has(w3)));
33879
+ const union2 = /* @__PURE__ */ new Set([...aWords, ...bWords]);
33880
+ const similarity = union2.size > 0 ? intersection2.size / union2.size : 0;
33881
+ if (similarity > 0.4) {
33882
+ staleClaims.push(`${a.key} \u2248 ${b2.key} (${(similarity * 100).toFixed(0)}% same category)`);
33883
+ if (staleClaims.length >= 5) break;
33884
+ }
33885
+ }
33886
+ if (staleClaims.length >= 5) break;
33887
+ }
33888
+ if (staleClaims.length > 0) {
33889
+ warnings.push(`${staleClaims.length} potentially overlapping claims: ${staleClaims.slice(0, 3).join("; ")}`);
33890
+ score -= 3;
33891
+ }
33805
33892
  if (entries.length > 80) {
33806
33893
  warnings.push(`${entries.length} entries (near limit of 100)`);
33807
33894
  score -= 3;
@@ -33906,10 +33993,12 @@ function registerTools(server2) {
33906
33993
  file: external_exports.string().optional().default("").describe("Related file or line (e.g. spec.md:145)"),
33907
33994
  tags: external_exports.string().optional().default("").describe("Semicolon-separated tags (e.g. risk;spec)"),
33908
33995
  ttl: external_exports.string().optional().default("").describe("Time to live (e.g. 7d, 2026-07-17). Empty = no expiration"),
33909
- links: external_exports.string().optional().default("").describe("Related entry keys, separated by space or ';' (e.g. risk-spec engine-arch). Builds graph edges.")
33996
+ links: external_exports.string().optional().default("").describe("Related entry keys, separated by space or ';' (e.g. risk-spec engine-arch). Builds graph edges."),
33997
+ path_scope: external_exports.string().optional().default("").describe("Glob pattern to scope this entry (e.g. src/**.ts). Empty = global."),
33998
+ origin: external_exports.enum(["human", "agent", "inferred"]).optional().default("agent").describe("Who created this entry.")
33910
33999
  }
33911
34000
  },
33912
- async ({ category, key, content, file: file2, tags, ttl, links }) => {
34001
+ async ({ category, key, content, file: file2, tags, ttl, links, path_scope, origin }) => {
33913
34002
  const data = readMemory();
33914
34003
  const newId = generateId();
33915
34004
  const date5 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
@@ -33939,7 +34028,7 @@ function registerTools(server2) {
33939
34028
  const resolvedTags = tags ? tags : verbatim ? "" : inferTags(content, key, config2.vocab);
33940
34029
  const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : [];
33941
34030
  const resolvedLinks = links ? links.split(/[\s;]+/).filter(Boolean).join(" ") : existingParts[9] || "";
33942
- let newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0|${resolvedLinks}`;
34031
+ let newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0|${resolvedLinks}|||||${path_scope || ""}|${origin}`;
33943
34032
  let action = "Saved";
33944
34033
  let mergeInfo = "";
33945
34034
  const tagsInferred = !tags && resolvedTags ? true : false;
@@ -33951,9 +34040,9 @@ function registerTools(server2) {
33951
34040
  } else {
33952
34041
  const accessed = 0;
33953
34042
  const lastAccessed = "";
33954
- const quality = verbatim ? 0.5 : qualityScore(resolvedTags, resolvedLinks, content, date5, accessed, lastAccessed);
34043
+ const quality = verbatim ? 0.5 : qualityScore(resolvedTags, resolvedLinks, content, date5, accessed, lastAccessed, origin);
33955
34044
  const confidence = 1;
33956
- newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|${accessed}|${resolvedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}`;
34045
+ newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|${accessed}|${resolvedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}|0|${path_scope || ""}|${origin}|active`;
33957
34046
  const match = lines[headerIdx].match(/\[(\d+)\|/);
33958
34047
  const count = match ? parseInt(match[1]) : 0;
33959
34048
  lines.splice(headerIdx + 1, 0, ` ${newEntry}`);
@@ -34002,22 +34091,26 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34002
34091
  mode: external_exports.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall: expands the related-entry subgraph from matches (more precise, fewer tokens)."),
34003
34092
  hops: external_exports.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
34004
34093
  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."),
34005
- bias: external_exports.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default).")
34094
+ 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'."),
34095
+ bias: external_exports.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
34096
+ path_scope: external_exports.string().optional().default("").describe("Glob pattern to filter entries by path scope (e.g. 'src/**.ts').")
34006
34097
  }
34007
34098
  },
34008
- async ({ query, category, from_date, to_date, mode, hops, compact, bias }) => {
34099
+ async ({ query, category, from_date, to_date, mode, hops, compact, bias, budget: budgetParam, path_scope }) => {
34009
34100
  const data = readMemory();
34010
34101
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
34011
- const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, sessionFiles });
34102
+ const resolvedBudget = budgetParam || (compact ? "normal" : "deep");
34103
+ const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, sessionFiles, path_scope: path_scope || void 0 });
34012
34104
  if (detail.entries.length === 0) {
34013
34105
  return { content: [{ type: "text", text: `No results found for "${query}"` }] };
34014
34106
  }
34015
34107
  bumpAccessed(detail.entries.map((e) => e.id));
34016
- if (compact) {
34108
+ if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
34017
34109
  const formatted2 = renderCompact(detail.entries, {
34018
34110
  adjacency: detail.adjacency,
34019
34111
  seeds: detail.seeds,
34020
- snippetLen: 90
34112
+ snippetLen: 90,
34113
+ budget: resolvedBudget
34021
34114
  });
34022
34115
  return { content: [{ type: "text", text: formatted2 }] };
34023
34116
  }
@@ -34025,9 +34118,12 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34025
34118
  const links = r2.links.length ? `
34026
34119
  links: ${r2.links.join(", ")}` : "";
34027
34120
  const pin = r2.priority > 0 ? r2.priority > 1 ? ` \u{1F4CC}${r2.priority}` : " \u{1F4CC}" : "";
34121
+ const originInfo = r2.origin !== "agent" ? ` | origin: ${r2.origin}` : "";
34122
+ const scopeInfo = r2.path_scope ? ` | scope: ${r2.path_scope}` : "";
34123
+ const statusInfo = r2.status !== "active" ? ` | status: ${r2.status}` : "";
34028
34124
  return `[${r2.category}] ${r2.key}${pin} (${r2.id})
34029
34125
  ${r2.content}
34030
- File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}`;
34126
+ File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}${originInfo}${scopeInfo}${statusInfo}`;
34031
34127
  }).join("\n\n");
34032
34128
  return { content: [{ type: "text", text: formatted }] };
34033
34129
  }
@@ -34038,34 +34134,60 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34038
34134
  title: "Delete from Memory",
34039
34135
  description: "Delete a memory entry by its key or id.",
34040
34136
  inputSchema: {
34041
- key: external_exports.string().describe("Key or id of the entry to delete")
34137
+ key: external_exports.string().describe("Key or id of the entry to delete"),
34138
+ hard: external_exports.boolean().optional().default(false).describe("If true, permanently remove the entry. If false (default), softly marks as obsolete (status=obsolete) so it can be resolved or restored later.")
34042
34139
  }
34043
34140
  },
34044
- async ({ key }) => {
34141
+ async ({ key, hard }) => {
34045
34142
  const data = readMemory();
34046
34143
  const lines = data.split("\n");
34047
34144
  const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
34048
34145
  if (headerIdx === -1) {
34049
34146
  return { content: [{ type: "text", text: "No entries in memory" }] };
34050
34147
  }
34051
- const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
34052
- const filtered = entryLines2.filter((l) => {
34053
- const parts = l.trim().split("|");
34054
- return parts[0] !== key && parts[2] !== key;
34055
- });
34056
- const removed = entryLines2.length - filtered.length;
34057
- const match = lines[headerIdx].match(/\[(\d+)\|/);
34058
- const count = match ? parseInt(match[1]) : 0;
34059
- lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`);
34060
- lines.splice(headerIdx + 1, entryLines2.length, ...filtered.map((l) => ` ${l.trim()}`));
34148
+ if (hard) {
34149
+ const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
34150
+ const filtered = entryLines2.filter((l) => {
34151
+ const parts = l.trim().split("|");
34152
+ return parts[0] !== key && parts[2] !== key;
34153
+ });
34154
+ const removed = entryLines2.length - filtered.length;
34155
+ const match = lines[headerIdx].match(/\[(\d+)\|/);
34156
+ const count = match ? parseInt(match[1]) : 0;
34157
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`);
34158
+ lines.splice(headerIdx + 1, entryLines2.length, ...filtered.map((l) => ` ${l.trim()}`));
34159
+ writeMemory(lines.join("\n"));
34160
+ if (removed === 0) {
34161
+ return {
34162
+ content: [{ type: "text", text: `"${key}" not found in memory.` }]
34163
+ };
34164
+ }
34165
+ return {
34166
+ content: [{ type: "text", text: `"${key}" permanently deleted. ${count - removed} entries remaining.` }]
34167
+ };
34168
+ }
34169
+ let found = false;
34170
+ for (let i = headerIdx + 1; i < lines.length; i++) {
34171
+ const line = lines[i];
34172
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
34173
+ if (line.startsWith(" summaries:")) break;
34174
+ const parts = line.trim().split("|");
34175
+ if (parts[0] === key || parts[2] === key) {
34176
+ while (parts.length < 17) parts.push("");
34177
+ parts[16] = "obsolete";
34178
+ lines[i] = ` ${parts.join("|")}`;
34179
+ found = true;
34180
+ break;
34181
+ }
34182
+ }
34061
34183
  writeMemory(lines.join("\n"));
34062
- if (removed === 0) {
34184
+ if (!found) {
34063
34185
  return {
34064
34186
  content: [{ type: "text", text: `"${key}" not found in memory.` }]
34065
34187
  };
34066
34188
  }
34067
34189
  return {
34068
- content: [{ type: "text", text: `"${key}" deleted. ${count - removed} entries remaining.` }]
34190
+ content: [{ type: "text", text: `"${key}" marked as obsolete. Use memory_resolve(key: "${key}") to restore.` }]
34069
34191
  };
34070
34192
  }
34071
34193
  );
@@ -34081,7 +34203,7 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34081
34203
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
34082
34204
  const entries = lines.map((l) => {
34083
34205
  const parts = l.trim().split("|");
34084
- return { category: parts[1] || "unknown", ttl: parts[7] || "", quality: parts[10] || "" };
34206
+ return { category: parts[1] || "unknown", ttl: parts[7] || "", quality: parts[10] || "", origin: parts.length > 15 ? parts[15] || "" : "", status: parts.length > 16 ? parts[16] || "" : "" };
34085
34207
  });
34086
34208
  const byCategory = {};
34087
34209
  for (const e of entries) {
@@ -34092,6 +34214,12 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34092
34214
  const withQuality = entries.filter((e) => e.quality).length;
34093
34215
  const avgQuality = withQuality > 0 ? (entries.reduce((sum, e) => sum + (e.quality ? parseFloat(e.quality) : 0), 0) / withQuality).toFixed(2) : "N/A";
34094
34216
  const summaryLines = data.split("\n").filter((l) => l.includes(":") && !l.startsWith(" ") && !l.startsWith("version") && !l.startsWith("entries") && !/^\[\d+\|]/.test(l));
34217
+ const byOrigin = {};
34218
+ const byStatus = {};
34219
+ for (const e of entries) {
34220
+ byOrigin[e.origin || "agent"] = (byOrigin[e.origin || "agent"] || 0) + 1;
34221
+ byStatus[e.status || "active"] = (byStatus[e.status || "active"] || 0) + 1;
34222
+ }
34095
34223
  const stats = [
34096
34224
  `Total entries: ${entries.length}`,
34097
34225
  `File summaries: ${summaryLines.length}`,
@@ -34099,6 +34227,12 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34099
34227
  "By category:",
34100
34228
  ...Object.entries(byCategory).map(([k3, v3]) => ` ${k3}: ${v3}`),
34101
34229
  "",
34230
+ "By origin:",
34231
+ ...Object.entries(byOrigin).map(([k3, v3]) => ` ${k3}: ${v3}`),
34232
+ "",
34233
+ "By status:",
34234
+ ...Object.entries(byStatus).map(([k3, v3]) => ` ${k3}: ${v3}`),
34235
+ "",
34102
34236
  `TTL: ${withTtl} with expiration, ${expired} expired`,
34103
34237
  `Average quality: ${avgQuality} (${withQuality} with score)`,
34104
34238
  "",
@@ -34108,7 +34242,9 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34108
34242
  const ttlInfo = parts[7] ? ` | TTL: ${parts[7]}` : "";
34109
34243
  const qualityInfo = parts[10] ? ` | Q: ${parts[10]}` : "";
34110
34244
  const accessInfo = parts[8] && parseInt(parts[8]) > 0 ? ` | accessed: ${parts[8]}x` : "";
34111
- return ` [${parts[1]}] ${parts[2]} (${parts[0]})${ttlInfo}${qualityInfo}${accessInfo}`;
34245
+ const originInfo = parts.length > 15 && parts[15] && parts[15] !== "agent" ? ` | origin: ${parts[15]}` : "";
34246
+ const statusInfo = parts.length > 16 && parts[16] && parts[16] !== "active" ? ` | status: ${parts[16]}` : "";
34247
+ return ` [${parts[1]}] ${parts[2]} (${parts[0]})${ttlInfo}${qualityInfo}${accessInfo}${originInfo}${statusInfo}`;
34112
34248
  }),
34113
34249
  "",
34114
34250
  `Most accessed:`,
@@ -35394,13 +35530,16 @@ ${note}` : ""}`
35394
35530
  mode: external_exports.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall."),
35395
35531
  hops: external_exports.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
35396
35532
  compact: external_exports.boolean().optional().default(false).describe("Token-efficient output"),
35397
- bias: external_exports.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default).")
35533
+ 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'."),
35534
+ bias: external_exports.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
35535
+ path_scope: external_exports.string().optional().default("").describe("Glob pattern to filter entries by path scope (e.g. 'src/**.ts').")
35398
35536
  }
35399
35537
  },
35400
- async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact, bias }) => {
35538
+ async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact, bias, budget: budgetParam, path_scope }) => {
35401
35539
  const data = readMemory();
35402
35540
  const resolvedFrom = from_date ? parseRelativeDate(from_date) : "";
35403
35541
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
35542
+ const resolvedBudget = budgetParam || (compact ? "normal" : "deep");
35404
35543
  const detail = graphRecallDetailed(data, query, {
35405
35544
  category: category || void 0,
35406
35545
  tags: tags || void 0,
@@ -35408,17 +35547,19 @@ ${note}` : ""}`
35408
35547
  to_date: to_date || void 0,
35409
35548
  hops,
35410
35549
  limit,
35411
- sessionFiles
35550
+ sessionFiles,
35551
+ path_scope: path_scope || void 0
35412
35552
  });
35413
35553
  if (detail.entries.length === 0) {
35414
35554
  return { content: [{ type: "text", text: `No results found for "${query}"` }] };
35415
35555
  }
35416
35556
  bumpAccessed(detail.entries.map((e) => e.id));
35417
- if (compact) {
35557
+ if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
35418
35558
  const formatted2 = renderCompact(detail.entries, {
35419
35559
  adjacency: detail.adjacency,
35420
35560
  seeds: detail.seeds,
35421
- snippetLen: 90
35561
+ snippetLen: 90,
35562
+ budget: resolvedBudget
35422
35563
  });
35423
35564
  return { content: [{ type: "text", text: `\u{1F50D} Search: "${query}"
35424
35565
 
@@ -35428,9 +35569,12 @@ ${formatted2}` }] };
35428
35569
  const links = r2.links.length ? `
35429
35570
  links: ${r2.links.join(", ")}` : "";
35430
35571
  const pin = r2.priority > 0 ? r2.priority > 1 ? ` \u{1F4CC}${r2.priority}` : " \u{1F4CC}" : "";
35572
+ const originInfo = r2.origin !== "agent" ? ` | origin: ${r2.origin}` : "";
35573
+ const scopeInfo = r2.path_scope ? ` | scope: ${r2.path_scope}` : "";
35574
+ const statusInfo = r2.status !== "active" ? ` | status: ${r2.status}` : "";
35431
35575
  return `[${r2.category}] ${r2.key}${pin} (${r2.id})
35432
35576
  ${r2.content}
35433
- File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}`;
35577
+ File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}${originInfo}${scopeInfo}${statusInfo}`;
35434
35578
  }).join("\n\n");
35435
35579
  let filterInfo = "";
35436
35580
  if (category) filterInfo += ` category: ${category}`;
@@ -35507,6 +35651,83 @@ ${formatted}` }]
35507
35651
  };
35508
35652
  }
35509
35653
  );
35654
+ server2.registerTool(
35655
+ "memory_resolve",
35656
+ {
35657
+ title: "Resolve Entry",
35658
+ description: "Restore an obsolete entry back to active status, or mark an entry as resolved. Reverses soft-delete.",
35659
+ inputSchema: {
35660
+ key: external_exports.string().describe("Key or id of the entry to resolve/restore")
35661
+ }
35662
+ },
35663
+ async ({ key }) => {
35664
+ const data = readMemory();
35665
+ const lines = data.split("\n");
35666
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35667
+ if (headerIdx === -1) {
35668
+ return { content: [{ type: "text", text: "No entries in memory" }] };
35669
+ }
35670
+ let found = false;
35671
+ let wasObsolete = false;
35672
+ for (let i = headerIdx + 1; i < lines.length; i++) {
35673
+ const line = lines[i];
35674
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
35675
+ if (line.startsWith(" summaries:")) break;
35676
+ const parts = line.trim().split("|");
35677
+ if (parts[0] === key || parts[2] === key) {
35678
+ while (parts.length < 17) parts.push("");
35679
+ wasObsolete = parts[16] === "obsolete";
35680
+ parts[16] = "active";
35681
+ lines[i] = ` ${parts.join("|")}`;
35682
+ found = true;
35683
+ break;
35684
+ }
35685
+ }
35686
+ if (!found) {
35687
+ return { content: [{ type: "text", text: `"${key}" not found in memory.` }] };
35688
+ }
35689
+ writeMemory(lines.join("\n"));
35690
+ const msg = wasObsolete ? `"${key}" restored to active status.` : `"${key}" marked as resolved.`;
35691
+ return { content: [{ type: "text", text: `\u2705 ${msg}` }] };
35692
+ }
35693
+ );
35694
+ server2.registerTool(
35695
+ "memory_suppress",
35696
+ {
35697
+ title: "Suppress Entry",
35698
+ description: "Suppress a memory entry so it's hidden from normal recalls. Sets status to 'obsolete'. Use memory_resolve to restore.",
35699
+ inputSchema: {
35700
+ key: external_exports.string().describe("Key or id of the entry to suppress")
35701
+ }
35702
+ },
35703
+ async ({ key }) => {
35704
+ const data = readMemory();
35705
+ const lines = data.split("\n");
35706
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35707
+ if (headerIdx === -1) {
35708
+ return { content: [{ type: "text", text: "No entries in memory" }] };
35709
+ }
35710
+ let found = false;
35711
+ for (let i = headerIdx + 1; i < lines.length; i++) {
35712
+ const line = lines[i];
35713
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
35714
+ if (line.startsWith(" summaries:")) break;
35715
+ const parts = line.trim().split("|");
35716
+ if (parts[0] === key || parts[2] === key) {
35717
+ while (parts.length < 17) parts.push("");
35718
+ parts[16] = "obsolete";
35719
+ lines[i] = ` ${parts.join("|")}`;
35720
+ found = true;
35721
+ break;
35722
+ }
35723
+ }
35724
+ if (!found) {
35725
+ return { content: [{ type: "text", text: `"${key}" not found in memory.` }] };
35726
+ }
35727
+ writeMemory(lines.join("\n"));
35728
+ return { content: [{ type: "text", text: `"${key}" suppressed. Use memory_resolve(key: "${key}") to restore.` }] };
35729
+ }
35730
+ );
35510
35731
  K3(
35511
35732
  server2,
35512
35733
  "memory_visualize",
@@ -47170,7 +47391,7 @@ function registerResources(server2) {
47170
47391
 
47171
47392
  // src/mcp/server.ts
47172
47393
  var server = new McpServer(
47173
- { name: "toon-memory", version: "3.5.0" },
47394
+ { name: "toon-memory", version: "3.6.0" },
47174
47395
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true }, experimental: { "io.modelcontextprotocol/ui": {} } } }
47175
47396
  );
47176
47397
  var s = server.server;
@@ -47182,7 +47403,7 @@ s.setRequestHandler(InitializeRequestSchema, async (request) => {
47182
47403
  return {
47183
47404
  protocolVersion,
47184
47405
  capabilities: s.getCapabilities(),
47185
- serverInfo: { name: "toon-memory", version: "3.5.0" },
47406
+ serverInfo: { name: "toon-memory", version: "3.6.0" },
47186
47407
  ...s._instructions && { instructions: s._instructions }
47187
47408
  };
47188
47409
  });
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "toon-memory",
3
- "version": "3.5.0",
4
- "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.",
3
+ "mcpName": "io.github.LuiggiVal08/toon-memory",
4
+ "version": "3.6.0",
5
+ "description": "MCP server giving AI coding agents offline, token-efficient persistent memory — 37 tools, 80% fewer tool calls, recall decisions, patterns, and bugs across sessions. No LLM, no server; works with 15+ agents.",
5
6
  "type": "module",
6
7
  "bin": {
7
8
  "toon-memory": "./bin/toon-memory.js"
@@ -26,14 +26,15 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
26
26
  return await $\`npx -y toon-memory dump\`.cwd(root).text()
27
27
  }
28
28
 
29
- const recall = async (query) => {
29
+ const recall = async (query, opts = {}) => {
30
30
  try {
31
+ const args = { query, mode: "flat", budget: opts.budget || "tiny", path_scope: opts.path_scope || "" }
31
32
  const result = await $\`npx -y toon-memory mcp\`.cwd(root)
32
33
  .stdin(JSON.stringify({
33
34
  jsonrpc: "2.0",
34
35
  id: 1,
35
36
  method: "tools/call",
36
- params: { name: "memory_recall", arguments: { query, mode: "flat", compact: true } }
37
+ params: { name: "memory_recall", arguments: args }
37
38
  }))
38
39
  .text()
39
40
  const parsed = JSON.parse(result)
@@ -62,6 +63,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
62
63
  "tool.execute.after": async (input) => {
63
64
  // Intelligent auto-loading: extract file path from tool result,
64
65
  // recall only memory relevant to that file, inject as context.
66
+ // Also proactively recalls entries scoped to the matched paths.
65
67
  try {
66
68
  const toolName = input?.tool || ""
67
69
  const args = input?.args || {}
@@ -71,6 +73,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
71
73
  if (args.file) filePath = args.file
72
74
  else if (args.path) filePath = args.path
73
75
  else if (args.filePath) filePath = args.filePath
76
+ else if (args.target) filePath = args.target
74
77
 
75
78
  // Also try to extract from tool output text
76
79
  if (!filePath && input?.output) {
@@ -79,19 +82,40 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
79
82
  if (fileMatch) filePath = fileMatch[1]
80
83
  }
81
84
 
82
- if (!filePath) return
83
-
84
- // Build recall query from file path components
85
- const basename = path.basename(filePath, path.extname(filePath))
86
- const dirParts = path.dirname(filePath).split(path.sep).filter(Boolean)
87
- const query = [basename, ...dirParts.slice(-2)].join(" ")
88
-
89
- const text = await recall(query)
90
- if (!text || text.includes("(empty)") || text.includes("No results")) return
85
+ if (filePath) {
86
+ // Build recall query from file path components
87
+ const basename = path.basename(filePath, path.extname(filePath))
88
+ const dirParts = path.dirname(filePath).split(path.sep).filter(Boolean)
89
+ const query = [basename, ...dirParts.slice(-2)].join(" ")
90
+
91
+ const text = await recall(query, { budget: "tiny", path_scope: filePath })
92
+ if (text && !text.includes("(empty)") && !text.includes("No results")) {
93
+ if (typeof input?.setContext === "function") {
94
+ input.setContext("toon-memory:" + filePath, text)
95
+ }
96
+ }
97
+ }
91
98
 
92
- // Inject as context for the next agent turn
93
- if (typeof input?.setContext === "function") {
94
- input.setContext("toon-memory:" + filePath, text)
99
+ // Proactive recall: if no file was found, try tool-name-based recall
100
+ // for common tool patterns that may have relevant memory entries
101
+ if (!filePath && toolName) {
102
+ const toolKeywords = toolName
103
+ .replace(/^memory_/, "")
104
+ .replace(/^context_/, "")
105
+ .replace(/^file_/, "")
106
+ .replace(/^text_document_/, "")
107
+ .split("_")
108
+ .filter(Boolean)
109
+ .join(" ")
110
+
111
+ if (toolKeywords.length > 3) {
112
+ const text = await recall(toolKeywords, { budget: "tiny" })
113
+ if (text && !text.includes("(empty)") && !text.includes("No results")) {
114
+ if (typeof input?.setContext === "function") {
115
+ input.setContext("toon-memory:" + toolName, text)
116
+ }
117
+ }
118
+ }
95
119
  }
96
120
  } catch {}
97
121
  },