Elffuss BraidHub

utopia-ia/elffuss-code public

main · 37.8 KiBRawPermalink
1// Herramientas de proyecto: el único mundo que toca Elffuss Code es la
2// carpeta de código que el usuario abre con el picker nativo.
3import * as db from '../db.js';
4
5let projectHandle = null;
6let projectName = '';
7let currentFile = null; // ruta abierta en el editor
8let onFileWritten = () => {}; // el IDE refresca pestañas/árbol
9
10export function setOnFileWritten(fn) { onFileWritten = fn; }
11export function setCurrentFile(path) { currentFile = path; }
12export function current() { return { projectName, currentFile }; }
13export function handle() { return projectHandle; }
14
15// Lee un archivo de texto dentro de un dir handle por ruta (soporta subdirs).
16async function readIn(dir, path) {
17 const parts = path.split('/'); const name = parts.pop();
18 for (const p of parts) dir = await dir.getDirectoryHandle(p);
19 return (await (await dir.getFileHandle(name)).getFile()).text();
20}
21
22// Integración git SIN dependencias: parsea el .git directamente (rama, último
23// commit con su SHA y el remoto «origin»). Suficiente para orientar; commitear
24// se le pide al agente/terminal.
25export async function gitInfo() {
26 if (!projectHandle) return { isRepo: false };
27 let git;
28 try { git = await projectHandle.getDirectoryHandle('.git'); }
29 catch { return { isRepo: false }; }
30 const out = { isRepo: true, branch: '(detached)', lastCommit: null, web: null };
31 try {
32 const head = (await readIn(git, 'HEAD')).trim();
33 out.branch = head.match(/ref:\s*refs\/heads\/(.+)/)?.[1] || head.slice(0, 7);
34 } catch { /* sin HEAD */ }
35 try {
36 // «<viejo> <nuevo> Autor <correo> <ts> <tz>\t<mensaje>»: el SHA del commit
37 // es el SEGUNDO campo (antes se tiraba). El correo no se guarda: no se enseña.
38 const last = (await readIn(git, 'logs/HEAD')).trim().split('\n').pop();
39 const m = last.match(/^\S+ (\S+) (.+?) <[^>]*> (\d+)[^\t]*\t(.+)$/);
40 if (m) out.lastCommit = { sha: /^[0-9a-f]{7,64}$/i.test(m[1]) ? m[1] : null, author: m[2], when: new Date(+m[3] * 1000), msg: m[4] };
41 } catch { /* sin logs (repo recién creado) */ }
42 try { out.web = remoteWeb(await readIn(git, 'config')); } catch { /* sin config */ }
43 return out;
44}
45
46// La URL web del remoto «origin», SIN credenciales (https://usuario:token@…
47// no puede acabar en un enlace) y con los enlaces de rama y commit según el
48// tipo de forja. null si no hay remoto o no es http(s)/ssh reconocible.
49export function remoteWeb(config) {
50 const sec = String(config || '').split(/^\s*\[/m).find(b => /^remote\s+"origin"\s*\]/.test(b));
51 const raw = sec?.match(/^\s*url\s*=\s*(\S+)/m)?.[1];
52 if (!raw) return null;
53 let host, path;
54 const ssh = raw.match(/^(?:ssh:\/\/)?[\w.-]+@([\w.-]+)(?::\d+)?[:/](.+)$/);
55 if (/^https?:\/\//i.test(raw)) {
56 try { const u = new URL(raw); host = u.hostname; path = u.pathname; } catch { return null; }
57 } else if (ssh) { host = ssh[1]; path = ssh[2]; }
58 else return null;
59 path = path.replace(/^\/+/, '').replace(/\.git\/?$/, '').replace(/\/+$/, '');
60 if (!host || !/^[\w.-]+\/[\w.\-/]+$/.test(path)) return null;
61 const base = `https://${host}/${path}`;
62 const kind = /(^|\.)github\.com$/i.test(host) ? 'github' : /(^|\.)gitlab\.com$/i.test(host) ? 'gitlab'
63 : /(^|\.)bitbucket\.org$/i.test(host) ? 'bitbucket' : 'gitea';
64 const enc = s => String(s).split('/').map(encodeURIComponent).join('/');
65 return {
66 base, kind,
67 branch: b => kind === 'gitea' ? `${base}/src/branch/${enc(b)}` : kind === 'bitbucket' ? `${base}/src/${enc(b)}` : kind === 'gitlab' ? `${base}/-/tree/${enc(b)}` : `${base}/tree/${enc(b)}`,
68 commit: sha => kind === 'bitbucket' ? `${base}/commits/${sha}` : kind === 'gitlab' ? `${base}/-/commit/${sha}` : `${base}/commit/${sha}`,
69 };
70}
71
72// Lista plana de archivos (para el command palette). Cacheada por proyecto.
73let fileListCache = null;
74export function invalidateFileList() { fileListCache = null; }
75export async function fileList() {
76 if (fileListCache) return fileListCache;
77 if (!projectHandle) return [];
78 const files = [];
79 async function walk(dir, prefix, depth) {
80 if (depth > 8 || files.length > 4000) return;
81 for await (const e of dir.values()) {
82 if (IGNORE.has(e.name)) continue;
83 const p = prefix ? prefix + '/' + e.name : e.name;
84 if (e.kind === 'directory') await walk(e, p, depth + 1);
85 else files.push(p);
86 }
87 }
88 await walk(projectHandle, '', 0);
89 fileListCache = files;
90 return files;
91}
92
93export async function openProject(handle) {
94 projectHandle = handle;
95 projectName = handle.name || 'proyecto';
96 await db.set('kv', 'project', handle).catch(() => {});
97 return projectName;
98}
99
100// Reabrir el último proyecto (el navegador puede exigir un gesto para re-conceder).
101export async function restoreProject() {
102 const h = await db.get('kv', 'project').catch(() => null);
103 if (!h) return null;
104 const q = h.queryPermission ? await h.queryPermission({ mode: 'readwrite' }) : 'granted';
105 if (q === 'granted') {
106 projectHandle = h;
107 projectName = h.name || 'proyecto';
108 return { name: projectName, ready: true };
109 }
110 return { name: h.name, ready: false, handle: h };
111}
112
113export async function regrant(h) {
114 if (await h.requestPermission({ mode: 'readwrite' }) !== 'granted')
115 throw new Error('permiso denegado');
116 return openProject(h);
117}
118
119const IGNORE = new Set(['node_modules', '.git', 'dist', 'build', 'target', '__pycache__', '.next', 'venv', '.venv', '.DS_Store']);
120const MAX_READ = 60_000;
121
122// Normaliza rutas del modelo: quita ./ y / iniciales y segmentos '.'
123const normalize = path => (path || '').split('/').filter(p => p && p !== '.');
124
125async function dirOf(path, { create = false } = {}) {
126 if (!projectHandle) throw new Error('No hay proyecto abierto');
127 const parts = normalize(path);
128 const name = parts.pop();
129 let dir = projectHandle;
130 for (const p of parts) dir = await dir.getDirectoryHandle(p, { create });
131 return { dir, name };
132}
133
134// Buscar archivos por nombre (para sugerir cuando el modelo inventa rutas, o
135// para resolver un enlace del chat que solo mencionaba el nombre del fichero).
136// Busca por NOMBRE de fichero en todo el proyecto.
137//
138// El tope era `visited > 500`, y ESE era el bug: se pidió «obj_1_Zusammenbau.stl»,
139// el fichero EXISTÍA en una subcarpeta, y el recorrido se rendía antes de llegar.
140// El error decía «no existe en este proyecto» —una afirmación falsa— y encima
141// sugería otro fichero cualquiera, el primero que hubiera cabido en el presupuesto.
142//
143// Sube a 20.000 entradas, que es un proyecto grande de verdad, y cuando se agota
144// se DICE: «no está» y «me he rendido» no son lo mismo. Con lo primero el modelo
145// deja de intentarlo.
146export const FIND_MAX_VISITED = 20000;
147// `tope` es inyectable SOLO para que el banco pueda forzar el caso «me he
148// rendido»: el orden de recorrido de OPFS es arbitrario, así que sembrar muchos
149// ficheros no garantiza agotar nada y el control negativo saldría por suerte.
150export async function findByName(basename, limit = 5, tope = FIND_MAX_VISITED) {
151 const hits = [];
152 let visited = 0;
153 let agotado = false;
154 const diana = basename.toLowerCase();
155 async function walk(dir, prefix) {
156 if (hits.length >= limit) return;
157 if (visited > tope) { agotado = true; return; }
158 for await (const e of dir.values()) {
159 if (IGNORE.has(e.name)) continue;
160 visited++;
161 const p = prefix ? prefix + '/' + e.name : e.name;
162 if (e.kind === 'directory') await walk(e, p);
163 else if (e.name.toLowerCase() === diana) hits.push(p);
164 if (hits.length >= limit) return;
165 if (visited > tope) { agotado = true; return; }
166 }
167 }
168 await walk(projectHandle, '');
169 hits.agotado = agotado;
170 return hits;
171}
172
173// Árbol de texto (para el modelo y el CONTEXTO). Ignora dependencias/binarios.
174const TREE_MAX = 800;
175export async function tree({ path = '', depth = 3 } = {}) {
176 if (!projectHandle) throw new Error('No hay proyecto abierto');
177 let root = projectHandle;
178 for (const p of normalize(path)) root = await root.getDirectoryHandle(p);
179 const out = [];
180 let count = 0, truncated = false;
181 async function walk(dir, prefix, d) {
182 if (d > depth || count >= TREE_MAX) return;
183 const entries = [];
184 for await (const e of dir.values()) entries.push(e);
185 entries.sort((a, b) => (a.kind !== b.kind) ? (a.kind === 'directory' ? -1 : 1) : a.name.localeCompare(b.name));
186 for (const e of entries) {
187 if (IGNORE.has(e.name)) continue;
188 if (++count > TREE_MAX) { truncated = true; return; }
189 out.push(prefix + (e.kind === 'directory' ? '📁 ' : '') + e.name);
190 if (e.kind === 'directory') { await walk(e, prefix + ' ', d + 1); if (truncated) return; }
191 }
192 }
193 await walk(root, '', 1);
194 let res = out.join('\n') || '(vacío)';
195 // Corte con AVISO y guía (como read/search): un «…» pelado se lee como «esto
196 // es todo» y el modelo trabaja sobre un árbol incompleto sin saberlo.
197 if (truncated)
198 res += `\n… árbol recortado (>${TREE_MAX} entradas). Acota con code.tree({path:"subcarpeta"}) o localiza con code.search.`;
199 return res;
200}
201
202const PAGE_SIZE = 100, PAGE_MAX = 500;
203
204// Lectura completa (comportamiento de siempre) O por páginas de líneas — para
205// ficheros grandes, o para plantarse justo en el número de línea que dio
206// code.search y traer contexto antes/después sin volcar el fichero entero.
207// offset: línea 1-based donde empezar (con limit, PAGE_SIZE por defecto)
208// around: centra la página en esa línea (offset = around - limit/2)
209// Sin offset/limit/around → fichero completo tal cual (no rompe nada que ya
210// dependa de leerlo entero, p.ej. code.edit).
211export async function read({ path, offset, limit, around } = {}) {
212 if (!path) throw new Error('Falta path');
213 let file, leido = path;
214 try {
215 const { dir, name } = await dirOf(path);
216 file = await (await dir.getFileHandle(name)).getFile();
217 } catch {
218 // No está en la ruta pedida. Antes aquí se lanzaba SIEMPRE, aunque la
219 // búsqueda hubiera encontrado el fichero: te decía «¿quizá X?» y te hacía
220 // gastar otro turno en pedir X. Si hay UNA sola coincidencia exacta de
221 // nombre, se lee y se dice por qué ruta; si hay varias, se eligen a mano
222 // porque adivinar la equivocada es peor que preguntar.
223 const base = normalize(path).pop() || path;
224 const hits = await findByName(base).catch(() => []);
225 if (hits.length === 1) {
226 try {
227 const { dir, name } = await dirOf(hits[0]);
228 file = await (await dir.getFileHandle(name)).getFile();
229 leido = hits[0];
230 } catch { /* se cayó también: abajo se informa */ }
231 }
232 if (!file) throw new Error(
233 (hits.agotado && !hits.length
234 ? `no he podido recorrer el proyecto entero buscando «${base}» (demasiadas entradas), así que NO sé si existe.`
235 : `no existe «${path}» en este proyecto.`) +
236 (hits.length > 1 ? ` Hay ${hits.length} con ese nombre: ${hits.join(' · ')} — repite con la ruta completa.` : '') +
237 (hits.agotado && hits.length ? ' (búsqueda incompleta: puede haber más)' : '') +
238 ' Consulta el árbol (code.tree) o busca (code.search) antes de leer.');
239 }
240 const full = await file.text();
241 // Si se resolvió por nombre, el modelo tiene que ENTERARSE de la ruta real:
242 // su siguiente code.edit usa la que él escribió y fallaría.
243 const aviso = leido === path ? '' : `(«${path}» no existe tal cual; leo ${leido})\n`;
244
245 if (offset == null && limit == null && around == null) {
246 return aviso + (full.length > MAX_READ ? full.slice(0, MAX_READ) + `\n… (recortado, ${file.size} bytes)` : full);
247 }
248
249 const lines = full.split('\n');
250 const total = lines.length;
251 const size = Math.max(1, Math.min(Math.round(limit) || PAGE_SIZE, PAGE_MAX));
252 const start = around != null
253 ? Math.max(1, Math.round(around) - Math.floor(size / 2))
254 : Math.max(1, Math.round(offset) || 1);
255 const startIdx = start - 1;
256 // Pedir más allá del final devolvía un rango imposible («líneas 999-998 de 6»)
257 // y CERO contenido: el modelo se quedaba sin nada que hacer. Mejor decírselo.
258 if (startIdx >= total)
259 return `${leido}: solo tiene ${total} líneas y pediste desde la ${start} — usa offset entre 1 y ${total}.`;
260 const slice = lines.slice(startIdx, startIdx + size);
261 const endLine = startIdx + slice.length;
262 const numbered = slice.map((l, i) => `${start + i}→${l}`).join('\n');
263 const more = endLine < total ? `\n… quedan líneas ${endLine + 1}-${total} — pide code.read con offset:${endLine + 1} para seguir` : '';
264 return `${leido}: líneas ${start}-${endLine} de ${total}\n${numbered}${more}`;
265}
266
267// Aprobación de escritura: si «Auto» está apagado, el IDE pide confirmación
268// antes de que la elfa toque archivos (como «Edit automatically» del plugin).
269let approveWrite = async () => true;
270export function setWriteApprover(fn) { approveWrite = fn; }
271
272// `write` reescribe el fichero ENTERO, así que es la vía por la que se pierde
273// código. Medido: tras dos rechazos de la guarda de sintaxis en `edit`, el
274// modelo se escapó por aquí y reescribió el fichero. En uno de cuatro líneas da
275// igual; en uno de seiscientas, así es como desaparece medio proyecto.
276// `_interno` lo pone `edit`, que ya ha comprobado lo suyo sobre el texto exacto.
277export async function write({ path, content = '', _interno = false } = {}) {
278 if (!path) throw new Error('Falta path');
279 if (!_interno) {
280 let previo = null;
281 try { const { dir, name } = await dirOf(path); previo = await (await (await dir.getFileHandle(name)).getFile()).text(); }
282 catch { /* fichero nuevo: nada que preservar */ }
283 if (previo !== null) {
284 const antes = previo.split('\n').length, ahora = content.split('\n').length;
285 // Un fichero con cuerpo que se queda en menos de la mitad casi nunca es
286 // intencionado: es el modelo reescribiendo de memoria lo que no recuerda.
287 if (antes >= 40 && ahora < antes * 0.5) {
288 anota('truncaria', path, { antes, ahora });
289 throw new Error(`Eso dejaría ${path} en ${ahora} líneas cuando tiene ${antes}: perderías el resto del fichero. ` +
290 `Para cambiar una parte usa code.edit con «search» y «replace»; code.write solo para ficheros nuevos o reescrituras completas de verdad.`);
291 }
292 revisaSintaxis(path, previo, content);
293 }
294 }
295 if (!await approveWrite(path, content)) return `Cambio en ${path} rechazado por el usuario`;
296 const { dir, name } = await dirOf(path, { create: true });
297 const fh = await dir.getFileHandle(name, { create: true });
298 const w = await fh.createWritable();
299 await w.write(content);
300 await w.close();
301 invalidateFileList();
302 onFileWritten(path, content);
303 return `Escrito ${path} (${content.split('\n').length} líneas)`;
304}
305
306// Edición PARCIAL (no hace falta reescribir el fichero entero): sustituye
307// `search` por `replace`. Primero intenta coincidencia EXACTA (rápida, sin
308// ambigüedad); si no la encuentra tal cual —el modelo puede recordar mal un
309// espacio o un salto de línea—, cae a un parcheado difuso (diff-match-patch,
310// la misma librería que usan herramientas como aider) que localiza el punto
311// más parecido dentro del fichero real. Si ni así hay confianza suficiente,
312// falla con un mensaje claro para que el agente reintente con más contexto
313// — nunca escribe una coincidencia dudosa.
314// Telemetría de edición: por qué vía se resolvió cada intento. Sin esto,
315// «la edición falla» no es accionable — no sabes si el modelo cita mal, si
316// cita ambiguo o si no encuentra el sitio.
317export const editStats = { total: 0, exacta: 0, bloque: 0, nucleo: 0, difusa: 0, ambigua: 0, noEncontrado: 0, sinCambio: 0, noExiste: 0, rompeSintaxis: 0, yaAplicado: 0, truncaria: 0, detalle: [] };
318export function resetEditStats() {
319 editStats.total = editStats.exacta = editStats.bloque = editStats.nucleo = editStats.difusa = 0;
320 editStats.ambigua = editStats.noEncontrado = editStats.sinCambio = editStats.noExiste = editStats.rompeSintaxis = editStats.yaAplicado = editStats.truncaria = 0;
321 editStats.detalle.length = 0;
322}
323const anota = (via, path, extra) => { editStats[via]++; editStats.detalle.push({ via, path, ...extra }); };
324
325// read() paginado devuelve «12→código» para que el modelo pueda pedir un
326// offset; el efecto secundario es que el modelo copia ESE texto como «search»,
327// con el número pegado delante. Entonces la cita no existe en el fichero y la
328// edición no puede encajar NUNCA — un fichero que pasa de una página se vuelve
329// ineditable. Se los quitamos, pero solo si TODAS las líneas los llevan: así
330// una flecha suelta dentro del código de verdad no se toca.
331const SIN_NUMEROS = /^[ \t]*\d+→/;
332// Exigir que TODAS las líneas lleven número no valía: un modelo pequeño numera
333// unas sí y otras no, la limpieza no se disparaba y la cita no podía casar. Con
334// mayoría basta, y «\d+→» al principio de línea es lo bastante raro en código
335// real como para no llevarse nada por delante. Se mira search y replace por
336// separado: si los números se colaran en «replace» acabarían ESCRITOS dentro
337// del fichero, que es peor que no editar.
338function quitaNumerosDeLinea(txt) {
339 if (txt == null) return txt;
340 const lineas = txt.split('\n');
341 const conCuerpo = lineas.filter(l => l.trim());
342 if (!conCuerpo.length) return txt;
343 const numeradas = conCuerpo.filter(l => SIN_NUMEROS.test(l)).length;
344 return numeradas / conCuerpo.length >= 0.6 ? lineas.map(l => l.replace(SIN_NUMEROS, '')).join('\n') : txt;
345}
346
347// Una edición que deja el fichero sintácticamente roto es peor que una que no
348// se aplica: el modelo dice «arreglado» y lo que hay es un fichero que ya ni
349// carga. Caso real medido: el modelo sustituyó la línea de la firma por una
350// función entera CON su llave de cierre, dejando huérfano el cuerpo de antes
351// («Illegal return statement»). new Function() solo PARSEA, no ejecuta; para
352// que trague un módulo hay que quitarle import/export, que son sintaxis de
353// módulo. Solo se rechaza si el fichero estaba BIEN antes: si ya venía roto,
354// la edición es justamente lo que viene a arreglarlo.
355const ES_JS = /\.(js|mjs|cjs|jsx)$/i;
356function seParsea(codigo) {
357 const sinModulo = codigo
358 .replace(/^\s*import\s+[^;]*;?\s*$/gm, '')
359 .replace(/^\s*export\s+default\s+/gm, 'void ')
360 .replace(/^\s*export\s*\{[^}]*\}\s*;?\s*$/gm, '')
361 .replace(/^(\s*)export\s+/gm, '$1');
362 try { new Function(sinModulo); return true; } catch (e) { return e instanceof SyntaxError ? String(e.message) : true; }
363}
364function revisaSintaxis(path, antes, despues) {
365 if (!ES_JS.test(path)) return;
366 if (seParsea(antes) !== true) return; // ya estaba roto: no estorbar
367 const mal = seParsea(despues);
368 if (mal !== true) {
369 anota('rompeSintaxis', path, { error: String(mal).slice(0, 80) });
370 throw new Error(`Esa edición dejaría ${path} sin poder cargarse (${mal}). ` +
371 `Suele pasar por cerrar una llave de más: revisa que «replace» encaje con lo que rodea a «search», ` +
372 `o incluye en «search» el bloque completo que vas a sustituir.`);
373 }
374}
375
376export async function edit({ path, search, replace } = {}) {
377 editStats.total++;
378 if (!path) throw new Error('Falta path');
379 if (search == null || replace == null) throw new Error('Faltan search y replace');
380 // Cada uno por su cuenta: el modelo puede numerar solo uno de los dos.
381 search = quitaNumerosDeLinea(search);
382 replace = quitaNumerosDeLinea(replace);
383 // Contenido COMPLETO, sin el tope de MAX_READ. edit reescribe el fichero
384 // entero, así que leer la vista recortada de read() truncaría todo lo que
385 // hubiese más allá de MAX_READ (bug histórico: editar un fichero >60KB lo
386 // dejaba en 60KB y metía el marcador «… (recortado)» dentro del código).
387 let current;
388 try {
389 const { dir, name } = await dirOf(path);
390 current = await (await (await dir.getFileHandle(name)).getFile()).text();
391 } catch {
392 anota('noExiste', path, {});
393 await read({ path }); // relanza el error «que enseña» (sugiere code.tree/search); nunca retorna
394 throw new Error(`no existe «${path}»`);
395 }
396
397 // Reintentar sobre algo YA hecho era un error igual que no encontrarlo, así
398 // que el modelo volvía a intentarlo en bucle. Si el resultado ya está y la
399 // cita ya no, la edición sobra: decirlo como estado y seguir. Se exige el
400 // «replace» COMPLETO presente y el «search» ausente, para no dar por buena
401 // una edición que no ocurrió.
402 if (replace.trim().length >= 8 && current.includes(replace) && !current.includes(search)) {
403 anota('yaAplicado', path, {});
404 return `Ese cambio ya está en ${path} — no hace falta editar. Sigue con lo siguiente.`;
405 }
406
407 const first = current.indexOf(search);
408 if (first !== -1) {
409 if (current.indexOf(search, first + 1) !== -1) {
410 anota('ambigua', path, { fase: 'exacta' });
411 // decir DÓNDE está, igual que en las vías difusas: pedir «más contexto»
412 // a secas hace que un modelo pequeño cite más largo y peor.
413 const lineas = [];
414 for (let i = current.indexOf(search); i !== -1 && lineas.length < 8; i = current.indexOf(search, i + 1))
415 lineas.push(current.slice(0, i).split('\n').length);
416 throw new Error(`«search» aparece ${lineas.length} veces en ${path} (líneas ${lineas.join(', ')}). ` +
417 `Cita un bloque que incluya alguna línea que solo exista en el sitio que quieres cambiar.`);
418 }
419 const siguiente = current.slice(0, first) + replace + current.slice(first + search.length);
420 // La vía difusa ya comprobaba esto abajo; la exacta no. Un search idéntico
421 // al replace escribía el mismo fichero y devolvía ÉXITO, así que el agente
422 // daba la tarea por arreglada sin haber cambiado una coma.
423 if (siguiente === current) {
424 anota('sinCambio', path, { fase: 'exacta' });
425 throw new Error(`La edición en ${path} no cambió nada: «search» y «replace» son iguales. Escribe en «replace» el código YA corregido.`);
426 }
427 revisaSintaxis(path, current, siguiente);
428 anota('exacta', path, {});
429 return write({ path, content: siguiente, _interno: true });
430 }
431
432 // fallback difuso, LOCAL y por líneas (sin depender de esm.sh en tiempo de
433 // edición — eso rompería la edición sin conexión, justo lo contrario del
434 // producto). El error típico del modelo al recordar «search» es la sangría o
435 // los espacios; localizamos el bloque normalizando espacios y, si hace falta,
436 // por parecido de líneas — y sustituimos ESE bloque, esté donde esté (también
437 // en lo hondo de un fichero grande).
438 const norm = s => s.replace(/[ \t]+/g, ' ').trim(); // .trim() se lleva también el \r final
439 // Partimos guardando el offset de carácter de cada línea: así el bloque se
440 // sustituye por CORTE EXACTO y todo lo de fuera queda byte a byte igual
441 // (incluidos sus finales de línea). Con split/join se reescribía el fichero
442 // entero y un fichero CRLF acababa con finales de línea MEZCLADOS.
443 const curLines = [], lineStart = [];
444 for (let i = 0; i <= current.length;) {
445 const nl = current.indexOf('\n', i);
446 lineStart.push(i);
447 if (nl === -1) { curLines.push(current.slice(i)); break; }
448 curLines.push(current.slice(i, nl)); // puede acabar en \r
449 i = nl + 1;
450 }
451 const crlf = (current.match(/\r\n/g) || []).length;
452 const eol = crlf && crlf * 2 >= (current.match(/\n/g) || []).length ? '\r\n' : '\n';
453 const nCur = curLines.map(norm); // normalizamos UNA vez
454 let seaLines = search.replace(/[\r\n]+$/, '').split(/\r?\n/);
455 let repLines = replace.split(/\r?\n/);
456
457 // Posiciones donde un bloque de líneas encaja (ignorando espacios).
458 const locate = (nBlock) => {
459 const at = [];
460 for (let i = 0; i + nBlock.length <= nCur.length; i++) {
461 let same = true;
462 for (let j = 0; j < nBlock.length; j++) if (nCur[i + j] !== nBlock[j]) { same = false; break; }
463 if (same) { at.push(i); if (at.length > 8) break; }
464 }
465 return at;
466 };
467 // Pedir «más contexto» a un modelo pequeño produce citas más largas y peores.
468 // Decirle en qué líneas está le deja elegir con un bloque MÁS corto y único.
469 const ambiguous = (donde = []) => new Error(
470 `«search» encaja en ${donde.length || 'varios'} sitios de ${path}` +
471 (donde.length ? ` (líneas ${donde.map(i => i + 1).join(', ')})` : '') +
472 `. Cita un bloque que incluya alguna línea que solo exista en el sitio que quieres cambiar.`);
473
474 let start = -1, k = seaLines.length;
475
476 // 1) el bloque ENTERO, idéntico salvo espacios → tiene que ser ÚNICO
477 {
478 const at = locate(seaLines.map(norm));
479 if (at.length > 1) { anota('ambigua', path, { fase: 'bloque' }); throw ambiguous(at); }
480 if (at.length === 1) { start = at[0]; anota('bloque', path, {}); }
481 }
482
483 // 2) si no aparece entero, puede ser que el fichero tenga líneas que el modelo
484 // NO vio (un comentario añadido después, p. ej.) metidas dentro del bloque.
485 // Como search y replace comparten el contexto sin tocar al principio y al
486 // final, recortamos esa parte común y buscamos solo el NÚCLEO que cambia: así
487 // lo que el modelo no vio se queda donde estaba en vez de desaparecer.
488 if (start === -1) {
489 let pre = 0, suf = 0;
490 while (pre < seaLines.length && pre < repLines.length && norm(seaLines[pre]) === norm(repLines[pre])) pre++;
491 while (suf < seaLines.length - pre && suf < repLines.length - pre &&
492 norm(seaLines[seaLines.length - 1 - suf]) === norm(repLines[repLines.length - 1 - suf])) suf++;
493 const core = seaLines.slice(pre, seaLines.length - suf);
494 if (core.length) {
495 let at = locate(core.map(norm));
496 if (at.length > 1) {
497 // desempate por CONTEXTO: gana el candidato con más líneas del contexto
498 // recortado alrededor (y solo si gana en solitario).
499 const ctx = [...seaLines.slice(0, pre), ...seaLines.slice(seaLines.length - suf)].map(norm).filter(Boolean);
500 const near = i => {
501 const from = Math.max(0, i - pre - 3), to = Math.min(nCur.length, i + core.length + suf + 3);
502 const around = nCur.slice(from, to);
503 return ctx.filter(c => around.includes(c)).length;
504 };
505 const scored = at.map(i => ({ i, s: near(i) })).sort((a, b) => b.s - a.s);
506 if (ctx.length && scored[0].s > scored[1].s) at = [scored[0].i];
507 }
508 if (at.length > 1) { anota('ambigua', path, { fase: 'nucleo' }); throw ambiguous(at); }
509 if (at.length === 1) { start = at[0]; k = core.length; repLines = repLines.slice(pre, repLines.length - suf); anota('nucleo', path, { pre, suf }); }
510 }
511 }
512
513 // 3) por parecido: la ventana con más líneas coincidentes, exigiendo ≥70% y
514 // que gane con claridad a la segunda mejor (sin ambigüedad)
515 let mejorVentana = null;
516 if (start === -1) {
517 const nSea = seaLines.map(norm);
518 let best = -1, bestScore = 0, second = 0;
519 for (let i = 0; i + k <= nCur.length; i++) {
520 let hit = 0;
521 for (let j = 0; j < k; j++) if (nCur[i + j] === nSea[j]) hit++;
522 const score = hit / k;
523 if (score > bestScore) { second = bestScore; bestScore = score; best = i; }
524 else if (score > second) second = score;
525 }
526 if (bestScore >= 0.7 && bestScore - second >= 0.2) { start = best; anota('difusa', path, { parecido: +bestScore.toFixed(2) }); }
527 else if (bestScore > 0) anota('noEncontrado', path, { mejorParecido: +bestScore.toFixed(2), segundo: +second.toFixed(2) });
528 // Pedirle que RELEA le cuesta un turno entero y a un modelo pequeño le sale
529 // una cita más larga y peor. Como ya sabemos dónde está lo más parecido,
530 // se lo damos literal y numerado: puede copiar de ahí en el mismo turno.
531 if (best >= 0 && bestScore > 0) {
532 const desde = Math.max(0, best - 2), hasta = Math.min(curLines.length, best + k + 2);
533 mejorVentana = curLines.slice(desde, hasta)
534 .map((l, i) => `${desde + i + 1}→${l}`).slice(0, 12).join('\n');
535 }
536 }
537 if (start === -1)
538 throw new Error(`No encontré en ${path} el bloque que citas. ` +
539 (mejorVentana ? `Lo más parecido que hay es esto (copia «search» LITERAL de aquí, sin los números):\n${mejorVentana}`
540 : `Léelo con code.read y copia «search» literal de esas líneas.`));
541
542 // Corte exacto del bloque [start, start+k): desde el inicio de su primera
543 // línea hasta el inicio de la siguiente (es decir, salto de línea incluido).
544 const cutFrom = lineStart[start];
545 const hasTrailingNL = start + k < lineStart.length;
546 const cutTo = hasTrailingNL ? lineStart[start + k] : current.length;
547 const block = repLines.join(eol) + (hasTrailingNL ? eol : '');
548 const nextContent = current.slice(0, cutFrom) + block + current.slice(cutTo);
549 if (nextContent === current) {
550 anota('sinCambio', path, {});
551 throw new Error(`La edición en ${path} no cambió nada — revisa «replace».`);
552 }
553 revisaSintaxis(path, current, nextContent);
554 return write({ path, content: nextContent, _interno: true });
555}
556
557// grep-lite por el proyecto (texto, con límites para no arrasar). Los topes
558// existen por rendimiento, pero si se alcanzan hay que DECÍRSELO al modelo
559// (igual que read() avisa «quedan líneas…»); si no, un corte silencioso se lee
560// como «no hay más» y el modelo da por cerrada una búsqueda incompleta.
561const SEARCH_MAX_FILES = 1500, SEARCH_MAX_HITS = 80, SEARCH_MAX_BYTES = 2_000_000;
562// Binarios: NO pueden contener el texto que se busca y leerlos como texto es
563// caro. Fuera de esta lista quedan .svg/.json/.md/.csv, que son texto y sí se
564// buscan. (Antes el tope de tamaño hacía de filtro accidental de binarios.)
565const BINARY_EXT = /\.(png|jpe?g|gif|webp|avif|ico|bmp|tiff?|mp[34]|m4a|wav|ogg|mov|avi|webm|pdf|zip|gz|bz2|xz|tar|7z|rar|woff2?|ttf|eot|otf|wasm|bin|exe|dll|so|dylib|class|jar|pyc|sqlite3?)$/i;
566export async function search({ query, ext = '' } = {}) {
567 if (!query) throw new Error('Falta query');
568 if (!projectHandle) throw new Error('No hay proyecto abierto');
569 const results = [];
570 const porNombre = []; // coincidencias en el NOMBRE del fichero
571 const skipped = []; // ficheros de texto NO buscados por tamaño
572 let checked = 0, capped = false;
573 const q = query.toLowerCase();
574 async function walk(dir, prefix) {
575 if (results.length >= SEARCH_MAX_HITS || checked >= SEARCH_MAX_FILES) { capped = true; return; }
576 for await (const e of dir.values()) {
577 if (IGNORE.has(e.name)) continue;
578 const p = prefix ? prefix + '/' + e.name : e.name;
579 if (e.kind === 'directory') { await walk(e, p); if (capped) return; continue; }
580 if (ext && !e.name.endsWith(ext)) continue;
581 // El NOMBRE cuenta como resultado, y se mira ANTES de descartar binarios.
582 // Antes no: buscar un «.stl» por su nombre devolvía «Sin resultados»
583 // aunque el fichero estuviera ahí, porque solo se grepeaba el contenido y
584 // de un binario ni se abría. «Sin resultados» leído por el modelo es «eso
585 // no existe», y a partir de ahí deja de buscar.
586 if (e.name.toLowerCase().includes(q) && porNombre.length < SEARCH_MAX_HITS)
587 porNombre.push(p);
588 if (BINARY_EXT.test(e.name)) continue;
589 const f = await e.getFile();
590 // Un fichero grande es justo donde el modelo NO puede leerlo entero, así
591 // que es el que más falta hace buscar. Se busca hasta SEARCH_MAX_BYTES; y
592 // lo que quede fuera se DICE (antes: >200KB se saltaba en silencio, y
593 // «Sin resultados» sonaba a «ese código no existe» siendo mentira).
594 if (f.size > SEARCH_MAX_BYTES) { skipped.push(p); continue; }
595 checked++;
596 const lines = (await f.text()).split('\n');
597 for (let i = 0; i < lines.length; i++) {
598 if (lines[i].toLowerCase().includes(q)) {
599 results.push(`${p}:${i + 1}: ${lines[i].trim().slice(0, 140)}`);
600 if (results.length >= SEARCH_MAX_HITS) { capped = true; break; }
601 }
602 }
603 if (results.length >= SEARCH_MAX_HITS || checked >= SEARCH_MAX_FILES) { capped = true; return; }
604 }
605 }
606 await walk(projectHandle, '');
607 // Todo lo que la búsqueda NO ha mirado se cuenta; un resultado incompleto que
608 // se presenta como completo es peor que no buscar.
609 const notes = [];
610 if (capped) notes.push(`búsqueda cortada (${results.length} resultados, ${checked} ficheros revisados) — puede haber más: afina con ext o un término más concreto`);
611 if (skipped.length) notes.push(`${skipped.length} fichero(s) NO buscados por tamaño (>${SEARCH_MAX_BYTES / 1e6} MB): ${skipped.slice(0, 3).join(', ')}${skipped.length > 3 ? '…' : ''} — mira dentro con code.read`);
612 const tail = notes.length ? '\n… ' + notes.join('. ') + '.' : '';
613 const cabecera = porNombre.length
614 ? `${porNombre.length} fichero(s) cuyo NOMBRE contiene «${query}»:\n` + porNombre.map(x => ' ' + x).join('\n') + '\n'
615 : '';
616 if (!results.length)
617 return (cabecera || `Sin resultados para «${query}»`) +
618 (cabecera && !results.length ? '(ninguna coincidencia dentro del contenido)' : '') + (tail || '');
619 return cabecera + (cabecera ? `Coincidencias en el contenido:\n` : '') + results.join('\n') + tail;
620}
621
622// ── code.run: ejecutar el código y ver qué hace de verdad ───────────────────
623//
624// Medido con Gemma E4B: arregló un bug DOS veces (cambió la constante Y el
625// operador) y dejó un fichero perfectamente válido pero incorrecto, rematando
626// con «aplicado correctamente». Ninguna guarda sintáctica puede ver eso: la
627// única forma de saberlo es ejecutarlo.
628//
629// Corre en un Worker de módulo: sin DOM, sin acceso a la página, y se le corta
630// el paso por tiempo si se cuelga en un bucle. Los imports relativos se
631// resuelven a mano contra el proyecto — sin build, un blob no sabe resolver
632// «./otro.js» por su cuenta, y sin esto solo servirían los ficheros sueltos.
633const RUN_MS = 4000, RUN_MAX_MODULOS = 40;
634
635async function moduloComoBlob(path, hechos = new Map(), profundidad = 0) {
636 const clave = normalize(path).join('/');
637 if (hechos.has(clave)) return hechos.get(clave);
638 if (hechos.size >= RUN_MAX_MODULOS || profundidad > 12)
639 throw new Error(`demasiados ficheros encadenados desde ${path}`);
640 hechos.set(clave, null); // marca de ciclo
641 const { dir, name } = await dirOf(clave);
642 let txt = await (await (await dir.getFileHandle(name)).getFile()).text();
643
644 // reescribir cada import/export relativo al blob del fichero al que apunta
645 const relativos = [...txt.matchAll(/(from\s*|import\s*\(\s*)(['"])(\.[^'"]+)\2/g)];
646 for (const m of relativos) {
647 const destino = normalize(clave.split('/').slice(0, -1).join('/') + '/' + m[3]).join('/');
648 let url;
649 try { url = await moduloComoBlob(destino, hechos, profundidad + 1); }
650 catch { continue; } // que falle al importar, no aquí
651 if (url) txt = txt.split(m[0]).join(`${m[1]}${m[2]}${url}${m[2]}`);
652 }
653 const url = URL.createObjectURL(new Blob([txt], { type: 'text/javascript' }));
654 hechos.set(clave, url);
655 return url;
656}
657
658export async function run({ path, expr } = {}) {
659 if (!path) throw new Error('Falta path');
660 if (!expr) throw new Error('Falta expr: qué quieres evaluar, p.ej. "m.max([])"');
661 if (!ES_JS.test(path)) throw new Error(`code.run solo ejecuta JavaScript, y ${path} no lo es`);
662 if (/^\s*import[\s{]/.test(expr) || /\brequire\s*\(/.test(expr))
663 throw new Error(`«expr» es solo una EXPRESIÓN, no un programa: el módulo ya está importado. ` +
664 `Escribe directamente la llamada, p.ej. «miFuncion(1, 2)» o «m.miFuncion(1, 2)».`);
665 const hechos = new Map();
666 let url;
667 try { url = await moduloComoBlob(path, hechos); }
668 catch (e) { throw new Error(`no pude preparar ${path} para ejecutarlo: ${e.message}`); }
669
670 // Los nombres exportados se ATAN como variables sueltas, además de en «m».
671 // Medido: el modelo escribe «slugify(...)» de forma natural, le saltaba un
672 // «slugify is not defined», y de ahí concluía que su arreglo estaba mal y se
673 // ponía a destrozar código que YA funcionaba — le quitó el export y rompió el
674 // módulo. La herramienta de comprobar le enseñó que lo correcto era incorrecto.
675 // Y si aun así nombra algo que no existe, el error DICE qué hay exportado, en
676 // vez de dejarle deducir que el fichero está roto.
677 const guion = `
678 self.onmessage = async ({ data }) => {
679 try {
680 const m = await import(data.url);
681 const nombres = Object.keys(m).filter(n => /^[A-Za-z_$][\\w$]*$/.test(n));
682 const fn = new Function('m', ...nombres, 'return (' + data.expr + ')');
683 const valor = await fn(m, ...nombres.map(n => m[n]));
684 let texto;
685 try { texto = JSON.stringify(valor); } catch { texto = String(valor); }
686 if (texto === undefined) texto = String(valor);
687 self.postMessage({ ok: true, tipo: typeof valor, texto });
688 } catch (e) {
689 let exporta = [];
690 try { exporta = Object.keys(await import(data.url)); } catch { /* ni carga */ }
691 self.postMessage({ ok: false, error: e.message, exporta });
692 }
693 };`;
694 const wUrl = URL.createObjectURL(new Blob([guion], { type: 'text/javascript' }));
695 const worker = new Worker(wUrl, { type: 'module' });
696 try {
697 const r = await new Promise((resolve) => {
698 // Un bucle infinito en el código del usuario no puede colgar el IDE.
699 const reloj = setTimeout(() => resolve({ ok: false, error: `no terminó en ${RUN_MS} ms (¿bucle infinito?)` }), RUN_MS);
700 worker.onmessage = e => { clearTimeout(reloj); resolve(e.data); };
701 worker.onerror = e => { clearTimeout(reloj); resolve({ ok: false, error: e.message || 'error al cargar el módulo' }); };
702 worker.postMessage({ url, expr });
703 });
704 if (r.ok) return `${expr} → ${r.texto} (${r.tipo})`;
705 // Un «X is not defined» sin más lleva al modelo a «el fichero está mal».
706 // Decirle qué exporta de verdad corta esa deducción en seco.
707 const noDefinido = /(\w+) is not defined/.exec(r.error || '');
708 const pista = noDefinido && r.exporta?.length
709 ? ` — «${noDefinido[1]}» no está en ${path}, que exporta: ${r.exporta.join(', ')}. Llámalo por su nombre o con m.<nombre>; el fichero NO tiene por qué estar mal.`
710 : (r.exporta?.length ? ` (${path} exporta: ${r.exporta.join(', ')})` : '');
711 return `${expr} lanzó: ${r.error}${pista}`;
712 } finally {
713 worker.terminate();
714 URL.revokeObjectURL(wUrl);
715 for (const u of hechos.values()) if (u) URL.revokeObjectURL(u);
716 }
717}