toon-memory 3.6.1 → 3.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -3
- package/dist/cli/setup.js +14 -2
- package/mcp/server.js +527 -65
- package/package.json +3 -2
- package/src/lib/graph.ts +114 -11
- package/src/lib/quality.ts +44 -15
- package/src/mcp/tools.ts +458 -8
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.
|
|
5
|
-
"description": "MCP server giving AI coding agents offline, token-efficient persistent 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.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"bin": {
|
|
8
8
|
"toon-memory": "./bin/toon-memory.js"
|
|
@@ -30,6 +30,7 @@
|
|
|
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
36
|
"prepublishOnly": "npm run build && npm test"
|
package/src/lib/graph.ts
CHANGED
|
@@ -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_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 {
|
|
@@ -89,7 +126,8 @@ 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
|
|
@@ -116,7 +154,7 @@ export function buildGraph(entries: GraphEntry[]): MemoryGraph {
|
|
|
116
154
|
}
|
|
117
155
|
|
|
118
156
|
for (const e of entries) {
|
|
119
|
-
for (const l of e.links) link(e.key, l)
|
|
157
|
+
for (const l of e.links) link(e.key, linkKey(l))
|
|
120
158
|
const refs = e.content.match(/\[\[([\w-]+)\]\]/g) || []
|
|
121
159
|
for (const r of refs) link(e.key, r.slice(2, -2))
|
|
122
160
|
}
|
|
@@ -156,6 +194,44 @@ export interface GraphRecallOpts {
|
|
|
156
194
|
sessionFiles?: string[]
|
|
157
195
|
/** Path scope glob filter: only return entries whose path_scope matches. */
|
|
158
196
|
path_scope?: string
|
|
197
|
+
/** Use Reciprocal Rank Fusion instead of weighted linear scoring. */
|
|
198
|
+
rrf?: boolean
|
|
199
|
+
/** Temporal view (YYYY-MM-DD): include entries valid on that date.
|
|
200
|
+
* Entries superseded AFTER `asOf` still count; entries created after `asOf` are excluded. */
|
|
201
|
+
asOf?: string
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Reciprocal Rank Fusion of several rankers (BM25 fused multiple times, centrality).
|
|
206
|
+
* k is the RRF smoothing constant. Ranks are 0-based.
|
|
207
|
+
*/
|
|
208
|
+
export function rrfFuse(rankers: Array<Map<string, number>>, k = 60): Map<string, number> {
|
|
209
|
+
const out = new Map<string, number>()
|
|
210
|
+
for (const ranker of rankers) {
|
|
211
|
+
for (const [key, rank] of ranker) {
|
|
212
|
+
out.set(key, (out.get(key) || 0) + 1 / (k + rank))
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return out
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Adaptive RRF smoothing constant. The textbook k=60 is tuned for large candidate
|
|
220
|
+
* sets from independent retrievers; on a small memory graph it flattens every rank
|
|
221
|
+
* into a narrow score band. Scaling with sqrt(candidateCount) keeps the top ranks
|
|
222
|
+
* distinguishable while remaining stable as memory grows.
|
|
223
|
+
*/
|
|
224
|
+
export function rrfK(candidateCount: number): number {
|
|
225
|
+
return Math.max(3, Math.min(60, Math.round(Math.sqrt(candidateCount))))
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Build a 0-based rank map from a score map (higher score = lower rank). */
|
|
229
|
+
export function rankBy(score: Map<string, number>): Map<string, number> {
|
|
230
|
+
const out = new Map<string, number>()
|
|
231
|
+
;[...score.entries()]
|
|
232
|
+
.sort((a, b) => b[1] - a[1])
|
|
233
|
+
.forEach(([key], i) => out.set(key, i))
|
|
234
|
+
return out
|
|
159
235
|
}
|
|
160
236
|
|
|
161
237
|
/**
|
|
@@ -253,8 +329,13 @@ export function graphRecallDetailed(
|
|
|
253
329
|
const cent = centrality(adjacency)
|
|
254
330
|
|
|
255
331
|
const seedKeys = new Set<string>()
|
|
332
|
+
const asOf = opts.asOf || ""
|
|
256
333
|
for (const e of entries) {
|
|
257
|
-
if (e.status === "obsolete")
|
|
334
|
+
if (e.status === "obsolete" || e.status === "draft") {
|
|
335
|
+
// Temporal view: a superseded entry was still valid until its supersededOn date.
|
|
336
|
+
if (!(asOf && e.status === "obsolete" && e.supersededOn && e.supersededOn > asOf)) continue
|
|
337
|
+
}
|
|
338
|
+
if (asOf && e.date && e.date > asOf) continue
|
|
258
339
|
if (category && e.category !== category) continue
|
|
259
340
|
if (tagsFilter.length > 0 && !tagsFilter.every((t) => e.tags.includes(t))) continue
|
|
260
341
|
if (from_date && e.date < from_date) continue
|
|
@@ -273,10 +354,16 @@ export function graphRecallDetailed(
|
|
|
273
354
|
|
|
274
355
|
let selected: GraphEntry[]
|
|
275
356
|
const scored: Array<{ e: GraphEntry; s: number }> = []
|
|
357
|
+
const visibleEntries = entries.filter((e) => {
|
|
358
|
+
if (e.status === "obsolete" || e.status === "draft") {
|
|
359
|
+
return !!(asOf && e.status === "obsolete" && e.supersededOn && e.supersededOn > asOf)
|
|
360
|
+
}
|
|
361
|
+
return !(asOf && e.date && e.date > asOf)
|
|
362
|
+
})
|
|
363
|
+
const isVisible = new Set(visibleEntries.map((e) => e.key))
|
|
276
364
|
if (seedKeys.size === 0) {
|
|
277
365
|
scored.push(
|
|
278
|
-
...
|
|
279
|
-
.filter((e) => e.status !== "obsolete")
|
|
366
|
+
...visibleEntries
|
|
280
367
|
.sort((a, b) => {
|
|
281
368
|
if (a.priority !== b.priority) return b.priority - a.priority
|
|
282
369
|
return importance(b) - importance(a)
|
|
@@ -295,18 +382,33 @@ export function graphRecallDetailed(
|
|
|
295
382
|
best.set(key, dist)
|
|
296
383
|
if (dist >= hops) continue
|
|
297
384
|
for (const nb of adjacency.get(key) || []) {
|
|
385
|
+
if (!isVisible.has(nb)) continue
|
|
298
386
|
queue.push({ key: nb, dist: dist + 1 })
|
|
299
387
|
}
|
|
300
388
|
}
|
|
301
389
|
|
|
390
|
+
// RRF mode: fuse per-signal rankers instead of the weighted linear score.
|
|
391
|
+
// BM25 (the only real retriever on a small memory graph) is fused three times;
|
|
392
|
+
// centrality contributes once as the graph signal. Importance is dropped from
|
|
393
|
+
// the fusion — on small graphs its rank is dominated by recency noise and
|
|
394
|
+
// including it drags nDCG down (validated on scripts/bench-rrf.mjs). k is
|
|
395
|
+
// adaptive: the textbook k=60 flattens rank differences on small graphs, so it
|
|
396
|
+
// scales with sqrt(candidate count).
|
|
397
|
+
const sub = (m: Map<string, number>) => new Map([...m].filter(([k]) => isVisible.has(k)))
|
|
398
|
+
const bm25Rank = rankBy(sub(bm25))
|
|
399
|
+
const centRank = rankBy(sub(cent))
|
|
400
|
+
const fused = opts.rrf ? rrfFuse([bm25Rank, bm25Rank, bm25Rank, centRank], rrfK(bm25Rank.size)) : null
|
|
401
|
+
|
|
302
402
|
scored.push(
|
|
303
403
|
...[...best.keys()]
|
|
304
404
|
.map((k) => {
|
|
305
405
|
const e = byKey.get(k)!
|
|
306
406
|
const dist = best.get(k)!
|
|
307
407
|
const decay = Math.pow(DECAY, dist)
|
|
308
|
-
let s =
|
|
309
|
-
|
|
408
|
+
let s = fused
|
|
409
|
+
? fused.get(k) || 0
|
|
410
|
+
: (bm25.get(k) || 0) + W_CENT * (cent.get(k) || 0) + W_IMP * importance(e)
|
|
411
|
+
if (!fused && seedKeys.has(k)) s += SEED_BONUS
|
|
310
412
|
if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
|
|
311
413
|
const entryFile = e.file.split(":")[0]
|
|
312
414
|
if (opts.sessionFiles.some((f) => f === entryFile)) {
|
|
@@ -327,7 +429,7 @@ export function graphRecallDetailed(
|
|
|
327
429
|
selected = scored.map((x) => x.e)
|
|
328
430
|
|
|
329
431
|
// Inject pinned entries that aren't already in the result set, sorted by priority desc.
|
|
330
|
-
const pinnedKeys = new Set(
|
|
432
|
+
const pinnedKeys = new Set(visibleEntries.filter((e) => e.priority > 0).map((e) => e.key))
|
|
331
433
|
const inResult = new Set(selected.map((e) => e.key))
|
|
332
434
|
const toInject = [...pinnedKeys]
|
|
333
435
|
.filter((k) => !inResult.has(k) && byKey.has(k))
|
|
@@ -440,7 +542,8 @@ export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {
|
|
|
440
542
|
const originInfo = e.origin !== "agent" ? ` · origin: ${e.origin}` : ""
|
|
441
543
|
const scopeInfo = e.path_scope ? ` · scope: ${e.path_scope}` : ""
|
|
442
544
|
const statusInfo = e.status !== "active" ? ` · status: ${e.status}` : ""
|
|
443
|
-
|
|
545
|
+
const supersededInfo = e.supersededOn ? ` · superseded: ${e.supersededOn}` : ""
|
|
546
|
+
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
547
|
}
|
|
445
548
|
|
|
446
549
|
// "normal" budget (default)
|
package/src/lib/quality.ts
CHANGED
|
@@ -7,7 +7,17 @@
|
|
|
7
7
|
* primer (auto-generated knowledge map).
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
import {
|
|
10
|
+
import {
|
|
11
|
+
parseEntries,
|
|
12
|
+
buildGraph,
|
|
13
|
+
bm25Scores,
|
|
14
|
+
centrality,
|
|
15
|
+
renderCompact,
|
|
16
|
+
rankBy,
|
|
17
|
+
rrfFuse,
|
|
18
|
+
rrfK,
|
|
19
|
+
type GraphEntry,
|
|
20
|
+
} from "./graph"
|
|
11
21
|
import { normalize, isExpiredLocal, tokenize, importance, isPrivate } from "./utils"
|
|
12
22
|
import { expandSynonyms } from "./synonyms"
|
|
13
23
|
import { fuzzyMatch } from "./fuzzy"
|
|
@@ -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
|
-
|
|
178
|
+
// Preserve superseded_on (field 17) from the existing entry.
|
|
179
|
+
const existingSupersededOn = ep.length > 17 ? ep[17] || "" : ""
|
|
180
|
+
|
|
181
|
+
return `${id}|${category}|${key}|${content}|${file}|${mergedTags}|${date}|${ttl}|${accessed}|${mergedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}|${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 } = {}
|
|
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
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
206
|
+
const eligible = entries.filter((e) => {
|
|
207
|
+
if (category && e.category !== category) return false
|
|
208
|
+
if (e.ttl && isExpiredLocal(e.ttl)) 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(" ")}`
|
|
@@ -222,8 +247,13 @@ export function generateSmartRecall(
|
|
|
222
247
|
sessionBias = 0.15
|
|
223
248
|
}
|
|
224
249
|
}
|
|
225
|
-
|
|
226
|
-
|
|
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(
|
|
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) =>
|
|
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,8 +276,7 @@ export function generateSmartRecall(
|
|
|
246
276
|
}
|
|
247
277
|
|
|
248
278
|
if (scored.length === 0) {
|
|
249
|
-
const top =
|
|
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
282
|
return importance(b) - importance(a)
|