@saulwade/swl-ses 1.1.4 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/CLAUDE.md +2 -2
  2. package/README.md +3 -3
  3. package/bin/swl-mcp-server.js +187 -0
  4. package/habilidades/benchmark-memoria/SKILL.md +186 -0
  5. package/habilidades/contenedores-docker/SKILL.md +8 -1
  6. package/habilidades/datos-etl/SKILL.md +18 -1
  7. package/habilidades/eval-framework/SKILL.md +212 -0
  8. package/habilidades/memoria-busqueda/SKILL.md +24 -1
  9. package/habilidades/planear-fase/SKILL.md +299 -269
  10. package/habilidades/postgresql-experto/SKILL.md +24 -1
  11. package/habilidades/verificar-trabajo/SKILL.md +7 -1
  12. package/hooks/lib/evolution-tracker.js +65 -11
  13. package/hooks/lib/memory-search.js +44 -13
  14. package/hooks/sugerir-contribuir.js +226 -0
  15. package/manifiestos/hooks-config.json +9 -0
  16. package/manifiestos/modulos.json +33 -1
  17. package/manifiestos/perfiles.json +2 -1
  18. package/package.json +4 -3
  19. package/plugin.json +343 -343
  20. package/scripts/benchmark-memoria.js +167 -0
  21. package/scripts/detectar-aprendizajes-duplicados.js +151 -0
  22. package/scripts/lib/benchmark-metrics.js +160 -0
  23. package/scripts/lib/eval-metrics-store.js +218 -0
  24. package/scripts/lib/eval-quality.js +171 -0
  25. package/scripts/lib/eval-schemas.js +144 -0
  26. package/scripts/lib/eval-self-correct.js +106 -0
  27. package/scripts/lib/eval-validator.js +185 -0
  28. package/scripts/lib/jaccard-similarity.js +98 -0
  29. package/scripts/lib/longmemeval-runner.js +125 -0
  30. package/scripts/lib/rrf-fusion.js +175 -0
  31. package/scripts/lib/scoring-instintos.js +40 -3
  32. package/scripts/mcp-server/README.md +128 -0
  33. package/scripts/mcp-server/handlers.js +206 -0
  34. package/scripts/run-eval.js +141 -0
