toon-memory 2.5.2 → 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.
- package/README.md +124 -3
- package/dist/cli/setup.js +463 -425
- package/mcp/server.js +2058 -1084
- package/package.json +4 -2
- package/skills/toon-memory.md +1 -0
- package/src/cli/agents.ts +184 -0
- package/src/cli/capture-toggle.ts +29 -0
- package/src/cli/commands.ts +532 -0
- package/src/cli/config-writer.ts +133 -0
- package/src/cli/constants.ts +56 -0
- package/src/cli/hooks.ts +202 -0
- package/src/cli/instructions.ts +35 -0
- package/src/cli/memory.ts +104 -0
- package/src/cli/opencode-plugin.ts +84 -0
- package/src/cli/setup.ts +5 -1596
- package/src/cli/types.ts +29 -0
- package/src/cli/watch.ts +169 -0
- package/src/lib/code-search.ts +192 -0
- package/src/lib/context.ts +658 -0
- package/src/lib/git.ts +263 -0
- package/src/lib/project-scan.ts +224 -0
- package/src/mcp/archive.ts +129 -0
- package/src/mcp/config.ts +88 -0
- package/src/mcp/consolidation.ts +70 -0
- package/src/mcp/crypto.ts +41 -0
- package/src/mcp/entries.ts +110 -0
- package/src/mcp/memory-io.ts +53 -0
- package/src/mcp/observations.ts +16 -0
- package/src/mcp/resources.ts +57 -0
- package/src/mcp/scoring.ts +77 -0
- package/src/mcp/server.ts +5 -1482
- package/src/mcp/tools.ts +826 -0
package/src/cli/setup.ts
CHANGED
|
@@ -1,1546 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { checkbox, select, confirm } from "@inquirer/prompts"
|
|
5
|
-
import { gzipSync, gunzipSync } from "zlib"
|
|
6
|
-
import { extractProjectDeps } from "../lib/vocab"
|
|
1
|
+
import { captureToggle } from "./capture-toggle"
|
|
2
|
+
import { init, uninstall, status, upgrade, stats, exportMemory, importMemory, dumpMemory, interactiveInstall } from "./commands"
|
|
3
|
+
import { watch } from "./watch"
|
|
7
4
|
|
|
8
|
-
const __dirname = dirname(fileURLToPath(import.meta.url))
|
|
9
|
-
const projectRoot = process.cwd()
|
|
10
|
-
const sourceDir = join(__dirname, "..", "..", "src")
|
|
11
|
-
|
|
12
|
-
/** Resolve this package's package.json by walking up from the module location.
|
|
13
|
-
* Setup logic may run from dist/cli/setup.js, so a fixed relative path is wrong. */
|
|
14
|
-
function resolvePackageJson(): string | null {
|
|
15
|
-
let dir = __dirname
|
|
16
|
-
while (true) {
|
|
17
|
-
const candidate = join(dir, "package.json")
|
|
18
|
-
if (existsSync(candidate)) {
|
|
19
|
-
try {
|
|
20
|
-
const p = JSON.parse(readFileSync(candidate, "utf-8"))
|
|
21
|
-
if (p && p.name === "toon-memory") return candidate
|
|
22
|
-
} catch {
|
|
23
|
-
// ignore and keep walking
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
const parent = dirname(dir)
|
|
27
|
-
if (parent === dir) return null
|
|
28
|
-
dir = parent
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
const HOME = process.env.HOME || process.env.USERPROFILE || "~"
|
|
32
|
-
|
|
33
|
-
/** Shared memory directory (agent-agnostic) */
|
|
34
|
-
const MEMORY_DIR = join(projectRoot, ".toon-memory", "memory")
|
|
35
|
-
|
|
36
|
-
/** Config format: "json" | "toml" | "jsonc" | "none" (instructions only) */
|
|
37
|
-
type AgentFormat = "json" | "toml" | "jsonc" | "none"
|
|
38
|
-
|
|
39
|
-
/** Supported AI coding agent configuration */
|
|
40
|
-
interface Agent {
|
|
41
|
-
name: string
|
|
42
|
-
global?: string
|
|
43
|
-
local?: string
|
|
44
|
-
mcpKey: string
|
|
45
|
-
format: AgentFormat
|
|
46
|
-
needsHooks: boolean
|
|
47
|
-
needsInstructions: boolean
|
|
48
|
-
instructionFile?: string
|
|
49
|
-
/** Claude Code-style hook events for activity capture (e.g. PostToolUse, Stop) */
|
|
50
|
-
captureJson?: string[]
|
|
51
|
-
/** Codex TOML hook events for activity capture (e.g. post_tool_use, stop) */
|
|
52
|
-
captureToml?: string[]
|
|
53
|
-
/** OpenCode: install the toon-memory plugin instead of a `hooks` config key */
|
|
54
|
-
needsPlugin?: boolean
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/** Path to the compiled capture script (dist/cli/capture.js) */
|
|
58
|
-
const CAPTURE_JS = join(__dirname, "capture.js")
|
|
59
|
-
|
|
60
|
-
/** Path to the compiled session-start reminder script (dist/cli/session-start.js) */
|
|
61
|
-
const SESSION_START_JS = join(__dirname, "session-start.js")
|
|
62
|
-
|
|
63
|
-
/** Hook script content for SessionStart reminder (prints active sessions + conflicts) */
|
|
64
|
-
function sessionStartHookContent(agentName: string): string {
|
|
65
|
-
return `#!/bin/bash
|
|
66
|
-
node "${SESSION_START_JS}" ${agentName}
|
|
67
|
-
exit 0
|
|
68
|
-
`
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/** Config file that holds the opt-in capture flag */
|
|
72
|
-
const CAPTURE_CONFIG = join(MEMORY_DIR, "config.json")
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
* Hook script content for activity capture. It is a no-op unless capture is
|
|
76
|
-
* explicitly enabled (env TOON_MEMORY_CAPTURE or config.json `"capture": true`),
|
|
77
|
-
* so registering it costs almost nothing when disabled.
|
|
78
|
-
*/
|
|
79
|
-
function captureHookContent(agentName: string): string {
|
|
80
|
-
return `#!/bin/bash
|
|
81
|
-
CFG="${CAPTURE_CONFIG}"
|
|
82
|
-
if [ -z "$TOON_MEMORY_CAPTURE" ]; then
|
|
83
|
-
if [ ! -f "$CFG" ]; then exit 0; fi
|
|
84
|
-
grep -q '"capture"[[:space:]]*:[[:space:]]*true' "$CFG" 2>/dev/null || exit 0
|
|
85
|
-
fi
|
|
86
|
-
node "${CAPTURE_JS}" ${agentName}
|
|
87
|
-
exit 0
|
|
88
|
-
`
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
/** Base instruction content for agents */
|
|
92
|
-
const INSTRUCTION_CONTENT = `# toon-memory
|
|
93
|
-
|
|
94
|
-
Persistent memory for this project. Use it to avoid re-investigating things.
|
|
95
|
-
|
|
96
|
-
## At the START of every session
|
|
97
|
-
1. Run memory_stats to see what's in memory.
|
|
98
|
-
2. If the user asks something that might be in memory, run memory_recall BEFORE reading files.
|
|
99
|
-
|
|
100
|
-
## When making decisions
|
|
101
|
-
- Before implementing a non-trivial change: memory_remember(category='decision')
|
|
102
|
-
- When you resolve a complex bug: memory_remember(category='bug')
|
|
103
|
-
- When you observe a code pattern: memory_remember(category='pattern')
|
|
104
|
-
|
|
105
|
-
## At the END of every session
|
|
106
|
-
- Save important decisions, bugs resolved, and patterns observed.
|
|
107
|
-
`
|
|
108
|
-
|
|
109
|
-
/**
|
|
110
|
-
* Passive instruction note for OpenCode. Unlike other agents, OpenCode gets its
|
|
111
|
-
* memory auto-injected via `.opencode/instructions/memory-autoload.md` (written
|
|
112
|
-
* by the plugin on session.created), so the agent should NOT be told to actively
|
|
113
|
-
* run memory_recall — that would duplicate context. memory_recall is only a
|
|
114
|
-
* fallback for deep/semantic queries beyond the auto-loaded dump.
|
|
115
|
-
*/
|
|
116
|
-
const OPENCODE_PASSIVE_INSTRUCTION = `# toon-memory
|
|
117
|
-
|
|
118
|
-
La memoria se auto-inyecta vía .opencode/instructions/memory-autoload.md; usa memory_recall solo como fallback.
|
|
119
|
-
`
|
|
120
|
-
|
|
121
|
-
/**
|
|
122
|
-
* Detect all supported AI coding agents on the system.
|
|
123
|
-
*
|
|
124
|
-
* Scans for configuration files in both global (~/.config/) and local
|
|
125
|
-
* (.opencode/, .vscode/, etc.) locations.
|
|
126
|
-
*
|
|
127
|
-
* @returns Array of detected agent configurations
|
|
128
|
-
*/
|
|
129
|
-
function detectAgents(): Agent[] {
|
|
130
|
-
const agents: Agent[] = []
|
|
131
|
-
|
|
132
|
-
// OpenCode
|
|
133
|
-
agents.push({
|
|
134
|
-
name: "opencode",
|
|
135
|
-
global: join(HOME, ".config", "opencode", "opencode.json"),
|
|
136
|
-
local: join(projectRoot, ".opencode", "opencode.json"),
|
|
137
|
-
mcpKey: "mcp",
|
|
138
|
-
format: "json",
|
|
139
|
-
needsHooks: false,
|
|
140
|
-
needsPlugin: true,
|
|
141
|
-
needsInstructions: true,
|
|
142
|
-
instructionFile: join(projectRoot, "AGENTS.md")
|
|
143
|
-
})
|
|
144
|
-
|
|
145
|
-
// VS Code / GitHub Copilot
|
|
146
|
-
agents.push({
|
|
147
|
-
name: "vscode/copilot",
|
|
148
|
-
local: join(projectRoot, ".vscode", "mcp.json"),
|
|
149
|
-
mcpKey: "servers",
|
|
150
|
-
format: "json",
|
|
151
|
-
needsHooks: false,
|
|
152
|
-
needsInstructions: false
|
|
153
|
-
})
|
|
154
|
-
|
|
155
|
-
// Claude Code
|
|
156
|
-
agents.push({
|
|
157
|
-
name: "claude",
|
|
158
|
-
global: join(HOME, ".claude", "settings.json"),
|
|
159
|
-
local: join(projectRoot, ".claude", "settings.json"),
|
|
160
|
-
mcpKey: "mcpServers",
|
|
161
|
-
format: "json",
|
|
162
|
-
needsHooks: true,
|
|
163
|
-
needsInstructions: true,
|
|
164
|
-
instructionFile: join(projectRoot, ".claude", "AGENTS.md"),
|
|
165
|
-
captureJson: ["PostToolUse", "Stop"]
|
|
166
|
-
})
|
|
167
|
-
|
|
168
|
-
// Cursor
|
|
169
|
-
agents.push({
|
|
170
|
-
name: "cursor",
|
|
171
|
-
local: join(projectRoot, ".cursor", "mcp.json"),
|
|
172
|
-
mcpKey: "mcpServers",
|
|
173
|
-
format: "json",
|
|
174
|
-
needsHooks: false,
|
|
175
|
-
needsInstructions: false
|
|
176
|
-
})
|
|
177
|
-
|
|
178
|
-
// Windsurf
|
|
179
|
-
agents.push({
|
|
180
|
-
name: "windsurf",
|
|
181
|
-
global: join(HOME, ".codeium", "windsurf", "mcp_config.json"),
|
|
182
|
-
mcpKey: "mcpServers",
|
|
183
|
-
format: "json",
|
|
184
|
-
needsHooks: false,
|
|
185
|
-
needsInstructions: false
|
|
186
|
-
})
|
|
187
|
-
|
|
188
|
-
// Cline
|
|
189
|
-
agents.push({
|
|
190
|
-
name: "cline",
|
|
191
|
-
local: join(projectRoot, ".cline", "mcp.json"),
|
|
192
|
-
mcpKey: "mcpServers",
|
|
193
|
-
format: "json",
|
|
194
|
-
needsHooks: false,
|
|
195
|
-
needsInstructions: false
|
|
196
|
-
})
|
|
197
|
-
|
|
198
|
-
// Continue
|
|
199
|
-
agents.push({
|
|
200
|
-
name: "continue",
|
|
201
|
-
local: join(projectRoot, ".continue", "config.json"),
|
|
202
|
-
mcpKey: "mcpServers",
|
|
203
|
-
format: "json",
|
|
204
|
-
needsHooks: false,
|
|
205
|
-
needsInstructions: false
|
|
206
|
-
})
|
|
207
|
-
|
|
208
|
-
// Codex CLI
|
|
209
|
-
agents.push({
|
|
210
|
-
name: "codex",
|
|
211
|
-
local: join(projectRoot, ".codex", "config.toml"),
|
|
212
|
-
mcpKey: "mcpServers",
|
|
213
|
-
format: "toml",
|
|
214
|
-
needsHooks: true,
|
|
215
|
-
needsInstructions: true,
|
|
216
|
-
instructionFile: join(projectRoot, ".codex", "AGENTS.md"),
|
|
217
|
-
captureToml: ["PostToolUse", "Stop"]
|
|
218
|
-
})
|
|
219
|
-
|
|
220
|
-
// Gemini CLI
|
|
221
|
-
agents.push({
|
|
222
|
-
name: "gemini",
|
|
223
|
-
local: join(projectRoot, ".gemini", "settings.json"),
|
|
224
|
-
mcpKey: "mcpServers",
|
|
225
|
-
format: "json",
|
|
226
|
-
needsHooks: true,
|
|
227
|
-
needsInstructions: true,
|
|
228
|
-
instructionFile: join(projectRoot, ".gemini", "GEMINI.md")
|
|
229
|
-
})
|
|
230
|
-
|
|
231
|
-
// Zed
|
|
232
|
-
agents.push({
|
|
233
|
-
name: "zed",
|
|
234
|
-
global: join(HOME, ".config", "zed", "settings.json"),
|
|
235
|
-
mcpKey: "mcp_servers",
|
|
236
|
-
format: "jsonc",
|
|
237
|
-
needsHooks: false,
|
|
238
|
-
needsInstructions: false
|
|
239
|
-
})
|
|
240
|
-
|
|
241
|
-
// Antigravity
|
|
242
|
-
agents.push({
|
|
243
|
-
name: "antigravity",
|
|
244
|
-
local: join(projectRoot, ".gemini", "config", "mcp_config.json"),
|
|
245
|
-
mcpKey: "mcpServers",
|
|
246
|
-
format: "json",
|
|
247
|
-
needsHooks: true,
|
|
248
|
-
needsInstructions: true,
|
|
249
|
-
instructionFile: join(projectRoot, "antigravity-cli", "AGENTS.md")
|
|
250
|
-
})
|
|
251
|
-
|
|
252
|
-
// Aider (instructions only, no MCP)
|
|
253
|
-
agents.push({
|
|
254
|
-
name: "aider",
|
|
255
|
-
mcpKey: "",
|
|
256
|
-
format: "none",
|
|
257
|
-
needsHooks: false,
|
|
258
|
-
needsInstructions: true,
|
|
259
|
-
instructionFile: join(projectRoot, "CONVENTIONS.md")
|
|
260
|
-
})
|
|
261
|
-
|
|
262
|
-
// KiloCode
|
|
263
|
-
agents.push({
|
|
264
|
-
name: "kilocode",
|
|
265
|
-
global: join(HOME, ".kilocode", "mcp_settings.json"),
|
|
266
|
-
mcpKey: "mcpServers",
|
|
267
|
-
format: "json",
|
|
268
|
-
needsHooks: false,
|
|
269
|
-
needsInstructions: true,
|
|
270
|
-
instructionFile: join(HOME, ".kilocode", "rules", "toon-memory.md")
|
|
271
|
-
})
|
|
272
|
-
|
|
273
|
-
// OpenClaw
|
|
274
|
-
agents.push({
|
|
275
|
-
name: "openclaw",
|
|
276
|
-
local: join(projectRoot, ".openclaw.json"),
|
|
277
|
-
mcpKey: "mcpServers",
|
|
278
|
-
format: "json",
|
|
279
|
-
needsHooks: false,
|
|
280
|
-
needsInstructions: false
|
|
281
|
-
})
|
|
282
|
-
|
|
283
|
-
// Kiro
|
|
284
|
-
agents.push({
|
|
285
|
-
name: "kiro",
|
|
286
|
-
local: join(projectRoot, ".kiro", "settings", "mcp.json"),
|
|
287
|
-
mcpKey: "mcpServers",
|
|
288
|
-
format: "json",
|
|
289
|
-
needsHooks: false,
|
|
290
|
-
needsInstructions: false
|
|
291
|
-
})
|
|
292
|
-
|
|
293
|
-
return agents
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
/**
|
|
297
|
-
* Install memory directory and initial data file.
|
|
298
|
-
*
|
|
299
|
-
* Creates `.toon-memory/memory/` directory and initial `data.toon` if needed.
|
|
300
|
-
* The MCP server handles all memory operations.
|
|
301
|
-
*/
|
|
302
|
-
function installMemoryDir(): void {
|
|
303
|
-
const memoryFile = join(MEMORY_DIR, "data.toon")
|
|
304
|
-
|
|
305
|
-
if (!existsSync(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true })
|
|
306
|
-
|
|
307
|
-
if (!existsSync(memoryFile)) {
|
|
308
|
-
writeFileSync(memoryFile, "version: 1\n[0|]\n")
|
|
309
|
-
console.log(" Created .toon-memory/memory/data.toon")
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
/**
|
|
314
|
-
* Add `.toon-memory/memory/` to `.gitignore` if not already present.
|
|
315
|
-
*/
|
|
316
|
-
function ensureGitignore(): void {
|
|
317
|
-
const gitignorePath = join(projectRoot, ".gitignore")
|
|
318
|
-
const entries = [".toon-memory/memory/", ".opencode/instructions/memory-autoload.md"]
|
|
319
|
-
|
|
320
|
-
if (!existsSync(gitignorePath)) {
|
|
321
|
-
writeFileSync(gitignorePath, `${entries.join("\n")}\n`)
|
|
322
|
-
console.log(" Created .gitignore with memory exclusion")
|
|
323
|
-
return
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
const content = readFileSync(gitignorePath, "utf-8")
|
|
327
|
-
const missing = entries.filter((e) => !content.includes(e))
|
|
328
|
-
if (missing.length > 0) {
|
|
329
|
-
writeFileSync(gitignorePath, `${content.trim()}\n${missing.join("\n")}\n`)
|
|
330
|
-
console.log(` Added to .gitignore: ${missing.join(", ")}`)
|
|
331
|
-
}
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
/**
|
|
335
|
-
* Install MCP server configuration for a JSON-format agent.
|
|
336
|
-
*
|
|
337
|
-
* Adds the `toon-memory` MCP server entry to the agent's config file.
|
|
338
|
-
* OpenCode uses a different format than other agents.
|
|
339
|
-
*/
|
|
340
|
-
function installJSONConfig(agent: Agent, scope: string): void {
|
|
341
|
-
const configPath = scope === "global" ? agent.global : agent.local
|
|
342
|
-
|
|
343
|
-
if (!configPath) {
|
|
344
|
-
console.log(` No ${scope} config path for ${agent.name}`)
|
|
345
|
-
return
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
const configDir = dirname(configPath)
|
|
349
|
-
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
350
|
-
|
|
351
|
-
let config: Record<string, any> = {}
|
|
352
|
-
if (existsSync(configPath)) {
|
|
353
|
-
try {
|
|
354
|
-
config = JSON.parse(readFileSync(configPath, "utf-8"))
|
|
355
|
-
} catch {
|
|
356
|
-
config = {}
|
|
357
|
-
}
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
const mcpKey = agent.mcpKey || "mcpServers"
|
|
361
|
-
if (!config[mcpKey]) config[mcpKey] = {}
|
|
362
|
-
|
|
363
|
-
if (agent.name === "opencode") {
|
|
364
|
-
config[mcpKey]["toon-memory"] = {
|
|
365
|
-
enabled: true,
|
|
366
|
-
type: "local",
|
|
367
|
-
command: ["npx", "-y", "toon-memory", "mcp"]
|
|
368
|
-
}
|
|
369
|
-
} else {
|
|
370
|
-
config[mcpKey]["toon-memory"] = {
|
|
371
|
-
command: "npx",
|
|
372
|
-
args: ["-y", "toon-memory", "mcp"]
|
|
373
|
-
}
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
writeFileSync(configPath, JSON.stringify(config, null, 2))
|
|
377
|
-
console.log(` MCP server added to ${configPath}`)
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
/**
|
|
381
|
-
* Install MCP server configuration for Codex CLI (TOML format).
|
|
382
|
-
*
|
|
383
|
-
* Writes a clean config.toml with the MCP server entry.
|
|
384
|
-
* If the file exists, it is overwritten.
|
|
385
|
-
*/
|
|
386
|
-
function installTOMLConfig(agent: Agent): void {
|
|
387
|
-
const configPath = agent.local
|
|
388
|
-
if (!configPath) return
|
|
389
|
-
|
|
390
|
-
const configDir = dirname(configPath)
|
|
391
|
-
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
392
|
-
|
|
393
|
-
const toml = `[mcpServers.toon-memory]
|
|
394
|
-
command = "npx"
|
|
395
|
-
args = ["-y", "toon-memory", "mcp"]
|
|
396
|
-
`
|
|
397
|
-
|
|
398
|
-
writeFileSync(configPath, toml)
|
|
399
|
-
console.log(` MCP server added to ${configPath}`)
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
/**
|
|
403
|
-
* Install MCP server configuration for Zed (JSONC format).
|
|
404
|
-
*
|
|
405
|
-
* Writes valid JSON to Zed's settings.json. If the file exists
|
|
406
|
-
* with comments, the user must merge manually.
|
|
407
|
-
*/
|
|
408
|
-
function installZedConfig(agent: Agent): void {
|
|
409
|
-
const configPath = agent.global
|
|
410
|
-
if (!configPath) return
|
|
411
|
-
|
|
412
|
-
const configDir = dirname(configPath)
|
|
413
|
-
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
414
|
-
|
|
415
|
-
let config: Record<string, any> = {}
|
|
416
|
-
if (existsSync(configPath)) {
|
|
417
|
-
try {
|
|
418
|
-
// Strip JSONC comments before parsing
|
|
419
|
-
const raw = readFileSync(configPath, "utf-8")
|
|
420
|
-
const stripped = raw.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "")
|
|
421
|
-
config = JSON.parse(stripped)
|
|
422
|
-
} catch {
|
|
423
|
-
config = {}
|
|
424
|
-
}
|
|
425
|
-
}
|
|
426
|
-
|
|
427
|
-
if (!config.mcp_servers) config.mcp_servers = {}
|
|
428
|
-
|
|
429
|
-
config.mcp_servers["toon-memory"] = {
|
|
430
|
-
command: "npx",
|
|
431
|
-
args: ["-y", "toon-memory", "mcp"]
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
writeFileSync(configPath, JSON.stringify(config, null, 2))
|
|
435
|
-
console.log(` MCP server added to ${configPath}`)
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
/**
|
|
439
|
-
* Install MCP config for an agent based on its format.
|
|
440
|
-
*/
|
|
441
|
-
function installMCPConfig(agent: Agent, scope: string): void {
|
|
442
|
-
if (agent.format === "none") {
|
|
443
|
-
console.log(` ${agent.name}: instructions only (no MCP)`)
|
|
444
|
-
return
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
if (agent.format === "toml") {
|
|
448
|
-
installTOMLConfig(agent)
|
|
449
|
-
} else if (agent.format === "jsonc") {
|
|
450
|
-
installZedConfig(agent)
|
|
451
|
-
} else {
|
|
452
|
-
installJSONConfig(agent, scope)
|
|
453
|
-
}
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
/**
|
|
457
|
-
* Install instruction files for an agent.
|
|
458
|
-
*
|
|
459
|
-
* Creates AGENTS.md, GEMINI.md, CONVENTIONS.md, etc. with
|
|
460
|
-
* reminders to use toon-memory tools.
|
|
461
|
-
*/
|
|
462
|
-
function installInstructions(agent: Agent): void {
|
|
463
|
-
if (!agent.needsInstructions || !agent.instructionFile) return
|
|
464
|
-
|
|
465
|
-
const filePath = agent.instructionFile
|
|
466
|
-
const fileDir = dirname(filePath)
|
|
467
|
-
|
|
468
|
-
if (!existsSync(fileDir)) mkdirSync(fileDir, { recursive: true })
|
|
469
|
-
|
|
470
|
-
const content = agent.name === "opencode"
|
|
471
|
-
? OPENCODE_PASSIVE_INSTRUCTION
|
|
472
|
-
: INSTRUCTION_CONTENT
|
|
473
|
-
|
|
474
|
-
if (existsSync(filePath)) {
|
|
475
|
-
const existing = readFileSync(filePath, "utf-8")
|
|
476
|
-
if (existing.includes("toon-memory") || existing.includes("memory_recall")) {
|
|
477
|
-
console.log(` Instructions already present in ${filePath}`)
|
|
478
|
-
return
|
|
479
|
-
}
|
|
480
|
-
// Append to existing file
|
|
481
|
-
writeFileSync(filePath, `${existing.trim()}\n\n${content}`)
|
|
482
|
-
console.log(` Appended toon-memory instructions to ${filePath}`)
|
|
483
|
-
} else {
|
|
484
|
-
writeFileSync(filePath, content)
|
|
485
|
-
console.log(` Created ${filePath}`)
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
/**
|
|
490
|
-
* Install SessionStart hook for agents that support it.
|
|
491
|
-
*
|
|
492
|
-
* Creates a shell script that reminds the agent to use memory tools,
|
|
493
|
-
* then registers it in the agent's config.
|
|
494
|
-
*/
|
|
495
|
-
function installHooks(agent: Agent): void {
|
|
496
|
-
if (!agent.needsHooks) return
|
|
497
|
-
|
|
498
|
-
const hookDir = join(projectRoot, ".toon-memory", "hooks")
|
|
499
|
-
if (!existsSync(hookDir)) mkdirSync(hookDir, { recursive: true })
|
|
500
|
-
|
|
501
|
-
const hookPath = join(hookDir, `session-start-${agent.name}.sh`)
|
|
502
|
-
writeFileSync(hookPath, sessionStartHookContent(agent.name))
|
|
503
|
-
chmodSync(hookPath, 0o755)
|
|
504
|
-
console.log(` Hook script created at ${hookPath}`)
|
|
505
|
-
|
|
506
|
-
// Register hook in agent config
|
|
507
|
-
if (agent.format === "toml" && agent.local) {
|
|
508
|
-
registerHookTOML(agent, hookPath)
|
|
509
|
-
} else if (agent.format === "json" || agent.format === "jsonc") {
|
|
510
|
-
registerHookJSON(agent, hookPath)
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
// Activity capture hooks (opt-in, no-op unless explicitly enabled)
|
|
514
|
-
if (agent.captureJson && agent.format === "json") {
|
|
515
|
-
const capPath = join(hookDir, `capture-${agent.name}.sh`)
|
|
516
|
-
writeFileSync(capPath, captureHookContent(agent.name))
|
|
517
|
-
chmodSync(capPath, 0o755)
|
|
518
|
-
console.log(` Capture hook created at ${capPath}`)
|
|
519
|
-
registerCaptureHookJSON(agent, capPath)
|
|
520
|
-
}
|
|
521
|
-
if (agent.captureToml && agent.format === "toml" && agent.local) {
|
|
522
|
-
const capPath = join(hookDir, `capture-${agent.name}.sh`)
|
|
523
|
-
writeFileSync(capPath, captureHookContent(agent.name))
|
|
524
|
-
chmodSync(capPath, 0o755)
|
|
525
|
-
console.log(` Capture hook created at ${capPath}`)
|
|
526
|
-
registerCaptureHookTOML(agent, capPath)
|
|
527
|
-
}
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
/** Register activity-capture hooks (PostToolUse/Stop) in a JSON agent config. */
|
|
531
|
-
function registerCaptureHookJSON(agent: Agent, scriptPath: string): void {
|
|
532
|
-
const configPath = agent.local || agent.global
|
|
533
|
-
if (!configPath) return
|
|
534
|
-
|
|
535
|
-
const configDir = dirname(configPath)
|
|
536
|
-
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
537
|
-
|
|
538
|
-
let config: Record<string, any> = {}
|
|
539
|
-
if (existsSync(configPath)) {
|
|
540
|
-
try {
|
|
541
|
-
config = JSON.parse(readFileSync(configPath, "utf-8"))
|
|
542
|
-
} catch {
|
|
543
|
-
config = {}
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
if (!config.hooks) config.hooks = {}
|
|
548
|
-
for (const event of agent.captureJson || []) {
|
|
549
|
-
if (!config.hooks[event]) config.hooks[event] = []
|
|
550
|
-
if (!config.hooks[event].some((h: any) => h.command === scriptPath)) {
|
|
551
|
-
config.hooks[event].push({ command: scriptPath })
|
|
552
|
-
}
|
|
553
|
-
}
|
|
554
|
-
|
|
555
|
-
writeFileSync(configPath, JSON.stringify(config, null, 2))
|
|
556
|
-
console.log(` Capture hooks registered in ${configPath}`)
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
/** Register activity-capture hooks (PostToolUse/Stop) in a Codex TOML config. */
|
|
560
|
-
function registerCaptureHookTOML(agent: Agent, scriptPath: string): void {
|
|
561
|
-
const configPath = agent.local
|
|
562
|
-
if (!configPath || !existsSync(configPath)) return
|
|
563
|
-
|
|
564
|
-
let content = readFileSync(configPath, "utf-8")
|
|
565
|
-
for (const event of agent.captureToml || []) {
|
|
566
|
-
if (content.includes(`event = "${event}"`)) continue
|
|
567
|
-
content += `\n[[hooks]]\nevent = "${event}"\ncommand = "${scriptPath}"\n`
|
|
568
|
-
}
|
|
569
|
-
|
|
570
|
-
writeFileSync(configPath, content)
|
|
571
|
-
console.log(` Capture hooks registered in ${configPath}`)
|
|
572
|
-
}
|
|
573
|
-
|
|
574
|
-
/** Register SessionStart hook in TOML config (Codex CLI, stable [[hooks]] format). */
|
|
575
|
-
function registerHookTOML(agent: Agent, hookPath: string): void {
|
|
576
|
-
const configPath = agent.local
|
|
577
|
-
if (!configPath || !existsSync(configPath)) return
|
|
578
|
-
|
|
579
|
-
let content = readFileSync(configPath, "utf-8")
|
|
580
|
-
if (content.includes('event = "SessionStart"')) {
|
|
581
|
-
console.log(` Hook already registered in ${configPath}`)
|
|
582
|
-
return
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
content += `\n[[hooks]]\nevent = "SessionStart"\ncommand = "${hookPath}"\n`
|
|
586
|
-
writeFileSync(configPath, content)
|
|
587
|
-
console.log(` Hook registered in ${configPath}`)
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
/**
|
|
591
|
-
* OpenCode plugin source with PASSIVE memory injection. OpenCode 1.17+ delivers
|
|
592
|
-
* hooks via plugins (not a top-level `hooks` config key), so `init` writes this
|
|
593
|
-
* file into `.opencode/plugins/`. The plugin:
|
|
594
|
-
* - on `session.created` runs `npx -y toon-memory dump` and writes the result to
|
|
595
|
-
* `.opencode/instructions/memory-autoload.md`, which OpenCode loads into every
|
|
596
|
-
* session automatically — no agent action required.
|
|
597
|
-
* - on `experimental.session.compacting` re-injects the dump into `output.context`
|
|
598
|
-
* so memory survives compaction.
|
|
599
|
-
* - on `tool.execute.after` keeps the opt-in activity capture (gated by
|
|
600
|
-
* TOON_MEMORY_CAPTURE).
|
|
601
|
-
* Uses `worktree || directory` as the project root.
|
|
602
|
-
*/
|
|
603
|
-
function opencodePluginContent(): string {
|
|
604
|
-
return `import * as fs from "fs"
|
|
605
|
-
|
|
606
|
-
export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
607
|
-
const root = worktree || directory
|
|
608
|
-
const INS = root + "/.opencode/instructions"
|
|
609
|
-
const OUT = INS + "/memory-autoload.md"
|
|
610
|
-
const dump = async () => {
|
|
611
|
-
return await $\`npx -y toon-memory dump\`.cwd(root).text()
|
|
612
|
-
}
|
|
613
|
-
const write = (text) => {
|
|
614
|
-
fs.mkdirSync(INS, { recursive: true })
|
|
615
|
-
fs.writeFileSync(OUT, text)
|
|
616
|
-
}
|
|
617
|
-
return {
|
|
618
|
-
"session.created": async () => {
|
|
619
|
-
try {
|
|
620
|
-
const out = await dump()
|
|
621
|
-
write(out)
|
|
622
|
-
} catch {}
|
|
623
|
-
},
|
|
624
|
-
"experimental.session.compacting": async ({ output }) => {
|
|
625
|
-
try {
|
|
626
|
-
const out = await dump()
|
|
627
|
-
if (Array.isArray(output?.context)) output.context.push(out)
|
|
628
|
-
} catch {}
|
|
629
|
-
},
|
|
630
|
-
"tool.execute.after": async (input) => {
|
|
631
|
-
if (!process.env.TOON_MEMORY_CAPTURE) return
|
|
632
|
-
const cap = directory + "/bin/cli/capture.js"
|
|
633
|
-
try {
|
|
634
|
-
const payload = JSON.stringify({
|
|
635
|
-
session_id: input?.session?.id ?? "",
|
|
636
|
-
tool_name: input?.tool ?? "",
|
|
637
|
-
tool_input: input?.args ?? {},
|
|
638
|
-
})
|
|
639
|
-
await $\`node \${cap} opencode\`.stdin(payload).quiet()
|
|
640
|
-
} catch {}
|
|
641
|
-
},
|
|
642
|
-
}
|
|
643
|
-
}
|
|
644
|
-
`
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
/**
|
|
648
|
-
* Install the toon-memory OpenCode plugin (auto-capture via hooks) and remove
|
|
649
|
-
* any stale top-level `hooks` key left by older versions.
|
|
650
|
-
*/
|
|
651
|
-
function installOpenCodePlugin(agent: Agent): void {
|
|
652
|
-
const pluginsDir = join(projectRoot, ".opencode", "plugins")
|
|
653
|
-
if (!existsSync(pluginsDir)) mkdirSync(pluginsDir, { recursive: true })
|
|
654
|
-
|
|
655
|
-
const dest = join(pluginsDir, "toon-memory.ts")
|
|
656
|
-
writeFileSync(dest, opencodePluginContent())
|
|
657
|
-
console.log(` Plugin created at ${dest}`)
|
|
658
|
-
|
|
659
|
-
// Seed the auto-loaded memory file at install time so the very first session
|
|
660
|
-
// already has memory in context (resolves session.created timing on first boot).
|
|
661
|
-
const instrDir = join(projectRoot, ".opencode", "instructions")
|
|
662
|
-
if (!existsSync(instrDir)) mkdirSync(instrDir, { recursive: true })
|
|
663
|
-
const instrFile = join(instrDir, "memory-autoload.md")
|
|
664
|
-
writeFileSync(instrFile, dumpMemoryMarkdown())
|
|
665
|
-
console.log(` Seeded ${instrFile}`)
|
|
666
|
-
|
|
667
|
-
const configPath = agent.local || agent.global
|
|
668
|
-
if (configPath && existsSync(configPath)) {
|
|
669
|
-
try {
|
|
670
|
-
const config = JSON.parse(readFileSync(configPath, "utf-8"))
|
|
671
|
-
if (config.hooks) {
|
|
672
|
-
delete config.hooks
|
|
673
|
-
writeFileSync(configPath, JSON.stringify(config, null, 2))
|
|
674
|
-
console.log(` Removed stale "hooks" key from ${configPath}`)
|
|
675
|
-
}
|
|
676
|
-
} catch {}
|
|
677
|
-
}
|
|
678
|
-
}
|
|
679
|
-
|
|
680
|
-
/**
|
|
681
|
-
* Install Antigravity hooks. Antigravity keeps hooks in a separate `hooks.json`
|
|
682
|
-
* (under .gemini/config/). The official schema maps arbitrary hook NAMES to
|
|
683
|
-
* event configs; each event wraps handlers in `hooks: [{ type, command }]`.
|
|
684
|
-
* Supported events: PreToolUse, PostToolUse, PreInvocation, PostInvocation, Stop.
|
|
685
|
-
* There is no SessionStart event (issue #180 open), so the session-start
|
|
686
|
-
* reminder runs on PreInvocation (fires before the model is called).
|
|
687
|
-
*/
|
|
688
|
-
const ANTIGRAVITY_HOOK_NAME = "toon-memory"
|
|
689
|
-
function registerAntigravityHooks(agent: Agent): void {
|
|
690
|
-
const hookDir = join(projectRoot, ".toon-memory", "hooks")
|
|
691
|
-
if (!existsSync(hookDir)) mkdirSync(hookDir, { recursive: true })
|
|
692
|
-
|
|
693
|
-
const sessionPath = join(hookDir, "session-start-antigravity.sh")
|
|
694
|
-
writeFileSync(sessionPath, sessionStartHookContent("antigravity"))
|
|
695
|
-
chmodSync(sessionPath, 0o755)
|
|
696
|
-
console.log(` Hook script created at ${sessionPath}`)
|
|
697
|
-
|
|
698
|
-
const capPath = join(hookDir, "capture-antigravity.sh")
|
|
699
|
-
writeFileSync(capPath, captureHookContent("antigravity"))
|
|
700
|
-
chmodSync(capPath, 0o755)
|
|
701
|
-
console.log(` Capture hook created at ${capPath}`)
|
|
702
|
-
|
|
703
|
-
const base = agent.local ? dirname(agent.local) : projectRoot
|
|
704
|
-
const hooksFile = join(base, "hooks.json")
|
|
705
|
-
mkdirSync(base, { recursive: true })
|
|
706
|
-
|
|
707
|
-
let cfg: Record<string, any> = {}
|
|
708
|
-
if (existsSync(hooksFile)) {
|
|
709
|
-
try {
|
|
710
|
-
cfg = JSON.parse(readFileSync(hooksFile, "utf-8"))
|
|
711
|
-
} catch {
|
|
712
|
-
cfg = {}
|
|
713
|
-
}
|
|
714
|
-
}
|
|
715
|
-
|
|
716
|
-
cfg[ANTIGRAVITY_HOOK_NAME] = {
|
|
717
|
-
PreInvocation: [{ type: "command", command: sessionPath }],
|
|
718
|
-
PostToolUse: [{ matcher: "*", hooks: [{ type: "command", command: capPath }] }],
|
|
719
|
-
Stop: [{ type: "command", command: capPath }],
|
|
720
|
-
}
|
|
721
|
-
|
|
722
|
-
writeFileSync(hooksFile, JSON.stringify(cfg, null, 2))
|
|
723
|
-
console.log(` Antigravity hooks registered in ${hooksFile}`)
|
|
724
|
-
}
|
|
725
|
-
|
|
726
|
-
/** Register SessionStart hook in JSON config */
|
|
727
|
-
function registerHookJSON(agent: Agent, hookPath: string): void {
|
|
728
|
-
const configPath = agent.format === "jsonc" ? agent.global : (agent.local || agent.global)
|
|
729
|
-
if (!configPath) return
|
|
730
|
-
|
|
731
|
-
const configDir = dirname(configPath)
|
|
732
|
-
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
733
|
-
|
|
734
|
-
let config: Record<string, any> = {}
|
|
735
|
-
if (existsSync(configPath)) {
|
|
736
|
-
try {
|
|
737
|
-
if (agent.format === "jsonc") {
|
|
738
|
-
const raw = readFileSync(configPath, "utf-8")
|
|
739
|
-
const stripped = raw.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "")
|
|
740
|
-
config = JSON.parse(stripped)
|
|
741
|
-
} else {
|
|
742
|
-
config = JSON.parse(readFileSync(configPath, "utf-8"))
|
|
743
|
-
}
|
|
744
|
-
} catch {
|
|
745
|
-
config = {}
|
|
746
|
-
}
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
// Claude Code / Gemini CLI format: `hooks.SessionStart` object
|
|
750
|
-
// (OpenCode uses a plugin instead; Antigravity uses its own hooks.json)
|
|
751
|
-
if (agent.name === "claude" || agent.name === "gemini") {
|
|
752
|
-
if (!config.hooks) config.hooks = {}
|
|
753
|
-
if (!config.hooks.SessionStart) config.hooks.SessionStart = []
|
|
754
|
-
if (!config.hooks.SessionStart.some((h: any) => h.command === hookPath)) {
|
|
755
|
-
config.hooks.SessionStart.push({ command: hookPath })
|
|
756
|
-
writeFileSync(configPath, JSON.stringify(config, null, 2))
|
|
757
|
-
console.log(` Hook registered in ${configPath}`)
|
|
758
|
-
}
|
|
759
|
-
return
|
|
760
|
-
}
|
|
761
|
-
}
|
|
762
|
-
|
|
763
|
-
/**
|
|
764
|
-
* Install everything for a single agent.
|
|
765
|
-
*/
|
|
766
|
-
function installForAgent(agent: Agent, scope: string): void {
|
|
767
|
-
console.log(`${agent.name}:`)
|
|
768
|
-
installMCPConfig(agent, scope)
|
|
769
|
-
installInstructions(agent)
|
|
770
|
-
if (agent.needsPlugin) installOpenCodePlugin(agent)
|
|
771
|
-
else if (agent.name === "antigravity") registerAntigravityHooks(agent)
|
|
772
|
-
else installHooks(agent)
|
|
773
|
-
}
|
|
774
|
-
|
|
775
|
-
/**
|
|
776
|
-
* Read/write the shared memory config.json, preserving unknown keys
|
|
777
|
-
* (e.g. `encrypted`, `capture`) so we never clobber sibling settings.
|
|
778
|
-
*/
|
|
779
|
-
function updateMemoryConfig(patch: Record<string, any>): void {
|
|
780
|
-
if (!existsSync(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true })
|
|
781
|
-
let cfg: Record<string, any> = {}
|
|
782
|
-
if (existsSync(CAPTURE_CONFIG)) {
|
|
783
|
-
try {
|
|
784
|
-
cfg = JSON.parse(readFileSync(CAPTURE_CONFIG, "utf-8"))
|
|
785
|
-
} catch {
|
|
786
|
-
cfg = {}
|
|
787
|
-
}
|
|
788
|
-
}
|
|
789
|
-
Object.assign(cfg, patch)
|
|
790
|
-
writeFileSync(CAPTURE_CONFIG, JSON.stringify(cfg, null, 2))
|
|
791
|
-
}
|
|
792
|
-
|
|
793
|
-
/**
|
|
794
|
-
* Interactive multi-select for agents using @inquirer/prompts.
|
|
795
|
-
* Returns the selected Agent array.
|
|
796
|
-
*/
|
|
797
|
-
async function promptAgentSelection(agents: Agent[]): Promise<Agent[]> {
|
|
798
|
-
return checkbox({
|
|
799
|
-
message: "¿Qué agentes quieres configurar?",
|
|
800
|
-
choices: agents.map((a) => ({
|
|
801
|
-
name: `${a.name} (${a.format === "none" ? "instrucciones" : a.global ? "local/global" : "solo local"})`,
|
|
802
|
-
value: a,
|
|
803
|
-
checked: true
|
|
804
|
-
}))
|
|
805
|
-
})
|
|
806
|
-
}
|
|
807
|
-
|
|
808
|
-
/**
|
|
809
|
-
* Initialize toon-memory. Behaviour depends on flags and TTY:
|
|
810
|
-
*
|
|
811
|
-
* - `--agent` flag → non-interactive install for the listed agents
|
|
812
|
-
* - No `--agent`, TTY present → interactive checkbox + scope prompt
|
|
813
|
-
* - No `--agent`, no TTY → install for ALL agents (CI fallback)
|
|
814
|
-
*/
|
|
815
|
-
async function init(scope?: string, agentFilter?: string[]): Promise<void> {
|
|
816
|
-
console.log("\n🧠 toon-memory init\n")
|
|
817
|
-
|
|
818
|
-
installMemoryDir()
|
|
819
|
-
|
|
820
|
-
// Hito 7 (B): derive a project-specific tag vocabulary from dependencies.
|
|
821
|
-
const deps = extractProjectDeps(projectRoot)
|
|
822
|
-
const depCount = Object.keys(deps).length
|
|
823
|
-
if (depCount > 0) {
|
|
824
|
-
updateMemoryConfig({ vocab: deps })
|
|
825
|
-
console.log(` Detected ${depCount} dependencies → auto-tag vocabulary written to config.json`)
|
|
826
|
-
}
|
|
827
|
-
|
|
828
|
-
const agents = detectAgents()
|
|
829
|
-
let selected: Agent[]
|
|
830
|
-
let finalScope = scope || "local"
|
|
831
|
-
|
|
832
|
-
if (agentFilter && agentFilter.length > 0) {
|
|
833
|
-
selected = agents.filter((a) => agentFilter.includes(a.name.toLowerCase()))
|
|
834
|
-
if (selected.length === 0) {
|
|
835
|
-
console.log(`Agentes no encontrados: ${agentFilter.join(", ")}`)
|
|
836
|
-
console.log(`Disponibles: ${agents.map((a) => a.name).join(", ")}`)
|
|
837
|
-
process.exit(1)
|
|
838
|
-
}
|
|
839
|
-
} else if (process.stdin.isTTY) {
|
|
840
|
-
selected = await promptAgentSelection(agents)
|
|
841
|
-
if (selected.length === 0) {
|
|
842
|
-
console.log("\nNo se seleccionaron agentes. Nada instalado.\n")
|
|
843
|
-
return
|
|
844
|
-
}
|
|
845
|
-
finalScope = await select({
|
|
846
|
-
message: "Alcance:",
|
|
847
|
-
choices: [
|
|
848
|
-
{ name: "Local (proyecto)", value: "local" },
|
|
849
|
-
{ name: "Global (~home)", value: "global" }
|
|
850
|
-
],
|
|
851
|
-
default: finalScope as "local" | "global"
|
|
852
|
-
})
|
|
853
|
-
const ok = await confirm({ message: "¿Proceder?", default: true })
|
|
854
|
-
if (!ok) {
|
|
855
|
-
console.log("\nInstalación cancelada.\n")
|
|
856
|
-
return
|
|
857
|
-
}
|
|
858
|
-
} else {
|
|
859
|
-
selected = agents
|
|
860
|
-
}
|
|
861
|
-
|
|
862
|
-
console.log(`\nInstalando (${finalScope}) — ${selected.map((a) => a.name).join(", ")}...\n`)
|
|
863
|
-
|
|
864
|
-
for (const agent of selected) {
|
|
865
|
-
installForAgent(agent, finalScope)
|
|
866
|
-
console.log("")
|
|
867
|
-
}
|
|
868
|
-
|
|
869
|
-
ensureGitignore()
|
|
870
|
-
|
|
871
|
-
console.log("Done! Restart your agent to use memory tools.\n")
|
|
872
|
-
}
|
|
873
|
-
|
|
874
|
-
/**
|
|
875
|
-
* Uninstall toon-memory from all detected agents.
|
|
876
|
-
*
|
|
877
|
-
* Removes MCP server configurations, instruction files, and hooks.
|
|
878
|
-
*/
|
|
879
|
-
function uninstall(): void {
|
|
880
|
-
console.log("\n🧠 toon-memory uninstaller\n")
|
|
881
|
-
|
|
882
|
-
const agents = detectAgents()
|
|
883
|
-
|
|
884
|
-
for (const agent of agents) {
|
|
885
|
-
// Remove MCP config from JSON files
|
|
886
|
-
if (agent.format === "json" || agent.format === "jsonc") {
|
|
887
|
-
const configs = [agent.global, agent.local].filter(Boolean) as string[]
|
|
888
|
-
|
|
889
|
-
for (const configPath of configs) {
|
|
890
|
-
if (!existsSync(configPath)) continue
|
|
891
|
-
|
|
892
|
-
try {
|
|
893
|
-
let config: Record<string, any>
|
|
894
|
-
if (agent.format === "jsonc") {
|
|
895
|
-
const raw = readFileSync(configPath, "utf-8")
|
|
896
|
-
const stripped = raw.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "")
|
|
897
|
-
config = JSON.parse(stripped)
|
|
898
|
-
} else {
|
|
899
|
-
config = JSON.parse(readFileSync(configPath, "utf-8"))
|
|
900
|
-
}
|
|
901
|
-
|
|
902
|
-
const mcpKey = agent.mcpKey || "mcpServers"
|
|
903
|
-
|
|
904
|
-
if (config[mcpKey]?.["toon-memory"]) {
|
|
905
|
-
delete config[mcpKey]["toon-memory"]
|
|
906
|
-
writeFileSync(configPath, JSON.stringify(config, null, 2))
|
|
907
|
-
console.log(` Removed MCP from ${agent.name} (${configPath})`)
|
|
908
|
-
}
|
|
909
|
-
} catch {}
|
|
910
|
-
}
|
|
911
|
-
}
|
|
912
|
-
|
|
913
|
-
// Remove TOML config
|
|
914
|
-
if (agent.format === "toml" && agent.local && existsSync(agent.local)) {
|
|
915
|
-
try {
|
|
916
|
-
let content = readFileSync(agent.local, "utf-8")
|
|
917
|
-
content = content.replace(/\[mcpServers\.toon-memory\][\s\S]*?(?=\n\[|$)/, "").trim() + "\n"
|
|
918
|
-
writeFileSync(agent.local, content)
|
|
919
|
-
console.log(` Removed MCP from ${agent.name} (${agent.local})`)
|
|
920
|
-
} catch {}
|
|
921
|
-
}
|
|
922
|
-
}
|
|
923
|
-
|
|
924
|
-
// Remove instruction files
|
|
925
|
-
for (const agent of agents) {
|
|
926
|
-
if (agent.instructionFile && existsSync(agent.instructionFile)) {
|
|
927
|
-
try {
|
|
928
|
-
const content = readFileSync(agent.instructionFile, "utf-8")
|
|
929
|
-
// Only remove if it's purely toon-memory instructions
|
|
930
|
-
if (content.includes(INSTRUCTION_CONTENT.trim()) && content.length < INSTRUCTION_CONTENT.length + 100) {
|
|
931
|
-
unlinkSync(agent.instructionFile)
|
|
932
|
-
console.log(` Removed ${agent.instructionFile}`)
|
|
933
|
-
}
|
|
934
|
-
} catch {}
|
|
935
|
-
}
|
|
936
|
-
}
|
|
937
|
-
|
|
938
|
-
// Remove hook scripts
|
|
939
|
-
const hookDir = join(projectRoot, ".toon-memory", "hooks")
|
|
940
|
-
if (existsSync(hookDir)) {
|
|
941
|
-
rmSync(hookDir, { recursive: true, force: true })
|
|
942
|
-
console.log(" Removed .toon-memory/hooks/")
|
|
943
|
-
}
|
|
944
|
-
|
|
945
|
-
// Remove legacy .opencode/tools/ if exists
|
|
946
|
-
const toolsFile = join(projectRoot, ".opencode", "tools", "memory.ts")
|
|
947
|
-
if (existsSync(toolsFile)) {
|
|
948
|
-
unlinkSync(toolsFile)
|
|
949
|
-
console.log(" Removed .opencode/tools/memory.ts")
|
|
950
|
-
}
|
|
951
|
-
|
|
952
|
-
// Remove OpenCode plugin
|
|
953
|
-
const ocPlugin = join(projectRoot, ".opencode", "plugins", "toon-memory.ts")
|
|
954
|
-
if (existsSync(ocPlugin)) {
|
|
955
|
-
unlinkSync(ocPlugin)
|
|
956
|
-
console.log(" Removed .opencode/plugins/toon-memory.ts")
|
|
957
|
-
}
|
|
958
|
-
|
|
959
|
-
// Remove toon-memory hook from Antigravity hooks.json (leave other hooks intact)
|
|
960
|
-
const agyHooks = join(projectRoot, ".gemini", "config", "hooks.json")
|
|
961
|
-
if (existsSync(agyHooks)) {
|
|
962
|
-
try {
|
|
963
|
-
const agyCfg = JSON.parse(readFileSync(agyHooks, "utf-8"))
|
|
964
|
-
if (agyCfg[ANTIGRAVITY_HOOK_NAME]) {
|
|
965
|
-
delete agyCfg[ANTIGRAVITY_HOOK_NAME]
|
|
966
|
-
if (Object.keys(agyCfg).length === 0) {
|
|
967
|
-
unlinkSync(agyHooks)
|
|
968
|
-
console.log(" Removed .gemini/config/hooks.json")
|
|
969
|
-
} else {
|
|
970
|
-
writeFileSync(agyHooks, JSON.stringify(agyCfg, null, 2))
|
|
971
|
-
console.log(" Removed toon-memory hook from .gemini/config/hooks.json")
|
|
972
|
-
}
|
|
973
|
-
}
|
|
974
|
-
} catch {
|
|
975
|
-
unlinkSync(agyHooks)
|
|
976
|
-
console.log(" Removed .gemini/config/hooks.json")
|
|
977
|
-
}
|
|
978
|
-
}
|
|
979
|
-
|
|
980
|
-
console.log("\n✅ toon-memory uninstalled from all agents\n")
|
|
981
|
-
}
|
|
982
|
-
|
|
983
|
-
/**
|
|
984
|
-
* Show toon-memory installation status.
|
|
985
|
-
*
|
|
986
|
-
* Displays version, memory entry count, and agent configuration status.
|
|
987
|
-
*/
|
|
988
|
-
function status(): void {
|
|
989
|
-
console.log("\n🧠 toon-memory status\n")
|
|
990
|
-
|
|
991
|
-
// Check npm package
|
|
992
|
-
const pkgPath = resolvePackageJson()
|
|
993
|
-
let version = "unknown"
|
|
994
|
-
if (pkgPath) {
|
|
995
|
-
try {
|
|
996
|
-
version = JSON.parse(readFileSync(pkgPath, "utf-8")).version
|
|
997
|
-
} catch {
|
|
998
|
-
// keep "unknown"
|
|
999
|
-
}
|
|
1000
|
-
}
|
|
1001
|
-
console.log(`Version: ${version}`)
|
|
1002
|
-
|
|
1003
|
-
// Check memory file
|
|
1004
|
-
const memoryFile = join(MEMORY_DIR, "data.toon")
|
|
1005
|
-
if (existsSync(memoryFile)) {
|
|
1006
|
-
const data = readFileSync(memoryFile, "utf-8")
|
|
1007
|
-
const lines = data.split("\n").filter((l: string) => l.startsWith(" ") && l.includes("|"))
|
|
1008
|
-
console.log(`Memory: ${lines.length} entries`)
|
|
1009
|
-
} else {
|
|
1010
|
-
console.log("Memory: not initialized")
|
|
1011
|
-
}
|
|
1012
|
-
|
|
1013
|
-
// Capture status
|
|
1014
|
-
let capture = false
|
|
1015
|
-
if (process.env.TOON_MEMORY_CAPTURE) capture = true
|
|
1016
|
-
else if (existsSync(CAPTURE_CONFIG)) {
|
|
1017
|
-
try {
|
|
1018
|
-
const c = JSON.parse(readFileSync(CAPTURE_CONFIG, "utf-8"))
|
|
1019
|
-
if (c.capture) capture = true
|
|
1020
|
-
} catch {}
|
|
1021
|
-
}
|
|
1022
|
-
console.log(`Capture: ${capture ? "enabled" : "disabled (opt-in)"}`)
|
|
1023
|
-
|
|
1024
|
-
// Check agent configs
|
|
1025
|
-
const agents = detectAgents()
|
|
1026
|
-
console.log("\nAgent configs:")
|
|
1027
|
-
|
|
1028
|
-
for (const agent of agents) {
|
|
1029
|
-
let configured = false
|
|
1030
|
-
|
|
1031
|
-
// Check MCP config
|
|
1032
|
-
if (agent.format === "json" || agent.format === "jsonc") {
|
|
1033
|
-
const configs = [agent.global, agent.local].filter(Boolean) as string[]
|
|
1034
|
-
|
|
1035
|
-
for (const configPath of configs) {
|
|
1036
|
-
if (!existsSync(configPath)) continue
|
|
1037
|
-
|
|
1038
|
-
try {
|
|
1039
|
-
let config: Record<string, any>
|
|
1040
|
-
if (agent.format === "jsonc") {
|
|
1041
|
-
const raw = readFileSync(configPath, "utf-8")
|
|
1042
|
-
const stripped = raw.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "")
|
|
1043
|
-
config = JSON.parse(stripped)
|
|
1044
|
-
} else {
|
|
1045
|
-
config = JSON.parse(readFileSync(configPath, "utf-8"))
|
|
1046
|
-
}
|
|
1047
|
-
|
|
1048
|
-
if (config[agent.mcpKey]?.["toon-memory"]) {
|
|
1049
|
-
configured = true
|
|
1050
|
-
}
|
|
1051
|
-
} catch {}
|
|
1052
|
-
}
|
|
1053
|
-
}
|
|
1054
|
-
|
|
1055
|
-
// Check TOML
|
|
1056
|
-
if (agent.format === "toml" && agent.local && existsSync(agent.local)) {
|
|
1057
|
-
const content = readFileSync(agent.local, "utf-8")
|
|
1058
|
-
if (content.includes("toon-memory")) configured = true
|
|
1059
|
-
}
|
|
1060
|
-
|
|
1061
|
-
// Check instructions
|
|
1062
|
-
const hasInstructions = agent.instructionFile ? existsSync(agent.instructionFile) : false
|
|
1063
|
-
|
|
1064
|
-
// Check hooks / plugin
|
|
1065
|
-
const hookPath = join(projectRoot, ".toon-memory", "hooks", `session-start-${agent.name}.sh`)
|
|
1066
|
-
let hasHooks = existsSync(hookPath)
|
|
1067
|
-
if (agent.needsPlugin) {
|
|
1068
|
-
hasHooks = existsSync(join(projectRoot, ".opencode", "plugins", "toon-memory.ts"))
|
|
1069
|
-
}
|
|
1070
|
-
|
|
1071
|
-
if (agent.format === "none") {
|
|
1072
|
-
console.log(` ${hasInstructions ? "✅" : "❌"} ${agent.name} (instructions only)`)
|
|
1073
|
-
} else {
|
|
1074
|
-
const mcpStatus = configured ? "✅" : "❌"
|
|
1075
|
-
const instrStatus = agent.needsInstructions ? (hasInstructions ? " 📝" : "") : ""
|
|
1076
|
-
const hookStatus = (agent.needsHooks || agent.needsPlugin) ? (hasHooks ? " 🪝" : "") : ""
|
|
1077
|
-
console.log(` ${mcpStatus} ${agent.name}${instrStatus}${hookStatus}`)
|
|
1078
|
-
}
|
|
1079
|
-
}
|
|
1080
|
-
|
|
1081
|
-
console.log("")
|
|
1082
|
-
}
|
|
1083
|
-
|
|
1084
|
-
/**
|
|
1085
|
-
* Upgrade toon-memory to the latest version.
|
|
1086
|
-
*/
|
|
1087
|
-
function upgrade(): void {
|
|
1088
|
-
console.log("\n🧠 toon-memory upgrade\n")
|
|
1089
|
-
|
|
1090
|
-
try {
|
|
1091
|
-
const pkgPath = resolvePackageJson()
|
|
1092
|
-
const currentVersion = pkgPath ? JSON.parse(readFileSync(pkgPath, "utf-8")).version : "unknown"
|
|
1093
|
-
|
|
1094
|
-
console.log(`Current version: ${currentVersion}`)
|
|
1095
|
-
console.log("\nTo upgrade, run:")
|
|
1096
|
-
console.log(" npm install -g toon-memory@latest")
|
|
1097
|
-
console.log("\nThen restart your agent.\n")
|
|
1098
|
-
} catch {
|
|
1099
|
-
console.log("To upgrade, run:")
|
|
1100
|
-
console.log(" npm install -g toon-memory@latest")
|
|
1101
|
-
console.log("\nThen restart your agent.\n")
|
|
1102
|
-
}
|
|
1103
|
-
}
|
|
1104
|
-
|
|
1105
|
-
/**
|
|
1106
|
-
* Display memory statistics.
|
|
1107
|
-
*/
|
|
1108
|
-
function stats(): void {
|
|
1109
|
-
console.log("\n🧠 toon-memory stats\n")
|
|
1110
|
-
|
|
1111
|
-
const memoryFile = join(MEMORY_DIR, "data.toon")
|
|
1112
|
-
|
|
1113
|
-
if (!existsSync(memoryFile)) {
|
|
1114
|
-
console.log("Memory not initialized. Run 'npx toon-memory init' first.\n")
|
|
1115
|
-
return
|
|
1116
|
-
}
|
|
1117
|
-
|
|
1118
|
-
const data = readFileSync(memoryFile, "utf-8")
|
|
1119
|
-
const lines = data.split("\n").filter((l: string) => l.startsWith(" ") && l.includes("|"))
|
|
1120
|
-
|
|
1121
|
-
const categories: Record<string, number> = {}
|
|
1122
|
-
let latestDate = ""
|
|
1123
|
-
|
|
1124
|
-
for (const line of lines) {
|
|
1125
|
-
const parts = line.trim().split("|")
|
|
1126
|
-
if (parts.length >= 7) {
|
|
1127
|
-
const category = parts[1]
|
|
1128
|
-
const date = parts[6]
|
|
1129
|
-
categories[category] = (categories[category] || 0) + 1
|
|
1130
|
-
if (date > latestDate) latestDate = date
|
|
1131
|
-
}
|
|
1132
|
-
}
|
|
1133
|
-
|
|
1134
|
-
console.log("📊 Memory Stats")
|
|
1135
|
-
console.log("━".repeat(20))
|
|
1136
|
-
console.log(`Total entries: ${lines.length}`)
|
|
1137
|
-
|
|
1138
|
-
for (const [cat, count] of Object.entries(categories)) {
|
|
1139
|
-
console.log(`├── ${cat}: ${count}`)
|
|
1140
|
-
}
|
|
1141
|
-
|
|
1142
|
-
console.log(`Last updated: ${latestDate || "never"}`)
|
|
1143
|
-
|
|
1144
|
-
const fileSize = Buffer.byteLength(data, "utf-8")
|
|
1145
|
-
console.log(`File size: ${(fileSize / 1024).toFixed(1)} KB`)
|
|
1146
|
-
console.log("")
|
|
1147
|
-
}
|
|
1148
|
-
|
|
1149
|
-
/**
|
|
1150
|
-
* Export memory to JSON format.
|
|
1151
|
-
*/
|
|
1152
|
-
function exportMemory(): void {
|
|
1153
|
-
console.log("\n🧠 toon-memory export\n")
|
|
1154
|
-
|
|
1155
|
-
const memoryFile = join(MEMORY_DIR, "data.toon")
|
|
1156
|
-
|
|
1157
|
-
if (!existsSync(memoryFile)) {
|
|
1158
|
-
console.log("Memory not initialized. Run 'npx toon-memory init' first.\n")
|
|
1159
|
-
return
|
|
1160
|
-
}
|
|
1161
|
-
|
|
1162
|
-
const data = readFileSync(memoryFile, "utf-8")
|
|
1163
|
-
const lines = data.split("\n").filter((l: string) => l.startsWith(" ") && l.includes("|"))
|
|
1164
|
-
|
|
1165
|
-
const entries = lines.map((line: string) => {
|
|
1166
|
-
const parts = line.trim().split("|")
|
|
1167
|
-
return {
|
|
1168
|
-
id: parts[0],
|
|
1169
|
-
category: parts[1],
|
|
1170
|
-
key: parts[2],
|
|
1171
|
-
content: parts[3],
|
|
1172
|
-
file: parts[4],
|
|
1173
|
-
tags: parts[5] ? parts[5].split(";") : [],
|
|
1174
|
-
date: parts[6]
|
|
1175
|
-
}
|
|
1176
|
-
})
|
|
1177
|
-
|
|
1178
|
-
const exportData = {
|
|
1179
|
-
project: basename(projectRoot),
|
|
1180
|
-
exported_at: new Date().toISOString(),
|
|
1181
|
-
entries,
|
|
1182
|
-
summaries: {}
|
|
1183
|
-
}
|
|
1184
|
-
|
|
1185
|
-
const outputPath = join(projectRoot, "toon-memory-export.json")
|
|
1186
|
-
writeFileSync(outputPath, JSON.stringify(exportData, null, 2))
|
|
1187
|
-
|
|
1188
|
-
console.log(`Exported ${entries.length} entries to:`)
|
|
1189
|
-
console.log(` ${outputPath}\n`)
|
|
1190
|
-
}
|
|
1191
|
-
|
|
1192
|
-
/**
|
|
1193
|
-
* Import memory from JSON file.
|
|
1194
|
-
*/
|
|
1195
|
-
function importMemory(): void {
|
|
1196
|
-
console.log("\n🧠 toon-memory import\n")
|
|
1197
|
-
|
|
1198
|
-
const importFile = process.argv[3]
|
|
1199
|
-
|
|
1200
|
-
if (!importFile) {
|
|
1201
|
-
console.log("Usage: npx toon-memory import <file.json>\n")
|
|
1202
|
-
return
|
|
1203
|
-
}
|
|
1204
|
-
|
|
1205
|
-
const importPath = importFile.startsWith("/") ? importFile : join(projectRoot, importFile)
|
|
1206
|
-
|
|
1207
|
-
if (!existsSync(importPath)) {
|
|
1208
|
-
console.log(`File not found: ${importPath}\n`)
|
|
1209
|
-
return
|
|
1210
|
-
}
|
|
1211
|
-
|
|
1212
|
-
let importData: any
|
|
1213
|
-
try {
|
|
1214
|
-
importData = JSON.parse(readFileSync(importPath, "utf-8"))
|
|
1215
|
-
} catch {
|
|
1216
|
-
console.log("Invalid JSON file\n")
|
|
1217
|
-
return
|
|
1218
|
-
}
|
|
1219
|
-
|
|
1220
|
-
if (!importData.entries || !Array.isArray(importData.entries)) {
|
|
1221
|
-
console.log("Invalid format: missing 'entries' array\n")
|
|
1222
|
-
return
|
|
1223
|
-
}
|
|
1224
|
-
|
|
1225
|
-
const memoryFile = join(MEMORY_DIR, "data.toon")
|
|
1226
|
-
|
|
1227
|
-
if (!existsSync(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true })
|
|
1228
|
-
|
|
1229
|
-
let existingKeys: string[] = []
|
|
1230
|
-
if (existsSync(memoryFile)) {
|
|
1231
|
-
const existing = readFileSync(memoryFile, "utf-8")
|
|
1232
|
-
existingKeys = existing.split("\n")
|
|
1233
|
-
.filter((l: string) => l.startsWith(" ") && l.includes("|"))
|
|
1234
|
-
.map((l: string) => l.trim().split("|")[2])
|
|
1235
|
-
}
|
|
1236
|
-
|
|
1237
|
-
const newEntries = importData.entries.filter((e: any) => !existingKeys.includes(e.key))
|
|
1238
|
-
|
|
1239
|
-
if (newEntries.length === 0) {
|
|
1240
|
-
console.log("No new entries to import (all keys already exist)\n")
|
|
1241
|
-
return
|
|
1242
|
-
}
|
|
1243
|
-
|
|
1244
|
-
const newLines = newEntries.map((e: any) => {
|
|
1245
|
-
const tags = Array.isArray(e.tags) ? e.tags.join(";") : (e.tags || "")
|
|
1246
|
-
return ` ${e.id}|${e.category}|${e.key}|${e.content}|${e.file}|${tags}|${e.date}`
|
|
1247
|
-
}).join("\n")
|
|
1248
|
-
|
|
1249
|
-
if (existsSync(memoryFile)) {
|
|
1250
|
-
const existing = readFileSync(memoryFile, "utf-8")
|
|
1251
|
-
const existingCount = existing.split("\n")
|
|
1252
|
-
.filter((l: string) => l.startsWith(" ") && l.includes("|")).length
|
|
1253
|
-
const updated = existing.replace(
|
|
1254
|
-
/entries\[\d+\|]/,
|
|
1255
|
-
`entries[${existingCount + newEntries.length}|]`
|
|
1256
|
-
) + "\n" + newLines
|
|
1257
|
-
writeFileSync(memoryFile, updated)
|
|
1258
|
-
} else {
|
|
1259
|
-
writeFileSync(memoryFile, `version: 1\nentries[${newEntries.length}|]{id|category|key|content|file|tags|date}:\n${newLines}\n`)
|
|
1260
|
-
}
|
|
1261
|
-
|
|
1262
|
-
console.log(`Imported ${newEntries.length} new entries`)
|
|
1263
|
-
console.log(`Skipped ${importData.entries.length - newEntries.length} duplicates\n`)
|
|
1264
|
-
}
|
|
1265
|
-
|
|
1266
|
-
/**
|
|
1267
|
-
* Render the project memory as markdown ready to be injected into agent
|
|
1268
|
-
* context. Reads `.toon-memory/memory/data.toon` (projectRoot = cwd), parses
|
|
1269
|
-
* entries and file summaries, and returns a string. If there is no memory
|
|
1270
|
-
* yet, returns a minimal "(empty)" document.
|
|
1271
|
-
*/
|
|
1272
|
-
function dumpMemoryMarkdown(): string {
|
|
1273
|
-
const memoryFile = join(MEMORY_DIR, "data.toon")
|
|
1274
|
-
|
|
1275
|
-
if (!existsSync(memoryFile)) {
|
|
1276
|
-
return "# toon-memory\n(empty)\n"
|
|
1277
|
-
}
|
|
1278
|
-
|
|
1279
|
-
const data = readFileSync(memoryFile, "utf-8")
|
|
1280
|
-
const lines = data.split("\n").filter((l: string) => l.startsWith(" ") && l.includes("|"))
|
|
1281
|
-
|
|
1282
|
-
const entries = lines.map((line: string) => {
|
|
1283
|
-
const parts = line.trim().split("|")
|
|
1284
|
-
return {
|
|
1285
|
-
id: parts[0] ?? "",
|
|
1286
|
-
category: parts[1] ?? "",
|
|
1287
|
-
key: parts[2] ?? "",
|
|
1288
|
-
content: parts[3] ?? "",
|
|
1289
|
-
file: parts[4] ?? "",
|
|
1290
|
-
tags: parts[5] ? parts[5].split(";").filter(Boolean) : [],
|
|
1291
|
-
date: parts[6] ?? "",
|
|
1292
|
-
}
|
|
1293
|
-
})
|
|
1294
|
-
|
|
1295
|
-
// File summaries live in the `summaries:` section as ` <file>: <summary>`.
|
|
1296
|
-
const allLines = data.split("\n")
|
|
1297
|
-
const summaryIdx = allLines.findIndex((l: string) => l.trim().startsWith("summaries:"))
|
|
1298
|
-
const summaries: { file: string; summary: string }[] = []
|
|
1299
|
-
if (summaryIdx !== -1) {
|
|
1300
|
-
for (const sl of allLines.slice(summaryIdx + 1)) {
|
|
1301
|
-
if (!sl.includes(":") || !sl.startsWith(" ")) continue
|
|
1302
|
-
const idx = sl.indexOf(":")
|
|
1303
|
-
const file = sl.slice(0, idx).trim()
|
|
1304
|
-
const summary = sl.slice(idx + 1).trim()
|
|
1305
|
-
if (file && summary) summaries.push({ file, summary })
|
|
1306
|
-
}
|
|
1307
|
-
}
|
|
1308
|
-
|
|
1309
|
-
if (entries.length === 0 && summaries.length === 0) {
|
|
1310
|
-
return "# toon-memory\n(empty)\n"
|
|
1311
|
-
}
|
|
1312
|
-
|
|
1313
|
-
const out: string[] = ["# toon-memory (auto-loaded)", ""]
|
|
1314
|
-
|
|
1315
|
-
for (const e of entries) {
|
|
1316
|
-
out.push(`## ${e.category}: ${e.key}`)
|
|
1317
|
-
out.push(e.content)
|
|
1318
|
-
if (e.file) out.push(`- file: ${e.file}`)
|
|
1319
|
-
if (e.tags.length) out.push(`- tags: ${e.tags.join(", ")}`)
|
|
1320
|
-
if (e.date) out.push(`- date: ${e.date}`)
|
|
1321
|
-
out.push("")
|
|
1322
|
-
}
|
|
1323
|
-
|
|
1324
|
-
if (summaries.length > 0) {
|
|
1325
|
-
out.push("## file summaries")
|
|
1326
|
-
for (const s of summaries) {
|
|
1327
|
-
out.push(`- ${s.file}: ${s.summary}`)
|
|
1328
|
-
}
|
|
1329
|
-
out.push("")
|
|
1330
|
-
}
|
|
1331
|
-
|
|
1332
|
-
return out.join("\n").trimEnd() + "\n"
|
|
1333
|
-
}
|
|
1334
|
-
|
|
1335
|
-
/**
|
|
1336
|
-
* Print the project memory as injectable markdown (the `dump` CLI command).
|
|
1337
|
-
*/
|
|
1338
|
-
function dumpMemory(): void {
|
|
1339
|
-
console.log(dumpMemoryMarkdown())
|
|
1340
|
-
}
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
/** Watch mode options */
|
|
1344
|
-
interface WatchOptions {
|
|
1345
|
-
interval: number
|
|
1346
|
-
maxBackups: number
|
|
1347
|
-
compress: boolean
|
|
1348
|
-
logFile: boolean
|
|
1349
|
-
logPath: string
|
|
1350
|
-
}
|
|
1351
|
-
|
|
1352
|
-
/** Parse watch CLI arguments into WatchOptions */
|
|
1353
|
-
function parseWatchOptions(args: string[]): WatchOptions {
|
|
1354
|
-
const opts: WatchOptions = {
|
|
1355
|
-
interval: 5,
|
|
1356
|
-
maxBackups: 10,
|
|
1357
|
-
compress: false,
|
|
1358
|
-
logFile: false,
|
|
1359
|
-
logPath: ""
|
|
1360
|
-
}
|
|
1361
|
-
|
|
1362
|
-
for (let i = 1; i < args.length; i++) {
|
|
1363
|
-
const arg = args[i]
|
|
1364
|
-
if (arg === "--compress" || arg === "-c") {
|
|
1365
|
-
opts.compress = true
|
|
1366
|
-
} else if (arg === "--log" || arg === "-l") {
|
|
1367
|
-
opts.logFile = true
|
|
1368
|
-
opts.logPath = args[++i] || join(MEMORY_DIR, "watch.log")
|
|
1369
|
-
} else if (arg === "--max-backups" || arg === "-m") {
|
|
1370
|
-
opts.maxBackups = parseInt(args[++i]) || 10
|
|
1371
|
-
} else if (!arg.startsWith("-")) {
|
|
1372
|
-
opts.interval = parseInt(arg) || 5
|
|
1373
|
-
}
|
|
1374
|
-
}
|
|
1375
|
-
|
|
1376
|
-
return opts
|
|
1377
|
-
}
|
|
1378
|
-
|
|
1379
|
-
/** Write a line to the watch log file */
|
|
1380
|
-
function writeWatchLog(logPath: string, message: string): void {
|
|
1381
|
-
if (!logPath) return
|
|
1382
|
-
const timestamp = new Date().toISOString()
|
|
1383
|
-
const logLine = `[${timestamp}] ${message}\n`
|
|
1384
|
-
writeFileSync(logPath, logLine, { flag: "a" })
|
|
1385
|
-
}
|
|
1386
|
-
|
|
1387
|
-
/** Get list of backup files sorted by creation time (oldest first) */
|
|
1388
|
-
function getBackupFiles(backupDir: string): string[] {
|
|
1389
|
-
if (!existsSync(backupDir)) return []
|
|
1390
|
-
|
|
1391
|
-
return readdirSync(backupDir)
|
|
1392
|
-
.filter(f => f.startsWith("backup-") && (f.endsWith(".toon") || f.endsWith(".gz")))
|
|
1393
|
-
.map(f => join(backupDir, f))
|
|
1394
|
-
.sort((a, b) => statSync(a).mtimeMs - statSync(b).mtimeMs)
|
|
1395
|
-
}
|
|
1396
|
-
|
|
1397
|
-
/** Remove oldest backups if we exceed maxBackups */
|
|
1398
|
-
function pruneBackups(backupDir: string, maxBackups: number): number {
|
|
1399
|
-
if (maxBackups <= 0) return 0
|
|
1400
|
-
|
|
1401
|
-
const files = getBackupFiles(backupDir)
|
|
1402
|
-
const excess = files.length - maxBackups
|
|
1403
|
-
|
|
1404
|
-
if (excess <= 0) return 0
|
|
1405
|
-
|
|
1406
|
-
for (let i = 0; i < excess; i++) {
|
|
1407
|
-
unlinkSync(files[i])
|
|
1408
|
-
}
|
|
1409
|
-
|
|
1410
|
-
return excess
|
|
1411
|
-
}
|
|
1412
|
-
|
|
1413
|
-
/** Compress content with gzip */
|
|
1414
|
-
function compressData(data: string): Buffer {
|
|
1415
|
-
return gzipSync(Buffer.from(data, "utf-8"))
|
|
1416
|
-
}
|
|
1417
|
-
|
|
1418
|
-
/**
|
|
1419
|
-
* Watch mode - backup memory every N minutes
|
|
1420
|
-
*/
|
|
1421
|
-
function watch(): void {
|
|
1422
|
-
console.log("\n🧠 toon-memory watch\n")
|
|
1423
|
-
|
|
1424
|
-
const memoryFile = join(MEMORY_DIR, "data.toon")
|
|
1425
|
-
const backupDir = join(MEMORY_DIR, "backups")
|
|
1426
|
-
|
|
1427
|
-
if (!existsSync(memoryFile)) {
|
|
1428
|
-
console.log("Memory not initialized. Run 'npx toon-memory init' first.\n")
|
|
1429
|
-
return
|
|
1430
|
-
}
|
|
1431
|
-
|
|
1432
|
-
if (!existsSync(backupDir)) mkdirSync(backupDir, { recursive: true })
|
|
1433
|
-
|
|
1434
|
-
const opts = parseWatchOptions(args)
|
|
1435
|
-
|
|
1436
|
-
if (opts.logFile) {
|
|
1437
|
-
const logDir = dirname(opts.logPath)
|
|
1438
|
-
if (!existsSync(logDir)) mkdirSync(logDir, { recursive: true })
|
|
1439
|
-
}
|
|
1440
|
-
|
|
1441
|
-
console.log(`Watching memory file every ${opts.interval} minutes...`)
|
|
1442
|
-
console.log(`Max backups: ${opts.maxBackups === 0 ? "unlimited" : opts.maxBackups}`)
|
|
1443
|
-
console.log(`Compression: ${opts.compress ? "enabled" : "disabled"}`)
|
|
1444
|
-
console.log(`Logging: ${opts.logFile ? `enabled (${opts.logPath})` : "disabled"}`)
|
|
1445
|
-
console.log(`Press Ctrl+C to stop\n`)
|
|
1446
|
-
|
|
1447
|
-
let lastContent = readFileSync(memoryFile, "utf-8")
|
|
1448
|
-
let lastHash = hashContent(lastContent)
|
|
1449
|
-
let backupCount = 0
|
|
1450
|
-
|
|
1451
|
-
if (opts.logFile) writeWatchLog(opts.logPath, "Watch started")
|
|
1452
|
-
|
|
1453
|
-
const backup = () => {
|
|
1454
|
-
try {
|
|
1455
|
-
const currentContent = readFileSync(memoryFile, "utf-8")
|
|
1456
|
-
const currentHash = hashContent(currentContent)
|
|
1457
|
-
|
|
1458
|
-
if (currentHash !== lastHash) {
|
|
1459
|
-
const timestamp = new Date().toISOString().replace(/[:.]/g, "-")
|
|
1460
|
-
const ext = opts.compress ? ".toon.gz" : ".toon"
|
|
1461
|
-
const backupFile = join(backupDir, `backup-${timestamp}${ext}`)
|
|
1462
|
-
|
|
1463
|
-
if (opts.compress) {
|
|
1464
|
-
writeFileSync(backupFile, compressData(currentContent))
|
|
1465
|
-
} else {
|
|
1466
|
-
writeFileSync(backupFile, currentContent)
|
|
1467
|
-
}
|
|
1468
|
-
|
|
1469
|
-
backupCount++
|
|
1470
|
-
console.log(`📦 Backup #${backupCount} created: ${timestamp}`)
|
|
1471
|
-
if (opts.logFile) writeWatchLog(opts.logPath, `Backup #${backupCount}: ${timestamp}`)
|
|
1472
|
-
|
|
1473
|
-
lastContent = currentContent
|
|
1474
|
-
lastHash = currentHash
|
|
1475
|
-
|
|
1476
|
-
const pruned = pruneBackups(backupDir, opts.maxBackups)
|
|
1477
|
-
if (pruned > 0) {
|
|
1478
|
-
console.log(`🗑️ Pruned ${pruned} old backup(s)`)
|
|
1479
|
-
if (opts.logFile) writeWatchLog(opts.logPath, `Pruned ${pruned} old backup(s)`)
|
|
1480
|
-
}
|
|
1481
|
-
}
|
|
1482
|
-
} catch (err) {
|
|
1483
|
-
const msg = `Error creating backup: ${(err as Error).message}`
|
|
1484
|
-
console.error(`❌ ${msg}`)
|
|
1485
|
-
if (opts.logFile) writeWatchLog(opts.logPath, msg)
|
|
1486
|
-
}
|
|
1487
|
-
}
|
|
1488
|
-
|
|
1489
|
-
/** Simple hash for change detection (not cryptographic) */
|
|
1490
|
-
function hashContent(content: string): string {
|
|
1491
|
-
let hash = 0
|
|
1492
|
-
for (let i = 0; i < content.length; i++) {
|
|
1493
|
-
const char = content.charCodeAt(i)
|
|
1494
|
-
hash = ((hash << 5) - hash) + char
|
|
1495
|
-
hash = hash & hash
|
|
1496
|
-
}
|
|
1497
|
-
return hash.toString(36)
|
|
1498
|
-
}
|
|
1499
|
-
|
|
1500
|
-
backup()
|
|
1501
|
-
const interval = setInterval(backup, opts.interval * 60 * 1000)
|
|
1502
|
-
|
|
1503
|
-
process.on("SIGINT", () => {
|
|
1504
|
-
clearInterval(interval)
|
|
1505
|
-
console.log(`\n✅ Watch stopped. ${backupCount} backups created.\n`)
|
|
1506
|
-
if (opts.logFile) writeWatchLog(opts.logPath, `Watch stopped. ${backupCount} backups created.`)
|
|
1507
|
-
process.exit(0)
|
|
1508
|
-
})
|
|
1509
|
-
|
|
1510
|
-
process.on("SIGTERM", () => {
|
|
1511
|
-
clearInterval(interval)
|
|
1512
|
-
process.exit(0)
|
|
1513
|
-
})
|
|
1514
|
-
}
|
|
1515
|
-
|
|
1516
|
-
/**
|
|
1517
|
-
* Enable or disable activity capture (the opt-in hook log).
|
|
1518
|
-
*/
|
|
1519
|
-
function captureToggle(enable: boolean): void {
|
|
1520
|
-
if (!existsSync(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true })
|
|
1521
|
-
|
|
1522
|
-
let config: Record<string, any> = {}
|
|
1523
|
-
if (existsSync(CAPTURE_CONFIG)) {
|
|
1524
|
-
try {
|
|
1525
|
-
config = JSON.parse(readFileSync(CAPTURE_CONFIG, "utf-8"))
|
|
1526
|
-
} catch {
|
|
1527
|
-
config = {}
|
|
1528
|
-
}
|
|
1529
|
-
}
|
|
1530
|
-
|
|
1531
|
-
config.capture = enable
|
|
1532
|
-
writeFileSync(CAPTURE_CONFIG, JSON.stringify(config, null, 2))
|
|
1533
|
-
|
|
1534
|
-
if (enable) {
|
|
1535
|
-
console.log("\n🔴 Captura de actividad HABILITADA.")
|
|
1536
|
-
console.log("Los hooks grabarán observaciones en .toon-memory/memory/observations.toon.")
|
|
1537
|
-
console.log("Revisa con `memory_captured` y promuévelas con `memory_remember`.\n")
|
|
1538
|
-
} else {
|
|
1539
|
-
console.log("\n⚪ Captura de actividad DESHABILITADA.\n")
|
|
1540
|
-
}
|
|
1541
|
-
}
|
|
1542
|
-
|
|
1543
|
-
// Main
|
|
1544
5
|
const args = process.argv.slice(2)
|
|
1545
6
|
|
|
1546
7
|
if (args[0] === "capture") {
|
|
@@ -1607,7 +68,7 @@ if (args[0] === "import") {
|
|
|
1607
68
|
}
|
|
1608
69
|
|
|
1609
70
|
if (args[0] === "watch") {
|
|
1610
|
-
watch()
|
|
71
|
+
watch(args)
|
|
1611
72
|
process.exit(0)
|
|
1612
73
|
}
|
|
1613
74
|
|
|
@@ -1621,7 +82,7 @@ console.log(`Comando desconocido: '${args[0]}'\n`)
|
|
|
1621
82
|
printUsage()
|
|
1622
83
|
process.exit(1)
|
|
1623
84
|
|
|
1624
|
-
/** Minimal usage string for unknown commands
|
|
85
|
+
/** Minimal usage string for unknown commands. */
|
|
1625
86
|
function printUsage(): void {
|
|
1626
87
|
console.log(`Uso: toon-memory <comando> [opciones]
|
|
1627
88
|
Comandos: init, status, stats, export, import, watch, uninstall, capture, upgrade, mcp
|
|
@@ -1631,55 +92,3 @@ Init: toon-memory init [--agent <nombre> --agent <nombre>...] [--scope local|glo
|
|
|
1631
92
|
Opciones: -v/--version, -h/--help
|
|
1632
93
|
Sin argumentos inicia el instalador interactivo.`)
|
|
1633
94
|
}
|
|
1634
|
-
|
|
1635
|
-
/**
|
|
1636
|
-
* Guided interactive installer: pick agents, choose local vs global scope,
|
|
1637
|
-
* confirm, then install. Requires a TTY; otherwise prints a non-interactive hint.
|
|
1638
|
-
*/
|
|
1639
|
-
async function interactiveInstall(): Promise<void> {
|
|
1640
|
-
if (!process.stdin.isTTY) {
|
|
1641
|
-
console.log("\n🧠 toon-memory — la instalación interactiva requiere una terminal.")
|
|
1642
|
-
console.log("Ejecuta 'toon-memory init [--agent <nombre>]' para instalación no interactiva.\n")
|
|
1643
|
-
return
|
|
1644
|
-
}
|
|
1645
|
-
|
|
1646
|
-
const agents = detectAgents()
|
|
1647
|
-
const selected = await promptAgentSelection(agents)
|
|
1648
|
-
if (selected.length === 0) {
|
|
1649
|
-
console.log("\nNo se seleccionaron agentes. Nada instalado.\n")
|
|
1650
|
-
return
|
|
1651
|
-
}
|
|
1652
|
-
|
|
1653
|
-
const scope = await select({
|
|
1654
|
-
message: "Alcance:",
|
|
1655
|
-
choices: [
|
|
1656
|
-
{ name: "Local (proyecto)", value: "local" },
|
|
1657
|
-
{ name: "Global (~home)", value: "global" }
|
|
1658
|
-
]
|
|
1659
|
-
})
|
|
1660
|
-
|
|
1661
|
-
const ok = await confirm({ message: "¿Proceder?", default: true })
|
|
1662
|
-
if (!ok) {
|
|
1663
|
-
console.log("\nInstalación cancelada.\n")
|
|
1664
|
-
return
|
|
1665
|
-
}
|
|
1666
|
-
|
|
1667
|
-
console.log(`\nInstalando (${scope}) — ${selected.map((a) => a.name).join(", ")}...\n`)
|
|
1668
|
-
installMemoryDir()
|
|
1669
|
-
|
|
1670
|
-
const deps = extractProjectDeps(projectRoot)
|
|
1671
|
-
if (Object.keys(deps).length > 0) {
|
|
1672
|
-
updateMemoryConfig({ vocab: deps })
|
|
1673
|
-
console.log(` Detected ${Object.keys(deps).length} dependencies → auto-tag vocabulary written to config.json`)
|
|
1674
|
-
}
|
|
1675
|
-
|
|
1676
|
-
for (const agent of selected) {
|
|
1677
|
-
installForAgent(agent, scope)
|
|
1678
|
-
console.log("")
|
|
1679
|
-
}
|
|
1680
|
-
|
|
1681
|
-
ensureGitignore()
|
|
1682
|
-
|
|
1683
|
-
console.log("Done! Restart your agent to use memory tools.")
|
|
1684
|
-
console.log("Run 'npx toon-memory uninstall' to remove.\n")
|
|
1685
|
-
}
|