toon-memory 3.6.0 → 3.7.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
@@ -12,7 +12,7 @@ import { archiveOldEntries } from "./archive"
12
12
  import { consolidateEntries } from "./consolidation"
13
13
  import { readUnderLock } from "../lib/lock"
14
14
  import { encrypt, decrypt } from "./crypto"
15
- import { graphRecallDetailed, renderCompact, parseEntries, buildGraph } from "../lib/graph"
15
+ import { graphRecallDetailed, renderCompact, parseEntries, buildGraph, parseLinkToken, formatLink, typedLinks } from "../lib/graph"
16
16
  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"
@@ -43,6 +43,7 @@ server.registerTool(
43
43
  path_scope: z.string().optional().default("").describe("Glob pattern to scope this entry (e.g. src/**.ts). Empty = global."),
44
44
  origin: z.enum(["human", "agent", "inferred"]).optional().default("agent").describe("Who created this entry."),
45
45
  },
46
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
46
47
  },
47
48
  async ({ category, key, content, file, tags, ttl, links, path_scope, origin }) => {
48
49
  const data = readMemory()
@@ -147,16 +148,19 @@ server.registerTool(
147
148
  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'."),
148
149
  bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
149
150
  path_scope: z.string().optional().default("").describe("Glob pattern to filter entries by path scope (e.g. 'src/**.ts')."),
151
+ 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."),
152
+ 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."),
150
153
  },
154
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
151
155
  },
152
- async ({ query, category, from_date, to_date, mode, hops, compact, bias, budget: budgetParam, path_scope }) => {
156
+ async ({ query, category, from_date, to_date, mode, hops, compact, bias, budget: budgetParam, path_scope, rrf, as_of }) => {
153
157
  const data = readMemory()
154
158
 
155
159
  // Delegate to graphRecallDetailed for both flat and graph modes
156
160
  // This avoids duplicating BM25 + ranking logic
157
161
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
158
162
  const resolvedBudget = budgetParam || (compact ? "normal" : "deep")
159
- const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, sessionFiles, path_scope: path_scope || undefined })
163
+ const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, sessionFiles, path_scope: path_scope || undefined, rrf, asOf: as_of || undefined })
160
164
  if (detail.entries.length === 0) {
161
165
  return { content: [{ type: "text" as const, text: `No results found for "${query}"` }] }
162
166
  }
@@ -177,7 +181,8 @@ server.registerTool(
177
181
  const originInfo = r.origin !== "agent" ? ` | origin: ${r.origin}` : ""
178
182
  const scopeInfo = r.path_scope ? ` | scope: ${r.path_scope}` : ""
179
183
  const statusInfo = r.status !== "active" ? ` | status: ${r.status}` : ""
180
- 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}`
184
+ const supersededInfo = r.supersededOn ? ` | superseded: ${r.supersededOn}` : ""
185
+ 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}`
181
186
  })
182
187
  .join("\n\n")
183
188
  return { content: [{ type: "text" as const, text: formatted }] }
@@ -195,6 +200,7 @@ server.registerTool(
195
200
  key: z.string().describe("Key or id of the entry to delete"),
196
201
  hard: z.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."),
197
202
  },
203
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
198
204
  },
199
205
  async ({ key, hard }) => {
200
206
  const data = readMemory()
@@ -269,6 +275,7 @@ server.registerTool(
269
275
  title: "Memory Stats",
270
276
  description: "Show project memory statistics.",
271
277
  inputSchema: {},
278
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
272
279
  },
273
280
  async () => {
274
281
  const data = readMemory()
@@ -391,6 +398,7 @@ server.registerTool(
391
398
  since: z.string().describe("Show changes since (e.g. 24h, 7d, 2026-07-10)"),
392
399
  type: z.enum(["all", "created", "updated"]).optional().default("all").describe("Filter by change type"),
393
400
  },
401
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
394
402
  },
395
403
  async ({ since, type }) => {
396
404
  const sinceDate = parseRelativeDate(since)
@@ -451,6 +459,7 @@ server.registerTool(
451
459
  context: z.string().describe("Text or context to search for suggestions"),
452
460
  limit: z.number().optional().default(5).describe("Maximum suggestions"),
453
461
  },
462
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
454
463
  },
455
464
  async ({ context, limit }) => {
456
465
  const related = findRelatedEntries(context, "", limit)
@@ -479,13 +488,15 @@ server.registerTool(
479
488
  limit: z.number().optional().default(8).describe("Maximum entries to return"),
480
489
  category: z.string().optional().default("").describe("Filter by category (empty = all)"),
481
490
  bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
491
+ 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."),
482
492
  },
493
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
483
494
  },
484
- async ({ intent, limit, category, bias }) => {
495
+ async ({ intent, limit, category, bias, rrf }) => {
485
496
  const data = readMemory()
486
497
  const mtimes = fileMtimes()
487
498
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
488
- const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles })
499
+ const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles, rrf })
489
500
  return { content: [{ type: "text" as const, text: result }] }