@@ -0,0 +1,171 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * eval-quality.js — Métricas de calidad para outputs estructurados de SWL.
5
+ *
6
+ * Patrón adoptado de `temp/agentmemory-main/src/eval/quality.ts`. Adaptado a
7
+ * swl-ses: scoring de aprendizajes, instintos, y resultados de búsqueda
8
+ * memoria.
9
+ *
10
+ * Cada función devuelve un score en [0, 100]. Los puntos se asignan por
11
+ * "presencia y calidad de campos clave" — un output con todos los campos
12
+ * tiene score 100, un output trivial tiene score bajo.
13
+ *
14
+ * Funciones puras zero-deps.
15
+ *
16
+ * @module scripts/lib/eval-quality
17
+ */
18
+
19
+ // ── helpers ───────────────────────────────────────────────────────────────────
20
+
21
+ function clamp(n, min, max) {
22
+ if (Number.isNaN(n)) return min;
23
+ return Math.max(min, Math.min(max, n));
24
+ }
25
+
26
+ // ── scoring de outputs ────────────────────────────────────────────────────────
27
+
28
+ /**
29
+ * Score de calidad de una observación comprimida.
30
+ * Adaptado de scoreCompression() de agentmemory.
31
+ *
32
+ * Distribución de puntos:
33
+ * - facts presentes (no vacíos): 25
34
+ * - facts ≥ 3: +10
35
+ * - narrative ≥ 20 chars: 20
36
+ * - narrative ≥ 50 chars: +5
37
+ * - title 5-120 chars: 15
38
+ * - concepts presentes: 15
39
+ * - importance ∈ [1, 10]: 10
40
+ *
41
+ * @param {object} obs
42
+ * @returns {number} en [0, 100]
43
+ */
44
+ function scoreObservacion(obs) {
45
+ let score = 0;
46
+ if (Array.isArray(obs?.facts) && obs.facts.length > 0) score += 25;
47
+ if (Array.isArray(obs?.facts) && obs.facts.length >= 3) score += 10;
48
+ if (typeof obs?.narrative === 'string' && obs.narrative.length >= 20) score += 20;
49
+ if (typeof obs?.narrative === 'string' && obs.narrative.length >= 50) score += 5;
50
+ if (typeof obs?.title === 'string' && obs.title.length >= 5 && obs.title.length <= 120) score += 15;
51
+ if (Array.isArray(obs?.concepts) && obs.concepts.length > 0) score += 15;
52
+ if (typeof obs?.importance === 'number' && obs.importance >= 1 && obs.importance <= 10) score += 10;
53
+ return clamp(score, 0, 100);
54
+ }
55
+
56
+ /**
57
+ * Score de calidad de un resumen de sesión.
58
+ * Adaptado de scoreSummary() de agentmemory.
59
+ *
60
+ * @param {object} summary
61
+ * @returns {number} en [0, 100]
62
+ */
63
+ function scoreResumen(summary) {
64
+ let score = 0;
65
+ if (typeof summary?.title === 'string' && summary.title.length >= 5) score += 20;
66
+ if (typeof summary?.narrative === 'string' && summary.narrative.length >= 20) score += 25;
67
+ if (typeof summary?.narrative === 'string' && summary.narrative.length >= 100) score += 5;
68
+ if (Array.isArray(summary?.keyDecisions) && summary.keyDecisions.length > 0) score += 20;
69
+ if (Array.isArray(summary?.filesModified) && summary.filesModified.length > 0) score += 15;
70
+ if (Array.isArray(summary?.concepts) && summary.concepts.length > 0) score += 15;
71
+ return clamp(score, 0, 100);
72
+ }
73
+
74
+ /**
75
+ * Score de relevancia de un contexto inyectado.
76
+ * Adaptado de scoreContextRelevance() de agentmemory.
77
+ *
78
+ * @param {string} context - Texto del contexto.
79
+ * @param {string} project - Nombre del proyecto.
80
+ * @returns {number} en [0, 100]
81
+ */
82
+ function scoreRelevanciaContexto(context, project) {
83
+ if (typeof context !== 'string') return 0;
84
+ let score = 0;
85
+ if (context.length > 0) score += 20;
86
+ if (project && context.toLowerCase().includes(String(project).toLowerCase())) score += 20;
87
+ if (context.includes('<')) score += 15;
88
+ const sectionCount = (context.match(/<\w+>/g) || []).length;
89
+ if (sectionCount >= 2) score += 15;
90
+ if (sectionCount >= 4) score += 10;
91
+ if (context.length >= 100) score += 10;
92
+ if (context.length >= 500) score += 10;
93
+ return clamp(score, 0, 100);
94
+ }
95
+
96
+ /**
97
+ * Score de calidad de un aprendizaje SWL extraído de una sesión.
98
+ * Específico de swl-ses (no en agentmemory).
99
+ *
100
+ * Distribución:
101
+ * - título no vacío y descriptivo (≥ 10 chars): 20
102
+ * - título empieza con fecha [YYYY-MM-DD]: 10
103
+ * - cuerpo ≥ 100 chars: 20
104
+ * - cuerpo ≥ 300 chars: +10
105
+ * - tipo identificado (decisión|patrón|...): 15
106
+ * - menciona archivo o regla concreta: 15
107
+ * - tiene "trigger" o "criterio de disparo": 10
108
+ *
109
+ * @param {object} aprendizaje { titulo, contenido, tipo? }
110
+ * @returns {number}
111
+ */
112
+ function scoreAprendizaje(aprendizaje) {
113
+ let score = 0;
114
+ const titulo = String(aprendizaje?.titulo || '');
115
+ const contenido = String(aprendizaje?.contenido || '');
116
+
117
+ if (titulo.length >= 10) score += 20;
118
+ if (/^\[\d{4}-\d{2}-\d{2}\]/.test(titulo)) score += 10;
119
+ if (contenido.length >= 100) score += 20;
120
+ if (contenido.length >= 300) score += 10;
121
+
122
+ const tipos = ['decisión', 'patrón', 'anti-patrón', 'bug-fix', 'descubrimiento', 'gotcha'];
123
+ if (aprendizaje?.tipo && tipos.some(t => String(aprendizaje.tipo).includes(t))) {
124
+ score += 15;
125
+ }
126
+
127
+ if (/`[^`]+\.(js|ts|md|py|json|yaml)`|`[^`]+\/[^`]+`/.test(contenido)) score += 15;
128
+ if (/trigger|criterio de disparo|cuando .+ entonces/i.test(contenido)) score += 10;
129
+
130
+ return clamp(score, 0, 100);
131
+ }
132
+
133
+ /**
134
+ * Score de calidad de un instinto.
135
+ * Específico de swl-ses.
136
+ *
137
+ * Distribución:
138
+ * - pattern presente: 25
139
+ * - pattern ≥ 30 chars: +10
140
+ * - confidence ∈ [0, 1]: 15
141
+ * - status válido (active|degraded|archived): 10
142
+ * - source_sessions o source_agents declarado: 15
143
+ * - evidence_count ≥ 1: 15
144
+ * - last_validated_at presente: 10
145
+ *
146
+ * @param {object} instinto
147
+ * @returns {number}
148
+ */
149
+ function scoreInstinto(instinto) {
150
+ let score = 0;
151
+ const pattern = String(instinto?.pattern || '');
152
+ if (pattern.length > 0) score += 25;
153
+ if (pattern.length >= 30) score += 10;
154
+ if (typeof instinto?.confidence === 'number' && instinto.confidence >= 0 && instinto.confidence <= 1) score += 15;
155
+ if (['active', 'degraded', 'archived'].includes(instinto?.status)) score += 10;
156
+ if ((Array.isArray(instinto?.source_sessions) && instinto.source_sessions.length > 0) ||
157
+ (Array.isArray(instinto?.source_agents) && instinto.source_agents.length > 0)) score += 15;
158
+ if (typeof instinto?.evidence_count === 'number' && instinto.evidence_count >= 1) score += 15;
159
+ if (instinto?.last_validated_at || instinto?.last_validated) score += 10;
160
+ return clamp(score, 0, 100);
161
+ }
162
+
163
+ // ── exports ───────────────────────────────────────────────────────────────────
164
+
165
+ module.exports = {
166
+ scoreObservacion,
167
+ scoreResumen,
168
+ scoreRelevanciaContexto,
169
+ scoreAprendizaje,
170
+ scoreInstinto,
171
+ };
@@ -0,0 +1,144 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * eval-schemas.js — Schemas JSON-lite para evaluación de outputs SWL.
5
+ *
6
+ * Patrón adoptado de `temp/agentmemory-main/src/eval/schemas.ts`. Adaptado a
7
+ * swl-ses: sin Zod (sería dep externa). Uso JSON Schema-lite con validador
8
+ * propio en `eval-validator.js`. Funciones puras zero-deps.
9
+ *
10
+ * Cada schema describe la estructura esperada de un output evaluable. El
11
+ * validador devuelve `{ valid, errors[] }` para que el caller decida.
12
+ *
13
+ * @module scripts/lib/eval-schemas
14
+ */
15
+
16
+ // ── tipos enumerados ──────────────────────────────────────────────────────────
17
+
18
+ const TIPOS_OBSERVACION = [
19
+ 'file_read', 'file_write', 'file_edit',
20
+ 'command_run', 'search', 'web_fetch',
21
+ 'conversation', 'error', 'decision',
22
+ 'discovery', 'subagent', 'notification',
23
+ 'task', 'other',
24
+ ];
25
+
26
+ const TIPOS_MEMORIA = [
27
+ 'pattern', 'preference', 'architecture',
28
+ 'bug', 'workflow', 'fact',
29
+ ];
30
+
31
+ const TIPOS_RELACION = [
32
+ 'supersedes', 'extends', 'derives', 'contradicts', 'related',
33
+ ];
34
+
35
+ // ── schemas JSON-lite ─────────────────────────────────────────────────────────
36
+
37
+ /**
38
+ * Schema para output de compresión de observación.
39
+ * Estructura compatible con `CompressOutputSchema` de agentmemory.
40
+ */
41
+ const COMPRESS_OUTPUT_SCHEMA = {
42
+ type: 'object',
43
+ required: ['type', 'title', 'facts', 'narrative', 'concepts', 'files', 'importance'],
44
+ properties: {
45
+ type: { type: 'string', enum: TIPOS_OBSERVACION },
46
+ title: { type: 'string', minLength: 1, maxLength: 120 },
47
+ subtitle: { type: 'string' },
48
+ facts: { type: 'array', minItems: 1, items: { type: 'string' } },
49
+ narrative: { type: 'string', minLength: 10 },
50
+ concepts: { type: 'array', items: { type: 'string' } },
51
+ files: { type: 'array', items: { type: 'string' } },
52
+ importance: { type: 'integer', minimum: 1, maximum: 10 },
53
+ },
54
+ };
55
+
56
+ /**
57
+ * Schema para output de resumen de sesión.
58
+ */
59
+ const SUMMARY_OUTPUT_SCHEMA = {
60
+ type: 'object',
61
+ required: ['title', 'narrative', 'keyDecisions', 'filesModified', 'concepts'],
62
+ properties: {
63
+ title: { type: 'string', minLength: 1 },
64
+ narrative: { type: 'string', minLength: 20 },
65
+ keyDecisions: { type: 'array', items: { type: 'string' } },
66
+ filesModified: { type: 'array', items: { type: 'string' } },
67
+ concepts: { type: 'array', items: { type: 'string' } },
68
+ },
69
+ };
70
+
71
+ /**
72
+ * Schema para input de búsqueda.
73
+ */
74
+ const SEARCH_INPUT_SCHEMA = {
75
+ type: 'object',
76
+ required: ['query'],
77
+ properties: {
78
+ query: { type: 'string', minLength: 1 },
79
+ limit: { type: 'integer', minimum: 1 },
80
+ },
81
+ };
82
+
83
+ /**
84
+ * Schema para input de "remember" (guardar memoria).
85
+ */
86
+ const REMEMBER_INPUT_SCHEMA = {
87
+ type: 'object',
88
+ required: ['content'],
89
+ properties: {
90
+ content: { type: 'string', minLength: 1 },
91
+ type: { type: 'string', enum: TIPOS_MEMORIA },
92
+ concepts: { type: 'array', items: { type: 'string' } },
93
+ files: { type: 'array', items: { type: 'string' } },
94
+ },
95
+ };
96
+
97
+ /**
98
+ * Schema para resultado de evaluación.
99
+ */
100
+ const EVAL_RESULT_SCHEMA = {
101
+ type: 'object',
102
+ required: ['valid', 'qualityScore', 'latencyMs', 'functionId'],
103
+ properties: {
104
+ valid: { type: 'boolean' },
105
+ errors: { type: 'array', items: { type: 'string' } },
106
+ qualityScore: { type: 'number', minimum: 0, maximum: 100 },
107
+ latencyMs: { type: 'number', minimum: 0 },
108
+ functionId: { type: 'string', minLength: 1 },
109
+ metadata: { type: 'object' },
110
+ },
111
+ };
112
+
113
+ /**
114
+ * Schema para resultado de búsqueda en memoria SWL.
115
+ */
116
+ const MEMORY_SEARCH_RESULT_SCHEMA = {
117
+ type: 'object',
118
+ required: ['id', 'tipo', 'titulo', 'fecha', 'relevancia'],
119
+ properties: {
120
+ id: { type: 'string', minLength: 1 },
121
+ tipo: { type: 'string', enum: ['aprendizaje', 'sesion', 'instinto'] },
122
+ titulo: { type: 'string' },
123
+ fecha: { type: 'string' },
124
+ relevancia: { type: 'number', minimum: 0, maximum: 1 },
125
+ combinedScore: { type: 'number', minimum: 0 },
126
+ confidence: { type: 'number', minimum: 0, maximum: 1 },
127
+ },
128
+ };
129
+
130
+ // ── exports ───────────────────────────────────────────────────────────────────
131
+
132
+ module.exports = {
133
+ // Schemas
134
+ COMPRESS_OUTPUT_SCHEMA,
135
+ SUMMARY_OUTPUT_SCHEMA,
136
+ SEARCH_INPUT_SCHEMA,
137
+ REMEMBER_INPUT_SCHEMA,
138
+ EVAL_RESULT_SCHEMA,
139
+ MEMORY_SEARCH_RESULT_SCHEMA,
140
+ // Enums
141
+ TIPOS_OBSERVACION,
142
+ TIPOS_MEMORIA,
143
+ TIPOS_RELACION,
144
+ };
@@ -0,0 +1,106 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * eval-self-correct.js — Loop de auto-corrección para outputs invalidos.
5
+ *
6
+ * Patrón adoptado de `temp/agentmemory-main/src/eval/self-correct.ts`.
7
+ * Adaptado a swl-ses: en lugar de un MemoryProvider que llama a un LLM, este
8
+ * módulo expone un loop genérico que:
9
+ *
10
+ * 1. Ejecuta una función productora.
11
+ * 2. Valida el output con un validador.
12
+ * 3. Si falla, re-ejecuta con el prompt ampliado con un sufijo más estricto.
13
+ * 4. Repite hasta `maxRetries` o éxito.
14
+ *
15
+ * El productor es agnóstico: puede ser una llamada a Claude (Skill o Bash),
16
+ * o cualquier función async que produzca un output basado en un prompt.
17
+ *
18
+ * No intenta automatizar llamadas LLM — el caller pasa la función concreta.
19
+ * Esto mantiene swl-ses zero-deps.
20
+ *
21
+ * @module scripts/lib/eval-self-correct
22
+ */
23
+
24
+ const SUFIJO_ESTRICTO = `
25
+
26
+ IMPORTANTE: Tu respuesta anterior fue inválida. Por favor asegúrate de que tu
27
+ output siga ESTRICTAMENTE el formato requerido. Cada campo obligatorio debe
28
+ estar presente con valores válidos.
29
+
30
+ Errores detectados en el intento anterior:
31
+ {{ERRORS}}
32
+ `;
33
+
34
+ /**
35
+ * Ejecuta un loop de auto-corrección sobre una función productora.
36
+ *
37
+ * @param {object} opts
38
+ * @param {function(string, string): Promise<string>} opts.productor - Recibe (sysPrompt, userPrompt) y devuelve output.
39
+ * @param {function(string): {valid: boolean, errors?: string[]}} opts.validador
40
+ * @param {string} opts.sysPrompt
41
+ * @param {string} opts.userPrompt
42
+ * @param {number} [opts.maxRetries=1] - Número máximo de reintentos tras fallo inicial.
43
+ * @returns {Promise<{ output: string, valid: boolean, retried: boolean, intentos: number, errors?: string[] }>}
44
+ */
45
+ async function compresseConReintento(opts) {
46
+ const { productor, validador, sysPrompt, userPrompt, maxRetries = 1 } = opts;
47
+
48
+ if (typeof productor !== 'function') {
49
+ throw new Error('productor debe ser una función async (sysPrompt, userPrompt) => Promise<string>');
50
+ }
51
+ if (typeof validador !== 'function') {
52
+ throw new Error('validador debe ser una función (output) => {valid, errors?}');
53
+ }
54
+
55
+ // Intento 1
56
+ const primerOutput = await productor(sysPrompt, userPrompt);
57
+ const primerResultado = validador(primerOutput);
58
+ if (primerResultado.valid) {
59
+ return {
60
+ output: primerOutput,
61
+ valid: true,
62
+ retried: false,
63
+ intentos: 1,
64
+ };
65
+ }
66
+
67
+ let ultimoOutput = primerOutput;
68
+ let ultimosErrores = primerResultado.errors || [];
69
+
70
+ for (let i = 0; i < maxRetries; i++) {
71
+ const erroresFmt = ultimosErrores.length > 0
72
+ ? ultimosErrores.map(e => ` - ${e}`).join('\n')
73
+ : ' (sin detalle)';
74
+ const sysAmpliado = sysPrompt + SUFIJO_ESTRICTO.replace('{{ERRORS}}', erroresFmt);
75
+
76
+ const reintentoOutput = await productor(sysAmpliado, userPrompt);
77
+ const reintentoResultado = validador(reintentoOutput);
78
+
79
+ if (reintentoResultado.valid) {
80
+ return {
81
+ output: reintentoOutput,
82
+ valid: true,
83
+ retried: true,
84
+ intentos: i + 2,
85
+ };
86
+ }
87
+
88
+ ultimoOutput = reintentoOutput;
89
+ ultimosErrores = reintentoResultado.errors || [];
90
+ }
91
+
92
+ return {
93
+ output: ultimoOutput,
94
+ valid: false,
95
+ retried: maxRetries > 0,
96
+ intentos: maxRetries + 1,
97
+ errors: ultimosErrores,
98
+ };
99
+ }
100
+
101
+ // ── exports ───────────────────────────────────────────────────────────────────
102
+
103
+ module.exports = {
104
+ compresseConReintento,
105
+ SUFIJO_ESTRICTO,
106
+ };
@@ -0,0 +1,185 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * eval-validator.js — Validador JSON Schema-lite para outputs SWL.
5
+ *
6
+ * Patrón adoptado de `temp/agentmemory-main/src/eval/validator.ts`. Adaptado a
7
+ * swl-ses: sin Zod (mantiene principio zero-deps). Implementación propia que
8
+ * cubre el subset de JSON Schema usado por `eval-schemas.js`:
9
+ * - type: object | array | string | number | integer | boolean
10
+ * - required, properties (object)
11
+ * - items, minItems (array)
12
+ * - minLength, maxLength (string)
13
+ * - minimum, maximum (number)
14
+ * - enum
15
+ *
16
+ * Funciones puras zero-deps. Backward compatible: schemas pueden agregar
17
+ * keywords nuevos en el futuro sin romper validaciones existentes.
18
+ *
19
+ * @module scripts/lib/eval-validator
20
+ */
21
+
22
+ // ── helpers ───────────────────────────────────────────────────────────────────
23
+
24
+ function obtenerTipo(value) {
25
+ if (value === null) return 'null';
26
+ if (Array.isArray(value)) return 'array';
27
+ return typeof value;
28
+ }
29
+
30
+ function esEntero(value) {
31
+ return typeof value === 'number' && Number.isInteger(value);
32
+ }
33
+
34
+ // ── validadores por tipo ──────────────────────────────────────────────────────
35
+
36
+ function validarString(value, schema, errors, ruta) {
37
+ if (typeof value !== 'string') {
38
+ errors.push(`${ruta}: esperado string, recibido ${obtenerTipo(value)}`);
39
+ return;
40
+ }
41
+ if (typeof schema.minLength === 'number' && value.length < schema.minLength) {
42
+ errors.push(`${ruta}: longitud ${value.length} < minLength ${schema.minLength}`);
43
+ }
44
+ if (typeof schema.maxLength === 'number' && value.length > schema.maxLength) {
45
+ errors.push(`${ruta}: longitud ${value.length} > maxLength ${schema.maxLength}`);
46
+ }
47
+ if (Array.isArray(schema.enum) && !schema.enum.includes(value)) {
48
+ errors.push(`${ruta}: valor "${value}" no en enum [${schema.enum.join(', ')}]`);
49
+ }
50
+ }
51
+
52
+ function validarNumber(value, schema, errors, ruta) {
53
+ if (schema.type === 'integer') {
54
+ if (!esEntero(value)) {
55
+ errors.push(`${ruta}: esperado integer, recibido ${obtenerTipo(value)}`);
56
+ return;
57
+ }
58
+ } else if (typeof value !== 'number') {
59
+ errors.push(`${ruta}: esperado number, recibido ${obtenerTipo(value)}`);
60
+ return;
61
+ }
62
+ if (typeof schema.minimum === 'number' && value < schema.minimum) {
63
+ errors.push(`${ruta}: valor ${value} < minimum ${schema.minimum}`);
64
+ }
65
+ if (typeof schema.maximum === 'number' && value > schema.maximum) {
66
+ errors.push(`${ruta}: valor ${value} > maximum ${schema.maximum}`);
67
+ }
68
+ if (Array.isArray(schema.enum) && !schema.enum.includes(value)) {
69
+ errors.push(`${ruta}: valor ${value} no en enum`);
70
+ }
71
+ }
72
+
73
+ function validarBoolean(value, schema, errors, ruta) {
74
+ if (typeof value !== 'boolean') {
75
+ errors.push(`${ruta}: esperado boolean, recibido ${obtenerTipo(value)}`);
76
+ }
77
+ }
78
+
79
+ function validarArray(value, schema, errors, ruta) {
80
+ if (!Array.isArray(value)) {
81
+ errors.push(`${ruta}: esperado array, recibido ${obtenerTipo(value)}`);
82
+ return;
83
+ }
84
+ if (typeof schema.minItems === 'number' && value.length < schema.minItems) {
85
+ errors.push(`${ruta}: ${value.length} items < minItems ${schema.minItems}`);
86
+ }
87
+ if (typeof schema.maxItems === 'number' && value.length > schema.maxItems) {
88
+ errors.push(`${ruta}: ${value.length} items > maxItems ${schema.maxItems}`);
89
+ }
90
+ if (schema.items) {
91
+ for (let i = 0; i < value.length; i++) {
92
+ validarValor(value[i], schema.items, errors, `${ruta}[${i}]`);
93
+ }
94
+ }
95
+ }
96
+
97
+ function validarObject(value, schema, errors, ruta) {
98
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
99
+ errors.push(`${ruta}: esperado object, recibido ${obtenerTipo(value)}`);
100
+ return;
101
+ }
102
+ if (Array.isArray(schema.required)) {
103
+ for (const key of schema.required) {
104
+ if (!(key in value)) {
105
+ errors.push(`${ruta}: campo requerido faltante: "${key}"`);
106
+ }
107
+ }
108
+ }
109
+ if (schema.properties && typeof schema.properties === 'object') {
110
+ for (const [key, subSchema] of Object.entries(schema.properties)) {
111
+ if (key in value) {
112
+ validarValor(value[key], subSchema, errors, `${ruta}.${key}`);
113
+ }
114
+ }
115
+ }
116
+ }
117
+
118
+ function validarValor(value, schema, errors, ruta) {
119
+ if (!schema || typeof schema !== 'object') return;
120
+
121
+ switch (schema.type) {
122
+ case 'string': validarString(value, schema, errors, ruta); break;
123
+ case 'number':
124
+ case 'integer': validarNumber(value, schema, errors, ruta); break;
125
+ case 'boolean': validarBoolean(value, schema, errors, ruta); break;
126
+ case 'array': validarArray(value, schema, errors, ruta); break;
127
+ case 'object': validarObject(value, schema, errors, ruta); break;
128
+ default:
129
+ // Sin type explícito: validar enum si aplica, sino aceptar
130
+ if (Array.isArray(schema.enum) && !schema.enum.includes(value)) {
131
+ errors.push(`${ruta}: valor no en enum`);
132
+ }
133
+ }
134
+ }
135
+
136
+ // ── API pública ───────────────────────────────────────────────────────────────
137
+
138
+ /**
139
+ * Valida un valor contra un schema JSON-lite.
140
+ * @param {*} value
141
+ * @param {object} schema
142
+ * @returns {{ valid: boolean, errors: string[] }}
143
+ */
144
+ function validar(value, schema) {
145
+ const errors = [];
146
+ validarValor(value, schema, errors, '$');
147
+ return { valid: errors.length === 0, errors };
148
+ }
149
+
150
+ /**
151
+ * Valida input contra schema, devolviendo formato compatible con eval results.
152
+ * @param {object} schema
153
+ * @param {*} data
154
+ * @param {string} functionId
155
+ * @returns {object} { valid, data?, result? }
156
+ */
157
+ function validarInput(schema, data, functionId) {
158
+ const result = validar(data, schema);
159
+ if (result.valid) {
160
+ return { valid: true, data };
161
+ }
162
+ return {
163
+ valid: false,
164
+ result: {
165
+ valid: false,
166
+ errors: result.errors,
167
+ qualityScore: 0,
168
+ latencyMs: 0,
169
+ functionId: functionId || 'unknown',
170
+ },
171
+ };
172
+ }
173
+
174
+ /**
175
+ * Conveniencia: valida output (alias de validarInput).
176
+ */
177
+ const validarOutput = validarInput;
178
+
179
+ // ── exports ───────────────────────────────────────────────────────────────────
180
+
181
+ module.exports = {
182
+ validar,
183
+ validarInput,
184
+ validarOutput,
185
+ };