toon-memory 3.7.0 → 4.1.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
@@ -21988,24 +21988,83 @@ var require_dist = __commonJS({
21988
21988
  });
21989
21989
 
21990
21990
  // src/lib/utils.ts
21991
- function importance(e) {
21992
- const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
21993
- const days = (Date.now() - (/* @__PURE__ */ new Date(`${e.date || today}T00:00:00`)).getTime()) / 864e5;
21991
+ function importance(e, today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0]) {
21992
+ const days = (Date.parse(`${today}T00:00:00`) - Date.parse(`${e.date || today}T00:00:00`)) / 864e5;
21994
21993
  const recency = Math.min(1, Math.max(0, 30 - days) / 30);
21995
21994
  const freq = Math.min(1, e.accessed / 5);
21996
21995
  return recency * 0.6 + freq * 0.4;
21997
21996
  }
21998
- var normalize, isExpiredLocal, tokenize, isPrivate;
21997
+ var normalize, isExpiredLocal, tokenize, escField, unescField, parseToonLine, toToonLine, isPrivate;
21999
21998
  var init_utils = __esm({
22000
21999
  "src/lib/utils.ts"() {
22001
22000
  "use strict";
22002
22001
  normalize = (s2) => s2.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
22003
- isExpiredLocal = (ttl) => {
22002
+ isExpiredLocal = (ttl, today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0]) => {
22004
22003
  if (!ttl) return false;
22005
- const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
22006
22004
  return ttl <= today;
22007
22005
  };
22008
22006
  tokenize = (s2) => s2.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[-_]/g, " ").toLowerCase().split(/\s+/).filter(Boolean);
22007
+ escField = (s2) => {
22008
+ let out = "";
22009
+ for (let i = 0; i < s2.length; i++) {
22010
+ const c2 = s2[i];
22011
+ if (c2 === "\\") out += "\\\\";
22012
+ else if (c2 === "\n") out += "\\n";
22013
+ else if (c2 === "\r") {
22014
+ out += "\\n";
22015
+ if (s2[i + 1] === "\n") i++;
22016
+ } else if (c2 === "|") out += "\\|";
22017
+ else out += c2;
22018
+ }
22019
+ return out;
22020
+ };
22021
+ unescField = (s2) => {
22022
+ let out = "";
22023
+ for (let i = 0; i < s2.length; i++) {
22024
+ const c2 = s2[i];
22025
+ if (c2 === "\\" && i + 1 < s2.length) {
22026
+ const n = s2[i + 1];
22027
+ if (n === "n") {
22028
+ out += "\n";
22029
+ i++;
22030
+ } else if (n === "|") {
22031
+ out += "|";
22032
+ i++;
22033
+ } else if (n === "\\") {
22034
+ out += "\\";
22035
+ i++;
22036
+ } else out += c2;
22037
+ } else out += c2;
22038
+ }
22039
+ return out;
22040
+ };
22041
+ parseToonLine = (line) => {
22042
+ const parts = [];
22043
+ let cur = "";
22044
+ let escaped = false;
22045
+ for (const c2 of line.trim()) {
22046
+ if (escaped) {
22047
+ cur += c2;
22048
+ escaped = false;
22049
+ continue;
22050
+ }
22051
+ if (c2 === "\\") {
22052
+ cur += c2;
22053
+ escaped = true;
22054
+ continue;
22055
+ }
22056
+ if (c2 === "|") {
22057
+ parts.push(unescField(cur));
22058
+ cur = "";
22059
+ continue;
22060
+ }
22061
+ cur += c2;
22062
+ }
22063
+ if (escaped) cur += "\\";
22064
+ parts.push(unescField(cur));
22065
+ return parts;
22066
+ };
22067
+ toToonLine = (parts) => ` ${parts.map(escField).join("|")}`;
22009
22068
  isPrivate = (e) => e.tags.some((t) => t.toLowerCase() === "private");
22010
22069
  }
22011
22070
  });
