@saulwade/swl-ses 1.1.3 → 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.
- package/CLAUDE.md +5 -3
- package/README.md +3 -3
- package/bin/swl-mcp-server.js +187 -0
- package/habilidades/benchmark-memoria/SKILL.md +186 -0
- package/habilidades/contenedores-docker/SKILL.md +8 -1
- package/habilidades/datos-etl/SKILL.md +18 -1
- package/habilidades/eval-framework/SKILL.md +212 -0
- package/habilidades/memoria-busqueda/SKILL.md +24 -1
- package/habilidades/planear-fase/SKILL.md +299 -269
- package/habilidades/postgresql-experto/SKILL.md +24 -1
- package/habilidades/verificar-trabajo/SKILL.md +7 -1
- package/hooks/lib/evolution-tracker.js +65 -11
- package/hooks/lib/memory-search.js +44 -13
- package/hooks/sugerir-contribuir.js +226 -0
- package/manifiestos/hooks-config.json +9 -0
- package/manifiestos/modulos.json +36 -2
- package/manifiestos/perfiles.json +2 -1
- package/manifiestos/skills-lock.json +1 -1
- package/package.json +4 -3
- package/plugin.json +343 -343
- package/reglas/analisis-previo-tareas-grandes.md +172 -0
- package/reglas/arreglar-al-detectar.md +147 -0
- package/scripts/benchmark-memoria.js +167 -0
- package/scripts/detectar-aprendizajes-duplicados.js +151 -0
- package/scripts/lib/benchmark-metrics.js +160 -0
- package/scripts/lib/eval-metrics-store.js +218 -0
- package/scripts/lib/eval-quality.js +171 -0
- package/scripts/lib/eval-schemas.js +144 -0
- package/scripts/lib/eval-self-correct.js +106 -0
- package/scripts/lib/eval-validator.js +185 -0
- package/scripts/lib/jaccard-similarity.js +98 -0
- package/scripts/lib/longmemeval-runner.js +125 -0
- package/scripts/lib/rrf-fusion.js +175 -0
- package/scripts/lib/scoring-instintos.js +40 -3
- package/scripts/mcp-server/README.md +128 -0
- package/scripts/mcp-server/handlers.js +206 -0
- package/scripts/run-eval.js +141 -0
|
@@ -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
|
+
};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* jaccard-similarity.js — Métrica de Jaccard sobre conjuntos de tokens.
|
|
5
|
+
*
|
|
6
|
+
* Patrón adoptado de `temp/agentmemory-main/src/functions/auto-forget.ts`
|
|
7
|
+
* para detectar memorias contradictorias/duplicadas con vocabulario compartido.
|
|
8
|
+
*
|
|
9
|
+
* Jaccard(A, B) = |A ∩ B| / |A ∪ B|
|
|
10
|
+
*
|
|
11
|
+
* Propiedades:
|
|
12
|
+
* - Rango [0, 1]: 0 = sin overlap, 1 = idénticos.
|
|
13
|
+
* - Simétrico: J(A, B) = J(B, A).
|
|
14
|
+
* - Independiente de longitudes absolutas (ambos cortos pueden ser 1.0).
|
|
15
|
+
*
|
|
16
|
+
* Sin dependencias — Node stdlib only. Funciones puras.
|
|
17
|
+
*
|
|
18
|
+
* @module scripts/lib/jaccard-similarity
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
// ── constantes ────────────────────────────────────────────────────────────────
|
|
22
|
+
|
|
23
|
+
/** Longitud mínima de un token para ser considerado significativo. */
|
|
24
|
+
const MIN_TOKEN_LENGTH = 3;
|
|
25
|
+
|
|
26
|
+
/** Stop words en español que se excluyen del análisis. */
|
|
27
|
+
const STOP_WORDS = new Set([
|
|
28
|
+
'que', 'los', 'las', 'del', 'una', 'por', 'con', 'para', 'como',
|
|
29
|
+
'sin', 'mas', 'sus', 'lo', 'le', 'la', 'el', 'al', 'no', 'es',
|
|
30
|
+
'se', 'de', 'en', 'un', 'a', 'y', 'o', 'pero', 'cuando',
|
|
31
|
+
'donde', 'porque', 'desde', 'hasta', 'sobre', 'bajo', 'entre',
|
|
32
|
+
'esta', 'este', 'esto', 'esa', 'ese', 'eso', 'tras', 'durante',
|
|
33
|
+
'mediante', 'segun', 'asi', 'tan', 'ya', 'aun', 'aunque',
|
|
34
|
+
// English equivalents (frequently mixed in technical text)
|
|
35
|
+
'the', 'and', 'for', 'with', 'this', 'that', 'have', 'from',
|
|
36
|
+
'are', 'was', 'will', 'not', 'has', 'had', 'but', 'can',
|
|
37
|
+
]);
|
|
38
|
+
|
|
39
|
+
// ── funciones puras ───────────────────────────────────────────────────────────
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Convierte un texto en un Set de tokens significativos (lowercase, sin stop
|
|
43
|
+
* words, longitud mínima). Preserva acentos.
|
|
44
|
+
*
|
|
45
|
+
* @param {string} text
|
|
46
|
+
* @returns {Set<string>}
|
|
47
|
+
*/
|
|
48
|
+
function tokenize(text) {
|
|
49
|
+
if (!text || typeof text !== 'string') return new Set();
|
|
50
|
+
return new Set(
|
|
51
|
+
String(text)
|
|
52
|
+
.toLowerCase()
|
|
53
|
+
.replace(/[`*_~\[\](){}<>#"'\-.,;:!?\/\\]/g, ' ')
|
|
54
|
+
.split(/\s+/)
|
|
55
|
+
.filter(t => t.length >= MIN_TOKEN_LENGTH && !STOP_WORDS.has(t)),
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Jaccard similarity entre dos Sets.
|
|
61
|
+
*
|
|
62
|
+
* @param {Set} setA
|
|
63
|
+
* @param {Set} setB
|
|
64
|
+
* @returns {number} en [0, 1]
|
|
65
|
+
*/
|
|
66
|
+
function jaccard(setA, setB) {
|
|
67
|
+
if (!(setA instanceof Set) || !(setB instanceof Set)) return 0;
|
|
68
|
+
if (setA.size === 0 && setB.size === 0) return 0;
|
|
69
|
+
if (setA.size === 0 || setB.size === 0) return 0;
|
|
70
|
+
|
|
71
|
+
let intersection = 0;
|
|
72
|
+
for (const token of setA) {
|
|
73
|
+
if (setB.has(token)) intersection++;
|
|
74
|
+
}
|
|
75
|
+
const union = setA.size + setB.size - intersection;
|
|
76
|
+
return union === 0 ? 0 : intersection / union;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Conveniencia: jaccard sobre dos textos.
|
|
81
|
+
*
|
|
82
|
+
* @param {string} a
|
|
83
|
+
* @param {string} b
|
|
84
|
+
* @returns {number} en [0, 1]
|
|
85
|
+
*/
|
|
86
|
+
function similarity(a, b) {
|
|
87
|
+
return jaccard(tokenize(a), tokenize(b));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// ── exports ───────────────────────────────────────────────────────────────────
|
|
91
|
+
|
|
92
|
+
module.exports = {
|
|
93
|
+
tokenize,
|
|
94
|
+
jaccard,
|
|
95
|
+
similarity,
|
|
96
|
+
MIN_TOKEN_LENGTH,
|
|
97
|
+
STOP_WORDS,
|
|
98
|
+
};
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* longmemeval-runner.js — Adapter que ejecuta queries del benchmark contra
|
|
5
|
+
* `hooks/lib/memory-search` y devuelve métricas.
|
|
6
|
+
*
|
|
7
|
+
* Patrón adoptado de `temp/agentmemory-main/benchmark/longmemeval-bench.ts`.
|
|
8
|
+
* Adaptado: en lugar de cargar haystack desde el dataset, usa el estado
|
|
9
|
+
* actual del proyecto SWL (APRENDIZAJES.md, sesiones, instintos).
|
|
10
|
+
*
|
|
11
|
+
* El dataset es un JSONL donde cada línea es:
|
|
12
|
+
* {
|
|
13
|
+
* "question_id": "q-001",
|
|
14
|
+
* "question": "texto libre de la query",
|
|
15
|
+
* "gold_ids": ["apr-N", "ses-YYYY-MM-DD-HHMM"],
|
|
16
|
+
* "category": "decision" | "patron" | "anti-patron" | "gotcha" | ...,
|
|
17
|
+
* "status": "real" | "placeholder"
|
|
18
|
+
* }
|
|
19
|
+
*
|
|
20
|
+
* @module scripts/lib/longmemeval-runner
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const fs = require('fs');
|
|
24
|
+
const path = require('path');
|
|
25
|
+
|
|
26
|
+
const memorySearch = require('../../hooks/lib/memory-search');
|
|
27
|
+
const benchmarkMetrics = require('./benchmark-metrics');
|
|
28
|
+
|
|
29
|
+
// ── parser de dataset ─────────────────────────────────────────────────────────
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Parsea un archivo JSONL del dataset.
|
|
33
|
+
* @param {string} ruta
|
|
34
|
+
* @returns {object[]}
|
|
35
|
+
*/
|
|
36
|
+
function leerDataset(ruta) {
|
|
37
|
+
if (!fs.existsSync(ruta)) {
|
|
38
|
+
throw new Error(`Dataset no encontrado: ${ruta}`);
|
|
39
|
+
}
|
|
40
|
+
const contenido = fs.readFileSync(ruta, 'utf8');
|
|
41
|
+
const entries = [];
|
|
42
|
+
let lineNum = 0;
|
|
43
|
+
for (const linea of contenido.split('\n')) {
|
|
44
|
+
lineNum++;
|
|
45
|
+
if (!linea.trim()) continue;
|
|
46
|
+
if (linea.trim().startsWith('//')) continue; // comentarios
|
|
47
|
+
try {
|
|
48
|
+
entries.push(JSON.parse(linea));
|
|
49
|
+
} catch (err) {
|
|
50
|
+
throw new Error(`JSONL malformado en línea ${lineNum}: ${err.message}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return entries;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// ── ejecución de query individual ─────────────────────────────────────────────
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Ejecuta una query del benchmark contra memoria SWL y compara con gold.
|
|
60
|
+
*
|
|
61
|
+
* @param {string} baseDir - Raíz del proyecto.
|
|
62
|
+
* @param {object} entry - Una línea del dataset.
|
|
63
|
+
* @param {object} [opts]
|
|
64
|
+
* @param {number} [opts.limit=20] - Top-k a recuperar.
|
|
65
|
+
* @returns {object} Métricas + ids retrieved + entry original.
|
|
66
|
+
*/
|
|
67
|
+
function ejecutarEntry(baseDir, entry, opts = {}) {
|
|
68
|
+
const limit = opts.limit || 20;
|
|
69
|
+
const inicio = Date.now();
|
|
70
|
+
const resultados = memorySearch.search(baseDir, entry.question, { limit });
|
|
71
|
+
const latencyMs = Date.now() - inicio;
|
|
72
|
+
|
|
73
|
+
const retrievedIds = resultados.map(r => r.id);
|
|
74
|
+
const goldIds = Array.isArray(entry.gold_ids) ? entry.gold_ids : [];
|
|
75
|
+
const metricas = benchmarkMetrics.calcularMetricas(retrievedIds, goldIds);
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
question_id: entry.question_id || 'unknown',
|
|
79
|
+
question: entry.question,
|
|
80
|
+
category: entry.category || null,
|
|
81
|
+
status: entry.status || 'unknown',
|
|
82
|
+
retrievedIds,
|
|
83
|
+
goldIds,
|
|
84
|
+
metricas,
|
|
85
|
+
latencyMs,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Ejecuta el dataset completo y devuelve resultados + métricas agregadas.
|
|
91
|
+
*
|
|
92
|
+
* @param {string} baseDir
|
|
93
|
+
* @param {string} datasetPath
|
|
94
|
+
* @param {object} [opts]
|
|
95
|
+
* @returns {{ entries: object[], promedio: object, dataset: object }}
|
|
96
|
+
*/
|
|
97
|
+
function ejecutarDataset(baseDir, datasetPath, opts = {}) {
|
|
98
|
+
const entries = leerDataset(datasetPath);
|
|
99
|
+
const resultados = entries.map(e => ejecutarEntry(baseDir, e, opts));
|
|
100
|
+
const promedio = benchmarkMetrics.promediar(resultados.map(r => r.metricas));
|
|
101
|
+
|
|
102
|
+
// Estadísticas del dataset
|
|
103
|
+
const placeholderCount = entries.filter(e => e.status === 'placeholder').length;
|
|
104
|
+
const realCount = entries.filter(e => e.status === 'real').length;
|
|
105
|
+
const datasetMeta = {
|
|
106
|
+
total: entries.length,
|
|
107
|
+
real: realCount,
|
|
108
|
+
placeholder: placeholderCount,
|
|
109
|
+
significativo: realCount >= 30,
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
return {
|
|
113
|
+
entries: resultados,
|
|
114
|
+
promedio,
|
|
115
|
+
dataset: datasetMeta,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// ── exports ───────────────────────────────────────────────────────────────────
|
|
120
|
+
|
|
121
|
+
module.exports = {
|
|
122
|
+
leerDataset,
|
|
123
|
+
ejecutarEntry,
|
|
124
|
+
ejecutarDataset,
|
|
125
|
+
};
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* rrf-fusion.js — Reciprocal Rank Fusion para combinar streams de búsqueda.
|
|
5
|
+
*
|
|
6
|
+
* Patrón adoptado de `temp/agentmemory-main/src/state/hybrid-search.ts`. El
|
|
7
|
+
* algoritmo RRF combina rankings de múltiples sistemas de retrieval (BM25,
|
|
8
|
+
* vector, graph) sin requerir que sus scores sean comparables — solo importa
|
|
9
|
+
* la posición relativa (rank) en cada lista.
|
|
10
|
+
*
|
|
11
|
+
* Fórmula:
|
|
12
|
+
*
|
|
13
|
+
* RRF(d) = Σ_i w_i / (k + rank_i(d))
|
|
14
|
+
*
|
|
15
|
+
* donde:
|
|
16
|
+
* d = un documento candidato
|
|
17
|
+
* i = índice del stream (BM25, vector, graph, ...)
|
|
18
|
+
* w_i = peso del stream i (default 1.0 si no se especifica)
|
|
19
|
+
* rank_i(d) = posición 1-indexed de d en el stream i, o ∞ si no aparece
|
|
20
|
+
* k = constante de smoothing (default 60, estándar Cormack 2009)
|
|
21
|
+
*
|
|
22
|
+
* Propiedades:
|
|
23
|
+
* - Robust frente a magnitudes de score heterogéneas — solo usa rank.
|
|
24
|
+
* - Documentos que aparecen en múltiples streams reciben boost natural.
|
|
25
|
+
* - Documentos que aparecen solo una vez no son penalizados — su rank ∞ en
|
|
26
|
+
* otros streams contribuye 0.
|
|
27
|
+
* - k ≈ 60 minimiza el peso de ranks bajos (< 60 efectivos).
|
|
28
|
+
*
|
|
29
|
+
* Versus suma simple de scores:
|
|
30
|
+
* - No requiere normalización entre streams (BM25 vs vector cosine son
|
|
31
|
+
* incomparables).
|
|
32
|
+
* - Más resistente a outliers (un score muy alto en un stream no domina).
|
|
33
|
+
*
|
|
34
|
+
* Sin dependencias — Node stdlib only. Backward compatible: el caller puede
|
|
35
|
+
* mantener su lógica anterior y usar RRF solo cuando combine ≥2 streams.
|
|
36
|
+
*
|
|
37
|
+
* @module scripts/lib/rrf-fusion
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
// ── constantes ────────────────────────────────────────────────────────────────
|
|
41
|
+
|
|
42
|
+
/** Constante k del RRF estándar (Cormack et al., 2009). */
|
|
43
|
+
const RRF_K_DEFAULT = 60;
|
|
44
|
+
|
|
45
|
+
// ── funciones puras ───────────────────────────────────────────────────────────
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Construye un mapa `id → rank` desde un stream de resultados ordenados.
|
|
49
|
+
* Rank es 1-indexed: el primer elemento tiene rank 1.
|
|
50
|
+
* Si un id aparece varias veces, conserva el rank más bajo (mejor).
|
|
51
|
+
*
|
|
52
|
+
* @param {Array<{id: string}>} stream - Resultados ordenados (mejor primero).
|
|
53
|
+
* @returns {Map<string, number>} Mapa id → rank.
|
|
54
|
+
*/
|
|
55
|
+
function rankMap(stream) {
|
|
56
|
+
const map = new Map();
|
|
57
|
+
if (!Array.isArray(stream)) return map;
|
|
58
|
+
for (let i = 0; i < stream.length; i++) {
|
|
59
|
+
const item = stream[i];
|
|
60
|
+
if (!item || typeof item.id !== 'string') continue;
|
|
61
|
+
const rank = i + 1;
|
|
62
|
+
const previo = map.get(item.id);
|
|
63
|
+
if (previo === undefined || rank < previo) {
|
|
64
|
+
map.set(item.id, rank);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return map;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Score parcial del stream para un id dado.
|
|
72
|
+
* Si el id NO aparece en el stream, devuelve 0 (rank ∞).
|
|
73
|
+
*
|
|
74
|
+
* @param {Map<string, number>} map - Resultado de rankMap().
|
|
75
|
+
* @param {string} id
|
|
76
|
+
* @param {number} k
|
|
77
|
+
* @returns {number} contribución 1/(k + rank), o 0 si no aparece.
|
|
78
|
+
*/
|
|
79
|
+
function streamScore(map, id, k) {
|
|
80
|
+
const rank = map.get(id);
|
|
81
|
+
if (rank === undefined) return 0;
|
|
82
|
+
return 1 / (k + rank);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Reciprocal Rank Fusion: combina N streams de búsqueda en un ranking unificado.
|
|
87
|
+
*
|
|
88
|
+
* Cada stream es un array de objetos con al menos `{ id: string }`. La posición
|
|
89
|
+
* en el array determina el rank (1-indexed). Cualquier metadata extra (titulo,
|
|
90
|
+
* fecha, score, etc.) del primer stream donde aparece el id se preserva en el
|
|
91
|
+
* resultado.
|
|
92
|
+
*
|
|
93
|
+
* Si se proveen `weights`, se ponderan los streams. El array de pesos debe
|
|
94
|
+
* tener el mismo largo que `streams`. Si no se provee, todos los streams pesan
|
|
95
|
+
* 1.0. Pesos no positivos se tratan como 0 (efectivamente desactivan el stream).
|
|
96
|
+
*
|
|
97
|
+
* Si todos los pesos suman > 0, se normalizan a 1.0 para que el `combinedScore`
|
|
98
|
+
* resultante sea comparable entre invocaciones con distintos pesos.
|
|
99
|
+
*
|
|
100
|
+
* @param {Array<Array<object>>} streams - Lista de streams ordenados.
|
|
101
|
+
* @param {object} [opts]
|
|
102
|
+
* @param {number} [opts.k=60] - Constante k del RRF.
|
|
103
|
+
* @param {number[]} [opts.weights] - Pesos por stream (alineado con streams[]).
|
|
104
|
+
* @param {number} [opts.limit] - Limita la salida a N elementos top.
|
|
105
|
+
* @returns {Array<object>} Resultados combinados con `combinedScore`,
|
|
106
|
+
* ordenados descendente. Conserva metadata del primer stream donde apareció
|
|
107
|
+
* cada id.
|
|
108
|
+
*/
|
|
109
|
+
function rrfFusion(streams, opts = {}) {
|
|
110
|
+
if (!Array.isArray(streams) || streams.length === 0) return [];
|
|
111
|
+
|
|
112
|
+
const k = typeof opts.k === 'number' && opts.k > 0 ? opts.k : RRF_K_DEFAULT;
|
|
113
|
+
|
|
114
|
+
// Normalizar pesos
|
|
115
|
+
let weights;
|
|
116
|
+
if (Array.isArray(opts.weights) && opts.weights.length === streams.length) {
|
|
117
|
+
const positivos = opts.weights.map(w =>
|
|
118
|
+
typeof w === 'number' && w > 0 ? w : 0,
|
|
119
|
+
);
|
|
120
|
+
const total = positivos.reduce((a, b) => a + b, 0);
|
|
121
|
+
weights = total > 0 ? positivos.map(w => w / total) : positivos;
|
|
122
|
+
} else {
|
|
123
|
+
// Sin weights explícitos: todos iguales y normalizados (suman 1.0).
|
|
124
|
+
const efectivos = streams.filter(s => Array.isArray(s) && s.length > 0).length;
|
|
125
|
+
if (efectivos === 0) return [];
|
|
126
|
+
weights = streams.map(s =>
|
|
127
|
+
Array.isArray(s) && s.length > 0 ? 1 / efectivos : 0,
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Construir rankMap por stream + recolectar metadata por id
|
|
132
|
+
const maps = streams.map(rankMap);
|
|
133
|
+
const metadata = new Map(); // id → primer item visto
|
|
134
|
+
|
|
135
|
+
for (const stream of streams) {
|
|
136
|
+
if (!Array.isArray(stream)) continue;
|
|
137
|
+
for (const item of stream) {
|
|
138
|
+
if (!item || typeof item.id !== 'string') continue;
|
|
139
|
+
if (!metadata.has(item.id)) {
|
|
140
|
+
metadata.set(item.id, item);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Calcular combinedScore para cada id
|
|
146
|
+
const combined = [];
|
|
147
|
+
for (const id of metadata.keys()) {
|
|
148
|
+
let score = 0;
|
|
149
|
+
for (let i = 0; i < streams.length; i++) {
|
|
150
|
+
score += weights[i] * streamScore(maps[i], id, k);
|
|
151
|
+
}
|
|
152
|
+
if (score > 0) {
|
|
153
|
+
combined.push({
|
|
154
|
+
...metadata.get(id),
|
|
155
|
+
combinedScore: score,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
combined.sort((a, b) => b.combinedScore - a.combinedScore);
|
|
161
|
+
|
|
162
|
+
if (typeof opts.limit === 'number' && opts.limit > 0) {
|
|
163
|
+
return combined.slice(0, opts.limit);
|
|
164
|
+
}
|
|
165
|
+
return combined;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ── exports ───────────────────────────────────────────────────────────────────
|
|
169
|
+
|
|
170
|
+
module.exports = {
|
|
171
|
+
rrfFusion,
|
|
172
|
+
rankMap,
|
|
173
|
+
streamScore,
|
|
174
|
+
RRF_K_DEFAULT,
|
|
175
|
+
};
|