toon-memory 2.0.0 → 2.1.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/server.ts CHANGED
@@ -5,6 +5,8 @@ import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs"
5
5
  import { dirname, join } from "path"
6
6
  import { fileURLToPath } from "url"
7
7
  import { randomBytes, createCipheriv, createDecipheriv } from "crypto"
8
+ import { withLockSync, atomicWrite, readUnderLock } from "../lib/lock"
9
+ import { coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS } from "../lib/sessions"
8
10
 
9
11
  const __dirname = dirname(fileURLToPath(import.meta.url))
10
12
 
@@ -17,6 +19,9 @@ const MEMORY_FILE = join(MEMORY_DIR, "data.toon")
17
19
  /** Archive file for old entries */
18
20
  const ARCHIVE_FILE = join(MEMORY_DIR, "archive.toon")
19
21
 
22
+ /** Observations log written by capture hooks (opt-in, separate from memory) */
23
+ const OBSERVATIONS_FILE = join(MEMORY_DIR, "observations.toon")
24
+
20
25
  /** Configuration file for encryption settings */
21
26
  const CONFIG_FILE = join(MEMORY_DIR, "config.json")
22
27
 
@@ -26,6 +31,15 @@ const MAX_ENTRIES = 100
26
31
  /** Days before entries are archived */
27
32
  const ARCHIVE_DAYS = 30
28
33
 
34
+ /**
35
+ * Write `content` to a memory file atomically and safely across processes.
36
+ * Uses an advisory lock (temp+rename) so parallel sessions can't corrupt
37
+ * the same file. Encryption, if enabled, is applied by the caller.
38
+ */
39
+ function safeWrite(file: string, content: string): void {
40
+ withLockSync(file, () => atomicWrite(file, content))
41
+ }
42
+
29
43
  /** Encryption algorithm for AES-256-GCM */
30
44
  const ALGORITHM = "aes-256-gcm"
31
45
 
