toon-memory 3.4.0 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/mcp/server.js CHANGED
@@ -22176,7 +22176,10 @@ function parseEntries(data) {
22176
22176
  accessed: accessedRaw ? parseInt(accessedRaw) || 0 : 0,
22177
22177
  links: (linksRaw || "").split(/[\s;]+/).map((t) => t.trim()).filter(Boolean),
22178
22178
  lastAccessed: parts.length > 12 ? parts[12] || "" : "",
22179
- pinned: parts.length > 13 && parts[13] === "1"
22179
+ priority: parts.length > 13 ? parseInt(parts[13]) || 0 : 0,
22180
+ path_scope: parts.length > 14 ? parts[14] || "" : "",
22181
+ origin: parts.length > 15 && parts[15] ? parts[15] : "agent",
22182
+ status: parts.length > 16 && parts[16] ? parts[16] : "active"
22180
22183
  });
22181
22184
  }
22182
22185
  return out;
@@ -22223,7 +22226,7 @@ function bm25Scores(entries, query) {
22223
22226
  const scores = /* @__PURE__ */ new Map();
22224
22227
  if (N === 0) return scores;
22225
22228
  const docs = entries.map(
22226
- (e) => tokenize(`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`)
22229
+ (e) => tokenize(`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")} ${e.path_scope}`)
22227
22230
  );
22228
22231
  const df2 = /* @__PURE__ */ new Map();
22229
22232
  for (const d2 of docs) {
@@ -22273,11 +22276,13 @@ function graphRecallDetailed(data, query, opts = {}) {
22273
22276
  const cent = centrality(adjacency);
22274
22277
  const seedKeys = /* @__PURE__ */ new Set();
22275
22278
  for (const e of entries) {
22279
+ if (e.status === "obsolete") continue;
22276
22280
  if (category && e.category !== category) continue;
22277
22281
  if (tagsFilter.length > 0 && !tagsFilter.every((t) => e.tags.includes(t))) continue;
22278
22282
  if (from_date && e.date < from_date) continue;
22279
22283
  if (to_date && e.date > to_date) continue;
22280
22284
  if (e.ttl && isExpiredLocal(e.ttl)) continue;
22285
+ if (opts.path_scope && e.path_scope && !globMatch(opts.path_scope, e.path_scope)) continue;
22281
22286
  const text = normalize(
22282
22287
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
22283
22288
  );
@@ -22291,8 +22296,8 @@ function graphRecallDetailed(data, query, opts = {}) {
22291
22296
  const scored = [];
22292
22297
  if (seedKeys.size === 0) {
22293
22298
  scored.push(
22294
- ...[...entries].sort((a, b2) => {
22295
- if (a.pinned !== b2.pinned) return a.pinned ? -1 : 1;
22299
+ ...[...entries].filter((e) => e.status !== "obsolete").sort((a, b2) => {
22300
+ if (a.priority !== b2.priority) return b2.priority - a.priority;
22296
22301
  return importance(b2) - importance(a);
22297
22302
  }).slice(0, opts.limit ?? 6).map((e) => ({ e, s: importance(e) }))
22298
22303
  );
@@ -22316,23 +22321,27 @@ function graphRecallDetailed(data, query, opts = {}) {
22316
22321
  const decay = Math.pow(DECAY, dist);
22317
22322
  let s2 = (bm25.get(k3) || 0) + W_CENT * cent.get(k3) + W_IMP * importance(e);
22318
22323
  if (seedKeys.has(k3)) s2 += SEED_BONUS;
22324
+ if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
22325
+ const entryFile = e.file.split(":")[0];
22326
+ if (opts.sessionFiles.some((f3) => f3 === entryFile)) {
22327
+ s2 *= 1.15;
22328
+ }
22329
+ }
22319
22330
  s2 *= decay;
22320
- return { e, s: s2, pinned: e.pinned };
22331
+ return { e, s: s2, priority: e.priority };
22321
22332
  }).sort((a, b2) => {
22322
- if (a.pinned !== b2.pinned) return a.pinned ? -1 : 1;
22333
+ if (a.priority !== b2.priority) return b2.priority - a.priority;
22323
22334
  return b2.s - a.s;
22324
22335
  }).slice(0, opts.limit ?? 6)
22325
22336
  );
22326
22337
  }
22327
22338
  selected = scored.map((x) => x.e);
22328
- const pinnedKeys = new Set(entries.filter((e) => e.pinned).map((e) => e.key));
22339
+ const pinnedKeys = new Set(entries.filter((e) => e.priority > 0 && e.status !== "obsolete").map((e) => e.key));
22329
22340
  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
- }
22341
+ const toInject = [...pinnedKeys].filter((k3) => !inResult.has(k3) && byKey.has(k3)).map((k3) => byKey.get(k3)).sort((a, b2) => b2.priority - a.priority);
22342
+ for (const e of toInject) {
22343
+ selected.unshift(e);
22344
+ scored.unshift({ e, s: 999 });
22336
22345
  }
22337
22346
  const subAdj = /* @__PURE__ */ new Map();
22338
22347
  for (const e of selected) {
@@ -22345,18 +22354,51 @@ function graphRecallDetailed(data, query, opts = {}) {
22345
22354
  selected.forEach((e) => scores.set(e.key, scored.find((x) => x.e.key === e.key).s));
22346
22355
  return { entries: selected, seeds: seedKeys, adjacency: subAdj, scores };
22347
22356
  }
22357
+ function globMatch(pattern, target) {
22358
+ if (!pattern) return true;
22359
+ if (pattern.startsWith("/")) pattern = pattern.slice(1);
22360
+ if (target.startsWith("/")) target = target.slice(1);
22361
+ const reStr = "^" + pattern.replace(/\*\*/g, "___DOUBLESTAR___").replace(/\*/g, "[^/]*").replace(/___DOUBLESTAR___/g, ".*").replace(/\?/g, ".").replace(/\./g, "\\.").replace(/\\\.\*/g, ".*") + "$";
22362
+ try {
22363
+ return new RegExp(reStr).test(target);
22364
+ } catch {
22365
+ return false;
22366
+ }
22367
+ }
22348
22368
  function renderCompact(entries, opts = {}) {
22349
22369
  const index = /* @__PURE__ */ new Map();
22350
22370
  entries.forEach((e, i) => index.set(e.key, i + 1));
22351
22371
  const snippetLen = opts.snippetLen ?? 90;
22372
+ const budget = opts.budget ?? "normal";
22352
22373
  return entries.map((e) => {
22353
22374
  const n = index.get(e.key);
22354
22375
  const isSeed = opts.seeds ? opts.seeds.has(e.key) : true;
22376
+ if (budget === "tiny") {
22377
+ const firstLine = e.content.split("\n")[0] || "";
22378
+ const snippet = firstLine.length > 80 ? firstLine.slice(0, 80).trimEnd() + "\u2026" : firstLine;
22379
+ const pin = e.priority > 0 ? e.priority > 1 ? ` \u{1F4CC}${e.priority}` : " \u{1F4CC}" : "";
22380
+ return `[${n}] ${e.category}/${e.key}${pin}
22381
+ ${snippet}`;
22382
+ }
22383
+ if (budget === "deep") {
22384
+ const ttlInfo = e.ttl ? ` \xB7 ttl: ${e.ttl}` : "";
22385
+ const accessInfo = e.accessed > 0 ? ` \xB7 accessed: ${e.accessed}x` : "";
22386
+ const lastAccess = e.lastAccessed ? ` \xB7 lastAccess: ${e.lastAccessed}` : "";
22387
+ const pin = e.priority > 0 ? e.priority > 1 ? ` \u{1F4CC}${e.priority}` : " \u{1F4CC}" : "";
22388
+ const links = e.links.length ? `
22389
+ links: ${e.links.join(", ")}` : "";
22390
+ const originInfo = e.origin !== "agent" ? ` \xB7 origin: ${e.origin}` : "";
22391
+ const scopeInfo = e.path_scope ? ` \xB7 scope: ${e.path_scope}` : "";
22392
+ const statusInfo = e.status !== "active" ? ` \xB7 status: ${e.status}` : "";
22393
+ return `[${n}] ${e.category}/${e.key}${pin} (${e.id})
22394
+ ${e.content}
22395
+ File: ${e.file} | Tags: ${e.tags.join(";")} | Date: ${e.date}${ttlInfo}${accessInfo}${lastAccess}${originInfo}${scopeInfo}${statusInfo}${links}`;
22396
+ }
22355
22397
  let body = e.content;
22356
22398
  if (!isSeed && e.content.length > snippetLen) {
22357
22399
  body = e.content.slice(0, snippetLen).trimEnd() + "\u2026";
22358
22400
  }
22359
- const tag = e.pinned ? " \u{1F4CC}" : "";
22401
+ const tag = e.priority > 0 ? e.priority > 1 ? ` \u{1F4CC}${e.priority}` : " \u{1F4CC}" : "";
22360
22402
  const tags = e.tags.length ? ` \xB7 tags: ${e.tags.join(";")}` : "";
22361
22403
  let edges = "";
22362
22404
  if (opts.adjacency) {
@@ -22392,7 +22434,7 @@ __export(quality_exports, {
22392
22434
  mergeEntries: () => mergeEntries,
22393
22435
  qualityScore: () => qualityScore
22394
22436
  });
22395
- function qualityScore(tags, links, content, date5, accessed = 0, lastAccessed = "") {
22437
+ function qualityScore(tags, links, content, date5, accessed = 0, lastAccessed = "", origin = "") {
22396
22438
  let score = 0;
22397
22439
  if (tags) {
22398
22440
  const count = tags.split(";").filter(Boolean).length;
@@ -22424,6 +22466,8 @@ function qualityScore(tags, links, content, date5, accessed = 0, lastAccessed =
22424
22466
  else if (daysSinceAccess < 7) score += 0.07;
22425
22467
  else if (daysSinceAccess < 30) score += 0.03;
22426
22468
  }
22469
+ if (origin === "human") score += 0.1;
22470
+ else if (origin === "inferred") score -= 0.05;
22427
22471
  if (date5) {
22428
22472
  const daysSinceCreation = (Date.now() - (/* @__PURE__ */ new Date(`${date5}T00:00:00`)).getTime()) / 864e5;
22429
22473
  const daysSinceLastAccess = lastAccessed ? (Date.now() - new Date(lastAccessed).getTime()) / 864e5 : daysSinceCreation;
@@ -22464,8 +22508,21 @@ function mergeEntries(existingLine, newLine) {
22464
22508
  const existingLastAccessed = ep2.length > 12 ? ep2[12] || "" : "";
22465
22509
  const newLastAccessed = np2.length > 12 ? np2[12] || "" : "";
22466
22510
  const lastAccessed = newLastAccessed > existingLastAccessed ? newLastAccessed : existingLastAccessed;
22511
+ const existingPriority = ep2.length > 13 ? parseInt(ep2[13]) || 0 : 0;
22512
+ const newPriority = np2.length > 13 ? parseInt(np2[13]) || 0 : 0;
22513
+ const priority = Math.max(existingPriority, newPriority);
22467
22514
  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}`;
22515
+ const existingScope = ep2.length > 14 ? ep2[14] || "" : "";
22516
+ const newScope = np2.length > 14 ? np2[14] || "" : "";
22517
+ const path_scope = newScope || existingScope;
22518
+ const existingOrigin = ep2.length > 15 ? ep2[15] || "" : "";
22519
+ const newOrigin = np2.length > 15 ? np2[15] || "" : "";
22520
+ const originRank = { human: 3, agent: 2, inferred: 1 };
22521
+ const origin = (originRank[newOrigin] || 0) >= (originRank[existingOrigin] || 0) ? newOrigin : existingOrigin;
22522
+ const existingStatus = ep2.length > 16 ? ep2[16] || "" : "";
22523
+ const newStatus = np2.length > 16 ? np2[16] || "" : "";
22524
+ const status = newStatus === "active" || existingStatus === "active" ? "active" : newStatus || existingStatus || "active";
22525
+ return `${id2}|${category}|${key}|${content}|${file2}|${mergedTags}|${date5}|${ttl}|${accessed}|${mergedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}|${priority}|${path_scope}|${origin}|${status}`;
22469
22526
  }
22470
22527
  function generateSmartRecall(data, intent, opts = {}) {
22471
22528
  const entries = parseEntries(data);
@@ -22499,23 +22556,28 @@ function generateSmartRecall(data, intent, opts = {}) {
22499
22556
  const fileDate = mtimes.get(filePath);
22500
22557
  if (fileDate && e.date && fileDate > e.date) drift = 0.3;
22501
22558
  }
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 };
22559
+ let sessionBias = 0;
22560
+ if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
22561
+ const entryFile = e.file.split(":")[0];
22562
+ if (opts.sessionFiles.some((f3) => f3 === entryFile)) {
22563
+ sessionBias = 0.15;
22564
+ }
22565
+ }
22566
+ const combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias;
22567
+ return { entry: e, score: combined, matchesQuery, priority: e.priority };
22504
22568
  }).filter((x) => x.score > 0 || x.matchesQuery).sort((a, b2) => {
22505
- if (a.pinned !== b2.pinned) return a.pinned ? -1 : 1;
22569
+ if (a.priority !== b2.priority) return b2.priority - a.priority;
22506
22570
  return b2.score - a.score;
22507
22571
  }).slice(0, limit);
22508
- const pinnedKeys = new Set(entries.filter((e) => e.pinned).map((e) => e.key));
22572
+ const pinnedKeys = new Set(entries.filter((e) => e.priority > 0).map((e) => e.key));
22509
22573
  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
- }
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);
22575
+ for (const e of toInject) {
22576
+ scored.unshift({ entry: e, score: 999, matchesQuery: false, priority: e.priority });
22515
22577
  }
22516
22578
  if (scored.length === 0) {
22517
22579
  const top = entries.filter((e) => !category || e.category === category).sort((a, b2) => {
22518
- if (a.pinned !== b2.pinned) return a.pinned ? -1 : 1;
22580
+ if (a.priority !== b2.priority) return b2.priority - a.priority;
22519
22581
  return importance(b2) - importance(a);
22520
22582
  }).slice(0, limit);
22521
22583
  if (top.length === 0) return "No entries in memory.";
@@ -22539,7 +22601,7 @@ function generateSystemPrimer(data) {
22539
22601
  ""
22540
22602
  ];
22541
22603
  const top = [...entries].filter((e) => !isPrivate(e)).sort((a, b2) => {
22542
- if (a.pinned !== b2.pinned) return a.pinned ? -1 : 1;
22604
+ if (a.priority !== b2.priority) return b2.priority - a.priority;
22543
22605
  return importance(b2) - importance(a);
22544
22606
  }).slice(0, 5);
22545
22607
  lines.push("Top memories:");
@@ -22553,7 +22615,7 @@ function generateSystemPrimer(data) {
22553
22615
  e.lastAccessed
22554
22616
  );
22555
22617
  const conf = quality >= 0.5 ? "high" : quality >= 0.3 ? "medium" : "low";
22556
- const pin = e.pinned ? " \u{1F4CC}" : "";
22618
+ const pin = e.priority > 0 ? e.priority > 1 ? ` \u{1F4CC}${e.priority}` : " \u{1F4CC}" : "";
22557
22619
  lines.push(
22558
22620
  ` [${e.category}] ${e.key}${pin} \u2014 ${e.content.slice(0, 80)} (quality: ${conf})`
22559
22621
  );
@@ -22592,6 +22654,7 @@ __export(sessions_exports, {
22592
22654
  currentBranch: () => currentBranch,
22593
22655
  detectConflicts: () => detectConflicts,
22594
22656
  endSession: () => endSession,
22657
+ getCurrentSessionFiles: () => getCurrentSessionFiles,
22595
22658
  heartbeat: () => heartbeat,
22596
22659
  listSessions: () => listSessions,
22597
22660
  pruneSessions: () => pruneSessions,
@@ -22741,6 +22804,12 @@ function detectConflicts(active = listSessions().filter((s2) => s2.active)) {
22741
22804
  }
22742
22805
  return conflicts;
22743
22806
  }
22807
+ function getCurrentSessionFiles() {
22808
+ const id2 = resolveSessionId({});
22809
+ const all = listSessions();
22810
+ const mine = all.find((s2) => s2.id === id2);
22811
+ return mine ? Object.keys(mine.files) : [];
22812
+ }
22744
22813
  function coordinationView(selfId) {
22745
22814
  const all = listSessions();
22746
22815
  const active = all.filter((s2) => s2.active);
@@ -33441,9 +33510,19 @@ function formatOverview(data) {
33441
33510
  if (e.ttl && isExpiredLocal(e.ttl)) expired++;
33442
33511
  }
33443
33512
  const cats = Object.entries(byCategory).map(([k3, v3]) => `${k3}:${v3}`).join(" ");
33513
+ const originBreak = () => {
33514
+ const o = {};
33515
+ for (const e of entries) {
33516
+ o[e.origin] = (o[e.origin] || 0) + 1;
33517
+ }
33518
+ return Object.entries(o).map(([k3, v3]) => `${k3}:${v3}`).join(" ");
33519
+ };
33520
+ const obsoleteCount = entries.filter((e) => e.status === "obsolete").length;
33444
33521
  const ttlNote = expired > 0 ? ` | ${expired} expired` : "";
33445
- return `## Memory (${entries.length} entries)${ttlNote}
33446
- ${cats}`;
33522
+ const obsoleteNote = obsoleteCount > 0 ? ` | ${obsoleteCount} obsolete` : "";
33523
+ return `## Memory (${entries.length} entries)${ttlNote}${obsoleteNote}
33524
+ ${cats}
33525
+ Origin: ${originBreak()}`;
33447
33526
  }
33448
33527
  function formatRelevantEntries(data, task, limit = 6) {
33449
33528
  const entries = parseEntries(data);
@@ -33783,6 +33862,33 @@ function generateContextHealth(data, root) {
33783
33862
  if (stale.length > 0) {
33784
33863
  info.push(`${stale.length} stale sessions (will be pruned automatically)`);
33785
33864
  }
33865
+ const missingEvidence = entries.filter((e) => e.path_scope && !e.file);
33866
+ if (missingEvidence.length > 0) {
33867
+ warnings.push(`${missingEvidence.length} entries with path_scope but no file (missing evidence): ${missingEvidence.slice(0, 3).map((e) => e.key).join(", ")}`);
33868
+ score -= 3;
33869
+ }
33870
+ const staleClaims = [];
33871
+ for (let i = 0; i < entries.length; i++) {
33872
+ for (let j3 = i + 1; j3 < entries.length; j3++) {
33873
+ const a = entries[i], b2 = entries[j3];
33874
+ if (a.category !== b2.category) continue;
33875
+ if (a.key === b2.key) continue;
33876
+ const aWords = new Set(normalize(a.content).split(/\s+/).filter((w3) => w3.length > 3));
33877
+ const bWords = new Set(normalize(b2.content).split(/\s+/).filter((w3) => w3.length > 3));
33878
+ const intersection2 = new Set([...aWords].filter((w3) => bWords.has(w3)));
33879
+ const union2 = /* @__PURE__ */ new Set([...aWords, ...bWords]);
33880
+ const similarity = union2.size > 0 ? intersection2.size / union2.size : 0;
33881
+ if (similarity > 0.4) {
33882
+ staleClaims.push(`${a.key} \u2248 ${b2.key} (${(similarity * 100).toFixed(0)}% same category)`);
33883
+ if (staleClaims.length >= 5) break;
33884
+ }
33885
+ }
33886
+ if (staleClaims.length >= 5) break;
33887
+ }
33888
+ if (staleClaims.length > 0) {
33889
+ warnings.push(`${staleClaims.length} potentially overlapping claims: ${staleClaims.slice(0, 3).join("; ")}`);
33890
+ score -= 3;
33891
+ }
33786
33892
  if (entries.length > 80) {
33787
33893
  warnings.push(`${entries.length} entries (near limit of 100)`);
33788
33894
  score -= 3;
@@ -33887,10 +33993,12 @@ function registerTools(server2) {
33887
33993
  file: external_exports.string().optional().default("").describe("Related file or line (e.g. spec.md:145)"),
33888
33994
  tags: external_exports.string().optional().default("").describe("Semicolon-separated tags (e.g. risk;spec)"),
33889
33995
  ttl: external_exports.string().optional().default("").describe("Time to live (e.g. 7d, 2026-07-17). Empty = no expiration"),
33890
- links: external_exports.string().optional().default("").describe("Related entry keys, separated by space or ';' (e.g. risk-spec engine-arch). Builds graph edges.")
33996
+ links: external_exports.string().optional().default("").describe("Related entry keys, separated by space or ';' (e.g. risk-spec engine-arch). Builds graph edges."),
33997
+ path_scope: external_exports.string().optional().default("").describe("Glob pattern to scope this entry (e.g. src/**.ts). Empty = global."),
33998
+ origin: external_exports.enum(["human", "agent", "inferred"]).optional().default("agent").describe("Who created this entry.")
33891
33999
  }
33892
34000
  },
33893
- async ({ category, key, content, file: file2, tags, ttl, links }) => {
34001
+ async ({ category, key, content, file: file2, tags, ttl, links, path_scope, origin }) => {
33894
34002
  const data = readMemory();
33895
34003
  const newId = generateId();
33896
34004
  const date5 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
@@ -33920,7 +34028,7 @@ function registerTools(server2) {
33920
34028
  const resolvedTags = tags ? tags : verbatim ? "" : inferTags(content, key, config2.vocab);
33921
34029
  const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : [];
33922
34030
  const resolvedLinks = links ? links.split(/[\s;]+/).filter(Boolean).join(" ") : existingParts[9] || "";
33923
- let newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0|${resolvedLinks}`;
34031
+ let newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0|${resolvedLinks}|||||${path_scope || ""}|${origin}`;
33924
34032
  let action = "Saved";
33925
34033
  let mergeInfo = "";
33926
34034
  const tagsInferred = !tags && resolvedTags ? true : false;
@@ -33932,9 +34040,9 @@ function registerTools(server2) {
33932
34040
  } else {
33933
34041
  const accessed = 0;
33934
34042
  const lastAccessed = "";
33935
- const quality = verbatim ? 0.5 : qualityScore(resolvedTags, resolvedLinks, content, date5, accessed, lastAccessed);
34043
+ const quality = verbatim ? 0.5 : qualityScore(resolvedTags, resolvedLinks, content, date5, accessed, lastAccessed, origin);
33936
34044
  const confidence = 1;
33937
- newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|${accessed}|${resolvedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}`;
34045
+ newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|${accessed}|${resolvedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}|0|${path_scope || ""}|${origin}|active`;
33938
34046
  const match = lines[headerIdx].match(/\[(\d+)\|/);
33939
34047
  const count = match ? parseInt(match[1]) : 0;
33940
34048
  lines.splice(headerIdx + 1, 0, ` ${newEntry}`);
@@ -33982,30 +34090,40 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
33982
34090
  to_date: external_exports.string().optional().default("").describe("End date filter (YYYY-MM-DD)"),
33983
34091
  mode: external_exports.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall: expands the related-entry subgraph from matches (more precise, fewer tokens)."),
33984
34092
  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.")
34093
+ compact: external_exports.boolean().optional().default(false).describe("Token-efficient output: numeric indices (1, 2), omits id/date/file (keeps tags), edges as '->2', truncates graph neighbors to a snippet. Does not mutate .toon file."),
34094
+ budget: external_exports.enum(["tiny", "normal", "deep"]).optional().default("deep").describe("'tiny': key+1 line (~50 tokens). 'normal': compact with tags/edges. 'deep': all fields (default). Overrides 'compact'."),
34095
+ bias: external_exports.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
34096
+ path_scope: external_exports.string().optional().default("").describe("Glob pattern to filter entries by path scope (e.g. 'src/**.ts').")
33986
34097
  }
33987
34098
  },
33988
- async ({ query, category, from_date, to_date, mode, hops, compact }) => {
34099
+ async ({ query, category, from_date, to_date, mode, hops, compact, bias, budget: budgetParam, path_scope }) => {
33989
34100
  const data = readMemory();
33990
- const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops });
34101
+ const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
34102
+ const resolvedBudget = budgetParam || (compact ? "normal" : "deep");
34103
+ const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, sessionFiles, path_scope: path_scope || void 0 });
33991
34104
  if (detail.entries.length === 0) {
33992
34105
  return { content: [{ type: "text", text: `No results found for "${query}"` }] };
33993
34106
  }
33994
34107
  bumpAccessed(detail.entries.map((e) => e.id));
33995
- if (compact) {
34108
+ if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
33996
34109
  const formatted2 = renderCompact(detail.entries, {
33997
34110
  adjacency: detail.adjacency,
33998
34111
  seeds: detail.seeds,
33999
- snippetLen: 90
34112
+ snippetLen: 90,
34113
+ budget: resolvedBudget
34000
34114
  });
34001
34115
  return { content: [{ type: "text", text: formatted2 }] };
34002
34116
  }
34003
34117
  const formatted = detail.entries.map((r2) => {
34004
34118
  const links = r2.links.length ? `
34005
34119
  links: ${r2.links.join(", ")}` : "";
34006
- return `[${r2.category}] ${r2.key} (${r2.id})
34120
+ const pin = r2.priority > 0 ? r2.priority > 1 ? ` \u{1F4CC}${r2.priority}` : " \u{1F4CC}" : "";
34121
+ const originInfo = r2.origin !== "agent" ? ` | origin: ${r2.origin}` : "";
34122
+ const scopeInfo = r2.path_scope ? ` | scope: ${r2.path_scope}` : "";
34123
+ const statusInfo = r2.status !== "active" ? ` | status: ${r2.status}` : "";
34124
+ return `[${r2.category}] ${r2.key}${pin} (${r2.id})
34007
34125
  ${r2.content}
34008
- File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}`;
34126
+ File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}${originInfo}${scopeInfo}${statusInfo}`;
34009
34127
  }).join("\n\n");
34010
34128
  return { content: [{ type: "text", text: formatted }] };
34011
34129
  }
@@ -34016,34 +34134,60 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34016
34134
  title: "Delete from Memory",
34017
34135
  description: "Delete a memory entry by its key or id.",
34018
34136
  inputSchema: {
34019
- key: external_exports.string().describe("Key or id of the entry to delete")
34137
+ key: external_exports.string().describe("Key or id of the entry to delete"),
34138
+ hard: external_exports.boolean().optional().default(false).describe("If true, permanently remove the entry. If false (default), softly marks as obsolete (status=obsolete) so it can be resolved or restored later.")
34020
34139
  }
34021
34140
  },
34022
- async ({ key }) => {
34141
+ async ({ key, hard }) => {
34023
34142
  const data = readMemory();
34024
34143
  const lines = data.split("\n");
34025
34144
  const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
34026
34145
  if (headerIdx === -1) {
34027
34146
  return { content: [{ type: "text", text: "No entries in memory" }] };
34028
34147
  }
34029
- const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
34030
- const filtered = entryLines2.filter((l) => {
34031
- const parts = l.trim().split("|");
34032
- return parts[0] !== key && parts[2] !== key;
34033
- });
34034
- const removed = entryLines2.length - filtered.length;
34035
- const match = lines[headerIdx].match(/\[(\d+)\|/);
34036
- const count = match ? parseInt(match[1]) : 0;
34037
- lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`);
34038
- lines.splice(headerIdx + 1, entryLines2.length, ...filtered.map((l) => ` ${l.trim()}`));
34148
+ if (hard) {
34149
+ const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
34150
+ const filtered = entryLines2.filter((l) => {
34151
+ const parts = l.trim().split("|");
34152
+ return parts[0] !== key && parts[2] !== key;
34153
+ });
34154
+ const removed = entryLines2.length - filtered.length;
34155
+ const match = lines[headerIdx].match(/\[(\d+)\|/);
34156
+ const count = match ? parseInt(match[1]) : 0;
34157
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`);
34158
+ lines.splice(headerIdx + 1, entryLines2.length, ...filtered.map((l) => ` ${l.trim()}`));
34159
+ writeMemory(lines.join("\n"));
34160
+ if (removed === 0) {
34161
+ return {
34162
+ content: [{ type: "text", text: `"${key}" not found in memory.` }]
34163
+ };
34164
+ }
34165
+ return {
34166
+ content: [{ type: "text", text: `"${key}" permanently deleted. ${count - removed} entries remaining.` }]
34167
+ };
34168
+ }
34169
+ let found = false;
34170
+ for (let i = headerIdx + 1; i < lines.length; i++) {
34171
+ const line = lines[i];
34172
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
34173
+ if (line.startsWith(" summaries:")) break;
34174
+ const parts = line.trim().split("|");
34175
+ if (parts[0] === key || parts[2] === key) {
34176
+ while (parts.length < 17) parts.push("");
34177
+ parts[16] = "obsolete";
34178
+ lines[i] = ` ${parts.join("|")}`;
34179
+ found = true;
34180
+ break;
34181
+ }
34182
+ }
34039
34183
  writeMemory(lines.join("\n"));
34040
- if (removed === 0) {
34184
+ if (!found) {
34041
34185
  return {
34042
34186
  content: [{ type: "text", text: `"${key}" not found in memory.` }]
34043
34187
  };
34044
34188
  }
34045
34189
  return {
34046
- content: [{ type: "text", text: `"${key}" deleted. ${count - removed} entries remaining.` }]
34190
+ content: [{ type: "text", text: `"${key}" marked as obsolete. Use memory_resolve(key: "${key}") to restore.` }]
34047
34191
  };
34048
34192
  }
34049
34193
  );
@@ -34059,7 +34203,7 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34059
34203
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
34060
34204
  const entries = lines.map((l) => {
34061
34205
  const parts = l.trim().split("|");
34062
- return { category: parts[1] || "unknown", ttl: parts[7] || "", quality: parts[10] || "" };
34206
+ return { category: parts[1] || "unknown", ttl: parts[7] || "", quality: parts[10] || "", origin: parts.length > 15 ? parts[15] || "" : "", status: parts.length > 16 ? parts[16] || "" : "" };
34063
34207
  });
34064
34208
  const byCategory = {};
34065
34209
  for (const e of entries) {
@@ -34070,6 +34214,12 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34070
34214
  const withQuality = entries.filter((e) => e.quality).length;
34071
34215
  const avgQuality = withQuality > 0 ? (entries.reduce((sum, e) => sum + (e.quality ? parseFloat(e.quality) : 0), 0) / withQuality).toFixed(2) : "N/A";
34072
34216
  const summaryLines = data.split("\n").filter((l) => l.includes(":") && !l.startsWith(" ") && !l.startsWith("version") && !l.startsWith("entries") && !/^\[\d+\|]/.test(l));
34217
+ const byOrigin = {};
34218
+ const byStatus = {};
34219
+ for (const e of entries) {
34220
+ byOrigin[e.origin || "agent"] = (byOrigin[e.origin || "agent"] || 0) + 1;
34221
+ byStatus[e.status || "active"] = (byStatus[e.status || "active"] || 0) + 1;
34222
+ }
34073
34223
  const stats = [
34074
34224
  `Total entries: ${entries.length}`,
34075
34225
  `File summaries: ${summaryLines.length}`,
@@ -34077,6 +34227,12 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34077
34227
  "By category:",
34078
34228
  ...Object.entries(byCategory).map(([k3, v3]) => ` ${k3}: ${v3}`),
34079
34229
  "",
34230
+ "By origin:",
34231
+ ...Object.entries(byOrigin).map(([k3, v3]) => ` ${k3}: ${v3}`),
34232
+ "",
34233
+ "By status:",
34234
+ ...Object.entries(byStatus).map(([k3, v3]) => ` ${k3}: ${v3}`),
34235
+ "",
34080
34236
  `TTL: ${withTtl} with expiration, ${expired} expired`,
34081
34237
  `Average quality: ${avgQuality} (${withQuality} with score)`,
34082
34238
  "",
@@ -34086,7 +34242,9 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34086
34242
  const ttlInfo = parts[7] ? ` | TTL: ${parts[7]}` : "";
34087
34243
  const qualityInfo = parts[10] ? ` | Q: ${parts[10]}` : "";
34088
34244
  const accessInfo = parts[8] && parseInt(parts[8]) > 0 ? ` | accessed: ${parts[8]}x` : "";
34089
- return ` [${parts[1]}] ${parts[2]} (${parts[0]})${ttlInfo}${qualityInfo}${accessInfo}`;
34245
+ const originInfo = parts.length > 15 && parts[15] && parts[15] !== "agent" ? ` | origin: ${parts[15]}` : "";
34246
+ const statusInfo = parts.length > 16 && parts[16] && parts[16] !== "active" ? ` | status: ${parts[16]}` : "";
34247
+ return ` [${parts[1]}] ${parts[2]} (${parts[0]})${ttlInfo}${qualityInfo}${accessInfo}${originInfo}${statusInfo}`;
34090
34248
  }),
34091
34249
  "",
34092
34250
  `Most accessed:`,
@@ -34095,6 +34253,37 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34095
34253
  return { key: parts[2], accessed: parts.length > 8 ? parseInt(parts[8]) || 0 : 0, quality: parts[10] || "" };
34096
34254
  }).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
34255
  ];
34256
+ const coldEntries = lines.filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")).map((l) => {
34257
+ const p2 = l.trim().split("|");
34258
+ return {
34259
+ key: p2[2],
34260
+ cat: p2[1],
34261
+ quality: parseFloat(p2[10]) || 0,
34262
+ accessed: p2.length > 8 ? parseInt(p2[8]) || 0 : 0,
34263
+ lastAccessed: p2.length > 12 ? p2[12] || "" : "",
34264
+ date: p2[6] || ""
34265
+ };
34266
+ }).filter((e) => {
34267
+ if (e.accessed >= 2) return false;
34268
+ if (e.quality < 0.7) return false;
34269
+ const lastDate = e.lastAccessed || e.date;
34270
+ if (!lastDate) return false;
34271
+ const daysSinceLastAccess = (Date.now() - new Date(lastDate).getTime()) / 864e5;
34272
+ return daysSinceLastAccess > 30;
34273
+ }).sort((a, b2) => b2.quality - a.quality);
34274
+ if (coldEntries.length > 0) {
34275
+ stats.push(
34276
+ "",
34277
+ `Cold memories (${coldEntries.length}):`,
34278
+ ...coldEntries.slice(0, 5).map((e) => {
34279
+ const lastDate = e.lastAccessed || e.date;
34280
+ const daysSince = Math.round((Date.now() - new Date(lastDate).getTime()) / 864e5);
34281
+ return ` ${e.key} (Q: ${e.quality.toFixed(2)}) \u2014 ${daysSince}d since last access`;
34282
+ }),
34283
+ "",
34284
+ "\u{1F4A1} Run memory_archive() to archive cold entries."
34285
+ );
34286
+ }
34098
34287
  return { content: [{ type: "text", text: stats.join("\n") }] };
34099
34288
  }
34100
34289
  );
@@ -34178,13 +34367,15 @@ ${formatted}` }] };
34178
34367
  inputSchema: {
34179
34368
  intent: external_exports.string().describe("Describe what you need to know (e.g. 'database schema for backend')"),
34180
34369
  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)")
34370
+ 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).")
34182
34372
  }
34183
34373
  },
34184
- async ({ intent, limit, category }) => {
34374
+ async ({ intent, limit, category, bias }) => {
34185
34375
  const data = readMemory();
34186
34376
  const mtimes = fileMtimes();
34187
- const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes });
34377
+ const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
34378
+ const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles });
34188
34379
  return { content: [{ type: "text", text: result }] };
34189
34380
  }
34190
34381
  );
@@ -35058,14 +35249,30 @@ To import later: memory_import_gist(gist_id: "${gist.id}")`
35058
35249
  }
35059
35250
  }
35060
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.");
35061
35272
  return {
35062
35273
  content: [{
35063
35274
  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.`
35275
+ text: previewLines.join("\n")
35069
35276
  }]
