Elffuss BraidHub

utopia-ia/elffuss-code public

main · 13.6 KiBRawPermalink
1// Guardia de regresión: code.edit sobre ficheros y proyectos GRANDES.
2// Cada assert nació de un bug real (ago-2026):
3// 1) edit() leía la vista recortada de read() (MAX_READ=60KB) y al reescribir
4// TRUNCABA cualquier fichero >60KB, metiendo «… (recortado)» en el código.
5// 2) search() cortaba a 400 ficheros / 80 hits EN SILENCIO (el modelo no sabía
6// que la búsqueda estaba incompleta).
7// 3) el fallback difuso (diff-match-patch por esm.sh) no localizaba objetivos
8// profundos, aplicaba el parche en OTRO sitio y REPORTABA ÉXITO (falso
9// positivo); además dependía de la red (rompía la edición sin conexión).
10// 4) code.tree cortaba a 350 entradas con un «…» pelado: el modelo daba por
11// completo un árbol que no lo estaba.
12// 5) search se saltaba EN SILENCIO todo fichero >200KB — «Sin resultados»
13// sonaba a «ese código no existe» siendo mentira, y justo en los ficheros
14// grandes, que son los que el modelo no puede leer enteros.
15// 6) read con offset más allá del final devolvía un rango imposible
16// («líneas 999-998 de 6») y ningún contenido.
17// 7) el difuso rehacía el fichero con split/join('\n'): un fichero CRLF salía
18// con finales de línea MEZCLADOS (se tocaba lo que no se había editado).
19// Determinista, sin modelo (modo rules). Corre contra local o producción:
20// BASE=http://localhost:8790 node bigfile_edit.mjs
21import { chromium } from 'playwright';
22const BASE = process.env.BASE || 'http://localhost:8790';
23let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; };
24
25const b = await chromium.launch();
26const ctx = await b.newContext();
27await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} });
28const p = await ctx.newPage();
29await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' });
30
31// ---------- 1 · edición exacta en fichero grande (>60KB) sin truncar ----------
32await p.evaluate(async () => {
33 const o = await navigator.storage.getDirectory();
34 const w = await (await o.getFileHandle('big.js', { create: true })).createWritable();
35 let s = 'export const VERSION = "1.0.0"; // EDIT_ME\n';
36 for (let i = 1; i <= 3000; i++) s += `function f${i}(){ return ${i}; } // relleno\n`;
37 s += 'export const TAIL = "SENTINEL_END";\n';
38 await w.write(s); await w.close();
39});
40await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(1200);
41{
42 const r = await p.evaluate(async () => {
43 const code = await import('/js/tools/code.js');
44 await code.edit({ path: 'big.js', search: 'VERSION = "1.0.0"', replace: 'VERSION = "2.0.0"' });
45 const o = await navigator.storage.getDirectory();
46 const t = await (await (await o.getFileHandle('big.js')).getFile()).text();
47 return { edit: t.includes('2.0.0'), tail: t.includes('SENTINEL_END'), trunc: t.includes('recortado'), lines: t.split('\n').length };
48 });
49 ok('1 · fichero >60KB: la edición se aplica', r.edit);
50 ok('1 · fichero >60KB: el final SOBREVIVE (no trunca)', r.tail, `${r.lines} líneas`);
51 ok('1 · fichero >60KB: no inyecta «recortado» en el código', !r.trunc);
52}
53
54// ---------- 2 · edición DIFUSA (sangría distinta) en lo hondo, y rechazo seguro ----------
55await p.evaluate(async () => {
56 const o = await navigator.storage.getDirectory();
57 const w = await (await o.getFileHandle('deep.js', { create: true })).createWritable();
58 let s = 'const HEAD=1;\n';
59 for (let i = 1; i <= 3000; i++) s += (i === 2000)
60 ? ' function computeTax(rate){\n return rate * 0.21;\n }\n'
61 : `function g${i}(){ return ${i}; }\n`;
62 s += 'const TAIL="KEEP_ME";\n';
63 await w.write(s); await w.close();
64});
65await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(1000);
66{
67 const A = await p.evaluate(async () => {
68 const code = await import('/js/tools/code.js');
69 let err = null;
70 try { await code.edit({ path: 'deep.js', search: 'function computeTax(rate){\nreturn rate * 0.21;\n}', replace: 'function computeTax(rate){\n return rate * 0.27;\n }' }); } catch (e) { err = e.message; }
71 const o = await navigator.storage.getDirectory();
72 const t = await (await (await o.getFileHandle('deep.js')).getFile()).text();
73 return { err, applied: t.includes('0.27'), tail: t.includes('KEEP_ME'), tax: (t.match(/computeTax/g) || []).length, lines: t.split('\n').length };
74 });
75 ok('2 · difuso: aplica pese a sangría distinta, en lo hondo del fichero', A.applied && !A.err);
76 ok('2 · difuso: sin duplicar, cola preservada, sin truncar', A.tax === 1 && A.tail && A.lines >= 3000);
77
78 const B = await p.evaluate(async () => {
79 const code = await import('/js/tools/code.js');
80 const o = await navigator.storage.getDirectory();
81 const before = await (await (await o.getFileHandle('deep.js')).getFile()).text();
82 let threw = false; try { await code.edit({ path: 'deep.js', search: 'function noExiste(zzz){ return 42; }', replace: 'BOOM' }); } catch { threw = true; }
83 const after = await (await (await o.getFileHandle('deep.js')).getFile()).text();
84 return { threw, intact: before === after };
85 });
86 ok('2 · seguridad: un search inexistente se RECHAZA sin tocar el fichero', B.threw && B.intact);
87}
88
89// ---------- 3 · proyecto grande: search encuentra y AVISA al cortar ----------
90await p.evaluate(async () => {
91 const o = await navigator.storage.getDirectory();
92 const d = await o.getDirectoryHandle('lib', { create: true });
93 for (let i = 0; i < 100; i++) {
94 const w = await (await d.getFileHandle('c' + i + '.js', { create: true })).createWritable();
95 await w.write('const WIDGET = ' + i + ';\n'); await w.close();
96 }
97});
98await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(1000);
99{
100 const r = await p.evaluate(async () => {
101 const code = await import('/js/tools/code.js');
102 const s = await code.search({ query: 'WIDGET' });
103 return { hits: s.split('\n').filter(l => /c\d+\.js/.test(l)).length, capped: /cortada/.test(s) };
104 });
105 ok('3 · proyecto grande: search encuentra resultados', r.hits > 0);
106 ok('3 · proyecto grande: AVISA cuando corta (no corte silencioso)', r.capped);
107}
108
109// ---------- 4 · code.tree: al cortar, AVISA y guía (no un «…» pelado) ----------
110await p.evaluate(async () => {
111 const o = await navigator.storage.getDirectory();
112 const d = await o.getDirectoryHandle('many', { create: true });
113 for (let i = 0; i < 900; i++) { const w = await (await d.getFileHandle('t' + i + '.js', { create: true })).createWritable(); await w.write('//' + i); await w.close(); }
114});
115await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(1000);
116{
117 const t = await p.evaluate(async () => (await import('/js/tools/code.js')).tree({ depth: 3 }));
118 ok('4 · proyecto grande: code.tree AVISA al cortar y dice cómo ver más', /recortado/.test(t) && /(code\.tree|code\.search)/.test(t));
119}
120
121// ---------- 5 · fichero de varios MB: edita rápido, sin truncar ----------
122await p.evaluate(async () => {
123 const o = await navigator.storage.getDirectory();
124 const w = await (await o.getFileHandle('huge.js', { create: true })).createWritable();
125 const parts = ['const HEAD=1;\n'];
126 for (let i = 1; i <= 40000; i++) parts.push(i === 30000 ? 'export function target(){ return "AAA"; }\n' : `function h${i}(){ return ${i}; }\n`);
127 parts.push('const TAIL="HUGE_TAIL";\n');
128 await w.write(parts.join('')); await w.close();
129});
130await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(1200);
131{
132 const r = await p.evaluate(async () => {
133 const code = await import('/js/tools/code.js');
134 const t0 = performance.now();
135 await code.edit({ path: 'huge.js', search: 'export function target(){ return "AAA"; }', replace: 'export function target(){ return "BBB"; }' });
136 const ms = performance.now() - t0;
137 const o = await navigator.storage.getDirectory();
138 const t = await (await (await o.getFileHandle('huge.js')).getFile()).text();
139 return { ms: Math.round(ms), edit: t.includes('"BBB"'), tail: t.includes('HUGE_TAIL'), lines: t.split('\n').length };
140 });
141 ok('5 · fichero de varios MB: edición aplicada, cola intacta, sin truncar', r.edit && r.tail && r.lines >= 40000);
142 ok('5 · fichero de varios MB: rápido (<4s)', r.ms < 4000, `${r.ms}ms`);
143}
144
145// ---------- 6 · search DENTRO de ficheros grandes, y confiesa lo que no miró ----------
146// Bug: se saltaba EN SILENCIO todo fichero >200KB, así que «Sin resultados» se
147// leía como «ese código no existe» — mentira. Y un fichero grande es justo el
148// que el modelo no puede leer entero: el que más falta hace poder buscar.
149await p.evaluate(async () => {
150 const o = await navigator.storage.getDirectory();
151 const put = async (n, s) => { const w = await (await o.getFileHandle(n, { create: true })).createWritable(); await w.write(s); await w.close(); };
152 let mid = ''; for (let i = 0; i < 5000; i++) mid += `const p${i} = ${i}; // relleno relleno relleno\n`;
153 await put('mid.js', mid + 'const MID_NEEDLE = 1;\n'); // ~250KB (antes: invisible)
154 let mb = ''; for (let i = 0; i < 60000; i++) mb += `function m${i}(){ return ${i}; }\n`;
155 await put('mb.js', mb); // >2MB (fuera de tope: hay que DECIRLO)
156});
157await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(1200);
158{
159 const r = await p.evaluate(async () => {
160 const code = await import('/js/tools/code.js');
161 const s = await code.search({ query: 'MID_NEEDLE' });
162 return { found: /mid\.js:\d+/.test(s), declares: /NO buscados por tamaño/.test(s) && /mb\.js/.test(s), raw: s.slice(0, 200) };
163 });
164 ok('6 · search encuentra dentro de un fichero de ~250KB', r.found, r.raw);
165 ok('6 · search DECLARA los ficheros que no pudo mirar por tamaño', r.declares);
166}
167
168// ---------- 7 · bordes: leer más allá del final, y CRLF que sobrevive a edit ----------
169await p.evaluate(async () => {
170 const o = await navigator.storage.getDirectory();
171 const put = async (n, s) => { const w = await (await o.getFileHandle(n, { create: true })).createWritable(); await w.write(s); await w.close(); };
172 await put('small.js', 'a\nb\nc\nd\ne\n');
173 await put('crlf.js', 'const A = 1;\r\n function calc(x){\r\n return x + 1;\r\n }\r\nconst B = 2;\r\n');
174});
175await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(1000);
176{
177 const r = await p.evaluate(async () => {
178 const code = await import('/js/tools/code.js');
179 const past = await code.read({ path: 'small.js', offset: 999, limit: 10 });
180 // sangría distinta a propósito → entra por el camino difuso, que es el que
181 // reescribía el bloque con finales de línea LF y dejaba el fichero mezclado
182 await code.edit({ path: 'crlf.js', search: 'function calc(x){\nreturn x + 1;\n}', replace: 'function calc(x){\n return x + 2;\n }' });
183 const o = await navigator.storage.getDirectory();
184 const t = await (await (await o.getFileHandle('crlf.js')).getFile()).text();
185 return {
186 pastSane: !/líneas 999-998/.test(past) && /6/.test(past),
187 applied: t.includes('x + 2'),
188 crs: (t.match(/\r/g) || []).length,
189 lfAlone: /[^\r]\n/.test(t),
190 };
191 });
192 ok('7 · read más allá del final: mensaje útil, no un rango imposible', r.pastSane);
193 ok('7 · CRLF: la edición se aplica…', r.applied);
194 ok('7 · CRLF: …y NO mezcla finales de línea (los 5 CR siguen ahí)', r.crs === 5 && !r.lfAlone, `${r.crs} CR`);
195}
196
197// ---------- 8 · el fichero tiene líneas que el modelo NO vio, en lo hondo ----------
198// Bug: al cambiar diff-match-patch por el emparejador por líneas, se perdió la
199// tolerancia a líneas INSERTADAS dentro del bloque (un comentario añadido
200// después). El bloque entero dejaba de encajar y edit fallaba del todo; y si
201// hubiese encajado por parecido, se habría COMIDO la línea no vista.
202await p.evaluate(async () => {
203 const o = await navigator.storage.getDirectory();
204 const w = await (await o.getFileHandle('shift.js', { create: true })).createWritable();
205 let s = 'const HEAD=1;\n';
206 for (let i = 1; i <= 4000; i++) s += (i === 2500)
207 ? 'function precio(base){\n // TODO: revisar con contabilidad (añadido luego)\n const iva = 0.21;\n return base * (1 + iva);\n}\n'
208 : `function s${i}(){ return ${i}; }\n`;
209 s += 'const TAIL="SHIFT_TAIL";\n';
210 await w.write(s); await w.close();
211});
212await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(1200);
213{
214 const r = await p.evaluate(async () => {
215 const code = await import('/js/tools/code.js');
216 let err = null;
217 // el modelo recuerda la función SIN el comentario que se añadió después
218 try {
219 await code.edit({
220 path: 'shift.js',
221 search: 'function precio(base){\n const iva = 0.21;\n return base * (1 + iva);\n}',
222 replace: 'function precio(base){\n const iva = 0.10;\n return base * (1 + iva);\n}',
223 });
224 } catch (e) { err = e.message; }
225 const o = await navigator.storage.getDirectory();
226 const t = await (await (await o.getFileHandle('shift.js')).getFile()).text();
227 return { err, applied: t.includes('0.10'), keptComment: t.includes('contabilidad'), tail: t.includes('SHIFT_TAIL'), lines: t.split('\n').length };
228 });
229 ok('8 · el modelo no vio una línea intermedia: la edición SE APLICA igual', r.applied && !r.err, r.err || '');
230 ok('8 · …y la línea que no vio SIGUE ahí (no se la come)', r.keptComment);
231 ok('8 · …y el resto del fichero grande queda intacto', r.tail && r.lines >= 4000);
232}
233
234console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ TODO VERDE — edición y búsqueda robustas en grande');
235await b.close();
236process.exit(fails ? 1 : 0);