toon-memory 2.5.1 → 2.7.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.
@@ -0,0 +1,56 @@
1
+ import { existsSync, readFileSync, mkdirSync, writeFileSync } from "fs"
2
+ import { dirname, join } from "path"
3
+
4
+ export const projectRoot = process.cwd()
5
+ export const HOME = process.env.HOME || process.env.USERPROFILE || "~"
6
+
7
+ /** Shared memory directory (agent-agnostic) */
8
+ export const MEMORY_DIR = join(projectRoot, ".toon-memory", "memory")
9
+
10
+ /**
11
+ * Directory containing the running CLI script.
12
+ * Derived from process.argv[1] — avoids __dirname / import.meta.url issues
13
+ * in ESM bundles with top-level await.
14
+ */
15
+ const scriptDir = dirname(process.argv[1] || process.cwd())
16
+
17
+ /** Path to the compiled capture script (dist/cli/capture.js) */
18
+ export const CAPTURE_JS = join(scriptDir, "capture.js")
19
+
20
+ /** Path to the compiled session-start reminder script (dist/cli/session-start.js) */
21
+ export const SESSION_START_JS = join(scriptDir, "session-start.js")
22
+
23
+ /** Config file that holds the opt-in capture flag */
24
+ export const CAPTURE_CONFIG = join(MEMORY_DIR, "config.json")
25
+
26
+ export const ANTIGRAVITY_HOOK_NAME = "toon-memory"
27
+
28
+ /** Base instruction content for agents */
29
+ export const INSTRUCTION_CONTENT = `# toon-memory
30
+
31
+ Persistent memory for this project. Use it to avoid re-investigating things.
32
+
33
+ ## At the START of every session
34
+ 1. Run memory_stats to see what's in memory.
35
+ 2. If the user asks something that might be in memory, run memory_recall BEFORE reading files.
36
+
37
+ ## When making decisions
38
+ - Before implementing a non-trivial change: memory_remember(category='decision')
39
+ - When you resolve a complex bug: memory_remember(category='bug')
40
+ - When you observe a code pattern: memory_remember(category='pattern')
41
+
42
+ ## At the END of every session
43
+ - Save important decisions, bugs resolved, and patterns observed.
44
+ `
45
+
46
+ /**
47
+ * Passive instruction note for OpenCode. Unlike other agents, OpenCode gets its
48
+ * memory auto-injected via `.opencode/instructions/memory-autoload.md` (written
49
+ * by the plugin on session.created), so the agent should NOT be told to actively
50
+ * run memory_recall — that would duplicate context. memory_recall is only a
51
+ * fallback for deep/semantic queries beyond the auto-loaded dump.
52
+ */
53
+ export const OPENCODE_PASSIVE_INSTRUCTION = `# toon-memory
54
+
55
+ La memoria se auto-inyecta vía .opencode/instructions/memory-autoload.md; usa memory_recall solo como fallback.
56
+ `
@@ -0,0 +1,202 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "fs"
2
+ import { dirname, join } from "path"
3
+ import type { Agent } from "./types"
4
+ import { projectRoot, CAPTURE_JS, SESSION_START_JS, CAPTURE_CONFIG, ANTIGRAVITY_HOOK_NAME } from "./constants"
5
+
6
+ /** Hook script content for SessionStart reminder */
7
+ export function sessionStartHookContent(agentName: string): string {
8
+ return `#!/bin/bash
9
+ node "${SESSION_START_JS}" ${agentName}
10
+ exit 0
11
+ `
12
+ }
13
+
14
+ /**
15
+ * Hook script content for activity capture. It is a no-op unless capture is
16
+ * explicitly enabled (env TOON_MEMORY_CAPTURE or config.json `"capture": true`).
17
+ */
18
+ export function captureHookContent(agentName: string): string {
19
+ return `#!/bin/bash
20
+ CFG="${CAPTURE_CONFIG}"
21
+ if [ -z "$TOON_MEMORY_CAPTURE" ]; then
22
+ if [ ! -f "$CFG" ]; then exit 0; fi
23
+ grep -q '"capture"[[:space:]]*:[[:space:]]*true' "$CFG" 2>/dev/null || exit 0
24
+ fi
25
+ node "${CAPTURE_JS}" ${agentName}
26
+ exit 0
27
+ `
28
+ }
29
+
30
+ /**
31
+ * Install SessionStart hook for agents that support it.
32
+ * Creates a shell script and registers it in the agent's config.
33
+ */
34
+ export function installHooks(agent: Agent): void {
35
+ if (!agent.needsHooks) return
36
+
37
+ const hookDir = join(projectRoot, ".toon-memory", "hooks")
38
+ if (!existsSync(hookDir)) mkdirSync(hookDir, { recursive: true })
39
+
40
+ const hookPath = join(hookDir, `session-start-${agent.name}.sh`)
41
+ writeFileSync(hookPath, sessionStartHookContent(agent.name))
42
+ chmodSync(hookPath, 0o755)
43
+ console.log(` Hook script created at ${hookPath}`)
44
+
45
+ if (agent.format === "toml" && agent.local) {
46
+ registerHookTOML(agent, hookPath)
47
+ } else if (agent.format === "json" || agent.format === "jsonc") {
48
+ registerHookJSON(agent, hookPath)
49
+ }
50
+
51
+ if (agent.captureJson && agent.format === "json") {
52
+ const capPath = join(hookDir, `capture-${agent.name}.sh`)
53
+ writeFileSync(capPath, captureHookContent(agent.name))
54
+ chmodSync(capPath, 0o755)
55
+ console.log(` Capture hook created at ${capPath}`)
56
+ registerCaptureHookJSON(agent, capPath)
57
+ }
58
+ if (agent.captureToml && agent.format === "toml" && agent.local) {
59
+ const capPath = join(hookDir, `capture-${agent.name}.sh`)
60
+ writeFileSync(capPath, captureHookContent(agent.name))
61
+ chmodSync(capPath, 0o755)
62
+ console.log(` Capture hook created at ${capPath}`)
63
+ registerCaptureHookTOML(agent, capPath)
64
+ }
65
+ }
66
+
67
+ /** Register activity-capture hooks (PostToolUse/Stop) in a JSON agent config. */
68
+ export function registerCaptureHookJSON(agent: Agent, scriptPath: string): void {
69
+ const configPath = agent.local || agent.global
70
+ if (!configPath) return
71
+
72
+ const configDir = dirname(configPath)
73
+ if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
74
+
75
+ let config: Record<string, any> = {}
76
+ if (existsSync(configPath)) {
77
+ try {
78
+ config = JSON.parse(readFileSync(configPath, "utf-8"))
79
+ } catch {
80
+ config = {}
81
+ }
82
+ }
83
+
84
+ if (!config.hooks) config.hooks = {}
85
+ for (const event of agent.captureJson || []) {
86
+ if (!config.hooks[event]) config.hooks[event] = []
87
+ if (!config.hooks[event].some((h: any) => h.command === scriptPath)) {
88
+ config.hooks[event].push({ command: scriptPath })
89
+ }
90
+ }
91
+
92
+ writeFileSync(configPath, JSON.stringify(config, null, 2))
93
+ console.log(` Capture hooks registered in ${configPath}`)
94
+ }
95
+
96
+ /** Register activity-capture hooks (PostToolUse/Stop) in a Codex TOML config. */
97
+ export function registerCaptureHookTOML(agent: Agent, scriptPath: string): void {
98
+ const configPath = agent.local
99
+ if (!configPath || !existsSync(configPath)) return
100
+
101
+ let content = readFileSync(configPath, "utf-8")
102
+ for (const event of agent.captureToml || []) {
103
+ if (content.includes(`event = "${event}"`)) continue
104
+ content += `\n[[hooks]]\nevent = "${event}"\ncommand = "${scriptPath}"\n`
105
+ }
106
+
107
+ writeFileSync(configPath, content)
108
+ console.log(` Capture hooks registered in ${configPath}`)
109
+ }
110
+
111
+ /** Register SessionStart hook in TOML config (Codex CLI). */
112
+ export function registerHookTOML(agent: Agent, hookPath: string): void {
113
+ const configPath = agent.local
114
+ if (!configPath || !existsSync(configPath)) return
115
+
116
+ let content = readFileSync(configPath, "utf-8")
117
+ if (content.includes('event = "SessionStart"')) {
118
+ console.log(` Hook already registered in ${configPath}`)
119
+ return
120
+ }
121
+
122
+ content += `\n[[hooks]]\nevent = "SessionStart"\ncommand = "${hookPath}"\n`
123
+ writeFileSync(configPath, content)
124
+ console.log(` Hook registered in ${configPath}`)
125
+ }
126
+
127
+ /** Register SessionStart hook in JSON config (Claude Code / Gemini CLI). */
128
+ export function registerHookJSON(agent: Agent, hookPath: string): void {
129
+ const configPath = agent.format === "jsonc" ? agent.global : (agent.local || agent.global)
130
+ if (!configPath) return
131
+
132
+ const configDir = dirname(configPath)
133
+ if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
134
+
135
+ let config: Record<string, any> = {}
136
+ if (existsSync(configPath)) {
137
+ try {
138
+ if (agent.format === "jsonc") {
139
+ const raw = readFileSync(configPath, "utf-8")
140
+ const stripped = raw.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "")
141
+ config = JSON.parse(stripped)
142
+ } else {
143
+ config = JSON.parse(readFileSync(configPath, "utf-8"))
144
+ }
145
+ } catch {
146
+ config = {}
147
+ }
148
+ }
149
+
150
+ if (agent.name === "claude" || agent.name === "gemini") {
151
+ if (!config.hooks) config.hooks = {}
152
+ if (!config.hooks.SessionStart) config.hooks.SessionStart = []
153
+ if (!config.hooks.SessionStart.some((h: any) => h.command === hookPath)) {
154
+ config.hooks.SessionStart.push({ command: hookPath })
155
+ writeFileSync(configPath, JSON.stringify(config, null, 2))
156
+ console.log(` Hook registered in ${configPath}`)
157
+ }
158
+ return
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Install Antigravity hooks. Antigravity keeps hooks in a separate `hooks.json`
164
+ * (under .gemini/config/). The official schema maps arbitrary hook NAMES to
165
+ * event configs; each event wraps handlers in `hooks: [{ type, command }]`.
166
+ */
167
+ export function registerAntigravityHooks(agent: Agent): void {
168
+ const hookDir = join(projectRoot, ".toon-memory", "hooks")
169
+ if (!existsSync(hookDir)) mkdirSync(hookDir, { recursive: true })
170
+
171
+ const sessionPath = join(hookDir, "session-start-antigravity.sh")
172
+ writeFileSync(sessionPath, sessionStartHookContent("antigravity"))
173
+ chmodSync(sessionPath, 0o755)
174
+ console.log(` Hook script created at ${sessionPath}`)
175
+
176
+ const capPath = join(hookDir, "capture-antigravity.sh")
177
+ writeFileSync(capPath, captureHookContent("antigravity"))
178
+ chmodSync(capPath, 0o755)
179
+ console.log(` Capture hook created at ${capPath}`)
180
+
181
+ const base = agent.local ? dirname(agent.local) : projectRoot
182
+ const hooksFile = join(base, "hooks.json")
183
+ mkdirSync(base, { recursive: true })
184
+
185
+ let cfg: Record<string, any> = {}
186
+ if (existsSync(hooksFile)) {
187
+ try {
188
+ cfg = JSON.parse(readFileSync(hooksFile, "utf-8"))
189
+ } catch {
190
+ cfg = {}
191
+ }
192
+ }
193
+
194
+ cfg[ANTIGRAVITY_HOOK_NAME] = {
195
+ PreInvocation: [{ type: "command", command: sessionPath }],
196
+ PostToolUse: [{ matcher: "*", hooks: [{ type: "command", command: capPath }] }],
197
+ Stop: [{ type: "command", command: capPath }],
198
+ }
199
+
200
+ writeFileSync(hooksFile, JSON.stringify(cfg, null, 2))
201
+ console.log(` Antigravity hooks registered in ${hooksFile}`)
202
+ }
@@ -0,0 +1,35 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"
2
+ import { dirname } from "path"
3
+ import type { Agent } from "./types"
4
+ import { INSTRUCTION_CONTENT, OPENCODE_PASSIVE_INSTRUCTION } from "./constants"
5
+
6
+ /**
7
+ * Install instruction files for an agent.
8
+ * Creates AGENTS.md, GEMINI.md, CONVENTIONS.md, etc. with
9
+ * reminders to use toon-memory tools.
10
+ */
11
+ export function installInstructions(agent: Agent): void {
12
+ if (!agent.needsInstructions || !agent.instructionFile) return
13
+
14
+ const filePath = agent.instructionFile
15
+ const fileDir = dirname(filePath)
16
+
17
+ if (!existsSync(fileDir)) mkdirSync(fileDir, { recursive: true })
18
+
19
+ const content = agent.name === "opencode"
20
+ ? OPENCODE_PASSIVE_INSTRUCTION
21
+ : INSTRUCTION_CONTENT
22
+
23
+ if (existsSync(filePath)) {
24
+ const existing = readFileSync(filePath, "utf-8")
25
+ if (existing.includes("toon-memory") || existing.includes("memory_recall")) {
26
+ console.log(` Instructions already present in ${filePath}`)
27
+ return
28
+ }
29
+ writeFileSync(filePath, `${existing.trim()}\n\n${content}`)
30
+ console.log(` Appended toon-memory instructions to ${filePath}`)
31
+ } else {
32
+ writeFileSync(filePath, content)
33
+ console.log(` Created ${filePath}`)
34
+ }
35
+ }
@@ -0,0 +1,104 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"
2
+ import { join } from "path"
3
+ import { MEMORY_DIR, projectRoot } from "./constants"
4
+
5
+ /**
6
+ * Install memory directory and initial data file.
7
+ * Creates `.toon-memory/memory/` directory and initial `data.toon` if needed.
8
+ */
9
+ export function installMemoryDir(): void {
10
+ const memoryFile = join(MEMORY_DIR, "data.toon")
11
+
12
+ if (!existsSync(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true })
13
+
14
+ if (!existsSync(memoryFile)) {
15
+ writeFileSync(memoryFile, "version: 1\n[0|]\n")
16
+ console.log(" Created .toon-memory/memory/data.toon")
17
+ }
18
+ }
19
+
20
+ /**
21
+ * Add `.toon-memory/memory/` to `.gitignore` if not already present.
22
+ */
23
+ export function ensureGitignore(): void {
24
+ const gitignorePath = join(projectRoot, ".gitignore")
25
+ const entries = [".toon-memory/memory/", ".opencode/instructions/memory-autoload.md"]
26
+
27
+ if (!existsSync(gitignorePath)) {
28
+ writeFileSync(gitignorePath, `${entries.join("\n")}\n`)
29
+ console.log(" Created .gitignore with memory exclusion")
30
+ return
31
+ }
32
+
33
+ const content = readFileSync(gitignorePath, "utf-8")
34
+ const missing = entries.filter((e) => !content.includes(e))
35
+ if (missing.length > 0) {
36
+ writeFileSync(gitignorePath, `${content.trim()}\n${missing.join("\n")}\n`)
37
+ console.log(` Added to .gitignore: ${missing.join(", ")}`)
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Render the project memory as markdown ready to be injected into agent context.
43
+ */
44
+ export function dumpMemoryMarkdown(): string {
45
+ const memoryFile = join(MEMORY_DIR, "data.toon")
46
+
47
+ if (!existsSync(memoryFile)) {
48
+ return "# toon-memory\n(empty)\n"
49
+ }
50
+
51
+ const data = readFileSync(memoryFile, "utf-8")
52
+ const lines = data.split("\n").filter((l: string) => l.startsWith(" ") && l.includes("|"))
53
+
54
+ const entries = lines.map((line: string) => {
55
+ const parts = line.trim().split("|")
56
+ return {
57
+ id: parts[0] ?? "",
58
+ category: parts[1] ?? "",
59
+ key: parts[2] ?? "",
60
+ content: parts[3] ?? "",
61
+ file: parts[4] ?? "",
62
+ tags: parts[5] ? parts[5].split(";").filter(Boolean) : [],
63
+ date: parts[6] ?? "",
64
+ }
65
+ })
66
+
67
+ const allLines = data.split("\n")
68
+ const summaryIdx = allLines.findIndex((l: string) => l.trim().startsWith("summaries:"))
69
+ const summaries: { file: string; summary: string }[] = []
70
+ if (summaryIdx !== -1) {
71
+ for (const sl of allLines.slice(summaryIdx + 1)) {
72
+ if (!sl.includes(":") || !sl.startsWith(" ")) continue
73
+ const idx = sl.indexOf(":")
74
+ const file = sl.slice(0, idx).trim()
75
+ const summary = sl.slice(idx + 1).trim()
76
+ if (file && summary) summaries.push({ file, summary })
77
+ }
78
+ }
79
+
80
+ if (entries.length === 0 && summaries.length === 0) {
81
+ return "# toon-memory\n(empty)\n"
82
+ }
83
+
84
+ const out: string[] = ["# toon-memory (auto-loaded)", ""]
85
+
86
+ for (const e of entries) {
87
+ out.push(`## ${e.category}: ${e.key}`)
88
+ out.push(e.content)
89
+ if (e.file) out.push(`- file: ${e.file}`)
90
+ if (e.tags.length) out.push(`- tags: ${e.tags.join(", ")}`)
91
+ if (e.date) out.push(`- date: ${e.date}`)
92
+ out.push("")
93
+ }
94
+
95
+ if (summaries.length > 0) {
96
+ out.push("## file summaries")
97
+ for (const s of summaries) {
98
+ out.push(`- ${s.file}: ${s.summary}`)
99
+ }
100
+ out.push("")
101
+ }
102
+
103
+ return out.join("\n").trimEnd() + "\n"
104
+ }
@@ -0,0 +1,84 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"
2
+ import { join } from "path"
3
+ import type { Agent } from "./types"
4
+ import { projectRoot } from "./constants"
5
+ import { dumpMemoryMarkdown } from "./memory"
6
+
7
+ /**
8
+ * OpenCode plugin source with PASSIVE memory injection. OpenCode 1.17+ delivers
9
+ * hooks via plugins (not a top-level `hooks` config key), so `init` writes this
10
+ * file into `.opencode/plugins/`.
11
+ */
12
+ export function opencodePluginContent(): string {
13
+ return `import * as fs from "fs"
14
+
15
+ export const ToonMemory = async ({ $, directory, worktree }) => {
16
+ const root = worktree || directory
17
+ const INS = root + "/.opencode/instructions"
18
+ const OUT = INS + "/memory-autoload.md"
19
+ const dump = async () => {
20
+ return await $\`npx -y toon-memory dump\`.cwd(root).text()
21
+ }
22
+ const write = (text) => {
23
+ fs.mkdirSync(INS, { recursive: true })
24
+ fs.writeFileSync(OUT, text)
25
+ }
26
+ return {
27
+ "session.created": async () => {
28
+ try {
29
+ const out = await dump()
30
+ write(out)
31
+ } catch {}
32
+ },
33
+ "experimental.session.compacting": async ({ output }) => {
34
+ try {
35
+ const out = await dump()
36
+ if (Array.isArray(output?.context)) output.context.push(out)
37
+ } catch {}
38
+ },
39
+ "tool.execute.after": async (input) => {
40
+ if (!process.env.TOON_MEMORY_CAPTURE) return
41
+ const cap = directory + "/bin/cli/capture.js"
42
+ try {
43
+ const payload = JSON.stringify({
44
+ session_id: input?.session?.id ?? "",
45
+ tool_name: input?.tool ?? "",
46
+ tool_input: input?.args ?? {},
47
+ })
48
+ await $\`node \${cap} opencode\`.stdin(payload).quiet()
49
+ } catch {}
50
+ },
51
+ }
52
+ }
53
+ `
54
+ }
55
+
56
+ /**
57
+ * Install the toon-memory OpenCode plugin and remove any stale `hooks` key.
58
+ */
59
+ export function installOpenCodePlugin(agent: Agent): void {
60
+ const pluginsDir = join(projectRoot, ".opencode", "plugins")
61
+ if (!existsSync(pluginsDir)) mkdirSync(pluginsDir, { recursive: true })
62
+
63
+ const dest = join(pluginsDir, "toon-memory.ts")
64
+ writeFileSync(dest, opencodePluginContent())
65
+ console.log(` Plugin created at ${dest}`)
66
+
67
+ const instrDir = join(projectRoot, ".opencode", "instructions")
68
+ if (!existsSync(instrDir)) mkdirSync(instrDir, { recursive: true })
69
+ const instrFile = join(instrDir, "memory-autoload.md")
70
+ writeFileSync(instrFile, dumpMemoryMarkdown())
71
+ console.log(` Seeded ${instrFile}`)
72
+
73
+ const configPath = agent.local || agent.global
74
+ if (configPath && existsSync(configPath)) {
75
+ try {
76
+ const config = JSON.parse(readFileSync(configPath, "utf-8"))
77
+ if (config.hooks) {
78
+ delete config.hooks
79
+ writeFileSync(configPath, JSON.stringify(config, null, 2))
80
+ console.log(` Removed stale "hooks" key from ${configPath}`)
81
+ }
82
+ } catch {}
83
+ }
84
+ }