toon-memory 2.7.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/mcp/tools.ts CHANGED
@@ -1,23 +1,23 @@
1
1
  import type { McpServer } from "@modelcontextprotocol/server"
2
2
  import { z } from "zod"
3
- import { readFileSync, writeFileSync, existsSync } from "fs"
4
- import { readMemory, writeMemory } from "./memory-io"
5
- import { loadConfig, saveConfig, getKey, MEMORY_FILE, OBSERVATIONS_FILE, MAX_ENTRIES } from "./config"
3
+ import { readFileSync, writeFileSync, existsSync, copyFileSync, mkdirSync, readdirSync } from "fs"
4
+ import { join, basename } from "path"
5
+ import { readMemory, writeMemory, safeWrite } from "./memory-io"
6
+ import { loadConfig, saveConfig, getKey, MEMORY_FILE, OBSERVATIONS_FILE, MEMORY_DIR, MAX_ENTRIES, getMaxEntries, ARCHIVE_FILE } from "./config"
6
7
  import { generateId, parseTTL, isExpired, inferTags, parseRelativeDate } from "./entries"
7
- import { entryScore, findRelatedEntries, bumpAccessed } from "./scoring"
8
+ import { findRelatedEntries, bumpAccessed } from "./scoring"
8
9
  import { readObservations } from "./observations"
9
10
  import { archiveOldEntries } from "./archive"
10
11
  import { consolidateEntries } from "./consolidation"
12
+ import { readUnderLock } from "../lib/lock"
11
13
  import { encrypt, decrypt } from "./crypto"
12
- import { graphRecallDetailed, renderCompact } from "../lib/graph"
14
+ import { graphRecallDetailed, renderCompact, parseEntries } from "../lib/graph"
13
15
  import { qualityScore, mergeEntries, generateSmartRecall } from "../lib/quality"
14
16
  import { generateContextBrief, generateContextGenerate, generateContextDiff, generateContextFocus, generateContextHealth, generateContextExport } from "../lib/context"
15
17
  import { coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS } from "../lib/sessions"
16
18
 
17
- const normalize = (s: string) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
18
-
19
19
  /**
20
- * Register all 15 memory tools.
20
+ * Register all 20 memory tools.
21
21
  */
