toon-memory 4.3.5 → 4.4.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.de.md +2 -2
- package/README.es.md +2 -2
- package/README.fr.md +2 -2
- package/README.ja.md +2 -2
- package/README.ko.md +2 -2
- package/README.md +57 -11
- package/README.pt-br.md +2 -2
- package/README.zh.md +2 -2
- package/bin/toon-memory.js +4 -0
- package/dist/cli/capture.js +658 -26
- package/dist/cli/setup.js +1783 -110
- package/mcp/server.js +1369 -356
- package/package.json +3 -2
- package/src/bin/toon-memory.ts +4 -0
- package/src/cli/ambient.ts +117 -0
- package/src/cli/capture.ts +5 -2
- package/src/cli/constants.ts +19 -11
- package/src/cli/dense.ts +50 -0
- package/src/cli/instructions.ts +2 -2
- package/src/cli/opencode-plugin.ts +100 -95
- package/src/cli/setup.ts +51 -4
- package/src/cli/sleep.ts +45 -0
- package/src/lib/activation.ts +32 -0
- package/src/lib/compiler.ts +178 -0
- package/src/lib/dense.ts +123 -0
- package/src/lib/graph.ts +123 -36
- package/src/lib/handoff.ts +144 -0
- package/src/lib/ngrams.ts +68 -0
- package/src/lib/promoter.ts +140 -0
- package/src/lib/quality.ts +25 -10
- package/src/lib/utils.ts +17 -7
- package/src/mcp/args.ts +46 -0
- package/src/mcp/config.ts +20 -0
- package/src/mcp/edges.ts +99 -0
- package/src/mcp/entries.ts +34 -9
- package/src/mcp/feedback.ts +130 -0
- package/src/mcp/resources.ts +12 -9
- package/src/mcp/server.ts +13 -1
- package/src/mcp/tools.ts +271 -102
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "toon-memory",
|
|
3
3
|
"mcpName": "io.github.LuiggiVal08/toon-memory",
|
|
4
|
-
"version": "4.
|
|
4
|
+
"version": "4.4.1",
|
|
5
5
|
"description": "The Continuity Layer for AI Agents — an MCP memory server that preserves project knowledge, decisions, and conventions across sessions so every session starts where the last one ended. Offline, token-efficient, no LLM, no server; works with 20+ agents.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"bin": {
|
|
@@ -34,7 +34,8 @@
|
|
|
34
34
|
"capture:viewer": "node scripts/capture-viewer.mjs",
|
|
35
35
|
"inspect": "npm run build && npx @modelcontextprotocol/inspector node bin/toon-memory.js mcp",
|
|
36
36
|
"prepublishOnly": "npm run build && npm test",
|
|
37
|
-
"bench:retrieval": "node scripts/bench-retrieval.mjs"
|
|
37
|
+
"bench:retrieval": "node scripts/bench-retrieval.mjs",
|
|
38
|
+
"bench:check": "node scripts/bench-check.mjs"
|
|
38
39
|
},
|
|
39
40
|
"dependencies": {
|
|
40
41
|
"@inquirer/checkbox": "^5.2.1",
|
package/src/bin/toon-memory.ts
CHANGED
|
@@ -35,6 +35,10 @@ Commands:
|
|
|
35
35
|
viewer [--port <n>] Open the interactive graph viewer in a browser (auto-picks a free port)
|
|
36
36
|
uninstall Remove toon-memory from all agents
|
|
37
37
|
capture <on|off> Enable/disable activity capture hooks
|
|
38
|
+
brief [task] Print the compact handoff brief for session start
|
|
39
|
+
doctor Check memory path, signals and injection channel
|
|
40
|
+
signal --type <t> --summary <s> Append one deterministic signal
|
|
41
|
+
promote Promote high-confidence signals into memory
|
|
38
42
|
upgrade Upgrade to the latest version
|
|
39
43
|
|
|
40
44
|
Options:
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CLI surface for the ambient memory loops:
|
|
3
|
+
* brief — compact handoff packet for injection at session start
|
|
4
|
+
* doctor — is memory wired correctly in this workspace?
|
|
5
|
+
* signal — append one deterministic signal to session.toon
|
|
6
|
+
* promote — promote high-confidence signals into data.toon
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { existsSync, readFileSync } from "fs"
|
|
10
|
+
import { join } from "path"
|
|
11
|
+
import { buildHandoffBrief } from "../lib/handoff"
|
|
12
|
+
import { compileContext, renderContextPackage } from "../lib/compiler"
|
|
13
|
+
import { promoteSignals, PROMOTE_THRESHOLD, type Signal } from "../lib/promoter"
|
|
14
|
+
import { readMemory, writeMemory } from "../mcp/memory-io"
|
|
15
|
+
import { MEMORY_DIR, MEMORY_FILE, CONFIG_FILE, GLOBAL_FILE } from "../mcp/config"
|
|
16
|
+
import { readSessionEntries, writeSessionEntry } from "../mcp/session-store"
|
|
17
|
+
import { parseEntries } from "../lib/graph"
|
|
18
|
+
import { entryAgeDays, projectSlug } from "../lib/handoff"
|
|
19
|
+
|
|
20
|
+
function flag(args: string[], name: string): string {
|
|
21
|
+
const i = args.indexOf(`--${name}`)
|
|
22
|
+
return i !== -1 && args[i + 1] && !args[i + 1].startsWith("--") ? args[i + 1] : ""
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Print the handoff brief. This is what hooks inject — never the full dump. */
|
|
26
|
+
export function printBrief(task = ""): void {
|
|
27
|
+
const data = readMemory()
|
|
28
|
+
const root = process.cwd()
|
|
29
|
+
if (task.trim()) {
|
|
30
|
+
const sessions = readSessionEntries()
|
|
31
|
+
.slice(-2)
|
|
32
|
+
.map((e) => `${e.session || "cli"}: ${e.summary.slice(0, 80)}`)
|
|
33
|
+
process.stdout.write(renderContextPackage(compileContext(data, task, { root, sessions })))
|
|
34
|
+
return
|
|
35
|
+
}
|
|
36
|
+
process.stdout.write(buildHandoffBrief(data, root, { task }))
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Append one signal to the unified session store. */
|
|
40
|
+
export function recordSignal(args: string[]): void {
|
|
41
|
+
const type = flag(args, "type") || "observation"
|
|
42
|
+
const summary = flag(args, "summary")
|
|
43
|
+
if (!summary) {
|
|
44
|
+
console.error("signal: --summary is required")
|
|
45
|
+
process.exitCode = 1
|
|
46
|
+
return
|
|
47
|
+
}
|
|
48
|
+
writeSessionEntry({
|
|
49
|
+
ts: new Date().toISOString(),
|
|
50
|
+
session: flag(args, "session") || process.env.TOON_MEMORY_SESSION || "cli",
|
|
51
|
+
agent: flag(args, "agent") || "opencode",
|
|
52
|
+
branch: flag(args, "branch") || "",
|
|
53
|
+
tool: `${type}:${flag(args, "tool") || "hook"}`,
|
|
54
|
+
file: flag(args, "file") || "",
|
|
55
|
+
summary,
|
|
56
|
+
})
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Promote high-confidence signals. Deterministic; no model call. */
|
|
60
|
+
export function runPromotion(args: string[]): void {
|
|
61
|
+
const thresholdArg = Number(flag(args, "threshold"))
|
|
62
|
+
const threshold = Number.isFinite(thresholdArg) && thresholdArg > 0 ? thresholdArg : PROMOTE_THRESHOLD
|
|
63
|
+
const entries = readSessionEntries(flag(args, "session") || undefined)
|
|
64
|
+
const signals: Signal[] = entries.map((e) => ({
|
|
65
|
+
type: e.tool,
|
|
66
|
+
summary: e.summary,
|
|
67
|
+
file: e.file,
|
|
68
|
+
session: e.session,
|
|
69
|
+
ts: e.ts,
|
|
70
|
+
}))
|
|
71
|
+
const result = promoteSignals(readMemory(), signals, { threshold })
|
|
72
|
+
if (result.promoted.length > 0) writeMemory(result.data)
|
|
73
|
+
console.log(`Promoted ${result.promoted.length} signal(s); ${result.kept} kept in log.`)
|
|
74
|
+
for (const p of result.promoted) console.log(` + ${p.category}/${p.key} (${p.score})`)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Read-only health check for the ambient loops. */
|
|
78
|
+
export function printDoctor(): void {
|
|
79
|
+
const root = process.cwd()
|
|
80
|
+
const lines: string[] = [
|
|
81
|
+
`toon-memory doctor — ${root}`,
|
|
82
|
+
`mcp_project: ${projectSlug(root)}`,
|
|
83
|
+
]
|
|
84
|
+
|
|
85
|
+
if (!existsSync(MEMORY_FILE)) {
|
|
86
|
+
lines.push(`memory: MISSING (${MEMORY_FILE}) — run 'toon-memory init'`)
|
|
87
|
+
} else {
|
|
88
|
+
const entries = parseEntries(readFileSync(MEMORY_FILE, "utf-8"))
|
|
89
|
+
const today = new Date().toISOString().split("T")[0]
|
|
90
|
+
const newest = entries.reduce((a, e) => (e.date > a ? e.date : a), "")
|
|
91
|
+
const age = newest ? entryAgeDays(newest, today) : 0
|
|
92
|
+
const freshness = !newest ? "empty" : age > 30 ? `stale-${age}d` : "fresh"
|
|
93
|
+
const stale = entries.filter((e) => e.date && entryAgeDays(e.date, today) > 30 && e.status !== "obsolete").length
|
|
94
|
+
const traps = entries.filter(
|
|
95
|
+
(e) => e.category === "warning" || e.tags.some((t) => ["trap", "gotcha", "risk"].includes(t.toLowerCase()))
|
|
96
|
+
).length
|
|
97
|
+
lines.push(`memory: ${entries.length} entries | newest: ${newest || "none"} | freshness: ${freshness}`)
|
|
98
|
+
lines.push(`hygiene: ${stale} stale | ${traps} traps`)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const sessionFile = join(MEMORY_DIR, "session.toon")
|
|
102
|
+
lines.push(`signals: ${existsSync(sessionFile) ? readSessionEntries().length : 0} in session.toon`)
|
|
103
|
+
lines.push(`config: ${existsSync(CONFIG_FILE) ? "present" : "default"}`)
|
|
104
|
+
lines.push(`global: ${existsSync(GLOBAL_FILE) ? "present" : "absent"}`)
|
|
105
|
+
|
|
106
|
+
const plugin = join(root, ".opencode", "plugins", "toon-memory.ts")
|
|
107
|
+
if (existsSync(plugin)) {
|
|
108
|
+
const src = readFileSync(plugin, "utf-8")
|
|
109
|
+
const hasSystem = src.includes("experimental.chat.system.transform")
|
|
110
|
+
lines.push(`opencode plugin: installed | system injection: ${hasSystem ? "OK" : "STALE — re-run init"}`)
|
|
111
|
+
} else {
|
|
112
|
+
lines.push("opencode plugin: absent")
|
|
113
|
+
}
|
|
114
|
+
lines.push(`injection: brief via 'toon-memory brief' (system.transform) | auto-write via 'signal' + 'promote'`)
|
|
115
|
+
lines.push(`catalog: ${process.env.TOON_MEMORY_EXPERT_TOOLS === "1" ? "expert" : "core"} (set TOON_MEMORY_EXPERT_TOOLS=1 for advanced tools)`)
|
|
116
|
+
console.log(lines.join("\n"))
|
|
117
|
+
}
|
package/src/cli/capture.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { createHash } from "crypto"
|
|
|
4
4
|
import { withLockSync, atomicWrite } from "../lib/lock"
|
|
5
5
|
import { heartbeat, endSession, resolveSessionId, currentBranch } from "../lib/sessions"
|
|
6
6
|
import { pruneObservations } from "../mcp/observations"
|
|
7
|
+
import { runSleep } from "./sleep"
|
|
7
8
|
import { parseToonLine } from "../lib/utils"
|
|
8
9
|
|
|
9
10
|
/**
|
|
@@ -153,8 +154,10 @@ function main(): void {
|
|
|
153
154
|
if (sessionEnabled()) {
|
|
154
155
|
const input = payload.tool_input ?? payload.input ?? {}
|
|
155
156
|
const { file } = derive(effectiveTool, input)
|
|
156
|
-
if (isStop)
|
|
157
|
-
|
|
157
|
+
if (isStop) {
|
|
158
|
+
endSession(agent, sessionId)
|
|
159
|
+
runSleep()
|
|
160
|
+
} else heartbeat(agent, sessionId, { file })
|
|
158
161
|
}
|
|
159
162
|
|
|
160
163
|
// Observation log: opt-in only.
|
package/src/cli/constants.ts
CHANGED
|
@@ -29,7 +29,7 @@ export const CAPTURE_CONFIG = join(MEMORY_DIR, "config.json")
|
|
|
29
29
|
export const ANTIGRAVITY_HOOK_NAME = "toon-memory"
|
|
30
30
|
|
|
31
31
|
/** Base instruction content for agents */
|
|
32
|
-
|
|
32
|
+
const INSTRUCTION_CONTENT_BASE = `# toon-memory
|
|
33
33
|
|
|
34
34
|
Persistent memory for this project. Use it to avoid re-investigating things.
|
|
35
35
|
|
|
@@ -49,15 +49,23 @@ Persistent memory for this project. Use it to avoid re-investigating things.
|
|
|
49
49
|
- Save important decisions, bugs resolved, and patterns observed.
|
|
50
50
|
`
|
|
51
51
|
|
|
52
|
-
/**
|
|
53
|
-
|
|
54
|
-
* memory auto-injected via `.opencode/instructions/memory-autoload.md` (written
|
|
55
|
-
* by the plugin on session.created), so the agent should NOT be told to actively
|
|
56
|
-
* run memory_recall — that would duplicate context. memory_recall is only a
|
|
57
|
-
* fallback for deep/semantic queries beyond the auto-loaded dump.
|
|
58
|
-
*/
|
|
59
|
-
export const OPENCODE_PASSIVE_INSTRUCTION = `# toon-memory
|
|
52
|
+
/** Marker used to keep injected instructions idempotent without matching unrelated prose. */
|
|
53
|
+
export const INSTRUCTION_MARKER = "<!-- toon-memory:instructions -->"
|
|
60
54
|
|
|
61
|
-
|
|
62
|
-
|
|
55
|
+
const ACTIVE_RULES = `
|
|
56
|
+
## Memory loop
|
|
57
|
+
- A compact brief is auto-injected at session start; when a task is known it is a context_compile packet with directives, constraints and retrieve/hydrate keys.
|
|
58
|
+
- Call memory_compile(task=...) at task start for a fresh packet; follow its Retrieval plan and hydrate only the keys you need.
|
|
59
|
+
- Use memory_recall BEFORE the first read/grep when the task may already be solved in memory.
|
|
60
|
+
- Before editing a file, check the warnings in the brief; run memory_recall(query=<path>) for file-specific traps.
|
|
61
|
+
- When a recalled entry was useful or wrong, call memory_feedback(key=..., signal=...) to train future ranking.
|
|
62
|
+
- When you learn a directive, decision or fix, save it with memory_remember — or let the ambient hooks capture it.
|
|
63
|
+
- When the user asks to see the memory graph, call memory_visualize().
|
|
63
64
|
`
|
|
65
|
+
|
|
66
|
+
export const OPENCODE_PASSIVE_INSTRUCTION = `${INSTRUCTION_MARKER}
|
|
67
|
+
# toon-memory
|
|
68
|
+
${ACTIVE_RULES}`
|
|
69
|
+
|
|
70
|
+
export const INSTRUCTION_CONTENT = `${INSTRUCTION_MARKER}
|
|
71
|
+
${INSTRUCTION_CONTENT_BASE}${ACTIVE_RULES}`
|
package/src/cli/dense.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { existsSync } from "fs"
|
|
2
|
+
import { loadConfig, saveConfig, VECTORS_FILE } from "../mcp/config"
|
|
3
|
+
import { readMemory } from "../mcp/memory-io"
|
|
4
|
+
import { buildVectors, loadDenseModule, readVectors } from "../lib/dense"
|
|
5
|
+
|
|
6
|
+
export const DEFAULT_DENSE_MODEL = "multilingual-e5-small"
|
|
7
|
+
|
|
8
|
+
export async function runDense(args: string[]): Promise<void> {
|
|
9
|
+
const action = args[0] || "status"
|
|
10
|
+
const config = loadConfig()
|
|
11
|
+
const dense = config.dense || {}
|
|
12
|
+
|
|
13
|
+
if (action === "enable") {
|
|
14
|
+
saveConfig({ ...config, dense: { ...dense, enabled: true, model: args[1] || dense.model || DEFAULT_DENSE_MODEL } })
|
|
15
|
+
console.log(`Dense retrieval enabled (model: ${args[1] || dense.model || DEFAULT_DENSE_MODEL}). Run 'toon-memory dense build' once.`)
|
|
16
|
+
return
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
if (action === "disable") {
|
|
20
|
+
saveConfig({ ...config, dense: { ...dense, enabled: false } })
|
|
21
|
+
console.log("Dense retrieval disabled. BM25 recall remains active.")
|
|
22
|
+
return
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (action === "install") {
|
|
26
|
+
console.log("Install the optional embedder: npm install toon-memory-dense")
|
|
27
|
+
console.log("Then point to it with TOON_MEMORY_DENSE_MODULE=/absolute/path/to/module.js if it is not on the default resolution path.")
|
|
28
|
+
return
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (action === "build") {
|
|
32
|
+
const module = await loadDenseModule()
|
|
33
|
+
if (!module) {
|
|
34
|
+
console.error("Dense embedder not found. Run 'toon-memory dense install' first.")
|
|
35
|
+
process.exitCode = 1
|
|
36
|
+
return
|
|
37
|
+
}
|
|
38
|
+
const count = await buildVectors(readMemory(), module, dense.model || DEFAULT_DENSE_MODEL)
|
|
39
|
+
console.log(`Built vectors for ${count} entries in ${VECTORS_FILE}.`)
|
|
40
|
+
return
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const stored = readVectors()
|
|
44
|
+
console.log([
|
|
45
|
+
`dense: ${dense.enabled ? "enabled" : "disabled"}`,
|
|
46
|
+
`model: ${dense.model || DEFAULT_DENSE_MODEL}`,
|
|
47
|
+
`module: ${process.env.TOON_MEMORY_DENSE_MODULE || "toon-memory-dense"}`,
|
|
48
|
+
`vectors: ${existsSync(VECTORS_FILE) ? `${stored.vectors.size} entries, dim ${stored.dim}` : "not built"}`,
|
|
49
|
+
].join("\n"))
|
|
50
|
+
}
|
package/src/cli/instructions.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"
|
|
2
2
|
import { dirname } from "path"
|
|
3
3
|
import type { Agent } from "./types"
|
|
4
|
-
import { INSTRUCTION_CONTENT, OPENCODE_PASSIVE_INSTRUCTION } from "./constants"
|
|
4
|
+
import { INSTRUCTION_CONTENT, OPENCODE_PASSIVE_INSTRUCTION, INSTRUCTION_MARKER } from "./constants"
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Install instruction files for an agent.
|
|
@@ -22,7 +22,7 @@ export function installInstructions(agent: Agent): void {
|
|
|
22
22
|
|
|
23
23
|
if (existsSync(filePath)) {
|
|
24
24
|
const existing = readFileSync(filePath, "utf-8")
|
|
25
|
-
if (existing.includes(
|
|
25
|
+
if (existing.includes(INSTRUCTION_MARKER)) {
|
|
26
26
|
console.log(` Instructions already present in ${filePath}`)
|
|
27
27
|
return
|
|
28
28
|
}
|
|
@@ -2,56 +2,70 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"
|
|
|
2
2
|
import { join } from "path"
|
|
3
3
|
import type { Agent } from "./types"
|
|
4
4
|
import { projectRoot } from "./constants"
|
|
5
|
-
import { dumpMemoryMarkdown } from "./memory"
|
|
6
5
|
|
|
7
6
|
/**
|
|
8
|
-
* OpenCode plugin source with
|
|
9
|
-
*
|
|
10
|
-
*
|
|
7
|
+
* OpenCode plugin source with AMBIENT memory: a compact handoff brief is
|
|
8
|
+
* pushed into the system prompt on every turn, and signals are recorded
|
|
9
|
+
* automatically from user directives, tool errors and edits. Promotion to
|
|
10
|
+
* durable memory is deterministic and runs once at session idle.
|
|
11
11
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
12
|
+
* OpenCode 1.17+ delivers hooks via plugins. Only supported hooks are used:
|
|
13
|
+
* event, experimental.chat.system.transform, experimental.session.compacting,
|
|
14
|
+
* chat.message, tool.execute.before, tool.execute.after.
|
|
15
15
|
*/
|
|
16
16
|
export function opencodePluginContent(): string {
|
|
17
|
-
return `import * as
|
|
18
|
-
import * as path from "path"
|
|
17
|
+
return `import * as path from "path"
|
|
19
18
|
|
|
20
19
|
export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
21
20
|
const root = worktree || directory
|
|
22
|
-
|
|
23
|
-
|
|
21
|
+
let cachedBrief = ""
|
|
22
|
+
let cachedTask = ""
|
|
23
|
+
let cachedAt = 0
|
|
24
|
+
let lastTask = ""
|
|
25
|
+
let promoted = false
|
|
26
|
+
let dynamic = []
|
|
27
|
+
|
|
28
|
+
const run = async (cmd) => {
|
|
29
|
+
try { return (await cmd.cwd(root).text()).trim() } catch { return "" }
|
|
30
|
+
}
|
|
24
31
|
|
|
25
|
-
const
|
|
26
|
-
|
|
32
|
+
const brief = async () => {
|
|
33
|
+
const task = (lastTask || "").replace(/[\`$"]/g, " ").trim().slice(0, 200)
|
|
34
|
+
const now = Date.now()
|
|
35
|
+
if (cachedBrief && cachedTask === task && now - cachedAt < 5 * 60 * 1000) return cachedBrief
|
|
36
|
+
cachedBrief = task
|
|
37
|
+
? await run(\`TOON_MEMORY_TASK=\${JSON.stringify(task)} npx -y toon-memory brief\`)
|
|
38
|
+
: await run(\`npx -y toon-memory brief\`)
|
|
39
|
+
cachedTask = task
|
|
40
|
+
cachedAt = now
|
|
41
|
+
return cachedBrief
|
|
27
42
|
}
|
|
28
43
|
|
|
29
44
|
const recall = async (query, opts = {}) => {
|
|
30
45
|
try {
|
|
31
|
-
const args = { query, mode: "flat", budget:
|
|
46
|
+
const args = { query, mode: "flat", budget: "tiny", limit: 3, path_scope: opts.path_scope || "" }
|
|
32
47
|
if (opts.category) args.category = opts.category
|
|
33
|
-
const result = await $\`npx -y toon-memory mcp\`.
|
|
34
|
-
.
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
}))
|
|
40
|
-
.text()
|
|
48
|
+
const result = await run($\`npx -y toon-memory mcp\`.stdin(JSON.stringify({
|
|
49
|
+
jsonrpc: "2.0",
|
|
50
|
+
id: 1,
|
|
51
|
+
method: "tools/call",
|
|
52
|
+
params: { name: "memory_recall", arguments: args }
|
|
53
|
+
})))
|
|
41
54
|
const parsed = JSON.parse(result)
|
|
42
55
|
return parsed?.result?.content?.[0]?.text || ""
|
|
43
56
|
} catch { return "" }
|
|
44
57
|
}
|
|
45
58
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
return await recall(filePath, { budget: "tiny", path_scope: filePath, category: "warning" })
|
|
59
|
+
const record = async (type, summary, file, session) => {
|
|
60
|
+
if (!summary) return
|
|
61
|
+
await run($\`npx -y toon-memory signal --type \${type} --summary \${summary} --file \${file || ""} --session \${session || "opencode"}\`)
|
|
50
62
|
}
|
|
51
63
|
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
64
|
+
const inject = (key, text) => {
|
|
65
|
+
if (!text || text.includes("(empty)") || text.includes("No results")) return
|
|
66
|
+
dynamic = dynamic.filter((d) => d.key !== key)
|
|
67
|
+
dynamic.push({ key, text: text.slice(0, 400) })
|
|
68
|
+
if (dynamic.length > 2) dynamic.shift()
|
|
55
69
|
}
|
|
56
70
|
|
|
57
71
|
const pickPath = (args) => {
|
|
@@ -69,92 +83,88 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
69
83
|
return [basename, ...dirParts.slice(-2)].join(" ")
|
|
70
84
|
}
|
|
71
85
|
|
|
72
|
-
const
|
|
73
|
-
|
|
74
|
-
|
|
86
|
+
const extractPath = (text) => {
|
|
87
|
+
const match = text.match(/(?:file|path|source):\\s*([\\w/.\\-]+)/i)
|
|
88
|
+
return match ? match[1] : ""
|
|
75
89
|
}
|
|
76
90
|
|
|
77
|
-
// Edit/write-ish tools are where known risks matter most.
|
|
78
91
|
const isEditTool = (name) => {
|
|
79
92
|
if (!name) return false
|
|
80
93
|
return name === "edit" || name === "write" || name === "apply-patch" ||
|
|
81
94
|
name.includes("edit") || name.includes("write") || name.includes("patch")
|
|
82
95
|
}
|
|
83
96
|
|
|
97
|
+
const isDirective = (text) =>
|
|
98
|
+
/recuerda|siempre|nunca|no hagas|importante|ten cuidado|decidimos|must not|always|never/i.test(text)
|
|
99
|
+
|
|
84
100
|
return {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
101
|
+
event: async ({ event }) => {
|
|
102
|
+
const type = event?.type || ""
|
|
103
|
+
if (type === "session.created" || type === "session.updated") {
|
|
104
|
+
cachedBrief = ""
|
|
105
|
+
cachedTask = ""
|
|
106
|
+
cachedAt = 0
|
|
107
|
+
lastTask = ""
|
|
108
|
+
dynamic = []
|
|
109
|
+
promoted = false
|
|
110
|
+
}
|
|
111
|
+
if (type === "session.idle" && !promoted) {
|
|
112
|
+
promoted = true
|
|
113
|
+
await run($\`npx -y toon-memory promote\`)
|
|
114
|
+
}
|
|
90
115
|
},
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
116
|
+
|
|
117
|
+
"experimental.chat.system.transform": async (input, output) => {
|
|
118
|
+
const text = await brief()
|
|
119
|
+
if (text) output.system.push(text)
|
|
120
|
+
for (const d of dynamic) output.system.push(d.text)
|
|
121
|
+
},
|
|
122
|
+
|
|
123
|
+
"experimental.session.compacting": async (input, output) => {
|
|
124
|
+
const text = await brief()
|
|
125
|
+
if (text && Array.isArray(output?.context)) output.context.push(text)
|
|
96
126
|
},
|
|
127
|
+
|
|
128
|
+
"chat.message": async (input) => {
|
|
129
|
+
const parts = input?.parts || input?.message?.parts || []
|
|
130
|
+
const text = parts.map((p) => typeof p?.text === "string" ? p.text : "").join(" ")
|
|
131
|
+
lastTask = text.replace(/\s+/g, " ").trim().slice(0, 200)
|
|
132
|
+
if (isDirective(text)) {
|
|
133
|
+
await record("user_directive", text.replace(/\\s+/g, " ").slice(0, 280), "", input?.sessionID)
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
|
|
97
137
|
"tool.execute.before": async (input, output) => {
|
|
98
|
-
// Pre-edit risk surfacing: for edit/write tools, surface known
|
|
99
|
-
// warning entries for the target file BEFORE the tool runs.
|
|
100
138
|
try {
|
|
101
139
|
const toolName = input?.tool || ""
|
|
102
140
|
if (!isEditTool(toolName)) return
|
|
103
|
-
const
|
|
104
|
-
const filePath = pickPath(args)
|
|
141
|
+
const filePath = pickPath(output?.args || input?.args || {})
|
|
105
142
|
if (!filePath) return
|
|
106
|
-
const text = await
|
|
107
|
-
inject(
|
|
143
|
+
const text = await recall(filePath, { category: "warning" })
|
|
144
|
+
inject("risks:" + filePath, "⚠ KNOWN RISKS for " + filePath + ":\\n" + text)
|
|
108
145
|
} catch {}
|
|
109
146
|
},
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
// recall only memory relevant to that file, inject as context.
|
|
113
|
-
// Also proactively recalls entries scoped to the matched paths.
|
|
147
|
+
|
|
148
|
+
"tool.execute.after": async (input, output) => {
|
|
114
149
|
try {
|
|
115
150
|
const toolName = input?.tool || ""
|
|
116
|
-
const args = input?.args || {}
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
let filePath = pickPath(args)
|
|
120
|
-
|
|
121
|
-
// Also try to extract from tool output text
|
|
122
|
-
if (!filePath && input?.output) {
|
|
123
|
-
const outputText = typeof input.output === "string" ? input.output : ""
|
|
124
|
-
const fileMatch = outputText.match(/(?:file|path|source):\s*([\\w/.\\-]+)/i)
|
|
125
|
-
if (fileMatch) filePath = fileMatch[1]
|
|
126
|
-
}
|
|
151
|
+
const args = output?.args || input?.args || {}
|
|
152
|
+
const resultText = typeof output?.output === "string" ? output.output : ""
|
|
153
|
+
const filePath = pickPath(args) || extractPath(resultText)
|
|
127
154
|
|
|
128
155
|
if (filePath) {
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
const text = await recall(query, { budget: "tiny", path_scope: filePath })
|
|
132
|
-
inject(input, "toon-memory:" + filePath, text)
|
|
133
|
-
|
|
134
|
-
// Pre-edit risk block for edit/write tools (same key as the before
|
|
135
|
-
// hook — setContext overwrites, so no duplication when both fire).
|
|
156
|
+
const text = await recall(buildQuery(filePath), { path_scope: filePath })
|
|
157
|
+
inject("memory:" + filePath, text)
|
|
136
158
|
if (isEditTool(toolName)) {
|
|
137
|
-
|
|
138
|
-
inject(input, "toon-memory:risks:" + filePath, "⚠ KNOWN RISKS for " + filePath + ":\\n" + riskText)
|
|
159
|
+
await record("diff_pattern", "Edited " + filePath + " while implementing a change", filePath, input?.sessionID)
|
|
139
160
|
}
|
|
140
161
|
}
|
|
141
162
|
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
.replace(/^context_/, "")
|
|
148
|
-
.replace(/^file_/, "")
|
|
149
|
-
.replace(/^text_document_/, "")
|
|
150
|
-
.split("_")
|
|
151
|
-
.filter(Boolean)
|
|
152
|
-
.join(" ")
|
|
153
|
-
|
|
154
|
-
if (toolKeywords.length > 3) {
|
|
155
|
-
const text = await recall(toolKeywords, { budget: "tiny" })
|
|
156
|
-
inject(input, "toon-memory:" + toolName, text)
|
|
157
|
-
}
|
|
163
|
+
if (/error|failed|exception|fatal/i.test(resultText)) {
|
|
164
|
+
const line = resultText.split("\\n").find((l) => /error|failed|exception|fatal/i.test(l)) || ""
|
|
165
|
+
const signature = line.replace(/\\s+/g, " ").slice(0, 180)
|
|
166
|
+
inject("error:" + toolName, "⚠ Tool error: " + signature)
|
|
167
|
+
await record("error_fix", "Tool " + toolName + " failed: " + signature, filePath, input?.sessionID)
|
|
158
168
|
}
|
|
159
169
|
} catch {}
|
|
160
170
|
},
|
|
@@ -165,6 +175,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
165
175
|
|
|
166
176
|
/**
|
|
167
177
|
* Install the toon-memory OpenCode plugin and remove any stale `hooks` key.
|
|
178
|
+
* No 87 KB markdown dump: the brief is injected live through system.transform.
|
|
168
179
|
*/
|
|
169
180
|
export function installOpenCodePlugin(agent: Agent): void {
|
|
170
181
|
const pluginsDir = join(projectRoot, ".opencode", "plugins")
|
|
@@ -174,12 +185,6 @@ export function installOpenCodePlugin(agent: Agent): void {
|
|
|
174
185
|
writeFileSync(dest, opencodePluginContent())
|
|
175
186
|
console.log(` Plugin created at ${dest}`)
|
|
176
187
|
|
|
177
|
-
const instrDir = join(projectRoot, ".opencode", "instructions")
|
|
178
|
-
if (!existsSync(instrDir)) mkdirSync(instrDir, { recursive: true })
|
|
179
|
-
const instrFile = join(instrDir, "memory-autoload.md")
|
|
180
|
-
writeFileSync(instrFile, dumpMemoryMarkdown())
|
|
181
|
-
console.log(` Seeded ${instrFile}`)
|
|
182
|
-
|
|
183
188
|
const configPath = agent.local || agent.global
|
|
184
189
|
if (configPath && existsSync(configPath)) {
|
|
185
190
|
try {
|
package/src/cli/setup.ts
CHANGED
|
@@ -2,9 +2,45 @@ import { captureToggle } from "./capture-toggle"
|
|
|
2
2
|
import { init, uninstall, status, upgrade, stats, exportMemory, importMemory, dumpMemory, interactiveInstall } from "./commands"
|
|
3
3
|
import { watch } from "./watch"
|
|
4
4
|
import { viewer, viewerExport } from "../viewer"
|
|
5
|
+
import { printBrief, printDoctor, recordSignal, runPromotion } from "./ambient"
|
|
6
|
+
import { runSleep } from "./sleep"
|
|
7
|
+
import { runDense } from "./dense"
|
|
5
8
|
|
|
6
9
|
const args = process.argv.slice(2)
|
|
7
10
|
|
|
11
|
+
if (args[0] === "brief") {
|
|
12
|
+
printBrief(args.slice(1).join(" ") || process.env.TOON_MEMORY_TASK || "")
|
|
13
|
+
process.exit(0)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
if (args[0] === "doctor") {
|
|
17
|
+
printDoctor()
|
|
18
|
+
process.exit(0)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
if (args[0] === "signal") {
|
|
22
|
+
recordSignal(args.slice(1))
|
|
23
|
+
process.exit(0)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
if (args[0] === "promote") {
|
|
27
|
+
runPromotion(args.slice(1))
|
|
28
|
+
process.exit(0)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (args[0] === "sleep") {
|
|
32
|
+
const result = runSleep()
|
|
33
|
+
console.log(result.ran
|
|
34
|
+
? `Sleep complete: ${result.promoted} promoted, ${result.edges} edges, ${result.pruned} pruned, ${result.duplicates} duplicates.`
|
|
35
|
+
: "Sleep is disabled (config.sleep.enabled or TOON_MEMORY_SLEEP=1).")
|
|
36
|
+
process.exit(0)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
if (args[0] === "dense") {
|
|
40
|
+
await runDense(args.slice(1))
|
|
41
|
+
process.exit(0)
|
|
42
|
+
}
|
|
43
|
+
|
|
8
44
|
if (args[0] === "capture") {
|
|
9
45
|
captureToggle(args[1] === "on")
|
|
10
46
|
process.exit(0)
|
|
@@ -22,17 +58,22 @@ if (args[0] === "init") {
|
|
|
22
58
|
}
|
|
23
59
|
const rest = args.slice(1)
|
|
24
60
|
const agentNames: string[] = []
|
|
61
|
+
const scopes = new Set(["local", "global"])
|
|
62
|
+
const addAgents = (value: string) =>
|
|
63
|
+
value.split(",").map((a) => a.trim().toLowerCase()).filter(Boolean).forEach((a) => agentNames.push(a))
|
|
25
64
|
let scope: string | undefined
|
|
26
65
|
let i = 0
|
|
27
66
|
while (i < rest.length) {
|
|
28
67
|
if (rest[i] === "--agent" && rest[i + 1]) {
|
|
29
|
-
|
|
68
|
+
addAgents(rest[i + 1])
|
|
30
69
|
i += 2
|
|
31
70
|
} else if (rest[i] === "--scope" && rest[i + 1]) {
|
|
32
71
|
scope = rest[i + 1]
|
|
33
72
|
i += 2
|
|
34
73
|
} else if (rest[i] !== "--agent" && rest[i] !== "--scope") {
|
|
35
|
-
|
|
74
|
+
const token = rest[i].toLowerCase()
|
|
75
|
+
if (scopes.has(token) && !scope) scope = token
|
|
76
|
+
else addAgents(token)
|
|
36
77
|
i++
|
|
37
78
|
} else {
|
|
38
79
|
i++
|
|
@@ -118,9 +159,15 @@ Press 'r' in the terminal while serving to reload the graph.`)
|
|
|
118
159
|
/** Minimal usage string for unknown commands. */
|
|
119
160
|
function printUsage(): void {
|
|
120
161
|
console.log(`Usage: toon-memory <command> [options]
|
|
121
|
-
Commands: init, status, stats, export, import, watch, viewer, uninstall, capture, upgrade, mcp
|
|
162
|
+
Commands: init, status, stats, export, import, watch, viewer, uninstall, capture, upgrade, brief, doctor, signal, promote, sleep, dense, mcp
|
|
163
|
+
brief [task] — Print the compact handoff brief injected at session start
|
|
164
|
+
doctor — Check memory path, signals and injection channel
|
|
165
|
+
signal --type <t> --summary <s> [--file <f>] — Append one deterministic signal
|
|
166
|
+
promote [--threshold <0-1>] — Promote high-confidence signals into memory
|
|
167
|
+
sleep — Deterministic consolidation (opt-in: config.sleep.enabled)
|
|
168
|
+
dense <status|enable|disable|build|install> — Optional local embeddings with BM25 fallback
|
|
122
169
|
viewer [--export] [--port <n>] — Start an HTTP server with the graph viewer (press 'r' to reload). --export saves static HTML.
|
|
123
|
-
Init: toon-memory init [
|
|
170
|
+
Init: toon-memory init [local|global] [agent...] | --agent <name>[,<name>...] [--scope local|global]
|
|
124
171
|
Without --agent: interactive agent and scope selector.
|
|
125
172
|
With --agent: non-interactive installation (default: scope local).
|
|
126
173
|
Options: -v/--version, -h/--help
|