@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
|
@@ -1,105 +1,105 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Auth opt-in para swl-mcp-server v1.0.0 (ADR-0019 Sub-fase 3).
|
|
5
|
-
*
|
|
6
|
-
* El stub experimental v0.1.x corría sin auth. Cualquier proceso con acceso al
|
|
7
|
-
* stdio podía leer toda la memoria SWL. Esa decisión era aceptable solo en
|
|
8
|
-
* single-user local — no en multi-usuario, no expuesto a red, no compartido.
|
|
9
|
-
*
|
|
10
|
-
* v1.0.0 introduce auth **opt-in**:
|
|
11
|
-
* - Si `SWL_MCP_API_KEY` NO está definida en el entorno del server, el comportamiento
|
|
12
|
-
* es idéntico al stub (sin auth). Compatibilidad total con clientes existentes.
|
|
13
|
-
* - Si `SWL_MCP_API_KEY` ESTÁ definida, cada `tools/call` debe incluir
|
|
14
|
-
* `params._auth = "<api-key>"`. Sin el token o con token incorrecto, se devuelve
|
|
15
|
-
* `-32001 Unauthorized`.
|
|
16
|
-
*
|
|
17
|
-
* Decisión deliberada de NO usar header `Authorization: Bearer ...`:
|
|
18
|
-
* - El protocolo MCP sobre stdio NO transporta headers HTTP.
|
|
19
|
-
* - Inventar un campo en `initialize.capabilities` específico para swl-ses
|
|
20
|
-
* rompería la spec del protocolo.
|
|
21
|
-
* - `_auth` como campo en `params` es el patrón de menor fricción.
|
|
22
|
-
*
|
|
23
|
-
* Limitaciones aceptadas:
|
|
24
|
-
* - Token estático sin rotación automática — el operador rota manualmente
|
|
25
|
-
* cambiando la env var del proceso.
|
|
26
|
-
* - Sin scopes (read/write) porque v1 sigue siendo read-only.
|
|
27
|
-
*
|
|
28
|
-
* @module scripts/mcp-server/auth
|
|
29
|
-
*/
|
|
30
|
-
|
|
31
|
-
const ENV_VAR_NAME = 'SWL_MCP_API_KEY';
|
|
32
|
-
const ERROR_CODE_UNAUTHORIZED = -32001;
|
|
33
|
-
const ERROR_CODE_FORBIDDEN = -32002;
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* Construye un validador de auth desde el entorno actual.
|
|
37
|
-
*
|
|
38
|
-
* Pattern de "construct once, use many": leer la env var una sola vez al arranque
|
|
39
|
-
* y devolver una función pura que valida cada request. Evita race conditions con
|
|
40
|
-
* tests que mutan process.env.
|
|
41
|
-
*
|
|
42
|
-
* @param {object} [opciones] - { env: NodeJS.ProcessEnv } sustituible para tests.
|
|
43
|
-
* @returns {{ requerida: boolean, validar: (request: object) => { ok: boolean, code?: number, message?: string } }}
|
|
44
|
-
*/
|
|
45
|
-
function construirValidador(opciones = {}) {
|
|
46
|
-
const env = opciones.env || process.env;
|
|
47
|
-
const apiKey = env[ENV_VAR_NAME];
|
|
48
|
-
const requerida = typeof apiKey === 'string' && apiKey.length > 0;
|
|
49
|
-
|
|
50
|
-
return {
|
|
51
|
-
requerida,
|
|
52
|
-
validar: (request) => {
|
|
53
|
-
if (!requerida) return { ok: true };
|
|
54
|
-
// Solo validar tools/call — initialize, ping, tools/list son metadata pública.
|
|
55
|
-
const metodo = request && request.method;
|
|
56
|
-
if (metodo !== 'tools/call') return { ok: true };
|
|
57
|
-
|
|
58
|
-
const params = request.params || {};
|
|
59
|
-
const tokenCliente = params._auth;
|
|
60
|
-
|
|
61
|
-
if (typeof tokenCliente !== 'string' || tokenCliente.length === 0) {
|
|
62
|
-
return {
|
|
63
|
-
ok: false,
|
|
64
|
-
code: ERROR_CODE_UNAUTHORIZED,
|
|
65
|
-
message: 'swl-mcp-server requiere autenticación: SWL_MCP_API_KEY está configurada en el server. El cliente debe enviar params._auth con el API key.',
|
|
66
|
-
};
|
|
67
|
-
}
|
|
68
|
-
if (!comparacionConstante(tokenCliente, apiKey)) {
|
|
69
|
-
return {
|
|
70
|
-
ok: false,
|
|
71
|
-
code: ERROR_CODE_FORBIDDEN,
|
|
72
|
-
message: 'Token inválido.',
|
|
73
|
-
};
|
|
74
|
-
}
|
|
75
|
-
return { ok: true };
|
|
76
|
-
},
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* Comparación de strings en tiempo constante para evitar timing attacks
|
|
82
|
-
* sobre el API key. Implementación zero-deps simple.
|
|
83
|
-
*
|
|
84
|
-
* Si las longitudes difieren, igual se itera la longitud máxima para no filtrar
|
|
85
|
-
* información sobre el largo del secreto vía duración de la comparación.
|
|
86
|
-
*/
|
|
87
|
-
function comparacionConstante(a, b) {
|
|
88
|
-
if (typeof a !== 'string' || typeof b !== 'string') return false;
|
|
89
|
-
const len = Math.max(a.length, b.length);
|
|
90
|
-
let diff = a.length ^ b.length;
|
|
91
|
-
for (let i = 0; i < len; i++) {
|
|
92
|
-
const ca = i < a.length ? a.charCodeAt(i) : 0;
|
|
93
|
-
const cb = i < b.length ? b.charCodeAt(i) : 0;
|
|
94
|
-
diff |= ca ^ cb;
|
|
95
|
-
}
|
|
96
|
-
return diff === 0;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
module.exports = {
|
|
100
|
-
construirValidador,
|
|
101
|
-
comparacionConstante,
|
|
102
|
-
ENV_VAR_NAME,
|
|
103
|
-
ERROR_CODE_UNAUTHORIZED,
|
|
104
|
-
ERROR_CODE_FORBIDDEN,
|
|
105
|
-
};
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Auth opt-in para swl-mcp-server v1.0.0 (ADR-0019 Sub-fase 3).
|
|
5
|
+
*
|
|
6
|
+
* El stub experimental v0.1.x corría sin auth. Cualquier proceso con acceso al
|
|
7
|
+
* stdio podía leer toda la memoria SWL. Esa decisión era aceptable solo en
|
|
8
|
+
* single-user local — no en multi-usuario, no expuesto a red, no compartido.
|
|
9
|
+
*
|
|
10
|
+
* v1.0.0 introduce auth **opt-in**:
|
|
11
|
+
* - Si `SWL_MCP_API_KEY` NO está definida en el entorno del server, el comportamiento
|
|
12
|
+
* es idéntico al stub (sin auth). Compatibilidad total con clientes existentes.
|
|
13
|
+
* - Si `SWL_MCP_API_KEY` ESTÁ definida, cada `tools/call` debe incluir
|
|
14
|
+
* `params._auth = "<api-key>"`. Sin el token o con token incorrecto, se devuelve
|
|
15
|
+
* `-32001 Unauthorized`.
|
|
16
|
+
*
|
|
17
|
+
* Decisión deliberada de NO usar header `Authorization: Bearer ...`:
|
|
18
|
+
* - El protocolo MCP sobre stdio NO transporta headers HTTP.
|
|
19
|
+
* - Inventar un campo en `initialize.capabilities` específico para swl-ses
|
|
20
|
+
* rompería la spec del protocolo.
|
|
21
|
+
* - `_auth` como campo en `params` es el patrón de menor fricción.
|
|
22
|
+
*
|
|
23
|
+
* Limitaciones aceptadas:
|
|
24
|
+
* - Token estático sin rotación automática — el operador rota manualmente
|
|
25
|
+
* cambiando la env var del proceso.
|
|
26
|
+
* - Sin scopes (read/write) porque v1 sigue siendo read-only.
|
|
27
|
+
*
|
|
28
|
+
* @module scripts/mcp-server/auth
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
const ENV_VAR_NAME = 'SWL_MCP_API_KEY';
|
|
32
|
+
const ERROR_CODE_UNAUTHORIZED = -32001;
|
|
33
|
+
const ERROR_CODE_FORBIDDEN = -32002;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Construye un validador de auth desde el entorno actual.
|
|
37
|
+
*
|
|
38
|
+
* Pattern de "construct once, use many": leer la env var una sola vez al arranque
|
|
39
|
+
* y devolver una función pura que valida cada request. Evita race conditions con
|
|
40
|
+
* tests que mutan process.env.
|
|
41
|
+
*
|
|
42
|
+
* @param {object} [opciones] - { env: NodeJS.ProcessEnv } sustituible para tests.
|
|
43
|
+
* @returns {{ requerida: boolean, validar: (request: object) => { ok: boolean, code?: number, message?: string } }}
|
|
44
|
+
*/
|
|
45
|
+
function construirValidador(opciones = {}) {
|
|
46
|
+
const env = opciones.env || process.env;
|
|
47
|
+
const apiKey = env[ENV_VAR_NAME];
|
|
48
|
+
const requerida = typeof apiKey === 'string' && apiKey.length > 0;
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
requerida,
|
|
52
|
+
validar: (request) => {
|
|
53
|
+
if (!requerida) return { ok: true };
|
|
54
|
+
// Solo validar tools/call — initialize, ping, tools/list son metadata pública.
|
|
55
|
+
const metodo = request && request.method;
|
|
56
|
+
if (metodo !== 'tools/call') return { ok: true };
|
|
57
|
+
|
|
58
|
+
const params = request.params || {};
|
|
59
|
+
const tokenCliente = params._auth;
|
|
60
|
+
|
|
61
|
+
if (typeof tokenCliente !== 'string' || tokenCliente.length === 0) {
|
|
62
|
+
return {
|
|
63
|
+
ok: false,
|
|
64
|
+
code: ERROR_CODE_UNAUTHORIZED,
|
|
65
|
+
message: 'swl-mcp-server requiere autenticación: SWL_MCP_API_KEY está configurada en el server. El cliente debe enviar params._auth con el API key.',
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
if (!comparacionConstante(tokenCliente, apiKey)) {
|
|
69
|
+
return {
|
|
70
|
+
ok: false,
|
|
71
|
+
code: ERROR_CODE_FORBIDDEN,
|
|
72
|
+
message: 'Token inválido.',
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
return { ok: true };
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Comparación de strings en tiempo constante para evitar timing attacks
|
|
82
|
+
* sobre el API key. Implementación zero-deps simple.
|
|
83
|
+
*
|
|
84
|
+
* Si las longitudes difieren, igual se itera la longitud máxima para no filtrar
|
|
85
|
+
* información sobre el largo del secreto vía duración de la comparación.
|
|
86
|
+
*/
|
|
87
|
+
function comparacionConstante(a, b) {
|
|
88
|
+
if (typeof a !== 'string' || typeof b !== 'string') return false;
|
|
89
|
+
const len = Math.max(a.length, b.length);
|
|
90
|
+
let diff = a.length ^ b.length;
|
|
91
|
+
for (let i = 0; i < len; i++) {
|
|
92
|
+
const ca = i < a.length ? a.charCodeAt(i) : 0;
|
|
93
|
+
const cb = i < b.length ? b.charCodeAt(i) : 0;
|
|
94
|
+
diff |= ca ^ cb;
|
|
95
|
+
}
|
|
96
|
+
return diff === 0;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
module.exports = {
|
|
100
|
+
construirValidador,
|
|
101
|
+
comparacionConstante,
|
|
102
|
+
ENV_VAR_NAME,
|
|
103
|
+
ERROR_CODE_UNAUTHORIZED,
|
|
104
|
+
ERROR_CODE_FORBIDDEN,
|
|
105
|
+
};
|
|
@@ -1,106 +1,106 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Cache mtime-based para handlers del swl-mcp-server v1.0.0 (ADR-0019 Sub-fase 3).
|
|
5
|
-
*
|
|
6
|
-
* El stub experimental leía disco en cada call (latencia medida ~10ms con
|
|
7
|
-
* APRENDIZAJES.md de 1172 líneas). Para datasets más grandes (>10k líneas) o
|
|
8
|
-
* múltiples clientes concurrentes, el caching reduce sustancialmente la carga.
|
|
9
|
-
*
|
|
10
|
-
* Patrón:
|
|
11
|
-
* - Key = path absoluto del archivo.
|
|
12
|
-
* - Value = { mtime, contenido, parsed }.
|
|
13
|
-
* - Invalidación: si fs.stat().mtime > value.mtime → recargar y reparsear.
|
|
14
|
-
* - TTL opcional vía `SWL_MCP_CACHE_TTL_MS` (default 60000 ms): aunque mtime no
|
|
15
|
-
* haya cambiado, recargar tras TTL para defensa contra clock skew o ediciones
|
|
16
|
-
* que no actualizan mtime (raras pero posibles en filesystems exóticos).
|
|
17
|
-
*
|
|
18
|
-
* Zero-deps. NO usar para escritura — sigue read-only.
|
|
19
|
-
*
|
|
20
|
-
* @module scripts/mcp-server/cache
|
|
21
|
-
*/
|
|
22
|
-
|
|
23
|
-
const fs = require('fs');
|
|
24
|
-
|
|
25
|
-
const DEFAULT_TTL_MS = 60 * 1000;
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* Crea una instancia de cache mtime-based.
|
|
29
|
-
*
|
|
30
|
-
* @param {object} [opciones]
|
|
31
|
-
* @param {number} [opciones.ttlMs] - TTL en milisegundos. Default 60000.
|
|
32
|
-
* @param {object} [opciones.env] - Para leer SWL_MCP_CACHE_TTL_MS en tests.
|
|
33
|
-
* @returns {{ get: Function, invalidate: Function, stats: Function, _store: Map }}
|
|
34
|
-
*/
|
|
35
|
-
function crearCache(opciones = {}) {
|
|
36
|
-
const env = opciones.env || process.env;
|
|
37
|
-
const ttlMs = opciones.ttlMs !== undefined
|
|
38
|
-
? opciones.ttlMs
|
|
39
|
-
: (parseInt(env.SWL_MCP_CACHE_TTL_MS, 10) || DEFAULT_TTL_MS);
|
|
40
|
-
|
|
41
|
-
const store = new Map();
|
|
42
|
-
const stats = { hits: 0, misses: 0, invalidations: 0 };
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Obtiene el valor cacheado para `path`. Si el archivo cambió (mtime) o el TTL
|
|
46
|
-
* expiró, vuelve a leer y parsear con `parser(contenido, path)`.
|
|
47
|
-
*
|
|
48
|
-
* @param {string} ruta - Path absoluto del archivo a cachear.
|
|
49
|
-
* @param {(contenido: string, ruta: string) => any} parser - Función que transforma
|
|
50
|
-
* el contenido del archivo en el objeto a cachear. DEBE ser pura.
|
|
51
|
-
* @returns {{ data: any, hit: boolean } | null} null si el archivo no existe.
|
|
52
|
-
*/
|
|
53
|
-
function get(ruta, parser) {
|
|
54
|
-
let stat;
|
|
55
|
-
try {
|
|
56
|
-
stat = fs.statSync(ruta);
|
|
57
|
-
} catch (err) {
|
|
58
|
-
if (err.code === 'ENOENT') return null;
|
|
59
|
-
throw err;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
const mtimeMs = stat.mtimeMs;
|
|
63
|
-
const ahora = Date.now();
|
|
64
|
-
const cached = store.get(ruta);
|
|
65
|
-
|
|
66
|
-
if (cached && cached.mtimeMs === mtimeMs && (ahora - cached.cargadoEn) < ttlMs) {
|
|
67
|
-
stats.hits++;
|
|
68
|
-
return { data: cached.data, hit: true };
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
if (cached) stats.invalidations++;
|
|
72
|
-
else stats.misses++;
|
|
73
|
-
|
|
74
|
-
const contenido = fs.readFileSync(ruta, 'utf-8');
|
|
75
|
-
const data = parser(contenido, ruta);
|
|
76
|
-
store.set(ruta, { mtimeMs, cargadoEn: ahora, data });
|
|
77
|
-
return { data, hit: false };
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* Invalida una entrada o todo el cache.
|
|
82
|
-
* @param {string} [ruta] - Si se omite, vacía todo.
|
|
83
|
-
*/
|
|
84
|
-
function invalidate(ruta) {
|
|
85
|
-
if (ruta === undefined) {
|
|
86
|
-
const n = store.size;
|
|
87
|
-
store.clear();
|
|
88
|
-
stats.invalidations += n;
|
|
89
|
-
return n;
|
|
90
|
-
}
|
|
91
|
-
if (store.delete(ruta)) stats.invalidations++;
|
|
92
|
-
return 0;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
return {
|
|
96
|
-
get,
|
|
97
|
-
invalidate,
|
|
98
|
-
stats: () => ({ ...stats, size: store.size, ttlMs }),
|
|
99
|
-
_store: store, // exposed para tests
|
|
100
|
-
};
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
module.exports = {
|
|
104
|
-
crearCache,
|
|
105
|
-
DEFAULT_TTL_MS,
|
|
106
|
-
};
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Cache mtime-based para handlers del swl-mcp-server v1.0.0 (ADR-0019 Sub-fase 3).
|
|
5
|
+
*
|
|
6
|
+
* El stub experimental leía disco en cada call (latencia medida ~10ms con
|
|
7
|
+
* APRENDIZAJES.md de 1172 líneas). Para datasets más grandes (>10k líneas) o
|
|
8
|
+
* múltiples clientes concurrentes, el caching reduce sustancialmente la carga.
|
|
9
|
+
*
|
|
10
|
+
* Patrón:
|
|
11
|
+
* - Key = path absoluto del archivo.
|
|
12
|
+
* - Value = { mtime, contenido, parsed }.
|
|
13
|
+
* - Invalidación: si fs.stat().mtime > value.mtime → recargar y reparsear.
|
|
14
|
+
* - TTL opcional vía `SWL_MCP_CACHE_TTL_MS` (default 60000 ms): aunque mtime no
|
|
15
|
+
* haya cambiado, recargar tras TTL para defensa contra clock skew o ediciones
|
|
16
|
+
* que no actualizan mtime (raras pero posibles en filesystems exóticos).
|
|
17
|
+
*
|
|
18
|
+
* Zero-deps. NO usar para escritura — sigue read-only.
|
|
19
|
+
*
|
|
20
|
+
* @module scripts/mcp-server/cache
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const fs = require('fs');
|
|
24
|
+
|
|
25
|
+
const DEFAULT_TTL_MS = 60 * 1000;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Crea una instancia de cache mtime-based.
|
|
29
|
+
*
|
|
30
|
+
* @param {object} [opciones]
|
|
31
|
+
* @param {number} [opciones.ttlMs] - TTL en milisegundos. Default 60000.
|
|
32
|
+
* @param {object} [opciones.env] - Para leer SWL_MCP_CACHE_TTL_MS en tests.
|
|
33
|
+
* @returns {{ get: Function, invalidate: Function, stats: Function, _store: Map }}
|
|
34
|
+
*/
|
|
35
|
+
function crearCache(opciones = {}) {
|
|
36
|
+
const env = opciones.env || process.env;
|
|
37
|
+
const ttlMs = opciones.ttlMs !== undefined
|
|
38
|
+
? opciones.ttlMs
|
|
39
|
+
: (parseInt(env.SWL_MCP_CACHE_TTL_MS, 10) || DEFAULT_TTL_MS);
|
|
40
|
+
|
|
41
|
+
const store = new Map();
|
|
42
|
+
const stats = { hits: 0, misses: 0, invalidations: 0 };
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Obtiene el valor cacheado para `path`. Si el archivo cambió (mtime) o el TTL
|
|
46
|
+
* expiró, vuelve a leer y parsear con `parser(contenido, path)`.
|
|
47
|
+
*
|
|
48
|
+
* @param {string} ruta - Path absoluto del archivo a cachear.
|
|
49
|
+
* @param {(contenido: string, ruta: string) => any} parser - Función que transforma
|
|
50
|
+
* el contenido del archivo en el objeto a cachear. DEBE ser pura.
|
|
51
|
+
* @returns {{ data: any, hit: boolean } | null} null si el archivo no existe.
|
|
52
|
+
*/
|
|
53
|
+
function get(ruta, parser) {
|
|
54
|
+
let stat;
|
|
55
|
+
try {
|
|
56
|
+
stat = fs.statSync(ruta);
|
|
57
|
+
} catch (err) {
|
|
58
|
+
if (err.code === 'ENOENT') return null;
|
|
59
|
+
throw err;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const mtimeMs = stat.mtimeMs;
|
|
63
|
+
const ahora = Date.now();
|
|
64
|
+
const cached = store.get(ruta);
|
|
65
|
+
|
|
66
|
+
if (cached && cached.mtimeMs === mtimeMs && (ahora - cached.cargadoEn) < ttlMs) {
|
|
67
|
+
stats.hits++;
|
|
68
|
+
return { data: cached.data, hit: true };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (cached) stats.invalidations++;
|
|
72
|
+
else stats.misses++;
|
|
73
|
+
|
|
74
|
+
const contenido = fs.readFileSync(ruta, 'utf-8');
|
|
75
|
+
const data = parser(contenido, ruta);
|
|
76
|
+
store.set(ruta, { mtimeMs, cargadoEn: ahora, data });
|
|
77
|
+
return { data, hit: false };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Invalida una entrada o todo el cache.
|
|
82
|
+
* @param {string} [ruta] - Si se omite, vacía todo.
|
|
83
|
+
*/
|
|
84
|
+
function invalidate(ruta) {
|
|
85
|
+
if (ruta === undefined) {
|
|
86
|
+
const n = store.size;
|
|
87
|
+
store.clear();
|
|
88
|
+
stats.invalidations += n;
|
|
89
|
+
return n;
|
|
90
|
+
}
|
|
91
|
+
if (store.delete(ruta)) stats.invalidations++;
|
|
92
|
+
return 0;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return {
|
|
96
|
+
get,
|
|
97
|
+
invalidate,
|
|
98
|
+
stats: () => ({ ...stats, size: store.size, ttlMs }),
|
|
99
|
+
_store: store, // exposed para tests
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
module.exports = {
|
|
104
|
+
crearCache,
|
|
105
|
+
DEFAULT_TTL_MS,
|
|
106
|
+
};
|
|
@@ -24,6 +24,19 @@
|
|
|
24
24
|
const fs = require('fs');
|
|
25
25
|
const path = require('path');
|
|
26
26
|
const zlib = require('zlib');
|
|
27
|
+
// Escritura atómica (CLAUDE.md § Code style): truncar el archivo de auditoría
|
|
28
|
+
// con writeFileSync plano puede corromperlo si la rotación se interrumpe a
|
|
29
|
+
// mitad (nemesis iter-1 S3-4). Require tolerante: repo madre vs destino aplanado.
|
|
30
|
+
let atomicWriteSync;
|
|
31
|
+
try {
|
|
32
|
+
({ atomicWriteSync } = require(path.join(__dirname, '..', 'hooks', 'lib', 'atomic-write.js')));
|
|
33
|
+
} catch {
|
|
34
|
+
try {
|
|
35
|
+
({ atomicWriteSync } = require(path.join(__dirname, 'atomic-write.js')));
|
|
36
|
+
} catch {
|
|
37
|
+
atomicWriteSync = (ruta, contenido) => fs.writeFileSync(ruta, contenido);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
27
40
|
|
|
28
41
|
const ARGS = process.argv.slice(2);
|
|
29
42
|
const DRY_RUN = ARGS.includes('--dry-run');
|
|
@@ -38,7 +51,9 @@ const ARCHIVOS = [
|
|
|
38
51
|
{ nombre: 'audit-merkle', ruta: path.join(RAIZ, 'audit-merkle.jsonl'), campoTs: 'ts' },
|
|
39
52
|
];
|
|
40
53
|
|
|
41
|
-
|
|
54
|
+
// Canónico post-ADR-0031: dirs runtime de .planning/ en inglés ('archive',
|
|
55
|
+
// no 'archivo'). El shim del instalador § 6c-bis migra los dirs viejos.
|
|
56
|
+
const DESTINO_DIR = path.join(RAIZ, 'archive', 'audit');
|
|
42
57
|
|
|
43
58
|
function ahoraMs() {
|
|
44
59
|
return Date.now();
|
|
@@ -85,7 +100,10 @@ function appendGzipped(destinoPath, lineas) {
|
|
|
85
100
|
|
|
86
101
|
function escribirActivo(ruta, lineas) {
|
|
87
102
|
const contenido = lineas.length > 0 ? lineas.join('\n') + '\n' : '';
|
|
88
|
-
|
|
103
|
+
// Atómico: si el proceso muere a mitad, el archivo activo queda íntegro
|
|
104
|
+
// (la versión previa o la nueva completa, nunca truncado). Los .gz de los
|
|
105
|
+
// grupos-mes se escriben ANTES de esta truncación (orden en rotarArchivo).
|
|
106
|
+
atomicWriteSync(ruta, contenido);
|
|
89
107
|
}
|
|
90
108
|
|
|
91
109
|
function rotarArchivo(spec) {
|
|
@@ -133,6 +151,34 @@ function rotarArchivo(spec) {
|
|
|
133
151
|
const destinoPath = path.join(DESTINO_DIR, `${spec.nombre}-${mesKey}.jsonl.gz`);
|
|
134
152
|
appendGzipped(destinoPath, lineas);
|
|
135
153
|
}
|
|
154
|
+
// Checkpoint de cadena Merkle (nemesis iter-1 S3-5): tras truncar, el
|
|
155
|
+
// archivo activo empieza en una entrada cuyo `prev` apunta a una entrada
|
|
156
|
+
// ya archivada (no al génesis). Persistir ese `prev` como `hashInicial`
|
|
157
|
+
// permite a verificarCadena(activo, {hashInicial}) validar el activo como
|
|
158
|
+
// continuación de la cadena archivada, sin falso positivo de rotura.
|
|
159
|
+
// Solo aplica a archivos encadenados (la primera retenida trae `prev`).
|
|
160
|
+
if (retenidas.length > 0) {
|
|
161
|
+
// leerJSONL ya parseó cada registro en `.obj` — sin re-parse.
|
|
162
|
+
const primeraRetenida = retenidas[0].obj;
|
|
163
|
+
if (primeraRetenida && typeof primeraRetenida.prev === 'string') {
|
|
164
|
+
const checkpointPath = path.join(DESTINO_DIR, `.checkpoint-${spec.nombre}.json`);
|
|
165
|
+
// `hashInicial` = prev de la 1a retenida = hash de la ÚLTIMA archivada.
|
|
166
|
+
// NOTA para un consumidor productivo: este checkpoint es un ANCLA de
|
|
167
|
+
// conveniencia, NO una raíz de confianza. verificarCadena(activo,
|
|
168
|
+
// {hashInicial}) prueba la consistencia INTERNA del activo, no que
|
|
169
|
+
// continúe la cadena archivada — para eso el consumidor debe recomputar
|
|
170
|
+
// el hash de la última entrada del .gz y compararlo con este hashInicial
|
|
171
|
+
// (re-auditoría nemesis iter-2). Coherente con el modelo pre-existente
|
|
172
|
+
// (SHA256 sin clave, sin raíz publicada).
|
|
173
|
+
atomicWriteSync(checkpointPath, JSON.stringify({
|
|
174
|
+
archivo: spec.nombre,
|
|
175
|
+
hashInicial: primeraRetenida.prev,
|
|
176
|
+
archivadas: archivadas.length,
|
|
177
|
+
// Fecha LOCAL (no UTC) — clase C1.
|
|
178
|
+
rotado: new Date().toLocaleDateString('sv'),
|
|
179
|
+
}, null, 2) + '\n');
|
|
180
|
+
}
|
|
181
|
+
}
|
|
136
182
|
escribirActivo(spec.ruta, retenidas.map((r) => r.raw));
|
|
137
183
|
}
|
|
138
184
|
|