@saulwade/swl-ses 1.5.0 → 1.5.2

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 (134) hide show
  1. package/CLAUDE.md +19 -2
  2. package/README.md +561 -561
  3. package/agentes/arquitecto-swl.md +33 -1
  4. package/agentes/nemesis-auditor-swl.md +59 -19
  5. package/bin/swl-mcp-server.js +214 -214
  6. package/comandos/swl/.evolved.json +22 -22
  7. package/comandos/swl/contribuir.md +233 -233
  8. package/comandos/swl/nemesis.md +230 -56
  9. package/gateway/lib/event-channel.js +191 -191
  10. package/habilidades/backend-production-resilience/SKILL.md +288 -288
  11. package/habilidades/benchmark-memoria/SKILL.md +186 -186
  12. package/habilidades/diagrama-arquitectura/assets/template.html +276 -276
  13. package/habilidades/doubt-driven-review/SKILL.md +171 -171
  14. package/habilidades/doubt-driven-review/recursos/EXAMPLES.md +130 -130
  15. package/habilidades/ejecutar-task-iterativo/SKILL.md +278 -278
  16. package/habilidades/eval-framework/SKILL.md +212 -212
  17. package/habilidades/feynman-auditor-swl/SKILL.md +123 -123
  18. package/habilidades/feynman-auditor-swl/recursos/preguntas-language-agnostic.md +108 -108
  19. package/habilidades/harness-claude-code/SKILL.md +299 -299
  20. package/habilidades/infra-github-actions/SKILL.md +166 -166
  21. package/habilidades/legacy-code-rescue/SKILL.md +267 -267
  22. package/habilidades/manejo-errores/.evolved.json +8 -8
  23. package/habilidades/meta-skills-estandar/SKILL.md +225 -1
  24. package/habilidades/meta-skills-estandar/recursos/convencion-examples.md +93 -93
  25. package/habilidades/meta-skills-estandar/recursos/skills-as-agents.md +163 -163
  26. package/habilidades/nemesis-evaluacion-json/SKILL.md +266 -0
  27. package/habilidades/nemesis-redistribuir/SKILL.md +341 -0
  28. package/habilidades/node-experto/SKILL.md +105 -4
  29. package/habilidades/patrones-python/SKILL.md +229 -229
  30. package/habilidades/patrones-python/recursos/patrones-avanzados.md +469 -469
  31. package/habilidades/planear-fase/SKILL.md +319 -319
  32. package/habilidades/protocolo-revision-swl/SKILL.md +350 -276
  33. package/habilidades/release-semver/.evolved.json +8 -8
  34. package/habilidades/state-inconsistency-auditor-swl/SKILL.md +166 -166
  35. package/habilidades/state-inconsistency-auditor-swl/recursos/coupled-state-patterns.md +147 -147
  36. package/habilidades/tdd-workflow/SKILL.md +150 -4
  37. package/habilidades/testing-python/SKILL.md +340 -340
  38. package/habilidades/verificar-trabajo/SKILL.md +8 -3
  39. package/habilidades/web-fetcher-routing/SKILL.md +75 -75
  40. package/hooks/check-update.js +31 -3
  41. package/hooks/claudemd-bloat-detector.js +161 -161
  42. package/hooks/lib/agent-routing.js +107 -107
  43. package/hooks/lib/auto-consolidator.js +335 -335
  44. package/hooks/lib/error-classifier.js +308 -308
  45. package/hooks/lib/merkle-audit.js +96 -96
  46. package/hooks/lib/provenance-tracker.js +191 -191
  47. package/hooks/lib/rate-limit-tracker.js +253 -253
  48. package/hooks/lib/resource-quota.js +122 -122
  49. package/hooks/lib/retry-jitter.js +165 -165
  50. package/hooks/lib/security-net.js +201 -201
  51. package/hooks/lib/skill-auditor.js +588 -588
  52. package/hooks/lib/sync-status.js +228 -228
  53. package/hooks/lib/taint-tracker.js +107 -107
  54. package/hooks/lib/text-similarity.js +241 -241
  55. package/hooks/lib/toon-compressor.js +245 -245
  56. package/hooks/registro-turnos.js +209 -209
  57. package/hooks/sugerir-regenerar-inventario.js +170 -170
  58. package/hooks/validar-formato-post-subagente.js +140 -140
  59. package/hooks/validar-memoria-hook.js +218 -218
  60. package/instintos/prompt-appendices.yaml +57 -57
  61. package/manifiestos/agent-output-schemas.json +57 -57
  62. package/manifiestos/modulos.json +1324 -1321
  63. package/manifiestos/skills-lock.json +1114 -1114
  64. package/package.json +2 -2
  65. package/plantillas/auditor-veto-template.md +105 -105
  66. package/plantillas/github-workflows/README.md +47 -47
  67. package/plantillas/github-workflows/release-please.yml +44 -44
  68. package/plantillas/github-workflows/swl-ci.yml +107 -107
  69. package/plantillas/github-workflows/swl-security.yml +51 -51
  70. package/plugin.json +353 -351
  71. package/reglas/analisis-previo-tareas-grandes.md +172 -172
  72. package/reglas/arreglar-al-detectar.md +147 -147
  73. package/reglas/fragmentos-compartidos.md +152 -152
  74. package/reglas/harness-claude-code.md +213 -213
  75. package/reglas/registro-componentes-nuevos.md +192 -0
  76. package/reglas/usar-context7.md +226 -226
  77. package/schemas/diary-entry.schema.json +80 -80
  78. package/scripts/actualizar.js +110 -1
  79. package/scripts/audit-tools/audit-history.js +330 -330
  80. package/scripts/audit-tools/bundle-tracker.js +290 -290
  81. package/scripts/audit-tools/canary-monitor.js +352 -352
  82. package/scripts/audit-tools/code-profiler.js +605 -605
  83. package/scripts/audit-tools/dep-doctor.js +320 -320
  84. package/scripts/audit-tools/env-validator.js +206 -206
  85. package/scripts/audit-tools/lib/fs-walk.js +48 -48
  86. package/scripts/audit-tools/lib/output.js +23 -23
  87. package/scripts/audit-tools/migration-checker.js +392 -392
  88. package/scripts/audit-tools/pentest-scanner.js +1436 -1436
  89. package/scripts/benchmark-memoria.js +167 -167
  90. package/scripts/configurar-branch-protection.js +418 -418
  91. package/scripts/derivar-feature-list.js +489 -489
  92. package/scripts/detectar-aprendizajes-duplicados.js +151 -151
  93. package/scripts/doctor.js +58 -4
  94. package/scripts/field-report.js +199 -199
  95. package/scripts/generar-checklists-consolidados.js +273 -273
  96. package/scripts/generar-inventario.js +420 -420
  97. package/scripts/generar-matriz-lenguajes.js +271 -271
  98. package/scripts/lib/artefactos-python.js +43 -43
  99. package/scripts/lib/benchmark-metrics.js +160 -160
  100. package/scripts/lib/budget-enforcer.js +252 -252
  101. package/scripts/lib/configurar-ci.js +380 -380
  102. package/scripts/lib/contadores-inventario.js +217 -217
  103. package/scripts/lib/detectar-stack-detallado.js +307 -307
  104. package/scripts/lib/diary-entry.js +234 -234
  105. package/scripts/lib/eval-metrics-store.js +218 -218
  106. package/scripts/lib/eval-quality.js +171 -171
  107. package/scripts/lib/eval-schemas.js +144 -144
  108. package/scripts/lib/eval-self-correct.js +106 -106
  109. package/scripts/lib/eval-validator.js +185 -185
  110. package/scripts/lib/expandir-targets.js +71 -71
  111. package/scripts/lib/jaccard-similarity.js +98 -98
  112. package/scripts/lib/longmemeval-runner.js +125 -125
  113. package/scripts/lib/mcp_config.py +127 -0
  114. package/scripts/lib/npm-version.js +261 -261
  115. package/scripts/lib/paquetes-conocidos.js +50 -50
  116. package/scripts/lib/prompt-builder.js +264 -264
  117. package/scripts/lib/rrf-fusion.js +175 -175
  118. package/scripts/lib/scoring-instintos.js +277 -277
  119. package/scripts/lib/semantic-search.js +252 -252
  120. package/scripts/lib/toml-merge.js +204 -204
  121. package/scripts/lib/transformadores/codex.js +375 -375
  122. package/scripts/lib/transformadores/cursor.js +359 -359
  123. package/scripts/limpiar-artefactos-python.js +131 -131
  124. package/scripts/mcp-orchestrator.py +8 -18
  125. package/scripts/mcp-pool-manager.py +12 -23
  126. package/scripts/mcp-server/README.md +170 -170
  127. package/scripts/mcp-server/auth.js +105 -105
  128. package/scripts/mcp-server/cache.js +106 -106
  129. package/scripts/mcp-server/telemetry.js +78 -78
  130. package/scripts/migrar-csv-a-array.js +168 -168
  131. package/scripts/migrar-fase-dominio.js +201 -201
  132. package/scripts/publicar.js +511 -511
  133. package/scripts/run-eval.js +141 -141
  134. package/scripts/validar-userland-vacio.js +110 -110
