toon-memory 3.4.0 → 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
@@ -22176,7 +22176,7 @@ function parseEntries(data) {
22176
22176
  accessed: accessedRaw ? parseInt(accessedRaw) || 0 : 0,
22177
22177
  links: (linksRaw || "").split(/[\s;]+/).map((t) => t.trim()).filter(Boolean),
22178
22178
  lastAccessed: parts.length > 12 ? parts[12] || "" : "",
22179
- pinned: parts.length > 13 && parts[13] === "1"
22179
+ priority: parts.length > 13 ? parseInt(parts[13]) || 0 : 0
22180
22180
  });
22181
22181
  }
22182
22182
  return out;
@@ -22292,7 +22292,7 @@ function graphRecallDetailed(data, query, opts = {}) {
22292
22292
  if (seedKeys.size === 0) {
22293
22293
  scored.push(
22294
22294
  ...[...entries].sort((a, b2) => {
22295
- if (a.pinned !== b2.pinned) return a.pinned ? -1 : 1;
22295
+ if (a.priority !== b2.priority) return b2.priority - a.priority;
22296
22296
  return importance(b2) - importance(a);
22297
22297
  }).slice(0, opts.limit ?? 6).map((e) => ({ e, s: importance(e) }))
22298
22298
  );
@@ -22316,23 +22316,27 @@ function graphRecallDetailed(data, query, opts = {}) {
22316
22316
  const decay = Math.pow(DECAY, dist);
22317
22317
  let s2 = (bm25.get(k3) || 0) + W_CENT * cent.get(k3) + W_IMP * importance(e);
22318
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
+ }
22319
22325
  s2 *= decay;
22320
- return { e, s: s2, pinned: e.pinned };
22326
+ return { e, s: s2, priority: e.priority };
22321
22327
  }).sort((a, b2) => {
22322
- if (a.pinned !== b2.pinned) return a.pinned ? -1 : 1;
22328
+ if (a.priority !== b2.priority) return b2.priority - a.priority;
22323
22329
  return b2.s - a.s;
22324
22330
  }).slice(0, opts.limit ?? 6)
22325
22331
  );
22326
22332
  }
22327
22333
  selected = scored.map((x) => x.e);
22328
- const pinnedKeys = new Set(entries.filter((e) => e.pinned).map((e) => e.key));
22334
+ const pinnedKeys = new Set(entries.filter((e) => e.priority > 0).map((e) => e.key));
22329
22335
  const inResult = new Set(selected.map((e) => e.key));
22330
- for (const pKey of pinnedKeys) {
22331
- if (!inResult.has(pKey) && byKey.has(pKey)) {
22332
- const e = byKey.get(pKey);
22333
- selected.unshift(e);
22334
- scored.unshift({ e, s: 999 });
22335
- }
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 });
22336
22340
  }
22337
22341
  const subAdj = /* @__PURE__ */ new Map();
