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.
package/src/mcp/server.ts CHANGED
@@ -1,1493 +1,18 @@
1
1
  import { McpServer } from "@modelcontextprotocol/server"
2
2
  import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"
3
- import { z } from "zod"
4
- import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs"
5
- import { dirname, join } from "path"
6
- import { fileURLToPath } from "url"
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"
10
- import { graphRecallDetailed, renderCompact, parseEntries, buildGraph, bm25Scores, centrality } from "../lib/graph"
11
- import { qualityScore, mergeEntries, generateSmartRecall, generateSystemPrimer } from "../lib/quality"
3
+ import { registerTools } from "./tools"
4
+ import { registerResources } from "./resources"
5
+ import { pruneExpiredEntries } from "./archive"
12
6
 
13
- const __dirname = dirname(fileURLToPath(import.meta.url))
14
-
15
- /** Base directory for memory storage */
16
- const MEMORY_DIR = join(process.cwd(), ".toon-memory", "memory")
17
-
18
- /** Main memory data file */
19
- const MEMORY_FILE = join(MEMORY_DIR, "data.toon")
20
-
21
- /** Archive file for old entries */
22
- const ARCHIVE_FILE = join(MEMORY_DIR, "archive.toon")
23
-
24
- /** Observations log written by capture hooks (opt-in, separate from memory) */
25
- const OBSERVATIONS_FILE = join(MEMORY_DIR, "observations.toon")
26
-
27
- /** Configuration file for encryption settings */
28
- const CONFIG_FILE = join(MEMORY_DIR, "config.json")
29
-
30
- /** Maximum active entries before auto-archive */
31
- const MAX_ENTRIES = 100
32
-
33
- /** Days before entries are archived */
34
- const ARCHIVE_DAYS = 30
35
-
36
- /**
37
- * Write `content` to a memory file atomically and safely across processes.
38
- * Uses an advisory lock (temp+rename) so parallel sessions can't corrupt
39
- * the same file. Encryption, if enabled, is applied by the caller.
40
- */
41
- function safeWrite(file: string, content: string): void {
42
- withLockSync(file, () => atomicWrite(file, content))
43
- }
44
-
45
- /** Encryption algorithm for AES-256-GCM */
46
- const ALGORITHM = "aes-256-gcm"
47
-
48
- /** Memory configuration with encryption settings */
49
- interface MemoryConfig {
50
- /** Whether encryption is enabled */
51
- encrypted: boolean
52
- /** Project-specific tag vocabulary discovered from dependencies (Hito 7). */
53
- vocab?: Record<string, string[]>
54
- }
55
-
56
- /**
57
- * Load memory configuration from config.json.
58
- *
59
- * @returns MemoryConfig object with encryption settings
60
- *
61
- * @example
62
- * ```typescript
63
- * const config = loadConfig()
64
- * if (config.encrypted) {
65
- * console.log("Encryption enabled")
66
- * }
67
- * ```
68
- */
69
- function loadConfig(): MemoryConfig {
70
- if (!existsSync(CONFIG_FILE)) {
71
- return { encrypted: false }
72
- }
73
- try {
74
- return JSON.parse(readFileSync(CONFIG_FILE, "utf-8"))
75
- } catch {
76
- return { encrypted: false }
77
- }
78
- }
79
-
80
- /**
81
- * Save memory configuration to config.json.
82
- *
83
- * @param config - MemoryConfig to save
84
- */
85
- function saveConfig(config: MemoryConfig): void {
86
- ensureMemoryDir()
87
- // Merge so we never clobber a `vocab` written by `toon-memory init`.
88
- let existing: Partial<MemoryConfig> = {}
89
- if (existsSync(CONFIG_FILE)) {
90
- try {
91
- existing = JSON.parse(readFileSync(CONFIG_FILE, "utf-8"))
92
- } catch {
93
- existing = {}
94
- }
95
- }
96
- writeFileSync(CONFIG_FILE, JSON.stringify({ ...existing, ...config }, null, 2))
97
- }
98
-
99
- /**
100
- * Get the encryption key from environment variable.
101
- *
102
- * @returns The key string, or undefined if not set
103
- */
104
- function getKey(): string | undefined {
105
- return process.env.TOON_MEMORY_KEY
106
- }
107
-
108
- /**
109
- * Ensure memory directory exists, creating it if necessary.
110
- */
111
- function ensureMemoryDir(): void {
112
- if (!existsSync(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true })
113
- }
114
-
115
- /**
116
- * Ensure memory file exists with default structure.
117
- */
118
- function ensureMemoryFile(): void {
119
- ensureMemoryDir()
120
- if (!existsSync(MEMORY_FILE)) {
121
- writeFileSync(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence}:\n")
122
- }
123
- }
124
-
125
- /**
126
- * Encrypt text using AES-256-GCM.
127
- *
128
- * @param text - Plain text to encrypt
129
- * @param key - Hex-encoded encryption key (64 chars)
130
- * @returns Encrypted string in format "iv:authTag:ciphertext"
131
- *
132
- * @example
133
- * ```typescript
134
- * const encrypted = encrypt("my secret", key)
135
- * // "a1b2c3d4...:e5f6g7h8...:i9j0k1l2..."
136
- * ```
137
- */
138
- function encrypt(text: string, key: string): string {
139
- const keyBuffer = Buffer.from(key, "hex")
140
- const iv = randomBytes(16)
141
- const cipher = createCipheriv(ALGORITHM, keyBuffer, iv)
142
-
143
- let encrypted = cipher.update(text, "utf8", "hex")
144
- encrypted += cipher.final("hex")
145
-
146
- const authTag = cipher.getAuthTag()
147
-
148
- return `${iv.toString("hex")}:${authTag.toString("hex")}:${encrypted}`
149
- }
150
-
151
- /**
152
- * Decrypt AES-256-GCM encrypted data.
153
- *
154
- * @param encryptedData - Encrypted string in format "iv:authTag:ciphertext"
155
- * @param key - Hex-encoded encryption key (64 chars)
156
- * @returns Decrypted plain text
157
- * @throws If key is invalid or data is corrupted
158
- */
159
- function decrypt(encryptedData: string, key: string): string {
160
- const keyBuffer = Buffer.from(key, "hex")
161
- const parts = encryptedData.split(":")
162
- if (parts.length !== 3) {
163
- throw new Error("Invalid encrypted data format: expected iv:authTag:ciphertext")
164
- }
165
- const [ivHex, authTagHex, encrypted] = parts
166
-
167
- const iv = Buffer.from(ivHex, "hex")
168
- const authTag = Buffer.from(authTagHex, "hex")
169
- const decipher = createDecipheriv(ALGORITHM, keyBuffer, iv)
170
- decipher.setAuthTag(authTag)
171
-
172
- let decrypted = decipher.update(encrypted, "hex", "utf8")
173
- decrypted += decipher.final("utf8")
174
-
175
- return decrypted
176
- }
177
-
178
- /**
179
- * Read memory file, decrypting if encryption is enabled.
180
- * Key is read from TOON_MEMORY_KEY env var.
181
- *
182
- * @returns Memory content as string (TOON format)
183
- */
184
- function readMemory(): string {
185
- ensureMemoryFile()
186
- const config = loadConfig()
187
- const data = readUnderLock(MEMORY_FILE)
188
-
189
- if (config.encrypted) {
190
- const key = getKey()
191
- if (!key) return ""
192
- try {
193
- return decrypt(data, key)
194
- } catch {
195
- return ""
196
- }
197
- }
198
-
199
- return data
200
- }
201
-
202
- /**
203
- * Write content to memory file, encrypting if encryption is enabled.
204
- * Key is read from TOON_MEMORY_KEY env var.
205
- *
206
- * @param content - Memory content to write (TOON format)
207
- */
208
- function writeMemory(content: string): void {
209
- ensureMemoryFile()
210
- const config = loadConfig()
211
-
212
- if (config.encrypted) {
213
- const key = getKey()
214
- if (!key) return
215
- const encrypted = encrypt(content, key)
216
- safeWrite(MEMORY_FILE, encrypted)
217
- return
218
- }
219
-
220
- safeWrite(MEMORY_FILE, content)
221
- }
222
-
223
- /**
224
- * Generate a random 8-character hex ID for memory entries.
225
- *
226
- * @returns Hex string (8 chars)
227
- */
228
- function generateId(): string {
229
- return randomBytes(4).toString("hex")
230
- }
231
-
232
- /**
233
- * Parse a TTL value into an absolute date string (YYYY-MM-DD).
234
- * Supports: exact dates (2026-07-17), relative days (7d, 30d).
235
- * Returns empty string if no TTL.
236
- */
237
- function parseTTL(ttl: string): string {
238
- if (!ttl || !ttl.trim()) return ""
239
- const trimmed = ttl.trim()
240
- const dayMatch = trimmed.match(/^(\d+)d$/)
241
- if (dayMatch) {
242
- const days = parseInt(dayMatch[1])
243
- const d = new Date()
244
- d.setDate(d.getDate() + days)
245
- return d.toISOString().split("T")[0]
246
- }
247
- if (/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) return trimmed
248
- return ""
249
- }
250
-
251
- /**
252
- * Check if a TTL value has expired (date is in the past).
253
- */
254
- function isExpired(ttl: string): boolean {
255
- if (!ttl) return false
256
- const ttlDate = parseTTL(ttl) || ttl
257
- const today = new Date().toISOString().split("T")[0]
258
- return ttlDate <= today
259
- }
260
-
261
- /** Built-in vocabulary for automatic tag inference */
262
- const TAG_VOCABULARY: Record<string, string[]> = {
263
- "redis": ["redis", "cache", "caching", "memcached"],
264
- "auth": ["auth", "authentication", "authorization", "login", "token", "jwt", "session", "oauth"],
265
- "api": ["api", "endpoint", "rest", "graphql", "route", "router", "controller"],
266
- "db": ["database", "db", "sql", "postgres", "mysql", "mongo", "query", "migration", "schema"],
267
- "security": ["security", "encrypt", "decrypt", "vulnerability", "xss", "csrf", "cors", "sanitiz"],
268
- "test": ["test", "testing", "vitest", "jest", "spec", "mock", "assert", "coverage"],
269
- "deploy": ["deploy", "docker", "ci/cd", "github actions", "pipeline", "kubernetes", "k8s"],
270
- "config": ["config", "configuration", "settings", "env", "environment", "dotenv"],
271
- "performance": ["performance", "optimize", "benchmark", "latency", "throughput", "cache"],
272
- "refactor": ["refactor", "cleanup", "restructure", "reorganize", "rework"],
273
- "error": ["error", "exception", "throw", "catch", "handling", "retry", "fallback"],
274
- "logging": ["log", "logging", "logger", "debug", "trace", "monitor", "observability"],
275
- "types": ["typescript", "types", "type", "interface", "generic", "enum", "zod", "schema"],
276
- "async": ["async", "await", "promise", "concurrent", "parallel", "worker", "queue"],
277
- "state": ["state", "store", "redux", "context", "reducer", "action", "observable"],
278
- "ui": ["ui", "component", "render", "dom", "css", "style", "layout", "responsive"],
279
- "storage": ["storage", "file", "filesystem", "s3", "blob", "upload", "download"],
280
- "email": ["email", "mail", "smtp", "sendgrid", "newsletter", "notification"],
281
- "payment": ["payment", "stripe", "billing", "invoice", "checkout", "subscription"],
282
- "webhook": ["webhook", "callback", "event", "listener", "hook"],
283
- }
284
-
285
- /**
286
- * Infer tags from content and key by matching against vocabulary.
287
- * The built-in vocabulary is always used; a project-specific `vocab`
288
- * (discovered from dependencies at `init`) is matched on top of it.
289
- * Returns semicolon-separated tags.
290
- */
291
- function inferTags(content: string, key: string, vocab?: Record<string, string[]>): string {
292
- const text = `${key} ${content}`.toLowerCase()
293
- const matched: string[] = []
294
- for (const [tag, keywords] of Object.entries(TAG_VOCABULARY)) {
295
- if (keywords.some((kw) => text.includes(kw))) {
296
- matched.push(tag)
297
- }
298
- }
299
- if (vocab) {
300
- for (const [tag, keywords] of Object.entries(vocab)) {
301
- if (keywords.some((kw) => text.includes(kw))) {
302
- matched.push(tag)
303
- }
304
- }
305
- }
306
- return matched.join(";")
307
- }
308
-
309
- /**
310
- * Parse a relative date string into an absolute YYYY-MM-DD date.
311
- * Supports: "24h", "7d", "30d", or an exact date "2026-07-10".
312
- */
313
- function parseRelativeDate(since: string): string {
314
- const trimmed = since.trim()
315
- const hourMatch = trimmed.match(/^(\d+)h$/)
316
- if (hourMatch) {
317
- const d = new Date()
318
- d.setHours(d.getHours() - parseInt(hourMatch[1]))
319
- return d.toISOString().split("T")[0]
320
- }
321
- const dayMatch = trimmed.match(/^(\d+)d$/)
322
- if (dayMatch) {
323
- const d = new Date()
324
- d.setDate(d.getDate() - parseInt(dayMatch[1]))
325
- return d.toISOString().split("T")[0]
326
- }
327
- if (/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) return trimmed
328
- const today = new Date().toISOString().split("T")[0]
329
- return today
330
- }
331
-
332
- const normalize = (s: string) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
333
-
334
- /**
335
- * Find entries related to the given text by fuzzy matching.
336
- * Returns top N results ranked by match quality.
337
- */
338
- function findRelatedEntries(text: string, excludeKey: string = "", limit: number = 3): Array<{ id: string; cat: string; key: string; content: string; file: string; tags: string; date: string; score: number }> {
339
- const data = readMemory()
340
- const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
341
- const queryTokens = normalize(text).split(" ").filter(Boolean)
342
-
343
- const scored = lines
344
- .map((line) => {
345
- const trimmed = line.trim()
346
- const parts = trimmed.split("|")
347
- if (parts.length < 7) return null
348
- const [id, cat, key, content, file, tags, date] = parts
349
- if (key === excludeKey) return null
350
- const searchStr = normalize(`${id} ${cat} ${key} ${content} ${file} ${tags}`)
351
- let score = 0
352
- for (const token of queryTokens) {
353
- if (searchStr.includes(token)) score++
354
- }
355
- if (score === 0) return null
356
- return { id, cat, key, content, file, tags, date, score }
357
- })
358
- .filter(Boolean)
359
- .sort((a, b) => b!.score - a!.score)
360
- .slice(0, limit)
361
-
362
- return scored as Array<{ id: string; cat: string; key: string; content: string; file: string; tags: string; date: string; score: number }>
363
- }
364
-
365
- /**
366
- * Archive entries older than ARCHIVE_DAYS to archive.toon.
367
- *
368
- * Moves old entries from data.toon to archive.toon to keep
369
- * the active memory file manageable.
370
- *
371
- * @returns Object with counts of archived and kept entries
372
- *
373
- * @example
374
- * ```typescript
375
- * const result = archiveOldEntries()
376
- * console.log(`Archived: ${result.archived}, Kept: ${result.kept}`)
377
- * ```
378
- */
379
- /**
380
- * Importance score for an entry: blends recency and access frequency.
381
- * Deterministic — no LLM. Higher = more worth keeping.
382
- */
383
- function entryScore(dateStr: string, accessed: number): number {
384
- const days = (Date.now() - new Date(`${dateStr}T00:00:00`).getTime()) / 86400000
385
- const recency = Math.max(0, 30 - days) / 30
386
- const freq = Math.min(1, accessed / 5)
387
- return recency * 0.6 + freq * 0.4
388
- }
389
-
390
- function entryScoreForLine(line: string): number {
391
- const parts = line.trim().split("|")
392
- const date = parts[6] || new Date().toISOString().split("T")[0]
393
- const accessed = parts.length > 8 ? parseInt(parts[8]) || 0 : 0
394
- return entryScore(date, accessed)
395
- }
396
-
397
- /**
398
- * Increment the `accessed` counter for the given entry ids.
399
- * Used by recall/suggest so frequently-used memories rank higher.
400
- */
401
- function bumpAccessed(ids: string[]): void {
402
- if (ids.length === 0) return
403
- const idSet = new Set(ids)
404
- const data = readMemory()
405
- const lines = data.split("\n")
406
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
407
- if (headerIdx === -1) return
408
-
409
- for (let i = headerIdx + 1; i < lines.length; i++) {
410
- const line = lines[i]
411
- if (!line.startsWith(" ") || !line.includes("|")) continue
412
- if (line.startsWith(" summaries:")) break
413
- const parts = line.trim().split("|")
414
- if (idSet.has(parts[0])) {
415
- const accessed = parts.length > 8 ? (parseInt(parts[8]) || 0) + 1 : 1
416
- parts[8] = String(accessed)
417
- lines[i] = ` ${parts.join("|")}`
418
- }
419
- }
420
- writeMemory(lines.join("\n"))
421
- }
422
-
423
- /**
424
- * Read captured activity from observations.toon (written by hooks).
425
- */
426
- function readObservations(): Array<{ ts: string; session: string; agent: string; branch: string; tool: string; file: string; summary: string }> {
427
- if (!existsSync(OBSERVATIONS_FILE)) return []
428
- return readFileSync(OBSERVATIONS_FILE, "utf-8")
429
- .split("\n")
430
- .filter((l) => l.startsWith(" ") && l.includes("|"))
431
- .map((l) => {
432
- const p = l.trim().split("|")
433
- return { ts: p[0] || "", session: p[1] || "", agent: p[2] || "", branch: p[3] || "", tool: p[4] || "", file: p[6] || "", summary: p[7] || "" }
434
- })
435
- }
436
-
437
- /**
438
- * Archive entries older than ARCHIVE_DAYS or with expired TTL.
439
- * When `trimToMax` is set, also archive the lowest-importance entries
440
- * until the active count is at or below MAX_ENTRIES.
441
- */
442
- function archiveOldEntries(opts: { trimToMax?: boolean } = {}): { archived: number; kept: number } {
443
- const data = readMemory()
444
- const lines = data.split("\n")
445
- const headerIdx = lines.findIndex((l) => l.startsWith("entries["))
446
-
447
- if (headerIdx === -1) return { archived: 0, kept: 0 }
448
-
449
- const today = new Date()
450
- const cutoff = new Date(today)
451
- cutoff.setDate(cutoff.getDate() - ARCHIVE_DAYS)
452
- const cutoffStr = cutoff.toISOString().split("T")[0]
453
-
454
- const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0)
455
- const toArchive = new Set<number>()
456
-
457
- entryLines.forEach((line, idx) => {
458
- const parts = line.trim().split("|")
459
- if (parts.length < 7) return
460
- const date = parts[6]
461
- const ttl = parts[7] || ""
462
- if (date < cutoffStr || (ttl && isExpired(ttl))) toArchive.add(idx)
463
- })
464
-
465
- if (opts.trimToMax) {
466
- const remaining = entryLines.length - toArchive.size
467
- if (remaining > MAX_ENTRIES) {
468
- const need = remaining - MAX_ENTRIES
469
- const candidates = entryLines
470
- .map((line, idx) => ({ idx, score: entryScoreForLine(line) }))
471
- .filter((c) => !toArchive.has(c.idx))
472
- .sort((a, b) => a.score - b.score)
473
- for (let i = 0; i < need && i < candidates.length; i++) toArchive.add(candidates[i].idx)
474
- }
475
- }
476
-
477
- if (toArchive.size === 0) return { archived: 0, kept: entryLines.length }
478
-
479
- const toArchiveLines = entryLines.filter((_, idx) => toArchive.has(idx)).map((l) => l.trim())
480
- const toKeepLines = entryLines.filter((_, idx) => !toArchive.has(idx)).map((l) => l.trim())
481
-
482
- // Write archived entries
483
- let archiveContent = ""
484
- if (existsSync(ARCHIVE_FILE)) {
485
- archiveContent = readFileSync(ARCHIVE_FILE, "utf-8")
486
- } else {
487
- archiveContent = `version: 1\narchived:\n`
488
- }
489
-
490
- const archiveLines = archiveContent.split("\n")
491
- let archiveHeaderIdx = archiveLines.findIndex((l) => l.startsWith("archived["))
492
- if (archiveHeaderIdx === -1) {
493
- archiveLines.push(`archived[0|]{id|category|key|content|file|tags|date}:`)
494
- archiveHeaderIdx = archiveLines.length - 1
495
- }
496
-
497
- const archiveMatch = archiveLines[archiveHeaderIdx].match(/archived\[(\d+)\|/)
498
- const archiveCount = archiveMatch ? parseInt(archiveMatch[1]) : 0
499
-
500
- for (const entry of toArchiveLines) {
501
- archiveLines.splice(archiveHeaderIdx + 1, 0, ` ${entry}`)
502
- }
503
- archiveLines[archiveHeaderIdx] = archiveLines[archiveHeaderIdx].replace(/archived\[\d+\|/, `[${archiveCount + toArchiveLines.length}|`)
504
-
505
- safeWrite(ARCHIVE_FILE, archiveLines.join("\n"))
506
-
507
- // Update main file
508
- lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${toKeepLines.length}|`)
509
- const keepSet = new Set(toKeepLines)
510
- const allEntryLines = lines.slice(headerIdx + 1)
511
- const newEntryLines = allEntryLines.filter((l) => {
512
- if (l.trim().length === 0) return false
513
- return keepSet.has(l.trim())
514
- })
515
- lines.splice(headerIdx + 1, allEntryLines.length, ...newEntryLines.map((l) => ` ${l.trim()}`))
516
- writeMemory(lines.join("\n"))
517
-
518
- return { archived: toArchiveLines.length, kept: toKeepLines.length }
519
- }
520
-
521
- /**
522
- * Remove entries whose TTL has expired, run at server startup.
523
- * Distinct from archiveOldEntries: pruning == hard delete of entries that
524
- * have outlived their TTL (they've passed their useful window), rather than
525
- * archiving by age. Runs entirely under the memory-file lock so parallel
526
- * sessions can't corrupt the file mid-prune.
527
- *
528
- * @returns Number of entries pruned
529
- */
530
- function pruneExpiredEntries(): number {
531
- ensureMemoryFile()
532
- if (!existsSync(MEMORY_FILE)) return 0
533
- let pruned = 0
534
- withLockSync(MEMORY_FILE, () => {
535
- const data = readMemory()
536
- const lines = data.split("\n")
537
- const headerIdx = lines.findIndex((l) => l.startsWith("entries["))
538
- if (headerIdx === -1) return
539
-
540
- const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
541
- const kept = entryLines.filter((l) => {
542
- const parts = l.trim().split("|")
543
- if (parts.length < 8) return true
544
- const ttl = parts[7] || ""
545
- if (ttl && isExpired(ttl)) {
546
- pruned++
547
- return false
548
- }
549
- return true
550
- })
551
- if (pruned === 0) return
552
-
553
- lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${kept.length}|`)
554
- const keepSet = new Set(kept.map((l) => l.trim()))
555
- const allEntryLines = lines.slice(headerIdx + 1)
556
- const newLines = allEntryLines.filter((l) => l.trim().length === 0 || keepSet.has(l.trim()))
557
- lines.splice(headerIdx + 1, allEntryLines.length, ...newLines.map((l) => (l.trim().length ? ` ${l.trim()}` : l)))
558
- writeMemory(lines.join("\n"))
559
- })
560
- return pruned
561
- }
562
-
563
- /**
564
- * Deterministic consolidation: merge entries with the same key (combining
565
- * tags, links, max confidence, latest date), then remove exact-content
566
- * duplicates. No LLM involved.
567
- */
568
- function consolidateEntries(): { removed: number; kept: number; duplicates: string[] } {
569
- const data = readMemory()
570
- const lines = data.split("\n")
571
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
572
- if (headerIdx === -1) return { removed: 0, kept: 0, duplicates: [] }
573
-
574
- const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
575
-
576
- // Phase 1: Merge entries with the same key
577
- const byKey = new Map<number, string>() // first occurrence index -> merged line
578
- const keyOrder: number[] = []
579
- const mergedAway: number[] = []
580
-
581
- for (let i = 0; i < entryLines.length; i++) {
582
- const line = entryLines[i].trim()
583
- const parts = line.split("|")
584
- if (parts.length < 3) continue
585
- const key = parts[2]
586
- const existingIdx = keyOrder.findIndex((idx) => {
587
- const ep = entryLines[idx].trim().split("|")
588
- return ep[2] === key
589
- })
590
- if (existingIdx !== -1) {
591
- // Merge into the first occurrence
592
- const mergedLine = mergeEntries(byKey.get(keyOrder[existingIdx])!, line)
593
- byKey.set(keyOrder[existingIdx], mergedLine)
594
- mergedAway.push(i)
595
- } else {
596
- byKey.set(i, line)
597
- keyOrder.push(i)
598
- }
599
- }
600
-
601
- // Phase 2: Remove exact-content duplicates (normalized)
602
- const contentSeen = new Map<string, string>()
603
- const order: string[] = []
604
- const duplicates: string[] = []
605
-
606
- for (const idx of keyOrder) {
607
- const line = byKey.get(idx)!
608
- const parts = line.split("|")
609
- if (parts.length < 3) {
610
- order.push(line)
611
- continue
612
- }
613
- const content = (parts[3] || "").toLowerCase().replace(/\s+/g, " ").trim()
614
- if (contentSeen.has(content)) {
615
- duplicates.push(parts[2])
616
- continue
617
- }
618
- contentSeen.set(content, line)
619
- order.push(line)
620
- }
621
-
622
- const totalRemoved = mergedAway.length + duplicates.length
623
- if (totalRemoved === 0) return { removed: 0, kept: order.length, duplicates: [] }
624
-
625
- lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${order.length}|`)
626
- lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...order.map((l) => ` ${l}`))
627
- writeMemory(lines.join("\n"))
628
-
629
- return { removed: totalRemoved, kept: order.length, duplicates }
630
- }
7
+ declare const TOON_VERSION: string
631
8
 
632
9
  const server = new McpServer(
633
- { name: "toon-memory", version: "2.4.3" },
10
+ { name: "toon-memory", version: TOON_VERSION },
634
11
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
635
12
  )
636
13
 
637
- /**
638
- * Register memory entries as an MCP resource.
639
- * Agents can read this as context in the system prompt.
640
- */
641
- server.registerResource(
642
- "memory-entries",
643
- "toon://memory/entries",
644
- { title: "Memory Entries", mimeType: "text/plain" },
645
- async (uri) => {
646
- const data = readMemory()
647
- return { contents: [{ uri: uri.href, text: data }] }
648
- }
649
- )
650
-
651
- /**
652
- * Register memory stats as an MCP resource.
653
- */
654
- server.registerResource(
655
- "memory-stats",
656
- "toon://memory/stats",
657
- { title: "Memory Stats", mimeType: "text/plain" },
658
- async (uri) => {
659
- const data = readMemory()
660
- const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
661
- const entries = lines.map((l) => {
662
- const parts = l.trim().split("|")
663
- return { category: parts[1] || "unknown", ttl: parts[7] || "" }
664
- })
665
- const byCategory: Record<string, number> = {}
666
- for (const e of entries) {
667
- byCategory[e.category] = (byCategory[e.category] || 0) + 1
668
- }
669
- const withTtl = entries.filter((e) => e.ttl).length
670
- const expired = entries.filter((e) => e.ttl && isExpired(e.ttl)).length
671
- const text = [
672
- `Entradas totales: ${entries.length}`,
673
- `TTL: ${withTtl} con expiración, ${expired} expiradas`,
674
- "Por categoría:",
675
- ...Object.entries(byCategory).map(([k, v]) => ` ${k}: ${v}`),
676
- ].join("\n")
677
- return { contents: [{ uri: uri.href, text }] }
678
- }
679
- )
680
-
681
- /**
682
- * Register memory summaries as an MCP resource.
683
- */
684
- server.registerResource(
685
- "memory-summaries",
686
- "toon://memory/summaries",
687
- { title: "Memory Summaries", mimeType: "text/plain" },
688
- async (uri) => {
689
- const data = readMemory()
690
- const primer = generateSystemPrimer(data)
691
- return { contents: [{ uri: uri.href, text: primer }] }
692
- }
693
- )
694
-
695
- /**
696
- * Register the memory_remember tool.
697
- * Saves a fact to persistent memory (decisions, patterns, bugs, knowledge).
698
- *
699
- * @example
700
- * ```typescript
701
- * // From MCP tool call:
702
- * await callTool("memory_remember", {
703
- * category: "decision",
704
- * key: "use-ts-for-mcp",
705
- * content: "Using TypeScript for MCP server implementation"
706
- * })
707
- * ```
708
- */
709
- server.registerTool(
710
- "memory_remember",
711
- {
712
- title: "Save to Memory",
713
- description: "Guarda un hecho en la memoria persistente del proyecto (decisiones, patrones, bugs, conocimiento). Se recuerda entre sesiones.",
714
- inputSchema: {
715
- category: z.enum(["decision", "pattern", "bug", "knowledge"]).describe("Categoría del hecho"),
716
- key: z.string().describe("Título corto en kebab-case (ej: risk-engine-prioridad)"),
717
- content: z.string().describe("Contenido detallado del hecho"),
718
- file: z.string().optional().default("").describe("Archivo o línea relacionada (ej: spec.md:145)"),
719
- tags: z.string().optional().default("").describe("Tags separados por punto y coma (ej: risk;spec)"),
720
- ttl: z.string().optional().default("").describe("Time to live (ej: 7d, 2026-07-17). Vacío = sin expiración"),
721
- 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."),
722
- },
723
- },
724
- async ({ category, key, content, file, tags, ttl, links }) => {
725
- const data = readMemory()
726
- const newId = generateId()
727
- const date = new Date().toISOString().split("T")[0]
728
- const lines = data.split("\n")
729
-
730
- let headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
731
- if (headerIdx === -1) {
732
- lines.push(`[0|]`)
733
- headerIdx = lines.length - 1
734
- }
735
-
736
- // Find existing entry with same key (upsert)
737
- let existingIdx = -1
738
- let existingId = newId
739
- for (let i = headerIdx + 1; i < lines.length; i++) {
740
- const line = lines[i]
741
- if (!line.startsWith(" ") || !line.includes("|")) continue
742
- if (line.startsWith(" summaries:")) break
743
- const parts = line.trim().split("|")
744
- if (parts[2] === key) {
745
- existingIdx = i
746
- existingId = parts[0] // Preserve original ID
747
- break
748
- }
749
- }
750
-
751
- const entryId = existingIdx !== -1 ? existingId : newId
752
- const resolvedTtl = parseTTL(ttl)
753
- const resolvedTags = tags ? tags : inferTags(content, key, loadConfig().vocab)
754
- // Preserve existing links on upsert unless new ones are provided.
755
- const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : []
756
- const resolvedLinks = links
757
- ? links.split(/[\s;]+/).filter(Boolean).join(" ")
758
- : existingParts[9] || ""
759
- let newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|0|${resolvedLinks}`
760
- let action = "Guardado"
761
- let mergeInfo = ""
762
- const tagsInferred = !tags && resolvedTags ? true : false
763
-
764
- if (existingIdx !== -1) {
765
- // Merge-dedup: combine attributes instead of overwriting
766
- newEntry = mergeEntries(lines[existingIdx].trim(), newEntry)
767
- lines[existingIdx] = ` ${newEntry}`
768
- action = "Actualizado"
769
- mergeInfo = "\n🔗 Merge: tags combinados, fecha y links actualizados"
770
- } else {
771
- // Create new entry with quality score and confidence
772
- const quality = qualityScore(resolvedTags, resolvedLinks, content, date)
773
- const confidence = 1.0 // User-asserted facts get max confidence
774
- newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|0|${resolvedLinks}|${quality.toFixed(2)}|${confidence}`
775
- const match = lines[headerIdx].match(/\[(\d+)\|/)
776
- const count = match ? parseInt(match[1]) : 0
777
- lines.splice(headerIdx + 1, 0, ` ${newEntry}`)
778
- lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`)
779
- }
780
-
781
- writeMemory(lines.join("\n"))
782
-
783
- // Auto-archive if we exceed MAX_ENTRIES (old entries, then lowest-importance)
784
- const headerMatch = lines[headerIdx].match(/\[(\d+)\|/)
785
- const entryCount = headerMatch ? parseInt(headerMatch[1]) : 0
786
- let archiveMsg = ""
787
- if (entryCount > MAX_ENTRIES) {
788
- const result = archiveOldEntries({ trimToMax: true })
789
- if (result.archived > 0) {
790
- archiveMsg = `\n📦 Auto-archived ${result.archived} low-importance entries (${result.kept} kept)`
791
- }
792
- }
793
-
794
- const ttlMsg = resolvedTtl ? `\n⏰ TTL: ${resolvedTtl}` : ""
795
- const inferredMsg = tagsInferred ? `\n🏷️ Tags inferidos: ${resolvedTags}` : ""
796
-
797
- const related = findRelatedEntries(`${key} ${content} ${resolvedTags}`, key, 3)
798
- let relatedMsg = ""
799
- if (related.length > 0) {
800
- const items = related.map((r) => ` [${r.cat}] ${r.key} — ${r.content.slice(0, 80)}`).join("\n")
801
- relatedMsg = `\n\n🔗 Entradas relacionadas:\n${items}`
802
- }
803
-
804
- return {
805
- content: [{ type: "text" as const, text: `🧠 ${action}: ${category}/${key} (${entryId})\n${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }],
806
- }
807
- }
808
- )
809
-
810
- /**
811
- * Register the memory_recall tool.
812
- * Search persistent memory for relevant entries by text, category, or date range.
813
- *
814
- * @example
815
- * ```typescript
816
- * // From MCP tool call:
817
- * await callTool("memory_recall", { query: "risk engine" })
818
- * await callTool("memory_recall", { query: "redis", category: "bug" })
819
- * ```
820
- */
821
- server.registerTool(
822
- "memory_recall",
823
- {
824
- title: "Search Memory",
825
- description: "Busca en la memoria persistente del proyecto. Devuelve entradas relevantes. Usar ANTES de leer archivos.",
826
- inputSchema: {
827
- query: z.string().describe("Texto a buscar"),
828
- category: z.string().optional().default("").describe("Filtrar por categoría (vacío = todos)"),
829
- from_date: z.string().optional().default("").describe("Fecha inicio filtro (YYYY-MM-DD)"),
830
- to_date: z.string().optional().default("").describe("Fecha fin filtro (YYYY-MM-DD)"),
831
- 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)."),
832
- hops: z.number().optional().default(1).describe("Profundidad del grafo en modo 'graph' (1 o 2). Default 1."),
833
- 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."),
834
- },
835
- },
836
- async ({ query, category, from_date, to_date, mode, hops, compact }) => {
837
- const data = readMemory()
838
- const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
839
-
840
- // Normalize for fuzzy matching: hyphens/underscores → spaces, collapse whitespace
841
- const normalize = (s: string) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
842
- const queryTokens = normalize(query).split(" ").filter(Boolean)
843
-
844
- const results = lines
845
- .map((line) => {
846
- const trimmed = line.trim()
847
- const parts = trimmed.split("|")
848
- if (parts.length < 7) return null
849
- const [id, cat, key, content, file, tags, date, ttl, accessedRaw] = parts
850
- const qualityRaw = parts[10] || ""
851
- const confidenceRaw = parts[11] || ""
852
- if (category && cat !== category) return null
853
- if (from_date && date < from_date) return null
854
- if (to_date && date > to_date) return null
855
- if (ttl && isExpired(ttl)) return null
856
- const searchStr = normalize(`${id} ${cat} ${key} ${content} ${file} ${tags} ${qualityRaw} ${confidenceRaw}`)
857
- // All query tokens must match (AND logic)
858
- if (!queryTokens.every((token) => searchStr.includes(token))) return null
859
- const accessed = accessedRaw ? parseInt(accessedRaw) || 0 : 0
860
- return { id, cat, key, content, file, tags, date, accessed, qualityRaw, confidenceRaw }
861
- })
862
- .filter(Boolean) as Array<{ id: string; cat: string; key: string; content: string; file: string; tags: string; date: string; accessed: number; qualityRaw: string; confidenceRaw: string }>
863
-
864
- if (results.length === 0) {
865
- return { content: [{ type: "text" as const, text: `No se encontraron resultados para "${query}"` }] }
866
- }
867
-
868
- // Graph mode: expand the ego-subgraph from keyword matches and return the
869
- // focused, relationship-aware result set (fewer tokens, higher precision).
870
- if (mode === "graph") {
871
- const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops })
872
- if (detail.entries.length === 0) {
873
- return { content: [{ type: "text" as const, text: `No se encontraron resultados para "${query}"` }] }
874
- }
875
- bumpAccessed(detail.entries.map((e) => e.id))
876
- if (compact) {
877
- const formatted = renderCompact(detail.entries, {
878
- adjacency: detail.adjacency,
879
- seeds: detail.seeds,
880
- snippetLen: 90,
881
- })
882
- return { content: [{ type: "text" as const, text: formatted }] }
883
- }
884
- const formatted = detail.entries
885
- .map((r) => {
886
- const links = r.links.length ? `\n links: ${r.links.join(", ")}` : ""
887
- return `[${r.category}] ${r.key} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}`
888
- })
889
- .join("\n\n")
890
- return { content: [{ type: "text" as const, text: formatted }] }
891
- }
892
-
893
- // Rank by importance (recency + access frequency) + quality, then bump access counts.
894
- const ranked = results
895
- .map((r) => {
896
- const quality = r.qualityRaw ? parseFloat(r.qualityRaw) || 0 : 0
897
- const qualityBoost = quality * 0.15
898
- return { ...r, score: entryScore(r.date, r.accessed) + qualityBoost }
899
- })
900
- .sort((a, b) => b.score - a.score)
901
-
902
- bumpAccessed(ranked.map((r) => r.id))
903
-
904
- if (compact) {
905
- const entries = ranked.map((r) => ({
906
- id: r.id,
907
- category: r.cat,
908
- key: r.key,
909
- content: r.content,
910
- file: r.file,
911
- tags: r.tags ? r.tags.split(";").filter(Boolean) : [],
912
- date: r.date,
913
- ttl: "",
914
- accessed: r.accessed,
915
- links: [] as string[],
916
- }))
917
- const formatted = renderCompact(entries)
918
- return { content: [{ type: "text" as const, text: formatted }] }
919
- }
920
-
921
- const formatted = ranked
922
- .map((r) => `[${r.cat}] ${r.key} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`)
923
- .join("\n\n")
924
-
925
- return { content: [{ type: "text" as const, text: formatted }] }
926
- }
927
- )
928
-
929
- /**
930
- * Register the memory_forget tool.
931
- * Delete a memory entry by key or ID.
932
- *
933
- * @example
934
- * ```typescript
935
- * await callTool("memory_forget", { key: "old-decision" })
936
- * ```
937
- */
938
- server.registerTool(
939
- "memory_forget",
940
- {
941
- title: "Delete from Memory",
942
- description: "Elimina una entrada de la memoria por su key o id.",
943
- inputSchema: {
944
- key: z.string().describe("Key o id de la entrada a eliminar"),
945
- },
946
- },
947
- async ({ key }) => {
948
- const data = readMemory()
949
- const lines = data.split("\n")
950
- const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
951
-
952
- if (headerIdx === -1) {
953
- return { content: [{ type: "text" as const, text: "No hay entradas en memoria" }] }
954
- }
955
-
956
- const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
957
- const filtered = entryLines.filter((l) => {
958
- const parts = l.trim().split("|")
959
- return parts[0] !== key && parts[2] !== key
960
- })
961
-
962
- const removed = entryLines.length - filtered.length
963
- const match = lines[headerIdx].match(/\[(\d+)\|/)
964
- const count = match ? parseInt(match[1]) : 0
965
- lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`)
966
- lines.splice(headerIdx + 1, entryLines.length, ...filtered.map((l) => ` ${l.trim()}`))
967
-
968
- writeMemory(lines.join("\n"))
969
- return {
970
- content: [{ type: "text" as const, text: `"${key}" eliminado. Quedan ${count - removed} entradas.` }],
971
- }
972
- }
973
- )
974
-
975
- /**
976
- * Register the memory_stats tool.
977
- * Display memory statistics including entry counts and categories.
978
- *
979
- * @example
980
- * ```typescript
981
- * await callTool("memory_stats", {})
982
- * ```
983
- */
984
- server.registerTool(
985
- "memory_stats",
986
- {
987
- title: "Memory Stats",
988
- description: "Muestra estadísticas de la memoria del proyecto.",
989
- inputSchema: {},
990
- },
991
- async () => {
992
- const data = readMemory()
993
- const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
994
- const entries = lines.map((l) => {
995
- const parts = l.trim().split("|")
996
- return { category: parts[1] || "unknown", ttl: parts[7] || "", quality: parts[10] || "" }
997
- })
998
-
999
- const byCategory: Record<string, number> = {}
1000
- for (const e of entries) {
1001
- byCategory[e.category] = (byCategory[e.category] || 0) + 1
1002
- }
1003
-
1004
- const withTtl = entries.filter((e) => e.ttl).length
1005
- const expired = entries.filter((e) => e.ttl && isExpired(e.ttl)).length
1006
- const withQuality = entries.filter((e) => e.quality).length
1007
- const avgQuality = withQuality > 0
1008
- ? (entries.reduce((sum, e) => sum + (e.quality ? parseFloat(e.quality) : 0), 0) / withQuality).toFixed(2)
1009
- : "N/A"
1010
-
1011
- const summaryLines = data.split("\n").filter((l) => l.includes(":") && !l.startsWith(" ") && !l.startsWith("version") && !l.startsWith("entries") && !/^\[\d+\|]/.test(l))
1012
- const stats = [
1013
- `Entradas totales: ${entries.length}`,
1014
- `Resúmenes de archivos: ${summaryLines.length}`,
1015
- "",
1016
- "Por categoría:",
1017
- ...Object.entries(byCategory).map(([k, v]) => ` ${k}: ${v}`),
1018
- "",
1019
- `TTL: ${withTtl} con expiración, ${expired} expiradas`,
1020
- `Calidad promedio: ${avgQuality} (${withQuality} con score)`,
1021
- "",
1022
- `Últimas 5 entradas:`,
1023
- ...lines.slice(-5).map((l) => {
1024
- const parts = l.trim().split("|")
1025
- const ttlInfo = parts[7] ? ` | TTL: ${parts[7]}` : ""
1026
- const qualityInfo = parts[10] ? ` | Q: ${parts[10]}` : ""
1027
- return ` [${parts[1]}] ${parts[2]} (${parts[0]})${ttlInfo}${qualityInfo}`
1028
- }),
1029
- ]
1030
-
1031
- return { content: [{ type: "text" as const, text: stats.join("\n") }] }
1032
- }
1033
- )
1034
-
1035
- /**
1036
- * Register the memory_diff tool.
1037
- * Show what changed in memory since a given date.
1038
- */
1039
- server.registerTool(
1040
- "memory_diff",
1041
- {
1042
- title: "Memory Diff",
1043
- description: "Muestra qué cambió en la memoria desde una fecha. Útil para saber qué se aprendió desde la última sesión.",
1044
- inputSchema: {
1045
- since: z.string().describe("Desde cuándo mostrar cambios (ej: 24h, 7d, 2026-07-10)"),
1046
- type: z.enum(["all", "created", "updated"]).optional().default("all").describe("Filtrar por tipo de cambio"),
1047
- },
1048
- },
1049
- async ({ since, type }) => {
1050
- const sinceDate = parseRelativeDate(since)
1051
- const today = new Date().toISOString().split("T")[0]
1052
- const data = readMemory()
1053
- const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
1054
-
1055
- const results = lines
1056
- .map((line) => {
1057
- const trimmed = line.trim()
1058
- const parts = trimmed.split("|")
1059
- if (parts.length < 7) return null
1060
- const [id, cat, key, content, file, tags, date] = parts
1061
- if (date < sinceDate) return null
1062
- // For "updated" we check if date is recent but key existed before
1063
- // For simplicity: same date as today = created today, otherwise "updated" if date >= sinceDate
1064
- const changeType = date === today ? "created" : "updated"
1065
- if (type !== "all" && changeType !== type) return null
1066
- return { id, cat, key, content, file, tags, date, changeType }
1067
- })
1068
- .filter(Boolean)
1069
-
1070
- if (results.length === 0) {
1071
- return { content: [{ type: "text" as const, text: `No hay cambios desde ${sinceDate}` }] }
1072
- }
1073
-
1074
- const created = results.filter((r) => r!.changeType === "created")
1075
- const updated = results.filter((r) => r!.changeType === "updated")
1076
-
1077
- const sections: string[] = [`📋 Cambios desde ${sinceDate}:`, ""]
1078
-
1079
- if (created.length > 0 && (type === "all" || type === "created")) {
1080
- sections.push(`➕ Nuevas (${created.length}):`)
1081
- for (const r of created) {
1082
- sections.push(` [${r!.cat}] ${r!.key} (${r!.id})\n ${r!.content}`)
1083
- }
1084
- sections.push("")
1085
- }
1086
-
1087
- if (updated.length > 0 && (type === "all" || type === "updated")) {
1088
- sections.push(`✏️ Actualizadas (${updated.length}):`)
1089
- for (const r of updated) {
1090
- sections.push(` [${r!.cat}] ${r!.key} (${r!.id}) — ${r!.date}`)
1091
- }
1092
- sections.push("")
1093
- }
1094
-
1095
- return { content: [{ type: "text" as const, text: sections.join("\n") }] }
1096
- }
1097
- )
1098
-
1099
- /**
1100
- * Register the memory_suggest tool.
1101
- * Suggest related entries for a given text context.
1102
- */
1103
- server.registerTool(
1104
- "memory_suggest",
1105
- {
1106
- title: "Suggest Related Memories",
1107
- description: "Sugiere entradas de memoria relacionadas con un contexto dado. Útil para obtener contexto antes de una tarea.",
1108
- inputSchema: {
1109
- context: z.string().describe("Texto o contexto para buscar sugerencias"),
1110
- limit: z.number().optional().default(5).describe("Máximo de sugerencias"),
1111
- },
1112
- },
1113
- async ({ context, limit }) => {
1114
- const related = findRelatedEntries(context, "", limit)
1115
-
1116
- if (related.length === 0) {
1117
- return { content: [{ type: "text" as const, text: `No se encontraron entradas relacionadas con "${context}"` }] }
1118
- }
1119
-
1120
- const formatted = related
1121
- .map((r) => `[${r.cat}] ${r.key} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`)
1122
- .join("\n\n")
1123
-
1124
- return { content: [{ type: "text" as const, text: `🔍 Sugerencias para "${context}":\n\n${formatted}` }] }
1125
- }
1126
- )
1127
-
1128
- /**
1129
- * Register the memory_smart_recall tool.
1130
- * Unified recall: BM25 + graph traversal + quality + decay in one call.
1131
- * The LLM calls this at the start of a task to get everything it needs.
1132
- */
1133
- server.registerTool(
1134
- "memory_smart_recall",
1135
- {
1136
- title: "Smart Recall (Unified)",
1137
- 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.",
1138
- inputSchema: {
1139
- intent: z.string().describe("Describe qué necesitas saber (ej: 'diseño de base de datos para backend')"),
1140
- limit: z.number().optional().default(8).describe("Máximo de entradas a devolver"),
1141
- category: z.string().optional().default("").describe("Filtrar por categoría (vacío = todos)"),
1142
- },
1143
- },
1144
- async ({ intent, limit, category }) => {
1145
- const data = readMemory()
1146
- const result = generateSmartRecall(data, intent, { limit, category })
1147
- return { content: [{ type: "text" as const, text: result }] }
1148
- }
1149
- )
1150
-
1151
- /**
1152
- * Register the memory_summary tool.
1153
- * Get or set file summaries to save tokens when reading large files.
1154
- *
1155
- * @example
1156
- * ```typescript
1157
- * // Set a summary
1158
- * await callTool("memory_summary", {
1159
- * action: "set",
1160
- * file: "src/complex.ts",
1161
- * summary: "Complex module handling X, Y, Z"
1162
- * })
1163
- *
1164
- * // Get a summary
1165
- * await callTool("memory_summary", {
1166
- * action: "get",
1167
- * file: "src/complex.ts"
1168
- * })
1169
- * ```
1170
- */
1171
- server.registerTool(
1172
- "memory_summary",
1173
- {
1174
- title: "File Summary",
1175
- description: "Guarda o recupera un resumen de un archivo grande para ahorrar tokens.",
1176
- inputSchema: {
1177
- action: z.enum(["get", "set"]).describe("get para leer, set para guardar"),
1178
- file: z.string().describe("Ruta del archivo"),
1179
- summary: z.string().optional().default("").describe("Resumen del archivo (solo para set)"),
1180
- },
1181
- },
1182
- async ({ action, file, summary }) => {
1183
- const data = readMemory()
1184
-
1185
- if (action === "get") {
1186
- const lines = data.split("\n")
1187
- const summaryIdx = lines.findIndex((l) => l.trim().startsWith("summaries:"))
1188
- if (summaryIdx === -1) {
1189
- return { content: [{ type: "text" as const, text: `No hay resúmenes guardados para "${file}"` }] }
1190
- }
1191
-
1192
- const summaryLines = lines.slice(summaryIdx + 1).filter((l) => l.includes(":"))
1193
- const match = summaryLines.find((l) => l.startsWith(` ${file}:`))
1194
- if (!match) {
1195
- return { content: [{ type: "text" as const, text: `No hay resumen para "${file}"` }] }
1196
- }
1197
-
1198
- const summaryText = match.replace(` ${file}: `, "")
1199
- return { content: [{ type: "text" as const, text: summaryText }] }
1200
- }
1201
-
1202
- const lines = data.split("\n")
1203
- let summaryIdx = lines.findIndex((l) => l.trim().startsWith("summaries:"))
1204
-
1205
- if (summaryIdx === -1) {
1206
- lines.push("", "summaries:")
1207
- summaryIdx = lines.length - 1
1208
- }
1209
-
1210
- const summaryLines = lines.slice(summaryIdx + 1).filter((l) => l.includes(":"))
1211
- const existingIdx = summaryLines.findIndex((l) => l.startsWith(` ${file}:`))
1212
-
1213
- if (existingIdx !== -1) {
1214
- summaryLines[existingIdx] = ` ${file}: ${summary}`
1215
- } else {
1216
- summaryLines.push(` ${file}: ${summary}`)
1217
- }
1218
-
1219
- lines.splice(summaryIdx + 1, lines.length - summaryIdx - 1, ...summaryLines)
1220
- writeMemory(lines.join("\n"))
1221
- return {
1222
- content: [{ type: "text" as const, text: `📝 Resumen guardado para ${file}` }],
1223
- }
1224
- }
1225
- )
1226
-
1227
- /**
1228
- * Register the memory_archive tool.
1229
- * Archive old entries (>30 days) to archive.toon to keep memory clean.
1230
- *
1231
- * @example
1232
- * ```typescript
1233
- * await callTool("memory_archive", {})
1234
- * // "📦 Archivadas 5 entradas antiguas"
1235
- * ```
1236
- */
1237
- server.registerTool(
1238
- "memory_archive",
1239
- {
1240
- title: "Archive Old Entries",
1241
- description: "Mover entradas antiguas (>30 días) a archive.toon para mantener la memoria limpia.",
1242
- inputSchema: {},
1243
- },
1244
- async () => {
1245
- const result = archiveOldEntries()
1246
-
1247
- if (result.archived === 0) {
1248
- return { content: [{ type: "text" as const, text: "No hay entradas antiguas para archivar" }] }
1249
- }
1250
-
1251
- return {
1252
- content: [{
1253
- type: "text" as const,
1254
- text: `📦 Archivadas ${result.archived} entradas antiguas\n📋 Quedan ${result.kept} entradas activas`
1255
- }],
1256
- }
1257
- }
1258
- )
1259
-
1260
- /**
1261
- * Register the memory_encrypt tool.
1262
- * Enable AES-256-GCM encryption for the memory file.
1263
- *
1264
- * ⚠️ Warning: Save the encryption key! It cannot be recovered.
1265
- *
1266
- * @example
1267
- * ```typescript
1268
- * await callTool("memory_encrypt", {})
1269
- * // "🔐 Encriptación habilitada\n⚠️ Guarda esta clave: ..."
1270
- * ```
1271
- */
1272
- server.registerTool(
1273
- "memory_encrypt",
1274
- {
1275
- title: "Enable Encryption",
1276
- description: "Habilita encriptación AES-256-GCM para la memoria. La clave se genera automáticamente.",
1277
- inputSchema: {},
1278
- },
1279
- async () => {
1280
- const config = loadConfig()
1281
-
1282
- if (config.encrypted) {
1283
- return { content: [{ type: "text" as const, text: "La encriptación ya está habilitada" }] }
1284
- }
1285
-
1286
- const key = getKey()
1287
- if (!key) {
1288
- return { content: [{ type: "text" as const, text: "❌ Define TOON_MEMORY_KEY en el entorno antes de encriptar" }] }
1289
- }
1290
-
1291
- const data = readFileSync(MEMORY_FILE, "utf-8")
1292
- const encrypted = encrypt(data, key)
1293
- writeFileSync(MEMORY_FILE, encrypted)
1294
-
1295
- saveConfig({ encrypted: true })
1296
-
1297
- return {
1298
- content: [{ type: "text" as const, text: "🔐 Encriptación habilitada" }],
1299
- }
1300
- }
1301
- )
1302
-
1303
- /**
1304
- * Register the memory_decrypt tool.
1305
- * Disable encryption and decrypt the memory file.
1306
- *
1307
- * @example
1308
- * ```typescript
1309
- * await callTool("memory_decrypt", { key: "your-encryption-key" })
1310
- * // "🔓 Encriptación deshabilitada"
1311
- * ```
1312
- */
1313
- server.registerTool(
1314
- "memory_decrypt",
1315
- {
1316
- title: "Disable Encryption",
1317
- description: "Deshabilita la encriptación y decodifica la memoria.",
1318
- inputSchema: {
1319
- key: z.string().describe("Clave de encriptación"),
1320
- },
1321
- },
1322
- async ({ key }) => {
1323
- const config = loadConfig()
1324
-
1325
- if (!config.encrypted) {
1326
- return { content: [{ type: "text" as const, text: "La encriptación no está habilitada" }] }
1327
- }
1328
-
1329
- const resolvedKey = key || getKey() || ""
1330
- if (!resolvedKey) {
1331
- return { content: [{ type: "text" as const, text: "❌ No hay clave. Pásala como argumento o la del archivo .env" }] }
1332
- }
1333
-
1334
- try {
1335
- const data = readFileSync(MEMORY_FILE, "utf-8")
1336
- const decrypted = decrypt(data, resolvedKey)
1337
-
1338
- writeFileSync(MEMORY_FILE, decrypted)
1339
- saveConfig({ encrypted: false })
1340
-
1341
- return {
1342
- content: [{ type: "text" as const, text: "🔓 Encriptación deshabilitada" }],
1343
- }
1344
- } catch {
1345
- return { content: [{ type: "text" as const, text: "❌ Clave incorrecta o datos corruptos" }] }
1346
- }
1347
- }
1348
- )
1349
-
1350
- /**
1351
- * Register the memory_captured tool.
1352
- * Show activity captured automatically by hooks (opt-in, off by default).
1353
- */
1354
- server.registerTool(
1355
- "memory_captured",
1356
- {
1357
- title: "List Captured Activity",
1358
- 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.",
1359
- inputSchema: {
1360
- limit: z.number().optional().default(20).describe("Máximo de observaciones a mostrar"),
1361
- tool: z.string().optional().default("").describe("Filtrar por nombre de herramienta"),
1362
- file: z.string().optional().default("").describe("Filtrar por archivo"),
1363
- clear: z.boolean().optional().default(false).describe("Si true, limpia el log de captura"),
1364
- },
1365
- },
1366
- async ({ limit, tool, file, clear }) => {
1367
- if (clear) {
1368
- if (existsSync(OBSERVATIONS_FILE)) {
1369
- writeFileSync(OBSERVATIONS_FILE, "version: 1\nobservations[0|]{ts|session|agent|branch|tool|hash|file|summary}:\n")
1370
- }
1371
- return { content: [{ type: "text" as const, text: "🧹 Log de captura limpiado" }] }
1372
- }
1373
-
1374
- let obs = readObservations()
1375
- if (tool) obs = obs.filter((o) => o.tool.toLowerCase().includes(tool.toLowerCase()))
1376
- if (file) obs = obs.filter((o) => o.file.toLowerCase().includes(file.toLowerCase()))
1377
- obs = obs.slice(-limit).reverse()
1378
-
1379
- if (obs.length === 0) {
1380
- return {
1381
- content: [{
1382
- type: "text" as const,
1383
- text: "No hay actividad capturada. La captura está desactivada por defecto; actívala con `toon-memory capture on`.",
1384
- }],
1385
- }
1386
- }
1387
-
1388
- const formatted = obs
1389
- .map((o) => `[${o.ts}] ${o.agent}@${o.branch}/${o.tool}${o.file ? ` (${o.file})` : ""}\n ${o.summary}`)
1390
- .join("\n\n")
1391
-
1392
- return { content: [{ type: "text" as const, text: `🔍 Actividad capturada (${obs.length}):\n\n${formatted}` }] }
1393
- }
1394
- )
1395
-
1396
- /**
1397
- * Register the memory_consolidate tool.
1398
- * Deterministic de-duplication of memory entries (no LLM).
1399
- */
1400
- server.registerTool(
1401
- "memory_consolidate",
1402
- {
1403
- title: "Consolidate Memory",
1404
- description: "Consolida la memoria eliminando entradas con contenido idéntico (mantiene la primera). Determinista, sin LLM.",
1405
- inputSchema: {},
1406
- },
1407
- async () => {
1408
- const result = consolidateEntries()
1409
- if (result.removed === 0) {
1410
- return { content: [{ type: "text" as const, text: `✅ Memoria ya consolidada (${result.kept} entradas, 0 duplicados)` }] }
1411
- }
1412
- return {
1413
- content: [{
1414
- type: "text" as const,
1415
- text: `🧹 Consolidadas ${result.removed} entradas duplicadas.\nQuedan ${result.kept} activas.\nDuplicados: ${result.duplicates.join(", ")}`,
1416
- }],
1417
- }
1418
- }
1419
- )
1420
-
1421
- /**
1422
- * Register the memory_sessions tool.
1423
- * File-based multi-session coordination — shows other active agent sessions
1424
- * (branch, files, last-seen) and soft conflicts, so parallel sessions don't
1425
- * step on each other. No server, no network, no LLM.
1426
- */
1427
- server.registerTool(
1428
- "memory_sessions",
1429
- {
1430
- title: "Active Sessions & Conflicts",
1431
- 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.",
1432
- inputSchema: {
1433
- conflictsOnly: z.boolean().optional().default(false).describe("Si true, muestra solo conflictos suaves"),
1434
- },
1435
- },
1436
- async ({ conflictsOnly }) => {
1437
- const selfId = resolveSessionId()
1438
- const { active, conflicts } = coordinationView(selfId)
1439
-
1440
- if (conflictsOnly) {
1441
- if (conflicts.length === 0) {
1442
- return { content: [{ type: "text" as const, text: "✅ No hay conflictos suaves entre sesiones activas." }] }
1443
- }
1444
- const lines = conflicts.map((c) => {
1445
- const who = c.sessions.map((s) => `${s.agent}@${s.branch} (${s.id})`).join(", ")
1446
- return `⚠️ ${c.file}\n ↔ ${who}`
1447
- })
1448
- return {
1449
- content: [{ type: "text" as const, text: `🔥 Conflictos suaves (${conflicts.length}):\n\n${lines.join("\n\n")}` }],
1450
- }
1451
- }
1452
-
1453
- if (active.length === 0) {
1454
- return {
1455
- content: [{
1456
- type: "text" as const,
1457
- text: "🟢 No hay otras sesiones activas en este proyecto.\n(Esta sesión: " + selfId + " @ " + currentBranch() + ")",
1458
- }],
1459
- }
1460
- }
1461
-
1462
- const ttlMin = Math.round(SESSION_TTL_MS / 60000)
1463
- const section = (s: ReturnType<typeof coordinationView>["active"][number]) => {
1464
- const mins = Math.max(0, Math.round(s.ageMs / 60000))
1465
- const tag = s.id === selfId ? " (tú)" : ""
1466
- const ended = s.ended ? " 🏁" : ""
1467
- const files = Object.keys(s.files).slice(0, 8).map((f) => ` • ${f}`).join("\n")
1468
- const fileBlock = files ? `\n Archivos:\n${files}` : ""
1469
- return `• ${s.agent} @ ${s.branch}${tag}${ended}\n id: ${s.id}\n hace ${mins} min${fileBlock}`
1470
- }
1471
-
1472
- const parts = [
1473
- `🧭 Sesiones activas (${active.length}) — ventana ${ttlMin} min:`,
1474
- "",
1475
- ...active.map(section),
1476
- ]
1477
-
1478
- if (conflicts.length > 0) {
1479
- parts.push("", `🔥 Conflictos suaves (${conflicts.length}):`)
1480
- for (const c of conflicts) {
1481
- const who = c.sessions.map((s) => `${s.agent}@${s.branch}`).join(", ")
1482
- parts.push(` ⚠️ ${c.file} ↔ ${who}`)
1483
- }
1484
- } else {
1485
- parts.push("", "✅ Sin conflictos suaves detectados.")
1486
- }
1487
-
1488
- return { content: [{ type: "text" as const, text: parts.join("\n") }] }
1489
- }
1490
- )
14
+ registerResources(server)
15
+ registerTools(server)
1491
16
 
1492
17
  // Startup TTL prune: drop entries whose TTL has elapsed. Best-effort — never
1493
18
  // block server startup on a prune failure.