toon-memory 2.5.2 → 2.7.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.
@@ -0,0 +1,826 @@
1
+ import type { McpServer } from "@modelcontextprotocol/server"
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"
6
+ import { generateId, parseTTL, isExpired, inferTags, parseRelativeDate } from "./entries"
7
+ import { entryScore, findRelatedEntries, bumpAccessed } from "./scoring"
8
+ import { readObservations } from "./observations"
9
+ import { archiveOldEntries } from "./archive"
10
+ import { consolidateEntries } from "./consolidation"
11
+ import { encrypt, decrypt } from "./crypto"
12
+ import { graphRecallDetailed, renderCompact } from "../lib/graph"
13
+ import { qualityScore, mergeEntries, generateSmartRecall } from "../lib/quality"
14
+ import { generateContextBrief, generateContextGenerate, generateContextDiff, generateContextFocus, generateContextHealth, generateContextExport } from "../lib/context"
15
+ import { coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS } from "../lib/sessions"
16
+
17
+ const normalize = (s: string) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
18
+
19
+ /**
20
+ * Register all 15 memory tools.
21
+ */
22
+ export function registerTools(server: McpServer): void {
23
+
24
+ // ── memory_remember ──────────────────────────────────────────────────────────
25
+
26
+ server.registerTool(
27
+ "memory_remember",
28
+ {
29
+ title: "Save to Memory",
30
+ description: "Guarda un hecho en la memoria persistente del proyecto (decisiones, patrones, bugs, conocimiento). Se recuerda entre sesiones.",
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."),
39
+ },
40
+ },
41
+ async ({ category, key, content, file, tags, ttl, links }) => {
42
+ const data = readMemory()
43
+ const newId = generateId()
44
+ const date = new Date().toISOString().split("T")[0]
45
+ const lines = data.split("\n")
46
+
47
+ let headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
48
+ if (headerIdx === -1) {
49
+ lines.push(`[0|]`)
50
+ headerIdx = lines.length - 1
51
+ }
52
+
53
+ let existingIdx = -1
54
+ let existingId = newId
55
+ for (let i = headerIdx + 1; i < lines.length; i++) {
56
+ const line = lines[i]
57
+ if (!line.startsWith(" ") || !line.includes("|")) continue
58
+ if (line.startsWith(" summaries:")) break
59
+ const parts = line.trim().split("|")
60
+ if (parts[2] === key) {
61
+ existingIdx = i
62
+ existingId = parts[0]
63
+ break
64
+ }
65
+ }
66
+
67
+ const entryId = existingIdx !== -1 ? existingId : newId
68
+ const resolvedTtl = parseTTL(ttl)
69
+ const resolvedTags = tags ? tags : inferTags(content, key, loadConfig().vocab)
70
+ const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : []
71
+ const resolvedLinks = links
72
+ ? links.split(/[\s;]+/).filter(Boolean).join(" ")
73
+ : existingParts[9] || ""
74
+ let newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|0|${resolvedLinks}`
75
+ let action = "Guardado"
76
+ let mergeInfo = ""
77
+ const tagsInferred = !tags && resolvedTags ? true : false
78
+
79
+ if (existingIdx !== -1) {
80
+ newEntry = mergeEntries(lines[existingIdx].trim(), newEntry)
81
+ lines[existingIdx] = ` ${newEntry}`
82
+ action = "Actualizado"
83
+ mergeInfo = "\n🔗 Merge: tags combinados, fecha y links actualizados"
84
+ } else {
85
+ const quality = qualityScore(resolvedTags, resolvedLinks, content, date)
86
+ const confidence = 1.0
87
+ newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|0|${resolvedLinks}|${quality.toFixed(2)}|${confidence}`
88
+ const match = lines[headerIdx].match(/\[(\d+)\|/)
89
+ const count = match ? parseInt(match[1]) : 0
90
+ lines.splice(headerIdx + 1, 0, ` ${newEntry}`)
91
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`)
92
+ }
93
+
94
+ writeMemory(lines.join("\n"))
95
+
96
+ const headerMatch = lines[headerIdx].match(/\[(\d+)\|/)
97
+ const entryCount = headerMatch ? parseInt(headerMatch[1]) : 0
98
+ let archiveMsg = ""
99
+ if (entryCount > MAX_ENTRIES) {
100
+ const result = archiveOldEntries({ trimToMax: true })
101
+ if (result.archived > 0) {
102
+ archiveMsg = `\n📦 Auto-archived ${result.archived} low-importance entries (${result.kept} kept)`
103
+ }
104
+ }
105
+
106
+ const ttlMsg = resolvedTtl ? `\n⏰ TTL: ${resolvedTtl}` : ""
107
+ const inferredMsg = tagsInferred ? `\n🏷️ Tags inferidos: ${resolvedTags}` : ""
108
+
109
+ const related = findRelatedEntries(`${key} ${content} ${resolvedTags}`, key, 3)
110
+ let relatedMsg = ""
111
+ if (related.length > 0) {
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}`
114
+ }
115
+
116
+ return {
117
+ content: [{ type: "text" as const, text: `🧠 ${action}: ${category}/${key} (${entryId})\n${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }],
118
+ }
119
+ }
120
+ )
121
+
122
+ // ── memory_recall ────────────────────────────────────────────────────────────
123
+
124
+ server.registerTool(
125
+ "memory_recall",
126
+ {
127
+ title: "Search Memory",
128
+ description: "Busca en la memoria persistente del proyecto. Devuelve entradas relevantes. Usar ANTES de leer archivos.",
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."),
137
+ },
138
+ },
139
+ async ({ query, category, from_date, to_date, mode, hops, compact }) => {
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
+
164
+ if (results.length === 0) {
165
+ return { content: [{ type: "text" as const, text: `No se encontraron resultados para "${query}"` }] }
166
+ }
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")
188
+ return { content: [{ type: "text" as const, text: formatted }] }
189
+ }
190
+
191
+ const ranked = results
192
+ .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 }
196
+ })
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
+ .join("\n\n")
221
+
222
+ return { content: [{ type: "text" as const, text: formatted }] }
223
+ }
224
+ )
225
+
226
+ // ── memory_forget ────────────────────────────────────────────────────────────
227
+
228
+ server.registerTool(
229
+ "memory_forget",
230
+ {
231
+ title: "Delete from Memory",
232
+ description: "Elimina una entrada de la memoria por su key o id.",
233
+ inputSchema: {
234
+ key: z.string().describe("Key o id de la entrada a eliminar"),
235
+ },
236
+ },
237
+ async ({ key }) => {
238
+ const data = readMemory()
239
+ const lines = data.split("\n")
240
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
241
+
242
+ if (headerIdx === -1) {
243
+ return { content: [{ type: "text" as const, text: "No hay entradas en memoria" }] }
244
+ }
245
+
246
+ const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
247
+ const filtered = entryLines.filter((l) => {
248
+ const parts = l.trim().split("|")
249
+ return parts[0] !== key && parts[2] !== key
250
+ })
251
+
252
+ const removed = entryLines.length - filtered.length
253
+ const match = lines[headerIdx].match(/\[(\d+)\|/)
254
+ const count = match ? parseInt(match[1]) : 0
255
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`)
256
+ lines.splice(headerIdx + 1, entryLines.length, ...filtered.map((l) => ` ${l.trim()}`))
257
+
258
+ writeMemory(lines.join("\n"))
259
+ return {
260
+ content: [{ type: "text" as const, text: `"${key}" eliminado. Quedan ${count - removed} entradas.` }],
261
+ }
262
+ }
263
+ )
264
+
265
+ // ── memory_stats ─────────────────────────────────────────────────────────────
266
+
267
+ server.registerTool(
268
+ "memory_stats",
269
+ {
270
+ title: "Memory Stats",
271
+ description: "Muestra estadísticas de la memoria del proyecto.",
272
+ inputSchema: {},
273
+ },
274
+ async () => {
275
+ const data = readMemory()
276
+ const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
277
+ const entries = lines.map((l) => {
278
+ const parts = l.trim().split("|")
279
+ return { category: parts[1] || "unknown", ttl: parts[7] || "", quality: parts[10] || "" }
280
+ })
281
+
282
+ const byCategory: Record<string, number> = {}
283
+ for (const e of entries) {
284
+ byCategory[e.category] = (byCategory[e.category] || 0) + 1
285
+ }
286
+
287
+ const withTtl = entries.filter((e) => e.ttl).length
288
+ const expired = entries.filter((e) => e.ttl && isExpired(e.ttl)).length
289
+ const withQuality = entries.filter((e) => e.quality).length
290
+ const avgQuality = withQuality > 0
291
+ ? (entries.reduce((sum, e) => sum + (e.quality ? parseFloat(e.quality) : 0), 0) / withQuality).toFixed(2)
292
+ : "N/A"
293
+
294
+ const summaryLines = data.split("\n").filter((l) => l.includes(":") && !l.startsWith(" ") && !l.startsWith("version") && !l.startsWith("entries") && !/^\[\d+\|]/.test(l))
295
+ const stats = [
296
+ `Entradas totales: ${entries.length}`,
297
+ `Resúmenes de archivos: ${summaryLines.length}`,
298
+ "",
299
+ "Por categoría:",
300
+ ...Object.entries(byCategory).map(([k, v]) => ` ${k}: ${v}`),
301
+ "",
302
+ `TTL: ${withTtl} con expiración, ${expired} expiradas`,
303
+ `Calidad promedio: ${avgQuality} (${withQuality} con score)`,
304
+ "",
305
+ `Últimas 5 entradas:`,
306
+ ...lines.slice(-5).map((l) => {
307
+ const parts = l.trim().split("|")
308
+ const ttlInfo = parts[7] ? ` | TTL: ${parts[7]}` : ""
309
+ const qualityInfo = parts[10] ? ` | Q: ${parts[10]}` : ""
310
+ return ` [${parts[1]}] ${parts[2]} (${parts[0]})${ttlInfo}${qualityInfo}`
311
+ }),
312
+ ]
313
+
314
+ return { content: [{ type: "text" as const, text: stats.join("\n") }] }
315
+ }
316
+ )
317
+
318
+ // ── memory_diff ──────────────────────────────────────────────────────────────
319
+
320
+ server.registerTool(
321
+ "memory_diff",
322
+ {
323
+ 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.",
325
+ 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"),
328
+ },
329
+ },
330
+ async ({ since, type }) => {
331
+ const sinceDate = parseRelativeDate(since)
332
+ const today = new Date().toISOString().split("T")[0]
333
+ const data = readMemory()
334
+ const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
335
+
336
+ const results = lines
337
+ .map((line) => {
338
+ const trimmed = line.trim()
339
+ const parts = trimmed.split("|")
340
+ if (parts.length < 7) return null
341
+ const [id, cat, key, content, file, tags, date] = parts
342
+ if (date < sinceDate) return null
343
+ const changeType = date === today ? "created" : "updated"
344
+ if (type !== "all" && changeType !== type) return null
345
+ return { id, cat, key, content, file, tags, date, changeType }
346
+ })
347
+ .filter(Boolean)
348
+
349
+ if (results.length === 0) {
350
+ return { content: [{ type: "text" as const, text: `No hay cambios desde ${sinceDate}` }] }
351
+ }
352
+
353
+ const created = results.filter((r) => r!.changeType === "created")
354
+ const updated = results.filter((r) => r!.changeType === "updated")
355
+
356
+ const sections: string[] = [`📋 Cambios desde ${sinceDate}:`, ""]
357
+
358
+ if (created.length > 0 && (type === "all" || type === "created")) {
359
+ sections.push(`➕ Nuevas (${created.length}):`)
360
+ for (const r of created) {
361
+ sections.push(` [${r!.cat}] ${r!.key} (${r!.id})\n ${r!.content}`)
362
+ }
363
+ sections.push("")
364
+ }
365
+
366
+ if (updated.length > 0 && (type === "all" || type === "updated")) {
367
+ sections.push(`✏️ Actualizadas (${updated.length}):`)
368
+ for (const r of updated) {
369
+ sections.push(` [${r!.cat}] ${r!.key} (${r!.id}) — ${r!.date}`)
370
+ }
371
+ sections.push("")
372
+ }
373
+
374
+ return { content: [{ type: "text" as const, text: sections.join("\n") }] }
375
+ }
376
+ )
377
+
378
+ // ── memory_suggest ───────────────────────────────────────────────────────────
379
+
380
+ server.registerTool(
381
+ "memory_suggest",
382
+ {
383
+ title: "Suggest Related Memories",
384
+ description: "Sugiere entradas de memoria relacionadas con un contexto dado. Útil para obtener contexto antes de una tarea.",
385
+ inputSchema: {
386
+ context: z.string().describe("Texto o contexto para buscar sugerencias"),
387
+ limit: z.number().optional().default(5).describe("Máximo de sugerencias"),
388
+ },
389
+ },
390
+ async ({ context, limit }) => {
391
+ const related = findRelatedEntries(context, "", limit)
392
+
393
+ if (related.length === 0) {
394
+ return { content: [{ type: "text" as const, text: `No se encontraron entradas relacionadas con "${context}"` }] }
395
+ }
396
+
397
+ const formatted = related
398
+ .map((r) => `[${r.cat}] ${r.key} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`)
399
+ .join("\n\n")
400
+
401
+ return { content: [{ type: "text" as const, text: `🔍 Sugerencias para "${context}":\n\n${formatted}` }] }
402
+ }
403
+ )
404
+
405
+ // ── memory_smart_recall ──────────────────────────────────────────────────────
406
+
407
+ server.registerTool(
408
+ "memory_smart_recall",
409
+ {
410
+ 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.",
412
+ 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)"),
416
+ },
417
+ },
418
+ async ({ intent, limit, category }) => {
419
+ const data = readMemory()
420
+ const result = generateSmartRecall(data, intent, { limit, category })
421
+ return { content: [{ type: "text" as const, text: result }] }
422
+ }
423
+ )
424
+
425
+ // ── memory_summary ───────────────────────────────────────────────────────────
426
+
427
+ server.registerTool(
428
+ "memory_summary",
429
+ {
430
+ title: "File Summary",
431
+ description: "Guarda o recupera un resumen de un archivo grande para ahorrar tokens.",
432
+ 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)"),
436
+ },
437
+ },
438
+ async ({ action, file, summary }) => {
439
+ const data = readMemory()
440
+
441
+ if (action === "get") {
442
+ const lines = data.split("\n")
443
+ const summaryIdx = lines.findIndex((l) => l.trim().startsWith("summaries:"))
444
+ if (summaryIdx === -1) {
445
+ return { content: [{ type: "text" as const, text: `No hay resúmenes guardados para "${file}"` }] }
446
+ }
447
+
448
+ const summaryLines = lines.slice(summaryIdx + 1).filter((l) => l.includes(":"))
449
+ const match = summaryLines.find((l) => l.startsWith(` ${file}:`))
450
+ if (!match) {
451
+ return { content: [{ type: "text" as const, text: `No hay resumen para "${file}"` }] }
452
+ }
453
+
454
+ const summaryText = match.replace(` ${file}: `, "")
455
+ return { content: [{ type: "text" as const, text: summaryText }] }
456
+ }
457
+
458
+ const lines = data.split("\n")
459
+ let summaryIdx = lines.findIndex((l) => l.trim().startsWith("summaries:"))
460
+
461
+ if (summaryIdx === -1) {
462
+ lines.push("", "summaries:")
463
+ summaryIdx = lines.length - 1
464
+ }
465
+
466
+ const summaryLines = lines.slice(summaryIdx + 1).filter((l) => l.includes(":"))
467
+ const existingIdx = summaryLines.findIndex((l) => l.startsWith(` ${file}:`))
468
+
469
+ if (existingIdx !== -1) {
470
+ summaryLines[existingIdx] = ` ${file}: ${summary}`
471
+ } else {
472
+ summaryLines.push(` ${file}: ${summary}`)
473
+ }
474
+
475
+ lines.splice(summaryIdx + 1, lines.length - summaryIdx - 1, ...summaryLines)
476
+ writeMemory(lines.join("\n"))
477
+ return {
478
+ content: [{ type: "text" as const, text: `📝 Resumen guardado para ${file}` }],
479
+ }
480
+ }
481
+ )
482
+
483
+ // ── memory_archive ───────────────────────────────────────────────────────────
484
+
485
+ server.registerTool(
486
+ "memory_archive",
487
+ {
488
+ title: "Archive Old Entries",
489
+ description: "Mover entradas antiguas (>30 días) a archive.toon para mantener la memoria limpia.",
490
+ inputSchema: {},
491
+ },
492
+ async () => {
493
+ const result = archiveOldEntries()
494
+
495
+ if (result.archived === 0) {
496
+ return { content: [{ type: "text" as const, text: "No hay entradas antiguas para archivar" }] }
497
+ }
498
+
499
+ return {
500
+ content: [{
501
+ type: "text" as const,
502
+ text: `📦 Archivadas ${result.archived} entradas antiguas\n📋 Quedan ${result.kept} entradas activas`
503
+ }],
504
+ }
505
+ }
506
+ )
507
+
508
+ // ── memory_encrypt ───────────────────────────────────────────────────────────
509
+
510
+ server.registerTool(
511
+ "memory_encrypt",
512
+ {
513
+ title: "Enable Encryption",
514
+ description: "Habilita encriptación AES-256-GCM para la memoria. La clave se genera automáticamente.",
515
+ inputSchema: {},
516
+ },
517
+ async () => {
518
+ const config = loadConfig()
519
+
520
+ if (config.encrypted) {
521
+ return { content: [{ type: "text" as const, text: "La encriptación ya está habilitada" }] }
522
+ }
523
+
524
+ const key = getKey()
525
+ if (!key) {
526
+ return { content: [{ type: "text" as const, text: "❌ Define TOON_MEMORY_KEY en el entorno antes de encriptar" }] }
527
+ }
528
+
529
+ const data = readFileSync(MEMORY_FILE, "utf-8")
530
+ const encrypted = encrypt(data, key)
531
+ writeFileSync(MEMORY_FILE, encrypted)
532
+
533
+ saveConfig({ encrypted: true })
534
+
535
+ return {
536
+ content: [{ type: "text" as const, text: "🔐 Encriptación habilitada" }],
537
+ }
538
+ }
539
+ )
540
+
541
+ // ── memory_decrypt ───────────────────────────────────────────────────────────
542
+
543
+ server.registerTool(
544
+ "memory_decrypt",
545
+ {
546
+ title: "Disable Encryption",
547
+ description: "Deshabilita la encriptación y decodifica la memoria.",
548
+ inputSchema: {
549
+ key: z.string().describe("Clave de encriptación"),
550
+ },
551
+ },
552
+ async ({ key }) => {
553
+ const config = loadConfig()
554
+
555
+ if (!config.encrypted) {
556
+ return { content: [{ type: "text" as const, text: "La encriptación no está habilitada" }] }
557
+ }
558
+
559
+ const resolvedKey = key || getKey() || ""
560
+ if (!resolvedKey) {
561
+ return { content: [{ type: "text" as const, text: "❌ No hay clave. Pásala como argumento o la del archivo .env" }] }
562
+ }
563
+
564
+ try {
565
+ const data = readFileSync(MEMORY_FILE, "utf-8")
566
+ const decrypted = decrypt(data, resolvedKey)
567
+
568
+ writeFileSync(MEMORY_FILE, decrypted)
569
+ saveConfig({ encrypted: false })
570
+
571
+ return {
572
+ content: [{ type: "text" as const, text: "🔓 Encriptación deshabilitada" }],
573
+ }
574
+ } catch {
575
+ return { content: [{ type: "text" as const, text: "❌ Clave incorrecta o datos corruptos" }] }
576
+ }
577
+ }
578
+ )
579
+
580
+ // ── memory_captured ──────────────────────────────────────────────────────────
581
+
582
+ server.registerTool(
583
+ "memory_captured",
584
+ {
585
+ 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.",
587
+ 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"),
592
+ },
593
+ },
594
+ async ({ limit, tool, file, clear }) => {
595
+ if (clear) {
596
+ if (existsSync(OBSERVATIONS_FILE)) {
597
+ writeFileSync(OBSERVATIONS_FILE, "version: 1\nobservations[0|]{ts|session|agent|branch|tool|hash|file|summary}:\n")
598
+ }
599
+ return { content: [{ type: "text" as const, text: "🧹 Log de captura limpiado" }] }
600
+ }
601
+
602
+ let obs = readObservations()
603
+ if (tool) obs = obs.filter((o) => o.tool.toLowerCase().includes(tool.toLowerCase()))
604
+ if (file) obs = obs.filter((o) => o.file.toLowerCase().includes(file.toLowerCase()))
605
+ obs = obs.slice(-limit).reverse()
606
+
607
+ if (obs.length === 0) {
608
+ return {
609
+ content: [{
610
+ type: "text" as const,
611
+ text: "No hay actividad capturada. La captura está desactivada por defecto; actívala con `toon-memory capture on`.",
612
+ }],
613
+ }
614
+ }
615
+
616
+ const formatted = obs
617
+ .map((o) => `[${o.ts}] ${o.agent}@${o.branch}/${o.tool}${o.file ? ` (${o.file})` : ""}\n ${o.summary}`)
618
+ .join("\n\n")
619
+
620
+ return { content: [{ type: "text" as const, text: `🔍 Actividad capturada (${obs.length}):\n\n${formatted}` }] }
621
+ }
622
+ )
623
+
624
+ // ── memory_consolidate ───────────────────────────────────────────────────────
625
+
626
+ server.registerTool(
627
+ "memory_consolidate",
628
+ {
629
+ title: "Consolidate Memory",
630
+ description: "Consolida la memoria eliminando entradas con contenido idéntico (mantiene la primera). Determinista, sin LLM.",
631
+ inputSchema: {},
632
+ },
633
+ async () => {
634
+ const result = consolidateEntries()
635
+ if (result.removed === 0) {
636
+ return { content: [{ type: "text" as const, text: `✅ Memoria ya consolidada (${result.kept} entradas, 0 duplicados)` }] }
637
+ }
638
+ return {
639
+ content: [{
640
+ type: "text" as const,
641
+ text: `🧹 Consolidadas ${result.removed} entradas duplicadas.\nQuedan ${result.kept} activas.\nDuplicados: ${result.duplicates.join(", ")}`,
642
+ }],
643
+ }
644
+ }
645
+ )
646
+
647
+ // ── memory_sessions ──────────────────────────────────────────────────────────
648
+
649
+ server.registerTool(
650
+ "memory_sessions",
651
+ {
652
+ 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.",
654
+ inputSchema: {
655
+ conflictsOnly: z.boolean().optional().default(false).describe("Si true, muestra solo conflictos suaves"),
656
+ },
657
+ },
658
+ async ({ conflictsOnly }) => {
659
+ const selfId = resolveSessionId()
660
+ const { active, conflicts } = coordinationView(selfId)
661
+
662
+ if (conflictsOnly) {
663
+ if (conflicts.length === 0) {
664
+ return { content: [{ type: "text" as const, text: "✅ No hay conflictos suaves entre sesiones activas." }] }
665
+ }
666
+ const lines = conflicts.map((c) => {
667
+ const who = c.sessions.map((s) => `${s.agent}@${s.branch} (${s.id})`).join(", ")
668
+ return `⚠️ ${c.file}\n ↔ ${who}`
669
+ })
670
+ return {
671
+ content: [{ type: "text" as const, text: `🔥 Conflictos suaves (${conflicts.length}):\n\n${lines.join("\n\n")}` }],
672
+ }
673
+ }
674
+
675
+ if (active.length === 0) {
676
+ return {
677
+ content: [{
678
+ type: "text" as const,
679
+ text: "🟢 No hay otras sesiones activas en este proyecto.\n(Esta sesión: " + selfId + " @ " + currentBranch() + ")",
680
+ }],
681
+ }
682
+ }
683
+
684
+ const ttlMin = Math.round(SESSION_TTL_MS / 60000)
685
+ const section = (s: ReturnType<typeof coordinationView>["active"][number]) => {
686
+ const mins = Math.max(0, Math.round(s.ageMs / 60000))
687
+ const tag = s.id === selfId ? " (tú)" : ""
688
+ const ended = s.ended ? " 🏁" : ""
689
+ 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}`
692
+ }
693
+
694
+ const parts = [
695
+ `🧭 Sesiones activas (${active.length}) — ventana ${ttlMin} min:`,
696
+ "",
697
+ ...active.map(section),
698
+ ]
699
+
700
+ if (conflicts.length > 0) {
701
+ parts.push("", `🔥 Conflictos suaves (${conflicts.length}):`)
702
+ for (const c of conflicts) {
703
+ const who = c.sessions.map((s) => `${s.agent}@${s.branch}`).join(", ")
704
+ parts.push(` ⚠️ ${c.file} ↔ ${who}`)
705
+ }
706
+ } else {
707
+ parts.push("", "✅ Sin conflictos suaves detectados.")
708
+ }
709
+
710
+ return { content: [{ type: "text" as const, text: parts.join("\n") }] }
711
+ }
712
+ )
713
+
714
+ // ── context_brief ────────────────────────────────────────────────────────────
715
+
716
+ server.registerTool(
717
+ "context_brief",
718
+ {
719
+ 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.",
721
+ 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"),
724
+ },
725
+ },
726
+ async ({ task, limit }) => {
727
+ const data = readMemory()
728
+ const brief = generateContextBrief(data, { task: task || undefined, limit })
729
+ return { content: [{ type: "text" as const, text: brief }] }
730
+ }
731
+ )
732
+
733
+ // ── context_generate ─────────────────────────────────────────────────
734
+
735
+ server.registerTool(
736
+ "context_generate",
737
+ {
738
+ 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.",
740
+ inputSchema: {
741
+ task: z.string().optional().default("").describe("Tarea del agente. Si se provee, rankea entries por relevancia a esta tarea."),
742
+ },
743
+ },
744
+ async ({ task }) => {
745
+ const data = readMemory()
746
+ const root = process.cwd()
747
+ const brief = generateContextGenerate(data, root, { task: task || undefined })
748
+ return { content: [{ type: "text" as const, text: brief }] }
749
+ }
750
+ )
751
+
752
+ // ── context_diff ─────────────────────────────────────────────────────
753
+
754
+ server.registerTool(
755
+ "context_diff",
756
+ {
757
+ title: "Context Diff",
758
+ description: "Qué cambió desde la última sesión: git commits + archivos modificados + entradas de memoria nuevas/actualizadas. Cero LLM.",
759
+ inputSchema: {
760
+ since: z.string().optional().default("").describe("Fecha desde (YYYY-MM-DD o relativa como '7d'). Vacío = últimos cambios visibles."),
761
+ },
762
+ },
763
+ async ({ since }) => {
764
+ const data = readMemory()
765
+ const root = process.cwd()
766
+ const diff = generateContextDiff(data, root, since || undefined)
767
+ return { content: [{ type: "text" as const, text: diff }] }
768
+ }
769
+ )
770
+
771
+ // ── context_focus ────────────────────────────────────────────────────
772
+
773
+ server.registerTool(
774
+ "context_focus",
775
+ {
776
+ 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.",
778
+ 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"),
781
+ },
782
+ },
783
+ async ({ task, limit }) => {
784
+ const data = readMemory()
785
+ const root = process.cwd()
786
+ const focused = generateContextFocus(data, root, task, { limit })
787
+ return { content: [{ type: "text" as const, text: focused }] }
788
+ }
789
+ )
790
+
791
+ // ── context_health ───────────────────────────────────────────────────
792
+
793
+ server.registerTool(
794
+ "context_health",
795
+ {
796
+ 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.",
798
+ inputSchema: {},
799
+ },
800
+ async () => {
801
+ const data = readMemory()
802
+ const root = process.cwd()
803
+ const { markdown } = generateContextHealth(data, root)
804
+ return { content: [{ type: "text" as const, text: markdown }] }
805
+ }
806
+ )
807
+
808
+ // ── context_export ───────────────────────────────────────────────────
809
+
810
+ server.registerTool(
811
+ "context_export",
812
+ {
813
+ 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.",
815
+ inputSchema: {
816
+ format: z.enum(["full", "compact"]).optional().default("full").describe("full = detallado con graph, compact = resumido sin edges"),
817
+ },
818
+ },
819
+ async ({ format }) => {
820
+ const data = readMemory()
821
+ const exported = generateContextExport(data, format as "full" | "compact")
822
+ return { content: [{ type: "text" as const, text: exported }] }
823
+ }
824
+ )
825
+
826
+ } // end registerTools