@saulwade/swl-ses 1.5.2 → 1.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.
Files changed (64) hide show
  1. package/CLAUDE.md +32 -61
  2. package/README.md +20 -3
  3. package/agentes/datos-swl.md +1 -1
  4. package/agentes/frontend-angular-swl.md +7 -7
  5. package/agentes/frontend-css-swl.md +4 -4
  6. package/agentes/frontend-react-swl.md +7 -7
  7. package/agentes/frontend-swl.md +9 -9
  8. package/agentes/frontend-tailwind-swl.md +4 -4
  9. package/agentes/rendimiento-swl.md +2 -2
  10. package/bin/swl-ses.js +49 -7
  11. package/comandos/swl/brainstorm.md +1 -0
  12. package/comandos/swl/compactar.md +1 -1
  13. package/comandos/swl/discutir-fase.md +15 -1
  14. package/comandos/swl/mapear-codebase.md +1 -1
  15. package/comandos/swl/nemesis.md +29 -0
  16. package/comandos/swl/planear-fase.md +2 -2
  17. package/comandos/swl/verificar.md +4 -4
  18. package/habilidades/aprendizaje-continuo/SKILL.md +7 -1
  19. package/habilidades/diseno-herramientas-agente/SKILL.md +1 -0
  20. package/habilidades/doc-sync/SKILL.md +441 -1
  21. package/habilidades/doubt-driven-review/SKILL.md +177 -171
  22. package/habilidades/feynman-auditor-swl/SKILL.md +129 -123
  23. package/habilidades/infra-github-actions/SKILL.md +172 -166
  24. package/habilidades/meta-skills-estandar/recursos/skills-as-agents.md +163 -163
  25. package/habilidades/nemesis-evaluacion-json/SKILL.md +5 -0
  26. package/habilidades/nemesis-redistribuir/SKILL.md +5 -0
  27. package/habilidades/node-experto/SKILL.md +197 -3
  28. package/habilidades/prevencion-racionalizacion/SKILL.md +1 -0
  29. package/habilidades/privacy-memoria/SKILL.md +1 -0
  30. package/habilidades/sre-patrones/SKILL.md +1 -1
  31. package/habilidades/state-inconsistency-auditor-swl/SKILL.md +172 -166
  32. package/habilidades/tdd-workflow/SKILL.md +178 -3
  33. package/habilidades/verificacion-evidencia/SKILL.md +1 -0
  34. package/habilidades/web-fetcher-routing/SKILL.md +81 -75
  35. package/habilidades/workflow-claude-code/SKILL.md +2 -2
  36. package/hooks/extraccion-aprendizajes.js +11 -0
  37. package/manifiestos/modulos.json +2 -1
  38. package/manifiestos/skills-lock.json +1142 -1114
  39. package/package.json +7 -4
  40. package/plugin.json +4 -2
  41. package/reglas/auditorias-documentales-estructurales.md +205 -0
  42. package/schemas/agent-frontmatter.schema.json +1 -1
  43. package/scripts/desinstalar.js +105 -24
  44. package/scripts/generar-inventario.js +450 -420
  45. package/scripts/instalador.js +55 -4
  46. package/scripts/lib/parsear-opciones.js +3 -0
  47. package/scripts/lib/ui.js +148 -22
  48. package/scripts/tui/componentes/selector-multi.js +189 -0
  49. package/scripts/tui/componentes/selector-unico.js +158 -0
  50. package/scripts/tui/ejecutores.js +375 -0
  51. package/scripts/tui/index.js +162 -0
  52. package/scripts/tui/lib/colores.js +129 -0
  53. package/scripts/tui/lib/render.js +264 -0
  54. package/scripts/tui/lib/teclas.js +113 -0
  55. package/scripts/tui/pantallas/inspect.js +173 -0
  56. package/scripts/tui/pantallas/install-wizard.js +334 -0
  57. package/scripts/tui/pantallas/menu-principal.js +52 -0
  58. package/scripts/tui/pantallas/progreso.js +274 -0
  59. package/scripts/tui/pantallas/resumen.js +132 -0
  60. package/scripts/tui/pantallas/uninstall-wizard.js +208 -0
  61. package/scripts/tui/pantallas/update-wizard.js +232 -0
  62. package/scripts/tui/pantallas/welcome.js +187 -0
  63. package/scripts/verificar-docs-vs-codigo.js +654 -0
  64. package/scripts/verificar-evolucion.js +19 -3
