toon-memory 3.0.0 → 3.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.de.md +7 -5
- package/README.es.md +7 -5
- package/README.fr.md +7 -5
- package/README.ja.md +7 -5
- package/README.ko.md +7 -5
- package/README.md +7 -5
- package/README.pt-br.md +7 -5
- package/README.zh.md +7 -5
- package/dist/cli/setup.js +133 -22
- package/mcp/server.js +159 -2
- package/package.json +4 -2
- package/src/cli/agents.ts +10 -9
- package/src/cli/commands.ts +1 -1
- package/src/cli/config-writer.ts +90 -3
- package/src/cli/hooks.ts +2 -2
- package/src/cli/opencode-plugin.ts +58 -11
- package/src/cli/types.ts +4 -2
- package/src/lib/quality.ts +18 -1
- package/src/mcp/tools.ts +177 -1
|
@@ -5,24 +5,47 @@ import { projectRoot } from "./constants"
|
|
|
5
5
|
import { dumpMemoryMarkdown } from "./memory"
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
|
-
* OpenCode plugin source with
|
|
9
|
-
* hooks via plugins (not a top-level `hooks` config key), so `init`
|
|
10
|
-
* file into `.opencode/plugins/`.
|
|
8
|
+
* OpenCode plugin source with INTELLIGENT memory injection. OpenCode 1.17+
|
|
9
|
+
* delivers hooks via plugins (not a top-level `hooks` config key), so `init`
|
|
10
|
+
* writes this file into `.opencode/plugins/`.
|
|
11
|
+
*
|
|
12
|
+
* Two injection modes:
|
|
13
|
+
* 1. Session start → full dump (seeded in instructions/)
|
|
14
|
+
* 2. Tool execution → targeted recall by file path (injected via output.context)
|
|
11
15
|
*/
|
|
12
16
|
export function opencodePluginContent(): string {
|
|
13
17
|
return `import * as fs from "fs"
|
|
18
|
+
import * as path from "path"
|
|
14
19
|
|
|
15
20
|
export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
16
21
|
const root = worktree || directory
|
|
17
22
|
const INS = root + "/.opencode/instructions"
|
|
18
23
|
const OUT = INS + "/memory-autoload.md"
|
|
24
|
+
|
|
19
25
|
const dump = async () => {
|
|
20
26
|
return await $\`npx -y toon-memory dump\`.cwd(root).text()
|
|
21
27
|
}
|
|
28
|
+
|
|
29
|
+
const recall = async (query) => {
|
|
30
|
+
try {
|
|
31
|
+
const result = await $\`npx -y toon-memory mcp\`.cwd(root)
|
|
32
|
+
.stdin(JSON.stringify({
|
|
33
|
+
jsonrpc: "2.0",
|
|
34
|
+
id: 1,
|
|
35
|
+
method: "tools/call",
|
|
36
|
+
params: { name: "memory_recall", arguments: { query, mode: "flat", compact: true } }
|
|
37
|
+
}))
|
|
38
|
+
.text()
|
|
39
|
+
const parsed = JSON.parse(result)
|
|
40
|
+
return parsed?.result?.content?.[0]?.text || ""
|
|
41
|
+
} catch { return "" }
|
|
42
|
+
}
|
|
43
|
+
|
|
22
44
|
const write = (text) => {
|
|
23
45
|
fs.mkdirSync(INS, { recursive: true })
|
|
24
46
|
fs.writeFileSync(OUT, text)
|
|
25
47
|
}
|
|
48
|
+
|
|
26
49
|
return {
|
|
27
50
|
"session.created": async () => {
|
|
28
51
|
try {
|
|
@@ -37,15 +60,39 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
37
60
|
} catch {}
|
|
38
61
|
},
|
|
39
62
|
"tool.execute.after": async (input) => {
|
|
40
|
-
|
|
41
|
-
|
|
63
|
+
// Intelligent auto-loading: extract file path from tool result,
|
|
64
|
+
// recall only memory relevant to that file, inject as context.
|
|
42
65
|
try {
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
66
|
+
const toolName = input?.tool || ""
|
|
67
|
+
const args = input?.args || {}
|
|
68
|
+
|
|
69
|
+
// Extract file path from tool arguments or output
|
|
70
|
+
let filePath = ""
|
|
71
|
+
if (args.file) filePath = args.file
|
|
72
|
+
else if (args.path) filePath = args.path
|
|
73
|
+
else if (args.filePath) filePath = args.filePath
|
|
74
|
+
|
|
75
|
+
// Also try to extract from tool output text
|
|
76
|
+
if (!filePath && input?.output) {
|
|
77
|
+
const outputText = typeof input.output === "string" ? input.output : ""
|
|
78
|
+
const fileMatch = outputText.match(/(?:file|path|source):\s*([\\w/.\\-]+)/i)
|
|
79
|
+
if (fileMatch) filePath = fileMatch[1]
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (!filePath) return
|
|
83
|
+
|
|
84
|
+
// Build recall query from file path components
|
|
85
|
+
const basename = path.basename(filePath, path.extname(filePath))
|
|
86
|
+
const dirParts = path.dirname(filePath).split(path.sep).filter(Boolean)
|
|
87
|
+
const query = [basename, ...dirParts.slice(-2)].join(" ")
|
|
88
|
+
|
|
89
|
+
const text = await recall(query)
|
|
90
|
+
if (!text || text.includes("(empty)") || text.includes("No results")) return
|
|
91
|
+
|
|
92
|
+
// Inject as context for the next agent turn
|
|
93
|
+
if (typeof input?.setContext === "function") {
|
|
94
|
+
input.setContext("toon-memory:" + filePath, text)
|
|
95
|
+
}
|
|
49
96
|
} catch {}
|
|
50
97
|
},
|
|
51
98
|
}
|
package/src/cli/types.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
/** Config format: "json" | "toml" | "jsonc" | "none" (instructions only) */
|
|
2
|
-
export type AgentFormat = "json" | "toml" | "jsonc" | "none"
|
|
1
|
+
/** Config format: "json" | "toml" | "jsonc" | "continue" | "openclaw" | "none" (instructions only) */
|
|
2
|
+
export type AgentFormat = "json" | "toml" | "jsonc" | "continue" | "openclaw" | "none"
|
|
3
3
|
|
|
4
4
|
/** Supported AI coding agent configuration */
|
|
5
5
|
export interface Agent {
|
|
6
6
|
name: string
|
|
7
7
|
global?: string
|
|
8
8
|
local?: string
|
|
9
|
+
/** Separate path for hook registration (when it differs from the MCP config path) */
|
|
10
|
+
hookPath?: string
|
|
9
11
|
mcpKey: string
|
|
10
12
|
format: AgentFormat
|
|
11
13
|
needsHooks: boolean
|
package/src/lib/quality.ts
CHANGED
|
@@ -24,6 +24,7 @@ import { fuzzyMatch } from "./fuzzy"
|
|
|
24
24
|
* - Specificity (0.1 max): unique word ratio
|
|
25
25
|
* - Access frequency (0.15 max): how often recalled
|
|
26
26
|
* - Access recency (0.1 max): how recently accessed
|
|
27
|
+
* - Staleness decay: entries not accessed in 30+ days lose up to 0.2
|
|
27
28
|
*/
|
|
28
29
|
export function qualityScore(
|
|
29
30
|
tags: string,
|
|
@@ -68,7 +69,23 @@ export function qualityScore(
|
|
|
68
69
|
else if (daysSinceAccess < 7) score += 0.07
|
|
69
70
|
else if (daysSinceAccess < 30) score += 0.03
|
|
70
71
|
}
|
|
71
|
-
|
|
72
|
+
|
|
73
|
+
// Staleness decay: penalize entries that haven't been accessed recently
|
|
74
|
+
// and were created more than 30 days ago. Decay ramps up over time.
|
|
75
|
+
if (date) {
|
|
76
|
+
const daysSinceCreation = (Date.now() - new Date(`${date}T00:00:00`).getTime()) / 86400000
|
|
77
|
+
const daysSinceLastAccess = lastAccessed
|
|
78
|
+
? (Date.now() - new Date(lastAccessed).getTime()) / 86400000
|
|
79
|
+
: daysSinceCreation
|
|
80
|
+
|
|
81
|
+
// Only decay if entry is old AND hasn't been accessed recently
|
|
82
|
+
if (daysSinceCreation > 30 && daysSinceLastAccess > 30) {
|
|
83
|
+
const staleness = Math.min(1, (daysSinceLastAccess - 30) / 90) // 0→1 over 30-120 days
|
|
84
|
+
score -= staleness * 0.2 // Max penalty: -0.2
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return Math.max(0, Math.min(1, score))
|
|
72
89
|
}
|
|
73
90
|
|
|
74
91
|
/**
|
package/src/mcp/tools.ts
CHANGED
|
@@ -11,7 +11,7 @@ import { archiveOldEntries } from "./archive"
|
|
|
11
11
|
import { consolidateEntries } from "./consolidation"
|
|
12
12
|
import { readUnderLock } from "../lib/lock"
|
|
13
13
|
import { encrypt, decrypt } from "./crypto"
|
|
14
|
-
import { graphRecallDetailed, renderCompact, parseEntries } from "../lib/graph"
|
|
14
|
+
import { graphRecallDetailed, renderCompact, parseEntries, buildGraph } from "../lib/graph"
|
|
15
15
|
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"
|
|
@@ -1374,6 +1374,182 @@ server.registerTool(
|
|
|
1374
1374
|
}
|
|
1375
1375
|
)
|
|
1376
1376
|
|
|
1377
|
+
// ── memory_merge_similar ─────────────────────────────────────────────
|
|
1378
|
+
|
|
1379
|
+
server.registerTool(
|
|
1380
|
+
"memory_merge_similar",
|
|
1381
|
+
{
|
|
1382
|
+
title: "Merge Similar Entries",
|
|
1383
|
+
description: "Find entries with overlapping content (>50% word similarity) and merge them. Deterministic, no LLM. Keeps the longer content and combines tags.",
|
|
1384
|
+
inputSchema: {
|
|
1385
|
+
dryRun: z.boolean().optional().default(false).describe("If true, show what would be merged without making changes."),
|
|
1386
|
+
},
|
|
1387
|
+
},
|
|
1388
|
+
async ({ dryRun }) => {
|
|
1389
|
+
const data = readMemory()
|
|
1390
|
+
const entries = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
|
|
1391
|
+
|
|
1392
|
+
if (entries.length < 2) {
|
|
1393
|
+
return { content: [{ type: "text" as const, text: "✅ Not enough entries to compress." }] }
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
// Parse entries and compute similarity
|
|
1397
|
+
const parsed = entries.map((line) => {
|
|
1398
|
+
const parts = line.trim().split("|")
|
|
1399
|
+
if (parts.length < 7) return null
|
|
1400
|
+
const [id, cat, key, content, file, tags, date, ttl, accessedRaw] = parts
|
|
1401
|
+
const words = new Set(normalize(`${key} ${content} ${tags}`).split(" ").filter(Boolean))
|
|
1402
|
+
return { id, cat, key, content, file, tags, date, ttl, accessed: parseInt(accessedRaw) || 0, words, line }
|
|
1403
|
+
}).filter(Boolean) as Array<{ id: string; cat: string; key: string; content: string; file: string; tags: string; date: string; ttl: string; accessed: number; words: Set<string>; line: string }>
|
|
1404
|
+
|
|
1405
|
+
// Find pairs with >50% word overlap (Jaccard similarity)
|
|
1406
|
+
const mergePairs: Array<{ a: number; b: number; similarity: number }> = []
|
|
1407
|
+
for (let i = 0; i < parsed.length; i++) {
|
|
1408
|
+
for (let j = i + 1; j < parsed.length; j++) {
|
|
1409
|
+
const a = parsed[i], b = parsed[j]
|
|
1410
|
+
const intersection = new Set([...a.words].filter((w) => b.words.has(w)))
|
|
1411
|
+
const union = new Set([...a.words, ...b.words])
|
|
1412
|
+
const similarity = union.size > 0 ? intersection.size / union.size : 0
|
|
1413
|
+
if (similarity > 0.5) {
|
|
1414
|
+
mergePairs.push({ a: i, b: j, similarity })
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
if (mergePairs.length === 0) {
|
|
1420
|
+
return { content: [{ type: "text" as const, text: "✅ No similar entries found to merge." }] }
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
// Sort by similarity (highest first) and merge greedily
|
|
1424
|
+
mergePairs.sort((x, y) => y.similarity - x.similarity)
|
|
1425
|
+
const merged = new Set<number>()
|
|
1426
|
+
const mergeActions: string[] = []
|
|
1427
|
+
|
|
1428
|
+
for (const pair of mergePairs) {
|
|
1429
|
+
if (merged.has(pair.a) || merged.has(pair.b)) continue
|
|
1430
|
+
const a = parsed[pair.a], b = parsed[pair.b]
|
|
1431
|
+
|
|
1432
|
+
// Merge: keep the entry with more content, combine tags
|
|
1433
|
+
const mergedTags = [...new Set([...a.tags.split(";"), ...b.tags.split(";")])].filter(Boolean).join(";")
|
|
1434
|
+
const longer = a.content.length >= b.content.length ? a : b
|
|
1435
|
+
const shorter = a.content.length < b.content.length ? a : b
|
|
1436
|
+
const newContent = longer.content
|
|
1437
|
+
const newDate = a.date > b.date ? a.date : b.date
|
|
1438
|
+
const newAccessed = a.accessed + b.accessed
|
|
1439
|
+
|
|
1440
|
+
mergeActions.push(` [${longer.cat}] ${longer.key} ← ${shorter.key} (similarity: ${(pair.similarity * 100).toFixed(0)}%)`)
|
|
1441
|
+
|
|
1442
|
+
if (!dryRun) {
|
|
1443
|
+
// Update the longer entry with merged data
|
|
1444
|
+
const mergedLine = ` ${longer.id}|${longer.cat}|${longer.key}|${newContent}|${longer.file}|${mergedTags}|${newDate}|${longer.ttl}|${newAccessed}|${longer.line.split("|")[9] || ""}|${longer.line.split("|")[10] || ""}|${longer.line.split("|")[11] || ""}|${longer.line.split("|")[12] || ""}`
|
|
1445
|
+
// Replace in entries array
|
|
1446
|
+
entries[entries.indexOf(longer.line)] = mergedLine
|
|
1447
|
+
merged.add(pair.b)
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
if (dryRun) {
|
|
1452
|
+
return {
|
|
1453
|
+
content: [{
|
|
1454
|
+
type: "text" as const,
|
|
1455
|
+
text: `🔍 Dry run — would merge ${merged.size} entries:\n\n${mergeActions.join("\n")}\n\nRun with dryRun: false to apply.`
|
|
1456
|
+
}],
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
// Remove merged entries and write back
|
|
1461
|
+
const newLines = entries.filter((_, i) => !merged.has(i))
|
|
1462
|
+
const headerIdx = newLines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
|
|
1463
|
+
if (headerIdx !== -1) {
|
|
1464
|
+
const count = newLines.filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")).length
|
|
1465
|
+
newLines[headerIdx] = newLines[headerIdx].replace(/\[\d+\|/, `[${count}|`)
|
|
1466
|
+
}
|
|
1467
|
+
writeMemory(newLines.join("\n"))
|
|
1468
|
+
|
|
1469
|
+
return {
|
|
1470
|
+
content: [{
|
|
1471
|
+
type: "text" as const,
|
|
1472
|
+
text: `✅ Merged ${merged.size} entries into ${entries.length - merged.size} entries.\n\n${mergeActions.join("\n")}`
|
|
1473
|
+
}],
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
)
|
|
1477
|
+
|
|
1478
|
+
// ── memory_graph_path ────────────────────────────────────────────────
|
|
1479
|
+
|
|
1480
|
+
server.registerTool(
|
|
1481
|
+
"memory_graph_path",
|
|
1482
|
+
{
|
|
1483
|
+
title: "Find Graph Path",
|
|
1484
|
+
description: "Find the shortest path between two memory entries in the knowledge graph. Shows how two concepts are connected through related entries.",
|
|
1485
|
+
inputSchema: {
|
|
1486
|
+
from: z.string().describe("Starting entry key"),
|
|
1487
|
+
to: z.string().describe("Target entry key"),
|
|
1488
|
+
},
|
|
1489
|
+
},
|
|
1490
|
+
async ({ from, to }) => {
|
|
1491
|
+
const data = readMemory()
|
|
1492
|
+
const entries = parseEntries(data)
|
|
1493
|
+
const graph = buildGraph(entries)
|
|
1494
|
+
|
|
1495
|
+
if (!graph.byKey.has(from)) {
|
|
1496
|
+
return { content: [{ type: "text" as const, text: `❌ Entry "${from}" not found in memory.` }] }
|
|
1497
|
+
}
|
|
1498
|
+
if (!graph.byKey.has(to)) {
|
|
1499
|
+
return { content: [{ type: "text" as const, text: `❌ Entry "${to}" not found in memory.` }] }
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
// BFS shortest path
|
|
1503
|
+
const visited = new Set<string>()
|
|
1504
|
+
const parent = new Map<string, string>()
|
|
1505
|
+
const queue = [from]
|
|
1506
|
+
visited.add(from)
|
|
1507
|
+
|
|
1508
|
+
while (queue.length > 0) {
|
|
1509
|
+
const current = queue.shift()!
|
|
1510
|
+
if (current === to) break
|
|
1511
|
+
|
|
1512
|
+
for (const neighbor of graph.adjacency.get(current) || []) {
|
|
1513
|
+
if (!visited.has(neighbor)) {
|
|
1514
|
+
visited.add(neighbor)
|
|
1515
|
+
parent.set(neighbor, current)
|
|
1516
|
+
queue.push(neighbor)
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
if (!visited.has(to)) {
|
|
1522
|
+
return {
|
|
1523
|
+
content: [{
|
|
1524
|
+
type: "text" as const,
|
|
1525
|
+
text: `🔗 No path found between "${from}" and "${to}". They may be in disconnected parts of the memory graph.`
|
|
1526
|
+
}],
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
// Reconstruct path
|
|
1531
|
+
const path: string[] = []
|
|
1532
|
+
let current: string | null = to
|
|
1533
|
+
while (current !== null) {
|
|
1534
|
+
path.unshift(current)
|
|
1535
|
+
current = parent.get(current) || null
|
|
1536
|
+
}
|
|
1537
|
+
|
|
1538
|
+
const pathStr = path.map((key, i) => {
|
|
1539
|
+
const entry = graph.byKey.get(key)!
|
|
1540
|
+
const arrow = i < path.length - 1 ? ` → ` : ""
|
|
1541
|
+
return `[${entry.category}] ${key}${arrow}`
|
|
1542
|
+
}).join("\n ")
|
|
1543
|
+
|
|
1544
|
+
return {
|
|
1545
|
+
content: [{
|
|
1546
|
+
type: "text" as const,
|
|
1547
|
+
text: `🔗 Path (${path.length} hops):\n\n ${pathStr}`
|
|
1548
|
+
}],
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
)
|
|
1552
|
+
|
|
1377
1553
|
} // end registerTools
|
|
1378
1554
|
|
|
1379
1555
|
/** Parse relative time string to milliseconds. */
|