@saulwade/swl-ses 2.5.3 → 2.6.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.
- package/CLAUDE.md +9 -9
- package/README.md +37 -37
- package/agentes/_intent-spec.md +73 -73
- package/agentes/_propose-step.md +90 -90
- package/agentes/accesibilidad-wcag-swl.md +690 -690
- package/agentes/arquitecto-swl.md +267 -267
- package/agentes/auto-evolucion-swl.md +932 -908
- package/agentes/backend-csharp-swl.md +420 -420
- package/agentes/backend-go-swl.md +390 -390
- package/agentes/backend-java-swl.md +281 -281
- package/agentes/backend-rust-swl.md +364 -364
- package/agentes/backend-workers-swl.md +482 -482
- package/agentes/cloud-infra-swl.md +509 -509
- package/agentes/consolidador-swl.md +541 -541
- package/agentes/depurador-swl.md +352 -352
- package/agentes/devops-ci-swl.md +400 -400
- package/agentes/disenador-ui-swl.md +569 -569
- package/agentes/documentador-swl.md +345 -345
- package/agentes/frontend-angular-swl.md +621 -621
- package/agentes/frontend-css-swl.md +716 -716
- package/agentes/frontend-react-swl.md +692 -692
- package/agentes/frontend-swl.md +496 -496
- package/agentes/frontend-tailwind-swl.md +826 -826
- package/agentes/investigador-swl.md +432 -432
- package/agentes/investigador-ux-swl.md +505 -505
- package/agentes/migrador-swl.md +442 -442
- package/agentes/mobile-android-swl.md +511 -511
- package/agentes/mobile-cross-swl.md +541 -541
- package/agentes/mobile-ios-swl.md +502 -502
- package/agentes/mobile-testing-swl.md +302 -302
- package/agentes/nemesis-auditor-swl.md +285 -285
- package/agentes/observabilidad-swl.md +438 -438
- package/agentes/pagos-swl.md +310 -310
- package/agentes/perfilador-usuario-swl.md +321 -321
- package/agentes/planificador-swl.md +399 -399
- package/agentes/producto-prd-swl.md +589 -589
- package/agentes/red-team-swl.md +218 -218
- package/agentes/release-manager-swl.md +590 -590
- package/agentes/rendimiento-swl.md +713 -713
- package/agentes/revisor-angular-swl.md +278 -278
- package/agentes/revisor-csharp-swl.md +264 -264
- package/agentes/revisor-go-swl.md +259 -259
- package/agentes/revisor-java-swl.md +257 -257
- package/agentes/revisor-kotlin-swl.md +273 -273
- package/agentes/revisor-nextjs-swl.md +281 -281
- package/agentes/revisor-php-swl.md +271 -271
- package/agentes/revisor-react-swl.md +278 -278
- package/agentes/revisor-rust-swl.md +346 -346
- package/agentes/revisor-seguridad-swl.md +399 -399
- package/agentes/revisor-swift-swl.md +268 -268
- package/agentes/revisor-typescript-swl.md +346 -346
- package/agentes/tdd-qa-swl.md +393 -393
- package/bin/swl-ses.js +32 -7
- package/comandos/swl/actualizar.md +3 -3
- package/comandos/swl/aprender.md +13 -0
- package/comandos/swl/deuda-codigo.md +97 -97
- package/comandos/swl/evaluar-skill.md +18 -3
- package/comandos/swl/evolucion-continua.md +73 -0
- package/comandos/swl/evolucionar.md +13 -0
- package/comandos/swl/instalar.md +4 -4
- package/comandos/swl/notificaciones.md +1 -1
- package/comandos/swl/status.md +2 -2
- package/gateway/cron/jobs.example.json +12 -0
- package/habilidades/auto-evolucion-protocolo/SKILL.md +19 -1
- package/habilidades/autoresearch/SKILL.md +3 -2
- package/habilidades/backend-async-postgres-testing/SKILL.md +2 -1
- package/habilidades/benchmark-memoria/SKILL.md +7 -7
- package/habilidades/changelog-generator/SKILL.md +1 -1
- package/habilidades/changelog-generator/scripts/parse-commits.js +2 -1
- package/habilidades/checkpoints-verificacion/SKILL.md +6 -0
- package/habilidades/compactacion-contexto/SKILL.md +2 -1
- package/habilidades/contenedores-docker/SKILL.md +4 -2
- package/habilidades/context-builder/SKILL.md +4 -0
- package/habilidades/doubt-driven-review/SKILL.md +17 -1
- package/habilidades/drift-detection/SKILL.md +6 -1
- package/habilidades/ejecutar-fase/SKILL.md +6 -6
- package/habilidades/ejecutar-task-iterativo/SKILL.md +278 -278
- package/habilidades/eval-framework/SKILL.md +8 -3
- package/habilidades/extractor-de-aprendizajes/SKILL.md +8 -2
- package/habilidades/git-worktrees-paralelo/SKILL.md +19 -1
- package/habilidades/harness-claude-code/SKILL.md +7 -3
- package/habilidades/infra-github-actions/SKILL.md +4 -3
- package/habilidades/instalar-sistema/SKILL.md +5 -1
- package/habilidades/memoria-busqueda/SKILL.md +31 -39
- package/habilidades/planear-fase/SKILL.md +9 -1
- package/habilidades/prevencion-sobreingenieria/recursos/soluciones-nativas.md +166 -166
- package/habilidades/prevencion-sobreingenieria/recursos/variables-residuales-post-refactor.md +85 -85
- package/habilidades/proceso-ddia-fundamentos/SKILL.md +3 -2
- package/habilidades/proceso-ingenieria-requerimientos/SKILL.md +147 -147
- package/habilidades/release-semver/SKILL.md +2 -2
- package/habilidades/swl-claudemd/SKILL.md +6 -7
- package/habilidades/swl-dashboard/SKILL.md +11 -43
- package/habilidades/tdd-workflow/SKILL.md +12 -7
- package/habilidades/validacion-ci-sistema/SKILL.md +1 -1
- package/hooks/agente-lifecycle.js +2 -1
- package/hooks/aiisms-detector.js +13 -4
- package/hooks/audit-trail.js +2 -1
- package/hooks/auto-consolidacion.js +2 -1
- package/hooks/captura-acciones-post.js +2 -1
- package/hooks/captura-acciones-session.js +2 -1
- package/hooks/captura-feedback-usuario.js +3 -2
- package/hooks/claudemd-bloat-detector.js +12 -3
- package/hooks/claudemd-duplicacion-detector.js +13 -3
- package/hooks/contexto-iteracion.js +2 -1
- package/hooks/contexto-subagente.js +68 -68
- package/hooks/degradacion-instintos.js +2 -1
- package/hooks/extraccion-aprendizajes.js +109 -15
- package/hooks/grafo-contexto.js +2 -1
- package/hooks/guardrail-modelo.js +2 -1
- package/hooks/inbox-aviso.js +2 -1
- package/hooks/inyeccion-contexto.js +2 -1
- package/hooks/lib/agent-matcher.js +2 -1
- package/hooks/lib/agent-routing.js +2 -1
- package/hooks/lib/autonomia.js +5 -3
- package/hooks/lib/captura-acciones.js +2 -1
- package/hooks/lib/consolidation-lock.js +21 -10
- package/hooks/lib/etapa-auto-evolucion.js +10 -4
- package/hooks/lib/etapa-metricas.js +2 -1
- package/hooks/lib/etapa-perfil-usuario.js +20 -4
- package/hooks/lib/evolution-tracker.js +2 -1
- package/hooks/lib/gateway-notify.js +17 -3
- package/hooks/lib/loop-telemetry.js +5 -4
- package/hooks/lib/mcp-health.js +2 -1
- package/hooks/lib/memory-search.js +4 -0
- package/hooks/lib/merkle-audit.js +58 -6
- package/hooks/lib/notificacion-formato.js +58 -0
- package/hooks/lib/nudge-tracker.js +2 -1
- package/hooks/lib/otlp-exporter.js +2 -1
- package/hooks/lib/propose-step.js +3 -2
- package/hooks/lib/raiz-proyecto.js +127 -0
- package/hooks/lib/run-log.js +2 -1
- package/hooks/lib/singleton-guard.js +225 -27
- package/hooks/lib/telegram-cliente.js +28 -11
- package/hooks/notificacion-telegram.js +13 -3
- package/hooks/preservar-estado-pre-compact.js +2 -1
- package/hooks/proteccion-rutas.js +59 -3
- package/hooks/registro-turnos.js +2 -1
- package/hooks/resumen-sesion.js +2 -1
- package/hooks/risk-scoring.js +2 -1
- package/hooks/rotar-audit-auto.js +46 -20
- package/hooks/session-briefing.js +127 -1
- package/hooks/spec-gate.js +2 -1
- package/hooks/sugerir-contribuir.js +6 -3
- package/hooks/sugerir-regenerar-inventario.js +3 -2
- package/hooks/tdd-gate.js +2 -1
- package/hooks/telemetria-agentes.js +2 -1
- package/hooks/telemetria-skill-routing.js +2 -1
- package/hooks/tracking-costos.js +4 -3
- package/hooks/validar-formato-post-subagente.js +2 -1
- package/hooks/validar-intent-spec.js +2 -1
- package/hooks/validar-memoria-hook.js +13 -3
- package/hooks/validar-planning-paths.js +2 -1
- package/instintos/perfil-usuario.yaml +506 -3
- package/instintos/proyecto.yaml +78 -0
- package/llms.txt +29 -29
- package/manifiestos/canonical-hashes.json +5588 -4925
- package/manifiestos/hooks-config.json +469 -469
- package/manifiestos/invariantes-criticos.json +30 -30
- package/manifiestos/modulos.json +1429 -1423
- package/manifiestos/planning-paths.json +1 -0
- package/manifiestos/skills-lock.json +1275 -1275
- package/package.json +94 -95
- package/plugin.json +369 -369
- package/scripts/actualizar.js +3 -0
- package/scripts/auditar-clases-conocidas.js +134 -106
- package/scripts/benchmark-memoria.js +1 -0
- package/scripts/bootstrap-instintos.js +85 -14
- package/scripts/canario-hooks.js +166 -166
- package/scripts/cli/autonomia.js +23 -0
- package/scripts/cli/benchmark-memoria.js +37 -0
- package/scripts/cli/ciclo-autonomo.js +73 -0
- package/scripts/cli/ciclo-fase-b.js +102 -0
- package/scripts/cli/guardrail-metrics.js +39 -0
- package/scripts/cli/loop-telemetry.js +4 -2
- package/scripts/cli/memoria-search.js +69 -0
- package/scripts/cli/nudge-accionar.js +39 -0
- package/scripts/cli/run-eval.js +38 -0
- package/scripts/cli/run-skill-evals.js +13 -2
- package/scripts/derivar-feature-list.js +15 -14
- package/scripts/desinstalar.js +11 -0
- package/scripts/doctor.js +50 -13
- package/scripts/evidencia-valor.js +101 -101
- package/scripts/field-report.js +16 -16
- package/scripts/instalador.js +98 -7
- package/scripts/lib/activar-hooks-proyecto.js +116 -104
- package/scripts/lib/auditar-invocaciones-comandos.js +96 -6
- package/scripts/lib/ciclo-autonomo/candidatos.js +174 -0
- package/scripts/lib/ciclo-autonomo/config.js +165 -0
- package/scripts/lib/ciclo-autonomo/drenador-feedback.js +174 -0
- package/scripts/lib/ciclo-autonomo/fallback.js +77 -0
- package/scripts/lib/ciclo-autonomo/guard-convivencia.js +139 -0
- package/scripts/lib/ciclo-autonomo/higiene-nudges.js +112 -0
- package/scripts/lib/ciclo-autonomo/index.js +301 -0
- package/scripts/lib/ciclo-autonomo/lock.js +124 -0
- package/scripts/lib/ciclo-autonomo/presupuesto.js +122 -0
- package/scripts/lib/ciclo-autonomo/puente-degradacion.js +240 -0
- package/scripts/lib/ciclo-autonomo/runner-fase-b.js +248 -0
- package/scripts/lib/ciclo-autonomo/writer-instintos.js +190 -0
- package/scripts/lib/ciclo-autonomo/yaml-instintos.js +535 -0
- package/scripts/lib/estado.js +9 -0
- package/scripts/lib/evidencia-valor.js +228 -228
- package/scripts/lib/expandir-targets.js +71 -71
- package/scripts/lib/gitignore-manifest.js +8 -1
- package/scripts/lib/hooks-settings.js +45 -0
- package/scripts/lib/limpiar-basura-global.js +161 -0
- package/scripts/lib/toml-merge.js +204 -204
- package/scripts/mcp-server/auth.js +105 -105
- package/scripts/mcp-server/cache.js +106 -106
- package/scripts/rotar-audit-logs.js +48 -2
- package/scripts/run-eval.js +1 -0
- package/scripts/run-skill-evals.js +287 -8
- package/scripts/smoke-test.js +16 -8
- package/scripts/tui/pantallas/install-wizard.js +69 -13
- package/scripts/validar.js +40 -1
|
@@ -58,6 +58,17 @@ function escribirSettings(settingsPath, settings) {
|
|
|
58
58
|
* Determina si un hook entry en settings.json pertenece a SWL.
|
|
59
59
|
* @param {object} entry - { matcher, hooks: [{ type, command }] }
|
|
60
60
|
* @returns {boolean}
|
|
61
|
+
*
|
|
62
|
+
* ACOPLAMIENTO (re-auditoría nemesis iter-3): esta función y
|
|
63
|
+
* `hooksSWLRegistrados` deben reconocer los MISMOS formatos de comando. Hoy
|
|
64
|
+
* ambas son ciegas al modo wrapper (`bash ./hooks/_run-hook.sh <name>.js`,
|
|
65
|
+
* opt-in SWL_HOOKS_USAR_WRAPPER=1, default en v6.0.0) — esa ceguera se
|
|
66
|
+
* COMPENSA (registrarHooks preserva los wrapper como noSWL, hooksSWLRegistrados
|
|
67
|
+
* no los reune → ni pérdida ni duplicación). Al hacer una wrapper-aware para
|
|
68
|
+
* v6.0.0, actualizar la OTRA en el MISMO commit: si solo esHookSWL reconoce el
|
|
69
|
+
* wrapper, registrarHooks los quitaría de noSWL sin que hooksSWLRegistrados los
|
|
70
|
+
* reuna → se desregistran (regresión). El test wrapper-mode de
|
|
71
|
+
* instalador-transaccional.test.js vigila este invariante.
|
|
61
72
|
*/
|
|
62
73
|
function esHookSWL(entry) {
|
|
63
74
|
const hooksArr = entry.hooks || [];
|
|
@@ -68,6 +79,39 @@ function esHookSWL(entry) {
|
|
|
68
79
|
});
|
|
69
80
|
}
|
|
70
81
|
|
|
82
|
+
/**
|
|
83
|
+
* Devuelve los basenames de los hooks SWL actualmente registrados en
|
|
84
|
+
* settings.json (ej. ['extraccion-aprendizajes.js', ...]). Se usa para
|
|
85
|
+
* PRESERVAR los hooks pre-existentes al re-registrar: sin esto, derivar el
|
|
86
|
+
* set solo de lo recién copiado desregistraría los hooks que colisionaron
|
|
87
|
+
* sin --force pero siguen en disco y funcionando (regresión detectada por la
|
|
88
|
+
* re-auditoría nemesis iter-2).
|
|
89
|
+
*
|
|
90
|
+
* @param {string} settingsPath
|
|
91
|
+
* @returns {string[]} basenames únicos de hooks SWL registrados.
|
|
92
|
+
*
|
|
93
|
+
* ACOPLAMIENTO con `esHookSWL` (ver su docstring): ambas deben reconocer los
|
|
94
|
+
* mismos formatos de comando. El regex de abajo captura el modo inline
|
|
95
|
+
* (`node ... hooks/x.js`) y el wrapper ABSOLUTO (`bash "…/hooks/x.js"`), pero
|
|
96
|
+
* NO el wrapper RELATIVO (`bash ./hooks/_run-hook.sh x.js`, nombre pelón). Esa
|
|
97
|
+
* ceguera se compensa hoy con la de esHookSWL; al volver una wrapper-aware,
|
|
98
|
+
* actualizar la otra en el mismo commit.
|
|
99
|
+
*/
|
|
100
|
+
function hooksSWLRegistrados(settingsPath) {
|
|
101
|
+
const settings = leerSettings(settingsPath);
|
|
102
|
+
const nombres = new Set();
|
|
103
|
+
for (const grupos of Object.values(settings.hooks || {})) {
|
|
104
|
+
if (!Array.isArray(grupos)) continue;
|
|
105
|
+
for (const entry of grupos) {
|
|
106
|
+
for (const h of (entry.hooks || [])) {
|
|
107
|
+
const m = String(h.command || '').match(/hooks[\/\\]([\w.-]+\.js)/);
|
|
108
|
+
if (m) nombres.add(m[1]);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return [...nombres];
|
|
113
|
+
}
|
|
114
|
+
|
|
71
115
|
/**
|
|
72
116
|
* Calcula la ruta del settings.json para un runtime.
|
|
73
117
|
* @param {object} runtime - Configuración del runtime
|
|
@@ -815,6 +859,7 @@ module.exports = {
|
|
|
815
859
|
verificarHooks,
|
|
816
860
|
repararHooks,
|
|
817
861
|
esHookSWL,
|
|
862
|
+
hooksSWLRegistrados,
|
|
818
863
|
registrarOptimizaciones,
|
|
819
864
|
verificarOptimizaciones,
|
|
820
865
|
validarEstructuraSettings,
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* limpiar-basura-global.js — Purga de directorios basura de una instalación
|
|
5
|
+
* global de swl-ses.
|
|
6
|
+
*
|
|
7
|
+
* Caso de origen (2026-07-15): un `install --global` crea `~/_userland`. Una
|
|
8
|
+
* versión previa de `swl-ses doctor` contaba ese `_userland` como marcador de
|
|
9
|
+
* "proyecto swl" (`esProyectoSwl`), así que correr `doctor` desde el HOME
|
|
10
|
+
* sembraba `~/.planning/` con marcadores scaffold (`# PROJECT\n\n(Generado por
|
|
11
|
+
* swl-ses doctor)`). Como el HOME no es un proyecto, ese `.planning/` es basura;
|
|
12
|
+
* peor, hooks que resolvían la raíz vía raiz-proyecto la capturaban y volcaban
|
|
13
|
+
* telemetría ahí. El fix de raiz-proyecto (frontera del HOME) corta la captura;
|
|
14
|
+
* este módulo purga el scaffold ya sembrado en el próximo install global.
|
|
15
|
+
*
|
|
16
|
+
* También purga un `~/_userland/` VACÍO: el contenedor de plugins userland que
|
|
17
|
+
* un install global dejaba en el HOME (subdirs agentes/habilidades/plugins/
|
|
18
|
+
* reglas con solo `.gitkeep`). El instalador actual no lo crea ahí, así que un
|
|
19
|
+
* `_userland` vacío en el HOME es scaffold huérfano.
|
|
20
|
+
*
|
|
21
|
+
* Conservador por diseño (invariantes de seguridad): SOLO elimina un `.planning/`
|
|
22
|
+
* cuyos marcadores llevan la huella del scaffold de doctor, y un `_userland/`
|
|
23
|
+
* SIN archivos reales. Un proyecto real o un `_userland` con plugins del usuario
|
|
24
|
+
* nunca se tocan.
|
|
25
|
+
*
|
|
26
|
+
* Zero-deps.
|
|
27
|
+
*
|
|
28
|
+
* @module scripts/lib/limpiar-basura-global
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
const fs = require('fs');
|
|
32
|
+
const os = require('os');
|
|
33
|
+
const path = require('path');
|
|
34
|
+
|
|
35
|
+
// Huella inequívoca del scaffold vacío que `swl-ses doctor` escribía en cada
|
|
36
|
+
// marcador (`# PROJECT\n\n(Generado por swl-ses doctor)\n`).
|
|
37
|
+
const HUELLA_SCAFFOLD_DOCTOR = '(Generado por swl-ses doctor)';
|
|
38
|
+
const MARCADORES = ['PROYECTO.md', 'REQUISITOS.md', 'HOJA-RUTA.md', 'ESTADO.md'];
|
|
39
|
+
|
|
40
|
+
// Archivos que NO cuentan como contenido real (placeholders de scaffold).
|
|
41
|
+
const ARCHIVOS_PLACEHOLDER = new Set(['.gitkeep', '.DS_Store', 'Thumbs.db']);
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* ¿El `.planning/` de `dir` es el scaffold espurio de doctor (no un proyecto
|
|
45
|
+
* real)? Señal: existe al menos un marcador y TODOS los marcadores presentes
|
|
46
|
+
* llevan la huella del scaffold. Un proyecto real tiene marcadores con
|
|
47
|
+
* contenido propio → devuelve false y no se toca.
|
|
48
|
+
*
|
|
49
|
+
* @param {string} dir - Directorio que contiene el `.planning/` a evaluar.
|
|
50
|
+
* @returns {boolean}
|
|
51
|
+
*/
|
|
52
|
+
function esPlanningEspurio(dir) {
|
|
53
|
+
const planning = path.join(dir, '.planning');
|
|
54
|
+
let esDir = false;
|
|
55
|
+
try {
|
|
56
|
+
esDir = fs.statSync(planning).isDirectory();
|
|
57
|
+
} catch (_) {
|
|
58
|
+
return false; // no existe
|
|
59
|
+
}
|
|
60
|
+
if (!esDir) return false;
|
|
61
|
+
|
|
62
|
+
const presentes = MARCADORES.filter(m => fs.existsSync(path.join(planning, m)));
|
|
63
|
+
if (presentes.length === 0) return false;
|
|
64
|
+
|
|
65
|
+
return presentes.every(m => {
|
|
66
|
+
try {
|
|
67
|
+
return fs.readFileSync(path.join(planning, m), 'utf8').includes(HUELLA_SCAFFOLD_DOCTOR);
|
|
68
|
+
} catch (_) {
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Cuenta archivos reales (no placeholders de scaffold) bajo `dir`, recursivo.
|
|
76
|
+
* @param {string} dir
|
|
77
|
+
* @returns {number}
|
|
78
|
+
*/
|
|
79
|
+
function contarArchivosReales(dir) {
|
|
80
|
+
let entradas;
|
|
81
|
+
try {
|
|
82
|
+
entradas = fs.readdirSync(dir, { withFileTypes: true });
|
|
83
|
+
} catch (_) {
|
|
84
|
+
return 0;
|
|
85
|
+
}
|
|
86
|
+
let n = 0;
|
|
87
|
+
for (const e of entradas) {
|
|
88
|
+
if (e.isDirectory()) {
|
|
89
|
+
n += contarArchivosReales(path.join(dir, e.name));
|
|
90
|
+
} else if (!ARCHIVOS_PLACEHOLDER.has(e.name)) {
|
|
91
|
+
n += 1;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return n;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* ¿El `_userland/` de `dir` es un scaffold vacío (sin plugins reales del
|
|
99
|
+
* usuario)? Señal: existe y no contiene ningún archivo real (solo placeholders
|
|
100
|
+
* como `.gitkeep`). Un `_userland` con plugins del usuario → false, no se toca.
|
|
101
|
+
*
|
|
102
|
+
* @param {string} dir
|
|
103
|
+
* @returns {boolean}
|
|
104
|
+
*/
|
|
105
|
+
function esUserlandVacio(dir) {
|
|
106
|
+
const userland = path.join(dir, '_userland');
|
|
107
|
+
let esDir = false;
|
|
108
|
+
try {
|
|
109
|
+
esDir = fs.statSync(userland).isDirectory();
|
|
110
|
+
} catch (_) {
|
|
111
|
+
return false; // no existe
|
|
112
|
+
}
|
|
113
|
+
if (!esDir) return false;
|
|
114
|
+
return contarArchivosReales(userland) === 0;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Elimina los directorios basura de una instalación global en el HOME:
|
|
119
|
+
* - `.planning/` espurio sembrado por doctor (huella del scaffold).
|
|
120
|
+
* - `_userland/` vacío (scaffold sin plugins del usuario).
|
|
121
|
+
* Idempotente: si no hay basura, no hace nada. Conservador: cada objetivo tiene
|
|
122
|
+
* su invariante de seguridad y NUNCA borra contenido real (proyecto o plugins).
|
|
123
|
+
* Un fallo de borrado en un objetivo no aborta los demás.
|
|
124
|
+
*
|
|
125
|
+
* @param {object} [opts]
|
|
126
|
+
* @param {string} [opts.home] - Raíz global a limpiar (default: os.homedir()).
|
|
127
|
+
* @param {boolean} [opts.dryRun=false] - No borra; solo reporta qué borraría.
|
|
128
|
+
* @returns {{eliminados: string[], dryRun: boolean}} Paths eliminados (o que se
|
|
129
|
+
* eliminarían en dryRun).
|
|
130
|
+
*/
|
|
131
|
+
function limpiarBasuraGlobal(opts = {}) {
|
|
132
|
+
const home = opts.home || os.homedir();
|
|
133
|
+
const dryRun = !!opts.dryRun;
|
|
134
|
+
const eliminados = [];
|
|
135
|
+
|
|
136
|
+
const objetivos = [
|
|
137
|
+
{ detectar: () => esPlanningEspurio(home), ruta: path.join(home, '.planning') },
|
|
138
|
+
{ detectar: () => esUserlandVacio(home), ruta: path.join(home, '_userland') },
|
|
139
|
+
];
|
|
140
|
+
|
|
141
|
+
for (const obj of objetivos) {
|
|
142
|
+
if (!obj.detectar()) continue;
|
|
143
|
+
if (!dryRun) {
|
|
144
|
+
try {
|
|
145
|
+
fs.rmSync(obj.ruta, { recursive: true, force: true });
|
|
146
|
+
} catch (_) {
|
|
147
|
+
continue; // no se pudo borrar: no reportar como eliminado, seguir con el resto
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
eliminados.push(obj.ruta);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return { eliminados, dryRun };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
module.exports = {
|
|
157
|
+
limpiarBasuraGlobal,
|
|
158
|
+
esPlanningEspurio,
|
|
159
|
+
esUserlandVacio,
|
|
160
|
+
HUELLA_SCAFFOLD_DOCTOR,
|
|
161
|
+
};
|
|
@@ -1,204 +1,204 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Merge mínimo de secciones TOML — zero-deps.
|
|
5
|
-
*
|
|
6
|
-
* Opera sobre el formato concreto de `~/.codex/config.toml` (OpenAI Codex CLI):
|
|
7
|
-
* [mcp_servers.<name>]
|
|
8
|
-
* command = "node"
|
|
9
|
-
* args = ["...", "..."]
|
|
10
|
-
* [mcp_servers.<name>.env]
|
|
11
|
-
* KEY = "value"
|
|
12
|
-
*
|
|
13
|
-
* Reglas:
|
|
14
|
-
* - NUNCA reescribe el archivo entero. Solo agrega o reemplaza la sección
|
|
15
|
-
* `[mcp_servers.<name>]` indicada (incluyendo sub-tabla `.env`).
|
|
16
|
-
* - Si el archivo no existe lo crea con permisos 0600.
|
|
17
|
-
* - Si el archivo tiene comentarios o secciones desconocidas, las preserva.
|
|
18
|
-
* - Bloque "owned" delimitado por marcadores `# SWL-MCP-BEGIN <name>` /
|
|
19
|
-
* `# SWL-MCP-END <name>` para permitir actualizaciones idempotentes.
|
|
20
|
-
*
|
|
21
|
-
* NO soporta:
|
|
22
|
-
* - TOML completo (arrays multilínea complejos, inline tables, etc.)
|
|
23
|
-
* - Multi-section nested tables fuera de `mcp_servers.*`
|
|
24
|
-
*
|
|
25
|
-
* Si en el futuro Codex publica un comando idempotente `codex mcp add --idempotent`
|
|
26
|
-
* podemos delegarle el trabajo y deprecar este helper.
|
|
27
|
-
*
|
|
28
|
-
* @module scripts/lib/toml-merge
|
|
29
|
-
*/
|
|
30
|
-
|
|
31
|
-
const fs = require('fs');
|
|
32
|
-
const path = require('path');
|
|
33
|
-
|
|
34
|
-
const { atomicWriteSync } = require('../../hooks/lib/atomic-write');
|
|
35
|
-
|
|
36
|
-
const BEGIN_PREFIX = '# SWL-MCP-BEGIN';
|
|
37
|
-
const END_PREFIX = '# SWL-MCP-END';
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Serializa un servidor MCP en bloque TOML.
|
|
41
|
-
*
|
|
42
|
-
* @param {string} name - Nombre del server (identificador en config.toml).
|
|
43
|
-
* @param {{ command: string, args?: string[], env?: Record<string,string> }} cfg
|
|
44
|
-
* @returns {string} Bloque TOML con marcadores.
|
|
45
|
-
*/
|
|
46
|
-
function serializarServidor(name, cfg) {
|
|
47
|
-
if (!name || typeof name !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(name)) {
|
|
48
|
-
throw new Error(`Nombre de MCP server inválido: "${name}". Solo [a-zA-Z0-9_-].`);
|
|
49
|
-
}
|
|
50
|
-
if (!cfg || typeof cfg.command !== 'string' || cfg.command.length === 0) {
|
|
51
|
-
throw new Error(`MCP server "${name}" requiere "command" string no vacío.`);
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
const lineas = [];
|
|
55
|
-
lineas.push(`${BEGIN_PREFIX} ${name}`);
|
|
56
|
-
lineas.push(`[mcp_servers.${name}]`);
|
|
57
|
-
lineas.push(`command = ${tomlString(cfg.command)}`);
|
|
58
|
-
|
|
59
|
-
if (Array.isArray(cfg.args) && cfg.args.length > 0) {
|
|
60
|
-
const items = cfg.args.map(tomlString).join(', ');
|
|
61
|
-
lineas.push(`args = [${items}]`);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
if (cfg.env && typeof cfg.env === 'object' && Object.keys(cfg.env).length > 0) {
|
|
65
|
-
lineas.push('');
|
|
66
|
-
lineas.push(`[mcp_servers.${name}.env]`);
|
|
67
|
-
for (const [k, v] of Object.entries(cfg.env)) {
|
|
68
|
-
if (typeof v !== 'string') {
|
|
69
|
-
throw new Error(`MCP server "${name}" env.${k} debe ser string (recibido: ${typeof v}).`);
|
|
70
|
-
}
|
|
71
|
-
// Solo claves alfanuméricas/_ en env names — TOML restricción razonable
|
|
72
|
-
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k)) {
|
|
73
|
-
throw new Error(`MCP server "${name}" env key inválido: "${k}".`);
|
|
74
|
-
}
|
|
75
|
-
lineas.push(`${k} = ${tomlString(v)}`);
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
lineas.push(`${END_PREFIX} ${name}`);
|
|
80
|
-
return lineas.join('\n');
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* Escapa un string para TOML usando comillas dobles.
|
|
85
|
-
* No usa basic-string raw para evitar pitfalls con backslashes.
|
|
86
|
-
*/
|
|
87
|
-
function tomlString(s) {
|
|
88
|
-
// TOML basic string: escape backslash, doblequote, control chars.
|
|
89
|
-
const escapado = String(s)
|
|
90
|
-
.replace(/\\/g, '\\\\')
|
|
91
|
-
.replace(/"/g, '\\"')
|
|
92
|
-
.replace(/\n/g, '\\n')
|
|
93
|
-
.replace(/\r/g, '\\r')
|
|
94
|
-
.replace(/\t/g, '\\t');
|
|
95
|
-
return `"${escapado}"`;
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
/**
|
|
99
|
-
* Inserta o actualiza un servidor MCP en `config.toml`.
|
|
100
|
-
*
|
|
101
|
-
* Idempotente: si el bloque ya existe con el mismo contenido, no escribe.
|
|
102
|
-
* Si existe con contenido distinto, lo reemplaza dentro de los marcadores.
|
|
103
|
-
* Si no existe, lo agrega al final del archivo precedido de línea en blanco.
|
|
104
|
-
*
|
|
105
|
-
* @param {string} rutaConfig - Path absoluto a config.toml (típicamente ~/.codex/config.toml).
|
|
106
|
-
* @param {string} name - Nombre del MCP server (clave de [mcp_servers.<name>]).
|
|
107
|
-
* @param {{ command: string, args?: string[], env?: Record<string,string> }} cfg
|
|
108
|
-
* @returns {{ accion: 'creado' | 'agregado' | 'actualizado' | 'sin-cambios', ruta: string }}
|
|
109
|
-
*/
|
|
110
|
-
function upsertMcpServer(rutaConfig, name, cfg) {
|
|
111
|
-
const bloqueNuevo = serializarServidor(name, cfg);
|
|
112
|
-
|
|
113
|
-
let existente = '';
|
|
114
|
-
let existia = false;
|
|
115
|
-
try {
|
|
116
|
-
existente = fs.readFileSync(rutaConfig, 'utf-8');
|
|
117
|
-
existia = true;
|
|
118
|
-
} catch (err) {
|
|
119
|
-
if (err.code !== 'ENOENT') throw err;
|
|
120
|
-
// Archivo no existe — se crea
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
const beginTag = `${BEGIN_PREFIX} ${name}`;
|
|
124
|
-
const endTag = `${END_PREFIX} ${name}`;
|
|
125
|
-
|
|
126
|
-
if (!existia) {
|
|
127
|
-
const dir = path.dirname(rutaConfig);
|
|
128
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
129
|
-
const contenido = `# config.toml de Codex CLI — gestionado parcialmente por swl-ses\n# Bloques delimitados por SWL-MCP-BEGIN/END son regenerables.\n\n${bloqueNuevo}\n`;
|
|
130
|
-
atomicWriteSync(rutaConfig, contenido, 'utf8', { mode: 0o600 });
|
|
131
|
-
return { accion: 'creado', ruta: rutaConfig };
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
const idxBegin = existente.indexOf(beginTag);
|
|
135
|
-
const idxEnd = existente.indexOf(endTag);
|
|
136
|
-
|
|
137
|
-
// Caso 1: no existe el bloque → append al final
|
|
138
|
-
if (idxBegin === -1 || idxEnd === -1) {
|
|
139
|
-
const separador = existente.endsWith('\n') ? '\n' : '\n\n';
|
|
140
|
-
const contenido = existente + separador + bloqueNuevo + '\n';
|
|
141
|
-
atomicWriteSync(rutaConfig, contenido, 'utf8', { mode: 0o600 });
|
|
142
|
-
return { accion: 'agregado', ruta: rutaConfig };
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
// Caso 2: existe — comparar contenido
|
|
146
|
-
// Calculamos fin REAL incluyendo el endTag completo.
|
|
147
|
-
const finBloqueExistente = idxEnd + endTag.length;
|
|
148
|
-
const bloqueExistente = existente.slice(idxBegin, finBloqueExistente);
|
|
149
|
-
|
|
150
|
-
if (bloqueExistente === bloqueNuevo) {
|
|
151
|
-
return { accion: 'sin-cambios', ruta: rutaConfig };
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
const contenido = existente.slice(0, idxBegin) + bloqueNuevo + existente.slice(finBloqueExistente);
|
|
155
|
-
atomicWriteSync(rutaConfig, contenido, 'utf8', { mode: 0o600 });
|
|
156
|
-
return { accion: 'actualizado', ruta: rutaConfig };
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/**
|
|
160
|
-
* Elimina un bloque MCP server por nombre. Idempotente: si no existe, no hace nada.
|
|
161
|
-
*
|
|
162
|
-
* @param {string} rutaConfig
|
|
163
|
-
* @param {string} name
|
|
164
|
-
* @returns {{ accion: 'eliminado' | 'sin-cambios', ruta: string }}
|
|
165
|
-
*/
|
|
166
|
-
function removeMcpServer(rutaConfig, name) {
|
|
167
|
-
let existente = '';
|
|
168
|
-
try {
|
|
169
|
-
existente = fs.readFileSync(rutaConfig, 'utf-8');
|
|
170
|
-
} catch (err) {
|
|
171
|
-
if (err.code === 'ENOENT') return { accion: 'sin-cambios', ruta: rutaConfig };
|
|
172
|
-
throw err;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
const beginTag = `${BEGIN_PREFIX} ${name}`;
|
|
176
|
-
const endTag = `${END_PREFIX} ${name}`;
|
|
177
|
-
const idxBegin = existente.indexOf(beginTag);
|
|
178
|
-
const idxEnd = existente.indexOf(endTag);
|
|
179
|
-
|
|
180
|
-
if (idxBegin === -1 || idxEnd === -1) {
|
|
181
|
-
return { accion: 'sin-cambios', ruta: rutaConfig };
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
// Quitar bloque + posible newline previo y posterior (cosmético)
|
|
185
|
-
let inicio = idxBegin;
|
|
186
|
-
let fin = idxEnd + endTag.length;
|
|
187
|
-
// Comer un \n previo si existe (no comer doble \n para preservar separadores entre secciones)
|
|
188
|
-
if (inicio > 0 && existente[inicio - 1] === '\n') inicio--;
|
|
189
|
-
if (fin < existente.length && existente[fin] === '\n') fin++;
|
|
190
|
-
|
|
191
|
-
const contenido = existente.slice(0, inicio) + existente.slice(fin);
|
|
192
|
-
atomicWriteSync(rutaConfig, contenido, 'utf8', { mode: 0o600 });
|
|
193
|
-
return { accion: 'eliminado', ruta: rutaConfig };
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
module.exports = {
|
|
197
|
-
upsertMcpServer,
|
|
198
|
-
removeMcpServer,
|
|
199
|
-
serializarServidor,
|
|
200
|
-
// Para tests
|
|
201
|
-
_tomlString: tomlString,
|
|
202
|
-
BEGIN_PREFIX,
|
|
203
|
-
END_PREFIX,
|
|
204
|
-
};
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Merge mínimo de secciones TOML — zero-deps.
|
|
5
|
+
*
|
|
6
|
+
* Opera sobre el formato concreto de `~/.codex/config.toml` (OpenAI Codex CLI):
|
|
7
|
+
* [mcp_servers.<name>]
|
|
8
|
+
* command = "node"
|
|
9
|
+
* args = ["...", "..."]
|
|
10
|
+
* [mcp_servers.<name>.env]
|
|
11
|
+
* KEY = "value"
|
|
12
|
+
*
|
|
13
|
+
* Reglas:
|
|
14
|
+
* - NUNCA reescribe el archivo entero. Solo agrega o reemplaza la sección
|
|
15
|
+
* `[mcp_servers.<name>]` indicada (incluyendo sub-tabla `.env`).
|
|
16
|
+
* - Si el archivo no existe lo crea con permisos 0600.
|
|
17
|
+
* - Si el archivo tiene comentarios o secciones desconocidas, las preserva.
|
|
18
|
+
* - Bloque "owned" delimitado por marcadores `# SWL-MCP-BEGIN <name>` /
|
|
19
|
+
* `# SWL-MCP-END <name>` para permitir actualizaciones idempotentes.
|
|
20
|
+
*
|
|
21
|
+
* NO soporta:
|
|
22
|
+
* - TOML completo (arrays multilínea complejos, inline tables, etc.)
|
|
23
|
+
* - Multi-section nested tables fuera de `mcp_servers.*`
|
|
24
|
+
*
|
|
25
|
+
* Si en el futuro Codex publica un comando idempotente `codex mcp add --idempotent`
|
|
26
|
+
* podemos delegarle el trabajo y deprecar este helper.
|
|
27
|
+
*
|
|
28
|
+
* @module scripts/lib/toml-merge
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
const fs = require('fs');
|
|
32
|
+
const path = require('path');
|
|
33
|
+
|
|
34
|
+
const { atomicWriteSync } = require('../../hooks/lib/atomic-write');
|
|
35
|
+
|
|
36
|
+
const BEGIN_PREFIX = '# SWL-MCP-BEGIN';
|
|
37
|
+
const END_PREFIX = '# SWL-MCP-END';
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Serializa un servidor MCP en bloque TOML.
|
|
41
|
+
*
|
|
42
|
+
* @param {string} name - Nombre del server (identificador en config.toml).
|
|
43
|
+
* @param {{ command: string, args?: string[], env?: Record<string,string> }} cfg
|
|
44
|
+
* @returns {string} Bloque TOML con marcadores.
|
|
45
|
+
*/
|
|
46
|
+
function serializarServidor(name, cfg) {
|
|
47
|
+
if (!name || typeof name !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(name)) {
|
|
48
|
+
throw new Error(`Nombre de MCP server inválido: "${name}". Solo [a-zA-Z0-9_-].`);
|
|
49
|
+
}
|
|
50
|
+
if (!cfg || typeof cfg.command !== 'string' || cfg.command.length === 0) {
|
|
51
|
+
throw new Error(`MCP server "${name}" requiere "command" string no vacío.`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const lineas = [];
|
|
55
|
+
lineas.push(`${BEGIN_PREFIX} ${name}`);
|
|
56
|
+
lineas.push(`[mcp_servers.${name}]`);
|
|
57
|
+
lineas.push(`command = ${tomlString(cfg.command)}`);
|
|
58
|
+
|
|
59
|
+
if (Array.isArray(cfg.args) && cfg.args.length > 0) {
|
|
60
|
+
const items = cfg.args.map(tomlString).join(', ');
|
|
61
|
+
lineas.push(`args = [${items}]`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (cfg.env && typeof cfg.env === 'object' && Object.keys(cfg.env).length > 0) {
|
|
65
|
+
lineas.push('');
|
|
66
|
+
lineas.push(`[mcp_servers.${name}.env]`);
|
|
67
|
+
for (const [k, v] of Object.entries(cfg.env)) {
|
|
68
|
+
if (typeof v !== 'string') {
|
|
69
|
+
throw new Error(`MCP server "${name}" env.${k} debe ser string (recibido: ${typeof v}).`);
|
|
70
|
+
}
|
|
71
|
+
// Solo claves alfanuméricas/_ en env names — TOML restricción razonable
|
|
72
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k)) {
|
|
73
|
+
throw new Error(`MCP server "${name}" env key inválido: "${k}".`);
|
|
74
|
+
}
|
|
75
|
+
lineas.push(`${k} = ${tomlString(v)}`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
lineas.push(`${END_PREFIX} ${name}`);
|
|
80
|
+
return lineas.join('\n');
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Escapa un string para TOML usando comillas dobles.
|
|
85
|
+
* No usa basic-string raw para evitar pitfalls con backslashes.
|
|
86
|
+
*/
|
|
87
|
+
function tomlString(s) {
|
|
88
|
+
// TOML basic string: escape backslash, doblequote, control chars.
|
|
89
|
+
const escapado = String(s)
|
|
90
|
+
.replace(/\\/g, '\\\\')
|
|
91
|
+
.replace(/"/g, '\\"')
|
|
92
|
+
.replace(/\n/g, '\\n')
|
|
93
|
+
.replace(/\r/g, '\\r')
|
|
94
|
+
.replace(/\t/g, '\\t');
|
|
95
|
+
return `"${escapado}"`;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Inserta o actualiza un servidor MCP en `config.toml`.
|
|
100
|
+
*
|
|
101
|
+
* Idempotente: si el bloque ya existe con el mismo contenido, no escribe.
|
|
102
|
+
* Si existe con contenido distinto, lo reemplaza dentro de los marcadores.
|
|
103
|
+
* Si no existe, lo agrega al final del archivo precedido de línea en blanco.
|
|
104
|
+
*
|
|
105
|
+
* @param {string} rutaConfig - Path absoluto a config.toml (típicamente ~/.codex/config.toml).
|
|
106
|
+
* @param {string} name - Nombre del MCP server (clave de [mcp_servers.<name>]).
|
|
107
|
+
* @param {{ command: string, args?: string[], env?: Record<string,string> }} cfg
|
|
108
|
+
* @returns {{ accion: 'creado' | 'agregado' | 'actualizado' | 'sin-cambios', ruta: string }}
|
|
109
|
+
*/
|
|
110
|
+
function upsertMcpServer(rutaConfig, name, cfg) {
|
|
111
|
+
const bloqueNuevo = serializarServidor(name, cfg);
|
|
112
|
+
|
|
113
|
+
let existente = '';
|
|
114
|
+
let existia = false;
|
|
115
|
+
try {
|
|
116
|
+
existente = fs.readFileSync(rutaConfig, 'utf-8');
|
|
117
|
+
existia = true;
|
|
118
|
+
} catch (err) {
|
|
119
|
+
if (err.code !== 'ENOENT') throw err;
|
|
120
|
+
// Archivo no existe — se crea
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const beginTag = `${BEGIN_PREFIX} ${name}`;
|
|
124
|
+
const endTag = `${END_PREFIX} ${name}`;
|
|
125
|
+
|
|
126
|
+
if (!existia) {
|
|
127
|
+
const dir = path.dirname(rutaConfig);
|
|
128
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
129
|
+
const contenido = `# config.toml de Codex CLI — gestionado parcialmente por swl-ses\n# Bloques delimitados por SWL-MCP-BEGIN/END son regenerables.\n\n${bloqueNuevo}\n`;
|
|
130
|
+
atomicWriteSync(rutaConfig, contenido, 'utf8', { mode: 0o600 });
|
|
131
|
+
return { accion: 'creado', ruta: rutaConfig };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const idxBegin = existente.indexOf(beginTag);
|
|
135
|
+
const idxEnd = existente.indexOf(endTag);
|
|
136
|
+
|
|
137
|
+
// Caso 1: no existe el bloque → append al final
|
|
138
|
+
if (idxBegin === -1 || idxEnd === -1) {
|
|
139
|
+
const separador = existente.endsWith('\n') ? '\n' : '\n\n';
|
|
140
|
+
const contenido = existente + separador + bloqueNuevo + '\n';
|
|
141
|
+
atomicWriteSync(rutaConfig, contenido, 'utf8', { mode: 0o600 });
|
|
142
|
+
return { accion: 'agregado', ruta: rutaConfig };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Caso 2: existe — comparar contenido
|
|
146
|
+
// Calculamos fin REAL incluyendo el endTag completo.
|
|
147
|
+
const finBloqueExistente = idxEnd + endTag.length;
|
|
148
|
+
const bloqueExistente = existente.slice(idxBegin, finBloqueExistente);
|
|
149
|
+
|
|
150
|
+
if (bloqueExistente === bloqueNuevo) {
|
|
151
|
+
return { accion: 'sin-cambios', ruta: rutaConfig };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const contenido = existente.slice(0, idxBegin) + bloqueNuevo + existente.slice(finBloqueExistente);
|
|
155
|
+
atomicWriteSync(rutaConfig, contenido, 'utf8', { mode: 0o600 });
|
|
156
|
+
return { accion: 'actualizado', ruta: rutaConfig };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Elimina un bloque MCP server por nombre. Idempotente: si no existe, no hace nada.
|
|
161
|
+
*
|
|
162
|
+
* @param {string} rutaConfig
|
|
163
|
+
* @param {string} name
|
|
164
|
+
* @returns {{ accion: 'eliminado' | 'sin-cambios', ruta: string }}
|
|
165
|
+
*/
|
|
166
|
+
function removeMcpServer(rutaConfig, name) {
|
|
167
|
+
let existente = '';
|
|
168
|
+
try {
|
|
169
|
+
existente = fs.readFileSync(rutaConfig, 'utf-8');
|
|
170
|
+
} catch (err) {
|
|
171
|
+
if (err.code === 'ENOENT') return { accion: 'sin-cambios', ruta: rutaConfig };
|
|
172
|
+
throw err;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const beginTag = `${BEGIN_PREFIX} ${name}`;
|
|
176
|
+
const endTag = `${END_PREFIX} ${name}`;
|
|
177
|
+
const idxBegin = existente.indexOf(beginTag);
|
|
178
|
+
const idxEnd = existente.indexOf(endTag);
|
|
179
|
+
|
|
180
|
+
if (idxBegin === -1 || idxEnd === -1) {
|
|
181
|
+
return { accion: 'sin-cambios', ruta: rutaConfig };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Quitar bloque + posible newline previo y posterior (cosmético)
|
|
185
|
+
let inicio = idxBegin;
|
|
186
|
+
let fin = idxEnd + endTag.length;
|
|
187
|
+
// Comer un \n previo si existe (no comer doble \n para preservar separadores entre secciones)
|
|
188
|
+
if (inicio > 0 && existente[inicio - 1] === '\n') inicio--;
|
|
189
|
+
if (fin < existente.length && existente[fin] === '\n') fin++;
|
|
190
|
+
|
|
191
|
+
const contenido = existente.slice(0, inicio) + existente.slice(fin);
|
|
192
|
+
atomicWriteSync(rutaConfig, contenido, 'utf8', { mode: 0o600 });
|
|
193
|
+
return { accion: 'eliminado', ruta: rutaConfig };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
module.exports = {
|
|
197
|
+
upsertMcpServer,
|
|
198
|
+
removeMcpServer,
|
|
199
|
+
serializarServidor,
|
|
200
|
+
// Para tests
|
|
201
|
+
_tomlString: tomlString,
|
|
202
|
+
BEGIN_PREFIX,
|
|
203
|
+
END_PREFIX,
|
|
204
|
+
};
|