toon-memory 3.6.1 → 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
  });
@@ -22158,10 +22217,26 @@ var init_fuzzy = __esm({
22158
22217
  });
22159
22218
 
22160
22219
  // src/lib/graph.ts
22220
+ function parseLinkToken(token) {
22221
+ const idx = token.lastIndexOf(":");
22222
+ if (idx === -1) return { type: DEFAULT_EDGE_TYPE, key: token };
22223
+ const type = token.slice(0, idx);
22224
+ const key = token.slice(idx + 1);
22225
+ return { type: type || DEFAULT_EDGE_TYPE, key: key || token };
22226
+ }
22227
+ function linkKey(token) {
22228
+ return parseLinkToken(token).key;
22229
+ }
22230
+ function formatLink(type, key) {
22231
+ return type && type !== DEFAULT_EDGE_TYPE ? `${type}:${key}` : key;
22232
+ }
22233
+ function typedLinks(links) {
22234
+ return links.map(parseLinkToken);
22235
+ }
22161
22236
  function parseEntries(data) {
22162
22237
  const out = [];
22163
22238
  for (const line of entryLines(data)) {
22164
- const parts = line.trim().split("|");
22239
+ const parts = parseToonLine(line);
22165
22240
  if (parts.length < 7) continue;
22166
22241
  const [id2, category, key, content, file2, tags, date5, ttl, accessedRaw, linksRaw] = parts;
22167
22242
  out.push({
@@ -22179,11 +22254,25 @@ function parseEntries(data) {
22179
22254
  priority: parts.length > 13 ? parseInt(parts[13]) || 0 : 0,
22180
22255
  path_scope: parts.length > 14 ? parts[14] || "" : "",
22181
22256
  origin: parts.length > 15 && parts[15] ? parts[15] : "agent",
22182
- status: parts.length > 16 && parts[16] ? parts[16] : "active"
22257
+ status: parts.length > 16 && parts[16] ? parts[16] : "active",
22258
+ supersededOn: parts.length > 17 ? parts[17] || "" : ""
22183
22259
  });
22184
22260
  }
22185
22261
  return out;
22186
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
+ }
22187
22276
  function buildGraph(entries) {
22188
22277
  const byKey = /* @__PURE__ */ new Map();
22189
22278
  for (const e of entries) {
@@ -22199,7 +22288,7 @@ function buildGraph(entries) {
22199
22288
  adj.get(b2).add(a);
22200
22289
  };
22201
22290
  for (const e of entries) {
22202
- for (const l of e.links) link(e.key, l);
22291
+ for (const l of e.links) link(e.key, linkKey(l));
22203
22292
  const refs = e.content.match(/\[\[([\w-]+)\]\]/g) || [];
22204
22293
  for (const r2 of refs) link(e.key, r2.slice(2, -2));
22205
22294
  }
@@ -22219,8 +22308,88 @@ function buildGraph(entries) {
22219
22308
  }
22220
22309
  const adjacency = /* @__PURE__ */ new Map();
22221
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
+ }
22222
22352
  return { adjacency, byKey };
22223
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
+ }
22376
+ function rrfFuse(rankers, k3 = 60) {
22377
+ const out = /* @__PURE__ */ new Map();
22378
+ for (const ranker of rankers) {
22379
+ for (const [key, rank] of ranker) {
22380
+ out.set(key, (out.get(key) || 0) + 1 / (k3 + rank));
22381
+ }
22382
+ }
22383
+ return out;
22384
+ }
22385
+ function rrfK(candidateCount) {
22386
+ return Math.max(3, Math.min(60, Math.round(Math.sqrt(candidateCount))));
22387
+ }
22388
+ function rankBy(score) {
22389
+ const out = /* @__PURE__ */ new Map();
22390
+ [...score.entries()].sort((a, b2) => b2[1] - a[1]).forEach(([key], i) => out.set(key, i));
22391
+ return out;
22392
+ }
22224
22393
  function bm25Scores(entries, query) {
22225
22394
  const N = entries.length;
22226
22395
  const scores = /* @__PURE__ */ new Map();
@@ -22275,13 +22444,17 @@ function graphRecallDetailed(data, query, opts = {}) {
22275
22444
  const bm25 = bm25Scores(entries, query);
22276
22445
  const cent = centrality(adjacency);
22277
22446
  const seedKeys = /* @__PURE__ */ new Set();
22447
+ const asOf = opts.asOf || "";
22278
22448
  for (const e of entries) {
22279
- if (e.status === "obsolete") continue;
22449
+ if (e.status === "obsolete" || e.status === "draft") {
22450
+ if (!(asOf && e.status === "obsolete" && e.supersededOn && e.supersededOn > asOf)) continue;
22451
+ }
22452
+ if (asOf && e.date && e.date > asOf) continue;
22280
22453
  if (category && e.category !== category) continue;
22281
22454
  if (tagsFilter.length > 0 && !tagsFilter.every((t) => e.tags.includes(t))) continue;
22282
22455
  if (from_date && e.date < from_date) continue;
22283
22456
  if (to_date && e.date > to_date) continue;
22284
- if (e.ttl && isExpiredLocal(e.ttl)) continue;
22457
+ if (e.ttl && isExpiredLocal(e.ttl, opts.today)) continue;
22285
22458
  if (opts.path_scope && e.path_scope && !globMatch(opts.path_scope, e.path_scope)) continue;
22286
22459
  const text = normalize(
22287
22460
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
@@ -22294,12 +22467,19 @@ function graphRecallDetailed(data, query, opts = {}) {
22294
22467
  }
22295
22468
  let selected;
22296
22469
  const scored = [];
22470
+ const visibleEntries = entries.filter((e) => {
22471
+ if (e.status === "obsolete" || e.status === "draft") {
22472
+ return !!(asOf && e.status === "obsolete" && e.supersededOn && e.supersededOn > asOf);
22473
+ }
22474
+ return !(asOf && e.date && e.date > asOf);
22475
+ });
22476
+ const isVisible = new Set(visibleEntries.map((e) => e.key));
22297
22477
  if (seedKeys.size === 0) {
22298
22478
  scored.push(
22299
- ...[...entries].filter((e) => e.status !== "obsolete").sort((a, b2) => {
22479
+ ...visibleEntries.sort((a, b2) => {
22300
22480
  if (a.priority !== b2.priority) return b2.priority - a.priority;
22301
- return importance(b2) - importance(a);
22302
- }).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) }))
22303
22483
  );
22304
22484
  } else {
22305
22485
  const best = /* @__PURE__ */ new Map();
@@ -22311,16 +22491,21 @@ function graphRecallDetailed(data, query, opts = {}) {
22311
22491
  best.set(key, dist);
22312
22492
  if (dist >= hops) continue;
22313
22493
  for (const nb2 of adjacency.get(key) || []) {
22494
+ if (!isVisible.has(nb2)) continue;
22314
22495
  queue.push({ key: nb2, dist: dist + 1 });
22315
22496
  }
22316
22497
  }
22498
+ const sub = (m3) => new Map([...m3].filter(([k3]) => isVisible.has(k3)));
22499
+ const bm25Rank = rankBy(sub(bm25));
22500
+ const centRank = rankBy(sub(cent));
22501
+ const fused = opts.rrf ? rrfFuse([bm25Rank, bm25Rank, bm25Rank, centRank], rrfK(bm25Rank.size)) : null;
22317
22502
  scored.push(
22318
22503
  ...[...best.keys()].map((k3) => {
22319
22504
  const e = byKey.get(k3);
22320
22505
  const dist = best.get(k3);
22321
22506
  const decay = Math.pow(DECAY, dist);
22322
- let s2 = (bm25.get(k3) || 0) + W_CENT * cent.get(k3) + W_IMP * importance(e);
22323
- if (seedKeys.has(k3)) s2 += SEED_BONUS;
22507
+ let s2 = fused ? fused.get(k3) || 0 : (bm25.get(k3) || 0) + W_CENT * (cent.get(k3) || 0) + W_IMP * importance(e, opts.today);
22508
+ if (!fused && seedKeys.has(k3)) s2 += SEED_BONUS;
22324
22509
  if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
22325
22510
  const entryFile = e.file.split(":")[0];
22326
22511
  if (opts.sessionFiles.some((f3) => f3 === entryFile)) {
@@ -22336,7 +22521,7 @@ function graphRecallDetailed(data, query, opts = {}) {
22336
22521
  );
22337
22522
  }
22338
22523
  selected = scored.map((x) => x.e);
22339
- const pinnedKeys = new Set(entries.filter((e) => e.priority > 0 && e.status !== "obsolete").map((e) => e.key));
22524
+ const pinnedKeys = new Set(visibleEntries.filter((e) => e.priority > 0).map((e) => e.key));
22340
22525
  const inResult = new Set(selected.map((e) => e.key));
22341
22526
  const toInject = [...pinnedKeys].filter((k3) => !inResult.has(k3) && byKey.has(k3)).map((k3) => byKey.get(k3)).sort((a, b2) => b2.priority - a.priority);
22342
22527
  for (const e of toInject) {
@@ -22390,9 +22575,10 @@ function renderCompact(entries, opts = {}) {
22390
22575
  const originInfo = e.origin !== "agent" ? ` \xB7 origin: ${e.origin}` : "";
22391
22576
  const scopeInfo = e.path_scope ? ` \xB7 scope: ${e.path_scope}` : "";
22392
22577
  const statusInfo = e.status !== "active" ? ` \xB7 status: ${e.status}` : "";
22578
+ const supersededInfo = e.supersededOn ? ` \xB7 superseded: ${e.supersededOn}` : "";
22393
22579
  return `[${n}] ${e.category}/${e.key}${pin} (${e.id})
22394
22580
  ${e.content}
22395
- File: ${e.file} | Tags: ${e.tags.join(";")} | Date: ${e.date}${ttlInfo}${accessInfo}${lastAccess}${originInfo}${scopeInfo}${statusInfo}${links}`;
22581
+ File: ${e.file} | Tags: ${e.tags.join(";")} | Date: ${e.date}${ttlInfo}${accessInfo}${lastAccess}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}${links}`;
22396
22582
  }
22397
22583
  let body = e.content;
22398
22584
  if (!isSeed && e.content.length > snippetLen) {
@@ -22409,13 +22595,14 @@ function renderCompact(entries, opts = {}) {
22409
22595
  ${body}${tags}${edges}`;
22410
22596
  }).join("\n\n");
22411
22597
  }
22412
- var entryLines, W_CENT, W_IMP, SEED_BONUS, DECAY;
22598
+ var DEFAULT_EDGE_TYPE, entryLines, W_CENT, W_IMP, SEED_BONUS, DECAY;
22413
22599
  var init_graph = __esm({
22414
22600
  "src/lib/graph.ts"() {
22415
22601
  "use strict";
22416
22602
  init_utils();
22417
22603
  init_synonyms();
22418
22604
  init_fuzzy();
22605
+ DEFAULT_EDGE_TYPE = "related";
22419
22606
  entryLines = (data) => data.split("\n").filter(
22420
22607
  (l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")
22421
22608
  );
@@ -22479,8 +22666,8 @@ function qualityScore(tags, links, content, date5, accessed = 0, lastAccessed =
22479
22666
  return Math.max(0, Math.min(1, score));
22480
22667
  }
22481
22668
  function mergeEntries(existingLine, newLine) {
22482
- const ep2 = existingLine.trim().split("|");
22483
- const np2 = newLine.trim().split("|");
22669
+ const ep2 = parseToonLine(existingLine);
22670
+ const np2 = parseToonLine(newLine);
22484
22671
  if (ep2.length < 7 || np2.length < 7) return newLine;
22485
22672
  const id2 = ep2[0];
22486
22673
  const category = np2[1] || ep2[1];
@@ -22522,7 +22709,8 @@ function mergeEntries(existingLine, newLine) {
22522
22709
  const existingStatus = ep2.length > 16 ? ep2[16] || "" : "";
22523
22710
  const newStatus = np2.length > 16 ? np2[16] || "" : "";
22524
22711
  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}`;
22712
+ const existingSupersededOn = ep2.length > 17 ? ep2[17] || "" : "";
22713
+ return toToonLine([id2, category, key, content, file2, mergedTags, date5, ttl, String(accessed), mergedLinks, quality.toFixed(2), String(confidence), lastAccessed, String(priority), path_scope, origin, status, existingSupersededOn]);
22526
22714
  }
22527
22715
  function generateSmartRecall(data, intent, opts = {}) {
22528
22716
  const entries = parseEntries(data);
@@ -22535,11 +22723,16 @@ function generateSmartRecall(data, intent, opts = {}) {
22535
22723
  const mtimes = opts.fileMtimes;
22536
22724
  const qTokens = tokenize(intent);
22537
22725
  const expandedTokens = expandSynonyms(qTokens);
22538
- const scored = entries.filter((e) => {
22726
+ const eligible = entries.filter((e) => {
22539
22727
  if (category && e.category !== category) return false;
22540
- if (e.ttl && isExpiredLocal(e.ttl)) return false;
22728
+ if (e.ttl && isExpiredLocal(e.ttl, opts.today)) return false;
22729
+ if (e.status === "obsolete" || e.status === "draft") return false;
22541
22730
  return true;
22542
- }).map((e) => {
22731
+ });
22732
+ const bm25Rank = rankBy(new Map([...bm25].filter(([k3]) => eligible.some((e) => e.key === k3))));
22733
+ const centRank = rankBy(new Map([...cent].filter(([k3]) => eligible.some((e) => e.key === k3))));
22734
+ const fused = opts.rrf ? rrfFuse([bm25Rank, bm25Rank, bm25Rank, centRank], rrfK(bm25Rank.size)) : null;
22735
+ const scored = eligible.map((e) => {
22543
22736
  const text = normalize(
22544
22737
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
22545
22738
  );
@@ -22549,7 +22742,7 @@ function generateSmartRecall(data, intent, opts = {}) {
22549
22742
  const matchesQuery = exactMatch || fuzzy;
22550
22743
  const bm25Score = bm25.get(e.key) || 0;
22551
22744
  const centScore = cent.get(e.key) || 0;
22552
- const impScore = importance(e);
22745
+ const impScore = importance(e, opts.today);
22553
22746
  let drift = 0;
22554
22747
  if (mtimes && e.file) {
22555
22748
  const filePath = e.file.split(":")[0];
@@ -22563,22 +22756,27 @@ function generateSmartRecall(data, intent, opts = {}) {
22563
22756
  sessionBias = 0.15;
22564
22757
  }
22565
22758
  }
22566
- const combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias;
22759
+ let combined;
22760
+ if (opts.rrf) {
22761
+ combined = (fused?.get(e.key) ?? 0) - drift + sessionBias;
22762
+ } else {
22763
+ combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias;
22764
+ }
22567
22765
  return { entry: e, score: combined, matchesQuery, priority: e.priority };
22568
22766
  }).filter((x) => x.score > 0 || x.matchesQuery).sort((a, b2) => {
22569
22767
  if (a.priority !== b2.priority) return b2.priority - a.priority;
22570
22768
  return b2.score - a.score;
22571
22769
  }).slice(0, limit);
22572
- const pinnedKeys = new Set(entries.filter((e) => e.priority > 0).map((e) => e.key));
22770
+ const pinnedKeys = new Set(eligible.filter((e) => e.priority > 0).map((e) => e.key));
22573
22771
  const inResult = new Set(scored.map((x) => x.entry.key));
22574
- const toInject = [...pinnedKeys].filter((k3) => !inResult.has(k3)).map((k3) => entries.find((en2) => en2.key === k3)).filter(Boolean).sort((a, b2) => b2.priority - a.priority);
22772
+ const toInject = [...pinnedKeys].filter((k3) => !inResult.has(k3)).map((k3) => eligible.find((en2) => en2.key === k3)).filter(Boolean).sort((a, b2) => b2.priority - a.priority);
22575
22773
  for (const e of toInject) {
22576
22774
  scored.unshift({ entry: e, score: 999, matchesQuery: false, priority: e.priority });
22577
22775
  }
22578
22776
  if (scored.length === 0) {
22579
- const top = entries.filter((e) => !category || e.category === category).sort((a, b2) => {
22777
+ const top = eligible.sort((a, b2) => {
22580
22778
  if (a.priority !== b2.priority) return b2.priority - a.priority;
22581
- return importance(b2) - importance(a);
22779
+ return importance(b2, opts.today) - importance(a, opts.today);
22582
22780
  }).slice(0, limit);
22583
22781
  if (top.length === 0) return "No entries in memory.";
22584
22782
  return renderCompact(top);
@@ -32802,7 +33000,7 @@ function entryScore(dateStr, accessed) {
32802
33000
  return importance({ date: dateStr, accessed });
32803
33001
  }
32804
33002
  function entryScoreForLine(line) {
32805
- const parts = line.trim().split("|");
33003
+ const parts = parseToonLine(line);
32806
33004
  const date5 = parts[6] || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
32807
33005
  const accessed = parts.length > 8 ? parseInt(parts[8]) || 0 : 0;
32808
33006
  return entryScore(date5, accessed);
@@ -32813,7 +33011,7 @@ function findRelatedEntries(text, excludeKey = "", limit = 3) {
32813
33011
  const queryTokens = normalize(text).split(" ").filter(Boolean);
32814
33012
  const scored = lines.map((line) => {
32815
33013
  const trimmed = line.trim();
32816
- const parts = trimmed.split("|");
33014
+ const parts = parseToonLine(trimmed);
32817
33015
  if (parts.length < 7) return null;
32818
33016
  const [id2, cat, key, content, file2, tags, date5] = parts;
32819
33017
  if (key === excludeKey) return null;
@@ -32839,13 +33037,13 @@ function bumpAccessed(ids) {
32839
33037
  const line = lines[i];
32840
33038
  if (!line.startsWith(" ") || !line.includes("|")) continue;
32841
33039
  if (line.startsWith(" summaries:")) break;
32842
- const parts = line.trim().split("|");
33040
+ const parts = parseToonLine(line);
32843
33041
  if (idSet.has(parts[0])) {
32844
33042
  const accessed = parts.length > 8 ? (parseInt(parts[8]) || 0) + 1 : 1;
32845
33043
  parts[8] = String(accessed);
32846
33044
  while (parts.length < 13) parts.push("");
32847
33045
  parts[12] = now;
32848
- lines[i] = ` ${parts.join("|")}`;
33046
+ lines[i] = toToonLine(parts);
32849
33047
  }
32850
33048
  }
32851
33049
  writeMemory(lines.join("\n"));
@@ -32853,16 +33051,18 @@ function bumpAccessed(ids) {
32853
33051
 
32854
33052
  // src/mcp/observations.ts
32855
33053
  import { readFileSync as readFileSync3, existsSync as existsSync3, writeFileSync as writeFileSync3 } from "fs";
33054
+ init_utils();
32856
33055
  function readObservations() {
32857
33056
  if (!existsSync3(OBSERVATIONS_FILE)) return [];
32858
33057
  return readFileSync3(OBSERVATIONS_FILE, "utf-8").split("\n").filter((l) => l.startsWith(" ") && l.includes("|")).map((l) => {
32859
- const p2 = l.trim().split("|");
33058
+ const p2 = parseToonLine(l);
32860
33059
  return { ts: p2[0] || "", session: p2[1] || "", agent: p2[2] || "", branch: p2[3] || "", tool: p2[4] || "", file: p2[6] || "", summary: p2[7] || "" };
32861
33060
  });
32862
33061
  }
32863
33062
 
32864
33063
  // src/mcp/archive.ts
32865
33064
  import { readFileSync as readFileSync4, existsSync as existsSync4 } from "fs";
33065
+ init_utils();
32866
33066
  function archiveOldEntries(opts = {}) {
32867
33067
  const data = readMemory();
32868
33068
  const lines = data.split("\n");
@@ -32875,7 +33075,7 @@ function archiveOldEntries(opts = {}) {
32875
33075
  const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0);
32876
33076
  const toArchive = /* @__PURE__ */ new Set();
32877
33077
  entryLines2.forEach((line, idx) => {
32878
- const parts = line.trim().split("|");
33078
+ const parts = parseToonLine(line);
32879
33079
  if (parts.length < 7) return;
32880
33080
  const date5 = parts[6];
32881
33081
  const ttl = parts[7] || "";
@@ -32936,7 +33136,7 @@ function pruneExpiredEntries() {
32936
33136
  if (headerIdx === -1) return;
32937
33137
  const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
32938
33138
  const kept = entryLines2.filter((l) => {
32939
- const parts = l.trim().split("|");
33139
+ const parts = parseToonLine(l);
32940
33140
  if (parts.length < 8) return true;
32941
33141
  const ttl = parts[7] || "";
32942
33142
  if (ttl && isExpired(ttl)) {
@@ -32958,6 +33158,7 @@ function pruneExpiredEntries() {
32958
33158
 
32959
33159
  // src/mcp/consolidation.ts
32960
33160
  init_quality();
33161
+ init_utils();
32961
33162
  function contentSimilarity(a, b2) {
32962
33163
  const wordsA = new Set(a.toLowerCase().replace(/\s+/g, " ").trim().split(" "));
32963
33164
  const wordsB = new Set(b2.toLowerCase().replace(/\s+/g, " ").trim().split(" "));
@@ -32982,11 +33183,11 @@ function consolidateEntries() {
32982
33183
  const mergedAway = [];
32983
33184
  for (let i = 0; i < entryLines2.length; i++) {
32984
33185
  const line = entryLines2[i].trim();
32985
- const parts = line.split("|");
33186
+ const parts = parseToonLine(line);
32986
33187
  if (parts.length < 3) continue;
32987
33188
  const key = parts[2];
32988
33189
  const existingIdx = keyOrder.findIndex((idx) => {
32989
- const ep2 = entryLines2[idx].trim().split("|");
33190
+ const ep2 = parseToonLine(entryLines2[idx]);
32990
33191
  return ep2[2] === key;
32991
33192
  });
32992
33193
  if (existingIdx !== -1) {
@@ -33003,7 +33204,7 @@ function consolidateEntries() {
33003
33204
  const duplicates = [];
33004
33205
  for (const idx of keyOrder) {
33005
33206
  const line = byKey.get(idx);
33006
- const parts = line.split("|");
33207
+ const parts = parseToonLine(line);
33007
33208
  if (parts.length < 3) {
33008
33209
  order.push(line);
33009
33210
  continue;
@@ -33016,7 +33217,7 @@ function consolidateEntries() {
33016
33217
  }
33017
33218
  let merged = false;
33018
33219
  for (const [seenNorm, existing] of contentSeen) {
33019
- const existingParts = existing.line.split("|");
33220
+ const existingParts = parseToonLine(existing.line);
33020
33221
  if (existingParts[1] !== parts[1]) continue;
33021
33222
  const sim = contentSimilarity(content, existingParts[3] || "");
33022
33223
  if (sim >= NEAR_DUP_THRESHOLD) {
@@ -33981,6 +34182,356 @@ init_sessions();
33981
34182
  init_utils();
33982
34183
  init_synonyms();
33983
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
+ }
33984
34535
  server2.registerTool(
33985
34536
  "memory_remember",
33986
34537
  {
@@ -33996,7 +34547,8 @@ function registerTools(server2) {
33996
34547
  links: external_exports.string().optional().default("").describe("Related entry keys, separated by space or ';' (e.g. risk-spec engine-arch). Builds graph edges."),
33997
34548
  path_scope: external_exports.string().optional().default("").describe("Glob pattern to scope this entry (e.g. src/**.ts). Empty = global."),
33998
34549
  origin: external_exports.enum(["human", "agent", "inferred"]).optional().default("agent").describe("Who created this entry.")
33999
- }
34550
+ },
34551
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
34000
34552
  },
34001
34553
  async ({ category, key, content, file: file2, tags, ttl, links, path_scope, origin }) => {
34002
34554
  const data = readMemory();
@@ -34014,7 +34566,7 @@ function registerTools(server2) {
34014
34566
  const line = lines[i];
34015
34567
  if (!line.startsWith(" ") || !line.includes("|")) continue;
34016
34568
  if (line.startsWith(" summaries:")) break;
34017
- const parts = line.trim().split("|");
34569
+ const parts = parseToonLine(line);
34018
34570
  if (parts[2] === key) {
34019
34571
  existingIdx = i;
34020
34572
  existingId = parts[0];
@@ -34026,15 +34578,15 @@ function registerTools(server2) {
34026
34578
  const config2 = loadConfig();
34027
34579
  const verbatim = config2.verbatim === true;
34028
34580
  const resolvedTags = tags ? tags : verbatim ? "" : inferTags(content, key, config2.vocab);
34029
- const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : [];
34581
+ const existingParts = existingIdx !== -1 ? parseToonLine(lines[existingIdx]) : [];
34030
34582
  const resolvedLinks = links ? links.split(/[\s;]+/).filter(Boolean).join(" ") : existingParts[9] || "";
34031
- 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]);
34032
34584
  let action = "Saved";
34033
34585
  let mergeInfo = "";
34034
34586
  const tagsInferred = !tags && resolvedTags ? true : false;
34035
34587
  if (existingIdx !== -1) {
34036
34588
  newEntry = mergeEntries(lines[existingIdx].trim(), newEntry);
34037
- lines[existingIdx] = ` ${newEntry}`;
34589
+ lines[existingIdx] = newEntry;
34038
34590
  action = "Updated";
34039
34591
  mergeInfo = "\nMerge: tags combined, date and links updated";
34040
34592
  } else {
@@ -34042,10 +34594,10 @@ function registerTools(server2) {
34042
34594
  const lastAccessed = "";
34043
34595
  const quality = verbatim ? 0.5 : qualityScore(resolvedTags, resolvedLinks, content, date5, accessed, lastAccessed, origin);
34044
34596
  const confidence = 1;
34045
- 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"]);
34046
34598
  const match = lines[headerIdx].match(/\[(\d+)\|/);
34047
34599
  const count = match ? parseInt(match[1]) : 0;
34048
- lines.splice(headerIdx + 1, 0, ` ${newEntry}`);
34600
+ lines.splice(headerIdx + 1, 0, newEntry);
34049
34601
  lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`);
34050
34602
  }
34051
34603
  writeMemory(lines.join("\n"));
@@ -34093,14 +34645,17 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34093
34645
  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."),
34094
34646
  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
34647
  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').")
34097
- }
34648
+ path_scope: external_exports.string().optional().default("").describe("Glob pattern to filter entries by path scope (e.g. 'src/**.ts')."),
34649
+ rrf: external_exports.boolean().optional().default(false).describe("Use Reciprocal Rank Fusion (BM25x3 + centrality ranks, adaptive k=sqrtN) instead of weighted linear scoring. Weight-free: reaches parity with the tuned linear scorer on scripts/bench-rrf.mjs."),
34650
+ as_of: external_exports.string().optional().default("").describe("Temporal view (YYYY-MM-DD): return entries valid on that date. Superseded entries still appear if they were active then.")
34651
+ },
34652
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
34098
34653
  },
34099
- async ({ query, category, from_date, to_date, mode, hops, compact, bias, budget: budgetParam, path_scope }) => {
34654
+ async ({ query, category, from_date, to_date, mode, hops, compact, bias, budget: budgetParam, path_scope, rrf, as_of }) => {
34100
34655
  const data = readMemory();
34101
34656
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
34102
34657
  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 });
34658
+ const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, sessionFiles, path_scope: path_scope || void 0, rrf, asOf: as_of || void 0 });
34104
34659
  if (detail.entries.length === 0) {
34105
34660
  return { content: [{ type: "text", text: `No results found for "${query}"` }] };
34106
34661
  }
@@ -34121,9 +34676,10 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34121
34676
  const originInfo = r2.origin !== "agent" ? ` | origin: ${r2.origin}` : "";
34122
34677
  const scopeInfo = r2.path_scope ? ` | scope: ${r2.path_scope}` : "";
34123
34678
  const statusInfo = r2.status !== "active" ? ` | status: ${r2.status}` : "";
34679
+ const supersededInfo = r2.supersededOn ? ` | superseded: ${r2.supersededOn}` : "";
34124
34680
  return `[${r2.category}] ${r2.key}${pin} (${r2.id})
34125
34681
  ${r2.content}
34126
- File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}${originInfo}${scopeInfo}${statusInfo}`;
34682
+ File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}`;
34127
34683
  }).join("\n\n");
34128
34684
  return { content: [{ type: "text", text: formatted }] };
34129
34685
  }
@@ -34131,64 +34687,27 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34131
34687
  server2.registerTool(
34132
34688
  "memory_forget",
34133
34689
  {
34134
- title: "Delete from Memory",
34135
- 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.",
34136
34692
  inputSchema: {
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.")
34139
- }
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).")
34697
+ },
34698
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false }
34140
34699
  },
34141
- async ({ key, hard }) => {
34142
- const data = readMemory();
34143
- const lines = data.split("\n");
34144
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
34145
- if (headerIdx === -1) {
34146
- return { content: [{ type: "text", text: "No entries in memory" }] };
34147
- }
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
- }
34183
- writeMemory(lines.join("\n"));
34184
- if (!found) {
34185
- return {
34186
- content: [{ type: "text", text: `"${key}" not found in memory.` }]
34187
- };
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);
34188
34710
  }
34189
- return {
34190
- content: [{ type: "text", text: `"${key}" marked as obsolete. Use memory_resolve(key: "${key}") to restore.` }]
34191
- };
34192
34711
  }
34193
34712
  );
34194
34713
  server2.registerTool(
@@ -34196,13 +34715,14 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34196
34715
  {
34197
34716
  title: "Memory Stats",
34198
34717
  description: "Show project memory statistics.",
34199
- inputSchema: {}
34718
+ inputSchema: {},
34719
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
34200
34720
  },
34201
34721
  async () => {
34202
34722
  const data = readMemory();
34203
34723
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
34204
34724
  const entries = lines.map((l) => {
34205
- const parts = l.trim().split("|");
34725
+ const parts = parseToonLine(l);
34206
34726
  return { category: parts[1] || "unknown", ttl: parts[7] || "", quality: parts[10] || "", origin: parts.length > 15 ? parts[15] || "" : "", status: parts.length > 16 ? parts[16] || "" : "" };
34207
34727
  });
34208
34728
  const byCategory = {};
@@ -34238,7 +34758,7 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34238
34758
  "",
34239
34759
  `Last 5 entries:`,
34240
34760
  ...lines.slice(-5).map((l) => {
34241
- const parts = l.trim().split("|");
34761
+ const parts = parseToonLine(l);
34242
34762
  const ttlInfo = parts[7] ? ` | TTL: ${parts[7]}` : "";
34243
34763
  const qualityInfo = parts[10] ? ` | Q: ${parts[10]}` : "";
34244
34764
  const accessInfo = parts[8] && parseInt(parts[8]) > 0 ? ` | accessed: ${parts[8]}x` : "";
@@ -34249,12 +34769,12 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34249
34769
  "",
34250
34770
  `Most accessed:`,
34251
34771
  ...lines.filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")).map((l) => {
34252
- const parts = l.trim().split("|");
34772
+ const parts = parseToonLine(l);
34253
34773
  return { key: parts[2], accessed: parts.length > 8 ? parseInt(parts[8]) || 0 : 0, quality: parts[10] || "" };
34254
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})`)
34255
34775
  ];