@@ -91,7 +105,7 @@ function ensureMemoryDir(): void {
91
105
  function ensureMemoryFile(): void {
92
106
  ensureMemoryDir()
93
107
  if (!existsSync(MEMORY_FILE)) {
94
- writeFileSync(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl}:\n")
108
+ writeFileSync(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed}:\n")
95
109
  }
96
110
  }
97
111
 
@@ -131,7 +145,11 @@ function encrypt(text: string, key: string): string {
131
145
  */
132
146
  function decrypt(encryptedData: string, key: string): string {
133
147
  const keyBuffer = Buffer.from(key, "hex")
134
- const [ivHex, authTagHex, encrypted] = encryptedData.split(":")
148
+ const parts = encryptedData.split(":")
149
+ if (parts.length !== 3) {
150
+ throw new Error("Invalid encrypted data format: expected iv:authTag:ciphertext")
151
+ }
152
+ const [ivHex, authTagHex, encrypted] = parts
135
153
 
136
154
  const iv = Buffer.from(ivHex, "hex")
137
155
  const authTag = Buffer.from(authTagHex, "hex")
@@ -144,15 +162,6 @@ function decrypt(encryptedData: string, key: string): string {
144
162
  return decrypted
145
163
  }
146
164
 
147
- /**
148
- * Generate a random 256-bit encryption key.
149
- *
150
- * @returns Hex-encoded key (64 chars)
151
- */
152
- function generateKey(): string {
153
- return randomBytes(32).toString("hex")
154
- }
155
-
156
165
  /**
157
166
  * Read memory file, decrypting if encryption is enabled.
158
167
  * Key is read from TOON_MEMORY_KEY env var.
@@ -162,7 +171,7 @@ function generateKey(): string {
162
171
  function readMemory(): string {
163
172
  ensureMemoryFile()
164
173
  const config = loadConfig()
165
- const data = readFileSync(MEMORY_FILE, "utf-8")
174
+ const data = readUnderLock(MEMORY_FILE)
166
175
 
167
176
  if (config.encrypted) {
168
177
  const key = getKey()
@@ -191,11 +200,11 @@ function writeMemory(content: string): void {
191
200
  const key = getKey()
192
201
  if (!key) return
193
202
  const encrypted = encrypt(content, key)
194
- writeFileSync(MEMORY_FILE, encrypted)
203
+ safeWrite(MEMORY_FILE, encrypted)
195
204
  return
196
205
  }
197
206
 
198
- writeFileSync(MEMORY_FILE, content)
207
+ safeWrite(MEMORY_FILE, content)
199
208
  }
200
209
 
201
210
  /**
@@ -345,41 +354,109 @@ function findRelatedEntries(text: string, excludeKey: string = "", limit: number
345
354
  * console.log(`Archived: ${result.archived}, Kept: ${result.kept}`)
346
355
  * ```
347
356
  */
348
- function archiveOldEntries(): { archived: number; kept: number } {
357
+ /**
358
+ * Importance score for an entry: blends recency and access frequency.
359
+ * Deterministic — no LLM. Higher = more worth keeping.
360
+ */
361
+ function entryScore(dateStr: string, accessed: number): number {
362
+ const days = (Date.now() - new Date(`${dateStr}T00:00:00`).getTime()) / 86400000
363
+ const recency = Math.max(0, 30 - days) / 30
364
+ const freq = Math.min(1, accessed / 5)
365
+ return recency * 0.6 + freq * 0.4
366
+ }
367
+
368
+ function entryScoreForLine(line: string): number {
369
+ const parts = line.trim().split("|")
370
+ const date = parts[6] || new Date().toISOString().split("T")[0]
371
+ const accessed = parts.length > 8 ? parseInt(parts[8]) || 0 : 0
372
+ return entryScore(date, accessed)
373
+ }
374
+
375
+ /**
376
+ * Increment the `accessed` counter for the given entry ids.
377
+ * Used by recall/suggest so frequently-used memories rank higher.
378
+ */
379
+ function bumpAccessed(ids: string[]): void {
380
+ if (ids.length === 0) return
381
+ const idSet = new Set(ids)
382
+ const data = readMemory()
383
+ const lines = data.split("\n")
384
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
385
+ if (headerIdx === -1) return
386
+
387
+ for (let i = headerIdx + 1; i < lines.length; i++) {
388
+ const line = lines[i]
389
+ if (!line.startsWith(" ") || !line.includes("|")) continue
390
+ if (line.startsWith(" summaries:")) break
391
+ const parts = line.trim().split("|")
392
+ if (idSet.has(parts[0])) {
393
+ const accessed = parts.length > 8 ? (parseInt(parts[8]) || 0) + 1 : 1
394
+ parts[8] = String(accessed)
395
+ lines[i] = ` ${parts.join("|")}`
396
+ }
397
+ }
398
+ writeMemory(lines.join("\n"))
399
+ }
400
+
401
+ /**
402
+ * Read captured activity from observations.toon (written by hooks).
403
+ */
404
+ function readObservations(): Array<{ ts: string; session: string; agent: string; branch: string; tool: string; file: string; summary: string }> {
405
+ if (!existsSync(OBSERVATIONS_FILE)) return []
406
+ return readFileSync(OBSERVATIONS_FILE, "utf-8")
407
+ .split("\n")
408
+ .filter((l) => l.startsWith(" ") && l.includes("|"))
409
+ .map((l) => {
410
+ const p = l.trim().split("|")
411
+ return { ts: p[0] || "", session: p[1] || "", agent: p[2] || "", branch: p[3] || "", tool: p[4] || "", file: p[6] || "", summary: p[7] || "" }
412
+ })
413
+ }
414
+
415
+ /**
416
+ * Archive entries older than ARCHIVE_DAYS or with expired TTL.
417
+ * When `trimToMax` is set, also archive the lowest-importance entries
418
+ * until the active count is at or below MAX_ENTRIES.
419
+ */
420
+ function archiveOldEntries(opts: { trimToMax?: boolean } = {}): { archived: number; kept: number } {
349
421
  const data = readMemory()
350
422
  const lines = data.split("\n")
351
423
  const headerIdx = lines.findIndex((l) => l.startsWith("entries["))
352
-
424
+
353
425
  if (headerIdx === -1) return { archived: 0, kept: 0 }
354
-
426
+
355
427
  const today = new Date()
356
428
  const cutoff = new Date(today)
357
429
  cutoff.setDate(cutoff.getDate() - ARCHIVE_DAYS)
358
430
  const cutoffStr = cutoff.toISOString().split("T")[0]
359
-
431
+
360
432
  const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0)
361
- const toArchive: string[] = []
362
- const toKeep: string[] = []
363
-
364
- for (const line of entryLines) {
433
+ const toArchive = new Set<number>()
434
+
435
+ entryLines.forEach((line, idx) => {
365
436
  const parts = line.trim().split("|")
366
- if (parts.length >= 7) {
367
- const date = parts[6]
368
- const ttl = parts[7] || ""
369
- const isOld = date < cutoffStr
370
- const isTtlExpired = ttl && isExpired(ttl)
371
- if (isOld || isTtlExpired) {
372
- toArchive.push(line.trim())
373
- } else {
374
- toKeep.push(line.trim())
375
- }
376
- } else {
377
- toKeep.push(line.trim())
437
+ if (parts.length < 7) return
438
+ const date = parts[6]
439
+ const ttl = parts[7] || ""
440
+ if (date < cutoffStr || (ttl && isExpired(ttl))) toArchive.add(idx)
441
+ })
442
+
443
+ if (opts.trimToMax) {
444
+ const remaining = entryLines.length - toArchive.size
445
+ if (remaining > MAX_ENTRIES) {
446
+ const need = remaining - MAX_ENTRIES
447
+ const candidates = entryLines
448
+ .map((line, idx) => ({ idx, score: entryScoreForLine(line) }))
449
+ .filter((c) => !toArchive.has(c.idx))
450
+ .sort((a, b) => a.score - b.score)
451
+ for (let i = 0; i < need && i < candidates.length; i++) toArchive.add(candidates[i].idx)
378
452
  }
379
453
  }
380
-
381
- if (toArchive.length === 0) return { archived: 0, kept: toKeep.length }
382
-
454
+
455
+ if (toArchive.size === 0) return { archived: 0, kept: entryLines.length }
456
+
457
+ const toArchiveLines = entryLines.filter((_, idx) => toArchive.has(idx)).map((l) => l.trim())
458
+ const toKeepLines = entryLines.filter((_, idx) => !toArchive.has(idx)).map((l) => l.trim())
459
+
383
460
  // Write archived entries
384
461
  let archiveContent = ""
385
462
  if (existsSync(ARCHIVE_FILE)) {
@@ -387,34 +464,121 @@ function archiveOldEntries(): { archived: number; kept: number } {
387
464
  } else {
388
465
  archiveContent = `version: 1\narchived:\n`
389
466
  }
390
-
467
+
391
468
  const archiveLines = archiveContent.split("\n")
392
469
  let archiveHeaderIdx = archiveLines.findIndex((l) => l.startsWith("archived["))
393
470
  if (archiveHeaderIdx === -1) {
394
471
  archiveLines.push(`archived[0|]{id|category|key|content|file|tags|date}:`)
395
472
  archiveHeaderIdx = archiveLines.length - 1
396
473
  }
397
-
474
+
398
475
  const archiveMatch = archiveLines[archiveHeaderIdx].match(/archived\[(\d+)\|/)
399
476
  const archiveCount = archiveMatch ? parseInt(archiveMatch[1]) : 0
400
-
401
- for (const entry of toArchive) {
477
+
478
+ for (const entry of toArchiveLines) {
402
479
  archiveLines.splice(archiveHeaderIdx + 1, 0, ` ${entry}`)
403
480
  }
404
- archiveLines[archiveHeaderIdx] = archiveLines[archiveHeaderIdx].replace(/archived\[\d+\|/, `[${archiveCount + toArchive.length}|`)
405
-
406
- writeFileSync(ARCHIVE_FILE, archiveLines.join("\n"))
407
-
481
+ archiveLines[archiveHeaderIdx] = archiveLines[archiveHeaderIdx].replace(/archived\[\d+\|/, `[${archiveCount + toArchiveLines.length}|`)
482
+
483
+ safeWrite(ARCHIVE_FILE, archiveLines.join("\n"))
484
+
408
485
  // Update main file
409
- lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${toKeep.length}|`)
410
- lines.splice(headerIdx + 1, entryLines.length, ...toKeep.map((l) => ` ${l}`))
486
+ lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${toKeepLines.length}|`)
487
+ const keepSet = new Set(toKeepLines)
488
+ const allEntryLines = lines.slice(headerIdx + 1)
489
+ const newEntryLines = allEntryLines.filter((l) => {
490
+ if (l.trim().length === 0) return false
491
+ return keepSet.has(l.trim())
492
+ })
493
+ lines.splice(headerIdx + 1, allEntryLines.length, ...newEntryLines.map((l) => ` ${l.trim()}`))
411
494
  writeMemory(lines.join("\n"))
412
-
413
- return { archived: toArchive.length, kept: toKeep.length }
495
+
496
+ return { archived: toArchiveLines.length, kept: toKeepLines.length }
497
+ }
498
+
499
+ /**
500
+ * Remove entries whose TTL has expired, run at server startup.
501
+ * Distinct from archiveOldEntries: pruning == hard delete of entries that
502
+ * have outlived their TTL (they've passed their useful window), rather than
503
+ * archiving by age. Runs entirely under the memory-file lock so parallel
504
+ * sessions can't corrupt the file mid-prune.
505
+ *
506
+ * @returns Number of entries pruned
507
+ */
508
+ function pruneExpiredEntries(): number {
509
+ ensureMemoryFile()
510
+ if (!existsSync(MEMORY_FILE)) return 0
511
+ let pruned = 0
512
+ withLockSync(MEMORY_FILE, () => {
513
+ const data = readMemory()
514
+ const lines = data.split("\n")
515
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries["))
516
+ if (headerIdx === -1) return
517
+
518
+ const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
519
+ const kept = entryLines.filter((l) => {
520
+ const parts = l.trim().split("|")
521
+ if (parts.length < 8) return true
522
+ const ttl = parts[7] || ""
523
+ if (ttl && isExpired(ttl)) {
524
+ pruned++
525
+ return false
526
+ }
527
+ return true
528
+ })
529
+ if (pruned === 0) return
530
+
531
+ lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${kept.length}|`)
532
+ const keepSet = new Set(kept.map((l) => l.trim()))
533
+ const allEntryLines = lines.slice(headerIdx + 1)
534
+ const newLines = allEntryLines.filter((l) => l.trim().length === 0 || keepSet.has(l.trim()))
535
+ lines.splice(headerIdx + 1, allEntryLines.length, ...newLines.map((l) => (l.trim().length ? ` ${l.trim()}` : l)))
536
+ writeMemory(lines.join("\n"))
537
+ })
538
+ return pruned
539
+ }
540
+
541
+ /**
542
+ * Deterministic consolidation: remove entries with identical (normalized)
543
+ * content, keeping the first. No LLM involved.
544
+ */
545
+ function consolidateEntries(): { removed: number; kept: number; duplicates: string[] } {
546
+ const data = readMemory()
547
+ const lines = data.split("\n")
548
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
549
+ if (headerIdx === -1) return { removed: 0, kept: 0, duplicates: [] }
550
+
551
+ const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
552
+ const seen = new Map<string, string>()
553
+ const order: string[] = []
554
+ const duplicates: string[] = []
555
+
556
+ for (const line of entryLines) {
557
+ const parts = line.trim().split("|")
558
+ if (parts.length < 3) {
559
+ order.push(line.trim())
560
+ continue
561
+ }
562
+ const content = (parts[3] || "").toLowerCase().replace(/\s+/g, " ").trim()
563
+ if (seen.has(content)) {
564
+ duplicates.push(parts[2])
565
+ continue
566
+ }
567
+ seen.set(content, line.trim())
568
+ order.push(line.trim())
569
+ }
570
+
571
+ if (duplicates.length === 0) return { removed: 0, kept: order.length, duplicates: [] }
572
+
573
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${order.length}|`)
574
+ lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...order.map((l) => ` ${l}`))
575
+ writeMemory(lines.join("\n"))
576
+
577
+ return { removed: duplicates.length, kept: order.length, duplicates }
414
578
  }
415
579
 
416
580
  const server = new McpServer(
417
- { name: "toon-memory", version: "2.0.0" },
581
+ { name: "toon-memory", version: "2.1.0" },
418
582
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
419
583
  )
420
584
 
@@ -539,7 +703,7 @@ server.registerTool(
539
703
  const entryId = existingIdx !== -1 ? existingId : newId
540
704
  const resolvedTtl = parseTTL(ttl)
541
705
  const resolvedTags = tags ? tags : inferTags(content, key)
542
- const newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}`
706
+ const newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|0`
543
707
  let action = "Guardado"
544
708
  const tagsInferred = !tags && resolvedTags ? true : false
545
709
 
@@ -557,14 +721,14 @@ server.registerTool(
557
721
 
558
722
  writeMemory(lines.join("\n"))
559
723
 
560
- // Auto-archive if we exceed MAX_ENTRIES
724
+ // Auto-archive if we exceed MAX_ENTRIES (old entries, then lowest-importance)
561
725
  const headerMatch = lines[headerIdx].match(/\[(\d+)\|/)
562
726
  const entryCount = headerMatch ? parseInt(headerMatch[1]) : 0
563
727
  let archiveMsg = ""
564
728
  if (entryCount > MAX_ENTRIES) {
565
- const result = archiveOldEntries()
729
+ const result = archiveOldEntries({ trimToMax: true })
566
730
  if (result.archived > 0) {
567
- archiveMsg = `\n📦 Auto-archived ${result.archived} old entries (${result.kept} kept)`
731
+ archiveMsg = `\n📦 Auto-archived ${result.archived} low-importance entries (${result.kept} kept)`
568
732
  }
569
733
  }
570
734
 
@@ -609,7 +773,7 @@ server.registerTool(
609
773
  },
610
774
  async ({ query, category, from_date, to_date }) => {
611
775
  const data = readMemory()
612
- const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith("summaries:"))
776
+ const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
613
777
 
614
778
  // Normalize for fuzzy matching: hyphens/underscores → spaces, collapse whitespace
615
779
  const normalize = (s: string) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
@@ -620,7 +784,7 @@ server.registerTool(
620
784
  const trimmed = line.trim()
621
785
  const parts = trimmed.split("|")
622
786
  if (parts.length < 7) return null
623
- const [id, cat, key, content, file, tags, date, ttl] = parts
787
+ const [id, cat, key, content, file, tags, date, ttl, accessedRaw] = parts
624
788
  if (category && cat !== category) return null
625
789
  if (from_date && date < from_date) return null
626
790
  if (to_date && date > to_date) return null
@@ -628,16 +792,24 @@ server.registerTool(
628
792
  const searchStr = normalize(`${id} ${cat} ${key} ${content} ${file} ${tags}`)
629
793
  // All query tokens must match (AND logic)
630
794
  if (!queryTokens.every((token) => searchStr.includes(token))) return null
631
- return { id, cat, key, content, file, tags, date }
795
+ const accessed = accessedRaw ? parseInt(accessedRaw) || 0 : 0
796
+ return { id, cat, key, content, file, tags, date, accessed }
632
797
  })
633
- .filter(Boolean)
798
+ .filter(Boolean) as Array<{ id: string; cat: string; key: string; content: string; file: string; tags: string; date: string; accessed: number }>
634
799
 
635
800
  if (results.length === 0) {
636
801
  return { content: [{ type: "text" as const, text: `No se encontraron resultados para "${query}"` }] }
637
802
  }
638
803
 
639
- const formatted = results
640
- .map((r) => `[${r!.cat}] ${r!.key} (${r!.id})\n ${r!.content}\n File: ${r!.file} | Tags: ${r!.tags} | Date: ${r!.date}`)
804
+ // Rank by importance (recency + access frequency), then bump access counts.
805
+ const ranked = results
806
+ .map((r) => ({ ...r, score: entryScore(r.date, r.accessed) }))
807
+ .sort((a, b) => b.score - a.score)
808
+
809
+ bumpAccessed(ranked.map((r) => r.id))
810
+
811
+ const formatted = ranked
812
+ .map((r) => `[${r.cat}] ${r.key} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`)
641
813
  .join("\n\n")
642
814
 
643
815
  return { content: [{ type: "text" as const, text: formatted }] }
@@ -671,7 +843,7 @@ server.registerTool(
671
843
  return { content: [{ type: "text" as const, text: "No hay entradas en memoria" }] }
672
844
  }
673
845
 
674
- const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith("summaries:"))
846
+ const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
675
847
  const filtered = entryLines.filter((l) => {
676
848
  const parts = l.trim().split("|")
677
849
  return parts[0] !== key && parts[2] !== key
@@ -1036,5 +1208,155 @@ server.registerTool(
1036
1208
  }
1037
1209
  )
1038
1210
 
1211
+ /**
1212
+ * Register the memory_captured tool.
1213
+ * Show activity captured automatically by hooks (opt-in, off by default).
1214
+ */
1215
+ server.registerTool(
1216
+ "memory_captured",
1217
+ {
1218
+ title: "List Captured Activity",
1219
+ 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.",
1220
+ inputSchema: {
1221
+ limit: z.number().optional().default(20).describe("Máximo de observaciones a mostrar"),
1222
+ tool: z.string().optional().default("").describe("Filtrar por nombre de herramienta"),
1223
+ file: z.string().optional().default("").describe("Filtrar por archivo"),
1224
+ clear: z.boolean().optional().default(false).describe("Si true, limpia el log de captura"),
1225
+ },
1226
+ },
1227
+ async ({ limit, tool, file, clear }) => {
1228
+ if (clear) {
1229
+ if (existsSync(OBSERVATIONS_FILE)) {
1230
+ writeFileSync(OBSERVATIONS_FILE, "version: 1\nobservations[0|]{ts|session|agent|branch|tool|hash|file|summary}:\n")
1231
+ }
1232
+ return { content: [{ type: "text" as const, text: "🧹 Log de captura limpiado" }] }
1233
+ }
1234
+
1235
+ let obs = readObservations()
1236
+ if (tool) obs = obs.filter((o) => o.tool.toLowerCase().includes(tool.toLowerCase()))
1237
+ if (file) obs = obs.filter((o) => o.file.toLowerCase().includes(file.toLowerCase()))
1238
+ obs = obs.slice(-limit).reverse()
1239
+
1240
+ if (obs.length === 0) {
1241
+ return {
1242
+ content: [{
1243
+ type: "text" as const,
1244
+ text: "No hay actividad capturada. La captura está desactivada por defecto; actívala con `toon-memory capture on`.",
1245
+ }],
1246
+ }
1247
+ }
1248
+
1249
+ const formatted = obs
1250
+ .map((o) => `[${o.ts}] ${o.agent}@${o.branch}/${o.tool}${o.file ? ` (${o.file})` : ""}\n ${o.summary}`)
1251
+ .join("\n\n")
1252
+
1253
+ return { content: [{ type: "text" as const, text: `🔍 Actividad capturada (${obs.length}):\n\n${formatted}` }] }
1254
+ }
1255
+ )
1256
+
1257
+ /**
1258
+ * Register the memory_consolidate tool.
1259
+ * Deterministic de-duplication of memory entries (no LLM).
1260
+ */
1261
+ server.registerTool(
1262
+ "memory_consolidate",
1263
+ {
1264
+ title: "Consolidate Memory",
1265
+ description: "Consolida la memoria eliminando entradas con contenido idéntico (mantiene la primera). Determinista, sin LLM.",
1266
+ inputSchema: {},
1267
+ },
1268
+ async () => {
1269
+ const result = consolidateEntries()
1270
+ if (result.removed === 0) {
1271
+ return { content: [{ type: "text" as const, text: `✅ Memoria ya consolidada (${result.kept} entradas, 0 duplicados)` }] }
1272
+ }
1273
+ return {
1274
+ content: [{
1275
+ type: "text" as const,
1276
+ text: `🧹 Consolidadas ${result.removed} entradas duplicadas.\nQuedan ${result.kept} activas.\nDuplicados: ${result.duplicates.join(", ")}`,
1277
+ }],
1278
+ }
1279
+ }
1280
+ )
1281
+
1282
+ /**
1283
+ * Register the memory_sessions tool.
1284
+ * File-based multi-session coordination — shows other active agent sessions
1285
+ * (branch, files, last-seen) and soft conflicts, so parallel sessions don't
1286
+ * step on each other. No server, no network, no LLM.
1287
+ */
1288
+ server.registerTool(
1289
+ "memory_sessions",
1290
+ {
1291
+ title: "Active Sessions & Conflicts",
1292
+ 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.",
1293
+ inputSchema: {
1294
+ conflictsOnly: z.boolean().optional().default(false).describe("Si true, muestra solo conflictos suaves"),
1295
+ },
1296
+ },
1297
+ async ({ conflictsOnly }) => {
1298
+ const selfId = resolveSessionId()
1299
+ const { active, conflicts } = coordinationView(selfId)
1300
+
1301
+ if (conflictsOnly) {
1302
+ if (conflicts.length === 0) {
1303
+ return { content: [{ type: "text" as const, text: "✅ No hay conflictos suaves entre sesiones activas." }] }
1304
+ }
1305
+ const lines = conflicts.map((c) => {
1306
+ const who = c.sessions.map((s) => `${s.agent}@${s.branch} (${s.id})`).join(", ")
1307
+ return `⚠️ ${c.file}\n ↔ ${who}`
1308
+ })
1309
+ return {
1310
+ content: [{ type: "text" as const, text: `🔥 Conflictos suaves (${conflicts.length}):\n\n${lines.join("\n\n")}` }],
1311
+ }
1312
+ }
1313
+
1314
+ if (active.length === 0) {
1315
+ return {
1316
+ content: [{
1317
+ type: "text" as const,
1318
+ text: "🟢 No hay otras sesiones activas en este proyecto.\n(Esta sesión: " + selfId + " @ " + currentBranch() + ")",
1319
+ }],
1320
+ }
1321
+ }
1322
+
1323
+ const ttlMin = Math.round(SESSION_TTL_MS / 60000)
1324
+ const section = (s: ReturnType<typeof coordinationView>["active"][number]) => {
1325
+ const mins = Math.max(0, Math.round(s.ageMs / 60000))
1326
+ const tag = s.id === selfId ? " (tú)" : ""
1327
+ const ended = s.ended ? " 🏁" : ""
1328
+ const files = Object.keys(s.files).slice(0, 8).map((f) => ` • ${f}`).join("\n")
1329
+ const fileBlock = files ? `\n Archivos:\n${files}` : ""
1330
+ return `• ${s.agent} @ ${s.branch}${tag}${ended}\n id: ${s.id}\n hace ${mins} min${fileBlock}`
1331
+ }
1332
+
1333
+ const parts = [
1334
+ `🧭 Sesiones activas (${active.length}) — ventana ${ttlMin} min:`,
1335
+ "",
1336
+ ...active.map(section),
1337
+ ]
1338
+
1339
+ if (conflicts.length > 0) {
1340
+ parts.push("", `🔥 Conflictos suaves (${conflicts.length}):`)
1341
+ for (const c of conflicts) {
1342
+ const who = c.sessions.map((s) => `${s.agent}@${s.branch}`).join(", ")
1343
+ parts.push(` ⚠️ ${c.file} ↔ ${who}`)
1344
+ }
1345
+ } else {
1346
+ parts.push("", "✅ Sin conflictos suaves detectados.")
1347
+ }
1348
+
1349
+ return { content: [{ type: "text" as const, text: parts.join("\n") }] }
1350
+ }
1351
+ )
1352
+
1353
+ // Startup TTL prune: drop entries whose TTL has elapsed. Best-effort — never
1354
+ // block server startup on a prune failure.
1355
+ try {
1356
+ pruneExpiredEntries()
1357
+ } catch {
1358
+ // ignore — pruning is non-critical for serving requests
1359
+ }
1360
+
1039
1361
  const transport = new StdioServerTransport()
1040
1362
  await server.connect(transport)
package/src/memory.ts CHANGED
@@ -11,7 +11,7 @@ const MEMORY_FILE = join(MEMORY_DIR, "data.toon")
11
11
  function ensureMemoryFile() {
12
12
  if (!existsSync(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true })
13
13
  if (!existsSync(MEMORY_FILE)) {
14
- writeFileSync(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date}:\n")
14
+ writeFileSync(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl}:\n")
15
15
  }
16
16
  }
17
17