toon-memory 4.3.4 → 4.4.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
@@ -7,7 +7,8 @@ import { readMemory, writeMemory, safeWrite } from "./memory-io"
7
7
  import { loadConfig, saveConfig, getKey, MEMORY_FILE, OBSERVATIONS_FILE, MEMORY_DIR, MAX_ENTRIES, getMaxEntries, ARCHIVE_FILE, GLOBAL_FILE } from "./config"
8
8
  import { generateId, parseTTL, isExpired, inferTags, parseRelativeDate } from "./entries"
9
9
  import { findRelatedEntries, bumpAccessed } from "./scoring"
10
- import { readObservations } from "./observations"
10
+ import { readObservations } from "./session-store"
11
+ import { positiveInt, optionalPositiveInt, requiredText, splitIds, noMatches } from "./args"
11
12
  import { archiveOldEntries } from "./archive"
12
13
  import { consolidateEntries, consolidateVersions, mergeMemoryFiles } from "./consolidation"
13
14
  import { readUnderLock } from "../lib/lock"
@@ -21,14 +22,55 @@ import { fileMtimes } from "../lib/git"
21
22
  import { normalize, isExpiredLocal, tokenize, importance, estimateTokens, parseToonLine, toToonLine, escField, unescField } from "../lib/utils"
22
23
  import { evidenceFor, detectContradictions } from "../lib/evidence"
23
24
  import { expandSynonyms } from "../lib/synonyms"
25
+ import { buildHandoffBrief, entryAgeDays, projectSlug } from "../lib/handoff"
26
+ import { compileContext, renderContextPackage } from "../lib/compiler"
27
+ import { appendFeedback, markWrong, readFeedback, utilityMap } from "./feedback"
28
+ import { deriveEdges, readEdges, rebuildEdges } from "./edges"
29
+ import type { ActivationEdge } from "../lib/activation"
30
+ import { denseScores } from "../lib/dense"
24
31
 
25
32
  /**
26
- * Register all MCP memory tools (38 total across tools.ts).
33
+ * Register all MCP memory tools (42 total across tools.ts).
27
34
  */