34256
34776
  const coldEntries = lines.filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")).map((l) => {
34257
- const p2 = l.trim().split("|");
34777
+ const p2 = parseToonLine(l);
34258
34778
  return {
34259
34779
  key: p2[2],
34260
34780
  cat: p2[1],
@@ -34295,7 +34815,8 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34295
34815
  inputSchema: {
34296
34816
  since: external_exports.string().describe("Show changes since (e.g. 24h, 7d, 2026-07-10)"),
34297
34817
  type: external_exports.enum(["all", "created", "updated"]).optional().default("all").describe("Filter by change type")
34298
- }
34818
+ },
34819
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
34299
34820
  },
34300
34821
  async ({ since, type }) => {
34301
34822
  const sinceDate = parseRelativeDate(since);
@@ -34304,7 +34825,7 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34304
34825
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
34305
34826
  const results = lines.map((line) => {
34306
34827
  const trimmed = line.trim();
34307
- const parts = trimmed.split("|");
34828
+ const parts = parseToonLine(trimmed);
34308
34829
  if (parts.length < 7) return null;
34309
34830
  const [id2, cat, key, content, file2, tags, date5] = parts;
34310
34831
  if (date5 < sinceDate) return null;
@@ -34344,7 +34865,8 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34344
34865
  inputSchema: {
34345
34866
  context: external_exports.string().describe("Text or context to search for suggestions"),
34346
34867
  limit: external_exports.number().optional().default(5).describe("Maximum suggestions")
34347
- }
34868
+ },
34869
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
34348
34870
  },
34349
34871
  async ({ context, limit }) => {
34350
34872
  const related = findRelatedEntries(context, "", limit);
@@ -34368,14 +34890,16 @@ ${formatted}` }] };
34368
34890
  intent: external_exports.string().describe("Describe what you need to know (e.g. 'database schema for backend')"),
34369
34891
  limit: external_exports.number().optional().default(8).describe("Maximum entries to return"),
34370
34892
  category: external_exports.string().optional().default("").describe("Filter by category (empty = all)"),
34371
- bias: external_exports.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default).")
34372
- }
34893
+ bias: external_exports.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
34894
+ rrf: external_exports.boolean().optional().default(false).describe("Use Reciprocal Rank Fusion (BM25x3 + centrality ranks, adaptive k=sqrtN) instead of weighted linear scoring. Weight-free: reaches parity with the tuned linear scorer on scripts/bench-rrf.mjs.")
34895
+ },
34896
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
34373
34897
  },
34374
- async ({ intent, limit, category, bias }) => {
34898
+ async ({ intent, limit, category, bias, rrf }) => {
34375
34899
  const data = readMemory();
34376
34900
  const mtimes = fileMtimes();
34377
34901
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
34378
- const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles });
34902
+ const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles, rrf });
34379
34903
  return { content: [{ type: "text", text: result }] };
34380
34904
  }
34381
34905
  );
@@ -34388,7 +34912,8 @@ ${formatted}` }] };
34388
34912
  action: external_exports.enum(["get", "set"]).describe("get to read, set to save"),
