toon-memory 3.3.1 → 3.5.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
@@ -22175,7 +22175,8 @@ function parseEntries(data) {
22175
22175
  ttl: ttl || "",
22176
22176
  accessed: accessedRaw ? parseInt(accessedRaw) || 0 : 0,
22177
22177
  links: (linksRaw || "").split(/[\s;]+/).map((t) => t.trim()).filter(Boolean),
22178
- lastAccessed: parts.length > 12 ? parts[12] || "" : ""
22178
+ lastAccessed: parts.length > 12 ? parts[12] || "" : "",
22179
+ priority: parts.length > 13 ? parseInt(parts[13]) || 0 : 0
22179
22180
  });
22180
22181
  }
22181
22182
  return out;
@@ -22263,6 +22264,7 @@ function graphRecallDetailed(data, query, opts = {}) {
22263
22264
  const { adjacency, byKey } = buildGraph(entries);
22264
22265
  const hops = Math.max(1, Math.min(2, opts.hops ?? 1));
22265
22266
  const category = opts.category || "";
22267
+ const tagsFilter = opts.tags ? opts.tags.split(";").map((t) => t.trim()).filter(Boolean) : [];
22266
22268
  const from_date = opts.from_date || "";
22267
22269
  const to_date = opts.to_date || "";
22268
22270
  const qTokens = tokenize(query);
@@ -22272,6 +22274,7 @@ function graphRecallDetailed(data, query, opts = {}) {
22272
22274
  const seedKeys = /* @__PURE__ */ new Set();
22273
22275
  for (const e of entries) {
22274
22276
  if (category && e.category !== category) continue;
22277
+ if (tagsFilter.length > 0 && !tagsFilter.every((t) => e.tags.includes(t))) continue;
22275
22278
  if (from_date && e.date < from_date) continue;
22276
22279
  if (to_date && e.date > to_date) continue;
22277
22280
  if (e.ttl && isExpiredLocal(e.ttl)) continue;
@@ -22288,7 +22291,10 @@ function graphRecallDetailed(data, query, opts = {}) {
22288
22291
  const scored = [];
22289
22292
  if (seedKeys.size === 0) {
22290
22293
  scored.push(
22291
- ...[...entries].sort((a, b2) => importance(b2) - importance(a)).slice(0, opts.limit ?? 6).map((e) => ({ e, s: importance(e) }))
22294
+ ...[...entries].sort((a, b2) => {
22295
+ if (a.priority !== b2.priority) return b2.priority - a.priority;
22296
+ return importance(b2) - importance(a);
22297
+ }).slice(0, opts.limit ?? 6).map((e) => ({ e, s: importance(e) }))
22292
22298
  );
22293
22299
  } else {
22294
22300
  const best = /* @__PURE__ */ new Map();
@@ -22310,12 +22316,28 @@ function graphRecallDetailed(data, query, opts = {}) {
22310
22316
  const decay = Math.pow(DECAY, dist);
22311
22317
  let s2 = (bm25.get(k3) || 0) + W_CENT * cent.get(k3) + W_IMP * importance(e);
22312
22318
  if (seedKeys.has(k3)) s2 += SEED_BONUS;
22319
+ if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
22320
+ const entryFile = e.file.split(":")[0];
22321
+ if (opts.sessionFiles.some((f3) => f3 === entryFile)) {
22322
+ s2 *= 1.15;
22323
+ }
22324
+ }
22313
22325
  s2 *= decay;
22314
- return { e, s: s2 };
22315
- }).sort((a, b2) => b2.s - a.s).slice(0, opts.limit ?? 6)
22326
+ return { e, s: s2, priority: e.priority };
22327
+ }).sort((a, b2) => {
22328
+ if (a.priority !== b2.priority) return b2.priority - a.priority;
22329
+ return b2.s - a.s;
22330
+ }).slice(0, opts.limit ?? 6)
22316
22331
  );
22317
22332
  }
22318
22333
  selected = scored.map((x) => x.e);
22334
+ const pinnedKeys = new Set(entries.filter((e) => e.priority > 0).map((e) => e.key));
22335
+ const inResult = new Set(selected.map((e) => e.key));
22336
+ const toInject = [...pinnedKeys].filter((k3) => !inResult.has(k3) && byKey.has(k3)).map((k3) => byKey.get(k3)).sort((a, b2) => b2.priority - a.priority);
22337
+ for (const e of toInject) {
22338
+ selected.unshift(e);
22339
+ scored.unshift({ e, s: 999 });
22340
+ }
22319
22341
  const subAdj = /* @__PURE__ */ new Map();