35070
35277
  };
35071
35278
  }
@@ -35150,22 +35357,105 @@ ${mergeActions.join("\n")}`
35150
35357
  };
35151
35358
  }
35152
35359
  );
35360
+ server2.registerTool(
35361
+ "memory_checkpoint",
35362
+ {
35363
+ title: "Session Checkpoint",
35364
+ 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
+ inputSchema: {
35366
+ note: external_exports.string().optional().default("").describe("Optional summary of what was accomplished in this session.")
35367
+ }
35368
+ },
35369
+ async ({ note }) => {
35370
+ const data = readMemory();
35371
+ const lines = data.split("\n");
35372
+ let headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35373
+ if (headerIdx === -1) {
35374
+ lines.push(`[0|]`);
35375
+ headerIdx = lines.length - 1;
35376
+ }
35377
+ const sessionId = resolveSessionId({});
35378
+ const shortId = sessionId.replace(/^proc-/, "").slice(0, 8);
35379
+ const key = `checkpoint-${shortId}`;
35380
+ const now = /* @__PURE__ */ new Date();
35381
+ const date5 = now.toISOString().split("T")[0];
35382
+ const ttl7d = new Date(now.getTime() + 7 * 864e5).toISOString().split("T")[0];
35383
+ const sessions = await Promise.resolve().then(() => (init_sessions(), sessions_exports));
35384
+ const allSessions = sessions.listSessions();
35385
+ const mySession = allSessions.find((s2) => s2.id === sessionId);
35386
+ const branch = mySession?.branch || currentBranch();
35387
+ const files = mySession ? Object.keys(mySession.files) : [];
35388
+ const fileList = files.length > 0 ? `
35389
+ Files touched: ${files.slice(0, 10).join(", ")}${files.length > 10 ? ` (+${files.length - 10} more)` : ""}` : "";
35390
+ const content = `Session checkpoint (${date5})${note ? `
35391
+ Note: ${note}` : ""}
35392
+ Branch: ${branch}${fileList}`;
35393
+ let existingIdx = -1;
35394
+ let existingId = "";
35395
+ for (let i = headerIdx + 1; i < lines.length; i++) {
35396
+ const line = lines[i];
35397
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
35398
+ if (line.startsWith(" summaries:")) break;
35399
+ const parts = line.trim().split("|");
35400
+ if (parts[2] === key) {
35401
+ existingIdx = i;
35402
+ existingId = parts[0];
35403
+ break;
35404
+ }
35405
+ }
35406
+ if (existingIdx !== -1) {
35407
+ const parts = lines[existingIdx].trim().split("|");
35408
+ parts[3] = content;
35409
+ parts[6] = date5;
35410
+ parts[7] = ttl7d;
35411
+ while (parts.length < 14) parts.push("");
35412
+ parts[13] = "0";
35413
+ lines[existingIdx] = ` ${parts.join("|")}`;
35414
+ writeMemory(lines.join("\n"));
35415
+ return {
35416
+ content: [{ type: "text", text: `\u{1F4DD} Checkpoint updated: ${key}
35417
+ \u23F0 TTL: ${ttl7d} (7d)
35418
+ ${note ? `
35419
+ ${note}` : ""}` }]
35420
+ };
35421
+ }
35422
+ const newId = `cp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
35423
+ const quality = qualityScore("checkpoint", "", content, date5);
35424
+ const newEntry = `${newId}|knowledge|${key}|${content}||checkpoint|${date5}|${ttl7d}|0||${quality.toFixed(2)}|1|${now.toISOString()}|0`;
35425
+ const match = lines[headerIdx].match(/\[(\d+)\|/);
35426
+ const count = match ? parseInt(match[1]) : 0;
35427
+ lines.splice(headerIdx + 1, 0, ` ${newEntry}`);
35428
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`);
35429
+ writeMemory(lines.join("\n"));
35430
+ return {
35431
+ content: [{
35432
+ type: "text",
35433
+ text: `\u{1F4DD} Checkpoint saved: ${key} (${newId})
35434
+ \u23F0 TTL: ${ttl7d} (7d)${note ? `
35435
+
35436
+ ${note}` : ""}`
35437
+ }]
35438
+ };
35439
+ }
35440
+ );
35153
35441
  server2.registerTool(
35154
35442
  "memory_pin",
35155
35443
  {
35156
35444
  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.",
35445
+ 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
35446
  inputSchema: {
35159
- key: external_exports.string().describe("Key or id of the entry to pin")
35447
+ key: external_exports.string().describe("Key or id of the entry to pin"),
35448
+ priority: external_exports.number().optional().default(1).describe("Priority level 1-5 (5 = highest). Default: 1.")
35160
35449
  }
35161
35450
  },
35162
- async ({ key }) => {
35451
+ async ({ key, priority }) => {
35163
35452
  const data = readMemory();
35164
35453
  const lines = data.split("\n");
35165
35454
  const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35166
35455
  if (headerIdx === -1) {
35167
35456
  return { content: [{ type: "text", text: "No entries in memory" }] };
35168
35457
  }
35458
+ const clampedPriority = Math.max(1, Math.min(5, Math.round(priority)));
35169
35459
  let found = false;
35170
35460
  for (let i = headerIdx + 1; i < lines.length; i++) {
35171
35461
  const line = lines[i];
@@ -35174,7 +35464,7 @@ ${mergeActions.join("\n")}`
35174
35464
  const parts = line.trim().split("|");
35175
35465
  if (parts[0] === key || parts[2] === key) {
35176
35466
  while (parts.length < 14) parts.push("");
35177
- parts[13] = "1";
35467
+ parts[13] = String(clampedPriority);
35178
35468
  lines[i] = ` ${parts.join("|")}`;
35179
35469
  found = true;
35180
35470
  break;
@@ -35184,7 +35474,7 @@ ${mergeActions.join("\n")}`
35184
35474
  return { content: [{ type: "text", text: `"${key}" not found in memory.` }] };
35185
35475
  }
35186
35476
  writeMemory(lines.join("\n"));
35187
- return { content: [{ type: "text", text: `\u{1F4CC} Pinned "${key}". It will now appear first in recalls.` }] };
35477
+ return { content: [{ type: "text", text: `\u{1F4CC}${clampedPriority > 1 ? clampedPriority : ""} Pinned "${key}" at priority ${clampedPriority}. It will now appear first in recalls.` }] };
35188
35478
  }
35189
35479
  );
35190
35480
  server2.registerTool(
@@ -35222,7 +35512,7 @@ ${mergeActions.join("\n")}`
35222
35512
  return { content: [{ type: "text", text: `"${key}" not found in memory.` }] };
35223
35513
  }
35224
35514
  writeMemory(lines.join("\n"));
35225
- return { content: [{ type: "text", text: `\u{1F4CC} Unpinned "${key}". It will now use normal ranking.` }] };
35515
+ return { content: [{ type: "text", text: `Unpinned "${key}". It will now use normal ranking.` }] };
35226
35516
  }
