@saulwade/swl-ses 2.4.1 → 2.4.3

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.
package/scripts/doctor.js CHANGED
@@ -10,7 +10,7 @@
10
10
  const fs = require('fs');
11
11
  const path = require('path');
12
12
 
13
- const { detectarRuntimes, detectarInstalacionesDuales } = require('./lib/detectar-runtime');
13
+ const { detectarRuntimes, detectarInstalacionesDuales, esDirGlobalDeAlgunRuntime, scopesReales } = require('./lib/detectar-runtime');
14
14
  const { cargarEstado, verificarIntegridad } = require('./lib/estado');
15
15
  const { verificarHooks, repararHooks, rutaSettings, cargarHooksConfig, desregistrarHooks, esHookSWL, verificarOptimizaciones, registrarOptimizaciones, validarEstructuraSettings } = require('./lib/hooks-settings');
16
16
  const {
@@ -106,7 +106,10 @@ async function doctor(opciones = {}) {
106
106
  try {
107
107
  const runtimesParaDrift = detectarRuntimes();
108
108
  for (const runtime of runtimesParaDrift) {
109
- for (const dir of [runtime.global, path.resolve(runtime.local)]) {
109
+ // Dedup + guard anti-fantasma: desde HOME, global y local colapsan al
110
+ // mismo dir (reporte doble) o el local resuelve al GLOBAL de otro
111
+ // runtime (drift "proyecto" espurio). Caso real doctor 2026-07-03.
112
+ for (const { dir, esGlobal } of scopesReales(runtime)) {
110
113
  if (!fs.existsSync(dir)) continue;
111
114
  const estado = cargarEstado(dir);
112
115
  if (!estado || !estado.versionSistema) continue;
@@ -115,7 +118,7 @@ async function doctor(opciones = {}) {
115
118
  driftsDetectados.push({
116
119
  runtime: runtime.nombre,
117
120
  runtimeId: runtime.id,
118
- scope: dir === runtime.global ? 'global' : 'proyecto',
121
+ scope: esGlobal ? 'global' : 'proyecto',
119
122
  dir,
120
123
  versionInstalada: estado.versionSistema,
121
124
  perfil: estado.perfil || 'desconocido',
@@ -259,13 +262,10 @@ async function doctor(opciones = {}) {
259
262
 
260
263
  // 5. Verificar estado de instalación por runtime
261
264
  for (const runtime of runtimes) {
262
- // Deduplicar: cuando global y local resuelven al mismo path (ej: running desde home dir)
263
- const dirsRaw = [runtime.global, path.resolve(runtime.local)];
264
- const dirs = [...new Set(dirsRaw)];
265
- for (const dir of dirs) {
265
+ // Deduplicar + descartar locales que resuelven al global de otro runtime
266
+ // (ej: doctor corrido desde el home dir)
267
+ for (const { dir, esGlobal } of scopesReales(runtime)) {
266
268
  if (!fs.existsSync(dir)) continue;
267
-
268
- const esGlobal = dir === runtime.global;
269
269
  const estado = cargarEstado(dir);
270
270
  if (estado) {
271
271
  const { integro, problemas } = verificarIntegridad(estado);
@@ -379,11 +379,7 @@ async function doctor(opciones = {}) {
379
379
  // Sub-fase 12 v1.5.0: deduplicar paths cuando cwd === homedir (runtime.local
380
380
  // y runtime.global colapsan al mismo directorio) — evita reporte doble.
381
381
  for (const runtime of runtimes) {
382
- const dirsUnicos = Array.from(new Set([
383
- path.resolve(runtime.global),
384
- path.resolve(runtime.local),
385
- ]));
386
- for (const dir of dirsUnicos) {
382
+ for (const { dir } of scopesReales(runtime)) {
387
383
  if (!fs.existsSync(dir)) continue;
388
384
  const estado = cargarEstado(dir);
389
385
  if (!estado || !estado.perfil) continue;
@@ -559,12 +555,20 @@ async function doctor(opciones = {}) {
559
555
  for (const runtime of runtimes) {
560
556
  const dir = path.resolve(runtime.local);
561
557
  if (!fs.existsSync(dir)) continue;
558
+ // Local que resuelve al global de OTRO runtime = scope fantasma (ver scopesReales)
559
+ if (esDirGlobalDeAlgunRuntime(dir) && dir !== path.resolve(runtime.global)) continue;
562
560
  const estado = cargarEstado(dir);
563
561
  if (!estado) continue;
564
562
 
565
563
  const settingsPath = rutaSettings(runtime, dir);
566
564
  if (fs.existsSync(settingsPath)) {
567
- const structResult = validarEstructuraSettings(settingsPath);
565
+ // Cursor usa hooks.json con eventos camelCase propios y entradas PLANAS
566
+ // ({command, type}) — el esquema Claude produce falsos errores
567
+ // ("afterFileEdit: evento no reconocido", "[0].hooks debe ser array").
568
+ // Codex también usa hooks.json pero con FORMA Claude ({matcher,
569
+ // hooks:[...]}, eventos PascalCase) — ver transformadores/codex.js.
570
+ const formatoHooks = runtime.id === 'cursor' ? 'plano' : 'claude';
571
+ const structResult = validarEstructuraSettings(settingsPath, { formatoHooks });
568
572
  if (structResult.ok) {
569
573
  console.log(formatearPaso(`Estructura settings ${runtime.nombre}`, 'Formato válido'));
570
574
  ok++;
@@ -624,8 +628,7 @@ async function doctor(opciones = {}) {
624
628
 
625
629
  // 8. Verificar componentes externos
626
630
  for (const runtime of runtimes) {
627
- const dirs = [runtime.global, path.resolve(runtime.local)];
628
- for (const dir of dirs) {
631
+ for (const { dir } of scopesReales(runtime)) {
629
632
  if (!fs.existsSync(dir)) continue;
630
633
  const estado = cargarEstado(dir);
631
634
  if (estado && estado.componentesExternos && estado.componentesExternos.length > 0) {
@@ -712,6 +715,11 @@ async function doctor(opciones = {}) {
712
715
  } else {
713
716
  console.log(` ${reparados} reparado(s), ${color.rojo(`${fallos} fallo(s)`)}.`);
714
717
  }
718
+ // Las reparaciones no se re-verifican en esta corrida: honestidad sobre
719
+ // el alcance (caso repair-loop 2026-07-03 — un falso positivo del check
720
+ // se "reparaba" y reaparecía indefinidamente).
721
+ console.log(` ${color.dim('Re-ejecuta `doctor` para confirmar. Si el MISMO problema reaparece tras reparar,')}`);
722
+ console.log(` ${color.dim('es un falso positivo del check (repórtalo) — no falta de reparación.')}`);
715
723
  } else {
716
724
  console.log(` ${color.dim('Reparación cancelada. Usa --force para reparar sin confirmar.')}`);
717
725
  }
@@ -151,6 +151,48 @@ const RUNTIMES = {
151
151
  },
152
152
  };
153
153
 
154
+ /**
155
+ * ¿El directorio dado es el dir GLOBAL de alguno de los runtimes conocidos?
156
+ *
157
+ * Un dir global jamás debe interpretarse como instalación "de proyecto" de
158
+ * otro runtime: con cwd en el HOME del usuario, todos los `runtime.local`
159
+ * relativos (.claude, .cursor, .codex, …) resuelven dentro del HOME y
160
+ * colisionan con los globales — el caso más dañino es OpenClaude, cuyo
161
+ * local `.claude` colisiona con el global de Claude Code.
162
+ *
163
+ * @param {string} dir - Ruta absoluta o relativa a evaluar.
164
+ * @returns {boolean}
165
+ */
166
+ function esDirGlobalDeAlgunRuntime(dir) {
167
+ const objetivo = path.resolve(dir);
168
+ for (const config of Object.values(RUNTIMES)) {
169
+ if (path.resolve(config.global) === objetivo) return true;
170
+ }
171
+ return false;
172
+ }
173
+
174
+ /**
175
+ * Scopes REALES de un runtime: [global, proyecto] deduplicados y sin
176
+ * fantasmas. Con cwd en el HOME, el local relativo (.claude/.cursor/.codex)
177
+ * resuelve al dir GLOBAL propio (duplicado) o al de OTRO runtime (scope
178
+ * "proyecto" espurio — p.ej. el local de OpenClaude colisiona con el global
179
+ * de Claude Code, y un uninstall de ese "proyecto" borraría el global).
180
+ *
181
+ * Consumidores: doctor, actualizar, TUI (inspect/uninstall/update/welcome).
182
+ *
183
+ * @param {object} runtime - Config de RUNTIMES (con .global y .local).
184
+ * @returns {Array<{dir: string, esGlobal: boolean}>}
185
+ */
186
+ function scopesReales(runtime) {
187
+ const globalAbs = path.resolve(runtime.global);
188
+ const localAbs = path.resolve(runtime.local);
189
+ const scopes = [{ dir: globalAbs, esGlobal: true }];
190
+ if (localAbs !== globalAbs && !esDirGlobalDeAlgunRuntime(localAbs)) {
191
+ scopes.push({ dir: localAbs, esGlobal: false });
192
+ }
193
+ return scopes;
194
+ }
195
+
154
196
  /**
155
197
  * Detecta qué runtimes están instalados en el sistema
156
198
  */
@@ -174,6 +216,13 @@ function detectarRuntimes() {
174
216
  // Si este runtime comparte su directorio local con otro (ej: openclaude comparte .claude/ con claude),
175
217
  // solo considerarlo instalado localmente si el estado de instalación declara explícitamente este target.
176
218
  let localEfectivo = localExiste;
219
+
220
+ // Guard universal: el dir global de un runtime NUNCA es una instalación de
221
+ // proyecto. Con cwd en el HOME, `<cwd>/.claude` resuelve al GLOBAL de
222
+ // Claude Code y la detección lo trataba como "proyecto" de OpenClaude —
223
+ // produciendo falso "instalación duplicada", 47 hooks "faltantes" y un
224
+ // repair-loop (caso real doctor 2026-07-03).
225
+ if (esDirGlobalDeAlgunRuntime(localAbs)) localEfectivo = false;
177
226
  const comparte = (localUsadoPor[localAbs] || []).length > 1;
178
227
  if (comparte && localExiste && !globalExiste) {
179
228
  // Revisar el estado de instalación para ver si el target coincide
@@ -293,6 +342,13 @@ function detectarInstalacionesDuales(runtimeId, opciones = {}) {
293
342
  return { hayConflicto: false, global: false, local: false, globalDir, localDir };
294
343
  }
295
344
 
345
+ // El dir global de CUALQUIER runtime no puede ser el lado "proyecto" del
346
+ // conflicto: con cwd en HOME, el local de OpenClaude (.claude) resuelve al
347
+ // global de Claude Code y se reportaba "duplicado global+proyecto" espurio.
348
+ if (esDirGlobalDeAlgunRuntime(localDir)) {
349
+ return { hayConflicto: false, global: Boolean(require('./estado').cargarEstado(globalDir)), local: false, globalDir, localDir };
350
+ }
351
+
296
352
  const estadoGlobal = cargarEstado(globalDir);
297
353
  const estadoLocal = cargarEstado(localDir);
298
354
 
@@ -322,21 +378,32 @@ function detectarInstalacionesDuales(runtimeId, opciones = {}) {
322
378
  *
323
379
  * @returns {string[]} Lista de runtime IDs ordenada de "más usado" a "menos usado".
324
380
  */
325
- function listarRuntimesInstalables() {
326
- return [
381
+ function listarRuntimesInstalables(opciones = {}) {
382
+ const existeDir = opciones.existeDir || fs.existsSync;
383
+ const base = [
327
384
  'claude', // Soporte completo, primer ciudadano
328
385
  'cursor', // Soporte parcial — reglas + MCP
329
386
  'codex', // Soporte parcial — AGENTS.md + MCP (v1.5.0+)
330
387
  'opencode', // Soporte completo
331
388
  'gemini', // Soporte completo
332
389
  'copilot', // Soporte parcial — agentes consolidados
333
- // 'openclaude' intencionalmente excluido — comparte dir con claude
334
390
  ];
391
+ // OpenClaude comparte el dir de PROYECTO (.claude/) con Claude Code, así
392
+ // que NO se bootstrapea por default (evita duplicados para quien no lo
393
+ // usa). Pero su GLOBAL (~/.openclaude) es un dir propio: si YA existe (el
394
+ // usuario lo instaló alguna vez), --all-runtimes DEBE actualizarlo —
395
+ // excluirlo incondicionalmente dejaba un drift de versión permanente que
396
+ // ningún reinstall masivo cerraba (caso real doctor 2026-07-03: todo el
397
+ // parque en 2.4.2 y ~/.openclaude clavado en 2.4.1 pese a --all-runtimes).
398
+ if (existeDir(RUNTIMES.openclaude.global)) base.splice(1, 0, 'openclaude');
399
+ return base;
335
400
  }
336
401
 
337
402
  module.exports = {
338
403
  RUNTIMES,
339
404
  detectarRuntimes,
405
+ esDirGlobalDeAlgunRuntime,
406
+ scopesReales,
340
407
  detectarInstalacionesDuales,
341
408
  obtenerRuntime,
342
409
  calcularRutas,
@@ -689,18 +689,55 @@ function registrarOptimizaciones(settingsPath) {
689
689
  * hooks con formato válido. No valida contenido semántico, solo estructura.
690
690
  *
691
691
  * @param {string} settingsPath
692
+ * @param {object} [opts]
693
+ * @param {'claude'|'plano'} [opts.formatoHooks='claude'] - 'claude' valida el
694
+ * esquema de Claude Code ({matcher, hooks:[{type,command}]}, eventos
695
+ * PascalCase). 'plano' valida hooks.json de Cursor/Codex: entradas planas
696
+ * ({command, type?}) bajo eventos camelCase PROPIOS del runtime — los
697
+ * nombres de evento NO se validan contra whitelist porque cada runtime
698
+ * define su set y lo amplía por versión (afterFileEdit,
699
+ * beforeShellExecution, etc. son legítimos en Cursor; el esquema Claude
700
+ * los marcaba como error — caso real doctor 2026-07-03).
692
701
  * @returns {{ ok: boolean, problemas: string[] }}
693
702
  */
694
- function validarEstructuraSettings(settingsPath) {
703
+ function validarEstructuraSettings(settingsPath, opts = {}) {
704
+ const formatoHooks = opts.formatoHooks || 'claude';
695
705
  const settings = leerSettings(settingsPath);
696
706
  const problemas = [];
697
707
 
698
- // Validar sección hooks
699
- if (settings.hooks) {
708
+ // Formato plano (Cursor/Codex hooks.json): shape-only, sin whitelist de eventos.
709
+ if (settings.hooks && formatoHooks === 'plano') {
710
+ if (typeof settings.hooks !== 'object' || Array.isArray(settings.hooks)) {
711
+ problemas.push('hooks: debe ser un objeto { evento: [entradas] }');
712
+ } else {
713
+ for (const [evento, entradas] of Object.entries(settings.hooks)) {
714
+ if (!Array.isArray(entradas)) {
715
+ problemas.push(`hooks.${evento}: debe ser un array de entradas`);
716
+ continue;
717
+ }
718
+ for (let i = 0; i < entradas.length; i++) {
719
+ const entrada = entradas[i];
720
+ if (!entrada || typeof entrada !== 'object') {
721
+ problemas.push(`hooks.${evento}[${i}]: debe ser un objeto`);
722
+ continue;
723
+ }
724
+ if (typeof entrada.command !== 'string' || !entrada.command) {
725
+ problemas.push(`hooks.${evento}[${i}]: falta campo command (string)`);
726
+ }
727
+ }
728
+ }
729
+ }
730
+ }
731
+
732
+ // Validar sección hooks (esquema Claude Code)
733
+ if (settings.hooks && formatoHooks === 'claude') {
700
734
  const eventosValidos = new Set([
701
735
  'PreToolUse', 'PostToolUse', 'UserPromptSubmit', 'Stop',
702
736
  'SubagentStart', 'SubagentStop', 'PreCompact', 'PostCompact',
703
737
  'Notification', 'SessionStart', 'TaskCompleted',
738
+ // Codex CLI usa la forma Claude en su hooks.json pero agrega este evento
739
+ // propio (ver transformadores/codex.js EVENTOS_VALIDOS).
740
+ 'PermissionRequest',
704
741
  ]);
705
742
 
706
743
  for (const [evento, entradas] of Object.entries(settings.hooks)) {
@@ -1,173 +1,175 @@
1
- 'use strict';
2
-
3
- /**
4
- * Pantalla Inspect — navegador read-only de componentes instalados.
5
- *
6
- * Flujo:
7
- * 1. Lista de instalaciones detectadas (runtime + scope + perfil + version)
8
- * 2. Al seleccionar una, muestra detalles:
9
- * - Componentes por categoría (con conteos)
10
- * - Última actualización
11
- * - Lista de hooks registrados
12
- * - Lista de skills disponibles
13
- *
14
- * No modifica nada. Solo lee de los archivos de estado.
15
- */
16
-
17
- const fs = require('fs');
18
- const path = require('path');
19
-
20
- const { selectorUnico } = require('../componentes/selector-unico');
21
- const render = require('../lib/render');
22
- const teclas = require('../lib/teclas');
23
- const { colores, semantico, iconos } = require('../lib/colores');
24
-
25
- function _cargarDatosInstalaciones() {
26
- let detectarRuntimes, cargarEstado;
27
- try {
28
- ({ detectarRuntimes } = require('../../lib/detectar-runtime'));
29
- ({ cargarEstado } = require('../../lib/estado'));
30
- } catch (_) {
31
- return [];
32
- }
33
-
34
- const runtimes = detectarRuntimes();
35
- const filas = [];
36
- for (const runtime of runtimes) {
37
- const candidatos = [
38
- { ruta: runtime.global, scope: 'global' },
39
- { ruta: path.resolve(runtime.local), scope: 'proyecto' },
40
- ];
41
- for (const { ruta, scope } of candidatos) {
42
- if (!fs.existsSync(ruta)) continue;
43
- const estado = cargarEstado(ruta);
44
- if (!estado) continue;
45
- filas.push({
46
- id: `${runtime.id}:${scope}`,
47
- runtimeId: runtime.id,
48
- runtimeNombre: runtime.nombre,
49
- scope,
50
- ruta,
51
- version: estado.versionSistema || 'desconocida',
52
- perfil: estado.perfil || '-',
53
- instalado: estado.fechaInstalacion || estado.timestamp || '-',
54
- componentes: estado.componentesInstalados || [],
55
- archivos: estado.archivosInstalados || [],
56
- });
57
- }
58
- }
59
- return filas;
60
- }
61
-
62
- function _agruparPorCategoria(archivos) {
63
- const grupos = {};
64
- for (const a of archivos) {
65
- const cat = a.tipo || a.categoria || 'otros';
66
- grupos[cat] = (grupos[cat] || 0) + 1;
67
- }
68
- return grupos;
69
- }
70
-
71
- function _pantallaDetalle(fila) {
72
- return new Promise((resolve) => {
73
- if (!render.ES_TTY || !process.stdin.isTTY) {
74
- resolve();
75
- return;
76
- }
77
-
78
- function _renderizar() {
79
- render.limpiarPantalla();
80
- const { cols, rows } = render.obtenerDimensiones();
81
-
82
- render.escribirEn(2, 3, semantico.titulo(`${fila.runtimeNombre} ${fila.scope}`));
83
- render.escribirEn(3, 3, colores.dim(fila.ruta));
84
-
85
- const datos = [
86
- ['Versión', colores.cyan('v' + fila.version)],
87
- ['Perfil', semantico.enfasis(fila.perfil)],
88
- ['Instalado', fila.instalado],
89
- ['Total componentes', String(fila.componentes.length)],
90
- ['Total archivos', String(fila.archivos.length)],
91
- ];
92
-
93
- datos.forEach((d, i) => {
94
- render.escribirEn(5 + i, 5,
95
- render.rellenarDer(colores.dim(d[0] + ':'), 22) + d[1]);
96
- });
97
-
98
- // Conteos por categoría
99
- const grupos = _agruparPorCategoria(fila.archivos);
100
- const categorias = Object.entries(grupos).sort(([a], [b]) => a.localeCompare(b));
101
-
102
- const filaCat = 5 + datos.length + 2;
103
- render.escribirEn(filaCat, 3, semantico.enfasis('Archivos por categoría:'));
104
- categorias.forEach(([cat, n], i) => {
105
- const fila = filaCat + 1 + i;
106
- if (fila >= rows - 3) return;
107
- render.escribirEn(fila, 5,
108
- render.rellenarDer(`${iconos.punto} ${cat}`, 22) +
109
- colores.cyan(String(n).padStart(4)));
110
- });
111
-
112
- render.dibujarPiePagina([
113
- ['Enter|Esc', 'volver al listado'],
114
- ]);
115
- }
116
-
117
- render.iniciarModoTui();
118
- _renderizar();
119
-
120
- const onResize = () => _renderizar();
121
- process.stdout.on('resize', onResize);
122
-
123
- const teclado = teclas.crearTeclado();
124
- function _finalizar() {
125
- teclado.desactivar();
126
- process.stdout.removeListener('resize', onResize);
127
- render.salirModoTui();
128
- resolve();
129
- }
130
- teclado.on('return', _finalizar);
131
- teclado.on('escape', _finalizar);
132
- teclado.activar();
133
- });
134
- }
135
-
136
- async function ejecutarInspect() {
137
- const instalaciones = _cargarDatosInstalaciones();
138
-
139
- if (instalaciones.length === 0) {
140
- return {
141
- exito: false,
142
- error: 'No se detectaron instalaciones SWL en este equipo.',
143
- sugerencia: 'Ejecuta swl-ses install para crear una.',
144
- };
145
- }
146
-
147
- // Loop: seleccionar una instalación → ver detalle → volver al listado.
148
- // Esc en el listado sale del Inspect.
149
- while (true) {
150
- const items = instalaciones.map(i => ({
151
- valor: i.id,
152
- etiqueta: `${i.runtimeNombre} (${i.scope}) v${i.version} · perfil ${i.perfil}`,
153
- descripcion: `${i.componentes.length} componentes · ${i.archivos.length} archivos · ${i.ruta}`,
154
- }));
155
-
156
- const elegida = await selectorUnico({
157
- titulo: 'Inspect — Elige una instalación para ver detalle:',
158
- items,
159
- });
160
- if (!elegida) break;
161
-
162
- const fila = instalaciones.find(i => i.id === elegida);
163
- if (fila) await _pantallaDetalle(fila);
164
- }
165
-
166
- return { exito: true };
167
- }
168
-
169
- module.exports = {
170
- ejecutarInspect,
171
- _cargarDatosInstalaciones,
172
- _agruparPorCategoria,
173
- };
1
+ 'use strict';
2
+
3
+ /**
4
+ * Pantalla Inspect — navegador read-only de componentes instalados.
5
+ *
6
+ * Flujo:
7
+ * 1. Lista de instalaciones detectadas (runtime + scope + perfil + version)
8
+ * 2. Al seleccionar una, muestra detalles:
9
+ * - Componentes por categoría (con conteos)
10
+ * - Última actualización
11
+ * - Lista de hooks registrados
12
+ * - Lista de skills disponibles
13
+ *
14
+ * No modifica nada. Solo lee de los archivos de estado.
15
+ */
16
+
17
+ const fs = require('fs');
18
+ const path = require('path');
19
+
20
+ const { selectorUnico } = require('../componentes/selector-unico');
21
+ const render = require('../lib/render');
22
+ const teclas = require('../lib/teclas');
23
+ const { colores, semantico, iconos } = require('../lib/colores');
24
+
25
+ function _cargarDatosInstalaciones() {
26
+ let detectarRuntimes, cargarEstado;
27
+ try {
28
+ ({ detectarRuntimes, scopesReales } = require('../../lib/detectar-runtime'));
29
+ ({ cargarEstado } = require('../../lib/estado'));
30
+ } catch (_) {
31
+ return [];
32
+ }
33
+
34
+ const runtimes = detectarRuntimes();
35
+ const filas = [];
36
+ for (const runtime of runtimes) {
37
+ // Dedup + guard anti-fantasma: desde HOME, el local relativo resuelve al
38
+ // global propio (duplicado) o al de OTRO runtime (p.ej. .claude de
39
+ // OpenClaude = global de Claude Code) ver scopesReales().
40
+ const candidatos = scopesReales(runtime).map(({ dir, esGlobal }) => (
41
+ { ruta: dir, scope: esGlobal ? 'global' : 'proyecto' }
42
+ ));
43
+ for (const { ruta, scope } of candidatos) {
44
+ if (!fs.existsSync(ruta)) continue;
45
+ const estado = cargarEstado(ruta);
46
+ if (!estado) continue;
47
+ filas.push({
48
+ id: `${runtime.id}:${scope}`,
49
+ runtimeId: runtime.id,
50
+ runtimeNombre: runtime.nombre,
51
+ scope,
52
+ ruta,
53
+ version: estado.versionSistema || 'desconocida',
54
+ perfil: estado.perfil || '-',
55
+ instalado: estado.fechaInstalacion || estado.timestamp || '-',
56
+ componentes: estado.componentesInstalados || [],
57
+ archivos: estado.archivosInstalados || [],
58
+ });
59
+ }
60
+ }
61
+ return filas;
62
+ }
63
+
64
+ function _agruparPorCategoria(archivos) {
65
+ const grupos = {};
66
+ for (const a of archivos) {
67
+ const cat = a.tipo || a.categoria || 'otros';
68
+ grupos[cat] = (grupos[cat] || 0) + 1;
69
+ }
70
+ return grupos;
71
+ }
72
+
73
+ function _pantallaDetalle(fila) {
74
+ return new Promise((resolve) => {
75
+ if (!render.ES_TTY || !process.stdin.isTTY) {
76
+ resolve();
77
+ return;
78
+ }
79
+
80
+ function _renderizar() {
81
+ render.limpiarPantalla();
82
+ const { cols, rows } = render.obtenerDimensiones();
83
+
84
+ render.escribirEn(2, 3, semantico.titulo(`${fila.runtimeNombre} — ${fila.scope}`));
85
+ render.escribirEn(3, 3, colores.dim(fila.ruta));
86
+
87
+ const datos = [
88
+ ['Versión', colores.cyan('v' + fila.version)],
89
+ ['Perfil', semantico.enfasis(fila.perfil)],
90
+ ['Instalado', fila.instalado],
91
+ ['Total componentes', String(fila.componentes.length)],
92
+ ['Total archivos', String(fila.archivos.length)],
93
+ ];
94
+
95
+ datos.forEach((d, i) => {
96
+ render.escribirEn(5 + i, 5,
97
+ render.rellenarDer(colores.dim(d[0] + ':'), 22) + d[1]);
98
+ });
99
+
100
+ // Conteos por categoría
101
+ const grupos = _agruparPorCategoria(fila.archivos);
102
+ const categorias = Object.entries(grupos).sort(([a], [b]) => a.localeCompare(b));
103
+
104
+ const filaCat = 5 + datos.length + 2;
105
+ render.escribirEn(filaCat, 3, semantico.enfasis('Archivos por categoría:'));
106
+ categorias.forEach(([cat, n], i) => {
107
+ const fila = filaCat + 1 + i;
108
+ if (fila >= rows - 3) return;
109
+ render.escribirEn(fila, 5,
110
+ render.rellenarDer(`${iconos.punto} ${cat}`, 22) +
111
+ colores.cyan(String(n).padStart(4)));
112
+ });
113
+
114
+ render.dibujarPiePagina([
115
+ ['Enter|Esc', 'volver al listado'],
116
+ ]);
117
+ }
118
+
119
+ render.iniciarModoTui();
120
+ _renderizar();
121
+
122
+ const onResize = () => _renderizar();
123
+ process.stdout.on('resize', onResize);
124
+
125
+ const teclado = teclas.crearTeclado();
126
+ function _finalizar() {
127
+ teclado.desactivar();
128
+ process.stdout.removeListener('resize', onResize);
129
+ render.salirModoTui();
130
+ resolve();
131
+ }
132
+ teclado.on('return', _finalizar);
133
+ teclado.on('escape', _finalizar);
134
+ teclado.activar();
135
+ });
136
+ }
137
+
138
+ async function ejecutarInspect() {
139
+ const instalaciones = _cargarDatosInstalaciones();
140
+
141
+ if (instalaciones.length === 0) {
142
+ return {
143
+ exito: false,
144
+ error: 'No se detectaron instalaciones SWL en este equipo.',
145
+ sugerencia: 'Ejecuta swl-ses install para crear una.',
146
+ };
147
+ }
148
+
149
+ // Loop: seleccionar una instalación → ver detalle → volver al listado.
150
+ // Esc en el listado sale del Inspect.
151
+ while (true) {
152
+ const items = instalaciones.map(i => ({
153
+ valor: i.id,
154
+ etiqueta: `${i.runtimeNombre} (${i.scope}) — v${i.version} · perfil ${i.perfil}`,
155
+ descripcion: `${i.componentes.length} componentes · ${i.archivos.length} archivos · ${i.ruta}`,
156
+ }));
157
+
158
+ const elegida = await selectorUnico({
159
+ titulo: 'Inspect — Elige una instalación para ver detalle:',
160
+ items,
161
+ });
162
+ if (!elegida) break;
163
+
164
+ const fila = instalaciones.find(i => i.id === elegida);
165
+ if (fila) await _pantallaDetalle(fila);
166
+ }
167
+
168
+ return { exito: true };
169
+ }
170
+
171
+ module.exports = {
172
+ ejecutarInspect,
173
+ _cargarDatosInstalaciones,
174
+ _agruparPorCategoria,
175
+ };