490
501
  }
491
502
  )
@@ -502,6 +513,7 @@ server.registerTool(
502
513
  file: z.string().describe("File path"),
503
514
  summary: z.string().optional().default("").describe("File summary (only for set)"),
504
515
  },
516
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
505
517
  },
506
518
  async ({ action, file, summary }) => {
507
519
  const data = readMemory()
@@ -556,6 +568,7 @@ server.registerTool(
556
568
  title: "Archive Old Entries",
557
569
  description: "Move old entries (>30 days) to archive.toon to keep memory clean.",
558
570
  inputSchema: {},
571
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
559
572
  },
560
573
  async () => {
561
574
  const result = archiveOldEntries()
@@ -581,6 +594,7 @@ server.registerTool(
581
594
  title: "Enable Encryption",
582
595
  description: "Enable AES-256-GCM encryption for memory. Requires TOON_MEMORY_KEY in environment.",
583
596
  inputSchema: {},
597
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
584
598
  },
585
599
  async () => {
586
600
  const config = loadConfig()
@@ -616,6 +630,7 @@ server.registerTool(
616
630
  inputSchema: {
617
631
  key: z.string().describe("Encryption key"),
618
632
  },
633
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
619
634
  },
620
635
  async ({ key }) => {
621
636
  const config = loadConfig()
@@ -658,6 +673,7 @@ server.registerTool(
658
673
  file: z.string().optional().default("").describe("Filter by file"),
659
674
  clear: z.boolean().optional().default(false).describe("If true, clears the capture log"),
660
675
  },
676
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
661
677
  },
662
678
  async ({ limit, tool, file, clear }) => {
663
679
  if (clear) {
@@ -697,6 +713,7 @@ server.registerTool(
697
713
  title: "Consolidate Memory",
698
714
  description: "Consolidate memory by removing entries with identical content (keeps the first). Deterministic, no LLM.",
699
715
  inputSchema: {},
716
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
700
717
  },
701
718
  async () => {
702
719
  const result = consolidateEntries()
@@ -722,6 +739,7 @@ server.registerTool(
722
739
  inputSchema: {
723
740
  conflictsOnly: z.boolean().optional().default(false).describe("If true, only show soft conflicts"),
724
741
  },
742
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
725
743
  },
726
744
  async ({ conflictsOnly }) => {
727
745
  const selfId = resolveSessionId()
@@ -790,6 +808,7 @@ server.registerTool(
790
808
  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."),
791
809
  limit: z.number().optional().default(6).describe("Maximum relevant entries to show"),
792
810
  },
811
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
793
812
  },
794
813
  async ({ task, limit }) => {
795
814
  const data = readMemory()
@@ -808,6 +827,7 @@ server.registerTool(
808
827
  inputSchema: {
809
828
  task: z.string().optional().default("").describe("Agent task. If provided, ranks entries by relevance to this task."),
810
829
  },
830
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
811
831
  },
812
832
  async ({ task }) => {
813
833
  const data = readMemory()
@@ -827,6 +847,7 @@ server.registerTool(
827
847
  inputSchema: {
828
848
  since: z.string().optional().default("").describe("Start date (YYYY-MM-DD or relative like '7d'). Empty = last visible changes."),
829
849
  },
850
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
830
851
  },
831
852
  async ({ since }) => {
832
853
  const data = readMemory()
@@ -847,6 +868,7 @@ server.registerTool(
847
868
  task: z.string().describe("Task or symbol to search context for (e.g. 'fix auth bug', 'authenticate')"),
848
869
  limit: z.number().optional().default(6).describe("Maximum memory entries to include"),
849
870
  },
871
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
850
872
  },
851
873
  async ({ task, limit }) => {
852
874
  const data = readMemory()
@@ -864,6 +886,7 @@ server.registerTool(
864
886
  title: "Memory Health Audit",
865
887
  description: "Full memory health audit: orphan links, duplicates, broken refs, expired TTL, quality, stale sessions. Includes score 0-100. Zero LLM.",
866
888
  inputSchema: {},
889
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
867
890
  },
868
891
  async () => {
869
892
  const data = readMemory()
@@ -883,6 +906,7 @@ server.registerTool(
883
906
  inputSchema: {
884
907
  format: z.enum(["full", "compact"]).optional().default("full").describe("full = detailed with graph, compact = summarized without edges"),
885
908
  },
909
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
886
910
  },
887
911
  async ({ format }) => {
888
912
  const data = readMemory()
@@ -899,6 +923,7 @@ server.registerTool(
899
923
  title: "Backup Memory",
900
924
  description: "Create a timestamped backup of the memory file. Use before major operations or to preserve state.",
901
925
  inputSchema: {},
926
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
902
927
  },
903
928
  async () => {
904
929
  if (!existsSync(MEMORY_FILE)) {
@@ -952,6 +977,7 @@ server.registerTool(
952
977
  title: "System Primer",
953
978
  description: "Generate a compact system primer: always-current knowledge map for auto-injection into agent context. Excludes private entries, shows top memories by importance, categories, and patterns. Use at session start or when context feels stale.",
954
979
  inputSchema: {},
980
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
955
981
  },
956
982
  async () => {
957
983
  const data = readMemory()
@@ -973,6 +999,7 @@ server.registerTool(
973
999
  count: z.number().optional().default(3).describe("Number of entries to compress (2-10). Default: 3."),
974
1000
  category: z.string().optional().default("").describe("Filter by category (empty = all)."),
975
1001
  },
1002
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
976
1003
  },
977
1004
  async ({ query, count, category }) => {
978
1005
  const data = readMemory()
@@ -1058,6 +1085,7 @@ server.registerTool(
1058
1085
  minQuality: z.number().optional().default(0.3).describe("Entries below this quality score are compression candidates (0-1). Default: 0.3."),
1059
1086
  dryRun: z.boolean().optional().default(false).describe("If true, show what would be compressed without making changes."),
1060
1087
  },
1088
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
1061
1089
  },
1062
1090
  async ({ minQuality, dryRun }) => {
1063
1091
  const data = readMemory()
@@ -1158,6 +1186,7 @@ server.registerTool(
1158
1186
  inputSchema: {
1159
1187
  description: z.string().optional().default("").describe("Optional description for the Gist."),
1160
1188
  },
1189
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
1161
1190
  },
1162
1191
  async ({ description }) => {
1163
1192
  const token = process.env.GITHUB_TOKEN
@@ -1223,6 +1252,7 @@ server.registerTool(
1223
1252
  gist_id: z.string().describe("GitHub Gist ID or full URL (https://gist.github.com/user/id)."),
1224
1253
  merge: z.boolean().optional().default(true).describe("If true, merge with existing memory. If false, replace entirely."),
1225
1254
  },
1255
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
1226
1256
  },
1227
1257
  async ({ gist_id, merge }) => {
1228
1258
  const token = process.env.GITHUB_TOKEN
@@ -1341,6 +1371,7 @@ server.registerTool(
1341
1371
  since: z.string().optional().default("24h").describe("Time window to merge (e.g. '24h', '7d', '2026-07-20'). Default: 24h."),
1342
1372
  promote: z.boolean().optional().default(false).describe("If true, auto-promote unique observations to memory entries."),
1343
1373
  },
1374
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
1344
1375
  },
1345
1376
  async ({ since, promote }) => {
1346
1377
  const { listSessions, pruneSessions } = await import("../lib/sessions")
@@ -1483,6 +1514,7 @@ server.registerTool(
1483
1514
  inputSchema: {
1484
1515
  dryRun: z.boolean().optional().default(false).describe("If true, show what would be merged without making changes."),
1485
1516
  },
1517
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
1486
1518
  },
1487
1519
  async ({ dryRun }) => {
1488
1520
  const data = readMemory()
@@ -1606,6 +1638,7 @@ server.registerTool(
1606
1638
  from: z.string().describe("Starting entry key"),
1607
1639
  to: z.string().describe("Target entry key"),
1608
1640
  },
1641
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
1609
1642
  },
1610
1643
  async ({ from, to }) => {
1611
1644
  const data = readMemory()
@@ -1680,6 +1713,7 @@ server.registerTool(
1680
1713
  inputSchema: {
1681
1714
  note: z.string().optional().default("").describe("Optional summary of what was accomplished in this session."),
1682
1715
  },
1716
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
1683
1717
  },
1684
1718
  async ({ note }) => {
1685
1719
  const data = readMemory()
@@ -1769,6 +1803,7 @@ server.registerTool(
1769
1803
  key: z.string().describe("Key or id of the entry to pin"),
1770
1804
  priority: z.number().optional().default(1).describe("Priority level 1-5 (5 = highest). Default: 1."),
1771
1805
  },
1806
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
1772
1807
  },
1773
1808
  async ({ key, priority }) => {
1774
1809
  const data = readMemory()
@@ -1815,6 +1850,7 @@ server.registerTool(
1815
1850
  inputSchema: {
1816
1851
  key: z.string().describe("Key or id of the entry to unpin"),
1817
1852
  },
1853
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
1818
1854
  },
1819
1855
  async ({ key }) => {
1820
1856
  const data = readMemory()
@@ -1870,9 +1906,12 @@ server.registerTool(
1870
1906
  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'."),
1871
1907
  bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
1872
1908
  path_scope: z.string().optional().default("").describe("Glob pattern to filter entries by path scope (e.g. 'src/**.ts')."),
1909
+ 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."),
1910
+ as_of: z.string().optional().default("").describe("Temporal view (YYYY-MM-DD): return entries valid on that date."),
1873
1911
  },
1912
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
1874
1913
  },
1875
- async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact, bias, budget: budgetParam, path_scope }) => {
1914
+ async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact, bias, budget: budgetParam, path_scope, rrf, as_of }) => {
1876
1915
  const data = readMemory()
1877
1916
 
1878
1917
  const resolvedFrom = from_date ? parseRelativeDate(from_date) : ""
@@ -1887,6 +1926,8 @@ server.registerTool(
1887
1926
  limit,
1888
1927
  sessionFiles,
1889
1928
  path_scope: path_scope || undefined,
1929
+ rrf,
1930
+ asOf: as_of || undefined,
1890
1931
  })
1891
1932
 
1892
1933
  if (detail.entries.length === 0) {
@@ -1912,7 +1953,8 @@ server.registerTool(
1912
1953
  const originInfo = r.origin !== "agent" ? ` | origin: ${r.origin}` : ""
1913
1954
  const scopeInfo = r.path_scope ? ` | scope: ${r.path_scope}` : ""
1914
1955
  const statusInfo = r.status !== "active" ? ` | status: ${r.status}` : ""
1915
- 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}`
1956
+ const supersededInfo = r.supersededOn ? ` | superseded: ${r.supersededOn}` : ""
1957
+ 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}`
1916
1958
  })
1917
1959
  .join("\n\n")
1918
1960
 
@@ -1940,6 +1982,7 @@ server.registerTool(
1940
1982
  tags: z.string().describe("Semicolon-separated tags to apply"),
1941
1983
  ids: z.string().describe("Comma or space-separated entry keys or IDs to modify"),
1942
1984
  },
1985
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
1943
1986
  },
1944
1987
  async ({ action, tags, ids }) => {
1945
1988
  const data = readMemory()
@@ -2014,6 +2057,7 @@ server.registerTool(
2014
2057
  inputSchema: {
2015
2058
  key: z.string().describe("Key or id of the entry to resolve/restore"),
2016
2059
  },
2060
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
2017
2061
  },
2018
2062
  async ({ key }) => {
2019
2063
  const data = readMemory()
@@ -2062,6 +2106,7 @@ server.registerTool(
2062
2106
  inputSchema: {
2063
2107
  key: z.string().describe("Key or id of the entry to suppress"),
2064
2108
  },
2109
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
2065
2110
  },
2066
2111
  async ({ key }) => {
2067
2112
  const data = readMemory()
@@ -2096,6 +2141,410 @@ server.registerTool(
2096
2141
  }
2097
2142
  )
2098
2143
 
2144
+ // ── memory_supersede ─────────────────────────────────────────────────────────
2145
+
2146
+ server.registerTool(
2147
+ "memory_supersede",
2148
+ {
2149
+ title: "Supersede Entry",
2150
+ description: "Mark an entry as superseded (obsolete) by a newer entry, using typed graph edges (superseded_by / supersedes). The old entry stays in the file for history but is hidden from normal recalls. Use memory_recall(as_of: date) to see what was true at a point in time.",
2151
+ inputSchema: {
2152
+ old_key: z.string().describe("Key or id of the entry being superseded"),
2153
+ new_key: z.string().optional().default("").describe("Key or id of the replacement entry (can be empty if the topic is simply retired)."),
2154
+ reason: z.string().optional().default("").describe("Optional note explaining why it was superseded. Appended to the old entry's content."),
2155
+ },
2156
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
2157
+ },
2158
+ async ({ old_key, new_key, reason }) => {
2159
+ const data = readMemory()
2160
+ const lines = data.split("\n")
2161
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
2162
+ if (headerIdx === -1) {
2163
+ return { content: [{ type: "text" as const, text: "No entries in memory" }] }
2164
+ }
2165
+
2166
+ const today = new Date().toISOString().split("T")[0]
2167
+
2168
+ let oldIdx = -1
2169
+ for (let i = headerIdx + 1; i < lines.length; i++) {
2170
+ const line = lines[i]
2171
+ if (!line.startsWith(" ") || !line.includes("|")) continue
2172
+ if (line.startsWith(" summaries:")) break
2173
+ const parts = line.trim().split("|")
2174
+ if (parts[0] === old_key || parts[2] === old_key) {
2175
+ oldIdx = i
2176
+ break
2177
+ }
2178
+ }
2179
+
2180
+ if (oldIdx === -1) {
2181
+ return { content: [{ type: "text" as const, text: `❌ "${old_key}" not found in memory.` }] }
2182
+ }
2183
+
2184
+ let newIdx = -1
2185
+ let newKey = ""
2186
+ if (new_key) {
2187
+ for (let i = headerIdx + 1; i < lines.length; i++) {
2188
+ const line = lines[i]
2189
+ if (!line.startsWith(" ") || !line.includes("|")) continue
2190
+ if (line.startsWith(" summaries:")) break
2191
+ const parts = line.trim().split("|")
2192
+ if (parts[0] === new_key || parts[2] === new_key) {
2193
+ newIdx = i
2194
+ newKey = parts[2]
2195
+ break
2196
+ }
2197
+ }
2198
+ if (newIdx === -1) {
2199
+ return { content: [{ type: "text" as const, text: `❌ Replacement "${new_key}" not found in memory.` }] }
2200
+ }
2201
+ }
2202
+
2203
+ const oldParts = lines[oldIdx].trim().split("|")
2204
+ const oldKey = oldParts[2]
2205
+
2206
+ // Tag the old entry as superseded.
2207
+ const tags = (oldParts[5] || "").split(";").map((t) => t.trim()).filter(Boolean)
2208
+ if (!tags.includes("superseded")) tags.push("superseded")
2209
+
2210
+ // Add the typed link old --superseded_by--> new.
2211
+ const links = (oldParts[9] || "").split(/[\s;]+/).filter(Boolean)
2212
+ if (newKey) {
2213
+ const edge = formatLink("superseded_by", newKey)
2214
+ if (!links.includes(edge)) links.push(edge)
2215
+ }
2216
+
2217
+ // Append the reason to the content (kept in history). Records are single-line, so
2218
+ // newlines in the reason would corrupt the | delimited format — flatten them.
2219
+ let content = oldParts[3] || ""
2220
+ if (reason && !content.includes(reason)) {
2221
+ const flat = reason.replace(/[\r\n]+/g, " ").trim()
2222
+ content = `${content} ⏳ Superseded (${today}): ${flat}`
2223
+ }
2224
+
2225
+ while (oldParts.length < 18) oldParts.push("")
2226
+ oldParts[3] = content
2227
+ oldParts[5] = tags.join(";")
2228
+ oldParts[9] = links.join(" ")
2229
+ oldParts[16] = "obsolete"
2230
+ oldParts[17] = today
2231
+ lines[oldIdx] = ` ${oldParts.join("|")}`
2232
+
2233
+ // Mirror link on the replacement: new --supersedes--> old.
2234
+ if (newIdx !== -1) {
2235
+ const newParts = lines[newIdx].trim().split("|")
2236
+ const newLinks = (newParts[9] || "").split(/[\s;]+/).filter(Boolean)
2237
+ const edge = formatLink("supersedes", oldKey)
2238
+ if (!newLinks.includes(edge)) {
2239
+ newLinks.push(edge)
2240
+ newParts[9] = newLinks.join(" ")
2241
+ lines[newIdx] = ` ${newParts.join("|")}`
2242
+ }
2243
+ }
2244
+
2245
+ writeMemory(lines.join("\n"))
2246
+
2247
+ const target = newKey ? ` by "${newKey}"` : " (retired)"
2248
+ return {
2249
+ content: [{
2250
+ type: "text" as const,
2251
+ text: `⏳ "${oldKey}" superseded${target} on ${today}.\n\nOld entry is now status=obsolete (hidden from normal recalls).\n · link: superseded_by${newKey ? `:${newKey}` : ""}\n · tag: superseded\n\nTo see what was true before: memory_recall(query: "${oldKey}", as_of: "${today}")\nTo restore: memory_resolve(key: "${oldKey}")${reason ? `\n\nReason: ${reason}` : ""}`,
2252
+ }],
2253
+ }
2254
+ }
2255
+ )
2256
+
2257
+ // ── memory_reflect ───────────────────────────────────────────────────────────
2258
+
2259
+ server.registerTool(
2260
+ "memory_reflect",
2261
+ {
2262
+ title: "Reflect on Memory",
2263
+ 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.",
2264
+ inputSchema: {
2265
+ category: z.string().optional().default("").describe("Restrict analysis to one category (empty = all)."),
2266
+ limit: z.number().optional().default(5).describe("Max items per section."),
2267
+ },
2268
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
2269
+ },
2270
+ async ({ category, limit }) => {
2271
+ const data = readMemory()
2272
+ const entries = parseEntries(data)
2273
+ const cap = Math.max(1, Math.min(20, limit || 5))
2274
+ if (entries.length === 0) {
2275
+ return { content: [{ type: "text" as const, text: "Empty memory." }] }
2276
+ }
2277
+
2278
+ const scope = entries.filter((e) => !category || e.category === category)
2279
+ const { adjacency } = buildGraph(entries)
2280
+
2281
+ const sections: string[] = [`🧠 Memory reflect (${scope.length}/${entries.length} entries)`]
2282
+
2283
+ // 1. Hubs and orphans
2284
+ const degree = new Map<string, number>()
2285
+ for (const [k, nbs] of adjacency) degree.set(k, nbs.length)
2286
+ const hubs = [...degree.entries()].sort((a, b) => b[1] - a[1]).filter(([, d]) => d >= 3)
2287
+ if (hubs.length > 0) {
2288
+ sections.push("", "🔗 Hubs (connectors):")
2289
+ for (const [k, d] of hubs.slice(0, cap)) {
2290
+ const e = entries.find((x) => x.key === k)
2291
+ sections.push(` ${k} (deg ${d}) — ${e ? e.content.slice(0, 70) : ""}`)
2292
+ }
2293
+ }
2294
+ const orphans = scope.filter((e) => e.status === "active" && !(degree.get(e.key) || 0) && e.tags.length === 0)
2295
+ if (orphans.length > 0) {
2296
+ sections.push("", "🕳️ Orphans (no links, no tags — consider linking):")
2297
+ for (const e of orphans.slice(0, cap)) {
2298
+ sections.push(` [${e.category}] ${e.key} — ${e.content.slice(0, 70)}`)
2299
+ }
2300
+ }
2301
+
2302
+ // 2. Tag co-occurrence themes
2303
+ const pairCount = new Map<string, number>()
2304
+ for (const e of scope) {
2305
+ if (e.tags.length < 2) continue
2306
+ const t = [...e.tags].sort()
2307
+ for (let i = 0; i < t.length; i++) {
2308
+ for (let j = i + 1; j < t.length; j++) {
2309
+ const pair = `${t[i]} + ${t[j]}`
2310
+ pairCount.set(pair, (pairCount.get(pair) || 0) + 1)
2311
+ }
2312
+ }
2313
+ }
2314
+ const themes = [...pairCount.entries()].sort((a, b) => b[1] - a[1])
2315
+ if (themes.length > 0) {
2316
+ sections.push("", "🏷️ Latent themes (tag co-occurrence):")
2317
+ for (const [pair, n] of themes.slice(0, cap)) {
2318
+ sections.push(` ${pair} — ${n} entries`)
2319
+ }
2320
+ }
2321
+
2322
+ // 3. Near-duplicates (Jaccard word overlap > 0.5)
2323
+ const active = scope.filter((e) => e.status === "active")
2324
+ const wordSets = new Map<string, Set<string>>()
2325
+ for (const e of active) {
2326
+ wordSets.set(e.key, new Set(normalize(`${e.key} ${e.content} ${e.tags.join(" ")}`).split(" ").filter(Boolean)))
2327
+ }
2328
+ const dupes: Array<{ a: string; b: string; sim: number }> = []
2329
+ const keysArr = active.map((e) => e.key)
2330
+ for (let i = 0; i < keysArr.length; i++) {
2331
+ for (let j = i + 1; j < keysArr.length; j++) {
2332
+ const wa = wordSets.get(keysArr[i])!
2333
+ const wb = wordSets.get(keysArr[j])!
2334
+ const inter = new Set([...wa].filter((w) => wb.has(w)))
2335
+ const union = new Set([...wa, ...wb])
2336
+ const sim = union.size > 0 ? inter.size / union.size : 0
2337
+ if (sim > 0.5) dupes.push({ a: keysArr[i], b: keysArr[j], sim })
2338
+ }
2339
+ }
2340
+ if (dupes.length > 0) {
2341
+ sections.push("", "♻️ Near-duplicates (merge candidates):")
2342
+ for (const d of dupes.sort((x, y) => y.sim - x.sim).slice(0, cap)) {
2343
+ sections.push(` ${d.a} ↔ ${d.b} (${(d.sim * 100).toFixed(0)}% overlap)`)
2344
+ }
2345
+ }
2346
+
2347
+ // 4. Contradiction candidates: same category, ≥2 shared tags, split polarity markers
2348
+ const NEGATION = /\b(no longer|never|not|no|doesn'?t|don'?t|shouldn'?t|cannot|can'?t|instead of|contradicts|replaces|deprecated|broken|fails|wrong|incorrect)\b/i
2349
+ const contradictions: string[] = []
2350
+ for (let i = 0; i < active.length; i++) {
2351
+ for (let j = i + 1; j < active.length; j++) {
2352
+ const a = active[i], b = active[j]
2353
+ if (a.category !== b.category) continue
2354
+ const shared = a.tags.filter((t) => b.tags.includes(t)).length
2355
+ if (shared < 2) continue
2356
+ const aNeg = NEGATION.test(a.content)
2357
+ const bNeg = NEGATION.test(b.content)
2358
+ if (aNeg !== bNeg) {
2359
+ contradictions.push(`${a.key} ↔ ${b.key} [${a.category}] (${shared} shared tags, split polarity)`)
2360
+ }
2361
+ }
2362
+ }
2363
+ if (contradictions.length > 0) {
2364
+ sections.push("", "⚡ Contradiction candidates (verify):")
2365
+ for (const c of contradictions.slice(0, cap)) {
2366
+ sections.push(` ${c}`)
2367
+ }
2368
+ }
2369
+
2370
+ // 5. Stale / archive candidates
2371
+ const now = Date.now()
2372
+ const stale = active.filter((e) => {
2373
+ if (e.tags.includes("private")) return false
2374
+ if (e.ttl && isExpiredLocal(e.ttl)) return true
2375
+ if (!e.date) return false
2376
+ const ageDays = (now - new Date(`${e.date}T00:00:00`).getTime()) / 86400000
2377
+ const lastAccessDays = e.lastAccessed ? (now - new Date(e.lastAccessed).getTime()) / 86400000 : ageDays
2378
+ return ageDays > 120 && lastAccessDays > 90 && e.accessed === 0
2379
+ })
2380
+ if (stale.length > 0) {
2381
+ sections.push("", "🗄️ Stale (archive candidates):")
2382
+ for (const e of stale.sort((a, b) => a.date.localeCompare(b.date)).slice(0, cap)) {
2383
+ sections.push(` [${e.category}] ${e.key} — ${e.content.slice(0, 70)}`)
2384
+ }
2385
+ }
2386
+
2387
+ // 6. Superseded-but-active (tag/link present but status not obsolete)
2388
+ const pending = entries.filter((e) => e.status === "active" && (e.tags.includes("superseded") || typedLinks(e.links).some((l) => l.type === "superseded_by")))
2389
+ if (pending.length > 0) {
2390
+ sections.push("", "🔎 Superseded tag but still active (fix with memory_supersede):")
2391
+ for (const e of pending.slice(0, cap)) {
2392
+ sections.push(` [${e.category}] ${e.key}`)
2393
+ }
2394
+ }
2395
+
2396
+ // 7. Drafts pending review
2397
+ const drafts = entries.filter((e) => e.status === "draft")
2398
+ if (drafts.length > 0) {
2399
+ sections.push("", "📝 Drafts pending review (promote with memory_promote / memory_resolve):")
2400
+ for (const e of drafts.slice(0, cap)) {
2401
+ sections.push(` [${e.category}] ${e.key} — ${e.content.slice(0, 70)}`)
2402
+ }
2403
+ }
2404
+
2405
+ return { content: [{ type: "text" as const, text: sections.join("\n") }] }
2406
+ }
2407
+ )
2408
+
2409
+ // ── memory_promote ───────────────────────────────────────────────────────────
2410
+
2411
+ server.registerTool(
2412
+ "memory_promote",
2413
+ {
2414
+ title: "Promote Observations",
2415
+ 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.",
2416
+ inputSchema: {
2417
+ dryRun: z.boolean().optional().default(true).describe("If true, only preview what would be promoted (no writes)."),
2418
+ minConfidence: z.number().optional().default(0.65).describe("Observations at or below this confidence become drafts; above it become active entries."),
2419
+ max: z.number().optional().default(5).describe("Maximum observations to promote."),
2420
+ days: z.number().optional().default(7).describe("Only consider observations from the last N days."),
2421
+ },
2422
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
2423
+ },
2424
+ async ({ dryRun, minConfidence, max, days }) => {
2425
+ const obs = readObservations()
2426
+ if (obs.length === 0) {
2427
+ return { content: [{ type: "text" as const, text: "No captured activity. Enable with `toon-memory capture on`." }] }
2428
+ }
2429
+
2430
+ const cutoff = Date.now() - (days || 7) * 86400000
2431
+ const recent = obs.filter((o) => new Date(o.ts).getTime() >= cutoff)
2432
+
2433
+ const data = readMemory()
2434
+ const existing = parseEntries(data)
2435
+ const existingKeys = new Set(existing.map((e) => e.key))
2436
+ const existingWords = existing.map((e) => new Set(normalize(`${e.key} ${e.content} ${e.tags.join(" ")}`).split(" ").filter(Boolean)))
2437
+
2438
+ // Deterministic confidence heuristic (0..1).
2439
+ const confidence = (o: { tool: string; file: string; summary: string }): number => {
2440
+ const summary = (o.summary || "").trim()
2441
+ if (!summary) return 0.1
2442
+ let c = 0.5
2443
+ const len = summary.length
2444
+ if (len >= 40 && len <= 300) c += 0.1
2445
+ else if (len < 40) c -= 0.1
2446
+ if (o.file) c += 0.15
2447
+ const tool = (o.tool || "").toLowerCase()
2448
+ if (["edit", "write", "create", "bash", "git", "npm"].includes(tool)) c += 0.1
2449
+ else if (["read", "grep", "glob", "search", "ls", "list"].includes(tool)) c -= 0.15
2450
+ if (/\b(error|fail|bug|fix|broken|fails|failed|cannot|crash)\b/i.test(summary)) c += 0.1
2451
+ if (/\b(viewed|read|opened|inspected|browsed|listed|scanned)\b/i.test(summary)) c -= 0.1
2452
+ return Math.max(0.05, Math.min(1, c))
2453
+ }
2454
+
2455
+ const alreadyKnown = (o: { tool: string; summary: string }): boolean => {
2456
+ const words = new Set(normalize(`${o.tool} ${o.summary}`).split(" ").filter(Boolean))
2457
+ if (words.size === 0) return true
2458
+ for (const set of existingWords) {
2459
+ const inter = new Set([...words].filter((w) => set.has(w)))
2460
+ const union = new Set([...words, ...set])
2461
+ if (inter.size / union.size > 0.5) return true
2462
+ }
2463
+ return false
2464
+ }
2465
+
2466
+ const seen = new Set<string>()
2467
+ const candidates = recent
2468
+ .filter((o) => {
2469
+ const dedupKey = `${o.tool}|${o.summary}`
2470
+ if (seen.has(dedupKey)) return false
2471
+ seen.add(dedupKey)
2472
+ return o.summary && !alreadyKnown(o)
2473
+ })
2474
+ .map((o) => ({ o, conf: confidence(o) }))
2475
+ .sort((a, b) => b.conf - a.conf)
2476
+ .slice(0, max || 5)
2477
+
2478
+ if (candidates.length === 0) {
2479
+ return { content: [{ type: "text" as const, text: "✅ Nothing new to promote — all recent observations are already covered by memory or below threshold." }] }
2480
+ }
2481
+
2482
+ const preview = candidates.map(({ o, conf }) => {
2483
+ const kind = conf <= minConfidence ? "draft" : "active"
2484
+ return ` [${kind}] ${(o.summary || "").slice(0, 90)} (conf ${conf.toFixed(2)})${o.file ? ` @ ${o.file}` : ""}`
2485
+ })
2486
+ const kindLabel = (conf: number) => (conf <= minConfidence ? "draft" : "active")
2487
+
2488
+ if (dryRun) {
2489
+ return {
2490
+ content: [{
2491
+ type: "text" as const,
2492
+ text: `🔍 Dry run — ${candidates.length} candidate(s) from the last ${days || 7}d (threshold ${minConfidence}):\n\n${preview.join("\n")}\n\nRun with dryRun: false to promote.`
2493
+ }],
2494
+ }
2495
+ }
2496
+
2497
+ const date = new Date().toISOString().split("T")[0]
2498
+ const lines = data.split("\n")
2499
+ let headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
2500
+ if (headerIdx === -1) {
2501
+ lines.push(`[0|]`)
2502
+ headerIdx = lines.length - 1
2503
+ }
2504
+ const match = lines[headerIdx].match(/\[(\d+)\|/)
2505
+ let count = match ? parseInt(match[1]) : 0
2506
+
2507
+ let promoted = 0
2508
+ let drafted = 0
2509
+ const actions: string[] = []
2510
+ for (const { o, conf } of candidates) {
2511
+ const key = o.summary
2512
+ .toLowerCase()
2513
+ .replace(/[^a-z0-9\s]/g, "")
2514
+ .split(/\s+/)
2515
+ .filter(Boolean)
2516
+ .slice(0, 4)
2517
+ .join("-")
2518
+ .slice(0, 40) || `observation-${Date.now().toString(36)}`
2519
+ if (existingKeys.has(key)) continue
2520
+
2521
+ const newId = generateId()
2522
+ const status = kindLabel(conf)
2523
+ const tags = ["captured", `${o.agent || "agent"}`]
2524
+ if (status === "draft") tags.push("draft")
2525
+ const content = (o.summary || "").slice(0, 500)
2526
+ const quality = qualityScore(tags.join(";"), "", content, date)
2527
+ const entry = `${newId}|knowledge|${key}|${content}|${o.file || ""}|${tags.join(";")}|${date}||0||${quality.toFixed(2)}|${conf.toFixed(2)}|${date}|0||inferred|${status}`
2528
+
2529
+ lines.splice(headerIdx + 1, 0, ` ${entry}`)
2530
+ count++
2531
+ existingKeys.add(key)
2532
+ if (status === "draft") drafted++
2533
+ else promoted++
2534
+ actions.push(` [${status}] ${key} (conf ${conf.toFixed(2)})`)
2535
+ }
2536
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count}|`)
2537
+ writeMemory(lines.join("\n"))
2538
+
2539
+ return {
2540
+ content: [{
2541
+ type: "text" as const,
2542
+ text: `📤 Promoted ${promoted} active + ${drafted} draft from the capture log.\n\n${actions.join("\n")}\n\nDrafts are hidden from recalls until promoted — use memory_resolve(key) to activate, or review with memory_reflect.`
2543
+ }],
2544
+ }
2545
+ }
2546
+ )
2547
+
2099
2548
  // ── memory_visualize (MCP Apps) ──────────────────────────────────────────────
2100
2549
 
2101
2550
  registerAppTool(
@@ -2107,6 +2556,7 @@ registerAppTool(
2107
2556
  inputSchema: {
2108
2557
  query: z.string().optional().default("").describe("Optional search query to highlight entries in the viewer"),
2109
2558
  },
2559
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
2110
2560
  _meta: { ui: { resourceUri: "ui://viewer" } },
2111
2561
  },
2112
2562
  async ({ query }) => {