@saulwade/swl-ses 1.3.8 → 1.4.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 +12 -4
- package/README.md +1 -1
- package/bin/swl-mcp-server.js +187 -187
- package/bin/swl-webhook-server.js +198 -0
- package/comandos/swl/.evolved.json +22 -22
- package/comandos/swl/adoptar-proyecto.md +21 -1
- package/comandos/swl/claudemd.md +14 -1
- package/comandos/swl/contribuir.md +233 -233
- package/comandos/swl/exportar-vault.md +108 -0
- package/comandos/swl/nuevo-proyecto.md +24 -2
- package/gateway/adapters/base.js +109 -0
- package/gateway/adapters/discord.js +167 -0
- package/gateway/adapters/email.js +221 -0
- package/gateway/adapters/slack.js +192 -0
- package/gateway/adapters/telegram.js +183 -0
- package/gateway/adapters/webhook.js +113 -0
- package/gateway/adapters/whatsapp.js +214 -0
- package/gateway/agent-executor.js +322 -0
- package/gateway/command-relay.js +271 -0
- package/gateway/cron/jobs.js +263 -0
- package/gateway/cron/scheduler.js +322 -0
- package/gateway/cron/store.js +335 -0
- package/gateway/index.js +320 -0
- package/gateway/lib/event-channel.js +191 -0
- package/gateway/session.js +131 -0
- package/gateway/webhook-server.js +324 -0
- package/habilidades/backend-production-resilience/SKILL.md +288 -288
- package/habilidades/benchmark-memoria/SKILL.md +186 -186
- package/habilidades/build-errors-nextjs/SKILL.md +55 -1
- package/habilidades/diagrama-arquitectura/assets/template.html +276 -276
- package/habilidades/doubt-driven-review/SKILL.md +171 -171
- package/habilidades/doubt-driven-review/recursos/EXAMPLES.md +130 -130
- package/habilidades/eval-framework/SKILL.md +212 -212
- package/habilidades/extractor-de-aprendizajes/SKILL.md +20 -10
- package/habilidades/harness-claude-code/SKILL.md +299 -299
- package/habilidades/infra-github-actions/SKILL.md +166 -166
- package/habilidades/legacy-code-rescue/SKILL.md +267 -267
- package/habilidades/manejo-errores/.evolved.json +8 -8
- package/habilidades/meta-skills-estandar/recursos/convencion-examples.md +93 -93
- package/habilidades/meta-skills-estandar/recursos/skills-as-agents.md +163 -163
- package/habilidades/nextjs-testing/SKILL.md +89 -5
- package/habilidades/node-experto/SKILL.md +37 -1
- package/habilidades/patrones-python/SKILL.md +229 -229
- package/habilidades/patrones-python/recursos/patrones-avanzados.md +469 -469
- package/habilidades/planear-fase/SKILL.md +319 -319
- package/habilidades/react-experto/SKILL.md +45 -4
- package/habilidades/release-semver/.evolved.json +8 -8
- package/habilidades/tdd-workflow/SKILL.md +36 -4
- package/habilidades/testing-python/SKILL.md +340 -340
- package/hooks/claudemd-bloat-detector.js +161 -161
- package/hooks/inyeccion-contexto.js +8 -3
- package/hooks/lib/agent-routing.js +107 -107
- package/hooks/lib/auto-consolidator.js +335 -335
- package/hooks/lib/error-classifier.js +308 -308
- package/hooks/lib/merkle-audit.js +96 -96
- package/hooks/lib/provenance-tracker.js +191 -191
- package/hooks/lib/rate-limit-ip.js +177 -0
- package/hooks/lib/rate-limit-tracker.js +253 -253
- package/hooks/lib/resource-quota.js +122 -122
- package/hooks/lib/retry-jitter.js +165 -165
- package/hooks/lib/skill-auditor.js +588 -588
- package/hooks/lib/sync-status.js +228 -228
- package/hooks/lib/taint-tracker.js +107 -107
- package/hooks/lib/text-similarity.js +241 -241
- package/hooks/lib/toon-compressor.js +245 -245
- package/hooks/lib/webhook-dedup.js +184 -0
- package/hooks/lib/webhook-verify.js +123 -0
- package/hooks/proteccion-rutas.js +120 -15
- package/hooks/registro-turnos.js +209 -209
- package/hooks/sugerir-regenerar-inventario.js +170 -170
- package/hooks/validar-formato-post-subagente.js +140 -140
- package/hooks/validar-memoria-hook.js +218 -218
- package/instintos/prompt-appendices.yaml +57 -57
- package/manifiestos/agent-output-schemas.json +57 -57
- package/manifiestos/modulos.json +1 -0
- package/manifiestos/skills-lock.json +34 -34
- package/package.json +5 -3
- package/plantillas/auditor-veto-template.md +105 -105
- package/plantillas/github-workflows/README.md +47 -47
- package/plantillas/github-workflows/release-please.yml +44 -44
- package/plantillas/github-workflows/swl-ci.yml +107 -107
- package/plantillas/github-workflows/swl-security.yml +51 -51
- package/plugin.json +1 -1
- package/reglas/analisis-previo-tareas-grandes.md +172 -172
- package/reglas/arreglar-al-detectar.md +147 -147
- package/reglas/fragmentos-compartidos.md +152 -152
- package/reglas/harness-claude-code.md +213 -213
- package/reglas/usar-context7.md +226 -226
- package/reglas/usar-sistema-swl.md +251 -0
- package/schemas/diary-entry.schema.json +80 -80
- package/scripts/benchmark-memoria.js +167 -167
- package/scripts/comandos/skills.js +251 -2
- package/scripts/configurar-branch-protection.js +418 -418
- package/scripts/detectar-aprendizajes-duplicados.js +151 -151
- package/scripts/field-report.js +199 -199
- package/scripts/generar-checklists-consolidados.js +273 -273
- package/scripts/generar-inventario.js +420 -420
- package/scripts/generar-matriz-lenguajes.js +271 -271
- package/scripts/lib/artefactos-python.js +43 -43
- package/scripts/lib/benchmark-metrics.js +160 -160
- package/scripts/lib/budget-enforcer.js +252 -252
- package/scripts/lib/configurar-ci.js +380 -380
- package/scripts/lib/contadores-inventario.js +217 -217
- package/scripts/lib/detectar-stack-detallado.js +307 -307
- package/scripts/lib/diary-entry.js +234 -234
- package/scripts/lib/eval-metrics-store.js +218 -218
- package/scripts/lib/eval-quality.js +171 -171
- package/scripts/lib/eval-schemas.js +144 -144
- package/scripts/lib/eval-self-correct.js +106 -106
- package/scripts/lib/eval-validator.js +185 -185
- package/scripts/lib/jaccard-similarity.js +98 -98
- package/scripts/lib/longmemeval-runner.js +125 -125
- package/scripts/lib/npm-version.js +261 -261
- package/scripts/lib/paquetes-conocidos.js +50 -50
- package/scripts/lib/prompt-builder.js +264 -264
- package/scripts/lib/rrf-fusion.js +175 -175
- package/scripts/lib/scoring-instintos.js +277 -277
- package/scripts/lib/semantic-search.js +252 -252
- package/scripts/limpiar-artefactos-python.js +131 -131
- package/scripts/mcp-server/README.md +128 -128
- package/scripts/mcp-server/handlers.js +206 -206
- package/scripts/migrar-csv-a-array.js +168 -168
- package/scripts/migrar-fase-dominio.js +201 -201
- package/scripts/publicar.js +511 -511
- package/scripts/run-eval.js +141 -141
- package/scripts/validar-manifest.js +195 -195
- package/scripts/validar-userland-vacio.js +110 -110
- package/scripts/verificar-release.js +110 -0
|
@@ -1,175 +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
|
-
};
|
|
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
|
+
};
|