corvusmem 0.2.1 → 0.3.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/CHANGELOG.md CHANGED
@@ -4,6 +4,32 @@ All notable changes to **Corvusmem** are documented here.
4
4
  Format based on [Keep a Changelog](https://keepachangelog.com/); versions follow [SemVer](https://semver.org/).
5
5
 
6
6
  ## [Unreleased]
7
+
8
+ ## [0.3.0] — 2026-11-05
9
+ ### Added
10
+ - **Standalone project folder.** In a project without Senzu, Corvus now keeps its memory in its own
11
+ `.corvusmem/` directory (facts + `MEMORIA.md`) instead of `senzu/`. With Senzu present it still couples to
12
+ `senzu/` (expected); an existing `.corvusmem/` is kept, and legacy Senzu layouts are untouched.
13
+ - **`corvusmem import`.** Deterministic, offline, read-only discovery of the memory documents already in a project,
14
+ in two tiers: `agent` — known agent-memory files (`CLAUDE.md`/`CLAUDE.local.md` incl. nested, `AGENTS.md`, `GEMINI.md`,
15
+ `.github/copilot-instructions.md`, Cursor rules, a Senzu `MEMORIA.md`) — and `doc` — any other markdown in subfolders
16
+ that may hold memory (e.g. `docs/architecture.md`, `notes/decisions.md`), minus boilerplate (README, CHANGELOG, LICENSE…).
17
+ `--json` prints the machine contract.
18
+ - **`/corvus-absorb` command.** Installed into `.claude/commands/` (and bundled in the Codex/Claude plugin). It reads
19
+ the documents `import` finds, judges what is durable memory, **asks the user when a `doc`-tier file or a fact's family
20
+ is unclear**, and saves the rest with `corvusmem --save` — so teammates keep what they already wrote instead of
21
+ starting over. The engine stays deterministic; the judgment is the agent's.
22
+
23
+ ## [0.2.2] — 2026-11-05
24
+ ### Fixed
25
+ - **Portable, durable hook paths.** `install` now copies the hook files into a stable location (`.corvusmem/hooks/`
26
+ per project, `~/.config/corvusmem/hooks/` for a global install) and references them with `${CLAUDE_PROJECT_DIR}`
27
+ (per-project) or an absolute path (global) — instead of the ephemeral `npx` cache path (`…/_npx/<hash>/…`). This
28
+ fixes hooks silently not running after npx clears its cache, on a fresh reinstall, or when a committed project
29
+ `.claude/settings.json` + `.corvusmem/` is shared with a teammate (now portable across machines and OSes). A
30
+ reinstall also removes any old npx-path entries. `uninstall` removes the copied hooks but keeps your memory.
31
+
32
+ ## [0.2.1] — 2026-11-05
7
33
  ### Changed
8
34
  - The memory-map **zone names** now follow the UI language (English by default, Spanish with `CORVUS_LANG`/marker
9
35
  `lang`), closing the last Spanish label in the injected memory map.
package/cli/corvusmem.mjs CHANGED
@@ -1,22 +1,24 @@
1
- #!/usr/bin/env node
2
- // Despachador del CLI `corvusmem`: el subcomando decide a quién llama.
3
- // corvusmem install [--claude|--codex|--global|--plugin <dir>...] -> install.mjs (instalar/empaquetar)
4
- // corvusmem uninstall [...] -> install.mjs --uninstall
5
- // corvusmem <lo que sea> -> cli/memory.mjs (la CLI de memoria)
6
- // Asi `npx corvusmem install --claude` funciona una vez publicado (npm) o con el repo publico (npx github:...).
7
- import { spawnSync } from 'node:child_process';
8
- import path from 'node:path';
9
- import { fileURLToPath } from 'node:url';
10
-
11
- const AQUI = path.dirname(fileURLToPath(import.meta.url));
12
- const ROOT = path.join(AQUI, '..');
13
- const argv = process.argv.slice(2);
14
- const sub = argv[0];
15
-
16
- let destino, args;
17
- if (sub === 'install') { destino = path.join(ROOT, 'install.mjs'); args = argv.slice(1); }
18
- else if (sub === 'uninstall') { destino = path.join(ROOT, 'install.mjs'); args = ['--uninstall', ...argv.slice(1)]; }
19
- else { destino = path.join(ROOT, 'cli', 'memory.mjs'); args = argv; }
20
-
21
- const r = spawnSync(process.execPath, [destino, ...args], { stdio: 'inherit' });
22
- process.exit(r.status == null ? 1 : r.status);
1
+ #!/usr/bin/env node
2
+ // Despachador del CLI `corvusmem`: el subcomando decide a quién llama.
3
+ // corvusmem install [--claude|--codex|--global|--plugin <dir>...] -> install.mjs (instalar/empaquetar)
4
+ // corvusmem uninstall [...] -> install.mjs --uninstall
5
+ // corvusmem import [--json] -> cli/import.mjs (find existing memory docs)
6
+ // corvusmem <lo que sea> -> cli/memory.mjs (la CLI de memoria)
7
+ // Asi `npx corvusmem install --claude` funciona una vez publicado (npm) o con el repo publico (npx github:...).
8
+ import { spawnSync } from 'node:child_process';
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+
12
+ const AQUI = path.dirname(fileURLToPath(import.meta.url));
13
+ const ROOT = path.join(AQUI, '..');
14
+ const argv = process.argv.slice(2);
15
+ const sub = argv[0];
16
+
17
+ let destino, args;
18
+ if (sub === 'install') { destino = path.join(ROOT, 'install.mjs'); args = argv.slice(1); }
19
+ else if (sub === 'uninstall') { destino = path.join(ROOT, 'install.mjs'); args = ['--uninstall', ...argv.slice(1)]; }
20
+ else if (sub === 'import') { destino = path.join(ROOT, 'cli', 'import.mjs'); args = argv.slice(1); }
21
+ else { destino = path.join(ROOT, 'cli', 'memory.mjs'); args = argv; }
22
+
23
+ const r = spawnSync(process.execPath, [destino, ...args], { stdio: 'inherit' });
24
+ process.exit(r.status == null ? 1 : r.status);
package/cli/import.mjs ADDED
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+ // `corvusmem import` — list the memory documents already in this project, in two tiers, so the agent
3
+ // (via /corvus-absorb) can read them and save what matters. Deterministic, offline, READ-ONLY: it writes
4
+ // nothing to memory. `--json` prints the machine-readable contract the command consumes.
5
+ import { escanearMemoria } from '../src/import.mjs';
6
+
7
+ const argv = process.argv.slice(2);
8
+ const json = argv.includes('--json');
9
+ const root = process.env.CLAUDE_PROJECT_DIR || process.cwd();
10
+ const r = escanearMemoria(root);
11
+
12
+ if (json) { process.stdout.write(JSON.stringify(r, null, 2) + '\n'); process.exit(0); }
13
+
14
+ if (!r.total) {
15
+ process.stdout.write('No existing memory documents found (CLAUDE.md, AGENTS.md, MEMORIA.md, Cursor rules, docs/*.md…).\n');
16
+ process.exit(0);
17
+ }
18
+ const KIND = { claude: 'Claude', agents: 'AGENTS.md', gemini: 'Gemini', copilot: 'Copilot', cursor: 'Cursor', windsurf: 'Windsurf', senzu: 'Senzu', markdown: 'markdown' };
19
+ const line = f => ` • ${f.rel} (${KIND[f.kind] || f.kind}, ${f.lines} lines)\n`;
20
+ const agent = r.files.filter(f => f.tier === 'agent');
21
+ const docs = r.files.filter(f => f.tier === 'doc');
22
+
23
+ process.stdout.write(`Found ${r.total} document${r.total > 1 ? 's' : ''} Corvus can absorb:\n\n`);
24
+ if (agent.length) { process.stdout.write(`Agent memory (${agent.length}):\n`); for (const f of agent) process.stdout.write(line(f)); }
25
+ if (docs.length) {
26
+ if (agent.length) process.stdout.write('\n');
27
+ process.stdout.write(`Other markdown that may hold memory (${docs.length}):\n`);
28
+ for (const f of docs) process.stdout.write(line(f));
29
+ if (r.truncated) process.stdout.write(' … more not shown\n');
30
+ }
31
+ process.stdout.write('\nRun /corvus-absorb inside Claude Code to read them and save what matters into memory.\n');
32
+ process.exit(0);
@@ -0,0 +1,52 @@
1
+ ---
2
+ description: Absorb the project's existing memory (CLAUDE.md, AGENTS.md, Cursor rules, a Senzu MEMORIA.md) into Corvus so nothing the team already wrote is lost.
3
+ ---
4
+
5
+ You are absorbing this project's **existing** memory into Corvus. The goal: a teammate adopting Corvus keeps everything they already wrote, instead of starting from scratch.
6
+
7
+ **Speak the user's language.** Every question, confirmation and the final report go in the language the user writes to you in (Spanish, etc.) — only this command's name and the saved `--keys` identifiers stay in English (and `--keys` should also include the user's own language).
8
+
9
+ ## 1. Find the documents (deterministic — let the tool do this)
10
+ Run:
11
+
12
+ ```
13
+ npx corvusmem import --json
14
+ ```
15
+
16
+ It returns the memory documents already in the repo in two tiers (`{ agent, docs, truncated, files: [{ tier, kind, rel, lines }] }`):
17
+
18
+ - **`tier: "agent"`** — known agent-memory files (CLAUDE.md, AGENTS.md, Cursor/Copilot/Gemini rules, a Senzu MEMORIA.md). High confidence: read and absorb these.
19
+ - **`tier: "doc"`** — other markdown that *may* hold memory, found in subfolders (e.g. `docs/architecture.md`, `notes/decisions.md`). These are candidates, not certainties.
20
+
21
+ If the list is empty, say so and stop. If `truncated` is true, mention that more markdown exists than was shown.
22
+
23
+ ## 2. Read and judge (this is YOUR job, not the tool's)
24
+ Read every **`agent`**-tier file. For **`doc`**-tier files, open the ones whose name or location suggests memory (architecture, decisions, conventions, ADRs, domain notes); **when it is unclear whether a `doc` file is worth absorbing, ask the user** — list the file(s) and ask which to include, rather than guessing or dumping everything.
25
+
26
+ From whatever you read, keep **only durable memory** — what should still be true next week:
27
+
28
+ - decisions, with the reason behind them
29
+ - rules and conventions the team must follow
30
+ - user / team preferences
31
+ - project facts (stack, architecture, domains, external services, environments)
32
+ - constraints, known gotchas, "what didn't work"
33
+ - open goals or pending tasks
34
+
35
+ Ignore the noise: install/run steps, generic boilerplate, tool tutorials, anything obvious from the code, and anything transient.
36
+
37
+ ## 3. Save each item (deterministic sink)
38
+ For every item worth keeping, run one command:
39
+
40
+ ```
41
+ npx corvusmem --save --dimension <family.topic> --value "<self-contained statement>" --keys "<term-en>,<term-native>" --source agente
42
+ ```
43
+
44
+ - `family` is one of: `identity`, `preference`, `project`, `goal`, `pending`, `constraint`, `note`, `fact`, `learning`, `link`.
45
+ - Make `--value` stand on its own: name the thing and use absolute dates (e.g. "Payments go through Stripe with idempotent webhooks (one key per event)", not "we use it").
46
+ - `--keys`: a few search terms, including the user's own language.
47
+ - Add `--scope usuario` only for facts true across **all** the user's projects; the default is this project.
48
+ - Corvus de-duplicates by dimension, so re-running is safe — a repeated value is not stored twice.
49
+ - If you cannot tell which family a fact belongs to, or whether two notes are the same fact, **ask the user** instead of guessing.
50
+
51
+ ## 4. Report
52
+ Finish with a short summary: how many documents you read, how many facts you saved (grouped by family), and anything you deliberately skipped and why. **Do not delete or modify the original files** — they stay as they are.
package/install.mjs CHANGED
@@ -1,162 +1,218 @@
1
- #!/usr/bin/env node
2
- // Instalador de Corvusmem (F10-T2). Registra los hooks del núcleo y prepara las carpetas de memoria, sin
3
- // dependencias y sin red. Determinista, merge-safe (no pisa lo que el usuario ya tenga) e idempotente.
4
- //
5
- // node install.mjs [opciones]
6
- // --project <dir> proyecto destino (por defecto: el directorio actual)
7
- // --home <dir> HOME para la memoria global y los ajustes de usuario (por defecto: el del sistema)
8
- // --global registra los hooks en el HOME (todos los proyectos) en vez de en el proyecto
9
- // --uninstall quita los hooks de Corvusmem (deja intacto lo demás)
10
- // --dry-run enseña lo que haría, sin escribir
11
- // --plugin <dir> empaqueta un PLUGIN autocontenido (Claude/Codex) en <dir> y sale (no toca settings.json)
12
- //
13
- // Claude: registra los hooks en .claude/settings.json (o ~/.claude/settings.json con --global), fusionando.
14
- // Codex: ejecuta los hooks por la vía de PLUGIN. Con `--plugin <dir>` se genera ese plugin en el MISMO formato que el
15
- // plugin de Senzu que Codex ya consume: .claude-plugin/plugin.json + hooks/hooks.json (con ${CLAUDE_PLUGIN_ROOT}) +
16
- // los .mjs del núcleo. El usuario lo publica en un marketplace de Codex, lo instala y aprueba los hooks en la app
17
- // (quedan en ~/.codex/config.toml -> hooks.state). Sin --plugin, el instalador deja el manifiesto .corvusmem/hooks.json.
18
- import fs from 'node:fs';
19
- import os from 'node:os';
20
- import path from 'node:path';
21
- import { fileURLToPath } from 'node:url';
22
-
23
- const AQUI = path.dirname(fileURLToPath(import.meta.url));
24
- const SRC = path.join(AQUI, 'src'); // donde viven los hooks del núcleo (ruta absoluta)
25
- const args = process.argv.slice(2);
26
- const opt = n => { const i = args.indexOf(n); return i >= 0 ? (args[i + 1] && !args[i + 1].startsWith('--') ? args[i + 1] : true) : null; };
27
- const has = n => args.includes(n);
28
-
29
- const PROYECTO = path.resolve(opt('--project') && opt('--project') !== true ? String(opt('--project')) : process.cwd());
30
- const HOME = path.resolve(opt('--home') && opt('--home') !== true ? String(opt('--home')) : os.homedir());
31
- const GLOBAL = has('--global');
32
- const DRY = has('--dry-run');
33
- const log = s => process.stdout.write(s + '\n');
34
-
35
- // El conjunto de hooks de CEREBRO (sin el método Senzu: ni router, ni guards, ni skill-reminders).
36
- const HOOKSET = {
37
- SessionStart: [{ files: ['session-start.mjs'] }],
38
- UserPromptSubmit: [{ files: ['live-memory.mjs', 'live-recall.mjs'] }],
39
- PreToolUse: [{ matcher: 'Edit|Write|MultiEdit|NotebookEdit|apply_patch', files: ['file-memory.mjs'] }],
40
- PostToolUse: [{ matcher: 'Edit|Write|MultiEdit|apply_patch', files: ['facts-guard.mjs'] },
41
- { matcher: 'Bash|PowerShell', files: ['facts-guard.mjs'] }],
42
- Stop: [{ files: ['session-state.mjs', 'facts-guard.mjs'] }],
43
- SessionEnd: [{ files: ['session-end.mjs'] }],
44
- };
45
-
46
- const cmdDe = file => `node "${path.join(SRC, file).replace(/\\/g, '/')}"`; // runtime garantizado: node, rutas con /
47
- const esNuestro = cmd => typeof cmd === 'string' && cmd.includes(SRC.replace(/\\/g, '/')); // nuestras entradas, por su ruta
48
-
49
- // Para EMPAQUETAR como plugin (Claude/Codex): el comando apunta al propio plugin, no a una ruta de la maquina.
50
- const cmdPlugin = file => `node "\${CLAUDE_PLUGIN_ROOT}/hooks/${file}"`;
51
- function gruposPlugin(ev) {
52
- return HOOKSET[ev].map(g => {
53
- const grp = {};
54
- if (g.matcher) grp.matcher = g.matcher;
55
- grp.hooks = g.files.map(f => ({ type: 'command', command: cmdPlugin(f), timeout: ev === 'SessionEnd' ? 5 : 30 }));
56
- return grp;
57
- });
58
- }
59
-
60
- // Empaqueta Corvusmem como PLUGIN autocontenido (mismo formato que el plugin de Senzu que Codex ya consume):
61
- // .claude-plugin/plugin.json + hooks/hooks.json (con ${CLAUDE_PLUGIN_ROOT}) + los .mjs del nucleo copiados a hooks/.
62
- // El usuario lo publica en un marketplace de Codex, lo instala y APRUEBA los hooks en la app (quedan en
63
- // ~/.codex/config.toml -> hooks.state). Vale igual como plugin de Claude.
64
- function empaquetarPlugin(destino) {
65
- const dir = path.resolve(destino);
66
- let pkg = {}; try { pkg = JSON.parse(fs.readFileSync(path.join(AQUI, 'package.json'), 'utf8')); } catch {}
67
- if (DRY) { log(` [dry-run] would package the plugin in ${dir}`); return; }
68
- const hooksDir = path.join(dir, 'hooks');
69
- fs.mkdirSync(hooksDir, { recursive: true });
70
- fs.mkdirSync(path.join(dir, '.claude-plugin'), { recursive: true });
71
- // 1) hooks.json en formato de plugin (CLAUDE_PLUGIN_ROOT), mismos eventos que el HOOKSET
72
- const h = {}; for (const ev of Object.keys(HOOKSET)) h[ev] = gruposPlugin(ev);
73
- fs.writeFileSync(path.join(hooksDir, 'hooks.json'), JSON.stringify({ hooks: h }, null, 2) + '\n');
74
- // 2) los .mjs del nucleo (hooks + dependencias de mismo directorio: autocontenido, cero imports externos)
75
- let n = 0;
76
- for (const f of fs.readdirSync(SRC)) if (f.endsWith('.mjs')) { fs.copyFileSync(path.join(SRC, f), path.join(hooksDir, f)); n++; }
77
- // 3) plugin.json
78
- const plugin = { name: 'corvusmem', description: pkg.description || 'Memoria determinista, offline y sin dependencias para agentes de IA.', version: pkg.version || '0.0.0', author: { name: 'Peterson Sena' }, license: 'SEE LICENSE IN LICENSE' };
79
- fs.writeFileSync(path.join(dir, '.claude-plugin', 'plugin.json'), JSON.stringify(plugin, null, 2) + '\n');
80
- log(` [plugin] ${dir}: .claude-plugin/plugin.json + hooks/hooks.json + ${n} .mjs`);
81
- log(' Publish it to a Codex marketplace (like Senzu\'s); install it and approve the hooks in the app.');
82
- }
83
-
84
- // Construye los grupos de hooks de un evento en el formato de settings.json de Claude.
85
- function gruposDe(ev) {
86
- return HOOKSET[ev].map(g => {
87
- const grp = {};
88
- if (g.matcher) grp.matcher = g.matcher;
89
- grp.hooks = g.files.map(f => ({ type: 'command', command: cmdDe(f), timeout: ev === 'SessionEnd' ? 5 : 30 }));
90
- return grp;
91
- });
92
- }
93
-
94
- function leerJson(file) { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { if (e.code === 'ENOENT') return {}; throw e; } }
95
-
96
- // Fusiona en settings.json: quita SOLO lo nuestro (por la ruta) y, si no es --uninstall, vuelve a ponerlo.
97
- function fusionar(settings, { quitar }) {
98
- const hooks = settings.hooks && typeof settings.hooks === 'object' ? settings.hooks : {};
99
- for (const ev of Object.keys(HOOKSET)) {
100
- const existentes = Array.isArray(hooks[ev]) ? hooks[ev] : [];
101
- // de los grupos que había, conserva los hooks que NO son nuestros (así no pisamos los del usuario)
102
- const ajenos = existentes
103
- .map(g => ({ ...g, hooks: (Array.isArray(g.hooks) ? g.hooks : []).filter(h => !esNuestro(h && h.command)) }))
104
- .filter(g => g.hooks.length);
105
- const nuevos = quitar ? [] : gruposDe(ev);
106
- const total = ajenos.concat(nuevos);
107
- if (total.length) hooks[ev] = total; else delete hooks[ev];
108
- }
109
- if (Object.keys(hooks).length) settings.hooks = hooks; else delete settings.hooks;
110
- return settings;
111
- }
112
-
113
- function escribir(file, obj) {
114
- if (DRY) { log(` [dry-run] would write ${file}`); return; }
115
- fs.mkdirSync(path.dirname(file), { recursive: true });
116
- fs.writeFileSync(file, JSON.stringify(obj, null, 2) + '\n');
117
- }
118
-
119
- function asegurarDir(dir) {
120
- if (DRY) { log(` [dry-run] would create ${dir}`); return; }
121
- fs.mkdirSync(dir, { recursive: true });
122
- }
123
-
124
- function run() {
125
- if (!fs.existsSync(path.join(SRC, 'facts.mjs'))) { log(`Core not found in ${SRC}. Run install.mjs from the Corvusmem repo.`); process.exit(2); }
126
-
127
- // Modo empaquetar plugin (Claude/Codex): no toca settings.json; genera un plugin autocontenido en <dir>.
128
- const destinoPlugin = opt('--plugin');
129
- if (destinoPlugin && destinoPlugin !== true) {
130
- log(`Corvusmem · package plugin (Claude/Codex)${DRY ? ' (dry-run)' : ''}`);
131
- empaquetarPlugin(destinoPlugin);
132
- log('Done.');
133
- return;
134
- }
135
-
136
- const quitar = has('--uninstall');
137
- log(`Corvusmem · ${quitar ? 'uninstall' : 'install'}${GLOBAL ? ' (global)' : ''}${DRY ? ' (dry-run)' : ''}`);
138
-
139
- // 1) Claude: hooks en settings.json (proyecto o HOME)
140
- const settingsFile = GLOBAL ? path.join(HOME, '.claude', 'settings.json') : path.join(PROYECTO, '.claude', 'settings.json');
141
- let settings;
142
- try { settings = leerJson(settingsFile); }
143
- catch { log(` [claude] WARNING: ${settingsFile} is not valid JSON; leaving it untouched (fix it and retry).`); process.exit(2); }
144
- escribir(settingsFile, fusionar(settings, { quitar }));
145
- log(` [claude] ${quitar ? 'Corvusmem hooks removed from' : 'hooks registered in'} ${settingsFile}`);
146
-
147
- // 2) Manifiesto portable de hooks (lo consume el plugin para Claude/Codex, F10-T4)
148
- const manifest = path.join(PROYECTO, '.corvusmem', 'hooks.json');
149
- if (quitar) { if (!DRY) { try { fs.rmSync(manifest, { force: true }); } catch {} } log(` [manifest] removed ${manifest}`); }
150
- else { const h = {}; for (const ev of Object.keys(HOOKSET)) h[ev] = gruposDe(ev); escribir(manifest, { hooks: h }); log(` [manifest] ${manifest} (used by the Codex/Claude plugin)`); }
151
-
152
- // 3) Carpetas de memoria (no se borran al desinstalar: son datos del usuario)
153
- if (!quitar) {
154
- asegurarDir(path.join(PROYECTO, '.corvusmem')); // memoria del proyecto
155
- asegurarDir(path.join(HOME, '.config', 'corvusmem')); // memoria global del usuario
156
- log(' [memory] .corvusmem/ (project) and ~/.config/corvusmem/ (global) ready');
157
- }
158
-
159
- log('Done.' + (quitar ? '' : ' Codex: per-event hooks go through the plugin; in Claude they are already active.'));
160
- }
161
-
162
- run();
1
+ #!/usr/bin/env node
2
+ // Instalador de Corvusmem (F10-T2). Registra los hooks del núcleo y prepara las carpetas de memoria, sin
3
+ // dependencias y sin red. Determinista, merge-safe (no pisa lo que el usuario ya tenga) e idempotente.
4
+ //
5
+ // node install.mjs [opciones]
6
+ // --project <dir> proyecto destino (por defecto: el directorio actual)
7
+ // --home <dir> HOME para la memoria global y los ajustes de usuario (por defecto: el del sistema)
8
+ // --global registra los hooks en el HOME (todos los proyectos) en vez de en el proyecto
9
+ // --uninstall quita los hooks de Corvusmem (deja intacto lo demás)
10
+ // --dry-run enseña lo que haría, sin escribir
11
+ // --plugin <dir> empaqueta un PLUGIN autocontenido (Claude/Codex) en <dir> y sale (no toca settings.json)
12
+ //
13
+ // Claude: registra los hooks en .claude/settings.json (o ~/.claude/settings.json con --global), fusionando.
14
+ // Codex: ejecuta los hooks por la vía de PLUGIN. Con `--plugin <dir>` se genera ese plugin en el MISMO formato que el
15
+ // plugin de Senzu que Codex ya consume: .claude-plugin/plugin.json + hooks/hooks.json (con ${CLAUDE_PLUGIN_ROOT}) +
16
+ // los .mjs del núcleo. El usuario lo publica en un marketplace de Codex, lo instala y aprueba los hooks en la app
17
+ // (quedan en ~/.codex/config.toml -> hooks.state). Sin --plugin, el instalador deja el manifiesto .corvusmem/hooks.json.
18
+ import fs from 'node:fs';
19
+ import os from 'node:os';
20
+ import path from 'node:path';
21
+ import { fileURLToPath } from 'node:url';
22
+
23
+ const AQUI = path.dirname(fileURLToPath(import.meta.url));
24
+ const SRC = path.join(AQUI, 'src'); // donde viven los hooks del núcleo (ruta absoluta)
25
+ const CMDS_SRC = path.join(AQUI, 'commands'); // slash-command templates (/corvus-absorb)
26
+ const args = process.argv.slice(2);
27
+ const opt = n => { const i = args.indexOf(n); return i >= 0 ? (args[i + 1] && !args[i + 1].startsWith('--') ? args[i + 1] : true) : null; };
28
+ const has = n => args.includes(n);
29
+
30
+ const PROYECTO = path.resolve(opt('--project') && opt('--project') !== true ? String(opt('--project')) : process.cwd());
31
+ const HOME = path.resolve(opt('--home') && opt('--home') !== true ? String(opt('--home')) : os.homedir());
32
+ const GLOBAL = has('--global');
33
+ const DRY = has('--dry-run');
34
+ const log = s => process.stdout.write(s + '\n');
35
+
36
+ // El conjunto de hooks de CEREBRO (sin el método Senzu: ni router, ni guards, ni skill-reminders).
37
+ const HOOKSET = {
38
+ SessionStart: [{ files: ['session-start.mjs'] }],
39
+ UserPromptSubmit: [{ files: ['live-memory.mjs', 'live-recall.mjs'] }],
40
+ PreToolUse: [{ matcher: 'Edit|Write|MultiEdit|NotebookEdit|apply_patch', files: ['file-memory.mjs'] }],
41
+ PostToolUse: [{ matcher: 'Edit|Write|MultiEdit|apply_patch', files: ['facts-guard.mjs'] },
42
+ { matcher: 'Bash|PowerShell', files: ['facts-guard.mjs'] }],
43
+ Stop: [{ files: ['session-state.mjs', 'facts-guard.mjs'] }],
44
+ SessionEnd: [{ files: ['session-end.mjs'] }],
45
+ };
46
+
47
+ // Los hooks del nucleo se COPIAN a un sitio DURABLE (NO la ruta efimera de npx `_npx/<hash>` ni node_modules): el
48
+ // proyecto (.corvusmem/hooks) o el HOME global (~/.config/corvusmem/hooks). El comando del settings.json apunta ahi,
49
+ // asi sobrevive a que npx limpie su cache y cada instalacion queda autocontenida.
50
+ const hooksDir = GLOBAL ? path.join(HOME, '.config', 'corvusmem', 'hooks') : path.join(PROYECTO, '.corvusmem', 'hooks');
51
+ // En PROYECTO, $CLAUDE_PROJECT_DIR hace el settings.json PORTABLE: al commitear .corvusmem/ y .claude/settings.json,
52
+ // vale para todo el equipo en cualquier maquina/OS. En GLOBAL, ruta absoluta al HOME (los settings globales no se
53
+ // comparten entre maquinas).
54
+ const cmdDe = file => GLOBAL
55
+ ? `node "${path.join(hooksDir, file).replace(/\\/g, '/')}"`
56
+ : `node "\${CLAUDE_PROJECT_DIR}/.corvusmem/hooks/${file}"`; // forma braceada documentada (portable Win/Mac/Linux)
57
+ // Nuestras entradas (para fusionar sin pisar las del usuario y para MIGRAR las viejas con ruta de npx): cualquier
58
+ // comando que mencione corvusmem y uno de nuestros ficheros de hook.
59
+ const NUESTROS_HOOKS = new Set(Object.values(HOOKSET).flat().flatMap(g => g.files));
60
+ const esNuestro = cmd => typeof cmd === 'string' && /corvusmem/i.test(cmd) && [...NUESTROS_HOOKS].some(f => cmd.includes(f));
61
+ // Copia los .mjs del nucleo (hooks + dependencias del mismo directorio: autocontenido) al sitio durable. Devuelve n.
62
+ function copiarHooks(dir) {
63
+ if (DRY) { log(` [dry-run] would copy core hook files to ${dir}`); return 0; }
64
+ fs.mkdirSync(dir, { recursive: true });
65
+ let n = 0;
66
+ for (const f of fs.readdirSync(SRC)) if (f.endsWith('.mjs')) { fs.copyFileSync(path.join(SRC, f), path.join(dir, f)); n++; }
67
+ return n;
68
+ }
69
+
70
+ // Slash commands (e.g. /corvus-absorb) go to .claude/commands/ — per project, or the HOME with --global.
71
+ function instalarComandos(quitar) {
72
+ let files = [];
73
+ try { files = fs.readdirSync(CMDS_SRC).filter(f => f.endsWith('.md')); } catch { return; }
74
+ if (!files.length) return;
75
+ const destDir = path.join(GLOBAL ? HOME : PROYECTO, '.claude', 'commands');
76
+ if (quitar) {
77
+ if (!DRY) for (const f of files) { try { fs.rmSync(path.join(destDir, f), { force: true }); } catch {} }
78
+ log(` [commands] removed ${files.length} command(s) from ${destDir.replace(/\\/g, '/')}`);
79
+ return;
80
+ }
81
+ if (DRY) { log(` [dry-run] would copy ${files.length} command(s) to ${destDir}`); return; }
82
+ fs.mkdirSync(destDir, { recursive: true });
83
+ for (const f of files) fs.copyFileSync(path.join(CMDS_SRC, f), path.join(destDir, f));
84
+ log(` [commands] ${files.length} command(s) copied to ${destDir.replace(/\\/g, '/')}`);
85
+ }
86
+
87
+ // Para EMPAQUETAR como plugin (Claude/Codex): el comando apunta al propio plugin, no a una ruta de la maquina.
88
+ const cmdPlugin = file => `node "\${CLAUDE_PLUGIN_ROOT}/hooks/${file}"`;
89
+ function gruposPlugin(ev) {
90
+ return HOOKSET[ev].map(g => {
91
+ const grp = {};
92
+ if (g.matcher) grp.matcher = g.matcher;
93
+ grp.hooks = g.files.map(f => ({ type: 'command', command: cmdPlugin(f), timeout: ev === 'SessionEnd' ? 5 : 30 }));
94
+ return grp;
95
+ });
96
+ }
97
+
98
+ // Empaqueta Corvusmem como PLUGIN autocontenido (mismo formato que el plugin de Senzu que Codex ya consume):
99
+ // .claude-plugin/plugin.json + hooks/hooks.json (con ${CLAUDE_PLUGIN_ROOT}) + los .mjs del nucleo copiados a hooks/.
100
+ // El usuario lo publica en un marketplace de Codex, lo instala y APRUEBA los hooks en la app (quedan en
101
+ // ~/.codex/config.toml -> hooks.state). Vale igual como plugin de Claude.
102
+ function empaquetarPlugin(destino) {
103
+ const dir = path.resolve(destino);
104
+ let pkg = {}; try { pkg = JSON.parse(fs.readFileSync(path.join(AQUI, 'package.json'), 'utf8')); } catch {}
105
+ if (DRY) { log(` [dry-run] would package the plugin in ${dir}`); return; }
106
+ const hooksDir = path.join(dir, 'hooks');
107
+ fs.mkdirSync(hooksDir, { recursive: true });
108
+ fs.mkdirSync(path.join(dir, '.claude-plugin'), { recursive: true });
109
+ // 1) hooks.json en formato de plugin (CLAUDE_PLUGIN_ROOT), mismos eventos que el HOOKSET
110
+ const h = {}; for (const ev of Object.keys(HOOKSET)) h[ev] = gruposPlugin(ev);
111
+ fs.writeFileSync(path.join(hooksDir, 'hooks.json'), JSON.stringify({ hooks: h }, null, 2) + '\n');
112
+ // 2) los .mjs del nucleo (hooks + dependencias de mismo directorio: autocontenido, cero imports externos)
113
+ let n = 0;
114
+ for (const f of fs.readdirSync(SRC)) if (f.endsWith('.mjs')) { fs.copyFileSync(path.join(SRC, f), path.join(hooksDir, f)); n++; }
115
+ // 3) slash commands (/corvus-absorb) in the plugin's commands/ dir
116
+ let nc = 0;
117
+ try {
118
+ const cmds = fs.readdirSync(CMDS_SRC).filter(f => f.endsWith('.md'));
119
+ if (cmds.length) { fs.mkdirSync(path.join(dir, 'commands'), { recursive: true }); for (const f of cmds) { fs.copyFileSync(path.join(CMDS_SRC, f), path.join(dir, 'commands', f)); nc++; } }
120
+ } catch { /* no commands/ */ }
121
+ // 4) plugin.json
122
+ const plugin = { name: 'corvusmem', description: pkg.description || 'Memoria determinista, offline y sin dependencias para agentes de IA.', version: pkg.version || '0.0.0', author: { name: 'Peterson Sena' }, license: 'SEE LICENSE IN LICENSE' };
123
+ fs.writeFileSync(path.join(dir, '.claude-plugin', 'plugin.json'), JSON.stringify(plugin, null, 2) + '\n');
124
+ log(` [plugin] ${dir}: .claude-plugin/plugin.json + hooks/hooks.json + ${n} .mjs${nc ? ` + ${nc} command(s)` : ''}`);
125
+ log(' Publish it to a Codex marketplace (like Senzu\'s); install it and approve the hooks in the app.');
126
+ }
127
+
128
+ // Construye los grupos de hooks de un evento en el formato de settings.json de Claude.
129
+ function gruposDe(ev) {
130
+ return HOOKSET[ev].map(g => {
131
+ const grp = {};
132
+ if (g.matcher) grp.matcher = g.matcher;
133
+ grp.hooks = g.files.map(f => ({ type: 'command', command: cmdDe(f), timeout: ev === 'SessionEnd' ? 5 : 30 }));
134
+ return grp;
135
+ });
136
+ }
137
+
138
+ function leerJson(file) { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { if (e.code === 'ENOENT') return {}; throw e; } }
139
+
140
+ // Fusiona en settings.json: quita SOLO lo nuestro (por la ruta) y, si no es --uninstall, vuelve a ponerlo.
141
+ function fusionar(settings, { quitar }) {
142
+ const hooks = settings.hooks && typeof settings.hooks === 'object' ? settings.hooks : {};
143
+ for (const ev of Object.keys(HOOKSET)) {
144
+ const existentes = Array.isArray(hooks[ev]) ? hooks[ev] : [];
145
+ // de los grupos que había, conserva los hooks que NO son nuestros (así no pisamos los del usuario)
146
+ const ajenos = existentes
147
+ .map(g => ({ ...g, hooks: (Array.isArray(g.hooks) ? g.hooks : []).filter(h => !esNuestro(h && h.command)) }))
148
+ .filter(g => g.hooks.length);
149
+ const nuevos = quitar ? [] : gruposDe(ev);
150
+ const total = ajenos.concat(nuevos);
151
+ if (total.length) hooks[ev] = total; else delete hooks[ev];
152
+ }
153
+ if (Object.keys(hooks).length) settings.hooks = hooks; else delete settings.hooks;
154
+ return settings;
155
+ }
156
+
157
+ function escribir(file, obj) {
158
+ if (DRY) { log(` [dry-run] would write ${file}`); return; }
159
+ fs.mkdirSync(path.dirname(file), { recursive: true });
160
+ fs.writeFileSync(file, JSON.stringify(obj, null, 2) + '\n');
161
+ }
162
+
163
+ function asegurarDir(dir) {
164
+ if (DRY) { log(` [dry-run] would create ${dir}`); return; }
165
+ fs.mkdirSync(dir, { recursive: true });
166
+ }
167
+
168
+ function run() {
169
+ if (!fs.existsSync(path.join(SRC, 'facts.mjs'))) { log(`Core not found in ${SRC}. Run install.mjs from the Corvusmem repo.`); process.exit(2); }
170
+
171
+ // Modo empaquetar plugin (Claude/Codex): no toca settings.json; genera un plugin autocontenido en <dir>.
172
+ const destinoPlugin = opt('--plugin');
173
+ if (destinoPlugin && destinoPlugin !== true) {
174
+ log(`Corvusmem · package plugin (Claude/Codex)${DRY ? ' (dry-run)' : ''}`);
175
+ empaquetarPlugin(destinoPlugin);
176
+ log('Done.');
177
+ return;
178
+ }
179
+
180
+ const quitar = has('--uninstall');
181
+ log(`Corvusmem · ${quitar ? 'uninstall' : 'install'}${GLOBAL ? ' (global)' : ''}${DRY ? ' (dry-run)' : ''}`);
182
+
183
+ // 0) Copias DURABLES de los hooks (o quitarlas). La MEMORIA (.corvusmem/memoria, ~/.config/corvusmem) no se toca.
184
+ if (quitar) {
185
+ if (!DRY) { try { fs.rmSync(hooksDir, { recursive: true, force: true }); } catch {} }
186
+ log(` [hooks] removed ${hooksDir}`);
187
+ } else {
188
+ const n = copiarHooks(hooksDir);
189
+ log(` [hooks] ${n} core file(s) copied to ${hooksDir.replace(/\\/g, '/')}`);
190
+ }
191
+
192
+ // 1) Claude: hooks en settings.json (proyecto o HOME)
193
+ const settingsFile = GLOBAL ? path.join(HOME, '.claude', 'settings.json') : path.join(PROYECTO, '.claude', 'settings.json');
194
+ let settings;
195
+ try { settings = leerJson(settingsFile); }
196
+ catch { log(` [claude] WARNING: ${settingsFile} is not valid JSON; leaving it untouched (fix it and retry).`); process.exit(2); }
197
+ escribir(settingsFile, fusionar(settings, { quitar }));
198
+ log(` [claude] ${quitar ? 'Corvusmem hooks removed from' : 'hooks registered in'} ${settingsFile}`);
199
+
200
+ // 1b) Claude slash commands (/corvus-absorb)
201
+ instalarComandos(quitar);
202
+
203
+ // 2) Manifiesto portable de hooks (lo consume el plugin para Claude/Codex, F10-T4)
204
+ const manifest = path.join(PROYECTO, '.corvusmem', 'hooks.json');
205
+ if (quitar) { if (!DRY) { try { fs.rmSync(manifest, { force: true }); } catch {} } log(` [manifest] removed ${manifest}`); }
206
+ else { const h = {}; for (const ev of Object.keys(HOOKSET)) h[ev] = gruposDe(ev); escribir(manifest, { hooks: h }); log(` [manifest] ${manifest} (used by the Codex/Claude plugin)`); }
207
+
208
+ // 3) Carpetas de memoria (no se borran al desinstalar: son datos del usuario)
209
+ if (!quitar) {
210
+ asegurarDir(path.join(PROYECTO, '.corvusmem')); // memoria del proyecto
211
+ asegurarDir(path.join(HOME, '.config', 'corvusmem')); // memoria global del usuario
212
+ log(' [memory] .corvusmem/ (project) and ~/.config/corvusmem/ (global) ready');
213
+ }
214
+
215
+ log('Done.' + (quitar ? '' : ' Codex: per-event hooks go through the plugin; in Claude they are already active.'));
216
+ }
217
+
218
+ run();
package/package.json CHANGED
@@ -1,53 +1,54 @@
1
- {
2
- "name": "corvusmem",
3
- "version": "0.2.1",
4
- "description": "Deterministic, offline, zero-dependency memory for AI coding agents (Claude Code, Codex) and a standalone CLI.",
5
- "type": "module",
6
- "bin": {
7
- "corvusmem": "cli/corvusmem.mjs"
8
- },
9
- "files": [
10
- "src/",
11
- "cli/",
12
- "cortex/",
13
- "install.mjs",
14
- "docs.md",
15
- "COMMERCIAL.md",
16
- "CHANGELOG.md"
17
- ],
18
- "scripts": {
19
- "test": "node tests/test-boundary.mjs && node tests/test-facts.mjs && node tests/test-hard-recall.mjs && node tests/test-install.mjs && node tests/test-plugin.mjs && node tests/test-parity.mjs && node tests/test-cortex-visual.mjs",
20
- "test:core": "node tests/test-boundary.mjs && node tests/test-facts.mjs && node tests/test-hard-recall.mjs && node tests/test-install.mjs && node tests/test-plugin.mjs && node tests/test-parity.mjs",
21
- "bench:tokens": "node tools/eval-tokens.mjs",
22
- "preversion": "npm run test:core",
23
- "prepublishOnly": "npm run test:core"
24
- },
25
- "engines": {
26
- "node": ">=18"
27
- },
28
- "keywords": [
29
- "memory",
30
- "ai",
31
- "agent",
32
- "llm",
33
- "claude-code",
34
- "codex",
35
- "offline",
36
- "deterministic",
37
- "local-first",
38
- "no-embeddings"
39
- ],
40
- "author": "Peterson Sena",
41
- "license": "SEE LICENSE IN LICENSE",
42
- "homepage": "https://corvusmem.vercel.app",
43
- "repository": {
44
- "type": "git",
45
- "url": "git+https://github.com/petersonsenadevs/corvusmem.git"
46
- },
47
- "bugs": {
48
- "url": "https://github.com/petersonsenadevs/corvusmem/issues"
49
- },
50
- "devDependencies": {
51
- "gpt-tokenizer": "^4.1.0"
52
- }
53
- }
1
+ {
2
+ "name": "corvusmem",
3
+ "version": "0.3.0",
4
+ "description": "Deterministic, offline, zero-dependency memory for AI coding agents (Claude Code, Codex) and a standalone CLI.",
5
+ "type": "module",
6
+ "bin": {
7
+ "corvusmem": "cli/corvusmem.mjs"
8
+ },
9
+ "files": [
10
+ "src/",
11
+ "cli/",
12
+ "commands/",
13
+ "cortex/",
14
+ "install.mjs",
15
+ "docs.md",
16
+ "COMMERCIAL.md",
17
+ "CHANGELOG.md"
18
+ ],
19
+ "scripts": {
20
+ "test": "node tests/test-boundary.mjs && node tests/test-facts.mjs && node tests/test-hard-recall.mjs && node tests/test-install.mjs && node tests/test-import.mjs && node tests/test-plugin.mjs && node tests/test-parity.mjs && node tests/test-cortex-visual.mjs",
21
+ "test:core": "node tests/test-boundary.mjs && node tests/test-facts.mjs && node tests/test-hard-recall.mjs && node tests/test-install.mjs && node tests/test-import.mjs && node tests/test-plugin.mjs && node tests/test-parity.mjs",
22
+ "bench:tokens": "node tools/eval-tokens.mjs",
23
+ "preversion": "npm run test:core",
24
+ "prepublishOnly": "npm run test:core"
25
+ },
26
+ "engines": {
27
+ "node": ">=18"
28
+ },
29
+ "keywords": [
30
+ "memory",
31
+ "ai",
32
+ "agent",
33
+ "llm",
34
+ "claude-code",
35
+ "codex",
36
+ "offline",
37
+ "deterministic",
38
+ "local-first",
39
+ "no-embeddings"
40
+ ],
41
+ "author": "Peterson Sena",
42
+ "license": "SEE LICENSE IN LICENSE",
43
+ "homepage": "https://corvusmem.vercel.app",
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "git+https://github.com/petersonsenadevs/corvusmem.git"
47
+ },
48
+ "bugs": {
49
+ "url": "https://github.com/petersonsenadevs/corvusmem/issues"
50
+ },
51
+ "devDependencies": {
52
+ "gpt-tokenizer": "^4.1.0"
53
+ }
54
+ }
package/src/facts.mjs CHANGED
@@ -17,7 +17,7 @@ import os from 'node:os';
17
17
  import { spawnSync } from 'node:child_process';
18
18
  import { fileURLToPath } from 'node:url';
19
19
  import { ruta, rutaMemoriaUsuario, rutaEstado, localeUI } from './lib.mjs';
20
- export { rutaNativa, localeUI } from './lib.mjs'; // memory.mjs: --path (C:\, C:/, /c/ de Git Bash → el mismo almacén) e idioma de UI
20
+ export { rutaNativa, localeUI, carpetaBase } from './lib.mjs'; // memory.mjs: --path (C:\, C:/, /c/ de Git Bash → el mismo almacén), idioma de UI y carpeta base (senzu/ vs .corvusmem/)
21
21
 
22
22
  export const FAMILIAS_VARIOS = /^(objetivo|pendiente|nota|hecho|enlace|aprendizaje)(\.|$)/;
23
23
  // Multiusuario (F14): familias PERSONALES (de la persona, no del proyecto). En memoria de proyecto COMPARTIDA, su
package/src/import.mjs ADDED
@@ -0,0 +1,86 @@
1
+ // Corvus memory import — DISCOVERY ONLY (deterministic, offline, zero-dependency).
2
+ // Finds the memory documents already in a project so nothing a teammate wrote is lost, in two tiers:
3
+ // tier 'agent' — known agent-memory files (CLAUDE.md, AGENTS.md, Cursor/Copilot/Gemini rules, a Senzu
4
+ // MEMORIA.md): high confidence, absorb them.
5
+ // tier 'doc' — any OTHER markdown that may hold memory (e.g. docs/architecture.md, notes/decisions.md),
6
+ // minus obvious boilerplate (README, CHANGELOG, LICENSE…): the agent judges / asks the user.
7
+ //
8
+ // It does NOT decide what counts as "real" memory and it NEVER writes: that judgment belongs to the agent,
9
+ // via the /corvus-absorb command, which reads these files and calls `corvusmem --save` for what matters.
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { rutaNativa } from './lib.mjs';
13
+
14
+ // Well-known agent-memory files, by relative path. `kind` = which tool wrote it.
15
+ const FIJOS = [
16
+ ['CLAUDE.md', 'claude'],
17
+ ['CLAUDE.local.md', 'claude'],
18
+ ['.claude/CLAUDE.md', 'claude'],
19
+ ['AGENTS.md', 'agents'],
20
+ ['GEMINI.md', 'gemini'],
21
+ ['.github/copilot-instructions.md', 'copilot'],
22
+ ['.cursorrules', 'cursor'],
23
+ ['.windsurfrules', 'windsurf'],
24
+ ['senzu/devlog/MEMORIA.md', 'senzu'],
25
+ ];
26
+ // Agent-memory file names worth finding nested in subfolders (e.g. packages/*/CLAUDE.md).
27
+ const ANIDADOS = new Map([['CLAUDE.md', 'claude'], ['CLAUDE.local.md', 'claude'], ['AGENTS.md', 'agents'], ['GEMINI.md', 'gemini']]);
28
+ // Dirs we never walk into (heavy, generated, template-only, or Corvus/Senzu's own stores).
29
+ const NO_ENTRAR = new Set(['node_modules', '.git', '.corvusmem', 'senzu', '.claude', '.agents', '.github',
30
+ '.vscode', '.idea', 'vendor', 'dist', 'build', 'out', '.next', '.astro', '.nuxt', '.svelte-kit',
31
+ '.venv', 'venv', '__pycache__', 'coverage', '.cache', 'tmp', 'target']);
32
+ // Markdown that is almost never project memory -> kept out of the 'doc' tier.
33
+ const BOILERPLATE = new Set(['readme.md', 'changelog.md', 'change-log.md', 'changes.md', 'history.md',
34
+ 'license.md', 'licence.md', 'copying.md', 'contributing.md', 'code_of_conduct.md', 'security.md',
35
+ 'authors.md', 'maintainers.md', 'support.md', 'funding.md', 'notice.md', 'pull_request_template.md',
36
+ 'issue_template.md']);
37
+ const MAX_PROF = 5; // bounded walk: deep enough for packages/*/app/docs, cheap enough to stay instant
38
+ const MAX_DOCS = 80; // cap the generic-markdown tier so a huge repo stays readable
39
+
40
+ function meta(abs) {
41
+ const txt = fs.readFileSync(abs, 'utf8');
42
+ return { bytes: Buffer.byteLength(txt, 'utf8'), lines: txt ? txt.replace(/\r/g, '').replace(/\n$/, '').split('\n').length : 0 };
43
+ }
44
+ function esMd(name) { const l = name.toLowerCase(); return l.endsWith('.md') || l.endsWith('.mdc') || l.endsWith('.markdown'); }
45
+ function reg(root, abs, tier, kind) { return { tier, kind, rel: path.relative(root, abs).replace(/\\/g, '/'), ...meta(abs) }; }
46
+ function esFichero(abs) { try { return fs.statSync(abs).isFile(); } catch { return false; } }
47
+
48
+ function walk(root, dir, prof, vistos, agent, docs) {
49
+ if (prof > MAX_PROF) return;
50
+ let ents;
51
+ try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
52
+ for (const e of ents) {
53
+ if (e.isDirectory()) {
54
+ if (NO_ENTRAR.has(e.name) || e.name === '.cursor') continue;
55
+ walk(root, path.join(dir, e.name), prof + 1, vistos, agent, docs);
56
+ continue;
57
+ }
58
+ if (!e.isFile()) continue;
59
+ const abs = path.join(dir, e.name);
60
+ if (vistos.has(abs)) continue;
61
+ if (ANIDADOS.has(e.name)) { vistos.add(abs); agent.push(reg(root, abs, 'agent', ANIDADOS.get(e.name))); continue; }
62
+ if (esMd(e.name) && !BOILERPLATE.has(e.name.toLowerCase())) { vistos.add(abs); docs.push(reg(root, abs, 'doc', 'markdown')); }
63
+ }
64
+ }
65
+
66
+ // Returns { root, total, agent, docs, truncated, files: [{ tier, kind, rel, bytes, lines }] } in stable order.
67
+ export function escanearMemoria(root0) {
68
+ const root = rutaNativa(root0);
69
+ const agent = [], docs = [];
70
+ const vistos = new Set();
71
+ // 1. fixed well-known agent-memory locations
72
+ for (const [rel, kind] of FIJOS) { const abs = path.join(root, rel); if (esFichero(abs) && !vistos.has(abs)) { vistos.add(abs); agent.push(reg(root, abs, 'agent', kind)); } }
73
+ // 2. Cursor project rules (.cursor/rules/*.mdc)
74
+ try {
75
+ const rd = path.join(root, '.cursor', 'rules');
76
+ for (const f of fs.readdirSync(rd)) if (esMd(f)) { const abs = path.join(rd, f); if (!vistos.has(abs)) { vistos.add(abs); agent.push(reg(root, abs, 'agent', 'cursor')); } }
77
+ } catch { /* no .cursor/rules */ }
78
+ // 3. bounded walk: nested agent files + any other markdown that may hold memory
79
+ walk(root, root, 0, vistos, agent, docs);
80
+ const porRel = (a, b) => a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0;
81
+ agent.sort(porRel); docs.sort(porRel);
82
+ const truncated = docs.length > MAX_DOCS;
83
+ const docsOut = truncated ? docs.slice(0, MAX_DOCS) : docs;
84
+ const files = [...agent, ...docsOut];
85
+ return { root, total: files.length, agent: agent.length, docs: docsOut.length, truncated, files };
86
+ }
package/src/lib.mjs CHANGED
@@ -88,13 +88,22 @@ function ejecutarPorArchivo(entradas) {
88
88
  // conventions.md/json, ui-verify y el marcador senzu.json. Proyectos antiguos sin migrar (devlog/ y
89
89
  // .dev-standards.json en la raíz) siguen funcionando: cada ruta se busca primero donde corresponde al
90
90
  // proyecto y después en la otra ubicación. /instalar migra con git mv.
91
- export const CARPETA = 'senzu';
91
+ export const CARPETA = 'senzu'; // Senzu's folder name (coupled mode)
92
+ export const CARPETA_CORVUS = '.corvusmem'; // Corvus's own folder (standalone, no Senzu)
92
93
  export function esLegado(root) {
93
94
  return !fs.existsSync(path.join(root, CARPETA)) && (fs.existsSync(path.join(root, '.dev-standards.json')) || fs.existsSync(path.join(root, 'devlog')));
94
95
  }
96
+ // Base folder for this project's memory & config. Couple to Senzu when the project uses it
97
+ // (senzu/ dir or legacy marker); otherwise Corvus lives standalone in its own .corvusmem/.
98
+ export function carpetaBase(root) {
99
+ if (fs.existsSync(path.join(root, CARPETA))) return CARPETA; // Senzu present -> couple (expected)
100
+ if (fs.existsSync(path.join(root, CARPETA_CORVUS))) return CARPETA_CORVUS; // Corvus dir already here -> keep it
101
+ if (esLegado(root)) return CARPETA; // legacy Senzu project (root devlog / .dev-standards.json)
102
+ return CARPETA_CORVUS; // brand-new, no Senzu -> Corvus owns its dir
103
+ }
95
104
  const VIEJA = { 'ui-verify': '.ui-verify', 'senzu.json': '.dev-standards.json', auditoria: 'docs/auditoria', entrega: 'docs/entrega', 'mapa.md': 'docs/MAPA.md' };
96
105
  export function ruta(root, nombre) { // 'devlog' | 'plan' | 'design-system' | 'conventions.md' | 'conventions.json' | 'ui-verify' | 'senzu.json'
97
- const nueva = path.join(root, CARPETA, nombre);
106
+ const nueva = path.join(root, carpetaBase(root), nombre);
98
107
  const vieja = path.join(root, VIEJA[nombre] || nombre);
99
108
  const [primera, segunda] = esLegado(root) ? [vieja, nueva] : [nueva, vieja];
100
109
  if (fs.existsSync(primera)) return primera;
@@ -643,7 +652,7 @@ export function pad3(n) { return String(n).padStart(3, '0'); }
643
652
 
644
653
  // ¿Archivos de código en la raíz o un nivel por debajo? (sin node_modules, .git, senzu, .claude, .agents…)
645
654
  const EXT_CODIGO = /\.(php|ts|tsx|js|jsx|mjs|cjs|py|go|rs|rb|java|kt|cs|vue|svelte|astro|ps1|sh)$/i;
646
- const NO_MIRAR = new Set(['node_modules', '.git', 'senzu', '.claude', '.agents', 'vendor', 'dist', 'build', '.venv', 'venv', '__pycache__']);
655
+ const NO_MIRAR = new Set(['node_modules', '.git', 'senzu', '.corvusmem', '.claude', '.agents', 'vendor', 'dist', 'build', '.venv', 'venv', '__pycache__']);
647
656
  function hayCodigoSuelto(root) {
648
657
  const mira = (dir, nivel) => {
649
658
  let ents = []; try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return false; }