toon-memory 3.7.0 → 4.1.1

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/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "toon-memory",
3
3
  "mcpName": "io.github.LuiggiVal08/toon-memory",
4
- "version": "3.7.0",
5
- "description": "MCP server giving AI coding agents offline, token-efficient persistent memory — 40 tools, 80% fewer tool calls, recall decisions, patterns, and bugs across sessions. No LLM, no server; works with 15+ agents.",
4
+ "version": "4.1.1",
5
+ "description": "MCP server giving AI coding agents offline, token-efficient persistent memory — 35 tools, 80% fewer tool calls, recall decisions, patterns, and bugs across sessions. No LLM, no server; works with 15+ agents.",
6
6
  "type": "module",
7
7
  "bin": {
8
8
  "toon-memory": "./bin/toon-memory.js"
@@ -33,7 +33,8 @@
33
33
  "bench:rrf": "node scripts/bench-rrf.mjs",
34
34
  "capture:viewer": "node scripts/capture-viewer.mjs",
35
35
  "inspect": "npm run build && npx @modelcontextprotocol/inspector node bin/toon-memory.js mcp",
36
- "prepublishOnly": "npm run build && npm test"
36
+ "prepublishOnly": "npm run build && npm test",
37
+ "bench:retrieval": "node scripts/bench-retrieval.mjs"
37
38
  },