@@ -1,392 +1,392 @@
1
- // Adaptado de temp/ultraship-main/tools/migration-checker.mjs bajo MIT License
2
- // Fuente: Houseofmvps/ultraship (https://github.com/Houseofmvps/ultraship)
3
- 'use strict';
4
-
5
- const { readFileSync, existsSync, readdirSync, statSync } = require('fs');
6
- const { join, relative, resolve } = require('path');
7
- const { outputJSON, outputError } = require('./lib/output');
8
-
9
- /**
10
- * Detecta el ORM de un directorio revisando package.json o archivos Python.
11
- * @param {string} dir
12
- * @returns {string|null}
13
- */
14
- function detectOrm(dir) {
15
- // Verificar primero ORM de Python (Alembic)
16
- const alembicDetected = (
17
- existsSync(join(dir, 'alembic.ini')) ||
18
- (existsSync(join(dir, 'alembic')) && existsSync(join(dir, 'alembic', 'versions')))
19
- );
20
- if (alembicDetected) return 'alembic';
21
-
22
- // Verificar requirements.txt / pyproject.toml para alembic
23
- const reqPath = join(dir, 'requirements.txt');
24
- if (existsSync(reqPath)) {
25
- const content = readFileSync(reqPath, 'utf8').toLowerCase();
26
- if (content.includes('alembic')) return 'alembic';
27
- }
28
- const pyprojectPath = join(dir, 'pyproject.toml');
29
- if (existsSync(pyprojectPath)) {
30
- const content = readFileSync(pyprojectPath, 'utf8').toLowerCase();
31
- if (content.includes('alembic')) return 'alembic';
32
- }
33
-
34
- // ORM de Node.js desde package.json
35
- const pkgPath = join(dir, 'package.json');
36
- if (!existsSync(pkgPath)) return null;
37
-
38
- let pkg;
39
- try {
40
- pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
41
- } catch {
42
- return null;
43
- }
44
- const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
45
-
46
- if (allDeps['drizzle-orm'] || allDeps['drizzle-kit']) return 'drizzle';
47
- if (allDeps['prisma'] || allDeps['@prisma/client']) return 'prisma';
48
- if (allDeps['knex']) return 'knex';
49
- if (allDeps['typeorm']) return 'typeorm';
50
- if (allDeps['sequelize']) return 'sequelize';
51
- if (allDeps['mongoose']) return 'mongoose';
52
- return null;
53
- }
54
-
55
- /**
56
- * Revisa migraciones de Drizzle ORM.
57
- * @param {string} dir
58
- * @returns {object}
59
- */
60
- function checkDrizzle(dir) {
61
- const findings = [];
62
- const info = { orm: 'drizzle', migration_dir: null, schema_files: [], migrations: [] };
63
-
64
- // Buscar config de Drizzle
65
- const configNames = ['drizzle.config.ts', 'drizzle.config.js', 'drizzle.config.mjs'];
66
- let configPath = null;
67
- for (const name of configNames) {
68
- const p = join(dir, name);
69
- if (existsSync(p)) { configPath = p; break; }
70
- }
71
-
72
- if (!configPath) {
73
- findings.push({ severity: 'high', message: 'No se encontró drizzle.config — las migraciones podrían no estar configuradas' });
74
- } else {
75
- const config = readFileSync(configPath, 'utf8');
76
- const outMatch = config.match(/out\s*:\s*['"]([^'"]+)['"]/);
77
- if (outMatch) info.migration_dir = outMatch[1];
78
- }
79
-
80
- // Buscar directorio de migraciones
81
- const migrationDirs = [info.migration_dir, 'drizzle', 'migrations', 'db/migrations'].filter(Boolean);
82
- let migDir = null;
83
- for (const d of migrationDirs) {
84
- const p = join(dir, d);
85
- try {
86
- if (existsSync(p) && statSync(p).isDirectory()) { migDir = p; info.migration_dir = d; break; }
87
- } catch { /* skip */ }
88
- }
89
-
90
- if (migDir) {
91
- const files = readdirSync(migDir).filter(f => f.endsWith('.sql') || f.endsWith('.ts') || f.endsWith('.js'));
92
- info.migrations = files.map(f => {
93
- try {
94
- const s = statSync(join(migDir, f));
95
- return { name: f, modified: s.mtime.toISOString().split('T')[0] };
96
- } catch { return { name: f }; }
97
- });
98
- info.migration_count = files.length;
99
-
100
- // Verificar journal (Drizzle registra migraciones aplicadas)
101
- const journalPath = join(migDir, 'meta', '_journal.json');
102
- if (existsSync(journalPath)) {
103
- try {
104
- const journal = JSON.parse(readFileSync(journalPath, 'utf8'));
105
- info.applied_count = journal.entries ? journal.entries.length : 0;
106
- if (info.migration_count > info.applied_count) {
107
- findings.push({
108
- severity: 'critical',
109
- message: `${info.migration_count - info.applied_count} migración(es) pendiente(s) sin aplicar — ejecutar: npx drizzle-kit push`,
110
- });
111
- }
112
- } catch { /* ignorar */ }
113
- }
114
- } else {
115
- findings.push({ severity: 'medium', message: 'No se encontró directorio de migraciones — ejecutar: npx drizzle-kit generate' });
116
- }
117
-
118
- // Buscar archivos de schema
119
- const schemaPatterns = ['schema.ts', 'schema.js', 'db/schema.ts', 'src/db/schema.ts', 'src/schema.ts'];
120
- for (const pattern of schemaPatterns) {
121
- if (existsSync(join(dir, pattern))) info.schema_files.push(pattern);
122
- }
123
- const schemaDirs = ['src/db', 'db', 'src/schema'];
124
- for (const d of schemaDirs) {
125
- const p = join(dir, d);
126
- try {
127
- if (existsSync(p) && statSync(p).isDirectory()) {
128
- const files = readdirSync(p).filter(f => f.includes('schema') && (f.endsWith('.ts') || f.endsWith('.js')));
129
- for (const f of files) info.schema_files.push(join(d, f));
130
- }
131
- } catch { /* skip */ }
132
- }
133
-
134
- if (info.schema_files.length === 0) {
135
- findings.push({ severity: 'high', message: 'No se encontraron archivos de schema — Drizzle ORM requiere definiciones de schema' });
136
- }
137
-
138
- return { ...info, findings };
139
- }
140
-
141
- /**
142
- * Revisa migraciones de Prisma.
143
- * @param {string} dir
144
- * @returns {object}
145
- */
146
- function checkPrisma(dir) {
147
- const findings = [];
148
- const info = { orm: 'prisma', schema_file: null, migrations: [] };
149
-
150
- const schemaPaths = ['prisma/schema.prisma', 'schema.prisma'];
151
- for (const p of schemaPaths) {
152
- if (existsSync(join(dir, p))) { info.schema_file = p; break; }
153
- }
154
-
155
- if (!info.schema_file) {
156
- findings.push({ severity: 'critical', message: 'No se encontró prisma/schema.prisma' });
157
- return { ...info, findings };
158
- }
159
-
160
- const migDir = join(dir, 'prisma/migrations');
161
- try {
162
- if (existsSync(migDir) && statSync(migDir).isDirectory()) {
163
- const dirs = readdirSync(migDir).filter(f => {
164
- try {
165
- const p = join(migDir, f);
166
- return statSync(p).isDirectory() && f !== '_lock';
167
- } catch { return false; }
168
- });
169
- info.migrations = dirs.map(d => ({ name: d }));
170
- info.migration_count = dirs.length;
171
- } else {
172
- findings.push({ severity: 'medium', message: 'No se encontró directorio de migraciones de Prisma — ejecutar: npx prisma migrate dev' });
173
- }
174
- } catch { /* skip */ }
175
-
176
- const nodeModulesPrisma = join(dir, 'node_modules/.prisma/client');
177
- if (!existsSync(nodeModulesPrisma)) {
178
- findings.push({ severity: 'high', message: 'Cliente de Prisma no generado — ejecutar: npx prisma generate' });
179
- }
180
-
181
- return { ...info, findings };
182
- }
183
-
184
- /**
185
- * Revisa migraciones de Knex.
186
- * @param {string} dir
187
- * @returns {object}
188
- */
189
- function checkKnex(dir) {
190
- const findings = [];
191
- const info = { orm: 'knex', migration_dir: null, migrations: [] };
192
-
193
- const knexfileNames = ['knexfile.js', 'knexfile.ts', 'knexfile.mjs'];
194
- let found = false;
195
- for (const name of knexfileNames) {
196
- if (existsSync(join(dir, name))) { found = true; break; }
197
- }
198
-
199
- if (!found) {
200
- findings.push({ severity: 'medium', message: 'No se encontró knexfile — la configuración de migraciones podría estar inline' });
201
- }
202
-
203
- const migDirs = ['migrations', 'db/migrations', 'src/migrations'];
204
- for (const d of migDirs) {
205
- const p = join(dir, d);
206
- try {
207
- if (existsSync(p) && statSync(p).isDirectory()) {
208
- info.migration_dir = d;
209
- const files = readdirSync(p).filter(f => f.endsWith('.js') || f.endsWith('.ts'));
210
- info.migrations = files.map(f => ({ name: f }));
211
- info.migration_count = files.length;
212
- break;
213
- }
214
- } catch { /* skip */ }
215
- }
216
-
217
- if (!info.migration_dir) {
218
- findings.push({ severity: 'medium', message: 'No se encontró directorio de migraciones — ejecutar: npx knex migrate:make initial' });
219
- }
220
-
221
- return { ...info, findings };
222
- }
223
-
224
- /**
225
- * Revisa migraciones de Alembic (Python/SQLAlchemy).
226
- * Detecta mediante alembic.ini, directorio alembic/versions/, requirements.txt o pyproject.toml.
227
- * Compara revisiones encontradas en archivos contra .alembic_applied.txt (opcional).
228
- * @param {string} dir
229
- * @returns {object}
230
- */
231
- function checkAlembic(dir) {
232
- const findings = [];
233
- const info = {
234
- orm: 'alembic',
235
- versions_dir: null,
236
- revisions_found: [],
237
- revisions_applied: null,
238
- pending: [],
239
- extra_applied: [],
240
- };
241
-
242
- // Localizar directorio de versiones
243
- const versionsDir = join(dir, 'alembic', 'versions');
244
- if (existsSync(versionsDir)) {
245
- info.versions_dir = 'alembic/versions';
246
- }
247
-
248
- if (!info.versions_dir) {
249
- findings.push({
250
- severity: 'medium',
251
- message: 'No se encontró directorio alembic/versions/ — ejecutar: alembic init alembic',
252
- });
253
- return { ...info, findings };
254
- }
255
-
256
- // Parsear revision IDs de archivos de migración Python
257
- let versionFiles = [];
258
- try {
259
- versionFiles = readdirSync(versionsDir).filter(f => f.endsWith('.py') && f !== '__init__.py');
260
- } catch {
261
- findings.push({ severity: 'high', message: `No se pudo leer el directorio ${info.versions_dir}` });
262
- return { ...info, findings };
263
- }
264
-
265
- const revisionRegex = /revision\s*=\s*['"]([^'"]+)['"]/;
266
- for (const file of versionFiles) {
267
- try {
268
- const content = readFileSync(join(versionsDir, file), 'utf8');
269
- const match = content.match(revisionRegex);
270
- if (match) {
271
- info.revisions_found.push({ revision: match[1], file });
272
- }
273
- } catch { /* skip archivos no legibles */ }
274
- }
275
-
276
- if (info.revisions_found.length === 0 && versionFiles.length > 0) {
277
- findings.push({
278
- severity: 'medium',
279
- message: `Se encontraron ${versionFiles.length} archivo(s) en alembic/versions/ pero ninguno tiene campo 'revision' — revisar formato`,
280
- });
281
- }
282
-
283
- // Comparar contra .alembic_applied.txt (opcional)
284
- const appliedPath = join(dir, '.alembic_applied.txt');
285
- if (existsSync(appliedPath)) {
286
- try {
287
- const appliedContent = readFileSync(appliedPath, 'utf8');
288
- const appliedRevisions = new Set(
289
- appliedContent.split('\n').map(l => l.trim()).filter(Boolean)
290
- );
291
- info.revisions_applied = [...appliedRevisions];
292
-
293
- const foundRevisions = new Set(info.revisions_found.map(r => r.revision));
294
-
295
- // Pendientes: en archivos pero no aplicadas
296
- info.pending = info.revisions_found
297
- .filter(r => !appliedRevisions.has(r.revision))
298
- .map(r => r.revision);
299
-
300
- // Extra: aplicadas pero no en archivos (posible eliminación de migración)
301
- info.extra_applied = [...appliedRevisions].filter(r => !foundRevisions.has(r));
302
-
303
- if (info.pending.length > 0) {
304
- findings.push({
305
- severity: 'critical',
306
- message: `${info.pending.length} migración(es) de Alembic pendiente(s) sin aplicar — ejecutar: alembic upgrade head`,
307
- pending_revisions: info.pending,
308
- });
309
- }
310
-
311
- if (info.extra_applied.length > 0) {
312
- findings.push({
313
- severity: 'high',
314
- message: `${info.extra_applied.length} revisión(es) aplicada(s) no encontradas en archivos — posible eliminación de migración`,
315
- extra_revisions: info.extra_applied,
316
- });
317
- }
318
- } catch {
319
- findings.push({ severity: 'low', message: 'No se pudo leer .alembic_applied.txt — sin comparación de estado aplicado' });
320
- }
321
- } else {
322
- // Sin archivo de aplicadas — solo reportar conteo
323
- if (info.revisions_found.length > 0) {
324
- findings.push({
325
- severity: 'info',
326
- message: `${info.revisions_found.length} revisión(es) de Alembic encontradas. Crear .alembic_applied.txt con IDs aplicados para rastrear estado`,
327
- });
328
- }
329
- }
330
-
331
- info.revision_count = info.revisions_found.length;
332
-
333
- return { ...info, findings };
334
- }
335
-
336
- function main() {
337
- const args = process.argv.slice(2);
338
- const rawDir = args.find(a => !a.startsWith('--'));
339
- const dir = resolve(rawDir || process.cwd());
340
-
341
- if (!existsSync(dir)) {
342
- outputError(`Directorio no encontrado: ${dir}`);
343
- process.exit(0);
344
- }
345
-
346
- const orm = detectOrm(dir);
347
-
348
- if (!orm) {
349
- outputJSON({
350
- success: true,
351
- packages_scanned: 1,
352
- orm: null,
353
- message: 'No se detectó un ORM compatible (Drizzle, Prisma, Knex, Alembic, TypeORM, Sequelize)',
354
- findings: [],
355
- });
356
- process.exit(0);
357
- }
358
-
359
- let result;
360
- switch (orm) {
361
- case 'drizzle': result = checkDrizzle(dir); break;
362
- case 'prisma': result = checkPrisma(dir); break;
363
- case 'knex': result = checkKnex(dir); break;
364
- case 'alembic': result = checkAlembic(dir); break;
365
- default:
366
- result = {
367
- orm,
368
- findings: [{
369
- severity: 'info',
370
- message: `${orm} detectado pero la verificación de migraciones aún no está implementada para este ORM`,
371
- }],
372
- };
373
- }
374
-
375
- const allFindings = result.findings || [];
376
- const deploySafe = allFindings.filter(f => f.severity === 'critical').length === 0;
377
-
378
- outputJSON({
379
- success: true,
380
- packages_scanned: 1,
381
- deploy_safe: deploySafe,
382
- orm,
383
- result,
384
- findings: allFindings,
385
- });
386
- }
387
-
388
- if (require.main === module) {
389
- main();
390
- }
391
-
392
- module.exports = { detectOrm, checkDrizzle, checkPrisma, checkKnex, checkAlembic };
1
+ // Adaptado de temp/ultraship-main/tools/migration-checker.mjs bajo MIT License
2
+ // Fuente: Houseofmvps/ultraship (https://github.com/Houseofmvps/ultraship)
3
+ 'use strict';
4
+
5
+ const { readFileSync, existsSync, readdirSync, statSync } = require('fs');
6
+ const { join, relative, resolve } = require('path');
7
+ const { outputJSON, outputError } = require('./lib/output');
8
+
9
+ /**
10
+ * Detecta el ORM de un directorio revisando package.json o archivos Python.
11
+ * @param {string} dir
12
+ * @returns {string|null}
13
+ */
14
+ function detectOrm(dir) {
15
+ // Verificar primero ORM de Python (Alembic)
16
+ const alembicDetected = (
17
+ existsSync(join(dir, 'alembic.ini')) ||
18
+ (existsSync(join(dir, 'alembic')) && existsSync(join(dir, 'alembic', 'versions')))
19
+ );
20
+ if (alembicDetected) return 'alembic';
21
+
22
+ // Verificar requirements.txt / pyproject.toml para alembic
23
+ const reqPath = join(dir, 'requirements.txt');
24
+ if (existsSync(reqPath)) {
25
+ const content = readFileSync(reqPath, 'utf8').toLowerCase();
26
+ if (content.includes('alembic')) return 'alembic';
27
+ }
28
+ const pyprojectPath = join(dir, 'pyproject.toml');
29
+ if (existsSync(pyprojectPath)) {
30
+ const content = readFileSync(pyprojectPath, 'utf8').toLowerCase();
31
+ if (content.includes('alembic')) return 'alembic';
32
+ }
33
+
34
+ // ORM de Node.js desde package.json
35
+ const pkgPath = join(dir, 'package.json');
36
+ if (!existsSync(pkgPath)) return null;
37
+
38
+ let pkg;
39
+ try {
40
+ pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
41
+ } catch {
42
+ return null;
43
+ }
44
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
45
+
46
+ if (allDeps['drizzle-orm'] || allDeps['drizzle-kit']) return 'drizzle';
47
+ if (allDeps['prisma'] || allDeps['@prisma/client']) return 'prisma';
48
+ if (allDeps['knex']) return 'knex';
49
+ if (allDeps['typeorm']) return 'typeorm';
50
+ if (allDeps['sequelize']) return 'sequelize';
51
+ if (allDeps['mongoose']) return 'mongoose';
52
+ return null;
53
+ }
54
+
55
+ /**
56
+ * Revisa migraciones de Drizzle ORM.
57
+ * @param {string} dir
58
+ * @returns {object}
59
+ */
60
+ function checkDrizzle(dir) {
61
+ const findings = [];
62
+ const info = { orm: 'drizzle', migration_dir: null, schema_files: [], migrations: [] };
63
+
64
+ // Buscar config de Drizzle
65
+ const configNames = ['drizzle.config.ts', 'drizzle.config.js', 'drizzle.config.mjs'];
66
+ let configPath = null;
67
+ for (const name of configNames) {
68
+ const p = join(dir, name);
69
+ if (existsSync(p)) { configPath = p; break; }
70
+ }
71
+
72
+ if (!configPath) {
73
+ findings.push({ severity: 'high', message: 'No se encontró drizzle.config — las migraciones podrían no estar configuradas' });
74
+ } else {
75
+ const config = readFileSync(configPath, 'utf8');
76
+ const outMatch = config.match(/out\s*:\s*['"]([^'"]+)['"]/);
77
+ if (outMatch) info.migration_dir = outMatch[1];
78
+ }
79
+
80
+ // Buscar directorio de migraciones
81
+ const migrationDirs = [info.migration_dir, 'drizzle', 'migrations', 'db/migrations'].filter(Boolean);
82
+ let migDir = null;
83
+ for (const d of migrationDirs) {
84
+ const p = join(dir, d);
85
+ try {
86
+ if (existsSync(p) && statSync(p).isDirectory()) { migDir = p; info.migration_dir = d; break; }
87
+ } catch { /* skip */ }
88
+ }
89
+
90
+ if (migDir) {
91
+ const files = readdirSync(migDir).filter(f => f.endsWith('.sql') || f.endsWith('.ts') || f.endsWith('.js'));
92
+ info.migrations = files.map(f => {
93
+ try {
94
+ const s = statSync(join(migDir, f));
95
+ return { name: f, modified: s.mtime.toISOString().split('T')[0] };
96
+ } catch { return { name: f }; }
97
+ });
98
+ info.migration_count = files.length;
99
+
100
+ // Verificar journal (Drizzle registra migraciones aplicadas)
101
+ const journalPath = join(migDir, 'meta', '_journal.json');
102
+ if (existsSync(journalPath)) {
103
+ try {
104
+ const journal = JSON.parse(readFileSync(journalPath, 'utf8'));
105
+ info.applied_count = journal.entries ? journal.entries.length : 0;
106
+ if (info.migration_count > info.applied_count) {
107
+ findings.push({
108
+ severity: 'critical',
109
+ message: `${info.migration_count - info.applied_count} migración(es) pendiente(s) sin aplicar — ejecutar: npx drizzle-kit push`,
110
+ });
111
+ }
112
+ } catch { /* ignorar */ }
113
+ }
114
+ } else {
115
+ findings.push({ severity: 'medium', message: 'No se encontró directorio de migraciones — ejecutar: npx drizzle-kit generate' });
116
+ }
117
+
118
+ // Buscar archivos de schema
119
+ const schemaPatterns = ['schema.ts', 'schema.js', 'db/schema.ts', 'src/db/schema.ts', 'src/schema.ts'];
120
+ for (const pattern of schemaPatterns) {
121
+ if (existsSync(join(dir, pattern))) info.schema_files.push(pattern);
122
+ }
123
+ const schemaDirs = ['src/db', 'db', 'src/schema'];
124
+ for (const d of schemaDirs) {
125
+ const p = join(dir, d);
126
+ try {
127
+ if (existsSync(p) && statSync(p).isDirectory()) {
128
+ const files = readdirSync(p).filter(f => f.includes('schema') && (f.endsWith('.ts') || f.endsWith('.js')));
129
+ for (const f of files) info.schema_files.push(join(d, f));
130
+ }
131
+ } catch { /* skip */ }
132
+ }
133
+
134
+ if (info.schema_files.length === 0) {
135
+ findings.push({ severity: 'high', message: 'No se encontraron archivos de schema — Drizzle ORM requiere definiciones de schema' });
136
+ }
137
+
138
+ return { ...info, findings };
139
+ }
140
+
141
+ /**
142
+ * Revisa migraciones de Prisma.
143
+ * @param {string} dir
144
+ * @returns {object}
145
+ */
146
+ function checkPrisma(dir) {
147
+ const findings = [];
148
+ const info = { orm: 'prisma', schema_file: null, migrations: [] };
149
+
150
+ const schemaPaths = ['prisma/schema.prisma', 'schema.prisma'];
151
+ for (const p of schemaPaths) {
152
+ if (existsSync(join(dir, p))) { info.schema_file = p; break; }
153
+ }
154
+
155
+ if (!info.schema_file) {
156
+ findings.push({ severity: 'critical', message: 'No se encontró prisma/schema.prisma' });
157
+ return { ...info, findings };
158
+ }
159
+
160
+ const migDir = join(dir, 'prisma/migrations');
161
+ try {
162
+ if (existsSync(migDir) && statSync(migDir).isDirectory()) {
163
+ const dirs = readdirSync(migDir).filter(f => {
164
+ try {
165
+ const p = join(migDir, f);
166
+ return statSync(p).isDirectory() && f !== '_lock';
167
+ } catch { return false; }
168
+ });
169
+ info.migrations = dirs.map(d => ({ name: d }));
170
+ info.migration_count = dirs.length;
171
+ } else {
172
+ findings.push({ severity: 'medium', message: 'No se encontró directorio de migraciones de Prisma — ejecutar: npx prisma migrate dev' });
173
+ }
174
+ } catch { /* skip */ }
175
+
176
+ const nodeModulesPrisma = join(dir, 'node_modules/.prisma/client');
177
+ if (!existsSync(nodeModulesPrisma)) {
178
+ findings.push({ severity: 'high', message: 'Cliente de Prisma no generado — ejecutar: npx prisma generate' });
179
+ }
180
+
181
+ return { ...info, findings };
182
+ }
183
+
184
+ /**
185
+ * Revisa migraciones de Knex.
186
+ * @param {string} dir
187
+ * @returns {object}
188
+ */
189
+ function checkKnex(dir) {
190
+ const findings = [];
191
+ const info = { orm: 'knex', migration_dir: null, migrations: [] };
192
+
193
+ const knexfileNames = ['knexfile.js', 'knexfile.ts', 'knexfile.mjs'];
194
+ let found = false;
195
+ for (const name of knexfileNames) {
196
+ if (existsSync(join(dir, name))) { found = true; break; }
197
+ }
198
+
199
+ if (!found) {
200
+ findings.push({ severity: 'medium', message: 'No se encontró knexfile — la configuración de migraciones podría estar inline' });
201
+ }
202
+
203
+ const migDirs = ['migrations', 'db/migrations', 'src/migrations'];
204
+ for (const d of migDirs) {
205
+ const p = join(dir, d);
206
+ try {
207
+ if (existsSync(p) && statSync(p).isDirectory()) {
208
+ info.migration_dir = d;
209
+ const files = readdirSync(p).filter(f => f.endsWith('.js') || f.endsWith('.ts'));
210
+ info.migrations = files.map(f => ({ name: f }));
211
+ info.migration_count = files.length;
212
+ break;
213
+ }
214
+ } catch { /* skip */ }
215
+ }
216
+
217
+ if (!info.migration_dir) {
218
+ findings.push({ severity: 'medium', message: 'No se encontró directorio de migraciones — ejecutar: npx knex migrate:make initial' });
219
+ }
220
+
221
+ return { ...info, findings };
222
+ }
223
+
224
+ /**
225
+ * Revisa migraciones de Alembic (Python/SQLAlchemy).
226
+ * Detecta mediante alembic.ini, directorio alembic/versions/, requirements.txt o pyproject.toml.
227
+ * Compara revisiones encontradas en archivos contra .alembic_applied.txt (opcional).
228
+ * @param {string} dir
229
+ * @returns {object}
230
+ */
231
+ function checkAlembic(dir) {
232
+ const findings = [];
233
+ const info = {
234
+ orm: 'alembic',
235
+ versions_dir: null,
236
+ revisions_found: [],
237
+ revisions_applied: null,
238
+ pending: [],
239
+ extra_applied: [],
240
+ };
241
+
242
+ // Localizar directorio de versiones
243
+ const versionsDir = join(dir, 'alembic', 'versions');
244
+ if (existsSync(versionsDir)) {
245
+ info.versions_dir = 'alembic/versions';
246
+ }
247
+
248
+ if (!info.versions_dir) {
249
+ findings.push({
250
+ severity: 'medium',
251
+ message: 'No se encontró directorio alembic/versions/ — ejecutar: alembic init alembic',
252
+ });
253
+ return { ...info, findings };
254
+ }
255
+
256
+ // Parsear revision IDs de archivos de migración Python
257
+ let versionFiles = [];
258
+ try {
259
+ versionFiles = readdirSync(versionsDir).filter(f => f.endsWith('.py') && f !== '__init__.py');
260
+ } catch {
261
+ findings.push({ severity: 'high', message: `No se pudo leer el directorio ${info.versions_dir}` });
262
+ return { ...info, findings };
263
+ }
264
+
265
+ const revisionRegex = /revision\s*=\s*['"]([^'"]+)['"]/;
266
+ for (const file of versionFiles) {
267
+ try {
268
+ const content = readFileSync(join(versionsDir, file), 'utf8');
269
+ const match = content.match(revisionRegex);
270
+ if (match) {
271
+ info.revisions_found.push({ revision: match[1], file });
272
+ }
273
+ } catch { /* skip archivos no legibles */ }
274
+ }
275
+
276
+ if (info.revisions_found.length === 0 && versionFiles.length > 0) {
277
+ findings.push({
278
+ severity: 'medium',
279
+ message: `Se encontraron ${versionFiles.length} archivo(s) en alembic/versions/ pero ninguno tiene campo 'revision' — revisar formato`,
280
+ });
281
+ }
282
+
283
+ // Comparar contra .alembic_applied.txt (opcional)
284
+ const appliedPath = join(dir, '.alembic_applied.txt');
285
+ if (existsSync(appliedPath)) {
286
+ try {
287
+ const appliedContent = readFileSync(appliedPath, 'utf8');
288
+ const appliedRevisions = new Set(
289
+ appliedContent.split('\n').map(l => l.trim()).filter(Boolean)
290
+ );
291
+ info.revisions_applied = [...appliedRevisions];
292
+
293
+ const foundRevisions = new Set(info.revisions_found.map(r => r.revision));
294
+
295
+ // Pendientes: en archivos pero no aplicadas
296
+ info.pending = info.revisions_found
297
+ .filter(r => !appliedRevisions.has(r.revision))
298
+ .map(r => r.revision);
299
+
300
+ // Extra: aplicadas pero no en archivos (posible eliminación de migración)
301
+ info.extra_applied = [...appliedRevisions].filter(r => !foundRevisions.has(r));
302
+
303
+ if (info.pending.length > 0) {
304
+ findings.push({
305
+ severity: 'critical',
306
+ message: `${info.pending.length} migración(es) de Alembic pendiente(s) sin aplicar — ejecutar: alembic upgrade head`,
307
+ pending_revisions: info.pending,
308
+ });
309
+ }
310
+
311
+ if (info.extra_applied.length > 0) {
312
+ findings.push({
313
+ severity: 'high',
314
+ message: `${info.extra_applied.length} revisión(es) aplicada(s) no encontradas en archivos — posible eliminación de migración`,
315
+ extra_revisions: info.extra_applied,
316
+ });
317
+ }
318
+ } catch {
319
+ findings.push({ severity: 'low', message: 'No se pudo leer .alembic_applied.txt — sin comparación de estado aplicado' });
320
+ }
321
+ } else {
322
+ // Sin archivo de aplicadas — solo reportar conteo
323
+ if (info.revisions_found.length > 0) {
324
+ findings.push({
325
+ severity: 'info',
326
+ message: `${info.revisions_found.length} revisión(es) de Alembic encontradas. Crear .alembic_applied.txt con IDs aplicados para rastrear estado`,
327
+ });
328
+ }
329
+ }
330
+
331
+ info.revision_count = info.revisions_found.length;
332
+
333
+ return { ...info, findings };
334
+ }
335
+
336
+ function main() {
337
+ const args = process.argv.slice(2);
338
+ const rawDir = args.find(a => !a.startsWith('--'));
339
+ const dir = resolve(rawDir || process.cwd());
340
+
341
+ if (!existsSync(dir)) {
342
+ outputError(`Directorio no encontrado: ${dir}`);
343
+ process.exit(0);
344
+ }
345
+
346
+ const orm = detectOrm(dir);
347
+
348
+ if (!orm) {
349
+ outputJSON({
350
+ success: true,
351
+ packages_scanned: 1,
352
+ orm: null,
353
+ message: 'No se detectó un ORM compatible (Drizzle, Prisma, Knex, Alembic, TypeORM, Sequelize)',
354
+ findings: [],
355
+ });
356
+ process.exit(0);
357
+ }
358
+
359
+ let result;
360
+ switch (orm) {
361
+ case 'drizzle': result = checkDrizzle(dir); break;
362
+ case 'prisma': result = checkPrisma(dir); break;
363
+ case 'knex': result = checkKnex(dir); break;
364
+ case 'alembic': result = checkAlembic(dir); break;
365
+ default:
366
+ result = {
367
+ orm,
368
+ findings: [{
369
+ severity: 'info',
370
+ message: `${orm} detectado pero la verificación de migraciones aún no está implementada para este ORM`,
371
+ }],
372
+ };
373
+ }
374
+
375
+ const allFindings = result.findings || [];
376
+ const deploySafe = allFindings.filter(f => f.severity === 'critical').length === 0;
377
+
378
+ outputJSON({
379
+ success: true,
380
+ packages_scanned: 1,
381
+ deploy_safe: deploySafe,
382
+ orm,
383
+ result,
384
+ findings: allFindings,
385
+ });
386
+ }
387
+
388
+ if (require.main === module) {
389
+ main();
390
+ }
391
+
392
+ module.exports = { detectOrm, checkDrizzle, checkPrisma, checkKnex, checkAlembic };