toon-memory 3.6.1 → 4.1.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,12 +12,12 @@ 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"
19
19
  import { fileMtimes } from "../lib/git"
20
- import { normalize, isExpiredLocal, tokenize, importance } from "../lib/utils"
20
+ import { normalize, isExpiredLocal, tokenize, importance, parseToonLine, toToonLine, escField, unescField } from "../lib/utils"
21
21
  import { expandSynonyms } from "../lib/synonyms"
22
22
 
23
23
  /**
@@ -25,6 +25,409 @@ import { expandSynonyms } from "../lib/synonyms"
25
25
  */
26
26
  export function registerTools(server: McpServer): void {
27
27
 
28
+ type ToolText = { type: "text"; text: string }
29
+
30
+ // ── Shared lifecycle helpers (backing canonical memory_forget) ──
31
+
32
+ function softDelete(key: string): { content: ToolText[] } {
33
+ const data = readMemory()
34
+ const lines = data.split("\n")
35
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
36
+
37
+ if (headerIdx === -1) {
38
+ return { content: [{ type: "text", text: "No entries in memory" }] }
39
+ }
40
+
41
+ let found = false
42
+ for (let i = headerIdx + 1; i < lines.length; i++) {
43
+ const line = lines[i]
44
+ if (!line.startsWith(" ") || !line.includes("|")) continue
45
+ if (line.startsWith(" summaries:")) break
46
+ const parts = parseToonLine(line)
47
+ if (parts[0] === key || parts[2] === key) {
48
+ while (parts.length < 17) parts.push("")
49
+ parts[16] = "obsolete"
50
+ lines[i] = toToonLine(parts)
51
+ found = true
52
+ break
53
+ }
54
+ }
55
+
56
+ writeMemory(lines.join("\n"))
57
+
58
+ if (!found) {
59
+ return { content: [{ type: "text", text: `"${key}" not found in memory.` }] }
60
+ }
61
+
62
+ return { content: [{ type: "text", text: `"${key}" marked as obsolete. Use memory_forget(key, action: 'restore') to restore.` }] }
63
+ }
64
+
65
+ function hardDelete(key: string): { content: ToolText[] } {
66
+ const data = readMemory()
67
+ const lines = data.split("\n")
68
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
69
+
70
+ if (headerIdx === -1) {
71
+ return { content: [{ type: "text", text: "No entries in memory" }] }
72
+ }
73
+
74
+ const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
75
+ const filtered = entryLines.filter((l) => {
76
+ const parts = parseToonLine(l)
77
+ return parts[0] !== key && parts[2] !== key
78
+ })
79
+
80
+ const removed = entryLines.length - filtered.length
81
+ const match = lines[headerIdx].match(/\[(\d+)\|/)
82
+ const count = match ? parseInt(match[1]) : 0
83
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`)
84
+ lines.splice(headerIdx + 1, entryLines.length, ...filtered.map((l) => ` ${l.trim()}`))
85
+
86
+ writeMemory(lines.join("\n"))
87
+
88
+ if (removed === 0) {
89
+ return { content: [{ type: "text", text: `"${key}" not found in memory.` }] }
90
+ }
91
+
92
+ return { content: [{ type: "text", text: `"${key}" permanently deleted. ${count - removed} entries remaining.` }] }
93
+ }
94
+
95
+ function restoreEntry(key: string): { content: ToolText[] } {
96
+ const data = readMemory()
97
+ const lines = data.split("\n")
98
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
99
+
100
+ if (headerIdx === -1) {
101
+ return { content: [{ type: "text", text: "No entries in memory" }] }
102
+ }
103
+
104
+ let found = false
105
+ let wasObsolete = false
106
+ for (let i = headerIdx + 1; i < lines.length; i++) {
107
+ const line = lines[i]
108
+ if (!line.startsWith(" ") || !line.includes("|")) continue
109
+ if (line.startsWith(" summaries:")) break
110
+ const parts = parseToonLine(line)
111
+ if (parts[0] === key || parts[2] === key) {
112
+ while (parts.length < 17) parts.push("")
113
+ wasObsolete = parts[16] === "obsolete"
114
+ parts[16] = "active"
115
+ lines[i] = toToonLine(parts)
116
+ found = true
117
+ break
118
+ }
119
+ }
120
+
121
+ if (!found) {
122
+ return { content: [{ type: "text", text: `"${key}" not found in memory.` }] }
123
+ }
124
+
125
+ writeMemory(lines.join("\n"))
126
+
127
+ const msg = wasObsolete ? `"${key}" restored to active status.` : `"${key}" marked as resolved.`
128
+ return { content: [{ type: "text", text: `✅ ${msg}` }] }
129
+ }
130
+
131
+ function supersedeEntry(old_key: string, new_key: string, reason: string): { content: ToolText[] } {
132
+ const data = readMemory()
133
+ const lines = data.split("\n")
134
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
135
+ if (headerIdx === -1) {
136
+ return { content: [{ type: "text", text: "No entries in memory" }] }
137
+ }
138
+
139
+ const today = new Date().toISOString().split("T")[0]
140
+
141
+ let oldIdx = -1
142
+ for (let i = headerIdx + 1; i < lines.length; i++) {
143
+ const line = lines[i]
144
+ if (!line.startsWith(" ") || !line.includes("|")) continue
145
+ if (line.startsWith(" summaries:")) break
146
+ const parts = parseToonLine(line)
147
+ if (parts[0] === old_key || parts[2] === old_key) {
148
+ oldIdx = i
149
+ break
150
+ }
151
+ }
152
+
153
+ if (oldIdx === -1) {
154
+ return { content: [{ type: "text", text: `❌ "${old_key}" not found in memory.` }] }
155
+ }
156
+
157
+ let newIdx = -1
158
+ let newKey = ""
159
+ if (new_key) {
160
+ for (let i = headerIdx + 1; i < lines.length; i++) {
161
+ const line = lines[i]
162
+ if (!line.startsWith(" ") || !line.includes("|")) continue
163
+ if (line.startsWith(" summaries:")) break
164
+ const parts = parseToonLine(line)
165
+ if (parts[0] === new_key || parts[2] === new_key) {
166
+ newIdx = i
167
+ newKey = parts[2]
168
+ break
169
+ }
170
+ }
171
+ if (newIdx === -1) {
172
+ return { content: [{ type: "text", text: `❌ Replacement "${new_key}" not found in memory.` }] }
173
+ }
174
+ }
175
+
176
+ const oldParts = parseToonLine(lines[oldIdx])
177
+ const oldKey = oldParts[2]
178
+
179
+ const tags = (oldParts[5] || "").split(";").map((t) => t.trim()).filter(Boolean)
180
+ if (!tags.includes("superseded")) tags.push("superseded")
181
+
182
+ const links = (oldParts[9] || "").split(/[\s;]+/).filter(Boolean)
183
+ if (newKey) {
184
+ const edge = formatLink("superseded_by", newKey)
185
+ if (!links.includes(edge)) links.push(edge)
186
+ }
187
+
188
+ let content = oldParts[3] || ""
189
+ if (reason && !content.includes(reason)) {
190
+ const flat = reason.replace(/[\r\n]+/g, " ").trim()
191
+ content = `${content} ⏳ Superseded (${today}): ${flat}`
192
+ }
193
+
194
+ while (oldParts.length < 18) oldParts.push("")
195
+ oldParts[3] = content
196
+ oldParts[5] = tags.join(";")
197
+ oldParts[9] = links.join(" ")
198
+ oldParts[16] = "obsolete"
199
+ oldParts[17] = today
200
+ lines[oldIdx] = toToonLine(oldParts)
201
+
202
+ if (newIdx !== -1) {
203
+ const newParts = parseToonLine(lines[newIdx])
204
+ const newLinks = (newParts[9] || "").split(/[\s;]+/).filter(Boolean)
205
+ const edge = formatLink("supersedes", oldKey)
206
+ if (!newLinks.includes(edge)) {
207
+ newLinks.push(edge)
208
+ newParts[9] = newLinks.join(" ")
209
+ lines[newIdx] = toToonLine(newParts)
210
+ }
211
+ }
212
+
213
+ writeMemory(lines.join("\n"))
214
+
215
+ const target = newKey ? ` by "${newKey}"` : " (retired)"
216
+ return {
217
+ content: [{
218
+ type: "text",
219
+ 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_forget(key: "${oldKey}", action: 'restore')${reason ? `\n\nReason: ${reason}` : ""}`,
220
+ }],
221
+ }
222
+ }
223
+
224
+ // ── Shared cleanup helpers (backing canonical memory_consolidate) ──
225
+
226
+ function runConsolidate(): { content: ToolText[] } {
227
+ const result = consolidateEntries()
228
+ if (result.removed === 0) {
229
+ return { content: [{ type: "text", text: `✅ Memory already consolidated (${result.kept} entries, 0 duplicates)` }] }
230
+ }
231
+ return {
232
+ content: [{
233
+ type: "text",
234
+ text: `🧹 Consolidated ${result.removed} duplicate entries.\n${result.kept} active entries remaining.\nDuplicates: ${result.duplicates.join(", ")}`,
235
+ }],
236
+ }
237
+ }
238
+
239
+ function runMergeSimilar(dryRun: boolean): { content: ToolText[] } {
240
+ const data = readMemory()
241
+ const lines = data.split("\n")
242
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
243
+ if (headerIdx === -1) {
244
+ return { content: [{ type: "text", text: "No entries in memory." }] }
245
+ }
246
+
247
+ const parsed: Array<{ lineIdx: number; id: string; cat: string; key: string; content: string; file: string; tags: string; date: string; ttl: string; accessed: number; words: Set<string>; line: string }> = []
248
+ for (let i = headerIdx + 1; i < lines.length; i++) {
249
+ const line = lines[i]
250
+ if (!line.startsWith(" ") || !line.includes("|")) continue
251
+ if (line.startsWith(" summaries:")) break
252
+ const parts = parseToonLine(line)
253
+ if (parts.length < 7) continue
254
+ const [id, cat, key, content, file, tags, date, ttl, accessedRaw] = parts
255
+ const words = new Set(normalize(`${key} ${content} ${tags}`).split(" ").filter(Boolean))
256
+ parsed.push({ lineIdx: i, id, cat, key, content, file, tags, date, ttl, accessed: parseInt(accessedRaw) || 0, words, line })
257
+ }
258
+
259
+ if (parsed.length < 2) {
260
+ return { content: [{ type: "text", text: "✅ Not enough entries to compress." }] }
261
+ }
262
+
263
+ const mergePairs: Array<{ a: number; b: number; similarity: number }> = []
264
+ for (let i = 0; i < parsed.length; i++) {
265
+ for (let j = i + 1; j < parsed.length; j++) {
266
+ const a = parsed[i], b = parsed[j]
267
+ const intersection = new Set([...a.words].filter((w) => b.words.has(w)))
268
+ const union = new Set([...a.words, ...b.words])
269
+ const similarity = union.size > 0 ? intersection.size / union.size : 0
270
+ if (similarity > 0.5) {
271
+ mergePairs.push({ a: i, b: j, similarity })
272
+ }
273
+ }
274
+ }
275
+
276
+ if (mergePairs.length === 0) {
277
+ return { content: [{ type: "text", text: "✅ No similar entries found to merge." }] }
278
+ }
279
+
280
+ mergePairs.sort((x, y) => y.similarity - x.similarity)
281
+ const merged = new Set<number>()
282
+ const mergeActions: string[] = []
283
+
284
+ for (const pair of mergePairs) {
285
+ if (merged.has(pair.a) || merged.has(pair.b)) continue
286
+ const a = parsed[pair.a], b = parsed[pair.b]
287
+
288
+ const mergedTags = [...new Set([...a.tags.split(";"), ...b.tags.split(";")])].filter(Boolean).join(";")
289
+ const longer = a.content.length >= b.content.length ? a : b
290
+ const shorter = a.content.length < b.content.length ? a : b
291
+ const newContent = longer.content
292
+ const newDate = a.date > b.date ? a.date : b.date
293
+ const newAccessed = a.accessed + b.accessed
294
+
295
+ mergeActions.push(` [${longer.cat}] ${longer.key} ← ${shorter.key} (similarity: ${(pair.similarity * 100).toFixed(0)}%)`)
296
+
297
+ if (!dryRun) {
298
+ const lp = parseToonLine(longer.line)
299
+ const mergedLine = toToonLine([longer.id, longer.cat, longer.key, newContent, longer.file, mergedTags, newDate, longer.ttl, String(newAccessed), lp[9] || "", lp[10] || "", lp[11] || "", lp[12] || ""])
300
+ lines[longer.lineIdx] = mergedLine
301
+ merged.add(pair.b)
302
+ }
303
+ }
304
+
305
+ if (dryRun) {
306
+ const previewLines: string[] = [
307
+ `🔍 Dry run — ${mergePairs.length} merge candidate(s) found:`,
308
+ "",
309
+ ]
310
+ for (const pair of mergePairs) {
311
+ const a = parsed[pair.a], b = parsed[pair.b]
312
+ const mergedTags = [...new Set([...a.tags.split(";"), ...b.tags.split(";")])].filter(Boolean).join(";")
313
+ const longer = a.content.length >= b.content.length ? a : b
314
+ const shorter = a.content.length < b.content.length ? a : b
315
+ previewLines.push(` ── Pair: [${a.cat}] ${a.key} ↔ [${b.cat}] ${b.key}`)
316
+ previewLines.push(` Similarity: ${(pair.similarity * 100).toFixed(0)}%`)
317
+ previewLines.push(` A tags: ${a.tags || "(none)"}`)
318
+ previewLines.push(` B tags: ${b.tags || "(none)"}`)
319
+ previewLines.push(` → Merged tags: ${mergedTags || "(none)"}`)
320
+ previewLines.push(` → Content winner: "${longer.key}" (${longer.content.length} chars vs ${shorter.content.length})`)
321
+ previewLines.push(` → Result content: ${longer.content.slice(0, 120)}${longer.content.length > 120 ? "…" : ""}`)
322
+ previewLines.push("")
323
+ }
324
+ previewLines.push(`Would merge ${merged.size} entries into ${parsed.length - merged.size} entries.`)
325
+ previewLines.push("Run with dryRun: false to apply.")
326
+ return {
327
+ content: [{
328
+ type: "text",
329
+ text: previewLines.join("\n"),
330
+ }],
331
+ }
332
+ }
333
+
334
+ // Rebuild the entries section, preserving version + header lines.
335
+ const kept = parsed.filter((_, i) => !merged.has(i)).map((p) => lines[p.lineIdx])
336
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${kept.length}|`)
337
+ lines.splice(headerIdx + 1, parsed.length, ...kept.map((l) => ` ${l.trim()}`))
338
+ writeMemory(lines.join("\n"))
339
+
340
+ return {
341
+ content: [{
342
+ type: "text",
343
+ text: `✅ Merged ${merged.size} entries into ${parsed.length - merged.size} entries.\n\n${mergeActions.join("\n")}`
344
+ }],
345
+ }
346
+ }
347
+
348
+ function runCompressAll(minQuality: number, dryRun: boolean): { content: ToolText[] } {
349
+ const data = readMemory()
350
+ const lines = data.split("\n")
351
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
352
+ if (headerIdx === -1) {
353
+ return { content: [{ type: "text", text: "No entries in memory." }] }
354
+ }
355
+
356
+ const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
357
+
358
+ const candidates: { idx: number; line: string; quality: number; key: string }[] = []
359
+ for (let i = 0; i < entryLines.length; i++) {
360
+ const line = entryLines[i].trim()
361
+ const parts = parseToonLine(line)
362
+ if (parts.length < 11) continue
363
+ const quality = parseFloat(parts[10]) || 0
364
+ const tags = parts[5] || ""
365
+ const key = parts[2]
366
+ const content = parts[3] || ""
367
+
368
+ const isCandidate = quality < minQuality || !tags || content.length < 20
369
+ if (isCandidate) {
370
+ candidates.push({ idx: i, line, quality, key })
371
+ }
372
+ }
373
+
374
+ if (candidates.length === 0) {
375
+ return {
376
+ content: [{
377
+ type: "text",
378
+ text: `✅ No compression candidates found. All entries have quality >= ${minQuality} or have tags.`
379
+ }],
380
+ }
381
+ }
382
+
383
+ const byCategory = new Map<string, typeof candidates>()
384
+ for (const c of candidates) {
385
+ const parts = parseToonLine(c.line)
386
+ const cat = parts[1] || "unknown"
387
+ if (!byCategory.has(cat)) byCategory.set(cat, [])
388
+ byCategory.get(cat)!.push(c)
389
+ }
390
+
391
+ const sections: string[] = [
392
+ `📦 Compression candidates: ${candidates.length} entries below quality ${minQuality}`,
393
+ "",
394
+ "By category:",
395
+ ]
396
+
397
+ for (const [cat, items] of byCategory) {
398
+ sections.push(` ${cat}: ${items.length} entries`)
399
+ for (const item of items.slice(0, 3)) {
400
+ const parts = parseToonLine(item.line)
401
+ sections.push(` - ${item.key} (Q: ${item.quality.toFixed(2)}) — ${(parts[3] || "").slice(0, 60)}`)
402
+ }
403
+ if (items.length > 3) {
404
+ sections.push(` ... and ${items.length - 3} more`)
405
+ }
406
+ }
407
+
408
+ if (dryRun) {
409
+ sections.push("", "🔍 Dry run — no changes made. Use dryRun: false to compress.")
410
+ return { content: [{ type: "text", text: sections.join("\n") }] }
411
+ }
412
+
413
+ const removeKeys = new Set(candidates.map((c) => c.key))
414
+ const kept = entryLines.filter((l) => {
415
+ const parts = parseToonLine(l)
416
+ return !removeKeys.has(parts[2])
417
+ })
418
+
419
+ const match = lines[headerIdx].match(/\[(\d+)\|/)
420
+ const count = match ? parseInt(match[1]) : 0
421
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${kept.length}|`)
422
+ lines.splice(headerIdx + 1, entryLines.length, ...kept.map((l) => ` ${l.trim()}`))
423
+ writeMemory(lines.join("\n"))
424
+
425
+ sections.push("", `🗑️ Removed ${candidates.length} low-quality entries. ${kept.length} entries remaining.`)
426
+ sections.push("💡 Use memory_compress to merge related entries before removing them.")
427
+
428
+ return { content: [{ type: "text", text: sections.join("\n") }] }
429
+ }
430
+
28
431
  // ── memory_remember ──────────────────────────────────────────────────────────
