toon-memory 2.10.0 → 3.0.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.de.md +1209 -0
- package/README.es.md +1214 -0
- package/README.fr.md +1209 -0
- package/README.ja.md +1209 -0
- package/README.ko.md +1209 -0
- package/README.md +16 -3
- package/README.pt-br.md +1211 -0
- package/README.zh.md +1209 -0
- package/dist/cli/session-start.js +32 -1
- package/mcp/server.js +28271 -27641
- package/package.json +1 -1
- package/src/cli/session-start.ts +47 -1
- package/src/lib/context.ts +6 -5
- package/src/lib/graph.ts +4 -0
- package/src/lib/quality.ts +46 -10
- package/src/lib/utils.ts +4 -0
- package/src/mcp/config.ts +2 -0
- package/src/mcp/consolidation.ts +52 -7
- package/src/mcp/scoring.ts +7 -2
- package/src/mcp/tools.ts +573 -7
package/src/mcp/tools.ts
CHANGED
|
@@ -16,6 +16,8 @@ import { qualityScore, mergeEntries, generateSmartRecall } from "../lib/quality"
|
|
|
16
16
|
import { generateContextBrief, generateContextGenerate, generateContextDiff, generateContextFocus, generateContextHealth, generateContextExport } from "../lib/context"
|
|
17
17
|
import { coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS } from "../lib/sessions"
|
|
18
18
|
import { fileMtimes } from "../lib/git"
|
|
19
|
+
import { normalize, isExpiredLocal, tokenize, importance } from "../lib/utils"
|
|
20
|
+
import { expandSynonyms } from "../lib/synonyms"
|
|
19
21
|
|
|
20
22
|
/**
|
|
21
23
|
* Register all 20 memory tools.
|
|
@@ -28,7 +30,7 @@ server.registerTool(
|
|
|
28
30
|
"memory_remember",
|
|
29
31
|
{
|
|
30
32
|
title: "Save to Memory",
|
|
31
|
-
description: "Save a fact to the project's persistent memory (decisions, patterns, bugs, knowledge). Persists between sessions.
|
|
33
|
+
description: "Save a fact to the project's persistent memory (decisions, patterns, bugs, knowledge). Persists between sessions. Tags: 'private' excludes from context injection; 'superseded' marks as obsolete.",
|
|
32
34
|
inputSchema: {
|
|
33
35
|
category: z.enum(["decision", "pattern", "bug", "knowledge"]).describe("Category of the fact"),
|
|
34
36
|
key: z.string().describe("Short title in kebab-case (e.g. risk-engine-priority)"),
|
|
@@ -67,7 +69,9 @@ server.registerTool(
|
|
|
67
69
|
|
|
68
70
|
const entryId = existingIdx !== -1 ? existingId : newId
|
|
69
71
|
const resolvedTtl = parseTTL(ttl)
|
|
70
|
-
const
|
|
72
|
+
const config = loadConfig()
|
|
73
|
+
const verbatim = config.verbatim === true
|
|
74
|
+
const resolvedTags = tags ? tags : (verbatim ? "" : inferTags(content, key, config.vocab))
|
|
71
75
|
const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : []
|
|
72
76
|
const resolvedLinks = links
|
|
73
77
|
? links.split(/[\s;]+/).filter(Boolean).join(" ")
|
|
@@ -83,9 +87,11 @@ server.registerTool(
|
|
|
83
87
|
action = "Updated"
|
|
84
88
|
mergeInfo = "\nMerge: tags combined, date and links updated"
|
|
85
89
|
} else {
|
|
86
|
-
const
|
|
90
|
+
const accessed = 0
|
|
91
|
+
const lastAccessed = ""
|
|
92
|
+
const quality = verbatim ? 0.5 : qualityScore(resolvedTags, resolvedLinks, content, date, accessed, lastAccessed)
|
|
87
93
|
const confidence = 1.0
|
|
88
|
-
newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}
|
|
94
|
+
newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|${accessed}|${resolvedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}`
|
|
89
95
|
const match = lines[headerIdx].match(/\[(\d+)\|/)
|
|
90
96
|
const count = match ? parseInt(match[1]) : 0
|
|
91
97
|
lines.splice(headerIdx + 1, 0, ` ${newEntry}`)
|
|
@@ -126,7 +132,7 @@ server.registerTool(
|
|
|
126
132
|
"memory_recall",
|
|
127
133
|
{
|
|
128
134
|
title: "Search Memory",
|
|
129
|
-
description: "Search the project's persistent memory. Returns relevant entries. Use BEFORE reading files.",
|
|
135
|
+
description: "Search the project's persistent memory. Returns relevant entries. Use BEFORE reading files. Pattern: recall → context_diff for recent changes → capture to save observations.",
|
|
130
136
|
inputSchema: {
|
|
131
137
|
query: z.string().describe("Text to search for"),
|
|
132
138
|
category: z.string().optional().default("").describe("Filter by category (empty = all)"),
|
|
@@ -256,8 +262,21 @@ server.registerTool(
|
|
|
256
262
|
const parts = l.trim().split("|")
|
|
257
263
|
const ttlInfo = parts[7] ? ` | TTL: ${parts[7]}` : ""
|
|
258
264
|
const qualityInfo = parts[10] ? ` | Q: ${parts[10]}` : ""
|
|
259
|
-
|
|
265
|
+
const accessInfo = parts[8] && parseInt(parts[8]) > 0 ? ` | accessed: ${parts[8]}x` : ""
|
|
266
|
+
return ` [${parts[1]}] ${parts[2]} (${parts[0]})${ttlInfo}${qualityInfo}${accessInfo}`
|
|
260
267
|
}),
|
|
268
|
+
"",
|
|
269
|
+
`Most accessed:`,
|
|
270
|
+
...lines
|
|
271
|
+
.filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
|
|
272
|
+
.map((l) => {
|
|
273
|
+
const parts = l.trim().split("|")
|
|
274
|
+
return { key: parts[2], accessed: parts.length > 8 ? parseInt(parts[8]) || 0 : 0, quality: parts[10] || "" }
|
|
275
|
+
})
|
|
276
|
+
.filter((e) => e.accessed > 0)
|
|
277
|
+
.sort((a, b) => b.accessed - a.accessed)
|
|
278
|
+
.slice(0, 5)
|
|
279
|
+
.map((e) => ` ${e.key}: ${e.accessed}x (Q: ${e.quality})`),
|
|
261
280
|
]
|
|
262
281
|
|
|
263
282
|
return { content: [{ type: "text" as const, text: stats.join("\n") }] }
|
|
@@ -357,7 +376,7 @@ server.registerTool(
|
|
|
357
376
|
"memory_smart_recall",
|
|
358
377
|
{
|
|
359
378
|
title: "Smart Recall (Unified)",
|
|
360
|
-
description: "Unified retrieval: combines BM25 + graph + decay + quality in a single call. Use at the START of each task to get all relevant memory context.",
|
|
379
|
+
description: "Unified retrieval: combines BM25 + graph + decay + quality in a single call. Use at the START of each task to get all relevant memory context. Then use context_diff for recent changes, context_focus for deep dives.",
|
|
361
380
|
inputSchema: {
|
|
362
381
|
intent: z.string().describe("Describe what you need to know (e.g. 'database schema for backend')"),
|
|
363
382
|
limit: z.number().optional().default(8).describe("Maximum entries to return"),
|
|
@@ -826,4 +845,551 @@ server.registerTool(
|
|
|
826
845
|
}
|
|
827
846
|
)
|
|
828
847
|
|
|
848
|
+
// ── memory_primer ─────────────────────────────────────────────────────
|
|
849
|
+
|
|
850
|
+
server.registerTool(
|
|
851
|
+
"memory_primer",
|
|
852
|
+
{
|
|
853
|
+
title: "System Primer",
|
|
854
|
+
description: "Generate a compact system primer: always-current knowledge map for auto-injection into agent context. Excludes private entries, shows top memories by importance, categories, and patterns. Use at session start or when context feels stale.",
|
|
855
|
+
inputSchema: {},
|
|
856
|
+
},
|
|
857
|
+
async () => {
|
|
858
|
+
const data = readMemory()
|
|
859
|
+
const { generateSystemPrimer } = await import("../lib/quality")
|
|
860
|
+
const primer = generateSystemPrimer(data)
|
|
861
|
+
return { content: [{ type: "text" as const, text: primer }] }
|
|
862
|
+
}
|
|
863
|
+
)
|
|
864
|
+
|
|
865
|
+
// ── memory_compress ────────────────────────────────────────────────────
|
|
866
|
+
|
|
867
|
+
server.registerTool(
|
|
868
|
+
"memory_compress",
|
|
869
|
+
{
|
|
870
|
+
title: "Compress Memory Entries",
|
|
871
|
+
description: "LLM-powered compression: select entries to compress into one concise entry. The agent (YOU) reads the entries, writes a compressed summary, then calls memory_remember to save it. Two-step dance: this tool provides context, you provide intelligence.",
|
|
872
|
+
inputSchema: {
|
|
873
|
+
query: z.string().optional().default("").describe("Search query to find entries to compress (e.g. 'auth bug fixes'). Empty = show lowest-quality entries."),
|
|
874
|
+
count: z.number().optional().default(3).describe("Number of entries to compress (2-10). Default: 3."),
|
|
875
|
+
category: z.string().optional().default("").describe("Filter by category (empty = all)."),
|
|
876
|
+
},
|
|
877
|
+
},
|
|
878
|
+
async ({ query, count, category }) => {
|
|
879
|
+
const data = readMemory()
|
|
880
|
+
const entries = parseEntries(data)
|
|
881
|
+
const clampedCount = Math.max(2, Math.min(10, count))
|
|
882
|
+
|
|
883
|
+
let candidates: typeof entries
|
|
884
|
+
|
|
885
|
+
if (query) {
|
|
886
|
+
// Find entries matching the query
|
|
887
|
+
const qTokens = tokenize(query)
|
|
888
|
+
const expandedTokens = expandSynonyms(qTokens)
|
|
889
|
+
candidates = entries
|
|
890
|
+
.filter((e) => {
|
|
891
|
+
if (category && e.category !== category) return false
|
|
892
|
+
if (e.ttl && isExpiredLocal(e.ttl)) return false
|
|
893
|
+
const text = normalize(`${e.key} ${e.content} ${e.tags.join(" ")}`)
|
|
894
|
+
return expandedTokens.some((t) => text.includes(t)) || qTokens.some((t) => text.includes(t))
|
|
895
|
+
})
|
|
896
|
+
.sort((a, b) => importance(b) - importance(a))
|
|
897
|
+
} else {
|
|
898
|
+
// Find lowest-quality entries (candidates for compression)
|
|
899
|
+
candidates = entries
|
|
900
|
+
.filter((e) => {
|
|
901
|
+
if (category && e.category !== category) return false
|
|
902
|
+
if (e.ttl && isExpiredLocal(e.ttl)) return false
|
|
903
|
+
return true
|
|
904
|
+
})
|
|
905
|
+
.sort((a, b) => importance(a) - importance(b))
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
const toCompress = candidates.slice(0, clampedCount)
|
|
909
|
+
|
|
910
|
+
if (toCompress.length < 2) {
|
|
911
|
+
return {
|
|
912
|
+
content: [{
|
|
913
|
+
type: "text" as const,
|
|
914
|
+
text: `Need at least 2 entries to compress. Found ${toCompress.length} matching entries.`
|
|
915
|
+
}],
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
// Build the compression prompt for the agent
|
|
920
|
+
const entryList = toCompress.map((e, i) =>
|
|
921
|
+
`${i + 1}. [${e.category}] ${e.key} (${e.id})\n ${e.content}\n Tags: ${e.tags.join(";")} | File: ${e.file} | Date: ${e.date}`
|
|
922
|
+
).join("\n\n")
|
|
923
|
+
|
|
924
|
+
const prompt = [
|
|
925
|
+
`📦 Compress ${toCompress.length} entries into 1 concise entry.`,
|
|
926
|
+
"",
|
|
927
|
+
"Entries to compress:",
|
|
928
|
+
entryList,
|
|
929
|
+
"",
|
|
930
|
+
"Instructions:",
|
|
931
|
+
"1. Read the entries above",
|
|
932
|
+
"2. Write a single concise summary that captures the essential information",
|
|
933
|
+
"3. Call memory_remember with:",
|
|
934
|
+
` - category: "${toCompress[0].category}" (or most appropriate)`,
|
|
935
|
+
" - key: a short kebab-case title (e.g. 'auth-bug-patterns')",
|
|
936
|
+
" - content: your compressed summary (1-3 sentences)",
|
|
937
|
+
" - tags: combine the most relevant tags from all entries",
|
|
938
|
+
` - file: "${toCompress.find((e) => e.file)?.file || ""}" (if applicable)`,
|
|
939
|
+
" - links: combine relevant links",
|
|
940
|
+
"",
|
|
941
|
+
"4. After saving, call memory_forget for each original entry ID:",
|
|
942
|
+
toCompress.map((e) => ` memory_forget(key: "${e.id}")`).join("\n"),
|
|
943
|
+
"",
|
|
944
|
+
"The compressed entry should be strictly better than the sum of its parts.",
|
|
945
|
+
].join("\n")
|
|
946
|
+
|
|
947
|
+
return { content: [{ type: "text" as const, text: prompt }] }
|
|
948
|
+
}
|
|
949
|
+
)
|
|
950
|
+
|
|
951
|
+
// ── memory_compress_all ────────────────────────────────────────────────
|
|
952
|
+
|
|
953
|
+
server.registerTool(
|
|
954
|
+
"memory_compress_all",
|
|
955
|
+
{
|
|
956
|
+
title: "Lazy Batch Compression",
|
|
957
|
+
description: "Compress all low-quality entries (no tags, low quality score) in one pass. Deterministic, no LLM — merges entries with similar content and removes empty/stale ones. Inspired by MemPalace's lazy compression.",
|
|
958
|
+
inputSchema: {
|
|
959
|
+
minQuality: z.number().optional().default(0.3).describe("Entries below this quality score are compression candidates (0-1). Default: 0.3."),
|
|
960
|
+
dryRun: z.boolean().optional().default(false).describe("If true, show what would be compressed without making changes."),
|
|
961
|
+
},
|
|
962
|
+
},
|
|
963
|
+
async ({ minQuality, dryRun }) => {
|
|
964
|
+
const data = readMemory()
|
|
965
|
+
const lines = data.split("\n")
|
|
966
|
+
const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
|
|
967
|
+
if (headerIdx === -1) {
|
|
968
|
+
return { content: [{ type: "text" as const, text: "No entries in memory." }] }
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
|
|
972
|
+
|
|
973
|
+
// Find compression candidates: low quality, no tags, or stale
|
|
974
|
+
const candidates: { idx: number; line: string; quality: number; key: string }[] = []
|
|
975
|
+
for (let i = 0; i < entryLines.length; i++) {
|
|
976
|
+
const line = entryLines[i].trim()
|
|
977
|
+
const parts = line.split("|")
|
|
978
|
+
if (parts.length < 11) continue
|
|
979
|
+
const quality = parseFloat(parts[10]) || 0
|
|
980
|
+
const tags = parts[5] || ""
|
|
981
|
+
const key = parts[2]
|
|
982
|
+
const content = parts[3] || ""
|
|
983
|
+
|
|
984
|
+
// Candidates: low quality OR no tags OR very short content
|
|
985
|
+
const isCandidate = quality < minQuality || !tags || content.length < 20
|
|
986
|
+
if (isCandidate) {
|
|
987
|
+
candidates.push({ idx: i, line, quality, key })
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
if (candidates.length === 0) {
|
|
992
|
+
return {
|
|
993
|
+
content: [{
|
|
994
|
+
type: "text" as const,
|
|
995
|
+
text: `✅ No compression candidates found. All entries have quality >= ${minQuality} or have tags.`
|
|
996
|
+
}],
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
// Group candidates by category for potential merging
|
|
1001
|
+
const byCategory = new Map<string, typeof candidates>()
|
|
1002
|
+
for (const c of candidates) {
|
|
1003
|
+
const parts = c.line.split("|")
|
|
1004
|
+
const cat = parts[1] || "unknown"
|
|
1005
|
+
if (!byCategory.has(cat)) byCategory.set(cat, [])
|
|
1006
|
+
byCategory.get(cat)!.push(c)
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
const sections: string[] = [
|
|
1010
|
+
`📦 Compression candidates: ${candidates.length} entries below quality ${minQuality}`,
|
|
1011
|
+
"",
|
|
1012
|
+
"By category:",
|
|
1013
|
+
]
|
|
1014
|
+
|
|
1015
|
+
for (const [cat, items] of byCategory) {
|
|
1016
|
+
sections.push(` ${cat}: ${items.length} entries`)
|
|
1017
|
+
for (const item of items.slice(0, 3)) {
|
|
1018
|
+
const parts = item.line.split("|")
|
|
1019
|
+
sections.push(` - ${item.key} (Q: ${item.quality.toFixed(2)}) — ${(parts[3] || "").slice(0, 60)}`)
|
|
1020
|
+
}
|
|
1021
|
+
if (items.length > 3) {
|
|
1022
|
+
sections.push(` ... and ${items.length - 3} more`)
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
if (dryRun) {
|
|
1027
|
+
sections.push("", "🔍 Dry run — no changes made. Use dryRun: false to compress.")
|
|
1028
|
+
return { content: [{ type: "text" as const, text: sections.join("\n") }] }
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
// Remove candidates (conservative: just remove the lowest quality ones)
|
|
1032
|
+
// Don't auto-merge — let the agent decide via memory_compress
|
|
1033
|
+
const removeKeys = new Set(candidates.map((c) => c.key))
|
|
1034
|
+
const kept = entryLines.filter((l) => {
|
|
1035
|
+
const parts = l.trim().split("|")
|
|
1036
|
+
return !removeKeys.has(parts[2])
|
|
1037
|
+
})
|
|
1038
|
+
|
|
1039
|
+
const match = lines[headerIdx].match(/\[(\d+)\|/)
|
|
1040
|
+
const count = match ? parseInt(match[1]) : 0
|
|
1041
|
+
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${kept.length}|`)
|
|
1042
|
+
lines.splice(headerIdx + 1, entryLines.length, ...kept.map((l) => ` ${l.trim()}`))
|
|
1043
|
+
writeMemory(lines.join("\n"))
|
|
1044
|
+
|
|
1045
|
+
sections.push("", `🗑️ Removed ${candidates.length} low-quality entries. ${kept.length} entries remaining.`)
|
|
1046
|
+
sections.push("💡 Use memory_compress to merge related entries before removing them.")
|
|
1047
|
+
|
|
1048
|
+
return { content: [{ type: "text" as const, text: sections.join("\n") }] }
|
|
1049
|
+
}
|
|
1050
|
+
)
|
|
1051
|
+
|
|
1052
|
+
// ── memory_export_gist ─────────────────────────────────────────────────
|
|
1053
|
+
|
|
1054
|
+
server.registerTool(
|
|
1055
|
+
"memory_export_gist",
|
|
1056
|
+
{
|
|
1057
|
+
title: "Export to GitHub Gist",
|
|
1058
|
+
description: "Export memory to a private GitHub Gist for cloud sync. Requires GITHUB_TOKEN env var. Zero deps — uses Node's built-in fetch().",
|
|
1059
|
+
inputSchema: {
|
|
1060
|
+
description: z.string().optional().default("").describe("Optional description for the Gist."),
|
|
1061
|
+
},
|
|
1062
|
+
},
|
|
1063
|
+
async ({ description }) => {
|
|
1064
|
+
const token = process.env.GITHUB_TOKEN
|
|
1065
|
+
if (!token) {
|
|
1066
|
+
return {
|
|
1067
|
+
content: [{
|
|
1068
|
+
type: "text" as const,
|
|
1069
|
+
text: "❌ GITHUB_TOKEN not set. Add it to your environment:\n export GITHUB_TOKEN=ghp_your_token_here"
|
|
1070
|
+
}],
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
if (!existsSync(MEMORY_FILE)) {
|
|
1075
|
+
return { content: [{ type: "text" as const, text: "No memory file to export." }] }
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
const data = readFileSync(MEMORY_FILE, "utf-8")
|
|
1079
|
+
const desc = description || `toon-memory backup ${new Date().toISOString().split("T")[0]}`
|
|
1080
|
+
|
|
1081
|
+
try {
|
|
1082
|
+
const resp = await fetch("https://api.github.com/gists", {
|
|
1083
|
+
method: "POST",
|
|
1084
|
+
headers: {
|
|
1085
|
+
Authorization: `Bearer ${token}`,
|
|
1086
|
+
"Content-Type": "application/json",
|
|
1087
|
+
Accept: "application/vnd.github.v3+json",
|
|
1088
|
+
},
|
|
1089
|
+
body: JSON.stringify({
|
|
1090
|
+
description: desc,
|
|
1091
|
+
public: false,
|
|
1092
|
+
files: {
|
|
1093
|
+
"data.toon": { content: data },
|
|
1094
|
+
},
|
|
1095
|
+
}),
|
|
1096
|
+
})
|
|
1097
|
+
|
|
1098
|
+
if (!resp.ok) {
|
|
1099
|
+
const err = await resp.text()
|
|
1100
|
+
return { content: [{ type: "text" as const, text: `❌ GitHub API error (${resp.status}): ${err}` }] }
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
const gist = await resp.json() as { id: string; html_url: string; created_at: string }
|
|
1104
|
+
return {
|
|
1105
|
+
content: [{
|
|
1106
|
+
type: "text" as const,
|
|
1107
|
+
text: `📤 Memory exported to Gist\nID: ${gist.id}\nURL: ${gist.html_url}\n\nTo import later: memory_import_gist(gist_id: "${gist.id}")`
|
|
1108
|
+
}],
|
|
1109
|
+
}
|
|
1110
|
+
} catch (err) {
|
|
1111
|
+
return { content: [{ type: "text" as const, text: `❌ Failed to export: ${err}` }] }
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
)
|
|
1115
|
+
|
|
1116
|
+
// ── memory_import_gist ─────────────────────────────────────────────────
|
|
1117
|
+
|
|
1118
|
+
server.registerTool(
|
|
1119
|
+
"memory_import_gist",
|
|
1120
|
+
{
|
|
1121
|
+
title: "Import from GitHub Gist",
|
|
1122
|
+
description: "Import memory from a GitHub Gist. Merges entries (keeps newer dates, combines tags). Requires GITHUB_TOKEN env var.",
|
|
1123
|
+
inputSchema: {
|
|
1124
|
+
gist_id: z.string().describe("GitHub Gist ID or full URL (https://gist.github.com/user/id)."),
|
|
1125
|
+
merge: z.boolean().optional().default(true).describe("If true, merge with existing memory. If false, replace entirely."),
|
|
1126
|
+
},
|
|
1127
|
+
},
|
|
1128
|
+
async ({ gist_id, merge }) => {
|
|
1129
|
+
const token = process.env.GITHUB_TOKEN
|
|
1130
|
+
if (!token) {
|
|
1131
|
+
return {
|
|
1132
|
+
content: [{
|
|
1133
|
+
type: "text" as const,
|
|
1134
|
+
text: "❌ GITHUB_TOKEN not set. Add it to your environment:\n export GITHUB_TOKEN=ghp_your_token_here"
|
|
1135
|
+
}],
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
// Extract gist ID from URL if needed
|
|
1140
|
+
const idMatch = gist_id.match(/\/([a-f0-9]+)$/i) || [null, gist_id]
|
|
1141
|
+
const id = idMatch[1] || gist_id
|
|
1142
|
+
|
|
1143
|
+
try {
|
|
1144
|
+
const resp = await fetch(`https://api.github.com/gists/${id}`, {
|
|
1145
|
+
headers: {
|
|
1146
|
+
Authorization: `Bearer ${token}`,
|
|
1147
|
+
Accept: "application/vnd.github.v3+json",
|
|
1148
|
+
},
|
|
1149
|
+
})
|
|
1150
|
+
|
|
1151
|
+
if (!resp.ok) {
|
|
1152
|
+
const err = await resp.text()
|
|
1153
|
+
return { content: [{ type: "text" as const, text: `❌ GitHub API error (${resp.status}): ${err}` }] }
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
const gist = await resp.json() as { files: Record<string, { content: string }> }
|
|
1157
|
+
const file = gist.files["data.toon"]
|
|
1158
|
+
if (!file) {
|
|
1159
|
+
return { content: [{ type: "text" as const, text: "❌ Gist does not contain data.toon file." }] }
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
const remoteData = file.content
|
|
1163
|
+
|
|
1164
|
+
if (!merge) {
|
|
1165
|
+
// Replace entirely
|
|
1166
|
+
safeWrite(MEMORY_FILE, remoteData)
|
|
1167
|
+
const entries = parseEntries(remoteData)
|
|
1168
|
+
return {
|
|
1169
|
+
content: [{
|
|
1170
|
+
type: "text" as const,
|
|
1171
|
+
text: `📥 Memory replaced from Gist (${entries.length} entries).`
|
|
1172
|
+
}],
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
// Merge mode: combine entries from both sources
|
|
1177
|
+
const localData = existsSync(MEMORY_FILE) ? readFileSync(MEMORY_FILE, "utf-8") : "version: 1\nentries[0|]\n"
|
|
1178
|
+
const localEntries = parseEntries(localData)
|
|
1179
|
+
const remoteEntries = parseEntries(remoteData)
|
|
1180
|
+
|
|
1181
|
+
const localByKey = new Map(localEntries.map((e) => [e.key, e]))
|
|
1182
|
+
let added = 0
|
|
1183
|
+
let updated = 0
|
|
1184
|
+
|
|
1185
|
+
for (const remote of remoteEntries) {
|
|
1186
|
+
const existing = localByKey.get(remote.key)
|
|
1187
|
+
if (!existing) {
|
|
1188
|
+
// New entry from remote
|
|
1189
|
+
localByKey.set(remote.key, remote)
|
|
1190
|
+
added++
|
|
1191
|
+
} else {
|
|
1192
|
+
// Merge: keep newer date, combine tags, take max quality
|
|
1193
|
+
const mergedTags = [...new Set([...existing.tags, ...remote.tags])].join(";")
|
|
1194
|
+
const mergedLinks = [...new Set([...existing.links, ...remote.links])].join(" ")
|
|
1195
|
+
const newerDate = remote.date > existing.date ? remote.date : existing.date
|
|
1196
|
+
const merged = {
|
|
1197
|
+
...existing,
|
|
1198
|
+
tags: mergedTags.split(";").filter(Boolean),
|
|
1199
|
+
links: mergedLinks.split(/[\s;]+/).filter(Boolean),
|
|
1200
|
+
date: newerDate,
|
|
1201
|
+
content: remote.content.length > existing.content.length ? remote.content : existing.content,
|
|
1202
|
+
}
|
|
1203
|
+
localByKey.set(remote.key, merged)
|
|
1204
|
+
updated++
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
// Rebuild the file
|
|
1209
|
+
const entries = [...localByKey.values()]
|
|
1210
|
+
const lines = [
|
|
1211
|
+
"version: 1",
|
|
1212
|
+
`[${entries.length}|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence|lastAccessed}:`,
|
|
1213
|
+
...entries.map((e) => {
|
|
1214
|
+
const tags = e.tags.join(";")
|
|
1215
|
+
const links = e.links.join(" ")
|
|
1216
|
+
const q = qualityScore(tags, links, e.content, e.date, e.accessed, e.lastAccessed)
|
|
1217
|
+
return ` ${e.id}|${e.category}|${e.key}|${e.content}|${e.file}|${tags}|${e.date}|${e.ttl}|${e.accessed}|${links}|${q.toFixed(2)}|1|${e.lastAccessed}`
|
|
1218
|
+
}),
|
|
1219
|
+
]
|
|
1220
|
+
safeWrite(MEMORY_FILE, lines.join("\n"))
|
|
1221
|
+
|
|
1222
|
+
return {
|
|
1223
|
+
content: [{
|
|
1224
|
+
type: "text" as const,
|
|
1225
|
+
text: `📥 Memory merged from Gist\n Added: ${added} new entries\n Updated: ${updated} existing entries\n Total: ${entries.length} entries`
|
|
1226
|
+
}],
|
|
1227
|
+
}
|
|
1228
|
+
} catch (err) {
|
|
1229
|
+
return { content: [{ type: "text" as const, text: `❌ Failed to import: ${err}` }] }
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
)
|
|
1233
|
+
|
|
1234
|
+
// ── memory_merge_sessions ──────────────────────────────────────────────
|
|
1235
|
+
|
|
1236
|
+
server.registerTool(
|
|
1237
|
+
"memory_merge_sessions",
|
|
1238
|
+
{
|
|
1239
|
+
title: "Merge Session Observations",
|
|
1240
|
+
description: "Merge observations from multiple sessions/branches into a consolidated view. Deduplicates and suggests entries to promote to memory. Inspired by Hindsight's multi-agent session merging.",
|
|
1241
|
+
inputSchema: {
|
|
1242
|
+
since: z.string().optional().default("24h").describe("Time window to merge (e.g. '24h', '7d', '2026-07-20'). Default: 24h."),
|
|
1243
|
+
promote: z.boolean().optional().default(false).describe("If true, auto-promote unique observations to memory entries."),
|
|
1244
|
+
},
|
|
1245
|
+
},
|
|
1246
|
+
async ({ since, promote }) => {
|
|
1247
|
+
const { listSessions, pruneSessions } = await import("../lib/sessions")
|
|
1248
|
+
pruneSessions()
|
|
1249
|
+
const sessions = listSessions()
|
|
1250
|
+
|
|
1251
|
+
// Filter sessions by time window
|
|
1252
|
+
const sinceMs = parseRelativeMs(since)
|
|
1253
|
+
const cutoff = Date.now() - sinceMs
|
|
1254
|
+
const recentSessions = sessions.filter((s) => new Date(s.lastSeen).getTime() >= cutoff)
|
|
1255
|
+
|
|
1256
|
+
if (recentSessions.length === 0) {
|
|
1257
|
+
return { content: [{ type: "text" as const, text: `No sessions found in the last ${since}.` }] }
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
// Collect all files touched across sessions
|
|
1261
|
+
const allFiles = new Map<string, Array<{ session: string; agent: string; branch: string; touched: string }>>()
|
|
1262
|
+
for (const s of recentSessions) {
|
|
1263
|
+
for (const [file, touched] of Object.entries(s.files)) {
|
|
1264
|
+
if (!allFiles.has(file)) allFiles.set(file, [])
|
|
1265
|
+
allFiles.get(file)!.push({ session: s.id, agent: s.agent, branch: s.branch, touched })
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
// Find files touched by multiple sessions (potential merge points)
|
|
1270
|
+
const sharedFiles = [...allFiles.entries()]
|
|
1271
|
+
.filter(([_, sessions]) => sessions.length >= 2)
|
|
1272
|
+
.sort((a, b) => b[1].length - a[1].length)
|
|
1273
|
+
|
|
1274
|
+
// Read observations for these sessions
|
|
1275
|
+
let observations: Array<{ ts: string; session: string; agent: string; branch: string; tool: string; file: string; summary: string }> = []
|
|
1276
|
+
if (existsSync(OBSERVATIONS_FILE)) {
|
|
1277
|
+
const data = readFileSync(OBSERVATIONS_FILE, "utf-8")
|
|
1278
|
+
const sessionIds = new Set(recentSessions.map((s) => s.id))
|
|
1279
|
+
observations = data.split("\n")
|
|
1280
|
+
.filter((l) => l.startsWith(" ") && l.includes("|"))
|
|
1281
|
+
.map((l) => {
|
|
1282
|
+
const p = l.trim().split("|")
|
|
1283
|
+
return { ts: p[0] || "", session: p[1] || "", agent: p[2] || "", branch: p[3] || "", tool: p[4] || "", file: p[6] || "", summary: p[7] || "" }
|
|
1284
|
+
})
|
|
1285
|
+
.filter((o) => sessionIds.has(o.session))
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
// Deduplicate observations by tool+summary hash
|
|
1289
|
+
const seen = new Set<string>()
|
|
1290
|
+
const uniqueObs = observations.filter((o) => {
|
|
1291
|
+
const key = `${o.tool}|${o.summary}`
|
|
1292
|
+
if (seen.has(key)) return false
|
|
1293
|
+
seen.add(key)
|
|
1294
|
+
return true
|
|
1295
|
+
})
|
|
1296
|
+
|
|
1297
|
+
// Build output
|
|
1298
|
+
const sections: string[] = [
|
|
1299
|
+
`🔀 Session Merge Report (${recentSessions.length} sessions, last ${since})`,
|
|
1300
|
+
"",
|
|
1301
|
+
`Sessions:`,
|
|
1302
|
+
...recentSessions.map((s) => {
|
|
1303
|
+
const mins = Math.max(0, Math.round((Date.now() - new Date(s.lastSeen).getTime()) / 60000))
|
|
1304
|
+
const files = Object.keys(s.files).length
|
|
1305
|
+
return ` ${s.agent}@${s.branch} (${s.id}) — ${mins}min ago, ${files} files`
|
|
1306
|
+
}),
|
|
1307
|
+
]
|
|
1308
|
+
|
|
1309
|
+
if (sharedFiles.length > 0) {
|
|
1310
|
+
sections.push("", `Shared files (${sharedFiles.length}):`)
|
|
1311
|
+
for (const [file, sess] of sharedFiles.slice(0, 10)) {
|
|
1312
|
+
const who = sess.map((s) => `${s.agent}@${s.branch}`).join(", ")
|
|
1313
|
+
sections.push(` ${file} ↔ ${who}`)
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
if (uniqueObs.length > 0) {
|
|
1318
|
+
sections.push("", `Unique observations (${uniqueObs.length} of ${observations.length} total):`)
|
|
1319
|
+
for (const o of uniqueObs.slice(0, 15)) {
|
|
1320
|
+
sections.push(` [${o.tool}] ${o.agent}@${o.branch}: ${o.summary.slice(0, 100)}`)
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
// Auto-promote mode
|
|
1325
|
+
if (promote && uniqueObs.length > 0) {
|
|
1326
|
+
const data = readMemory()
|
|
1327
|
+
const entries = parseEntries(data)
|
|
1328
|
+
const existingKeys = new Set(entries.map((e) => e.key))
|
|
1329
|
+
let promoted = 0
|
|
1330
|
+
|
|
1331
|
+
for (const obs of uniqueObs.slice(0, 5)) {
|
|
1332
|
+
// Generate a key from the observation summary
|
|
1333
|
+
const key = obs.summary
|
|
1334
|
+
.toLowerCase()
|
|
1335
|
+
.replace(/[^a-z0-9\s]/g, "")
|
|
1336
|
+
.split(/\s+/)
|
|
1337
|
+
.slice(0, 4)
|
|
1338
|
+
.join("-")
|
|
1339
|
+
.slice(0, 40)
|
|
1340
|
+
|
|
1341
|
+
if (!key || existingKeys.has(key)) continue
|
|
1342
|
+
|
|
1343
|
+
// Use memory_remember logic inline
|
|
1344
|
+
const newId = generateId()
|
|
1345
|
+
const date = new Date().toISOString().split("T")[0]
|
|
1346
|
+
const content = obs.summary.slice(0, 500)
|
|
1347
|
+
const file = obs.file || ""
|
|
1348
|
+
const tags = `session-merge;${obs.agent};${obs.branch}`
|
|
1349
|
+
const quality = qualityScore(tags, "", content, date)
|
|
1350
|
+
const entry = `${newId}|knowledge|${key}|${content}|${file}|${tags}|${date}||0||${quality.toFixed(2)}|1|`
|
|
1351
|
+
|
|
1352
|
+
// Append to memory
|
|
1353
|
+
const lines = data.split("\n")
|
|
1354
|
+
let headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
|
|
1355
|
+
if (headerIdx === -1) {
|
|
1356
|
+
lines.push(`[0|]`)
|
|
1357
|
+
headerIdx = lines.length - 1
|
|
1358
|
+
}
|
|
1359
|
+
const match = lines[headerIdx].match(/\[(\d+)\|/)
|
|
1360
|
+
const count = match ? parseInt(match[1]) : 0
|
|
1361
|
+
lines.splice(headerIdx + 1, 0, ` ${entry}`)
|
|
1362
|
+
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`)
|
|
1363
|
+
writeMemory(lines.join("\n"))
|
|
1364
|
+
existingKeys.add(key)
|
|
1365
|
+
promoted++
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
sections.push("", `📤 Promoted ${promoted} observations to memory.`)
|
|
1369
|
+
} else if (uniqueObs.length > 0) {
|
|
1370
|
+
sections.push("", `💡 Use 'promote: true' to auto-save unique observations as memory entries.`)
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
return { content: [{ type: "text" as const, text: sections.join("\n") }] }
|
|
1374
|
+
}
|
|
1375
|
+
)
|
|
1376
|
+
|
|
829
1377
|
} // end registerTools
|
|
1378
|
+
|
|
1379
|
+
/** Parse relative time string to milliseconds. */
|
|
1380
|
+
function parseRelativeMs(s: string): number {
|
|
1381
|
+
const match = s.match(/^(\d+)(h|d|m)$/i)
|
|
1382
|
+
if (!match) {
|
|
1383
|
+
// Try parsing as date
|
|
1384
|
+
const d = new Date(s)
|
|
1385
|
+
if (!isNaN(d.getTime())) return Date.now() - d.getTime()
|
|
1386
|
+
return 24 * 60 * 60 * 1000 // default 24h
|
|
1387
|
+
}
|
|
1388
|
+
const n = parseInt(match[1])
|
|
1389
|
+
switch (match[2].toLowerCase()) {
|
|
1390
|
+
case "m": return n * 60 * 1000
|
|
1391
|
+
case "h": return n * 60 * 60 * 1000
|
|
1392
|
+
case "d": return n * 24 * 60 * 60 * 1000
|
|
1393
|
+
default: return 24 * 60 * 60 * 1000
|
|
1394
|
+
}
|
|
1395
|
+
}
|