22320
22342
  for (const e of selected) {
22321
22343
  subAdj.set(
@@ -22338,13 +22360,14 @@ function renderCompact(entries, opts = {}) {
22338
22360
  if (!isSeed && e.content.length > snippetLen) {
22339
22361
  body = e.content.slice(0, snippetLen).trimEnd() + "\u2026";
22340
22362
  }
22363
+ const tag = e.priority > 0 ? e.priority > 1 ? ` \u{1F4CC}${e.priority}` : " \u{1F4CC}" : "";
22341
22364
  const tags = e.tags.length ? ` \xB7 tags: ${e.tags.join(";")}` : "";
22342
22365
  let edges = "";
22343
22366
  if (opts.adjacency) {
22344
22367
  const nb2 = (opts.adjacency.get(e.key) || []).map((k3) => index.get(k3)).filter((x) => typeof x === "number");
22345
22368
  if (nb2.length) edges = ` \xB7 edges: ->${nb2.join(", ->")}`;
22346
22369
  }
22347
- return `[${n}] ${e.category}/${e.key}
22370
+ return `[${n}] ${e.category}/${e.key}${tag}
22348
22371
  ${body}${tags}${edges}`;
22349
22372
  }).join("\n\n");
22350
22373
  }
@@ -22445,8 +22468,11 @@ function mergeEntries(existingLine, newLine) {
22445
22468
  const existingLastAccessed = ep2.length > 12 ? ep2[12] || "" : "";
22446
22469
  const newLastAccessed = np2.length > 12 ? np2[12] || "" : "";
22447
22470
  const lastAccessed = newLastAccessed > existingLastAccessed ? newLastAccessed : existingLastAccessed;
22471
+ const existingPriority = ep2.length > 13 ? parseInt(ep2[13]) || 0 : 0;
22472
+ const newPriority = np2.length > 13 ? parseInt(np2[13]) || 0 : 0;
22473
+ const priority = Math.max(existingPriority, newPriority);
22448
22474
  const quality = qualityScore(mergedTags, mergedLinks, content, date5, accessed, lastAccessed);
22449
- return `${id2}|${category}|${key}|${content}|${file2}|${mergedTags}|${date5}|${ttl}|${accessed}|${mergedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}`;
22475
+ return `${id2}|${category}|${key}|${content}|${file2}|${mergedTags}|${date5}|${ttl}|${accessed}|${mergedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}|${priority}`;
22450
22476
  }
22451
22477
  function generateSmartRecall(data, intent, opts = {}) {
22452
22478
  const entries = parseEntries(data);
@@ -22480,11 +22506,30 @@ function generateSmartRecall(data, intent, opts = {}) {
22480
22506
  const fileDate = mtimes.get(filePath);
22481
22507
  if (fileDate && e.date && fileDate > e.date) drift = 0.3;
22482
22508
  }
22483
- const combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift;
22484
- return { entry: e, score: combined, matchesQuery };
22485
- }).filter((x) => x.score > 0 || x.matchesQuery).sort((a, b2) => b2.score - a.score).slice(0, limit);
22509
+ let sessionBias = 0;
22510
+ if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
22511
+ const entryFile = e.file.split(":")[0];
22512
+ if (opts.sessionFiles.some((f3) => f3 === entryFile)) {
22513
+ sessionBias = 0.15;
22514
+ }
22515
+ }
22516
+ const combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias;
22517
+ return { entry: e, score: combined, matchesQuery, priority: e.priority };
22518
+ }).filter((x) => x.score > 0 || x.matchesQuery).sort((a, b2) => {
22519
+ if (a.priority !== b2.priority) return b2.priority - a.priority;
22520
+ return b2.score - a.score;
22521
+ }).slice(0, limit);
22522
+ const pinnedKeys = new Set(entries.filter((e) => e.priority > 0).map((e) => e.key));
22523
+ const inResult = new Set(scored.map((x) => x.entry.key));
22524
+ 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);
22525
+ for (const e of toInject) {
22526
+ scored.unshift({ entry: e, score: 999, matchesQuery: false, priority: e.priority });
22527
+ }
22486
22528
  if (scored.length === 0) {
22487
- const top = entries.filter((e) => !category || e.category === category).sort((a, b2) => importance(b2) - importance(a)).slice(0, limit);
22529
+ const top = entries.filter((e) => !category || e.category === category).sort((a, b2) => {
22530
+ if (a.priority !== b2.priority) return b2.priority - a.priority;
22531
+ return importance(b2) - importance(a);
22532
+ }).slice(0, limit);
22488
22533
  if (top.length === 0) return "No entries in memory.";
22489
22534
  return renderCompact(top);
22490
22535
  }
@@ -22505,7 +22550,10 @@ function generateSystemPrimer(data) {
22505
22550
  `Entries: ${entries.length}`,
22506
22551
  ""
22507
22552
  ];
22508
- const top = [...entries].filter((e) => !isPrivate(e)).sort((a, b2) => importance(b2) - importance(a)).slice(0, 5);
22553
+ const top = [...entries].filter((e) => !isPrivate(e)).sort((a, b2) => {
22554
+ if (a.priority !== b2.priority) return b2.priority - a.priority;
22555
+ return importance(b2) - importance(a);
22556
+ }).slice(0, 5);
22509
22557
  lines.push("Top memories:");
22510
22558
  for (const e of top) {
22511
22559
  const quality = qualityScore(
@@ -22517,8 +22565,9 @@ function generateSystemPrimer(data) {
22517
22565
  e.lastAccessed
22518
22566
  );
22519
22567
  const conf = quality >= 0.5 ? "high" : quality >= 0.3 ? "medium" : "low";
22568
+ const pin = e.priority > 0 ? e.priority > 1 ? ` \u{1F4CC}${e.priority}` : " \u{1F4CC}" : "";
22520
22569
  lines.push(
22521
- ` [${e.category}] ${e.key} \u2014 ${e.content.slice(0, 80)} (quality: ${conf})`
22570
+ ` [${e.category}] ${e.key}${pin} \u2014 ${e.content.slice(0, 80)} (quality: ${conf})`
22522
22571
  );
22523
22572
  }
22524
22573
  lines.push("");
@@ -22555,6 +22604,7 @@ __export(sessions_exports, {
22555
22604
  currentBranch: () => currentBranch,
22556
22605
  detectConflicts: () => detectConflicts,
22557
22606
  endSession: () => endSession,
22607
+ getCurrentSessionFiles: () => getCurrentSessionFiles,
22558
22608
  heartbeat: () => heartbeat,
22559
22609
  listSessions: () => listSessions,
22560
22610
  pruneSessions: () => pruneSessions,
@@ -22704,6 +22754,12 @@ function detectConflicts(active = listSessions().filter((s2) => s2.active)) {
22704
22754
  }
22705
22755
  return conflicts;
22706
22756
  }
22757
+ function getCurrentSessionFiles() {
22758
+ const id2 = resolveSessionId({});
22759
+ const all = listSessions();
22760
+ const mine = all.find((s2) => s2.id === id2);
22761
+ return mine ? Object.keys(mine.files) : [];
22762
+ }
22707
22763
  function coordinationView(selfId) {
22708
22764
  const all = listSessions();
22709
22765
  const active = all.filter((s2) => s2.active);
@@ -32548,7 +32604,7 @@ function ensureMemoryDir() {
32548
32604
  function ensureMemoryFile() {
32549
32605
  ensureMemoryDir();
32550
32606
  if (!existsSync2(MEMORY_FILE)) {
32551
- writeFileSync2(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence}:\n");
32607
+ writeFileSync2(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence|lastAccessed|pinned}:\n");
32552
32608
  }
32553
32609
  }
32554
32610
 
@@ -33945,12 +34001,14 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
33945
34001
  to_date: external_exports.string().optional().default("").describe("End date filter (YYYY-MM-DD)"),
33946
34002
  mode: external_exports.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall: expands the related-entry subgraph from matches (more precise, fewer tokens)."),
33947
34003
  hops: external_exports.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
33948
- 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.")
34004
+ compact: external_exports.boolean().optional().default(false).describe("Token-efficient output: numeric indices (1, 2), omits id/date/file (keeps tags), edges as '->2', truncates graph neighbors to a snippet. Does not mutate .toon file."),
34005
+ bias: external_exports.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default).")
33949
34006
  }
33950
34007
  },
33951
- async ({ query, category, from_date, to_date, mode, hops, compact }) => {
34008
+ async ({ query, category, from_date, to_date, mode, hops, compact, bias }) => {
33952
34009
  const data = readMemory();
33953
- const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops });
34010
+ const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
34011
+ const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, sessionFiles });
33954
34012
  if (detail.entries.length === 0) {
33955
34013
  return { content: [{ type: "text", text: `No results found for "${query}"` }] };
33956
34014
  }
@@ -33966,7 +34024,8 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
33966
34024
  const formatted = detail.entries.map((r2) => {
33967
34025
  const links = r2.links.length ? `
33968
34026
  links: ${r2.links.join(", ")}` : "";
33969
- return `[${r2.category}] ${r2.key} (${r2.id})
34027
+ const pin = r2.priority > 0 ? r2.priority > 1 ? ` \u{1F4CC}${r2.priority}` : " \u{1F4CC}" : "";
34028
+ return `[${r2.category}] ${r2.key}${pin} (${r2.id})
33970
34029
  ${r2.content}
33971
34030
  File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}`;
33972
34031
  }).join("\n\n");
@@ -34058,6 +34117,37 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34058
34117
  return { key: parts[2], accessed: parts.length > 8 ? parseInt(parts[8]) || 0 : 0, quality: parts[10] || "" };
34059
34118
  }).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})`)
34060
34119
  ];
34120
+ const coldEntries = lines.filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")).map((l) => {
34121
+ const p2 = l.trim().split("|");
34122
+ return {
34123
+ key: p2[2],
34124
+ cat: p2[1],
34125
+ quality: parseFloat(p2[10]) || 0,
34126
+ accessed: p2.length > 8 ? parseInt(p2[8]) || 0 : 0,
34127
+ lastAccessed: p2.length > 12 ? p2[12] || "" : "",
34128
+ date: p2[6] || ""
34129
+ };
34130
+ }).filter((e) => {
34131
+ if (e.accessed >= 2) return false;
34132
+ if (e.quality < 0.7) return false;
34133
+ const lastDate = e.lastAccessed || e.date;
34134
+ if (!lastDate) return false;
34135
+ const daysSinceLastAccess = (Date.now() - new Date(lastDate).getTime()) / 864e5;
34136
+ return daysSinceLastAccess > 30;
34137
+ }).sort((a, b2) => b2.quality - a.quality);
34138
+ if (coldEntries.length > 0) {
34139
+ stats.push(
34140
+ "",
34141
+ `Cold memories (${coldEntries.length}):`,
34142
+ ...coldEntries.slice(0, 5).map((e) => {
34143
+ const lastDate = e.lastAccessed || e.date;
34144
+ const daysSince = Math.round((Date.now() - new Date(lastDate).getTime()) / 864e5);
34145
+ return ` ${e.key} (Q: ${e.quality.toFixed(2)}) \u2014 ${daysSince}d since last access`;
34146
+ }),
34147
+ "",
34148
+ "\u{1F4A1} Run memory_archive() to archive cold entries."
34149
+ );
34150
+ }
34061
34151
  return { content: [{ type: "text", text: stats.join("\n") }] };
34062
34152
  }
34063
34153
  );
@@ -34141,13 +34231,15 @@ ${formatted}` }] };
34141
34231
  inputSchema: {
34142
34232
  intent: external_exports.string().describe("Describe what you need to know (e.g. 'database schema for backend')"),
34143
34233
  limit: external_exports.number().optional().default(8).describe("Maximum entries to return"),
34144
- category: external_exports.string().optional().default("").describe("Filter by category (empty = all)")
34234
+ category: external_exports.string().optional().default("").describe("Filter by category (empty = all)"),
34235
+ bias: external_exports.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default).")
34145
34236
  }
