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/mcp/server.js CHANGED
@@ -27907,50 +27907,137 @@ var importance = (e) => {
27907
27907
  const freq = Math.min(1, e.accessed / 5);
27908
27908
  return recency * 0.6 + freq * 0.4;
27909
27909
  };
27910
- function graphRecall(data, query, opts = {}) {
27910
+ var tokenize = (s) => normalize(s).split(" ").filter(Boolean);
27911
+ function bm25Scores(entries, query) {
27912
+ const N = entries.length;
27913
+ const scores = /* @__PURE__ */ new Map();
27914
+ if (N === 0) return scores;
27915
+ const docs = entries.map(
27916
+ (e) => tokenize(`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`)
27917
+ );
27918
+ const df = /* @__PURE__ */ new Map();
27919
+ for (const d of docs) {
27920
+ for (const t of new Set(d)) df.set(t, (df.get(t) || 0) + 1);
27921
+ }
27922
+ const avgdl = docs.reduce((a, b2) => a + b2.length, 0) / N;
27923
+ const k1 = 1.5;
27924
+ const b = 0.75;
27925
+ const qTokens = tokenize(query);
27926
+ entries.forEach((e, i) => {
27927
+ const d = docs[i];
27928
+ const dl = d.length || 1;
27929
+ let score = 0;
27930
+ for (const t of qTokens) {
27931
+ const dfT = df.get(t);
27932
+ if (!dfT) continue;
27933
+ const f = d.filter((x) => x === t).length;
27934
+ const idf = Math.log((N - dfT + 0.5) / (dfT + 0.5) + 1);
27935
+ score += idf * (f * (k1 + 1)) / (f + k1 * (1 - b + b * dl / avgdl));
27936
+ }
27937
+ scores.set(e.key, score);
27938
+ });
27939
+ return scores;
27940
+ }
27941
+ function centrality(adjacency) {
27942
+ let maxDeg = 1;
27943
+ const deg = /* @__PURE__ */ new Map();
27944
+ for (const [k, v] of adjacency) {
27945
+ deg.set(k, v.length);
27946
+ if (v.length > maxDeg) maxDeg = v.length;
27947
+ }
27948
+ const out = /* @__PURE__ */ new Map();
27949
+ for (const [k, d] of deg) out.set(k, d / maxDeg);
27950
+ return out;
27951
+ }
27952
+ var W_CENT = 0.4;
27953
+ var W_IMP = 0.25;
27954
+ var SEED_BONUS = 1;
27955
+ var DECAY = 0.5;
27956
+ function graphRecallDetailed(data, query, opts = {}) {
27911
27957
  const entries = parseEntries(data);
27912
27958
  const { adjacency, byKey } = buildGraph(entries);
27913
27959
  const hops = Math.max(1, Math.min(2, opts.hops ?? 1));
27914
27960
  const category = opts.category || "";
27915
27961
  const from_date = opts.from_date || "";
27916
27962
  const to_date = opts.to_date || "";
27917
- const queryTokens = normalize(query).split(" ").filter(Boolean);
27918
- const seedScore = /* @__PURE__ */ new Map();
27963
+ const qTokens = tokenize(query);
27964
+ const bm25 = bm25Scores(entries, query);
27965
+ const cent = centrality(adjacency);
27966
+ const seedKeys = /* @__PURE__ */ new Set();
27919
27967
  for (const e of entries) {
27920
27968
  if (category && e.category !== category) continue;
27921
27969
  if (from_date && e.date < from_date) continue;
27922
27970
  if (to_date && e.date > to_date) continue;
27923
27971
  if (e.ttl && isExpiredLocal(e.ttl)) continue;
27924
- const searchStr = normalize(
27972
+ const text = normalize(
27925
27973
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
27926
27974
  );
27927
- if (queryTokens.length > 0 && !queryTokens.every((t) => searchStr.includes(t)))
27928
- continue;
27929
- seedScore.set(e.key, importance(e) + 1);
27930
- }
27931
- if (seedScore.size === 0) {
27932
- return [...entries].sort((a, b) => importance(b) - importance(a)).slice(0, opts.limit ?? 6);
27933
- }
27934
- const best = /* @__PURE__ */ new Map();
27935
- const queue = [];
27936
- for (const k of seedScore.keys()) queue.push({ key: k, dist: 0 });
27937
- while (queue.length) {
27938
- const { key, dist } = queue.shift();
27939
- if (best.has(key) && best.get(key) <= dist) continue;
27940
- best.set(key, dist);
27941
- if (dist >= hops) continue;
27942
- for (const nb of adjacency.get(key) || []) {
27943
- queue.push({ key: nb, dist: dist + 1 });
27944
- }
27945
- }
27946
- const scored = [...best.keys()].map((k) => {
27947
- const e = byKey.get(k);
27948
- let s = importance(e);
27949
- if (seedScore.has(k)) s += 1;
27950
- else s += 0.6 / best.get(k);
27951
- return { e, s };
27952
- }).sort((a, b) => b.s - a.s);
27953
- return scored.slice(0, opts.limit ?? 6).map((x) => x.e);
27975
+ if (qTokens.length > 0 && !qTokens.every((t) => text.includes(t))) continue;
27976
+ seedKeys.add(e.key);
27977
+ }
27978
+ let selected;
27979
+ const scored = [];
27980
+ if (seedKeys.size === 0) {
27981
+ scored.push(
27982
+ ...[...entries].sort((a, b) => importance(b) - importance(a)).slice(0, opts.limit ?? 6).map((e) => ({ e, s: importance(e) }))
27983
+ );
27984
+ } else {
27985
+ const best = /* @__PURE__ */ new Map();
27986
+ const queue = [];
27987
+ for (const k of seedKeys) queue.push({ key: k, dist: 0 });
27988
+ while (queue.length) {
27989
+ const { key, dist } = queue.shift();
27990
+ if (best.has(key) && best.get(key) <= dist) continue;
27991
+ best.set(key, dist);
27992
+ if (dist >= hops) continue;
27993
+ for (const nb of adjacency.get(key) || []) {
27994
+ queue.push({ key: nb, dist: dist + 1 });
27995
+ }
27996
+ }
27997
+ scored.push(
27998
+ ...[...best.keys()].map((k) => {
27999
+ const e = byKey.get(k);
28000
+ const dist = best.get(k);
28001
+ const decay = Math.pow(DECAY, dist);
28002
+ let s = (bm25.get(k) || 0) + W_CENT * cent.get(k) + W_IMP * importance(e);
28003
+ if (seedKeys.has(k)) s += SEED_BONUS;
28004
+ s *= decay;
28005
+ return { e, s };
28006
+ }).sort((a, b) => b.s - a.s).slice(0, opts.limit ?? 6)
28007
+ );
28008
+ }
28009
+ selected = scored.map((x) => x.e);
28010
+ const subAdj = /* @__PURE__ */ new Map();
28011
+ for (const e of selected) {
28012
+ subAdj.set(
28013
+ e.key,
28014
+ (adjacency.get(e.key) || []).filter((k) => selected.some((s) => s.key === k))
28015
+ );
28016
+ }
28017
+ const scores = /* @__PURE__ */ new Map();
28018
+ selected.forEach((e) => scores.set(e.key, scored.find((x) => x.e.key === e.key).s));
28019
+ return { entries: selected, seeds: seedKeys, adjacency: subAdj, scores };
28020
+ }
28021
+ function renderCompact(entries, opts = {}) {
28022
+ const index = /* @__PURE__ */ new Map();
28023
+ entries.forEach((e, i) => index.set(e.key, i + 1));
28024
+ const snippetLen = opts.snippetLen ?? 90;
28025
+ return entries.map((e) => {
28026
+ const n = index.get(e.key);
28027
+ const isSeed = opts.seeds ? opts.seeds.has(e.key) : true;
28028
+ let body = e.content;
28029
+ if (!isSeed && e.content.length > snippetLen) {
28030
+ body = e.content.slice(0, snippetLen).trimEnd() + "\u2026";
28031
+ }
28032
+ const tags = e.tags.length ? ` \xB7 tags: ${e.tags.join(";")}` : "";
28033
+ let edges = "";
28034
+ if (opts.adjacency) {
28035
+ const nb = (opts.adjacency.get(e.key) || []).map((k) => index.get(k)).filter((x) => typeof x === "number");
28036
+ if (nb.length) edges = ` \xB7 edges: ->${nb.join(", ->")}`;
28037
+ }
28038
+ return `[${n}] ${e.category}/${e.key}
28039
+ ${body}${tags}${edges}`;
28040
+ }).join("\n\n");
27954
28041
  }
27955
28042
 
27956
28043
  // src/mcp/server.ts
@@ -27978,7 +28065,15 @@ function loadConfig() {
27978
28065
  }
27979
28066
  function saveConfig(config2) {
27980
28067
  ensureMemoryDir();
27981
- writeFileSync3(CONFIG_FILE, JSON.stringify(config2, null, 2));
28068
+ let existing = {};
28069
+ if (existsSync3(CONFIG_FILE)) {
28070
+ try {
28071
+ existing = JSON.parse(readFileSync3(CONFIG_FILE, "utf-8"));
28072
+ } catch {
28073
+ existing = {};
28074
+ }
28075
+ }
28076
+ writeFileSync3(CONFIG_FILE, JSON.stringify({ ...existing, ...config2 }, null, 2));
27982
28077
  }
27983
28078
  function getKey() {
27984
28079
  return process.env.TOON_MEMORY_KEY;
@@ -28087,7 +28182,7 @@ var TAG_VOCABULARY = {
28087
28182
  "payment": ["payment", "stripe", "billing", "invoice", "checkout", "subscription"],
28088
28183
  "webhook": ["webhook", "callback", "event", "listener", "hook"]
28089
28184
  };
28090
- function inferTags(content, key) {
28185
+ function inferTags(content, key, vocab) {
28091
28186
  const text = `${key} ${content}`.toLowerCase();
28092
28187
  const matched = [];
28093
28188
  for (const [tag, keywords] of Object.entries(TAG_VOCABULARY)) {
@@ -28095,6 +28190,13 @@ function inferTags(content, key) {
28095
28190
  matched.push(tag);
28096
28191
  }
28097
28192
  }
28193
+ if (vocab) {
28194
+ for (const [tag, keywords] of Object.entries(vocab)) {
28195
+ if (keywords.some((kw) => text.includes(kw))) {
28196
+ matched.push(tag);
28197
+ }
28198
+ }
28199
+ }
28098
28200
  return matched.join(";");
28099
28201
  }
28100
28202
  function parseRelativeDate(since) {
@@ -28296,7 +28398,7 @@ function consolidateEntries() {
28296
28398
  return { removed: duplicates.length, kept: order.length, duplicates };
28297
28399
  }
28298
28400
  var server = new McpServer(
28299
- { name: "toon-memory", version: "2.2.0" },
28401
+ { name: "toon-memory", version: "2.4.0" },
28300
28402
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
28301
28403
  );
28302
28404
  server.registerResource(
@@ -28389,7 +28491,7 @@ server.registerTool(
28389
28491
  }
28390
28492
  const entryId = existingIdx !== -1 ? existingId : newId;
28391
28493
  const resolvedTtl = parseTTL(ttl);
28392
- const resolvedTags = tags ? tags : inferTags(content, key);
28494
+ const resolvedTags = tags ? tags : inferTags(content, key, loadConfig().vocab);
28393
28495
  const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : [];
28394
28496
  const resolvedLinks = links ? links.split(/[\s;]+/).filter(Boolean).join(" ") : existingParts[9] || "";
28395
28497
  const newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0|${resolvedLinks}`;
@@ -28445,10 +28547,11 @@ server.registerTool(
28445
28547
  from_date: external_exports.string().optional().default("").describe("Fecha inicio filtro (YYYY-MM-DD)"),
28446
28548
  to_date: external_exports.string().optional().default("").describe("Fecha fin filtro (YYYY-MM-DD)"),
28447
28549
  mode: external_exports.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = b\xFAsqueda por palabra clave (default). 'graph' = recall basado en grafo: expande el subgrafo de entradas relacionadas desde las coincidencias (m\xE1s preciso, menos tokens)."),
28448
- hops: external_exports.number().optional().default(1).describe("Profundidad del grafo en modo 'graph' (1 o 2). Default 1.")
28550
+ hops: external_exports.number().optional().default(1).describe("Profundidad del grafo en modo 'graph' (1 o 2). Default 1."),
28551
+ compact: external_exports.boolean().optional().default(false).describe("Salida token-efficient: \xEDndices num\xE9ricos (1, 2), omite id/fecha/archivo (conserva tags), aristas como '->2', y trunca vecinos del grafo a un snippet. No muta el archivo .toon.")
28449
28552
  }
28450
28553
  },
28451
- async ({ query, category, from_date, to_date, mode, hops }) => {
28554
+ async ({ query, category, from_date, to_date, mode, hops, compact }) => {
28452
28555
  const data = readMemory();
28453
28556
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
28454
28557
  const normalize3 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
@@ -28471,12 +28574,20 @@ server.registerTool(
28471
28574
  return { content: [{ type: "text", text: `No se encontraron resultados para "${query}"` }] };
28472
28575
  }
28473
28576
  if (mode === "graph") {
28474
- const subgraph = graphRecall(data, query, { category, from_date, to_date, hops });
28475
- if (subgraph.length === 0) {
28577
+ const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops });
28578
+ if (detail.entries.length === 0) {
28476
28579
  return { content: [{ type: "text", text: `No se encontraron resultados para "${query}"` }] };
28477
28580
  }
28478
- bumpAccessed(subgraph.map((e) => e.id));
28479
- const formatted2 = subgraph.map((r) => {
28581
+ bumpAccessed(detail.entries.map((e) => e.id));
28582
+ if (compact) {
28583
+ const formatted3 = renderCompact(detail.entries, {
28584
+ adjacency: detail.adjacency,
28585
+ seeds: detail.seeds,
28586
+ snippetLen: 90
28587
+ });
28588
+ return { content: [{ type: "text", text: formatted3 }] };
28589
+ }
28590
+ const formatted2 = detail.entries.map((r) => {
28480
28591
  const links = r.links.length ? `
28481
28592
  links: ${r.links.join(", ")}` : "";
28482
28593
  return `[${r.category}] ${r.key} (${r.id})
@@ -28487,6 +28598,22 @@ server.registerTool(
28487
28598
  }
28488
28599
  const ranked = results.map((r) => ({ ...r, score: entryScore(r.date, r.accessed) })).sort((a, b) => b.score - a.score);
28489
28600
  bumpAccessed(ranked.map((r) => r.id));
28601
+ if (compact) {
28602
+ const entries = ranked.map((r) => ({
28603
+ id: r.id,
28604
+ category: r.cat,
28605
+ key: r.key,
28606
+ content: r.content,
28607
+ file: r.file,
28608
+ tags: r.tags ? r.tags.split(";").filter(Boolean) : [],
28609
+ date: r.date,
28610
+ ttl: "",
28611
+ accessed: r.accessed,
28612
+ links: []
28613
+ }));
28614
+ const formatted2 = renderCompact(entries);
28615
+ return { content: [{ type: "text", text: formatted2 }] };
28616
+ }
28490
28617
  const formatted = ranked.map((r) => `[${r.cat}] ${r.key} (${r.id})
28491
28618
  ${r.content}
28492
28619
  File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`).join("\n\n");
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "toon-memory",
3
- "version": "2.2.0",
4
- "description": "Persistent memory system for AI coding agents using TOON format (22% fewer tokens than JSON, measured)",
3
+ "version": "2.4.0",
4
+ "description": "MCP server giving AI coding agents offline, token-efficient persistent memory — recall decisions, patterns, and bugs across sessions with 68.5% fewer tokens than re-reading context. No LLM, no server; works with 15+ agents.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "toon-memory": "./bin/toon-memory.js"
@@ -24,6 +24,7 @@
24
24
  "test": "vitest run",
25
25
  "test:watch": "vitest",
26
26
  "bench": "node scripts/benchmark-toon.mjs",
27
+ "bench:impact": "node scripts/benchmark-impact.mjs",
27
28
  "prepublishOnly": "npm run build && npm test"
28
29
  },
29
30
  "dependencies": {
@@ -8,17 +8,17 @@ A persistent memory system for AI coding agents. It remembers decisions, pattern
8
8
 
9
9
  | Agent | Config File | Format | Hooks |
10
10
  |-------|-------------|--------|-------|
11
- | OpenCode | `.opencode/opencode.json` | MCP server | — |
11
+ | OpenCode | `.opencode/opencode.json` + `.opencode/plugins/toon-memory.ts` | Plugin | SessionStart (plugin, no top-level `hooks`) |
12
12
  | VS Code / Copilot | `.vscode/mcp.json` | MCP server | — |
13
- | Claude Code | `.claude/settings.json` | MCP server | SessionStart |
13
+ | Claude Code | `.claude/settings.json` | MCP server | SessionStart + PostToolUse + Stop |
14
14
  | Cursor | `.cursor/mcp.json` | MCP server | — |
15
15
  | Windsurf | `~/.codeium/windsurf/mcp_config.json` | MCP server | — |
16
16
  | Cline | `.cline/mcp.json` | MCP server | — |
17
17
  | Continue | `.continue/config.json` | MCP server | — |
18
- | Codex CLI | `.codex/config.toml` | TOML | SessionStart |
19
- | Gemini CLI | `.gemini/settings.json` | MCP server | SessionStart |
18
+ | Codex CLI | `.codex/config.toml` | TOML | SessionStart + PostToolUse + Stop (`[[hooks]] event=`) |
19
+ | Gemini CLI | `.gemini/settings.json` | MCP server | SessionStart + PostToolUse + Stop (`hooks.*`) |
20
20
  | Zed | `~/.config/zed/settings.json` | JSONC | — |
21
- | Antigravity | `.gemini/config/mcp_config.json` | MCP server | SessionStart |
21
+ | Antigravity | `.gemini/config/mcp_config.json` + `.gemini/config/hooks.json` | hooks.json | PreInvocation + PostToolUse + Stop (no SessionStart event) |
22
22
  | Aider | — | Instructions only | — |
23
23
  | KiloCode | `~/.kilocode/mcp_settings.json` | MCP server | — |
24
24
  | OpenClaw | `.openclaw.json` | MCP server | — |
@@ -1,10 +1,54 @@
1
1
  #!/usr/bin/env node
2
2
  import { dirname, join } from "path"
3
+ import { readFileSync } from "fs"
3
4
  import { fileURLToPath } from "url"
4
5
 
5
6
  const __dirname = dirname(fileURLToPath(import.meta.url))
6
7
  const args = process.argv.slice(2)
7
8
 
9
+ function getVersion(): string {
10
+ try {
11
+ const pkg = JSON.parse(readFileSync(join(__dirname, "..", "package.json"), "utf-8"))
12
+ return pkg.version || "unknown"
13
+ } catch {
14
+ return "unknown"
15
+ }
16
+ }
17
+
18
+ const HELP = `toon-memory — MCP memory server for AI coding agents
19
+
20
+ Usage:
21
+ toon-memory <command> [scope]
22
+
23
+ Commands:
24
+ init [local|global] Install memory tools + hooks for detected agents
25
+ status Show version, memory count, and agent config status
26
+ stats Show memory statistics
27
+ export [file] Export memory to a TOON/JSON file
28
+ import <file> Import memory from a TOON/JSON file
29
+ watch Watch memory file and re-render on change
30
+ uninstall Remove toon-memory from all agents
31
+ capture <on|off> Enable/disable activity capture hooks
32
+ upgrade Upgrade to the latest version
33
+
34
+ Options:
35
+ -v, --version Show version
36
+ -h, --help Show this help
37
+
38
+ MCP mode:
39
+ toon-memory mcp Run as an MCP server (stdio)
40
+ `
41
+
42
+ if (args[0] === "-v" || args[0] === "--version") {
43
+ console.log(getVersion())
44
+ process.exit(0)
45
+ }
46
+
47
+ if (args[0] === "-h" || args[0] === "--help") {
48
+ console.log(HELP)
49
+ process.exit(0)
50
+ }
51
+
8
52
  if (args[0] === "mcp") {
9
53
  await import(join(__dirname, "..", "mcp", "server.js"))
10
54
  } else {