Elffuss BraidHub

utopia-ia/elffuss-claw public

main · 6.4 KiBRawPermalink
1// rateArtifact — el evaluador que decide si un juego generado funciona.
2// Dos fallos que costaron una conclusión equivocada:
3// · al expirar el plazo devolvía la lectura ANTERIOR, así que bajo carga un
4// juego vivo se medía como muerto (y el evaluador se usa MIENTRAS el modelo
5// genera, o sea justo cuando la máquina va cargada);
6// · la sonda se inyectaba tras los scripts del artefacto, así que era ciega a
7// los errores de arranque, que son los más frecuentes.
8import { createRequire } from 'module';
9const { chromium } = createRequire(import.meta.url)('playwright');
10
11const pagina = (cuerpo, cabeza = '') => `<!doctype html><html><head>${cabeza}</head><body>
12<canvas id="c" width="300" height="200"></canvas><script>${cuerpo}<\/script></body></html>`;
13
14const vivo = `const x=document.getElementById('c').getContext('2d'); let t=0;
15 let dx=0; document.addEventListener('keydown',()=>{dx+=37});
16 (function b(){ t++; x.fillStyle='#000'; x.fillRect(0,0,300,200);
17 x.fillStyle='#0f0'; x.fillRect((t*3+dx)%280,50,20,20); requestAnimationFrame(b); })();`;
18
19const CASOS = [
20 { id: 'juego-vivo', desc: 'un juego que va: pinta, anima y responde', html: pagina(vivo), nota: 5 },
21
22 { id: 'error-arranque', desc: 'error en el PRIMER script → la sonda tiene que verlo',
23 html: pagina('noExisteEstaFuncion(); ' + vivo), sinErrores: false },
24
25 { id: 'error-al-pulsar', desc: 'revienta al recibir una tecla',
26 html: pagina(vivo + `document.addEventListener('keydown',()=>{ null.x; });`), sinErrores: false },
27
28 { id: 'quieto', desc: 'pinta pero no anima', html: pagina(`const x=document.getElementById('c').getContext('2d'); x.fillRect(0,0,300,200);`), falla: 'vivo' },
29
30 { id: 'sordo', desc: 'anima pero no escucha la entrada',
31 html: pagina(`const x=document.getElementById('c').getContext('2d'); let t=0;
32 (function b(){ t++; x.fillStyle='#000'; x.fillRect(0,0,300,200); x.fillStyle='#f00'; x.fillRect(t%280,50,20,20); requestAnimationFrame(b); })();`),
33 falla: 'responde' },
34
35 { id: 'sin-canvas', desc: 'sin canvas no se puede medir: «no medible», NO cero',
36 html: '<!doctype html><html><head></head><body><h1>hola</h1></body></html>', noMedible: true },
37
38 // El defecto REAL del snake que generó Gemma: arranca en la casilla 10 de una
39 // rejilla de 20, ya moviéndose, y choca contra la pared en segundo y medio.
40 // Gráficamente impecable y pasaba las cinco señales anteriores.
41 { id: 'se-suicida', desc: 'la partida se acaba sola en segundos sin tocar nada',
42 html: `<!doctype html><html><head></head><body><canvas id="c" width="300" height="200"></canvas><div id="fin"></div><script>
43 const x=document.getElementById('c').getContext('2d'); let p=0; let vivo=true;
44 document.addEventListener('keydown',()=>{});
45 const t=setInterval(()=>{ p++; x.fillStyle='#000'; x.fillRect(0,0,300,200); x.fillStyle='#0f0'; x.fillRect(p*12,80,10,10);
46 if(p>8){ vivo=false; clearInterval(t); document.getElementById('fin').textContent='GAME OVER'; } },150);
47 <\/script></body></html>`, falla: 'sobrevive' },
48
49 { id: 'aguanta', desc: 'un juego que NO se acaba solo no puede marcarse como tal',
50 html: pagina(vivo), noFalla: 'sobrevive' },
51
52 // Lo CORRECTO tras el consejo que le damos al modelo: no arrancar hasta la
53 // primera pulsación. Medido solo antes de tocar nada, esto parecía muerto y
54 // penalizábamos justo el arreglo que habíamos pedido.
55 { id: 'espera-al-jugador', desc: 'no arranca hasta la primera tecla → sigue estando VIVO',
56 html: `<!doctype html><html><head></head><body><canvas id="c" width="300" height="200"></canvas><script>
57 const x=document.getElementById('c').getContext('2d'); let t=0, jugando=false;
58 x.fillStyle='#333'; x.fillRect(0,0,300,200);
59 document.addEventListener('keydown',()=>{ jugando=true; });
60 (function b(){ if(jugando){ t++; x.fillStyle='#000'; x.fillRect(0,0,300,200);
61 x.fillStyle='#0ff'; x.fillRect((t*3)%280,80,20,20); } requestAnimationFrame(b); })();
62 <\/script></body></html>`, noFalla: 'vivo' },
63
64 { id: 'ya-terminado', desc: 'arranca en pantalla de fin de partida',
65 html: `<!doctype html><html><head></head><body><canvas id="c" width="300" height="200"></canvas><p>GAME OVER</p><script>${vivo}<\/script></body></html>`,
66 falla: 'arranca' },
67];
68
69const b = await chromium.launch({ channel: 'chrome', headless: true });
70const p = await (await b.newContext()).newPage();
71await p.goto('https://claw.elffuss.com/', { waitUntil: 'domcontentloaded' });
72await p.waitForTimeout(1200);
73
74const evaluar = (casos, carga) => p.evaluate(async ({ casos, carga }) => {
75 const rlm = await import('/js/rlm.js?v=' + Date.now());
76 const out = [];
77 for (const c of casos) {
78 let matar = null;
79 if (carga) {
80 // ocupar el hilo principal a ratos, como cuando el modelo está generando
81 const id = setInterval(() => { const t = performance.now(); while (performance.now() - t < 120); }, 160);
82 matar = () => clearInterval(id);
83 }
84 const r = await rlm.rateArtifact(c.html);
85 if (matar) matar();
86 out.push({ id: c.id, nota: r.nota, maximo: r.maximo, detalle: r.detalle, medible: r.medible, error: r.error });
87 }
88 return out;
89}, { casos, carga });
90
91let fallos = 0;
92for (const carga of [false, true]) {
93 const res = await evaluar(CASOS, carga);
94 console.log(`\n${carga ? '── CON EL HILO PRINCIPAL CARGADO (como al generar) ──' : '── en reposo ──'}`);
95 for (const c of CASOS) {
96 const r = res.find(x => x.id === c.id);
97 let bien = true, nota = '';
98 if (c.noMedible) { bien = r.medible === false && r.nota < 0; nota = bien ? '' : `medible=${r.medible} nota=${r.nota}`; }
99 else if (c.nota != null) { bien = r.nota === (c.nota === 5 ? r.maximo : c.nota); nota = bien ? '' : `nota ${r.nota}, esperaba ${c.nota} · falla ${Object.entries(r.detalle||{}).filter(([,v])=>!v).map(([k])=>k).join(',')}`; }
100 else if (c.sinErrores === false) { bien = r.detalle?.sinErrores === false; nota = bien ? '' : 'no vio el error'; }
101 else if (c.falla) { bien = r.detalle?.[c.falla] === false; nota = bien ? '' : `no detectó que falla «${c.falla}»`; }
102 else if (c.noFalla) { bien = r.detalle?.[c.noFalla] === true; nota = bien ? '' : `marcó «${c.noFalla}» como fallo y no lo es`; }
103 if (!bien) fallos++;
104 console.log(` ${bien ? '✓' : '✗'} ${c.id.padEnd(15)} ${c.desc}${nota ? '\n └─ ' + nota : ''}`);
105 }
106}
107console.log(fallos ? `\n ❌ ${fallos} fallos` : '\n ✅ todo correcto, en reposo y bajo carga');
108await b.close();
109process.exit(fallos ? 1 : 0);