22338
22342
  for (const e of selected) {
@@ -22356,7 +22360,7 @@ function renderCompact(entries, opts = {}) {
22356
22360
  if (!isSeed && e.content.length > snippetLen) {
22357
22361
  body = e.content.slice(0, snippetLen).trimEnd() + "\u2026";
22358
22362
  }
22359
- const tag = e.pinned ? " \u{1F4CC}" : "";
22363
+ const tag = e.priority > 0 ? e.priority > 1 ? ` \u{1F4CC}${e.priority}` : " \u{1F4CC}" : "";
22360
22364
  const tags = e.tags.length ? ` \xB7 tags: ${e.tags.join(";")}` : "";
22361
22365
  let edges = "";
22362
22366
  if (opts.adjacency) {
@@ -22464,8 +22468,11 @@ function mergeEntries(existingLine, newLine) {
22464
22468
  const existingLastAccessed = ep2.length > 12 ? ep2[12] || "" : "";
22465
22469
  const newLastAccessed = np2.length > 12 ? np2[12] || "" : "";
22466
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);
22467
22474
  const quality = qualityScore(mergedTags, mergedLinks, content, date5, accessed, lastAccessed);
22468
- 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}`;
22469
22476
  }
22470
22477
  function generateSmartRecall(data, intent, opts = {}) {
22471
22478
  const entries = parseEntries(data);
@@ -22499,23 +22506,28 @@ function generateSmartRecall(data, intent, opts = {}) {
22499
22506
  const fileDate = mtimes.get(filePath);
22500
22507
  if (fileDate && e.date && fileDate > e.date) drift = 0.3;
22501
22508
  }
22502
- const combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift;
22503
- return { entry: e, score: combined, matchesQuery, pinned: e.pinned };
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 };
22504
22518
  }).filter((x) => x.score > 0 || x.matchesQuery).sort((a, b2) => {
22505
- if (a.pinned !== b2.pinned) return a.pinned ? -1 : 1;
22519
+ if (a.priority !== b2.priority) return b2.priority - a.priority;
22506
22520
  return b2.score - a.score;
22507
22521
  }).slice(0, limit);
22508
- const pinnedKeys = new Set(entries.filter((e) => e.pinned).map((e) => e.key));
22522
+ const pinnedKeys = new Set(entries.filter((e) => e.priority > 0).map((e) => e.key));
22509
22523
  const inResult = new Set(scored.map((x) => x.entry.key));
22510
- for (const pKey of pinnedKeys) {
22511
- if (!inResult.has(pKey)) {
22512
- const e = entries.find((en2) => en2.key === pKey);
22513
- if (e) scored.unshift({ entry: e, score: 999, matchesQuery: false, pinned: true });
22514
- }
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 });
22515
22527
  }
22516
22528
  if (scored.length === 0) {
22517
22529
  const top = entries.filter((e) => !category || e.category === category).sort((a, b2) => {
22518
- if (a.pinned !== b2.pinned) return a.pinned ? -1 : 1;
22530
+ if (a.priority !== b2.priority) return b2.priority - a.priority;
22519
22531
  return importance(b2) - importance(a);
22520
22532
  }).slice(0, limit);
22521
22533
  if (top.length === 0) return "No entries in memory.";
@@ -22539,7 +22551,7 @@ function generateSystemPrimer(data) {
22539
22551
  ""
22540
22552
  ];
22541
22553
  const top = [...entries].filter((e) => !isPrivate(e)).sort((a, b2) => {
22542
- if (a.pinned !== b2.pinned) return a.pinned ? -1 : 1;
22554
+ if (a.priority !== b2.priority) return b2.priority - a.priority;
22543
22555
  return importance(b2) - importance(a);
22544
22556
  }).slice(0, 5);
22545
22557
  lines.push("Top memories:");
@@ -22553,7 +22565,7 @@ function generateSystemPrimer(data) {
22553
22565
  e.lastAccessed
22554
22566
  );
22555
22567
  const conf = quality >= 0.5 ? "high" : quality >= 0.3 ? "medium" : "low";
22556
- const pin = e.pinned ? " \u{1F4CC}" : "";
22568
+ const pin = e.priority > 0 ? e.priority > 1 ? ` \u{1F4CC}${e.priority}` : " \u{1F4CC}" : "";
22557
22569
  lines.push(
22558
22570
  ` [${e.category}] ${e.key}${pin} \u2014 ${e.content.slice(0, 80)} (quality: ${conf})`
22559
22571
  );
@@ -22592,6 +22604,7 @@ __export(sessions_exports, {
22592
22604
  currentBranch: () => currentBranch,
22593
22605
  detectConflicts: () => detectConflicts,
22594
22606
  endSession: () => endSession,
22607
+ getCurrentSessionFiles: () => getCurrentSessionFiles,
22595
22608
  heartbeat: () => heartbeat,
22596
22609
  listSessions: () => listSessions,
22597
22610
  pruneSessions: () => pruneSessions,
@@ -22741,6 +22754,12 @@ function detectConflicts(active = listSessions().filter((s2) => s2.active)) {
22741
22754
  }
22742
22755
  return conflicts;
22743
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
+ }
22744
22763
  function coordinationView(selfId) {
22745
22764
  const all = listSessions();
22746
22765
  const active = all.filter((s2) => s2.active);
@@ -33982,12 +34001,14 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
33982
34001
  to_date: external_exports.string().optional().default("").describe("End date filter (YYYY-MM-DD)"),
33983
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)."),
33984
34003
  hops: external_exports.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
33985
- 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).")
33986
34006
  }
33987
34007
  },
33988
- async ({ query, category, from_date, to_date, mode, hops, compact }) => {
34008
+ async ({ query, category, from_date, to_date, mode, hops, compact, bias }) => {
33989
34009
  const data = readMemory();
33990
- 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 });
33991
34012
  if (detail.entries.length === 0) {
33992
34013
  return { content: [{ type: "text", text: `No results found for "${query}"` }] };
33993
34014
  }
@@ -34003,7 +34024,8 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34003
34024
  const formatted = detail.entries.map((r2) => {
34004
34025
  const links = r2.links.length ? `
34005
34026
  links: ${r2.links.join(", ")}` : "";
34006
- 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})
34007
34029
  ${r2.content}
34008
34030
  File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}`;
34009
34031
  }).join("\n\n");
