Elffuss BraidHub

utopia-ia/elffuss-code public

CEO: no cycle after a pause during isReady(), agents without stop() are still cut, a pause says so

Three fixes in ceo.js (a copy of the core's ceo.js; the same change goes to
elffuss/core).

- A pause or user activity that landed while tick() or forceCycle() awaited
  ws.isReady() was lost: `running` was still false, so interrupt() did
  nothing, and after the await only `running` was checked. In Claw, where
  isReady() reads IndexedDB, a full cycle then ran and wrote a proposal right
  after the user paused. Every pause or activity now bumps an epoch, and both
  check it (and enabled, running and isBusy) after the await.
- Since think() stopped throwing on interrupt it relied on the agent honouring
  the signal or stop(). An agent with neither (Claw's, at the time)
  kept calling the model and running tools to the end after the user came
  back. Without stop() the callback throws again, as the core did before; with
  stop() the events are still ignored without throwing.
- A deliberate pause from the Mind ended the cycle with "Vuelves tu...",
  written for the user coming back. The first interrupt of a cycle now records
  why, and a pause says "En pausa: corto el ciclo y no guardo nada."

tests/ceo-cycle.mjs runs ceo.js in Node with a fake agent and workspace: no
cycle after a pause or activity during an asynchronous isReady(), a Claw-shaped
agent makes no model call or tool run after the cut, a Code-shaped one stops
without an exception, the two cut texts, and a cycle nobody cuts still writes
its proposal. Against the previous ceo.js it fails 5 of 11 checks.
CEO_JS=<path> runs it against another copy, such as the core's.
Changeset86dfa66543e3426a7e3a3d1ea3e600ed50f025623bc5f000cab2edcfd89c0b08
AuthorKikoCis <kikocisneros@gmail.com> · 2026-10-11 15:10 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2026-10-11 15:10 +02:00
Parents22eb75f6760e

Browse the files at this changeset

2 files changed

added tests/ceo-cycle.mjs +191 −0
@@ -0,0 +1,191 @@
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);
modified web/js/ceo.js +42 −9
@@ -63,11 +63,24 @@
6363 // Una parada por ciclo: pausar o volver a usar la app la aborta, y la señal
6464 // llega hasta el proveedor (corta la generación) y hasta las herramientas.
6565 let cycleAborter = null;
66+// Cada pausa o actividad del usuario cambia la «época». tick() y forceCycle()
67+// esperan a isReady() antes de arrancar, y en Claw esa espera es asíncrona
68+// (consulta IndexedDB): si la época cambió mientras esperaban, el usuario pausó
69+// o volvió y el ciclo NO arranca. Antes solo se miraba `running`, que en ese
70+// hueco aún es false, así que interrupt() no hacía nada y el ciclo arrancaba
71+// igual y escribía su propuesta justo después de pausar.
72+let epoca = 0;
73+// Quién cortó: 'actividad' (el usuario volvió) o 'pausa' (lo pausó a propósito
74+// desde la Mente). Cuenta el primero que corta el ciclo; con eso se elige qué
75+// se le dice (antes las dos decían «Vuelves tú…»).
76+let motivoCorte = 'actividad';
6677 // Interrumpir el ciclo en curso. `running` NO se pone a false aquí: lo hace el
6778 // propio ciclo al terminar de verdad. Mientras tanto vale 'interrupt' y
6879 // forceCycle()/tick() no arrancan un segundo ciclo encima del que aún se está
6980 // desmontando — dos ciclos a la vez son dos generate() contra el mismo modelo.
70-function interrupt() {
81+function interrupt(motivo = 'actividad') {
82+ epoca++;
83+ if (running !== 'interrupt') motivoCorte = motivo;
7184 if (!running) return;
7285 running = 'interrupt';
7386 try { cycleAborter?.abort(); } catch { /* */ }
@@ -134,7 +147,7 @@
134147 initCrossTab();
135148 }
136149 export function isThisTabLeader() { return isLeader; }
137-export function noteActivity() { lastActivity = Date.now(); interrupt(); }
150+export function noteActivity() { lastActivity = Date.now(); interrupt('actividad'); }
138151 export function isEnabled() { return enabled; }
139152 export function isRunning() { return !!running; }
140153 // Play/stop: persistido AQUÍ (fuente única) — cualquier botón que lo toque
@@ -153,7 +166,7 @@
153166 export function disable() {
154167 // Antes ponía running = false sin más: el ciclo seguía generando por detrás,
155168 // escribía su propuesta igual, y «Pensar ahora» podía lanzar otro a la vez.
156- enabled = false; interrupt(); if (timer) clearTimeout(timer);
169+ enabled = false; interrupt('pausa'); if (timer) clearTimeout(timer);
157170 try { localStorage.setItem(K('ceoEnabled'), '0'); } catch { /* */ }
158171 emit('sys', { type: 'status', text: 'CEO en pausa' });
159172 }
@@ -178,9 +191,11 @@
178191 export async function forceCycle() {
179192 if (!isLeader) { emit('ceo', { type: 'paused', text: 'Otra pestaña lleva el cerebro — ábrela ahí para forzar un ciclo.' }); return false; }
180193 if (running) return false;
194+ const e = epoca;
181195 // isReady() puede ser síncrona (Code: handle en memoria) o async (Claw: consulta IndexedDB) — se espera siempre.
182196 if (!(await ws?.isReady()) || !getProvider()) { emit('ceo', { type: 'paused', text: 'Necesito un espacio de trabajo abierto y un modelo cargado.' }); return false; }
183197 if (running) return false; // otro ciclo arrancó mientras se esperaba a isReady()
198+ if (e !== epoca) { emit('ceo', { type: 'paused', text: textoCorte() }); return false; }
184199 try { await runCycle(); } finally { lastCycleEnd = Date.now(); }
185200 return true;
186201 }
@@ -190,9 +205,13 @@
190205 const idle = Date.now() - lastActivity;
191206 const rested = Date.now() - lastCycleEnd > COOLDOWN_MS;
192207 const mightRun = isLeader && !running && !isBusy() && idle >= IDLE_MS && rested && getProvider();
193- if (mightRun && await ws?.isReady() && !running) {
194- try { await runCycle(); } catch { /* siguiente ciclo */ }
195- lastCycleEnd = Date.now();
208+ if (mightRun) {
209+ const e = epoca;
210+ // Tras la espera se vuelve a mirar todo lo que pudo cambiar en ella.
211+ if (await ws?.isReady() && e === epoca && enabled && !running && !isBusy()) {
212+ try { await runCycle(); } catch { /* siguiente ciclo */ }
213+ lastCycleEnd = Date.now();
214+ }
196215 }
197216 schedule();
198217 }
@@ -208,6 +227,12 @@
208227 if (!prov) return '';
209228 if (signal?.aborted) throw new Error('interrumpido');
210229 const a = new Agent({ chat: (h, s, cb, sig) => prov.chat(h, s, cb, sig) });
230+ // Un agente sin stop() no se entera de la señal (el de Claw antes de su
231+ // stop-fix: handle(texto, onEvent)). Con él la única forma de cortarlo es
232+ // lanzar desde su callback, como hacía antes el core; si no, cada perfil
233+ // seguía llamando al modelo y ejecutando herramientas hasta el final aunque
234+ // el usuario hubiera vuelto. Con stop() se ignora sin lanzar (ver abajo).
235+ const sinParada = typeof a.stop !== 'function';
211236 const stop = () => { try { a.stop?.(); } catch { /* */ } };
212237 signal?.addEventListener('abort', stop, { once: true });
213238 let out = '';
@@ -216,7 +241,10 @@
216241 // Parado: se ignora lo que llegue, sin lanzar. Lanzar desde aquí metía una
217242 // excepción en mitad del agente (y de su proveedor), y un agente que no
218243 // distingue la parada la reportaba a telemetría como fallo del modelo.
219- if (running === 'interrupt' || signal?.aborted) return;
244+ if (running === 'interrupt' || signal?.aborted) {
245+ if (sinParada) throw new Error('interrumpido');
246+ return;
247+ }
220248 if (ev.type === 'token') { out += ev.text; emit(channel, { type: 'token', text: ev.text }); }
221249 else if (ev.type === 'tool') emit(channel, { type: 'tool', text: humanizeTool(ev.call.tool, ev.call.args), tool: ev.call.tool, path: ev.call.args?.path || null });
222250 else if (ev.type === 'tool_result') emit(channel, { type: 'tool_result', tool: ev.tool, text: String(ev.result || '').replace(/\s+/g, ' ').trim().slice(0, 100) });
@@ -227,6 +255,11 @@
227255 return out;
228256 }
229257
258+// Lo que se dice al cortar un ciclo, según quién lo cortó (ver motivoCorte).
259+const textoCorte = () => motivoCorte === 'pausa'
260+ ? 'En pausa: corto el ciclo y no guardo nada.'
261+ : 'Vuelves tú — dejo lo mío y te cedo el mando.';
262+
230263 async function runCycle() {
231264 running = true;
232265 const aborter = (cycleAborter = new AbortController());
@@ -256,7 +289,7 @@
256289 catch { emit(d.id, { type: 'done', text: '(interrumpido)' }); return null; }
257290 }));
258291 // Interrumpido: NO se escribe nada. Ni propuesta a medias ni fichero vacío.
259- if (running === 'interrupt' || signal.aborted) { emit('ceo', { type: 'paused', text: 'Vuelves tú — dejo lo mío y te cedo el mando.' }); return; }
292+ if (running === 'interrupt' || signal.aborted) { emit('ceo', { type: 'paused', text: textoCorte() }); return; }
260293
261294 const valid = proposals.filter(Boolean).filter(p => p.text && p.text.length > 8);
262295 const md = `# Propuestas de mejora — ciclo ${cycleN}\n\n**Misión:** ${getMission()}\n\n` +
@@ -268,7 +301,7 @@
268301 const path = `${getSoulDir()}/${stamp}-${topic}.md`;
269302 try {
270303 await rotateSoul();
271- if (signal.aborted) { emit('ceo', { type: 'paused', text: 'Vuelves tú — dejo lo mío y te cedo el mando.' }); return; }
304+ if (signal.aborted) { emit('ceo', { type: 'paused', text: textoCorte() }); return; }
272305 await ws.write({ path, content: md });
273306 emit('ceo', { type: 'built', text: `Propuesta guardada en ${path}`, path, md, proposals: valid });
274307 } catch (e) {