Elffuss BraidHub

utopia-ia/elffuss-code public

7c24e7b60e19 · 10.2 KiBRawPermalink
1// Mente v3: estrellas por perfil (no consolas), historial completo, perfiles
2// editables, ciudad de fondo + haces de actividad, y tool-calling REAL del CEO.
3import { chromium } from 'playwright';
4const OUT = (process.env.SCRATCH || '/tmp/elffuss-test');
5const BASE = process.env.BASE || 'http://localhost:8799';
6let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
7
8const b = await chromium.launch({ args: ['--enable-unsafe-webgpu', '--use-angle=metal', '--autoplay-policy=no-user-gesture-required'] });
9const ctx = await b.newContext();
10await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); localStorage.removeItem('elffusscode.ceoProfiles'); } catch {} });
11const p = await ctx.newPage({ viewport: { width: 1500, height: 900 } });
12p.on('console', m => { if (m.type() === 'error' && !/allow-same-origin|soundcloud|widget|encrypted-media|permissions policy/i.test(m.text())) console.log(' err:', m.text().slice(0, 160)); });
13await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' });
14const MARK = 'MARCA-UNICA-93af7c';
15await p.evaluate(async (mark) => {
16 const o = await navigator.storage.getDirectory();
17 const w = async (n, t) => { const f = await o.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); };
18 await w('README.md', '# demo\n' + mark + '\nProyecto de prueba.');
19 const src = await o.getDirectoryHandle('src', { create: true });
20 const wsrc = async (n, t) => { const f = await src.getFileHandle(n, { create: true }); const s = await f.createWritable(); await s.write(t); await s.close(); };
21 await wsrc('app.js', 'export const app = 1;');
22}, MARK);
23await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(2000);
24
25await p.locator('#activity img').click(); await p.waitForTimeout(1200);
26ok('overlay + mundo montado', await p.locator('#mind-overlay').count() > 0);
27
28// leyenda con los 4 perfiles por defecto + CEO
29const legendItems = await p.locator('#mind-legend .ml-item').allInnerTexts();
30ok('leyenda con 4 perfiles + CEO', legendItems.length === 5 && legendItems.some(t => /CEO/.test(t)) && legendItems.some(t => /Arquitectura/.test(t)), legendItems.join(' · '));
31
32// ciudad de fondo construida (motor real)
33await p.waitForTimeout(2500);
34let dbg = await p.evaluate(async () => (await import('/js/mind.js'))._debug());
35ok('ciudad de fondo construida bajo la Mente', dbg.hasCity, JSON.stringify(dbg));
36
37// estrellas: una línea normal vs una tool-call deben crear estrellas (tamaño/estilo distinto por kind, verificado por código)
38const before = (await p.evaluate(async () => (await import('/js/mind.js'))._debug())).starCount;
39await p.evaluate(async () => { const m = await import('/js/mind.js'); m.pushThought('arq', { type: 'open', name: 'Arquitectura' }); m.pushThought('arq', { type: 'token', text: 'Esta es una línea de pensamiento normal que se vuelve estrella.\n' }); });
40await p.waitForTimeout(200);
41const afterLine = (await p.evaluate(async () => (await import('/js/mind.js'))._debug())).starCount;
42ok('una línea de texto crea una estrella', afterLine > before, `${before}→${afterLine}`);
43await p.evaluate(async (mark) => { const m = await import('/js/mind.js'); m.pushThought('arq', { type: 'tool', text: 'leyendo README.md…', path: 'README.md' }); }, MARK);
44await p.waitForTimeout(200);
45const afterTool = (await p.evaluate(async () => (await import('/js/mind.js'))._debug())).starCount;
46ok('una tool-call crea otra estrella', afterTool > afterLine, `${afterLine}→${afterTool}`);
47
48// el historial completo muestra TODO (línea + tool)
49const logText = await p.evaluate(() => document.getElementById('mind-log-body').innerText);
50ok('el historial recoge la línea de texto', /línea de pensamiento normal/.test(logText));
51ok('el historial recoge la tool-call', /leyendo README\.md/.test(logText));
52
53// haz de actividad sobre la ciudad (README.md existe en el modelo → beam real)
54dbg = await p.evaluate(async () => (await import('/js/mind.js'))._debug());
55ok('la tool-call sobre un fichero real generó un haz + resaltado', dbg.beamCount > 0 && dbg.fileActivityCount > 0, JSON.stringify(dbg));
56
57// editor de perfiles: renombrar Arquitectura y cambiar color, guardar
58await p.click('#mind-config'); await p.waitForTimeout(300);
59const rows = p.locator('.cfg-prof');
60ok('panel de config muestra 4 filas de perfil', await rows.count() === 4);
61await rows.nth(0).locator('.cp-name').fill('Seguridad');
62await rows.nth(0).locator('.cp-color').evaluate(el => { el.value = '#ff0055'; el.dispatchEvent(new Event('input')); });
63await p.click('#cfg-save'); await p.waitForTimeout(300);
64const newLegend = await p.locator('#mind-legend .ml-item').allInnerTexts();
65ok('el perfil renombrado aparece en la leyenda', newLegend.some(t => /Seguridad/.test(t)), newLegend.join(' · '));
66
67// tool-calling REAL del CEO: forceCycle con un proveedor falso que SÍ lee el fichero real
68const cycleResult = await p.evaluate(async (mark) => {
69 const ceo = await import('/js/ceo.js');
70 const mind = await import('/js/mind.js');
71 ceo.init({
72 provider: () => ({
73 chat: async (history) => {
74 const res = history.find(m => m.role === 'user' && m.content.startsWith('[resultado code.read]'));
75 if (!res) return '```tool\n{"tool":"code.read","args":{"path":"README.md"}}\n```';
76 const snippet = res.content.includes(mark) ? mark : 'NO-MARK';
77 return 'Propuesta basada en el contenido real: ' + snippet;
78 },
79 }),
80 isBusy: () => false,
81 onEvent: (ch, ev) => mind.pushThought(ch, ev),
82 });
83 const t0 = Date.now();
84 while (!ceo.isThisTabLeader() && Date.now() - t0 < 5000) await new Promise(r => setTimeout(r, 100));
85 const ran = await ceo.forceCycle();
86 return { ran, leader: ceo.isThisTabLeader() };
87}, MARK);
88ok('forceCycle se ejecuta (semáforo líder + GPU libre)', cycleResult.ran, JSON.stringify(cycleResult));
89await p.waitForTimeout(500);
90const logAfterCycle = await p.evaluate(() => document.getElementById('mind-log-body').innerText);
91ok('la propuesta del CEO contiene el MARCADOR real leído del fichero (tool-calling REAL, no simulado)', logAfterCycle.includes(MARK), logAfterCycle.slice(-400));
92ok('se creó un nodo de propuesta forjada (clicable, con .md guardado)', await p.evaluate(() => document.querySelectorAll('.mind-node-label').length > 0));
93ok('el RESULTADO real de la tool (no solo el nombre) quedó linkado en el historial', /→ .*README/.test(logAfterCycle) || /→ /.test(logAfterCycle), '(línea "→ …" presente)');
94ok('el nombre del fichero guardado es DESCRIPTIVO (fecha+tema, no mejoras-NNN)', await p.evaluate(() => {
95 const rows = [...document.querySelectorAll('.mind-node-label')].map(l => l.textContent);
96 return rows.some(t => /^\d{4}-\d{2}-\d{2}-\d{4}-/.test(t));
97}));
98
99// clic en la leyenda → la cámara VUELA a centrarse (posición cambia de verdad)
100const posBefore = (await p.evaluate(async () => (await import('/js/mind.js'))._debug())).cameraPos;
101await p.click('.ml-item[data-id="rend"]'); // perfil lejos de la posición inicial de cámara
102await p.waitForTimeout(150);
103const midFly = await p.evaluate(async () => (await import('/js/mind.js'))._debug());
104ok('el clic dispara el vuelo (flying=true a mitad de camino)', midFly.flying);
105await p.waitForTimeout(1300); // esperar a que termine (dur 1.1s)
106const posAfter = (await p.evaluate(async () => (await import('/js/mind.js'))._debug())).cameraPos;
107const moved = Math.hypot(posAfter[0] - posBefore[0], posAfter[1] - posBefore[1], posAfter[2] - posBefore[2]);
108ok('la cámara realmente se movió al centrarse en el perfil', moved > 5, `desplazamiento ${moved.toFixed(1)}`);
109const settledFly = (await p.evaluate(async () => (await import('/js/mind.js'))._debug())).flying;
110ok('el vuelo termina solo (flying=false al acabar)', settledFly === false);
111
112// panel de propuesta: markdown FORMATEADO (no crudo) + botón «Ejecutar»
113await p.evaluate(() => document.querySelectorAll('.mind-node-label')[0]?.click());
114await p.waitForTimeout(400);
115const panelHtml = await p.evaluate(() => document.querySelector('#mind-panel .mp-body')?.innerHTML || '');
116ok('el .md se renderiza FORMATEADO (hay <h4> real, no texto crudo con ##)', /<h4/.test(panelHtml), panelHtml.slice(0, 80));
117ok('sin símbolos ## crudos en el panel (se renderizaron como encabezado)', !/##\s/.test(await p.evaluate(() => document.querySelector('#mind-panel .mp-body')?.innerText || '')));
118ok('botón «Ejecutar esta propuesta» presente', await p.locator('#mp-exec').count() > 0);
119// clic en Ejecutar → cierra la Mente y la propuesta entra en la cola del chat real
120await p.click('#mp-exec');
121await p.waitForTimeout(600);
122ok('«Ejecutar» cierra la Mente y manda la propuesta a la cola del chat', await p.evaluate(() => document.getElementById('mind-overlay').style.display === 'none'));
123const chatText = await p.locator('#chat-log').innerText();
124ok('la propuesta llegó como mensaje real al chat/cola', /Implementa esta propuesta/.test(chatText));
125
126// anti-solape: crear MUCHOS nodos de golpe y comprobar que no quedan amontonados
127await p.locator('#activity img').click(); await p.waitForTimeout(600);
128await p.evaluate(async () => {
129 const m = await import('/js/mind.js');
130 for (let i = 0; i < 20; i++) m.pushThought('ceo', { type: 'built', text: 'extra ' + i, path: `.elffuss/soul/extra-${i}.md`, md: '# extra ' + i, proposals: [] });
131});
132await p.waitForTimeout(1000);
133const positions = await p.evaluate(() => [...document.querySelectorAll('.mind-node-label')].filter(l => l.style.display !== 'none').map(l => [parseFloat(l.style.left), parseFloat(l.style.top)]));
134let overlaps = 0;
135for (let i = 0; i < positions.length; i++) for (let j = i + 1; j < positions.length; j++) {
136 if (Math.abs(positions[i][0] - positions[j][0]) < 20 && Math.abs(positions[i][1] - positions[j][1]) < 8) overlaps++;
137}
138ok('con muchos nodos NO quedan etiquetas amontonadas en el mismo punto', overlaps === 0, `${overlaps} solapes entre ${positions.length} visibles`);
139ok('el número de etiquetas visibles está acotado (no crece sin límite)', positions.length <= 14, `${positions.length} visibles`);
140
141await p.screenshot({ path: OUT + '/mind_stars.png' });
142console.log('captura → mind_stars.png');
143console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ MENTE v3 (estrellas + perfiles + ciudad + tool-calling real) OK');
144await b.close();
145process.exit(fails ? 1 : 0);