toon-memory 3.7.0 → 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
@@ -17,7 +17,7 @@ import { qualityScore, mergeEntries, generateSmartRecall } from "../lib/quality"
17
17
  import { generateContextBrief, generateContextGenerate, generateContextDiff, generateContextFocus, generateContextHealth, generateContextExport } from "../lib/context"
18
18
  import { coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS, getCurrentSessionFiles } from "../lib/sessions"
19
19
  import { fileMtimes } from "../lib/git"
20
- import { normalize, isExpiredLocal, tokenize, importance } 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(
@@ -63,7 +466,7 @@ server.registerTool(
63
466
  const line = lines[i]
64
467
  if (!line.startsWith(" ") || !line.includes("|")) continue
65
468
  if (line.startsWith(" summaries:")) break
66
- const parts = line.trim().split("|")
469
+ const parts = parseToonLine(line)
67
470
  if (parts[2] === key) {
68
471
  existingIdx = i
69
472
  existingId = parts[0]
@@ -76,18 +479,18 @@ server.registerTool(
76
479
  const config = loadConfig()
77
480
  const verbatim = config.verbatim === true
78
481
  const resolvedTags = tags ? tags : (verbatim ? "" : inferTags(content, key, config.vocab))
79
- const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : []
482
+ const existingParts = existingIdx !== -1 ? parseToonLine(lines[existingIdx]) : []
80
483
  const resolvedLinks = links
81
484
  ? links.split(/[\s;]+/).filter(Boolean).join(" ")
82
485
  : existingParts[9] || ""
83
- 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])
84
487
  let action = "Saved"
85
488
  let mergeInfo = ""
86
489
  const tagsInferred = !tags && resolvedTags ? true : false
87
490
 
88
491
  if (existingIdx !== -1) {
89
492
  newEntry = mergeEntries(lines[existingIdx].trim(), newEntry)
90
- lines[existingIdx] = ` ${newEntry}`
493
+ lines[existingIdx] = newEntry
91
494
  action = "Updated"
92
495
  mergeInfo = "\nMerge: tags combined, date and links updated"
93
496
  } else {
@@ -95,10 +498,10 @@ server.registerTool(
95
498
  const lastAccessed = ""
96
499
  const quality = verbatim ? 0.5 : qualityScore(resolvedTags, resolvedLinks, content, date, accessed, lastAccessed, origin)
97
500
  const confidence = 1.0
98
- 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"])
99
502
  const match = lines[headerIdx].match(/\[(\d+)\|/)
100
503
  const count = match ? parseInt(match[1]) : 0
101
- lines.splice(headerIdx + 1, 0, ` ${newEntry}`)
504
+ lines.splice(headerIdx + 1, 0, newEntry)
102
505
  lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`)
103
506
  }
104
507
 
@@ -194,75 +597,26 @@ server.registerTool(
194
597
  server.registerTool(
195
598
  "memory_forget",
196
599
  {
197
- title: "Delete from Memory",
198
- 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.",
199
602
  inputSchema: {
200
- key: z.string().describe("Key or id of the entry to delete"),
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."),
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)."),
202
607
  },
203
608
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
204
609
  },
205
- async ({ key, hard }) => {
206
- const data = readMemory()
207
- const lines = data.split("\n")
208
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
209
-
210
- if (headerIdx === -1) {
211
- return { content: [{ type: "text" as const, text: "No entries in memory" }] }
212
- }
213
-
214
- if (hard) {
215
- const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
216
- const filtered = entryLines.filter((l) => {
217
- const parts = l.trim().split("|")
218
- return parts[0] !== key && parts[2] !== key
219
- })
220
-
221
- const removed = entryLines.length - filtered.length
222
- const match = lines[headerIdx].match(/\[(\d+)\|/)
223
- const count = match ? parseInt(match[1]) : 0
224
- lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`)
225
- lines.splice(headerIdx + 1, entryLines.length, ...filtered.map((l) => ` ${l.trim()}`))
226
-
227
- writeMemory(lines.join("\n"))
228
-
229
- if (removed === 0) {
230
- return {
231
- content: [{ type: "text" as const, text: `"${key}" not found in memory.` }],
232
- }
233
- }
234
-
235
- return {
236
- content: [{ type: "text" as const, text: `"${key}" permanently deleted. ${count - removed} entries remaining.` }],
237
- }
238
- }
239
-
240
- // Soft-delete: mark status as "obsolete"
241
- let found = false
242
- for (let i = headerIdx + 1; i < lines.length; i++) {
243
- const line = lines[i]
244
- if (!line.startsWith(" ") || !line.includes("|")) continue
245
- if (line.startsWith(" summaries:")) break
246
- const parts = line.trim().split("|")
247
- if (parts[0] === key || parts[2] === key) {
248
- while (parts.length < 17) parts.push("")
249
- parts[16] = "obsolete"
250
- lines[i] = ` ${parts.join("|")}`
251
- found = true
252
- break
253
- }
254
- }
255
-
256
- writeMemory(lines.join("\n"))
257
-
258
- if (!found) {
259
- return {
260
- content: [{ type: "text" as const, text: `"${key}" not found in memory.` }],
261
- }
262
- }
263
-
264
- return {
265
- 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)
266
620
  }
267
621
  }
268
622
  )