@@ -22177,7 +22236,7 @@ function typedLinks(links) {
22177
22236
  function parseEntries(data) {
22178
22237
  const out = [];
22179
22238
  for (const line of entryLines(data)) {
22180
- const parts = line.trim().split("|");
22239
+ const parts = parseToonLine(line);
22181
22240
  if (parts.length < 7) continue;
22182
22241
  const [id2, category, key, content, file2, tags, date5, ttl, accessedRaw, linksRaw] = parts;
22183
22242
  out.push({
@@ -22201,6 +22260,19 @@ function parseEntries(data) {
22201
22260
  }
22202
22261
  return out;
22203
22262
  }
22263
+ function orphanScore(a, b2) {
22264
+ const aTags = new Set(a.tags);
22265
+ let sharedTags = 0;
22266
+ for (const t of b2.tags) if (aTags.has(t)) sharedTags++;
22267
+ const aKey = new Set(tokenize(a.key));
22268
+ const bKey = new Set(tokenize(b2.key));
22269
+ let sharedKey = 0;
22270
+ for (const t of bKey) if (aKey.has(t)) sharedKey++;
22271
+ const aTok = new Set(tokenize(a.content));
22272
+ let sharedContent = 0;
22273
+ for (const t of tokenize(b2.content)) if (aTok.has(t)) sharedContent++;
22274
+ return sharedTags * 4 + sharedKey * 2 + sharedContent;
22275
+ }
22204
22276
  function buildGraph(entries) {
22205
22277
  const byKey = /* @__PURE__ */ new Map();
22206
22278
  for (const e of entries) {
@@ -22236,8 +22308,71 @@ function buildGraph(entries) {
22236
22308
  }
22237
22309
  const adjacency = /* @__PURE__ */ new Map();
22238
22310
  for (const [k3, v3] of adj) adjacency.set(k3, [...v3]);
22311
+ const allKeys = [...byKey.keys()];
22312
+ for (const key of allKeys) {
22313
+ if (adj.has(key)) continue;
22314
+ let best = "";
22315
+ let bestScore = -1;
22316
+ for (const other of allKeys) {
22317
+ if (other === key) continue;
22318
+ const score = orphanScore(byKey.get(key), byKey.get(other));
22319
+ if (best === "" || score > bestScore || score === bestScore && other < best) {
22320
+ bestScore = score;
22321
+ best = other;
22322
+ }
22323
+ }
22324
+ if (best) link(key, best);
22325
+ }
22326
+ for (const [k3, v3] of adj) adjacency.set(k3, [...v3]);
22327
+ const comps = connectedComponents(adjacency);
22328
+ if (comps.length > 1) {
22329
+ let largest = comps[0];
22330
+ for (const c2 of comps) if (c2.length > largest.length) largest = c2;
22331
+ const largestSet = new Set(largest);
22332
+ for (const comp of comps) {
22333
+ if (comp.length === largest.length && comp[0] === largest[0]) continue;
22334
+ let bestA = "";
22335
+ let bestB = "";
22336
+ let bestScore = -1;
22337
+ for (const a of comp) {
22338
+ const ea2 = byKey.get(a);
22339
+ for (const b2 of largest) {
22340
+ const score = orphanScore(ea2, byKey.get(b2));
22341
+ if (bestA === "" || score > bestScore || score === bestScore && a + b2 < bestA + bestB) {
22342
+ bestScore = score;
22343
+ bestA = a;
22344
+ bestB = b2;
22345
+ }
22346
+ }
22347
+ }
22348
+ if (bestA) link(bestA, bestB);
22349
+ }
22350
+ for (const [k3, v3] of adj) adjacency.set(k3, [...v3]);
22351
+ }
22239
22352
  return { adjacency, byKey };
22240
22353
  }
22354
+ function connectedComponents(adjacency) {
22355
+ const comps = [];
22356
+ const seen = /* @__PURE__ */ new Set();
22357
+ for (const [start] of adjacency) {
22358
+ if (seen.has(start)) continue;
22359
+ const comp = [];
22360
+ const stack = [start];
22361
+ seen.add(start);
22362
+ while (stack.length) {
22363
+ const cur = stack.pop();
22364
+ comp.push(cur);
22365
+ for (const next of adjacency.get(cur) || []) {
22366
+ if (!seen.has(next)) {
22367
+ seen.add(next);
22368
+ stack.push(next);
22369
+ }
22370
+ }
22371
+ }
22372
+ comps.push(comp);
22373
+ }
22374
+ return comps;
22375
+ }
22241
22376
  function rrfFuse(rankers, k3 = 60) {
22242
22377
  const out = /* @__PURE__ */ new Map();
22243
22378
  for (const ranker of rankers) {
@@ -22319,7 +22454,7 @@ function graphRecallDetailed(data, query, opts = {}) {
22319
22454
  if (tagsFilter.length > 0 && !tagsFilter.every((t) => e.tags.includes(t))) continue;
22320
22455
  if (from_date && e.date < from_date) continue;
22321
22456
  if (to_date && e.date > to_date) continue;
22322
- if (e.ttl && isExpiredLocal(e.ttl)) continue;
22457
+ if (e.ttl && isExpiredLocal(e.ttl, opts.today)) continue;
22323
22458
  if (opts.path_scope && e.path_scope && !globMatch(opts.path_scope, e.path_scope)) continue;
22324
22459
  const text = normalize(
22325
22460
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
@@ -22343,8 +22478,8 @@ function graphRecallDetailed(data, query, opts = {}) {
22343
22478
  scored.push(
22344
22479
  ...visibleEntries.sort((a, b2) => {
22345
22480
  if (a.priority !== b2.priority) return b2.priority - a.priority;
22346
- return importance(b2) - importance(a);
22347
- }).slice(0, opts.limit ?? 6).map((e) => ({ e, s: importance(e) }))
22481
+ return importance(b2, opts.today) - importance(a, opts.today);
22482
+ }).slice(0, opts.limit ?? 6).map((e) => ({ e, s: importance(e, opts.today) }))
22348
22483
  );
22349
22484
  } else {
22350
22485
  const best = /* @__PURE__ */ new Map();
@@ -22369,7 +22504,7 @@ function graphRecallDetailed(data, query, opts = {}) {
22369
22504
  const e = byKey.get(k3);
22370
22505
  const dist = best.get(k3);
22371
22506
  const decay = Math.pow(DECAY, dist);
22372
- let s2 = fused ? fused.get(k3) || 0 : (bm25.get(k3) || 0) + W_CENT * (cent.get(k3) || 0) + W_IMP * importance(e);
22507
+ let s2 = fused ? fused.get(k3) || 0 : (bm25.get(k3) || 0) + W_CENT * (cent.get(k3) || 0) + W_IMP * importance(e, opts.today);
22373
22508
  if (!fused && seedKeys.has(k3)) s2 += SEED_BONUS;
22374
22509
  if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
22375
22510
  const entryFile = e.file.split(":")[0];
@@ -22531,8 +22666,8 @@ function qualityScore(tags, links, content, date5, accessed = 0, lastAccessed =
22531
22666
  return Math.max(0, Math.min(1, score));
22532
22667
  }
22533
22668
  function mergeEntries(existingLine, newLine) {
22534
- const ep2 = existingLine.trim().split("|");
22535
- const np2 = newLine.trim().split("|");
22669
+ const ep2 = parseToonLine(existingLine);
22670
+ const np2 = parseToonLine(newLine);
22536
22671
  if (ep2.length < 7 || np2.length < 7) return newLine;
22537
22672
  const id2 = ep2[0];
22538
22673
  const category = np2[1] || ep2[1];
@@ -22575,7 +22710,7 @@ function mergeEntries(existingLine, newLine) {
22575
22710
  const newStatus = np2.length > 16 ? np2[16] || "" : "";
22576
22711
  const status = newStatus === "active" || existingStatus === "active" ? "active" : newStatus || existingStatus || "active";
22577
22712
  const existingSupersededOn = ep2.length > 17 ? ep2[17] || "" : "";
22578
- return `${id2}|${category}|${key}|${content}|${file2}|${mergedTags}|${date5}|${ttl}|${accessed}|${mergedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}|${priority}|${path_scope}|${origin}|${status}|${existingSupersededOn}`;
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]);
22579
22714
  }
22580
22715
  function generateSmartRecall(data, intent, opts = {}) {
22581
22716
  const entries = parseEntries(data);
@@ -22590,7 +22725,7 @@ function generateSmartRecall(data, intent, opts = {}) {
22590
22725
  const expandedTokens = expandSynonyms(qTokens);
22591
22726
  const eligible = entries.filter((e) => {
22592
22727
  if (category && e.category !== category) return false;
22593
- if (e.ttl && isExpiredLocal(e.ttl)) return false;
22728
+ if (e.ttl && isExpiredLocal(e.ttl, opts.today)) return false;
22594
22729
  if (e.status === "obsolete" || e.status === "draft") return false;
22595
22730
  return true;
22596
22731
  });
@@ -22607,7 +22742,7 @@ function generateSmartRecall(data, intent, opts = {}) {
22607
22742
  const matchesQuery = exactMatch || fuzzy;
22608
22743
  const bm25Score = bm25.get(e.key) || 0;
22609
22744
  const centScore = cent.get(e.key) || 0;
22610
- const impScore = importance(e);
22745
+ const impScore = importance(e, opts.today);
22611
22746
  let drift = 0;
22612
22747
  if (mtimes && e.file) {
22613
22748
  const filePath = e.file.split(":")[0];
@@ -22641,7 +22776,7 @@ function generateSmartRecall(data, intent, opts = {}) {
22641
22776
  if (scored.length === 0) {
22642
22777
  const top = eligible.sort((a, b2) => {
22643
22778
  if (a.priority !== b2.priority) return b2.priority - a.priority;
22644
- return importance(b2) - importance(a);
22779
+ return importance(b2, opts.today) - importance(a, opts.today);
22645
22780
  }).slice(0, limit);
22646
22781
  if (top.length === 0) return "No entries in memory.";
22647
22782
  return renderCompact(top);
@@ -32865,7 +33000,7 @@ function entryScore(dateStr, accessed) {
32865
33000
  return importance({ date: dateStr, accessed });
32866
33001
  }
32867
33002
  function entryScoreForLine(line) {
32868
- const parts = line.trim().split("|");
33003
+ const parts = parseToonLine(line);
32869
33004
  const date5 = parts[6] || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
32870
33005
  const accessed = parts.length > 8 ? parseInt(parts[8]) || 0 : 0;
32871
33006
  return entryScore(date5, accessed);
@@ -32876,7 +33011,7 @@ function findRelatedEntries(text, excludeKey = "", limit = 3) {
32876
33011
  const queryTokens = normalize(text).split(" ").filter(Boolean);
32877
33012
  const scored = lines.map((line) => {
32878
33013
  const trimmed = line.trim();
32879
- const parts = trimmed.split("|");
33014
+ const parts = parseToonLine(trimmed);
32880
33015
  if (parts.length < 7) return null;
32881
33016
  const [id2, cat, key, content, file2, tags, date5] = parts;
32882
33017
  if (key === excludeKey) return null;
@@ -32902,13 +33037,13 @@ function bumpAccessed(ids) {
32902
33037
  const line = lines[i];
32903
33038
  if (!line.startsWith(" ") || !line.includes("|")) continue;
32904
33039
  if (line.startsWith(" summaries:")) break;
32905
- const parts = line.trim().split("|");
33040
+ const parts = parseToonLine(line);
32906
33041
  if (idSet.has(parts[0])) {
32907
33042
  const accessed = parts.length > 8 ? (parseInt(parts[8]) || 0) + 1 : 1;
32908
33043
  parts[8] = String(accessed);
32909
33044
  while (parts.length < 13) parts.push("");
32910
33045
  parts[12] = now;
32911
- lines[i] = ` ${parts.join("|")}`;
33046
+ lines[i] = toToonLine(parts);
32912
33047
  }
32913
33048
  }
32914
33049
  writeMemory(lines.join("\n"));
@@ -32916,16 +33051,18 @@ function bumpAccessed(ids) {
32916
33051
 
32917
33052
  // src/mcp/observations.ts
32918
33053
  import { readFileSync as readFileSync3, existsSync as existsSync3, writeFileSync as writeFileSync3 } from "fs";
33054
+ init_utils();
32919
33055
  function readObservations() {
32920
33056
  if (!existsSync3(OBSERVATIONS_FILE)) return [];
32921
33057
  return readFileSync3(OBSERVATIONS_FILE, "utf-8").split("\n").filter((l) => l.startsWith(" ") && l.includes("|")).map((l) => {
32922
- const p2 = l.trim().split("|");
33058
+ const p2 = parseToonLine(l);
32923
33059
  return { ts: p2[0] || "", session: p2[1] || "", agent: p2[2] || "", branch: p2[3] || "", tool: p2[4] || "", file: p2[6] || "", summary: p2[7] || "" };
32924
33060
  });
32925
33061
  }
32926
33062
 
32927
33063
  // src/mcp/archive.ts
32928
33064
  import { readFileSync as readFileSync4, existsSync as existsSync4 } from "fs";
33065
+ init_utils();
32929
33066
  function archiveOldEntries(opts = {}) {
32930
33067
  const data = readMemory();
32931
33068
  const lines = data.split("\n");
@@ -32938,7 +33075,7 @@ function archiveOldEntries(opts = {}) {
32938
33075
  const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0);
32939
33076
  const toArchive = /* @__PURE__ */ new Set();
32940
33077
  entryLines2.forEach((line, idx) => {
32941
- const parts = line.trim().split("|");
33078
+ const parts = parseToonLine(line);
32942
33079
  if (parts.length < 7) return;
32943
33080
  const date5 = parts[6];
32944
33081
  const ttl = parts[7] || "";
@@ -32999,7 +33136,7 @@ function pruneExpiredEntries() {
32999
33136
  if (headerIdx === -1) return;
33000
33137
  const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
33001
33138
  const kept = entryLines2.filter((l) => {
33002
- const parts = l.trim().split("|");
33139
+ const parts = parseToonLine(l);
33003
33140
  if (parts.length < 8) return true;
33004
33141
  const ttl = parts[7] || "";
33005
33142
  if (ttl && isExpired(ttl)) {
@@ -33021,6 +33158,7 @@ function pruneExpiredEntries() {
33021
33158
 
33022
33159
  // src/mcp/consolidation.ts
33023
33160
  init_quality();
33161
+ init_utils();
33024
33162
  function contentSimilarity(a, b2) {
33025
33163
  const wordsA = new Set(a.toLowerCase().replace(/\s+/g, " ").trim().split(" "));
33026
33164
  const wordsB = new Set(b2.toLowerCase().replace(/\s+/g, " ").trim().split(" "));
@@ -33045,11 +33183,11 @@ function consolidateEntries() {
33045
33183
  const mergedAway = [];
33046
33184
  for (let i = 0; i < entryLines2.length; i++) {
33047
33185
  const line = entryLines2[i].trim();
33048
- const parts = line.split("|");
33186
+ const parts = parseToonLine(line);
33049
33187
  if (parts.length < 3) continue;
33050
33188
  const key = parts[2];
33051
33189
  const existingIdx = keyOrder.findIndex((idx) => {
33052
- const ep2 = entryLines2[idx].trim().split("|");
33190
+ const ep2 = parseToonLine(entryLines2[idx]);
33053
33191
  return ep2[2] === key;
33054
33192
  });
33055
33193
  if (existingIdx !== -1) {
@@ -33066,7 +33204,7 @@ function consolidateEntries() {
33066
33204
  const duplicates = [];
33067
33205
  for (const idx of keyOrder) {
33068
33206
  const line = byKey.get(idx);
33069
- const parts = line.split("|");
33207
+ const parts = parseToonLine(line);
33070
33208
  if (parts.length < 3) {
33071
33209
  order.push(line);
33072
33210
  continue;
@@ -33079,7 +33217,7 @@ function consolidateEntries() {
33079
33217
  }
33080
33218
  let merged = false;
33081
33219
  for (const [seenNorm, existing] of contentSeen) {
33082
- const existingParts = existing.line.split("|");
33220
+ const existingParts = parseToonLine(existing.line);
33083
33221
  if (existingParts[1] !== parts[1]) continue;
33084
33222
  const sim = contentSimilarity(content, existingParts[3] || "");
33085
33223
  if (sim >= NEAR_DUP_THRESHOLD) {
@@ -34044,6 +34182,356 @@ init_sessions();
34044
34182
  init_utils();
34045
34183
  init_synonyms();
34046
34184
  function registerTools(server2) {
34185
+ function softDelete(key) {
34186
+ const data = readMemory();
34187
+ const lines = data.split("\n");
34188
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
34189
+ if (headerIdx === -1) {
34190
+ return { content: [{ type: "text", text: "No entries in memory" }] };
34191
+ }
34192
+ let found = false;
34193
+ for (let i = headerIdx + 1; i < lines.length; i++) {
34194
+ const line = lines[i];
34195
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
34196
+ if (line.startsWith(" summaries:")) break;
34197
+ const parts = parseToonLine(line);
34198
+ if (parts[0] === key || parts[2] === key) {
34199
+ while (parts.length < 17) parts.push("");
34200
+ parts[16] = "obsolete";
34201
+ lines[i] = toToonLine(parts);
34202
+ found = true;
34203
+ break;
34204
+ }
34205
+ }
34206
+ writeMemory(lines.join("\n"));
34207
+ if (!found) {
34208
+ return { content: [{ type: "text", text: `"${key}" not found in memory.` }] };
34209
+ }
34210
+ return { content: [{ type: "text", text: `"${key}" marked as obsolete. Use memory_forget(key, action: 'restore') to restore.` }] };
34211
+ }
34212
+ function hardDelete(key) {
34213
+ const data = readMemory();
34214
+ const lines = data.split("\n");
34215
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
34216
+ if (headerIdx === -1) {
34217
+ return { content: [{ type: "text", text: "No entries in memory" }] };
34218
+ }
34219
+ const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
34220
+ const filtered = entryLines2.filter((l) => {
34221
+ const parts = parseToonLine(l);
34222
+ return parts[0] !== key && parts[2] !== key;
34223
+ });
34224
+ const removed = entryLines2.length - filtered.length;
34225
+ const match = lines[headerIdx].match(/\[(\d+)\|/);
34226
+ const count = match ? parseInt(match[1]) : 0;
34227
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`);
34228
+ lines.splice(headerIdx + 1, entryLines2.length, ...filtered.map((l) => ` ${l.trim()}`));
34229
+ writeMemory(lines.join("\n"));
34230
+ if (removed === 0) {
34231
+ return { content: [{ type: "text", text: `"${key}" not found in memory.` }] };
34232
+ }
34233
+ return { content: [{ type: "text", text: `"${key}" permanently deleted. ${count - removed} entries remaining.` }] };
34234
+ }
34235
+ function restoreEntry(key) {
34236
+ const data = readMemory();
34237
+ const lines = data.split("\n");
34238
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
34239
+ if (headerIdx === -1) {
34240
+ return { content: [{ type: "text", text: "No entries in memory" }] };
34241
+ }
34242
+ let found = false;
34243
+ let wasObsolete = false;
34244
+ for (let i = headerIdx + 1; i < lines.length; i++) {
34245
+ const line = lines[i];
34246
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
34247
+ if (line.startsWith(" summaries:")) break;
34248
+ const parts = parseToonLine(line);
34249
+ if (parts[0] === key || parts[2] === key) {
34250
+ while (parts.length < 17) parts.push("");
34251
+ wasObsolete = parts[16] === "obsolete";
34252
+ parts[16] = "active";
34253
+ lines[i] = toToonLine(parts);
34254
+ found = true;
34255
+ break;
34256
+ }
34257
+ }
34258
+ if (!found) {
34259
+ return { content: [{ type: "text", text: `"${key}" not found in memory.` }] };
34260
+ }
34261
+ writeMemory(lines.join("\n"));
34262
+ const msg = wasObsolete ? `"${key}" restored to active status.` : `"${key}" marked as resolved.`;
34263
+ return { content: [{ type: "text", text: `\u2705 ${msg}` }] };
34264
+ }
34265
+ function supersedeEntry(old_key, new_key, reason) {
34266
+ const data = readMemory();
34267
+ const lines = data.split("\n");
34268
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
34269
+ if (headerIdx === -1) {
34270
+ return { content: [{ type: "text", text: "No entries in memory" }] };
34271
+ }
34272
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
34273
+ let oldIdx = -1;
34274
+ for (let i = headerIdx + 1; i < lines.length; i++) {
34275
+ const line = lines[i];
34276
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
34277
+ if (line.startsWith(" summaries:")) break;
34278
+ const parts = parseToonLine(line);
34279
+ if (parts[0] === old_key || parts[2] === old_key) {
34280
+ oldIdx = i;
34281
+ break;
34282
+ }
34283
+ }
34284
+ if (oldIdx === -1) {
34285
+ return { content: [{ type: "text", text: `\u274C "${old_key}" not found in memory.` }] };
34286
+ }
34287
+ let newIdx = -1;
34288
+ let newKey = "";
34289
+ if (new_key) {
34290
+ for (let i = headerIdx + 1; i < lines.length; i++) {
34291
+ const line = lines[i];
34292
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
34293
+ if (line.startsWith(" summaries:")) break;
34294
+ const parts = parseToonLine(line);
34295
+ if (parts[0] === new_key || parts[2] === new_key) {
34296
+ newIdx = i;
34297
+ newKey = parts[2];
34298
+ break;
34299
+ }
34300
+ }
34301
+ if (newIdx === -1) {
34302
+ return { content: [{ type: "text", text: `\u274C Replacement "${new_key}" not found in memory.` }] };
34303
+ }
34304
+ }
34305
+ const oldParts = parseToonLine(lines[oldIdx]);
34306
+ const oldKey = oldParts[2];
34307
+ const tags = (oldParts[5] || "").split(";").map((t) => t.trim()).filter(Boolean);
34308
+ if (!tags.includes("superseded")) tags.push("superseded");
34309
+ const links = (oldParts[9] || "").split(/[\s;]+/).filter(Boolean);
34310
+ if (newKey) {
34311
+ const edge = formatLink("superseded_by", newKey);
34312
+ if (!links.includes(edge)) links.push(edge);
34313
+ }
34314
+ let content = oldParts[3] || "";
34315
+ if (reason && !content.includes(reason)) {
34316
+ const flat = reason.replace(/[\r\n]+/g, " ").trim();
34317
+ content = `${content} \u23F3 Superseded (${today}): ${flat}`;
34318
+ }
34319
+ while (oldParts.length < 18) oldParts.push("");
34320
+ oldParts[3] = content;
34321
+ oldParts[5] = tags.join(";");
34322
+ oldParts[9] = links.join(" ");
34323
+ oldParts[16] = "obsolete";
34324
+ oldParts[17] = today;
34325
+ lines[oldIdx] = toToonLine(oldParts);
34326
+ if (newIdx !== -1) {
34327
+ const newParts = parseToonLine(lines[newIdx]);
34328
+ const newLinks = (newParts[9] || "").split(/[\s;]+/).filter(Boolean);
34329
+ const edge = formatLink("supersedes", oldKey);
34330
+ if (!newLinks.includes(edge)) {
34331
+ newLinks.push(edge);
34332
+ newParts[9] = newLinks.join(" ");
34333
+ lines[newIdx] = toToonLine(newParts);
34334
+ }
34335
+ }
34336
+ writeMemory(lines.join("\n"));
34337
+ const target = newKey ? ` by "${newKey}"` : " (retired)";
34338
+ return {
34339
+ content: [{
34340
+ type: "text",
34341
+ text: `\u23F3 "${oldKey}" superseded${target} on ${today}.
34342
+
34343
+ Old entry is now status=obsolete (hidden from normal recalls).
34344
+ \xB7 link: superseded_by${newKey ? `:${newKey}` : ""}
34345
+ \xB7 tag: superseded
34346
+
34347
+ To see what was true before: memory_recall(query: "${oldKey}", as_of: "${today}")
34348
+ To restore: memory_forget(key: "${oldKey}", action: 'restore')${reason ? `
34349
+
34350
+ Reason: ${reason}` : ""}`
34351
+ }]
34352
+ };
34353
+ }
34354
+ function runConsolidate() {
34355
+ const result = consolidateEntries();
34356
+ if (result.removed === 0) {
34357
+ return { content: [{ type: "text", text: `\u2705 Memory already consolidated (${result.kept} entries, 0 duplicates)` }] };
34358
+ }
34359
+ return {
34360
+ content: [{
34361
+ type: "text",
34362
+ text: `\u{1F9F9} Consolidated ${result.removed} duplicate entries.
34363
+ ${result.kept} active entries remaining.
34364
+ Duplicates: ${result.duplicates.join(", ")}`
34365
+ }]
34366
+ };
34367
+ }
34368
+ function runMergeSimilar(dryRun) {
34369
+ const data = readMemory();
34370
+ const lines = data.split("\n");
34371
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
34372
+ if (headerIdx === -1) {
34373
+ return { content: [{ type: "text", text: "No entries in memory." }] };
34374
+ }
34375
+ const parsed = [];
34376
+ for (let i = headerIdx + 1; i < lines.length; i++) {
34377
+ const line = lines[i];
34378
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
34379
+ if (line.startsWith(" summaries:")) break;
34380
+ const parts = parseToonLine(line);
34381
+ if (parts.length < 7) continue;
34382
+ const [id2, cat, key, content, file2, tags, date5, ttl, accessedRaw] = parts;
34383
+ const words = new Set(normalize(`${key} ${content} ${tags}`).split(" ").filter(Boolean));
34384
+ parsed.push({ lineIdx: i, id: id2, cat, key, content, file: file2, tags, date: date5, ttl, accessed: parseInt(accessedRaw) || 0, words, line });
34385
+ }
34386
+ if (parsed.length < 2) {
34387
+ return { content: [{ type: "text", text: "\u2705 Not enough entries to compress." }] };
34388
+ }
34389
+ const mergePairs = [];
34390
+ for (let i = 0; i < parsed.length; i++) {
34391
+ for (let j3 = i + 1; j3 < parsed.length; j3++) {
34392
+ const a = parsed[i], b2 = parsed[j3];
34393
+ const intersection2 = new Set([...a.words].filter((w3) => b2.words.has(w3)));
34394
+ const union2 = /* @__PURE__ */ new Set([...a.words, ...b2.words]);
34395
+ const similarity = union2.size > 0 ? intersection2.size / union2.size : 0;
34396
+ if (similarity > 0.5) {
34397
+ mergePairs.push({ a: i, b: j3, similarity });
34398
+ }
34399
+ }
34400
+ }
34401
+ if (mergePairs.length === 0) {
34402
+ return { content: [{ type: "text", text: "\u2705 No similar entries found to merge." }] };
34403
+ }
34404
+ mergePairs.sort((x, y2) => y2.similarity - x.similarity);
34405
+ const merged = /* @__PURE__ */ new Set();
34406
+ const mergeActions = [];
34407
+ for (const pair of mergePairs) {
34408
+ if (merged.has(pair.a) || merged.has(pair.b)) continue;
34409
+ const a = parsed[pair.a], b2 = parsed[pair.b];
34410
+ const mergedTags = [.../* @__PURE__ */ new Set([...a.tags.split(";"), ...b2.tags.split(";")])].filter(Boolean).join(";");
34411
+ const longer = a.content.length >= b2.content.length ? a : b2;
34412
+ const shorter = a.content.length < b2.content.length ? a : b2;
34413
+ const newContent = longer.content;
34414
+ const newDate = a.date > b2.date ? a.date : b2.date;
34415
+ const newAccessed = a.accessed + b2.accessed;
34416
+ mergeActions.push(` [${longer.cat}] ${longer.key} \u2190 ${shorter.key} (similarity: ${(pair.similarity * 100).toFixed(0)}%)`);
34417
+ if (!dryRun) {
34418
+ const lp2 = parseToonLine(longer.line);
34419
+ const mergedLine = toToonLine([longer.id, longer.cat, longer.key, newContent, longer.file, mergedTags, newDate, longer.ttl, String(newAccessed), lp2[9] || "", lp2[10] || "", lp2[11] || "", lp2[12] || ""]);
34420
+ lines[longer.lineIdx] = mergedLine;
34421
+ merged.add(pair.b);
34422
+ }
34423
+ }
34424
+ if (dryRun) {
34425
+ const previewLines = [
34426
+ `\u{1F50D} Dry run \u2014 ${mergePairs.length} merge candidate(s) found:`,
34427
+ ""
34428
+ ];
34429
+ for (const pair of mergePairs) {
34430
+ const a = parsed[pair.a], b2 = parsed[pair.b];
34431
+ const mergedTags = [.../* @__PURE__ */ new Set([...a.tags.split(";"), ...b2.tags.split(";")])].filter(Boolean).join(";");
34432
+ const longer = a.content.length >= b2.content.length ? a : b2;
34433
+ const shorter = a.content.length < b2.content.length ? a : b2;
34434
+ previewLines.push(` \u2500\u2500 Pair: [${a.cat}] ${a.key} \u2194 [${b2.cat}] ${b2.key}`);
34435
+ previewLines.push(` Similarity: ${(pair.similarity * 100).toFixed(0)}%`);
34436
+ previewLines.push(` A tags: ${a.tags || "(none)"}`);
34437
+ previewLines.push(` B tags: ${b2.tags || "(none)"}`);
34438
+ previewLines.push(` \u2192 Merged tags: ${mergedTags || "(none)"}`);
34439
+ previewLines.push(` \u2192 Content winner: "${longer.key}" (${longer.content.length} chars vs ${shorter.content.length})`);
34440
+ previewLines.push(` \u2192 Result content: ${longer.content.slice(0, 120)}${longer.content.length > 120 ? "\u2026" : ""}`);
34441
+ previewLines.push("");
34442
+ }
34443
+ previewLines.push(`Would merge ${merged.size} entries into ${parsed.length - merged.size} entries.`);
34444
+ previewLines.push("Run with dryRun: false to apply.");
34445
+ return {
34446
+ content: [{
34447
+ type: "text",
34448
+ text: previewLines.join("\n")
34449
+ }]
34450
+ };
34451
+ }
34452
+ const kept = parsed.filter((_2, i) => !merged.has(i)).map((p2) => lines[p2.lineIdx]);
34453
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${kept.length}|`);
34454
+ lines.splice(headerIdx + 1, parsed.length, ...kept.map((l) => ` ${l.trim()}`));
34455
+ writeMemory(lines.join("\n"));
34456
+ return {
34457
+ content: [{
34458
+ type: "text",
34459
+ text: `\u2705 Merged ${merged.size} entries into ${parsed.length - merged.size} entries.
34460
+
34461
+ ${mergeActions.join("\n")}`
34462
+ }]
34463
+ };
34464
+ }
34465
+ function runCompressAll(minQuality, dryRun) {
34466
+ const data = readMemory();
34467
+ const lines = data.split("\n");
34468
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
34469
+ if (headerIdx === -1) {
34470
+ return { content: [{ type: "text", text: "No entries in memory." }] };
34471
+ }
34472
+ const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
34473
+ const candidates = [];
34474
+ for (let i = 0; i < entryLines2.length; i++) {
34475
+ const line = entryLines2[i].trim();
34476
+ const parts = parseToonLine(line);
34477
+ if (parts.length < 11) continue;
34478
+ const quality = parseFloat(parts[10]) || 0;
34479
+ const tags = parts[5] || "";
34480
+ const key = parts[2];
34481
+ const content = parts[3] || "";
34482
+ const isCandidate = quality < minQuality || !tags || content.length < 20;
34483
+ if (isCandidate) {
34484
+ candidates.push({ idx: i, line, quality, key });
34485
+ }
34486
+ }
34487
+ if (candidates.length === 0) {
34488
+ return {
34489
+ content: [{
34490
+ type: "text",
34491
+ text: `\u2705 No compression candidates found. All entries have quality >= ${minQuality} or have tags.`
34492
+ }]
34493
+ };
34494
+ }
34495
+ const byCategory = /* @__PURE__ */ new Map();
34496
+ for (const c2 of candidates) {
34497
+ const parts = parseToonLine(c2.line);
34498
+ const cat = parts[1] || "unknown";
34499
+ if (!byCategory.has(cat)) byCategory.set(cat, []);
34500
+ byCategory.get(cat).push(c2);
34501
+ }
34502
+ const sections = [
34503
+ `\u{1F4E6} Compression candidates: ${candidates.length} entries below quality ${minQuality}`,
34504
+ "",
34505
+ "By category:"
34506
+ ];
34507
+ for (const [cat, items] of byCategory) {
34508
+ sections.push(` ${cat}: ${items.length} entries`);
34509
+ for (const item of items.slice(0, 3)) {
34510
+ const parts = parseToonLine(item.line);
34511
+ sections.push(` - ${item.key} (Q: ${item.quality.toFixed(2)}) \u2014 ${(parts[3] || "").slice(0, 60)}`);
34512
+ }
34513
+ if (items.length > 3) {
34514
+ sections.push(` ... and ${items.length - 3} more`);
34515
+ }
34516
+ }
34517
+ if (dryRun) {
34518
+ sections.push("", "\u{1F50D} Dry run \u2014 no changes made. Use dryRun: false to compress.");
34519
+ return { content: [{ type: "text", text: sections.join("\n") }] };
34520
+ }
34521
+ const removeKeys = new Set(candidates.map((c2) => c2.key));
34522
+ const kept = entryLines2.filter((l) => {
34523
+ const parts = parseToonLine(l);
34524
+ return !removeKeys.has(parts[2]);
34525
+ });
34526
+ const match = lines[headerIdx].match(/\[(\d+)\|/);
34527
+ const count = match ? parseInt(match[1]) : 0;
34528
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${kept.length}|`);
34529
+ lines.splice(headerIdx + 1, entryLines2.length, ...kept.map((l) => ` ${l.trim()}`));
34530
+ writeMemory(lines.join("\n"));
34531
+ sections.push("", `\u{1F5D1}\uFE0F Removed ${candidates.length} low-quality entries. ${kept.length} entries remaining.`);
34532
+ sections.push("\u{1F4A1} Use memory_compress to merge related entries before removing them.");
34533
+ return { content: [{ type: "text", text: sections.join("\n") }] };
34534
+ }
34047
34535
  server2.registerTool(
34048
34536
  "memory_remember",
34049
34537
  {
@@ -34078,7 +34566,7 @@ function registerTools(server2) {
34078
34566
  const line = lines[i];
34079
34567
  if (!line.startsWith(" ") || !line.includes("|")) continue;
34080
34568
  if (line.startsWith(" summaries:")) break;
34081
- const parts = line.trim().split("|");
34569
+ const parts = parseToonLine(line);
34082
34570
  if (parts[2] === key) {
34083
34571
  existingIdx = i;
34084
34572
  existingId = parts[0];
@@ -34090,15 +34578,15 @@ function registerTools(server2) {
34090
34578
  const config2 = loadConfig();
34091
34579
  const verbatim = config2.verbatim === true;
34092
34580
  const resolvedTags = tags ? tags : verbatim ? "" : inferTags(content, key, config2.vocab);
34093
- const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : [];
34581
+ const existingParts = existingIdx !== -1 ? parseToonLine(lines[existingIdx]) : [];
34094
34582
  const resolvedLinks = links ? links.split(/[\s;]+/).filter(Boolean).join(" ") : existingParts[9] || "";
34095
- let newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0|${resolvedLinks}|||||${path_scope || ""}|${origin}`;
34583
+ let newEntry = toToonLine([entryId, category, key, content, file2 || "", resolvedTags, date5, resolvedTtl, "0", resolvedLinks, "", "", "", path_scope || "", origin]);
34096
34584
  let action = "Saved";
34097
34585
  let mergeInfo = "";
34098
34586
  const tagsInferred = !tags && resolvedTags ? true : false;
34099
34587
  if (existingIdx !== -1) {
34100
34588
  newEntry = mergeEntries(lines[existingIdx].trim(), newEntry);
34101
- lines[existingIdx] = ` ${newEntry}`;
34589
+ lines[existingIdx] = newEntry;
34102
34590
  action = "Updated";
34103
34591
  mergeInfo = "\nMerge: tags combined, date and links updated";
34104
34592
  } else {
@@ -34106,10 +34594,10 @@ function registerTools(server2) {
34106
34594
  const lastAccessed = "";
34107
34595
  const quality = verbatim ? 0.5 : qualityScore(resolvedTags, resolvedLinks, content, date5, accessed, lastAccessed, origin);
34108
34596
  const confidence = 1;
34109
- newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|${accessed}|${resolvedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}|0|${path_scope || ""}|${origin}|active`;
34597
+ newEntry = toToonLine([entryId, category, key, content, file2 || "", resolvedTags, date5, resolvedTtl, String(accessed), resolvedLinks, quality.toFixed(2), String(confidence), lastAccessed, "0", path_scope || "", origin, "active"]);
34110
34598
  const match = lines[headerIdx].match(/\[(\d+)\|/);
34111
34599
  const count = match ? parseInt(match[1]) : 0;
34112
- lines.splice(headerIdx + 1, 0, ` ${newEntry}`);
34600
+ lines.splice(headerIdx + 1, 0, newEntry);
34113
34601
  lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`);
34114
34602
  }
34115
34603
  writeMemory(lines.join("\n"));
@@ -34199,65 +34687,27 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34199
34687
  server2.registerTool(
34200
34688
  "memory_forget",
34201
34689
  {
34202
- title: "Delete from Memory",
34203
- description: "Delete a memory entry by its key or id.",
34690
+ title: "Forget from Memory",
34691
+ description: "Lifecycle operations for a memory entry: soft (default) marks it obsolete and hides it from recalls, hard permanently removes it, restore brings it back to active, supersede retires it with a typed superseded_by edge to a newer entry.",
34204
34692
  inputSchema: {
34205
- key: external_exports.string().describe("Key or id of the entry to delete"),
34206
- 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.")
34693
+ key: external_exports.string().describe("Key or id of the entry"),
34694
+ action: external_exports.enum(["soft", "hard", "restore", "supersede"]).optional().default("soft").describe("soft: mark obsolete (default). hard: permanently remove. restore: bring an obsolete entry back to active. supersede: mark obsolete with a superseded_by link to new_key."),
34695
+ new_key: external_exports.string().optional().default("").describe("Replacement entry key or id (only used with action: supersede)."),
34696
+ reason: external_exports.string().optional().default("").describe("Optional note appended to the old entry (only used with action: supersede).")
34207
34697
  },
34208
34698
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false }
34209
34699
  },
34210
- async ({ key, hard }) => {
34211
- const data = readMemory();
34212
- const lines = data.split("\n");
34213
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
34214
- if (headerIdx === -1) {
34215
- return { content: [{ type: "text", text: "No entries in memory" }] };
34216
- }
34217
- if (hard) {
34218
- const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
34219
- const filtered = entryLines2.filter((l) => {
34220
- const parts = l.trim().split("|");
34221
- return parts[0] !== key && parts[2] !== key;
34222
- });
34223
- const removed = entryLines2.length - filtered.length;
34224
- const match = lines[headerIdx].match(/\[(\d+)\|/);
34225
- const count = match ? parseInt(match[1]) : 0;
34226
- lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`);
34227
- lines.splice(headerIdx + 1, entryLines2.length, ...filtered.map((l) => ` ${l.trim()}`));
34228
- writeMemory(lines.join("\n"));
34229
- if (removed === 0) {
34230
- return {
34231
- content: [{ type: "text", text: `"${key}" not found in memory.` }]
34232
- };
34233
- }
34234
- return {
34235
- content: [{ type: "text", text: `"${key}" permanently deleted. ${count - removed} entries remaining.` }]
34236
- };
34237
- }
34238
- let found = false;
34239
- for (let i = headerIdx + 1; i < lines.length; i++) {
34240
- const line = lines[i];
34241
- if (!line.startsWith(" ") || !line.includes("|")) continue;
34242
- if (line.startsWith(" summaries:")) break;
34243
- const parts = line.trim().split("|");
34244
- if (parts[0] === key || parts[2] === key) {
34245
- while (parts.length < 17) parts.push("");
34246
- parts[16] = "obsolete";
34247
- lines[i] = ` ${parts.join("|")}`;
34248
- found = true;
34249
- break;
34250
- }
34251
- }
34252
- writeMemory(lines.join("\n"));
34253
- if (!found) {
34254
- return {
34255
- content: [{ type: "text", text: `"${key}" not found in memory.` }]
34256
- };
34700
+ async ({ key, action, new_key, reason }) => {
34701
+ switch (action) {
34702
+ case "hard":
34703
+ return hardDelete(key);
34704
+ case "restore":
34705
+ return restoreEntry(key);
34706
+ case "supersede":
34707
+ return supersedeEntry(key, new_key, reason);
34708
+ default:
34709
+ return softDelete(key);
34257
34710
  }
34258
- return {
34259
- content: [{ type: "text", text: `"${key}" marked as obsolete. Use memory_resolve(key: "${key}") to restore.` }]
34260
- };
34261
34711
  }
34262
34712
  );
34263
34713
  server2.registerTool(
@@ -34272,7 +34722,7 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34272
34722
  const data = readMemory();
34273
34723
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
34274
34724
  const entries = lines.map((l) => {
34275
- const parts = l.trim().split("|");
34725
+ const parts = parseToonLine(l);
34276
34726
  return { category: parts[1] || "unknown", ttl: parts[7] || "", quality: parts[10] || "", origin: parts.length > 15 ? parts[15] || "" : "", status: parts.length > 16 ? parts[16] || "" : "" };
34277
34727
  });
34278
34728
  const byCategory = {};
@@ -34308,7 +34758,7 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34308
34758
  "",
34309
34759
  `Last 5 entries:`,
34310
34760
  ...lines.slice(-5).map((l) => {
34311
- const parts = l.trim().split("|");
34761
+ const parts = parseToonLine(l);
34312
34762
  const ttlInfo = parts[7] ? ` | TTL: ${parts[7]}` : "";
34313
34763
  const qualityInfo = parts[10] ? ` | Q: ${parts[10]}` : "";
34314
34764
  const accessInfo = parts[8] && parseInt(parts[8]) > 0 ? ` | accessed: ${parts[8]}x` : "";
@@ -34319,12 +34769,12 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34319
34769
  "",
34320
34770
  `Most accessed:`,
34321
34771
  ...lines.filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")).map((l) => {
34322
- const parts = l.trim().split("|");
34772
+ const parts = parseToonLine(l);
34323
34773
  return { key: parts[2], accessed: parts.length > 8 ? parseInt(parts[8]) || 0 : 0, quality: parts[10] || "" };
34324
34774
  }).filter((e) => e.accessed > 0).sort((a, b2) => b2.accessed - a.accessed).slice(0, 5).map((e) => ` ${e.key}: ${e.accessed}x (Q: ${e.quality})`)
34325
34775
  ];
34326
34776
  const coldEntries = lines.filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")).map((l) => {
34327
- const p2 = l.trim().split("|");
34777
+ const p2 = parseToonLine(l);
34328
34778
  return {
34329
34779
  key: p2[2],
34330
34780
  cat: p2[1],
@@ -34375,7 +34825,7 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34375
34825
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
34376
34826
  const results = lines.map((line) => {
34377
34827
  const trimmed = line.trim();
34378
- const parts = trimmed.split("|");
34828
+ const parts = parseToonLine(trimmed);
34379
34829
  if (parts.length < 7) return null;
34380
34830
  const [id2, cat, key, content, file2, tags, date5] = parts;
34381
34831
  if (date5 < sinceDate) return null;
@@ -34478,7 +34928,7 @@ ${formatted}` }] };
34478
34928
  if (!match) {
34479
34929
  return { content: [{ type: "text", text: `No summary for "${file2}"` }] };
34480
34930
  }
34481
- const summaryText = match.replace(` ${file2}: `, "");
34931
+ const summaryText = unescField(match.replace(` ${file2}: `, ""));
34482
34932
  return { content: [{ type: "text", text: summaryText }] };
34483
34933
  }
34484
34934
  const lines = data.split("\n");
@@ -34490,9 +34940,9 @@ ${formatted}` }] };
34490
34940
  const summaryLines = lines.slice(summaryIdx + 1).filter((l) => l.includes(":"));
34491
34941
  const existingIdx = summaryLines.findIndex((l) => l.startsWith(` ${file2}:`));
34492
34942
  if (existingIdx !== -1) {
34493
- summaryLines[existingIdx] = ` ${file2}: ${summary}`;
34943
+ summaryLines[existingIdx] = ` ${file2}: ${escField(summary)}`;
34494
34944
  } else {
34495
- summaryLines.push(` ${file2}: ${summary}`);
34945
+ summaryLines.push(` ${file2}: ${escField(summary)}`);
34496
34946
  }
34497
34947
  lines.splice(summaryIdx + 1, lines.length - summaryIdx - 1, ...summaryLines);
34498
34948
  writeMemory(lines.join("\n"));
@@ -34624,23 +35074,23 @@ ${formatted}` }] };
34624
35074
  "memory_consolidate",
34625
35075
  {
34626
35076
  title: "Consolidate Memory",
34627
- description: "Consolidate memory by removing entries with identical content (keeps the first). Deterministic, no LLM.",
34628
- inputSchema: {},
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.",
35078
+ 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."),
35080
+ minQuality: external_exports.number().optional().default(0.3).describe("Entries below this quality score are candidates (only used with mode: low-quality)."),
35081
+ dryRun: external_exports.boolean().optional().default(false).describe("If true, show what would change without writing.")
35082
+ },
34629
35083
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true }
34630
35084
  },
34631
- async () => {
34632
- const result = consolidateEntries();
34633
- if (result.removed === 0) {
34634
- return { content: [{ type: "text", text: `\u2705 Memory already consolidated (${result.kept} entries, 0 duplicates)` }] };
35085
+ async ({ mode, minQuality, dryRun }) => {
35086
+ switch (mode) {
35087
+ case "similar":
35088
+ return runMergeSimilar(dryRun);
35089
+ case "low-quality":
35090
+ return runCompressAll(minQuality, dryRun);
35091
+ default:
35092
+ return runConsolidate();
34635
35093
  }
34636
- return {
34637
- content: [{
34638
- type: "text",
34639
- text: `\u{1F9F9} Consolidated ${result.removed} duplicate entries.
34640
- ${result.kept} active entries remaining.
34641
- Duplicates: ${result.duplicates.join(", ")}`
34642
- }]
34643
- };
34644
35094
  }
34645
35095
  );
34646
35096
  server2.registerTool(
@@ -34937,88 +35387,6 @@ ${files}` : "";
34937
35387
  return { content: [{ type: "text", text: prompt }] };
34938
35388
  }
34939
35389
  );
34940
- server2.registerTool(
34941
- "memory_compress_all",
34942
- {
34943
- title: "Lazy Batch Compression",
34944
- description: "Compress all low-quality entries (no tags, low quality score) in one pass. Deterministic, no LLM \u2014 merges entries with similar content and removes empty/stale ones. Inspired by MemPalace's lazy compression.",
34945
- inputSchema: {
34946
- minQuality: external_exports.number().optional().default(0.3).describe("Entries below this quality score are compression candidates (0-1). Default: 0.3."),
34947
- dryRun: external_exports.boolean().optional().default(false).describe("If true, show what would be compressed without making changes.")
34948
- },
34949
- annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false }
34950
- },
34951
- async ({ minQuality, dryRun }) => {
34952
- const data = readMemory();
34953
- const lines = data.split("\n");
34954
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
34955
- if (headerIdx === -1) {
34956
- return { content: [{ type: "text", text: "No entries in memory." }] };
34957
- }
34958
- const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
34959
- const candidates = [];
34960
- for (let i = 0; i < entryLines2.length; i++) {
34961
- const line = entryLines2[i].trim();
34962
- const parts = line.split("|");
34963
- if (parts.length < 11) continue;
34964
- const quality = parseFloat(parts[10]) || 0;
34965
- const tags = parts[5] || "";
34966
- const key = parts[2];
34967
- const content = parts[3] || "";
34968
- const isCandidate = quality < minQuality || !tags || content.length < 20;
34969
- if (isCandidate) {
34970
- candidates.push({ idx: i, line, quality, key });
34971
- }
34972
- }
34973
- if (candidates.length === 0) {
34974
- return {
34975
- content: [{
34976
- type: "text",
34977
- text: `\u2705 No compression candidates found. All entries have quality >= ${minQuality} or have tags.`
34978
- }]
34979
- };
34980
- }
34981
- const byCategory = /* @__PURE__ */ new Map();
34982
- for (const c2 of candidates) {
34983
- const parts = c2.line.split("|");
34984
- const cat = parts[1] || "unknown";
34985
- if (!byCategory.has(cat)) byCategory.set(cat, []);
34986
- byCategory.get(cat).push(c2);
34987
- }
34988
- const sections = [
34989
- `\u{1F4E6} Compression candidates: ${candidates.length} entries below quality ${minQuality}`,
34990
- "",
34991
- "By category:"
34992
- ];
34993
- for (const [cat, items] of byCategory) {
34994
- sections.push(` ${cat}: ${items.length} entries`);
34995
- for (const item of items.slice(0, 3)) {
34996
- const parts = item.line.split("|");
34997
- sections.push(` - ${item.key} (Q: ${item.quality.toFixed(2)}) \u2014 ${(parts[3] || "").slice(0, 60)}`);
34998
- }
34999
- if (items.length > 3) {
35000
- sections.push(` ... and ${items.length - 3} more`);
35001
- }
35002
- }
35003
- if (dryRun) {
35004
- sections.push("", "\u{1F50D} Dry run \u2014 no changes made. Use dryRun: false to compress.");
35005
- return { content: [{ type: "text", text: sections.join("\n") }] };
35006
- }
35007
- const removeKeys = new Set(candidates.map((c2) => c2.key));
35008
- const kept = entryLines2.filter((l) => {
35009
- const parts = l.trim().split("|");
35010
- return !removeKeys.has(parts[2]);
35011
- });
35012
- const match = lines[headerIdx].match(/\[(\d+)\|/);
35013
- const count = match ? parseInt(match[1]) : 0;
35014
- lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${kept.length}|`);
35015
- lines.splice(headerIdx + 1, entryLines2.length, ...kept.map((l) => ` ${l.trim()}`));
35016
- writeMemory(lines.join("\n"));
35017
- sections.push("", `\u{1F5D1}\uFE0F Removed ${candidates.length} low-quality entries. ${kept.length} entries remaining.`);
35018
- sections.push("\u{1F4A1} Use memory_compress to merge related entries before removing them.");
35019
- return { content: [{ type: "text", text: sections.join("\n") }] };
35020
- }
35021
- );
35022
35390
  server2.registerTool(
35023
35391
  "memory_export_gist",
35024
35392
  {
@@ -35164,7 +35532,7 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
35164
35532
  const tags = e.tags.join(";");
35165
35533
  const links = e.links.join(" ");
35166
35534
  const q2 = qualityScore(tags, links, e.content, e.date, e.accessed, e.lastAccessed);
35167
- return ` ${e.id}|${e.category}|${e.key}|${e.content}|${e.file}|${tags}|${e.date}|${e.ttl}|${e.accessed}|${links}|${q2.toFixed(2)}|1|${e.lastAccessed}`;
35535
+ return toToonLine([e.id, e.category, e.key, e.content, e.file, tags, e.date, e.ttl, String(e.accessed), links, q2.toFixed(2), "1", e.lastAccessed]);
35168
35536
  })
35169
35537
  ];
35170
35538
  safeWrite(MEMORY_FILE, lines.join("\n"));
@@ -35216,7 +35584,7 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
35216
35584
  const data = readFileSync10(OBSERVATIONS_FILE, "utf-8");
35217
35585
  const sessionIds = new Set(recentSessions.map((s2) => s2.id));
35218
35586
  observations = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|")).map((l) => {
35219
- const p2 = l.trim().split("|");
35587
+ const p2 = parseToonLine(l);
35220
35588
  return { ts: p2[0] || "", session: p2[1] || "", agent: p2[2] || "", branch: p2[3] || "", tool: p2[4] || "", file: p2[6] || "", summary: p2[7] || "" };
35221
35589
  }).filter((o) => sessionIds.has(o.session));
35222
35590
  }
@@ -35264,7 +35632,7 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
35264
35632
  const file2 = obs.file || "";
35265
35633
  const tags = `session-merge;${obs.agent};${obs.branch}`;
35266
35634
  const quality = qualityScore(tags, "", content, date5);
35267
- const entry = `${newId}|knowledge|${key}|${content}|${file2}|${tags}|${date5}||0||${quality.toFixed(2)}|1|`;
35635
+ const entry = toToonLine([newId, "knowledge", key, content, file2, tags, date5, "", "0", "", quality.toFixed(2), "1", ""]);
35268
35636
  const lines = data.split("\n");
35269
35637
  let headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35270
35638
  if (headerIdx === -1) {
@@ -35273,7 +35641,7 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
35273
35641
  }
35274
35642
  const match = lines[headerIdx].match(/\[(\d+)\|/);
35275
35643
  const count = match ? parseInt(match[1]) : 0;
35276
- lines.splice(headerIdx + 1, 0, ` ${entry}`);
35644
+ lines.splice(headerIdx + 1, 0, entry);
35277
35645
  lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`);
35278
35646
  writeMemory(lines.join("\n"));
35279
35647
  existingKeys.add(key);
@@ -35286,108 +35654,6 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
35286
35654
  return { content: [{ type: "text", text: sections.join("\n") }] };
35287
35655
  }
35288
35656
  );
35289
- server2.registerTool(
35290
- "memory_merge_similar",
35291
- {
35292
- title: "Merge Similar Entries",
35293
- description: "Find entries with overlapping content (>50% word similarity) and merge them. Deterministic, no LLM. Keeps the longer content and combines tags.",
35294
- inputSchema: {
35295
- dryRun: external_exports.boolean().optional().default(false).describe("If true, show what would be merged without making changes.")
35296
- },
35297
- annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false }
35298
- },
35299
- async ({ dryRun }) => {
35300
- const data = readMemory();
35301
- const entries = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
35302
- if (entries.length < 2) {
35303
- return { content: [{ type: "text", text: "\u2705 Not enough entries to compress." }] };
35304
- }
35305
- const parsed = entries.map((line) => {
35306
- const parts = line.trim().split("|");
35307
- if (parts.length < 7) return null;
35308
- const [id2, cat, key, content, file2, tags, date5, ttl, accessedRaw] = parts;
35309
- const words = new Set(normalize(`${key} ${content} ${tags}`).split(" ").filter(Boolean));
35310
- return { id: id2, cat, key, content, file: file2, tags, date: date5, ttl, accessed: parseInt(accessedRaw) || 0, words, line };
35311
- }).filter(Boolean);
35312
- const mergePairs = [];
35313
- for (let i = 0; i < parsed.length; i++) {
35314
- for (let j3 = i + 1; j3 < parsed.length; j3++) {
35315
- const a = parsed[i], b2 = parsed[j3];
35316
- const intersection2 = new Set([...a.words].filter((w3) => b2.words.has(w3)));
35317
- const union2 = /* @__PURE__ */ new Set([...a.words, ...b2.words]);
35318
- const similarity = union2.size > 0 ? intersection2.size / union2.size : 0;
35319
- if (similarity > 0.5) {
35320
- mergePairs.push({ a: i, b: j3, similarity });
35321
- }
35322
- }
35323
- }
35324
- if (mergePairs.length === 0) {
35325
- return { content: [{ type: "text", text: "\u2705 No similar entries found to merge." }] };
35326
- }
35327
- mergePairs.sort((x, y2) => y2.similarity - x.similarity);
35328
- const merged = /* @__PURE__ */ new Set();
35329
- const mergeActions = [];
35330
- for (const pair of mergePairs) {
35331
- if (merged.has(pair.a) || merged.has(pair.b)) continue;
35332
- const a = parsed[pair.a], b2 = parsed[pair.b];
35333
- const mergedTags = [.../* @__PURE__ */ new Set([...a.tags.split(";"), ...b2.tags.split(";")])].filter(Boolean).join(";");
35334
- const longer = a.content.length >= b2.content.length ? a : b2;
35335
- const shorter = a.content.length < b2.content.length ? a : b2;
35336
- const newContent = longer.content;
35337
- const newDate = a.date > b2.date ? a.date : b2.date;
35338
- const newAccessed = a.accessed + b2.accessed;
35339
- mergeActions.push(` [${longer.cat}] ${longer.key} \u2190 ${shorter.key} (similarity: ${(pair.similarity * 100).toFixed(0)}%)`);
35340
- if (!dryRun) {
35341
- const mergedLine = ` ${longer.id}|${longer.cat}|${longer.key}|${newContent}|${longer.file}|${mergedTags}|${newDate}|${longer.ttl}|${newAccessed}|${longer.line.split("|")[9] || ""}|${longer.line.split("|")[10] || ""}|${longer.line.split("|")[11] || ""}|${longer.line.split("|")[12] || ""}`;
35342
- entries[entries.indexOf(longer.line)] = mergedLine;
35343
- merged.add(pair.b);
35344
- }
35345
- }
35346
- if (dryRun) {
35347
- const previewLines = [
35348
- `\u{1F50D} Dry run \u2014 ${mergePairs.length} merge candidate(s) found:`,
35349
- ""
35350
- ];
35351
- for (const pair of mergePairs) {
35352
- const a = parsed[pair.a], b2 = parsed[pair.b];
35353
- const mergedTags = [.../* @__PURE__ */ new Set([...a.tags.split(";"), ...b2.tags.split(";")])].filter(Boolean).join(";");
35354
- const longer = a.content.length >= b2.content.length ? a : b2;
35355
- const shorter = a.content.length < b2.content.length ? a : b2;
35356
- previewLines.push(` \u2500\u2500 Pair: [${a.cat}] ${a.key} \u2194 [${b2.cat}] ${b2.key}`);
35357
- previewLines.push(` Similarity: ${(pair.similarity * 100).toFixed(0)}%`);
35358
- previewLines.push(` A tags: ${a.tags || "(none)"}`);
35359
- previewLines.push(` B tags: ${b2.tags || "(none)"}`);
35360
- previewLines.push(` \u2192 Merged tags: ${mergedTags || "(none)"}`);
35361
- previewLines.push(` \u2192 Content winner: "${longer.key}" (${longer.content.length} chars vs ${shorter.content.length})`);
35362
- previewLines.push(` \u2192 Result content: ${longer.content.slice(0, 120)}${longer.content.length > 120 ? "\u2026" : ""}`);
35363
- previewLines.push("");
35364
- }
35365
- previewLines.push(`Would merge ${merged.size} entries into ${entries.length - merged.size} entries.`);
35366
- previewLines.push("Run with dryRun: false to apply.");
35367
- return {
35368
- content: [{
35369
- type: "text",
35370
- text: previewLines.join("\n")
35371
- }]
35372
- };
35373
- }
35374
- const newLines = entries.filter((_2, i) => !merged.has(i));
35375
- const headerIdx = newLines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35376
- if (headerIdx !== -1) {
35377
- const count = newLines.filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")).length;
35378
- newLines[headerIdx] = newLines[headerIdx].replace(/\[\d+\|/, `[${count}|`);
35379
- }
35380
- writeMemory(newLines.join("\n"));
35381
- return {
35382
- content: [{
35383
- type: "text",
35384
- text: `\u2705 Merged ${merged.size} entries into ${entries.length - merged.size} entries.
35385
-
35386
- ${mergeActions.join("\n")}`
35387
- }]
35388
- };
35389
- }
35390
- );
35391
35657
  server2.registerTool(
35392
35658
  "memory_graph_path",
35393
35659
  {
@@ -35493,7 +35759,7 @@ Branch: ${branch}${fileList}`;
35493
35759
  const line = lines[i];
35494
35760
  if (!line.startsWith(" ") || !line.includes("|")) continue;
35495
35761
  if (line.startsWith(" summaries:")) break;
35496
- const parts = line.trim().split("|");
35762
+ const parts = parseToonLine(line);
35497
35763
  if (parts[2] === key) {
35498
35764
  existingIdx = i;
35499
35765
  existingId = parts[0];
@@ -35501,13 +35767,13 @@ Branch: ${branch}${fileList}`;
35501
35767
  }
35502
35768
  }
35503
35769
  if (existingIdx !== -1) {
35504
- const parts = lines[existingIdx].trim().split("|");
35770
+ const parts = parseToonLine(lines[existingIdx]);
35505
35771
  parts[3] = content;
35506
35772
  parts[6] = date5;
35507
35773
  parts[7] = ttl7d;
35508
35774
  while (parts.length < 14) parts.push("");
35509
35775
  parts[13] = "0";
35510
- lines[existingIdx] = ` ${parts.join("|")}`;
35776
+ lines[existingIdx] = toToonLine(parts);
35511
35777
  writeMemory(lines.join("\n"));
35512
35778
  return {
35513
35779
  content: [{ type: "text", text: `\u{1F4DD} Checkpoint updated: ${key}
@@ -35518,10 +35784,10 @@ ${note}` : ""}` }]
35518
35784
  }
35519
35785
  const newId = `cp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
35520
35786
  const quality = qualityScore("checkpoint", "", content, date5);
35521
- const newEntry = `${newId}|knowledge|${key}|${content}||checkpoint|${date5}|${ttl7d}|0||${quality.toFixed(2)}|1|${now.toISOString()}|0`;
35787
+ const newEntry = toToonLine([newId, "knowledge", key, content, "", "checkpoint", date5, ttl7d, "0", "", quality.toFixed(2), "1", now.toISOString(), "0"]);
35522
35788
  const match = lines[headerIdx].match(/\[(\d+)\|/);
35523
35789
  const count = match ? parseInt(match[1]) : 0;
35524
- lines.splice(headerIdx + 1, 0, ` ${newEntry}`);
35790
+ lines.splice(headerIdx + 1, 0, newEntry);
35525
35791
  lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`);
35526
35792
  writeMemory(lines.join("\n"));
35527
35793
  return {
@@ -35559,11 +35825,11 @@ ${note}` : ""}`
35559
35825
  const line = lines[i];
35560
35826
  if (!line.startsWith(" ") || !line.includes("|")) continue;
35561
35827
  if (line.startsWith(" summaries:")) break;
35562
- const parts = line.trim().split("|");
35828
+ const parts = parseToonLine(line);
35563
35829
  if (parts[0] === key || parts[2] === key) {
35564
35830
  while (parts.length < 14) parts.push("");
35565
35831
  parts[13] = String(clampedPriority);
35566
- lines[i] = ` ${parts.join("|")}`;
35832
+ lines[i] = toToonLine(parts);
35567
35833
  found = true;
35568
35834
  break;
35569
35835
  }
@@ -35597,11 +35863,11 @@ ${note}` : ""}`
35597
35863
  const line = lines[i];
35598
35864
  if (!line.startsWith(" ") || !line.includes("|")) continue;
35599
35865
  if (line.startsWith(" summaries:")) break;
35600
- const parts = line.trim().split("|");
35866
+ const parts = parseToonLine(line);
35601
35867
  if (parts[0] === key || parts[2] === key) {
35602
35868
  if (parts.length > 13) {
35603
35869
  parts[13] = "0";
35604
- lines[i] = ` ${parts.join("|")}`;
35870
+ lines[i] = toToonLine(parts);
35605
35871
  }
35606
35872
  found = true;
35607
35873
  break;
@@ -35724,7 +35990,7 @@ ${formatted}` }]
35724
35990
  const line = lines[i];
35725
35991
  if (!line.startsWith(" ") || !line.includes("|")) continue;
35726
35992
  if (line.startsWith(" summaries:")) break;
35727
- const parts = line.trim().split("|");
35993
+ const parts = parseToonLine(line);
35728
35994
  const entryId = parts[0];
35729
35995
  const entryKey = parts[2];
35730
35996
  if (!targetSet.has(entryId) && !targetSet.has(entryKey)) continue;
@@ -35738,7 +36004,7 @@ ${formatted}` }]
35738
36004
  newTags = [...tagsToApply];
35739
36005
  }
35740
36006
  parts[5] = newTags.join(";");
35741
- lines[i] = ` ${parts.join("|")}`;
36007
+ lines[i] = toToonLine(parts);
35742
36008
  modified++;
35743
36009
  modifiedKeys.push(entryKey);
35744
36010
  }
@@ -35757,187 +36023,6 @@ ${formatted}` }]
35757
36023
  };
35758
36024
  }
35759
36025
  );
35760
- server2.registerTool(
35761
- "memory_resolve",
35762
- {
35763
- title: "Resolve Entry",
35764
- description: "Restore an obsolete entry back to active status, or mark an entry as resolved. Reverses soft-delete.",
35765
- inputSchema: {
35766
- key: external_exports.string().describe("Key or id of the entry to resolve/restore")
35767
- },
35768
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
35769
- },
35770
- async ({ key }) => {
35771
- const data = readMemory();
35772
- const lines = data.split("\n");
35773
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35774
- if (headerIdx === -1) {
35775
- return { content: [{ type: "text", text: "No entries in memory" }] };
35776
- }
35777
- let found = false;
35778
- let wasObsolete = false;
35779
- for (let i = headerIdx + 1; i < lines.length; i++) {
35780
- const line = lines[i];
35781
- if (!line.startsWith(" ") || !line.includes("|")) continue;
35782
- if (line.startsWith(" summaries:")) break;
35783
- const parts = line.trim().split("|");
35784
- if (parts[0] === key || parts[2] === key) {
35785
- while (parts.length < 17) parts.push("");
35786
- wasObsolete = parts[16] === "obsolete";
35787
- parts[16] = "active";
35788
- lines[i] = ` ${parts.join("|")}`;
35789
- found = true;
35790
- break;
35791
- }
35792
- }
35793
- if (!found) {
35794
- return { content: [{ type: "text", text: `"${key}" not found in memory.` }] };
35795
- }
35796
- writeMemory(lines.join("\n"));
35797
- const msg = wasObsolete ? `"${key}" restored to active status.` : `"${key}" marked as resolved.`;
35798
- return { content: [{ type: "text", text: `\u2705 ${msg}` }] };
35799
- }
35800
- );
35801
- server2.registerTool(
35802
- "memory_suppress",
35803
- {
35804
- title: "Suppress Entry",
35805
- description: "Suppress a memory entry so it's hidden from normal recalls. Sets status to 'obsolete'. Use memory_resolve to restore.",
35806
- inputSchema: {
35807
- key: external_exports.string().describe("Key or id of the entry to suppress")
35808
- },
35809
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
35810
- },
35811
- async ({ key }) => {
35812
- const data = readMemory();
35813
- const lines = data.split("\n");
35814
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35815
- if (headerIdx === -1) {
35816
- return { content: [{ type: "text", text: "No entries in memory" }] };
35817
- }
35818
- let found = false;
35819
- for (let i = headerIdx + 1; i < lines.length; i++) {
35820
- const line = lines[i];
35821
- if (!line.startsWith(" ") || !line.includes("|")) continue;
35822
- if (line.startsWith(" summaries:")) break;
35823
- const parts = line.trim().split("|");
35824
- if (parts[0] === key || parts[2] === key) {
35825
- while (parts.length < 17) parts.push("");
35826
- parts[16] = "obsolete";
35827
- lines[i] = ` ${parts.join("|")}`;
35828
- found = true;
35829
- break;
35830
- }
35831
- }
35832
- if (!found) {
35833
- return { content: [{ type: "text", text: `"${key}" not found in memory.` }] };
35834
- }
35835
- writeMemory(lines.join("\n"));
35836
- return { content: [{ type: "text", text: `"${key}" suppressed. Use memory_resolve(key: "${key}") to restore.` }] };
35837
- }
35838
- );
35839
- server2.registerTool(
35840
- "memory_supersede",
35841
- {
35842
- title: "Supersede Entry",
35843
- description: "Mark an entry as superseded (obsolete) by a newer entry, using typed graph edges (superseded_by / supersedes). The old entry stays in the file for history but is hidden from normal recalls. Use memory_recall(as_of: date) to see what was true at a point in time.",
35844
- inputSchema: {
35845
- old_key: external_exports.string().describe("Key or id of the entry being superseded"),
35846
- new_key: external_exports.string().optional().default("").describe("Key or id of the replacement entry (can be empty if the topic is simply retired)."),
35847
- reason: external_exports.string().optional().default("").describe("Optional note explaining why it was superseded. Appended to the old entry's content.")
35848
- },
35849
- annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true }
35850
- },
35851
- async ({ old_key, new_key, reason }) => {
35852
- const data = readMemory();
35853
- const lines = data.split("\n");
35854
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35855
- if (headerIdx === -1) {
35856
- return { content: [{ type: "text", text: "No entries in memory" }] };
35857
- }
35858
- const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
35859
- let oldIdx = -1;
35860
- for (let i = headerIdx + 1; i < lines.length; i++) {
35861
- const line = lines[i];
35862
- if (!line.startsWith(" ") || !line.includes("|")) continue;
35863
- if (line.startsWith(" summaries:")) break;
35864
- const parts = line.trim().split("|");
35865
- if (parts[0] === old_key || parts[2] === old_key) {
35866
- oldIdx = i;
35867
- break;
35868
- }
35869
- }
35870
- if (oldIdx === -1) {
35871
- return { content: [{ type: "text", text: `\u274C "${old_key}" not found in memory.` }] };
35872
- }
35873
- let newIdx = -1;
35874
- let newKey = "";
35875
- if (new_key) {
35876
- for (let i = headerIdx + 1; i < lines.length; i++) {
35877
- const line = lines[i];
35878
- if (!line.startsWith(" ") || !line.includes("|")) continue;
35879
- if (line.startsWith(" summaries:")) break;
35880
- const parts = line.trim().split("|");
35881
- if (parts[0] === new_key || parts[2] === new_key) {
35882
- newIdx = i;
35883
- newKey = parts[2];
35884
- break;
35885
- }
35886
- }
35887
- if (newIdx === -1) {
35888
- return { content: [{ type: "text", text: `\u274C Replacement "${new_key}" not found in memory.` }] };
35889
- }
35890
- }
35891
- const oldParts = lines[oldIdx].trim().split("|");
35892
- const oldKey = oldParts[2];
35893
- const tags = (oldParts[5] || "").split(";").map((t) => t.trim()).filter(Boolean);
35894
- if (!tags.includes("superseded")) tags.push("superseded");
35895
- const links = (oldParts[9] || "").split(/[\s;]+/).filter(Boolean);
35896
- if (newKey) {
35897
- const edge = formatLink("superseded_by", newKey);
35898
- if (!links.includes(edge)) links.push(edge);
35899
- }
35900
- let content = oldParts[3] || "";
35901
- if (reason && !content.includes(reason)) {
35902
- const flat = reason.replace(/[\r\n]+/g, " ").trim();
35903
- content = `${content} \u23F3 Superseded (${today}): ${flat}`;
35904
- }
35905
- while (oldParts.length < 18) oldParts.push("");
35906
- oldParts[3] = content;
35907
- oldParts[5] = tags.join(";");
35908
- oldParts[9] = links.join(" ");
35909
- oldParts[16] = "obsolete";
35910
- oldParts[17] = today;
35911
- lines[oldIdx] = ` ${oldParts.join("|")}`;
35912
- if (newIdx !== -1) {
35913
- const newParts = lines[newIdx].trim().split("|");
35914
- const newLinks = (newParts[9] || "").split(/[\s;]+/).filter(Boolean);
35915
- const edge = formatLink("supersedes", oldKey);
35916
- if (!newLinks.includes(edge)) {
35917
- newLinks.push(edge);
35918
- newParts[9] = newLinks.join(" ");
35919
- lines[newIdx] = ` ${newParts.join("|")}`;
35920
- }
35921
- }
35922
- writeMemory(lines.join("\n"));
35923
- const target = newKey ? ` by "${newKey}"` : " (retired)";
35924
- return {
35925
- content: [{
35926
- type: "text",
35927
- text: `\u23F3 "${oldKey}" superseded${target} on ${today}.
35928
-
35929
- Old entry is now status=obsolete (hidden from normal recalls).
35930
- \xB7 link: superseded_by${newKey ? `:${newKey}` : ""}
35931
- \xB7 tag: superseded
35932
-
35933
- To see what was true before: memory_recall(query: "${oldKey}", as_of: "${today}")
35934
- To restore: memory_resolve(key: "${oldKey}")${reason ? `
35935
-
35936
- Reason: ${reason}` : ""}`
35937
- }]
35938
- };
35939
- }
35940
- );
35941
36026
  server2.registerTool(
35942
36027
  "memory_reflect",
35943
36028
  {
@@ -36055,14 +36140,14 @@ Reason: ${reason}` : ""}`
36055
36140
  }
36056
36141
  const pending = entries.filter((e) => e.status === "active" && (e.tags.includes("superseded") || typedLinks(e.links).some((l) => l.type === "superseded_by")));
36057
36142
  if (pending.length > 0) {
36058
- sections.push("", "\u{1F50E} Superseded tag but still active (fix with memory_supersede):");
36143
+ sections.push("", "\u{1F50E} Superseded tag but still active (fix with memory_forget action: 'supersede'):");
36059
36144
  for (const e of pending.slice(0, cap)) {
36060
36145
  sections.push(` [${e.category}] ${e.key}`);
36061
36146
  }
36062
36147
  }
36063
36148
  const drafts = entries.filter((e) => e.status === "draft");
36064
36149
  if (drafts.length > 0) {
36065
- sections.push("", "\u{1F4DD} Drafts pending review (promote with memory_promote / memory_resolve):");
36150
+ sections.push("", "\u{1F4DD} Drafts pending review (promote with memory_promote / memory_forget action: 'restore'):");
36066
36151
  for (const e of drafts.slice(0, cap)) {
36067
36152
  sections.push(` [${e.category}] ${e.key} \u2014 ${e.content.slice(0, 70)}`);
36068
36153
  }
@@ -36167,8 +36252,8 @@ Run with dryRun: false to promote.`
36167
36252
  if (status === "draft") tags.push("draft");
36168
36253
  const content = (o.summary || "").slice(0, 500);
36169
36254
  const quality = qualityScore(tags.join(";"), "", content, date5);
36170
- const entry = `${newId}|knowledge|${key}|${content}|${o.file || ""}|${tags.join(";")}|${date5}||0||${quality.toFixed(2)}|${conf.toFixed(2)}|${date5}|0||inferred|${status}`;
36171
- lines.splice(headerIdx + 1, 0, ` ${entry}`);
36255
+ const entry = toToonLine([newId, "knowledge", key, content, o.file || "", tags.join(";"), date5, "", "0", "", quality.toFixed(2), conf.toFixed(2), date5, "0", "", "inferred", status]);
36256
+ lines.splice(headerIdx + 1, 0, entry);
36172
36257
  count++;
36173
36258
  existingKeys.add(key);
36174
36259
  if (status === "draft") drafted++;
@@ -36184,7 +36269,7 @@ Run with dryRun: false to promote.`
36184
36269
 
36185
36270
  ${actions.join("\n")}
36186
36271
 
36187
- Drafts are hidden from recalls until promoted \u2014 use memory_resolve(key) to activate, or review with memory_reflect.`
36272
+ Drafts are hidden from recalls until promoted \u2014 use memory_forget(key, action: 'restore') to activate, or review with memory_reflect.`
36188
36273
  }]
36189
36274
  };
36190
36275
  }
@@ -46827,6 +46912,7 @@ function Lk(e) {
46827
46912
  }
46828
46913
 
46829
46914
  // src/mcp/resources.ts
46915
+ init_utils();
46830
46916
  init_quality();
46831
46917
 
46832
46918
  // src/viewer/data.ts
@@ -47808,7 +47894,7 @@ function registerResources(server2) {
47808
47894
  const data = readMemory();
47809
47895
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
47810
47896
  const entries = lines.map((l) => {
47811
- const parts = l.trim().split("|");
47897
+ const parts = parseToonLine(l);
47812
47898
  return { category: parts[1] || "unknown", ttl: parts[7] || "" };
47813
47899
  });
47814
47900
  const byCategory = {};
@@ -47853,7 +47939,7 @@ function registerResources(server2) {
47853
47939
 
47854
47940
  // src/mcp/server.ts
47855
47941
  var server = new McpServer(
47856
- { name: "toon-memory", version: "3.7.0" },
47942
+ { name: "toon-memory", version: "4.1.0" },
47857
47943
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true }, experimental: { "io.modelcontextprotocol/ui": {} } } }
47858
47944
  );
47859
47945
  var s = server.server;
@@ -47865,7 +47951,7 @@ s.setRequestHandler(InitializeRequestSchema, async (request) => {
47865
47951
  return {
47866
47952
  protocolVersion,
47867
47953
  capabilities: s.getCapabilities(),
47868
- serverInfo: { name: "toon-memory", version: "3.7.0" },
47954
+ serverInfo: { name: "toon-memory", version: "4.1.0" },
47869
47955
  ...s._instructions && { instructions: s._instructions }
47870
47956
  };
47871
47957
  });