toon-memory 2.11.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 +1211 -0
- package/README.es.md +1216 -0
- package/README.fr.md +1211 -0
- package/README.ja.md +1211 -0
- package/README.ko.md +1211 -0
- package/README.md +22 -7
- package/README.pt-br.md +1213 -0
- package/README.zh.md +1211 -0
- package/dist/cli/session-start.js +32 -1
- package/dist/cli/setup.js +133 -22
- package/mcp/server.js +28719 -27935
- 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/session-start.ts +47 -1
- package/src/cli/types.ts +4 -2
- package/src/lib/graph.ts +4 -0
- package/src/lib/quality.ts +61 -10
- 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 +747 -5
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "toon-memory",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "MCP server giving AI coding agents offline, token-efficient persistent memory —
|
|
3
|
+
"version": "3.1.0",
|
|
4
|
+
"description": "MCP server giving AI coding agents offline, token-efficient persistent memory — 29 tools, 80% fewer tool calls, recall decisions, patterns, and bugs across sessions. No LLM, no server; works with 15+ agents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"toon-memory": "./bin/toon-memory.js"
|
|
@@ -27,6 +27,8 @@
|
|
|
27
27
|
"bench:impact": "node scripts/benchmark-impact.mjs",
|
|
28
28
|
"bench:context": "node scripts/bench-context-tools.mjs",
|
|
29
29
|
"bench:full": "node scripts/bench-full-impact.mjs",
|
|
30
|
+
"bench:compress-all": "node scripts/bench-compress-all.mjs",
|
|
31
|
+
"bench:primer": "node scripts/bench-primer.mjs",
|
|
30
32
|
"inspect": "npm run build && npx @modelcontextprotocol/inspector node bin/toon-memory.js mcp",
|
|
31
33
|
"prepublishOnly": "npm run build && npm test"
|
|
32
34
|
},
|
package/src/cli/agents.ts
CHANGED
|
@@ -58,7 +58,8 @@ export function detectAgents(): Agent[] {
|
|
|
58
58
|
agents.push({
|
|
59
59
|
name: "claude",
|
|
60
60
|
global: join(HOME, ".claude", "settings.json"),
|
|
61
|
-
local: join(projectRoot, ".
|
|
61
|
+
local: join(projectRoot, ".mcp.json"),
|
|
62
|
+
hookPath: join(projectRoot, ".claude", "settings.json"),
|
|
62
63
|
mcpKey: "mcpServers",
|
|
63
64
|
format: "json",
|
|
64
65
|
needsHooks: true,
|
|
@@ -99,8 +100,8 @@ export function detectAgents(): Agent[] {
|
|
|
99
100
|
agents.push({
|
|
100
101
|
name: "continue",
|
|
101
102
|
local: join(projectRoot, ".continue", "config.json"),
|
|
102
|
-
mcpKey: "
|
|
103
|
-
format: "
|
|
103
|
+
mcpKey: "experimental.modelContextProtocolServers",
|
|
104
|
+
format: "continue",
|
|
104
105
|
needsHooks: false,
|
|
105
106
|
needsInstructions: false
|
|
106
107
|
})
|
|
@@ -130,7 +131,7 @@ export function detectAgents(): Agent[] {
|
|
|
130
131
|
agents.push({
|
|
131
132
|
name: "zed",
|
|
132
133
|
global: join(HOME, ".config", "zed", "settings.json"),
|
|
133
|
-
mcpKey: "
|
|
134
|
+
mcpKey: "context_servers",
|
|
134
135
|
format: "jsonc",
|
|
135
136
|
needsHooks: false,
|
|
136
137
|
needsInstructions: false
|
|
@@ -138,7 +139,7 @@ export function detectAgents(): Agent[] {
|
|
|
138
139
|
|
|
139
140
|
agents.push({
|
|
140
141
|
name: "antigravity",
|
|
141
|
-
local: join(projectRoot, ".
|
|
142
|
+
local: join(projectRoot, ".agents", "mcp_config.json"),
|
|
142
143
|
mcpKey: "mcpServers",
|
|
143
144
|
format: "json",
|
|
144
145
|
needsHooks: true,
|
|
@@ -158,7 +159,7 @@ export function detectAgents(): Agent[] {
|
|
|
158
159
|
agents.push({
|
|
159
160
|
name: "kilocode",
|
|
160
161
|
global: join(HOME, ".kilocode", "mcp_settings.json"),
|
|
161
|
-
mcpKey: "
|
|
162
|
+
mcpKey: "mcp",
|
|
162
163
|
format: "json",
|
|
163
164
|
needsHooks: false,
|
|
164
165
|
needsInstructions: true,
|
|
@@ -167,9 +168,9 @@ export function detectAgents(): Agent[] {
|
|
|
167
168
|
|
|
168
169
|
agents.push({
|
|
169
170
|
name: "openclaw",
|
|
170
|
-
|
|
171
|
-
mcpKey: "
|
|
172
|
-
format: "
|
|
171
|
+
global: join(HOME, ".openclaw", "openclaw.json"),
|
|
172
|
+
mcpKey: "mcp.servers",
|
|
173
|
+
format: "openclaw",
|
|
173
174
|
needsHooks: false,
|
|
174
175
|
needsInstructions: false
|
|
175
176
|
})
|
package/src/cli/commands.ts
CHANGED
|
@@ -187,7 +187,7 @@ export function uninstall(): void {
|
|
|
187
187
|
console.log(" Removed .opencode/plugins/toon-memory.ts")
|
|
188
188
|
}
|
|
189
189
|
|
|
190
|
-
const agyHooks = join(projectRoot, ".
|
|
190
|
+
const agyHooks = join(projectRoot, ".agents", "hooks.json")
|
|
191
191
|
if (existsSync(agyHooks)) {
|
|
192
192
|
try {
|
|
193
193
|
const agyCfg = JSON.parse(readFileSync(agyHooks, "utf-8"))
|
package/src/cli/config-writer.ts
CHANGED
|
@@ -35,6 +35,11 @@ export function installJSONConfig(agent: Agent, scope: string): void {
|
|
|
35
35
|
type: "local",
|
|
36
36
|
command: ["npx", "-y", "toon-memory", "mcp"]
|
|
37
37
|
}
|
|
38
|
+
} else if (agent.name === "kilocode") {
|
|
39
|
+
config[mcpKey]["toon-memory"] = {
|
|
40
|
+
type: "local",
|
|
41
|
+
command: ["npx", "-y", "toon-memory", "mcp"]
|
|
42
|
+
}
|
|
38
43
|
} else {
|
|
39
44
|
config[mcpKey]["toon-memory"] = {
|
|
40
45
|
command: "npx",
|
|
@@ -86,19 +91,97 @@ export function installZedConfig(agent: Agent): void {
|
|
|
86
91
|
}
|
|
87
92
|
}
|
|
88
93
|
|
|
89
|
-
if (!config.
|
|
94
|
+
if (!config.context_servers) config.context_servers = {}
|
|
95
|
+
|
|
96
|
+
config.context_servers["toon-memory"] = {
|
|
97
|
+
command: "npx",
|
|
98
|
+
args: ["-y", "toon-memory", "mcp"],
|
|
99
|
+
source: "custom"
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
writeFileSync(configPath, JSON.stringify(config, null, 2))
|
|
103
|
+
console.log(` MCP server added to ${configPath}`)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Install MCP server configuration for Continue (array-based format).
|
|
108
|
+
* Uses experimental.modelContextProtocolServers with name/command/args array.
|
|
109
|
+
*/
|
|
110
|
+
export function installContinueConfig(agent: Agent): void {
|
|
111
|
+
const configPath = agent.local
|
|
112
|
+
if (!configPath) return
|
|
113
|
+
|
|
114
|
+
const configDir = dirname(configPath)
|
|
115
|
+
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
116
|
+
|
|
117
|
+
let config: Record<string, any> = {}
|
|
118
|
+
if (existsSync(configPath)) {
|
|
119
|
+
try {
|
|
120
|
+
config = JSON.parse(readFileSync(configPath, "utf-8"))
|
|
121
|
+
} catch {
|
|
122
|
+
config = {}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (!config.experimental) config.experimental = {}
|
|
127
|
+
if (!config.experimental.modelContextProtocolServers) {
|
|
128
|
+
config.experimental.modelContextProtocolServers = []
|
|
129
|
+
}
|
|
90
130
|
|
|
91
|
-
|
|
131
|
+
const servers = config.experimental.modelContextProtocolServers
|
|
132
|
+
const existing = servers.findIndex(
|
|
133
|
+
(s: any) => s.name === "toon-memory"
|
|
134
|
+
)
|
|
135
|
+
const entry = {
|
|
136
|
+
name: "toon-memory",
|
|
92
137
|
command: "npx",
|
|
93
138
|
args: ["-y", "toon-memory", "mcp"]
|
|
94
139
|
}
|
|
95
140
|
|
|
141
|
+
if (existing >= 0) {
|
|
142
|
+
servers[existing] = entry
|
|
143
|
+
} else {
|
|
144
|
+
servers.push(entry)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
writeFileSync(configPath, JSON.stringify(config, null, 2))
|
|
148
|
+
console.log(` MCP server added to ${configPath}`)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Install MCP server configuration for OpenClaw (nested mcp.servers format).
|
|
153
|
+
*/
|
|
154
|
+
export function installOpenClawConfig(agent: Agent): void {
|
|
155
|
+
const configPath = agent.global
|
|
156
|
+
if (!configPath) return
|
|
157
|
+
|
|
158
|
+
const configDir = dirname(configPath)
|
|
159
|
+
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
160
|
+
|
|
161
|
+
let config: Record<string, any> = {}
|
|
162
|
+
if (existsSync(configPath)) {
|
|
163
|
+
try {
|
|
164
|
+
config = JSON.parse(readFileSync(configPath, "utf-8"))
|
|
165
|
+
} catch {
|
|
166
|
+
config = {}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
if (!config.mcp) config.mcp = {}
|
|
171
|
+
if (!config.mcp.servers) config.mcp.servers = {}
|
|
172
|
+
|
|
173
|
+
config.mcp.servers["toon-memory"] = {
|
|
174
|
+
command: "npx",
|
|
175
|
+
args: ["-y", "toon-memory", "mcp"],
|
|
176
|
+
enabled: true
|
|
177
|
+
}
|
|
178
|
+
|
|
96
179
|
writeFileSync(configPath, JSON.stringify(config, null, 2))
|
|
97
180
|
console.log(` MCP server added to ${configPath}`)
|
|
98
181
|
}
|
|
99
182
|
|
|
100
183
|
/**
|
|
101
|
-
* Install MCP
|
|
184
|
+
* Install MCP server configuration for an agent based on its format.
|
|
102
185
|
*/
|
|
103
186
|
export function installMCPConfig(agent: Agent, scope: string): void {
|
|
104
187
|
if (agent.format === "none") {
|
|
@@ -110,6 +193,10 @@ export function installMCPConfig(agent: Agent, scope: string): void {
|
|
|
110
193
|
installTOMLConfig(agent)
|
|
111
194
|
} else if (agent.format === "jsonc") {
|
|
112
195
|
installZedConfig(agent)
|
|
196
|
+
} else if (agent.format === "continue") {
|
|
197
|
+
installContinueConfig(agent)
|
|
198
|
+
} else if (agent.format === "openclaw") {
|
|
199
|
+
installOpenClawConfig(agent)
|
|
113
200
|
} else {
|
|
114
201
|
installJSONConfig(agent, scope)
|
|
115
202
|
}
|
package/src/cli/hooks.ts
CHANGED
|
@@ -66,7 +66,7 @@ export function installHooks(agent: Agent): void {
|
|
|
66
66
|
|
|
67
67
|
/** Register activity-capture hooks (PostToolUse/Stop) in a JSON agent config. */
|
|
68
68
|
export function registerCaptureHookJSON(agent: Agent, scriptPath: string): void {
|
|
69
|
-
const configPath = agent.local || agent.global
|
|
69
|
+
const configPath = agent.hookPath || agent.local || agent.global
|
|
70
70
|
if (!configPath) return
|
|
71
71
|
|
|
72
72
|
const configDir = dirname(configPath)
|
|
@@ -126,7 +126,7 @@ export function registerHookTOML(agent: Agent, hookPath: string): void {
|
|
|
126
126
|
|
|
127
127
|
/** Register SessionStart hook in JSON config (Claude Code / Gemini CLI). */
|
|
128
128
|
export function registerHookJSON(agent: Agent, hookPath: string): void {
|
|
129
|
-
const configPath = agent.format === "jsonc" ? agent.global : (agent.local || agent.global)
|
|
129
|
+
const configPath = agent.hookPath || (agent.format === "jsonc" ? agent.global : (agent.local || agent.global))
|
|
130
130
|
if (!configPath) return
|
|
131
131
|
|
|
132
132
|
const configDir = dirname(configPath)
|
|
@@ -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/session-start.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { readFileSync } from "fs"
|
|
1
|
+
import { readFileSync, existsSync } from "fs"
|
|
2
|
+
import { join } from "path"
|
|
2
3
|
import { heartbeat, coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS } from "../lib/sessions"
|
|
3
4
|
|
|
4
5
|
/**
|
|
@@ -8,11 +9,50 @@ import { heartbeat, coordinationView, resolveSessionId, currentBranch, SESSION_T
|
|
|
8
9
|
* 1. Registers this session's heartbeat (so parallel sessions can see it).
|
|
9
10
|
* 2. Prints a short reminder listing OTHER active sessions, their branches,
|
|
10
11
|
* and any soft file conflicts — so the agent doesn't clobber sibling work.
|
|
12
|
+
* 3. Injects the system primer (top memories by importance) so the agent
|
|
13
|
+
* starts with context without having to call memory_recall.
|
|
11
14
|
*
|
|
12
15
|
* No network, no LLM. Exits 0 always (a failing hook must never block the
|
|
13
16
|
* agent from starting).
|
|
14
17
|
*/
|
|
15
18
|
|
|
19
|
+
const MEMORY_DIR = join(process.cwd(), ".toon-memory", "memory")
|
|
20
|
+
const MEMORY_FILE = join(MEMORY_DIR, "data.toon")
|
|
21
|
+
|
|
22
|
+
/** Minimal system primer: top 5 memories by importance. ~50-100 tokens. */
|
|
23
|
+
function systemPrimer(): string {
|
|
24
|
+
if (!existsSync(MEMORY_FILE)) return ""
|
|
25
|
+
try {
|
|
26
|
+
const data = readFileSync(MEMORY_FILE, "utf-8")
|
|
27
|
+
const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
|
|
28
|
+
if (lines.length === 0) return ""
|
|
29
|
+
|
|
30
|
+
// Parse entries and sort by importance (accessed + recency)
|
|
31
|
+
const entries = lines
|
|
32
|
+
.map((l) => {
|
|
33
|
+
const p = l.trim().split("|")
|
|
34
|
+
if (p.length < 7) return null
|
|
35
|
+
const accessed = p.length > 8 ? parseInt(p[8]) || 0 : 0
|
|
36
|
+
const daysSince = (Date.now() - new Date(`${p[6]}T00:00:00`).getTime()) / 86400000
|
|
37
|
+
const recency = daysSince < 7 ? 3 : daysSince < 30 ? 2 : daysSince < 90 ? 1 : 0
|
|
38
|
+
return { key: p[2], content: p[3], category: p[1], tags: p[5] || "", importance: accessed + recency }
|
|
39
|
+
})
|
|
40
|
+
.filter(Boolean)
|
|
41
|
+
.sort((a, b) => b!.importance - a!.importance)
|
|
42
|
+
.slice(0, 5)
|
|
43
|
+
|
|
44
|
+
if (entries.length === 0) return ""
|
|
45
|
+
|
|
46
|
+
const lines2 = [" Top memories:"]
|
|
47
|
+
for (const e of entries) {
|
|
48
|
+
lines2.push(` [${e!.category}] ${e!.key}: ${e!.content.slice(0, 100)}`)
|
|
49
|
+
}
|
|
50
|
+
return lines2.join("\n")
|
|
51
|
+
} catch {
|
|
52
|
+
return ""
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
16
56
|
function main(): void {
|
|
17
57
|
const agent = process.argv[2] || "agent"
|
|
18
58
|
|
|
@@ -62,6 +102,12 @@ function main(): void {
|
|
|
62
102
|
lines.push(" No file conflicts detected.")
|
|
63
103
|
}
|
|
64
104
|
|
|
105
|
+
// Inject system primer (top memories) — automatic context at session start
|
|
106
|
+
const primer = systemPrimer()
|
|
107
|
+
if (primer) {
|
|
108
|
+
lines.push(primer)
|
|
109
|
+
}
|
|
110
|
+
|
|
65
111
|
lines.push(" Use memory_recall before reading files and memory_sessions to coordinate.")
|
|
66
112
|
console.log(lines.join("\n"))
|
|
67
113
|
process.exit(0)
|
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/graph.ts
CHANGED
|
@@ -30,6 +30,8 @@ export interface GraphEntry {
|
|
|
30
30
|
accessed: number
|
|
31
31
|
/** Explicit outgoing links declared on the entry. */
|
|
32
32
|
links: string[]
|
|
33
|
+
/** ISO timestamp of last recall/access. Empty if never accessed. */
|
|
34
|
+
lastAccessed: string
|
|
33
35
|
}
|
|
34
36
|
|
|
35
37
|
export interface MemoryGraph {
|
|
@@ -49,6 +51,7 @@ const entryLines = (data: string): string[] =>
|
|
|
49
51
|
/**
|
|
50
52
|
* Parse TOON memory content into structured entries.
|
|
51
53
|
* Tolerant of the trailing `links` field (absent on older entries).
|
|
54
|
+
* Also handles the `lastAccessed` field (field 12) for access tracking.
|
|
52
55
|
*/
|
|
53
56
|
export function parseEntries(data: string): GraphEntry[] {
|
|
54
57
|
const out: GraphEntry[] = []
|
|
@@ -74,6 +77,7 @@ export function parseEntries(data: string): GraphEntry[] {
|
|
|
74
77
|
.split(/[\s;]+/)
|
|
75
78
|
.map((t) => t.trim())
|
|
76
79
|
.filter(Boolean),
|
|
80
|
+
lastAccessed: parts.length > 12 ? parts[12] || "" : "",
|
|
77
81
|
})
|
|
78
82
|
}
|
|
79
83
|
return out
|
package/src/lib/quality.ts
CHANGED
|
@@ -15,8 +15,25 @@ import { fuzzyMatch } from "./fuzzy"
|
|
|
15
15
|
/**
|
|
16
16
|
* Quality score for an entry (0..1). Pure heuristics, no LLM.
|
|
17
17
|
* Measures how well-structured and useful a memory entry is.
|
|
18
|
+
*
|
|
19
|
+
* Factors:
|
|
20
|
+
* - Tags (0.3 max): structured categorization
|
|
21
|
+
* - Links (0.2 max): graph connectivity
|
|
22
|
+
* - Content length (0.3 max): detail level
|
|
23
|
+
* - Recency (0.1 max): how recently created
|
|
24
|
+
* - Specificity (0.1 max): unique word ratio
|
|
25
|
+
* - Access frequency (0.15 max): how often recalled
|
|
26
|
+
* - Access recency (0.1 max): how recently accessed
|
|
27
|
+
* - Staleness decay: entries not accessed in 30+ days lose up to 0.2
|
|
18
28
|
*/
|
|
19
|
-
export function qualityScore(
|
|
29
|
+
export function qualityScore(
|
|
30
|
+
tags: string,
|
|
31
|
+
links: string,
|
|
32
|
+
content: string,
|
|
33
|
+
date: string,
|
|
34
|
+
accessed: number = 0,
|
|
35
|
+
lastAccessed: string = ""
|
|
36
|
+
): number {
|
|
20
37
|
let score = 0
|
|
21
38
|
if (tags) {
|
|
22
39
|
const count = tags.split(";").filter(Boolean).length
|
|
@@ -30,7 +47,7 @@ export function qualityScore(tags: string, links: string, content: string, date:
|
|
|
30
47
|
if (len > 20) score += 0.1
|
|
31
48
|
if (len > 60) score += 0.1
|
|
32
49
|
if (len > 150) score += 0.1
|
|
33
|
-
// Recency bonus
|
|
50
|
+
// Recency bonus (creation date)
|
|
34
51
|
if (date) {
|
|
35
52
|
const days = (Date.now() - new Date(`${date}T00:00:00`).getTime()) / 86400000
|
|
36
53
|
if (days < 7) score += 0.1
|
|
@@ -41,7 +58,34 @@ export function qualityScore(tags: string, links: string, content: string, date:
|
|
|
41
58
|
const unique = new Set(words)
|
|
42
59
|
const specificity = words.length > 0 ? unique.size / words.length : 0
|
|
43
60
|
score += specificity * 0.1
|
|
44
|
-
|
|
61
|
+
// Access frequency: entries recalled more often are more valuable
|
|
62
|
+
if (accessed > 0) {
|
|
63
|
+
score += Math.min(0.15, accessed * 0.03)
|
|
64
|
+
}
|
|
65
|
+
// Access recency: recently accessed entries are more relevant
|
|
66
|
+
if (lastAccessed) {
|
|
67
|
+
const daysSinceAccess = (Date.now() - new Date(lastAccessed).getTime()) / 86400000
|
|
68
|
+
if (daysSinceAccess < 1) score += 0.1
|
|
69
|
+
else if (daysSinceAccess < 7) score += 0.07
|
|
70
|
+
else if (daysSinceAccess < 30) score += 0.03
|
|
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))
|
|
45
89
|
}
|
|
46
90
|
|
|
47
91
|
/**
|
|
@@ -80,19 +124,24 @@ export function mergeEntries(existingLine: string, newLine: string): string {
|
|
|
80
124
|
const newAccessed = np.length > 8 ? parseInt(np[8]) || 0 : 0
|
|
81
125
|
const accessed = Math.max(existingAccessed, newAccessed)
|
|
82
126
|
|
|
127
|
+
// Merge links (union)
|
|
128
|
+
const existingLinks = (ep[9] || "").split(/[\s;]+/).filter(Boolean)
|
|
129
|
+
const newLinks = (np[9] || "").split(/[\s;]+/).filter(Boolean)
|
|
130
|
+
const mergedLinks = [...new Set([...existingLinks, ...newLinks])].join(" ")
|
|
131
|
+
|
|
83
132
|
// Take max confidence — handle entries with <12 fields gracefully
|
|
84
133
|
const existingConf = ep.length > 11 ? parseFloat(ep[11]) || 0 : 0
|
|
85
134
|
const newConf = np.length > 11 ? parseFloat(np[11]) || 0 : 0
|
|
86
135
|
const confidence = Math.max(existingConf, newConf)
|
|
87
136
|
|
|
88
|
-
//
|
|
89
|
-
const
|
|
90
|
-
const
|
|
91
|
-
const
|
|
137
|
+
// Take most recent lastAccessed (field 12)
|
|
138
|
+
const existingLastAccessed = ep.length > 12 ? ep[12] || "" : ""
|
|
139
|
+
const newLastAccessed = np.length > 12 ? np[12] || "" : ""
|
|
140
|
+
const lastAccessed = newLastAccessed > existingLastAccessed ? newLastAccessed : existingLastAccessed
|
|
92
141
|
|
|
93
|
-
const quality = qualityScore(mergedTags, mergedLinks, content, date)
|
|
142
|
+
const quality = qualityScore(mergedTags, mergedLinks, content, date, accessed, lastAccessed)
|
|
94
143
|
|
|
95
|
-
return `${id}|${category}|${key}|${content}|${file}|${mergedTags}|${date}|${ttl}|${accessed}|${mergedLinks}|${quality.toFixed(2)}|${confidence}`
|
|
144
|
+
return `${id}|${category}|${key}|${content}|${file}|${mergedTags}|${date}|${ttl}|${accessed}|${mergedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}`
|
|
96
145
|
}
|
|
97
146
|
|
|
98
147
|
/**
|
|
@@ -194,7 +243,9 @@ export function generateSystemPrimer(data: string): string {
|
|
|
194
243
|
e.tags.join(";"),
|
|
195
244
|
e.links.join(" "),
|
|
196
245
|
e.content,
|
|
197
|
-
e.date
|
|
246
|
+
e.date,
|
|
247
|
+
e.accessed,
|
|
248
|
+
e.lastAccessed
|
|
198
249
|
)
|
|
199
250
|
const conf = quality >= 0.5 ? "high" : quality >= 0.3 ? "medium" : "low"
|
|
200
251
|
lines.push(
|
package/src/mcp/config.ts
CHANGED
|
@@ -39,6 +39,8 @@ export interface MemoryConfig {
|
|
|
39
39
|
vocab?: Record<string, string[]>
|
|
40
40
|
/** Maximum active entries before auto-archive (default 100). */
|
|
41
41
|
maxEntries?: number
|
|
42
|
+
/** Verbatim mode: skip tag inference and quality scoring at write time. */
|
|
43
|
+
verbatim?: boolean
|
|
42
44
|
}
|
|
43
45
|
|
|
44
46
|
/**
|
package/src/mcp/consolidation.ts
CHANGED
|
@@ -1,10 +1,30 @@
|
|
|
1
1
|
import { readMemory, writeMemory } from "./memory-io"
|
|
2
2
|
import { mergeEntries } from "../lib/quality"
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* Jaccard similarity between two content strings (0..1).
|
|
6
|
+
* Normalizes whitespace and case before comparing word sets.
|
|
7
|
+
*/
|
|
8
|
+
function contentSimilarity(a: string, b: string): number {
|
|
9
|
+
const wordsA = new Set(a.toLowerCase().replace(/\s+/g, " ").trim().split(" "))
|
|
10
|
+
const wordsB = new Set(b.toLowerCase().replace(/\s+/g, " ").trim().split(" "))
|
|
11
|
+
if (wordsA.size === 0 && wordsB.size === 0) return 1
|
|
12
|
+
if (wordsA.size === 0 || wordsB.size === 0) return 0
|
|
13
|
+
let intersection = 0
|
|
14
|
+
for (const w of wordsA) {
|
|
15
|
+
if (wordsB.has(w)) intersection++
|
|
16
|
+
}
|
|
17
|
+
const union = wordsA.size + wordsB.size - intersection
|
|
18
|
+
return union > 0 ? intersection / union : 0
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Threshold for near-duplicate detection (0..1). */
|
|
22
|
+
const NEAR_DUP_THRESHOLD = 0.7
|
|
23
|
+
|
|
4
24
|
/**
|
|
5
25
|
* Deterministic consolidation: merge entries with the same key (combining
|
|
6
26
|
* tags, links, max confidence, latest date), then remove exact-content
|
|
7
|
-
* duplicates. No LLM involved.
|
|
27
|
+
* duplicates and merge near-duplicates (similarity > 0.7). No LLM involved.
|
|
8
28
|
*/
|
|
9
29
|
export function consolidateEntries(): { removed: number; kept: number; duplicates: string[] } {
|
|
10
30
|
const data = readMemory()
|
|
@@ -38,8 +58,8 @@ export function consolidateEntries(): { removed: number; kept: number; duplicate
|
|
|
38
58
|
}
|
|
39
59
|
}
|
|
40
60
|
|
|
41
|
-
// Phase 2: Remove exact-content duplicates
|
|
42
|
-
const contentSeen = new Map<string, string>()
|
|
61
|
+
// Phase 2: Remove exact-content duplicates AND merge near-duplicates
|
|
62
|
+
const contentSeen = new Map<string, { line: string; idx: number }>()
|
|
43
63
|
const order: string[] = []
|
|
44
64
|
const duplicates: string[] = []
|
|
45
65
|
|
|
@@ -50,13 +70,38 @@ export function consolidateEntries(): { removed: number; kept: number; duplicate
|
|
|
50
70
|
order.push(line)
|
|
51
71
|
continue
|
|
52
72
|
}
|
|
53
|
-
const content =
|
|
54
|
-
|
|
73
|
+
const content = parts[3] || ""
|
|
74
|
+
const normalized = content.toLowerCase().replace(/\s+/g, " ").trim()
|
|
75
|
+
|
|
76
|
+
// Check for exact duplicate first
|
|
77
|
+
if (contentSeen.has(normalized)) {
|
|
55
78
|
duplicates.push(parts[2])
|
|
56
79
|
continue
|
|
57
80
|
}
|
|
58
|
-
|
|
59
|
-
|
|
81
|
+
|
|
82
|
+
// Check for near-duplicate (same category, similar content)
|
|
83
|
+
let merged = false
|
|
84
|
+
for (const [seenNorm, existing] of contentSeen) {
|
|
85
|
+
const existingParts = existing.line.split("|")
|
|
86
|
+
if (existingParts[1] !== parts[1]) continue // different category
|
|
87
|
+
const sim = contentSimilarity(content, existingParts[3] || "")
|
|
88
|
+
if (sim >= NEAR_DUP_THRESHOLD) {
|
|
89
|
+
// Merge into the existing entry (keep the one with higher quality)
|
|
90
|
+
const mergedLine = mergeEntries(existing.line, line)
|
|
91
|
+
contentSeen.set(seenNorm, { line: mergedLine, idx: existing.idx })
|
|
92
|
+
// Replace in order array
|
|
93
|
+
const orderIdx = order.findIndex((l) => l === existing.line)
|
|
94
|
+
if (orderIdx !== -1) order[orderIdx] = mergedLine
|
|
95
|
+
duplicates.push(parts[2])
|
|
96
|
+
merged = true
|
|
97
|
+
break
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (!merged) {
|
|
102
|
+
contentSeen.set(normalized, { line, idx: order.length })
|
|
103
|
+
order.push(line)
|
|
104
|
+
}
|
|
60
105
|
}
|
|
61
106
|
|
|
62
107
|
const totalRemoved = mergedAway.length + duplicates.length
|