toon-memory 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/lib/graph.ts CHANGED
@@ -8,6 +8,10 @@
8
8
  * Everything is deterministic and offline: no embeddings, no LLM, no network.
9
9
  * The graph's value is precision (relational context) and smaller result sets
10
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.
11
15
  */
12
16
 
13
17
  export interface GraphEntry {
@@ -130,16 +134,89 @@ const importance = (e: GraphEntry): number => {
130
134
  return recency * 0.6 + freq * 0.4
131
135
  }
132
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
+
133
209
  /**
134
- * Graph-aware recall. Seeds are keyword matches (AND logic); the result is the
135
- * ego-subgraph expanded up to `hops` with relevance propagated from seeds.
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.
136
213
  * Falls back to top-by-importance when the query matches nothing.
137
214
  */
138
- export function graphRecall(
215
+ export function graphRecallDetailed(
139
216
  data: string,
140
217
  query: string,
141
218
  opts: GraphRecallOpts = {}
142
- ): GraphEntry[] {
219
+ ): GraphRecallResult {
143
220
  const entries = parseEntries(data)
144
221
  const { adjacency, byKey } = buildGraph(entries)
145
222
  const hops = Math.max(1, Math.min(2, opts.hops ?? 1))
@@ -147,54 +224,131 @@ export function graphRecall(
147
224
  const from_date = opts.from_date || ""
148
225
  const to_date = opts.to_date || ""
149
226
 
150
- const queryTokens = normalize(query)
151
- .split(" ")
152
- .filter(Boolean)
227
+ const qTokens = tokenize(query)
228
+ const bm25 = bm25Scores(entries, query)
229
+ const cent = centrality(adjacency)
153
230
 
154
- const seedScore = new Map<string, number>()
231
+ const seedKeys = new Set<string>()
155
232
  for (const e of entries) {
156
233
  if (category && e.category !== category) continue
157
234
  if (from_date && e.date < from_date) continue
158
235
  if (to_date && e.date > to_date) continue
159
236
  if (e.ttl && isExpiredLocal(e.ttl)) continue
160
- const searchStr = normalize(
237
+ const text = normalize(
161
238
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
162
239
  )
163
- if (queryTokens.length > 0 && !queryTokens.every((t) => searchStr.includes(t)))
164
- continue
165
- seedScore.set(e.key, importance(e) + 1.0)
240
+ if (qTokens.length > 0 && !qTokens.every((t) => text.includes(t))) continue
241
+ seedKeys.add(e.key)
166
242
  }
167
243
 
168
- // No matches: return the most important entries as a sane fallback.
169
- if (seedScore.size === 0) {
170
- return [...entries]
171
- .sort((a, b) => importance(b) - importance(a))
172
- .slice(0, opts.limit ?? 6)
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
+ )
173
282
  }
174
283
 
175
- // BFS from all seeds, recording the shortest hop distance to each node.
176
- const best = new Map<string, number>()
177
- const queue: Array<{ key: string; dist: number }> = []
178
- for (const k of seedScore.keys()) queue.push({ key: k, dist: 0 })
179
- while (queue.length) {
180
- const { key, dist } = queue.shift()!
181
- if (best.has(key) && best.get(key)! <= dist) continue
182
- best.set(key, dist)
183
- if (dist >= hops) continue
184
- for (const nb of adjacency.get(key) || []) {
185
- queue.push({ key: nb, dist: dist + 1 })
186
- }
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
+ )
187
293
  }
188
294
 
189
- const scored = [...best.keys()]
190
- .map((k) => {
191
- const e = byKey.get(k)!
192
- let s = importance(e)
193
- if (seedScore.has(k)) s += 1.0
194
- else s += 0.6 / best.get(k)!
195
- return { e, s }
196
- })
197
- .sort((a, b) => b.s - a.s)
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
198
334
 
199
- return scored.slice(0, opts.limit ?? 6).map((x) => x.e)
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")
200
354
  }
@@ -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,7 +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 { graphRecall } from "../lib/graph"
10
+ import { graphRecallDetailed, renderCompact } from "../lib/graph"
11
11
 
12
12
  const __dirname = dirname(fileURLToPath(import.meta.url))
13
13
 
@@ -48,6 +48,8 @@ const ALGORITHM = "aes-256-gcm"
48
48
  interface MemoryConfig {
49
49
  /** Whether encryption is enabled */
50
50
  encrypted: boolean
51
+ /** Project-specific tag vocabulary discovered from dependencies (Hito 7). */
52
+ vocab?: Record<string, string[]>
51
53
  }
52
54
 
53
55
  /**
@@ -81,7 +83,16 @@ function loadConfig(): MemoryConfig {
81
83
  */
82
84
  function saveConfig(config: MemoryConfig): void {
83
85
  ensureMemoryDir()
84
- writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2))
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))
85
96
  }
