corvusmem 0.3.3 → 0.5.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
@@ -5,6 +5,50 @@ Format based on [Keep a Changelog](https://keepachangelog.com/); versions follow
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.5.0] — 2026-11-08
9
+ ### Added
10
+ - **Install Corvus as a native plugin — Claude Code and Codex.** The repo is now a Claude Code **marketplace**
11
+ (`.claude-plugin/marketplace.json` + a committed `plugins/corvusmem/`), so you install it the way you install any
12
+ plugin instead of wiring hooks into a project:
13
+ ```
14
+ /plugin marketplace add petersonsenadevs/corvusmem
15
+ /plugin install corvusmem@corvusmem
16
+ ```
17
+ The hooks fire natively (the host's own plugin mechanism), everywhere, with nothing to maintain. Codex consumes the
18
+ **same** plugin (`hooks/hooks.json` uses `${CLAUDE_PLUGIN_ROOT}`; edits arrive as `apply_patch`). `npx corvusmem install`
19
+ stays as the path for agents without plugin support, or a quick trial. Generate/refresh both with
20
+ `node install.mjs --marketplace` (the release flow runs it so the plugin always carries the current version and hooks).
21
+ - **Fast save/recall — no more `npx` cold start.** The memory CLI now ships *next to* the hooks — in the plugin
22
+ (`$CLAUDE_PLUGIN_ROOT/cli/`), in a per-project install (`.corvusmem/cli/`) and in a global one
23
+ (`~/.config/corvusmem/cli/`). The hooks pick the fastest available invocation (`node ".../cli/corvusmem.mjs"`) and
24
+ fall back to `npx corvusmem` only for an agent that has none of it installed. So once Corvus is installed, the agent
25
+ saving a fact no longer pays npm's resolve-and-spawn cost on every call.
26
+
27
+ ## [0.4.0] — 2026-11-08
28
+ ### Changed
29
+ - **Corvus is the memory owner — its hooks are the ones that fire, Senzu defers to it.** When Corvus is installed
30
+ (per-project or global), it OWNS the memory: its hooks inject and capture as normal, and Senzu steps back from memory
31
+ (its recall/capture/facts hooks yield to Corvus, and its session-start drops the facts block) while keeping everything
32
+ else — method, plan, devlog, guards. Before, both layers shared a first-wins handshake and Senzu (listed first) won,
33
+ so Corvus looked like it "did nothing". Now the split is deterministic and Corvus's memory is what you see.
34
+ *(Requires the matching Senzu release that defers to Corvus; update the Senzu plugin too.)*
35
+ - **One stable store, and it adopts what Senzu had.** Project facts always live in Corvus's own
36
+ `.corvusmem/memory/facts.jsonl` (English, visible) — never in `senzu/memoria/hechos.jsonl`, and the location never
37
+ flips when Senzu is added or removed. When Corvus lands on a project that already used Senzu, it **adopts** the facts
38
+ from `senzu/memoria/hechos.jsonl` into its own store once (a copy, so nothing is lost and it is reversible), and never
39
+ clobbers facts it already has.
40
+ - **The installer says so.** Installing into a project that already uses Senzu now prints that Corvus owns the memory
41
+ there (it adopts Senzu's facts and Senzu defers), and to update the Senzu plugin so it steps back.
42
+
43
+ ## [0.3.4] — 2026-11-07
44
+ ### Changed
45
+ - **`/corvus-absorb` is now exhaustive by design.** The command states its real goal up front — *after it runs, the
46
+ agent should be able to work without re-reading the markdown docs* — and instructs the agent to open and read
47
+ **every** doc-tier file (not a sample), expect **many facts** (dozens, often 100+ for a rich repo; one or more per
48
+ feature/node spec), and **check coverage** at the end (every substantial doc must contribute at least one fact). It
49
+ also corrects the misconception that fewer facts is better: the per-message cap is on *injection*, not *storage*, so
50
+ more good atomic facts make memory richer, never noisier. Still skips noise (how-tos, API dumps, boilerplate).
51
+
8
52
  ## [0.3.3] — 2026-11-07
9
53
  ### Fixed
10
54
  - **A stray `senzu/` folder no longer hijacks Corvus's standalone memory.** Corvus coupled to Senzu whenever a
package/README.md CHANGED
@@ -1,94 +1,110 @@
1
- <p align="center">
2
- <img src="https://raw.githubusercontent.com/petersonsenadevs/corvusmem/main/assets/crow.png" alt="Corvusmem — the crow that remembers" width="200" />
3
- </p>
4
-
5
- # Corvusmem
6
-
7
- <p align="center">
8
- <a href="https://www.npmjs.com/package/corvusmem"><img src="https://img.shields.io/npm/v/corvusmem?color=e07a33" alt="npm version" /></a>
9
- <img src="https://img.shields.io/node/v/corvusmem" alt="node" />
10
- <img src="https://img.shields.io/badge/dependencies-0-brightgreen" alt="zero dependencies" />
11
- <img src="https://img.shields.io/badge/offline-yes-brightgreen" alt="offline" />
12
- <img src="https://img.shields.io/badge/license-PolyForm%20NC-blue" alt="license" />
13
- </p>
14
-
15
- **Deterministic, offline, zero-dependency memory for AI coding agents.** Corvusmem stores the stable facts your
16
- agent learns, replaces and dates them, and recalls them the same way every time — in any language, with no network
17
- and no servers. It plugs into where you already work: Claude Code / Codex (hooks) and a standalone CLI.
18
-
19
- 🌐 [Website](https://corvusmem.vercel.app) · 📖 [Docs](https://corvusmem.vercel.app/docs) · 📊 [Benchmarks](https://corvusmem.vercel.app/benchmarks) · 📦 [npm](https://www.npmjs.com/package/corvusmem)
20
-
21
- > **Narrative docs (what it is, the message, the Cortex, FAQ):** [`docs.md`](./docs.md). This README is the quick
22
- > reference for structure and commands.
23
-
24
- ## Why Corvusmem
25
- - **Deterministic** — same input, same result. No embeddings, no vector database, no model to run recall.
26
- - **Offline & private** — the memory is a plain file you own. No server, no cloud, no API key, no telemetry.
27
- - **Zero-dependency** — pure Node, identical on Windows, macOS and Linux.
28
- - **Any language** — keys and values in any language; recall is language-agnostic.
29
- - **Per-author** — on a shared project, teammates' personal facts never overwrite each other.
30
- - **Bounded footprint** — a hard cap keeps the context cost flat (O(1), not O(n)) — see the [benchmarks](https://corvusmem.vercel.app/benchmarks).
31
- - **See it** — the Cortex draws your whole memory as a local HTML brain.
32
-
33
- ## How it works
34
- Your agent forgets everything between sessions. Corvusmem is a memory it keeps: facts live in a lightweight local
35
- graph, retrieved by name, date and relevance with two-hop activation — no embeddings, no vector database, no API key.
36
- Same input, same result. The whole memory is a file you own.
37
-
38
- ## Structure
39
- - `src/` — the core: the facts engine (`facts.mjs`), shared base (`lib`, `messages`, `session-end`), host detection
40
- (`host.mjs`) and the brain hooks (`live-recall`, `session-start`, `session-state`, `live-memory`,
41
- `file-memory`, `facts-guard`). Same-directory imports only: self-contained, zero external dependencies.
42
- - `cli/` — `memory.mjs`: the command line (`--save` / `--search` / `--recall` / `--context` / `--cortex`).
43
- - `cortex/` — `cortex.mjs` + `cortex-text.mjs`: your memory as a local HTML page (the "Cortex"), no network.
44
- - `tests/` — deterministic, LLM-free suites: `test-boundary` (clean core), `test-facts` (engine), `test-hard-recall`.
45
-
46
- ## Install
47
- ```
48
- npx corvusmem install --claude # register the hooks in the current project's .claude/settings.json
49
- npx corvusmem install --global # for every project (~/.claude/settings.json)
50
- npx corvusmem uninstall # remove Corvusmem's hooks (leaves everything else intact)
51
- npx corvusmem install --dry-run # show what it would do, without writing
52
- ```
53
- Merge-safe (it never overwrites your hooks or permissions) and idempotent. It creates `.corvusmem/` (project
54
- memory) and `~/.config/corvusmem/` (global memory), and writes `.corvusmem/hooks.json` (a portable manifest).
55
-
56
- **Per-project vs global only decides *where the hooks turn on*** — for one repo (`--claude`, config in that repo) or
57
- for every project (`--global`, in your home). It does **not** change where memory lives: project facts always land in
58
- that repo's `.corvusmem/`, your personal facts in `~/.config/corvusmem/`. You never need a per-project install just to
59
- keep memory in the repo — that happens either way.
60
-
61
- **Sharing with a team**: commit `.corvusmem/` (the shared project memory) and, for a per-project install,
62
- `.claude/settings.json` so teammates get the hooks the moment they clone. Never commit `~/.config/corvusmem/` — that is
63
- your private memory.
64
-
65
- **Codex**: the hooks run through the plugin path (a marketplace in `~/.codex/config.toml`), not the project
66
- `settings.json`. Publish it to a Codex marketplace, install it and approve the hooks in the app. On Claude Code they
67
- are active right away.
68
-
69
- ## Usage
70
- Once installed, the agent captures and recalls memory on its own — you don't do a thing. To look at it or steer it:
71
- ```
72
- npx corvusmem --cortex # your whole memory as a local HTML brain (offline)
73
- npx corvusmem --recall "stripe webhook" # ask what it already knows, from the terminal
74
- npx corvusmem --list # list every fact
75
- npx corvusmem --save --dimension project.stack --value "Astro + Tailwind" --scope project
76
- npx corvusmem --forget <id> # drop one fact
77
- ```
78
- The Cortex also takes `--client` (a shareable view with nothing private), `--output <dir>` and `--lang en|es|…`.
79
- Flags are English with Spanish aliases (`--save`/`--guardar`, `--recall`/`--recordar`); keys and values work in any
80
- language — the memory is language-agnostic.
81
-
82
- ## Test
83
- ```
84
- npm test
85
- ```
86
- (or `node tests/test-boundary.mjs && node tests/test-facts.mjs && node tests/test-hard-recall.mjs`)
87
-
88
- ## License
89
- Dual-licensed (© 2026 Peterson Sena):
90
- - **Noncommercial use** (personal, study, hobby, nonprofit, education/public sector): free under **PolyForm
91
- Noncommercial 1.0.0** (`LICENSE`), keeping the credit (`Required Notice`).
92
- - **Commercial use**: requires a separate **paid license** — see `COMMERCIAL.md` (petersonsena24@gmail.com).
93
-
94
- This is not legal advice; for final commercial terms, consult a professional.
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/petersonsenadevs/corvusmem/main/assets/crow.png" alt="Corvusmem — the crow that remembers" width="200" />
3
+ </p>
4
+
5
+ # Corvusmem
6
+
7
+ <p align="center">
8
+ <a href="https://www.npmjs.com/package/corvusmem"><img src="https://img.shields.io/npm/v/corvusmem?color=e07a33" alt="npm version" /></a>
9
+ <img src="https://img.shields.io/node/v/corvusmem" alt="node" />
10
+ <img src="https://img.shields.io/badge/dependencies-0-brightgreen" alt="zero dependencies" />
11
+ <img src="https://img.shields.io/badge/offline-yes-brightgreen" alt="offline" />
12
+ <img src="https://img.shields.io/badge/license-PolyForm%20NC-blue" alt="license" />
13
+ </p>
14
+
15
+ **Deterministic, offline, zero-dependency memory for AI coding agents.** Corvusmem stores the stable facts your
16
+ agent learns, replaces and dates them, and recalls them the same way every time — in any language, with no network
17
+ and no servers. It plugs into where you already work: Claude Code / Codex (hooks) and a standalone CLI.
18
+
19
+ 🌐 [Website](https://corvusmem.vercel.app) · 📖 [Docs](https://corvusmem.vercel.app/docs) · 📊 [Benchmarks](https://corvusmem.vercel.app/benchmarks) · 📦 [npm](https://www.npmjs.com/package/corvusmem)
20
+
21
+ > **Narrative docs (what it is, the message, the Cortex, FAQ):** [`docs.md`](./docs.md). This README is the quick
22
+ > reference for structure and commands.
23
+
24
+ ## Why Corvusmem
25
+ - **Deterministic** — same input, same result. No embeddings, no vector database, no model to run recall.
26
+ - **Offline & private** — the memory is a plain file you own. No server, no cloud, no API key, no telemetry.
27
+ - **Zero-dependency** — pure Node, identical on Windows, macOS and Linux.
28
+ - **Any language** — keys and values in any language; recall is language-agnostic.
29
+ - **Per-author** — on a shared project, teammates' personal facts never overwrite each other.
30
+ - **Bounded footprint** — a hard cap keeps the context cost flat (O(1), not O(n)) — see the [benchmarks](https://corvusmem.vercel.app/benchmarks).
31
+ - **See it** — the Cortex draws your whole memory as a local HTML brain.
32
+
33
+ ## How it works
34
+ Your agent forgets everything between sessions. Corvusmem is a memory it keeps: facts live in a lightweight local
35
+ graph, retrieved by name, date and relevance with two-hop activation — no embeddings, no vector database, no API key.
36
+ Same input, same result. The whole memory is a file you own.
37
+
38
+ ## Structure
39
+ - `src/` — the core: the facts engine (`facts.mjs`), shared base (`lib`, `messages`, `session-end`), host detection
40
+ (`host.mjs`) and the brain hooks (`live-recall`, `session-start`, `session-state`, `live-memory`,
41
+ `file-memory`, `facts-guard`). Same-directory imports only: self-contained, zero external dependencies.
42
+ - `cli/` — `memory.mjs`: the command line (`--save` / `--search` / `--recall` / `--context` / `--cortex`).
43
+ - `cortex/` — `cortex.mjs` + `cortex-text.mjs`: your memory as a local HTML page (the "Cortex"), no network.
44
+ - `tests/` — deterministic, LLM-free suites: `test-boundary` (clean core), `test-facts` (engine), `test-hard-recall`.
45
+
46
+ ## Install
47
+
48
+ Two ways. **Install it as a plugin** if your agent supports plugins (Claude Code, Codex) — it is native, there is
49
+ nothing to wire into a project, and the memory CLI runs locally (no `npx` cold start). **Use the `npx` install** for
50
+ any agent that does not do plugins, or for a quick trial.
51
+
52
+ ### As a plugin — Claude Code (recommended)
53
+ ```
54
+ /plugin marketplace add petersonsenadevs/corvusmem
55
+ /plugin install corvusmem@corvusmem
56
+ ```
57
+ The hooks fire natively (the same mechanism Claude uses for any plugin), everywhere, and saving/recalling runs as
58
+ `node "$CLAUDE_PLUGIN_ROOT/cli/corvusmem.mjs"` — no `npx`. Update later with `/plugin update corvusmem@corvusmem`.
59
+
60
+ ### As a plugin — Codex
61
+ Add the same marketplace in the Codex app and approve the hooks (they live in `~/.codex/config.toml`). Codex consumes
62
+ the **same** plugin — `hooks/hooks.json` uses `${CLAUDE_PLUGIN_ROOT}`, and edits arrive as `apply_patch`, which the
63
+ hooks already understand.
64
+
65
+ ### As an npx install (any agent, or a quick trial)
66
+ ```
67
+ npx corvusmem install # register the hooks in the current project's .claude/settings.json
68
+ npx corvusmem install --global # for every project (~/.claude/settings.json)
69
+ npx corvusmem uninstall # remove Corvusmem's hooks (leaves memory intact)
70
+ npx corvusmem install --dry-run # show what it would do, without writing
71
+ ```
72
+ Merge-safe (it never overwrites your hooks or permissions) and idempotent. It copies the hooks **and** the memory CLI
73
+ to a durable spot (`.corvusmem/hooks/` + `.corvusmem/cli/`, or `~/.config/corvusmem/` for `--global`), so the hooks and
74
+ the save/recall commands run via `node` — not `npx` — from then on. It also writes `.corvusmem/hooks.json` (a portable
75
+ manifest). The bare `npx corvusmem --save/--recall` still works for an agent with none of this set up (just slower).
76
+
77
+ **Per-project vs global only decides *where the hooks turn on*** — for one repo (config in that repo) or for every
78
+ project (`--global`, in your home). It does **not** change where memory lives: project facts always land in that repo's
79
+ `.corvusmem/`, your personal facts in `~/.config/corvusmem/`.
80
+
81
+ **Sharing with a team**: commit `.corvusmem/` (the shared project memory) and, for a per-project install,
82
+ `.claude/settings.json` so teammates get the hooks the moment they clone. Never commit `~/.config/corvusmem/` — that is
83
+ your private memory.
84
+
85
+ ## Usage
86
+ Once installed, the agent captures and recalls memory on its own — you don't do a thing. To look at it or steer it:
87
+ ```
88
+ npx corvusmem --cortex # your whole memory as a local HTML brain (offline)
89
+ npx corvusmem --recall "stripe webhook" # ask what it already knows, from the terminal
90
+ npx corvusmem --list # list every fact
91
+ npx corvusmem --save --dimension project.stack --value "Astro + Tailwind" --scope project
92
+ npx corvusmem --forget <id> # drop one fact
93
+ ```
94
+ The Cortex also takes `--client` (a shareable view with nothing private), `--output <dir>` and `--lang en|es|…`.
95
+ Flags are English with Spanish aliases (`--save`/`--guardar`, `--recall`/`--recordar`); keys and values work in any
96
+ language — the memory is language-agnostic.
97
+
98
+ ## Test
99
+ ```
100
+ npm test
101
+ ```
102
+ (or `node tests/test-boundary.mjs && node tests/test-facts.mjs && node tests/test-hard-recall.mjs`)
103
+
104
+ ## License
105
+ Dual-licensed (© 2026 Peterson Sena):
106
+ - **Noncommercial use** (personal, study, hobby, nonprofit, education/public sector): free under **PolyForm
107
+ Noncommercial 1.0.0** (`LICENSE`), keeping the credit (`Required Notice`).
108
+ - **Commercial use**: requires a separate **paid license** — see `COMMERCIAL.md` (petersonsena24@gmail.com).
109
+
110
+ This is not legal advice; for final commercial terms, consult a professional.
@@ -58,7 +58,7 @@ if (perdidas.length) avisos.push(`rutas que ya no existen en el proyecto: ${perd
58
58
  // Decisiones que citan un valor que un hecho ya sustituyó (motor de hechos, hooks/facts.mjs). Sin el motor, se omite.
59
59
  {
60
60
  const AQUI = path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1'));
61
- const motor = [path.join(AQUI, '..', 'src', 'facts.mjs'), path.join(AQUI, '..', '..', '..', 'hooks', 'facts.mjs'), path.join(root, '.claude', 'hooks', 'facts.mjs')].find(f => fs.existsSync(f));
61
+ const motor = [path.join(AQUI, '..', 'src', 'facts.mjs'), path.join(AQUI, '..', 'hooks', 'facts.mjs'), path.join(AQUI, '..', '..', '..', 'hooks', 'facts.mjs'), path.join(root, '.claude', 'hooks', 'facts.mjs')].find(f => fs.existsSync(f));
62
62
  if (motor) {
63
63
  try {
64
64
  const { decisionesObsoletas } = await import(new URL('file:///' + motor.replace(/\\/g, '/').replace(/^\//, '')).href);
package/cli/memory.mjs CHANGED
@@ -42,7 +42,7 @@ const out = s => process.stdout.write(s + '\n');
42
42
 
43
43
  async function motor() { // facts.mjs de los hooks: junto a la skill (plugin o .claude), o en el paquete de Senzu
44
44
  const marcador = (() => { try { return JSON.parse(fs.readFileSync(path.join(root, 'senzu', 'senzu.json'), 'utf8')); } catch { return {}; } })();
45
- const c = [path.join(AQUI, '..', 'src', 'facts.mjs'), path.join(AQUI, '..', '..', '..', 'hooks', 'facts.mjs'), path.join(root, '.claude', 'hooks', 'facts.mjs'),
45
+ const c = [path.join(AQUI, '..', 'src', 'facts.mjs'), path.join(AQUI, '..', 'hooks', 'facts.mjs'), path.join(AQUI, '..', '..', '..', 'hooks', 'facts.mjs'), path.join(root, '.claude', 'hooks', 'facts.mjs'),
46
46
  marcador.standardsRoot && path.join(marcador.standardsRoot, 'core', 'hooks', 'facts.mjs'), process.env.SENZU_HOME && path.join(process.env.SENZU_HOME, 'core', 'hooks', 'facts.mjs')].filter(Boolean);
47
47
  for (const f of c) if (fs.existsSync(f)) return import(pathToFileURL(f).href);
48
48
  out('No encuentro el motor de hechos (hooks/facts.mjs). ¿Está instalado? Ejecuta: npx corvusmem install');
@@ -1,8 +1,8 @@
1
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.
2
+ description: Absorb the project's existing knowledge — agent files AND the whole docs tree (architecture, decisions, feature/node specs, devlog) — into Corvus, thoroughly, so the team's memory lives in Corvus instead of only in scattered markdown.
3
3
  ---
4
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.
5
+ You are absorbing this project's **existing** knowledge into Corvus. The goal is concrete: **after this runs, the agent should be able to work on the project without re-reading the markdown docs**, because everything in them that matters is now in memory. If you only skim `CLAUDE.md` and save a handful of facts, you have FAILED — the team will keep opening their `.md` files and Corvus adds nothing. Be **exhaustive about what matters**, selective only about noise.
6
6
 
7
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
8
 
@@ -20,21 +20,21 @@ It returns the memory documents already in the repo in two tiers (`{ agent, docs
20
20
 
21
21
  If the list is empty, say so and stop. If `truncated` is true, mention that more markdown exists than was shown.
22
22
 
23
- ## 2. Read and judge (this is YOUR job, not the tool's)
24
- Read **every `agent`-tier file** in full.
23
+ ## 2. Read EVERYTHING, then distil (this is YOUR job, not the tool's)
24
+ Read **every `agent`-tier file** in full, and **open and read every `doc`-tier file too — not a sample**. Each file in the doc tier (architecture notes, ADRs, a devlog, and every feature / node / design spec) is listed because it likely holds durable knowledge. **Judge by the content inside, never the filename.** A large `docs/` tree is the whole point — read all of it; skip a file only after reading enough to see it is pure noise. Only **ask the user** when there are so many files that reading them all is genuinely impractical; otherwise read, don't ask.
25
25
 
26
- For the **`doc`-tier**, **actually open and read** the files that usually carry durable memory — anything under `architecture/`, `decisions/`, `adr/`, `devlog/` or `notes/`, and design or feature specs (`features/…`, `*-design.md`, `*-spec.md`, `roadmap*`). **Judge by the content inside, not the filename**: do not skip a file just because it is not called `decisions.md`, and a large `docs/` tree is normal, not a reason to stop. **Prefer reading over skipping, and reading over asking.** Only **ask the user** when a file's relevance is genuinely ambiguous, or when there are so many candidates that reading them all is impractical — then list them and ask which to include. Asking is the exception.
26
+ **Expect many facts — this is the part people get wrong.** A substantial doc usually yields *several* facts: its purpose, each decision and its reason, each contract/interface, each gotcha or "what didn't work". A project with N feature/node specs should produce **well more than N facts** — dozens, often 100+ for a rich repo. **Thirty facts out of thirty-plus docs means you under-read: go back and read the specs you skipped.** The point of Corvus is that the agent stops needing the `.md` files — that only works if what matters is actually in memory.
27
27
 
28
- From everything you read, keep **only durable memory** — what should still be true next week:
28
+ Keep every piece of **durable memory** — what should still be true next week:
29
29
 
30
30
  - decisions, with the reason behind them (one fact per distinct decision)
31
31
  - rules and conventions the team must follow
32
- - user / team preferences
33
- - project facts (stack, architecture, domains, external services, environments)
32
+ - project facts (stack, architecture, components, domains, external services, environments)
33
+ - **per-feature / per-node contracts and behaviour** (what each one does, its inputs/outputs, its rules) — one or more facts per spec
34
34
  - constraints, known gotchas, "what didn't work"
35
- - open goals or pending tasks
35
+ - user / team preferences, open goals, pending tasks
36
36
 
37
- Be **thorough**: a rich project may yield dozens of facts across its architecture, feature and devlog docs — capture each distinct decision, rule and gotcha, not just the ones in `CLAUDE.md`. But do **not** mirror the docs: skip install/run steps, step-by-step how-tos, API/parameter dumps, tool tutorials, generic boilerplate, anything obvious from the code, anything transient, and anything already covered by a fact you saved.
37
+ Leave out only the **noise**: install/run steps, step-by-step how-tos, API/parameter dumps you would re-read from the doc anyway, tool tutorials, generic boilerplate, anything obvious from the code, anything transient, and anything already covered by a fact you saved. **When in doubt whether something is durable, keep it** — storage is cheap and recall only ever surfaces the few relevant facts per message, so more good facts make memory richer, never noisier.
38
38
 
39
39
  ## 3. Save each item (deterministic sink)
40
40
  For every item worth keeping, run one command:
@@ -47,8 +47,9 @@ npx corvusmem --save --dimension <family.topic> --value "<self-contained stateme
47
47
  - 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").
48
48
  - `--keys`: a few search terms, including the user's own language.
49
49
  - Add `--scope usuario` only for facts true across **all** the user's projects; the default is this project.
50
+ - Make each fact **atomic** (one idea) and give it good `--keys` — that is exactly what lets you store many facts without losing any to recall.
50
51
  - Corvus de-duplicates by dimension, so re-running is safe — a repeated value is not stored twice.
51
52
  - If you cannot tell which family a fact belongs to, or whether two notes are the same fact, **ask the user** instead of guessing.
52
53
 
53
- ## 4. Report
54
- 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.
54
+ ## 4. Report — and check coverage
55
+ Finish with: how many documents you read (out of how many `import` found), how many facts you saved (grouped by family), and — importantly — **confirm every doc-tier file contributed at least one fact**, or name the ones that did not and why. If a substantial spec produced zero facts, you skipped it: go back and read it. **Do not delete or modify the original files** — they stay as they are.
package/docs.md CHANGED
@@ -1,108 +1,125 @@
1
- # Corvusmem — Documentation
2
-
3
- > **Your agent, with a memory of its own — and it never leaves your machine.**
4
- >
5
- > For developers who use AI coding agents (Claude Code, Codex) and are tired of them **forgetting everything** between
6
- > sessions, Corvusmem is a **deterministic memory** that lives in a local file you control — no embeddings, no server,
7
- > no API keys. Unlike cloud memories (mem0, Zep), **yours never leaves your machine**.
8
-
9
- This is the narrative documentation (the same as the website `/docs`). For the quick reference of structure and
10
- commands, see the [`README.md`](./README.md).
11
-
12
- ## What it is
13
-
14
- Agents forget everything between sessions. Corvusmem is the memory that **remembers** your people and your projects,
15
- in a single local file you own. It is **deterministic** (same input, same result), **offline** (no network) and
16
- **zero-dependency**. Unlike cloud memories, yours stays yours.
17
-
18
- ## Install
19
-
20
- In Claude Code, from the project root:
21
-
22
- ```
23
- npx corvusmem install --claude # register the hooks in the project's .claude/settings.json
24
- npx corvusmem install --global # for every project (~/.claude/settings.json)
25
- npx corvusmem uninstall # remove Corvusmem's hooks (leaves everything else intact)
26
- npx corvusmem install --dry-run # show what it would do, without writing
27
- ```
28
-
29
- Merge-safe (it never overwrites your hooks or permissions) and idempotent. It creates `.corvusmem/` (project memory)
30
- and, if requested, `~/.config/corvusmem/` (global user memory).
31
-
32
- **Per-project or global only decides *where the hooks turn on*** — in one repo (`--claude`, the config lives in that
33
- repo) or in every project (`--global`, in your home). It does **not** change where memory lives: a project's facts
34
- always land in that repo's `.corvusmem/`, and your personal facts in `~/.config/corvusmem/`. You don't need a
35
- per-project install just to keep memory in the repo — it goes there either way.
36
-
37
- **Codex**: the user installs it from the Codex app (via plugin), not from the CLI. The agent does not install on Codex.
38
-
39
- ## How it works
40
-
41
- 1. **Capture.** A `PostToolUse` hook reads each exchange and extracts facts (decisions, paths, project context).
42
- 2. **Store.** Each fact lands in a lightweight local graph with its name, date and links. The whole Cortex is one file.
43
- 3. **Retrieve.** A query activates the matching node and spreads one hop out (two-hop activation), surfacing related
44
- facts — no semantic search, no embedding model. Instant.
45
-
46
- ## The memory
47
-
48
- Think of it as a notebook your agent keeps for you — but it only writes down what is **stable**: decisions, the
49
- project's stack, who you are, your preferences, your goals. Passing chatter is ignored. When something changes, the new
50
- value **replaces** the old one (the old one is kept, dated, in the history), so your agent never works from something
51
- you already changed. Recall is deterministic: same question, same answer.
52
-
53
- There are two kinds of memory, and they never get mixed up:
54
-
55
- - **Project memory** — about the project (stack, client, decisions, deadlines). Lives in `.corvusmem/` in the project
56
- folder, so the team and Codex share it. "The stack is Next" is true no matter who said it.
57
- - **Your memory** — about you (who you are, how you like to work), carried across every project. Lives on your machine
58
- (`~/.config/corvusmem/`), private to you, never committed. Your agent recalls both at once.
59
-
60
- ## Teams — one project, many people
61
-
62
- When several people work on the same project, the shared memory keeps each person's **personal** facts separate: if Ana
63
- prefers Vim and Bob prefers Emacs, both are kept and neither overwrites the other. Facts that describe the **project
64
- itself** (stack, decisions) stay shared and have no owner. You configure nothing — the author is read from your `git`
65
- email (or your system user), with no network. For a solo developer it's invisible; it just works.
66
-
67
- **To share it with the team**, commit `.corvusmem/` (the shared project memory) and, if you installed per-project,
68
- `.claude/settings.json` so teammates get the hooks the moment they clone. Never commit `~/.config/corvusmem/` — that is
69
- your private, personal memory.
70
-
71
- ## The Cortex
72
-
73
- The Cortex draws everything your agent knows as a **brain of points** — one glow per fact. Each kind of memory settles
74
- in its own zone (decisions, goals, project facts, who you are, what was lived). Search a fact and only its node and
75
- connections light up, like a neuron firing. It is not a picture: it is a readout of the memory the agent actually uses.
76
- Open your own Cortex from any project folder with `npx corvusmem --cortex` (from source: `node cli/memory.mjs
77
- --cortex`). It writes a self-contained HTML file — offline, no network — and prints the path to open in your browser.
78
-
79
- ## Hosts
80
-
81
- The engine detects where it runs and adapts; the memory is the same underneath.
82
-
83
- - **Claude Code** — the hooks register in the project settings; capture after every tool call.
84
- - **Codex** — runs through the plugin path; the same brain, the same local file.
85
- - **Standalone** — a plain CLI for any project: read, write and search the memory directly.
86
-
87
- ## License
88
-
89
- **Free for personal and noncommercial use** under **PolyForm Noncommercial 1.0.0**. Zero telemetry — your memory lives
90
- in local files you own. Using Corvusmem inside a company or a paid product needs a **commercial license**: see
91
- [`COMMERCIAL.md`](./COMMERCIAL.md) (petersonsena24@gmail.com). © 2026 Peterson Sena.
92
-
93
- ## FAQ
94
-
95
- **Does my data ever leave my machine?** No. The memory is a local file you own. No server, no cloud, no API key, no
96
- telemetry. It runs entirely offline.
97
-
98
- **How is this different from mem0 or Zep?** Those store your memory in their cloud behind an API. Corvusmem keeps
99
- everything local and deterministic — same input, same result, no embeddings or vector database.
100
-
101
- **Do I need an embedding model or a vector database?** No. Facts are stored in a lightweight local graph and retrieved
102
- by name, date and relevance with two-hop activation.
103
-
104
- **Which agents does it work with?** Claude Code and Codex today, plus a standalone CLI. The engine detects its host and
105
- adapts; the memory is the same underneath.
106
-
107
- **Is it free?** Free for personal and noncommercial use (PolyForm Noncommercial). Inside a company or a paid product it
108
- needs a commercial license.
1
+ # Corvusmem — Documentation
2
+
3
+ > **Your agent, with a memory of its own — and it never leaves your machine.**
4
+ >
5
+ > For developers who use AI coding agents (Claude Code, Codex) and are tired of them **forgetting everything** between
6
+ > sessions, Corvusmem is a **deterministic memory** that lives in a local file you control — no embeddings, no server,
7
+ > no API keys. Unlike cloud memories (mem0, Zep), **yours never leaves your machine**.
8
+
9
+ This is the narrative documentation (the same as the website `/docs`). For the quick reference of structure and
10
+ commands, see the [`README.md`](./README.md).
11
+
12
+ ## What it is
13
+
14
+ Agents forget everything between sessions. Corvusmem is the memory that **remembers** your people and your projects,
15
+ in a single local file you own. It is **deterministic** (same input, same result), **offline** (no network) and
16
+ **zero-dependency**. Unlike cloud memories, yours stays yours.
17
+
18
+ ## Install
19
+
20
+ Pick one. **As a plugin** if your agent supports plugins (Claude Code, Codex): native, nothing to wire into a project,
21
+ and the memory CLI runs locally (no `npx` cold start). **As an `npx` install** for any other agent, or a quick trial.
22
+
23
+ ### As a plugin — Claude Code (recommended)
24
+
25
+ ```
26
+ /plugin marketplace add petersonsenadevs/corvusmem
27
+ /plugin install corvusmem@corvusmem
28
+ ```
29
+
30
+ Claude loads it the way it loads any plugin: the hooks fire natively, everywhere, and saving/recalling runs as
31
+ `node "$CLAUDE_PLUGIN_ROOT/cli/corvusmem.mjs"` — no `npx`. Update with `/plugin update corvusmem@corvusmem`.
32
+
33
+ ### As a plugin — Codex
34
+
35
+ Add the same marketplace in the Codex app and approve the hooks (stored in `~/.codex/config.toml`). It is the **same**
36
+ plugin: `hooks/hooks.json` uses `${CLAUDE_PLUGIN_ROOT}`, and edits arrive as `apply_patch`, which the hooks understand.
37
+
38
+ ### As an npx install (any agent, or a quick trial)
39
+
40
+ ```
41
+ npx corvusmem install # register the hooks in the project's .claude/settings.json
42
+ npx corvusmem install --global # for every project (~/.claude/settings.json)
43
+ npx corvusmem uninstall # remove Corvusmem's hooks (leaves memory intact)
44
+ npx corvusmem install --dry-run # show what it would do, without writing
45
+ ```
46
+
47
+ Merge-safe (it never overwrites your hooks or permissions) and idempotent. It copies the hooks **and** the memory CLI
48
+ to a durable spot (`.corvusmem/hooks/` + `.corvusmem/cli/`, or `~/.config/corvusmem/` for `--global`), so from then on
49
+ the hooks and the save/recall commands run via `node`, not `npx`. The bare `npx corvusmem --save/--recall` still works
50
+ for an agent with none of this set up (just slower).
51
+
52
+ **Per-project or global only decides *where the hooks turn on*** — in one repo (the config lives in that repo) or in
53
+ every project (`--global`, in your home). It does **not** change where memory lives: a project's facts always land in
54
+ that repo's `.corvusmem/`, and your personal facts in `~/.config/corvusmem/`.
55
+
56
+ ## How it works
57
+
58
+ 1. **Capture.** A `PostToolUse` hook reads each exchange and extracts facts (decisions, paths, project context).
59
+ 2. **Store.** Each fact lands in a lightweight local graph with its name, date and links. The whole Cortex is one file.
60
+ 3. **Retrieve.** A query activates the matching node and spreads one hop out (two-hop activation), surfacing related
61
+ facts — no semantic search, no embedding model. Instant.
62
+
63
+ ## The memory
64
+
65
+ Think of it as a notebook your agent keeps for you — but it only writes down what is **stable**: decisions, the
66
+ project's stack, who you are, your preferences, your goals. Passing chatter is ignored. When something changes, the new
67
+ value **replaces** the old one (the old one is kept, dated, in the history), so your agent never works from something
68
+ you already changed. Recall is deterministic: same question, same answer.
69
+
70
+ There are two kinds of memory, and they never get mixed up:
71
+
72
+ - **Project memory** — about the project (stack, client, decisions, deadlines). Lives in `.corvusmem/` in the project
73
+ folder, so the team and Codex share it. "The stack is Next" is true no matter who said it.
74
+ - **Your memory** — about you (who you are, how you like to work), carried across every project. Lives on your machine
75
+ (`~/.config/corvusmem/`), private to you, never committed. Your agent recalls both at once.
76
+
77
+ ## Teams — one project, many people
78
+
79
+ When several people work on the same project, the shared memory keeps each person's **personal** facts separate: if Ana
80
+ prefers Vim and Bob prefers Emacs, both are kept and neither overwrites the other. Facts that describe the **project
81
+ itself** (stack, decisions) stay shared and have no owner. You configure nothing — the author is read from your `git`
82
+ email (or your system user), with no network. For a solo developer it's invisible; it just works.
83
+
84
+ **To share it with the team**, commit `.corvusmem/` (the shared project memory) and, if you installed per-project,
85
+ `.claude/settings.json` so teammates get the hooks the moment they clone. Never commit `~/.config/corvusmem/` — that is
86
+ your private, personal memory.
87
+
88
+ ## The Cortex
89
+
90
+ The Cortex draws everything your agent knows as a **brain of points** — one glow per fact. Each kind of memory settles
91
+ in its own zone (decisions, goals, project facts, who you are, what was lived). Search a fact and only its node and
92
+ connections light up, like a neuron firing. It is not a picture: it is a readout of the memory the agent actually uses.
93
+ Open your own Cortex from any project folder with `npx corvusmem --cortex` (from source: `node cli/memory.mjs
94
+ --cortex`). It writes a self-contained HTML file — offline, no network — and prints the path to open in your browser.
95
+
96
+ ## Hosts
97
+
98
+ The engine detects where it runs and adapts; the memory is the same underneath.
99
+
100
+ - **Claude Code** — the hooks register in the project settings; capture after every tool call.
101
+ - **Codex** — runs through the plugin path; the same brain, the same local file.
102
+ - **Standalone** — a plain CLI for any project: read, write and search the memory directly.
103
+
104
+ ## License
105
+
106
+ **Free for personal and noncommercial use** under **PolyForm Noncommercial 1.0.0**. Zero telemetry — your memory lives
107
+ in local files you own. Using Corvusmem inside a company or a paid product needs a **commercial license**: see
108
+ [`COMMERCIAL.md`](./COMMERCIAL.md) (petersonsena24@gmail.com). © 2026 Peterson Sena.
109
+
110
+ ## FAQ
111
+
112
+ **Does my data ever leave my machine?** No. The memory is a local file you own. No server, no cloud, no API key, no
113
+ telemetry. It runs entirely offline.
114
+
115
+ **How is this different from mem0 or Zep?** Those store your memory in their cloud behind an API. Corvusmem keeps
116
+ everything local and deterministic — same input, same result, no embeddings or vector database.
117
+
118
+ **Do I need an embedding model or a vector database?** No. Facts are stored in a lightweight local graph and retrieved
119
+ by name, date and relevance with two-hop activation.
120
+
121
+ **Which agents does it work with?** Claude Code and Codex today, plus a standalone CLI. The engine detects its host and
122
+ adapts; the memory is the same underneath.
123
+
124
+ **Is it free?** Free for personal and noncommercial use (PolyForm Noncommercial). Inside a company or a paid product it
125
+ needs a commercial license.
package/install.mjs CHANGED
@@ -19,10 +19,12 @@ import fs from 'node:fs';
19
19
  import os from 'node:os';
20
20
  import path from 'node:path';
21
21
  import { fileURLToPath } from 'node:url';
22
+ import { esSenzu } from './src/lib.mjs'; // para el aviso de proyecto con Senzu
22
23
 
23
24
  const AQUI = path.dirname(fileURLToPath(import.meta.url));
24
25
  const SRC = path.join(AQUI, 'src'); // donde viven los hooks del núcleo (ruta absoluta)
25
26
  const CMDS_SRC = path.join(AQUI, 'commands'); // slash-command templates (/corvus-absorb)
27
+ const CLI_SRC = path.join(AQUI, 'cli'); // el CLI de la memoria (corvusmem.mjs + subcomandos): se empaqueta para el guardado RÁPIDO (sin npx)
26
28
  const args = process.argv.slice(2);
27
29
  const opt = n => { const i = args.indexOf(n); return i >= 0 ? (args[i + 1] && !args[i + 1].startsWith('--') ? args[i + 1] : true) : null; };
28
30
  const has = n => args.includes(n);
@@ -66,6 +68,17 @@ function copiarHooks(dir) {
66
68
  for (const f of fs.readdirSync(SRC)) if (f.endsWith('.mjs')) { fs.copyFileSync(path.join(SRC, f), path.join(dir, f)); n++; }
67
69
  return n;
68
70
  }
71
+ // Copia el CLI de memoria (corvusmem.mjs + subcomandos) a <baseDir>/cli/, HERMANO de hooks/. Así el agente guarda y
72
+ // recuerda con `node "<baseDir>/cli/corvusmem.mjs" --save …` — rápido y nativo, SIN el arranque en frío de npx. cli/memory.mjs
73
+ // resuelve el motor en ../hooks/facts.mjs (ver su `motor()`). El `npx corvusmem` sigue valiendo como fallback.
74
+ function copiarCli(baseDir) {
75
+ if (DRY) { log(` [dry-run] would copy the memory CLI to ${path.join(baseDir, 'cli')}`); return 0; }
76
+ const dir = path.join(baseDir, 'cli');
77
+ fs.mkdirSync(dir, { recursive: true });
78
+ let n = 0;
79
+ for (const f of fs.readdirSync(CLI_SRC)) if (f.endsWith('.mjs')) { fs.copyFileSync(path.join(CLI_SRC, f), path.join(dir, f)); n++; }
80
+ return n;
81
+ }
69
82
 
70
83
  // Slash commands (e.g. /corvus-absorb) go to .claude/commands/ — per project, or the HOME with --global.
71
84
  function instalarComandos(quitar) {
@@ -112,6 +125,8 @@ function empaquetarPlugin(destino) {
112
125
  // 2) los .mjs del nucleo (hooks + dependencias de mismo directorio: autocontenido, cero imports externos)
113
126
  let n = 0;
114
127
  for (const f of fs.readdirSync(SRC)) if (f.endsWith('.mjs')) { fs.copyFileSync(path.join(SRC, f), path.join(hooksDir, f)); n++; }
128
+ // 2b) el CLI de memoria en <plugin>/cli/ (hermano de hooks/): para que el agente guarde/recuerde con node, sin npx
129
+ const ncli = copiarCli(dir);
115
130
  // 3) slash commands (/corvus-absorb) in the plugin's commands/ dir
116
131
  let nc = 0;
117
132
  try {
@@ -119,10 +134,33 @@ function empaquetarPlugin(destino) {
119
134
  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
135
  } catch { /* no commands/ */ }
121
136
  // 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' };
137
+ 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' }, homepage: pkg.homepage || 'https://corvusmem.vercel.app', repository: (pkg.repository && pkg.repository.url) || 'https://github.com/petersonsenadevs/corvusmem', license: 'SEE LICENSE IN LICENSE' };
123
138
  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.');
139
+ log(` [plugin] ${dir}: .claude-plugin/plugin.json + hooks/hooks.json + ${n} .mjs + ${ncli} cli${nc ? ` + ${nc} command(s)` : ''}`);
140
+ }
141
+
142
+ // Genera, DENTRO del repo, el plugin committeable `plugins/corvusmem/` y el `.claude-plugin/marketplace.json` de la
143
+ // raíz: el propio repo ES el marketplace de Claude Code (igual que Senzu). Tras esto:
144
+ // Claude Code: /plugin marketplace add petersonsenadevs/corvusmem · /plugin install corvusmem@corvusmem
145
+ // Codex: consume el MISMO plugin (hooks.json con ${CLAUDE_PLUGIN_ROOT}); se aprueban los hooks en la app.
146
+ // Se vuelve a ejecutar en cada release (lo hace el flujo de versión) para que el plugin lleve la versión y los hooks al día.
147
+ function generarMarketplace() {
148
+ let pkg = {}; try { pkg = JSON.parse(fs.readFileSync(path.join(AQUI, 'package.json'), 'utf8')); } catch { }
149
+ const pluginDir = path.join(AQUI, 'plugins', 'corvusmem');
150
+ if (!DRY) fs.rmSync(pluginDir, { recursive: true, force: true }); // regenerar limpio
151
+ empaquetarPlugin(pluginDir);
152
+ const desc = pkg.description || 'Memoria determinista, offline y sin dependencias para agentes de IA (Claude Code, Codex).';
153
+ const mkt = {
154
+ name: 'corvusmem',
155
+ owner: { name: 'Peterson Sena' },
156
+ metadata: { version: pkg.version || '0.0.0', description: 'Marketplace de Corvusmem: memoria determinista, offline y sin dependencias para agentes de IA.' },
157
+ plugins: [{
158
+ name: 'corvusmem', source: './plugins/corvusmem', description: desc, version: pkg.version || '0.0.0',
159
+ category: 'development', keywords: ['memory', 'memoria', 'hooks', 'offline', 'deterministic', 'facts', 'recall', 'claude', 'codex'],
160
+ }],
161
+ };
162
+ if (!DRY) { fs.mkdirSync(path.join(AQUI, '.claude-plugin'), { recursive: true }); fs.writeFileSync(path.join(AQUI, '.claude-plugin', 'marketplace.json'), JSON.stringify(mkt, null, 2) + '\n'); }
163
+ log(` [marketplace] .claude-plugin/marketplace.json -> plugins/corvusmem (v${pkg.version || '0.0.0'})`);
126
164
  }
127
165
 
128
166
  // Construye los grupos de hooks de un evento en el formato de settings.json de Claude.
@@ -177,16 +215,26 @@ function run() {
177
215
  return;
178
216
  }
179
217
 
218
+ // Modo marketplace: genera plugins/corvusmem/ + .claude-plugin/marketplace.json EN EL REPO (el repo es el marketplace).
219
+ if (has('--marketplace')) {
220
+ log(`Corvusmem · generate marketplace + committed plugin${DRY ? ' (dry-run)' : ''}`);
221
+ generarMarketplace();
222
+ log('Done.');
223
+ return;
224
+ }
225
+
180
226
  const quitar = has('--uninstall');
181
227
  log(`Corvusmem · ${quitar ? 'uninstall' : 'install'}${GLOBAL ? ' (global)' : ''}${DRY ? ' (dry-run)' : ''}`);
182
228
 
183
229
  // 0) Copias DURABLES de los hooks (o quitarlas). La MEMORIA (.corvusmem/memoria, ~/.config/corvusmem) no se toca.
230
+ const cliBase = path.dirname(hooksDir); // .corvusmem/ (proyecto) o ~/.config/corvusmem/ (global); el cli va junto a hooks
184
231
  if (quitar) {
185
- if (!DRY) { try { fs.rmSync(hooksDir, { recursive: true, force: true }); } catch {} }
232
+ if (!DRY) { try { fs.rmSync(hooksDir, { recursive: true, force: true }); } catch {} try { fs.rmSync(path.join(cliBase, 'cli'), { recursive: true, force: true }); } catch {} }
186
233
  log(` [hooks] removed ${hooksDir}`);
187
234
  } else {
188
235
  const n = copiarHooks(hooksDir);
189
- log(` [hooks] ${n} core file(s) copied to ${hooksDir.replace(/\\/g, '/')}`);
236
+ const ncli = copiarCli(cliBase);
237
+ log(` [hooks] ${n} core file(s) + ${ncli} CLI file(s) copied to ${cliBase.replace(/\\/g, '/')} (fast save, no npx)`);
190
238
  }
191
239
 
192
240
  // 1) Claude: hooks en settings.json (proyecto o HOME)
@@ -212,6 +260,15 @@ function run() {
212
260
  log(' [memory] .corvusmem/ (project) and ~/.config/corvusmem/ (global) ready');
213
261
  }
214
262
 
263
+ // Heads-up: in a project that already uses Senzu, Corvus becomes the MEMORY owner — it adopts the facts Senzu had
264
+ // in senzu/memoria/ into its own .corvusmem/memory/, and Senzu (updated to its latest) defers its memory hooks to
265
+ // Corvus. Senzu keeps everything else (method, plan, devlog, guards). Update the global Senzu plugin so it defers.
266
+ if (!quitar && !GLOBAL && esSenzu(PROYECTO)) {
267
+ log(' [senzu] This project also uses Senzu. Corvus now OWNS the memory here: it adopts the facts from');
268
+ log(' senzu/memoria/ into .corvusmem/memory/ and Senzu defers its memory hooks to Corvus.');
269
+ log(' Update the Senzu plugin to its latest so it steps back from memory (it keeps method/devlog/guards).');
270
+ }
271
+
215
272
  log('Done.' + (quitar ? '' : ' Codex: per-event hooks go through the plugin; in Claude they are already active.'));
216
273
  }
217
274
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "corvusmem",
3
- "version": "0.3.3",
3
+ "version": "0.5.0",
4
4
  "description": "Deterministic, offline, zero-dependency memory for AI coding agents (Claude Code, Codex) and a standalone CLI.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/facts.mjs CHANGED
@@ -17,8 +17,8 @@ import crypto from 'node:crypto';
17
17
  import os from 'node:os';
18
18
  import { spawnSync } from 'node:child_process';
19
19
  import { fileURLToPath } from 'node:url';
20
- import { ruta, rutaMemoriaUsuario, rutaEstado, localeUI, nombresMemoria, migrarMemoriaCorvus } from './lib.mjs';
21
- 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/)
20
+ import { ruta, rutaMemoriaUsuario, rutaEstado, localeUI, nombresMemoria, migrarMemoriaCorvus, adoptarMemoriaSenzu } from './lib.mjs';
21
+ export { rutaNativa, localeUI, carpetaBase, esSenzu, adoptarMemoriaSenzu } from './lib.mjs'; // memory.mjs: --path (C:\, C:/, /c/ de Git Bash → el mismo almacén), idioma de UI, carpeta base y adopción de la memoria de Senzu
22
22
 
23
23
  export const FAMILIAS_VARIOS = /^(objetivo|pendiente|nota|hecho|enlace|aprendizaje)(\.|$)/;
24
24
  // Multiusuario (F14): familias PERSONALES (de la persona, no del proyecto). En memoria de proyecto COMPARTIDA, su
@@ -41,8 +41,9 @@ function autorActual(root, env = process.env) {
41
41
  }
42
42
  export function rutaHechos(root, alcance = 'proyecto') {
43
43
  if (alcance === 'usuario') return path.join(path.dirname(rutaMemoriaUsuario()), 'hechos.jsonl'); // compartida con Senzu: nombre en español
44
+ adoptarMemoriaSenzu(root); // proyecto que ya usaba Senzu: hereda senzu/memoria/hechos.jsonl una vez (copia)
44
45
  migrarMemoriaCorvus(root); // instalaciones viejas: .corvusmem/memoria/hechos.jsonl -> .corvusmem/memory/facts.jsonl (idempotente)
45
- return path.join(ruta(root, 'memoria'), nombresMemoria(root).facts); // standalone: memory/facts.jsonl · acoplado/legacy: memoria/hechos.jsonl
46
+ return path.join(ruta(root, 'memoria'), nombresMemoria(root).facts); // SIEMPRE .corvusmem/memory/facts.jsonl; Corvus es el dueño, Senzu le cede la memoria
46
47
  }
47
48
 
48
49
  // ---------------------------------------------------------------- texto: normalizar y partir en palabras
package/src/host.mjs CHANGED
@@ -1,118 +1,119 @@
1
- #!/usr/bin/env node
2
- // host.mjs — Detección de anfitrión del núcleo de memoria (carve-out Corvusmem, F9-T2).
3
- // El MISMO núcleo corre bajo varios anfitriones; aquí se resuelve, por señales del entorno, determinista y sin red:
4
- // · agente: 'claude' | 'codex' | 'obsidian' | 'standalone' — el runtime que ejecuta el núcleo
5
- // · senzu: ¿está la capa Senzu presente en el proyecto? — clave para el apretón de manos (F9-T3): si está,
6
- // el núcleo cede la inyección para no duplicarla
7
- // · memoria: dónde leer/escribir — { proyecto, usuario (global), estado (sesión) }
8
- // · inyeccion: por dónde sale el contexto — 'hook-stdout' (claude/codex) | 'plugin-api' (obsidian) | 'stdout'
9
- // Señales REALES del repo (ver lib.readHookInput): Claude exporta CLAUDE_PROJECT_DIR/CLAUDE_PLUGIN_ROOT; Codex no,
10
- // y la raíz llega como "cwd" en la entrada, con forma de parche (apply_patch / codex_tool_name); Senzu = marcador
11
- // senzu/senzu.json (lib.rutaMarcador). Obsidian y standalone aún no corren en este repo: Obsidian lo marca su
12
- // adaptador (CORVUS_OBSIDIAN, F10-T3); sin señales → standalone. Todo lee de un `env` INYECTABLE: así se testea
13
- // hermético y queda determinista.
14
- import fs from 'node:fs';
15
- import os from 'node:os';
16
- import path from 'node:path';
17
- import crypto from 'node:crypto';
18
- import { pathToFileURL } from 'node:url';
19
- import { rutaNativa, ruta, rutaMarcador } from './lib.mjs';
20
-
21
- export const ANFITRIONES = ['claude', 'codex', 'obsidian', 'standalone'];
22
-
23
- // Espejo de lib.rutaMemoriaUsuario pero leyendo del env inyectado (memoria global, igual en todos los anfitriones).
24
- const rutaUsuario = env => env.SENZU_MEMORIA_USUARIO || env.DEV_STANDARDS_MEMORIA_USUARIO
25
- || path.join(os.homedir(), '.config', 'senzu', 'memoria.md');
26
-
27
- const existeMarcadorSenzu = raiz => { try { return fs.existsSync(rutaMarcador(raiz)); } catch { return false; } };
28
-
29
- function detectarAgente(env, input) {
30
- // 1) Forzado explícito, pero SOLO si es un valor conocido: una variable "mentida"/basura se ignora y se detecta igual
31
- const forzado = String(env.CORVUS_ANFITRION || '').toLowerCase();
32
- if (ANFITRIONES.includes(forzado)) return forzado;
33
- // 2) Obsidian: marcador explícito de su adaptador (gana a Claude: es una señal deliberada, no ambiental)
34
- if (env.CORVUS_OBSIDIAN) return 'obsidian';
35
- // 3) Claude: exporta estas variables de entorno
36
- if (env.CLAUDE_PROJECT_DIR || env.CLAUDE_PLUGIN_ROOT) return 'claude';
37
- // 4) Codex: no exporta CLAUDE_*; la raíz llega como cwd y la edición como parche
38
- if (input && (input.codex_tool_name || input.tool_name === 'apply_patch' || input.cwd)) return 'codex';
39
- // 5) Sin señales: uso directo (CLI / biblioteca)
40
- return 'standalone';
41
- }
42
-
43
- // Resuelve el anfitrión y el mapa de memoria. input = entrada del hook (opcional); env = variables (inyectable);
44
- // root = raíz del proyecto (opcional; si falta se deduce del env/input/cwd). Solo lectura: no crea carpetas.
45
- export function resolverHost({ input = {}, env = process.env, root } = {}) {
46
- const raiz = rutaNativa(root || env.CLAUDE_PROJECT_DIR || (input && input.cwd) || process.cwd());
47
- const agente = detectarAgente(env, input);
48
- const senzu = existeMarcadorSenzu(raiz);
49
- const inyeccion = agente === 'obsidian' ? 'plugin-api' : agente === 'standalone' ? 'stdout' : 'hook-stdout';
50
- const proyecto = senzu ? path.dirname(rutaMarcador(raiz))
51
- : agente === 'obsidian' ? (env.CORVUS_VAULT || null)
52
- : path.join(raiz, '.corvusmem');
53
- return {
54
- agente,
55
- senzu,
56
- raiz,
57
- inyeccion,
58
- memoria: {
59
- proyecto,
60
- usuario: rutaUsuario(env),
61
- estado: path.join(ruta(raiz, '.estado'), 'ultima-sesion.json'), // sin efecto: no crea el dir (a diferencia de lib.rutaEstado)
62
- },
63
- };
64
- }
65
-
66
- // ---------------------------------------------------------------- apretón de manos (F9-T3)
67
- // Que recuerdo-vivo + session-start (los que emiten additionalContext) no inyecten DOS VECES cuando hay dos capas
68
- // registradas para el mismo evento (p. ej. el núcleo Corvusmem y el adaptador Senzu). Cerrojo de turno
69
- // "primero-gana", atómico: la primera invocación de un evento+turno se queda el turno e inyecta; la segunda lo ve
70
- // y cede. El contenido es el mismo motor en ambas capas, así que da igual quién gane: basta con que inyecte UNA.
71
- // NO se basa en "quién es Senzu" (en el repo fuente los hooks son los de Senzu pero no hay senzu.json; un cede por
72
- // marcador los silenciaría): el dueño determinista por capa se decide en F10, cuando cada capa tiene su instalación.
73
- const sanitClave = s => s.replace(/[^a-zA-Z0-9_.-]/g, '_').slice(0, 180);
74
-
75
- // Clave del turno: el mismo mensaje/arranque produce la MISMA clave en las dos capas (para que colisionen y una ceda),
76
- // pero DISTINTA entre proyectos (raíz) y sesiones (sid), para no mezclar turnos de proyectos ni de sesiones distintas.
77
- function claveTurno(evento, input, root) {
78
- const sid = String((input && input.session_id) || 'default');
79
- const raiz = root ? crypto.createHash('md5').update(String(root)).digest('hex').slice(0, 8) : '';
80
- let huella = '';
81
- if (evento === 'UserPromptSubmit') huella = crypto.createHash('md5').update(String((input && input.prompt) || '')).digest('hex').slice(0, 12);
82
- else if (evento === 'SessionStart') huella = String((input && input.source) || '');
83
- return `${evento}:${raiz}:${sid}:${huella}`;
84
- }
85
-
86
- // Reclamo atómico: true = me quedo el turno (inyecto); false = ya lo tiene otro fresco (cedo). Creación exclusiva
87
- // (flag 'wx') → en una carrera de procesos solo uno crea el archivo. Marca caducada (crash/sesión muerta) → se
88
- // retira y se reintenta. Reloj hacia atrás (ahora < ts) → diff negativa < ttl → fresca → cedo (no caduca en falso).
89
- function reclamarMarca(f, { pid, ahora, ttlMs }) {
90
- try { fs.mkdirSync(path.dirname(f), { recursive: true }); } catch { }
91
- for (let i = 0; i < 2; i++) {
92
- try {
93
- fs.writeFileSync(f, JSON.stringify({ pid, ts: ahora }), { flag: 'wx' });
94
- return true;
95
- } catch (e) {
96
- if (e.code !== 'EEXIST') throw e;
97
- let ts = 0;
98
- try { ts = (JSON.parse(fs.readFileSync(f, 'utf8')) || {}).ts || 0; } catch { }
99
- if (ahora - ts < ttlMs) return false; // marca fresca de otra capa: cedo
100
- try { fs.rmSync(f, { force: true }); } catch { } // marca huérfana: la retiro y reintento
101
- }
102
- }
103
- return false; // otro se adelantó tras retirar la huérfana: cedo
104
- }
105
-
106
- // ¿Debo inyectar YO este evento? dir inyectable para tests; por defecto el temp con prefijo dev-standards- (lo barre
107
- // session-end a los 2 días). ttlMs = ventana de un turno: pasada, una marca se considera huérfana.
108
- export function reclamarInyeccion(evento, { input = {}, root, ahora = Date.now(), ttlMs = 60000, dir } = {}) {
109
- const clave = claveTurno(evento, input, root);
110
- const f = dir ? path.join(dir, sanitClave(clave) + '.claim') : path.join(os.tmpdir(), 'dev-standards-hsk-' + sanitClave(clave) + '.flag');
111
- const inyectar = reclamarMarca(f, { pid: process.pid, ahora, ttlMs });
112
- return { inyectar, clave, archivo: f, motivo: inyectar ? 'reclamado' : 'ya reclamado este turno' };
113
- }
114
-
115
- // CLI de diagnóstico: `node core/hooks/host.mjs` imprime el anfitrión resuelto aquí y ahora.
116
- if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
117
- process.stdout.write(JSON.stringify(resolverHost(), null, 2) + '\n');
118
- }
1
+ #!/usr/bin/env node
2
+ // host.mjs — Detección de anfitrión del núcleo de memoria (carve-out Corvusmem, F9-T2).
3
+ // El MISMO núcleo corre bajo varios anfitriones; aquí se resuelve, por señales del entorno, determinista y sin red:
4
+ // · agente: 'claude' | 'codex' | 'obsidian' | 'standalone' — el runtime que ejecuta el núcleo
5
+ // · senzu: ¿está la capa Senzu presente en el proyecto? — clave para el apretón de manos (F9-T3): si está,
6
+ // el núcleo cede la inyección para no duplicarla
7
+ // · memoria: dónde leer/escribir — { proyecto, usuario (global), estado (sesión) }
8
+ // · inyeccion: por dónde sale el contexto — 'hook-stdout' (claude/codex) | 'plugin-api' (obsidian) | 'stdout'
9
+ // Señales REALES del repo (ver lib.readHookInput): Claude exporta CLAUDE_PROJECT_DIR/CLAUDE_PLUGIN_ROOT; Codex no,
10
+ // y la raíz llega como "cwd" en la entrada, con forma de parche (apply_patch / codex_tool_name); Senzu = marcador
11
+ // senzu/senzu.json (lib.rutaMarcador). Obsidian y standalone aún no corren en este repo: Obsidian lo marca su
12
+ // adaptador (CORVUS_OBSIDIAN, F10-T3); sin señales → standalone. Todo lee de un `env` INYECTABLE: así se testea
13
+ // hermético y queda determinista.
14
+ import fs from 'node:fs';
15
+ import os from 'node:os';
16
+ import path from 'node:path';
17
+ import crypto from 'node:crypto';
18
+ import { pathToFileURL } from 'node:url';
19
+ import { rutaNativa, ruta, rutaMarcador } from './lib.mjs';
20
+
21
+ export const ANFITRIONES = ['claude', 'codex', 'obsidian', 'standalone'];
22
+
23
+ // Espejo de lib.rutaMemoriaUsuario pero leyendo del env inyectado (memoria global, igual en todos los anfitriones).
24
+ const rutaUsuario = env => env.SENZU_MEMORIA_USUARIO || env.DEV_STANDARDS_MEMORIA_USUARIO
25
+ || path.join(os.homedir(), '.config', 'senzu', 'memoria.md');
26
+
27
+ const existeMarcadorSenzu = raiz => { try { return fs.existsSync(rutaMarcador(raiz)); } catch { return false; } };
28
+
29
+ function detectarAgente(env, input) {
30
+ // 1) Forzado explícito, pero SOLO si es un valor conocido: una variable "mentida"/basura se ignora y se detecta igual
31
+ const forzado = String(env.CORVUS_ANFITRION || '').toLowerCase();
32
+ if (ANFITRIONES.includes(forzado)) return forzado;
33
+ // 2) Obsidian: marcador explícito de su adaptador (gana a Claude: es una señal deliberada, no ambiental)
34
+ if (env.CORVUS_OBSIDIAN) return 'obsidian';
35
+ // 3) Claude: exporta estas variables de entorno
36
+ if (env.CLAUDE_PROJECT_DIR || env.CLAUDE_PLUGIN_ROOT) return 'claude';
37
+ // 4) Codex: no exporta CLAUDE_*; la raíz llega como cwd y la edición como parche
38
+ if (input && (input.codex_tool_name || input.tool_name === 'apply_patch' || input.cwd)) return 'codex';
39
+ // 5) Sin señales: uso directo (CLI / biblioteca)
40
+ return 'standalone';
41
+ }
42
+
43
+ // Resuelve el anfitrión y el mapa de memoria. input = entrada del hook (opcional); env = variables (inyectable);
44
+ // root = raíz del proyecto (opcional; si falta se deduce del env/input/cwd). Solo lectura: no crea carpetas.
45
+ export function resolverHost({ input = {}, env = process.env, root } = {}) {
46
+ const raiz = rutaNativa(root || env.CLAUDE_PROJECT_DIR || (input && input.cwd) || process.cwd());
47
+ const agente = detectarAgente(env, input);
48
+ const senzu = existeMarcadorSenzu(raiz);
49
+ const inyeccion = agente === 'obsidian' ? 'plugin-api' : agente === 'standalone' ? 'stdout' : 'hook-stdout';
50
+ // Corvus's project store is ALWAYS its own .corvusmem/ — it never resolves into senzu/ any more. The `senzu` flag
51
+ // above still drives the hand-off: when Senzu is present Corvus's hooks stand down (lib.cederASenzu), they do not
52
+ // share Senzu's file. Obsidian keeps its vault.
53
+ const proyecto = agente === 'obsidian' ? (env.CORVUS_VAULT || null) : path.join(raiz, '.corvusmem');
54
+ return {
55
+ agente,
56
+ senzu,
57
+ raiz,
58
+ inyeccion,
59
+ memoria: {
60
+ proyecto,
61
+ usuario: rutaUsuario(env),
62
+ estado: path.join(ruta(raiz, '.estado'), 'ultima-sesion.json'), // sin efecto: no crea el dir (a diferencia de lib.rutaEstado)
63
+ },
64
+ };
65
+ }
66
+
67
+ // ---------------------------------------------------------------- apretón de manos (F9-T3)
68
+ // Que recuerdo-vivo + session-start (los que emiten additionalContext) no inyecten DOS VECES cuando hay dos capas
69
+ // registradas para el mismo evento (p. ej. el núcleo Corvusmem y el adaptador Senzu). Cerrojo de turno
70
+ // "primero-gana", atómico: la primera invocación de un evento+turno se queda el turno e inyecta; la segunda lo ve
71
+ // y cede. El contenido es el mismo motor en ambas capas, así que da igual quién gane: basta con que inyecte UNA.
72
+ // NO se basa en "quién es Senzu" (en el repo fuente los hooks son los de Senzu pero no hay senzu.json; un cede por
73
+ // marcador los silenciaría): el dueño determinista por capa se decide en F10, cuando cada capa tiene su instalación.
74
+ const sanitClave = s => s.replace(/[^a-zA-Z0-9_.-]/g, '_').slice(0, 180);
75
+
76
+ // Clave del turno: el mismo mensaje/arranque produce la MISMA clave en las dos capas (para que colisionen y una ceda),
77
+ // pero DISTINTA entre proyectos (raíz) y sesiones (sid), para no mezclar turnos de proyectos ni de sesiones distintas.
78
+ function claveTurno(evento, input, root) {
79
+ const sid = String((input && input.session_id) || 'default');
80
+ const raiz = root ? crypto.createHash('md5').update(String(root)).digest('hex').slice(0, 8) : '';
81
+ let huella = '';
82
+ if (evento === 'UserPromptSubmit') huella = crypto.createHash('md5').update(String((input && input.prompt) || '')).digest('hex').slice(0, 12);
83
+ else if (evento === 'SessionStart') huella = String((input && input.source) || '');
84
+ return `${evento}:${raiz}:${sid}:${huella}`;
85
+ }
86
+
87
+ // Reclamo atómico: true = me quedo el turno (inyecto); false = ya lo tiene otro fresco (cedo). Creación exclusiva
88
+ // (flag 'wx') → en una carrera de procesos solo uno crea el archivo. Marca caducada (crash/sesión muerta) → se
89
+ // retira y se reintenta. Reloj hacia atrás (ahora < ts) → diff negativa < ttl → fresca → cedo (no caduca en falso).
90
+ function reclamarMarca(f, { pid, ahora, ttlMs }) {
91
+ try { fs.mkdirSync(path.dirname(f), { recursive: true }); } catch { }
92
+ for (let i = 0; i < 2; i++) {
93
+ try {
94
+ fs.writeFileSync(f, JSON.stringify({ pid, ts: ahora }), { flag: 'wx' });
95
+ return true;
96
+ } catch (e) {
97
+ if (e.code !== 'EEXIST') throw e;
98
+ let ts = 0;
99
+ try { ts = (JSON.parse(fs.readFileSync(f, 'utf8')) || {}).ts || 0; } catch { }
100
+ if (ahora - ts < ttlMs) return false; // marca fresca de otra capa: cedo
101
+ try { fs.rmSync(f, { force: true }); } catch { } // marca huérfana: la retiro y reintento
102
+ }
103
+ }
104
+ return false; // otro se adelantó tras retirar la huérfana: cedo
105
+ }
106
+
107
+ // ¿Debo inyectar YO este evento? dir inyectable para tests; por defecto el temp con prefijo dev-standards- (lo barre
108
+ // session-end a los 2 días). ttlMs = ventana de un turno: pasada, una marca se considera huérfana.
109
+ export function reclamarInyeccion(evento, { input = {}, root, ahora = Date.now(), ttlMs = 60000, dir } = {}) {
110
+ const clave = claveTurno(evento, input, root);
111
+ const f = dir ? path.join(dir, sanitClave(clave) + '.claim') : path.join(os.tmpdir(), 'dev-standards-hsk-' + sanitClave(clave) + '.flag');
112
+ const inyectar = reclamarMarca(f, { pid: process.pid, ahora, ttlMs });
113
+ return { inyectar, clave, archivo: f, motivo: inyectar ? 'reclamado' : 'ya reclamado este turno' };
114
+ }
115
+
116
+ // CLI de diagnóstico: `node core/hooks/host.mjs` imprime el anfitrión resuelto aquí y ahora.
117
+ if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
118
+ process.stdout.write(JSON.stringify(resolverHost(), null, 2) + '\n');
119
+ }
package/src/lib.mjs CHANGED
@@ -109,20 +109,21 @@ export function carpetaBase(root) {
109
109
  if (esLegado(root)) return CARPETA; // legacy Senzu project (root devlog / .dev-standards.json)
110
110
  return CARPETA_CORVUS; // no real Senzu (even a stray senzu/) -> Corvus owns its dir
111
111
  }
112
- // Facts storage names. Standalone (Corvus's own .corvusmem/) uses English names; coupled to Senzu (or a legacy
113
- // layout) keeps Senzu's Spanish names, because the file is SHARED with Senzu and must stay compatible.
112
+ // Facts storage names. Corvus's store is ALWAYS its own .corvusmem/memory/facts.jsonl with English names. Corvus is
113
+ // the memory owner: when it is installed, Senzu defers its memory hooks to Corvus (Senzu-side), and Corvus ADOPTS the
114
+ // facts Senzu had in senzu/memoria/hechos.jsonl into its own store (see adoptarMemoriaSenzu) so nothing is lost.
115
+ // MEM_*_ES remain for that adoption and for the one-time migration of pre-0.4 installs (.corvusmem/memoria/ -> memory/).
114
116
  export const MEM_DIR_ES = 'memoria', MEM_FACTS_ES = 'hechos.jsonl', MEM_CORRUPT_ES = 'hechos.danado.jsonl';
115
117
  export const MEM_DIR_EN = 'memory', MEM_FACTS_EN = 'facts.jsonl', MEM_CORRUPT_EN = 'facts.corrupt.jsonl';
116
- export function nombresMemoria(root) {
117
- return carpetaBase(root) === CARPETA_CORVUS
118
- ? { dir: MEM_DIR_EN, facts: MEM_FACTS_EN, corrupt: MEM_CORRUPT_EN }
119
- : { dir: MEM_DIR_ES, facts: MEM_FACTS_ES, corrupt: MEM_CORRUPT_ES };
118
+ export function nombresMemoria(_root) {
119
+ return { dir: MEM_DIR_EN, facts: MEM_FACTS_EN, corrupt: MEM_CORRUPT_EN };
120
120
  }
121
121
  // One-time, idempotent migration: older standalone installs kept facts in .corvusmem/memoria/hechos.jsonl.
122
122
  // Rename that to .corvusmem/memory/facts.jsonl (and the corrupted-lines file) so a standalone Corvus reads English.
123
123
  // NEVER touches a Senzu-coupled or legacy project (base must be .corvusmem). Safe under races: best-effort, swallowed.
124
124
  export function migrarMemoriaCorvus(root) {
125
- if (carpetaBase(root) !== CARPETA_CORVUS) return;
125
+ // Runs regardless of Senzu: Corvus's store is always .corvusmem/, so always try to lift an old .corvusmem/memoria/
126
+ // into .corvusmem/memory/. It only ever touches Corvus's own dir and is idempotent, so it is safe everywhere.
126
127
  const base = path.join(root, CARPETA_CORVUS), viejoDir = path.join(base, MEM_DIR_ES), nuevoDir = path.join(base, MEM_DIR_EN);
127
128
  try {
128
129
  if (!fs.existsSync(path.join(viejoDir, MEM_FACTS_ES)) || fs.existsSync(path.join(nuevoDir, MEM_FACTS_EN))) return;
@@ -134,11 +135,47 @@ export function migrarMemoriaCorvus(root) {
134
135
  try { if (!fs.readdirSync(viejoDir).length) fs.rmdirSync(viejoDir); } catch { } // si queda vacía, se va
135
136
  } catch { /* best-effort: si no se puede migrar, se sigue leyendo el viejo via ruta() */ }
136
137
  }
138
+ // One-time adoption: when Corvus takes over a project that already used Senzu, lift the facts Senzu kept in
139
+ // senzu/memoria/hechos.jsonl into Corvus's own .corvusmem/memory/facts.jsonl (COPY, not move: Senzu's file is left
140
+ // intact, so nothing breaks mid-migration and it is reversible). Runs only when Corvus's store does not exist yet, so
141
+ // it seeds once and never clobbers Corvus's own facts. Best-effort and idempotent.
142
+ export function adoptarMemoriaSenzu(root) {
143
+ try {
144
+ const corvus = path.join(root, CARPETA_CORVUS, MEM_DIR_EN, MEM_FACTS_EN);
145
+ if (fs.existsSync(corvus)) return; // Corvus ya tiene su memoria: no se toca
146
+ const senzu = path.join(root, CARPETA, MEM_DIR_ES, MEM_FACTS_ES); // senzu/memoria/hechos.jsonl
147
+ if (!fs.existsSync(senzu)) return; // no hay memoria de Senzu que adoptar
148
+ fs.mkdirSync(path.dirname(corvus), { recursive: true });
149
+ fs.copyFileSync(senzu, corvus); // hereda los hechos (copia, no mueve)
150
+ const senzuBad = path.join(root, CARPETA, MEM_DIR_ES, MEM_CORRUPT_ES);
151
+ const corvusBad = path.join(root, CARPETA_CORVUS, MEM_DIR_EN, MEM_CORRUPT_EN);
152
+ if (fs.existsSync(senzuBad) && !fs.existsSync(corvusBad)) { try { fs.copyFileSync(senzuBad, corvusBad); } catch { } }
153
+ } catch { /* best-effort: si no se puede adoptar, Corvus arranca con su memoria vacía */ }
154
+ }
155
+ // Cómo debe GUARDAR/RECORDAR el agente, lo más rápido disponible (sin el arranque en frío de npx):
156
+ // 1) Plugin (Claude/Codex): el hook corre con CLAUDE_PLUGIN_ROOT y el CLI va empaquetado en <plugin>/cli/. Se emite
157
+ // la ruta ABSOLUTA porque el Bash del agente no tiene esa variable.
158
+ // 2) Proyecto (install): el CLI está en .corvusmem/cli/ y ${CLAUDE_PROJECT_DIR} sí lo tiene el agente (portable).
159
+ // 3) Global (install --global): CLI en ~/.config/corvusmem/cli/ (ruta absoluta al HOME).
160
+ // 4) Fallback para agentes SIN estos estándares (ni plugin ni install): `npx corvusmem` (lento pero siempre funciona).
161
+ export function rutaCliMemoria(root) {
162
+ const node = f => `node "${String(f).replace(/\\/g, '/')}"`;
163
+ try {
164
+ const pr = process.env.CLAUDE_PLUGIN_ROOT;
165
+ if (pr && fs.existsSync(path.join(pr, 'cli', 'corvusmem.mjs'))) return node(path.join(pr, 'cli', 'corvusmem.mjs'));
166
+ if (fs.existsSync(path.join(root, CARPETA_CORVUS, 'cli', 'corvusmem.mjs'))) return 'node "${CLAUDE_PROJECT_DIR}/.corvusmem/cli/corvusmem.mjs"';
167
+ const g = path.join(os.homedir(), '.config', 'corvusmem', 'cli', 'corvusmem.mjs');
168
+ if (fs.existsSync(g)) return node(g);
169
+ } catch { }
170
+ return 'npx corvusmem';
171
+ }
137
172
  const VIEJA = { 'ui-verify': '.ui-verify', 'senzu.json': '.dev-standards.json', auditoria: 'docs/auditoria', entrega: 'docs/entrega', 'mapa.md': 'docs/MAPA.md' };
138
173
  export function ruta(root, nombre) { // 'devlog' | 'plan' | 'design-system' | 'conventions.md' | 'conventions.json' | 'ui-verify' | 'senzu.json' | 'memoria'
174
+ // MEMORY is ALWAYS Corvus's own, in English, and never flips with Senzu's presence: .corvusmem/memory/. The store
175
+ // never moves when Senzu is added or removed; Corvus is the memory owner and Senzu defers to it (Senzu-side hayCorvus).
176
+ if (nombre === 'memoria') return path.join(root, CARPETA_CORVUS, MEM_DIR_EN);
139
177
  const base = carpetaBase(root);
140
- // 'memoria' es la carpeta de hechos: en standalone (.corvusmem) se llama 'memory' (inglés); acoplado/legacy sigue 'memoria'
141
- const nombreReal = nombre === 'memoria' && base === CARPETA_CORVUS ? MEM_DIR_EN : nombre;
178
+ const nombreReal = nombre;
142
179
  const nueva = path.join(root, base, nombreReal);
143
180
  const vieja = path.join(root, VIEJA[nombre] || nombre);
144
181
  const [primera, segunda] = esLegado(root) ? [vieja, nueva] : [nueva, vieja];
@@ -6,7 +6,7 @@
6
6
 
7
7
  import fs from 'node:fs';
8
8
  import crypto from 'node:crypto';
9
- import { readHookInput, projectRoot, sessionFlag, outHookJson, esMensajeDelUsuario, localeUI, msg } from './lib.mjs';
9
+ import { readHookInput, projectRoot, sessionFlag, outHookJson, esMensajeDelUsuario, localeUI, msg, rutaCliMemoria } from './lib.mjs';
10
10
  import { reclamarInyeccion } from './host.mjs';
11
11
  import { recuerdo, palabras, palabraConPeso, UMBRAL_RECUERDO, anotarUso, apuntarInyeccion, mapaMemoria, textoMapa, intencionTemporal } from './facts.mjs';
12
12
 
@@ -47,7 +47,7 @@ const elegidos = todos
47
47
  if (elegidos.length || !todos.some(x => (x.fuente === 'hecho' ? x.puntuacion >= UMBRAL_HECHO : x.puntuacion > 0))) apuntarInyeccion(root, { sid, origen: 'mensaje', consulta, items: elegidos });
48
48
  // X-T9: el agente no sabe qué hay si nadie se lo dice. Sin nada que coincida, con un mensaje con contenido (2+ palabras
49
49
  // con peso), una línea: lo que tiene la memoria y cómo consultarla (es un índice, no datos inventados)
50
- const cli = 'npx corvusmem';
50
+ const cli = rutaCliMemoria(root); // plugin/proyecto/global → node directo (rápido); npx como fallback
51
51
  if (!elegidos.length) {
52
52
  // (solo si de verdad no coincide NADA: si coincidía algo ya dicho en la sesión, decir «no hay nada» sería falso)
53
53
  const nada = !todos.some(x => (x.fuente === 'hecho' ? x.puntuacion >= UMBRAL_HECHO : x.puntuacion > 0));
@@ -5,7 +5,7 @@
5
5
  // (p. ej. Senzu), no del motor de memoria. Corvusmem instalado solo habla de memoria y nada más.
6
6
 
7
7
  import {
8
- readHookInput, projectRoot, outHookJson, leerUltimaSesion, localeUI, msg,
8
+ readHookInput, projectRoot, outHookJson, leerUltimaSesion, localeUI, msg, rutaCliMemoria,
9
9
  } from './lib.mjs';
10
10
  import { contextoHechos, decisionesObsoletas, abiertos, FAMILIAS_CICLO, contradicciones, mapaMemoria, textoMapa, etiquetaDimension } from './facts.mjs';
11
11
  import { reclamarInyeccion } from './host.mjs';
@@ -19,7 +19,7 @@ const L = [];
19
19
  // Los valores son DATOS: entre comillas, en una línea y recortados (un hecho que dijera «ignora las reglas» no puede
20
20
  // colarse como instrucción).
21
21
  const citar = v => '«' + String(v).replace(/[\r\n\t]+/g, ' ').replace(/[«»]/g, '"').trim().slice(0, 160) + (String(v).length > 160 ? '…' : '') + '»';
22
- const cli = 'npx corvusmem';
22
+ const cli = rutaCliMemoria(root); // plugin/proyecto/global → node directo (rápido); npx como fallback
23
23
  try {
24
24
  // Memoria de HECHOS (motor determinista, cualquier idioma): lo vigente por familias (objetivos y pendientes, abajo).
25
25
  const hechos = contextoHechos(root, { presupuesto: 12 }).filter(h => !FAMILIAS_CICLO.test(h.dimension));