35227
35517
  );
35228
35518
  server2.registerTool(
@@ -35239,29 +35529,37 @@ ${mergeActions.join("\n")}`
35239
35529
  limit: external_exports.number().optional().default(6).describe("Maximum entries to return"),
35240
35530
  mode: external_exports.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall."),
35241
35531
  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")
35532
+ compact: external_exports.boolean().optional().default(false).describe("Token-efficient output"),
35533
+ budget: external_exports.enum(["tiny", "normal", "deep"]).optional().default("deep").describe("'tiny': key+1 line (~50 tokens). 'normal': compact with tags/edges. 'deep': all fields (default). Overrides 'compact'."),
35534
+ bias: external_exports.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
35535
+ path_scope: external_exports.string().optional().default("").describe("Glob pattern to filter entries by path scope (e.g. 'src/**.ts').")
35243
35536
  }
35244
35537
  },
35245
- async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact }) => {
35538
+ async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact, bias, budget: budgetParam, path_scope }) => {
35246
35539
  const data = readMemory();
35247
35540
  const resolvedFrom = from_date ? parseRelativeDate(from_date) : "";
35541
+ const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
35542
+ const resolvedBudget = budgetParam || (compact ? "normal" : "deep");
35248
35543
  const detail = graphRecallDetailed(data, query, {
35249
35544
  category: category || void 0,
35250
35545
  tags: tags || void 0,
35251
35546
  from_date: resolvedFrom || void 0,
35252
35547
  to_date: to_date || void 0,
35253
35548
  hops,
35254
- limit
35549
+ limit,
35550
+ sessionFiles,
35551
+ path_scope: path_scope || void 0
35255
35552
  });
35256
35553
  if (detail.entries.length === 0) {
35257
35554
  return { content: [{ type: "text", text: `No results found for "${query}"` }] };
35258
35555
  }
35259
35556
  bumpAccessed(detail.entries.map((e) => e.id));
35260
- if (compact) {
35557
+ if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
35261
35558
  const formatted2 = renderCompact(detail.entries, {
35262
35559
  adjacency: detail.adjacency,
35263
35560
  seeds: detail.seeds,
35264
- snippetLen: 90
35561
+ snippetLen: 90,
35562
+ budget: resolvedBudget
35265
35563
  });
35266
35564
  return { content: [{ type: "text", text: `\u{1F50D} Search: "${query}"
35267
35565
 
@@ -35270,10 +35568,13 @@ ${formatted2}` }] };
35270
35568
  const formatted = detail.entries.map((r2) => {
35271
35569
  const links = r2.links.length ? `
35272
35570
  links: ${r2.links.join(", ")}` : "";
35273
- const pin = r2.pinned ? " \u{1F4CC}" : "";
35571
+ const pin = r2.priority > 0 ? r2.priority > 1 ? ` \u{1F4CC}${r2.priority}` : " \u{1F4CC}" : "";
35572
+ const originInfo = r2.origin !== "agent" ? ` | origin: ${r2.origin}` : "";
35573
+ const scopeInfo = r2.path_scope ? ` | scope: ${r2.path_scope}` : "";
35574
+ const statusInfo = r2.status !== "active" ? ` | status: ${r2.status}` : "";
35274
35575
  return `[${r2.category}] ${r2.key}${pin} (${r2.id})
35275
35576
  ${r2.content}
35276
- File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}`;
35577
+ File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}${originInfo}${scopeInfo}${statusInfo}`;
35277
35578
  }).join("\n\n");