86
97
 
87
98
  /**
@@ -272,9 +283,11 @@ const TAG_VOCABULARY: Record<string, string[]> = {
272
283
 
273
284
  /**
274
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.
275
288
  * Returns semicolon-separated tags.
276
289
  */
277
- function inferTags(content: string, key: string): string {
290
+ function inferTags(content: string, key: string, vocab?: Record<string, string[]>): string {
278
291
  const text = `${key} ${content}`.toLowerCase()
279
292
  const matched: string[] = []
280
293
  for (const [tag, keywords] of Object.entries(TAG_VOCABULARY)) {
@@ -282,6 +295,13 @@ function inferTags(content: string, key: string): string {
282
295
  matched.push(tag)
283
296
  }
284
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
+ }
285
305
  return matched.join(";")
286
306
  }
287
307
 
@@ -579,7 +599,7 @@ function consolidateEntries(): { removed: number; kept: number; duplicates: stri
579
599
  }
580
600
 
581
601
  const server = new McpServer(
582
- { name: "toon-memory", version: "2.2.0" },
602
+ { name: "toon-memory", version: "2.4.0" },
583
603
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
584
604
  )
585
605
 
@@ -704,7 +724,7 @@ server.registerTool(
704
724
 
705
725
  const entryId = existingIdx !== -1 ? existingId : newId
706
726
  const resolvedTtl = parseTTL(ttl)
707
- const resolvedTags = tags ? tags : inferTags(content, key)
727
+ const resolvedTags = tags ? tags : inferTags(content, key, loadConfig().vocab)
708
728
  // Preserve existing links on upsert unless new ones are provided.
709
729
  const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : []
710
730
  const resolvedLinks = links
@@ -778,9 +798,10 @@ server.registerTool(
778
798
  to_date: z.string().optional().default("").describe("Fecha fin filtro (YYYY-MM-DD)"),
779
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)."),
780
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."),
781
802
  },
782
803
  },
783
- async ({ query, category, from_date, to_date, mode, hops }) => {
804
+ async ({ query, category, from_date, to_date, mode, hops, compact }) => {
784
805
  const data = readMemory()
785
806
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
786
807
 
@@ -813,12 +834,20 @@ server.registerTool(
813
834
  // Graph mode: expand the ego-subgraph from keyword matches and return the
814
835
  // focused, relationship-aware result set (fewer tokens, higher precision).
815
836
  if (mode === "graph") {
816
- const subgraph = graphRecall(data, query, { category, from_date, to_date, hops })
817
- if (subgraph.length === 0) {
837
+ const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops })
838
+ if (detail.entries.length === 0) {
818
839
  return { content: [{ type: "text" as const, text: `No se encontraron resultados para "${query}"` }] }
819
840
  }
820
- bumpAccessed(subgraph.map((e) => e.id))
821
- const formatted = subgraph
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
822
851
  .map((r) => {
823
852
  const links = r.links.length ? `\n links: ${r.links.join(", ")}` : ""
824
853
  return `[${r.category}] ${r.key} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}`
@@ -834,6 +863,23 @@ server.registerTool(
834
863
 
835
864
  bumpAccessed(ranked.map((r) => r.id))
836
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
+
837
883
  const formatted = ranked
838
884
  .map((r) => `[${r.cat}] ${r.key} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`)
839
885
  .join("\n\n")