@@ -34095,6 +34117,37 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34095
34117
  return { key: parts[2], accessed: parts.length > 8 ? parseInt(parts[8]) || 0 : 0, quality: parts[10] || "" };
34096
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})`)
34097
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
+ }
34098
34151
  return { content: [{ type: "text", text: stats.join("\n") }] };
34099
34152
  }
34100
34153
  );
@@ -34178,13 +34231,15 @@ ${formatted}` }] };
34178
34231
  inputSchema: {
34179
34232
  intent: external_exports.string().describe("Describe what you need to know (e.g. 'database schema for backend')"),
34180
34233
  limit: external_exports.number().optional().default(8).describe("Maximum entries to return"),
34181
- 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).")
34182
34236
  }
34183
34237
  },
34184
- async ({ intent, limit, category }) => {
34238
+ async ({ intent, limit, category, bias }) => {
34185
34239
  const data = readMemory();
34186
34240
  const mtimes = fileMtimes();
34187
- 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 });
34188
34243
  return { content: [{ type: "text", text: result }] };
34189
34244
  }
34190
34245
  );
@@ -35058,14 +35113,30 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
35058
35113
  }
35059
35114
  }
35060
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.");
35061
35136
  return {
35062
35137
  content: [{
35063
35138
  type: "text",
35064
- text: `\u{1F50D} Dry run \u2014 would merge ${merged.size} entries:
35065
-
35066
- ${mergeActions.join("\n")}
35067
-
35068
- Run with dryRun: false to apply.`
35139
+ text: previewLines.join("\n")
35069
35140
  }]
35070
35141
  };
35071
35142
  }
@@ -35150,22 +35221,105 @@ ${mergeActions.join("\n")}`
35150
35221
  };
35151
35222
  }
35152
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
+ );
35153
35305
  server2.registerTool(
35154
35306
  "memory_pin",
35155
35307
  {
35156
35308
  title: "Pin Entry",
35157
- description: "Pin a memory entry so it always appears first in recalls. Useful for critical decisions, project rules, or frequently-needed context.",
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.",
35158
35310
  inputSchema: {
35159
- key: external_exports.string().describe("Key or id of the entry to pin")
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.")
35160
35313
  }
35161
35314
  },
35162
- async ({ key }) => {
35315
+ async ({ key, priority }) => {
35163
35316
  const data = readMemory();
35164
35317
  const lines = data.split("\n");
35165
35318
  const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35166
35319
  if (headerIdx === -1) {
35167
35320
  return { content: [{ type: "text", text: "No entries in memory" }] };
35168
35321
  }
35322
+ const clampedPriority = Math.max(1, Math.min(5, Math.round(priority)));
35169
35323
  let found = false;
35170
35324
  for (let i = headerIdx + 1; i < lines.length; i++) {
35171
35325
  const line = lines[i];
@@ -35174,7 +35328,7 @@ ${mergeActions.join("\n")}`
35174
35328
  const parts = line.trim().split("|");
35175
35329
  if (parts[0] === key || parts[2] === key) {
35176
35330
  while (parts.length < 14) parts.push("");
35177
- parts[13] = "1";
35331
+ parts[13] = String(clampedPriority);
35178
35332
  lines[i] = ` ${parts.join("|")}`;
35179
35333
  found = true;
35180
35334
  break;
@@ -35184,7 +35338,7 @@ ${mergeActions.join("\n")}`
35184
35338
  return { content: [{ type: "text", text: `"${key}" not found in memory.` }] };
35185
35339
  }
35186
35340
  writeMemory(lines.join("\n"));
35187
- return { content: [{ type: "text", text: `\u{1F4CC} Pinned "${key}". It will now appear first in recalls.` }] };
35341
+ return { content: [{ type: "text", text: `\u{1F4CC}${clampedPriority > 1 ? clampedPriority : ""} Pinned "${key}" at priority ${clampedPriority}. It will now appear first in recalls.` }] };
35188
35342
  }
35189
35343
  );
35190
35344
  server2.registerTool(
@@ -35222,7 +35376,7 @@ ${mergeActions.join("\n")}`
35222
35376
  return { content: [{ type: "text", text: `"${key}" not found in memory.` }] };
35223
35377
  }