34389
34913
  file: external_exports.string().describe("File path"),
34390
34914
  summary: external_exports.string().optional().default("").describe("File summary (only for set)")
34391
- }
34915
+ },
34916
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
34392
34917
  },
34393
34918
  async ({ action, file: file2, summary }) => {
34394
34919
  const data = readMemory();
@@ -34403,7 +34928,7 @@ ${formatted}` }] };
34403
34928
  if (!match) {
34404
34929
  return { content: [{ type: "text", text: `No summary for "${file2}"` }] };
34405
34930
  }
34406
- const summaryText = match.replace(` ${file2}: `, "");
34931
+ const summaryText = unescField(match.replace(` ${file2}: `, ""));
34407
34932
  return { content: [{ type: "text", text: summaryText }] };
34408
34933
  }
34409
34934
  const lines = data.split("\n");
@@ -34415,9 +34940,9 @@ ${formatted}` }] };
34415
34940
  const summaryLines = lines.slice(summaryIdx + 1).filter((l) => l.includes(":"));
34416
34941
  const existingIdx = summaryLines.findIndex((l) => l.startsWith(` ${file2}:`));
34417
34942
  if (existingIdx !== -1) {
34418
- summaryLines[existingIdx] = ` ${file2}: ${summary}`;
34943
+ summaryLines[existingIdx] = ` ${file2}: ${escField(summary)}`;
34419
34944
  } else {
34420
- summaryLines.push(` ${file2}: ${summary}`);
34945
+ summaryLines.push(` ${file2}: ${escField(summary)}`);
34421
34946
  }
