toon-memory 2.5.2 → 2.8.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,637 @@
1
+ /**
2
+ * Context briefing generator for toon-memory.
3
+ *
4
+ * Combines multiple data sources (memory entries, sessions, git state,
5
+ * health checks) into a single compact markdown string — zero LLM calls,
6
+ * pure deterministic logic. The agent calls one tool instead of 5-6
7
+ * separate memory_* calls, saving tokens on both sides.
8
+ *
9
+ * Design principles:
10
+ * - No LLM, no network, no embeddings
11
+ * - Output targets ~200-400 tokens (compact by default)
12
+ * - Reuses graph, quality, and sessions library modules
13
+ * - All data is read-only — no mutations
14
+ */
15
+
16
+ import { existsSync, readFileSync } from "fs"
17
+ import { join } from "path"
18
+ import { parseEntries, buildGraph, bm25Scores, centrality, renderCompact, type GraphEntry } from "./graph"
19
+ import { qualityScore } from "./quality"
20
+ import { normalize, isExpiredLocal, tokenize, importance } from "./utils"
21
+ import { coordinationView, currentBranch, pruneSessions, listSessions } from "./sessions"
22
+ import { readRecentCommits, gitStatusSummary, readGitIndex } from "./git"
23
+ import { scanProjectStructure, readManifest, readEnvExample } from "./project-scan"
24
+ import { findFilesByPattern, searchCode, findCallers } from "./code-search"
25
+
26
+ // ── Section builders ────────────────────────────────────────────────
27
+
28
+ /**
29
+ * Memory overview: entry count + category breakdown.
30
+ * ~2-3 lines, ~30 tokens.
31
+ */
32
+ function formatOverview(data: string): string {
33
+ const entries = parseEntries(data)
34
+ if (entries.length === 0) return "Memoria: vacía"
35
+
36
+ const byCategory: Record<string, number> = {}
37
+ let expired = 0
38
+ for (const e of entries) {
39
+ byCategory[e.category] = (byCategory[e.category] || 0) + 1
40
+ if (e.ttl && isExpiredLocal(e.ttl)) expired++
41
+ }
42
+
43
+ const cats = Object.entries(byCategory)
44
+ .map(([k, v]) => `${k}:${v}`)
45
+ .join(" ")
46
+ const ttlNote = expired > 0 ? ` | ${expired} expiradas` : ""
47
+
48
+ return `## Memoria (${entries.length} entradas)${ttlNote}\n${cats}`
49
+ }
50
+
51
+ /**
52
+ * Relevant entries for a task: smart recall using BM25 + centrality + importance.
53
+ * Skipped when task is empty (general briefing mode).
54
+ */
55
+ function formatRelevantEntries(data: string, task: string, limit: number = 6): string {
56
+ const entries = parseEntries(data)
57
+ if (entries.length === 0) return ""
58
+
59
+ const { adjacency, byKey } = buildGraph(entries)
60
+ const bm25 = bm25Scores(entries, task)
61
+ const cent = centrality(adjacency)
62
+ const qTokens = tokenize(task)
63
+
64
+ const scored = entries
65
+ .filter((e) => !(e.ttl && isExpiredLocal(e.ttl)))
66
+ .map((e) => {
67
+ const text = normalize(
68
+ `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
69
+ )
70
+ const matchesQuery = qTokens.length === 0 || qTokens.some((t) => text.includes(t))
71
+ const bm25Score = bm25.get(e.key) || 0
72
+ const centScore = cent.get(e.key) || 0
73
+ const impScore = importance(e)
74
+ const combined =
75
+ bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0)
76
+ return { entry: e, score: combined, matchesQuery }
77
+ })
78
+ .filter((x) => x.score > 0 || x.matchesQuery)
79
+ .sort((a, b) => b.score - a.score)
80
+ .slice(0, limit)
81
+
82
+ if (scored.length === 0) return ""
83
+
84
+ // Build a compact subgraph for edge rendering
85
+ const selectedKeys = new Set(scored.map((x) => x.entry.key))
86
+ const subAdj = new Map<string, string[]>()
87
+ for (const x of scored) {
88
+ const nb = (adjacency.get(x.entry.key) || []).filter((k) => selectedKeys.has(k))
89
+ if (nb.length) subAdj.set(x.entry.key, nb)
90
+ }
91
+
92
+ const seeds = new Set(scored.filter((x) => x.matchesQuery).map((x) => x.entry.key))
93
+ const rendered = renderCompact(
94
+ scored.map((x) => x.entry),
95
+ { adjacency: subAdj, seeds, snippetLen: 80 }
96
+ )
97
+
98
+ return `## Entradas relevantes\n${rendered}`
99
+ }
100
+
101
+ /**
102
+ * Top patterns/rules from memory. These are mandatory conventions the agent
103
+ * must follow. Limited to 5 for token efficiency.
104
+ */
105
+ function formatPatterns(data: string): string {
106
+ const entries = parseEntries(data)
107
+ const patterns = entries
108
+ .filter((e) => e.category === "pattern")
109
+ .sort((a, b) => importance(b) - importance(a))
110
+ .slice(0, 5)
111
+
112
+ if (patterns.length === 0) return ""
113
+
114
+ const lines = patterns.map(
115
+ (e) => `- **${e.key}**: ${e.content.slice(0, 120)}`
116
+ )
117
+ return `## Patrones establecidos\n${lines.join("\n")}`
118
+ }
119
+
120
+ /**
121
+ * Active sessions and soft conflicts. ~3-5 lines.
122
+ */
123
+ function formatSessions(): string {
124
+ pruneSessions()
125
+ const { active, conflicts } = coordinationView()
126
+ const branch = currentBranch()
127
+
128
+ if (active.length === 0 && conflicts.length === 0) {
129
+ return `## Sesiones\nRama: ${branch} | Sin otras sesiones activas`
130
+ }
131
+
132
+ const lines: string[] = [`## Sesiones (${active.length} activa${active.length !== 1 ? "s" : ""}) —rama: ${branch}`]
133
+
134
+ for (const s of active.slice(0, 5)) {
135
+ const mins = Math.max(0, Math.round(s.ageMs / 60000))
136
+ const files = Object.keys(s.files).length
137
+ lines.push(`- ${s.agent}@${s.branch} (${mins}min, ${files} archivos)`)
138
+ }
139
+
140
+ if (conflicts.length > 0) {
141
+ lines.push("", `**Conflictos suaves (${conflicts.length}):**`)
142
+ for (const c of conflicts.slice(0, 3)) {
143
+ const who = c.sessions.map((s) => s.agent).join(" + ")
144
+ lines.push(`- ${c.file} ↔ ${who}`)
145
+ }
146
+ }
147
+
148
+ return lines.join("\n")
149
+ }
150
+
151
+ /**
152
+ * Health warnings: expired entries, high entry count, etc.
153
+ * Only included when there are actual warnings.
154
+ */
155
+ function formatHealth(data: string): string {
156
+ const entries = parseEntries(data)
157
+ const warnings: string[] = []
158
+
159
+ const expired = entries.filter((e) => e.ttl && isExpiredLocal(e.ttl))
160
+ if (expired.length > 0) {
161
+ warnings.push(`${expired.length} entradas con TTL expirado (ejecutar memory_archive)`)
162
+ }
163
+
164
+ if (entries.length > 80) {
165
+ warnings.push(`${entries.length} entradas (cerca del límite de 100, auto-archive se activará)`)
166
+ }
167
+
168
+ const orphanLinks = findOrphanLinks(entries)
169
+ if (orphanLinks.length > 0) {
170
+ warnings.push(`${orphanLinks.length} links huérfanos: ${orphanLinks.slice(0, 3).join(", ")}`)
171
+ }
172
+
173
+ if (warnings.length === 0) return ""
174
+
175
+ return `## Salud\n⚠️ ${warnings.join("\n⚠️ ")}`
176
+ }
177
+
178
+ /**
179
+ * Find links that reference non-existent keys.
180
+ */
181
+ function findOrphanLinks(entries: GraphEntry[]): string[] {
182
+ const keys = new Set(entries.map((e) => e.key))
183
+ const orphans: string[] = []
184
+ for (const e of entries) {
185
+ for (const link of e.links) {
186
+ if (!keys.has(link)) orphans.push(`${e.key}->${link}`)
187
+ }
188
+ }
189
+ return orphans
190
+ }
191
+
192
+ // ── Main entry point ────────────────────────────────────────────────
193
+
194
+ export interface ContextBriefOpts {
195
+ /** When provided, entries are ranked by relevance to this task. */
196
+ task?: string
197
+ /** Max entries in the relevant-entries section. Default 6. */
198
+ limit?: number
199
+ }
200
+
201
+ /**
202
+ * Generate a single context briefing from memory + sessions + health.
203
+ *
204
+ * Zero LLM calls. The output is a compact markdown string (~200-400 tokens)
205
+ * that the agent can inject directly into its context window.
206
+ *
207
+ * Two modes:
208
+ * - **task mode** (task provided): entries ranked by relevance to the task,
209
+ * plus overview, sessions, patterns, and health warnings.
210
+ * - **general mode** (no task): top entries by importance, plus overview,
211
+ * sessions, patterns, and health warnings.
212
+ */
213
+ export function generateContextBrief(data: string, opts: ContextBriefOpts = {}): string {
214
+ const sections: string[] = []
215
+
216
+ // 1. Overview (always included)
217
+ sections.push(formatOverview(data))
218
+
219
+ // 2. Relevant entries (task mode) or top entries (general mode)
220
+ if (opts.task) {
221
+ const relevant = formatRelevantEntries(data, opts.task, opts.limit)
222
+ if (relevant) sections.push(relevant)
223
+ } else {
224
+ const top = formatTopEntries(data, opts.limit ?? 6)
225
+ if (top) sections.push(top)
226
+ }
227
+
228
+ // 3. Patterns (always if present)
229
+ sections.push(formatPatterns(data))
230
+
231
+ // 4. Sessions (always)
232
+ sections.push(formatSessions())
233
+
234
+ // 5. Health warnings (only when relevant)
235
+ sections.push(formatHealth(data))
236
+
237
+ return sections.filter(Boolean).join("\n\n")
238
+ }
239
+
240
+ /**
241
+ * Top entries by importance (general mode fallback).
242
+ */
243
+ function formatTopEntries(data: string, limit: number): string {
244
+ const entries = parseEntries(data)
245
+ if (entries.length === 0) return ""
246
+
247
+ const top = [...entries]
248
+ .filter((e) => !(e.ttl && isExpiredLocal(e.ttl)))
249
+ .sort((a, b) => importance(b) - importance(a))
250
+ .slice(0, limit)
251
+
252
+ if (top.length === 0) return ""
253
+
254
+ const rendered = renderCompact(top)
255
+ return `## Top memorias\n${rendered}`
256
+ }
257
+
258
+ // ── context_generate ─────────────────────────────────────────────────
259
+
260
+ export interface ContextGenerateOpts {
261
+ task?: string
262
+ }
263
+
264
+ /**
265
+ * Full context briefing: project + git + memory → system prompt ready.
266
+ * Reads the actual project filesystem, not just memory.
267
+ * ~400-600 tokens. Zero LLM.
268
+ */
269
+ export function generateContextGenerate(data: string, root: string, opts: ContextGenerateOpts = {}): string {
270
+ const sections: string[] = []
271
+
272
+ // 1. Project manifest
273
+ const manifest = readManifest(root)
274
+ if (manifest) {
275
+ const deps = manifest.deps.length > 0 ? manifest.deps.slice(0, 15).join(", ") : "ninguna"
276
+ const version = manifest.version ? ` v${manifest.version}` : ""
277
+ sections.push(`## Proyecto\n${manifest.name}${version} (${manifest.language})\nDeps: ${deps}`)
278
+ }
279
+
280
+ // 2. Structure
281
+ const structure = scanProjectStructure(root)
282
+ if (structure.dirs.length > 0 || structure.rootFiles.length > 0) {
283
+ const dirs = structure.dirs.length > 0 ? `Dirs: ${structure.dirs.join(", ")}` : ""
284
+ const files = structure.rootFiles.length > 0 ? `Root: ${structure.rootFiles.slice(0, 10).join(", ")}` : ""
285
+ const exts = Object.entries(structure.extensions)
286
+ .sort((a, b) => b[1] - a[1])
287
+ .slice(0, 5)
288
+ .map(([k, v]) => `${k}:${v}`)
289
+ .join(" ")
290
+ const src = `${structure.sourceFileCount} archivos fuente`
291
+ const parts = [dirs, files, `${src} ${exts ? `(${exts})` : ""}`].filter(Boolean)
292
+ if (parts.length > 0) sections.push(`## Estructura\n${parts.join("\n")}`)
293
+ }
294
+
295
+ // 3. Environment variables
296
+ const envVars = readEnvExample(root)
297
+ if (envVars.length > 0) {
298
+ const envLines = envVars.slice(0, 8).map((v) => `- ${v.name}${v.comment ? ` — ${v.comment}` : ""}`)
299
+ sections.push(`## Env vars (${envVars.length})\n${envLines.join("\n")}`)
300
+ }
301
+
302
+ // 4. Git status
303
+ const git = gitStatusSummary(root)
304
+ if (git.branch !== "unknown") {
305
+ const recent = git.recentCommits.slice(0, 3)
306
+ const commitLines = recent.map((c) => `- ${c.shortHash} ${c.subject}`)
307
+ const parts = [`Rama: ${git.branch}`, `Archivos tracked: ${git.trackedFiles}`]
308
+ if (commitLines.length > 0) parts.push(`Últimos commits:\n${commitLines.join("\n")}`)
309
+ sections.push(`## Git\n${parts.join("\n")}`)
310
+ }
311
+
312
+ // 5. Memory overview + entries
313
+ sections.push(formatOverview(data))
314
+ if (opts.task) {
315
+ const relevant = formatRelevantEntries(data, opts.task, 6)
316
+ if (relevant) sections.push(relevant)
317
+ } else {
318
+ const top = formatTopEntries(data, 6)
319
+ if (top) sections.push(top)
320
+ }
321
+ sections.push(formatPatterns(data))
322
+
323
+ // 6. Sessions
324
+ sections.push(formatSessions())
325
+
326
+ // 7. Health
327
+ sections.push(formatHealth(data))
328
+
329
+ return sections.filter(Boolean).join("\n\n")
330
+ }
331
+
332
+ // ── context_diff ─────────────────────────────────────────────────────
333
+
334
+ /**
335
+ * What changed since the last session: git commits + memory changes + touched files.
336
+ * ~200-400 tokens. Zero LLM.
337
+ */
338
+ export function generateContextDiff(data: string, root: string, since?: string): string {
339
+ const sections: string[] = []
340
+
341
+ // 1. Git commits
342
+ const commits = readRecentCommits(10, root)
343
+ if (commits.length > 0) {
344
+ const cutoff = since || commits[0]?.date || ""
345
+ const recent = cutoff
346
+ ? commits.filter((c) => c.date >= cutoff)
347
+ : commits.slice(0, 5)
348
+ if (recent.length > 0) {
349
+ const lines = recent.map((c) => `- ${c.shortHash} (${c.date}) ${c.subject}`)
350
+ sections.push(`## Git commits (${recent.length})\n${lines.join("\n")}`)
351
+ }
352
+ }
353
+
354
+ // 2. Modified files from git index
355
+ const tracked = readGitIndex(root)
356
+ if (tracked.length > 0) {
357
+ sections.push(`## Archivos tracked (${tracked.length})\n${tracked.slice(0, 20).join("\n")}`)
358
+ }
359
+
360
+ // 3. Memory changes (reuse existing diff logic)
361
+ const entries = parseEntries(data)
362
+ const today = new Date().toISOString().split("T")[0]
363
+ const sinceDate = since || today
364
+ const recentEntries = entries.filter((e) => e.date >= sinceDate)
365
+ if (recentEntries.length > 0) {
366
+ const created = recentEntries.filter((e) => e.date === today)
367
+ const updated = recentEntries.filter((e) => e.date !== today)
368
+ const parts: string[] = []
369
+ if (created.length > 0) parts.push(`Nuevas: ${created.map((e) => e.key).join(", ")}`)
370
+ if (updated.length > 0) parts.push(`Actualizadas: ${updated.map((e) => e.key).join(", ")}`)
371
+ if (parts.length > 0) sections.push(`## Memoria (${recentEntries.length} cambios)\n${parts.join("\n")}`)
372
+ }
373
+
374
+ // 4. Active sessions
375
+ const sessions = listSessions().filter((s) => s.active)
376
+ if (sessions.length > 0) {
377
+ const lines = sessions.slice(0, 5).map((s) => `- ${s.agent}@${s.branch} (${Object.keys(s.files).length} archivos)`)
378
+ sections.push(`## Sesiones activas (${sessions.length})\n${lines.join("\n")}`)
379
+ }
380
+
381
+ if (sections.length === 0) return "Sin cambios recientes."
382
+ return sections.filter(Boolean).join("\n\n")
383
+ }
384
+
385
+ // ── context_focus ────────────────────────────────────────────────────
386
+
387
+ export interface ContextFocusOpts {
388
+ /** Max entries to include. Default 6. */
389
+ limit?: number
390
+ }
391
+
392
+ /**
393
+ * Hyper-focused context for a specific task: memory entries + related files + code references.
394
+ * ~300-500 tokens. Zero LLM.
395
+ */
396
+ export function generateContextFocus(data: string, root: string, task: string, opts: ContextFocusOpts = {}): string {
397
+ const sections: string[] = []
398
+ const limit = opts.limit ?? 6
399
+
400
+ // 1. Relevant memory entries
401
+ const relevant = formatRelevantEntries(data, task, limit)
402
+ if (relevant) sections.push(relevant)
403
+
404
+ // 2. Extract keywords from task for file/code search
405
+ const keywords = task.toLowerCase().split(/\s+/).filter((w) => w.length > 2)
406
+
407
+ // 3. Related files
408
+ const allFiles: string[] = []
409
+ for (const kw of keywords) {
410
+ allFiles.push(...findFilesByPattern(root, kw))
411
+ }
412
+ const uniqueFiles = [...new Set(allFiles)].slice(0, 10)
413
+ if (uniqueFiles.length > 0) {
414
+ sections.push(`## Archivos relacionados\n${uniqueFiles.join("\n")}`)
415
+ }
416
+
417
+ // 4. Code references (callers and matches)
418
+ for (const kw of keywords.slice(0, 3)) {
419
+ const callers = findCallers(root, kw)
420
+ if (callers.length > 0) {
421
+ const lines = callers.slice(0, 5).map((c) => `${c.file}:${c.line} — ${c.content.slice(0, 80)}`)
422
+ sections.push(`## Referencias: ${kw}\n${lines.join("\n")}`)
423
+ }
424
+ }
425
+
426
+ // 5. Related tests
427
+ const testFiles: string[] = []
428
+ for (const kw of keywords.slice(0, 2)) {
429
+ const tests = findFilesByPattern(root, ".test.")
430
+ .filter((f) => f.toLowerCase().includes(kw))
431
+ testFiles.push(...tests)
432
+ }
433
+ const uniqueTests = [...new Set(testFiles)].slice(0, 5)
434
+ if (uniqueTests.length > 0) {
435
+ sections.push(`## Tests existentes\n${uniqueTests.join("\n")}`)
436
+ }
437
+
438
+ if (sections.length === 0) return `Sin contexto encontrado para "${task}".`
439
+ return sections.filter(Boolean).join("\n\n")
440
+ }
441
+
442
+ // ── context_health ───────────────────────────────────────────────────
443
+
444
+ export interface HealthReport {
445
+ score: number
446
+ warnings: string[]
447
+ info: string[]
448
+ critical: string[]
449
+ }
450
+
451
+ /**
452
+ * Full health audit: orphan links, duplicates, missing quality, expired TTL, broken file refs.
453
+ * Returns structured report + markdown string. Zero LLM.
454
+ */
455
+ export function generateContextHealth(data: string, root: string): { report: HealthReport; markdown: string } {
456
+ const entries = parseEntries(data)
457
+ const critical: string[] = []
458
+ const warnings: string[] = []
459
+ const info: string[] = []
460
+ let score = 100
461
+
462
+ // 1. Orphan links
463
+ const keys = new Set(entries.map((e) => e.key))
464
+ const orphanLinks: string[] = []
465
+ for (const e of entries) {
466
+ for (const link of e.links) {
467
+ if (!keys.has(link)) orphanLinks.push(`${e.key}->${link}`)
468
+ }
469
+ }
470
+ if (orphanLinks.length > 0) {
471
+ warnings.push(`${orphanLinks.length} links huérfanos: ${orphanLinks.slice(0, 5).join(", ")}`)
472
+ score -= 5
473
+ }
474
+
475
+ // 2. Duplicate content
476
+ const contentMap = new Map<string, string[]>()
477
+ for (const e of entries) {
478
+ const existing = contentMap.get(e.content) || []
479
+ existing.push(e.key)
480
+ contentMap.set(e.content, existing)
481
+ }
482
+ const duplicates: string[] = []
483
+ for (const [_, keys] of contentMap) {
484
+ if (keys.length > 1) duplicates.push(keys.join(" = "))
485
+ }
486
+ if (duplicates.length > 0) {
487
+ warnings.push(`${duplicates.length} entradas duplicadas: ${duplicates.slice(0, 3).join("; ")}`)
488
+ score -= 5
489
+ }
490
+
491
+ // 3. Never-accessed old entries (created >7d ago but never recalled = possibly stale)
492
+ const weekAgo = new Date(Date.now() - 7 * 86400000).toISOString().split("T")[0]
493
+ const staleNeverAccessed = entries.filter((e) => e.accessed === 0 && e.date < weekAgo)
494
+ if (staleNeverAccessed.length > 0) {
495
+ info.push(`${staleNeverAccessed.length} entradas antiguas nunca recuperadas (posiblemente obsoletas)`)
496
+ score -= 2
497
+ }
498
+
499
+ // 4. Expired TTL
500
+ const expired = entries.filter((e) => e.ttl && isExpiredLocal(e.ttl))
501
+ if (expired.length > 0) {
502
+ info.push(`${expired.length} entradas con TTL expirado (auto-prune en próximo inicio)`)
503
+ score -= 3
504
+ }
505
+
506
+ // 5. Broken file refs
507
+ const brokenFiles: string[] = []
508
+ for (const e of entries) {
509
+ if (e.file) {
510
+ const filePath = e.file.split(":")[0]
511
+ if (filePath && !existsSync(join(root, filePath))) {
512
+ brokenFiles.push(`${e.key}: ${e.file}`)
513
+ }
514
+ }
515
+ }
516
+ if (brokenFiles.length > 0) {
517
+ warnings.push(`${brokenFiles.length} refs a archivos inexistentes: ${brokenFiles.slice(0, 3).join("; ")}`)
518
+ score -= 5
519
+ }
520
+
521
+ // 6. Stale sessions
522
+ const sessions = listSessions()
523
+ const stale = sessions.filter((s) => !s.active && !s.ended)
524
+ if (stale.length > 0) {
525
+ info.push(`${stale.length} sesiones stale (serán pruned automáticamente)`)
526
+ }
527
+
528
+ // 7. Entry count
529
+ if (entries.length > 80) {
530
+ warnings.push(`${entries.length} entradas (cerca del límite de 100)`)
531
+ score -= 3
532
+ } else if (entries.length === 0) {
533
+ info.push("Memoria vacía")
534
+ }
535
+
536
+ score = Math.max(0, score)
537
+
538
+ const report: HealthReport = { score, warnings, info, critical }
539
+
540
+ // Build markdown
541
+ const parts: string[] = [`## Memory Health: ${score >= 90 ? "✅" : score >= 70 ? "⚠️" : "❌"} ${score}/100`]
542
+
543
+ if (critical.length > 0) {
544
+ parts.push("", "### Crítico", ...critical.map((w) => `- ${w}`))
545
+ }
546
+ if (warnings.length > 0) {
547
+ parts.push("", "### Warnings", ...warnings.map((w) => `- ${w}`))
548
+ }
549
+ if (info.length > 0) {
550
+ parts.push("", "### Info", ...info.map((i) => `- ${i}`))
551
+ }
552
+
553
+ return { report, markdown: parts.join("\n") }
554
+ }
555
+
556
+ // ── context_export ───────────────────────────────────────────────────
557
+
558
+ export type ExportFormat = "full" | "compact"
559
+
560
+ /**
561
+ * Export memory as injectable markdown for other agents or sessions.
562
+ * Zero LLM. Output is complete memory dump in readable format.
563
+ */
564
+ export function generateContextExport(data: string, format: ExportFormat = "full"): string {
565
+ const entries = parseEntries(data)
566
+ const sections: string[] = []
567
+
568
+ // Header
569
+ const today = new Date().toISOString().split("T")[0]
570
+ sections.push(`# toon-memory export\nFecha: ${today} | Entradas: ${entries.length}\n`)
571
+
572
+ if (entries.length === 0) {
573
+ sections.push("Memoria vacía.")
574
+ return sections.join("\n")
575
+ }
576
+
577
+ // Group by category
578
+ const byCategory: Record<string, GraphEntry[]> = {}
579
+ for (const e of entries) {
580
+ if (!byCategory[e.category]) byCategory[e.category] = []
581
+ byCategory[e.category].push(e)
582
+ }
583
+
584
+ const categoryLabels: Record<string, string> = {
585
+ decision: "Decisiones",
586
+ pattern: "Patrones",
587
+ bug: "Bugs",
588
+ knowledge: "Conocimiento",
589
+ }
590
+
591
+ for (const [cat, items] of Object.entries(byCategory)) {
592
+ const label = categoryLabels[cat] || cat
593
+ sections.push(`## ${label} (${items.length})`)
594
+
595
+ for (const e of items) {
596
+ if (format === "compact") {
597
+ sections.push(`- **${e.key}**: ${e.content.slice(0, 120)}`)
598
+ } else {
599
+ const tags = e.tags.length > 0 ? ` · tags: ${e.tags.join(";")}` : ""
600
+ const links = e.links.length > 0 ? ` · links: ${e.links.join(", ")}` : ""
601
+ const file = e.file ? ` · file: ${e.file}` : ""
602
+ sections.push(`### ${e.key}\n${e.content}\n_${e.date}${tags}${file}${links}_`)
603
+ }
604
+ }
605
+ sections.push("")
606
+ }
607
+
608
+ // Graph summary (full format only)
609
+ if (format === "full") {
610
+ const { adjacency } = buildGraph(entries)
611
+ if (adjacency.size > 0) {
612
+ const edges: string[] = []
613
+ for (const [key, neighbors] of adjacency) {
614
+ for (const n of neighbors) {
615
+ if (key < n) edges.push(`${key} -> ${n}`)
616
+ }
617
+ }
618
+ if (edges.length > 0) {
619
+ sections.push(`## Grafo (${edges.length} edges)`)
620
+ sections.push(edges.slice(0, 20).join("\n"))
621
+ }
622
+ }
623
+ }
624
+
625
+ // Sessions snapshot
626
+ const sessions = listSessions()
627
+ if (sessions.length > 0) {
628
+ const active = sessions.filter((s) => s.active)
629
+ sections.push(`## Sesiones (${active.length} activas / ${sessions.length} total)`)
630
+ for (const s of sessions.slice(0, 5)) {
631
+ const status = s.active ? "🟢" : "⚪"
632
+ sections.push(`- ${status} ${s.agent}@${s.branch} (${s.id})`)
633
+ }
634
+ }
635
+
636
+ return sections.filter(Boolean).join("\n")
637
+ }