corvusmem 0.0.0-stage → 0.1.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/COMMERCIAL.md +17 -0
- package/LICENSE +82 -0
- package/README.md +52 -2
- package/cli/corvusmem.mjs +22 -0
- package/cli/memory-check.mjs +73 -0
- package/cli/memory.mjs +182 -0
- package/cli/search.mjs +344 -0
- package/cortex/cortex-text.mjs +149 -0
- package/cortex/cortex.mjs +781 -0
- package/docs.md +99 -0
- package/install.mjs +162 -0
- package/package.json +43 -4
- package/src/facts-guard.mjs +80 -0
- package/src/facts.mjs +1283 -0
- package/src/file-memory.mjs +45 -0
- package/src/host.mjs +118 -0
- package/src/lib.mjs +1263 -0
- package/src/live-memory.mjs +43 -0
- package/src/live-recall.mjs +73 -0
- package/src/messages.mjs +503 -0
- package/src/session-end.mjs +22 -0
- package/src/session-start.mjs +159 -0
- package/src/session-state.mjs +82 -0
package/COMMERCIAL.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Commercial use of Corvusmem
|
|
2
|
+
|
|
3
|
+
Corvusmem is **free for noncommercial use** (personal, study, hobby, nonprofits, educational/public
|
|
4
|
+
institutions) under the **PolyForm Noncommercial License 1.0.0** (see `LICENSE`). In every case you must
|
|
5
|
+
**keep the credit** (the `Required Notice: Copyright 2026 Peterson Sena` line).
|
|
6
|
+
|
|
7
|
+
**Commercial use requires a separate paid license.** Commercial use includes, among others:
|
|
8
|
+
- integrating it into a product or service you sell or monetize;
|
|
9
|
+
- using it inside a for-profit company for its operations;
|
|
10
|
+
- offering it as part of a paid consultancy or SaaS.
|
|
11
|
+
|
|
12
|
+
## How to get a commercial license
|
|
13
|
+
Write to **Peterson Sena — petersonsena24@gmail.com** stating the intended use (product, scale, company).
|
|
14
|
+
Terms are agreed (price/royalty and the required attribution). Without that license, commercial use is not
|
|
15
|
+
permitted by the public license.
|
|
16
|
+
|
|
17
|
+
> Note: this is not legal advice. The specific commercial terms are set in writing between the parties.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
Required Notice: Copyright 2026 Peterson Sena <petersonsena24@gmail.com>
|
|
2
|
+
|
|
3
|
+
Hemispheric is dual-licensed. Noncommercial use is granted under the PolyForm
|
|
4
|
+
Noncommercial License 1.0.0, reproduced below. COMMERCIAL USE REQUIRES A SEPARATE
|
|
5
|
+
PAID LICENSE from the licensor — see COMMERCIAL.md (contact petersonsena24@gmail.com).
|
|
6
|
+
Any permitted use must keep the "Required Notice" line above.
|
|
7
|
+
|
|
8
|
+
--------------------------------------------------------------------------------
|
|
9
|
+
|
|
10
|
+
# PolyForm Noncommercial License 1.0.0
|
|
11
|
+
|
|
12
|
+
<https://polyformproject.org/licenses/noncommercial/1.0.0>
|
|
13
|
+
|
|
14
|
+
## Acceptance
|
|
15
|
+
|
|
16
|
+
In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
|
|
17
|
+
|
|
18
|
+
## Copyright License
|
|
19
|
+
|
|
20
|
+
The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
|
|
21
|
+
|
|
22
|
+
## Distribution License
|
|
23
|
+
|
|
24
|
+
The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
|
|
25
|
+
|
|
26
|
+
## Notices
|
|
27
|
+
|
|
28
|
+
You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
|
|
29
|
+
|
|
30
|
+
> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
|
|
31
|
+
|
|
32
|
+
## Changes and New Works License
|
|
33
|
+
|
|
34
|
+
The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
|
|
35
|
+
|
|
36
|
+
## Patent License
|
|
37
|
+
|
|
38
|
+
The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
|
|
39
|
+
|
|
40
|
+
## Noncommercial Purposes
|
|
41
|
+
|
|
42
|
+
Any noncommercial purpose is a permitted purpose.
|
|
43
|
+
|
|
44
|
+
## Personal Uses
|
|
45
|
+
|
|
46
|
+
Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose.
|
|
47
|
+
|
|
48
|
+
## Noncommercial Organizations
|
|
49
|
+
|
|
50
|
+
Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding.
|
|
51
|
+
|
|
52
|
+
## Fair Use
|
|
53
|
+
|
|
54
|
+
You may have "fair use" rights for the software under the law. These terms do not limit them.
|
|
55
|
+
|
|
56
|
+
## No Other Rights
|
|
57
|
+
|
|
58
|
+
These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
|
|
59
|
+
|
|
60
|
+
## Patent Defense
|
|
61
|
+
|
|
62
|
+
If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
|
|
63
|
+
|
|
64
|
+
## Violations
|
|
65
|
+
|
|
66
|
+
The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
|
|
67
|
+
|
|
68
|
+
## No Liability
|
|
69
|
+
|
|
70
|
+
***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
|
|
71
|
+
|
|
72
|
+
## Definitions
|
|
73
|
+
|
|
74
|
+
The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
|
|
75
|
+
|
|
76
|
+
**You** refers to the individual or entity agreeing to these terms.
|
|
77
|
+
|
|
78
|
+
**Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
|
|
79
|
+
|
|
80
|
+
**Your licenses** are all the licenses granted to you for the software under these terms.
|
|
81
|
+
|
|
82
|
+
**Use** means anything you do with the software requiring one of your licenses.
|
package/README.md
CHANGED
|
@@ -1,3 +1,53 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="https://raw.githubusercontent.com/petersonsenadevs/Corvusmem-claude-codex/main/assets/crow.png" alt="Corvusmem — the crow that remembers" width="200" />
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
# Corvusmem
|
|
6
|
+
|
|
7
|
+
**Deterministic, offline, zero-dependency memory for AI coding agents.** Corvusmem stores the stable facts your
|
|
8
|
+
agent learns, replaces and dates them, and recalls them the same way every time — in any language, with no network
|
|
9
|
+
and no servers. It plugs into where you already work: Claude Code / Codex (hooks) and a standalone CLI.
|
|
10
|
+
|
|
11
|
+
> **Narrative docs (what it is, the message, the Cortex, FAQ):** [`docs.md`](./docs.md). This README is the quick
|
|
12
|
+
> reference for structure and commands.
|
|
13
|
+
|
|
14
|
+
## How it works
|
|
15
|
+
Your agent forgets everything between sessions. Corvusmem is a memory it keeps: facts live in a lightweight local
|
|
16
|
+
graph, retrieved by name, date and relevance with two-hop activation — no embeddings, no vector database, no API key.
|
|
17
|
+
Same input, same result. The whole memory is a file you own.
|
|
18
|
+
|
|
19
|
+
## Structure
|
|
20
|
+
- `src/` — the core: the facts engine (`facts.mjs`), shared base (`lib`, `messages`, `session-end`), host detection
|
|
21
|
+
(`host.mjs`) and the brain hooks (`live-recall`, `session-start`, `session-state`, `live-memory`,
|
|
22
|
+
`file-memory`, `facts-guard`). Same-directory imports only: self-contained, zero external dependencies.
|
|
23
|
+
- `cli/` — `memory.mjs`: the command line (`--save` / `--search` / `--recall` / `--context` / `--cortex`).
|
|
24
|
+
- `cortex/` — `cortex.mjs` + `cortex-text.mjs`: your memory as a local HTML page (the "Cortex"), no network.
|
|
25
|
+
- `tests/` — deterministic, LLM-free suites: `test-boundary` (clean core), `test-facts` (engine), `test-hard-recall`.
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
```
|
|
29
|
+
npx corvusmem install --claude # register the hooks in the current project's .claude/settings.json
|
|
30
|
+
npx corvusmem install --global # for every project (~/.claude/settings.json)
|
|
31
|
+
npx corvusmem uninstall # remove Corvusmem's hooks (leaves everything else intact)
|
|
32
|
+
npx corvusmem install --dry-run # show what it would do, without writing
|
|
33
|
+
```
|
|
34
|
+
Merge-safe (it never overwrites your hooks or permissions) and idempotent. It creates `.corvusmem/` (project
|
|
35
|
+
memory) and `~/.config/corvusmem/` (global memory), and writes `.corvusmem/hooks.json` (a portable manifest).
|
|
36
|
+
|
|
37
|
+
**Codex**: the hooks run through the plugin path (a marketplace in `~/.codex/config.toml`), not the project
|
|
38
|
+
`settings.json`. Publish it to a Codex marketplace, install it and approve the hooks in the app. On Claude Code they
|
|
39
|
+
are active right away.
|
|
40
|
+
|
|
41
|
+
## Test
|
|
42
|
+
```
|
|
43
|
+
npm test
|
|
44
|
+
```
|
|
45
|
+
(or `node tests/test-boundary.mjs && node tests/test-facts.mjs && node tests/test-hard-recall.mjs`)
|
|
46
|
+
|
|
47
|
+
## License
|
|
48
|
+
Dual-licensed (© 2026 Peterson Sena):
|
|
49
|
+
- **Noncommercial use** (personal, study, hobby, nonprofit, education/public sector): free under **PolyForm
|
|
50
|
+
Noncommercial 1.0.0** (`LICENSE`), keeping the credit (`Required Notice`).
|
|
51
|
+
- **Commercial use**: requires a separate **paid license** — see `COMMERCIAL.md` (petersonsena24@gmail.com).
|
|
52
|
+
|
|
53
|
+
This is not legal advice; for final commercial terms, consult a professional.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Despachador del CLI `corvusmem`: el subcomando decide a quién llama.
|
|
3
|
+
// corvusmem install [--claude|--codex|--global|--plugin <dir>...] -> install.mjs (instalar/empaquetar)
|
|
4
|
+
// corvusmem uninstall [...] -> install.mjs --uninstall
|
|
5
|
+
// corvusmem <lo que sea> -> cli/memory.mjs (la CLI de memoria)
|
|
6
|
+
// Asi `npx corvusmem install --claude` funciona una vez publicado (npm) o con el repo publico (npx github:...).
|
|
7
|
+
import { spawnSync } from 'node:child_process';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
|
|
11
|
+
const AQUI = path.dirname(fileURLToPath(import.meta.url));
|
|
12
|
+
const ROOT = path.join(AQUI, '..');
|
|
13
|
+
const argv = process.argv.slice(2);
|
|
14
|
+
const sub = argv[0];
|
|
15
|
+
|
|
16
|
+
let destino, args;
|
|
17
|
+
if (sub === 'install') { destino = path.join(ROOT, 'install.mjs'); args = argv.slice(1); }
|
|
18
|
+
else if (sub === 'uninstall') { destino = path.join(ROOT, 'install.mjs'); args = ['--uninstall', ...argv.slice(1)]; }
|
|
19
|
+
else { destino = path.join(ROOT, 'cli', 'memory.mjs'); args = argv; }
|
|
20
|
+
|
|
21
|
+
const r = spawnSync(process.execPath, [destino, ...args], { stdio: 'inherit' });
|
|
22
|
+
process.exit(r.status == null ? 1 : r.status);
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Revisa la memoria del proyecto (senzu/devlog/MEMORIA.md) y avisa de lo que la estropea con el tiempo:
|
|
3
|
+
// - más de 60 líneas (lo sustituido y lo cerrado va a MEMORIA-historico.md);
|
|
4
|
+
// - «ver NNN» que no existe en el devlog; D-xxx repetidos; huecos en la numeración (aviso suave);
|
|
5
|
+
// - pendientes con fecha «[desde AAAA-MM-DD]» abiertos hace más de N días (--dias, 7 por defecto);
|
|
6
|
+
// - pendientes SIN fecha (no se puede saber si caducaron);
|
|
7
|
+
// - rutas entre acentos graves que ya no existen en el proyecto.
|
|
8
|
+
// Ejecutar desde la RAÍZ del proyecto: node <skills-dir>/devlog/scripts/memory-check.mjs [--dias 7]
|
|
9
|
+
// Sale con 1 si hay algo que arreglar (0 si está sana).
|
|
10
|
+
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
|
|
14
|
+
const args = process.argv.slice(2);
|
|
15
|
+
const dias = parseInt(args[args.indexOf('--dias') + 1], 10) || 7;
|
|
16
|
+
const root = process.cwd();
|
|
17
|
+
const dl = ['senzu/devlog', 'devlog'].map(d => path.join(root, d)).find(d => fs.existsSync(d));
|
|
18
|
+
const out = s => process.stdout.write(s + '\n');
|
|
19
|
+
if (!dl) { out('[memoria] No hay devlog en este proyecto (senzu/devlog).'); process.exit(0); }
|
|
20
|
+
const memF = path.join(dl, 'MEMORIA.md');
|
|
21
|
+
if (!fs.existsSync(memF)) { out(`[memoria] No hay ${path.relative(root, memF)}: créala con la skill devlog (references/memoria.md).`); process.exit(1); }
|
|
22
|
+
|
|
23
|
+
const txt = fs.readFileSync(memF, 'utf8').replace(/^/, '').replace(/\r/g, '').replace(/<!--[\s\S]*?-->/g, '');
|
|
24
|
+
const lineas = txt.split('\n').filter(l => l.trim());
|
|
25
|
+
const avisos = [];
|
|
26
|
+
const cuerpo = lineas.filter(l => !/^#/.test(l.trim()));
|
|
27
|
+
if (cuerpo.length > 60) avisos.push(`tiene ${cuerpo.length} líneas (máximo 60): mueve lo sustituido y lo cerrado a MEMORIA-historico.md`);
|
|
28
|
+
|
|
29
|
+
const nums = new Set();
|
|
30
|
+
for (const d of fs.readdirSync(dl)) {
|
|
31
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(d)) continue;
|
|
32
|
+
for (const f of fs.readdirSync(path.join(dl, d))) { const m = /^(\d{3,})-/.exec(f); if (m) nums.add(m[1]); }
|
|
33
|
+
}
|
|
34
|
+
const rotas = [...new Set(lineas.flatMap(l => [...l.matchAll(/\bver\s+(\d{3,})\b/gi)].map(m => m[1])))].filter(n => !nums.has(n));
|
|
35
|
+
if (rotas.length) avisos.push(`cita entradas que no existen: ${rotas.map(n => 'ver ' + n).join(', ')}`);
|
|
36
|
+
|
|
37
|
+
const ids = lineas.map(l => (/^\s*[-*]\s+D-(\d+)\s*·/.exec(l) || [])[1]).filter(Boolean).map(Number);
|
|
38
|
+
const repes = [...new Set(ids.filter((d, i) => ids.indexOf(d) !== i))];
|
|
39
|
+
if (repes.length) avisos.push(`números de decisión repetidos: ${repes.map(n => 'D-' + String(n).padStart(3, '0')).join(', ')}`);
|
|
40
|
+
|
|
41
|
+
const pend = (/^##\s+Pendientes[^\n]*\n([\s\S]*?)(?=^##\s|(?![\s\S]))/m.exec(txt) || [])[1] || '';
|
|
42
|
+
const hoy = Date.now();
|
|
43
|
+
const viejos = [], sinFecha = [];
|
|
44
|
+
for (const l of pend.split('\n').filter(x => /^\s*[-*]\s+\S/.test(x))) {
|
|
45
|
+
const m = /\[desde (\d{4}-\d{2}-\d{2})\]/.exec(l);
|
|
46
|
+
const corto = l.replace(/^\s*[-*]\s*/, '').replace(/\[desde [^\]]+\]\s*/, '').slice(0, 80);
|
|
47
|
+
if (!m) { sinFecha.push(corto); continue; }
|
|
48
|
+
const d = Math.floor((hoy - Date.parse(m[1] + 'T00:00:00')) / 864e5);
|
|
49
|
+
if (d >= dias) viejos.push(`${corto} (${d} días)`);
|
|
50
|
+
}
|
|
51
|
+
if (viejos.length) avisos.push(`pendientes abiertos hace más de ${dias} días (¿siguen vigentes?): ${viejos.join(' · ')}`);
|
|
52
|
+
if (sinFecha.length) avisos.push(`pendientes sin fecha (escríbelos «- [desde AAAA-MM-DD] …»): ${sinFecha.join(' · ')}`);
|
|
53
|
+
|
|
54
|
+
const rutas = [...new Set(lineas.flatMap(l => [...l.matchAll(/`([\w./-]+\/[\w.-]+\.[a-z0-9]{1,5})`/gi)].map(m => m[1])))];
|
|
55
|
+
const perdidas = rutas.filter(r => !/[<>*]/.test(r) && !fs.existsSync(path.join(root, r)));
|
|
56
|
+
if (perdidas.length) avisos.push(`rutas que ya no existen en el proyecto: ${perdidas.join(', ')} (¿se movieron? actualiza la línea o pásala al histórico)`);
|
|
57
|
+
|
|
58
|
+
// Decisiones que citan un valor que un hecho ya sustituyó (motor de hechos, hooks/facts.mjs). Sin el motor, se omite.
|
|
59
|
+
{
|
|
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));
|
|
62
|
+
if (motor) {
|
|
63
|
+
try {
|
|
64
|
+
const { decisionesObsoletas } = await import(new URL('file:///' + motor.replace(/\\/g, '/').replace(/^\//, '')).href);
|
|
65
|
+
for (const o of decisionesObsoletas(root)) avisos.push(`${o.decision} cita «${o.valorViejo}», pero el hecho ${o.dimension} ahora es «${o.valorNuevo}»: ¿sigue vigente esa decisión? Actualízala (o pásala al histórico como sustituida)`);
|
|
66
|
+
} catch { }
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (!avisos.length) { out(`[memoria] ${path.relative(root, memF)}: sana (${cuerpo.length} líneas, ${ids.length} decisiones).`); process.exit(0); }
|
|
71
|
+
out(`[memoria] ${path.relative(root, memF)}: ${avisos.length} aviso(s)`);
|
|
72
|
+
for (const a of avisos) out(` - ${a}`);
|
|
73
|
+
process.exit(1);
|
package/cli/memory.mjs
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Memoria de HECHOS (determinista, en cualquier idioma, sin red): lo que el usuario afirma de forma estable.
|
|
3
|
+
// El agente entiende la frase (en el idioma que sea) y la guarda estructurada; el motor la sustituye, la fecha y la
|
|
4
|
+
// recupera siempre igual. Para buscar entre idiomas, añade --claves en otros idiomas (p. ej. en inglés y en el del usuario).
|
|
5
|
+
// node memory.mjs --guardar --dimension identidad.ubicacion --valor "Málaga" [--texto "vivo en Málaga"]
|
|
6
|
+
// [--claves "ciudad,city,vive,lives"] [--idioma es] [--alcance proyecto|usuario] [--duda] [--fuente usuario|agente|devlog] [--desde AAAA-MM-DD] [--hasta AAAA-MM-DD]
|
|
7
|
+
// node memory.mjs --buscar "dónde vive" [--historico] [--limite 8] [--json]
|
|
8
|
+
// node memory.mjs --contexto [--presupuesto 12] lo vigente, repartido por familias (lo usa el inicio de sesión)
|
|
9
|
+
// node memory.mjs --lista [--todo] | --olvidar <id>
|
|
10
|
+
// node memory.mjs --nada [--motivo "…"] revisado: nada estable que guardar en esta sesión
|
|
11
|
+
// node memory.mjs --enlazar <dimensión A> <dimensión B> (o --enlaces A,B al guardar): al recordar uno, llega el otro
|
|
12
|
+
// node memory.mjs --informe [--dias 30] [--json] el uso REAL: qué se inyectó, si sirvió, el ruido y los silencios
|
|
13
|
+
// node memory.mjs --cortex [--cliente] [--salida <carpeta>] [--idioma es|en|pt|fr|de|it] la memoria en un HTML local, sin red
|
|
14
|
+
// Dimensiones: «familia.tema» libre (identidad.nombre, proyecto.stack, preferencia.gestor-paquetes, restriccion.presupuesto…).
|
|
15
|
+
// Un valor nuevo en la misma dimensión SUSTITUYE al anterior (queda en el histórico); objetivo.*, pendiente.*, nota.*,
|
|
16
|
+
// hecho.* y aprendizaje.* acumulan. --duda: el usuario no lo afirmó del todo («creo que…»): se guarda sin sustituir.
|
|
17
|
+
import fs from 'node:fs';
|
|
18
|
+
import path from 'node:path';
|
|
19
|
+
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
20
|
+
|
|
21
|
+
const AQUI = path.dirname(fileURLToPath(import.meta.url));
|
|
22
|
+
const args = process.argv.slice(2);
|
|
23
|
+
// F14: flags en inglés (primarios) con alias en castellano. Se normalizan a la forma interna (castellano) para no
|
|
24
|
+
// tocar el resto del código; los flags en castellano siguen funcionando EXACTAMENTE igual.
|
|
25
|
+
const ALIAS_FLAG = {
|
|
26
|
+
'--save': '--guardar', '--search': '--buscar', '--recall': '--recordar', '--context': '--contexto',
|
|
27
|
+
'--list': '--lista', '--forget': '--olvidar', '--resolve': '--resolver', '--abandon': '--abandonar',
|
|
28
|
+
'--open': '--abiertos', '--in-progress': '--en-curso', '--doubt': '--duda', '--source': '--fuente',
|
|
29
|
+
'--value': '--valor', '--keys': '--claves', '--scope': '--alcance', '--lang': '--idioma',
|
|
30
|
+
'--history': '--historico', '--since': '--desde', '--until': '--hasta', '--days': '--dias',
|
|
31
|
+
'--limit': '--limite', '--budget': '--presupuesto', '--reason': '--motivo', '--link': '--enlazar',
|
|
32
|
+
'--links': '--enlaces', '--client': '--cliente', '--text': '--texto', '--report': '--informe',
|
|
33
|
+
'--output': '--salida', '--all': '--todo', '--none': '--nada', '--as': '--como', '--author': '--autor',
|
|
34
|
+
};
|
|
35
|
+
const ALIAS_VAL = { user: 'usuario', project: 'proyecto', agent: 'agente' }; // valores de enum en inglés
|
|
36
|
+
for (let i = 0; i < args.length; i++) if (ALIAS_FLAG[args[i]]) args[i] = ALIAS_FLAG[args[i]];
|
|
37
|
+
for (let i = 0; i < args.length; i++) if ((args[i] === '--alcance' || args[i] === '--fuente') && ALIAS_VAL[args[i + 1]]) args[i + 1] = ALIAS_VAL[args[i + 1]];
|
|
38
|
+
const opt = n => { const i = args.indexOf(n); return i >= 0 ? (args[i + 1] !== undefined && !args[i + 1].startsWith('--') ? args[i + 1] : true) : null; };
|
|
39
|
+
const rutaPedida = String(opt('--path') && opt('--path') !== true ? opt('--path') : process.env.CLAUDE_PROJECT_DIR || process.cwd());
|
|
40
|
+
let root = path.resolve(rutaPedida); // provisional: para encontrar el motor; abajo, normalizada como en los hooks
|
|
41
|
+
const out = s => process.stdout.write(s + '\n');
|
|
42
|
+
|
|
43
|
+
async function motor() { // facts.mjs de los hooks: junto a la skill (plugin o .claude), o en el paquete de Senzu
|
|
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'),
|
|
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
|
+
for (const f of c) if (fs.existsSync(f)) return import(pathToFileURL(f).href);
|
|
48
|
+
out('No encuentro el motor de hechos (hooks/facts.mjs). ¿Está instalado? Ejecuta: npx corvusmem install');
|
|
49
|
+
process.exit(2);
|
|
50
|
+
}
|
|
51
|
+
const m = await motor();
|
|
52
|
+
root = m.rutaNativa ? m.rutaNativa(rutaPedida) : root; // /c/… de Git Bash, C:/ o barra final → la misma carpeta
|
|
53
|
+
const fecha = s => String(s || '').slice(0, 10);
|
|
54
|
+
const linea = h => `- [${h.dimension}] ${h.valor}${h.estado !== 'activo' ? ` (${h.estado}${h.hasta ? ' ' + fecha(h.hasta) : ''})` : ''}${h.desde ? ` · desde ${fecha(h.desde)}` : ''}${h.autor ? ` · de ${h.autor}` : ''}${h.devlog ? ` · ver ${h.devlog}` : ''} · ${h.alcance} · ${h.id}`;
|
|
55
|
+
|
|
56
|
+
if (opt('--guardar')) {
|
|
57
|
+
let r;
|
|
58
|
+
try { r = m.guardarHecho(root, {
|
|
59
|
+
dimension: opt('--dimension'), valor: opt('--valor'), texto: opt('--texto') === true ? undefined : opt('--texto'),
|
|
60
|
+
claves: opt('--claves') && opt('--claves') !== true ? String(opt('--claves')).split(',') : [], idioma: opt('--idioma') || undefined,
|
|
61
|
+
devlog: opt('--devlog') && opt('--devlog') !== true ? String(opt('--devlog')) : undefined, // por defecto, la entrada de hoy
|
|
62
|
+
enlaces: opt('--enlaces') && opt('--enlaces') !== true ? String(opt('--enlaces')).split(',') : [], // dimensiones relacionadas
|
|
63
|
+
alcance: opt('--alcance') || 'proyecto', duda: !!opt('--duda'),
|
|
64
|
+
autor: opt('--autor') && opt('--autor') !== true ? String(opt('--autor')) : undefined, // multiusuario (F14); si no, se autodetecta
|
|
65
|
+
fuente: opt('--fuente') && opt('--fuente') !== true ? String(opt('--fuente')) : 'usuario', // usuario | agente | devlog
|
|
66
|
+
desde: opt('--desde') && opt('--desde') !== true ? new Date(opt('--desde')).toISOString() : undefined,
|
|
67
|
+
hasta: opt('--hasta') && opt('--hasta') !== true ? new Date(opt('--hasta')).toISOString() : undefined,
|
|
68
|
+
}); } catch (e) { out(`No guardado: ${e.message}`); process.exit(2); } // p. ej. una familia fuera de la convención
|
|
69
|
+
if (opt('--json')) { out(JSON.stringify(r, null, 2)); process.exit(0); }
|
|
70
|
+
const que = { nuevo: 'Guardado', 'ya-estaba': 'Ya estaba (no se duplica)', sustituye: 'Guardado y sustituye a lo anterior', dudoso: 'Guardado como dudoso (no sustituye nada)' }[r.accion];
|
|
71
|
+
out(`${que}: ${linea(r.hecho)}`);
|
|
72
|
+
for (const s of r.sustituidos) out(` sustituido: ${linea(s)}`);
|
|
73
|
+
for (const a of r.avisos || []) out(a.tipo === 'casi-duplicado'
|
|
74
|
+
? ` ojo, casi duplicado (${a.motivo}): ${linea(a.hecho)} → si es lo mismo, --olvidar uno de los dos`
|
|
75
|
+
: a.tipo === 'contradice' ? ` ojo, contradice (${a.motivo}): ${linea(a.hecho)} → pregunta al usuario cuál vale`
|
|
76
|
+
: a.tipo === 'autocontenido' ? ` ojo, ¿se entiende solo? ${a.motivo}`
|
|
77
|
+
: a.tipo === 'misma-dimension' ? ` ojo, ¿misma dimensión? ${a.motivo}: ${linea(a.hecho)}`
|
|
78
|
+
: ` convención: ${a.motivo}`);
|
|
79
|
+
process.exit(0);
|
|
80
|
+
}
|
|
81
|
+
if (opt('--buscar')) {
|
|
82
|
+
const hits = m.buscarHechos(root, String(opt('--buscar')), { historico: !!opt('--historico'), limite: Number(opt('--limite')) || 8 });
|
|
83
|
+
if (m.anotarUso) m.anotarUso(root, hits.map(x => x.hecho.id));
|
|
84
|
+
// X-T11: lo que busca el propio agente se apunta (sin sesión: al cerrar, se asigna al turno por la hora) y, si lo
|
|
85
|
+
// usa, el hecho aprende las palabras con que preguntó el usuario
|
|
86
|
+
if (m.apuntarInyeccion) m.apuntarInyeccion(root, { sid: 'cli', origen: 'consulta', consulta: String(opt('--buscar')), items: hits.map(x => ({ fuente: 'hecho', id: x.hecho.id, texto: `[${x.hecho.dimension}] ${x.hecho.valor}`, puntuacion: x.puntuacion })) });
|
|
87
|
+
if (opt('--json')) { out(JSON.stringify(hits, null, 2)); process.exit(0); }
|
|
88
|
+
if (!hits.length) { out('Nada en la memoria de hechos para eso. Dilo así: no lo supongas.'); process.exit(0); }
|
|
89
|
+
for (const x of hits) out(`${linea(x.hecho)}\n ${x.motivo}`);
|
|
90
|
+
process.exit(0);
|
|
91
|
+
}
|
|
92
|
+
if (opt('--recordar')) { // las tres memorias a la vez: hechos, MEMORIA.md y devlog
|
|
93
|
+
const l = m.recuerdo(root, String(opt('--recordar')), { historico: !!opt('--historico'), limite: Number(opt('--limite')) || 6 });
|
|
94
|
+
if (m.anotarUso) m.anotarUso(root, l.filter(x => x.fuente === 'hecho').map(x => x.id));
|
|
95
|
+
if (m.apuntarInyeccion) m.apuntarInyeccion(root, { sid: 'cli', origen: 'consulta', consulta: String(opt('--recordar')), items: l });
|
|
96
|
+
if (opt('--json')) { out(JSON.stringify(l, null, 2)); process.exit(0); }
|
|
97
|
+
if (!l.length) { out('Nada en hechos, memoria ni devlog para eso. Dilo así: no lo supongas.'); process.exit(0); }
|
|
98
|
+
for (const x of l) out(`[${x.fuente}] ${x.texto}${x.ver && !new RegExp(`\\bver ${x.ver}\\b`).test(x.texto) ? ` · ver ${x.ver}` : ''}\n ${x.motivo}`);
|
|
99
|
+
process.exit(0);
|
|
100
|
+
}
|
|
101
|
+
if (opt('--contexto')) {
|
|
102
|
+
const l = m.contextoHechos(root, { presupuesto: Number(opt('--presupuesto')) || 12 });
|
|
103
|
+
if (opt('--json')) { out(JSON.stringify(l, null, 2)); process.exit(0); }
|
|
104
|
+
out(l.length ? l.map(linea).join('\n') : 'Sin hechos guardados.');
|
|
105
|
+
process.exit(0);
|
|
106
|
+
}
|
|
107
|
+
if (opt('--lista')) {
|
|
108
|
+
const l = m.todosLosHechos(root).filter(h => opt('--todo') || h.estado === 'activo' || h.estado === 'dudoso');
|
|
109
|
+
out(l.length ? l.map(linea).join('\n') : 'Sin hechos guardados.');
|
|
110
|
+
process.exit(0);
|
|
111
|
+
}
|
|
112
|
+
// objetivos y pendientes: --en-curso <id|dimensión> · --resolver <id|dimensión> [--como "…"] · --abandonar <id|dimensión> [--motivo "…"]
|
|
113
|
+
for (const [flag, progreso, titulo] of [['--en-curso', 'en-curso', 'En curso'], ['--resolver', 'resuelto', 'Resuelto'], ['--abandonar', 'abandonado', 'Abandonado']]) {
|
|
114
|
+
if (!opt(flag)) continue;
|
|
115
|
+
const ref = String(opt(flag)), nota = [opt('--como'), opt('--motivo')].find(x => x && x !== true);
|
|
116
|
+
let h = null;
|
|
117
|
+
try { h = ref !== 'true' ? m.cambiarProgreso(root, ref, progreso, nota) : null; } catch (e) { out(e.message); process.exit(2); }
|
|
118
|
+
out(h ? `${titulo}: ${linea(h)}${nota ? ` — ${nota}` : ''}` : 'No hay un objetivo o pendiente ABIERTO con ese id o dimensión (solo objetivo.* y pendiente.* tienen ciclo de vida).');
|
|
119
|
+
process.exit(h ? 0 : 2);
|
|
120
|
+
}
|
|
121
|
+
if (opt('--abiertos')) { // objetivos y pendientes abiertos, los más antiguos primero
|
|
122
|
+
const l = m.abiertos(root);
|
|
123
|
+
out(l.length ? l.map(h => `${linea(h)} · abierto desde ${fecha(h.creado)}${h.progreso === 'en-curso' ? ' (en curso)' : ''}`).join('\n') : 'No hay objetivos ni pendientes abiertos.');
|
|
124
|
+
process.exit(0);
|
|
125
|
+
}
|
|
126
|
+
if (opt('--enlazar')) { // --enlazar <dimensión A> <dimensión B>: al recordar A, llega también lo vigente de B (y al revés)
|
|
127
|
+
const i = args.indexOf('--enlazar'), a = args[i + 1], b = args[i + 2];
|
|
128
|
+
const h = a && b && !a.startsWith('--') && !b.startsWith('--') ? m.enlazarHechos(root, a, b) : null;
|
|
129
|
+
out(h ? `Enlazado: ${linea(h)} → [${m.claveDimension(b)}]` : 'No hay un hecho vigente en esa dimensión (o faltan las dos dimensiones).');
|
|
130
|
+
process.exit(h ? 0 : 2);
|
|
131
|
+
}
|
|
132
|
+
if (opt('--nada')) { // revisado: el usuario no dijo nada estable que guardar (cuenta como revisión para el cierre)
|
|
133
|
+
out('Revisado: nada nuevo que guardar en la memoria' + (opt('--motivo') && opt('--motivo') !== true ? ` (${opt('--motivo')})` : '') + '.');
|
|
134
|
+
process.exit(0);
|
|
135
|
+
}
|
|
136
|
+
if (opt('--olvidar')) {
|
|
137
|
+
const h = m.olvidarHecho(root, String(opt('--olvidar')));
|
|
138
|
+
out(h ? `Olvidado (queda en el archivo como invalidado): ${linea(h)}` : 'No existe ese id.');
|
|
139
|
+
process.exit(h ? 0 : 2);
|
|
140
|
+
}
|
|
141
|
+
if (opt('--informe')) { // X-T4: el uso REAL (lo que se inyectó en las sesiones y si el agente lo usó)
|
|
142
|
+
if (!m.informeUso) { out('Este Senzu no trae el informe de uso todavía: actualízalo.'); process.exit(2); }
|
|
143
|
+
const dias = Number(opt('--dias')) || 30;
|
|
144
|
+
const r = m.informeUso(root, { dias });
|
|
145
|
+
if (opt('--json')) { out(JSON.stringify(r, null, 2)); process.exit(0); }
|
|
146
|
+
if (!r.mensajes) { out(`Sin registro de uso en los últimos ${dias} días: se llena solo al hablar con el agente (senzu/.estado/recuerdo-uso.jsonl).`); process.exit(0); }
|
|
147
|
+
out(`Uso real de la memoria (últimos ${dias} días)`);
|
|
148
|
+
out(` Mensajes con recuerdo: ${r.conRecuerdo} · silencios (nada que decir): ${r.silencios}`);
|
|
149
|
+
out(` Recuerdos inyectados: ${r.inyectados} · usados: ${r.usados} · ignorados: ${r.ignorados} · sin datos: ${r.sinDatos}`
|
|
150
|
+
+ (r.precision != null ? ` · precisión real: ${r.precision} %` : ''));
|
|
151
|
+
if (r.debiles.usados + r.debiles.ignorados) out(` Relaciones débiles: usadas ${r.debiles.usados} · ignoradas ${r.debiles.ignorados}`);
|
|
152
|
+
if (r.ruido.length) { out(' Lo que más se ignora (posible ruido):'); for (const x of r.ruido) out(` - [${x.fuente}] ${x.texto} (ignorado ${x.ignorado}, usado ${x.usado})`); }
|
|
153
|
+
if (r.ignoradosRecientes.length) { out(' Ignorados recientes:'); for (const x of r.ignoradosRecientes) out(` - «${x.consulta}» → ${x.texto}`); }
|
|
154
|
+
if (r.silenciosRecientes.length) { out(' Silencios recientes (¿había algo que recordar?):'); for (const x of r.silenciosRecientes) out(` - «${x.consulta}»`); }
|
|
155
|
+
if (r.busquedas) out(` Búsquedas del propio agente (--recordar/--buscar): ${r.busquedas}`);
|
|
156
|
+
if (r.aprendido && r.aprendido.length) {
|
|
157
|
+
out(' Aprendido del uso (palabras del usuario que ya traen el hecho; ×2 o más, confirmadas):');
|
|
158
|
+
for (const x of r.aprendido) out(` - [${x.dimension}] ${x.valor}: ${Object.entries(x.palabras).map(([w, n]) => n > 1 ? `${w} ×${n}` : w).join(', ')}`);
|
|
159
|
+
}
|
|
160
|
+
process.exit(0);
|
|
161
|
+
}
|
|
162
|
+
if (opt('--cortex')) { // Cortex: la memoria en un HTML local, sin red; --cliente: sin nada privado, para enseñarlo
|
|
163
|
+
if (!m.datosCortex) { out('Este Senzu no trae Cortex todavía: actualízalo.'); process.exit(2); }
|
|
164
|
+
const cliente = !!opt('--cliente');
|
|
165
|
+
const cortexFile = [path.join(AQUI, '..', 'cortex', 'cortex.mjs'), path.join(AQUI, 'cortex.mjs')].find(f => fs.existsSync(f));
|
|
166
|
+
const { htmlCortex } = await import(pathToFileURL(cortexFile).href);
|
|
167
|
+
const datos = m.datosCortex(root, { cliente });
|
|
168
|
+
const dir = opt('--salida') && opt('--salida') !== true ? path.resolve(String(opt('--salida'))) : m.ruta(root, 'cortex');
|
|
169
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
170
|
+
// la memoria es privada: la carpeta se ignora a sí misma en git (nadie la commitea por descuido)
|
|
171
|
+
const gi = path.join(dir, '.gitignore');
|
|
172
|
+
if (!fs.existsSync(gi)) fs.writeFileSync(gi, '# Cortex: memoria privada del proyecto, generada. No se versiona.\n*\n');
|
|
173
|
+
const file = path.join(dir, cliente ? 'cliente.html' : 'index.html');
|
|
174
|
+
fs.writeFileSync(file, htmlCortex(datos, { cli: fileURLToPath(import.meta.url), idioma: opt('--idioma') && opt('--idioma') !== true ? String(opt('--idioma')).slice(0, 2).toLowerCase() : null }));
|
|
175
|
+
const n = Object.values(datos.zonas).reduce((s, l) => s + l.length, 0);
|
|
176
|
+
out(`Cortex${cliente ? ' (vista para el cliente)' : ''}: ${file}`);
|
|
177
|
+
out(` ${n} recuerdos · ${datos.cambios.length} cambios en 7 días · ${datos.abiertos.length} abiertos. Ábrelo en el navegador (funciona sin red).`);
|
|
178
|
+
if (!cliente) out(' Tiene datos privados: para enseñarlo, genera la vista para el cliente con --cortex --cliente.');
|
|
179
|
+
process.exit(0);
|
|
180
|
+
}
|
|
181
|
+
out('Usage: --save --dimension <family.topic> --value <text> [--keys a,b] [--scope user] [--doubt] | --search <query> [--history] | --context | --list [--all] | --forget <id> | --cortex [--client] [--output <dir>]');
|
|
182
|
+
process.exit(2);
|