34422
34947
  lines.splice(summaryIdx + 1, lines.length - summaryIdx - 1, ...summaryLines);
34423
34948
  writeMemory(lines.join("\n"));
@@ -34431,7 +34956,8 @@ ${formatted}` }] };
34431
34956
  {
34432
34957
  title: "Archive Old Entries",
34433
34958
  description: "Move old entries (>30 days) to archive.toon to keep memory clean.",
34434
- inputSchema: {}
34959
+ inputSchema: {},
34960
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false }
34435
34961
  },
34436
34962
  async () => {
34437
34963
  const result = archiveOldEntries();
@@ -34452,7 +34978,8 @@ ${formatted}` }] };
34452
34978
  {
34453
34979
  title: "Enable Encryption",
34454
34980
  description: "Enable AES-256-GCM encryption for memory. Requires TOON_MEMORY_KEY in environment.",
34455
- inputSchema: {}
34981
+ inputSchema: {},
34982
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true }
34456
34983
  },
34457
34984
  async () => {
34458
34985
  const config2 = loadConfig();
@@ -34479,7 +35006,8 @@ ${formatted}` }] };
34479
35006
  description: "Disable encryption and decode memory.",
34480
35007
  inputSchema: {
34481
35008
  key: external_exports.string().describe("Encryption key")
34482
- }
35009
+ },
35010
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true }
34483
35011
  },
34484
35012
  async ({ key }) => {
34485
35013
  const config2 = loadConfig();
@@ -34513,7 +35041,8 @@ ${formatted}` }] };
34513
35041
  tool: external_exports.string().optional().default("").describe("Filter by tool name"),
34514
35042
  file: external_exports.string().optional().default("").describe("Filter by file"),
34515
35043
  clear: external_exports.boolean().optional().default(false).describe("If true, clears the capture log")
34516
- }
35044
+ },
35045
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false }
34517
35046
  },
34518
35047
  async ({ limit, tool, file: file2, clear }) => {
34519
35048
  if (clear) {
@@ -34545,22 +35074,23 @@ ${formatted}` }] };
34545
35074
  "memory_consolidate",
34546
35075
  {
34547
35076
  title: "Consolidate Memory",
34548
- description: "Consolidate memory by removing entries with identical content (keeps the first). Deterministic, no LLM.",
34549
- 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
+ },
35083
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true }
34550
35084
  },
34551
- async () => {
34552
- const result = consolidateEntries();
34553
- if (result.removed === 0) {
34554
- 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();
34555
35093
  }
34556
- return {
34557
- content: [{
34558
- type: "text",
34559
- text: `\u{1F9F9} Consolidated ${result.removed} duplicate entries.
34560
- ${result.kept} active entries remaining.
34561
- Duplicates: ${result.duplicates.join(", ")}`
34562
- }]
34563
- };
34564
35094
  }
34565
35095
  );
34566
35096
  server2.registerTool(
@@ -34570,7 +35100,8 @@ Duplicates: ${result.duplicates.join(", ")}`
34570
35100
  description: "Show active agent sessions in this project (git branch, files touched, last-seen) and detect soft conflicts (files touched by 2+ sessions). Use at startup to avoid overwriting other parallel sessions' work.",
34571
35101
  inputSchema: {
34572
35102
  conflictsOnly: external_exports.boolean().optional().default(false).describe("If true, only show soft conflicts")
34573
- }
35103
+ },
35104
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
34574
35105
  },
34575
35106
  async ({ conflictsOnly }) => {
34576
35107
  const selfId = resolveSessionId();
@@ -34636,7 +35167,8 @@ ${files}` : "";
34636
35167
  inputSchema: {
34637
35168
  task: external_exports.string().optional().default("").describe("Current agent task. If provided, entries are ranked by relevance to this task. If empty, shows top entries by importance."),
34638
35169
  limit: external_exports.number().optional().default(6).describe("Maximum relevant entries to show")
34639
- }
35170
+ },
35171
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
34640
35172
  },
34641
35173
  async ({ task, limit }) => {
34642
35174
  const data = readMemory();
@@ -34651,7 +35183,8 @@ ${files}` : "";
34651
35183
  description: "Generate a full system prompt: project (package.json, deps, framework) + git (branch, commits) + memory (relevant entries) + sessions. Single call to prepare the agent. Zero LLM.",
34652
35184
  inputSchema: {
34653
35185
  task: external_exports.string().optional().default("").describe("Agent task. If provided, ranks entries by relevance to this task.")
34654
- }
35186
+ },
35187
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
34655
35188
  },
34656
35189
  async ({ task }) => {
34657
35190
  const data = readMemory();
@@ -34667,7 +35200,8 @@ ${files}` : "";
34667
35200
  description: "What changed since the last session: git commits + modified files + new/updated memory entries. Zero LLM.",
34668
35201
  inputSchema: {
34669
35202
  since: external_exports.string().optional().default("").describe("Start date (YYYY-MM-DD or relative like '7d'). Empty = last visible changes.")
34670
- }
35203
+ },
35204
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
34671
35205
  },
34672
35206
  async ({ since }) => {
34673
35207
  const data = readMemory();
@@ -34684,7 +35218,8 @@ ${files}` : "";
34684
35218
  inputSchema: {
34685
35219
  task: external_exports.string().describe("Task or symbol to search context for (e.g. 'fix auth bug', 'authenticate')"),
34686
35220
  limit: external_exports.number().optional().default(6).describe("Maximum memory entries to include")
34687
- }
35221
+ },
35222
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
34688
35223
  },
34689
35224
  async ({ task, limit }) => {
34690
35225
  const data = readMemory();
@@ -34698,7 +35233,8 @@ ${files}` : "";
34698
35233
  {
34699
35234
  title: "Memory Health Audit",
34700
35235
  description: "Full memory health audit: orphan links, duplicates, broken refs, expired TTL, quality, stale sessions. Includes score 0-100. Zero LLM.",
34701
- inputSchema: {}
35236
+ inputSchema: {},
35237
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
34702
35238
  },
34703
35239
  async () => {
34704
35240
  const data = readMemory();
@@ -34714,7 +35250,8 @@ ${files}` : "";
34714
35250
  description: "Export all memory as markdown injectable for other agents or sessions. Full (detailed) or compact format. Zero LLM.",
34715
35251
  inputSchema: {
34716
35252
  format: external_exports.enum(["full", "compact"]).optional().default("full").describe("full = detailed with graph, compact = summarized without edges")
34717
- }
35253
+ },
35254
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
34718
35255
  },
