fivetech commited on
Commit
a1bf4fe
·
verified ·
1 Parent(s): c3bcdb4

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +171 -30
app.js CHANGED
@@ -35,7 +35,7 @@ const MODES = [
35
  { id: 'duel', name: '1 vs 1 — Duel', desc: 'Dos agentes se enfrentan en rondas alternas. Ideal para debates intensos.', live: true },
36
  { id: 'ffa', name: 'Free For All', desc: 'Hasta ocho agentes defienden sus propias posiciones.', live: true },
37
  { id: 'team', name: 'Team Battle', desc: 'Dos equipos de agentes colaboran y compiten entre sí (2v2, 3v3 o 4v4).', live: true },
38
- { id: 'tournament', name: 'Survival Tournament', desc: 'Eliminatorias: el ganador avanza hasta la gran final.', live: false },
39
  ];
40
  const STRATEGY_TEXT = {
41
  attack: 'Estrategia ATTACK: busca debilidades en los argumentos de tus rivales y atácalas con precisión. Señala exactamente qué afirmación es débil y por qué.',
@@ -157,7 +157,7 @@ function renderModes() {
157
  }));
158
  }
159
  function renderPicked() {
160
- const need = mode === 'duel' ? '2 agentes' : mode === 'team' ? 'equipos parejos: 4, 6 u 8 agentes' : '3-8 agentes';
161
  $('#picked-line').innerHTML = `<span class="chip">Modo: <b>${MODES.find(m => m.id === mode).name}</b></span>` +
162
  selected.map(id => { const a = agentById(id); return a ? `<span class="chip" style="border-color:${a.color}">${a.emoji} <b>${esc(a.name)}</b></span>` : ''; }).join('') +
163
  `<span class="chip" style="color:var(--muted)">necesitas ${need} — selecciona en «Agentes»</span>`;
@@ -276,7 +276,7 @@ async function ensureModel() {
276
  if (wllama && modelKey === url) return;
277
  $('#start-btn').disabled = true;
278
  setPill('loading', 'cargando ' + dispLabel + '…');
279
- if (key === 'mimo' && !CONFIG.modelUrl && !CONFIG.repo) setLoad(0, `⚠️ MiMo 9B: fallo conocido de generación en wllama 3.5.1 (en validación). Descargando ${m.file} de todos modos (ctx ${CONFIG.nCtx})…`);
280
  else setLoad(0, `Descargando ${m.file} (ctx ${CONFIG.nCtx})…`);
281
  try {
282
  if (wllama) await wllama.exit();
@@ -429,7 +429,8 @@ function addSystemMsg(text) {
429
  async function agentIntervention(agent, phase, round, extraInstr) {
430
  const strat = strategyOf(agent, round);
431
  const system = agent.system + ' ' + (STRATEGY_TEXT[strat] || '') + ' ' + RULES;
432
- const view = transcriptView(battle.events);
 
433
  const phaseInstr = {
434
  opening: 'Fase OPENING: presenta tu tesis inicial sobre el tema, con tu posición clara.',
435
  crossfire: 'Fase CROSSFIRE: reacciona a la última intervención; pregunta, presiona o responde según tu estrategia.',
@@ -459,11 +460,58 @@ async function agentIntervention(agent, phase, round, extraInstr) {
459
  div.classList.remove('streaming');
460
  if (stopRequested || !answer) { div.remove(); setPill('ready', modelKey ? 'listo' : 'sin modelo'); return null; }
461
  textEl.innerHTML = md(answer);
462
- battle.events.push({ id: 'ev_' + battle.events.length, round, phase, agent: agent.name, agentId: agent.id, content: answer, strategy: strat, ts: new Date().toISOString() });
 
 
463
  setPill('ready', 'listo');
464
  return answer;
465
  }
466
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
467
  function buildSteps(b) {
468
  const steps = [];
469
  b.participants.forEach((a, i) => steps.push({ phase: 'opening', round: 1, idx: i }));
@@ -491,8 +539,16 @@ async function runBattle() {
491
  for (let s = battle.resume.step || 0; s < battle.steps.length; s++) {
492
  if (stopRequested) { battle.resume = { step: s }; break; }
493
  const st = battle.steps[s];
 
 
 
 
 
 
 
494
  const a = battle.participants[st.idx];
495
- if (!a) continue;
 
496
  const key = st.phase + ':' + st.round;
497
  if (key !== lastKey) {
498
  renderPhaseTrack(PHASE_TRACK_MAP[st.phase]);
@@ -512,8 +568,11 @@ async function runBattle() {
512
  renderFighters(null);
513
  if (stopRequested) {
514
  addSystemMsg('⏸ Batalla en pausa. Pulsa START BATTLE para continuar donde se quedó.');
 
 
515
  } else if (!battle.winner) {
516
- await runJudging();
 
517
  }
518
  } finally {
519
  running = false;
@@ -522,19 +581,19 @@ async function runBattle() {
522
  }
523
 
524
  /* ================= JUDGES ================= */
525
- async function runJudging() {
526
  renderPhaseTrack('judging');
527
  addSystemMsg('⚖️ Los tres jueces evalúan de forma independiente…');
528
- const ps = battle.participants;
529
  const names = ps.map(a => a.name);
530
- const transcript = transcriptView(battle.events, 12000);
531
  const teamNote = battle.mode === 'team' ? '\nFormato por equipos: EQUIPO A = ' + ps.filter(a => a.team === 'A').map(a => a.name).join(', ') + '; EQUIPO B = ' + ps.filter(a => a.team === 'B').map(a => a.name).join(', ') : '';
532
- battle.scores = {}; // agentId -> criterion -> media de jueces
533
- battle.judgeReports = [];
534
- battle.heuristicEval = false; // true si alguna puntuación NO viene de JSON estructurado del modelo
535
- ps.forEach(a => battle.scores[a.id] = {});
536
  for (const j of JUDGES) {
537
- if (stopRequested) return;
538
  const critList = j.criteria.map(c => WEIGHTS.find(w => w[0] === c)[1]).join('" y "');
539
  const system = `Eres ${j.name}, juez de un torneo de debate (${j.desc}). Evalúas SOLO los criterios "${critList}". Eres estricto, independiente y no conoces las puntuaciones de otros jueces.`;
540
  const user = `Tema: ${battle.topic}\nParticipantes: ${names.join(', ')}${teamNote}\n\nTranscripción:\n${transcript}\n\n` +
@@ -554,23 +613,23 @@ async function runJudging() {
554
  j.criteria.forEach(c => {
555
  let v = parsed?.[a.name]?.[c];
556
  if (typeof v !== 'number' || isNaN(v)) {
557
- battle.heuristicEval = true;
558
- const mine = battle.events.filter(e => e.agentId === a.id);
559
  v = Math.min(10, 4 + mine.length + (mine.reduce((s, e) => s + e.content.length, 0) / 600));
560
  v = Math.round(v * 10) / 10;
561
  }
562
  v = Math.max(0, Math.min(10, v));
563
- const cur = battle.scores[a.id][c];
564
- battle.scores[a.id][c] = cur === undefined ? v : Math.round(((cur + v) / 2) * 10) / 10;
565
  });
566
  });
567
- battle.judgeReports.push({ judge: j.name, emoji: j.emoji, parsed, fallback: !parsed });
568
  addSystemMsg(`${j.emoji} ${j.name} ha entregado su evaluación`);
569
  }
570
  // HEAD JUDGE
571
  let verdict = null;
572
  try {
573
- const totals = ps.map(a => ({ name: a.name, total: totalScore(a.id) }));
574
  const system = 'Eres el Head Judge de un torneo de debate. Consolidas las evaluaciones de tres jueces y produces el veredicto final, con justificación breve y concreta.';
575
  const user = `Tema: ${battle.topic}\nPuntuaciones ponderadas totales: ${totals.map(t => `${t.name}: ${t.total}`).join(', ')}\n\n` +
576
  `Transcripción (resumen):\n${transcript.slice(0, 6000)}\n\n` +
@@ -582,15 +641,61 @@ async function runJudging() {
582
  verdict = extractJSON(out2);
583
  }
584
  } catch (e) { console.warn('head judge', e); }
585
- finalizeBattle(verdict);
 
 
586
  }
587
  function teamTotals() {
588
  if (!battle || battle.mode !== 'team') return null;
589
  const avg = t => { const ms = battle.participants.filter(a => a.team === t); return ms.length ? Math.round(ms.reduce((s, a) => s + totalScore(a.id), 0) / ms.length * 100) / 100 : 0; };
590
  return { A: avg('A'), B: avg('B') };
591
  }
592
- function totalScore(agentId) {
593
- const s = battle.scores[agentId] || {};
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
594
  let t = 0;
595
  WEIGHTS.forEach(([k, , w]) => { t += (s[k] ?? 5) * w / 100; });
596
  return Math.round(t * 100) / 100;
@@ -643,6 +748,30 @@ function finalizeBattle(verdict) {
643
  }
644
 
645
  /* ================= RESULTS ================= */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
646
  function renderResults(totals, winner, verdict) {
647
  const heur = !!battle.heuristicEval;
648
  $('#verdict-hero').innerHTML = `
@@ -701,6 +830,7 @@ function startBattle(topic) {
701
  const min = mode === 'duel' ? 2 : mode === 'team' ? 4 : 3;
702
  if (ps.length < min) { alert(`Selecciona al menos ${min} agentes en la pestaña Agentes.`); showView('roster'); return; }
703
  if (mode === 'team' && ps.length % 2) { alert('Team Battle necesita un número par de agentes (4, 6 u 8): equipos parejos.'); showView('roster'); return; }
 
704
  if (!topic) { $('#topic').focus(); return; }
705
  if (mode === 'team') {
706
  // asignación alterna por orden de selección y turnos entrelazados A1,B1,A2,B2…
@@ -713,8 +843,9 @@ function startBattle(topic) {
713
  id: 'match_' + Date.now(), topic, mode, rounds: parseInt($('#rounds').value) || 2,
714
  participants: ps, events: [], scores: {}, judgeReports: [],
715
  resume: { step: 0 }, steps: null, winner: null, winnerTeam: null, verdict: null,
716
- createdAt: new Date().toISOString(),
717
  };
 
718
  $('#battle-log').innerHTML = '';
719
  $('#challenge-input').value = '';
720
  showView('battle');
@@ -745,7 +876,12 @@ function userChallenge() {
745
  const text = $('#challenge-input').value.trim();
746
  if (!text || !battle) return;
747
  $('#challenge-input').value = '';
748
- const curStep = battle.steps ? battle.steps[Math.min(battle.resume.step || 0, battle.steps.length - 1)] : null;
 
 
 
 
 
749
  addEvent({ name: 'Tú', emoji: '⚡', color: '#8b5cf6' }, 'challenge', text, curStep ? curStep.round : 1, true);
750
  }
751
  $('#challenge-btn').addEventListener('click', userChallenge);
@@ -769,7 +905,7 @@ function renderHall() {
769
  return `<div class="match-item" data-match="${m.id}">
770
  <div class="mtopic">${esc(m.topic)}</div>
771
  <div class="mmeta">${MODES.find(x => x.id === m.mode)?.name || m.mode} · ${m.events.length} intervenciones · ${new Date(m.date).toLocaleString('es')}</div>
772
- <div class="mmeta">${m.heuristic ? '⚠️ sin evaluación fiable (no cuenta para el Hall)' : (m.winnerTeam ? '🛡️ Equipo ' + m.winnerTeam : '👑 ' + (w ? esc(w.name) : 'Empate'))}</div>
773
  <button class="btn ghost small" data-replay="${m.id}">▶ Replay</button>
774
  </div>`;
775
  }).join('') : '<p style="color:var(--muted);font-size:.85rem">Aún no hay batallas guardadas.</p>';
@@ -788,15 +924,20 @@ async function startReplay(matchId) {
788
  $('#battle-log').innerHTML = '';
789
  addSystemMsg(`▶ REPLAY — ${m.topic} (${new Date(m.date).toLocaleString('es')})`);
790
  if (replayTimer) clearInterval(replayTimer);
791
- let i = 0;
792
  replayTimer = setInterval(() => {
793
  if (i >= m.events.length) {
794
  clearInterval(replayTimer); replayTimer = null;
795
  const w = m.winner ? agentById(m.winner) : null;
796
- addSystemMsg(m.winnerTeam ? `🛡️ Ganador: Equipo ${m.winnerTeam}` : (w ? `👑 Ganador: ${w.name}` : '🤝 Empate'));
797
  return;
798
  }
799
  const ev = m.events[i++];
 
 
 
 
 
800
  const a = ev.agentId === 'user' ? { name: 'Tú', emoji: '⚡', color: '#8b5cf6' } : ps.find(x => x.id === ev.agentId) || agentById(ev.agentId) || { name: ev.agent, emoji: '🤖', color: '#888' };
801
  addEvent(a, ev.phase, ev.content, ev.round, ev.agentId === 'user');
802
  }, 1100);
@@ -808,7 +949,7 @@ function renderRoadmap() {
808
  { n: 1, name: 'Arena Foundation', tag: 'done', items: ['Estructura modular', 'Integración con el runtime (wllama)', 'Agent Manager', 'Arena State Manager', 'Sistema de turnos y fases', 'Modalidad 1 vs 1'] },
809
  { n: 2, name: 'Battle Experience', tag: 'done', items: ['Arena Lobby', 'Selección visual de agentes', 'Live Battle con streaming', 'Crossfire y refutaciones', 'Participación humana (Challenge Agent)'] },
810
  { n: 3, name: 'Intelligence System', tag: 'partial', items: ['Tres jueces independientes + Head Judge', 'Puntuaciones ponderadas', 'Informe de resultados', 'Pendiente: detector de contradicciones y repeticiones (Referee AI)'] },
811
- { n: 4, name: 'Tournament Mode', tag: 'partial', items: ['Free For All', 'Team Battle (2v2, 3v3, 4v4 con veredicto por equipos)', 'Pendiente: eliminatorias, rematches con estrategia revisada'] },
812
  { n: 5, name: 'Memory & Replay', tag: 'partial', items: ['Historial de competiciones (localStorage)', 'Replay de batallas', 'Pendiente: IndexedDB, exportación JSON/Markdown/PDF, memoria persistente de agentes'] },
813
  { n: 6, name: 'Premium Experience', tag: 'todo', items: ['Animaciones y sonidos', 'Efectos de competición', 'Sistema de logros completo', 'Personalización avanzada', 'Optimización WebGPU', 'Multi-Model Arena'] },
814
  ];
 
35
  { id: 'duel', name: '1 vs 1 — Duel', desc: 'Dos agentes se enfrentan en rondas alternas. Ideal para debates intensos.', live: true },
36
  { id: 'ffa', name: 'Free For All', desc: 'Hasta ocho agentes defienden sus propias posiciones.', live: true },
37
  { id: 'team', name: 'Team Battle', desc: 'Dos equipos de agentes colaboran y compiten entre sí (2v2, 3v3 o 4v4).', live: true },
38
+ { id: 'tournament', name: 'Survival Tournament', desc: 'Eliminatorias de 4 u 8 agentes: el ganador de cada duelo avanza hasta la gran final.', live: true },
39
  ];
40
  const STRATEGY_TEXT = {
41
  attack: 'Estrategia ATTACK: busca debilidades en los argumentos de tus rivales y atácalas con precisión. Señala exactamente qué afirmación es débil y por qué.',
 
157
  }));
158
  }
159
  function renderPicked() {
160
+ const need = mode === 'duel' ? '2 agentes' : mode === 'team' ? 'equipos parejos: 4, 6 u 8 agentes' : mode === 'tournament' ? '4 u 8 agentes' : '3-8 agentes';
161
  $('#picked-line').innerHTML = `<span class="chip">Modo: <b>${MODES.find(m => m.id === mode).name}</b></span>` +
162
  selected.map(id => { const a = agentById(id); return a ? `<span class="chip" style="border-color:${a.color}">${a.emoji} <b>${esc(a.name)}</b></span>` : ''; }).join('') +
163
  `<span class="chip" style="color:var(--muted)">necesitas ${need} — selecciona en «Agentes»</span>`;
 
276
  if (wllama && modelKey === url) return;
277
  $('#start-btn').disabled = true;
278
  setPill('loading', 'cargando ' + dispLabel + '…');
279
+ if (key === 'mimo' && !CONFIG.modelUrl && !CONFIG.repo) setLoad(0, `⚠️ MiMo 9B: fallo de generación observado en pruebas con wllama 3.5.1/3.8.1 (en validación). Descargando ${m.file} de todos modos (ctx ${CONFIG.nCtx})…`);
280
  else setLoad(0, `Descargando ${m.file} (ctx ${CONFIG.nCtx})…`);
281
  try {
282
  if (wllama) await wllama.exit();
 
429
  async function agentIntervention(agent, phase, round, extraInstr) {
430
  const strat = strategyOf(agent, round);
431
  const system = agent.system + ' ' + (STRATEGY_TEXT[strat] || '') + ' ' + RULES;
432
+ const tm = battle.tournament && battle.tournament.currentMatch != null ? battle.tournament.matches[battle.tournament.currentMatch] : null;
433
+ const view = transcriptView(tm ? tm.events : battle.events);
434
  const phaseInstr = {
435
  opening: 'Fase OPENING: presenta tu tesis inicial sobre el tema, con tu posición clara.',
436
  crossfire: 'Fase CROSSFIRE: reacciona a la última intervención; pregunta, presiona o responde según tu estrategia.',
 
460
  div.classList.remove('streaming');
461
  if (stopRequested || !answer) { div.remove(); setPill('ready', modelKey ? 'listo' : 'sin modelo'); return null; }
462
  textEl.innerHTML = md(answer);
463
+ const ev = { id: 'ev_' + battle.events.length, round, phase, agent: agent.name, agentId: agent.id, content: answer, strategy: strat, ts: new Date().toISOString() };
464
+ if (tm) { ev.match = battle.tournament.currentMatch; tm.events.push(ev); }
465
+ battle.events.push(ev);
466
  setPill('ready', 'listo');
467
  return answer;
468
  }
469
 
470
+ /* ---- Tournament: eliminatorias con pasos aplanados; la pausa/reanudación por pasos sigue funcionando ---- */
471
+ const TOURN_NAMES = { 4: ['Semifinal 1', 'Semifinal 2', 'Final'], 8: ['Cuartos 1', 'Cuartos 2', 'Cuartos 3', 'Cuartos 4', 'Semifinal 1', 'Semifinal 2', 'Final'] };
472
+ const TOURN_FEEDERS = { 4: [[0, 1]], 8: [[0, 1], [2, 3], [4, 5]] };
473
+ function setupTournament(b) {
474
+ const n = b.participants.length;
475
+ const names = TOURN_NAMES[n];
476
+ const matches = [];
477
+ for (let i = 0; i < n / 2; i++) matches.push({ name: names[i], a: 2 * i, b: 2 * i + 1, winner: null, judged: false, events: [] });
478
+ b.tournament = { size: n, matches, names, currentMatch: 0 };
479
+ // primera ronda completa encolada de entrada; las siguientes rondas se crean al conocerse los ganadores
480
+ b.steps = [];
481
+ for (let i = 0; i < n / 2; i++) b.steps.push(...tournamentMatchSteps(b, i));
482
+ }
483
+ function tournamentMatchSteps(b, mi) {
484
+ const m = b.tournament.matches[mi];
485
+ const steps = [{ banner: `🏟️ ${m.name}: ${m.a != null ? b.participants[m.a].name : '?'} vs ${m.b != null ? b.participants[m.b].name : '?'}`, match: mi }];
486
+ const pair = [m.a, m.b];
487
+ pair.forEach(idx => steps.push({ phase: 'opening', round: 1, idx, match: mi }));
488
+ for (let r = 1; r <= b.rounds; r++) {
489
+ pair.forEach(idx => steps.push({ phase: 'crossfire', round: r, idx, match: mi }));
490
+ pair.forEach(idx => steps.push({ phase: 'rebuttal', round: r, idx, match: mi }));
491
+ }
492
+ pair.forEach(idx => steps.push({ phase: 'closing', round: b.rounds, idx, match: mi }));
493
+ steps.push({ judge: mi });
494
+ return steps;
495
+ }
496
+ function tournamentAdvance(b) {
497
+ const t = b.tournament, n = t.size, names = t.names;
498
+ const nextIdx = t.matches.length;
499
+ if (nextIdx >= names.length) return false; // la final ya existe
500
+ const feeders = TOURN_FEEDERS[n][nextIdx - n / 2];
501
+ // solo crear la siguiente eliminatoria cuando sus dos alimentadores ya se jugaron
502
+ if (!t.matches[feeders[0]].judged || !t.matches[feeders[1]].judged) return false;
503
+ const wA = t.matches[feeders[0]].winner, wB = t.matches[feeders[1]].winner;
504
+ const m = { name: names[nextIdx], a: wA, b: wB, winner: null, judged: false, events: [] };
505
+ t.matches.push(m);
506
+ if (wA == null || wB == null) {
507
+ addSystemMsg(`⚠️ ${m.name} no puede disputarse: falta un ganador fiable de una ronda anterior.`);
508
+ m.judged = true; m.skipped = true;
509
+ b.steps.push({ judge: nextIdx });
510
+ } else {
511
+ b.steps.push(...tournamentMatchSteps(b, nextIdx));
512
+ }
513
+ return true;
514
+ }
515
  function buildSteps(b) {
516
  const steps = [];
517
  b.participants.forEach((a, i) => steps.push({ phase: 'opening', round: 1, idx: i }));
 
539
  for (let s = battle.resume.step || 0; s < battle.steps.length; s++) {
540
  if (stopRequested) { battle.resume = { step: s }; break; }
541
  const st = battle.steps[s];
542
+ if (st.banner) { addSystemMsg(st.banner); battle.resume = { step: s + 1 }; continue; }
543
+ if (st.judge !== undefined) {
544
+ await judgeTournamentMatch(st.judge);
545
+ if (stopRequested) { battle.resume = { step: s }; break; }
546
+ battle.resume = { step: s + 1 };
547
+ continue;
548
+ }
549
  const a = battle.participants[st.idx];
550
+ if (!a) { battle.resume = { step: s + 1 }; continue; }
551
+ if (battle.tournament && st.match !== undefined) battle.tournament.currentMatch = st.match;
552
  const key = st.phase + ':' + st.round;
553
  if (key !== lastKey) {
554
  renderPhaseTrack(PHASE_TRACK_MAP[st.phase]);
 
568
  renderFighters(null);
569
  if (stopRequested) {
570
  addSystemMsg('⏸ Batalla en pausa. Pulsa START BATTLE para continuar donde se quedó.');
571
+ } else if (battle.mode === 'tournament') {
572
+ finalizeTournament();
573
  } else if (!battle.winner) {
574
+ const jr = await runJudging();
575
+ if (jr) finalizeBattle(jr.verdict);
576
  }
577
  } finally {
578
  running = false;
 
581
  }
582
 
583
  /* ================= JUDGES ================= */
584
+ async function runJudging(pl, evs) {
585
  renderPhaseTrack('judging');
586
  addSystemMsg('⚖️ Los tres jueces evalúan de forma independiente…');
587
+ const ps = pl || battle.participants;
588
  const names = ps.map(a => a.name);
589
+ const transcript = transcriptView(evs || battle.events, 12000);
590
  const teamNote = battle.mode === 'team' ? '\nFormato por equipos: EQUIPO A = ' + ps.filter(a => a.team === 'A').map(a => a.name).join(', ') + '; EQUIPO B = ' + ps.filter(a => a.team === 'B').map(a => a.name).join(', ') : '';
591
+ const scores = {}; // agentId -> criterion -> media de jueces
592
+ const judgeReports = [];
593
+ let heuristicEval = false; // true si alguna puntuación NO viene de JSON estructurado del modelo
594
+ ps.forEach(a => scores[a.id] = {});
595
  for (const j of JUDGES) {
596
+ if (stopRequested) return null;
597
  const critList = j.criteria.map(c => WEIGHTS.find(w => w[0] === c)[1]).join('" y "');
598
  const system = `Eres ${j.name}, juez de un torneo de debate (${j.desc}). Evalúas SOLO los criterios "${critList}". Eres estricto, independiente y no conoces las puntuaciones de otros jueces.`;
599
  const user = `Tema: ${battle.topic}\nParticipantes: ${names.join(', ')}${teamNote}\n\nTranscripción:\n${transcript}\n\n` +
 
613
  j.criteria.forEach(c => {
614
  let v = parsed?.[a.name]?.[c];
615
  if (typeof v !== 'number' || isNaN(v)) {
616
+ heuristicEval = true;
617
+ const mine = (evs || battle.events).filter(e => e.agentId === a.id);
618
  v = Math.min(10, 4 + mine.length + (mine.reduce((s, e) => s + e.content.length, 0) / 600));
619
  v = Math.round(v * 10) / 10;
620
  }
621
  v = Math.max(0, Math.min(10, v));
622
+ const cur = scores[a.id][c];
623
+ scores[a.id][c] = cur === undefined ? v : Math.round(((cur + v) / 2) * 10) / 10;
624
  });
625
  });
626
+ judgeReports.push({ judge: j.name, emoji: j.emoji, parsed, fallback: !parsed });
627
  addSystemMsg(`${j.emoji} ${j.name} ha entregado su evaluación`);
628
  }
629
  // HEAD JUDGE
630
  let verdict = null;
631
  try {
632
+ const totals = ps.map(a => ({ name: a.name, total: totalScore(a.id, scores) }));
633
  const system = 'Eres el Head Judge de un torneo de debate. Consolidas las evaluaciones de tres jueces y produces el veredicto final, con justificación breve y concreta.';
634
  const user = `Tema: ${battle.topic}\nPuntuaciones ponderadas totales: ${totals.map(t => `${t.name}: ${t.total}`).join(', ')}\n\n` +
635
  `Transcripción (resumen):\n${transcript.slice(0, 6000)}\n\n` +
 
641
  verdict = extractJSON(out2);
642
  }
643
  } catch (e) { console.warn('head judge', e); }
644
+ // compat: modos no torneo mantienen el estado en battle
645
+ battle.scores = scores; battle.judgeReports = judgeReports; battle.heuristicEval = heuristicEval;
646
+ return { scores, judgeReports, verdict, heuristic: heuristicEval };
647
  }
648
  function teamTotals() {
649
  if (!battle || battle.mode !== 'team') return null;
650
  const avg = t => { const ms = battle.participants.filter(a => a.team === t); return ms.length ? Math.round(ms.reduce((s, a) => s + totalScore(a.id), 0) / ms.length * 100) / 100 : 0; };
651
  return { A: avg('A'), B: avg('B') };
652
  }
653
+ async function judgeTournamentMatch(mi) {
654
+ const m = battle.tournament.matches[mi];
655
+ if (m.judged || m.skipped) return;
656
+ const pair = [battle.participants[m.a], battle.participants[m.b]];
657
+ const jr = await runJudging(pair, m.events);
658
+ if (!jr) return; // pausa durante el juicio: se reintenta al reanudar
659
+ m.judged = true; m.scores = jr.scores; m.judgeReports = jr.judgeReports; m.verdict = jr.verdict; m.heuristic = jr.heuristic;
660
+ const tA = totalScore(pair[0].id, jr.scores), tB = totalScore(pair[1].id, jr.scores);
661
+ m.totalA = tA; m.totalB = tB;
662
+ let w = null;
663
+ if (!jr.heuristic) {
664
+ if (jr.verdict && jr.verdict.winner && jr.verdict.winner !== 'Empate') w = pair.find(a => a.name.toLowerCase() === String(jr.verdict.winner).toLowerCase()) || null;
665
+ if (!w && tA !== tB) w = tA > tB ? pair[0] : pair[1];
666
+ }
667
+ m.winner = w ? battle.participants.indexOf(w) : null;
668
+ addSystemMsg(w ? `✅ ${m.name}: avanza ${w.name} (${Math.max(tA, tB)} vs ${Math.min(tA, tB)})` : `⚠️ ${m.name}: sin ganador fiable (evaluación no disponible)`);
669
+ if (!jr.heuristic) {
670
+ pair.forEach(a => {
671
+ const st = stats[a.id] = stats[a.id] || { wins: 0, losses: 0, draws: 0, scoreSum: 0, matches: 0, awards: {} };
672
+ st.matches++; st.scoreSum += totalScore(a.id, jr.scores);
673
+ if (!w) st.draws++; else if (a.id === w.id) st.wins++; else st.losses++;
674
+ });
675
+ persistAll();
676
+ }
677
+ tournamentAdvance(battle);
678
+ }
679
+ function finalizeTournament() {
680
+ renderPhaseTrack('verdict');
681
+ const t = battle.tournament;
682
+ const finalM = t.matches[t.matches.length - 1];
683
+ const champ = finalM && finalM.winner != null ? battle.participants[finalM.winner] : null;
684
+ battle.winner = champ ? champ.id : null;
685
+ battle.verdict = finalM ? finalM.verdict : null;
686
+ battle.heuristicEval = t.matches.some(m => m.heuristic || m.skipped);
687
+ battle.finishedAt = new Date().toISOString();
688
+ matches.unshift({ id: battle.id, topic: battle.topic, mode: battle.mode, rounds: battle.rounds, participants: battle.participants.map(a => a.id),
689
+ events: battle.events, winner: battle.winner, heuristic: battle.heuristicEval,
690
+ tournament: t.matches.map(m => ({ name: m.name, a: m.a, b: m.b, winner: m.winner, totalA: m.totalA, totalB: m.totalB, heuristic: !!m.heuristic, skipped: !!m.skipped })),
691
+ date: battle.finishedAt });
692
+ if (matches.length > 10) matches.length = 10;
693
+ persistAll();
694
+ renderTournamentResults(champ);
695
+ showView('results');
696
+ }
697
+ function totalScore(agentId, scores) {
698
+ const s = (scores || battle.scores || {})[agentId] || {};
699
  let t = 0;
700
  WEIGHTS.forEach(([k, , w]) => { t += (s[k] ?? 5) * w / 100; });
701
  return Math.round(t * 100) / 100;
 
748
  }
749
 
750
  /* ================= RESULTS ================= */
751
+ function renderTournamentResults(champ) {
752
+ const t = battle.tournament;
753
+ const heur = battle.heuristicEval;
754
+ $('#verdict-hero').innerHTML = `
755
+ <div class="crown">${champ ? '🏆' : '⚠️'}</div>
756
+ <h1 style="font-size:1.8rem;font-weight:900">${champ ? `<span style="color:${champ.color}">${champ.emoji} ${esc(champ.name)}</span> — CAMPEÓN DEL TORNEO` : '⚠️ Torneo sin campeón fiable'}</h1>
757
+ <p style="color:var(--muted);margin-top:8px;font-size:.9rem">${esc(battle.topic)}</p>
758
+ ${heur ? `<p style="max-width:660px;margin:12px auto 0;font-size:.88rem;line-height:1.6;color:#f59e0b">Alguna eliminatoria no tuvo evaluación estructurada del modelo. Las rondas sin evaluación fiable no cuentan para el Hall of Fame ni otorgan premios.</p>` : ''}`;
759
+ document.querySelector('#mech-metrics')?.remove();
760
+ $('#score-table').innerHTML = `
761
+ <tr><th>Eliminatoria</th><th>Enfrentamiento</th><th>Resultado</th></tr>
762
+ ${t.matches.map(m => {
763
+ const an = m.a != null ? battle.participants[m.a].name : '?', bn = m.b != null ? battle.participants[m.b].name : '?';
764
+ const res = m.skipped ? '<span style="color:var(--muted)">no disputada</span>'
765
+ : m.heuristic ? '<span style="color:#f59e0b">sin ganador fiable</span>'
766
+ : m.winner != null ? `${m.totalA} — ${m.totalB} → <b>${esc(battle.participants[m.winner].name)}</b>` : '<span style="color:var(--muted)">empate</span>';
767
+ return `<tr><td>${esc(m.name)}</td><td>${esc(an)} vs ${esc(bn)}</td><td>${res}</td></tr>`;
768
+ }).join('')}`;
769
+ $('#judge-cards').innerHTML = t.matches.filter(m => m.judgeReports).map(m =>
770
+ `<div class="judge-card"><h4>⚖️ ${esc(m.name)}</h4><p>${m.heuristic ? 'Evaluación heurística (respuesta no estructurada).' : (m.verdict?.justification ? esc(m.verdict.justification) : 'Veredicto por puntuación ponderada.')}</p></div>`).join('');
771
+ $('#awards').innerHTML = champ && !heur
772
+ ? `<span class="award">🏆 ${esc(champ.name)} — Campeón del Torneo</span>`
773
+ : '<span class="award">⚠️ Sin premios: evaluación no disponible en alguna ronda</span>';
774
+ }
775
  function renderResults(totals, winner, verdict) {
776
  const heur = !!battle.heuristicEval;
777
  $('#verdict-hero').innerHTML = `
 
830
  const min = mode === 'duel' ? 2 : mode === 'team' ? 4 : 3;
831
  if (ps.length < min) { alert(`Selecciona al menos ${min} agentes en la pestaña Agentes.`); showView('roster'); return; }
832
  if (mode === 'team' && ps.length % 2) { alert('Team Battle necesita un número par de agentes (4, 6 u 8): equipos parejos.'); showView('roster'); return; }
833
+ if (mode === 'tournament' && ps.length !== 4 && ps.length !== 8) { alert('Survival Tournament necesita exactamente 4 u 8 agentes.'); showView('roster'); return; }
834
  if (!topic) { $('#topic').focus(); return; }
835
  if (mode === 'team') {
836
  // asignación alterna por orden de selección y turnos entrelazados A1,B1,A2,B2…
 
843
  id: 'match_' + Date.now(), topic, mode, rounds: parseInt($('#rounds').value) || 2,
844
  participants: ps, events: [], scores: {}, judgeReports: [],
845
  resume: { step: 0 }, steps: null, winner: null, winnerTeam: null, verdict: null,
846
+ tournament: null, createdAt: new Date().toISOString(),
847
  };
848
+ if (mode === 'tournament') setupTournament(battle);
849
  $('#battle-log').innerHTML = '';
850
  $('#challenge-input').value = '';
851
  showView('battle');
 
876
  const text = $('#challenge-input').value.trim();
877
  if (!text || !battle) return;
878
  $('#challenge-input').value = '';
879
+ let curStep = null;
880
+ if (battle.steps) {
881
+ for (let k = Math.min(battle.resume.step || 0, battle.steps.length - 1); k >= 0; k--) {
882
+ if (battle.steps[k].phase) { curStep = battle.steps[k]; break; }
883
+ }
884
+ }
885
  addEvent({ name: 'Tú', emoji: '⚡', color: '#8b5cf6' }, 'challenge', text, curStep ? curStep.round : 1, true);
886
  }
887
  $('#challenge-btn').addEventListener('click', userChallenge);
 
905
  return `<div class="match-item" data-match="${m.id}">
906
  <div class="mtopic">${esc(m.topic)}</div>
907
  <div class="mmeta">${MODES.find(x => x.id === m.mode)?.name || m.mode} · ${m.events.length} intervenciones · ${new Date(m.date).toLocaleString('es')}</div>
908
+ <div class="mmeta">${m.heuristic ? '⚠️ sin evaluación fiable (no cuenta para el Hall)' : (m.mode === 'tournament' ? '🏆 Campeón: ' + (w ? esc(w.name) : '—') : m.winnerTeam ? '🛡️ Equipo ' + m.winnerTeam : '👑 ' + (w ? esc(w.name) : 'Empate'))}</div>
909
  <button class="btn ghost small" data-replay="${m.id}">▶ Replay</button>
910
  </div>`;
911
  }).join('') : '<p style="color:var(--muted);font-size:.85rem">Aún no hay batallas guardadas.</p>';
 
924
  $('#battle-log').innerHTML = '';
925
  addSystemMsg(`▶ REPLAY — ${m.topic} (${new Date(m.date).toLocaleString('es')})`);
926
  if (replayTimer) clearInterval(replayTimer);
927
+ let i = 0, lastMatch = null;
928
  replayTimer = setInterval(() => {
929
  if (i >= m.events.length) {
930
  clearInterval(replayTimer); replayTimer = null;
931
  const w = m.winner ? agentById(m.winner) : null;
932
+ addSystemMsg(m.mode === 'tournament' ? (w ? `🏆 Campeón: ${w.name}` : '⚠️ Torneo sin campeón fiable') : m.winnerTeam ? `🛡️ Ganador: Equipo ${m.winnerTeam}` : (w ? `👑 Ganador: ${w.name}` : '🤝 Empate'));
933
  return;
934
  }
935
  const ev = m.events[i++];
936
+ if (m.mode === 'tournament' && ev.match !== undefined && ev.match !== lastMatch) {
937
+ lastMatch = ev.match;
938
+ const tm = m.tournament && m.tournament[ev.match];
939
+ if (tm) addSystemMsg(`🏟️ ${tm.name}`);
940
+ }
941
  const a = ev.agentId === 'user' ? { name: 'Tú', emoji: '⚡', color: '#8b5cf6' } : ps.find(x => x.id === ev.agentId) || agentById(ev.agentId) || { name: ev.agent, emoji: '🤖', color: '#888' };
942
  addEvent(a, ev.phase, ev.content, ev.round, ev.agentId === 'user');
943
  }, 1100);
 
949
  { n: 1, name: 'Arena Foundation', tag: 'done', items: ['Estructura modular', 'Integración con el runtime (wllama)', 'Agent Manager', 'Arena State Manager', 'Sistema de turnos y fases', 'Modalidad 1 vs 1'] },
950
  { n: 2, name: 'Battle Experience', tag: 'done', items: ['Arena Lobby', 'Selección visual de agentes', 'Live Battle con streaming', 'Crossfire y refutaciones', 'Participación humana (Challenge Agent)'] },
951
  { n: 3, name: 'Intelligence System', tag: 'partial', items: ['Tres jueces independientes + Head Judge', 'Puntuaciones ponderadas', 'Informe de resultados', 'Pendiente: detector de contradicciones y repeticiones (Referee AI)'] },
952
+ { n: 4, name: 'Tournament Mode', tag: 'partial', items: ['Free For All', 'Team Battle (2v2, 3v3, 4v4 con veredicto por equipos)', 'Survival Tournament (eliminatorias de 4 u 8 con campeón)', 'Pendiente: rematches con estrategia revisada'] },
953
  { n: 5, name: 'Memory & Replay', tag: 'partial', items: ['Historial de competiciones (localStorage)', 'Replay de batallas', 'Pendiente: IndexedDB, exportación JSON/Markdown/PDF, memoria persistente de agentes'] },
954
  { n: 6, name: 'Premium Experience', tag: 'todo', items: ['Animaciones y sonidos', 'Efectos de competición', 'Sistema de logros completo', 'Personalización avanzada', 'Optimización WebGPU', 'Multi-Model Arena'] },
955
  ];