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/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,200 @@ 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
+ 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 = {}) {
27957
+ const entries = parseEntries(data);
27958
+ const { adjacency, byKey } = buildGraph(entries);
27959
+ const hops = Math.max(1, Math.min(2, opts.hops ?? 1));
27960
+ const category = opts.category || "";
27961
+ const from_date = opts.from_date || "";
27962
+ const to_date = opts.to_date || "";
27963
+ const qTokens = tokenize(query);
27964
+ const bm25 = bm25Scores(entries, query);
27965
+ const cent = centrality(adjacency);
27966
+ const seedKeys = /* @__PURE__ */ new Set();
27967
+ for (const e of entries) {
27968
+ if (category && e.category !== category) continue;
27969
+ if (from_date && e.date < from_date) continue;
27970
+ if (to_date && e.date > to_date) continue;
27971
+ if (e.ttl && isExpiredLocal(e.ttl)) continue;
27972
+ const text = normalize(
27973
+ `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
27974
+ );
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");
28041
+ }
28042
+
27849
28043
  // src/mcp/server.ts
27850
28044
  var __dirname = dirname(fileURLToPath(import.meta.url));
27851
28045
  var MEMORY_DIR = join2(process.cwd(), ".toon-memory", "memory");
@@ -27871,7 +28065,15 @@ function loadConfig() {
27871
28065
  }
27872
28066
  function saveConfig(config2) {
27873
28067
  ensureMemoryDir();
27874
- 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));
27875
28077
  }
27876
28078
  function getKey() {
27877
28079
  return process.env.TOON_MEMORY_KEY;
@@ -27882,7 +28084,7 @@ function ensureMemoryDir() {
27882
28084
  function ensureMemoryFile() {
27883
28085
  ensureMemoryDir();
27884
28086
  if (!existsSync3(MEMORY_FILE)) {
27885
- writeFileSync3(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed}:\n");
28087
+ writeFileSync3(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links}:\n");
27886
28088
  }
27887
28089
  }
27888
28090
  function encrypt(text, key) {
@@ -27980,7 +28182,7 @@ var TAG_VOCABULARY = {
27980
28182
  "payment": ["payment", "stripe", "billing", "invoice", "checkout", "subscription"],
27981
28183
  "webhook": ["webhook", "callback", "event", "listener", "hook"]
27982
28184
  };
27983
- function inferTags(content, key) {
28185
+ function inferTags(content, key, vocab) {
27984
28186
  const text = `${key} ${content}`.toLowerCase();
27985
28187
  const matched = [];
27986
28188
  for (const [tag, keywords] of Object.entries(TAG_VOCABULARY)) {
@@ -27988,6 +28190,13 @@ function inferTags(content, key) {
27988
28190
  matched.push(tag);
27989
28191
  }
27990
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
+ }
27991
28200
  return matched.join(";");
27992
28201
  }
27993
28202
  function parseRelativeDate(since) {
@@ -28008,18 +28217,18 @@ function parseRelativeDate(since) {
28008
28217
  const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
28009
28218
  return today;
28010
28219
  }
28011
- var normalize = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28220
+ var normalize2 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28012
28221
  function findRelatedEntries(text, excludeKey = "", limit = 3) {
28013
28222
  const data = readMemory();
28014
28223
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
28015
- const queryTokens = normalize(text).split(" ").filter(Boolean);
28224
+ const queryTokens = normalize2(text).split(" ").filter(Boolean);
28016
28225
  const scored = lines.map((line) => {
28017
28226
  const trimmed = line.trim();
28018
28227
  const parts = trimmed.split("|");
28019
28228
  if (parts.length < 7) return null;
28020
28229
  const [id, cat, key, content, file2, tags, date5] = parts;
28021
28230
  if (key === excludeKey) return null;
28022
- const searchStr = normalize(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
28231
+ const searchStr = normalize2(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
28023
28232
  let score = 0;
28024
28233
  for (const token of queryTokens) {
28025
28234
  if (searchStr.includes(token)) score++;
@@ -28077,9 +28286,9 @@ function archiveOldEntries(opts = {}) {
28077
28286
  const cutoff = new Date(today);
28078
28287
  cutoff.setDate(cutoff.getDate() - ARCHIVE_DAYS);
28079
28288
  const cutoffStr = cutoff.toISOString().split("T")[0];
28080
- const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0);
28289
+ const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0);
28081
28290
  const toArchive = /* @__PURE__ */ new Set();
28082
- entryLines.forEach((line, idx) => {
28291
+ entryLines2.forEach((line, idx) => {
28083
28292
  const parts = line.trim().split("|");
28084
28293
  if (parts.length < 7) return;
28085
28294
  const date5 = parts[6];
@@ -28087,16 +28296,16 @@ function archiveOldEntries(opts = {}) {
28087
28296
  if (date5 < cutoffStr || ttl && isExpired(ttl)) toArchive.add(idx);
28088
28297
  });
28089
28298
  if (opts.trimToMax) {
28090
- const remaining = entryLines.length - toArchive.size;
28299
+ const remaining = entryLines2.length - toArchive.size;
28091
28300
  if (remaining > MAX_ENTRIES) {
28092
28301
  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);
28302
+ const candidates = entryLines2.map((line, idx) => ({ idx, score: entryScoreForLine(line) })).filter((c) => !toArchive.has(c.idx)).sort((a, b) => a.score - b.score);
28094
28303
  for (let i = 0; i < need && i < candidates.length; i++) toArchive.add(candidates[i].idx);
28095
28304
  }
28096
28305
  }
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());
28306
+ if (toArchive.size === 0) return { archived: 0, kept: entryLines2.length };
28307
+ const toArchiveLines = entryLines2.filter((_, idx) => toArchive.has(idx)).map((l) => l.trim());
28308
+ const toKeepLines = entryLines2.filter((_, idx) => !toArchive.has(idx)).map((l) => l.trim());
28100
28309
  let archiveContent = "";
28101
28310
  if (existsSync3(ARCHIVE_FILE)) {
28102
28311
  archiveContent = readFileSync3(ARCHIVE_FILE, "utf-8");
@@ -28138,8 +28347,8 @@ function pruneExpiredEntries() {
28138
28347
  const lines = data.split("\n");
28139
28348
  const headerIdx = lines.findIndex((l) => l.startsWith("entries["));
28140
28349
  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) => {
28350
+ const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
28351
+ const kept = entryLines2.filter((l) => {
28143
28352
  const parts = l.trim().split("|");
28144
28353
  if (parts.length < 8) return true;
28145
28354
  const ttl = parts[7] || "";
@@ -28164,11 +28373,11 @@ function consolidateEntries() {
28164
28373
  const lines = data.split("\n");
28165
28374
  const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l));
28166
28375
  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:"));
28376
+ const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
28168
28377
  const seen = /* @__PURE__ */ new Map();
28169
28378
  const order = [];
28170
28379
  const duplicates = [];
28171
- for (const line of entryLines) {
28380
+ for (const line of entryLines2) {
28172
28381
  const parts = line.trim().split("|");
28173
28382
  if (parts.length < 3) {
28174
28383
  order.push(line.trim());
@@ -28189,7 +28398,7 @@ function consolidateEntries() {
28189
28398
  return { removed: duplicates.length, kept: order.length, duplicates };
28190
28399
  }
28191
28400
  var server = new McpServer(
28192
- { name: "toon-memory", version: "2.1.0" },
28401
+ { name: "toon-memory", version: "2.3.0" },
28193
28402
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
28194
28403
  );
28195
28404
  server.registerResource(
@@ -28253,10 +28462,11 @@ server.registerTool(
28253
28462
  content: external_exports.string().describe("Contenido detallado del hecho"),
28254
28463
  file: external_exports.string().optional().default("").describe("Archivo o l\xEDnea relacionada (ej: spec.md:145)"),
28255
28464
  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")
28465
+ ttl: external_exports.string().optional().default("").describe("Time to live (ej: 7d, 2026-07-17). Vac\xEDo = sin expiraci\xF3n"),
28466
+ 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
28467
  }
28258
28468
  },
28259
- async ({ category, key, content, file: file2, tags, ttl }) => {
28469
+ async ({ category, key, content, file: file2, tags, ttl, links }) => {
28260
28470
  const data = readMemory();
28261
28471
  const newId = generateId();
28262
28472
  const date5 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
@@ -28281,8 +28491,10 @@ server.registerTool(
28281
28491
  }
28282
28492
  const entryId = existingIdx !== -1 ? existingId : newId;
28283
28493
  const resolvedTtl = parseTTL(ttl);
28284
- const resolvedTags = tags ? tags : inferTags(content, key);
28285
- const newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0`;
28494
+ const resolvedTags = tags ? tags : inferTags(content, key, loadConfig().vocab);
28495
+ const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : [];
28496
+ const resolvedLinks = links ? links.split(/[\s;]+/).filter(Boolean).join(" ") : existingParts[9] || "";
28497
+ const newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0|${resolvedLinks}`;
28286
28498
  let action = "Guardado";
28287
28499
  const tagsInferred = !tags && resolvedTags ? true : false;
28288
28500
  if (existingIdx !== -1) {
@@ -28333,14 +28545,17 @@ server.registerTool(
28333
28545
  query: external_exports.string().describe("Texto a buscar"),
28334
28546
  category: external_exports.string().optional().default("").describe("Filtrar por categor\xEDa (vac\xEDo = todos)"),
28335
28547
  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)")
28548
+ to_date: external_exports.string().optional().default("").describe("Fecha fin filtro (YYYY-MM-DD)"),
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)."),
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.")
28337
28552
  }
28338
28553
  },
28339
- async ({ query, category, from_date, to_date }) => {
28554
+ async ({ query, category, from_date, to_date, mode, hops, compact }) => {
28340
28555
  const data = readMemory();
28341
28556
  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);
28557
+ const normalize3 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
28558
+ const queryTokens = normalize3(query).split(" ").filter(Boolean);
28344
28559
  const results = lines.map((line) => {
28345
28560
  const trimmed = line.trim();
28346
28561
  const parts = trimmed.split("|");
@@ -28350,7 +28565,7 @@ server.registerTool(
28350
28565
  if (from_date && date5 < from_date) return null;
28351
28566
  if (to_date && date5 > to_date) return null;
28352
28567
  if (ttl && isExpired(ttl)) return null;
28353
- const searchStr = normalize2(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
28568
+ const searchStr = normalize3(`${id} ${cat} ${key} ${content} ${file2} ${tags}`);
28354
28569
  if (!queryTokens.every((token) => searchStr.includes(token))) return null;
28355
28570
  const accessed = accessedRaw ? parseInt(accessedRaw) || 0 : 0;
28356
28571
  return { id, cat, key, content, file: file2, tags, date: date5, accessed };
@@ -28358,8 +28573,47 @@ server.registerTool(
28358
28573
  if (results.length === 0) {
28359
28574
  return { content: [{ type: "text", text: `No se encontraron resultados para "${query}"` }] };
28360
28575
  }
28576
+ if (mode === "graph") {
28577
+ const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops });
28578
+ if (detail.entries.length === 0) {
28579
+ return { content: [{ type: "text", text: `No se encontraron resultados para "${query}"` }] };
28580
+ }
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) => {
28591
+ const links = r.links.length ? `
28592
+ links: ${r.links.join(", ")}` : "";
28593
+ return `[${r.category}] ${r.key} (${r.id})
28594
+ ${r.content}
28595
+ File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}`;
28596
+ }).join("\n\n");
28597
+ return { content: [{ type: "text", text: formatted2 }] };
28598
+ }
28361
28599
  const ranked = results.map((r) => ({ ...r, score: entryScore(r.date, r.accessed) })).sort((a, b) => b.score - a.score);
28362
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
+ }
28363
28617
  const formatted = ranked.map((r) => `[${r.cat}] ${r.key} (${r.id})
28364
28618
  ${r.content}
28365
28619
  File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`).join("\n\n");
@@ -28382,16 +28636,16 @@ server.registerTool(
28382
28636
  if (headerIdx === -1) {
28383
28637
  return { content: [{ type: "text", text: "No hay entradas en memoria" }] };
28384
28638
  }
28385
- const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
28386
- const filtered = entryLines.filter((l) => {
28639
+ const entryLines2 = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"));
28640
+ const filtered = entryLines2.filter((l) => {
28387
28641
  const parts = l.trim().split("|");
28388
28642
  return parts[0] !== key && parts[2] !== key;
28389
28643
  });
28390
- const removed = entryLines.length - filtered.length;
28644
+ const removed = entryLines2.length - filtered.length;
28391
28645
  const match = lines[headerIdx].match(/\[(\d+)\|/);
28392
28646
  const count = match ? parseInt(match[1]) : 0;
28393
28647
  lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`);
28394
- lines.splice(headerIdx + 1, entryLines.length, ...filtered.map((l) => ` ${l.trim()}`));
28648
+ lines.splice(headerIdx + 1, entryLines2.length, ...filtered.map((l) => ` ${l.trim()}`));
28395
28649
  writeMemory(lines.join("\n"));
28396
28650
  return {
28397
28651
  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.3.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": {
package/src/cli/setup.ts CHANGED
@@ -3,6 +3,7 @@ import { basename, dirname, join } from "path"
3
3
  import { fileURLToPath } from "url"
4
4
  import { createInterface } from "readline"
5
5
  import { gzipSync, gunzipSync } from "zlib"
6
+ import { extractProjectDeps } from "../lib/vocab"
6
7
 
7
8
  const __dirname = dirname(fileURLToPath(import.meta.url))
8
9
  const projectRoot = process.cwd()
@@ -601,17 +602,43 @@ function installForAgent(agent: Agent, scope: string): void {
601
602
  installHooks(agent)
602
603
  }
603
604
 
605
+ /**
606
+ * Read/write the shared memory config.json, preserving unknown keys
607
+ * (e.g. `encrypted`, `capture`) so we never clobber sibling settings.
608
+ */
609
+ function updateMemoryConfig(patch: Record<string, any>): void {
610
+ if (!existsSync(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true })
611
+ let cfg: Record<string, any> = {}
612
+ if (existsSync(CAPTURE_CONFIG)) {
613
+ try {
614
+ cfg = JSON.parse(readFileSync(CAPTURE_CONFIG, "utf-8"))
615
+ } catch {
616
+ cfg = {}
617
+ }
618
+ }
619
+ Object.assign(cfg, patch)
620
+ writeFileSync(CAPTURE_CONFIG, JSON.stringify(cfg, null, 2))
621
+ }
622
+
604
623
  /**
605
624
  * Initialize toon-memory for all detected agents (non-interactive).
606
625
  *
607
- * Installs MCP server configs, creates memory directory, and
608
- * updates `.gitignore`.
626
+ * Installs MCP server configs, creates memory directory, discovers project
627
+ * dependencies for tag inference, and updates `.gitignore`.
609
628
  */
610
629
  function init(scope: string = "local"): void {
611
630
  console.log("\n🧠 toon-memory init\n")
612
631
 
613
632
  installMemoryDir()
614
633
 
634
+ // Hito 7 (B): derive a project-specific tag vocabulary from dependencies.
635
+ const deps = extractProjectDeps(projectRoot)
636
+ const depCount = Object.keys(deps).length
637
+ if (depCount > 0) {
638
+ updateMemoryConfig({ vocab: deps })
639
+ console.log(` Detected ${depCount} dependencies → auto-tag vocabulary written to config.json`)
640
+ }
641
+
615
642
  const agents = detectAgents()
616
643
  for (const agent of agents) {
617
644
  installForAgent(agent, scope)