34719
35256
  async ({ format }) => {
34720
35257
  const data = readMemory();
@@ -34727,7 +35264,8 @@ ${files}` : "";
34727
35264
  {
34728
35265
  title: "Backup Memory",
34729
35266
  description: "Create a timestamped backup of the memory file. Use before major operations or to preserve state.",
34730
- inputSchema: {}
35267
+ inputSchema: {},
35268
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false }
34731
35269
  },
34732
35270
  async () => {
34733
35271
  if (!existsSync10(MEMORY_FILE)) {
@@ -34767,7 +35305,8 @@ ${files}` : "";
34767
35305
  {
34768
35306
  title: "System Primer",
34769
35307
  description: "Generate a compact system primer: always-current knowledge map for auto-injection into agent context. Excludes private entries, shows top memories by importance, categories, and patterns. Use at session start or when context feels stale.",
34770
- inputSchema: {}
35308
+ inputSchema: {},
35309
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
34771
35310
  },
34772
35311
  async () => {
34773
35312
  const data = readMemory();
@@ -34785,7 +35324,8 @@ ${files}` : "";
34785
35324
  query: external_exports.string().optional().default("").describe("Search query to find entries to compress (e.g. 'auth bug fixes'). Empty = show lowest-quality entries."),
34786
35325
  count: external_exports.number().optional().default(3).describe("Number of entries to compress (2-10). Default: 3."),
34787
35326
  category: external_exports.string().optional().default("").describe("Filter by category (empty = all).")
34788
- }
35327
+ },
35328
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
34789
35329
  },
34790
35330
  async ({ query, count, category }) => {
34791
35331
  const data = readMemory();
@@ -34847,87 +35387,6 @@ ${files}` : "";
34847
35387
  return { content: [{ type: "text", text: prompt }] };
34848
35388
  }
34849
35389
  );
34850
- server2.registerTool(
34851
- "memory_compress_all",
34852
- {
34853
- title: "Lazy Batch Compression",
34854
- 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.",
34855
- inputSchema: {
34856
- minQuality: external_exports.number().optional().default(0.3).describe("Entries below this quality score are compression candidates (0-1). Default: 0.3."),
34857
- dryRun: external_exports.boolean().optional().default(false).describe("If true, show what would be compressed without making changes.")
34858
- }
34859
- },
34860
- async ({ minQuality, dryRun }) => {
34861
- const data = readMemory();
34862
- const lines = data.split("\n");
34863
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
34864
- if (headerIdx === -1) {
34865
- return { content: [{ type: "text", text: "No entries in memory." }] };
34866
- }
34867
- const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
34868
- const candidates = [];
34869
- for (let i = 0; i < entryLines2.length; i++) {
34870
- const line = entryLines2[i].trim();
34871
- const parts = line.split("|");
34872
- if (parts.length < 11) continue;
34873
- const quality = parseFloat(parts[10]) || 0;
34874
- const tags = parts[5] || "";
34875
- const key = parts[2];
34876
- const content = parts[3] || "";
34877
- const isCandidate = quality < minQuality || !tags || content.length < 20;
34878
- if (isCandidate) {
34879
- candidates.push({ idx: i, line, quality, key });
34880
- }
34881
- }
34882
- if (candidates.length === 0) {
34883
- return {
34884
- content: [{
34885
- type: "text",
34886
- text: `\u2705 No compression candidates found. All entries have quality >= ${minQuality} or have tags.`
34887
- }]
34888
- };
34889
- }
34890
- const byCategory = /* @__PURE__ */ new Map();
34891
- for (const c2 of candidates) {
34892
- const parts = c2.line.split("|");
34893
- const cat = parts[1] || "unknown";
34894
- if (!byCategory.has(cat)) byCategory.set(cat, []);
34895
- byCategory.get(cat).push(c2);
34896
- }
34897
- const sections = [
34898
- `\u{1F4E6} Compression candidates: ${candidates.length} entries below quality ${minQuality}`,
34899
- "",
34900
- "By category:"
34901
- ];
34902
- for (const [cat, items] of byCategory) {
34903
- sections.push(` ${cat}: ${items.length} entries`);
34904
- for (const item of items.slice(0, 3)) {
34905
- const parts = item.line.split("|");
34906
- sections.push(` - ${item.key} (Q: ${item.quality.toFixed(2)}) \u2014 ${(parts[3] || "").slice(0, 60)}`);
34907
- }
34908
- if (items.length > 3) {
34909
- sections.push(` ... and ${items.length - 3} more`);
34910
- }
34911
- }
34912
- if (dryRun) {
34913
- sections.push("", "\u{1F50D} Dry run \u2014 no changes made. Use dryRun: false to compress.");
34914
- return { content: [{ type: "text", text: sections.join("\n") }] };
34915
- }
34916
- const removeKeys = new Set(candidates.map((c2) => c2.key));
34917
- const kept = entryLines2.filter((l) => {
34918
- const parts = l.trim().split("|");
34919
- return !removeKeys.has(parts[2]);
34920
- });
34921
- const match = lines[headerIdx].match(/\[(\d+)\|/);
34922
- const count = match ? parseInt(match[1]) : 0;
34923
- lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${kept.length}|`);
34924
- lines.splice(headerIdx + 1, entryLines2.length, ...kept.map((l) => ` ${l.trim()}`));
34925
- writeMemory(lines.join("\n"));
34926
- sections.push("", `\u{1F5D1}\uFE0F Removed ${candidates.length} low-quality entries. ${kept.length} entries remaining.`);
34927
- sections.push("\u{1F4A1} Use memory_compress to merge related entries before removing them.");
34928
- return { content: [{ type: "text", text: sections.join("\n") }] };
34929
- }
34930
- );
34931
35390
  server2.registerTool(
34932
35391
  "memory_export_gist",
34933
35392
  {
@@ -34935,7 +35394,8 @@ ${files}` : "";
34935
35394
  description: "Export memory to a private GitHub Gist for cloud sync. Requires GITHUB_TOKEN env var. Zero deps \u2014 uses Node's built-in fetch().",
34936
35395
  inputSchema: {
34937
35396
  description: external_exports.string().optional().default("").describe("Optional description for the Gist.")
34938
- }
35397
+ },
35398
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false }
34939
35399
  },
34940
35400
  async ({ description }) => {
34941
35401
  const token = process.env.GITHUB_TOKEN;
@@ -34996,7 +35456,8 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
34996
35456
  inputSchema: {
34997
35457
  gist_id: external_exports.string().describe("GitHub Gist ID or full URL (https://gist.github.com/user/id)."),
34998
35458
  merge: external_exports.boolean().optional().default(true).describe("If true, merge with existing memory. If false, replace entirely.")
34999
- }
35459
+ },
35460
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false }
35000
35461
  },
35001
35462
  async ({ gist_id, merge: merge2 }) => {
35002
35463
  const token = process.env.GITHUB_TOKEN;
@@ -35071,7 +35532,7 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
35071
35532
  const tags = e.tags.join(";");
35072
35533
  const links = e.links.join(" ");
35073
35534
  const q2 = qualityScore(tags, links, e.content, e.date, e.accessed, e.lastAccessed);
35074
- 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]);
35075
35536
  })
35076
35537
  ];
35077
35538
  safeWrite(MEMORY_FILE, lines.join("\n"));
@@ -35097,7 +35558,8 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
35097
35558
  inputSchema: {
35098
35559
  since: external_exports.string().optional().default("24h").describe("Time window to merge (e.g. '24h', '7d', '2026-07-20'). Default: 24h."),
35099
35560
  promote: external_exports.boolean().optional().default(false).describe("If true, auto-promote unique observations to memory entries.")
35100
- }
35561
+ },
35562
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false }
35101
35563
  },
35102
35564
  async ({ since, promote }) => {
35103
35565
  const { listSessions: listSessions2, pruneSessions: pruneSessions2 } = await Promise.resolve().then(() => (init_sessions(), sessions_exports));
@@ -35122,7 +35584,7 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
35122
35584
  const data = readFileSync10(OBSERVATIONS_FILE, "utf-8");
35123
35585
  const sessionIds = new Set(recentSessions.map((s2) => s2.id));
35124
35586
  observations = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|")).map((l) => {
35125
- const p2 = l.trim().split("|");
35587
+ const p2 = parseToonLine(l);
35126
35588
  return { ts: p2[0] || "", session: p2[1] || "", agent: p2[2] || "", branch: p2[3] || "", tool: p2[4] || "", file: p2[6] || "", summary: p2[7] || "" };
35127
35589
  }).filter((o) => sessionIds.has(o.session));
35128
35590
  }
@@ -35170,7 +35632,7 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
35170
35632
  const file2 = obs.file || "";
35171
35633
  const tags = `session-merge;${obs.agent};${obs.branch}`;
35172
35634
  const quality = qualityScore(tags, "", content, date5);
35173
- 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", ""]);
35174
35636
  const lines = data.split("\n");
35175
35637
  let headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35176
35638
  if (headerIdx === -1) {
@@ -35179,7 +35641,7 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
35179
35641
  }
