@saulwade/swl-ses 1.0.0 → 1.1.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 (108) hide show
  1. package/CLAUDE.md +8 -5
  2. package/README.md +2 -2
  3. package/agentes/accesibilidad-wcag-swl.md +5 -7
  4. package/agentes/arquitecto-swl.md +5 -3
  5. package/agentes/auto-evolucion-swl.md +42 -12
  6. package/agentes/backend-api-swl.md +5 -3
  7. package/agentes/backend-csharp-swl.md +5 -3
  8. package/agentes/backend-go-swl.md +5 -3
  9. package/agentes/backend-java-swl.md +5 -3
  10. package/agentes/backend-node-swl.md +5 -3
  11. package/agentes/backend-python-swl.md +5 -3
  12. package/agentes/backend-rust-swl.md +5 -3
  13. package/agentes/backend-workers-swl.md +5 -3
  14. package/agentes/cloud-infra-swl.md +5 -6
  15. package/agentes/consolidador-swl.md +5 -3
  16. package/agentes/datos-swl.md +5 -7
  17. package/agentes/depurador-swl.md +6 -3
  18. package/agentes/devops-ci-swl.md +5 -3
  19. package/agentes/disenador-ui-swl.md +5 -7
  20. package/agentes/documentador-swl.md +5 -3
  21. package/agentes/frontend-angular-swl.md +5 -11
  22. package/agentes/frontend-css-swl.md +5 -9
  23. package/agentes/frontend-react-swl.md +5 -9
  24. package/agentes/frontend-swl.md +5 -9
  25. package/agentes/frontend-tailwind-swl.md +5 -9
  26. package/agentes/implementador-swl.md +6 -3
  27. package/agentes/investigador-swl.md +5 -3
  28. package/agentes/investigador-ux-swl.md +5 -9
  29. package/agentes/llm-apps-swl.md +5 -3
  30. package/agentes/migrador-swl.md +6 -3
  31. package/agentes/mobile-android-swl.md +5 -3
  32. package/agentes/mobile-cross-swl.md +5 -3
  33. package/agentes/mobile-ios-swl.md +5 -3
  34. package/agentes/mobile-testing-swl.md +5 -3
  35. package/agentes/notificador-swl.md +5 -3
  36. package/agentes/observabilidad-swl.md +5 -3
  37. package/agentes/orquestador-swl.md +29 -8
  38. package/agentes/pagos-swl.md +5 -3
  39. package/agentes/perfilador-usuario-swl.md +4 -2
  40. package/agentes/planificador-swl.md +5 -3
  41. package/agentes/producto-prd-swl.md +5 -3
  42. package/agentes/red-team-swl.md +4 -2
  43. package/agentes/release-manager-swl.md +6 -8
  44. package/agentes/rendimiento-swl.md +5 -6
  45. package/agentes/resolutor-build-swl.md +5 -3
  46. package/agentes/revisor-angular-swl.md +5 -3
  47. package/agentes/revisor-codigo-swl.md +5 -3
  48. package/agentes/revisor-csharp-swl.md +5 -3
  49. package/agentes/revisor-go-swl.md +5 -3
  50. package/agentes/revisor-java-swl.md +5 -3
  51. package/agentes/revisor-kotlin-swl.md +5 -3
  52. package/agentes/revisor-nextjs-swl.md +5 -3
  53. package/agentes/revisor-php-swl.md +5 -3
  54. package/agentes/revisor-react-swl.md +5 -3
  55. package/agentes/revisor-rust-swl.md +5 -3
  56. package/agentes/revisor-seguridad-swl.md +5 -3
  57. package/agentes/revisor-swift-swl.md +5 -3
  58. package/agentes/revisor-typescript-swl.md +5 -3
  59. package/agentes/sre-swl.md +5 -3
  60. package/agentes/tdd-qa-swl.md +5 -3
  61. package/agentes/ux-disenador-swl.md +5 -9
  62. package/bin/swl-ses.js +27 -6
  63. package/comandos/swl/evaluar-skill.md +18 -0
  64. package/comandos/swl/evolucion-estado.md +49 -0
  65. package/comandos/swl/release.md +41 -0
  66. package/comandos/swl/salud.md +23 -0
  67. package/hooks/auto-evolucion.js +35 -1
  68. package/hooks/clasificador-mensajes.js +50 -3
  69. package/hooks/lib/agent-routing.js +107 -0
  70. package/hooks/lib/delegation-tracker.js +162 -44
  71. package/hooks/lib/evolution-tracker.js +12 -3
  72. package/hooks/lib/memory-search.js +59 -1
  73. package/hooks/lib/nudge-tracker.js +10 -1
  74. package/hooks/lib/provenance-tracker.js +11 -3
  75. package/hooks/lib/text-similarity.js +241 -0
  76. package/hooks/metricas-evolucion.js +168 -1
  77. package/hooks/monitor-contexto.js +54 -6
  78. package/hooks/preservar-estado-pre-compact.js +11 -1
  79. package/hooks/risk-scoring.js +10 -1
  80. package/hooks/tracking-costos.js +10 -1
  81. package/hooks/validar-formato-post-subagente.js +140 -0
  82. package/hooks/validar-memoria-hook.js +218 -0
  83. package/manifiestos/agent-output-schemas.json +57 -0
  84. package/manifiestos/hooks-config.json +18 -0
  85. package/manifiestos/modulos.json +5 -1
  86. package/manifiestos/skills-lock.json +1065 -0
  87. package/package.json +4 -6
  88. package/plugin.json +1 -1
  89. package/reglas/arquitectura.md +20 -0
  90. package/reglas/fragmentos-compartidos.md +152 -0
  91. package/reglas/gobernanza.md +10 -1
  92. package/reglas/seguridad-agentes.md +12 -0
  93. package/reglas/skills-estandar.md +19 -0
  94. package/reglas/usar-context7.md +226 -0
  95. package/schemas/agent-frontmatter.schema.json +18 -0
  96. package/scripts/auditar-agentes-gaps.js +9 -1
  97. package/scripts/auditar-cobertura-frameworks.js +9 -1
  98. package/scripts/auditar-skills-gaps.js +9 -1
  99. package/scripts/bootstrap-instintos.js +11 -1
  100. package/scripts/generar-inventario.js +112 -9
  101. package/scripts/generar-matriz-lenguajes.js +271 -0
  102. package/scripts/generar-skills-lock.js +190 -0
  103. package/scripts/lib/estado.js +12 -2
  104. package/scripts/lib/gitignore-manifest.js +32 -2
  105. package/scripts/lib/semantic-search.js +10 -0
  106. package/scripts/migrar-csv-a-array.js +168 -0
  107. package/scripts/migrar-fase-dominio.js +201 -0
  108. package/scripts/validar-userland-vacio.js +110 -0
