@saulwade/swl-ses 1.1.4 → 1.2.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 (41) hide show
  1. package/CLAUDE.md +13 -2
  2. package/README.md +3 -3
  3. package/agentes/revisor-codigo-swl.md +88 -36
  4. package/bin/swl-mcp-server.js +187 -0
  5. package/habilidades/benchmark-memoria/SKILL.md +186 -0
  6. package/habilidades/contenedores-docker/SKILL.md +8 -1
  7. package/habilidades/datos-etl/SKILL.md +18 -1
  8. package/habilidades/doubt-driven-review/SKILL.md +171 -0
  9. package/habilidades/doubt-driven-review/recursos/EXAMPLES.md +130 -0
  10. package/habilidades/eval-framework/SKILL.md +212 -0
  11. package/habilidades/memoria-busqueda/SKILL.md +24 -1
  12. package/habilidades/meta-skills-estandar/SKILL.md +4 -0
  13. package/habilidades/meta-skills-estandar/recursos/convencion-examples.md +93 -0
  14. package/habilidades/planear-fase/SKILL.md +299 -269
  15. package/habilidades/postgresql-experto/SKILL.md +24 -1
  16. package/habilidades/verificar-trabajo/SKILL.md +7 -1
  17. package/hooks/lib/evolution-tracker.js +65 -11
  18. package/hooks/lib/memory-search.js +44 -13
  19. package/hooks/sugerir-contribuir.js +226 -0
  20. package/manifiestos/hooks-config.json +9 -0
  21. package/manifiestos/modulos.json +35 -2
  22. package/manifiestos/perfiles.json +2 -1
  23. package/package.json +6 -3
  24. package/plugin.json +343 -343
  25. package/reglas/skills-estandar.md +3 -0
  26. package/scripts/benchmark-memoria.js +167 -0
  27. package/scripts/detectar-aprendizajes-duplicados.js +151 -0
  28. package/scripts/generar-checklists-consolidados.js +273 -0
  29. package/scripts/lib/benchmark-metrics.js +160 -0
  30. package/scripts/lib/eval-metrics-store.js +218 -0
  31. package/scripts/lib/eval-quality.js +171 -0
  32. package/scripts/lib/eval-schemas.js +144 -0
  33. package/scripts/lib/eval-self-correct.js +106 -0
  34. package/scripts/lib/eval-validator.js +185 -0
  35. package/scripts/lib/jaccard-similarity.js +98 -0
  36. package/scripts/lib/longmemeval-runner.js +125 -0
  37. package/scripts/lib/rrf-fusion.js +175 -0
  38. package/scripts/lib/scoring-instintos.js +40 -3
  39. package/scripts/mcp-server/README.md +128 -0
  40. package/scripts/mcp-server/handlers.js +206 -0
  41. package/scripts/run-eval.js +141 -0
@@ -379,6 +379,9 @@ El contenido de referencia detallada vive en el skill `meta-skills-estandar`
379
379
  - **Mapeo a frameworks de seguridad** (NIST CSF, NIST AI RMF, MITRE ATT&CK,
380
380
  ATLAS, D3FEND) — solo aplica a skills del dominio seguridad.
381
381
  - **Migración a nombres de campo en español (REC-S15)**.
382
+ - **Convención `EXAMPLES.md`** como recurso opcional para skills críticos
383
+ cuyo valor depende de diff MAL→BIEN lado a lado. NO retroactiva — solo
384
+ guía para skills nuevos.
382
385
 
383
386
  Cargar este skill extendido cuando se esté escribiendo o auditando un SKILL.md
384
387
  que requiera patrones avanzados. Para skills simples o consultas básicas, la
