toon-memory 2.0.0 → 2.2.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 +219 -21
- package/dist/cli/capture.js +276 -0
- package/dist/cli/session-start.js +192 -0
- package/dist/cli/setup.js +123 -21
- package/dist/cli/toon-memory.js +3 -2
- package/mcp/server.js +647 -72
- package/package.json +5 -3
- package/skills/toon-memory.md +44 -10
- package/src/cli/capture.ts +187 -0
- package/src/cli/session-start.ts +70 -0
- package/src/cli/setup.ts +148 -15
- package/src/lib/graph.ts +200 -0
- package/src/lib/lock.ts +120 -0
- package/src/lib/sessions.ts +225 -0
- package/src/mcp/server.ts +411 -63
- package/src/memory.ts +1 -1
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "toon-memory",
|
|
3
|
-
"version": "2.
|
|
4
|
-
"description": "Persistent memory system for AI coding agents using TOON format (
|
|
3
|
+
"version": "2.2.0",
|
|
4
|
+
"description": "Persistent memory system for AI coding agents using TOON format (22% fewer tokens than JSON, measured)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"toon-memory": "./bin/toon-memory.js"
|
|
@@ -20,9 +20,10 @@
|
|
|
20
20
|
"build": "npm run build:bin && npm run build:mcp && npm run build:cli",
|
|
21
21
|
"build:bin": "esbuild src/bin/toon-memory.ts --platform=node --format=esm --outfile=bin/toon-memory.js",
|
|
22
22
|
"build:mcp": "esbuild src/mcp/server.ts --bundle --platform=node --format=esm --outfile=mcp/server.js",
|
|
23
|
-
"build:cli": "esbuild src/cli/setup.ts --platform=node --format=esm --outfile=dist/cli/setup.js && esbuild src/cli/toon-memory.ts --platform=node --format=esm --outfile=dist/cli/toon-memory.js",
|
|
23
|
+
"build:cli": "esbuild src/cli/setup.ts --bundle --platform=node --format=esm --outfile=dist/cli/setup.js && esbuild src/cli/toon-memory.ts --bundle --platform=node --format=esm --outfile=dist/cli/toon-memory.js && esbuild src/cli/capture.ts --bundle --platform=node --format=esm --outfile=dist/cli/capture.js && esbuild src/cli/session-start.ts --bundle --platform=node --format=esm --outfile=dist/cli/session-start.js",
|
|
24
24
|
"test": "vitest run",
|
|
25
25
|
"test:watch": "vitest",
|
|
26
|
+
"bench": "node scripts/benchmark-toon.mjs",
|
|
26
27
|
"prepublishOnly": "npm run build && npm test"
|
|
27
28
|
},
|
|
28
29
|
"dependencies": {
|
|
@@ -33,6 +34,7 @@
|
|
|
33
34
|
"devDependencies": {
|
|
34
35
|
"@types/node": "^26.1.1",
|
|
35
36
|
"esbuild": "^0.25.0",
|
|
37
|
+
"gpt-tokenizer": "^3.4.0",
|
|
36
38
|
"typescript": "^7.0.2",
|
|
37
39
|
"vitest": "^4.1.10"
|
|
38
40
|
},
|
package/skills/toon-memory.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
## What is this?
|
|
4
4
|
|
|
5
|
-
A persistent memory system for AI coding agents. It remembers decisions, patterns, bugs, and knowledge **between sessions** using TOON format (
|
|
5
|
+
A persistent memory system for AI coding agents. It remembers decisions, patterns, bugs, and knowledge **between sessions** using TOON format (22% fewer tokens than JSON, measured).
|
|
6
6
|
|
|
7
7
|
## Supported Agents
|
|
8
8
|
|
|
@@ -28,15 +28,27 @@ A persistent memory system for AI coding agents. It remembers decisions, pattern
|
|
|
28
28
|
|
|
29
29
|
| Tool | Description |
|
|
30
30
|
|------|-------------|
|
|
31
|
-
| `memory_remember` | Save a decision, pattern, bug, or knowledge |
|
|
32
|
-
| `memory_recall` | Search memory (use BEFORE reading files) |
|
|
31
|
+
| `memory_remember` | Save a decision, pattern, bug, or knowledge (with optional TTL and auto-tag inference) |
|
|
32
|
+
| `memory_recall` | Search memory (use BEFORE reading files, filters expired TTL entries) |
|
|
33
33
|
| `memory_forget` | Remove an entry by key or id |
|
|
34
|
-
| `memory_stats` | View memory state |
|
|
34
|
+
| `memory_stats` | View memory state (including TTL stats) |
|
|
35
35
|
| `memory_summary` | Save/retrieve file summaries |
|
|
36
|
-
| `memory_archive` | Archive old entries |
|
|
36
|
+
| `memory_archive` | Archive old entries and expired TTL entries |
|
|
37
|
+
| `memory_diff` | Show changes since a date (24h, 7d, or exact date) |
|
|
38
|
+
| `memory_suggest` | Find related entries for a given context |
|
|
37
39
|
| `memory_encrypt` | Enable encryption |
|
|
38
40
|
| `memory_decrypt` | Disable encryption |
|
|
39
41
|
|
|
42
|
+
## MCP Resources
|
|
43
|
+
|
|
44
|
+
Memory is also exposed as MCP resources:
|
|
45
|
+
|
|
46
|
+
| Resource | URI | Description |
|
|
47
|
+
|----------|-----|-------------|
|
|
48
|
+
| Memory Entries | `toon://memory/entries` | Full memory dump |
|
|
49
|
+
| Memory Stats | `toon://memory/stats` | Category counts and TTL info |
|
|
50
|
+
| Memory Summaries | `toon://memory/summaries` | File summaries |
|
|
51
|
+
|
|
40
52
|
## Installation
|
|
41
53
|
|
|
42
54
|
### Interactive installer (recommended)
|
|
@@ -72,24 +84,28 @@ Add to your agent's MCP config:
|
|
|
72
84
|
|
|
73
85
|
1. Run `memory_stats` to see what's in memory.
|
|
74
86
|
2. If the user asks something that might be in memory → `memory_recall(query)` BEFORE reading files.
|
|
87
|
+
3. Use `memory_diff({ since: "24h" })` to see what changed since last session.
|
|
75
88
|
|
|
76
89
|
### When making decisions
|
|
77
90
|
|
|
78
91
|
- Before implementing a non-trivial change → `memory_remember(category='decision')`
|
|
79
92
|
- When you resolve a complex bug → `memory_remember(category='bug')`
|
|
80
93
|
- When you observe a code pattern → `memory_remember(category='pattern')`
|
|
94
|
+
- Leave `tags` empty for auto-inference from content
|
|
81
95
|
|
|
82
96
|
### When exploring the project
|
|
83
97
|
|
|
84
98
|
1. First: `memory_recall(query="what you need to know")`
|
|
85
|
-
2.
|
|
86
|
-
3.
|
|
99
|
+
2. Use `memory_suggest({ context: "topic" })` for related entries
|
|
100
|
+
3. If no result: use grep or search tools
|
|
101
|
+
4. Only if both fail: read files directly
|
|
87
102
|
|
|
88
103
|
### At the END of every session
|
|
89
104
|
|
|
90
105
|
1. If you made design decisions → `memory_remember(category='decision')`
|
|
91
106
|
2. If you resolved a bug → `memory_remember(category='bug')`
|
|
92
107
|
3. If you observed a pattern → `memory_remember(category='pattern')`
|
|
108
|
+
4. Use `ttl` for temporary context (deadlines, sprints)
|
|
93
109
|
|
|
94
110
|
## Categories
|
|
95
111
|
|
|
@@ -100,15 +116,32 @@ Add to your agent's MCP config:
|
|
|
100
116
|
| `bug` | Complex bug resolved | "Redis pool exhaustion, missing max_connections" |
|
|
101
117
|
| `knowledge` | General project knowledge | "Broker uses RESP protocol, not Redis-specific" |
|
|
102
118
|
|
|
119
|
+
## TTL (Time to Live)
|
|
120
|
+
|
|
121
|
+
Entries can have an optional TTL for temporary context:
|
|
122
|
+
|
|
123
|
+
```typescript
|
|
124
|
+
memory_remember({
|
|
125
|
+
category: "knowledge",
|
|
126
|
+
key: "sprint-deadline",
|
|
127
|
+
content: "Sprint ends July 18",
|
|
128
|
+
ttl: "7d" // or "2026-12-31" for exact dates
|
|
129
|
+
})
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
- Entries with expired TTL are auto-filtered from `memory_recall`
|
|
133
|
+
- Expired entries are auto-archived by `memory_archive`
|
|
134
|
+
- Empty TTL = no expiration
|
|
135
|
+
|
|
103
136
|
## File format
|
|
104
137
|
|
|
105
138
|
Data is stored in `.toon-memory/memory/data.toon` using TOON (Token-Oriented Object Notation):
|
|
106
139
|
|
|
107
140
|
```
|
|
108
141
|
version: 1
|
|
109
|
-
entries[2|]{id|category|key|content|file|tags|date}:
|
|
110
|
-
a1b2c3d4|decision|risk-priority|Risk Engine has priority|spec.md:145|risk;spec|2026-07-10
|
|
111
|
-
e5f6g7h8|pattern|pandas-over-numpy|Analytics uses pandas|indicators.py|python;analytics|2026-07-10
|
|
142
|
+
entries[2|]{id|category|key|content|file|tags|date|ttl}:
|
|
143
|
+
a1b2c3d4|decision|risk-priority|Risk Engine has priority|spec.md:145|risk;spec|2026-07-10|
|
|
144
|
+
e5f6g7h8|pattern|pandas-over-numpy|Analytics uses pandas|indicators.py|python;analytics|2026-07-10|30d
|
|
112
145
|
summaries:
|
|
113
146
|
path/to/big-file.py: Brief summary of what this file does
|
|
114
147
|
```
|
|
@@ -118,3 +151,4 @@ summaries:
|
|
|
118
151
|
- Don't store trivia in memory (only important facts)
|
|
119
152
|
- Don't forget to save a decision before implementing
|
|
120
153
|
- Don't re-read files that already have a summary in `memory_summary`
|
|
154
|
+
- Don't use TTL for permanent knowledge — only for time-sensitive context
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync, appendFileSync } from "fs"
|
|
2
|
+
import { join } from "path"
|
|
3
|
+
import { createHash } from "crypto"
|
|
4
|
+
import { withLockSync, atomicWrite } from "../lib/lock"
|
|
5
|
+
import { heartbeat, endSession, resolveSessionId, currentBranch } from "../lib/sessions"
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Hook capture script for toon-memory.
|
|
9
|
+
*
|
|
10
|
+
* Invoked by an agent's PostToolUse / Stop hook. Reads the JSON payload
|
|
11
|
+
* from stdin, applies a deterministic privacy filter, de-duplicates, and
|
|
12
|
+
* appends a lightweight observation to `.toon-memory/memory/observations.toon`.
|
|
13
|
+
*
|
|
14
|
+
* This script makes NO network calls and NO LLM calls. It only records
|
|
15
|
+
* what tool ran. Promoting an observation into real memory is still the
|
|
16
|
+
* agent's decision (via `memory_remember`).
|
|
17
|
+
*
|
|
18
|
+
* Two concerns, decoupled:
|
|
19
|
+
* - SESSION HEARTBEAT: always runs (opt-out via TOON_MEMORY_NO_SESSION).
|
|
20
|
+
* It records this session's presence/branch/files so parallel sessions
|
|
21
|
+
* can coordinate via `memory_sessions`. No server, no network.
|
|
22
|
+
* - OBSERVATION LOG: opt-in. Only writes to observations.toon when
|
|
23
|
+
* TOON_MEMORY_CAPTURE is set or config.json has `"capture": true`.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
const MEMORY_DIR = join(process.cwd(), ".toon-memory", "memory")
|
|
27
|
+
const OBSERVATIONS_FILE = join(MEMORY_DIR, "observations.toon")
|
|
28
|
+
const CONFIG_FILE = join(MEMORY_DIR, "config.json")
|
|
29
|
+
|
|
30
|
+
const DEDUP_WINDOW_MS = 5 * 60 * 1000
|
|
31
|
+
|
|
32
|
+
function captureEnabled(): boolean {
|
|
33
|
+
if (process.env.TOON_MEMORY_CAPTURE) return true
|
|
34
|
+
try {
|
|
35
|
+
const cfg = JSON.parse(readFileSync(CONFIG_FILE, "utf-8"))
|
|
36
|
+
if (cfg && cfg.capture) return true
|
|
37
|
+
} catch {
|
|
38
|
+
// no config
|
|
39
|
+
}
|
|
40
|
+
return false
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function sessionEnabled(): boolean {
|
|
44
|
+
return !process.env.TOON_MEMORY_NO_SESSION
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Deterministic secret redaction — no LLM, no network. */
|
|
48
|
+
function stripSecrets(text: string): string {
|
|
49
|
+
let t = text
|
|
50
|
+
t = t.replace(/sk-[A-Za-z0-9]{20,}/g, "<redacted>")
|
|
51
|
+
t = t.replace(/AKIA[0-9A-Z]{16}/g, "<redacted>")
|
|
52
|
+
t = t.replace(/gh[pousr]_[A-Za-z0-9]{36,}/g, "<redacted>")
|
|
53
|
+
t = t.replace(/xox[baprs]-[A-Za-z0-9-]{10,}/g, "<redacted>")
|
|
54
|
+
t = t.replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, "<redacted>")
|
|
55
|
+
t = t.replace(/Bearer\s+[A-Za-z0-9._-]+/gi, "Bearer <redacted>")
|
|
56
|
+
t = t.replace(
|
|
57
|
+
/(password|secret|token|api[_-]?key|access[_-]?key|private[_-]?key)\s*[:=]\s*["']?[A-Za-z0-9/+._-]{8,}/gi,
|
|
58
|
+
(m) => m.replace(/[A-Za-z0-9/+._-]{8,}$/, "<redacted>")
|
|
59
|
+
)
|
|
60
|
+
return t
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Extract a short, human-readable summary and file path from a tool payload. */
|
|
64
|
+
function derive(tool: string, input: unknown): { file: string; summary: string } {
|
|
65
|
+
let file = ""
|
|
66
|
+
let summary = ""
|
|
67
|
+
|
|
68
|
+
if (input && typeof input === "object") {
|
|
69
|
+
const obj = input as Record<string, unknown>
|
|
70
|
+
file = String(obj.file_path || obj.path || obj.filename || obj.notebook_path || "")
|
|
71
|
+
const rawCmd =
|
|
72
|
+
obj.command ??
|
|
73
|
+
obj.cmd ??
|
|
74
|
+
obj.prompt ??
|
|
75
|
+
obj.new_string ??
|
|
76
|
+
obj.old_string ??
|
|
77
|
+
obj.content ??
|
|
78
|
+
""
|
|
79
|
+
if (rawCmd) summary = String(rawCmd)
|
|
80
|
+
else summary = JSON.stringify(obj).slice(0, 200)
|
|
81
|
+
} else if (typeof input === "string") {
|
|
82
|
+
summary = input
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
summary = stripSecrets(String(summary || "")).replace(/\s+/g, " ").trim().slice(0, 200)
|
|
86
|
+
return { file: String(file || "").trim(), summary }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function ensureMemoryDir(): void {
|
|
90
|
+
if (!existsSync(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true })
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function appendObservation(row: string): void {
|
|
94
|
+
ensureMemoryDir()
|
|
95
|
+
let data = existsSync(OBSERVATIONS_FILE)
|
|
96
|
+
? readFileSync(OBSERVATIONS_FILE, "utf-8")
|
|
97
|
+
: "version: 1\nobservations[0|]{ts|session|agent|branch|tool|hash|file|summary}:\n"
|
|
98
|
+
|
|
99
|
+
const lines = data.split("\n")
|
|
100
|
+
let headerIdx = lines.findIndex((l) => l.startsWith("observations["))
|
|
101
|
+
if (headerIdx === -1) {
|
|
102
|
+
lines.push("observations[0|]{ts|session|agent|branch|tool|hash|file|summary}:")
|
|
103
|
+
headerIdx = lines.length - 1
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const entryLines = lines
|
|
107
|
+
.slice(headerIdx + 1)
|
|
108
|
+
.filter((l) => l.trim().length > 0)
|
|
109
|
+
.map((l) => l.trim())
|
|
110
|
+
|
|
111
|
+
entryLines.unshift(row)
|
|
112
|
+
|
|
113
|
+
const match = lines[headerIdx].match(/\[(\d+)\|/)
|
|
114
|
+
const count = match ? parseInt(match[1]) : 0
|
|
115
|
+
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`)
|
|
116
|
+
lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...entryLines.map((l) => ` ${l}`))
|
|
117
|
+
withLockSync(OBSERVATIONS_FILE, () => atomicWrite(OBSERVATIONS_FILE, lines.join("\n")))
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function main(): void {
|
|
121
|
+
const agent = process.argv[2] || "agent"
|
|
122
|
+
|
|
123
|
+
let raw = ""
|
|
124
|
+
try {
|
|
125
|
+
raw = readFileSync(0, "utf-8")
|
|
126
|
+
} catch {
|
|
127
|
+
process.exit(0)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
let payload: Record<string, unknown> = {}
|
|
131
|
+
try {
|
|
132
|
+
payload = JSON.parse(raw)
|
|
133
|
+
} catch {
|
|
134
|
+
process.exit(0)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const toolName: string =
|
|
138
|
+
(payload.tool_name as string) ||
|
|
139
|
+
(payload.toolName as string) ||
|
|
140
|
+
(payload.tool as string) ||
|
|
141
|
+
""
|
|
142
|
+
|
|
143
|
+
// Stop / SessionEnd events have no tool — record as a session marker.
|
|
144
|
+
const isStop = !toolName && (payload.session_id || payload.stop_reason || payload.session_id_untruncated)
|
|
145
|
+
const effectiveTool = toolName || "Stop"
|
|
146
|
+
|
|
147
|
+
const sessionId = resolveSessionId(payload)
|
|
148
|
+
|
|
149
|
+
// Session heartbeat: always run (unless explicitly disabled) so parallel
|
|
150
|
+
// sessions can coordinate. Cheap, local, no network.
|
|
151
|
+
if (sessionEnabled()) {
|
|
152
|
+
const input = payload.tool_input ?? payload.input ?? {}
|
|
153
|
+
const { file } = derive(effectiveTool, input)
|
|
154
|
+
if (isStop) endSession(agent, sessionId)
|
|
155
|
+
else heartbeat(agent, sessionId, { file })
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Observation log: opt-in only.
|
|
159
|
+
if (!captureEnabled()) process.exit(0)
|
|
160
|
+
|
|
161
|
+
const input = payload.tool_input ?? payload.input ?? {}
|
|
162
|
+
const { file, summary } = derive(effectiveTool, input)
|
|
163
|
+
const normalized = JSON.stringify(input ?? {})
|
|
164
|
+
const hash = createHash("sha256").update(`${effectiveTool}|${normalized}`).digest("hex").slice(0, 16)
|
|
165
|
+
const ts = new Date().toISOString()
|
|
166
|
+
const branch = currentBranch()
|
|
167
|
+
|
|
168
|
+
// De-duplicate within window (deterministic, no LLM).
|
|
169
|
+
if (existsSync(OBSERVATIONS_FILE)) {
|
|
170
|
+
const data = readFileSync(OBSERVATIONS_FILE, "utf-8")
|
|
171
|
+
for (const line of data.split("\n")) {
|
|
172
|
+
if (!line.startsWith(" ")) continue
|
|
173
|
+
const p = line.trim().split("|")
|
|
174
|
+
if (p[5] === hash) {
|
|
175
|
+
const prev = new Date(p[0]).getTime()
|
|
176
|
+
if (Date.now() - prev < DEDUP_WINDOW_MS) process.exit(0)
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (!isStop && !toolName) process.exit(0)
|
|
182
|
+
|
|
183
|
+
appendObservation(`${ts}|${sessionId}|${agent}|${branch}|${effectiveTool}|${hash}|${file}|${summary}`)
|
|
184
|
+
process.exit(0)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
main()
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { readFileSync } from "fs"
|
|
2
|
+
import { heartbeat, coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS } from "../lib/sessions"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* SessionStart hook for toon-memory.
|
|
6
|
+
*
|
|
7
|
+
* Runs once when an agent session begins. It:
|
|
8
|
+
* 1. Registers this session's heartbeat (so parallel sessions can see it).
|
|
9
|
+
* 2. Prints a short reminder listing OTHER active sessions, their branches,
|
|
10
|
+
* and any soft file conflicts — so the agent doesn't clobber sibling work.
|
|
11
|
+
*
|
|
12
|
+
* No network, no LLM. Exits 0 always (a failing hook must never block the
|
|
13
|
+
* agent from starting).
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
function main(): void {
|
|
17
|
+
const agent = process.argv[2] || "agent"
|
|
18
|
+
|
|
19
|
+
let payload: Record<string, unknown> = {}
|
|
20
|
+
try {
|
|
21
|
+
const raw = readFileSync(0, "utf-8")
|
|
22
|
+
if (raw.trim()) payload = JSON.parse(raw)
|
|
23
|
+
} catch {
|
|
24
|
+
// no/empty payload is fine
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const sessionId = resolveSessionId(payload)
|
|
28
|
+
try {
|
|
29
|
+
heartbeat(agent, sessionId)
|
|
30
|
+
} catch {
|
|
31
|
+
// never block session start
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
let view: ReturnType<typeof coordinationView>
|
|
35
|
+
try {
|
|
36
|
+
view = coordinationView(sessionId)
|
|
37
|
+
} catch {
|
|
38
|
+
process.exit(0)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const others = view.active.filter((s) => s.id !== sessionId && !s.ended)
|
|
42
|
+
const lines: string[] = []
|
|
43
|
+
lines.push("toon-memory:")
|
|
44
|
+
lines.push(` Esta sesión: ${agent} @ ${currentBranch()} (ventana ${Math.round(SESSION_TTL_MS / 60000)} min)`)
|
|
45
|
+
|
|
46
|
+
if (others.length > 0) {
|
|
47
|
+
lines.push(` Otras sesiones activas (${others.length}):`)
|
|
48
|
+
for (const s of others) {
|
|
49
|
+
const files = Object.keys(s.files).slice(0, 5).join(", ") || "—"
|
|
50
|
+
lines.push(` • ${s.agent} @ ${s.branch} — ${files}`)
|
|
51
|
+
}
|
|
52
|
+
} else {
|
|
53
|
+
lines.push(" Sin otras sesiones activas.")
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (view.conflicts.length > 0) {
|
|
57
|
+
lines.push(` ⚠️ Conflictos suaves (${view.conflicts.length}): usa memory_sessions para ver detalle.`)
|
|
58
|
+
for (const c of view.conflicts) {
|
|
59
|
+
lines.push(` • ${c.file}`)
|
|
60
|
+
}
|
|
61
|
+
} else {
|
|
62
|
+
lines.push(" Sin conflictos de archivos detectados.")
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
lines.push(" Usa memory_recall antes de leer archivos y memory_sessions para coordinar.")
|
|
66
|
+
console.log(lines.join("\n"))
|
|
67
|
+
process.exit(0)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
main()
|
package/src/cli/setup.ts
CHANGED
|
@@ -25,13 +25,45 @@ interface Agent {
|
|
|
25
25
|
needsHooks: boolean
|
|
26
26
|
needsInstructions: boolean
|
|
27
27
|
instructionFile?: string
|
|
28
|
+
/** Claude Code-style hook events for activity capture (e.g. PostToolUse, Stop) */
|
|
29
|
+
captureJson?: string[]
|
|
30
|
+
/** Codex TOML hook events for activity capture (e.g. post_tool_use, stop) */
|
|
31
|
+
captureToml?: string[]
|
|
28
32
|
}
|
|
29
33
|
|
|
30
|
-
/**
|
|
31
|
-
const
|
|
32
|
-
|
|
34
|
+
/** Path to the compiled capture script (dist/cli/capture.js) */
|
|
35
|
+
const CAPTURE_JS = join(__dirname, "capture.js")
|
|
36
|
+
|
|
37
|
+
/** Path to the compiled session-start reminder script (dist/cli/session-start.js) */
|
|
38
|
+
const SESSION_START_JS = join(__dirname, "session-start.js")
|
|
39
|
+
|
|
40
|
+
/** Hook script content for SessionStart reminder (prints active sessions + conflicts) */
|
|
41
|
+
function sessionStartHookContent(agentName: string): string {
|
|
42
|
+
return `#!/bin/bash
|
|
43
|
+
node "${SESSION_START_JS}" ${agentName}
|
|
33
44
|
exit 0
|
|
34
45
|
`
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Config file that holds the opt-in capture flag */
|
|
49
|
+
const CAPTURE_CONFIG = join(MEMORY_DIR, "config.json")
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Hook script content for activity capture. It is a no-op unless capture is
|
|
53
|
+
* explicitly enabled (env TOON_MEMORY_CAPTURE or config.json `"capture": true`),
|
|
54
|
+
* so registering it costs almost nothing when disabled.
|
|
55
|
+
*/
|
|
56
|
+
function captureHookContent(agentName: string): string {
|
|
57
|
+
return `#!/bin/bash
|
|
58
|
+
CFG="${CAPTURE_CONFIG}"
|
|
59
|
+
if [ -z "$TOON_MEMORY_CAPTURE" ]; then
|
|
60
|
+
if [ ! -f "$CFG" ]; then exit 0; fi
|
|
61
|
+
grep -q '"capture"[[:space:]]*:[[:space:]]*true' "$CFG" 2>/dev/null || exit 0
|
|
62
|
+
fi
|
|
63
|
+
node "${CAPTURE_JS}" ${agentName}
|
|
64
|
+
exit 0
|
|
65
|
+
`
|
|
66
|
+
}
|
|
35
67
|
|
|
36
68
|
/** Base instruction content for agents */
|
|
37
69
|
const INSTRUCTION_CONTENT = `# toon-memory
|
|
@@ -69,9 +101,10 @@ function detectAgents(): Agent[] {
|
|
|
69
101
|
local: join(projectRoot, ".opencode", "opencode.json"),
|
|
70
102
|
mcpKey: "mcp",
|
|
71
103
|
format: "json",
|
|
72
|
-
needsHooks:
|
|
104
|
+
needsHooks: true,
|
|
73
105
|
needsInstructions: true,
|
|
74
|
-
instructionFile: join(projectRoot, "AGENTS.md")
|
|
106
|
+
instructionFile: join(projectRoot, "AGENTS.md"),
|
|
107
|
+
captureJson: ["PostToolUse", "Stop"]
|
|
75
108
|
})
|
|
76
109
|
|
|
77
110
|
// VS Code / GitHub Copilot
|
|
@@ -93,7 +126,8 @@ function detectAgents(): Agent[] {
|
|
|
93
126
|
format: "json",
|
|
94
127
|
needsHooks: true,
|
|
95
128
|
needsInstructions: true,
|
|
96
|
-
instructionFile: join(projectRoot, ".claude", "AGENTS.md")
|
|
129
|
+
instructionFile: join(projectRoot, ".claude", "AGENTS.md"),
|
|
130
|
+
captureJson: ["PostToolUse", "Stop"]
|
|
97
131
|
})
|
|
98
132
|
|
|
99
133
|
// Cursor
|
|
@@ -144,7 +178,8 @@ function detectAgents(): Agent[] {
|
|
|
144
178
|
format: "toml",
|
|
145
179
|
needsHooks: true,
|
|
146
180
|
needsInstructions: true,
|
|
147
|
-
instructionFile: join(projectRoot, ".codex", "AGENTS.md")
|
|
181
|
+
instructionFile: join(projectRoot, ".codex", "AGENTS.md"),
|
|
182
|
+
captureToml: ["post_tool_use", "stop"]
|
|
148
183
|
})
|
|
149
184
|
|
|
150
185
|
// Gemini CLI
|
|
@@ -424,7 +459,7 @@ function installHooks(agent: Agent): void {
|
|
|
424
459
|
if (!existsSync(hookDir)) mkdirSync(hookDir, { recursive: true })
|
|
425
460
|
|
|
426
461
|
const hookPath = join(hookDir, `session-start-${agent.name}.sh`)
|
|
427
|
-
writeFileSync(hookPath,
|
|
462
|
+
writeFileSync(hookPath, sessionStartHookContent(agent.name))
|
|
428
463
|
chmodSync(hookPath, 0o755)
|
|
429
464
|
console.log(` Hook script created at ${hookPath}`)
|
|
430
465
|
|
|
@@ -434,6 +469,66 @@ function installHooks(agent: Agent): void {
|
|
|
434
469
|
} else if (agent.format === "json" || agent.format === "jsonc") {
|
|
435
470
|
registerHookJSON(agent, hookPath)
|
|
436
471
|
}
|
|
472
|
+
|
|
473
|
+
// Activity capture hooks (opt-in, no-op unless explicitly enabled)
|
|
474
|
+
if (agent.captureJson && agent.format === "json") {
|
|
475
|
+
const capPath = join(hookDir, `capture-${agent.name}.sh`)
|
|
476
|
+
writeFileSync(capPath, captureHookContent(agent.name))
|
|
477
|
+
chmodSync(capPath, 0o755)
|
|
478
|
+
console.log(` Capture hook created at ${capPath}`)
|
|
479
|
+
registerCaptureHookJSON(agent, capPath)
|
|
480
|
+
}
|
|
481
|
+
if (agent.captureToml && agent.format === "toml" && agent.local) {
|
|
482
|
+
const capPath = join(hookDir, `capture-${agent.name}.sh`)
|
|
483
|
+
writeFileSync(capPath, captureHookContent(agent.name))
|
|
484
|
+
chmodSync(capPath, 0o755)
|
|
485
|
+
console.log(` Capture hook created at ${capPath}`)
|
|
486
|
+
registerCaptureHookTOML(agent, capPath)
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** Register activity-capture hooks (PostToolUse/Stop) in a JSON agent config. */
|
|
491
|
+
function registerCaptureHookJSON(agent: Agent, scriptPath: string): void {
|
|
492
|
+
const configPath = agent.local || agent.global
|
|
493
|
+
if (!configPath) return
|
|
494
|
+
|
|
495
|
+
const configDir = dirname(configPath)
|
|
496
|
+
if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true })
|
|
497
|
+
|
|
498
|
+
let config: Record<string, any> = {}
|
|
499
|
+
if (existsSync(configPath)) {
|
|
500
|
+
try {
|
|
501
|
+
config = JSON.parse(readFileSync(configPath, "utf-8"))
|
|
502
|
+
} catch {
|
|
503
|
+
config = {}
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
if (!config.hooks) config.hooks = {}
|
|
508
|
+
for (const event of agent.captureJson || []) {
|
|
509
|
+
if (!config.hooks[event]) config.hooks[event] = []
|
|
510
|
+
if (!config.hooks[event].some((h: any) => h.command === scriptPath)) {
|
|
511
|
+
config.hooks[event].push({ command: scriptPath })
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
writeFileSync(configPath, JSON.stringify(config, null, 2))
|
|
516
|
+
console.log(` Capture hooks registered in ${configPath}`)
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/** Register activity-capture hooks (post_tool_use/stop) in a Codex TOML config. */
|
|
520
|
+
function registerCaptureHookTOML(agent: Agent, scriptPath: string): void {
|
|
521
|
+
const configPath = agent.local
|
|
522
|
+
if (!configPath || !existsSync(configPath)) return
|
|
523
|
+
|
|
524
|
+
let content = readFileSync(configPath, "utf-8")
|
|
525
|
+
for (const event of agent.captureToml || []) {
|
|
526
|
+
if (content.includes(`[hooks.${event}]`)) continue
|
|
527
|
+
content += `\n[hooks.${event}]\ncommand = "${scriptPath}"\n`
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
writeFileSync(configPath, content)
|
|
531
|
+
console.log(` Capture hooks registered in ${configPath}`)
|
|
437
532
|
}
|
|
438
533
|
|
|
439
534
|
/** Register SessionStart hook in TOML config (Codex CLI) */
|
|
@@ -475,8 +570,8 @@ function registerHookJSON(agent: Agent, hookPath: string): void {
|
|
|
475
570
|
}
|
|
476
571
|
}
|
|
477
572
|
|
|
478
|
-
// Claude Code format
|
|
479
|
-
if (agent.name === "claude") {
|
|
573
|
+
// Claude Code / OpenCode (Claude-compatible) format
|
|
574
|
+
if (agent.name === "claude" || agent.name === "opencode") {
|
|
480
575
|
if (!config.hooks) config.hooks = {}
|
|
481
576
|
if (!config.hooks.SessionStart) config.hooks.SessionStart = []
|
|
482
577
|
if (!config.hooks.SessionStart.some((h: any) => h.command === hookPath)) {
|
|
@@ -635,6 +730,17 @@ function status(): void {
|
|
|
635
730
|
console.log("Memory: not initialized")
|
|
636
731
|
}
|
|
637
732
|
|
|
733
|
+
// Capture status
|
|
734
|
+
let capture = false
|
|
735
|
+
if (process.env.TOON_MEMORY_CAPTURE) capture = true
|
|
736
|
+
else if (existsSync(CAPTURE_CONFIG)) {
|
|
737
|
+
try {
|
|
738
|
+
const c = JSON.parse(readFileSync(CAPTURE_CONFIG, "utf-8"))
|
|
739
|
+
if (c.capture) capture = true
|
|
740
|
+
} catch {}
|
|
741
|
+
}
|
|
742
|
+
console.log(`Capture: ${capture ? "enabled" : "disabled (opt-in)"}`)
|
|
743
|
+
|
|
638
744
|
// Check agent configs
|
|
639
745
|
const agents = detectAgents()
|
|
640
746
|
console.log("\nAgent configs:")
|
|
@@ -949,11 +1055,6 @@ function compressData(data: string): Buffer {
|
|
|
949
1055
|
return gzipSync(Buffer.from(data, "utf-8"))
|
|
950
1056
|
}
|
|
951
1057
|
|
|
952
|
-
/** Decompress gzip data to string */
|
|
953
|
-
function decompressData(data: Buffer): string {
|
|
954
|
-
return gunzipSync(data).toString("utf-8")
|
|
955
|
-
}
|
|
956
|
-
|
|
957
1058
|
/**
|
|
958
1059
|
* Watch mode - backup memory every N minutes
|
|
959
1060
|
*/
|
|
@@ -1052,9 +1153,41 @@ function watch(): void {
|
|
|
1052
1153
|
})
|
|
1053
1154
|
}
|
|
1054
1155
|
|
|
1156
|
+
/**
|
|
1157
|
+
* Enable or disable activity capture (the opt-in hook log).
|
|
1158
|
+
*/
|
|
1159
|
+
function captureToggle(enable: boolean): void {
|
|
1160
|
+
if (!existsSync(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true })
|
|
1161
|
+
|
|
1162
|
+
let config: Record<string, any> = {}
|
|
1163
|
+
if (existsSync(CAPTURE_CONFIG)) {
|
|
1164
|
+
try {
|
|
1165
|
+
config = JSON.parse(readFileSync(CAPTURE_CONFIG, "utf-8"))
|
|
1166
|
+
} catch {
|
|
1167
|
+
config = {}
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
config.capture = enable
|
|
1172
|
+
writeFileSync(CAPTURE_CONFIG, JSON.stringify(config, null, 2))
|
|
1173
|
+
|
|
1174
|
+
if (enable) {
|
|
1175
|
+
console.log("\n🔴 Captura de actividad HABILITADA.")
|
|
1176
|
+
console.log("Los hooks grabarán observaciones en .toon-memory/memory/observations.toon.")
|
|
1177
|
+
console.log("Revisa con `memory_captured` y promuévelas con `memory_remember`.\n")
|
|
1178
|
+
} else {
|
|
1179
|
+
console.log("\n⚪ Captura de actividad DESHABILITADA.\n")
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1055
1183
|
// Main
|
|
1056
1184
|
const args = process.argv.slice(2)
|
|
1057
1185
|
|
|
1186
|
+
if (args[0] === "capture") {
|
|
1187
|
+
captureToggle(args[1] === "on")
|
|
1188
|
+
process.exit(0)
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1058
1191
|
if (args[0] === "uninstall") {
|
|
1059
1192
|
uninstall()
|
|
1060
1193
|
process.exit(0)
|