22
22
  export function registerTools(server: McpServer): void {
23
23
 
@@ -27,15 +27,15 @@ server.registerTool(
27
27
  "memory_remember",
28
28
  {
29
29
  title: "Save to Memory",
30
- description: "Guarda un hecho en la memoria persistente del proyecto (decisiones, patrones, bugs, conocimiento). Se recuerda entre sesiones.",
30
+ description: "Save a fact to the project's persistent memory (decisions, patterns, bugs, knowledge). Persists between sessions.",
31
31
  inputSchema: {
32
- category: z.enum(["decision", "pattern", "bug", "knowledge"]).describe("Categoría del hecho"),
33
- key: z.string().describe("Título corto en kebab-case (ej: risk-engine-prioridad)"),
34
- content: z.string().describe("Contenido detallado del hecho"),
35
- file: z.string().optional().default("").describe("Archivo o línea relacionada (ej: spec.md:145)"),
36
- tags: z.string().optional().default("").describe("Tags separados por punto y coma (ej: risk;spec)"),
37
- ttl: z.string().optional().default("").describe("Time to live (ej: 7d, 2026-07-17). Vacío = sin expiración"),
38
- 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."),
32
+ category: z.enum(["decision", "pattern", "bug", "knowledge"]).describe("Category of the fact"),
33
+ key: z.string().describe("Short title in kebab-case (e.g. risk-engine-priority)"),
34
+ content: z.string().describe("Detailed content of the fact"),
35
+ file: z.string().optional().default("").describe("Related file or line (e.g. spec.md:145)"),
36
+ tags: z.string().optional().default("").describe("Semicolon-separated tags (e.g. risk;spec)"),
37
+ ttl: z.string().optional().default("").describe("Time to live (e.g. 7d, 2026-07-17). Empty = no expiration"),
38
+ links: z.string().optional().default("").describe("Related entry keys, separated by space or ';' (e.g. risk-spec engine-arch). Builds graph edges."),
39
39
  },
40
40
  },
41
41
  async ({ category, key, content, file, tags, ttl, links }) => {
@@ -72,15 +72,15 @@ server.registerTool(
72
72
  ? links.split(/[\s;]+/).filter(Boolean).join(" ")
73
73
  : existingParts[9] || ""
74
74
  let newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|0|${resolvedLinks}`
75
- let action = "Guardado"
75
+ let action = "Saved"
76
76
  let mergeInfo = ""
77
77
  const tagsInferred = !tags && resolvedTags ? true : false
78
78
 
79
79
  if (existingIdx !== -1) {
80
80
  newEntry = mergeEntries(lines[existingIdx].trim(), newEntry)
81
81
  lines[existingIdx] = ` ${newEntry}`
82
- action = "Actualizado"
83
- mergeInfo = "\n🔗 Merge: tags combinados, fecha y links actualizados"
82
+ action = "Updated"
83
+ mergeInfo = "\nMerge: tags combined, date and links updated"
84
84
  } else {
85
85
  const quality = qualityScore(resolvedTags, resolvedLinks, content, date)
86
86
  const confidence = 1.0
@@ -96,7 +96,7 @@ server.registerTool(
96
96
  const headerMatch = lines[headerIdx].match(/\[(\d+)\|/)
97
97
  const entryCount = headerMatch ? parseInt(headerMatch[1]) : 0
98
98
  let archiveMsg = ""
99
- if (entryCount > MAX_ENTRIES) {
99
+ if (entryCount > getMaxEntries()) {
100
100
  const result = archiveOldEntries({ trimToMax: true })
101
101
  if (result.archived > 0) {
102
102
  archiveMsg = `\n📦 Auto-archived ${result.archived} low-importance entries (${result.kept} kept)`
@@ -104,13 +104,13 @@ server.registerTool(
104
104
  }
105
105
 
106
106
  const ttlMsg = resolvedTtl ? `\n⏰ TTL: ${resolvedTtl}` : ""
107
- const inferredMsg = tagsInferred ? `\n🏷️ Tags inferidos: ${resolvedTags}` : ""
107
+ const inferredMsg = tagsInferred ? `\n🏷️ Inferred tags: ${resolvedTags}` : ""
108
108
 
109
109
  const related = findRelatedEntries(`${key} ${content} ${resolvedTags}`, key, 3)
110
110
  let relatedMsg = ""
111
111
  if (related.length > 0) {
112
112
  const items = related.map((r) => ` [${r.cat}] ${r.key} — ${r.content.slice(0, 80)}`).join("\n")
113
- relatedMsg = `\n\n🔗 Entradas relacionadas:\n${items}`
113
+ relatedMsg = `\n\n🔗 Related entries:\n${items}`
114
114
  }
115
115
 
116
116
  return {
@@ -125,100 +125,41 @@ server.registerTool(
125
125
  "memory_recall",
126
126
  {
127
127
  title: "Search Memory",
128
- description: "Busca en la memoria persistente del proyecto. Devuelve entradas relevantes. Usar ANTES de leer archivos.",
128
+ description: "Search the project's persistent memory. Returns relevant entries. Use BEFORE reading files.",
129
129
  inputSchema: {
130
- query: z.string().describe("Texto a buscar"),
131
- category: z.string().optional().default("").describe("Filtrar por categoría (vacío = todos)"),
132
- from_date: z.string().optional().default("").describe("Fecha inicio filtro (YYYY-MM-DD)"),
133
- to_date: z.string().optional().default("").describe("Fecha fin filtro (YYYY-MM-DD)"),
134
- 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)."),
135
- hops: z.number().optional().default(1).describe("Profundidad del grafo en modo 'graph' (1 o 2). Default 1."),
136
- compact: z.boolean().optional().default(false).describe("Salida token-efficient: índices numéricos (1, 2), omite id/fecha/archivo (conserva tags), aristas como '->2', y trunca vecinos del grafo a un snippet. No muta el archivo .toon."),
130
+ query: z.string().describe("Text to search for"),
131
+ category: z.string().optional().default("").describe("Filter by category (empty = all)"),
132
+ from_date: z.string().optional().default("").describe("Start date filter (YYYY-MM-DD)"),
133
+ to_date: z.string().optional().default("").describe("End date filter (YYYY-MM-DD)"),
134
+ mode: z.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall: expands the related-entry subgraph from matches (more precise, fewer tokens)."),
135
+ hops: z.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
136
+ compact: z.boolean().optional().default(false).describe("Token-efficient output: numeric indices (1, 2), omits id/date/file (keeps tags), edges as '->2', truncates graph neighbors to a snippet. Does not mutate .toon file."),
137
137
  },
138
138
  },
139
139
  async ({ query, category, from_date, to_date, mode, hops, compact }) => {
140
140
  const data = readMemory()
141
- const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
142
-
143
- const queryTokens = normalize(query).split(" ").filter(Boolean)
144
-
145
- const results = lines
146
- .map((line) => {
147
- const trimmed = line.trim()
148
- const parts = trimmed.split("|")
149
- if (parts.length < 7) return null
150
- const [id, cat, key, content, file, tags, date, ttl, accessedRaw] = parts
151
- const qualityRaw = parts[10] || ""
152
- const confidenceRaw = parts[11] || ""
153
- if (category && cat !== category) return null
154
- if (from_date && date < from_date) return null
155
- if (to_date && date > to_date) return null
156
- if (ttl && isExpired(ttl)) return null
157
- const searchStr = normalize(`${id} ${cat} ${key} ${content} ${file} ${tags} ${qualityRaw} ${confidenceRaw}`)
158
- if (!queryTokens.every((token) => searchStr.includes(token))) return null
159
- const accessed = accessedRaw ? parseInt(accessedRaw) || 0 : 0
160
- return { id, cat, key, content, file, tags, date, accessed, qualityRaw, confidenceRaw }
161
- })
162
- .filter(Boolean) as Array<{ id: string; cat: string; key: string; content: string; file: string; tags: string; date: string; accessed: number; qualityRaw: string; confidenceRaw: string }>
163
141
 
164
- if (results.length === 0) {
165
- return { content: [{ type: "text" as const, text: `No se encontraron resultados para "${query}"` }] }
142
+ // Delegate to graphRecallDetailed for both flat and graph modes
143
+ // This avoids duplicating BM25 + ranking logic
144
+ const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops })
145
+ if (detail.entries.length === 0) {
146
+ return { content: [{ type: "text" as const, text: `No results found for "${query}"` }] }
166
147
  }
167
-
168
- if (mode === "graph") {
169
- const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops })
170
- if (detail.entries.length === 0) {
171
- return { content: [{ type: "text" as const, text: `No se encontraron resultados para "${query}"` }] }
172
- }
173
- bumpAccessed(detail.entries.map((e) => e.id))
174
- if (compact) {
175
- const formatted = renderCompact(detail.entries, {
176
- adjacency: detail.adjacency,
177
- seeds: detail.seeds,
178
- snippetLen: 90,
179
- })
180
- return { content: [{ type: "text" as const, text: formatted }] }
181
- }
182
- const formatted = detail.entries
183
- .map((r) => {
184
- const links = r.links.length ? `\n links: ${r.links.join(", ")}` : ""
185
- return `[${r.category}] ${r.key} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}`
186
- })
187
- .join("\n\n")
148
+ bumpAccessed(detail.entries.map((e) => e.id))
149
+ if (compact) {
150
+ const formatted = renderCompact(detail.entries, {
151
+ adjacency: detail.adjacency,
152
+ seeds: detail.seeds,
153
+ snippetLen: 90,
154
+ })
188
155
  return { content: [{ type: "text" as const, text: formatted }] }
189
156
  }
190
-
191
- const ranked = results
157
+ const formatted = detail.entries
192
158
  .map((r) => {
193
- const quality = r.qualityRaw ? parseFloat(r.qualityRaw) || 0 : 0
194
- const qualityBoost = quality * 0.15
195
- return { ...r, score: entryScore(r.date, r.accessed) + qualityBoost }
159
+ const links = r.links.length ? `\n links: ${r.links.join(", ")}` : ""
160
+ return `[${r.category}] ${r.key} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}`
196
161
  })
197
- .sort((a, b) => b.score - a.score)
198
-
199
- bumpAccessed(ranked.map((r) => r.id))
200
-
201
- if (compact) {
202
- const entries = ranked.map((r) => ({
203
- id: r.id,
204
- category: r.cat,
205
- key: r.key,
206
- content: r.content,
207
- file: r.file,
208
- tags: r.tags ? r.tags.split(";").filter(Boolean) : [],
209
- date: r.date,
210
- ttl: "",
211
- accessed: r.accessed,
212
- links: [] as string[],
213
- }))
214
- const formatted = renderCompact(entries)
215
- return { content: [{ type: "text" as const, text: formatted }] }
216
- }
217
-
218
- const formatted = ranked
219
- .map((r) => `[${r.cat}] ${r.key} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`)
220
162
  .join("\n\n")
221
-
222
163
  return { content: [{ type: "text" as const, text: formatted }] }
223
164
  }
224
165
  )
@@ -229,9 +170,9 @@ server.registerTool(
229
170
  "memory_forget",
230
171
  {
231
172
  title: "Delete from Memory",
232
- description: "Elimina una entrada de la memoria por su key o id.",
173
+ description: "Delete a memory entry by its key or id.",
233
174
  inputSchema: {
234
- key: z.string().describe("Key o id de la entrada a eliminar"),
175
+ key: z.string().describe("Key or id of the entry to delete"),
235
176
  },
236
177
  },
237
178
  async ({ key }) => {
@@ -240,7 +181,7 @@ server.registerTool(
240
181
  const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
241
182
 
242
183
  if (headerIdx === -1) {
243
- return { content: [{ type: "text" as const, text: "No hay entradas en memoria" }] }
184
+ return { content: [{ type: "text" as const, text: "No entries in memory" }] }
244
185
  }
245
186
 
246
187
  const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
@@ -256,8 +197,15 @@ server.registerTool(
256
197
  lines.splice(headerIdx + 1, entryLines.length, ...filtered.map((l) => ` ${l.trim()}`))
257
198
 
258
199
  writeMemory(lines.join("\n"))
200
+
201
+ if (removed === 0) {
202
+ return {
203
+ content: [{ type: "text" as const, text: `"${key}" not found in memory.` }],
204
+ }
205
+ }
206
+
259
207
  return {
260
- content: [{ type: "text" as const, text: `"${key}" eliminado. Quedan ${count - removed} entradas.` }],
208
+ content: [{ type: "text" as const, text: `"${key}" deleted. ${count - removed} entries remaining.` }],
261
209
  }
262
210
  }
263
211
  )
@@ -268,7 +216,7 @@ server.registerTool(
268
216
  "memory_stats",
269
217
  {
270
218
  title: "Memory Stats",
271
- description: "Muestra estadísticas de la memoria del proyecto.",
219
+ description: "Show project memory statistics.",
272
220
  inputSchema: {},
273
221
  },
274
222
  async () => {
@@ -293,16 +241,16 @@ server.registerTool(
293
241
 
294
242
  const summaryLines = data.split("\n").filter((l) => l.includes(":") && !l.startsWith(" ") && !l.startsWith("version") && !l.startsWith("entries") && !/^\[\d+\|]/.test(l))
295
243
  const stats = [
296
- `Entradas totales: ${entries.length}`,
297
- `Resúmenes de archivos: ${summaryLines.length}`,
244
+ `Total entries: ${entries.length}`,
245
+ `File summaries: ${summaryLines.length}`,
298
246
  "",
299
- "Por categoría:",
247
+ "By category:",
300
248
  ...Object.entries(byCategory).map(([k, v]) => ` ${k}: ${v}`),
301
249
  "",
302
- `TTL: ${withTtl} con expiración, ${expired} expiradas`,
303
- `Calidad promedio: ${avgQuality} (${withQuality} con score)`,
250
+ `TTL: ${withTtl} with expiration, ${expired} expired`,
251
+ `Average quality: ${avgQuality} (${withQuality} with score)`,
304
252
  "",
305
- `Últimas 5 entradas:`,
253
+ `Last 5 entries:`,
306
254
  ...lines.slice(-5).map((l) => {
307
255
  const parts = l.trim().split("|")
308
256
  const ttlInfo = parts[7] ? ` | TTL: ${parts[7]}` : ""
@@ -321,10 +269,10 @@ server.registerTool(
321
269
  "memory_diff",
322
270
  {
323
271
  title: "Memory Diff",
324
- description: "Muestra qué cambió en la memoria desde una fecha. Útil para saber qué se aprendió desde la última sesión.",
272
+ description: "Show what changed in memory since a date. Useful for seeing what was learned since the last session.",
325
273
  inputSchema: {
326
- since: z.string().describe("Desde cuándo mostrar cambios (ej: 24h, 7d, 2026-07-10)"),
327
- type: z.enum(["all", "created", "updated"]).optional().default("all").describe("Filtrar por tipo de cambio"),
274
+ since: z.string().describe("Show changes since (e.g. 24h, 7d, 2026-07-10)"),
275
+ type: z.enum(["all", "created", "updated"]).optional().default("all").describe("Filter by change type"),
328
276
  },
329
277
  },
330
278
  async ({ since, type }) => {
@@ -347,16 +295,16 @@ server.registerTool(
347
295
  .filter(Boolean)
348
296
 
349
297
  if (results.length === 0) {
350
- return { content: [{ type: "text" as const, text: `No hay cambios desde ${sinceDate}` }] }
298
+ return { content: [{ type: "text" as const, text: `No changes since ${sinceDate}` }] }
351
299
  }
352
300
 
353
301
  const created = results.filter((r) => r!.changeType === "created")
354
302
  const updated = results.filter((r) => r!.changeType === "updated")
355
303
 
356
- const sections: string[] = [`📋 Cambios desde ${sinceDate}:`, ""]
304
+ const sections: string[] = [`📋 Changes since ${sinceDate}:`, ""]
357
305
 
358
306
  if (created.length > 0 && (type === "all" || type === "created")) {
359
- sections.push(`➕ Nuevas (${created.length}):`)
307
+ sections.push(`➕ New (${created.length}):`)
360
308
  for (const r of created) {
361
309
  sections.push(` [${r!.cat}] ${r!.key} (${r!.id})\n ${r!.content}`)
362
310
  }
@@ -364,7 +312,7 @@ server.registerTool(
364
312
  }
365
313
 
366
314
  if (updated.length > 0 && (type === "all" || type === "updated")) {
367
- sections.push(`✏️ Actualizadas (${updated.length}):`)
315
+ sections.push(`✏️ Updated (${updated.length}):`)
368
316
  for (const r of updated) {
369
317
  sections.push(` [${r!.cat}] ${r!.key} (${r!.id}) — ${r!.date}`)
370
318
  }
@@ -381,24 +329,24 @@ server.registerTool(
381
329
  "memory_suggest",
382
330
  {
383
331
  title: "Suggest Related Memories",
384
- description: "Sugiere entradas de memoria relacionadas con un contexto dado. Útil para obtener contexto antes de una tarea.",
332
+ description: "Suggest memory entries related to a given context. Useful for gathering context before a task.",
385
333
  inputSchema: {
386
- context: z.string().describe("Texto o contexto para buscar sugerencias"),
387
- limit: z.number().optional().default(5).describe("Máximo de sugerencias"),
334
+ context: z.string().describe("Text or context to search for suggestions"),
335
+ limit: z.number().optional().default(5).describe("Maximum suggestions"),
388
336
  },
389
337
  },
390
338
  async ({ context, limit }) => {
391
339
  const related = findRelatedEntries(context, "", limit)
392
340
 
393
341
  if (related.length === 0) {
394
- return { content: [{ type: "text" as const, text: `No se encontraron entradas relacionadas con "${context}"` }] }
342
+ return { content: [{ type: "text" as const, text: `No related entries found for "${context}"` }] }
395
343
  }
396
344
 
397
345
  const formatted = related
398
346
  .map((r) => `[${r.cat}] ${r.key} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`)
399
347
  .join("\n\n")
400
348
 
401
- return { content: [{ type: "text" as const, text: `🔍 Sugerencias para "${context}":\n\n${formatted}` }] }
349
+ return { content: [{ type: "text" as const, text: `🔍 Suggestions for "${context}":\n\n${formatted}` }] }
402
350
  }
403
351
  )
404
352
 
@@ -408,11 +356,11 @@ server.registerTool(
408
356
  "memory_smart_recall",
409
357
  {
410
358
  title: "Smart Recall (Unified)",
411
- description: "Recuperación unificada: combina BM25 + grafo + decay + calidad en una sola llamada. Usar al INICIO de cada tarea para obtener todo el contexto relevante de memoria.",
359
+ description: "Unified retrieval: combines BM25 + graph + decay + quality in a single call. Use at the START of each task to get all relevant memory context.",
412
360
  inputSchema: {
413
- intent: z.string().describe("Describe qué necesitas saber (ej: 'diseño de base de datos para backend')"),
414
- limit: z.number().optional().default(8).describe("Máximo de entradas a devolver"),
415
- category: z.string().optional().default("").describe("Filtrar por categoría (vacío = todos)"),
361
+ intent: z.string().describe("Describe what you need to know (e.g. 'database schema for backend')"),
362
+ limit: z.number().optional().default(8).describe("Maximum entries to return"),
363
+ category: z.string().optional().default("").describe("Filter by category (empty = all)"),
416
364
  },
417
365
  },
418
366
  async ({ intent, limit, category }) => {
@@ -428,11 +376,11 @@ server.registerTool(
428
376
  "memory_summary",
429
377
  {
430
378
  title: "File Summary",
431
- description: "Guarda o recupera un resumen de un archivo grande para ahorrar tokens.",
379
+ description: "Save or retrieve a summary of a large file to save tokens.",
432
380
  inputSchema: {
433
- action: z.enum(["get", "set"]).describe("get para leer, set para guardar"),
434
- file: z.string().describe("Ruta del archivo"),
435
- summary: z.string().optional().default("").describe("Resumen del archivo (solo para set)"),
381
+ action: z.enum(["get", "set"]).describe("get to read, set to save"),
382
+ file: z.string().describe("File path"),
383
+ summary: z.string().optional().default("").describe("File summary (only for set)"),
436
384
  },
437
385
  },
438
386
  async ({ action, file, summary }) => {
@@ -442,13 +390,13 @@ server.registerTool(
442
390
  const lines = data.split("\n")
443
391
  const summaryIdx = lines.findIndex((l) => l.trim().startsWith("summaries:"))
444
392
  if (summaryIdx === -1) {
445
- return { content: [{ type: "text" as const, text: `No hay resúmenes guardados para "${file}"` }] }
393
+ return { content: [{ type: "text" as const, text: `No summaries saved for "${file}"` }] }
446
394
  }
447
395
 
448
396
  const summaryLines = lines.slice(summaryIdx + 1).filter((l) => l.includes(":"))
449
397
  const match = summaryLines.find((l) => l.startsWith(` ${file}:`))
450
398
  if (!match) {
451
- return { content: [{ type: "text" as const, text: `No hay resumen para "${file}"` }] }
399
+ return { content: [{ type: "text" as const, text: `No summary for "${file}"` }] }
452
400
  }
453
401
 
454
402
  const summaryText = match.replace(` ${file}: `, "")
@@ -475,7 +423,7 @@ server.registerTool(
475
423
  lines.splice(summaryIdx + 1, lines.length - summaryIdx - 1, ...summaryLines)
476
424
  writeMemory(lines.join("\n"))
477
425
  return {
478
- content: [{ type: "text" as const, text: `📝 Resumen guardado para ${file}` }],
426
+ content: [{ type: "text" as const, text: `📝 Summary saved for ${file}` }],
479
427
  }
480
428
  }
481
429
  )
@@ -486,20 +434,20 @@ server.registerTool(
486
434
  "memory_archive",
487
435
  {
488
436
  title: "Archive Old Entries",
489
- description: "Mover entradas antiguas (>30 días) a archive.toon para mantener la memoria limpia.",
437
+ description: "Move old entries (>30 days) to archive.toon to keep memory clean.",
490
438
  inputSchema: {},
491
439
  },
492
440
  async () => {
493
441
  const result = archiveOldEntries()
494
442
 
495
443
  if (result.archived === 0) {
496
- return { content: [{ type: "text" as const, text: "No hay entradas antiguas para archivar" }] }
444
+ return { content: [{ type: "text" as const, text: "No old entries to archive" }] }
497
445
  }
498
446
 
499
447
  return {
500
448
  content: [{
501
449
  type: "text" as const,
502
- text: `📦 Archivadas ${result.archived} entradas antiguas\n📋 Quedan ${result.kept} entradas activas`
450
+ text: `📦 Archived ${result.archived} old entries\n📋 ${result.kept} active entries remaining`
503
451
  }],
504
452
  }
505
453
  }
@@ -511,29 +459,29 @@ server.registerTool(
511
459
  "memory_encrypt",
512
460
  {
513
461
  title: "Enable Encryption",
514
- description: "Habilita encriptación AES-256-GCM para la memoria. La clave se genera automáticamente.",
462
+ description: "Enable AES-256-GCM encryption for memory. Requires TOON_MEMORY_KEY in environment.",
515
463
  inputSchema: {},
516
464
  },
517
465
  async () => {
518
466
  const config = loadConfig()
519
467
 
520
468
  if (config.encrypted) {
521
- return { content: [{ type: "text" as const, text: "La encriptación ya está habilitada" }] }
469
+ return { content: [{ type: "text" as const, text: "Encryption is already enabled" }] }
522
470
  }
523
471
 
524
472
  const key = getKey()
525
473
  if (!key) {
526
- return { content: [{ type: "text" as const, text: "❌ Define TOON_MEMORY_KEY en el entorno antes de encriptar" }] }
474
+ return { content: [{ type: "text" as const, text: "❌ Set TOON_MEMORY_KEY in environment before encrypting" }] }
527
475
  }
528
476
 
529
- const data = readFileSync(MEMORY_FILE, "utf-8")
477
+ const data = readUnderLock(MEMORY_FILE)
530
478
  const encrypted = encrypt(data, key)
531
- writeFileSync(MEMORY_FILE, encrypted)
479
+ safeWrite(MEMORY_FILE, encrypted)
532
480
 
533
481
  saveConfig({ encrypted: true })
534
482
 
535
483
  return {
536
- content: [{ type: "text" as const, text: "🔐 Encriptación habilitada" }],
484
+ content: [{ type: "text" as const, text: "🔐 Encryption enabled" }],
537
485
  }
538
486
  }
539
487
  )
@@ -544,35 +492,35 @@ server.registerTool(
544
492
  "memory_decrypt",
545
493
  {
546
494
  title: "Disable Encryption",
547
- description: "Deshabilita la encriptación y decodifica la memoria.",
495
+ description: "Disable encryption and decode memory.",
548
496
  inputSchema: {
549
- key: z.string().describe("Clave de encriptación"),
497
+ key: z.string().describe("Encryption key"),
550
498
  },
551
499
  },
552
500
  async ({ key }) => {
553
501
  const config = loadConfig()
554
502
 
555
503
  if (!config.encrypted) {
556
- return { content: [{ type: "text" as const, text: "La encriptación no está habilitada" }] }
504
+ return { content: [{ type: "text" as const, text: "Encryption is not enabled" }] }
557
505
  }
558
506
 
559
507
  const resolvedKey = key || getKey() || ""
560
508
  if (!resolvedKey) {
561
- return { content: [{ type: "text" as const, text: "❌ No hay clave. Pásala como argumento o la del archivo .env" }] }
509
+ return { content: [{ type: "text" as const, text: "❌ No key provided. Pass as argument or set in .env file" }] }
562
510
  }
563
511
 
564
512
  try {
565
- const data = readFileSync(MEMORY_FILE, "utf-8")
513
+ const data = readUnderLock(MEMORY_FILE)
566
514
  const decrypted = decrypt(data, resolvedKey)
567
515
 
568
- writeFileSync(MEMORY_FILE, decrypted)
516
+ safeWrite(MEMORY_FILE, decrypted)
569
517
  saveConfig({ encrypted: false })
570
518
 
571
519
  return {
572
- content: [{ type: "text" as const, text: "🔓 Encriptación deshabilitada" }],
520
+ content: [{ type: "text" as const, text: "🔓 Encryption disabled" }],
573
521
  }
574
522
  } catch {
575
- return { content: [{ type: "text" as const, text: "❌ Clave incorrecta o datos corruptos" }] }
523
+ return { content: [{ type: "text" as const, text: "❌ Wrong key or corrupted data" }] }
576
524
  }
577
525
  }
578
526
  )
@@ -583,12 +531,12 @@ server.registerTool(
583
531
  "memory_captured",
584
532
  {
585
533
  title: "List Captured Activity",
586
- description: "Muestra el log de actividad capturado automáticamente por los hooks (solo si la captura está habilitada). Útil para promover observaciones a memoria con memory_remember.",
534
+ description: "Show activity log captured automatically by hooks (only if capture is enabled). Useful for promoting observations to memory with memory_remember.",
587
535
  inputSchema: {
588
- limit: z.number().optional().default(20).describe("Máximo de observaciones a mostrar"),
589
- tool: z.string().optional().default("").describe("Filtrar por nombre de herramienta"),
590
- file: z.string().optional().default("").describe("Filtrar por archivo"),
591
- clear: z.boolean().optional().default(false).describe("Si true, limpia el log de captura"),
536
+ limit: z.number().optional().default(20).describe("Maximum observations to show"),
537
+ tool: z.string().optional().default("").describe("Filter by tool name"),
538
+ file: z.string().optional().default("").describe("Filter by file"),
539
+ clear: z.boolean().optional().default(false).describe("If true, clears the capture log"),
592
540
  },
593
541
  },
594
542
  async ({ limit, tool, file, clear }) => {
@@ -596,7 +544,7 @@ server.registerTool(
596
544
  if (existsSync(OBSERVATIONS_FILE)) {
597
545
  writeFileSync(OBSERVATIONS_FILE, "version: 1\nobservations[0|]{ts|session|agent|branch|tool|hash|file|summary}:\n")
598
546
  }
599
- return { content: [{ type: "text" as const, text: "🧹 Log de captura limpiado" }] }
547
+ return { content: [{ type: "text" as const, text: "🧹 Capture log cleared" }] }
600
548
  }
601
549
 
602
550
  let obs = readObservations()
@@ -608,7 +556,7 @@ server.registerTool(
608
556
  return {
609
557
  content: [{
610
558
  type: "text" as const,
611
- text: "No hay actividad capturada. La captura está desactivada por defecto; actívala con `toon-memory capture on`.",
559
+ text: "No captured activity. Capture is disabled by default; enable with `toon-memory capture on`.",
612
560
  }],
613
561
  }
614
562
  }
@@ -617,7 +565,7 @@ server.registerTool(
617
565
  .map((o) => `[${o.ts}] ${o.agent}@${o.branch}/${o.tool}${o.file ? ` (${o.file})` : ""}\n ${o.summary}`)
618
566
  .join("\n\n")
619
567
 
620
- return { content: [{ type: "text" as const, text: `🔍 Actividad capturada (${obs.length}):\n\n${formatted}` }] }
568
+ return { content: [{ type: "text" as const, text: `🔍 Captured activity (${obs.length}):\n\n${formatted}` }] }
621
569
  }
622
570
  )
623
571
 
@@ -627,18 +575,18 @@ server.registerTool(
627
575
  "memory_consolidate",
628
576
  {
629
577
  title: "Consolidate Memory",
630
- description: "Consolida la memoria eliminando entradas con contenido idéntico (mantiene la primera). Determinista, sin LLM.",
578
+ description: "Consolidate memory by removing entries with identical content (keeps the first). Deterministic, no LLM.",
631
579
  inputSchema: {},
632
580
  },
633
581
  async () => {
634
582
  const result = consolidateEntries()
635
583
  if (result.removed === 0) {
636
- return { content: [{ type: "text" as const, text: `✅ Memoria ya consolidada (${result.kept} entradas, 0 duplicados)` }] }
584
+ return { content: [{ type: "text" as const, text: `✅ Memory already consolidated (${result.kept} entries, 0 duplicates)` }] }
637
585
  }
638
586
  return {
639
587
  content: [{
640
588
  type: "text" as const,
641
- text: `🧹 Consolidadas ${result.removed} entradas duplicadas.\nQuedan ${result.kept} activas.\nDuplicados: ${result.duplicates.join(", ")}`,
589
+ text: `🧹 Consolidated ${result.removed} duplicate entries.\n${result.kept} active entries remaining.\nDuplicates: ${result.duplicates.join(", ")}`,
642
590
  }],
643
591
  }
644
592
  }
@@ -650,9 +598,9 @@ server.registerTool(
650
598
  "memory_sessions",
651
599
  {
652
600
  title: "Active Sessions & Conflicts",
653
- description: "Muestra las sesiones de agente activas en este proyecto (rama git, archivos tocados, last-seen) y detecta conflictos suaves (archivos tocados por 2+ sesiones). Úsalo al iniciar para no pisar el trabajo de otras sesiones paralelas.",
601
+ description: "Show active agent sessions in this project (git branch, files touched, last-seen) and detect soft conflicts (files touched by 2+ sessions). Use at startup to avoid overwriting other parallel sessions' work.",
654
602
  inputSchema: {
655
- conflictsOnly: z.boolean().optional().default(false).describe("Si true, muestra solo conflictos suaves"),
603
+ conflictsOnly: z.boolean().optional().default(false).describe("If true, only show soft conflicts"),
656
604
  },
657
605
  },
658
606
  async ({ conflictsOnly }) => {
@@ -661,14 +609,14 @@ server.registerTool(
661
609
 
662
610
  if (conflictsOnly) {
663
611
  if (conflicts.length === 0) {
664
- return { content: [{ type: "text" as const, text: "✅ No hay conflictos suaves entre sesiones activas." }] }
612
+ return { content: [{ type: "text" as const, text: "✅ No soft conflicts between active sessions." }] }
665
613
  }
666
614
  const lines = conflicts.map((c) => {
667
615
  const who = c.sessions.map((s) => `${s.agent}@${s.branch} (${s.id})`).join(", ")
668
616
  return `⚠️ ${c.file}\n ↔ ${who}`
669
617
  })
670
618
  return {
671
- content: [{ type: "text" as const, text: `🔥 Conflictos suaves (${conflicts.length}):\n\n${lines.join("\n\n")}` }],
619
+ content: [{ type: "text" as const, text: `🔥 Soft conflicts (${conflicts.length}):\n\n${lines.join("\n\n")}` }],
672
620
  }
673
621
  }
674
622
 
@@ -676,7 +624,7 @@ server.registerTool(
676
624
  return {
677
625
  content: [{
678
626
  type: "text" as const,
679
- text: "🟢 No hay otras sesiones activas en este proyecto.\n(Esta sesión: " + selfId + " @ " + currentBranch() + ")",
627
+ text: "🟢 No other active sessions in this project.\n(This session: " + selfId + " @ " + currentBranch() + ")",
680
628
  }],
681
629
  }
682
630
  }
@@ -684,27 +632,27 @@ server.registerTool(
684
632
  const ttlMin = Math.round(SESSION_TTL_MS / 60000)
685
633
  const section = (s: ReturnType<typeof coordinationView>["active"][number]) => {
686
634
  const mins = Math.max(0, Math.round(s.ageMs / 60000))
687
- const tag = s.id === selfId ? " (tú)" : ""
635
+ const tag = s.id === selfId ? " (you)" : ""
688
636
  const ended = s.ended ? " 🏁" : ""
689
637
  const files = Object.keys(s.files).slice(0, 8).map((f) => ` • ${f}`).join("\n")
690
- const fileBlock = files ? `\n Archivos:\n${files}` : ""
691
- return `• ${s.agent} @ ${s.branch}${tag}${ended}\n id: ${s.id}\n hace ${mins} min${fileBlock}`
638
+ const fileBlock = files ? `\n Files:\n${files}` : ""
639
+ return `• ${s.agent} @ ${s.branch}${tag}${ended}\n id: ${s.id}\n ${mins} min ago${fileBlock}`
692
640
  }
693
641
 
694
642
  const parts = [
695
- `🧭 Sesiones activas (${active.length}) — ventana ${ttlMin} min:`,
643
+ `🧭 Active sessions (${active.length}) — window ${ttlMin} min:`,
696
644
  "",
697
645
  ...active.map(section),
698
646
  ]
699
647
 
700
648
  if (conflicts.length > 0) {
701
- parts.push("", `🔥 Conflictos suaves (${conflicts.length}):`)
649
+ parts.push("", `🔥 Soft conflicts (${conflicts.length}):`)
702
650
  for (const c of conflicts) {
703
651
  const who = c.sessions.map((s) => `${s.agent}@${s.branch}`).join(", ")
704
652
  parts.push(` ⚠️ ${c.file} ↔ ${who}`)
705
653
  }
706
654
  } else {
707
- parts.push("", "✅ Sin conflictos suaves detectados.")
655
+ parts.push("", "✅ No soft conflicts detected.")
708
656
  }
709
657
 
710
658
  return { content: [{ type: "text" as const, text: parts.join("\n") }] }
@@ -717,10 +665,10 @@ server.registerTool(
717
665
  "context_brief",
718
666
  {
719
667
  title: "Context Briefing",
720
- description: "Genera un briefing de contexto compacto: memoria relevante + sesiones activas + salud del proyecto. Un solo call en vez de 5-6 llamadas separadas. Cero LLM, pura lógica determinista.",
668
+ description: "Generate a compact context briefing: relevant memory + active sessions + project health. Single call instead of 5-6 separate calls. Zero LLM, pure deterministic logic.",
721
669
  inputSchema: {
722
- task: z.string().optional().default("").describe("Tarea actual del agente. Si se provee, las entradas se rankean por relevancia a esta tarea. Si está vacío, muestra las top entradas por importancia."),
723
- limit: z.number().optional().default(6).describe("Máximo de entradas relevantes a mostrar"),
670
+ task: z.string().optional().default("").describe("Current agent task. If provided, entries are ranked by relevance to this task. If empty, shows top entries by importance."),
671
+ limit: z.number().optional().default(6).describe("Maximum relevant entries to show"),
724
672
  },
725
673
  },
726
674
  async ({ task, limit }) => {
@@ -736,9 +684,9 @@ server.registerTool(
736
684
  "context_generate",
737
685
  {
738
686
  title: "Generate Full Context",
739
- description: "Genera un system prompt completo: proyecto (package.json, deps, framework) + git (rama, commits) + memoria (entries relevantes) + sesiones. Un solo call para preparar al agente. Cero LLM.",
687
+ description: "Generate a full system prompt: project (package.json, deps, framework) + git (branch, commits) + memory (relevant entries) + sessions. Single call to prepare the agent. Zero LLM.",
740
688
  inputSchema: {
741
- task: z.string().optional().default("").describe("Tarea del agente. Si se provee, rankea entries por relevancia a esta tarea."),
689
+ task: z.string().optional().default("").describe("Agent task. If provided, ranks entries by relevance to this task."),
742
690
  },
743
691
  },
744
692
  async ({ task }) => {
@@ -755,9 +703,9 @@ server.registerTool(
755
703
  "context_diff",
756
704
  {
757
705
  title: "Context Diff",
758
- description: "Qué cambió desde la última sesión: git commits + archivos modificados + entradas de memoria nuevas/actualizadas. Cero LLM.",
706
+ description: "What changed since the last session: git commits + modified files + new/updated memory entries. Zero LLM.",
759
707
  inputSchema: {
760
- since: z.string().optional().default("").describe("Fecha desde (YYYY-MM-DD o relativa como '7d'). Vacío = últimos cambios visibles."),
708
+ since: z.string().optional().default("").describe("Start date (YYYY-MM-DD or relative like '7d'). Empty = last visible changes."),
761
709
  },
762
710
  },
763
711
  async ({ since }) => {
@@ -774,10 +722,10 @@ server.registerTool(
774
722
  "context_focus",
775
723
  {
776
724
  title: "Focus Context for Task",
777
- description: "Contexto hiper-enfocado para una tarea específica: entries relevantes + archivos relacionados + código que referencia el símbolo + tests existentes. Cero LLM.",
725
+ description: "Hyper-focused context for a specific task: relevant entries + related files + code referencing the symbol + existing tests. Zero LLM.",
778
726
  inputSchema: {
779
- task: z.string().describe("Tarea o símbolo para buscar contexto (ej: 'fix auth bug', 'authenticate')"),
780
- limit: z.number().optional().default(6).describe("Máximo de entries de memoria a incluir"),
727
+ task: z.string().describe("Task or symbol to search context for (e.g. 'fix auth bug', 'authenticate')"),
728
+ limit: z.number().optional().default(6).describe("Maximum memory entries to include"),
781
729
  },
782
730
  },
783
731
  async ({ task, limit }) => {
@@ -794,7 +742,7 @@ server.registerTool(
794
742
  "context_health",
795
743
  {
796
744
  title: "Memory Health Audit",
797
- description: "Auditoría completa de salud de la memoria: links huérfanos, duplicados, refs rotos, TTL expirado, calidad, sesiones stale. Incluye score 0-100. Cero LLM.",
745
+ description: "Full memory health audit: orphan links, duplicates, broken refs, expired TTL, quality, stale sessions. Includes score 0-100. Zero LLM.",
798
746
  inputSchema: {},
799
747
  },
800
748
  async () => {
@@ -811,9 +759,9 @@ server.registerTool(
811
759
  "context_export",
812
760
  {
813
761
  title: "Export Memory as Markdown",
814
- description: "Exporta toda la memoria como markdown inyectable para otros agentes o sesiones. Formato full (detallado) o compacto. Cero LLM.",
762
+ description: "Export all memory as markdown injectable for other agents or sessions. Full (detailed) or compact format. Zero LLM.",
815
763
  inputSchema: {
816
- format: z.enum(["full", "compact"]).optional().default("full").describe("full = detallado con graph, compact = resumido sin edges"),
764
+ format: z.enum(["full", "compact"]).optional().default("full").describe("full = detailed with graph, compact = summarized without edges"),
817
765
  },
818
766
  },
819
767
  async ({ format }) => {
@@ -823,4 +771,57 @@ server.registerTool(
823
771
  }
824
772
  )
825
773
 
774
+ // ── memory_backup ───────────────────────────────────────────────────
775
+
776
+ server.registerTool(
777
+ "memory_backup",
778
+ {
779
+ title: "Backup Memory",
780
+ description: "Create a timestamped backup of the memory file. Use before major operations or to preserve state.",
781
+ inputSchema: {},
782
+ },
783
+ async () => {
784
+ if (!existsSync(MEMORY_FILE)) {
785
+ return { content: [{ type: "text" as const, text: "No memory file to backup" }] }
786
+ }
787
+
788
+ const backupDir = join(MEMORY_DIR, "backups")
789
+ if (!existsSync(backupDir)) mkdirSync(backupDir, { recursive: true })
790
+
791
+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19)
792
+ const backupFile = join(backupDir, `memory-${timestamp}.toon`)
793
+
794
+ copyFileSync(MEMORY_FILE, backupFile)
795
+
796
+ // Also backup archive if it exists
797
+ let archiveBackup = ""
798
+ if (existsSync(ARCHIVE_FILE)) {
799
+ const archiveBackupFile = join(backupDir, `archive-${timestamp}.toon`)
800
+ copyFileSync(ARCHIVE_FILE, archiveBackupFile)
801
+ archiveBackup = `\n📦 Archive backed up`
802
+ }
803
+
804
+ // Prune old backups (keep last 10)
805
+ const backups = readdirSync(backupDir)
806
+ .filter((f) => f.startsWith("memory-") && f.endsWith(".toon"))
807
+ .sort()
808
+ .reverse()
809
+ for (const old of backups.slice(10)) {
810
+ try {
811
+ const { unlinkSync } = require("fs")
812
+ unlinkSync(join(backupDir, old))
813
+ } catch {
814
+ // ignore
815
+ }
816
+ }
817
+
818
+ return {
819
+ content: [{
820
+ type: "text" as const,
821
+ text: `💾 Memory backed up to ${basename(backupFile)}${archiveBackup}\n📦 ${backups.length} backup(s) retained`
822
+ }],
823
+ }
824
+ }
825
+ )
826
+
826
827
  } // end registerTools