@saulwade/swl-ses 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,297 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * scripts/auditar-claudemd.js
6
+ *
7
+ * Auditor del archivo CLAUDE.md según best practices Anthropic (ADR-0016).
8
+ *
9
+ * Verifica:
10
+ * - Existencia del archivo (en ./ o en .claude/)
11
+ * - Líneas totales (umbral SWL_CLAUDEMD_MAX_LINES, default 200)
12
+ * - Bullets/párrafos monolíticos (umbral SWL_CLAUDEMD_MAX_BULLET_CHARS, default 1000)
13
+ * - Presencia de secciones canónicas (Stack, Comandos, Code style, Conventions, @references)
14
+ * - Uso de @references (al menos 1 si el archivo supera 80 líneas)
15
+ * - Placeholders sin reemplazar ([TBD], [TODO], [COMPLETAR])
16
+ *
17
+ * Uso:
18
+ * node scripts/auditar-claudemd.js [ruta] # Audita CLAUDE.md (default: ./)
19
+ * node scripts/auditar-claudemd.js --json # Salida JSON
20
+ * node scripts/auditar-claudemd.js --strict # exit 1 si veredicto != OK
21
+ *
22
+ * Exit codes:
23
+ * 0 — OK o WARN (veredicto consultivo)
24
+ * 1 — ERROR (no existe / placeholders / faltan secciones críticas) o --strict + WARN
25
+ */
26
+
27
+ const fs = require('fs');
28
+ const path = require('path');
29
+
30
+ // ─── Config ───────────────────────────────────────────────────────────────
31
+ const MAX_LINES = parseInt(process.env.SWL_CLAUDEMD_MAX_LINES, 10) || 200;
32
+ const MAX_BULLET_CHARS =
33
+ parseInt(process.env.SWL_CLAUDEMD_MAX_BULLET_CHARS, 10) || 1000;
34
+
35
+ const SECCIONES_CANONICAS = [
36
+ { nombre: 'Stack', regex: /^##\s+Stack/m },
37
+ { nombre: 'Comandos', regex: /^##\s+Comandos/m },
38
+ { nombre: 'Code style', regex: /^##\s+(Code\s+style|Estilo\s+de\s+código)/im },
39
+ { nombre: 'Conventions', regex: /^##\s+(Conventions|Convenciones)/im },
40
+ ];
41
+
42
+ const PLACEHOLDERS = /\[(TBD|TODO|COMPLETAR|PENDIENTE|XXX|FIXME)\]/g;
43
+
44
+ // ─── Auditoría ────────────────────────────────────────────────────────────
45
+
46
+ function ubicarClaudeMd(dir = process.cwd()) {
47
+ const candidatos = [
48
+ path.join(dir, 'CLAUDE.md'),
49
+ path.join(dir, '.claude', 'CLAUDE.md'),
50
+ ];
51
+ for (const c of candidatos) {
52
+ if (fs.existsSync(c)) return c;
53
+ }
54
+ return null;
55
+ }
56
+
57
+ function auditar(rutaClaudeMd) {
58
+ if (!rutaClaudeMd || !fs.existsSync(rutaClaudeMd)) {
59
+ return {
60
+ veredicto: 'ERROR',
61
+ ruta: rutaClaudeMd,
62
+ hallazgos: [{
63
+ severidad: 'ERROR',
64
+ mensaje: 'CLAUDE.md no existe en el directorio de trabajo',
65
+ sugerencia: 'Ejecuta `/swl:claudemd init-project` para generarlo',
66
+ }],
67
+ };
68
+ }
69
+
70
+ const contenido = fs.readFileSync(rutaClaudeMd, 'utf8');
71
+ const lineas = contenido.split('\n');
72
+ const hallazgos = [];
73
+
74
+ // 1. Líneas totales
75
+ if (lineas.length > MAX_LINES) {
76
+ hallazgos.push({
77
+ severidad: 'WARN',
78
+ regla: 'tamano-total',
79
+ mensaje: `CLAUDE.md tiene ${lineas.length} líneas (umbral: ${MAX_LINES})`,
80
+ sugerencia: 'Extraer secciones grandes a archivos `@`-referenciados (ej. `@docs/variables-entorno.md`)',
81
+ });
82
+ }
83
+
84
+ // 2. Bullets/párrafos monolíticos
85
+ const bulletsMonoliticos = detectarBulletsGigantes(contenido);
86
+ for (const b of bulletsMonoliticos) {
87
+ hallazgos.push({
88
+ severidad: 'WARN',
89
+ regla: 'bullet-gigante',
90
+ mensaje: `Bullet/párrafo en línea ${b.linea} tiene ${b.chars} chars (umbral: ${MAX_BULLET_CHARS})`,
91
+ sugerencia: 'Convertir a tabla, lista jerárquica o extraer a archivo separado',
92
+ preview: b.preview,
93
+ });
94
+ }
95
+
96
+ // 3. Secciones canónicas
97
+ const seccionesAusentes = SECCIONES_CANONICAS.filter(s => !s.regex.test(contenido));
98
+ if (seccionesAusentes.length > 0) {
99
+ const nombres = seccionesAusentes.map(s => s.nombre).join(', ');
100
+ hallazgos.push({
101
+ severidad: 'WARN',
102
+ regla: 'secciones-canonicas',
103
+ mensaje: `Faltan secciones canónicas Anthropic: ${nombres}`,
104
+ sugerencia: `Agregar las secciones faltantes (ver \`/swl:claudemd refactor\` para template)`,
105
+ });
106
+ }
107
+
108
+ // 4. @references si el archivo es grande
109
+ if (lineas.length > 80) {
110
+ const tieneAtReferences = /@[a-zA-Z][a-zA-Z0-9_\-./]+\.md/.test(contenido);
111
+ if (!tieneAtReferences) {
112
+ hallazgos.push({
113
+ severidad: 'WARN',
114
+ regla: 'sin-at-references',
115
+ mensaje: 'Archivo grande (>80 líneas) sin @references a docs externos',
116
+ sugerencia: 'Usar `@docs/...md` o `@.planning/...md` para enlazar contenido en lugar de duplicarlo',
117
+ });
118
+ }
119
+ }
120
+
121
+ // 5. Placeholders sin reemplazar
122
+ const matches = [...contenido.matchAll(PLACEHOLDERS)];
123
+ if (matches.length > 0) {
124
+ hallazgos.push({
125
+ severidad: 'ERROR',
126
+ regla: 'placeholders',
127
+ mensaje: `${matches.length} placeholder(s) sin reemplazar: ${[...new Set(matches.map(m => m[0]))].join(', ')}`,
128
+ sugerencia: 'Reemplazar todos los placeholders antes de commitear',
129
+ });
130
+ }
131
+
132
+ // ─── Veredicto ───────────────────────────────────────────────────────────
133
+ const tieneError = hallazgos.some(h => h.severidad === 'ERROR');
134
+ const tieneWarn = hallazgos.some(h => h.severidad === 'WARN');
135
+ const veredicto = tieneError ? 'ERROR' : tieneWarn ? 'WARN' : 'OK';
136
+
137
+ return {
138
+ veredicto,
139
+ ruta: rutaClaudeMd,
140
+ metricas: {
141
+ lineas: lineas.length,
142
+ bytes: contenido.length,
143
+ umbral_lineas: MAX_LINES,
144
+ umbral_bullet_chars: MAX_BULLET_CHARS,
145
+ secciones_presentes: SECCIONES_CANONICAS.filter(s => s.regex.test(contenido)).map(s => s.nombre),
146
+ secciones_ausentes: seccionesAusentes.map(s => s.nombre),
147
+ tiene_at_references: /@[a-zA-Z][a-zA-Z0-9_\-./]+\.md/.test(contenido),
148
+ },
149
+ hallazgos,
150
+ };
151
+ }
152
+
153
+ /**
154
+ * Detecta bullets/párrafos cuyo contenido excede MAX_BULLET_CHARS.
155
+ * Un "bullet" es una línea que empieza con `-` o `*` (ignorando indentación).
156
+ * Un "párrafo" es bloque de texto contiguo sin línea vacía.
157
+ */
158
+ function detectarBulletsGigantes(contenido) {
159
+ const lineas = contenido.split('\n');
160
+ const gigantes = [];
161
+ let buffer = '';
162
+ let lineaInicio = 0;
163
+ let dentroDeBullet = false;
164
+ let dentroDeCodeFence = false;
165
+
166
+ const flush = () => {
167
+ if (buffer.length > MAX_BULLET_CHARS) {
168
+ gigantes.push({
169
+ linea: lineaInicio + 1,
170
+ chars: buffer.length,
171
+ preview: buffer.slice(0, 100) + (buffer.length > 100 ? '…' : ''),
172
+ });
173
+ }
174
+ buffer = '';
175
+ dentroDeBullet = false;
176
+ };
177
+
178
+ for (let i = 0; i < lineas.length; i++) {
179
+ const linea = lineas[i];
180
+
181
+ // Skipear bloques de código (no son bullets)
182
+ if (/^\s*```/.test(linea)) {
183
+ flush();
184
+ dentroDeCodeFence = !dentroDeCodeFence;
185
+ continue;
186
+ }
187
+ if (dentroDeCodeFence) continue;
188
+
189
+ // Skipear tablas Markdown (líneas que empiezan con `|`):
190
+ // las tablas son grandes por naturaleza y no son "bullets monolíticos"
191
+ if (/^\s*\|/.test(linea)) {
192
+ flush();
193
+ continue;
194
+ }
195
+
196
+ // Línea vacía termina el bullet/párrafo actual
197
+ if (/^\s*$/.test(linea)) {
198
+ flush();
199
+ continue;
200
+ }
201
+
202
+ // Header termina el buffer
203
+ if (/^#/.test(linea)) {
204
+ flush();
205
+ continue;
206
+ }
207
+
208
+ // Inicio de nuevo bullet
209
+ if (/^\s*[-*+]\s/.test(linea)) {
210
+ flush();
211
+ lineaInicio = i;
212
+ buffer = linea;
213
+ dentroDeBullet = true;
214
+ continue;
215
+ }
216
+
217
+ // Continuación: si estamos en bullet, acumular; si no, párrafo
218
+ if (dentroDeBullet) {
219
+ buffer += '\n' + linea;
220
+ } else {
221
+ if (buffer === '') lineaInicio = i;
222
+ buffer += (buffer ? '\n' : '') + linea;
223
+ }
224
+ }
225
+ flush();
226
+ return gigantes;
227
+ }
228
+
229
+ // ─── CLI ──────────────────────────────────────────────────────────────────
230
+
231
+ function imprimirReporte(resultado) {
232
+ const colorVeredicto = {
233
+ OK: '\x1b[32m', // verde
234
+ WARN: '\x1b[33m', // amarillo
235
+ ERROR: '\x1b[31m', // rojo
236
+ };
237
+ const reset = '\x1b[0m';
238
+
239
+ console.log(`\n${colorVeredicto[resultado.veredicto]}=== AUDITORÍA CLAUDE.md ===${reset}`);
240
+ console.log(`Veredicto: ${colorVeredicto[resultado.veredicto]}${resultado.veredicto}${reset}`);
241
+ console.log(`Ruta: ${resultado.ruta || '(no encontrado)'}\n`);
242
+
243
+ if (resultado.metricas) {
244
+ const m = resultado.metricas;
245
+ console.log(`Métricas:`);
246
+ console.log(` - Líneas: ${m.lineas} / ${m.umbral_lineas}`);
247
+ console.log(` - Secciones canónicas presentes: ${m.secciones_presentes.length}/4 (${m.secciones_presentes.join(', ') || 'ninguna'})`);
248
+ if (m.secciones_ausentes.length > 0) {
249
+ console.log(` - Secciones ausentes: ${m.secciones_ausentes.join(', ')}`);
250
+ }
251
+ console.log(` - @references: ${m.tiene_at_references ? 'sí' : 'no'}`);
252
+ console.log('');
253
+ }
254
+
255
+ if (resultado.hallazgos.length === 0) {
256
+ console.log('Sin hallazgos. CLAUDE.md cumple best practices Anthropic.\n');
257
+ return;
258
+ }
259
+
260
+ console.log(`Hallazgos (${resultado.hallazgos.length}):\n`);
261
+ for (const h of resultado.hallazgos) {
262
+ const color = colorVeredicto[h.severidad] || '';
263
+ console.log(` ${color}[${h.severidad}]${reset} ${h.mensaje}`);
264
+ if (h.sugerencia) console.log(` → ${h.sugerencia}`);
265
+ if (h.preview) console.log(` Preview: ${h.preview}`);
266
+ console.log('');
267
+ }
268
+ }
269
+
270
+ function main() {
271
+ const args = process.argv.slice(2);
272
+ const flagJson = args.includes('--json');
273
+ const flagStrict = args.includes('--strict');
274
+ const rutaArg = args.find(a => !a.startsWith('--'));
275
+
276
+ const ruta = rutaArg
277
+ ? path.resolve(rutaArg)
278
+ : ubicarClaudeMd();
279
+
280
+ const resultado = auditar(ruta);
281
+
282
+ if (flagJson) {
283
+ console.log(JSON.stringify(resultado, null, 2));
284
+ } else {
285
+ imprimirReporte(resultado);
286
+ }
287
+
288
+ if (resultado.veredicto === 'ERROR') process.exit(1);
289
+ if (flagStrict && resultado.veredicto === 'WARN') process.exit(1);
290
+ process.exit(0);
291
+ }
292
+
293
+ if (require.main === module) {
294
+ main();
295
+ }
296
+
297
+ module.exports = { auditar, ubicarClaudeMd, detectarBulletsGigantes, MAX_LINES, MAX_BULLET_CHARS };
@@ -571,6 +571,10 @@ async function install(opciones) {
571
571
  reglas: reglasInstaladas,
572
572
  skills: skillsInstalados,
573
573
  conteos,
574
+ // ADR-0016: pasar directorio del proyecto destino para que el
575
+ // transformador Claude pueda detectar stack/comandos/framework.
576
+ // Otros transformadores ignoran este campo.
577
+ dirProyecto: process.cwd(),
574
578
  });
575
579
 
576
580
  if (instrucciones) {
@@ -0,0 +1,307 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * detectar-stack-detallado.js
5
+ *
6
+ * Detecta stack del proyecto destino con información rica para generación de
7
+ * CLAUDE.md (no solo presencia, sino también: framework principal, scripts
8
+ * disponibles, package manager, deps clave).
9
+ *
10
+ * Diferencia con `detectar-stack.js`: ese módulo es para FILTRAR reglas de
11
+ * lenguaje (presence/absence). Este módulo es para POBLAR el bloque CLAUDE.md
12
+ * inyectado por el installer con info accionable del proyecto destino.
13
+ *
14
+ * Zero-dependencies (solo fs/path nativos). Defensivo: cualquier read failure
15
+ * devuelve null/undefined, nunca lanza.
16
+ */
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+
21
+ /**
22
+ * Lee package.json del proyecto destino.
23
+ * @returns {{ name?: string, version?: string, scripts?: object, dependencies?: object, devDependencies?: object } | null}
24
+ */
25
+ function leerPackageJson(dirProyecto) {
26
+ return _leerJsonSeguro(path.join(dirProyecto, 'package.json'));
27
+ }
28
+
29
+ /**
30
+ * Detecta el package manager Node usado (basado en lockfile).
31
+ * @returns {'pnpm' | 'yarn' | 'bun' | 'npm' | null}
32
+ */
33
+ function detectarPackageManagerNode(dirProyecto) {
34
+ if (fs.existsSync(path.join(dirProyecto, 'pnpm-lock.yaml'))) return 'pnpm';
35
+ if (fs.existsSync(path.join(dirProyecto, 'yarn.lock'))) return 'yarn';
36
+ if (fs.existsSync(path.join(dirProyecto, 'bun.lockb'))) return 'bun';
37
+ if (fs.existsSync(path.join(dirProyecto, 'package-lock.json'))) return 'npm';
38
+ if (fs.existsSync(path.join(dirProyecto, 'package.json'))) return 'npm';
39
+ return null;
40
+ }
41
+
42
+ /**
43
+ * Detecta el package manager Python.
44
+ * @returns {'poetry' | 'uv' | 'pdm' | 'pip' | null}
45
+ */
46
+ function detectarPackageManagerPython(dirProyecto) {
47
+ const pyproject = path.join(dirProyecto, 'pyproject.toml');
48
+ if (fs.existsSync(pyproject)) {
49
+ const contenido = _leerArchivoSeguro(pyproject) || '';
50
+ if (contenido.includes('[tool.poetry]')) return 'poetry';
51
+ if (contenido.includes('[tool.uv]')) return 'uv';
52
+ if (contenido.includes('[tool.pdm]')) return 'pdm';
53
+ return 'pip'; // pyproject genérico
54
+ }
55
+ if (fs.existsSync(path.join(dirProyecto, 'requirements.txt'))) return 'pip';
56
+ if (fs.existsSync(path.join(dirProyecto, 'Pipfile'))) return 'pip';
57
+ return null;
58
+ }
59
+
60
+ /**
61
+ * Detecta framework Node a partir de dependencies.
62
+ * @returns {string | null}
63
+ */
64
+ function detectarFrameworkNode(packageJson) {
65
+ if (!packageJson) return null;
66
+ const deps = { ...(packageJson.dependencies || {}), ...(packageJson.devDependencies || {}) };
67
+
68
+ if (deps.next) return `Next.js ${_limpiarVersion(deps.next)}`;
69
+ if (deps['@angular/core']) return `Angular ${_limpiarVersion(deps['@angular/core'])}`;
70
+ if (deps['@nestjs/core']) return `NestJS ${_limpiarVersion(deps['@nestjs/core'])}`;
71
+ if (deps.svelte) return `Svelte ${_limpiarVersion(deps.svelte)}`;
72
+ if (deps.vue) return `Vue ${_limpiarVersion(deps.vue)}`;
73
+ if (deps.remix || deps['@remix-run/node']) return 'Remix';
74
+ if (deps.astro) return `Astro ${_limpiarVersion(deps.astro)}`;
75
+ if (deps.nuxt) return `Nuxt ${_limpiarVersion(deps.nuxt)}`;
76
+ if (deps.fastify) return `Fastify ${_limpiarVersion(deps.fastify)}`;
77
+ if (deps.express) return `Express ${_limpiarVersion(deps.express)}`;
78
+ if (deps.react) return `React ${_limpiarVersion(deps.react)} (sin framework)`;
79
+
80
+ return null;
81
+ }
82
+
83
+ /**
84
+ * Detecta framework Python leyendo deps en pyproject.toml o requirements.txt.
85
+ * @returns {string | null}
86
+ */
87
+ function detectarFrameworkPython(dirProyecto) {
88
+ const pyproject = _leerArchivoSeguro(path.join(dirProyecto, 'pyproject.toml')) || '';
89
+ const requirements = _leerArchivoSeguro(path.join(dirProyecto, 'requirements.txt')) || '';
90
+ const deps = (pyproject + '\n' + requirements).toLowerCase();
91
+
92
+ if (deps.includes('fastapi')) return 'FastAPI';
93
+ if (deps.includes('django')) return 'Django';
94
+ if (deps.includes('flask')) return 'Flask';
95
+ if (deps.includes('starlette')) return 'Starlette';
96
+ if (deps.includes('aiohttp')) return 'aiohttp';
97
+ return null;
98
+ }
99
+
100
+ /**
101
+ * Detecta el ORM/driver de BD principal.
102
+ * @returns {string | null}
103
+ */
104
+ function detectarORM(packageJson, dirProyecto) {
105
+ const depsNode = packageJson
106
+ ? { ...(packageJson.dependencies || {}), ...(packageJson.devDependencies || {}) }
107
+ : {};
108
+
109
+ if (depsNode.prisma || depsNode['@prisma/client']) return 'Prisma';
110
+ if (depsNode['drizzle-orm']) return 'Drizzle';
111
+ if (depsNode.typeorm) return 'TypeORM';
112
+ if (depsNode.sequelize) return 'Sequelize';
113
+ if (depsNode.mongoose) return 'Mongoose';
114
+
115
+ // Python
116
+ const pyproject = _leerArchivoSeguro(path.join(dirProyecto, 'pyproject.toml')) || '';
117
+ const requirements = _leerArchivoSeguro(path.join(dirProyecto, 'requirements.txt')) || '';
118
+ const depsPy = (pyproject + '\n' + requirements).toLowerCase();
119
+ if (depsPy.includes('sqlalchemy')) return 'SQLAlchemy';
120
+ if (depsPy.includes('peewee')) return 'Peewee';
121
+ if (depsPy.includes('tortoise-orm')) return 'Tortoise ORM';
122
+
123
+ return null;
124
+ }
125
+
126
+ /**
127
+ * Detecta lenguaje principal con confianza (devuelve el más probable).
128
+ * @returns {{ lenguaje: string, runtime?: string } | null}
129
+ */
130
+ function detectarLenguajePrincipal(dirProyecto) {
131
+ // Node.js / TypeScript
132
+ if (fs.existsSync(path.join(dirProyecto, 'package.json'))) {
133
+ if (fs.existsSync(path.join(dirProyecto, 'tsconfig.json'))) {
134
+ return { lenguaje: 'TypeScript', runtime: 'Node.js' };
135
+ }
136
+ return { lenguaje: 'JavaScript', runtime: 'Node.js' };
137
+ }
138
+ // Python
139
+ if (
140
+ fs.existsSync(path.join(dirProyecto, 'pyproject.toml')) ||
141
+ fs.existsSync(path.join(dirProyecto, 'requirements.txt')) ||
142
+ fs.existsSync(path.join(dirProyecto, 'setup.py'))
143
+ ) {
144
+ return { lenguaje: 'Python' };
145
+ }
146
+ // Go
147
+ if (fs.existsSync(path.join(dirProyecto, 'go.mod'))) return { lenguaje: 'Go' };
148
+ // Rust
149
+ if (fs.existsSync(path.join(dirProyecto, 'Cargo.toml'))) return { lenguaje: 'Rust' };
150
+ // Java / Kotlin
151
+ if (fs.existsSync(path.join(dirProyecto, 'pom.xml'))) return { lenguaje: 'Java', runtime: 'Maven' };
152
+ if (
153
+ fs.existsSync(path.join(dirProyecto, 'build.gradle')) ||
154
+ fs.existsSync(path.join(dirProyecto, 'build.gradle.kts'))
155
+ ) {
156
+ return { lenguaje: 'Java/Kotlin', runtime: 'Gradle' };
157
+ }
158
+ // PHP
159
+ if (fs.existsSync(path.join(dirProyecto, 'composer.json'))) return { lenguaje: 'PHP' };
160
+ // Swift
161
+ if (fs.existsSync(path.join(dirProyecto, 'Package.swift'))) return { lenguaje: 'Swift' };
162
+ // Ruby
163
+ if (fs.existsSync(path.join(dirProyecto, 'Gemfile'))) return { lenguaje: 'Ruby' };
164
+ // C# / .NET
165
+ if (fs.existsSync(path.join(dirProyecto, 'global.json'))) return { lenguaje: 'C#', runtime: '.NET' };
166
+
167
+ return null;
168
+ }
169
+
170
+ /**
171
+ * Detecta scripts comunes del proyecto (test, dev, build, lint).
172
+ * Devuelve los scripts npm si existen + comandos típicos del lenguaje.
173
+ *
174
+ * @returns {Array<{ comando: string, proposito: string }>}
175
+ */
176
+ function detectarComandos(dirProyecto) {
177
+ const comandos = [];
178
+ const pkg = leerPackageJson(dirProyecto);
179
+ const pm = detectarPackageManagerNode(dirProyecto);
180
+
181
+ if (pkg && pkg.scripts) {
182
+ const interesantes = ['dev', 'start', 'build', 'test', 'lint', 'typecheck', 'format'];
183
+ for (const script of interesantes) {
184
+ if (pkg.scripts[script]) {
185
+ comandos.push({
186
+ comando: `${pm || 'npm'} run ${script}`,
187
+ proposito: _propositoScript(script),
188
+ });
189
+ }
190
+ }
191
+ // Si tiene "test" como entrypoint puro
192
+ if (pkg.scripts.test && !comandos.some(c => c.comando.includes('test'))) {
193
+ comandos.push({ comando: `${pm || 'npm'} test`, proposito: 'Tests' });
194
+ }
195
+ }
196
+
197
+ // Python
198
+ const pmPy = detectarPackageManagerPython(dirProyecto);
199
+ if (pmPy === 'poetry') {
200
+ comandos.push({ comando: 'poetry install', proposito: 'Instalar dependencias' });
201
+ comandos.push({ comando: 'poetry run pytest', proposito: 'Tests' });
202
+ } else if (pmPy === 'uv') {
203
+ comandos.push({ comando: 'uv sync', proposito: 'Instalar dependencias' });
204
+ comandos.push({ comando: 'uv run pytest', proposito: 'Tests' });
205
+ } else if (pmPy === 'pip') {
206
+ comandos.push({ comando: 'pip install -r requirements.txt', proposito: 'Instalar dependencias' });
207
+ comandos.push({ comando: 'pytest', proposito: 'Tests' });
208
+ }
209
+
210
+ // Go
211
+ if (fs.existsSync(path.join(dirProyecto, 'go.mod'))) {
212
+ comandos.push({ comando: 'go test ./...', proposito: 'Tests' });
213
+ comandos.push({ comando: 'go build ./...', proposito: 'Build' });
214
+ }
215
+
216
+ // Rust
217
+ if (fs.existsSync(path.join(dirProyecto, 'Cargo.toml'))) {
218
+ comandos.push({ comando: 'cargo test', proposito: 'Tests' });
219
+ comandos.push({ comando: 'cargo build', proposito: 'Build' });
220
+ comandos.push({ comando: 'cargo clippy', proposito: 'Lint' });
221
+ }
222
+
223
+ return comandos;
224
+ }
225
+
226
+ /**
227
+ * Detección integral: devuelve resumen del stack del proyecto destino.
228
+ *
229
+ * @returns {{
230
+ * lenguajePrincipal: { lenguaje: string, runtime?: string } | null,
231
+ * framework: string | null,
232
+ * orm: string | null,
233
+ * packageManager: string | null,
234
+ * comandos: Array<{ comando: string, proposito: string }>,
235
+ * detectado: boolean
236
+ * }}
237
+ */
238
+ function detectarStackDetallado(dirProyecto) {
239
+ const lenguajePrincipal = detectarLenguajePrincipal(dirProyecto);
240
+ const pkg = leerPackageJson(dirProyecto);
241
+ const framework = detectarFrameworkNode(pkg) || detectarFrameworkPython(dirProyecto);
242
+ const orm = detectarORM(pkg, dirProyecto);
243
+ const packageManager =
244
+ detectarPackageManagerNode(dirProyecto) || detectarPackageManagerPython(dirProyecto);
245
+ const comandos = detectarComandos(dirProyecto);
246
+
247
+ return {
248
+ lenguajePrincipal,
249
+ framework,
250
+ orm,
251
+ packageManager,
252
+ comandos,
253
+ detectado: lenguajePrincipal !== null,
254
+ };
255
+ }
256
+
257
+ // ─── Helpers privados ────────────────────────────────────────────────────────
258
+
259
+ function _leerJsonSeguro(ruta) {
260
+ try {
261
+ if (!fs.existsSync(ruta)) return null;
262
+ return JSON.parse(fs.readFileSync(ruta, 'utf8'));
263
+ } catch {
264
+ return null;
265
+ }
266
+ }
267
+
268
+ function _leerArchivoSeguro(ruta) {
269
+ try {
270
+ if (!fs.existsSync(ruta)) return null;
271
+ return fs.readFileSync(ruta, 'utf8');
272
+ } catch {
273
+ return null;
274
+ }
275
+ }
276
+
277
+ function _limpiarVersion(rango) {
278
+ // "^15.0.0" → "15", "~3.4.1" → "3"
279
+ if (typeof rango !== 'string') return '';
280
+ const m = rango.match(/(\d+)/);
281
+ return m ? m[1] : '';
282
+ }
283
+
284
+ function _propositoScript(nombre) {
285
+ const map = {
286
+ dev: 'Servidor de desarrollo',
287
+ start: 'Iniciar app',
288
+ build: 'Build de producción',
289
+ test: 'Tests',
290
+ lint: 'Lint',
291
+ typecheck: 'Verificar tipos',
292
+ format: 'Formatear código',
293
+ };
294
+ return map[nombre] || nombre;
295
+ }
296
+
297
+ module.exports = {
298
+ detectarStackDetallado,
299
+ detectarLenguajePrincipal,
300
+ detectarFrameworkNode,
301
+ detectarFrameworkPython,
302
+ detectarORM,
303
+ detectarPackageManagerNode,
304
+ detectarPackageManagerPython,
305
+ detectarComandos,
306
+ leerPackageJson,
307
+ };