corvusmem 0.5.2 → 0.6.1
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 +95 -1
- package/README.md +20 -0
- package/assets/icon.png +0 -0
- package/cli/import.mjs +8 -1
- package/cli/memory.mjs +29 -1
- package/commands/corvus-absorb.md +9 -6
- package/commands/corvus-cortex.md +3 -1
- package/cortex/cortex-text.mjs +8 -6
- package/cortex/cortex.mjs +62 -16
- package/install.mjs +8 -3
- package/package.json +6 -3
- package/src/extractor.mjs +71 -0
- package/src/facts-guard.mjs +5 -5
- package/src/facts.mjs +84 -1
- package/src/lib.mjs +3 -0
- package/src/live-memory.mjs +104 -30
- package/src/live-recall.mjs +6 -2
- package/src/messages.mjs +6 -0
- package/src/session-start.mjs +1 -0
- package/src/session-state.mjs +30 -12
package/CHANGELOG.md
CHANGED
|
@@ -4,14 +4,108 @@ 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
|
+
### Fixed
|
|
8
|
+
- **`/corvus-absorb` works on a WSL project.** The command hard-coded `npx corvusmem import`, and a Windows `npx`
|
|
9
|
+
cannot reach a WSL path (`\\wsl$\…`, no UNC support), so the agent's absorb failed across the boundary. It now uses
|
|
10
|
+
the installed local CLI (`node "<…>/cli/corvusmem.mjs"`) like `/corvus-cortex` and `/corvus-install`, with `npx` only
|
|
11
|
+
as the fallback. README and docs gained a WSL note (run Claude Code and Corvus on the Linux side) and the **Node ≥18**
|
|
12
|
+
requirement is now explicit.
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
- **The Cortex is dark-only, opens in 3D, and pops the browser.** Removed the light-mode toggle (the standalone Cortex
|
|
16
|
+
is always dark; the web-embedded brain still follows the page theme so it is not a black box on a light page); the
|
|
17
|
+
view now starts in **3D** by default (2D still a click away); and `/corvus-cortex` now opens the generated HTML in the
|
|
18
|
+
browser immediately instead of only printing its path.
|
|
7
19
|
|
|
8
|
-
## [0.
|
|
20
|
+
## [0.6.0] — 2026-11-18
|
|
21
|
+
### Added
|
|
22
|
+
- **Head-to-head benchmark vs paid memory products (`tools/eval-productos/`).** Corvusmem's memory engine measured
|
|
23
|
+
against **mem0** and **Zep/Graphiti** on the academic **LoCoMo** benchmark (1986 questions), under identical
|
|
24
|
+
conditions (same local Qwen3 answerer + judge; only the memory differs). Corvusmem **beats mem0 globally**
|
|
25
|
+
(25.6 % vs 21.1 %) and **nearly triples it on temporal** questions (16.2 % vs 5.3 %). And in its **native,
|
|
26
|
+
LLM-free mode** — indexing the raw turns, which is how the product actually works — Corvusmem reaches
|
|
27
|
+
**34.8 % global, the highest of every column measured**, above the free embedding baseline with LLM ingestion
|
|
28
|
+
(28.0 %) and its own LLM-ingestion variant (25.6 %): its retrieval pulls the answer-bearing turn **2–4× more
|
|
29
|
+
often** than a semantic embedding, deterministically and offline. Honest caveat documented: local Qwen3, not
|
|
30
|
+
GPT-4o, so not comparable to their official leaderboards; and with LLM-cleaned facts the embedding still wins
|
|
31
|
+
two single categories (cat1, cat3). Raw results + `comparar.mjs` reproduce the tables offline (`BENCHMARK.md`).
|
|
32
|
+
Dev tooling — not shipped in the npm package.
|
|
33
|
+
- **`corvusmem --health` and a reliability panel in the Cortex.** One source (`datosSalud`) answers "is the memory
|
|
34
|
+
working?": active facts (and by family), open goals/todos, real-world use (injected vs used, real precision from your
|
|
35
|
+
own sessions), the deterministic battery result (`hit@5`, abstention, dedup, ms — shown only where the dev eval
|
|
36
|
+
exists), and what the last session saved or skipped. The Cortex shows the same as a panel that reads without
|
|
37
|
+
JavaScript; private rows (real use, last session) are owner-only and never travel to the client view or its JSON.
|
|
38
|
+
- **Fact-shaped nudges while you work (high precision).** Beyond rules/corrections, the live hook now spots statements
|
|
39
|
+
that carry a reusable datum — a tool in use (`we use X`), a figure with a currency (`charges 600 €`), a location
|
|
40
|
+
(`vivo en Madrid`), an office/API named — and nudges the agent to save it, then leaves a non-blocking reminder at
|
|
41
|
+
close if nothing was saved. A **question is never treated as a fact**, so `which package manager do we use` or
|
|
42
|
+
`cuánto paga…` stay silent: 0 false positives across the whole adversarial battery. The detector is pure and tested
|
|
43
|
+
(`tests/test-hecho-detector.mjs`, 34/0); the close nudge only ever emits `systemMessage`, never blocks.
|
|
44
|
+
- **Deterministic fact extractor — the agent no longer has to invent the key.** When you state a fact-shaped
|
|
45
|
+
sentence, the live hook now **distills the save command itself** (`--dimension … --valor … --claves …`, already
|
|
46
|
+
canonical) and offers it for the agent to review, instead of leaving the agent to pick the key (the cause of saves
|
|
47
|
+
landing under the wrong dimension/store). Pure and canonical (`dimensionConvencional`/`clavesConvencionales`), tested
|
|
48
|
+
(`tests/test-extractor.mjs` 83/0; integration `tests/test-extractor-integracion.mjs` 12/0 proving extract → store →
|
|
49
|
+
recall and chronological substitution). De-risked on LongMemEval knowledge-update (n=21): the compressed fact régimen
|
|
50
|
+
beats raw turns on **both recall@5 and abstention**.
|
|
51
|
+
|
|
52
|
+
### Improved
|
|
53
|
+
- **Less noise from the project diary (higher real-world precision).** Live recall now gives diary/decision hits an
|
|
54
|
+
**absolute floor** (`0.25–0.35 × the diary's own score scale`, auto-calibrated from your usage history and scaled by
|
|
55
|
+
confidence) on top of the relative threshold. The diary was ~70 % of injected noise — injected on weak overlap
|
|
56
|
+
because it only had to be "best of its source"; facts and standing preferences are untouched, and projects without
|
|
57
|
+
enough history get no floor (behavior unchanged). Measured on real usage logs: injection precision **23.7 % →
|
|
58
|
+
28.8 %** (new `npm run bench:precision`), ~6 noisy injections cut per useful one lost, with the battery's
|
|
59
|
+
**abstention held at 100 %**.
|
|
60
|
+
- **Clearer bar for what to save (less agent variance).** The save prompt is now one concrete, positive checklist
|
|
61
|
+
(`save.criterios`) — decision made, limit/constraint found, stable preference, external fact with a name/figure,
|
|
62
|
+
a gotcha and its cause, a goal/pending — with the test "would you need it next time and it's not in the code?".
|
|
63
|
+
The same bar is shown at session start and at the close nudge (it replaced the vague "did the user say anything
|
|
64
|
+
stable?" that invited a "no"), so different agents converge on saving the same things.
|
|
65
|
+
- **Recall understands more paraphrases, deterministically.** The concept lexicon that already powers cross-language
|
|
66
|
+
recall gained the missing concepts (`indentation`, `office`, `deploy`, `fee/charge`), so a query phrased differently
|
|
67
|
+
from the stored fact (`sangrar`≈indent, `publicar`≈deploy, `sede`≈office, `charge`≈cobra) now finds it — no
|
|
68
|
+
embeddings, no network. On the adversarial battery: injected hit@5 **63.6 % → 90.9 %** with **abstention held at
|
|
69
|
+
100 %** (never recall more by inventing more). The one query that still misses is one the engine *should* decline —
|
|
70
|
+
it names something memory never heard (`API`), so it stays silent on purpose ("knows what it doesn't know"); the
|
|
71
|
+
battery now tracks that as an abstention check, not a recall miss.
|
|
72
|
+
### Added
|
|
73
|
+
- **The memory battery is now a CI gate.** `npm test` runs `eval-memoria --gate`, which fails the build if recall or
|
|
74
|
+
honesty regress: injected hit@5 must stay ≥ 90 %, abstention must stay 100 %, near-duplicate guard 100 %, and the
|
|
75
|
+
battery can't be gutted (a minimum case count). The reliability work can't silently rot.
|
|
76
|
+
- **Memory reliability battery (`tools/eval-memoria/`).** A deterministic, LLM-free adversarial eval of the recall
|
|
77
|
+
engine — paraphrase, synonyms, cross-language, temporal and trap queries — that reports **hit@5**, **injected hit@5**
|
|
78
|
+
(≥ threshold), **abstention precision**, **near-duplicate guard** and **ms/query**, and writes `resultados.json`.
|
|
79
|
+
This is the baseline and, later, the regression gate for the F15 "reliable memory" work. First baseline
|
|
80
|
+
(2026-11-09): hit@5 81.8 % · injected 63.6 % · abstention 100 % · dedup 100 % · ~2 ms/query.
|
|
81
|
+
|
|
82
|
+
### Fixed
|
|
83
|
+
- **The plugin test is now isolated from a globally-installed Corvusmem.** `test-plugin`'s "no install → npx
|
|
84
|
+
fallback" check read the real `~/.config/corvusmem`, so it failed on a machine that has Corvusmem installed
|
|
85
|
+
globally — which also blocked `npm version`/`npm publish`, since both run `test:core`. It now points `HOME` at
|
|
86
|
+
an empty temp dir for that one assertion. `test:core` is green end to end.
|
|
87
|
+
|
|
88
|
+
## [0.5.3] — 2026-11-09
|
|
89
|
+
### Added
|
|
90
|
+
- **Ready for the Anthropic plugin directory.** The generated plugin now ships a square listing **icon**
|
|
91
|
+
(`.claude-plugin/icon.png` — the crow on a dark background), a `displayName`, and a plain `https://` `repository`
|
|
92
|
+
URL (the directory drops `git+…`/`.git`). `claude plugin validate --strict ./plugins/corvusmem` now passes clean,
|
|
93
|
+
so Corvusmem can be submitted to the directory at claude.ai/directory/manage (the git marketplace still works as-is).
|
|
9
94
|
### Added
|
|
10
95
|
- **`/corvus-install` — bake Corvusmem into a project, as a command.** A new slash command (bundled in the plugin and
|
|
11
96
|
in `.claude/commands/`) installs the hooks into the **current** project so it carries its own memory. Commit
|
|
12
97
|
`.corvusmem/` and `.claude/settings.json` and a teammate who receives the project gets Corvus firing in Claude Code
|
|
13
98
|
or Codex **with nothing to install**. `install.mjs` now ships inside the plugin and runs from it (the core is resolved
|
|
14
99
|
from `hooks/` when there is no `src/`), so the command works natively — `npx corvusmem install` stays as the fallback.
|
|
100
|
+
- **Collapsible Cortex side panel.** The Cortex's right panel now has a header and a collapse button; hide it and the
|
|
101
|
+
brain fills the width, with a floating button to bring it back (remembered per viewer). The panel also got a lighter
|
|
102
|
+
touch: a search icon, section dividers and a cleaner header.
|
|
103
|
+
### Fixed
|
|
104
|
+
- **`corvusmem import` ran only from the repo, not the plugin** — `cli/import.mjs` imported the engine from `../src/`,
|
|
105
|
+
which does not exist inside the plugin (the core is in `hooks/`), so `/corvus-absorb` crashed when Corvus was
|
|
106
|
+
installed as a plugin. It now resolves the engine from `src/` or `hooks/`, whichever is present.
|
|
107
|
+
- **The Cortex was written to a loose `cortex/` folder at the project root.** It now always renders inside
|
|
108
|
+
`.corvusmem/cortex/`, next to the memory it draws — never a stray folder in the root (or in `senzu/`).
|
|
15
109
|
|
|
16
110
|
## [0.5.1] — 2026-11-08
|
|
17
111
|
### Changed
|
package/README.md
CHANGED
|
@@ -37,6 +37,22 @@ Your agent forgets everything between sessions. Corvusmem is a memory it keeps:
|
|
|
37
37
|
graph, retrieved by name, date and relevance with two-hop activation — no embeddings, no vector database, no API key.
|
|
38
38
|
Same input, same result. The whole memory is a file you own.
|
|
39
39
|
|
|
40
|
+
## Benchmarks
|
|
41
|
+
On **LoCoMo** — the academic long-conversation benchmark (1986 questions) — measured against the paid memory products
|
|
42
|
+
**mem0** and **Zep/Graphiti** under identical conditions (same local Qwen3 answerer and judge; only the memory differs):
|
|
43
|
+
|
|
44
|
+
- In its **native, LLM-free mode** — indexing the raw turns, which is how the product actually works — Corvusmem scores
|
|
45
|
+
**34.8 % end-to-end, the highest of every configuration measured**: above mem0 (21.1 %) and above a free embedding
|
|
46
|
+
baseline (28.0 %), while being deterministic, offline and $0.
|
|
47
|
+
- Its retrieval pulls the answer-bearing turn **2–4× more often** than a semantic embedding, in every category.
|
|
48
|
+
- **Honest caveat:** this runs on a local Qwen3, not GPT-4o, so the absolute numbers are **not** comparable to their
|
|
49
|
+
official GPT-4o leaderboards; and with LLM-cleaned facts the embedding still wins two single categories. It is a
|
|
50
|
+
controlled, reproducible head-to-head between memories, not a leaderboard claim.
|
|
51
|
+
|
|
52
|
+
Full tables, raw results and a one-command reproduction:
|
|
53
|
+
[`BENCHMARK.md`](https://github.com/petersonsenadevs/corvusmem/blob/main/tools/eval-productos/BENCHMARK.md) ·
|
|
54
|
+
[benchmarks on the site](https://corvusmem.vercel.app/benchmarks).
|
|
55
|
+
|
|
40
56
|
## Structure
|
|
41
57
|
- `src/` — the core: the facts engine (`facts.mjs`), shared base (`lib`, `messages`, `session-end`), host detection
|
|
42
58
|
(`host.mjs`) and the brain hooks (`live-recall`, `session-start`, `session-state`, `live-memory`,
|
|
@@ -84,6 +100,10 @@ project (`--global`, in your home). It does **not** change where memory lives: p
|
|
|
84
100
|
project, then commit `.corvusmem/` (the shared project memory) and `.claude/settings.json` — teammates get Corvus firing
|
|
85
101
|
the moment they clone, with nothing to install. Never commit `~/.config/corvusmem/` — that is your private memory.
|
|
86
102
|
|
|
103
|
+
**On WSL**: if your project lives in WSL (`\\wsl$\…`), run **Claude Code and Corvus from inside WSL** so Node and
|
|
104
|
+
`npx` are Linux-native. A Windows `npx` cannot reach a `\\wsl$\…` path (no UNC support), which is what breaks
|
|
105
|
+
`npx corvusmem …` across the boundary; running on the Linux side — where the path is a normal `/home/…` — just works.
|
|
106
|
+
|
|
87
107
|
## Usage
|
|
88
108
|
Once installed, the agent captures and recalls memory on its own — you don't do a thing. Two slash commands come with
|
|
89
109
|
it (native — no `npx`):
|
package/assets/icon.png
ADDED
|
Binary file
|
package/cli/import.mjs
CHANGED
|
@@ -3,7 +3,14 @@
|
|
|
3
3
|
// `corvusmem import` — list the memory documents already in this project, in two tiers, so the agent
|
|
4
4
|
// (via /corvus-absorb) can read them and save what matters. Deterministic, offline, READ-ONLY: it writes
|
|
5
5
|
// nothing to memory. `--json` prints the machine-readable contract the command consumes.
|
|
6
|
-
import
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
9
|
+
// El motor vive en ../src (repo) o ../hooks (dentro del plugin): resuelve el que exista, así `corvusmem import`
|
|
10
|
+
// (y /corvus-absorb) funciona también instalado como plugin, no solo desde el repo.
|
|
11
|
+
const AQUI = path.dirname(fileURLToPath(import.meta.url));
|
|
12
|
+
const motor = [path.join(AQUI, '..', 'src', 'import.mjs'), path.join(AQUI, '..', 'hooks', 'import.mjs')].find(f => fs.existsSync(f));
|
|
13
|
+
const { escanearMemoria } = await import(pathToFileURL(motor).href);
|
|
7
14
|
|
|
8
15
|
const argv = process.argv.slice(2);
|
|
9
16
|
const json = argv.includes('--json');
|
package/cli/memory.mjs
CHANGED
|
@@ -32,6 +32,7 @@ const ALIAS_FLAG = {
|
|
|
32
32
|
'--limit': '--limite', '--budget': '--presupuesto', '--reason': '--motivo', '--link': '--enlazar',
|
|
33
33
|
'--links': '--enlaces', '--client': '--cliente', '--text': '--texto', '--report': '--informe',
|
|
34
34
|
'--output': '--salida', '--all': '--todo', '--none': '--nada', '--as': '--como', '--author': '--autor',
|
|
35
|
+
'--health': '--salud',
|
|
35
36
|
};
|
|
36
37
|
const ALIAS_VAL = { user: 'usuario', project: 'proyecto', agent: 'agente' }; // valores de enum en inglés
|
|
37
38
|
for (let i = 0; i < args.length; i++) if (ALIAS_FLAG[args[i]]) args[i] = ALIAS_FLAG[args[i]];
|
|
@@ -181,5 +182,32 @@ if (opt('--cortex')) { // Cortex: la memoria en un HTML local, sin red; --clie
|
|
|
181
182
|
if (!cliente) out(' Tiene datos privados: para enseñarlo, genera la vista para el cliente con --cortex --cliente.');
|
|
182
183
|
process.exit(0);
|
|
183
184
|
}
|
|
184
|
-
|
|
185
|
+
if (opt('--salud')) { // F15-T8: la salud de la memoria en números (hechos, uso real, batería, última sesión)
|
|
186
|
+
if (!m.datosSalud) { out('Este Corvus no trae --health todavía: actualízalo.'); process.exit(2); }
|
|
187
|
+
const s = m.datosSalud(root, { dias: Number(opt('--dias')) || 30 });
|
|
188
|
+
if (opt('--json')) { out(JSON.stringify(s, null, 2)); process.exit(0); }
|
|
189
|
+
out(`Corvusmem · salud de la memoria (${root})`);
|
|
190
|
+
const fam = Object.entries(s.hechos.porFamilia).sort((a, b) => b[1] - a[1]).map(([k, v]) => `${k} ${v}`).join(' · ');
|
|
191
|
+
out('\nHechos');
|
|
192
|
+
out(` ${s.hechos.activos} activos${s.hechos.dudosos ? ` · ${s.hechos.dudosos} dudosos` : ''} · ${s.hechos.historico} en histórico · ${s.hechos.abiertos} objetivos/pendientes abiertos`);
|
|
193
|
+
if (fam) out(` por familia: ${fam}`);
|
|
194
|
+
if (s.pistasSaturadas && s.pistasSaturadas.length) { // F17-T4: efecto fan — pistas con muchos hechos (interferencia)
|
|
195
|
+
out('\nPistas saturadas (efecto fan: concreta la consulta)');
|
|
196
|
+
for (const p of s.pistasSaturadas) out(` «${p.dimension}» · ${p.hechos} hechos · interferencia ${p.interferencia}`);
|
|
197
|
+
}
|
|
198
|
+
out(`\nUso real (últimos ${s.uso ? s.uso.dias : 30} días)`);
|
|
199
|
+
if (s.uso) out(` ${s.uso.mensajes} mensajes · ${s.uso.inyectados} recuerdos inyectados · ${s.uso.usados} usados · ${s.uso.ignorados} ignorados`
|
|
200
|
+
+ (s.uso.precision != null ? ` · precisión real ${s.uso.precision} %` : ''));
|
|
201
|
+
else out(' sin registro todavía: se llena solo al hablar con el agente.');
|
|
202
|
+
out('\nBatería (eval determinista)');
|
|
203
|
+
if (s.bateria) out(` hit@5 inyectado ${s.bateria.hit5} % · abstención ${s.bateria.abstencion} % · duplicados ${s.bateria.duplicados} % · ${s.bateria.ms} ms/consulta (${s.bateria.consultas} consultas, ${s.bateria.fecha})`);
|
|
204
|
+
else out(' no disponible en una instalación (es una herramienta de desarrollo del repo).');
|
|
205
|
+
out('\nÚltima sesión');
|
|
206
|
+
if (s.ultimaSesion && s.ultimaSesion.fecha) {
|
|
207
|
+
if (s.ultimaSesion.guardo) out(` ${s.ultimaSesion.fecha} · guardó ${s.ultimaSesion.guardo} hecho(s): ${s.ultimaSesion.hechos.map(h => `[${h.dimension}]`).join(' ')}`);
|
|
208
|
+
else out(` ${s.ultimaSesion.fecha} · no guardó nada${s.ultimaSesion.archivos ? ` (tocó ${s.ultimaSesion.archivos} archivos)` : ''}`);
|
|
209
|
+
} else out(' sin datos de sesión todavía.');
|
|
210
|
+
process.exit(0);
|
|
211
|
+
}
|
|
212
|
+
out('Usage: --save --dimension <family.topic> --value <text> [--keys a,b] [--scope user] [--doubt] | --search <query> [--history] | --context | --list [--all] | --health | --forget <id> | --cortex [--client] [--output <dir>]');
|
|
185
213
|
process.exit(2);
|
|
@@ -7,11 +7,14 @@ You are absorbing this project's **existing** knowledge into Corvus. The goal is
|
|
|
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
|
|
|
9
9
|
## 1. Find the documents (deterministic — let the tool do this)
|
|
10
|
-
|
|
10
|
+
Use the memory CLI's `import`, with the **fastest local path available** — do **not** default to `npx` (it is only the fallback for an agent with nothing installed, and a Windows `npx` cannot reach a WSL project at `\\wsl$\…` because it does not support UNC paths). Use the first that applies:
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
12
|
+
- **Plugin** (`CLAUDE_PLUGIN_ROOT` set): `node "$CLAUDE_PLUGIN_ROOT/cli/corvusmem.mjs" import --json`
|
|
13
|
+
- **Per-project** (`.corvusmem/cli/corvusmem.mjs` exists): `node "$CLAUDE_PROJECT_DIR/.corvusmem/cli/corvusmem.mjs" import --json`
|
|
14
|
+
- **Global** (`~/.config/corvusmem/cli/corvusmem.mjs` exists): `node "<that path>" import --json`
|
|
15
|
+
- **Nothing installed** (fallback only): `npx corvusmem import --json`
|
|
16
|
+
|
|
17
|
+
> **WSL:** if the project lives in WSL, run Claude Code (and Corvus) **inside WSL** so Node is Linux-native — mixing a Windows agent with a `\\wsl$\…` path is exactly what breaks `npx`.
|
|
15
18
|
|
|
16
19
|
It returns the memory documents already in the repo in two tiers (`{ agent, docs, truncated, files: [{ tier, kind, rel, lines }] }`):
|
|
17
20
|
|
|
@@ -37,10 +40,10 @@ Keep every piece of **durable memory** — what should still be true next week:
|
|
|
37
40
|
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
41
|
|
|
39
42
|
## 3. Save each item (deterministic sink)
|
|
40
|
-
For every item worth keeping, run one command:
|
|
43
|
+
For every item worth keeping, run one command — the **same local CLI as step 1** (`node "<…>/cli/corvusmem.mjs"`), with `npx corvusmem` only as the fallback:
|
|
41
44
|
|
|
42
45
|
```
|
|
43
|
-
|
|
46
|
+
node "<corvusmem cli>" --save --dimension <family.topic> --value "<self-contained statement>" --keys "<term-en>,<term-native>" --source agente
|
|
44
47
|
```
|
|
45
48
|
|
|
46
49
|
- `family` is one of: `identity`, `preference`, `project`, `goal`, `pending`, `constraint`, `note`, `fact`, `learning`, `link`.
|
|
@@ -11,4 +11,6 @@ Run it with the **fastest local path available** — do not default to `npx` (th
|
|
|
11
11
|
- **Global install** (`~/.config/corvusmem/cli/corvusmem.mjs` exists): `node "<that path>" --cortex`
|
|
12
12
|
- **Nothing installed** (fallback only): `npx corvusmem --cortex`
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
The command writes a local HTML file and prints its path. **Open it in the user's browser right away** — don't just hand them the path. Use your browser tool to navigate to the `file://` path if you have one, otherwise the OS opener: `start "" "<path>"` on Windows, `open "<path>"` on macOS, `xdg-open "<path>"` (or `wslview "<path>"` on WSL) on Linux. Then tell the user it is open and give the path too, in case they want to reopen it.
|
|
15
|
+
|
|
16
|
+
Pick the user's language for anything you say. Add `--cliente` for a client-facing view, or `--idioma en|es` to force the language. It renders only what is actually stored; never invent memory that is not there.
|
package/cortex/cortex-text.mjs
CHANGED
|
@@ -12,8 +12,9 @@ export const TEXTOS = {
|
|
|
12
12
|
vistaClienteT: 'Así lo verá el cliente: sin lo tuyo, lo deducido ni los comandos', claro: 'Claro', oscuro: 'Oscuro', idioma: 'Idioma', vista: 'Vista',
|
|
13
13
|
pista: 'Toca una zona para ver lo que guarda', pista3d: 'Arrástralo para girarlo en cualquier dirección · doble clic: de lado · cada destello es un recuerdo que se usa',
|
|
14
14
|
piensa: 'Ver cómo piensa', pararP: 'Parar', piensaT: 'Reproduce sus últimas consultas a la memoria, encendiendo cada zona que tocó', masUsa: 'Lo que más consulta ({d} días):', sinUso: 'Aún no hay uso registrado: brilla según lo que guarda cada zona.', nadaEncontro: 'no encontró nada', loUso: 'lo usó', noLoUso: 'no lo usó', paso: '{i} de {n}',
|
|
15
|
-
buscar: 'Pregunta a la memoria…', buscarL: 'Buscar en la memoria', semana: 'Esta semana', nadaSemana: 'Nada nuevo en los últimos 7 días.',
|
|
15
|
+
buscar: 'Pregunta a la memoria…', buscarL: 'Buscar en la memoria', panelTitulo: 'Memoria', panelOcultar: 'Ocultar panel', panelVer: 'Ver panel', semana: 'Esta semana', nadaSemana: 'Nada nuevo en los últimos 7 días.',
|
|
16
16
|
sigueAbierto: 'Sigue abierto', todo: 'Todo lo que recuerda', coincide: 'Lo que coincide',
|
|
17
|
+
salud: { t: 'Fiabilidad', hechos: 'Hechos', bateria: 'Batería (eval)', uso: 'Uso real', sesion: 'Última sesión' },
|
|
17
18
|
sinRes: 'Nada en la memoria para «{q}». Si no está aquí, la memoria no lo sabe.', zonaVacia: 'Aún no hay nada en esta zona.',
|
|
18
19
|
vacia: 'La memoria está vacía. Se llena sola cuando hablas con el agente.', verMas: 'Ver {n} más',
|
|
19
20
|
quien: 'Quién lo dijo', desde: 'Desde', usado: 'Usado', enDevlog: 'En el devlog', historia: 'Historia', relacionado: 'Relacionado', cambiar: 'Para cambiarlo:', cerrar: 'Cerrar el detalle',
|
|
@@ -36,8 +37,9 @@ export const TEXTOS = {
|
|
|
36
37
|
vistaClienteT: 'What the client will see: nothing of yours, nothing inferred, no commands', claro: 'Light', oscuro: 'Dark', idioma: 'Language', vista: 'View',
|
|
37
38
|
pista: 'Tap a zone to see what it holds', pista3d: 'Drag to turn it any way · double click: side view · each spark is a memory being used',
|
|
38
39
|
piensa: 'See how it thinks', pararP: 'Stop', piensaT: 'Replays its latest lookups in memory, lighting up each zone it touched', masUsa: 'What it looks up most ({d} days):', sinUso: 'No usage recorded yet: it glows by what each zone holds.', nadaEncontro: 'found nothing', loUso: 'used it', noLoUso: 'did not use it', paso: '{i} of {n}',
|
|
39
|
-
buscar: 'Ask the memory…', buscarL: 'Search the memory', semana: 'This week', nadaSemana: 'Nothing new in the last 7 days.',
|
|
40
|
+
buscar: 'Ask the memory…', buscarL: 'Search the memory', panelTitulo: 'Memory', panelOcultar: 'Hide panel', panelVer: 'Show panel', semana: 'This week', nadaSemana: 'Nothing new in the last 7 days.',
|
|
40
41
|
sigueAbierto: 'Still open', todo: 'Everything it remembers', coincide: 'Matches',
|
|
42
|
+
salud: { t: 'Reliability', hechos: 'Facts', bateria: 'Battery (eval)', uso: 'Real use', sesion: 'Last session' },
|
|
41
43
|
sinRes: 'Nothing in the memory for “{q}”. If it is not here, the memory does not know it.', zonaVacia: 'Nothing in this zone yet.',
|
|
42
44
|
vacia: 'The memory is empty. It fills up by itself as you talk to the agent.', verMas: 'Show {n} more',
|
|
43
45
|
quien: 'Who said it', desde: 'Since', usado: 'Used', enDevlog: 'In the devlog', historia: 'History', relacionado: 'Related', cambiar: 'To change it:', cerrar: 'Close details',
|
|
@@ -60,7 +62,7 @@ export const TEXTOS = {
|
|
|
60
62
|
vistaClienteT: 'O que o cliente verá: nada teu, nada deduzido, sem comandos', claro: 'Claro', oscuro: 'Escuro', idioma: 'Idioma', vista: 'Vista',
|
|
61
63
|
pista: 'Toca numa zona para ver o que guarda', pista3d: 'Arrasta para o rodar em qualquer direção · duplo clique: de lado · cada brilho é uma memória em uso',
|
|
62
64
|
piensa: 'Ver como pensa', pararP: 'Parar', piensaT: 'Reproduz as suas últimas consultas à memória, acendendo cada zona que tocou', masUsa: 'O que mais consulta ({d} dias):', sinUso: 'Ainda não há uso registado: brilha conforme o que cada zona guarda.', nadaEncontro: 'não encontrou nada', loUso: 'usou', noLoUso: 'não usou', paso: '{i} de {n}',
|
|
63
|
-
buscar: 'Pergunta à memória…', buscarL: 'Pesquisar na memória', semana: 'Esta semana', nadaSemana: 'Nada de novo nos últimos 7 dias.',
|
|
65
|
+
buscar: 'Pergunta à memória…', buscarL: 'Pesquisar na memória', panelTitulo: 'Memória', panelOcultar: 'Ocultar painel', panelVer: 'Ver painel', semana: 'Esta semana', nadaSemana: 'Nada de novo nos últimos 7 dias.',
|
|
64
66
|
sigueAbierto: 'Continua em aberto', todo: 'Tudo o que lembra', coincide: 'O que coincide',
|
|
65
67
|
sinRes: 'Nada na memória para «{q}». Se não está aqui, a memória não o sabe.', zonaVacia: 'Ainda não há nada nesta zona.',
|
|
66
68
|
vacia: 'A memória está vazia. Enche-se sozinha quando falas com o agente.', verMas: 'Ver mais {n}',
|
|
@@ -84,7 +86,7 @@ export const TEXTOS = {
|
|
|
84
86
|
vistaClienteT: 'Ce que verra le client : rien de toi, rien de déduit, aucune commande', claro: 'Clair', oscuro: 'Sombre', idioma: 'Langue', vista: 'Vue',
|
|
85
87
|
pista: 'Touche une zone pour voir ce qu’elle garde', pista3d: 'Fais-le glisser pour le tourner dans tous les sens · double clic : de profil · chaque éclat est un souvenir utilisé',
|
|
86
88
|
piensa: 'Voir comment il pense', pararP: 'Arrêter', piensaT: 'Rejoue ses dernières recherches dans la mémoire en allumant chaque zone touchée', masUsa: 'Ce qu’il consulte le plus ({d} jours) :', sinUso: 'Aucun usage enregistré pour l’instant : il brille selon ce que garde chaque zone.', nadaEncontro: 'n’a rien trouvé', loUso: 'l’a utilisé', noLoUso: 'ne l’a pas utilisé', paso: '{i} sur {n}',
|
|
87
|
-
buscar: 'Demande à la mémoire…', buscarL: 'Chercher dans la mémoire', semana: 'Cette semaine', nadaSemana: 'Rien de nouveau ces 7 derniers jours.',
|
|
89
|
+
buscar: 'Demande à la mémoire…', buscarL: 'Chercher dans la mémoire', panelTitulo: 'Mémoire', panelOcultar: 'Masquer le panneau', panelVer: 'Afficher le panneau', semana: 'Cette semaine', nadaSemana: 'Rien de nouveau ces 7 derniers jours.',
|
|
88
90
|
sigueAbierto: 'Toujours ouvert', todo: 'Tout ce dont elle se souvient', coincide: 'Ce qui correspond',
|
|
89
91
|
sinRes: 'Rien dans la mémoire pour « {q} ». Si ce n’est pas ici, la mémoire ne le sait pas.', zonaVacia: 'Rien dans cette zone pour l’instant.',
|
|
90
92
|
vacia: 'La mémoire est vide. Elle se remplit toute seule quand tu parles à l’agent.', verMas: 'Voir {n} de plus',
|
|
@@ -108,7 +110,7 @@ export const TEXTOS = {
|
|
|
108
110
|
vistaClienteT: 'So sieht es der Kunde: nichts von dir, nichts Abgeleitetes, keine Befehle', claro: 'Hell', oscuro: 'Dunkel', idioma: 'Sprache', vista: 'Ansicht',
|
|
109
111
|
pista: 'Tippe auf eine Zone, um zu sehen, was sie enthält', pista3d: 'Ziehen, um es in jede Richtung zu drehen · Doppelklick: Seitenansicht · jedes Aufblitzen ist eine genutzte Erinnerung',
|
|
110
112
|
piensa: 'Sehen, wie es denkt', pararP: 'Stopp', piensaT: 'Spielt die letzten Abfragen im Gedächtnis ab und lässt jede berührte Zone aufleuchten', masUsa: 'Am häufigsten abgefragt ({d} Tage):', sinUso: 'Noch keine Nutzung erfasst: Es leuchtet nach dem, was jede Zone enthält.', nadaEncontro: 'nichts gefunden', loUso: 'genutzt', noLoUso: 'nicht genutzt', paso: '{i} von {n}',
|
|
111
|
-
buscar: 'Frag das Gedächtnis…', buscarL: 'Im Gedächtnis suchen', semana: 'Diese Woche', nadaSemana: 'Nichts Neues in den letzten 7 Tagen.',
|
|
113
|
+
buscar: 'Frag das Gedächtnis…', buscarL: 'Im Gedächtnis suchen', panelTitulo: 'Gedächtnis', panelOcultar: 'Panel ausblenden', panelVer: 'Panel anzeigen', semana: 'Diese Woche', nadaSemana: 'Nichts Neues in den letzten 7 Tagen.',
|
|
112
114
|
sigueAbierto: 'Noch offen', todo: 'Alles, woran es sich erinnert', coincide: 'Treffer',
|
|
113
115
|
sinRes: 'Nichts im Gedächtnis zu „{q}“. Was hier nicht steht, weiß das Gedächtnis nicht.', zonaVacia: 'In dieser Zone ist noch nichts.',
|
|
114
116
|
vacia: 'Das Gedächtnis ist leer. Es füllt sich von selbst, wenn du mit dem Agenten sprichst.', verMas: '{n} weitere anzeigen',
|
|
@@ -132,7 +134,7 @@ export const TEXTOS = {
|
|
|
132
134
|
vistaClienteT: 'Ciò che vedrà il cliente: niente di tuo, niente di dedotto, nessun comando', claro: 'Chiaro', oscuro: 'Scuro', idioma: 'Lingua', vista: 'Vista',
|
|
133
135
|
pista: 'Tocca una zona per vedere cosa contiene', pista3d: 'Trascinalo per girarlo in ogni direzione · doppio clic: di lato · ogni scintilla è un ricordo usato',
|
|
134
136
|
piensa: 'Guarda come pensa', pararP: 'Ferma', piensaT: 'Riproduce le sue ultime consultazioni della memoria, accendendo ogni zona toccata', masUsa: 'Ciò che consulta di più ({d} giorni):', sinUso: 'Ancora nessun uso registrato: brilla in base a ciò che ogni zona contiene.', nadaEncontro: 'non ha trovato nulla', loUso: 'l’ha usato', noLoUso: 'non l’ha usato', paso: '{i} di {n}',
|
|
135
|
-
buscar: 'Chiedi alla memoria…', buscarL: 'Cerca nella memoria', semana: 'Questa settimana', nadaSemana: 'Niente di nuovo negli ultimi 7 giorni.',
|
|
137
|
+
buscar: 'Chiedi alla memoria…', buscarL: 'Cerca nella memoria', panelTitulo: 'Memoria', panelOcultar: 'Nascondi pannello', panelVer: 'Mostra pannello', semana: 'Questa settimana', nadaSemana: 'Niente di nuovo negli ultimi 7 giorni.',
|
|
136
138
|
sigueAbierto: 'Ancora aperto', todo: 'Tutto ciò che ricorda', coincide: 'Risultati',
|
|
137
139
|
sinRes: 'Niente nella memoria per «{q}». Se non è qui, la memoria non lo sa.', zonaVacia: 'Ancora niente in questa zona.',
|
|
138
140
|
vacia: 'La memoria è vuota. Si riempie da sola quando parli con l’agente.', verMas: 'Mostra altri {n}',
|
package/cortex/cortex.mjs
CHANGED
|
@@ -156,6 +156,12 @@ h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .16em; color: v
|
|
|
156
156
|
.cambios li::before, .abiertos li::before { content: ""; width: 8px; height: 8px; margin-top: 8px; border-radius: 50%; background: var(--c); box-shadow: 0 0 10px var(--c); }
|
|
157
157
|
.cambios small, .abiertos small { display: block; color: var(--suave); font-size: 12px; }
|
|
158
158
|
.vacio { color: var(--suave); font-size: 14px; margin: 0; }
|
|
159
|
+
.salud { display: grid; gap: 10px; }
|
|
160
|
+
.salud-l { list-style: none; margin: 0; padding: 0; display: grid; gap: 7px; }
|
|
161
|
+
.salud-l li { display: flex; align-items: baseline; gap: 8px; font-size: 14px; border: 1px solid var(--borde); border-radius: var(--radio); padding: 8px 12px; background: var(--papel-alto); }
|
|
162
|
+
.salud-l li > span { color: var(--suave); }
|
|
163
|
+
.salud-l li > b { color: var(--texto); font-variant-numeric: tabular-nums; }
|
|
164
|
+
.salud-l li > small { color: var(--suave); margin-left: auto; text-align: right; font-size: 12px; }
|
|
159
165
|
.lista { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
|
|
160
166
|
.hecho { padding: 12px 16px 12px 18px; border-radius: 16px; background: var(--papel-alto); border: 1px solid var(--borde); display: grid; gap: 2px; cursor: pointer; position: relative; box-shadow: 0 1px 2px rgba(0,0,0,.25); transition: border-color .2s, transform .2s, box-shadow .2s; }
|
|
161
167
|
.hecho::before { content: ""; position: absolute; left: 0; top: 14px; bottom: 14px; width: 3px; border-radius: 3px; background: var(--c); box-shadow: 0 0 12px var(--c); }
|
|
@@ -186,6 +192,26 @@ h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .16em; color: v
|
|
|
186
192
|
.mandos select, .busca input { font-size: 16px; }
|
|
187
193
|
.panel { position: static; max-height: none; border-left: 0; border-top: 1px solid var(--linea); padding: 18px 16px 40px; }
|
|
188
194
|
}
|
|
195
|
+
/* --- Panel: cabecera, colapso y pulido --------------------------------------------------------------- */
|
|
196
|
+
.panel { border-top-left-radius: 20px; box-shadow: inset 1px 1px 0 color-mix(in srgb, #fff 4%, transparent); }
|
|
197
|
+
[data-theme="light"] .panel { box-shadow: none; }
|
|
198
|
+
.panel-cab { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 2px; }
|
|
199
|
+
.panel-tit { display: inline-flex; align-items: center; gap: 9px; font: 700 12px/1 var(--fuente-titulos); letter-spacing: .2em; text-transform: uppercase; color: var(--suave); }
|
|
200
|
+
.panel-tit::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: var(--foco); box-shadow: 0 0 10px color-mix(in srgb, var(--foco) 70%, transparent); }
|
|
201
|
+
.panel-cerrar, .panel-abrir { display: inline-flex; align-items: center; justify-content: center; width: 40px; height: 40px; min-width: 40px; border: 1px solid var(--borde); background: var(--papel-alto); border-radius: 12px; color: var(--suave); transition: background .2s, color .2s, border-color .2s, transform .2s; }
|
|
202
|
+
.panel-cerrar:hover, .panel-abrir:hover { color: var(--texto); border-color: var(--linea); background: var(--papel); }
|
|
203
|
+
.panel-cerrar svg, .panel-abrir svg { width: 17px; height: 17px; }
|
|
204
|
+
.panel > section { padding-top: 20px; border-top: 1px solid color-mix(in srgb, var(--linea) 55%, transparent); }
|
|
205
|
+
.busca { position: relative; display: block; }
|
|
206
|
+
.busca .lupa { position: absolute; left: 15px; top: 50%; transform: translateY(-50%); width: 17px; height: 17px; color: var(--suave); pointer-events: none; }
|
|
207
|
+
.busca input { padding-left: 44px; }
|
|
208
|
+
/* botón flotante para reabrir (solo visible cuando el panel está colapsado) */
|
|
209
|
+
.panel-abrir { position: fixed; top: 20px; right: 20px; z-index: 6; display: none; box-shadow: 0 10px 26px -14px rgba(0,0,0,.55); }
|
|
210
|
+
.panel-abrir:hover { transform: translateY(-1px); }
|
|
211
|
+
[data-panel="off"] .escena { grid-template-columns: minmax(0, 1fr); }
|
|
212
|
+
[data-panel="off"] .panel { display: none; }
|
|
213
|
+
[data-panel="off"] .panel-abrir { display: inline-flex; }
|
|
214
|
+
html[data-solo] .panel-abrir { display: none !important; }
|
|
189
215
|
@media (prefers-reduced-motion: reduce) { * { transition: none !important; animation: none !important; } }
|
|
190
216
|
`;
|
|
191
217
|
|
|
@@ -219,7 +245,6 @@ const APP = String.raw`
|
|
|
219
245
|
$$('[data-t-aria]').forEach(function (e) { e.setAttribute('aria-label', t(e.getAttribute('data-t-aria'))); });
|
|
220
246
|
$$('[data-t-ph]').forEach(function (e) { e.setAttribute('placeholder', t(e.getAttribute('data-t-ph'))); });
|
|
221
247
|
$$('[data-t-title]').forEach(function (e) { e.setAttribute('title', t(e.getAttribute('data-t-title'))); });
|
|
222
|
-
$('#tema').textContent = raiz.getAttribute('data-theme') === 'light' ? t('oscuro') : t('claro');
|
|
223
248
|
$('#pie').textContent = t('pie', { f: new Date(D.generado).toLocaleString(L) }) + ' ' + (D.cliente ? t('pieCliente') : t('pieDueno'));
|
|
224
249
|
}
|
|
225
250
|
var sel = $('#idioma');
|
|
@@ -414,17 +439,10 @@ const APP = String.raw`
|
|
|
414
439
|
$('#buscar').addEventListener('input', function (e) { filtro = e.target.value.trim().toLowerCase(); limite = PAGINA; lista(); focoBusqueda(); });
|
|
415
440
|
$('#mas').addEventListener('click', function () { limite += PAGINA * 3; lista(); });
|
|
416
441
|
$('#cerrar').addEventListener('click', function () { $('#detalle').hidden = true; });
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
var oscuro = raiz.getAttribute('data-theme') === 'light';
|
|
420
|
-
raiz.setAttribute('data-theme', oscuro ? 'dark' : 'light');
|
|
421
|
-
tema.textContent = oscuro ? t('claro') : t('oscuro'); todo();
|
|
422
|
-
});
|
|
423
|
-
// Embebido en la web (mismo origen → comparte localStorage): el Cortex SIGUE el tema de la web (clave 'theme';
|
|
424
|
-
// 'light' = claro, si no oscuro) para no quedar como una caja negra sobre una página clara (ni texto ilegible en el
|
|
425
|
-
// hero transparente). Reacciona al toggle de la web por el evento 'storage'.
|
|
442
|
+
// El Cortex es OSCURO (sin modo claro ni botón de tema). Única excepción: EMBEBIDO en la web (data-solo, mismo origen
|
|
443
|
+
// → comparte localStorage), sigue el tema de la página para no quedar como una caja negra sobre una página clara.
|
|
426
444
|
function temaWeb() { try { return localStorage.getItem('theme') === 'light' ? 'light' : 'dark'; } catch (e) { return null; } }
|
|
427
|
-
function aplicarTemaWeb() { var w = temaWeb(); if (
|
|
445
|
+
function aplicarTemaWeb() { if (!raiz.hasAttribute('data-solo')) return; var w = temaWeb(); if (w) raiz.setAttribute('data-theme', w); }
|
|
428
446
|
aplicarTemaWeb();
|
|
429
447
|
window.addEventListener('storage', function (e) { if (e.key === 'theme') { aplicarTemaWeb(); todo(); } });
|
|
430
448
|
var cli = $('#cliente');
|
|
@@ -435,6 +453,15 @@ const APP = String.raw`
|
|
|
435
453
|
});
|
|
436
454
|
var pb = $('#piensa'); if (pb) pb.addEventListener('click', pensar);
|
|
437
455
|
|
|
456
|
+
// ---------------- Panel lateral colapsable (se recuerda por visor, sin tocar la memoria)
|
|
457
|
+
try { if (localStorage.getItem('cortex-panel') === 'off') raiz.setAttribute('data-panel', 'off'); } catch (e) {}
|
|
458
|
+
function panel(off) {
|
|
459
|
+
if (off) raiz.setAttribute('data-panel', 'off'); else raiz.removeAttribute('data-panel');
|
|
460
|
+
try { localStorage.setItem('cortex-panel', off ? 'off' : 'on'); } catch (e) {}
|
|
461
|
+
}
|
|
462
|
+
var ptog = $('#panel-toggle'); if (ptog) ptog.addEventListener('click', function () { panel(true); });
|
|
463
|
+
var pabr = $('#panel-abrir'); if (pabr) pabr.addEventListener('click', function () { panel(false); });
|
|
464
|
+
|
|
438
465
|
// ---------------- 3D: un cerebro de verdad hecho de puntos, con neuronas que se encienden
|
|
439
466
|
// Cada hemisferio es la UNIÓN de elipsoides (cuerpo, polo frontal, polo occipital, lóbulo temporal y cerebelo); de
|
|
440
467
|
// cada uno se toman puntos de su superficie que no caen dentro de otro: queda la piel del cerebro. Entre hemisferios,
|
|
@@ -702,7 +729,7 @@ const APP = String.raw`
|
|
|
702
729
|
});
|
|
703
730
|
traducir();
|
|
704
731
|
todo();
|
|
705
|
-
|
|
732
|
+
var _b3 = $('[data-ir="3d"]'); if (_b3) _b3.click(); // arranca SIEMPRE en 3D (es la vista por defecto), no solo incrustado
|
|
706
733
|
})();
|
|
707
734
|
`;
|
|
708
735
|
|
|
@@ -710,6 +737,20 @@ const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<',
|
|
|
710
737
|
// JSON dentro de <script type="application/json">: «<» escapado, así ningún valor puede cerrar la etiqueta
|
|
711
738
|
const json = o => JSON.stringify(o).replace(/</g, '\\u003c');
|
|
712
739
|
|
|
740
|
+
// F15-T8: panel de fiabilidad, server-rendered desde datos.salud (se lee sin JavaScript; las etiquetas se traducen por
|
|
741
|
+
// data-t, los números son neutros). Filas privadas (uso real, última sesión) con `solo-dueno`: ocultas en vista cliente.
|
|
742
|
+
function panelSalud(s, cliente, es) {
|
|
743
|
+
if (!s) return '';
|
|
744
|
+
const fam = Object.entries(s.hechos.porFamilia || {}).sort((a, b) => b[1] - a[1]).slice(0, 6).map(([k, v]) => `${k} ${v}`).join(' · ');
|
|
745
|
+
const fila = (clave, val, det, priv) => `<li${priv ? ' class="solo-dueno"' : ''}><span data-t="salud.${clave}">${es.salud[clave]}</span><b>${esc(String(val))}</b>${det ? `<small>${esc(det)}</small>` : ''}</li>`;
|
|
746
|
+
const filas = [fila('hechos', s.hechos.activos, fam)];
|
|
747
|
+
if (s.bateria) filas.push(fila('bateria', `${s.bateria.hit5}%`, `hit@5 · ${s.bateria.abstencion}% abst · ${s.bateria.ms} ms`));
|
|
748
|
+
if (!cliente && s.uso) filas.push(fila('uso', s.uso.precision != null ? `${s.uso.precision}%` : '—', `${s.uso.usados}/${s.uso.inyectados}`, true));
|
|
749
|
+
if (!cliente && s.ultimaSesion && s.ultimaSesion.fecha) filas.push(fila('sesion', s.ultimaSesion.guardo ? `+${s.ultimaSesion.guardo}` : '0',
|
|
750
|
+
`${s.ultimaSesion.fecha}${s.ultimaSesion.hechos.length ? ' · ' + s.ultimaSesion.hechos.map(h => String(h.dimension).split('.')[0]).join(' ') : ''}`, true));
|
|
751
|
+
return `<section class="salud" id="salud-s"><h2 data-t="salud.t">${es.salud.t}</h2><ul class="salud-l">${filas.join('')}</ul></section>`;
|
|
752
|
+
}
|
|
753
|
+
|
|
713
754
|
export function htmlCortex(datos, { cli = null, idioma = null, soloCerebro = false } = {}) {
|
|
714
755
|
const cliente = !!datos.cliente;
|
|
715
756
|
const solo = !!(datos.soloCerebro || soloCerebro); // modo incrustable: solo el cerebro 3D, sin panel ni mandos
|
|
@@ -737,14 +778,13 @@ export function htmlCortex(datos, { cli = null, idioma = null, soloCerebro = fal
|
|
|
737
778
|
<p class="cifras" id="cifras"></p>
|
|
738
779
|
</div>
|
|
739
780
|
<div class="mandos">
|
|
740
|
-
<span role="group" data-t-aria="vista"><button type="button" data-ir="2d" aria-pressed="
|
|
781
|
+
<span role="group" data-t-aria="vista"><button type="button" data-ir="2d" aria-pressed="false">2D</button> <button type="button" data-ir="3d" aria-pressed="true">3D</button></span>
|
|
741
782
|
${cliente ? '' : `<button type="button" id="cliente" aria-pressed="false" data-t="vistaCliente" data-t-title="vistaClienteT">${es.vistaCliente}</button>`}
|
|
742
783
|
${datos.actividad && datos.actividad.pensamientos && datos.actividad.pensamientos.length ? `<button type="button" id="piensa" aria-pressed="false" data-t="piensa" data-t-title="piensaT">${es.piensa}</button>` : ''}
|
|
743
|
-
<button type="button" id="tema">${es.claro}</button>
|
|
744
784
|
<label><span class="sr" data-t="idioma">${es.idioma}</span><select id="idioma"></select></label>
|
|
745
785
|
</div>
|
|
746
786
|
</div>
|
|
747
|
-
<div class="escenario" data-vista="
|
|
787
|
+
<div class="escenario" data-vista="3d">
|
|
748
788
|
<div class="v2d">
|
|
749
789
|
<div class="dibujo">${cerebro()}</div>
|
|
750
790
|
<p class="pista" data-t="pista">${es.pista}</p>
|
|
@@ -757,7 +797,12 @@ export function htmlCortex(datos, { cli = null, idioma = null, soloCerebro = fal
|
|
|
757
797
|
</div>
|
|
758
798
|
</section>
|
|
759
799
|
<aside class="panel">
|
|
760
|
-
<
|
|
800
|
+
<div class="panel-cab">
|
|
801
|
+
<span class="panel-tit" data-t="panelTitulo">${es.panelTitulo}</span>
|
|
802
|
+
<button type="button" class="panel-cerrar" id="panel-toggle" data-t-aria="panelOcultar" data-t-title="panelOcultar" aria-label="${es.panelOcultar}" title="${es.panelOcultar}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 6l6 6-6 6"/></svg></button>
|
|
803
|
+
</div>
|
|
804
|
+
<label class="busca"><span class="sr" data-t="buscarL">${es.buscarL}</span><svg class="lupa" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4-4"/></svg><input id="buscar" type="search" data-t-ph="buscar" placeholder="${es.buscar}" autocomplete="off"></label>
|
|
805
|
+
${solo ? '' : panelSalud(datos.salud, cliente, es)}
|
|
761
806
|
<section><h2 data-t="semana">${es.semana}</h2><ul class="cambios" id="cambios-l"></ul><p class="vacio" id="cambios-v" data-t="nadaSemana">${es.nadaSemana}</p></section>
|
|
762
807
|
<section id="abiertos-s"><h2 data-t="sigueAbierto">${es.sigueAbierto}</h2><ul class="abiertos" id="abiertos-l"></ul></section>
|
|
763
808
|
<section>
|
|
@@ -779,6 +824,7 @@ export function htmlCortex(datos, { cli = null, idioma = null, soloCerebro = fal
|
|
|
779
824
|
</article>
|
|
780
825
|
<p class="pie" id="pie"></p>
|
|
781
826
|
</aside>
|
|
827
|
+
<button type="button" class="panel-abrir" id="panel-abrir" data-t-aria="panelVer" data-t-title="panelVer" aria-label="${es.panelVer}" title="${es.panelVer}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 6l-6 6 6 6"/></svg></button>
|
|
782
828
|
</div>
|
|
783
829
|
<script type="application/json" id="datos-cortex">${json(D)}</script>
|
|
784
830
|
<script type="application/json" id="textos-cortex">${json(TEXTOS)}</script>
|
package/install.mjs
CHANGED
|
@@ -152,10 +152,15 @@ function empaquetarPlugin(destino) {
|
|
|
152
152
|
const cmds = fs.readdirSync(CMDS_SRC).filter(f => f.endsWith('.md'));
|
|
153
153
|
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++; } }
|
|
154
154
|
} catch { /* no commands/ */ }
|
|
155
|
-
//
|
|
156
|
-
const
|
|
155
|
+
// 4b) icono del listado (cuervo sobre fondo oscuro): el directorio de Anthropic lo pide (PNG cuadrado < 2 MB).
|
|
156
|
+
const iconoSrc = path.join(AQUI, 'assets', 'icon.png');
|
|
157
|
+
let iconoCampo = undefined;
|
|
158
|
+
if (fs.existsSync(iconoSrc)) { fs.copyFileSync(iconoSrc, path.join(dir, '.claude-plugin', 'icon.png')); iconoCampo = '.claude-plugin/icon.png'; }
|
|
159
|
+
// 4) plugin.json — repository en https:// PURO (el directorio descarta git+…/.git); displayName + icon para el listado.
|
|
160
|
+
const repo = String((pkg.repository && pkg.repository.url) || 'https://github.com/petersonsenadevs/corvusmem').replace(/^git\+/, '').replace(/\.git$/, '');
|
|
161
|
+
const plugin = { name: 'corvusmem', displayName: 'Corvusmem', description: pkg.description || 'Memoria determinista, offline y sin dependencias para agentes de IA.', version: pkg.version || '0.0.0', author: { name: 'Peterson Sena (r3v3rs3)', url: 'https://dev.to/r3v3rs3' }, homepage: pkg.homepage || 'https://corvusmem.vercel.app', repository: repo, license: 'SEE LICENSE IN LICENSE', ...(iconoCampo ? { icon: iconoCampo } : {}) };
|
|
157
162
|
fs.writeFileSync(path.join(dir, '.claude-plugin', 'plugin.json'), JSON.stringify(plugin, null, 2) + '\n');
|
|
158
|
-
log(` [plugin] ${dir}: .claude-plugin/plugin.json + hooks/hooks.json + ${n} .mjs + ${ncli} cli + ${ncx} cortex${nc ? ` + ${nc} command(s)` : ''}`);
|
|
163
|
+
log(` [plugin] ${dir}: .claude-plugin/plugin.json + hooks/hooks.json + ${n} .mjs + ${ncli} cli + ${ncx} cortex${nc ? ` + ${nc} command(s)` : ''}${iconoCampo ? ' + icon' : ''}`);
|
|
159
164
|
}
|
|
160
165
|
|
|
161
166
|
// Genera, DENTRO del repo, el plugin committeable `plugins/corvusmem/` y el `.claude-plugin/marketplace.json` de la
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "corvusmem",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.1",
|
|
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": {
|
|
@@ -11,15 +11,17 @@
|
|
|
11
11
|
"cli/",
|
|
12
12
|
"commands/",
|
|
13
13
|
"cortex/",
|
|
14
|
+
"assets/icon.png",
|
|
14
15
|
"install.mjs",
|
|
15
16
|
"docs.md",
|
|
16
17
|
"COMMERCIAL.md",
|
|
17
18
|
"CHANGELOG.md"
|
|
18
19
|
],
|
|
19
20
|
"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",
|
|
21
|
+
"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-save-criterios.mjs && node tests/test-hecho-detector.mjs && node tests/test-extractor.mjs && node tests/test-extractor-integracion.mjs && node tests/test-recall-piso.mjs && node tests/test-health.mjs && node tools/eval-memoria/eval.mjs --gate && node tests/test-cortex-visual.mjs",
|
|
22
|
+
"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 && node tests/test-save-criterios.mjs && node tests/test-hecho-detector.mjs && node tests/test-extractor.mjs && node tests/test-extractor-integracion.mjs && node tests/test-recall-piso.mjs && node tests/test-health.mjs && node tools/eval-memoria/eval.mjs --gate",
|
|
22
23
|
"bench:tokens": "node tools/eval-tokens.mjs",
|
|
24
|
+
"bench:precision": "node tools/eval-precision-inyeccion.mjs",
|
|
23
25
|
"preversion": "npm run test:core",
|
|
24
26
|
"prepublishOnly": "npm run test:core"
|
|
25
27
|
},
|
|
@@ -49,6 +51,7 @@
|
|
|
49
51
|
"url": "https://github.com/petersonsenadevs/corvusmem/issues"
|
|
50
52
|
},
|
|
51
53
|
"devDependencies": {
|
|
54
|
+
"@huggingface/transformers": "^4.3.2",
|
|
52
55
|
"gpt-tokenizer": "^4.1.0"
|
|
53
56
|
}
|
|
54
57
|
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Corvusmem · author: Peterson Sena (r3v3rs3) · https://github.com/petersonsenadevs/corvusmem
|
|
2
|
+
// Extractor DETERMINISTA de hechos (F17-T8): de una frase con forma de hecho saca {dimension, valor, claves} sin LLM
|
|
3
|
+
// ni red, misma entrada → misma salida. Hoy esa destilación la hace el AGENTE a mano (live-memory solo detecta y
|
|
4
|
+
// empuja); eso lo hace inconsistente y es la raíz del bug de que un dato acabe en la dimensión o el almacén equivocados.
|
|
5
|
+
// Este módulo ADELANTA el trabajo SOLO donde la dimensión es inequívoca (ubicación personal, sede, herramienta); para
|
|
6
|
+
// lo ambiguo (p. ej. el coste de un proveedor) devuelve null y el agente decide como hasta ahora. Alta precisión,
|
|
7
|
+
// recall bajo: el mismo contrato que el detector esHechoGuardable (src/live-memory.mjs), del que es subconjunto.
|
|
8
|
+
// La dimensión y las claves pasan SIEMPRE por la convención del motor (dimensionConvencional/clavesConvencionales de
|
|
9
|
+
// facts.mjs), así el extractor produce exactamente lo que guardaría un agente cuidadoso: cero divergencia de formato.
|
|
10
|
+
|
|
11
|
+
import { dimensionConvencional, clavesConvencionales, normalizar } from './facts.mjs';
|
|
12
|
+
import { esHechoGuardable, PREGUNTA } from './live-memory.mjs';
|
|
13
|
+
|
|
14
|
+
// Gestores de paquetes y editores conocidos: si la herramienta usada es uno de estos, la dimensión es más fina que
|
|
15
|
+
// «proyecto.stack» (es una preferencia de utillaje). Listas cerradas y deterministas; lo que no esté cae a stack.
|
|
16
|
+
const GESTORES = new Set(['npm', 'pnpm', 'yarn', 'bun', 'pip', 'pipenv', 'poetry', 'pdm', 'composer', 'cargo', 'go', 'gem', 'bundler', 'maven', 'gradle']);
|
|
17
|
+
const EDITORES = new Set(['vscode', 'vs-code', 'vim', 'neovim', 'nvim', 'emacs', 'webstorm', 'phpstorm', 'pycharm', 'intellij', 'sublime', 'zed', 'cursor', 'nano', 'helix']);
|
|
18
|
+
|
|
19
|
+
// Limpia un valor capturado: espacios simples y sin puntuación de cierre colgando. Conserva mayúsculas (nombres propios).
|
|
20
|
+
const limpiarValor = s => String(s || '').replace(/\s+/g, ' ').replace(/[.,;:!?¿¡\s]+$/u, '').trim();
|
|
21
|
+
const esNombrePropio = s => /^\p{Lu}/u.test(String(s || '').trim());
|
|
22
|
+
|
|
23
|
+
// Cada regla: un patrón con UN grupo de captura (la entidad) y cómo mapearla a dimensión. El orden es el de precisión.
|
|
24
|
+
// Las de ubicación exigen nombre propio en el grupo (ya lo fuerza \p{Lu} en el patrón); la de herramienta decide la
|
|
25
|
+
// familia por la lista a la que pertenece el token.
|
|
26
|
+
const REGLAS = [
|
|
27
|
+
{
|
|
28
|
+
nombre: 'ubicacion-personal',
|
|
29
|
+
re: /\b(?:vivo|vive|vivimos|viven|viv[íi]a|resido|reside)\s+en\s+(\p{Lu}[\p{L}À-ɏ'’-]*(?:\s+\p{Lu}[\p{L}À-ɏ'’-]*)*)/u,
|
|
30
|
+
dim: () => 'identidad.ubicacion',
|
|
31
|
+
claves: v => ['ciudad', v],
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
nombre: 'sede-oficina',
|
|
35
|
+
re: /\b(?:la\s+oficina|la\s+sede|el\s+despacho)\b[^.?!\n]{0,24}?\best[aá]\s+en\s+(\p{Lu}[\p{L}À-ɏ'’-]*(?:\s+\p{Lu}[\p{L}À-ɏ'’-]*)*)/u,
|
|
36
|
+
dim: () => 'proyecto.sede',
|
|
37
|
+
claves: v => ['sede', 'oficina', v],
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
nombre: 'herramienta',
|
|
41
|
+
re: /\b(?:usamos|utilizamos|trabajamos\s+con|we\s+use|we\s+work\s+with)\s+([\p{L}@][\w.@/+-]{1,})/iu,
|
|
42
|
+
dim: v => {
|
|
43
|
+
const t = normalizar(v).replace(/[^\p{L}\p{N}-]/gu, '');
|
|
44
|
+
if (GESTORES.has(t)) return 'preferencia.gestor-paquetes';
|
|
45
|
+
if (EDITORES.has(t)) return 'preferencia.editor';
|
|
46
|
+
return 'proyecto.stack';
|
|
47
|
+
},
|
|
48
|
+
claves: v => [v],
|
|
49
|
+
},
|
|
50
|
+
];
|
|
51
|
+
|
|
52
|
+
// Devuelve { dimension, valor, claves, fragmento, regla } canónico, o null si no hay un hecho de dimensión INEQUÍVOCA.
|
|
53
|
+
// Una pregunta nunca es un hecho (reusa el guardián del detector). Es un SUBCONJUNTO de esHechoGuardable: lo que este
|
|
54
|
+
// detecta pero el extractor no sabe dimensionar con seguridad, devuelve null (y el agente sigue destilándolo a mano).
|
|
55
|
+
export function extraerHecho(texto) {
|
|
56
|
+
const t = String(texto || '').trim();
|
|
57
|
+
if (!t || PREGUNTA.test(t)) return null;
|
|
58
|
+
for (const regla of REGLAS) {
|
|
59
|
+
const mm = regla.re.exec(t);
|
|
60
|
+
if (!mm) continue;
|
|
61
|
+
const valor = limpiarValor(mm[1]);
|
|
62
|
+
if (!valor) continue;
|
|
63
|
+
if (regla.nombre !== 'herramienta' && !esNombrePropio(valor)) continue;
|
|
64
|
+
let dimension;
|
|
65
|
+
try { dimension = dimensionConvencional(regla.dim(valor)).dimension; } catch { continue; }
|
|
66
|
+
const claves = clavesConvencionales(regla.claves(valor), dimension);
|
|
67
|
+
const fragmento = (esHechoGuardable(t) || mm[0]).replace(/\s+/g, ' ').trim().slice(0, 120);
|
|
68
|
+
return { dimension, valor, claves, fragmento, regla: regla.nombre };
|
|
69
|
+
}
|
|
70
|
+
return null;
|
|
71
|
+
}
|
package/src/facts-guard.mjs
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
|
|
10
10
|
import fs from 'node:fs';
|
|
11
11
|
import path from 'node:path';
|
|
12
|
-
import { readHookInput, projectRoot, sessionFlag, sinTextoCitado, relDelProyecto, rutaNativa, ruta, rutaRel, rutaMemoriaUsuario, testOnce, rutaBuscador, editadosSesion } from './lib.mjs';
|
|
12
|
+
import { readHookInput, projectRoot, sessionFlag, sinTextoCitado, relDelProyecto, rutaNativa, ruta, rutaRel, rutaMemoriaUsuario, testOnce, rutaBuscador, editadosSesion, localeUI, msg } from './lib.mjs';
|
|
13
13
|
import { palabras, palabraConPeso, todosLosHechos } from './facts.mjs';
|
|
14
14
|
|
|
15
15
|
const p = readHookInput() || {};
|
|
@@ -50,6 +50,7 @@ if (evento === 'PostToolUse') {
|
|
|
50
50
|
|
|
51
51
|
// ---------------- Stop: dos comprobaciones, cada una UNA vez por sesión, en un solo mensaje
|
|
52
52
|
const root = projectRoot();
|
|
53
|
+
const lang = localeUI(root);
|
|
53
54
|
const rev = leerRevision(flag);
|
|
54
55
|
const cli = rutaBuscador(root).replace(/buscar\.mjs$/, 'memory.mjs');
|
|
55
56
|
const motivos = [];
|
|
@@ -59,10 +60,9 @@ let peticiones = null;
|
|
|
59
60
|
try { peticiones = JSON.parse(fs.readFileSync(sessionFlag(sid, 'peticiones'), 'utf8')); } catch { }
|
|
60
61
|
const conversacion = Array.isArray(peticiones) && peticiones.filter(x => palabras(x && x.texto).filter(palabraConPeso).length >= 2).length >= 2;
|
|
61
62
|
if (conversacion && !rev.revisada && testOnce(sid, 'hechos-guard')) {
|
|
62
|
-
motivos.push('Revisa la memoria (en el idioma en que haya hablado el usuario)
|
|
63
|
-
+
|
|
64
|
-
+ `Si
|
|
65
|
-
+ `Si no: node ${cli} --nada. Las decisiones y reglas del proyecto van a MEMORIA.md (/recordar). No inventes hechos que el usuario no dijo.`);
|
|
63
|
+
motivos.push('Revisa la memoria (en el idioma en que haya hablado el usuario).' + msg('save.criterios', lang).replace(/\s+/g, ' ').trimEnd()
|
|
64
|
+
+ ` Si va: node ${cli} --guardar --dimension familia.tema --valor "…" --claves "…" (familia: identidad, preferencia, proyecto, objetivo, pendiente, restriccion, nota o aprendizaje; tema en castellano, sea cual sea el idioma de la conversación; claves también en inglés y en su idioma; que se entienda solo: nombres y fechas absolutas, no «mañana» ni «él»; con «creo que…», --duda; lo que deduces tú y no dijo, --fuente agente). `
|
|
65
|
+
+ `Si no hay nada que guardar: node ${cli} --nada. Las decisiones y reglas del proyecto van a MEMORIA.md (/recordar). No inventes hechos que el usuario no dijo.`);
|
|
66
66
|
}
|
|
67
67
|
// 2. Consolidar (F6-T3): si la sesión TRABAJÓ (3+ archivos tocados, sin contar la memoria ni el plan) y no guardó ningún
|
|
68
68
|
// aprendizaje.*, lo aprendido pasa a conocimiento duradero, enlazado solo con la entrada del devlog de hoy.
|
package/src/facts.mjs
CHANGED
|
@@ -1104,8 +1104,11 @@ export function datosCortex(root, { cliente = false, ahora = hoy(), dias = 7, en
|
|
|
1104
1104
|
.map(h => ({ id: h.id, privado: privado(h) || undefined, tema: temaDe(h.dimension), valor: h.valor, zona: zonaDe(h), progreso: h.progreso || 'abierto', dias: Math.max(0, Math.floor((Date.parse(ahora) - Date.parse(h.creado)) / 864e5)) }));
|
|
1105
1105
|
// el nombre del proyecto: el que sabe la memoria (proyecto.nombre) o, si no, el de la carpeta
|
|
1106
1106
|
const nombre = actuales.find(h => h.dimension === 'proyecto.nombre');
|
|
1107
|
+
// F15-T8: salud en el panel. Con cliente, sin lo privado (uso real y última sesión): solo hechos y batería.
|
|
1108
|
+
const salud = datosSalud(root, { ahora });
|
|
1109
|
+
const saludVista = cliente ? { generado: salud.generado, hechos: salud.hechos, bateria: salud.bateria } : salud;
|
|
1107
1110
|
return { proyecto: nombre ? nombre.valor : path.basename(path.resolve(root)), generado: ahora, cliente, zonas, cambios: cambios.slice(0, 20), abiertos: abiertosV,
|
|
1108
|
-
actividad: actividadCortex(root, { cliente, ahora }) };
|
|
1111
|
+
actividad: actividadCortex(root, { cliente, ahora }), salud: saludVista };
|
|
1109
1112
|
}
|
|
1110
1113
|
// Cómo PIENSA (X-T10): del registro de uso real, qué zonas ha consultado el agente y cuánto. Cada recuerdo que llegó
|
|
1111
1114
|
// pesa más cuanto más reciente (se reduce a la mitad cada 3 días), más si lo usó y menos si lo ignoró. Y la secuencia
|
|
@@ -1151,6 +1154,46 @@ export function apuntarInyeccion(root, { sid, origen, consulta, items = [] }, {
|
|
|
1151
1154
|
function leerUso(root) {
|
|
1152
1155
|
try { return fs.readFileSync(rutaUso(root), 'utf8').split(/\r?\n/).filter(Boolean).map(l => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean); } catch { return []; }
|
|
1153
1156
|
}
|
|
1157
|
+
// F17-T9: la ESCALA del diario (y las decisiones) para darles un suelo ABSOLUTO proporcional a su tamaño. Los puntos
|
|
1158
|
+
// de search.mjs dependen del tamaño del devlog (~0,7 pequeño, ~38 grande), así que un suelo fijo rompería los diarios
|
|
1159
|
+
// pequeños. La escala = p90 del MEJOR acierto de diario por consulta en el historial real (recuerdo-uso.jsonl), que ya
|
|
1160
|
+
// se acumula solo. Sin historial suficiente → 0 (sin suelo: se comporta como antes; no se daña a un proyecto nuevo).
|
|
1161
|
+
const MIN_CONSULTAS_ESCALA = 20; // por debajo de esto no hay muestra para fiarse: no se pone suelo
|
|
1162
|
+
const MAX_LINEAS_ESCALA = 1000; // solo la historia RECIENTE: representa la escala ACTUAL del diario (que crece con el
|
|
1163
|
+
// tiempo) y acota el coste del hook (parsear 3000 líneas por mensaje era ~14 ms)
|
|
1164
|
+
function mejoresDiario(root) {
|
|
1165
|
+
let raw = ''; try { raw = fs.readFileSync(rutaUso(root), 'utf8'); } catch { return []; }
|
|
1166
|
+
const lineas = raw.split(/\r?\n/).filter(Boolean);
|
|
1167
|
+
const recientes = lineas.length > MAX_LINEAS_ESCALA ? lineas.slice(-MAX_LINEAS_ESCALA) : lineas;
|
|
1168
|
+
const mejores = [];
|
|
1169
|
+
for (const ln of recientes) {
|
|
1170
|
+
let l; try { l = JSON.parse(ln); } catch { continue; }
|
|
1171
|
+
if (!l || l.origen === 'consulta') continue;
|
|
1172
|
+
let mx = 0; for (const it of (l.items || [])) if ((it.fuente === 'devlog' || it.fuente === 'memoria') && it.puntuacion != null && it.puntuacion > mx) mx = it.puntuacion;
|
|
1173
|
+
if (mx > 0) mejores.push(mx);
|
|
1174
|
+
}
|
|
1175
|
+
return mejores;
|
|
1176
|
+
}
|
|
1177
|
+
export function escalaDiario(root) {
|
|
1178
|
+
const mejores = mejoresDiario(root);
|
|
1179
|
+
if (mejores.length < MIN_CONSULTAS_ESCALA) return 0;
|
|
1180
|
+
mejores.sort((a, b) => a - b);
|
|
1181
|
+
return mejores[Math.min(mejores.length - 1, Math.floor(mejores.length * 0.90))]; // p90
|
|
1182
|
+
}
|
|
1183
|
+
// F17-T9e: el SUELO del diario = fracción × escala, con la fracción ESCALADA POR CONFIANZA. Con poca historia (recién
|
|
1184
|
+
// pasado el mínimo) el suelo es suave (0,25); con mucha, firme (0,35). De-risk 018/022: en un proyecto maduro el suelo
|
|
1185
|
+
// aguanta más alto sin estropear la relación ruido:útil, pero a 0,35 fijo el proyecto pequeño sufría → más datos, más
|
|
1186
|
+
// confianza, listón más alto. Sin historial suficiente → 0 (sin suelo). Única fuente del suelo (la usan hook y bench).
|
|
1187
|
+
const FRAC_MIN = 0.25, FRAC_MAX = 0.35, N_FRAC_MAX = 200; // 0,25 en el mínimo (20) → 0,35 con ≥200 consultas de diario
|
|
1188
|
+
export function pisoDiario(root) {
|
|
1189
|
+
const mejores = mejoresDiario(root);
|
|
1190
|
+
const n = mejores.length;
|
|
1191
|
+
if (n < MIN_CONSULTAS_ESCALA) return 0;
|
|
1192
|
+
mejores.sort((a, b) => a - b);
|
|
1193
|
+
const escala = mejores[Math.min(n - 1, Math.floor(n * 0.90))];
|
|
1194
|
+
const t = Math.max(0, Math.min(1, (n - MIN_CONSULTAS_ESCALA) / (N_FRAC_MAX - MIN_CONSULTAS_ESCALA)));
|
|
1195
|
+
return (FRAC_MIN + (FRAC_MAX - FRAC_MIN) * t) * escala;
|
|
1196
|
+
}
|
|
1154
1197
|
// Lo que dijo el agente, con su hora, de una conversación de Claude Code (JSONL). Formato desconocido → [].
|
|
1155
1198
|
export function textosDelAgente(transcript) {
|
|
1156
1199
|
let crudo = ''; try { crudo = fs.readFileSync(transcript, 'utf8'); } catch { return []; }
|
|
@@ -1239,6 +1282,40 @@ export function informeUso(root, { dias = 30, ahora = hoy() } = {}) {
|
|
|
1239
1282
|
};
|
|
1240
1283
|
}
|
|
1241
1284
|
|
|
1285
|
+
// F15-T8: la salud de la memoria en números, UNA sola fuente para `--health` (CLI) y el panel del Cortex. Todo sale
|
|
1286
|
+
// del propio registro del proyecto (hechos, uso real, última sesión). La batería (eval determinista) solo existe en el
|
|
1287
|
+
// repo —es una herramienta de desarrollo, no va en el paquete—: en una instalación, `bateria` es null (y se dice).
|
|
1288
|
+
export function datosSalud(root, { dias = 30, ahora = hoy() } = {}) {
|
|
1289
|
+
const todos = todosLosHechos(root).filter(h => h.estado !== 'invalidado');
|
|
1290
|
+
const activos = todos.filter(h => h.estado === 'activo');
|
|
1291
|
+
const porFamilia = {}, porDimension = {};
|
|
1292
|
+
for (const h of activos) { const i = h.dimension.indexOf('.'); const fam = i >= 0 ? h.dimension.slice(0, i) : h.dimension; porFamilia[fam] = (porFamilia[fam] || 0) + 1; porDimension[h.dimension] = (porDimension[h.dimension] || 0) + 1; }
|
|
1293
|
+
// F17-T4: efecto fan (ACT-R, S − ln fan): una pista con MUCHOS hechos hace cada uno menos recuperable (interferencia).
|
|
1294
|
+
// Aviso determinista para que el agente concrete la consulta; no toca el ranking. Umbral = 5 (igual que ABANICO).
|
|
1295
|
+
const UMBRAL_FAN = 5;
|
|
1296
|
+
const pistasSaturadas = Object.entries(porDimension).filter(([, n]) => n >= UMBRAL_FAN).sort((a, b) => b[1] - a[1])
|
|
1297
|
+
.map(([dimension, n]) => ({ dimension, hechos: n, interferencia: +Math.log(n).toFixed(2), aviso: `${n} hechos en «${dimension}»: concreta la pista para recuperar el que buscas` }));
|
|
1298
|
+
const uso = informeUso(root, { dias, ahora });
|
|
1299
|
+
let ultimaSesion = null;
|
|
1300
|
+
try {
|
|
1301
|
+
const s = JSON.parse(fs.readFileSync(rutaEstado(root), 'utf8'));
|
|
1302
|
+
const g = Array.isArray(s.hechosGuardados) ? s.hechosGuardados : [];
|
|
1303
|
+
ultimaSesion = { fecha: String(s.actualizado || '').slice(0, 10) || null, guardo: g.length, hechos: g.slice(0, 5).map(h => ({ dimension: h.dimension, valor: h.valor })), archivos: Array.isArray(s.editados) ? s.editados.length : 0 };
|
|
1304
|
+
} catch {}
|
|
1305
|
+
let bateria = null;
|
|
1306
|
+
try {
|
|
1307
|
+
const f = path.join(AQUI, '..', 'tools', 'eval-memoria', 'resultados.json');
|
|
1308
|
+
if (fs.existsSync(f)) { const r = JSON.parse(fs.readFileSync(f, 'utf8')); const g = r.global || {}; bateria = { fecha: r.fecha, hit5: g.hit5_inyectado, abstencion: g.abstencion, duplicados: g.duplicados_ok, ms: g.ms_por_consulta, consultas: g.consultas }; }
|
|
1309
|
+
} catch {}
|
|
1310
|
+
return {
|
|
1311
|
+
generado: ahora,
|
|
1312
|
+
hechos: { activos: activos.length, dudosos: todos.filter(h => h.estado === 'dudoso').length, historico: todos.filter(h => h.estado === 'sustituido' || h.estado === 'cerrado').length, abiertos: abiertos(root, { ahora }).length, porFamilia },
|
|
1313
|
+
pistasSaturadas,
|
|
1314
|
+
uso: uso.mensajes ? { dias, mensajes: uso.mensajes, inyectados: uso.inyectados, usados: uso.usados, ignorados: uso.ignorados, precision: uso.precision } : null,
|
|
1315
|
+
bateria, ultimaSesion,
|
|
1316
|
+
};
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1242
1319
|
// ---------------------------------------------------------------- léxico multilingüe de la convención (X-T8)
|
|
1243
1320
|
// Para cada tema canónico, cómo se dice en ~20 idiomas (es, en, ca, pt, fr, de, it, nl, pl, tr, ru, uk, el, ja, zh, ko,
|
|
1244
1321
|
// ar, he, hi, vi, sv). Va al ÍNDICE (no a lo guardado: vale también para lo que ya existe) y no cuenta para la longitud
|
|
@@ -1266,6 +1343,12 @@ export const LEXICO = {
|
|
|
1266
1343
|
analitica: 'analytics analitica analytique statistiques analytik analisi analityka analitik аналитика аналітика αναλυτικά アナリティクス 分析 분석 تحليلات אנליטיקה एनालिटिक्स phan tich analys',
|
|
1267
1344
|
lanzamiento: 'launch release lanzamiento llancament lancamento lancement markteinfuhrung lancio lancering premiera lansman запуск κυκλοφορία ローンチ 发布 출시 إطلاق השקה लॉन्च lansering',
|
|
1268
1345
|
tests: 'tests testing pruebas proves testes essais testen testy testler тесты тести δοκιμές テスト 测试 테스트 اختبارات בדיקות परीक्षण tester',
|
|
1346
|
+
// F15-T5: conceptos que faltaban (el baseline los perdía por paráfrasis sin vocabulario compartido). Formas en
|
|
1347
|
+
// varios idiomas y conjugaciones frecuentes, para que la CONSULTA coincida con lo que el hecho ya dice.
|
|
1348
|
+
indentacion: 'indentation indent indents indented indentar indentado indento indentas indenta sangria sangrado sangrar sangro sangras sangra tabs tab tabulacion tabulaciones tabulador espacios whitespace einruckung inspringen wciecie rientro indentazione',
|
|
1349
|
+
oficina: 'office oficina officina sede seu bureau buro despacho workplace headquarters escritorio ufficio buero kantoor biuro',
|
|
1350
|
+
deploy: 'deploy deployment deployed deploying despliegue desplegar desplegamos desplegado publicar publico publicamos publicado publicacion publish publishing published release releasing lanzar produccion bereitstellung implantacio implantar',
|
|
1351
|
+
tarifa: 'rate fee fees charge charges charged charging cobra cobrar cobramos cobrado cobro paga pagar pago pricing bill billing honorarios tarifas tariff honoraire tariffa gebuhr',
|
|
1269
1352
|
};
|
|
1270
1353
|
const LEXICO_TOKENS = new Map(Object.entries(LEXICO).map(([t, s]) => [t, palabras(s)]));
|
|
1271
1354
|
// Las palabras del léxico de un hecho (si su tema es de la convención); [] si no
|
package/src/lib.mjs
CHANGED
|
@@ -175,6 +175,9 @@ export function ruta(root, nombre) { // 'devlog' | 'plan' | 'design-system' |
|
|
|
175
175
|
// MEMORY is ALWAYS Corvus's own, in English, and never flips with Senzu's presence: .corvusmem/memory/. The store
|
|
176
176
|
// never moves when Senzu is added or removed; Corvus is the memory owner and Senzu defers to it (Senzu-side hayCorvus).
|
|
177
177
|
if (nombre === 'memoria') return path.join(root, CARPETA_CORVUS, MEM_DIR_EN);
|
|
178
|
+
// El Cortex es salida PROPIA de Corvus: vive SIEMPRE dentro de .corvusmem/cortex, nunca suelto en la raíz del
|
|
179
|
+
// proyecto (ni en senzu/), esté o no Senzu. Así no ensucia la raíz con una carpeta cortex/ aparte.
|
|
180
|
+
if (nombre === 'cortex') return path.join(root, CARPETA_CORVUS, 'cortex');
|
|
178
181
|
const base = carpetaBase(root);
|
|
179
182
|
const nombreReal = nombre;
|
|
180
183
|
const nueva = path.join(root, base, nombreReal);
|
package/src/live-memory.mjs
CHANGED
|
@@ -4,41 +4,115 @@
|
|
|
4
4
|
// 2. Si la petición trae una REGLA o una CORRECCIÓN clara («no vuelvas a…», «te dije…», «a partir de ahora…»,
|
|
5
5
|
// «siempre usa…»), pide al agente apuntarla antes de seguir (memoria del proyecto o del usuario) y deja una
|
|
6
6
|
// marca: estado-sesion bloquea el cierre una vez si al final no está apuntada.
|
|
7
|
+
// 3. (F15-T3) Si la petición es una FRASE CON FORMA DE HECHO —un dato que servirá luego: una herramienta que se usa,
|
|
8
|
+
// una cifra con su concepto, una ubicación, una API nombrada— empuja a guardarlo (nudge suave, no bloquea) y deja
|
|
9
|
+
// la marca 'hecho-pendiente' para un recordatorio de cierre. Alta precisión, recall bajo: una PREGUNTA nunca es un
|
|
10
|
+
// hecho que guardar (así «¿cuánto paga…?» o «qué framework usamos…» no disparan). Antes perder uno que meter ruido.
|
|
7
11
|
// Solo señales fuertes: «siempre» o «nunca» sueltos no cuentan (salen en cualquier frase).
|
|
8
12
|
|
|
9
13
|
import fs from 'node:fs';
|
|
10
|
-
import {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
// 1. últimas peticiones (las 5 últimas bastan para saber de qué iba la sesión)
|
|
19
|
-
try {
|
|
20
|
-
const f = sessionFlag(sid, 'peticiones');
|
|
21
|
-
let previas = [];
|
|
22
|
-
try { previas = JSON.parse(fs.readFileSync(f, 'utf8')); } catch {}
|
|
23
|
-
previas.push({ t: new Date().toISOString(), texto: corto });
|
|
24
|
-
fs.writeFileSync(f, JSON.stringify(previas.slice(-5)));
|
|
25
|
-
} catch {}
|
|
26
|
-
|
|
27
|
-
// 2. reglas y correcciones
|
|
28
|
-
const REGLA = new RegExp([
|
|
14
|
+
import { pathToFileURL } from 'node:url';
|
|
15
|
+
import { readHookInput, sessionFlag, outHookJson, rutaMemoriaUsuario, projectRoot, rutaRel, esMensajeDelUsuario, localeUI, msg, rutaCliMemoria } from './lib.mjs';
|
|
16
|
+
import { extraerHecho } from './extractor.mjs'; // F17-T8c: destila la dimensión/valor/claves cuando es inequívoco (ciclo seguro: solo se usa en funciones)
|
|
17
|
+
|
|
18
|
+
// ---------------- Detectores (puros y exportables: los tests los llaman sin montar el hook) ----------------
|
|
19
|
+
|
|
20
|
+
// Reglas y correcciones del usuario (señal fuerte y duradera).
|
|
21
|
+
export const REGLA = new RegExp([
|
|
29
22
|
'no vuelvas a', 'nunca m[aá]s', 'ya te (lo )?(he )?dicho', 'te (lo )?(he )?dicho', 'te dije', 'a partir de ahora',
|
|
30
23
|
'de ahora en adelante', 'para la pr[oó]xima', 'recuerda que', 'acu[eé]rdate de', 'cada vez que', 'no me gusta que',
|
|
31
24
|
'prefiero que', 'no quiero que', 'eso no era (para|lo)', 'otra vez lo mismo', 'siempre (usa|haz|pon|escribe|responde|commitea|crea|pregunta)',
|
|
32
25
|
'nunca (uses|hagas|pongas|commitees|subas|toques|borres|escribas)', 'no (lo|me) (vuelvas|repitas)',
|
|
33
26
|
].join('|'), 'i');
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
27
|
+
|
|
28
|
+
// Una PREGUNTA no es un hecho que guardar. Marcadores en ES/EN, con o sin signos; incluye «que» sin tilde a propósito
|
|
29
|
+
// (preferimos abstenernos a arriesgar un falso positivo con «qué framework usamos…»). Es el guardián de la precisión.
|
|
30
|
+
// Nota: con acentos no se puede cerrar con \b (á/é no son «word char» ASCII, el \b falla tras ellas): lookarounds \p{L}.
|
|
31
|
+
export const PREGUNTA = /[?¿]|(?<![\p{L}])(qu[eé]|cu[aá]l(es)?|cu[aá]nto?s?|cu[aá]nta?s?|qui[eé]n(es)?|d[oó]nde|c[oó]mo|cu[aá]ndo|por\s+qu[eé]|which|what|how|where|who|whom|whose|when|why|do\s+we|does|can\s+(we|the|it|i|you)|could|should)(?![\p{L}])/iu;
|
|
32
|
+
|
|
33
|
+
// Frases con FORMA DE HECHO: afirmación con un dato reusable. Cada patrón exige el dato (herramienta, cifra con
|
|
34
|
+
// moneda, ubicación con nombre propio, API/endpoint/URL nombrado), no solo el verbo. Recall bajo, precisión alta.
|
|
35
|
+
const HECHOS = [
|
|
36
|
+
// herramienta/stack estable que se USA: «usamos X», «we use X», «trabajamos con X»
|
|
37
|
+
/\b(usamos|utilizamos|trabajamos\s+con|we\s+use|we\s+work\s+with)\s+[\p{L}@][\w.@/+-]{1,}/iu,
|
|
38
|
+
// dato externo con CIFRA y moneda: «… cobra/paga/cuesta … 600 €/$/eur»
|
|
39
|
+
/\b(paga|pagan|pagamos|cobra|cobran|cuesta|cuestan|charges?|pays?|costs?)\b[^.?!\n]{0,40}?(\d[\d.,]*\s*(€|\$|eur|usd|euros|d[oó]lares)|[€$]\s?\d)/iu,
|
|
40
|
+
// ubicación con nombre propio: «vivo/vive/vivía en Madrid», «resido en …»
|
|
41
|
+
/\b(vivo|vive|vivimos|viven|viv[íi]a|resido|reside)\s+en\s+\p{Lu}/u,
|
|
42
|
+
// sede/oficina en un sitio: «la oficina está en Bilbao», «la sede está en …»
|
|
43
|
+
/\b(la\s+oficina|la\s+sede|el\s+despacho)\b[^.?!\n]{0,24}?\best[aá](?![\p{L}])[^.?!\n]{0,12}?\ben\b\s*\p{Lu}/iu,
|
|
44
|
+
// servicio externo nombrado: «la API es/está en …», «el endpoint es …», «la URL es …»
|
|
45
|
+
/\b(la\s+api|el\s+endpoint|la\s+url|el\s+host|el\s+servidor|the\s+api|the\s+endpoint|the\s+url)\b[^.?!\n]{0,24}?\b(es|est[aá]\s+en|is|at)\b\s*[^\s.?!]{3,}/iu,
|
|
46
|
+
];
|
|
47
|
+
|
|
48
|
+
// Devuelve el fragmento con forma de hecho (recortado) o null. Una pregunta nunca es un hecho.
|
|
49
|
+
export function esHechoGuardable(texto) {
|
|
50
|
+
const t = String(texto || '').trim();
|
|
51
|
+
if (!t || PREGUNTA.test(t)) return null;
|
|
52
|
+
for (const re of HECHOS) { const m = re.exec(t); if (m) return m[0].replace(/\s+/g, ' ').trim().slice(0, 120); }
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// F17-T8c: el comando de guardado que el nudge le ofrece al agente. Si el extractor determinista dimensiona el hecho
|
|
57
|
+
// (ubicación, sede, herramienta), el comando va YA DESTILADO —dimensión/valor/claves rellenos, el agente solo revisa—;
|
|
58
|
+
// si no, el placeholder de siempre y el agente destila a mano. Así la clave deja de depender de que el agente acierte.
|
|
59
|
+
// Puro y exportable (el test lo llama sin montar el hook).
|
|
60
|
+
export function comandoGuardado(texto, cli) {
|
|
61
|
+
const sug = extraerHecho(texto);
|
|
62
|
+
// `cli` (rutaCliMemoria) YA trae el ejecutable completo (`node "…/corvusmem.mjs"` o `npx corvusmem`): no se le
|
|
63
|
+
// antepone otro «node» (eso daba el comando roto «node node …», bug preexistente que el cableado destapó).
|
|
64
|
+
if (sug) {
|
|
65
|
+
return `Si va, el comando ya destilado (revísalo y ajusta la dimensión/valor si no encaja): `
|
|
66
|
+
+ `${cli} --guardar --dimension ${sug.dimension} --valor "${sug.valor}" --claves "${sug.claves.join(', ')}".`;
|
|
67
|
+
}
|
|
68
|
+
return `Si va: ${cli} --guardar --dimension familia.tema --valor "…" --claves "…" `
|
|
69
|
+
+ `(familia: identidad, preferencia, proyecto, objetivo, pendiente, restriccion, nota o aprendizaje; `
|
|
70
|
+
+ `claves también en inglés y en su idioma; nombres y fechas absolutas).`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ---------------- Hook (solo al ejecutarse como script; al importarlo para los tests, no corre) ----------------
|
|
74
|
+
|
|
75
|
+
if (import.meta.url === pathToFileURL(process.argv[1] || '').href) {
|
|
76
|
+
const p = readHookInput();
|
|
77
|
+
const texto = p && typeof p.prompt === 'string' ? p.prompt.trim() : '';
|
|
78
|
+
if (!texto || !esMensajeDelUsuario(texto)) process.exit(0); // lo de un subagente no es una corrección del usuario
|
|
79
|
+
const sid = p.session_id ? String(p.session_id) : 'default';
|
|
80
|
+
const corto = texto.replace(/\s+/g, ' ').slice(0, 200);
|
|
81
|
+
|
|
82
|
+
// 1. últimas peticiones (las 5 últimas bastan para saber de qué iba la sesión)
|
|
83
|
+
try {
|
|
84
|
+
const f = sessionFlag(sid, 'peticiones');
|
|
85
|
+
let previas = [];
|
|
86
|
+
try { previas = JSON.parse(fs.readFileSync(f, 'utf8')); } catch {}
|
|
87
|
+
previas.push({ t: new Date().toISOString(), texto: corto });
|
|
88
|
+
fs.writeFileSync(f, JSON.stringify(previas.slice(-5)));
|
|
89
|
+
} catch {}
|
|
90
|
+
|
|
91
|
+
const root = projectRoot();
|
|
92
|
+
|
|
93
|
+
// 2. reglas y correcciones (señal fuerte: bloquea el cierre si no queda apuntada)
|
|
94
|
+
const m = REGLA.exec(texto);
|
|
95
|
+
if (m) {
|
|
96
|
+
try { fs.writeFileSync(sessionFlag(sid, 'memoria-pendiente'), corto); } catch {}
|
|
97
|
+
outHookJson('UserPromptSubmit', {
|
|
98
|
+
additionalContext: `[senzu] Esto parece una regla o una corrección del usuario («${m[0]}…»). Si es duradera, apúntala ANTES de seguir: `
|
|
99
|
+
+ `de este proyecto → ${rutaRel(root, 'devlog')}/MEMORIA.md («Reglas del cliente y del proyecto» o «Lo que no funcionó»); `
|
|
100
|
+
+ `de todos sus proyectos → ${rutaMemoriaUsuario().replace(/\\/g, '/')} (memoria del usuario). Si dudas cuál, pregúntale en una línea. `
|
|
101
|
+
+ 'Si solo era una corrección de este momento (no una regla), sigue sin apuntar nada y dilo al cerrar.',
|
|
102
|
+
});
|
|
103
|
+
process.exit(0);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// 3. frase con forma de hecho (alta precisión): empuja a guardar sin bloquear, y deja marca para el cierre
|
|
107
|
+
const h = esHechoGuardable(texto);
|
|
108
|
+
if (!h) process.exit(0);
|
|
109
|
+
try { fs.writeFileSync(sessionFlag(sid, 'hecho-pendiente'), corto); } catch {}
|
|
110
|
+
const lang = localeUI(root);
|
|
111
|
+
const cli = rutaCliMemoria(root);
|
|
112
|
+
outHookJson('UserPromptSubmit', {
|
|
113
|
+
additionalContext: `[senzu] Esto suena a un dato que puede servir la próxima vez («${h}»). ${msg('save.criterios', lang)} `
|
|
114
|
+
+ comandoGuardado(texto, cli) + ' '
|
|
115
|
+
+ 'Si era solo de este momento, sigue sin guardar.',
|
|
116
|
+
});
|
|
117
|
+
process.exit(0);
|
|
118
|
+
}
|
package/src/live-recall.mjs
CHANGED
|
@@ -9,12 +9,15 @@ import fs from 'node:fs';
|
|
|
9
9
|
import crypto from 'node:crypto';
|
|
10
10
|
import { readHookInput, projectRoot, sessionFlag, outHookJson, esMensajeDelUsuario, localeUI, msg, rutaCliMemoria } from './lib.mjs';
|
|
11
11
|
import { reclamarInyeccion } from './host.mjs';
|
|
12
|
-
import { recuerdo, palabras, palabraConPeso, UMBRAL_RECUERDO, anotarUso, apuntarInyeccion, mapaMemoria, textoMapa, intencionTemporal } from './facts.mjs';
|
|
12
|
+
import { recuerdo, palabras, palabraConPeso, UMBRAL_RECUERDO, anotarUso, apuntarInyeccion, mapaMemoria, textoMapa, intencionTemporal, pisoDiario } from './facts.mjs';
|
|
13
13
|
|
|
14
14
|
// Umbrales (se afinan con la evaluación de F4). Hechos: BM25 del motor (IDF suavizado, escala estable). Memoria y
|
|
15
15
|
// devlog: los puntos de search.mjs dependen del tamaño del devlog (0,7 en uno pequeño, 38 en uno grande), así que el
|
|
16
16
|
// umbral es RELATIVO al mejor de su fuente; el buscador ya no devuelve nada si no hay relación.
|
|
17
17
|
const UMBRAL_HECHO = UMBRAL_RECUERDO, RELATIVO = 0.5, MAXIMO = 5; // el de hechos, compartido con la evaluación
|
|
18
|
+
// F17-T9: suelo ABSOLUTO para diario+decisiones (0,25–0,35 × escala, escalado por confianza; `pisoDiario` en facts.mjs
|
|
19
|
+
// es la única fuente). El relativo solo exige «ser el mejor de su fuente»; sin un suelo, el diario cuela entradas
|
|
20
|
+
// flojas cuando no hay nada bueno. Auto-calibrado del historial; sin historial suficiente → 0 (sin suelo, como antes).
|
|
18
21
|
|
|
19
22
|
const p = readHookInput();
|
|
20
23
|
const texto = p && typeof p.prompt === 'string' ? p.prompt.trim() : '';
|
|
@@ -39,8 +42,9 @@ const clave = x => crypto.createHash('md5').update(`${x.fuente}|${x.id}|${x.text
|
|
|
39
42
|
const intencion = intencionTemporal(consulta);
|
|
40
43
|
const todos = recuerdo(root, consulta.slice(0, 600), { limite: 10, historico: intencion === 'historical' ? 'auto' : false, futuro: intencion === 'future' ? 'auto' : false });
|
|
41
44
|
const mejor = f => Math.max(0, ...todos.filter(x => x.fuente === f).map(x => x.puntuacion));
|
|
45
|
+
const PISO_DIARIO = pisoDiario(root); // F17-T9: suelo absoluto para diario+decisiones (0 si no hay historial)
|
|
42
46
|
const elegidos = todos
|
|
43
|
-
.filter(x => (x.fuente === 'hecho' ? x.puntuacion >= UMBRAL_HECHO : x.puntuacion > 0 && x.puntuacion >= RELATIVO * mejor(x.fuente)) && !ya.has(clave(x)))
|
|
47
|
+
.filter(x => (x.fuente === 'hecho' ? x.puntuacion >= UMBRAL_HECHO : x.puntuacion > 0 && x.puntuacion >= RELATIVO * mejor(x.fuente) && x.puntuacion >= PISO_DIARIO) && !ya.has(clave(x)))
|
|
44
48
|
.sort((a, b) => (a.debil === true) - (b.debil === true)) // lo sólido delante; los roces de una palabra, detrás y marcados
|
|
45
49
|
.slice(0, MAXIMO);
|
|
46
50
|
// X-T4: se apunta lo que se inyecta (o el silencio) para medir el uso real; al cerrar se marca si sirvió
|
package/src/messages.mjs
CHANGED
|
@@ -537,6 +537,12 @@ export const CAT = {
|
|
|
537
537
|
en: ' SAVE what the user says that is stable (in any language): {cli} --save --dimension family.topic --value "…" --keys "term in English,in their language" (family: identity, preference, project, goal, pending, constraint, note, learning). Make it stand on its own: who or what by name and an absolute date («Marco Bianchi, the photographer, charges 600 €», not «charges 600 €»; «on 2026-10-15», not «tomorrow»). With «I think…», --doubt; what you infer yourself, --source agent.',
|
|
538
538
|
es: ' GUARDA lo estable que diga el usuario (en el idioma que sea): {cli} --guardar --dimension familia.tema --valor "…" --claves "término en inglés,en su idioma" (familia: identidad, preferencia, proyecto, objetivo, pendiente, restriccion, nota, aprendizaje). Que se entienda solo: quién o qué con su nombre y fecha absoluta («Marco Bianchi, el fotógrafo, cobra 600 €», no «cobra 600 €»; «el 15-10», no «mañana»). Con «creo que…», --duda; lo que deduces tú, --fuente agente.',
|
|
539
539
|
},
|
|
540
|
+
// F15-T2: la VARA de qué guardar, en una sola fuente (la usan el inicio de sesión y el aviso de cierre), para que
|
|
541
|
+
// agentes distintos guarden lo mismo. Concreta y en positivo: "guarda si…", no "¿dijo algo estable?".
|
|
542
|
+
'save.criterios': {
|
|
543
|
+
en: ' Save if something came up this session that will matter NEXT time (to you or a teammate): a decision made, a limit or constraint discovered, a stable user preference, an external fact with a name or figure (client, price, URL, path), a gotcha that cost time and its cause, or a goal or pending item. The bar: would you need it again and is it not already in the code? Then save it. Routine work and this-moment-only details are NOT saved.',
|
|
544
|
+
es: ' Guarda si en esta sesión salió algo que servirá la PRÓXIMA vez (a ti o a un compañero): una decisión tomada, un límite o restricción descubierto, una preferencia estable del usuario, un dato externo con nombre o cifra (cliente, precio, URL, ruta), un tropiezo que costó tiempo y su causa, o un objetivo o pendiente. La vara: ¿lo necesitarías otra vez y no está ya en el código? Entonces va. El trabajo rutinario y lo de este momento NO se guardan.',
|
|
545
|
+
},
|
|
540
546
|
'start.prev': {
|
|
541
547
|
en: '- Previous session ({when}): {parts}. If the user says «continue» or /resume, pick up from there; otherwise do not mention it.',
|
|
542
548
|
es: '- Sesión anterior ({when}): {parts}. Si el usuario dice «sigue» o /retomar, continúa desde ahí; si no, no lo menciones.',
|
package/src/session-start.mjs
CHANGED
|
@@ -51,6 +51,7 @@ try {
|
|
|
51
51
|
L.push(msg('start.map.intro', lang));
|
|
52
52
|
L.push(mapa.hechos ? textoMapa(mapa) : msg('start.map.empty', lang));
|
|
53
53
|
L.push(msg('start.map.consult', lang, { cli }));
|
|
54
|
+
L.push(msg('save.criterios', lang)); // F15-T2: la vara (qué guardar), antes de la sintaxis del comando
|
|
54
55
|
L.push(msg('start.map.save', lang, { cli }));
|
|
55
56
|
} catch { }
|
|
56
57
|
// En qué se quedó la sesión anterior (session-state): para seguir sin que el usuario tenga que contarlo.
|
package/src/session-state.mjs
CHANGED
|
@@ -66,18 +66,36 @@ if (evento === 'Stop') try {
|
|
|
66
66
|
}
|
|
67
67
|
} catch {}
|
|
68
68
|
|
|
69
|
-
// 2. al cerrar: ¿quedó
|
|
69
|
+
// 2. al cerrar: ¿quedó apuntado lo que dijo el usuario?
|
|
70
70
|
if (evento !== 'Stop') process.exit(0);
|
|
71
|
-
const marca = sessionFlag(sid, 'memoria-pendiente');
|
|
72
|
-
if (!fs.existsSync(marca)) process.exit(0);
|
|
73
|
-
let desde = 0; try { desde = fs.statSync(marca).mtimeMs; } catch {}
|
|
74
71
|
const mtime = f => { try { return fs.statSync(f).mtimeMs; } catch { return 0; } };
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
if (
|
|
82
|
-
|
|
72
|
+
|
|
73
|
+
// 2a. regla o corrección pendiente → bloquea UNA vez (es una instrucción del usuario: la vara más alta).
|
|
74
|
+
const marca = sessionFlag(sid, 'memoria-pendiente');
|
|
75
|
+
if (fs.existsSync(marca)) {
|
|
76
|
+
let desde = 0; try { desde = fs.statSync(marca).mtimeMs; } catch {}
|
|
77
|
+
const apuntada = Math.max(memoriaProyecto(root).mtime, mtime(path.join(ruta(root, 'devlog'), 'MEMORIA-historico.md')), mtime(rutaMemoriaUsuario())) >= desde;
|
|
78
|
+
if (!apuntada) {
|
|
79
|
+
const dijo = (() => { try { return fs.readFileSync(marca, 'utf8'); } catch { return ''; } })();
|
|
80
|
+
const razon = `[senzu] El usuario dio una regla o una corrección en esta sesión («${dijo.slice(0, 120)}») y no está en la memoria. `
|
|
81
|
+
+ `Apúntala: de este proyecto → ${rutaRel(root, 'devlog')}/MEMORIA.md; de todos sus proyectos → ${rutaMemoriaUsuario().replace(/\\/g, '/')}. `
|
|
82
|
+
+ 'Si no era una regla duradera, dilo en una línea y cierra.';
|
|
83
|
+
if (p.stop_hook_active !== true && testOnce(sid, 'stop-recordar')) process.stdout.write(JSON.stringify({ decision: 'block', reason: razon }) + '\n');
|
|
84
|
+
else process.stdout.write(JSON.stringify({ systemMessage: razon }) + '\n');
|
|
85
|
+
process.exit(0);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// 2b. (F15-T3) frase con forma de hecho sin guardar → recordatorio SUAVE, NUNCA bloquea (systemMessage).
|
|
90
|
+
// Si la sesión guardó algún hecho (facts.jsonl), editó MEMORIA.md o la memoria del usuario, se calla: ya hubo registro.
|
|
91
|
+
const marcaHecho = sessionFlag(sid, 'hecho-pendiente');
|
|
92
|
+
if (fs.existsSync(marcaHecho)) {
|
|
93
|
+
let desdeH = 0; try { desdeH = fs.statSync(marcaHecho).mtimeMs; } catch {}
|
|
94
|
+
const guardado = Math.max(memoriaProyecto(root).mtime, mtime(rutaHechos(root)), mtime(rutaMemoriaUsuario())) >= desdeH;
|
|
95
|
+
if (!guardado && testOnce(sid, 'stop-hecho')) {
|
|
96
|
+
const dijoH = (() => { try { return fs.readFileSync(marcaHecho, 'utf8'); } catch { return ''; } })();
|
|
97
|
+
process.stdout.write(JSON.stringify({ systemMessage: `[senzu] En esta sesión salió un dato que puede servir la próxima vez («${dijoH.slice(0, 100)}») y no está guardado. `
|
|
98
|
+
+ 'Si vale para la próxima vez, guárdalo (node … --guardar --dimension familia.tema --valor "…"); si era solo de este momento, déjalo.' }) + '\n');
|
|
99
|
+
}
|
|
100
|
+
}
|
|
83
101
|
process.exit(0);
|