toon-memory 1.8.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/README.md +158 -20
- package/dist/cli/capture.js +276 -0
- package/dist/cli/session-start.js +192 -0
- package/dist/cli/setup.js +123 -21
- package/dist/cli/toon-memory.js +3 -2
- package/mcp/server.js +614 -63
- package/package.json +5 -3
- package/skills/toon-memory.md +44 -10
- package/src/cli/capture.ts +187 -0
- package/src/cli/session-start.ts +70 -0
- package/src/cli/setup.ts +148 -15
- package/src/lib/lock.ts +120 -0
- package/src/lib/sessions.ts +225 -0
- package/src/mcp/server.ts +518 -63
- package/src/memory.ts +1 -1
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
|
|
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 =
|
|
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
|
-
|
|
203
|
+
safeWrite(MEMORY_FILE, encrypted)
|
|
195
204
|
return
|
|
196
205
|
}
|
|
197
206
|
|
|
198
|
-
|
|
207
|
+
safeWrite(MEMORY_FILE, content)
|
|
199
208
|
}
|
|
200
209
|
|
|
201
210
|
/**
|
|
@@ -298,6 +307,39 @@ function parseRelativeDate(since: string): string {
|
|
|
298
307
|
return today
|
|
299
308
|
}
|
|
300
309
|
|
|
310
|
+
const normalize = (s: string) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Find entries related to the given text by fuzzy matching.
|
|
314
|
+
* Returns top N results ranked by match quality.
|
|
315
|
+
*/
|
|
316
|
+
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 }> {
|
|
317
|
+
const data = readMemory()
|
|
318
|
+
const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
|
|
319
|
+
const queryTokens = normalize(text).split(" ").filter(Boolean)
|
|
320
|
+
|
|
321
|
+
const scored = lines
|
|
322
|
+
.map((line) => {
|
|
323
|
+
const trimmed = line.trim()
|
|
324
|
+
const parts = trimmed.split("|")
|
|
325
|
+
if (parts.length < 7) return null
|
|
326
|
+
const [id, cat, key, content, file, tags, date] = parts
|
|
327
|
+
if (key === excludeKey) return null
|
|
328
|
+
const searchStr = normalize(`${id} ${cat} ${key} ${content} ${file} ${tags}`)
|
|
329
|
+
let score = 0
|
|
330
|
+
for (const token of queryTokens) {
|
|
331
|
+
if (searchStr.includes(token)) score++
|
|
332
|
+
}
|
|
333
|
+
if (score === 0) return null
|
|
334
|
+
return { id, cat, key, content, file, tags, date, score }
|
|
335
|
+
})
|
|
336
|
+
.filter(Boolean)
|
|
337
|
+
.sort((a, b) => b!.score - a!.score)
|
|
338
|
+
.slice(0, limit)
|
|
339
|
+
|
|
340
|
+
return scored as Array<{ id: string; cat: string; key: string; content: string; file: string; tags: string; date: string; score: number }>
|
|
341
|
+
}
|
|
342
|
+
|
|
301
343
|
/**
|
|
302
344
|
* Archive entries older than ARCHIVE_DAYS to archive.toon.
|
|
303
345
|
*
|
|
@@ -312,41 +354,109 @@ function parseRelativeDate(since: string): string {
|
|
|
312
354
|
* console.log(`Archived: ${result.archived}, Kept: ${result.kept}`)
|
|
313
355
|
* ```
|
|
314
356
|
*/
|
|
315
|
-
|
|
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 } {
|
|
316
421
|
const data = readMemory()
|
|
317
422
|
const lines = data.split("\n")
|
|
318
423
|
const headerIdx = lines.findIndex((l) => l.startsWith("entries["))
|
|
319
|
-
|
|
424
|
+
|
|
320
425
|
if (headerIdx === -1) return { archived: 0, kept: 0 }
|
|
321
|
-
|
|
426
|
+
|
|
322
427
|
const today = new Date()
|
|
323
428
|
const cutoff = new Date(today)
|
|
324
429
|
cutoff.setDate(cutoff.getDate() - ARCHIVE_DAYS)
|
|
325
430
|
const cutoffStr = cutoff.toISOString().split("T")[0]
|
|
326
|
-
|
|
431
|
+
|
|
327
432
|
const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0)
|
|
328
|
-
const toArchive
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
for (const line of entryLines) {
|
|
433
|
+
const toArchive = new Set<number>()
|
|
434
|
+
|
|
435
|
+
entryLines.forEach((line, idx) => {
|
|
332
436
|
const parts = line.trim().split("|")
|
|
333
|
-
if (parts.length
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
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)
|
|
345
452
|
}
|
|
346
453
|
}
|
|
347
|
-
|
|
348
|
-
if (toArchive.
|
|
349
|
-
|
|
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
|
+
|
|
350
460
|
// Write archived entries
|
|
351
461
|
let archiveContent = ""
|
|
352
462
|
if (existsSync(ARCHIVE_FILE)) {
|
|
@@ -354,35 +464,185 @@ function archiveOldEntries(): { archived: number; kept: number } {
|
|
|
354
464
|
} else {
|
|
355
465
|
archiveContent = `version: 1\narchived:\n`
|
|
356
466
|
}
|
|
357
|
-
|
|
467
|
+
|
|
358
468
|
const archiveLines = archiveContent.split("\n")
|
|
359
469
|
let archiveHeaderIdx = archiveLines.findIndex((l) => l.startsWith("archived["))
|
|
360
470
|
if (archiveHeaderIdx === -1) {
|
|
361
471
|
archiveLines.push(`archived[0|]{id|category|key|content|file|tags|date}:`)
|
|
362
472
|
archiveHeaderIdx = archiveLines.length - 1
|
|
363
473
|
}
|
|
364
|
-
|
|
474
|
+
|
|
365
475
|
const archiveMatch = archiveLines[archiveHeaderIdx].match(/archived\[(\d+)\|/)
|
|
366
476
|
const archiveCount = archiveMatch ? parseInt(archiveMatch[1]) : 0
|
|
367
|
-
|
|
368
|
-
for (const entry of
|
|
477
|
+
|
|
478
|
+
for (const entry of toArchiveLines) {
|
|
369
479
|
archiveLines.splice(archiveHeaderIdx + 1, 0, ` ${entry}`)
|
|
370
480
|
}
|
|
371
|
-
archiveLines[archiveHeaderIdx] = archiveLines[archiveHeaderIdx].replace(/archived\[\d+\|/, `[${archiveCount +
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
481
|
+
archiveLines[archiveHeaderIdx] = archiveLines[archiveHeaderIdx].replace(/archived\[\d+\|/, `[${archiveCount + toArchiveLines.length}|`)
|
|
482
|
+
|
|
483
|
+
safeWrite(ARCHIVE_FILE, archiveLines.join("\n"))
|
|
484
|
+
|
|
375
485
|
// Update main file
|
|
376
|
-
lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${
|
|
377
|
-
|
|
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()}`))
|
|
378
494
|
writeMemory(lines.join("\n"))
|
|
379
|
-
|
|
380
|
-
return { archived:
|
|
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 }
|
|
381
578
|
}
|
|
382
579
|
|
|
383
580
|
const server = new McpServer(
|
|
384
|
-
{ name: "toon-memory", version: "
|
|
385
|
-
{ capabilities: { tools: { listChanged: true } } }
|
|
581
|
+
{ name: "toon-memory", version: "2.1.0" },
|
|
582
|
+
{ capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
|
|
583
|
+
)
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* Register memory entries as an MCP resource.
|
|
587
|
+
* Agents can read this as context in the system prompt.
|
|
588
|
+
*/
|
|
589
|
+
server.registerResource(
|
|
590
|
+
"memory-entries",
|
|
591
|
+
"toon://memory/entries",
|
|
592
|
+
{ title: "Memory Entries", mimeType: "text/plain" },
|
|
593
|
+
async (uri) => {
|
|
594
|
+
const data = readMemory()
|
|
595
|
+
return { contents: [{ uri: uri.href, text: data }] }
|
|
596
|
+
}
|
|
597
|
+
)
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* Register memory stats as an MCP resource.
|
|
601
|
+
*/
|
|
602
|
+
server.registerResource(
|
|
603
|
+
"memory-stats",
|
|
604
|
+
"toon://memory/stats",
|
|
605
|
+
{ title: "Memory Stats", mimeType: "text/plain" },
|
|
606
|
+
async (uri) => {
|
|
607
|
+
const data = readMemory()
|
|
608
|
+
const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
|
|
609
|
+
const entries = lines.map((l) => {
|
|
610
|
+
const parts = l.trim().split("|")
|
|
611
|
+
return { category: parts[1] || "unknown", ttl: parts[7] || "" }
|
|
612
|
+
})
|
|
613
|
+
const byCategory: Record<string, number> = {}
|
|
614
|
+
for (const e of entries) {
|
|
615
|
+
byCategory[e.category] = (byCategory[e.category] || 0) + 1
|
|
616
|
+
}
|
|
617
|
+
const withTtl = entries.filter((e) => e.ttl).length
|
|
618
|
+
const expired = entries.filter((e) => e.ttl && isExpired(e.ttl)).length
|
|
619
|
+
const text = [
|
|
620
|
+
`Entradas totales: ${entries.length}`,
|
|
621
|
+
`TTL: ${withTtl} con expiración, ${expired} expiradas`,
|
|
622
|
+
"Por categoría:",
|
|
623
|
+
...Object.entries(byCategory).map(([k, v]) => ` ${k}: ${v}`),
|
|
624
|
+
].join("\n")
|
|
625
|
+
return { contents: [{ uri: uri.href, text }] }
|
|
626
|
+
}
|
|
627
|
+
)
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* Register memory summaries as an MCP resource.
|
|
631
|
+
*/
|
|
632
|
+
server.registerResource(
|
|
633
|
+
"memory-summaries",
|
|
634
|
+
"toon://memory/summaries",
|
|
635
|
+
{ title: "Memory Summaries", mimeType: "text/plain" },
|
|
636
|
+
async (uri) => {
|
|
637
|
+
const data = readMemory()
|
|
638
|
+
const lines = data.split("\n")
|
|
639
|
+
const summaryIdx = lines.findIndex((l) => l.trim().startsWith("summaries:"))
|
|
640
|
+
if (summaryIdx === -1) {
|
|
641
|
+
return { contents: [{ uri: uri.href, text: "No hay resúmenes guardados" }] }
|
|
642
|
+
}
|
|
643
|
+
const summaryText = lines.slice(summaryIdx + 1).filter((l) => l.includes(":")).join("\n")
|
|
644
|
+
return { contents: [{ uri: uri.href, text: summaryText || "No hay resúmenes guardados" }] }
|
|
645
|
+
}
|
|
386
646
|
)
|
|
387
647
|
|
|
388
648
|
/**
|
|
@@ -443,7 +703,7 @@ server.registerTool(
|
|
|
443
703
|
const entryId = existingIdx !== -1 ? existingId : newId
|
|
444
704
|
const resolvedTtl = parseTTL(ttl)
|
|
445
705
|
const resolvedTags = tags ? tags : inferTags(content, key)
|
|
446
|
-
const newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}`
|
|
706
|
+
const newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|0`
|
|
447
707
|
let action = "Guardado"
|
|
448
708
|
const tagsInferred = !tags && resolvedTags ? true : false
|
|
449
709
|
|
|
@@ -461,21 +721,29 @@ server.registerTool(
|
|
|
461
721
|
|
|
462
722
|
writeMemory(lines.join("\n"))
|
|
463
723
|
|
|
464
|
-
// Auto-archive if we exceed MAX_ENTRIES
|
|
724
|
+
// Auto-archive if we exceed MAX_ENTRIES (old entries, then lowest-importance)
|
|
465
725
|
const headerMatch = lines[headerIdx].match(/\[(\d+)\|/)
|
|
466
726
|
const entryCount = headerMatch ? parseInt(headerMatch[1]) : 0
|
|
467
727
|
let archiveMsg = ""
|
|
468
728
|
if (entryCount > MAX_ENTRIES) {
|
|
469
|
-
const result = archiveOldEntries()
|
|
729
|
+
const result = archiveOldEntries({ trimToMax: true })
|
|
470
730
|
if (result.archived > 0) {
|
|
471
|
-
archiveMsg = `\n📦 Auto-archived ${result.archived}
|
|
731
|
+
archiveMsg = `\n📦 Auto-archived ${result.archived} low-importance entries (${result.kept} kept)`
|
|
472
732
|
}
|
|
473
733
|
}
|
|
474
734
|
|
|
475
735
|
const ttlMsg = resolvedTtl ? `\n⏰ TTL: ${resolvedTtl}` : ""
|
|
476
736
|
const inferredMsg = tagsInferred ? `\n🏷️ Tags inferidos: ${resolvedTags}` : ""
|
|
737
|
+
|
|
738
|
+
const related = findRelatedEntries(`${key} ${content} ${resolvedTags}`, key, 3)
|
|
739
|
+
let relatedMsg = ""
|
|
740
|
+
if (related.length > 0) {
|
|
741
|
+
const items = related.map((r) => ` [${r.cat}] ${r.key} — ${r.content.slice(0, 80)}`).join("\n")
|
|
742
|
+
relatedMsg = `\n\n🔗 Entradas relacionadas:\n${items}`
|
|
743
|
+
}
|
|
744
|
+
|
|
477
745
|
return {
|
|
478
|
-
content: [{ type: "text" as const, text: `🧠 ${action}: ${category}/${key} (${entryId})\n${content}${ttlMsg}${inferredMsg}${archiveMsg}` }],
|
|
746
|
+
content: [{ type: "text" as const, text: `🧠 ${action}: ${category}/${key} (${entryId})\n${content}${ttlMsg}${inferredMsg}${archiveMsg}${relatedMsg}` }],
|
|
479
747
|
}
|
|
480
748
|
}
|
|
481
749
|
)
|
|
@@ -505,7 +773,7 @@ server.registerTool(
|
|
|
505
773
|
},
|
|
506
774
|
async ({ query, category, from_date, to_date }) => {
|
|
507
775
|
const data = readMemory()
|
|
508
|
-
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:"))
|
|
509
777
|
|
|
510
778
|
// Normalize for fuzzy matching: hyphens/underscores → spaces, collapse whitespace
|
|
511
779
|
const normalize = (s: string) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
|
|
@@ -516,7 +784,7 @@ server.registerTool(
|
|
|
516
784
|
const trimmed = line.trim()
|
|
517
785
|
const parts = trimmed.split("|")
|
|
518
786
|
if (parts.length < 7) return null
|
|
519
|
-
const [id, cat, key, content, file, tags, date, ttl] = parts
|
|
787
|
+
const [id, cat, key, content, file, tags, date, ttl, accessedRaw] = parts
|
|
520
788
|
if (category && cat !== category) return null
|
|
521
789
|
if (from_date && date < from_date) return null
|
|
522
790
|
if (to_date && date > to_date) return null
|
|
@@ -524,16 +792,24 @@ server.registerTool(
|
|
|
524
792
|
const searchStr = normalize(`${id} ${cat} ${key} ${content} ${file} ${tags}`)
|
|
525
793
|
// All query tokens must match (AND logic)
|
|
526
794
|
if (!queryTokens.every((token) => searchStr.includes(token))) return null
|
|
527
|
-
|
|
795
|
+
const accessed = accessedRaw ? parseInt(accessedRaw) || 0 : 0
|
|
796
|
+
return { id, cat, key, content, file, tags, date, accessed }
|
|
528
797
|
})
|
|
529
|
-
.filter(Boolean)
|
|
798
|
+
.filter(Boolean) as Array<{ id: string; cat: string; key: string; content: string; file: string; tags: string; date: string; accessed: number }>
|
|
530
799
|
|
|
531
800
|
if (results.length === 0) {
|
|
532
801
|
return { content: [{ type: "text" as const, text: `No se encontraron resultados para "${query}"` }] }
|
|
533
802
|
}
|
|
534
803
|
|
|
535
|
-
|
|
536
|
-
|
|
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}`)
|
|
537
813
|
.join("\n\n")
|
|
538
814
|
|
|
539
815
|
return { content: [{ type: "text" as const, text: formatted }] }
|
|
@@ -567,7 +843,7 @@ server.registerTool(
|
|
|
567
843
|
return { content: [{ type: "text" as const, text: "No hay entradas en memoria" }] }
|
|
568
844
|
}
|
|
569
845
|
|
|
570
|
-
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:"))
|
|
571
847
|
const filtered = entryLines.filter((l) => {
|
|
572
848
|
const parts = l.trim().split("|")
|
|
573
849
|
return parts[0] !== key && parts[2] !== key
|
|
@@ -704,6 +980,35 @@ server.registerTool(
|
|
|
704
980
|
}
|
|
705
981
|
)
|
|
706
982
|
|
|
983
|
+
/**
|
|
984
|
+
* Register the memory_suggest tool.
|
|
985
|
+
* Suggest related entries for a given text context.
|
|
986
|
+
*/
|
|
987
|
+
server.registerTool(
|
|
988
|
+
"memory_suggest",
|
|
989
|
+
{
|
|
990
|
+
title: "Suggest Related Memories",
|
|
991
|
+
description: "Sugiere entradas de memoria relacionadas con un contexto dado. Útil para obtener contexto antes de una tarea.",
|
|
992
|
+
inputSchema: {
|
|
993
|
+
context: z.string().describe("Texto o contexto para buscar sugerencias"),
|
|
994
|
+
limit: z.number().optional().default(5).describe("Máximo de sugerencias"),
|
|
995
|
+
},
|
|
996
|
+
},
|
|
997
|
+
async ({ context, limit }) => {
|
|
998
|
+
const related = findRelatedEntries(context, "", limit)
|
|
999
|
+
|
|
1000
|
+
if (related.length === 0) {
|
|
1001
|
+
return { content: [{ type: "text" as const, text: `No se encontraron entradas relacionadas con "${context}"` }] }
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
const formatted = related
|
|
1005
|
+
.map((r) => `[${r.cat}] ${r.key} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`)
|
|
1006
|
+
.join("\n\n")
|
|
1007
|
+
|
|
1008
|
+
return { content: [{ type: "text" as const, text: `🔍 Sugerencias para "${context}":\n\n${formatted}` }] }
|
|
1009
|
+
}
|
|
1010
|
+
)
|
|
1011
|
+
|
|
707
1012
|
/**
|
|
708
1013
|
* Register the memory_summary tool.
|
|
709
1014
|
* Get or set file summaries to save tokens when reading large files.
|
|
@@ -903,5 +1208,155 @@ server.registerTool(
|
|
|
903
1208
|
}
|
|
904
1209
|
)
|
|
905
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
|
+
|
|
906
1361
|
const transport = new StdioServerTransport()
|
|
907
1362
|
await server.connect(transport)
|