38
39
  "dependencies": {
39
40
  "@inquirer/prompts": "^8.5.2",
@@ -30,7 +30,7 @@ A persistent memory system for AI coding agents. It remembers decisions, pattern
30
30
  |------|-------------|
31
31
  | `memory_remember` | Save a decision, pattern, bug, or knowledge (with optional TTL and auto-tag inference) |
32
32
  | `memory_recall` | Search memory (use BEFORE reading files, filters expired TTL entries) |
33
- | `memory_forget` | Remove an entry by key or id |
33
+ | `memory_forget` | Lifecycle ops by key/id: `action: "soft"` (default) marks obsolete, `"hard"` deletes, `"restore"` reactivates, `"supersede"` retires with `superseded_by` link |
34
34
  | `memory_stats` | View memory state (including TTL stats) |
35
35
  | `memory_summary` | Save/retrieve file summaries |
36
36
  | `memory_archive` | Archive old entries and expired TTL entries |
@@ -38,7 +38,7 @@ A persistent memory system for AI coding agents. It remembers decisions, pattern
38
38
  | `memory_smart_recall` | Unified retrieval: BM25 + graph + decay + quality in one call (use at session start) |
39
39
  | `memory_suggest` | Find related entries for a given context |
40
40
  | `memory_captured` | Show activity log captured automatically by hooks |
41
- | `memory_consolidate` | Deduplicate identical entries (keeps first, deterministic, no LLM) |
41
+ | `memory_consolidate` | Cleanup: `mode: "identical"` (default) dedupes identical entries, `"similar"` merges near-duplicates, `"low-quality"` batch-removes low-quality entries |
42
42
  | `memory_sessions` | Show active agent sessions and detect file conflicts |
43
43
  | `context_brief` | One-call context briefing: memory + sessions + health in compact markdown |
44
44
  | `memory_encrypt` | Enable AES-256-GCM encryption |
@@ -50,12 +50,10 @@ A persistent memory system for AI coding agents. It remembers decisions, pattern
50
50
  | `context_health` | Memory health audit with score 0-100 |
51
51
  | `context_export` | Export memory as markdown for system prompts |
52
52
  | `memory_compress` | LLM-powered compression of selected entries |
53
- | `memory_compress_all` | Batch compression of low-quality entries |
54
53
  | `memory_primer` | Auto-generated knowledge map for session start |
55
54
  | `memory_merge_sessions` | Merge observations across parallel sessions |
56
55
  | `memory_export_gist` | Export memory to a private GitHub Gist |
57
56
  | `memory_import_gist` | Import memory from a GitHub Gist |
58
- | `memory_merge_similar` | Find and merge near-duplicates by Jaccard similarity |
59
57
  | `memory_graph_path` | BFS shortest path between two entries |
60
58
  | `memory_visualize` | Open interactive memory graph viewer |
61
59
  | `memory_pin` | Pin entry with priority 1-5 for top recall placement |
@@ -31,6 +31,7 @@ Commands:
31
31
  export [file] Export memory to a TOON/JSON file
32
32
  import <file> Import memory from a TOON/JSON file
33
33
  watch Watch memory file and re-render on change
34
+ viewer [--port <n>] Open the interactive graph viewer in a browser (auto-picks a free port)
34
35
  uninstall Remove toon-memory from all agents
35
36
  capture <on|off> Enable/disable activity capture hooks
36
37
  upgrade Upgrade to the latest version
@@ -4,6 +4,7 @@ import { createHash } from "crypto"
4
4
  import { withLockSync, atomicWrite } from "../lib/lock"
5
5
  import { heartbeat, endSession, resolveSessionId, currentBranch } from "../lib/sessions"
6
6
  import { pruneObservations } from "../mcp/observations"
7
+ import { parseToonLine } from "../lib/utils"
7
8
 
8
9
  /**
9
10
  * Hook capture script for toon-memory.
@@ -171,7 +172,7 @@ function main(): void {
171
172
  const data = readFileSync(OBSERVATIONS_FILE, "utf-8")
172
173
  for (const line of data.split("\n")) {
173
174
  if (!line.startsWith(" ")) continue
174
- const p = line.trim().split("|")
175
+ const p = parseToonLine(line)
175
176
  if (p[5] === hash) {
176
177
  const prev = new Date(p[0]).getTime()
177
178
  if (Date.now() - prev < DEDUP_WINDOW_MS) process.exit(0)
@@ -6,6 +6,7 @@ import type { Agent } from "./types"
6
6
  import { projectRoot, INSTRUCTION_CONTENT, ANTIGRAVITY_HOOK_NAME } from "./constants"
7
7
  import { detectAgents, resolvePackageJson } from "./agents"
8
8
  import { installMemoryDir, ensureGitignore, dumpMemoryMarkdown } from "./memory"
9
+ import { parseToonLine } from "../lib/utils"
9
10
  import { installMCPConfig, updateMemoryConfig } from "./config-writer"
10
11
  import { installInstructions } from "./instructions"
11
12
  import { installHooks, registerAntigravityHooks } from "./hooks"
@@ -340,7 +341,7 @@ export function stats(): void {
340
341
  let latestDate = ""
341
342
 
342
343
  for (const line of lines) {
343
- const parts = line.trim().split("|")
344
+ const parts = parseToonLine(line)
344
345
  if (parts.length >= 7) {
345
346
  const category = parts[1]
346
347
  const date = parts[6]
@@ -381,7 +382,7 @@ export function exportMemory(): void {
381
382
  const lines = data.split("\n").filter((l: string) => l.startsWith(" ") && l.includes("|"))
382
383
 
383
384
  const entries = lines.map((line: string) => {
384
- const parts = line.trim().split("|")
385
+ const parts = parseToonLine(line)
385
386
  return {
386
387
  id: parts[0],
387
388
  category: parts[1],
@@ -449,7 +450,7 @@ export function importMemory(): void {
449
450
  const existing = readFileSync(memoryFile, "utf-8")
450
451
  existingKeys = existing.split("\n")
451
452
  .filter((l: string) => l.startsWith(" ") && l.includes("|"))
452
- .map((l: string) => l.trim().split("|")[2])
453
+ .map((l: string) => parseToonLine(l)[2])
453
454
  }
454
455
 
455
456
  const newEntries = importData.entries.filter((e: any) => !existingKeys.includes(e.key))
package/src/cli/memory.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"
2
2
  import { join } from "path"
3
3
  import { MEMORY_DIR, projectRoot } from "./constants"
4
+ import { parseToonLine, unescField } from "../lib/utils"
4
5
 
5
6
  /**
6
7
  * Install memory directory and initial data file.
@@ -52,7 +53,7 @@ export function dumpMemoryMarkdown(): string {
52
53
  const lines = data.split("\n").filter((l: string) => l.startsWith(" ") && l.includes("|"))
53
54
 
54
55
  const entries = lines.map((line: string) => {
55
- const parts = line.trim().split("|")
56
+ const parts = parseToonLine(line)
56
57
  return {
57
58
  id: parts[0] ?? "",
58
59
  category: parts[1] ?? "",
@@ -72,7 +73,7 @@ export function dumpMemoryMarkdown(): string {
72
73
  if (!sl.includes(":") || !sl.startsWith(" ")) continue
73
74
  const idx = sl.indexOf(":")
74
75
  const file = sl.slice(0, idx).trim()
75
- const summary = sl.slice(idx + 1).trim()
76
+ const summary = unescField(sl.slice(idx + 1).trim())
76
77
  if (file && summary) summaries.push({ file, summary })
77
78
  }
78
79
  }
@@ -1,6 +1,7 @@
1
1
  import { readFileSync, existsSync } from "fs"
2
2
  import { join } from "path"
3
3
  import { heartbeat, coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS } from "../lib/sessions"
4
+ import { parseToonLine } from "../lib/utils"
4
5
 
5
6
  /**
6
7
  * SessionStart hook for toon-memory.
@@ -30,7 +31,7 @@ function systemPrimer(): string {
30
31
  // Parse entries and sort by importance (accessed + recency)
31
32
  const entries = lines
32
33
  .map((l) => {
33
- const p = l.trim().split("|")
34
+ const p = parseToonLine(l)
34
35
  if (p.length < 7) return null
35
36
  const accessed = p.length > 8 ? parseInt(p[8]) || 0 : 0
36
37
  const daysSince = (Date.now() - new Date(`${p[6]}T00:00:00`).getTime()) / 86400000
package/src/cli/setup.ts CHANGED
@@ -16,6 +16,10 @@ if (args[0] === "uninstall") {
16
16
  }
17
17
 
18
18
  if (args[0] === "init") {
19
+ if (args.includes("-h") || args.includes("--help")) {
20
+ printUsage()
21
+ process.exit(0)
22
+ }
19
23
  const rest = args.slice(1)
20
24
  const agentNames: string[] = []
21
25
  let scope: string | undefined
@@ -74,9 +78,19 @@ if (args[0] === "watch") {
74
78
  }
75
79
 
76
80
  if (args[0] === "viewer") {
81
+ if (args.includes("-h") || args.includes("--help")) {
82
+ printViewerUsage()
83
+ process.exit(0)
84
+ }
77
85
  const portIdx = args.indexOf("--port")
78
- const port = portIdx !== -1 && args[portIdx + 1] ? args[portIdx + 1] : undefined
86
+ if (portIdx !== -1 && !args[portIdx + 1]) {
87
+ console.error("Missing value for --port\n")
88
+ printViewerUsage()
89
+ process.exit(1)
90
+ }
91
+ const port = portIdx !== -1 ? args[portIdx + 1] : undefined
79
92
  if (args.includes("--export")) {
93
+ if (port) console.log("Note: --port is ignored with --export")
80
94
  viewerExport()
81
95
  } else {
82
96
  viewer(port)
@@ -90,6 +104,17 @@ if (args[0] === "viewer") {
90
104
  process.exit(1)
91
105
  }
92
106
 
107
+ /** Viewer-specific usage. */
108
+ function printViewerUsage(): void {
109
+ console.log(`Usage: toon-memory viewer [options]
110
+ Options:
111
+ --export Save a static HTML viewer to .toon-memory/viewer/index.html
112
+ --port <n> Port to serve on (default: 3000, or $PORT)
113
+ -h, --help Show this help
114
+
115
+ Press 'r' in the terminal while serving to reload the graph.`)
116
+ }
117
+
93
118
  /** Minimal usage string for unknown commands. */
94
119
  function printUsage(): void {
95
120
  console.log(`Usage: toon-memory <command> [options]
package/src/lib/graph.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  * without mutating the stored `.toon` file.
15
15
  */
16
16
 
17
- import { normalize, isExpiredLocal, tokenize, importance } from "./utils"
17
+ import { normalize, isExpiredLocal, tokenize, importance, parseToonLine } from "./utils"
18
18
  import { expandSynonyms } from "./synonyms"
19
19
  import { fuzzyMatch } from "./fuzzy"
20
20
 
@@ -40,7 +40,7 @@ export interface GraphEntry {
40
40
  origin: "human" | "agent" | "inferred"
41
41
  /** Lifecycle status. Obsolete/draft entries are filtered from normal recalls. */
42
42
  status: "active" | "obsolete" | "resolved" | "draft"
43
- /** ISO date when this entry was superseded (set by memory_supersede). Empty if never superseded. */
43
+ /** ISO date when this entry was superseded (set by memory_forget action=supersede). Empty if never superseded. */
44
44
  supersededOn: string
45
45
  }
46
46
 
@@ -101,7 +101,7 @@ const entryLines = (data: string): string[] =>
101
101
  export function parseEntries(data: string): GraphEntry[] {
102
102
  const out: GraphEntry[] = []
103
103
  for (const line of entryLines(data)) {
104
- const parts = line.trim().split("|")
104
+ const parts = parseToonLine(line)
105
105
  if (parts.length < 7) continue
106
106
  const [id, category, key, content, file, tags, date, ttl, accessedRaw, linksRaw] =
107
107
  parts
@@ -133,9 +133,26 @@ export function parseEntries(data: string): GraphEntry[] {
133
133
  return out
134
134
  }
135
135
 
136
+ /** Similarity used to attach orphans: shared tags dominate, then shared key
137
+ * tokens, then shared content tokens. Deterministic (tie-break by key). */
138
+ function orphanScore(a: GraphEntry, b: GraphEntry): number {
139
+ const aTags = new Set(a.tags)
140
+ let sharedTags = 0
141
+ for (const t of b.tags) if (aTags.has(t)) sharedTags++
142
+ const aKey = new Set(tokenize(a.key))
143
+ const bKey = new Set(tokenize(b.key))
144
+ let sharedKey = 0
145
+ for (const t of bKey) if (aKey.has(t)) sharedKey++
146
+ const aTok = new Set(tokenize(a.content))
147
+ let sharedContent = 0
148
+ for (const t of tokenize(b.content)) if (aTok.has(t)) sharedContent++
149
+ return sharedTags * 4 + sharedKey * 2 + sharedContent
150
+ }
151
+
136
152
  /**
137
153
  * Build the adjacency graph from explicit links and implicit `[[key]]` refs.
138
- * Edges are undirected and only connect keys that actually exist.
154
+ * Edges are undirected and only connect keys that actually exist. Nodes with
155
+ * zero edges are linked to their most similar entry so every node connects.
139
156
  */
140
157
  export function buildGraph(entries: GraphEntry[]): MemoryGraph {
141
158
  const byKey = new Map<string, GraphEntry>()
@@ -177,9 +194,83 @@ export function buildGraph(entries: GraphEntry[]): MemoryGraph {
177
194
 
178
195
  const adjacency = new Map<string, string[]>()
179
196
  for (const [k, v] of adj) adjacency.set(k, [...v])
197
+
198
+ // Guarantee connectivity: every entry gets at least one edge. Orphans are
199
+ // attached to their most similar entry so nothing floats alone in the graph.
200
+ const allKeys = [...byKey.keys()]
201
+ for (const key of allKeys) {
202
+ if (adj.has(key)) continue
203
+ let best = ""
204
+ let bestScore = -1
205
+ for (const other of allKeys) {
206
+ if (other === key) continue
207
+ const score = orphanScore(byKey.get(key)!, byKey.get(other)!)
208
+ if (best === "" || score > bestScore || (score === bestScore && other < best)) {
209
+ bestScore = score
210
+ best = other
211
+ }
212
+ }
213
+ if (best) link(key, best)
214
+ }
215
+ for (const [k, v] of adj) adjacency.set(k, [...v])
216
+
217
+ // Bridge any remaining islands into the largest component so the graph is
218
+ // one connected whole, not several self-connected clusters.
219
+ const comps = connectedComponents(adjacency)
220
+ if (comps.length > 1) {
221
+ let largest = comps[0]
222
+ for (const c of comps) if (c.length > largest.length) largest = c
223
+ const largestSet = new Set(largest)
224
+ for (const comp of comps) {
225
+ if (comp.length === largest.length && comp[0] === largest[0]) continue
226
+ let bestA = ""
227
+ let bestB = ""
228
+ let bestScore = -1
229
+ for (const a of comp) {
230
+ const ea = byKey.get(a)!
231
+ for (const b of largest) {
232
+ const score = orphanScore(ea, byKey.get(b)!)
233
+ if (
234
+ bestA === "" ||
235
+ score > bestScore ||
236
+ (score === bestScore && a + b < bestA + bestB)
237
+ ) {
238
+ bestScore = score
239
+ bestA = a
240
+ bestB = b
241
+ }
242
+ }
243
+ }
244
+ if (bestA) link(bestA, bestB)
245
+ }
246
+ for (const [k, v] of adj) adjacency.set(k, [...v])
247
+ }
180
248
  return { adjacency, byKey }
181
249
  }
182
250
 
251
+ function connectedComponents(adjacency: Map<string, string[]>): string[][] {
252
+ const comps: string[][] = []
253
+ const seen = new Set<string>()
254
+ for (const [start] of adjacency) {
255
+ if (seen.has(start)) continue
256
+ const comp: string[] = []
257
+ const stack = [start]
258
+ seen.add(start)
259
+ while (stack.length) {
260
+ const cur = stack.pop()!
261
+ comp.push(cur)
262
+ for (const next of adjacency.get(cur) || []) {
263
+ if (!seen.has(next)) {
264
+ seen.add(next)
265
+ stack.push(next)
266
+ }
267
+ }
268
+ }
269
+ comps.push(comp)
270
+ }
271
+ return comps
272
+ }
273
+
183
274
  export interface GraphRecallOpts {
184
275
  category?: string
185
276
  /** Semicolon-separated; entry must have ALL specified tags to match. */
@@ -199,6 +290,8 @@ export interface GraphRecallOpts {
199
290
  /** Temporal view (YYYY-MM-DD): include entries valid on that date.
200
291
  * Entries superseded AFTER `asOf` still count; entries created after `asOf` are excluded. */
201
292
  asOf?: string
293
+ /** Reference date (YYYY-MM-DD) for recency/decay/TTL scoring. Defaults to the wall clock. */
294
+ today?: string
202
295
  }
203
296
 
204
297
  /**
@@ -340,7 +433,7 @@ export function graphRecallDetailed(
340
433
  if (tagsFilter.length > 0 && !tagsFilter.every((t) => e.tags.includes(t))) continue
341
434
  if (from_date && e.date < from_date) continue
342
435
  if (to_date && e.date > to_date) continue
343
- if (e.ttl && isExpiredLocal(e.ttl)) continue
436
+ if (e.ttl && isExpiredLocal(e.ttl, opts.today)) continue
344
437
  if (opts.path_scope && e.path_scope && !globMatch(opts.path_scope, e.path_scope)) continue
345
438
  const text = normalize(
346
439
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
@@ -366,10 +459,10 @@ export function graphRecallDetailed(
366
459
  ...visibleEntries
367
460
  .sort((a, b) => {
368
461
  if (a.priority !== b.priority) return b.priority - a.priority
369
- return importance(b) - importance(a)
462
+ return importance(b, opts.today) - importance(a, opts.today)
370
463
  })
371
464
  .slice(0, opts.limit ?? 6)
372
- .map((e) => ({ e, s: importance(e) }))
465
+ .map((e) => ({ e, s: importance(e, opts.today) }))
373
466
  )
374
467
  } else {
375
468
  // BFS from all seeds, recording the shortest hop distance to each node.
@@ -407,7 +500,7 @@ export function graphRecallDetailed(
407
500
  const decay = Math.pow(DECAY, dist)
408
501
  let s = fused
409
502
  ? fused.get(k) || 0
410
- : (bm25.get(k) || 0) + W_CENT * (cent.get(k) || 0) + W_IMP * importance(e)
503
+ : (bm25.get(k) || 0) + W_CENT * (cent.get(k) || 0) + W_IMP * importance(e, opts.today)
411
504
  if (!fused && seedKeys.has(k)) s += SEED_BONUS
412
505
  if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
413
506
  const entryFile = e.file.split(":")[0]
@@ -18,7 +18,7 @@ import {
18
18
  rrfK,
19
19
  type GraphEntry,
20
20
  } from "./graph"
21
- import { normalize, isExpiredLocal, tokenize, importance, isPrivate } from "./utils"
21
+ import { normalize, isExpiredLocal, tokenize, importance, isPrivate, parseToonLine, toToonLine } from "./utils"
22
22
  import { expandSynonyms } from "./synonyms"
23
23
  import { fuzzyMatch } from "./fuzzy"
24
24
 
@@ -109,8 +109,8 @@ export function qualityScore(
109
109
  * quality. Returns the merged TOON entry line.
110
110
  */
111
111
  export function mergeEntries(existingLine: string, newLine: string): string {
112
- const ep = existingLine.trim().split("|")
113
- const np = newLine.trim().split("|")
112
+ const ep = parseToonLine(existingLine)
113
+ const np = parseToonLine(newLine)
114
114
  if (ep.length < 7 || np.length < 7) return newLine
115
115
 
116
116
  const id = ep[0]
@@ -178,7 +178,7 @@ export function mergeEntries(existingLine: string, newLine: string): string {
178
178
  // Preserve superseded_on (field 17) from the existing entry.
179
179
  const existingSupersededOn = ep.length > 17 ? ep[17] || "" : ""
180
180
 
181
- return `${id}|${category}|${key}|${content}|${file}|${mergedTags}|${date}|${ttl}|${accessed}|${mergedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}|${priority}|${path_scope}|${origin}|${status}|${existingSupersededOn}`
181
+ return toToonLine([id, category, key, content, file, mergedTags, date, ttl, String(accessed), mergedLinks, quality.toFixed(2), String(confidence), lastAccessed, String(priority), path_scope, origin, status, existingSupersededOn])
182
182
  }
183
183
 
184
184
  /**
@@ -188,7 +188,7 @@ export function mergeEntries(existingLine: string, newLine: string): string {
188
188
  export function generateSmartRecall(
189
189
  data: string,
190
190
  intent: string,
191
- opts: { limit?: number; category?: string; bumpAccess?: (ids: string[]) => void; fileMtimes?: Map<string, string>; sessionFiles?: string[]; rrf?: boolean } = {}
191
+ opts: { limit?: number; category?: string; bumpAccess?: (ids: string[]) => void; fileMtimes?: Map<string, string>; sessionFiles?: string[]; rrf?: boolean; today?: string } = {}
192
192
  ): string {
193
193
  const entries = parseEntries(data)
194
194
  if (entries.length === 0) return "Empty memory."
@@ -205,7 +205,7 @@ export function generateSmartRecall(
205
205
 
206
206
  const eligible = entries.filter((e) => {
207
207
  if (category && e.category !== category) return false
208
- if (e.ttl && isExpiredLocal(e.ttl)) return false
208
+ if (e.ttl && isExpiredLocal(e.ttl, opts.today)) return false
209
209
  if (e.status === "obsolete" || e.status === "draft") return false
210
210
  return true
211
211
  })
@@ -231,7 +231,7 @@ export function generateSmartRecall(
231
231
  const matchesQuery = exactMatch || fuzzy
232
232
  const bm25Score = bm25.get(e.key) || 0
233
233
  const centScore = cent.get(e.key) || 0
234
- const impScore = importance(e)
234
+ const impScore = importance(e, opts.today)
235
235
  // Drift penalty: if the linked file was modified after the entry was created
236
236
  let drift = 0
237
237
  if (mtimes && e.file) {
@@ -279,7 +279,7 @@ export function generateSmartRecall(
279
279
  const top = eligible
280
280
  .sort((a, b) => {
281
281
  if (a.priority !== b.priority) return b.priority - a.priority
282
- return importance(b) - importance(a)
282
+ return importance(b, opts.today) - importance(a, opts.today)
283
283
  })
284
284
  .slice(0, limit)
285
285
  if (top.length === 0) return "No entries in memory."
package/src/lib/utils.ts CHANGED
@@ -6,17 +6,18 @@
6
6
  export const normalize = (s: string): string =>
7
7
  s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
8
8
 
9
- export const isExpiredLocal = (ttl: string): boolean => {
9
+ export const isExpiredLocal = (ttl: string, today = new Date().toISOString().split("T")[0]): boolean => {
10
10
  if (!ttl) return false
11
- const today = new Date().toISOString().split("T")[0]
12
11
  return ttl <= today
13
12
  }
14
13
 
15
14
  /** Lightweight importance score: recency (60%) + frequency (40%). */
16
- export function importance(e: { date: string; accessed: number }): number {
17
- const today = new Date().toISOString().split("T")[0]
15
+ export function importance(
16
+ e: { date: string; accessed: number },
17
+ today = new Date().toISOString().split("T")[0]
18
+ ): number {
18
19
  const days =
19
- (Date.now() - new Date(`${e.date || today}T00:00:00`).getTime()) / 86400000
20
+ (Date.parse(`${today}T00:00:00`) - Date.parse(`${e.date || today}T00:00:00`)) / 86400000
20
21
  const recency = Math.min(1, Math.max(0, 30 - days) / 30)
21
22
  const freq = Math.min(1, e.accessed / 5)
22
23
  return recency * 0.6 + freq * 0.4
@@ -30,6 +31,81 @@ export const tokenize = (s: string): string[] =>
30
31
  .split(/\s+/)
31
32
  .filter(Boolean)
32
33
 
34
+ /**
35
+ * Escape a field for the pipe-delimited TOON format. Literal newlines, pipes and
36
+ * backslashes would otherwise break line-based parsing (a multi-line content turns
37
+ * each continuation line into a bogus entry), so they are stored as `\n`, `\|` and
38
+ * `\\` to keep the encoding reversible.
39
+ */
40
+ export const escField = (s: string): string => {
41
+ let out = ""
42
+ for (let i = 0; i < s.length; i++) {
43
+ const c = s[i]
44
+ if (c === "\\") out += "\\\\"
45
+ else if (c === "\n") out += "\\n"
46
+ else if (c === "\r") {
47
+ out += "\\n"
48
+ if (s[i + 1] === "\n") i++
49
+ } else if (c === "|") out += "\\|"
50
+ else out += c
51
+ }
52
+ return out
53
+ }
54
+
55
+ /** Inverse of `escField`: `\\n` -> newline, `\\|` -> pipe, `\\\\` -> backslash. */
56
+ export const unescField = (s: string): string => {
57
+ let out = ""
58
+ for (let i = 0; i < s.length; i++) {
59
+ const c = s[i]
60
+ if (c === "\\" && i + 1 < s.length) {
61
+ const n = s[i + 1]
62
+ if (n === "n") {
63
+ out += "\n"
64
+ i++
65
+ } else if (n === "|") {
66
+ out += "|"
67
+ i++
68
+ } else if (n === "\\") {
69
+ out += "\\"
70
+ i++
71
+ } else out += c
72
+ } else out += c
73
+ }
74
+ return out
75
+ }
76
+
77
+ /** Split a stored TOON line into unescaped fields (`\|` is not a delimiter). */
78
+ export const parseToonLine = (line: string): string[] => {
79
+ const parts: string[] = []
80
+ let cur = ""
81
+ let escaped = false
82
+ for (const c of line.trim()) {
83
+ if (escaped) {
84
+ cur += c
85
+ escaped = false
86
+ continue
87
+ }
88
+ if (c === "\\") {
89
+ cur += c
90
+ escaped = true
91
+ continue
92
+ }
93
+ if (c === "|") {
94
+ parts.push(unescField(cur))
95
+ cur = ""
96
+ continue
97
+ }
98
+ cur += c
99
+ }
100
+ if (escaped) cur += "\\"
101
+ parts.push(unescField(cur))
102
+ return parts
103
+ }
104
+
105
+ /** Serialize raw fields into a stored TOON line (escapes newlines, pipes, backslashes). */
106
+ export const toToonLine = (parts: string[]): string =>
107
+ ` ${parts.map(escField).join("|")}`
108
+
33
109
  /** Check if an entry is marked as private (excluded from context injection). */
34
110
  export const isPrivate = (e: { tags: string[] }): boolean =>
35
111
  e.tags.some((t) => t.toLowerCase() === "private")
@@ -4,6 +4,7 @@ import { readMemory, writeMemory, safeWrite } from "./memory-io"
4
4
  import { ensureMemoryFile, MEMORY_FILE, MEMORY_DIR, getMaxEntries, ARCHIVE_DAYS, ARCHIVE_FILE } from "./config"
5
5
  import { isExpired } from "./entries"
6
6
  import { entryScoreForLine } from "./scoring"
7
+ import { parseToonLine } from "../lib/utils"
7
8
 
8
9
  /**
9
10
  * Archive entries older than ARCHIVE_DAYS or with expired TTL.
@@ -26,7 +27,7 @@ export function archiveOldEntries(opts: { trimToMax?: boolean } = {}): { archive
26
27
  const toArchive = new Set<number>()
27
28
 
28
29
  entryLines.forEach((line, idx) => {
29
- const parts = line.trim().split("|")
30
+ const parts = parseToonLine(line)
30
31
  if (parts.length < 7) return
31
32
  const date = parts[6]
32
33
  const ttl = parts[7] || ""
@@ -108,7 +109,7 @@ export function pruneExpiredEntries(): number {
108
109
 
109
110
  const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
110
111
  const kept = entryLines.filter((l) => {
111
- const parts = l.trim().split("|")
112
+ const parts = parseToonLine(l)
112
113
  if (parts.length < 8) return true
113
114
  const ttl = parts[7] || ""
114
115
  if (ttl && isExpired(ttl)) {
@@ -1,5 +1,6 @@
1
1
  import { readMemory, writeMemory } from "./memory-io"
2
2
  import { mergeEntries } from "../lib/quality"
3
+ import { parseToonLine } from "../lib/utils"
3
4
 
4
5
  /**
5
6
  * Jaccard similarity between two content strings (0..1).
@@ -41,11 +42,11 @@ export function consolidateEntries(): { removed: number; kept: number; duplicate
41
42
 
42
43
  for (let i = 0; i < entryLines.length; i++) {
43
44
  const line = entryLines[i].trim()
44
- const parts = line.split("|")
45
+ const parts = parseToonLine(line)
45
46
  if (parts.length < 3) continue
46
47
  const key = parts[2]
47
48
  const existingIdx = keyOrder.findIndex((idx) => {
48
- const ep = entryLines[idx].trim().split("|")
49
+ const ep = parseToonLine(entryLines[idx])
49
50
  return ep[2] === key
50
51
  })
51
52
  if (existingIdx !== -1) {
@@ -65,7 +66,7 @@ export function consolidateEntries(): { removed: number; kept: number; duplicate
65
66
 
66
67
  for (const idx of keyOrder) {
67
68
  const line = byKey.get(idx)!
68
- const parts = line.split("|")
69
+ const parts = parseToonLine(line)
69
70
  if (parts.length < 3) {
70
71
  order.push(line)
71
72
  continue
@@ -82,7 +83,7 @@ export function consolidateEntries(): { removed: number; kept: number; duplicate
82
83
  // Check for near-duplicate (same category, similar content)
83
84
  let merged = false
84
85
  for (const [seenNorm, existing] of contentSeen) {
85
- const existingParts = existing.line.split("|")
86
+ const existingParts = parseToonLine(existing.line)
86
87
  if (existingParts[1] !== parts[1]) continue // different category
87
88
  const sim = contentSimilarity(content, existingParts[3] || "")
88
89
  if (sim >= NEAR_DUP_THRESHOLD) {
@@ -1,5 +1,6 @@
1
1
  import { readFileSync, existsSync, writeFileSync } from "fs"
2
2
  import { OBSERVATIONS_FILE } from "./config"
3
+ import { parseToonLine } from "../lib/utils"
3
4
 
4
5
  /** Maximum observations to keep in the log file */
5
6
  const MAX_OBSERVATIONS = 500
@@ -13,7 +14,7 @@ export function readObservations(): Array<{ ts: string; session: string; agent:
13
14
  .split("\n")
14
15
  .filter((l) => l.startsWith(" ") && l.includes("|"))
15
16
  .map((l) => {
16
- const p = l.trim().split("|")
17
+ const p = parseToonLine(l)
17
18
  return { ts: p[0] || "", session: p[1] || "", agent: p[2] || "", branch: p[3] || "", tool: p[4] || "", file: p[6] || "", summary: p[7] || "" }
18
19
  })
19
20
  }
@@ -3,6 +3,7 @@ import { registerAppResource } from "@modelcontextprotocol/ext-apps/server"
3
3
  import { createUIResource } from "@mcp-ui/server"
4
4
  import { readMemory } from "./memory-io"
5
5
  import { isExpired } from "./entries"
6
+ import { parseToonLine } from "../lib/utils"
6
7
  import { generateSystemPrimer } from "../lib/quality"
7
8
  import { buildViewerData } from "../viewer/data"
8
9
  import { generateHtml } from "../viewer/html"
@@ -29,7 +30,7 @@ export function registerResources(server: McpServer): void {
29
30
  const data = readMemory()
30
31
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
31
32
  const entries = lines.map((l) => {
32
- const parts = l.trim().split("|")
33
+ const parts = parseToonLine(l)
33
34
  return { category: parts[1] || "unknown", ttl: parts[7] || "" }
34
35
  })
35
36
  const byCategory: Record<string, number> = {}