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