toon-memory 2.9.8 → 2.10.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
@@ -28295,7 +28295,7 @@ function importance(e) {
28295
28295
  const freq = Math.min(1, e.accessed / 5);
28296
28296
  return recency * 0.6 + freq * 0.4;
28297
28297
  }
28298
- var tokenize = (s) => normalize(s).split(" ").filter(Boolean);
28298
+ var tokenize = (s) => s.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[-_]/g, " ").toLowerCase().split(/\s+/).filter(Boolean);
28299
28299
 
28300
28300
  // src/mcp/entries.ts
28301
28301
  function generateId() {
@@ -28534,6 +28534,142 @@ function pruneExpiredEntries() {
28534
28534
  return pruned;
28535
28535
  }
28536
28536
 
28537
+ // src/lib/synonyms.ts
28538
+ var SYNONYMS = {
28539
+ // Infrastructure / networking
28540
+ "conexi\xF3n": ["timeout", "red", "conectar", "disconnect", "connection", "conn"],
28541
+ "conectar": ["timeout", "red", "conexi\xF3n", "connect", "connection"],
28542
+ "ca\xEDda": ["down", "crash", "fail", "error", "dropped", "falla"],
28543
+ "down": ["ca\xEDda", "crash", "fail", "caer", "offline"],
28544
+ "crash": ["ca\xEDda", "down", "fail", "error", "colapso"],
28545
+ "timeout": ["conexi\xF3n", "red", "expirar", "deadline", "exceed"],
28546
+ "red": ["network", "conexi\xF3n", "ip", "dns", "proxy", "gateway"],
28547
+ "network": ["red", "conexi\xF3n", "ip", "dns", "proxy"],
28548
+ "server": ["servidor", "backend", "api", "host"],
28549
+ "servidor": ["server", "backend", "api", "host"],
28550
+ "client": ["cliente", "frontend", "browser", "user-agent"],
28551
+ "cliente": ["client", "frontend", "browser"],
28552
+ // Data / storage
28553
+ "cache": ["redis", "memcached", "cached", "cach\xE9"],
28554
+ "redis": ["cache", "memcached", "session", "pubsub"],
28555
+ "pool": ["pool", "connection pool", "pooling", "concurrencia"],
28556
+ "database": ["db", "postgres", "mysql", "mongo", "sql", "base de datos"],
28557
+ "db": ["database", "postgres", "mysql", "mongo", "sql"],
28558
+ "session": ["sesi\xF3n", "cookie", "token", "auth"],
28559
+ // Errors / debugging
28560
+ "error": ["bug", "exception", "fail", "fallo", "error", "err"],
28561
+ "bug": ["error", "defect", "issue", "fallo", "problema"],
28562
+ "exception": ["error", "throw", "catch", "error"],
28563
+ "fail": ["error", "falla", "fallo", "crash", "fail"],
28564
+ "falla": ["error", "fail", "fallo", "bug", "crash"],
28565
+ "debug": ["debugging", "log", "trace", "diagn\xF3stico"],
28566
+ "log": ["logging", "debug", "trace", "registro"],
28567
+ "warning": ["warn", "advertencia", "alerta"],
28568
+ // Architecture
28569
+ "auth": ["authentication", "autenticaci\xF3n", "login", "jwt", "token", "oauth"],
28570
+ "autenticaci\xF3n": ["auth", "authentication", "login", "jwt", "oauth"],
28571
+ "api": ["endpoint", "route", "rest", "graphql", "rpc"],
28572
+ "endpoint": ["api", "route", "url", "path"],
28573
+ "config": ["configuraci\xF3n", "settings", "env", "environment"],
28574
+ "configuraci\xF3n": ["config", "settings", "env", "environment"],
28575
+ "deploy": ["deployment", "despliegue", "release", "ship", "ci/cd"],
28576
+ "despliegue": ["deploy", "deployment", "release", "publish"],
28577
+ "migration": ["migraci\xF3n", "migrate", "upgrade", "schema change"],
28578
+ "migraci\xF3n": ["migration", "migrate", "upgrade"],
28579
+ // Code / patterns
28580
+ "refactor": ["refactoring", "reorganizar", "reestructurar", "clean"],
28581
+ "reestructurar": ["refactor", "refactoring", "reorganizar", "restructure"],
28582
+ "pattern": ["patr\xF3n", "pattern", "convention", "norma", "est\xE1ndar"],
28583
+ "patr\xF3n": ["pattern", "convention", "norma", "est\xE1ndar"],
28584
+ "decision": ["decisi\xF3n", "decision", "elecci\xF3n", "choice", "acuerdo"],
28585
+ "decisi\xF3n": ["decision", "elecci\xF3n", "choice", "acuerdo"],
28586
+ "knowledge": ["conocimiento", "knowledge", "info", "informaci\xF3n"],
28587
+ "conocimiento": ["knowledge", "info", "informaci\xF3n"],
28588
+ // Performance
28589
+ "performance": ["rendimiento", "perf", "latency", "throughput", "speed"],
28590
+ "rendimiento": ["performance", "perf", "latency", "speed"],
28591
+ "latency": ["latencia", "delay", "response time", "rt"],
28592
+ "latencia": ["latency", "delay", "response time"],
28593
+ "memory": ["memoria", "ram", "heap", "leak"],
28594
+ "memoria": ["memory", "ram", "heap", "leak"],
28595
+ "leak": ["fuga", "memory leak", "memoria"],
28596
+ // Testing
28597
+ "test": ["testing", "prueba", "tests", "spec"],
28598
+ "prueba": ["test", "testing", "spec"],
28599
+ "mock": ["mocking", "stub", "fake", "doble"],
28600
+ "coverage": ["cobertura", "coverage", "tests"],
28601
+ // Git / VCS
28602
+ "commit": ["commits", "\u63D0\u4EA4", "checkpoint", "save"],
28603
+ "branch": ["rama", "branch", "feature branch", "checkout"],
28604
+ "rama": ["branch", "feature branch", "checkout"],
28605
+ "merge": ["mergear", "merge", "combine", "unir"],
28606
+ "conflict": ["conflicto", "conflict", "merge conflict", "clash"],
28607
+ "conflicto": ["conflict", "merge conflict", "clash"],
28608
+ "revert": ["rollback", "deshacer", "undo", "restore"],
28609
+ // UI / frontend
28610
+ "ui": ["interfaz", "interface", "gui", "frontend", "vista"],
28611
+ "interfaz": ["ui", "interface", "gui", "frontend"],
28612
+ "component": ["componente", "widget", "module", "pieza"],
28613
+ "componente": ["component", "widget", "module"],
28614
+ "responsive": ["responsive", "mobile", "adaptativo", "layout"],
28615
+ "layout": ["dise\xF1o", "design", "layout", "estructura"],
28616
+ // DevOps
28617
+ "docker": ["container", "contenedor", "image", "imagen"],
28618
+ "contenedor": ["docker", "container", "image"],
28619
+ "kubernetes": ["k8s", "cluster", "pods", "deployment"],
28620
+ "ci/cd": ["pipeline", "deploy", "continuous integration", "continuous deployment"],
28621
+ "monitoring": ["monitoreo", "observability", "metrics", "alerts"],
28622
+ "monitoreo": ["monitoring", "observability", "metrics"]
28623
+ };
28624
+ function expandSynonyms(queryTokens) {
28625
+ const expanded = new Set(queryTokens);
28626
+ for (const token of queryTokens) {
28627
+ const synonyms = SYNONYMS[token];
28628
+ if (synonyms) {
28629
+ for (const s of synonyms) expanded.add(s);
28630
+ }
28631
+ }
28632
+ return [...expanded];
28633
+ }
28634
+
28635
+ // src/lib/fuzzy.ts
28636
+ function levenshtein(a, b) {
28637
+ const al = a.length;
28638
+ const bl = b.length;
28639
+ if (al === 0) return bl;
28640
+ if (bl === 0) return al;
28641
+ let prev = new Array(bl + 1);
28642
+ let curr = new Array(bl + 1);
28643
+ for (let j = 0; j <= bl; j++) prev[j] = j;
28644
+ for (let i = 1; i <= al; i++) {
28645
+ curr[0] = i;
28646
+ for (let j = 1; j <= bl; j++) {
28647
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
28648
+ curr[j] = Math.min(
28649
+ prev[j] + 1,
28650
+ // deletion
28651
+ curr[j - 1] + 1,
28652
+ // insertion
28653
+ prev[j - 1] + cost
28654
+ // substitution
28655
+ );
28656
+ }
28657
+ ;
28658
+ [prev, curr] = [curr, prev];
28659
+ }
28660
+ return prev[bl];
28661
+ }
28662
+ function fuzzyMatch(queryTokens, docTokens, maxDistance = 2) {
28663
+ for (const qt of queryTokens) {
28664
+ if (qt.length <= 2) continue;
28665
+ for (const dt of docTokens) {
28666
+ if (Math.abs(qt.length - dt.length) > maxDistance) continue;
28667
+ if (levenshtein(qt, dt) <= maxDistance) return true;
28668
+ }
28669
+ }
28670
+ return false;
28671
+ }
28672
+
28537
28673
  // src/lib/graph.ts
28538
28674
  var entryLines = (data) => data.split("\n").filter(
28539
28675
  (l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")
@@ -28635,6 +28771,7 @@ function graphRecallDetailed(data, query, opts = {}) {
28635
28771
  const from_date = opts.from_date || "";
28636
28772
  const to_date = opts.to_date || "";
28637
28773
  const qTokens = tokenize(query);
28774
+ const expandedTokens = expandSynonyms(qTokens);
28638
28775
  const bm25 = bm25Scores(entries, query);
28639
28776
  const cent = centrality(adjacency);
28640
28777
  const seedKeys = /* @__PURE__ */ new Set();
@@ -28646,7 +28783,10 @@ function graphRecallDetailed(data, query, opts = {}) {
28646
28783
  const text = normalize(
28647
28784
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
28648
28785
  );
28649
- if (qTokens.length > 0 && !qTokens.every((t) => text.includes(t))) continue;
28786
+ const docTokens = text.split(" ");
28787
+ const exactMatch = expandedTokens.some((t) => text.includes(t));
28788
+ const fuzzy = !exactMatch && fuzzyMatch(qTokens, docTokens);
28789
+ if (qTokens.length > 0 && !exactMatch && !fuzzy) continue;
28650
28790
  seedKeys.add(e.key);
28651
28791
  }
28652
28792
  let selected;
@@ -28778,7 +28918,9 @@ function generateSmartRecall(data, intent, opts = {}) {
28778
28918
  const cent = centrality(adjacency);
28779
28919
  const limit = opts.limit ?? 8;
28780
28920
  const category = opts.category || "";
28921
+ const mtimes = opts.fileMtimes;
28781
28922
  const qTokens = tokenize(intent);
28923
+ const expandedTokens = expandSynonyms(qTokens);
28782
28924
  const scored = entries.filter((e) => {
28783
28925
  if (category && e.category !== category) return false;
28784
28926
  if (e.ttl && isExpiredLocal(e.ttl)) return false;
@@ -28787,11 +28929,20 @@ function generateSmartRecall(data, intent, opts = {}) {
28787
28929
  const text = normalize(
28788
28930
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
28789
28931
  );
28790
- const matchesQuery = qTokens.length === 0 || qTokens.some((t) => text.includes(t));
28932
+ const docTokens = text.split(" ");
28933
+ const exactMatch = qTokens.length === 0 || expandedTokens.some((t) => text.includes(t));
28934
+ const fuzzy = !exactMatch && qTokens.length > 0 && fuzzyMatch(qTokens, docTokens);
28935
+ const matchesQuery = exactMatch || fuzzy;
28791
28936
  const bm25Score = bm25.get(e.key) || 0;
28792
28937
  const centScore = cent.get(e.key) || 0;
28793
28938
  const impScore = importance(e);
28794
- const combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0);
28939
+ let drift = 0;
28940
+ if (mtimes && e.file) {
28941
+ const filePath = e.file.split(":")[0];
28942
+ const fileDate = mtimes.get(filePath);
28943
+ if (fileDate && e.date && fileDate > e.date) drift = 0.3;
28944
+ }
28945
+ const combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift;
28795
28946
  return { entry: e, score: combined, matchesQuery };
28796
28947
  }).filter((x) => x.score > 0 || x.matchesQuery).sort((a, b) => b.score - a.score).slice(0, limit);
28797
28948
  if (scored.length === 0) {
@@ -29098,6 +29249,17 @@ function readGitIndex(cwd) {
29098
29249
  if (!dir) return [];
29099
29250
  return parseIndex(dir).map((e) => e.name);
29100
29251
  }
29252
+ function fileMtimes(cwd) {
29253
+ const dir = gitDir(cwd);
29254
+ if (!dir) return /* @__PURE__ */ new Map();
29255
+ const entries = parseIndex(dir);
29256
+ const out = /* @__PURE__ */ new Map();
29257
+ for (const e of entries) {
29258
+ const date5 = new Date(e.mtimeSec * 1e3).toISOString().split("T")[0];
29259
+ out.set(e.name, date5);
29260
+ }
29261
+ return out;
29262
+ }
29101
29263
  function readObject(sha, cwd) {
29102
29264
  const dir = gitDir(cwd);
29103
29265
  if (!dir) return null;
@@ -29475,11 +29637,15 @@ function formatRelevantEntries(data, task, limit = 6) {
29475
29637
  const bm25 = bm25Scores(entries, task);
29476
29638
  const cent = centrality(adjacency);
29477
29639
  const qTokens = tokenize(task);
29640
+ const expandedTokens = expandSynonyms(qTokens);
29478
29641
  const scored = entries.filter((e) => !(e.ttl && isExpiredLocal(e.ttl))).map((e) => {
29479
29642
  const text = normalize(
29480
29643
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
29481
29644
  );
29482
- const matchesQuery = qTokens.length === 0 || qTokens.some((t) => text.includes(t));
29645
+ const docTokens = text.split(" ");
29646
+ const exactMatch = qTokens.length === 0 || expandedTokens.some((t) => text.includes(t));
29647
+ const fuzzy = !exactMatch && qTokens.length > 0 && fuzzyMatch(qTokens, docTokens);
29648
+ const matchesQuery = exactMatch || fuzzy;
29483
29649
  const bm25Score = bm25.get(e.key) || 0;
29484
29650
  const centScore = cent.get(e.key) || 0;
29485
29651
  const impScore = importance(e);
@@ -29782,6 +29948,21 @@ function generateContextHealth(data, root) {
29782
29948
  warnings.push(`${brokenFiles.length} refs to non-existent files: ${brokenFiles.slice(0, 3).join("; ")}`);
29783
29949
  score -= 5;
29784
29950
  }
29951
+ const mtimes = fileMtimes(root);
29952
+ const driftedEntries = [];
29953
+ for (const e of entries) {
29954
+ if (!e.file) continue;
29955
+ const filePath = e.file.split(":")[0];
29956
+ if (!filePath) continue;
29957
+ const fileDate = mtimes.get(filePath);
29958
+ if (fileDate && e.date && fileDate > e.date) {
29959
+ driftedEntries.push(`${e.key} (${e.file} modified ${fileDate})`);
29960
+ }
29961
+ }
29962
+ if (driftedEntries.length > 0) {
29963
+ warnings.push(`${driftedEntries.length} entries with stale file refs: ${driftedEntries.slice(0, 3).join("; ")}`);
29964
+ score -= 4;
29965
+ }
29785
29966
  const sessions = listSessions();
29786
29967
  const stale = sessions.filter((s) => !s.active && !s.ended);
29787
29968
  if (stale.length > 0) {
@@ -29879,7 +30060,7 @@ function registerTools(server2) {
29879
30060
  "memory_remember",
29880
30061
  {
29881
30062
  title: "Save to Memory",
29882
- description: "Save a fact to the project's persistent memory (decisions, patterns, bugs, knowledge). Persists between sessions.",
30063
+ description: "Save a fact to the project's persistent memory (decisions, patterns, bugs, knowledge). Persists between sessions. To mark an entry as obsolete, save a new entry with tags containing 'superseded' (e.g. tags: 'superseded;zod').",
29883
30064
  inputSchema: {
29884
30065
  category: external_exports.enum(["decision", "pattern", "bug", "knowledge"]).describe("Category of the fact"),
29885
30066
  key: external_exports.string().describe("Short title in kebab-case (e.g. risk-engine-priority)"),
@@ -30172,7 +30353,8 @@ ${formatted}` }] };
30172
30353
  },
30173
30354
  async ({ intent, limit, category }) => {
30174
30355
  const data = readMemory();
30175
- const result = generateSmartRecall(data, intent, { limit, category });
30356
+ const mtimes = fileMtimes();
30357
+ const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes });
30176
30358
  return { content: [{ type: "text", text: result }] };
30177
30359
  }
30178
30360
  );
@@ -30612,7 +30794,7 @@ function registerResources(server2) {
30612
30794
 
30613
30795
  // src/mcp/server.ts
30614
30796
  var server = new McpServer(
30615
- { name: "toon-memory", version: "2.9.8" },
30797
+ { name: "toon-memory", version: "2.10.0" },
30616
30798
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
30617
30799
  );
30618
30800
  registerResources(server);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "toon-memory",
3
- "version": "2.9.8",
3
+ "version": "2.10.0",
4
4
  "description": "MCP server giving AI coding agents offline, token-efficient persistent memory — 21 tools, 80% fewer tool calls, recall decisions, patterns, and bugs across sessions. No LLM, no server; works with 15+ agents.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -18,8 +18,10 @@ import { join } from "path"
18
18
  import { parseEntries, buildGraph, bm25Scores, centrality, renderCompact, type GraphEntry } from "./graph"
19
19
  import { qualityScore } from "./quality"
20
20
  import { normalize, isExpiredLocal, tokenize, importance } from "./utils"
21
+ import { expandSynonyms } from "./synonyms"
22
+ import { fuzzyMatch } from "./fuzzy"
21
23
  import { coordinationView, currentBranch, pruneSessions, listSessions } from "./sessions"
22
- import { readRecentCommits, gitStatusSummary, readGitIndex } from "./git"
24
+ import { readRecentCommits, gitStatusSummary, readGitIndex, fileMtimes } from "./git"
23
25
  import { scanProjectStructure, readManifest, readEnvExample } from "./project-scan"
24
26
  import { findFilesByPattern, searchCode, findCallers } from "./code-search"
25
27
 
@@ -60,6 +62,7 @@ function formatRelevantEntries(data: string, task: string, limit: number = 6): s
60
62
  const bm25 = bm25Scores(entries, task)
61
63
  const cent = centrality(adjacency)
62
64
  const qTokens = tokenize(task)
65
+ const expandedTokens = expandSynonyms(qTokens)
63
66
 
64
67
  const scored = entries
65
68
  .filter((e) => !(e.ttl && isExpiredLocal(e.ttl)))
@@ -67,7 +70,10 @@ function formatRelevantEntries(data: string, task: string, limit: number = 6): s
67
70
  const text = normalize(
68
71
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
69
72
  )
70
- const matchesQuery = qTokens.length === 0 || qTokens.some((t) => text.includes(t))
73
+ const docTokens = text.split(" ")
74
+ const exactMatch = qTokens.length === 0 || expandedTokens.some((t) => text.includes(t))
75
+ const fuzzy = !exactMatch && qTokens.length > 0 && fuzzyMatch(qTokens, docTokens)
76
+ const matchesQuery = exactMatch || fuzzy
71
77
  const bm25Score = bm25.get(e.key) || 0
72
78
  const centScore = cent.get(e.key) || 0
73
79
  const impScore = importance(e)
@@ -539,14 +545,31 @@ export function generateContextHealth(data: string, root: string): { report: Hea
539
545
  score -= 5
540
546
  }
541
547
 
542
- // 6. Stale sessions
548
+ // 6. Code drift detection: entries whose linked file changed after creation
549
+ const mtimes = fileMtimes(root)
550
+ const driftedEntries: string[] = []
551
+ for (const e of entries) {
552
+ if (!e.file) continue
553
+ const filePath = e.file.split(":")[0]
554
+ if (!filePath) continue
555
+ const fileDate = mtimes.get(filePath)
556
+ if (fileDate && e.date && fileDate > e.date) {
557
+ driftedEntries.push(`${e.key} (${e.file} modified ${fileDate})`)
558
+ }
559
+ }
560
+ if (driftedEntries.length > 0) {
561
+ warnings.push(`${driftedEntries.length} entries with stale file refs: ${driftedEntries.slice(0, 3).join("; ")}`)
562
+ score -= 4
563
+ }
564
+
565
+ // 7. Stale sessions
543
566
  const sessions = listSessions()
544
567
  const stale = sessions.filter((s) => !s.active && !s.ended)
545
568
  if (stale.length > 0) {
546
569
  info.push(`${stale.length} stale sessions (will be pruned automatically)`)
547
570
  }
548
571
 
549
- // 7. Entry count
572
+ // 8. Entry count
550
573
  if (entries.length > 80) {
551
574
  warnings.push(`${entries.length} entries (near limit of 100)`)
552
575
  score -= 3
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Fuzzy token matching via Levenshtein distance.
3
+ *
4
+ * Handles typos and minor variations (e.g. "tiemout" ≈ "timeout").
5
+ * Pure JS — zero dependencies, ~20 lines of core logic.
6
+ */
7
+
8
+ /**
9
+ * Levenshtein edit distance between two strings.
10
+ * Classic DP approach, O(n*m) time, O(min(n,m)) space.
11
+ */
12
+ export function levenshtein(a: string, b: string): number {
13
+ const al = a.length
14
+ const bl = b.length
15
+ if (al === 0) return bl
16
+ if (bl === 0) return al
17
+
18
+ // Optimization: only keep two rows at a time
19
+ let prev = new Array(bl + 1)
20
+ let curr = new Array(bl + 1)
21
+ for (let j = 0; j <= bl; j++) prev[j] = j
22
+
23
+ for (let i = 1; i <= al; i++) {
24
+ curr[0] = i
25
+ for (let j = 1; j <= bl; j++) {
26
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1
27
+ curr[j] = Math.min(
28
+ prev[j] + 1, // deletion
29
+ curr[j - 1] + 1, // insertion
30
+ prev[j - 1] + cost // substitution
31
+ )
32
+ }
33
+ ;[prev, curr] = [curr, prev]
34
+ }
35
+ return prev[bl]
36
+ }
37
+
38
+ /**
39
+ * Check if any query token fuzzy-matches any document token
40
+ * within the given Levenshtein distance.
41
+ *
42
+ * Short-circuits on first match for speed.
43
+ */
44
+ export function fuzzyMatch(
45
+ queryTokens: string[],
46
+ docTokens: string[],
47
+ maxDistance: number = 2
48
+ ): boolean {
49
+ for (const qt of queryTokens) {
50
+ // Skip very short tokens (1-2 chars) — too many false positives
51
+ if (qt.length <= 2) continue
52
+ for (const dt of docTokens) {
53
+ if (Math.abs(qt.length - dt.length) > maxDistance) continue
54
+ if (levenshtein(qt, dt) <= maxDistance) return true
55
+ }
56
+ }
57
+ return false
58
+ }
package/src/lib/git.ts CHANGED
@@ -149,6 +149,22 @@ export function readGitIndex(cwd?: string): string[] {
149
149
  return parseIndex(dir).map((e) => e.name)
150
150
  }
151
151
 
152
+ /**
153
+ * Return a map of file path → last-modified date (YYYY-MM-DD) from the git index.
154
+ * Used for drift detection: compare entry creation date against file mtime.
155
+ */
156
+ export function fileMtimes(cwd?: string): Map<string, string> {
157
+ const dir = gitDir(cwd)
158
+ if (!dir) return new Map()
159
+ const entries = parseIndex(dir)
160
+ const out = new Map<string, string>()
161
+ for (const e of entries) {
162
+ const date = new Date(e.mtimeSec * 1000).toISOString().split("T")[0]
163
+ out.set(e.name, date)
164
+ }
165
+ return out
166
+ }
167
+
152
168
  /**
153
169
  * Parse a raw git object (decompressed with zlib).
154
170
  * Returns the object type and content.
package/src/lib/graph.ts CHANGED
@@ -15,6 +15,8 @@
15
15
  */
16
16
 
17
17
  import { normalize, isExpiredLocal, tokenize, importance } from "./utils"
18
+ import { expandSynonyms } from "./synonyms"
19
+ import { fuzzyMatch } from "./fuzzy"
18
20
 
19
21
  export interface GraphEntry {
20
22
  id: string
@@ -207,6 +209,7 @@ export function graphRecallDetailed(
207
209
  const to_date = opts.to_date || ""
208
210
 
209
211
  const qTokens = tokenize(query)
212
+ const expandedTokens = expandSynonyms(qTokens)
210
213
  const bm25 = bm25Scores(entries, query)
211
214
  const cent = centrality(adjacency)
212
215
 
@@ -219,7 +222,10 @@ export function graphRecallDetailed(
219
222
  const text = normalize(
220
223
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
221
224
  )
222
- if (qTokens.length > 0 && !qTokens.every((t) => text.includes(t))) continue
225
+ const docTokens = text.split(" ")
226
+ const exactMatch = expandedTokens.some((t) => text.includes(t))
227
+ const fuzzy = !exactMatch && fuzzyMatch(qTokens, docTokens)
228
+ if (qTokens.length > 0 && !exactMatch && !fuzzy) continue
223
229
  seedKeys.add(e.key)
224
230
  }
225
231
 
@@ -9,6 +9,8 @@
9
9
 
10
10
  import { parseEntries, buildGraph, bm25Scores, centrality, renderCompact, type GraphEntry } from "./graph"
11
11
  import { normalize, isExpiredLocal, tokenize, importance } from "./utils"
12
+ import { expandSynonyms } from "./synonyms"
13
+ import { fuzzyMatch } from "./fuzzy"
12
14
 
13
15
  /**
14
16
  * Quality score for an entry (0..1). Pure heuristics, no LLM.
@@ -100,7 +102,7 @@ export function mergeEntries(existingLine: string, newLine: string): string {
100
102
  export function generateSmartRecall(
101
103
  data: string,
102
104
  intent: string,
103
- opts: { limit?: number; category?: string; bumpAccess?: (ids: string[]) => void } = {}
105
+ opts: { limit?: number; category?: string; bumpAccess?: (ids: string[]) => void; fileMtimes?: Map<string, string> } = {}
104
106
  ): string {
105
107
  const entries = parseEntries(data)
106
108
  if (entries.length === 0) return "Empty memory."
@@ -110,8 +112,10 @@ export function generateSmartRecall(
110
112
  const cent = centrality(adjacency)
111
113
  const limit = opts.limit ?? 8
112
114
  const category = opts.category || ""
115
+ const mtimes = opts.fileMtimes
113
116
 
114
117
  const qTokens = tokenize(intent)
118
+ const expandedTokens = expandSynonyms(qTokens)
115
119
 
116
120
  const scored = entries
117
121
  .filter((e) => {
@@ -123,12 +127,22 @@ export function generateSmartRecall(
123
127
  const text = normalize(
124
128
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
125
129
  )
126
- const matchesQuery = qTokens.length === 0 || qTokens.some((t) => text.includes(t))
130
+ const docTokens = text.split(" ")
131
+ const exactMatch = qTokens.length === 0 || expandedTokens.some((t) => text.includes(t))
132
+ const fuzzy = !exactMatch && qTokens.length > 0 && fuzzyMatch(qTokens, docTokens)
133
+ const matchesQuery = exactMatch || fuzzy
127
134
  const bm25Score = bm25.get(e.key) || 0
128
135
  const centScore = cent.get(e.key) || 0
129
136
  const impScore = importance(e)
137
+ // Drift penalty: if the linked file was modified after the entry was created
138
+ let drift = 0
139
+ if (mtimes && e.file) {
140
+ const filePath = e.file.split(":")[0]
141
+ const fileDate = mtimes.get(filePath)
142
+ if (fileDate && e.date && fileDate > e.date) drift = 0.3
143
+ }
130
144
  const combined =
131
- bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0)
145
+ bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift
132
146
  return { entry: e, score: combined, matchesQuery }
133
147
  })
134
148
  .filter((x) => x.score > 0 || x.matchesQuery)
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Domain-specific synonym dictionary for toon-memory.
3
+ *
4
+ * Maps common coding/DevOps terms to their equivalents so that queries
5
+ * like "conexión caída" can find entries containing "timeout de red".
6
+ * Pure static map — zero LLM, zero network, zero embeddings.
7
+ */
8
+
9
+ export const SYNONYMS: Record<string, string[]> = {
10
+ // Infrastructure / networking
11
+ "conexión": ["timeout", "red", "conectar", "disconnect", "connection", "conn"],
12
+ "conectar": ["timeout", "red", "conexión", "connect", "connection"],
13
+ "caída": ["down", "crash", "fail", "error", "dropped", "falla"],
14
+ "down": ["caída", "crash", "fail", "caer", "offline"],
15
+ "crash": ["caída", "down", "fail", "error", "colapso"],
16
+ "timeout": ["conexión", "red", "expirar", "deadline", "exceed"],
17
+ "red": ["network", "conexión", "ip", "dns", "proxy", "gateway"],
18
+ "network": ["red", "conexión", "ip", "dns", "proxy"],
19
+ "server": ["servidor", "backend", "api", "host"],
20
+ "servidor": ["server", "backend", "api", "host"],
21
+ "client": ["cliente", "frontend", "browser", "user-agent"],
22
+ "cliente": ["client", "frontend", "browser"],
23
+
24
+ // Data / storage
25
+ "cache": ["redis", "memcached", "cached", "caché"],
26
+ "redis": ["cache", "memcached", "session", "pubsub"],
27
+ "pool": ["pool", "connection pool", "pooling", "concurrencia"],
28
+ "database": ["db", "postgres", "mysql", "mongo", "sql", "base de datos"],
29
+ "db": ["database", "postgres", "mysql", "mongo", "sql"],
30
+ "session": ["sesión", "cookie", "token", "auth"],
31
+
32
+ // Errors / debugging
33
+ "error": ["bug", "exception", "fail", "fallo", "error", "err"],
34
+ "bug": ["error", "defect", "issue", "fallo", "problema"],
35
+ "exception": ["error", "throw", "catch", "error"],
36
+ "fail": ["error", "falla", "fallo", "crash", "fail"],
37
+ "falla": ["error", "fail", "fallo", "bug", "crash"],
38
+ "debug": ["debugging", "log", "trace", "diagnóstico"],
39
+ "log": ["logging", "debug", "trace", "registro"],
40
+ "warning": ["warn", "advertencia", "alerta"],
41
+
42
+ // Architecture
43
+ "auth": ["authentication", "autenticación", "login", "jwt", "token", "oauth"],
44
+ "autenticación": ["auth", "authentication", "login", "jwt", "oauth"],
45
+ "api": ["endpoint", "route", "rest", "graphql", "rpc"],
46
+ "endpoint": ["api", "route", "url", "path"],
47
+ "config": ["configuración", "settings", "env", "environment"],
48
+ "configuración": ["config", "settings", "env", "environment"],
49
+ "deploy": ["deployment", "despliegue", "release", "ship", "ci/cd"],
50
+ "despliegue": ["deploy", "deployment", "release", "publish"],
51
+ "migration": ["migración", "migrate", "upgrade", "schema change"],
52
+ "migración": ["migration", "migrate", "upgrade"],
53
+
54
+ // Code / patterns
55
+ "refactor": ["refactoring", "reorganizar", "reestructurar", "clean"],
56
+ "reestructurar": ["refactor", "refactoring", "reorganizar", "restructure"],
57
+ "pattern": ["patrón", "pattern", "convention", "norma", "estándar"],
58
+ "patrón": ["pattern", "convention", "norma", "estándar"],
59
+ "decision": ["decisión", "decision", "elección", "choice", "acuerdo"],
60
+ "decisión": ["decision", "elección", "choice", "acuerdo"],
61
+ "knowledge": ["conocimiento", "knowledge", "info", "información"],
62
+ "conocimiento": ["knowledge", "info", "información"],
63
+
64
+ // Performance
65
+ "performance": ["rendimiento", "perf", "latency", "throughput", "speed"],
66
+ "rendimiento": ["performance", "perf", "latency", "speed"],
67
+ "latency": ["latencia", "delay", "response time", "rt"],
68
+ "latencia": ["latency", "delay", "response time"],
69
+ "memory": ["memoria", "ram", "heap", "leak"],
70
+ "memoria": ["memory", "ram", "heap", "leak"],
71
+ "leak": ["fuga", "memory leak", "memoria"],
72
+
73
+ // Testing
74
+ "test": ["testing", "prueba", "tests", "spec"],
75
+ "prueba": ["test", "testing", "spec"],
76
+ "mock": ["mocking", "stub", "fake", "doble"],
77
+ "coverage": ["cobertura", "coverage", "tests"],
78
+
79
+ // Git / VCS
80
+ "commit": ["commits", "提交", "checkpoint", "save"],
81
+ "branch": ["rama", "branch", "feature branch", "checkout"],
82
+ "rama": ["branch", "feature branch", "checkout"],
83
+ "merge": ["mergear", "merge", "combine", "unir"],
84
+ "conflict": ["conflicto", "conflict", "merge conflict", "clash"],
85
+ "conflicto": ["conflict", "merge conflict", "clash"],
86
+ "revert": ["rollback", "deshacer", "undo", "restore"],
87
+
88
+ // UI / frontend
89
+ "ui": ["interfaz", "interface", "gui", "frontend", "vista"],
90
+ "interfaz": ["ui", "interface", "gui", "frontend"],
91
+ "component": ["componente", "widget", "module", "pieza"],
92
+ "componente": ["component", "widget", "module"],
93
+ "responsive": ["responsive", "mobile", "adaptativo", "layout"],
94
+ "layout": ["diseño", "design", "layout", "estructura"],
95
+
96
+ // DevOps
97
+ "docker": ["container", "contenedor", "image", "imagen"],
98
+ "contenedor": ["docker", "container", "image"],
99
+ "kubernetes": ["k8s", "cluster", "pods", "deployment"],
100
+ "ci/cd": ["pipeline", "deploy", "continuous integration", "continuous deployment"],
101
+ "monitoring": ["monitoreo", "observability", "metrics", "alerts"],
102
+ "monitoreo": ["monitoring", "observability", "metrics"],
103
+ }
104
+
105
+ /**
106
+ * Expand query tokens with domain synonyms.
107
+ * Returns a deduplicated set containing the original tokens + their synonyms.
108
+ */
109
+ export function expandSynonyms(queryTokens: string[]): string[] {
110
+ const expanded = new Set(queryTokens)
111
+ for (const token of queryTokens) {
112
+ const synonyms = SYNONYMS[token]
113
+ if (synonyms) {
114
+ for (const s of synonyms) expanded.add(s)
115
+ }
116
+ }
117
+ return [...expanded]
118
+ }
package/src/lib/utils.ts CHANGED
@@ -22,4 +22,10 @@ export function importance(e: { date: string; accessed: number }): number {
22
22
  return recency * 0.6 + freq * 0.4
23
23
  }
24
24
 
25
- export const tokenize = (s: string): string[] => normalize(s).split(" ").filter(Boolean)
25
+ export const tokenize = (s: string): string[] =>
26
+ s
27
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
28
+ .replace(/[-_]/g, " ")
29
+ .toLowerCase()
30
+ .split(/\s+/)
31
+ .filter(Boolean)
package/src/mcp/tools.ts CHANGED
@@ -15,6 +15,7 @@ import { graphRecallDetailed, renderCompact, parseEntries } from "../lib/graph"
15
15
  import { qualityScore, mergeEntries, generateSmartRecall } from "../lib/quality"
16
16
  import { generateContextBrief, generateContextGenerate, generateContextDiff, generateContextFocus, generateContextHealth, generateContextExport } from "../lib/context"
17
17
  import { coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS } from "../lib/sessions"
18
+ import { fileMtimes } from "../lib/git"
18
19
 
19
20
  /**
20
21
  * Register all 20 memory tools.
@@ -27,7 +28,7 @@ server.registerTool(
27
28
  "memory_remember",
28
29
  {
29
30
  title: "Save to Memory",
30
- description: "Save a fact to the project's persistent memory (decisions, patterns, bugs, knowledge). Persists between sessions.",
31
+ description: "Save a fact to the project's persistent memory (decisions, patterns, bugs, knowledge). Persists between sessions. To mark an entry as obsolete, save a new entry with tags containing 'superseded' (e.g. tags: 'superseded;zod').",
31
32
  inputSchema: {
32
33
  category: z.enum(["decision", "pattern", "bug", "knowledge"]).describe("Category of the fact"),
33
34
  key: z.string().describe("Short title in kebab-case (e.g. risk-engine-priority)"),
@@ -365,7 +366,8 @@ server.registerTool(
365
366
  },
366
367
  async ({ intent, limit, category }) => {
367
368
  const data = readMemory()
368
- const result = generateSmartRecall(data, intent, { limit, category })
369
+ const mtimes = fileMtimes()
370
+ const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes })
369
371
  return { content: [{ type: "text" as const, text: result }] }
370
372
  }
371
373
  )