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.
@@ -0,0 +1,192 @@
1
+ // src/cli/session-start.ts
2
+ import { readFileSync as readFileSync2 } from "fs";
3
+
4
+ // src/lib/sessions.ts
5
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync, unlinkSync } from "fs";
6
+ import { join } from "path";
7
+ import { execSync } from "child_process";
8
+ var SESSION_TTL_MS = 10 * 60 * 1e3;
9
+ var PRUNE_STALE_MS = 10 * 60 * 1e3;
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 sessionDir() {
20
+ return join(process.cwd(), ".toon-memory", "memory", "sessions");
21
+ }
22
+ function sessionPath(id) {
23
+ return join(sessionDir(), `${id}.json`);
24
+ }
25
+ function ensureSessionDir() {
26
+ const dir = sessionDir();
27
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
28
+ }
29
+ function resolveSessionId(payload = {}) {
30
+ const fromPayload = payload.session_id || payload.sessionId || payload.session_id_untruncated;
31
+ if (fromPayload && fromPayload.trim()) return fromPayload.trim();
32
+ if (process.env.TOON_MEMORY_SESSION_ID && process.env.TOON_MEMORY_SESSION_ID.trim()) {
33
+ return process.env.TOON_MEMORY_SESSION_ID.trim();
34
+ }
35
+ return `proc-${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
36
+ }
37
+ function currentBranch() {
38
+ if (process.env.TOON_MEMORY_BRANCH && process.env.TOON_MEMORY_BRANCH.trim()) {
39
+ return process.env.TOON_MEMORY_BRANCH.trim();
40
+ }
41
+ try {
42
+ const branch = execSync("git rev-parse --abbrev-ref HEAD", {
43
+ encoding: "utf-8",
44
+ timeout: 2e3,
45
+ stdio: ["ignore", "pipe", "ignore"]
46
+ }).trim();
47
+ return branch || "unknown";
48
+ } catch {
49
+ return "unknown";
50
+ }
51
+ }
52
+ function readRecord(id) {
53
+ const p = sessionPath(id);
54
+ if (!existsSync(p)) return null;
55
+ try {
56
+ return JSON.parse(readFileSync(p, "utf-8"));
57
+ } catch {
58
+ return null;
59
+ }
60
+ }
61
+ function heartbeat(agent, sessionId, opts = {}) {
62
+ ensureSessionDir();
63
+ const now = (/* @__PURE__ */ new Date()).toISOString();
64
+ const existing = readRecord(sessionId);
65
+ const record = existing ? { ...existing, agent, pid: process.pid, lastSeen: now, branch: currentBranch(), ended: opts.ended ?? existing.ended } : {
66
+ id: sessionId,
67
+ agent,
68
+ pid: process.pid,
69
+ branch: currentBranch(),
70
+ startedAt: now,
71
+ lastSeen: now,
72
+ ended: opts.ended ?? false,
73
+ files: {}
74
+ };
75
+ if (opts.file && opts.file.trim()) {
76
+ record.files[opts.file.trim()] = now;
77
+ }
78
+ writeFileSync(sessionPath(sessionId), JSON.stringify(record, null, 2));
79
+ }
80
+ function recentIso(iso) {
81
+ const t = new Date(iso).getTime();
82
+ return !isNaN(t) && Date.now() - t <= SESSION_TTL_MS;
83
+ }
84
+ function listSessions() {
85
+ const dir = sessionDir();
86
+ if (!existsSync(dir)) return [];
87
+ return readdirSync(dir).filter((f) => f.endsWith(".json")).map((f) => {
88
+ try {
89
+ return JSON.parse(readFileSync(join(dir, f), "utf-8"));
90
+ } catch {
91
+ return null;
92
+ }
93
+ }).filter(Boolean).map((r) => {
94
+ const rec = r;
95
+ const active = recentIso(rec.lastSeen);
96
+ return { ...rec, active, ageMs: Date.now() - new Date(rec.lastSeen).getTime() };
97
+ }).sort((a, b) => b.lastSeen.localeCompare(a.lastSeen));
98
+ }
99
+ function pruneSessions() {
100
+ const pruned = [];
101
+ const dir = sessionDir();
102
+ if (!existsSync(dir)) return pruned;
103
+ for (const f of readdirSync(dir).filter((x) => x.endsWith(".json"))) {
104
+ const p = join(dir, f);
105
+ let rec = null;
106
+ try {
107
+ rec = JSON.parse(readFileSync(p, "utf-8"));
108
+ } catch {
109
+ continue;
110
+ }
111
+ if (!rec) continue;
112
+ const stale = Date.now() - new Date(rec.lastSeen).getTime() > PRUNE_STALE_MS;
113
+ if (stale && !isAlive(rec.pid)) {
114
+ try {
115
+ unlinkSync(p);
116
+ pruned.push(rec.id);
117
+ } catch {
118
+ }
119
+ }
120
+ }
121
+ return pruned;
122
+ }
123
+ function detectConflicts(active = listSessions().filter((s) => s.active)) {
124
+ const byFile = /* @__PURE__ */ new Map();
125
+ for (const s of active) {
126
+ if (s.ended) continue;
127
+ for (const file of Object.keys(s.files)) {
128
+ if (!byFile.has(file)) byFile.set(file, []);
129
+ byFile.get(file).push({ id: s.id, agent: s.agent, branch: s.branch });
130
+ }
131
+ }
132
+ const conflicts = [];
133
+ for (const [file, sessions] of byFile) {
134
+ if (sessions.length >= 2) conflicts.push({ file, sessions });
135
+ }
136
+ return conflicts;
137
+ }
138
+ function coordinationView(selfId) {
139
+ const all = listSessions();
140
+ const active = all.filter((s) => s.active);
141
+ const conflicts = detectConflicts(active);
142
+ const self = selfId ? all.find((s) => s.id === selfId) : void 0;
143
+ pruneSessions();
144
+ return { active, conflicts, self };
145
+ }
146
+
147
+ // src/cli/session-start.ts
148
+ function main() {
149
+ const agent = process.argv[2] || "agent";
150
+ let payload = {};
151
+ try {
152
+ const raw = readFileSync2(0, "utf-8");
153
+ if (raw.trim()) payload = JSON.parse(raw);
154
+ } catch {
155
+ }
156
+ const sessionId = resolveSessionId(payload);
157
+ try {
158
+ heartbeat(agent, sessionId);
159
+ } catch {
160
+ }
161
+ let view;
162
+ try {
163
+ view = coordinationView(sessionId);
164
+ } catch {
165
+ process.exit(0);
166
+ }
167
+ const others = view.active.filter((s) => s.id !== sessionId && !s.ended);
168
+ const lines = [];
169
+ lines.push("toon-memory:");
170
+ lines.push(` Esta sesi\xF3n: ${agent} @ ${currentBranch()} (ventana ${Math.round(SESSION_TTL_MS / 6e4)} min)`);
171
+ if (others.length > 0) {
172
+ lines.push(` Otras sesiones activas (${others.length}):`);
173
+ for (const s of others) {
174
+ const files = Object.keys(s.files).slice(0, 5).join(", ") || "\u2014";
175
+ lines.push(` \u2022 ${s.agent} @ ${s.branch} \u2014 ${files}`);
176
+ }
177
+ } else {
178
+ lines.push(" Sin otras sesiones activas.");
179
+ }
180
+ if (view.conflicts.length > 0) {
181
+ lines.push(` \u26A0\uFE0F Conflictos suaves (${view.conflicts.length}): usa memory_sessions para ver detalle.`);
182
+ for (const c of view.conflicts) {
183
+ lines.push(` \u2022 ${c.file}`);
184
+ }
185
+ } else {
186
+ lines.push(" Sin conflictos de archivos detectados.");
187
+ }
188
+ lines.push(" Usa memory_recall antes de leer archivos y memory_sessions para coordinar.");
189
+ console.log(lines.join("\n"));
190
+ process.exit(0);
191
+ }
192
+ main();
package/dist/cli/setup.js CHANGED
@@ -1,18 +1,35 @@
1
+ // src/cli/setup.ts
1
2
  import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, readdirSync, statSync, chmodSync, rmSync } from "fs";
2
3
  import { basename, dirname, join } from "path";
3
4
  import { fileURLToPath } from "url";
4
5
  import { createInterface } from "readline";
5
- import { gzipSync, gunzipSync } from "zlib";
6
- const __dirname = dirname(fileURLToPath(import.meta.url));
7
- const projectRoot = process.cwd();
8
- const sourceDir = join(__dirname, "..", "..", "src");
9
- const HOME = process.env.HOME || process.env.USERPROFILE || "~";
10
- const MEMORY_DIR = join(projectRoot, ".toon-memory", "memory");
11
- const HOOK_CONTENT = `#!/bin/bash
12
- echo "toon-memory: Use memory_recall BEFORE reading files for project context."
6
+ import { gzipSync } from "zlib";
7
+ var __dirname = dirname(fileURLToPath(import.meta.url));
8
+ var projectRoot = process.cwd();
9
+ var sourceDir = join(__dirname, "..", "..", "src");
10
+ var HOME = process.env.HOME || process.env.USERPROFILE || "~";
11
+ var MEMORY_DIR = join(projectRoot, ".toon-memory", "memory");
12
+ var CAPTURE_JS = join(__dirname, "capture.js");
13
+ var SESSION_START_JS = join(__dirname, "session-start.js");
14
+ function sessionStartHookContent(agentName) {
15
+ return `#!/bin/bash
16
+ node "${SESSION_START_JS}" ${agentName}
13
17
  exit 0
14
18
  `;
15
- const INSTRUCTION_CONTENT = `# toon-memory
19
+ }
20
+ var CAPTURE_CONFIG = join(MEMORY_DIR, "config.json");
21
+ function captureHookContent(agentName) {
22
+ return `#!/bin/bash
23
+ CFG="${CAPTURE_CONFIG}"
24
+ if [ -z "$TOON_MEMORY_CAPTURE" ]; then
25
+ if [ ! -f "$CFG" ]; then exit 0; fi
26
+ grep -q '"capture"[[:space:]]*:[[:space:]]*true' "$CFG" 2>/dev/null || exit 0
27
+ fi
28
+ node "${CAPTURE_JS}" ${agentName}
29
+ exit 0
30
+ `;
31
+ }
32
+ var INSTRUCTION_CONTENT = `# toon-memory
16
33
 
17
34
  Persistent memory for this project. Use it to avoid re-investigating things.
18
35
 
@@ -36,9 +53,10 @@ function detectAgents() {
36
53
  local: join(projectRoot, ".opencode", "opencode.json"),
37
54
  mcpKey: "mcp",
38
55
  format: "json",
39
- needsHooks: false,
56
+ needsHooks: true,
40
57
  needsInstructions: true,
41
- instructionFile: join(projectRoot, "AGENTS.md")
58
+ instructionFile: join(projectRoot, "AGENTS.md"),
59
+ captureJson: ["PostToolUse", "Stop"]
42
60
  });
43
61
  agents2.push({
44
62
  name: "vscode/copilot",
@@ -56,7 +74,8 @@ function detectAgents() {
56
74
  format: "json",
57
75
  needsHooks: true,
58
76
  needsInstructions: true,
59
- instructionFile: join(projectRoot, ".claude", "AGENTS.md")
77
+ instructionFile: join(projectRoot, ".claude", "AGENTS.md"),
78
+ captureJson: ["PostToolUse", "Stop"]
60
79
  });
61
80
  agents2.push({
62
81
  name: "cursor",
@@ -97,7 +116,8 @@ function detectAgents() {
97
116
  format: "toml",
98
117
  needsHooks: true,
99
118
  needsInstructions: true,
100
- instructionFile: join(projectRoot, ".codex", "AGENTS.md")
119
+ instructionFile: join(projectRoot, ".codex", "AGENTS.md"),
120
+ captureToml: ["post_tool_use", "stop"]
101
121
  });
102
122
  agents2.push({
103
123
  name: "gemini",
@@ -291,7 +311,7 @@ function installHooks(agent) {
291
311
  const hookDir = join(projectRoot, ".toon-memory", "hooks");
292
312
  if (!existsSync(hookDir)) mkdirSync(hookDir, { recursive: true });
293
313
  const hookPath = join(hookDir, `session-start-${agent.name}.sh`);
294
- writeFileSync(hookPath, HOOK_CONTENT);
314
+ writeFileSync(hookPath, sessionStartHookContent(agent.name));
295
315
  chmodSync(hookPath, 493);
296
316
  console.log(` Hook script created at ${hookPath}`);
297
317
  if (agent.format === "toml" && agent.local) {
@@ -299,6 +319,57 @@ function installHooks(agent) {
299
319
  } else if (agent.format === "json" || agent.format === "jsonc") {
300
320
  registerHookJSON(agent, hookPath);
301
321
  }
322
+ if (agent.captureJson && agent.format === "json") {
323
+ const capPath = join(hookDir, `capture-${agent.name}.sh`);
324
+ writeFileSync(capPath, captureHookContent(agent.name));
325
+ chmodSync(capPath, 493);
326
+ console.log(` Capture hook created at ${capPath}`);
327
+ registerCaptureHookJSON(agent, capPath);
328
+ }
329
+ if (agent.captureToml && agent.format === "toml" && agent.local) {
330
+ const capPath = join(hookDir, `capture-${agent.name}.sh`);
331
+ writeFileSync(capPath, captureHookContent(agent.name));
332
+ chmodSync(capPath, 493);
333
+ console.log(` Capture hook created at ${capPath}`);
334
+ registerCaptureHookTOML(agent, capPath);
335
+ }
336
+ }
337
+ function registerCaptureHookJSON(agent, scriptPath) {
338
+ const configPath = agent.local || agent.global;
339
+ if (!configPath) return;
340
+ const configDir = dirname(configPath);
341
+ if (!existsSync(configDir)) mkdirSync(configDir, { recursive: true });
342
+ let config = {};
343
+ if (existsSync(configPath)) {
344
+ try {
345
+ config = JSON.parse(readFileSync(configPath, "utf-8"));
346
+ } catch {
347
+ config = {};
348
+ }
349
+ }
350
+ if (!config.hooks) config.hooks = {};
351
+ for (const event of agent.captureJson || []) {
352
+ if (!config.hooks[event]) config.hooks[event] = [];
353
+ if (!config.hooks[event].some((h) => h.command === scriptPath)) {
354
+ config.hooks[event].push({ command: scriptPath });
355
+ }
356
+ }
357
+ writeFileSync(configPath, JSON.stringify(config, null, 2));
358
+ console.log(` Capture hooks registered in ${configPath}`);
359
+ }
360
+ function registerCaptureHookTOML(agent, scriptPath) {
361
+ const configPath = agent.local;
362
+ if (!configPath || !existsSync(configPath)) return;
363
+ let content = readFileSync(configPath, "utf-8");
364
+ for (const event of agent.captureToml || []) {
365
+ if (content.includes(`[hooks.${event}]`)) continue;
366
+ content += `
367
+ [hooks.${event}]
368
+ command = "${scriptPath}"
369
+ `;
370
+ }
371
+ writeFileSync(configPath, content);
372
+ console.log(` Capture hooks registered in ${configPath}`);
302
373
  }
303
374
  function registerHookTOML(agent, hookPath) {
304
375
  const configPath = agent.local;
@@ -334,7 +405,7 @@ function registerHookJSON(agent, hookPath) {
334
405
  config = {};
335
406
  }
336
407
  }
337
- if (agent.name === "claude") {
408
+ if (agent.name === "claude" || agent.name === "opencode") {
338
409
  if (!config.hooks) config.hooks = {};
339
410
  if (!config.hooks.SessionStart) config.hooks.SessionStart = [];
340
411
  if (!config.hooks.SessionStart.some((h) => h.command === hookPath)) {
@@ -445,6 +516,16 @@ function status() {
445
516
  } else {
446
517
  console.log("Memory: not initialized");
447
518
  }
519
+ let capture = false;
520
+ if (process.env.TOON_MEMORY_CAPTURE) capture = true;
521
+ else if (existsSync(CAPTURE_CONFIG)) {
522
+ try {
523
+ const c = JSON.parse(readFileSync(CAPTURE_CONFIG, "utf-8"));
524
+ if (c.capture) capture = true;
525
+ } catch {
526
+ }
527
+ }
528
+ console.log(`Capture: ${capture ? "enabled" : "disabled (opt-in)"}`);
448
529
  const agents2 = detectAgents();
449
530
  console.log("\nAgent configs:");
450
531
  for (const agent of agents2) {
@@ -671,9 +752,6 @@ function pruneBackups(backupDir, maxBackups) {
671
752
  function compressData(data) {
672
753
  return gzipSync(Buffer.from(data, "utf-8"));
673
754
  }
674
- function decompressData(data) {
675
- return gunzipSync(data).toString("utf-8");
676
- }
677
755
  function watch() {
678
756
  console.log("\n\u{1F9E0} toon-memory watch\n");
679
757
  const memoryFile = join(MEMORY_DIR, "data.toon");
@@ -752,7 +830,31 @@ function watch() {
752
830
  process.exit(0);
753
831
  });
754
832
  }
755
- const args = process.argv.slice(2);
833
+ function captureToggle(enable) {
834
+ if (!existsSync(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true });
835
+ let config = {};
836
+ if (existsSync(CAPTURE_CONFIG)) {
837
+ try {
838
+ config = JSON.parse(readFileSync(CAPTURE_CONFIG, "utf-8"));
839
+ } catch {
840
+ config = {};
841
+ }
842
+ }
843
+ config.capture = enable;
844
+ writeFileSync(CAPTURE_CONFIG, JSON.stringify(config, null, 2));
845
+ if (enable) {
846
+ console.log("\n\u{1F534} Captura de actividad HABILITADA.");
847
+ console.log("Los hooks grabar\xE1n observaciones en .toon-memory/memory/observations.toon.");
848
+ console.log("Revisa con `memory_captured` y promu\xE9velas con `memory_remember`.\n");
849
+ } else {
850
+ console.log("\n\u26AA Captura de actividad DESHABILITADA.\n");
851
+ }
852
+ }
853
+ var args = process.argv.slice(2);
854
+ if (args[0] === "capture") {
855
+ captureToggle(args[1] === "on");
856
+ process.exit(0);
857
+ }
756
858
  if (args[0] === "uninstall") {
757
859
  uninstall();
758
860
  process.exit(0);
@@ -785,7 +887,7 @@ if (args[0] === "watch") {
785
887
  watch();
786
888
  process.exit(0);
787
889
  }
788
- const agents = detectAgents();
890
+ var agents = detectAgents();
789
891
  console.log("\n\u{1F9E0} toon-memory installer\n");
790
892
  console.log("Available agents:");
791
893
  agents.forEach((a, i) => {
@@ -794,7 +896,7 @@ agents.forEach((a, i) => {
794
896
  console.log(` ${indicator} ${i + 1}. ${a.name}`);
795
897
  });
796
898
  console.log("");
797
- const rl = createInterface({ input: process.stdin, output: process.stdout });
899
+ var rl = createInterface({ input: process.stdin, output: process.stdout });
798
900
  rl.question("Select agents (numbers separated by commas, 'all', or Enter for all): ", (answer) => {
799
901
  let selected;
800
902
  const trimmed = answer.trim().toLowerCase();
@@ -1,7 +1,8 @@
1
+ // src/cli/toon-memory.ts
1
2
  import { dirname, join } from "path";
2
3
  import { fileURLToPath } from "url";
3
- const __dirname = dirname(fileURLToPath(import.meta.url));
4
- const args = process.argv.slice(2);
4
+ var __dirname = dirname(fileURLToPath(import.meta.url));
5
+ var args = process.argv.slice(2);
5
6
  if (args[0] === "mcp") {
6
7
  await import(join(__dirname, "..", "mcp", "server.js"));
7
8
  } else {