@@ -281,7 +635,7 @@ server.registerTool(
281
635
  const data = readMemory()
282
636
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
283
637
  const entries = lines.map((l) => {
284
- const parts = l.trim().split("|")
638
+ const parts = parseToonLine(l)
285
639
  return { category: parts[1] || "unknown", ttl: parts[7] || "", quality: parts[10] || "", origin: parts.length > 15 ? parts[15] || "" : "", status: parts.length > 16 ? parts[16] || "" : "" }
286
640
  })
287
641
 
@@ -323,7 +677,7 @@ server.registerTool(
323
677
  "",
324
678
  `Last 5 entries:`,
325
679
  ...lines.slice(-5).map((l) => {
326
- const parts = l.trim().split("|")
680
+ const parts = parseToonLine(l)
327
681
  const ttlInfo = parts[7] ? ` | TTL: ${parts[7]}` : ""
328
682
  const qualityInfo = parts[10] ? ` | Q: ${parts[10]}` : ""
329
683
  const accessInfo = parts[8] && parseInt(parts[8]) > 0 ? ` | accessed: ${parts[8]}x` : ""
@@ -336,7 +690,7 @@ server.registerTool(
336
690
  ...lines
337
691
  .filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
338
692
  .map((l) => {
339
- const parts = l.trim().split("|")
693
+ const parts = parseToonLine(l)
340
694
  return { key: parts[2], accessed: parts.length > 8 ? parseInt(parts[8]) || 0 : 0, quality: parts[10] || "" }
341
695
  })
342
696
  .filter((e) => e.accessed > 0)
@@ -349,7 +703,7 @@ server.registerTool(
349
703
  const coldEntries = lines
350
704
  .filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
351
705
  .map((l) => {
352
- const p = l.trim().split("|")
706
+ const p = parseToonLine(l)
353
707
  return {
354
708
  key: p[2],
355
709
  cat: p[1],
@@ -409,7 +763,7 @@ server.registerTool(
409
763
  const results = lines
410
764
  .map((line) => {
411
765
  const trimmed = line.trim()
412
- const parts = trimmed.split("|")
766
+ const parts = parseToonLine(trimmed)
413
767
  if (parts.length < 7) return null
414
768
  const [id, cat, key, content, file, tags, date] = parts
415
769
  if (date < sinceDate) return null
@@ -531,7 +885,7 @@ server.registerTool(
531
885
  return { content: [{ type: "text" as const, text: `No summary for "${file}"` }] }
532
886
  }
533
887
 
534
- const summaryText = match.replace(` ${file}: `, "")
888
+ const summaryText = unescField(match.replace(` ${file}: `, ""))
535
889
  return { content: [{ type: "text" as const, text: summaryText }] }
536
890
  }
537
891
 
@@ -547,9 +901,9 @@ server.registerTool(
547
901
  const existingIdx = summaryLines.findIndex((l) => l.startsWith(` ${file}:`))
548
902
 
549
903
  if (existingIdx !== -1) {
550
- summaryLines[existingIdx] = ` ${file}: ${summary}`
904
+ summaryLines[existingIdx] = ` ${file}: ${escField(summary)}`
551
905
  } else {
552
- summaryLines.push(` ${file}: ${summary}`)
906
+ summaryLines.push(` ${file}: ${escField(summary)}`)
553
907
  }
554
908
 
555
909
  lines.splice(summaryIdx + 1, lines.length - summaryIdx - 1, ...summaryLines)
@@ -711,20 +1065,22 @@ server.registerTool(
711
1065
  "memory_consolidate",
712
1066
  {
713
1067
  title: "Consolidate Memory",
714
- description: "Consolidate memory by removing entries with identical content (keeps the first). Deterministic, no LLM.",
715
- 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
+ },
716
1074
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
717
1075
  },
718
- async () => {
719
- const result = consolidateEntries()
720
- if (result.removed === 0) {
721
- return { content: [{ type: "text" as const, text: `✅ Memory already consolidated (${result.kept} entries, 0 duplicates)` }] }
722
- }
723
- return {
724
- content: [{
725
- type: "text" as const,
726
- text: `🧹 Consolidated ${result.removed} duplicate entries.\n${result.kept} active entries remaining.\nDuplicates: ${result.duplicates.join(", ")}`,
727
- }],
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()
728
1084
  }
729
1085
  }
730
1086
  )
@@ -1074,108 +1430,6 @@ server.registerTool(
1074
1430
  }
1075
1431
  )
1076
1432
 
1077
- // ── memory_compress_all ────────────────────────────────────────────────
1078
-
1079
- server.registerTool(
1080
- "memory_compress_all",
1081
- {
1082
- title: "Lazy Batch Compression",
1083
- 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.",
1084
- inputSchema: {
1085
- minQuality: z.number().optional().default(0.3).describe("Entries below this quality score are compression candidates (0-1). Default: 0.3."),
1086
- dryRun: z.boolean().optional().default(false).describe("If true, show what would be compressed without making changes."),
1087
- },
1088
- annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
1089
- },
1090
- async ({ minQuality, dryRun }) => {
1091
- const data = readMemory()
1092
- const lines = data.split("\n")
1093
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
1094
- if (headerIdx === -1) {
1095
- return { content: [{ type: "text" as const, text: "No entries in memory." }] }
1096
- }
1097
-
1098
- const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
1099
-
1100
- // Find compression candidates: low quality, no tags, or stale
1101
- const candidates: { idx: number; line: string; quality: number; key: string }[] = []
1102
- for (let i = 0; i < entryLines.length; i++) {
1103
- const line = entryLines[i].trim()
1104
- const parts = line.split("|")
1105
- if (parts.length < 11) continue
1106
- const quality = parseFloat(parts[10]) || 0
1107
- const tags = parts[5] || ""
1108
- const key = parts[2]
1109
- const content = parts[3] || ""
1110
-
1111
- // Candidates: low quality OR no tags OR very short content
1112
- const isCandidate = quality < minQuality || !tags || content.length < 20
1113
- if (isCandidate) {
1114
- candidates.push({ idx: i, line, quality, key })
1115
- }
1116
- }
1117
-
1118
- if (candidates.length === 0) {
1119
- return {
1120
- content: [{
1121
- type: "text" as const,
1122
- text: `✅ No compression candidates found. All entries have quality >= ${minQuality} or have tags.`
1123
- }],
1124
- }
1125
- }
1126
-
1127
- // Group candidates by category for potential merging
1128
- const byCategory = new Map<string, typeof candidates>()
1129
- for (const c of candidates) {
1130
- const parts = c.line.split("|")
1131
- const cat = parts[1] || "unknown"
1132
- if (!byCategory.has(cat)) byCategory.set(cat, [])
1133
- byCategory.get(cat)!.push(c)
1134
- }
1135
-
1136
- const sections: string[] = [
1137
- `📦 Compression candidates: ${candidates.length} entries below quality ${minQuality}`,
1138
- "",
1139
- "By category:",
1140
- ]
1141
-
1142
- for (const [cat, items] of byCategory) {
1143
- sections.push(` ${cat}: ${items.length} entries`)
1144
- for (const item of items.slice(0, 3)) {
1145
- const parts = item.line.split("|")
1146
- sections.push(` - ${item.key} (Q: ${item.quality.toFixed(2)}) — ${(parts[3] || "").slice(0, 60)}`)
1147
- }
1148
- if (items.length > 3) {
1149
- sections.push(` ... and ${items.length - 3} more`)
1150
- }
1151
- }
1152
-
1153
- if (dryRun) {
1154
- sections.push("", "🔍 Dry run — no changes made. Use dryRun: false to compress.")
1155
- return { content: [{ type: "text" as const, text: sections.join("\n") }] }
1156
- }
1157
-
1158
- // Remove candidates (conservative: just remove the lowest quality ones)
1159
- // Don't auto-merge — let the agent decide via memory_compress
1160
- const removeKeys = new Set(candidates.map((c) => c.key))
1161
- const kept = entryLines.filter((l) => {
1162
- const parts = l.trim().split("|")
1163
- return !removeKeys.has(parts[2])
1164
- })
1165
-
1166
- const match = lines[headerIdx].match(/\[(\d+)\|/)
1167
- const count = match ? parseInt(match[1]) : 0
1168
- lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${kept.length}|`)
1169
- lines.splice(headerIdx + 1, entryLines.length, ...kept.map((l) => ` ${l.trim()}`))
1170
- writeMemory(lines.join("\n"))
1171
-
1172
- sections.push("", `🗑️ Removed ${candidates.length} low-quality entries. ${kept.length} entries remaining.`)
1173
- sections.push("💡 Use memory_compress to merge related entries before removing them.")
1174
-
1175
- return { content: [{ type: "text" as const, text: sections.join("\n") }] }
1176
- }
1177
- )
1178
-
1179
1433
  // ── memory_export_gist ─────────────────────────────────────────────────
1180
1434
 
1181
1435
  server.registerTool(
@@ -1343,7 +1597,7 @@ server.registerTool(
1343
1597
  const tags = e.tags.join(";")
1344
1598
  const links = e.links.join(" ")
1345
1599
  const q = qualityScore(tags, links, e.content, e.date, e.accessed, e.lastAccessed)
1346
- 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])
1347
1601
  }),
1348
1602
  ]
1349
1603
  safeWrite(MEMORY_FILE, lines.join("\n"))
@@ -1409,7 +1663,7 @@ server.registerTool(
1409
1663
  observations = data.split("\n")
1410
1664
  .filter((l) => l.startsWith(" ") && l.includes("|"))
1411
1665
  .map((l) => {
1412
- const p = l.trim().split("|")
1666
+ const p = parseToonLine(l)
1413
1667
  return { ts: p[0] || "", session: p[1] || "", agent: p[2] || "", branch: p[3] || "", tool: p[4] || "", file: p[6] || "", summary: p[7] || "" }
1414
1668
  })
1415
1669
  .filter((o) => sessionIds.has(o.session))
@@ -1477,7 +1731,7 @@ server.registerTool(
1477
1731
  const file = obs.file || ""
1478
1732
  const tags = `session-merge;${obs.agent};${obs.branch}`
1479
1733
  const quality = qualityScore(tags, "", content, date)
1480
- 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", ""])
1481
1735
 
1482
1736
  // Append to memory
1483
1737
  const lines = data.split("\n")
@@ -1488,7 +1742,7 @@ server.registerTool(
1488
1742
  }
1489
1743
  const match = lines[headerIdx].match(/\[(\d+)\|/)
1490
1744
  const count = match ? parseInt(match[1]) : 0
1491
- lines.splice(headerIdx + 1, 0, ` ${entry}`)
1745
+ lines.splice(headerIdx + 1, 0, entry)
1492
1746
  lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`)
1493
1747
  writeMemory(lines.join("\n"))
1494
1748
  existingKeys.add(key)
@@ -1504,129 +1758,6 @@ server.registerTool(
1504
1758
  }
1505
1759
  )
1506
1760
 
1507
- // ── memory_merge_similar ─────────────────────────────────────────────
1508
-
1509
- server.registerTool(
1510
- "memory_merge_similar",
1511
- {
1512
- title: "Merge Similar Entries",
1513
- description: "Find entries with overlapping content (>50% word similarity) and merge them. Deterministic, no LLM. Keeps the longer content and combines tags.",
1514
- inputSchema: {
1515
- dryRun: z.boolean().optional().default(false).describe("If true, show what would be merged without making changes."),
1516
- },
1517
- annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
1518
- },
1519
- async ({ dryRun }) => {
1520
- const data = readMemory()
1521
- const entries = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
1522
-
1523
- if (entries.length < 2) {
1524
- return { content: [{ type: "text" as const, text: "✅ Not enough entries to compress." }] }
1525
- }
1526
-
1527
- // Parse entries and compute similarity
1528
- const parsed = entries.map((line) => {
1529
- const parts = line.trim().split("|")
1530
- if (parts.length < 7) return null
1531
- const [id, cat, key, content, file, tags, date, ttl, accessedRaw] = parts
1532
- const words = new Set(normalize(`${key} ${content} ${tags}`).split(" ").filter(Boolean))
1533
- return { id, cat, key, content, file, tags, date, ttl, accessed: parseInt(accessedRaw) || 0, words, line }
1534
- }).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 }>
1535
-
1536
- // Find pairs with >50% word overlap (Jaccard similarity)
1537
- const mergePairs: Array<{ a: number; b: number; similarity: number }> = []
1538
- for (let i = 0; i < parsed.length; i++) {
1539
- for (let j = i + 1; j < parsed.length; j++) {
1540
- const a = parsed[i], b = parsed[j]
1541
- const intersection = new Set([...a.words].filter((w) => b.words.has(w)))
1542
- const union = new Set([...a.words, ...b.words])
1543
- const similarity = union.size > 0 ? intersection.size / union.size : 0
1544
- if (similarity > 0.5) {
1545
- mergePairs.push({ a: i, b: j, similarity })
1546
- }
1547
- }
1548
- }
1549
-
1550
- if (mergePairs.length === 0) {
1551
- return { content: [{ type: "text" as const, text: "✅ No similar entries found to merge." }] }
1552
- }
1553
-
1554
- // Sort by similarity (highest first) and merge greedily
1555
- mergePairs.sort((x, y) => y.similarity - x.similarity)
1556
- const merged = new Set<number>()
1557
- const mergeActions: string[] = []
1558
-
1559
- for (const pair of mergePairs) {
1560
- if (merged.has(pair.a) || merged.has(pair.b)) continue
1561
- const a = parsed[pair.a], b = parsed[pair.b]
1562
-
1563
- // Merge: keep the entry with more content, combine tags
1564
- const mergedTags = [...new Set([...a.tags.split(";"), ...b.tags.split(";")])].filter(Boolean).join(";")
1565
- const longer = a.content.length >= b.content.length ? a : b
1566
- const shorter = a.content.length < b.content.length ? a : b
1567
- const newContent = longer.content
1568
- const newDate = a.date > b.date ? a.date : b.date
1569
- const newAccessed = a.accessed + b.accessed
1570
-
1571
- mergeActions.push(` [${longer.cat}] ${longer.key} ← ${shorter.key} (similarity: ${(pair.similarity * 100).toFixed(0)}%)`)
1572
-
1573
- if (!dryRun) {
1574
- // Update the longer entry with merged data
1575
- 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] || ""}`
1576
- // Replace in entries array
1577
- entries[entries.indexOf(longer.line)] = mergedLine
1578
- merged.add(pair.b)
1579
- }
1580
- }
1581
-
1582
- if (dryRun) {
1583
- // Detailed preview: show what each merge produces
1584
- const previewLines: string[] = [
1585
- `🔍 Dry run — ${mergePairs.length} merge candidate(s) found:`,
1586
- "",
1587
- ]
1588
- for (const pair of mergePairs) {
1589
- const a = parsed[pair.a], b = parsed[pair.b]
1590
- const mergedTags = [...new Set([...a.tags.split(";"), ...b.tags.split(";")])].filter(Boolean).join(";")
1591
- const longer = a.content.length >= b.content.length ? a : b
1592
- const shorter = a.content.length < b.content.length ? a : b
1593
- previewLines.push(` ── Pair: [${a.cat}] ${a.key} ↔ [${b.cat}] ${b.key}`)
1594
- previewLines.push(` Similarity: ${(pair.similarity * 100).toFixed(0)}%`)
1595
- previewLines.push(` A tags: ${a.tags || "(none)"}`)
1596
- previewLines.push(` B tags: ${b.tags || "(none)"}`)
1597
- previewLines.push(` → Merged tags: ${mergedTags || "(none)"}`)
1598
- previewLines.push(` → Content winner: "${longer.key}" (${longer.content.length} chars vs ${shorter.content.length})`)
1599
- previewLines.push(` → Result content: ${longer.content.slice(0, 120)}${longer.content.length > 120 ? "…" : ""}`)
1600
- previewLines.push("")
1601
- }
1602
- previewLines.push(`Would merge ${merged.size} entries into ${entries.length - merged.size} entries.`)
1603
- previewLines.push("Run with dryRun: false to apply.")
1604
- return {
1605
- content: [{
1606
- type: "text" as const,
1607
- text: previewLines.join("\n"),
1608
- }],
1609
- }
1610
- }
1611
-
1612
- // Remove merged entries and write back
1613
- const newLines = entries.filter((_, i) => !merged.has(i))
1614
- const headerIdx = newLines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
1615
- if (headerIdx !== -1) {
1616
- const count = newLines.filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")).length
1617
- newLines[headerIdx] = newLines[headerIdx].replace(/\[\d+\|/, `[${count}|`)
1618
- }
1619
- writeMemory(newLines.join("\n"))
1620
-
1621
- return {
1622
- content: [{
1623
- type: "text" as const,
1624
- text: `✅ Merged ${merged.size} entries into ${entries.length - merged.size} entries.\n\n${mergeActions.join("\n")}`
1625
- }],
1626
- }
1627
- }
1628
- )
1629
-
1630
1761
  // ── memory_graph_path ────────────────────────────────────────────────
1631
1762
 
1632
1763
  server.registerTool(
@@ -1749,7 +1880,7 @@ server.registerTool(
1749
1880
  const line = lines[i]
1750
1881
  if (!line.startsWith(" ") || !line.includes("|")) continue
1751
1882
  if (line.startsWith(" summaries:")) break
1752
- const parts = line.trim().split("|")
1883
+ const parts = parseToonLine(line)
1753
1884
  if (parts[2] === key) {
1754
1885
  existingIdx = i
1755
1886
  existingId = parts[0]
@@ -1759,13 +1890,13 @@ server.registerTool(
1759
1890
 
1760
1891
  if (existingIdx !== -1) {
1761
1892
  // Update existing checkpoint
1762
- const parts = lines[existingIdx].trim().split("|")
1893
+ const parts = parseToonLine(lines[existingIdx])
1763
1894
  parts[3] = content
1764
1895
  parts[6] = date
1765
1896
  parts[7] = ttl7d
1766
1897
  while (parts.length < 14) parts.push("")
1767
1898
  parts[13] = "0"
1768
- lines[existingIdx] = ` ${parts.join("|")}`
1899
+ lines[existingIdx] = toToonLine(parts)
1769
1900
  writeMemory(lines.join("\n"))
1770
1901
  return {
1771
1902
  content: [{ type: "text" as const, text: `📝 Checkpoint updated: ${key}\n⏰ TTL: ${ttl7d} (7d)\n${note ? `\n${note}` : ""}` }],
@@ -1775,11 +1906,11 @@ server.registerTool(
1775
1906
  // Create new checkpoint entry
1776
1907
  const newId = `cp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
1777
1908
  const quality = qualityScore("checkpoint", "", content, date)
1778
- 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"])
1779
1910
 
1780
1911
  const match = lines[headerIdx].match(/\[(\d+)\|/)
1781
1912
  const count = match ? parseInt(match[1]) : 0
1782
- lines.splice(headerIdx + 1, 0, ` ${newEntry}`)
1913
+ lines.splice(headerIdx + 1, 0, newEntry)
1783
1914
  lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`)
1784
1915
  writeMemory(lines.join("\n"))
1785
1916
 
@@ -1821,11 +1952,11 @@ server.registerTool(
1821
1952
  const line = lines[i]
1822
1953
  if (!line.startsWith(" ") || !line.includes("|")) continue
1823
1954
  if (line.startsWith(" summaries:")) break
1824
- const parts = line.trim().split("|")
1955
+ const parts = parseToonLine(line)
1825
1956
  if (parts[0] === key || parts[2] === key) {
1826
1957
  while (parts.length < 14) parts.push("")
1827
1958
  parts[13] = String(clampedPriority)
1828
- lines[i] = ` ${parts.join("|")}`
1959
+ lines[i] = toToonLine(parts)
1829
1960
  found = true
1830
1961
  break
1831
1962
  }
@@ -1866,11 +1997,11 @@ server.registerTool(
1866
1997
  const line = lines[i]
1867
1998
  if (!line.startsWith(" ") || !line.includes("|")) continue
1868
1999
  if (line.startsWith(" summaries:")) break
1869
- const parts = line.trim().split("|")
2000
+ const parts = parseToonLine(line)
1870
2001
  if (parts[0] === key || parts[2] === key) {
1871
2002
  if (parts.length > 13) {
1872
2003
  parts[13] = "0"
1873
- lines[i] = ` ${parts.join("|")}`
2004
+ lines[i] = toToonLine(parts)
1874
2005
  }
1875
2006
  found = true
1876
2007
  break
@@ -2008,7 +2139,7 @@ server.registerTool(
2008
2139
  const line = lines[i]
2009
2140
  if (!line.startsWith(" ") || !line.includes("|")) continue
2010
2141
  if (line.startsWith(" summaries:")) break
2011
- const parts = line.trim().split("|")
2142
+ const parts = parseToonLine(line)
2012
2143
  const entryId = parts[0]
2013
2144
  const entryKey = parts[2]
2014
2145
 
@@ -2026,7 +2157,7 @@ server.registerTool(
2026
2157
  }
2027
2158
 
2028
2159
  parts[5] = newTags.join(";")
2029
- lines[i] = ` ${parts.join("|")}`
2160
+ lines[i] = toToonLine(parts)
2030
2161
  modified++
2031
2162
  modifiedKeys.push(entryKey)
2032
2163
  }
@@ -2047,213 +2178,6 @@ server.registerTool(
2047
2178
  }
2048
2179
  )
2049
2180
 
2050
- // ── memory_resolve ───────────────────────────────────────────────────────────
2051
-
2052
- server.registerTool(
2053
- "memory_resolve",
2054
- {
2055
- title: "Resolve Entry",
2056
- description: "Restore an obsolete entry back to active status, or mark an entry as resolved. Reverses soft-delete.",
2057
- inputSchema: {
2058
- key: z.string().describe("Key or id of the entry to resolve/restore"),
2059
- },
2060
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
2061
- },
2062
- async ({ key }) => {
2063
- const data = readMemory()
2064
- const lines = data.split("\n")
2065
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
2066
-
2067
- if (headerIdx === -1) {
2068
- return { content: [{ type: "text" as const, text: "No entries in memory" }] }
2069
- }
2070
-
2071
- let found = false
2072
- let wasObsolete = false
2073
- for (let i = headerIdx + 1; i < lines.length; i++) {
2074
- const line = lines[i]
2075
- if (!line.startsWith(" ") || !line.includes("|")) continue
2076
- if (line.startsWith(" summaries:")) break
2077
- const parts = line.trim().split("|")
2078
- if (parts[0] === key || parts[2] === key) {
2079
- while (parts.length < 17) parts.push("")
2080
- wasObsolete = parts[16] === "obsolete"
2081
- parts[16] = "active"
2082
- lines[i] = ` ${parts.join("|")}`
2083
- found = true
2084
- break
2085
- }
2086
- }
2087
-
2088
- if (!found) {
2089
- return { content: [{ type: "text" as const, text: `"${key}" not found in memory.` }] }
2090
- }
2091
-
2092
- writeMemory(lines.join("\n"))
2093
-
2094
- const msg = wasObsolete ? `"${key}" restored to active status.` : `"${key}" marked as resolved.`
2095
- return { content: [{ type: "text" as const, text: `✅ ${msg}` }] }
2096
- }
2097
- )
2098
-
2099
- // ── memory_suppress ──────────────────────────────────────────────────────────
2100
-
2101
- server.registerTool(
2102
- "memory_suppress",
2103
- {
2104
- title: "Suppress Entry",
2105
- description: "Suppress a memory entry so it's hidden from normal recalls. Sets status to 'obsolete'. Use memory_resolve to restore.",
2106
- inputSchema: {
2107
- key: z.string().describe("Key or id of the entry to suppress"),
2108
- },
2109
- annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
2110
- },
2111
- async ({ key }) => {
2112
- const data = readMemory()
2113
- const lines = data.split("\n")
2114
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
2115
-
2116
- if (headerIdx === -1) {
2117
- return { content: [{ type: "text" as const, text: "No entries in memory" }] }
2118
- }
2119
-
2120
- let found = false
2121
- for (let i = headerIdx + 1; i < lines.length; i++) {
2122
- const line = lines[i]
2123
- if (!line.startsWith(" ") || !line.includes("|")) continue
2124
- if (line.startsWith(" summaries:")) break
2125
- const parts = line.trim().split("|")
2126
- if (parts[0] === key || parts[2] === key) {
2127
- while (parts.length < 17) parts.push("")
2128
- parts[16] = "obsolete"
2129
- lines[i] = ` ${parts.join("|")}`
2130
- found = true
2131
- break
2132
- }
2133
- }
2134
-
2135
- if (!found) {
2136
- return { content: [{ type: "text" as const, text: `"${key}" not found in memory.` }] }
2137
- }
2138
-
2139
- writeMemory(lines.join("\n"))
2140
- return { content: [{ type: "text" as const, text: `"${key}" suppressed. Use memory_resolve(key: "${key}") to restore.` }] }
2141
- }
2142
- )
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
2181
  // ── memory_reflect ───────────────────────────────────────────────────────────
2258
2182
 
2259
2183
  server.registerTool(
@@ -2387,7 +2311,7 @@ server.registerTool(
2387
2311
  // 6. Superseded-but-active (tag/link present but status not obsolete)
2388
2312
  const pending = entries.filter((e) => e.status === "active" && (e.tags.includes("superseded") || typedLinks(e.links).some((l) => l.type === "superseded_by")))
2389
2313
  if (pending.length > 0) {
2390
- sections.push("", "🔎 Superseded tag but still active (fix with memory_supersede):")
2314
+ sections.push("", "🔎 Superseded tag but still active (fix with memory_forget action: 'supersede'):")
2391
2315
  for (const e of pending.slice(0, cap)) {
2392
2316
  sections.push(` [${e.category}] ${e.key}`)
2393
2317
  }
@@ -2396,7 +2320,7 @@ server.registerTool(
2396
2320
  // 7. Drafts pending review
2397
2321
  const drafts = entries.filter((e) => e.status === "draft")
2398
2322
  if (drafts.length > 0) {
2399
- sections.push("", "📝 Drafts pending review (promote with memory_promote / memory_resolve):")
2323
+ sections.push("", "📝 Drafts pending review (promote with memory_promote / memory_forget action: 'restore'):")
2400
2324
  for (const e of drafts.slice(0, cap)) {
2401
2325
  sections.push(` [${e.category}] ${e.key} — ${e.content.slice(0, 70)}`)
2402
2326
  }
@@ -2524,9 +2448,9 @@ server.registerTool(
2524
2448
  if (status === "draft") tags.push("draft")
2525
2449
  const content = (o.summary || "").slice(0, 500)
2526
2450
  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}`
2451
+ const entry = toToonLine([newId, "knowledge", key, content, o.file || "", tags.join(";"), date, "", "0", "", quality.toFixed(2), conf.toFixed(2), date, "0", "", "inferred", status])
2528
2452
 
2529
- lines.splice(headerIdx + 1, 0, ` ${entry}`)
2453
+ lines.splice(headerIdx + 1, 0, entry)
2530
2454
  count++
2531
2455
  existingKeys.add(key)
2532
2456
  if (status === "draft") drafted++
@@ -2539,7 +2463,7 @@ server.registerTool(
2539
2463
  return {
2540
2464
  content: [{
2541
2465
  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.`
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.`
2543
2467
  }],
2544
2468
  }
2545
2469
  }