zelin-v6x / src /response-validator.js
Z User
v7.1: CRITICAL fixes β€” 20+ bugs from deep audit
5cef531
Raw History Blame Contribute Delete
36.6 kB
/**
* ============================================
* 🧠 response-validator.js β€” Neural Validator v2.0
* ============================================
* Sistema avanzado de validaciΓ³n SIN REGEX.
* Reemplaza todos los patrones regex con:
*
* CAPA 1: Token Analyzer β€” anΓ‘lisis estadΓ­stico de tokens
* - Detecta garbled text por distribuciΓ³n de caracteres
* - Detecta repeticiΓ³n por comparaciΓ³n de tokens adyacentes
* - Detecta mezcla de idiomas por diccionarios de palabras
*
* CAPA 2: Syntactic Analyzer β€” gramΓ‘tica espaΓ±ola vΓ­a Map/Set
* - Adjacency rules como tablas de lookup (no regex)
* - "nop" + verbo β†’ invΓ‘lido (via Map.has(), no /nop\s+(hay|es)/)
* - Diccionarios completos de verbos, artΓ­culos, preposiciones
*
* CAPA 3: Context Coherence β€” anΓ‘lisis de coherencia semΓ‘ntica
* - Word overlap entre pregunta y respuesta
* - Topic drift detection
* - Respuesta corta para pregunta compleja
*
* CAPA 4: Neural Judge β€” IA local como juez de calidad
* - Usa el modelo local (Qwen3-0.6B o Gemma 4 4B)
* - Pregunta: "ΒΏEsta respuesta es coherente y humana?"
* - Solo se activa si las capas 1-3 no son concluyentes
*
* CAPA 5: Auto-Correction Engine β€” correcciΓ³n sin regex
* - Diccionario de correcciones (Map lookups)
* - Adjacency rule fixes (tabla-driven)
* - Token-level processing
*
* PRINCIPIO: CERO regex. Todo es anΓ‘lisis de strings, tokens, y Maps/Sets.
*/
import { isLocalAIReady, ollamaChatDirect } from './local-ai.js';
// ═══════════════════════════════════════════════════════════════════════════════
// CAPA 1: TOKEN ANALYZER β€” AnΓ‘lisis estadΓ­stico de tokens
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Tokeniza texto en palabras, preservando puntuaciΓ³n separada.
* Sin regex β€” usa string operations puras.
*/
function tokenize(text) {
if (!text || typeof text !== 'string') return [];
const tokens = [];
let current = '';
for (let i = 0; i < text.length; i++) {
const ch = text[i];
// Separar por espacios y puntuaciΓ³n
if (ch === ' ' || ch === '\t' || ch === '\n') {
if (current) tokens.push(current);
current = '';
} else if (ch === ',' || ch === '.' || ch === '!' || ch === '?' ||
ch === ';' || ch === ':' || ch === '-' || ch === 'β€”') {
if (current) tokens.push(current);
// No guardamos puntuaciΓ³n como tokens separados para este anΓ‘lisis
current = '';
} else {
current += ch;
}
}
if (current) tokens.push(current);
return tokens;
}
/**
* Detecta si un token es "garbled" β€” no parece una palabra real.
* Criterios: ratio consonante/vocal, longitud, caracteres repetidos.
* Sin regex β€” anΓ‘lisis carΓ‘cter por carΓ‘cter.
*/
function isGarbledToken(token) {
if (!token || token.length < 2) return false;
const lower = token.toLowerCase();
let vowels = 0;
let consonants = 0;
let repeatedChars = 0;
let consecutiveConsonants = 0;
let maxConsecutiveConsonants = 0;
const VOWELS = new Set(['a', 'e', 'i', 'o', 'u', 'Γ‘', 'Γ©', 'Γ­', 'Γ³', 'ΓΊ', 'Γ±']);
for (let i = 0; i < lower.length; i++) {
const ch = lower[i];
if (VOWELS.has(ch)) {
vowels++;
consecutiveConsonants = 0;
} else if ((ch >= 'a' && ch <= 'z') || ch === 'Γ±') {
consonants++;
consecutiveConsonants++;
if (consecutiveConsonants > maxConsecutiveConsonants) {
maxConsecutiveConsonants = consecutiveConsonants;
}
}
// Detectar repeticiΓ³n del mismo carΓ‘cter
if (i > 0 && lower[i] === lower[i - 1]) {
repeatedChars++;
}
}
const total = vowels + consonants;
if (total === 0) return false;
// Caso 1: Solo consonantes, sin vocales (5+ consonantes = garbled)
if (vowels === 0 && consonants >= 5) return true;
// Caso 2: Racha de consonantes consecutivas sin vocales (8+ = garbled)
if (maxConsecutiveConsonants >= 8) return true;
// Caso 3: Ratio consonante/vocal extremo (> 4 consonantes por vocal)
if (vowels > 0 && consonants / vowels > 4) return true;
// Caso 4: Muchos caracteres repetidos (mΓ‘s del 50% del token)
if (repeatedChars > total * 0.5 && total > 3) return true;
return false;
}
/**
* Detecta repeticiΓ³n de tokens (misma palabra 3+ veces seguidas).
* Sin regex β€” comparaciΓ³n directa de tokens adyacentes.
*/
function hasTokenRepetition(tokens) {
for (let i = 2; i < tokens.length; i++) {
const a = tokens[i].toLowerCase();
const b = tokens[i - 1].toLowerCase();
const c = tokens[i - 2].toLowerCase();
if (a === b && b === c && a.length >= 2) {
return true;
}
}
return false;
}
/**
* Detecta repeticiΓ³n excesiva del mismo carΓ‘cter (4+ veces seguidas).
* Sin regex β€” contador secuencial.
*/
function hasExcessiveCharRepetition(text) {
// Set de caracteres que contamos para repeticiΓ³n (letras, no nΓΊmeros ni sΓ­mbolos)
const LETTERS = new Set('abcdefghijklmnopqrstuvwxyzÑéíóúñABCDEFGHIJKLMNOPQRSTUVWXYZΓΓ‰ΓΓ“ΓšΓ‘'.split(''));
let count = 1;
for (let i = 1; i < text.length; i++) {
if (text[i] === text[i - 1] && LETTERS.has(text[i])) {
count++;
if (count >= 5) return true;
} else {
count = 1;
}
}
return false;
}
/**
* Detecta mezcla de idiomas (inglΓ©s + espaΓ±ol) en la misma frase.
* Sin regex β€” usa diccionarios de palabras frecuentes.
*/
function hasLanguageMix(text) {
const EN_WORDS = new Set([
'the', 'is', 'are', 'and', 'but', 'with', 'this', 'that',
'have', 'from', 'not', 'was', 'were', 'been', 'will', 'would',
'could', 'should', 'can', 'may', 'might', 'shall', 'must',
'does', 'did', 'has', 'had', 'having', 'being',
]);
const ES_TRANSITIONS = new Set([
'porque', 'tambiΓ©n', 'sin embargo', 'ademΓ‘s', 'entonces',
'aunque', 'por lo tanto', 'no obstante', 'asimismo',
]);
const tokens = tokenize(text);
let hasEnglish = false;
let hasSpanishTransition = false;
for (const t of tokens) {
if (EN_WORDS.has(t.toLowerCase())) hasEnglish = true;
if (ES_TRANSITIONS.has(t.toLowerCase())) hasSpanishTransition = true;
}
return hasEnglish && hasSpanishTransition;
}
/**
* Detecta cΓ³digo JSON o URLs filtrados en la respuesta.
* Sin regex β€” string operations.
*/
function hasCodeLeak(text) {
const t = text.trim();
// JSON/code: empieza con { o [ y termina con } o ]
if ((t.startsWith('{') || t.startsWith('[')) &&
(t.endsWith('}') || t.endsWith(']'))) {
return true;
}
// URL suelta
if (t.startsWith('http://') || t.startsWith('https://')) {
return true;
}
return false;
}
/**
* Detecta emojis repetidos excesivamente.
* Sin regex β€” detecciΓ³n por rango Unicode.
*/
function hasExcessiveEmoji(text) {
let emojiCount = 0;
let lastEmojiStart = -1;
let lastEmojiLen = 0;
let sameEmojiRepeat = 0;
for (let i = 0; i < text.length; i++) {
const code = text.codePointAt(i);
// Rangos de emojis comunes
if ((code >= 0x1F600 && code <= 0x1F64F) || // emoticons
(code >= 0x1F300 && code <= 0x1F5FF) || // symbols & pictographs
(code >= 0x1F680 && code <= 0x1F6FF)) { // transport & map
emojiCount++;
const emojiLen = code > 0xFFFF ? 2 : 1;
if (i === lastEmojiStart + lastEmojiLen || i === lastEmojiStart + lastEmojiLen + 1) {
// Could be same emoji β€” check
sameEmojiRepeat++;
if (sameEmojiRepeat >= 3) return true;
} else {
sameEmojiRepeat = 1;
}
lastEmojiStart = i;
lastEmojiLen = emojiLen;
}
}
return false;
}
/**
* Capa 1 completa: analizar texto incoherente/garbled.
* Retorna { detected: boolean, reason: string }
*/
function analyzeGarbled(text) {
// Caracteres repetidos excesivos
if (hasExcessiveCharRepetition(text)) {
return { detected: true, reason: 'excessive_char_repetition' };
}
// Tokens garbled
const tokens = tokenize(text);
let garbledCount = 0;
for (const t of tokens) {
if (isGarbledToken(t)) garbledCount++;
}
// 1+ garbled token en un mensaje corto, o 2+ en uno largo
if (garbledCount >= 1 && (tokens.length <= 3 || garbledCount >= 2)) {
return { detected: true, reason: 'garbled_tokens' };
}
// RepeticiΓ³n de tokens
if (hasTokenRepetition(tokens)) {
return { detected: true, reason: 'token_repetition' };
}
// Mezcla de idiomas
if (hasLanguageMix(text)) {
return { detected: true, reason: 'language_mix' };
}
// Code/JSON leak
if (hasCodeLeak(text)) {
return { detected: true, reason: 'code_leak' };
}
// Emojis excesivos
if (hasExcessiveEmoji(text)) {
return { detected: true, reason: 'excessive_emoji' };
}
return { detected: false };
}
// ═══════════════════════════════════════════════════════════════════════════════
// CAPA 2: SYNTACTIC ANALYZER β€” GramΓ‘tica espaΓ±ola vΓ­a Map/Set
// ═══════════════════════════════════════════════════════════════════════════════
// Diccionarios completos de palabras espaΓ±olas para anΓ‘lisis sintΓ‘ctico
const VERBS = new Set([
'hay', 'es', 'estΓ‘', 'son', 'era', 'fue', 'ser', 'tiene', 'tengo', 'tienes',
'puede', 'puedo', 'puedes', 'voy', 'vas', 'va', 'van', 'sΓ©', 'sabes',
'quiero', 'quieres', 'debes', 'tienes', 'debo', 'estoy', 'estΓ‘s', 'estΓ‘n',
'hago', 'haces', 'hace', 'dan', 'das', 'di', 'dio', 'dirΓ©', 'dirΓ‘s',
'vendrΓ‘', 'vendrΓ‘n', 'vino', 'vieron', 'vio', 've', 'ven',
'sabe', 'sabemos', 'saben', 'sabΓ­a', 'supo',
'tenΓ­a', 'tuvo', 'tendrΓ©', 'tendrΓ‘s', 'tendrΓ‘',
'podΓ­a', 'pudo', 'podrΓ©', 'podrΓ‘s', 'podrΓ‘',
'querΓ­a', 'quiso', 'querrΓ©', 'querrΓ‘s', 'querrΓ‘',
'debΓ­a', 'debiΓ³', 'deberΓ©', 'deberΓ‘s', 'deberΓ‘',
'estaba', 'estuve', 'estarΓ©', 'estarΓ‘s', 'estarΓ‘',
'era', 'fui', 'fuiste', 'fueron', 'serΓ©', 'serΓ‘s', 'serΓ‘',
'he', 'has', 'ha', 'han', 'habΓ­a', 'habΓ­as', 'habΓ­an',
]);
const ARTICLES = new Set([
'el', 'la', 'los', 'las', 'un', 'una', 'unos', 'unas',
]);
const PREPOSITIONS = new Set([
'de', 'en', 'por', 'para', 'con', 'sin', 'sobre', 'entre',
'hacia', 'hasta', 'desde', 'contra', 'segΓΊn', 'durante',
'mediante', 'tras', 'bajo', 'cabe', 'so',
]);
const PRONOUNS = new Set([
'me', 'te', 'se', 'le', 'lo', 'la', 'les', 'nos', 'os',
'yo', 'tΓΊ', 'Γ©l', 'ella', 'nosotros', 'nosotras',
'vosotros', 'vosotras', 'ellos', 'ellas',
'este', 'esta', 'esto', 'ese', 'esa', 'eso',
'aquel', 'aquella', 'aquello',
'mi', 'tu', 'su', 'nuestro', 'nuestra', 'vuestro', 'vuestra',
'mis', 'tus', 'sus', 'nuestros', 'nuestras', 'vuestros', 'vuestras',
'que', 'quien', 'quienes', 'cual', 'cuales', 'cuyo', 'cuya',
]);
const CONJUNCTIONS = new Set([
'y', 'o', 'pero', 'sino', 'ni', 'aunque', 'porque', 'si',
'cuando', 'mientras', 'donde', 'como', 'segΓΊn',
'pues', 'luego', 'asΓ­', 'por', 'tanto',
]);
// ── Adjacency Rules: quΓ© palabras NO deben seguir a otras ────────────────────
// Estructura: Map<word, Set<words_that_should_not_follow>>
// "nop" no debe ir antes de verbos, artΓ­culos, preposiciones, pronombres
const BAD_FOLLOWERS = new Map();
// "nop" solo es vΓ‘lido como respuesta aislada. Nunca antes de verbo/artΓ­culo/etc.
const NOP_INVALID_FOLLOWERS = new Set([
...VERBS, ...ARTICLES, ...PREPOSITIONS, ...PRONOUNS,
'al', // contracciΓ³n a+el
]);
BAD_FOLLOWERS.set('nop', NOP_INVALID_FOLLOWERS);
BAD_FOLLOWERS.set('Nop', NOP_INVALID_FOLLOWERS);
BAD_FOLLOWERS.set('NOP', NOP_INVALID_FOLLOWERS);
// "sip" igual β€” solo como respuesta aislada
const SIP_INVALID_FOLLOWERS = new Set([
...VERBS, ...ARTICLES, ...PREPOSITIONS, ...PRONOUNS,
'al',
]);
BAD_FOLLOWERS.set('sip', SIP_INVALID_FOLLOWERS);
BAD_FOLLOWERS.set('Sip', SIP_INVALID_FOLLOWERS);
BAD_FOLLOWERS.set('SIP', SIP_INVALID_FOLLOWERS);
/**
* Analiza si hay combinaciones gramaticales incorrectas.
* Sin regex β€” tokeniza y busca en el Map de adjacency rules.
* Retorna { detected: boolean, reason: string, details: string }
*/
function analyzeGrammar(text) {
const tokens = tokenize(text);
for (let i = 0; i < tokens.length - 1; i++) {
const current = tokens[i].toLowerCase();
const next = tokens[i + 1].toLowerCase();
const invalidFollowers = BAD_FOLLOWERS.get(current);
if (invalidFollowers && invalidFollowers.has(next)) {
return {
detected: true,
reason: 'bad_adjacency',
details: `"${tokens[i]} ${tokens[i + 1]}" β€” "${tokens[i].toLowerCase()}" no debe ir antes de "${tokens[i + 1].toLowerCase()}"`,
};
}
}
return { detected: false };
}
// ═══════════════════════════════════════════════════════════════════════════════
// CAPA 3: CONTEXT COHERENCE β€” AnΓ‘lisis de coherencia semΓ‘ntica
// ═══════════════════════════════════════════════════════════════════════════════
// Frases que indican que la IA no entendiΓ³ o estΓ‘ confundida
const CONFUSION_STARTS = new Set([
'no entiendo', 'no comprendo', 'no estoy segura', 'no estoy seguro',
'no sΓ© de quΓ©', 'no tengo idea',
]);
const AI_SELF_REFERENCES = new Set([
'como tu ia', 'como tu ia,', 'como ia', 'como ia,',
'como asistente', 'como modelo', 'soy una ia', 'soy un bot',
'soy un modelo', 'como una ia', 'como una ia,',
]);
const GENERIC_RESPONSES = new Set([
'es una buena', 'es interesante', 'es importante', 'es cierto', 'es verdad',
]);
// Frases que revelan el system prompt
const PROMPT_LEAKS = new Set([
'IDENTIDAD IRROMPIBLE', 'REGLAS ABSOLUTAS', 'SEGURIDAD inmutable', 'MODO THINKING',
]);
/**
* Detecta si la respuesta muestra signos de incomprensiΓ³n.
* Sin regex β€” comparaciΓ³n de strings con startsWith/Includes.
*/
function analyzeMisunderstanding(text) {
const lower = text.toLowerCase().trim();
// IA admite confusiΓ³n genΓ©rica
for (const phrase of CONFUSION_STARTS) {
if (lower.startsWith(phrase)) {
return { detected: true, reason: 'confusion_admitted', details: phrase };
}
}
// IA se refiere a sΓ­ misma como IA/bot/asistente
for (const phrase of AI_SELF_REFERENCES) {
if (lower.startsWith(phrase)) {
return { detected: true, reason: 'ai_self_reference', details: phrase };
}
}
// Respuesta genΓ©rica irrelevante
for (const phrase of GENERIC_RESPONSES) {
if (lower.startsWith(phrase)) {
return { detected: true, reason: 'generic_irrelevant', details: phrase };
}
}
// La IA repite literalmente lo que dijo el usuario
if (lower.startsWith('tΓΊ dijiste') || lower.startsWith('tu dijiste') ||
lower.startsWith('tΓΊ dices') || lower.startsWith('tu dices') ||
lower.startsWith('tΓΊ preguntas') || lower.startsWith('tu preguntas')) {
// Solo si son las primeras palabras del mensaje
const firstSpace = lower.indexOf(' ');
if (firstSpace > 0 && firstSpace < 15) {
return { detected: true, reason: 'echoing_user', details: 'repite al usuario' };
}
}
// Leak del system prompt
for (const phrase of PROMPT_LEAKS) {
if (text.includes(phrase)) {
return { detected: true, reason: 'prompt_leak', details: phrase };
}
}
// Frases repetitivas del modelo cuando no sabe quΓ© decir
const REPETITIVE_STARTS = ['es que ', 'bueno es que ', 'pues es que ', 'mira es que '];
for (const start of REPETITIVE_STARTS) {
if (lower.startsWith(start)) {
return { detected: true, reason: 'repetitive_start', details: start.trim() };
}
}
return { detected: false };
}
/**
* Detecta si la pregunta del usuario es compleja
* (requiere mΓ‘s que un "sΓ­/no" como respuesta).
* Sin regex β€” bΓΊsqueda de palabras clave en Set.
*/
const QUESTION_WORDS = new Set([
'cΓ³mo', 'por quΓ©', 'cuΓ‘l', 'cuΓ‘les', 'cuΓ‘ndo', 'cuΓ‘nto',
'quΓ©', 'quiΓ©n', 'quiΓ©nes', 'dΓ³nde',
]);
const COMPLEX_VERBS = new Set([
'explica', 'analiza', 'compara', 'describe', 'cuenta',
]);
function isComplexQuestion(userMessage) {
if (!userMessage || userMessage.length < 20) return false;
const tokens = tokenize(userMessage);
for (const t of tokens) {
if (QUESTION_WORDS.has(t.toLowerCase())) return true;
if (COMPLEX_VERBS.has(t.toLowerCase())) return true;
}
// TambiΓ©n "di ... sobre" como patrΓ³n
for (let i = 0; i < tokens.length - 1; i++) {
if (tokens[i].toLowerCase() === 'di' &&
tokens.slice(i + 1).some(t => t.toLowerCase() === 'sobre')) {
return true;
}
}
return false;
}
/**
* Detecta si la respuesta hace eco del mensaje del usuario.
* Sin regex β€” comparaciΓ³n de substrings.
*/
function isEchoingUser(response, userMessage) {
if (!userMessage || userMessage.length < 15) return false;
const rLower = response.toLowerCase().trim();
const uLower = userMessage.toLowerCase().trim();
// Si los primeros 70% del mensaje del usuario (mΓ‘x 40 chars) aparecen al inicio de la respuesta
const checkLen = Math.min(Math.floor(uLower.length * 0.7), 40);
if (checkLen < 10) return false;
const userPrefix = uLower.slice(0, checkLen);
return rLower.startsWith(userPrefix);
}
/**
* Detecta si hay demasiados headers markdown (system prompt leak).
* Sin regex β€” conteo de lΓ­neas que empiezan con ##.
*/
function hasMarkdownHeaders(text) {
if (text.length < 500) return false;
let headerCount = 0;
const lines = text.split('\n');
for (const line of lines) {
if (line.startsWith('##') || line.startsWith('###')) {
headerCount++;
}
}
return headerCount > 3;
}
/**
* Capa 3 completa: analizar coherencia con el contexto.
*/
function analyzeCoherence(text, userMessage) {
// IncomprensiΓ³n
const misunderstanding = analyzeMisunderstanding(text);
if (misunderstanding.detected) {
return { valid: false, reason: 'misunderstanding', details: misunderstanding.details };
}
// Pregunta compleja con respuesta demasiado corta
if (userMessage && isComplexQuestion(userMessage) && text.length < 15) {
// Excepciones: respuestas cortas vΓ‘lidas para preguntas complejas
const VALID_SHORT = new Set(['ns', 'ni idea', 'no sΓ©', 'dame un momento', 'no se']);
const tLower = text.toLowerCase().trim();
if (!VALID_SHORT.has(tLower)) {
return { valid: false, reason: 'incomplete_for_question' };
}
}
// Eco del usuario
if (isEchoingUser(text, userMessage)) {
return { valid: false, reason: 'echoing_user' };
}
// System prompt leak via markdown headers
if (hasMarkdownHeaders(text)) {
return { valid: false, reason: 'system_prompt_leak' };
}
return { valid: true };
}
// ═══════════════════════════════════════════════════════════════════════════════
// CAPA 4: NEURAL JUDGE β€” IA local como juez de calidad
// ═══════════════════════════════════════════════════════════════════════════════
// Cache de resultados del Neural Judge para no repetir llamadas
const _judgeCache = new Map();
const JUDGE_CACHE_MAX = 50;
const JUDGE_CACHE_TTL = 60_000; // 1 minuto
/**
* Usa el modelo local como juez de calidad.
* Solo se llama si las capas 1-3 no son concluyentes.
* El modelo decide si la respuesta es coherente y humana.
*
* Retorna { pass: boolean, score: number, reason: string }
*/
async function neuralJudge(response, userMessage) {
// Check cache
const cacheKey = response.slice(0, 80);
const cached = _judgeCache.get(cacheKey);
if (cached && Date.now() - cached.ts < JUDGE_CACHE_TTL) {
return cached.result;
}
if (!isLocalAIReady()) {
// Sin modelo local, no podemos juzgar β€” asumir vΓ‘lido
return { pass: true, score: 7, reason: 'no_local_model' };
}
try {
const raw = await ollamaChatDirect([
{
role: 'system',
content: `Juez de calidad para un bot de Discord espaΓ±ol. EvalΓΊa si esta respuesta es coherente, natural y humana.
Criterios:
- ΒΏTiene sentido la respuesta dada la pregunta/mensaje?
- ΒΏHay palabras mal colocadas o frases sin sentido?
- ΒΏSuena como algo que dirΓ­a un humano real en Discord?
- ΒΏHay errores gramaticales graves en espaΓ±ol?
Responde SOLO JSON: {"pass": true/false, "score": 0-10, "reason": "breve explicaciΓ³n"}
pass=true si score >= 7.`,
},
{
role: 'user',
content: `Mensaje del usuario: "${(userMessage ?? '').slice(0, 150)}"
Respuesta a evaluar: "${response.slice(0, 300)}"`,
},
], 100, 5000);
// Parsear JSON del output del modelo
const jsonStart = raw.indexOf('{');
const jsonEnd = raw.lastIndexOf('}');
if (jsonStart === -1 || jsonEnd === -1) {
return { pass: true, score: 7, reason: 'judge_parse_fail' };
}
const result = JSON.parse(raw.slice(jsonStart, jsonEnd + 1));
// Cache
_judgeCache.set(cacheKey, { result, ts: Date.now() });
if (_judgeCache.size > JUDGE_CACHE_MAX) {
const firstKey = _judgeCache.keys().next().value;
_judgeCache.delete(firstKey);
}
return {
pass: result.pass === true || (typeof result.score === 'number' && result.score >= 7),
score: result.score ?? 7,
reason: result.reason ?? 'judge_evaluated',
};
} catch {
// Si el juez falla, no bloquear β€” asumir vΓ‘lido
return { pass: true, score: 7, reason: 'judge_error' };
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// CAPA 5: AUTO-CORRECTION ENGINE β€” CorrecciΓ³n sin regex
// ═══════════════════════════════════════════════════════════════════════════════
// Diccionario de correcciones: palabra incorrecta β†’ palabra correcta
const TYPO_FIXES = new Map([
['etsa', 'esta'],
['bine', 'bien'],
['cmoo', 'como'],
['sloo', 'solo'],
['oseaque', 'osea que'],
['tmbien', 'tambiΓ©n'],
['tambien', 'tambiΓ©n'], // sin acento β†’ con acento (a veces)
]);
// Correcciones de adjacency: "nop" + siguiente palabra β†’ quΓ© usar en vez
// Map<palabra, Map<siguiente_palabra, correcciΓ³n>>
const ADJACENCY_FIXES = new Map();
// "nop" seguido de verbo β†’ reemplazar "nop" por "no"
const NOP_FIXES = new Map();
for (const verb of VERBS) {
NOP_FIXES.set(verb, 'no'); // "nop hay" β†’ "no hay"
}
for (const art of ARTICLES) {
NOP_FIXES.set(art, 'no'); // "nop el" β†’ "no el"
}
for (const prep of PREPOSITIONS) {
NOP_FIXES.set(prep, 'no'); // "nop de" β†’ "no de"
}
for (const pron of PRONOUNS) {
NOP_FIXES.set(pron, 'no'); // "nop me" β†’ "no me"
}
NOP_FIXES.set('al', 'no');
ADJACENCY_FIXES.set('nop', NOP_FIXES);
ADJACENCY_FIXES.set('Nop', NOP_FIXES);
// "sip" seguido de verbo β†’ reemplazar "sip" por "sΓ­"
const SIP_FIXES = new Map();
for (const verb of VERBS) {
SIP_FIXES.set(verb, 'sΓ­');
}
for (const art of ARTICLES) {
SIP_FIXES.set(art, 'sΓ­');
}
for (const prep of PREPOSITIONS) {
SIP_FIXES.set(prep, 'sΓ­');
}
for (const pron of PRONOUNS) {
SIP_FIXES.set(pron, 'sΓ­');
}
SIP_FIXES.set('al', 'sΓ­');
ADJACENCY_FIXES.set('sip', SIP_FIXES);
ADJACENCY_FIXES.set('Sip', SIP_FIXES);
// Correcciones de abreviaturas expandidas: "pq" antes de artΓ­culo β†’ "porque"
const PQ_EXPAND_BEFORE = new Set([
'el', 'la', 'los', 'las', 'un', 'una', 'no', 'sΓ­',
'me', 'te', 'se', 'le', 'lo', 'nos', 'les',
]);
const TMB_EXPAND_BEFORE = new Set([
'el', 'la', 'los', 'las', 'un', 'una',
'me', 'te', 'se', 'le', 'lo', 'nos', 'les',
'hay', 'es', 'estΓ‘', 'son', 'era', 'fue',
'puedo', 'puedes', 'quiero', 'quieres', 'tengo', 'tienes',
]);
/**
* Auto-corrije el texto usando diccionarios y adjacency rules.
* Sin regex β€” procesamiento token por token.
*/
export function autoCorrect(text) {
if (!text || typeof text !== 'string') return text;
const tokens = tokenize(text);
if (tokens.length === 0) return text;
const corrected = [];
for (let i = 0; i < tokens.length; i++) {
const current = tokens[i];
const currentLower = current.toLowerCase();
// 1. CorrecciΓ³n de typos obvios (diccionario)
if (TYPO_FIXES.has(currentLower) && currentLower !== 'tambien') {
// Mantener capitalizaciΓ³n original
const fix = TYPO_FIXES.get(currentLower);
corrected.push(applyCapitalization(current, fix));
continue;
}
// 2. CorrecciΓ³n de adjacency rules ("nop hay" β†’ "no hay")
if (i < tokens.length - 1) {
const nextLower = tokens[i + 1].toLowerCase();
const adjacencyFix = ADJACENCY_FIXES.get(currentLower);
if (adjacencyFix && adjacencyFix.has(nextLower)) {
const replacement = adjacencyFix.get(nextLower);
corrected.push(replacement);
continue;
}
}
// 3. "pq" antes de artΓ­culo/verbo β†’ "porque"
if (currentLower === 'pq' && i < tokens.length - 1) {
const nextLower = tokens[i + 1].toLowerCase();
if (PQ_EXPAND_BEFORE.has(nextLower)) {
corrected.push('porque');
continue;
}
}
// 4. "tmb" antes de artΓ­culo/verbo β†’ "tambiΓ©n"
if (currentLower === 'tmb' && i < tokens.length - 1) {
const nextLower = tokens[i + 1].toLowerCase();
if (TMB_EXPAND_BEFORE.has(nextLower)) {
corrected.push('tambiΓ©n');
continue;
}
}
// No hay correcciΓ³n β€” mantener token original
corrected.push(current);
}
// Reconstruir texto con espacios
return rebuildText(text, corrected);
}
/**
* Aplica la capitalizaciΓ³n del original al fix.
* Si original empieza con mayΓΊscula, el fix tambiΓ©n.
*/
function applyCapitalization(original, fix) {
if (original.length > 0 && original[0] === original[0].toUpperCase() &&
original[0] !== original[0].toLowerCase()) {
return fix.charAt(0).toUpperCase() + fix.slice(1);
}
return fix;
}
/**
* Reconstruye el texto a partir de los tokens corregidos,
* intentando preservar los espacios originales.
*/
function rebuildText(original, correctedTokens) {
// Enfoque simple: unir con espacios, preservando estructura bΓ‘sica
// Si solo habΓ­a 1 token, devolverlo tal cual
if (correctedTokens.length === 0) return original;
if (correctedTokens.length === 1) return correctedTokens[0];
// Unir con espacios, pero detectar si habΓ­a puntuaciΓ³n cerca
let result = correctedTokens[0];
for (let i = 1; i < correctedTokens.length; i++) {
result += ' ' + correctedTokens[i];
}
return result;
}
// ═══════════════════════════════════════════════════════════════════════════════
// VALIDACIΓ“N PRINCIPAL β€” Integra las 4 capas
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Valida si una respuesta es coherente y de calidad suficiente para enviar.
* Sin regex β€” 100% anΓ‘lisis de tokens + diccionarios + Neural Judge.
* Retorna { valid: true } o { valid: false, reason: string, fix: string }
*/
export function validateResponse(response, userMessage = '', conversationContext = '') {
if (!response || typeof response !== 'string') {
return { valid: false, reason: 'empty_response', fix: 'retry' };
}
const r = response.trim();
// Respuesta vacΓ­a o casi vacΓ­a
if (r.length < 2) {
return { valid: false, reason: 'too_short', fix: 'retry' };
}
// Solo puntuaciΓ³n β€” verificar sin regex
const punctChars = new Set([' ', '.', ',', '!', '?', ';', ':', '-', '_', '…', 'Β‘', 'ΒΏ', '"', "'", '(', ')']);
let allPunct = true;
for (const ch of r) {
if (!punctChars.has(ch)) { allPunct = false; break; }
}
if (allPunct) {
return { valid: false, reason: 'punctuation_only', fix: 'retry' };
}
// Respuestas que son solo valores nulos (sin regex)
const nullValues = new Set(['error', 'null', 'undefined', 'true', 'false', '{}', '[]']);
if (nullValues.has(r.toLowerCase())) {
return { valid: false, reason: 'null_value', fix: 'retry' };
}
// Respuesta demasiado larga (system prompt repetition)
if (r.length > 2000) {
return { valid: false, reason: 'too_long', fix: 'retry_strict' };
}
// CAPA 1: Texto incoherente/garbled
const garbled = analyzeGarbled(r);
if (garbled.detected) {
return { valid: false, reason: 'garbled_text', fix: 'retry_strict' };
}
// CAPA 2: Combinaciones gramaticales incorrectas
const grammar = analyzeGrammar(r);
if (grammar.detected) {
return { valid: false, reason: 'bad_grammar', fix: 'auto_correct' };
}
// CAPA 3: Coherencia con el contexto
const coherence = analyzeCoherence(r, userMessage);
if (!coherence.valid) {
const fixMap = {
misunderstanding: 'retry_with_context',
echoing_user: 'retry_creative',
system_prompt_leak: 'retry_strict',
incomplete_for_question: 'retry_with_context',
};
return { valid: false, reason: coherence.reason, fix: fixMap[coherence.reason] ?? 'retry' };
}
return { valid: true };
}
// ═══════════════════════════════════════════════════════════════════════════════
// RETRY PROMPT GENERATOR
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Genera un prompt de retry mΓ‘s estricto segΓΊn el tipo de error.
*/
export function getRetryPrompt(validationResult, originalUserMessage = '') {
const { reason } = validationResult;
const BASE_RETRY = 'IMPORTANTE: Tu respuesta anterior fue rechazada por el sistema de calidad. ';
switch (reason) {
case 'garbled_text':
return BASE_RETRY + 'Generaste texto incoherente. Escribe de nuevo en español correcto, mÑximo 2 líneas, casual y directo. Piensa QUÉ quieres decir antes de escribirlo.';
case 'bad_grammar':
return BASE_RETRY + 'Tu respuesta tiene un error gramatical. En espaΓ±ol, "nop" se usa SOLO como respuesta aislada (sΓ­/no), nunca antes de un verbo o artΓ­culo. "sip" igual. Reescribe correctamente.';
case 'misunderstanding':
return BASE_RETRY + `Parece que no entendiste el mensaje. El usuario dijo: "${originalUserMessage.slice(0, 100)}". Lee con atenciΓ³n y responde directamente a lo que pregunta o dice.`;
case 'echoing_user':
return BASE_RETRY + 'EstΓ‘s repitiendo lo que dijo el usuario. No repitas sus palabras β€” responde con tus propias palabras de forma natural.';
case 'system_prompt_leak':
return BASE_RETRY + 'EstΓ‘s repitiendo partes del system prompt. NUNCA hagas eso. Responde solo al mensaje del usuario de forma natural.';
case 'incomplete_for_question':
return BASE_RETRY + `La pregunta requiere mΓ‘s que una respuesta corta. El usuario preguntΓ³: "${originalUserMessage.slice(0, 100)}". Responde de forma completa pero concisa (2-3 lΓ­neas).`;
default:
return BASE_RETRY + 'Responde de nuevo: espaΓ±ol casual, directo, mΓ‘ximo 2 lΓ­neas, sin repetir el mensaje del usuario.';
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// GUARD RESPONSE β€” Sistema completo de validaciΓ³n + correcciΓ³n + retry
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Sistema completo de validaciΓ³n + auto-correcciΓ³n + retry + Neural Judge.
* Se integra en el flujo de respuesta de Zelin.
*
* FLUJO:
* 1. Auto-corregir (capa 5 β€” problemas simples)
* 2. Validar con capas 1-3 (token + gramΓ‘tica + coherencia)
* 3. Si pasa β†’ devolver
* 4. Si no pasa y es auto-correctible β†’ verificar si la correcciΓ³n resolviΓ³
* 5. Si hay retryFn β†’ reintentar con prompt mΓ‘s estricto
* 6. Neural Judge (capa 4) β€” solo si las capas 1-3 son ambiguas
* 7. Fallback β€” devolver auto-corregido
*
* @param {string} response - La respuesta generada por la IA
* @param {string} userMessage - El mensaje del usuario
* @param {Function} retryFn - FunciΓ³n para re-generar con prompt modificado
* @param {number} maxRetries - MΓ‘ximo de reintentos (default 1)
* @returns {Promise<string>} - La respuesta validada y corregida
*/
export async function guardResponse(response, userMessage = '', retryFn = null, maxRetries = 1) {
// Paso 1: Auto-corregir primero (problemas simples)
let corrected = autoCorrect(response);
// Paso 2: Validar la respuesta corregida con capas 1-3
const validation = validateResponse(corrected, userMessage);
if (validation.valid) {
return corrected;
}
// Si es auto-correctible, verificar si la auto-correcciΓ³n resolviΓ³ el problema
if (validation.fix === 'auto_correct') {
const revalidation = validateResponse(corrected, userMessage);
if (revalidation.valid) {
console.log(`[NeuralGuard] Auto-corregido: ${validation.reason}`);
return corrected;
}
}
// Paso 3: Si hay funciΓ³n de retry y no es auto-correctible, reintentar
if (retryFn && maxRetries > 0) {
const retryPrompt = getRetryPrompt(validation, userMessage);
console.log(`[NeuralGuard] ❌ Respuesta rechazada: ${validation.reason} β€” reintentando...`);
try {
const retry = await retryFn(retryPrompt);
if (retry && retry.trim().length > 2) {
// Validar el retry tambiΓ©n (pero sin mΓ‘s reintentos)
const retryCorrected = autoCorrect(retry);
const retryValidation = validateResponse(retryCorrected, userMessage);
if (retryValidation.valid) {
console.log('[NeuralGuard] βœ… Retry exitoso');
return retryCorrected;
}
// Paso 4: Neural Judge β€” ΓΊltima instancia antes de fallback
// Si el retry no pasΓ³ las capas 1-3, preguntar al juez IA
console.log('[NeuralGuard] 🧠 Consultando Neural Judge...');
const judgeResult = await neuralJudge(retryCorrected, userMessage);
if (judgeResult.pass) {
console.log(`[NeuralGuard] βœ… Neural Judge aprobΓ³ (score=${judgeResult.score}): ${judgeResult.reason}`);
return retryCorrected;
}
console.log(`[NeuralGuard] ❌ Neural Judge rechazó (score=${judgeResult.score}): ${judgeResult.reason}`);
// Si el Neural Judge tambiΓ©n rechaza, usar auto-correcciΓ³n del original
console.log('[NeuralGuard] ⚠️ Retry también falló, usando auto-corrección del original');
}
} catch (e) {
console.warn('[NeuralGuard] Retry fallΓ³:', e.message);
}
}
// Paso 5: Fallback β€” devolver la versiΓ³n auto-corregida del original
// (mejor que nada, y la auto-correcciΓ³n ya arreglΓ³ lo obvio)
console.log(`[NeuralGuard] ⚠️ Usando respuesta auto-corregida (no se pudo re-generar): ${validation.reason}`);
return corrected || response;
}