@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.
- package/CLAUDE.md +2 -2
- 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 +33 -1
- package/manifiestos/perfiles.json +2 -1
- package/package.json +4 -3
- package/plugin.json +343 -343
- 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,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
|
+
};
|
|
@@ -39,6 +39,10 @@ const HARMFUL_PENALTY_WEIGHT = 0.5;
|
|
|
39
39
|
const PROVEN_CONFIDENCE_THRESHOLD = 0.7;
|
|
40
40
|
const ESTABLISHED_THRESHOLD = 0.5;
|
|
41
41
|
const PROVEN_EVIDENCE_THRESHOLD = 3;
|
|
42
|
+
// Modelo de reforzamiento por feedback positivo (estilo agentmemory/lessons.ts).
|
|
43
|
+
// Cada feedback positivo cierra un (1 - REINFORCEMENT_DECAY) = 10% del gap
|
|
44
|
+
// entre la confianza actual y 1.0 — diminishing returns naturales.
|
|
45
|
+
const REINFORCEMENT_DECAY = 0.9;
|
|
42
46
|
|
|
43
47
|
// ── helpers ───────────────────────────────────────────────────────────────────
|
|
44
48
|
|
|
@@ -98,7 +102,38 @@ function harmfulRatio(instinto) {
|
|
|
98
102
|
}
|
|
99
103
|
|
|
100
104
|
/**
|
|
101
|
-
* Confianza
|
|
105
|
+
* Confianza reforzada por feedback positivo acumulado.
|
|
106
|
+
*
|
|
107
|
+
* Aplica un modelo de diminishing returns inspirado en `lessons.ts` de
|
|
108
|
+
* agentmemory: cada feedback positivo cierra una fracción del gap entre la
|
|
109
|
+
* confianza actual y 1.0. Aplicado N veces sobre la confianza base:
|
|
110
|
+
*
|
|
111
|
+
* c_N = 1 - REINFORCEMENT_DECAY^N · (1 - c_0)
|
|
112
|
+
*
|
|
113
|
+
* Con `REINFORCEMENT_DECAY = 0.9`:
|
|
114
|
+
* - 1 feedback: c_0=0.5 → 0.55
|
|
115
|
+
* - 5 feedback: c_0=0.5 → 0.705
|
|
116
|
+
* - 10 feedback: c_0=0.5 → 0.826
|
|
117
|
+
* - 50 feedback: c_0=0.5 → 0.997
|
|
118
|
+
*
|
|
119
|
+
* Si no hay `helpful_count` (o es 0), devuelve la confianza base sin tocar.
|
|
120
|
+
* Backward compatible: instintos sin el campo siguen comportándose igual.
|
|
121
|
+
*
|
|
122
|
+
* No persiste el resultado — se computa on-demand desde `helpful_count`. Eso
|
|
123
|
+
* preserva el invariante "confidence original es estática".
|
|
124
|
+
*/
|
|
125
|
+
function reinforcedConfidence(instinto) {
|
|
126
|
+
const baseConfidence = clamp(instinto.confidence || 0, 0, 1);
|
|
127
|
+
const helpful = instinto.helpful_count || 0;
|
|
128
|
+
if (helpful <= 0) return baseConfidence;
|
|
129
|
+
return 1 - Math.pow(REINFORCEMENT_DECAY, helpful) * (1 - baseConfidence);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Confianza efectiva considerando reforzamiento, decay temporal y feedback
|
|
134
|
+
* negativo.
|
|
135
|
+
*
|
|
136
|
+
* effective = reinforced × decay − harmful_penalty
|
|
102
137
|
*
|
|
103
138
|
* @param {object} instinto
|
|
104
139
|
* @param {string|Date} [currentDate=now] — fecha de referencia
|
|
@@ -111,10 +146,10 @@ function effectiveConfidence(instinto, currentDate) {
|
|
|
111
146
|
|
|
112
147
|
const days = validatedAt ? daysBetween(validatedAt, now) : 0;
|
|
113
148
|
const decay = decayFactor(days, halfLife);
|
|
114
|
-
const
|
|
149
|
+
const reinforced = reinforcedConfidence(instinto);
|
|
115
150
|
const penalty = HARMFUL_PENALTY_WEIGHT * harmfulRatio(instinto);
|
|
116
151
|
|
|
117
|
-
return clamp(
|
|
152
|
+
return clamp(reinforced * decay - penalty, 0, 1);
|
|
118
153
|
}
|
|
119
154
|
|
|
120
155
|
/**
|
|
@@ -223,6 +258,7 @@ module.exports = {
|
|
|
223
258
|
daysBetween,
|
|
224
259
|
decayFactor,
|
|
225
260
|
harmfulRatio,
|
|
261
|
+
reinforcedConfidence,
|
|
226
262
|
effectiveConfidence,
|
|
227
263
|
shouldAutoDeprecate,
|
|
228
264
|
maturityState,
|
|
@@ -237,4 +273,5 @@ module.exports = {
|
|
|
237
273
|
PROVEN_CONFIDENCE_THRESHOLD,
|
|
238
274
|
ESTABLISHED_THRESHOLD,
|
|
239
275
|
PROVEN_EVIDENCE_THRESHOLD,
|
|
276
|
+
REINFORCEMENT_DECAY,
|
|
240
277
|
};
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
# swl-mcp-server — STUB EXPERIMENTAL
|
|
2
|
+
|
|
3
|
+
> ⚠ **NO USAR EN PRODUCCIÓN**. Este es un stub experimental que demuestra
|
|
4
|
+
> el patrón de exponer la memoria de swl-ses a clientes MCP externos. La
|
|
5
|
+
> implementación completa requiere trabajo adicional (auth, observabilidad,
|
|
6
|
+
> tests de integración, schema migration). Ver sección "Limitaciones" más
|
|
7
|
+
> abajo.
|
|
8
|
+
|
|
9
|
+
## Qué hace
|
|
10
|
+
|
|
11
|
+
`bin/swl-mcp-server.js` es un servidor MCP en modo stdio que expone 3
|
|
12
|
+
endpoints de solo lectura:
|
|
13
|
+
|
|
14
|
+
1. **`swl_memory_search`** — búsqueda hybrid sobre memoria SWL
|
|
15
|
+
(aprendizajes + sesiones + instintos) usando `hooks/lib/memory-search`
|
|
16
|
+
con RRF fusion.
|
|
17
|
+
2. **`swl_aprendizajes_recientes`** — últimos N aprendizajes de
|
|
18
|
+
`.planning/APRENDIZAJES.md`.
|
|
19
|
+
3. **`swl_instintos_activos`** — instintos con `effective_confidence ≥
|
|
20
|
+
umbral`.
|
|
21
|
+
|
|
22
|
+
El server lee el estado file-based de swl-ses tal como existe en `cwd`
|
|
23
|
+
(o el directorio especificado por `SWL_MCP_BASE_DIR`). NO escribe — solo
|
|
24
|
+
lectura.
|
|
25
|
+
|
|
26
|
+
## Cómo arrancar (para testing)
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
# Modo standalone (smoke test)
|
|
30
|
+
echo '{"jsonrpc":"2.0","id":1,"method":"initialize"}' | node bin/swl-mcp-server.js
|
|
31
|
+
|
|
32
|
+
# Output esperado en stdout:
|
|
33
|
+
# {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2024-11-05","capabilities":{"tools":{"listChanged":false}},"serverInfo":{"name":"swl-mcp-server","version":"0.1.0-experimental"}}}
|
|
34
|
+
|
|
35
|
+
# Listar herramientas
|
|
36
|
+
echo '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | node bin/swl-mcp-server.js
|
|
37
|
+
|
|
38
|
+
# Buscar memoria
|
|
39
|
+
echo '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"swl_memory_search","arguments":{"query":"RRF fusion","limit":3}}}' | node bin/swl-mcp-server.js
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Cómo configurar en clientes MCP (NO recomendado en producción)
|
|
43
|
+
|
|
44
|
+
### Cursor (~/.cursor/mcp.json)
|
|
45
|
+
|
|
46
|
+
```json
|
|
47
|
+
{
|
|
48
|
+
"mcpServers": {
|
|
49
|
+
"swl-memory": {
|
|
50
|
+
"command": "node",
|
|
51
|
+
"args": ["/ruta/absoluta/a/swl-ses/bin/swl-mcp-server.js"],
|
|
52
|
+
"env": {
|
|
53
|
+
"SWL_MCP_BASE_DIR": "/ruta/al/proyecto/que/quiero/recuperar"
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### Gemini CLI
|
|
61
|
+
|
|
62
|
+
Similar, agregando el server a la config del cliente que soporte MCP stdio.
|
|
63
|
+
|
|
64
|
+
### Claude Code (NO necesario)
|
|
65
|
+
|
|
66
|
+
Claude Code ya tiene acceso directo a los archivos de swl-ses dentro de
|
|
67
|
+
su propio runtime. NO usar el MCP server desde Claude Code en el mismo
|
|
68
|
+
proyecto — sería redundante y agregaría latencia.
|
|
69
|
+
|
|
70
|
+
## Limitaciones (lo que NO se hace en este stub)
|
|
71
|
+
|
|
72
|
+
| Limitación | Impacto | Cuándo se debe arreglar |
|
|
73
|
+
|---|---|---|
|
|
74
|
+
| **Sin auth** | Cualquier proceso con acceso al stdio puede leer toda la memoria | Antes de exponer en redes públicas o multi-usuario |
|
|
75
|
+
| **Sin rate limiting** | Cliente malicioso/buggy puede saturar lectura de archivos | Cuando se observen ≥1 incidentes de saturación |
|
|
76
|
+
| **Sin HTTP transport** | Solo stdio; no se puede conectar remotamente | Cuando el caso de uso requiera servidor de red |
|
|
77
|
+
| **Sin tests de integración** | Solo smoke tests manuales | Antes de v1.0 del MCP server |
|
|
78
|
+
| **Sin observabilidad / métricas** | Logs JSON a stderr son lo único que hay | Cuando se use en >1 cliente simultáneo |
|
|
79
|
+
| **Sin hot-reload** | Cambios en swl-ses no se reflejan hasta restart del server | Ya — el server lee files en cada call, así que SÍ se reflejan; documentado por completitud |
|
|
80
|
+
| **Sin caching** | Cada call lee files de disco | Cuando latencia sea problema (~10ms hoy) |
|
|
81
|
+
| **Sin schema versioning** | Si cambia formato de APRENDIZAJES.md, los handlers pueden romper | Cuando se introduzca breaking change en el formato |
|
|
82
|
+
| **Sin support de resources/prompts** | Solo tools | Cuando el caso de uso lo demande |
|
|
83
|
+
| **Sin paginación** | Resultados grandes se truncan a `limit` | Cuando se requiera browse de >50 entries |
|
|
84
|
+
| **Single-tenant** | Asume un solo proyecto por instancia | Multi-tenancy necesita rediseño |
|
|
85
|
+
|
|
86
|
+
## Trigger para implementación completa
|
|
87
|
+
|
|
88
|
+
**Hoy**: 0 instalaciones reportadas. Mantener como stub.
|
|
89
|
+
|
|
90
|
+
**Trigger para invertir esfuerzo en implementación robusta**: el usuario
|
|
91
|
+
reporta uso real consistente de ≥2 runtimes distintos (Cursor + Claude
|
|
92
|
+
Code, o Gemini + Claude Code, etc.) sobre el mismo proyecto SWL durante
|
|
93
|
+
≥1 mes. Sin esto, la inversión de ~25 horas en hardening del server
|
|
94
|
+
no se justifica.
|
|
95
|
+
|
|
96
|
+
## Diseño futuro (cuando se implemente completo)
|
|
97
|
+
|
|
98
|
+
1. **Auth**: API key estática + bearer token con scopes:
|
|
99
|
+
- `swl:memory:read` (búsqueda y lectura)
|
|
100
|
+
- `swl:memory:write` (crear aprendizajes desde MCP — requiere validación)
|
|
101
|
+
- `swl:instintos:write` (modificar confidence — alto riesgo)
|
|
102
|
+
2. **HTTP transport opcional**: además de stdio, ofrecer servidor HTTP/SSE
|
|
103
|
+
con TLS y CORS configurable.
|
|
104
|
+
3. **Telemetría**: requests por handler, latencia p50/p95, errores por
|
|
105
|
+
tipo. Persistir en `.planning/evolucion/mcp-metrics.jsonl`.
|
|
106
|
+
4. **Caching invalidable**: caché en memoria de las lecturas de
|
|
107
|
+
APRENDIZAJES.md / instintos con `mtime`-based invalidation.
|
|
108
|
+
5. **Schema versioning**: cada handler declara `schema_version`. El
|
|
109
|
+
cliente puede pedir un version range. Breaking changes bumpan major.
|
|
110
|
+
6. **Tests de integración**: arrancar el server contra una fixture y
|
|
111
|
+
ejecutar 50+ scenarios. Smoke en CI.
|
|
112
|
+
|
|
113
|
+
## Estado de seguridad (auditoría rápida del stub)
|
|
114
|
+
|
|
115
|
+
- ✓ NO expone credenciales ni archivos fuera de `baseDir`.
|
|
116
|
+
- ✓ NO ejecuta código (solo lee files y devuelve JSON).
|
|
117
|
+
- ✓ NO modifica archivos.
|
|
118
|
+
- ✗ NO valida que `baseDir` sea un proyecto SWL válido — un cliente
|
|
119
|
+
podría apuntarlo a un directorio arbitrario y leer cualquier
|
|
120
|
+
archivo `*.md` que llamemos `APRENDIZAJES.md`.
|
|
121
|
+
- ✗ NO sanitiza queries de búsqueda (los regex en `instintos.yaml` parser
|
|
122
|
+
son seguros, pero falta hardening).
|
|
123
|
+
- ✗ NO hay timeout — un proyecto enorme con miles de sesiones podría
|
|
124
|
+
hacer colgar el server.
|
|
125
|
+
|
|
126
|
+
Estos puntos son ACEPTABLES para un stub experimental usado por el
|
|
127
|
+
mantenedor en un proyecto propio. NO ACEPTABLES para uso multi-usuario
|
|
128
|
+
o expuesto a la red.
|