@saulwade/swl-ses 1.1.4 → 1.2.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.
Files changed (41) hide show
  1. package/CLAUDE.md +13 -2
  2. package/README.md +3 -3
  3. package/agentes/revisor-codigo-swl.md +88 -36
  4. package/bin/swl-mcp-server.js +187 -0
  5. package/habilidades/benchmark-memoria/SKILL.md +186 -0
  6. package/habilidades/contenedores-docker/SKILL.md +8 -1
  7. package/habilidades/datos-etl/SKILL.md +18 -1
  8. package/habilidades/doubt-driven-review/SKILL.md +171 -0
  9. package/habilidades/doubt-driven-review/recursos/EXAMPLES.md +130 -0
  10. package/habilidades/eval-framework/SKILL.md +212 -0
  11. package/habilidades/memoria-busqueda/SKILL.md +24 -1
  12. package/habilidades/meta-skills-estandar/SKILL.md +4 -0
  13. package/habilidades/meta-skills-estandar/recursos/convencion-examples.md +93 -0
  14. package/habilidades/planear-fase/SKILL.md +299 -269
  15. package/habilidades/postgresql-experto/SKILL.md +24 -1
  16. package/habilidades/verificar-trabajo/SKILL.md +7 -1
  17. package/hooks/lib/evolution-tracker.js +65 -11
  18. package/hooks/lib/memory-search.js +44 -13
  19. package/hooks/sugerir-contribuir.js +226 -0
  20. package/manifiestos/hooks-config.json +9 -0
  21. package/manifiestos/modulos.json +35 -2
  22. package/manifiestos/perfiles.json +2 -1
  23. package/package.json +6 -3
  24. package/plugin.json +343 -343
  25. package/reglas/skills-estandar.md +3 -0
  26. package/scripts/benchmark-memoria.js +167 -0
  27. package/scripts/detectar-aprendizajes-duplicados.js +151 -0
  28. package/scripts/generar-checklists-consolidados.js +273 -0
  29. package/scripts/lib/benchmark-metrics.js +160 -0
  30. package/scripts/lib/eval-metrics-store.js +218 -0
  31. package/scripts/lib/eval-quality.js +171 -0
  32. package/scripts/lib/eval-schemas.js +144 -0
  33. package/scripts/lib/eval-self-correct.js +106 -0
  34. package/scripts/lib/eval-validator.js +185 -0
  35. package/scripts/lib/jaccard-similarity.js +98 -0
  36. package/scripts/lib/longmemeval-runner.js +125 -0
  37. package/scripts/lib/rrf-fusion.js +175 -0
  38. package/scripts/lib/scoring-instintos.js +40 -3
  39. package/scripts/mcp-server/README.md +128 -0
  40. package/scripts/mcp-server/handlers.js +206 -0
  41. package/scripts/run-eval.js +141 -0