35278
35579
  let filterInfo = "";
35279
35580
  if (category) filterInfo += ` category: ${category}`;
@@ -35350,6 +35651,83 @@ ${formatted}` }]
35350
35651
  };
35351
35652
  }
35352
35653
  );
35654
+ server2.registerTool(
35655
+ "memory_resolve",
35656
+ {
35657
+ title: "Resolve Entry",
35658
+ description: "Restore an obsolete entry back to active status, or mark an entry as resolved. Reverses soft-delete.",
35659
+ inputSchema: {
35660
+ key: external_exports.string().describe("Key or id of the entry to resolve/restore")
35661
+ }
35662
+ },
35663
+ async ({ key }) => {
35664
+ const data = readMemory();
35665
+ const lines = data.split("\n");
35666
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35667
+ if (headerIdx === -1) {
35668
+ return { content: [{ type: "text", text: "No entries in memory" }] };
35669
+ }
35670
+ let found = false;
35671
+ let wasObsolete = false;
35672
+ for (let i = headerIdx + 1; i < lines.length; i++) {
35673
+ const line = lines[i];
35674
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
35675
+ if (line.startsWith(" summaries:")) break;
35676
+ const parts = line.trim().split("|");
35677
+ if (parts[0] === key || parts[2] === key) {
35678
+ while (parts.length < 17) parts.push("");
35679
+ wasObsolete = parts[16] === "obsolete";
35680
+ parts[16] = "active";
35681
+ lines[i] = ` ${parts.join("|")}`;
35682
+ found = true;
35683
+ break;
35684
+ }
35685
+ }
35686
+ if (!found) {
35687
+ return { content: [{ type: "text", text: `"${key}" not found in memory.` }] };
35688
+ }
35689
+ writeMemory(lines.join("\n"));
35690
+ const msg = wasObsolete ? `"${key}" restored to active status.` : `"${key}" marked as resolved.`;
35691
+ return { content: [{ type: "text", text: `\u2705 ${msg}` }] };
35692
+ }
35693
+ );
35694
+ server2.registerTool(
35695
+ "memory_suppress",
35696
+ {
35697
+ title: "Suppress Entry",
35698
+ description: "Suppress a memory entry so it's hidden from normal recalls. Sets status to 'obsolete'. Use memory_resolve to restore.",
35699
+ inputSchema: {
35700
+ key: external_exports.string().describe("Key or id of the entry to suppress")
35701
+ }
35702
+ },
35703
+ async ({ key }) => {
35704
+ const data = readMemory();
35705
+ const lines = data.split("\n");
35706
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
35707
+ if (headerIdx === -1) {
35708
+ return { content: [{ type: "text", text: "No entries in memory" }] };
35709
+ }
35710
+ let found = false;
35711
+ for (let i = headerIdx + 1; i < lines.length; i++) {
35712
+ const line = lines[i];
35713
+ if (!line.startsWith(" ") || !line.includes("|")) continue;
35714
+ if (line.startsWith(" summaries:")) break;
35715
+ const parts = line.trim().split("|");
35716
+ if (parts[0] === key || parts[2] === key) {
35717
+ while (parts.length < 17) parts.push("");
35718
+ parts[16] = "obsolete";
35719
+ lines[i] = ` ${parts.join("|")}`;
35720
+ found = true;
35721
+ break;
35722
+ }
35723
+ }
35724
+ if (!found) {
35725
+ return { content: [{ type: "text", text: `"${key}" not found in memory.` }] };
35726
+ }
35727
+ writeMemory(lines.join("\n"));
35728
+ return { content: [{ type: "text", text: `"${key}" suppressed. Use memory_resolve(key: "${key}") to restore.` }] };
35729
+ }
35730
+ );
35353
35731
  K3(
35354
35732
  server2,
35355
35733
  "memory_visualize",
@@ -47013,7 +47391,7 @@ function registerResources(server2) {
47013
47391
 
47014
47392
  // src/mcp/server.ts
47015
47393
  var server = new McpServer(
47016
- { name: "toon-memory", version: "3.4.0" },
47394
+ { name: "toon-memory", version: "3.6.0" },
47017
47395
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true }, experimental: { "io.modelcontextprotocol/ui": {} } } }
47018
47396
  );
47019
47397
  var s = server.server;
@@ -47025,7 +47403,7 @@ s.setRequestHandler(InitializeRequestSchema, async (request) => {
47025
47403
  return {
47026
47404
  protocolVersion,
47027
47405
  capabilities: s.getCapabilities(),
47028
- serverInfo: { name: "toon-memory", version: "3.4.0" },
47406
+ serverInfo: { name: "toon-memory", version: "3.6.0" },
47029
47407
  ...s._instructions && { instructions: s._instructions }
47030
47408
  };
47031
47409
  });