toon-memory 2.4.5 → 2.5.1
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 +192 -41
- package/bin/toon-memory.js +17 -14
- package/dist/cli/setup.js +83 -125
- package/mcp/server.js +226 -33
- package/package.json +8 -2
- package/src/bin/toon-memory.ts +17 -14
- package/src/cli/setup.ts +93 -145
- package/src/lib/quality.ts +221 -0
- package/src/mcp/server.ts +98 -31
package/src/mcp/server.ts
CHANGED
|
@@ -7,7 +7,8 @@ import { fileURLToPath } from "url"
|
|
|
7
7
|
import { randomBytes, createCipheriv, createDecipheriv } from "crypto"
|
|
8
8
|
import { withLockSync, atomicWrite, readUnderLock } from "../lib/lock"
|
|
9
9
|
import { coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS } from "../lib/sessions"
|
|
10
|
-
import { graphRecallDetailed, renderCompact } from "../lib/graph"
|
|
10
|
+
import { graphRecallDetailed, renderCompact, parseEntries, buildGraph, bm25Scores, centrality } from "../lib/graph"
|
|
11
|
+
import { qualityScore, mergeEntries, generateSmartRecall, generateSystemPrimer } from "../lib/quality"
|
|
11
12
|
|
|
12
13
|
const __dirname = dirname(fileURLToPath(import.meta.url))
|
|
13
14
|
|
|
@@ -117,7 +118,7 @@ function ensureMemoryDir(): void {
|
|
|
117
118
|
function ensureMemoryFile(): void {
|
|
118
119
|
ensureMemoryDir()
|
|
119
120
|
if (!existsSync(MEMORY_FILE)) {
|
|
120
|
-
writeFileSync(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links}:\n")
|
|
121
|
+
writeFileSync(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence}:\n")
|
|
121
122
|
}
|
|
122
123
|
}
|
|
123
124
|
|
|
@@ -560,8 +561,9 @@ function pruneExpiredEntries(): number {
|
|
|
560
561
|
}
|
|
561
562
|
|
|
562
563
|
/**
|
|
563
|
-
* Deterministic consolidation:
|
|
564
|
-
*
|
|
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.
|
|
565
567
|
*/
|
|
566
568
|
function consolidateEntries(): { removed: number; kept: number; duplicates: string[] } {
|
|
567
569
|
const data = readMemory()
|
|
@@ -570,32 +572,61 @@ function consolidateEntries(): { removed: number; kept: number; duplicates: stri
|
|
|
570
572
|
if (headerIdx === -1) return { removed: 0, kept: 0, duplicates: [] }
|
|
571
573
|
|
|
572
574
|
const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
|
|
573
|
-
|
|
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>()
|
|
574
603
|
const order: string[] = []
|
|
575
604
|
const duplicates: string[] = []
|
|
576
605
|
|
|
577
|
-
for (const
|
|
578
|
-
const
|
|
606
|
+
for (const idx of keyOrder) {
|
|
607
|
+
const line = byKey.get(idx)!
|
|
608
|
+
const parts = line.split("|")
|
|
579
609
|
if (parts.length < 3) {
|
|
580
|
-
order.push(line
|
|
610
|
+
order.push(line)
|
|
581
611
|
continue
|
|
582
612
|
}
|
|
583
613
|
const content = (parts[3] || "").toLowerCase().replace(/\s+/g, " ").trim()
|
|
584
|
-
if (
|
|
614
|
+
if (contentSeen.has(content)) {
|
|
585
615
|
duplicates.push(parts[2])
|
|
586
616
|
continue
|
|
587
617
|
}
|
|
588
|
-
|
|
589
|
-
order.push(line
|
|
618
|
+
contentSeen.set(content, line)
|
|
619
|
+
order.push(line)
|
|
590
620
|
}
|
|
591
621
|
|
|
592
|
-
|
|
622
|
+
const totalRemoved = mergedAway.length + duplicates.length
|
|
623
|
+
if (totalRemoved === 0) return { removed: 0, kept: order.length, duplicates: [] }
|
|
593
624
|
|
|
594
625
|
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${order.length}|`)
|
|
595
626
|
lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...order.map((l) => ` ${l}`))
|
|
596
627
|
writeMemory(lines.join("\n"))
|
|
597
628
|
|
|
598
|
-
return { removed:
|
|
629
|
+
return { removed: totalRemoved, kept: order.length, duplicates }
|
|
599
630
|
}
|
|
600
631
|
|
|
601
632
|
const server = new McpServer(
|
|
@@ -656,13 +687,8 @@ server.registerResource(
|
|
|
656
687
|
{ title: "Memory Summaries", mimeType: "text/plain" },
|
|
657
688
|
async (uri) => {
|
|
658
689
|
const data = readMemory()
|
|
659
|
-
const
|
|
660
|
-
|
|
661
|
-
if (summaryIdx === -1) {
|
|
662
|
-
return { contents: [{ uri: uri.href, text: "No hay resúmenes guardados" }] }
|
|
663
|
-
}
|
|
664
|
-
const summaryText = lines.slice(summaryIdx + 1).filter((l) => l.includes(":")).join("\n")
|
|
665
|
-
return { contents: [{ uri: uri.href, text: summaryText || "No hay resúmenes guardados" }] }
|
|
690
|
+
const primer = generateSystemPrimer(data)
|
|
691
|
+
return { contents: [{ uri: uri.href, text: primer }] }
|
|
666
692
|
}
|
|
667
693
|
)
|
|
668
694
|
|
|
@@ -730,16 +756,22 @@ server.registerTool(
|
|
|
730
756
|
const resolvedLinks = links
|
|
731
757
|
? links.split(/[\s;]+/).filter(Boolean).join(" ")
|
|
732
758
|
: existingParts[9] || ""
|
|
733
|
-
|
|
759
|
+
let newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|0|${resolvedLinks}`
|
|
734
760
|
let action = "Guardado"
|
|
761
|
+
let mergeInfo = ""
|
|
735
762
|
const tagsInferred = !tags && resolvedTags ? true : false
|
|
736
763
|
|
|
737
764
|
if (existingIdx !== -1) {
|
|
738
|
-
//
|
|
765
|
+
// Merge-dedup: combine attributes instead of overwriting
|
|
766
|
+
newEntry = mergeEntries(lines[existingIdx].trim(), newEntry)
|
|
739
767
|
lines[existingIdx] = ` ${newEntry}`
|
|
740
768
|
action = "Actualizado"
|
|
769
|
+
mergeInfo = "\n🔗 Merge: tags combinados, fecha y links actualizados"
|
|
741
770
|
} else {
|
|
742
|
-
// Create new entry
|
|
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}`
|
|
743
775
|
const match = lines[headerIdx].match(/\[(\d+)\|/)
|
|
744
776
|
const count = match ? parseInt(match[1]) : 0
|
|
745
777
|
lines.splice(headerIdx + 1, 0, ` ${newEntry}`)
|
|
@@ -770,7 +802,7 @@ server.registerTool(
|
|
|
770
802
|
}
|
|
771
803
|
|
|
772
804
|
return {
|
|
773
|
-
content: [{ type: "text" as const, text: `🧠 ${action}: ${category}/${key} (${entryId})\n${content}${ttlMsg}${inferredMsg}${archiveMsg}${relatedMsg}` }],
|
|
805
|
+
content: [{ type: "text" as const, text: `🧠 ${action}: ${category}/${key} (${entryId})\n${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }],
|
|
774
806
|
}
|
|
775
807
|
}
|
|
776
808
|
)
|
|
@@ -815,17 +847,19 @@ server.registerTool(
|
|
|
815
847
|
const parts = trimmed.split("|")
|
|
816
848
|
if (parts.length < 7) return null
|
|
817
849
|
const [id, cat, key, content, file, tags, date, ttl, accessedRaw] = parts
|
|
850
|
+
const qualityRaw = parts[10] || ""
|
|
851
|
+
const confidenceRaw = parts[11] || ""
|
|
818
852
|
if (category && cat !== category) return null
|
|
819
853
|
if (from_date && date < from_date) return null
|
|
820
854
|
if (to_date && date > to_date) return null
|
|
821
855
|
if (ttl && isExpired(ttl)) return null
|
|
822
|
-
const searchStr = normalize(`${id} ${cat} ${key} ${content} ${file} ${tags}`)
|
|
856
|
+
const searchStr = normalize(`${id} ${cat} ${key} ${content} ${file} ${tags} ${qualityRaw} ${confidenceRaw}`)
|
|
823
857
|
// All query tokens must match (AND logic)
|
|
824
858
|
if (!queryTokens.every((token) => searchStr.includes(token))) return null
|
|
825
859
|
const accessed = accessedRaw ? parseInt(accessedRaw) || 0 : 0
|
|
826
|
-
return { id, cat, key, content, file, tags, date, accessed }
|
|
860
|
+
return { id, cat, key, content, file, tags, date, accessed, qualityRaw, confidenceRaw }
|
|
827
861
|
})
|
|
828
|
-
.filter(Boolean) as Array<{ id: string; cat: string; key: string; content: string; file: string; tags: string; date: string; accessed: number }>
|
|
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 }>
|
|
829
863
|
|
|
830
864
|
if (results.length === 0) {
|
|
831
865
|
return { content: [{ type: "text" as const, text: `No se encontraron resultados para "${query}"` }] }
|
|
@@ -856,9 +890,13 @@ server.registerTool(
|
|
|
856
890
|
return { content: [{ type: "text" as const, text: formatted }] }
|
|
857
891
|
}
|
|
858
892
|
|
|
859
|
-
// Rank by importance (recency + access frequency), then bump access counts.
|
|
893
|
+
// Rank by importance (recency + access frequency) + quality, then bump access counts.
|
|
860
894
|
const ranked = results
|
|
861
|
-
.map((r) =>
|
|
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
|
+
})
|
|
862
900
|
.sort((a, b) => b.score - a.score)
|
|
863
901
|
|
|
864
902
|
bumpAccessed(ranked.map((r) => r.id))
|
|
@@ -955,7 +993,7 @@ server.registerTool(
|
|
|
955
993
|
const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
|
|
956
994
|
const entries = lines.map((l) => {
|
|
957
995
|
const parts = l.trim().split("|")
|
|
958
|
-
return { category: parts[1] || "unknown", ttl: parts[7] || "" }
|
|
996
|
+
return { category: parts[1] || "unknown", ttl: parts[7] || "", quality: parts[10] || "" }
|
|
959
997
|
})
|
|
960
998
|
|
|
961
999
|
const byCategory: Record<string, number> = {}
|
|
@@ -965,6 +1003,10 @@ server.registerTool(
|
|
|
965
1003
|
|
|
966
1004
|
const withTtl = entries.filter((e) => e.ttl).length
|
|
967
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"
|
|
968
1010
|
|
|
969
1011
|
const summaryLines = data.split("\n").filter((l) => l.includes(":") && !l.startsWith(" ") && !l.startsWith("version") && !l.startsWith("entries") && !/^\[\d+\|]/.test(l))
|
|
970
1012
|
const stats = [
|
|
@@ -975,12 +1017,14 @@ server.registerTool(
|
|
|
975
1017
|
...Object.entries(byCategory).map(([k, v]) => ` ${k}: ${v}`),
|
|
976
1018
|
"",
|
|
977
1019
|
`TTL: ${withTtl} con expiración, ${expired} expiradas`,
|
|
1020
|
+
`Calidad promedio: ${avgQuality} (${withQuality} con score)`,
|
|
978
1021
|
"",
|
|
979
1022
|
`Últimas 5 entradas:`,
|
|
980
1023
|
...lines.slice(-5).map((l) => {
|
|
981
1024
|
const parts = l.trim().split("|")
|
|
982
1025
|
const ttlInfo = parts[7] ? ` | TTL: ${parts[7]}` : ""
|
|
983
|
-
|
|
1026
|
+
const qualityInfo = parts[10] ? ` | Q: ${parts[10]}` : ""
|
|
1027
|
+
return ` [${parts[1]}] ${parts[2]} (${parts[0]})${ttlInfo}${qualityInfo}`
|
|
984
1028
|
}),
|
|
985
1029
|
]
|
|
986
1030
|
|
|
@@ -1081,6 +1125,29 @@ server.registerTool(
|
|
|
1081
1125
|
}
|
|
1082
1126
|
)
|
|
1083
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
|
+
|
|
1084
1151
|
/**
|
|
1085
1152
|
* Register the memory_summary tool.
|
|
1086
1153
|
* Get or set file summaries to save tokens when reading large files.
|