35180
35642
  const match = lines[headerIdx].match(/\[(\d+)\|/);
35181
35643
  const count = match ? parseInt(match[1]) : 0;
35182
- lines.splice(headerIdx + 1, 0, ` ${entry}`);
35644
+ lines.splice(headerIdx + 1, 0, entry);
35183
35645
  lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`);
35184
35646
  writeMemory(lines.join("\n"));
35185
35647
  existingKeys.add(key);
@@ -35192,107 +35654,6 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
35192
35654
  return { content: [{ type: "text", text: sections.join("\n") }] };
35193
35655
  }
35194
35656
  );
35195
- server2.registerTool(
35196
- "memory_merge_similar",
35197
- {
35198
- title: "Merge Similar Entries",
35199
- description: "Find entries with overlapping content (>50% word similarity) and merge them. Deterministic, no LLM. Keeps the longer content and combines tags.",
35200
- inputSchema: {
35201
- dryRun: external_exports.boolean().optional().default(false).describe("If true, show what would be merged without making changes.")
35202
- }
35203
- },
35204
- async ({ dryRun }) => {
35205
- const data = readMemory();
35206
- const entries = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
35207
- if (entries.length < 2) {
35208
- return { content: [{ type: "text", text: "\u2705 Not enough entries to compress." }] };
35209
- }
35210
- const parsed = entries.map((line) => {
35211
- const parts = line.trim().split("|");
35212
- if (parts.length < 7) return null;
35213
- const [id2, cat, key, content, file2, tags, date5, ttl, accessedRaw] = parts;
35214
- const words = new Set(normalize(`${key} ${content} ${tags}`).split(" ").filter(Boolean));
35215
- return { id: id2, cat, key, content, file: file2, tags, date: date5, ttl, accessed: parseInt(accessedRaw) || 0, words, line };
35216
- }).filter(Boolean);
35217
- const mergePairs = [];
35218
- for (let i = 0; i < parsed.length; i++) {
35219
- for (let j3 = i + 1; j3 < parsed.length; j3++) {
35220
- const a = parsed[i], b2 = parsed[j3];
35221
- const intersection2 = new Set([...a.words].filter((w3) => b2.words.has(w3)));
35222
- const union2 = /* @__PURE__ */ new Set([...a.words, ...b2.words]);
35223
- const similarity = union2.size > 0 ? intersection2.size / union2.size : 0;
35224
- if (similarity > 0.5) {
35225
- mergePairs.push({ a: i, b: j3, similarity });
35226
- }
35227
- }
35228
- }
35229
- if (mergePairs.length === 0) {
35230
- return { content: [{ type: "text", text: "\u2705 No similar entries found to merge." }] };
35231
- }
35232
- mergePairs.sort((x, y2) => y2.similarity - x.similarity);
35233
- const merged = /* @__PURE__ */ new Set();
35234
- const mergeActions = [];
35235
- for (const pair of mergePairs) {
35236
- if (merged.has(pair.a) || merged.has(pair.b)) continue;
35237
- const a = parsed[pair.a], b2 = parsed[pair.b];
35238
- const mergedTags = [.../* @__PURE__ */ new Set([...a.tags.split(";"), ...b2.tags.split(";")])].filter(Boolean).join(";");
35239
- const longer = a.content.length >= b2.content.length ? a : b2;
35240
- const shorter = a.content.length < b2.content.length ? a : b2;
35241
- const newContent = longer.content;
35242
- const newDate = a.date > b2.date ? a.date : b2.date;
35243
- const newAccessed = a.accessed + b2.accessed;
35244
- mergeActions.push(` [${longer.cat}] ${longer.key} \u2190 ${shorter.key} (similarity: ${(pair.similarity * 100).toFixed(0)}%)`);
35245
- if (!dryRun) {
35246
- 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] || ""}`;
35247
- entries[entries.indexOf(longer.line)] = mergedLine;
35248
- merged.add(pair.b);
35249
- }
35250
- }
35251
- if (dryRun) {
35252
- const previewLines = [
35253
- `\u{1F50D} Dry run \u2014 ${mergePairs.length} merge candidate(s) found:`,
35254
- ""
35255
- ];
35256
- for (const pair of mergePairs) {
35257
- const a = parsed[pair.a], b2 = parsed[pair.b];
35258
- const mergedTags = [.../* @__PURE__ */ new Set([...a.tags.split(";"), ...b2.tags.split(";")])].filter(Boolean).join(";");
35259
- const longer = a.content.length >= b2.content.length ? a : b2;
35260
- const shorter = a.content.length < b2.content.length ? a : b2;
35261
- previewLines.push(` \u2500\u2500 Pair: [${a.cat}] ${a.key} \u2194 [${b2.cat}] ${b2.key}`);
35262
- previewLines.push(` Similarity: ${(pair.similarity * 100).toFixed(0)}%`);
35263
- previewLines.push(` A tags: ${a.tags || "(none)"}`);
35264
- previewLines.push(` B tags: ${b2.tags || "(none)"}`);
35265
- previewLines.push(` \u2192 Merged tags: ${mergedTags || "(none)"}`);
35266
- previewLines.push(` \u2192 Content winner: "${longer.key}" (${longer.content.length} chars vs ${shorter.content.length})`);
35267
- previewLines.push(` \u2192 Result content: ${longer.content.slice(0, 120)}${longer.content.length > 120 ? "\u2026" : ""}`);
35268
- previewLines.push("");
35269
- }
35270
- previewLines.push(`Would merge ${merged.size} entries into ${entries.length - merged.size} entries.`);
35271
- previewLines.push("Run with dryRun: false to apply.");
35272
- return {
35273
- content: [{
35274
- type: "text",
35275
- text: previewLines.join("\n")
35276
- }]
35277
- };
35278
- }
35279
- const newLines = entries.filter((_2, i) => !merged.has(i));
35280
- const headerIdx = newLines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35281
- if (headerIdx !== -1) {
35282
- const count = newLines.filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")).length;
35283
- newLines[headerIdx] = newLines[headerIdx].replace(/\[\d+\|/, `[${count}|`);
35284
- }
35285
- writeMemory(newLines.join("\n"));
35286
- return {
35287
- content: [{
35288
- type: "text",
35289
- text: `\u2705 Merged ${merged.size} entries into ${entries.length - merged.size} entries.
35290
-
35291
- ${mergeActions.join("\n")}`
35292
- }]
35293
- };
35294
- }
35295
- );
35296
35657
  server2.registerTool(
35297
35658
  "memory_graph_path",
35298
35659
  {
@@ -35301,7 +35662,8 @@ ${mergeActions.join("\n")}`
35301
35662
  inputSchema: {
35302
35663
  from: external_exports.string().describe("Starting entry key"),
35303
35664
  to: external_exports.string().describe("Target entry key")
35304
- }
35665
+ },
35666
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
35305
35667
  },
35306
35668
  async ({ from, to: to2 }) => {
35307
35669
  const data = readMemory();
@@ -35364,7 +35726,8 @@ ${mergeActions.join("\n")}`
35364
35726
  description: "Save or update a session checkpoint with 7-day TTL. Creates a knowledge entry snapshot of the current session state. Same session = upsert (single checkpoint per session). Auto-expires.",
35365
35727
  inputSchema: {
35366
35728
  note: external_exports.string().optional().default("").describe("Optional summary of what was accomplished in this session.")
35367
- }
35729
+ },
35730
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
35368
35731
  },
35369
35732
  async ({ note }) => {
35370
35733
  const data = readMemory();
@@ -35396,7 +35759,7 @@ Branch: ${branch}${fileList}`;
35396
35759
  const line = lines[i];
35397
35760
  if (!line.startsWith(" ") || !line.includes("|")) continue;
35398
35761
  if (line.startsWith(" summaries:")) break;
35399
- const parts = line.trim().split("|");
35762
+ const parts = parseToonLine(line);
35400
35763
  if (parts[2] === key) {
35401
35764
  existingIdx = i;
35402
35765
  existingId = parts[0];
@@ -35404,13 +35767,13 @@ Branch: ${branch}${fileList}`;
35404
35767
  }
35405
35768
  }
35406
35769
  if (existingIdx !== -1) {
35407
- const parts = lines[existingIdx].trim().split("|");
35770
+ const parts = parseToonLine(lines[existingIdx]);
35408
35771
  parts[3] = content;
35409
35772
  parts[6] = date5;
35410
35773
  parts[7] = ttl7d;
35411
35774
  while (parts.length < 14) parts.push("");
35412
35775
  parts[13] = "0";
35413
- lines[existingIdx] = ` ${parts.join("|")}`;
35776
+ lines[existingIdx] = toToonLine(parts);
35414
35777
  writeMemory(lines.join("\n"));
35415
35778
  return {
35416
35779
  content: [{ type: "text", text: `\u{1F4DD} Checkpoint updated: ${key}
@@ -35421,10 +35784,10 @@ ${note}` : ""}` }]
35421
35784
  }
35422
35785
  const newId = `cp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
35423
35786
  const quality = qualityScore("checkpoint", "", content, date5);
35424
- 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"]);
35425
35788
  const match = lines[headerIdx].match(/\[(\d+)\|/);
35426
35789
  const count = match ? parseInt(match[1]) : 0;
35427
- lines.splice(headerIdx + 1, 0, ` ${newEntry}`);
35790
+ lines.splice(headerIdx + 1, 0, newEntry);
35428
35791
  lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`);
35429
35792
  writeMemory(lines.join("\n"));
35430
35793
  return {
@@ -35446,7 +35809,8 @@ ${note}` : ""}`
35446
35809
  inputSchema: {
35447
35810
  key: external_exports.string().describe("Key or id of the entry to pin"),
35448
35811
  priority: external_exports.number().optional().default(1).describe("Priority level 1-5 (5 = highest). Default: 1.")
35449
- }
35812
+ },
35813
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
35450
35814
  },
35451
35815
  async ({ key, priority }) => {
35452
35816
  const data = readMemory();
@@ -35461,11 +35825,11 @@ ${note}` : ""}`
35461
35825
  const line = lines[i];
35462
35826
  if (!line.startsWith(" ") || !line.includes("|")) continue;
35463
35827
  if (line.startsWith(" summaries:")) break;
35464
- const parts = line.trim().split("|");
35828
+ const parts = parseToonLine(line);
35465
35829
  if (parts[0] === key || parts[2] === key) {
35466
35830
  while (parts.length < 14) parts.push("");
35467
35831
  parts[13] = String(clampedPriority);
35468
- lines[i] = ` ${parts.join("|")}`;
35832
+ lines[i] = toToonLine(parts);
35469
35833
  found = true;
35470
35834
  break;
35471
35835
  }
@@ -35484,7 +35848,8 @@ ${note}` : ""}`
35484
35848
  description: "Remove the pin from a memory entry so it returns to normal ranking.",
35485
35849
  inputSchema: {
35486
35850
  key: external_exports.string().describe("Key or id of the entry to unpin")
35487
- }
35851
+ },
35852
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
35488
35853
  },
35489
35854
  async ({ key }) => {
35490
35855
  const data = readMemory();
@@ -35498,11 +35863,11 @@ ${note}` : ""}`
35498
35863
  const line = lines[i];
35499
35864
  if (!line.startsWith(" ") || !line.includes("|")) continue;
35500
35865
  if (line.startsWith(" summaries:")) break;
35501
- const parts = line.trim().split("|");
35866
+ const parts = parseToonLine(line);
35502
35867
  if (parts[0] === key || parts[2] === key) {
35503
35868
  if (parts.length > 13) {
35504
35869
  parts[13] = "0";
35505
- lines[i] = ` ${parts.join("|")}`;
35870
+ lines[i] = toToonLine(parts);
35506
35871
  }
35507
35872
  found = true;
35508
35873
  break;
@@ -35532,10 +35897,13 @@ ${note}` : ""}`
35532
35897
  compact: external_exports.boolean().optional().default(false).describe("Token-efficient output"),
35533
35898
  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
35899
  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').")
35536
- }
35900
+ path_scope: external_exports.string().optional().default("").describe("Glob pattern to filter entries by path scope (e.g. 'src/**.ts')."),
35901
+ rrf: external_exports.boolean().optional().default(false).describe("Use Reciprocal Rank Fusion (BM25x3 + centrality ranks, adaptive k=sqrtN) instead of weighted linear scoring. Weight-free: reaches parity with the tuned linear scorer on scripts/bench-rrf.mjs."),
35902
+ as_of: external_exports.string().optional().default("").describe("Temporal view (YYYY-MM-DD): return entries valid on that date.")
35903
+ },
35904
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
35537
35905
  },
35538
- async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact, bias, budget: budgetParam, path_scope }) => {
35906
+ async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact, bias, budget: budgetParam, path_scope, rrf, as_of }) => {
35539
35907
  const data = readMemory();
35540
35908
  const resolvedFrom = from_date ? parseRelativeDate(from_date) : "";
35541
35909
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
@@ -35548,7 +35916,9 @@ ${note}` : ""}`
35548
35916
  hops,
35549
35917
  limit,
35550
35918
  sessionFiles,
35551
- path_scope: path_scope || void 0
35919
+ path_scope: path_scope || void 0,
35920
+ rrf,
35921
+ asOf: as_of || void 0
35552
35922
  });
35553
35923
  if (detail.entries.length === 0) {
35554
35924
  return { content: [{ type: "text", text: `No results found for "${query}"` }] };
@@ -35572,9 +35942,10 @@ ${formatted2}` }] };
35572
35942
  const originInfo = r2.origin !== "agent" ? ` | origin: ${r2.origin}` : "";