@@ -20,6 +20,15 @@ const fs = require('fs');
20
20
  const path = require('path');
21
21
 
22
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
+ }
23
32
  const args = new Set(process.argv.slice(2));
24
33
  const DRY = args.has('--dry-run');
25
34
  const SOLO_INV = args.has('--inventario');
@@ -206,6 +215,62 @@ function generarInventario() {
206
215
 
207
216
  // ── Generar SALUD.md ──────────────────────────────────────────────────
208
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
+
209
274
  function generarSalud() {
210
275
  const pkg = JSON.parse(fs.readFileSync(path.join(RAIZ, 'package.json'), 'utf8'));
211
276
  const plugin = JSON.parse(fs.readFileSync(path.join(RAIZ, 'plugin.json'), 'utf8'));
@@ -233,14 +298,24 @@ function generarSalud() {
233
298
  // Verificar versiones
234
299
  const versionConsistente = pkg.version === plugin.version;
235
300
 
236
- // Problemas
301
+ // Problemas estructurales
237
302
  const problemas = [];
238
303
  if (!versionConsistente) problemas.push(`Versiones inconsistentes: package.json=${pkg.version} plugin.json=${plugin.version}`);
239
304
  if (hookSyntax.fail > 0) problemas.push(`${hookSyntax.fail} hooks con error de sintaxis`);
240
305
  if (libSyntax.fail > 0) problemas.push(`${libSyntax.fail} libs con error de sintaxis`);
241
306
 
242
- const score = problemas.length === 0 ? '100%' : `${Math.round((1 - problemas.length / 10) * 100)}%`;
243
- const estado = problemas.length === 0 ? 'Excelente' : 'Con problemas';
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';
244
319
 
245
320
  const lines = [];
246
321
  lines.push('# Reporte de Salud del Sistema SWL');
@@ -251,7 +326,19 @@ function generarSalud() {
251
326
  lines.push('> Archivo generado automáticamente por `node scripts/generar-inventario.js --salud`.');
252
327
  lines.push('> NO editar manualmente — se regenera con cada release.');
253
328
  lines.push('');
254
- lines.push(`## Score Global: ${score} — Sistema en ${estado.toLowerCase()}`);
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}`);
255
342
  lines.push('');
256
343
  lines.push('| Componente | Score | Estado | Problemas |');
257
344
  lines.push('|------------|-------|--------|-----------|');
@@ -265,19 +352,35 @@ function generarSalud() {
265
352
  lines.push(`| Versiones | ${versionConsistente ? '100%' : '0%'} | ${versionConsistente ? 'Consistentes' : 'ERROR'} | package.json = plugin.json = ${pkg.version} |`);
266
353
  lines.push('');
267
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
+
268
371
  if (problemas.length > 0) {
269
- lines.push('## Problemas detectados');
372
+ lines.push('## Problemas estructurales detectados');
270
373
  lines.push('');
271
374
  for (const p of problemas) lines.push(`- ${p}`);
272
375
  lines.push('');
273
376
  } else {
274
- lines.push('## Problemas críticos');
377
+ lines.push('## Problemas estructurales');
275
378
  lines.push('');
276
379
  lines.push('Ninguno.');
277
380
  lines.push('');
278
381
  }
279
382
 
280
- lines.push('## Verificaciones positivas');
383
+ lines.push('## Verificaciones positivas (estructurales)');
281
384
  lines.push('');
282
385
  lines.push(`- **Frontmatter**: ${agentes.length} agentes + ${skills.length} skills + ${comandos} comandos verificados`);
283
386
  lines.push(`- **Skills**: ${skills.length}/${skills.length} con SKILL.md presente`);
@@ -300,7 +403,7 @@ if (AMBOS || SOLO_INV) {
300
403
  console.log('=== INVENTARIO.md (dry-run) ===\n');
301
404
  console.log(inventario.substring(0, 2000) + '\n...(truncado)');
302
405
  } else {
303
- fs.writeFileSync(path.join(RAIZ, 'INVENTARIO.md'), inventario, 'utf8');
406
+ atomicWriteSync(path.join(RAIZ, 'INVENTARIO.md'), inventario, 'utf8');
304
407
  console.log('INVENTARIO.md generado correctamente.');
305
408
  }
306
409
  }
@@ -311,7 +414,7 @@ if (AMBOS || SOLO_SAL) {
311
414
  console.log('\n=== SALUD.md (dry-run) ===\n');
312
415
  console.log(salud);
313
416
  } else {
314
- fs.writeFileSync(path.join(RAIZ, 'SALUD.md'), salud, 'utf8');
417
+ atomicWriteSync(path.join(RAIZ, 'SALUD.md'), salud, 'utf8');
315
418
  console.log('SALUD.md generado correctamente.');
316
419
  }
317
420
  }
@@ -0,0 +1,271 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * generar-matriz-lenguajes.js
6
+ *
7
+ * Recorre `agentes/`, `habilidades/` y `reglas/lenguajes/` y produce una
8
+ * matriz de cobertura por lenguaje en `.planning/cobertura-lenguajes.md`.
9
+ *
10
+ * Para cada lenguaje detectado, reporta:
11
+ * - Agentes (backend/frontend/mobile/revisor) que lo cubren.
12
+ * - Skills (experto, patrones, testing, build-errors).
13
+ * - Subdirectorio en reglas/lenguajes/.
14
+ * - Status de cobertura: completo (≥4 elementos) | parcial (1-3) | faltante (0).
15
+ *
16
+ * Uso: ejecutar como parte de `/swl:salud` o pre-release.
17
+ * node scripts/generar-matriz-lenguajes.js
18
+ *
19
+ * Zero-deps. Idempotente.
20
+ */
21
+
22
+ const fs = require('fs');
23
+ const path = require('path');
24
+
25
+ const ROOT = process.cwd();
26
+ const SALIDA = path.join(ROOT, '.planning', 'cobertura-lenguajes.md');
27
+
28
+ // Cargar atomic-write desde hooks/lib/ (regla obligatoria de CLAUDE.md:
29
+ // escrituras atómicas para archivos de estado y artefactos en .planning/).
30
+ const { atomicWriteSync } = require(path.join(ROOT, 'hooks', 'lib', 'atomic-write.js'));
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // Lenguajes a evaluar (taxonomía SWL)
34
+ // ---------------------------------------------------------------------------
35
+
36
+ /**
37
+ * Cada entrada define:
38
+ * - clave: nombre interno usado para matchear archivos.
39
+ * - etiqueta: nombre humano para el reporte.
40
+ * - agentesEsperados: prefijos/sufijos en agentes/.
41
+ * - skillsEsperados: prefijos en habilidades/.
42
+ * - reglaSubdir: nombre esperado en reglas/lenguajes/ (null si no aplica).
43
+ * - smokeMin: ejemplo mínimo de smoke test en CI.
44
+ */
45
+ const LENGUAJES = [
46
+ { clave: 'python', etiqueta: 'Python',
47
+ agentesEsperados: ['backend-python-swl'],
48
+ skillsKeywords: ['async-python', 'django', 'fastapi', 'python', 'sqlalchemy'],
49
+ revisor: null,
50
+ reglaSubdir: null,
51
+ smokeMin: '`pytest -x` + smoke import de paquete principal.' },
52
+ { clave: 'node', etiqueta: 'Node/TypeScript',
53
+ agentesEsperados: ['backend-node-swl'],
54
+ skillsKeywords: ['typescript', 'node-experto', 'fastify', 'express', 'nestjs', 'prisma'],
55
+ revisor: 'revisor-typescript-swl',
56
+ reglaSubdir: null,
57
+ smokeMin: '`vitest run` o `jest --ci` + `tsc --noEmit`.' },
58
+ { clave: 'java', etiqueta: 'Java',
59
+ agentesEsperados: ['backend-java-swl'],
60
+ skillsKeywords: ['java-experto', 'java-patrones', 'java-testing', 'build-errors-java', 'spring'],
61
+ revisor: 'revisor-java-swl',
62
+ reglaSubdir: 'java',
63
+ smokeMin: '`mvn test` o `gradle test` con cobertura mínima de JaCoCo.' },
64
+ { clave: 'go', etiqueta: 'Go',
65
+ agentesEsperados: ['backend-go-swl'],
66
+ skillsKeywords: ['go-experto', 'go-patrones', 'go-testing', 'build-errors-go'],
67
+ revisor: 'revisor-go-swl',
68
+ reglaSubdir: 'go',
69
+ smokeMin: '`go test ./... -race -count=1`.' },
70
+ { clave: 'rust', etiqueta: 'Rust',
71
+ agentesEsperados: ['backend-rust-swl'],
72
+ skillsKeywords: ['rust-experto', 'rust-patrones', 'rust-testing', 'build-errors-rust', 'axum', 'actix'],
73
+ revisor: 'revisor-rust-swl',
74
+ reglaSubdir: 'rust',
75
+ smokeMin: '`cargo test` + `cargo clippy -- -D warnings`.' },
76
+ { clave: 'csharp', etiqueta: 'C# / .NET',
77
+ agentesEsperados: ['backend-csharp-swl'],
78
+ skillsKeywords: ['csharp-experto', 'csharp-patrones', 'csharp-testing', 'build-errors-csharp', 'efcore'],
79
+ revisor: 'revisor-csharp-swl',
80
+ reglaSubdir: 'csharp',
81
+ smokeMin: '`dotnet test --no-build` con xUnit/NUnit y coverlet.' },
82
+ { clave: 'php', etiqueta: 'PHP / Laravel',
83
+ agentesEsperados: [],
84
+ skillsKeywords: ['php-experto', 'php-patrones', 'php-testing', 'build-errors-php', 'laravel'],
85
+ revisor: 'revisor-php-swl',
86
+ reglaSubdir: 'php',
87
+ smokeMin: '`vendor/bin/phpunit` o `pest` + `phpstan analyse`.' },
88
+ { clave: 'kotlin', etiqueta: 'Kotlin (Android)',
89
+ agentesEsperados: ['mobile-android-swl'],
90
+ skillsKeywords: ['kotlin-compose', 'kotlin-experto', 'kotlin-testing', 'build-errors-kotlin'],
91
+ revisor: 'revisor-kotlin-swl',
92
+ reglaSubdir: 'kotlin',
93
+ smokeMin: '`./gradlew test connectedAndroidTest` (al menos JVM tests).' },
94
+ { clave: 'swift', etiqueta: 'Swift (iOS)',
95
+ agentesEsperados: ['mobile-ios-swl'],
96
+ skillsKeywords: ['swift-experto', 'swift-patrones', 'swift-testing', 'build-errors-swift', 'swiftui'],
97
+ revisor: 'revisor-swift-swl',
98
+ reglaSubdir: 'swift',
99
+ smokeMin: '`swift test` o `xcodebuild test` en scheme primario.' },
100
+ { clave: 'react', etiqueta: 'React',
101
+ agentesEsperados: ['frontend-react-swl'],
102
+ skillsKeywords: ['react', 'frontend-react'],
103
+ revisor: 'revisor-react-swl',
104
+ reglaSubdir: null,
105
+ smokeMin: 'React Testing Library con cobertura mínima de smoke render.' },
106
+ { clave: 'angular', etiqueta: 'Angular',
107
+ agentesEsperados: ['frontend-angular-swl'],
108
+ skillsKeywords: ['angular-avanzado', 'angular-moderno'],
109
+ revisor: 'revisor-angular-swl',
110
+ reglaSubdir: null,
111
+ smokeMin: '`ng test --watch=false --no-progress` con headless Chrome.' },
112
+ { clave: 'nextjs', etiqueta: 'Next.js',
113
+ agentesEsperados: [],
114
+ skillsKeywords: ['nextjs-experto', 'nextjs-patrones', 'nextjs-testing', 'build-errors-nextjs'],
115
+ revisor: 'revisor-nextjs-swl',
116
+ reglaSubdir: 'nextjs',
117
+ smokeMin: '`next build` + Playwright sobre rutas críticas.' },
118
+ { clave: 'reactnative', etiqueta: 'React Native / Flutter',
119
+ agentesEsperados: ['mobile-cross-swl'],
120
+ skillsKeywords: ['mobile-react-native', 'mobile-flutter', 'mobile-cross'],
121
+ revisor: null,
122
+ reglaSubdir: null,
123
+ smokeMin: '`detox test` (RN) o `flutter test` + `flutter analyze`.' },
124
+ ];
125
+
126
+ // ---------------------------------------------------------------------------
127
+ // Detección
128
+ // ---------------------------------------------------------------------------
129
+
130
+ function listarSeguro(dir) {
131
+ try { return fs.readdirSync(path.join(ROOT, dir)); }
132
+ catch { return []; }
133
+ }
134
+
135
+ function detectarCobertura(lang) {
136
+ const agentesDisco = listarSeguro('agentes');
137
+ const skillsDisco = listarSeguro('habilidades');
138
+ const reglasDisco = listarSeguro('reglas/lenguajes');
139
+
140
+ const agentes = lang.agentesEsperados.filter(a =>
141
+ agentesDisco.includes(a + '.md'));
142
+ const revisor = lang.revisor && agentesDisco.includes(lang.revisor + '.md')
143
+ ? lang.revisor
144
+ : null;
145
+ const skills = skillsDisco.filter(s =>
146
+ lang.skillsKeywords.some(k => s.toLowerCase().includes(k.toLowerCase())));
147
+ const regla = lang.reglaSubdir && reglasDisco.includes(lang.reglaSubdir)
148
+ ? lang.reglaSubdir
149
+ : null;
150
+
151
+ const elementos = agentes.length + (revisor ? 1 : 0) + skills.length + (regla ? 1 : 0);
152
+ let status;
153
+ if (elementos === 0) status = 'faltante';
154
+ else if (elementos < 4) status = 'parcial';
155
+ else status = 'completo';
156
+
157
+ return { agentes, revisor, skills, regla, elementos, status };
158
+ }
159
+
160
+ // ---------------------------------------------------------------------------
161
+ // Render
162
+ // ---------------------------------------------------------------------------
163
+
164
+ function renderTabla() {
165
+ const filas = LENGUAJES.map(lang => {
166
+ const cov = detectarCobertura(lang);
167
+ const icono = cov.status === 'completo' ? '✅' : cov.status === 'parcial' ? '⚠️' : '❌';
168
+ const agenteCelda = cov.agentes.length > 0 ? cov.agentes.join(', ') : '—';
169
+ const revisorCelda = cov.revisor || '—';
170
+ const skillsCelda = cov.skills.length > 0 ? `${cov.skills.length} skill(s)` : '—';
171
+ const reglaCelda = cov.regla ? `reglas/lenguajes/${cov.regla}/` : '—';
172
+ return `| ${icono} ${lang.etiqueta} | ${agenteCelda} | ${revisorCelda} | ${skillsCelda} | ${reglaCelda} | ${cov.status} |`;
173
+ });
174
+
175
+ return [
176
+ '| Lenguaje | Agente(s) | Revisor | Skills | Regla por-lenguaje | Status |',
177
+ '|----------|-----------|---------|--------|--------------------|--------|',
178
+ ...filas,
179
+ ].join('\n');
180
+ }
181
+
182
+ function renderSmoke() {
183
+ return LENGUAJES.map(lang => {
184
+ const cov = detectarCobertura(lang);
185
+ const tag = cov.status === 'faltante'
186
+ ? '_(sin cobertura SWL — el smoke aplica solo si el proyecto del usuario lo usa)_'
187
+ : '';
188
+ return `### ${lang.etiqueta}\n\n- Smoke mínimo: ${lang.smokeMin}\n${tag ? '- ' + tag + '\n' : ''}`;
189
+ }).join('\n');
190
+ }
191
+
192
+ function renderResumen() {
193
+ const total = LENGUAJES.length;
194
+ const completos = LENGUAJES.filter(l => detectarCobertura(l).status === 'completo').length;
195
+ const parciales = LENGUAJES.filter(l => detectarCobertura(l).status === 'parcial').length;
196
+ const faltantes = LENGUAJES.filter(l => detectarCobertura(l).status === 'faltante').length;
197
+ return [
198
+ `**Total lenguajes evaluados**: ${total}`,
199
+ `**Cobertura completa** (≥4 elementos: agente + revisor + skills + regla): ${completos}`,
200
+ `**Cobertura parcial** (1-3 elementos): ${parciales}`,
201
+ `**Sin cobertura SWL**: ${faltantes}`,
202
+ ].join('\n');
203
+ }
204
+
205
+ // ---------------------------------------------------------------------------
206
+ // Main
207
+ // ---------------------------------------------------------------------------
208
+
209
+ function main() {
210
+ const fecha = new Date().toISOString().slice(0, 10);
211
+ const contenido = `# Matriz de cobertura SWL × lenguaje
212
+
213
+ > **Generado automáticamente** por \`scripts/generar-matriz-lenguajes.js\`.
214
+ > Última generación: ${fecha}.
215
+ > NO editar a mano — re-ejecutar el script.
216
+
217
+ Esta matriz documenta qué lenguajes del stack polyglot SWL tienen cobertura
218
+ completa de **agentes + skills + reglas + revisores**, y qué smoke test mínimo
219
+ debería ejecutarse en CI antes de release de un proyecto que use cada lenguaje.
220
+
221
+ Aplica a:
222
+
223
+ - **Pre-release del repo madre swl-ses**: validar que ningún lenguaje
224
+ declarado oficialmente perdió componentes desde el último release.
225
+ - **Proyectos usuario**: usar la columna "Smoke mínimo" como guía de qué
226
+ ejecutar como mínimo antes de \`/swl:release\` en su proyecto.
227
+
228
+ ## Resumen
229
+
230
+ ${renderResumen()}
231
+
232
+ ## Cobertura por lenguaje
233
+
234
+ ${renderTabla()}
235
+
236
+ **Leyenda**:
237
+ - ✅ **completo**: ≥4 elementos (agente backend/frontend/mobile + revisor + skills + regla por-lenguaje).
238
+ - ⚠️ **parcial**: 1-3 elementos. Aceptable si el lenguaje es de uso secundario.
239
+ - ❌ **faltante**: ningún elemento detectado. Si el proyecto declara este lenguaje, la cobertura SWL es inadecuada.
240
+
241
+ ## Smoke test mínimo recomendado por lenguaje
242
+
243
+ ${renderSmoke()}
244
+
245
+ ## Cómo se usa esta matriz
246
+
247
+ 1. **Pre-release de swl-ses**: \`/swl:release\` invoca este script. Si algún
248
+ lenguaje pasó de **completo** a **parcial** o de **parcial** a **faltante**
249
+ sin ADR documentado, el release se bloquea.
250
+ 2. **CI de proyecto usuario**: el comando \`/swl:configurar-ci\` genera el
251
+ workflow incluyendo el smoke mínimo del lenguaje detectado.
252
+ 3. **Auditoría**: ejecutar \`node scripts/generar-matriz-lenguajes.js\` cuando
253
+ se agrega/elimina un agente, skill o regla por-lenguaje. La salida actualizada
254
+ debe commitearse junto al cambio.
255
+
256
+ ## Política de cierre por categoría
257
+
258
+ - **Lenguaje completo (✅)**: cualquier eliminación de componente requiere ADR
259
+ en \`.planning/adrs/\` justificando la regresión.
260
+ - **Lenguaje parcial (⚠️)**: documentar en este archivo el plan para llegar a
261
+ cobertura completa, o decisión explícita de mantener parcial (con razón).
262
+ - **Lenguaje faltante (❌)**: el repo no debe afirmar soporte oficial. Mover
263
+ cualquier mención a "stack polyglot soportado" hasta que pase a parcial.
264
+ `;
265
+
266
+ atomicWriteSync(SALIDA, contenido, 'utf8');
267
+ console.log(`Matriz generada: ${path.relative(ROOT, SALIDA)}`);
268
+ console.log(renderResumen());
269
+ }
270
+
271
+ main();
@@ -0,0 +1,190 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * generar-skills-lock.js
4
+ *
5
+ * Genera `manifiestos/skills-lock.json` con SHA256 de cada `habilidades/*\/SKILL.md`.
6
+ * Permite detectar drift silencioso: alguien edita un skill localmente sin
7
+ * commit y nadie lo nota hasta que falla. El lock se regenera en cada
8
+ * `/swl:release` y se valida en `/swl:salud`.
9
+ *
10
+ * Uso:
11
+ * node scripts/generar-skills-lock.js # genera y escribe
12
+ * node scripts/generar-skills-lock.js --check # compara, falla si hay drift
13
+ * node scripts/generar-skills-lock.js --json # imprime resumen JSON
14
+ *
15
+ * Origen: análisis de temp/design.md-main/skills-lock.json (mayo 2026).
16
+ *
17
+ * Zero-dependencies. Compatible Windows (CRLF-safe), Node 18+.
18
+ */
19
+
20
+ 'use strict';
21
+
22
+ const fs = require('fs');
23
+ const path = require('path');
24
+ const crypto = require('crypto');
25
+
26
+ const ROOT = path.resolve(__dirname, '..');
27
+
28
+ // Escritura atómica obligatoria (regla CLAUDE.md). Fallback defensivo.
29
+ let atomicWriteSync;
30
+ try {
31
+ ({ atomicWriteSync } = require(path.join(ROOT, 'hooks', 'lib', 'atomic-write.js')));
32
+ } catch {
33
+ atomicWriteSync = (p, c, e) => fs.writeFileSync(p, c, e);
34
+ }
35
+ const HABILIDADES_DIR = path.join(ROOT, 'habilidades');
36
+ const LOCK_FILE = path.join(ROOT, 'manifiestos', 'skills-lock.json');
37
+ const LOCK_VERSION = 1;
38
+
39
+ const CHECK = process.argv.includes('--check');
40
+ const JSON_OUT = process.argv.includes('--json');
41
+
42
+ function sha256(buffer) {
43
+ return crypto.createHash('sha256').update(buffer).digest('hex');
44
+ }
45
+
46
+ function leerFrontmatter(contenido) {
47
+ const m = contenido.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/);
48
+ if (!m) return {};
49
+ const fm = {};
50
+ for (const linea of m[1].split(/\r?\n/)) {
51
+ const kv = linea.match(/^([a-zA-Z_][a-zA-Z0-9_-]*):\s*(.*)$/);
52
+ if (kv) fm[kv[1]] = kv[2].trim();
53
+ }
54
+ return fm;
55
+ }
56
+
57
+ function generarLock() {
58
+ if (!fs.existsSync(HABILIDADES_DIR)) {
59
+ console.error(`ERROR: directorio no encontrado: ${HABILIDADES_DIR}`);
60
+ process.exit(2);
61
+ }
62
+
63
+ const skills = [];
64
+ const dirs = fs
65
+ .readdirSync(HABILIDADES_DIR, { withFileTypes: true })
66
+ .filter((d) => d.isDirectory())
67
+ .map((d) => d.name)
68
+ .sort();
69
+
70
+ for (const dir of dirs) {
71
+ const skillFile = path.join(HABILIDADES_DIR, dir, 'SKILL.md');
72
+ if (!fs.existsSync(skillFile)) {
73
+ // Skill sin SKILL.md — anomalía pero no fatal
74
+ skills.push({
75
+ nombre: dir,
76
+ path: `habilidades/${dir}/SKILL.md`,
77
+ hash: null,
78
+ bytes: 0,
79
+ warning: 'skill-md-faltante',
80
+ });
81
+ continue;
82
+ }
83
+
84
+ const buffer = fs.readFileSync(skillFile);
85
+ const contenido = buffer.toString('utf-8');
86
+ const fm = leerFrontmatter(contenido);
87
+
88
+ skills.push({
89
+ nombre: fm.name || dir,
90
+ path: `habilidades/${dir}/SKILL.md`,
91
+ hash: `sha256:${sha256(buffer)}`,
92
+ bytes: buffer.length,
93
+ version: fm.version || null,
94
+ });
95
+ }
96
+
97
+ // Hash agregado del lock completo (excluyendo timestamps)
98
+ const datosCanonicos = JSON.stringify(
99
+ skills.map((s) => ({ nombre: s.nombre, hash: s.hash })),
100
+ null,
101
+ 0
102
+ );
103
+ const lockHash = `sha256:${sha256(Buffer.from(datosCanonicos, 'utf-8'))}`;
104
+
105
+ return {
106
+ lockfileVersion: LOCK_VERSION,
107
+ generatedAt: new Date().toISOString(),
108
+ skillsCount: skills.length,
109
+ lockHash,
110
+ skills,
111
+ };
112
+ }
113
+
114
+ function comparar(actual, anterior) {
115
+ if (!anterior) return { drifted: [], faltantes: actual.skills, nuevos: [] };
116
+
117
+ const anteriorMap = new Map(anterior.skills.map((s) => [s.nombre, s]));
118
+ const actualMap = new Map(actual.skills.map((s) => [s.nombre, s]));
119
+
120
+ const drifted = [];
121
+ const nuevos = [];
122
+ const faltantes = [];
123
+
124
+ for (const s of actual.skills) {
125
+ const prev = anteriorMap.get(s.nombre);
126
+ if (!prev) {
127
+ nuevos.push(s.nombre);
128
+ } else if (prev.hash !== s.hash) {
129
+ drifted.push({ nombre: s.nombre, antes: prev.hash, ahora: s.hash });
130
+ }
131
+ }
132
+ for (const s of anterior.skills) {
133
+ if (!actualMap.has(s.nombre)) {
134
+ faltantes.push(s.nombre);
135
+ }
136
+ }
137
+
138
+ return { drifted, faltantes, nuevos };
139
+ }
140
+
141
+ function main() {
142
+ const actual = generarLock();
143
+
144
+ if (CHECK) {
145
+ if (!fs.existsSync(LOCK_FILE)) {
146
+ console.error(`ERROR: ${LOCK_FILE} no existe. Ejecutar sin --check para generarlo.`);
147
+ process.exit(1);
148
+ }
149
+ const anterior = JSON.parse(fs.readFileSync(LOCK_FILE, 'utf-8'));
150
+ const diff = comparar(actual, anterior);
151
+ const total = diff.drifted.length + diff.faltantes.length + diff.nuevos.length;
152
+
153
+ if (JSON_OUT) {
154
+ console.log(JSON.stringify({ ok: total === 0, ...diff }, null, 2));
155
+ } else if (total === 0) {
156
+ console.log(`✓ skills-lock OK: ${actual.skillsCount} skills sin drift`);
157
+ } else {
158
+ console.log(`✗ skills-lock DRIFT detectado:`);
159
+ if (diff.drifted.length) {
160
+ console.log(` Modificados (${diff.drifted.length}):`);
161
+ diff.drifted.forEach((d) => console.log(` - ${d.nombre}`));
162
+ }
163
+ if (diff.nuevos.length) {
164
+ console.log(` Nuevos (${diff.nuevos.length}):`);
165
+ diff.nuevos.forEach((n) => console.log(` - ${n}`));
166
+ }
167
+ if (diff.faltantes.length) {
168
+ console.log(` Faltantes (${diff.faltantes.length}):`);
169
+ diff.faltantes.forEach((n) => console.log(` - ${n}`));
170
+ }
171
+ console.log(`\n Para regenerar: node scripts/generar-skills-lock.js`);
172
+ }
173
+ process.exit(total === 0 ? 0 : 1);
174
+ }
175
+
176
+ // Generar
177
+ atomicWriteSync(LOCK_FILE, JSON.stringify(actual, null, 2) + '\n', 'utf-8');
178
+ if (JSON_OUT) {
179
+ console.log(JSON.stringify({ ok: true, file: LOCK_FILE, count: actual.skillsCount }));
180
+ } else {
181
+ console.log(`✓ Generado ${LOCK_FILE}`);
182
+ console.log(` ${actual.skillsCount} skills, lockHash=${actual.lockHash.slice(0, 23)}...`);
183
+ }
184
+ }
185
+
186
+ if (require.main === module) {
187
+ main();
188
+ }
189
+
190
+ module.exports = { generarLock, comparar };
@@ -8,6 +8,16 @@
8
8
  const fs = require('fs');