35224
35378
  writeMemory(lines.join("\n"));
35225
- return { content: [{ type: "text", text: `\u{1F4CC} Unpinned "${key}". It will now use normal ranking.` }] };
35379
+ return { content: [{ type: "text", text: `Unpinned "${key}". It will now use normal ranking.` }] };
35226
35380
  }
35227
35381
  );
35228
35382
  server2.registerTool(
@@ -35239,19 +35393,22 @@ ${mergeActions.join("\n")}`
35239
35393
  limit: external_exports.number().optional().default(6).describe("Maximum entries to return"),
35240
35394
  mode: external_exports.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall."),
35241
35395
  hops: external_exports.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
35242
- compact: external_exports.boolean().optional().default(false).describe("Token-efficient output")
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).")
35243
35398
  }
35244
35399
  },
35245
- async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact }) => {
35400
+ async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact, bias }) => {
35246
35401
  const data = readMemory();
35247
35402
  const resolvedFrom = from_date ? parseRelativeDate(from_date) : "";
35403
+ const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
35248
35404
  const detail = graphRecallDetailed(data, query, {
35249
35405
  category: category || void 0,
35250
35406
  tags: tags || void 0,
35251
35407
  from_date: resolvedFrom || void 0,
35252
35408
  to_date: to_date || void 0,
35253
35409
  hops,
35254
- limit
35410
+ limit,
35411
+ sessionFiles
35255
35412
  });
35256
35413
  if (detail.entries.length === 0) {
35257
35414
  return { content: [{ type: "text", text: `No results found for "${query}"` }] };
@@ -35270,7 +35427,7 @@ ${formatted2}` }] };
35270
35427
  const formatted = detail.entries.map((r2) => {
35271
35428
  const links = r2.links.length ? `
35272
35429
  links: ${r2.links.join(", ")}` : "";
35273
- const pin = r2.pinned ? " \u{1F4CC}" : "";
35430
+ const pin = r2.priority > 0 ? r2.priority > 1 ? ` \u{1F4CC}${r2.priority}` : " \u{1F4CC}" : "";
35274
35431
  return `[${r2.category}] ${r2.key}${pin} (${r2.id})
35275
35432
  ${r2.content}
35276
35433
  File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}`;
@@ -47013,7 +47170,7 @@ function registerResources(server2) {
47013
47170
 
47014
47171
  // src/mcp/server.ts
47015
47172
  var server = new McpServer(
47016
- { name: "toon-memory", version: "3.4.0" },
47173
+ { name: "toon-memory", version: "3.5.0" },
47017
47174
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true }, experimental: { "io.modelcontextprotocol/ui": {} } } }
47018
47175
  );
47019
47176
  var s = server.server;
@@ -47025,7 +47182,7 @@ s.setRequestHandler(InitializeRequestSchema, async (request) => {
47025
47182
  return {
47026
47183
  protocolVersion,
47027
47184
  capabilities: s.getCapabilities(),
47028
- serverInfo: { name: "toon-memory", version: "3.4.0" },
47185
+ serverInfo: { name: "toon-memory", version: "3.5.0" },
47029
47186
  ...s._instructions && { instructions: s._instructions }
47030
47187
  };
47031
47188
  });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "toon-memory",
3
- "version": "3.4.0",
4
- "description": "MCP server giving AI coding agents offline, token-efficient persistent memory — 34 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"
@@ -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
 
package/src/lib/graph.ts CHANGED
@@ -32,8 +32,8 @@ export interface GraphEntry {
32
32
  links: string[]
33
33
  /** ISO timestamp of last recall/access. Empty if never accessed. */
34
34
  lastAccessed: string
35
- /** Whether the entry is pinned (always appears first in recall). */
36
- pinned: boolean
35
+ /** Priority level 0-5. 0 = normal, 1-5 = pinned with priority (5 = highest). */
36
+ priority: number
37
37
  }