@@ -0,0 +1,160 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * benchmark-metrics.js — Métricas de retrieval para benchmark de memoria SWL.
5
+ *
6
+ * Patrón adoptado de `temp/agentmemory-main/benchmark/longmemeval-bench.ts`.
7
+ * Funciones puras zero-deps. Adaptado a IDs SWL (aprendizaje, sesion,
8
+ * instinto) en lugar de session_id de agentmemory.
9
+ *
10
+ * Métricas:
11
+ * - recallAt(k): 1.0 si al menos un gold ID está en los top-k, sino 0.0
12
+ * - precisionAt(k): proporción de top-k que son gold
13
+ * - mrr: Mean Reciprocal Rank (1/rank del primer gold encontrado)
14
+ * - ndcgAt(k): Normalized Discounted Cumulative Gain
15
+ *
16
+ * @module scripts/lib/benchmark-metrics
17
+ */
18
+
19
+ // ── helpers ───────────────────────────────────────────────────────────────────
20
+
21
+ function asSet(arr) {
22
+ return new Set(Array.isArray(arr) ? arr : []);
23
+ }
24
+
25
+ // ── métricas individuales ─────────────────────────────────────────────────────
26
+
27
+ /**
28
+ * Recall @ k: 1.0 si ALGÚN id gold está en los primeros k retrieved.
29
+ *
30
+ * @param {string[]} retrievedIds - IDs ordenados (mejor primero).
31
+ * @param {string[]} goldIds - IDs correctos esperados.
32
+ * @param {number} k
33
+ * @returns {number} 0 o 1
34
+ */
35
+ function recallAt(retrievedIds, goldIds, k) {
36
+ if (!Array.isArray(retrievedIds) || !Array.isArray(goldIds)) return 0;
37
+ const topK = new Set(retrievedIds.slice(0, k));
38
+ return goldIds.some(g => topK.has(g)) ? 1.0 : 0.0;
39
+ }
40
+
41
+ /**
42
+ * Precision @ k: proporción de los primeros k retrieved que son gold.
43
+ *
44
+ * @param {string[]} retrievedIds
45
+ * @param {string[]} goldIds
46
+ * @param {number} k
47
+ * @returns {number} en [0, 1]
48
+ */
49
+ function precisionAt(retrievedIds, goldIds, k) {
50
+ if (!Array.isArray(retrievedIds) || !Array.isArray(goldIds) || k <= 0) return 0;
51
+ const goldSet = asSet(goldIds);
52
+ const topK = retrievedIds.slice(0, k);
53
+ if (topK.length === 0) return 0;
54
+ const hits = topK.filter(id => goldSet.has(id)).length;
55
+ return hits / topK.length;
56
+ }
57
+
58
+ /**
59
+ * Mean Reciprocal Rank: 1/rank del primer gold encontrado, o 0 si ninguno.
60
+ *
61
+ * @param {string[]} retrievedIds
62
+ * @param {string[]} goldIds
63
+ * @returns {number} en [0, 1]
64
+ */
65
+ function mrr(retrievedIds, goldIds) {
66
+ if (!Array.isArray(retrievedIds) || !Array.isArray(goldIds)) return 0;
67
+ const goldSet = asSet(goldIds);
68
+ for (let i = 0; i < retrievedIds.length; i++) {
69
+ if (goldSet.has(retrievedIds[i])) {
70
+ return 1 / (i + 1);
71
+ }
72
+ }
73
+ return 0;
74
+ }
75
+
76
+ function dcg(relevancias, k) {
77
+ let suma = 0;
78
+ for (let i = 0; i < Math.min(k, relevancias.length); i++) {
79
+ suma += (relevancias[i] ? 1 : 0) / Math.log2(i + 2);
80
+ }
81
+ return suma;
82
+ }
83
+
84
+ /**
85
+ * Normalized Discounted Cumulative Gain @ k.
86
+ *
87
+ * @param {string[]} retrievedIds
88
+ * @param {string[]} goldIds
89
+ * @param {number} k
90
+ * @returns {number} en [0, 1]
91
+ */
92
+ function ndcgAt(retrievedIds, goldIds, k) {
93
+ if (!Array.isArray(retrievedIds) || !Array.isArray(goldIds) || k <= 0) return 0;
94
+ const goldSet = asSet(goldIds);
95
+ const rels = retrievedIds.slice(0, k).map(id => goldSet.has(id));
96
+ const idealRels = Array.from({ length: Math.min(k, goldSet.size) }, () => true);
97
+ const idealDCG = dcg(idealRels, k);
98
+ if (idealDCG === 0) return 0;
99
+ return dcg(rels, k) / idealDCG;
100
+ }
101
+
102
+ // ── agregados ─────────────────────────────────────────────────────────────────
103
+
104
+ /**
105
+ * Calcula el conjunto completo de métricas para una query.
106
+ *
107
+ * @param {string[]} retrievedIds
108
+ * @param {string[]} goldIds
109
+ * @returns {{ recall_at_5, recall_at_10, recall_at_20, mrr, ndcg_at_10, precision_at_5 }}
110
+ */
111
+ function calcularMetricas(retrievedIds, goldIds) {
112
+ return {
113
+ recall_at_5: recallAt(retrievedIds, goldIds, 5),
114
+ recall_at_10: recallAt(retrievedIds, goldIds, 10),
115
+ recall_at_20: recallAt(retrievedIds, goldIds, 20),
116
+ mrr: mrr(retrievedIds, goldIds),
117
+ ndcg_at_10: ndcgAt(retrievedIds, goldIds, 10),
118
+ precision_at_5: precisionAt(retrievedIds, goldIds, 5),
119
+ };
120
+ }
121
+
122
+ /**
123
+ * Promedia métricas sobre múltiples queries.
124
+ *
125
+ * @param {Array<object>} resultados - Array de objetos producidos por calcularMetricas().
126
+ * @returns {object} Promedios con campo `n` (cantidad de queries).
127
+ */
128
+ function promediar(resultados) {
129
+ if (!Array.isArray(resultados) || resultados.length === 0) {
130
+ return {
131
+ n: 0,
132
+ recall_at_5: 0,
133
+ recall_at_10: 0,
134
+ recall_at_20: 0,
135
+ mrr: 0,
136
+ ndcg_at_10: 0,
137
+ precision_at_5: 0,
138
+ };
139
+ }
140
+
141
+ const claves = ['recall_at_5', 'recall_at_10', 'recall_at_20', 'mrr', 'ndcg_at_10', 'precision_at_5'];
142
+ const promedio = { n: resultados.length };
143
+ for (const k of claves) {
144
+ const sum = resultados.reduce((a, r) => a + (r[k] || 0), 0);
145
+ promedio[k] = sum / resultados.length;
146
+ }
147
+ return promedio;
148
+ }
149
+
150
+ // ── exports ───────────────────────────────────────────────────────────────────
151
+
152
+ module.exports = {
153
+ recallAt,
154
+ precisionAt,
155
+ mrr,
156
+ ndcgAt,
157
+ dcg,
158
+ calcularMetricas,
159
+ promediar,
160
+ };
@@ -0,0 +1,218 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * eval-metrics-store.js — Persistencia agregada de métricas de evaluación.
5
+ *
6
+ * Patrón adoptado de `temp/agentmemory-main/src/eval/metrics-store.ts`.
7
+ * Adaptado a swl-ses: file-based en lugar de SQLite. Persiste:
8
+ * - JSONL append-only: `.planning/evolucion/eval-results.jsonl` (cada eval individual)
9
+ * - JSON agregado: `.planning/evolucion/eval-metrics.json` (totales por functionId)
10
+ *
11
+ * El JSONL preserva el detalle histórico (un evento por evaluación). El JSON
12
+ * agregado se recalcula incrementalmente: avg latency, avg quality, success
13
+ * rate por functionId. Lectura barata sin escanear todo el JSONL.
14
+ *
15
+ * Funciones puras donde es posible. Las funciones I/O usan escrituras atómicas
16
+ * (atomicWriteJSON) para `eval-metrics.json`. El JSONL usa appendFileSync
17
+ * (regla SWL: JSONL para alta frecuencia).
18
+ *
19
+ * @module scripts/lib/eval-metrics-store
20
+ */
21
+
22
+ const fs = require('fs');
23
+ const path = require('path');
24
+
25
+ let atomicWriteJSON;
26
+ try {
27
+ ({ atomicWriteJSON } = require('../../hooks/lib/atomic-write'));
28
+ } catch {
29
+ atomicWriteJSON = (p, o) => fs.writeFileSync(p, JSON.stringify(o, null, 2), 'utf8');
30
+ }
31
+
32
+ // ── constantes ────────────────────────────────────────────────────────────────
33
+
34
+ const DIR_EVOLUCION = path.join('.planning', 'evolucion');
35
+ const RUTA_JSONL = path.join(DIR_EVOLUCION, 'eval-results.jsonl');
36
+ const RUTA_AGREGADO = path.join(DIR_EVOLUCION, 'eval-metrics.json');
37
+
38
+ // ── helpers ───────────────────────────────────────────────────────────────────
39
+
40
+ function asegurarDir(baseDir) {
41
+ const dir = path.join(baseDir, DIR_EVOLUCION);
42
+ if (!fs.existsSync(dir)) {
43
+ fs.mkdirSync(dir, { recursive: true });
44
+ }
45
+ }
46
+
47
+ function leerAgregado(baseDir) {
48
+ const ruta = path.join(baseDir, RUTA_AGREGADO);
49
+ if (!fs.existsSync(ruta)) return {};
50
+ try {
51
+ return JSON.parse(fs.readFileSync(ruta, 'utf8'));
52
+ } catch {
53
+ return {};
54
+ }
55
+ }
56
+
57
+ // ── API pública ───────────────────────────────────────────────────────────────
58
+
59
+ /**
60
+ * Registra una evaluación completada.
61
+ *
62
+ * Append-only al JSONL + actualización incremental del agregado.
63
+ *
64
+ * @param {string} baseDir - Raíz del proyecto.
65
+ * @param {object} evento
66
+ * @param {string} evento.functionId - Identificador de la función evaluada.
67
+ * @param {number} evento.latencyMs
68
+ * @param {boolean} evento.success
69
+ * @param {number} [evento.qualityScore] - en [0, 100]
70
+ * @param {object} [evento.metadata]
71
+ * @returns {{ recorded: boolean, error?: string }}
72
+ */
73
+ function registrar(baseDir, evento) {
74
+ if (!evento || typeof evento.functionId !== 'string') {
75
+ return { recorded: false, error: 'functionId requerido' };
76
+ }
77
+
78
+ asegurarDir(baseDir);
79
+
80
+ const ts = new Date().toISOString();
81
+ const lineaJSONL = JSON.stringify({
82
+ timestamp: ts,
83
+ functionId: evento.functionId,
84
+ latencyMs: typeof evento.latencyMs === 'number' ? evento.latencyMs : 0,
85
+ success: Boolean(evento.success),
86
+ qualityScore: typeof evento.qualityScore === 'number' ? evento.qualityScore : null,
87
+ metadata: evento.metadata || null,
88
+ });
89
+
90
+ try {
91
+ fs.appendFileSync(path.join(baseDir, RUTA_JSONL), lineaJSONL + '\n', 'utf8');
92
+ } catch (err) {
93
+ return { recorded: false, error: 'JSONL append failed: ' + err.message };
94
+ }
95
+
96
+ // Actualizar agregado
97
+ try {
98
+ const agregado = leerAgregado(baseDir);
99
+ const fid = evento.functionId;
100
+ const m = agregado[fid] || {
101
+ functionId: fid,
102
+ totalCalls: 0,
103
+ successCount: 0,
104
+ failureCount: 0,
105
+ avgLatencyMs: 0,
106
+ avgQualityScore: 0,
107
+ qualityCallCounts: 0,
108
+ lastUpdatedAt: ts,
109
+ };
110
+
111
+ const prev = m.totalCalls;
112
+ m.totalCalls += 1;
113
+ m.avgLatencyMs = (m.avgLatencyMs * prev + (evento.latencyMs || 0)) / m.totalCalls;
114
+ if (evento.success) m.successCount += 1;
115
+ else m.failureCount += 1;
116
+
117
+ if (typeof evento.qualityScore === 'number') {
118
+ const prevQ = m.qualityCallCounts || 0;
119
+ m.avgQualityScore = (m.avgQualityScore * prevQ + evento.qualityScore) / (prevQ + 1);
120
+ m.qualityCallCounts = prevQ + 1;
121
+ }
122
+
123
+ m.lastUpdatedAt = ts;
124
+ agregado[fid] = m;
125
+ atomicWriteJSON(path.join(baseDir, RUTA_AGREGADO), agregado);
126
+ } catch (err) {
127
+ return { recorded: true, error: 'Aggregate update failed: ' + err.message };
128
+ }
129
+
130
+ return { recorded: true };
131
+ }
132
+
133
+ /**
134
+ * Lee las métricas agregadas para un functionId específico.
135
+ * @param {string} baseDir
136
+ * @param {string} functionId
137
+ * @returns {object|null}
138
+ */
139
+ function obtener(baseDir, functionId) {
140
+ const agregado = leerAgregado(baseDir);
141
+ return agregado[functionId] || null;
142
+ }
143
+
144
+ /**
145
+ * Lee todas las métricas agregadas.
146
+ * @param {string} baseDir
147
+ * @returns {object[]}
148
+ */
149
+ function obtenerTodos(baseDir) {
150
+ const agregado = leerAgregado(baseDir);
151
+ return Object.values(agregado);
152
+ }
153
+
154
+ /**
155
+ * Recorre el JSONL y reconstruye el agregado desde cero.
156
+ * Útil tras corrupción del agregado o auditoría histórica.
157
+ *
158
+ * @param {string} baseDir
159
+ * @returns {{ rebuilt: number, functions: number }}
160
+ */
161
+ function reconstruirAgregado(baseDir) {
162
+ const ruta = path.join(baseDir, RUTA_JSONL);
163
+ if (!fs.existsSync(ruta)) return { rebuilt: 0, functions: 0 };
164
+
165
+ const agregado = {};
166
+ let lineas = 0;
167
+ const contenido = fs.readFileSync(ruta, 'utf8');
168
+ for (const linea of contenido.split('\n')) {
169
+ if (!linea.trim()) continue;
170
+ let evento;
171
+ try { evento = JSON.parse(linea); } catch { continue; }
172
+
173
+ const fid = evento.functionId;
174
+ if (!fid) continue;
175
+ lineas++;
176
+
177
+ const m = agregado[fid] || {
178
+ functionId: fid,
179
+ totalCalls: 0,
180
+ successCount: 0,
181
+ failureCount: 0,
182
+ avgLatencyMs: 0,
183
+ avgQualityScore: 0,
184
+ qualityCallCounts: 0,
185
+ lastUpdatedAt: evento.timestamp,
186
+ };
187
+
188
+ const prev = m.totalCalls;
189
+ m.totalCalls += 1;
190
+ m.avgLatencyMs = (m.avgLatencyMs * prev + (evento.latencyMs || 0)) / m.totalCalls;
191
+ if (evento.success) m.successCount += 1;
192
+ else m.failureCount += 1;
193
+
194
+ if (typeof evento.qualityScore === 'number') {
195
+ const prevQ = m.qualityCallCounts || 0;
196
+ m.avgQualityScore = (m.avgQualityScore * prevQ + evento.qualityScore) / (prevQ + 1);
197
+ m.qualityCallCounts = prevQ + 1;
198
+ }
199
+
200
+ m.lastUpdatedAt = evento.timestamp;
201
+ agregado[fid] = m;
202
+ }
203
+
204
+ asegurarDir(baseDir);
205
+ atomicWriteJSON(path.join(baseDir, RUTA_AGREGADO), agregado);
206
+ return { rebuilt: lineas, functions: Object.keys(agregado).length };
207
+ }
208
+
209
+ // ── exports ───────────────────────────────────────────────────────────────────
210
+
211
+ module.exports = {
212
+ registrar,
213
+ obtener,
214
+ obtenerTodos,
215
+ reconstruirAgregado,
216
+ RUTA_JSONL,
217
+ RUTA_AGREGADO,
218
+ };
@@ -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
+ };