9
9
  const path = require('path');
10
10
 
11
+ // Escritura atómica obligatoria — el archivo de estado de instalación
12
+ // (.swl-install-state.json) es lo que doctor/repair/uninstall consultan.
13
+ // Corromperlo durante una migración v2→v3 deja la instalación en limbo.
14
+ let atomicWriteJSON;
15
+ try {
16
+ ({ atomicWriteJSON } = require(path.join(__dirname, '..', '..', 'hooks', 'lib', 'atomic-write.js')));
17
+ } catch {
18
+ atomicWriteJSON = (p, o) => fs.writeFileSync(p, JSON.stringify(o, null, 2), 'utf-8');
19
+ }
20
+
11
21
  const NOMBRE_ESTADO = '.swl-install-state.json';
12
22
 
13
23
  /**
@@ -61,7 +71,7 @@ function registrarComponente(estado, componente) {
61
71
  */
62
72
  function guardarEstado(estado, directorio) {
63
73
  const rutaEstado = path.join(directorio, NOMBRE_ESTADO);
64
- fs.writeFileSync(rutaEstado, JSON.stringify(estado, null, 2), 'utf-8');
74
+ atomicWriteJSON(rutaEstado, estado);
65
75
  return rutaEstado;
66
76
  }
67
77
 
@@ -83,7 +93,7 @@ function cargarEstado(directorio) {
83
93
  estado.componentesExternos = [];
84
94
  }
85
95
  // Persistir la migración
86
- fs.writeFileSync(rutaEstado, JSON.stringify(estado, null, 2), 'utf-8');
96
+ atomicWriteJSON(rutaEstado, estado);
87
97
  }
88
98
  return estado;
89
99
  } catch {