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 CHANGED
@@ -17,6 +17,8 @@
17
17
  - [Quick Start](#quick-start)
18
18
  - [Supported Agents](#supported-agents)
19
19
  - [MCP Tools](#mcp-tools)
20
+ - [Coordinación multi-sesión](#coordinación-multi-sesión)
21
+ - [Memory Graph (recall basado en grafo)](#memory-graph-recall-basado-en-grafo)
20
22
  - [Tips & Best Practices](#tips--best-practices)
21
23
  - [CLI Commands](#cli-commands)
22
24
  - [Configuration](#configuration)
@@ -59,18 +61,24 @@ Read [How toon-memory Makes Your AI Agent Smarter](https://luiggival08.github.io
59
61
 
60
62
  ## Features
61
63
 
62
- - **8 MCP tools** — Full memory management via Model Context Protocol
64
+ - **13 MCP tools** — Full memory management via Model Context Protocol, including `memory_sessions` for multi-session coordination
65
+ - **MCP Resources** — Read memory as context without tool invocations
63
66
  - **15 agents supported** — OpenCode, VS Code, Claude Code, Cursor, Windsurf, Cline, Continue, Codex CLI, Gemini CLI, Zed, Antigravity, Aider, KiloCode, OpenClaw, Kiro
64
67
  - **Interactive installer** — Select which agents to configure from a menu
65
68
  - **SessionStart hooks** — Auto-reminders for Claude Code, Codex CLI, Gemini CLI, Antigravity
66
- - **TOON format** — 40% fewer tokens than JSON, better LLM comprehension
69
+ - **TOON format** — 22% fewer tokens than JSON (measured), better LLM comprehension
67
70
  - **Per-project memory** — Each project gets its own memory file
68
71
  - **Zero config** — Just install and use
69
72
  - **Auto gitignore** — Automatically adds `.toon-memory/memory/` to `.gitignore`
70
73
  - **Date filtering** — Search memory by date range
71
- - **Auto-archive** — Old entries (>30 days) or 100+ entries moved to archive automatically
74
+ - **Auto-archive** — Old entries (>30 days), expired TTL entries, or 100+ entries moved to archive automatically
72
75
  - **Encryption** — AES-256-GCM encryption for sensitive data
73
76
  - **Watch mode** — Auto-backup every N minutes
77
+ - **Memory TTL** — Configurable per-entry expiration (7d, 30d, or exact dates)
78
+ - **Tag inference** — Auto-detect tags from content when tags are empty
79
+ - **Memory diff** — See what changed since your last session
80
+ - **Related entries** — Auto-suggest related memories when saving
81
+ - **Memory graph** — Connect entries with `links`/`[[key]]` refs; `memory_recall` can expand a relationship-aware subgraph for more precise, lower-token recall (no embeddings, no LLM)
74
82
 
75
83
  ---
76
84
 
@@ -145,14 +153,29 @@ memory_remember # Save important decisions
145
153
 
146
154
  | Tool | Description |
147
155
  |------|-------------|
148
- | `memory_remember` | Save a decision, pattern, bug, or knowledge |
149
- | `memory_recall` | Search memory (use BEFORE reading files) |
156
+ | `memory_remember` | Save a decision, pattern, bug, or knowledge (optional TTL, auto-tag inference, and `links` to build the memory graph) |
157
+ | `memory_recall` | Search memory (use BEFORE reading files, filters expired TTL). `mode: "graph"` expands a relationship-aware subgraph for higher precision |
150
158
  | `memory_forget` | Remove an entry by key or id |
151
- | `memory_stats` | View memory state |
159
+ | `memory_stats` | View memory state (including TTL stats) |
152
160
  | `memory_summary` | Save/retrieve file summaries |
153
- | `memory_archive` | Archive old entries (>30 days) |
161
+ | `memory_archive` | Archive old entries (>30 days) and expired TTL entries |
162
+ | `memory_diff` | Show changes since a date (24h, 7d, or exact date) |
163
+ | `memory_suggest` | Find related entries for a given context |
154
164
  | `memory_encrypt` | Enable AES-256-GCM encryption |
155
165
  | `memory_decrypt` | Disable encryption |
166
+ | `memory_captured` | List activity auto-captured by hooks (opt-in) or clear the log |
167
+ | `memory_consolidate` | De-duplicate entries with identical content (deterministic, no LLM) |
168
+ | `memory_sessions` | Show active agent sessions (branch, files, last-seen) and soft conflicts for parallel work |
169
+
170
+ ### MCP Resources
171
+
172
+ Memory is also exposed as MCP resources for direct context reading:
173
+
174
+ | Resource | URI | Description |
175
+ |----------|-----|-------------|
176
+ | Memory Entries | `toon://memory/entries` | Full memory dump |
177
+ | Memory Stats | `toon://memory/stats` | Category counts and TTL info |
178
+ | Memory Summaries | `toon://memory/summaries` | File summaries
156
179
 
157
180
  ### Examples
158
181
 
@@ -167,10 +190,42 @@ memory_remember({
167
190
  tags: "validation;types"
168
191
  })
169
192
  // 🧠 Guardado: decision/use-zod (a1b2c3d4)
193
+ // 🔗 Entradas relacionadas:
194
+ // [pattern] zod-schemas — Shared Zod schemas for API validation
170
195
  ```
171
196
 
172
197
  > **Tip:** Use descriptive keys like `use-zod` instead of vague ones like `validation`. Your agent searches by key and content, so specificity helps.
173
198
 
199
+ #### Remember with TTL
200
+
201
+ ```typescript
202
+ memory_remember({
203
+ category: "knowledge",
204
+ key: "sprint-deadline",
205
+ content: "Sprint ends July 18, feature freeze is July 16",
206
+ ttl: "7d"
207
+ })
208
+ // 🧠 Guardado: knowledge/sprint-deadline (x1y2z3w4)
209
+ // ⏰ TTL: 2026-07-19
210
+ ```
211
+
212
+ > **Tip:** Use TTL for temporary context like deadlines, sprint info, or time-sensitive notes. Entries with expired TTL are automatically filtered from search results.
213
+
214
+ #### Auto-inferred tags
215
+
216
+ ```typescript
217
+ memory_remember({
218
+ category: "bug",
219
+ key: "redis-connection-timeout",
220
+ content: "Redis connection timeout in production, increased pool size"
221
+ // tags left empty — auto-inferred from content
222
+ })
223
+ // 🧠 Guardado: bug/redis-connection-timeout (a1b2c3d4)
224
+ // 🏷️ Tags inferidos: redis
225
+ ```
226
+
227
+ > **Tip:** Leave `tags` empty and the system will infer them from your content using a vocabulary of 20+ categories (redis, auth, api, db, security, etc.).
228
+
174
229
  #### Search memory
175
230
 
176
231
  ```typescript
@@ -202,7 +257,39 @@ memory_archive()
202
257
  // 📋 Quedan 42 entradas activas
203
258
  ```
204
259
 
205
- > **Tip:** Run this periodically to keep memory lean. Archived entries are still searchable via `memory_recall` with date filters.
260
+ > **Tip:** Run this periodically to keep memory lean. Archived entries are still searchable via `memory_recall` with date filters. Entries with expired TTL are also archived automatically.
261
+
262
+ #### Show changes since last session
263
+
264
+ ```typescript
265
+ memory_diff({ since: "24h" })
266
+ // 📋 Cambios desde 2026-07-11:
267
+ //
268
+ // ➕ Nuevas (2):
269
+ // [decision] use-zod (a1b2c3d4)
270
+ // Use Zod for validation
271
+ // [bug] redis-timeout (e5f6g7h8)
272
+ // Redis connection timeout fix
273
+ ```
274
+
275
+ > **Tip:** Use `memory_diff` at the start of a session to see what your agent learned since you last worked on the project.
276
+
277
+ #### Find related entries
278
+
279
+ ```typescript
280
+ memory_suggest({ context: "redis cache configuration" })
281
+ // 🔍 Sugerencias para "redis cache configuration":
282
+ //
283
+ // [decision] redis-cache-config (a1b2c3d4)
284
+ // Redis cache layer for session storage
285
+ // File: src/cache.ts | Tags: redis;cache | Date: 2026-07-10
286
+ //
287
+ // [bug] redis-pool-fix (i9j0k1l2)
288
+ // Added max_connections=20
289
+ // File: redis.ts | Tags: redis;fix | Date: 2026-07-10
290
+ ```
291
+
292
+ > **Tip:** Use `memory_suggest` when you need context about a topic but aren't sure what to search for.
206
293
 
207
294
  #### Enable encryption
208
295
 
@@ -217,6 +304,110 @@ memory_encrypt()
217
304
 
218
305
  ---
219
306
 
307
+ ## Coordinación multi-sesión
308
+
309
+ When you run **several AI agent sessions in parallel** (e.g. three OpenCode sessions on the same repo at once), they can accidentally clobber each other's work. toon-memory ships with **`memory_sessions`**, a file-based coordination tool that lets every session see what its siblings are doing — with **no server, no network, and no LLM calls**.
310
+
311
+ ### How it works
312
+
313
+ - On startup, a `SessionStart` hook writes a **heartbeat file** for the session at `.toon-memory/memory/sessions/<id>.json`. Each process writes *only its own* file, so there's no lock contention.
314
+ - The heartbeat records the agent name, the **git branch**, the **files touched**, and a **last-seen** timestamp.
315
+ - Reading across all those files gives every session a shared, eventually-consistent view of who else is active.
316
+ - Dead sessions (process PID no longer alive **and** a stale heartbeat past the TTL window) are pruned lazily.
317
+
318
+ ### The `memory_sessions` tool
319
+
320
+ ```typescript
321
+ memory_sessions({ conflictsOnly: false })
322
+ // 🧭 Sesiones activas (2) — ventana 30 min:
323
+ //
324
+ // • opencode @ feature/auth (tú)
325
+ // id: a1b2c3d4
326
+ // hace 2 min
327
+ // Archivos:
328
+ // • src/auth.ts
329
+ //
330
+ // • claude @ feature/db
331
+ // id: e5f6g7h8
332
+ // hace 9 min
333
+ // • src/db.ts
334
+ //
335
+ // 🔥 Conflictos suaves (1):
336
+ // ⚠️ src/types.ts ↔ opencode @ feature/auth, claude @ feature/db
337
+ ```
338
+
339
+ - Pass `conflictsOnly: true` to skip the session list and show only soft conflicts:
340
+ ```typescript
341
+ memory_sessions({ conflictsOnly: true })
342
+ // 🔥 Conflictos suaves (1):
343
+ //
344
+ // ⚠️ src/types.ts
345
+ // ↔ opencode @ feature/auth (a1b2c3d4), claude @ feature/db (e5f6g7h8)
346
+ ```
347
+ - A **soft conflict** is any file touched by 2+ active sessions — a heads-up that you might be editing the same code. It's not a hard lock, just a warning to coordinate.
348
+
349
+ ### Recommended parallel-session habit
350
+
351
+ 1. At the start of every session, the `SessionStart` hook already prints the other active sessions and any soft conflicts.
352
+ 2. Run `memory_sessions()` to see the full picture (branches, files, last-seen) and `memory_sessions({ conflictsOnly: true })` if you only care about clashes.
353
+ 3. If you share a file with another session, sync up before editing so you don't overwrite each other's changes.
354
+
355
+ > **Tip:** This is purely local and lock-free — safe to run as often as you like. Combine it with `memory_recall({ query: "project context" })` at session start for both cross-session *memory* and cross-session *presence*.
356
+
357
+ ---
358
+
359
+ ## Memory Graph (recall basado en grafo)
360
+
361
+ When your memory grows, a flat keyword search can return either too much (every match) or the wrong context (no relationships). toon-memory can treat memory as a **lightweight knowledge graph** so recall returns the *right* entries with fewer tokens.
362
+
363
+ It's fully **deterministic and offline** — no embeddings, no vector DB, no LLM, no server. Edges come from two sources:
364
+
365
+ - **Explicit `links`** — keys you declare when saving an entry.
366
+ - **Implicit `[[key]]` refs** — any `[[some-key]]` mention inside the content.
367
+
368
+ ### How it works
369
+
370
+ 1. `memory_remember` stores `links` on the entry (space- or `;`-separated keys).
371
+ 2. `memory_recall({ mode: "graph" })` finds keyword matches (seeds), then expands the **ego-subgraph** up to `hops` (1 or 2) along the edges.
372
+ 3. Relevance propagates from the seeds to their neighbors, so a related decision or spec surfaces even if it doesn't contain the query word.
373
+ 4. The result set is capped (`limit`, default 6) → **smaller, more precise context** for the agent.
374
+
375
+ ### Remember with links
376
+
377
+ ```typescript
378
+ memory_remember({
379
+ category: "decision",
380
+ key: "risk-engine-priority",
381
+ content: "The engine prioritizes risk over speed (see [[risk-spec]]).",
382
+ file: "spec.md:10",
383
+ tags: "risk;spec",
384
+ links: "engine-arch" // explicit edge to another entry
385
+ })
386
+ // 🧠 Guardado: decision/risk-engine-priority (a1b2c3d4)
387
+ ```
388
+
389
+ ### Recall with graph mode
390
+
391
+ ```typescript
392
+ memory_recall({ query: "riesgo", mode: "graph", hops: 2 })
393
+ // [decision] risk-engine-priority (a1b2c3d4)
394
+ // The engine prioritizes risk over speed (see [[risk-spec]]).
395
+ // File: spec.md:10 | Tags: risk;spec | Date: 2026-07-01
396
+ // links: engine-arch
397
+ //
398
+ // [knowledge] risk-spec (a2b3c4d5)
399
+ // Risk specification for the engine.
400
+ // links: risk-engine-priority;engine-arch
401
+ //
402
+ // [pattern] engine-arch (e6f7g8h9)
403
+ // Engine architecture.
404
+ // links: risk-spec
405
+ ```
406
+
407
+ > **Tip:** Use `mode: "graph"` when a decision ripples across several entries (architecture, specs, related bugs). For isolated facts, the default `flat` mode is enough. The graph is built on read, so there's no extra index file to maintain.
408
+
409
+ ---
410
+
220
411
  ## Tips & Best Practices
221
412
 
222
413
  Here are some patterns that work well with toon-memory:
@@ -479,7 +670,7 @@ Add to `~/.config/zed/settings.json`:
479
670
  ## How It Works
480
671
 
481
672
  1. **MCP Server** — Runs locally, talks to your agent via stdio
482
- 2. **TOON Format** — Stores data in Token-Oriented Object Notation (~40% fewer tokens than JSON)
673
+ 2. **TOON Format** — Stores data in Token-Oriented Object Notation (~22.5% fewer tokens than JSON, measured over 16 entries with gpt-tokenizer)
483
674
  3. **Per-project memory** — Each project gets `.toon-memory/memory/data.toon`
484
675
  4. **Zero config** — Just install and use
485
676
 
@@ -487,10 +678,10 @@ Add to `~/.config/zed/settings.json`:
487
678
 
488
679
  ```
489
680
  version: 1
490
- entries[3|]{id|category|key|content|file|tags|date}:
491
- a1b2c3d4|decision|use-zod|Use Zod for validation|src/types.ts|validation;types|2026-07-10
492
- e5f6g7h8|pattern|pydantic-configs|Project uses Pydantic v2|config.py|python;patterns|2026-07-10
493
- i9j0k1l2|bug|redis-pool-fix|Added max_connections=20|redis.ts|redis;fix|2026-07-10
681
+ entries[3|]{id|category|key|content|file|tags|date|ttl|accessed|links}:
682
+ a1b2c3d4|decision|use-zod|Use Zod for validation|src/types.ts|validation;types|2026-07-10||0|
683
+ e5f6g7h8|pattern|pydantic-configs|Project uses Pydantic v2|config.py|python;patterns|2026-07-10||0|
684
+ i9j0k1l2|bug|redis-pool-fix|Added max_connections=20 (see [[use-zod]])|redis.ts|redis;fix|2026-07-10|7d|0|use-zod
494
685
  summaries:
495
686
  src/services/redis.ts: Redis connection pool with retry logic
496
687
  ```
@@ -519,13 +710,14 @@ summaries:
519
710
 
520
711
  TOON (Token-Oriented Object Notation) is designed for LLMs:
521
712
 
522
- | Format | Token Count | LLM Accuracy |
523
- |--------|-------------|--------------|
524
- | JSON | 100 | 75% |
525
- | YAML | 95 | 72% |
526
- | **TOON** | **60** | **76.4%** |
713
+ | Format | Tokens (16 entries) |
714
+ |--------|---------------------|
715
+ | JSON | 1097 |
716
+ | **TOON** | **850** |
717
+
718
+ Measured with `gpt-tokenizer` (cl100k_base) over 16 representative memory entries — see `scripts/benchmark-toon.mjs` (`npm run bench`).
527
719
 
528
- - **40% fewer tokens** than JSON
720
+ - **22.5% fewer tokens** than JSON at file level (up to 30.5% on a single entry)
529
721
  - **Lossless roundtrip** — No data loss
530
722
  - **Better LLM comprehension** — Structured for AI consumption
531
723
 
@@ -622,11 +814,17 @@ toon-memory/
622
814
  │ │ ├── setup.ts # CLI commands
623
815
  │ │ └── toon-memory.ts # CLI runner
624
816
  │ ├── mcp/
625
- │ │ └── server.ts # MCP server (8 tools)
817
+ │ │ └── server.ts # MCP server (13 tools + 3 resources)
818
+ │ ├── lib/
819
+ │ │ ├── lock.ts # Advisory file lock + atomic write
820
+ │ │ ├── sessions.ts # Multi-session coordination
821
+ │ │ └── graph.ts # Memory graph (parse, build, graph recall)
626
822
  │ └── memory.ts # Custom tool (OpenCode)
627
823
  ├── tests/
628
824
  │ ├── cli.test.ts # CLI tests
629
- │ └── memory.test.ts # Memory tests
825
+ │ ├── memory.test.ts # Memory tests
826
+ │ ├── sessions.test.ts # Multi-session tests
827
+ │ └── graph.test.ts # Memory graph tests
630
828
  ├── .github/workflows/
631
829
  │ ├── ci.yml # CI (Node.js 20/22)
632
830
  │ └── publish.yml # Auto-publish on release
@@ -0,0 +1,276 @@
1
+ // src/cli/capture.ts
2
+ import { readFileSync as readFileSync3, existsSync as existsSync3, mkdirSync as mkdirSync2 } from "fs";
3
+ import { join as join2 } from "path";
4
+ import { createHash } from "crypto";
5
+
6
+ // src/lib/lock.ts
7
+ import { openSync, closeSync, writeFileSync, readFileSync, unlinkSync, existsSync, statSync, renameSync } from "fs";
8
+ var STALE_MS = 15e3;
9
+ var LOCK_TIMEOUT_MS = 1e4;
10
+ function isAlive(pid) {
11
+ if (!pid || pid <= 0) return false;
12
+ try {
13
+ process.kill(pid, 0);
14
+ return true;
15
+ } catch {
16
+ return false;
17
+ }
18
+ }
19
+ function tryAcquire(lockFile) {
20
+ if (existsSync(lockFile)) {
21
+ const age = Date.now() - statSync(lockFile).mtimeMs;
22
+ let stale = age > STALE_MS;
23
+ if (!stale) {
24
+ try {
25
+ const pid = parseInt(readFileSync(lockFile, "utf-8").trim(), 10);
26
+ if (!isAlive(pid)) stale = true;
27
+ } catch {
28
+ stale = true;
29
+ }
30
+ }
31
+ if (stale) {
32
+ try {
33
+ unlinkSync(lockFile);
34
+ } catch {
35
+ }
36
+ } else {
37
+ return false;
38
+ }
39
+ }
40
+ try {
41
+ const fd = openSync(lockFile, "wx");
42
+ writeFileSync(fd, String(process.pid));
43
+ closeSync(fd);
44
+ return true;
45
+ } catch {
46
+ return false;
47
+ }
48
+ }
49
+ var held = /* @__PURE__ */ new Map();
50
+ function withLockSync(file, fn) {
51
+ const lockFile = `${file}.lock`;
52
+ const depth = held.get(lockFile) ?? 0;
53
+ if (depth > 0) {
54
+ held.set(lockFile, depth + 1);
55
+ try {
56
+ fn();
57
+ } finally {
58
+ const d = (held.get(lockFile) ?? 0) - 1;
59
+ if (d <= 0) held.delete(lockFile);
60
+ else held.set(lockFile, d);
61
+ }
62
+ return;
63
+ }
64
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
65
+ while (!tryAcquire(lockFile)) {
66
+ if (Date.now() > deadline) throw new Error(`toon-memory lock timeout: ${file}`);
67
+ const t = Date.now() + 10;
68
+ while (Date.now() < t) {
69
+ }
70
+ }
71
+ held.set(lockFile, 1);
72
+ try {
73
+ fn();
74
+ } finally {
75
+ const d = (held.get(lockFile) ?? 0) - 1;
76
+ if (d <= 0) {
77
+ held.delete(lockFile);
78
+ try {
79
+ unlinkSync(lockFile);
80
+ } catch {
81
+ }
82
+ } else {
83
+ held.set(lockFile, d);
84
+ }
85
+ }
86
+ }
87
+ function atomicWrite(file, content) {
88
+ const tmp = `${file}.tmp`;
89
+ writeFileSync(tmp, content);
90
+ renameSync(tmp, file);
91
+ }
92
+
93
+ // src/lib/sessions.ts
94
+ import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2, readdirSync, unlinkSync as unlinkSync2 } from "fs";
95
+ import { join } from "path";
96
+ import { execSync } from "child_process";
97
+ var SESSION_TTL_MS = 10 * 60 * 1e3;
98
+ var PRUNE_STALE_MS = 10 * 60 * 1e3;
99
+ function sessionDir() {
100
+ return join(process.cwd(), ".toon-memory", "memory", "sessions");
101
+ }
102
+ function sessionPath(id) {
103
+ return join(sessionDir(), `${id}.json`);
104
+ }
105
+ function ensureSessionDir() {
106
+ const dir = sessionDir();
107
+ if (!existsSync2(dir)) mkdirSync(dir, { recursive: true });
108
+ }
109
+ function resolveSessionId(payload = {}) {
110
+ const fromPayload = payload.session_id || payload.sessionId || payload.session_id_untruncated;
111
+ if (fromPayload && fromPayload.trim()) return fromPayload.trim();
112
+ if (process.env.TOON_MEMORY_SESSION_ID && process.env.TOON_MEMORY_SESSION_ID.trim()) {
113
+ return process.env.TOON_MEMORY_SESSION_ID.trim();
114
+ }
115
+ return `proc-${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
116
+ }
117
+ function currentBranch() {
118
+ if (process.env.TOON_MEMORY_BRANCH && process.env.TOON_MEMORY_BRANCH.trim()) {
119
+ return process.env.TOON_MEMORY_BRANCH.trim();
120
+ }
121
+ try {
122
+ const branch = execSync("git rev-parse --abbrev-ref HEAD", {
123
+ encoding: "utf-8",
124
+ timeout: 2e3,
125
+ stdio: ["ignore", "pipe", "ignore"]
126
+ }).trim();
127
+ return branch || "unknown";
128
+ } catch {
129
+ return "unknown";
130
+ }
131
+ }
132
+ function readRecord(id) {
133
+ const p = sessionPath(id);
134
+ if (!existsSync2(p)) return null;
135
+ try {
136
+ return JSON.parse(readFileSync2(p, "utf-8"));
137
+ } catch {
138
+ return null;
139
+ }
140
+ }
141
+ function heartbeat(agent, sessionId, opts = {}) {
142
+ ensureSessionDir();
143
+ const now = (/* @__PURE__ */ new Date()).toISOString();
144
+ const existing = readRecord(sessionId);
145
+ const record = existing ? { ...existing, agent, pid: process.pid, lastSeen: now, branch: currentBranch(), ended: opts.ended ?? existing.ended } : {
146
+ id: sessionId,
147
+ agent,
148
+ pid: process.pid,
149
+ branch: currentBranch(),
150
+ startedAt: now,
151
+ lastSeen: now,
152
+ ended: opts.ended ?? false,
153
+ files: {}
154
+ };
155
+ if (opts.file && opts.file.trim()) {
156
+ record.files[opts.file.trim()] = now;
157
+ }
158
+ writeFileSync2(sessionPath(sessionId), JSON.stringify(record, null, 2));
159
+ }
160
+ function endSession(agent, sessionId) {
161
+ heartbeat(agent, sessionId, { ended: true });
162
+ }
163
+
164
+ // src/cli/capture.ts
165
+ var MEMORY_DIR = join2(process.cwd(), ".toon-memory", "memory");
166
+ var OBSERVATIONS_FILE = join2(MEMORY_DIR, "observations.toon");
167
+ var CONFIG_FILE = join2(MEMORY_DIR, "config.json");
168
+ var DEDUP_WINDOW_MS = 5 * 60 * 1e3;
169
+ function captureEnabled() {
170
+ if (process.env.TOON_MEMORY_CAPTURE) return true;
171
+ try {
172
+ const cfg = JSON.parse(readFileSync3(CONFIG_FILE, "utf-8"));
173
+ if (cfg && cfg.capture) return true;
174
+ } catch {
175
+ }
176
+ return false;
177
+ }
178
+ function sessionEnabled() {
179
+ return !process.env.TOON_MEMORY_NO_SESSION;
180
+ }
181
+ function stripSecrets(text) {
182
+ let t = text;
183
+ t = t.replace(/sk-[A-Za-z0-9]{20,}/g, "<redacted>");
184
+ t = t.replace(/AKIA[0-9A-Z]{16}/g, "<redacted>");
185
+ t = t.replace(/gh[pousr]_[A-Za-z0-9]{36,}/g, "<redacted>");
186
+ t = t.replace(/xox[baprs]-[A-Za-z0-9-]{10,}/g, "<redacted>");
187
+ t = t.replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, "<redacted>");
188
+ t = t.replace(/Bearer\s+[A-Za-z0-9._-]+/gi, "Bearer <redacted>");
189
+ t = t.replace(
190
+ /(password|secret|token|api[_-]?key|access[_-]?key|private[_-]?key)\s*[:=]\s*["']?[A-Za-z0-9/+._-]{8,}/gi,
191
+ (m) => m.replace(/[A-Za-z0-9/+._-]{8,}$/, "<redacted>")
192
+ );
193
+ return t;
194
+ }
195
+ function derive(tool, input) {
196
+ let file = "";
197
+ let summary = "";
198
+ if (input && typeof input === "object") {
199
+ const obj = input;
200
+ file = String(obj.file_path || obj.path || obj.filename || obj.notebook_path || "");
201
+ const rawCmd = obj.command ?? obj.cmd ?? obj.prompt ?? obj.new_string ?? obj.old_string ?? obj.content ?? "";
202
+ if (rawCmd) summary = String(rawCmd);
203
+ else summary = JSON.stringify(obj).slice(0, 200);
204
+ } else if (typeof input === "string") {
205
+ summary = input;
206
+ }
207
+ summary = stripSecrets(String(summary || "")).replace(/\s+/g, " ").trim().slice(0, 200);
208
+ return { file: String(file || "").trim(), summary };
209
+ }
210
+ function ensureMemoryDir() {
211
+ if (!existsSync3(MEMORY_DIR)) mkdirSync2(MEMORY_DIR, { recursive: true });
212
+ }
213
+ function appendObservation(row) {
214
+ ensureMemoryDir();
215
+ let data = existsSync3(OBSERVATIONS_FILE) ? readFileSync3(OBSERVATIONS_FILE, "utf-8") : "version: 1\nobservations[0|]{ts|session|agent|branch|tool|hash|file|summary}:\n";
216
+ const lines = data.split("\n");
217
+ let headerIdx = lines.findIndex((l) => l.startsWith("observations["));
218
+ if (headerIdx === -1) {
219
+ lines.push("observations[0|]{ts|session|agent|branch|tool|hash|file|summary}:");
220
+ headerIdx = lines.length - 1;
221
+ }
222
+ const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0).map((l) => l.trim());
223
+ entryLines.unshift(row);
224
+ const match = lines[headerIdx].match(/\[(\d+)\|/);
225
+ const count = match ? parseInt(match[1]) : 0;
226
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`);
227
+ lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...entryLines.map((l) => ` ${l}`));
228
+ withLockSync(OBSERVATIONS_FILE, () => atomicWrite(OBSERVATIONS_FILE, lines.join("\n")));
229
+ }
230
+ function main() {
231
+ const agent = process.argv[2] || "agent";
232
+ let raw = "";
233
+ try {
234
+ raw = readFileSync3(0, "utf-8");
235
+ } catch {
236
+ process.exit(0);
237
+ }
238
+ let payload = {};
239
+ try {
240
+ payload = JSON.parse(raw);
241
+ } catch {
242
+ process.exit(0);
243
+ }
244
+ const toolName = payload.tool_name || payload.toolName || payload.tool || "";
245
+ const isStop = !toolName && (payload.session_id || payload.stop_reason || payload.session_id_untruncated);
246
+ const effectiveTool = toolName || "Stop";
247
+ const sessionId = resolveSessionId(payload);
248
+ if (sessionEnabled()) {
249
+ const input2 = payload.tool_input ?? payload.input ?? {};
250
+ const { file: file2 } = derive(effectiveTool, input2);
251
+ if (isStop) endSession(agent, sessionId);
252
+ else heartbeat(agent, sessionId, { file: file2 });
253
+ }
254
+ if (!captureEnabled()) process.exit(0);
255
+ const input = payload.tool_input ?? payload.input ?? {};
256
+ const { file, summary } = derive(effectiveTool, input);
257
+ const normalized = JSON.stringify(input ?? {});
258
+ const hash = createHash("sha256").update(`${effectiveTool}|${normalized}`).digest("hex").slice(0, 16);
259
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
260
+ const branch = currentBranch();
261
+ if (existsSync3(OBSERVATIONS_FILE)) {
262
+ const data = readFileSync3(OBSERVATIONS_FILE, "utf-8");
263
+ for (const line of data.split("\n")) {
264
+ if (!line.startsWith(" ")) continue;
265
+ const p = line.trim().split("|");
266
+ if (p[5] === hash) {
267
+ const prev = new Date(p[0]).getTime();
268
+ if (Date.now() - prev < DEDUP_WINDOW_MS) process.exit(0);
269
+ }
270
+ }
271
+ }
272
+ if (!isStop && !toolName) process.exit(0);
273
+ appendObservation(`${ts}|${sessionId}|${agent}|${branch}|${effectiveTool}|${hash}|${file}|${summary}`);
274
+ process.exit(0);
275
+ }
276
+ main();