| 1 | // El ciclo del cerebro CEO (web/js/ceo.js) en Node, sin navegador ni modelo: |
| 2 | // cuándo arranca, cuándo NO arranca y qué hace al cortarse. |
| 3 | // |
| 4 | // 1. Pausar mientras tick() espera a isReady() (asíncrona en Claw): antes el |
| 5 | // ciclo arrancaba igual y escribía una propuesta justo después de pausar. |
| 6 | // 2. Lo mismo con actividad del usuario en ese hueco. |
| 7 | // 3. Un agente SIN stop() (el de Claw antes de su stop-fix) se corta en |
| 8 | // cuanto vuelve el usuario: antes seguía llamando al modelo y ejecutando |
| 9 | // herramientas hasta el final. |
| 10 | // 4. Un agente con stop() (el de Code) se corta sin excepciones, y no se |
| 11 | // escribe nada. |
| 12 | // 5. El texto del corte distingue «vuelves tú» (actividad) de «en pausa» |
| 13 | // (pausado a propósito desde la Mente). |
| 14 | // |
| 15 | // ceo.js se copia a una carpeta temporal junto a un agent.js y un humanize.js |
| 16 | // de mentira (los de verdad necesitan el navegador). |
| 17 | // |
| 18 | // node tests/ceo-cycle.mjs |
| 19 | // CEO_JS=<ruta a otra copia de ceo.js> node tests/ceo-cycle.mjs (p. ej. la del core) |
| 20 | import { mkdtempSync, writeFileSync, copyFileSync } from 'node:fs'; |
| 21 | import { tmpdir } from 'node:os'; |
| 22 | import { join, dirname, resolve } from 'node:path'; |
| 23 | import { fileURLToPath, pathToFileURL } from 'node:url'; |
| 24 | |
| 25 | const AQUI = dirname(fileURLToPath(import.meta.url)); |
| 26 | const CEO = resolve(process.env.CEO_JS || join(AQUI, '..', 'web', 'js', 'ceo.js')); |
| 27 | let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 28 | const dormir = ms => new Promise(r => setTimeout(r, ms)); |
| 29 | async function hasta(cond, max = 8000) { const t0 = Date.now(); while (!cond()) { if (Date.now() - t0 > max) return false; await dormir(10); } return true; } |
| 30 | |
| 31 | // Lo mínimo del navegador que usa ceo.js: localStorage, y sin Web Locks ni |
| 32 | // BroadcastChannel (así esta pestaña es la líder y no queda nada abierto). |
| 33 | const mem = new Map(); |
| 34 | Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: { |
| 35 | getItem: k => (mem.has(k) ? mem.get(k) : null), setItem: (k, v) => { mem.set(k, String(v)); }, removeItem: k => { mem.delete(k); }, |
| 36 | } }); |
| 37 | Object.defineProperty(globalThis, 'navigator', { configurable: true, value: {} }); |
| 38 | Object.defineProperty(globalThis, 'BroadcastChannel', { configurable: true, value: undefined }); |
| 39 | |
| 40 | // Agente con stop() y señal, como el de Code. |
| 41 | const AGENTE_CON_PARADA = `export class Agent { |
| 42 | constructor(p) { this.p = p; this.parado = false; } |
| 43 | stop() { this.parado = true; } |
| 44 | async handle(task, onEvent, { signal } = {}) { |
| 45 | for (let i = 0; i < 4; i++) { |
| 46 | if (this.parado || signal?.aborted) return 'aborted'; |
| 47 | await this.p.chat([{ role: 'user', content: task }], '', t => onEvent({ type: 'token', text: t }), signal); |
| 48 | if (this.parado || signal?.aborted) return 'aborted'; |
| 49 | onEvent({ type: 'tool', call: { tool: 'code.read', args: { path: 'a.js' } } }); |
| 50 | globalThis.__herramientas++; |
| 51 | onEvent({ type: 'tool_result', tool: 'code.read', result: 'contenido' }); |
| 52 | } |
| 53 | onEvent({ type: 'text', text: 'Propuesta: añadir pruebas al módulo a.js' }); |
| 54 | return 'ok'; |
| 55 | } |
| 56 | }`; |
| 57 | // Agente SIN stop() ni señal, como el de Claw antes de su stop-fix. |
| 58 | const AGENTE_SIN_PARADA = `export class Agent { |
| 59 | constructor(p) { this.p = p; } |
| 60 | async handle(task, onEvent) { |
| 61 | for (let i = 0; i < 4; i++) { |
| 62 | await this.p.chat([{ role: 'user', content: task }], '', t => onEvent({ type: 'token', text: t })); |
| 63 | onEvent({ type: 'tool', call: { tool: 'fs.read', args: { path: 'a.txt' } } }); |
| 64 | globalThis.__herramientas++; |
| 65 | onEvent({ type: 'tool_result', tool: 'fs.read', result: 'contenido' }); |
| 66 | } |
| 67 | onEvent({ type: 'text', text: 'Propuesta: ordenar la carpeta de documentos' }); |
| 68 | } |
| 69 | }`; |
| 70 | |
| 71 | function preparar(agente) { |
| 72 | const dir = mkdtempSync(join(process.env.TMPDIR || tmpdir(), 'ceo-cycle-')); |
| 73 | copyFileSync(CEO, join(dir, 'ceo.js')); |
| 74 | writeFileSync(join(dir, 'package.json'), '{"type":"module"}'); |
| 75 | writeFileSync(join(dir, 'agent.js'), agente); |
| 76 | writeFileSync(join(dir, 'humanize.js'), 'export const humanizeTool = (t, a) => t + " " + (a?.path || "");'); |
| 77 | return dir; |
| 78 | } |
| 79 | let version = 0; |
| 80 | const cargar = dir => import(pathToFileURL(join(dir, 'ceo.js')).href + '?v=' + (++version)); |
| 81 | |
| 82 | function proveedor() { |
| 83 | const p = { llamadas: 0, trasCorte: 0, cortado: false, |
| 84 | async chat(h, s, cb) { |
| 85 | p.llamadas++; if (p.cortado) p.trasCorte++; |
| 86 | await dormir(30); |
| 87 | cb('·'); |
| 88 | return 'una propuesta concreta y accionable'; |
| 89 | } }; |
| 90 | return p; |
| 91 | } |
| 92 | function espacio(espera = 0) { |
| 93 | const w = { escritos: [], preguntas: 0, alPreguntar: null, |
| 94 | async isReady() { w.preguntas++; const f = w.alPreguntar; w.alPreguntar = null; f?.(); await dormir(espera); return true; }, |
| 95 | async tree() { return 'a.js\nb.js'; }, |
| 96 | async write({ path }) { w.escritos.push(path); }, |
| 97 | async list() { return []; }, async read() { return ''; }, async remove() {}, |
| 98 | }; |
| 99 | return w; |
| 100 | } |
| 101 | function montar(ceo, w, p, ns) { |
| 102 | const eventos = []; |
| 103 | ceo.init({ workspace: w, provider: () => p, isBusy: () => false, namespace: ns, onEvent: (canal, ev) => eventos.push({ canal, ev }) }); |
| 104 | return eventos; |
| 105 | } |
| 106 | const ultimoCorte = eventos => eventos.filter(e => e.canal === 'ceo' && e.ev.type === 'paused').at(-1)?.ev.text || ''; |
| 107 | |
| 108 | // 1 · pausar mientras tick() espera isReady() |
| 109 | { |
| 110 | const ceo = await cargar(preparar(AGENTE_CON_PARADA)); |
| 111 | const w = espacio(200), p = proveedor(); |
| 112 | montar(ceo, w, p, 't1'); |
| 113 | ceo.enable(); |
| 114 | ceo.setMission('revisar el proyecto'); // así el próximo tick no espera a estar ocioso |
| 115 | w.alPreguntar = () => ceo.disable(); // la pausa cae justo en la espera |
| 116 | await hasta(() => w.preguntas >= 1, 8000); |
| 117 | await dormir(700); |
| 118 | ok('1 · pausar mientras tick() espera isReady(): ningún ciclo arranca', w.preguntas === 1 && p.llamadas === 0 && w.escritos.length === 0, JSON.stringify({ preguntas: w.preguntas, llamadas: p.llamadas, escritos: w.escritos })); |
| 119 | ok('1 · …y el cerebro queda en pausa', !ceo.isEnabled() && !ceo.isRunning()); |
| 120 | } |
| 121 | |
| 122 | // 2 · volver a usar la app en ese mismo hueco |
| 123 | { |
| 124 | const ceo = await cargar(preparar(AGENTE_CON_PARADA)); |
| 125 | const w = espacio(200), p = proveedor(); |
| 126 | montar(ceo, w, p, 't2'); |
| 127 | ceo.enable(); |
| 128 | ceo.setMission('revisar el proyecto'); |
| 129 | w.alPreguntar = () => ceo.noteActivity(); |
| 130 | await hasta(() => w.preguntas >= 1, 8000); |
| 131 | await dormir(700); |
| 132 | ok('2 · actividad mientras tick() espera isReady(): ningún ciclo arranca', p.llamadas === 0 && w.escritos.length === 0, JSON.stringify({ llamadas: p.llamadas, escritos: w.escritos })); |
| 133 | ceo.disable(); |
| 134 | } |
| 135 | |
| 136 | // 3 · agente sin stop(): cortarlo es lanzar desde su callback |
| 137 | { |
| 138 | const ceo = await cargar(preparar(AGENTE_SIN_PARADA)); |
| 139 | const w = espacio(0), p = proveedor(); |
| 140 | const eventos = montar(ceo, w, p, 't3'); |
| 141 | globalThis.__herramientas = 0; |
| 142 | const ciclo = ceo.forceCycle(); |
| 143 | await hasta(() => p.llamadas >= 1); |
| 144 | ceo.noteActivity(); p.cortado = true; |
| 145 | const herramientasAlCortar = globalThis.__herramientas; |
| 146 | await ciclo; |
| 147 | await dormir(200); |
| 148 | ok('3 · agente sin stop(): tras volver el usuario nadie llama más al modelo', p.trasCorte === 0, `${p.trasCorte} llamadas después del corte`); |
| 149 | ok('3 · …ni ejecuta más herramientas', globalThis.__herramientas === herramientasAlCortar, `${globalThis.__herramientas - herramientasAlCortar} después del corte`); |
| 150 | ok('3 · …ni se escribe la propuesta', w.escritos.length === 0 && !ceo.isRunning(), JSON.stringify(w.escritos)); |
| 151 | ok('3 · …y se dice «vuelves tú»', /^Vuelves tú/.test(ultimoCorte(eventos)), ultimoCorte(eventos)); |
| 152 | } |
| 153 | |
| 154 | // 4 · agente con stop(): se corta sin excepciones |
| 155 | { |
| 156 | const ceo = await cargar(preparar(AGENTE_CON_PARADA)); |
| 157 | const w = espacio(0), p = proveedor(); |
| 158 | const eventos = montar(ceo, w, p, 't4'); |
| 159 | globalThis.__herramientas = 0; |
| 160 | let error = null; |
| 161 | const ciclo = ceo.forceCycle().catch(e => { error = e; }); |
| 162 | await hasta(() => p.llamadas >= 1); |
| 163 | ceo.noteActivity(); p.cortado = true; |
| 164 | const nAlCortar = eventos.length; |
| 165 | await ciclo; |
| 166 | const tokensTrasCorte = eventos.slice(nAlCortar).filter(e => e.canal !== 'ceo' && e.ev.type === 'token').length; |
| 167 | ok('4 · agente con stop(): el ciclo se corta sin excepción y sin escribir', !error && w.escritos.length === 0 && !ceo.isRunning(), JSON.stringify({ error: error?.message, escritos: w.escritos })); |
| 168 | ok('4 · …el agente no vuelve a llamar al modelo y lo que aún llega no se pinta', p.trasCorte === 0 && tokensTrasCorte === 0, JSON.stringify({ llamadas: p.trasCorte, tokens: tokensTrasCorte })); |
| 169 | } |
| 170 | |
| 171 | // 5 · el texto del corte: pausa a propósito frente a actividad |
| 172 | { |
| 173 | const ceo = await cargar(preparar(AGENTE_CON_PARADA)); |
| 174 | const w = espacio(0), p = proveedor(); |
| 175 | const eventos = montar(ceo, w, p, 't5'); |
| 176 | ceo.enable(); |
| 177 | const ciclo = ceo.forceCycle(); |
| 178 | await hasta(() => p.llamadas >= 1); |
| 179 | ceo.disable(); |
| 180 | await ciclo; |
| 181 | ok('5 · pausar desde la Mente a mitad de ciclo dice «en pausa», no «vuelves tú»', /^En pausa/.test(ultimoCorte(eventos)) && w.escritos.length === 0, ultimoCorte(eventos)); |
| 182 | // y un ciclo que nadie corta sí escribe su propuesta (el resto no es trivial) |
| 183 | const p2 = proveedor(), w2 = espacio(0); |
| 184 | const ceo2 = await cargar(preparar(AGENTE_CON_PARADA)); |
| 185 | montar(ceo2, w2, p2, 't5b'); |
| 186 | await ceo2.forceCycle(); |
| 187 | ok('5 · un ciclo sin cortes sí deja su propuesta escrita', w2.escritos.length === 1 && /\.md$/.test(w2.escritos[0]), JSON.stringify(w2.escritos)); |
| 188 | } |
| 189 | |
| 190 | console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ CICLO DEL CEO OK — no arranca tras pausar, y se corta con cualquier agente'); |
| 191 | process.exit(fails ? 1 : 0); |