Elffuss BraidHub

utopia-ia/elffuss-code public

152be91d1268 · 34.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).
136export async function findByName(basename, limit = 5) {
137 const hits = [];
138 let visited = 0;
139 async function walk(dir, prefix) {
140 if (hits.length >= limit || visited > 500) return;
141 for await (const e of dir.values()) {
142 if (IGNORE.has(e.name)) continue;
143 visited++;
144 const p = prefix ? prefix + '/' + e.name : e.name;
145 if (e.kind === 'directory') await walk(e, p);
146 else if (e.name.toLowerCase() === basename.toLowerCase()) hits.push(p);
147 if (hits.length >= limit || visited > 500) return;
148 }
149 }
150 await walk(projectHandle, '');
151 return hits;
152}
153
154// Árbol de texto (para el modelo y el CONTEXTO). Ignora dependencias/binarios.
155const TREE_MAX = 800;
156export async function tree({ path = '', depth = 3 } = {}) {
157 if (!projectHandle) throw new Error('No hay proyecto abierto');
158 let root = projectHandle;
159 for (const p of normalize(path)) root = await root.getDirectoryHandle(p);
160 const out = [];
161 let count = 0, truncated = false;
162 async function walk(dir, prefix, d) {
163 if (d > depth || count >= TREE_MAX) return;
164 const entries = [];
165 for await (const e of dir.values()) entries.push(e);
166 entries.sort((a, b) => (a.kind !== b.kind) ? (a.kind === 'directory' ? -1 : 1) : a.name.localeCompare(b.name));
167 for (const e of entries) {
168 if (IGNORE.has(e.name)) continue;
169 if (++count > TREE_MAX) { truncated = true; return; }
170 out.push(prefix + (e.kind === 'directory' ? '📁 ' : '') + e.name);
171 if (e.kind === 'directory') { await walk(e, prefix + ' ', d + 1); if (truncated) return; }
172 }
173 }
174 await walk(root, '', 1);
175 let res = out.join('\n') || '(vacío)';
176 // Corte con AVISO y guía (como read/search): un «…» pelado se lee como «esto
177 // es todo» y el modelo trabaja sobre un árbol incompleto sin saberlo.
178 if (truncated)
179 res += `\n… árbol recortado (>${TREE_MAX} entradas). Acota con code.tree({path:"subcarpeta"}) o localiza con code.search.`;
180 return res;
181}
182
183const PAGE_SIZE = 100, PAGE_MAX = 500;
184
185// Lectura completa (comportamiento de siempre) O por páginas de líneas — para
186// ficheros grandes, o para plantarse justo en el número de línea que dio
187// code.search y traer contexto antes/después sin volcar el fichero entero.
188// offset: línea 1-based donde empezar (con limit, PAGE_SIZE por defecto)
189// around: centra la página en esa línea (offset = around - limit/2)
190// Sin offset/limit/around → fichero completo tal cual (no rompe nada que ya
191// dependa de leerlo entero, p.ej. code.edit).
192export async function read({ path, offset, limit, around } = {}) {
193 if (!path) throw new Error('Falta path');
194 let file;
195 try {
196 const { dir, name } = await dirOf(path);
197 file = await (await dir.getFileHandle(name)).getFile();
198 } catch {
199 // error que ENSEÑA: el modelo puede auto-corregirse en el siguiente paso
200 const base = normalize(path).pop() || path;
201 const hits = await findByName(base).catch(() => []);
202 throw new Error(`no existe «${path}» en este proyecto.` +
203 (hits.length ? ` ¿Quizá: ${hits.join(' · ')}?` : '') +
204 ' Consulta el árbol (code.tree) o busca (code.search) antes de leer.');
205 }
206 const full = await file.text();
207
208 if (offset == null && limit == null && around == null) {
209 return full.length > MAX_READ ? full.slice(0, MAX_READ) + `\n… (recortado, ${file.size} bytes)` : full;
210 }
211
212 const lines = full.split('\n');
213 const total = lines.length;
214 const size = Math.max(1, Math.min(Math.round(limit) || PAGE_SIZE, PAGE_MAX));
215 const start = around != null
216 ? Math.max(1, Math.round(around) - Math.floor(size / 2))
217 : Math.max(1, Math.round(offset) || 1);
218 const startIdx = start - 1;
219 // Pedir más allá del final devolvía un rango imposible («líneas 999-998 de 6»)
220 // y CERO contenido: el modelo se quedaba sin nada que hacer. Mejor decírselo.
221 if (startIdx >= total)
222 return `${path}: solo tiene ${total} líneas y pediste desde la ${start} — usa offset entre 1 y ${total}.`;
223 const slice = lines.slice(startIdx, startIdx + size);
224 const endLine = startIdx + slice.length;
225 const numbered = slice.map((l, i) => `${start + i}→${l}`).join('\n');
226 const more = endLine < total ? `\n… quedan líneas ${endLine + 1}-${total} — pide code.read con offset:${endLine + 1} para seguir` : '';
227 return `${path}: líneas ${start}-${endLine} de ${total}\n${numbered}${more}`;
228}
229
230// Aprobación de escritura: si «Auto» está apagado, el IDE pide confirmación
231// antes de que la elfa toque archivos (como «Edit automatically» del plugin).
232let approveWrite = async () => true;
233export function setWriteApprover(fn) { approveWrite = fn; }
234
235// `write` reescribe el fichero ENTERO, así que es la vía por la que se pierde
236// código. Medido: tras dos rechazos de la guarda de sintaxis en `edit`, el
237// modelo se escapó por aquí y reescribió el fichero. En uno de cuatro líneas da
238// igual; en uno de seiscientas, así es como desaparece medio proyecto.
239// `_interno` lo pone `edit`, que ya ha comprobado lo suyo sobre el texto exacto.
240export async function write({ path, content = '', _interno = false } = {}) {
241 if (!path) throw new Error('Falta path');
242 if (!_interno) {
243 let previo = null;
244 try { const { dir, name } = await dirOf(path); previo = await (await (await dir.getFileHandle(name)).getFile()).text(); }
245 catch { /* fichero nuevo: nada que preservar */ }
246 if (previo !== null) {
247 const antes = previo.split('\n').length, ahora = content.split('\n').length;
248 // Un fichero con cuerpo que se queda en menos de la mitad casi nunca es
249 // intencionado: es el modelo reescribiendo de memoria lo que no recuerda.
250 if (antes >= 40 && ahora < antes * 0.5) {
251 anota('truncaria', path, { antes, ahora });
252 throw new Error(`Eso dejaría ${path} en ${ahora} líneas cuando tiene ${antes}: perderías el resto del fichero. ` +
253 `Para cambiar una parte usa code.edit con «search» y «replace»; code.write solo para ficheros nuevos o reescrituras completas de verdad.`);
254 }
255 revisaSintaxis(path, previo, content);
256 }
257 }
258 if (!await approveWrite(path, content)) return `Cambio en ${path} rechazado por el usuario`;
259 const { dir, name } = await dirOf(path, { create: true });
260 const fh = await dir.getFileHandle(name, { create: true });
261 const w = await fh.createWritable();
262 await w.write(content);
263 await w.close();
264 invalidateFileList();
265 onFileWritten(path, content);
266 return `Escrito ${path} (${content.split('\n').length} líneas)`;
267}
268
269// Edición PARCIAL (no hace falta reescribir el fichero entero): sustituye
270// `search` por `replace`. Primero intenta coincidencia EXACTA (rápida, sin
271// ambigüedad); si no la encuentra tal cual —el modelo puede recordar mal un
272// espacio o un salto de línea—, cae a un parcheado difuso (diff-match-patch,
273// la misma librería que usan herramientas como aider) que localiza el punto
274// más parecido dentro del fichero real. Si ni así hay confianza suficiente,
275// falla con un mensaje claro para que el agente reintente con más contexto
276// — nunca escribe una coincidencia dudosa.
277// Telemetría de edición: por qué vía se resolvió cada intento. Sin esto,
278// «la edición falla» no es accionable — no sabes si el modelo cita mal, si
279// cita ambiguo o si no encuentra el sitio.
280export 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: [] };
281export function resetEditStats() {
282 editStats.total = editStats.exacta = editStats.bloque = editStats.nucleo = editStats.difusa = 0;
283 editStats.ambigua = editStats.noEncontrado = editStats.sinCambio = editStats.noExiste = editStats.rompeSintaxis = editStats.yaAplicado = editStats.truncaria = 0;
284 editStats.detalle.length = 0;
285}
286const anota = (via, path, extra) => { editStats[via]++; editStats.detalle.push({ via, path, ...extra }); };
287
288// read() paginado devuelve «12→código» para que el modelo pueda pedir un
289// offset; el efecto secundario es que el modelo copia ESE texto como «search»,
290// con el número pegado delante. Entonces la cita no existe en el fichero y la
291// edición no puede encajar NUNCA — un fichero que pasa de una página se vuelve
292// ineditable. Se los quitamos, pero solo si TODAS las líneas los llevan: así
293// una flecha suelta dentro del código de verdad no se toca.
294const SIN_NUMEROS = /^[ \t]*\d+→/;
295// Exigir que TODAS las líneas lleven número no valía: un modelo pequeño numera
296// unas sí y otras no, la limpieza no se disparaba y la cita no podía casar. Con
297// mayoría basta, y «\d+→» al principio de línea es lo bastante raro en código
298// real como para no llevarse nada por delante. Se mira search y replace por
299// separado: si los números se colaran en «replace» acabarían ESCRITOS dentro
300// del fichero, que es peor que no editar.
301function quitaNumerosDeLinea(txt) {
302 if (txt == null) return txt;
303 const lineas = txt.split('\n');
304 const conCuerpo = lineas.filter(l => l.trim());
305 if (!conCuerpo.length) return txt;
306 const numeradas = conCuerpo.filter(l => SIN_NUMEROS.test(l)).length;
307 return numeradas / conCuerpo.length >= 0.6 ? lineas.map(l => l.replace(SIN_NUMEROS, '')).join('\n') : txt;
308}
309
310// Una edición que deja el fichero sintácticamente roto es peor que una que no
311// se aplica: el modelo dice «arreglado» y lo que hay es un fichero que ya ni
312// carga. Caso real medido: el modelo sustituyó la línea de la firma por una
313// función entera CON su llave de cierre, dejando huérfano el cuerpo de antes
314// («Illegal return statement»). new Function() solo PARSEA, no ejecuta; para
315// que trague un módulo hay que quitarle import/export, que son sintaxis de
316// módulo. Solo se rechaza si el fichero estaba BIEN antes: si ya venía roto,
317// la edición es justamente lo que viene a arreglarlo.
318const ES_JS = /\.(js|mjs|cjs|jsx)$/i;
319function seParsea(codigo) {
320 const sinModulo = codigo
321 .replace(/^\s*import\s+[^;]*;?\s*$/gm, '')
322 .replace(/^\s*export\s+default\s+/gm, 'void ')
323 .replace(/^\s*export\s*\{[^}]*\}\s*;?\s*$/gm, '')
324 .replace(/^(\s*)export\s+/gm, '$1');
325 try { new Function(sinModulo); return true; } catch (e) { return e instanceof SyntaxError ? String(e.message) : true; }
326}
327function revisaSintaxis(path, antes, despues) {
328 if (!ES_JS.test(path)) return;
329 if (seParsea(antes) !== true) return; // ya estaba roto: no estorbar
330 const mal = seParsea(despues);
331 if (mal !== true) {
332 anota('rompeSintaxis', path, { error: String(mal).slice(0, 80) });
333 throw new Error(`Esa edición dejaría ${path} sin poder cargarse (${mal}). ` +
334 `Suele pasar por cerrar una llave de más: revisa que «replace» encaje con lo que rodea a «search», ` +
335 `o incluye en «search» el bloque completo que vas a sustituir.`);
336 }
337}
338
339export async function edit({ path, search, replace } = {}) {
340 editStats.total++;
341 if (!path) throw new Error('Falta path');
342 if (search == null || replace == null) throw new Error('Faltan search y replace');
343 // Cada uno por su cuenta: el modelo puede numerar solo uno de los dos.
344 search = quitaNumerosDeLinea(search);
345 replace = quitaNumerosDeLinea(replace);
346 // Contenido COMPLETO, sin el tope de MAX_READ. edit reescribe el fichero
347 // entero, así que leer la vista recortada de read() truncaría todo lo que
348 // hubiese más allá de MAX_READ (bug histórico: editar un fichero >60KB lo
349 // dejaba en 60KB y metía el marcador «… (recortado)» dentro del código).
350 let current;
351 try {
352 const { dir, name } = await dirOf(path);
353 current = await (await (await dir.getFileHandle(name)).getFile()).text();
354 } catch {
355 anota('noExiste', path, {});
356 await read({ path }); // relanza el error «que enseña» (sugiere code.tree/search); nunca retorna
357 throw new Error(`no existe «${path}»`);
358 }
359
360 // Reintentar sobre algo YA hecho era un error igual que no encontrarlo, así
361 // que el modelo volvía a intentarlo en bucle. Si el resultado ya está y la
362 // cita ya no, la edición sobra: decirlo como estado y seguir. Se exige el
363 // «replace» COMPLETO presente y el «search» ausente, para no dar por buena
364 // una edición que no ocurrió.
365 if (replace.trim().length >= 8 && current.includes(replace) && !current.includes(search)) {
366 anota('yaAplicado', path, {});
367 return `Ese cambio ya está en ${path} — no hace falta editar. Sigue con lo siguiente.`;
368 }
369
370 const first = current.indexOf(search);
371 if (first !== -1) {
372 if (current.indexOf(search, first + 1) !== -1) {
373 anota('ambigua', path, { fase: 'exacta' });
374 // decir DÓNDE está, igual que en las vías difusas: pedir «más contexto»
375 // a secas hace que un modelo pequeño cite más largo y peor.
376 const lineas = [];
377 for (let i = current.indexOf(search); i !== -1 && lineas.length < 8; i = current.indexOf(search, i + 1))
378 lineas.push(current.slice(0, i).split('\n').length);
379 throw new Error(`«search» aparece ${lineas.length} veces en ${path} (líneas ${lineas.join(', ')}). ` +
380 `Cita un bloque que incluya alguna línea que solo exista en el sitio que quieres cambiar.`);
381 }
382 const siguiente = current.slice(0, first) + replace + current.slice(first + search.length);
383 // La vía difusa ya comprobaba esto abajo; la exacta no. Un search idéntico
384 // al replace escribía el mismo fichero y devolvía ÉXITO, así que el agente
385 // daba la tarea por arreglada sin haber cambiado una coma.
386 if (siguiente === current) {
387 anota('sinCambio', path, { fase: 'exacta' });
388 throw new Error(`La edición en ${path} no cambió nada: «search» y «replace» son iguales. Escribe en «replace» el código YA corregido.`);
389 }
390 revisaSintaxis(path, current, siguiente);
391 anota('exacta', path, {});
392 return write({ path, content: siguiente, _interno: true });
393 }
394
395 // fallback difuso, LOCAL y por líneas (sin depender de esm.sh en tiempo de
396 // edición — eso rompería la edición sin conexión, justo lo contrario del
397 // producto). El error típico del modelo al recordar «search» es la sangría o
398 // los espacios; localizamos el bloque normalizando espacios y, si hace falta,
399 // por parecido de líneas — y sustituimos ESE bloque, esté donde esté (también
400 // en lo hondo de un fichero grande).
401 const norm = s => s.replace(/[ \t]+/g, ' ').trim(); // .trim() se lleva también el \r final
402 // Partimos guardando el offset de carácter de cada línea: así el bloque se
403 // sustituye por CORTE EXACTO y todo lo de fuera queda byte a byte igual
404 // (incluidos sus finales de línea). Con split/join se reescribía el fichero
405 // entero y un fichero CRLF acababa con finales de línea MEZCLADOS.
406 const curLines = [], lineStart = [];
407 for (let i = 0; i <= current.length;) {
408 const nl = current.indexOf('\n', i);
409 lineStart.push(i);
410 if (nl === -1) { curLines.push(current.slice(i)); break; }
411 curLines.push(current.slice(i, nl)); // puede acabar en \r
412 i = nl + 1;
413 }
414 const crlf = (current.match(/\r\n/g) || []).length;
415 const eol = crlf && crlf * 2 >= (current.match(/\n/g) || []).length ? '\r\n' : '\n';
416 const nCur = curLines.map(norm); // normalizamos UNA vez
417 let seaLines = search.replace(/[\r\n]+$/, '').split(/\r?\n/);
418 let repLines = replace.split(/\r?\n/);
419
420 // Posiciones donde un bloque de líneas encaja (ignorando espacios).
421 const locate = (nBlock) => {
422 const at = [];
423 for (let i = 0; i + nBlock.length <= nCur.length; i++) {
424 let same = true;
425 for (let j = 0; j < nBlock.length; j++) if (nCur[i + j] !== nBlock[j]) { same = false; break; }
426 if (same) { at.push(i); if (at.length > 8) break; }
427 }
428 return at;
429 };
430 // Pedir «más contexto» a un modelo pequeño produce citas más largas y peores.
431 // Decirle en qué líneas está le deja elegir con un bloque MÁS corto y único.
432 const ambiguous = (donde = []) => new Error(
433 `«search» encaja en ${donde.length || 'varios'} sitios de ${path}` +
434 (donde.length ? ` (líneas ${donde.map(i => i + 1).join(', ')})` : '') +
435 `. Cita un bloque que incluya alguna línea que solo exista en el sitio que quieres cambiar.`);
436
437 let start = -1, k = seaLines.length;
438
439 // 1) el bloque ENTERO, idéntico salvo espacios → tiene que ser ÚNICO
440 {
441 const at = locate(seaLines.map(norm));
442 if (at.length > 1) { anota('ambigua', path, { fase: 'bloque' }); throw ambiguous(at); }
443 if (at.length === 1) { start = at[0]; anota('bloque', path, {}); }
444 }
445
446 // 2) si no aparece entero, puede ser que el fichero tenga líneas que el modelo
447 // NO vio (un comentario añadido después, p. ej.) metidas dentro del bloque.
448 // Como search y replace comparten el contexto sin tocar al principio y al
449 // final, recortamos esa parte común y buscamos solo el NÚCLEO que cambia: así
450 // lo que el modelo no vio se queda donde estaba en vez de desaparecer.
451 if (start === -1) {
452 let pre = 0, suf = 0;
453 while (pre < seaLines.length && pre < repLines.length && norm(seaLines[pre]) === norm(repLines[pre])) pre++;
454 while (suf < seaLines.length - pre && suf < repLines.length - pre &&
455 norm(seaLines[seaLines.length - 1 - suf]) === norm(repLines[repLines.length - 1 - suf])) suf++;
456 const core = seaLines.slice(pre, seaLines.length - suf);
457 if (core.length) {
458 let at = locate(core.map(norm));
459 if (at.length > 1) {
460 // desempate por CONTEXTO: gana el candidato con más líneas del contexto
461 // recortado alrededor (y solo si gana en solitario).
462 const ctx = [...seaLines.slice(0, pre), ...seaLines.slice(seaLines.length - suf)].map(norm).filter(Boolean);
463 const near = i => {
464 const from = Math.max(0, i - pre - 3), to = Math.min(nCur.length, i + core.length + suf + 3);
465 const around = nCur.slice(from, to);
466 return ctx.filter(c => around.includes(c)).length;
467 };
468 const scored = at.map(i => ({ i, s: near(i) })).sort((a, b) => b.s - a.s);
469 if (ctx.length && scored[0].s > scored[1].s) at = [scored[0].i];
470 }
471 if (at.length > 1) { anota('ambigua', path, { fase: 'nucleo' }); throw ambiguous(at); }
472 if (at.length === 1) { start = at[0]; k = core.length; repLines = repLines.slice(pre, repLines.length - suf); anota('nucleo', path, { pre, suf }); }
473 }
474 }
475
476 // 3) por parecido: la ventana con más líneas coincidentes, exigiendo ≥70% y
477 // que gane con claridad a la segunda mejor (sin ambigüedad)
478 let mejorVentana = null;
479 if (start === -1) {
480 const nSea = seaLines.map(norm);
481 let best = -1, bestScore = 0, second = 0;
482 for (let i = 0; i + k <= nCur.length; i++) {
483 let hit = 0;
484 for (let j = 0; j < k; j++) if (nCur[i + j] === nSea[j]) hit++;
485 const score = hit / k;
486 if (score > bestScore) { second = bestScore; bestScore = score; best = i; }
487 else if (score > second) second = score;
488 }
489 if (bestScore >= 0.7 && bestScore - second >= 0.2) { start = best; anota('difusa', path, { parecido: +bestScore.toFixed(2) }); }
490 else if (bestScore > 0) anota('noEncontrado', path, { mejorParecido: +bestScore.toFixed(2), segundo: +second.toFixed(2) });
491 // Pedirle que RELEA le cuesta un turno entero y a un modelo pequeño le sale
492 // una cita más larga y peor. Como ya sabemos dónde está lo más parecido,
493 // se lo damos literal y numerado: puede copiar de ahí en el mismo turno.
494 if (best >= 0 && bestScore > 0) {
495 const desde = Math.max(0, best - 2), hasta = Math.min(curLines.length, best + k + 2);
496 mejorVentana = curLines.slice(desde, hasta)
497 .map((l, i) => `${desde + i + 1}→${l}`).slice(0, 12).join('\n');
498 }
499 }
500 if (start === -1)
501 throw new Error(`No encontré en ${path} el bloque que citas. ` +
502 (mejorVentana ? `Lo más parecido que hay es esto (copia «search» LITERAL de aquí, sin los números):\n${mejorVentana}`
503 : `Léelo con code.read y copia «search» literal de esas líneas.`));
504
505 // Corte exacto del bloque [start, start+k): desde el inicio de su primera
506 // línea hasta el inicio de la siguiente (es decir, salto de línea incluido).
507 const cutFrom = lineStart[start];
508 const hasTrailingNL = start + k < lineStart.length;
509 const cutTo = hasTrailingNL ? lineStart[start + k] : current.length;
510 const block = repLines.join(eol) + (hasTrailingNL ? eol : '');
511 const nextContent = current.slice(0, cutFrom) + block + current.slice(cutTo);
512 if (nextContent === current) {
513 anota('sinCambio', path, {});
514 throw new Error(`La edición en ${path} no cambió nada — revisa «replace».`);
515 }
516 revisaSintaxis(path, current, nextContent);
517 return write({ path, content: nextContent, _interno: true });
518}
519
520// grep-lite por el proyecto (texto, con límites para no arrasar). Los topes
521// existen por rendimiento, pero si se alcanzan hay que DECÍRSELO al modelo
522// (igual que read() avisa «quedan líneas…»); si no, un corte silencioso se lee
523// como «no hay más» y el modelo da por cerrada una búsqueda incompleta.
524const SEARCH_MAX_FILES = 1500, SEARCH_MAX_HITS = 80, SEARCH_MAX_BYTES = 2_000_000;
525// Binarios: NO pueden contener el texto que se busca y leerlos como texto es
526// caro. Fuera de esta lista quedan .svg/.json/.md/.csv, que son texto y sí se
527// buscan. (Antes el tope de tamaño hacía de filtro accidental de binarios.)
528const 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;
529export async function search({ query, ext = '' } = {}) {
530 if (!query) throw new Error('Falta query');
531 if (!projectHandle) throw new Error('No hay proyecto abierto');
532 const results = [];
533 const skipped = []; // ficheros de texto NO buscados por tamaño
534 let checked = 0, capped = false;
535 const q = query.toLowerCase();
536 async function walk(dir, prefix) {
537 if (results.length >= SEARCH_MAX_HITS || checked >= SEARCH_MAX_FILES) { capped = true; return; }
538 for await (const e of dir.values()) {
539 if (IGNORE.has(e.name)) continue;
540 const p = prefix ? prefix + '/' + e.name : e.name;
541 if (e.kind === 'directory') { await walk(e, p); if (capped) return; continue; }
542 if (ext && !e.name.endsWith(ext)) continue;
543 if (BINARY_EXT.test(e.name)) continue;
544 const f = await e.getFile();
545 // Un fichero grande es justo donde el modelo NO puede leerlo entero, así
546 // que es el que más falta hace buscar. Se busca hasta SEARCH_MAX_BYTES; y
547 // lo que quede fuera se DICE (antes: >200KB se saltaba en silencio, y
548 // «Sin resultados» sonaba a «ese código no existe» siendo mentira).
549 if (f.size > SEARCH_MAX_BYTES) { skipped.push(p); continue; }
550 checked++;
551 const lines = (await f.text()).split('\n');
552 for (let i = 0; i < lines.length; i++) {
553 if (lines[i].toLowerCase().includes(q)) {
554 results.push(`${p}:${i + 1}: ${lines[i].trim().slice(0, 140)}`);
555 if (results.length >= SEARCH_MAX_HITS) { capped = true; break; }
556 }
557 }
558 if (results.length >= SEARCH_MAX_HITS || checked >= SEARCH_MAX_FILES) { capped = true; return; }
559 }
560 }
561 await walk(projectHandle, '');
562 // Todo lo que la búsqueda NO ha mirado se cuenta; un resultado incompleto que
563 // se presenta como completo es peor que no buscar.
564 const notes = [];
565 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`);
566 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`);
567 const tail = notes.length ? '\n… ' + notes.join('. ') + '.' : '';
568 if (!results.length)
569 return `Sin resultados para «${query}»` + (tail || '');
570 return results.join('\n') + tail;
571}
572
573// ── code.run: ejecutar el código y ver qué hace de verdad ───────────────────
574//
575// Medido con Gemma E4B: arregló un bug DOS veces (cambió la constante Y el
576// operador) y dejó un fichero perfectamente válido pero incorrecto, rematando
577// con «aplicado correctamente». Ninguna guarda sintáctica puede ver eso: la
578// única forma de saberlo es ejecutarlo.
579//
580// Corre en un Worker de módulo: sin DOM, sin acceso a la página, y se le corta
581// el paso por tiempo si se cuelga en un bucle. Los imports relativos se
582// resuelven a mano contra el proyecto — sin build, un blob no sabe resolver
583// «./otro.js» por su cuenta, y sin esto solo servirían los ficheros sueltos.
584const RUN_MS = 4000, RUN_MAX_MODULOS = 40;
585
586async function moduloComoBlob(path, hechos = new Map(), profundidad = 0) {
587 const clave = normalize(path).join('/');
588 if (hechos.has(clave)) return hechos.get(clave);
589 if (hechos.size >= RUN_MAX_MODULOS || profundidad > 12)
590 throw new Error(`demasiados ficheros encadenados desde ${path}`);
591 hechos.set(clave, null); // marca de ciclo
592 const { dir, name } = await dirOf(clave);
593 let txt = await (await (await dir.getFileHandle(name)).getFile()).text();
594
595 // reescribir cada import/export relativo al blob del fichero al que apunta
596 const relativos = [...txt.matchAll(/(from\s*|import\s*\(\s*)(['"])(\.[^'"]+)\2/g)];
597 for (const m of relativos) {
598 const destino = normalize(clave.split('/').slice(0, -1).join('/') + '/' + m[3]).join('/');
599 let url;
600 try { url = await moduloComoBlob(destino, hechos, profundidad + 1); }
601 catch { continue; } // que falle al importar, no aquí
602 if (url) txt = txt.split(m[0]).join(`${m[1]}${m[2]}${url}${m[2]}`);
603 }
604 const url = URL.createObjectURL(new Blob([txt], { type: 'text/javascript' }));
605 hechos.set(clave, url);
606 return url;
607}
608
609export async function run({ path, expr } = {}) {
610 if (!path) throw new Error('Falta path');
611 if (!expr) throw new Error('Falta expr: qué quieres evaluar, p.ej. "m.max([])"');
612 if (!ES_JS.test(path)) throw new Error(`code.run solo ejecuta JavaScript, y ${path} no lo es`);
613 if (/^\s*import[\s{]/.test(expr) || /\brequire\s*\(/.test(expr))
614 throw new Error(`«expr» es solo una EXPRESIÓN, no un programa: el módulo ya está importado. ` +
615 `Escribe directamente la llamada, p.ej. «miFuncion(1, 2)» o «m.miFuncion(1, 2)».`);
616 const hechos = new Map();
617 let url;
618 try { url = await moduloComoBlob(path, hechos); }
619 catch (e) { throw new Error(`no pude preparar ${path} para ejecutarlo: ${e.message}`); }
620
621 // Los nombres exportados se ATAN como variables sueltas, además de en «m».
622 // Medido: el modelo escribe «slugify(...)» de forma natural, le saltaba un
623 // «slugify is not defined», y de ahí concluía que su arreglo estaba mal y se
624 // ponía a destrozar código que YA funcionaba — le quitó el export y rompió el
625 // módulo. La herramienta de comprobar le enseñó que lo correcto era incorrecto.
626 // Y si aun así nombra algo que no existe, el error DICE qué hay exportado, en
627 // vez de dejarle deducir que el fichero está roto.
628 const guion = `
629 self.onmessage = async ({ data }) => {
630 try {
631 const m = await import(data.url);
632 const nombres = Object.keys(m).filter(n => /^[A-Za-z_$][\\w$]*$/.test(n));
633 const fn = new Function('m', ...nombres, 'return (' + data.expr + ')');
634 const valor = await fn(m, ...nombres.map(n => m[n]));
635 let texto;
636 try { texto = JSON.stringify(valor); } catch { texto = String(valor); }
637 if (texto === undefined) texto = String(valor);
638 self.postMessage({ ok: true, tipo: typeof valor, texto });
639 } catch (e) {
640 let exporta = [];
641 try { exporta = Object.keys(await import(data.url)); } catch { /* ni carga */ }
642 self.postMessage({ ok: false, error: e.message, exporta });
643 }
644 };`;
645 const wUrl = URL.createObjectURL(new Blob([guion], { type: 'text/javascript' }));
646 const worker = new Worker(wUrl, { type: 'module' });
647 try {
648 const r = await new Promise((resolve) => {
649 // Un bucle infinito en el código del usuario no puede colgar el IDE.
650 const reloj = setTimeout(() => resolve({ ok: false, error: `no terminó en ${RUN_MS} ms (¿bucle infinito?)` }), RUN_MS);
651 worker.onmessage = e => { clearTimeout(reloj); resolve(e.data); };
652 worker.onerror = e => { clearTimeout(reloj); resolve({ ok: false, error: e.message || 'error al cargar el módulo' }); };
653 worker.postMessage({ url, expr });
654 });
655 if (r.ok) return `${expr} → ${r.texto} (${r.tipo})`;
656 // Un «X is not defined» sin más lleva al modelo a «el fichero está mal».
657 // Decirle qué exporta de verdad corta esa deducción en seco.
658 const noDefinido = /(\w+) is not defined/.exec(r.error || '');
659 const pista = noDefinido && r.exporta?.length
660 ? ` — «${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.`
661 : (r.exporta?.length ? ` (${path} exporta: ${r.exporta.join(', ')})` : '');
662 return `${expr} lanzó: ${r.error}${pista}`;
663 } finally {
664 worker.terminate();
665 URL.revokeObjectURL(wUrl);
666 for (const u of hechos.values()) if (u) URL.revokeObjectURL(u);
667 }
668}