28
35
  export function registerTools(server: McpServer): void {
29
36
 
30
37
  type ToolText = { type: "text"; text: string }
31
38
 
39
+ /**
40
+ * Advanced tools stay registered only with TOON_MEMORY_EXPERT_TOOLS=1 so the
41
+ * default catalog is small enough for an agent to choose correctly.
42
+ */
43
+ const EXPERT_TOOLS = new Set([
44
+ "memory_stats", "memory_diff", "memory_suggest", "memory_primer", "memory_reflect",
45
+ "memory_visualize", "memory_graph_path", "memory_sessions", "memory_merge_sessions",
46
+ "memory_compress", "memory_consolidate", "memory_archive", "memory_backup",
47
+ "memory_encrypt", "memory_decrypt", "memory_secret", "memory_tag", "memory_pin",
48
+ "memory_unpin", "memory_edges", "context_generate", "context_diff", "context_focus", "context_health",
49
+ "context_export", "memory_export_gist", "memory_import_gist", "memory_export_global",
50
+ "memory_import_global",
51
+ ])
52
+ const expertMode = process.env.TOON_MEMORY_EXPERT_TOOLS === "1"
53
+ const sdk = server as any
54
+ const register = (name: string, config: any, cb: (...args: any[]) => any): void => {
55
+ if (!expertMode && EXPERT_TOOLS.has(name)) return
56
+ sdk.registerTool(name, config, cb)
57
+ }
58
+ const recallExtras = async (query = ""): Promise<{
59
+ utility: Map<string, number>
60
+ edges?: ActivationEdge[]
61
+ activation?: boolean
62
+ dense?: Map<string, number>
63
+ }> => {
64
+ const config = loadConfig()
65
+ const edges = config.graph?.activation ? readEdges() : undefined
66
+ const dense = config.dense?.enabled ? await denseScores(query, readMemory()) : new Map()
67
+ return {
68
+ utility: utilityMap(),
69
+ ...(edges && edges.length ? { edges, activation: true } : {}),
70
+ ...(dense.size ? { dense } : {}),
71
+ }
72
+ }
73
+
32
74
  // ── Shared lifecycle helpers (backing canonical memory_forget) ──
33
75
 
34
76
  function softDelete(key: string): { content: ToolText[] } {
@@ -453,15 +495,15 @@ function runCompressAll(minQuality: number, dryRun: boolean): { content: ToolTex
453
495
 
454
496
  // ── memory_remember ──────────────────────────────────────────────────────────
455
497
 
456
- server.registerTool(
498
+ register(
457
499
  "memory_remember",
458
500
  {
459
501
  title: "Save to Memory",
460
502
  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.",
461
503
  inputSchema: {
462
- 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."),
463
- key: z.string().describe("Short title in kebab-case (e.g. risk-engine-priority)"),
464
- content: z.string().describe("Detailed content of the fact"),
504
+ category: z.enum(["decision", "pattern", "bug", "knowledge", "warning", "architecture"]).describe("Category of the fact. 'warning' = negative memory ('NO hacer esto, rompe X') — recalled with a boost so past mistakes surface first."),
505
+ key: requiredText("key", 120).describe("Short title in kebab-case (e.g. risk-engine-priority)"),
506
+ content: requiredText("content").describe("Detailed content of the fact"),
465
507
  file: z.string().optional().default("").describe("Related file or line (e.g. spec.md:145)"),
466
508
  tags: z.string().optional().default("").describe("Semicolon-separated tags (e.g. risk;spec)"),
467
509
  ttl: z.string().optional().default("").describe("Time to live (e.g. 7d, 2026-07-17). Empty = no expiration"),
@@ -511,7 +553,7 @@ server.registerTool(
511
553
  // Write-path intelligence (deterministic, no LLM): detect contradictions
512
554
  // against warnings / critical decisions and annotate the entry with its
513
555
  // evidence level (verified when the referenced file exists on disk).
514
- const tagList = resolvedTags.split(";").map((t) => t.trim()).filter(Boolean)
556
+ const tagList = resolvedTags.split(";").map((t: string) => t.trim()).filter(Boolean)
515
557
  const candidate = { key, content, category, tags: tagList }
516
558
  const existingEntries = parseEntries(data)
517
559
  const conflicts = detectContradictions(existingEntries, candidate)
@@ -579,7 +621,7 @@ server.registerTool(
579
621
 
580
622
  // ── memory_recall ────────────────────────────────────────────────────────────
581
623
 
582
- server.registerTool(
624
+ register(
583
625
  "memory_recall",
584
626
  {
585
627
  title: "Search Memory",
@@ -587,34 +629,39 @@ server.registerTool(
587
629
  inputSchema: {
588
630
  query: z.string().optional().default("").describe("Text to search for (optional when mode:'index' or ids is given)"),
589
631
  category: z.string().optional().default("").describe("Filter by category (empty = all)"),
590
- from_date: z.string().optional().default("").describe("Start date filter (YYYY-MM-DD)"),
632
+ from_date: z.string().optional().default("").describe("Start date filter (YYYY-MM-DD or relative like 'ayer', 'la semana pasada', '7d')"),
633
+ since: z.string().optional().default("").describe("Alias of from_date with natural-language dates."),
591
634
  to_date: z.string().optional().default("").describe("End date filter (YYYY-MM-DD)"),
592
635
  mode: z.enum(["flat", "graph", "index"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall: expands the related-entry subgraph from matches (more precise, fewer tokens). 'index' = one line per entry (key, id, category, date, relevance %) with no content — browse then fetch full entries with `ids`."),
593
636
  ids: z.string().optional().default("").describe("Batch fetch: comma/space/;-separated entry ids or keys, rendered in the given order (unknown entries skipped). Complements mode:'index' — layer 2 of progressive disclosure. Overrides mode."),
594
- hops: z.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
595
- limit: z.number().optional().describe("Maximum entries returned. Default 6 (15 in 'index' mode). Keeps token cost low."),
596
- 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."),
597
- 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'."),
598
- 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."),
637
+ hops: positiveInt(1, 3).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
638
+ limit: optionalPositiveInt(200).describe("Maximum entries returned. Default 6 (15 in 'index' mode). Keeps token cost low."),
639
+ compact: z.boolean().optional().default(false).describe("Token-efficient output: numeric indices (1, 2), omits id/date/file (keeps tags). Does not mutate .toon file."),
640
+ budget: z.enum(["tiny", "normal", "deep"]).optional().describe("'tiny': key+1 line (~50 tokens). 'normal': compact with tags/edges. 'deep': all fields (default). Overrides 'compact'."),
641
+ budget_tokens: optionalPositiveInt(20000).describe("Deterministic token budget: include entries until the estimated output reaches ~N tokens (overrides limit)."),
599
642
  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."),
600
643
  bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
601
644
  path_scope: z.string().optional().default("").describe("Glob pattern to filter entries by path scope (e.g. 'src/**.ts')."),
602
645
  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."),
603
646
  as_of: z.string().optional().default("").describe("Temporal view (YYYY-MM-DD): return entries valid on that date. Superseded entries still appear if they were active then."),
647
+ today: z.string().optional().default("").describe("Alias of as_of (documented in older changelogs)."),
648
+ sessionBias: z.boolean().optional().default(false).describe("Alias of bias:'session' (documented in older READMEs)."),
604
649
  },
605
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
650
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
606
651
  },
607
- async ({ query, category, from_date, to_date, mode, ids, hops, limit: limitParam, compact, budget: budgetParam, budget_tokens, explain, bias, path_scope, rrf, as_of }) => {
652
+ async ({ query, category, from_date, since, to_date, mode, ids, hops, limit: limitParam, compact, budget: budgetParam, budget_tokens, explain, bias, path_scope, rrf, as_of, today, sessionBias }) => {
608
653
  const data = readMemory()
609
654
  const resolvedBudget = budgetParam || (compact ? "normal" : "deep")
610
- const resolvedAsOf = as_of || undefined
655
+ const resolvedAsOf = as_of || today || undefined
656
+ const resolvedBias = sessionBias && bias === "none" ? "session" : bias
657
+ const resolvedFrom = from_date || since ? parseRelativeDate(from_date || since) : ""
611
658
 
612
659
  // ── Batch fetch by ids/keys (layer 2 of progressive disclosure) ──────
613
660
  if (ids && ids.trim()) {
614
- const tokens = ids.split(/[\s,;]+/).map((t) => t.trim()).filter(Boolean)
661
+ const tokens = splitIds(ids)
615
662
  const entries = fetchEntriesByIds(data, tokens, { asOf: resolvedAsOf })
616
663
  if (entries.length === 0) {
617
- return { content: [{ type: "text" as const, text: `No entries found for ids: ${ids}` }] }
664
+ return noMatches(ids)
618
665
  }
619
666
  bumpAccessed(entries.map((e) => e.id))
620
667
  const label = entries.length === 1 ? "entry" : "entries"
@@ -641,15 +688,13 @@ server.registerTool(
641
688
 
642
689
  // Delegate to graphRecallDetailed for flat / graph / index modes
643
690
  // This avoids duplicating BM25 + ranking logic
644
- const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
691
+ const sessionFiles = resolvedBias === "session" ? getCurrentSessionFiles() : undefined
645
692
  const limit = limitParam ?? (mode === "index" ? 15 : 6)
646
- const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, limit, sessionFiles, path_scope: path_scope || undefined, rrf, asOf: resolvedAsOf })
693
+ const detail = graphRecallDetailed(data, query, { category, from_date: resolvedFrom, to_date, hops, limit, sessionFiles, path_scope: path_scope || undefined, rrf, asOf: resolvedAsOf, ...(await recallExtras(query)) })
647
694
 
648
695
  // ── Index mode: one line per entry, no content ───────────────────────
649
696
  if (mode === "index") {
650
- if (detail.entries.length === 0) {
651
- return { content: [{ type: "text" as const, text: `No results found for "${query}"` }] }
652
- }
697
+ if (detail.entries.length === 0) return noMatches(query)
653
698
  const formatted = renderIndex(detail.entries, { scores: detail.scores })
654
699
  return {
655
700
  content: [{
@@ -659,9 +704,7 @@ server.registerTool(
659
704
  }
660
705
  }
661
706
 
662
- if (detail.entries.length === 0) {
663
- return { content: [{ type: "text" as const, text: `No results found for "${query}"` }] }
664
- }
707
+ if (detail.entries.length === 0) return noMatches(query)
665
708
  bumpAccessed(detail.entries.map((e) => e.id))
666
709
  const reasons = explain ? detail.reasons : undefined
667
710
  if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
@@ -705,13 +748,13 @@ server.registerTool(
705
748
 
706
749
  // ── memory_forget ────────────────────────────────────────────────────────────
707
750
 
708
- server.registerTool(
751
+ register(
709
752
  "memory_forget",
710
753
  {
711
754
  title: "Forget from Memory",
712
755
  description: "Lifecycle operations for a memory entry: soft (default) marks it obsolete and hides it from recalls, hard permanently removes it, restore brings it back to active, supersede retires it with a typed superseded_by edge to a newer entry.",
713
756
  inputSchema: {
714
- key: z.string().describe("Key or id of the entry"),
757
+ key: requiredText("key", 200).describe("Key or id of the entry"),
715
758
  action: z.enum(["soft", "hard", "restore", "supersede"]).optional().default("soft").describe("soft: mark obsolete (default). hard: permanently remove. restore: bring an obsolete entry back to active. supersede: mark obsolete with a superseded_by link to new_key."),
716
759
  new_key: z.string().optional().default("").describe("Replacement entry key or id (only used with action: supersede)."),
717
760
  reason: z.string().optional().default("").describe("Optional note appended to the old entry (only used with action: supersede)."),
@@ -734,7 +777,7 @@ server.registerTool(
734
777
 
735
778
  // ── memory_stats ─────────────────────────────────────────────────────────────
736
779
 
737
- server.registerTool(
780
+ register(
738
781
  "memory_stats",
739
782
  {
740
783
  title: "Memory Stats",
@@ -791,9 +834,19 @@ server.registerTool(
791
834
  const deadCount = byStatus["obsolete"] || 0
792
835
  const deadPct = entries.length > 0 ? ((deadCount / entries.length) * 100).toFixed(0) : "0"
793
836
 
837
+ const today = new Date().toISOString().split("T")[0]
838
+ const newest = fullParts.map((p) => p[6] || "").filter(Boolean).sort().at(-1) || ""
839
+ const age = newest ? entryAgeDays(newest, today) : 0
840
+ const freshness = !newest ? "empty" : age > 30 ? `stale-${age}d` : "fresh"
841
+ const staleCount = fullParts.filter((p) => p[6] && entryAgeDays(p[6], today) > 30 && p[16] !== "obsolete").length
842
+ const trapCount = fullParts.filter(
843
+ (p) => p[1] === "warning" || /(^|;)(trap|gotcha|risk)(;|$)/i.test(p[5] || "")
844
+ ).length
845
+
794
846
  const stats = [
795
847
  `Total entries: ${entries.length}`,
796
848
  `File summaries: ${summaryLines.length}`,
849
+ `Freshness: ${freshness} | stale: ${staleCount} | traps: ${trapCount} | catalog: ${expertMode ? "expert" : "core"}`,
797
850
  "",
798
851
  "By category:",
799
852
  ...Object.entries(byCategory).map(([k, v]) => ` ${k}: ${v}`),
@@ -879,13 +932,13 @@ server.registerTool(
879
932
 
880
933
  // ── memory_diff ──────────────────────────────────────────────────────────────
881
934
 
882
- server.registerTool(
935
+ register(
883
936
  "memory_diff",
884
937
  {
885
938
  title: "Memory Diff",
886
939
  description: "Show what changed in memory since a date. Useful for seeing what was learned since the last session.",
887
940
  inputSchema: {
888
- since: z.string().describe("Show changes since (e.g. 24h, 7d, 2026-07-10)"),
941
+ since: requiredText("since", 80).describe("Show changes since (e.g. 24h, 7d, 2026-07-10)"),
889
942
  type: z.enum(["all", "created", "updated"]).optional().default("all").describe("Filter by change type"),
890
943
  },
891
944
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
@@ -940,14 +993,14 @@ server.registerTool(
940
993
 
941
994
  // ── memory_suggest ───────────────────────────────────────────────────────────
942
995
 
943
- server.registerTool(
996
+ register(
944
997
  "memory_suggest",
945
998
  {
946
999
  title: "Suggest Related Memories",
947
1000
  description: "Suggest memory entries related to a given context. Useful for gathering context before a task.",
948
1001
  inputSchema: {
949
- context: z.string().describe("Text or context to search for suggestions"),
950
- limit: z.number().optional().default(5).describe("Maximum suggestions"),
1002
+ context: requiredText("context", 500).describe("Text or context to search for suggestions"),
1003
+ limit: positiveInt(5, 20).describe("Maximum suggestions"),
951
1004
  },
952
1005
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
953
1006
  },
@@ -968,18 +1021,18 @@ server.registerTool(
968
1021
 
969
1022
  // ── memory_smart_recall ──────────────────────────────────────────────────────
970
1023
 
971
- server.registerTool(
1024
+ register(
972
1025
  "memory_smart_recall",
973
1026
  {
974
1027
  title: "Smart Recall (Unified)",
975
1028
  description: "Unified retrieval: combines BM25 + graph + decay + quality in a single call. Use at the START of each task to get all relevant memory context. Then use context_diff for recent changes, context_focus for deep dives.",
976
1029
  inputSchema: {
977
- intent: z.string().describe("Describe what you need to know (e.g. 'database schema for backend')"),
978
- limit: z.number().optional().default(8).describe("Maximum entries to return"),
1030
+ intent: requiredText("intent", 500).describe("Describe what you need to know (e.g. 'database schema for backend')"),
1031
+ limit: positiveInt(8, 50).describe("Maximum entries to return"),
979
1032
  category: z.string().optional().default("").describe("Filter by category (empty = all)"),
980
1033
  bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
981
1034
  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."),
982
- 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."),
1035
+ budget_tokens: optionalPositiveInt(20000).describe("Deterministic token budget: include entries until the estimated output reaches ~N tokens (overrides limit)."),
983
1036
  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."),
984
1037
  },
985
1038
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
@@ -988,21 +1041,21 @@ server.registerTool(
988
1041
  const data = readMemory()
989
1042
  const mtimes = fileMtimes()
990
1043
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
991
- const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles, rrf, budgetTokens: budget_tokens || undefined, explain })
1044
+ const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles, rrf, budgetTokens: budget_tokens || undefined, explain, ...(await recallExtras(intent)) })
992
1045
  return { content: [{ type: "text" as const, text: result }] }
993
1046
  }
994
1047
  )
995
1048
 
996
1049
  // ── memory_summary ───────────────────────────────────────────────────────────
997
1050
 
998
- server.registerTool(
1051
+ register(
999
1052
  "memory_summary",
1000
1053
  {
1001
1054
  title: "File Summary",
1002
1055
  description: "Save or retrieve a summary of a large file to save tokens.",
1003
1056
  inputSchema: {
1004
1057
  action: z.enum(["get", "set"]).describe("get to read, set to save"),
1005
- file: z.string().describe("File path"),
1058
+ file: requiredText("file", 500).describe("File path"),
1006
1059
  summary: z.string().optional().default("").describe("File summary (only for set)"),
1007
1060
  },
1008
1061
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
@@ -1054,7 +1107,7 @@ server.registerTool(
1054
1107
 
1055
1108
  // ── memory_archive ───────────────────────────────────────────────────────────
1056
1109
 
1057
- server.registerTool(
1110
+ register(
1058
1111
  "memory_archive",
1059
1112
  {
1060
1113
  title: "Archive Old Entries",
@@ -1080,7 +1133,7 @@ server.registerTool(
1080
1133
 
1081
1134
  // ── memory_encrypt ───────────────────────────────────────────────────────────
1082
1135
 
1083
- server.registerTool(
1136
+ register(
1084
1137
  "memory_encrypt",
1085
1138
  {
1086
1139
  title: "Enable Encryption",
@@ -1114,13 +1167,13 @@ server.registerTool(
1114
1167
 
1115
1168
  // ── memory_decrypt ───────────────────────────────────────────────────────────
1116
1169
 
1117
- server.registerTool(
1170
+ register(
1118
1171
  "memory_decrypt",
1119
1172
  {
1120
1173
  title: "Disable Encryption",
1121
1174
  description: "Disable encryption and decode memory.",
1122
1175
  inputSchema: {
1123
- key: z.string().describe("Encryption key"),
1176
+ key: z.string().optional().default("").describe("Encryption key. If omitted, TOON_MEMORY_KEY is used."),
1124
1177
  },
1125
1178
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
1126
1179
  },
@@ -1154,7 +1207,7 @@ server.registerTool(
1154
1207
 
1155
1208
  // ── memory_secret ────────────────────────────────────────────────────────────
1156
1209
 
1157
- server.registerTool(
1210
+ register(
1158
1211
  "memory_secret",
1159
1212
  {
1160
1213
  title: "Encrypted Secrets Vault",
@@ -1224,13 +1277,13 @@ server.registerTool(
1224
1277
 
1225
1278
  // ── memory_captured ──────────────────────────────────────────────────────────
1226
1279
 
1227
- server.registerTool(
1280
+ register(
1228
1281
  "memory_captured",
1229
1282
  {
1230
1283
  title: "List Captured Activity",
1231
1284
  description: "Show activity log captured automatically by hooks (only if capture is enabled). Useful for promoting observations to memory with memory_remember.",
1232
1285
  inputSchema: {
1233
- limit: z.number().optional().default(20).describe("Maximum observations to show"),
1286
+ limit: positiveInt(20, 100).describe("Maximum observations to show"),
1234
1287
  tool: z.string().optional().default("").describe("Filter by tool name"),
1235
1288
  file: z.string().optional().default("").describe("Filter by file"),
1236
1289
  clear: z.boolean().optional().default(false).describe("If true, clears the capture log"),
@@ -1269,14 +1322,14 @@ server.registerTool(
1269
1322
 
1270
1323
  // ── memory_consolidate ───────────────────────────────────────────────────────
1271
1324
 
1272
- server.registerTool(
1325
+ register(
1273
1326
  "memory_consolidate",
1274
1327
  {
1275
1328
  title: "Consolidate Memory",
1276
1329
  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.",
1277
1330
  inputSchema: {
1278
1331
  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."),
1279
- minQuality: z.number().optional().default(0.3).describe("Entries below this quality score are candidates (only used with mode: low-quality)."),
1332
+ minQuality: z.coerce.number().min(0).max(1).optional().default(0.3).describe("Entries below this quality score are candidates (only used with mode: low-quality)."),
1280
1333
  dryRun: z.boolean().optional().default(false).describe("If true, show what would change without writing."),
1281
1334
  },
1282
1335
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
@@ -1297,7 +1350,7 @@ server.registerTool(
1297
1350
 
1298
1351
  // ── memory_sessions ──────────────────────────────────────────────────────────
1299
1352
 
1300
- server.registerTool(
1353
+ register(
1301
1354
  "memory_sessions",
1302
1355
  {
1303
1356
  title: "Active Sessions & Conflicts",
@@ -1365,27 +1418,85 @@ server.registerTool(
1365
1418
 
1366
1419
  // ── context_brief ────────────────────────────────────────────────────────────
1367
1420
 
1368
- server.registerTool(
1421
+ register(
1369
1422
  "context_brief",
1370
1423
  {
1371
1424
  title: "Context Briefing",
1372
1425
  description: "Generate a compact context briefing: relevant memory + active sessions + project health. Single call instead of 5-6 separate calls. Zero LLM, pure deterministic logic.",
1373
1426
  inputSchema: {
1374
1427
  task: z.string().optional().default("").describe("Current agent task. If provided, entries are ranked by relevance to this task. If empty, shows top entries by importance."),
1375
- limit: z.number().optional().default(6).describe("Maximum relevant entries to show"),
1428
+ limit: positiveInt(6, 50).describe("Maximum relevant entries to show"),
1429
+ handoff: z.boolean().optional().default(true).describe("Prepend the compact handoff packet with identity, freshness, directives, traps and file pointers."),
1430
+ budget: positiveInt(1200, 4000).describe("Token ceiling for the handoff packet when handoff=true."),
1376
1431
  },
1377
1432
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
1378
1433
  },
1379
- async ({ task, limit }) => {
1434
+ async ({ task, limit, handoff, budget }) => {
1380
1435
  const data = readMemory()
1436
+ if (task && handoff) {
1437
+ const sessions = readObservations()
1438
+ .slice(-2)
1439
+ .map((e) => `${e.session || "cli"}: ${e.summary.slice(0, 80)}`)
1440
+ const compiled = compileContext(data, task, { maxTokens: budget, ...(await recallExtras(task)), sessions })
1441
+ return { content: [{ type: "text" as const, text: renderContextPackage(compiled) }] }
1442
+ }
1381
1443
  const brief = generateContextBrief(data, { task: task || undefined, limit })
1382
- return { content: [{ type: "text" as const, text: brief }] }
1444
+ if (!handoff) return { content: [{ type: "text" as const, text: brief }] }
1445
+ const packet = buildHandoffBrief(data, process.cwd(), { task: task || undefined, maxTokens: budget })
1446
+ return { content: [{ type: "text" as const, text: `${packet}\n\n${brief}` }] }
1447
+ }
1448
+ )
1449
+
1450
+ // ── context_compile ──────────────────────────────────────────────────────────
1451
+
1452
+ register(
1453
+ "context_compile",
1454
+ {
1455
+ title: "Compile Task Context",
1456
+ description: "Compile a task into a tiny context packet: directives, constraints, relevant memory, decisions, retrieval queries, hydrate keys, files and sessions. Deterministic, zero LLM, feedback-aware. Prefer this over context_brief when a task is known.",
1457
+ inputSchema: {
1458
+ task: requiredText("task", 1000).describe("Current agent task or question"),
1459
+ budget: positiveInt(200, 6000).describe("Token ceiling for the compiled packet"),
1460
+ },
1461
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
1462
+ },
1463
+ async ({ task, budget }) => {
1464
+ const data = readMemory()
1465
+ const sessions = readObservations()
1466
+ .slice(-2)
1467
+ .map((e) => `${e.session || "cli"}: ${e.summary.slice(0, 80)}`)
1468
+ const compiled = compileContext(data, task, { maxTokens: budget, ...(await recallExtras(task)), sessions })
1469
+ return { content: [{ type: "text" as const, text: renderContextPackage(compiled) }] }
1470
+ }
1471
+ )
1472
+
1473
+ // ── context_hydrate ──────────────────────────────────────────────────────────
1474
+
1475
+ register(
1476
+ "context_hydrate",
1477
+ {
1478
+ title: "Hydrate Compressed Context",
1479
+ description: "Expand hydrate keys emitted by context_compile into full memory entries. Layer 2 of progressive disclosure.",
1480
+ inputSchema: {
1481
+ keys: z.array(requiredText("key", 200)).min(1).max(20).describe("Keys or ids from context_compile's Hydrate section"),
1482
+ },
1483
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
1484
+ },
1485
+ async ({ keys }) => {
1486
+ const data = readMemory()
1487
+ const entries = fetchEntriesByIds(data, splitIds(keys.join(",")))
1488
+ if (entries.length === 0) return noMatches(keys.join(","))
1489
+ bumpAccessed(entries.map((e) => e.id))
1490
+ const formatted = entries
1491
+ .map((e) => `[${e.category}] ${e.key} (${e.id})\n ${e.content}\n File: ${e.file} | Tags: ${e.tags.join(";")} | Date: ${e.date}`)
1492
+ .join("\n\n")
1493
+ return { content: [{ type: "text" as const, text: `Hydrated ${entries.length} ${entries.length === 1 ? "entry" : "entries"}:\n\n${formatted}` }] }
1383
1494
  }
1384
1495
  )
1385
1496
 
1386
1497
  // ── context_generate ─────────────────────────────────────────────────
1387
1498
 
1388
- server.registerTool(
1499
+ register(
1389
1500
  "context_generate",
1390
1501
  {
1391
1502
  title: "Generate Full Context",
@@ -1405,7 +1516,7 @@ server.registerTool(
1405
1516
 
1406
1517
  // ── context_diff ─────────────────────────────────────────────────────
1407
1518
 
1408
- server.registerTool(
1519
+ register(
1409
1520
  "context_diff",
1410
1521
  {
1411
1522
  title: "Context Diff",
@@ -1425,14 +1536,14 @@ server.registerTool(
1425
1536
 
1426
1537
  // ── context_focus ────────────────────────────────────────────────────
1427
1538
 
1428
- server.registerTool(
1539
+ register(
1429
1540
  "context_focus",
1430
1541
  {
1431
1542
  title: "Focus Context for Task",
1432
1543
  description: "Hyper-focused context for a specific task: relevant entries + related files + code referencing the symbol + existing tests. Zero LLM.",
1433
1544
  inputSchema: {
1434
- task: z.string().describe("Task or symbol to search context for (e.g. 'fix auth bug', 'authenticate')"),
1435
- limit: z.number().optional().default(6).describe("Maximum memory entries to include"),
1545
+ task: requiredText("task", 500).describe("Task or symbol to search context for (e.g. 'fix auth bug', 'authenticate')"),
1546
+ limit: positiveInt(6, 50).describe("Maximum memory entries to include"),
1436
1547
  },
1437
1548
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
1438
1549
  },
@@ -1446,7 +1557,7 @@ server.registerTool(
1446
1557
 
1447
1558
  // ── context_health ───────────────────────────────────────────────────
1448
1559
 
1449
- server.registerTool(
1560
+ register(
1450
1561
  "context_health",
1451
1562
  {
1452
1563
  title: "Memory Health Audit",
@@ -1464,7 +1575,7 @@ server.registerTool(
1464
1575
 
1465
1576
  // ── context_export ───────────────────────────────────────────────────
1466
1577
 
1467
- server.registerTool(
1578
+ register(
1468
1579
  "context_export",
1469
1580
  {
1470
1581
  title: "Export Memory as Markdown",
@@ -1483,7 +1594,7 @@ server.registerTool(
1483
1594
 
1484
1595
  // ── memory_backup ───────────────────────────────────────────────────
1485
1596
 
1486
- server.registerTool(
1597
+ register(
1487
1598
  "memory_backup",
1488
1599
  {
1489
1600
  title: "Backup Memory",
@@ -1537,7 +1648,7 @@ server.registerTool(
1537
1648
 
1538
1649
  // ── memory_primer ─────────────────────────────────────────────────────
1539
1650
 
1540
- server.registerTool(
1651
+ register(
1541
1652
  "memory_primer",
1542
1653
  {
1543
1654
  title: "System Primer",
@@ -1555,14 +1666,14 @@ server.registerTool(
1555
1666
 
1556
1667
  // ── memory_compress ────────────────────────────────────────────────────
1557
1668
 
1558
- server.registerTool(
1669
+ register(
1559
1670
  "memory_compress",
1560
1671
  {
1561
1672
  title: "Compress Memory Entries",
1562
1673
  description: "LLM-powered compression: select entries to compress into one concise entry. The agent (YOU) reads the entries, writes a compressed summary, then calls memory_remember to save it. Two-step dance: this tool provides context, you provide intelligence.",
1563
1674
  inputSchema: {
1564
1675
  query: z.string().optional().default("").describe("Search query to find entries to compress (e.g. 'auth bug fixes'). Empty = show lowest-quality entries."),
1565
- count: z.number().optional().default(3).describe("Number of entries to compress (2-10). Default: 3."),
1676
+ count: positiveInt(3, 10).describe("Number of entries to compress (2-10). Default: 3."),
1566
1677
  category: z.string().optional().default("").describe("Filter by category (empty = all)."),
1567
1678
  },
1568
1679
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
@@ -1642,7 +1753,7 @@ server.registerTool(
1642
1753
 
1643
1754
  // ── memory_export_gist ─────────────────────────────────────────────────
1644
1755
 
1645
- server.registerTool(
1756
+ register(
1646
1757
  "memory_export_gist",
1647
1758
  {
1648
1759
  title: "Export to GitHub Gist",
@@ -1707,13 +1818,13 @@ server.registerTool(
1707
1818
 
1708
1819
  // ── memory_import_gist ─────────────────────────────────────────────────
1709
1820
 
1710
- server.registerTool(
1821
+ register(
1711
1822
  "memory_import_gist",
1712
1823
  {
1713
1824
  title: "Import from GitHub Gist",
1714
1825
  description: "Import memory from a GitHub Gist. Merges entries (keeps newer dates, combines tags). Requires GITHUB_TOKEN env var.",
1715
1826
  inputSchema: {
1716
- gist_id: z.string().describe("GitHub Gist ID or full URL (https://gist.github.com/user/id)."),
1827
+ gist_id: requiredText("gist_id", 300).describe("GitHub Gist ID or full URL (https://gist.github.com/user/id)."),
1717
1828
  merge: z.boolean().optional().default(true).describe("If true, merge with existing memory. If false, replace entirely."),
1718
1829
  },
1719
1830
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
@@ -1829,7 +1940,7 @@ server.registerTool(
1829
1940
  // are pulled into a project with a one-shot merge (offline, deterministic) —
1830
1941
  // never a live dual-source recall, so the ranking pipeline stays untouched.
1831
1942
 
1832
- server.registerTool(
1943
+ register(
1833
1944
  "memory_export_global",
1834
1945
  {
1835
1946
  title: "Export to Global Memory",
@@ -1851,7 +1962,7 @@ server.registerTool(
1851
1962
  }
1852
1963
  )
1853
1964
 
1854
- server.registerTool(
1965
+ register(
1855
1966
  "memory_import_global",
1856
1967
  {
1857
1968
  title: "Import Global Memory",
@@ -1891,7 +2002,7 @@ server.registerTool(
1891
2002
 
1892
2003
  // ── memory_merge_sessions ──────────────────────────────────────────────
1893
2004
 
1894
- server.registerTool(
2005
+ register(
1895
2006
  "memory_merge_sessions",
1896
2007
  {
1897
2008
  title: "Merge Session Observations",
@@ -2035,14 +2146,14 @@ server.registerTool(
2035
2146
 
2036
2147
  // ── memory_graph_path ────────────────────────────────────────────────
2037
2148
 
2038
- server.registerTool(
2149
+ register(
2039
2150
  "memory_graph_path",
2040
2151
  {
2041
2152
  title: "Find Graph Path",
2042
2153
  description: "Find the shortest path between two memory entries in the knowledge graph. Shows how two concepts are connected through related entries.",
2043
2154
  inputSchema: {
2044
- from: z.string().describe("Starting entry key"),
2045
- to: z.string().describe("Target entry key"),
2155
+ from: requiredText("from", 200).describe("Starting entry key"),
2156
+ to: requiredText("to", 200).describe("Target entry key"),
2046
2157
  },
2047
2158
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
2048
2159
  },
@@ -2111,7 +2222,7 @@ server.registerTool(
2111
2222
 
2112
2223
  // ── memory_checkpoint ─────────────────────────────────────────────────────────
2113
2224
 
2114
- server.registerTool(
2225
+ register(
2115
2226
  "memory_checkpoint",
2116
2227
  {
2117
2228
  title: "Session Checkpoint",
@@ -2200,14 +2311,14 @@ server.registerTool(
2200
2311
 
2201
2312
  // ── memory_pin ───────────────────────────────────────────────────────────────
2202
2313
 
2203
- server.registerTool(
2314
+ register(
2204
2315
  "memory_pin",
2205
2316
  {
2206
2317
  title: "Pin Entry",
2207
2318
  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.",
2208
2319
  inputSchema: {
2209
- key: z.string().describe("Key or id of the entry to pin"),
2210
- priority: z.number().optional().default(1).describe("Priority level 1-5 (5 = highest). Default: 1."),
2320
+ key: requiredText("key", 200).describe("Key or id of the entry to pin"),
2321
+ priority: positiveInt(1, 5).describe("Priority level 1-5 (5 = highest). Default: 1."),
2211
2322
  },
2212
2323
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
2213
2324
  },
@@ -2248,13 +2359,13 @@ server.registerTool(
2248
2359
 
2249
2360
  // ── memory_unpin ─────────────────────────────────────────────────────────────
2250
2361
 
2251
- server.registerTool(
2362
+ register(
2252
2363
  "memory_unpin",
2253
2364
  {
2254
2365
  title: "Unpin Entry",
2255
2366
  description: "Remove the pin from a memory entry so it returns to normal ranking.",
2256
2367
  inputSchema: {
2257
- key: z.string().describe("Key or id of the entry to unpin"),
2368
+ key: requiredText("key", 200).describe("Key or id of the entry to unpin"),
2258
2369
  },
2259
2370
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
2260
2371
  },
@@ -2292,22 +2403,81 @@ server.registerTool(
2292
2403
  }
2293
2404
  )
2294
2405
 
2406
+ // ── memory_feedback ──────────────────────────────────────────────────────────
2407
+
2408
+ register(
2409
+ "memory_feedback",
2410
+ {
2411
+ title: "Feedback on recalled memory",
2412
+ description: "Tell toon-memory whether a recalled entry was useful, irrelevant, outdated or wrong. Explicit feedback adjusts learned utility; 'wrong' also flags evidence as conflict. Use this after acting on a recalled memory.",
2413
+ inputSchema: {
2414
+ key: requiredText("key", 200).describe("Key or id of the entry you used"),
2415
+ signal: z.enum(["useful", "irrelevant", "outdated", "wrong"]).describe("useful | irrelevant | outdated | wrong"),
2416
+ task: z.string().trim().max(500).optional().describe("Short description of the task where the memory was used"),
2417
+ },
2418
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
2419
+ },
2420
+ async ({ key, signal, task }) => {
2421
+ const data = readMemory()
2422
+ const entry = parseEntries(data).find((e) => e.key === key || e.id === key)
2423
+ if (!entry) {
2424
+ return { content: [{ type: "text" as const, text: `"${key}" not found in memory.` }] }
2425
+ }
2426
+ appendFeedback({ key: entry.key, signal, source: "explicit", task: task || "" })
2427
+ if (signal === "wrong") markWrong(entry.key)
2428
+ const utility = utilityMap().get(entry.key) || 0
2429
+ return {
2430
+ content: [{
2431
+ type: "text" as const,
2432
+ text: `📣 Feedback recorded: ${entry.key} → ${signal}. Learned utility: ${utility.toFixed(2)}${signal === "wrong" ? " (evidence flagged as conflict)" : ""}.`,
2433
+ }],
2434
+ }
2435
+ }
2436
+ )
2437
+
2438
+ // ── memory_edges ─────────────────────────────────────────────────────────────
2439
+
2440
+ register(
2441
+ "memory_edges",
2442
+ {
2443
+ title: "Typed memory edges",
2444
+ description: "List or rebuild typed edges in edges.toon. Edges are derived from explicit links and feedback; spread activation is opt-in via config.graph.activation.",
2445
+ inputSchema: {
2446
+ action: z.enum(["list", "rebuild"]).optional().default("list").describe("list shows current edges; rebuild derives them from data.toon and feedback.toon"),
2447
+ limit: positiveInt(20, 200).describe("Maximum edges to list"),
2448
+ },
2449
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
2450
+ },
2451
+ async ({ action, limit }) => {
2452
+ if (action === "rebuild") {
2453
+ const count = rebuildEdges(readMemory(), readFeedback())
2454
+ return { content: [{ type: "text" as const, text: `Rebuilt ${count} typed edge(s) in edges.toon.` }] }
2455
+ }
2456
+ const edges = readEdges().slice(0, limit)
2457
+ if (edges.length === 0) {
2458
+ return { content: [{ type: "text" as const, text: "No typed edges yet. Run memory_edges(action=\"rebuild\")." }] }
2459
+ }
2460
+ const text = edges.map((e) => `${e.from} -[${e.type} ${e.weight.toFixed(2)}]-> ${e.to} (${e.ts || "unknown"})`).join("\n")
2461
+ return { content: [{ type: "text" as const, text: `${edges.length} typed edge(s):\n${text}` }] }
2462
+ }
2463
+ )
2464
+
2295
2465
  // ── memory_search ────────────────────────────────────────────────────────────
2296
2466
 
2297
- server.registerTool(
2467
+ register(
2298
2468
  "memory_search",
2299
2469
  {
2300
2470
  title: "Unified Search",
2301
2471
  description: "Search memory with combined filters: text query, category, tags, and date range. Returns ranked results.",
2302
2472
  inputSchema: {
2303
- query: z.string().describe("Text to search for"),
2473
+ query: requiredText("query", 500).describe("Text to search for"),
2304
2474
  category: z.string().optional().default("").describe("Filter by category (empty = all)"),
2305
2475
  tags: z.string().optional().default("").describe("Semicolon-separated tags; entry must have ALL specified tags"),
2306
2476
  from_date: z.string().optional().default("").describe("Start date filter (YYYY-MM-DD or relative like 7d)"),
2307
2477
  to_date: z.string().optional().default("").describe("End date filter (YYYY-MM-DD)"),
2308
- limit: z.number().optional().default(6).describe("Maximum entries to return"),
2478
+ limit: positiveInt(6, 200).describe("Maximum entries to return"),
2309
2479
  mode: z.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall."),
2310
- hops: z.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
2480
+ hops: positiveInt(1, 3).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
2311
2481
  compact: z.boolean().optional().default(false).describe("Token-efficient output"),
2312
2482
  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'."),
2313
2483
  bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
@@ -2315,7 +2485,7 @@ server.registerTool(
2315
2485
  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."),
2316
2486
  as_of: z.string().optional().default("").describe("Temporal view (YYYY-MM-DD): return entries valid on that date."),
2317
2487
  },
2318
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
2488
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
2319
2489
  },
2320
2490
  async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact, bias, budget: budgetParam, path_scope, rrf, as_of }) => {
2321
2491
  const data = readMemory()
@@ -2333,12 +2503,11 @@ server.registerTool(
2333
2503
  sessionFiles,
2334
2504
  path_scope: path_scope || undefined,
2335
2505
  rrf,
2506
+ ...(await recallExtras(query)),
2336
2507
  asOf: as_of || undefined,
2337
2508
  })
2338
2509
 
2339
- if (detail.entries.length === 0) {
2340
- return { content: [{ type: "text" as const, text: `No results found for "${query}"` }] }
2341
- }
2510
+ if (detail.entries.length === 0) return noMatches(query)
2342
2511
 
2343
2512
  bumpAccessed(detail.entries.map((e) => e.id))
2344
2513
 
@@ -2378,15 +2547,15 @@ server.registerTool(
2378
2547
 
2379
2548
  // ── memory_tag ───────────────────────────────────────────────────────────────
2380
2549
 
2381
- server.registerTool(
2550
+ register(
2382
2551
  "memory_tag",
2383
2552
  {
2384
2553
  title: "Batch Tag Operations",
2385
2554
  description: "Batch add, remove, or set tags on one or more memory entries by key or id.",
2386
2555
  inputSchema: {
2387
2556
  action: z.enum(["add", "remove", "set"]).describe("'add': merge tags (union). 'remove': remove specified tags. 'set': replace all tags."),
2388
- tags: z.string().describe("Semicolon-separated tags to apply"),
2389
- ids: z.string().describe("Comma or space-separated entry keys or IDs to modify"),
2557
+ tags: requiredText("tags", 300).describe("Semicolon-separated tags to apply"),
2558
+ ids: requiredText("ids", 1000).describe("Comma, semicolon or space-separated entry keys or IDs to modify"),
2390
2559
  },
2391
2560
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
2392
2561
  },
@@ -2399,9 +2568,9 @@ server.registerTool(
2399
2568
  return { content: [{ type: "text" as const, text: "No entries in memory." }] }
2400
2569
  }
2401
2570
 
2402
- const targetIds = ids.split(/[\s,]+/).filter(Boolean)
2571
+ const targetIds = splitIds(ids)
2403
2572
  const targetSet = new Set(targetIds)
2404
- const tagsToApply = tags.split(";").map((t) => t.trim()).filter(Boolean)
2573
+ const tagsToApply = tags.split(";").map((t: string) => t.trim()).filter(Boolean)
2405
2574
 
2406
2575
  if (tagsToApply.length === 0) {
2407
2576
  return { content: [{ type: "text" as const, text: "No tags provided." }] }
@@ -2455,14 +2624,14 @@ server.registerTool(
2455
2624
 
2456
2625
  // ── memory_reflect ───────────────────────────────────────────────────────────
2457
2626
 
2458
- server.registerTool(
2627
+ register(
2459
2628
  "memory_reflect",
2460
2629
  {
2461
2630
  title: "Reflect on Memory",
2462
2631
  description: "Deterministic memory audit (no LLM): tag co-occurrence themes, hub/orphan entries, near-duplicates, contradiction candidates, stale entries, and superseded-but-active entries. Signals what to link, merge, or retire.",
2463
2632
  inputSchema: {
2464
2633
  category: z.string().optional().default("").describe("Restrict analysis to one category (empty = all)."),
2465
- limit: z.number().optional().default(5).describe("Max items per section."),
2634
+ limit: positiveInt(5, 20).describe("Max items per section."),
2466
2635
  },
2467
2636
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
2468
2637
  },
@@ -2607,16 +2776,16 @@ server.registerTool(
2607
2776
 
2608
2777
  // ── memory_promote ───────────────────────────────────────────────────────────
2609
2778
 
2610
- server.registerTool(
2779
+ register(
2611
2780
  "memory_promote",
2612
2781
  {
2613
2782
  title: "Promote Observations",
2614
2783
  description: "Heuristic auto-promote from the capture log (no LLM). Each observation gets a deterministic confidence score; high-confidence ones promote as active entries, low-confidence (≤ minConfidence) become reviewable drafts. Opt-in: run with dryRun: true first.",
2615
2784
  inputSchema: {
2616
2785
  dryRun: z.boolean().optional().default(true).describe("If true, only preview what would be promoted (no writes)."),
2617
- minConfidence: z.number().optional().default(0.65).describe("Observations at or below this confidence become drafts; above it become active entries."),
2618
- max: z.number().optional().default(5).describe("Maximum observations to promote."),
2619
- days: z.number().optional().default(7).describe("Only consider observations from the last N days."),
2786
+ minConfidence: z.coerce.number().min(0).max(1).optional().default(0.65).describe("Observations at or below this confidence become drafts; above it become active entries."),
2787
+ max: positiveInt(5, 50).describe("Maximum observations to promote."),
2788
+ days: positiveInt(7, 365).describe("Only consider observations from the last N days."),
2620
2789
  },
2621
2790
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
2622
2791
  },
@@ -2746,7 +2915,7 @@ server.registerTool(
2746
2915
 
2747
2916
  // ── memory_visualize (MCP Apps) ──────────────────────────────────────────────
2748
2917
 
2749
- registerAppTool(
2918
+ if (expertMode) registerAppTool(
2750
2919
  server as unknown as Parameters<typeof registerAppTool>[0],
2751
2920
  "memory_visualize",
2752
2921
  {