@designerbyron/lifecode-rag 0.0.0-stage → 1.0.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.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +191 -2
  3. package/bin/lifecode-rag.mjs +449 -0
  4. package/client.js +2801 -0
  5. package/cordis.patch.yml +3 -0
  6. package/docs/ARCHITECTURE-v0.2.md +269 -0
  7. package/docs/AUTO-DISCOVERY.md +111 -0
  8. package/docs/AUTOMATION-POLICIES.md +232 -0
  9. package/docs/CONTRATO-v0.1.md +195 -0
  10. package/docs/EMBEDDING-PROVIDERS.md +105 -0
  11. package/docs/OBSERVABILITY.md +241 -0
  12. package/docs/PA-UI-0-API-CONTRACT.md +802 -0
  13. package/docs/PERFORMANCE-BUDGETS.md +118 -0
  14. package/docs/PROJECT-AWARE-ARCHITECTURE.md +580 -0
  15. package/docs/PROJECT-AWARE-DATA-CONTRACT.md +411 -0
  16. package/docs/PROJECT-AWARE-ERROR-CONTRACT.md +112 -0
  17. package/docs/PROJECT-AWARE-SESSION-CONTRACT.md +120 -0
  18. package/docs/WORKSPACE-API.md +239 -0
  19. package/icon.svg +7 -0
  20. package/index.js +198 -0
  21. package/lib/audit-export.mjs +70 -0
  22. package/lib/audit.mjs +120 -0
  23. package/lib/auto-context.mjs +322 -0
  24. package/lib/automation.mjs +214 -0
  25. package/lib/chunk.mjs +100 -0
  26. package/lib/config-resolve.mjs +119 -0
  27. package/lib/context.mjs +150 -0
  28. package/lib/conversation-events.mjs +145 -0
  29. package/lib/db.mjs +309 -0
  30. package/lib/diagnose.mjs +197 -0
  31. package/lib/discovery.mjs +402 -0
  32. package/lib/doctor.mjs +82 -0
  33. package/lib/embed.mjs +96 -0
  34. package/lib/embedders.mjs +103 -0
  35. package/lib/errors.mjs +227 -0
  36. package/lib/exec-context.mjs +238 -0
  37. package/lib/extract.mjs +260 -0
  38. package/lib/harness-workspaces.mjs +85 -0
  39. package/lib/hash.mjs +34 -0
  40. package/lib/ingest.mjs +239 -0
  41. package/lib/inputs.mjs +67 -0
  42. package/lib/library-state.mjs +252 -0
  43. package/lib/maintenance.mjs +113 -0
  44. package/lib/metrics.mjs +164 -0
  45. package/lib/migrate.mjs +373 -0
  46. package/lib/operations.mjs +132 -0
  47. package/lib/pa-api.mjs +517 -0
  48. package/lib/paths.mjs +345 -0
  49. package/lib/policy.mjs +125 -0
  50. package/lib/profile.mjs +128 -0
  51. package/lib/readmodel.mjs +159 -0
  52. package/lib/recovery.mjs +557 -0
  53. package/lib/registry-schema.mjs +206 -0
  54. package/lib/registry.mjs +406 -0
  55. package/lib/resolve.mjs +311 -0
  56. package/lib/retention.mjs +143 -0
  57. package/lib/revocation.mjs +124 -0
  58. package/lib/roots-structure.mjs +224 -0
  59. package/lib/schema.mjs +173 -0
  60. package/lib/scope-ops.mjs +379 -0
  61. package/lib/scope-stores.mjs +128 -0
  62. package/lib/search.mjs +345 -0
  63. package/lib/selection.mjs +150 -0
  64. package/lib/server.mjs +335 -0
  65. package/lib/session-identity.mjs +51 -0
  66. package/lib/sessions.mjs +343 -0
  67. package/lib/sync-scheduler.mjs +354 -0
  68. package/lib/sync.mjs +755 -0
  69. package/lib/tags.mjs +45 -0
  70. package/lib/tools.mjs +364 -0
  71. package/lib/trusted-roots.mjs +149 -0
  72. package/lib/worker-context.mjs +22 -0
  73. package/package.json +67 -5
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Byron Vanegas
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,192 @@
1
- # Temporary Holding Version
1
+ # LifeCode RAG
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Plugin independiente de recuperación aumentada para DeepSeek Harness. Indexa conocimiento local
4
+ (proyectos, documentación, decisiones) en almacenes **propios** —uno por ámbito— y lo devuelve al modelo en
5
+ fragmentos compactos, citables y con presupuesto de tokens.
6
+
7
+ No depende de `@deepseek-ai/*`, no usa el almacén del Skill Center y no comparte rutas privadas con él.
8
+
9
+ **Paquete:** `@designerbyron/lifecode-rag` · **versión 1.0.0** · contrato público de herramientas
10
+ **v0.1.0** (congelado) · API del panel `pa/1.2.0`.
11
+
12
+ Identificadores internos que **no** cambian con el nombre del paquete: id del plugin `lifecode-rag`,
13
+ herramientas `lifecode_rag_*` y rutas `/lifecode-rag/pa/*`.
14
+
15
+ **Requisitos:** Node.js ≥ 22.5 (usa `node:sqlite`) y DeepSeek Harness ≥ 0.2.2-rc.3 y < 0.3.0.
16
+
17
+ ## Modelo Project-Aware
18
+
19
+ - **Perfil** → un registro `registry.sqlite3` con proyectos, bibliotecas, raíces autorizadas, grants,
20
+ selecciones de sesión, operaciones y auditoría encadenada.
21
+ - **Ámbito** (`prj_…` proyecto, `lib_…` biblioteca) → su propio almacén `scopes/<id>/rag.sqlite3`.
22
+ - **Sesión** → selecciona un proyecto (explícita o por directorio de trabajo). Máximo **8 ámbitos**
23
+ (1 proyecto + 7 bibliotecas) por selección.
24
+ - **Autorización** → se comprueba antes de abrir cada almacén y se revalida en puntos de control antes de
25
+ devolver resultados. Si se revoca un grant a mitad de una operación, la operación **falla en cerrado**
26
+ (`grant-revoked`) y no entrega contenido del ámbito revocado.
27
+ - **Ausencia ≠ vacío** → un almacén ausente o corrupto se declara y no se crea ni se sobrescribe solo.
28
+
29
+ Rutas por perfil (`<profile_root>` = `$DSH_HOME/lifecode-rag/profiles/<profile>`):
30
+
31
+ | Ruta | Contenido |
32
+ |---|---|
33
+ | `<profile_root>/registry.sqlite3` | registro Project-Aware del perfil |
34
+ | `<profile_root>/scopes/<scope_id>/rag.sqlite3` | almacén de un proyecto o biblioteca |
35
+ | `<profile_root>/config.json` | configuración efectiva (opcional; si falta se usan los valores por defecto sin escribir) |
36
+
37
+ El almacén **heredado v0.2** (`$DSH_HOME/lifecode-rag/rag.sqlite3`, o `LIFECODE_RAG_ROOT`) sigue
38
+ funcionando para quien ya lo tenga; el panel lateral sigue sirviendo ese almacén.
39
+
40
+ ## Herramientas (contrato v0.1.0)
41
+
42
+ | Herramienta | Qué hace | Aprobación |
43
+ |---|---|---|
44
+ | `lifecode_rag_ingest` | Indexa ficheros o directorios de texto | Sólo si la ruta está fuera del proyecto |
45
+ | `lifecode_rag_search` | Búsqueda híbrida (FTS + vectores) | No |
46
+ | `lifecode_rag_context` | Contexto con MMR, presupuesto y citas | No |
47
+ | `lifecode_rag_get` | Lee una fuente y sus fragmentos | No |
48
+ | `lifecode_rag_list` | Lista fuentes | No |
49
+ | `lifecode_rag_forget` | Elimina una fuente | Siempre |
50
+ | `lifecode_rag_reindex` | Reconstruye el índice | Siempre |
51
+
52
+ Ninguna herramienta acepta `project_id`, `scope_id` ni `session_id`: la selección es humana y vive en la
53
+ sesión, no en el prompt.
54
+
55
+ ## Instalación
56
+
57
+ Instalación desde el registro público, en el directorio del perfil de DSH:
58
+
59
+ ```sh
60
+ npm install @designerbyron/lifecode-rag@1.0.0
61
+ ```
62
+
63
+ `package.json` del perfil:
64
+
65
+ ```json
66
+ {
67
+ "dependencies": { "@designerbyron/lifecode-rag": "1.0.0" },
68
+ "dsh": { "profile": { "bundles": ["lifecode-rag"] } }
69
+ }
70
+ ```
71
+
72
+ Reinicia DeepSeek Harness: el plugin carga su `cordis.patch.yml`, registra las siete herramientas y monta
73
+ el panel lateral **LifeCode RAG**.
74
+
75
+ Para desarrollo se puede enlazar un checkout en lugar de instalar:
76
+
77
+ ```sh
78
+ dsh plugin --profile <perfil> add "link:C:/ruta/al/checkout" --offline
79
+ ```
80
+
81
+ Tras cambiar el código del plugin, basta recargarlo con el gestor de plugins (desactivar y activar) o
82
+ reiniciar la aplicación; no hace falta reinstalar.
83
+
84
+ ## Primer proyecto
85
+
86
+ El registro del perfil se inicializa con `--create` (sin ese indicador la CLI **no** inventa un perfil):
87
+
88
+ ```sh
89
+ # 1. Crear el proyecto (imprime el prj_…)
90
+ node bin/lifecode-rag.mjs project create --name "Mi proyecto" --create
91
+
92
+ # 2. Autorizar la carpeta de documentos como raíz del proyecto
93
+ node bin/lifecode-rag.mjs root add --project prj_… --path "C:/ruta/a/mi/proyecto"
94
+
95
+ # 3. (Opcional) Fijar la selección de una sesión concreta; sin selección, el proyecto
96
+ # se resuelve por el directorio de trabajo de la sesión contra las raíces autorizadas
97
+ node bin/lifecode-rag.mjs select --session <session-id> --project prj_…
98
+
99
+ # Comprobación
100
+ node bin/lifecode-rag.mjs project list
101
+ node bin/lifecode-rag.mjs root list
102
+ node bin/lifecode-rag.mjs session show --session <session-id>
103
+ ```
104
+
105
+ Desde ese momento el agente usa las siete herramientas con datos reales: `ingest` sobre esa carpeta,
106
+ `search`, `context`, `get`, `list`, y `forget`/`reindex` con aprobación.
107
+
108
+ ## Diagnóstico
109
+
110
+ ```sh
111
+ node bin/lifecode-rag.mjs diagnose # perfil, registro, almacenes, sincronización y auditoría
112
+ node bin/lifecode-rag.mjs diagnose --json # lo mismo, para scripts
113
+ node bin/lifecode-rag.mjs doctor # runtime, configuración y almacén heredado
114
+ node bin/lifecode-rag.mjs library status # estado de los almacenes por ámbito
115
+ node bin/lifecode-rag.mjs sync status # filas de sincronización por ámbito
116
+ node bin/lifecode-rag.mjs sync report # últimas pasadas y ticks auditados
117
+ ```
118
+
119
+ Todo el diagnóstico es de **sólo lectura**: no repara, no crea y no migra nada.
120
+
121
+ ## Sincronización
122
+
123
+ Manual por defecto: `sync run [--scope <id>] [--dry-run] [--limit n]`. La sincronización periódica está
124
+ **desactivada** (`automation.enabled=false`) y, cuando se activa, corre con presupuesto por tick
125
+ (`tickBudgetMs`, 2 000 ms por defecto) y límite de ficheros (`maxFilesPerRun`, 25). Nunca borra fuentes:
126
+ una desaparición se marca `missing` y se revierte si el fichero vuelve con el mismo hash. Los secretos
127
+ evidentes (`.env`, claves, `.pem`, `secrets.json`…) se excluyen por nombre.
128
+
129
+ ## Contexto automático
130
+
131
+ Desactivado por defecto (`autoContext.enabled=false`). Si se activa, el hook `agent/pre-step` añade un
132
+ mensaje con contexto recuperado, sólo en el primer paso de un turno con prompt humano, con presupuesto de
133
+ tiempo (2 000 ms), sin egreso de red y sin compartir estado entre sesiones.
134
+
135
+ ## Modos del panel: REAL y DEMO
136
+
137
+ - **REAL** (`Modo de datos: api`) — el panel lee `/lifecode-rag/pa/*` del host. Toda cifra mostrada sale
138
+ del almacén del perfil. Si la API no responde, el panel **no inventa**: pasa a DEMO y lo dice.
139
+ - **DEMO** (`Modo de datos: demo`) — fixtures sintéticos, marcados como tales en la cabecera; nunca
140
+ muestra datos del proyecto real ni cifras del almacén.
141
+ - Las escrituras (ingesta, olvido, reindexación) **no** se ejecutan desde el panel: la API responde `403`
142
+ y remite a las herramientas, que pasan por la aprobación del host.
143
+
144
+ ## Seguridad
145
+
146
+ - La autorización no se cachea: cada apertura y cada punto de control releen el registro.
147
+ - `forget` y `reindex` exigen aprobación humana; una aprobación denegada o no disponible falla en cerrado.
148
+ - Enlaces duros, enlaces simbólicos y rutas fuera de las raíces autorizadas se rechazan al registrar y al
149
+ ingerir.
150
+ - La ingesta es atómica por fichero: si falla la sustitución, la versión anterior queda intacta.
151
+ - Las auditorías (registro y almacén) son cadenas SHA-256 verificables; se comprueban al abrir y en el
152
+ diagnóstico.
153
+
154
+ ## Pruebas
155
+
156
+ ```sh
157
+ npm test # node --test --test-concurrency=1
158
+ npm run test:hermetic # la suite + huella del almacén real antes y después
159
+ npm run check # estructura, cero dependencias, red acotada
160
+ ```
161
+
162
+ Las pruebas y las herramientas de desarrollo viven en el repositorio, no en el paquete publicado
163
+ (`files` excluye `tests/` y `tools/`).
164
+
165
+ ## Documentación
166
+
167
+ - [`docs/PROJECT-AWARE-ARCHITECTURE.md`](docs/PROJECT-AWARE-ARCHITECTURE.md) — arquitectura y decisiones.
168
+ - [`docs/PROJECT-AWARE-DATA-CONTRACT.md`](docs/PROJECT-AWARE-DATA-CONTRACT.md) — esquema y rutas.
169
+ - [`docs/PROJECT-AWARE-SESSION-CONTRACT.md`](docs/PROJECT-AWARE-SESSION-CONTRACT.md) — sesión y selección.
170
+ - [`docs/PROJECT-AWARE-ERROR-CONTRACT.md`](docs/PROJECT-AWARE-ERROR-CONTRACT.md) — códigos y semántica.
171
+ - [`docs/CONTRATO-v0.1.md`](docs/CONTRATO-v0.1.md) — contrato público de las siete herramientas.
172
+ - [`docs/PA-UI-0-API-CONTRACT.md`](docs/PA-UI-0-API-CONTRACT.md) — contrato de la API del panel.
173
+ - [`docs/AUTO-DISCOVERY.md`](docs/AUTO-DISCOVERY.md) — descubrimiento automático.
174
+ - [`docs/AUTOMATION-POLICIES.md`](docs/AUTOMATION-POLICIES.md) — sincronización y presupuesto.
175
+ - [`docs/EMBEDDING-PROVIDERS.md`](docs/EMBEDDING-PROVIDERS.md) — proveedores de embeddings.
176
+ - [`docs/OBSERVABILITY.md`](docs/OBSERVABILITY.md) — métricas y trazas.
177
+ - [`docs/PERFORMANCE-BUDGETS.md`](docs/PERFORMANCE-BUDGETS.md) — presupuestos medidos.
178
+ - [`docs/WORKSPACE-API.md`](docs/WORKSPACE-API.md) — API del espacio de trabajo.
179
+ - [`docs/ARCHITECTURE-v0.2.md`](docs/ARCHITECTURE-v0.2.md) — arquitectura del almacén heredado.
180
+
181
+ La evidencia de cada acto de ingeniería (planes K1, auditorías `eval/`, matrices de aceptación) vive en
182
+ el repositorio de desarrollo y **no** se distribuye en el paquete.
183
+
184
+ ## Licencia
185
+
186
+ **MIT** — Copyright (c) 2026 Byron Vanegas.
187
+
188
+ Se concede permiso, de forma gratuita, a cualquier persona que obtenga una copia de este software y de
189
+ sus ficheros de documentación, para usarlo, copiarlo, modificarlo, fusionarlo, publicarlo, distribuirlo,
190
+ sublicenciarlo y/o vender copias, con la única condición de incluir este aviso de copyright y esta
191
+ licencia en todas las copias o partes sustanciales del software. El software se entrega «tal cual», sin
192
+ garantía de ningún tipo. Texto completo en [`LICENSE`](LICENSE).
@@ -0,0 +1,449 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * CLI de LifeCode RAG. No registra herramientas ni habla con el host: sirve para diagnosticar, verificar
4
+ * y recuperar los almacenes antes o después de una operación. Nunca crea un almacén que falte.
5
+ *
6
+ * node bin/lifecode-rag.mjs doctor
7
+ * node bin/lifecode-rag.mjs project create --name <nombre> [--create] | project list
8
+ * node bin/lifecode-rag.mjs root add --project <prj_id> --path <ruta absoluta> [--create] | root list
9
+ * node bin/lifecode-rag.mjs select --session <id> --project <prj_id> [--by human|host]
10
+ * node bin/lifecode-rag.mjs session show --session <id>
11
+ * node bin/lifecode-rag.mjs audit export|verify
12
+ * node bin/lifecode-rag.mjs library status|verify|plan|recover|rollback
13
+ * node bin/lifecode-rag.mjs sync run [--scope <id>] [--dry-run] [--limit n] | sync status
14
+ */
15
+
16
+ import { auditState, exportAuditJsonl, verifyAuditExport } from '../lib/audit-export.mjs';
17
+ import { closeDatabase, openDatabase } from '../lib/db.mjs';
18
+ import { diagnoseProfile } from '../lib/diagnose.mjs';
19
+ import { runDoctor } from '../lib/doctor.mjs';
20
+ import { loadConfig, ragRoot, storePaths } from '../lib/paths.mjs';
21
+ import { profileKey, profileRoot } from '../lib/profile.mjs';
22
+ import { closeRegistry, openRegistry, addRoot, createProject, getProject, listRoots } from '../lib/registry.mjs';
23
+ import { describeProject, registerDiscoveredProject, scanWorkspace } from '../lib/discovery.mjs';
24
+ import { addTrustedRoot, listTrustedRoots, removeTrustedRoot } from '../lib/trusted-roots.mjs';
25
+ import { getSession, registerSelection } from '../lib/sessions.mjs';
26
+ import {
27
+ listRecoveryArtifacts, planRecovery, recoverScopeStore, rollbackRecovery, scopeHealth,
28
+ } from '../lib/recovery.mjs';
29
+ import { isServable } from '../lib/library-state.mjs';
30
+ import { activeSyncScopes, syncScopes, syncStatus } from '../lib/sync.mjs';
31
+
32
+ const argv = process.argv.slice(2);
33
+ const [command, subcommand] = argv;
34
+
35
+ function fail(message, code = 1) {
36
+ console.error(`✗ ${message}`);
37
+ process.exit(code);
38
+ }
39
+
40
+ function flag(name, fallback = null) {
41
+ const index = argv.indexOf(`--${name}`);
42
+ if (index < 0) return fallback;
43
+ const value = argv[index + 1];
44
+ return value === undefined || value.startsWith('--') ? true : value;
45
+ }
46
+
47
+ if (command === 'doctor') {
48
+ const root = ragRoot(process.env);
49
+ const report = runDoctor({ root });
50
+ console.log(`LifeCode RAG · ${root}`);
51
+ for (const item of report.checks) {
52
+ const icon = item.status === 'ok' ? '✓' : item.status === 'warn' ? '!' : '✗';
53
+ console.log(` ${icon} ${item.name}: ${item.detail}`);
54
+ }
55
+ console.log(` · perfil Project-Aware: ${profileKey(process.env)} (usa \`diagnose\` para el detalle del registro y los almacenes)`);
56
+ process.exit(report.ok ? 0 : 1);
57
+ }
58
+
59
+ if (command === 'diagnose') {
60
+ // Diagnóstico del perfil Project-Aware: sólo lectura, sin reparar nada y sin tocar el registro.
61
+ const report = diagnoseProfile({ env: process.env });
62
+ if (flag('json', false)) {
63
+ console.log(JSON.stringify(report, null, 2));
64
+ process.exit(report.ok ? 0 : 1);
65
+ }
66
+ const icon = (value) => (value ? '✓' : '✗');
67
+ console.log(`LifeCode RAG · diagnóstico del perfil ${report.profile.key}`);
68
+ console.log(` ${icon(Boolean(report.profile.config.sha256))} perfil: ${report.profile.root}`);
69
+ const cfg = report.profile.config;
70
+ console.log(
71
+ ` ${icon(!cfg.error)} configuración: ${cfg.exists ? `${cfg.bytes} B sha256 ${String(cfg.sha256).slice(0, 12)}…` : 'no existe (valores por defecto)'}` +
72
+ `${cfg.automation ? ` · automation=${cfg.automation.enabled ? 'ON' : 'off'}` : ''}` +
73
+ `${cfg.autoContext ? ` · autoContext=${cfg.autoContext.enabled ? 'ON' : 'off'}` : ''}`,
74
+ );
75
+ const reg = report.registry;
76
+ if (!reg?.exists) {
77
+ console.log(' ✗ registro: no existe en este perfil');
78
+ } else if (reg.error) {
79
+ console.log(` ✗ registro: ${reg.error} (${reg.path})`);
80
+ } else {
81
+ console.log(
82
+ ` ${icon(reg.quickCheck === 'ok' && reg.foreignKeys === 0 && reg.audit?.ok)} registro: ${reg.bytes} B · quick_check=${reg.quickCheck} · fk=${reg.foreignKeys} · auditoría=${reg.audit?.count ?? 0}${reg.audit?.ok ? ' ok' : ` ROTA en ${reg.audit?.brokenAt}`} · operaciones sin cerrar=${reg.unfinishedOperations.length}`,
83
+ );
84
+ for (const item of report.scopes) {
85
+ const counts = item.counts && !item.counts.error ? item.counts : null;
86
+ const detail = counts
87
+ ? `${counts.sources} fuentes / ${counts.chunks} chunks / ${counts.vectors} vectores · sync ${Object.entries(item.sync ?? {}).map(([k, v]) => `${k}=${v}`).join(' ') || 'sin filas'} · auditoría=${counts.audit?.count ?? 0}${counts.audit?.ok ? '' : ' ROTA'}`
88
+ : item.reason ?? 'sin almacén';
89
+ console.log(` ${isServable(item.state) ? '✓' : '✗'} ${item.kind === 'prj' ? 'proyecto' : 'biblioteca'} ${item.name ?? item.scopeId}: ${item.state}${item.state === 'present' ? '' : ` (${detail})`}${item.state === 'present' ? ` · ${detail}` : ''}`);
90
+ }
91
+ for (const selection of report.selections) {
92
+ console.log(` · sesión ${selection.session_id}: ${selection.state} (${selection.selection_source}/${selection.selected_by}, revisión ${selection.revision})`);
93
+ }
94
+ }
95
+ if (report.problems.length > 0) {
96
+ console.log(' problemas:');
97
+ for (const problem of report.problems) console.log(` ✗ ${problem}`);
98
+ }
99
+ console.log(`RESULTADO: ${report.ok ? 'sin problemas' : `${report.problems.length} problema(s)`}`);
100
+ process.exit(report.ok ? 0 : 1);
101
+ }
102
+
103
+ if (command === 'audit' && (subcommand === 'export' || subcommand === 'verify')) {
104
+ const root = ragRoot(process.env);
105
+ loadConfig(root);
106
+ const opened = openDatabase({ root, create: false });
107
+ try {
108
+ const path = storePaths(root).audit;
109
+ if (subcommand === 'export') {
110
+ const result = exportAuditJsonl(opened.db, { path });
111
+ console.log(`✓ auditoría exportada: ${result.entries} entrada(s), ${result.bytes} bytes → ${path}`);
112
+ } else {
113
+ const result = verifyAuditExport(opened.db, { path });
114
+ if (result.ok) {
115
+ console.log(`✓ auditoría coherente: ${result.entries} entrada(s), base y fichero coinciden`);
116
+ } else {
117
+ fail(`auditoría incoherente: ${result.reason}${result.seq ? ` (seq ${result.seq})` : ''}`);
118
+ }
119
+ const state = auditState(opened.db, { path });
120
+ if (!state.ok) fail(`estado de auditoría inválido: ${state.where}/${state.reason}`);
121
+ }
122
+ } finally {
123
+ closeDatabase(opened.db);
124
+ }
125
+ process.exit(0);
126
+ }
127
+
128
+ /** Todos los ámbitos del registro con su nombre y estado; sólo lee. */
129
+ function allScopes(registryDb) {
130
+ const projects = registryDb.prepare(`SELECT id, name, status FROM projects ORDER BY name`).all()
131
+ .map((row) => ({ id: row.id, kind: 'prj', name: row.name, status: row.status }));
132
+ const libraries = registryDb.prepare(`SELECT id, name, status FROM libraries ORDER BY name`).all()
133
+ .map((row) => ({ id: row.id, kind: 'lib', name: row.name, status: row.status }));
134
+ return [...projects, ...libraries];
135
+ }
136
+
137
+ function findScope(registryDb, id) {
138
+ if (typeof id !== 'string' || id.length === 0) fail('falta --scope <scope_id>', 2);
139
+ const scope = allScopes(registryDb).find((entry) => entry.id === id);
140
+ if (!scope) fail(`no existe el ámbito ${id} en este perfil`, 2);
141
+ return scope;
142
+ }
143
+
144
+ if (command === 'library') {
145
+ const env = process.env;
146
+ const root = profileRoot(env);
147
+ const key = profileKey(env);
148
+ const now = Date.now();
149
+ let registry;
150
+ try {
151
+ registry = openRegistry({ root, create: false, now });
152
+ } catch (error) {
153
+ fail(`registro no disponible en ${root}: ${error?.message ?? error}`);
154
+ }
155
+ try {
156
+ if (!subcommand || subcommand === 'status' || subcommand === 'verify') {
157
+ const scopes = allScopes(registry.db);
158
+ const health = scopeHealth({ profileRootPath: root, profileKey: key, scopes });
159
+ console.log(`LifeCode RAG · ${root}`);
160
+ let blocked = 0;
161
+ for (const entry of health) {
162
+ const ok = subcommand === 'verify' ? isServable(entry.state) : true;
163
+ if (!ok) blocked += 1;
164
+ const icon = isServable(entry.state) ? '✓' : '✗';
165
+ const size = entry.bytes ? `, ${entry.bytes} bytes` : '';
166
+ console.log(` ${icon} ${entry.kind} ${entry.scopeId} (${entry.name ?? 'sin nombre'}): ${entry.state}${size}${entry.reason ? ` — ${entry.reason}` : ''}`);
167
+ for (const staging of entry.artifacts.staging) console.log(` ! trabajo de recuperación sin terminar: ${staging}`);
168
+ for (const quarantine of entry.artifacts.quarantine) console.log(` · cuarentena disponible: ${quarantine}`);
169
+ }
170
+ process.exit(subcommand === 'verify' && blocked > 0 ? 1 : 0);
171
+ }
172
+
173
+ if (subcommand === 'plan' || subcommand === 'recover') {
174
+ const scope = findScope(registry.db, flag('scope'));
175
+ if (subcommand === 'plan') {
176
+ const plan = planRecovery({ profileRootPath: root, profileKey: key, scope });
177
+ console.log(JSON.stringify(plan, null, 2));
178
+ process.exit(plan.plan === 'blocked' ? 1 : 0);
179
+ }
180
+ const { config } = loadConfig(root);
181
+ const mode = flag('mode', 'auto');
182
+ const result = recoverScopeStore({
183
+ profileRootPath: root,
184
+ profileKey: key,
185
+ scope,
186
+ config,
187
+ mode,
188
+ confirm: flag('confirm') === true,
189
+ now,
190
+ actor: 'human',
191
+ registryDb: registry.db,
192
+ });
193
+ console.log(JSON.stringify(result, null, 2));
194
+ process.exit(0);
195
+ }
196
+
197
+ if (subcommand === 'rollback') {
198
+ const scope = findScope(registry.db, flag('scope'));
199
+ const art = listRecoveryArtifacts({ profileRootPath: root, scope });
200
+ const from = flag('from', null);
201
+ const quarantine = from === null ? art.quarantine.at(-1) : String(from);
202
+ if (!quarantine) fail(`no hay cuarentena para ${scope.id}; usa --from <ruta>`, 2);
203
+ const result = rollbackRecovery({ profileRootPath: root, scope, quarantine, now, registryDb: registry.db });
204
+ console.log(JSON.stringify(result, null, 2));
205
+ process.exit(0);
206
+ }
207
+
208
+ fail('uso: library status|verify|plan --scope <id>|recover --scope <id> [--mode auto|rebuild|reinit] --confirm|rollback --scope <id> [--from <ruta>]', 2);
209
+ } finally {
210
+ closeRegistry(registry.db);
211
+ }
212
+ }
213
+
214
+ if (command === 'sync') {
215
+ const env = process.env;
216
+ const root = profileRoot(env);
217
+ const key = profileKey(env);
218
+ const { config } = loadConfig(root);
219
+ const now = Date.now();
220
+ let registry;
221
+ try {
222
+ registry = openRegistry({ root, create: false, now });
223
+ } catch (error) {
224
+ fail(`registro no disponible en ${root}: ${error?.message ?? error}`);
225
+ }
226
+ try {
227
+ if (!subcommand || subcommand === 'status') {
228
+ const scopes = activeSyncScopes(registry.db);
229
+ console.log(`LifeCode RAG · ${root}`);
230
+ if (scopes.length === 0) console.log(' · ningún ámbito activo con raíz autorizada');
231
+ for (const scope of scopes) {
232
+ const status = syncStatus(registry.db, { scopeKind: scope.kind, scopeId: scope.id });
233
+ const detail = status.length === 0
234
+ ? 'sin sincronizar'
235
+ : status.map((entry) => `${entry.status}=${entry.count}`).join(' ');
236
+ console.log(` · ${scope.kind} ${scope.id} (${scope.name}): ${detail}`);
237
+ }
238
+ process.exit(0);
239
+ }
240
+
241
+ if (subcommand === 'run') {
242
+ const scopeId = flag('scope', null);
243
+ const scopes = activeSyncScopes(registry.db).filter((scope) => scopeId === null || scope.id === scopeId);
244
+ if (scopes.length === 0) fail('no hay ámbitos activos que sincronizar con ese filtro', 2);
245
+ const limit = flag('limit', null);
246
+ const results = await syncScopes({
247
+ registryDb: registry.db,
248
+ profileRoot: root,
249
+ profileKey: key,
250
+ scopes,
251
+ config,
252
+ now: () => Date.now(),
253
+ limit: limit === null ? null : Number(limit),
254
+ actor: 'human',
255
+ dryRun: flag('dry-run') === true,
256
+ });
257
+ for (const result of results) {
258
+ console.log(`${result.scope_kind} ${result.scope_id}: observados=${result.observed} sin_cambios=${result.unchanged} nuevos=${result.new} modificados=${result.changed} ausentes=${result.missing} ilegibles=${result.unreadable} no_soportados=${result.unsupported} sensibles=${result.sensitive} ingeridos=${result.ingested} fallos=${result.failed}${result.stop_reason ? ` motivo=${result.stop_reason}` : ''}${result.cancelled ? ' CANCELADO' : ''}${result.dry_run ? ' (simulación)' : ''}`);
259
+ for (const error of result.errors.slice(0, 5)) console.log(` ! ${error.code}: ${error.path ?? ''} ${error.message}`);
260
+ }
261
+ const failed = results.some((result) => result.failed > 0 || result.cancelled || result.complete === false);
262
+ process.exit(failed ? 1 : 0);
263
+ }
264
+
265
+ if (subcommand === 'report') {
266
+ // Observabilidad sin inspeccionar la base a mano: últimas pasadas y ticks tal como quedaron
267
+ // auditados (M6.7 §7). Sólo agregados; nunca contenido de documentos ni de prompts.
268
+ const limit = Number(flag('limit', 10));
269
+ const rows = registry.db
270
+ .prepare(
271
+ `SELECT seq, at, action, outcome, detail FROM audit_registry
272
+ WHERE action IN ('sync.run', 'sync.tick')
273
+ ORDER BY seq DESC LIMIT ?`,
274
+ )
275
+ .all(Number.isInteger(limit) && limit > 0 ? limit : 10);
276
+ if (rows.length === 0) console.log(' · sin pasadas de sincronización auditadas');
277
+ for (const row of rows) {
278
+ let detail = {};
279
+ try { detail = row.detail ? JSON.parse(row.detail) : {}; } catch { detail = {}; }
280
+ const parts = [
281
+ `scopes=${detail.scopes ?? '?'}`,
282
+ `nuevos=${detail.new ?? 0}`,
283
+ `ingeridos=${detail.ingested ?? 0}`,
284
+ `ausentes=${detail.missing ?? 0}`,
285
+ `fallos=${detail.failed ?? 0}`,
286
+ `no_soportados=${detail.unsupported ?? 0}`,
287
+ `sensibles=${detail.sensitive ?? 0}`,
288
+ `parciales=${detail.partial ?? 0}`,
289
+ `ms=${detail.ms ?? '?'}`,
290
+ detail.budget_ms ? `presupuesto_ms=${detail.budget_ms}` : null,
291
+ detail.stop_reason ? `motivo=${detail.stop_reason}` : null,
292
+ ].filter(Boolean);
293
+ console.log(` #${row.seq} ${row.action} ${row.outcome} ${new Date(Number(row.at)).toISOString()} ${parts.join(' ')}`);
294
+ }
295
+ process.exit(0);
296
+ }
297
+
298
+ fail('uso: sync run [--scope <id>] [--dry-run] [--limit n] | sync status | sync report [--limit n]', 2);
299
+ } finally {
300
+ closeRegistry(registry.db);
301
+ }
302
+ }
303
+
304
+ if (command === 'project' || command === 'root' || command === 'select' || command === 'session'
305
+ || command === 'trust' || command === 'discover') {
306
+ // Registro del perfil: crear proyecto, autorizar una raíz o fijar la selección de una sesión. No crea
307
+ // el almacén salvo `--create` explícito: la CLI nunca inventa un perfil. Toda salida va por stdout en
308
+ // JSON para que sea verificable; el código de salida es 0 sólo si la operación se completó.
309
+ const env = process.env;
310
+ const root = profileRoot(env);
311
+ const key = profileKey(env);
312
+ const now = Date.now();
313
+ let registry;
314
+ try {
315
+ registry = openRegistry({ root, create: flag('create', false) === true, now });
316
+ } catch (error) {
317
+ fail(`registro no disponible en ${root}: ${error?.message ?? error}`);
318
+ }
319
+ const db = registry.db;
320
+ let status = 0;
321
+ try {
322
+ if (command === 'project' && (!subcommand || subcommand === 'list')) {
323
+ const rows = db.prepare('SELECT id, name, status, created_at FROM projects ORDER BY created_at').all();
324
+ console.log(JSON.stringify({ profile: key, root, projects: rows.length, rows }, null, 1));
325
+ } else if (command === 'project' && (subcommand === 'create' || subcommand === 'add')) {
326
+ const name = flag('name');
327
+ if (name === null || name === true) fail('falta --name <nombre>', 2);
328
+ const project = createProject(db, { name: String(name), now });
329
+ console.log(JSON.stringify({ ok: true, profile: key, project }, null, 1));
330
+ } else if (command === 'project') {
331
+ fail('uso: project create --name <nombre> [--create] | project list', 2);
332
+ } else if (command === 'root' && (!subcommand || subcommand === 'list')) {
333
+ const rows = listRoots(db);
334
+ console.log(JSON.stringify({ profile: key, roots: rows.length, rows }, null, 1));
335
+ } else if (command === 'root' && (subcommand === 'add' || subcommand === 'authorize')) {
336
+ const projectId = flag('project');
337
+ const path = flag('path');
338
+ if (projectId === null || projectId === true) fail('falta --project <prj_id>', 2);
339
+ if (path === null || path === true) fail('falta --path <ruta absoluta>', 2);
340
+ if (!getProject(db, String(projectId))) fail(`no existe el proyecto ${projectId} en este perfil`, 2);
341
+ const row = addRoot(db, { scopeKind: 'prj', scopeId: String(projectId), path: String(path), addedBy: 'human', now });
342
+ console.log(JSON.stringify({ ok: true, profile: key, root: row }, null, 1));
343
+ } else if (command === 'root') {
344
+ fail('uso: root add --project <prj_id> --path <ruta absoluta> [--create] | root list', 2);
345
+ } else if (command === 'select') {
346
+ const session = flag('session');
347
+ const projectId = flag('project');
348
+ if (session === null || session === true) fail('falta --session <id>', 2);
349
+ if (projectId === null || projectId === true) fail('falta --project <prj_id>', 2);
350
+ const result = registerSelection(db, {
351
+ identity: { sessionId: String(session), profileKey: key },
352
+ expectedProfileKey: key,
353
+ projectId: String(projectId),
354
+ selectedBy: flag('by', 'human') === 'host' ? 'host' : 'human',
355
+ source: 'explicit',
356
+ actor: 'human',
357
+ now,
358
+ });
359
+ const selection = result.selection;
360
+ console.log(JSON.stringify({
361
+ ok: true,
362
+ profile: key,
363
+ created: result.created,
364
+ changed: result.changed,
365
+ selection: {
366
+ session: selection.session_id,
367
+ project: selection.project_id,
368
+ source: selection.selection_source,
369
+ by: selection.selected_by,
370
+ state: selection.state,
371
+ revision: selection.revision,
372
+ },
373
+ }, null, 1));
374
+ } else if (command === 'trust' && (!subcommand || subcommand === 'list')) {
375
+ const rows = listTrustedRoots(db);
376
+ console.log(JSON.stringify({
377
+ profile: key, root, trusted: rows.length, rows,
378
+ }, null, 1));
379
+ } else if (command === 'trust' && (subcommand === 'add' || subcommand === 'authorize')) {
380
+ const path = flag('path');
381
+ if (path === null || path === true) fail('falta --path <ruta absoluta del workspace>', 2);
382
+ const result = addTrustedRoot(db, {
383
+ path: String(path),
384
+ readAuthorization: flag('read', 'true') !== 'false',
385
+ addedBy: 'human',
386
+ now,
387
+ });
388
+ console.log(JSON.stringify({
389
+ ok: true, profile: key, created: result.created, changed: result.changed, root: result.root,
390
+ }, null, 1));
391
+ } else if (command === 'trust' && subcommand === 'remove') {
392
+ const path = flag('path');
393
+ if (path === null || path === true) fail('falta --path <ruta absoluta del workspace>', 2);
394
+ const result = removeTrustedRoot(db, { path: String(path), removedBy: 'human', now });
395
+ console.log(JSON.stringify({ ok: true, profile: key, changed: result.changed }, null, 1));
396
+ } else if (command === 'discover' && (subcommand === 'scan' || subcommand === 'register')) {
397
+ const path = flag('path');
398
+ if (path === null || path === true) fail('falta --path <ruta absoluta del workspace confiable>', 2);
399
+ const scan = scanWorkspace(String(path));
400
+ if (subcommand === 'scan') {
401
+ console.log(JSON.stringify({ profile: key, ...scan }, null, 1));
402
+ } else {
403
+ const authorization = flag('read', 'true') !== 'false' ? 'read' : 'discovered';
404
+ const results = scan.projects.map((project) => registerDiscoveredProject(db, {
405
+ path: project.path,
406
+ name: project.name,
407
+ type: project.type,
408
+ indicators: project.indicators,
409
+ source: 'cli',
410
+ authorization,
411
+ now,
412
+ }));
413
+ console.log(JSON.stringify({
414
+ profile: key,
415
+ scanned: scan.projects.length,
416
+ registered: results.filter((row) => row.created).length,
417
+ reused: results.filter((row) => !row.created).length,
418
+ skipped: scan.skipped,
419
+ results,
420
+ }, null, 1));
421
+ }
422
+ } else if (command === 'discover' && subcommand === 'show') {
423
+ const projectId = flag('project');
424
+ if (projectId === null || projectId === true) fail('falta --project <prj_id>', 2);
425
+ console.log(JSON.stringify({ profile: key, project: describeProject(db, String(projectId)) }, null, 1));
426
+ } else if (command === 'discover') {
427
+ fail('uso: discover scan|register --path <ruta> [--read true|false] | discover show --project <id>', 2);
428
+ } else if (command === 'trust') {
429
+ fail('uso: trust add --path <ruta> [--read true|false] | trust list | trust remove --path <ruta>', 2);
430
+ } else if (command === 'session' && subcommand === 'show') {
431
+ const session = flag('session');
432
+ if (session === null || session === true) fail('falta --session <id>', 2);
433
+ const row = getSession(db, String(session));
434
+ console.log(JSON.stringify({ profile: key, session: row ?? null }, null, 1));
435
+ if (!row) status = 1;
436
+ } else {
437
+ fail('uso: session show --session <id>', 2);
438
+ }
439
+ } catch (error) {
440
+ // Un error de dominio (proyecto inexistente, raíz no autorizable) no puede tumbar la CLI con traza.
441
+ console.error(`✗ ${error?.message ?? error}`);
442
+ status = 1;
443
+ } finally {
444
+ closeRegistry(db);
445
+ }
446
+ process.exit(status);
447
+ }
448
+
449
+ fail('uso: lifecode-rag.mjs doctor | diagnose | audit export | audit verify | project create|list | root add|list | select | session show | library status|verify|plan|recover|rollback | sync run|status|report', 2);