29
432
 
30
433
  server.registerTool(
@@ -43,6 +446,7 @@ server.registerTool(
43
446
  path_scope: z.string().optional().default("").describe("Glob pattern to scope this entry (e.g. src/**.ts). Empty = global."),
44
447
  origin: z.enum(["human", "agent", "inferred"]).optional().default("agent").describe("Who created this entry."),
45
448
  },
449
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
46
450
  },
47
451
  async ({ category, key, content, file, tags, ttl, links, path_scope, origin }) => {
48
452
  const data = readMemory()
@@ -62,7 +466,7 @@ server.registerTool(
62
466
  const line = lines[i]
63
467
  if (!line.startsWith(" ") || !line.includes("|")) continue
64
468
  if (line.startsWith(" summaries:")) break
65
- const parts = line.trim().split("|")
469
+ const parts = parseToonLine(line)
66
470
  if (parts[2] === key) {
67
471
  existingIdx = i
68
472
  existingId = parts[0]
@@ -75,18 +479,18 @@ server.registerTool(
75
479
  const config = loadConfig()
76
480
  const verbatim = config.verbatim === true
77
481
  const resolvedTags = tags ? tags : (verbatim ? "" : inferTags(content, key, config.vocab))
78
- const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : []
482
+ const existingParts = existingIdx !== -1 ? parseToonLine(lines[existingIdx]) : []
79
483
  const resolvedLinks = links
80
484
  ? links.split(/[\s;]+/).filter(Boolean).join(" ")
81
485
  : existingParts[9] || ""
82
- let newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|0|${resolvedLinks}|||||${path_scope || ""}|${origin}`
486
+ let newEntry = toToonLine([entryId, category, key, content, file || "", resolvedTags, date, resolvedTtl, "0", resolvedLinks, "", "", "", path_scope || "", origin])
83
487
  let action = "Saved"
84
488
  let mergeInfo = ""
85
489
  const tagsInferred = !tags && resolvedTags ? true : false
86
490
 
87
491
  if (existingIdx !== -1) {
88
492
  newEntry = mergeEntries(lines[existingIdx].trim(), newEntry)
89
- lines[existingIdx] = ` ${newEntry}`
493
+ lines[existingIdx] = newEntry
90
494
  action = "Updated"
91
495
  mergeInfo = "\nMerge: tags combined, date and links updated"
92
496
  } else {
@@ -94,10 +498,10 @@ server.registerTool(
94
498
  const lastAccessed = ""
95
499
  const quality = verbatim ? 0.5 : qualityScore(resolvedTags, resolvedLinks, content, date, accessed, lastAccessed, origin)
96
500
  const confidence = 1.0
97
- newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|${accessed}|${resolvedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}|0|${path_scope || ""}|${origin}|active`
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"])
98
502
  const match = lines[headerIdx].match(/\[(\d+)\|/)
99
503
  const count = match ? parseInt(match[1]) : 0
100
- lines.splice(headerIdx + 1, 0, ` ${newEntry}`)
504
+ lines.splice(headerIdx + 1, 0, newEntry)
101
505
  lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`)
102
506
  }
103
507
 
@@ -147,16 +551,19 @@ server.registerTool(
147
551
  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
552
  bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
149
553
  path_scope: z.string().optional().default("").describe("Glob pattern to filter entries by path scope (e.g. 'src/**.ts')."),
554
+ 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."),
555
+ 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
556
  },
557
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
151
558
  },
152
- async ({ query, category, from_date, to_date, mode, hops, compact, bias, budget: budgetParam, path_scope }) => {
559
+ async ({ query, category, from_date, to_date, mode, hops, compact, bias, budget: budgetParam, path_scope, rrf, as_of }) => {
153
560
  const data = readMemory()
154
561
 
155
562
  // Delegate to graphRecallDetailed for both flat and graph modes
156
563
  // This avoids duplicating BM25 + ranking logic
157
564
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
158
565
  const resolvedBudget = budgetParam || (compact ? "normal" : "deep")
159
- const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, sessionFiles, path_scope: path_scope || undefined })
566
+ const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, sessionFiles, path_scope: path_scope || undefined, rrf, asOf: as_of || undefined })
160
567
  if (detail.entries.length === 0) {
161
568
  return { content: [{ type: "text" as const, text: `No results found for "${query}"` }] }
162
569
  }
@@ -177,7 +584,8 @@ server.registerTool(
177
584
  const originInfo = r.origin !== "agent" ? ` | origin: ${r.origin}` : ""
178
585
  const scopeInfo = r.path_scope ? ` | scope: ${r.path_scope}` : ""
179
586
  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}`
587
+ 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}`
181
589
  })
182
590
  .join("\n\n")
183
591
  return { content: [{ type: "text" as const, text: formatted }] }
@@ -189,74 +597,26 @@ server.registerTool(
189
597
  server.registerTool(
190
598
  "memory_forget",
191
599
  {
192
- title: "Delete from Memory",
193
- description: "Delete a memory entry by its key or id.",
600
+ title: "Forget from Memory",
601
+ 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.",
194
602
  inputSchema: {
195
- key: z.string().describe("Key or id of the entry to delete"),
196
- 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."),
603
+ key: z.string().describe("Key or id of the entry"),
604
+ 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."),
605
+ new_key: z.string().optional().default("").describe("Replacement entry key or id (only used with action: supersede)."),
606
+ reason: z.string().optional().default("").describe("Optional note appended to the old entry (only used with action: supersede)."),
197
607
  },
608
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
198
609
  },
199
- async ({ key, hard }) => {
200
- const data = readMemory()
201
- const lines = data.split("\n")
202
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
203
-
204
- if (headerIdx === -1) {
205
- return { content: [{ type: "text" as const, text: "No entries in memory" }] }
206
- }
207
-
208
- if (hard) {
209
- const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
210
- const filtered = entryLines.filter((l) => {
211
- const parts = l.trim().split("|")
212
- return parts[0] !== key && parts[2] !== key
213
- })
214
-
215
- const removed = entryLines.length - filtered.length
216
- const match = lines[headerIdx].match(/\[(\d+)\|/)
217
- const count = match ? parseInt(match[1]) : 0
218
- lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`)
219
- lines.splice(headerIdx + 1, entryLines.length, ...filtered.map((l) => ` ${l.trim()}`))
220
-
221
- writeMemory(lines.join("\n"))
222
-
223
- if (removed === 0) {
224
- return {
225
- content: [{ type: "text" as const, text: `"${key}" not found in memory.` }],
226
- }
227
- }
228
-
229
- return {
230
- content: [{ type: "text" as const, text: `"${key}" permanently deleted. ${count - removed} entries remaining.` }],
231
- }
232
- }
233
-
234
- // Soft-delete: mark status as "obsolete"
235
- let found = false
236
- for (let i = headerIdx + 1; i < lines.length; i++) {
237
- const line = lines[i]
238
- if (!line.startsWith(" ") || !line.includes("|")) continue
239
- if (line.startsWith(" summaries:")) break
240
- const parts = line.trim().split("|")
241
- if (parts[0] === key || parts[2] === key) {
242
- while (parts.length < 17) parts.push("")
243
- parts[16] = "obsolete"
244
- lines[i] = ` ${parts.join("|")}`
245
- found = true
246
- break
247
- }
248
- }
249
-
250
- writeMemory(lines.join("\n"))
251
-
252
- if (!found) {
253
- return {
254
- content: [{ type: "text" as const, text: `"${key}" not found in memory.` }],
255
- }
256
- }
257
-
258
- return {
259
- content: [{ type: "text" as const, text: `"${key}" marked as obsolete. Use memory_resolve(key: "${key}") to restore.` }],
610
+ async ({ key, action, new_key, reason }) => {
611
+ switch (action) {
612
+ case "hard":
613
+ return hardDelete(key)
614
+ case "restore":
615
+ return restoreEntry(key)
616
+ case "supersede":
617
+ return supersedeEntry(key, new_key, reason)
618
+ default:
619
+ return softDelete(key)
260
620
  }
261
621
  }
262
622
  )
@@ -269,12 +629,13 @@ server.registerTool(
269
629
  title: "Memory Stats",
270
630
  description: "Show project memory statistics.",
271
631
  inputSchema: {},
632
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
272
633
  },
273
634
  async () => {
274
635
  const data = readMemory()
275
636
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
276
637
  const entries = lines.map((l) => {
277
- const parts = l.trim().split("|")
638
+ const parts = parseToonLine(l)
278
639
  return { category: parts[1] || "unknown", ttl: parts[7] || "", quality: parts[10] || "", origin: parts.length > 15 ? parts[15] || "" : "", status: parts.length > 16 ? parts[16] || "" : "" }
279
640
  })
280
641
 
@@ -316,7 +677,7 @@ server.registerTool(
316
677
  "",
317
678
  `Last 5 entries:`,
318
679
  ...lines.slice(-5).map((l) => {
319
- const parts = l.trim().split("|")
680
+ const parts = parseToonLine(l)
320
681
  const ttlInfo = parts[7] ? ` | TTL: ${parts[7]}` : ""
321
682
  const qualityInfo = parts[10] ? ` | Q: ${parts[10]}` : ""
322
683
  const accessInfo = parts[8] && parseInt(parts[8]) > 0 ? ` | accessed: ${parts[8]}x` : ""
@@ -329,7 +690,7 @@ server.registerTool(
329
690
  ...lines
330
691
  .filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
331
692
  .map((l) => {
332
- const parts = l.trim().split("|")
693
+ const parts = parseToonLine(l)
333
694
  return { key: parts[2], accessed: parts.length > 8 ? parseInt(parts[8]) || 0 : 0, quality: parts[10] || "" }
334
695
  })
335
696
  .filter((e) => e.accessed > 0)
@@ -342,7 +703,7 @@ server.registerTool(
342
703
  const coldEntries = lines
343
704
  .filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
344
705
  .map((l) => {
345
- const p = l.trim().split("|")
706
+ const p = parseToonLine(l)
346
707
  return {
347
708
  key: p[2],
348
709
  cat: p[1],
@@ -391,6 +752,7 @@ server.registerTool(
391
752
  since: z.string().describe("Show changes since (e.g. 24h, 7d, 2026-07-10)"),
392
753
  type: z.enum(["all", "created", "updated"]).optional().default("all").describe("Filter by change type"),
393
754
  },
755
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
394
756
  },
395
757
  async ({ since, type }) => {
396
758
  const sinceDate = parseRelativeDate(since)
@@ -401,7 +763,7 @@ server.registerTool(
401
763
  const results = lines
402
764
  .map((line) => {
403
765
  const trimmed = line.trim()
404
- const parts = trimmed.split("|")
766
+ const parts = parseToonLine(trimmed)
405
767
  if (parts.length < 7) return null
406
768
  const [id, cat, key, content, file, tags, date] = parts
407
769
  if (date < sinceDate) return null
@@ -451,6 +813,7 @@ server.registerTool(
451
813
  context: z.string().describe("Text or context to search for suggestions"),
452
814
  limit: z.number().optional().default(5).describe("Maximum suggestions"),
453
815
  },
816
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
454
817
  },
455
818
  async ({ context, limit }) => {
456
819
  const related = findRelatedEntries(context, "", limit)
@@ -479,13 +842,15 @@ server.registerTool(
479
842
  limit: z.number().optional().default(8).describe("Maximum entries to return"),
480
843
  category: z.string().optional().default("").describe("Filter by category (empty = all)"),
481
844
  bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
845
+ 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
846
  },
847
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
483
848
  },
484
- async ({ intent, limit, category, bias }) => {
849
+ async ({ intent, limit, category, bias, rrf }) => {
485
850
  const data = readMemory()
486
851
  const mtimes = fileMtimes()
487
852
  const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
488
- const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles })
853
+ const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles, rrf })
489
854
  return { content: [{ type: "text" as const, text: result }] }
490
855
  }
491
856
  )
@@ -502,6 +867,7 @@ server.registerTool(
502
867
  file: z.string().describe("File path"),
503
868
  summary: z.string().optional().default("").describe("File summary (only for set)"),
504
869
  },
870
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
505
871
  },
506
872
  async ({ action, file, summary }) => {
507
873
  const data = readMemory()
@@ -519,7 +885,7 @@ server.registerTool(
519
885
  return { content: [{ type: "text" as const, text: `No summary for "${file}"` }] }
520
886
  }
521
887
 
522
- const summaryText = match.replace(` ${file}: `, "")
888
+ const summaryText = unescField(match.replace(` ${file}: `, ""))
523
889
  return { content: [{ type: "text" as const, text: summaryText }] }
524
890
  }
525
891
 
@@ -535,9 +901,9 @@ server.registerTool(
535
901
  const existingIdx = summaryLines.findIndex((l) => l.startsWith(` ${file}:`))
536
902
 
537
903
  if (existingIdx !== -1) {
538
- summaryLines[existingIdx] = ` ${file}: ${summary}`
904
+ summaryLines[existingIdx] = ` ${file}: ${escField(summary)}`
539
905
  } else {
540
- summaryLines.push(` ${file}: ${summary}`)
906
+ summaryLines.push(` ${file}: ${escField(summary)}`)
541
907
  }
542
908
 
543
909
  lines.splice(summaryIdx + 1, lines.length - summaryIdx - 1, ...summaryLines)
@@ -556,6 +922,7 @@ server.registerTool(
556
922
  title: "Archive Old Entries",
557
923
  description: "Move old entries (>30 days) to archive.toon to keep memory clean.",
558
924
  inputSchema: {},
925
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
559
926
  },
560
927
  async () => {
561
928
  const result = archiveOldEntries()
@@ -581,6 +948,7 @@ server.registerTool(
581
948
  title: "Enable Encryption",
582
949
  description: "Enable AES-256-GCM encryption for memory. Requires TOON_MEMORY_KEY in environment.",
583
950
  inputSchema: {},
951
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
584
952
  },
585
953
  async () => {
586
954
  const config = loadConfig()
@@ -616,6 +984,7 @@ server.registerTool(
616
984
  inputSchema: {
617
985
  key: z.string().describe("Encryption key"),
618
986
  },
987
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
619
988
  },
620
989
  async ({ key }) => {
621
990
  const config = loadConfig()
@@ -658,6 +1027,7 @@ server.registerTool(
658
1027
  file: z.string().optional().default("").describe("Filter by file"),
659
1028
  clear: z.boolean().optional().default(false).describe("If true, clears the capture log"),
660
1029
  },
1030
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
661
1031
  },
662
1032
  async ({ limit, tool, file, clear }) => {
663
1033
  if (clear) {
@@ -695,19 +1065,22 @@ server.registerTool(
695
1065
  "memory_consolidate",
696
1066
  {
697
1067
  title: "Consolidate Memory",
698
- description: "Consolidate memory by removing entries with identical content (keeps the first). Deterministic, no LLM.",
699
- inputSchema: {},
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.",
1069
+ 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."),
1071
+ minQuality: z.number().optional().default(0.3).describe("Entries below this quality score are candidates (only used with mode: low-quality)."),
1072
+ dryRun: z.boolean().optional().default(false).describe("If true, show what would change without writing."),
1073
+ },
1074
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
700
1075
  },
701
- async () => {
702
- const result = consolidateEntries()
703
- if (result.removed === 0) {
704
- return { content: [{ type: "text" as const, text: `✅ Memory already consolidated (${result.kept} entries, 0 duplicates)` }] }
705
- }
706
- return {
707
- content: [{
708
- type: "text" as const,
709
- text: `🧹 Consolidated ${result.removed} duplicate entries.\n${result.kept} active entries remaining.\nDuplicates: ${result.duplicates.join(", ")}`,
710
- }],
1076
+ async ({ mode, minQuality, dryRun }) => {
1077
+ switch (mode) {
1078
+ case "similar":
1079
+ return runMergeSimilar(dryRun)
1080
+ case "low-quality":
1081
+ return runCompressAll(minQuality, dryRun)
1082
+ default:
1083
+ return runConsolidate()
711
1084
  }
712
1085
  }
713
1086
  )
@@ -722,6 +1095,7 @@ server.registerTool(
722
1095
  inputSchema: {
723
1096
  conflictsOnly: z.boolean().optional().default(false).describe("If true, only show soft conflicts"),
724
1097
  },
1098
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
725
1099
  },
726
1100
  async ({ conflictsOnly }) => {
727
1101
  const selfId = resolveSessionId()
@@ -790,6 +1164,7 @@ server.registerTool(
790
1164
  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
1165
  limit: z.number().optional().default(6).describe("Maximum relevant entries to show"),
792
1166
  },
1167
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
793
1168
  },
794
1169
  async ({ task, limit }) => {
795
1170
  const data = readMemory()
@@ -808,6 +1183,7 @@ server.registerTool(
808
1183
  inputSchema: {
809
1184
  task: z.string().optional().default("").describe("Agent task. If provided, ranks entries by relevance to this task."),
810
1185
  },
1186
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
811
1187
  },
812
1188
  async ({ task }) => {
813
1189
  const data = readMemory()
@@ -827,6 +1203,7 @@ server.registerTool(
827
1203
  inputSchema: {
828
1204
  since: z.string().optional().default("").describe("Start date (YYYY-MM-DD or relative like '7d'). Empty = last visible changes."),
829
1205
  },
1206
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
830
1207
  },
831
1208
  async ({ since }) => {
832
1209
  const data = readMemory()
@@ -847,6 +1224,7 @@ server.registerTool(
847
1224
  task: z.string().describe("Task or symbol to search context for (e.g. 'fix auth bug', 'authenticate')"),
848
1225
  limit: z.number().optional().default(6).describe("Maximum memory entries to include"),
849
1226
  },
1227
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
850
1228
  },
851
1229
  async ({ task, limit }) => {
852
1230
  const data = readMemory()
@@ -864,6 +1242,7 @@ server.registerTool(
864
1242
  title: "Memory Health Audit",
865
1243
  description: "Full memory health audit: orphan links, duplicates, broken refs, expired TTL, quality, stale sessions. Includes score 0-100. Zero LLM.",
866
1244
  inputSchema: {},
1245
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
867
1246
  },
868
1247
  async () => {
869
1248
  const data = readMemory()
@@ -883,6 +1262,7 @@ server.registerTool(
883
1262
  inputSchema: {
884
1263
  format: z.enum(["full", "compact"]).optional().default("full").describe("full = detailed with graph, compact = summarized without edges"),
885
1264
  },
1265
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
886
1266
  },
887
1267
  async ({ format }) => {
888
1268
  const data = readMemory()
@@ -899,6 +1279,7 @@ server.registerTool(
899
1279
  title: "Backup Memory",
900
1280
  description: "Create a timestamped backup of the memory file. Use before major operations or to preserve state.",
901
1281
  inputSchema: {},
1282
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
902
1283
  },
903
1284
  async () => {
904
1285
  if (!existsSync(MEMORY_FILE)) {
@@ -952,6 +1333,7 @@ server.registerTool(
952
1333
  title: "System Primer",
953
1334
  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
1335
  inputSchema: {},
1336
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
955
1337
  },
956
1338
  async () => {
957
1339
  const data = readMemory()
@@ -973,6 +1355,7 @@ server.registerTool(
973
1355
  count: z.number().optional().default(3).describe("Number of entries to compress (2-10). Default: 3."),
974
1356
  category: z.string().optional().default("").describe("Filter by category (empty = all)."),
975
1357
  },
1358
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
976
1359
  },
977
1360
  async ({ query, count, category }) => {
978
1361
  const data = readMemory()
@@ -1047,107 +1430,6 @@ server.registerTool(
1047
1430
  }
1048
1431
  )
1049
1432
 
1050
- // ── memory_compress_all ────────────────────────────────────────────────
1051
-
1052
- server.registerTool(
1053
- "memory_compress_all",
1054
- {
1055
- title: "Lazy Batch Compression",
1056
- description: "Compress all low-quality entries (no tags, low quality score) in one pass. Deterministic, no LLM — merges entries with similar content and removes empty/stale ones. Inspired by MemPalace's lazy compression.",
1057
- inputSchema: {
1058
- minQuality: z.number().optional().default(0.3).describe("Entries below this quality score are compression candidates (0-1). Default: 0.3."),
1059
- dryRun: z.boolean().optional().default(false).describe("If true, show what would be compressed without making changes."),
1060
- },
1061
- },
1062
- async ({ minQuality, dryRun }) => {
1063
- const data = readMemory()
1064
- const lines = data.split("\n")
1065
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
1066
- if (headerIdx === -1) {
1067
- return { content: [{ type: "text" as const, text: "No entries in memory." }] }
1068
- }
1069
-
1070
- const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
1071
-
1072
- // Find compression candidates: low quality, no tags, or stale
1073
- const candidates: { idx: number; line: string; quality: number; key: string }[] = []
1074
- for (let i = 0; i < entryLines.length; i++) {
1075
- const line = entryLines[i].trim()
1076
- const parts = line.split("|")
1077
- if (parts.length < 11) continue
1078
- const quality = parseFloat(parts[10]) || 0
1079
- const tags = parts[5] || ""
1080
- const key = parts[2]
1081
- const content = parts[3] || ""
1082
-
1083
- // Candidates: low quality OR no tags OR very short content
1084
- const isCandidate = quality < minQuality || !tags || content.length < 20
1085
- if (isCandidate) {
1086
- candidates.push({ idx: i, line, quality, key })
1087
- }
1088
- }
1089
-
1090
- if (candidates.length === 0) {
1091
- return {
1092
- content: [{
1093
- type: "text" as const,
1094
- text: `✅ No compression candidates found. All entries have quality >= ${minQuality} or have tags.`
1095
- }],
1096
- }
1097
- }
1098
-
1099
- // Group candidates by category for potential merging
1100
- const byCategory = new Map<string, typeof candidates>()
1101
- for (const c of candidates) {
1102
- const parts = c.line.split("|")
1103
- const cat = parts[1] || "unknown"
1104
- if (!byCategory.has(cat)) byCategory.set(cat, [])
1105
- byCategory.get(cat)!.push(c)
1106
- }
1107
-
1108
- const sections: string[] = [
1109
- `📦 Compression candidates: ${candidates.length} entries below quality ${minQuality}`,
1110
- "",
1111
- "By category:",
1112
- ]
1113
-
1114
- for (const [cat, items] of byCategory) {
1115
- sections.push(` ${cat}: ${items.length} entries`)
1116
- for (const item of items.slice(0, 3)) {
1117
- const parts = item.line.split("|")
1118
- sections.push(` - ${item.key} (Q: ${item.quality.toFixed(2)}) — ${(parts[3] || "").slice(0, 60)}`)
1119
- }
1120
- if (items.length > 3) {
1121
- sections.push(` ... and ${items.length - 3} more`)
1122
- }
1123
- }
1124
-
1125
- if (dryRun) {
1126
- sections.push("", "🔍 Dry run — no changes made. Use dryRun: false to compress.")
1127
- return { content: [{ type: "text" as const, text: sections.join("\n") }] }
1128
- }
1129
-
1130
- // Remove candidates (conservative: just remove the lowest quality ones)
1131
- // Don't auto-merge — let the agent decide via memory_compress
1132
- const removeKeys = new Set(candidates.map((c) => c.key))
1133
- const kept = entryLines.filter((l) => {
1134
- const parts = l.trim().split("|")
1135
- return !removeKeys.has(parts[2])
1136
- })
1137
-
1138
- const match = lines[headerIdx].match(/\[(\d+)\|/)
1139
- const count = match ? parseInt(match[1]) : 0
1140
- lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${kept.length}|`)
1141
- lines.splice(headerIdx + 1, entryLines.length, ...kept.map((l) => ` ${l.trim()}`))
1142
- writeMemory(lines.join("\n"))
1143
-
1144
- sections.push("", `🗑️ Removed ${candidates.length} low-quality entries. ${kept.length} entries remaining.`)
1145
- sections.push("💡 Use memory_compress to merge related entries before removing them.")
1146
-
1147
- return { content: [{ type: "text" as const, text: sections.join("\n") }] }
1148
- }
1149
- )
1150
-
1151
1433
  // ── memory_export_gist ─────────────────────────────────────────────────
1152
1434
 
1153
1435
  server.registerTool(
@@ -1158,6 +1440,7 @@ server.registerTool(
1158
1440
  inputSchema: {
1159
1441
  description: z.string().optional().default("").describe("Optional description for the Gist."),
1160
1442
  },
1443
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
1161
1444
  },
1162
1445
  async ({ description }) => {
1163
1446
  const token = process.env.GITHUB_TOKEN
@@ -1223,6 +1506,7 @@ server.registerTool(
1223
1506
  gist_id: z.string().describe("GitHub Gist ID or full URL (https://gist.github.com/user/id)."),
1224
1507
  merge: z.boolean().optional().default(true).describe("If true, merge with existing memory. If false, replace entirely."),
1225
1508
  },
1509
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
1226
1510
  },
1227
1511
  async ({ gist_id, merge }) => {
1228
1512
  const token = process.env.GITHUB_TOKEN
@@ -1313,7 +1597,7 @@ server.registerTool(
1313
1597
  const tags = e.tags.join(";")
1314
1598
  const links = e.links.join(" ")
1315
1599
  const q = qualityScore(tags, links, e.content, e.date, e.accessed, e.lastAccessed)
1316
- return ` ${e.id}|${e.category}|${e.key}|${e.content}|${e.file}|${tags}|${e.date}|${e.ttl}|${e.accessed}|${links}|${q.toFixed(2)}|1|${e.lastAccessed}`
1600
+ return toToonLine([e.id, e.category, e.key, e.content, e.file, tags, e.date, e.ttl, String(e.accessed), links, q.toFixed(2), "1", e.lastAccessed])
1317
1601
  }),
1318
1602
  ]
1319
1603
  safeWrite(MEMORY_FILE, lines.join("\n"))
@@ -1341,6 +1625,7 @@ server.registerTool(
1341
1625
  since: z.string().optional().default("24h").describe("Time window to merge (e.g. '24h', '7d', '2026-07-20'). Default: 24h."),
1342
1626
  promote: z.boolean().optional().default(false).describe("If true, auto-promote unique observations to memory entries."),
1343
1627
  },
1628
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
1344
1629
  },
1345
1630
  async ({ since, promote }) => {
1346
1631
  const { listSessions, pruneSessions } = await import("../lib/sessions")
@@ -1378,7 +1663,7 @@ server.registerTool(
1378
1663
  observations = data.split("\n")
1379
1664
  .filter((l) => l.startsWith(" ") && l.includes("|"))
1380
1665
  .map((l) => {
1381
- const p = l.trim().split("|")
1666
+ const p = parseToonLine(l)
1382
1667
  return { ts: p[0] || "", session: p[1] || "", agent: p[2] || "", branch: p[3] || "", tool: p[4] || "", file: p[6] || "", summary: p[7] || "" }
1383
1668
  })
1384
1669
  .filter((o) => sessionIds.has(o.session))
@@ -1446,7 +1731,7 @@ server.registerTool(
1446
1731
  const file = obs.file || ""
1447
1732
  const tags = `session-merge;${obs.agent};${obs.branch}`
1448
1733
  const quality = qualityScore(tags, "", content, date)
1449
- const entry = `${newId}|knowledge|${key}|${content}|${file}|${tags}|${date}||0||${quality.toFixed(2)}|1|`
1734
+ const entry = toToonLine([newId, "knowledge", key, content, file, tags, date, "", "0", "", quality.toFixed(2), "1", ""])
1450
1735
 
1451
1736
  // Append to memory
1452
1737
  const lines = data.split("\n")
@@ -1457,7 +1742,7 @@ server.registerTool(
1457
1742
  }
1458
1743
  const match = lines[headerIdx].match(/\[(\d+)\|/)
1459
1744
  const count = match ? parseInt(match[1]) : 0
1460
- lines.splice(headerIdx + 1, 0, ` ${entry}`)
1745
+ lines.splice(headerIdx + 1, 0, entry)
1461
1746
  lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`)
1462
1747
  writeMemory(lines.join("\n"))
1463
1748
  existingKeys.add(key)
@@ -1473,128 +1758,6 @@ server.registerTool(
1473
1758
  }
1474
1759
  )
1475
1760
 
1476
- // ── memory_merge_similar ─────────────────────────────────────────────
1477
-
1478
- server.registerTool(
1479
- "memory_merge_similar",
1480
- {
1481
- title: "Merge Similar Entries",
1482
- description: "Find entries with overlapping content (>50% word similarity) and merge them. Deterministic, no LLM. Keeps the longer content and combines tags.",
1483
- inputSchema: {
1484
- dryRun: z.boolean().optional().default(false).describe("If true, show what would be merged without making changes."),
1485
- },
1486
- },
1487
- async ({ dryRun }) => {
1488
- const data = readMemory()
1489
- const entries = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
1490
-
1491
- if (entries.length < 2) {
1492
- return { content: [{ type: "text" as const, text: "✅ Not enough entries to compress." }] }
1493
- }
1494
-
1495
- // Parse entries and compute similarity
1496
- const parsed = entries.map((line) => {
1497
- const parts = line.trim().split("|")
1498
- if (parts.length < 7) return null
1499
- const [id, cat, key, content, file, tags, date, ttl, accessedRaw] = parts
1500
- const words = new Set(normalize(`${key} ${content} ${tags}`).split(" ").filter(Boolean))
1501
- return { id, cat, key, content, file, tags, date, ttl, accessed: parseInt(accessedRaw) || 0, words, line }
1502
- }).filter(Boolean) as Array<{ id: string; cat: string; key: string; content: string; file: string; tags: string; date: string; ttl: string; accessed: number; words: Set<string>; line: string }>
1503
-
1504
- // Find pairs with >50% word overlap (Jaccard similarity)
1505
- const mergePairs: Array<{ a: number; b: number; similarity: number }> = []
1506
- for (let i = 0; i < parsed.length; i++) {
1507
- for (let j = i + 1; j < parsed.length; j++) {
1508
- const a = parsed[i], b = parsed[j]
1509
- const intersection = new Set([...a.words].filter((w) => b.words.has(w)))
1510
- const union = new Set([...a.words, ...b.words])
1511
- const similarity = union.size > 0 ? intersection.size / union.size : 0
1512
- if (similarity > 0.5) {
1513
- mergePairs.push({ a: i, b: j, similarity })
1514
- }
1515
- }
1516
- }
1517
-
1518
- if (mergePairs.length === 0) {
1519
- return { content: [{ type: "text" as const, text: "✅ No similar entries found to merge." }] }
1520
- }
1521
-
1522
- // Sort by similarity (highest first) and merge greedily
1523
- mergePairs.sort((x, y) => y.similarity - x.similarity)
1524
- const merged = new Set<number>()
1525
- const mergeActions: string[] = []
1526
-
1527
- for (const pair of mergePairs) {
1528
- if (merged.has(pair.a) || merged.has(pair.b)) continue
1529
- const a = parsed[pair.a], b = parsed[pair.b]
1530
-
1531
- // Merge: keep the entry with more content, combine tags
1532
- const mergedTags = [...new Set([...a.tags.split(";"), ...b.tags.split(";")])].filter(Boolean).join(";")
1533
- const longer = a.content.length >= b.content.length ? a : b
1534
- const shorter = a.content.length < b.content.length ? a : b
1535
- const newContent = longer.content
1536
- const newDate = a.date > b.date ? a.date : b.date
1537
- const newAccessed = a.accessed + b.accessed
1538
-
1539
- mergeActions.push(` [${longer.cat}] ${longer.key} ← ${shorter.key} (similarity: ${(pair.similarity * 100).toFixed(0)}%)`)
1540
-
1541
- if (!dryRun) {
1542
- // Update the longer entry with merged data
1543
- const mergedLine = ` ${longer.id}|${longer.cat}|${longer.key}|${newContent}|${longer.file}|${mergedTags}|${newDate}|${longer.ttl}|${newAccessed}|${longer.line.split("|")[9] || ""}|${longer.line.split("|")[10] || ""}|${longer.line.split("|")[11] || ""}|${longer.line.split("|")[12] || ""}`
1544
- // Replace in entries array
1545
- entries[entries.indexOf(longer.line)] = mergedLine
1546
- merged.add(pair.b)
1547
- }
1548
- }
1549
-
1550
- if (dryRun) {
1551
- // Detailed preview: show what each merge produces
1552
- const previewLines: string[] = [
1553
- `🔍 Dry run — ${mergePairs.length} merge candidate(s) found:`,
1554
- "",
1555
- ]
1556
- for (const pair of mergePairs) {
1557
- const a = parsed[pair.a], b = parsed[pair.b]
1558
- const mergedTags = [...new Set([...a.tags.split(";"), ...b.tags.split(";")])].filter(Boolean).join(";")
1559
- const longer = a.content.length >= b.content.length ? a : b
1560
- const shorter = a.content.length < b.content.length ? a : b
1561
- previewLines.push(` ── Pair: [${a.cat}] ${a.key} ↔ [${b.cat}] ${b.key}`)
1562
- previewLines.push(` Similarity: ${(pair.similarity * 100).toFixed(0)}%`)
1563
- previewLines.push(` A tags: ${a.tags || "(none)"}`)
1564
- previewLines.push(` B tags: ${b.tags || "(none)"}`)
1565
- previewLines.push(` → Merged tags: ${mergedTags || "(none)"}`)
1566
- previewLines.push(` → Content winner: "${longer.key}" (${longer.content.length} chars vs ${shorter.content.length})`)
1567
- previewLines.push(` → Result content: ${longer.content.slice(0, 120)}${longer.content.length > 120 ? "…" : ""}`)
1568
- previewLines.push("")
1569
- }
1570
- previewLines.push(`Would merge ${merged.size} entries into ${entries.length - merged.size} entries.`)
1571
- previewLines.push("Run with dryRun: false to apply.")
1572
- return {
1573
- content: [{
1574
- type: "text" as const,
1575
- text: previewLines.join("\n"),
1576
- }],
1577
- }
1578
- }
1579
-
1580
- // Remove merged entries and write back
1581
- const newLines = entries.filter((_, i) => !merged.has(i))
1582
- const headerIdx = newLines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
1583
- if (headerIdx !== -1) {
1584
- const count = newLines.filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")).length
1585
- newLines[headerIdx] = newLines[headerIdx].replace(/\[\d+\|/, `[${count}|`)
1586
- }
1587
- writeMemory(newLines.join("\n"))
1588
-
1589
- return {
1590
- content: [{
1591
- type: "text" as const,
1592
- text: `✅ Merged ${merged.size} entries into ${entries.length - merged.size} entries.\n\n${mergeActions.join("\n")}`
1593
- }],
1594
- }
1595
- }
1596
- )
1597
-
1598
1761
  // ── memory_graph_path ────────────────────────────────────────────────
1599
1762
 
1600
1763
  server.registerTool(
@@ -1606,6 +1769,7 @@ server.registerTool(
1606
1769
  from: z.string().describe("Starting entry key"),
1607
1770
  to: z.string().describe("Target entry key"),
1608
1771
  },
1772
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
1609
1773
  },
1610
1774
  async ({ from, to }) => {
1611
1775
  const data = readMemory()
@@ -1680,6 +1844,7 @@ server.registerTool(
1680
1844
  inputSchema: {
1681
1845
  note: z.string().optional().default("").describe("Optional summary of what was accomplished in this session."),
1682
1846
  },
1847
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
1683
1848
  },
1684
1849
  async ({ note }) => {
1685
1850
  const data = readMemory()
@@ -1715,7 +1880,7 @@ server.registerTool(
1715
1880
  const line = lines[i]
1716
1881
  if (!line.startsWith(" ") || !line.includes("|")) continue
1717
1882
  if (line.startsWith(" summaries:")) break
1718
- const parts = line.trim().split("|")
1883
+ const parts = parseToonLine(line)
1719
1884
  if (parts[2] === key) {
1720
1885
  existingIdx = i
1721
1886
  existingId = parts[0]
@@ -1725,13 +1890,13 @@ server.registerTool(
1725
1890
 
1726
1891
  if (existingIdx !== -1) {
1727
1892
  // Update existing checkpoint
1728
- const parts = lines[existingIdx].trim().split("|")
1893
+ const parts = parseToonLine(lines[existingIdx])
1729
1894
  parts[3] = content
1730
1895
  parts[6] = date
1731
1896
  parts[7] = ttl7d
1732
1897
  while (parts.length < 14) parts.push("")
1733
1898
  parts[13] = "0"
1734
- lines[existingIdx] = ` ${parts.join("|")}`
1899
+ lines[existingIdx] = toToonLine(parts)
1735
1900
  writeMemory(lines.join("\n"))
1736
1901
  return {
1737
1902
  content: [{ type: "text" as const, text: `📝 Checkpoint updated: ${key}\n⏰ TTL: ${ttl7d} (7d)\n${note ? `\n${note}` : ""}` }],
@@ -1741,11 +1906,11 @@ server.registerTool(
1741
1906
  // Create new checkpoint entry
1742
1907
  const newId = `cp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
1743
1908
  const quality = qualityScore("checkpoint", "", content, date)
1744
- const newEntry = `${newId}|knowledge|${key}|${content}||checkpoint|${date}|${ttl7d}|0||${quality.toFixed(2)}|1|${now.toISOString()}|0`
1909
+ const newEntry = toToonLine([newId, "knowledge", key, content, "", "checkpoint", date, ttl7d, "0", "", quality.toFixed(2), "1", now.toISOString(), "0"])
1745
1910
 
1746
1911
  const match = lines[headerIdx].match(/\[(\d+)\|/)
1747
1912
  const count = match ? parseInt(match[1]) : 0
1748
- lines.splice(headerIdx + 1, 0, ` ${newEntry}`)
1913
+ lines.splice(headerIdx + 1, 0, newEntry)
1749
1914
  lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`)
1750
1915
  writeMemory(lines.join("\n"))
1751
1916
 
@@ -1769,6 +1934,7 @@ server.registerTool(
1769
1934
  key: z.string().describe("Key or id of the entry to pin"),
1770
1935
  priority: z.number().optional().default(1).describe("Priority level 1-5 (5 = highest). Default: 1."),
1771
1936
  },
1937
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
1772
1938
  },
1773
1939
  async ({ key, priority }) => {
1774
1940
  const data = readMemory()
@@ -1786,11 +1952,11 @@ server.registerTool(
1786
1952
  const line = lines[i]
1787
1953
  if (!line.startsWith(" ") || !line.includes("|")) continue
1788
1954
  if (line.startsWith(" summaries:")) break
1789
- const parts = line.trim().split("|")
1955
+ const parts = parseToonLine(line)
1790
1956
  if (parts[0] === key || parts[2] === key) {
1791
1957
  while (parts.length < 14) parts.push("")
1792
1958
  parts[13] = String(clampedPriority)
1793
- lines[i] = ` ${parts.join("|")}`
1959
+ lines[i] = toToonLine(parts)
1794
1960
  found = true
1795
1961
  break
1796
1962
  }
@@ -1815,6 +1981,7 @@ server.registerTool(
1815
1981
  inputSchema: {
1816
1982
  key: z.string().describe("Key or id of the entry to unpin"),
1817
1983
  },
1984
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
1818
1985
  },
1819
1986
  async ({ key }) => {
1820
1987
  const data = readMemory()
@@ -1830,11 +1997,11 @@ server.registerTool(
1830
1997
  const line = lines[i]
1831
1998
  if (!line.startsWith(" ") || !line.includes("|")) continue
1832
1999
  if (line.startsWith(" summaries:")) break
1833
- const parts = line.trim().split("|")
2000
+ const parts = parseToonLine(line)
1834
2001
  if (parts[0] === key || parts[2] === key) {
1835
2002
  if (parts.length > 13) {
1836
2003
  parts[13] = "0"
1837
- lines[i] = ` ${parts.join("|")}`
2004
+ lines[i] = toToonLine(parts)
1838
2005
  }
1839
2006
  found = true
1840
2007
  break
@@ -1870,9 +2037,12 @@ server.registerTool(
1870
2037
  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
2038
  bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
1872
2039
  path_scope: z.string().optional().default("").describe("Glob pattern to filter entries by path scope (e.g. 'src/**.ts')."),
2040
+ 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."),
2041
+ as_of: z.string().optional().default("").describe("Temporal view (YYYY-MM-DD): return entries valid on that date."),
1873
2042
  },
2043
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
1874
2044
  },
1875
- async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact, bias, budget: budgetParam, path_scope }) => {
2045
+ async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact, bias, budget: budgetParam, path_scope, rrf, as_of }) => {
1876
2046
  const data = readMemory()
1877
2047
 
1878
2048
  const resolvedFrom = from_date ? parseRelativeDate(from_date) : ""
@@ -1887,6 +2057,8 @@ server.registerTool(
1887
2057
  limit,
1888
2058
  sessionFiles,
1889
2059
  path_scope: path_scope || undefined,
2060
+ rrf,
2061
+ asOf: as_of || undefined,
1890
2062
  })
1891
2063
 
1892
2064
  if (detail.entries.length === 0) {
@@ -1912,7 +2084,8 @@ server.registerTool(
1912
2084
  const originInfo = r.origin !== "agent" ? ` | origin: ${r.origin}` : ""
1913
2085
  const scopeInfo = r.path_scope ? ` | scope: ${r.path_scope}` : ""
1914
2086
  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}`
2087
+ const supersededInfo = r.supersededOn ? ` | superseded: ${r.supersededOn}` : ""
2088
+ 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
2089
  })
1917
2090
  .join("\n\n")
1918
2091
 
@@ -1940,6 +2113,7 @@ server.registerTool(
1940
2113
  tags: z.string().describe("Semicolon-separated tags to apply"),
1941
2114
  ids: z.string().describe("Comma or space-separated entry keys or IDs to modify"),
1942
2115
  },
2116
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
1943
2117
  },
1944
2118
  async ({ action, tags, ids }) => {
1945
2119
  const data = readMemory()
@@ -1965,7 +2139,7 @@ server.registerTool(
1965
2139
  const line = lines[i]
1966
2140
  if (!line.startsWith(" ") || !line.includes("|")) continue
1967
2141
  if (line.startsWith(" summaries:")) break
1968
- const parts = line.trim().split("|")
2142
+ const parts = parseToonLine(line)
1969
2143
  const entryId = parts[0]
1970
2144
  const entryKey = parts[2]
1971
2145
 
@@ -1983,7 +2157,7 @@ server.registerTool(
1983
2157
  }
1984
2158
 
1985
2159
  parts[5] = newTags.join(";")
1986
- lines[i] = ` ${parts.join("|")}`
2160
+ lines[i] = toToonLine(parts)
1987
2161
  modified++
1988
2162
  modifiedKeys.push(entryKey)
1989
2163
  }
@@ -2004,95 +2178,294 @@ server.registerTool(
2004
2178
  }
2005
2179
  )
2006
2180
 
2007
- // ── memory_resolve ───────────────────────────────────────────────────────────
2181
+ // ── memory_reflect ───────────────────────────────────────────────────────────
2008
2182
 
2009
2183
  server.registerTool(
2010
- "memory_resolve",
2184
+ "memory_reflect",
2011
2185
  {
2012
- title: "Resolve Entry",
2013
- description: "Restore an obsolete entry back to active status, or mark an entry as resolved. Reverses soft-delete.",
2186
+ title: "Reflect on Memory",
2187
+ 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.",
2014
2188
  inputSchema: {
2015
- key: z.string().describe("Key or id of the entry to resolve/restore"),
2189
+ category: z.string().optional().default("").describe("Restrict analysis to one category (empty = all)."),
2190
+ limit: z.number().optional().default(5).describe("Max items per section."),
2016
2191
  },
2192
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
2017
2193
  },
2018
- async ({ key }) => {
2194
+ async ({ category, limit }) => {
2019
2195
  const data = readMemory()
2020
- const lines = data.split("\n")
2021
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
2196
+ const entries = parseEntries(data)
2197
+ const cap = Math.max(1, Math.min(20, limit || 5))
2198
+ if (entries.length === 0) {
2199
+ return { content: [{ type: "text" as const, text: "Empty memory." }] }
2200
+ }
2022
2201
 
2023
- if (headerIdx === -1) {
2024
- return { content: [{ type: "text" as const, text: "No entries in memory" }] }
2202
+ const scope = entries.filter((e) => !category || e.category === category)
2203
+ const { adjacency } = buildGraph(entries)
2204
+
2205
+ const sections: string[] = [`🧠 Memory reflect (${scope.length}/${entries.length} entries)`]
2206
+
2207
+ // 1. Hubs and orphans
2208
+ const degree = new Map<string, number>()
2209
+ for (const [k, nbs] of adjacency) degree.set(k, nbs.length)
2210
+ const hubs = [...degree.entries()].sort((a, b) => b[1] - a[1]).filter(([, d]) => d >= 3)
2211
+ if (hubs.length > 0) {
2212
+ sections.push("", "🔗 Hubs (connectors):")
2213
+ for (const [k, d] of hubs.slice(0, cap)) {
2214
+ const e = entries.find((x) => x.key === k)
2215
+ sections.push(` ${k} (deg ${d}) — ${e ? e.content.slice(0, 70) : ""}`)
2216
+ }
2217
+ }
2218
+ const orphans = scope.filter((e) => e.status === "active" && !(degree.get(e.key) || 0) && e.tags.length === 0)
2219
+ if (orphans.length > 0) {
2220
+ sections.push("", "🕳️ Orphans (no links, no tags — consider linking):")
2221
+ for (const e of orphans.slice(0, cap)) {
2222
+ sections.push(` [${e.category}] ${e.key} — ${e.content.slice(0, 70)}`)
2223
+ }
2025
2224
  }
2026
2225
 
2027
- let found = false
2028
- let wasObsolete = false
2029
- for (let i = headerIdx + 1; i < lines.length; i++) {
2030
- const line = lines[i]
2031
- if (!line.startsWith(" ") || !line.includes("|")) continue
2032
- if (line.startsWith(" summaries:")) break
2033
- const parts = line.trim().split("|")
2034
- if (parts[0] === key || parts[2] === key) {
2035
- while (parts.length < 17) parts.push("")
2036
- wasObsolete = parts[16] === "obsolete"
2037
- parts[16] = "active"
2038
- lines[i] = ` ${parts.join("|")}`
2039
- found = true
2040
- break
2226
+ // 2. Tag co-occurrence themes
2227
+ const pairCount = new Map<string, number>()
2228
+ for (const e of scope) {
2229
+ if (e.tags.length < 2) continue
2230
+ const t = [...e.tags].sort()
2231
+ for (let i = 0; i < t.length; i++) {
2232
+ for (let j = i + 1; j < t.length; j++) {
2233
+ const pair = `${t[i]} + ${t[j]}`
2234
+ pairCount.set(pair, (pairCount.get(pair) || 0) + 1)
2235
+ }
2236
+ }
2237
+ }
2238
+ const themes = [...pairCount.entries()].sort((a, b) => b[1] - a[1])
2239
+ if (themes.length > 0) {
2240
+ sections.push("", "🏷️ Latent themes (tag co-occurrence):")
2241
+ for (const [pair, n] of themes.slice(0, cap)) {
2242
+ sections.push(` ${pair} — ${n} entries`)
2041
2243
  }
2042
2244
  }
2043
2245
 
2044
- if (!found) {
2045
- return { content: [{ type: "text" as const, text: `"${key}" not found in memory.` }] }
2246
+ // 3. Near-duplicates (Jaccard word overlap > 0.5)
2247
+ const active = scope.filter((e) => e.status === "active")
2248
+ const wordSets = new Map<string, Set<string>>()
2249
+ for (const e of active) {
2250
+ wordSets.set(e.key, new Set(normalize(`${e.key} ${e.content} ${e.tags.join(" ")}`).split(" ").filter(Boolean)))
2251
+ }
2252
+ const dupes: Array<{ a: string; b: string; sim: number }> = []
2253
+ const keysArr = active.map((e) => e.key)
2254
+ for (let i = 0; i < keysArr.length; i++) {
2255
+ for (let j = i + 1; j < keysArr.length; j++) {
2256
+ const wa = wordSets.get(keysArr[i])!
2257
+ const wb = wordSets.get(keysArr[j])!
2258
+ const inter = new Set([...wa].filter((w) => wb.has(w)))
2259
+ const union = new Set([...wa, ...wb])
2260
+ const sim = union.size > 0 ? inter.size / union.size : 0
2261
+ if (sim > 0.5) dupes.push({ a: keysArr[i], b: keysArr[j], sim })
2262
+ }
2263
+ }
2264
+ if (dupes.length > 0) {
2265
+ sections.push("", "♻️ Near-duplicates (merge candidates):")
2266
+ for (const d of dupes.sort((x, y) => y.sim - x.sim).slice(0, cap)) {
2267
+ sections.push(` ${d.a} ↔ ${d.b} (${(d.sim * 100).toFixed(0)}% overlap)`)
2268
+ }
2046
2269
  }
2047
2270
 
2048
- writeMemory(lines.join("\n"))
2271
+ // 4. Contradiction candidates: same category, ≥2 shared tags, split polarity markers
2272
+ 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
2273
+ const contradictions: string[] = []
2274
+ for (let i = 0; i < active.length; i++) {
2275
+ for (let j = i + 1; j < active.length; j++) {
2276
+ const a = active[i], b = active[j]
2277
+ if (a.category !== b.category) continue
2278
+ const shared = a.tags.filter((t) => b.tags.includes(t)).length
2279
+ if (shared < 2) continue
2280
+ const aNeg = NEGATION.test(a.content)
2281
+ const bNeg = NEGATION.test(b.content)
2282
+ if (aNeg !== bNeg) {
2283
+ contradictions.push(`${a.key} ↔ ${b.key} [${a.category}] (${shared} shared tags, split polarity)`)
2284
+ }
2285
+ }
2286
+ }
2287
+ if (contradictions.length > 0) {
2288
+ sections.push("", "⚡ Contradiction candidates (verify):")
2289
+ for (const c of contradictions.slice(0, cap)) {
2290
+ sections.push(` ${c}`)
2291
+ }
2292
+ }
2049
2293
 
2050
- const msg = wasObsolete ? `"${key}" restored to active status.` : `"${key}" marked as resolved.`
2051
- return { content: [{ type: "text" as const, text: `✅ ${msg}` }] }
2294
+ // 5. Stale / archive candidates
2295
+ const now = Date.now()
2296
+ const stale = active.filter((e) => {
2297
+ if (e.tags.includes("private")) return false
2298
+ if (e.ttl && isExpiredLocal(e.ttl)) return true
2299
+ if (!e.date) return false
2300
+ const ageDays = (now - new Date(`${e.date}T00:00:00`).getTime()) / 86400000
2301
+ const lastAccessDays = e.lastAccessed ? (now - new Date(e.lastAccessed).getTime()) / 86400000 : ageDays
2302
+ return ageDays > 120 && lastAccessDays > 90 && e.accessed === 0
2303
+ })
2304
+ if (stale.length > 0) {
2305
+ sections.push("", "🗄️ Stale (archive candidates):")
2306
+ for (const e of stale.sort((a, b) => a.date.localeCompare(b.date)).slice(0, cap)) {
2307
+ sections.push(` [${e.category}] ${e.key} — ${e.content.slice(0, 70)}`)
2308
+ }
2309
+ }
2310
+
2311
+ // 6. Superseded-but-active (tag/link present but status not obsolete)
2312
+ const pending = entries.filter((e) => e.status === "active" && (e.tags.includes("superseded") || typedLinks(e.links).some((l) => l.type === "superseded_by")))
2313
+ if (pending.length > 0) {
2314
+ sections.push("", "🔎 Superseded tag but still active (fix with memory_forget action: 'supersede'):")
2315
+ for (const e of pending.slice(0, cap)) {
2316
+ sections.push(` [${e.category}] ${e.key}`)
2317
+ }
2318
+ }
2319
+
2320
+ // 7. Drafts pending review
2321
+ const drafts = entries.filter((e) => e.status === "draft")
2322
+ if (drafts.length > 0) {
2323
+ sections.push("", "📝 Drafts pending review (promote with memory_promote / memory_forget action: 'restore'):")
2324
+ for (const e of drafts.slice(0, cap)) {
2325
+ sections.push(` [${e.category}] ${e.key} — ${e.content.slice(0, 70)}`)
2326
+ }
2327
+ }
2328
+
2329
+ return { content: [{ type: "text" as const, text: sections.join("\n") }] }
2052
2330
  }
2053
2331
  )
2054
2332
 
2055
- // ── memory_suppress ──────────────────────────────────────────────────────────
2333
+ // ── memory_promote ───────────────────────────────────────────────────────────
2056
2334
 
2057
2335
  server.registerTool(
2058
- "memory_suppress",
2336
+ "memory_promote",
2059
2337
  {
2060
- title: "Suppress Entry",
2061
- description: "Suppress a memory entry so it's hidden from normal recalls. Sets status to 'obsolete'. Use memory_resolve to restore.",
2338
+ title: "Promote Observations",
2339
+ 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.",
2062
2340
  inputSchema: {
2063
- key: z.string().describe("Key or id of the entry to suppress"),
2341
+ dryRun: z.boolean().optional().default(true).describe("If true, only preview what would be promoted (no writes)."),
2342
+ minConfidence: z.number().optional().default(0.65).describe("Observations at or below this confidence become drafts; above it become active entries."),
2343
+ max: z.number().optional().default(5).describe("Maximum observations to promote."),
2344
+ days: z.number().optional().default(7).describe("Only consider observations from the last N days."),
2064
2345
  },
2346
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
2065
2347
  },
2066
- async ({ key }) => {
2348
+ async ({ dryRun, minConfidence, max, days }) => {
2349
+ const obs = readObservations()
2350
+ if (obs.length === 0) {
2351
+ return { content: [{ type: "text" as const, text: "No captured activity. Enable with `toon-memory capture on`." }] }
2352
+ }
2353
+
2354
+ const cutoff = Date.now() - (days || 7) * 86400000
2355
+ const recent = obs.filter((o) => new Date(o.ts).getTime() >= cutoff)
2356
+
2067
2357
  const data = readMemory()
2068
- const lines = data.split("\n")
2069
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
2358
+ const existing = parseEntries(data)
2359
+ const existingKeys = new Set(existing.map((e) => e.key))
2360
+ const existingWords = existing.map((e) => new Set(normalize(`${e.key} ${e.content} ${e.tags.join(" ")}`).split(" ").filter(Boolean)))
2361
+
2362
+ // Deterministic confidence heuristic (0..1).
2363
+ const confidence = (o: { tool: string; file: string; summary: string }): number => {
2364
+ const summary = (o.summary || "").trim()
2365
+ if (!summary) return 0.1
2366
+ let c = 0.5
2367
+ const len = summary.length
2368
+ if (len >= 40 && len <= 300) c += 0.1
2369
+ else if (len < 40) c -= 0.1
2370
+ if (o.file) c += 0.15
2371
+ const tool = (o.tool || "").toLowerCase()
2372
+ if (["edit", "write", "create", "bash", "git", "npm"].includes(tool)) c += 0.1
2373
+ else if (["read", "grep", "glob", "search", "ls", "list"].includes(tool)) c -= 0.15
2374
+ if (/\b(error|fail|bug|fix|broken|fails|failed|cannot|crash)\b/i.test(summary)) c += 0.1
2375
+ if (/\b(viewed|read|opened|inspected|browsed|listed|scanned)\b/i.test(summary)) c -= 0.1
2376
+ return Math.max(0.05, Math.min(1, c))
2377
+ }
2378
+
2379
+ const alreadyKnown = (o: { tool: string; summary: string }): boolean => {
2380
+ const words = new Set(normalize(`${o.tool} ${o.summary}`).split(" ").filter(Boolean))
2381
+ if (words.size === 0) return true
2382
+ for (const set of existingWords) {
2383
+ const inter = new Set([...words].filter((w) => set.has(w)))
2384
+ const union = new Set([...words, ...set])
2385
+ if (inter.size / union.size > 0.5) return true
2386
+ }
2387
+ return false
2388
+ }
2070
2389
 
2071
- if (headerIdx === -1) {
2072
- return { content: [{ type: "text" as const, text: "No entries in memory" }] }
2390
+ const seen = new Set<string>()
2391
+ const candidates = recent
2392
+ .filter((o) => {
2393
+ const dedupKey = `${o.tool}|${o.summary}`
2394
+ if (seen.has(dedupKey)) return false
2395
+ seen.add(dedupKey)
2396
+ return o.summary && !alreadyKnown(o)
2397
+ })
2398
+ .map((o) => ({ o, conf: confidence(o) }))
2399
+ .sort((a, b) => b.conf - a.conf)
2400
+ .slice(0, max || 5)
2401
+
2402
+ if (candidates.length === 0) {
2403
+ return { content: [{ type: "text" as const, text: "✅ Nothing new to promote — all recent observations are already covered by memory or below threshold." }] }
2073
2404
  }
2074
2405
 
2075
- let found = false
2076
- for (let i = headerIdx + 1; i < lines.length; i++) {
2077
- const line = lines[i]
2078
- if (!line.startsWith(" ") || !line.includes("|")) continue
2079
- if (line.startsWith(" summaries:")) break
2080
- const parts = line.trim().split("|")
2081
- if (parts[0] === key || parts[2] === key) {
2082
- while (parts.length < 17) parts.push("")
2083
- parts[16] = "obsolete"
2084
- lines[i] = ` ${parts.join("|")}`
2085
- found = true
2086
- break
2406
+ const preview = candidates.map(({ o, conf }) => {
2407
+ const kind = conf <= minConfidence ? "draft" : "active"
2408
+ return ` [${kind}] ${(o.summary || "").slice(0, 90)} (conf ${conf.toFixed(2)})${o.file ? ` @ ${o.file}` : ""}`
2409
+ })
2410
+ const kindLabel = (conf: number) => (conf <= minConfidence ? "draft" : "active")
2411
+
2412
+ if (dryRun) {
2413
+ return {
2414
+ content: [{
2415
+ type: "text" as const,
2416
+ 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.`
2417
+ }],
2087
2418
  }
2088
2419
  }
2089
2420
 
2090
- if (!found) {
2091
- return { content: [{ type: "text" as const, text: `"${key}" not found in memory.` }] }
2421
+ const date = new Date().toISOString().split("T")[0]
2422
+ const lines = data.split("\n")
2423
+ let headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
2424
+ if (headerIdx === -1) {
2425
+ lines.push(`[0|]`)
2426
+ headerIdx = lines.length - 1
2092
2427
  }
2093
-
2428
+ const match = lines[headerIdx].match(/\[(\d+)\|/)
2429
+ let count = match ? parseInt(match[1]) : 0
2430
+
2431
+ let promoted = 0
2432
+ let drafted = 0
2433
+ const actions: string[] = []
2434
+ for (const { o, conf } of candidates) {
2435
+ const key = o.summary
2436
+ .toLowerCase()
2437
+ .replace(/[^a-z0-9\s]/g, "")
2438
+ .split(/\s+/)
2439
+ .filter(Boolean)
2440
+ .slice(0, 4)
2441
+ .join("-")
2442
+ .slice(0, 40) || `observation-${Date.now().toString(36)}`
2443
+ if (existingKeys.has(key)) continue
2444
+
2445
+ const newId = generateId()
2446
+ const status = kindLabel(conf)
2447
+ const tags = ["captured", `${o.agent || "agent"}`]
2448
+ if (status === "draft") tags.push("draft")
2449
+ const content = (o.summary || "").slice(0, 500)
2450
+ const quality = qualityScore(tags.join(";"), "", content, date)
2451
+ const entry = toToonLine([newId, "knowledge", key, content, o.file || "", tags.join(";"), date, "", "0", "", quality.toFixed(2), conf.toFixed(2), date, "0", "", "inferred", status])
2452
+
2453
+ lines.splice(headerIdx + 1, 0, entry)
2454
+ count++
2455
+ existingKeys.add(key)
2456
+ if (status === "draft") drafted++
2457
+ else promoted++
2458
+ actions.push(` [${status}] ${key} (conf ${conf.toFixed(2)})`)
2459
+ }
2460
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count}|`)
2094
2461
  writeMemory(lines.join("\n"))
2095
- return { content: [{ type: "text" as const, text: `"${key}" suppressed. Use memory_resolve(key: "${key}") to restore.` }] }
2462
+
2463
+ return {
2464
+ content: [{
2465
+ type: "text" as const,
2466
+ 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_forget(key, action: 'restore') to activate, or review with memory_reflect.`
2467
+ }],
2468
+ }
2096
2469
  }
2097
2470
  )
2098
2471
 
@@ -2107,6 +2480,7 @@ registerAppTool(
2107
2480
  inputSchema: {
2108
2481
  query: z.string().optional().default("").describe("Optional search query to highlight entries in the viewer"),
2109
2482
  },
2483
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
2110
2484
  _meta: { ui: { resourceUri: "ui://viewer" } },
2111
2485
  },
2112
2486
  async ({ query }) => {