toon-memory 4.1.2 → 4.3.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/src/mcp/tools.ts CHANGED
@@ -9,7 +9,7 @@ import { generateId, parseTTL, isExpired, inferTags, parseRelativeDate } from ".
9
9
  import { findRelatedEntries, bumpAccessed } from "./scoring"
10
10
  import { readObservations } from "./observations"
11
11
  import { archiveOldEntries } from "./archive"
12
- import { consolidateEntries } from "./consolidation"
12
+ import { consolidateEntries, consolidateVersions } from "./consolidation"
13
13
  import { readUnderLock } from "../lib/lock"
14
14
  import { encrypt, decrypt } from "./crypto"
15
15
  import { graphRecallDetailed, renderCompact, parseEntries, buildGraph, parseLinkToken, formatLink, typedLinks } from "../lib/graph"
@@ -17,7 +17,7 @@ import { qualityScore, mergeEntries, generateSmartRecall } from "../lib/quality"
17
17
  import { generateContextBrief, generateContextGenerate, generateContextDiff, generateContextFocus, generateContextHealth, generateContextExport } from "../lib/context"
18
18
  import { coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS, getCurrentSessionFiles } from "../lib/sessions"
19
19
  import { fileMtimes } from "../lib/git"
20
- import { normalize, isExpiredLocal, tokenize, importance, parseToonLine, toToonLine, escField, unescField } from "../lib/utils"
20
+ import { normalize, isExpiredLocal, tokenize, importance, estimateTokens, parseToonLine, toToonLine, escField, unescField } from "../lib/utils"
21
21
  import { expandSynonyms } from "../lib/synonyms"
22
22
 