34146
34237
  },
34147
- async ({ intent, limit, category }) => {
34238
+ async ({ intent, limit, category, bias }) => {
34148
34239
  const data = readMemory();
34149
34240
  const mtimes = fileMtimes();
34150
- const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes });
34241
+ const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
34242
+ const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles });
34151
34243
  return { content: [{ type: "text", text: result }] };
34152
34244
  }
34153
34245
  );
@@ -35021,14 +35113,30 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
35021
35113
  }
35022
35114
  }
35023
35115
  if (dryRun) {
35116
+ const previewLines = [
35117
+ `\u{1F50D} Dry run \u2014 ${mergePairs.length} merge candidate(s) found:`,
35118
+ ""
35119
+ ];
35120
+ for (const pair of mergePairs) {
35121
+ const a = parsed[pair.a], b2 = parsed[pair.b];
35122
+ const mergedTags = [.../* @__PURE__ */ new Set([...a.tags.split(";"), ...b2.tags.split(";")])].filter(Boolean).join(";");
35123
+ const longer = a.content.length >= b2.content.length ? a : b2;
35124
+ const shorter = a.content.length < b2.content.length ? a : b2;
35125
+ previewLines.push(` \u2500\u2500 Pair: [${a.cat}] ${a.key} \u2194 [${b2.cat}] ${b2.key}`);
35126
+ previewLines.push(` Similarity: ${(pair.similarity * 100).toFixed(0)}%`);
35127
+ previewLines.push(` A tags: ${a.tags || "(none)"}`);
35128
+ previewLines.push(` B tags: ${b2.tags || "(none)"}`);
35129
+ previewLines.push(` \u2192 Merged tags: ${mergedTags || "(none)"}`);
35130
+ previewLines.push(` \u2192 Content winner: "${longer.key}" (${longer.content.length} chars vs ${shorter.content.length})`);
35131
+ previewLines.push(` \u2192 Result content: ${longer.content.slice(0, 120)}${longer.content.length > 120 ? "\u2026" : ""}`);
35132
+ previewLines.push("");
35133
+ }
35134
+ previewLines.push(`Would merge ${merged.size} entries into ${entries.length - merged.size} entries.`);
35135
+ previewLines.push("Run with dryRun: false to apply.");
35024
35136
  return {
35025
35137
  content: [{
35026
35138
  type: "text",
35027
- text: `\u{1F50D} Dry run \u2014 would merge ${merged.size} entries:
35028
-
35029
- ${mergeActions.join("\n")}
35030
-
35031
- Run with dryRun: false to apply.`
35139
+ text: previewLines.join("\n")
35032
35140
  }]
35033
35141
  };
35034
35142
  }
