| 1 | // Cerebro CEO autónomo (compartido por Elffuss Code y Elffuss Claw): cuando el |
| 2 | // usuario NO está pidiendo nada (ocioso) y hay un modelo local cargado, la elfa |
| 3 | // «trabaja por su cuenta» — revisa el espacio de trabajo, reparte el trabajo en |
| 4 | // varios perfiles que piensan EN PARALELO (cada uno una línea de pensamiento en |
| 5 | // la vista Mente) y sintetiza propuestas de mejora. |
| 6 | // |
| 7 | // Agnóstico de herramientas a propósito: cada app inyecta su propio adaptador |
| 8 | // de workspace (`init({ workspace, ... })`) — Code usa code.js (proyecto de |
| 9 | // código), Claw usa fs.js (carpetas con permiso). El core no sabe ni le importa |
| 10 | // cuál es. |
| 11 | // |
| 12 | // Seguridad: NO modifica tus ficheros. Deja las propuestas en una carpeta |
| 13 | // aditiva (nunca toca lo existente) y las hace «flotar» en la Mente. Se PARA en |
| 14 | // cuanto detecta actividad del usuario y reanuda al volver a estar ocioso. |
| 15 | import { Agent } from './agent.js'; |
| 16 | import { humanizeTool } from './humanize.js'; |
| 17 | |
| 18 | const IDLE_MS = 18000; // 18 s sin actividad → el CEO se pone a trabajar |
| 19 | const TICK_MS = 3000; // frecuencia de comprobación |
| 20 | // 5 min entre ciclos automáticos: con 45s, una tarde ociosa generaba MILES de |
| 21 | // ficheros. «Pensar ahora» (forceCycle) sigue disponible sin esperar esto. |
| 22 | const COOLDOWN_MS = 300000; |
| 23 | const SOUL_CAP = 25; // ficheros sueltos antes de consolidar en archivo.md |
| 24 | |
| 25 | // perfil por defecto si la app anfitriona no da los suyos |
| 26 | const GENERIC_PROFILES = [ |
| 27 | { id: 'p1', name: 'Revisión', focus: 'qué mejorar de forma concreta y accionable', color: '#7c5cff' }, |
| 28 | { id: 'p2', name: 'Calidad', focus: 'errores, casos borde, cosas que podrían fallar', color: '#49e8ff' }, |
| 29 | ]; |
| 30 | |
| 31 | const slug = s => String(s).toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '') |
| 32 | .replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '').slice(0, 24) || 'perfil'; |
| 33 | |
| 34 | // ── namespace (localStorage) y adaptador de workspace: los da la app anfitriona ── |
| 35 | let NS = 'elffuss'; // prefijo de las claves de localStorage |
| 36 | let ws = null; // { isReady, tree, write, read, list, remove } |
| 37 | let getProvider = () => null; |
| 38 | // Lo que el cerebro le cuenta al usuario (la Mente, su historial). ceo.js lo |
| 39 | // comparten Claw y Code, cada una con su i18n: la app pasa su traductor con |
| 40 | // usarTraductor(t) (t(clave, vars) → texto, o la propia clave si no la tiene). |
| 41 | // Sin traductor, o sin la clave, va en español, como hasta ahora. (Lo que se le |
| 42 | // pide al MODELO —el encargo de cada perfil, la propuesta— no pasa por aquí.) |
| 43 | const ES = { |
| 44 | ceoProfilesUpdated: 'Perfiles actualizados: {names}', ceoNewMission: 'Nueva misión recibida: {mission}', |
| 45 | ceoNewSoulDir: 'Nueva carpeta-alma: {dir}/', ceoOn: 'CEO en guardia — trabajaré cuando estés ocioso', ceoOff: 'CEO en pausa', |
| 46 | ceoOtherTab: 'Otra pestaña lleva el cerebro — ábrela ahí para forzar un ciclo.', |
| 47 | ceoNeedsWs: 'Necesito un espacio de trabajo abierto y un modelo cargado.', |
| 48 | ceoCutPause: 'En pausa: corto el ciclo y no guardo nada.', ceoCutBack: 'Vuelves tú — dejo lo mío y te cedo el mando.', |
| 49 | ceoNewCycle: 'Nuevo ciclo: reviso el espacio de trabajo y reparto el trabajo…', |
| 50 | ceoSurvey: 'Panorama captado ({n} entradas). Delegando…', ceoInterrupted: '(interrumpido)', |
| 51 | ceoSaved: 'Propuesta guardada en {path}', ceoReadyNoFile: 'Propuesta lista (no pude escribir el fichero)', |
| 52 | ceoArchived: 'Consolidé {n} propuestas antiguas en archivo.md', |
| 53 | }; |
| 54 | let traductor = null; |
| 55 | export function usarTraductor(fn) { traductor = typeof fn === 'function' ? fn : null; } |
| 56 | function tx(clave, vars) { |
| 57 | let s = null; |
| 58 | try { s = traductor?.(clave, vars); } catch { /* traductor roto: español */ } |
| 59 | if (typeof s === 'string' && s && s !== clave) return s; |
| 60 | const base = ES[clave] ?? clave; |
| 61 | return vars ? base.replace(/\{(\w+)\}/g, (_, k) => (vars[k] ?? '')) : base; |
| 62 | } |
| 63 | let isBusy = () => false; // ¿el usuario tiene trabajo en cola/procesándose? → prioridad |
| 64 | let defaultProfiles = GENERIC_PROFILES; |
| 65 | // Qué herramientas puede usar el cerebro: (nombre) => bool, o null = todas. El |
| 66 | // cerebro trabaja SOLO mientras no miras y promete no cambiar nada; la app |
| 67 | // anfitriona le pasa una lista de solo lectura para que esa promesa no dependa |
| 68 | // de que el modelo obedezca (Claw: ver kernel.js). Sin la opción, todo como antes. |
| 69 | let allowTool = null; |
| 70 | const K = suffix => NS + '.' + suffix; |
| 71 | |
| 72 | function loadProfiles() { |
| 73 | try { const s = JSON.parse(localStorage.getItem(K('ceoProfiles'))); if (Array.isArray(s) && s.length) return s; } catch { /* */ } |
| 74 | return defaultProfiles.map(p => ({ ...p })); |
| 75 | } |
| 76 | let profiles = null; |
| 77 | export function getProfiles() { if (!profiles) profiles = loadProfiles(); return profiles; } |
| 78 | export function setProfiles(list) { |
| 79 | const used = new Set(); |
| 80 | profiles = (list || []).filter(p => p && p.name).map(p => { |
| 81 | let id = p.id || slug(p.name); let n = id, i = 2; |
| 82 | while (used.has(n)) n = id + '-' + i++; |
| 83 | used.add(n); |
| 84 | return { id: n, name: String(p.name).slice(0, 40), focus: String(p.focus || '').slice(0, 200), color: /^#[0-9a-f]{6}$/i.test(p.color || '') ? p.color : '#7c5cff' }; |
| 85 | }); |
| 86 | if (!profiles.length) profiles = defaultProfiles.map(p => ({ ...p })); |
| 87 | try { localStorage.setItem(K('ceoProfiles'), JSON.stringify(profiles)); } catch { /* */ } |
| 88 | emit('ceo', { type: 'reprogram', text: tx('ceoProfilesUpdated', { names: profiles.map(p => p.name).join(', ') }), profiles }); |
| 89 | return profiles; |
| 90 | } |
| 91 | |
| 92 | let enabled = false, running = false, lastActivity = Date.now(), timer = null, lastCycleEnd = 0, cycleN = 0; |
| 93 | // Una parada por ciclo: pausar o volver a usar la app la aborta, y la señal |
| 94 | // llega hasta el proveedor (corta la generación) y hasta las herramientas. |
| 95 | let cycleAborter = null; |
| 96 | // Cada pausa o actividad del usuario cambia la «época». tick() y forceCycle() |
| 97 | // esperan a isReady() antes de arrancar, y en Claw esa espera es asíncrona |
| 98 | // (consulta IndexedDB): si la época cambió mientras esperaban, el usuario pausó |
| 99 | // o volvió y el ciclo NO arranca. Antes solo se miraba `running`, que en ese |
| 100 | // hueco aún es false, así que interrupt() no hacía nada y el ciclo arrancaba |
| 101 | // igual y escribía su propuesta justo después de pausar. |
| 102 | let epoca = 0; |
| 103 | // Quién cortó: 'actividad' (el usuario volvió) o 'pausa' (lo pausó a propósito |
| 104 | // desde la Mente). Cuenta el primero que corta el ciclo; con eso se elige qué |
| 105 | // se le dice (antes las dos decían «Vuelves tú…»). |
| 106 | let motivoCorte = 'actividad'; |
| 107 | // Interrumpir el ciclo en curso. `running` NO se pone a false aquí: lo hace el |
| 108 | // propio ciclo al terminar de verdad. Mientras tanto vale 'interrupt' y |
| 109 | // forceCycle()/tick() no arrancan un segundo ciclo encima del que aún se está |
| 110 | // desmontando — dos ciclos a la vez son dos generate() contra el mismo modelo. |
| 111 | function interrupt(motivo = 'actividad') { |
| 112 | epoca++; |
| 113 | if (running !== 'interrupt') motivoCorte = motivo; |
| 114 | if (!running) return; |
| 115 | running = 'interrupt'; |
| 116 | try { cycleAborter?.abort(); } catch { /* */ } |
| 117 | } |
| 118 | |
| 119 | // MISIÓN reprogramable: el usuario puede reorientar el cerebro desde la Mente |
| 120 | // («céntrate en seguridad», «optimiza mis Excel», «documenta todo»…). |
| 121 | let DEFAULT_MISSION = 'Revisar el espacio de trabajo y proponer mejoras concretas y accionables.'; |
| 122 | let mission = null; |
| 123 | function ensureMission() { if (mission == null) { try { mission = localStorage.getItem(K('ceoMission')) || DEFAULT_MISSION; } catch { mission = DEFAULT_MISSION; } } } |
| 124 | export function getMission() { ensureMission(); return mission; } |
| 125 | export function setMission(text) { |
| 126 | mission = (text || '').trim() || DEFAULT_MISSION; |
| 127 | try { localStorage.setItem(K('ceoMission'), mission); } catch { /* */ } |
| 128 | emit('ceo', { type: 'reprogram', text: tx('ceoNewMission', { mission }) }); |
| 129 | lastCycleEnd = 0; lastActivity = Date.now() - IDLE_MS; // que arranque un ciclo pronto con la nueva misión |
| 130 | return mission; |
| 131 | } |
| 132 | |
| 133 | // Carpeta-«alma» donde el cerebro crea y guarda TODO (configurable). |
| 134 | let DEFAULT_SOUL = '.elffuss/soul'; |
| 135 | let soulDir = null; |
| 136 | function ensureSoulDir() { if (soulDir == null) { try { soulDir = localStorage.getItem(K('ceoDir')) || DEFAULT_SOUL; } catch { soulDir = DEFAULT_SOUL; } } } |
| 137 | export function getSoulDir() { ensureSoulDir(); return soulDir; } |
| 138 | export function setSoulDir(dir) { |
| 139 | soulDir = (dir || '').trim().replace(/^\/+|\/+$/g, '') || DEFAULT_SOUL; |
| 140 | try { localStorage.setItem(K('ceoDir'), soulDir); } catch { /* */ } |
| 141 | emit('ceo', { type: 'reprogram', text: tx('ceoNewSoulDir', { dir: soulDir }) }); |
| 142 | return soulDir; |
| 143 | } |
| 144 | |
| 145 | // ── semáforo cross-pestaña: UN SOLO cerebro ejecuta, TODAS visualizan ─────── |
| 146 | // El líder tiene un Web Lock exclusivo (se libera solo al cerrar la pestaña); |
| 147 | // difunde sus pensamientos por BroadcastChannel para que el resto los vea. |
| 148 | // (Aislado por origen por el propio navegador: Code y Claw nunca se cruzan.) |
| 149 | let isLeader = false, bc = null, realEmit = () => {}, crossTabWired = false; |
| 150 | function initCrossTab() { |
| 151 | if (crossTabWired) return; |
| 152 | crossTabWired = true; |
| 153 | try { |
| 154 | bc = new BroadcastChannel(NS + '-ceo'); |
| 155 | bc.onmessage = e => { if (e.data && e.data.kind === 'thought') realEmit(e.data.channel, e.data.ev); }; |
| 156 | } catch { /* sin BroadcastChannel */ } |
| 157 | if (navigator.locks && navigator.locks.request) { |
| 158 | navigator.locks.request(NS + '-ceo-leader', { mode: 'exclusive' }, () => new Promise(() => { isLeader = true; })) |
| 159 | .catch(() => { isLeader = true; }); |
| 160 | } else { isLeader = true; } |
| 161 | } |
| 162 | function emit(channel, ev) { |
| 163 | realEmit(channel, ev); |
| 164 | try { bc && bc.postMessage({ kind: 'thought', channel, ev }); } catch { /* ev no serializable */ } |
| 165 | } |
| 166 | |
| 167 | // init({ workspace, provider, onEvent, isBusy, namespace, defaultProfiles, defaultMission, defaultSoulDir, allowTool }) |
| 168 | export function init(opts = {}) { |
| 169 | if (opts.workspace) ws = opts.workspace; |
| 170 | if (opts.provider) getProvider = opts.provider; |
| 171 | if (opts.onEvent) realEmit = opts.onEvent; |
| 172 | if (opts.isBusy) isBusy = opts.isBusy; |
| 173 | if (opts.namespace) NS = opts.namespace; |
| 174 | if (opts.defaultProfiles) defaultProfiles = opts.defaultProfiles; |
| 175 | if (opts.defaultMission) DEFAULT_MISSION = opts.defaultMission; |
| 176 | if (opts.defaultSoulDir) DEFAULT_SOUL = opts.defaultSoulDir; |
| 177 | if (opts.allowTool) allowTool = opts.allowTool; |
| 178 | initCrossTab(); |
| 179 | } |
| 180 | export function isThisTabLeader() { return isLeader; } |
| 181 | export function noteActivity() { lastActivity = Date.now(); interrupt('actividad'); } |
| 182 | export function isEnabled() { return enabled; } |
| 183 | export function isRunning() { return !!running; } |
| 184 | // Play/stop: persistido AQUÍ (fuente única) — cualquier botón que lo toque |
| 185 | // queda sincronizado, y la elección sobrevive a recargar la página. |
| 186 | // |
| 187 | // En una clave NUEVA, «ceoDecision» ('on' | 'off'). La anterior, «ceoEnabled», |
| 188 | // la escribía también el primer clic en 🧠, que encendía el cerebro sin pedirlo, |
| 189 | // y no distingue un ▶ de verdad de aquel encendido implícito: con ella, quien |
| 190 | // pasó una vez por la Mente tenía el cerebro autónomo encendido en cada visita. |
| 191 | // Ya no se lee —cuenta como «sin decidir»: apagado, y el botón dice «activar»— |
| 192 | // y se borra la primera vez que se mira. |
| 193 | const CLAVE_DECISION = () => K('ceoDecision'); |
| 194 | function decision() { |
| 195 | try { |
| 196 | if (localStorage.getItem(K('ceoEnabled')) != null) localStorage.removeItem(K('ceoEnabled')); |
| 197 | return localStorage.getItem(CLAVE_DECISION()); |
| 198 | } catch { return null; } |
| 199 | } |
| 200 | export function wasEnabledLastSession() { return decision() === 'on'; } |
| 201 | // ¿el usuario llegó a decidir alguna vez (play o stop)? Distingue «nunca lo |
| 202 | // tocó» de «lo pausó a propósito» — solo lo primero debe auto-activarse al |
| 203 | // abrir la Mente; lo segundo hay que RESPETARLO, no pisarlo. |
| 204 | export function hasDecided() { return decision() != null; } |
| 205 | export function enable() { |
| 206 | if (enabled) return; |
| 207 | enabled = true; lastActivity = Date.now(); schedule(); |
| 208 | try { localStorage.setItem(CLAVE_DECISION(), 'on'); } catch { /* */ } |
| 209 | emit('sys', { type: 'status', text: tx('ceoOn') }); |
| 210 | } |
| 211 | export function disable() { |
| 212 | // Antes ponía running = false sin más: el ciclo seguía generando por detrás, |
| 213 | // escribía su propuesta igual, y «Pensar ahora» podía lanzar otro a la vez. |
| 214 | enabled = false; interrupt('pausa'); if (timer) clearTimeout(timer); |
| 215 | try { localStorage.setItem(CLAVE_DECISION(), 'off'); } catch { /* */ } |
| 216 | emit('sys', { type: 'status', text: tx('ceoOff') }); |
| 217 | } |
| 218 | |
| 219 | function schedule() { if (timer) clearTimeout(timer); timer = setTimeout(tick, TICK_MS); } |
| 220 | |
| 221 | // ¿Puede pensar AHORA? Para que la UI lo diga antes de prometer un ciclo: |
| 222 | // devuelve '' si sí, o el motivo ('leader' | 'running' | 'workspace' | |
| 223 | // 'provider'). Sin modelo de verdad (el anfitrión devuelve null en modo |
| 224 | // básico) no hay ciclo: con el motor de reglas solo salían propuestas basura |
| 225 | // escritas dentro del proyecto. |
| 226 | export async function whyNotThink() { |
| 227 | if (!isLeader) return 'leader'; |
| 228 | if (running) return 'running'; |
| 229 | if (!(await ws?.isReady())) return 'workspace'; |
| 230 | if (!getProvider()) return 'provider'; |
| 231 | return ''; |
| 232 | } |
| 233 | |
| 234 | // «Pensar ahora» — salta la espera de ociosidad. Sigue respetando el |
| 235 | // semáforo: si otra pestaña es la líder, no compite por la GPU. |
| 236 | export async function forceCycle() { |
| 237 | if (!isLeader) { emit('ceo', { type: 'paused', text: tx('ceoOtherTab') }); return false; } |
| 238 | if (running) return false; |
| 239 | const e = epoca; |
| 240 | // isReady() puede ser síncrona (Code: handle en memoria) o async (Claw: consulta IndexedDB) — se espera siempre. |
| 241 | if (!(await ws?.isReady()) || !getProvider()) { emit('ceo', { type: 'paused', text: tx('ceoNeedsWs') }); return false; } |
| 242 | if (running) return false; // otro ciclo arrancó mientras se esperaba a isReady() |
| 243 | if (e !== epoca) { emit('ceo', { type: 'paused', text: textoCorte() }); return false; } |
| 244 | try { await runCycle(); } finally { lastCycleEnd = Date.now(); } |
| 245 | return true; |
| 246 | } |
| 247 | |
| 248 | async function tick() { |
| 249 | if (!enabled) return; |
| 250 | const idle = Date.now() - lastActivity; |
| 251 | const rested = Date.now() - lastCycleEnd > COOLDOWN_MS; |
| 252 | const mightRun = isLeader && !running && !isBusy() && idle >= IDLE_MS && rested && getProvider(); |
| 253 | if (mightRun) { |
| 254 | const e = epoca; |
| 255 | // Tras la espera se vuelve a mirar todo lo que pudo cambiar en ella. |
| 256 | if (await ws?.isReady() && e === epoca && enabled && !running && !isBusy()) { |
| 257 | try { await runCycle(); } catch { /* siguiente ciclo */ } |
| 258 | lastCycleEnd = Date.now(); |
| 259 | } |
| 260 | } |
| 261 | schedule(); |
| 262 | } |
| 263 | |
| 264 | // helper: corre el agente con el proveedor actual sobre un prompt, emitiendo |
| 265 | // tokens/herramientas a un canal. Devuelve el texto final. Las tool-calls pasan |
| 266 | // SIEMPRE por el mismo runTool que usa el chat normal (Agent.handle real). |
| 267 | // `signal` es la parada del ciclo: llega al proveedor como 4º argumento de |
| 268 | // chat() (antes este envoltorio lo tiraba, y el proveedor nunca se enteraba de |
| 269 | // que había que parar) y además para el agente. |
| 270 | async function think(channel, task, signal = null) { |
| 271 | const prov = getProvider(); |
| 272 | if (!prov) return ''; |
| 273 | if (signal?.aborted) throw new Error('interrumpido'); |
| 274 | const a = new Agent({ chat: (h, s, cb, sig) => prov.chat(h, s, cb, sig) }); |
| 275 | // Un agente sin stop() no se entera de la señal (el de Claw antes de su |
| 276 | // stop-fix: handle(texto, onEvent)). Con él la única forma de cortarlo es |
| 277 | // lanzar desde su callback, como hacía antes el core; si no, cada perfil |
| 278 | // seguía llamando al modelo y ejecutando herramientas hasta el final aunque |
| 279 | // el usuario hubiera vuelto. Con stop() se ignora sin lanzar (ver abajo). |
| 280 | const sinParada = typeof a.stop !== 'function'; |
| 281 | const stop = () => { try { a.stop?.(); } catch { /* */ } }; |
| 282 | signal?.addEventListener('abort', stop, { once: true }); |
| 283 | let out = ''; |
| 284 | try { |
| 285 | await a.handle(task, ev => { |
| 286 | // Parado: se ignora lo que llegue, sin lanzar. Lanzar desde aquí metía una |
| 287 | // excepción en mitad del agente (y de su proveedor), y un agente que no |
| 288 | // distingue la parada la reportaba a telemetría como fallo del modelo. |
| 289 | if (running === 'interrupt' || signal?.aborted) { |
| 290 | if (sinParada) throw new Error('interrumpido'); |
| 291 | return; |
| 292 | } |
| 293 | if (ev.type === 'token') { out += ev.text; emit(channel, { type: 'token', text: ev.text }); } |
| 294 | 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 }); |
| 295 | 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) }); |
| 296 | else if (ev.type === 'text') { out = ev.text; } |
| 297 | }, { signal, permitir: allowTool }); |
| 298 | } finally { signal?.removeEventListener('abort', stop); } |
| 299 | if (signal?.aborted) throw new Error('interrumpido'); |
| 300 | return out; |
| 301 | } |
| 302 | |
| 303 | // Lo que se dice al cortar un ciclo, según quién lo cortó (ver motivoCorte). |
| 304 | const textoCorte = () => tx(motivoCorte === 'pausa' ? 'ceoCutPause' : 'ceoCutBack'); |
| 305 | |
| 306 | async function runCycle() { |
| 307 | running = true; |
| 308 | const aborter = (cycleAborter = new AbortController()); |
| 309 | try { await cycle(aborter.signal); } |
| 310 | finally { |
| 311 | // Solo aquí: hasta que el ciclo ha terminado de verdad, sigue «en marcha». |
| 312 | running = false; |
| 313 | if (cycleAborter === aborter) cycleAborter = null; |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | async function cycle(signal) { |
| 318 | cycleN++; |
| 319 | emit('ceo', { type: 'cycle', n: cycleN, text: tx('ceoNewCycle') }); |
| 320 | |
| 321 | let tree = ''; |
| 322 | try { tree = await ws.tree({ depth: 2 }); } catch { /* sin workspace */ } |
| 323 | emit('ceo', { type: 'survey', text: tx('ceoSurvey', { n: tree.split('\n').length }) }); |
| 324 | |
| 325 | const brief = (d) => `MISIÓN del equipo (fijada por el usuario): ${getMission()}\n` + |
| 326 | `Eres el jefe de ${d.name}. Dentro de esa misión, céntrate en: ${d.focus}. ` + |
| 327 | `Explora lo mínimo con tus herramientas y propón UNA mejora CONCRETA y accionable, ` + |
| 328 | `entendible por un humano. Sé breve. No modifiques nada existente: solo la propuesta.`; |
| 329 | const proposals = await Promise.all(getProfiles().map(async d => { |
| 330 | emit(d.id, { type: 'open', name: d.name, focus: d.focus }); |
| 331 | try { const p = await think(d.id, brief(d), signal); emit(d.id, { type: 'done', text: p }); return { dept: d.name, text: p }; } |
| 332 | catch { emit(d.id, { type: 'done', text: tx('ceoInterrupted') }); return null; } |
| 333 | })); |
| 334 | // Interrumpido: NO se escribe nada. Ni propuesta a medias ni fichero vacío. |
| 335 | if (running === 'interrupt' || signal.aborted) { emit('ceo', { type: 'paused', text: textoCorte() }); return; } |
| 336 | |
| 337 | const valid = proposals.filter(Boolean).filter(p => p.text && p.text.length > 8); |
| 338 | const md = `# Propuestas de mejora — ciclo ${cycleN}\n\n**Misión:** ${getMission()}\n\n` + |
| 339 | valid.map(p => `## ${p.dept}\n${p.text}\n`).join('\n') + |
| 340 | `\n_— generado por el cerebro CEO de Elffuss mientras estabas ocioso._\n`; |
| 341 | const d = new Date(); |
| 342 | const stamp = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}-${String(d.getHours()).padStart(2, '0')}${String(d.getMinutes()).padStart(2, '0')}`; |
| 343 | const topic = slug((valid[0]?.text || 'ciclo').split(/[.,;\n]/)[0]) || 'ciclo'; |
| 344 | const path = `${getSoulDir()}/${stamp}-${topic}.md`; |
| 345 | try { |
| 346 | await rotateSoul(); |
| 347 | if (signal.aborted) { emit('ceo', { type: 'paused', text: textoCorte() }); return; } |
| 348 | await ws.write({ path, content: md }); |
| 349 | emit('ceo', { type: 'built', text: tx('ceoSaved', { path }), path, md, proposals: valid }); |
| 350 | } catch (e) { |
| 351 | emit('ceo', { type: 'built', text: tx('ceoReadyNoFile'), md, proposals: valid }); |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | // Rotación: si hay demasiados ficheros sueltos, los MÁS ANTIGUOS se consolidan |
| 356 | // (recopilan) en un único archivo.md y se borran — para no acabar con miles. |
| 357 | async function rotateSoul() { |
| 358 | try { |
| 359 | const soul = getSoulDir(); |
| 360 | const names = (await ws.list(soul)).filter(n => n.endsWith('.md') && n !== 'archivo.md'); |
| 361 | if (names.length < SOUL_CAP) return; |
| 362 | names.sort(); // el nombre empieza por fecha → orden cronológico |
| 363 | const excess = names.slice(0, names.length - SOUL_CAP + 1); |
| 364 | let archive = ''; try { archive = await ws.read({ path: `${soul}/archivo.md` }); } catch { archive = '# Archivo histórico del cerebro\n'; } |
| 365 | for (const name of excess) { |
| 366 | try { archive += `\n---\n## ${name}\n${await ws.read({ path: `${soul}/${name}` })}\n`; } catch { /* */ } |
| 367 | } |
| 368 | await ws.write({ path: `${soul}/archivo.md`, content: archive.slice(-80000) }); |
| 369 | for (const name of excess) { try { await ws.remove(soul, name); } catch { /* */ } } |
| 370 | emit('ceo', { type: 'reprogram', text: tx('ceoArchived', { n: excess.length }) }); |
| 371 | } catch { /* soulDir aún sin crear o sin permiso: nada que rotar */ } |
| 372 | } |