23
23
  /**
@@ -236,6 +236,27 @@ function runConsolidate(): { content: ToolText[] } {
236
236
  }
237
237
  }
238
238
 
239
+ function runConsolidateVersions(dryRun: boolean): { content: ToolText[] } {
240
+ const result = consolidateVersions(dryRun)
241
+ if (result.groups.length === 0) {
242
+ return { content: [{ type: "text", text: "✅ No version supersession detected." }] }
243
+ }
244
+ if (dryRun) {
245
+ return {
246
+ content: [{
247
+ type: "text",
248
+ text: `🔍 Version supersession candidates (${result.groups.length}):\n${result.proposals.map((p) => ` • ${p}`).join("\n")}\n\nRun again with dryRun: false to apply.`,
249
+ }],
250
+ }
251
+ }
252
+ return {
253
+ content: [{
254
+ type: "text",
255
+ text: `🗂️ Marked ${result.removed} old-version entries obsolete:\n${result.proposals.map((p) => ` • ${p}`).join("\n")}`,
256
+ }],
257
+ }
258
+ }
259
+
239
260
  function runMergeSimilar(dryRun: boolean): { content: ToolText[] } {
240
261
  const data = readMemory()
241
262
  const lines = data.split("\n")
@@ -436,7 +457,7 @@ server.registerTool(
436
457
  title: "Save to Memory",
437
458
  description: "Save a fact to the project's persistent memory (decisions, patterns, bugs, knowledge). Persists between sessions. Tags: 'private' excludes from context injection; 'superseded' marks as obsolete.",
438
459
  inputSchema: {
439
- category: z.enum(["decision", "pattern", "bug", "knowledge"]).describe("Category of the fact"),
460
+ category: z.enum(["decision", "pattern", "bug", "knowledge", "warning"]).describe("Category of the fact. 'warning' = negative memory ('NO hacer esto, rompe X') — recalled with a boost so past mistakes surface first."),
440
461
  key: z.string().describe("Short title in kebab-case (e.g. risk-engine-priority)"),
441
462
  content: z.string().describe("Detailed content of the fact"),
442
463
  file: z.string().optional().default("").describe("Related file or line (e.g. spec.md:145)"),
@@ -445,10 +466,11 @@ server.registerTool(
445
466
  links: z.string().optional().default("").describe("Related entry keys, separated by space or ';' (e.g. risk-spec engine-arch). Builds graph edges."),
446
467
  path_scope: z.string().optional().default("").describe("Glob pattern to scope this entry (e.g. src/**.ts). Empty = global."),
447
468
  origin: z.enum(["human", "agent", "inferred"]).optional().default("agent").describe("Who created this entry."),
469
+ importance: z.enum(["critical", "high", "medium", "low"]).optional().describe("Explicit importance level — critical/high entries surface first in recall, low last. Omit for auto (recency + frequency)."),
448
470
  },
449
471
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
450
472
  },
451
- async ({ category, key, content, file, tags, ttl, links, path_scope, origin }) => {
473
+ async ({ category, key, content, file, tags, ttl, links, path_scope, origin, importance = "" }) => {
452
474
  const data = readMemory()
453
475
  const newId = generateId()
454
476
  const date = new Date().toISOString().split("T")[0]
@@ -483,7 +505,7 @@ server.registerTool(
483
505
  const resolvedLinks = links
484
506
  ? links.split(/[\s;]+/).filter(Boolean).join(" ")
485
507
  : existingParts[9] || ""
486
- let newEntry = toToonLine([entryId, category, key, content, file || "", resolvedTags, date, resolvedTtl, "0", resolvedLinks, "", "", "", path_scope || "", origin])
508
+ let newEntry = toToonLine([entryId, category, key, content, file || "", resolvedTags, date, resolvedTtl, "0", resolvedLinks, "", "", "", "0", path_scope || "", origin, "", "", importance])
487
509
  let action = "Saved"
488
510
  let mergeInfo = ""
489
511
  const tagsInferred = !tags && resolvedTags ? true : false
@@ -498,7 +520,7 @@ server.registerTool(
498
520
  const lastAccessed = ""
499
521
  const quality = verbatim ? 0.5 : qualityScore(resolvedTags, resolvedLinks, content, date, accessed, lastAccessed, origin)
500
522
  const confidence = 1.0
501
- newEntry = toToonLine([entryId, category, key, content, file || "", resolvedTags, date, resolvedTtl, String(accessed), resolvedLinks, quality.toFixed(2), String(confidence), lastAccessed, "0", path_scope || "", origin, "active"])
523
+ newEntry = toToonLine([entryId, category, key, content, file || "", resolvedTags, date, resolvedTtl, String(accessed), resolvedLinks, quality.toFixed(2), String(confidence), lastAccessed, "0", path_scope || "", origin, "active", "", importance])
502
524
  const match = lines[headerIdx].match(/\[(\d+)\|/)
503
525
  const count = match ? parseInt(match[1]) : 0
504
526
  lines.splice(headerIdx + 1, 0, newEntry)
@@ -549,6 +571,8 @@ server.registerTool(
549
571
  hops: z.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
550
572
  compact: z.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."),
551
573
  budget: z.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'."),
574
+ budget_tokens: z.number().optional().default(0).describe("Deterministic token budget: include entries until the estimated output reaches ~N tokens (overrides limit). 0 = no budget."),
575
+ explain: z.boolean().optional().default(false).describe("Append a 'why this entry' line to each result (relevance %, times used, last used, importance). No LLM — pure heuristics."),
552
576
  bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
553
577
  path_scope: z.string().optional().default("").describe("Glob pattern to filter entries by path scope (e.g. 'src/**.ts')."),
554
578
  rrf: z.boolean().optional().default(false).describe("Use Reciprocal Rank Fusion (BM25x3 + centrality ranks, adaptive k=sqrtN) instead of weighted linear scoring. Weight-free: reaches parity with the tuned linear scorer on scripts/bench-rrf.mjs."),
@@ -556,7 +580,7 @@ server.registerTool(
556
580
  },
557
581
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
558
582
  },
559
- async ({ query, category, from_date, to_date, mode, hops, compact, bias, budget: budgetParam, path_scope, rrf, as_of }) => {
583
+ async ({ query, category, from_date, to_date, mode, hops, compact, budget: budgetParam, budget_tokens, explain, bias, path_scope, rrf, as_of }) => {
560
584
  const data = readMemory()
561
585
 
562
586
  // Delegate to graphRecallDetailed for both flat and graph modes
@@ -568,12 +592,15 @@ server.registerTool(
568
592
  return { content: [{ type: "text" as const, text: `No results found for "${query}"` }] }
569
593
  }
570
594
  bumpAccessed(detail.entries.map((e) => e.id))
595
+ const reasons = explain ? detail.reasons : undefined
571
596
  if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
572
597
  const formatted = renderCompact(detail.entries, {
573
598
  adjacency: detail.adjacency,
574
599
  seeds: detail.seeds,
575
600
  snippetLen: 90,
576
601
  budget: resolvedBudget,
602
+ reasons,
603
+ budgetTokens: budget_tokens || undefined,
577
604
  })
578
605
  return { content: [{ type: "text" as const, text: formatted }] }
579
606
  }
@@ -585,9 +612,22 @@ server.registerTool(
585
612
  const scopeInfo = r.path_scope ? ` | scope: ${r.path_scope}` : ""
586
613
  const statusInfo = r.status !== "active" ? ` | status: ${r.status}` : ""
587
614
  const supersededInfo = r.supersededOn ? ` | superseded: ${r.supersededOn}` : ""
588
- return `[${r.category}] ${r.key}${pin} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}`
615
+ const why = reasons?.get(r.key) ? `\n ↳ ${reasons.get(r.key)}` : ""
616
+ return `[${r.category}] ${r.key}${pin} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}${why}`
589
617
  })
590
618
  .join("\n\n")
619
+ // Deterministic token budget for the deep render.
620
+ if (budget_tokens && budget_tokens > 0) {
621
+ const blocks = formatted.split("\n\n")
622
+ let acc = 0
623
+ let out: string[] = []
624
+ for (let i = 0; i < blocks.length; i++) {
625
+ acc += estimateTokens(blocks[i])
626
+ if (i > 0 && acc > budget_tokens) break
627
+ out.push(blocks[i])
628
+ }
629
+ return { content: [{ type: "text" as const, text: out.join("\n\n") }] }
630
+ }
591
631
  return { content: [{ type: "text" as const, text: formatted }] }
592
632
  }
593
633
  )
@@ -654,10 +694,31 @@ server.registerTool(
654
694
  const summaryLines = data.split("\n").filter((l) => l.includes(":") && !l.startsWith(" ") && !l.startsWith("version") && !l.startsWith("entries") && !/^\[\d+\|]/.test(l))
655
695
  const byOrigin: Record<string, number> = {}
656
696
  const byStatus: Record<string, number> = {}
657
- for (const e of entries) {
658
- byOrigin[e.origin || "agent"] = (byOrigin[e.origin || "agent"] || 0) + 1
659
- byStatus[e.status || "active"] = (byStatus[e.status || "active"] || 0) + 1
660
- }
697
+ const accessed = new Map<string, number>()
698
+ const fullParts = lines
699
+ .filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
700
+ .map((l) => parseToonLine(l))
701
+ for (const p of fullParts) {
702
+ byOrigin[p.length > 15 ? p[15] || "agent" : "agent"] = (byOrigin[p.length > 15 ? p[15] || "agent" : "agent"] || 0) + 1
703
+ const st = p.length > 16 ? p[16] || "active" : "active"
704
+ byStatus[st] = (byStatus[st] || 0) + 1
705
+ accessed.set(p[0], p.length > 8 ? parseInt(p[8]) || 0 : 0)
706
+ }
707
+
708
+ // Extended stats: hit rate, duplicate %, dead %
709
+ const hitRate = entries.length > 0
710
+ ? ((fullParts.filter((p) => (parseInt(p[8]) || 0) > 0).length / entries.length) * 100).toFixed(0)
711
+ : "0"
712
+ const contentCounts = new Map<string, number>()
713
+ for (const p of fullParts) {
714
+ const norm = (p[3] || "").toLowerCase().replace(/\s+/g, " ").trim()
715
+ contentCounts.set(norm, (contentCounts.get(norm) || 0) + 1)
716
+ }
717
+ let dupCount = 0
718
+ for (const c of contentCounts.values()) if (c > 1) dupCount += c - 1
719
+ const dupPct = entries.length > 0 ? ((dupCount / entries.length) * 100).toFixed(0) : "0"
720
+ const deadCount = byStatus["obsolete"] || 0
721
+ const deadPct = entries.length > 0 ? ((deadCount / entries.length) * 100).toFixed(0) : "0"
661
722
 
662
723
  const stats = [
663
724
  `Total entries: ${entries.length}`,
@@ -675,6 +736,10 @@ server.registerTool(
675
736
  `TTL: ${withTtl} with expiration, ${expired} expired`,
676
737
  `Average quality: ${avgQuality} (${withQuality} with score)`,
677
738
  "",
739
+ `Hit rate: ${hitRate}% recalled at least once (${fullParts.filter((p) => (parseInt(p[8]) || 0) > 0).length}/${entries.length})`,
740
+ `Duplicate: ${dupPct}% (${dupCount} exact-content dups)`,
741
+ `Dead: ${deadPct}% (${deadCount} obsolete)`,
742
+ "",
678
743
  `Last 5 entries:`,
679
744
  ...lines.slice(-5).map((l) => {
680
745
  const parts = parseToonLine(l)
@@ -843,14 +908,16 @@ server.registerTool(
843
908
  category: z.string().optional().default("").describe("Filter by category (empty = all)"),
844
909
  bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
845
910
  rrf: z.boolean().optional().default(false).describe("Use Reciprocal Rank Fusion (BM25x3 + centrality ranks, adaptive k=sqrtN) instead of weighted linear scoring. Weight-free: reaches parity with the tuned linear scorer on scripts/bench-rrf.mjs."),
911
+ budget_tokens: z.number().optional().default(0).describe("Deterministic token budget: include entries until the estimated output reaches ~N tokens (overrides limit). 0 = no budget."),
912
+ explain: z.boolean().optional().default(false).describe("Append a 'why this entry' line to each result (relevance %, times used, last used, importance). No LLM — pure heuristics."),
846
913
  },
847
914
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
848
915
  },
849
- async ({ intent, limit, category, bias, rrf }) => {
916
+ async ({ intent, limit, category, bias, rrf, budget_tokens, explain }) => {
850
917
  const data = readMemory()
851
918
  const mtimes = fileMtimes()
852
919
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
853
- const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles, rrf })
920
+ const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles, rrf, budgetTokens: budget_tokens || undefined, explain })
854
921
  return { content: [{ type: "text" as const, text: result }] }
855
922
  }
856
923
  )
@@ -1065,9 +1132,9 @@ server.registerTool(
1065
1132
  "memory_consolidate",
1066
1133
  {
1067
1134
  title: "Consolidate Memory",
1068
- description: "Cleanup operations, all deterministic (no LLM): identical removes duplicate entries (keeps the first), similar merges entries with >50% word overlap (keeps longer content, combines tags), low-quality removes entries below minQuality or without tags.",
1135
+ description: "Cleanup operations, all deterministic (no LLM): identical removes duplicate entries (keeps the first), similar merges entries with >50% word overlap (keeps longer content, combines tags), low-quality removes entries below minQuality or without tags, versions marks entries describing the same subject with older versions obsolete in favor of the newest.",
1069
1136
  inputSchema: {
1070
- mode: z.enum(["identical", "similar", "low-quality"]).optional().default("identical").describe("identical: dedupe entries with identical content (default). similar: merge entries with >50% word overlap. low-quality: remove entries below minQuality or without tags."),
1137
+ mode: z.enum(["identical", "similar", "low-quality", "versions"]).optional().default("identical").describe("identical: dedupe entries with identical content (default). similar: merge entries with >50% word overlap. low-quality: remove entries below minQuality or without tags. versions: detect version supersession ('Use React 18' vs 'React 19') and obsolete the older ones."),
1071
1138
  minQuality: z.number().optional().default(0.3).describe("Entries below this quality score are candidates (only used with mode: low-quality)."),
1072
1139
  dryRun: z.boolean().optional().default(false).describe("If true, show what would change without writing."),
1073
1140
  },
@@ -1079,6 +1146,8 @@ server.registerTool(
1079
1146
  return runMergeSimilar(dryRun)
1080
1147
  case "low-quality":
1081
1148
  return runCompressAll(minQuality, dryRun)
1149
+ case "versions":
1150
+ return runConsolidateVersions(dryRun)
1082
1151
  default:
1083
1152
  return runConsolidate()
1084
1153
  }