Elffuss BraidHub

utopia-ia/elffuss-code public

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