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/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.6.1",
5
- "description": "MCP server giving AI coding agents offline, token-efficient persistent memory — 37 tools, 80% fewer tool calls, recall decisions, patterns, and bugs across sessions. No LLM, no server; works with 15+ agents.",
4
+ "version": "4.1.0",
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"
@@ -30,9 +30,11 @@
30
30
  "bench:full": "node scripts/bench-full-impact.mjs",
31
31
  "bench:compress-all": "node scripts/bench-compress-all.mjs",
32
32
  "bench:primer": "node scripts/bench-primer.mjs",
33
+ "bench:rrf": "node scripts/bench-rrf.mjs",
33
34
  "capture:viewer": "node scripts/capture-viewer.mjs",
34
35
  "inspect": "npm run build && npx @modelcontextprotocol/inspector node bin/toon-memory.js mcp",
35
- "prepublishOnly": "npm run build && npm test"
36
+ "prepublishOnly": "npm run build && npm test",
37
+ "bench:retrieval": "node scripts/bench-retrieval.mjs"
36
38
  },
37
39
  "dependencies": {
38
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 |
@@ -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/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
 
@@ -38,8 +38,45 @@ export interface GraphEntry {
38
38
  path_scope: string
39
39
  /** Who created this entry. */
40
40
  origin: "human" | "agent" | "inferred"
41
- /** Lifecycle status. Obsolete entries are filtered from normal recalls. */
42
- status: "active" | "obsolete" | "resolved"
41
+ /** Lifecycle status. Obsolete/draft entries are filtered from normal recalls. */
42
+ status: "active" | "obsolete" | "resolved" | "draft"
43
+ /** ISO date when this entry was superseded (set by memory_forget action=supersede). Empty if never superseded. */
44
+ supersededOn: string
45
+ }
46
+
47
+ /** Edge type labels used in typed links (`type:key`). */
48
+ export const EDGE_TYPES = ["related", "supersedes", "superseded_by", "implements", "blocks", "depends_on", "references", "applies_to"] as const
49
+
50
+ /** Default edge type when a link token has no `type:` prefix. */
51
+ export const DEFAULT_EDGE_TYPE = "related"
52
+
53
+ /**
54
+ * Parse a link token into its edge type and target key.
55
+ * Tolerant: a plain key (`risk-spec`) gets the default `related` type,
56
+ * while `type:key` (e.g. `supersedes:engine-arch`) carries its declared type.
57
+ * Keys are kebab-case and never contain colons, so the LAST `:` is the split point.
58
+ */
59
+ export function parseLinkToken(token: string): { type: string; key: string } {
60
+ const idx = token.lastIndexOf(":")
61
+ if (idx === -1) return { type: DEFAULT_EDGE_TYPE, key: token }
62
+ const type = token.slice(0, idx)
63
+ const key = token.slice(idx + 1)
64
+ return { type: type || DEFAULT_EDGE_TYPE, key: key || token }
65
+ }
66
+
67
+ /** Key part of a link token (strips any `type:` prefix). */
68
+ export function linkKey(token: string): string {
69
+ return parseLinkToken(token).key
70
+ }
71
+
72
+ /** Render a typed link token. Plain keys stay as-is (backward compatible). */
73
+ export function formatLink(type: string, key: string): string {
74
+ return type && type !== DEFAULT_EDGE_TYPE ? `${type}:${key}` : key
75
+ }
76
+
77
+ /** Expand raw link tokens into typed edges. */
78
+ export function typedLinks(links: string[]): Array<{ type: string; key: string }> {
79
+ return links.map(parseLinkToken)
43
80
  }
44
81
 
45
82
  export interface MemoryGraph {
@@ -64,7 +101,7 @@ const entryLines = (data: string): string[] =>
64
101
  export function parseEntries(data: string): GraphEntry[] {
65
102
  const out: GraphEntry[] = []
66
103
  for (const line of entryLines(data)) {
67
- const parts = line.trim().split("|")
104
+ const parts = parseToonLine(line)
68
105
  if (parts.length < 7) continue
69
106
  const [id, category, key, content, file, tags, date, ttl, accessedRaw, linksRaw] =
70
107
  parts
@@ -89,15 +126,33 @@ export function parseEntries(data: string): GraphEntry[] {
89
126
  priority: parts.length > 13 ? parseInt(parts[13]) || 0 : 0,
90
127
  path_scope: parts.length > 14 ? parts[14] || "" : "",
91
128
  origin: parts.length > 15 && parts[15] ? parts[15] as "human" | "agent" | "inferred" : "agent",
92
- status: parts.length > 16 && parts[16] ? parts[16] as "active" | "obsolete" | "resolved" : "active",
129
+ status: parts.length > 16 && parts[16] ? parts[16] as "active" | "obsolete" | "resolved" | "draft" : "active",
130
+ supersededOn: parts.length > 17 ? parts[17] || "" : "",
93
131
  })
94
132
  }
95
133
  return out
96
134
  }
97
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
+
98
152
  /**
99
153
  * Build the adjacency graph from explicit links and implicit `[[key]]` refs.
100
- * 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.
101
156
  */
102
157
  export function buildGraph(entries: GraphEntry[]): MemoryGraph {
103
158
  const byKey = new Map<string, GraphEntry>()
@@ -116,7 +171,7 @@ export function buildGraph(entries: GraphEntry[]): MemoryGraph {
116
171
  }
117
172
 
118
173
  for (const e of entries) {
119
- for (const l of e.links) link(e.key, l)
174
+ for (const l of e.links) link(e.key, linkKey(l))
120
175
  const refs = e.content.match(/\[\[([\w-]+)\]\]/g) || []
121
176
  for (const r of refs) link(e.key, r.slice(2, -2))
122
177
  }
@@ -139,9 +194,83 @@ export function buildGraph(entries: GraphEntry[]): MemoryGraph {
139
194
 
140
195
  const adjacency = new Map<string, string[]>()
141
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
+ }
142
248
  return { adjacency, byKey }
143
249
  }
144
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
+
145
274
  export interface GraphRecallOpts {
146
275
  category?: string
147
276
  /** Semicolon-separated; entry must have ALL specified tags to match. */
@@ -156,6 +285,46 @@ export interface GraphRecallOpts {
156
285
  sessionFiles?: string[]
157
286
  /** Path scope glob filter: only return entries whose path_scope matches. */
158
287
  path_scope?: string
288
+ /** Use Reciprocal Rank Fusion instead of weighted linear scoring. */
289
+ rrf?: boolean
290
+ /** Temporal view (YYYY-MM-DD): include entries valid on that date.
291
+ * Entries superseded AFTER `asOf` still count; entries created after `asOf` are excluded. */
292
+ asOf?: string
293
+ /** Reference date (YYYY-MM-DD) for recency/decay/TTL scoring. Defaults to the wall clock. */
294
+ today?: string
295
+ }
296
+
297
+ /**
298
+ * Reciprocal Rank Fusion of several rankers (BM25 fused multiple times, centrality).
299
+ * k is the RRF smoothing constant. Ranks are 0-based.
300
+ */
301
+ export function rrfFuse(rankers: Array<Map<string, number>>, k = 60): Map<string, number> {
302
+ const out = new Map<string, number>()
303
+ for (const ranker of rankers) {
304
+ for (const [key, rank] of ranker) {
305
+ out.set(key, (out.get(key) || 0) + 1 / (k + rank))
306
+ }
307
+ }
308
+ return out
309
+ }
310
+
311
+ /**
312
+ * Adaptive RRF smoothing constant. The textbook k=60 is tuned for large candidate
313
+ * sets from independent retrievers; on a small memory graph it flattens every rank
314
+ * into a narrow score band. Scaling with sqrt(candidateCount) keeps the top ranks
315
+ * distinguishable while remaining stable as memory grows.
316
+ */
317
+ export function rrfK(candidateCount: number): number {
318
+ return Math.max(3, Math.min(60, Math.round(Math.sqrt(candidateCount))))
319
+ }
320
+
321
+ /** Build a 0-based rank map from a score map (higher score = lower rank). */
322
+ export function rankBy(score: Map<string, number>): Map<string, number> {
323
+ const out = new Map<string, number>()
324
+ ;[...score.entries()]
325
+ .sort((a, b) => b[1] - a[1])
326
+ .forEach(([key], i) => out.set(key, i))
327
+ return out
159
328
  }
160
329
 
161
330
  /**
@@ -253,13 +422,18 @@ export function graphRecallDetailed(
253
422
  const cent = centrality(adjacency)
254
423
 
255
424
  const seedKeys = new Set<string>()
425
+ const asOf = opts.asOf || ""
256
426
  for (const e of entries) {
257
- if (e.status === "obsolete") continue
427
+ if (e.status === "obsolete" || e.status === "draft") {
428
+ // Temporal view: a superseded entry was still valid until its supersededOn date.
429
+ if (!(asOf && e.status === "obsolete" && e.supersededOn && e.supersededOn > asOf)) continue
430
+ }
431
+ if (asOf && e.date && e.date > asOf) continue
258
432
  if (category && e.category !== category) continue
259
433
  if (tagsFilter.length > 0 && !tagsFilter.every((t) => e.tags.includes(t))) continue
260
434
  if (from_date && e.date < from_date) continue
261
435
  if (to_date && e.date > to_date) continue
262
- if (e.ttl && isExpiredLocal(e.ttl)) continue
436
+ if (e.ttl && isExpiredLocal(e.ttl, opts.today)) continue
263
437
  if (opts.path_scope && e.path_scope && !globMatch(opts.path_scope, e.path_scope)) continue
264
438
  const text = normalize(
265
439
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
@@ -273,16 +447,22 @@ export function graphRecallDetailed(
273
447
 
274
448
  let selected: GraphEntry[]
275
449
  const scored: Array<{ e: GraphEntry; s: number }> = []
450
+ const visibleEntries = entries.filter((e) => {
451
+ if (e.status === "obsolete" || e.status === "draft") {
452
+ return !!(asOf && e.status === "obsolete" && e.supersededOn && e.supersededOn > asOf)
453
+ }
454
+ return !(asOf && e.date && e.date > asOf)
455
+ })
456
+ const isVisible = new Set(visibleEntries.map((e) => e.key))
276
457
  if (seedKeys.size === 0) {
277
458
  scored.push(
278
- ...[...entries]
279
- .filter((e) => e.status !== "obsolete")
459
+ ...visibleEntries
280
460
  .sort((a, b) => {
281
461
  if (a.priority !== b.priority) return b.priority - a.priority
282
- return importance(b) - importance(a)
462
+ return importance(b, opts.today) - importance(a, opts.today)
283
463
  })
284
464
  .slice(0, opts.limit ?? 6)
285
- .map((e) => ({ e, s: importance(e) }))
465
+ .map((e) => ({ e, s: importance(e, opts.today) }))
286
466
  )
287
467
  } else {
288
468
  // BFS from all seeds, recording the shortest hop distance to each node.
@@ -295,18 +475,33 @@ export function graphRecallDetailed(
295
475
  best.set(key, dist)
296
476
  if (dist >= hops) continue
297
477
  for (const nb of adjacency.get(key) || []) {
478
+ if (!isVisible.has(nb)) continue
298
479
  queue.push({ key: nb, dist: dist + 1 })
299
480
  }
300
481
  }
301
482
 
483
+ // RRF mode: fuse per-signal rankers instead of the weighted linear score.
484
+ // BM25 (the only real retriever on a small memory graph) is fused three times;
485
+ // centrality contributes once as the graph signal. Importance is dropped from
486
+ // the fusion — on small graphs its rank is dominated by recency noise and
487
+ // including it drags nDCG down (validated on scripts/bench-rrf.mjs). k is
488
+ // adaptive: the textbook k=60 flattens rank differences on small graphs, so it
489
+ // scales with sqrt(candidate count).
490
+ const sub = (m: Map<string, number>) => new Map([...m].filter(([k]) => isVisible.has(k)))
491
+ const bm25Rank = rankBy(sub(bm25))
492
+ const centRank = rankBy(sub(cent))
493
+ const fused = opts.rrf ? rrfFuse([bm25Rank, bm25Rank, bm25Rank, centRank], rrfK(bm25Rank.size)) : null
494
+
302
495
  scored.push(
303
496
  ...[...best.keys()]
304
497
  .map((k) => {
305
498
  const e = byKey.get(k)!
306
499
  const dist = best.get(k)!
307
500
  const decay = Math.pow(DECAY, dist)
308
- let s = (bm25.get(k) || 0) + W_CENT * cent.get(k)! + W_IMP * importance(e)
309
- if (seedKeys.has(k)) s += SEED_BONUS
501
+ let s = fused
502
+ ? fused.get(k) || 0
503
+ : (bm25.get(k) || 0) + W_CENT * (cent.get(k) || 0) + W_IMP * importance(e, opts.today)
504
+ if (!fused && seedKeys.has(k)) s += SEED_BONUS
310
505
  if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
311
506
  const entryFile = e.file.split(":")[0]
312
507
  if (opts.sessionFiles.some((f) => f === entryFile)) {
@@ -327,7 +522,7 @@ export function graphRecallDetailed(
327
522
  selected = scored.map((x) => x.e)
328
523
 
329
524
  // Inject pinned entries that aren't already in the result set, sorted by priority desc.
330
- const pinnedKeys = new Set(entries.filter((e) => e.priority > 0 && e.status !== "obsolete").map((e) => e.key))
525
+ const pinnedKeys = new Set(visibleEntries.filter((e) => e.priority > 0).map((e) => e.key))
331
526
  const inResult = new Set(selected.map((e) => e.key))
332
527
  const toInject = [...pinnedKeys]
333
528
  .filter((k) => !inResult.has(k) && byKey.has(k))
@@ -440,7 +635,8 @@ export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {
440
635
  const originInfo = e.origin !== "agent" ? ` · origin: ${e.origin}` : ""
441
636
  const scopeInfo = e.path_scope ? ` · scope: ${e.path_scope}` : ""
442
637
  const statusInfo = e.status !== "active" ? ` · status: ${e.status}` : ""
443
- return `[${n}] ${e.category}/${e.key}${pin} (${e.id})\n ${e.content}\n File: ${e.file} | Tags: ${e.tags.join(";")} | Date: ${e.date}${ttlInfo}${accessInfo}${lastAccess}${originInfo}${scopeInfo}${statusInfo}${links}`
638
+ const supersededInfo = e.supersededOn ? ` · superseded: ${e.supersededOn}` : ""
639
+ return `[${n}] ${e.category}/${e.key}${pin} (${e.id})\n ${e.content}\n File: ${e.file} | Tags: ${e.tags.join(";")} | Date: ${e.date}${ttlInfo}${accessInfo}${lastAccess}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}${links}`
444
640
  }
445
641
 
446
642
  // "normal" budget (default)
@@ -7,8 +7,18 @@
7
7
  * primer (auto-generated knowledge map).
8
8
  */
9
9
 
10
- import { parseEntries, buildGraph, bm25Scores, centrality, renderCompact, type GraphEntry } from "./graph"
11
- import { normalize, isExpiredLocal, tokenize, importance, isPrivate } from "./utils"
10
+ import {
11
+ parseEntries,
12
+ buildGraph,
13
+ bm25Scores,
14
+ centrality,
15
+ renderCompact,
16
+ rankBy,
17
+ rrfFuse,
18
+ rrfK,
19
+ type GraphEntry,
20
+ } from "./graph"
21
+ import { normalize, isExpiredLocal, tokenize, importance, isPrivate, parseToonLine, toToonLine } from "./utils"
12
22
  import { expandSynonyms } from "./synonyms"
13
23
  import { fuzzyMatch } from "./fuzzy"
14
24
 
@@ -99,8 +109,8 @@ export function qualityScore(
99
109
  * quality. Returns the merged TOON entry line.
100
110
  */
101
111
  export function mergeEntries(existingLine: string, newLine: string): string {
102
- const ep = existingLine.trim().split("|")
103
- const np = newLine.trim().split("|")
112
+ const ep = parseToonLine(existingLine)
113
+ const np = parseToonLine(newLine)
104
114
  if (ep.length < 7 || np.length < 7) return newLine
105
115
 
106
116
  const id = ep[0]
@@ -165,7 +175,10 @@ export function mergeEntries(existingLine: string, newLine: string): string {
165
175
  const newStatus = np.length > 16 ? np[16] || "" : ""
166
176
  const status = newStatus === "active" || existingStatus === "active" ? "active" : newStatus || existingStatus || "active"
167
177
 
168
- return `${id}|${category}|${key}|${content}|${file}|${mergedTags}|${date}|${ttl}|${accessed}|${mergedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}|${priority}|${path_scope}|${origin}|${status}`
178
+ // Preserve superseded_on (field 17) from the existing entry.
179
+ const existingSupersededOn = ep.length > 17 ? ep[17] || "" : ""
180
+
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])
169
182
  }
170
183
 
171
184
  /**
@@ -175,7 +188,7 @@ export function mergeEntries(existingLine: string, newLine: string): string {
175
188
  export function generateSmartRecall(
176
189
  data: string,
177
190
  intent: string,
178
- opts: { limit?: number; category?: string; bumpAccess?: (ids: string[]) => void; fileMtimes?: Map<string, string>; sessionFiles?: string[] } = {}
191
+ opts: { limit?: number; category?: string; bumpAccess?: (ids: string[]) => void; fileMtimes?: Map<string, string>; sessionFiles?: string[]; rrf?: boolean; today?: string } = {}
179
192
  ): string {
180
193
  const entries = parseEntries(data)
181
194
  if (entries.length === 0) return "Empty memory."
@@ -190,12 +203,24 @@ export function generateSmartRecall(
190
203
  const qTokens = tokenize(intent)
191
204
  const expandedTokens = expandSynonyms(qTokens)
192
205
 
193
- const scored = entries
194
- .filter((e) => {
195
- if (category && e.category !== category) return false
196
- if (e.ttl && isExpiredLocal(e.ttl)) return false
197
- return true
198
- })
206
+ const eligible = entries.filter((e) => {
207
+ if (category && e.category !== category) return false
208
+ if (e.ttl && isExpiredLocal(e.ttl, opts.today)) return false
209
+ if (e.status === "obsolete" || e.status === "draft") return false
210
+ return true
211
+ })
212
+
213
+ // RRF mode: fuse per-signal rankers instead of the weighted linear score.
214
+ // BM25 (the only real retriever on a small memory graph) is fused three times;
215
+ // centrality contributes once as the graph signal. Importance is dropped from the
216
+ // fusion (recency-dominated noise on small graphs; validated on scripts/bench-rrf.mjs).
217
+ // k is adaptive (sqrt of candidate count) — the textbook k=60 flattens rank
218
+ // differences on small memory graphs.
219
+ const bm25Rank = rankBy(new Map([...bm25].filter(([k]) => eligible.some((e) => e.key === k))))
220
+ const centRank = rankBy(new Map([...cent].filter(([k]) => eligible.some((e) => e.key === k))))
221
+ const fused = opts.rrf ? rrfFuse([bm25Rank, bm25Rank, bm25Rank, centRank], rrfK(bm25Rank.size)) : null
222
+
223
+ const scored = eligible
199
224
  .map((e) => {
200
225
  const text = normalize(
201
226
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
@@ -206,7 +231,7 @@ export function generateSmartRecall(
206
231
  const matchesQuery = exactMatch || fuzzy
207
232
  const bm25Score = bm25.get(e.key) || 0
208
233
  const centScore = cent.get(e.key) || 0
209
- const impScore = importance(e)
234
+ const impScore = importance(e, opts.today)
210
235
  // Drift penalty: if the linked file was modified after the entry was created
211
236
  let drift = 0
212
237
  if (mtimes && e.file) {
@@ -222,8 +247,13 @@ export function generateSmartRecall(
222
247
  sessionBias = 0.15
223
248
  }
224
249
  }
225
- const combined =
226
- bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias
250
+ let combined: number
251
+ if (opts.rrf) {
252
+ combined = (fused?.get(e.key) ?? 0) - drift + sessionBias
253
+ } else {
254
+ combined =
255
+ bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias
256
+ }
227
257
  return { entry: e, score: combined, matchesQuery, priority: e.priority }
228
258
  })
229
259
  .filter((x) => x.score > 0 || x.matchesQuery)
@@ -234,11 +264,11 @@ export function generateSmartRecall(
234
264
  .slice(0, limit)
235
265
 
236
266
  // Inject pinned entries not already in the result set, sorted by priority desc.
237
- const pinnedKeys = new Set(entries.filter((e) => e.priority > 0).map((e) => e.key))
267
+ const pinnedKeys = new Set(eligible.filter((e) => e.priority > 0).map((e) => e.key))
238
268
  const inResult = new Set(scored.map((x) => x.entry.key))
239
269
  const toInject = [...pinnedKeys]
240
270
  .filter((k) => !inResult.has(k))
241
- .map((k) => entries.find((en) => en.key === k)!)
271
+ .map((k) => eligible.find((en) => en.key === k)!)
242
272
  .filter(Boolean)
243
273
  .sort((a, b) => b.priority - a.priority)
244
274
  for (const e of toInject) {
@@ -246,11 +276,10 @@ export function generateSmartRecall(
246
276
  }
247
277
 
248
278
  if (scored.length === 0) {
249
- const top = entries
250
- .filter((e) => !category || e.category === category)
279
+ const top = eligible
251
280
  .sort((a, b) => {
252
281
  if (a.priority !== b.priority) return b.priority - a.priority
253
- return importance(b) - importance(a)
282
+ return importance(b, opts.today) - importance(a, opts.today)
254
283
  })
255
284
  .slice(0, limit)
256
285
  if (top.length === 0) return "No entries in memory."