| 1 | // Glue específico de Elffuss Claw para el cerebro CEO genérico (ceo.js, core): |
| 2 | // Claw no tiene un único «proyecto» como Code — tiene varias carpetas |
| 3 | // autorizadas (fs.js) — así que el cerebro trabaja dentro de la PRIMERA |
| 4 | // carpeta autorizada (la que fs.root()/fs.write() usan por defecto si no se |
| 5 | // indica `folder`), tratándola como su espacio de trabajo principal. |
| 6 | import * as fs from './tools/fs.js'; |
| 7 | import * as db from './db.js'; |
| 8 | import * as perms from './permissions.js'; |
| 9 | |
| 10 | const IGNORE = new Set(['node_modules', '.git', 'dist', 'build', 'target', '__pycache__', '.next', 'venv', '.venv', '.DS_Store']); |
| 11 | |
| 12 | // La carpeta donde escribe el cerebro: la primera autorizada (o null). |
| 13 | export async function carpetaDelAlma() { |
| 14 | try { return (await fs.folders())[0] || null; } catch { return null; } |
| 15 | } |
| 16 | |
| 17 | // Las propuestas ya guardadas en la carpeta-alma, para que la Mente las enseñe |
| 18 | // después de recargar (antes Claw llamaba a mind.init sin esto y, tras una |
| 19 | // recarga, la Mente no tenía ni una etiqueta). NUNCA pide nada: sin el permiso |
| 20 | // «Archivos» concedido, o si el navegador no da ya acceso a la carpeta, no |
| 21 | // lista — abrir la Mente no puede sacar un diálogo de permisos. |
| 22 | export async function propuestasGuardadas(soulDir, { max = 40 } = {}) { |
| 23 | try { |
| 24 | if (!perms.has('fs')) return []; |
| 25 | const nombre = await carpetaDelAlma(); |
| 26 | if (!nombre) return []; |
| 27 | const raiz = await db.get('fs', nombre); |
| 28 | if (!raiz) return []; |
| 29 | if (raiz.queryPermission && await raiz.queryPermission({ mode: 'read' }) !== 'granted') return []; |
| 30 | let dir = raiz; |
| 31 | for (const p of String(soulDir || '').split('/').filter(Boolean)) { |
| 32 | try { dir = await dir.getDirectoryHandle(p); } catch { return []; } |
| 33 | } |
| 34 | const ficheros = []; |
| 35 | for await (const e of dir.values()) { |
| 36 | if (e.kind === 'file' && e.name.endsWith('.md') && e.name !== 'archivo.md') ficheros.push(e); |
| 37 | } |
| 38 | ficheros.sort((a, b) => a.name.localeCompare(b.name)); // empiezan por fecha |
| 39 | return await Promise.all(ficheros.slice(-max).map(async e => ({ |
| 40 | path: `${String(soulDir).replace(/^\/+|\/+$/g, '')}/${e.name}`, |
| 41 | md: await (await e.getFile()).text(), |
| 42 | }))); |
| 43 | } catch { return []; } |
| 44 | } |
| 45 | |
| 46 | // El cerebro trabaja mientras NO miras, así que nunca pide permisos: ni el |
| 47 | // «Archivos» de Claw (fs.root() lo pedía y, con el permiso revocado y carpetas |
| 48 | // aún guardadas, el cerebro ocioso sacaba «📁 Permiso: Archivos» antes de |
| 49 | // llamar al modelo, esperaba la respuesta y lo volvía a pedir al escribir) ni |
| 50 | // el del navegador sobre la carpeta. Sin los dos concedidos no hay espacio de |
| 51 | // trabajo: isReady() dice que no y el ciclo no arranca. |
| 52 | async function raizSinPreguntar(nombre) { |
| 53 | if (!perms.has('fs')) throw new Error('sin el permiso «Archivos»'); |
| 54 | const nombres = await fs.folders(); |
| 55 | const h = await db.get('fs', nombre || nombres[0]); |
| 56 | if (!h) throw new Error('sin carpeta autorizada'); |
| 57 | if (h.queryPermission && await h.queryPermission({ mode: 'readwrite' }) !== 'granted') throw new Error('el navegador no ha dado acceso a la carpeta'); |
| 58 | return h; |
| 59 | } |
| 60 | |
| 61 | async function dirHandle(dirPath, { create = false } = {}) { |
| 62 | let dir = await raizSinPreguntar(); |
| 63 | for (const p of dirPath.split('/').filter(Boolean)) dir = await dir.getDirectoryHandle(p, { create }); |
| 64 | return dir; |
| 65 | } |
| 66 | async function fichero(path, { create = false } = {}) { |
| 67 | const partes = String(path || '').split('/').filter(Boolean); |
| 68 | const nombre = partes.pop(); |
| 69 | if (!nombre) throw new Error('Falta path'); |
| 70 | return (await dirHandle(partes.join('/'), { create })).getFileHandle(nombre, { create }); |
| 71 | } |
| 72 | |
| 73 | async function walk(dir, prefix, depth, budget) { |
| 74 | if (depth <= 0 || budget.n > 350) return []; |
| 75 | const entries = []; |
| 76 | for await (const e of dir.values()) { if (!IGNORE.has(e.name)) entries.push(e); } |
| 77 | entries.sort((a, b) => (a.kind !== b.kind) ? (a.kind === 'directory' ? -1 : 1) : a.name.localeCompare(b.name)); |
| 78 | const out = []; |
| 79 | for (const e of entries) { |
| 80 | if (++budget.n > 350) { out.push(prefix + '…'); break; } |
| 81 | out.push(prefix + (e.kind === 'directory' ? '📁 ' : '') + e.name); |
| 82 | if (e.kind === 'directory') out.push(...await walk(e, prefix + ' ', depth - 1, budget)); |
| 83 | } |
| 84 | return out; |
| 85 | } |
| 86 | |
| 87 | export const ceoWorkspace = { |
| 88 | isReady: async () => { try { await raizSinPreguntar(); return true; } catch { return false; } }, |
| 89 | tree: async ({ depth = 2 } = {}) => { |
| 90 | const names = await fs.folders(); |
| 91 | if (!names.length) return '(sin carpetas autorizadas)'; |
| 92 | const budget = { n: 0 }; |
| 93 | const out = []; |
| 94 | for (const name of names) { |
| 95 | out.push('📁 ' + name); |
| 96 | try { out.push(...await walk(await raizSinPreguntar(name), ' ', depth, budget)); } catch { /* sin permiso ya */ } |
| 97 | } |
| 98 | return out.join('\n') || '(vacío)'; |
| 99 | }, |
| 100 | write: async ({ path, content = '' }) => { |
| 101 | const w = await (await fichero(path, { create: true })).createWritable(); |
| 102 | await w.write(content); |
| 103 | await w.close(); |
| 104 | return `Escrito ${path} (${content.length} caracteres)`; |
| 105 | }, |
| 106 | read: async ({ path }) => (await (await fichero(path)).getFile()).text(), |
| 107 | list: async (dirPath) => { |
| 108 | const dir = await dirHandle(dirPath, { create: true }); |
| 109 | const names = []; |
| 110 | for await (const e of dir.values()) if (e.kind === 'file') names.push(e.name); |
| 111 | return names; |
| 112 | }, |
| 113 | remove: async (dirPath, name) => (await dirHandle(dirPath)).removeEntry(name), |
| 114 | }; |
| 115 | |
| 116 | // «perfiles»: líneas de pensamiento paralelas adaptadas a lo que Claw |
| 117 | // realmente puede hacer (carpetas, apps, tareas, memoria) — no a código. |
| 118 | export const CEO_DEFAULT_PROFILES = [ |
| 119 | { id: 'org', name: 'Organización', focus: 'archivos y carpetas autorizadas: qué limpiar, renombrar o agrupar mejor; automatizaciones (fs.watch) que ahorrarían trabajo repetitivo', color: '#7c5cff' }, |
| 120 | { id: 'prod', name: 'Productividad', focus: 'apps creadas, skills instaladas y tareas programadas: qué automatizar o qué skill nueva ayudaría de verdad', color: '#49e8ff' }, |
| 121 | { id: 'memo', name: 'Memoria', focus: 'qué hechos útiles sobre el usuario merece la pena recordar a partir de lo visto, y qué recordado ya no aplica', color: '#3fb970' }, |
| 122 | ]; |