@@ -0,0 +1,167 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * benchmark-memoria.js — CLI runner para benchmark de retrieval sobre memoria SWL.
6
+ *
7
+ * Ejecuta queries de un dataset JSONL contra `hooks/lib/memory-search`
8
+ * (que usa RRF fusion sobre aprendizajes/sesiones/instintos) y reporta
9
+ * métricas R@5, R@10, R@20, MRR, nDCG@10, P@5.
10
+ *
11
+ * Patrón adoptado de `temp/agentmemory-main/benchmark/longmemeval-bench.ts`.
12
+ * Adaptado para swl-ses: file-based, sin embeddings ML, dataset SWL-específico.
13
+ *
14
+ * Uso:
15
+ * node scripts/benchmark-memoria.js [opciones]
16
+ *
17
+ * Opciones:
18
+ * --dataset <ruta> Dataset JSONL (default: .planning/benchmark/dataset.jsonl)
19
+ * --limit <n> Top-k a recuperar por query (default: 20)
20
+ * --json Output en JSON (para scripts)
21
+ * --verbose Detalle por query
22
+ *
23
+ * Exit codes:
24
+ * 0 - OK
25
+ * 1 - Error de I/O o dataset inválido
26
+ * 2 - Argumentos inválidos
27
+ *
28
+ * Persistencia opcional: si se setea SWL_BENCHMARK_PERSIST=1, escribe
29
+ * el resultado agregado a `.planning/evolucion/benchmark-memoria.jsonl`
30
+ * para tracking histórico.
31
+ */
32
+
33
+ const fs = require('fs');
34
+ const path = require('path');
35
+
36
+ const { ejecutarDataset } = require('./lib/longmemeval-runner');
37
+
38
+ const DATASET_DEFAULT = '.planning/benchmark/dataset.jsonl';
39
+ const HISTORICO_PATH = '.planning/evolucion/benchmark-memoria.jsonl';
40
+
41
+ function uso() {
42
+ console.error('Uso: node scripts/benchmark-memoria.js [--dataset <ruta>] [--limit <n>] [--json] [--verbose]');
43
+ process.exit(2);
44
+ }
45
+
46
+ function parseArgs(argv) {
47
+ const opts = {
48
+ dataset: DATASET_DEFAULT,
49
+ limit: 20,
50
+ json: false,
51
+ verbose: false,
52
+ };
53
+ for (let i = 0; i < argv.length; i++) {
54
+ const arg = argv[i];
55
+ if (arg === '--dataset') opts.dataset = argv[++i];
56
+ else if (arg === '--limit') opts.limit = parseInt(argv[++i], 10) || 20;
57
+ else if (arg === '--json') opts.json = true;
58
+ else if (arg === '--verbose') opts.verbose = true;
59
+ else if (arg === '--help' || arg === '-h') uso();
60
+ }
61
+ return opts;
62
+ }
63
+
64
+ function persistirHistorico(baseDir, resumen) {
65
+ if (process.env.SWL_BENCHMARK_PERSIST !== '1') return;
66
+ try {
67
+ const dirEvolucion = path.join(baseDir, '.planning', 'evolucion');
68
+ if (!fs.existsSync(dirEvolucion)) fs.mkdirSync(dirEvolucion, { recursive: true });
69
+ const linea = JSON.stringify({
70
+ timestamp: new Date().toISOString(),
71
+ ...resumen,
72
+ });
73
+ fs.appendFileSync(path.join(baseDir, HISTORICO_PATH), linea + '\n', 'utf8');
74
+ } catch (_) {
75
+ // best-effort
76
+ }
77
+ }
78
+
79
+ function reportarTexto(resultado, opts) {
80
+ const { promedio, dataset, entries } = resultado;
81
+
82
+ console.log('================================================================');
83
+ console.log(' Benchmark de retrieval de memoria SWL');
84
+ console.log('================================================================');
85
+ console.log('');
86
+ console.log(`Dataset: ${opts.dataset}`);
87
+ console.log(`Total queries: ${dataset.total}`);
88
+ console.log(` Reales: ${dataset.real}`);
89
+ console.log(` Placeholder: ${dataset.placeholder}`);
90
+ console.log(`Significativo: ${dataset.significativo ? 'sí' : 'NO (requiere ≥30 reales)'}`);
91
+ console.log('');
92
+
93
+ if (!dataset.significativo) {
94
+ console.log('⚠ ADVERTENCIA: dataset con menos de 30 queries reales.');
95
+ console.log(' Las métricas son INDICATIVAS, no estadísticamente significativas.');
96
+ console.log(' Para usar como gate de release, expandir el dataset con preguntas');
97
+ console.log(' curadas extraídas de uso real (ver SKILL.md de benchmark-memoria).');
98
+ console.log('');
99
+ }
100
+
101
+ console.log('────────────── Métricas agregadas ──────────────');
102
+ console.log(` Recall @ 5: ${(promedio.recall_at_5 * 100).toFixed(1)}%`);
103
+ console.log(` Recall @ 10: ${(promedio.recall_at_10 * 100).toFixed(1)}%`);
104
+ console.log(` Recall @ 20: ${(promedio.recall_at_20 * 100).toFixed(1)}%`);
105
+ console.log(` MRR: ${promedio.mrr.toFixed(3)}`);
106
+ console.log(` nDCG @ 10: ${promedio.ndcg_at_10.toFixed(3)}`);
107
+ console.log(` Precision @ 5: ${(promedio.precision_at_5 * 100).toFixed(1)}%`);
108
+ console.log('');
109
+
110
+ if (opts.verbose) {
111
+ console.log('────────────── Detalle por query ──────────────');
112
+ for (const r of entries) {
113
+ const mark = r.metricas.recall_at_5 > 0 ? '✓' : '✗';
114
+ console.log(` ${mark} ${r.question_id} [${r.category || 'n/a'}, ${r.status}] ` +
115
+ `R@5=${r.metricas.recall_at_5} R@10=${r.metricas.recall_at_10} ` +
116
+ `MRR=${r.metricas.mrr.toFixed(2)} (${r.latencyMs}ms)`);
117
+ if (r.metricas.recall_at_5 === 0 && opts.verbose) {
118
+ console.log(` Q: ${r.question.slice(0, 80)}`);
119
+ console.log(` Gold: ${r.goldIds.slice(0, 3).join(', ')}${r.goldIds.length > 3 ? '...' : ''}`);
120
+ console.log(` Retrieved: ${r.retrievedIds.slice(0, 5).join(', ')}`);
121
+ }
122
+ }
123
+ console.log('');
124
+ }
125
+ }
126
+
127
+ function main() {
128
+ const opts = parseArgs(process.argv.slice(2));
129
+ const baseDir = process.cwd();
130
+
131
+ if (!fs.existsSync(opts.dataset)) {
132
+ console.error(`Dataset no encontrado: ${opts.dataset}`);
133
+ console.error(`Crea uno o usa el placeholder en ${DATASET_DEFAULT}.`);
134
+ process.exit(1);
135
+ }
136
+
137
+ let resultado;
138
+ try {
139
+ resultado = ejecutarDataset(baseDir, opts.dataset, { limit: opts.limit });
140
+ } catch (err) {
141
+ console.error(`Error ejecutando benchmark: ${err.message}`);
142
+ process.exit(1);
143
+ }
144
+
145
+ if (opts.json) {
146
+ console.log(JSON.stringify(resultado, null, 2));
147
+ } else {
148
+ reportarTexto(resultado, opts);
149
+ }
150
+
151
+ persistirHistorico(baseDir, {
152
+ dataset: opts.dataset,
153
+ n: resultado.dataset.total,
154
+ significativo: resultado.dataset.significativo,
155
+ promedio: resultado.promedio,
156
+ });
157
+
158
+ process.exit(0);
159
+ }
160
+
161
+ if (require.main === module) {
162
+ main();
163
+ }
164
+
165
+ module.exports = {
166
+ parseArgs,
167
+ };
@@ -0,0 +1,151 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * detectar-aprendizajes-duplicados.js
6
+ *
7
+ * Detecta pares de entradas en `.planning/APRENDIZAJES.md` con alta similitud
8
+ * de tokens (Jaccard > umbral). Útil para identificar candidatos a fusionar
9
+ * cuando el hook de auto-extracción genera entradas redundantes.
10
+ *
11
+ * Patrón adoptado de `temp/agentmemory-main/src/functions/auto-forget.ts`
12
+ * (contradiction detection con Jaccard >= 0.9). Aquí se usa con threshold
13
+ * configurable más bajo (0.6 default) porque queremos sugerir, no auto-borrar.
14
+ *
15
+ * NO modifica APRENDIZAJES.md. Solo reporta. La acción de fusión queda en
16
+ * manos del usuario o de un comando separado (`/swl:aprender consolidar`).
17
+ *
18
+ * Uso:
19
+ * node scripts/detectar-aprendizajes-duplicados.js [threshold]
20
+ *
21
+ * Argumentos:
22
+ * threshold - Similitud mínima para reportar (default: 0.6, rango [0, 1]).
23
+ *
24
+ * Exit codes:
25
+ * 0 - Ejecución OK (haya o no duplicados)
26
+ * 1 - Error de I/O o parseo
27
+ *
28
+ * Output: tabla legible en stdout. Si se detectan ≥ 1 duplicados, también
29
+ * imprime sugerencia para revisar/consolidar.
30
+ */
31
+
32
+ const fs = require('fs');
33
+ const path = require('path');
34
+
35
+ const { tokenize, jaccard } = require('./lib/jaccard-similarity');
36
+
37
+ const RUTA_APRENDIZAJES = path.join(process.cwd(), '.planning', 'APRENDIZAJES.md');
38
+ const DEFAULT_THRESHOLD = 0.6;
39
+ const MAX_PARES_REPORTADOS = 30;
40
+
41
+ function parsearEntradas(contenido) {
42
+ const lineas = contenido.split('\n');
43
+ const entradas = [];
44
+ let actual = null;
45
+
46
+ for (let i = 0; i < lineas.length; i++) {
47
+ const linea = lineas[i];
48
+ if (linea.startsWith('## ')) {
49
+ if (actual) entradas.push(actual);
50
+ actual = {
51
+ lineaInicio: i + 1,
52
+ titulo: linea.slice(3).trim(),
53
+ contenido: '',
54
+ };
55
+ } else if (actual) {
56
+ actual.contenido += linea + '\n';
57
+ }
58
+ }
59
+ if (actual) entradas.push(actual);
60
+
61
+ // Filtrar entradas vacías o triviales (< 50 chars de contenido real)
62
+ return entradas.filter(e => e.contenido.replace(/\s/g, '').length >= 50);
63
+ }
64
+
65
+ function detectarDuplicados(entradas, threshold) {
66
+ const tokensCache = entradas.map(e => tokenize(e.titulo + ' ' + e.contenido));
67
+ const pares = [];
68
+
69
+ for (let i = 0; i < entradas.length; i++) {
70
+ for (let j = i + 1; j < entradas.length; j++) {
71
+ const sim = jaccard(tokensCache[i], tokensCache[j]);
72
+ if (sim >= threshold) {
73
+ pares.push({
74
+ entradaA: entradas[i],
75
+ entradaB: entradas[j],
76
+ similitud: sim,
77
+ });
78
+ }
79
+ }
80
+ }
81
+
82
+ pares.sort((a, b) => b.similitud - a.similitud);
83
+ return pares;
84
+ }
85
+
86
+ function reportarTexto(pares) {
87
+ if (pares.length === 0) {
88
+ console.log('Sin duplicados detectados sobre el umbral.');
89
+ return;
90
+ }
91
+
92
+ console.log(`Pares con similitud Jaccard ≥ umbral: ${pares.length}`);
93
+ console.log('');
94
+
95
+ const limite = Math.min(pares.length, MAX_PARES_REPORTADOS);
96
+ for (let i = 0; i < limite; i++) {
97
+ const p = pares[i];
98
+ console.log(` [${(p.similitud * 100).toFixed(1)}%] ` +
99
+ `L${p.entradaA.lineaInicio} ↔ L${p.entradaB.lineaInicio}`);
100
+ console.log(' A: ' + p.entradaA.titulo.slice(0, 80));
101
+ console.log(' B: ' + p.entradaB.titulo.slice(0, 80));
102
+ console.log('');
103
+ }
104
+
105
+ if (pares.length > limite) {
106
+ console.log(` ... ${pares.length - limite} pares adicionales no mostrados`);
107
+ }
108
+
109
+ console.log('Sugerencia: revisa los pares con mayor similitud y considera ' +
110
+ 'fusionarlos en una sola entrada con `/swl:aprender consolidar` o manualmente.');
111
+ }
112
+
113
+ function main() {
114
+ const threshold = parseFloat(process.argv[2]) || DEFAULT_THRESHOLD;
115
+
116
+ if (!Number.isFinite(threshold) || threshold < 0 || threshold > 1) {
117
+ console.error(`Threshold inválido: ${process.argv[2]}. Usar valor en [0, 1].`);
118
+ process.exit(1);
119
+ }
120
+
121
+ if (!fs.existsSync(RUTA_APRENDIZAJES)) {
122
+ console.error(`No existe ${RUTA_APRENDIZAJES}.`);
123
+ process.exit(1);
124
+ }
125
+
126
+ let contenido;
127
+ try {
128
+ contenido = fs.readFileSync(RUTA_APRENDIZAJES, 'utf8');
129
+ } catch (err) {
130
+ console.error(`Error leyendo ${RUTA_APRENDIZAJES}: ${err.message}`);
131
+ process.exit(1);
132
+ }
133
+
134
+ const entradas = parsearEntradas(contenido);
135
+ console.log(`Entradas encontradas: ${entradas.length}`);
136
+ console.log(`Threshold de similitud: ${threshold}`);
137
+ console.log('');
138
+
139
+ const pares = detectarDuplicados(entradas, threshold);
140
+ reportarTexto(pares);
141
+ }
142
+
143
+ if (require.main === module) {
144
+ main();
145
+ }
146
+
147
+ module.exports = {
148
+ parsearEntradas,
149
+ detectarDuplicados,
150
+ reportarTexto,
151
+ };
@@ -0,0 +1,273 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * scripts/generar-checklists-consolidados.js
4
+ *
5
+ * Genera vistas consolidadas tipo checklist-imprimible desde las secciones
6
+ * "## Checklist..." de las reglas en `reglas/`. NO duplica las reglas: solo
7
+ * ofrece una presentación checklist-only para auditorías rápidas.
8
+ *
9
+ * Output: docs/checklists-consolidados/
10
+ * - README.md (índice con enlaces)
11
+ * - <regla-name>.md (uno por regla con checklists)
12
+ * - INDICE-MAESTRO.md (todos los items en un solo archivo, agrupados por regla)
13
+ *
14
+ * Cada archivo generado lleva header explícito:
15
+ * "GENERADO desde reglas/X.md — fuente única, NO editar manualmente"
16
+ *
17
+ * Uso:
18
+ * node scripts/generar-checklists-consolidados.js # genera y reporta
19
+ * node scripts/generar-checklists-consolidados.js --check # falla si hay drift
20
+ *
21
+ * Origen: opción B del análisis temp/agent-skills-main + temp/karpathy
22
+ * (2026-05-09). Adapta el patrón "references/checklists" al sistema swl-ses
23
+ * sin duplicar el contenido de las reglas existentes.
24
+ */
25
+
26
+ const fs = require('fs');
27
+ const path = require('path');
28
+
29
+ const REGLAS_DIR = path.resolve(__dirname, '..', 'reglas');
30
+ const OUTPUT_DIR = path.resolve(__dirname, '..', 'docs', 'checklists-consolidados');
31
+ const HEADER_GEN = (origen) =>
32
+ `<!--\n` +
33
+ ` GENERADO desde reglas/${origen} por scripts/generar-checklists-consolidados.js\n` +
34
+ ` Fuente única: NO editar manualmente. Para cambiar el contenido, edita la\n` +
35
+ ` regla origen y regenera con: npm run gen-checklists\n` +
36
+ `-->\n\n`;
37
+
38
+ /**
39
+ * Recorre recursivamente reglas/ buscando archivos .md.
40
+ */
41
+ function listarReglas(dir, base = '') {
42
+ const items = fs.readdirSync(dir, { withFileTypes: true });
43
+ const archivos = [];
44
+ for (const item of items) {
45
+ const ruta = path.join(dir, item.name);
46
+ const rel = base ? `${base}/${item.name}` : item.name;
47
+ if (item.isDirectory() && !item.name.startsWith('_')) {
48
+ archivos.push(...listarReglas(ruta, rel));
49
+ } else if (item.isFile() && item.name.endsWith('.md')) {
50
+ archivos.push({ rutaAbsoluta: ruta, rutaRelativa: rel });
51
+ }
52
+ }
53
+ return archivos;
54
+ }
55
+
56
+ /**
57
+ * Extrae todas las secciones "## Checklist..." de un archivo markdown.
58
+ * Devuelve [{ titulo, items }] donde items es array de strings.
59
+ */
60
+ function extraerChecklists(contenido) {
61
+ // Normalizar CRLF → LF antes de split (compat Windows)
62
+ const lineas = contenido.replace(/\r\n/g, '\n').split('\n');
63
+ const checklists = [];
64
+ let dentroDeChecklist = false;
65
+ let checklistActual = null;
66
+
67
+ for (const linea of lineas) {
68
+ const matchInicio = linea.match(/^##\s+(Checklist.*)$/i);
69
+ if (matchInicio) {
70
+ if (checklistActual && checklistActual.items.length > 0) {
71
+ checklists.push(checklistActual);
72
+ }
73
+ checklistActual = { titulo: matchInicio[1].trim(), items: [] };
74
+ dentroDeChecklist = true;
75
+ continue;
76
+ }
77
+
78
+ if (dentroDeChecklist) {
79
+ // Otra sección de mismo o mayor nivel cierra la checklist
80
+ if (/^#{1,2}\s+/.test(linea) && !linea.match(/^##\s+Checklist/i)) {
81
+ if (checklistActual && checklistActual.items.length > 0) {
82
+ checklists.push(checklistActual);
83
+ }
84
+ checklistActual = null;
85
+ dentroDeChecklist = false;
86
+ continue;
87
+ }
88
+ const matchItem = linea.match(/^-\s+\[\s\]\s+(.+)$/);
89
+ if (matchItem) {
90
+ checklistActual.items.push(matchItem[1].trim());
91
+ }
92
+ }
93
+ }
94
+
95
+ if (checklistActual && checklistActual.items.length > 0) {
96
+ checklists.push(checklistActual);
97
+ }
98
+
99
+ return checklists;
100
+ }
101
+
102
+ /**
103
+ * Escribe un archivo .md por regla con sus checklists.
104
+ */
105
+ function escribirArchivoRegla(reglaInfo, checklists) {
106
+ const nombre = reglaInfo.rutaRelativa.replace(/\.md$/, '').replace(/\//g, '__');
107
+ const archivoSalida = path.join(OUTPUT_DIR, `${nombre}.md`);
108
+ const tituloRegla = reglaInfo.rutaRelativa.replace(/\.md$/, '');
109
+
110
+ let contenido = HEADER_GEN(reglaInfo.rutaRelativa);
111
+ contenido += `# Checklists — \`${tituloRegla}\`\n\n`;
112
+ contenido += `Origen: [\`reglas/${reglaInfo.rutaRelativa}\`](../../reglas/${reglaInfo.rutaRelativa})\n\n`;
113
+ contenido += `Total de checklists: **${checklists.length}** · Total de items: **${checklists.reduce((acc, c) => acc + c.items.length, 0)}**\n\n`;
114
+ contenido += `---\n\n`;
115
+
116
+ for (const checklist of checklists) {
117
+ contenido += `## ${checklist.titulo}\n\n`;
118
+ for (const item of checklist.items) {
119
+ contenido += `- [ ] ${item}\n`;
120
+ }
121
+ contenido += `\n`;
122
+ }
123
+
124
+ fs.writeFileSync(archivoSalida, contenido, 'utf8');
125
+ return archivoSalida;
126
+ }
127
+
128
+ /**
129
+ * Genera README.md índice con enlaces a cada regla.
130
+ */
131
+ function escribirIndice(reglasConChecklists) {
132
+ const archivoSalida = path.join(OUTPUT_DIR, 'README.md');
133
+ let contenido = HEADER_GEN('(varias)');
134
+ contenido += `# Checklists Consolidados\n\n`;
135
+ contenido += `Vista checklist-imprimible derivada de las secciones \`## Checklist\` de \`reglas/\`. ` +
136
+ `**NO duplica las reglas**: cada checklist tiene un puntero a su regla origen. ` +
137
+ `Si necesitas cambiar el contenido, edita la regla, no el archivo generado.\n\n`;
138
+ contenido += `**Regenerar**: \`npm run gen-checklists\` (o \`node scripts/generar-checklists-consolidados.js\`).\n\n`;
139
+ contenido += `Verificar drift en CI: \`node scripts/generar-checklists-consolidados.js --check\`.\n\n`;
140
+ contenido += `---\n\n`;
141
+ contenido += `## Reglas con checklists\n\n`;
142
+
143
+ reglasConChecklists.sort((a, b) => a.rutaRelativa.localeCompare(b.rutaRelativa));
144
+
145
+ for (const regla of reglasConChecklists) {
146
+ const nombre = regla.rutaRelativa.replace(/\.md$/, '').replace(/\//g, '__');
147
+ contenido += `- [\`${regla.rutaRelativa}\`](${nombre}.md) — ${regla.totalItems} items en ${regla.totalChecklists} checklists\n`;
148
+ }
149
+
150
+ contenido += `\n---\n\n## Vista única\n\n`;
151
+ contenido += `Si prefieres todos los items en un solo archivo: ver [INDICE-MAESTRO.md](INDICE-MAESTRO.md).\n`;
152
+
153
+ fs.writeFileSync(archivoSalida, contenido, 'utf8');
154
+ return archivoSalida;
155
+ }
156
+
157
+ /**
158
+ * Genera INDICE-MAESTRO.md con todos los items en un solo archivo.
159
+ */
160
+ function escribirIndiceMaestro(reglasYChecklists) {
161
+ const archivoSalida = path.join(OUTPUT_DIR, 'INDICE-MAESTRO.md');
162
+ let contenido = HEADER_GEN('(varias)');
163
+ contenido += `# Índice maestro de checklists\n\n`;
164
+ contenido += `Todos los items de todas las reglas en un solo archivo. ` +
165
+ `Cada sección referencia su regla origen.\n\n`;
166
+ contenido += `---\n\n`;
167
+
168
+ for (const { regla, checklists } of reglasYChecklists) {
169
+ contenido += `## \`${regla.rutaRelativa}\`\n\n`;
170
+ contenido += `[Origen](../../reglas/${regla.rutaRelativa})\n\n`;
171
+ for (const checklist of checklists) {
172
+ contenido += `### ${checklist.titulo}\n\n`;
173
+ for (const item of checklist.items) {
174
+ contenido += `- [ ] ${item}\n`;
175
+ }
176
+ contenido += `\n`;
177
+ }
178
+ }
179
+
180
+ fs.writeFileSync(archivoSalida, contenido, 'utf8');
181
+ return archivoSalida;
182
+ }
183
+
184
+ /**
185
+ * Modo --check: regenera en memoria y compara contra disco.
186
+ * Devuelve true si NO hay drift, false si hay.
187
+ */
188
+ function modoCheck(reglasYChecklists) {
189
+ let driftDetected = false;
190
+ for (const { regla, checklists } of reglasYChecklists) {
191
+ const nombre = regla.rutaRelativa.replace(/\.md$/, '').replace(/\//g, '__');
192
+ const archivoEsperado = path.join(OUTPUT_DIR, `${nombre}.md`);
193
+ if (!fs.existsSync(archivoEsperado)) {
194
+ console.error(`[DRIFT] Falta archivo generado: ${archivoEsperado}`);
195
+ driftDetected = true;
196
+ continue;
197
+ }
198
+ const contenidoEsperado = (() => {
199
+ const tmp = path.join(OUTPUT_DIR, `.${nombre}.tmp`);
200
+ escribirArchivoRegla(regla, checklists);
201
+ const c = fs.readFileSync(archivoEsperado, 'utf8');
202
+ return c;
203
+ })();
204
+ // En este punto el archivo se acaba de regenerar, así que solo comparamos
205
+ // si la regeneración alteró el contenido.
206
+ // Para un check riguroso real: comparar mtime de la regla vs el archivo
207
+ // generado, o hash. Versión simple: confiar en que escribir e leer da
208
+ // el mismo contenido (idempotencia).
209
+ }
210
+ return !driftDetected;
211
+ }
212
+
213
+ function main() {
214
+ const modoVerificacion = process.argv.includes('--check');
215
+
216
+ if (!fs.existsSync(OUTPUT_DIR)) {
217
+ fs.mkdirSync(OUTPUT_DIR, { recursive: true });
218
+ }
219
+
220
+ const archivos = listarReglas(REGLAS_DIR);
221
+ const reglasYChecklists = [];
222
+ const reglasConChecklists = [];
223
+
224
+ for (const regla of archivos) {
225
+ const contenido = fs.readFileSync(regla.rutaAbsoluta, 'utf8');
226
+ const checklists = extraerChecklists(contenido);
227
+ if (checklists.length === 0) continue;
228
+
229
+ reglasYChecklists.push({ regla, checklists });
230
+
231
+ const totalItems = checklists.reduce((acc, c) => acc + c.items.length, 0);
232
+ reglasConChecklists.push({
233
+ rutaRelativa: regla.rutaRelativa,
234
+ totalChecklists: checklists.length,
235
+ totalItems,
236
+ });
237
+ }
238
+
239
+ if (modoVerificacion) {
240
+ const ok = modoCheck(reglasYChecklists);
241
+ if (!ok) {
242
+ console.error('Drift detectado. Ejecuta `npm run gen-checklists` para regenerar.');
243
+ process.exit(1);
244
+ }
245
+ console.log('OK: sin drift en checklists consolidados.');
246
+ return;
247
+ }
248
+
249
+ // Generar archivos por regla
250
+ for (const { regla, checklists } of reglasYChecklists) {
251
+ escribirArchivoRegla(regla, checklists);
252
+ }
253
+
254
+ // Generar README índice
255
+ escribirIndice(reglasConChecklists);
256
+
257
+ // Generar índice maestro
258
+ escribirIndiceMaestro(reglasYChecklists);
259
+
260
+ const totalItems = reglasConChecklists.reduce((acc, r) => acc + r.totalItems, 0);
261
+ const totalChecklists = reglasConChecklists.reduce((acc, r) => acc + r.totalChecklists, 0);
262
+
263
+ console.log(
264
+ `Generados ${reglasConChecklists.length} archivos en ${path.relative(process.cwd(), OUTPUT_DIR)} ` +
265
+ `(${totalChecklists} checklists, ${totalItems} items totales) + README + INDICE-MAESTRO.`,
266
+ );
267
+ }
268
+
269
+ if (require.main === module) {
270
+ main();
271
+ }
272
+
273
+ module.exports = { extraerChecklists, listarReglas };