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