@@ -1,420 +1,450 @@
1
- #!/usr/bin/env node
2
- 'use strict';
3
-
4
- /**
5
- * generar-inventario.js — Genera INVENTARIO.md y SALUD.md desde el disco.
6
- *
7
- * Elimina la necesidad de mantener estos archivos manualmente.
8
- * Lee el estado real de agentes/, habilidades/, hooks/, etc.
9
- *
10
- * Uso:
11
- * node scripts/generar-inventario.js # Genera ambos
12
- * node scripts/generar-inventario.js --inventario # Solo INVENTARIO.md
13
- * node scripts/generar-inventario.js --salud # Solo SALUD.md
14
- * node scripts/generar-inventario.js --dry-run # Muestra sin escribir
15
- *
16
- * @module scripts/generar-inventario
17
- */
18
-
19
- const fs = require('fs');
20
- const path = require('path');
21
-
22
- const RAIZ = path.resolve(__dirname, '..');
23
-
24
- // Escritura atómica obligatoria (regla CLAUDE.md). INVENTARIO.md y SALUD.md
25
- // son artefactos de release; corrupción durante regeneración rompe la gate.
26
- let atomicWriteSync;
27
- try {
28
- ({ atomicWriteSync } = require(path.join(RAIZ, 'hooks', 'lib', 'atomic-write.js')));
29
- } catch {
30
- atomicWriteSync = (p, c, e) => fs.writeFileSync(p, c, e);
31
- }
32
- const args = new Set(process.argv.slice(2));
33
- const DRY = args.has('--dry-run');
34
- const SOLO_INV = args.has('--inventario');
35
- const SOLO_SAL = args.has('--salud');
36
- const AMBOS = !SOLO_INV && !SOLO_SAL;
37
-
38
- // ── Helpers ────────────────────────────────────────────────────────────
39
-
40
- function leerFrontmatter(ruta) {
41
- try {
42
- const contenido = fs.readFileSync(ruta, 'utf8');
43
- const match = contenido.match(/^---\r?\n([\s\S]*?)\r?\n---/);
44
- if (!match) return {};
45
- const fm = {};
46
- for (const linea of match[1].split(/\r?\n/)) {
47
- const idx = linea.indexOf(':');
48
- if (idx > 0) {
49
- const key = linea.slice(0, idx).trim();
50
- const val = linea.slice(idx + 1).trim().replace(/^["']|["']$/g, '');
51
- fm[key] = val;
52
- }
53
- }
54
- return fm;
55
- } catch { return {}; }
56
- }
57
-
58
- function contarArchivos(dir, ext) {
59
- try {
60
- return fs.readdirSync(dir).filter(f => f.endsWith(ext)).length;
61
- } catch { return 0; }
62
- }
63
-
64
- function contarDirectorios(dir) {
65
- try {
66
- return fs.readdirSync(dir).filter(d =>
67
- fs.statSync(path.join(dir, d)).isDirectory()
68
- ).length;
69
- } catch { return 0; }
70
- }
71
-
72
- function contarSkills(dir) {
73
- try {
74
- return fs.readdirSync(dir).filter(d => {
75
- const skillMd = path.join(dir, d, 'SKILL.md');
76
- return fs.existsSync(skillMd);
77
- }).length;
78
- } catch { return 0; }
79
- }
80
-
81
- // ── Recolectar datos ──────────────────────────────────────────────────
82
-
83
- function recolectarAgentes() {
84
- const dir = path.join(RAIZ, 'agentes');
85
- const archivos = fs.readdirSync(dir).filter(f => f.endsWith('.md'));
86
- return archivos.map(f => {
87
- const fm = leerFrontmatter(path.join(dir, f));
88
- return {
89
- archivo: f,
90
- name: fm.name || f.replace('.md', ''),
91
- version: fm.version || '?',
92
- model: fm.model || '?',
93
- nivelRiesgo: fm.nivelRiesgo || '?',
94
- };
95
- });
96
- }
97
-
98
- function recolectarSkills() {
99
- const dir = path.join(RAIZ, 'habilidades');
100
- const dirs = fs.readdirSync(dir).filter(d =>
101
- fs.existsSync(path.join(dir, d, 'SKILL.md'))
102
- );
103
- return dirs.map(d => {
104
- const fm = leerFrontmatter(path.join(dir, d, 'SKILL.md'));
105
- return { dir: d, name: fm.name || d, description: (fm.description || '').substring(0, 80) };
106
- });
107
- }
108
-
109
- function recolectarHooks() {
110
- const dir = path.join(RAIZ, 'hooks');
111
- return fs.readdirSync(dir).filter(f => f.endsWith('.js') && f !== 'lib');
112
- }
113
-
114
- function recolectarLibs() {
115
- const dir = path.join(RAIZ, 'hooks', 'lib');
116
- return fs.readdirSync(dir).filter(f => f.endsWith('.js'));
117
- }
118
-
119
- function verificarSintaxis(archivos, dirBase) {
120
- const { execSync } = require('child_process');
121
- let ok = 0, fail = 0;
122
- for (const f of archivos) {
123
- try {
124
- execSync(`node -c "${path.join(dirBase, f)}"`, { stdio: 'pipe' });
125
- ok++;
126
- } catch { fail++; }
127
- }
128
- return { ok, fail, total: archivos.length };
129
- }
130
-
131
- // ── Generar INVENTARIO.md ─────────────────────────────────────────────
132
-
133
- function generarInventario() {
134
- const pkg = JSON.parse(fs.readFileSync(path.join(RAIZ, 'package.json'), 'utf8'));
135
- const agentes = recolectarAgentes();
136
- const skills = recolectarSkills();
137
- const hooks = recolectarHooks();
138
- const libs = recolectarLibs();
139
- const comandos = contarArchivos(path.join(RAIZ, 'comandos', 'swl'), '.md');
140
- const reglasBase = contarArchivos(path.join(RAIZ, 'reglas'), '.md');
141
- const reglasLang = fs.readdirSync(path.join(RAIZ, 'reglas', 'lenguajes'))
142
- .filter(d => fs.statSync(path.join(RAIZ, 'reglas', 'lenguajes', d)).isDirectory())
143
- .reduce((acc, d) => acc + contarArchivos(path.join(RAIZ, 'reglas', 'lenguajes', d), '.md'), 0);
144
- const schemas = contarArchivos(path.join(RAIZ, 'schemas'), '.json');
145
- const scripts = contarArchivos(path.join(RAIZ, 'scripts', 'lib'), '.js') + contarArchivos(path.join(RAIZ, 'scripts', 'lib'), '.py');
146
-
147
- const lines = [];
148
- lines.push(`# INVENTARIO.md — Referencia completa de componentes SWL v${pkg.version}`);
149
- lines.push('');
150
- lines.push('> Archivo generado automáticamente por `node scripts/generar-inventario.js`.');
151
- lines.push('> NO editar manualmente — se regenera con cada release.');
152
- lines.push('');
153
- lines.push('## Resumen');
154
- lines.push('');
155
- lines.push('| Componente | Cantidad |');
156
- lines.push('|-----------|----------|');
157
- lines.push(`| Agentes SWL | ${agentes.length} |`);
158
- lines.push(`| Habilidades | ${skills.length} |`);
159
- lines.push(`| Comandos | ${comandos} |`);
160
- lines.push(`| Reglas base | ${reglasBase} |`);
161
- lines.push(`| Reglas por lenguaje | ${reglasLang} |`);
162
- lines.push(`| Hooks | ${hooks.length} |`);
163
- lines.push(`| Librerías de hooks | ${libs.length} |`);
164
- lines.push(`| Schemas | ${schemas} |`);
165
- lines.push(`| Scripts lib | ${scripts} |`);
166
- lines.push('');
167
-
168
- // Equipos
169
- lines.push('## Equipos de agentes (paralelización real)');
170
- lines.push('');
171
- lines.push('| Equipo | Líder | Miembros paralelos | Cuándo |');
172
- lines.push('|--------|-------|-------------------|--------|');
173
- lines.push('| Discovery | investigador-swl | investigador-ux-swl, producto-prd-swl | Proyecto nuevo |');
174
- lines.push('| Arquitectura | arquitecto-swl | rendimiento-swl, revisor-seguridad-swl | Decisión de diseño |');
175
- lines.push('| Frontend | frontend-swl | frontend-react-swl, frontend-css-swl, frontend-tailwind-swl | Feature UI compleja |');
176
- lines.push('| Backend | backend-python-swl | backend-api-swl, backend-workers-swl | Feature backend compleja |');
177
- lines.push('| Mobile | mobile-cross-swl | mobile-android-swl, mobile-ios-swl, mobile-testing-swl | Feature mobile |');
178
- lines.push('| Calidad | tdd-qa-swl | revisor-codigo-swl, revisor-seguridad-swl, accesibilidad-wcag-swl | Pre-release |');
179
- lines.push('| Operaciones | devops-ci-swl | cloud-infra-swl, observabilidad-swl, sre-swl | Deploy, infra, confiabilidad |');
180
- lines.push('| Cierre | consolidador-swl | documentador-swl, release-manager-swl, notificador-swl | Fase completada |');
181
- lines.push('');
182
-
183
- // Agentes
184
- lines.push(`## Agentes SWL — Registro completo (${agentes.length})`);
185
- lines.push('');
186
- lines.push('| Agente | Versión | Modelo | Riesgo |');
187
- lines.push('|--------|---------|--------|--------|');
188
- for (const a of agentes.sort((x, y) => x.name.localeCompare(y.name))) {
189
- lines.push(`| ${a.name} | ${a.version} | ${a.model} | ${a.nivelRiesgo} |`);
190
- }
191
- lines.push('');
192
-
193
- // Hooks
194
- lines.push(`## Hooks activos (${hooks.length} + ${libs.length} librerías)`);
195
- lines.push('');
196
- lines.push('| Hook | Archivo |');
197
- lines.push('|------|---------|');
198
- for (const h of hooks.sort()) {
199
- lines.push(`| ${h.replace('.js', '')} | \`hooks/${h}\` |`);
200
- }
201
- lines.push('');
202
-
203
- // Libs
204
- lines.push(`### Librerías de hooks (hooks/lib/) ${libs.length}`);
205
- lines.push('');
206
- lines.push('| Librería | Archivo |');
207
- lines.push('|----------|---------|');
208
- for (const l of libs.sort()) {
209
- lines.push(`| ${l.replace('.js', '')} | \`hooks/lib/${l}\` |`);
210
- }
211
- lines.push('');
212
-
213
- return lines.join('\n');
214
- }
215
-
216
- // ── Generar SALUD.md ──────────────────────────────────────────────────
217
-
218
- /**
219
- * Componentes críticos del sistema cuya conducta debe estar verificada con
220
- * tests/evals para que el score conductual no sea opaco.
221
- *
222
- * Cada entrada lista los keywords que matchean nombres de archivos en tests/
223
- * o evals/. Si al menos un archivo coincide, el componente tiene cobertura
224
- * conductual mínima.
225
- */
226
- const COMPONENTES_CRITICOS = [
227
- { id: 'orquestador', keywords: ['orquestador', 'orquestacion'] },
228
- { id: 'auto-evolucion', keywords: ['auto-evolucion', 'auto-evolution'] },
229
- { id: 'red-team', keywords: ['red-team', 'redteam'] },
230
- { id: 'risk-scoring', keywords: ['risk-scoring', 'risk_scoring', 'risk-engine'] },
231
- { id: 'memory-search', keywords: ['memory-search', 'memoria-busqueda'] },
232
- { id: 'command-relay', keywords: ['command-relay', 'gateway'] },
233
- { id: 'privacy-filter', keywords: ['privacy', 'privacy-filter', 'privacy-memoria'] },
234
- { id: 'delegation', keywords: ['delegation', 'delegacion'] },
235
- ];
236
-
237
- /**
238
- * Calcula cobertura conductual: cuántos componentes críticos tienen ≥1 archivo
239
- * de test o eval. NO mide calidad de los tests — solo presencia mínima.
240
- */
241
- function calcularScoreConductual() {
242
- const todosTests = [];
243
- const walk = (dir) => {
244
- let entries;
245
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
246
- catch { return; }
247
- for (const e of entries) {
248
- const full = path.join(dir, e.name);
249
- if (e.isDirectory()) walk(full);
250
- else todosTests.push(full.toLowerCase());
251
- }
252
- };
253
- walk(path.join(RAIZ, 'tests'));
254
- // También considerar evals dentro de habilidades/*/evals/
255
- walk(path.join(RAIZ, 'habilidades'));
256
-
257
- const cobertura = COMPONENTES_CRITICOS.map(c => {
258
- const cubierto = todosTests.some(t =>
259
- c.keywords.some(k => t.includes(k.toLowerCase()))
260
- );
261
- return { id: c.id, cubierto };
262
- });
263
-
264
- const cubiertos = cobertura.filter(c => c.cubierto).length;
265
- const total = cobertura.length;
266
- return {
267
- cubiertos,
268
- total,
269
- porcentaje: Math.round((cubiertos / total) * 100),
270
- detalle: cobertura,
271
- };
272
- }
273
-
274
- function generarSalud() {
275
- const pkg = JSON.parse(fs.readFileSync(path.join(RAIZ, 'package.json'), 'utf8'));
276
- const plugin = JSON.parse(fs.readFileSync(path.join(RAIZ, 'plugin.json'), 'utf8'));
277
- const agentes = recolectarAgentes();
278
- const skills = recolectarSkills();
279
- const hooks = recolectarHooks();
280
- const libs = recolectarLibs();
281
- const comandos = contarArchivos(path.join(RAIZ, 'comandos', 'swl'), '.md');
282
- const reglasBase = contarArchivos(path.join(RAIZ, 'reglas'), '.md');
283
- const reglasLang = fs.readdirSync(path.join(RAIZ, 'reglas', 'lenguajes'))
284
- .filter(d => fs.statSync(path.join(RAIZ, 'reglas', 'lenguajes', d)).isDirectory())
285
- .reduce((acc, d) => acc + contarArchivos(path.join(RAIZ, 'reglas', 'lenguajes', d), '.md'), 0);
286
- const schemas = contarArchivos(path.join(RAIZ, 'schemas'), '.json');
287
-
288
- // Verificar sintaxis
289
- const hookSyntax = verificarSintaxis(hooks, path.join(RAIZ, 'hooks'));
290
- const libSyntax = verificarSintaxis(libs, path.join(RAIZ, 'hooks', 'lib'));
291
-
292
- // Verificar frontmatter
293
- let agentesOk = 0;
294
- for (const a of agentes) {
295
- if (a.name !== '?' && a.version !== '?') agentesOk++;
296
- }
297
-
298
- // Verificar versiones
299
- const versionConsistente = pkg.version === plugin.version;
300
-
301
- // Problemas estructurales
302
- const problemas = [];
303
- if (!versionConsistente) problemas.push(`Versiones inconsistentes: package.json=${pkg.version} plugin.json=${plugin.version}`);
304
- if (hookSyntax.fail > 0) problemas.push(`${hookSyntax.fail} hooks con error de sintaxis`);
305
- if (libSyntax.fail > 0) problemas.push(`${libSyntax.fail} libs con error de sintaxis`);
306
-
307
- const scoreEstructural = problemas.length === 0
308
- ? '100%'
309
- : `${Math.round((1 - problemas.length / 10) * 100)}%`;
310
- const estadoEstructural = problemas.length === 0 ? 'Excelente' : 'Con problemas';
311
-
312
- // Score conductual (cobertura mínima por componente crítico)
313
- const conductual = calcularScoreConductual();
314
- let estadoConductual;
315
- if (conductual.porcentaje >= 80) estadoConductual = 'Excelente';
316
- else if (conductual.porcentaje >= 50) estadoConductual = 'Aceptable';
317
- else if (conductual.porcentaje >= 20) estadoConductual = 'Insuficiente';
318
- else estadoConductual = 'Crítico';
319
-
320
- const lines = [];
321
- lines.push('# Reporte de Salud del Sistema SWL');
322
- lines.push('');
323
- lines.push(`**Generado**: ${new Date().toISOString().slice(0, 10)}`);
324
- lines.push(`**Versión del sistema**: ${pkg.version}`);
325
- lines.push('');
326
- lines.push('> Archivo generado automáticamente por `node scripts/generar-inventario.js --salud`.');
327
- lines.push('> NO editar manualmente — se regenera con cada release.');
328
- lines.push('');
329
- lines.push('## Dos scores, dos preguntas');
330
- lines.push('');
331
- lines.push('- **Score estructural**: ¿el paquete está bien armado? (frontmatter,');
332
- lines.push(' sintaxis, schemas, manifiestos, versiones consistentes).');
333
- lines.push('- **Score conductual**: ¿el sistema hace lo que dice hacer? (cobertura');
334
- lines.push(' de tests/evals para componentes críticos: orquestación, evolución,');
335
- lines.push(' seguridad, memoria, gateway).');
336
- lines.push('');
337
- lines.push('Un score estructural alto sin score conductual igual NO implica que el');
338
- lines.push('sistema funcione — solo que está bien empaquetado. La separación es');
339
- lines.push('honestidad operativa: ver `.planning/adrs/` para histórico de decisiones.');
340
- lines.push('');
341
- lines.push(`## Score estructural: ${scoreEstructural} — ${estadoEstructural}`);
342
- lines.push('');
343
- lines.push('| Componente | Score | Estado | Problemas |');
344
- lines.push('|------------|-------|--------|-----------|');
345
- lines.push(`| Agentes | ${agentesOk === agentes.length ? '100%' : Math.round(agentesOk / agentes.length * 100) + '%'} | ${agentesOk === agentes.length ? 'Excelente' : 'Advertencia'} | ${agentes.length - agentesOk} |`);
346
- lines.push(`| Skills | 100% | Excelente | 0 |`);
347
- lines.push(`| Comandos | 100% | Excelente | 0 |`);
348
- lines.push(`| Reglas | 100% | Excelente | 0 (${reglasBase} base + ${reglasLang} lenguaje) |`);
349
- lines.push(`| Hooks | ${hookSyntax.fail === 0 ? '100%' : Math.round(hookSyntax.ok / hookSyntax.total * 100) + '%'} | ${hookSyntax.fail === 0 ? 'Excelente' : 'Error'} | ${hookSyntax.fail} |`);
350
- lines.push(`| Hook libs | ${libSyntax.fail === 0 ? '100%' : Math.round(libSyntax.ok / libSyntax.total * 100) + '%'} | ${libSyntax.fail === 0 ? 'Excelente' : 'Error'} | ${libSyntax.fail} |`);
351
- lines.push(`| Schemas | 100% | Excelente | 0 (${schemas} schemas) |`);
352
- lines.push(`| Versiones | ${versionConsistente ? '100%' : '0%'} | ${versionConsistente ? 'Consistentes' : 'ERROR'} | package.json = plugin.json = ${pkg.version} |`);
353
- lines.push('');
354
-
355
- lines.push(`## Score conductual: ${conductual.porcentaje}% — ${estadoConductual}`);
356
- lines.push('');
357
- lines.push(`Cobertura mínima de tests/evals por componente crítico: ${conductual.cubiertos}/${conductual.total}.`);
358
- lines.push('');
359
- lines.push('Este score mide **presencia** de tests, no calidad. Un componente con un');
360
- lines.push('solo test marca como cubierto. Subir esta cifra requiere agregar evals');
361
- lines.push('comportamentales por componente ver propuesta #4 en `.planning/`.');
362
- lines.push('');
363
- lines.push('| Componente crítico | Cobertura |');
364
- lines.push('|--------------------|-----------|');
365
- for (const c of conductual.detalle) {
366
- const icono = c.cubierto ? '' : '❌';
367
- lines.push(`| ${c.id} | ${icono} ${c.cubierto ? 'sí' : 'no falta eval'} |`);
368
- }
369
- lines.push('');
370
-
371
- if (problemas.length > 0) {
372
- lines.push('## Problemas estructurales detectados');
373
- lines.push('');
374
- for (const p of problemas) lines.push(`- ${p}`);
375
- lines.push('');
376
- } else {
377
- lines.push('## Problemas estructurales');
378
- lines.push('');
379
- lines.push('Ninguno.');
380
- lines.push('');
381
- }
382
-
383
- lines.push('## Verificaciones positivas (estructurales)');
384
- lines.push('');
385
- lines.push(`- **Frontmatter**: ${agentes.length} agentes + ${skills.length} skills + ${comandos} comandos verificados`);
386
- lines.push(`- **Skills**: ${skills.length}/${skills.length} con SKILL.md presente`);
387
- lines.push(`- **Hooks sintaxis**: ${hookSyntax.ok}/${hookSyntax.total} pasan \`node --check\``);
388
- lines.push(`- **Hook libs sintaxis**: ${libSyntax.ok}/${libSyntax.total} pasan \`node --check\``);
389
- lines.push(`- **Versiones**: package.json (${pkg.version}) = plugin.json (${plugin.version})`);
390
- lines.push(`- **Reglas base**: ${reglasBase} con estructura válida`);
391
- lines.push(`- **Reglas lenguajes**: ${reglasLang} archivos`);
392
- lines.push(`- **Schemas**: ${schemas} archivos JSON válidos`);
393
- lines.push('');
394
-
395
- return lines.join('\n');
396
- }
397
-
398
- // ── Ejecutar ──────────────────────────────────────────────────────────
399
-
400
- if (AMBOS || SOLO_INV) {
401
- const inventario = generarInventario();
402
- if (DRY) {
403
- console.log('=== INVENTARIO.md (dry-run) ===\n');
404
- console.log(inventario.substring(0, 2000) + '\n...(truncado)');
405
- } else {
406
- atomicWriteSync(path.join(RAIZ, 'INVENTARIO.md'), inventario, 'utf8');
407
- console.log('INVENTARIO.md generado correctamente.');
408
- }
409
- }
410
-
411
- if (AMBOS || SOLO_SAL) {
412
- const salud = generarSalud();
413
- if (DRY) {
414
- console.log('\n=== SALUD.md (dry-run) ===\n');
415
- console.log(salud);
416
- } else {
417
- atomicWriteSync(path.join(RAIZ, 'SALUD.md'), salud, 'utf8');
418
- console.log('SALUD.md generado correctamente.');
419
- }
420
- }
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * generar-inventario.js — Genera INVENTARIO.md y SALUD.md desde el disco.
6
+ *
7
+ * Elimina la necesidad de mantener estos archivos manualmente.
8
+ * Lee el estado real de agentes/, habilidades/, hooks/, etc.
9
+ *
10
+ * Uso:
11
+ * node scripts/generar-inventario.js # Genera ambos
12
+ * node scripts/generar-inventario.js --inventario # Solo INVENTARIO.md
13
+ * node scripts/generar-inventario.js --salud # Solo SALUD.md
14
+ * node scripts/generar-inventario.js --dry-run # Muestra sin escribir
15
+ *
16
+ * @module scripts/generar-inventario
17
+ */
18
+
19
+ const fs = require('fs');
20
+ const path = require('path');
21
+
22
+ const RAIZ = path.resolve(__dirname, '..');
23
+
24
+ // Escritura atómica obligatoria (regla CLAUDE.md). INVENTARIO.md y SALUD.md
25
+ // son artefactos de release; corrupción durante regeneración rompe la gate.
26
+ let atomicWriteSync;
27
+ try {
28
+ ({ atomicWriteSync } = require(path.join(RAIZ, 'hooks', 'lib', 'atomic-write.js')));
29
+ } catch {
30
+ atomicWriteSync = (p, c, e) => fs.writeFileSync(p, c, e);
31
+ }
32
+ const args = new Set(process.argv.slice(2));
33
+ const DRY = args.has('--dry-run');
34
+ const SOLO_INV = args.has('--inventario');
35
+ const SOLO_SAL = args.has('--salud');
36
+ const AMBOS = !SOLO_INV && !SOLO_SAL;
37
+
38
+ // ── Helpers ────────────────────────────────────────────────────────────
39
+
40
+ function leerFrontmatter(ruta) {
41
+ try {
42
+ const contenido = fs.readFileSync(ruta, 'utf8');
43
+ const match = contenido.match(/^---\r?\n([\s\S]*?)\r?\n---/);
44
+ if (!match) return {};
45
+ const fm = {};
46
+ for (const linea of match[1].split(/\r?\n/)) {
47
+ const idx = linea.indexOf(':');
48
+ if (idx > 0) {
49
+ const key = linea.slice(0, idx).trim();
50
+ const val = linea.slice(idx + 1).trim().replace(/^["']|["']$/g, '');
51
+ fm[key] = val;
52
+ }
53
+ }
54
+ return fm;
55
+ } catch { return {}; }
56
+ }
57
+
58
+ function contarArchivos(dir, ext) {
59
+ try {
60
+ return fs.readdirSync(dir).filter(f => f.endsWith(ext)).length;
61
+ } catch { return 0; }
62
+ }
63
+
64
+ function contarDirectorios(dir) {
65
+ try {
66
+ return fs.readdirSync(dir).filter(d =>
67
+ fs.statSync(path.join(dir, d)).isDirectory()
68
+ ).length;
69
+ } catch { return 0; }
70
+ }
71
+
72
+ function contarSkills(dir) {
73
+ try {
74
+ return fs.readdirSync(dir).filter(d => {
75
+ const skillMd = path.join(dir, d, 'SKILL.md');
76
+ return fs.existsSync(skillMd);
77
+ }).length;
78
+ } catch { return 0; }
79
+ }
80
+
81
+ // ── Recolectar datos ──────────────────────────────────────────────────
82
+
83
+ function recolectarAgentes() {
84
+ const dir = path.join(RAIZ, 'agentes');
85
+ const archivos = fs.readdirSync(dir).filter(f => f.endsWith('.md'));
86
+ return archivos.map(f => {
87
+ const fm = leerFrontmatter(path.join(dir, f));
88
+ return {
89
+ archivo: f,
90
+ name: fm.name || f.replace('.md', ''),
91
+ version: fm.version || '?',
92
+ model: fm.model || '?',
93
+ nivelRiesgo: fm.nivelRiesgo || '?',
94
+ };
95
+ });
96
+ }
97
+
98
+ function recolectarSkills() {
99
+ const dir = path.join(RAIZ, 'habilidades');
100
+ const dirs = fs.readdirSync(dir).filter(d =>
101
+ fs.existsSync(path.join(dir, d, 'SKILL.md'))
102
+ );
103
+ return dirs.map(d => {
104
+ const fm = leerFrontmatter(path.join(dir, d, 'SKILL.md'));
105
+ return { dir: d, name: fm.name || d, description: (fm.description || '').substring(0, 80) };
106
+ });
107
+ }
108
+
109
+ function recolectarHooks() {
110
+ const dir = path.join(RAIZ, 'hooks');
111
+ return fs.readdirSync(dir).filter(f => f.endsWith('.js') && f !== 'lib');
112
+ }
113
+
114
+ function recolectarLibs() {
115
+ const dir = path.join(RAIZ, 'hooks', 'lib');
116
+ return fs.readdirSync(dir).filter(f => f.endsWith('.js'));
117
+ }
118
+
119
+ function verificarSintaxis(archivos, dirBase) {
120
+ const { execSync } = require('child_process');
121
+ let ok = 0, fail = 0;
122
+ for (const f of archivos) {
123
+ try {
124
+ execSync(`node -c "${path.join(dirBase, f)}"`, { stdio: 'pipe' });
125
+ ok++;
126
+ } catch { fail++; }
127
+ }
128
+ return { ok, fail, total: archivos.length };
129
+ }
130
+
131
+ // ── Generar INVENTARIO.md ─────────────────────────────────────────────
132
+
133
+ function generarInventario() {
134
+ const pkg = JSON.parse(fs.readFileSync(path.join(RAIZ, 'package.json'), 'utf8'));
135
+ const agentes = recolectarAgentes();
136
+ const skills = recolectarSkills();
137
+ const hooks = recolectarHooks();
138
+ const libs = recolectarLibs();
139
+ const comandos = contarArchivos(path.join(RAIZ, 'comandos', 'swl'), '.md');
140
+ const reglasBase = contarArchivos(path.join(RAIZ, 'reglas'), '.md');
141
+ const reglasLang = fs.readdirSync(path.join(RAIZ, 'reglas', 'lenguajes'))
142
+ .filter(d => fs.statSync(path.join(RAIZ, 'reglas', 'lenguajes', d)).isDirectory())
143
+ .reduce((acc, d) => acc + contarArchivos(path.join(RAIZ, 'reglas', 'lenguajes', d), '.md'), 0);
144
+ const schemas = contarArchivos(path.join(RAIZ, 'schemas'), '.json');
145
+ const scripts = contarArchivos(path.join(RAIZ, 'scripts', 'lib'), '.js') + contarArchivos(path.join(RAIZ, 'scripts', 'lib'), '.py');
146
+
147
+ const lines = [];
148
+ lines.push(`# INVENTARIO.md — Referencia completa de componentes SWL v${pkg.version}`);
149
+ lines.push('');
150
+ lines.push('> Archivo generado automáticamente por `node scripts/generar-inventario.js`.');
151
+ lines.push('> NO editar manualmente — se regenera con cada release.');
152
+ lines.push('');
153
+ lines.push('## Resumen');
154
+ lines.push('');
155
+ lines.push('| Componente | Cantidad |');
156
+ lines.push('|-----------|----------|');
157
+ lines.push(`| Agentes SWL | ${agentes.length} |`);
158
+ lines.push(`| Habilidades | ${skills.length} |`);
159
+ lines.push(`| Comandos | ${comandos} |`);
160
+ lines.push(`| Reglas base | ${reglasBase} |`);
161
+ lines.push(`| Reglas por lenguaje | ${reglasLang} |`);
162
+ lines.push(`| Hooks | ${hooks.length} |`);
163
+ lines.push(`| Librerías de hooks | ${libs.length} |`);
164
+ lines.push(`| Schemas | ${schemas} |`);
165
+ lines.push(`| Scripts lib | ${scripts} |`);
166
+ lines.push('');
167
+
168
+ // Equipos
169
+ lines.push('## Equipos de agentes (paralelización real)');
170
+ lines.push('');
171
+ lines.push('| Equipo | Líder | Miembros paralelos | Cuándo |');
172
+ lines.push('|--------|-------|-------------------|--------|');
173
+ lines.push('| Discovery | investigador-swl | investigador-ux-swl, producto-prd-swl | Proyecto nuevo |');
174
+ lines.push('| Arquitectura | arquitecto-swl | rendimiento-swl, revisor-seguridad-swl | Decisión de diseño |');
175
+ lines.push('| Frontend | frontend-swl | frontend-react-swl, frontend-css-swl, frontend-tailwind-swl | Feature UI compleja |');
176
+ lines.push('| Backend | backend-python-swl | backend-api-swl, backend-workers-swl | Feature backend compleja |');
177
+ lines.push('| Mobile | mobile-cross-swl | mobile-android-swl, mobile-ios-swl, mobile-testing-swl | Feature mobile |');
178
+ lines.push('| Calidad | tdd-qa-swl | revisor-codigo-swl, revisor-seguridad-swl, accesibilidad-wcag-swl | Pre-release |');
179
+ lines.push('| Operaciones | devops-ci-swl | cloud-infra-swl, observabilidad-swl, sre-swl | Deploy, infra, confiabilidad |');
180
+ lines.push('| Cierre | consolidador-swl | documentador-swl, release-manager-swl, notificador-swl | Fase completada |');
181
+ lines.push('');
182
+
183
+ // Agentes
184
+ lines.push(`## Agentes SWL — Registro completo (${agentes.length})`);
185
+ lines.push('');
186
+ lines.push('| Agente | Versión | Modelo | Riesgo |');
187
+ lines.push('|--------|---------|--------|--------|');
188
+ for (const a of agentes.sort((x, y) => x.name.localeCompare(y.name))) {
189
+ lines.push(`| ${a.name} | ${a.version} | ${a.model} | ${a.nivelRiesgo} |`);
190
+ }
191
+ lines.push('');
192
+
193
+ // Reglas — Registro completo (v1.6.1, Cabo A5)
194
+ const reglasBaseList = fs.readdirSync(path.join(RAIZ, 'reglas'))
195
+ .filter(f => f.endsWith('.md') && !f.startsWith('_'))
196
+ .sort();
197
+ lines.push(`## Reglas — Registro completo (${reglasBaseList.length} base + ${reglasLang} por lenguaje)`);
198
+ lines.push('');
199
+ lines.push('### Reglas base (transversales)');
200
+ lines.push('');
201
+ lines.push('| Regla | Archivo |');
202
+ lines.push('|-------|---------|');
203
+ for (const r of reglasBaseList) {
204
+ lines.push(`| ${r.replace('.md', '')} | \`reglas/${r}\` |`);
205
+ }
206
+ lines.push('');
207
+ lines.push('### Reglas por lenguaje');
208
+ lines.push('');
209
+ const dirLenguajes = path.join(RAIZ, 'reglas', 'lenguajes');
210
+ if (fs.existsSync(dirLenguajes)) {
211
+ const lenguajes = fs.readdirSync(dirLenguajes)
212
+ .filter(d => fs.statSync(path.join(dirLenguajes, d)).isDirectory())
213
+ .sort();
214
+ lines.push('| Lenguaje | Cantidad de reglas |');
215
+ lines.push('|----------|--------------------|');
216
+ for (const lang of lenguajes) {
217
+ const cnt = contarArchivos(path.join(dirLenguajes, lang), '.md');
218
+ lines.push(`| ${lang} | ${cnt} |`);
219
+ }
220
+ lines.push('');
221
+ }
222
+
223
+ // Hooks
224
+ lines.push(`## Hooks activos (${hooks.length} + ${libs.length} librerías)`);
225
+ lines.push('');
226
+ lines.push('| Hook | Archivo |');
227
+ lines.push('|------|---------|');
228
+ for (const h of hooks.sort()) {
229
+ lines.push(`| ${h.replace('.js', '')} | \`hooks/${h}\` |`);
230
+ }
231
+ lines.push('');
232
+
233
+ // Libs
234
+ lines.push(`### Librerías de hooks (hooks/lib/) — ${libs.length}`);
235
+ lines.push('');
236
+ lines.push('| Librería | Archivo |');
237
+ lines.push('|----------|---------|');
238
+ for (const l of libs.sort()) {
239
+ lines.push(`| ${l.replace('.js', '')} | \`hooks/lib/${l}\` |`);
240
+ }
241
+ lines.push('');
242
+
243
+ return lines.join('\n');
244
+ }
245
+
246
+ // ── Generar SALUD.md ──────────────────────────────────────────────────
247
+
248
+ /**
249
+ * Componentes críticos del sistema cuya conducta debe estar verificada con
250
+ * tests/evals para que el score conductual no sea opaco.
251
+ *
252
+ * Cada entrada lista los keywords que matchean nombres de archivos en tests/
253
+ * o evals/. Si al menos un archivo coincide, el componente tiene cobertura
254
+ * conductual mínima.
255
+ */
256
+ const COMPONENTES_CRITICOS = [
257
+ { id: 'orquestador', keywords: ['orquestador', 'orquestacion'] },
258
+ { id: 'auto-evolucion', keywords: ['auto-evolucion', 'auto-evolution'] },
259
+ { id: 'red-team', keywords: ['red-team', 'redteam'] },
260
+ { id: 'risk-scoring', keywords: ['risk-scoring', 'risk_scoring', 'risk-engine'] },
261
+ { id: 'memory-search', keywords: ['memory-search', 'memoria-busqueda'] },
262
+ { id: 'command-relay', keywords: ['command-relay', 'gateway'] },
263
+ { id: 'privacy-filter', keywords: ['privacy', 'privacy-filter', 'privacy-memoria'] },
264
+ { id: 'delegation', keywords: ['delegation', 'delegacion'] },
265
+ ];
266
+
267
+ /**
268
+ * Calcula cobertura conductual: cuántos componentes críticos tienen ≥1 archivo
269
+ * de test o eval. NO mide calidad de los tests — solo presencia mínima.
270
+ */
271
+ function calcularScoreConductual() {
272
+ const todosTests = [];
273
+ const walk = (dir) => {
274
+ let entries;
275
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
276
+ catch { return; }
277
+ for (const e of entries) {
278
+ const full = path.join(dir, e.name);
279
+ if (e.isDirectory()) walk(full);
280
+ else todosTests.push(full.toLowerCase());
281
+ }
282
+ };
283
+ walk(path.join(RAIZ, 'tests'));
284
+ // También considerar evals dentro de habilidades/*/evals/
285
+ walk(path.join(RAIZ, 'habilidades'));
286
+
287
+ const cobertura = COMPONENTES_CRITICOS.map(c => {
288
+ const cubierto = todosTests.some(t =>
289
+ c.keywords.some(k => t.includes(k.toLowerCase()))
290
+ );
291
+ return { id: c.id, cubierto };
292
+ });
293
+
294
+ const cubiertos = cobertura.filter(c => c.cubierto).length;
295
+ const total = cobertura.length;
296
+ return {
297
+ cubiertos,
298
+ total,
299
+ porcentaje: Math.round((cubiertos / total) * 100),
300
+ detalle: cobertura,
301
+ };
302
+ }
303
+
304
+ function generarSalud() {
305
+ const pkg = JSON.parse(fs.readFileSync(path.join(RAIZ, 'package.json'), 'utf8'));
306
+ const plugin = JSON.parse(fs.readFileSync(path.join(RAIZ, 'plugin.json'), 'utf8'));
307
+ const agentes = recolectarAgentes();
308
+ const skills = recolectarSkills();
309
+ const hooks = recolectarHooks();
310
+ const libs = recolectarLibs();
311
+ const comandos = contarArchivos(path.join(RAIZ, 'comandos', 'swl'), '.md');
312
+ const reglasBase = contarArchivos(path.join(RAIZ, 'reglas'), '.md');
313
+ const reglasLang = fs.readdirSync(path.join(RAIZ, 'reglas', 'lenguajes'))
314
+ .filter(d => fs.statSync(path.join(RAIZ, 'reglas', 'lenguajes', d)).isDirectory())
315
+ .reduce((acc, d) => acc + contarArchivos(path.join(RAIZ, 'reglas', 'lenguajes', d), '.md'), 0);
316
+ const schemas = contarArchivos(path.join(RAIZ, 'schemas'), '.json');
317
+
318
+ // Verificar sintaxis
319
+ const hookSyntax = verificarSintaxis(hooks, path.join(RAIZ, 'hooks'));
320
+ const libSyntax = verificarSintaxis(libs, path.join(RAIZ, 'hooks', 'lib'));
321
+
322
+ // Verificar frontmatter
323
+ let agentesOk = 0;
324
+ for (const a of agentes) {
325
+ if (a.name !== '?' && a.version !== '?') agentesOk++;
326
+ }
327
+
328
+ // Verificar versiones
329
+ const versionConsistente = pkg.version === plugin.version;
330
+
331
+ // Problemas estructurales
332
+ const problemas = [];
333
+ if (!versionConsistente) problemas.push(`Versiones inconsistentes: package.json=${pkg.version} plugin.json=${plugin.version}`);
334
+ if (hookSyntax.fail > 0) problemas.push(`${hookSyntax.fail} hooks con error de sintaxis`);
335
+ if (libSyntax.fail > 0) problemas.push(`${libSyntax.fail} libs con error de sintaxis`);
336
+
337
+ const scoreEstructural = problemas.length === 0
338
+ ? '100%'
339
+ : `${Math.round((1 - problemas.length / 10) * 100)}%`;
340
+ const estadoEstructural = problemas.length === 0 ? 'Excelente' : 'Con problemas';
341
+
342
+ // Score conductual (cobertura mínima por componente crítico)
343
+ const conductual = calcularScoreConductual();
344
+ let estadoConductual;
345
+ if (conductual.porcentaje >= 80) estadoConductual = 'Excelente';
346
+ else if (conductual.porcentaje >= 50) estadoConductual = 'Aceptable';
347
+ else if (conductual.porcentaje >= 20) estadoConductual = 'Insuficiente';
348
+ else estadoConductual = 'Crítico';
349
+
350
+ const lines = [];
351
+ lines.push('# Reporte de Salud del Sistema SWL');
352
+ lines.push('');
353
+ lines.push(`**Generado**: ${new Date().toISOString().slice(0, 10)}`);
354
+ lines.push(`**Versión del sistema**: ${pkg.version}`);
355
+ lines.push('');
356
+ lines.push('> Archivo generado automáticamente por `node scripts/generar-inventario.js --salud`.');
357
+ lines.push('> NO editar manualmente se regenera con cada release.');
358
+ lines.push('');
359
+ lines.push('## Dos scores, dos preguntas');
360
+ lines.push('');
361
+ lines.push('- **Score estructural**: ¿el paquete está bien armado? (frontmatter,');
362
+ lines.push(' sintaxis, schemas, manifiestos, versiones consistentes).');
363
+ lines.push('- **Score conductual**: ¿el sistema hace lo que dice hacer? (cobertura');
364
+ lines.push(' de tests/evals para componentes críticos: orquestación, evolución,');
365
+ lines.push(' seguridad, memoria, gateway).');
366
+ lines.push('');
367
+ lines.push('Un score estructural alto sin score conductual igual NO implica que el');
368
+ lines.push('sistema funcione — solo que está bien empaquetado. La separación es');
369
+ lines.push('honestidad operativa: ver `.planning/adrs/` para histórico de decisiones.');
370
+ lines.push('');
371
+ lines.push(`## Score estructural: ${scoreEstructural} — ${estadoEstructural}`);
372
+ lines.push('');
373
+ lines.push('| Componente | Score | Estado | Problemas |');
374
+ lines.push('|------------|-------|--------|-----------|');
375
+ lines.push(`| Agentes | ${agentesOk === agentes.length ? '100%' : Math.round(agentesOk / agentes.length * 100) + '%'} | ${agentesOk === agentes.length ? 'Excelente' : 'Advertencia'} | ${agentes.length - agentesOk} |`);
376
+ lines.push(`| Skills | 100% | Excelente | 0 |`);
377
+ lines.push(`| Comandos | 100% | Excelente | 0 |`);
378
+ lines.push(`| Reglas | 100% | Excelente | 0 (${reglasBase} base + ${reglasLang} lenguaje) |`);
379
+ lines.push(`| Hooks | ${hookSyntax.fail === 0 ? '100%' : Math.round(hookSyntax.ok / hookSyntax.total * 100) + '%'} | ${hookSyntax.fail === 0 ? 'Excelente' : 'Error'} | ${hookSyntax.fail} |`);
380
+ lines.push(`| Hook libs | ${libSyntax.fail === 0 ? '100%' : Math.round(libSyntax.ok / libSyntax.total * 100) + '%'} | ${libSyntax.fail === 0 ? 'Excelente' : 'Error'} | ${libSyntax.fail} |`);
381
+ lines.push(`| Schemas | 100% | Excelente | 0 (${schemas} schemas) |`);
382
+ lines.push(`| Versiones | ${versionConsistente ? '100%' : '0%'} | ${versionConsistente ? 'Consistentes' : 'ERROR'} | package.json = plugin.json = ${pkg.version} |`);
383
+ lines.push('');
384
+
385
+ lines.push(`## Score conductual: ${conductual.porcentaje}% ${estadoConductual}`);
386
+ lines.push('');
387
+ lines.push(`Cobertura mínima de tests/evals por componente crítico: ${conductual.cubiertos}/${conductual.total}.`);
388
+ lines.push('');
389
+ lines.push('Este score mide **presencia** de tests, no calidad. Un componente con un');
390
+ lines.push('solo test marca como cubierto. Subir esta cifra requiere agregar evals');
391
+ lines.push('comportamentales por componente ver propuesta #4 en `.planning/`.');
392
+ lines.push('');
393
+ lines.push('| Componente crítico | Cobertura |');
394
+ lines.push('|--------------------|-----------|');
395
+ for (const c of conductual.detalle) {
396
+ const icono = c.cubierto ? '✅' : '❌';
397
+ lines.push(`| ${c.id} | ${icono} ${c.cubierto ? 'sí' : 'no — falta eval'} |`);
398
+ }
399
+ lines.push('');
400
+
401
+ if (problemas.length > 0) {
402
+ lines.push('## Problemas estructurales detectados');
403
+ lines.push('');
404
+ for (const p of problemas) lines.push(`- ${p}`);
405
+ lines.push('');
406
+ } else {
407
+ lines.push('## Problemas estructurales');
408
+ lines.push('');
409
+ lines.push('Ninguno.');
410
+ lines.push('');
411
+ }
412
+
413
+ lines.push('## Verificaciones positivas (estructurales)');
414
+ lines.push('');
415
+ lines.push(`- **Frontmatter**: ${agentes.length} agentes + ${skills.length} skills + ${comandos} comandos verificados`);
416
+ lines.push(`- **Skills**: ${skills.length}/${skills.length} con SKILL.md presente`);
417
+ lines.push(`- **Hooks sintaxis**: ${hookSyntax.ok}/${hookSyntax.total} pasan \`node --check\``);
418
+ lines.push(`- **Hook libs sintaxis**: ${libSyntax.ok}/${libSyntax.total} pasan \`node --check\``);
419
+ lines.push(`- **Versiones**: package.json (${pkg.version}) = plugin.json (${plugin.version})`);
420
+ lines.push(`- **Reglas base**: ${reglasBase} con estructura válida`);
421
+ lines.push(`- **Reglas lenguajes**: ${reglasLang} archivos`);
422
+ lines.push(`- **Schemas**: ${schemas} archivos JSON válidos`);
423
+ lines.push('');
424
+
425
+ return lines.join('\n');
426
+ }
427
+
428
+ // ── Ejecutar ──────────────────────────────────────────────────────────
429
+
430
+ if (AMBOS || SOLO_INV) {
431
+ const inventario = generarInventario();
432
+ if (DRY) {
433
+ console.log('=== INVENTARIO.md (dry-run) ===\n');
434
+ console.log(inventario.substring(0, 2000) + '\n...(truncado)');
435
+ } else {
436
+ atomicWriteSync(path.join(RAIZ, 'INVENTARIO.md'), inventario, 'utf8');
437
+ console.log('INVENTARIO.md generado correctamente.');
438
+ }
439
+ }
440
+
441
+ if (AMBOS || SOLO_SAL) {
442
+ const salud = generarSalud();
443
+ if (DRY) {
444
+ console.log('\n=== SALUD.md (dry-run) ===\n');
445
+ console.log(salud);
446
+ } else {
447
+ atomicWriteSync(path.join(RAIZ, 'SALUD.md'), salud, 'utf8');
448
+ console.log('SALUD.md generado correctamente.');
449
+ }
450
+ }