35573
35943
  const scopeInfo = r2.path_scope ? ` | scope: ${r2.path_scope}` : "";
35574
35944
  const statusInfo = r2.status !== "active" ? ` | status: ${r2.status}` : "";
35945
+ const supersededInfo = r2.supersededOn ? ` | superseded: ${r2.supersededOn}` : "";
35575
35946
  return `[${r2.category}] ${r2.key}${pin} (${r2.id})
35576
35947
  ${r2.content}
35577
- File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}${originInfo}${scopeInfo}${statusInfo}`;
35948
+ File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}`;
35578
35949
  }).join("\n\n");
35579
35950
  let filterInfo = "";
35580
35951
  if (category) filterInfo += ` category: ${category}`;
@@ -35597,7 +35968,8 @@ ${formatted}` }]
35597
35968
  action: external_exports.enum(["add", "remove", "set"]).describe("'add': merge tags (union). 'remove': remove specified tags. 'set': replace all tags."),
35598
35969
  tags: external_exports.string().describe("Semicolon-separated tags to apply"),
35599
35970
  ids: external_exports.string().describe("Comma or space-separated entry keys or IDs to modify")
35600
- }
35971
+ },
35972
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
35601
35973
  },
35602
35974
  async ({ action, tags, ids }) => {
35603
35975
  const data = readMemory();
@@ -35618,7 +35990,7 @@ ${formatted}` }]
35618
35990
  const line = lines[i];
35619
35991
  if (!line.startsWith(" ") || !line.includes("|")) continue;
35620
35992
  if (line.startsWith(" summaries:")) break;
35621
- const parts = line.trim().split("|");
35993
+ const parts = parseToonLine(line);
35622
35994
  const entryId = parts[0];
35623
35995
  const entryKey = parts[2];
35624
35996
  if (!targetSet.has(entryId) && !targetSet.has(entryKey)) continue;
@@ -35632,7 +36004,7 @@ ${formatted}` }]
35632
36004
  newTags = [...tagsToApply];
35633
36005
  }
35634
36006
  parts[5] = newTags.join(";");
35635
- lines[i] = ` ${parts.join("|")}`;
36007
+ lines[i] = toToonLine(parts);
35636
36008
  modified++;
35637
36009
  modifiedKeys.push(entryKey);
35638
36010
  }
@@ -35652,80 +36024,254 @@ ${formatted}` }]
35652
36024
  }
35653
36025
  );
35654
36026
  server2.registerTool(
35655
- "memory_resolve",
36027
+ "memory_reflect",
35656
36028
  {
35657
- title: "Resolve Entry",
35658
- description: "Restore an obsolete entry back to active status, or mark an entry as resolved. Reverses soft-delete.",
36029
+ title: "Reflect on Memory",
36030
+ description: "Deterministic memory audit (no LLM): tag co-occurrence themes, hub/orphan entries, near-duplicates, contradiction candidates, stale entries, and superseded-but-active entries. Signals what to link, merge, or retire.",
35659
36031
  inputSchema: {
35660
- key: external_exports.string().describe("Key or id of the entry to resolve/restore")
35661
- }
36032
+ category: external_exports.string().optional().default("").describe("Restrict analysis to one category (empty = all)."),
36033
+ limit: external_exports.number().optional().default(5).describe("Max items per section.")
36034
+ },
36035
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }
35662
36036
  },
35663
- async ({ key }) => {
36037
+ async ({ category, limit }) => {
35664
36038
  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" }] };
36039
+ const entries = parseEntries(data);
36040
+ const cap = Math.max(1, Math.min(20, limit || 5));
36041
+ if (entries.length === 0) {
36042
+ return { content: [{ type: "text", text: "Empty memory." }] };
36043
+ }
36044
+ const scope = entries.filter((e) => !category || e.category === category);
36045
+ const { adjacency } = buildGraph(entries);
36046
+ const sections = [`\u{1F9E0} Memory reflect (${scope.length}/${entries.length} entries)`];
36047
+ const degree = /* @__PURE__ */ new Map();
36048
+ for (const [k3, nbs] of adjacency) degree.set(k3, nbs.length);
36049
+ const hubs = [...degree.entries()].sort((a, b2) => b2[1] - a[1]).filter(([, d2]) => d2 >= 3);
36050
+ if (hubs.length > 0) {
36051
+ sections.push("", "\u{1F517} Hubs (connectors):");
36052
+ for (const [k3, d2] of hubs.slice(0, cap)) {
36053
+ const e = entries.find((x) => x.key === k3);
36054
+ sections.push(` ${k3} (deg ${d2}) \u2014 ${e ? e.content.slice(0, 70) : ""}`);
36055
+ }
36056
+ }
36057
+ const orphans = scope.filter((e) => e.status === "active" && !(degree.get(e.key) || 0) && e.tags.length === 0);
36058
+ if (orphans.length > 0) {
36059
+ sections.push("", "\u{1F573}\uFE0F Orphans (no links, no tags \u2014 consider linking):");
36060
+ for (const e of orphans.slice(0, cap)) {
36061
+ sections.push(` [${e.category}] ${e.key} \u2014 ${e.content.slice(0, 70)}`);
36062
+ }
36063
+ }
36064
+ const pairCount = /* @__PURE__ */ new Map();
36065
+ for (const e of scope) {
36066
+ if (e.tags.length < 2) continue;
36067
+ const t = [...e.tags].sort();
36068
+ for (let i = 0; i < t.length; i++) {
36069
+ for (let j3 = i + 1; j3 < t.length; j3++) {
36070
+ const pair = `${t[i]} + ${t[j3]}`;
36071
+ pairCount.set(pair, (pairCount.get(pair) || 0) + 1);
36072
+ }
36073
+ }
36074
+ }
36075
+ const themes = [...pairCount.entries()].sort((a, b2) => b2[1] - a[1]);
36076
+ if (themes.length > 0) {
36077
+ sections.push("", "\u{1F3F7}\uFE0F Latent themes (tag co-occurrence):");
36078
+ for (const [pair, n] of themes.slice(0, cap)) {
36079
+ sections.push(` ${pair} \u2014 ${n} entries`);
36080
+ }
36081
+ }
36082
+ const active = scope.filter((e) => e.status === "active");
36083
+ const wordSets = /* @__PURE__ */ new Map();
36084
+ for (const e of active) {
36085
+ wordSets.set(e.key, new Set(normalize(`${e.key} ${e.content} ${e.tags.join(" ")}`).split(" ").filter(Boolean)));
36086
+ }
36087
+ const dupes = [];
36088
+ const keysArr = active.map((e) => e.key);
36089
+ for (let i = 0; i < keysArr.length; i++) {
36090
+ for (let j3 = i + 1; j3 < keysArr.length; j3++) {
36091
+ const wa2 = wordSets.get(keysArr[i]);
36092
+ const wb2 = wordSets.get(keysArr[j3]);
36093
+ const inter = new Set([...wa2].filter((w3) => wb2.has(w3)));
36094
+ const union2 = /* @__PURE__ */ new Set([...wa2, ...wb2]);
36095
+ const sim = union2.size > 0 ? inter.size / union2.size : 0;
36096
+ if (sim > 0.5) dupes.push({ a: keysArr[i], b: keysArr[j3], sim });
36097
+ }
36098
+ }
36099
+ if (dupes.length > 0) {
36100
+ sections.push("", "\u267B\uFE0F Near-duplicates (merge candidates):");
36101
+ for (const d2 of dupes.sort((x, y2) => y2.sim - x.sim).slice(0, cap)) {
36102
+ sections.push(` ${d2.a} \u2194 ${d2.b} (${(d2.sim * 100).toFixed(0)}% overlap)`);
36103
+ }
36104
+ }
36105
+ const NEGATION = /\b(no longer|never|not|no|doesn'?t|don'?t|shouldn'?t|cannot|can'?t|instead of|contradicts|replaces|deprecated|broken|fails|wrong|incorrect)\b/i;
36106
+ const contradictions = [];
36107
+ for (let i = 0; i < active.length; i++) {
36108
+ for (let j3 = i + 1; j3 < active.length; j3++) {
36109
+ const a = active[i], b2 = active[j3];
36110
+ if (a.category !== b2.category) continue;
36111
+ const shared = a.tags.filter((t) => b2.tags.includes(t)).length;
36112
+ if (shared < 2) continue;
36113
+ const aNeg = NEGATION.test(a.content);
36114
+ const bNeg = NEGATION.test(b2.content);
36115
+ if (aNeg !== bNeg) {
36116
+ contradictions.push(`${a.key} \u2194 ${b2.key} [${a.category}] (${shared} shared tags, split polarity)`);
36117
+ }
36118
+ }
36119
+ }
36120
+ if (contradictions.length > 0) {
36121
+ sections.push("", "\u26A1 Contradiction candidates (verify):");
36122
+ for (const c2 of contradictions.slice(0, cap)) {
36123
+ sections.push(` ${c2}`);
36124
+ }
36125
+ }
36126
+ const now = Date.now();
36127
+ const stale = active.filter((e) => {
36128
+ if (e.tags.includes("private")) return false;
36129
+ if (e.ttl && isExpiredLocal(e.ttl)) return true;
36130
+ if (!e.date) return false;
36131
+ const ageDays = (now - (/* @__PURE__ */ new Date(`${e.date}T00:00:00`)).getTime()) / 864e5;
36132
+ const lastAccessDays = e.lastAccessed ? (now - new Date(e.lastAccessed).getTime()) / 864e5 : ageDays;
36133
+ return ageDays > 120 && lastAccessDays > 90 && e.accessed === 0;
36134
+ });
36135
+ if (stale.length > 0) {
36136
+ sections.push("", "\u{1F5C4}\uFE0F Stale (archive candidates):");
36137
+ for (const e of stale.sort((a, b2) => a.date.localeCompare(b2.date)).slice(0, cap)) {
36138
+ sections.push(` [${e.category}] ${e.key} \u2014 ${e.content.slice(0, 70)}`);
36139
+ }
35669
36140
  }
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;
36141
+ const pending = entries.filter((e) => e.status === "active" && (e.tags.includes("superseded") || typedLinks(e.links).some((l) => l.type === "superseded_by")));
36142
+ if (pending.length > 0) {
36143
+ sections.push("", "\u{1F50E} Superseded tag but still active (fix with memory_forget action: 'supersede'):");
36144
+ for (const e of pending.slice(0, cap)) {
36145
+ sections.push(` [${e.category}] ${e.key}`);
35684
36146
  }
35685
36147
  }
35686
- if (!found) {
35687
- return { content: [{ type: "text", text: `"${key}" not found in memory.` }] };
36148
+ const drafts = entries.filter((e) => e.status === "draft");
36149
+ if (drafts.length > 0) {
36150
+ sections.push("", "\u{1F4DD} Drafts pending review (promote with memory_promote / memory_forget action: 'restore'):");
36151
+ for (const e of drafts.slice(0, cap)) {
36152
+ sections.push(` [${e.category}] ${e.key} \u2014 ${e.content.slice(0, 70)}`);
36153
+ }
35688
36154
  }
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}` }] };
36155
+ return { content: [{ type: "text", text: sections.join("\n") }] };
35692
36156
  }
