| 1 | // BATERÍA DURA DE EDICIÓN — sin modelo, determinista. |
| 2 | // Aísla code.edit del resto del agente: cada caso es una forma REAL en que un |
| 3 | // modelo pequeño cita mal el bloque a cambiar. Así «la edición falla» deja de |
| 4 | // ser una queja y pasa a ser una lista de causas con nombre. |
| 5 | import { createRequire } from 'module'; |
| 6 | // playwright se resuelve desde NODE_PATH o desde node_modules del proyecto |
| 7 | const { chromium } = createRequire(import.meta.url)('playwright'); |
| 8 | |
| 9 | const CASOS = [ |
| 10 | // id, fichero, search, replace, qué debe pasar |
| 11 | { id: 'exacta', desc: 'cita literal', |
| 12 | f: 'a.js', txt: 'const a = 1;\nconst b = 2;\n', s: 'const b = 2;', r: 'const b = 3;', esperado: 'const b = 3;' }, |
| 13 | |
| 14 | { id: 'sangria-mal', desc: 'el modelo reindenta al citar', |
| 15 | f: 'a.js', txt: 'function f() {\n return 1;\n}\n', s: 'function f() {\n return 1;\n}', r: 'function f() {\n return 2;\n}', esperado: 'return 2;' }, |
| 16 | |
| 17 | { id: 'tabs-vs-espacios', desc: 'el fichero usa tabs, el modelo espacios', |
| 18 | f: 'a.js', txt: 'function f() {\n\treturn 1;\n}\n', s: 'function f() {\n return 1;\n}', r: 'function f() {\n return 9;\n}', esperado: 'return 9;' }, |
| 19 | |
| 20 | { id: 'numeros-de-linea', desc: 'el modelo copia «12→» de la lectura paginada', |
| 21 | f: 'a.js', txt: 'const a = 1;\nconst b = 2;\n', s: '2→const b = 2;', r: '2→const b = 7;', esperado: 'const b = 7;' }, |
| 22 | |
| 23 | { id: 'numeros-parciales', desc: 'el modelo numera unas líneas sí y otras no', |
| 24 | f: 'a.js', txt: 'const a = 1;\nconst b = 2;\nconst c = 3;\n', s: '1→const a = 1;\nconst b = 2;\n3→const c = 3;', |
| 25 | r: '1→const a = 9;\nconst b = 2;\n3→const c = 3;', esperado: 'const a = 9;', noContiene: '→' }, |
| 26 | |
| 27 | { id: 'numeros-en-replace', desc: 'los números NO pueden acabar escritos dentro del fichero', |
| 28 | f: 'a.js', txt: 'const a = 1;\nconst b = 2;\n', s: 'const b = 2;', r: '2→const b = 7;', noContiene: '→' }, |
| 29 | |
| 30 | { id: 'ya-aplicado', desc: 'el cambio ya está hecho → estado, no error (si no, reintenta en bucle)', |
| 31 | f: 'a.js', txt: 'function f() {\n return 2;\n}\n', s: ' return 1;', r: ' return 2;', sinError: true }, |
| 32 | |
| 33 | { id: 'error-ensena', desc: 'si no encuentra la cita, el error trae las líneas reales', |
| 34 | f: 'a.js', txt: 'function calcula(a, b) {\n const t = a * b;\n return t;\n}\n', |
| 35 | s: 'function calcula(x, y) {\n const total = x * y;\n return total;\n}', r: 'lo que sea', debeFallar: true, errorTrae: 'const t = a * b' }, |
| 36 | |
| 37 | { id: 'ambigua-dice-donde', desc: 'la ambigüedad dice EN QUÉ LÍNEAS está, no «añade contexto»', |
| 38 | f: 'a.js', txt: 'function f() {\n return 1;\n}\nfunction g() {\n return 1;\n}\n', s: ' return 1;', r: ' return 9;', debeFallar: true, errorTrae: 'líneas 2, 5' }, |
| 39 | |
| 40 | { id: 'linea-extra-dentro', desc: 'el fichero tiene un comentario que el modelo no vio', |
| 41 | f: 'a.js', txt: 'function f() {\n // añadido luego\n return 1;\n}\n', s: 'function f() {\n return 1;\n}', r: 'function f() {\n return 5;\n}', esperado: 'return 5;', conserva: 'añadido luego' }, |
| 42 | |
| 43 | { id: 'duplicado', desc: 'el bloque aparece dos veces → debe NEGARSE', |
| 44 | f: 'a.js', txt: 'function f() {\n return 1;\n}\nfunction g() {\n return 1;\n}\n', s: ' return 1;', r: ' return 2;', debeFallar: true }, |
| 45 | |
| 46 | { id: 'crlf', desc: 'fichero con finales de línea de Windows', |
| 47 | f: 'a.js', txt: 'const a = 1;\r\nconst b = 2;\r\nconst c = 3;\r\n', s: 'const b = 2;', r: 'const b = 4;', esperado: 'const b = 4;', sinMezcla: true }, |
| 48 | |
| 49 | { id: 'sin-salto-final', desc: 'el bloque es la última línea y no hay salto final', |
| 50 | f: 'a.js', txt: 'const a = 1;\nconst b = 2;', s: 'const b = 2;', r: 'const b = 8;', esperado: 'const b = 8;' }, |
| 51 | |
| 52 | { id: 'borrado', desc: 'replace vacío = borrar el bloque', |
| 53 | f: 'a.js', txt: 'const a = 1;\nconst basura = 0;\nconst c = 3;\n', s: 'const basura = 0;\n', r: '', noContiene: 'basura' }, |
| 54 | |
| 55 | { id: 'acentos', desc: 'texto con acentos y eñes', |
| 56 | f: 'a.js', txt: 'const msg = "año de diseño";\n', s: 'const msg = "año de diseño";', r: 'const msg = "año nuevo";', esperado: 'año nuevo' }, |
| 57 | |
| 58 | { id: 'llave-sola', desc: 'search es «}» a secas: aparece mil veces → debe NEGARSE', |
| 59 | f: 'a.js', txt: 'function f() {\n return 1;\n}\nfunction g() {\n return 2;\n}\n', s: '}', r: '} // fin', debeFallar: true }, |
| 60 | |
| 61 | { id: 'elision', desc: 'el modelo elide el centro con «…»', |
| 62 | f: 'a.js', txt: 'function f() {\n const x = 1;\n const y = 2;\n return x + y;\n}\n', s: 'function f() {\n …\n return x + y;\n}', r: 'function f() {\n …\n return x * y;\n}', esperado: 'return x * y;', conserva: 'const x = 1;' }, |
| 63 | |
| 64 | { id: 'comillas-distintas', desc: 'cambia comillas al citar → NO debe adivinar (cambian el significado)', |
| 65 | f: 'a.js', txt: "const s = 'hola';\nconst t = 'adios';\n", s: 'const s = "hola";', r: 'const s = "HOLA";', debeFallar: true }, |
| 66 | |
| 67 | { id: 'sin-cambio', desc: 'search y replace idénticos → debe NEGARSE', |
| 68 | f: 'a.js', txt: 'const a = 1;\n', s: 'const a = 1;', r: 'const a = 1;', debeFallar: true }, |
| 69 | |
| 70 | { id: 'fichero-grande', desc: 'el bloque está en la línea 800 de un fichero largo', |
| 71 | f: 'a.js', txt: Array.from({length:1500},(_,i)=>`const v${i} = ${i};`).join('\n')+'\n', s: 'const v800 = 800;', r: 'const v800 = 999;', esperado: 'const v800 = 999;', intactas: 1500 }, |
| 72 | |
| 73 | // Caso REAL medido con Gemma E4B en la tarea max-empty: sustituyó la línea de |
| 74 | // la firma por una función entera CON su llave de cierre, dejando huérfano el |
| 75 | // cuerpo anterior. El fichero quedaba sin poder cargarse y el modelo remataba |
| 76 | // con «el cambio se ha aplicado correctamente». |
| 77 | { id: 'rompe-sintaxis', desc: 'la edición dejaría el fichero sin cargar → debe NEGARSE', |
| 78 | f: 'a.js', txt: 'export function max(arr) {\n return arr.reduce((a, b) => a > b ? a : b);\n}\n', |
| 79 | s: 'export function max(arr) {', r: 'export function max(arr) {\n if (!arr.length) return undefined;\n}', debeFallar: true }, |
| 80 | |
| 81 | { id: 'ya-estaba-roto', desc: 'si el fichero YA venía roto, la guarda no puede estorbar', |
| 82 | f: 'a.js', txt: 'export function f() {\n return 1;\n\n', s: 'return 1;', r: 'return 2;', esperado: 'return 2;' }, |
| 83 | |
| 84 | { id: 'markdown', desc: 'la guarda solo mira JS: un .md con llaves sueltas se edita igual', |
| 85 | f: 'a.md', txt: '# doc\nabre { sin cerrar\n', s: 'abre { sin cerrar', r: 'abre { otra vez sin cerrar', esperado: 'otra vez' }, |
| 86 | |
| 87 | { id: 'sintaxis-ok', desc: 'una edición correcta de varias líneas no se bloquea', |
| 88 | f: 'a.js', txt: 'export function max(arr) {\n return arr.reduce((a, b) => a > b ? a : b);\n}\n', |
| 89 | s: 'export function max(arr) {\n return arr.reduce((a, b) => a > b ? a : b);\n}', |
| 90 | r: 'export function max(arr) {\n if (!arr.length) return undefined;\n return arr.reduce((a, b) => a > b ? a : b);\n}', esperado: 'if (!arr.length)' }, |
| 91 | |
| 92 | // ── code.write, que es por donde se pierde código ─────────────────────────── |
| 93 | // Medido: tras dos rechazos de la guarda en edit, el modelo se escapó por |
| 94 | // write y reescribió el fichero entero. En uno de cuatro líneas da igual. |
| 95 | { id: 'write-trunca', op: 'write', desc: 'reescribir 300 líneas con 10 → debe NEGARSE', |
| 96 | f: 'a.js', txt: Array.from({length:300},(_,i)=>`export const v${i} = ${i};`).join('\n')+'\n', |
| 97 | contenido: 'export const v0 = 0;\n', debeFallar: true }, |
| 98 | |
| 99 | { id: 'write-rompe', op: 'write', desc: 'reescribir con JS roto un fichero sano → debe NEGARSE', |
| 100 | f: 'a.js', txt: Array.from({length:60},(_,i)=>`export const v${i} = ${i};`).join('\n')+'\n', |
| 101 | contenido: Array.from({length:60},(_,i)=>`export const v${i} = ${i};`).join('\n')+'\nfunction rota( {\n', debeFallar: true }, |
| 102 | |
| 103 | { id: 'write-nuevo', op: 'write', desc: 'crear un fichero nuevo no se toca', |
| 104 | f: 'nuevo.js', txt: null, contenido: 'export const x = 1;\n', esperado: 'export const x = 1;' }, |
| 105 | |
| 106 | { id: 'write-legitimo', op: 'write', desc: 'reescritura completa de tamaño parecido sí pasa', |
| 107 | f: 'a.js', txt: Array.from({length:60},(_,i)=>`export const v${i} = ${i};`).join('\n')+'\n', |
| 108 | contenido: Array.from({length:58},(_,i)=>`export const w${i} = ${i};`).join('\n')+'\n', esperado: 'export const w0 = 0;' }, |
| 109 | |
| 110 | { id: 'write-corto', op: 'write', desc: 'un fichero pequeño sí se puede reescribir corto', |
| 111 | f: 'a.js', txt: 'export const a = 1;\nexport const b = 2;\n', contenido: 'export const a = 1;\n', esperado: 'export const a = 1;' }, |
| 112 | ]; |
| 113 | |
| 114 | const b = await chromium.launch({ channel: 'chrome', headless: true }); |
| 115 | // Modo Básico: esta prueba pone su propio proveedor y no necesita modelo. Sin |
| 116 | // esto, al abrir la página main.js se pone a cargar el modelo local por defecto |
| 117 | // (con GPU, Gemma; sin ella, el ONNX ligero) mientras la prueba corre. |
| 118 | const ctxPrueba = await b.newContext(); |
| 119 | await ctxPrueba.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} }); |
| 120 | const p = await ctxPrueba.newPage(); |
| 121 | // Por defecto contra producción, como siempre; BASE=… la corre contra otro |
| 122 | // servidor (un árbol local), que es lo que hace falta antes de desplegar. |
| 123 | await p.goto((process.env.BASE || 'https://code.elffuss.com') + '/', { waitUntil: 'domcontentloaded' }); |
| 124 | await p.waitForTimeout(1200); |
| 125 | |
| 126 | const res = await p.evaluate(async (CASOS) => { |
| 127 | const code = await import('/js/tools/code.js?v=' + Date.now()); |
| 128 | const raiz = await navigator.storage.getDirectory(); |
| 129 | await code.openProject(raiz); |
| 130 | code.resetEditStats(); |
| 131 | const out = []; |
| 132 | for (const c of CASOS) { |
| 133 | for await (const [n] of raiz.entries()) await raiz.removeEntry(n, { recursive: true }).catch(() => {}); |
| 134 | if (c.txt != null) { |
| 135 | const fh = await raiz.getFileHandle(c.f, { create: true }); |
| 136 | const w = await fh.createWritable(); await w.write(c.txt); await w.close(); |
| 137 | } |
| 138 | code.invalidateFileList(); |
| 139 | let error = null, despues = c.txt ?? ''; |
| 140 | const antes = { ...code.editStats }; |
| 141 | try { |
| 142 | if (c.op === 'write') await code.write({ path: c.f, content: c.contenido }); |
| 143 | else await code.edit({ path: c.f, search: c.s, replace: c.r }); |
| 144 | } |
| 145 | catch (e) { error = e.message; } |
| 146 | try { despues = await (await (await raiz.getFileHandle(c.f)).getFile()).text(); } catch {} |
| 147 | const via = ['exacta','bloque','nucleo','difusa','ambigua','noEncontrado','sinCambio','noExiste','rompeSintaxis','yaAplicado','truncaria'] |
| 148 | .find(k => code.editStats[k] > (antes[k] || 0)) || '—'; |
| 149 | out.push({ id: c.id, error, via, cambio: despues !== c.txt, |
| 150 | texto: despues, lineas: despues.split('\n').length, |
| 151 | mezclaEOL: /\r\n/.test(despues) && /[^\r]\n/.test(despues) }); |
| 152 | } |
| 153 | return out; |
| 154 | }, CASOS); |
| 155 | |
| 156 | console.log('BATERÍA DE EDICIÓN — formas reales de citar mal un bloque\n'); |
| 157 | let ok = 0; |
| 158 | for (const c of CASOS) { |
| 159 | const r = res.find(x => x.id === c.id); |
| 160 | let bien, nota = ''; |
| 161 | if (c.debeFallar) { |
| 162 | bien = !!r.error && !r.cambio; nota = bien ? 'se negó, como debe' : '⚠ EDITÓ CUANDO NO DEBÍA'; |
| 163 | if (bien && c.errorTrae && !r.error.includes(c.errorTrae)) { bien = false; nota = `el error no trae «${c.errorTrae}»: ${r.error.replace(/\s+/g,' ').slice(0,110)}`; } |
| 164 | } |
| 165 | else if (c.sinError) { bien = !r.error && !r.cambio; nota = bien ? 'lo dio por hecho' : (r.error ? 'dio error: ' + r.error.slice(0,70) : 'editó cuando no debía'); } |
| 166 | else { |
| 167 | bien = !r.error && r.texto.includes(c.esperado ?? ''); |
| 168 | if (bien && c.conserva && !r.texto.includes(c.conserva)) { bien = false; nota = `se comió «${c.conserva}»`; } |
| 169 | if (bien && c.noContiene && r.texto.includes(c.noContiene)) { bien = false; nota = 'no borró'; } |
| 170 | if (bien && c.sinMezcla && r.mezclaEOL) { bien = false; nota = 'mezcló CRLF y LF'; } |
| 171 | if (bien && c.intactas && r.lineas !== c.intactas + 1) { bien = false; nota = `el fichero pasó de ${c.intactas} a ${r.lineas-1} líneas`; } |
| 172 | if (!bien && !nota) nota = (r.error || 'no aplicó el cambio').replace(/\s+/g,' ').slice(0,110); |
| 173 | } |
| 174 | if (bien) ok++; |
| 175 | console.log(` ${bien ? '✓' : '✗'} ${c.id.padEnd(19)} ${String(r.via).padEnd(13)} ${c.desc}`); |
| 176 | if (!bien) console.log(` └─ ${nota}`); |
| 177 | } |
| 178 | console.log(`\n ${ok}/${CASOS.length} casos correctos`); |
| 179 | if (process.argv[2]) { const r = res.find(x => x.id === process.argv[2]); console.log('\n--- resultado de ' + process.argv[2] + ' ---\n' + JSON.stringify(r.texto)); } |
| 180 | process.exit(ok === CASOS.length ? 0 : 1); |
| 181 | await b.close(); |