toon-memory 2.1.0 → 2.3.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 +133 -10
- package/dist/cli/setup.js +203 -119
- package/mcp/server.js +289 -35
- package/package.json +1 -1
- package/src/cli/setup.ts +29 -2
- package/src/lib/graph.ts +354 -0
- package/src/lib/vocab.ts +100 -0
- package/src/mcp/server.ts +80 -8
package/src/lib/graph.ts
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory graph layer for toon-memory.
|
|
3
|
+
*
|
|
4
|
+
* Turns the flat TOON entry list into a lightweight knowledge graph:
|
|
5
|
+
* - nodes = memory entries (keyed by `key`)
|
|
6
|
+
* - edges = explicit `links` + implicit `[[key]]` references in content
|
|
7
|
+
*
|
|
8
|
+
* Everything is deterministic and offline: no embeddings, no LLM, no network.
|
|
9
|
+
* The graph's value is precision (relational context) and smaller result sets
|
|
10
|
+
* (an ego-subgraph instead of dumping every keyword match).
|
|
11
|
+
*
|
|
12
|
+
* Hito 7 adds BM25 relevance scoring + graph centrality re-ranking, plus a
|
|
13
|
+
* `detailed` result so the MCP server can render compact / numeric-edge output
|
|
14
|
+
* without mutating the stored `.toon` file.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export interface GraphEntry {
|
|
18
|
+
id: string
|
|
19
|
+
category: string
|
|
20
|
+
key: string
|
|
21
|
+
content: string
|
|
22
|
+
file: string
|
|
23
|
+
tags: string[]
|
|
24
|
+
date: string
|
|
25
|
+
ttl: string
|
|
26
|
+
accessed: number
|
|
27
|
+
/** Explicit outgoing links declared on the entry. */
|
|
28
|
+
links: string[]
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface MemoryGraph {
|
|
32
|
+
/** key -> connected keys (undirected, deduped, only keys that exist). */
|
|
33
|
+
adjacency: Map<string, string[]>
|
|
34
|
+
/** key -> entry (first occurrence wins on duplicate keys). */
|
|
35
|
+
byKey: Map<string, GraphEntry>
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const isExpiredLocal = (ttl: string): boolean => {
|
|
39
|
+
if (!ttl) return false
|
|
40
|
+
const today = new Date().toISOString().split("T")[0]
|
|
41
|
+
return ttl <= today
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const normalize = (s: string): string =>
|
|
45
|
+
s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
|
|
46
|
+
|
|
47
|
+
const entryLines = (data: string): string[] =>
|
|
48
|
+
data
|
|
49
|
+
.split("\n")
|
|
50
|
+
.filter(
|
|
51
|
+
(l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Parse TOON memory content into structured entries.
|
|
56
|
+
* Tolerant of the trailing `links` field (absent on older entries).
|
|
57
|
+
*/
|
|
58
|
+
export function parseEntries(data: string): GraphEntry[] {
|
|
59
|
+
const out: GraphEntry[] = []
|
|
60
|
+
for (const line of entryLines(data)) {
|
|
61
|
+
const parts = line.trim().split("|")
|
|
62
|
+
if (parts.length < 7) continue
|
|
63
|
+
const [id, category, key, content, file, tags, date, ttl, accessedRaw, linksRaw] =
|
|
64
|
+
parts
|
|
65
|
+
out.push({
|
|
66
|
+
id,
|
|
67
|
+
category,
|
|
68
|
+
key,
|
|
69
|
+
content,
|
|
70
|
+
file: file || "",
|
|
71
|
+
tags: (tags || "")
|
|
72
|
+
.split(";")
|
|
73
|
+
.map((t) => t.trim())
|
|
74
|
+
.filter(Boolean),
|
|
75
|
+
date: date || "",
|
|
76
|
+
ttl: ttl || "",
|
|
77
|
+
accessed: accessedRaw ? parseInt(accessedRaw) || 0 : 0,
|
|
78
|
+
links: (linksRaw || "")
|
|
79
|
+
.split(/[\s;]+/)
|
|
80
|
+
.map((t) => t.trim())
|
|
81
|
+
.filter(Boolean),
|
|
82
|
+
})
|
|
83
|
+
}
|
|
84
|
+
return out
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Build the adjacency graph from explicit links and implicit `[[key]]` refs.
|
|
89
|
+
* Edges are undirected and only connect keys that actually exist.
|
|
90
|
+
*/
|
|
91
|
+
export function buildGraph(entries: GraphEntry[]): MemoryGraph {
|
|
92
|
+
const byKey = new Map<string, GraphEntry>()
|
|
93
|
+
for (const e of entries) {
|
|
94
|
+
if (!byKey.has(e.key)) byKey.set(e.key, e)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const adj = new Map<string, Set<string>>()
|
|
98
|
+
const link = (a: string, b: string): void => {
|
|
99
|
+
if (a === b) return
|
|
100
|
+
if (!byKey.has(a) || !byKey.has(b)) return
|
|
101
|
+
if (!adj.has(a)) adj.set(a, new Set())
|
|
102
|
+
adj.get(a)!.add(b)
|
|
103
|
+
if (!adj.has(b)) adj.set(b, new Set())
|
|
104
|
+
adj.get(b)!.add(a)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
for (const e of entries) {
|
|
108
|
+
for (const l of e.links) link(e.key, l)
|
|
109
|
+
const refs = e.content.match(/\[\[([\w-]+)\]\]/g) || []
|
|
110
|
+
for (const r of refs) link(e.key, r.slice(2, -2))
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const adjacency = new Map<string, string[]>()
|
|
114
|
+
for (const [k, v] of adj) adjacency.set(k, [...v])
|
|
115
|
+
return { adjacency, byKey }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export interface GraphRecallOpts {
|
|
119
|
+
category?: string
|
|
120
|
+
from_date?: string
|
|
121
|
+
to_date?: string
|
|
122
|
+
/** Graph traversal depth from matched seeds (1 or 2). Default 1. */
|
|
123
|
+
hops?: number
|
|
124
|
+
/** Max entries returned (keeps token cost low). Default 6. */
|
|
125
|
+
limit?: number
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const importance = (e: GraphEntry): number => {
|
|
129
|
+
const today = new Date().toISOString().split("T")[0]
|
|
130
|
+
const days =
|
|
131
|
+
(Date.now() - new Date(`${e.date || today}T00:00:00`).getTime()) / 86400000
|
|
132
|
+
const recency = Math.max(0, 30 - days) / 30
|
|
133
|
+
const freq = Math.min(1, e.accessed / 5)
|
|
134
|
+
return recency * 0.6 + freq * 0.4
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const tokenize = (s: string): string[] => normalize(s).split(" ").filter(Boolean)
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* BM25 relevance of each entry for the query. Deterministic and offline.
|
|
141
|
+
* Returns a map key -> score (0 when the entry shares no query token).
|
|
142
|
+
*/
|
|
143
|
+
export function bm25Scores(entries: GraphEntry[], query: string): Map<string, number> {
|
|
144
|
+
const N = entries.length
|
|
145
|
+
const scores = new Map<string, number>()
|
|
146
|
+
if (N === 0) return scores
|
|
147
|
+
|
|
148
|
+
const docs = entries.map((e) =>
|
|
149
|
+
tokenize(`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`)
|
|
150
|
+
)
|
|
151
|
+
const df = new Map<string, number>()
|
|
152
|
+
for (const d of docs) {
|
|
153
|
+
for (const t of new Set(d)) df.set(t, (df.get(t) || 0) + 1)
|
|
154
|
+
}
|
|
155
|
+
const avgdl = docs.reduce((a, b) => a + b.length, 0) / N
|
|
156
|
+
const k1 = 1.5
|
|
157
|
+
const b = 0.75
|
|
158
|
+
const qTokens = tokenize(query)
|
|
159
|
+
|
|
160
|
+
entries.forEach((e, i) => {
|
|
161
|
+
const d = docs[i]
|
|
162
|
+
const dl = d.length || 1
|
|
163
|
+
let score = 0
|
|
164
|
+
for (const t of qTokens) {
|
|
165
|
+
const dfT = df.get(t)
|
|
166
|
+
if (!dfT) continue
|
|
167
|
+
const f = d.filter((x) => x === t).length
|
|
168
|
+
const idf = Math.log((N - dfT + 0.5) / (dfT + 0.5) + 1)
|
|
169
|
+
score += (idf * (f * (k1 + 1))) / (f + k1 * (1 - b + (b * dl) / avgdl))
|
|
170
|
+
}
|
|
171
|
+
scores.set(e.key, score)
|
|
172
|
+
})
|
|
173
|
+
return scores
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Degree-normalized centrality (0..1). A hub connected to many entries scores
|
|
178
|
+
* near 1, so it surfaces even when it lacks the exact query word.
|
|
179
|
+
*/
|
|
180
|
+
export function centrality(adjacency: Map<string, string[]>): Map<string, number> {
|
|
181
|
+
let maxDeg = 1
|
|
182
|
+
const deg = new Map<string, number>()
|
|
183
|
+
for (const [k, v] of adjacency) {
|
|
184
|
+
deg.set(k, v.length)
|
|
185
|
+
if (v.length > maxDeg) maxDeg = v.length
|
|
186
|
+
}
|
|
187
|
+
const out = new Map<string, number>()
|
|
188
|
+
for (const [k, d] of deg) out.set(k, d / maxDeg)
|
|
189
|
+
return out
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export interface GraphRecallResult {
|
|
193
|
+
/** Selected entries, ordered by final score (desc). */
|
|
194
|
+
entries: GraphEntry[]
|
|
195
|
+
/** Keys that directly matched the query (seeds, distance 0). */
|
|
196
|
+
seeds: Set<string>
|
|
197
|
+
/** Adjacency restricted to the selected entries (for numeric-edge rendering). */
|
|
198
|
+
adjacency: Map<string, string[]>
|
|
199
|
+
/** Final combined score per key (bm25 + centrality + importance + seed bonus). */
|
|
200
|
+
scores: Map<string, number>
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const W_CENT = 0.4
|
|
204
|
+
const W_IMP = 0.25
|
|
205
|
+
const SEED_BONUS = 1.0
|
|
206
|
+
/** Per-hop decay: a node 1 hop from a seed scores half of an equivalent seed. */
|
|
207
|
+
const DECAY = 0.5
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Graph-aware recall with BM25 + centrality re-ranking.
|
|
211
|
+
* Seeds are keyword matches (AND logic); the result is the ego-subgraph
|
|
212
|
+
* expanded up to `hops` (1 or 2), with relevance propagated from the seeds.
|
|
213
|
+
* Falls back to top-by-importance when the query matches nothing.
|
|
214
|
+
*/
|
|
215
|
+
export function graphRecallDetailed(
|
|
216
|
+
data: string,
|
|
217
|
+
query: string,
|
|
218
|
+
opts: GraphRecallOpts = {}
|
|
219
|
+
): GraphRecallResult {
|
|
220
|
+
const entries = parseEntries(data)
|
|
221
|
+
const { adjacency, byKey } = buildGraph(entries)
|
|
222
|
+
const hops = Math.max(1, Math.min(2, opts.hops ?? 1))
|
|
223
|
+
const category = opts.category || ""
|
|
224
|
+
const from_date = opts.from_date || ""
|
|
225
|
+
const to_date = opts.to_date || ""
|
|
226
|
+
|
|
227
|
+
const qTokens = tokenize(query)
|
|
228
|
+
const bm25 = bm25Scores(entries, query)
|
|
229
|
+
const cent = centrality(adjacency)
|
|
230
|
+
|
|
231
|
+
const seedKeys = new Set<string>()
|
|
232
|
+
for (const e of entries) {
|
|
233
|
+
if (category && e.category !== category) continue
|
|
234
|
+
if (from_date && e.date < from_date) continue
|
|
235
|
+
if (to_date && e.date > to_date) continue
|
|
236
|
+
if (e.ttl && isExpiredLocal(e.ttl)) continue
|
|
237
|
+
const text = normalize(
|
|
238
|
+
`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
|
|
239
|
+
)
|
|
240
|
+
if (qTokens.length > 0 && !qTokens.every((t) => text.includes(t))) continue
|
|
241
|
+
seedKeys.add(e.key)
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
let selected: GraphEntry[]
|
|
245
|
+
const scored: Array<{ e: GraphEntry; s: number }> = []
|
|
246
|
+
if (seedKeys.size === 0) {
|
|
247
|
+
scored.push(
|
|
248
|
+
...[...entries]
|
|
249
|
+
.sort((a, b) => importance(b) - importance(a))
|
|
250
|
+
.slice(0, opts.limit ?? 6)
|
|
251
|
+
.map((e) => ({ e, s: importance(e) }))
|
|
252
|
+
)
|
|
253
|
+
} else {
|
|
254
|
+
// BFS from all seeds, recording the shortest hop distance to each node.
|
|
255
|
+
const best = new Map<string, number>()
|
|
256
|
+
const queue: Array<{ key: string; dist: number }> = []
|
|
257
|
+
for (const k of seedKeys) queue.push({ key: k, dist: 0 })
|
|
258
|
+
while (queue.length) {
|
|
259
|
+
const { key, dist } = queue.shift()!
|
|
260
|
+
if (best.has(key) && best.get(key)! <= dist) continue
|
|
261
|
+
best.set(key, dist)
|
|
262
|
+
if (dist >= hops) continue
|
|
263
|
+
for (const nb of adjacency.get(key) || []) {
|
|
264
|
+
queue.push({ key: nb, dist: dist + 1 })
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
scored.push(
|
|
269
|
+
...[...best.keys()]
|
|
270
|
+
.map((k) => {
|
|
271
|
+
const e = byKey.get(k)!
|
|
272
|
+
const dist = best.get(k)!
|
|
273
|
+
const decay = Math.pow(DECAY, dist)
|
|
274
|
+
let s = (bm25.get(k) || 0) + W_CENT * cent.get(k)! + W_IMP * importance(e)
|
|
275
|
+
if (seedKeys.has(k)) s += SEED_BONUS
|
|
276
|
+
s *= decay
|
|
277
|
+
return { e, s }
|
|
278
|
+
})
|
|
279
|
+
.sort((a, b) => b.s - a.s)
|
|
280
|
+
.slice(0, opts.limit ?? 6)
|
|
281
|
+
)
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
selected = scored.map((x) => x.e)
|
|
285
|
+
|
|
286
|
+
// Restrict adjacency to the selected entries for compact edge rendering.
|
|
287
|
+
const subAdj = new Map<string, string[]>()
|
|
288
|
+
for (const e of selected) {
|
|
289
|
+
subAdj.set(
|
|
290
|
+
e.key,
|
|
291
|
+
(adjacency.get(e.key) || []).filter((k) => selected.some((s) => s.key === k))
|
|
292
|
+
)
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const scores = new Map<string, number>()
|
|
296
|
+
selected.forEach((e) => scores.set(e.key, scored.find((x) => x.e.key === e.key)!.s))
|
|
297
|
+
|
|
298
|
+
return { entries: selected, seeds: seedKeys, adjacency: subAdj, scores }
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Convenience wrapper returning just the ordered entries (backward compatible).
|
|
303
|
+
*/
|
|
304
|
+
export function graphRecall(
|
|
305
|
+
data: string,
|
|
306
|
+
query: string,
|
|
307
|
+
opts: GraphRecallOpts = {}
|
|
308
|
+
): GraphEntry[] {
|
|
309
|
+
return graphRecallDetailed(data, query, opts).entries
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
export interface RenderCompactOpts {
|
|
313
|
+
/** Restricted adjacency for numeric edge rendering (graph mode). */
|
|
314
|
+
adjacency?: Map<string, string[]>
|
|
315
|
+
/** Keys that directly matched the query (seeds = full content). */
|
|
316
|
+
seeds?: Set<string>
|
|
317
|
+
/** Max chars before a neighbor (non-seed) is truncated with an ellipsis. */
|
|
318
|
+
snippetLen?: number
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Token-efficient rendering of recall results.
|
|
323
|
+
* - each entry gets a stable numeric index `1`, `2`, ...
|
|
324
|
+
* - `id` / `date` / `file` are dropped (only `tags` is kept)
|
|
325
|
+
* - graph edges render as `->2, ->3` (numeric) when `adjacency` is given
|
|
326
|
+
* - neighbors reached via graph (non-seeds) are truncated to `snippetLen`
|
|
327
|
+
*
|
|
328
|
+
* The stored `.toon` file is never mutated — this only shapes the output.
|
|
329
|
+
*/
|
|
330
|
+
export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {}): string {
|
|
331
|
+
const index = new Map<string, number>()
|
|
332
|
+
entries.forEach((e, i) => index.set(e.key, i + 1))
|
|
333
|
+
const snippetLen = opts.snippetLen ?? 90
|
|
334
|
+
|
|
335
|
+
return entries
|
|
336
|
+
.map((e) => {
|
|
337
|
+
const n = index.get(e.key)!
|
|
338
|
+
const isSeed = opts.seeds ? opts.seeds.has(e.key) : true
|
|
339
|
+
let body = e.content
|
|
340
|
+
if (!isSeed && e.content.length > snippetLen) {
|
|
341
|
+
body = e.content.slice(0, snippetLen).trimEnd() + "…"
|
|
342
|
+
}
|
|
343
|
+
const tags = e.tags.length ? ` · tags: ${e.tags.join(";")}` : ""
|
|
344
|
+
let edges = ""
|
|
345
|
+
if (opts.adjacency) {
|
|
346
|
+
const nb = (opts.adjacency.get(e.key) || [])
|
|
347
|
+
.map((k) => index.get(k))
|
|
348
|
+
.filter((x): x is number => typeof x === "number")
|
|
349
|
+
if (nb.length) edges = ` · edges: ->${nb.join(", ->")}`
|
|
350
|
+
}
|
|
351
|
+
return `[${n}] ${e.category}/${e.key}\n ${body}${tags}${edges}`
|
|
352
|
+
})
|
|
353
|
+
.join("\n\n")
|
|
354
|
+
}
|
package/src/lib/vocab.ts
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Project-vocabulary discovery for toon-memory (Hito 7).
|
|
3
|
+
*
|
|
4
|
+
* On `toon-memory init` we scan the project's dependency manifests and turn
|
|
5
|
+
* each dependency into a tag keyword. Those keywords are written to
|
|
6
|
+
* `config.json` as `vocab`, and `memory_remember`'s tag inference matches
|
|
7
|
+
* against them — so a project that depends on `redis` auto-tags entries that
|
|
8
|
+
* mention "redis" with `redis`, without a hand-maintained glossary.
|
|
9
|
+
*
|
|
10
|
+
* Deterministic and offline: we only read manifest files, never hit the network.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { existsSync, readFileSync } from "fs"
|
|
14
|
+
import { join } from "path"
|
|
15
|
+
|
|
16
|
+
/** tag -> keywords that should attach that tag. */
|
|
17
|
+
export type Vocab = Record<string, string[]>
|
|
18
|
+
|
|
19
|
+
/** Cargo-style manifest names we understand. */
|
|
20
|
+
const MANIFESTS = ["package.json", "Cargo.toml", "requirements.txt", "pyproject.toml", "go.mod"]
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Scan `root` for dependency manifests and return a vocabulary derived from
|
|
24
|
+
* the declared dependencies. Missing manifests are silently skipped.
|
|
25
|
+
*/
|
|
26
|
+
export function extractProjectDeps(root: string): Vocab {
|
|
27
|
+
const vocab: Vocab = {}
|
|
28
|
+
|
|
29
|
+
const pkgPath = join(root, "package.json")
|
|
30
|
+
if (existsSync(pkgPath)) {
|
|
31
|
+
try {
|
|
32
|
+
const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"))
|
|
33
|
+
const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) }
|
|
34
|
+
for (const name of Object.keys(deps)) {
|
|
35
|
+
const tag = name.replace(/^@[^/]+\//, "").toLowerCase()
|
|
36
|
+
vocab[tag] = name.includes("/") ? [name.toLowerCase(), tag] : [name.toLowerCase()]
|
|
37
|
+
}
|
|
38
|
+
} catch {
|
|
39
|
+
// ignore malformed manifest
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const cargoPath = join(root, "Cargo.toml")
|
|
44
|
+
if (existsSync(cargoPath)) {
|
|
45
|
+
try {
|
|
46
|
+
const txt = readFileSync(cargoPath, "utf-8")
|
|
47
|
+
const block = txt.match(/\[dependencies\][\s\S]*?(?:\n\[|$)/)?.[0] || ""
|
|
48
|
+
for (const line of block.split("\n")) {
|
|
49
|
+
const m = line.match(/^\s*([A-Za-z0-9_-]+)\s*=/)
|
|
50
|
+
if (m) {
|
|
51
|
+
const tag = m[1].toLowerCase()
|
|
52
|
+
vocab[tag] = [tag]
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
} catch {
|
|
56
|
+
// ignore
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
for (const file of ["requirements.txt", "pyproject.toml"]) {
|
|
61
|
+
const p = join(root, file)
|
|
62
|
+
if (!existsSync(p)) continue
|
|
63
|
+
try {
|
|
64
|
+
const txt = readFileSync(p, "utf-8")
|
|
65
|
+
for (const raw of txt.split("\n")) {
|
|
66
|
+
const name = raw.trim().split(/[<>=!~ \[\]]/)[0].toLowerCase()
|
|
67
|
+
if (!name || name.startsWith("#") || name.includes("[") ) continue
|
|
68
|
+
vocab[name] = [name]
|
|
69
|
+
}
|
|
70
|
+
} catch {
|
|
71
|
+
// ignore
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const goPath = join(root, "go.mod")
|
|
76
|
+
if (existsSync(goPath)) {
|
|
77
|
+
try {
|
|
78
|
+
const txt = readFileSync(goPath, "utf-8")
|
|
79
|
+
for (const raw of txt.split("\n")) {
|
|
80
|
+
const m = raw.match(/^\s*([A-Za-z0-9_./-]+)\s+v[0-9]/)
|
|
81
|
+
if (m) {
|
|
82
|
+
const full = m[1]
|
|
83
|
+
const tag = full.split("/").pop()!.toLowerCase()
|
|
84
|
+
vocab[tag] = [tag, full.toLowerCase()]
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
} catch {
|
|
88
|
+
// ignore
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return vocab
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Merge two vocabularies; `extra` wins on key collisions. */
|
|
96
|
+
export function mergeVocab(base: Vocab, extra: Vocab): Vocab {
|
|
97
|
+
return { ...base, ...extra }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export { MANIFESTS }
|
package/src/mcp/server.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { fileURLToPath } from "url"
|
|
|
7
7
|
import { randomBytes, createCipheriv, createDecipheriv } from "crypto"
|
|
8
8
|
import { withLockSync, atomicWrite, readUnderLock } from "../lib/lock"
|
|
9
9
|
import { coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS } from "../lib/sessions"
|
|
10
|
+
import { graphRecallDetailed, renderCompact } from "../lib/graph"
|
|
10
11
|
|
|
11
12
|
const __dirname = dirname(fileURLToPath(import.meta.url))
|
|
12
13
|
|
|
@@ -47,6 +48,8 @@ const ALGORITHM = "aes-256-gcm"
|
|
|
47
48
|
interface MemoryConfig {
|
|
48
49
|
/** Whether encryption is enabled */
|
|
49
50
|
encrypted: boolean
|
|
51
|
+
/** Project-specific tag vocabulary discovered from dependencies (Hito 7). */
|
|
52
|
+
vocab?: Record<string, string[]>
|
|
50
53
|
}
|
|
51
54
|
|
|
52
55
|
/**
|
|
@@ -80,7 +83,16 @@ function loadConfig(): MemoryConfig {
|
|
|
80
83
|
*/
|
|
81
84
|
function saveConfig(config: MemoryConfig): void {
|
|
82
85
|
ensureMemoryDir()
|
|
83
|
-
|
|
86
|
+
// Merge so we never clobber a `vocab` written by `toon-memory init`.
|
|
87
|
+
let existing: Partial<MemoryConfig> = {}
|
|
88
|
+
if (existsSync(CONFIG_FILE)) {
|
|
89
|
+
try {
|
|
90
|
+
existing = JSON.parse(readFileSync(CONFIG_FILE, "utf-8"))
|
|
91
|
+
} catch {
|
|
92
|
+
existing = {}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
writeFileSync(CONFIG_FILE, JSON.stringify({ ...existing, ...config }, null, 2))
|
|
84
96
|
}
|
|
85
97
|
|
|
86
98
|
/**
|
|
@@ -105,7 +117,7 @@ function ensureMemoryDir(): void {
|
|
|
105
117
|
function ensureMemoryFile(): void {
|
|
106
118
|
ensureMemoryDir()
|
|
107
119
|
if (!existsSync(MEMORY_FILE)) {
|
|
108
|
-
writeFileSync(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed}:\n")
|
|
120
|
+
writeFileSync(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links}:\n")
|
|
109
121
|
}
|
|
110
122
|
}
|
|
111
123
|
|
|
@@ -271,9 +283,11 @@ const TAG_VOCABULARY: Record<string, string[]> = {
|
|
|
271
283
|
|
|
272
284
|
/**
|
|
273
285
|
* Infer tags from content and key by matching against vocabulary.
|
|
286
|
+
* The built-in vocabulary is always used; a project-specific `vocab`
|
|
287
|
+
* (discovered from dependencies at `init`) is matched on top of it.
|
|
274
288
|
* Returns semicolon-separated tags.
|
|
275
289
|
*/
|
|
276
|
-
function inferTags(content: string, key: string): string {
|
|
290
|
+
function inferTags(content: string, key: string, vocab?: Record<string, string[]>): string {
|
|
277
291
|
const text = `${key} ${content}`.toLowerCase()
|
|
278
292
|
const matched: string[] = []
|
|
279
293
|
for (const [tag, keywords] of Object.entries(TAG_VOCABULARY)) {
|
|
@@ -281,6 +295,13 @@ function inferTags(content: string, key: string): string {
|
|
|
281
295
|
matched.push(tag)
|
|
282
296
|
}
|
|
283
297
|
}
|
|
298
|
+
if (vocab) {
|
|
299
|
+
for (const [tag, keywords] of Object.entries(vocab)) {
|
|
300
|
+
if (keywords.some((kw) => text.includes(kw))) {
|
|
301
|
+
matched.push(tag)
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
284
305
|
return matched.join(";")
|
|
285
306
|
}
|
|
286
307
|
|
|
@@ -578,7 +599,7 @@ function consolidateEntries(): { removed: number; kept: number; duplicates: stri
|
|
|
578
599
|
}
|
|
579
600
|
|
|
580
601
|
const server = new McpServer(
|
|
581
|
-
{ name: "toon-memory", version: "2.
|
|
602
|
+
{ name: "toon-memory", version: "2.3.0" },
|
|
582
603
|
{ capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
|
|
583
604
|
)
|
|
584
605
|
|
|
@@ -671,9 +692,10 @@ server.registerTool(
|
|
|
671
692
|
file: z.string().optional().default("").describe("Archivo o línea relacionada (ej: spec.md:145)"),
|
|
672
693
|
tags: z.string().optional().default("").describe("Tags separados por punto y coma (ej: risk;spec)"),
|
|
673
694
|
ttl: z.string().optional().default("").describe("Time to live (ej: 7d, 2026-07-17). Vacío = sin expiración"),
|
|
695
|
+
links: z.string().optional().default("").describe("Entradas relacionadas por key, separadas por espacio o ';' (ej: risk-spec engine-arch). Construye aristas del grafo de memoria."),
|
|
674
696
|
},
|
|
675
697
|
},
|
|
676
|
-
async ({ category, key, content, file, tags, ttl }) => {
|
|
698
|
+
async ({ category, key, content, file, tags, ttl, links }) => {
|
|
677
699
|
const data = readMemory()
|
|
678
700
|
const newId = generateId()
|
|
679
701
|
const date = new Date().toISOString().split("T")[0]
|
|
@@ -702,8 +724,13 @@ server.registerTool(
|
|
|
702
724
|
|
|
703
725
|
const entryId = existingIdx !== -1 ? existingId : newId
|
|
704
726
|
const resolvedTtl = parseTTL(ttl)
|
|
705
|
-
const resolvedTags = tags ? tags : inferTags(content, key)
|
|
706
|
-
|
|
727
|
+
const resolvedTags = tags ? tags : inferTags(content, key, loadConfig().vocab)
|
|
728
|
+
// Preserve existing links on upsert unless new ones are provided.
|
|
729
|
+
const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : []
|
|
730
|
+
const resolvedLinks = links
|
|
731
|
+
? links.split(/[\s;]+/).filter(Boolean).join(" ")
|
|
732
|
+
: existingParts[9] || ""
|
|
733
|
+
const newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|0|${resolvedLinks}`
|
|
707
734
|
let action = "Guardado"
|
|
708
735
|
const tagsInferred = !tags && resolvedTags ? true : false
|
|
709
736
|
|
|
@@ -769,9 +796,12 @@ server.registerTool(
|
|
|
769
796
|
category: z.string().optional().default("").describe("Filtrar por categoría (vacío = todos)"),
|
|
770
797
|
from_date: z.string().optional().default("").describe("Fecha inicio filtro (YYYY-MM-DD)"),
|
|
771
798
|
to_date: z.string().optional().default("").describe("Fecha fin filtro (YYYY-MM-DD)"),
|
|
799
|
+
mode: z.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = búsqueda por palabra clave (default). 'graph' = recall basado en grafo: expande el subgrafo de entradas relacionadas desde las coincidencias (más preciso, menos tokens)."),
|
|
800
|
+
hops: z.number().optional().default(1).describe("Profundidad del grafo en modo 'graph' (1 o 2). Default 1."),
|
|
801
|
+
compact: z.boolean().optional().default(false).describe("Salida token-efficient: índices numéricos (1, 2), omite id/fecha/archivo (conserva tags), aristas como '->2', y trunca vecinos del grafo a un snippet. No muta el archivo .toon."),
|
|
772
802
|
},
|
|
773
803
|
},
|
|
774
|
-
async ({ query, category, from_date, to_date }) => {
|
|
804
|
+
async ({ query, category, from_date, to_date, mode, hops, compact }) => {
|
|
775
805
|
const data = readMemory()
|
|
776
806
|
const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
|
|
777
807
|
|
|
@@ -801,6 +831,31 @@ server.registerTool(
|
|
|
801
831
|
return { content: [{ type: "text" as const, text: `No se encontraron resultados para "${query}"` }] }
|
|
802
832
|
}
|
|
803
833
|
|
|
834
|
+
// Graph mode: expand the ego-subgraph from keyword matches and return the
|
|
835
|
+
// focused, relationship-aware result set (fewer tokens, higher precision).
|
|
836
|
+
if (mode === "graph") {
|
|
837
|
+
const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops })
|
|
838
|
+
if (detail.entries.length === 0) {
|
|
839
|
+
return { content: [{ type: "text" as const, text: `No se encontraron resultados para "${query}"` }] }
|
|
840
|
+
}
|
|
841
|
+
bumpAccessed(detail.entries.map((e) => e.id))
|
|
842
|
+
if (compact) {
|
|
843
|
+
const formatted = renderCompact(detail.entries, {
|
|
844
|
+
adjacency: detail.adjacency,
|
|
845
|
+
seeds: detail.seeds,
|
|
846
|
+
snippetLen: 90,
|
|
847
|
+
})
|
|
848
|
+
return { content: [{ type: "text" as const, text: formatted }] }
|
|
849
|
+
}
|
|
850
|
+
const formatted = detail.entries
|
|
851
|
+
.map((r) => {
|
|
852
|
+
const links = r.links.length ? `\n links: ${r.links.join(", ")}` : ""
|
|
853
|
+
return `[${r.category}] ${r.key} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}`
|
|
854
|
+
})
|
|
855
|
+
.join("\n\n")
|
|
856
|
+
return { content: [{ type: "text" as const, text: formatted }] }
|
|
857
|
+
}
|
|
858
|
+
|
|
804
859
|
// Rank by importance (recency + access frequency), then bump access counts.
|
|
805
860
|
const ranked = results
|
|
806
861
|
.map((r) => ({ ...r, score: entryScore(r.date, r.accessed) }))
|
|
@@ -808,6 +863,23 @@ server.registerTool(
|
|
|
808
863
|
|
|
809
864
|
bumpAccessed(ranked.map((r) => r.id))
|
|
810
865
|
|
|
866
|
+
if (compact) {
|
|
867
|
+
const entries = ranked.map((r) => ({
|
|
868
|
+
id: r.id,
|
|
869
|
+
category: r.cat,
|
|
870
|
+
key: r.key,
|
|
871
|
+
content: r.content,
|
|
872
|
+
file: r.file,
|
|
873
|
+
tags: r.tags ? r.tags.split(";").filter(Boolean) : [],
|
|
874
|
+
date: r.date,
|
|
875
|
+
ttl: "",
|
|
876
|
+
accessed: r.accessed,
|
|
877
|
+
links: [] as string[],
|
|
878
|
+
}))
|
|
879
|
+
const formatted = renderCompact(entries)
|
|
880
|
+
return { content: [{ type: "text" as const, text: formatted }] }
|
|
881
|
+
}
|
|
882
|
+
|
|
811
883
|
const formatted = ranked
|
|
812
884
|
.map((r) => `[${r.cat}] ${r.key} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`)
|
|
813
885
|
.join("\n\n")
|