@@ -35113,6 +35221,292 @@ ${mergeActions.join("\n")}`
35113
35221
  };
35114
35222
  }
35115
35223
  );
35224
+ server2.registerTool(
35225
+ "memory_checkpoint",
35226
+ {
35227
+ title: "Session Checkpoint",
35228
+ 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.",
35229
+ inputSchema: {
35230
+ note: external_exports.string().optional().default("").describe("Optional summary of what was accomplished in this session.")
35231
+ }
35232
+ },
35233
+ async ({ note }) => {
35234
+ const data = readMemory();
35235
+ const lines = data.split("\n");
35236
+ let headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35237
+ if (headerIdx === -1) {
35238
+ lines.push(`[0|]`);
35239
+ headerIdx = lines.length - 1;
35240
+ }
35241
+ const sessionId = resolveSessionId({});
35242
+ const shortId = sessionId.replace(/^proc-/, "").slice(0, 8);
35243
+ const key = `checkpoint-${shortId}`;
35244
+ const now = /* @__PURE__ */ new Date();
35245
+ const date5 = now.toISOString().split("T")[0];
35246
+ const ttl7d = new Date(now.getTime() + 7 * 864e5).toISOString().split("T")[0];
35247
+ const sessions = await Promise.resolve().then(() => (init_sessions(), sessions_exports));
35248
+ const allSessions = sessions.listSessions();
35249
+ const mySession = allSessions.find((s2) => s2.id === sessionId);
35250
+ const branch = mySession?.branch || currentBranch();
35251
+ const files = mySession ? Object.keys(mySession.files) : [];
35252
+ const fileList = files.length > 0 ? `
35253
+ Files touched: ${files.slice(0, 10).join(", ")}${files.length > 10 ? ` (+${files.length - 10} more)` : ""}` : "";
35254
+ const content = `Session checkpoint (${date5})${note ? `
35255
+ Note: ${note}` : ""}
35256
+ Branch: ${branch}${fileList}`;
35257
+ let existingIdx = -1;
35258
+ let existingId = "";
35259
+ for (let i = headerIdx + 1; i < lines.length; i++) {
35260
+ const line = lines[i];
35261
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
35262
+ if (line.startsWith(" summaries:")) break;
35263
+ const parts = line.trim().split("|");
35264
+ if (parts[2] === key) {
35265
+ existingIdx = i;
35266
+ existingId = parts[0];
35267
+ break;
35268
+ }
35269
+ }
35270
+ if (existingIdx !== -1) {
35271
+ const parts = lines[existingIdx].trim().split("|");
35272
+ parts[3] = content;
35273
+ parts[6] = date5;
35274
+ parts[7] = ttl7d;
35275
+ while (parts.length < 14) parts.push("");
35276
+ parts[13] = "0";
35277
+ lines[existingIdx] = ` ${parts.join("|")}`;
35278
+ writeMemory(lines.join("\n"));
35279
+ return {
35280
+ content: [{ type: "text", text: `\u{1F4DD} Checkpoint updated: ${key}
35281
+ \u23F0 TTL: ${ttl7d} (7d)
35282
+ ${note ? `
35283
+ ${note}` : ""}` }]
35284
+ };
35285
+ }
35286
+ const newId = `cp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
35287
+ const quality = qualityScore("checkpoint", "", content, date5);
35288
+ const newEntry = `${newId}|knowledge|${key}|${content}||checkpoint|${date5}|${ttl7d}|0||${quality.toFixed(2)}|1|${now.toISOString()}|0`;
35289
+ const match = lines[headerIdx].match(/\[(\d+)\|/);
35290
+ const count = match ? parseInt(match[1]) : 0;
35291
+ lines.splice(headerIdx + 1, 0, ` ${newEntry}`);
35292
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`);
35293
+ writeMemory(lines.join("\n"));
35294
+ return {
35295
+ content: [{
35296
+ type: "text",
35297
+ text: `\u{1F4DD} Checkpoint saved: ${key} (${newId})
35298
+ \u23F0 TTL: ${ttl7d} (7d)${note ? `
35299
+
35300
+ ${note}` : ""}`
35301
+ }]
35302
+ };
35303
+ }
35304
+ );
35305
+ server2.registerTool(
35306
+ "memory_pin",
35307
+ {
35308
+ title: "Pin Entry",
35309
+ description: "Pin a memory entry with priority level (1-5). Higher priority entries appear first in recalls. Default: 1. Useful for critical decisions, project rules, or frequently-needed context.",
35310
+ inputSchema: {
35311
+ key: external_exports.string().describe("Key or id of the entry to pin"),
35312
+ priority: external_exports.number().optional().default(1).describe("Priority level 1-5 (5 = highest). Default: 1.")
35313
+ }
35314
+ },
35315
+ async ({ key, priority }) => {
35316
+ const data = readMemory();
35317
+ const lines = data.split("\n");
35318
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35319
+ if (headerIdx === -1) {
35320
+ return { content: [{ type: "text", text: "No entries in memory" }] };
35321
+ }
35322
+ const clampedPriority = Math.max(1, Math.min(5, Math.round(priority)));
35323
+ let found = false;
35324
+ for (let i = headerIdx + 1; i < lines.length; i++) {
35325
+ const line = lines[i];
35326
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
35327
+ if (line.startsWith(" summaries:")) break;
35328
+ const parts = line.trim().split("|");
35329
+ if (parts[0] === key || parts[2] === key) {
35330
+ while (parts.length < 14) parts.push("");
35331
+ parts[13] = String(clampedPriority);
35332
+ lines[i] = ` ${parts.join("|")}`;
35333
+ found = true;
35334
+ break;
35335
+ }
35336
+ }
35337
+ if (!found) {
35338
+ return { content: [{ type: "text", text: `"${key}" not found in memory.` }] };
35339
+ }
35340
+ writeMemory(lines.join("\n"));
35341
+ return { content: [{ type: "text", text: `\u{1F4CC}${clampedPriority > 1 ? clampedPriority : ""} Pinned "${key}" at priority ${clampedPriority}. It will now appear first in recalls.` }] };
35342
+ }
35343
+ );
35344
+ server2.registerTool(
35345
+ "memory_unpin",
35346
+ {
35347
+ title: "Unpin Entry",
35348
+ description: "Remove the pin from a memory entry so it returns to normal ranking.",
35349
+ inputSchema: {
35350
+ key: external_exports.string().describe("Key or id of the entry to unpin")
35351
+ }
35352
+ },
35353
+ async ({ key }) => {
35354
+ const data = readMemory();
35355
+ const lines = data.split("\n");
35356
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35357
+ if (headerIdx === -1) {
35358
+ return { content: [{ type: "text", text: "No entries in memory" }] };
35359
+ }
35360
+ let found = false;
35361
+ for (let i = headerIdx + 1; i < lines.length; i++) {
35362
+ const line = lines[i];
35363
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
35364
+ if (line.startsWith(" summaries:")) break;
35365
+ const parts = line.trim().split("|");
35366
+ if (parts[0] === key || parts[2] === key) {
35367
+ if (parts.length > 13) {
35368
+ parts[13] = "0";
35369
+ lines[i] = ` ${parts.join("|")}`;
35370
+ }
35371
+ found = true;
35372
+ break;
35373
+ }
35374
+ }
35375
+ if (!found) {
35376
+ return { content: [{ type: "text", text: `"${key}" not found in memory.` }] };
35377
+ }
35378
+ writeMemory(lines.join("\n"));
35379
+ return { content: [{ type: "text", text: `Unpinned "${key}". It will now use normal ranking.` }] };
35380
+ }
35381
+ );
35382
+ server2.registerTool(
35383
+ "memory_search",
35384
+ {
35385
+ title: "Unified Search",
35386
+ description: "Search memory with combined filters: text query, category, tags, and date range. Returns ranked results.",
35387
+ inputSchema: {
35388
+ query: external_exports.string().describe("Text to search for"),
35389
+ category: external_exports.string().optional().default("").describe("Filter by category (empty = all)"),
35390
+ tags: external_exports.string().optional().default("").describe("Semicolon-separated tags; entry must have ALL specified tags"),
35391
+ from_date: external_exports.string().optional().default("").describe("Start date filter (YYYY-MM-DD or relative like 7d)"),
35392
+ to_date: external_exports.string().optional().default("").describe("End date filter (YYYY-MM-DD)"),
35393
+ limit: external_exports.number().optional().default(6).describe("Maximum entries to return"),
35394
+ mode: external_exports.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall."),
35395
+ hops: external_exports.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
35396
+ compact: external_exports.boolean().optional().default(false).describe("Token-efficient output"),
35397
+ bias: external_exports.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default).")
35398
+ }
35399
+ },
35400
+ async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact, bias }) => {
35401
+ const data = readMemory();
35402
+ const resolvedFrom = from_date ? parseRelativeDate(from_date) : "";
35403
+ const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
35404
+ const detail = graphRecallDetailed(data, query, {
35405
+ category: category || void 0,
35406
+ tags: tags || void 0,
35407
+ from_date: resolvedFrom || void 0,
35408
+ to_date: to_date || void 0,
35409
+ hops,
35410
+ limit,
35411
+ sessionFiles
35412
+ });
35413
+ if (detail.entries.length === 0) {
35414
+ return { content: [{ type: "text", text: `No results found for "${query}"` }] };
35415
+ }
35416
+ bumpAccessed(detail.entries.map((e) => e.id));
35417
+ if (compact) {
35418
+ const formatted2 = renderCompact(detail.entries, {
35419
+ adjacency: detail.adjacency,
35420
+ seeds: detail.seeds,
35421
+ snippetLen: 90
35422
+ });
35423
+ return { content: [{ type: "text", text: `\u{1F50D} Search: "${query}"
35424
+
35425
+ ${formatted2}` }] };
35426
+ }
35427
+ const formatted = detail.entries.map((r2) => {
35428
+ const links = r2.links.length ? `
35429
+ links: ${r2.links.join(", ")}` : "";
35430
+ const pin = r2.priority > 0 ? r2.priority > 1 ? ` \u{1F4CC}${r2.priority}` : " \u{1F4CC}" : "";
35431
+ return `[${r2.category}] ${r2.key}${pin} (${r2.id})
35432
+ ${r2.content}
35433
+ File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}`;
35434
+ }).join("\n\n");
35435
+ let filterInfo = "";
35436
+ if (category) filterInfo += ` category: ${category}`;
35437
+ if (tags) filterInfo += ` tags: ${tags}`;
35438
+ if (from_date) filterInfo += ` from: ${from_date}`;
35439
+ if (to_date) filterInfo += ` to: ${to_date}`;
35440
+ return {
35441
+ content: [{ type: "text", text: `\u{1F50D} Search results${filterInfo}:
35442
+
35443
+ ${formatted}` }]
35444
+ };
35445
+ }
35446
+ );
35447
+ server2.registerTool(
35448
+ "memory_tag",
35449
+ {
35450
+ title: "Batch Tag Operations",
35451
+ description: "Batch add, remove, or set tags on one or more memory entries by key or id.",
35452
+ inputSchema: {
35453
+ action: external_exports.enum(["add", "remove", "set"]).describe("'add': merge tags (union). 'remove': remove specified tags. 'set': replace all tags."),
35454
+ tags: external_exports.string().describe("Semicolon-separated tags to apply"),
35455
+ ids: external_exports.string().describe("Comma or space-separated entry keys or IDs to modify")
35456
+ }
35457
+ },
35458
+ async ({ action, tags, ids }) => {
35459
+ const data = readMemory();
35460
+ const lines = data.split("\n");
35461
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35462
+ if (headerIdx === -1) {
35463
+ return { content: [{ type: "text", text: "No entries in memory." }] };
35464
+ }
35465
+ const targetIds = ids.split(/[\s,]+/).filter(Boolean);
35466
+ const targetSet = new Set(targetIds);
35467
+ const tagsToApply = tags.split(";").map((t) => t.trim()).filter(Boolean);
35468
+ if (tagsToApply.length === 0) {
35469
+ return { content: [{ type: "text", text: "No tags provided." }] };
35470
+ }
35471
+ let modified = 0;
35472
+ const modifiedKeys = [];
35473
+ for (let i = headerIdx + 1; i < lines.length; i++) {
35474
+ const line = lines[i];
35475
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
35476
+ if (line.startsWith(" summaries:")) break;
35477
+ const parts = line.trim().split("|");
35478
+ const entryId = parts[0];
35479
+ const entryKey = parts[2];
35480
+ if (!targetSet.has(entryId) && !targetSet.has(entryKey)) continue;
35481
+ const currentTags = (parts[5] || "").split(";").map((t) => t.trim()).filter(Boolean);
35482
+ let newTags;
35483
+ if (action === "add") {
35484
+ newTags = [.../* @__PURE__ */ new Set([...currentTags, ...tagsToApply])];
35485
+ } else if (action === "remove") {
35486
+ newTags = currentTags.filter((t) => !tagsToApply.includes(t));
35487
+ } else {
35488
+ newTags = [...tagsToApply];
35489
+ }
35490
+ parts[5] = newTags.join(";");
35491
+ lines[i] = ` ${parts.join("|")}`;
35492
+ modified++;
35493
+ modifiedKeys.push(entryKey);
35494
+ }
35495
+ if (modified === 0) {
35496
+ return { content: [{ type: "text", text: `No entries found matching: ${targetIds.join(", ")}` }] };
35497
+ }
35498
+ writeMemory(lines.join("\n"));
35499
+ const actionLabel = action === "add" ? "Added" : action === "remove" ? "Removed" : "Set";
35500
+ return {
35501
+ content: [{
35502
+ type: "text",
35503
+ text: `\u{1F3F7}\uFE0F ${actionLabel} tags on ${modified} entries:
35504
+ Tags: ${tagsToApply.join(";")}
35505
+ Entries: ${modifiedKeys.join(", ")}`
35506
+ }]
35507
+ };
35508
+ }
35509
+ );
35116
35510
  K3(
35117
35511
  server2,
35118
35512
  "memory_visualize",
@@ -46776,7 +47170,7 @@ function registerResources(server2) {
46776
47170
 
46777
47171
  // src/mcp/server.ts
46778
47172
  var server = new McpServer(
46779
- { name: "toon-memory", version: "3.3.1" },
47173
+ { name: "toon-memory", version: "3.5.0" },
46780
47174
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true }, experimental: { "io.modelcontextprotocol/ui": {} } } }
46781
47175
  );
46782
47176
  var s = server.server;
@@ -46788,7 +47182,7 @@ s.setRequestHandler(InitializeRequestSchema, async (request) => {
46788
47182
  return {
46789
47183
  protocolVersion,
46790
47184
  capabilities: s.getCapabilities(),
46791
- serverInfo: { name: "toon-memory", version: "3.3.1" },
47185
+ serverInfo: { name: "toon-memory", version: "3.5.0" },
46792
47186
  ...s._instructions && { instructions: s._instructions }
46793
47187
  };
46794
47188
  });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "toon-memory",
3
- "version": "3.3.1",
4
- "description": "MCP server giving AI coding agents offline, token-efficient persistent memory — 29 tools, 80% fewer tool calls, recall decisions, patterns, and bugs across sessions. No LLM, no server; works with 15+ agents.",
3
+ "version": "3.5.0",
4
+ "description": "MCP server giving AI coding agents offline, token-efficient persistent memory — 35 tools, 80% fewer tool calls, recall decisions, patterns, and bugs across sessions. No LLM, no server; works with 15+ agents.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "toon-memory": "./bin/toon-memory.js"
@@ -72,7 +72,11 @@
72
72
  "toon",
73
73
  "mcp",
74
74
  "llm",
75
- "token-efficiency"
75
+ "token-efficiency",
76
+ "pin",
77
+ "search",
78
+ "tags",
79
+ "graph"
76
80
  ],
77
81
  "author": "luiggival",
78
82
  "license": "MIT",
@@ -43,6 +43,26 @@ A persistent memory system for AI coding agents. It remembers decisions, pattern
43
43
  | `context_brief` | One-call context briefing: memory + sessions + health in compact markdown |
44
44
  | `memory_encrypt` | Enable AES-256-GCM encryption |
45
45
  | `memory_decrypt` | Disable encryption and decode memory |
46
+ | `memory_backup` | Create timestamped backup of memory file |
47
+ | `context_generate` | Full project briefing: project + git + memory + sessions |
48
+ | `context_diff` | Incremental briefing since last session |
49
+ | `context_focus` | Hyper-focused briefing for a specific task |
50
+ | `context_health` | Memory health audit with score 0-100 |
51
+ | `context_export` | Export memory as markdown for system prompts |
52
+ | `memory_compress` | LLM-powered compression of selected entries |
53
+ | `memory_compress_all` | Batch compression of low-quality entries |
54
+ | `memory_primer` | Auto-generated knowledge map for session start |
55
+ | `memory_merge_sessions` | Merge observations across parallel sessions |
56
+ | `memory_export_gist` | Export memory to a private GitHub Gist |
57
+ | `memory_import_gist` | Import memory from a GitHub Gist |
58
+ | `memory_merge_similar` | Find and merge near-duplicates by Jaccard similarity |
59
+ | `memory_graph_path` | BFS shortest path between two entries |
60
+ | `memory_visualize` | Open interactive memory graph viewer |
61
+ | `memory_pin` | Pin entry with priority 1-5 for top recall placement |
62
+ | `memory_unpin` | Remove the priority flag from an entry |
63
+ | `memory_search` | Search with category, tags, and date range filters |
64
+ | `memory_tag` | Batch tag operations (add, remove, set) |
65
+ | `memory_checkpoint` | Create session snapshot with 7d TTL |
46
66
 
47
67
  ## MCP Resources
48
68