35693
36157
  );
35694
36158
  server2.registerTool(
35695
- "memory_suppress",
36159
+ "memory_promote",
35696
36160
  {
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.",
36161
+ title: "Promote Observations",
36162
+ description: "Heuristic auto-promote from the capture log (no LLM). Each observation gets a deterministic confidence score; high-confidence ones promote as active entries, low-confidence (\u2264 minConfidence) become reviewable drafts. Opt-in: run with dryRun: true first.",
35699
36163
  inputSchema: {
35700
- key: external_exports.string().describe("Key or id of the entry to suppress")
35701
- }
36164
+ dryRun: external_exports.boolean().optional().default(true).describe("If true, only preview what would be promoted (no writes)."),
36165
+ minConfidence: external_exports.number().optional().default(0.65).describe("Observations at or below this confidence become drafts; above it become active entries."),
36166
+ max: external_exports.number().optional().default(5).describe("Maximum observations to promote."),
36167
+ days: external_exports.number().optional().default(7).describe("Only consider observations from the last N days.")
36168
+ },
36169
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false }
35702
36170
  },
35703
- async ({ key }) => {
36171
+ async ({ dryRun, minConfidence, max, days }) => {
36172
+ const obs = readObservations();
36173
+ if (obs.length === 0) {
36174
+ return { content: [{ type: "text", text: "No captured activity. Enable with `toon-memory capture on`." }] };
36175
+ }
36176
+ const cutoff = Date.now() - (days || 7) * 864e5;
36177
+ const recent = obs.filter((o) => new Date(o.ts).getTime() >= cutoff);
35704
36178
  const data = readMemory();
36179
+ const existing = parseEntries(data);
36180
+ const existingKeys = new Set(existing.map((e) => e.key));
36181
+ const existingWords = existing.map((e) => new Set(normalize(`${e.key} ${e.content} ${e.tags.join(" ")}`).split(" ").filter(Boolean)));
36182
+ const confidence = (o) => {
36183
+ const summary = (o.summary || "").trim();
36184
+ if (!summary) return 0.1;
36185
+ let c2 = 0.5;
36186
+ const len = summary.length;
36187
+ if (len >= 40 && len <= 300) c2 += 0.1;
36188
+ else if (len < 40) c2 -= 0.1;
36189
+ if (o.file) c2 += 0.15;
36190
+ const tool = (o.tool || "").toLowerCase();
36191
+ if (["edit", "write", "create", "bash", "git", "npm"].includes(tool)) c2 += 0.1;
36192
+ else if (["read", "grep", "glob", "search", "ls", "list"].includes(tool)) c2 -= 0.15;
36193
+ if (/\b(error|fail|bug|fix|broken|fails|failed|cannot|crash)\b/i.test(summary)) c2 += 0.1;
36194
+ if (/\b(viewed|read|opened|inspected|browsed|listed|scanned)\b/i.test(summary)) c2 -= 0.1;
36195
+ return Math.max(0.05, Math.min(1, c2));
36196
+ };
36197
+ const alreadyKnown = (o) => {
36198
+ const words = new Set(normalize(`${o.tool} ${o.summary}`).split(" ").filter(Boolean));
36199
+ if (words.size === 0) return true;
36200
+ for (const set2 of existingWords) {
36201
+ const inter = new Set([...words].filter((w3) => set2.has(w3)));
36202
+ const union2 = /* @__PURE__ */ new Set([...words, ...set2]);
36203
+ if (inter.size / union2.size > 0.5) return true;
36204
+ }
36205
+ return false;
36206
+ };
36207
+ const seen = /* @__PURE__ */ new Set();
36208
+ const candidates = recent.filter((o) => {
36209
+ const dedupKey = `${o.tool}|${o.summary}`;
36210
+ if (seen.has(dedupKey)) return false;
36211
+ seen.add(dedupKey);
36212
+ return o.summary && !alreadyKnown(o);
36213
+ }).map((o) => ({ o, conf: confidence(o) })).sort((a, b2) => b2.conf - a.conf).slice(0, max || 5);
36214
+ if (candidates.length === 0) {
36215
+ return { content: [{ type: "text", text: "\u2705 Nothing new to promote \u2014 all recent observations are already covered by memory or below threshold." }] };
36216
+ }
36217
+ const preview = candidates.map(({ o, conf }) => {
36218
+ const kind = conf <= minConfidence ? "draft" : "active";
36219
+ return ` [${kind}] ${(o.summary || "").slice(0, 90)} (conf ${conf.toFixed(2)})${o.file ? ` @ ${o.file}` : ""}`;
36220
+ });
36221
+ const kindLabel = (conf) => conf <= minConfidence ? "draft" : "active";
36222
+ if (dryRun) {
36223
+ return {
36224
+ content: [{
36225
+ type: "text",
36226
+ text: `\u{1F50D} Dry run \u2014 ${candidates.length} candidate(s) from the last ${days || 7}d (threshold ${minConfidence}):
36227
+
36228
+ ${preview.join("\n")}
36229
+
36230
+ Run with dryRun: false to promote.`
36231
+ }]
36232
+ };
36233
+ }
36234
+ const date5 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
35705
36235
  const lines = data.split("\n");
35706
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
36236
+ let headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35707
36237
  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
- }
36238
+ lines.push(`[0|]`);
36239
+ headerIdx = lines.length - 1;
35723
36240
  }
35724
- if (!found) {
35725
- return { content: [{ type: "text", text: `"${key}" not found in memory.` }] };
36241
+ const match = lines[headerIdx].match(/\[(\d+)\|/);
36242
+ let count = match ? parseInt(match[1]) : 0;
36243
+ let promoted = 0;
36244
+ let drafted = 0;
36245
+ const actions = [];
36246
+ for (const { o, conf } of candidates) {
36247
+ const key = o.summary.toLowerCase().replace(/[^a-z0-9\s]/g, "").split(/\s+/).filter(Boolean).slice(0, 4).join("-").slice(0, 40) || `observation-${Date.now().toString(36)}`;
36248
+ if (existingKeys.has(key)) continue;
36249
+ const newId = generateId();
36250
+ const status = kindLabel(conf);
36251
+ const tags = ["captured", `${o.agent || "agent"}`];
36252
+ if (status === "draft") tags.push("draft");
36253
+ const content = (o.summary || "").slice(0, 500);
36254
+ const quality = qualityScore(tags.join(";"), "", content, date5);
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);
36257
+ count++;
36258
+ existingKeys.add(key);
36259
+ if (status === "draft") drafted++;
36260
+ else promoted++;
36261
+ actions.push(` [${status}] ${key} (conf ${conf.toFixed(2)})`);
35726
36262
  }
36263
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count}|`);
35727
36264
  writeMemory(lines.join("\n"));
35728
- return { content: [{ type: "text", text: `"${key}" suppressed. Use memory_resolve(key: "${key}") to restore.` }] };
36265
+ return {
36266
+ content: [{
36267
+ type: "text",
36268
+ text: `\u{1F4E4} Promoted ${promoted} active + ${drafted} draft from the capture log.
36269
+
36270
+ ${actions.join("\n")}
36271
+
36272
+ Drafts are hidden from recalls until promoted \u2014 use memory_forget(key, action: 'restore') to activate, or review with memory_reflect.`
36273
+ }]
36274
+ };
35729
36275
  }
35730
36276
  );
35731
36277
  K3(
@@ -35737,6 +36283,7 @@ ${formatted}` }]
35737
36283
  inputSchema: {
35738
36284
  query: external_exports.string().optional().default("").describe("Optional search query to highlight entries in the viewer")
35739
36285
  },
36286
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
35740
36287
  _meta: { ui: { resourceUri: "ui://viewer" } }
35741
36288
  },
35742
36289
  async ({ query }) => {
@@ -46365,6 +46912,7 @@ function Lk(e) {
46365
46912
  }
46366
46913
 
46367
46914
  // src/mcp/resources.ts
46915
+ init_utils();
46368
46916
  init_quality();
46369
46917
 
46370
46918
  // src/viewer/data.ts
@@ -47346,7 +47894,7 @@ function registerResources(server2) {
47346
47894
  const data = readMemory();
47347
47895
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
47348
47896
  const entries = lines.map((l) => {
47349
- const parts = l.trim().split("|");
47897
+ const parts = parseToonLine(l);
47350
47898
  return { category: parts[1] || "unknown", ttl: parts[7] || "" };
47351
47899
  });
47352
47900
  const byCategory = {};
@@ -47391,7 +47939,7 @@ function registerResources(server2) {
47391
47939
 
47392
47940
  // src/mcp/server.ts
47393
47941
  var server = new McpServer(
47394
- { name: "toon-memory", version: "3.6.1" },
47942
+ { name: "toon-memory", version: "4.1.0" },
47395
47943
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true }, experimental: { "io.modelcontextprotocol/ui": {} } } }
47396
47944
  );
47397
47945
  var s = server.server;
@@ -47403,7 +47951,7 @@ s.setRequestHandler(InitializeRequestSchema, async (request) => {
47403
47951
  return {
47404
47952
  protocolVersion,
47405
47953
  capabilities: s.getCapabilities(),
47406
- serverInfo: { name: "toon-memory", version: "3.6.1" },
47954
+ serverInfo: { name: "toon-memory", version: "4.1.0" },
47407
47955
  ...s._instructions && { instructions: s._instructions }
47408
47956
  };
47409
47957
  });