toon-memory 2.1.0 → 2.2.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 CHANGED
@@ -18,6 +18,7 @@
18
18
  - [Supported Agents](#supported-agents)
19
19
  - [MCP Tools](#mcp-tools)
20
20
  - [Coordinación multi-sesión](#coordinación-multi-sesión)
21
+ - [Memory Graph (recall basado en grafo)](#memory-graph-recall-basado-en-grafo)
21
22
  - [Tips & Best Practices](#tips--best-practices)
22
23
  - [CLI Commands](#cli-commands)
23
24
  - [Configuration](#configuration)
@@ -77,6 +78,7 @@ Read [How toon-memory Makes Your AI Agent Smarter](https://luiggival08.github.io
77
78
  - **Tag inference** — Auto-detect tags from content when tags are empty
78
79
  - **Memory diff** — See what changed since your last session
79
80
  - **Related entries** — Auto-suggest related memories when saving
81
+ - **Memory graph** — Connect entries with `links`/`[[key]]` refs; `memory_recall` can expand a relationship-aware subgraph for more precise, lower-token recall (no embeddings, no LLM)
80
82
 
81
83
  ---
82
84
 
@@ -151,8 +153,8 @@ memory_remember # Save important decisions
151
153
 
152
154
  | Tool | Description |
153
155
  |------|-------------|
154
- | `memory_remember` | Save a decision, pattern, bug, or knowledge (with optional TTL and auto-tag inference) |
155
- | `memory_recall` | Search memory (use BEFORE reading files, filters expired TTL entries) |
156
+ | `memory_remember` | Save a decision, pattern, bug, or knowledge (optional TTL, auto-tag inference, and `links` to build the memory graph) |
157
+ | `memory_recall` | Search memory (use BEFORE reading files, filters expired TTL). `mode: "graph"` expands a relationship-aware subgraph for higher precision |
156
158
  | `memory_forget` | Remove an entry by key or id |
157
159
  | `memory_stats` | View memory state (including TTL stats) |
158
160
  | `memory_summary` | Save/retrieve file summaries |
@@ -354,6 +356,58 @@ memory_sessions({ conflictsOnly: false })
354
356
 
355
357
  ---
356
358
 
359
+ ## Memory Graph (recall basado en grafo)
360
+
361
+ When your memory grows, a flat keyword search can return either too much (every match) or the wrong context (no relationships). toon-memory can treat memory as a **lightweight knowledge graph** so recall returns the *right* entries with fewer tokens.
362
+
363
+ It's fully **deterministic and offline** — no embeddings, no vector DB, no LLM, no server. Edges come from two sources:
364
+
365
+ - **Explicit `links`** — keys you declare when saving an entry.
366
+ - **Implicit `[[key]]` refs** — any `[[some-key]]` mention inside the content.
367
+
368
+ ### How it works
369
+
370
+ 1. `memory_remember` stores `links` on the entry (space- or `;`-separated keys).
371
+ 2. `memory_recall({ mode: "graph" })` finds keyword matches (seeds), then expands the **ego-subgraph** up to `hops` (1 or 2) along the edges.
372
+ 3. Relevance propagates from the seeds to their neighbors, so a related decision or spec surfaces even if it doesn't contain the query word.
373
+ 4. The result set is capped (`limit`, default 6) → **smaller, more precise context** for the agent.
374
+
375
+ ### Remember with links
376
+
377
+ ```typescript
378
+ memory_remember({
379
+ category: "decision",
380
+ key: "risk-engine-priority",
381
+ content: "The engine prioritizes risk over speed (see [[risk-spec]]).",
382
+ file: "spec.md:10",
383
+ tags: "risk;spec",
384
+ links: "engine-arch" // explicit edge to another entry
385
+ })
386
+ // 🧠 Guardado: decision/risk-engine-priority (a1b2c3d4)
387
+ ```
388
+
389
+ ### Recall with graph mode
390
+
391
+ ```typescript
392
+ memory_recall({ query: "riesgo", mode: "graph", hops: 2 })
393
+ // [decision] risk-engine-priority (a1b2c3d4)
394
+ // The engine prioritizes risk over speed (see [[risk-spec]]).
395
+ // File: spec.md:10 | Tags: risk;spec | Date: 2026-07-01
396
+ // links: engine-arch
397
+ //
398
+ // [knowledge] risk-spec (a2b3c4d5)
399
+ // Risk specification for the engine.
400
+ // links: risk-engine-priority;engine-arch
401
+ //
402
+ // [pattern] engine-arch (e6f7g8h9)
403
+ // Engine architecture.
404
+ // links: risk-spec
405
+ ```
406
+
407
+ > **Tip:** Use `mode: "graph"` when a decision ripples across several entries (architecture, specs, related bugs). For isolated facts, the default `flat` mode is enough. The graph is built on read, so there's no extra index file to maintain.
408
+
409
+ ---
410
+
357
411
  ## Tips & Best Practices
358
412
 
359
413
  Here are some patterns that work well with toon-memory:
@@ -624,10 +678,10 @@ Add to `~/.config/zed/settings.json`:
624
678
 
625
679
  ```
626
680
  version: 1
627
- entries[3|]{id|category|key|content|file|tags|date|ttl}:
628
- a1b2c3d4|decision|use-zod|Use Zod for validation|src/types.ts|validation;types|2026-07-10|
629
- e5f6g7h8|pattern|pydantic-configs|Project uses Pydantic v2|config.py|python;patterns|2026-07-10|
630
- i9j0k1l2|bug|redis-pool-fix|Added max_connections=20|redis.ts|redis;fix|2026-07-10|7d
681
+ entries[3|]{id|category|key|content|file|tags|date|ttl|accessed|links}:
682
+ a1b2c3d4|decision|use-zod|Use Zod for validation|src/types.ts|validation;types|2026-07-10||0|
683
+ e5f6g7h8|pattern|pydantic-configs|Project uses Pydantic v2|config.py|python;patterns|2026-07-10||0|
684
+ i9j0k1l2|bug|redis-pool-fix|Added max_connections=20 (see [[use-zod]])|redis.ts|redis;fix|2026-07-10|7d|0|use-zod
631
685
  summaries:
632
686
  src/services/redis.ts: Redis connection pool with retry logic
633
687
  ```
@@ -760,11 +814,17 @@ toon-memory/
760
814
  │ │ ├── setup.ts # CLI commands
761
815
  │ │ └── toon-memory.ts # CLI runner
762
816
  │ ├── mcp/
763
- │ │ └── server.ts # MCP server (11 tools + 3 resources)
817
+ │ │ └── server.ts # MCP server (13 tools + 3 resources)
818
+ │ ├── lib/
819
+ │ │ ├── lock.ts # Advisory file lock + atomic write
820
+ │ │ ├── sessions.ts # Multi-session coordination
821
+ │ │ └── graph.ts # Memory graph (parse, build, graph recall)
764
822
  │ └── memory.ts # Custom tool (OpenCode)
765
823
  ├── tests/
766
824
  │ ├── cli.test.ts # CLI tests
767
- │ └── memory.test.ts # Memory tests
825
+ │ ├── memory.test.ts # Memory tests
826
+ │ ├── sessions.test.ts # Multi-session tests
827
+ │ └── graph.test.ts # Memory graph tests
768
828
  ├── .github/workflows/
769
829
  │ ├── ci.yml # CI (Node.js 20/22)
770
830
  │ └── publish.yml # Auto-publish on release
package/mcp/server.js CHANGED
@@ -16506,8 +16506,8 @@ var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => {
16506
16506
  }
16507
16507
  return count;
16508
16508
  }
16509
- function getFullPath(resolver, id = "", normalize2) {
16510
- if (normalize2 !== false) id = normalizeId(id);
16509
+ function getFullPath(resolver, id = "", normalize3) {
16510
+ if (normalize3 !== false) id = normalizeId(id);
16511
16511
  return _getFullPath(resolver, resolver.parse(id));
16512
16512
  }
16513
16513
  exports.getFullPath = getFullPath;
@@ -17602,7 +17602,7 @@ var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => {
17602
17602
  var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
17603
17603
  const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils();
17604
17604
  const { SCHEMES, getSchemeHandler } = require_schemes();
17605
- function normalize2(uri, options) {
17605
+ function normalize3(uri, options) {
17606
17606
  if (typeof uri === "string") uri = serialize(parse3(uri, options), options);
17607
17607
  else if (typeof uri === "object") uri = parse3(serialize(uri, options), options);
17608
17608
  return uri;
@@ -17780,7 +17780,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => {
17780
17780
  }
17781
17781
  const fastUri = {
17782
17782
  SCHEMES,
17783
- normalize: normalize2,
17783
+ normalize: normalize3,
17784
17784
  resolve,
17785
17785
  resolveComponent,
17786
17786
  equal,
@@ -27846,6 +27846,113 @@ function coordinationView(selfId) {
27846
27846
  return { active, conflicts, self };
27847
27847
  }
27848
27848
 
27849
+ // src/lib/graph.ts
27850
+ var isExpiredLocal = (ttl) => {
27851
+ if (!ttl) return false;
27852
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
27853
+ return ttl <= today;
27854
+ };
27855
+ var normalize = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
27856
+ var entryLines = (data) => data.split("\n").filter(
27857
+ (l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")
27858
+ );
27859
+ function parseEntries(data) {
27860
+ const out = [];
27861
+ for (const line of entryLines(data)) {
27862
+ const parts = line.trim().split("|");
27863
+ if (parts.length < 7) continue;
27864
+ const [id, category, key, content, file2, tags, date5, ttl, accessedRaw, linksRaw] = parts;
27865
+ out.push({
27866
+ id,
27867
+ category,
27868
+ key,
27869
+ content,
27870
+ file: file2 || "",
27871
+ tags: (tags || "").split(";").map((t) => t.trim()).filter(Boolean),
27872
+ date: date5 || "",
27873
+ ttl: ttl || "",
27874
+ accessed: accessedRaw ? parseInt(accessedRaw) || 0 : 0,
27875
+ links: (linksRaw || "").split(/[\s;]+/).map((t) => t.trim()).filter(Boolean)
27876
+ });
27877
+ }
27878
+ return out;
27879
+ }
27880
+ function buildGraph(entries) {
27881
+ const byKey = /* @__PURE__ */ new Map();
27882
+ for (const e of entries) {
27883
+ if (!byKey.has(e.key)) byKey.set(e.key, e);
27884
+ }
27885
+ const adj = /* @__PURE__ */ new Map();
27886
+ const link = (a, b) => {
27887
+ if (a === b) return;
27888
+ if (!byKey.has(a) || !byKey.has(b)) return;
27889
+ if (!adj.has(a)) adj.set(a, /* @__PURE__ */ new Set());
27890
+ adj.get(a).add(b);
27891
+ if (!adj.has(b)) adj.set(b, /* @__PURE__ */ new Set());
27892
+ adj.get(b).add(a);
27893
+ };
27894
+ for (const e of entries) {
27895
+ for (const l of e.links) link(e.key, l);
27896
+ const refs = e.content.match(/\[\[([\w-]+)\]\]/g) || [];
27897
+ for (const r of refs) link(e.key, r.slice(2, -2));
27898
+ }
27899
+ const adjacency = /* @__PURE__ */ new Map();
27900
+ for (const [k, v] of adj) adjacency.set(k, [...v]);
27901
+ return { adjacency, byKey };
27902
+ }
27903
+ var importance = (e) => {
27904
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
27905
+ const days = (Date.now() - (/* @__PURE__ */ new Date(`${e.date || today}T00:00:00`)).getTime()) / 864e5;
27906
+ const recency = Math.max(0, 30 - days) / 30;
27907
+ const freq = Math.min(1, e.accessed / 5);
27908
+ return recency * 0.6 + freq * 0.4;
27909
+ };
27910
+ function graphRecall(data, query, opts = {}) {
27911
+ const entries = parseEntries(data);
27912
+ const { adjacency, byKey } = buildGraph(entries);
27913
+ const hops = Math.max(1, Math.min(2, opts.hops ?? 1));
27914
+ const category = opts.category || "";
27915
+ const from_date = opts.from_date || "";
27916
+ const to_date = opts.to_date || "";
27917
+ const queryTokens = normalize(query).split(" ").filter(Boolean);
27918
+ const seedScore = /* @__PURE__ */ new Map();
27919
+ for (const e of entries) {
27920
+ if (category && e.category !== category) continue;
27921
+ if (from_date && e.date < from_date) continue;
27922
+ if (to_date && e.date > to_date) continue;
27923
+ if (e.ttl && isExpiredLocal(e.ttl)) continue;
27924
+ const searchStr = normalize(
27925
+ `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
27926
+ );
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);
27954
+ }
27955
+
27849
27956
  // src/mcp/server.ts
27850
27957
  var __dirname = dirname(fileURLToPath(import.meta.url));
27851
27958
  var MEMORY_DIR = join2(process.cwd(), ".toon-memory", "memory");
@@ -27882,7 +27989,7 @@ function ensureMemoryDir() {
27882
27989
  function ensureMemoryFile() {
27883
27990
  ensureMemoryDir();
27884
27991
  if (!existsSync3(MEMORY_FILE)) {
27885
- writeFileSync3(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed}:\n");
27992
+ writeFileSync3(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links}:\n");
27886
27993
  }
27887
27994
  }
27888
27995
  function encrypt(text, key) {
@@ -28008,18 +28115,18 @@ function parseRelativeDate(since) {
28008
28115
  const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
28009
28116
  return today;
28010
28117
  }
28011
- var normalize = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28118
+ var normalize2 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28012
28119
  function findRelatedEntries(text, excludeKey = "", limit = 3) {
28013
28120
  const data = readMemory();
28014
28121
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
28015
- const queryTokens = normalize(text).split(" ").filter(Boolean);
28122
+ const queryTokens = normalize2(text).split(" ").filter(Boolean);
28016
28123
  const scored = lines.map((line) => {
28017
28124
  const trimmed = line.trim();
28018
28125
  const parts = trimmed.split("|");
28019
28126
  if (parts.length < 7) return null;
28020
28127
  const [id, cat, key, content, file2, tags, date5] = parts;
28021
28128
  if (key === excludeKey) return null;
28022
- const searchStr = normalize(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
28129
+ const searchStr = normalize2(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
28023
28130
  let score = 0;
28024
28131
  for (const token of queryTokens) {
28025
28132
  if (searchStr.includes(token)) score++;
@@ -28077,9 +28184,9 @@ function archiveOldEntries(opts = {}) {
28077
28184
  const cutoff = new Date(today);
28078
28185
  cutoff.setDate(cutoff.getDate() - ARCHIVE_DAYS);
28079
28186
  const cutoffStr = cutoff.toISOString().split("T")[0];
28080
- const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0);
28187
+ const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0);
28081
28188
  const toArchive = /* @__PURE__ */ new Set();
28082
- entryLines.forEach((line, idx) => {
28189
+ entryLines2.forEach((line, idx) => {
28083
28190
  const parts = line.trim().split("|");
28084
28191
  if (parts.length < 7) return;
28085
28192
  const date5 = parts[6];
@@ -28087,16 +28194,16 @@ function archiveOldEntries(opts = {}) {
28087
28194
  if (date5 < cutoffStr || ttl && isExpired(ttl)) toArchive.add(idx);
28088
28195
  });
28089
28196
  if (opts.trimToMax) {
28090
- const remaining = entryLines.length - toArchive.size;
28197
+ const remaining = entryLines2.length - toArchive.size;
28091
28198
  if (remaining > MAX_ENTRIES) {
28092
28199
  const need = remaining - MAX_ENTRIES;
28093
- const candidates = entryLines.map((line, idx) => ({ idx, score: entryScoreForLine(line) })).filter((c) => !toArchive.has(c.idx)).sort((a, b) => a.score - b.score);
28200
+ const candidates = entryLines2.map((line, idx) => ({ idx, score: entryScoreForLine(line) })).filter((c) => !toArchive.has(c.idx)).sort((a, b) => a.score - b.score);
28094
28201
  for (let i = 0; i < need && i < candidates.length; i++) toArchive.add(candidates[i].idx);
28095
28202
  }
28096
28203
  }
28097
- if (toArchive.size === 0) return { archived: 0, kept: entryLines.length };
28098
- const toArchiveLines = entryLines.filter((_, idx) => toArchive.has(idx)).map((l) => l.trim());
28099
- const toKeepLines = entryLines.filter((_, idx) => !toArchive.has(idx)).map((l) => l.trim());
28204
+ if (toArchive.size === 0) return { archived: 0, kept: entryLines2.length };
28205
+ const toArchiveLines = entryLines2.filter((_, idx) => toArchive.has(idx)).map((l) => l.trim());
28206
+ const toKeepLines = entryLines2.filter((_, idx) => !toArchive.has(idx)).map((l) => l.trim());
28100
28207
  let archiveContent = "";
28101
28208
  if (existsSync3(ARCHIVE_FILE)) {
28102
28209
  archiveContent = readFileSync3(ARCHIVE_FILE, "utf-8");
@@ -28138,8 +28245,8 @@ function pruneExpiredEntries() {
28138
28245
  const lines = data.split("\n");
28139
28246
  const headerIdx = lines.findIndex((l) => l.startsWith("entries["));
28140
28247
  if (headerIdx === -1) return;
28141
- const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
28142
- const kept = entryLines.filter((l) => {
28248
+ const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
28249
+ const kept = entryLines2.filter((l) => {
28143
28250
  const parts = l.trim().split("|");
28144
28251
  if (parts.length < 8) return true;
28145
28252
  const ttl = parts[7] || "";
@@ -28164,11 +28271,11 @@ function consolidateEntries() {
28164
28271
  const lines = data.split("\n");
28165
28272
  const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
28166
28273
  if (headerIdx === -1) return { removed: 0, kept: 0, duplicates: [] };
28167
- const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
28274
+ const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
28168
28275
  const seen = /* @__PURE__ */ new Map();
28169
28276
  const order = [];
28170
28277
  const duplicates = [];
28171
- for (const line of entryLines) {
28278
+ for (const line of entryLines2) {
28172
28279
  const parts = line.trim().split("|");
28173
28280
  if (parts.length < 3) {
28174
28281
  order.push(line.trim());
@@ -28189,7 +28296,7 @@ function consolidateEntries() {
28189
28296
  return { removed: duplicates.length, kept: order.length, duplicates };
28190
28297
  }
28191
28298
  var server = new McpServer(
28192
- { name: "toon-memory", version: "2.1.0" },
28299
+ { name: "toon-memory", version: "2.2.0" },
28193
28300
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
28194
28301
  );
28195
28302
  server.registerResource(
@@ -28253,10 +28360,11 @@ server.registerTool(
28253
28360
  content: external_exports.string().describe("Contenido detallado del hecho"),
28254
28361
  file: external_exports.string().optional().default("").describe("Archivo o l\xEDnea relacionada (ej: spec.md:145)"),
28255
28362
  tags: external_exports.string().optional().default("").describe("Tags separados por punto y coma (ej: risk;spec)"),
28256
- ttl: external_exports.string().optional().default("").describe("Time to live (ej: 7d, 2026-07-17). Vac\xEDo = sin expiraci\xF3n")
28363
+ ttl: external_exports.string().optional().default("").describe("Time to live (ej: 7d, 2026-07-17). Vac\xEDo = sin expiraci\xF3n"),
28364
+ links: external_exports.string().optional().default("").describe("Entradas relacionadas por key, separadas por espacio o ';' (ej: risk-spec engine-arch). Construye aristas del grafo de memoria.")
28257
28365
  }
28258
28366
  },
28259
- async ({ category, key, content, file: file2, tags, ttl }) => {
28367
+ async ({ category, key, content, file: file2, tags, ttl, links }) => {
28260
28368
  const data = readMemory();
28261
28369
  const newId = generateId();
28262
28370
  const date5 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
@@ -28282,7 +28390,9 @@ server.registerTool(
28282
28390
  const entryId = existingIdx !== -1 ? existingId : newId;
28283
28391
  const resolvedTtl = parseTTL(ttl);
28284
28392
  const resolvedTags = tags ? tags : inferTags(content, key);
28285
- const newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0`;
28393
+ const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : [];
28394
+ const resolvedLinks = links ? links.split(/[\s;]+/).filter(Boolean).join(" ") : existingParts[9] || "";
28395
+ const newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0|${resolvedLinks}`;
28286
28396
  let action = "Guardado";
28287
28397
  const tagsInferred = !tags && resolvedTags ? true : false;
28288
28398
  if (existingIdx !== -1) {
@@ -28333,14 +28443,16 @@ server.registerTool(
28333
28443
  query: external_exports.string().describe("Texto a buscar"),
28334
28444
  category: external_exports.string().optional().default("").describe("Filtrar por categor\xEDa (vac\xEDo = todos)"),
28335
28445
  from_date: external_exports.string().optional().default("").describe("Fecha inicio filtro (YYYY-MM-DD)"),
28336
- to_date: external_exports.string().optional().default("").describe("Fecha fin filtro (YYYY-MM-DD)")
28446
+ to_date: external_exports.string().optional().default("").describe("Fecha fin filtro (YYYY-MM-DD)"),
28447
+ 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.")
28337
28449
  }
28338
28450
  },
28339
- async ({ query, category, from_date, to_date }) => {
28451
+ async ({ query, category, from_date, to_date, mode, hops }) => {
28340
28452
  const data = readMemory();
28341
28453
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
28342
- const normalize2 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28343
- const queryTokens = normalize2(query).split(" ").filter(Boolean);
28454
+ const normalize3 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28455
+ const queryTokens = normalize3(query).split(" ").filter(Boolean);
28344
28456
  const results = lines.map((line) => {
28345
28457
  const trimmed = line.trim();
28346
28458
  const parts = trimmed.split("|");
@@ -28350,7 +28462,7 @@ server.registerTool(
28350
28462
  if (from_date && date5 < from_date) return null;
28351
28463
  if (to_date && date5 > to_date) return null;
28352
28464
  if (ttl && isExpired(ttl)) return null;
28353
- const searchStr = normalize2(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
28465
+ const searchStr = normalize3(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
28354
28466
  if (!queryTokens.every((token) => searchStr.includes(token))) return null;
28355
28467
  const accessed = accessedRaw ? parseInt(accessedRaw) || 0 : 0;
28356
28468
  return { id, cat, key, content, file: file2, tags, date: date5, accessed };
@@ -28358,6 +28470,21 @@ server.registerTool(
28358
28470
  if (results.length === 0) {
28359
28471
  return { content: [{ type: "text", text: `No se encontraron resultados para "${query}"` }] };
28360
28472
  }
28473
+ if (mode === "graph") {
28474
+ const subgraph = graphRecall(data, query, { category, from_date, to_date, hops });
28475
+ if (subgraph.length === 0) {
28476
+ return { content: [{ type: "text", text: `No se encontraron resultados para "${query}"` }] };
28477
+ }
28478
+ bumpAccessed(subgraph.map((e) => e.id));
28479
+ const formatted2 = subgraph.map((r) => {
28480
+ const links = r.links.length ? `
28481
+ links: ${r.links.join(", ")}` : "";
28482
+ return `[${r.category}] ${r.key} (${r.id})
28483
+ ${r.content}
28484
+ File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}`;
28485
+ }).join("\n\n");
28486
+ return { content: [{ type: "text", text: formatted2 }] };
28487
+ }
28361
28488
  const ranked = results.map((r) => ({ ...r, score: entryScore(r.date, r.accessed) })).sort((a, b) => b.score - a.score);
28362
28489
  bumpAccessed(ranked.map((r) => r.id));
28363
28490
  const formatted = ranked.map((r) => `[${r.cat}] ${r.key} (${r.id})
@@ -28382,16 +28509,16 @@ server.registerTool(
28382
28509
  if (headerIdx === -1) {
28383
28510
  return { content: [{ type: "text", text: "No hay entradas en memoria" }] };
28384
28511
  }
28385
- const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
28386
- const filtered = entryLines.filter((l) => {
28512
+ const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
28513
+ const filtered = entryLines2.filter((l) => {
28387
28514
  const parts = l.trim().split("|");
28388
28515
  return parts[0] !== key && parts[2] !== key;
28389
28516
  });
28390
- const removed = entryLines.length - filtered.length;
28517
+ const removed = entryLines2.length - filtered.length;
28391
28518
  const match = lines[headerIdx].match(/\[(\d+)\|/);
28392
28519
  const count = match ? parseInt(match[1]) : 0;
28393
28520
  lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`);
28394
- lines.splice(headerIdx + 1, entryLines.length, ...filtered.map((l) => ` ${l.trim()}`));
28521
+ lines.splice(headerIdx + 1, entryLines2.length, ...filtered.map((l) => ` ${l.trim()}`));
28395
28522
  writeMemory(lines.join("\n"));
28396
28523
  return {
28397
28524
  content: [{ type: "text", text: `"${key}" eliminado. Quedan ${count - removed} entradas.` }]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "toon-memory",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Persistent memory system for AI coding agents using TOON format (22% fewer tokens than JSON, measured)",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,200 @@
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
+
13
+ export interface GraphEntry {
14
+ id: string
15
+ category: string
16
+ key: string
17
+ content: string
18
+ file: string
19
+ tags: string[]
20
+ date: string
21
+ ttl: string
22
+ accessed: number
23
+ /** Explicit outgoing links declared on the entry. */
24
+ links: string[]
25
+ }
26
+
27
+ export interface MemoryGraph {
28
+ /** key -> connected keys (undirected, deduped, only keys that exist). */
29
+ adjacency: Map<string, string[]>
30
+ /** key -> entry (first occurrence wins on duplicate keys). */
31
+ byKey: Map<string, GraphEntry>
32
+ }
33
+
34
+ const isExpiredLocal = (ttl: string): boolean => {
35
+ if (!ttl) return false
36
+ const today = new Date().toISOString().split("T")[0]
37
+ return ttl <= today
38
+ }
39
+
40
+ const normalize = (s: string): string =>
41
+ s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
42
+
43
+ const entryLines = (data: string): string[] =>
44
+ data
45
+ .split("\n")
46
+ .filter(
47
+ (l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")
48
+ )
49
+
50
+ /**
51
+ * Parse TOON memory content into structured entries.
52
+ * Tolerant of the trailing `links` field (absent on older entries).
53
+ */
54
+ export function parseEntries(data: string): GraphEntry[] {
55
+ const out: GraphEntry[] = []
56
+ for (const line of entryLines(data)) {
57
+ const parts = line.trim().split("|")
58
+ if (parts.length < 7) continue
59
+ const [id, category, key, content, file, tags, date, ttl, accessedRaw, linksRaw] =
60
+ parts
61
+ out.push({
62
+ id,
63
+ category,
64
+ key,
65
+ content,
66
+ file: file || "",
67
+ tags: (tags || "")
68
+ .split(";")
69
+ .map((t) => t.trim())
70
+ .filter(Boolean),
71
+ date: date || "",
72
+ ttl: ttl || "",
73
+ accessed: accessedRaw ? parseInt(accessedRaw) || 0 : 0,
74
+ links: (linksRaw || "")
75
+ .split(/[\s;]+/)
76
+ .map((t) => t.trim())
77
+ .filter(Boolean),
78
+ })
79
+ }
80
+ return out
81
+ }
82
+
83
+ /**
84
+ * Build the adjacency graph from explicit links and implicit `[[key]]` refs.
85
+ * Edges are undirected and only connect keys that actually exist.
86
+ */
87
+ export function buildGraph(entries: GraphEntry[]): MemoryGraph {
88
+ const byKey = new Map<string, GraphEntry>()
89
+ for (const e of entries) {
90
+ if (!byKey.has(e.key)) byKey.set(e.key, e)
91
+ }
92
+
93
+ const adj = new Map<string, Set<string>>()
94
+ const link = (a: string, b: string): void => {
95
+ if (a === b) return
96
+ if (!byKey.has(a) || !byKey.has(b)) return
97
+ if (!adj.has(a)) adj.set(a, new Set())
98
+ adj.get(a)!.add(b)
99
+ if (!adj.has(b)) adj.set(b, new Set())
100
+ adj.get(b)!.add(a)
101
+ }
102
+
103
+ for (const e of entries) {
104
+ for (const l of e.links) link(e.key, l)
105
+ const refs = e.content.match(/\[\[([\w-]+)\]\]/g) || []
106
+ for (const r of refs) link(e.key, r.slice(2, -2))
107
+ }
108
+
109
+ const adjacency = new Map<string, string[]>()
110
+ for (const [k, v] of adj) adjacency.set(k, [...v])
111
+ return { adjacency, byKey }
112
+ }
113
+
114
+ export interface GraphRecallOpts {
115
+ category?: string
116
+ from_date?: string
117
+ to_date?: string
118
+ /** Graph traversal depth from matched seeds (1 or 2). Default 1. */
119
+ hops?: number
120
+ /** Max entries returned (keeps token cost low). Default 6. */
121
+ limit?: number
122
+ }
123
+
124
+ const importance = (e: GraphEntry): number => {
125
+ const today = new Date().toISOString().split("T")[0]
126
+ const days =
127
+ (Date.now() - new Date(`${e.date || today}T00:00:00`).getTime()) / 86400000
128
+ const recency = Math.max(0, 30 - days) / 30
129
+ const freq = Math.min(1, e.accessed / 5)
130
+ return recency * 0.6 + freq * 0.4
131
+ }
132
+
133
+ /**
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.
136
+ * Falls back to top-by-importance when the query matches nothing.
137
+ */
138
+ export function graphRecall(
139
+ data: string,
140
+ query: string,
141
+ opts: GraphRecallOpts = {}
142
+ ): GraphEntry[] {
143
+ const entries = parseEntries(data)
144
+ const { adjacency, byKey } = buildGraph(entries)
145
+ const hops = Math.max(1, Math.min(2, opts.hops ?? 1))
146
+ const category = opts.category || ""
147
+ const from_date = opts.from_date || ""
148
+ const to_date = opts.to_date || ""
149
+
150
+ const queryTokens = normalize(query)
151
+ .split(" ")
152
+ .filter(Boolean)
153
+
154
+ const seedScore = new Map<string, number>()
155
+ for (const e of entries) {
156
+ if (category && e.category !== category) continue
157
+ if (from_date && e.date < from_date) continue
158
+ if (to_date && e.date > to_date) continue
159
+ if (e.ttl && isExpiredLocal(e.ttl)) continue
160
+ const searchStr = normalize(
161
+ `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
162
+ )
163
+ if (queryTokens.length > 0 && !queryTokens.every((t) => searchStr.includes(t)))
164
+ continue
165
+ seedScore.set(e.key, importance(e) + 1.0)
166
+ }
167
+
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)
173
+ }
174
+
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
+ }
187
+ }
188
+
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)
198
+
199
+ return scored.slice(0, opts.limit ?? 6).map((x) => x.e)
200
+ }
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 { graphRecall } from "../lib/graph"
10
11
 
11
12
  const __dirname = dirname(fileURLToPath(import.meta.url))
12
13
 
@@ -105,7 +106,7 @@ function ensureMemoryDir(): void {
105
106
  function ensureMemoryFile(): void {
106
107
  ensureMemoryDir()
107
108
  if (!existsSync(MEMORY_FILE)) {
108
- writeFileSync(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed}:\n")
109
+ writeFileSync(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links}:\n")
109
110
  }
110
111
  }
111
112
 
@@ -578,7 +579,7 @@ function consolidateEntries(): { removed: number; kept: number; duplicates: stri
578
579
  }
579
580
 
580
581
  const server = new McpServer(
581
- { name: "toon-memory", version: "2.1.0" },
582
+ { name: "toon-memory", version: "2.2.0" },
582
583
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
583
584
  )
584
585
 
@@ -671,9 +672,10 @@ server.registerTool(
671
672
  file: z.string().optional().default("").describe("Archivo o línea relacionada (ej: spec.md:145)"),
672
673
  tags: z.string().optional().default("").describe("Tags separados por punto y coma (ej: risk;spec)"),
673
674
  ttl: z.string().optional().default("").describe("Time to live (ej: 7d, 2026-07-17). Vacío = sin expiración"),
675
+ 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
676
  },
675
677
  },
676
- async ({ category, key, content, file, tags, ttl }) => {
678
+ async ({ category, key, content, file, tags, ttl, links }) => {
677
679
  const data = readMemory()
678
680
  const newId = generateId()
679
681
  const date = new Date().toISOString().split("T")[0]
@@ -703,7 +705,12 @@ server.registerTool(
703
705
  const entryId = existingIdx !== -1 ? existingId : newId
704
706
  const resolvedTtl = parseTTL(ttl)
705
707
  const resolvedTags = tags ? tags : inferTags(content, key)
706
- const newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|0`
708
+ // Preserve existing links on upsert unless new ones are provided.
709
+ const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : []
710
+ const resolvedLinks = links
711
+ ? links.split(/[\s;]+/).filter(Boolean).join(" ")
712
+ : existingParts[9] || ""
713
+ const newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|0|${resolvedLinks}`
707
714
  let action = "Guardado"
708
715
  const tagsInferred = !tags && resolvedTags ? true : false
709
716
 
@@ -769,9 +776,11 @@ server.registerTool(
769
776
  category: z.string().optional().default("").describe("Filtrar por categoría (vacío = todos)"),
770
777
  from_date: z.string().optional().default("").describe("Fecha inicio filtro (YYYY-MM-DD)"),
771
778
  to_date: z.string().optional().default("").describe("Fecha fin filtro (YYYY-MM-DD)"),
779
+ 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
+ hops: z.number().optional().default(1).describe("Profundidad del grafo en modo 'graph' (1 o 2). Default 1."),
772
781
  },
773
782
  },
774
- async ({ query, category, from_date, to_date }) => {
783
+ async ({ query, category, from_date, to_date, mode, hops }) => {
775
784
  const data = readMemory()
776
785
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
777
786
 
@@ -801,6 +810,23 @@ server.registerTool(
801
810
  return { content: [{ type: "text" as const, text: `No se encontraron resultados para "${query}"` }] }
802
811
  }
803
812
 
813
+ // Graph mode: expand the ego-subgraph from keyword matches and return the
814
+ // focused, relationship-aware result set (fewer tokens, higher precision).
815
+ if (mode === "graph") {
816
+ const subgraph = graphRecall(data, query, { category, from_date, to_date, hops })
817
+ if (subgraph.length === 0) {
818
+ return { content: [{ type: "text" as const, text: `No se encontraron resultados para "${query}"` }] }
819
+ }
820
+ bumpAccessed(subgraph.map((e) => e.id))
821
+ const formatted = subgraph
822
+ .map((r) => {
823
+ const links = r.links.length ? `\n links: ${r.links.join(", ")}` : ""
824
+ return `[${r.category}] ${r.key} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}`
825
+ })
826
+ .join("\n\n")
827
+ return { content: [{ type: "text" as const, text: formatted }] }
828
+ }
829
+
804
830
  // Rank by importance (recency + access frequency), then bump access counts.
805
831
  const ranked = results
806
832
  .map((r) => ({ ...r, score: entryScore(r.date, r.accessed) }))