38
38
 
39
39
  export interface MemoryGraph {
@@ -80,7 +80,7 @@ export function parseEntries(data: string): GraphEntry[] {
80
80
  .map((t) => t.trim())
81
81
  .filter(Boolean),
82
82
  lastAccessed: parts.length > 12 ? parts[12] || "" : "",
83
- pinned: parts.length > 13 && parts[13] === "1",
83
+ priority: parts.length > 13 ? parseInt(parts[13]) || 0 : 0,
84
84
  })
85
85
  }
86
86
  return out
@@ -143,6 +143,8 @@ export interface GraphRecallOpts {
143
143
  hops?: number
144
144
  /** Max entries returned (keeps token cost low). Default 6. */
145
145
  limit?: number
146
+ /** Session bias: boost entries whose file matches current session files. */
147
+ sessionFiles?: string[]
146
148
  }
147
149
 
148
150
  /**
@@ -262,7 +264,7 @@ export function graphRecallDetailed(
262
264
  scored.push(
263
265
  ...[...entries]
264
266
  .sort((a, b) => {
265
- if (a.pinned !== b.pinned) return a.pinned ? -1 : 1
267
+ if (a.priority !== b.priority) return b.priority - a.priority
266
268
  return importance(b) - importance(a)
267
269
  })
268
270
  .slice(0, opts.limit ?? 6)
@@ -291,11 +293,17 @@ export function graphRecallDetailed(
291
293
  const decay = Math.pow(DECAY, dist)
292
294
  let s = (bm25.get(k) || 0) + W_CENT * cent.get(k)! + W_IMP * importance(e)
293
295
  if (seedKeys.has(k)) s += SEED_BONUS
296
+ if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
297
+ const entryFile = e.file.split(":")[0]
298
+ if (opts.sessionFiles.some((f) => f === entryFile)) {
299
+ s *= 1.15
300
+ }
301
+ }
294
302
  s *= decay
295
- return { e, s, pinned: e.pinned }
303
+ return { e, s, priority: e.priority }
296
304
  })
297
305
  .sort((a, b) => {
298
- if (a.pinned !== b.pinned) return a.pinned ? -1 : 1
306
+ if (a.priority !== b.priority) return b.priority - a.priority
299
307
  return b.s - a.s
300
308
  })
301
309
  .slice(0, opts.limit ?? 6)
@@ -304,15 +312,16 @@ export function graphRecallDetailed(
304
312
 
305
313
  selected = scored.map((x) => x.e)
306
314
 
307
- // Inject pinned entries that aren't already in the result set, always at top.
308
- const pinnedKeys = new Set(entries.filter((e) => e.pinned).map((e) => e.key))
315
+ // Inject pinned entries that aren't already in the result set, sorted by priority desc.
316
+ const pinnedKeys = new Set(entries.filter((e) => e.priority > 0).map((e) => e.key))
309
317
  const inResult = new Set(selected.map((e) => e.key))
310
- for (const pKey of pinnedKeys) {
311
- if (!inResult.has(pKey) && byKey.has(pKey)) {
312
- const e = byKey.get(pKey)!
313
- selected.unshift(e)
314
- scored.unshift({ e, s: 999 })
315
- }
318
+ const toInject = [...pinnedKeys]
319
+ .filter((k) => !inResult.has(k) && byKey.has(k))
320
+ .map((k) => byKey.get(k)!)
321
+ .sort((a, b) => b.priority - a.priority)
322
+ for (const e of toInject) {
323
+ selected.unshift(e)
324
+ scored.unshift({ e, s: 999 })
316
325
  }
317
326
 
318
327
  // Restrict adjacency to the selected entries for compact edge rendering.
@@ -372,7 +381,7 @@ export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {
372
381
  if (!isSeed && e.content.length > snippetLen) {
373
382
  body = e.content.slice(0, snippetLen).trimEnd() + "…"
374
383
  }
375
- const tag = e.pinned ? " 📌" : ""
384
+ const tag = e.priority > 0 ? (e.priority > 1 ? ` 📌${e.priority}` : " 📌") : ""
376
385
  const tags = e.tags.length ? ` · tags: ${e.tags.join(";")}` : ""
377
386
  let edges = ""
378
387
  if (opts.adjacency) {